@geastack/compiler 1.0.48 → 1.0.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +57 -19
  2. package/dist/cli.js +2 -1
  3. package/dist/compiler.d.ts +1 -1
  4. package/dist/compiler.js +13 -6
  5. package/dist/conversion/derive.js +5 -0
  6. package/dist/conversion/native-field-view.d.ts +7 -0
  7. package/dist/conversion/native-field-view.js +50 -0
  8. package/dist/conversion/native-record-products.js +1 -0
  9. package/dist/conversion/native-view-origins.d.ts +1 -1
  10. package/dist/conversion/native-view-origins.js +5 -4
  11. package/dist/conversion/nodes.d.ts +9 -0
  12. package/dist/conversion/nodes.js +18 -0
  13. package/dist/conversion/record-view.d.ts +25 -1
  14. package/dist/conversion/record-view.js +61 -2
  15. package/dist/conversion/structural-plan.js +7 -6
  16. package/dist/ir/borrowed-field-reads.d.ts +30 -0
  17. package/dist/ir/borrowed-field-reads.js +218 -0
  18. package/dist/ir/borrowed-window-cells.d.ts +35 -0
  19. package/dist/ir/borrowed-window-cells.js +117 -0
  20. package/dist/ir/call-dispatch.js +21 -4
  21. package/dist/ir/callable-class-flow.js +269 -43
  22. package/dist/ir/captures.js +18 -1
  23. package/dist/ir/certify.js +14 -1
  24. package/dist/ir/construction-only-fields.d.ts +15 -1
  25. package/dist/ir/construction-only-fields.js +71 -3
  26. package/dist/ir/dead-logical-merge.d.ts +4 -0
  27. package/dist/ir/dead-logical-merge.js +89 -18
  28. package/dist/ir/dense-loops.d.ts +38 -4
  29. package/dist/ir/dense-loops.js +112 -17
  30. package/dist/ir/dense-read-windows.d.ts +42 -0
  31. package/dist/ir/dense-read-windows.js +137 -0
  32. package/dist/ir/facts.d.ts +12 -0
  33. package/dist/ir/facts.js +18 -2
  34. package/dist/ir/field-read-reuse.d.ts +71 -0
  35. package/dist/ir/field-read-reuse.js +430 -0
  36. package/dist/ir/hoist.d.ts +19 -2
  37. package/dist/ir/hoist.js +143 -24
  38. package/dist/ir/lower-narrow.js +19 -1
  39. package/dist/ir/model.d.ts +19 -0
  40. package/dist/ir/native-field-view-domains.d.ts +12 -2
  41. package/dist/ir/native-field-view-domains.js +51 -15
  42. package/dist/ir/native-field-view-facts.js +5 -2
  43. package/dist/ir/native-method-frames.js +15 -2
  44. package/dist/ir/plain-field-read.d.ts +31 -0
  45. package/dist/ir/plain-field-read.js +51 -0
  46. package/dist/ir/program-facts.d.ts +14 -0
  47. package/dist/ir/program-facts.js +85 -2
  48. package/dist/ir/proven-branches.js +8 -1
  49. package/dist/ir/publish-conversion-recipes.js +5 -1
  50. package/dist/ir/short-circuit-threading.d.ts +12 -4
  51. package/dist/ir/short-circuit-threading.js +124 -12
  52. package/dist/ir/stable-cell-reads.d.ts +24 -1
  53. package/dist/ir/stable-cell-reads.js +65 -42
  54. package/dist/ir/write-effects.d.ts +42 -0
  55. package/dist/ir/write-effects.js +208 -0
  56. package/dist/plugins/gea/contract.d.ts +3 -2
  57. package/dist/plugins/gea/contract.js +3 -1
  58. package/dist/plugins/gea/host.d.ts +7 -2
  59. package/dist/plugins/gea/host.js +25 -5
  60. package/dist/project-preparation.d.ts +11 -0
  61. package/dist/project-preparation.js +44 -0
  62. package/dist/projection/classes.d.ts +8 -0
  63. package/dist/projection/classes.js +112 -12
  64. package/dist/projection/dispatch.d.ts +24 -4
  65. package/dist/projection/dispatch.js +71 -2
  66. package/dist/projection/fields.js +2 -2
  67. package/dist/representation/model.d.ts +3 -0
  68. package/dist/representation/model.js +3 -0
  69. package/dist/representation/value-records.js +22 -0
  70. package/dist/semantics/frontend-timing.d.ts +9 -0
  71. package/dist/semantics/frontend-timing.js +43 -2
  72. package/dist/semantics/frontend.js +103 -7
  73. package/dist/semantics/model/operations.d.ts +7 -0
  74. package/dist/semantics/normalize/binding-fixpoint.js +7 -2
  75. package/dist/semantics/normalize/callable-data-write.js +6 -2
  76. package/dist/semantics/normalize/field-bindings.js +151 -111
  77. package/dist/semantics/normalize/flow/callable-reach.js +27 -0
  78. package/dist/semantics/normalize/flow/component-solver.js +23 -5
  79. package/dist/semantics/normalize/flow/source-record-data.js +6 -2
  80. package/dist/semantics/normalize/flow/source-value-session.d.ts +13 -0
  81. package/dist/semantics/normalize/flow/source-value-session.js +207 -65
  82. package/dist/semantics/normalize/global-host-mutations.js +162 -1
  83. package/dist/semantics/normalize/parameter-bindings.js +16 -1
  84. package/dist/semantics/normalize/producers/class-lifecycle.js +2 -1
  85. package/dist/semantics/normalize/producers/erasure.js +13 -8
  86. package/dist/semantics/subclass-member-overlay-transform.d.ts +3 -2
  87. package/dist/semantics/subclass-member-overlay-transform.js +416 -316
  88. package/dist/semantics/typescript-tsgo.d.ts +20 -0
  89. package/dist/semantics/typescript-tsgo.js +832 -0
  90. package/dist/semantics/typescript.d.ts +0 -9
  91. package/dist/semantics/typescript.js +4 -1
  92. package/dist/targets/cpp/borrowed-call-entry.d.ts +9 -0
  93. package/dist/targets/cpp/borrowed-call-entry.js +12 -2
  94. package/dist/targets/cpp/captures.js +4 -0
  95. package/dist/targets/cpp/class-properties/computed-method-value.d.ts +1 -1
  96. package/dist/targets/cpp/class-properties/computed-method-value.js +17 -7
  97. package/dist/targets/cpp/class-properties/emit-class-properties.d.ts +8 -0
  98. package/dist/targets/cpp/class-properties/emit-class-properties.js +62 -2
  99. package/dist/targets/cpp/class-properties/native-method-read.js +12 -1
  100. package/dist/targets/cpp/conversions.js +1 -0
  101. package/dist/targets/cpp/emit-arrays.d.ts +5 -0
  102. package/dist/targets/cpp/emit-arrays.js +60 -10
  103. package/dist/targets/cpp/emit-binding-reference.d.ts +19 -6
  104. package/dist/targets/cpp/emit-binding-reference.js +26 -8
  105. package/dist/targets/cpp/emit-bindings.js +22 -0
  106. package/dist/targets/cpp/emit-callable.js +133 -16
  107. package/dist/targets/cpp/emit-carrier-members.d.ts +6 -0
  108. package/dist/targets/cpp/emit-carrier-members.js +24 -2
  109. package/dist/targets/cpp/emit-context.d.ts +97 -1
  110. package/dist/targets/cpp/emit-context.js +52 -0
  111. package/dist/targets/cpp/emit-equality.js +3 -0
  112. package/dist/targets/cpp/emit-narrowing.js +9 -0
  113. package/dist/targets/cpp/emit-native-field-view.d.ts +24 -0
  114. package/dist/targets/cpp/emit-native-field-view.js +87 -8
  115. package/dist/targets/cpp/emit-properties.js +139 -16
  116. package/dist/targets/cpp/emit-record-view.js +49 -22
  117. package/dist/targets/cpp/emit-return.js +5 -1
  118. package/dist/targets/cpp/emit-tonumber.js +4 -1
  119. package/dist/targets/cpp/emit-union-properties.js +1 -1
  120. package/dist/targets/cpp/emit.d.ts +4 -1
  121. package/dist/targets/cpp/emit.js +148 -6
  122. package/dist/targets/cpp/reactive-dependencies.js +100 -28
  123. package/dist/targets/cpp/translation-unit.js +71 -17
  124. package/dist/targets/cpp/virtual-methods.d.ts +2 -2
  125. package/dist/targets/cpp/virtual-methods.js +11 -3
  126. package/package.json +1 -1
  127. package/src/targets/cpp/runtime/gea_runtime.h +400 -21
