@geastack/geatsc-plugin-gea 0.1.6

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 (63) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +37 -0
  3. package/dist/analyze.d.ts +4 -0
  4. package/dist/analyze.js +195 -0
  5. package/dist/cpp-canvas-colors.d.ts +4 -0
  6. package/dist/cpp-canvas-colors.js +226 -0
  7. package/dist/cpp-field-access.d.ts +49 -0
  8. package/dist/cpp-field-access.js +144 -0
  9. package/dist/cpp-ir-dom-style.d.ts +1 -0
  10. package/dist/cpp-ir-dom-style.js +49 -0
  11. package/dist/cpp-ir.d.ts +30 -0
  12. package/dist/cpp-ir.js +2426 -0
  13. package/dist/cpp-keyed-component-diagnostics.d.ts +8 -0
  14. package/dist/cpp-keyed-component-diagnostics.js +74 -0
  15. package/dist/cpp-keyed-list-diagnostics.d.ts +17 -0
  16. package/dist/cpp-keyed-list-diagnostics.js +84 -0
  17. package/dist/cpp-mounted-lowering.d.ts +81 -0
  18. package/dist/cpp-mounted-lowering.js +2235 -0
  19. package/dist/cpp-mounted.d.ts +25 -0
  20. package/dist/cpp-mounted.js +1376 -0
  21. package/dist/cpp-reactive-component-diagnostics.d.ts +2 -0
  22. package/dist/cpp-reactive-component-diagnostics.js +76 -0
  23. package/dist/cpp-reactive-component.d.ts +14 -0
  24. package/dist/cpp-reactive-component.js +349 -0
  25. package/dist/cpp-replacements.d.ts +14 -0
  26. package/dist/cpp-replacements.js +787 -0
  27. package/dist/cpp-source-replacements.d.ts +11 -0
  28. package/dist/cpp-source-replacements.js +257 -0
  29. package/dist/cpp-store-hub.d.ts +7 -0
  30. package/dist/cpp-store-hub.js +160 -0
  31. package/dist/cpp-store-method-body-parser.d.ts +2 -0
  32. package/dist/cpp-store-method-body-parser.js +392 -0
  33. package/dist/cpp-store-method-context.d.ts +48 -0
  34. package/dist/cpp-store-method-context.js +114 -0
  35. package/dist/cpp-store-method-expressions.d.ts +12 -0
  36. package/dist/cpp-store-method-expressions.js +1263 -0
  37. package/dist/cpp-store-method-replacements.d.ts +5 -0
  38. package/dist/cpp-store-method-replacements.js +1521 -0
  39. package/dist/cpp-store-method-targets.d.ts +19 -0
  40. package/dist/cpp-store-method-targets.js +296 -0
  41. package/dist/cpp-store-typed-arrays.d.ts +2 -0
  42. package/dist/cpp-store-typed-arrays.js +655 -0
  43. package/dist/cpp-stores.d.ts +73 -0
  44. package/dist/cpp-stores.js +1739 -0
  45. package/dist/cpp-template-renderer.d.ts +23 -0
  46. package/dist/cpp-template-renderer.js +3530 -0
  47. package/dist/css-style-declaration-shims.d.ts +3 -0
  48. package/dist/css-style-declaration-shims.js +47 -0
  49. package/dist/host-declarations.d.ts +11 -0
  50. package/dist/host-declarations.js +320 -0
  51. package/dist/host-shims.d.ts +3 -0
  52. package/dist/host-shims.js +3217 -0
  53. package/dist/index.d.ts +3 -0
  54. package/dist/index.js +1239 -0
  55. package/dist/load-ir.d.ts +7 -0
  56. package/dist/load-ir.js +40 -0
  57. package/dist/types.d.ts +604 -0
  58. package/dist/types.js +1 -0
  59. package/dist/utils.d.ts +26 -0
  60. package/dist/utils.js +723 -0
  61. package/dist/validate.d.ts +3 -0
  62. package/dist/validate.js +226 -0
  63. package/package.json +57 -0
