@geastack/compiler 1.0.32 → 1.0.33

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/dist/compiler.js CHANGED
@@ -235,6 +235,23 @@ export const compile = (request) => {
235
235
  const nativeTypes = new Map([...coreNativeTypes, ...plugins.flatMap((plugin) => [...plugin.capabilities.nativeTypes])]);
236
236
  const nativeTypesByDeclaration = new Map(plugins.flatMap((plugin) => [...(plugin.capabilities.nativeTypesByDeclaration ?? new Map())]));
237
237
  const hostNamespaceRootDeclarations = plugins.flatMap((plugin) => plugin.capabilities.hostNamespaceRootDeclarations ?? []);
238
+ const hostProvidedNames = new Set([
239
+ ...coreHostFunctions.keys(),
240
+ ...coreHostConstants.keys(),
241
+ ...plugins.flatMap((plugin) => [
242
+ ...plugin.capabilities.hostFunctions.keys(),
243
+ ...plugin.capabilities.nativeConstants.keys(),
244
+ ...[...plugin.capabilities.hostFunctionsByDeclaration.values()].flatMap((names) => [...names.keys()]),
245
+ ...[...plugin.capabilities.hostConstantsByDeclaration.values()].flatMap((names) => [...names.keys()]),
246
+ // A namespace root or singleton is equally the host's by name: the
247
+ // framework states `declare const __gea_Panel: {...}` module-locally
248
+ // for a root its host table claims, and no global declares it.
249
+ ...plugin.capabilities.hostNamespaces.roots,
250
+ ...[...plugin.capabilities.hostNamespaceRootsByDeclaration.values()].flatMap((names) => [...names]),
251
+ ...plugin.capabilities.hostSingletons,
252
+ ...[...plugin.capabilities.hostSingletonsByDeclaration.values()].flatMap((names) => [...names])
253
+ ])
254
+ ]);
238
255
  const frontend = runFrontend({
239
256
  nativeFunctionDeclarations: plugins.flatMap((plugin) => plugin.capabilities.nativeFunctionDeclarations ?? []),
240
257
  ...(request.packageSources ? { packageSources: request.packageSources } : {}),
@@ -254,33 +271,15 @@ export const compile = (request) => {
254
271
  nativeTypesByDeclaration,
255
272
  hostSingletonDeclarations: new Map(plugins.flatMap((plugin) => [...(plugin.capabilities.hostSingletonDeclarations ?? new Map())])),
256
273
  standardClasses: new Set(coreNativeTypes.keys()),
257
- // What the installed hosts state they do NOT provide, unioned the same way
258
- // their positive claims are. A name is absent only because a host said so:
259
- // with no plugin stating one this set is empty and every ambient
260
- // declaration is believed exactly as before.
261
- absentGlobals: new Set(plugins.flatMap((plugin) => [...plugin.capabilities.absentGlobals])),
274
+ // An optional feature cannot erase a global another installed host
275
+ // actually supplies (for example WebGL absence versus Gea worker self).
276
+ absentGlobals: new Set(plugins.flatMap((plugin) => [...plugin.capabilities.absentGlobals]).filter((name) => !hostProvidedNames.has(name))),
262
277
  // The members the installed hosts reach on their own, unioned the same way
263
278
  // every other plugin table here is. `reachability.ts` keeps an instance
264
279
  // method only when live code names it, and a name only a lowering
265
280
  // synthesizes is one no walk over the source can see.
266
281
  hostReachedMemberKeys: new Set(plugins.flatMap((plugin) => [...plugin.capabilities.reachedMemberKeys])),
267
- hostProvidedNames: new Set([
268
- ...coreHostFunctions.keys(),
269
- ...coreHostConstants.keys(),
270
- ...plugins.flatMap((plugin) => [
271
- ...plugin.capabilities.hostFunctions.keys(),
272
- ...plugin.capabilities.nativeConstants.keys(),
273
- ...[...plugin.capabilities.hostFunctionsByDeclaration.values()].flatMap((names) => [...names.keys()]),
274
- ...[...plugin.capabilities.hostConstantsByDeclaration.values()].flatMap((names) => [...names.keys()]),
275
- // A namespace root or singleton is equally the host's by name: the
276
- // framework states `declare const __gea_Panel: {...}` module-locally
277
- // for a root its host table claims, and no global declares it.
278
- ...plugin.capabilities.hostNamespaces.roots,
279
- ...[...plugin.capabilities.hostNamespaceRootsByDeclaration.values()].flatMap((names) => [...names]),
280
- ...plugin.capabilities.hostSingletons,
281
- ...[...plugin.capabilities.hostSingletonsByDeclaration.values()].flatMap((names) => [...names])
282
- ])
283
- ]),
282
+ hostProvidedNames,
284
283
  hostNamespaceRoots: new Set(['Reflect', ...plugins.flatMap((plugin) => [...plugin.capabilities.hostNamespaces.roots])]),
285
284
  hostNamespaceRootDeclarations,
286
285
  // Every leaf path a plugin's own namespace tables publish -- see
package/dist/ir/lower.js CHANGED
@@ -1119,6 +1119,7 @@ exactArmNarrowing) => {
1119
1119
  exactArmNarrowing
1120
1120
  };
1121
1121
  const blockStarts = new Map();
1122
+ const bindingLifetimeOrigins = new Map();
1122
1123
  const finiteCloseStarts = new Map();
1123
1124
  const finiteCloseByStart = new Map();
1124
1125
  for (const id of order) {
@@ -1221,6 +1222,15 @@ exactArmNarrowing) => {
1221
1222
  finiteEntries.set(finiteCloseAtStart, { start: operationId, entry: block });
1222
1223
  }
1223
1224
  blockStarts.set(operationId, block);
1225
+ if (operation.family === 'binding' && operation.action === 'declare') {
1226
+ // A var belongs to the call's environment, even when its declaration is
1227
+ // inside a loop. An uninitialized lexical declaration still creates its
1228
+ // cell here; dropping that event lets a later conditional write move the
1229
+ // cell into a loop and reset it on every back edge.
1230
+ const origin = operation.blockScoped ? block : builder.blockOrder()[0];
1231
+ if (origin !== undefined && !bindingLifetimeOrigins.has(operation.declaration))
1232
+ bindingLifetimeOrigins.set(operation.declaration, origin);
1233
+ }
1224
1234
  const finiteStart = finiteCloseStarts.get(operationId);
1225
1235
  if (operation.family === 'destructuring' && operation.form === 'array-pattern-close' && finiteStart) {
1226
1236
  const entry = finiteEntries.get(operation.id);
@@ -1257,10 +1267,11 @@ exactArmNarrowing) => {
1257
1267
  join: info.join,
1258
1268
  ...(info.enclosingLoopBlocks.length > 0 ? { enclosingLoopBlocks: info.enclosingLoopBlocks } : {})
1259
1269
  })), iteratorCloseRegions);
