@geastack/compiler 1.0.24 → 1.0.26

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 (34) hide show
  1. package/dist/ir/build.d.ts +1 -1
  2. package/dist/ir/build.js +2 -1
  3. package/dist/ir/dense-loops.d.ts +11 -2
  4. package/dist/ir/dense-loops.js +58 -9
  5. package/dist/ir/integers.js +27 -3
  6. package/dist/ir/lower-invocation.js +1 -1
  7. package/dist/ir/model.d.ts +2 -0
  8. package/dist/ir/numeric-intrinsics.d.ts +1 -1
  9. package/dist/ir/numeric-intrinsics.js +10 -3
  10. package/dist/projection/callee.d.ts +7 -0
  11. package/dist/projection/callee.js +12 -2
  12. package/dist/projection/class-property-presence.d.ts +12 -4
  13. package/dist/projection/class-property-presence.js +14 -9
  14. package/dist/semantics/callable-origins.js +6 -3
  15. package/dist/semantics/frontend.js +5 -1
  16. package/dist/semantics/normalize/structural.d.ts +2 -1
  17. package/dist/semantics/normalize/structural.js +30 -6
  18. package/dist/semantics/normalize/symbol-keyed-this-slots.d.ts +46 -0
  19. package/dist/semantics/normalize/symbol-keyed-this-slots.js +270 -0
  20. package/dist/targets/cpp/class-properties/emit-class-properties.js +7 -2
  21. package/dist/targets/cpp/emit-arrays.js +2 -2
  22. package/dist/targets/cpp/emit-callable.js +23 -3
  23. package/dist/targets/cpp/emit-properties.js +15 -2
  24. package/dist/targets/cpp/emit-union-properties.js +18 -3
  25. package/dist/targets/cpp/emit.d.ts +0 -26
  26. package/dist/targets/cpp/emit.js +26 -2
  27. package/package.json +1 -1
  28. package/src/targets/cpp/runtime/gea_runtime.h +584 -14
  29. package/dist/representation/any-null-record-members.d.ts +0 -41
  30. package/dist/representation/any-null-record-members.js +0 -115
  31. package/dist/semantics/any-null-member-declarations.d.ts +0 -32
  32. package/dist/semantics/any-null-member-declarations.js +0 -90
  33. package/dist/semantics/normalize/fresh-array-result.d.ts +0 -32
  34. package/dist/semantics/normalize/fresh-array-result.js +0 -125
