@geastack/compiler 1.0.43 → 1.0.44

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
@@ -10,15 +10,21 @@ import { preflightReportLines } from './preflight/report.js';
10
10
  import { structuralShapeKey } from './semantics/model/structural-types.js';
11
11
  import { closeSync, openSync, writeSync } from 'node:fs';
12
12
  import { dirname } from 'node:path';
13
- import { setFlagsFromString } from 'node:v8';
13
+ import { getHeapStatistics, setFlagsFromString } from 'node:v8';
14
14
  // V8 grows the heap after each collection by up to four times what survived
15
15
  // it, bounded only by the old-space limit -- which builds raise to 32 GB so a
16
16
  // large program cannot fail on the default. A compile allocates fast and keeps
17
17
  // a few GB live, so with that headroom a large app's compile held 15.8 GB of
18
18
  // resident memory for 3.3 GB of live data. A 25% margin bounded it at 4.6 GB
19
19
  // for 9% more wall time. A caller that states its own percentage keeps it.
20
+ //
21
+ // The margin is only for a heap that limit leaves unbounded. A process given a
22
+ // few gigabytes is bounded by them already, and a 25% margin under them only
23
+ // makes it collect more often: a large three.js program compiling under a 4 GB
24
+ // heap took 5% longer with it (406 s against 387 s) and peaked 0.5 GB lower.
20
25
  const statedGrowth = [...process.execArgv, ...(process.env['NODE_OPTIONS'] ?? '').split(/\s+/)].some((flag) => /^--heap[-_]growing[-_]percent/.test(flag));
21
- if (!statedGrowth)
26
+ const boundedHeap = getHeapStatistics().heap_size_limit <= 8 * 1024 * 1024 * 1024;
27
+ if (!statedGrowth && !boundedHeap)
22
28
  setFlagsFromString('--heap-growing-percent=25');
23
29
  /**
24
30
  * `--project <tsconfig.json>` names the project explicitly; `--no-project`
@@ -1,3 +1,4 @@
1
+ import { getHeapStatistics } from 'node:v8';
1
2
  import { nativeBodyIgnoresLogicalReceiver } from './native-logical-receiver-body.js';
2
3
  import { nativeConstructorMethodBodiesOf } from './native-constructor-reads.js';
3
4
  import { classLayoutOfCopy, classLayoutsConstructedBy, constructedBaseOf } from '../projection/classes.js';
@@ -255,9 +256,12 @@ class ValueTable {
255
256
  ordinal = ordinal * 10 + digit;
256
257
  }
257
258
  this.ordinal = ordinal;
258
- if (this.lastSlots !== null && bar === 4 + this.lastBody.length && id.startsWith(this.lastBody, 4))
259
- return this.lastSlots;
259
+ // The body spelled out and compared whole: `id.startsWith(this.lastBody, 4)`
260
+ // asks the same, but took about eight times as long on these long ids, and
261
+ // this is asked millions of times a solve.
260
262
  const body = id.slice(4, bar);
263
+ if (this.lastSlots !== null && body === this.lastBody)
264
+ return this.lastSlots;
261
265
  let slots = this.byBody.get(body);
262
266
  if (slots === undefined) {
263
267
  if (!create)
@@ -3395,31 +3399,34 @@ const repointed = (value, pairs, seen, fresh) => {
3395
3399
  const partner = pairs.get(value);
3396
3400
  if (partner !== undefined)
3397
3401
  return partner;
3398
- if (fresh.objects.has(value))
3399
- fresh.reached = true;
3400
3402
  if (seen.has(value))
3401
3403
  return seen.get(value);
3404
+ // An object the new program holds that this answer allocated (`flowOverCopy`):
3405
+ // copied when asked to, so the answer holds its own as a solve's would.
3406
+ const copied = fresh.objects.has(value);
3407
+ if (copied && !fresh.copy)
3408
+ fresh.reached = true;
3402
3409
  seen.set(value, value);
3403
3410
  let result = value;
3404
3411
  if (Array.isArray(value)) {
3405
3412
  const items = value.map((item) => repointed(item, pairs, seen, fresh));
3406
- if (items.some((item, index) => item !== value[index]))
3413
+ if (copied || items.some((item, index) => item !== value[index]))
3407
3414
  result = items;
3408
3415
  }
3409
3416
  else if (value instanceof Map) {
3410
3417
  const entries = [...value].map(([key, item]) => [repointed(key, pairs, seen, fresh), repointed(item, pairs, seen, fresh)]);
3411
- if ([...value].some(([key, item], index) => entries[index][0] !== key || entries[index][1] !== item))
3418
+ if (copied || [...value].some(([key, item], index) => entries[index][0] !== key || entries[index][1] !== item))
3412
3419
  result = new Map(entries);
3413
3420
  }
3414
3421
  else if (value instanceof Set) {
3415
3422
  const items = [...value].map((item) => repointed(item, pairs, seen, fresh));
3416
- if ([...value].some((item, index) => items[index] !== item))
3423
+ if (copied || [...value].some((item, index) => items[index] !== item))
3417
3424
  result = new Set(items);
3418
3425
  }
3419
3426
  else {
3420
3427
  const prototype = Object.getPrototypeOf(value);
3421
3428
  if (prototype === Object.prototype || prototype === null) {
3422
- let copy = null;
3429
+ let copy = copied ? { ...value } : null;
3423
3430
  for (const key of Object.keys(value)) {
3424
3431
  const item = value[key];
3425
3432
  const moved = repointed(item, pairs, seen, fresh);
@@ -3429,6 +3436,8 @@ const repointed = (value, pairs, seen, fresh) => {
3429
3436
  if (copy !== null)
3430
3437
  result = copy;
3431
3438
  }
3439
+ else if (copied)
3440
+ fresh.reached = true;
3432
3441
  }
3433
3442
  seen.set(value, result);
3434
3443
  return result;
@@ -3437,9 +3446,9 @@ const repointed = (value, pairs, seen, fresh) => {
3437
3446
  * A remembered answer re-pointed from the program it was solved over to a
3438
3447
  * same-data copy of it, or null when it cannot stand for a solve of the copy.
3439
3448
  */
