@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.
- package/LICENSE +202 -0
- package/README.md +37 -0
- package/dist/analyze.d.ts +4 -0
- package/dist/analyze.js +195 -0
- package/dist/cpp-canvas-colors.d.ts +4 -0
- package/dist/cpp-canvas-colors.js +226 -0
- package/dist/cpp-field-access.d.ts +49 -0
- package/dist/cpp-field-access.js +144 -0
- package/dist/cpp-ir-dom-style.d.ts +1 -0
- package/dist/cpp-ir-dom-style.js +49 -0
- package/dist/cpp-ir.d.ts +30 -0
- package/dist/cpp-ir.js +2426 -0
- package/dist/cpp-keyed-component-diagnostics.d.ts +8 -0
- package/dist/cpp-keyed-component-diagnostics.js +74 -0
- package/dist/cpp-keyed-list-diagnostics.d.ts +17 -0
- package/dist/cpp-keyed-list-diagnostics.js +84 -0
- package/dist/cpp-mounted-lowering.d.ts +81 -0
- package/dist/cpp-mounted-lowering.js +2235 -0
- package/dist/cpp-mounted.d.ts +25 -0
- package/dist/cpp-mounted.js +1376 -0
- package/dist/cpp-reactive-component-diagnostics.d.ts +2 -0
- package/dist/cpp-reactive-component-diagnostics.js +76 -0
- package/dist/cpp-reactive-component.d.ts +14 -0
- package/dist/cpp-reactive-component.js +349 -0
- package/dist/cpp-replacements.d.ts +14 -0
- package/dist/cpp-replacements.js +787 -0
- package/dist/cpp-source-replacements.d.ts +11 -0
- package/dist/cpp-source-replacements.js +257 -0
- package/dist/cpp-store-hub.d.ts +7 -0
- package/dist/cpp-store-hub.js +160 -0
- package/dist/cpp-store-method-body-parser.d.ts +2 -0
- package/dist/cpp-store-method-body-parser.js +392 -0
- package/dist/cpp-store-method-context.d.ts +48 -0
- package/dist/cpp-store-method-context.js +114 -0
- package/dist/cpp-store-method-expressions.d.ts +12 -0
- package/dist/cpp-store-method-expressions.js +1263 -0
- package/dist/cpp-store-method-replacements.d.ts +5 -0
- package/dist/cpp-store-method-replacements.js +1521 -0
- package/dist/cpp-store-method-targets.d.ts +19 -0
- package/dist/cpp-store-method-targets.js +296 -0
- package/dist/cpp-store-typed-arrays.d.ts +2 -0
- package/dist/cpp-store-typed-arrays.js +655 -0
- package/dist/cpp-stores.d.ts +73 -0
- package/dist/cpp-stores.js +1739 -0
- package/dist/cpp-template-renderer.d.ts +23 -0
- package/dist/cpp-template-renderer.js +3530 -0
- package/dist/css-style-declaration-shims.d.ts +3 -0
- package/dist/css-style-declaration-shims.js +47 -0
- package/dist/host-declarations.d.ts +11 -0
- package/dist/host-declarations.js +320 -0
- package/dist/host-shims.d.ts +3 -0
- package/dist/host-shims.js +3217 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +1239 -0
- package/dist/load-ir.d.ts +7 -0
- package/dist/load-ir.js +40 -0
- package/dist/types.d.ts +604 -0
- package/dist/types.js +1 -0
- package/dist/utils.d.ts +26 -0
- package/dist/utils.js +723 -0
- package/dist/validate.d.ts +3 -0
- package/dist/validate.js +226 -0
- package/package.json +57 -0
|
@@ -0,0 +1,1739 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { dirname, resolve } from 'node:path';
|
|
3
|
+
import ts from 'typescript';
|
|
4
|
+
import { sanitizeCppIdentifier } from './utils.js';
|
|
5
|
+
import { storeDynamicFallbackEnabled, storeHubEmissionEnabled } from './cpp-store-hub.js';
|
|
6
|
+
// EXPERIMENTAL (ReactiveComponent): a component that holds its own reactive state
|
|
7
|
+
// (`component.reactiveState`) is modeled as its own store — the component class IS
|
|
8
|
+
// the store. Synthesizing a GeaIrStore (same className) lets the ONE mounted
|
|
9
|
+
// renderer resolve `this.field` reads, `this.method()` events, and reactive deps
|
|
10
|
+
// through the exact same store machinery as a declared store; the `selfStore`
|
|
11
|
+
// flag routes its field access through typed `store->field.get()` helpers and
|
|
12
|
+
// keeps store-method re-lowering away from its already-typed method bodies.
|
|
13
|
+
export function synthesizeReactiveComponentStores(components) {
|
|
14
|
+
const stores = [];
|
|
15
|
+
for (const component of components) {
|
|
16
|
+
const rs = component.reactiveState;
|
|
17
|
+
if (!rs)
|
|
18
|
+
continue;
|
|
19
|
+
// `el` is the mounted-root slot the framework re-adds to a base-less
|
|
20
|
+
// ReactiveComponent that reads `this.el` (see vendor/gea transform.ts). It is
|
|
21
|
+
// NOT user reactive state: it never re-renders and holds a node handle, not a
|
|
22
|
+
// primitive. Keep it out of the store's reactive fields so no typed
|
|
23
|
+
// `store->el.get()` reader/Signal is synthesized for it — the typed mount
|
|
24
|
+
// path binds it directly, and geatsc still emits the
|
|
25
|
+
// plain `gea_cpp_value el` member from the class itself.
|
|
26
|
+
const fields = rs.fields.filter((field) => field.name !== 'el');
|
|
27
|
+
stores.push({
|
|
28
|
+
id: `${component.id}#self-store`,
|
|
29
|
+
module: component.module,
|
|
30
|
+
className: component.exportName,
|
|
31
|
+
runtimeBase: 'compiled',
|
|
32
|
+
fields,
|
|
33
|
+
selfStore: true,
|
|
34
|
+
...(rs.methods && rs.methods.length > 0 ? { methods: rs.methods } : {}),
|
|
35
|
+
...(rs.getters && rs.getters.length > 0 ? { getters: rs.getters } : {}),
|
|
36
|
+
...(rs.constants && rs.constants.length > 0 ? { constants: rs.constants } : {}),
|
|
37
|
+
...(component.sourceSpan ? { sourceSpan: component.sourceSpan } : {}),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return stores;
|
|
41
|
+
}
|
|
42
|
+
// Forward declarations for the interface-reuse typed-item helpers, emitted at
|
|
43
|
+
// the TOP of the gea_ir store block (before `storeRuntimeSource`). Reason:
|
|
44
|
+
// `storeVectorItemPropertySet` (in storeRuntimeSource) makes a
|
|
45
|
+
// template-dependent call `set_typed_field(slot, ...)`. For synthesized item
|
|
46
|
+
// structs `slot` is a `gea_ir::X_item`, so ADL finds `gea_ir::set_typed_field`.
|
|
47
|
+
// For interface reuse `slot` is `::__gea_type_<Name>` (global scope), so ADL
|
|
48
|
+
// looks only in the global namespace and misses the gea_ir overload. A
|
|
49
|
+
// forward declaration here makes the name visible to ordinary lookup at the
|
|
50
|
+
// template's definition point (satisfying C++ two-phase lookup); the full
|
|
51
|
+
// definitions follow in `generateTypedItemHelpers`. The structs are already
|
|
52
|
+
// complete at this point (this block is emitted after geatsc's record-alias
|
|
53
|
+
// type definitions). Synthesized item types are unaffected (ADL already
|
|
54
|
+
// resolves them) so this only emits for interface-reuse fields.
|
|
55
|
+
export function generateInterfaceItemHelperForwardDeclarations(stores) {
|
|
56
|
+
const lines = [];
|
|
57
|
+
const seen = new Set();
|
|
58
|
+
for (const store of stores) {
|
|
59
|
+
for (const arrayField of collectStoreArrayFields([store])) {
|
|
60
|
+
if (!arrayField.useInterfaceStruct)
|
|
61
|
+
continue;
|
|
62
|
+
if (seen.has(arrayField.itemType))
|
|
63
|
+
continue;
|
|
64
|
+
seen.add(arrayField.itemType);
|
|
65
|
+
const ref = arrayField.itemTypeRef;
|
|
66
|
+
lines.push(`template <typename V> void set_typed_field(${ref} &item, const char *name, const V &value);`, `double read_number_field(const ${ref} &item, const char *name);`, `std::string read_string_field(const ${ref} &item, const char *name);`, `bool read_boolean_field(const ${ref} &item, const char *name);`);
|
|
67
|
+
if (storeDynamicFallbackEnabled())
|
|
68
|
+
lines.push(`gea_cpp_value gea_cpp_key(const std::vector<${ref}> &value);`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (lines.length > 0) {
|
|
72
|
+
// Declaring `gea_cpp_key(const std::vector<…>&)` inside `gea_ir` hides the
|
|
73
|
+
// global `::gea_cpp_key` overload set for unqualified calls in this
|
|
74
|
+
// namespace (`gea_cpp_key(field)` on a std::string/double field). Re-expose
|
|
75
|
+
// the global set with a using-declaration so both resolve.
|
|
76
|
+
lines.push('using ::gea_cpp_key;', '');
|
|
77
|
+
}
|
|
78
|
+
return lines;
|
|
79
|
+
}
|
|
80
|
+
export function generateStoreDeclarations(stores) {
|
|
81
|
+
// The synthesised typed item structs (emitted via `cppTypeForShape`) carry
|
|
82
|
+
// converting constructors that call `read_number_field` / `read_string_field`
|
|
83
|
+
// / `read_boolean_field`. Those primitives live in
|
|
84
|
+
// `generateStoreStateReaders`'s output, which is normally emitted *after*
|
|
85
|
+
// the structs in cpp-ir.ts's lines list. To keep the lookup order valid
|
|
86
|
+
// inside class bodies, we hoist the dynamic-record readers up here as a
|
|
87
|
+
// preamble (and skip emitting them again from the readers stage via
|
|
88
|
+
// `dynamicRecordReadersAlreadyEmitted`).
|
|
89
|
+
const lines = stores.length > 0 && storeDynamicFallbackEnabled() ? [...dynamicRecordReaderLines()] : [];
|
|
90
|
+
for (const store of stores) {
|
|
91
|
+
const declarations = [];
|
|
92
|
+
// cppTypeForField SYNTHESIZES the per-field item structs
|
|
93
|
+
// (`<Store>_<field>_item`) into `declarations` as a side effect — those
|
|
94
|
+
// back the typed vector storage and must still be emitted. The
|
|
95
|
+
// `<Store>_state` snapshot struct that used to wrap these members (and
|
|
96
|
+
// its `read_<Store>_state` readers + `for_each_*` helpers) had NO
|
|
97
|
+
// remaining call sites — every live binding reads through the per-field
|
|
98
|
+
// `read_<Store>_field_*` readers — so the dead mirror (whose array
|
|
99
|
+
// members also degraded to boxed vectors whenever the initializer shape
|
|
100
|
+
// was empty) is no longer emitted.
|
|
101
|
+
for (const field of store.fields) {
|
|
102
|
+
cppTypeForField(field, `${sanitizeCppIdentifier(store.className)}_${sanitizeCppIdentifier(field.name)}`, declarations);
|
|
103
|
+
}
|
|
104
|
+
lines.push(...declarations);
|
|
105
|
+
lines.push(...generateTypedItemHelpers(store));
|
|
106
|
+
}
|
|
107
|
+
return lines;
|
|
108
|
+
}
|
|
109
|
+
function dynamicRecordReaderLines() {
|
|
110
|
+
return [
|
|
111
|
+
'inline double read_number_field(const gea_cpp_value &value, const char *name) {',
|
|
112
|
+
' auto field = value.record_get_literal(name);',
|
|
113
|
+
' return field.is_nullish() ? 0.0 : static_cast<double>(field);',
|
|
114
|
+
'}',
|
|
115
|
+
'',
|
|
116
|
+
'inline bool read_boolean_field(const gea_cpp_value &value, const char *name) {',
|
|
117
|
+
' auto field = value.record_get_literal(name);',
|
|
118
|
+
' return field.is_nullish() ? false : static_cast<bool>(field);',
|
|
119
|
+
'}',
|
|
120
|
+
'',
|
|
121
|
+
'inline std::string read_string_field(const gea_cpp_value &value, const char *name) {',
|
|
122
|
+
' auto field = value.record_get_literal(name);',
|
|
123
|
+
' return field.is_nullish() ? std::string() : static_cast<std::string>(field);',
|
|
124
|
+
'}',
|
|
125
|
+
'',
|
|
126
|
+
];
|
|
127
|
+
}
|
|
128
|
+
// Helpers that bridge a typed item struct (synthesized by `cppTypeForShape`
|
|
129
|
+
// for `Array<{...primitives...}>` shapes in store fields) to and from
|
|
130
|
+
// `gea_cpp_value`. These let typed-storage stores expose their array fields
|
|
131
|
+
// across the dynamic boundary (`__gea_to_value` getter, observers reading
|
|
132
|
+
// `store.balls`) without paying per-property `record_get_literal` linear
|
|
133
|
+
// scans on every access. The per-property reads in lowered method bodies
|
|
134
|
+
// resolve through typed overloads of `read_number_field` / `read_string_field`
|
|
135
|
+
// emitted below; the geatsc emitter's fallback paths that call
|
|
136
|
+
// `slot.record_get_literal(...)` directly on a slot resolve through the
|
|
137
|
+
// duck-type member methods (also emitted on the item struct) so unmodified
|
|
138
|
+
// fallback code keeps compiling against typed storage.
|
|
139
|
+
function generateTypedItemHelpers(store) {
|
|
140
|
+
const lines = [];
|
|
141
|
+
// Two store fields can share the same interface element type (e.g.
|
|
142
|
+
// `hours: Forecast[]` and `days: Forecast[]`). Each would otherwise emit a
|
|
143
|
+
// duplicate set of `__gea_type_Forecast` helpers → ODR/redefinition errors.
|
|
144
|
+
// Synthesized item types are unique per field so they never collide.
|
|
145
|
+
const emittedItemTypes = new Set();
|
|
146
|
+
for (const arrayField of collectStoreArrayFields([store])) {
|
|
147
|
+
if (emittedItemTypes.has(arrayField.itemType))
|
|
148
|
+
continue;
|
|
149
|
+
emittedItemTypes.add(arrayField.itemType);
|
|
150
|
+
// Type-use spelling: `::__gea_type_X` for interface reuse (geatsc emits it
|
|
151
|
+
// at global scope) or bare `<Store>_<field>_item` for synthesized structs
|
|
152
|
+
// (defined in this same gea_ir block).
|
|
153
|
+
const itemTypeRef = arrayField.itemTypeRef;
|
|
154
|
+
const useInterfaceStruct = arrayField.useInterfaceStruct;
|
|
155
|
+
const fields = arrayField.itemFields;
|
|
156
|
+
if (storeDynamicFallbackEnabled() && !useInterfaceStruct) {
|
|
157
|
+
// gea_cpp_key(const X_item &): typed -> dynamic record value. SKIPPED for
|
|
158
|
+
// the interface case — geatsc already emits a global
|
|
159
|
+
// `gea_cpp_key(const __gea_type_X&)` overload; emitting another here
|
|
160
|
+
// would be an ODR/ambiguity hazard.
|
|
161
|
+
const setLines = fields
|
|
162
|
+
.map((f) => recordSetLineForField('__gea_out', `value.${sanitizeCppIdentifier(f.name)}`, f))
|
|
163
|
+
.filter((l) => l !== null);
|
|
164
|
+
lines.push(`inline gea_cpp_value gea_cpp_key(const ${itemTypeRef} &value) {`, ' gea_cpp_value __gea_out;', ' __gea_out.kind = gea_cpp_value::kind_t::record;', ' __gea_out.entries = std::make_shared<std::vector<std::pair<std::string, gea_cpp_value>>>();', ...setLines.map((l) => ` ${l}`), ' return __gea_out;', '}', '');
|
|
165
|
+
}
|
|
166
|
+
if (storeDynamicFallbackEnabled()) {
|
|
167
|
+
// gea_cpp_key(const std::vector<X> &): geatsc has NO vector overload for
|
|
168
|
+
// its interface struct, so we always emit this in dynamic-fallback mode.
|
|
169
|
+
// Its body pushes `gea_cpp_key(item)` which, in the interface case,
|
|
170
|
+
// resolves to geatsc's global single-item overload.
|
|
171
|
+
lines.push(`inline gea_cpp_value gea_cpp_key(const std::vector<${itemTypeRef}> &value) {`, ' gea_cpp_value __gea_out;', ' __gea_out.kind = gea_cpp_value::kind_t::array_value;', ' __gea_out.array_items = std::make_shared<std::vector<gea_cpp_value>>();', ' __gea_out.array_items->reserve(value.size());', ' for (const auto &__gea_item : value) __gea_out.array_items->push_back(gea_cpp_key(__gea_item));', ' __gea_out.object_id = reinterpret_cast<std::uintptr_t>(&value);', ' return __gea_out;', '}', '');
|
|
172
|
+
}
|
|
173
|
+
// gea_ir_set_typed_field(X &, const char *name, const auto &value):
|
|
174
|
+
// direct field write dispatched at runtime by name. Used by the
|
|
175
|
+
// typed-storage `set_array_item_field` lambda's `if constexpr` branch. For
|
|
176
|
+
// the interface case each branch ALSO sets `__gea_has_<field> = true` so
|
|
177
|
+
// the geatsc struct's `__gea_to_value`/`gea_cpp_key` don't silently emit an
|
|
178
|
+
// empty record.
|
|
179
|
+
const branches = fields
|
|
180
|
+
.map((f) => typedFieldSetBranch('item', f, useInterfaceStruct))
|
|
181
|
+
.filter((l) => l !== null);
|
|
182
|
+
lines.push(`template <typename V>`, `inline void set_typed_field(${itemTypeRef} &item, const char *name, const V &value) {`, ...branches.map((l) => ` ${l}`), '}', '');
|
|
183
|
+
// typed-element overload of read_number_field/read_string_field so
|
|
184
|
+
// method-body lowering can keep emitting `read_number_field(item, "x")`
|
|
185
|
+
// even when `item` is a typed struct. Resolution by argument type — the
|
|
186
|
+
// existing `gea_cpp_value` overloads stay in place for the dynamic branch.
|
|
187
|
+
const numberBranches = fields
|
|
188
|
+
.filter((f) => fieldShape(f)?.kind === 'literal' && fieldShape(f).valueType === 'number')
|
|
189
|
+
.map((f) => ` if (std::strcmp(name, ${JSON.stringify(f.name)}) == 0) return item.${sanitizeCppIdentifier(f.name)};`);
|
|
190
|
+
if (numberBranches.length > 0) {
|
|
191
|
+
lines.push(`inline double read_number_field(const ${itemTypeRef} &item, const char *name) {`, ...numberBranches, ' return 0.0;', '}', '');
|
|
192
|
+
}
|
|
193
|
+
const stringBranches = fields
|
|
194
|
+
.filter((f) => fieldShape(f)?.kind === 'literal' && fieldShape(f).valueType === 'string')
|
|
195
|
+
.map((f) => ` if (std::strcmp(name, ${JSON.stringify(f.name)}) == 0) return item.${sanitizeCppIdentifier(f.name)};`);
|
|
196
|
+
if (stringBranches.length > 0) {
|
|
197
|
+
lines.push(`inline std::string read_string_field(const ${itemTypeRef} &item, const char *name) {`, ...stringBranches, ' return std::string();', '}', '');
|
|
198
|
+
}
|
|
199
|
+
const booleanBranches = fields
|
|
200
|
+
.filter((f) => fieldShape(f)?.kind === 'literal' && fieldShape(f).valueType === 'boolean')
|
|
201
|
+
.map((f) => ` if (std::strcmp(name, ${JSON.stringify(f.name)}) == 0) return item.${sanitizeCppIdentifier(f.name)};`);
|
|
202
|
+
if (booleanBranches.length > 0) {
|
|
203
|
+
lines.push(`inline bool read_boolean_field(const ${itemTypeRef} &item, const char *name) {`, ...booleanBranches, ' return false;', '}', '');
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return lines;
|
|
207
|
+
}
|
|
208
|
+
function typedFieldSetBranch(target, field, useInterfaceStruct) {
|
|
209
|
+
// The outer `set_typed_field<V>` is one template instantiation per
|
|
210
|
+
// value-type V the call site passes. Different properties on the same
|
|
211
|
+
// item type may have different shapes (e.g. `x: number, color: string`);
|
|
212
|
+
// the runtime `strcmp` dispatch picks the branch, but every branch's body
|
|
213
|
+
// is compiled for every V. We guard each branch's assignment with
|
|
214
|
+
// `if constexpr` so V-incompatible casts (`static_cast<double>` on a
|
|
215
|
+
// `std::string` V) are skipped at compile time and don't fail the
|
|
216
|
+
// instantiation.
|
|
217
|
+
//
|
|
218
|
+
// For the interface-reuse case the geatsc struct carries per-field presence
|
|
219
|
+
// flags (`__gea_has_<field>`) that `__gea_to_value`/`gea_cpp_key` consult.
|
|
220
|
+
// Set the flag alongside every write or the dynamic surface silently empties.
|
|
221
|
+
const shape = fieldShape(field);
|
|
222
|
+
if (shape?.kind !== 'literal')
|
|
223
|
+
return null;
|
|
224
|
+
const name = sanitizeCppIdentifier(field.name);
|
|
225
|
+
const key = JSON.stringify(field.name);
|
|
226
|
+
const presence = useInterfaceStruct ? ` ${target}.__gea_has_${name} = true;` : '';
|
|
227
|
+
if (shape.valueType === 'number') {
|
|
228
|
+
return storeDynamicFallbackEnabled()
|
|
229
|
+
? `if (std::strcmp(name, ${key}) == 0) { if constexpr (std::is_arithmetic_v<std::decay_t<V>>) ${target}.${name} = static_cast<double>(value); else if constexpr (std::is_same_v<std::decay_t<V>, gea_cpp_value>) ${target}.${name} = gea::runtime::coerce::to_number(value);${presence} return; }`
|
|
230
|
+
: `if (std::strcmp(name, ${key}) == 0) { if constexpr (std::is_arithmetic_v<std::decay_t<V>>) ${target}.${name} = static_cast<double>(value);${presence} return; }`;
|
|
231
|
+
}
|
|
232
|
+
if (shape.valueType === 'boolean') {
|
|
233
|
+
return storeDynamicFallbackEnabled()
|
|
234
|
+
? `if (std::strcmp(name, ${key}) == 0) { if constexpr (std::is_arithmetic_v<std::decay_t<V>> || std::is_same_v<std::decay_t<V>, bool>) ${target}.${name} = static_cast<bool>(value); else if constexpr (std::is_same_v<std::decay_t<V>, gea_cpp_value>) ${target}.${name} = gea::runtime::coerce::to_boolean(value);${presence} return; }`
|
|
235
|
+
: `if (std::strcmp(name, ${key}) == 0) { if constexpr (std::is_arithmetic_v<std::decay_t<V>> || std::is_same_v<std::decay_t<V>, bool>) ${target}.${name} = static_cast<bool>(value);${presence} return; }`;
|
|
236
|
+
}
|
|
237
|
+
if (shape.valueType === 'string') {
|
|
238
|
+
return storeDynamicFallbackEnabled()
|
|
239
|
+
? `if (std::strcmp(name, ${key}) == 0) { if constexpr (std::is_same_v<std::decay_t<V>, std::string>) ${target}.${name} = value; else if constexpr (std::is_same_v<std::decay_t<V>, const char *> || std::is_same_v<std::decay_t<V>, char *>) ${target}.${name} = std::string(value); else if constexpr (std::is_same_v<std::decay_t<V>, gea_cpp_value>) ${target}.${name} = gea_cpp_to_string(value);${presence} return; }`
|
|
240
|
+
: `if (std::strcmp(name, ${key}) == 0) { if constexpr (std::is_same_v<std::decay_t<V>, std::string>) ${target}.${name} = value; else if constexpr (std::is_same_v<std::decay_t<V>, const char *> || std::is_same_v<std::decay_t<V>, char *>) ${target}.${name} = std::string(value);${presence} return; }`;
|
|
241
|
+
}
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
function recordSetLineForField(target, sourceExpr, field) {
|
|
245
|
+
const shape = fieldShape(field);
|
|
246
|
+
if (shape?.kind !== 'literal')
|
|
247
|
+
return null;
|
|
248
|
+
if (shape.valueType === 'number') {
|
|
249
|
+
return `${target}.record_set_literal(${JSON.stringify(field.name)}, gea_cpp_value(${sourceExpr}));`;
|
|
250
|
+
}
|
|
251
|
+
if (shape.valueType === 'boolean') {
|
|
252
|
+
return `${target}.record_set_literal(${JSON.stringify(field.name)}, gea_cpp_value(${sourceExpr}));`;
|
|
253
|
+
}
|
|
254
|
+
if (shape.valueType === 'string') {
|
|
255
|
+
return `${target}.record_set_literal(${JSON.stringify(field.name)}, gea_cpp_value(${sourceExpr}));`;
|
|
256
|
+
}
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
export function generateStoreStateReaders(stores) {
|
|
260
|
+
// The dynamic-record `read_*_field` helpers are now hoisted into
|
|
261
|
+
// `generateStoreDeclarations` so the typed item structs (which invoke
|
|
262
|
+
// them in their gea_cpp_value-converting ctor) see them at name lookup.
|
|
263
|
+
// This stage adds the per-store array-element / state readers that
|
|
264
|
+
// depend on the typed structs already being declared.
|
|
265
|
+
const lines = [];
|
|
266
|
+
for (const store of stores)
|
|
267
|
+
lines.push(...generateStoreStateReader(store));
|
|
268
|
+
return lines;
|
|
269
|
+
}
|
|
270
|
+
export function collectStoreArrayFields(stores) {
|
|
271
|
+
const fields = [];
|
|
272
|
+
for (const store of stores) {
|
|
273
|
+
const storeClass = sanitizeCppIdentifier(store.className);
|
|
274
|
+
const storeGlobalName = storeInstanceGlobalName(store);
|
|
275
|
+
for (const field of store.fields) {
|
|
276
|
+
const shape = fieldShape(field);
|
|
277
|
+
if (!isArrayObjectShape(shape))
|
|
278
|
+
continue;
|
|
279
|
+
const fieldName = sanitizeCppIdentifier(field.name);
|
|
280
|
+
// Prefer the metadata computed once by `attachTypedStorageMetadata`;
|
|
281
|
+
// fall back to re-deriving the predicate from the shape so callers that
|
|
282
|
+
// run before metadata attach (or in isolation) stay correct.
|
|
283
|
+
const useInterfaceStruct = field.typedStorage
|
|
284
|
+
? field.typedStorage.useInterfaceStruct === true
|
|
285
|
+
: arrayReusesInterfaceStruct(shape);
|
|
286
|
+
const itemType = field.typedStorage?.itemType ??
|
|
287
|
+
(useInterfaceStruct ? interfaceItemSymbol(shape.elementTypeName) : `${storeClass}_${fieldName}_item`);
|
|
288
|
+
// geatsc emits `__gea_type_<Name>` at GLOBAL scope (the geatsc cpp target
|
|
289
|
+
// here does not wrap its program in an anonymous namespace). The gea_ir
|
|
290
|
+
// helper blocks are nested namespaces, so the interface struct is named
|
|
291
|
+
// with a leading `::`. Synthesized item structs live in `namespace gea_ir`
|
|
292
|
+
// and are named bare.
|
|
293
|
+
const itemTypeRef = useInterfaceStruct ? `::${itemType}` : itemType;
|
|
294
|
+
fields.push({
|
|
295
|
+
storeClass,
|
|
296
|
+
stateType: `${storeClass}_state`,
|
|
297
|
+
storeGlobalName,
|
|
298
|
+
fieldName,
|
|
299
|
+
fieldType: `std::vector<${itemTypeRef}>`,
|
|
300
|
+
readerName: storeFieldReaderName(storeClass, fieldName),
|
|
301
|
+
itemType,
|
|
302
|
+
itemTypeRef,
|
|
303
|
+
useInterfaceStruct,
|
|
304
|
+
itemFields: shape.element.fields,
|
|
305
|
+
storeRuntimeBase: store.runtimeBase,
|
|
306
|
+
storeIsSelfStore: !!store.selfStore,
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return fields;
|
|
311
|
+
}
|
|
312
|
+
// Array-returning getters as keyed-list sources. Unlike fields, a getter is
|
|
313
|
+
// NOT stored — it is recomputed by calling `typed_store->${name}()`. We reuse
|
|
314
|
+
// the element type of an existing array-of-objects field the getter derives
|
|
315
|
+
// from (matched by return-type interface name, else by a dependency field), so
|
|
316
|
+
// no new item struct needs synthesizing and the row codegen is identical to a
|
|
317
|
+
// field-backed list. Getters whose element type can't be resolved to an
|
|
318
|
+
// existing field are skipped (the non-reactive-list diagnostic still flags
|
|
319
|
+
// them). NOT included in `collectStoreArrayFields` — that drives typed-vector
|
|
320
|
+
// STORAGE generation, which a getter must never get.
|
|
321
|
+
export function collectStoreArrayGetters(stores) {
|
|
322
|
+
const plans = [];
|
|
323
|
+
for (const store of stores) {
|
|
324
|
+
const fieldPlans = collectStoreArrayFields([store]);
|
|
325
|
+
if (fieldPlans.length === 0)
|
|
326
|
+
continue;
|
|
327
|
+
for (const getter of store.getters ?? []) {
|
|
328
|
+
if (!getter.returnsArray)
|
|
329
|
+
continue;
|
|
330
|
+
const source = getterSourceFieldPlan(getter, fieldPlans);
|
|
331
|
+
if (!source)
|
|
332
|
+
continue;
|
|
333
|
+
plans.push({
|
|
334
|
+
...source,
|
|
335
|
+
fieldName: sanitizeCppIdentifier(getter.name),
|
|
336
|
+
isGetter: true,
|
|
337
|
+
reactiveDeps: getter.deps.map((dep) => sanitizeCppIdentifier(dep)),
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
return plans;
|
|
342
|
+
}
|
|
343
|
+
// All keyed-list array sources: stored array-of-objects fields plus
|
|
344
|
+
// array-returning getters. Used by the keyed-list mount + mount-decision
|
|
345
|
+
// passes (NOT by storage/reader generation).
|
|
346
|
+
export function collectStoreArraySources(stores) {
|
|
347
|
+
return [...collectStoreArrayFields(stores), ...collectStoreArrayGetters(stores)];
|
|
348
|
+
}
|
|
349
|
+
function getterSourceFieldPlan(getter, fieldPlans) {
|
|
350
|
+
if (getter.elementTypeName) {
|
|
351
|
+
const symbol = interfaceItemSymbol(getter.elementTypeName);
|
|
352
|
+
const byType = fieldPlans.find((plan) => plan.useInterfaceStruct && plan.itemType === symbol);
|
|
353
|
+
if (byType)
|
|
354
|
+
return byType;
|
|
355
|
+
}
|
|
356
|
+
for (const dep of getter.deps) {
|
|
357
|
+
const byDep = fieldPlans.find((plan) => plan.fieldName === sanitizeCppIdentifier(dep));
|
|
358
|
+
if (byDep)
|
|
359
|
+
return byDep;
|
|
360
|
+
}
|
|
361
|
+
return null;
|
|
362
|
+
}
|
|
363
|
+
// Single-source-of-truth IR pre-pass: walks the bundle's stores, decides
|
|
364
|
+
// which fields qualify for typed-vector storage, and writes the metadata
|
|
365
|
+
// onto the IR's `GeaIrStoreField.typedStorage` slot. Every later pass
|
|
366
|
+
// (`applyTypedArrayStorage`, `replaceStoreMethodsFromIr`'s typed-field
|
|
367
|
+
// helpers, `generateStoreDeclarations`) reads from there directly instead
|
|
368
|
+
// of re-deriving the predicate. Mutates `bundle.stores[*].fields[*]` in
|
|
369
|
+
// place — safe because the IR is owned by the plugin for the lifetime of the
|
|
370
|
+
// generated-source transform.
|
|
371
|
+
export function attachTypedStorageMetadata(stores) {
|
|
372
|
+
for (const store of stores) {
|
|
373
|
+
const storeClass = sanitizeCppIdentifier(store.className);
|
|
374
|
+
for (const field of store.fields) {
|
|
375
|
+
const shape = fieldShape(field);
|
|
376
|
+
if (!isArrayObjectShape(shape)) {
|
|
377
|
+
delete field.typedStorage;
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
const fieldName = sanitizeCppIdentifier(field.name);
|
|
381
|
+
if (arrayReusesInterfaceStruct(shape)) {
|
|
382
|
+
const elementTypeName = shape.elementTypeName;
|
|
383
|
+
field.typedStorage = {
|
|
384
|
+
itemType: interfaceItemSymbol(elementTypeName),
|
|
385
|
+
readerName: storeFieldReaderName(storeClass, fieldName),
|
|
386
|
+
useInterfaceStruct: true,
|
|
387
|
+
elementTypeName,
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
else {
|
|
391
|
+
field.typedStorage = {
|
|
392
|
+
itemType: `${storeClass}_${fieldName}_item`,
|
|
393
|
+
readerName: storeFieldReaderName(storeClass, fieldName),
|
|
394
|
+
useInterfaceStruct: false,
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
export function enrichConstantInitializerShapes(stores, constants, sourceFiles = []) {
|
|
401
|
+
const constantShapes = sourceFiles.length > 0 ? collectConstInitializerShapes(sourceFiles, constants) : new Map();
|
|
402
|
+
const typedFieldShapes = sourceFiles.length > 0 ? collectStoreFieldTypeShapes(sourceFiles, stores) : new Map();
|
|
403
|
+
for (const store of stores) {
|
|
404
|
+
for (const field of store.fields) {
|
|
405
|
+
const typedShape = typedFieldShapes.get(`${sanitizeCppIdentifier(store.className)}.${sanitizeCppIdentifier(field.name)}`);
|
|
406
|
+
if (field.shape) {
|
|
407
|
+
if (shouldUseTypedFieldShape(field.shape, typedShape))
|
|
408
|
+
field.shape = typedShape;
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
const shape = typedShape ??
|
|
412
|
+
shapeFromConstantInitializer(field.initializer, constants, constantShapes);
|
|
413
|
+
if (shape)
|
|
414
|
+
field.shape = shape;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
function shouldUseTypedFieldShape(existing, typed) {
|
|
419
|
+
return (existing.kind === 'array' &&
|
|
420
|
+
!existing.element &&
|
|
421
|
+
!existing.elementTypeName &&
|
|
422
|
+
typed?.kind === 'array' &&
|
|
423
|
+
(!!typed.element || !!typed.elementTypeName));
|
|
424
|
+
}
|
|
425
|
+
export function enrichNamedArrayShapesFromSource(source, stores) {
|
|
426
|
+
const fieldsByItemType = new Map();
|
|
427
|
+
for (const store of stores) {
|
|
428
|
+
for (const field of store.fields) {
|
|
429
|
+
const shape = fieldShape(field);
|
|
430
|
+
if (shape?.kind !== 'array' || shape.element || !shape.elementTypeName)
|
|
431
|
+
continue;
|
|
432
|
+
const itemType = interfaceItemSymbol(shape.elementTypeName);
|
|
433
|
+
let fields = fieldsByItemType.get(itemType);
|
|
434
|
+
if (fields === undefined) {
|
|
435
|
+
fields = recordAliasStructFields(source, itemType);
|
|
436
|
+
fieldsByItemType.set(itemType, fields.length > 0 ? fields : null);
|
|
437
|
+
}
|
|
438
|
+
if (!fields || fields.length === 0)
|
|
439
|
+
continue;
|
|
440
|
+
field.shape = {
|
|
441
|
+
...shape,
|
|
442
|
+
element: {
|
|
443
|
+
kind: 'object',
|
|
444
|
+
fields: fields.map((itemField) => ({
|
|
445
|
+
name: itemField.name,
|
|
446
|
+
...(itemField.shape ? { shape: itemField.shape } : {}),
|
|
447
|
+
})),
|
|
448
|
+
},
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
export function enrichNamedArrayShapesFromTypeSources(entryFiles, stores) {
|
|
454
|
+
const typeNames = new Set();
|
|
455
|
+
for (const store of stores) {
|
|
456
|
+
for (const field of store.fields) {
|
|
457
|
+
const shape = fieldShape(field);
|
|
458
|
+
if (shape?.kind !== 'array' || shape.element || !shape.elementTypeName)
|
|
459
|
+
continue;
|
|
460
|
+
typeNames.add(shape.elementTypeName);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
if (typeNames.size === 0)
|
|
464
|
+
return;
|
|
465
|
+
const fieldsByTypeName = typeFieldsFromReachableSources(entryFiles, typeNames);
|
|
466
|
+
for (const store of stores) {
|
|
467
|
+
for (const field of store.fields) {
|
|
468
|
+
const shape = fieldShape(field);
|
|
469
|
+
if (shape?.kind !== 'array' || shape.element || !shape.elementTypeName)
|
|
470
|
+
continue;
|
|
471
|
+
const fields = fieldsByTypeName.get(shape.elementTypeName);
|
|
472
|
+
if (!fields || fields.length === 0)
|
|
473
|
+
continue;
|
|
474
|
+
field.shape = {
|
|
475
|
+
...shape,
|
|
476
|
+
element: {
|
|
477
|
+
kind: 'object',
|
|
478
|
+
fields: fields.map((itemField) => ({
|
|
479
|
+
name: itemField.name,
|
|
480
|
+
...(itemField.shape ? { shape: itemField.shape } : {}),
|
|
481
|
+
})),
|
|
482
|
+
},
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
function typeFieldsFromReachableSources(entryFiles, typeNames) {
|
|
488
|
+
const out = new Map();
|
|
489
|
+
for (const file of reachableLocalSourceFiles(entryFiles)) {
|
|
490
|
+
if (out.size === typeNames.size)
|
|
491
|
+
break;
|
|
492
|
+
let sourceText;
|
|
493
|
+
try {
|
|
494
|
+
sourceText = fs.readFileSync(file, 'utf8');
|
|
495
|
+
}
|
|
496
|
+
catch {
|
|
497
|
+
continue;
|
|
498
|
+
}
|
|
499
|
+
const sourceFile = ts.createSourceFile(file, sourceText, ts.ScriptTarget.Latest, true, file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
500
|
+
for (const statement of sourceFile.statements) {
|
|
501
|
+
if (ts.isInterfaceDeclaration(statement) && typeNames.has(statement.name.text)) {
|
|
502
|
+
const fields = primitiveObjectFieldsFromMembers(statement.members);
|
|
503
|
+
if (fields)
|
|
504
|
+
out.set(statement.name.text, fields);
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
if (ts.isTypeAliasDeclaration(statement) && typeNames.has(statement.name.text) && ts.isTypeLiteralNode(statement.type)) {
|
|
508
|
+
const fields = primitiveObjectFieldsFromMembers(statement.type.members);
|
|
509
|
+
if (fields)
|
|
510
|
+
out.set(statement.name.text, fields);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
return out;
|
|
515
|
+
}
|
|
516
|
+
function primitiveObjectFieldsFromMembers(members) {
|
|
517
|
+
const fields = [];
|
|
518
|
+
for (const member of members) {
|
|
519
|
+
if (!ts.isPropertySignature(member) || !member.type)
|
|
520
|
+
return null;
|
|
521
|
+
const name = propertyNameText(member.name);
|
|
522
|
+
const valueType = literalValueTypeFromTypeNode(member.type);
|
|
523
|
+
if (!name || !valueType)
|
|
524
|
+
return null;
|
|
525
|
+
fields.push({ name, shape: { kind: 'literal', valueType } });
|
|
526
|
+
}
|
|
527
|
+
return fields;
|
|
528
|
+
}
|
|
529
|
+
function propertyNameText(name) {
|
|
530
|
+
if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name))
|
|
531
|
+
return name.text;
|
|
532
|
+
return null;
|
|
533
|
+
}
|
|
534
|
+
function literalValueTypeFromTypeNode(type) {
|
|
535
|
+
if (type.kind === ts.SyntaxKind.StringKeyword)
|
|
536
|
+
return 'string';
|
|
537
|
+
if (type.kind === ts.SyntaxKind.NumberKeyword)
|
|
538
|
+
return 'number';
|
|
539
|
+
if (type.kind === ts.SyntaxKind.BooleanKeyword)
|
|
540
|
+
return 'boolean';
|
|
541
|
+
if (ts.isLiteralTypeNode(type) &&
|
|
542
|
+
type.literal.kind === ts.SyntaxKind.NullKeyword) {
|
|
543
|
+
return 'null';
|
|
544
|
+
}
|
|
545
|
+
return null;
|
|
546
|
+
}
|
|
547
|
+
// Fix 3 — SINGLE SOURCE OF TRUTH reconciliation. `attachTypedStorageMetadata`
|
|
548
|
+
// (run at IR-load time, before any C++ exists) optimistically opts a store
|
|
549
|
+
// array into reusing geatsc's `::__gea_type_<Name>` struct based on the
|
|
550
|
+
// INITIALIZER shape. geatsc independently decides whether to EMIT that struct
|
|
551
|
+
// based on the DECLARED interface (collector.ts `recordAliasIsAllPrimitive`).
|
|
552
|
+
// These two predicates can diverge — e.g. the declared interface has a
|
|
553
|
+
// non-primitive field the initializer omits, so the plugin opts in but geatsc
|
|
554
|
+
// refuses to emit, leaving the plugin referencing a struct that does not exist
|
|
555
|
+
// (dangling reference → compile break).
|
|
556
|
+
//
|
|
557
|
+
// This pass closes the gap by making emission ⇔ reuse EXACT: once geatsc has
|
|
558
|
+
// produced the program source, we scan it for the struct geatsc actually
|
|
559
|
+
// emitted (`struct __gea_type_<Name>`). Any field still flagged
|
|
560
|
+
// `useInterfaceStruct` whose struct is absent is downgraded to the synthesized
|
|
561
|
+
// `<Store>_<field>_item` path — so the plugin NEVER references a struct geatsc
|
|
562
|
+
// did not emit. Call this on the geatsc-generated source BEFORE any store
|
|
563
|
+
// source generation that reads `field.typedStorage`.
|
|
564
|
+
export function reconcileInterfaceStructReuse(source, stores) {
|
|
565
|
+
for (const store of stores) {
|
|
566
|
+
const storeClass = sanitizeCppIdentifier(store.className);
|
|
567
|
+
for (const field of store.fields) {
|
|
568
|
+
const typed = field.typedStorage;
|
|
569
|
+
if (!typed || typed.useInterfaceStruct !== true)
|
|
570
|
+
continue;
|
|
571
|
+
if (geatscEmittedRecordAliasStruct(source, typed.itemType))
|
|
572
|
+
continue;
|
|
573
|
+
// geatsc did not emit `struct <itemType>` → fall back to the synthesized
|
|
574
|
+
// per-field struct so storage, readers, and helpers all stay self-hosted
|
|
575
|
+
// in `namespace gea_ir` and reference no undefined global type.
|
|
576
|
+
const fieldName = sanitizeCppIdentifier(field.name);
|
|
577
|
+
field.typedStorage = {
|
|
578
|
+
itemType: `${storeClass}_${fieldName}_item`,
|
|
579
|
+
readerName: storeFieldReaderName(storeClass, fieldName),
|
|
580
|
+
useInterfaceStruct: false,
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
// True when the geatsc-generated source defines `struct <typeName> { … }` at
|
|
586
|
+
// (global) scope. Matches the exact spelling the collector emits
|
|
587
|
+
// (`emitRecordAliasType`: `struct __gea_type_<safeIdent(Name)> {`). If the
|
|
588
|
+
// plugin's `sanitizeCppIdentifier`-derived `typeName` and geatsc's
|
|
589
|
+
// `safeIdent`-derived struct name diverge, the struct is simply "not found"
|
|
590
|
+
// here and the field is conservatively downgraded — so this also guards the
|
|
591
|
+
// symbol-name spelling divergence between the two sanitizers.
|
|
592
|
+
function geatscEmittedRecordAliasStruct(source, typeName) {
|
|
593
|
+
return new RegExp(`\\bstruct\\s+${escapeRegExpLiteral(typeName)}\\s*\\{`).test(source);
|
|
594
|
+
}
|
|
595
|
+
function recordAliasStructFields(source, typeName) {
|
|
596
|
+
const body = recordAliasStructBody(source, typeName);
|
|
597
|
+
if (!body)
|
|
598
|
+
return [];
|
|
599
|
+
const fields = [];
|
|
600
|
+
const pattern = /^\s*(std::string|double|bool)\s+([A-Za-z_][A-Za-z0-9_]*)\s*;/gm;
|
|
601
|
+
let match;
|
|
602
|
+
while ((match = pattern.exec(body))) {
|
|
603
|
+
const [, cppType, name] = match;
|
|
604
|
+
if (name.startsWith('__gea_'))
|
|
605
|
+
continue;
|
|
606
|
+
const valueType = cppType === 'std::string' ? 'string' : cppType === 'bool' ? 'boolean' : 'number';
|
|
607
|
+
fields.push({ name, shape: { kind: 'literal', valueType } });
|
|
608
|
+
}
|
|
609
|
+
return fields;
|
|
610
|
+
}
|
|
611
|
+
function recordAliasStructBody(source, typeName) {
|
|
612
|
+
const start = new RegExp(`\\bstruct\\s+${escapeRegExpLiteral(typeName)}\\s*\\{`).exec(source);
|
|
613
|
+
if (!start)
|
|
614
|
+
return null;
|
|
615
|
+
const bodyStart = start.index + start[0].length;
|
|
616
|
+
const end = source.indexOf('\n};', bodyStart);
|
|
617
|
+
return end === -1 ? null : source.slice(bodyStart, end);
|
|
618
|
+
}
|
|
619
|
+
function escapeRegExpLiteral(value) {
|
|
620
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
621
|
+
}
|
|
622
|
+
export function collectStoreFields(stores) {
|
|
623
|
+
const fields = [];
|
|
624
|
+
for (const store of stores) {
|
|
625
|
+
const storeClass = sanitizeCppIdentifier(store.className);
|
|
626
|
+
const storeGlobalName = storeInstanceGlobalName(store);
|
|
627
|
+
for (const field of store.fields) {
|
|
628
|
+
const fieldName = sanitizeCppIdentifier(field.name);
|
|
629
|
+
const reader = storeFieldReaderPlan(store, field);
|
|
630
|
+
fields.push({
|
|
631
|
+
storeClass,
|
|
632
|
+
stateType: `${storeClass}_state`,
|
|
633
|
+
fieldName,
|
|
634
|
+
fieldType: cppTypeForField(field, `${storeClass}_${fieldName}`, []),
|
|
635
|
+
readerName: reader?.readerName ?? null,
|
|
636
|
+
field,
|
|
637
|
+
shape: fieldShape(field),
|
|
638
|
+
reader,
|
|
639
|
+
storeGlobalName,
|
|
640
|
+
storeRuntimeBase: store.runtimeBase,
|
|
641
|
+
storeIsSelfStore: !!store.selfStore,
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
// A Store getter is a computed property in TypeScript, but geatsc emits it
|
|
645
|
+
// as a zero-argument C++ member function. Treat primitive getters as typed
|
|
646
|
+
// field-like template inputs so `{reader.progressPercent}` becomes
|
|
647
|
+
// `reader->progressPercent()` instead of a dynamic record lookup for a
|
|
648
|
+
// property that is intentionally not stored in the record mirror.
|
|
649
|
+
//
|
|
650
|
+
// Array getters already have a dedicated typed keyed-list path. Self-store
|
|
651
|
+
// component getters are inlined before this collector runs. A regular Store
|
|
652
|
+
// getter needs its exported singleton so the renderer can retain the typed
|
|
653
|
+
// shared_ptr all the way to the call.
|
|
654
|
+
if (!store.selfStore && storeGlobalName) {
|
|
655
|
+
for (const getter of store.getters ?? []) {
|
|
656
|
+
const shape = primitiveGetterShape(store, getter);
|
|
657
|
+
if (getter.returnsArray || shape?.kind !== 'literal')
|
|
658
|
+
continue;
|
|
659
|
+
if (shape.valueType !== 'string' && shape.valueType !== 'number' && shape.valueType !== 'boolean')
|
|
660
|
+
continue;
|
|
661
|
+
const fieldName = sanitizeCppIdentifier(getter.name);
|
|
662
|
+
const field = { name: getter.name, shape };
|
|
663
|
+
const fieldType = cppTypeForField(field, `${storeClass}_${fieldName}`, []);
|
|
664
|
+
const fallback = shape.valueType === 'string' ? 'std::string()' : shape.valueType === 'boolean' ? 'false' : '0.0';
|
|
665
|
+
const value = shape.valueType === 'string'
|
|
666
|
+
? `__gea_store->${fieldName}()`
|
|
667
|
+
: shape.valueType === 'boolean'
|
|
668
|
+
? `static_cast<bool>(__gea_store->${fieldName}())`
|
|
669
|
+
: `static_cast<double>(__gea_store->${fieldName}())`;
|
|
670
|
+
fields.push({
|
|
671
|
+
storeClass,
|
|
672
|
+
stateType: `${storeClass}_state`,
|
|
673
|
+
fieldName,
|
|
674
|
+
fieldType,
|
|
675
|
+
readerName: `[](const auto &__gea_store) -> ${fieldType} { return __gea_store ? ${value} : ${fallback}; }`,
|
|
676
|
+
field,
|
|
677
|
+
shape,
|
|
678
|
+
reader: null,
|
|
679
|
+
storeGlobalName,
|
|
680
|
+
storeRuntimeBase: store.runtimeBase,
|
|
681
|
+
storeIsSelfStore: false,
|
|
682
|
+
isGetter: true,
|
|
683
|
+
reactiveDeps: expandedGetterDeps(store, getter),
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return fields;
|
|
689
|
+
}
|
|
690
|
+
function expandedGetterDeps(store, getter) {
|
|
691
|
+
const getters = new Map((store.getters ?? []).map((candidate) => [candidate.name, candidate]));
|
|
692
|
+
const out = [];
|
|
693
|
+
const visiting = new Set();
|
|
694
|
+
const append = (name) => {
|
|
695
|
+
const nested = getters.get(name);
|
|
696
|
+
if (!nested || visiting.has(name)) {
|
|
697
|
+
const dep = sanitizeCppIdentifier(name);
|
|
698
|
+
if (!out.includes(dep))
|
|
699
|
+
out.push(dep);
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
visiting.add(name);
|
|
703
|
+
for (const dep of nested.deps)
|
|
704
|
+
append(dep);
|
|
705
|
+
visiting.delete(name);
|
|
706
|
+
};
|
|
707
|
+
for (const dep of getter.deps)
|
|
708
|
+
append(dep);
|
|
709
|
+
return out;
|
|
710
|
+
}
|
|
711
|
+
const primitiveGetterShapeCache = new Map();
|
|
712
|
+
// The current Gea IR producer records getter bodies/dependencies but may omit a
|
|
713
|
+
// primitive getter's shape. The compat source still carries its TypeScript
|
|
714
|
+
// return annotation, so recover that type here instead of discarding static
|
|
715
|
+
// information and falling back to a boxed property read.
|
|
716
|
+
function primitiveGetterShape(store, getter) {
|
|
717
|
+
if (getter.shape?.kind === 'literal')
|
|
718
|
+
return getter.shape;
|
|
719
|
+
const cacheKey = `${store.module}#${store.className}`;
|
|
720
|
+
let byName = primitiveGetterShapeCache.get(cacheKey);
|
|
721
|
+
if (!byName) {
|
|
722
|
+
byName = new Map();
|
|
723
|
+
try {
|
|
724
|
+
const sourceText = fs.readFileSync(store.module, 'utf8');
|
|
725
|
+
const sourceFile = ts.createSourceFile(store.module, sourceText, ts.ScriptTarget.Latest, true, store.module.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
726
|
+
for (const statement of sourceFile.statements) {
|
|
727
|
+
if (!ts.isClassDeclaration(statement) || statement.name?.text !== store.className)
|
|
728
|
+
continue;
|
|
729
|
+
for (const member of statement.members) {
|
|
730
|
+
if (!ts.isGetAccessorDeclaration(member) || !ts.isIdentifier(member.name) || !member.type)
|
|
731
|
+
continue;
|
|
732
|
+
const valueType = member.type.kind === ts.SyntaxKind.StringKeyword
|
|
733
|
+
? 'string'
|
|
734
|
+
: member.type.kind === ts.SyntaxKind.NumberKeyword
|
|
735
|
+
? 'number'
|
|
736
|
+
: member.type.kind === ts.SyntaxKind.BooleanKeyword
|
|
737
|
+
? 'boolean'
|
|
738
|
+
: null;
|
|
739
|
+
if (valueType)
|
|
740
|
+
byName.set(member.name.text, { kind: 'literal', valueType });
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
catch {
|
|
745
|
+
// Missing/unreadable source keeps the existing dynamic fallback.
|
|
746
|
+
}
|
|
747
|
+
primitiveGetterShapeCache.set(cacheKey, byName);
|
|
748
|
+
}
|
|
749
|
+
return byName.get(getter.name);
|
|
750
|
+
}
|
|
751
|
+
export function collectStoreMethods(stores) {
|
|
752
|
+
const methods = [];
|
|
753
|
+
for (const store of stores) {
|
|
754
|
+
const storeClass = sanitizeCppIdentifier(store.className);
|
|
755
|
+
const storeGlobalName = storeInstanceGlobalName(store);
|
|
756
|
+
for (const method of store.methods ?? []) {
|
|
757
|
+
methods.push({
|
|
758
|
+
storeClass,
|
|
759
|
+
stateType: `${storeClass}_state`,
|
|
760
|
+
storeGlobalName,
|
|
761
|
+
globalAccess: store.selfStore ? 'reference' : 'shared_ptr',
|
|
762
|
+
methodName: sanitizeCppIdentifier(method.name),
|
|
763
|
+
params: method.params.map((param) => ({
|
|
764
|
+
name: sanitizeCppIdentifier(param.name),
|
|
765
|
+
...(param.valueType ? { valueType: param.valueType } : {}),
|
|
766
|
+
})),
|
|
767
|
+
});
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
return methods;
|
|
771
|
+
}
|
|
772
|
+
export function collectSingletonMethodsFromSourceFiles(entryFiles, stores = []) {
|
|
773
|
+
const storeClasses = new Set(stores.map((store) => sanitizeCppIdentifier(store.className)));
|
|
774
|
+
const classMethods = new Map();
|
|
775
|
+
const singletons = [];
|
|
776
|
+
for (const file of reachableLocalSourceFiles(entryFiles)) {
|
|
777
|
+
let sourceText;
|
|
778
|
+
try {
|
|
779
|
+
sourceText = fs.readFileSync(file, 'utf8');
|
|
780
|
+
}
|
|
781
|
+
catch {
|
|
782
|
+
continue;
|
|
783
|
+
}
|
|
784
|
+
const sourceFile = ts.createSourceFile(file, sourceText, ts.ScriptTarget.Latest, true, file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
785
|
+
for (const statement of sourceFile.statements) {
|
|
786
|
+
if (ts.isClassDeclaration(statement) && statement.name) {
|
|
787
|
+
const className = sanitizeCppIdentifier(statement.name.text);
|
|
788
|
+
if (storeClasses.has(className) || classExtendsStore(statement))
|
|
789
|
+
continue;
|
|
790
|
+
const methods = [];
|
|
791
|
+
for (const member of statement.members) {
|
|
792
|
+
if (!ts.isMethodDeclaration(member))
|
|
793
|
+
continue;
|
|
794
|
+
if (!ts.isIdentifier(member.name))
|
|
795
|
+
continue;
|
|
796
|
+
if (hasModifier(member, ts.SyntaxKind.StaticKeyword) || hasModifier(member, ts.SyntaxKind.PrivateKeyword))
|
|
797
|
+
continue;
|
|
798
|
+
methods.push({
|
|
799
|
+
storeClass: className,
|
|
800
|
+
stateType: `${className}_state`,
|
|
801
|
+
globalAccess: 'reference',
|
|
802
|
+
methodName: sanitizeCppIdentifier(member.name.text),
|
|
803
|
+
params: member.parameters.map((param, index) => ({
|
|
804
|
+
name: ts.isIdentifier(param.name) ? sanitizeCppIdentifier(param.name.text) : `arg${index}`,
|
|
805
|
+
...(parameterValueType(param.type) ? { valueType: parameterValueType(param.type) } : {}),
|
|
806
|
+
})),
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
if (methods.length > 0)
|
|
810
|
+
classMethods.set(className, methods);
|
|
811
|
+
continue;
|
|
812
|
+
}
|
|
813
|
+
if (!ts.isVariableStatement(statement))
|
|
814
|
+
continue;
|
|
815
|
+
if (!hasModifier(statement, ts.SyntaxKind.ExportKeyword))
|
|
816
|
+
continue;
|
|
817
|
+
if ((statement.declarationList.flags & ts.NodeFlags.Const) === 0)
|
|
818
|
+
continue;
|
|
819
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
820
|
+
if (!ts.isIdentifier(declaration.name) || !declaration.initializer)
|
|
821
|
+
continue;
|
|
822
|
+
const className = newExpressionClassName(declaration.initializer);
|
|
823
|
+
if (!className || storeClasses.has(className))
|
|
824
|
+
continue;
|
|
825
|
+
singletons.push({ name: sanitizeCppIdentifier(declaration.name.text), className });
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
const out = [];
|
|
830
|
+
const seen = new Set();
|
|
831
|
+
for (const singleton of singletons) {
|
|
832
|
+
for (const method of classMethods.get(singleton.className) ?? []) {
|
|
833
|
+
const key = `${singleton.name}.${method.methodName}/${method.params.length}`;
|
|
834
|
+
if (seen.has(key))
|
|
835
|
+
continue;
|
|
836
|
+
seen.add(key);
|
|
837
|
+
out.push({ ...method, storeGlobalName: singleton.name });
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
return out;
|
|
841
|
+
}
|
|
842
|
+
// Resolve the exported singleton instance name for a store by scanning its
|
|
843
|
+
// module for `export const <name> = new <ClassName>(...)`. Returns undefined
|
|
844
|
+
// when the binding can't be found (no source, aliased export, etc.), in which
|
|
845
|
+
// case ambiguous field lookups simply stay unresolved as before.
|
|
846
|
+
const storeGlobalNameCache = new Map();
|
|
847
|
+
export function storeInstanceGlobalName(store) {
|
|
848
|
+
// A self-store has no exported singleton — its template reads it as `this`
|
|
849
|
+
// (`{this.count}`). Registering `this` as the instance name lets the
|
|
850
|
+
// receiver-disambiguation in storeFieldByName resolve `this.field` to the
|
|
851
|
+
// component's own store when the field name collides with another store.
|
|
852
|
+
// (Two ReactiveComponents sharing a field name stay ambiguous → slow path.)
|
|
853
|
+
if (store.selfStore)
|
|
854
|
+
return 'this';
|
|
855
|
+
const className = sanitizeCppIdentifier(store.className);
|
|
856
|
+
const cacheKey = `${store.module}#${className}`;
|
|
857
|
+
if (storeGlobalNameCache.has(cacheKey))
|
|
858
|
+
return storeGlobalNameCache.get(cacheKey);
|
|
859
|
+
let resolved;
|
|
860
|
+
try {
|
|
861
|
+
const source = fs.readFileSync(store.module, 'utf8');
|
|
862
|
+
const escaped = store.className.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
863
|
+
const match = source.match(new RegExp(`export\\s+const\\s+([A-Za-z_$][A-Za-z0-9_$]*)\\s*=\\s*new\\s+${escaped}\\b`));
|
|
864
|
+
if (match)
|
|
865
|
+
resolved = sanitizeCppIdentifier(match[1]);
|
|
866
|
+
}
|
|
867
|
+
catch {
|
|
868
|
+
resolved = undefined;
|
|
869
|
+
}
|
|
870
|
+
storeGlobalNameCache.set(cacheKey, resolved);
|
|
871
|
+
return resolved;
|
|
872
|
+
}
|
|
873
|
+
export function storeFieldReaderName(storeClass, fieldName) {
|
|
874
|
+
return `read_${sanitizeCppIdentifier(storeClass)}_field_${sanitizeCppIdentifier(fieldName)}`;
|
|
875
|
+
}
|
|
876
|
+
// Typed reader OVERLOADS for self-stores. The renderer's read call shape is
|
|
877
|
+
// identical in both modes — `read_App_field_count(store)` — so a self-store just
|
|
878
|
+
// needs a `shared_ptr<App>` overload whose body reads the typed Signal field
|
|
879
|
+
// directly. Emitted in the LATE gea_ir block (after `class App` is complete);
|
|
880
|
+
// the boxed overload from the early block remains for any dynamic consumer.
|
|
881
|
+
// Non-primitive fields (arrays, records) get no typed reader yet — an expression
|
|
882
|
+
// over them keeps resolving to the boxed overload, which fails to compile only
|
|
883
|
+
// if a typed renderer actually uses it (loud, not silent).
|
|
884
|
+
export function generateTypedSelfStoreReaders(stores) {
|
|
885
|
+
const lines = [];
|
|
886
|
+
for (const store of stores) {
|
|
887
|
+
if (!store.selfStore)
|
|
888
|
+
continue;
|
|
889
|
+
const storeClass = sanitizeCppIdentifier(store.className);
|
|
890
|
+
for (const field of store.fields) {
|
|
891
|
+
const shape = fieldShape(field);
|
|
892
|
+
if (shape?.kind !== 'literal')
|
|
893
|
+
continue;
|
|
894
|
+
const cppType = shape.valueType === 'string' ? 'std::string' : shape.valueType === 'boolean' ? 'bool' : 'double';
|
|
895
|
+
const fieldName = sanitizeCppIdentifier(field.name);
|
|
896
|
+
lines.push(`inline ${cppType} ${storeFieldReaderName(storeClass, fieldName)}(const std::shared_ptr<${storeClass}> &store) { return store->${fieldName}.get(); }`);
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
if (lines.length > 0)
|
|
900
|
+
lines.push('');
|
|
901
|
+
return lines;
|
|
902
|
+
}
|
|
903
|
+
export function storeFieldReaderPlan(store, field) {
|
|
904
|
+
const shape = fieldShape(field);
|
|
905
|
+
if (!isFieldReadableShape(shape))
|
|
906
|
+
return null;
|
|
907
|
+
const storeClass = sanitizeCppIdentifier(store.className);
|
|
908
|
+
const fieldName = sanitizeCppIdentifier(field.name);
|
|
909
|
+
return {
|
|
910
|
+
storeClass,
|
|
911
|
+
stateType: `${storeClass}_state`,
|
|
912
|
+
fieldName,
|
|
913
|
+
fieldType: cppTypeForField(field, `${storeClass}_${fieldName}`, []),
|
|
914
|
+
readerName: storeFieldReaderName(storeClass, fieldName),
|
|
915
|
+
field,
|
|
916
|
+
shape,
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
function generateStoreStateReader(store) {
|
|
920
|
+
if (!storeDynamicFallbackEnabled())
|
|
921
|
+
return [];
|
|
922
|
+
const lines = [];
|
|
923
|
+
// Dedup per item-type: two fields sharing an interface element type
|
|
924
|
+
// (`hours`/`days` both `Forecast[]`) produce the same `read___gea_type_X`
|
|
925
|
+
// reader fn. Synthesized item types are field-unique so never collide.
|
|
926
|
+
const emittedItemReaders = new Set();
|
|
927
|
+
for (const field of store.fields) {
|
|
928
|
+
const shape = fieldShape(field);
|
|
929
|
+
if (!isArrayObjectShape(shape))
|
|
930
|
+
continue;
|
|
931
|
+
const itemType = arrayItemTypeInfo(sanitizeCppIdentifier(store.className), field).itemType;
|
|
932
|
+
if (emittedItemReaders.has(itemType))
|
|
933
|
+
continue;
|
|
934
|
+
emittedItemReaders.add(itemType);
|
|
935
|
+
lines.push(...generateArrayItemStateReader(store, field, shape.element.fields));
|
|
936
|
+
}
|
|
937
|
+
for (const field of store.fields)
|
|
938
|
+
lines.push(...generateStoreFieldReader(store, field));
|
|
939
|
+
// The whole-state `read_<Store>_state` readers are gone with the dead
|
|
940
|
+
// `<Store>_state` mirror struct — bindings read per-field.
|
|
941
|
+
return lines;
|
|
942
|
+
}
|
|
943
|
+
function generateArrayItemStateReader(store, field, itemFields) {
|
|
944
|
+
const info = arrayItemTypeInfo(sanitizeCppIdentifier(store.className), field);
|
|
945
|
+
// Reader fn name keyed off the UNQUALIFIED item symbol so it never contains
|
|
946
|
+
// `::` (`read___gea_type_X`, not `read_::__gea_type_X`). cpp-mounted and
|
|
947
|
+
// generateArrayStoreFieldReader both reconstruct this same name.
|
|
948
|
+
const readerFn = `read_${info.itemType}`;
|
|
949
|
+
if (info.useInterfaceStruct) {
|
|
950
|
+
// Reuse geatsc's `__gea_from_value` factory, which SETS the per-field
|
|
951
|
+
// presence flags. A field-by-field read here would leave them false and
|
|
952
|
+
// empty the dynamic surface.
|
|
953
|
+
return [
|
|
954
|
+
`inline ${info.itemTypeRef} ${readerFn}(const gea_cpp_value &value) {`,
|
|
955
|
+
` return ${info.itemTypeRef}::__gea_from_value(value);`,
|
|
956
|
+
'}',
|
|
957
|
+
'',
|
|
958
|
+
];
|
|
959
|
+
}
|
|
960
|
+
const lines = [
|
|
961
|
+
`inline ${info.itemTypeRef} ${readerFn}(const gea_cpp_value &value) {`,
|
|
962
|
+
` ${info.itemTypeRef} item{};`,
|
|
963
|
+
];
|
|
964
|
+
for (const itemField of itemFields) {
|
|
965
|
+
const line = readLiteralFieldLine('item', 'value', itemField);
|
|
966
|
+
if (line)
|
|
967
|
+
lines.push(` ${line}`);
|
|
968
|
+
}
|
|
969
|
+
lines.push(' return item;', '}', '');
|
|
970
|
+
return lines;
|
|
971
|
+
}
|
|
972
|
+
function generateStoreFieldReader(store, field) {
|
|
973
|
+
const plan = storeFieldReaderPlan(store, field);
|
|
974
|
+
if (!plan)
|
|
975
|
+
return [];
|
|
976
|
+
if (!boxedStoreFieldReaderEmitted(store, plan))
|
|
977
|
+
return [];
|
|
978
|
+
// Typed-carrier stores additionally get `shared_ptr<Store>` reader
|
|
979
|
+
// overloads, but those are declared-and-defined ONLY in the late block
|
|
980
|
+
// (generateTypedStoreReaderDefinitions): this early block can precede the
|
|
981
|
+
// store class's forward declaration entirely (module emission order
|
|
982
|
+
// varies), and a `class X;` here would declare gea_ir::X, shadowing the
|
|
983
|
+
// global store class. Every typed call site lives in the late mounted
|
|
984
|
+
// renderers, which follow the definitions.
|
|
985
|
+
return plan.shape.kind === 'literal'
|
|
986
|
+
? generateScalarStoreFieldReader(store, plan)
|
|
987
|
+
: isArrayObjectShape(plan.shape)
|
|
988
|
+
? generateArrayStoreFieldReader(store, plan)
|
|
989
|
+
: [];
|
|
990
|
+
}
|
|
991
|
+
// Typed reader overloads exist for native IR stores whose global cells geatsc
|
|
992
|
+
// core types as `std::shared_ptr<Class>`. A lean runtime base changes the
|
|
993
|
+
// method implementation strategy, not the store's native carrier.
|
|
994
|
+
function typedReaderOverloadEligible(store) {
|
|
995
|
+
return !store.selfStore;
|
|
996
|
+
}
|
|
997
|
+
// Whether this field's BOXED reader is emitted at all. For a typed-carrier
|
|
998
|
+
// store (typed cell + typed mounts, hub on) a typed-direct field has NO
|
|
999
|
+
// remaining boxed call site — the shared_ptr overload reads the member
|
|
1000
|
+
// directly and every crossing on the store path is typed — so the boxed
|
|
1001
|
+
// reader (and its as_shared_ptr fast path) would be dead weight in the
|
|
1002
|
+
// program. Fields whose class member ISN'T the typed value keep the boxed
|
|
1003
|
+
// reader: the typed overload routes through it via gea_cpp_key.
|
|
1004
|
+
function boxedStoreFieldReaderEmitted(store, plan) {
|
|
1005
|
+
if (!typedReaderOverloadEligible(store) || !storeHubEmissionEnabled())
|
|
1006
|
+
return true;
|
|
1007
|
+
const typedDirect = (plan.shape.kind === 'literal' && scalarReaderHasTypedDefinition(store, plan)) ||
|
|
1008
|
+
(isArrayObjectShape(plan.shape) && arrayReaderHasTypedDefinition(store, plan));
|
|
1009
|
+
return !typedDirect;
|
|
1010
|
+
}
|
|
1011
|
+
// Mirrors the early-block emission predicate: which fields actually got a
|
|
1012
|
+
// reader. Must match generateScalarStoreFieldReader/generateArrayStoreFieldReader
|
|
1013
|
+
// or the typed overload would be declared without a boxed sibling (harmless)
|
|
1014
|
+
// or defined for a reader that doesn't exist (compile error).
|
|
1015
|
+
function storeFieldReaderEmitted(plan) {
|
|
1016
|
+
if (plan.shape.kind === 'literal')
|
|
1017
|
+
return !!literalFieldReadExpression('store', plan.field);
|
|
1018
|
+
return isArrayObjectShape(plan.shape);
|
|
1019
|
+
}
|
|
1020
|
+
// A scalar reader gets a typed fast-path DEFINITION in the late gea_ir block
|
|
1021
|
+
// (after the store class is complete — the typed member read needs it) iff the
|
|
1022
|
+
// class member is a typed primitive. Early-block emission is then a declaration
|
|
1023
|
+
// only. The predicate must match EXACTLY between the early declaration and the
|
|
1024
|
+
// late definition, or we'd declare without defining (or define twice).
|
|
1025
|
+
function scalarReaderHasTypedDefinition(store, plan) {
|
|
1026
|
+
if (store.selfStore)
|
|
1027
|
+
return false; // self-stores get a shared_ptr<T> overload instead
|
|
1028
|
+
return plan.fieldType === 'double' || plan.fieldType === 'std::string' || plan.fieldType === 'bool';
|
|
1029
|
+
}
|
|
1030
|
+
function generateScalarStoreFieldReader(store, plan) {
|
|
1031
|
+
const expr = literalFieldReadExpression('store', plan.field);
|
|
1032
|
+
if (!expr)
|
|
1033
|
+
return [];
|
|
1034
|
+
if (scalarReaderHasTypedDefinition(store, plan)) {
|
|
1035
|
+
return [`inline ${plan.fieldType} ${plan.readerName}(const gea_cpp_value &store);`, ''];
|
|
1036
|
+
}
|
|
1037
|
+
return [`inline ${plan.fieldType} ${plan.readerName}(const gea_cpp_value &store) {`, ` return ${expr};`, '}', ''];
|
|
1038
|
+
}
|
|
1039
|
+
// Late-block scalar reader definitions with the typed fast path: resolve the
|
|
1040
|
+
// store's typed instance from the boxed global's object_owner (one pointer cast)
|
|
1041
|
+
// and read the member directly — no string-keyed record lookup, no proxy
|
|
1042
|
+
// roundtrip, no gea_cpp_value materialization. Falls back to the dynamic read
|
|
1043
|
+
// for a value that doesn't carry the typed instance (defensive; the globals
|
|
1044
|
+
// always do).
|
|
1045
|
+
export function generateTypedStoreReaderDefinitions(stores) {
|
|
1046
|
+
const lines = [];
|
|
1047
|
+
for (const store of stores) {
|
|
1048
|
+
const storeClass = sanitizeCppIdentifier(store.className);
|
|
1049
|
+
for (const field of store.fields) {
|
|
1050
|
+
const plan = storeFieldReaderPlan(store, field);
|
|
1051
|
+
if (!plan)
|
|
1052
|
+
continue;
|
|
1053
|
+
// Typed-carrier stores don't emit boxed readers for typed-direct
|
|
1054
|
+
// fields at all — no boxed call site survives the debox. They still
|
|
1055
|
+
// need the shared_ptr overload emitted below because generated module
|
|
1056
|
+
// code can call the reader through the typed global cell.
|
|
1057
|
+
const emitBoxedReader = boxedStoreFieldReaderEmitted(store, plan);
|
|
1058
|
+
const fieldIdent = sanitizeCppIdentifier(field.name);
|
|
1059
|
+
if (emitBoxedReader && plan.shape.kind === 'literal' && scalarReaderHasTypedDefinition(store, plan)) {
|
|
1060
|
+
const expr = literalFieldReadExpression('store', plan.field);
|
|
1061
|
+
if (!expr)
|
|
1062
|
+
continue;
|
|
1063
|
+
lines.push(`inline ${plan.fieldType} ${plan.readerName}(const gea_cpp_value &store) {`, ` if (auto __gea_typed = gea_cpp_value_as_shared_ptr<${storeClass}>(store)) return __gea_typed->${fieldIdent};`, ` return ${expr};`, '}', '');
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
if (emitBoxedReader && isArrayObjectShape(plan.shape) && arrayReaderHasTypedDefinition(store, plan)) {
|
|
1067
|
+
lines.push(`inline ${plan.fieldType} ${plan.readerName}(const gea_cpp_value &store) {`, ` if (auto __gea_typed = gea_cpp_value_as_shared_ptr<${storeClass}>(store)) return __gea_typed->${fieldIdent};`, ...boxedArrayReaderBody(plan), '}', '');
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
// (The late `read_<Store>_state` definitions were removed with the dead
|
|
1071
|
+
// `<Store>_state` mirror struct — see generateStoreDeclarations.)
|
|
1072
|
+
if (typedReaderOverloadEligible(store)) {
|
|
1073
|
+
// shared_ptr overloads for the typed carrier: typed members read
|
|
1074
|
+
// directly; anything else boxes through gea_cpp_key (the retained
|
|
1075
|
+
// tracked proxy) into the boxed reader.
|
|
1076
|
+
for (const field of store.fields) {
|
|
1077
|
+
const plan = storeFieldReaderPlan(store, field);
|
|
1078
|
+
if (!plan || !storeFieldReaderEmitted(plan))
|
|
1079
|
+
continue;
|
|
1080
|
+
const fieldIdent = sanitizeCppIdentifier(field.name);
|
|
1081
|
+
const typedDirect = (plan.shape.kind === 'literal' && scalarReaderHasTypedDefinition(store, plan)) ||
|
|
1082
|
+
(isArrayObjectShape(plan.shape) && arrayReaderHasTypedDefinition(store, plan));
|
|
1083
|
+
lines.push(`inline ${plan.fieldType} ${plan.readerName}(const std::shared_ptr<${storeClass}> &store) {`, (plan.shape.kind === 'literal' && plan.fieldType === 'std::nullptr_t') ? ' return nullptr;' : typedDirect ? ` return store->${fieldIdent};` : ` return ${plan.readerName}(gea_cpp_key(store));`, '}', '');
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
return lines;
|
|
1088
|
+
}
|
|
1089
|
+
// A typedStorage array field's CLASS member is already the typed vector
|
|
1090
|
+
// (`std::vector<__gea_type_Forecast>` — applyTypedArrayStorage rewrote it), so
|
|
1091
|
+
// the typed read is a direct vector copy: no facade materialization of a
|
|
1092
|
+
// gea_cpp_value array, no per-element record conversion. Same decl-early /
|
|
1093
|
+
// def-late split as scalars.
|
|
1094
|
+
function arrayReaderHasTypedDefinition(store, plan) {
|
|
1095
|
+
return !store.selfStore && !!plan.field.typedStorage;
|
|
1096
|
+
}
|
|
1097
|
+
function boxedArrayReaderBody(plan) {
|
|
1098
|
+
// The per-item reader fn name is `read_<itemType>` — `read_<Store>_<field>_item`
|
|
1099
|
+
// for synthesized structs, `read___gea_type_<Name>` for interface reuse.
|
|
1100
|
+
const itemReader = `read_${arrayItemTypeInfo(plan.storeClass, plan.field).itemType}`;
|
|
1101
|
+
return [
|
|
1102
|
+
` ${plan.fieldType} items;`,
|
|
1103
|
+
` auto __gea_array_value = store.record_get_literal(${JSON.stringify(plan.field.name)});`,
|
|
1104
|
+
` const auto &__gea_values = (__gea_array_value.kind == gea_cpp_value::kind_t::proxy && __gea_array_value.proxy_target) ? __gea_array_value.proxy_target->array_ref() : __gea_array_value.array_ref();`,
|
|
1105
|
+
` items.reserve(__gea_values.size());`,
|
|
1106
|
+
` for (const auto &value : __gea_values) {`,
|
|
1107
|
+
` items.push_back(${itemReader}(value));`,
|
|
1108
|
+
' }',
|
|
1109
|
+
' return items;',
|
|
1110
|
+
];
|
|
1111
|
+
}
|
|
1112
|
+
function generateArrayStoreFieldReader(store, plan) {
|
|
1113
|
+
if (!isArrayObjectShape(plan.shape))
|
|
1114
|
+
return [];
|
|
1115
|
+
if (arrayReaderHasTypedDefinition(store, plan)) {
|
|
1116
|
+
return [`inline ${plan.fieldType} ${plan.readerName}(const gea_cpp_value &store);`, ''];
|
|
1117
|
+
}
|
|
1118
|
+
return [
|
|
1119
|
+
`inline ${plan.fieldType} ${plan.readerName}(const gea_cpp_value &store) {`,
|
|
1120
|
+
...boxedArrayReaderBody(plan),
|
|
1121
|
+
'}',
|
|
1122
|
+
'',
|
|
1123
|
+
];
|
|
1124
|
+
}
|
|
1125
|
+
function readLiteralFieldLine(target, source, field) {
|
|
1126
|
+
const name = sanitizeCppIdentifier(field.name);
|
|
1127
|
+
const expr = literalFieldReadExpression(source, field);
|
|
1128
|
+
return expr ? `${target}.${name} = ${expr};` : null;
|
|
1129
|
+
}
|
|
1130
|
+
function literalFieldReadExpression(source, field) {
|
|
1131
|
+
const shape = fieldShape(field);
|
|
1132
|
+
if (shape?.kind !== 'literal')
|
|
1133
|
+
return null;
|
|
1134
|
+
if (shape.valueType === 'number')
|
|
1135
|
+
return `read_number_field(${source}, ${JSON.stringify(field.name)})`;
|
|
1136
|
+
if (shape.valueType === 'boolean')
|
|
1137
|
+
return `read_boolean_field(${source}, ${JSON.stringify(field.name)})`;
|
|
1138
|
+
if (shape.valueType === 'string')
|
|
1139
|
+
return `read_string_field(${source}, ${JSON.stringify(field.name)})`;
|
|
1140
|
+
if (shape.valueType === 'null')
|
|
1141
|
+
return 'nullptr';
|
|
1142
|
+
return null;
|
|
1143
|
+
}
|
|
1144
|
+
// Resolve the element type info for a store array field, consistent with
|
|
1145
|
+
// `collectStoreArrayFields`. `itemType` is the unqualified symbol (used to
|
|
1146
|
+
// build `read_<itemType>` reader names — never contains `::`); `itemTypeRef`
|
|
1147
|
+
// is the qualified type-use spelling (`::__gea_type_X` for interface reuse).
|
|
1148
|
+
function arrayItemTypeInfo(storeClass, field) {
|
|
1149
|
+
const shape = fieldShape(field);
|
|
1150
|
+
const fieldName = sanitizeCppIdentifier(field.name);
|
|
1151
|
+
if (isArrayObjectShape(shape)) {
|
|
1152
|
+
const useInterfaceStruct = field.typedStorage
|
|
1153
|
+
? field.typedStorage.useInterfaceStruct === true
|
|
1154
|
+
: arrayReusesInterfaceStruct(shape);
|
|
1155
|
+
if (useInterfaceStruct) {
|
|
1156
|
+
const itemType = field.typedStorage?.itemType ?? interfaceItemSymbol(shape.elementTypeName);
|
|
1157
|
+
// `::`-qualified (global scope) — see `collectStoreArrayFields`.
|
|
1158
|
+
return { itemType, itemTypeRef: `::${itemType}`, useInterfaceStruct: true };
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
const itemType = field.typedStorage?.itemType ?? `${storeClass}_${fieldName}_item`;
|
|
1162
|
+
return { itemType, itemTypeRef: itemType, useInterfaceStruct: false };
|
|
1163
|
+
}
|
|
1164
|
+
function cppTypeForField(field, nameHint, declarations) {
|
|
1165
|
+
const shape = fieldShape(field);
|
|
1166
|
+
if (shape && isArrayObjectShape(shape) && field.typedStorage) {
|
|
1167
|
+
if (field.typedStorage.useInterfaceStruct) {
|
|
1168
|
+
return `std::vector<::${field.typedStorage.itemType}>`;
|
|
1169
|
+
}
|
|
1170
|
+
const elementType = cppTypeForShape(shape.element, field.typedStorage.itemType, declarations);
|
|
1171
|
+
return `std::vector<${elementType}>`;
|
|
1172
|
+
}
|
|
1173
|
+
return shape ? cppTypeForShape(shape, nameHint, declarations) : 'gea_cpp_value';
|
|
1174
|
+
}
|
|
1175
|
+
function cppTypeForShape(shape, nameHint, declarations) {
|
|
1176
|
+
if (shape.kind === 'literal') {
|
|
1177
|
+
if (shape.valueType === 'number') {
|
|
1178
|
+
// Keyed-list item position/velocity fields (x/y/dx/dy) lower to the
|
|
1179
|
+
// single-precision `gea_f32` type (hardware FPU) on boards that opt in via
|
|
1180
|
+
// GEA_NUMBER_FLOAT; plain `double` otherwise (byte-identical, test262-safe
|
|
1181
|
+
// default). The board gate lives in the `GEA_ITEM_NUMBER` macro emitted
|
|
1182
|
+
// below, so the field type is one `#define` rather than baked per-field.
|
|
1183
|
+
// gea_f32 is the unified single-precision type (see runtime/gea_f32.h);
|
|
1184
|
+
// this is the implicit, board-gated adoption path. Scoped to animated item
|
|
1185
|
+
// fields, where float's 2^24 integer-exactness limit is never a concern
|
|
1186
|
+
// (screen coords).
|
|
1187
|
+
if (/_item_(x|y|dx|dy)$/.test(nameHint))
|
|
1188
|
+
return 'GEA_ITEM_NUMBER';
|
|
1189
|
+
return 'double';
|
|
1190
|
+
}
|
|
1191
|
+
if (shape.valueType === 'boolean')
|
|
1192
|
+
return 'bool';
|
|
1193
|
+
if (shape.valueType === 'string')
|
|
1194
|
+
return 'std::string';
|
|
1195
|
+
return 'std::nullptr_t';
|
|
1196
|
+
}
|
|
1197
|
+
if (shape.kind === 'array') {
|
|
1198
|
+
// Interface-reuse array: storage element is the geatsc-declared global
|
|
1199
|
+
// struct `::__gea_type_<Name>`. Do NOT push a synthesized struct — geatsc
|
|
1200
|
+
// already emits it (and the gea plugin force-emits it; see collector.ts).
|
|
1201
|
+
if (isArrayObjectShape(shape) && arrayReusesInterfaceStruct(shape)) {
|
|
1202
|
+
return `std::vector<::${interfaceItemSymbol(shape.elementTypeName)}>`;
|
|
1203
|
+
}
|
|
1204
|
+
const elementType = shape.element ? cppTypeForShape(shape.element, `${nameHint}_item`, declarations) : 'gea_cpp_value';
|
|
1205
|
+
return `std::vector<${elementType}>`;
|
|
1206
|
+
}
|
|
1207
|
+
const structName = sanitizeCppIdentifier(nameHint);
|
|
1208
|
+
const nested = [];
|
|
1209
|
+
const fields = shape.fields.map((field) => {
|
|
1210
|
+
const fieldType = cppTypeForField(field, `${structName}_${sanitizeCppIdentifier(field.name)}`, nested);
|
|
1211
|
+
return ` ${fieldType} ${sanitizeCppIdentifier(field.name)};`;
|
|
1212
|
+
});
|
|
1213
|
+
declarations.push(...nested);
|
|
1214
|
+
// If any field is stored as `gea_number`, define the typedef right here (in
|
|
1215
|
+
// namespace gea_ir, before the struct that uses it). gea_number is `double` by
|
|
1216
|
+
// default (test262-safe, byte-identical); a board that defines GEA_NUMBER_FLOAT
|
|
1217
|
+
// lowers it to single-precision float for the hardware FPU. We emit it inline
|
|
1218
|
+
// rather than relying on runtime/gea_number.h because the per-app build dir
|
|
1219
|
+
// carries a stale snapshot of the runtime umbrella that need not include it. An
|
|
1220
|
+
// identical `using` re-declaration across structs is legal C++.
|
|
1221
|
+
if (fields.some((f) => f.includes('GEA_ITEM_NUMBER '))) {
|
|
1222
|
+
// The item-field number type is board-gated: on boards that define
|
|
1223
|
+
// GEA_NUMBER_FLOAT it is the single-precision `gea_f32` wrapper (hardware
|
|
1224
|
+
// FPU); otherwise plain `double` (byte-identical, test262-safe default).
|
|
1225
|
+
// gea_f32 itself is defined once in the runtime umbrella (runtime/gea_f32.h),
|
|
1226
|
+
// always float — so the board gate here only picks WHICH type the field
|
|
1227
|
+
// uses, not the wrapper's precision. Macro-guarded so re-definition across
|
|
1228
|
+
// structs is a no-op.
|
|
1229
|
+
declarations.push([
|
|
1230
|
+
'#ifndef GEA_ITEM_NUMBER_DEFINED',
|
|
1231
|
+
'#define GEA_ITEM_NUMBER_DEFINED',
|
|
1232
|
+
'#if defined(GEA_NUMBER_FLOAT)',
|
|
1233
|
+
'#define GEA_ITEM_NUMBER gea_f32',
|
|
1234
|
+
'#else',
|
|
1235
|
+
'#define GEA_ITEM_NUMBER double',
|
|
1236
|
+
'#endif',
|
|
1237
|
+
'#endif',
|
|
1238
|
+
].join('\n'));
|
|
1239
|
+
}
|
|
1240
|
+
declarations.push(`struct ${structName} {`);
|
|
1241
|
+
declarations.push(...fields);
|
|
1242
|
+
// Duck-type members so the typed struct can stand in for a `gea_cpp_value`
|
|
1243
|
+
// record slot in geatsc-emitter fallback code paths that call
|
|
1244
|
+
// `slot.record_get_literal(...)` / `slot.record_set_literal(...)` /
|
|
1245
|
+
// `slot.is_nullish()` / `slot.record_set(symbol, ...)` directly. The
|
|
1246
|
+
// gea plugin's lowered method bodies route through `set_typed_field`
|
|
1247
|
+
// / `read_number_field` overloads instead and don't need these, but
|
|
1248
|
+
// unmodified fallback emissions for the same store still link.
|
|
1249
|
+
const memberLines = generateTypedSlotMemberMethods(shape.fields, structName);
|
|
1250
|
+
if (memberLines.length > 0) {
|
|
1251
|
+
declarations.push('');
|
|
1252
|
+
declarations.push(...memberLines.map((l) => ` ${l}`));
|
|
1253
|
+
}
|
|
1254
|
+
declarations.push('};');
|
|
1255
|
+
declarations.push('');
|
|
1256
|
+
return structName;
|
|
1257
|
+
}
|
|
1258
|
+
function generateTypedSlotMemberMethods(fields, structName) {
|
|
1259
|
+
const getBranches = [];
|
|
1260
|
+
const setBranches = [];
|
|
1261
|
+
const fromValueAssigns = [];
|
|
1262
|
+
const fromRecordValueAssigns = [];
|
|
1263
|
+
const fromShapeAssigns = [];
|
|
1264
|
+
// Field-wise constructor params/inits, in declaration order. Lets a fully
|
|
1265
|
+
// typed seed construct the item directly — `gea_ir::X_item(0, 0, "#000")` —
|
|
1266
|
+
// instead of round-tripping each element through a boxed `gea_cpp_value`
|
|
1267
|
+
// record. See `rewriteCtorSeed` in cpp-store-typed-arrays.ts.
|
|
1268
|
+
const ctorParams = [];
|
|
1269
|
+
const ctorInits = [];
|
|
1270
|
+
for (const field of fields) {
|
|
1271
|
+
const shape = fieldShape(field);
|
|
1272
|
+
if (shape?.kind !== 'literal')
|
|
1273
|
+
continue;
|
|
1274
|
+
const name = sanitizeCppIdentifier(field.name);
|
|
1275
|
+
const key = JSON.stringify(field.name);
|
|
1276
|
+
if (shape.valueType === 'number') {
|
|
1277
|
+
getBranches.push(`if (std::strcmp(name, ${key}) == 0) return gea_cpp_value(this->${name});`);
|
|
1278
|
+
setBranches.push(`if (std::strcmp(name, ${key}) == 0) { this->${name} = gea::runtime::coerce::to_number(value); return; }`);
|
|
1279
|
+
fromValueAssigns.push(`this->${name} = read_number_field(value, ${key});`);
|
|
1280
|
+
fromRecordValueAssigns.push(`{ auto __gea_field = value.record_get_literal(${key}); if (!__gea_field.is_nullish()) this->${name} = gea::runtime::coerce::to_number(__gea_field); }`);
|
|
1281
|
+
fromShapeAssigns.push(`if constexpr (requires { other.${name}; }) this->${name} = static_cast<double>(other.${name});`);
|
|
1282
|
+
ctorParams.push(`double ${name}`);
|
|
1283
|
+
ctorInits.push(`${name}(${name})`);
|
|
1284
|
+
}
|
|
1285
|
+
else if (shape.valueType === 'boolean') {
|
|
1286
|
+
getBranches.push(`if (std::strcmp(name, ${key}) == 0) return gea_cpp_value(this->${name});`);
|
|
1287
|
+
setBranches.push(`if (std::strcmp(name, ${key}) == 0) { this->${name} = gea::runtime::coerce::to_boolean(value); return; }`);
|
|
1288
|
+
fromValueAssigns.push(`this->${name} = read_boolean_field(value, ${key});`);
|
|
1289
|
+
fromRecordValueAssigns.push(`{ auto __gea_field = value.record_get_literal(${key}); if (!__gea_field.is_nullish()) this->${name} = gea::runtime::coerce::to_boolean(__gea_field); }`);
|
|
1290
|
+
fromShapeAssigns.push(`if constexpr (requires { other.${name}; }) this->${name} = static_cast<bool>(other.${name});`);
|
|
1291
|
+
ctorParams.push(`bool ${name}`);
|
|
1292
|
+
ctorInits.push(`${name}(${name})`);
|
|
1293
|
+
}
|
|
1294
|
+
else if (shape.valueType === 'string') {
|
|
1295
|
+
getBranches.push(`if (std::strcmp(name, ${key}) == 0) return gea_cpp_value(this->${name});`);
|
|
1296
|
+
setBranches.push(`if (std::strcmp(name, ${key}) == 0) { this->${name} = gea_cpp_to_string(value); return; }`);
|
|
1297
|
+
fromValueAssigns.push(`this->${name} = read_string_field(value, ${key});`);
|
|
1298
|
+
fromRecordValueAssigns.push(`{ auto __gea_field = value.record_get_literal(${key}); if (!__gea_field.is_nullish()) this->${name} = gea_cpp_to_string(__gea_field); }`);
|
|
1299
|
+
fromShapeAssigns.push(`if constexpr (requires { other.${name}; }) this->${name} = static_cast<std::string>(other.${name});`);
|
|
1300
|
+
ctorParams.push(`std::string ${name}`);
|
|
1301
|
+
ctorInits.push(`${name}(std::move(${name}))`);
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
if (getBranches.length === 0 && setBranches.length === 0)
|
|
1305
|
+
return [];
|
|
1306
|
+
// A direct field-wise constructor for primitive object shapes. The one-field
|
|
1307
|
+
// case is important for static collision/tile data: those should construct
|
|
1308
|
+
// typed items directly instead of taking the generic shape-converting path.
|
|
1309
|
+
const allFieldsArePrimitive = fields.every((field) => fieldShape(field)?.kind === 'literal');
|
|
1310
|
+
const fieldwiseCtor = allFieldsArePrimitive && ctorParams.length >= 1 ? [`${structName}(${ctorParams.join(', ')}) : ${ctorInits.join(', ')} {}`] : [];
|
|
1311
|
+
if (!storeDynamicFallbackEnabled()) {
|
|
1312
|
+
return [
|
|
1313
|
+
`${structName}() = default;`,
|
|
1314
|
+
...fieldwiseCtor,
|
|
1315
|
+
'template <typename _GeaShape>',
|
|
1316
|
+
`${structName}(const _GeaShape &other) {`,
|
|
1317
|
+
...fromShapeAssigns.map((l) => ` ${l}`),
|
|
1318
|
+
`}`,
|
|
1319
|
+
`explicit ${structName}(const gea_cpp_value &value) {`,
|
|
1320
|
+
...fromRecordValueAssigns.map((l) => ` ${l}`),
|
|
1321
|
+
`}`,
|
|
1322
|
+
`static ${structName} __gea_from_value(const gea_cpp_value &value) { return ${structName}(value); }`,
|
|
1323
|
+
];
|
|
1324
|
+
}
|
|
1325
|
+
// The typed→dynamic body for `__gea_to_value()` mirrors the free
|
|
1326
|
+
// `gea_cpp_key(const X_item&)` overload but kept inline so any code that
|
|
1327
|
+
// does `pack_value(typed_item)` or invokes `gea_cpp_value(const T&)` (the
|
|
1328
|
+
// catch-all templated ctor that probes for `__gea_to_value()`) gets a
|
|
1329
|
+
// properly-populated record gea_cpp_value instead of an empty
|
|
1330
|
+
// kind=object placeholder.
|
|
1331
|
+
const toValueLines = [];
|
|
1332
|
+
for (const field of fields) {
|
|
1333
|
+
const shape = fieldShape(field);
|
|
1334
|
+
if (shape?.kind !== 'literal')
|
|
1335
|
+
continue;
|
|
1336
|
+
const name = sanitizeCppIdentifier(field.name);
|
|
1337
|
+
const key = JSON.stringify(field.name);
|
|
1338
|
+
toValueLines.push(`__gea_out.record_set_literal(${key}, gea_cpp_value(this->${name}));`);
|
|
1339
|
+
}
|
|
1340
|
+
return [
|
|
1341
|
+
// Default ctor — a user-declared default keeps brace-init `T{}` working
|
|
1342
|
+
// and pairs with the converting ctors below so the struct is no longer
|
|
1343
|
+
// an aggregate but still cheaply zero-initialisable.
|
|
1344
|
+
`${structName}() = default;`,
|
|
1345
|
+
...fieldwiseCtor,
|
|
1346
|
+
// Converting ctor from `gea_cpp_value`. Marked `explicit` so it doesn't
|
|
1347
|
+
// make typed and dynamic interchangeable in implicit-conversion
|
|
1348
|
+
// contexts (e.g. ternaries that mix a typed slot and a gea_cpp_value
|
|
1349
|
+
// sentinel); without `explicit` the compiler reports the conditional
|
|
1350
|
+
// as ambiguous because `gea_cpp_value` itself has a catch-all
|
|
1351
|
+
// `gea_cpp_value(const T&)` template that would convert the typed slot
|
|
1352
|
+
// back. Call sites that need the conversion (notably `push_array_items`
|
|
1353
|
+
// and the geatsc emitter's `vec.push_back(gea_cpp_key(<record>))`
|
|
1354
|
+
// fallback) go through `static_cast<X_item>(...)`, which is wired in
|
|
1355
|
+
// both `cpp-store-method-replacements.ts`'s `push_array_items` and the
|
|
1356
|
+
// typed-array push-rewrite in `cpp-store-typed-arrays.ts`.
|
|
1357
|
+
`explicit ${structName}(const gea_cpp_value &value) {`,
|
|
1358
|
+
...fromValueAssigns.map((l) => ` ${l}`),
|
|
1359
|
+
`}`,
|
|
1360
|
+
`static ${structName} __gea_from_value(const gea_cpp_value &value) { return ${structName}(value); }`,
|
|
1361
|
+
// `__gea_to_value()` matches the convention the geatsc runtime probes
|
|
1362
|
+
// for in `pack_value` and the templated `gea_cpp_value(const T&)`
|
|
1363
|
+
// catch-all ctor. Without this, those paths produce an empty
|
|
1364
|
+
// kind=object gea_cpp_value for typed items — which silently breaks
|
|
1365
|
+
// any reactive consumer that reads the array via the dynamic surface
|
|
1366
|
+
// (`store.record_get_literal("balls")` snapshots, change-record
|
|
1367
|
+
// previousValue, etc.).
|
|
1368
|
+
`gea_cpp_value __gea_to_value() const {`,
|
|
1369
|
+
` gea_cpp_value __gea_out;`,
|
|
1370
|
+
` __gea_out.kind = gea_cpp_value::kind_t::record;`,
|
|
1371
|
+
` __gea_out.entries = std::make_shared<std::vector<std::pair<std::string, gea_cpp_value>>>();`,
|
|
1372
|
+
...toValueLines.map((l) => ` ${l}`),
|
|
1373
|
+
` return __gea_out;`,
|
|
1374
|
+
`}`,
|
|
1375
|
+
// Converting ctor from any shape-equivalent struct (e.g. the
|
|
1376
|
+
// `__gea_record_N{...}` anonymous record temporaries the geatsc emitter
|
|
1377
|
+
// produces for typed object literals at each source location). Field
|
|
1378
|
+
// names are checked at compile time via `requires`. Implicit so the
|
|
1379
|
+
// emitter's `vec.push_back(<record temp>)` pattern flows directly.
|
|
1380
|
+
'template <typename _GeaShape, std::enable_if_t<!std::is_same_v<std::decay_t<_GeaShape>, gea_cpp_value> && !std::is_same_v<std::decay_t<_GeaShape>, ' + structName + '>, int> = 0>',
|
|
1381
|
+
`${structName}(const _GeaShape &other) {`,
|
|
1382
|
+
...fromShapeAssigns.map((l) => ` ${l}`),
|
|
1383
|
+
`}`,
|
|
1384
|
+
'gea_cpp_value record_get_literal(const char *name) const {',
|
|
1385
|
+
...getBranches.map((l) => ` ${l}`),
|
|
1386
|
+
' return gea_cpp_value::missing();',
|
|
1387
|
+
'}',
|
|
1388
|
+
'void record_set_literal(const char *name, const gea_cpp_value &value) {',
|
|
1389
|
+
...setBranches.map((l) => ` ${l}`),
|
|
1390
|
+
'}',
|
|
1391
|
+
// record_set(const gea_cpp_value &symbol_key, ...) — the legacy per-slot
|
|
1392
|
+
// dirty marker. Typed slots don't need it because dirty tracking is
|
|
1393
|
+
// signalled at the array level by `mark_dirty_field(array_key)`.
|
|
1394
|
+
'template <typename Key, typename Value>',
|
|
1395
|
+
'void record_set(const Key &, const Value &) {}',
|
|
1396
|
+
'bool is_nullish() const { return false; }',
|
|
1397
|
+
];
|
|
1398
|
+
}
|
|
1399
|
+
function fieldShape(field) {
|
|
1400
|
+
return field.shape ?? shapeFromInitializer(field.initializer);
|
|
1401
|
+
}
|
|
1402
|
+
function shapeFromInitializer(initializer) {
|
|
1403
|
+
if (!initializer)
|
|
1404
|
+
return null;
|
|
1405
|
+
const text = initializer.trim();
|
|
1406
|
+
if (/^-?(?:\d+|\d+\.\d+|\.\d+)$/.test(text))
|
|
1407
|
+
return { kind: 'literal', valueType: 'number' };
|
|
1408
|
+
if (text === 'true' || text === 'false')
|
|
1409
|
+
return { kind: 'literal', valueType: 'boolean' };
|
|
1410
|
+
if (text === 'null')
|
|
1411
|
+
return { kind: 'literal', valueType: 'null' };
|
|
1412
|
+
if ((text.startsWith("'") && text.endsWith("'")) || (text.startsWith('"') && text.endsWith('"'))) {
|
|
1413
|
+
return { kind: 'literal', valueType: 'string' };
|
|
1414
|
+
}
|
|
1415
|
+
return null;
|
|
1416
|
+
}
|
|
1417
|
+
function shapeFromConstantInitializer(initializer, constants, constantShapes = new Map()) {
|
|
1418
|
+
if (!initializer)
|
|
1419
|
+
return null;
|
|
1420
|
+
const text = initializer.trim();
|
|
1421
|
+
const name = text.startsWith('-') ? text.slice(1).trim() : text;
|
|
1422
|
+
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name))
|
|
1423
|
+
return null;
|
|
1424
|
+
const constant = constants.get(name);
|
|
1425
|
+
if (constant && constant.valueType !== 'object-array')
|
|
1426
|
+
return { kind: 'literal', valueType: constant.valueType };
|
|
1427
|
+
return constantShapes.get(name) ?? null;
|
|
1428
|
+
}
|
|
1429
|
+
function collectConstInitializerShapes(sourceFiles, constants) {
|
|
1430
|
+
const shapes = new Map();
|
|
1431
|
+
for (const [name, constant] of constants) {
|
|
1432
|
+
if (constant.valueType === 'object-array')
|
|
1433
|
+
continue;
|
|
1434
|
+
shapes.set(name, { kind: 'literal', valueType: constant.valueType });
|
|
1435
|
+
}
|
|
1436
|
+
const pending = new Map();
|
|
1437
|
+
for (const file of reachableLocalSourceFiles([...sourceFiles])) {
|
|
1438
|
+
let sourceText;
|
|
1439
|
+
try {
|
|
1440
|
+
sourceText = fs.readFileSync(file, 'utf8');
|
|
1441
|
+
}
|
|
1442
|
+
catch {
|
|
1443
|
+
continue;
|
|
1444
|
+
}
|
|
1445
|
+
const sourceFile = ts.createSourceFile(file, sourceText, ts.ScriptTarget.Latest, true, file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
1446
|
+
for (const statement of sourceFile.statements) {
|
|
1447
|
+
if (!ts.isVariableStatement(statement) || (statement.declarationList.flags & ts.NodeFlags.Const) === 0)
|
|
1448
|
+
continue;
|
|
1449
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
1450
|
+
if (!ts.isIdentifier(declaration.name) || !declaration.initializer)
|
|
1451
|
+
continue;
|
|
1452
|
+
pending.set(declaration.name.text, declaration.initializer.getText(sourceFile));
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
let changed = true;
|
|
1457
|
+
while (changed) {
|
|
1458
|
+
changed = false;
|
|
1459
|
+
for (const [name, expr] of pending) {
|
|
1460
|
+
if (shapes.has(name))
|
|
1461
|
+
continue;
|
|
1462
|
+
const shape = shapeFromExpression(expr, shapes);
|
|
1463
|
+
if (!shape)
|
|
1464
|
+
continue;
|
|
1465
|
+
shapes.set(name, shape);
|
|
1466
|
+
changed = true;
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
return shapes;
|
|
1470
|
+
}
|
|
1471
|
+
function collectStoreFieldTypeShapes(sourceFiles, stores) {
|
|
1472
|
+
const storeNames = new Set(stores.map((store) => sanitizeCppIdentifier(store.className)));
|
|
1473
|
+
const shapes = new Map();
|
|
1474
|
+
for (const file of reachableLocalSourceFiles([...sourceFiles])) {
|
|
1475
|
+
let sourceText;
|
|
1476
|
+
try {
|
|
1477
|
+
sourceText = fs.readFileSync(file, 'utf8');
|
|
1478
|
+
}
|
|
1479
|
+
catch {
|
|
1480
|
+
continue;
|
|
1481
|
+
}
|
|
1482
|
+
const sourceFile = ts.createSourceFile(file, sourceText, ts.ScriptTarget.Latest, true, file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
1483
|
+
for (const statement of sourceFile.statements) {
|
|
1484
|
+
if (!ts.isClassDeclaration(statement) || !statement.name)
|
|
1485
|
+
continue;
|
|
1486
|
+
const className = sanitizeCppIdentifier(statement.name.text);
|
|
1487
|
+
if (!storeNames.has(className))
|
|
1488
|
+
continue;
|
|
1489
|
+
for (const member of statement.members) {
|
|
1490
|
+
if (!ts.isPropertyDeclaration(member) || !member.type || !ts.isIdentifier(member.name))
|
|
1491
|
+
continue;
|
|
1492
|
+
const shape = shapeFromTypeNode(member.type);
|
|
1493
|
+
if (shape)
|
|
1494
|
+
shapes.set(`${className}.${sanitizeCppIdentifier(member.name.text)}`, shape);
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
return shapes;
|
|
1499
|
+
}
|
|
1500
|
+
function shapeFromTypeNode(type) {
|
|
1501
|
+
if (type.kind === ts.SyntaxKind.NumberKeyword)
|
|
1502
|
+
return { kind: 'literal', valueType: 'number' };
|
|
1503
|
+
if (type.kind === ts.SyntaxKind.StringKeyword)
|
|
1504
|
+
return { kind: 'literal', valueType: 'string' };
|
|
1505
|
+
if (type.kind === ts.SyntaxKind.BooleanKeyword)
|
|
1506
|
+
return { kind: 'literal', valueType: 'boolean' };
|
|
1507
|
+
if (ts.isArrayTypeNode(type))
|
|
1508
|
+
return arrayShapeFromElementTypeNode(type.elementType);
|
|
1509
|
+
if (ts.isTypeReferenceNode(type) && ts.isIdentifier(type.typeName)) {
|
|
1510
|
+
const typeName = type.typeName.text;
|
|
1511
|
+
if ((typeName === 'Array' || typeName === 'ReadonlyArray') && type.typeArguments?.length === 1) {
|
|
1512
|
+
return arrayShapeFromElementTypeNode(type.typeArguments[0]);
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
return null;
|
|
1516
|
+
}
|
|
1517
|
+
function arrayShapeFromElementTypeNode(type) {
|
|
1518
|
+
if (ts.isParenthesizedTypeNode(type))
|
|
1519
|
+
return arrayShapeFromElementTypeNode(type.type);
|
|
1520
|
+
if (ts.isTypeLiteralNode(type)) {
|
|
1521
|
+
const fields = primitiveObjectFieldsFromMembers(type.members);
|
|
1522
|
+
return fields ? { kind: 'array', element: { kind: 'object', fields } } : null;
|
|
1523
|
+
}
|
|
1524
|
+
if (ts.isTypeReferenceNode(type) && ts.isIdentifier(type.typeName) && !type.typeArguments?.length) {
|
|
1525
|
+
return { kind: 'array', elementTypeName: type.typeName.text };
|
|
1526
|
+
}
|
|
1527
|
+
return null;
|
|
1528
|
+
}
|
|
1529
|
+
function shapeFromExpression(expr, constants) {
|
|
1530
|
+
const text = expr.trim();
|
|
1531
|
+
const literal = shapeFromInitializer(text);
|
|
1532
|
+
if (literal)
|
|
1533
|
+
return literal;
|
|
1534
|
+
const identifier = text.startsWith('-') ? text.slice(1).trim() : text;
|
|
1535
|
+
if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(identifier)) {
|
|
1536
|
+
const shape = constants.get(identifier);
|
|
1537
|
+
return shape?.kind === 'literal' && shape.valueType === 'number' ? shape : null;
|
|
1538
|
+
}
|
|
1539
|
+
if (isNumericExpression(text, constants))
|
|
1540
|
+
return { kind: 'literal', valueType: 'number' };
|
|
1541
|
+
return null;
|
|
1542
|
+
}
|
|
1543
|
+
function isNumericExpression(expr, constants) {
|
|
1544
|
+
const source = ts.createSourceFile('expr.ts', `const __x = ${expr};`, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
1545
|
+
const statement = source.statements[0];
|
|
1546
|
+
if (!statement || !ts.isVariableStatement(statement))
|
|
1547
|
+
return false;
|
|
1548
|
+
const init = statement.declarationList.declarations[0]?.initializer;
|
|
1549
|
+
if (!init)
|
|
1550
|
+
return false;
|
|
1551
|
+
return expressionIsNumeric(init, constants);
|
|
1552
|
+
}
|
|
1553
|
+
function expressionIsNumeric(node, constants) {
|
|
1554
|
+
if (ts.isNumericLiteral(node))
|
|
1555
|
+
return true;
|
|
1556
|
+
if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword || node.kind === ts.SyntaxKind.NullKeyword)
|
|
1557
|
+
return false;
|
|
1558
|
+
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
|
|
1559
|
+
return false;
|
|
1560
|
+
if (ts.isIdentifier(node)) {
|
|
1561
|
+
const shape = constants.get(node.text);
|
|
1562
|
+
return shape?.kind === 'literal' && shape.valueType === 'number';
|
|
1563
|
+
}
|
|
1564
|
+
if (ts.isParenthesizedExpression(node))
|
|
1565
|
+
return expressionIsNumeric(node.expression, constants);
|
|
1566
|
+
if (ts.isPrefixUnaryExpression(node)) {
|
|
1567
|
+
return ((node.operator === ts.SyntaxKind.MinusToken || node.operator === ts.SyntaxKind.PlusToken) &&
|
|
1568
|
+
expressionIsNumeric(node.operand, constants));
|
|
1569
|
+
}
|
|
1570
|
+
if (ts.isBinaryExpression(node)) {
|
|
1571
|
+
if (node.operatorToken.kind === ts.SyntaxKind.PlusToken ||
|
|
1572
|
+
node.operatorToken.kind === ts.SyntaxKind.MinusToken ||
|
|
1573
|
+
node.operatorToken.kind === ts.SyntaxKind.AsteriskToken ||
|
|
1574
|
+
node.operatorToken.kind === ts.SyntaxKind.SlashToken ||
|
|
1575
|
+
node.operatorToken.kind === ts.SyntaxKind.PercentToken) {
|
|
1576
|
+
return expressionIsNumeric(node.left, constants) && expressionIsNumeric(node.right, constants);
|
|
1577
|
+
}
|
|
1578
|
+
return false;
|
|
1579
|
+
}
|
|
1580
|
+
if (ts.isCallExpression(node)) {
|
|
1581
|
+
const callee = node.expression.getText();
|
|
1582
|
+
if (!/^Math\.(?:abs|ceil|floor|max|min|pow|round|sqrt|sin|cos|tan)$/.test(callee))
|
|
1583
|
+
return false;
|
|
1584
|
+
return node.arguments.every((arg) => expressionIsNumeric(arg, constants));
|
|
1585
|
+
}
|
|
1586
|
+
if (ts.isPropertyAccessExpression(node)) {
|
|
1587
|
+
const text = node.getText();
|
|
1588
|
+
return text === 'window.innerWidth' || text === 'window.innerHeight';
|
|
1589
|
+
}
|
|
1590
|
+
return false;
|
|
1591
|
+
}
|
|
1592
|
+
function reachableLocalSourceFiles(entryFiles) {
|
|
1593
|
+
const out = [];
|
|
1594
|
+
const pending = [...entryFiles];
|
|
1595
|
+
const seen = new Set();
|
|
1596
|
+
for (let index = 0; index < pending.length; index += 1) {
|
|
1597
|
+
const file = pending[index];
|
|
1598
|
+
if (seen.has(file) || !fs.existsSync(file))
|
|
1599
|
+
continue;
|
|
1600
|
+
seen.add(file);
|
|
1601
|
+
out.push(file);
|
|
1602
|
+
let source;
|
|
1603
|
+
try {
|
|
1604
|
+
source = fs.readFileSync(file, 'utf8');
|
|
1605
|
+
}
|
|
1606
|
+
catch {
|
|
1607
|
+
continue;
|
|
1608
|
+
}
|
|
1609
|
+
for (const imported of localImportFiles(file, source)) {
|
|
1610
|
+
if (!seen.has(imported))
|
|
1611
|
+
pending.push(imported);
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
return out;
|
|
1615
|
+
}
|
|
1616
|
+
function localImportFiles(file, source) {
|
|
1617
|
+
const out = [];
|
|
1618
|
+
const pattern = /\bimport\b[\s\S]*?\bfrom\s+['"](\.{1,2}\/[^'"]+)['"]/g;
|
|
1619
|
+
let match;
|
|
1620
|
+
while ((match = pattern.exec(source))) {
|
|
1621
|
+
const resolved = resolveLocalSource(file, match[1]);
|
|
1622
|
+
if (resolved)
|
|
1623
|
+
out.push(resolved);
|
|
1624
|
+
}
|
|
1625
|
+
return out;
|
|
1626
|
+
}
|
|
1627
|
+
function resolveLocalSource(fromFile, specifier) {
|
|
1628
|
+
const base = resolve(dirname(fromFile), specifier);
|
|
1629
|
+
const candidates = [
|
|
1630
|
+
base,
|
|
1631
|
+
`${base}.ts`,
|
|
1632
|
+
`${base}.tsx`,
|
|
1633
|
+
`${base}.js`,
|
|
1634
|
+
`${base}.jsx`,
|
|
1635
|
+
resolve(base, 'index.ts'),
|
|
1636
|
+
resolve(base, 'index.tsx'),
|
|
1637
|
+
resolve(base, 'index.js'),
|
|
1638
|
+
resolve(base, 'index.jsx'),
|
|
1639
|
+
];
|
|
1640
|
+
return candidates.find((candidate) => fs.existsSync(candidate)) ?? null;
|
|
1641
|
+
}
|
|
1642
|
+
function hasModifier(node, kind) {
|
|
1643
|
+
return ts.canHaveModifiers(node) && (ts.getModifiers(node) ?? []).some((modifier) => modifier.kind === kind);
|
|
1644
|
+
}
|
|
1645
|
+
function classExtendsStore(node) {
|
|
1646
|
+
return (node.heritageClauses ?? []).some((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword &&
|
|
1647
|
+
clause.types.some((type) => {
|
|
1648
|
+
const expr = type.expression;
|
|
1649
|
+
return ts.isIdentifier(expr) && expr.text === 'Store';
|
|
1650
|
+
}));
|
|
1651
|
+
}
|
|
1652
|
+
function parameterValueType(type) {
|
|
1653
|
+
if (!type)
|
|
1654
|
+
return undefined;
|
|
1655
|
+
if (type.kind === ts.SyntaxKind.StringKeyword)
|
|
1656
|
+
return 'string';
|
|
1657
|
+
if (type.kind === ts.SyntaxKind.NumberKeyword)
|
|
1658
|
+
return 'number';
|
|
1659
|
+
if (type.kind === ts.SyntaxKind.BooleanKeyword)
|
|
1660
|
+
return 'boolean';
|
|
1661
|
+
return undefined;
|
|
1662
|
+
}
|
|
1663
|
+
function newExpressionClassName(expr) {
|
|
1664
|
+
const unwrapped = stripExpressionWrappers(expr);
|
|
1665
|
+
if (!ts.isNewExpression(unwrapped) || !ts.isIdentifier(unwrapped.expression))
|
|
1666
|
+
return null;
|
|
1667
|
+
return sanitizeCppIdentifier(unwrapped.expression.text);
|
|
1668
|
+
}
|
|
1669
|
+
function stripExpressionWrappers(expr) {
|
|
1670
|
+
let current = expr;
|
|
1671
|
+
while (ts.isParenthesizedExpression(current) ||
|
|
1672
|
+
ts.isAsExpression(current) ||
|
|
1673
|
+
ts.isTypeAssertionExpression(current) ||
|
|
1674
|
+
ts.isNonNullExpression(current) ||
|
|
1675
|
+
ts.isSatisfiesExpression(current)) {
|
|
1676
|
+
current = current.expression;
|
|
1677
|
+
}
|
|
1678
|
+
return current;
|
|
1679
|
+
}
|
|
1680
|
+
function isArrayObjectShape(shape) {
|
|
1681
|
+
return shape?.kind === 'array' && shape.element?.kind === 'object';
|
|
1682
|
+
}
|
|
1683
|
+
// The geatsc-declared interface struct symbol. Must match the symbol the
|
|
1684
|
+
// geatsc collector emits (`__gea_type_<safeIdent(name)>` — see
|
|
1685
|
+
// declarations/collector.ts). `sanitizeCppIdentifier` agrees with `safeIdent`
|
|
1686
|
+
// for ordinary alphanumeric interface names, which is the only shape that
|
|
1687
|
+
// reaches this path (named interface with all-primitive fields).
|
|
1688
|
+
export function interfaceItemSymbol(name) {
|
|
1689
|
+
return `__gea_type_${sanitizeCppIdentifier(name)}`;
|
|
1690
|
+
}
|
|
1691
|
+
// SINGLE SOURCE OF TRUTH for the interface-reuse opt-in (see also Fix 3:
|
|
1692
|
+
// `reconcileInterfaceStructReuse` below). The criterion here is the plugin's
|
|
1693
|
+
// FIRST, optimistic gate; it is later RECONCILED against geatsc's actual
|
|
1694
|
+
// emitted output so the plugin never references a `__gea_type_<Name>` struct
|
|
1695
|
+
// geatsc did not emit.
|
|
1696
|
+
//
|
|
1697
|
+
// An array shape is eligible to reuse geatsc's interface struct when ALL hold:
|
|
1698
|
+
// 1. it names a concrete interface element type (`shape.elementTypeName`);
|
|
1699
|
+
// 2. every element field present in the initializer is primitive (a
|
|
1700
|
+
// `literal` shape) — non-all-primitive keeps the synthesized path so
|
|
1701
|
+
// geatsc's file-scope field widening (which demotes nested record/array
|
|
1702
|
+
// fields to gea_cpp_value) can't desync from our field-by-field access;
|
|
1703
|
+
// 3. the interface name and every field name are PLAIN C++ identifiers whose
|
|
1704
|
+
// plugin spelling (`sanitizeCppIdentifier`) is verbatim. geatsc spells the
|
|
1705
|
+
// same names with `safeIdent`; the two agree only for plain identifiers
|
|
1706
|
+
// that neither sanitizer mangles. This guarantees the presence-flag
|
|
1707
|
+
// spelling (`__gea_has_<field>`) matches on both sides — a guard the
|
|
1708
|
+
// source-level struct-name reconciliation cannot see (it checks the struct
|
|
1709
|
+
// name, not per-field members).
|
|
1710
|
+
//
|
|
1711
|
+
// Note: criterion (2) is over INITIALIZER fields only (the plugin cannot see
|
|
1712
|
+
// the declared interface), whereas geatsc decides over the DECLARED interface.
|
|
1713
|
+
// They can diverge (interface has a non-primitive field the initializer omits).
|
|
1714
|
+
// `reconcileInterfaceStructReuse` resolves that by downgrading to the
|
|
1715
|
+
// synthesized path whenever geatsc did not actually emit the struct.
|
|
1716
|
+
function arrayReusesInterfaceStruct(shape) {
|
|
1717
|
+
if (!shape.elementTypeName)
|
|
1718
|
+
return false;
|
|
1719
|
+
if (!isPlainCppIdentifier(shape.elementTypeName))
|
|
1720
|
+
return false;
|
|
1721
|
+
return shape.element.fields.every((field) => fieldShape(field)?.kind === 'literal' && isPlainCppIdentifier(field.name));
|
|
1722
|
+
}
|
|
1723
|
+
// True when `name` is a PLAIN C++ identifier (`[A-Za-z_][A-Za-z0-9_]*`). For
|
|
1724
|
+
// such names the plugin's `sanitizeCppIdentifier` and geatsc's `safeIdent`
|
|
1725
|
+
// provably produce the SAME spelling — including reserved/keyword/stdlib names,
|
|
1726
|
+
// which BOTH mangle identically to `__gea_<name>` (e.g. `index` →
|
|
1727
|
+
// `__gea_index`, `y0` → `__gea_y0`). This is the criterion the reviewer asked
|
|
1728
|
+
// for ("field names are all plain identifiers"); a stricter verbatim-identity
|
|
1729
|
+
// check would WRONGLY exclude reserved-but-agreeing names like `index` and
|
|
1730
|
+
// desync the plugin from geatsc (which has no such guard and would still emit
|
|
1731
|
+
// and type the property with the struct). Non-identifier names (numeric or
|
|
1732
|
+
// symbol keys, `foo-bar`) are mangled with hex escapes (`_x2d_`) and are the
|
|
1733
|
+
// only place the two could disagree, so they are excluded here.
|
|
1734
|
+
function isPlainCppIdentifier(name) {
|
|
1735
|
+
return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name);
|
|
1736
|
+
}
|
|
1737
|
+
function isFieldReadableShape(shape) {
|
|
1738
|
+
return shape?.kind === 'literal' || isArrayObjectShape(shape);
|
|
1739
|
+
}
|