@@ -0,0 +1,832 @@
1
+ import { createRequire } from 'node:module';
2
+ import { readFileSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ const isHandle = (value) => typeof value === 'object' &&
5
+ value !== null &&
6
+ !Array.isArray(value) &&
7
+ ('n' in value || 't' in value || 's' in value || 'g' in value || 'o' in value);
8
+ const pascal = (name) => name.charAt(0).toUpperCase() + name.slice(1);
9
+ const normalizedPath = (file) => file.replace(/\\/g, '/').toLowerCase();
10
+ export const tsgoTypeScript = (real) => {
11
+ const require = createRequire(import.meta.url);
12
+ const koffi = require(process.env['GEA_TSGO_KOFFI'] ?? 'koffi');
13
+ const library = koffi.load(process.env['GEA_TSGO_DLL'] ?? 'tscapi.dll');
14
+ const nativeCall = library.func('void* tsc_call(const char*)');
15
+ const nativeFree = library.func('void tsc_free(void*)');
16
+ const stats = { calls: 0 };
17
+ const rpc = (request) => {
18
+ stats.calls++;
19
+ const pointer = nativeCall(JSON.stringify(request));
20
+ const text = koffi.decode(pointer, 'char', -1);
21
+ nativeFree(pointer);
22
+ const value = JSON.parse(text);
23
+ if (typeof value === 'object' && value !== null && 'error' in value)
24
+ throw new Error(`tsgo ${String(request['method'] ?? request['field'] ?? request['op'])}: ${String(value.error)}`);
25
+ return value;
26
+ };
27
+ // ---- flags: typescript-go bit -> TypeScript value, by name ----
28
+ const flagTable = JSON.parse(readFileSync(process.env['GEA_TSGO_FLAGS'] ?? 'corsa-flags.json', 'utf8'));
29
+ const flagMaps = new Map();
30
+ for (const [enumName, bits] of Object.entries(flagTable)) {
31
+ const stradaEnum = real[enumName];
32
+ const toStrada = new Map();
33
+ const toCorsa = new Map();
34
+ if (stradaEnum)
35
+ for (const [name, bit] of Object.entries(bits)) {
36
+ const value = stradaEnum[name];
37
+ if (typeof value !== 'number')
38
+ continue;
39
+ toStrada.set(bit, value);
40
+ // Only single-bit TypeScript values reverse cleanly.
41
+ if (value > 0 && (value & (value - 1)) === 0)
42
+ toCorsa.set(Math.log2(value), 2 ** bit);
43
+ }
44
+ flagMaps.set(enumName, { toStrada, toCorsa });
45
+ }
46
+ const translate = (enumName, value, direction) => {
47
+ const map = flagMaps.get(enumName)?.[direction];
48
+ if (!map)
49
+ return value;
50
+ let out = 0;
51
+ for (let bit = 0; bit < 53 && value >= 2 ** bit; bit++) {
52
+ if (Math.floor(value / 2 ** bit) % 2 === 0)
53
+ continue;
54
+ const mapped = map.get(bit);
55
+ if (mapped !== undefined)
56
+ out += mapped;
57
+ }
58
+ return out;
59
+ };
60
+ const stradaFlags = (enumName, value) => translate(enumName, value, 'toStrada');
61
+ const corsaFlags = (enumName, value) => translate(enumName, value, 'toCorsa');
62
+ // ---- kinds ----
63
+ const corsaKindNames = rpc({ op: 'kinds' });
64
+ const stradaKindOf = corsaKindNames.map((name) => real.SyntaxKind[name] ?? -1);
65
+ // ---- per-program session state ----
66
+ let files = [];
67
+ let stradaFiles = [];
68
+ let fileOfStrada = new WeakMap();
69
+ let mapped = [];
70
+ let nodeOfId = new Map();
71
+ let idOfNode = new WeakMap();
72
+ let typeOfId = new Map();
73
+ let symbolOfId = new Map();
74
+ let signatureOfId = new Map();
75
+ let objectOfId = new Map();
76
+ let generation = 0;
77
+ const mapFile = (index) => {
78
+ if (mapped[index])
79
+ return;
80
+ mapped[index] = true;
81
+ const source = stradaFiles[index];
82
+ if (!source)
83
+ return;
84
+ const byKey = new Map();
85
+ const add = (node) => {
86
+ const key = `${node.kind}:${node.pos}:${node.end}`;
87
+ const list = byKey.get(key);
88
+ if (list)
89
+ list.push(node);
90
+ else
91
+ byKey.set(key, [node]);
92
+ };
93
+ const visit = (node) => {
94
+ add(node);
95
+ real.forEachChild(node, visit, (list) => {
96
+ for (const child of list)
97
+ visit(child);
98
+ });
99
+ };
100
+ add(source);
101
+ real.forEachChild(source, visit, (list) => {
102
+ for (const child of list)
103
+ visit(child);
104
+ });
105
+ const flat = rpc({ op: 'fileNodes', file: index });
106
+ for (let at = 0; at < flat.length; at += 4) {
107
+ const id = flat[at];
108
+ const kind = stradaKindOf[flat[at + 1]] ?? -1;
109
+ const list = byKey.get(`${kind}:${flat[at + 2]}:${flat[at + 3]}`);
110
+ const node = list?.shift();
111
+ if (!node)
112
+ continue;
113
+ nodeOfId.set(id, node);
114
+ idOfNode.set(node, id);
115
+ }
116
+ };
117
+ const nodeFromId = (id) => {
118
+ const known = nodeOfId.get(id);
119
+ if (known)
120
+ return known;
121
+ const info = rpc({ op: 'node', id });
122
+ if (info.f >= 0)
123
+ mapFile(info.f);
124
+ return nodeOfId.get(id);
125
+ };
126
+ const idFromNode = (node) => {
127
+ const known = idOfNode.get(node);
128
+ if (known !== undefined)
129
+ return known;
130
+ const source = node.getSourceFile?.();
131
+ const index = source ? fileOfStrada.get(source) : undefined;
132
+ if (index === undefined)
133
+ return undefined;
134
+ mapFile(index);
135
+ return idOfNode.get(node);
136
+ };
137
+ // ---- value conversion ----
138
+ const toWire = (value) => {
139
+ if (value === undefined || value === null)
140
+ return null;
141
+ if (value instanceof TsgoType)
142
+ return { t: value.id };
143
+ if (value instanceof TsgoSymbol)
144
+ return { s: value.id };
145
+ if (value instanceof TsgoSignature)
146
+ return { g: value.id };
147
+ if (value instanceof TsgoObject)
148
+ return { o: value.id };
149
+ if (Array.isArray(value))
150
+ return value.map(toWire);
151
+ if (typeof value === 'object' && 'kind' in value && 'pos' in value) {
152
+ const id = idFromNode(value);
153
+ if (id === undefined) {
154
+ unmappedArgument = true;
155
+ noteUnmapped(value);
156
+ }
157
+ return id === undefined ? null : { n: id };
158
+ }
159
+ return value;
160
+ };
161
+ // A node with no typescript-go twin (synthesized, or a shape the two parsers
162
+ // span differently): the question has no answer, as TypeScript gives none for
163
+ // a node outside its program.
164
+ let unmappedArgument = false;
165
+ const unmappedKinds = new Map();
166
+ const noteUnmapped = (node) => {
167
+ if (!process.env['GEA_TSGO_DEBUG'])
168
+ return;
169
+ const label = real.SyntaxKind[node.kind] ?? String(node.kind);
170
+ const count = (unmappedKinds.get(label) ?? 0) + 1;
171
+ unmappedKinds.set(label, count);
172
+ if (count <= 3) {
173
+ const source = node.getSourceFile?.();
174
+ const where = source ? `${source.fileName.split('/').pop()}:${node.pos}-${node.end}` : 'detached';
175
+ console.error(`[tsgo] unmapped ${label} at ${where}${node.flags & real.NodeFlags.Synthesized ? ' (synthesized)' : ''}`);
176
+ }
177
+ };
178
+ const fromWire = (value) => {
179
+ if (value === null)
180
+ return undefined;
181
+ if (Array.isArray(value))
182
+ return value.map(fromWire);
183
+ if (isHandle(value)) {
184
+ if (value.n !== undefined)
185
+ return nodeFromId(value.n);
186
+ if (value.t !== undefined)
187
+ return typeFromId(value.t);
188
+ if (value.s !== undefined)
189
+ return symbolFromId(value.s);
190
+ if (value.g !== undefined)
191
+ return signatureFromId(value.g);
192
+ if (value.o !== undefined)
193
+ return objectFromId(value.o, value.c ?? '');
194
+ }
195
+ if (typeof value === 'object' && value !== null) {
196
+ const out = {};
197
+ for (const [key, item] of Object.entries(value))
198
+ out[key] = fromWire(item);
199
+ return out;
200
+ }
201
+ return value;
202
+ };
203
+ const callOn = (recv, method, args = []) => {
204
+ unmappedArgument = false;
205
+ const wire = args.map(toWire);
206
+ if (unmappedArgument)
207
+ return method.startsWith('GetTypeAt') || method === 'GetTypeOfSymbolAtLocation' ? checker.getAnyType() : undefined;
208
+ return fromWire(rpc({ op: 'call', recv, method, args: wire }));
209
+ };
210
+ const fieldOf = (recv, field) => fromWire(rpc({ op: 'get', recv, field }));
211
+ // ---- facades ----
212
+ class TsgoObject {
213
+ id;
214
+ className;
215
+ constructor(id, className) {
216
+ this.id = id;
217
+ this.className = className;
218
+ }
219
+ }
220
+ const objectFromId = (id, className) => {
221
+ const known = objectOfId.get(id);
222
+ if (known)
223
+ return known;
224
+ const target = new TsgoObject(id, className);
225
+ const facade = new Proxy(target, {
226
+ get: (object, key) => {
227
+ if (typeof key === 'symbol' || key in object)
228
+ return Reflect.get(object, key);
229
+ // Strada field names onto typescript-go accessors.
230
+ const name = className === 'IndexInfo' && key === 'type' ? 'ValueType' : pascal(key);
231
+ return callOn({ o: id }, name);
232
+ }
233
+ });
234
+ objectOfId.set(id, facade);
235
+ return facade;
236
+ };
237
+ class TsgoType {
238
+ id;
239
+ cache = new Map();
240
+ constructor(id) {
241
+ this.id = id;
242
+ }
243
+ once(key, compute) {
244
+ if (this.cache.has(key))
245
+ return this.cache.get(key);
246
+ const value = compute();
247
+ this.cache.set(key, value);
248
+ return value;
249
+ }
250
+ get handle() {
251
+ return { t: this.id };
252
+ }
253
+ get flags() {
254
+ return this.once('flags', () => stradaFlags('TypeFlags', callOn(this.handle, 'Flags')));
255
+ }
256
+ get objectFlags() {
257
+ return this.once('objectFlags', () => stradaFlags('ObjectFlags', callOn(this.handle, 'ObjectFlags')));
258
+ }
259
+ get symbol() {
260
+ return this.once('symbol', () => callOn(this.handle, 'Symbol'));
261
+ }
262
+ get aliasSymbol() {
263
+ return this.once('aliasSymbol', () => {
264
+ const alias = callOn(this.handle, 'Alias');
265
+ return alias?.symbol;
266
+ });
267
+ }
268
+ get aliasTypeArguments() {
269
+ return this.once('aliasTypeArguments', () => {
270
+ const alias = callOn(this.handle, 'Alias');
271
+ return alias?.typeArguments;
272
+ });
273
+ }
274
+ get types() {
275
+ return this.once('types', () => callOn(this.handle, 'GeatscTypes') ?? []);
276
+ }
277
+ get value() {
278
+ return this.once('value', () => callOn(this.handle, 'GeatscLiteralValue'));
279
+ }
280
+ get target() {
281
+ return this.once('target', () => callOn(this.handle, 'GeatscTarget'));
282
+ }
283
+ get intrinsicName() {
284
+ return this.once('intrinsicName', () => callOn(this.handle, 'GeatscIntrinsicName') || undefined);
285
+ }
286
+ // TypeScript's own type-data fields, read directly by parts of the compiler.
287
+ field(name) {
288
+ return this.once(`field:${name}`, () => callOn(this.handle, 'GeatscField', [name]));
289
+ }
290
+ get objectType() {
291
+ return this.field('objectType');
292
+ }
293
+ get indexType() {
294
+ return this.field('indexType');
295
+ }
296
+ get checkType() {
297
+ return this.field('checkType');
298
+ }
299
+ get extendsType() {
300
+ return this.field('extendsType');
301
+ }
302
+ get typeParameter() {
303
+ return this.field('typeParameter');
304
+ }
305
+ get constraintType() {
306
+ return this.field('constraintType');
307
+ }
308
+ get templateType() {
309
+ return this.field('templateType');
310
+ }
311
+ get nameType() {
312
+ return this.field('nameType');
313
+ }
314
+ get modifiersType() {
315
+ return this.field('modifiersType');
316
+ }
317
+ get baseType() {
318
+ return this.field('baseType');
319
+ }
320
+ get substitute() {
321
+ return this.field('substitute');
322
+ }
323
+ get type() {
324
+ return this.field('type');
325
+ }
326
+ get texts() {
327
+ return this.field('texts');
328
+ }
329
+ get fixedLength() {
330
+ return this.field('fixedLength');
331
+ }
332
+ get minLength() {
333
+ return this.field('minLength');
334
+ }
335
+ get hasRestElement() {
336
+ return this.field('hasRestElement');
337
+ }
338
+ get readonly() {
339
+ return this.field('readonly');
340
+ }
341
+ get elementFlags() {
342
+ return this.once('elementFlags', () => (this.field('elementFlags') ?? undefined)?.map((flag) => stradaFlags('ElementFlags', flag)));
343
+ }
344
+ get freshType() {
345
+ return this.field('freshType');
346
+ }
347
+ get regularType() {
348
+ return this.field('regularType');
349
+ }
350
+ get typeArguments() {
351
+ if ((this.objectFlags & real.ObjectFlags.Reference) === 0)
352
+ return undefined;
353
+ return checker.getTypeArguments(this);
354
+ }
355
+ getFlags() {
356
+ return this.flags;
357
+ }
358
+ getSymbol() {
359
+ return this.symbol;
360
+ }
361
+ getProperties() {
362
+ return checker.getPropertiesOfType(this);
363
+ }
364
+ getProperty(name) {
365
+ return checker.getPropertyOfType(this, name);
366
+ }
367
+ getApparentProperties() {
368
+ return checker.getPropertiesOfType(checker.getApparentType(this));
369
+ }
370
+ getCallSignatures() {
371
+ return checker.getSignaturesOfType(this, real.SignatureKind.Call);
372
+ }
373
+ getConstructSignatures() {
374
+ return checker.getSignaturesOfType(this, real.SignatureKind.Construct);
375
+ }
376
+ getStringIndexType() {
377
+ return checker.getIndexTypeOfType(this, real.IndexKind.String);
378
+ }
379
+ getNumberIndexType() {
380
+ return checker.getIndexTypeOfType(this, real.IndexKind.Number);
381
+ }
382
+ getBaseTypes() {
383
+ return checker.getBaseTypes(this);
384
+ }
385
+ getNonNullableType() {
386
+ return checker.getNonNullableType(this);
387
+ }
388
+ getConstraint() {
389
+ return checker.getBaseConstraintOfType(this);
390
+ }
391
+ getDefault() {
392
+ return callOn('checker', 'GetDefaultFromTypeParameter', [this]);
393
+ }
394
+ isUnion() {
395
+ return (this.flags & real.TypeFlags.Union) !== 0;
396
+ }
397
+ isIntersection() {
398
+ return (this.flags & real.TypeFlags.Intersection) !== 0;
399
+ }
400
+ isUnionOrIntersection() {
401
+ return (this.flags & real.TypeFlags.UnionOrIntersection) !== 0;
402
+ }
403
+ isLiteral() {
404
+ return (this.flags & (real.TypeFlags.StringLiteral | real.TypeFlags.NumberLiteral | real.TypeFlags.BigIntLiteral)) !== 0;
405
+ }
406
+ isStringLiteral() {
407
+ return (this.flags & real.TypeFlags.StringLiteral) !== 0;
408
+ }
409
+ isNumberLiteral() {
410
+ return (this.flags & real.TypeFlags.NumberLiteral) !== 0;
411
+ }
412
+ isTypeParameter() {
413
+ return (this.flags & real.TypeFlags.TypeParameter) !== 0;
414
+ }
415
+ isClassOrInterface() {
416
+ return (this.objectFlags & real.ObjectFlags.ClassOrInterface) !== 0;
417
+ }
418
+ isClass() {
419
+ return (this.objectFlags & real.ObjectFlags.Class) !== 0;
420
+ }
421
+ isIndexType() {
422
+ return (this.flags & real.TypeFlags.Index) !== 0;
423
+ }
424
+ }
425
+ const typeFromId = (id) => {
426
+ let type = typeOfId.get(id);
427
+ if (!type)
428
+ typeOfId.set(id, (type = new TsgoType(id)));
429
+ return type;
430
+ };
431
+ class TsgoSymbol {
432
+ id;
433
+ cache = new Map();
434
+ constructor(id) {
435
+ this.id = id;
436
+ }
437
+ once(key, compute) {
438
+ if (this.cache.has(key))
439
+ return this.cache.get(key);
440
+ const value = compute();
441
+ this.cache.set(key, value);
442
+ return value;
443
+ }
444
+ get handle() {
445
+ return { s: this.id };
446
+ }
447
+ get flags() {
448
+ return this.once('flags', () => stradaFlags('SymbolFlags', fieldOf(this.handle, 'Flags')));
449
+ }
450
+ get escapedName() {
451
+ return this.name;
452
+ }
453
+ get name() {
454
+ return this.once('name', () => fieldOf(this.handle, 'Name'));
455
+ }
456
+ get declarations() {
457
+ return this.once('declarations', () => {
458
+ const declarations = (fieldOf(this.handle, 'Declarations') ?? []).filter((declaration) => declaration !== undefined);
459
+ return declarations.length > 0 ? declarations : undefined;
460
+ });
461
+ }
462
+ get valueDeclaration() {
463
+ return this.once('valueDeclaration', () => fieldOf(this.handle, 'ValueDeclaration'));
464
+ }
465
+ get parent() {
466
+ return this.once('parent', () => fieldOf(this.handle, 'Parent'));
467
+ }
468
+ get exportSymbol() {
469
+ return this.once('exportSymbol', () => fieldOf(this.handle, 'ExportSymbol'));
470
+ }
471
+ get members() {
472
+ return this.once('members', () => tableOf(fieldOf(this.handle, 'Members')));
473
+ }
474
+ get exports() {
475
+ return this.once('exports', () => tableOf(fieldOf(this.handle, 'Exports')));
476
+ }
477
+ getName() {
478
+ return this.name;
479
+ }
480
+ getEscapedName() {
481
+ return this.escapedName;
482
+ }
483
+ getFlags() {
484
+ return this.flags;
485
+ }
486
+ getDeclarations() {
487
+ return this.declarations;
488
+ }
489
+ }
490
+ const tableOf = (value) => {
491
+ if (value === undefined || value === null || typeof value !== 'object')
492
+ return undefined;
493
+ return new Map(Object.entries(value).map(([name, symbol]) => [name, symbol]));
494
+ };
495
+ const symbolFromId = (id) => {
496
+ let symbol = symbolOfId.get(id);
497
+ if (!symbol)
498
+ symbolOfId.set(id, (symbol = new TsgoSymbol(id)));
499
+ return symbol;
500
+ };
501
+ class TsgoSignature {
502
+ id;
503
+ cache = new Map();
504
+ constructor(id) {
505
+ this.id = id;
506
+ }
507
+ once(key, compute) {
508
+ if (this.cache.has(key))
509
+ return this.cache.get(key);
510
+ const value = compute();
511
+ this.cache.set(key, value);
512
+ return value;
513
+ }
514
+ get handle() {
515
+ return { g: this.id };
516
+ }
517
+ get declaration() {
518
+ return this.once('declaration', () => callOn(this.handle, 'Declaration'));
519
+ }
520
+ get parameters() {
521
+ return this.once('parameters', () => callOn(this.handle, 'Parameters') ?? []);
522
+ }
523
+ get typeParameters() {
524
+ return this.once('typeParameters', () => {
525
+ const parameters = callOn(this.handle, 'TypeParameters');
526
+ return parameters && parameters.length > 0 ? parameters : undefined;
527
+ });
528
+ }
529
+ get thisParameter() {
530
+ return this.once('thisParameter', () => callOn(this.handle, 'ThisParameter'));
531
+ }
532
+ get minArgumentCount() {
533
+ return this.once('minArgumentCount', () => callOn(this.handle, 'MinArgumentCount'));
534
+ }
535
+ get flags() {
536
+ return this.once('flags', () => stradaFlags('SignatureFlags', callOn(this.handle, 'Flags')));
537
+ }
538
+ getDeclaration() {
539
+ return this.declaration;
540
+ }
541
+ getParameters() {
542
+ return this.parameters;
543
+ }
544
+ getTypeParameters() {
545
+ return this.typeParameters;
546
+ }
547
+ getReturnType() {
548
+ return checker.getReturnTypeOfSignature(this);
549
+ }
550
+ }
551
+ const signatureFromId = (id) => {
552
+ let signature = signatureOfId.get(id);
553
+ if (!signature)
554
+ signatureOfId.set(id, (signature = new TsgoSignature(id)));
555
+ return signature;
556
+ };
557
+ // ---- checker ----
558
+ // Methods whose arguments carry TypeScript enum values typescript-go numbers differently.
559
+ const argumentAdapters = {
560
+ resolveName: ([name, location, meaning, excludeGlobals]) => [
561
+ name,
562
+ location,
563
+ corsaFlags('SymbolFlags', meaning),
564
+ excludeGlobals
565
+ ],
566
+ getSymbolsInScope: ([location, meaning]) => [location, corsaFlags('SymbolFlags', meaning)],
567
+ getNullableType: ([type, flags]) => [type, corsaFlags('TypeFlags', flags)],
568
+ typeToString: ([type]) => [type],
569
+ getIndexTypeOfType: ([type, kind]) => [type, kind === real.IndexKind.Number ? checker.getNumberType() : checker.getStringType()],
570
+ getIndexInfoOfType: ([type, kind]) => [type, kind === real.IndexKind.Number ? checker.getNumberType() : checker.getStringType()],
571
+ getNumberLiteralType: ([value]) => [value],
572
+ getBigIntLiteralType: ([value]) => {
573
+ const literal = value;
574
+ return [literal.negative, literal.base10Value];
575
+ }
576
+ };
577
+ // TypeScript names typescript-go spells differently.
578
+ const methodNames = {
579
+ getIndexInfoOfType: 'GetIndexInfoOfType',
580
+ getTypeOfSymbol: 'GetTypeOfSymbol'
581
+ };
582
+ // ---- GEA_TSGO_COMPARE: the same question asked of TypeScript's own checker ----
583
+ let comparisonProgram = null;
584
+ let comparisonReal = null;
585
+ const comparisonMismatches = new Map();
586
+ const comparisonChecker = () => {
587
+ if (!comparisonReal && comparisonProgram)
588
+ comparisonReal = comparisonProgram.getTypeChecker();
589
+ return comparisonReal;
590
+ };
591
+ const declarationLabel = (node) => {
592
+ if (!node)
593
+ return '-';
594
+ const source = node.getSourceFile?.();
595
+ return `${source ? source.fileName.split('/').pop() : '?'}:${node.pos}`;
596
+ };
597
+ const summarize = (value, world) => {
598
+ if (value === undefined || value === null)
599
+ return 'none';
600
+ if (Array.isArray(value))
601
+ return `[${value.map((item) => summarize(item, world)).join(', ')}]`;
602
+ if (typeof value !== 'object')
603
+ return String(value);
604
+ if (value instanceof TsgoType)
605
+ return `type(${checker.typeToString(value)})`;
606
+ if (value instanceof TsgoSymbol)
607
+ return `symbol(${value.name}@${(value.declarations ?? []).map(declarationLabel).join('|')})`;
608
+ if (value instanceof TsgoSignature)
609
+ return `signature(${declarationLabel(value.declaration)})`;
610
+ const record = value;
611
+ if ('kind' in record && 'pos' in record)
612
+ return `${real.SyntaxKind[record['kind']]}@${declarationLabel(value)}`;
613
+ if ('escapedName' in record && 'flags' in record) {
614
+ const symbol = value;
615
+ return `symbol(${symbol.name}@${(symbol.declarations ?? []).map(declarationLabel).join('|')})`;
616
+ }
617
+ if ('parameters' in record && 'declaration' in record)
618
+ return `signature(${declarationLabel(value.declaration)})`;
619
+ if ('flags' in record && 'checker' in record) {
620
+ const reference = comparisonChecker();
621
+ return `type(${reference.typeToString(value)})`;
622
+ }
623
+ return 'object';
624
+ };
625
+ const checkerMethod = (key) => {
626
+ const method = methodNames[key] ?? pascal(key);
627
+ const adapt = argumentAdapters[key];
628
+ // typescript-go dereferences a type reference's target unconditionally.
629
+ if (key === 'getTypeArguments')
630
+ return (type) => type instanceof TsgoType && type.objectFlags & real.ObjectFlags.Reference ? callOn('checker', method, [type]) : [];
631
+ if (process.env['GEA_TSGO_COMPARE'])
632
+ return (...args) => {
633
+ const result = callOn('checker', method, adapt ? adapt(args) : args);
634
+ const reference = comparisonChecker();
635
+ const nodeOnly = args.every((arg) => arg === undefined || typeof arg !== 'object' || (arg !== null && 'kind' in arg && 'pos' in arg));
636
+ const real = reference?.[key];
637
+ if (!nodeOnly || typeof real !== 'function')
638
+ return result;
639
+ let expected;
640
+ try {
641
+ expected = real.apply(reference, args);
642
+ }
643
+ catch {
644
+ return result;
645
+ }
646
+ const mine = summarize(result, 'tsgo');
647
+ const theirs = summarize(expected, 'ts');
648
+ if (mine !== theirs) {
649
+ const key2 = `${key}: ${theirs} -> ${mine}`;
650
+ const count = (comparisonMismatches.get(key2) ?? 0) + 1;
651
+ comparisonMismatches.set(key2, count);
652
+ if (count === 1)
653
+ console.error(`[tsgo-compare] ${key}(${args.map((arg) => summarize(arg, 'ts')).join(', ')}): ts ${theirs} | tsgo ${mine}`);
654
+ }
655
+ return result;
656
+ };
657
+ if (process.env['GEA_TSGO_TRACE'])
658
+ return (...args) => {
659
+ const result = callOn('checker', method, adapt ? adapt(args) : args);
660
+ if (result instanceof TsgoType && result.flags & real.TypeFlags.Any) {
661
+ const describe = (value) => value instanceof TsgoType
662
+ ? `type(${checker.typeToString(value)})`
663
+ : value instanceof TsgoSymbol
664
+ ? `symbol(${value.name})`
665
+ : typeof value === 'object' && value !== null && 'kind' in value
666
+ ? `${real.SyntaxKind[value.kind]}(${value.getText?.().slice(0, 40)})`
667
+ : JSON.stringify(value);
668
+ console.error(`[tsgo-trace] ${key}(${args.map(describe).join(', ')}) -> any (${result.intrinsicName ?? ''})`);
669
+ }
670
+ return result;
671
+ };
672
+ return (...args) => callOn('checker', method, adapt ? adapt(args) : args);
673
+ };
674
+ // Every method a real checker has, as an own property: the compiler copies
675
+ // and wraps the checker (`{ ...checker }`), which a bare Proxy would survive
676
+ // with no methods at all.
677
+ const checkerTarget = {};
678
+ const realChecker = real.createProgram([], { noLib: true }).getTypeChecker();
679
+ for (const key of Object.keys(realChecker))
680
+ if (typeof realChecker[key] === 'function')
681
+ checkerTarget[key] = checkerMethod(key);
682
+ const checker = new Proxy(checkerTarget, {
683
+ get: (target, key) => {
684
+ if (typeof key === 'symbol')
685
+ return undefined;
686
+ if (!(key in target))
687
+ target[key] = checkerMethod(key);
688
+ return target[key];
689
+ }
690
+ });
691
+ const optionsJson = (options) => {
692
+ const out = {};
693
+ const enumName = (table, value) => typeof value === 'number' ? table[value]?.toLowerCase() : undefined;
694
+ for (const [key, value] of Object.entries(options)) {
695
+ if (value === undefined || key === 'configFilePath' || key === 'pathsBasePath' || key === 'configFile')
696
+ continue;
697
+ if (key === 'target')
698
+ out[key] = enumName(real.ScriptTarget, value);
699
+ else if (key === 'module')
700
+ out[key] = enumName(real.ModuleKind, value);
701
+ else if (key === 'moduleResolution') {
702
+ const name = enumName(real.ModuleResolutionKind, value);
703
+ out[key] = name === 'node10' || name === 'nodejs' || name === 'classic' ? 'bundler' : name;
704
+ }
705
+ else if (key === 'jsx')
706
+ out[key] = enumName(real.JsxEmit, value);
707
+ else if (key === 'newLine')
708
+ continue;
709
+ else if (key === 'lib')
710
+ continue;
711
+ else if (typeof value === 'boolean' || typeof value === 'string' || Array.isArray(value) || typeof value === 'number')
712
+ out[key] = value;
713
+ else if (typeof value === 'object')
714
+ out[key] = value;
715
+ }
716
+ // Every file the TypeScript program holds is a root below, libraries included.
717
+ out['noLib'] = true;
718
+ out['types'] = [];
719
+ out['skipLibCheck'] = true;
720
+ out['noEmit'] = true;
721
+ if (out['module'] === undefined)
722
+ out['module'] = 'esnext';
723
+ if (out['moduleResolution'] === undefined)
724
+ out['moduleResolution'] = out['module'] === 'nodenext' ? 'nodenext' : 'bundler';
725
+ return out;
726
+ };
727
+ const open = (program) => {
728
+ generation++;
729
+ comparisonProgram = program;
730
+ comparisonReal = null;
731
+ const sources = program.getSourceFiles();
732
+ const cwd = program.getCurrentDirectory();
733
+ const absolute = (fileName) => resolve(cwd, fileName).replace(/\\/g, '/');
734
+ const contents = {};
735
+ for (const source of sources)
736
+ contents[absolute(source.fileName)] = source.text;
737
+ const opened = rpc({
738
+ op: 'open',
739
+ cwd,
740
+ roots: sources.map((source) => absolute(source.fileName)),
741
+ files: contents,
742
+ options: optionsJson(program.getCompilerOptions())
743
+ });
744
+ if (process.env['GEA_TSGO_DEBUG'] && opened.configErrors.length > 0)
745
+ console.error('[tsgo] config:', opened.configErrors.join('\n'));
746
+ files = opened.files;
747
+ const byName = new Map(sources.map((source) => [normalizedPath(absolute(source.fileName)), source]));
748
+ stradaFiles = files.map((file) => byName.get(normalizedPath(file.name)));
749
+ fileOfStrada = new WeakMap();
750
+ stradaFiles.forEach((source, index) => {
751
+ if (source)
752
+ fileOfStrada.set(source, index);
753
+ });
754
+ mapped = files.map(() => false);
755
+ nodeOfId = new Map();
756
+ idOfNode = new WeakMap();
757
+ typeOfId = new Map();
758
+ symbolOfId = new Map();
759
+ signatureOfId = new Map();
760
+ objectOfId = new Map();
761
+ if (process.env['GEA_TSGO_DEBUG']) {
762
+ const missing = files.filter((_file, index) => !stradaFiles[index]).map((file) => file.name);
763
+ console.error(`[tsgo] opened ${files.length} files (${missing.length} without a TypeScript twin: ${missing.slice(0, 3).join(', ')}), generation ${generation}`);
764
+ const corsaNames = new Set(files.map((file) => normalizedPath(file.name)));
765
+ const lonely = sources.filter((source) => !corsaNames.has(normalizedPath(absolute(source.fileName)))).map((source) => source.fileName);
766
+ if (lonely.length > 0)
767
+ console.error(`[tsgo] ${lonely.length} TypeScript files typescript-go did not load: ${lonely.slice(0, 3).join(', ')}`);
768
+ }
769
+ };
770
+ const diagnosticsOf = (program, file) => {
771
+ const wanted = file ? [file] : program.getSourceFiles();
772
+ const out = [];
773
+ for (const source of wanted) {
774
+ const index = fileOfStrada.get(source);
775
+ if (index === undefined)
776
+ continue;
777
+ const handle = { n: files[index].node };
778
+ const raw = rpc({ op: 'call', recv: 'program', method: 'GetSemanticDiagnostics', args: [null, handle] });
779
+ for (const entry of raw ?? []) {
780
+ if (!isHandle(entry))
781
+ continue;
782
+ const recv = { o: entry.o };
783
+ out.push({
784
+ category: real.DiagnosticCategory.Error,
785
+ code: rpc({ op: 'call', recv, method: 'Code', args: [] }),
786
+ file: source,
787
+ start: rpc({ op: 'call', recv, method: 'Pos', args: [] }),
788
+ length: rpc({ op: 'call', recv, method: 'Len', args: [] }),
789
+ messageText: rpc({ op: 'call', recv, method: 'String', args: [] })
790
+ });
791
+ }
792
+ }
793
+ return out;
794
+ };
795
+ const createProgram = ((...args) => {
796
+ const program = real.createProgram(...args);
797
+ let current = -1;
798
+ const ensure = () => {
799
+ if (current === generation && current !== -1)
800
+ return;
801
+ open(program);
802
+ current = generation;
803
+ };
804
+ return new Proxy(program, {
805
+ get: (target, key, receiver) => {
806
+ if (key === 'getTypeChecker')
807
+ return () => {
808
+ ensure();
809
+ return checker;
810
+ };
811
+ if (key === 'getSemanticDiagnostics')
812
+ return (file) => {
813
+ ensure();
814
+ return process.env['GEA_TSGO_DIAGNOSTICS'] === '1' ? diagnosticsOf(target, file) : [];
815
+ };
816
+ if (key === 'getGlobalDiagnostics' || key === 'getDeclarationDiagnostics')
817
+ return () => [];
818
+ return Reflect.get(target, key, receiver);
819
+ }
820
+ });
821
+ });
822
+ process.on('exit', () => {
823
+ if (process.env['GEA_TSGO_COMPARE'])
824
+ for (const [label, count] of [...comparisonMismatches].sort((a, b) => b[1] - a[1]).slice(0, 25))
825
+ console.error(`[tsgo-compare-summary] ${count}x ${label.slice(0, 260)}`);
826
+ if (process.env['GEA_TSGO_DEBUG'])
827
+ console.error(`[tsgo] ${stats.calls} bridge calls; unmapped ${JSON.stringify(Object.fromEntries(unmappedKinds))}`);
828
+ });
829
+ return new Proxy(real, {
830
+ get: (target, key, receiver) => (key === 'createProgram' ? createProgram : Reflect.get(target, key, receiver))
831
+ });
832
+ };