@@ -0,0 +1,270 @@
1
+ import ts from 'typescript';
2
+ import { forEachReachableStatement } from './reachability.js';
3
+ export const emptySymbolKeyedThisSlotCensus = { slotsOf: () => [] };
4
+ const unwrapCasts = (node) => {
5
+ let current = node;
6
+ while (ts.isParenthesizedExpression(current) ||
7
+ ts.isAsExpression(current) ||
8
+ ts.isTypeAssertionExpression(current) ||
9
+ ts.isSatisfiesExpression(current) ||
10
+ ts.isNonNullExpression(current))
11
+ current = current.expression;
12
+ return current;
13
+ };
14
+ /** The types an expression is asserted to on the way out of `node`, outermost last. */
15
+ const assertedTypesOf = (node) => {
16
+ const asserted = [];
17
+ let current = node;
18
+ for (;;) {
19
+ if (ts.isAsExpression(current) || ts.isTypeAssertionExpression(current) || ts.isSatisfiesExpression(current))
20
+ asserted.push(current.type);
21
+ else if (!ts.isParenthesizedExpression(current) && !ts.isNonNullExpression(current))
22
+ return asserted;
23
+ current = current.expression;
24
+ }
25
+ };
26
+ const writeOperators = new Set([
27
+ ts.SyntaxKind.EqualsToken,
28
+ ts.SyntaxKind.BarBarEqualsToken,
29
+ ts.SyntaxKind.AmpersandAmpersandEqualsToken,
30
+ ts.SyntaxKind.QuestionQuestionEqualsToken
31
+ ]);
32
+ /** The parent of `node` past parentheses, with the child it was reached through. */
33
+ const outerOf = (node) => {
34
+ let child = node;
35
+ while (child.parent && ts.isParenthesizedExpression(child.parent))
36
+ child = child.parent;
37
+ return { child, parent: child.parent };
38
+ };
39
+ /** A `const k = Symbol(...)` declaration: one fresh symbol per evaluation of a module-level binding. */
40
+ const isFreshSymbolDeclaration = (declaration) => {
41
+ if (!ts.isVariableDeclaration(declaration) || !ts.isIdentifier(declaration.name) || !declaration.initializer)
42
+ return false;
43
+ const list = declaration.parent;
44
+ if (!ts.isVariableDeclarationList(list) || (list.flags & ts.NodeFlags.Const) === 0)
45
+ return false;
46
+ if (!ts.isVariableStatement(list.parent) || !ts.isSourceFile(list.parent.parent))
47
+ return false;
48
+ const initializer = declaration.initializer;
49
+ return ts.isCallExpression(initializer) && ts.isIdentifier(initializer.expression) && initializer.expression.text === 'Symbol';
50
+ };
51
+ export const censusSymbolKeyedThisSlots = (checker, files, reachable) => {
52
+ const resolvedDeclaration = (identifier) => {
53
+ let symbol = checker.getSymbolAtLocation(identifier);
54
+ if (symbol && symbol.flags & ts.SymbolFlags.Alias)
55
+ symbol = checker.getAliasedSymbol(symbol);
56
+ return symbol?.valueDeclaration ?? null;
57
+ };
58
+ // Every spelling a fresh symbol can be referenced by: its own name, plus any
59
+ // local name an import or export renames it to, to a fixpoint. Only those
60
+ // identifiers are resolved -- asking the checker for every identifier in a
61
+ // three.js-sized program is the cost this filter exists to avoid -- and a
62
+ // missed rename would be a missed escape, so the closure is taken in full.
63
+ const spellings = new Set();
64
+ const sources = files.filter((file) => !file.isDeclarationFile);
65
+ for (const file of sources)
66
+ for (const statement of file.statements)
67
+ if (ts.isVariableStatement(statement))
68
+ for (const declaration of statement.declarationList.declarations)
69
+ if (isFreshSymbolDeclaration(declaration))
70
+ spellings.add(declaration.name.text);
71
+ if (spellings.size === 0)
72
+ return emptySymbolKeyedThisSlotCensus;
73
+ for (let grew = true; grew;) {
74
+ grew = false;
75
+ for (const file of sources)
76
+ for (const statement of file.statements) {
77
+ const bindings = ts.isImportDeclaration(statement) &&
78
+ statement.importClause?.namedBindings &&
79
+ ts.isNamedImports(statement.importClause.namedBindings)
80
+ ? statement.importClause.namedBindings.elements
81
+ : ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)
82
+ ? statement.exportClause.elements
83
+ : [];
84
+ for (const binding of bindings) {
85
+ const imported = (binding.propertyName ?? binding.name).text;
86
+ if (spellings.has(imported) && !spellings.has(binding.name.text)) {
87
+ spellings.add(binding.name.text);
88
+ grew = true;
89
+ }
90
+ }
91
+ }
92
+ }
93
+ const accesses = [];
94
+ const escaped = new Set();
95
+ for (const file of sources) {
96
+ const visit = (node) => {
97
+ if (reachable.memberIsPruned(node))
98
+ return;
99
+ if (ts.isIdentifier(node) && spellings.has(node.text)) {
100
+ const declaration = resolvedDeclaration(node);
101
+ if (declaration && isFreshSymbolDeclaration(declaration) && declaration.name !== node) {
102
+ const { child, parent } = outerOf(node);
103
+ if (parent && ts.isElementAccessExpression(parent) && parent.argumentExpression === child) {
104
+ accesses.push({ node: parent, key: declaration });
105
+ }
106
+ else if (!(parent && ts.isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.InKeyword && parent.left === child) &&
107
+ !(parent && ts.isComputedPropertyName(parent) && isTypePositionMember(parent.parent)) &&
108
+ !(parent && (ts.isImportSpecifier(parent) || ts.isExportSpecifier(parent))) &&
109
+ !(parent && ts.isTypeQueryNode(parent))) {
110
+ escaped.add(declaration);
111
+ }
112
+ }
113
+ }
114
+ ts.forEachChild(node, visit);
115
+ };
116
+ forEachReachableStatement(reachable, file, visit);
117
+ }
118
+ /** The class whose instance `this` is at `access`, when it is an instance member's own `this`. */
119
+ const thisOwnerOf = (access) => {
120
+ if (unwrapCasts(access.expression).kind !== ts.SyntaxKind.ThisKeyword)
121
+ return null;
122
+ let container = access.parent;
123
+ while (!ts.isClassStaticBlockDeclaration(container) &&
124
+ (!ts.isFunctionLike(container) || ts.isArrowFunction(container)) &&
125
+ !ts.isPropertyDeclaration(container)) {
126
+ if (ts.isSourceFile(container))
127
+ return null;
128
+ container = container.parent;
129
+ }
130
+ const owner = container.parent;
131
+ if (!owner || !ts.isClassLike(owner))
132
+ return null;
133
+ if (!ts.isConstructorDeclaration(container) &&
134
+ !ts.isMethodDeclaration(container) &&
135
+ !ts.isAccessor(container) &&
136
+ !ts.isPropertyDeclaration(container))
137
+ return null;
138
+ if (!ts.isConstructorDeclaration(container) && ts.getCombinedModifierFlags(container) & ts.ModifierFlags.Static)
139
+ return null;
140
+ return owner;
141
+ };
142
+ /** The property an `as T` cast on the receiver declares for `key`, or `null`. */
143
+ const declaredPropertyOf = (access, key) => {
144
+ for (const asserted of assertedTypesOf(access.expression)) {
145
+ const type = checker.getTypeFromTypeNode(asserted);
146
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
147
+ continue;
148
+ for (const property of checker.getPropertiesOfType(type)) {
149
+ for (const declaration of property.getDeclarations() ?? []) {
150
+ const name = declaration.name;
151
+ if (name && ts.isComputedPropertyName(name) && ts.isIdentifier(name.expression) && resolvedDeclaration(name.expression) === key)
152
+ return property;
153
+ }
154
+ }
155
+ }
156
+ return null;
157
+ };
158
+ /**
159
+ * Whether `value` can hold a value of `target`: assignable either way, read
160
+ * element by element for an array literal against a tuple.
161
+ *
162
+ * Comparable rather than assignable, because the program this exists for
163
+ * writes wider than it declares: hono stores a `Blob`/`Uint8Array` body into
164
+ * the `string | ReadableStream | null` element its `InternalCache` states.
165
+ * Every read of the key is a conversion to that declared type
166
+ * (`(res as any)[cacheKey] as InternalCache`), so such a value already
167
+ * refused at its first read through the expando; the native write refuses
168
+ * it at the store instead. A value of a type DISJOINT from the slot's could
169
+ * never be read back at all, so it withdraws the key.
170
+ */
171
+ const fits = (value, target) => {
172
+ const unwrapped = ts.isParenthesizedExpression(value) ? value.expression : value;
173
+ const written = checker.getTypeAtLocation(unwrapped);
174
+ if (ts.isArrayLiteralExpression(unwrapped) && !unwrapped.elements.some(ts.isSpreadElement)) {
175
+ const arms = target.isUnion() ? target.types : [target];
176
+ return arms.some((arm) => {
177
+ if (!checker.isTupleType(arm))
178
+ return false;
179
+ const elements = checker.getTypeArguments(arm);
180
+ const fixedLength = arm.target.fixedLength;
181
+ if (unwrapped.elements.length !== elements.length || fixedLength !== elements.length)
182
+ return false;
183
+ return unwrapped.elements.every((element, index) => fits(element, elements[index]));
184
+ });
185
+ }
186
+ return checker.isTypeAssignableTo(written, target) || checker.isTypeAssignableTo(target, written);
187
+ };
188
+ const declaredByKey = new Map();
189
+ const conflicting = new Set();
190
+ for (const { node, key } of accesses) {
191
+ const property = declaredPropertyOf(node, key);
192
+ if (!property)
193
+ continue;
194
+ const held = declaredByKey.get(key);
195
+ if (!held)
196
+ declaredByKey.set(key, property);
197
+ else if (held !== property && checker.getTypeOfSymbol(held) !== checker.getTypeOfSymbol(property))
198
+ conflicting.add(key);
199
+ }
200
+ const withdrawn = new Set([...escaped, ...conflicting]);
201
+ for (const { node, key } of accesses) {
202
+ const property = declaredByKey.get(key);
203
+ if (!property)
204
+ continue;
205
+ const { child, parent } = outerOf(node);
206
+ if (parent && ts.isBinaryExpression(parent) && parent.left === child) {
207
+ if (!writeOperators.has(parent.operatorToken.kind)) {
208
+ if (parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment)
209
+ withdrawn.add(key);
210
+ continue;
211
+ }
212
+ if (!fits(parent.right, checker.getNonNullableType(checker.getTypeOfSymbol(property))))
213
+ withdrawn.add(key);
214
+ continue;
215
+ }
216
+ if (parent &&
217
+ (ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) &&
218
+ (parent.operator === ts.SyntaxKind.PlusPlusToken || parent.operator === ts.SyntaxKind.MinusMinusToken))
219
+ withdrawn.add(key);
220
+ // A destructuring target (`[o[k]] = xs`) writes without an `=` this walk reads.
221
+ else if (parent && isAssignmentTargetLiteral(child))
222
+ withdrawn.add(key);
223
+ }
224
+ const slots = new Map();
225
+ for (const { node, key } of accesses) {
226
+ if (withdrawn.has(key))
227
+ continue;
228
+ const property = declaredByKey.get(key);
229
+ if (!property)
230
+ continue;
231
+ const { child, parent } = outerOf(node);
232
+ if (!parent || !ts.isBinaryExpression(parent) || parent.left !== child || !writeOperators.has(parent.operatorToken.kind))
233
+ continue;
234
+ const owner = thisOwnerOf(node);
235
+ if (!owner)
236
+ continue;
237
+ const held = slots.get(owner);
238
+ if (!held)
239
+ slots.set(owner, [property]);
240
+ else if (!held.includes(property))
241
+ held.push(property);
242
+ }
243
+ if (process.env['GEA_BINDING_DEBUG']) {
244
+ for (const [owner, properties] of slots)
245
+ console.error(`[SYMBOL-THIS-SLOT] ${owner.name?.text ?? '<anonymous>'} ${properties.map((property) => property.getName()).join(' ')}`);
246
+ for (const key of withdrawn)
247
+ console.error(`[SYMBOL-THIS-SLOT] withdrawn ${key.name.text}`);
248
+ }
249
+ if (slots.size === 0)
250
+ return emptySymbolKeyedThisSlotCensus;
251
+ return { slotsOf: (owner) => slots.get(owner) ?? [] };
252
+ };
253
+ /** A member whose computed name is a type-level declaration (an interface or type literal member, a `declare`d field). */
254
+ const isTypePositionMember = (member) => ts.isPropertySignature(member) ||
255
+ ts.isMethodSignature(member) ||
256
+ (ts.isPropertyDeclaration(member) && (ts.getCombinedModifierFlags(member) & ts.ModifierFlags.Ambient) !== 0);
257
+ /** Whether an array/object literal is itself the left side of a destructuring assignment. */
258
+ const isAssignmentTargetLiteral = (node) => {
259
+ let current = node;
260
+ while (current.parent &&
261
+ (ts.isArrayLiteralExpression(current.parent) ||
262
+ ts.isObjectLiteralExpression(current.parent) ||
263
+ ts.isPropertyAssignment(current.parent) ||
264
+ ts.isShorthandPropertyAssignment(current.parent) ||
265
+ ts.isSpreadElement(current.parent) ||
266
+ ts.isParenthesizedExpression(current.parent)))
267
+ current = current.parent;
268
+ const parent = current.parent;
269
+ return !!parent && ts.isBinaryExpression(parent) && parent.left === current && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken;
270
+ };
@@ -172,7 +172,8 @@ valueRepresentation = boundMethodValueRepresentation(operation), receiverText =
172
172
  const heldReceiver = override === null ? receiverText : 'gea_method_receiver';