3440
- const flowOverCopy = (flow, pairs) => {
3449
+ const flowOverCopy = (flow, pairs, copy = false) => {
3441
3450
  const seen = new Map();
3442
- const fresh = { objects: new Set(pairs.values()), reached: false };
3451
+ const fresh = { objects: new Set(pairs.values()), reached: false, copy };
3443
3452
  const { nativeFieldViewAbsentRoutesOf: absentRoutesOf, callables, ...data } = flow;
3444
3453
  const moved = repointed(data, pairs, seen, fresh);
3445
3454
  // A solve allocates each callee identity afresh, and the dispatch passes then
@@ -3447,8 +3456,12 @@ const flowOverCopy = (flow, pairs) => {
3447
3456
  // re-pointed: handed back as they are, the reused answer would share them
3448
3457
  // with the bodies where a solve's never does.
3449
3458
  const callees = new Map([...callables].map(([value, callee]) => [value, repointed({ ...callee }, pairs, seen, fresh)]));
3459
+ // An answer holding an object a pass wrote into the program after the solve
3460
+ // is re-pointed once more, copying each such object: a solve of the new
3461
+ // program would allocate its own, equal to the copy and shared with
3462
+ // nothing. Only a plain object, array, map or set can be copied.
3450
3463
  if (fresh.reached)
3451
- return null;
3464
+ return copy ? null : flowOverCopy(flow, pairs, true);
3452
3465
  const answer = { ...moved, callables: callees };
3453
3466
  if (absentRoutesOf === undefined)
3454
3467
  return answer;
@@ -3609,7 +3622,12 @@ const releasePropagation = (cells) => {
3609
3622
  }
3610
3623
  }
3611
3624
  };
3612
- const valueOwnedBy = (id, owner) => id.startsWith('ssa|') && id.startsWith(owner, 4) && id.charCodeAt(4 + owner.length) === 124 && id.indexOf('|', 5 + owner.length) === -1;
3625
+ // `id.substring(...) === owner` rather than `id.startsWith(owner, 4)`: the same
3626
+ // question, several times faster for a long owner (see `ValueTable.slotsOf`).
3627
+ const valueOwnedBy = (id, owner) => id.startsWith('ssa|') &&
3628
+ id.substring(4, 4 + owner.length) === owner &&
3629
+ id.charCodeAt(4 + owner.length) === 124 &&
3630
+ id.indexOf('|', 5 + owner.length) === -1;
3613
3631
  /**
3614
3632
  * Every SSA value's carrier, read through the bodies rather than copied into
3615
3633
  * one table: a table of the program's every value, built at the solve's end,
@@ -3692,6 +3710,8 @@ let rememberedClasses = null;
3692
3710
  * other kind. A newer answer of the same kind replaces the older one, which
3693
3711
  * was solved over an earlier body generation and is only ever a worse match.
3694
3712
  */
3713
+ /** The heap limit from which a solve keeps the other kind's remembered answer (`nativeCallableFlowOf`). */
3714
+ const KEEP_OTHER_KIND_HEAP = 3 * 1024 * 1024 * 1024;
3695
3715
  const flowKindOf = (programConversions, constructionTopology) => (programConversions == null ? 0 : 1) + (constructionTopology == null ? 0 : 2);
3696
3716
  export const nativeCallableFlowOf = (...args) => {
3697
3717
  const [bodies, placements, classes, conversions, trace, deriver, programConversions, constructionTopology] = args;
@@ -3765,7 +3785,22 @@ export const nativeCallableFlowOf = (...args) => {
3765
3785
  // solve -- the compile's peak -- held beside its own state. An answer of the
3766
3786
  // other kind is still reused when no solve comes between, which is most
3767
3787
  // reuses; on a large program two more are solved.
3768
- entries.length = 0;
3788
+ //
3789
+ // Unless the heap is large enough to hold it: then only this kind's answer
3790
+ // goes, and the other kind's is kept for when the program comes back to it.
3791
+ // A large three.js program under a 4 GB heap asks again, after a solve of
3792
+ // the other kind, for the same data it last asked for of its own kind, and
3793
+ // each was a solve of several seconds. The choice follows the heap the
3794
+ // process was given, never what it holds at the moment: a reuse is the same
3795
+ // data either way, so it changes no answer.
3796
+ if (getHeapStatistics().heap_size_limit < KEEP_OTHER_KIND_HEAP)
3797
+ entries.length = 0;
3798
+ else {
3799
+ const kind = flowKindOf(programConversions, constructionTopology);
3800
+ for (let index = entries.length - 1; index >= 0; index--)
3801
+ if (flowKindOf(entries[index].programConversions, entries[index].constructionTopology) === kind)
3802
+ entries.splice(index, 1);
3803
+ }
3769
3804
  const flow = computeNativeCallableFlow(...args);
3770
3805
  return remember(flow, -1);
3771
3806
  };
@@ -1175,7 +1175,12 @@ export const packRestArguments = (ctx, block, lineage, operation, abi, passed) =
1175
1175
  throw new IrLoweringBlockedError(`a tuple-shaped rest slot's required field ${index} has no matching trailing argument`);
1176
1176
  return [];
1177
1177
  }
1178
- return [{ key: field.key, value: packingValueOf(entry) }];
1178
+ // Converted here, as a packed array's element is below: a position
1179
+ // several call forms fill (a number in one, an image source in another)
1180
+ // carries their join, and the record's store is not where a conversion
1181
+ // into it can be certified.
1182
+ const actual = packingValueOf(entry);
1183
+ return [{ key: field.key, value: convertTo(ctx, block, lineage, actual, field.value) ?? actual }];
1179
1184
  });
