tla-ts 0.0.10-dev.e3e5dd576 → 0.0.10-dev.e5c8dc315

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 (60) hide show
  1. package/dist/deciders.cjs +1 -1
  2. package/dist/deciders.js +1 -1
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/parallel-worker.cjs +1 -1
  6. package/dist/parallel-worker.js +1 -1
  7. package/dist/prove.cjs +10 -10
  8. package/dist/prove.js +57 -57
  9. package/dist/run.cjs +26 -26
  10. package/dist/run.js +32 -32
  11. package/dist/transfer.cjs +94 -94
  12. package/dist/transfer.js +83 -83
  13. package/package.json +1 -1
  14. package/src/ast.ts +16 -0
  15. package/src/check-trace.ts +43 -42
  16. package/src/check.ts +2 -1
  17. package/src/coverage.ts +66 -18
  18. package/src/environment.ts +34 -30
  19. package/src/evaluate.ts +57 -39
  20. package/src/instances.ts +17 -14
  21. package/src/liveness.ts +4 -0
  22. package/src/prover/smt/solver/ackermannize-bv-tactic.ts +3 -2
  23. package/src/prover/smt/solver/bit-blast-tactic.ts +1 -1
  24. package/src/prover/smt/solver/bv1-blast.ts +1 -1
  25. package/src/prover/smt/solver/card2bv.ts +1 -1
  26. package/src/prover/smt/solver/ctx-simplify.ts +8 -2
  27. package/src/prover/smt/solver/diff-neq.ts +8 -6
  28. package/src/prover/smt/solver/dt2bv-tactic.ts +10 -8
  29. package/src/prover/smt/solver/elim-uncnstr.ts +26 -20
  30. package/src/prover/smt/solver/eq2bv-tactic.ts +15 -6
  31. package/src/prover/smt/solver/fd-solver.ts +1 -1
  32. package/src/prover/smt/solver/fix-dl-var.ts +1 -1
  33. package/src/prover/smt/solver/fm-tactic.ts +9 -7
  34. package/src/prover/smt/solver/fpa2bv-tactic.ts +1 -1
  35. package/src/prover/smt/solver/lia2pb.ts +1 -1
  36. package/src/prover/smt/solver/nlqsat.ts +1 -0
  37. package/src/prover/smt/solver/normalize-bounds.ts +2 -2
  38. package/src/prover/smt/solver/occf.ts +1 -1
  39. package/src/prover/smt/solver/pb2bv-tactic.ts +9 -3
  40. package/src/prover/smt/solver/purify-arith.ts +51 -49
  41. package/src/prover/smt/solver/reduce-args.ts +2 -2
  42. package/src/prover/smt/solver/sat/goal2sat.ts +12 -2
  43. package/src/prover/smt/solver/sat/inc-sat-solver.ts +21 -5
  44. package/src/prover/smt/solver/sat/sat-tactic.ts +51 -32
  45. package/src/prover/smt/solver/sat/sat2goal.ts +4 -3
  46. package/src/prover/smt/solver/smtlib-script.ts +6 -4
  47. package/src/prover/smt/solver/solver.ts +0 -1
  48. package/src/prover/smt/solver/tactic.ts +40 -5
  49. package/src/prover/smt/solver/theory-lra-propagate.ts +1 -0
  50. package/src/prover/smt/solver/tseitin-cnf.ts +14 -5
  51. package/src/resolve.ts +54 -28
  52. package/src/runtime.ts +14 -1
  53. package/src/sany/generator-proofs.ts +1 -0
  54. package/src/sany/selectors.ts +1 -0
  55. package/src/search.ts +3 -1
  56. package/src/simulate.ts +26 -17
  57. package/src/spec-description.ts +8 -2
  58. package/src/subexpressions.ts +138 -45
  59. package/src/successors.ts +13 -7
  60. package/src/tlc/replay.ts +80 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tla-ts",
3
- "version": "0.0.10-dev.e3e5dd576",
3
+ "version": "0.0.10-dev.e5c8dc315",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/ast.ts CHANGED
@@ -527,6 +527,22 @@ export interface Module {
527
527
  hasRecursiveLet: boolean;
528
528
  }
