@oseo/compiler 0.0.0-stage → 0.1.0-canary.0

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.
Files changed (105) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +172 -2
  3. package/dist/agent-programs.d.ts +28 -0
  4. package/dist/agent-programs.d.ts.map +1 -0
  5. package/dist/agent-programs.js +134 -0
  6. package/dist/agent-programs.js.map +1 -0
  7. package/dist/agent-templates.d.ts +33 -0
  8. package/dist/agent-templates.d.ts.map +1 -0
  9. package/dist/agent-templates.js +45 -0
  10. package/dist/agent-templates.js.map +1 -0
  11. package/dist/compile.d.ts +20 -0
  12. package/dist/compile.d.ts.map +1 -0
  13. package/dist/compile.js +75 -0
  14. package/dist/compile.js.map +1 -0
  15. package/dist/fragments.d.ts +72 -0
  16. package/dist/fragments.d.ts.map +1 -0
  17. package/dist/fragments.js +158 -0
  18. package/dist/fragments.js.map +1 -0
  19. package/dist/hir-build.d.ts +80 -0
  20. package/dist/hir-build.d.ts.map +1 -0
  21. package/dist/hir-build.js +3077 -0
  22. package/dist/hir-build.js.map +1 -0
  23. package/dist/hir-print.d.ts +10 -0
  24. package/dist/hir-print.d.ts.map +1 -0
  25. package/dist/hir-print.js +271 -0
  26. package/dist/hir-print.js.map +1 -0
  27. package/dist/hir.d.ts +1246 -0
  28. package/dist/hir.d.ts.map +1 -0
  29. package/dist/hir.js +147 -0
  30. package/dist/hir.js.map +1 -0
  31. package/dist/host-scripts.d.ts +14 -0
  32. package/dist/host-scripts.d.ts.map +1 -0
  33. package/dist/host-scripts.js +204 -0
  34. package/dist/host-scripts.js.map +1 -0
  35. package/dist/index.d.ts +26 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +27 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/mir-build.d.ts +8 -0
  40. package/dist/mir-build.d.ts.map +1 -0
  41. package/dist/mir-build.js +5113 -0
  42. package/dist/mir-build.js.map +1 -0
  43. package/dist/mir-print.d.ts +7 -0
  44. package/dist/mir-print.d.ts.map +1 -0
  45. package/dist/mir-print.js +65 -0
  46. package/dist/mir-print.js.map +1 -0
  47. package/dist/mir-specialize.d.ts +7 -0
  48. package/dist/mir-specialize.d.ts.map +1 -0
  49. package/dist/mir-specialize.js +182 -0
  50. package/dist/mir-specialize.js.map +1 -0
  51. package/dist/mir.d.ts +571 -0
  52. package/dist/mir.d.ts.map +1 -0
  53. package/dist/mir.js +1 -0
  54. package/dist/module-builtin.d.ts +20 -0
  55. package/dist/module-builtin.d.ts.map +1 -0
  56. package/dist/module-builtin.js +57 -0
  57. package/dist/module-builtin.js.map +1 -0
  58. package/dist/module-compile.d.ts +64 -0
  59. package/dist/module-compile.d.ts.map +1 -0
  60. package/dist/module-compile.js +690 -0
  61. package/dist/module-compile.js.map +1 -0
  62. package/dist/module-json.d.ts +7 -0
  63. package/dist/module-json.d.ts.map +1 -0
  64. package/dist/module-json.js +88 -0
  65. package/dist/module-json.js.map +1 -0
  66. package/dist/modules.d.ts +87 -0
  67. package/dist/modules.d.ts.map +1 -0
  68. package/dist/modules.js +734 -0
  69. package/dist/modules.js.map +1 -0
  70. package/dist/native-fragments.d.ts +36 -0
  71. package/dist/native-fragments.d.ts.map +1 -0
  72. package/dist/native-fragments.js +110 -0
  73. package/dist/native-fragments.js.map +1 -0
  74. package/dist/native.d.ts +282 -0
  75. package/dist/native.d.ts.map +1 -0
  76. package/dist/native.js +47 -0
  77. package/dist/native.js.map +1 -0
  78. package/dist/regexp-execute.d.ts +74 -0
  79. package/dist/regexp-execute.d.ts.map +1 -0
  80. package/dist/regexp-execute.js +480 -0
  81. package/dist/regexp-execute.js.map +1 -0
  82. package/dist/regexp-matcher.d.ts +279 -0
  83. package/dist/regexp-matcher.d.ts.map +1 -0
  84. package/dist/regexp-matcher.js +1098 -0
  85. package/dist/regexp-matcher.js.map +1 -0
  86. package/dist/regexp-parse.d.ts +22 -0
  87. package/dist/regexp-parse.d.ts.map +1 -0
  88. package/dist/regexp-parse.js +1440 -0
  89. package/dist/regexp-parse.js.map +1 -0
  90. package/dist/regexp-print.d.ts +24 -0
  91. package/dist/regexp-print.d.ts.map +1 -0
  92. package/dist/regexp-print.js +147 -0
  93. package/dist/regexp-print.js.map +1 -0
  94. package/dist/regexp.d.ts +324 -0
  95. package/dist/regexp.d.ts.map +1 -0
  96. package/dist/regexp.js +22 -0
  97. package/dist/regexp.js.map +1 -0
  98. package/dist/source.d.ts +38 -0
  99. package/dist/source.d.ts.map +1 -0
  100. package/dist/source.js +10 -0
  101. package/dist/source.js.map +1 -0
  102. package/dist/syntax.d.ts +1232 -0
  103. package/dist/syntax.d.ts.map +1 -0
  104. package/dist/syntax.js +1 -0
  105. package/package.json +32 -3