@@ -0,0 +1,655 @@
1
+ // Source-level rewrite that turns store array fields whose IR shape is
2
+ // `Array<{...primitives...}>` from `std::vector<gea_cpp_value>` storage with
3
+ // dynamic record slots into `std::vector<X_item>` storage with real C++
4
+ // fields. The geatsc emitter (under the gea plugin's allow-any mode) emits
5
+ // the generic `gea_cpp_value`-shaped class skeleton; this pass localises the
6
+ // switch to typed storage to the spots that actually need it (field
7
+ // declaration, constructor seed, `__gea_to_value` getter/setter cast) and
8
+ // leaves the dynamic surface intact for everything else.
9
+ //
10
+ // The `set_array_item_field` lambda inside lowered store methods stays
11
+ // generic and dispatches via `if constexpr (std::is_same_v<Element,
12
+ // gea_cpp_value>)`. The typed branch calls `gea_ir::set_typed_field(slot,
13
+ // property, value)` (emitted per-item-type by `cpp-stores.ts`). Per-property
14
+ // reads via `gea_ir::read_number_field(item, "x")` resolve through typed
15
+ // overloads of the same helper that `cpp-stores.ts` also emits.
16
+ //
17
+ // This is purely a source-substitution pass over the existing geatsc-emitted
18
+ // classes — no app-specific logic. A store/field is eligible when its IR
19
+ // shape is `array<object<all-primitive-fields>>`.
20
+ import { sanitizeCppIdentifier } from './utils.js';
21
+ // Extract an array field's primitive item fields, in order. Returns [] for any
22
+ // shape that isn't `array<object<all-primitive>>` (the only shape eligible for
23
+ // direct field-wise seed construction).
24
+ function primitiveItemFields(field) {
25
+ const shape = field.shape;
26
+ if (!shape || shape.kind !== 'array' || shape.element?.kind !== 'object' || !shape.element.fields)
27
+ return [];
28
+ const out = [];
29
+ for (const f of shape.element.fields) {
30
+ const vt = f.shape?.kind === 'literal' ? f.shape.valueType : undefined;
31
+ if (vt !== 'number' && vt !== 'string' && vt !== 'boolean')
32
+ return [];
33
+ out.push({ name: f.name, valueType: vt });
34
+ }
35
+ return out;
36
+ }
37
+ export function applyTypedArrayStorage(source, ir) {
38
+ const grouped = new Map();
39
+ for (const store of ir.stores) {
40
+ const storeClass = sanitizeCppIdentifier(store.className);
41
+ for (const field of store.fields) {
42
+ if (!field.typedStorage)
43
+ continue;
44
+ const list = grouped.get(storeClass) ?? [];
45
+ const useInterfaceStruct = field.typedStorage.useInterfaceStruct === true;
46
+ list.push({
47
+ storeClass,
48
+ fieldName: sanitizeCppIdentifier(field.name),
49
+ itemType: field.typedStorage.itemType,
50
+ readerName: field.typedStorage.readerName,
51
+ // Interface reuse: geatsc emits `__gea_type_<Name>` at global scope, so
52
+ // the store class field decl names it with a leading `::`. Synthesized:
53
+ // the struct lives in `namespace gea_ir`, so qualify with `gea_ir::`.
54
+ qualifiedItemType: useInterfaceStruct ? `::${field.typedStorage.itemType}` : `gea_ir::${field.typedStorage.itemType}`,
55
+ useInterfaceStruct,
56
+ itemFields: primitiveItemFields(field),
57
+ });
58
+ if (!grouped.has(storeClass))
59
+ grouped.set(storeClass, list);
60
+ }
61
+ }
62
+ if (grouped.size === 0)
63
+ return source;
64
+ let next = source;
65
+ for (const [storeClass, fields] of grouped) {
66
+ next = rewriteClassBody(next, storeClass, (body) => rewriteFieldsInClassBody(body, fields));
67
+ next = rewriteOutOfLineMemberBodies(next, storeClass, (body) => rewriteFieldsInMemberBody(body, fields));
68
+ next = rewriteToValueSetterCast(next, storeClass, fields);
69
+ }
70
+ next = pruneUnusedRecordHelpers(next);
71
+ return next;
72
+ }
73
+ function rewriteFieldsInClassBody(body, fields) {
74
+ let next = body;
75
+ for (const field of fields) {
76
+ next = rewriteFieldDeclaration(next, field);
77
+ next = rewriteCtorSeed(next, field);
78
+ // The __gea_to_value getter for each field uses `gea_cpp_key(self->X)`
79
+ // which already picks up the new typed `gea_cpp_key(const X_item&)`
80
+ // overload via std::vector<T> templating, so no rewrite needed here.
81
+ }
82
+ // Rebuild store-field pushes as typed item constructors when the array item
83
+ // shape is known. This keeps static object-array data on native C++ fields
84
+ // instead of flowing through `__gea_record_N`/`gea_cpp_key` boxers.
85
+ for (const field of fields) {
86
+ next = rewritePushBackItemsForField(next, field);
87
+ }
88
+ return next;
89
+ }
90
+ // The module-split (typed-snapshot) emitter defines store members OUT-OF-LINE
91
+ // — the class definition with its field declarations goes to the layout
92
+ // header while `NotesStore::NotesStore() : Store() { ... }` and the methods
93
+ // land in the module .cpp. The class-body pass above never sees those bodies,
94
+ // so without this pass a typed field keeps its boxed
95
+ // `std::vector<gea_cpp_value>` constructor seed and the module fails to
96
+ // compile (`no viable overloaded '='`). Apply the same seed/push_back
97
+ // rewrites to every out-of-line member definition of the store class.
98
+ function rewriteFieldsInMemberBody(body, fields) {
99
+ let next = body;
100
+ for (const field of fields) {
101
+ next = rewriteCtorSeed(next, field);
102
+ }
103
+ for (const field of fields) {
104
+ next = rewritePushBackItemsForField(next, field);
105
+ }
106
+ return next;
107
+ }
108
+ function rewriteOutOfLineMemberBodies(source, className, transform) {
109
+ const memberPattern = new RegExp(`\\b${escapeRegExp(className)}::[A-Za-z_~][A-Za-z0-9_]*\\s*\\(`, 'g');
110
+ let next = source;
111
+ let searchFrom = 0;
112
+ for (;;) {
113
+ memberPattern.lastIndex = searchFrom;
114
+ const match = memberPattern.exec(next);
115
+ if (!match)
116
+ break;
117
+ const paramsOpen = match.index + match[0].length - 1;
118
+ const paramsClose = findMatchingParen(next, paramsOpen);
119
+ if (paramsClose < 0)
120
+ break;
121
+ // Skip the member-init list (`: Store()`) to the body brace; hitting a `;`
122
+ // first means this was a declaration or a call expression, not a
123
+ // definition. (The store emitter never brace-initializes in init lists,
124
+ // so the first `{` after the parameter list is always the body.)
125
+ let cursor = paramsClose + 1;
126
+ while (cursor < next.length && next[cursor] !== '{' && next[cursor] !== ';')
127
+ cursor += 1;
128
+ if (next[cursor] !== '{') {
129
+ searchFrom = paramsClose + 1;
130
+ continue;
131
+ }
132
+ const close = findMatchingBrace(next, cursor);
133
+ if (close < 0)
134
+ break;
135
+ const transformed = transform(next.slice(cursor + 1, close));
136
+ next = next.slice(0, cursor + 1) + transformed + next.slice(close);
137
+ searchFrom = cursor + 1 + transformed.length + 1;
138
+ }
139
+ return next;
140
+ }
141
+ // Rewrite `.push_back(__gea_record_N{...})` or
142
+ // `.push_back(gea_cpp_key(__gea_record_N{...}))` only on call sites whose
143
+ // receiver expression names the typed store field. geatsc has emitted both an
144
+ // older IIFE receiver pattern and a newer direct `(*this).field.push_back(...)`
145
+ // pattern, so handle both.
146
+ function rewritePushBackItemsForField(body, field) {
147
+ let next = rewritePushBackItemsAfterNeedle(body, field, `return ((*this).${field.fieldName});`, ` })().push_back(`);
148
+ next = rewritePushBackItemsAfterNeedle(next, field, `(*this).${field.fieldName}`, `.push_back(`);
149
+ return next;
150
+ }
151
+ function rewritePushBackItemsAfterNeedle(body, field, needle, tailFragment) {
152
+ let cursor = 0;
153
+ let out = '';
154
+ while (true) {
155
+ const needleIdx = body.indexOf(needle, cursor);
156
+ if (needleIdx < 0) {
157
+ out += body.slice(cursor);
158
+ break;
159
+ }
160
+ const tailStart = needleIdx + needle.length;
161
+ if (body.startsWith(tailFragment, tailStart)) {
162
+ const argStart = tailStart + tailFragment.length;
163
+ const pushClose = findMatchingParen(body, argStart - 1);
164
+ if (pushClose < 0) {
165
+ out += body.slice(cursor, tailStart) + body.slice(tailStart);
166
+ cursor = body.length;
167
+ break;
168
+ }
169
+ const originalArg = body.slice(argStart, pushClose).trim();
170
+ const unwrapped = unwrapOuterCall(originalArg, 'gea_cpp_key') ?? originalArg;
171
+ const nativeItem = buildNativeTypedItem(unwrapped, field);
172
+ if (nativeItem || unwrapped !== originalArg) {
173
+ out += body.slice(cursor, argStart);
174
+ out += nativeItem ?? unwrapped;
175
+ cursor = pushClose;
176
+ continue;
177
+ }
178
+ }
179
+ out += body.slice(cursor, tailStart);
180
+ cursor = tailStart;
181
+ }
182
+ return out;
183
+ }
184
+ function unwrapOuterCall(expr, callName) {
185
+ const trimmed = expr.trim();
186
+ const prefix = `${callName}(`;
187
+ if (!trimmed.startsWith(prefix))
188
+ return null;
189
+ const close = findMatchingParen(trimmed, prefix.length - 1);
190
+ if (close !== trimmed.length - 1)
191
+ return null;
192
+ return trimmed.slice(prefix.length, close).trim();
193
+ }
194
+ function buildNativeTypedItem(element, field) {
195
+ if (field.useInterfaceStruct || field.itemFields.length === 0)
196
+ return null;
197
+ const pairs = parseAggregateRecordElement(element);
198
+ if (!pairs)
199
+ return null;
200
+ for (const key of pairs.keys()) {
201
+ if (!field.itemFields.some((f) => f.name === key))
202
+ return null;
203
+ }
204
+ const args = field.itemFields.map((f) => {
205
+ const value = pairs.get(f.name);
206
+ const raw = value ?? (f.valueType === 'string' ? 'std::string()' : f.valueType === 'boolean' ? 'false' : '0');
207
+ return castNativeTypedCtorArg(raw, f.valueType);
208
+ });
209
+ return `${field.qualifiedItemType}(${args.join(', ')})`;
210
+ }
211
+ function parseAggregateRecordElement(element) {
212
+ const recordIdx = element.indexOf('__gea_record_');
213
+ if (recordIdx < 0)
214
+ return null;
215
+ const braceOpen = element.indexOf('{', recordIdx);
216
+ if (braceOpen < 0)
217
+ return null;
218
+ const braceClose = findMatchingBrace(element, braceOpen);
219
+ if (braceClose < 0)
220
+ return null;
221
+ const body = element.slice(braceOpen + 1, braceClose);
222
+ const pairs = new Map();
223
+ for (const part of splitTopLevelArgs(body)) {
224
+ const match = /^\s*\.([A-Za-z_]\w*)\s*=\s*([\s\S]+?)\s*$/.exec(part);
225
+ if (!match)
226
+ return null;
227
+ const name = match[1];
228
+ if (name.startsWith('__gea_has_'))
229
+ continue;
230
+ pairs.set(name, match[2]);
231
+ }
232
+ return pairs.size > 0 ? pairs : null;
233
+ }
234
+ // Turn the comma-separated boxed record builders of a ctor seed into a typed
235
+ // vector initializer that constructs each item through its field-wise ctor.
236
+ // Returns the `{...}` initializer (braces included) or null to signal the
237
+ // caller should keep the boxed converting-ctor seed.
238
+ function buildNativeTypedSeed(seedInner, field) {
239
+ // Interface-struct items carry presence flags the reader sets, so keep those
240
+ // on their existing reader/conversion path. Synthesized primitive items can
241
+ // be built directly, including one-field shapes such as collision indexes.
242
+ if (field.useInterfaceStruct || field.itemFields.length === 0)
243
+ return null;
244
+ const elements = splitTopLevelArgs(seedInner);
245
+ if (elements.length === 0)
246
+ return null;
247
+ const built = [];
248
+ for (const element of elements) {
249
+ const pairs = parseSeedRecordElement(element);
250
+ if (!pairs)
251
+ return null;
252
+ // A seed key with no matching struct field means we'd silently drop data —
253
+ // bail to the boxed path rather than emit a wrong constructor call.
254
+ for (const key of pairs.keys()) {
255
+ if (!field.itemFields.some((f) => f.name === key))
256
+ return null;
257
+ }
258
+ const args = field.itemFields.map((f) => {
259
+ const value = pairs.get(f.name);
260
+ if (value !== undefined)
261
+ return castNativeTypedCtorArg(value, f.valueType);
262
+ // Omitted key → the record literal didn't set it; use the zero value.
263
+ return f.valueType === 'string' ? 'std::string()' : f.valueType === 'boolean' ? 'false' : 'static_cast<double>(0)';
264
+ });
265
+ built.push(`${field.qualifiedItemType}(${args.join(', ')})`);
266
+ }
267
+ return `{${built.join(', ')}}`;
268
+ }
269
+ function castNativeTypedCtorArg(value, valueType) {
270
+ if (valueType === 'number')
271
+ return `static_cast<double>(${value})`;
272
+ if (valueType === 'boolean')
273
+ return `static_cast<bool>(${value})`;
274
+ return `std::string(${value})`;
275
+ }
276
+ // Split a brace/paren/bracket- and string-aware comma list at depth 0.
277
+ function splitTopLevelArgs(source) {
278
+ const parts = [];
279
+ let depth = 0;
280
+ let quote = null;
281
+ let escaped = false;
282
+ let start = 0;
283
+ for (let i = 0; i < source.length; i += 1) {
284
+ const ch = source[i];
285
+ if (quote) {
286
+ if (escaped)
287
+ escaped = false;
288
+ else if (ch === '\\')
289
+ escaped = true;
290
+ else if (ch === quote)
291
+ quote = null;
292
+ continue;
293
+ }
294
+ if (ch === '"' || ch === "'")
295
+ quote = ch;
296
+ else if (ch === '(' || ch === '{' || ch === '[')
297
+ depth += 1;
298
+ else if (ch === ')' || ch === '}' || ch === ']')
299
+ depth -= 1;
300
+ else if (ch === ',' && depth === 0) {
301
+ parts.push(source.slice(start, i));
302
+ start = i + 1;
303
+ }
304
+ }
305
+ parts.push(source.slice(start));
306
+ return parts.map((p) => p.trim()).filter((p) => p.length > 0);
307
+ }
308
+ // Parse one boxed record-builder IIFE (`([&]() { gea_cpp_value r; ...
309
+ // r.record_set_literal("k", V); ...; return r; })()`) into a key→value-expr
310
+ // map. Returns null for any element that isn't exactly that shape or whose
311
+ // values are themselves boxed (nested records can't assign to a typed field).
312
+ function parseSeedRecordElement(element) {
313
+ if (!element.includes('gea_cpp_value::kind_t::record'))
314
+ return null;
315
+ const pairs = new Map();
316
+ const needle = '.record_set_literal(';
317
+ let cursor = 0;
318
+ while (true) {
319
+ const at = element.indexOf(needle, cursor);
320
+ if (at < 0)
321
+ break;
322
+ const open = at + needle.length - 1;
323
+ const close = findMatchingParen(element, open);
324
+ if (close < 0)
325
+ return null;
326
+ const args = splitTopLevelArgs(element.slice(open + 1, close));
327
+ if (args.length !== 2)
328
+ return null;
329
+ const keyMatch = /^"((?:[^"\\]|\\.)*)"$/.exec(args[0]);
330
+ if (!keyMatch)
331
+ return null;
332
+ const key = keyMatch[1].replace(/\\(.)/g, '$1');
333
+ if (!/^[A-Za-z_]\w*$/.test(key))
334
+ return null;
335
+ const value = args[1];
336
+ if (!value || /\bgea_cpp_value\b/.test(value) || value.includes('record_set_literal'))
337
+ return null;
338
+ pairs.set(key, value);
339
+ cursor = close + 1;
340
+ }
341
+ return pairs.size > 0 ? pairs : null;
342
+ }
343
+ function findMatchingParen(source, openParen) {
344
+ let depth = 0;
345
+ let quote = null;
346
+ let escaped = false;
347
+ for (let i = openParen; i < source.length; i += 1) {
348
+ const ch = source[i];
349
+ if (quote) {
350
+ if (escaped)
351
+ escaped = false;
352
+ else if (ch === '\\')
353
+ escaped = true;
354
+ else if (ch === quote)
355
+ quote = null;
356
+ continue;
357
+ }
358
+ if (ch === '"' || ch === "'") {
359
+ quote = ch;
360
+ continue;
361
+ }
362
+ if (ch === '(')
363
+ depth += 1;
364
+ else if (ch === ')') {
365
+ depth -= 1;
366
+ if (depth === 0)
367
+ return i;
368
+ }
369
+ }
370
+ return -1;
371
+ }
372
+ // `mutable std::vector<gea_cpp_value> ${name}{};` → `mutable std::vector<gea_ir::${itemType}> ${name}{};`.
373
+ // The typed item struct is emitted inside `namespace gea_ir { ... }` by
374
+ // `cpp-stores.ts`, but store classes live outside that namespace, so we
375
+ // fully qualify here.
376
+ function rewriteFieldDeclaration(body, field) {
377
+ const pattern = new RegExp(`\\bmutable\\s+std::vector<\\s*gea_cpp_value\\s*>\\s+${escapeRegExp(field.fieldName)}(\\s*\\{\\s*\\}\\s*;)`);
378
+ return body.replace(pattern, `mutable std::vector<${field.qualifiedItemType}> ${field.fieldName}$1`);
379
+ }
380
+ // `this->${name} = std::vector<gea_cpp_value>{...records...};` → typed seeds.
381
+ //
382
+ // The seed records carry the store's initial array data (e.g. a notes app's
383
+ // pre-populated `notes = [{...}, ...]`). The typed field is now a
384
+ // `std::vector<X_item>`, which can't hold `gea_cpp_value` directly, so we
385
+ // keep the original record literals in a temporary `std::vector<gea_cpp_value>`
386
+ // and convert each element through `X_item`'s `gea_cpp_value` constructor.
387
+ // This preserves seed data instead of dropping it — important for stores
388
+ // whose array IS the data source (not a placeholder an `init()` rebuilds).
389
+ // Stores that DO clear+rebuild in `init()` (e.g. button-tetris's single
390
+ // placeholder) are unaffected: the seed is materialised then immediately
391
+ // overwritten.
392
+ function rewriteCtorSeed(body, field) {
393
+ // The emitter produces the store array-literal initializer in one of two shapes:
394
+ // direct: this->X = std::vector<gea_cpp_value>{ ELEMENTS };
395
+ // IIFE-wrapped: this->X = ([&]() { std::vector<gea_cpp_value> __gea_array =
396
+ // std::vector<gea_cpp_value>{ ELEMENTS };
397
+ // ...native-property-attribute bookkeeping...; return __gea_array; })();
398
+ // (the IIFE form is what the typed-runtime-coverage codegen emits so the array
399
+ // carries native property attributes). Either way the typed field is now a
400
+ // `std::vector<X_item>`, which can't hold `gea_cpp_value`, so we must rewrite the
401
+ // seed to typed items. Locate the ELEMENTS brace and the end of the whole
402
+ // assignment statement for both shapes.
403
+ const assignPattern = new RegExp(`this->${escapeRegExp(field.fieldName)}\\s*=\\s*`);
404
+ const match = assignPattern.exec(body);
405
+ if (!match)
406
+ return body;
407
+ const prefix = match[0];
408
+ const afterEq = match.index + prefix.length;
409
+ let seedOpen = -1;
410
+ let stmtEnd = -1;
411
+ if (/^std::vector<\s*gea_cpp_value\s*>\s*\{/.test(body.slice(afterEq))) {
412
+ seedOpen = body.indexOf('{', afterEq);
413
+ const close = findMatchingBrace(body, seedOpen);
414
+ if (close < 0)
415
+ return body;
416
+ let e = close + 1;
417
+ while (e < body.length && /\s/.test(body[e]))
418
+ e += 1;
419
+ if (body[e] === ';')
420
+ e += 1;
421
+ stmtEnd = e;
422
+ }
423
+ else if (body[afterEq] === '(') {
424
+ // `([&]() { ... })()` — find the lambda group's close, then the `()` call.
425
+ const groupClose = findMatchingParen(body, afterEq);
426
+ if (groupClose < 0)
427
+ return body;
428
+ let e = groupClose + 1;
429
+ while (e < body.length && /\s/.test(body[e]))
430
+ e += 1;
431
+ if (body[e] === '(') {
432
+ const invokeClose = findMatchingParen(body, e);
433
+ if (invokeClose < 0)
434
+ return body;
435
+ e = invokeClose + 1;
436
+ }
437
+ while (e < body.length && /\s/.test(body[e]))
438
+ e += 1;
439
+ if (body[e] === ';')
440
+ e += 1;
441
+ stmtEnd = e;
442
+ // The seed vector is the `= std::vector<gea_cpp_value>{` inside the IIFE (the
443
+ // second `std::vector<gea_cpp_value>` — the first is the local's declared type).
444
+ const innerPattern = /=\s*std::vector<\s*gea_cpp_value\s*>\s*\{/g;
445
+ innerPattern.lastIndex = afterEq;
446
+ const inner = innerPattern.exec(body);
447
+ if (!inner || inner.index > groupClose)
448
+ return body;
449
+ seedOpen = inner.index + inner[0].length - 1;
450
+ }
451
+ else {
452
+ return body;
453
+ }
454
+ const seedClose = findMatchingBrace(body, seedOpen);
455
+ if (seedClose < 0)
456
+ return body;
457
+ // `{ ...record literals... }` — the brace-delimited initializer contents,
458
+ // braces included.
459
+ const seedBraces = body.slice(seedOpen, seedClose + 1);
460
+ const seedInner = body.slice(seedOpen + 1, seedClose).trim();
461
+ const fieldRef = `this->${field.fieldName}`;
462
+ // No seed elements → just the empty typed vector.
463
+ if (seedInner.length === 0) {
464
+ const empty = `${prefix}std::vector<${field.qualifiedItemType}>{};`;
465
+ return body.slice(0, match.index) + empty + body.slice(stmtEnd);
466
+ }
467
+ // Preferred path: construct each item directly through its field-wise ctor —
468
+ // `std::vector<gea_ir::X_item>{ gea_ir::X_item(0, 0, "#000"), ... }` — with no
469
+ // boxed `gea_cpp_value` anywhere. Falls back to the converting-ctor seed below
470
+ // for anything that doesn't cleanly parse (nested objects, dynamic values,
471
+ // interface-struct items with presence flags, single-field items).
472
+ const nativeSeed = buildNativeTypedSeed(seedInner, field);
473
+ if (nativeSeed) {
474
+ const seeded = `${prefix}std::vector<${field.qualifiedItemType}>${nativeSeed};`;
475
+ return body.slice(0, match.index) + seeded + body.slice(stmtEnd);
476
+ }
477
+ const seedVar = `__gea_seed_${field.fieldName}`;
478
+ // Materialise each seed record. The synthesized item struct has an explicit
479
+ // `gea_cpp_value`-converting ctor (`gea_ir::X_item(v)`); geatsc's interface
480
+ // struct does NOT, so route those through the reader fn
481
+ // (`gea_ir::read___gea_type_X(v)` → `__gea_from_value`, which sets presence
482
+ // flags) instead.
483
+ const elementFromSeed = field.useInterfaceStruct
484
+ ? `gea_ir::read_${field.itemType}(__gea_seed_value)`
485
+ : `gea_ir::${field.itemType}(__gea_seed_value)`;
486
+ const replacement = `${prefix}std::vector<${field.qualifiedItemType}>{}; ` +
487
+ `{ std::vector<gea_cpp_value> ${seedVar} = std::vector<gea_cpp_value>${seedBraces}; ` +
488
+ `${fieldRef}.reserve(${seedVar}.size()); ` +
489
+ `for (auto &__gea_seed_value : ${seedVar}) ${fieldRef}.push_back(${elementFromSeed}); }`;
490
+ return body.slice(0, match.index) + replacement + body.slice(stmtEnd);
491
+ }
492
+ // In `__gea_to_value`'s setter lambda, the cast for typed-array fields:
493
+ // __gea_self->X = ([](auto &&v) -> std::vector<gea_cpp_value> { ... })(value);
494
+ // becomes:
495
+ // __gea_self->X = gea_ir::read_${storeClass}_${fieldName}(gea_cpp_value(value));
496
+ function rewriteToValueSetterCast(source, storeClass, fields) {
497
+ let next = source;
498
+ for (const field of fields) {
499
+ // The whole setter cast IIFE for this field starts with `__gea_self->X = ([...`
500
+ // and ends at the `)(__gea_value);` matching the lambda's invocation.
501
+ const startPattern = new RegExp(`__gea_self->${escapeRegExp(field.fieldName)}\\s*=\\s*\\(\\s*\\[`);
502
+ const startMatch = startPattern.exec(next);
503
+ if (!startMatch)
504
+ continue;
505
+ const start = startMatch.index;
506
+ // Find the IIFE's outer parenthesised expression: ( [...](...) -> ... { ... } )(__gea_value)
507
+ // Easiest: scan from `start` to find the `)(__gea_value);` close. The
508
+ // call-arg `__gea_value` is a literal in the geatsc-emitted code.
509
+ const tailPattern = /\)\(__gea_value\);/g;
510
+ tailPattern.lastIndex = start;
511
+ const tailMatch = tailPattern.exec(next);
512
+ if (!tailMatch)
513
+ continue;
514
+ const end = tailMatch.index + tailMatch[0].length;
515
+ const replacement = `__gea_self->${field.fieldName} = gea_ir::${field.readerName}(gea_cpp_value(__gea_value));`;
516
+ // Restrict to the `BallStore::__gea_to_value` (or member equivalent) so
517
+ // we don't accidentally clobber unrelated `__gea_self->X = (...)(value)`
518
+ // patterns elsewhere. The setter lambda always lives inside the
519
+ // `__gea_to_value()` body for this class.
520
+ const guardPattern = new RegExp(`\\b${escapeRegExp(storeClass)}::__gea_to_value\\b|\\bvirtual\\s+gea_cpp_value\\s+__gea_to_value\\b`);
521
+ const before = next.slice(0, start);
522
+ if (!guardPattern.test(before))
523
+ continue;
524
+ next = next.slice(0, start) + replacement + next.slice(end);
525
+ }
526
+ return next;
527
+ }
528
+ function rewriteClassBody(source, className, transform) {
529
+ const open = findClassOpenBrace(source, className);
530
+ if (open < 0)
531
+ return source;
532
+ const close = findMatchingBrace(source, open);
533
+ if (close < 0)
534
+ return source;
535
+ const transformed = transform(source.slice(open + 1, close));
536
+ return source.slice(0, open + 1) + transformed + source.slice(close);
537
+ }
538
+ function findClassOpenBrace(source, className) {
539
+ const pattern = new RegExp(`\\bclass\\s+${escapeRegExp(className)}\\b`, 'g');
540
+ let match;
541
+ while ((match = pattern.exec(source)) !== null) {
542
+ const brace = source.indexOf('{', match.index);
543
+ if (brace < 0)
544
+ return -1;
545
+ const semicolon = source.indexOf(';', match.index);
546
+ if (semicolon < 0 || brace < semicolon)
547
+ return brace;
548
+ }
549
+ return -1;
550
+ }
551
+ function findMatchingBrace(source, open) {
552
+ let depth = 0;
553
+ let quote = null;
554
+ let escaped = false;
555
+ for (let index = open; index < source.length; index += 1) {
556
+ const char = source[index];
557
+ if (quote) {
558
+ if (escaped)
559
+ escaped = false;
560
+ else if (char === '\\')
561
+ escaped = true;
562
+ else if (char === quote)
563
+ quote = null;
564
+ continue;
565
+ }
566
+ if (char === '"' || char === "'") {
567
+ quote = char;
568
+ continue;
569
+ }
570
+ if (char === '{')
571
+ depth += 1;
572
+ else if (char === '}') {
573
+ depth -= 1;
574
+ if (depth === 0)
575
+ return index;
576
+ }
577
+ }
578
+ return -1;
579
+ }
580
+ function pruneUnusedRecordHelpers(source) {
581
+ let next = source;
582
+ let changed = true;
583
+ while (changed) {
584
+ changed = false;
585
+ const pattern = /\nstruct\s+(__gea_record_\d+)\s*\{/g;
586
+ let match;
587
+ while ((match = pattern.exec(next)) !== null) {
588
+ const name = match[1];
589
+ const structOpen = next.indexOf('{', match.index);
590
+ if (structOpen < 0)
591
+ continue;
592
+ const structClose = findMatchingBrace(next, structOpen);
593
+ if (structClose < 0)
594
+ continue;
595
+ let removeEnd = structClose + 1;
596
+ while (removeEnd < next.length && /\s/.test(next[removeEnd]))
597
+ removeEnd += 1;
598
+ if (next[removeEnd] !== ';')
599
+ continue;
600
+ removeEnd += 1;
601
+ const helperStart = skipWhitespace(next, removeEnd);
602
+ const helperPrefix = `inline gea_cpp_value gea_cpp_key(const ${name} &__gea_v)`;
603
+ if (next.startsWith(helperPrefix, helperStart)) {
604
+ const helperOpen = next.indexOf('{', helperStart + helperPrefix.length);
605
+ if (helperOpen < 0)
606
+ continue;
607
+ const helperClose = findMatchingBrace(next, helperOpen);
608
+ if (helperClose < 0)
609
+ continue;
610
+ removeEnd = helperClose + 1;
611
+ }
612
+ while (removeEnd < next.length && (next[removeEnd] === '\n' || next[removeEnd] === '\r'))
613
+ removeEnd += 1;
614
+ const candidate = next.slice(0, match.index) + '\n' + next.slice(removeEnd);
615
+ if (!new RegExp(`\\b${escapeRegExp(name)}\\b`).test(candidate)) {
616
+ next = candidate;
617
+ changed = true;
618
+ break;
619
+ }
620
+ }
621
+ if (changed)
622
+ continue;
623
+ const helperPattern = /\ninline\s+gea_cpp_value\s+gea_cpp_key\(const\s+(__gea_record_\d+)\s+&__gea_v\)\s*\{/g;
624
+ let helperMatch;
625
+ while ((helperMatch = helperPattern.exec(next)) !== null) {
626
+ const name = helperMatch[1];
627
+ const helperOpen = next.indexOf('{', helperMatch.index);
628
+ if (helperOpen < 0)
629
+ continue;
630
+ const helperClose = findMatchingBrace(next, helperOpen);
631
+ if (helperClose < 0)
632
+ continue;
633
+ let removeEnd = helperClose + 1;
634
+ while (removeEnd < next.length && (next[removeEnd] === '\n' || next[removeEnd] === '\r'))
635
+ removeEnd += 1;
636
+ const candidate = next.slice(0, helperMatch.index) + '\n' + next.slice(removeEnd);
637
+ const structStillExists = new RegExp(`\\nstruct\\s+${escapeRegExp(name)}\\s*\\{`).test(candidate);
638
+ if (!structStillExists || !new RegExp(`\\b${escapeRegExp(name)}\\b`).test(candidate)) {
639
+ next = candidate;
640
+ changed = true;
641
+ break;
642
+ }
643
+ }
644
+ }
645
+ return next;
646
+ }
647
+ function skipWhitespace(source, index) {
648
+ let cursor = index;
649
+ while (cursor < source.length && /\s/.test(source[cursor]))
650
+ cursor += 1;
651
+ return cursor;
652
+ }
653
+ function escapeRegExp(text) {
654
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
655
+ }