tla-ts 0.0.3-dev.037ac3b → 0.0.3-dev.19a7038

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,
@@ -49,13 +50,17 @@ interface Check {
49
50
  actionIds: Int32Array;
50
51
  nodeStates: number[];
51
52
  nodeTableaux: number[];
52
- successors: number[][];
53
- actions: Uint8Array[];
54
- stateResults: Uint8Array[];
55
- 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 };
56
62
  initial: number[];
57
- nodeIds: Map<number, number>;
58
- nodesByState: Map<number, number[]>;
63
+ nodeIds: NodeTable;
59
64
  isDone: boolean[];
60
65
  errorNode: number | undefined;
61
66
  }
@@ -70,13 +75,45 @@ const removeRepeats = (path: number[]) =>
70
75
  const pushNode = (check: Check, state: number, tableauNode: number) => {
71
76
  check.nodeStates.push(state);
72
77
  check.nodeTableaux.push(tableauNode);
73
- check.successors.push([]);
74
- check.actions.push(new Uint8Array(0));
75
- check.stateResults.push(new Uint8Array(0));
76
- check.isWritten.push(false);
78
+ check.pending.push(undefined);
79
+ check.offsets.push(-1);
80
+ check.edgeOffsets.push(-1);
77
81
  return check.nodeStates.length - 1;
78
82
  };
79
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
+
80
117
  const SUCCESSOR_CAPACITY = 16;
81
118
 
82
119
  const SCC_MARKER = -42;
@@ -103,7 +140,10 @@ export const createLivenessChecker = (
103
140
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
104
141
  const solutions = getSolutions(formula);
105
142
  if (solutions.length === 0) {
106
- throw new TlaEvaluationError(TAUTOLOGY_MESSAGE);
143
+ throw setExitCode(
144
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
145
+ EXIT_STATUS.livenessEvaluationFailure,
146
+ );
107
147
  }
108
148
  const actionIds = new Map<string, number>();
109
149
  const checks = solutions.map((solution): Check => ({
@@ -116,13 +156,13 @@ export const createLivenessChecker = (
116
156
  }),
117
157
  nodeStates: [],
118
158
  nodeTableaux: [],
119
- successors: [],
120
- actions: [],
121
- stateResults: [],
122
- isWritten: [],
159
+ pending: [],
160
+ offsets: [],
161
+ results: { bytes: new Uint8Array(1024), length: 0 },
162
+ edgeOffsets: [],
163
+ edges: { ids: new Int32Array(1024), length: 0 },
123
164
  initial: [],
124
- nodeIds: new Map(),
125
- nodesByState: new Map(),
165
+ nodeIds: { slots: new Int32Array(3 << 10), size: 0, shift: 22 },
126
166
  isDone: [],
127
167
  errorNode: undefined,
128
168
  }));
@@ -208,18 +248,35 @@ export const createLivenessChecker = (
208
248
  model.infinitelyOftenActions.length === 0,
209
249
  );
210
250
 
211
- const getNodeId = (check: Check, state: number, tableauNode: number) =>
212
- check.solution.tableau
213
- ? check.nodeIds.get(state * check.solution.tableau.nodes.length + tableauNode)
214
- : 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
+ };
215
257
  const recordNode = (check: Check, state: number, tableauNode: number) => {
216
258
  const node = pushNode(check, state, tableauNode);
217
- check.nodeIds.set(state * (check.solution.tableau?.nodes.length ?? 1) + tableauNode, node);
218
- const siblings = check.nodesByState.get(state);
219
- if (siblings) siblings.push(node);
220
- 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));
221
273
  return node;