173
173
  const state = `${heldReceiver}->gea_method_state`;
174
174
  const bodyValue = `gea::nativeClassMethodValue<${cppClassName(owner.declaration)}, &${cppCallableDeclarationTagName(method.callable)}>(${state}, ${payload})`;
175
- const materialized = alignedValueText(ctx, 'class-properties/emit-class-properties.ts:212', bodyRepresentation, valueRepresentation, bodyValue) ??
175
+ const aligned = alignedValueText(ctx, 'class-properties/emit-class-properties.ts:212', bodyRepresentation, valueRepresentation, bodyValue);
176
+ const materialized = aligned ??
176
177
  // The published value declares no receiver while the body's convention
177
178
  // leads with one, so the receiver has to travel WITH the value
178
179
  // (`gea_runtime.h`'s `CallableObject::bindReceiver`). This is the arm half
@@ -196,7 +197,11 @@ valueRepresentation = boundMethodValueRepresentation(operation), receiverText =
196
197
  throw createCppEmitBlockedError(`conversion:${representationKey(bodyRepresentation)}->${representationKey(valueRepresentation)}`, `method "${key}" body convention cannot fill its published bound-method convention`);
197
198
  }
198
199
  const publicAbi = abiOfCallee(valueRepresentation);
199
- const originalValue = publicAbi !== null && abiKey(publicAbi) !== abiKey(bodyAbi)
200
+ // The adapter cache is per class evaluation, so it may only hold a value
201
+ // every instance shares. A receiver-bound value carries THIS read's
202
+ // receiver: cached, the second instance would call the first one's body
203
+ // (two hono `SmartRouter`s, the second matching against the first's routes).
204
+ const originalValue = aligned !== null && publicAbi !== null && abiKey(publicAbi) !== abiKey(bodyAbi)
200
205
  ? `gea::nativeClassAdaptedMethodValue<${cppClassName(owner.declaration)}, &${cppCallableDeclarationTagName(method.callable)}, ${valueType}>(${state}, [&]() { return ${materialized}; })`
