tla-ts 0.0.10-dev.28c823e4b → 0.0.10-dev.b4a856304

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 (68) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.d.cts +0 -34
  3. package/dist/index.d.ts +0 -34
  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 +43 -43
  8. package/dist/prove.js +47 -47
  9. package/dist/run.cjs +30 -30
  10. package/dist/run.js +33 -33
  11. package/dist/transfer.cjs +38 -38
  12. package/dist/transfer.js +39 -39
  13. package/package.json +1 -1
  14. package/src/ast.ts +5 -0
  15. package/src/bags.ts +5 -2
  16. package/src/builtins.ts +8 -1
  17. package/src/check.ts +193 -128
  18. package/src/cli/run.ts +2 -0
  19. package/src/cli/runtime-invariants.ts +7 -8
  20. package/src/cli/shared.ts +4 -0
  21. package/src/cli/tlc-arguments.ts +30 -24
  22. package/src/cli/tlc-usage.ts +3 -2
  23. package/src/evaluate.ts +102 -26
  24. package/src/java-overrides.ts +9 -4
  25. package/src/json-reader.ts +2 -1
  26. package/src/json.ts +11 -4
  27. package/src/levels.ts +15 -7
  28. package/src/lexer.ts +83 -72
  29. package/src/liveness-checker.ts +106 -77
  30. package/src/liveness.ts +34 -10
  31. package/src/parallel.ts +33 -26
  32. package/src/parser.ts +226 -163
  33. package/src/pcal/ast.ts +65 -53
  34. package/src/pcal/parse.ts +191 -144
  35. package/src/pcal/tokenize.ts +115 -91
  36. package/src/pcal/translate.ts +98 -83
  37. package/src/pcal/validate.ts +50 -48
  38. package/src/pretty-print.ts +6 -6
  39. package/src/randomization.ts +4 -1
  40. package/src/resolve.ts +70 -12
  41. package/src/runtime.ts +18 -11
  42. package/src/sany/builtins.ts +3 -1
  43. package/src/sany/generator.ts +127 -74
  44. package/src/sany/levels.ts +9 -5
  45. package/src/sany/lexer.ts +44 -40
  46. package/src/sany/linter.ts +1 -0
  47. package/src/search.ts +1 -1
  48. package/src/simulate.ts +59 -50
  49. package/src/spec-description.ts +34 -23
  50. package/src/standard-definitions.ts +3 -0
  51. package/src/standard-modules.ts +12 -1
  52. package/src/state-graph.ts +8 -1
  53. package/src/subexpressions.ts +47 -38
  54. package/src/successors.ts +35 -14
  55. package/src/symmetry.ts +19 -4
  56. package/src/tlc/fingerprint.ts +21 -15
  57. package/src/tlc/jar-data.ts +1 -0
  58. package/src/tlc/messages.ts +21 -2
  59. package/src/tlc/order.ts +38 -20
  60. package/src/tlc/random.ts +30 -18
  61. package/src/tlc/replay.ts +33 -13
  62. package/src/tlc/summary.ts +45 -36
  63. package/src/tlc/tlc-operators.ts +14 -4
  64. package/src/tlc/tlcext-operators.ts +15 -11
  65. package/src/tlc/trace-spec.ts +4 -0
  66. package/src/tlc/value-stream.ts +13 -9
  67. package/src/tlc/version.ts +1 -0
  68. package/src/values.ts +181 -74
@@ -165,21 +165,6 @@ const getThunk = (expression: Expression, scope: Scope | undefined) => {
165
165
  return binding?.kind === "Thunk" ? binding : undefined;
166
166
  };
167
167
 
168
- const unwrapBinding = (
169
- expression: Expression,
170
- scope: Scope | undefined,
171
- environment: Environment,
172
- ) => {
173
- if (expression.kind === "Let") {
174
- return {
175
- expression: expression.body,
176
- scope: bindDefinitions(expression.definitions, getConstantContext(environment, scope)),
177
- };
178
- }
179
- const thunk = getThunk(expression, scope);
180
- return thunk && { expression: thunk.expression, scope: thunk.scope };
181
- };
182
-
183
168
  const getParameters = (closure: Closure | undefined, scope: Scope | undefined) =>
