tla-ts 0.0.3-dev.a57ca4f → 0.0.3-dev.ab42bab

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/src/live-check.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { TlaEvaluationError } from "./errors";
2
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
2
3
  import { hasRepeatedEffects, type Environment } from "./evaluate";
3
4
  import {
4
5
  evaluateLive,
@@ -12,6 +13,7 @@ import {
12
13
  createJunction,
13
14
  createUnary,
14
15
  getSolutions,
16
+ getTermKey,
15
17
  isFulfilling,
16
18
  type LiveExpression,
17
19
  type Solution,
@@ -48,37 +50,21 @@ interface Check {
48
50
  actionIds: Int32Array;
49
51
  nodeStates: number[];
50
52
  nodeTableaux: number[];
51
- successors: number[][];
52
- actions: Uint8Array[];
53
- stateResults: Uint8Array[];
54
- isWritten: boolean[];
53
+ // The successors a node gathers until it is written.
54
+ pending: (number[] | undefined)[];
55
+ // Each written node's state results, then its action results edge by edge, from the node's
56
+ // offset in one buffer, so a node costs no objects of its own. An unwritten node has offset -1.
57
+ offsets: number[];
58
+ results: { bytes: Uint8Array; length: number };
59
+ // Each written node's successor count, then its successors, from the node's edge offset.
60
+ edgeOffsets: number[];
61
+ edges: { ids: Int32Array; length: number };
55
62
  initial: number[];
56
- nodeIds: Map<number, number>;
57
- nodesByState: Map<number, number[]>;
63
+ nodeIds: NodeTable;
58
64
  isDone: boolean[];
59
65
  errorNode: number | undefined;
60
66
  }
61
67
 
62
- const liveKeys = new WeakMap<LiveExpression, string>();
63
-
64
- const atomCount = { value: 0 };
65
-
66
- // Each solution builds its own junctions over shared atoms, so equal checks get equal keys.
67
- const getLiveKey = (expression: LiveExpression): string => {
68
- const cached = liveKeys.get(expression);
69
- if (cached !== undefined) return cached;
70
- const key =
71
- expression.kind === "Boolean"
72
- ? String(expression.value)
73
- : "body" in expression
74
- ? `${expression.kind}(${getLiveKey(expression.body)})`
75
- : "operands" in expression
76
- ? `${expression.kind}(${expression.operands.map(getLiveKey).join(",")})`
77
- : `${expression.kind}#${atomCount.value++}`;
78
- liveKeys.set(expression, key);
79
- return key;
80
- };
81
-
82
68
  const isSameState = (left: Value[], right: Value[]) =>
83
69
  left.every((value, position) => isSameValue(value, right[position]));
84
70
 
@@ -89,13 +75,45 @@ const removeRepeats = (path: number[]) =>
89
75
  const pushNode = (check: Check, state: number, tableauNode: number) => {
90
76
  check.nodeStates.push(state);
91
77
  check.nodeTableaux.push(tableauNode);
92
- check.successors.push([]);
93
- check.actions.push(new Uint8Array(0));
94
- check.stateResults.push(new Uint8Array(0));
95
- check.isWritten.push(false);
78
+ check.pending.push(undefined);
79
+ check.offsets.push(-1);
80
+ check.edgeOffsets.push(-1);
96
81
  return check.nodeStates.length - 1;
97
82
  };
98
83
 
84
+ // A Map holds at most 2^24 entries, so each tableau node of a state finds its node in an
85
+ // open-addressing table of (state plus one, tableau node, node) triples.
86
+ interface NodeTable {
87
+ slots: Int32Array;
88
+ size: number;
89
+ shift: number;
90
+ }
91
+
92
+ const getNodeSlot = (table: NodeTable, state: number, tableauNode: number) => {
93
+ const mask = table.slots.length / 3 - 1;
94
+ const hash = Math.imul(Math.imul(state, 0x9e3779b1) ^ tableauNode, 0x85ebca6b) >>> table.shift;
95
+ for (let index = hash; ; index = (index + 1) & mask) {
96
+ const slot = index * 3;
97
+ const stored = table.slots[slot];
98
+ if (stored === 0 || (stored === state + 1 && table.slots[slot + 1] === tableauNode))
99
+ return slot;
100
+ }
101
+ };
102
+
103
+ // Without a tableau a node is a state, so a successor the search hasn't expanded yet may lie past
104
+ // the per-node arrays.
105
+ const isWritten = (check: Check, node: number) => (check.offsets[node] ?? -1) !== -1;
106
+
107
+ const getPending = (check: Check, node: number) => (check.pending[node] ??= []);
108
+
109
+ const getSuccessors = (check: Check, node: number) => {
110
+ const offset = check.edgeOffsets[node];
111
+ return check.edges.ids.subarray(offset + 1, offset + 1 + check.edges.ids[offset]);
112
+ };
113
+
114
+ const getStateResult = (check: Check, node: number, position: number) =>
115
+ check.results.bytes[check.offsets[node] + position] === 1;
116
+
99
117
  const SUCCESSOR_CAPACITY = 16;
100
118
 
101
119
  const SCC_MARKER = -42;
@@ -122,26 +140,29 @@ export const createLivenessChecker = (
122
140
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
123
141
  const solutions = getSolutions(formula);
124
142
  if (solutions.length === 0) {
125
- throw new TlaEvaluationError(TAUTOLOGY_MESSAGE);
143
+ throw setExitCode(
144
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
145
+ EXIT_STATUS.livenessEvaluationFailure,
146
+ );
126
147
  }
127
148
  const actionIds = new Map<string, number>();
128
149
  const checks = solutions.map((solution): Check => ({
129
150
  solution,
130
151
  actionIds: Int32Array.from(solution.actionChecks, (predicate) => {
131
- const key = getLiveKey(predicate);
152
+ const key = getTermKey(predicate);
132
153
  const id = actionIds.get(key) ?? actionIds.size;
133
154
  actionIds.set(key, id);
134
155
  return id;
135
156
  }),
136
157
  nodeStates: [],
137
158
  nodeTableaux: [],
138
- successors: [],
139
- actions: [],
140
- stateResults: [],
141
- isWritten: [],
159
+ pending: [],
160
+ offsets: [],
161
+ results: { bytes: new Uint8Array(1024), length: 0 },
162
+ edgeOffsets: [],
163
+ edges: { ids: new Int32Array(1024), length: 0 },
142
164
  initial: [],
143
- nodeIds: new Map(),
144
- nodesByState: new Map(),
165
+ nodeIds: { slots: new Int32Array(3 << 10), size: 0, shift: 22 },
145
166
  isDone: [],
146
167
  errorNode: undefined,
147
168
  }));
@@ -227,18 +248,35 @@ export const createLivenessChecker = (
227
248
  model.infinitelyOftenActions.length === 0,
228
249
  );
229
250
 
230
- const getNodeId = (check: Check, state: number, tableauNode: number) =>
231
- check.solution.tableau
232
- ? check.nodeIds.get(state * check.solution.tableau.nodes.length + tableauNode)
233
- : state;
251
+ const getNodeId = (check: Check, state: number, tableauNode: number) => {
252
+ if (!check.solution.tableau) return state;
253
+ const slots = check.nodeIds.slots;
254
+ const slot = getNodeSlot(check.nodeIds, state, tableauNode);
255
+ return slots[slot] === 0 ? undefined : slots[slot + 2];
256
+ };
234
257
  const recordNode = (check: Check, state: number, tableauNode: number) => {
235
258
  const node = pushNode(check, state, tableauNode);
236
- check.nodeIds.set(state * (check.solution.tableau?.nodes.length ?? 1) + tableauNode, node);
237
- const siblings = check.nodesByState.get(state);
238
- if (siblings) siblings.push(node);
239
- else check.nodesByState.set(state, [node]);
259
+ const table = check.nodeIds;
260
+ if (++table.size * 2 > table.slots.length / 3) {
261
+ const old = table.slots;
262
+ table.slots = new Int32Array(old.length * 2);
263
+ table.shift--;
264
+ for (let slot = 0; slot < old.length; slot += 3) {
265
+ if (old[slot] !== 0)
266
+ table.slots.set(
267
+ old.subarray(slot, slot + 3),
268
+ getNodeSlot(table, old[slot] - 1, old[slot + 1]),
269
+ );
270
+ }
271
+ }
272
+ table.slots.set([state + 1, tableauNode, node], getNodeSlot(table, state, tableauNode));
240
273
  return node;
241
274
  };
275
+ // A state's nodes in the order they were recorded, which is the order of their ids.
276
+ const getStateNodes = (check: Check, tableau: Tableau, state: number) =>
277
+ tableau.nodes
278
+ .flatMap((_, tableauNode) => getNodeId(check, state, tableauNode) ?? [])
279
+ .sort((left, right) => left - right);
242
280
  const writeNode = (
243
281
  check: Check,
244
282
  node: number,
@@ -246,11 +284,32 @@ export const createLivenessChecker = (
246
284
  stateResults: Uint8Array,
247
285
  ) => {
248
286
  const actionCount = check.solution.actionChecks.length;
249
- const packed = new Uint8Array(actions.length * actionCount);
250
- actions.forEach((results, position) => packed.set(results, position * actionCount));
251
- check.actions[node] = packed;
252
- check.stateResults[node] = stateResults;
253
- check.isWritten[node] = true;
287
+ const results = check.results;
288
+ const offset = results.length;
289
+ results.length += stateResults.length + actions.length * actionCount;
290
+ if (results.length > results.bytes.length) {
291
+ const grown = new Uint8Array(Math.max(2 * results.bytes.length, results.length));
292
+ grown.set(results.bytes);
293
+ results.bytes = grown;
294
+ }
295
+ results.bytes.set(stateResults, offset);
296
+ actions.forEach((edge, position) =>
297
+ results.bytes.set(edge, offset + stateResults.length + position * actionCount),
298
+ );
299
+ check.offsets[node] = offset;
300
+ const successors = check.pending[node] ?? [];
301
+ const edges = check.edges;
302
+ const edgeOffset = edges.length;
303
+ edges.length += successors.length + 1;
304
+ if (edges.length > edges.ids.length) {
305
+ const grown = new Int32Array(Math.max(2 * edges.ids.length, edges.length));
306
+ grown.set(edges.ids);
307
+ edges.ids = grown;
308
+ }
309
+ edges.ids[edgeOffset] = successors.length;
310
+ edges.ids.set(successors, edgeOffset + 1);
311
+ check.edgeOffsets[node] = edgeOffset;
312
+ check.pending[node] = undefined;
254
313
  };
255
314
 
256
315
  // TLC collects a state's successors and the state itself in a SetOfStates, a hash set it
@@ -303,7 +362,7 @@ export const createLivenessChecker = (
303
362
  const stateResults = checkState(check, index, state);
304
363
  const tableauNode = tableau.nodes[check.nodeTableaux[node]];
305
364
  const actions: Uint8Array[] = [];
306
- const successors = check.successors[node];
365
+ const successors = getPending(check, node);
307
366
  const selfActions =
308
367
  tableauNode.successors.length > 0
309
368
  ? checkAction(check, index, state, state)
@@ -352,8 +411,8 @@ export const createLivenessChecker = (
352
411
  );
353
412
  check.isDone[index] = true;
354
413
  // TLC expands the nodes recorded before the loop, not the ones the loop records.
355
- for (const node of (check.nodesByState.get(index) ?? []).slice()) {
356
- const successors = check.successors[node];
414
+ for (const node of getStateNodes(check, tableau, index)) {
415
+ const successors = getPending(check, node);
357
416
  const actions: Uint8Array[] = [];
358
417
  set.forEach((successor, position) => {
359
418
  const isDone = check.isDone[successor.index] === true;
@@ -387,10 +446,10 @@ export const createLivenessChecker = (
387
446
  index: number,
388
447
  ) => {
389
448
  while (check.nodeStates.length <= index) pushNode(check, check.nodeStates.length, -1);
390
- const successors = check.successors[index];
449
+ const successors = getPending(check, index);
391
450
  const actions: Uint8Array[] = [];
392
451
  set.forEach((successor, position) => {
393
- if (check.isWritten[successor.index] && successors.includes(successor.index)) return;
452
+ if (isWritten(check, successor.index) && successors.includes(successor.index)) return;
394
453
  successors.push(successor.index);
395
454
  actions.push(actionResults[position]);
396
455
  });
@@ -404,20 +463,20 @@ export const createLivenessChecker = (
404
463
  const parents = new Map<number, number>();
405
464
  const queue: number[] = [];
406
465
  for (const node of check.initial) {
407
- if (!check.isWritten[node]) continue;
466
+ if (!isWritten(check, node)) continue;
408
467
  queue.push(node);
409
468
  parents.set(node, -1);
410
469
  }
411
470
  for (let position = 0; position < queue.length; position++) {
412
471
  const current = queue[position];
413
- for (const next of check.successors[current]) {
472
+ for (const next of getSuccessors(check, current)) {
414
473
  if (next === current && check.solution.tableau) continue;
415
474
  if (next === target) {
416
475
  const path = [target];
417
476
  for (let node = current; node !== -1; node = parents.get(node) ?? -1) path.push(node);
418
477
  return path;
419
478
  }
420
- if (!check.isWritten[next] || parents.has(next)) continue;
479
+ if (!isWritten(check, next) || parents.has(next)) continue;
421
480
  parents.set(next, current);
422
481
  queue.push(next);
423
482
  }
@@ -429,16 +488,17 @@ export const createLivenessChecker = (
429
488
  const findInModel = (check: Check, model: Solution["models"][number]): Lasso | undefined => {
430
489
  const solution = check.solution;
431
490
  const actionCount = solution.actionChecks.length;
491
+ const stateCount = solution.stateChecks.length;
432
492
  const getAction = (node: number, edge: number, position: number) =>
433
- check.actions[node][edge * actionCount + position] === 1;
493
+ check.results.bytes[check.offsets[node] + stateCount + edge * actionCount + position] === 1;
434
494
  const isAllowed = (node: number, edge: number) =>
435
495
  model.eventuallyAlways.every((position) => getAction(node, edge, position));
436
496
  const links = new Float64Array(check.nodeStates.length).fill(UNVISITED);
437
- const queue = check.initial.filter((node) => check.isWritten[node]);
497
+ const queue = check.initial.filter((node) => isWritten(check, node));
438
498
  const components: number[] = [];
439
499
 
440
500
  const isStuttering = (node: number) => {
441
- const edge = check.successors[node].indexOf(node);
501
+ const edge = getSuccessors(check, node).indexOf(node);
442
502
  return edge !== -1 && isAllowed(node, edge);
443
503
  };
444
504
  const isFulfilled = (node: number, promise: Solution["promises"][number]) =>
@@ -462,11 +522,11 @@ export const createLivenessChecker = (
462
522
  if (member === root) break;
463
523
  }
464
524
  const isStateSatisfied = model.infinitelyOftenStates.every((position) =>
465
- [...members].some((node) => check.stateResults[node][position] === 1),
525
+ [...members].some((node) => getStateResult(check, node, position)),
466
526
  );
467
527
  const isActionSatisfied = model.infinitelyOftenActions.every((position) =>
468
528
  [...members].some((node) =>
469
- check.successors[node].some(
529
+ getSuccessors(check, node).some(
470
530
  (next, edge) =>
471
531
  members.has(next) && isAllowed(node, edge) && getAction(node, edge, position),
472
532
  ),
@@ -507,7 +567,7 @@ export const createLivenessChecker = (
507
567
  const countAtStart = remaining.count;
508
568
  while (true) {
509
569
  model.infinitelyOftenStates.forEach((position, slot) => {
510
- if (!stateDone[slot] && check.stateResults[current.node][position] === 1) {
570
+ if (!stateDone[slot] && getStateResult(check, current.node, position)) {
511
571
  stateDone[slot] = true;
512
572
  remaining.count--;
513
573
  }
@@ -521,7 +581,7 @@ export const createLivenessChecker = (
521
581
  if (remaining.count <= 0) break;
522
582
  const step = { last: -1, unvisited: -1 };
523
583
  const countBeforeActions = remaining.count;
524
- const successors = check.successors[current.node];
584
+ const successors = getSuccessors(check, current.node);
525
585
  const taken = successors.some((next, edge) => {
526
586
  if (membersByState.has(check.nodeStates[next])) {
527
587
  if (!isMember(next) || !isAllowed(current.node, edge)) return false;
@@ -556,7 +616,8 @@ export const createLivenessChecker = (
556
616
  }
557
617
  current.node = previous;
558
618
  step.unvisited =
559
- check.successors[previous].find((next) => isMember(next) && !seen.has(next)) ?? -1;
619
+ getSuccessors(check, previous).find((next) => isMember(next) && !seen.has(next)) ??
620
+ -1;
560
621
  }
561
622
  take(step.unvisited);
562
623
  seen.add(step.unvisited);
@@ -586,7 +647,7 @@ export const createLivenessChecker = (
586
647
  const queue: [number, number][] = [];
587
648
  for (let state = start, parent = -1, position = 0; ; position++) {
588
649
  for (const node of membersByState.get(state) ?? []) {
589
- for (const [edge, next] of check.successors[node].entries()) {
650
+ for (const [edge, next] of getSuccessors(check, node).entries()) {
590
651
  if (next === node || !isAllowedEdge(node, edge)) continue;
591
652
  if (next === root) {
592
653
  const path: number[] = [];
@@ -639,8 +700,8 @@ export const createLivenessChecker = (
639
700
  stack.push(lowLink, node, SCC_MARKER);
640
701
  components.push(node);
641
702
  const nextLowLink = { value: counter.link++ };
642
- check.successors[node].forEach((next, edge) => {
643
- if (!check.isWritten[next]) return;
703
+ getSuccessors(check, node).forEach((next, edge) => {
704
+ if (!isWritten(check, next)) return;
644
705
  if (!isAllowed(node, edge)) {
645
706
  if (links[next] === UNVISITED) queue.push(next);
646
707
  return;
package/src/liveness.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { isLocallyResolved, type Definition, type Expression } from "./ast";
2
- import { TlaConfigError, TlaEvaluationError } from "./errors";
3
- import { EXIT_STATUS, setExitCode } from "./exit-codes";
2
+ import { STACK_OVERFLOW, TlaEvaluationError, TlaModuleError, UNEXPECTED_EXCEPTION } from "./errors";
3
+ import { EXIT_STATUS, getOwnExitCode, setExitCode } from "./exit-codes";
4
4
  import {
5
5
  describeLocation,
6
6
  describeRange,
@@ -61,6 +61,23 @@ const getConstantContext = (environment: Environment, scope: Scope | undefined):
61
61
  next: undefined,
62
62
  });
63
63
 
64
+ // TLC evaluates the constant parts of a property while it processes the spec. Its top-level handler
65
+ // prints a failure without a TLC error code of its own as an unexpected exception.
66
+ const evaluateConstant = (expression: Expression, context: Context) => {
67
+ try {
68
+ return evaluate(expression, context);
69
+ } catch (error) {
70
+ if (!(error instanceof TlaEvaluationError) || error instanceof TlaModuleError) throw error;
71
+ const code = getOwnExitCode(error);
72
+ throw code === undefined
73
+ ? setExitCode(
74
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
75
+ EXIT_STATUS.error,
76
+ )
77
+ : setExitCode(error, code);
78
+ }
79
+ };
80
+
64
81
  const createCannotHandleError = (expression: Expression) =>
65
82
  new TlaEvaluationError(
66
83
  `TLC cannot handle the temporal formula at ${describeLocation(expression)}`,
@@ -191,14 +208,18 @@ export const expandTemporal = (
191
208
  getDefinitionLevel(definition, environment) > 0
192
209
  ) {
193
210
  if (expanding.has(definition)) {
194
- throw new TlaConfigError(`The definition of ${expression.name} refers to itself`);
211
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
195
212
  }
196
- return expand(
213
+ const expanded = expand(
197
214
  definition.body,
198
215
  undefined,
199
216
  expression.name,
200
217
  new Set([...expanding, definition]),
201
218
  );
219
+ // TLC takes the body of a state-level definition in a specification as one initial predicate.
220
+ return !isProperty && getDefinitionLevel(definition, environment) < ACTION_LEVEL
221
+ ? [{ expression: definition.body, scope: undefined, name: expression.name }]
222
+ : expanded;
202
223
  }
203
224
  }
204
225
  const context = getConstantContext(environment, scope);
@@ -278,7 +299,7 @@ export const toLiveExpression = (
278
299
  ): LiveExpression => {
279
300
  const atomLevel = level === 0 ? getLevel(expression, scope, environment) : level;
280
301
  if (atomLevel === 0) {
281
- const value = evaluate(expression, getConstantContext(environment, scope));
302
+ const value = evaluateConstant(expression, getConstantContext(environment, scope));
282
303
  if (typeof value !== "boolean") {
283
304
  throw new TlaEvaluationError(
284
305
  `TLC expected a boolean in the temporal formula at ${describeLocation(expression)}`,
@@ -299,9 +320,7 @@ export const toLiveExpression = (
299
320
  scope: Scope | undefined,
300
321
  ) => {
301
322
  if (expansion.depth >= MAXIMUM_EXPANSION_DEPTH) {
302
- throw new TlaEvaluationError(
303
- `TLC overflowed the stack while expanding the temporal formula at ${describeLocation(expression)}`,
304
- );
323
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
305
324
  }
306
325
  expansion.depth++;
307
326
  const result = convert(body, bodyScope);
@@ -356,9 +375,45 @@ export const toLiveExpression = (
356
375
  return level > ACTION_LEVEL ? result : toAtom(expression, scope, level);
357
376
  };
358
377
 
378
+ // TLC translates the operands of a connective even when the whole formula is a state or action
379
+ // predicate, so it fails on a constant operand before it checks any state.
380
+ const convertOperands = (expression: Expression, scope: Scope | undefined) => {
381
+ switch (expression.kind) {
382
+ case "Label":
383
+ convert(expression.body, scope);
384
+ return;
385
+ case "Let":
386
+ convert(expression.body, bindLetDefinitions(expression, scope, environment));
387
+ return;
388
+ case "And":
389
+ case "Or":
390
+ for (const operand of expression.operands) convert(operand, scope);
391
+ return;
392
+ case "Apply":
393
+ if (
394
+ expression.operator === "=>" ||
395
+ (expression.operator === "~" && !isLocallyResolved(expression))
396
+ ) {
397
+ for (const operand of expression.args) convert(operand, scope);
398
+ }
399
+ return;
400
+ case "If": {
401
+ const condition = convert(expression.condition, scope);
402
+ const branches =
403
+ condition.kind === "Boolean"
404
+ ? [condition.value ? expression.consequent : expression.alternative]
405
+ : [expression.consequent, expression.alternative];
406
+ for (const branch of branches) convert(branch, scope);
407
+ }
408
+ }
409
+ };
410
+
359
411
  const convert = (expression: Expression, scope: Scope | undefined): LiveExpression => {
360
412
  const level = getLevel(expression, scope, environment);
361
- if (level <= ACTION_LEVEL) return toAtom(expression, scope, level);
413
+ if (level <= ACTION_LEVEL) {
414
+ convertOperands(expression, scope);
415
+ return toAtom(expression, scope, level);
416
+ }
362
417
  switch (expression.kind) {
363
418
  case "Label":
364
419
  return convert(expression.body, scope);
@@ -401,7 +456,10 @@ export const toLiveExpression = (
401
456
  return convertQuantifier(expression, scope);
402
457
  case "If": {
403
458
  if (getLevel(expression.condition, scope, environment) === 0) {
404
- const condition = evaluate(expression.condition, getConstantContext(environment, scope));
459
+ const condition = evaluateConstant(
460
+ expression.condition,
461
+ getConstantContext(environment, scope),
462
+ );
405
463
  if (typeof condition === "boolean") {
406
464
  return convert(condition ? expression.consequent : expression.alternative, scope);
407
465
  }
@@ -15,7 +15,7 @@ import type {
15
15
  WorkerMessage,
16
16
  } from "./parallel";
17
17
  import { getSuccessors, type Successor } from "./successors";
18
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
18
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
19
19
  import { OUT_DEGREE_BUCKETS } from "./tlc-summary";
20
20
  import { createStateDecoder, createStateEncoder, type EncodedStates } from "./transfer";
21
21
  import { getRankedStringCount, setStringOrder, type Value } from "./values";
@@ -61,7 +61,7 @@ const run = (start: StartMessage, parent: Port) => {
61
61
  });
62
62
  const environment = specification.environment;
63
63
  const search = createSearch(start.config, environment, () =>
64
- getTlcVariableOrder(start.source, loadModule),
64
+ getTlcDeclarationOrder(start.source, loadModule, "variable"),
65
65
  );
66
66
  const nextAction = search?.spec.next;
67
67
  if (!search || nextAction === undefined)
package/src/parallel.ts CHANGED
@@ -20,7 +20,7 @@ import {
20
20
  type SharedFingerprints,
21
21
  } from "./fingerprints";
22
22
  import { getInitialStates } from "./successors";
23
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
23
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
24
24
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
25
25
  import { createStateEncoder, type EncodedStates } from "./transfer";
26
26
  import { getRankedStringCount, setStringOrder, type Value } from "./values";
@@ -150,7 +150,7 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
150
150
  });
151
151
  const environment = specification.environment;
152
152
  const search = createSearch(config, environment, () =>
153
- getTlcVariableOrder(options.source, loadModule),
153
+ getTlcDeclarationOrder(options.source, loadModule, "variable"),
154
154
  );
155
155
  if (findAssumptionViolation(specification.assumptions, environment)) return fallBack();
156
156
  if (
package/src/parser.ts CHANGED
@@ -22,7 +22,7 @@ import type {
22
22
  StepBody,
23
23
  UseOrHide,
24
24
  } from "./ast";
25
- import { TlaSyntaxError } from "./errors";
25
+ import { createSanyError, formatRange, TlaSyntaxError } from "./errors";
26
26
  import { getNumeralValue, tokenize, type Token } from "./lexer";
27
27
 
28
28
  interface InfixOperator {
@@ -631,11 +631,15 @@ const parse = (source: string, isTlapm: boolean): Module => {
631
631
  return parseExpression();
632
632
  };
633
633
 
634
+ const lastArguments: { range: SourceRange | undefined } = { range: undefined };
635
+
634
636
  const parseArguments = () =>
635
637
  withoutOffside(() => {
638
+ const start = cursor.index;
636
639
  expect("(");
637
640
  const args = parseSeparated(parseArgument);
638
641
  expect(")");
642
+ lastArguments.range = getRange(start);
639
643
  return args;
640
644
  });
641
645
 
@@ -662,9 +666,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
662
666
  if (peek().kind === "Identifier" && (isAt("|->", 1) || isAt(":", 1))) {
663
667
  const kind = isAt("|->", 1) ? "Record" : "RecordSet";
664
668
  const fields = parseSeparated(() => {
669
+ const fieldStart = cursor.index;
670
+ const fieldLocation = getLocation(peek());
665
671
  const name = expectIdentifier();
672
+ fieldLocation.range = getRange(fieldStart);
666
673
  expect(kind === "Record" ? "|->" : ":");
667
- return { name, value: parseExpression() };
674
+ return { name, value: parseExpression(), location: fieldLocation };
668
675
  });
669
676
  expect("]");
670
677
  return { kind, fields, location };
@@ -856,7 +863,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
856
863
  const args = hasArguments ? parseArguments() : [];
857
864
  if (!isSelectorAhead()) {
858
865
  return hasArguments
859
- ? { kind: "Apply", operator: name, args, location }
866
+ ? { kind: "Apply", operator: name, args, argumentsRange: lastArguments.range, location }
860
867
  : { kind: "Identifier", name, location };
861
868
  }
862
869
  const instance = openModules
@@ -885,9 +892,10 @@ const parse = (source: string, isTlapm: boolean): Module => {
885
892
  const argumentCounts = selectors.map((selector) =>
886
893
  "args" in selector ? selector.args.length : 0,
887
894
  );
895
+ const argumentsRange = lastArguments.range;
888
896
  return argumentCounts.slice(0, -1).some((count) => count > 0)
889
- ? { kind: "Apply", operator, args: qualifiedArgs, argumentCounts, location }
890
- : { kind: "Apply", operator, args: qualifiedArgs, location };
897
+ ? { kind: "Apply", operator, args: qualifiedArgs, argumentCounts, argumentsRange, location }
898
+ : { kind: "Apply", operator, args: qualifiedArgs, argumentsRange, location };
891
899
  }
892
900
  if (token.kind === "Operator" && isOperatorName(token.text) && isAt("("))
893
901
  return { kind: "Apply", operator: token.text, args: parseArguments(), location };
@@ -1423,11 +1431,14 @@ const parse = (source: string, isTlapm: boolean): Module => {
1423
1431
  location: getLocation(keyword),
1424
1432
  };
1425
1433
  const invalid =
1426
- use.kind === "Hide" && !isTlapm ? use.facts.find((fact) => !isHideFact(fact)) : undefined;
1427
- if (invalid) {
1428
- throw createError(
1429
- "The only expression allowed as a fact in a HIDE is the name of a theorem, assumption, or step",
1430
- invalid.location,
1434
+ use.kind === "Hide" && !isTlapm ? use.facts.filter((fact) => !isHideFact(fact)) : [];
1435
+ if (invalid.length > 0) {
1436
+ throw createSanyError(
1437
+ invalid.map((fact) => ({
1438
+ location: formatRange(fact.location.range ?? getRange(start)),
1439
+ message:
1440
+ "The only expression allowed as a fact in a HIDE is \nthe name of a theorem, assumption, or step.",
1441
+ })),
1431
1442
  );
1432
1443
  }
1433
1444
  return withRange(use, start);