529
529
 
530
+ const functionConstructions = new WeakMap<FunctionDefinition, Expression>();
531
+
532
+ export const getFunctionConstruction = (definition: FunctionDefinition, isLet: boolean) => {
533
+ const known = functionConstructions.get(definition);
534
+ if (known) return known;
535
+ const construction: Expression = {
536
+ kind: "FunctionConstruction",
537
+ bounds: definition.bounds,
538
+ body: definition.body,
539
+ location: definition.location,
540
+ isRecursive: isLet,
541
+ };
542
+ functionConstructions.set(definition, construction);
543
+ return construction;
544
+ };
545
+
530
546
  export const getDefinitionExpressions = (definition: Definition) =>
531
547
  definition.kind === "Function"
532
548
  ? [...definition.bounds.map((bound) => bound.set), definition.body]
@@ -98,7 +98,6 @@ export const createTraceBuilder = (context: TraceContext) => {
98
98
  runtime.getBehavior = searchBehavior;
99
99
  }
100
100
  };
101
- // Deviation from TLC: TLCTrace#printTrace and Worker#doPostCondition rebuild a step with the generator that already drew for its state, so they miss it; printTrace leaks a NullPointerException and doPostCondition skips the postcondition.
102
101
  const rebuildFrom = (state: Value[], level: number) => {
103
102
  current.rebuilt = { state, level };
104
103
  runtime.reseedRandom();
@@ -110,17 +109,27 @@ export const createTraceBuilder = (context: TraceContext) => {
110
109
  if (error) throw error;
111
110
  return isSameValue(value, successor[position]);
112
111
  });
