@geastack/compiler 1.0.24 → 1.0.25

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/cli.js CHANGED
File without changes
@@ -70,8 +70,9 @@ export interface DenseArray {
70
70
  * rather than the loop's counter -- `ring[i % ring.length]`, the shape every
71
71
  * ring buffer and hash bucket is written in.
72
72
  *
73
- * A different proof, and a simpler one: `x % n` lies in `[0, n)` for every
74
- * dividend whenever `n > 0`, so the window needs no bound, no base and no
73
+ * A different proof, and a simpler one: `x % n` lies in `(-n, n)` for every
74
+ * dividend whenever `n > 0` -- and in `[0, n)` once the access has tested
75
+ * its sign (`DenseAccess.signed`) -- so the window needs no bound, no base and no
75
76
  * counter -- only that the array is non-empty and has no holes, which is what
76
77
  * the preheader checks. `bases`, `bound`, `inclusive`, `step` and `widened`
77
78
  * carry no meaning for one of these.
@@ -173,6 +174,14 @@ export interface DenseAccess {
173
174
  readonly array: number;
174
175
  /** The flag it renders behind: the innermost enclosing loop's, which implies the window's own. */
175
176
  readonly flag: number;
177
+ /**
178
+ * Whether this access's index is a REMAINDER, which the window's flag does
179
+ * not bound below: `x % n` takes the dividend's sign, so `-3 % 16` is `-3`
180
+ * and no preheader check can see that coming. The emitter tests the index's
181
+ * sign at the access itself -- a register compare, not the size reload the
182
+ * window exists to remove. A mask (`x & M`) is never negative and needs none.
183
+ */
184
+ readonly signed: boolean;
176
185
  }
177
186
  export interface DenseLoopPlan {
178
187
  readonly arrays: readonly DenseArray[];
@@ -252,7 +252,7 @@ export const denseLoopsOf = (body, hoists = loopInvariantHoistsOf(body)) => {
252
252
  const flag = flagAt(blockOfOperation.get(operation) ?? loop.preheader);
253
253
  if (flag === null)
254
254
  continue;
255
- accesses.set(operation, { array: ordinal, flag });
255
+ accesses.set(operation, { array: ordinal, flag, signed: candidate.signed.includes(operation) });
256
256
  }
257
257
  }
258
258
  }
@@ -504,9 +504,14 @@ const windowsOfLoop = (blocks, body, context) => {
504
504
  // taken modulo needs no number carried to the preheader, and a program
505
505
  // that spells both is better served by the shape that checks less.
506
506
  const ownLength = wrapsOwnLength(operation.key, receiver, context);
507
- const modulus = ownLength ? null : constantModulusOf(operation.key, context, block.operations, block.operations.indexOf(operation));
507
+ const at = block.operations.indexOf(operation);
508
+ const modulus = ownLength ? null : constantModulusOf(operation.key, context, block.operations, at);
508
509
  const wrapped = ownLength || modulus !== null;
509
- if (typed !== null && (wrapped || held.reference.kind === 'element'))
510
+ const signed = ownLength || (modulus !== null && !isMaskKey(operation.key, context, block.operations, at));
511
+ // A typed array has no own-length remainder form here (its length is not
512
+ // `cells`), but a constant reach is checked against its `size()` like any
513
+ // other window.
514
+ if (typed !== null && ((wrapped && modulus === null) || held.reference.kind === 'element'))
510
515
  continue;
511
516
  const base = wrapped ? null : indexBaseOf(operation.key, context, blocks);
512
517
  const found = byReference.get(key);
@@ -514,11 +519,21 @@ const windowsOfLoop = (blocks, body, context) => {
514
519
  if (found)
515
520
  found.sound = false;
516
521
  else
517
- byReference.set(key, { ...held, element, typed, wrapped, modulus, bases: [], operations: [], sound: false });
522
+ byReference.set(key, { ...held, element, typed, wrapped, modulus, bases: [], operations: [], signed: [], sound: false });
518
523
  continue;
519
524
  }
520
525
  if (!found) {
521
- byReference.set(key, { ...held, element, typed, wrapped, modulus, bases: [base], operations: [operation], sound: true });
526
+ byReference.set(key, {
527
+ ...held,
528
+ element,
529
+ typed,
530
+ wrapped,
531
+ modulus,
532
+ bases: [base],
533
+ operations: [operation],
534
+ signed: signed ? [operation] : [],
535
+ sound: true
536
+ });
522
537
  continue;
523
538
  }
524
539
  // Different addends each contribute a range check to the one cumulative
@@ -539,6 +554,8 @@ const windowsOfLoop = (blocks, body, context) => {
539
554
  if (!found.bases.some(same))
540
555
  found.bases.push(base);
541
556
  found.operations.push(operation);
557
+ if (signed)
558
+ found.signed.push(operation);
542
559
  }
543
560
  }
