@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,1521 @@
1
+ import { arrayElementAliasFieldTarget, arrayItemAliasKey, arrayItemFieldAliasKey, arrayItemFieldHint, constantMap, fieldHint, localArrayCppType, nextStoreMethodTemp, typedArrayItemFieldAccess } from './cpp-store-method-context.js';
2
+ import { parseStoreMethodBody } from './cpp-store-method-body-parser.js';
3
+ import { assignmentHint, globalStoreFieldTarget, lowerExpr, lowerForUpdate } from './cpp-store-method-expressions.js';
4
+ import { exprPath, methodPrefix, readClassMethodBody, replaceClassMethodBody, replaceClassMethodParameters, thisArrayItemFieldTarget, thisArrayLengthTarget, thisArrayPushTarget, thisFieldName } from './cpp-store-method-targets.js';
5
+ import { collectStoreFields, collectStoreMethods } from './cpp-stores.js';
6
+ import { sanitizeCppIdentifier } from './utils.js';
7
+ import { storeDynamicFallbackEnabled, storeHubEmissionEnabled } from './cpp-store-hub.js';
8
+ export function replaceStoreMethodsFromIr(source, ir, constants = new Map(), topLevelValueNames = new Map()) {
9
+ let next = source;
10
+ const storeFields = collectStoreFields(ir.stores);
11
+ const storeMethods = collectStoreMethods(ir.stores);
12
+ for (const store of ir.stores) {
13
+ // A self-store's class is the geatsc-compiled typed ReactiveComponent: its
14
+ // method bodies are already correct (typed Signal writes notify subscribers).
15
+ // This re-lowering targets the dynamic CompiledStore dirty-field protocol and
16
+ // would corrupt the base-less typed class — skip.
17
+ if (store.selfStore)
18
+ continue;
19
+ for (const method of store.methods ?? []) {
20
+ const className = sanitizeCppIdentifier(store.className);
21
+ const methodName = methodPrefix(method);
22
+ const topLevelFunctionNames = topLevelFunctionNameOverrides(next, className, methodName, method);
23
+ const methodTopLevelValueNames = mergeMaps(topLevelValueNames, topLevelValueNameOverrides(next, className, methodName));
24
+ const body = lowerStoreMethod(store, method, storeFields, storeMethods, constants, topLevelFunctionNames, methodTopLevelValueNames);
25
+ if (body) {
26
+ const typedParams = typedStoreMethodParams(method);
27
+ next = typedParams
28
+ ? replaceClassMethodParameters(next, className, methodName, typedParams, body)
29
+ : replaceClassMethodBody(next, className, methodName, body);
30
+ }
31
+ }
32
+ }
33
+ return next;
34
+ }
35
+ export function topLevelValueAccessorNamesFromSource(source) {
36
+ const accessors = new Map();
37
+ const pattern = /\b__gea_global_([A-Za-z_][A-Za-z0-9_]*)\s*\(\s*\)/g;
38
+ let match;
39
+ while ((match = pattern.exec(source)) !== null) {
40
+ const accessor = `__gea_global_${match[1]}()`;
41
+ accessors.set(match[1], accessor);
42
+ }
43
+ return accessors;
44
+ }
45
+ function mergeMaps(...maps) {
46
+ const merged = new Map();
47
+ for (const map of maps) {
48
+ for (const [key, value] of map)
49
+ merged.set(key, value);
50
+ }
51
+ return merged;
52
+ }
53
+ function topLevelValueNameOverrides(source, className, methodName) {
54
+ const originalBody = readClassMethodBody(source, className, methodName);
55
+ if (!originalBody)
56
+ return new Map();
57
+ return topLevelValueAccessorNamesFromSource(originalBody);
58
+ }
59
+ function topLevelFunctionNameOverrides(source, className, methodName, method) {
60
+ const originalBody = readClassMethodBody(source, className, methodName);
61
+ if (!originalBody)
62
+ return new Map();
63
+ const ops = method.ops ?? parseStoreMethodBody(method.body);
64
+ if (!ops)
65
+ return new Map();
66
+ const names = topLevelFunctionCallNames(ops);
67
+ const overrides = new Map();
68
+ for (const name of names) {
69
+ const pattern = generatedFunctionNamePattern(name);
70
+ const matches = new Set();
71
+ let match;
72
+ while ((match = pattern.exec(originalBody)) !== null)
73
+ matches.add(match[1]);
74
+ if (matches.size === 1)
75
+ overrides.set(name, [...matches][0]);
76
+ }
77
+ return overrides;
78
+ }
79
+ function topLevelFunctionCallNames(statements) {
80
+ const names = new Set();
81
+ const visitStatement = (statement) => {
82
+ if (statement.kind === 'var') {
83
+ if (statement.init)
84
+ visitExpr(statement.init);
85
+ }
86
+ else if (statement.kind === 'assign') {
87
+ visitExpr(statement.target);
88
+ visitExpr(statement.value);
89
+ }
90
+ else if (statement.kind === 'expr') {
91
+ visitExpr(statement.expr);
92
+ }
93
+ else if (statement.kind === 'if') {
94
+ visitExpr(statement.test);
95
+ statement.consequent.forEach(visitStatement);
96
+ statement.alternate?.forEach(visitStatement);
97
+ }
98
+ else if (statement.kind === 'for') {
99
+ if (statement.init)
100
+ visitStatement(statement.init);
101
+ if (statement.test)
102
+ visitExpr(statement.test);
103
+ if (statement.update)
104
+ visitExpr(statement.update);
105
+ statement.body.forEach(visitStatement);
106
+ }
107
+ else if (statement.kind === 'return') {
108
+ if (statement.value)
109
+ visitExpr(statement.value);
110
+ }
111
+ };
112
+ const visitExpr = (expr) => {
113
+ if (expr.kind === 'call') {
114
+ if (expr.callee.kind === 'identifier')
115
+ names.add(expr.callee.name);
116
+ visitExpr(expr.callee);
117
+ expr.args.forEach(visitExpr);
118
+ }
119
+ else if (expr.kind === 'member') {
120
+ visitExpr(expr.object);
121
+ }
122
+ else if (expr.kind === 'index') {
123
+ visitExpr(expr.object);
124
+ visitExpr(expr.index);
125
+ }
126
+ else if (expr.kind === 'object') {
127
+ expr.fields.forEach((field) => visitExpr(field.value));
128
+ }
129
+ else if (expr.kind === 'array') {
130
+ expr.elements.forEach(visitExpr);
131
+ }
132
+ else if (expr.kind === 'unary' || expr.kind === 'update') {
133
+ visitExpr(expr.arg);
134
+ }
135
+ else if (expr.kind === 'binary' || expr.kind === 'logical') {
136
+ visitExpr(expr.left);
137
+ visitExpr(expr.right);
138
+ }
139
+ else if (expr.kind === 'conditional') {
140
+ visitExpr(expr.test);
141
+ visitExpr(expr.consequent);
142
+ visitExpr(expr.alternate);
143
+ }
144
+ };
145
+ statements.forEach(visitStatement);
146
+ return names;
147
+ }
148
+ function escapeRegExp(text) {
149
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
150
+ }
151
+ function generatedFunctionNamePattern(name) {
152
+ const safeName = escapeRegExp(sanitizeCppIdentifier(name));
153
+ const legacyName = `fn_${safeName}`;
154
+ const moduleQualifiedName = `fn___gea_mod_[A-Za-z0-9_]+_x2e_${safeName}`;
155
+ const collisionSuffix = '(?:_x24_\\d+|_x[0-9a-fA-F]+_[A-Za-z0-9_]+)?';
156
+ return new RegExp(`\\b((?:${legacyName}|${moduleQualifiedName})${collisionSuffix})\\b(?:\\s*\\()?`, 'g');
157
+ }
158
+ // The typed C++ parameter list for a store method whose every parameter has a
159
+ // known primitive value type (e.g. `tick(timestampMs: number)` →
160
+ // `double timestampMs`). Returns null when the method has no params or any
161
+ // param lacks a value type — those keep geatsc's original `gea_cpp_value`
162
+ // signature (only the body is replaced). Crucially this rewrites ONLY the
163
+ // parameter list; the method's RETURN TYPE (and `virtual`/`const` qualifiers)
164
+ // is preserved from geatsc's original declaration. An earlier version
165
+ // hardcoded `virtual void …`, which silently demoted value-returning methods
166
+ // (e.g. `tick(): boolean`) to `void` and broke their callers
167
+ // (`if (this->tick(...))`).
168
+ function typedStoreMethodParams(method) {
169
+ if (method.params.length === 0)
170
+ return null;
171
+ if (method.params.some((param) => !param.valueType))
172
+ return null;
173
+ return method.params
174
+ .map((param) => `${cppParamType(param.valueType)} ${sanitizeCppIdentifier(param.name)}`)
175
+ .join(', ');
176
+ }
177
+ function cppParamType(valueType) {
178
+ if (valueType === 'number')
179
+ return 'double';
180
+ if (valueType === 'boolean')
181
+ return 'bool';
182
+ return 'std::string';
183
+ }
184
+ // `this.<arrayField>[<index>]` shape, or null.
185
+ function thisArrayIndexInit(expr) {
186
+ if (!expr || expr.kind !== 'index')
187
+ return null;
188
+ const obj = expr.object;
189
+ if (obj.kind !== 'member' || obj.object.kind !== 'this')
190
+ return null;
191
+ return { arrayField: obj.property, index: expr.index };
192
+ }
193
+ // Whether `name` is the target of an assignment / ++ / -- anywhere in stmts.
194
+ // Structural mutations of `this.<arrayField>`: whole-element assignment,
195
+ // `.length` assignment, or a mutating array method call. Item-FIELD writes
196
+ // (`this.arr[i].prop = v`) are not structural — element positions are stable.
197
+ function arrayStructurallyMutated(stmts, arrayField) {
198
+ const isThisArray = (e) => e.kind === 'member' && e.object.kind === 'this' && e.property === arrayField;
199
+ const mutatingCall = (e) => {
200
+ if (e.kind !== 'call' || e.callee.kind !== 'member' || !isThisArray(e.callee.object))
201
+ return false;
202
+ return ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'].includes(e.callee.property);
203
+ };
204
+ const inExpr = (e) => {
205
+ if (mutatingCall(e))
206
+ return true;
207
+ switch (e.kind) {
208
+ case 'member':
209
+ return inExpr(e.object);
210
+ case 'index':
211
+ return inExpr(e.object) || inExpr(e.index);
212
+ case 'call':
213
+ return inExpr(e.callee) || e.args.some(inExpr);
214
+ case 'object':
215
+ return e.fields.some((f) => inExpr(f.value));
216
+ case 'array':
217
+ return e.elements.some(inExpr);
218
+ case 'unary':
219
+ case 'update':
220
+ return inExpr(e.arg);
221
+ case 'binary':
222
+ case 'logical':
223
+ return inExpr(e.left) || inExpr(e.right);
224
+ case 'conditional':
225
+ return inExpr(e.test) || inExpr(e.consequent) || inExpr(e.alternate);
226
+ default:
227
+ return false;
228
+ }
229
+ };
230
+ const inStmt = (s) => {
231
+ switch (s.kind) {
232
+ case 'var':
233
+ return s.init ? inExpr(s.init) : false;
234
+ case 'assign': {
235
+ // Whole-element write: this.arr[i] = …
236
+ if (s.target.kind === 'index' && isThisArray(s.target.object))
237
+ return true;
238
+ // Length write: this.arr.length = …
239
+ if (s.target.kind === 'member' && s.target.property === 'length' && isThisArray(s.target.object))
240
+ return true;
241
+ return inExpr(s.target) || inExpr(s.value);
242
+ }
243
+ case 'expr':
244
+ return inExpr(s.expr);
245
+ case 'return':
246
+ return s.value ? inExpr(s.value) : false;
247
+ case 'if':
248
+ return inExpr(s.test) || s.consequent.some(inStmt) || (s.alternate?.some(inStmt) ?? false);
249
+ case 'for':
250
+ return ((s.init ? inStmt(s.init) : false) ||
251
+ (s.test ? inExpr(s.test) : false) ||
252
+ (s.update ? inExpr(s.update) : false) ||
253
+ s.body.some(inStmt));
254
+ default:
255
+ return false;
256
+ }
257
+ };
258
+ return stmts.some(inStmt);
259
+ }
260
+ function lowerStoreMethod(store, method, storeFields, storeMethods, constants, topLevelFunctionNames = new Map(), topLevelValueNames = new Map()) {
261
+ const rawOps = method.ops ?? parseStoreMethodBody(method.body);
262
+ if (!rawOps)
263
+ return null;
264
+ const ops = rawOps;
265
+ const context = {
266
+ store,
267
+ storeFields,
268
+ storeMethods,
269
+ params: new Set(method.params.map((param) => param.name)),
270
+ paramHints: new Map(method.params
271
+ .filter((param) => !!param.valueType)
272
+ .map((param) => [param.name, param.valueType])),
273
+ topLevelFunctionNames,
274
+ topLevelValueNames,
275
+ locals: new Set(),
276
+ constants: constantMap(store, constants),
277
+ localTypes: new Map(),
278
+ tempIndex: 0,
279
+ arrayElementAliases: new Map(),
280
+ arrayItemAliases: new Map(),
281
+ arrayItemFieldAliases: new Map(),
282
+ dirtyArrayFields: new Set(),
283
+ needsFieldSet: false,
284
+ needsArrayLengthSet: false,
285
+ needsArrayItemSet: false,
286
+ needsDynamicArrayItemSet: false,
287
+ needsArrayPush: false,
288
+ needsArrayUnshift: false,
289
+ needsArraySplice: false,
290
+ needsArrayPop: false,
291
+ needsArrayShift: false,
292
+ };
293
+ let body = lowerStatements(context, ops, 2);
294
+ if (!body)
295
+ return null;
296
+ if (needsMutationHelpers(context)) {
297
+ // Mutation flags can be discovered AFTER an early `return` was lowered —
298
+ // `flushBeforeReturn` only emits flush_dirty_fields()/storeDirectBatchEnd()
299
+ // when the flags are already set, so a leading guard return would skip the
300
+ // batch end and leak storeDirectBatchDepth for the rest of the session.
301
+ // Re-lower with the discovered flags so every return carries the flush.
302
+ body = lowerStatements(context, ops, 2);
303
+ if (!body)
304
+ return null;
305
+ }
306
+ return ['{', ...mutationHelpers(context), ...body, ...mutationFooter(context), ' }'];
307
+ }
308
+ function lowerStatements(context, statements, indent) {
309
+ const lines = [];
310
+ for (let index = 0; index < statements.length; index += 1) {
311
+ const statement = statements[index];
312
+ const lowered = lowerStatement(context, statement, indent, statements.slice(index + 1));
313
+ if (!lowered)
314
+ return null;
315
+ lines.push(...lowered);
316
+ }
317
+ return lines;
318
+ }
319
+ function lowerStatement(context, statement, indent, rest = []) {
320
+ const pad = ' '.repeat(indent);
321
+ if (statement.kind === 'var') {
322
+ context.locals.add(statement.name);
323
+ if (statement.localType)
324
+ context.localTypes.set(statement.name, statement.localType);
325
+ context.arrayElementAliases.delete(statement.name);
326
+ const name = sanitizeCppIdentifier(statement.name);
327
+ if (!statement.mutable) {
328
+ const aliasDecl = lowerArrayElementAliasDeclaration(context, statement, rest, pad, name);
329
+ if (aliasDecl)
330
+ return aliasDecl;
331
+ }
332
+ if (!statement.mutable && statement.init) {
333
+ const constexprLine = lowerConstLiteralMatrixDecl(name, statement.init, pad);
334
+ if (constexprLine)
335
+ return constexprLine;
336
+ }
337
+ const localArrayType = localArrayCppType(context, statement.name);
338
+ if (localArrayType && statement.init?.kind === 'array' && statement.init.elements.length === 0) {
339
+ return [`${pad}${localArrayType} ${name}{};`];
340
+ }
341
+ if (localArrayType && !statement.init) {
342
+ return [`${pad}${localArrayType} ${name}{};`];
343
+ }
344
+ const init = statement.init ? lowerExpr(context, statement.init, 'any') : 'gea_cpp_value::missing()';
345
+ return init ? [`${pad}auto ${name} = ${init};`] : null;
346
+ }
347
+ if (statement.kind === 'assign') {
348
+ const assignment = lowerAssignment(context, statement.target, statement.value, true);
349
+ return assignment ? [`${pad}${assignment}${assignment.endsWith('}') ? '' : ';'}`] : null;
350
+ }
351
+ if (statement.kind === 'expr') {
352
+ const expr = lowerExpr(context, statement.expr, 'any');
353
+ return expr ? [`${pad}(void)(${expr});`] : null;
354
+ }
355
+ if (statement.kind === 'return') {
356
+ const expr = statement.value ? lowerExpr(context, statement.value, 'any') : '';
357
+ return expr !== null ? [...flushBeforeReturn(context, pad), `${pad}return${expr ? ` ${expr}` : ''};`] : null;
358
+ }
359
+ if (statement.kind === 'if')
360
+ return lowerIfStatement(context, statement, indent);
361
+ if (statement.kind === 'for')
362
+ return lowerForStatement(context, statement, indent);
363
+ return null;
364
+ }
365
+ function lowerArrayElementAliasDeclaration(context, statement, rest, pad, name) {
366
+ const aliasInit = thisArrayIndexInit(statement.init);
367
+ if (!aliasInit)
368
+ return null;
369
+ if (arrayStructurallyMutated(rest, aliasInit.arrayField))
370
+ return null;
371
+ const index = lowerExpr(context, aliasInit.index, 'number');
372
+ if (!index)
373
+ return null;
374
+ const safeArray = sanitizeCppIdentifier(aliasInit.arrayField);
375
+ const array = `(*this).${safeArray}`;
376
+ const indexTemp = nextStoreMethodTemp(context, 'index');
377
+ const markDirtyOnce = `mark_dirty_array_field_once_${safeArray}`;
378
+ context.needsArrayItemSet = true;
379
+ context.dirtyArrayFields.add(aliasInit.arrayField);
380
+ context.arrayElementAliases.set(statement.name, {
381
+ arrayField: aliasInit.arrayField,
382
+ itemExpression: name,
383
+ indexExpression: indexTemp,
384
+ });
385
+ return [
386
+ `${pad}auto ${indexTemp} = static_cast<std::size_t>(${index});`,
387
+ `${pad}if (${indexTemp} >= ${array}.size()) { ${array}.resize(${indexTemp} + 1); ${markDirtyOnce}(); }`,
388
+ `${pad}auto &${name} = ${array}[${indexTemp}];`,
389
+ ];
390
+ }
391
+ function lowerIfStatement(context, statement, indent) {
392
+ const pad = ' '.repeat(indent);
393
+ const test = lowerExpr(context, statement.test, 'boolean');
394
+ const consequent = lowerStatements(context, statement.consequent, indent + 2);
395
+ if (!test || !consequent)
396
+ return null;
397
+ const lines = [`${pad}if (${test}) {`, ...consequent, `${pad}}`];
398
+ if (statement.alternate?.length) {
399
+ const alternate = lowerStatements(context, statement.alternate, indent + 2);
400
+ if (!alternate)
401
+ return null;
402
+ lines[lines.length - 1] = `${pad}} else {`;
403
+ lines.push(...alternate, `${pad}}`);
404
+ }
405
+ return lines;
406
+ }
407
+ function lowerForStatement(context, statement, indent) {
408
+ const pad = ' '.repeat(indent);
409
+ const loopItem = loopArrayItemReadCache(context, statement, indent + 2);
410
+ const init = loopItem ? lowerForIndexInit(context, statement.init, loopItem.indexName) : lowerForInit(context, statement.init);
411
+ const test = loopItem ? `${sanitizeCppIdentifier(loopItem.indexName)} < (*this).${sanitizeCppIdentifier(loopItem.arrayField)}.size()` : statement.test ? lowerExpr(context, statement.test, 'boolean') : '';
412
+ const update = statement.update ? lowerForUpdate(context, statement.update) : '';
413
+ if (loopItem) {
414
+ context.arrayItemAliases.set(arrayItemAliasKey(loopItem.arrayField, loopItem.indexName), loopItem.itemAlias);
415
+ for (const field of loopItem.fields) {
416
+ context.arrayItemFieldAliases.set(arrayItemFieldAliasKey(loopItem.arrayField, loopItem.indexName, field), loopItem.fieldAliases.get(field));
417
+ }
418
+ }
419
+ const body = lowerStatements(context, statement.body, indent + 2);
420
+ if (loopItem) {
421
+ context.arrayItemAliases.delete(arrayItemAliasKey(loopItem.arrayField, loopItem.indexName));
422
+ for (const field of loopItem.fields)
423
+ context.arrayItemFieldAliases.delete(arrayItemFieldAliasKey(loopItem.arrayField, loopItem.indexName, field));
424
+ }
425
+ if (init === null || test === null || update === null || !body)
426
+ return null;
427
+ return [`${pad}for (${init}; ${test}; ${update}) {`, ...(loopItem?.prelude ?? []), ...body, `${pad}}`];
428
+ }
429
+ function lowerForInit(context, statement) {
430
+ if (!statement)
431
+ return '';
432
+ if (statement.kind === 'var') {
433
+ context.locals.add(statement.name);
434
+ if (statement.localType)
435
+ context.localTypes.set(statement.name, statement.localType);
436
+ const init = statement.init ? lowerExpr(context, statement.init, 'number') : '0';
437
+ return init ? `double ${sanitizeCppIdentifier(statement.name)} = ${init}` : null;
438
+ }
439
+ if (statement.kind === 'assign')
440
+ return lowerAssignment(context, statement.target, statement.value);
441
+ return null;
442
+ }
443
+ function lowerForIndexInit(context, statement, indexName) {
444
+ if (!statement)
445
+ return '';
446
+ if (statement.kind !== 'var' || statement.name !== indexName)
447
+ return lowerForInit(context, statement);
448
+ context.locals.add(statement.name);
449
+ if (statement.localType)
450
+ context.localTypes.set(statement.name, statement.localType);
451
+ const init = statement.init ? lowerExpr(context, statement.init, 'number') : '0';
452
+ return init ? `std::size_t ${sanitizeCppIdentifier(statement.name)} = static_cast<std::size_t>(${init})` : null;
453
+ }
454
+ function loopArrayItemReadCache(context, statement, indent) {
455
+ if (!statement.test || statement.test.kind !== 'binary' || statement.test.op !== '<')
456
+ return null;
457
+ if (statement.test.left.kind !== 'identifier')
458
+ return null;
459
+ const indexName = statement.test.left.name;
460
+ const arrayField = thisArrayLengthTarget(statement.test.right);
461
+ if (!arrayField || mutatesArrayShape(statement.body, arrayField))
462
+ return null;
463
+ const fields = Array.from(collectArrayItemFieldReads(statement.body, arrayField, indexName)).sort();
464
+ if (fields.length === 0)
465
+ return null;
466
+ const contextualHints = collectArrayItemFieldReadHints(context, statement.body, arrayField, indexName);
467
+ const arrayName = sanitizeCppIdentifier(arrayField);
468
+ const indexId = sanitizeCppIdentifier(indexName);
469
+ const itemAlias = `__gea_${arrayName}_${indexId}_item`;
470
+ const fieldAliases = new Map();
471
+ const pad = ' '.repeat(indent);
472
+ const prelude = [`${pad}auto &${itemAlias} = (*this).${arrayName}[static_cast<std::size_t>(${indexId})];`];
473
+ for (const field of fields) {
474
+ const staticHint = arrayItemFieldHint(context.store, arrayField, field);
475
+ const hint = staticHint === 'any' ? contextualHints.get(field) ?? 'any' : staticHint;
476
+ if (hint === 'any')
477
+ continue;
478
+ const alias = `__gea_${arrayName}_${indexId}_${sanitizeCppIdentifier(field)}`;
479
+ fieldAliases.set(field, alias);
480
+ const directAccess = typedArrayItemFieldAccess(context.store, arrayField, field, itemAlias);
481
+ const fieldKey = JSON.stringify(field);
482
+ const dynamicRead = hint === 'string'
483
+ ? `gea_ir::read_string_field(${itemAlias}, ${fieldKey})`
484
+ : hint === 'boolean'
485
+ ? `gea::runtime::coerce::to_boolean(${itemAlias}.record_get_literal(${fieldKey}))`
486
+ : `gea_ir::read_number_field(${itemAlias}, ${fieldKey})`;
487
+ prelude.push(`${pad}auto ${alias} = ${directAccess ?? dynamicRead};`);
488
+ }
489
+ if (fieldAliases.size === 0)
490
+ return null;
491
+ return { arrayField, indexName, itemAlias, fields: [...fieldAliases.keys()], fieldAliases, prelude };
492
+ }
493
+ function collectArrayItemFieldReads(statements, arrayField, indexName) {
494
+ const fields = new Set();
495
+ const visitStatement = (statement) => {
496
+ if (statement.kind === 'var') {
497
+ if (statement.init)
498
+ visitExpr(statement.init);
499
+ }
500
+ else if (statement.kind === 'assign') {
501
+ visitExpr(statement.value);
502
+ }
503
+ else if (statement.kind === 'expr') {
504
+ visitExpr(statement.expr);
505
+ }
506
+ else if (statement.kind === 'return') {
507
+ if (statement.value)
508
+ visitExpr(statement.value);
509
+ }
510
+ else if (statement.kind === 'if') {
511
+ visitExpr(statement.test);
512
+ statement.consequent.forEach(visitStatement);
513
+ statement.alternate?.forEach(visitStatement);
514
+ }
515
+ else if (statement.kind === 'for') {
516
+ if (statement.init)
517
+ visitStatement(statement.init);
518
+ if (statement.test)
519
+ visitExpr(statement.test);
520
+ if (statement.update)
521
+ visitExpr(statement.update);
522
+ statement.body.forEach(visitStatement);
523
+ }
524
+ };
525
+ const visitExpr = (expr) => {
526
+ const item = thisArrayItemFieldTarget(expr);
527
+ if (item && item.arrayField === arrayField && item.index.kind === 'identifier' && item.index.name === indexName) {
528
+ fields.add(item.itemField);
529
+ }
530
+ if (expr.kind === 'member')
531
+ visitExpr(expr.object);
532
+ else if (expr.kind === 'index') {
533
+ visitExpr(expr.object);
534
+ visitExpr(expr.index);
535
+ }
536
+ else if (expr.kind === 'call') {
537
+ visitExpr(expr.callee);
538
+ expr.args.forEach(visitExpr);
539
+ }
540
+ else if (expr.kind === 'object') {
541
+ expr.fields.forEach((field) => visitExpr(field.value));
542
+ }
543
+ else if (expr.kind === 'array') {
544
+ expr.elements.forEach(visitExpr);
545
+ }
546
+ else if (expr.kind === 'unary' || expr.kind === 'update') {
547
+ visitExpr(expr.arg);
548
+ }
549
+ else if (expr.kind === 'binary' || expr.kind === 'logical') {
550
+ visitExpr(expr.left);
551
+ visitExpr(expr.right);
552
+ }
553
+ else if (expr.kind === 'conditional') {
554
+ visitExpr(expr.test);
555
+ visitExpr(expr.consequent);
556
+ visitExpr(expr.alternate);
557
+ }
558
+ };
559
+ statements.forEach(visitStatement);
560
+ return fields;
561
+ }
562
+ function collectArrayItemFieldReadHints(context, statements, arrayField, indexName) {
563
+ const hints = new Map();
564
+ const merge = (field, hint) => {
565
+ if (hint === 'any')
566
+ return;
567
+ const previous = hints.get(field);
568
+ if (!previous) {
569
+ hints.set(field, hint);
570
+ }
571
+ else if (previous !== hint) {
572
+ hints.set(field, 'any');
573
+ }
574
+ };
575
+ const assignmentTargetHint = (target) => {
576
+ const field = thisFieldName(target);
577
+ if (field)
578
+ return fieldHint(context.store, field);
579
+ const item = thisArrayItemFieldTarget(target);
580
+ if (item)
581
+ return arrayItemFieldHint(context.store, item.arrayField, item.itemField);
582
+ return assignmentHint(target);
583
+ };
584
+ const visitStatement = (statement) => {
585
+ if (statement.kind === 'var') {
586
+ if (statement.init)
587
+ visitExpr(statement.init, 'any');
588
+ }
589
+ else if (statement.kind === 'assign') {
590
+ visitExpr(statement.value, assignmentTargetHint(statement.target));
591
+ }
592
+ else if (statement.kind === 'expr') {
593
+ visitExpr(statement.expr, 'any');
594
+ }
595
+ else if (statement.kind === 'return') {
596
+ if (statement.value)
597
+ visitExpr(statement.value, 'any');
598
+ }
599
+ else if (statement.kind === 'if') {
600
+ visitExpr(statement.test, 'boolean');
601
+ statement.consequent.forEach(visitStatement);
602
+ statement.alternate?.forEach(visitStatement);
603
+ }
604
+ else if (statement.kind === 'for') {
605
+ if (statement.init)
606
+ visitStatement(statement.init);
607
+ if (statement.test)
608
+ visitExpr(statement.test, 'boolean');
609
+ if (statement.update)
610
+ visitExpr(statement.update, 'number');
611
+ statement.body.forEach(visitStatement);
612
+ }
613
+ };
614
+ const visitExpr = (expr, hint) => {
615
+ const item = thisArrayItemFieldTarget(expr);
616
+ if (item && item.arrayField === arrayField && item.index.kind === 'identifier' && item.index.name === indexName) {
617
+ merge(item.itemField, hint);
618
+ }
619
+ if (expr.kind === 'member') {
620
+ visitExpr(expr.object, 'any');
621
+ }
622
+ else if (expr.kind === 'index') {
623
+ visitExpr(expr.object, 'any');
624
+ visitExpr(expr.index, 'number');
625
+ }
626
+ else if (expr.kind === 'call') {
627
+ visitExpr(expr.callee, 'any');
628
+ expr.args.forEach((arg) => visitExpr(arg, 'any'));
629
+ }
630
+ else if (expr.kind === 'object') {
631
+ expr.fields.forEach((field) => visitExpr(field.value, 'any'));
632
+ }
633
+ else if (expr.kind === 'array') {
634
+ expr.elements.forEach((element) => visitExpr(element, 'any'));
635
+ }
636
+ else if (expr.kind === 'unary' || expr.kind === 'update') {
637
+ visitExpr(expr.arg, expr.kind === 'unary' && expr.op === '!' ? 'boolean' : 'number');
638
+ }
639
+ else if (expr.kind === 'binary' || expr.kind === 'logical') {
640
+ const op = expr.op === '===' ? '==' : expr.op === '!==' ? '!=' : expr.op;
641
+ if (op === '+' && (hint === 'string' || expressionContainsKnownString(context, expr.left) || expressionContainsKnownString(context, expr.right))) {
642
+ visitExpr(expr.left, 'string');
643
+ visitExpr(expr.right, 'string');
644
+ }
645
+ else if ((op === '==' || op === '!=') && (expressionContainsKnownString(context, expr.left) || expressionContainsKnownString(context, expr.right))) {
646
+ visitExpr(expr.left, 'string');
647
+ visitExpr(expr.right, 'string');
648
+ }
649
+ else if (op === '&&' || op === '||') {
650
+ visitExpr(expr.left, 'boolean');
651
+ visitExpr(expr.right, 'boolean');
652
+ }
653
+ else {
654
+ visitExpr(expr.left, 'number');
655
+ visitExpr(expr.right, 'number');
656
+ }
657
+ }
658
+ else if (expr.kind === 'conditional') {
659
+ visitExpr(expr.test, 'boolean');
660
+ visitExpr(expr.consequent, hint);
661
+ visitExpr(expr.alternate, hint);
662
+ }
663
+ };
664
+ statements.forEach(visitStatement);
665
+ return hints;
666
+ }
667
+ function expressionContainsKnownString(context, expr) {
668
+ if (expr.kind === 'string')
669
+ return true;
670
+ if (expr.kind === 'identifier') {
671
+ if (typeof context.constants.get(expr.name) === 'string')
672
+ return true;
673
+ if (context.paramHints.get(expr.name) === 'string')
674
+ return true;
675
+ return false;
676
+ }
677
+ if (expr.kind === 'member') {
678
+ const field = thisFieldName(expr);
679
+ if (field && fieldHint(context.store, field) === 'string')
680
+ return true;
681
+ const item = thisArrayItemFieldTarget(expr);
682
+ if (item && arrayItemFieldHint(context.store, item.arrayField, item.itemField) === 'string')
683
+ return true;
684
+ const aliasField = arrayElementAliasFieldTarget(context, expr);
685
+ if (aliasField && arrayItemFieldHint(context.store, aliasField.alias.arrayField, aliasField.itemField) === 'string')
686
+ return true;
687
+ return expressionContainsKnownString(context, expr.object);
688
+ }
689
+ if (expr.kind === 'binary' || expr.kind === 'logical') {
690
+ return expressionContainsKnownString(context, expr.left) || expressionContainsKnownString(context, expr.right);
691
+ }
692
+ if (expr.kind === 'conditional') {
693
+ return expressionContainsKnownString(context, expr.consequent) || expressionContainsKnownString(context, expr.alternate);
694
+ }
695
+ return false;
696
+ }
697
+ function mutatesArrayShape(statements, arrayField) {
698
+ const visitStatement = (statement) => {
699
+ if (statement.kind === 'assign')
700
+ return thisArrayLengthTarget(statement.target) === arrayField || visitExpr(statement.value);
701
+ if (statement.kind === 'var')
702
+ return statement.init ? visitExpr(statement.init) : false;
703
+ if (statement.kind === 'expr')
704
+ return visitExpr(statement.expr);
705
+ if (statement.kind === 'return')
706
+ return statement.value ? visitExpr(statement.value) : false;
707
+ if (statement.kind === 'if')
708
+ return visitExpr(statement.test) || statement.consequent.some(visitStatement) || Boolean(statement.alternate?.some(visitStatement));
709
+ if (statement.kind === 'for') {
710
+ return Boolean(statement.init && visitStatement(statement.init)) || Boolean(statement.test && visitExpr(statement.test)) || Boolean(statement.update && visitExpr(statement.update)) || statement.body.some(visitStatement);
711
+ }
712
+ return false;
713
+ };
714
+ const visitExpr = (expr) => {
715
+ if (thisArrayPushTarget(expr) === arrayField)
716
+ return true;
717
+ if (expr.kind === 'member')
718
+ return visitExpr(expr.object);
719
+ if (expr.kind === 'index')
720
+ return visitExpr(expr.object) || visitExpr(expr.index);
721
+ if (expr.kind === 'call')
722
+ return visitExpr(expr.callee) || expr.args.some(visitExpr);
723
+ if (expr.kind === 'object')
724
+ return expr.fields.some((field) => visitExpr(field.value));
725
+ if (expr.kind === 'array')
726
+ return expr.elements.some(visitExpr);
727
+ if (expr.kind === 'unary' || expr.kind === 'update')
728
+ return visitExpr(expr.arg);
729
+ if (expr.kind === 'binary' || expr.kind === 'logical')
730
+ return visitExpr(expr.left) || visitExpr(expr.right);
731
+ if (expr.kind === 'conditional')
732
+ return visitExpr(expr.test) || visitExpr(expr.consequent) || visitExpr(expr.alternate);
733
+ return false;
734
+ };
735
+ return statements.some(visitStatement);
736
+ }
737
+ function arrayItemFieldAlias(context, item) {
738
+ return item.index.kind === 'identifier'
739
+ ? context.arrayItemFieldAliases.get(arrayItemFieldAliasKey(item.arrayField, item.index.name, item.itemField)) ?? null
740
+ : null;
741
+ }
742
+ // True when the named store array field reuses geatsc's `::__gea_type_<Name>`
743
+ // struct (the interface-reuse path) rather than a synthesized
744
+ // `<Store>_<field>_item`. The reused struct presence-gates its dynamic surface
745
+ // (`__gea_to_value`/`__gea_json_into`/`gea_cpp_key`) on `__gea_has_<field>`, so
746
+ // a direct member write must ALSO set that flag or the change is invisible to
747
+ // snapshots/change-records/JSON.stringify. Synthesized structs have no such
748
+ // member, so this returns false for them and nothing is appended.
749
+ function arrayFieldReusesInterfaceStruct(store, arrayFieldName) {
750
+ const field = store.fields.find((candidate) => candidate.name === arrayFieldName);
751
+ return field?.typedStorage?.useInterfaceStruct === true;
752
+ }
753
+ // `<itemObjectExpr>.__gea_has_<field> = true` — the presence-flag write that
754
+ // must accompany a direct member assignment on a reused interface struct.
755
+ // `itemObjectExpr` is the SAME object reference the direct field write goes
756
+ // through (an alias or the bounds-checked array item temp).
757
+ function presenceFlagAssignment(itemObjectExpr, itemFieldName) {
758
+ return `${itemObjectExpr}.__gea_has_${sanitizeCppIdentifier(itemFieldName)} = true`;
759
+ }
760
+ function lowerAssignment(context, target, value, statementOnly = false) {
761
+ const field = thisFieldName(target);
762
+ if (field) {
763
+ context.needsFieldSet = true;
764
+ // Empty array literal → the field's OWN declared (typed) empty value, not a
765
+ // generic vector<gea_cpp_value>: the per-field item struct isn't constructible
766
+ // from gea_cpp_value, so the generic form wouldn't convert. decltype yields the
767
+ // exact element type (e.g. std::vector<Store_field_item>{}).
768
+ if (value.kind === 'array' && value.elements.length === 0) {
769
+ const member = `(*this).${sanitizeCppIdentifier(field)}`;
770
+ return `set_field(${JSON.stringify(field)}, ${member}, decltype(${member}){})`;
771
+ }
772
+ const expr = lowerExpr(context, value, fieldHint(context.store, field));
773
+ return expr ? `set_field(${JSON.stringify(field)}, (*this).${sanitizeCppIdentifier(field)}, ${expr})` : null;
774
+ }
775
+ const lengthField = thisArrayLengthTarget(target);
776
+ if (lengthField) {
777
+ context.needsArrayLengthSet = true;
778
+ const expr = lowerExpr(context, value, 'number');
779
+ return expr ? `set_array_length(${JSON.stringify(lengthField)}, (*this).${sanitizeCppIdentifier(lengthField)}, static_cast<std::size_t>(${expr}))` : null;
780
+ }
781
+ const item = thisArrayItemFieldTarget(target);
782
+ if (item) {
783
+ context.needsArrayItemSet = true;
784
+ const index = lowerExpr(context, item.index, 'number');
785
+ const expr = lowerExpr(context, value, arrayItemFieldHint(context.store, item.arrayField, item.itemField));
786
+ if (!index || !expr)
787
+ return null;
788
+ const alias = arrayItemFieldAlias(context, item);
789
+ const stored = alias ? `(${alias} = ${expr}, ${alias})` : expr;
790
+ const array = `(*this).${sanitizeCppIdentifier(item.arrayField)}`;
791
+ const itemAlias = item.index.kind === 'identifier' ? context.arrayItemAliases.get(arrayItemAliasKey(item.arrayField, item.index.name)) : undefined;
792
+ const indexTemp = nextStoreMethodTemp(context, 'index');
793
+ const itemObjectExpr = itemAlias ?? `${array}[${indexTemp}]`;
794
+ const directAccess = typedArrayItemFieldAccess(context.store, item.arrayField, item.itemField, itemObjectExpr);
795
+ if (directAccess) {
796
+ context.dirtyArrayFields.add(item.arrayField);
797
+ const markDirtyOnce = `mark_dirty_array_field_once_${sanitizeCppIdentifier(item.arrayField)}`;
798
+ // Interface-reuse structs presence-gate their dynamic surface on
799
+ // `__gea_has_<field>`; set it alongside the member write so the value is
800
+ // visible to snapshots/change-records/JSON.stringify. Synthesized structs
801
+ // have no such member, so this is empty for them.
802
+ const reusesInterfaceStruct = arrayFieldReusesInterfaceStruct(context.store, item.arrayField);
803
+ if (itemAlias) {
804
+ const setPresence = reusesInterfaceStruct ? `, ${presenceFlagAssignment(itemObjectExpr, item.itemField)}` : '';
805
+ if (statementOnly) {
806
+ const setPresenceStmt = reusesInterfaceStruct ? ` ${presenceFlagAssignment(itemObjectExpr, item.itemField)};` : '';
807
+ return `{ ${markDirtyOnce}(); ${directAccess} = ${stored};${setPresenceStmt} }`;
808
+ }
809
+ return `(${markDirtyOnce}(), ${directAccess} = ${stored}${setPresence})`;
810
+ }
811
+ const setPresence = reusesInterfaceStruct ? ` ${presenceFlagAssignment(itemObjectExpr, item.itemField)};` : '';
812
+ if (statementOnly) {
813
+ return `{ ${markDirtyOnce}(); auto ${indexTemp} = static_cast<std::size_t>(${index}); if (${indexTemp} >= ${array}.size()) ${array}.resize(${indexTemp} + 1); auto __gea_value = ${stored}; ${directAccess} = __gea_value;${setPresence} }`;
814
+ }
815
+ return `([&]() { ${markDirtyOnce}(); auto ${indexTemp} = static_cast<std::size_t>(${index}); if (${indexTemp} >= ${array}.size()) ${array}.resize(${indexTemp} + 1); auto __gea_value = ${stored}; ${directAccess} = __gea_value;${setPresence} return __gea_value; })()`;
816
+ }
817
+ context.needsDynamicArrayItemSet = true;
818
+ return `set_array_item_field(${JSON.stringify(item.arrayField)}, (*this).${sanitizeCppIdentifier(item.arrayField)}, static_cast<std::size_t>(${index}), ${JSON.stringify(item.itemField)}, ${stored})`;
819
+ }
820
+ const aliasField = arrayElementAliasFieldTarget(context, target);
821
+ if (aliasField) {
822
+ const { alias, itemField } = aliasField;
823
+ context.needsArrayItemSet = true;
824
+ const expr = lowerExpr(context, value, arrayItemFieldHint(context.store, alias.arrayField, itemField));
825
+ if (!expr)
826
+ return null;
827
+ const directAccess = typedArrayItemFieldAccess(context.store, alias.arrayField, itemField, alias.itemExpression);
828
+ if (directAccess) {
829
+ context.dirtyArrayFields.add(alias.arrayField);
830
+ const markDirtyOnce = `mark_dirty_array_field_once_${sanitizeCppIdentifier(alias.arrayField)}`;
831
+ const reusesInterfaceStruct = arrayFieldReusesInterfaceStruct(context.store, alias.arrayField);
832
+ const setPresence = reusesInterfaceStruct ? `, ${presenceFlagAssignment(alias.itemExpression, itemField)}` : '';
833
+ if (statementOnly) {
834
+ const setPresenceStmt = reusesInterfaceStruct ? ` ${presenceFlagAssignment(alias.itemExpression, itemField)};` : '';
835
+ return `{ ${markDirtyOnce}(); ${directAccess} = ${expr};${setPresenceStmt} }`;
836
+ }
837
+ return `(${markDirtyOnce}(), ${directAccess} = ${expr}${setPresence})`;
838
+ }
839
+ context.needsDynamicArrayItemSet = true;
840
+ return `set_array_item_field(${JSON.stringify(alias.arrayField)}, (*this).${sanitizeCppIdentifier(alias.arrayField)}, ${alias.indexExpression}, ${JSON.stringify(itemField)}, ${expr})`;
841
+ }
842
+ // Whole-element assignment `this.arr[i] = v`. Without this case the target
843
+ // falls through to the generic lowering, whose index read is a bounds-checked
844
+ // BY-VALUE lambda — assigning into that temporary silently no-ops (weather's
845
+ // fetch-queue shift returned the same head forever, so only the first city of
846
+ // every queue rebuild ever fetched). Emit a real lvalue write with the same
847
+ // dirty-once marking as item-field sets.
848
+ if (target.kind === 'index') {
849
+ const arrayField = thisFieldName(target.object);
850
+ if (arrayField) {
851
+ context.needsArrayItemSet = true;
852
+ context.dirtyArrayFields.add(arrayField);
853
+ const index = lowerExpr(context, target.index, 'number');
854
+ const expr = lowerExpr(context, value, 'any');
855
+ if (!index || !expr)
856
+ return null;
857
+ const array = `(*this).${sanitizeCppIdentifier(arrayField)}`;
858
+ const markDirtyOnce = `mark_dirty_array_field_once_${sanitizeCppIdentifier(arrayField)}`;
859
+ const indexTemp = nextStoreMethodTemp(context, 'index');
860
+ if (statementOnly) {
861
+ return `{ ${markDirtyOnce}(); auto ${indexTemp} = static_cast<std::size_t>(${index}); if (${indexTemp} >= ${array}.size()) ${array}.resize(${indexTemp} + 1); auto __gea_value = ${expr}; ${array}[${indexTemp}] = __gea_value; }`;
862
+ }
863
+ return `([&]() { ${markDirtyOnce}(); auto ${indexTemp} = static_cast<std::size_t>(${index}); if (${indexTemp} >= ${array}.size()) ${array}.resize(${indexTemp} + 1); auto __gea_value = ${expr}; ${array}[${indexTemp}] = __gea_value; return __gea_value; })()`;
864
+ }
865
+ }
866
+ const hostSetter = hostFacadePropertySetter(exprPath(target));
867
+ if (hostSetter) {
868
+ const rhs = lowerExpr(context, value, hostSetter.hint);
869
+ return rhs ? `${hostSetter.target}(${rhs})` : null;
870
+ }
871
+ const globalField = globalStoreFieldTarget(context, target);
872
+ if (globalField) {
873
+ const rhs = value.kind === 'array' && value.elements.length === 0
874
+ ? `decltype(${globalField.access}){}`
875
+ : lowerExpr(context, value, globalField.hint);
876
+ if (!rhs)
877
+ return null;
878
+ if (statementOnly) {
879
+ return `{ auto &__gea_store = ${globalField.storeAccess}; auto __gea_value = ${rhs}; __gea_store->${globalField.fieldName} = __gea_value; if constexpr (requires { __gea_store->__gea_hub.notify(${JSON.stringify(globalField.fieldName)}); }) __gea_store->__gea_hub.notify(${JSON.stringify(globalField.fieldName)}); }`;
880
+ }
881
+ return `([&]() { auto &__gea_store = ${globalField.storeAccess}; auto __gea_value = ${rhs}; __gea_store->${globalField.fieldName} = __gea_value; if constexpr (requires { __gea_store->__gea_hub.notify(${JSON.stringify(globalField.fieldName)}); }) __gea_store->__gea_hub.notify(${JSON.stringify(globalField.fieldName)}); return __gea_store->${globalField.fieldName}; })()`;
882
+ }
883
+ const lhs = lowerExpr(context, target, 'any');
884
+ const rhs = lowerExpr(context, value, assignmentHint(target));
885
+ return lhs && rhs ? `${lhs} = ${rhs}` : null;
886
+ }
887
+ function hostFacadePropertySetter(path) {
888
+ if (!path)
889
+ return null;
890
+ const setters = {
891
+ 'Display.orientation': { target: 'gea::host::Display.setOrientation', hint: 'string' },
892
+ 'display.orientation': { target: 'gea::host::Display.setOrientation', hint: 'string' },
893
+ '__gea_Display.orientation': { target: 'gea::host::Display.setOrientation', hint: 'string' },
894
+ 'Display.supportedOrientations': { target: 'gea::host::Display.setSupportedOrientations', hint: 'any' },
895
+ 'display.supportedOrientations': { target: 'gea::host::Display.setSupportedOrientations', hint: 'any' },
896
+ '__gea_Display.supportedOrientations': { target: 'gea::host::Display.setSupportedOrientations', hint: 'any' },
897
+ 'Display.autoRotate': { target: 'gea::host::Display.setAutoRotate', hint: 'boolean' },
898
+ 'display.autoRotate': { target: 'gea::host::Display.setAutoRotate', hint: 'boolean' },
899
+ '__gea_Display.autoRotate': { target: 'gea::host::Display.setAutoRotate', hint: 'boolean' },
900
+ 'Display.pixelFormat': { target: 'gea::host::Display.setPixelFormat', hint: 'string' },
901
+ 'display.pixelFormat': { target: 'gea::host::Display.setPixelFormat', hint: 'string' },
902
+ '__gea_Display.pixelFormat': { target: 'gea::host::Display.setPixelFormat', hint: 'string' },
903
+ };
904
+ return setters[path] ?? null;
905
+ }
906
+ // Exported for test coverage: the change-record snapshot gating
907
+ // (has_queued_consumers) must never regress to eager gea_cpp_key(array)
908
+ // whole-vector boxing.
909
+ export function mutationHelpers(context) {
910
+ if (!needsMutationHelpers(context))
911
+ return [];
912
+ const typedOnlyStore = storeHubEmissionEnabled() && !storeDynamicFallbackEnabled();
913
+ // Dirty keys are always string LITERALS from the re-lowered bodies (static
914
+ // lifetime), so the per-call scratch list holds pointers — no heap alloc per
915
+ // marked field per method invocation.
916
+ const lines = [
917
+ ' std::vector<const char *> dirty_fields;',
918
+ ...(context.needsArrayItemSet && !typedOnlyStore ? [' std::vector<std::pair<std::string, gea_cpp_value>> dirty_array_fields;'] : []),
919
+ ' auto mark_dirty_field = [&dirty_fields](const char *key) mutable -> void {',
920
+ ' const char *dirty_key = key ? key : "";',
921
+ ' for (const auto &existing : dirty_fields) {',
922
+ ' if (std::strcmp(existing, dirty_key) == 0) return;',
923
+ ' }',
924
+ ' dirty_fields.push_back(dirty_key);',
925
+ ' };',
926
+ ];
927
+ if (context.needsArrayItemSet && typedOnlyStore) {
928
+ for (const field of [...context.dirtyArrayFields].sort()) {
929
+ const safeField = sanitizeCppIdentifier(field);
930
+ lines.push(` bool __gea_dirty_array_field_${safeField} = false;`, ` auto mark_dirty_array_field_once_${safeField} = [&mark_dirty_field, &__gea_dirty_array_field_${safeField}]() mutable -> void {`, ` if (__gea_dirty_array_field_${safeField}) return;`, ` mark_dirty_field(${JSON.stringify(field)});`, ` __gea_dirty_array_field_${safeField} = true;`, ' };');
931
+ }
932
+ }
933
+ else if (context.needsArrayItemSet) {
934
+ lines.push(' auto mark_dirty_array_field = [this, &dirty_array_fields](const char *key, const auto &array) mutable -> void {', ' const char *dirty_key = key ? key : "";', ' for (const auto &existing : dirty_array_fields) {', ' if (existing.first == dirty_key) return;', ' }', ' auto self_value = this->__gea_ctor_return_value;', ' auto state = gea_cpp_key(__gea_global__priv().get(self_value));', ' auto previous = gea_ir::storeHasQueuedConsumers(state, key) ? gea_cpp_snapshot_value(gea_cpp_key(array)) : gea_cpp_value::missing();', ' dirty_array_fields.push_back({std::string(dirty_key), std::move(previous)});', ' };');
935
+ for (const field of [...context.dirtyArrayFields].sort()) {
936
+ const safeField = sanitizeCppIdentifier(field);
937
+ lines.push(` bool __gea_dirty_array_field_${safeField} = false;`, ` auto mark_dirty_array_field_once_${safeField} = [this, &mark_dirty_field, &mark_dirty_array_field, &__gea_dirty_array_field_${safeField}]() mutable -> void {`, ` if (__gea_dirty_array_field_${safeField}) return;`, ` mark_dirty_array_field(${JSON.stringify(field)}, (*this).${safeField});`, ` mark_dirty_field(${JSON.stringify(field)});`, ` __gea_dirty_array_field_${safeField} = true;`, ' };');
938
+ }
939
+ }
940
+ lines.push(...(context.needsArrayItemSet && !typedOnlyStore
941
+ ? [' auto flush_dirty_fields = [this, &dirty_fields, &dirty_array_fields]() mutable -> void {', ' if (dirty_fields.empty() && dirty_array_fields.empty()) return;']
942
+ : [' auto flush_dirty_fields = [this, &dirty_fields]() mutable -> void {', ' if (dirty_fields.empty()) return;']),
943
+ // Typed channel FIRST and unconditionally — the dynamic `direct` map may
944
+ // not exist (no boxed observers) while typed hub subscribers do. Only
945
+ // emitted when this program carries the hub (see decideStoreHubEmission).
946
+ ...(storeHubEmissionEnabled() ? [' for (const auto &__gea_hub_key : dirty_fields) (*this).__gea_hub.notify(__gea_hub_key);'] : []), ...(typedOnlyStore
947
+ ? [
948
+ ' dirty_fields.clear();',
949
+ ' return;',
950
+ ' };',
951
+ ]
952
+ : [
953
+ ' auto self_value = this->__gea_ctor_return_value;',
954
+ ' auto state = gea_cpp_key(__gea_global__priv().get(self_value));',
955
+ ]), ...(context.needsArrayItemSet && !typedOnlyStore
956
+ ? [
957
+ ' for (const auto &entry : dirty_array_fields) {',
958
+ ' if (entry.second.kind != gea_cpp_value::kind_t::missing) {',
959
+ ' (void)(fn__queue(self_value, state, entry.first, gea_ir::changeRecord(entry.second, self_value.record_get_literal(entry.first.c_str()))));',
960
+ ' }',
961
+ ' }',
962
+ ]
963
+ : []), ...(typedOnlyStore ? [] : [
964
+ ' auto direct_map = gea_cpp_key(state.record_get_literal("direct"));',
965
+ ' if (!gea::runtime::coerce::to_boolean(direct_map)) {',
966
+ ' dirty_fields.clear();',
967
+ ...(context.needsArrayItemSet ? [' dirty_array_fields.clear();'] : []),
968
+ ' return;',
969
+ ' }',
970
+ ' for (const auto &key : dirty_fields) {',
971
+ ' auto direct = gea_cpp_key(gea_cpp_map_like_get_literal(direct_map, key));',
972
+ ' if (!gea::runtime::coerce::to_boolean(direct)) continue;',
973
+ // Direct handlers registered via `bindReactiveApply` are zero-arg
974
+ // observers (`[apply, pending]() { schedule(apply, pending); }`) —
975
+ // they ignore the value entirely. Pre-fetching `self_value
976
+ // .record_get_literal(key)` here would trigger the store's
977
+ // `gea_cpp_key(typed_vec)` getter, which heap-allocates one record
978
+ // per element to box typed items into a gea_cpp_value array snapshot.
979
+ // For BallStore.balls (32 items) that's 32 wasted heap allocations
980
+ // per `flush_dirty_fields` call (i.e. per BallStore.tick() frame),
981
+ // observed as ~6 ms in raf. Pass `gea_cpp_value::missing()` instead
982
+ // — handlers that need the live value already re-read it themselves
983
+ // via the typed store pointer (see keyed-list `apply_typed_path`),
984
+ // and the dynamic-record proxy fallback path still snapshots when it
985
+ // calls handlers from its `set` trap with the actual new value.
986
+ ' for (auto &handler : direct) (void)handler(gea_cpp_value::missing());',
987
+ ' }',
988
+ ' dirty_fields.clear();',
989
+ ...(context.needsArrayItemSet && !typedOnlyStore ? [' dirty_array_fields.clear();'] : []),
990
+ ' };',
991
+ ]));
992
+ if (context.needsFieldSet) {
993
+ lines.push(' auto set_field = [this, &mark_dirty_field]<typename Field, typename Value>(const char *key, Field &field, Value value) mutable -> Value {', ' auto values_equal = []<typename Left, typename Right>(const Left &left, const Right &right) -> bool {', ' using L = std::decay_t<Left>;', ' using R = std::decay_t<Right>;', ' if constexpr (std::is_arithmetic_v<L> && std::is_arithmetic_v<R>) {', ' return gea_cpp_same_value_zero(static_cast<double>(left), static_cast<double>(right));', ' } else if constexpr (std::is_same_v<L, std::string> && std::is_same_v<R, std::string>) {', ' return left == right;', ' } else {', ' return false;', ' }', ' };', ' if (!values_equal(field, value)) {', ...(typedOnlyStore
994
+ ? [
995
+ ' gea_ir::storeAssignField(field, value);',
996
+ ' mark_dirty_field(key);',
997
+ ]
998
+ : [
999
+ ' auto self_value = this->__gea_ctor_return_value;',
1000
+ ' auto state = gea_cpp_key(__gea_global__priv().get(self_value));',
1001
+ ' const bool has_queued_consumers = gea_ir::storeHasQueuedConsumers(state, key);',
1002
+ ' auto old_value = has_queued_consumers ? gea_cpp_key(field) : gea_cpp_value::missing();',
1003
+ ' auto stored_value = has_queued_consumers ? gea_cpp_key(value) : gea_cpp_value::missing();',
1004
+ ' gea_ir::storeAssignField(field, value);',
1005
+ ' mark_dirty_field(key);',
1006
+ ' if (has_queued_consumers) {',
1007
+ ' (void)(fn__queue(self_value, state, std::string(key ? key : ""), gea_ir::changeRecord(old_value, stored_value)));',
1008
+ ' }',
1009
+ ]), ' }', ' return value;', ' };');
1010
+ }
1011
+ if (context.needsArrayLengthSet) {
1012
+ lines.push(
1013
+ // Change-record snapshots (gea_cpp_key(array)) box the ENTIRE typed
1014
+ // vector; only take them when a queued consumer will actually read the
1015
+ // change record — mirrors set_field's has_queued_consumers guard.
1016
+ ' auto set_array_length = [this, &mark_dirty_field]<typename Array>(const char *array_key, Array &array, std::size_t length) mutable -> double {', ' if (array.size() == length) return static_cast<double>(length);', ' array.resize(length);', ' mark_dirty_field(array_key);', ...(typedOnlyStore
1017
+ ? []
1018
+ : [
1019
+ ' auto self_value = this->__gea_ctor_return_value;',
1020
+ ' auto state = gea_cpp_key(__gea_global__priv().get(self_value));',
1021
+ ' const bool has_queued_consumers = gea_ir::storeHasQueuedConsumers(state, array_key);',
1022
+ ' auto old_value = has_queued_consumers ? gea_cpp_key(array) : gea_cpp_value::missing();',
1023
+ ' auto next_value = has_queued_consumers ? gea_cpp_key(array) : gea_cpp_value::missing();',
1024
+ ' if (has_queued_consumers) {',
1025
+ ' (void)(fn__queue(self_value, state, std::string(array_key ? array_key : ""), gea_ir::changeRecord(old_value, next_value)));',
1026
+ ' }',
1027
+ ]), ' return static_cast<double>(length);', ' };');
1028
+ }
1029
+ if (context.needsDynamicArrayItemSet) {
1030
+ // Dispatches statically on the array's element type. `gea_cpp_value`
1031
+ // arrays keep the dynamic record-slot path (back-compat for stores not
1032
+ // yet promoted to typed storage). Typed arrays (whose element type is a
1033
+ // synthesised `${storeClass}_${fieldName}_item` POD) write through
1034
+ // `gea_ir::set_typed_field`, which is generated per-item-type by the
1035
+ // gea plugin (see `generateTypedItemHelpers` in cpp-stores.ts) and
1036
+ // dispatches the property-name string to a real C++ field assignment.
1037
+ lines.push(...(typedOnlyStore
1038
+ ? [' auto set_array_item_field = [this, &mark_dirty_field]<typename Array, typename Value>(const char *array_key, Array &array, std::size_t index, const char *property, Value value) mutable -> Value {']
1039
+ : [' auto set_array_item_field = [this, &mark_dirty_field, &mark_dirty_array_field]<typename Array, typename Value>(const char *array_key, Array &array, std::size_t index, const char *property, Value value) mutable -> Value {']), ' using __GeaSlotElement = typename std::decay_t<Array>::value_type;', ...(typedOnlyStore ? [] : [' mark_dirty_array_field(array_key, array);']), ' if (index >= array.size()) array.resize(index + 1);', ' auto &slot = array[index];', ...(typedOnlyStore
1040
+ ? [' (void)sizeof(__GeaSlotElement);', ' gea_ir::set_typed_field(slot, property, value);']
1041
+ : [
1042
+ ' if constexpr (std::is_same_v<__GeaSlotElement, gea_cpp_value>) {',
1043
+ ' if (slot.is_nullish()) {',
1044
+ ' slot.kind = gea_cpp_value::kind_t::record;',
1045
+ ' slot.entries = std::make_shared<std::vector<std::pair<std::string, gea_cpp_value>>>();',
1046
+ ' }',
1047
+ ' slot.record_set_literal(property, gea_cpp_key(value));',
1048
+ ' slot.record_set(gea_ir::dirtySymbol(), gea_cpp_value(true));',
1049
+ ' } else {',
1050
+ ' gea_ir::set_typed_field(slot, property, value);',
1051
+ ' }',
1052
+ ]), ' mark_dirty_field(array_key);', ' return value;', ' };');
1053
+ }
1054
+ if (context.needsArrayPush) {
1055
+ lines.push(' auto push_array_items = [this, &mark_dirty_field]<typename Array, typename... Values>(const char *array_key, Array &array, Values... values) mutable -> double {', ' if constexpr (sizeof...(Values) > 0) {',
1056
+ // A typed-only store notifies through the SignalHub (mark_dirty_field →
1057
+ // flush_dirty_fields). The boxed change-record / queued-consumer notify
1058
+ // (self_value/_priv/storeHasQueuedConsumers/fn__queue) only exists in the
1059
+ // dynamic-fallback runtime, so gate it on !typedOnlyStore — otherwise it
1060
+ // references members a typed store does not carry.
1061
+ ...(typedOnlyStore
1062
+ ? []
1063
+ : [
1064
+ ' auto self_value = this->__gea_ctor_return_value;',
1065
+ ' auto state = gea_cpp_key(__gea_global__priv().get(self_value));',
1066
+ ' const bool has_queued_consumers = gea_ir::storeHasQueuedConsumers(state, array_key);',
1067
+ ' auto old_value = has_queued_consumers ? gea_cpp_key(array) : gea_cpp_value::missing();',
1068
+ ]),
1069
+ // Already-Element values (typed literal construction at the call site)
1070
+ // push straight through — no box + __gea_from_value round trip.
1071
+ ' auto push_one = [&]<typename Value>(Value value) mutable -> void {', ' using Element = typename std::decay_t<Array>::value_type;', ' if constexpr (std::is_same_v<std::decay_t<Value>, Element>) {', ' array.push_back(std::move(value));', ' } else if constexpr (requires(const gea_cpp_value &__gea_v) { Element::__gea_from_value(__gea_v); }) {', ' array.push_back(Element::__gea_from_value(gea_cpp_key(value)));', ' } else {', ' array.push_back(static_cast<Element>(gea_cpp_key(value)));', ' }', ' };', ' (push_one(values), ...);', ...(typedOnlyStore ? [] : [' auto next_value = has_queued_consumers ? gea_cpp_key(array) : gea_cpp_value::missing();']), ' mark_dirty_field(array_key);', ...(typedOnlyStore
1072
+ ? []
1073
+ : [
1074
+ ' if (has_queued_consumers) {',
1075
+ ' (void)(fn__queue(self_value, state, std::string(array_key ? array_key : ""), gea_ir::changeRecord(old_value, next_value)));',
1076
+ ' }',
1077
+ ]), ' }', ' return static_cast<double>(array.size());', ' };');
1078
+ }
1079
+ if (context.needsArrayUnshift) {
1080
+ lines.push(' auto unshift_array_items = [this, &mark_dirty_field]<typename Array, typename... Values>(const char *array_key, Array &array, Values... values) mutable -> double {', ' if constexpr (sizeof...(Values) > 0) {', ...(typedOnlyStore
1081
+ ? []
1082
+ : [
1083
+ ' auto self_value = this->__gea_ctor_return_value;',
1084
+ ' auto state = gea_cpp_key(__gea_global__priv().get(self_value));',
1085
+ ' const bool has_queued_consumers = gea_ir::storeHasQueuedConsumers(state, array_key);',
1086
+ ' auto old_value = has_queued_consumers ? gea_cpp_key(array) : gea_cpp_value::missing();',
1087
+ ]), ' using Element = typename std::decay_t<Array>::value_type;',
1088
+ // Already-Element values pass through; decodable elements use
1089
+ // __gea_from_value (the bare static_cast requires a converting ctor
1090
+ // interface-reuse structs do not have); everything else casts.
1091
+ ' auto __gea_make_insert = [&]<typename Value>(Value value) -> Element { if constexpr (std::is_same_v<std::decay_t<Value>, Element>) { return value; } else if constexpr (requires(const gea_cpp_value &__gea_v) { Element::__gea_from_value(__gea_v); }) { return Element::__gea_from_value(gea_cpp_key(value)); } else { return static_cast<Element>(gea_cpp_key(value)); } };', ' std::array<Element, sizeof...(Values)> __gea_inserts = {__gea_make_insert(values)...};', ' array.insert(array.begin(), std::make_move_iterator(__gea_inserts.begin()), std::make_move_iterator(__gea_inserts.end()));', ...(typedOnlyStore ? [] : [' auto next_value = has_queued_consumers ? gea_cpp_key(array) : gea_cpp_value::missing();']), ' mark_dirty_field(array_key);', ...(typedOnlyStore
1092
+ ? []
1093
+ : [
1094
+ ' if (has_queued_consumers) {',
1095
+ ' (void)(fn__queue(self_value, state, std::string(array_key ? array_key : ""), gea_ir::changeRecord(old_value, next_value)));',
1096
+ ' }',
1097
+ ]), ' }', ' return static_cast<double>(array.size());', ' };');
1098
+ }
1099
+ if (context.needsArraySplice) {
1100
+ lines.push(' auto splice_array_items = [this, &mark_dirty_field]<typename Array, typename... Values>(const char *array_key, Array &array, double start_raw, double delete_count_raw, Values... values) mutable -> Array {', ...(typedOnlyStore
1101
+ ? []
1102
+ : [
1103
+ ' auto self_value = this->__gea_ctor_return_value;',
1104
+ ' auto state = gea_cpp_key(__gea_global__priv().get(self_value));',
1105
+ ' const bool has_queued_consumers = gea_ir::storeHasQueuedConsumers(state, array_key);',
1106
+ ' auto old_value = has_queued_consumers ? gea_cpp_key(array) : gea_cpp_value::missing();',
1107
+ ]), ' const std::ptrdiff_t signed_size = static_cast<std::ptrdiff_t>(array.size());', ' std::ptrdiff_t start = static_cast<std::ptrdiff_t>(start_raw);', ' if (start < 0) start = std::max<std::ptrdiff_t>(0, signed_size + start);', ' if (start > signed_size) start = signed_size;', ' std::ptrdiff_t delete_count = static_cast<std::ptrdiff_t>(delete_count_raw);', ' if (delete_count < 0) delete_count = 0;', ' if (delete_count > signed_size - start) delete_count = signed_size - start;', ' auto removed_begin = array.begin() + start;', ' auto removed_end = removed_begin + delete_count;', ' Array removed(std::make_move_iterator(removed_begin), std::make_move_iterator(removed_end));', ' array.erase(removed_begin, removed_end);', ' if constexpr (sizeof...(Values) > 0) {', ' using Element = typename std::decay_t<Array>::value_type;', ' auto __gea_make_insert = [&]<typename Value>(Value value) -> Element { if constexpr (std::is_same_v<std::decay_t<Value>, Element>) { return value; } else if constexpr (requires(const gea_cpp_value &__gea_v) { Element::__gea_from_value(__gea_v); }) { return Element::__gea_from_value(gea_cpp_key(value)); } else { return static_cast<Element>(gea_cpp_key(value)); } };', ' std::array<Element, sizeof...(Values)> __gea_inserts = {__gea_make_insert(values)...};', ' array.insert(array.begin() + start, std::make_move_iterator(__gea_inserts.begin()), std::make_move_iterator(__gea_inserts.end()));', ' }', ...(typedOnlyStore ? [] : [' auto next_value = has_queued_consumers ? gea_cpp_key(array) : gea_cpp_value::missing();']), ' mark_dirty_field(array_key);', ...(typedOnlyStore
1108
+ ? []
1109
+ : [
1110
+ ' if (has_queued_consumers) {',
1111
+ ' (void)(fn__queue(self_value, state, std::string(array_key ? array_key : ""), gea_ir::changeRecord(old_value, next_value)));',
1112
+ ' }',
1113
+ ]), ' return removed;', ' };');
1114
+ }
1115
+ if (context.needsArrayPop || context.needsArrayShift) {
1116
+ const endIter = context.needsArrayPop;
1117
+ const beginIter = context.needsArrayShift;
1118
+ if (endIter) {
1119
+ lines.push(' auto pop_array_item = [this, &mark_dirty_field]<typename Array>(const char *array_key, Array &array) mutable -> typename Array::value_type {', ' using Element = typename Array::value_type;', ' if (array.empty()) return Element{};', ...(typedOnlyStore
1120
+ ? []
1121
+ : [
1122
+ ' auto self_value = this->__gea_ctor_return_value;',
1123
+ ' auto state = gea_cpp_key(__gea_global__priv().get(self_value));',
1124
+ ' const bool has_queued_consumers = gea_ir::storeHasQueuedConsumers(state, array_key);',
1125
+ ' auto old_value = has_queued_consumers ? gea_cpp_key(array) : gea_cpp_value::missing();',
1126
+ ]), ' Element removed = std::move(array.back());', ' array.pop_back();', ...(typedOnlyStore ? [] : [' auto next_value = has_queued_consumers ? gea_cpp_key(array) : gea_cpp_value::missing();']), ' mark_dirty_field(array_key);', ...(typedOnlyStore
1127
+ ? []
1128
+ : [
1129
+ ' if (has_queued_consumers) {',
1130
+ ' (void)(fn__queue(self_value, state, std::string(array_key ? array_key : ""), gea_ir::changeRecord(old_value, next_value)));',
1131
+ ' }',
1132
+ ]), ' return removed;', ' };');
1133
+ }
1134
+ if (beginIter) {
1135
+ lines.push(' auto shift_array_item = [this, &mark_dirty_field]<typename Array>(const char *array_key, Array &array) mutable -> typename Array::value_type {', ' using Element = typename Array::value_type;', ' if (array.empty()) return Element{};', ...(typedOnlyStore
1136
+ ? []
1137
+ : [
1138
+ ' auto self_value = this->__gea_ctor_return_value;',
1139
+ ' auto state = gea_cpp_key(__gea_global__priv().get(self_value));',
1140
+ ' const bool has_queued_consumers = gea_ir::storeHasQueuedConsumers(state, array_key);',
1141
+ ' auto old_value = has_queued_consumers ? gea_cpp_key(array) : gea_cpp_value::missing();',
1142
+ ]), ' Element removed = std::move(array.front());', ' array.erase(array.begin());', ...(typedOnlyStore ? [] : [' auto next_value = has_queued_consumers ? gea_cpp_key(array) : gea_cpp_value::missing();']), ' mark_dirty_field(array_key);', ...(typedOnlyStore
1143
+ ? []
1144
+ : [
1145
+ ' if (has_queued_consumers) {',
1146
+ ' (void)(fn__queue(self_value, state, std::string(array_key ? array_key : ""), gea_ir::changeRecord(old_value, next_value)));',
1147
+ ' }',
1148
+ ]), ' return removed;', ' };');
1149
+ }
1150
+ }
1151
+ // Open a keyed-list direct-dispatch batch for the duration of this method so
1152
+ // per-item writes (e.g. re-filling forecast rows) don't re-run each list's
1153
+ // .map on every write. Balanced by storeDirectBatchEnd() at every exit
1154
+ // (mutationFooter + flushBeforeReturn) — nested store calls share the
1155
+ // outermost batch and it flushes once when that one exits.
1156
+ if (!typedOnlyStore)
1157
+ lines.push(' gea_ir::storeDirectBatchBegin();');
1158
+ return rewritePrivStateLookups(lines);
1159
+ }
1160
+ // When the program carries the hub member block (which also hosts the
1161
+ // per-instance `_priv` state cache — see cpp-store-hub.ts), the mutation
1162
+ // helpers read the cached state record instead of re-probing the boxed
1163
+ // WeakMap on every mutating method call:
1164
+ // `auto self_value = <ctor value copy>` → const ref (no boxed copy; kept
1165
+ // because the fn__queue call sites pass it; gea_cpp_value's non-trivial
1166
+ // dtor keeps clang from warning where a site no longer uses it)
1167
+ // `auto state = key(_priv().get(self_value))` → `auto &state = cached ref`
1168
+ function rewritePrivStateLookups(lines) {
1169
+ if (!storeHubEmissionEnabled() || !storeDynamicFallbackEnabled())
1170
+ return lines;
1171
+ return lines.map((line) => {
1172
+ const indent = line.slice(0, line.length - line.trimStart().length);
1173
+ const body = line.trim();
1174
+ if (body === 'auto self_value = this->__gea_ctor_return_value;') {
1175
+ return `${indent}const auto &self_value = this->__gea_ctor_return_value;`;
1176
+ }
1177
+ if (body === 'auto state = gea_cpp_key(__gea_global__priv().get(self_value));') {
1178
+ return `${indent}auto &state = (*this).__gea_priv_state_ref();`;
1179
+ }
1180
+ return line;
1181
+ });
1182
+ }
1183
+ function mutationFooter(context) {
1184
+ if (!needsMutationHelpers(context))
1185
+ return [];
1186
+ return storeDynamicFallbackEnabled() ? [' flush_dirty_fields();', ' gea_ir::storeDirectBatchEnd();'] : [' flush_dirty_fields();'];
1187
+ }
1188
+ function flushBeforeReturn(context, pad) {
1189
+ if (!needsMutationHelpers(context))
1190
+ return [];
1191
+ return storeDynamicFallbackEnabled() ? [`${pad}flush_dirty_fields();`, `${pad}gea_ir::storeDirectBatchEnd();`] : [`${pad}flush_dirty_fields();`];
1192
+ }
1193
+ function needsMutationHelpers(context) {
1194
+ return (context.needsFieldSet ||
1195
+ context.needsArrayLengthSet ||
1196
+ context.needsArrayItemSet ||
1197
+ context.needsArrayPush ||
1198
+ context.needsArrayUnshift ||
1199
+ context.needsArraySplice ||
1200
+ context.needsArrayPop ||
1201
+ context.needsArrayShift);
1202
+ }
1203
+ // Mirror of `tryEmitConstNumericArrayLiteral` from the geatsc emitter
1204
+ // (`packages/geatsc/src/targets/cpp/emitter/variables.ts`), specialized for
1205
+ // the IR shape used by store-method body replacement. The plugin's
1206
+ // `replaceStoreMethodsFromIr` rebuilds method bodies from the captured IR
1207
+ // rather than from the geatsc-emitted text, so the geatsc-side fast path
1208
+ // never gets a chance to fire on locals declared inside store methods —
1209
+ // which is exactly where const piece-shape tables live in apps like
1210
+ // button-tetris. Without this mirror, the dynamic-vector lowering wins for
1211
+ // store-method bodies even after the geatsc pass has been taught the
1212
+ // constexpr form.
1213
+ function lowerConstLiteralMatrixDecl(name, init, pad) {
1214
+ const numeric = readNumericMatrixFromIr(init);
1215
+ if (numeric) {
1216
+ const elementType = narrowestNumericCppType(numeric.flat);
1217
+ if (numeric.shape === '2d') {
1218
+ const rowType = `std::array<${elementType}, ${numeric.cols}>`;
1219
+ const tableType = `std::array<${rowType}, ${numeric.rows}>`;
1220
+ const rows = numeric.values.map((row) => `${rowType}{${row.map((v) => formatNumericLiteral(v, elementType)).join(', ')}}`).join(', ');
1221
+ return [`${pad}static constexpr ${tableType} ${name} = {${rows}};`];
1222
+ }
1223
+ const items = numeric.values.map((v) => formatNumericLiteral(v, elementType)).join(', ');
1224
+ return [`${pad}static constexpr std::array<${elementType}, ${numeric.rows}> ${name} = {${items}};`];
1225
+ }
1226
+ const strings = readStringMatrixFromIr(init);
1227
+ if (strings) {
1228
+ // `const char*` is universally consumable: every place a string literal
1229
+ // is currently accepted (`std::string` ctor, `gea_cpp_value` ctor, the
1230
+ // typed `set_typed_field` `const char*` branch in the record helpers)
1231
+ // takes a `const char*` without any extra overload. The pointers
1232
+ // themselves live in .rodata; only the array of pointers is
1233
+ // materialized.
1234
+ if (strings.shape === '2d') {
1235
+ const rowType = `std::array<const char*, ${strings.cols}>`;
1236
+ const tableType = `std::array<${rowType}, ${strings.rows}>`;
1237
+ const rows = strings.values.map((row) => `${rowType}{${row.map(formatStringLiteral).join(', ')}}`).join(', ');
1238
+ return [`${pad}static constexpr ${tableType} ${name} = {${rows}};`];
1239
+ }
1240
+ const items = strings.values.map(formatStringLiteral).join(', ');
1241
+ return [`${pad}static constexpr std::array<const char*, ${strings.rows}> ${name} = {${items}};`];
1242
+ }
1243
+ const objects = readObjectMatrixFromIr(init);
1244
+ if (objects) {
1245
+ // Mirror of the geatsc top-level path
1246
+ // (`packages/geatsc/src/targets/cpp/emitter/variables.ts`'s object-matrix
1247
+ // branch). Lower a homogeneous `const X = [{ a: 1, b: 'x' }, ...]` to a
1248
+ // function-local POD struct + `static constexpr std::array<__row, N>`.
1249
+ // Per-field element type is the narrowest signed integer for numeric
1250
+ // columns, `bool` for boolean columns, `const char*` for string columns.
1251
+ // The struct is a literal type so the array sits in .rodata and
1252
+ // `tbl[i].field` compiles to one load.
1253
+ //
1254
+ // The struct also exposes a `__gea_to_value()` member so the
1255
+ // `gea_cpp_value(const T&)` catch-all template ctor (which probes for
1256
+ // `value.__gea_to_value()`) can box a row when generic emitter paths
1257
+ // wrap array access in `static_cast<gea_cpp_value>(__array[i])`. Typed
1258
+ // field reads (`row.x`) bypass this and go through the access lambda's
1259
+ // typed branch.
1260
+ const rowTypeName = `__const_${name}_row`;
1261
+ const fieldDecls = objects.fields
1262
+ .map((f) => `${cppTypeForObjectMatrixFieldFromIr(objects, f)} ${f.name};`)
1263
+ .join(' ');
1264
+ const setEntries = objects.fields
1265
+ .map((f) => `__gea_out.record_set_literal(${formatStringLiteral(f.name)}, gea_cpp_value(this->${f.name}));`)
1266
+ .join(' ');
1267
+ const toValueBody = `gea_cpp_value __gea_out; __gea_out.kind = gea_cpp_value::kind_t::record; ` +
1268
+ `__gea_out.entries = std::make_shared<std::vector<std::pair<std::string, gea_cpp_value>>>(); ` +
1269
+ `${setEntries} return __gea_out;`;
1270
+ const rowInits = objects.values
1271
+ .map((row) => {
1272
+ const cells = objects.fields.map((f) => formatObjectMatrixCellFromIr(row[f.name], f, objects));
1273
+ return `${rowTypeName}{${cells.join(', ')}}`;
1274
+ })
1275
+ .join(', ');
1276
+ return [
1277
+ `${pad}struct ${rowTypeName} { ${fieldDecls} gea_cpp_value __gea_to_value() const { ${toValueBody} } };`,
1278
+ `${pad}static constexpr std::array<${rowTypeName}, ${objects.rows}> ${name} = {${rowInits}};`,
1279
+ ];
1280
+ }
1281
+ return null;
1282
+ }
1283
+ function readNumericMatrixFromIr(expr) {
1284
+ if (expr.kind !== 'array' || expr.elements.length === 0)
1285
+ return null;
1286
+ if (expr.elements.every((e) => e.kind === 'array')) {
1287
+ const rowExprs = expr.elements;
1288
+ const cols = rowExprs[0].elements.length;
1289
+ if (cols === 0)
1290
+ return null;
1291
+ const rows = [];
1292
+ const flat = [];
1293
+ for (const row of rowExprs) {
1294
+ if (row.elements.length !== cols)
1295
+ return null;
1296
+ const out = [];
1297
+ for (const cell of row.elements) {
1298
+ const v = readNumericLeafFromIr(cell);
1299
+ if (v === null)
1300
+ return null;
1301
+ out.push(v);
1302
+ flat.push(v);
1303
+ }
1304
+ rows.push(out);
1305
+ }
1306
+ return { shape: '2d', rows: rowExprs.length, cols, values: rows, flat };
1307
+ }
1308
+ const flat = [];
1309
+ for (const cell of expr.elements) {
1310
+ const v = readNumericLeafFromIr(cell);
1311
+ if (v === null)
1312
+ return null;
1313
+ flat.push(v);
1314
+ }
1315
+ return { shape: '1d', rows: flat.length, cols: 0, values: flat, flat };
1316
+ }
1317
+ function readStringMatrixFromIr(expr) {
1318
+ if (expr.kind !== 'array' || expr.elements.length === 0)
1319
+ return null;
1320
+ if (expr.elements.every((e) => e.kind === 'array')) {
1321
+ const rowExprs = expr.elements;
1322
+ const cols = rowExprs[0].elements.length;
1323
+ if (cols === 0)
1324
+ return null;
1325
+ const rows = [];
1326
+ for (const row of rowExprs) {
1327
+ if (row.elements.length !== cols)
1328
+ return null;
1329
+ const out = [];
1330
+ for (const cell of row.elements) {
1331
+ if (cell.kind !== 'string')
1332
+ return null;
1333
+ out.push(cell.value);
1334
+ }
1335
+ rows.push(out);
1336
+ }
1337
+ return { shape: '2d', rows: rowExprs.length, cols, values: rows };
1338
+ }
1339
+ const flat = [];
1340
+ for (const cell of expr.elements) {
1341
+ if (cell.kind !== 'string')
1342
+ return null;
1343
+ flat.push(cell.value);
1344
+ }
1345
+ return { shape: '1d', rows: flat.length, cols: 0, values: flat };
1346
+ }
1347
+ function readObjectMatrixFromIr(expr) {
1348
+ if (expr.kind !== 'array' || expr.elements.length === 0)
1349
+ return null;
1350
+ if (!expr.elements.every((e) => e.kind === 'object'))
1351
+ return null;
1352
+ const objExprs = expr.elements;
1353
+ const schema = [];
1354
+ for (const prop of objExprs[0].fields) {
1355
+ const valueType = readObjectFieldValueTypeFromIr(prop.value);
1356
+ if (!valueType)
1357
+ return null;
1358
+ schema.push({ name: prop.name, valueType });
1359
+ }
1360
+ if (schema.length === 0)
1361
+ return null;
1362
+ const values = [];
1363
+ for (const obj of objExprs) {
1364
+ if (obj.fields.length !== schema.length)
1365
+ return null;
1366
+ const row = {};
1367
+ for (let i = 0; i < schema.length; i++) {
1368
+ const prop = obj.fields[i];
1369
+ if (prop.name !== schema[i].name)
1370
+ return null;
1371
+ const value = readObjectFieldValueFromIr(prop.value, schema[i].valueType);
1372
+ if (value === null)
1373
+ return null;
1374
+ row[schema[i].name] = value;
1375
+ }
1376
+ values.push(row);
1377
+ }
1378
+ return { shape: '1d', rows: values.length, fields: schema, values };
1379
+ }
1380
+ function readObjectFieldValueTypeFromIr(expr) {
1381
+ if (expr.kind === 'number')
1382
+ return 'number';
1383
+ if (expr.kind === 'unary' && (expr.op === '-' || expr.op === '+') && expr.arg.kind === 'number')
1384
+ return 'number';
1385
+ if (expr.kind === 'string')
1386
+ return 'string';
1387
+ if (expr.kind === 'boolean')
1388
+ return 'boolean';
1389
+ return null;
1390
+ }
1391
+ function readObjectFieldValueFromIr(expr, type) {
1392
+ if (type === 'number')
1393
+ return readNumericLeafFromIr(expr);
1394
+ if (type === 'string')
1395
+ return expr.kind === 'string' ? expr.value : null;
1396
+ if (type === 'boolean')
1397
+ return expr.kind === 'boolean' ? expr.value : null;
1398
+ return null;
1399
+ }
1400
+ function cppTypeForObjectMatrixFieldFromIr(matrix, field) {
1401
+ if (field.valueType === 'string')
1402
+ return 'const char*';
1403
+ if (field.valueType === 'boolean')
1404
+ return 'bool';
1405
+ const column = [];
1406
+ for (const row of matrix.values)
1407
+ column.push(row[field.name]);
1408
+ return narrowestNumericCppType(column);
1409
+ }
1410
+ function formatObjectMatrixCellFromIr(value, field, matrix) {
1411
+ if (field.valueType === 'string')
1412
+ return formatStringLiteral(value);
1413
+ if (field.valueType === 'boolean')
1414
+ return value ? 'true' : 'false';
1415
+ return formatNumericLiteral(value, cppTypeForObjectMatrixFieldFromIr(matrix, field));
1416
+ }
1417
+ function readNumericLeafFromIr(expr) {
1418
+ if (expr.kind === 'number')
1419
+ return Number.isFinite(expr.value) ? expr.value : null;
1420
+ if (expr.kind === 'unary' && (expr.op === '-' || expr.op === '+') && expr.arg.kind === 'number') {
1421
+ if (!Number.isFinite(expr.arg.value))
1422
+ return null;
1423
+ return expr.op === '-' ? -expr.arg.value : expr.arg.value;
1424
+ }
1425
+ return null;
1426
+ }
1427
+ function narrowestNumericCppType(values) {
1428
+ let allIntegers = true;
1429
+ let min = 0;
1430
+ let max = 0;
1431
+ let first = true;
1432
+ for (const v of values) {
1433
+ if (!Number.isFinite(v) || !Number.isInteger(v))
1434
+ allIntegers = false;
1435
+ if (first) {
1436
+ min = v;
1437
+ max = v;
1438
+ first = false;
1439
+ }
1440
+ else {
1441
+ if (v < min)
1442
+ min = v;
1443
+ if (v > max)
1444
+ max = v;
1445
+ }
1446
+ }
1447
+ if (!allIntegers)
1448
+ return 'double';
1449
+ if (min >= -128 && max <= 127)
1450
+ return 'std::int8_t';
1451
+ if (min >= -32768 && max <= 32767)
1452
+ return 'std::int16_t';
1453
+ if (min >= -2147483648 && max <= 2147483647)
1454
+ return 'std::int32_t';
1455
+ if (min >= -(2 ** 53) && max <= 2 ** 53)
1456
+ return 'std::int64_t';
1457
+ return 'double';
1458
+ }
1459
+ function formatNumericLiteral(value, cppType) {
1460
+ if (cppType === 'double') {
1461
+ if (Number.isInteger(value))
1462
+ return `${value}.0`;
1463
+ return String(value);
1464
+ }
1465
+ return String(value);
1466
+ }
1467
+ function formatStringLiteral(value) {
1468
+ // Mirror of `formatStringLiteral` in
1469
+ // `packages/geatsc/src/targets/cpp/emitter/variables.ts`. Escape so the
1470
+ // resulting C++ literal parses to the exact same byte sequence; non-ASCII
1471
+ // is encoded as UTF-8 byte escapes so the output is encoding-stable.
1472
+ let out = '"';
1473
+ for (let i = 0; i < value.length; i++) {
1474
+ const code = value.charCodeAt(i);
1475
+ const ch = value[i];
1476
+ if (ch === '\\' || ch === '"') {
1477
+ out += '\\' + ch;
1478
+ continue;
1479
+ }
1480
+ if (code === 0x0a) {
1481
+ out += '\\n';
1482
+ continue;
1483
+ }
1484
+ if (code === 0x0d) {
1485
+ out += '\\r';
1486
+ continue;
1487
+ }
1488
+ if (code === 0x09) {
1489
+ out += '\\t';
1490
+ continue;
1491
+ }
1492
+ if (code < 0x20 || code === 0x7f) {
1493
+ out += `\\x${code.toString(16).padStart(2, '0')}" "`;
1494
+ continue;
1495
+ }
1496
+ if (code <= 0x7f) {
1497
+ out += ch;
1498
+ continue;
1499
+ }
1500
+ const utf8 = utf8EncodeChar(ch);
1501
+ for (const byte of utf8)
1502
+ out += `\\x${byte.toString(16).padStart(2, '0')}" "`;
1503
+ }
1504
+ out += '"';
1505
+ return out;
1506
+ }
1507
+ function utf8EncodeChar(ch) {
1508
+ const bytes = [];
1509
+ for (const c of ch) {
1510
+ let cp = c.codePointAt(0);
1511
+ if (cp < 0x80)
1512
+ bytes.push(cp);
1513
+ else if (cp < 0x800)
1514
+ bytes.push(0xc0 | (cp >> 6), 0x80 | (cp & 0x3f));
1515
+ else if (cp < 0x10000)
1516
+ bytes.push(0xe0 | (cp >> 12), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
1517
+ else
1518
+ bytes.push(0xf0 | (cp >> 18), 0x80 | ((cp >> 12) & 0x3f), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
1519
+ }
1520
+ return bytes;
1521
+ }