@oseo/compiler 0.1.0-canary.0 → 0.1.0-canary.370
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -165
- package/dist/agent-programs.d.ts.map +1 -1
- package/dist/agent-programs.js.map +1 -1
- package/dist/agent-templates.d.ts.map +1 -1
- package/dist/agent-templates.js.map +1 -1
- package/dist/compile.d.ts.map +1 -1
- package/dist/compile.js.map +1 -1
- package/dist/fragments.d.ts.map +1 -1
- package/dist/fragments.js.map +1 -1
- package/dist/hir-build.d.ts.map +1 -1
- package/dist/hir-build.js.map +1 -1
- package/dist/hir-print.d.ts.map +1 -1
- package/dist/hir-print.js.map +1 -1
- package/dist/hir.d.ts.map +1 -1
- package/dist/hir.js.map +1 -1
- package/dist/host-scripts.d.ts.map +1 -1
- package/dist/host-scripts.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/mir-build.d.ts.map +1 -1
- package/dist/mir-build.js.map +1 -1
- package/dist/mir-print.d.ts.map +1 -1
- package/dist/mir-print.js.map +1 -1
- package/dist/mir-specialize.d.ts.map +1 -1
- package/dist/mir-specialize.js.map +1 -1
- package/dist/mir.d.ts.map +1 -1
- package/dist/module-builtin.d.ts.map +1 -1
- package/dist/module-builtin.js.map +1 -1
- package/dist/module-compile.d.ts.map +1 -1
- package/dist/module-compile.js.map +1 -1
- package/dist/module-json.d.ts.map +1 -1
- package/dist/module-json.js.map +1 -1
- package/dist/modules.d.ts.map +1 -1
- package/dist/modules.js.map +1 -1
- package/dist/native-fragments.d.ts.map +1 -1
- package/dist/native-fragments.js.map +1 -1
- package/dist/native.d.ts.map +1 -1
- package/dist/native.js.map +1 -1
- package/dist/regexp-execute.d.ts.map +1 -1
- package/dist/regexp-execute.js.map +1 -1
- package/dist/regexp-matcher.d.ts.map +1 -1
- package/dist/regexp-matcher.js.map +1 -1
- package/dist/regexp-parse.d.ts.map +1 -1
- package/dist/regexp-parse.js.map +1 -1
- package/dist/regexp-print.d.ts.map +1 -1
- package/dist/regexp-print.js.map +1 -1
- package/dist/regexp.d.ts.map +1 -1
- package/dist/regexp.js.map +1 -1
- package/dist/source.d.ts.map +1 -1
- package/dist/source.js.map +1 -1
- package/dist/syntax.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,173 +1,60 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
`@oseo/compiler`
|
|
2
|
+
================
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
targets, and lexical resolution validates that context independently of binding
|
|
11
|
-
write mode. Binding-identifier leaves retain their own hint metadata so a
|
|
12
|
-
frontend can attach name-based parameter hints without annotating an aggregate
|
|
13
|
-
ABI parameter. The Babel frontend also maps primitive members from inline
|
|
14
|
-
object, tuple, and array TypeScript annotations to those leaves without making
|
|
15
|
-
compiler core depend on TypeScript syntax or type resolution.
|
|
4
|
+
`@oseo/compiler` is the host-independent core of Oseo, an ahead-of-time
|
|
5
|
+
compiler for JavaScript and TypeScript. It resolves bindings and module
|
|
6
|
+
graphs, lowers programs to Oseo's intermediate representations, and applies
|
|
7
|
+
guarded optimizations. It defines the interfaces for frontends, backends,
|
|
8
|
+
runtimes, and toolchains but does not ship those adapters. To compile and run
|
|
9
|
+
a file from the shell, use the [Oseo CLI].
|
|
16
10
|
|
|
17
|
-
|
|
18
|
-
define frontend-neutral inputs. *modules.ts* owns graph construction and
|
|
19
|
-
linking. The _hir-\*.ts_ and _mir-\*.ts_ families separate representations,
|
|
20
|
-
construction, printing, and guarded specialization. *module-compile.ts* owns
|
|
21
|
-
whole-graph asynchronous compilation, while *compile.ts* composes source
|
|
22
|
-
compilation. *native.ts* contains replaceable backend, runtime, toolchain,
|
|
23
|
-
process, target, and host contracts. *index.ts* is the unchanged public export
|
|
24
|
-
and composition surface. Package-private modules are not package export paths.
|
|
11
|
+
[Oseo CLI]: https://github.com/dahlia/oseo/blob/main/docs/using/cli.md
|
|
25
12
|
|
|
26
|
-
Native target descriptions contain immutable artifact facts, including the
|
|
27
|
-
architecture, operating system, ABI, executable format, C standard,
|
|
28
|
-
sanitizer policy, and the processor hint that `Atomics.pause` executes. Stable
|
|
29
|
-
Oseo target IDs use operating-system, architecture, and optional ABI order.
|
|
30
|
-
Concrete toolchain spellings do not enter the compiler core. Execution-host
|
|
31
|
-
descriptions are separate capabilities. `targetForExecutionHost` selects the
|
|
32
|
-
one supported target for a normalized host, while `canExecuteTarget` rejects
|
|
33
|
-
mismatched pairs before process execution.
|
|
34
13
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
blocks, and terminators do not retain HIR nodes. M3 bindings use shared mutable
|
|
38
|
-
cells in traced environments, so escaped closures retain binding identity. MIR
|
|
39
|
-
also owns dynamic calls, receiver and constructor operations, ordinary
|
|
40
|
-
properties, arrays, and explicit completion state for `catch` and `finally`.
|
|
41
|
-
Binding reads retain runtime temporal-dead-zone checks, and every collecting
|
|
42
|
-
operation has an explicit safepoint.
|
|
43
|
-
Synchronous `for-of` adds backend-neutral iterator get, next, and close
|
|
44
|
-
operations with separately rooted results. Cleanup-depth targets distinguish
|
|
45
|
-
same-loop continuation from transfers that must close the iterator.
|
|
46
|
-
Array literal spread reuses iterator get and next while accumulating values and
|
|
47
|
-
holes through dedicated MIR operations. Iterator acquisition and stepping
|
|
48
|
-
failures return directly without `IteratorClose`, matching array accumulation
|
|
49
|
-
semantics. Arrays without spread retain their fixed-length lowering.
|
|
50
|
-
Call and constructor argument spread accumulate ordinary and iterated values in
|
|
51
|
-
a rooted private argument list after evaluating the target. Abrupt iterator
|
|
52
|
-
work returns without `IteratorClose`; invocations without spread retain fixed
|
|
53
|
-
positional lowering. Construction allocates its receiver after accumulation. A
|
|
54
|
-
spread before a later top-level await point keeps the list in the module
|
|
55
|
-
evaluator's traced asynchronous frame.
|
|
56
|
-
A `const` or `let` declaration list arrives as one owned `declaration-list`
|
|
57
|
-
statement, and HIR construction expands its declarators into the statement
|
|
58
|
-
list that contains the declaration. ECMAScript gives those declarators the
|
|
59
|
-
scope that contains them, so the existing per-scope predeclaration pass gives
|
|
60
|
-
the whole list one temporal dead zone, one duplicate-name check, and one set
|
|
61
|
-
of cells. A block would instead declare a scope the source does not have and
|
|
62
|
-
reset the same cells a second time. A declaration list that reaches a
|
|
63
|
-
single-statement position is a source-located diagnostic, because the grammar
|
|
64
|
-
admits a lexical declaration only where a StatementList is admitted.
|
|
65
|
-
Standalone array binding declarations use compiler-owned recursive
|
|
66
|
-
patterns rather than frontend AST nodes. MIR gives each pattern an explicit
|
|
67
|
-
iterator done state and steps elisions and elements in order. It drains rest
|
|
68
|
-
into a rooted array and enters conditional close blocks for abrupt or early
|
|
69
|
-
normal completion. Nested patterns compose those cleanup regions from the
|
|
70
|
-
inside out. Lexical leaves initialize predeclared cells, while hoisted `var`
|
|
71
|
-
leaves use checked writes to existing function-scope cells.
|
|
72
|
-
Object binding declarations share those recursive leaves. MIR checks
|
|
73
|
-
`RequireObjectCoercible` before evaluating a computed property name and
|
|
74
|
-
converts each key through `ToPropertyKey`. It reads properties from left to
|
|
75
|
-
right and applies defaults only to `undefined`. It enters nested array or
|
|
76
|
-
object patterns without recovering frontend syntax.
|
|
77
|
-
Catch parameters reuse those patterns after capturing the pending thrown value.
|
|
78
|
-
MIR resets every catch cell before initialization, retains conditional iterator
|
|
79
|
-
cleanup, and sends a pattern failure through the enclosing `finally` or abrupt
|
|
80
|
-
target without entering the catch body. A handler without a parameter still
|
|
81
|
-
consumes the pending completion to clear the error context, then discards the
|
|
82
|
-
thrown value and binds nothing.
|
|
83
|
-
Synchronous `for-of` declaration heads reuse the same patterns. MIR resets all
|
|
84
|
-
lexical leaves before iterator acquisition and before each iteration, while
|
|
85
|
-
`var` leaves write hoisted cells. Nested pattern cleanup resumes through the
|
|
86
|
-
outer iterator close block after a pattern failure.
|
|
87
|
-
Classic `for` declaration heads also reuse the recursive patterns. Every
|
|
88
|
-
lexical leaf enters its temporal dead zone before its initializer, and each
|
|
89
|
-
mutable `let` leaf moves into a fresh per-iteration cell before the loop update.
|
|
90
|
-
`const` leaves retain their single environment, while `var` leaves write the
|
|
91
|
-
existing hoisted cells.
|
|
92
|
-
Assignment-pattern heads reuse the existing-target path without creating
|
|
93
|
-
cells. Their identifier and member leaves run after each outer iterator step,
|
|
94
|
-
and a failure resumes through nested pattern cleanup before that outer close.
|
|
95
|
-
Destructuring assignment evaluates its right operand once, then sends the same
|
|
96
|
-
recursive patterns through checked writes to existing identifier cells or
|
|
97
|
-
owned member references. Member object and key expressions lower before the
|
|
98
|
-
corresponding iterator step, source read, or default; key conversion and
|
|
99
|
-
storage lower after value selection. A nullish member base fails before key
|
|
100
|
-
conversion and resumes through active nested and outer iterator cleanup. The
|
|
101
|
-
expression retains the original right-hand value, nested array cleanup stays
|
|
102
|
-
inside out, and imported and immutable leaves keep their ordinary errors.
|
|
103
|
-
Inside an ordinary asynchronous or asynchronous generator body, a member
|
|
104
|
-
object, a computed property name, and a default may each suspend at `await`,
|
|
105
|
-
because the pattern lowers into the body's traced frame and every value it has
|
|
106
|
-
already prepared lives in that frame's root slots. A module evaluator with
|
|
107
|
-
top-level await is such an asynchronous body, so module top level accepts the
|
|
108
|
-
same positions.
|
|
109
|
-
Compound assignment retains one identifier read or one member object,
|
|
110
|
-
property-key expression, converted key, and property read before evaluating its
|
|
111
|
-
right operand. The retained raw key value is converted again on the write path
|
|
112
|
-
after the right operand. Binary forms reuse the corresponding MIR operator
|
|
113
|
-
before a checked write. Logical forms lower through explicit branches, so the
|
|
114
|
-
skipped path performs no right evaluation, second key conversion, or write.
|
|
115
|
-
Inside an asynchronous body, including a module evaluator, an `await` in the
|
|
116
|
-
right operand suspends with the retained current value in the traced frame.
|
|
117
|
-
Update expressions retain a binding reference or one member object and raw key
|
|
118
|
-
value. They apply numeric coercion and arithmetic by one before a checked
|
|
119
|
-
write. Member steps convert the raw key independently for the read and write.
|
|
120
|
-
Prefix forms return the assigned value, while postfix forms keep the coerced
|
|
121
|
-
previous value rooted across the write. A nullish base fails before either key
|
|
122
|
-
conversion. The path reuses existing MIR operations. The module continuation
|
|
123
|
-
extractor can rebuild a member step around an admitted await in its object or
|
|
124
|
-
key expression.
|
|
125
|
-
Non-strict duplicate parameters share one binding while retaining every
|
|
126
|
-
argument position. Repeated declarations resolve to one function binding whose
|
|
127
|
-
body comes from the last declaration. Named function expressions retain a
|
|
128
|
-
private self binding.
|
|
14
|
+
Compile a script to MIR
|
|
15
|
+
-----------------------
|
|
129
16
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
exported names share one traced cell identity, and namespace creation retains
|
|
133
|
-
sorted live-cell mappings. MIR call targets also name promise operations,
|
|
134
|
-
timers, and the `module-evaluate` driver entry without importing a concrete
|
|
135
|
-
runtime or event loop into compiler core. A module graph's script instantiates
|
|
136
|
-
every environment, then passes the module table to `module-evaluate`: the
|
|
137
|
-
entry index, the module count, and per module its evaluator, a top-level await
|
|
138
|
-
flag, its namespace or `undefined`, and its requested module indices in source
|
|
139
|
-
order. The runtime driver owns every evaluation state field, so the build no
|
|
140
|
-
longer fixes evaluation order.
|
|
141
|
-
Function creation retains ordinary, arrow, asynchronous, and asynchronous-arrow
|
|
142
|
-
identity through HIR and MIR.
|
|
17
|
+
With Node.js 24 or later, add the compiler and the Babel frontend to your
|
|
18
|
+
project:
|
|
143
19
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
covers it while the startup evaluation order does not. `buildModuleGraph` and
|
|
148
|
-
`buildScriptRequests` retain one `ModuleRequestRecord` per resolved request,
|
|
149
|
-
with its referrer, location, decoded literal, canonical target, and
|
|
150
|
-
`evaluation` or `discovery` edge kind, in a deterministic order. A Script
|
|
151
|
-
referrer resolves against an explicit canonical identity and is never a module
|
|
152
|
-
record. A failure reached through an `import()` edge carries its importer
|
|
153
|
-
chain in the diagnostic notes.
|
|
20
|
+
~~~~ sh
|
|
21
|
+
npm install @oseo/compiler @oseo/parser-babel
|
|
22
|
+
~~~~
|
|
154
23
|
|
|
155
|
-
|
|
156
|
-
static closure in startup order, then the modules only `import()` reaches,
|
|
157
|
-
which are linked and instantiated at startup but evaluate only on request.
|
|
158
|
-
Each `import()` target has a namespace cell. HIR construction lowers a site to
|
|
159
|
-
the `module-import` call target with the target's constant table index as its
|
|
160
|
-
only argument, so no specifier is looked up at run time; a site whose target
|
|
161
|
-
the build did not record keeps the profile diagnostic. A Script referrer
|
|
162
|
-
compiles through `compileSource` with a fourth argument naming its canonical
|
|
163
|
-
identity and the closure `buildScriptRequests` found. Its program instantiates
|
|
164
|
-
the modules, installs the table without evaluating any of them, and then runs
|
|
165
|
-
the Script; the modules read the Script's global declarations as their outer
|
|
166
|
-
scope. The default frontends still leave `staticSpecifierImports` off, so
|
|
167
|
-
ordinary compilation reports every `import()` at parse time.
|
|
24
|
+
Or, with Deno 2.9 or later:
|
|
168
25
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
26
|
+
~~~~ sh
|
|
27
|
+
deno add jsr:@oseo/compiler jsr:@oseo/parser-babel
|
|
28
|
+
~~~~
|
|
29
|
+
|
|
30
|
+
Save this example as *compile.mjs*:
|
|
31
|
+
|
|
32
|
+
~~~~ js
|
|
33
|
+
import { compileSource, printMir, renderDiagnostic } from "@oseo/compiler";
|
|
34
|
+
import { createBabelFrontend } from "@oseo/parser-babel";
|
|
35
|
+
|
|
36
|
+
const result = compileSource(createBabelFrontend(), {
|
|
37
|
+
sourceId: "answer.js",
|
|
38
|
+
source: "console.log(6 * 7);",
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
if (result.mir == null) {
|
|
42
|
+
throw new Error(result.diagnostics.map(renderDiagnostic).join("\n"));
|
|
43
|
+
}
|
|
44
|
+
console.log(printMir(result.mir));
|
|
45
|
+
~~~~
|
|
46
|
+
|
|
47
|
+
Run `node compile.mjs` or `deno run compile.mjs`. This prints Oseo's mid-level
|
|
48
|
+
intermediate representation (MIR) without running the script or invoking a
|
|
49
|
+
native toolchain. For a module entry, use
|
|
50
|
+
`buildModuleGraph()` with a module frontend, loader, and resolver, then
|
|
51
|
+
`compileModuleGraph()` to lower the graph. Use [the C backend] to emit C11
|
|
52
|
+
from the resulting MIR.
|
|
53
|
+
|
|
54
|
+
Import from `@oseo/compiler` rather than from internal files. See the
|
|
55
|
+
[design document] for the compiler stages and the
|
|
56
|
+
[compiler implementation notes] for binding and module discovery details.
|
|
57
|
+
|
|
58
|
+
[the C backend]: https://github.com/dahlia/oseo/tree/main/packages/backend-c
|
|
59
|
+
[design document]: https://github.com/dahlia/oseo/blob/main/DESIGN.md
|
|
60
|
+
[compiler implementation notes]: https://github.com/dahlia/oseo/blob/main/docs/development/package-compiler.md
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-programs.d.ts","names":[],"sources":["../src/agent-programs.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"agent-programs.d.ts","names":[],"sources":["../src/agent-programs.ts"],"mappings":";;;;;;KA+BY;WACG,sBAAsB;;WACtB,KAAK;;;;;;;;;;;;;iBAwDJ,qBACd,UAAU,gBACV,UAAU,qBACV,eACA,sBACA,SAAS,kBACR;;iBAgHa,cAAc,sBAAsB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-programs.js","names":[],"sources":["../src/agent-programs.ts"],"sourcesContent":["import type { AgentSourceTemplate } from \"./agent-templates.ts\";\nimport { type AgentHolePlaceholder, buildHir } from \"./hir-build.ts\";\nimport type {\n CompilerOptions,\n MirFunction,\n MirOperation,\n MirProgram,\n} from \"./mir.ts\";\nimport { buildMir } from \"./mir-build.ts\";\nimport type { Diagnostic } from \"./source.ts\";\nimport type { SourceFrontend } from \"./syntax.ts\";\n\n/** An agent program compiled from one template, or why it was not. */\nexport type AgentProgramResult =\n | { readonly diagnostics: readonly Diagnostic[] }\n | { readonly mir: MirProgram };\n\n/*\n * The text with every `\\uXXXX` and `\\u{X...}` escape replaced by the code\n * point it spells. It over-approximates the identifiers an escape can\n * name, because it also decodes escapes inside strings and comments,\n * which only makes a placeholder name more conservative.\n */\nfunction decodeUnicodeEscapes(text: string): string {\n return text.replaceAll(\n /\\\\u(?:\\{([0-9A-Fa-f]+)\\}|([0-9A-Fa-f]{4}))/gu,\n (escape, braced: string | undefined, fixed: string | undefined) => {\n const codePoint = Number.parseInt(braced ?? fixed ?? \"\", 16);\n return codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : escape;\n },\n );\n}\n\n/*\n * Whether the character beside a hole ends every token there. A decimal\n * literal cannot touch an identifier character, a digit, or a dot without\n * forming a different token, and a non-ASCII neighbor may be an\n * identifier character, so each of those rejects the template.\n */\nfunction separatesHole(character: string | undefined): boolean {\n if (character == null) return true;\n const code = character.charCodeAt(0);\n if (code >= 0x80) return false;\n return !/[A-Za-z0-9$_.\\\\]/u.test(character);\n}\n\nfunction templateDiagnostic(\n template: AgentSourceTemplate,\n sourceId: string,\n message: string,\n): Diagnostic {\n return {\n byteRange: { end: 0, start: 0 },\n code: \"OSEO1001\",\n message,\n range: template.range,\n sourceId,\n };\n}\n\n/**\n * Compiles one agent program from its template (ADR 0026). The program\n * is the template text with each hole replaced by a fresh identifier that\n * resolves to the hole's Number, so it evaluates exactly what a start\n * source reads when each hole holds a decimal integer literal, which is\n * all the runtime lets a hole match: both replacements are one\n * PrimaryExpression token in the same position. The template is rejected\n * unless every hole is delimited as one token, the text with `0` in each\n * hole parses, and each placeholder is resolved as exactly one identifier\n * read and nothing else.\n */\nexport function compileAgentTemplate(\n frontend: SourceFrontend,\n template: AgentSourceTemplate,\n index: number,\n mainSourceId: string,\n options: CompilerOptions,\n): AgentProgramResult {\n const sourceId = agentSourceId(mainSourceId, index);\n const { segments } = template;\n // A placeholder must be fresh against every identifier the template can\n // spell, including one written with Unicode escapes, so the check runs\n // over the raw text and over the text with every escape decoded.\n const text = segments.join(\"\");\n const decoded = decodeUnicodeEscapes(text);\n const names = segments.slice(1).map((_, hole) => {\n let name = `$262AgentHole${hole}`;\n while (text.includes(name) || decoded.includes(name)) name = `_${name}`;\n return name;\n });\n for (let hole = 0; hole < names.length; hole += 1) {\n if (\n !separatesHole(segments[hole]?.at(-1)) ||\n !separatesHole(segments[hole + 1]?.at(0))\n ) {\n return {\n diagnostics: [\n templateDiagnostic(\n template,\n mainSourceId,\n `Agent source template hole ${hole} is not delimited as one ` +\n \"numeric literal token.\",\n ),\n ],\n };\n }\n }\n const literal = frontend.parse({ source: segments.join(\"0\"), sourceId });\n if (literal.program == null) return { diagnostics: literal.diagnostics };\n // Each placeholder's UTF-8 byte span, which the one read that may\n // resolve to the hole must occupy exactly.\n const encoder = new TextEncoder();\n const holes: AgentHolePlaceholder[] = [];\n let source = segments[0] ?? \"\";\n for (const [position, name] of names.entries()) {\n const start = encoder.encode(source).length;\n holes.push({ name, span: { end: start + name.length, start } });\n source += name + (segments[position + 1] ?? \"\");\n }\n const parsed = frontend.parse({ source, sourceId });\n if (parsed.program == null) return { diagnostics: parsed.diagnostics };\n const hir = buildHir(parsed.program, { agentHoles: holes });\n if (hir.program == null) return { diagnostics: hir.diagnostics };\n const mir = buildMir(hir.program, { ...options, test262Host: false });\n const split = (operation: MirOperation): MirOperation => {\n const functionSource = operation.functionSource;\n if (functionSource == null) return operation;\n const functionSourceHoles = splitAtPlaceholders(functionSource, names);\n return functionSourceHoles == null\n ? operation\n : { ...operation, functionSourceHoles };\n };\n const splitFunction = (functionValue: MirFunction): MirFunction => ({\n ...functionValue,\n blocks: functionValue.blocks.map((block) => ({\n ...block,\n operations: block.operations.map(split),\n })),\n });\n return {\n mir: {\n ...mir,\n agentProgram: index,\n functions: mir.functions.map(splitFunction),\n script: splitFunction(mir.script),\n },\n };\n}\n\n/*\n * A function's source text split at every placeholder it contains, or\n * undefined when it contains none. Each placeholder is absent from the\n * template's own text, and a hole never touches an identifier character,\n * so every occurrence is the hole it names.\n */\nfunction splitAtPlaceholders(\n text: string,\n names: readonly string[],\n): { readonly holes: readonly number[]; readonly runs: string[] } | undefined {\n const holeIndexes: number[] = [];\n const runs: string[] = [];\n let position = 0;\n let run = \"\";\n while (position < text.length) {\n // The longest placeholder wins, so hole 1 never claims hole 10.\n let hole = -1;\n for (const [index, name] of names.entries()) {\n if (\n text.startsWith(name, position) &&\n (hole < 0 || name.length > names[hole]!.length)\n ) {\n hole = index;\n }\n }\n if (hole < 0) {\n run += text[position];\n position += 1;\n continue;\n }\n runs.push(run);\n run = \"\";\n holeIndexes.push(hole);\n position += names[hole]!.length;\n }\n runs.push(run);\n return holeIndexes.length === 0 ? undefined : { holes: holeIndexes, runs };\n}\n\n/** The source identity an agent program's diagnostics report. */\nexport function agentSourceId(mainSourceId: string, index: number): string {\n return `${mainSourceId}#agent-${index}`;\n}\n"],"mappings":";;;;AAuBA,SAAS,qBAAqB,MAAsB;CAClD,OAAO,KAAK,WACV,iDACC,QAAQ,QAA4B,UAA8B;EACjE,MAAM,YAAY,OAAO,SAAS,UAAU,SAAS,IAAI,EAAE;EAC3D,OAAO,aAAa,UAAW,OAAO,cAAc,SAAS,IAAI;CACnE,CACF;AACF;AAQA,SAAS,cAAc,WAAwC;CAC7D,IAAI,aAAa,MAAM,OAAO;CAE9B,IADa,UAAU,WAAW,CAC3B,KAAK,KAAM,OAAO;CACzB,OAAO,CAAC,oBAAoB,KAAK,SAAS;AAC5C;AAEA,SAAS,mBACP,UACA,UACA,SACY;CACZ,OAAO;EACL,WAAW;GAAE,KAAK;GAAG,OAAO;EAAE;EAC9B,MAAM;EACN;EACA,OAAO,SAAS;EAChB;CACF;AACF;;;;;;;;;;;;AAaA,SAAgB,qBACd,UACA,UACA,OACA,cACA,SACoB;CACpB,MAAM,WAAW,cAAc,cAAc,KAAK;CAClD,MAAM,EAAE,aAAa;CAIrB,MAAM,OAAO,SAAS,KAAK,EAAE;CAC7B,MAAM,UAAU,qBAAqB,IAAI;CACzC,MAAM,Q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C;EACvD,MAAM,iBAAiB,UAAU;EACjC,IAAI,kBAAkB,MAAM,OAAO;EACnC,MAAM,sBAAsB,oBAAoB,gBAAgB,KAAK;EACrE,OAAO,uBAAuB,OAC1B,YACA;GAAE,GAAG;GAAW;EAAoB;CAC1C;CACA,MAAM,iBAAiB,mBAA6C;EAClE,GAAG;EACH,QAAQ,cAAc,OAAO,KAAK,WAAW;GAC3C,GAAG;GACH,YAAY,MAAM,WAAW,IAAI,KAAK;EACxC,EAAE;CACJ;CACA,OAAO,EACL,KAAK;EACH,GAAG;EACH,cAAc;EACd,WAAW,IAAI,UAAU,IAAI,aAAa;EAC1C,QAAQ,cAAc,IAAI,MAAM;CAClC,EACF;AACF;AAQA,SAAS,oBACP,MACA,OAC4E;CAC5E,MAAM,cAAwB,CAAC;CAC/B,MAAM,OAAiB,CAAC;CACxB,IAAI,WAAW;CACf,IAAI,MAAM;CACV,OAAO,WAAW,KAAK,QAAQ;EAE7B,IAAI,OAAO;EACX,KAAK,MAAM,CAAC,OAAO,SAAS,MAAM,QAAQ,GACxC,IACE,KAAK,WAAW,MAAM,QAAQ,MAC7B,OAAO,KAAK,KAAK,SAAS,MAAM,KAAK,CAAE,SAExC,OAAO;EAGX,IAAI,OAAO,GAAG;GACZ,OAAO,KAAK;GACZ,YAAY;GACZ;EACF;EACA,KAAK,KAAK,GAAG;EACb,MAAM;EACN,YAAY,KAAK,IAAI;EACrB,YAAY,MAAM,KAAK,CAAE;CAC3B;CACA,KAAK,KAAK,GAAG;CACb,OAAO,YAAY,WAAW,IAAI,SAAY;EAAE,OAAO;EAAa;CAAK;AAC3E;;AAGA,SAAgB,cAAc,cAAsB,OAAuB;CACzE,OAAO,GAAG,aAAa,SAAS;AAClC"}
|
|
1
|
+
{"version":3,"file":"agent-programs.js","names":[],"sources":["../src/agent-programs.ts"],"sourcesContent":["/*\n * Oseo, an ahead-of-time compiler for JavaScript and TypeScript.\n * Copyright (C) 2026 Hong Minhee <https://hongminhee.org/>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n */\n\nimport type { AgentSourceTemplate } from \"./agent-templates.ts\";\nimport { type AgentHolePlaceholder, buildHir } from \"./hir-build.ts\";\nimport type {\n CompilerOptions,\n MirFunction,\n MirOperation,\n MirProgram,\n} from \"./mir.ts\";\nimport { buildMir } from \"./mir-build.ts\";\nimport type { Diagnostic } from \"./source.ts\";\nimport type { SourceFrontend } from \"./syntax.ts\";\n\n/** An agent program compiled from one template, or why it was not. */\nexport type AgentProgramResult =\n | { readonly diagnostics: readonly Diagnostic[] }\n | { readonly mir: MirProgram };\n\n/*\n * The text with every `\\uXXXX` and `\\u{X...}` escape replaced by the code\n * point it spells. It over-approximates the identifiers an escape can\n * name, because it also decodes escapes inside strings and comments,\n * which only makes a placeholder name more conservative.\n */\nfunction decodeUnicodeEscapes(text: string): string {\n return text.replaceAll(\n /\\\\u(?:\\{([0-9A-Fa-f]+)\\}|([0-9A-Fa-f]{4}))/gu,\n (escape, braced: string | undefined, fixed: string | undefined) => {\n const codePoint = Number.parseInt(braced ?? fixed ?? \"\", 16);\n return codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : escape;\n },\n );\n}\n\n/*\n * Whether the character beside a hole ends every token there. A decimal\n * literal cannot touch an identifier character, a digit, or a dot without\n * forming a different token, and a non-ASCII neighbor may be an\n * identifier character, so each of those rejects the template.\n */\nfunction separatesHole(character: string | undefined): boolean {\n if (character == null) return true;\n const code = character.charCodeAt(0);\n if (code >= 0x80) return false;\n return !/[A-Za-z0-9$_.\\\\]/u.test(character);\n}\n\nfunction templateDiagnostic(\n template: AgentSourceTemplate,\n sourceId: string,\n message: string,\n): Diagnostic {\n return {\n byteRange: { end: 0, start: 0 },\n code: \"OSEO1001\",\n message,\n range: template.range,\n sourceId,\n };\n}\n\n/**\n * Compiles one agent program from its template (ADR 0026). The program\n * is the template text with each hole replaced by a fresh identifier that\n * resolves to the hole's Number, so it evaluates exactly what a start\n * source reads when each hole holds a decimal integer literal, which is\n * all the runtime lets a hole match: both replacements are one\n * PrimaryExpression token in the same position. The template is rejected\n * unless every hole is delimited as one token, the text with `0` in each\n * hole parses, and each placeholder is resolved as exactly one identifier\n * read and nothing else.\n */\nexport function compileAgentTemplate(\n frontend: SourceFrontend,\n template: AgentSourceTemplate,\n index: number,\n mainSourceId: string,\n options: CompilerOptions,\n): AgentProgramResult {\n const sourceId = agentSourceId(mainSourceId, index);\n const { segments } = template;\n // A placeholder must be fresh against every identifier the template can\n // spell, including one written with Unicode escapes, so the check runs\n // over the raw text and over the text with every escape decoded.\n const text = segments.join(\"\");\n const decoded = decodeUnicodeEscapes(text);\n const names = segments.slice(1).map((_, hole) => {\n let name = `$262AgentHole${hole}`;\n while (text.includes(name) || decoded.includes(name)) name = `_${name}`;\n return name;\n });\n for (let hole = 0; hole < names.length; hole += 1) {\n if (\n !separatesHole(segments[hole]?.at(-1)) ||\n !separatesHole(segments[hole + 1]?.at(0))\n ) {\n return {\n diagnostics: [\n templateDiagnostic(\n template,\n mainSourceId,\n `Agent source template hole ${hole} is not delimited as one ` +\n \"numeric literal token.\",\n ),\n ],\n };\n }\n }\n const literal = frontend.parse({ source: segments.join(\"0\"), sourceId });\n if (literal.program == null) return { diagnostics: literal.diagnostics };\n // Each placeholder's UTF-8 byte span, which the one read that may\n // resolve to the hole must occupy exactly.\n const encoder = new TextEncoder();\n const holes: AgentHolePlaceholder[] = [];\n let source = segments[0] ?? \"\";\n for (const [position, name] of names.entries()) {\n const start = encoder.encode(source).length;\n holes.push({ name, span: { end: start + name.length, start } });\n source += name + (segments[position + 1] ?? \"\");\n }\n const parsed = frontend.parse({ source, sourceId });\n if (parsed.program == null) return { diagnostics: parsed.diagnostics };\n const hir = buildHir(parsed.program, { agentHoles: holes });\n if (hir.program == null) return { diagnostics: hir.diagnostics };\n const mir = buildMir(hir.program, { ...options, test262Host: false });\n const split = (operation: MirOperation): MirOperation => {\n const functionSource = operation.functionSource;\n if (functionSource == null) return operation;\n const functionSourceHoles = splitAtPlaceholders(functionSource, names);\n return functionSourceHoles == null\n ? operation\n : { ...operation, functionSourceHoles };\n };\n const splitFunction = (functionValue: MirFunction): MirFunction => ({\n ...functionValue,\n blocks: functionValue.blocks.map((block) => ({\n ...block,\n operations: block.operations.map(split),\n })),\n });\n return {\n mir: {\n ...mir,\n agentProgram: index,\n functions: mir.functions.map(splitFunction),\n script: splitFunction(mir.script),\n },\n };\n}\n\n/*\n * A function's source text split at every placeholder it contains, or\n * undefined when it contains none. Each placeholder is absent from the\n * template's own text, and a hole never touches an identifier character,\n * so every occurrence is the hole it names.\n */\nfunction splitAtPlaceholders(\n text: string,\n names: readonly string[],\n): { readonly holes: readonly number[]; readonly runs: string[] } | undefined {\n const holeIndexes: number[] = [];\n const runs: string[] = [];\n let position = 0;\n let run = \"\";\n while (position < text.length) {\n // The longest placeholder wins, so hole 1 never claims hole 10.\n let hole = -1;\n for (const [index, name] of names.entries()) {\n if (\n text.startsWith(name, position) &&\n (hole < 0 || name.length > names[hole]!.length)\n ) {\n hole = index;\n }\n }\n if (hole < 0) {\n run += text[position];\n position += 1;\n continue;\n }\n runs.push(run);\n run = \"\";\n holeIndexes.push(hole);\n position += names[hole]!.length;\n }\n runs.push(run);\n return holeIndexes.length === 0 ? undefined : { holes: holeIndexes, runs };\n}\n\n/** The source identity an agent program's diagnostics report. */\nexport function agentSourceId(mainSourceId: string, index: number): string {\n return `${mainSourceId}#agent-${index}`;\n}\n"],"mappings":";;;;AAyCA,SAAS,qBAAqB,MAAsB;CAClD,OAAO,KAAK,WACV,iDACC,QAAQ,QAA4B,UAA8B;EACjE,MAAM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SAAS,MAAM,QAAQ,GACxC,IACE,KAAK,WAAW,MAAM,QAAQ,MAC7B,OAAO,KAAK,KAAK,SAAS,MAAM,KAAK,CAAE,SAExC,OAAO;EAGX,IAAI,OAAO,GAAG;GACZ,OAAO,KAAK;GACZ,YAAY;GACZ;EACF;EACA,KAAK,KAAK,GAAG;EACb,MAAM;EACN,YAAY,KAAK,IAAI;EACrB,YAAY,MAAM,KAAK,CAAE;CAC3B;CACA,KAAK,KAAK,GAAG;CACb,OAAO,YAAY,WAAW,IAAI,SAAY;EAAE,OAAO;EAAa;CAAK;AAC3E;;AAGA,SAAgB,cAAc,cAAsB,OAAuB;CACzE,OAAO,GAAG,aAAa,SAAS;AAClC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-templates.d.ts","names":[],"sources":["../src/agent-templates.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"agent-templates.d.ts","names":[],"sources":["../src/agent-templates.ts"],"mappings":";;;;;;;cA6Ba;;;;;;UAOI;WACN,OAAO;WACP;;;iBAQK,mBAAmB,QAAQ;;;;;;;;;;;iBAwB3B,sBACd,UAAU"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-templates.js","names":[],"sources":["../src/agent-templates.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"agent-templates.js","names":[],"sources":["../src/agent-templates.ts"],"sourcesContent":["/*\n * Oseo, an ahead-of-time compiler for JavaScript and TypeScript.\n * Copyright (C) 2026 Hong Minhee <https://hongminhee.org/>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n */\n\nimport type { SourceRange } from \"./source.ts\";\nimport type {\n SyntaxCallArgument,\n SyntaxCallTarget,\n SyntaxExpression,\n} from \"./syntax.ts\";\n\n/**\n * The global name of the test262 host object a Script compiled for the\n * test262 host reads.\n */\nexport const test262HostGlobalName = \"$262\";\n\n/**\n * One `$262.agent.start` source template found in a Script: the cooked\n * literal text around each substitution of a template literal, or the\n * whole text of a string literal, which has no substitution.\n */\nexport interface AgentSourceTemplate {\n readonly range: SourceRange;\n readonly segments: readonly string[];\n}\n\nfunction stringKey(expression: SyntaxExpression, name: string): boolean {\n return expression.kind === \"string\" && expression.value === name;\n}\n\n/** Whether a call target is exactly `$262.agent.start`. */\nexport function isAgentStartTarget(target: SyntaxCallTarget): boolean {\n if (target.kind !== \"property\" || !stringKey(target.key, \"start\")) {\n return false;\n }\n const agent = target.object;\n if (agent.kind !== \"property-get\" || !stringKey(agent.key, \"agent\")) {\n return false;\n }\n return (\n agent.object.kind === \"identifier\" &&\n agent.object.name === test262HostGlobalName\n );\n}\n\n/**\n * The literal runs of a start argument. The frontend lowers an untagged\n * template literal to a left-nested `+` chain that starts with its first\n * cooked string and continues with a `to-string` conversion for each\n * substitution and a string for each nonempty later run, so the chain is\n * read back into runs with one hole per conversion. A plain string literal\n * is one run, and a chain of string literals is their concatenation. Any\n * other argument has no template, and a start with it reaches the\n * runtime's owned boundary instead.\n */\nexport function agentTemplateSegments(\n argument: SyntaxCallArgument | undefined,\n): readonly string[] | undefined {\n if (argument == null || argument.kind === \"spread\") return undefined;\n const pieces: SyntaxExpression[] = [];\n let current: SyntaxExpression = argument;\n while (current.kind === \"binary\" && current.operator === \"+\") {\n pieces.push(current.right);\n current = current.left;\n }\n if (current.kind !== \"string\") return undefined;\n const segments = [current.value];\n for (const piece of pieces.toReversed()) {\n if (piece.kind === \"unary\" && piece.operator === \"to-string\") {\n segments.push(\"\");\n } else if (piece.kind === \"string\") {\n segments[segments.length - 1] += piece.value;\n } else {\n return undefined;\n }\n }\n return segments;\n}\n"],"mappings":";;;;;AA6BA,MAAa,wBAAwB;AAYrC,SAAS,UAAU,YAA8B,MAAuB;CACtE,OAAO,WAAW,SAAS,YAAY,WAAW,UAAU;AAC9D;;AAGA,SAAgB,mBAAmB,QAAmC;CACpE,IAAI,OAAO,SAAS,cAAc,CAAC,UAAU,OAAO,KAAK,OAAO,GAC9D,OAAO;CAET,MAAM,QAAQ,OAAO;CACrB,IAAI,MAAM,SAAS,kBAAkB,CAAC,UAAU,MAAM,KAAK,OAAO,GAChE,OAAO;CAET,OACE,MAAM,OAAO,SAAS,gBACtB,MAAM,OAAO;AAEjB;;;;;;;;;;;AAYA,SAAgB,sBACd,UAC+B;CAC/B,IAAI,YAAY,QAAQ,SAAS,SAAS,UAAU,OAAO;CAC3D,MAAM,SAA6B,CAAC;CACpC,IAAI,UAA4B;CAChC,OAAO,QAAQ,SAAS,YAAY,QAAQ,aAAa,KAAK;EAC5D,OAAO,KAAK,QAAQ,KAAK;EACzB,UAAU,QAAQ;CACpB;CACA,IAAI,QAAQ,SAAS,UAAU,OAAO;CACtC,MAAM,WAAW,CAAC,QAAQ,KAAK;CAC/B,KAAK,MAAM,SAAS,OAAO,WAAW,GACpC,IAAI,MAAM,SAAS,WAAW,MAAM,aAAa,aAC/C,SAAS,KAAK,EAAE;MACX,IAAI,MAAM,SAAS,UACxB,SAAS,SAAS,SAAS,MAAM,MAAM;MAEvC;CAGJ,OAAO;AACT"}
|
package/dist/compile.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compile.d.ts","names":[],"sources":["../src/compile.ts"],"mappings":";;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"compile.d.ts","names":[],"sources":["../src/compile.ts"],"mappings":";;;;;;;;;;;;;;;;iBAyCgB,cACd,UAAU,gBACV,OAAO,aACP,UAAS,iBACT,WAAW,uBACV"}
|
package/dist/compile.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compile.js","names":[],"sources":["../src/compile.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"compile.js","names":[],"sources":["../src/compile.ts"],"sourcesContent":["/*\n * Oseo, an ahead-of-time compiler for JavaScript and TypeScript.\n * Copyright (C) 2026 Hong Minhee <https://hongminhee.org/>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n */\n\nimport { agentSourceId, compileAgentTemplate } from \"./agent-programs.ts\";\nimport { compileHostScripts } from \"./host-scripts.ts\";\nimport { buildSeededHir } from \"./hir-build.ts\";\nimport type { CompilerOptions, MirAgentTemplate, MirProgram } from \"./mir.ts\";\nimport { buildMir } from \"./mir-build.ts\";\nimport {\n buildScriptGraphHir,\n type CompilationResult,\n type ScriptModuleRequests,\n} from \"./module-compile.ts\";\nimport type { SourceInput } from \"./source.ts\";\nimport type { SourceFrontend } from \"./syntax.ts\";\n/**\n * Compile source through owned syntax, HIR, and policy-selected MIR. With\n * the test262 host option, the result also carries one agent program for\n * each `$262.agent.start` template, and the main program's table names\n * them in the same order.\n *\n * `requests` names the modules a Script's `import()` calls reach, as\n * `buildScriptRequests` discovered them for the same Script under\n * its canonical identity. Without it, every `import()` keeps its profile\n * diagnostic.\n */\nexport function compileSource(\n frontend: SourceFrontend,\n input: SourceInput,\n options: CompilerOptions = {},\n requests?: ScriptModuleRequests,\n): CompilationResult {\n const frontendResult = frontend.parse(input);\n if (frontendResult.program == null) {\n return { diagnostics: frontendResult.diagnostics };\n }\n const host = options.test262Host === true;\n const seed = host\n ? { collectAgentTemplates: true, hostScriptBindings: true }\n : {};\n // A Script with `import()` calls carries the modules they reach.\n const hirResult =\n requests == null\n ? buildSeededHir(frontendResult.program, seed)\n : buildScriptGraphHir(frontendResult.program, requests, seed);\n if (hirResult.program == null) {\n return {\n diagnostics: hirResult.diagnostics,\n syntax: frontendResult.program,\n };\n }\n const mir = buildMir(hirResult.program, options);\n if (!host) {\n return {\n diagnostics: [],\n hir: hirResult.program,\n mir,\n syntax: frontendResult.program,\n };\n }\n const agents: MirProgram[] = [];\n const templates: MirAgentTemplate[] = [];\n for (const [index, template] of (\n hirResult.program.agentTemplates ?? []\n ).entries()) {\n const compiled = compileAgentTemplate(\n frontend,\n template,\n index,\n input.sourceId,\n options,\n );\n if (\"diagnostics\" in compiled) {\n return {\n diagnostics: compiled.diagnostics,\n syntax: frontendResult.program,\n };\n }\n agents.push(compiled.mir);\n templates.push({\n segments: template.segments,\n sourceId: agentSourceId(input.sourceId, index),\n });\n }\n const scripts = compileHostScripts(\n frontend,\n frontendResult.program,\n options,\n hirResult.nextBindingId,\n hirResult.nextFunctionId,\n hirResult.program.hostScriptSources ?? [],\n );\n return {\n agents,\n diagnostics: [],\n hir: hirResult.program,\n mir: {\n ...mir,\n functions: [...mir.functions, ...scripts.functions],\n globalBindings: [...mir.globalBindings, ...scripts.globals],\n hostObjectBindings: scripts.objects,\n test262Host: {\n agents: templates,\n mainAgentCanBlock: options.mainAgentCanBlock ?? true,\n scripts: scripts.scripts,\n },\n },\n syntax: frontendResult.program,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyCA,SAAgB,cACd,UACA,OACA,UAA2B,CAAC,GAC5B,UACmB;CACnB,MAAM,iBAAiB,SAAS,MAAM,KAAK;CAC3C,IAAI,eAAe,WAAW,MAC5B,OAAO,EAAE,aAAa,eAAe,YAAY;CAEnD,MAAM,OAAO,QAAQ,gBAAgB;CACrC,MAAM,OAAO,OACT;EAAE,uBAAuB;EAAM,oBAAoB;CAAK,IACxD,CAAC;CAEL,MAAM,YACJ,YAAY,OACR,eAAe,eAAe,SAAS,IAAI,IAC3C,oBAAoB,eAAe,SAAS,UAAU,IAAI;CAChE,IAAI,UAAU,WAAW,MACvB,OAAO;EACL,aAAa,UAAU;EACvB,QAAQ,eAAe;CACzB;CAEF,MAAM,MAAM,SAAS,UAAU,SAAS,OAAO;CAC/C,IAAI,CAAC,MACH,OAAO;EACL,aAAa,CAAC;EACd,KAAK,UAAU;EACf;EACA,QAAQ,eAAe;CACzB;CAEF,MAAM,SAAuB,CAAC;CAC9B,MAAM,YAAgC,CAAC;CACvC,KAAK,MAAM,CAAC,OAAO,cACjB,UAAU,QAAQ,kBAAkB,CAAC,EAAC,CACtC,QAAQ,GAAG;EACX,MAAM,WAAW,qBACf,UACA,UACA,OACA,MAAM,UACN,OACF;EACA,IAAI,iBAAiB,UACnB,OAAO;GACL,aAAa,SAAS;GACtB,QAAQ,eAAe;EACzB;EAEF,OAAO,KAAK,SAAS,GAAG;EACxB,UAAU,KAAK;GACb,UAAU,SAAS;GACnB,UAAU,cAAc,MAAM,UAAU,KAAK;EAC/C,CAAC;CACH;CACA,MAAM,UAAU,mBACd,UACA,eAAe,SACf,SACA,UAAU,eACV,UAAU,gBACV,UAAU,QAAQ,qBAAqB,CAAC,CAC1C;CACA,OAAO;EACL;EACA,aAAa,CAAC;EACd,KAAK,UAAU;EACf,KAAK;GACH,GAAG;GACH,WAAW,CAAC,GAAG,IAAI,WAAW,GAAG,QAAQ,SAAS;GAClD,gBAAgB,CAAC,GAAG,IAAI,gBAAgB,GAAG,QAAQ,OAAO;GAC1D,oBAAoB,QAAQ;GAC5B,aAAa;IACX,QAAQ;IACR,mBAAmB,QAAQ,qBAAqB;IAChD,SAAS,QAAQ;GACnB;EACF;EACA,QAAQ,eAAe;CACzB;AACF"}
|
package/dist/fragments.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fragments.d.ts","names":[],"sources":["../src/fragments.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"fragments.d.ts","names":[],"sources":["../src/fragments.ts"],"mappings":";;;;;;cA0Ba;;UAGI;WACN;WACA;WACA;WACA;;;;;;UAOM;WACN,KAAK;WACL,KAAK;;WAEL;WACA;;WAEA;;;UAIM,wBAAwB;WAC9B,YAAY;WACZ,kBAAkB;WAClB,mBAAmB;WACnB;WACA;WACA,SAAS;;;KAIR;WACG;WAA2B,SAAS;;WACpC;WAA2B,sBAAsB;;;KAGpD;WAEG;WACA,MAAM;WACN;;WAGA;WACA;WAOA;WACA,sBAAsB;;;;;;;iBAqCrB,uBACd,UAAU,gBACV,kBAAkB,eAClB,kBACA,UAAS,kBACR;;;;;;iBA6Ea,oBACd,UAAU,gBACV,SAAS,iBACT,OAAO,cACN;;iBA0Fa,oBACd,MAAM,2BACK,YAAY"}
|
package/dist/fragments.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fragments.js","names":[],"sources":["../src/fragments.ts"],"sourcesContent":["import type { Binding, HirProgram } from \"./hir.ts\";\nimport { buildSeededHir } from \"./hir-build.ts\";\nimport { buildMir } from \"./mir-build.ts\";\nimport type { CompilerOptions, MirProgram } from \"./mir.ts\";\nimport type { Diagnostic, SourceInput } from \"./source.ts\";\nimport type { SourceFrontend, SyntaxProgram } from \"./syntax.ts\";\n\n/** Private fragment contract; changes invalidate generated object reuse. */\nexport const scriptFragmentAbi = \"oseo-script-fragments-v1\";\n\n/** A Script binding exported to a later fragment in the same environment. */\nexport interface FragmentBinding {\n readonly id: number;\n readonly name: string;\n readonly mutable: boolean;\n readonly globalObject: boolean;\n}\n\n/**\n * Independently lowered unit, not a standalone executable MirProgram.\n * The launcher owns instantiation and supplies the shared environment.\n */\nexport interface ScriptFragment {\n readonly hir: HirProgram;\n readonly mir: MirProgram;\n /** Exclusive limits include hidden bindings and all nested functions. */\n readonly nextBindingId: number;\n readonly nextFunctionId: number;\n /** HIR body indices owned by launcher instantiation, not evaluation. */\n readonly launcherInitializers: readonly number[];\n}\n\n/** Prepared ordered bundle. No body input contributes to these bytes. */\nexport interface HarnessFragment extends ScriptFragment {\n readonly abi: typeof scriptFragmentAbi;\n readonly sources: readonly SourceInput[];\n readonly bindings: readonly FragmentBinding[];\n readonly globalReferences: readonly string[];\n readonly strict: boolean;\n readonly options: CompilerOptions;\n}\n\n/** A failed preparation must use the existing whole-Script path. */\nexport type HarnessFragmentResult =\n | { readonly kind: \"compiled\"; readonly harness: HarnessFragment }\n | { readonly kind: \"fallback\"; readonly diagnostics: readonly Diagnostic[] };\n\n/** A body is either compatible with a prepared bundle or requires fallback. */\nexport type BodyFragmentResult =\n | {\n readonly kind: \"compiled\";\n readonly body: ScriptFragment;\n readonly bindingCount: number;\n }\n | {\n readonly kind: \"fallback\";\n readonly reason:\n | \"diagnostic\"\n | \"shadowing\"\n | \"strictness\"\n | \"metadata\"\n | \"global-effects\"\n | \"requests\";\n readonly names: readonly string[];\n readonly diagnostics: readonly Diagnostic[];\n };\n\nfunction fragment(\n hir: HirProgram,\n nextBindingId: number,\n nextFunctionId: number,\n options: CompilerOptions,\n): ScriptFragment {\n // An Annex B.3.2.2 name is initialized to undefined during instantiation,\n // as a var is, so its initializer belongs to the launcher too.\n const varIds = new Set(\n hir.globalObjectBindings\n ?.filter((binding) => binding.declaration !== \"function\")\n .map((binding) => binding.id),\n );\n return {\n hir,\n mir: buildMir(hir, options),\n nextBindingId,\n nextFunctionId,\n launcherInitializers: hir.body.flatMap((statement, index) =>\n statement.kind === \"function-init\" ||\n (statement.kind === \"let\" && varIds.has(statement.bindingId)) ||\n (statement.kind === \"const\" &&\n statement.bindingId === hir.intrinsicGlobalObjectBindingId)\n ? [index]\n : [],\n ),\n };\n}\n\n/**\n * Compile an ordered bundle once, reserving every ID before any case resolves.\n * Source order and duplicates are significant. Locations use the fixed virtual\n * bundle source; native emission must supply the launcher's logical source map.\n */\nexport function compileHarnessFragment(\n frontend: SourceFrontend,\n sources: readonly SourceInput[],\n strict = false,\n options: CompilerOptions = {},\n): HarnessFragmentResult {\n const parsed = frontend.parse({\n source:\n (strict ? '\"use strict\";\\n' : \"\") +\n sources.map((source) => source.source).join(\"\\n\"),\n sourceId: \"oseo:harness\",\n });\n if (parsed.program == null || parsed.diagnostics.length > 0) {\n return { kind: \"fallback\", diagnostics: parsed.diagnostics };\n }\n if (\n parsed.program.globalLexicalNames == null ||\n parsed.program.globalObjectNames == null\n ) {\n return { kind: \"fallback\", diagnostics: [] };\n }\n const globalReferences = new Set<string>();\n const resolved = buildSeededHir(parsed.program, {\n globalReferences,\n fragmentMetadata: true,\n });\n if (resolved.program == null || resolved.scriptBindings == null) {\n return { kind: \"fallback\", diagnostics: resolved.diagnostics };\n }\n if ((resolved.initializingWithNames?.length ?? 0) > 0) {\n return { kind: \"fallback\", diagnostics: [] };\n }\n const objectIds = new Set(\n resolved.program.globalObjectBindings?.map((binding) => binding.id),\n );\n return {\n kind: \"compiled\",\n harness: {\n ...fragment(\n resolved.program,\n resolved.nextBindingId,\n resolved.nextFunctionId,\n options,\n ),\n abi: scriptFragmentAbi,\n sources: sources.map((source) => ({ ...source })),\n bindings: [...resolved.scriptBindings.values()].map((binding) => ({\n id: binding.id,\n name: binding.name,\n mutable: binding.mutable,\n globalObject: objectIds.has(binding.id),\n })),\n globalReferences: [...globalReferences].toSorted(),\n strict: parsed.program.strict === true,\n options: { ...options },\n },\n };\n}\n\nfunction shadowedNames(\n harness: HarnessFragment,\n body: SyntaxProgram,\n): readonly string[] {\n const protectedNames = new Set([\n ...harness.globalReferences,\n ...harness.bindings.map((binding) => binding.name),\n ]);\n return [\n ...new Set([\n ...(body.globalLexicalNames ?? []).map((entry) => entry.name),\n ...(body.globalObjectNames ?? []).map((entry) => entry.name),\n ]),\n ]\n .filter((name) => protectedNames.has(name))\n .toSorted();\n}\n\n/**\n * Resolve a case against a prepared harness without mutating the harness.\n * Fallback is an instruction to compile the original assembled Script, not a\n * replacement diagnostic. Module/raw admission belongs to the future runner.\n */\nexport function compileBodyFragment(\n frontend: SourceFrontend,\n harness: HarnessFragment,\n input: SourceInput,\n): BodyFragmentResult {\n const parsed = frontend.parse({\n ...input,\n source: (harness.strict ? '\"use strict\";\\n' : \"\") + input.source,\n });\n if (parsed.program == null || parsed.diagnostics.length > 0) {\n return {\n kind: \"fallback\",\n reason: \"diagnostic\",\n names: [],\n diagnostics: parsed.diagnostics,\n };\n }\n // A body with `import()` calls needs its request closure, which only\n // the whole Script build discovers against the Script's identity.\n if ((parsed.program.importCalls?.length ?? 0) > 0) {\n return {\n kind: \"fallback\",\n reason: \"requests\",\n names: [],\n diagnostics: [],\n };\n }\n if ((parsed.program.strict === true) !== harness.strict) {\n return {\n kind: \"fallback\",\n reason: \"strictness\",\n names: [],\n diagnostics: [],\n };\n }\n if (\n parsed.program.globalLexicalNames == null ||\n parsed.program.globalObjectNames == null\n ) {\n return {\n kind: \"fallback\",\n reason: \"metadata\",\n names: [],\n diagnostics: [],\n };\n }\n const names = shadowedNames(harness, parsed.program);\n if (names.length > 0) {\n return { kind: \"fallback\", reason: \"shadowing\", names, diagnostics: [] };\n }\n const bindings = new Map<string, Binding>(\n harness.bindings.map((binding) => [\n binding.name,\n { id: binding.id, name: binding.name, mutable: binding.mutable },\n ]),\n );\n const resolved = buildSeededHir(parsed.program, {\n bindings,\n fragmentMetadata: true,\n globalObjectBindingIds: harness.bindings\n .filter((binding) => binding.globalObject)\n .map((binding) => binding.id),\n nextBindingId: harness.nextBindingId,\n nextFunctionId: harness.nextFunctionId,\n });\n if (resolved.program == null) {\n return {\n kind: \"fallback\",\n reason: \"diagnostic\",\n names: [],\n diagnostics: resolved.diagnostics,\n };\n }\n if ((resolved.initializingWithNames?.length ?? 0) > 0) {\n return {\n kind: \"fallback\",\n reason: \"global-effects\",\n names: resolved.initializingWithNames ?? [],\n diagnostics: [],\n };\n }\n return {\n kind: \"compiled\",\n body: fragment(\n resolved.program,\n resolved.nextBindingId,\n resolved.nextFunctionId,\n harness.options,\n ),\n bindingCount: resolved.nextBindingId,\n };\n}\n\n/** Separate launcher-owned initialization from ordered evaluation in MIR. */\nexport function lowerFragmentPhases(\n unit: ScriptFragment,\n): readonly [MirProgram, MirProgram] {\n const initializers = new Set(unit.launcherInitializers);\n const lower = (instantiate: boolean): MirProgram =>\n buildMir(\n {\n ...unit.hir,\n body: unit.hir.body.filter(\n (_, index) => initializers.has(index) === instantiate,\n ),\n },\n {\n specialization: unit.mir.specialization,\n observeSpecialization: unit.mir.observeSpecialization,\n unhandledRejectionPolicy: unit.mir.unhandledRejectionPolicy ?? \"fatal\",\n },\n );\n return [lower(true), lower(false)];\n}\n"],"mappings":";;;;;AAQA,MAAa,oBAAoB;AA2DjC,SAAS,SACP,KACA,eACA,gBACA,SACgB;CAGhB,MAAM,SAAS,IAAI,IACjB,IAAI,sBACA,QAAQ,YAAY,QAAQ,gBAAgB,UAAU,CAAC,CACxD,KAAK,YAAY,QAAQ,EAAE,CAChC;CACA,OAAO;EACL;EACA,KAAK,SAAS,KAAK,OAAO;EAC1B;EACA;EACA,sBAAsB,IAAI,KAAK,SAAS,WAAW,UACjD,UAAU,SAAS,mBAClB,UAAU,SAAS,SAAS,OAAO,IAAI,UAAU,SAAS,KAC1D,UAAU,SAAS,WAClB,UAAU,cAAc,IAAI,iCAC1B,CAAC,KAAK,IACN,CAAC,CACP;CACF;AACF;;;;;;AAOA,SAAgB,uBACd,UACA,SACA,SAAS,OACT,UAA2B,CAAC,GACL;CACvB,MAAM,SAAS,SAAS,MAAM;EAC5B,SACG,SAAS,sBAAoB,MAC9B,QAAQ,KAAK,WAAW,OAAO,MAAM,CAAC,CAAC,KAAK,IAAI;EAClD,UAAU;CACZ,CAAC;CACD,IAAI,OAAO,WAAW,QAAQ,OAAO,YAAY,SAAS,GACxD,OAAO;EAAE,MAAM;EAAY,aAAa,OAAO;CAAY;CAE7D,IACE,OAAO,QAAQ,sBAAsB,QACrC,OAAO,QAAQ,qBAAqB,MAEpC,OAAO;EAAE,MAAM;EAAY,aAAa,CAAC;CAAE;CAE7C,MAAM,mCAAm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uBAAuB,UAAU,KAAK,GAClD,OAAO;EACL,MAAM;EACN,QAAQ;EACR,OAAO,SAAS,yBAAyB,CAAC;EAC1C,aAAa,CAAC;CAChB;CAEF,OAAO;EACL,MAAM;EACN,MAAM,SACJ,SAAS,SACT,SAAS,eACT,SAAS,gBACT,QAAQ,OACV;EACA,cAAc,SAAS;CACzB;AACF;;AAGA,SAAgB,oBACd,MACmC;CACnC,MAAM,eAAe,IAAI,IAAI,KAAK,oBAAoB;CACtD,MAAM,SAAS,gBACb,SACE;EACE,GAAG,KAAK;EACR,MAAM,KAAK,IAAI,KAAK,QACjB,GAAG,UAAU,aAAa,IAAI,KAAK,MAAM,WAC5C;CACF,GACA;EACE,gBAAgB,KAAK,IAAI;EACzB,uBAAuB,KAAK,IAAI;EAChC,0BAA0B,KAAK,IAAI,4BAA4B;CACjE,CACF;CACF,OAAO,CAAC,MAAM,IAAI,GAAG,MAAM,KAAK,CAAC;AACnC"}
|
|
1
|
+
{"version":3,"file":"fragments.js","names":[],"sources":["../src/fragments.ts"],"sourcesContent":["/*\n * Oseo, an ahead-of-time compiler for JavaScript and TypeScript.\n * Copyright (C) 2026 Hong Minhee <https://hongminhee.org/>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n */\n\nimport type { Binding, HirProgram } from \"./hir.ts\";\nimport { buildSeededHir } from \"./hir-build.ts\";\nimport { buildMir } from \"./mir-build.ts\";\nimport type { CompilerOptions, MirProgram } from \"./mir.ts\";\nimport type { Diagnostic, SourceInput } from \"./source.ts\";\nimport type { SourceFrontend, SyntaxProgram } from \"./syntax.ts\";\n\n/** Private fragment contract; changes invalidate generated object reuse. */\nexport const scriptFragmentAbi = \"oseo-script-fragments-v1\";\n\n/** A Script binding exported to a later fragment in the same environment. */\nexport interface FragmentBinding {\n readonly id: number;\n readonly name: string;\n readonly mutable: boolean;\n readonly globalObject: boolean;\n}\n\n/**\n * Independently lowered unit, not a standalone executable MirProgram.\n * The launcher owns instantiation and supplies the shared environment.\n */\nexport interface ScriptFragment {\n readonly hir: HirProgram;\n readonly mir: MirProgram;\n /** Exclusive limits include hidden bindings and all nested functions. */\n readonly nextBindingId: number;\n readonly nextFunctionId: number;\n /** HIR body indices owned by launcher instantiation, not evaluation. */\n readonly launcherInitializers: readonly number[];\n}\n\n/** Prepared ordered bundle. No body input contributes to these bytes. */\nexport interface HarnessFragment extends ScriptFragment {\n readonly abi: typeof scriptFragmentAbi;\n readonly sources: readonly SourceInput[];\n readonly bindings: readonly FragmentBinding[];\n readonly globalReferences: readonly string[];\n readonly strict: boolean;\n readonly options: CompilerOptions;\n}\n\n/** A failed preparation must use the existing whole-Script path. */\nexport type HarnessFragmentResult =\n | { readonly kind: \"compiled\"; readonly harness: HarnessFragment }\n | { readonly kind: \"fallback\"; readonly diagnostics: readonly Diagnostic[] };\n\n/** A body is either compatible with a prepared bundle or requires fallback. */\nexport type BodyFragmentResult =\n | {\n readonly kind: \"compiled\";\n readonly body: ScriptFragment;\n readonly bindingCount: number;\n }\n | {\n readonly kind: \"fallback\";\n readonly reason:\n | \"diagnostic\"\n | \"shadowing\"\n | \"strictness\"\n | \"metadata\"\n | \"global-effects\"\n | \"requests\";\n readonly names: readonly string[];\n readonly diagnostics: readonly Diagnostic[];\n };\n\nfunction fragment(\n hir: HirProgram,\n nextBindingId: number,\n nextFunctionId: number,\n options: CompilerOptions,\n): ScriptFragment {\n // An Annex B.3.2.2 name is initialized to undefined during instantiation,\n // as a var is, so its initializer belongs to the launcher too.\n const varIds = new Set(\n hir.globalObjectBindings\n ?.filter((binding) => binding.declaration !== \"function\")\n .map((binding) => binding.id),\n );\n return {\n hir,\n mir: buildMir(hir, options),\n nextBindingId,\n nextFunctionId,\n launcherInitializers: hir.body.flatMap((statement, index) =>\n statement.kind === \"function-init\" ||\n (statement.kind === \"let\" && varIds.has(statement.bindingId)) ||\n (statement.kind === \"const\" &&\n statement.bindingId === hir.intrinsicGlobalObjectBindingId)\n ? [index]\n : [],\n ),\n };\n}\n\n/**\n * Compile an ordered bundle once, reserving every ID before any case resolves.\n * Source order and duplicates are significant. Locations use the fixed virtual\n * bundle source; native emission must supply the launcher's logical source map.\n */\nexport function compileHarnessFragment(\n frontend: SourceFrontend,\n sources: readonly SourceInput[],\n strict = false,\n options: CompilerOptions = {},\n): HarnessFragmentResult {\n const parsed = frontend.parse({\n source:\n (strict ? '\"use strict\";\\n' : \"\") +\n sources.map((source) => source.source).join(\"\\n\"),\n sourceId: \"oseo:harness\",\n });\n if (parsed.program == null || parsed.diagnostics.length > 0) {\n return { kind: \"fallback\", diagnostics: parsed.diagnostics };\n }\n if (\n parsed.program.globalLexicalNames == null ||\n parsed.program.globalObjectNames == null\n ) {\n return { kind: \"fallback\", diagnostics: [] };\n }\n const globalReferences = new Set<string>();\n const resolved = buildSeededHir(parsed.program, {\n globalReferences,\n fragmentMetadata: true,\n });\n if (resolved.program == null || resolved.scriptBindings == null) {\n return { kind: \"fallback\", diagnostics: resolved.diagnostics };\n }\n if ((resolved.initializingWithNames?.length ?? 0) > 0) {\n return { kind: \"fallback\", diagnostics: [] };\n }\n const objectIds = new Set(\n resolved.program.globalObjectBindings?.map((binding) => binding.id),\n );\n return {\n kind: \"compiled\",\n harness: {\n ...fragment(\n resolved.program,\n resolved.nextBindingId,\n resolved.nextFunctionId,\n options,\n ),\n abi: scriptFragmentAbi,\n sources: sources.map((source) => ({ ...source })),\n bindings: [...resolved.scriptBindings.values()].map((binding) => ({\n id: binding.id,\n name: binding.name,\n mutable: binding.mutable,\n globalObject: objectIds.has(binding.id),\n })),\n globalReferences: [...globalReferences].toSorted(),\n strict: parsed.program.strict === true,\n options: { ...options },\n },\n };\n}\n\nfunction shadowedNames(\n harness: HarnessFragment,\n body: SyntaxProgram,\n): readonly string[] {\n const protectedNames = new Set([\n ...harness.globalReferences,\n ...harness.bindings.map((binding) => binding.name),\n ]);\n return [\n ...new Set([\n ...(body.globalLexicalNames ?? []).map((entry) => entry.name),\n ...(body.globalObjectNames ?? []).map((entry) => entry.name),\n ]),\n ]\n .filter((name) => protectedNames.has(name))\n .toSorted();\n}\n\n/**\n * Resolve a case against a prepared harness without mutating the harness.\n * Fallback is an instruction to compile the original assembled Script, not a\n * replacement diagnostic. Module/raw admission belongs to the future runner.\n */\nexport function compileBodyFragment(\n frontend: SourceFrontend,\n harness: HarnessFragment,\n input: SourceInput,\n): BodyFragmentResult {\n const parsed = frontend.parse({\n ...input,\n source: (harness.strict ? '\"use strict\";\\n' : \"\") + input.source,\n });\n if (parsed.program == null || parsed.diagnostics.length > 0) {\n return {\n kind: \"fallback\",\n reason: \"diagnostic\",\n names: [],\n diagnostics: parsed.diagnostics,\n };\n }\n // A body with `import()` calls needs its request closure, which only\n // the whole Script build discovers against the Script's identity.\n if ((parsed.program.importCalls?.length ?? 0) > 0) {\n return {\n kind: \"fallback\",\n reason: \"requests\",\n names: [],\n diagnostics: [],\n };\n }\n if ((parsed.program.strict === true) !== harness.strict) {\n return {\n kind: \"fallback\",\n reason: \"strictness\",\n names: [],\n diagnostics: [],\n };\n }\n if (\n parsed.program.globalLexicalNames == null ||\n parsed.program.globalObjectNames == null\n ) {\n return {\n kind: \"fallback\",\n reason: \"metadata\",\n names: [],\n diagnostics: [],\n };\n }\n const names = shadowedNames(harness, parsed.program);\n if (names.length > 0) {\n return { kind: \"fallback\", reason: \"shadowing\", names, diagnostics: [] };\n }\n const bindings = new Map<string, Binding>(\n harness.bindings.map((binding) => [\n binding.name,\n { id: binding.id, name: binding.name, mutable: binding.mutable },\n ]),\n );\n const resolved = buildSeededHir(parsed.program, {\n bindings,\n fragmentMetadata: true,\n globalObjectBindingIds: harness.bindings\n .filter((binding) => binding.globalObject)\n .map((binding) => binding.id),\n nextBindingId: harness.nextBindingId,\n nextFunctionId: harness.nextFunctionId,\n });\n if (resolved.program == null) {\n return {\n kind: \"fallback\",\n reason: \"diagnostic\",\n names: [],\n diagnostics: resolved.diagnostics,\n };\n }\n if ((resolved.initializingWithNames?.length ?? 0) > 0) {\n return {\n kind: \"fallback\",\n reason: \"global-effects\",\n names: resolved.initializingWithNames ?? [],\n diagnostics: [],\n };\n }\n return {\n kind: \"compiled\",\n body: fragment(\n resolved.program,\n resolved.nextBindingId,\n resolved.nextFunctionId,\n harness.options,\n ),\n bindingCount: resolved.nextBindingId,\n };\n}\n\n/** Separate launcher-owned initialization from ordered evaluation in MIR. */\nexport function lowerFragmentPhases(\n unit: ScriptFragment,\n): readonly [MirProgram, MirProgram] {\n const initializers = new Set(unit.launcherInitializers);\n const lower = (instantiate: boolean): MirProgram =>\n buildMir(\n {\n ...unit.hir,\n body: unit.hir.body.filter(\n (_, index) => initializers.has(index) === instantiate,\n ),\n },\n {\n specialization: unit.mir.specialization,\n observeSpecialization: unit.mir.observeSpecialization,\n unhandledRejectionPolicy: unit.mir.unhandledRejectionPolicy ?? \"fatal\",\n },\n );\n return [lower(true), lower(false)];\n}\n"],"mappings":";;;;;AA0BA,MAAa,oBAAoB;AA2DjC,SAAS,SACP,KACA,eACA,gBACA,SACgB;CAGhB,MAAM,SAAS,IAAI,IACjB,IAAI,sBACA,QAAQ,YAAY,QAAQ,gBAAgB,UAAU,CAAC,CACxD,KAAK,YAAY,QAAQ,EAAE,CAChC;CACA,OAAO;EACL;EACA,KAAK,SAAS,KAAK,OAAO;EAC1B;EACA;EACA,sBAAsB,IAAI,KAAK,SAAS,WAAW,UACjD,UAAU,SAAS,mBAClB,UAAU,SAAS,SAAS,OAAO,IAAI,UAAU,SAAS,KAC1D,UAAU,SAAS,WAClB,UAAU,cAAc,IAAI,iCAC1B,CAAC,KAAK,IACN,CAAC,CACP;CACF;AAC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AAS,KAAK,YAAY,CAChC,QAAQ,MACR;EAAE,IAAI,QAAQ;EAAI,MAAM,QAAQ;EAAM,SAAS,QAAQ;CAAQ,CACjE,CAAC,CACH;CACA,MAAM,WAAW,eAAe,OAAO,SAAS;EAC9C;EACA,kBAAkB;EAClB,wBAAwB,QAAQ,SAC7B,QAAQ,YAAY,QAAQ,YAAY,CAAC,CACzC,KAAK,YAAY,QAAQ,EAAE;EAC9B,eAAe,QAAQ;EACvB,gBAAgB,QAAQ;CAC1B,CAAC;CACD,IAAI,SAAS,WAAW,MACtB,OAAO;EACL,MAAM;EACN,QAAQ;EACR,OAAO,CAAC;EACR,aAAa,SAAS;CACxB;CAEF,KAAK,SAAS,uBAAuB,UAAU,KAAK,GAClD,OAAO;EACL,MAAM;EACN,QAAQ;EACR,OAAO,SAAS,yBAAyB,CAAC;EAC1C,aAAa,CAAC;CAChB;CAEF,OAAO;EACL,MAAM;EACN,MAAM,SACJ,SAAS,SACT,SAAS,eACT,SAAS,gBACT,QAAQ,OACV;EACA,cAAc,SAAS;CACzB;AACF;;AAGA,SAAgB,oBACd,MACmC;CACnC,MAAM,eAAe,IAAI,IAAI,KAAK,oBAAoB;CACtD,MAAM,SAAS,gBACb,SACE;EACE,GAAG,KAAK;EACR,MAAM,KAAK,IAAI,KAAK,QACjB,GAAG,UAAU,aAAa,IAAI,KAAK,MAAM,WAC5C;CACF,GACA;EACE,gBAAgB,KAAK,IAAI;EACzB,uBAAuB,KAAK,IAAI;EAChC,0BAA0B,KAAK,IAAI,4BAA4B;CACjE,CACF;CACF,OAAO,CAAC,MAAM,IAAI,GAAG,MAAM,KAAK,CAAC;AACnC"}
|
package/dist/hir-build.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hir-build.d.ts","names":[],"sources":["../src/hir-build.ts"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"hir-build.d.ts","names":[],"sources":["../src/hir-build.ts"],"mappings":";;;;;;;;;cA2Fa;iBAGG,iBACd,kBACA,MAAM,eACN,kBACC;KAq+DS,sBAAsB,iBAAiB;iBAiqBnC,sBACd,SAAS,6BACC;iBA8CI,sBAAsB,YAAY;iBA6IlC,0BAA0B,SAAS;iBAmCnC,sBACd,qBAAqB;;UAy2DN;WACN;WACA,MAAM;;;;;;;UAQA;;WAEN;;;;;WAKA,sBAAsB;;WAEtB;;UAGD,gBAAgB;WACf;;WAEA,mBAAmB;;WAEnB;WACA,WAAW,oBAAoB;;;;;;;WAO/B,gBAAgB,oBAAoB;;;;;;;;WAQpC;;;;;;WAMA,oBAAoB;WACpB;WACA;;UAGD,wBAAwB;WACvB,iBAAiB,oBAAoB;WACrC;WACA;WACA;;iBAGK,eACd,SAAS,eACT,OAAM,UACL;;iBA+La,SACd,SAAS,eACT,UAAS,iBACR"}
|