544
561
  }
@@ -569,7 +586,8 @@ const windowsOfLoop = (blocks, body, context) => {
569
586
  /**
570
587
  * Whether an index is a REMAINDER by this very array's `length`.
571
588
  *
572
- * `x % a.length` is in `[0, a.length)` for every dividend, so an access keyed
589
+ * `x % a.length` is in `(-a.length, a.length)` for every dividend, and the
590
+ * access tests the sign (`DenseAccess.signed`), so an access keyed
573
591
  * by one needs no bound of its own -- which is the whole point, because the
574
592
  * bound is what a per-access size read would cost. The receiver of the length
575
593
  * read has to be the SAME value the access itself indexes: `a[x % b.length]`
@@ -604,8 +622,8 @@ const wrapsOwnLength = (key, receiver, context) => {
604
622
  * The positive integer an index is taken modulo, when the divisor is a
605
623
  * CONSTANT -- `table[i % 16]`.
606
624
  *
607
- * The same arithmetic `wrapsOwnLength` relies on: `x % n` lies in `[0, n)` for
608
- * every dividend whenever `n > 0`. What this does NOT prove is that `n` is
625
+ * The same arithmetic `wrapsOwnLength` relies on: `x % n` lies in `(-n, n)`
626
+ * for every dividend whenever `n > 0`, and the access tests its sign. What this does NOT prove is that `n` is
609
627
  * inside the array, because a constant says nothing about a length; the
610
628
  * preheader's `size() >= n` is what closes that, and `DenseArray.modulus`
611
629
  * carries the number there.
@@ -616,7 +634,11 @@ const wrapsOwnLength = (key, receiver, context) => {
616
634
  */
617
635
  const constantModulusOf = (key, context, operations, at) => {
618
636
  const compute = remainderBehind(key, context, operations, at);
619
- if (compute?.kind !== 'compute' || compute.form !== 'binary' || compute.operator !== '%')
637
+ if (compute?.kind !== 'compute' || compute.form !== 'binary')
638
+ return null;
639
+ if (compute.operator === '&')
640
+ return constantMaskReachOf(compute.operands, context);
641
+ if (compute.operator !== '%')
620
642
  return null;
621
643
  const divisor = compute.operands[1];
622
644
  if (!divisor)
@@ -629,6 +651,33 @@ const constantModulusOf = (key, context, operations, at) => {
629
651
  return null;
630
652
  return value;
631
653
  };
654
+ /** Whether an index whose reach `constantModulusOf` read is a MASK, which is never negative. */
655
+ const isMaskKey = (key, context, operations, at) => {
656
+ const compute = remainderBehind(key, context, operations, at);
657
+ return compute?.kind === 'compute' && compute.form === 'binary' && compute.operator === '&';
658
+ };
659
+ /**
660
+ * `table[v & 255]` -- the other way every lookup table is indexed, and the
661
+ * one that needs no sign argument at all: `&` works on ToInt32 of both
662
+ * operands, so with a mask `M` in `[0, 2^31)` the result lies in `[0, M]` for
663
+ * EVERY left operand, NaN and negatives included. That is a window over
664
+ * `M + 1` elements, which is exactly what a constant modulus of `M + 1` asks
665
+ * the preheader to check, so it travels as one.
666
+ *
667
+ * Either operand may be the constant; a negative or fractional one bounds
668
+ * nothing and is not one of these.
669
+ */
670
+ const constantMaskReachOf = (operands, context) => {
671
+ for (const operand of operands) {
672
+ const text = context.constantTexts.get(operand.value);
673
+ if (text === undefined)
674
+ continue;
675
+ const value = Number(text);
676
+ if (Number.isSafeInteger(value) && value >= 0 && value <= 0x7fffffff)
677
+ return value + 1;
678
+ }
679
+ return null;
680
+ };
632
681
  /**
633
682
  * Where an index's value was computed, seeing through a binding.
634
683
  *
@@ -271,10 +271,26 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
271
271
  // was every index derived from it -- soft-float on every pixel of Bloom's
272
272
  // upscaler.
273
273
  const minMaxResults = new Map();
274
+ // `Math.clz32` counts the leading zeros of ToUint32 of anything, NaN
275
+ // included: always an integer in [0, 32]. `Math.abs` of an integer is an
276
+ // integer no larger than it. Without these a vorticity confinement's
277
+ // `Math.abs(gx)` and `Math.clz32(length)` were doubles, and with them every
278
+ // shift and product downstream -- soft-float per cell on the S31.
279
+ const clz32Results = new Set();
280
+ const absResults = new Map();
274
281
  for (const [call, intrinsic] of numericIntrinsicsOf(body).calls) {
275
- if (intrinsic === 'imul' && call.result)
282
+ if (!call.result)
283
+ continue;
284
+ if (intrinsic === 'imul')
276
285
  imulResults.add(call.result.id);
277
- else if (call.result)
286
+ else if (intrinsic === 'clz32')
287
+ clz32Results.add(call.result.id);
288
+ else if (intrinsic === 'abs') {
289
+ const argument = call.arguments[0];
290
+ if (argument)
291
+ absResults.set(call.result.id, argument);
292
+ }
293
+ else
278
294
  minMaxResults.set(call.result.id, call.arguments);
279
295
  }
280
296
  const definitions = new Map();
@@ -402,8 +418,11 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
402
418
  if (scalar)
403
419
  integralCells.add(cell);
404
420
  const producesInteger = (value) => {
405
- if (imulResults.has(value))
421
+ if (imulResults.has(value) || clz32Results.has(value))
406
422
  return true;
423
+ const absolute = absResults.get(value);
424
+ if (absolute !== undefined)
425
+ return integral.has(absolute.value);
407
426
  const chosen = minMaxResults.get(value);
408
427
  if (chosen !== undefined)
409
428
  return chosen.every((argument) => integral.has(argument.value));
@@ -624,6 +643,11 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
624
643
  const computeMagnitude = (operand) => {
625
644
  if (imulResults.has(operand.value))
626
645
  return boundedBy(2 ** 31);
646
+ if (clz32Results.has(operand.value))
647
+ return boundedBy(32);
648
+ const absolute = absResults.get(operand.value);
649
+ if (absolute !== undefined)
650
+ return magnitudeOfValue(absolute);
627
651
  const chosen = minMaxResults.get(operand.value);
628
652
  if (chosen !== undefined) {
629
653
  let answer = { kind: 'bounded', limit: 0 };
@@ -1,6 +1,6 @@
1
1
  import type { IrValueId } from '../identity/ids.js';
2
2
  import type { CallOperation, IrBody } from './model.js';
3
- export type NumericIntrinsic = 'imul' | 'min' | 'max';
3
+ export type NumericIntrinsic = 'imul' | 'min' | 'max' | 'abs' | 'clz32';
4
4
  /**
5
5
  * Language builtin calls authenticated by their native protocol, never by a
6
6
  * source identifier spelling. A user object named Math has no such protocol.
@@ -1,6 +1,13 @@
1
1
  import { allOperationsOf } from './model.js';
2
2
  import { operandsOfIrOperation } from './queries.js';
3
- const twoArgumentIntrinsics = new Set(['imul', 'min', 'max']);
3
+ /** How many arguments each intrinsic is recognized at; other arities keep the general callable path. */
4
+ const intrinsicArity = new Map([
5
+ ['imul', 2],
6
+ ['min', 2],
7
+ ['max', 2],
8
+ ['abs', 1],
9
+ ['clz32', 1]
10
+ ]);
4
11
  /**
5
12
  * Language builtin calls authenticated by their native protocol, never by a
6
13
  * source identifier spelling. A user object named Math has no such protocol.
@@ -26,7 +33,7 @@ export const numericIntrinsicsOf = (body) => {
26
33
  if (receiver.kind === 'native-handle' &&
27
34
  receiver.native === null &&
28
35
  receiver.protocol === 'Math' &&
29
- twoArgumentIntrinsics.has(keys.get(operation.key.value) ?? '')) {
36
+ intrinsicArity.has(keys.get(operation.key.value) ?? '')) {
30
37
  callees.set(operation.result.id, keys.get(operation.key.value));
31
38
  }
32
39
  }
@@ -37,7 +44,7 @@ export const numericIntrinsicsOf = (body) => {
37
44
  continue;
38
45
  const intrinsic = callees.get(operation.callee.value);
39
46
  // Other arities and coercing ABIs retain the general callable path.
40
- if (intrinsic === undefined || operation.arguments.length !== 2)
47
+ if (intrinsic === undefined || operation.arguments.length !== intrinsicArity.get(intrinsic))
41
48
  continue;
42
49
  if (!operation.arguments.every((argument) => argument.representation.kind === 'scalar' && argument.representation.domain === 'number'))
43
50
  continue;
@@ -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
@@ -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
  };
@@ -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`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/compiler",
3
- "version": "1.0.24",
3
+ "version": "1.0.25",
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": {
@@ -7995,6 +7995,13 @@ inline long long integerImul(std::uint32_t left, std::uint32_t right) {
7995
7995
  return static_cast<long long>(static_cast<std::int32_t>(left * right));
7996
7996
  }
7997
7997
 
7998
+ // `Math.abs` of a value the integer census holds in a `long long` (its
7999
+ // magnitude is below 2^63, so the negation cannot overflow).
8000
+ inline long long integerAbs(long long value) { return value < 0 ? -value : value; }
8001
+
8002
+ // `Math.clz32` of an argument that has already undergone ToUint32.
8003
+ inline long long integerClz32(std::uint32_t value) { return value == 0 ? 32 : __builtin_clz(value); }
8004
+
7998
8005
  inline long long integerBitwiseOr(long long left, long long right) {
7999
8006
  return static_cast<std::int32_t>(static_cast<std::uint32_t>(left) | static_cast<std::uint32_t>(right));
8000
8007
  }
@@ -8208,22 +8215,42 @@ class TypedArray {
8208
8215
 
8209
8216
  // The caller owns an admitted NON-SHARED dense window. Shared views are
8210
8217
  // excluded before emission because only instance access can enter their
8211
- // backing-store mutex. memcpy preserves aliasing between differently typed
8212
- // views of the same ArrayBuffer; native T* dereferences would let the C++
8213
- // optimizer assume those views are disjoint.
8214
- [[gnu::always_inline]] static T readInBounds(const T* base, std::size_t index) {
8215
- T value;
8216
- std::memcpy(&value, reinterpret_cast<const std::uint8_t*>(base) + index * sizeof(T), sizeof(T));
8217
- return value;
8218
+ // backing-store mutex. The element is accessed through a `may_alias` type:
8219
+ // differently typed views of one ArrayBuffer overlap, and a plain T*
8220
+ // dereference would let the C++ optimizer assume they are disjoint. It is
8221
+ // NOT a byte memcpy: GCC for rv32 expands a 4-byte memcpy into a `float` as
8222
+ // an integer load and a trip through the stack into the FPU register (a
8223
+ // store and a reload per element -- bloom's 18-tap stencil spent most of
8224
+ // its ~150 instructions a cell on them). A view's elements are aligned
8225
+ // (ECMA-262 requires byteOffset to be a multiple of the element size), so
8226
+ // the typed access is a plain `flw`/`fsw`. `may_alias` cannot be attached to
8227
+ // an already-defined class (`ClampedUint8`), which keeps the byte copy -- a
8228
+ // one-byte memcpy is a plain `lbu`/`sb` anyway.
8229
+ [[gnu::always_inline]] static T loadElement(const T* base, std::size_t index) {
8230
+ if constexpr (std::is_arithmetic_v<T>) {
8231
+ typedef T __attribute__((__may_alias__)) Aliased;
8232
+ return reinterpret_cast<const Aliased*>(base)[index];
8233
+ } else {
8234
+ T value;
8235
+ std::memcpy(&value, reinterpret_cast<const std::uint8_t*>(base) + index * sizeof(T), sizeof(T));
8236
+ return value;
8237
+ }
8238
+ }
8239
+ [[gnu::always_inline]] static void storeElement(T* base, std::size_t index, T value) {
8240
+ if constexpr (std::is_arithmetic_v<T>) {
8241
+ typedef T __attribute__((__may_alias__)) Aliased;
8242
+ reinterpret_cast<Aliased*>(base)[index] = value;
8243
+ } else {
8244
+ std::memcpy(reinterpret_cast<std::uint8_t*>(base) + index * sizeof(T), &value, sizeof(T));
8245
+ }
8218
8246
  }
8247
+ [[gnu::always_inline]] static T readInBounds(const T* base, std::size_t index) { return loadElement(base, index); }
8219
8248
  [[gnu::always_inline]] static void writeInBounds(T* base, std::size_t index, double value) {
8220
- const T converted = detail::typedArrayElement<T>(value);
8221
- std::memcpy(reinterpret_cast<std::uint8_t*>(base) + index * sizeof(T), &converted, sizeof(T));
8249
+ storeElement(base, index, detail::typedArrayElement<T>(value));
8222
8250
  }
8223
8251
  /** `writeInBounds` for a value the integer census holds as an integer (`detail::typedArrayIntegerElement`). */
8224
8252
  [[gnu::always_inline]] static void writeIntegerInBounds(T* base, std::size_t index, long long value) {
8225
- const T converted = detail::typedArrayIntegerElement<T>(value);
8226
- std::memcpy(reinterpret_cast<std::uint8_t*>(base) + index * sizeof(T), &converted, sizeof(T));
8253
+ storeElement(base, index, detail::typedArrayIntegerElement<T>(value));
8227
8254
  }
8228
8255
  /** An integer element as the integer it is, for a result the integer census holds in a `long long`. */
8229
8256
  [[gnu::always_inline]] static long long readIntegerInBounds(const T* base, std::size_t index) {
@@ -1,41 +0,0 @@
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;
@@ -1,115 +0,0 @@
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
- };
@@ -1,32 +0,0 @@
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>;
@@ -1,90 +0,0 @@
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
- };
@@ -1,32 +0,0 @@
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;
@@ -1,125 +0,0 @@
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;