1180
1185
  const packed = ctx.builder.allocateRecord(block, lineage, fields, slot.value);
1181
1186
  return [...args.slice(0, abi.restFrom).map((entry) => entry.value), { value: packed, representation: slot.value }];
package/dist/ir/shake.js CHANGED
@@ -6,6 +6,7 @@ import { nativeCallableFlowOf } from './callable-class-flow.js';
6
6
  import { allOperationsOf } from './model.js';
7
7
  import { arrayAllocationDrainsDynamicIterator, operandsOfIrOperation, resultOfIrOperation } from './queries.js';
8
8
  import { verifyIrBody } from './verify.js';
9
+ import { hostTemplateMemberOf } from './host-template-conversions.js';
9
10
  /**
10
11
  * Whether a carrier can put user code on the path of an otherwise arithmetic
11
12
  * operation.
@@ -412,6 +413,26 @@ const sliceBody = (body, placements, liveCells, structuralViewScopes) => {
412
413
  }
413
414
  }
414
415
  }
416
+ // `Object.values(x)`, `Object.entries(x)` and `Object.assign(t, x)` read
417
+ // every own field of `x` without spelling a key and without lowering to
418
+ // `own-property-keys`: they are host calls. Missed here, a field only
419
+ // ever observed through one of them had its initializer pruned, and the
420
+ // walk read the struct's default-constructed slot (`''`, `0`) instead.
421
+ if (operation.kind === 'call') {
422
+ const host = hostTemplateMemberOf(operation, (value) => definitions.get(value) ?? null);
423
+ if (host?.protocol === 'ObjectConstructor') {
424
+ const walked = host.member === 'values' || host.member === 'entries' || host.member === 'getOwnPropertyDescriptors'
425
+ ? operation.arguments.slice(0, 1)
426
+ : host.member === 'assign'
427
+ ? operation.arguments.slice(1)
428
+ : [];
429
+ if (operation.argumentsAreSpread && walked.length > 0)
430
+ fieldHazardScopes.add(anyClassScope);
431
+ for (const argument of walked)
432
+ for (const scope of receiverClassScopes(argument.representation, structuralViewScopes))
433
+ fieldHazardScopes.add(scope);
434
+ }
435
+ }
415
436
  // OrdinaryToPrimitive invokes `toString`/`valueOf` without an explicit
416
437
  // property operation. Root those protocol members on the carrier being
417
438
  // coerced, rather than keeping same-named methods on every class in the
@@ -625,14 +625,20 @@ export const runFrontend = (input) => {
625
625
  // consumers now also see one set of write and call-site objects instead
626
626
  // of two that are equal only field by field.
627
627
  const valueFlow = contentEqual ? { ...contentEqual } : built;
628
- const sharedFrom = contentEqual && shareSourceValueSession(contentEqual, valueFlow) ? contentEqual : undefined;
629
- // A round's solver is asked nothing once the next round's index replaces
630
- // it (`retireSourceValueSession`); keeping it cost ~1 GB per round. A
631
- // solver handed on above is the new round's own, and stays.
632
- for (const earlier of roundFlows)
633
- if (earlier !== valueFlow && earlier !== sharedFrom)
634
- retireSourceValueSession(earlier);
635
- roundFlows.length = 0;
628
+ if (contentEqual)
629
+ shareSourceValueSession(contentEqual, valueFlow);
630
+ // No round's solver is retired when the next round replaces it. Every
631
+ // round's census stays on the `upstream` chain of every later one, down
632
+ // to the settled census the structural censuses read, and a question it
633
+ // cannot answer itself falls through to an earlier round's census and
634
+ // that round's session. A retired session answers by solving the whole
635
+ // program again from nothing, and the rebuilt solver then lives as long
636
+ // as its index does: on a large three.js program the second round rebuilt
637
+ // the first round's solver and the structural censuses rebuilt the second
638
+ // and third rounds', three full solves (about a third of the frontend)
639
+ // to reach the very heap that keeping them reaches. The final round's
640
+ // solver is still released once the producers are done (`produced`
641
+ // below); an earlier one lives as long as its index, as a rebuilt one did.
636
642
  roundFlows.push(valueFlow);
637
643
  attachDeferredIntrinsicProtocolLedger(valueFlow, intrinsicProtocols);
638
644
  commonJsModuleRecords.attachToFlow(valueFlow);
@@ -1436,10 +1442,9 @@ export const runFrontend = (input) => {
1436
1442
  // mappers all agree on what "the same copy" means.
1437
1443
  copyKey: (candidate) => identities.copyKeyOf(candidate.specialization),
1438
1444
  // The final round's solver answers the producers and nothing after them.
1439
- produced: () => {
1440
- for (const flow of roundFlows)
1441
- retireSourceValueSession(flow);
1442
- },
1445
+ // Only the final round's: an earlier one stays as long as its index, as
1446
+ // it did when the structural censuses rebuilt it.
1447
+ produced: () => retireSourceValueSession(roundFlows[roundFlows.length - 1]),
1443
1448
  gates: (operations) => gatingEdges({
1444
1449
  files: compiled.sourceFiles,
1445
1450
  identities,
@@ -1472,8 +1477,7 @@ export const runFrontend = (input) => {
1472
1477
  const identity = fileIdentities.get(file.fileName);
1473
1478
  return identity === undefined ? [] : [[identity, file]];
1474
1479
  }));
1475
- for (const flow of roundFlows)
1476
- retireSourceValueSession(flow);
1480
+ retireSourceValueSession(roundFlows[roundFlows.length - 1]);
1477
1481
  return {
1478
1482
  dynamicFallbackTypes,
1479
1483
  dynamicWrittenTypes,
@@ -482,6 +482,8 @@ const componentEngine = (graph, mode) => {
482
482
  };
483
483
  /** Past this many entries an edge collection becomes a hash table: a lookup is a linear scan below it. */