113
- const findStepAction = (index: number, previous: Value[], state: Value[], isHeld: boolean) => {
112
+ const findStepAction = (
113
+ index: number,
114
+ previous: Value[],
115
+ state: Value[],
116
+ isHeld: boolean,
117
+ isDrawnOn = false,
118
+ ) => {
114
119
  const expanding = { ...current };
115
120
  Object.assign(current, { index, isExpanding: true, candidate: undefined });
116
- rebuildFrom(previous, depths[index]);
117
121
  const key = isHeld ? state : getFingerprintState(state);
122
+ const isMatch = (successor: Successor) =>
123
+ isHeld
124
+ ? isEqualState(key, successor.state)
125
+ : isSameState(getFingerprintState(successor.state), key);
118
126
  try {
119
- return context.findSuccessorAction(previous, (successor) =>
120
- isHeld
121
- ? isEqualState(key, successor.state)
122
- : isSameState(getFingerprintState(successor.state), key),
123
- );
127
+ current.rebuilt = { state: previous, level: depths[index] };
128
+ const drawn = isDrawnOn ? context.findSuccessorAction(previous, isMatch) : undefined;
129
+ if (drawn) return drawn;
130
+ // Deviation from TLC: when TLCTrace#printTrace and Worker#doPostCondition draw on and miss the step, printTrace leaks a NullPointerException and doPostCondition skips the postcondition.
131
+ rebuildFrom(previous, depths[index]);
132
+ return context.findSuccessorAction(previous, isMatch);
124
133
  } finally {
125
134
  Object.assign(current, expanding);
126
135
  }
@@ -134,40 +143,40 @@ export const createTraceBuilder = (context: TraceContext) => {
134
143
  const known = traceOptions.known ?? 1;
135
144
  const loopStart = traceOptions.loopStart;
136
145
  const rebuilt = is174 && loopStart !== undefined ? loopStart + 1 : steps.length - known;
137
- const isRebuiltAgain = known > 0 && !is174 && !traceOptions.isPrintedOnly;
146
+ const isRebuiltAgain = known > 0 && !is174 && !traceOptions.isPrintedOnly && steps.length > 1;
138
147
  const initialOutput =
139
- known === 0 || (steps.length > 1 && (rebuilt > 0 || isRebuiltAgain || is174))
140
- ? captureOutput(context.getInitialStates).lines
148
+ known === 0 || (steps.length > 1 && (rebuilt > 0 || is174))
149
+ ? runtime.runWithNewRandom(() => captureOutput(context.getInitialStates).lines)
141
150
  : [];
142
- const stepActions = steps.map((step, position) =>
143
- position === 0 || step.action === "Stuttering"
151
+ const last = steps.length - 1;
152
+ const findPositionAction = (position: number, isDrawnOn = false) =>
153
+ position === 0 || steps[position].action === "Stuttering"
144
154
  ? { result: undefined, lines: [] }
145
155
  : captureOutput(() =>
146
156
  findStepAction(
147
157
  path[position - 1],
148
158
  steps[position - 1].state,
149
- step.state,
150
- known === 2 && position === steps.length - 1,
151
- ),
152
- ),
153
- );
154
- const outputs = stepActions.map((step) => step.lines);
155
- if (environment.coverage && steps.length > 1) {
156
- if (rebuilt > 0 && isRebuiltAgain) captureOutput(context.getInitialStates);
157
- if (isRebuiltAgain) {
158
- steps.slice(1).forEach((step, position) => {
159
- if (step.action === "Stuttering") return;
160
- captureOutput(() =>
161
- findStepAction(
162
- path[position],
163
159
  steps[position].state,
164
- step.state,
165
- known === 2 && position === steps.length - 2,
160
+ known === 2 && position === last,
161
+ isDrawnOn,
166
162
  ),
167
163
  );
168
- });
169
- }
170
- }
164
+ // TLC's TLCStateRandom reseeds only for another state, so TLC rebuilds the step to a known successor drawing on from where the search stopped, unless it rebuilt a step before it.
165
+ const stepActions = steps.map((_step, position) =>
166
+ findPositionAction(position, known === 2 && position === last && last === 1 && !is174),
167
+ );
168
+ const outputs = stepActions.map((step) => step.lines);
169
+ const traceOutput = isRebuiltAgain
170
+ ? [
171
+ ...runtime.runWithNewRandom(() => [
172
+ captureOutput(context.getInitialStates).lines,
173
+ ...steps
174
+ .slice(1, last)
175
+ .map((_step, position) => findPositionAction(position + 1).lines),
176
+ ]),
177
+ findPositionAction(last, known === 2).lines,
178
+ ].flat()
179
+ : [];
171
180
  const prefixOutput = rebuilt > 0 ? [initialOutput, ...outputs.slice(1, rebuilt)].flat() : [];
172
181
  return {
173
182
  trace: steps.map((step, position) => {
@@ -194,7 +203,7 @@ export const createTraceBuilder = (context: TraceContext) => {
194
203
  }
195
204
  return traceStep;
196
205
  }),
197
- traceOutput: isRebuiltAgain ? [initialOutput, ...outputs].flat() : [],
206
+ traceOutput,
198
207
  };
199
208
  };
200
209
  const findTraceSuccessor = (state: Value[], isMatch: (successor: Successor) => boolean) =>
@@ -258,15 +267,7 @@ export const createTraceBuilder = (context: TraceContext) => {
258
267
  action: context.actions[position],
259
268
  }));
260
269
  if (!lastSuccessor) return toTrace(steps, path, traceOptions);
261
- const action = isReducing
262
- ? findTraceSuccessor(states[index], (successor) =>
263
- isSameState(successor.state, lastSuccessor.state),
264
- )?.action
265
- : lastSuccessor.action;
266
- return toTrace([...steps, { state: lastSuccessor.state, action }], path, {
267
- ...traceOptions,
268
- known: 2,
269
- });
270
+ return toTrace([...steps, lastSuccessor], path, { ...traceOptions, known: 2 });
270
271
  };
271
272
  // TLCTrace#printTrace applies the alias to every state but an initial one it prints without a successor.
272
273
  const getStateTrace = (index: number, traceOptions: TraceOptions = {}): Behavior => {
package/src/check.ts CHANGED
@@ -828,7 +828,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
828
828
  }
829
829
  return -2 - position;
830
830
  };
831
- const canonicalizeState = createCanonicalizer();
831
+ // TLC's states keep their own values, and coverage charges the cost model each value carries.
832
+ const canonicalizeState = coverage ? (state: Value[]) => state : createCanonicalizer();
832
833
 