184
169
  (closure?.params ?? []).flatMap((param): [string, Value][] => {
185
170
  const binding = lookupScope(scope, param.name);
@@ -206,6 +191,7 @@ const getInstanceActions = (
206
191
  const callAction = (): SpecAction[] => [
207
192
  { name: instanceAction.name, location: expression.location, parameters: [], expression, scope },
208
193
  ];
194
+ // TLC's action is the SubstInNode the instance puts around the operator's body.
209
195
  if (called && args.length === 0) {
210
196
  return [{ ...instanceAction, parameters: [], expression: called.body, scope: called.scope }];
211
197
  }
@@ -293,6 +279,7 @@ const getActions = (
293
279
  return getInstanceActions(instanceAction, expression, scope, called, environment);
294
280
  if (!called) return [createSplitAction()];
295
281
  const args = getArguments(expression);
282
+ // TLC names an action after the operator it applies, as SANY names it in the spec.
296
283
  const calledName = isLocallyResolved(expression)
297
284
  ? called.name
298
285
  : (environment.instanceNames.get(getOperatorName(expression) ?? "") ?? called.name);
@@ -335,11 +322,19 @@ const describeSpecification = (
335
322
  ): void => {
336
323
  const recurse = (inner: Expression, innerScope: Scope | undefined, innerFrames = frames) =>
337
324
  describeSpecification(inner, innerScope, environment, description, next, innerFrames);
325
+ // TLC wraps each conjunct it takes from an instance in the instance's SubstInNode.
338
326
  const createConjunct = (name: string, conjunct: Expression, conjunctScope: Scope | undefined) =>
339
327
  createAction(name, withSubstitutionFrames(conjunct, frames), conjunctScope);
340
- const unwrapped = unwrapBinding(expression, scope, environment);
341
- if (unwrapped) {
342
- recurse(unwrapped.expression, unwrapped.scope);
328
+ if (expression.kind === "Let") {
329
+ recurse(
330
+ expression.body,
331
+ bindDefinitions(expression.definitions, getConstantContext(environment, scope)),
332
+ );
333
+ return;
334
+ }
335
+ const thunk = getThunk(expression, scope);
336
+ if (thunk) {
337
+ recurse(thunk.expression, thunk.scope);
343
338
  return;
344
339
  }
345
340
  const called = resolveClosure(expression, scope, environment);
@@ -392,9 +387,16 @@ const describeProperty = (
392
387
  ): void => {
393
388
  const recurse = (inner: Expression, innerScope: Scope | undefined) =>
394
389
  describeProperty(configName, inner, innerScope, environment, description);
395
- const unwrapped = unwrapBinding(expression, scope, environment);
396
- if (unwrapped) {
397
- recurse(unwrapped.expression, unwrapped.scope);
390
+ if (expression.kind === "Let") {
391
+ recurse(
392
+ expression.body,
393
+ bindDefinitions(expression.definitions, getConstantContext(environment, scope)),
394
+ );
395
+ return;
396
+ }
397
+ const thunk = getThunk(expression, scope);
398
+ if (thunk) {
399
+ recurse(thunk.expression, thunk.scope);
398
400
  return;
399
401
  }
400
402
  const called = resolveClosure(expression, scope, environment);
@@ -474,6 +476,7 @@ const getSpecDescription = (
474
476
  describeSpecification(specification.body, undefined, environment, description, next);
475
477
  next.forEach((item) =>
476
478
  description.actions.push(
479
+ // TLC takes an instance's SubstInNode as one action, located at the instance.
477
480
  ...(item.frames.length > 0
478
481
  ? [
479
482
  {
@@ -525,8 +528,14 @@ export const getSubscriptVariables = (
525
528
  return expression.elements.every((element) => collect(element, innerScope));
526
529
  }
527
530
  if (expression.kind === "Label") return collect(expression.body, innerScope);
528
- const unwrapped = unwrapBinding(expression, innerScope, environment);
529
- if (unwrapped) return collect(unwrapped.expression, unwrapped.scope);
531
+ if (expression.kind === "Let") {
532
+ return collect(
533
+ expression.body,
534
+ bindDefinitions(expression.definitions, getConstantContext(environment, innerScope)),
535
+ );
536
+ }
537
+ const thunk = getThunk(expression, innerScope);
538
+ if (thunk) return collect(thunk.expression, thunk.scope);
530
539
  const argument =
531
540
  expression.kind === "Identifier" && isLocallyResolved(expression)
532
541
  ? lookupScope(innerScope, expression.name)
@@ -590,6 +599,8 @@ export const getSpecificationValue = (
590
599
  instanceActions: Map<string, InstanceAction>,
591
600
  ): Value => {
592
601
  const description = getSpecDescription(config, environment, instanceActions);
602
+ // Describing a checked formula evaluates the constant definitions it names, so only
603
+ // TLCGet("spec") describes them, not the actions TLC splits at startup.
593
604
  config.invariants.forEach((name) => {
594
605
  const definition = getOperatorDefinition(name, environment);
595
606
  if (definition) description.invariants.push(createAction(name, definition.body));
@@ -1,6 +1,9 @@
1
1
  import type { SourceRange } from "./ast";
2
2
  import type { OperatorLevels } from "./levels";
3
3
 
4
+ // SANY's view of the dummy definitions in tla2sany/StandardModules of the operators tla-ts
5
+ // implements natively: their levels, and where SANY reports a spec that defines one again.
6
+
4
7
  type Signature =
5
8
  | [string, number, number[], number[], number[]]
6
9
  | [string, number, number[], number[], number[], number[][], string[]];
@@ -87,6 +87,7 @@ const isSubsetOf = (left: Value[], right: Value) =>
87
87
  const BOOLEAN_SET = createSet([false, true]);
88
88
  markNormalized(BOOLEAN_SET);
89
89
 
90
+ // A balanced merge compares each element about log2 of the set count times.
90
91
  const getBalancedUnion = (sets: SetValue[], start: number, end: number): SetValue => {
91
92
  if (end - start === 1) return sets[start];
92
93
  const middle = (start + end) >> 1;
@@ -99,9 +100,11 @@ type ReducibleSet = SetValue | MixedSetValue | IntervalValue;
99
100
 
100
101
  const isMixedSet = (value: Value) => typeof value === "object" && value.kind === "MixedSet";
101
102
 
103
+ // These keep the intersection and difference they compute normalized.
102
104
  const isNormalizedReducible = (set: ReducibleSet) =>
103
105
  set.kind === "Interval" || (set.kind === "Set" && set.isNormalized);
104
106
 
107
+ // TLC combines a set enumeration or an interval with a set by testing each element's membership.
105
108
  const combineReducible = (
106
109
  operator: SetOperationValue["operator"],
107
110
  set: ReducibleSet,
@@ -162,6 +165,7 @@ export const CORE_OPERATORS: Builtin[] = [
162
165
  2,
163
166
  (args) => !isElementOf(getValue(args, 0, "\\notin"), getValue(args, 1, "\\notin")),
164
167
  ),
168
+ // TLC tests each element of the left set for membership in the right value.
165
169
  defineBinary("\\subseteq", (left, right) => {
166
170
  if (!isSetValue(left)) {
167
171
  throw new TlaEvaluationError(`\\subseteq expects a set but received ${formatValue(left)}`);
@@ -187,6 +191,7 @@ export const CORE_OPERATORS: Builtin[] = [
187
191
  }
188
192
  return !someStreamedElement(left, (element) => !isElementOf(element, right));
189
193
  }),
194
+ // TLC defers set operations on non-sets to enumerating or testing membership in the result.
190
195
  ...SET_OPERATORS.map((operator) =>
191
196
  defineOperator(operator, 2, (args) => {
192
197
  const left = getValue(args, 0, operator);
@@ -213,12 +218,14 @@ export const CORE_OPERATORS: Builtin[] = [
213
218
  : operator === "\\cap"
214
219
  ? getSortedIntersection
215
220
  : getSortedDifference;
221
+ // The merge compares the elements, which TLC tests for membership one by one instead.
216
222
  return computeLikeTlcOnFailure(
217
223
  (finiteLeft, finiteRight) => {
218
224
  const leftSet = toFiniteSet(finiteLeft);
219
225
  const rightSet = toFiniteSet(finiteRight);
220
226
  const merged = merge(leftSet, rightSet);
221
227
  if (operator === "\\cup") {
228
+ // TLC appends the right set's new elements to the left set's, unsorted.
222
229
  const written = getWrittenElements(leftSet);
223
230
  const added = getSortedDifference(rightSet, leftSet).elements;
224
231
  const isSorted =
@@ -261,6 +268,7 @@ export const CORE_OPERATORS: Builtin[] = [
261
268
  if (!isEnumeratedSet(outer) || sets.length !== written.length) {
262
269
  return markStreamedSet({ kind: "Union", base: outer });
263
270
  }
271
+ // TLC adds each set's elements in written order, and only those not yet in the union.
264
272
  const added = sets.flatMap(getWrittenElements);
265
273
  const getUnionLikeTlc = () => {
266
274
  const union: MixedSetValue = { kind: "MixedSet", elements: [] };
@@ -290,6 +298,7 @@ export const CORE_OPERATORS: Builtin[] = [
290
298
 
291
299
  const NEG_SIGNATURE = getJavaSignature("Integers", "Neg", "IntValue", 1);
292
300
 
301
+ // TLC computes this arithmetic in tlc2.module.Naturals, or Integers if loaded, named in errors.
293
302
  const createArithmeticOperators = (module: string) => {
294
303
  const dotDotSignature = getJavaSignature(module, "DotDot", "IntervalValue", 2);
295
304
  return [
@@ -332,12 +341,14 @@ const NATURALS_ARITHMETIC = createArithmeticOperators("Naturals");
332
341
 
333
342
  const INTEGERS_ARITHMETIC = createArithmeticOperators("Integers");
334
343
 
344
+ // TLC loads Integers for a trace exploration spec, whose methods then replace these.
335
345
  export const getTraceSpecArithmetic = (builtin: Builtin) => {
336
346
  const index = NATURALS_ARITHMETIC.indexOf(builtin);
337
347
  return index === -1 ? undefined : INTEGERS_ARITHMETIC[index];
338
348
  };
339
349
 
340
- // Naturals#GEQ names itself > in its errors, and Integers#GT returns a BoolValue.
350
+ // Naturals#GEQ names itself > in its errors, and Integers#GT returns a BoolValue. Only a
351
+ // spec that extends Integers gets Integers' comparisons.
341
352
  const createComparisonOperators = (module: string) => {
342
353
  const getSignature = (method: string, result = "tlc2.value.IBoolValue") =>
343
354
  `public static ${result} tlc2.module.${module}.${method}(tlc2.value.impl.Value,tlc2.value.impl.Value)`;
@@ -52,6 +52,8 @@ const INITIAL_CAPACITY = 16;
52
52
  const getCapacity = (size: number, capacity = INITIAL_CAPACITY): number =>
53
53
  size <= capacity * LOAD_FACTOR ? capacity : getCapacity(size, capacity * 2);
54
54
 
55
+ // The order in which a java.util.HashMap iterates over keys put in this order: by bucket, and in
56
+ // insertion order within a bucket. A bucket only becomes a tree once 8 keys collide in it.
55
57
  const getJavaHashOrder = <Key>(keys: Key[], getHash: (key: Key) => number) => {
56
58
  const mask = getCapacity(keys.length) - 1;
57
59
  const getBucket = (key: Key) => {
@@ -88,11 +90,14 @@ const createPlainWriter = (dump: StateDump, writeFile: WriteFile): StateWriter =
88
90
  if (!isSeen) writeState(successor);
89
91
  },
90
92
  writeConstrained: () => {},
93
+ // TLC 1.7.4 writes the state again, as it takes the stuttering step for one to a new state.
91
94
  writeStuttering: writeState,
92
95
  close: () => writeFile?.(dump.path, states.join("")),
93
96
  };
94
97
  };
95
98
 
99
+ // TLC 1.7.4 draws its nodes as ellipses, gives them no tooltip, and labels an edge with the name
100
+ // of its action alone.
96
101
  const createDotWriter = (
97
102
  dump: StateDump,
98
103
  writeFile: WriteFile,
@@ -109,7 +114,8 @@ const createDotWriter = (
109
114
  ];
110
115
  const ranks = new Map<number, Set<bigint>>();
111
116
  const colors = new Map<string, number>();
112
- // Deviation from TLC: it keys an edge by the XOR of its fingerprints, which merges distinct edges.
117
+ // TLC's DotStateWriter keys an edge by the XOR of its fingerprints, which merges every
118
+ // stuttering step and an edge with its reverse, so tla-ts keys it by both.
113
119
  const edges = new Set<string>();
114
120
  const isDuplicate = (state: GraphState, successor: GraphState) => {
115
121
  if (!dump.strict) return false;
@@ -122,6 +128,7 @@ const createDotWriter = (
122
128
  const rank = ranks.get(state.level) ?? new Set();
123
129
  ranks.set(state.level, rank.add(state.fingerprint));
124
130
  };
131
+ // TLC colors an edge by the name of its action, numbering the names from 2 as it finds them.
125
132
  const getColor = (action: GraphAction | undefined) => {
126
133
  if (!action) return 1;
127
134
  const color = colors.get(action.name) ?? colors.size + 2;
@@ -149,6 +149,9 @@ const applyDefinition = (definition: Definition, selection: Selection) => {
149
149
  return createApplication({ ...selection, params: [...selection.params, ...params] }, reference);
150
150
  };
151
151
 
152
+ // Generator.selectorToNode reports the first part of a name that selects nothing, after it analyzes
153
+ // the arguments of the parts before, and goes on after the name. An operator or a label must be given
154
+ // all its arguments, except in a name that an operator argument may select whole.
152
155
  const selectSubexpression = (
153
156
  selectors: Selector[],
154
157
  lookup: Lookup,
@@ -157,27 +160,25 @@ const selectSubexpression = (
157
160
  ): Expression => {
158
161
  const location = reference.location;
159
162
  const selection: Selection = { params: [], args: [], lets: [], location };
160
- let selectorIndex = 0;
161
- let current = undefined as Expression | undefined;
162
- let isFailed = false;
163
+ const state = { index: 0, current: undefined as Expression | undefined, isFailed: false };
163
164
 
164
165
  const report = (range: SourceRange | undefined, message: string) => {
165
166
  if (!range) throw createError(message, location);
166
167
  selectionErrors.set(reference, {
167
168
  args: selectors
168
- .slice(0, selectorIndex)
169
+ .slice(0, state.index)
169
170
  .flatMap((selector) => ("args" in selector ? selector.args : [])),
170
171
  error: { location: formatRange(range), message },
171
172
  });
172
- isFailed = true;
173
+ state.isFailed = true;
173
174
  return undefined;
174
175
  };
175
176
 
176
177
  const findDefinition = (local: Definition[] | undefined) => {
177
178
  const names: string[] = [];
178
179
  const args: Expression[] = [];
179
- while (selectorIndex < selectors.length) {
180
- const selector = selectors[selectorIndex];
180
+ while (state.index < selectors.length) {
181
+ const selector = selectors[state.index];
181
182
  if (selector.kind !== "Name") throw createError("Expected an operator name", location);
182
183
  names.push(selector.name);
183
184
  args.push(...selector.args);
@@ -187,7 +188,7 @@ const selectSubexpression = (
187
188
  : lookup(name);
188
189
  if (definition)
189
190
  return { definition, name, args, earlier: args.length - selector.args.length };
190
- selectorIndex++;
191
+ state.index++;
191
192
  }
192
193
  throw createError(`Unknown operator ${names.join("!")}`, location);
193
194
  };
@@ -196,10 +197,10 @@ const selectSubexpression = (
196
197
  const found = findDefinition(local);
197
198
  const definition = found.definition;
198
199
  const arity = getArity(definition);
199
- const isLast = selectorIndex === selectors.length - 1;
200
+ const isLast = state.index === selectors.length - 1;
200
201
  if (found.args.length !== arity && (!isOperator || found.args.length !== 0)) {
201
202
  return report(
202
- reference.argumentRanges?.[selectorIndex] ?? location.range,
203
+ reference.argumentRanges?.[state.index] ?? location.range,
203
204
  `The operator ${found.name} requires ${arity - found.earlier} arguments.`,
204
205
  );
205
206
  }
@@ -209,17 +210,17 @@ const selectSubexpression = (
209
210
  }
210
211
  selection.params.push(...definition.params);
211
212
  selection.args.push(...found.args);
212
- current = definition.body;
213
- selectorIndex++;
213
+ state.current = definition.body;
214
+ state.index++;
214
215
  return undefined;
215
216
  };
216
217
 
217
218
  const followLabels = () => {
218
- while (selectorIndex < selectors.length && !isFailed) {
219
- const selector = selectors[selectorIndex];
219
+ while (state.index < selectors.length && !state.isFailed) {
220
+ const selector = selectors[state.index];
220
221
  if (selector.kind !== "Name") return;
221
- const range = reference.selectorRanges?.[selectorIndex];
222
- const found = current && findLabel(current, selector.name, []);
222
+ const range = reference.selectorRanges?.[state.index];
223
+ const found = state.current && findLabel(state.current, selector.name, []);
223
224
  if (!found) return report(range, `Cannot find label \`${selector.name}'.`);
224
225
  const params = found.label.params;
225
226
  if (!isOperator && selector.args.length !== params.length) {
@@ -228,16 +229,17 @@ const selectSubexpression = (
228
229
  selection.lets.push(...found.lets);
229
230
  selection.params.push(...params.map((name) => ({ name, arity: 0 })));
230
231
  selection.args.push(...selector.args);
231
- current = found.label.body;
232
- selectorIndex++;
232
+ state.current = found.label.body;
233
+ state.index++;
233
234
  }
234
235
  };
235
236
 
236
237
  const selectOperand = (selector: Selector) => {
238
+ const current = state.current;
237
239
  if (!current) throw createError("Subexpression selection failed", location);
238
240
  if (selector.kind === "Colon") return;
239
241
  if (current.kind === "Label") {
240
- current = current.body;
242
+ state.current = current.body;
241
243
  selectOperand(selector);
242
244
  return;
243
245
  }
@@ -246,14 +248,14 @@ const selectSubexpression = (
246
248
  throw createError("A LET/IN expression has only one operand", location);
247
249
  }
248
250
  selection.lets.push(current.definitions);
249
- current = current.body;
251
+ state.current = current.body;
250
252
  return;
251
253
  }
252
254
  const binder = getBinder(current);
253
255
  if (binder && (selector.kind === "Bound" || selector.kind === "At")) {
254
256
  selection.params.push(...binder.names.map((name) => ({ name, arity: 0 })));
255
257
  if (selector.kind === "Bound") selection.args.push(...selector.args);
256
- current = binder.body;
258
+ state.current = binder.body;
257
259
  return;
258
260
  }
259
261
  if (current.kind === "Case" && selector.kind === "Operand") {
@@ -262,15 +264,15 @@ const selectSubexpression = (
262
264
  ...(current.other ? [{ condition: undefined, body: current.other }] : []),
263
265
  ];
264
266
  const arm = arms[getOperandIndex(selector.operand, arms.length)];
265
- const next = selectors[selectorIndex + 1];
267
+ const next = selectors[state.index + 1];
266
268
  if (!arm || next?.kind !== "Operand") {
267
269
  throw createError("A subexpression of CASE must have the form !i!j", location);
268
270
  }
269
- selectorIndex++;
271
+ state.index++;
270
272
  const part = getOperandIndex(next.operand, 2);
271
273
  const chosen = part === 0 ? arm.condition : part === 1 ? arm.body : undefined;
272
274
  if (!chosen) throw createError("Nonexistent CASE operand", location);
273
- current = chosen;
275
+ state.current = chosen;
274
276
  return;
275
277
  }
276
278
  if (selector.kind !== "Operand")
@@ -278,23 +280,23 @@ const selectSubexpression = (
278
280
  const operands = binder ? binder.sets : getOperands(current);
279
281
  const operand = operands?.[getOperandIndex(selector.operand, operands.length)];
280
282
  if (!operand) throw createError("Nonexistent operand specified by the selector", location);
281
- current = operand;
283
+ state.current = operand;
282
284
  };
283
285
 
284
286
  const first = enterDefinition(undefined);
285
- if (isFailed) return reference;
287
+ if (state.isFailed) return reference;
286
288
  if (first) return applyDefinition(first.definition, { ...selection, args: first.args });
287
289
  followLabels();
288
- while (selectorIndex < selectors.length && !isFailed) {
289
- const selector = selectors[selectorIndex];
290
+ while (state.index < selectors.length && !state.isFailed) {
291
+ const selector = selectors[state.index];
290
292
  if (selector.kind === "Name") {
291
- while (current?.kind === "Label") current = current.body;
292
- if (current?.kind !== "Let") {
293
+ while (state.current?.kind === "Label") state.current = state.current.body;
294
+ if (state.current?.kind !== "Let") {
293
295
  throw createError("A name selector here must be from a LET clause", location);
294
296
  }
295
- selection.lets.push(current.definitions);
296
- const last = enterDefinition(current.definitions);
297
- if (isFailed) return reference;
297
+ selection.lets.push(state.current.definitions);
298
+ const last = enterDefinition(state.current.definitions);
299
+ if (state.isFailed) return reference;
298
300
  if (last) {
299
301
  return applyDefinition(last.definition, {
300
302
  ...selection,
@@ -305,11 +307,11 @@ const selectSubexpression = (
305
307
  continue;
306
308
  }
307
309
  selectOperand(selector);
308
- selectorIndex++;
310
+ state.index++;
309
311
  }
310
- if (isFailed) return reference;
311
- if (!current) throw createError("Subexpression selection failed", location);
312
- return createApplication(selection, current);
312
+ if (state.isFailed) return reference;
313
+ if (!state.current) throw createError("Subexpression selection failed", location);
314
+ return createApplication(selection, state.current);
313
315
  };
314
316
 
315
317
  const getQualifiedSelectors = (
@@ -320,7 +322,7 @@ const getQualifiedSelectors = (
320
322
  ) => {
321
323
  if (!name.includes("!") || lookup(name)) return undefined;
322
324
  const parts = name.split("!");
323
- if (!parts.some((_part, index) => lookup(parts.slice(0, index + 1).join("!")))) return undefined;
325
+ if (!parts.some((_, index) => lookup(parts.slice(0, index + 1).join("!")))) return undefined;
324
326
  return getNameSelectors(name, args, counts);
325
327
  };
326
328
 
@@ -330,6 +332,9 @@ const containsReference = (expression: Expression): boolean =>
330
332
  (expression.kind === "Apply" && expression.operator.includes("!")) ||
331
333
  getChildren(expression).some(containsReference);
332
334
 
335
+ // A reference that starts with a name isGoal holds for, such as a theorem whose statement is an
336
+ // ASSUME/PROVE, stays for name resolution to check. isOperator holds where an operator may be given,
337
+ // as the argument of an operator that may take one.
333
338
  const resolveSubexpressions = (
334
339
  expression: Expression,
335
340
  lookup: Lookup,
@@ -398,6 +403,7 @@ const createLookup = (definitions: Definition[]): Lookup => {
398
403
  export const resolveInstanceSubexpressions = (instance: Instance, module: Module): Instance =>
399
404
  resolveInstance(instance, createLookup(module.definitions), () => false);
400
405
 
406
+ // Generator.selectorToNode resolves a name in a theorem, a proof, or a fact as it does in a definition.
401
407
  export const resolveModuleSubexpressions = (module: Module, available: Definition[]): Module => {
402
408
  const goals = new Set(
403
409
  module.theorems.flatMap((theorem) =>
@@ -436,6 +442,8 @@ export const resolveModuleSubexpressions = (module: Module, available: Definitio
436
442
  definitionLookup,
437
443
  (name) => isGoal(name) && clauses.every((clause) => clause.name !== name),
438
444
  );
445
+ // A name in a theorem, a proof, or a fact may also start with a step, a theorem, or a symbol that
446
+ // no definition names.
439
447
  const isProofGoal = (name: string) => isGoal(name) || !lookup(name);
440
448
  const resolveInProof = (expression: Expression) =>
441
449
  resolveSubexpressions(expression, lookup, isProofGoal);
@@ -501,6 +509,7 @@ export const resolveModuleSubexpressions = (module: Module, available: Definitio
501
509
  : proof;
502
510
  const resolved = {
503
511
  ...module,
512
+ // A named theorem's statement is resolved as its definition.
504
513
  theorems: module.theorems.map((theorem) => ({
505
514
  ...theorem,
506
515
  statement: