@oseo/backend-c 0.0.0-stage → 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/LICENSE +674 -0
- package/MIT-LICENSE.txt +21 -0
- package/README.md +58 -2
- package/dist/bounded-body.d.ts +28 -0
- package/dist/bounded-body.d.ts.map +1 -0
- package/dist/bounded-body.js +198 -0
- package/dist/bounded-body.js.map +1 -0
- package/dist/emitted-c.d.ts +676 -0
- package/dist/emitted-c.d.ts.map +1 -0
- package/dist/emitted-c.js +1331 -0
- package/dist/emitted-c.js.map +1 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2282 -0
- package/dist/index.js.map +1 -0
- package/dist/regexp-program.d.ts +64 -0
- package/dist/regexp-program.d.ts.map +1 -0
- package/dist/regexp-program.js +357 -0
- package/dist/regexp-program.js.map +1 -0
- package/package.json +36 -3
package/MIT-LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hong Minhee <https://hongminhee.org/>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,59 @@
|
|
|
1
|
-
|
|
1
|
+
`@oseo/backend-c`
|
|
2
|
+
=================
|
|
2
3
|
|
|
3
|
-
|
|
4
|
+
`@oseo/backend-c` emits deterministic C11 from Oseo's mid-level intermediate
|
|
5
|
+
representation (MIR). It does not parse JavaScript, choose runtime inputs, or
|
|
6
|
+
invoke a C compiler. If you only want to inspect the C for a JavaScript or
|
|
7
|
+
TypeScript file, run `oseo build FILE --emit-c` with the [Oseo CLI].
|
|
8
|
+
|
|
9
|
+
[Oseo CLI]: https://github.com/dahlia/oseo/blob/main/docs/using/cli.md
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
Emit C from MIR
|
|
13
|
+
---------------
|
|
14
|
+
|
|
15
|
+
If you already have a `MirProgram` from [`@oseo/compiler`], install the
|
|
16
|
+
backend:
|
|
17
|
+
|
|
18
|
+
~~~~ sh
|
|
19
|
+
npm install @oseo/backend-c
|
|
20
|
+
~~~~
|
|
21
|
+
|
|
22
|
+
Or, in a Deno project:
|
|
23
|
+
|
|
24
|
+
~~~~ sh
|
|
25
|
+
deno add jsr:@oseo/backend-c
|
|
26
|
+
~~~~
|
|
27
|
+
|
|
28
|
+
~~~~ js
|
|
29
|
+
import { cBackend } from "@oseo/backend-c";
|
|
30
|
+
|
|
31
|
+
const output = cBackend.emit(mir);
|
|
32
|
+
console.log(output.source);
|
|
33
|
+
~~~~
|
|
34
|
+
|
|
35
|
+
`output.source` is the standalone C translation unit. To build an executable,
|
|
36
|
+
compile the generated C and link it with the matching [Oseo C runtime]. If
|
|
37
|
+
`output.compilationUnits` is present, compile those files instead of the
|
|
38
|
+
standalone file and keep it beside them under `output.sourceName` for their
|
|
39
|
+
includes.
|
|
40
|
+
The [Oseo CLI] handles these steps for you. See the
|
|
41
|
+
[backend implementation notes] for how the emitter bounds native stack and
|
|
42
|
+
compiler memory use.
|
|
43
|
+
|
|
44
|
+
[`@oseo/compiler`]: https://github.com/dahlia/oseo/tree/main/packages/compiler
|
|
45
|
+
[Oseo C runtime]: https://github.com/dahlia/oseo/tree/main/packages/runtime-c
|
|
46
|
+
[backend implementation notes]: https://github.com/dahlia/oseo/blob/main/docs/development/package-backend-c.md
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
License
|
|
50
|
+
-------
|
|
51
|
+
|
|
52
|
+
The backend logic is licensed under GPL-3.0-or-later. The Oseo-authored C
|
|
53
|
+
templates and support that the backend contributes to its output are
|
|
54
|
+
[MIT-licensed]. The output includes the applicable notices; it does not put
|
|
55
|
+
your program under either license. See the [runtime linking decision] for
|
|
56
|
+
the separate terms that apply when the Oseo runtime is linked in.
|
|
57
|
+
|
|
58
|
+
[MIT-licensed]: https://github.com/dahlia/oseo/blob/main/packages/backend-c/MIT-LICENSE.txt
|
|
59
|
+
[runtime linking decision]: https://github.com/dahlia/oseo/blob/main/docs/adr/0021-runtime-linking-exception.md
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
//#region src/bounded-body.d.ts
|
|
2
|
+
/** Keep compiler IR retention bounded across many outlined helpers. */
|
|
3
|
+
declare class BodyUnits {
|
|
4
|
+
#private;
|
|
5
|
+
/** Assign consecutive definitions to bounded compiler translation units. */
|
|
6
|
+
assign(bytes: number): number;
|
|
7
|
+
/** Number of supplemental compiler units, excluding the launcher. */
|
|
8
|
+
get count(): number;
|
|
9
|
+
}
|
|
10
|
+
/** Standalone emission includes everything; build wrappers select one unit. */
|
|
11
|
+
declare function bodyUnit(source: string, unit: number): string;
|
|
12
|
+
/** The owner retains roots and completion storage across outlined calls. */
|
|
13
|
+
interface BoundedBody {
|
|
14
|
+
readonly declarations: string;
|
|
15
|
+
readonly execution: string;
|
|
16
|
+
}
|
|
17
|
+
/** Apply replacements only to syntax, preserving bytes inside C literals. */
|
|
18
|
+
declare function replaceSyntax(source: string, pattern: RegExp, replacement: (...groups: string[]) => string): string;
|
|
19
|
+
/**
|
|
20
|
+
* Outline large generated bodies without adding language calls or roots.
|
|
21
|
+
* Helpers return a continuation index to an iterative owner. Every automatic
|
|
22
|
+
* scalar lives in that owner's state, and static data keeps one identity.
|
|
23
|
+
* Only backend-produced C is inspected; no user source is parsed here.
|
|
24
|
+
*/
|
|
25
|
+
declare function boundBody(lines: readonly string[], name: string, frameCost: string, generator: boolean, usesCompletion: boolean, units?: BodyUnits, ownerUnit?: number): BoundedBody | undefined;
|
|
26
|
+
//#endregion
|
|
27
|
+
export { BodyUnits, BoundedBody, bodyUnit, boundBody, replaceSyntax };
|
|
28
|
+
//# sourceMappingURL=bounded-body.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bounded-body.d.ts","names":[],"sources":["../src/bounded-body.ts"],"mappings":";;cA6Ba;;;EAKX,OAAO;;MAUH;;;iBAMU,SAAS,gBAAgB;;UASxB;WACN;WACA;;;iBAYK,cACd,gBACA,SAAS,QACT,iBAAiB;;;;;;;iBAmBH,UACd,0BACA,cACA,mBACA,oBACA,yBACA,QAAQ,WACR,qBACC"}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
//#region src/bounded-body.ts
|
|
2
|
+
/** Maximum executable C text assigned to one outlined native helper. */
|
|
3
|
+
const chunkBytes = 16384;
|
|
4
|
+
/** Keep compiler IR retention bounded across many outlined helpers. */
|
|
5
|
+
var BodyUnits = class {
|
|
6
|
+
#unit = 1;
|
|
7
|
+
#bytes = 0;
|
|
8
|
+
/** Assign consecutive definitions to bounded compiler translation units. */
|
|
9
|
+
assign(bytes) {
|
|
10
|
+
if (this.#bytes + bytes > 262144 && this.#bytes > 0) {
|
|
11
|
+
this.#unit += 1;
|
|
12
|
+
this.#bytes = 0;
|
|
13
|
+
}
|
|
14
|
+
this.#bytes += bytes;
|
|
15
|
+
return this.#unit;
|
|
16
|
+
}
|
|
17
|
+
/** Number of supplemental compiler units, excluding the launcher. */
|
|
18
|
+
get count() {
|
|
19
|
+
return this.#unit;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
/** Standalone emission includes everything; build wrappers select one unit. */
|
|
23
|
+
function bodyUnit(source, unit) {
|
|
24
|
+
return `#if !defined(OSEO_C_BODY_UNIT) || OSEO_C_BODY_UNIT == ${unit}\n` + source + "\n#endif\n";
|
|
25
|
+
}
|
|
26
|
+
/** Mask literals before inspecting the backend's own generated C syntax. */
|
|
27
|
+
function syntax(source) {
|
|
28
|
+
return source.replace(/"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'/gu, (literal) => " ".repeat(literal.length));
|
|
29
|
+
}
|
|
30
|
+
/** Apply replacements only to syntax, preserving bytes inside C literals. */
|
|
31
|
+
function replaceSyntax(source, pattern, replacement) {
|
|
32
|
+
const masked = syntax(source);
|
|
33
|
+
let result = "";
|
|
34
|
+
let start = 0;
|
|
35
|
+
for (const match of masked.matchAll(pattern)) {
|
|
36
|
+
result += source.slice(start, match.index);
|
|
37
|
+
result += replacement(...match.slice(1));
|
|
38
|
+
start = match.index + match[0].length;
|
|
39
|
+
}
|
|
40
|
+
return result + source.slice(start);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Outline large generated bodies without adding language calls or roots.
|
|
44
|
+
* Helpers return a continuation index to an iterative owner. Every automatic
|
|
45
|
+
* scalar lives in that owner's state, and static data keeps one identity.
|
|
46
|
+
* Only backend-produced C is inspected; no user source is parsed here.
|
|
47
|
+
*/
|
|
48
|
+
function boundBody(lines, name, frameCost, generator, usesCompletion, units, ownerUnit = 0) {
|
|
49
|
+
if (lines.reduce((size, line) => size + line.length, 0) <= chunkBytes) return;
|
|
50
|
+
const statements = [];
|
|
51
|
+
let depth = 0;
|
|
52
|
+
let pending = [];
|
|
53
|
+
for (const line of lines) {
|
|
54
|
+
pending.push(line);
|
|
55
|
+
const masked = syntax(line);
|
|
56
|
+
for (const character of masked) {
|
|
57
|
+
if (character === "{") depth += 1;
|
|
58
|
+
if (character === "}") depth -= 1;
|
|
59
|
+
}
|
|
60
|
+
if (depth === 0) {
|
|
61
|
+
statements.push(pending.join("\n"));
|
|
62
|
+
pending = [];
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (depth !== 0 || pending.length !== 0) throw new Error("Generated C body has unbalanced statement scopes.");
|
|
66
|
+
const fields = /* @__PURE__ */ new Map();
|
|
67
|
+
const statics = [];
|
|
68
|
+
const staticNames = [];
|
|
69
|
+
const chunks = [[]];
|
|
70
|
+
const labels = /* @__PURE__ */ new Map();
|
|
71
|
+
let bytes = 0;
|
|
72
|
+
for (let unit of statements) {
|
|
73
|
+
const masked = syntax(unit);
|
|
74
|
+
if (/^\s*static\s/u.test(masked)) {
|
|
75
|
+
const identifier = masked.match(/^\s*static\s+(?:const\s+)?\w+\s*(?:\*\s*const\s*)?(\w+)\s*(?:\[|=)/u)?.[1];
|
|
76
|
+
if (identifier == null) throw new Error("Generated static data has no owned identifier.");
|
|
77
|
+
staticNames.push(identifier);
|
|
78
|
+
statics.push(unit);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
const label = masked.match(/^\s*(bb\d+|abrupt):;?\s*$/u)?.[1];
|
|
82
|
+
if (label != null) {
|
|
83
|
+
if (chunks.at(-1).length > 0) chunks.push([]);
|
|
84
|
+
labels.set(label, chunks.length - 1);
|
|
85
|
+
bytes = 0;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
unit = replaceSyntax(unit, /* @__PURE__ */ new RegExp("\\b((?:bool|int64_t|size_t|OseoFunctionEntry\\s+volatile)\\s+|const OseoValue\\s*\\*\\s*)(\\w+)", "gu"), (type, identifier) => {
|
|
89
|
+
fields.set(identifier, type.trim());
|
|
90
|
+
return identifier;
|
|
91
|
+
});
|
|
92
|
+
unit = replaceSyntax(unit, /^\s*(fast_\d+);$/gu, (identifier) => ` (void)${identifier};`);
|
|
93
|
+
unit = replaceSyntax(unit, /\boseo_roots_release\(context, &frame\);/gu, () => "");
|
|
94
|
+
if (bytes + unit.length > chunkBytes && chunks.at(-1).length > 0) {
|
|
95
|
+
chunks.push([]);
|
|
96
|
+
bytes = 0;
|
|
97
|
+
}
|
|
98
|
+
chunks.at(-1).push(unit);
|
|
99
|
+
bytes += unit.length;
|
|
100
|
+
}
|
|
101
|
+
const typeName = `${name}_state`;
|
|
102
|
+
const shared = [
|
|
103
|
+
"roots",
|
|
104
|
+
"result",
|
|
105
|
+
"callee",
|
|
106
|
+
"receiver",
|
|
107
|
+
"argument_count",
|
|
108
|
+
"arguments",
|
|
109
|
+
"new_target",
|
|
110
|
+
"generator",
|
|
111
|
+
"completion"
|
|
112
|
+
];
|
|
113
|
+
const aliases = [
|
|
114
|
+
...shared.map((field) => `#define ${field} (body->${field})`),
|
|
115
|
+
"#define frame (*body->frame)",
|
|
116
|
+
...[...fields.keys()].map((field) => `#define ${field} (body->${field})`),
|
|
117
|
+
...staticNames.map((field) => `#define ${field} ${name}_${field}`)
|
|
118
|
+
];
|
|
119
|
+
const helpers = chunks.map((chunk, index) => {
|
|
120
|
+
let source = chunk.join("\n");
|
|
121
|
+
source = replaceSyntax(source, /\bgoto\s+(bb\d+|abrupt);/gu, (label) => {
|
|
122
|
+
const target = labels.get(label);
|
|
123
|
+
if (target == null) throw new Error(`Missing C label ${label}.`);
|
|
124
|
+
return `return ${target}u;`;
|
|
125
|
+
});
|
|
126
|
+
source = replaceSyntax(source, /\breturn result;/gu, () => "return SIZE_MAX;");
|
|
127
|
+
const helper = `${units == null ? "static " : ""}size_t ${name}_${index}(
|
|
128
|
+
OseoContext *context, ${typeName} *body
|
|
129
|
+
) {
|
|
130
|
+
(void)context;
|
|
131
|
+
(void)body;
|
|
132
|
+
${source}
|
|
133
|
+
return ${index + 1 < chunks.length ? `${index + 1}u` : "SIZE_MAX"};
|
|
134
|
+
}`;
|
|
135
|
+
return units == null ? helper : bodyUnit(helper, units.assign(source.length));
|
|
136
|
+
});
|
|
137
|
+
const staticData = statics.map((source) => {
|
|
138
|
+
if (units == null) return source;
|
|
139
|
+
const equals = syntax(source).indexOf("=");
|
|
140
|
+
const declaration = source.slice(0, equals).replace(/\bstatic\s/u, "extern ");
|
|
141
|
+
return `#if !defined(OSEO_C_BODY_UNIT) || OSEO_C_BODY_UNIT == ${ownerUnit}
|
|
142
|
+
${source.replace(/\bstatic\s/u, "")}
|
|
143
|
+
#else
|
|
144
|
+
${declaration};
|
|
145
|
+
#endif`;
|
|
146
|
+
});
|
|
147
|
+
const table = `static size_t (*const ${name}_chunks[])(
|
|
148
|
+
OseoContext *, ${typeName} *
|
|
149
|
+
) = {
|
|
150
|
+
${chunks.map((_, index) => ` ${name}_${index},`).join("\n")}
|
|
151
|
+
};`;
|
|
152
|
+
return {
|
|
153
|
+
declarations: `#if ${frameCost} <= OSEO_MAX_ACTIVE_FRAME_SLOTS
|
|
154
|
+
typedef struct {
|
|
155
|
+
OseoRootFrame *frame;
|
|
156
|
+
OseoValue *roots;
|
|
157
|
+
OseoResult result;
|
|
158
|
+
OseoValue callee, receiver, new_target, generator;
|
|
159
|
+
size_t argument_count;
|
|
160
|
+
const OseoValue *arguments;
|
|
161
|
+
OseoCompletionRecord *completion;
|
|
162
|
+
${[...fields].map(([field, type]) => ` ${type} ${field};`).join("\n")}
|
|
163
|
+
} ${typeName};
|
|
164
|
+
${aliases.join("\n")}
|
|
165
|
+
${staticData.join("\n")}
|
|
166
|
+
${units == null ? "" : chunks.map((_, index) => `size_t ${name}_${index}(OseoContext *, ${typeName} *);`).join("\n")}
|
|
167
|
+
${helpers.join("\n")}
|
|
168
|
+
${[
|
|
169
|
+
...shared,
|
|
170
|
+
"frame",
|
|
171
|
+
...fields.keys(),
|
|
172
|
+
...staticNames
|
|
173
|
+
].map((field) => `#undef ${field}`).join("\n")}
|
|
174
|
+
${units == null ? table : bodyUnit(table, ownerUnit)}
|
|
175
|
+
#endif
|
|
176
|
+
`,
|
|
177
|
+
execution: ` ${typeName} body = {
|
|
178
|
+
.frame = ${generator ? "NULL" : "&frame"},
|
|
179
|
+
.roots = roots, .result = result,
|
|
180
|
+
.callee = callee, .receiver = receiver,
|
|
181
|
+
.argument_count = ${generator ? "0u" : "argument_count"},
|
|
182
|
+
.arguments = ${generator ? "NULL" : "arguments"},
|
|
183
|
+
.new_target = ${generator ? "oseo_undefined()" : "new_target"},
|
|
184
|
+
.generator = ${generator ? "generator" : "oseo_undefined()"},
|
|
185
|
+
.completion = ${usesCompletion ? "completion" : "NULL"}
|
|
186
|
+
};
|
|
187
|
+
size_t continuation = 0u;
|
|
188
|
+
while (continuation != SIZE_MAX) {
|
|
189
|
+
continuation = ${name}_chunks[continuation](context, &body);
|
|
190
|
+
}
|
|
191
|
+
${generator ? "" : " oseo_roots_release(context, &frame);\n"} return body.result;
|
|
192
|
+
`
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
//#endregion
|
|
197
|
+
export { BodyUnits, bodyUnit, boundBody, replaceSyntax };
|
|
198
|
+
//# sourceMappingURL=bounded-body.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bounded-body.js","names":["#bytes","#unit"],"sources":["../src/bounded-body.ts"],"sourcesContent":["/*\n * Oseo, an ahead-of-time compiler for JavaScript and TypeScript.\n * Copyright (C) 2026 Hong Minhee <https://hongminhee.org/>\n *\n * The fixed C templates incorporated into compiled programs are under\n * the MIT license. The GPL notice covers the surrounding code. See\n * docs/runtime-support-surface.md for the licensing boundary.\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\n// Fixed C output templates in this file are MIT (../MIT-LICENSE.txt).\n// Compiler logic is GPL-3.0-or-later (../LICENSE).\n\n/** Maximum executable C text assigned to one outlined native helper. */\nconst chunkBytes = 16_384;\n\n/** Keep compiler IR retention bounded across many outlined helpers. */\nexport class BodyUnits {\n #unit = 1;\n #bytes = 0;\n\n /** Assign consecutive definitions to bounded compiler translation units. */\n assign(bytes: number): number {\n if (this.#bytes + bytes > 262_144 && this.#bytes > 0) {\n this.#unit += 1;\n this.#bytes = 0;\n }\n this.#bytes += bytes;\n return this.#unit;\n }\n\n /** Number of supplemental compiler units, excluding the launcher. */\n get count(): number {\n return this.#unit;\n }\n}\n\n/** Standalone emission includes everything; build wrappers select one unit. */\nexport function bodyUnit(source: string, unit: number): string {\n return (\n `#if !defined(OSEO_C_BODY_UNIT) || OSEO_C_BODY_UNIT == ${unit}\\n` +\n source +\n \"\\n#endif\\n\"\n );\n}\n\n/** The owner retains roots and completion storage across outlined calls. */\nexport interface BoundedBody {\n readonly declarations: string;\n readonly execution: string;\n}\n\n/** Mask literals before inspecting the backend's own generated C syntax. */\nfunction syntax(source: string): string {\n return source.replace(\n /\"(?:\\\\[\\s\\S]|[^\"\\\\])*\"|'(?:\\\\[\\s\\S]|[^'\\\\])*'/gu,\n (literal) => \" \".repeat(literal.length),\n );\n}\n\n/** Apply replacements only to syntax, preserving bytes inside C literals. */\nexport function replaceSyntax(\n source: string,\n pattern: RegExp,\n replacement: (...groups: string[]) => string,\n): string {\n const masked = syntax(source);\n let result = \"\";\n let start = 0;\n for (const match of masked.matchAll(pattern)) {\n result += source.slice(start, match.index);\n result += replacement(...match.slice(1));\n start = match.index + match[0].length;\n }\n return result + source.slice(start);\n}\n\n/**\n * Outline large generated bodies without adding language calls or roots.\n * Helpers return a continuation index to an iterative owner. Every automatic\n * scalar lives in that owner's state, and static data keeps one identity.\n * Only backend-produced C is inspected; no user source is parsed here.\n */\nexport function boundBody(\n lines: readonly string[],\n name: string,\n frameCost: string,\n generator: boolean,\n usesCompletion: boolean,\n units?: BodyUnits,\n ownerUnit = 0,\n): BoundedBody | undefined {\n if (lines.reduce((size, line) => size + line.length, 0) <= chunkBytes) {\n return undefined;\n }\n const statements: string[] = [];\n let depth = 0;\n let pending: string[] = [];\n for (const line of lines) {\n pending.push(line);\n const masked = syntax(line);\n for (const character of masked) {\n if (character === \"{\") depth += 1;\n if (character === \"}\") depth -= 1;\n }\n if (depth === 0) {\n statements.push(pending.join(\"\\n\"));\n pending = [];\n }\n }\n if (depth !== 0 || pending.length !== 0) {\n throw new Error(\"Generated C body has unbalanced statement scopes.\");\n }\n const fields = new Map<string, string>();\n const statics: string[] = [];\n const staticNames: string[] = [];\n const chunks: string[][] = [[]];\n const labels = new Map<string, number>();\n let bytes = 0;\n for (let unit of statements) {\n const masked = syntax(unit);\n if (/^\\s*static\\s/u.test(masked)) {\n const identifier = masked.match(\n /^\\s*static\\s+(?:const\\s+)?\\w+\\s*(?:\\*\\s*const\\s*)?(\\w+)\\s*(?:\\[|=)/u,\n )?.[1];\n if (identifier == null) {\n throw new Error(\"Generated static data has no owned identifier.\");\n }\n staticNames.push(identifier);\n statics.push(unit);\n continue;\n }\n const label = masked.match(/^\\s*(bb\\d+|abrupt):;?\\s*$/u)?.[1];\n if (label != null) {\n if (chunks.at(-1)!.length > 0) chunks.push([]);\n labels.set(label, chunks.length - 1);\n bytes = 0;\n continue;\n }\n unit = replaceSyntax(\n unit,\n new RegExp(\n \"\\\\b((?:bool|int64_t|size_t|OseoFunctionEntry\\\\s+volatile)\\\\s+|\" +\n \"const OseoValue\\\\s*\\\\*\\\\s*)(\\\\w+)\",\n \"gu\",\n ),\n (type, identifier) => {\n fields.set(identifier!, type!.trim());\n return identifier!;\n },\n );\n // A declaration without an initializer becomes a harmless read.\n unit = replaceSyntax(\n unit,\n /^\\s*(fast_\\d+);$/gu,\n (identifier) => ` (void)${identifier};`,\n );\n unit = replaceSyntax(\n unit,\n /\\boseo_roots_release\\(context, &frame\\);/gu,\n () => \"\",\n );\n if (bytes + unit.length > chunkBytes && chunks.at(-1)!.length > 0) {\n chunks.push([]);\n bytes = 0;\n }\n chunks.at(-1)!.push(unit);\n bytes += unit.length;\n }\n const typeName = `${name}_state`;\n const shared = [\n \"roots\",\n \"result\",\n \"callee\",\n \"receiver\",\n \"argument_count\",\n \"arguments\",\n \"new_target\",\n \"generator\",\n \"completion\",\n ];\n const aliases = [\n ...shared.map((field) => `#define ${field} (body->${field})`),\n \"#define frame (*body->frame)\",\n ...[...fields.keys()].map((field) => `#define ${field} (body->${field})`),\n ...staticNames.map((field) => `#define ${field} ${name}_${field}`),\n ];\n const helpers = chunks.map((chunk, index) => {\n let source = chunk.join(\"\\n\");\n source = replaceSyntax(source, /\\bgoto\\s+(bb\\d+|abrupt);/gu, (label) => {\n const target = labels.get(label!);\n if (target == null) throw new Error(`Missing C label ${label}.`);\n return `return ${target}u;`;\n });\n source = replaceSyntax(\n source,\n /\\breturn result;/gu,\n () => \"return SIZE_MAX;\",\n );\n const helper = `${units == null ? \"static \" : \"\"}size_t ${name}_${index}(\n OseoContext *context, ${typeName} *body\n) {\n (void)context;\n (void)body;\n${source}\n return ${index + 1 < chunks.length ? `${index + 1}u` : \"SIZE_MAX\"};\n}`;\n return units == null\n ? helper\n : bodyUnit(helper, units.assign(source.length));\n });\n const staticData = statics.map((source) => {\n if (units == null) return source;\n const masked = syntax(source);\n const equals = masked.indexOf(\"=\");\n const declaration = source\n .slice(0, equals)\n .replace(/\\bstatic\\s/u, \"extern \");\n return `#if !defined(OSEO_C_BODY_UNIT) || OSEO_C_BODY_UNIT == ${ownerUnit}\n${source.replace(/\\bstatic\\s/u, \"\")}\n#else\n${declaration};\n#endif`;\n });\n const table = `static size_t (*const ${name}_chunks[])(\n OseoContext *, ${typeName} *\n) = {\n${chunks.map((_, index) => ` ${name}_${index},`).join(\"\\n\")}\n};`;\n const declarations = `#if ${frameCost} <= OSEO_MAX_ACTIVE_FRAME_SLOTS\ntypedef struct {\n OseoRootFrame *frame;\n OseoValue *roots;\n OseoResult result;\n OseoValue callee, receiver, new_target, generator;\n size_t argument_count;\n const OseoValue *arguments;\n OseoCompletionRecord *completion;\n${[...fields].map(([field, type]) => ` ${type} ${field};`).join(\"\\n\")}\n} ${typeName};\n${aliases.join(\"\\n\")}\n${staticData.join(\"\\n\")}\n${\n units == null\n ? \"\"\n : chunks\n .map(\n (_, index) =>\n `size_t ${name}_${index}(OseoContext *, ${typeName} *);`,\n )\n .join(\"\\n\")\n}\n${helpers.join(\"\\n\")}\n${[...shared, \"frame\", ...fields.keys(), ...staticNames]\n .map((field) => `#undef ${field}`)\n .join(\"\\n\")}\n${units == null ? table : bodyUnit(table, ownerUnit)}\n#endif\n`;\n const release = generator ? \"\" : \" oseo_roots_release(context, &frame);\\n\";\n const execution = ` ${typeName} body = {\n .frame = ${generator ? \"NULL\" : \"&frame\"},\n .roots = roots, .result = result,\n .callee = callee, .receiver = receiver,\n .argument_count = ${generator ? \"0u\" : \"argument_count\"},\n .arguments = ${generator ? \"NULL\" : \"arguments\"},\n .new_target = ${generator ? \"oseo_undefined()\" : \"new_target\"},\n .generator = ${generator ? \"generator\" : \"oseo_undefined()\"},\n .completion = ${usesCompletion ? \"completion\" : \"NULL\"}\n };\n size_t continuation = 0u;\n while (continuation != SIZE_MAX) {\n continuation = ${name}_chunks[continuation](context, &body);\n }\n${release} return body.result;\n`;\n return { declarations, execution };\n}\n"],"mappings":";;AA0BA,MAAM,aAAa;;AAGnB,IAAa,YAAb,MAAuB;CACrB,QAAQ;CACR,SAAS;;CAGT,OAAO,OAAuB;EAC5B,IAAI,KAAKA,SAAS,QAAQ,UAAW,KAAKA,SAAS,GAAG;GACpD,KAAKC,SAAS;GACd,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