484
484
  const SMALL_EDGES = 8;
485
+ /** How far ahead of its last edge read `observedState` looks before asking the dependency. */
486
+ const CURSOR_WINDOW = 4;
485
487
  const edgeCount = (edges) => edges === null ? 0 : edges instanceof Map || edges instanceof Set ? edges.size : Array.isArray(edges) ? edges.length : 1;
486
488
  const NO_EDGE_STATES = [];
487
489
  const edgeStates = (edges) => edges === null ? NO_EDGE_STATES : edges instanceof Set || Array.isArray(edges) ? edges : [edges];
@@ -814,11 +816,32 @@ export const dependencyFactSolver = (expand, mode, keysAreStates = false) => {
814
816
  return candidate;
815
817
  return undefined;
816
818
  }
819
+ // A transfer re-reads its edges in the order it first read them, so the
820
+ // running owner's next edge is nearly always the one asked for: checked
821
+ // first, a few places ahead for a read the transfer skipped this time.
822
+ // The test below asks a dependency's dependents, which for a node read
823
+ // from everywhere is a table of hundreds of thousands of states; on a
824
+ // large three.js program it was a tenth of the session's time.
825
+ if (owner === cursorOwner) {
826
+ const end = Math.min(observed.length, readCursor + CURSOR_WINDOW);
827
+ for (let at = readCursor; at < end; at++) {
828
+ const candidate = observed[at];
829
+ if (candidate.solverKey === dependency) {
830
+ readCursor = at + 1;
831
+ return candidate;
832
+ }
833
+ }
834
+ }
817
835
  // An owner is among a dependency's dependents exactly when it observes
