@oseo/backend-c 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.
- package/LICENSE +674 -0
- package/MIT-LICENSE.txt +21 -0
- package/README.md +146 -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 +1309 -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
|
|
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,147 @@
|
|
|
1
|
-
|
|
1
|
+
@oseo/backend-c
|
|
2
|
+
===============
|
|
2
3
|
|
|
3
|
-
This
|
|
4
|
+
This package emits deterministic C11 source from backend-neutral MIR. It
|
|
5
|
+
preserves generic and dynamic calls, receivers, constructors, explicit abrupt
|
|
6
|
+
completion, guarded operations, root frames, and safepoint locations. It does
|
|
7
|
+
not execute a compiler or choose runtime sources. MIR blocks and terminators are
|
|
8
|
+
its only semantic input; it never replays HIR.
|
|
9
|
+
|
|
10
|
+
The backend logic is under GPL-3.0-or-later. The Oseo-authored C templates
|
|
11
|
+
and support they contribute to output are under MIT; see *MIT-LICENSE.txt*.
|
|
12
|
+
Generated C includes the applicable notices without licensing the user's
|
|
13
|
+
program under MIT or GPL.
|
|
14
|
+
|
|
15
|
+
Lexical bindings use traced environments and shared cells. Their values remain
|
|
16
|
+
rooted across calls and collection.
|
|
17
|
+
|
|
18
|
+
Binding reads, property-key conversion, and ordinary property gets use
|
|
19
|
+
statically selected native helpers from the runtime archive. Their call-site
|
|
20
|
+
records carry root indices and source positions, so each generated program
|
|
21
|
+
compiles fewer operand loads and result stores. The helpers perform the same
|
|
22
|
+
runtime calls and root stores. MIR still owns guards and abrupt routing.
|
|
23
|
+
Fragment emission retains its dynamically relocated source-location call.
|
|
24
|
+
|
|
25
|
+
Only functions reachable from the script and blocks reachable from function
|
|
26
|
+
entry are emitted. Self-recursive calls use a standard C volatile function
|
|
27
|
+
pointer so strict warning settings do not reject valid recursion.
|
|
28
|
+
|
|
29
|
+
Every declared-function call enters the runtime call-depth budget before the
|
|
30
|
+
callee enters generated C. The call leaves the budget while unwinding either a
|
|
31
|
+
normal or abrupt result. Generated root slots and call-argument scratch slots
|
|
32
|
+
use a heap-backed root frame instead of a variable-sized C stack array.
|
|
33
|
+
|
|
34
|
+
The backend also charges each entry against the runtime's active root-slot
|
|
35
|
+
budget before entering generated C. A wide function therefore cannot exhaust
|
|
36
|
+
the process stack before an owned resource diagnostic is possible. Script
|
|
37
|
+
entries charge dense value slots plus binding-access calls separately from heap
|
|
38
|
+
allocation. Non-recursive generated expression temporaries can also exhaust C
|
|
39
|
+
stack space.
|
|
40
|
+
|
|
41
|
+
UTF-16 string-constant units use static read-only storage rather than automatic
|
|
42
|
+
compound literals, so source literal size does not enlarge a generated stack
|
|
43
|
+
frame.
|
|
44
|
+
|
|
45
|
+
Large bodies run through bounded native helpers that return continuation
|
|
46
|
+
indices to an iterative owner. The owner retains roots, completion records,
|
|
47
|
+
and scalar state across helper calls. Static data keeps one identity, and
|
|
48
|
+
normal or abrupt completion releases the owner's root frame exactly once.
|
|
49
|
+
This preserves the existing logical frame charge and 65,536-unit ceiling.
|
|
50
|
+
|
|
51
|
+
The backend also supplies optional compilation units for large programs. Each
|
|
52
|
+
wrapper selects a bounded group of definitions from the standalone C source.
|
|
53
|
+
Native composition stages and compiles these wrappers through the toolchain's
|
|
54
|
+
existing multiple-source contract, without cross-unit LTO. This bounds compiler
|
|
55
|
+
IR retention as well as individual execution bodies. Splitting functions inside
|
|
56
|
+
one translation unit alone is insufficient for unoptimized sanitizer builds.
|
|
57
|
+
The standalone source remains available for inspection and direct C emission.
|
|
58
|
+
|
|
59
|
+
Function creation passes MIR-owned UTF-16 names and plain parameter counts to
|
|
60
|
+
the runtime. It does not consult HIR or source syntax.
|
|
61
|
+
|
|
62
|
+
Value-slot discovery scans MIR argument IDs iteratively, so source-level call
|
|
63
|
+
size does not become a JavaScript call-stack limit during C emission. Generated
|
|
64
|
+
entry code passes diagnostic source identifiers with their UTF-8 byte lengths.
|
|
65
|
+
|
|
66
|
+
M2 guard failures and checked-addition overflow branch to the same emitted
|
|
67
|
+
generic addition block. The hit path uses private inline runtime primitives and
|
|
68
|
+
does not call generic addition or allocate. Block parameters carry the selected
|
|
69
|
+
result into one ordinary continuation.
|
|
70
|
+
|
|
71
|
+
M3 named property reads likewise preserve MIR-owned object and shape guards, a
|
|
72
|
+
fixed-slot hit, one generic fallback, and a block-parameter join. The runtime
|
|
73
|
+
exposes only private cache tests, fixed-slot loads, and cache updates to the C
|
|
74
|
+
backend. A named cache belongs to one static key site, so its hit path does not
|
|
75
|
+
allocate or materialize the property key.
|
|
76
|
+
|
|
77
|
+
Pending throws carry their diagnostic location and message through generated
|
|
78
|
+
completion slots, so intervening `finally` operations cannot overwrite an
|
|
79
|
+
unhandled exception's report.
|
|
80
|
+
|
|
81
|
+
Iterator operations keep the iterator, captured next method, and yielded value
|
|
82
|
+
in distinct root slots. Generated close blocks consult the stored completion
|
|
83
|
+
kind so `IteratorClose` preserves the required throw precedence.
|
|
84
|
+
|
|
85
|
+
Dynamic array accumulation emits runtime value and hole append operations.
|
|
86
|
+
Array spread steps its captured iterator method in MIR control-flow blocks and
|
|
87
|
+
returns abrupt acquisition, step, and append results without synthesizing a
|
|
88
|
+
close block.
|
|
89
|
+
|
|
90
|
+
Call and constructor spread use the same iterator control flow while appending
|
|
91
|
+
values to a GC-traced argument list. Generated invocations borrow the list count
|
|
92
|
+
and stable value pointer only for the call. Fixed-arity paths keep their
|
|
93
|
+
positional arguments.
|
|
94
|
+
|
|
95
|
+
Array binding lowering associates iterator get, next, and close operations with
|
|
96
|
+
a backend-local done bit. Exhaustion suppresses later steps and close calls.
|
|
97
|
+
Generated cleanup blocks close only a still-open iterator and preserve an
|
|
98
|
+
in-flight throw over a close failure.
|
|
99
|
+
|
|
100
|
+
Object binding lowering emits the MIR-owned coercibility check before computed
|
|
101
|
+
keys, then uses the existing property-key and generic property-read operations.
|
|
102
|
+
Nested patterns reuse the same binding targets and abrupt-completion path.
|
|
103
|
+
|
|
104
|
+
Catch parameter lowering captures the pending thrown value and resets every
|
|
105
|
+
catch cell. It runs the same recursive binding path before entering the body.
|
|
106
|
+
Pattern failures retain iterator cleanup and continue through an enclosing
|
|
107
|
+
`finally`.
|
|
108
|
+
|
|
109
|
+
`for-of` declaration patterns reuse that binding path after each outer iterator
|
|
110
|
+
step. Generated code resets lexical cells per iteration and writes hoisted `var`
|
|
111
|
+
cells in place. When initialization fails, generated code closes nested
|
|
112
|
+
iterators before the outer iterator.
|
|
113
|
+
|
|
114
|
+
`for-of` assignment patterns reuse the existing-target path after each outer
|
|
115
|
+
step. They add no target cells. A checked identifier or member write failure
|
|
116
|
+
closes nested pattern iterators before the outer iterator.
|
|
117
|
+
|
|
118
|
+
Standalone destructuring assignment reuses the same recursive path. That path
|
|
119
|
+
includes checked writes to existing identifier cells and property writes
|
|
120
|
+
through member references evaluated before the corresponding source value.
|
|
121
|
+
Generated code preserves the original right-hand value as the expression
|
|
122
|
+
result. It routes an immutable, imported, member-reference, or member-write
|
|
123
|
+
failure through every active array-pattern close block.
|
|
124
|
+
|
|
125
|
+
Compound assignment emits the existing binding or property read, binary
|
|
126
|
+
operation, and checked write sequence against one retained reference. Logical
|
|
127
|
+
forms branch before emitting the right operand and write. They preserve the
|
|
128
|
+
current value on the short path without adding a runtime ABI operation.
|
|
129
|
+
|
|
130
|
+
Update expressions emit the same checked binding or member read and write
|
|
131
|
+
operations around numeric coercion and arithmetic by one. A postfix form keeps
|
|
132
|
+
the coerced previous value in its root slot across the write. A prefix form
|
|
133
|
+
returns the assigned value. Member forms retain one object and raw key
|
|
134
|
+
evaluation but emit separate property-key conversions for the read and write. A
|
|
135
|
+
nullish-base check precedes those conversions.
|
|
136
|
+
|
|
137
|
+
M4 whole-graph programs allocate shared module cells and namespaces before
|
|
138
|
+
executing dependency-ordered bodies. Generated functions register one shared
|
|
139
|
+
code-identity dispatcher used by dynamic calls, promise executors, reactions,
|
|
140
|
+
and asynchronous continuations. Promise, timer, and top-level await MIR targets
|
|
141
|
+
remain runtime calls, so generated C does not own job queues or scheduler
|
|
142
|
+
policy.
|
|
143
|
+
|
|
144
|
+
Guaranteed-rejected frames use a C preprocessor branch to omit their bodies
|
|
145
|
+
before sanitizer IR construction. Entry points retain their runtime charge.
|
|
146
|
+
Callable charges use `OSEO_CALLABLE_FRAME_COST`, whose multiplier is supplied
|
|
147
|
+
by the toolchain; scripts retain their compact-root and binding-access charge.
|
|
@@ -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":";;cAOa;;;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":["// 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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