tla-ts 0.0.3-dev.d9ff6f2 → 0.0.3-dev.e5b05b9

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.
@@ -11,7 +11,7 @@ import {
11
11
  getNumber,
12
12
  getOperator,
13
13
  getSet,
14
- getIntegersSignature,
14
+ getArithmeticSignature,
15
15
  getJavaInteger,
16
16
  getValue,
17
17
  isOutOfRange,
@@ -123,7 +123,7 @@ export const CORE_OPERATORS: Builtin[] = [
123
123
  ),
124
124
  defineOperator("\\subseteq", 2, (args) => {
125
125
  const left = getSet(args, 0, "\\subseteq");
126
- const right = getSet(args, 1, "\\subseteq");
126
+ const right = getValue(args, 1, "\\subseteq");
127
127
  const isPowerSets =
128
128
  typeof left === "object" &&
129
129
  left.kind === "Subset" &&
@@ -135,8 +135,8 @@ export const CORE_OPERATORS: Builtin[] = [
135
135
  }),
136
136
  ...SET_OPERATORS.map((operator) =>
137
137
  defineOperator(operator, 2, (args) => {
138
- const left = getSet(args, 0, operator);
139
- const right = getSet(args, 1, operator);
138
+ const left = getValue(args, 0, operator);
139
+ const right = getValue(args, 1, operator);
140
140
  if (isReducible(left) && isReducible(right) && !isMixedSet(left) && !isMixedSet(right)) {
141
141
  if (operator === "\\cup" && isEmptySet(left)) return right;
142
142
  const merge =
@@ -145,7 +145,13 @@ export const CORE_OPERATORS: Builtin[] = [
145
145
  : operator === "\\cap"
146
146
  ? intersectSorted
147
147
  : differenceSorted;
148
- return merge(toFiniteSet(left), toFiniteSet(right));
148
+ // Merging compares elements across the sets. Where that fails, TLC's element-by-element
149
+ // membership test fails or succeeds on its own.
150
+ try {
151
+ return merge(toFiniteSet(left), toFiniteSet(right));
152
+ } catch (error) {
153
+ if (!(error instanceof TlaEvaluationError)) throw error;
154
+ }
149
155
  }
150
156
  if (isReducible(left)) return combineReducible(operator, left, right);
151
157
  if (operator !== "\\" && isReducible(right)) return combineReducible(operator, right, left);
@@ -179,51 +185,59 @@ export const CORE_OPERATORS: Builtin[] = [
179
185
  }),
180
186
  ];
181
187
 
182
- const DOT_DOT_SIGNATURE = getIntegersSignature("DotDot", "IntervalValue", 2);
188
+ const NEG_SIGNATURE = getArithmeticSignature("Integers", "Neg", "IntValue", 1);
183
189
 
184
- const NEG_SIGNATURE = getIntegersSignature("Neg", "IntValue", 1);
190
+ // TLC overrides the operators of Naturals with the Java class of Integers when a spec loads
191
+ // Integers, which names it in their errors.
192
+ const getArithmeticOperators = (javaClass: "Naturals" | "Integers") => {
193
+ const dotDotSignature = getArithmeticSignature(javaClass, "DotDot", "IntervalValue", 2);
194
+ return [
195
+ defineArithmetic(javaClass, "+", "Plus", (left, right) => left + right),
196
+ defineArithmetic(javaClass, "-", "Minus", (left, right) => left - right),
197
+ defineArithmetic(javaClass, "*", "Times", (left, right) => left * right),
198
+ defineArithmetic(javaClass, "^", "Expt", (base, exponent) => {
199
+ if (exponent < 0) {
200
+ throw new TlaModuleError(
201
+ `The second argument of ^ should be a natural number, but instead it is:\n${exponent}`,
202
+ );
203
+ }
204
+ if (base === 0 && exponent === 0) throw new TlaModuleError("0^0 is undefined.");
205
+ return base ** exponent;
206
+ }),
207
+ defineArithmetic(javaClass, "\\div", "Divide", (left, right) => {
208
+ if (right === 0) throw new TlaModuleError("The second argument of \\div is 0.");
209
+ const quotient = Math.floor(left / right);
210
+ if (isOutOfRange(quotient)) throw createOverflowError(`${left} \\div ${right}`);
211
+ return quotient;
212
+ }),
213
+ defineArithmetic(javaClass, "%", "Mod", (left, right) => {
214
+ if (right <= 0) {
215
+ throw new TlaModuleError(
216
+ `The second argument of % should be a positive number, but instead it is:\n${right}`,
217
+ );
218
+ }
219
+ return ((left % right) + right) % right;
220
+ }),
221
+ defineOperator("..", 2, (args) => ({
222
+ kind: "Interval",
223
+ low: getJavaInteger(getValue(args, 0, ".."), dotDotSignature),
224
+ high: getJavaInteger(getValue(args, 1, ".."), dotDotSignature),
225
+ })),
226
+ ];
227
+ };
185
228
 
186
229
  const NATURALS_OPERATORS = [
187
230
  defineConstant("Nat", { kind: "InfiniteSet", name: "Nat" }),
188
- defineArithmetic("+", "Plus", (left, right) => left + right),
189
- defineArithmetic("-", "Minus", (left, right) => left - right),
190
- defineArithmetic("*", "Times", (left, right) => left * right),
191
- defineArithmetic("^", "Expt", (base, exponent) => {
192
- if (exponent < 0) {
193
- throw new TlaModuleError(
194
- `The second argument of ^ should be a natural number, but instead it is:\n${exponent}`,
195
- );
196
- }
197
- if (base === 0 && exponent === 0) throw new TlaModuleError("0^0 is undefined.");
198
- return base ** exponent;
199
- }),
200
- defineArithmetic("\\div", "Divide", (left, right) => {
201
- if (right === 0) throw new TlaModuleError("The second argument of \\div is 0.");
202
- const quotient = Math.floor(left / right);
203
- if (isOutOfRange(quotient)) throw createOverflowError(`${left} \\div ${right}`);
204
- return quotient;
205
- }),
206
- defineArithmetic("%", "Mod", (left, right) => {
207
- if (right <= 0) {
208
- throw new TlaModuleError(
209
- `The second argument of % should be a positive number, but instead it is:\n${right}`,
210
- );
211
- }
212
- return ((left % right) + right) % right;
213
- }),
231
+ ...getArithmeticOperators("Naturals"),
214
232
  defineComparison("<", (left, right) => left < right),
215
233
  defineComparison(">", (left, right) => left > right),
216
234
  defineComparison("<=", (left, right) => left <= right),
217
235
  defineComparison(">=", (left, right) => left >= right),
218
- defineOperator("..", 2, (args) => ({
219
- kind: "Interval",
220
- low: getJavaInteger(getValue(args, 0, ".."), DOT_DOT_SIGNATURE),
221
- high: getJavaInteger(getValue(args, 1, ".."), DOT_DOT_SIGNATURE),
222
- })),
223
236
  ];
224
237
 
225
238
  const INTEGERS_OPERATORS = [
226
239
  defineConstant("Int", { kind: "InfiniteSet", name: "Int" }),
240
+ ...getArithmeticOperators("Integers"),
227
241
  defineOperator("-.", 1, (args) => {
228
242
  const value = getJavaInteger(getValue(args, 0, "-"), NEG_SIGNATURE);
229
243
  if (isOutOfRange(-value)) throw createOverflowError(`-${value}`);
@@ -0,0 +1,116 @@
1
+ import type { SourceRange } from "./ast";
2
+
3
+ // Where the modules in TLC's tla2sany/StandardModules define the operators that tla-ts implements
4
+ // natively, which SANY reports when a spec defines one of them again.
5
+ const RANGES: Record<string, Record<string, [number, number, number, number]>> = {
6
+ Naturals: {
7
+ Nat: [14, 1, 14, 16],
8
+ "+": [15, 1, 15, 19],
9
+ "-": [17, 1, 17, 33],
10
+ "*": [18, 1, 18, 17],
11
+ "^": [19, 1, 19, 19],
12
+ "<": [20, 1, 20, 19],
13
+ ">": [21, 1, 21, 19],
14
+ "<=": [22, 1, 22, 19],
15
+ ">=": [23, 1, 23, 19],
16
+ "%": [33, 1, 33, 20],
17
+ "\\div": [34, 1, 34, 20],
18
+ "..": [35, 1, 35, 20],
19
+ },
20
+ Integers: {
21
+ Int: [18, 1, 18, 12],
22
+ "-.": [22, 1, 22, 13],
23
+ },
24
+ Sequences: {
25
+ Seq: [20, 1, 20, 41],
26
+ Len: [25, 1, 25, 44],
27
+ "\\o": [30, 1, 31, 76],
28
+ Append: [36, 1, 36, 26],
29
+ Head: [41, 1, 41, 15],
30
+ Tail: [42, 1, 42, 61],
31
+ SubSeq: [48, 1, 48, 50],
32
+ SelectSeq: [53, 1, 65, 14],
33
+ },
34
+ FiniteSets: {
35
+ IsFiniteSet: [14, 1, 19, 68],
36
+ Cardinality: [21, 1, 27, 11],
37
+ },
38
+ Bags: {
39
+ IsABag: [20, 1, 24, 41],
40
+ BagToSet: [26, 1, 26, 23],
41
+ SetToBag: [31, 1, 31, 30],
42
+ BagIn: [36, 1, 36, 31],
43
+ EmptyBag: [41, 1, 41, 24],
44
+ "\\oplus": [43, 1, 49, 46],
45
+ "\\ominus": [51, 1, 60, 50],
46
+ BagUnion: [74, 1, 79, 58],
47
+ "\\sqsubseteq": [81, 1, 87, 42],
48
+ SubBag: [89, 1, 110, 11],
49
+ BagOfAll: [122, 1, 130, 66],
50
+ BagCardinality: [132, 1, 138, 8],
51
+ CopiesIn: [140, 1, 145, 33],
52
+ },
53
+ TLC: {
54
+ Print: [17, 1, 17, 22],
55
+ PrintT: [18, 1, 18, 19],
56
+ Assert: [24, 1, 25, 54],
57
+ JavaTime: [26, 1, 26, 32],
58
+ TLCGet: [75, 1, 75, 28],
59
+ TLCSet: [76, 1, 76, 20],
60
+ ":>": [78, 1, 78, 27],
61
+ "@@": [79, 1, 80, 50],
62
+ Permutations: [81, 1, 82, 54],
63
+ SortSeq: [88, 1, 92, 40],
64
+ RandomElement: [110, 1, 110, 41],
65
+ Any: [119, 1, 119, 22],
66
+ ToString: [121, 1, 121, 58],
67
+ TLCEval: [145, 1, 145, 15],
68
+ },
69
+ TLCExt: {
70
+ AssertEq: [14, 1, 20, 14],
71
+ AssertError: [23, 1, 26, 72],
72
+ TLCGetOrDefault: [30, 1, 31, 17],
73
+ TLCGetAndSet: [33, 1, 35, 57],
74
+ Trace: [41, 1, 57, 6],
75
+ CounterExample: [61, 1, 75, 8],
76
+ ToTrace: [77, 1, 87, 12],
77
+ TLCModelValue: [91, 1, 120, 29],
78
+ TLCDefer: [122, 1, 134, 6],
79
+ TLCNoOp: [138, 1, 145, 5],
80
+ PickSuccessor: [148, 1, 162, 37],
81
+ TLCCache: [166, 1, 173, 12],
82
+ TLCFP: [175, 1, 181, 24],
83
+ TLCEvalDefinition: [185, 1, 190, 6],
84
+ },
85
+ Randomization: {
86
+ RandomSubset: [30, 1, 30, 64],
87
+ RandomSetOfSubsets: [48, 1, 49, 67],
88
+ TestRandomSetOfSubsets: [61, 1, 62, 71],
89
+ },
90
+ Json: {
91
+ ToJson: [46, 1, 55, 37],
92
+ ToJsonArray: [57, 1, 64, 42],
93
+ ToJsonObject: [66, 1, 73, 43],
94
+ JsonSerialize: [75, 1, 80, 6],
95
+ JsonDeserialize: [82, 1, 87, 19],
96
+ ndJsonSerialize: [89, 1, 95, 6],
97
+ ndJsonDeserialize: [97, 1, 103, 19],
98
+ },
99
+ _Possible: {
100
+ _Track: [10, 1, 17, 38],
101
+ _Counts: [24, 1, 30, 14],
102
+ _CheckName: [32, 1, 35, 35],
103
+ _PrintCounts: [37, 1, 37, 31],
104
+ },
105
+ };
106
+
107
+ export const getStandardRange = (module: string, name: string): SourceRange | undefined => {
108
+ const range = RANGES[module]?.[name];
109
+ return (
110
+ range && {
111
+ module,
112
+ start: { line: range[0], column: range[1] },
113
+ end: { line: range[2], column: range[3] },
114
+ }
115
+ );
116
+ };
@@ -1,6 +1,5 @@
1
1
  import {
2
2
  getChildren,
3
- type Bound,
4
3
  type Definition,
5
4
  type Expression,
6
5
  type Instance,
@@ -8,10 +7,20 @@ import {
8
7
  type OperatorParam,
9
8
  type Selector,
10
9
  type SourceLocation,
10
+ type SourceRange,
11
11
  } from "./ast";
12
- import { TlaSyntaxError } from "./errors";
12
+ import { formatRange, TlaSyntaxError } from "./errors";
13
13
  import { getSourceName, mapChildren, mapDefinition } from "./instances";
14
- import { getArity, getBoundNames, getPatternNames, LOCAL_RESOLUTION } from "./resolve";
14
+ import {
15
+ getArity,
16
+ getBinder,
17
+ getNameSelectors,
18
+ getOperandIndex,
19
+ getOperands,
20
+ LOCAL_RESOLUTION,
21
+ selectionErrors,
22
+ selections,
23
+ } from "./resolve";
15
24
 
16
25
  type Lookup = (name: string) => Definition | undefined;
17
26
 
@@ -27,114 +36,19 @@ interface Selection {
27
36
  location: SourceLocation;
28
37
  }
29
38
 
39
+ // A name that selects a subexpression, with the range of each part and of the arguments of each
40
+ // part, where SANY reports an error in selecting that part.
41
+ interface SelectingName {
42
+ location: SourceLocation;
43
+ selectorRanges?: SourceRange[];
44
+ argumentRanges?: (SourceRange | undefined)[];
45
+ }
46
+
30
47
  const SELECTION_NAME = "$subexpression";
31
48
 
32
49
  const createError = (message: string, location: SourceLocation) =>
33
50
  new TlaSyntaxError(`${message} at line ${location.line}, column ${location.column}`);
34
51
 
35
- const getBoundSets = (bounds: Bound[]) =>
36
- bounds
37
- .filter((bound, index) => index === 0 || bounds[index - 1].set !== bound.set)
38
- .map((bound) => bound.set);
39
-
40
- const getOperandIndex = (operand: number | "<<" | ">>", count: number) => {
41
- if (typeof operand === "number") return operand >= 1 && operand <= count ? operand - 1 : -1;
42
- if (operand === "<<") return count > 0 ? 0 : -1;
43
- return count === 2 ? 1 : -1;
44
- };
45
-
46
- const getOperands = (expression: Expression): Expression[] | undefined => {
47
- switch (expression.kind) {
48
- case "Apply":
49
- return expression.args;
50
- case "And":
51
- case "Or":
52
- return expression.operands;
53
- case "If":
54
- return [expression.condition, expression.consequent, expression.alternative];
55
- case "Tuple":
56
- case "SetEnumeration":
57
- return expression.elements;
58
- case "Record":
59
- case "RecordSet":
60
- return expression.fields.map((field) => field.value);
61
- case "FunctionApplication":
62
- return [
63
- expression.function,
64
- expression.args.length === 1
65
- ? expression.args[0]
66
- : { kind: "Tuple", elements: expression.args, location: expression.location },
67
- ];
68
- case "FieldAccess":
69
- return [
70
- expression.record,
71
- { kind: "String", value: expression.field, location: expression.location },
72
- ];
73
- case "Prime":
74
- case "Unchanged":
75
- case "Enabled":
76
- case "Always":
77
- case "Eventually":
78
- return [expression.expression];
79
- case "BoxAction":
80
- case "AngleAction":
81
- return [expression.action, expression.subscript];
82
- case "WeakFairness":
83
- case "StrongFairness":
84
- return [expression.subscript, expression.action];
85
- case "FunctionSet":
86
- return [expression.domain, expression.range];
87
- case "Product":
88
- return expression.factors;
89
- case "Except":
90
- return [expression.function];
91
- default:
92
- return undefined;
93
- }
94
- };
95
-
96
- const getBinder = (
97
- expression: Expression,
98
- ): { names: string[]; body: Expression; sets: Expression[] } | undefined => {
99
- switch (expression.kind) {
100
- case "Forall":
101
- case "Exists":
102
- case "FunctionConstruction":
103
- return {
104
- names: getBoundNames(expression.bounds),
105
- body: expression.body,
106
- sets: getBoundSets(expression.bounds),
107
- };
108
- case "SetMap":
109
- return {
110
- names: getBoundNames(expression.bounds),
111
- body: expression.expression,
112
- sets: getBoundSets(expression.bounds),
113
- };
114
- case "SetFilter":
115
- return {
116
- names: getPatternNames(expression.bound.pattern),
117
- body: expression.predicate,
118
- sets: [expression.bound.set],
119
- };
120
- case "Choose":
121
- return {
122
- names: getPatternNames(expression.pattern),
123
- body: expression.body,
124
- sets: expression.set ? [expression.set] : [],
125
- };
126
- case "UnboundedQuantifier":
127
- case "Lambda":
128
- return {
129
- names: expression.kind === "Lambda" ? expression.params : expression.names,
130
- body: expression.body,
131
- sets: [],
132
- };
133
- default:
134
- return undefined;
135
- }
136
- };
137
-
138
52
  const findLabel = (
139
53
  expression: Expression,
140
54
  name: string,
@@ -153,9 +67,6 @@ const findLabel = (
153
67
  return undefined;
154
68
  };
155
69
 
156
- const takeArguments = (args: Expression[], count: number, pool: Expression[]) =>
157
- args.length === 0 && pool.length > 0 ? pool.splice(0, count) : args;
158
-
159
70
  const wrapLets = (body: Expression, lets: Definition[][], location: SourceLocation) =>
160
71
  lets.reduceRight<Expression>(
161
72
  (inner, definitions) => ({ kind: "Let", definitions, body: inner, location }),
@@ -235,14 +146,30 @@ const applyDefinition = (definition: Definition, selection: Selection) => {
235
146
  return createApplication({ ...selection, params: [...selection.params, ...params] }, reference);
236
147
  };
237
148
 
149
+ // Generator.selectorToNode reports the first part of a name that selects nothing, after it analyzes
150
+ // the arguments of the parts before, and goes on after the name. An operator or a label must be given
151
+ // all its arguments, except in a name that an operator argument may select whole.
238
152
  const selectSubexpression = (
239
153
  selectors: Selector[],
240
154
  lookup: Lookup,
241
- location: SourceLocation,
242
- pool: Expression[],
155
+ reference: Expression & SelectingName,
156
+ isOperator: boolean,
243
157
  ): Expression => {
158
+ const location = reference.location;
244
159
  const selection: Selection = { params: [], args: [], lets: [], location };
245
- const state = { index: 0, current: undefined as Expression | undefined };
160
+ const state = { index: 0, current: undefined as Expression | undefined, isFailed: false };
161
+
162
+ const report = (range: SourceRange | undefined, message: string) => {
163
+ if (!range) throw createError(message, location);
164
+ selectionErrors.set(reference, {
165
+ args: selectors
166
+ .slice(0, state.index)
167
+ .flatMap((selector) => ("args" in selector ? selector.args : [])),
168
+ error: { location: formatRange(range), message },
169
+ });
170
+ state.isFailed = true;
171
+ return undefined;
172
+ };
246
173
 
247
174
  const findDefinition = (local: Definition[] | undefined) => {
248
175
  const names: string[] = [];
@@ -256,9 +183,8 @@ const selectSubexpression = (
256
183
  const definition = local
257
184
  ? local.find((candidate) => getSourceName(candidate) === name)
258
185
  : lookup(name);
259
- if (definition) {
260
- return { definition, args: takeArguments(args, getArity(definition), pool) };
261
- }
186
+ if (definition)
187
+ return { definition, name, args, earlier: args.length - selector.args.length };
262
188
  state.index++;
263
189
  }
264
190
  throw createError(`Unknown operator ${names.join("!")}`, location);
@@ -269,8 +195,11 @@ const selectSubexpression = (
269
195
  const definition = found.definition;
270
196
  const arity = getArity(definition);
271
197
  const isLast = state.index === selectors.length - 1;
272
- if (found.args.length !== arity && found.args.length !== 0) {
273
- throw createError(`The operator ${definition.name} requires ${arity} arguments`, location);
198
+ if (found.args.length !== arity && (!isOperator || found.args.length !== 0)) {
199
+ return report(
200
+ reference.argumentRanges?.[state.index] ?? location.range,
201
+ `The operator ${found.name} requires ${arity - found.earlier} arguments.`,
202
+ );
274
203
  }
275
204
  if (isLast) return { definition, args: found.args };
276
205
  if (definition.kind !== "Operator") {
@@ -284,14 +213,19 @@ const selectSubexpression = (
284
213
  };
285
214
 
286
215
  const followLabels = () => {
287
- while (state.index < selectors.length) {
216
+ while (state.index < selectors.length && !state.isFailed) {
288
217
  const selector = selectors[state.index];
289
218
  if (selector.kind !== "Name") return;
219
+ const range = reference.selectorRanges?.[state.index];
290
220
  const found = state.current && findLabel(state.current, selector.name, []);
291
- if (!found) throw createError(`Cannot find label ${selector.name}`, location);
221
+ if (!found) return report(range, `Cannot find label \`${selector.name}'.`);
222
+ const params = found.label.params;
223
+ if (!isOperator && selector.args.length !== params.length) {
224
+ return report(range, `Label \`${selector.name}' used with wrong number of arguments.`);
225
+ }
292
226
  selection.lets.push(...found.lets);
293
- selection.params.push(...found.label.params.map((name) => ({ name, arity: 0 })));
294
- selection.args.push(...takeArguments(selector.args, found.label.params.length, pool));
227
+ selection.params.push(...params.map((name) => ({ name, arity: 0 })));
228
+ selection.args.push(...selector.args);
295
229
  state.current = found.label.body;
296
230
  state.index++;
297
231
  }
@@ -317,9 +251,7 @@ const selectSubexpression = (
317
251
  const binder = getBinder(current);
318
252
  if (binder && (selector.kind === "Bound" || selector.kind === "At")) {
319
253
  selection.params.push(...binder.names.map((name) => ({ name, arity: 0 })));
320
- if (selector.kind === "Bound") {
321
- selection.args.push(...takeArguments(selector.args, binder.names.length, pool));
322
- }
254
+ if (selector.kind === "Bound") selection.args.push(...selector.args);
323
255
  state.current = binder.body;
324
256
  return;
325
257
  }
@@ -349,9 +281,10 @@ const selectSubexpression = (
349
281
  };
350
282
 
351
283
  const first = enterDefinition(undefined);
284
+ if (state.isFailed) return reference;
352
285
  if (first) return applyDefinition(first.definition, { ...selection, args: first.args });
353
286
  followLabels();
354
- while (state.index < selectors.length) {
287
+ while (state.index < selectors.length && !state.isFailed) {
355
288
  const selector = selectors[state.index];
356
289
  if (selector.kind === "Name") {
357
290
  while (state.current?.kind === "Label") state.current = state.current.body;
@@ -360,6 +293,7 @@ const selectSubexpression = (
360
293
  }
361
294
  selection.lets.push(state.current.definitions);
362
295
  const last = enterDefinition(state.current.definitions);
296
+ if (state.isFailed) return reference;
363
297
  if (last) {
364
298
  return applyDefinition(last.definition, {
365
299
  ...selection,
@@ -372,19 +306,22 @@ const selectSubexpression = (
372
306
  selectOperand(selector);
373
307
  state.index++;
374
308
  }
309
+ if (state.isFailed) return reference;
375
310
  if (!state.current) throw createError("Subexpression selection failed", location);
376
311
  return createApplication(selection, state.current);
377
312
  };
378
313
 
379
- const getQualifiedSelectors = (name: string, lookup: Lookup): Selector[] | undefined => {
314
+ // A name such as Op(1)!lab(2) whose first parts name a definition selects part of it.
315
+ const getQualifiedSelectors = (
316
+ name: string,
317
+ args: Expression[],
318
+ counts: number[] | undefined,
319
+ lookup: Lookup,
320
+ ) => {
380
321
  if (!name.includes("!") || lookup(name)) return undefined;
381
322
  const parts = name.split("!");
382
- const prefix = parts.findIndex((_, index) => lookup(parts.slice(0, index + 1).join("!")));
383
- if (prefix === -1) return undefined;
384
- return [
385
- { kind: "Name", name: parts.slice(0, prefix + 1).join("!"), args: [] },
386
- ...parts.slice(prefix + 1).map((part): Selector => ({ kind: "Name", name: part, args: [] })),
387
- ];
323
+ if (!parts.some((_, index) => lookup(parts.slice(0, index + 1).join("!")))) return undefined;
324
+ return getNameSelectors(name, args, counts);
388
325
  };
389
326
 
390
327
  const containsReference = (expression: Expression): boolean =>
@@ -393,25 +330,48 @@ const containsReference = (expression: Expression): boolean =>
393
330
  (expression.kind === "Apply" && expression.operator.includes("!")) ||
394
331
  getChildren(expression).some(containsReference);
395
332
 
396
- const resolveSubexpressions = (expression: Expression, lookup: Lookup): Expression => {
333
+ // A reference into a theorem whose statement is an ASSUME/PROVE stays for name resolution to check.
334
+ // isOperator holds where an operator may be given, as the argument of an operator that may take one.
335
+ const resolveSubexpressions = (
336
+ expression: Expression,
337
+ lookup: Lookup,
338
+ goals: ReadonlySet<string>,
339
+ isOperator = false,
340
+ ): Expression => {
397
341
  if (!containsReference(expression)) return expression;
398
342
  if (expression.kind === "Let") {
399
343
  const local: Lookup = (name) =>
400
344
  expression.definitions.find((definition) => definition.name === name) ?? lookup(name);
401
- return mapChildren(expression, (child) => resolveSubexpressions(child, local));
402
- }
403
- const mapped = mapChildren(expression, (child) => resolveSubexpressions(child, lookup));
404
- if (mapped.kind === "Subexpression") {
405
- return selectSubexpression(mapped.selectors, lookup, mapped.location, []);
345
+ return mapChildren(expression, (child) => resolveSubexpressions(child, local, goals));
406
346
  }
407
- const name =
408
- mapped.kind === "Identifier" ? mapped.name : mapped.kind === "Apply" ? mapped.operator : "";
409
- const selectors = getQualifiedSelectors(name, lookup);
410
- if (!selectors) return mapped;
411
- const pool = mapped.kind === "Apply" ? [...mapped.args] : [];
412
- const resolved = selectSubexpression(selectors, lookup, mapped.location, pool);
413
- if (pool.length > 0) throw createError(`Too many arguments for ${name}`, mapped.location);
414
- return resolved;
347
+ const callee = expression.kind === "Apply" ? lookup(expression.operator) : undefined;
348
+ const mapped =
349
+ expression.kind === "Apply"
350
+ ? {
351
+ ...expression,
352
+ args: expression.args.map((arg, index) =>
353
+ resolveSubexpressions(
354
+ arg,
355
+ lookup,
356
+ goals,
357
+ callee?.kind !== "Operator" || callee.params[index]?.arity !== 0,
358
+ ),
359
+ ),
360
+ }
361
+ : mapChildren(expression, (child) => resolveSubexpressions(child, lookup, goals));
362
+ const selectors =
363
+ mapped.kind === "Subexpression"
364
+ ? mapped.selectors
365
+ : mapped.kind === "Identifier"
366
+ ? getQualifiedSelectors(mapped.name, [], undefined, lookup)
367
+ : mapped.kind === "Apply"
368
+ ? getQualifiedSelectors(mapped.operator, mapped.args, mapped.argumentCounts, lookup)
369
+ : undefined;
370
+ const first = selectors?.[0];
371
+ if (!selectors || (first?.kind === "Name" && goals.has(first.name))) return mapped;
372
+ const selected = selectSubexpression(selectors, lookup, mapped, isOperator);
373
+ if (selected !== mapped) selections.add(selected);
374
+ return selected;
415
375
  };
416
376
 
417
377
  const createLookup = (definitions: Definition[]): Lookup => {
@@ -424,8 +384,8 @@ export const resolveInstanceSubexpressions = (instance: Instance, module: Module
424
384
  return {
425
385
  ...instance,
426
386
  substitutions: instance.substitutions.map((substitution) => ({
427
- name: substitution.name,
428
- expression: resolveSubexpressions(substitution.expression, lookup),
387
+ ...substitution,
388
+ expression: resolveSubexpressions(substitution.expression, lookup, new Set(), true),
429
389
  })),
430
390
  };
431
391
  };
@@ -436,14 +396,19 @@ export const resolveModuleSubexpressions = (module: Module, available: Definitio
436
396
  module.definitions.some((definition) => containsReference(definition.body)) ||
437
397
  module.assumptions.some((assumption) => containsReference(assumption.expression));
438
398
  if (!hasReferences) return module;
399
+ const goals = new Set(
400
+ module.theorems.flatMap((theorem) =>
401
+ theorem.name !== undefined && theorem.statement.kind === "AssumeProve" ? [theorem.name] : [],
402
+ ),
403
+ );
439
404
  return {
440
405
  ...module,
441
406
  definitions: module.definitions.map((definition) =>
442
- mapDefinition(definition, (child) => resolveSubexpressions(child, lookup)),
407
+ mapDefinition(definition, (child) => resolveSubexpressions(child, lookup, goals)),
443
408
  ),
444
409
  assumptions: module.assumptions.map((assumption) => ({
445
410
  ...assumption,
446
- expression: resolveSubexpressions(assumption.expression, lookup),
411
+ expression: resolveSubexpressions(assumption.expression, lookup, goals),
447
412
  })),
448
413
  };
449
414
  };