222
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);
223
280
  const writeNode = (
224
281
  check: Check,
225
282
  node: number,
@@ -227,11 +284,32 @@ export const createLivenessChecker = (
227
284
  stateResults: Uint8Array,
228
285
  ) => {
229
286
  const actionCount = check.solution.actionChecks.length;
230
- const packed = new Uint8Array(actions.length * actionCount);
231
- actions.forEach((results, position) => packed.set(results, position * actionCount));
232
- check.actions[node] = packed;
233
- check.stateResults[node] = stateResults;
234
- 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;
235
313
  };
236
314
 
237
315
  // TLC collects a state's successors and the state itself in a SetOfStates, a hash set it
@@ -284,7 +362,7 @@ export const createLivenessChecker = (
284
362
  const stateResults = checkState(check, index, state);
285
363
  const tableauNode = tableau.nodes[check.nodeTableaux[node]];
286
364
  const actions: Uint8Array[] = [];
287
- const successors = check.successors[node];
365
+ const successors = getPending(check, node);
288
366
  const selfActions =
289
367
  tableauNode.successors.length > 0
290
368
  ? checkAction(check, index, state, state)
@@ -333,8 +411,8 @@ export const createLivenessChecker = (
333
411
  );
334
412
  check.isDone[index] = true;
335
413
  // TLC expands the nodes recorded before the loop, not the ones the loop records.
336
- for (const node of (check.nodesByState.get(index) ?? []).slice()) {
337
- const successors = check.successors[node];
414
+ for (const node of getStateNodes(check, tableau, index)) {
415
+ const successors = getPending(check, node);
338
416
  const actions: Uint8Array[] = [];
339
417
  set.forEach((successor, position) => {
340
418
  const isDone = check.isDone[successor.index] === true;
@@ -368,10 +446,10 @@ export const createLivenessChecker = (
368
446
  index: number,
369
447
  ) => {
370
448
  while (check.nodeStates.length <= index) pushNode(check, check.nodeStates.length, -1);
371
- const successors = check.successors[index];
449
+ const successors = getPending(check, index);
372
450
  const actions: Uint8Array[] = [];
373
451
  set.forEach((successor, position) => {
374
- if (check.isWritten[successor.index] && successors.includes(successor.index)) return;
452
+ if (isWritten(check, successor.index) && successors.includes(successor.index)) return;
375
453
  successors.push(successor.index);
376
454
  actions.push(actionResults[position]);
377
455
  });
@@ -385,20 +463,20 @@ export const createLivenessChecker = (
385
463
  const parents = new Map<number, number>();
386
464
  const queue: number[] = [];
387
465
  for (const node of check.initial) {
388
- if (!check.isWritten[node]) continue;
466
+ if (!isWritten(check, node)) continue;
389
467
  queue.push(node);
390
468
  parents.set(node, -1);
391
469
  }
392
470
  for (let position = 0; position < queue.length; position++) {
393
471
  const current = queue[position];
394
- for (const next of check.successors[current]) {
472
+ for (const next of getSuccessors(check, current)) {
395
473
  if (next === current && check.solution.tableau) continue;
396
474
  if (next === target) {
397
475
  const path = [target];
398
476
  for (let node = current; node !== -1; node = parents.get(node) ?? -1) path.push(node);
399
477
  return path;
400
478
  }
401
- if (!check.isWritten[next] || parents.has(next)) continue;
479
+ if (!isWritten(check, next) || parents.has(next)) continue;
402
480
  parents.set(next, current);
403
481
  queue.push(next);
404
482
  }
@@ -410,16 +488,17 @@ export const createLivenessChecker = (
410
488
  const findInModel = (check: Check, model: Solution["models"][number]): Lasso | undefined => {
411
489
  const solution = check.solution;
412
490
  const actionCount = solution.actionChecks.length;
491
+ const stateCount = solution.stateChecks.length;
413
492
  const getAction = (node: number, edge: number, position: number) =>
414
- check.actions[node][edge * actionCount + position] === 1;
493
+ check.results.bytes[check.offsets[node] + stateCount + edge * actionCount + position] === 1;
415
494
  const isAllowed = (node: number, edge: number) =>
416
495
  model.eventuallyAlways.every((position) => getAction(node, edge, position));
417
496
  const links = new Float64Array(check.nodeStates.length).fill(UNVISITED);
418
- const queue = check.initial.filter((node) => check.isWritten[node]);
497
+ const queue = check.initial.filter((node) => isWritten(check, node));
419
498
  const components: number[] = [];
420
499
 
421
500
  const isStuttering = (node: number) => {
422
- const edge = check.successors[node].indexOf(node);
501
+ const edge = getSuccessors(check, node).indexOf(node);
423
502
  return edge !== -1 && isAllowed(node, edge);
424
503
  };
425
504
  const isFulfilled = (node: number, promise: Solution["promises"][number]) =>
@@ -443,11 +522,11 @@ export const createLivenessChecker = (
443
522
  if (member === root) break;
444
523
  }
445
524
  const isStateSatisfied = model.infinitelyOftenStates.every((position) =>
446
- [...members].some((node) => check.stateResults[node][position] === 1),
525
+ [...members].some((node) => getStateResult(check, node, position)),
447
526
  );
448
527
  const isActionSatisfied = model.infinitelyOftenActions.every((position) =>
449
528
  [...members].some((node) =>
450
- check.successors[node].some(
529
+ getSuccessors(check, node).some(
451
530
  (next, edge) =>
452
531
  members.has(next) && isAllowed(node, edge) && getAction(node, edge, position),
453
532
  ),
@@ -488,7 +567,7 @@ export const createLivenessChecker = (
488
567
  const countAtStart = remaining.count;
489
568
  while (true) {
490
569
  model.infinitelyOftenStates.forEach((position, slot) => {
491
- if (!stateDone[slot] && check.stateResults[current.node][position] === 1) {
570
+ if (!stateDone[slot] && getStateResult(check, current.node, position)) {
492
571
  stateDone[slot] = true;
493
572
  remaining.count--;
494
573
  }
@@ -502,7 +581,7 @@ export const createLivenessChecker = (
502
581
  if (remaining.count <= 0) break;
503
582
  const step = { last: -1, unvisited: -1 };
504
583
  const countBeforeActions = remaining.count;
505
- const successors = check.successors[current.node];
584
+ const successors = getSuccessors(check, current.node);
506
585
  const taken = successors.some((next, edge) => {
507
586
  if (membersByState.has(check.nodeStates[next])) {
508
587
  if (!isMember(next) || !isAllowed(current.node, edge)) return false;
@@ -537,7 +616,8 @@ export const createLivenessChecker = (
537
616
  }
538
617
  current.node = previous;
539
618
  step.unvisited =
540
- check.successors[previous].find((next) => isMember(next) && !seen.has(next)) ?? -1;
619
+ getSuccessors(check, previous).find((next) => isMember(next) && !seen.has(next)) ??
620
+ -1;
541
621
  }
542
622
  take(step.unvisited);
543
623
  seen.add(step.unvisited);
@@ -567,7 +647,7 @@ export const createLivenessChecker = (
567
647
  const queue: [number, number][] = [];
568
648
  for (let state = start, parent = -1, position = 0; ; position++) {
569
649
  for (const node of membersByState.get(state) ?? []) {
570
- for (const [edge, next] of check.successors[node].entries()) {
650
+ for (const [edge, next] of getSuccessors(check, node).entries()) {
571
651
  if (next === node || !isAllowedEdge(node, edge)) continue;
572
652
  if (next === root) {
573
653
  const path: number[] = [];
@@ -620,8 +700,8 @@ export const createLivenessChecker = (
620
700
  stack.push(lowLink, node, SCC_MARKER);
621
701
  components.push(node);
622
702
  const nextLowLink = { value: counter.link++ };
623
- check.successors[node].forEach((next, edge) => {
624
- if (!check.isWritten[next]) return;
703
+ getSuccessors(check, node).forEach((next, edge) => {
704
+ if (!isWritten(check, next)) return;
625
705
  if (!isAllowed(node, edge)) {
626
706
  if (links[next] === UNVISITED) queue.push(next);
627
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);