package/README.md CHANGED
@@ -1,3 +1,173 @@
1
- # Temporary Holding Version
1
+ @oseo/compiler
2
+ ==============
2
3
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
4
+ This package owns Oseo syntax, hint metadata, lexical resolution, HIR, MIR,
5
+ specialization policy, diagnostics, targets, and extension interfaces.
6
+ Concrete parser, backend, runtime, toolchain, and host packages implement these
7
+ contracts without becoming compiler-core dependencies.
8
+ The exported syntax contract separates declaration binding patterns from
9
+ destructuring assignment patterns. Only assignment patterns admit member
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.
16
+
17
+ Internal ownership follows the compiler pipeline. *source.ts* and *syntax.ts*
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.
25
+
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
+
35
+ MIR is self-contained: constants, lexical binding reads and writes, MIR-owned
36
+ parameters, rest markers, and hints, operators, call targets, control-flow
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.
129
+
130
+ M4 adds owned module syntax, canonical graph discovery interfaces, static
131
+ linking, strongly connected components, and whole-graph lowering. Imported and
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.
143
+
144
+ Graph discovery also follows the literal `import()` sites that a frontend
145
+ reports in `importCalls`. Each target's static closure joins the graph after
146
+ the entry's static closure, but never a module's `dependencies`, so linking
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.
154
+
155
+ `compileModuleGraph` lists every discovered module in the table: the entry's
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.
168
+
169
+ `compileSource` and `buildMir` accept an explicit enabled or disabled
170
+ specialization policy. Enabled mode selects the M2 checked small-integer path
171
+ only for the reviewed two-parameter return form. Its MIR retains hint
172
+ provenance, two tag guards, checked arithmetic, a shared generic fallback, and
173
+ an explicit result join. Disabled mode emits the unchanged generic graph.
@@ -0,0 +1,28 @@
1
+ import { Diagnostic } from "./source.js";
2
+ import { SourceFrontend } from "./syntax.js";
3
+ import { AgentSourceTemplate } from "./agent-templates.js";
4
+ import { CompilerOptions, MirProgram } from "./mir.js";
5
+ //#region src/agent-programs.d.ts
6
+ /** An agent program compiled from one template, or why it was not. */
7
+ type AgentProgramResult = {
8
+ readonly diagnostics: readonly Diagnostic[];
9
+ } | {
10
+ readonly mir: MirProgram;
11
+ };
12
+ /**
13
+ * Compiles one agent program from its template (ADR 0026). The program
14
+ * is the template text with each hole replaced by a fresh identifier that
15
+ * resolves to the hole's Number, so it evaluates exactly what a start
16
+ * source reads when each hole holds a decimal integer literal, which is
17
+ * all the runtime lets a hole match: both replacements are one
18
+ * PrimaryExpression token in the same position. The template is rejected
19
+ * unless every hole is delimited as one token, the text with `0` in each
20
+ * hole parses, and each placeholder is resolved as exactly one identifier
21
+ * read and nothing else.
22
+ */
23
+ declare function compileAgentTemplate(frontend: SourceFrontend, template: AgentSourceTemplate, index: number, mainSourceId: string, options: CompilerOptions): AgentProgramResult;
24
+ /** The source identity an agent program's diagnostics report. */
25
+ declare function agentSourceId(mainSourceId: string, index: number): string;
26
+ //#endregion
27
+ export { AgentProgramResult, agentSourceId, compileAgentTemplate };
28
+ //# sourceMappingURL=agent-programs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-programs.d.ts","names":[],"sources":["../src/agent-programs.ts"],"mappings":";;;;;;KAaY;WACG,sBAAsB;;WACtB,KAAK;;;;;;;;;;;;;iBAwDJ,qBACd,UAAU,gBACV,UAAU,qBACV,eACA,sBACA,SAAS,kBACR;;iBAgHa,cAAc,sBAAsB"}
@@ -0,0 +1,134 @@
1
+ import { buildHir } from "./hir-build.js";
2
+ import { buildMir } from "./mir-build.js";
3
+
4
+ //#region src/agent-programs.ts
5
+ function decodeUnicodeEscapes(text) {
6
+ return text.replaceAll(/\\u(?:\{([0-9A-Fa-f]+)\}|([0-9A-Fa-f]{4}))/gu, (escape, braced, fixed) => {
7
+ const codePoint = Number.parseInt(braced ?? fixed ?? "", 16);
8
+ return codePoint <= 1114111 ? String.fromCodePoint(codePoint) : escape;
9
+ });
10
+ }
11
+ function separatesHole(character) {
12
+ if (character == null) return true;
13
+ if (character.charCodeAt(0) >= 128) return false;
14
+ return !/[A-Za-z0-9$_.\\]/u.test(character);
15
+ }
16
+ function templateDiagnostic(template, sourceId, message) {
17
+ return {
18
+ byteRange: {
19
+ end: 0,
20
+ start: 0
21
+ },
22
+ code: "OSEO1001",
23
+ message,
24
+ range: template.range,
25
+ sourceId
26
+ };
27
+ }
28
+ /**
29
+ * Compiles one agent program from its template (ADR 0026). The program
30
+ * is the template text with each hole replaced by a fresh identifier that
31
+ * resolves to the hole's Number, so it evaluates exactly what a start
32
+ * source reads when each hole holds a decimal integer literal, which is
33
+ * all the runtime lets a hole match: both replacements are one
34
+ * PrimaryExpression token in the same position. The template is rejected
35
+ * unless every hole is delimited as one token, the text with `0` in each
36
+ * hole parses, and each placeholder is resolved as exactly one identifier
37
+ * read and nothing else.
38
+ */
39
+ function compileAgentTemplate(frontend, template, index, mainSourceId, options) {
40
+ const sourceId = agentSourceId(mainSourceId, index);
41
+ const { segments } = template;
42
+ const text = segments.join("");
43
+ const decoded = decodeUnicodeEscapes(text);
44
+ const names = segments.slice(1).map((_, hole) => {
45
+ let name = `$262AgentHole${hole}`;
46
+ while (text.includes(name) || decoded.includes(name)) name = `_${name}`;
47
+ return name;
48
+ });
49
+ for (let hole = 0; hole < names.length; hole += 1) if (!separatesHole(segments[hole]?.at(-1)) || !separatesHole(segments[hole + 1]?.at(0))) return { diagnostics: [templateDiagnostic(template, mainSourceId, `Agent source template hole ${hole} is not delimited as one numeric literal token.`)] };
50
+ const literal = frontend.parse({
51
+ source: segments.join("0"),
52
+ sourceId
53
+ });
54
+ if (literal.program == null) return { diagnostics: literal.diagnostics };
55
+ const encoder = new TextEncoder();
56
+ const holes = [];
57
+ let source = segments[0] ?? "";
58
+ for (const [position, name] of names.entries()) {
59
+ const start = encoder.encode(source).length;
60
+ holes.push({
61
+ name,
62
+ span: {
63
+ end: start + name.length,
64
+ start
65
+ }
66
+ });
67
+ source += name + (segments[position + 1] ?? "");
68
+ }
69
+ const parsed = frontend.parse({
70
+ source,
71
+ sourceId
72
+ });
73
+ if (parsed.program == null) return { diagnostics: parsed.diagnostics };
74
+ const hir = buildHir(parsed.program, { agentHoles: holes });
75
+ if (hir.program == null) return { diagnostics: hir.diagnostics };
76
+ const mir = buildMir(hir.program, {
77
+ ...options,
78
+ test262Host: false
79
+ });
80
+ const split = (operation) => {
81
+ const functionSource = operation.functionSource;
82
+ if (functionSource == null) return operation;
83
+ const functionSourceHoles = splitAtPlaceholders(functionSource, names);
84
+ return functionSourceHoles == null ? operation : {
85
+ ...operation,
86
+ functionSourceHoles
87
+ };
88
+ };
89
+ const splitFunction = (functionValue) => ({
90
+ ...functionValue,
91
+ blocks: functionValue.blocks.map((block) => ({
92
+ ...block,
93
+ operations: block.operations.map(split)
94
+ }))
95
+ });
96
+ return { mir: {
97
+ ...mir,
98
+ agentProgram: index,
99
+ functions: mir.functions.map(splitFunction),
100
+ script: splitFunction(mir.script)
101
+ } };
102
+ }
103
+ function splitAtPlaceholders(text, names) {
104
+ const holeIndexes = [];
105
+ const runs = [];
106
+ let position = 0;
107
+ let run = "";
108
+ while (position < text.length) {
109
+ let hole = -1;
110
+ for (const [index, name] of names.entries()) if (text.startsWith(name, position) && (hole < 0 || name.length > names[hole].length)) hole = index;
111
+ if (hole < 0) {
112
+ run += text[position];
113
+ position += 1;
114
+ continue;
115
+ }
116
+ runs.push(run);
117
+ run = "";
118
+ holeIndexes.push(hole);
119
+ position += names[hole].length;
120
+ }
121
+ runs.push(run);
122
+ return holeIndexes.length === 0 ? void 0 : {
123
+ holes: holeIndexes,
124
+ runs
125
+ };
126
+ }
127
+ /** The source identity an agent program's diagnostics report. */
128
+ function agentSourceId(mainSourceId, index) {
129
+ return `${mainSourceId}#agent-${index}`;
130
+ }
131
+
132
+ //#endregion
133
+ export { agentSourceId, compileAgentTemplate };
134
+ //# sourceMappingURL=agent-programs.js.map
@@ -0,0 +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,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YAAY,WAAW,IAAI,SAAY;EAAE,OAAO;EAAa;CAAK;AAC3E;;AAGA,SAAgB,cAAc,cAAsB,OAAuB;CACzE,OAAO,GAAG,aAAa,SAAS;AAClC"}
@@ -0,0 +1,33 @@
1
+ import { SourceRange } from "./source.js";
2
+ import { SyntaxCallArgument, SyntaxCallTarget } from "./syntax.js";
3
+ //#region src/agent-templates.d.ts
4
+ /**
5
+ * The global name of the test262 host object a Script compiled for the
6
+ * test262 host reads.
7
+ */
8
+ declare const test262HostGlobalName = "$262";
9
+ /**
10
+ * One `$262.agent.start` source template found in a Script: the cooked
11
+ * literal text around each substitution of a template literal, or the
12
+ * whole text of a string literal, which has no substitution.
13
+ */
14
+ interface AgentSourceTemplate {
15
+ readonly range: SourceRange;
16
+ readonly segments: readonly string[];
17
+ }
18
+ /** Whether a call target is exactly `$262.agent.start`. */
19
+ declare function isAgentStartTarget(target: SyntaxCallTarget): boolean;
20
+ /**
21
+ * The literal runs of a start argument. The frontend lowers an untagged
22
+ * template literal to a left-nested `+` chain that starts with its first
23
+ * cooked string and continues with a `to-string` conversion for each
24
+ * substitution and a string for each nonempty later run, so the chain is
25
+ * read back into runs with one hole per conversion. A plain string literal
26
+ * is one run, and a chain of string literals is their concatenation. Any
27
+ * other argument has no template, and a start with it reaches the
28
+ * runtime's owned boundary instead.
29
+ */
30
+ declare function agentTemplateSegments(argument: SyntaxCallArgument | undefined): readonly string[] | undefined;
31
+ //#endregion
32
+ export { AgentSourceTemplate, agentTemplateSegments, isAgentStartTarget, test262HostGlobalName };
33
+ //# sourceMappingURL=agent-templates.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-templates.d.ts","names":[],"sources":["../src/agent-templates.ts"],"mappings":";;;;;;;cAWa;;;;;;UAOI;WACN,OAAO;WACP;;;iBAQK,mBAAmB,QAAQ;;;;;;;;;;;iBAwB3B,sBACd,UAAU"}
@@ -0,0 +1,45 @@
1
+ //#region src/agent-templates.ts
2
+ /**
3
+ * The global name of the test262 host object a Script compiled for the
4
+ * test262 host reads.
5
+ */
6
+ const test262HostGlobalName = "$262";
7
+ function stringKey(expression, name) {
8
+ return expression.kind === "string" && expression.value === name;
9
+ }
10
+ /** Whether a call target is exactly `$262.agent.start`. */
11
+ function isAgentStartTarget(target) {
12
+ if (target.kind !== "property" || !stringKey(target.key, "start")) return false;
13
+ const agent = target.object;
14
+ if (agent.kind !== "property-get" || !stringKey(agent.key, "agent")) return false;
15
+ return agent.object.kind === "identifier" && agent.object.name === "$262";
16
+ }
17
+ /**
18
+ * The literal runs of a start argument. The frontend lowers an untagged
19
+ * template literal to a left-nested `+` chain that starts with its first
20
+ * cooked string and continues with a `to-string` conversion for each
21
+ * substitution and a string for each nonempty later run, so the chain is
22
+ * read back into runs with one hole per conversion. A plain string literal
23
+ * is one run, and a chain of string literals is their concatenation. Any
24
+ * other argument has no template, and a start with it reaches the
25
+ * runtime's owned boundary instead.
26
+ */
27
+ function agentTemplateSegments(argument) {
28
+ if (argument == null || argument.kind === "spread") return void 0;
29
+ const pieces = [];
30
+ let current = argument;
31
+ while (current.kind === "binary" && current.operator === "+") {
32
+ pieces.push(current.right);
33
+ current = current.left;
34
+ }
35
+ if (current.kind !== "string") return void 0;
36
+ const segments = [current.value];
37
+ for (const piece of pieces.toReversed()) if (piece.kind === "unary" && piece.operator === "to-string") segments.push("");
38
+ else if (piece.kind === "string") segments[segments.length - 1] += piece.value;
39
+ else return;
40
+ return segments;
41
+ }
42
+
43
+ //#endregion
44
+ export { agentTemplateSegments, isAgentStartTarget, test262HostGlobalName };
45
+ //# sourceMappingURL=agent-templates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-templates.js","names":[],"sources":["../src/agent-templates.ts"],"sourcesContent":["import 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":";;;;;AAWA,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"}
@@ -0,0 +1,20 @@
1
+ import { SourceInput } from "./source.js";
2
+ import { SourceFrontend } from "./syntax.js";
3
+ import { CompilerOptions } from "./mir.js";
4
+ import { CompilationResult, ScriptModuleRequests } from "./module-compile.js";
5
+ //#region src/compile.d.ts
6
+ /**
7
+ * Compile source through owned syntax, HIR, and policy-selected MIR. With
8
+ * the test262 host option, the result also carries one agent program for
9
+ * each `$262.agent.start` template, and the main program's table names
10
+ * them in the same order.
11
+ *
12
+ * `requests` names the modules a Script's `import()` calls reach, as
13
+ * `buildScriptRequests` discovered them for the same Script under
14
+ * its canonical identity. Without it, every `import()` keeps its profile
15
+ * diagnostic.
16
+ */
17
+ declare function compileSource(frontend: SourceFrontend, input: SourceInput, options?: CompilerOptions, requests?: ScriptModuleRequests): CompilationResult;
18
+ //#endregion
19
+ export { compileSource };
20
+ //# sourceMappingURL=compile.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile.d.ts","names":[],"sources":["../src/compile.ts"],"mappings":";;;;;;;;;;;;;;;;iBAuBgB,cACd,UAAU,gBACV,OAAO,aACP,UAAS,iBACT,WAAW,uBACV"}
@@ -0,0 +1,75 @@
1
+ import { buildSeededHir } from "./hir-build.js";
2
+ import { buildMir } from "./mir-build.js";
3
+ import { agentSourceId, compileAgentTemplate } from "./agent-programs.js";
4
+ import { compileHostScripts } from "./host-scripts.js";
5
+ import { buildScriptGraphHir } from "./module-compile.js";
6
+
7
+ //#region src/compile.ts
8
+ /**
9
+ * Compile source through owned syntax, HIR, and policy-selected MIR. With
10
+ * the test262 host option, the result also carries one agent program for
11
+ * each `$262.agent.start` template, and the main program's table names
12
+ * them in the same order.
13
+ *
14
+ * `requests` names the modules a Script's `import()` calls reach, as
15
+ * `buildScriptRequests` discovered them for the same Script under
16
+ * its canonical identity. Without it, every `import()` keeps its profile
17
+ * diagnostic.
18
+ */
19
+ function compileSource(frontend, input, options = {}, requests) {
20
+ const frontendResult = frontend.parse(input);
21
+ if (frontendResult.program == null) return { diagnostics: frontendResult.diagnostics };
22
+ const host = options.test262Host === true;
23
+ const seed = host ? {
24
+ collectAgentTemplates: true,
25
+ hostScriptBindings: true
26
+ } : {};
27
+ const hirResult = requests == null ? buildSeededHir(frontendResult.program, seed) : buildScriptGraphHir(frontendResult.program, requests, seed);
28
+ if (hirResult.program == null) return {
29
+ diagnostics: hirResult.diagnostics,
30
+ syntax: frontendResult.program
31
+ };
32
+ const mir = buildMir(hirResult.program, options);
33
+ if (!host) return {
34
+ diagnostics: [],
35
+ hir: hirResult.program,
36
+ mir,
37
+ syntax: frontendResult.program
38
+ };
39
+ const agents = [];
40
+ const templates = [];
41
+ for (const [index, template] of (hirResult.program.agentTemplates ?? []).entries()) {
42
+ const compiled = compileAgentTemplate(frontend, template, index, input.sourceId, options);
43
+ if ("diagnostics" in compiled) return {
44
+ diagnostics: compiled.diagnostics,
45
+ syntax: frontendResult.program
46
+ };
47
+ agents.push(compiled.mir);
48
+ templates.push({
49
+ segments: template.segments,
50
+ sourceId: agentSourceId(input.sourceId, index)
51
+ });
52
+ }
53
+ const scripts = compileHostScripts(frontend, frontendResult.program, options, hirResult.nextBindingId, hirResult.nextFunctionId, hirResult.program.hostScriptSources ?? []);
54
+ return {
55
+ agents,
56
+ diagnostics: [],
57
+ hir: hirResult.program,
58
+ mir: {
59
+ ...mir,
60
+ functions: [...mir.functions, ...scripts.functions],
61
+ globalBindings: [...mir.globalBindings, ...scripts.globals],
62
+ hostObjectBindings: scripts.objects,
63
+ test262Host: {
64
+ agents: templates,
65
+ mainAgentCanBlock: options.mainAgentCanBlock ?? true,
66
+ scripts: scripts.scripts
67
+ }
68
+ },
69
+ syntax: frontendResult.program
70
+ };
71
+ }
72
+
73
+ //#endregion
74
+ export { compileSource };
75
+ //# sourceMappingURL=compile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile.js","names":[],"sources":["../src/compile.ts"],"sourcesContent":["import { 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":";;;;;;;;;;;;;;;;;;AAuBA,SAAgB,cACd,UACA,OACA,UAA2B,CAAC,GAC5B,UACmB;CACnB,MAAM,iBAAiB,SAAS,MAAM,KAAK;CAC3C,IAAI,eAAe,WAA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A,QAAQ,eAAe;CACzB;AACF"}
@@ -0,0 +1,72 @@
1
+ import { Diagnostic, SourceInput } from "./source.js";
2
+ import { SourceFrontend } from "./syntax.js";
3
+ import { HirProgram } from "./hir.js";
4
+ import { CompilerOptions, MirProgram } from "./mir.js";
5
+ //#region src/fragments.d.ts
6
+ /** Private fragment contract; changes invalidate generated object reuse. */
7
+ declare const scriptFragmentAbi = "oseo-script-fragments-v1";
8
+ /** A Script binding exported to a later fragment in the same environment. */
9
+ interface FragmentBinding {
10
+ readonly id: number;
11
+ readonly name: string;
12
+ readonly mutable: boolean;
13
+ readonly globalObject: boolean;
14
+ }
15
+ /**
16
+ * Independently lowered unit, not a standalone executable MirProgram.
17
+ * The launcher owns instantiation and supplies the shared environment.
18
+ */
19
+ interface ScriptFragment {
20
+ readonly hir: HirProgram;
21
+ readonly mir: MirProgram;
22
+ /** Exclusive limits include hidden bindings and all nested functions. */
23
+ readonly nextBindingId: number;
24
+ readonly nextFunctionId: number;
25
+ /** HIR body indices owned by launcher instantiation, not evaluation. */
26
+ readonly launcherInitializers: readonly number[];
27
+ }
28
+ /** Prepared ordered bundle. No body input contributes to these bytes. */
29
+ interface HarnessFragment extends ScriptFragment {
30
+ readonly abi: typeof scriptFragmentAbi;
31
+ readonly sources: readonly SourceInput[];
32
+ readonly bindings: readonly FragmentBinding[];
33
+ readonly globalReferences: readonly string[];
34
+ readonly strict: boolean;
35
+ readonly options: CompilerOptions;
36
+ }
37
+ /** A failed preparation must use the existing whole-Script path. */
38
+ type HarnessFragmentResult = {
39
+ readonly kind: "compiled";
40
+ readonly harness: HarnessFragment;
41
+ } | {
42
+ readonly kind: "fallback";
43
+ readonly diagnostics: readonly Diagnostic[];
44
+ };
45
+ /** A body is either compatible with a prepared bundle or requires fallback. */
46
+ type BodyFragmentResult = {
47
+ readonly kind: "compiled";
48
+ readonly body: ScriptFragment;
49
+ readonly bindingCount: number;
50
+ } | {
51
+ readonly kind: "fallback";
52
+ readonly reason: "diagnostic" | "shadowing" | "strictness" | "metadata" | "global-effects" | "requests";
53
+ readonly names: readonly string[];
54
+ readonly diagnostics: readonly Diagnostic[];
55
+ };
56
+ /**
57
+ * Compile an ordered bundle once, reserving every ID before any case resolves.
58
+ * Source order and duplicates are significant. Locations use the fixed virtual
59
+ * bundle source; native emission must supply the launcher's logical source map.
60
+ */
61
+ declare function compileHarnessFragment(frontend: SourceFrontend, sources: readonly SourceInput[], strict?: boolean, options?: CompilerOptions): HarnessFragmentResult;
62
+ /**
63
+ * Resolve a case against a prepared harness without mutating the harness.
64
+ * Fallback is an instruction to compile the original assembled Script, not a
65
+ * replacement diagnostic. Module/raw admission belongs to the future runner.
66
+ */
67
+ declare function compileBodyFragment(frontend: SourceFrontend, harness: HarnessFragment, input: SourceInput): BodyFragmentResult;
68
+ /** Separate launcher-owned initialization from ordered evaluation in MIR. */
69
+ declare function lowerFragmentPhases(unit: ScriptFragment): readonly [MirProgram, MirProgram];
70
+ //#endregion
71
+ export { BodyFragmentResult, FragmentBinding, HarnessFragment, HarnessFragmentResult, ScriptFragment, compileBodyFragment, compileHarnessFragment, lowerFragmentPhases, scriptFragmentAbi };
72
+ //# sourceMappingURL=fragments.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fragments.d.ts","names":[],"sources":["../src/fragments.ts"],"mappings":";;;;;;cAQa;;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"}