818
836
  // it: the two edges are only ever added together (`factsFrom`).
819
837
  const state = existingStateOf(dependency);
820
838
  return state !== undefined && edgeHas(state.dependents, owner) ? state : undefined;
821
839
  };
840
+ // The state whose transfer or seal is running and where its edge reads have
841
+ // reached (`observedState`). Only a hint: every hit is checked against the
842
+ // dependency's key, so a stale cursor costs a miss, never a wrong edge.
843
+ let cursorOwner = null;
844
+ let readCursor = 0;
822
845
  const withObserved = (observed, dependencyState) => {
823
846
  if (observed === null)
824
847
  return dependencyState;
@@ -981,6 +1004,10 @@ export const dependencyFactSolver = (expand, mode, keysAreStates = false) => {
981
1004
  const holding = holders.get(fact);
982
1005
  if (holding === undefined)
983
1006
  return NO_HOLDERS;
1007
+ // A key that is its own state needs no copy: the collection only grows in
1008
+ // `index`, which runs after the transfer asking has returned.
1009
+ if (keysAreStates)
1010
+ return edgeStates(holding);
984
1011
  const found = [];
985
1012
  for (const holder of edgeStates(holding))
986
1013
  found.push(holder.solverKey);
@@ -1046,8 +1073,16 @@ export const dependencyFactSolver = (expand, mode, keysAreStates = false) => {
1046
1073
  const observeFrom = (ownerState, dependency) => factsFrom(ownerState, dependency, false);
1047
1074
  // A state's edge readers, minted per transfer or seal call rather than kept
1048
1075
  // on every state (see `stateOf`).
1049
- const transferOf = (state) => definitionOf(state).transfer((dependency) => readFrom(state, dependency), (dependency) => observeFrom(state, dependency), (fact) => holdersOfFrom(state, fact), state.solverKey);
1050
- const sealOf = (state) => definitionOf(state).seal((dependency) => readFrom(state, dependency), (dependency) => observeFrom(state, dependency), (fact) => holdersOfFrom(state, fact), state.solverKey);
1076
+ const transferOf = (state) => {
1077
+ cursorOwner = state;
1078
+ readCursor = 0;
1079
+ return definitionOf(state).transfer((dependency) => readFrom(state, dependency), (dependency) => observeFrom(state, dependency), (fact) => holdersOfFrom(state, fact), state.solverKey);
1080
+ };
1081
+ const sealOf = (state) => {
1082
+ cursorOwner = state;
1083
+ readCursor = 0;
1084
+ return definitionOf(state).seal((dependency) => readFrom(state, dependency), (dependency) => observeFrom(state, dependency), (fact) => holdersOfFrom(state, fact), state.solverKey);
1085
+ };
1051
1086
  const propagate = () => {
1052
1087
  for (let cursor = 0; cursor < queue.length; cursor++) {
1053
1088
  const state = queue[cursor];
@@ -63,6 +63,9 @@ type QueryShape = {
63
63
  } | {
64
64
  readonly kind: 'unknown-reads';
65
65
  readonly node: ObjectRoot;
66
+ } | {
67
+ readonly kind: 'copy-sites';
68
+ readonly node: ObjectRoot;
66
69
  } | {
67
70
  readonly kind: 'key-reads' | 'key-uses' | 'family-slot';
68
71
  readonly node: ObjectRoot;