1270
+ const withBindingLifetimes = { ...sealed, bindingLifetimeOrigins };
1260
1271
  if (!isGenerator)
1261
- return sealed;
1272
+ return withBindingLifetimes;
1262
1273
  const boundary = generatorPrologueBoundaryOf(graph, order, parameterPrologue, blockStarts, sealed);
1263
- return boundary === null ? sealed : { ...sealed, generatorPrologueBoundary: boundary };
1274
+ return boundary === null ? withBindingLifetimes : { ...withBindingLifetimes, generatorPrologueBoundary: boundary };
1264
1275
  }
1265
1276
  catch (error) {
1266
1277
  throw new IrLoweringBlockedError(`IR verification failed for owner ${owner}: ${error.message}`);
@@ -1478,6 +1478,8 @@ export interface IrBlock {
1478
1478
  /** Every operation in a block, in execution order, terminator last. */
1479
1479
  export declare const allOperationsOf: (block: IrBlock) => readonly IrOperation[];
1480
1480
  export interface IrBody {
1481
+ /** Binding creation sites constrain cell lifetime even when no initializer writes a value. */
1482
+ readonly bindingLifetimeOrigins?: ReadonlyMap<DeclarationId, IrBlockId>;
1481
1483
  /** Host binding/path resolution published before conversion certification. */
1482
1484
  readonly hostNamespaceCensus?: import('./host-namespace-reads.js').HostNamespaceCensus;
1483
1485
  /** Certified adaptations used by the published dense storage windows. */
@@ -0,0 +1,41 @@
1
+ import type { SemanticResultId, StructuralTypeId } from '../identity/ids.js';
2
+ import type { SemanticGraph } from '../semantics/model/graph.js';
3
+ /**
4
+ * The record members an `any` value writes `null` into although their
5
+ * declared type admits no `null`, and every read of one.
6
+ *
7
+ * `any` is the unchecked top: the checker lets it into every position, so a
8
+ * declared type says nothing about what an `any` write stores. mongodb's
9
+ * `ServerDescription` declares `$clusterTime?: ClusterTime` and writes
10
+ * `this.$clusterTime = hello?.$clusterTime ?? null` with `hello` a
11
+ * `Document`; the right-hand side is `any`, and node stores the `null` the
12
+ * `?? null` produces. Laid out from the declaration alone the member had one
13
+ * `undefined` absence, the write converted the boxed `null` through a checked
14
+ * record unwrap, and the driver threw a TypeError building its first
15
+ * topology.
16
+ *
17
+ * Only a `null` the program SPELLS is admitted -- the literal itself, or the
18
+ * fallback arm of a `??`/`||`, or an arm of a conditional -- reached from a
19
+ * write whose value the checker typed `any`. A `null` arriving inside an
20
+ * opaque `any` (a parsed document's field) is not visible here and still
21
+ * meets the checked unwrap: this widens the layouts a program visibly writes
22
+ * `null` into, it does not guess at what a dynamic value holds.
23
+ *
24
+ * Such a member is laid out as its declared type plus `null` (`derive.ts`'s
25
+ * `recordFieldsOf`), and each constant-keyed read publishes that same field
26
+ * carrier, so the read observes the `null` rather than converting it back
27
+ * into the declaration's carrier.
28
+ *
29
+ * Keyed by the object shape the record -- or a class instance, through its
30
+ * body -- is laid out under, exactly as `unwritten-record-members.ts` keys its
31
+ * census.
32
+ */
33
+ export interface AnyNullRecordMembers {
34
+ readonly members: ReadonlyMap<StructuralTypeId, ReadonlySet<string>>;
35
+ /** Every constant-keyed read of one of those members, with the layout it reads. */
36
+ readonly reads: ReadonlyMap<SemanticResultId, {
37
+ readonly layout: StructuralTypeId;
38
+ readonly key: string;
39
+ }>;
40
+ }
41
+ export declare const anyNullRecordMembersOf: (graph: SemanticGraph) => AnyNullRecordMembers;
@@ -0,0 +1,115 @@
1
+ import { operandOf } from '../semantics/model/operands.js';
2
+ import { recordFieldKeyOf } from './object-shape.js';
3
+ /** The object shape a record or class-instance carrier of `id` is laid out under. */
4
+ const layoutShapeOf = (types, id) => {
5
+ let current = id;
6
+ for (let depth = 0; current !== null && depth < 16; depth += 1) {
7
+ const shape = types.get(current)?.shape;
8
+ if (!shape)
9
+ return null;
10
+ if (shape.kind === 'object')
11
+ return current;
12
+ if (shape.kind === 'declared' || shape.kind === 'object-anchor' || shape.kind === 'class-instance')
13
+ current = shape.body;
14
+ else
15
+ return null;
16
+ }
17
+ return null;
18
+ };
19
+ const isAny = (types, id) => {
20
+ const shape = types.get(id)?.shape;
21
+ return shape?.kind === 'primitive' && shape.primitive === 'any';
22
+ };
23
+ const admitsNull = (types, id, depth = 0) => {
24
+ const shape = types.get(id)?.shape;
25
+ if (!shape || depth > 16)
26
+ return true;
27
+ if (shape.kind === 'primitive')
28
+ return shape.primitive === 'null' || shape.primitive === 'any' || shape.primitive === 'unknown';
29
+ if (shape.kind === 'union')
30
+ return shape.members.some((member) => admitsNull(types, member, depth + 1));
31
+ if (shape.kind === 'declared' && shape.body !== null && types.get(shape.body)?.shape.kind === 'union')
32
+ return admitsNull(types, shape.body, depth + 1);
33
+ return false;
34
+ };
35
+ export const anyNullRecordMembersOf = (graph) => {
36
+ const types = graph.structuralTypes;
37
+ const producerOf = (operand) => {
38
+ if (operand.source.kind !== 'result')
39
+ return undefined;
40
+ const id = graph.results.get(operand.source.result);
41
+ return id === undefined ? undefined : graph.operations.get(id);
42
+ };
43
+ // Whether the value an operand carries may be a `null` the source spells.
44
+ const spellsNull = (operand, depth = 0) => {
45
+ if (!operand || depth > 8)
46
+ return false;
47
+ if (operand.source.kind === 'constant')
48
+ return operand.source.literal === 'null';
49
+ const producer = producerOf(operand);
50
+ if (producer?.family !== 'computation')
51
+ return false;
52
+ if (producer.form === 'assignment' || producer.form === 'comma') {
53
+ return spellsNull(operandOf(producer, 'value') ?? operandOf(producer, 'right'), depth + 1);
54
+ }
55
+ if (producer.form === 'logical' && (producer.operator === '??' || producer.operator === '||')) {
56
+ return spellsNull(operandOf(producer, 'right'), depth + 1);
57
+ }
58
+ if (producer.form === 'conditional') {
59
+ return producer.operands.some((candidate) => candidate.role !== 'condition' && spellsNull(candidate, depth + 1));
60
+ }
61
+ return false;
62
+ };
63
+ // The type the checker gave the value before the write converted it into
64
+ // the member's storage: the producing computation's own result.
65
+ const writtenAsAny = (operand) => {
66
+ if (isAny(types, operand.type))
67
+ return true;
68
+ const producer = producerOf(operand);
69
+ const result = producer?.results.find((candidate) => candidate.role === 'value');
70
+ return result !== undefined && isAny(types, result.type);
71
+ };
72
+ const members = new Map();
73
+ for (const operation of graph.operations.values()) {
74
+ if (operation.family !== 'property' || operation.keyIsComputed)
75
+ continue;
76
+ if (operation.internalMethod !== 'set' && operation.internalMethod !== 'define-own-property')
77
+ continue;
78
+ const key = operandOf(operation, 'key');
79
+ const receiver = operandOf(operation, 'receiver');
80
+ const value = operandOf(operation, 'value');
81
+ if (key?.source.kind !== 'constant' || !receiver || !value)
82
+ continue;
83
+ if (!writtenAsAny(value) || !spellsNull(value))
84
+ continue;
85
+ const layout = layoutShapeOf(types, receiver.type);
86
+ const shape = layout === null ? undefined : types.get(layout)?.shape;
87
+ if (layout === null || shape?.kind !== 'object')
88
+ continue;
89
+ const keyText = key.source.text;
90
+ const member = shape.members.find((candidate) => candidate.key.kind !== 'symbol' && recordFieldKeyOf(candidate.key) === keyText);
91
+ if (!member || member.accessor !== null || admitsNull(types, member.type))
92
+ continue;
93
+ const known = members.get(layout);
94
+ if (known)
95
+ known.add(keyText);
96
+ else
97
+ members.set(layout, new Set([keyText]));
98
+ }
99
+ const reads = new Map();
100
+ if (members.size === 0)
101
+ return { members, reads };
102
+ for (const operation of graph.operations.values()) {
103
+ if (operation.family !== 'property' || operation.internalMethod !== 'get' || operation.keyIsComputed)
104
+ continue;
105
+ const key = operandOf(operation, 'key');
106
+ const receiver = operandOf(operation, 'receiver');
107
+ const value = operation.results.find((candidate) => candidate.role === 'value');
108
+ if (key?.source.kind !== 'constant' || !receiver || !value)
109
+ continue;
110
+ const layout = layoutShapeOf(types, receiver.type);
111
+ if (layout !== null && members.get(layout)?.has(key.source.text))
112
+ reads.set(value.id, { layout, key: key.source.text });
113
+ }
114
+ return { members, reads };
115
+ };
@@ -7,7 +7,8 @@ import type { SemanticGraph } from '../semantics/model/graph.js';
7
7
  * `let x: T` with no initializer binds `undefined` (ECMA-262
8
8
  * LexicalDeclaration evaluation with no Initializer), and the checker's
9
9
  * definite-assignment analysis is scoped to one function body: a read in the
10
- * declaring body is proven assigned or rejected, but a read from any other
10
+ * declaring body is proven assigned, carries an undefined arm, or is rejected;
11
+ * a read from any other
11
12
  * function -- a module helper, a closure -- is simply assumed assigned. So
12
13
  * such a cell's declared type is a claim the language does not enforce there.
13
14
  * A lazily loaded optional module (`let codec: Codec`, then
@@ -19,8 +20,8 @@ import type { SemanticGraph } from '../semantics/model/graph.js';
19
20
  * read of it -- the storage is one carrier, and a read in the declaring body
20
21
  * that the checker proved is still a load of that storage. A read feeding a
21
22
  * position that states `T` converts through the ordinary checked unwrap. A
22
- * cell every read of which sits in the declaring body keeps its declared
23
- * carrier: the checker's analysis is the proof there.
23
+ * cell every read of which sits in the declaring body and excludes undefined
24
+ * keeps its declared carrier: the checker's analysis is the proof there.
24
25
  *
25
26
  * Same shape as an unwritten static field (`static-field-cells.ts`), whose
26
27
  * carrier helper this shares.
@@ -2,6 +2,15 @@ import { withoutFunctionSpecialization } from '../identity/ids.js';
2
2
  import { resultOf } from '../semantics/model/operands.js';
3
3
  const ownerOf = (caller) => caller.kind === 'function' ? `f:${withoutFunctionSpecialization(caller.functionId)}` : `r:${caller.regionId}`;
4
4
  export const unassignedBindingAbsenceOf = (graph) => {
5
+ const includesUndefined = (type, seen = new Set()) => {
6
+ if (seen.has(type))
7
+ return false;
8
+ seen.add(type);
9
+ const shape = graph.structuralTypes.get(type)?.shape;
10
+ return shape?.kind === 'primitive'
11
+ ? shape.primitive === 'undefined'
12
+ : shape?.kind === 'union' && shape.members.some((member) => includesUndefined(member, seen));
13
+ };
5
14
  const declared = new Map();
6
15
  for (const operation of graph.operations.values()) {
7
16
  if (operation.family !== 'binding' || operation.action !== 'declare' || !operation.mutable)
@@ -30,7 +39,10 @@ export const unassignedBindingAbsenceOf = (graph) => {
30
39
  bucket.push(value.id);
31
40
  else
32
41
  reads.set(operation.declaration, [value.id]);
33
- if (ownerOf(operation.caller) !== cell.owner)
42
+ // An evolving, unannotated local can legally be read before a conditional
43
+ // write in the same function. Its read's published undefined arm is the
44
+ // checker's proof that the initial absence must survive the writer census.
45
+ if (ownerOf(operation.caller) !== cell.owner || includesUndefined(value.type))
34
46
  declarations.add(operation.declaration);
35
47
  }
36
48
  for (const declaration of declarations) {
@@ -0,0 +1,32 @@
1
+ import ts from 'typescript';
2
+ /**
3
+ * Property declarations the program writes a spelled `null` into through an
4
+ * `any` value, restated to admit that `null`.
5
+ *
6
+ * `any` is the unchecked top: the checker lets it into every position, so a
7
+ * declaration says nothing about what an `any` write stores there. mongodb's
8
+ * `ServerDescription` declares `$clusterTime?: ClusterTime` and writes
9
+ * `this.$clusterTime = hello?.$clusterTime ?? null` with `hello` a
10
+ * `Document`: the right-hand side is `any`, the checker accepts it, and node
11
+ * stores the `null` the `?? null` produces. Every later stage took the
12
+ * declaration at its word -- the field was laid out with one `undefined`
13
+ * absence, the write converted the boxed `null` through a checked record
14
+ * unwrap and threw a TypeError, and a read of it would have folded
15
+ * `=== null` to `false`.
16
+ *
17
+ * The declaration is the one authority every read, local and comparison
18
+ * inherits its type from, so it is the place to state the truth: its type
19
+ * becomes `(T) | null` and the checker re-derives everything downstream from
20
+ * that, including a diagnostic wherever the program then passes the member on
21
+ * to a position that cannot hold `null` -- which is a real defect in the
22
+ * program's typing, not one this introduces.
23
+ *
24
+ * Only a `null` the program SPELLS counts -- the literal, the fallback arm of
25
+ * `??`/`||`, an arm of a conditional -- written by a plain `=` whose
26
+ * right-hand side the checker typed `any`. A `null` hidden inside an opaque
27
+ * `any` is not visible here and still meets the checked unwrap.
28
+ *
29
+ * Positions are those of the program's own current text, so the rewritten
30
+ * text supersedes every earlier preparation of the same file.
31
+ */
32
+ export declare const anyNullMemberDeclarations: (program: ts.Program, checker: ts.TypeChecker) => ReadonlyMap<string, string>;
@@ -0,0 +1,90 @@
1
+ import { resolve } from 'node:path';
2
+ import ts from 'typescript';
3
+ /**
4
+ * Property declarations the program writes a spelled `null` into through an
5
+ * `any` value, restated to admit that `null`.
6
+ *
7
+ * `any` is the unchecked top: the checker lets it into every position, so a
8
+ * declaration says nothing about what an `any` write stores there. mongodb's
9
+ * `ServerDescription` declares `$clusterTime?: ClusterTime` and writes
10
+ * `this.$clusterTime = hello?.$clusterTime ?? null` with `hello` a
11
+ * `Document`: the right-hand side is `any`, the checker accepts it, and node
12
+ * stores the `null` the `?? null` produces. Every later stage took the
13
+ * declaration at its word -- the field was laid out with one `undefined`
14
+ * absence, the write converted the boxed `null` through a checked record
15
+ * unwrap and threw a TypeError, and a read of it would have folded
16
+ * `=== null` to `false`.
17
+ *
18
+ * The declaration is the one authority every read, local and comparison
19
+ * inherits its type from, so it is the place to state the truth: its type
20
+ * becomes `(T) | null` and the checker re-derives everything downstream from
21
+ * that, including a diagnostic wherever the program then passes the member on
22
+ * to a position that cannot hold `null` -- which is a real defect in the
23
+ * program's typing, not one this introduces.
24
+ *
25
+ * Only a `null` the program SPELLS counts -- the literal, the fallback arm of
26
+ * `??`/`||`, an arm of a conditional -- written by a plain `=` whose
27
+ * right-hand side the checker typed `any`. A `null` hidden inside an opaque
28
+ * `any` is not visible here and still meets the checked unwrap.
29
+ *
30
+ * Positions are those of the program's own current text, so the rewritten
31
+ * text supersedes every earlier preparation of the same file.
32
+ */
33
+ export const anyNullMemberDeclarations = (program, checker) => {
34
+ if (!program.getCompilerOptions().strictNullChecks && !program.getCompilerOptions().strict)
35
+ return new Map();
36
+ const spellsNull = (expression, depth = 0) => {
37
+ if (depth > 8)
38
+ return false;
39
+ if (expression.kind === ts.SyntaxKind.NullKeyword)
40
+ return true;
41
+ if (ts.isParenthesizedExpression(expression))
42
+ return spellsNull(expression.expression, depth + 1);
43
+ if (ts.isConditionalExpression(expression))
44
+ return spellsNull(expression.whenTrue, depth + 1) || spellsNull(expression.whenFalse, depth + 1);
45
+ if (ts.isBinaryExpression(expression) &&
46
+ (expression.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken || expression.operatorToken.kind === ts.SyntaxKind.BarBarToken))
47
+ return spellsNull(expression.right, depth + 1);
48
+ return false;
49
+ };
50
+ const admitsNull = (type) => (type.flags & (ts.TypeFlags.Null | ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0 ||
51
+ (type.isUnion() && type.types.some((member) => (member.flags & ts.TypeFlags.Null) !== 0));
52
+ const widened = new Map();
53
+ const visit = (node) => {
54
+ if (ts.isBinaryExpression(node) &&
55
+ node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
56
+ (ts.isPropertyAccessExpression(node.left) || ts.isElementAccessExpression(node.left)) &&
57
+ spellsNull(node.right) &&
58
+ (checker.getTypeAtLocation(node.right).flags & ts.TypeFlags.Any) !== 0) {
59
+ const symbol = checker.getSymbolAtLocation(ts.isPropertyAccessExpression(node.left) ? node.left.name : node.left.argumentExpression);
60
+ for (const declaration of symbol?.declarations ?? []) {
61
+ if (!ts.isPropertyDeclaration(declaration) && !ts.isPropertySignature(declaration))
62
+ continue;
63
+ const typeNode = declaration.type;
64
+ const file = declaration.getSourceFile();
65
+ if (!typeNode || file.isDeclarationFile || admitsNull(checker.getTypeFromTypeNode(typeNode)))
66
+ continue;
67
+ const known = widened.get(file);
68
+ if (known)
69
+ known.add(typeNode);
70
+ else
71
+ widened.set(file, new Set([typeNode]));
72
+ }
73
+ }
74
+ ts.forEachChild(node, visit);
75
+ };
76
+ for (const file of program.getSourceFiles())
77
+ if (!file.isDeclarationFile)
78
+ visit(file);
79
+ const sourceText = new Map();
80
+ for (const [file, typeNodes] of widened) {
81
+ let text = file.text;
82
+ const ordered = [...typeNodes].sort((left, right) => right.getStart(file) - left.getStart(file));
83
+ for (const typeNode of ordered) {
84
+ const start = typeNode.getStart(file);
85
+ text = `${text.slice(0, start)}(${text.slice(start, typeNode.end)}) | null${text.slice(typeNode.end)}`;
86
+ }
87
+ sourceText.set(resolve(file.fileName), text);
88
+ }
89
+ return sourceText;
90
+ };
@@ -0,0 +1,32 @@
1
+ import ts from 'typescript';
2
+ /**
3
+ * The method body a member call runs when it returns an array NO OTHER
4
+ * REFERENCE holds: every `return` hands back an array literal, or a local
5
+ * initialized with one that the body only fills, indexes and measures.
6
+ *
7
+ * This is the one fact that makes converting an `array-object` between two
8
+ * element carriers sound. A conversion between them has to allocate, and for
9
+ * a mutable array a second array loses every write through the other alias
10
+ * (`array-object-call-argument-aliasing`). A call result proven fresh has no
11
+ * other alias: the callee dropped its own reference when it returned, so the
12
+ * converted array is the only one the program can ever observe, and a
13
+ * one-time element-wise copy at the call is indistinguishable from the
14
+ * callee having built it at the caller's element type.
15
+ *
16
+ * An `async` body qualifies the same way: its promise settles with the
17
+ * array its `return` names, and that array is still held by nothing else.
18
+ * mongodb's `AbstractCursor.toArray` is the shape this exists for -- it
19
+ * builds `const array: TSchema[] = []`, pushes every document and returns it,
20
+ * while the cursor class is folded onto its `any` copy (`specialization.ts`'s
21
+ * reinterpreted classes), so the body hands back `any[]` where the caller's
22
+ * view declares `CollectionInfo[]`.
23
+ *
24
+ * Deliberately syntactic and small. Any use of the local outside the listed
25
+ * forms -- passing it as an argument, storing it, capturing it in a closure,
26
+ * a method whose result aliases it (`reverse`, `sort`), iteration protocol
27
+ * hooks -- refuses, and a refusal only keeps the conversion refused. The key
28
+ * is returned alongside so lowering can confirm the call it runs really
29
+ * reaches this body: an override in the receiver's family, or a prototype
30
+ * write, would run a different body the proof never saw.
31
+ */
32
+ export declare const freshArrayResultBodyOf: (checker: ts.TypeChecker, node: ts.CallExpression) => ts.MethodDeclaration | null;
@@ -0,0 +1,125 @@
1
+ import ts from 'typescript';
2
+ import { inheritedImplementationOf } from './merged-declaration.js';
3
+ /**
4
+ * The method body a member call runs when it returns an array NO OTHER
5
+ * REFERENCE holds: every `return` hands back an array literal, or a local
6
+ * initialized with one that the body only fills, indexes and measures.
7
+ *
8
+ * This is the one fact that makes converting an `array-object` between two
9
+ * element carriers sound. A conversion between them has to allocate, and for
10
+ * a mutable array a second array loses every write through the other alias
11
+ * (`array-object-call-argument-aliasing`). A call result proven fresh has no
12
+ * other alias: the callee dropped its own reference when it returned, so the
13
+ * converted array is the only one the program can ever observe, and a
14
+ * one-time element-wise copy at the call is indistinguishable from the
15
+ * callee having built it at the caller's element type.
16
+ *
17
+ * An `async` body qualifies the same way: its promise settles with the
18
+ * array its `return` names, and that array is still held by nothing else.
19
+ * mongodb's `AbstractCursor.toArray` is the shape this exists for -- it
20
+ * builds `const array: TSchema[] = []`, pushes every document and returns it,
21
+ * while the cursor class is folded onto its `any` copy (`specialization.ts`'s
22
+ * reinterpreted classes), so the body hands back `any[]` where the caller's
23
+ * view declares `CollectionInfo[]`.
24
+ *
25
+ * Deliberately syntactic and small. Any use of the local outside the listed
26
+ * forms -- passing it as an argument, storing it, capturing it in a closure,
27
+ * a method whose result aliases it (`reverse`, `sort`), iteration protocol
28
+ * hooks -- refuses, and a refusal only keeps the conversion refused. The key
29
+ * is returned alongside so lowering can confirm the call it runs really
30
+ * reaches this body: an override in the receiver's family, or a prototype
31
+ * write, would run a different body the proof never saw.
32
+ */
33
+ export const freshArrayResultBodyOf = (checker, node) => {
34
+ if (ts.isOptionalChain(node))
35
+ return null;
36
+ const callee = skipParentheses(node.expression);
37
+ if (!ts.isPropertyAccessExpression(callee) || !ts.isIdentifier(callee.name))
38
+ return null;
39
+ const member = checker.getSymbolAtLocation(callee.name);
40
+ if (!member)
41
+ return null;
42
+ const implementation = inheritedImplementationOf(checker, member) ?? member;
43
+ const bodies = (implementation.declarations ?? []).filter((declaration) => ts.isMethodDeclaration(declaration) && declaration.body !== undefined && ts.isClassLike(declaration.parent));
44
+ const body = bodies.length === 1 ? bodies[0] : null;
45
+ if (!body || body.asteriskToken !== undefined)
46
+ return null;
47
+ return returnsFreshArray(checker, body) ? body : null;
48
+ };
49
+ const returnsFreshArray = (checker, body) => {
50
+ const returns = [];
51
+ let bare = false;
52
+ const collect = (node) => {
53
+ if (ts.isFunctionLike(node) || ts.isClassLike(node))
54
+ return;
55
+ if (ts.isReturnStatement(node)) {
56
+ if (node.expression)
57
+ returns.push(skipParentheses(node.expression));
58
+ else
59
+ bare = true;
60
+ }
61
+ ts.forEachChild(node, collect);
62
+ };
63
+ ts.forEachChild(body.body, collect);
64
+ if (bare || returns.length === 0)
65
+ return false;
66
+ return returns.every((expression) => ts.isArrayLiteralExpression(expression) || freshLocal(checker, body, expression));
67
+ };
68
+ const freshLocal = (checker, body, expression) => {
69
+ if (!ts.isIdentifier(expression))
70
+ return false;
71
+ const symbol = checker.getSymbolAtLocation(expression);
72
+ const declaration = symbol?.declarations?.length === 1 ? symbol.declarations[0] : undefined;
73
+ if (!symbol || !declaration || !ts.isVariableDeclaration(declaration) || !ts.isIdentifier(declaration.name))
74
+ return false;
75
+ if (!declaration.initializer || !ts.isArrayLiteralExpression(skipParentheses(declaration.initializer)))
76
+ return false;
77
+ const list = declaration.parent;
78
+ if (!ts.isVariableDeclarationList(list) || (list.flags & ts.NodeFlags.Const) === 0)
79
+ return false;
80
+ if (enclosingFunction(declaration) !== body)
81
+ return false;
82
+ let admitted = true;
83
+ const visit = (node) => {
84
+ if (!admitted)
85
+ return;
86
+ if (ts.isIdentifier(node) && node !== declaration.name && checker.getSymbolAtLocation(node) === symbol) {
87
+ admitted = enclosingFunction(node) === body && nonEscapingUse(node);
88
+ return;
89
+ }
90
+ ts.forEachChild(node, visit);
91
+ };
92
+ ts.forEachChild(body.body, visit);
93
+ return admitted;
94
+ };
95
+ /** A use that reads, fills or measures the array and hands no reference to it anywhere. */
96
+ const nonEscapingUse = (use) => {
97
+ const parent = use.parent;
98
+ if (ts.isReturnStatement(parent))
99
+ return true;
100
+ if (ts.isParenthesizedExpression(parent))
101
+ return false;
102
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === use && ts.isIdentifier(parent.name)) {
103
+ const name = parent.name.text;
104
+ if (name === 'length')
105
+ return !isAssignmentTarget(parent);
106
+ const call = parent.parent;
107
+ return (name === 'push' || name === 'unshift') && ts.isCallExpression(call) && call.expression === parent;
108
+ }
109
+ if (ts.isElementAccessExpression(parent) && parent.expression === use)
110
+ return true;
111
+ return false;
112
+ };
113
+ const isAssignmentTarget = (node) => ts.isBinaryExpression(node.parent) &&
114
+ node.parent.left === node &&
115
+ node.parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
116
+ node.parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment;
117
+ const enclosingFunction = (node) => {
118
+ let current = node.parent;
119
+ while (current && !ts.isFunctionLike(current))
120
+ current = current.parent;
121
+ return current;
122
+ };
123
+ const skipParentheses = (node) => ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isNonNullExpression(node) || ts.isSatisfiesExpression(node)
124
+ ? skipParentheses(node.expression)
125
+ : node;
@@ -1961,7 +1961,9 @@ const threadedFlowOf = (ctx, body, labels, hoists, mergeWrites) => {
1961
1961
  const result = resultOfIrOperation(operation);
1962
1962
  return result !== null && ctx.deadValues.has(result.id);
1963
1963
  };
1964
- const rendersNothing = (block) => block.operations.every(rendersNothingAtOrigin) &&
1964
+ const lifetimeBlocks = new Set(body.bindingLifetimeOrigins?.values());
1965
+ const rendersNothing = (block) => !lifetimeBlocks.has(block.id) &&
1966
+ block.operations.every(rendersNothingAtOrigin) &&
1965
1967
  (mergeWrites.get(block.id) ?? []).length === 0 &&
1966
1968
  // A relocated operation renders here, in its destination block. Counting
1967
1969
  // it as absent a second time lets the flow thread this block away and
@@ -2054,7 +2056,7 @@ const threadedFlowOf = (ctx, body, labels, hoists, mergeWrites) => {
2054
2056
  * written in the same order, flat, with every declaration at the top -- the
2055
2057
  * layout that needs no graph at all.
2056
2058
  */
2057
- const nestedBlocksOf = (plan, rendered, labels, successors, declarations, rootText, facts, internalLabels = new Map(), restricted = new Map()) => {
2059
+ const nestedBlocksOf = (plan, rendered, labels, successors, declarations, rootText, facts, internalLabels = new Map(), restricted = new Map(), lifetimeOrigins = new Map()) => {
2058
2060
  const flat = () => ({
2059
2061
  top: declarations,
2060
2062
  artifacts: plan.order.flatMap((id) => {
@@ -2075,7 +2077,7 @@ const nestedBlocksOf = (plan, rendered, labels, successors, declarations, rootTe
2075
2077
  ]);
2076
2078
  if (gotoTargetsOf(block.artifact.text).some((target) => !allowed.has(target)))
2077
2079
  return flat();
2078
- mentions.set(id, identifiersOf(block.artifact.text));
2080
+ mentions.set(id, new Set([...identifiersOf(block.artifact.text), ...[...lifetimeOrigins].filter(([, origin]) => origin === id).map(([name]) => name)]));
2079
2081
  }
2080
2082
  const scopes = declarationScopesOf(plan, declarations, mentions, rootText);
2081
2083
  const top = [];
@@ -2258,7 +2260,7 @@ const isBareIdentifier = (text) => {
2258
2260
  * handler renders its blocks bare, and an outer jump into one of them cannot
2259
2261
  * be re-nested), or when some chunk is unreachable along the spelled jumps.
2260
2262
  */
2261
- const regionScopedBlocksOf = (entry, chunkIds, chunks, labels, declarations, rootText, facts) => {
2263
+ const regionScopedBlocksOf = (entry, chunkIds, chunks, labels, declarations, rootText, facts, lifetimeOrigins = new Map()) => {
2262
2264
  if (chunkIds.length !== chunks.length)
2263
2265
  return null;
2264
2266
  const allLabels = new Set(labels.values());
@@ -2315,7 +2317,17 @@ const regionScopedBlocksOf = (entry, chunkIds, chunks, labels, declarations, roo
2315
2317
  const rendered = new Map();
2316
2318
  for (const [id, artifact] of texts)
2317
2319
  rendered.set(id, { label: targeted.has(id) ? requireBlockLabel(labels, id) : null, artifact });
2318
- return nestedBlocksOf(plan, rendered, labels, successors, declarations, rootText, facts, internal);
2320
+ const chunkOrigins = new Map();
2321
+ const atRoot = [];
2322
+ for (const [name, origin] of lifetimeOrigins) {
2323
+ const label = labels.get(origin);
2324
+ const chunk = label === undefined ? undefined : (internalOf.get(label) ?? nodeOfLabel.get(label));
2325
+ if (chunk === undefined)
2326
+ atRoot.push(name);
2327
+ else
2328
+ chunkOrigins.set(name, chunk);
2329
+ }
2330
+ return nestedBlocksOf(plan, rendered, labels, successors, declarations, [rootText, ...atRoot].join('\n'), facts, internal, new Map(), chunkOrigins);
2319
2331
  };
2320
2332
  /** One `blockN` label per block, in `blockOrder`, so a forward jump (a loop back-edge included) always resolves before any block renders. */
2321
2333
  const blockLabelsOf = (order) => {
@@ -3082,13 +3094,26 @@ virtualDispatch = new Map(), narrowedStorage = { reads: new Map(), integral: new
3082
3094
  // scope of a variable whose declaration initializes it.
3083
3095
  const declarationFacts = { kind: 'materialized', representation: { kind: 'void' }, owner, lineage: null };
3084
3096
  let topDeclarations = ctx.declarations;
3097
+ const lifetimeOrigins = new Map();
3098
+ const atEntry = [];
3099
+ for (const [declaration, origin] of body.bindingLifetimeOrigins ?? []) {
3100
+ const name = ctx.bindingNames.get(declaration);
3101
+ if (name === undefined)
3102
+ continue;
3103
+ const rendered = flow.rendered.find((id) => id === origin || labels.get(id) === labels.get(origin));
3104
+ if (origin === body.entry || rendered === undefined || rendered === body.entry)
3105
+ atEntry.push(name);
3106
+ else
3107
+ lifetimeOrigins.set(name, rendered);
3108
+ }
3109
+ const lifetimeRootText = [...entryPrologue, ...atEntry].join('\n');
3085
3110
  if (plan !== null && flow.successors !== null) {
3086
- const nested = nestedBlocksOf(plan, renderedBlocks, labels, flow.successors, ctx.declarations, entryPrologue.join('\n'), declarationFacts, new Map(), restrictedParametersOf(ctx));
3111
+ const nested = nestedBlocksOf(plan, renderedBlocks, labels, flow.successors, ctx.declarations, lifetimeRootText, declarationFacts, new Map(), restrictedParametersOf(ctx), lifetimeOrigins);
3087
3112
  topDeclarations = nested.top;
3088
3113
  blocks.push(...nested.artifacts);
3089
3114
  }
3090
3115
  else if (!isSingleBlock && flow.successors === null) {
3091
- const nested = regionScopedBlocksOf(body.entry, chunkIds, blocks, labels, ctx.declarations, entryPrologue.join('\n'), declarationFacts);
3116
+ const nested = regionScopedBlocksOf(body.entry, chunkIds, blocks, labels, ctx.declarations, lifetimeRootText, declarationFacts, lifetimeOrigins);
3092
3117
  if (nested !== null) {
3093
3118
  topDeclarations = nested.top;
3094
3119
  blocks.splice(0, blocks.length, ...nested.artifacts);
@@ -3096,7 +3121,7 @@ virtualDispatch = new Map(), narrowedStorage = { reads: new Map(), integral: new
3096
3121
  }
3097
3122
  else if (isSingleBlock && blocks.length === 1) {
3098
3123
  const only = blocks[0];
3099
- const segmented = segmentScopedBodyOf(only.text, ctx.declarations, entryPrologue.join('\n'));
3124
+ const segmented = segmentScopedBodyOf(only.text, ctx.declarations, lifetimeRootText);
3100
3125
  if (segmented !== null) {
3101
3126
  topDeclarations = segmented.top;
3102
3127
  blocks.splice(0, 1, { text: segmented.text, facts: only.facts });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/compiler",
3
- "version": "1.0.32",
3
+ "version": "1.0.33",
4
4
  "description": "The geastack TypeScript-to-C++ compiler: one semantic spine, no source-shaped authority, no boxing of statically typed values.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -28920,14 +28920,14 @@ inline constexpr bool sharedRecordDelegation = sharedRecordDocument<T> && native
28920
28920
  struct NativeRecordDocumentBridge;
28921
28921
  template <typename T>
28922
28922
  const NativeRecordDocumentBridge& recordDocumentBridgeOf();
28923
- inline bool recordOwnDescriptor(const Ref<void>& source, const NativeRecordDocumentBridge& bridge, const PropertyKey& key,
28924
- PropertyDescriptor& out);
28925
- inline std::vector<PropertyKey> recordDocumentOwnKeys(const Ref<void>& source, const NativeRecordDocumentBridge& bridge);
28926
- inline bool recordDynamicDefine(const Ref<void>& source, const NativeRecordDocumentBridge& bridge, const PropertyKey& key,
28927
- const PropertyDescriptor& descriptor);
28928
- inline bool recordDocumentDelete(const Ref<void>& source, const NativeRecordDocumentBridge& bridge, const PropertyKey& key);
28929
- inline bool recordDynamicHas(const Ref<void>& source, const NativeRecordDocumentBridge& bridge, const PropertyKey& key);
28930
- inline std::vector<PropertyKey> recordEnumerableStringKeys(const Ref<void>& source, const NativeRecordDocumentBridge& bridge);
28923
+ bool recordOwnDescriptor(const Ref<void>& source, const NativeRecordDocumentBridge& bridge, const PropertyKey& key,
28924
+ PropertyDescriptor& out);
28925
+ std::vector<PropertyKey> recordDocumentOwnKeys(const Ref<void>& source, const NativeRecordDocumentBridge& bridge);
28926
+ bool recordDynamicDefine(const Ref<void>& source, const NativeRecordDocumentBridge& bridge, const PropertyKey& key,
28927
+ const PropertyDescriptor& descriptor);
28928
+ bool recordDocumentDelete(const Ref<void>& source, const NativeRecordDocumentBridge& bridge, const PropertyKey& key);
28929
+ bool recordDynamicHas(const Ref<void>& source, const NativeRecordDocumentBridge& bridge, const PropertyKey& key);
28930
+ std::vector<PropertyKey> recordEnumerableStringKeys(const Ref<void>& source, const NativeRecordDocumentBridge& bridge);
28931
28931
  } // namespace detail
28932
28932
 
28933
28933
  template <typename T>