833
834
  const toRecord = search.toRecord;
834
835
  const getUncoveredInitialStates = () =>
package/src/coverage.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ getFunctionConstruction,
2
3
  isLocallyResolved,
3
4
  type Bound,
4
5
  type Definition,
@@ -7,6 +8,7 @@ import {
7
8
  type SourceRange,
8
9
  } from "./ast";
9
10
  import { formatRange } from "./errors";
11
+ import { SELECTION_NAME } from "./resolve";
10
12
  import type { Environment, Scope } from "./evaluate";
11
13
  import { getJavaHashCode } from "./java-hash";
12
14
  import { getTlcFingerprint } from "./tlc/fingerprint";
@@ -92,6 +94,8 @@ interface Resolved {
92
94
  scope: Local | undefined;
93
95
  }
94
96
 
97
+ export const letDefinitions = new WeakMap<Scope, Definition>();
98
+
95
99
  const STANDARD_MODULES = new Set([
96
100
  "FiniteSets",
97
101
  "Sequences",
@@ -176,6 +180,10 @@ const findCoverageRelation = (coverage: Coverage, kind: CoverageKind, expression
176
180
  (relation) => relation.kind === kind && relation.expression === expression,
177
181
  )?.node;
178
182
 
183
+ const getRelationRange = (expression: Expression) =>
184
+ expression.location.range ??
185
+ (expression.kind === "Let" ? expression.body.location.range : undefined);
186
+
179
187
  export const addCoverageRelation = (
180
188
  coverage: Coverage,
181
189
  kind: CoverageKind,
@@ -185,7 +193,7 @@ export const addCoverageRelation = (
185
193
  ) => {
186
194
  const shared = kind === "next" ? findCoverageRelation(coverage, kind, expression) : undefined;
187
195
  if (shared !== undefined) return shared;
188
- const node = addNode(coverage, undefined, expression.location.range, -1, false);
196
+ const node = addNode(coverage, undefined, getRelationRange(expression), -1, false);
189
197
  coverage.relations.push({ kind, label, expression, scope, node });
190
198
  return node;
191
199
  };
@@ -206,9 +214,9 @@ export const getCoverageLabel = (
206
214
  ) => {
207
215
  const definition = name === undefined ? undefined : environment.definitions.get(name);
208
216
  const head = definition?.kind === "Operator" ? definition.head : undefined;
209
- const range = expression.location.range;
217
+ const range = getRelationRange(expression);
210
218
  if (!definition || !head) return `Action ${range ? formatRange(range) : "Unknown location"}`;
211
- if (isSameRange(definition.body.location.range, range) || !range) {
219
+ if (isSameRange(getRelationRange(definition.body), range) || !range) {
212
220
  return `${definition.name} ${formatRange(head)}`;
213
221
  }
214
222
  return `${definition.name} ${formatRange(head)} (${range.start.line} ${range.start.column} ${range.end.line} ${range.end.column})`;
@@ -255,6 +263,15 @@ const bindNames = (names: string[], locals: Local | undefined) =>
255
263
  locals,
256
264
  );
257
265
 
266
+ const bindLocalDefinitions = (definitions: Definition[], locals: Local | undefined) => {
267
+ const inner = definitions.reduce<Local | undefined>(
268
+ (parent, definition) => ({ name: definition.name, definition, scope: undefined, parent }),
269
+ locals,
270
+ );
271
+ for (let local = inner; local !== locals && local; local = local.parent) local.scope = inner;
272
+ return inner;
273
+ };
274
+
258
275
  const getBoundNames = (bounds: Bound[]) =>
259
276
  bounds.flatMap((bound) =>
260
277
  bound.pattern.kind === "Name" ? [bound.pattern.name] : bound.pattern.names,
@@ -324,10 +341,13 @@ export const buildCoverage = (
324
341
  definition.kind === "Function"
325
342
  ? getBoundNames(definition.bounds)
326
343
  : definition.params.map((param) => param.name);
327
- walk(definition.body, bindNames(names, resolved.scope));
328
344
  if (definition.kind === "Function") {
329
- getBoundSets(definition.bounds).forEach((set) => walk(set, resolved.scope));
330
- }
345
+ const isLet = resolved.scope !== undefined;
346
+ enter(getFunctionConstruction(definition, isLet), definition.location.range, () => {
347
+ walk(definition.body, bindNames(names, resolved.scope));
348
+ getBoundSets(definition.bounds).forEach((set) => walk(set, resolved.scope));
349
+ });
350
+ } else walk(definition.body, bindNames(names, resolved.scope));
331
351
  walking.pop();
332
352
  };
333
353
 
@@ -403,22 +423,17 @@ export const buildCoverage = (
403
423
  walk(expression.body, bindNames(expression.params, locals));
404
424
  return;
405
425
  case "Selection":
406
- walk(expression.expression, locals);
426
+ if (range === undefined) walk(expression.expression, locals);
427
+ else enter(expression, range, () => walk(expression.expression, locals));
407
428
  return;
408
429
  case "Let": {
409
- const inner = expression.definitions.reduce<Local | undefined>(
410
- (parent, definition) => ({ name: definition.name, definition, scope: undefined, parent }),
411
- locals,
412
- );
413
- for (let local = inner; local !== locals && local; local = local.parent) {
414
- local.scope = inner;
415
- }
430
+ const inner = bindLocalDefinitions(expression.definitions, locals);
416
431
  expression.definitions.forEach((definition) => {
417
432
  if (definition.kind === "Operator") letBodies.set(definition.body, expression.body);
418
433
  });
419
- getHashtableOrder(expression.definitions).forEach((definition) =>
420
- walkDefinition({ definition, scope: inner }),
421
- );
434
+ getHashtableOrder(expression.definitions).forEach((definition) => {
435
+ if (definition.name !== SELECTION_NAME) walkDefinition({ definition, scope: inner });
436
+ });
422
437
  walk(expression.body, inner);
423
438
  return;
424
439
  }
@@ -576,9 +591,18 @@ export const buildCoverage = (
576
591
  }
577
592
  };
578
593
 
594
+ const getScopeLocals = (scope: Scope | undefined) => {
595
+ const scoped: Definition[] = [];
596
+ for (let node = scope; node; node = node.parent) {
597
+ const definition = letDefinitions.get(node);
598
+ if (definition) scoped.unshift(definition);
599
+ }
600
+ return bindLocalDefinitions(scoped, undefined);
601
+ };
602
+
579
603
  coverage.relations.forEach((relation) => {
580
604
  stack.push(relation.node);
581
- walk(relation.expression, undefined);
605
+ walk(relation.expression, getScopeLocals(relation.scope));
582
606
  stack.pop();
583
607
  });
584
608
  };
@@ -747,6 +771,30 @@ export const tagSubset = (coverage: Coverage, set: Value, subset: Value) => {
747
771
  if (node !== undefined && typeof subset === "object") coverage.values.set(subset, node);
748
772
  };
749
773
 
774
+ const RANDOMLY_INDEXED_KINDS = new Set<string>([
775
+ "Set",
776
+ "MixedSet",
777
+ "Interval",
778
+ "FunctionSet",
779
+ "RecordSet",
780
+ "ProductSet",
781
+ ]);
782
+
783
+ // TLC's EnumerableValue#elements(Ordering.RANDOMIZED) draws indices, but a value class without its own k-out-of-n enumerator draws the whole set first, and SubsetValue converts itself to a SetEnumValue.
784
+ export const chargeRandomOrder = (coverage: Coverage, set: Value, size: number, order: Value[]) => {
785
+ if (typeof set !== "object" || RANDOMLY_INDEXED_KINDS.has(set.kind)) return;
786
+ if (set.kind !== "Subset") {
787
+ const enumerator = createEnumerator(coverage, set, size, false);
788
+ for (let position = 0; position <= size; position++) enumerator.next();
789
+ return;
790
+ }
791
+ const node = coverage.values.get(set);
792
+ if (node !== undefined) coverage.secondary[node] += size;
793
+ for (let position = 0; position < order.length; position++) {
794
+ tagSubset(coverage, set, order[position]);
795
+ }
796
+ };
797
+
750
798
  export const createChargedEnumerator = (
751
799
  coverage: Coverage,
752
800
  set: Value,
@@ -6,6 +6,7 @@ import {
6
6
  type Declaration,
7
7
  type Definition,
8
8
  type Expression,
9
+ type FunctionDefinition,
9
10
  type Instance,
10
11
  type Module,
11
12
  type OperatorParam,
@@ -44,8 +45,11 @@ import {
44
45
  createLocalArguments,
45
46
  createLocalIdentifier,
46
47
  getEnabledVariableName,
48
+ getFunctionBody,
47
49
  renameLocals,
50
+ withInstanceParams,
48
51
  withLetInstances,
52
+ withSubstitutionFrames,
49
53
  } from "./instances";
50
54
  import { overrideDefinitions, type JavaOverride } from "./java-overrides";
51
55
  import { extractModule } from "./parser";
@@ -203,21 +207,30 @@ const getNodeWord = (kind: SymbolKind) =>
203
207
  const getNodeClass = (kind: SymbolKind) =>
204
208
  kind === "Theorem" ? "ThmOrAssumpDefNode" : getNodeWord(kind);
205
209
 
206
- const createLocalFunction = (definition: Definition, key: string): Definition => ({
210
+ const createLocalFunction = (definition: FunctionDefinition, key: string): Definition => ({
207
211
  kind: "Operator",
208
212
  name: key,
209
213
  params: [],
210
- body: {
211
- kind: "Let",
212
- definitions: [definition],
213
- body: createLocalIdentifier(definition.name, definition.location),
214
- location: definition.location,
215
- },
214
+ body: getFunctionBody(definition),
216
215
  isLocal: true,
217
216
  isRecursive: false,
218
217
  location: definition.location,
219
218
  });
220
219
 
220
+ const getSubstitutionFrame = (instance: Instance): Expression => {
221
+ const range = instance.definitionRange
222
+ ? {
223
+ ...instance.definitionRange,
224
+ start: { line: instance.location.line, column: instance.location.column },
225
+ }
226
+ : instance.instanceRange;
227
+ return {
228
+ kind: "Identifier",
229
+ name: instance.name ?? instance.module,
230
+ location: { ...range.start, range },
231
+ };
232
+ };
233
+
221
234
  const mentionsName = (expression: Expression, names: Set<string>): boolean => {
222
235
  const name = getReferencedName(expression);
223
236
  return (
@@ -526,12 +539,6 @@ export const createEnvironment = (
526
539
  });
527
540
  const params = instance.params.map((param) => ({ ...param, name: `${param.name}${suffix}` }));
528
541
  params.forEach((param) => instanceParams.add(param));
529
- const substitutionRange = instance.definitionRange
530
- ? {
531
- ...instance.definitionRange,
532
- start: { line: instance.location.line, column: instance.location.column },
533
- }
534
- : instance.instanceRange;
535
542
  const instantiation = createInstantiation({
536
543
  params,
537
544
  substitutions: new Map(
@@ -555,13 +562,7 @@ export const createEnvironment = (
555
562
  return key;
556
563
  },
557
564
  createName,
558
- ...(declarations.length > 0 && {
559
- frame: {
560
- kind: "Identifier",
561
- name: instance.name ?? instance.module,
562
- location: { ...substitutionRange.start, range: substitutionRange },
563
- },
564
- }),
565
+ ...(declarations.length > 0 && { frame: getSubstitutionFrame(instance) }),
565
566
  });
566
567
  return getInstanceSymbols(instance, linked.exported, declarations, (key, name) => {
567
568
  const copy =
@@ -763,22 +764,25 @@ export const createEnvironment = (
763
764
  },
764
765
  createName,
765
766
  });
767
+ const frames = declarations.length > 0 ? [getSubstitutionFrame(instance)] : [];
766
768
  const declared = new Set(declarations.map((declaration) => declaration.name));
767
- const aliases = [...linked.exported]
769
+ const exported = [...linked.exported]
768
770
  .filter((entry) => !declared.has(entry[0]) && entry[1].kind !== "Instance")
769
771
  .map((entry) => {
772
+ const name = instance.name === undefined ? entry[0] : `${instance.name}!${entry[0]}`;
770
773
  const key = instantiation.getKey(entry[1].key);
774
+ const copy = copies.find((candidate) => candidate.name === key);
775
+ const original = definitions.get(key);
776
+ const definition = copy ?? (original && withInstanceParams(original, instance.params));
777
+ if (definition) {
778
+ const operator =
779
+ definition.kind === "Operator" ? definition : createLocalFunction(definition, name);
780
+ return { ...operator, name, body: withSubstitutionFrames(operator.body, frames) };
781
+ }
771
782
  const ownParams = createArgumentParams(entry[1].arity, entry[1].params);
772
- const params = [...instance.params, ...ownParams];
773
- return createLocalAlias(
774
- instance.name === undefined ? entry[0] : `${instance.name}!${entry[0]}`,
775
- key,
776
- params,
777
- key === entry[1].key ? ownParams : params,
778
- location,
779
- );
783
+ return createLocalAlias(name, key, [...instance.params, ...ownParams], ownParams, location);
780
784
  });
781
- return [...substitutionDefinitions, ...copies, ...aliases];
785
+ return [...substitutionDefinitions, ...copies, ...exported];
782
786
  };
783
787
 
784
788
  const getAvailableDefinitions = (visible: Symbols) =>
package/src/evaluate.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  getChildren,
3
+ getFunctionConstruction,
3
4
  getReferencedName,
4
5
  isLocallyResolved,
5
6
  type Bound,
@@ -761,28 +762,29 @@ const getBoundTupleLengths = (bounds: Bound[]) =>
761
762
  bound.pattern.kind === "Tuple" ? bound.pattern.names.length : undefined,
762
763
  );
763
764
 
764
- const getDefinitionSource = (definition: FunctionDefinition): Expression => ({
765
- kind: "FunctionConstruction",
766
- bounds: definition.bounds,
767
- body: definition.body,
768
- location: definition.location,
769
- });
770
-
771
765
  const createRecursiveFunction = (
772
766
  definition: FunctionDefinition,
773
767
  context: Context,
774
768
  ): RebindableLazyFunction => {
775
769
  const domain = getBoundsDomain(definition.bounds, context);
770
+ const compute = (argument: Value, self: Value) =>
771
+ evaluate(
772
+ definition.body,
773
+ withScope(
774
+ context,
775
+ bindArgument(definition.bounds, bindValue(undefined, definition.name, self), argument),
776
+ ),
777
+ );
778
+ const coverage = context.environment.coverage;
779
+ const node = coverage && !context.environment.callStack ? coverage.current : -1;
776
780
  const functionValue = createLazyFunction(
777
781
  domain,
778
- (argument, self) =>
779
- evaluate(
780
- definition.body,
781
- withScope(
782
- context,
783
- bindArgument(definition.bounds, bindValue(undefined, definition.name, self), argument),
784
- ),
785
- ),
782
+ coverage
783
+ ? (argument, self) =>
784
+ coverage.current === -1
785
+ ? compute(argument, self)
786
+ : runAtCoverageNode(coverage, node, () => compute(argument, self))
787
+ : compute,
786
788
  getLazyFunctionSource(
787
789
  getLazyFunctionTemplate(definition.bounds, definition.body),
788
790
  definition.bounds,
@@ -834,9 +836,11 @@ const compileDefinitionBody = (definition: Definition, environment: Environment)
834
836
  };
835
837
  }
836
838
  if (definition.kind !== "Function") return getEntryEvaluator(definition.body, environment);
837
- if (definition.isSelfReferential)
838
- return (context) => createRecursiveFunction(definition, context);
839
- return getEntryEvaluator(getDefinitionSource(definition), environment);
839
+ const construction = getFunctionConstruction(definition, false);
840
+ if (!definition.isSelfReferential) return getEntryEvaluator(construction, environment);
841
+ const evaluator: Evaluator = (context) => createRecursiveFunction(definition, context);
842
+ const coverage = environment.coverage;
843
+ return coverage ? countEvaluator(construction, evaluator, coverage) : evaluator;
840
844
  };
841
845
 
842
846
  const CALLER_SCOPE: Scope = {
@@ -1143,20 +1147,29 @@ interface ReevaluatedDefinitions {
1143
1147
  streamed: ReadonlySet<Definition>;
1144
1148
  }
1145
1149
 
1146
- const letFunctionConstructions = new WeakMap<FunctionDefinition, Expression>();
1150
+ const isRecursiveOperator = (definition: Definition) =>
1151
+ definition.kind === "Operator" && definition.isRecursive && definition.params.length > 0;
1147
1152
 
1148
- const getLetFunctionConstruction = (definition: FunctionDefinition): Expression => {
1149
- const known = letFunctionConstructions.get(definition);
1150
- if (known) return known;
1151
- const construction: Expression = {
1152
- kind: "FunctionConstruction",
1153
- bounds: definition.bounds,
1154
- body: definition.body,
1155
- location: definition.location,
1156
- isRecursive: true,
1157
- };
1158
- letFunctionConstructions.set(definition, construction);
1159
- return construction;
1153
+ // TLC finds a RECURSIVE operator with parameters by its definition, not in its context, so every definition reaches it.
1154
+ const chainRecursiveOperatorsFirst = (
1155
+ definitions: Definition[],
1156
+ nodes: Scope[],
1157
+ outer: Scope | undefined,
1158
+ ) => {
1159
+ let scope = outer;
1160
+ for (let index = 0; index < definitions.length; index++) {
1161
+ if (isRecursiveOperator(definitions[index])) {
1162
+ nodes[index].parent = scope;
1163
+ scope = nodes[index];
1164
+ }
1165
+ }
1166
+ for (let index = 0; index < definitions.length; index++) {
1167
+ if (!isRecursiveOperator(definitions[index])) {
1168
+ nodes[index].parent = scope;
1169
+ scope = nodes[index];
1170
+ }
1171
+ }
1172
+ return scope;
1160
1173
  };
1161
1174
 
1162
1175
  export const bindDefinitions = (
@@ -1169,24 +1182,29 @@ export const bindDefinitions = (
1169
1182
  binding: { kind: "Value", value: false },
1170
1183
  parent: undefined,
1171
1184
  }));
1172
- const scope = nodes.reduce<Scope | undefined>((parent, node) => {
1173
- node.parent = parent;
1174
- return node;
1175
- }, context.scope);
1176
- let isRecursiveAtOrAfter = false;
1185
+ let scope = context.scope;
1186
+ let hasRecursive = false;
1187
+ for (let index = 0; index < nodes.length; index++) {
1188
+ nodes[index].parent = scope;
1189
+ scope = nodes[index];
1190
+ hasRecursive ||= definitions[index].isRecursive;
1191
+ }
1192
+ if (hasRecursive) scope = chainRecursiveOperatorsFirst(definitions, nodes, context.scope);
1193
+ let isRecursiveValueAtOrAfter = false;
1177
1194
  for (let index = definitions.length - 1; index >= 0; index--) {
1178
1195
  const definition = definitions[index];
1179
- isRecursiveAtOrAfter ||= definition.isRecursive;
1196
+ isRecursiveValueAtOrAfter ||=
1197
+ definition.isRecursive && definition.kind === "Operator" && definition.params.length === 0;
1180
1198
  // TLC's LET evaluates an operator without parameters in the context before it, which TLCEval#tlcEval tells from an empty one.
1181
1199
  const ownScope =
1182
- definition.kind === "Operator" && definition.params.length === 0 && !isRecursiveAtOrAfter
1200
+ definition.kind === "Operator" && definition.params.length === 0 && !isRecursiveValueAtOrAfter
1183
1201
  ? nodes[index].parent
1184
1202
  : scope;
1185
1203
  nodes[index].binding =
1186
1204
  definition.kind === "Function"
1187
1205
  ? {
1188
1206
  kind: "Thunk",
1189
- expression: getLetFunctionConstruction(definition),
1207
+ expression: getFunctionConstruction(definition, true),
1190
1208
  scope,
1191
1209
  state: context.state,
1192
1210
  next: context.next,