201
206
  : materialized;
202
207
  const fallback = nativePrototypeMethodFallbackText(ctx, receiverRepresentation, key, owner, valueRepresentation, heldReceiver, originalValue, dispatchesStatically(ctx, operation.receiver));
@@ -1040,8 +1040,8 @@ export const emitDenseSetup = (ctx, lines, blockId) => {
1040
1040
  // modulus is bounded by itself instead, and nothing ties that number to
1041
1041
  // this array, so the length has to cover it: `table[i % 16]` is a
1042
1042
  // window exactly when the table holds sixteen elements or more.
1043
- const reach = array.modulus === null ? `${cells}.size() > 0` : `${cells}.size() >= ${array.modulus}`;
1044
- said.push(...holder.guard, `${holder.text}->holes.empty()`, reach, ...writable);
1043
+ const reach = array.modulus === null ? `${size} > 0` : `${size} >= ${array.modulus}`;
1044
+ said.push(...holder.guard, ...shape, reach, ...writable);
1045
1045
  // The divisor of every index in this window, read here rather than on
1046
1046
  // every turn. Nothing in the loop resizes the array -- that is what the
1047
1047
  // window's own admission proved -- but only this hoist tells the
@@ -43,11 +43,11 @@ export const emitBindCallable = (ctx, lines, operation) => {
43
43
  if (operation.result.representation.kind !== 'function-value-dispatch') {
44
44
  throw createCppEmitBlockedError('call-abi:bind-callable', 'a bound Function result is not carried as an evaluated function-value dispatch');
45
45
  }
46
- const guarded = operation.unboxedMethod !== undefined && operation.unboxedMethodConfirmed !== true;
46
+ const guarded = (operation.unboxedMethod !== undefined && operation.unboxedMethodConfirmed !== true) || operation.builtinShadowGuard === 'bind';
47
47
  if (guarded && operation.detached !== false) {
48
- throw createCppEmitBlockedError('call-abi:bind-shadowable', `"${operation.unboxedMethod.key}" was bound as the builtin Function.prototype.bind on the assumption that no boxed ` +
48
+ throw createCppEmitBlockedError('call-abi:bind-shadowable', `"${operation.unboxedMethod?.key ?? 'method'}" was bound as the builtin Function.prototype.bind on the assumption that no boxed ` +
49
49
  `value holds its Function object, and the reflection census did not confirm it: an instance, prototype or ` +
50
- `constructor of ${String(operation.unboxedMethod.owner)} or a related class reaches dynamic code, where a ` +
50
+ `constructor of ${String(operation.unboxedMethod?.owner ?? 'its class')} or a related class reaches dynamic code, where a ` +
51
51
  `computed write can shadow "bind"`);
52
52
  }
53
53
  if (operation.detached) {
@@ -931,6 +931,26 @@ export const emitCall = (ctx, lines, operation) => {
931
931
  lines.push(`${expression};`);
932
932
  return;
933
933
  }
934
+ const unary = ctx.numericCalls.get(operation);
935
+ if (unary === 'abs' || unary === 'clz32') {
936
+ const argument = operation.arguments[0];
937
+ const text = operandText(ctx, argument);
938
+ const integerArgument = isIntegerStorageValue(ctx, argument.value);
939
+ const integerResult = operation.result !== null && isIntegerStorageValue(ctx, operation.result.id);
940
+ // `abs` of an integer argument is the integer one (`ir/integers.ts`);
941
+ // otherwise it is the double the host computes, NaN and -0 included.
942
+ // `clz32` is an integer whatever it is given, through ToUint32.
943
+ const expression = unary === 'abs'
944
+ ? integerResult && integerArgument
945
+ ? `gea::integerAbs(static_cast<long long>(${text}))`
946
+ : `std::fabs(static_cast<double>(${text}))`
947
+ : `gea::integerClz32(${integerArgument ? `static_cast<std::uint32_t>(static_cast<long long>(${text}))` : `gea::toUint32(${text})`})`;
948
+ if (operation.result && !ctx.unreadValues.has(operation.result.id))
949
+ lines.push(`${defineValue(ctx, operation.result)} = ${expression};`);
950
+ else
951
+ lines.push(`${expression};`);
952
+ return;
953
+ }
934
954
  if (ctx.numericCalls.get(operation) === 'imul') {
935
955
  const args = operation.arguments.map((argument) => {
936
956
  const text = operandText(ctx, argument);
@@ -394,10 +394,23 @@ const denseCellText = (ctx, operation) => {
394
394
  // could run: measured on `bench/comparison/fixtures/object_create.ts`,
395
395
  // 9.05ms without the hint and 8.49ms with it, for the same instructions in a
396
396
  // better order.
397
+ //
398
+ // A remainder index (`DenseAccess.signed`) carries the dividend's sign, and
399
+ // an un-narrowed one its fraction too: `t[-3 % 16]` and `t[1.5 % 16]` are
400
+ // both `undefined` in JS, and as a `size_t` they are an out-of-bounds read
401
+ // and `t[1]`. The test rides on the flag, so the cold half answers them.
402
+ const key = ctx.denseIndices.get(operation.key.value) ?? operandText(ctx, operation.key);
403
+ const flag = cppDenseFlagName(access.flag);
404
+ const integral = ctx.denseIndices.has(operation.key.value) || ctx.integerValues.has(operation.key.value);
405
+ const guarded = !access.signed
406
+ ? flag
407
+ : integral
408
+ ? `${flag} && (${key}) >= 0`
409
+ : `${flag} && (${key}) >= 0 && static_cast<double>(static_cast<long long>(${key})) == (${key})`;
397
410
  return {
398
411
  pointer: cppDensePointerName(access.array),
399
- index: `static_cast<std::size_t>(${ctx.denseIndices.get(operation.key.value) ?? operandText(ctx, operation.key)})`,
400
- flag: `GEA_LIKELY(${cppDenseFlagName(access.flag)})`,
412
+ index: `static_cast<std::size_t>(${key})`,
413
+ flag: `GEA_LIKELY(${guarded})`,
401
414
  text: `${cppDensePointerName(access.array)}[static_cast<std::size_t>(${ctx.denseIndices.get(operation.key.value) ?? operandText(ctx, operation.key)})]${operation.receiver.representation.kind === 'typed-array' ? '' : '.value'}`
402
415
  };
403
416
  };
@@ -90,7 +90,7 @@ export const unionClassMethodValueReceiverClaim = (ctx, operation) => {
90
90
  const key = ctx.staticKeyTexts.get(operation.key.value);
91
91
  if (key === undefined || objectPrototypeMemberNames.has(key))
92
92
  return null;
93
- if (deferredUnionMethodClaim(ctx, operation.receiver, operation.key) !== null)
93
+ if (ctx.unionMethodReads.has(operation.result.id))
94
94
  return null;
95
95
  for (const leaf of unionPropertyLeaves(receiver, '')) {
96
96
  const arm = leaf.representation;
@@ -1193,7 +1193,7 @@ export const taggedUnionGetText = (ctx, lines, operation) => {
1193
1193
  // Recorded by the prototype-read walk, which asked the same claim.
1194
1194
  return '';
1195
1195
  }
1196
- if (deferredUnionMethodClaim(ctx, operation.receiver, operation.key) !== null) {
1196
+ if (ctx.unionMethodReads.has(operation.result.id)) {
1197
1197
  // Recorded by the prototype-read walk's sibling, which asked the same claim.
1198
1198
  return '';
1199
1199
  }
@@ -1610,9 +1610,24 @@ export const unionMemberTypeofReadsOf = (ctx, body) => {
1610
1610
  };
1611
1611
  export const unionMethodReadsOf = (ctx, body) => {
1612
1612
  const reads = new Map();
1613
+ // A claimed read renders nothing and its CALL renders the dispatch, so a
1614
+ // read anything else consumes -- `union.m.bind(union)`, hono's
1615
+ // `router.match.bind(router)` -- keeps the per-arm value walk instead of
1616
+ // naming a value that was never defined.
1617
+ const otherwiseConsumed = new Set();
1618
+ for (const block of body.blocks.values())
1619
+ for (const operation of allOperationsOf(block))
1620
+ for (const operand of operandsOfIrOperation(operation)) {
1621
+ if (operation.kind === 'call' &&
1622
+ operand.value === operation.callee.value &&
1623
+ operation.receiver?.value !== operand.value &&
1624
+ !operation.arguments.some((argument) => argument.value === operand.value))
1625
+ continue;
1626
+ otherwiseConsumed.add(operand.value);
1627
+ }
1613
1628
  for (const block of body.blocks.values()) {
1614
1629
  for (const operation of allOperationsOf(block)) {
1615
- if (operation.kind !== 'get')
1630
+ if (operation.kind !== 'get' || otherwiseConsumed.has(operation.result.id))
1616
1631
  continue;
1617
1632
  const claim = deferredUnionMethodClaim(ctx, operation.receiver, operation.key);
1618
1633
  if (claim !== null)
@@ -17,31 +17,5 @@ import type { IntegerStorageFacts } from '../../ir/integers.js';
17
17
  import { type InstantiationFacts } from '../../ir/instantiation.js';
18
18
  import { type CallableIdentityDemand } from '../../ir/callable-identity-demand.js';
19
19
  import type { HostMethodAlias } from './host/host-method-aliases.js';
20
- /**
21
- * The C++ statements one lowered body renders to, as artifacts for the
22
- * emission boundary.
23
- *
24
- * `hostMembers` is every host spelling this compilation installed -- the
25
- * backend's own plus every plugin's. It is a parameter rather than an import
26
- * because which host is in front of the compiler is a property of the
27
- * compilation, not of this file.
28
- *
29
- * `deriver` is what `targets/cpp/emit-properties.ts` asks for a receiver's
30
- * own declared field representation, to widen a concrete value into a
31
- * `dynamic` field the same way this function's own `return` handling widens
32
- * into a `dynamic` ABI result -- see citations.md finding 1.
33
- *
34
- * `captures` defaults to `emptyCaptureIndex` (every owner closes over
35
- * nothing) so every existing caller keeps compiling and behaving exactly as
36
- * before; `translation-unit.ts` is the one caller that has an index to pass,
37
- * built once for the whole program by `targets/cpp/captures.ts`.
38
- */
39
- /**
40
- * The namespace every incoming value of a merge stands for, or `null`.
41
- *
42
- * `null` unless at least one arm is a namespace and every other arm is either
43
- * the same namespace or an absent constant -- see the call site for why an
44
- * absent arm is the one thing that may accompany it.
45
- */
46
20
  export declare const emitBody: (body: IrBody, placements: ReadonlyMap<DeclarationId, BindingPlacement>, classes: ReadonlyMap<DeclarationId, ClassLayout>, hosts: HostSpellings, deriver: RepresentationDeriver, wellKnownSymbols: ReadonlyMap<DeclarationId, string> | undefined, captures: CaptureIndex | undefined, symbolKeys: Map<string, string>, templateObjects: Map<string, TemplateObjectDefinition>, directCallableBindings?: ReadonlyMap<DeclarationId, FunctionId>, virtualDispatch?: ReadonlyMap<string, CallableAbi>, narrowedStorage?: IntegerStorageFacts, narrowedFormals?: ReadonlySet<number>, repeatedConstructors?: ReadonlyMap<DeclarationId, DeclarationId>, dyingArguments?: ReadonlySet<IrValueId>, instantiation?: InstantiationFacts, abiOfCallable?: (callable: FunctionId) => IrBody["abi"], functionFacts?: ReadonlyMap<FunctionId, CallableFactsSpelling>, hostMethodAliases?: ReadonlyMap<DeclarationId, HostMethodAlias>, callableMemberCandidates?: ReadonlyMap<string, FunctionId>, borrowableMemberBodies?: ReadonlySet<FunctionId>, stableBorrowEntries?: ReadonlyMap<string, StableBorrowEntry>, printerDrift?: PrinterDrift[], conversions?: ConversionCensus | null, nativeSelections?: ReadonlyMap<string, NativeSelectionHelper> | undefined, callableIdentityDemand?: CallableIdentityDemand, nativeIntegrityRestricted?: IntegrityRestrictions, fixedFieldStateConstant?: boolean, definitionCells?: ReadonlySet<DeclarationId>, constructionOnlyFields?: ConstructionOnlyFields, keyOrderUnobserved?: ReadonlySet<string>, taskBodies?: ReadonlySet<string>) => readonly CppArtifact[];
47
21
  export { cppConstructedThunkName, cppConstructThunkName, cppFormalName, cppReceiverName, cppThunkName, isCppEmitBlockedError } from './emit-context.js';
@@ -889,6 +889,18 @@ const emitCompute = (ctx, lines, operation) => {
889
889
  // `roundingArithmetic`).
890
890
  const rounding = integral && ctx.roundingArithmetic.has(operation.result.id) ? roundingIntegerHelpers.get(operation.operator) : undefined;
891
891
  if (rounding !== undefined) {
892
+ // An ordinary dense window's subscript is `base + counter`, and the
893
+ // window's flag already proved every such sum inside `[0, size())`
894
+ // (`gea::denseIndexWindow`), so under the flag it cannot leave +-2^53 and
895
+ // the rounding check is dead weight on every turn -- eight instructions and
896
+ // two branches per pixel of a rotozoom's `words[line + x]` on a 32-bit
897
+ // core. The fast arm takes a plain sum (wrapping, so it stays defined
898
+ // whatever the operands); the general arm keeps the faithful one. It is
899
+ // TEXT, not a statement: withholding pastes a value only when its operation
900
+ // rendered exactly one, and a second one here left the faithful sum
901
+ // computed on every turn beside the plain one (reel's fire, 64 -> 87 ms).
902
+ if (operation.operator === '+' && isOrdinaryDenseKey(ctx, operation.result.id))
903
+ ctx.denseIndices.set(operation.result.id, `static_cast<long long>(static_cast<unsigned long long>(${left}) + static_cast<unsigned long long>(${right}))`);
892
904
  lines.push(`${name} = ${rounding}(${left}, ${right});`);
893
905
  return;
894
906
  }
@@ -2152,6 +2164,16 @@ const blockLabelsOf = (order) => {
2152
2164
  * the same namespace or an absent constant -- see the call site for why an
2153
2165
  * absent arm is the one thing that may accompany it.
2154
2166
  */
2167
+ /** Whether a value is the subscript of an access in an ordinary (counter-bounded, not wrapped) dense window. */
2168
+ const isOrdinaryDenseKey = (ctx, value) => {
2169
+ for (const [operation, access] of ctx.denseAccesses) {
2170
+ if ((operation.kind !== 'get' && operation.kind !== 'set') || operation.key.value !== value)
2171
+ continue;
2172
+ if (ctx.denseArrays.find((array) => array.ordinal === access.array)?.wrapped === false)
2173
+ return true;
2174
+ }
2175
+ return false;
2176
+ };
2155
2177
  export const emitBody = (body, placements, classes, hosts, deriver, wellKnownSymbols = new Map(), captures = emptyCaptureIndex,
2156
2178
  // No default: `symbolKeys`/`templateObjects` are ONE table for the whole
2157
2179
  // program (`translation-unit.ts`'s own comment on its `templateObjects`
@@ -2299,12 +2321,14 @@ virtualDispatch = new Map(), narrowedStorage = { reads: new Map(), integral: new
2299
2321
  // The receiver every method-value read keeps for the call that consumes it,
2300
2322
  // asked of the class layout rather than recorded by whichever resolver
2301
2323
  // happened to spell the value.
2324
+ // Union method reads first: whether a read is deferred to its call decides
2325
+ // whether it publishes a receiver for that call to supply.
2326
+ for (const [value, read] of unionMethodReadsOf(ctx, body))
2327
+ prepass.unionMethodReads.set(value, read);
2302
2328
  for (const [value, receiver] of directCallReceiversOf(ctx, body))
2303
2329
  prepass.directCallReceivers.set(value, receiver);
2304
2330
  for (const [value, callee] of virtualCalleesOf(ctx, body))
2305
2331
  prepass.virtualCallees.set(value, callee);
2306
- for (const [value, read] of unionMethodReadsOf(ctx, body))
2307
- prepass.unionMethodReads.set(value, read);
2308
2332
  // A member read nothing but `typeof` consumes, off arms that disagree about
2309
2333
  // the member; the read renders nothing and the `typeof` renders the dispatch.
2310
2334
  for (const [value, read] of unionMemberTypeofReadsOf(ctx, body))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/compiler",
3
- "version": "1.0.24",
3
+ "version": "1.0.26",
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": {