tla-ts 0.0.3-dev.07eab97 → 0.0.3-dev.0ad0249

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 (80) hide show
  1. package/dist/cli.cjs +1 -1
  2. package/dist/cli.js +1 -1
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +160 -46
  5. package/dist/index.d.ts +160 -46
  6. package/dist/index.js +1 -1
  7. package/dist/parallel-worker.cjs +1 -1
  8. package/dist/parallel-worker.js +2 -2
  9. package/dist/parallel.cjs +1 -1
  10. package/dist/parallel.js +2 -2
  11. package/dist/run-cli.cjs +1351 -22
  12. package/dist/run-cli.js +1351 -22
  13. package/dist/transfer.cjs +83 -33
  14. package/dist/transfer.js +83 -33
  15. package/package.json +4 -1
  16. package/src/ast.ts +42 -5
  17. package/src/bags.ts +4 -7
  18. package/src/builtins.ts +29 -17
  19. package/src/bundled-modules.ts +3 -3
  20. package/src/canonical.ts +4 -3
  21. package/src/check.ts +1296 -429
  22. package/src/cli.ts +8 -1
  23. package/src/codegen.ts +68 -21
  24. package/src/config.ts +225 -206
  25. package/src/environment.ts +388 -115
  26. package/src/errors.ts +155 -18
  27. package/src/evaluate.ts +713 -259
  28. package/src/exit-codes.ts +6 -24
  29. package/src/fingerprints.ts +1 -2
  30. package/src/index.ts +1 -0
  31. package/src/instances.ts +3 -1
  32. package/src/java-overrides.ts +104 -25
  33. package/src/levels.ts +37 -27
  34. package/src/lexer.ts +14 -1
  35. package/src/live-check.ts +204 -148
  36. package/src/liveness.ts +191 -122
  37. package/src/obligation-expression.ts +2 -2
  38. package/src/obligation-source.ts +2 -0
  39. package/src/parallel-worker.ts +6 -1
  40. package/src/parallel.ts +57 -6
  41. package/src/parser.ts +369 -115
  42. package/src/pcal-ast.ts +770 -0
  43. package/src/pcal-parse.ts +1523 -0
  44. package/src/pcal-tokenize.ts +516 -0
  45. package/src/pcal-translate.ts +1230 -0
  46. package/src/pcal-validate.ts +454 -0
  47. package/src/randomization.ts +24 -7
  48. package/src/resolve.ts +1332 -453
  49. package/src/run-cli.ts +1161 -196
  50. package/src/runtime.ts +16 -0
  51. package/src/sany-builtins.ts +147 -0
  52. package/src/sany-generator.ts +3112 -0
  53. package/src/sany-levels.ts +1208 -0
  54. package/src/sany-lexer.ts +545 -0
  55. package/src/sany-linter.ts +122 -0
  56. package/src/sany-modules.ts +1398 -0
  57. package/src/sany-nodes.ts +463 -0
  58. package/src/sany-parse-error.ts +2161 -0
  59. package/src/sany-report.ts +354 -0
  60. package/src/sany-selectors.ts +738 -0
  61. package/src/sany-source.ts +248 -0
  62. package/src/sany-xml.ts +1017 -0
  63. package/src/spec-description.ts +25 -5
  64. package/src/standard-modules.ts +172 -129
  65. package/src/standard-ranges.ts +116 -0
  66. package/src/state-graph.ts +29 -6
  67. package/src/subexpressions.ts +221 -161
  68. package/src/successors.ts +141 -173
  69. package/src/symmetry.ts +168 -50
  70. package/src/tableau.ts +3 -1
  71. package/src/tlc-ext.ts +13 -17
  72. package/src/tlc-messages.ts +329 -0
  73. package/src/tlc-module.ts +49 -21
  74. package/src/tlc-modules.ts +0 -4
  75. package/src/tlc-order.ts +55 -9
  76. package/src/tlc-random.ts +28 -3
  77. package/src/tlc-replay.ts +655 -0
  78. package/src/tlc-version.ts +18 -0
  79. package/src/transfer.ts +15 -3
  80. package/src/values.ts +664 -317
package/src/parser.ts CHANGED
@@ -23,14 +23,29 @@ import type {
23
23
  UseOrHide,
24
24
  } from "./ast";
25
25
  import { createSanyError, formatRange, TlaSyntaxError } from "./errors";
26
- import { getNumeralValue, tokenize, type Token } from "./lexer";
26
+ import { getNumeralValue, readAtAsIdentifier, tokenize, type Token } from "./lexer";
27
+ import { getSanyParseError } from "./sany-parse-error";
27
28
 
28
- interface InfixOperator {
29
+ interface Precedence {
29
30
  low: number;
30
31
  high: number;
32
+ }
33
+
34
+ interface InfixOperator extends Precedence {
31
35
  isAssociative: boolean;
32
36
  }
33
37
 
38
+ // TLAplusParser.lastOp, the operator parsed last, and the operator an operand being parsed follows
39
+ // in its expression.
40
+ interface OperatorContext {
41
+ last?: Precedence;
42
+ preceding?: Precedence;
43
+ }
44
+
45
+ // SANY's precedences of a postfix operator and of the "[" of a function application.
46
+ const POSTFIX_PRECEDENCE: Precedence = { low: 15, high: 15 };
47
+ const FUNCTION_PRECEDENCE: Precedence = { low: 16, high: 16 };
48
+
34
49
  const createInfix = (low: number, high: number, isAssociative: boolean) => ({
35
50
  low,
36
51
  high,
@@ -141,6 +156,19 @@ const POSTFIX_OPERATORS = new Set(["^+", "^*", "^#"]);
141
156
 
142
157
  const PREFIX_OPERATOR_REFERENCES = new Set(["-", "~", "-."]);
143
158
 
159
+ // The prefix operators SANY reads in a definition's left-hand side, built-in ones included.
160
+ const DEFINABLE_PREFIX_OPERATORS = new Set([
161
+ "-.",
162
+ "~",
163
+ "[]",
164
+ "<>",
165
+ "ENABLED",
166
+ "UNCHANGED",
167
+ "SUBSET",
168
+ "UNION",
169
+ "DOMAIN",
170
+ ]);
171
+
144
172
  const EXPRESSION_PREFIXES = new Set([
145
173
  "-",
146
174
  "~",
@@ -169,6 +197,16 @@ const OPERATOR_ARGUMENTS = new Set([
169
197
  ...POSTFIX_OPERATORS,
170
198
  ]);
171
199
 
200
+ // A SANY InfixExpr or PostfixExpr.
201
+ const isOperatorExpression = (expression: Expression) =>
202
+ expression.kind === "Prime" ||
203
+ expression.kind === "Product" ||
204
+ ((expression.kind === "And" || expression.kind === "Or") && !expression.isBulleted) ||
205
+ (expression.kind === "Apply" &&
206
+ (expression.args.length === 2
207
+ ? INFIX_OPERATORS.has(expression.operator)
208
+ : POSTFIX_OPERATORS.has(expression.operator)));
209
+
172
210
  const isOperatorName = (text: string) =>
173
211
  INFIX_OPERATORS.has(text) || POSTFIX_OPERATORS.has(text) || text === "-.";
174
212
 
@@ -262,6 +300,7 @@ const FACT_KEYWORDS = new Set([
262
300
  "IF",
263
301
  "LAMBDA",
264
302
  "LET",
303
+ "MODULE",
265
304
  "SF_",
266
305
  "SUBSET",
267
306
  "UNCHANGED",
@@ -291,30 +330,36 @@ const BUILTIN_CONSTANTS = new Set(["TRUE", "FALSE", "BOOLEAN", "STRING"]);
291
330
 
292
331
  const NO_OFFSIDE = -1;
293
332
 
294
- const getModuleHeader = (name: string) => new RegExp(`^-{4,}\\s*MODULE\\s+${name}\\s*-{3,}$`);
295
-
296
- // The text of a module that starts on its own line in a file, as TLC's monolith extractor reads
297
- // modules that follow the root module.
333
+ // MonolithSpecExtractor.module: a module that no file defines can follow the root module in the
334
+ // root module's file, from its ---- MODULE line to the next ==== line.
298
335
  export const extractModule = (source: string, name: string) => {
336
+ const header = new RegExp(`^-{4,}\\s*MODULE\\s+${name}\\s*-{3,}$`);
299
337
  const lines = source.split(/\r?\n/);
300
- const start = lines.findIndex((line) => getModuleHeader(name).test(line));
338
+ const start = lines.findIndex((line) => header.test(line));
301
339
  if (start === -1) return undefined;
302
340
  const end = lines.findIndex((line, index) => index > start && line.startsWith("===="));
303
- return lines.slice(start, end === -1 ? undefined : end + 1).join("\n");
341
+ return `${lines.slice(start, end === -1 ? undefined : end + 1).join("\n")}\n`;
304
342
  };
305
343
 
306
- // isTlapm parses as tlapm does for proof obligations, which accepts and rejects some modules that
307
- // SANY does not.
308
- const parse = (source: string, isTlapm: boolean): Module => {
309
- const tokens = tokenize(source);
344
+ // The tlapm mode parses as tlapm does for proof obligations, which accepts and rejects some modules
345
+ // that SANY does not. The sany mode leaves the checks that SANY makes after parsing to the SANY
346
+ // generator.
347
+ type ParseMode = "tlc" | "tlapm" | "sany";
348
+
349
+ const parse = (source: string, mode: ParseMode): Module => {
350
+ const isTlapm = mode === "tlapm";
351
+ const tokens = isTlapm ? tokenize(source) : tokenize(source).map(readAtAsIdentifier);
310
352
  const cursor = { index: 0, offsideColumns: [] as number[] };
353
+ const operators: OperatorContext = {};
311
354
  // A RECURSIVE declaration covers the definitions of its own LET or module.
312
355
  const recursiveScopes: Set<string>[] = [];
313
356
  const factNames = new Set<string>();
314
357
  // The NEW, TAKE, and PICK names in scope, which a DEF clause cannot cite.
315
358
  const proofScopes: Set<string>[] = [];
316
- // A fact may cite an operator of a parameterized instance without the instance's arguments.
359
+ // A fact or an operator argument may cite an operator of a parameterized instance without the
360
+ // instance's arguments, as with Op <- I!Op in a substitution.
317
361
  const factStart = { index: -1 };
362
+ // SANY reports a location in a nested module as one in the module of its file.
318
363
  const openModules: Module[] = [];
319
364
 
320
365
  const isRecursiveName = (name: string) => recursiveScopes[recursiveScopes.length - 1].has(name);
@@ -329,15 +374,14 @@ const parse = (source: string, isTlapm: boolean): Module => {
329
374
  const tokenEnds: SourceLocation[] = [];
330
375
  const tokenRanges: SourceRange[] = [];
331
376
 
332
- const getRange = (startIndex: number) => {
333
- const endIndex = cursor.index - 1;
377
+ const getRange = (startIndex: number, endIndex = cursor.index - 1) => {
334
378
  const cached = startIndex === endIndex ? tokenRanges[startIndex] : undefined;
335
379
  if (cached) return cached;
336
380
  const last = tokens[endIndex];
337
381
  tokenStarts[startIndex] ??= getLocation(tokens[startIndex]);
338
382
  tokenEnds[endIndex] ??= { line: last.line, column: last.endColumn };
339
383
  const range = {
340
- module: openModules[openModules.length - 1].name,
384
+ module: openModules[0].name,
341
385
  start: tokenStarts[startIndex],
342
386
  end: tokenEnds[endIndex],
343
387
  };
@@ -435,8 +479,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
435
479
  const createUnexpected = (message: string, token: Token = peekRaw()) =>
436
480
  createError(message, token, token);
437
481
 
482
+ // TLAplusParser.isFieldNameToken: a keyword or an underscore names a field or a module too.
438
483
  const isFieldName = (token: Token) =>
439
- (token.kind === "Identifier" || token.kind === "Keyword") && !isTlapmKeyword(token);
484
+ (token.kind === "Identifier" ||
485
+ token.kind === "Keyword" ||
486
+ (token.kind === "Operator" && token.text === "_")) &&
487
+ !isTlapmKeyword(token);
440
488
 
441
489
  const isAt = (text: string, offset = 0) => {
442
490
  const token = peek(offset);
@@ -472,7 +520,42 @@ const parse = (source: string, isTlapm: boolean): Module => {
472
520
  return token.text;
473
521
  };
474
522
 
475
- const withoutOffside = <Result>(parse: () => Result) => {
523
+ const expectName = () => {
524
+ const start = cursor.index;
525
+ return { name: expectIdentifier(), range: getRange(start) };
526
+ };
527
+
528
+ const getNames = (names: { name: string; range: SourceRange }[]) => ({
529
+ names: names.map((item) => item.name),
530
+ ranges: names.map((item) => item.range),
531
+ });
532
+
533
+ // TLAplusParser.Substitution: an identifier, or a prefix, infix or postfix operator.
534
+ const expectSubstitutionTarget = () => {
535
+ const token = peek();
536
+ const isOperator =
537
+ token.kind !== "String" &&
538
+ (DEFINABLE_PREFIX_OPERATORS.has(token.text) ||
539
+ INFIX_OPERATORS.has(token.text) ||
540
+ POSTFIX_OPERATORS.has(token.text) ||
541
+ token.text === "'");
542
+ if (!isOperator) return expectIdentifier();
543
+ cursor.index++;
544
+ return token.text;
545
+ };
546
+
547
+ // SANY takes a keyword for the name of a module, as it does for a field.
548
+ const keywordModuleName = { isUsed: false };
549
+ const expectModuleName = () => {
550
+ if (peek().kind === "Identifier" || !isFieldName(peek())) return expectIdentifier();
551
+ keywordModuleName.isUsed = true;
552
+ return advance().text;
553
+ };
554
+
555
+ // tlapm reads a bracketed expression apart from the junction list around it, whose alignment
556
+ // SANY keeps applying.
557
+ const withBracketLayout = <Result>(parse: () => Result) => {
558
+ if (!isTlapm) return parse();
476
559
  cursor.offsideColumns.push(NO_OFFSIDE);
477
560
  const result = parse();
478
561
  cursor.offsideColumns.pop();
@@ -514,10 +597,13 @@ const parse = (source: string, isTlapm: boolean): Module => {
514
597
  };
515
598
 
516
599
  const parsePattern = (): BoundPattern => {
517
- if (!accept("<<")) return { kind: "Name", name: expectIdentifier() };
518
- const names = parseSeparated(expectIdentifier);
600
+ if (!accept("<<")) {
601
+ const named = expectName();
602
+ return { kind: "Name", name: named.name, ranges: [named.range] };
603
+ }
604
+ const names = getNames(parseSeparated(expectName));
519
605
  expect(">>");
520
- return { kind: "Tuple", names };
606
+ return { kind: "Tuple", names: names.names, ranges: names.ranges };
521
607
  };
522
608
 
523
609
  const parseBounds = () =>
@@ -560,8 +646,9 @@ const parse = (source: string, isTlapm: boolean): Module => {
560
646
  );
561
647
  };
562
648
 
649
+ // SANY's OpOrExpr reads an operator as an argument only before what ends the argument, and as
650
+ // the start of an expression, such as -.(1), otherwise.
563
651
  const isStandalone = (operator: Token) => {
564
- if (!EXPRESSION_PREFIXES.has(operator.text)) return true;
565
652
  const token = peek(1);
566
653
  return (
567
654
  token.kind === "End" ||
@@ -623,10 +710,19 @@ const parse = (source: string, isTlapm: boolean): Module => {
623
710
  if (isAt("LAMBDA")) {
624
711
  const start = cursor.index;
625
712
  advance();
626
- const params = parseSeparated(expectIdentifier);
713
+ const params = getNames(parseSeparated(expectName));
627
714
  expect(":");
628
715
  const body = parseExpression();
629
- return withRange({ kind: "Lambda", params, body, location: getLocation(token) }, start);
716
+ return withRange(
717
+ {
718
+ kind: "Lambda",
719
+ params: params.names,
720
+ paramRanges: params.ranges,
721
+ body,
722
+ location: getLocation(token),
723
+ },
724
+ start,
725
+ );
630
726
  }
631
727
  const argument = parseExpression();
632
728
  // SANY reads an argument that only names an operator of a parameterized instance, such as
@@ -640,7 +736,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
640
736
  const lastArguments: { range: SourceRange | undefined } = { range: undefined };
641
737
 
642
738
  const parseArguments = () =>
643
- withoutOffside(() => {
739
+ withBracketLayout(() => {
644
740
  const start = cursor.index;
645
741
  expect("(");
646
742
  const args = parseSeparated(parseArgument);
@@ -667,18 +763,25 @@ const parse = (source: string, isTlapm: boolean): Module => {
667
763
  };
668
764
 
669
765
  const parseBracket = (start: Token): Expression =>
670
- withoutOffside(() => {
766
+ withBracketLayout(() => {
671
767
  const location = getLocation(start);
672
- if (peek().kind === "Identifier" && (isAt("|->", 1) || isAt(":", 1))) {
673
- const kind = isAt("|->", 1) ? "Record" : "RecordSet";
674
- const fields = parseSeparated(() => {
768
+ // SANY takes a keyword for the first field of a record, as it does for a selected field.
769
+ const isIdentifier = peek().kind === "Identifier";
770
+ const isRecord = isAt("|->", 1) && (isIdentifier || isFieldName(peek()));
771
+ if (isRecord || (isIdentifier && isAt(":", 1))) {
772
+ const kind = isRecord ? "Record" : "RecordSet";
773
+ const parseField = (readName: () => string) => {
675
774
  const fieldStart = cursor.index;
676
775
  const fieldLocation = getLocation(peek());
677
- const name = expectIdentifier();
776
+ const name = readName();
678
777
  fieldLocation.range = getRange(fieldStart);
679
- expect(kind === "Record" ? "|->" : ":");
778
+ expect(isRecord ? "|->" : ":");
680
779
  return { name, value: parseExpression(), location: fieldLocation };
681
- });
780
+ };
781
+ const fields = [
782
+ parseField(() => (isIdentifier ? expectIdentifier() : advance().text)),
783
+ ...(accept(",") ? parseSeparated(() => parseField(expectIdentifier)) : []),
784
+ ];
682
785
  expect("]");
683
786
  return { kind, fields, location };
684
787
  }
@@ -716,17 +819,29 @@ const parse = (source: string, isTlapm: boolean): Module => {
716
819
  expect("]");
717
820
  return { kind: "Except", function: expression, updates, location };
718
821
  }
822
+ if (!isTlapm && !isAt("]_")) {
823
+ const args = [expression];
824
+ while (accept(",")) args.push(parseExpression());
825
+ expect("]");
826
+ return { kind: "Bracket", args, location };
827
+ }
719
828
  expect("]_");
720
- return {
721
- kind: "BoxAction",
722
- action: expression,
723
- subscript: parseSubscript(),
724
- location,
725
- };
829
+ return { kind: "BoxAction", action: expression, subscript: parseSubscript(), location };
726
830
  });
727
831
 
832
+ // SANY reads the set after the \in of {x \in S} as a whole expression, whatever operators it has.
833
+ const parseSetMembership = (): Expression => {
834
+ const start = cursor.index;
835
+ const element = withRange(parsePrefix(), start);
836
+ const location = getLocation(advance());
837
+ return withRange(
838
+ { kind: "Apply", operator: "\\in", args: [element, parseExpression()], location },
839
+ start,
840
+ );
841
+ };
842
+
728
843
  const parseBrace = (start: Token): Expression =>
729
- withoutOffside(() => {
844
+ withBracketLayout(() => {
730
845
  const location = getLocation(start);
731
846
  if (accept("}")) return { kind: "SetEnumeration", elements: [], location };
732
847
  if (isBoundAhead() && (peek(1).text === "\\in" || isAt("<<"))) {
@@ -741,7 +856,8 @@ const parse = (source: string, isTlapm: boolean): Module => {
741
856
  }
742
857
  cursor.index = checkpoint;
743
858
  }
744
- const first = parseExpression();
859
+ const first =
860
+ peek().kind === "Identifier" && isAt("\\in", 1) ? parseSetMembership() : parseExpression();
745
861
  if (accept(":")) {
746
862
  const bounds = parseBounds();
747
863
  expect("}");
@@ -755,7 +871,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
755
871
 
756
872
  const parseTuple = (start: Token): Expression => {
757
873
  const location = getLocation(start);
758
- const elements = withoutOffside(() =>
874
+ const elements = withBracketLayout(() =>
759
875
  isAt(">>") || isAt(">>_") ? [] : parseSeparated(() => parseExpression()),
760
876
  );
761
877
  if (accept(">>_")) {
@@ -776,12 +892,13 @@ const parse = (source: string, isTlapm: boolean): Module => {
776
892
  expect(":");
777
893
  return { kind, bounds, body: parseExpression(), location };
778
894
  }
779
- const names = parseSeparated(expectIdentifier);
895
+ const names = getNames(parseSeparated(expectName));
780
896
  expect(":");
781
897
  return {
782
898
  kind: "UnboundedQuantifier",
783
899
  quantifier: start.text === "\\A" || start.text === "\\AA" ? "Forall" : "Exists",
784
- names,
900
+ names: names.names,
901
+ nameRanges: names.ranges,
785
902
  body: parseExpression(),
786
903
  isTemporal,
787
904
  location,
@@ -835,7 +952,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
835
952
  return { kind: "Name", name: token.text, args: isAt("(") ? parseArguments() : [] };
836
953
  };
837
954
 
838
- const parsePrimary = (): Expression => {
955
+ const parsePrimary = (preceding?: Precedence): Expression => {
839
956
  const start = cursor.index;
840
957
  const isFactStart = start === factStart.index;
841
958
  const token = advance();
@@ -861,13 +978,34 @@ const parse = (source: string, isTlapm: boolean): Module => {
861
978
  if (token.kind === "Identifier" || isStep) {
862
979
  const name = isStep ? (getStepName(token) ?? token.text) : token.text;
863
980
  if (isLabelAhead()) {
864
- const params = accept("(") ? parseSeparated(expectIdentifier) : [];
865
- if (params.length > 0) expect(")");
981
+ const params = getNames(accept("(") ? parseSeparated(expectName) : []);
982
+ if (params.names.length > 0) expect(")");
866
983
  expect("::");
867
- return { kind: "Label", name, params, body: parseExpression(), location };
984
+ const body = parseExpression();
985
+ // TLAplusParser.labelDoesNotChangeParse.
986
+ if (
987
+ !isTlapm &&
988
+ preceding !== undefined &&
989
+ operators.last !== undefined &&
990
+ isOperatorExpression(body) &&
991
+ preceding.high >= operators.last.low
992
+ ) {
993
+ throw createError("Removing the label would change expression parsing", token);
994
+ }
995
+ return {
996
+ kind: "Label",
997
+ name,
998
+ params: params.names,
999
+ paramRanges: params.ranges,
1000
+ body,
1001
+ location,
1002
+ };
868
1003
  }
869
1004
  const hasArguments = isAt("(");
1005
+ if (name === "@" && !hasArguments && !isSelectorAhead())
1006
+ return { kind: "ExceptAt", location };
870
1007
  const args = hasArguments ? parseArguments() : [];
1008
+ const argumentRanges = [hasArguments ? lastArguments.range : undefined];
871
1009
  if (!isSelectorAhead()) {
872
1010
  return hasArguments
873
1011
  ? { kind: "Apply", operator: name, args, argumentsRange: lastArguments.range, location }
@@ -878,8 +1016,8 @@ const parse = (source: string, isTlapm: boolean): Module => {
878
1016
  .find((candidate) => candidate.name === name);
879
1017
  const isMissingArguments =
880
1018
  instance !== undefined &&
1019
+ mode === "tlc" &&
881
1020
  !isFactStart &&
882
- !isTlapm &&
883
1021
  instance.params.length !== args.length;
884
1022
  if (isMissingArguments && args.length > 0) {
885
1023
  throw createError(
@@ -888,9 +1026,13 @@ const parse = (source: string, isTlapm: boolean): Module => {
888
1026
  );
889
1027
  }
890
1028
  const selectors: Selector[] = [{ kind: "Name", name, args }];
1029
+ const selectorRanges = [getRange(start, start)];
891
1030
  while (isSelectorAhead()) {
892
1031
  advance();
1032
+ selectorRanges.push(getRange(cursor.index, cursor.index));
1033
+ lastArguments.range = undefined;
893
1034
  selectors.push(parseSelector());
1035
+ argumentRanges.push(lastArguments.range);
894
1036
  }
895
1037
  const names = selectors.flatMap((selector) =>
896
1038
  selector.kind === "Name" ? [selector.name] : [],
@@ -902,12 +1044,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
902
1044
  const argumentCounts = selectors.map((selector) =>
903
1045
  "args" in selector ? selector.args.length : 0,
904
1046
  );
905
- const argumentsRange = lastArguments.range;
1047
+ const argumentsRange = argumentRanges.findLast((range) => range !== undefined);
906
1048
  const reference: Expression =
907
1049
  names.length < selectors.length
908
- ? { kind: "Subexpression", selectors, location }
1050
+ ? { kind: "Subexpression", selectors, selectorRanges, argumentRanges, location }
909
1051
  : qualifiedArgs.length === 0
910
- ? { kind: "Identifier", name: operator, location }
1052
+ ? { kind: "Identifier", name: operator, selectorRanges, location }
911
1053
  : argumentCounts.slice(0, -1).some((count) => count > 0)
912
1054
  ? {
913
1055
  kind: "Apply",
@@ -915,9 +1057,19 @@ const parse = (source: string, isTlapm: boolean): Module => {
915
1057
  args: qualifiedArgs,
916
1058
  argumentCounts,
917
1059
  argumentsRange,
1060
+ selectorRanges,
1061
+ argumentRanges,
918
1062
  location,
919
1063
  }
920
- : { kind: "Apply", operator, args: qualifiedArgs, argumentsRange, location };
1064
+ : {
1065
+ kind: "Apply",
1066
+ operator,
1067
+ args: qualifiedArgs,
1068
+ argumentsRange,
1069
+ selectorRanges,
1070
+ argumentRanges,
1071
+ location,
1072
+ };
921
1073
  if (isMissingArguments) {
922
1074
  missingArguments.set(reference, {
923
1075
  location: formatRange(getRange(start)),
@@ -926,11 +1078,16 @@ const parse = (source: string, isTlapm: boolean): Module => {
926
1078
  }
927
1079
  return reference;
928
1080
  }
929
- if (token.kind === "Operator" && isOperatorName(token.text) && isAt("("))
1081
+ // SANY reads an infix or postfix operator as a primary expression, with or without arguments.
1082
+ if (token.kind === "Operator" && isOperatorName(token.text) && isAt("(")) {
930
1083
  return { kind: "Apply", operator: token.text, args: parseArguments(), location };
1084
+ }
1085
+ if (token.kind === "Operator" && isOperatorName(token.text) && !isTlapm) {
1086
+ return { kind: "Identifier", name: token.text, location };
1087
+ }
931
1088
  switch (token.text) {
932
1089
  case "(": {
933
- const expression = withoutOffside(() => parseExpression());
1090
+ const expression = withBracketLayout(() => parseExpression());
934
1091
  expect(")");
935
1092
  return expression;
936
1093
  }
@@ -986,7 +1143,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
986
1143
  case "WF_":
987
1144
  case "SF_": {
988
1145
  const subscript = parseSubscript();
989
- const action = withoutOffside(() => {
1146
+ const action = withBracketLayout(() => {
990
1147
  expect("(");
991
1148
  const expression = parseExpression();
992
1149
  expect(")");
@@ -1003,7 +1160,25 @@ const parse = (source: string, isTlapm: boolean): Module => {
1003
1160
  throw createUnexpected(`Unexpected ${describe(token)}`, token);
1004
1161
  };
1005
1162
 
1163
+ // SANY rejects the operator after a prefix operator's operand unless it binds looser than the
1164
+ // prefix operator.
1165
+ const parsePrefixOperand = (operator: Token, low: number, high: number) => {
1166
+ operators.last = operators.preceding = { low, high };
1167
+ const operand = parseExpression(high + 1);
1168
+ const next = peek();
1169
+ const nextHigh =
1170
+ next.text === "'" || POSTFIX_OPERATORS.has(next.text)
1171
+ ? POSTFIX_PRECEDENCE.high
1172
+ : INFIX_OPERATORS.get(next.text)?.high;
1173
+ if (!isTlapm && next.kind === "Operator" && nextHigh !== undefined && nextHigh >= low) {
1174
+ throw createError(`Precedence conflict between ${operator.text} and ${next.text}`, next);
1175
+ }
1176
+ return operand;
1177
+ };
1178
+
1006
1179
  const parsePrefix = (): Expression => {
1180
+ const preceding = operators.preceding;
1181
+ operators.preceding = undefined;
1007
1182
  const token = peek();
1008
1183
  const location = getLocation(token);
1009
1184
  if (token.kind === "Operator" && (token.text === "/\\" || token.text === "\\/")) {
@@ -1013,35 +1188,46 @@ const parse = (source: string, isTlapm: boolean): Module => {
1013
1188
  switch (token.text) {
1014
1189
  case "~":
1015
1190
  advance();
1016
- return { kind: "Apply", operator: "~", args: [parseExpression(5)], location };
1191
+ return {
1192
+ kind: "Apply",
1193
+ operator: "~",
1194
+ args: [parsePrefixOperand(token, 4, 4)],
1195
+ location,
1196
+ };
1017
1197
  case "-":
1018
1198
  advance();
1019
1199
  return {
1020
1200
  kind: "Apply",
1021
1201
  operator: "-.",
1022
- args: [parseExpression(NEGATION_PRECEDENCE + 1)],
1202
+ args: [parsePrefixOperand(token, NEGATION_PRECEDENCE, NEGATION_PRECEDENCE)],
1023
1203
  location,
1024
1204
  };
1025
1205
  case "[]":
1026
1206
  advance();
1027
- return { kind: "Always", expression: parseExpression(16), location };
1207
+ return { kind: "Always", expression: parsePrefixOperand(token, 4, 15), location };
1028
1208
  case "<>":
1029
1209
  advance();
1030
- return { kind: "Eventually", expression: parseExpression(16), location };
1210
+ return { kind: "Eventually", expression: parsePrefixOperand(token, 4, 15), location };
1031
1211
  case "ENABLED":
1032
1212
  advance();
1033
- return { kind: "Enabled", expression: parseExpression(16), location };
1213
+ return { kind: "Enabled", expression: parsePrefixOperand(token, 4, 15), location };
1034
1214
  case "UNCHANGED":
1035
1215
  advance();
1036
- return { kind: "Unchanged", expression: parseExpression(16), location };
1216
+ return { kind: "Unchanged", expression: parsePrefixOperand(token, 4, 15), location };
1037
1217
  case "SUBSET":
1038
1218
  case "UNION":
1039
1219
  case "DOMAIN":
1040
1220
  advance();
1041
- return { kind: "Apply", operator: token.text, args: [parseExpression(9)], location };
1221
+ return {
1222
+ kind: "Apply",
1223
+ operator: token.text,
1224
+ // tlapm gives these operators the precedence 8 of the TLA+ book, and SANY 10-13.
1225
+ args: [isTlapm ? parseExpression(9) : parsePrefixOperand(token, 10, 13)],
1226
+ location,
1227
+ };
1042
1228
  }
1043
1229
  }
1044
- return parsePrimary();
1230
+ return parsePrimary(preceding);
1045
1231
  };
1046
1232
 
1047
1233
  const parseExpression = (minimumPrecedence = 0): Expression => {
@@ -1057,11 +1243,13 @@ const parse = (source: string, isTlapm: boolean): Module => {
1057
1243
  const location = getLocation(token);
1058
1244
  if (token.text === "'" && minimumPrecedence <= 15) {
1059
1245
  advance();
1246
+ operators.last = POSTFIX_PRECEDENCE;
1060
1247
  state.left = withRange({ kind: "Prime", expression: state.left, location }, start);
1061
1248
  continue;
1062
1249
  }
1063
1250
  if (POSTFIX_OPERATORS.has(token.text) && minimumPrecedence <= 15) {
1064
1251
  advance();
1252
+ operators.last = POSTFIX_PRECEDENCE;
1065
1253
  state.left = withRange(
1066
1254
  { kind: "Apply", operator: token.text, args: [state.left], location },
1067
1255
  start,
@@ -1070,8 +1258,9 @@ const parse = (source: string, isTlapm: boolean): Module => {
1070
1258
  }
1071
1259
  if (token.text === "[") {
1072
1260
  advance();
1073
- const args = withoutOffside(() => parseSeparated(() => parseExpression()));
1074
- withoutOffside(() => expect("]"));
1261
+ const args = withBracketLayout(() => parseSeparated(() => parseExpression()));
1262
+ withBracketLayout(() => expect("]"));
1263
+ operators.last = FUNCTION_PRECEDENCE;
1075
1264
  state.left = withRange(
1076
1265
  { kind: "FunctionApplication", function: state.left, args, location },
1077
1266
  start,
@@ -1102,14 +1291,20 @@ const parse = (source: string, isTlapm: boolean): Module => {
1102
1291
  if (infix.low > NEGATION_PRECEDENCE && isAt("-")) {
1103
1292
  throw createError(`Precedence conflict between ${token.text} and -`, peek());
1104
1293
  }
1294
+ operators.last = operators.preceding = infix;
1105
1295
  const right = parseExpression(infix.high + 1);
1106
1296
  const left = state.left;
1107
1297
  if (token.text === "/\\" || token.text === "\\/") {
1108
1298
  const kind = token.text === "/\\" ? "And" : "Or";
1299
+ const prefixEnds = [getRange(start).end];
1109
1300
  state.left =
1110
1301
  left.kind === kind && previous?.text === token.text
1111
- ? { ...left, operands: [...left.operands, right] }
1112
- : { kind, operands: [left, right], location };
1302
+ ? {
1303
+ ...left,
1304
+ operands: [...left.operands, right],
1305
+ prefixEnds: [...(left.prefixEnds ?? []), ...prefixEnds],
1306
+ }
1307
+ : { kind, operands: [left, right], prefixEnds, location };
1113
1308
  } else if (token.text === "\\X") {
1114
1309
  state.left =
1115
1310
  left.kind === "Product" && previous?.text === "\\X"
@@ -1136,7 +1331,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1136
1331
  const body = parseExpression();
1137
1332
  const last = tokens[cursor.index - 1];
1138
1333
  const end = { line: last.line, column: last.endColumn };
1139
- return { body, bodyRange: { module: openModules[openModules.length - 1].name, start, end } };
1334
+ return { body, bodyRange: { module: openModules[0].name, start, end } };
1140
1335
  };
1141
1336
 
1142
1337
  const parseDefinition = (isLocal: boolean): Definition | Instance => {
@@ -1144,6 +1339,16 @@ const parse = (source: string, isTlapm: boolean): Module => {
1144
1339
  return withRange(parseDefinitionUnit(isLocal), start);
1145
1340
  };
1146
1341
 
1342
+ const toParam = (named: { name: string; range: SourceRange }): OperatorParam => ({
1343
+ name: named.name,
1344
+ arity: 0,
1345
+ location: {
1346
+ line: named.range.start.line,
1347
+ column: named.range.start.column,
1348
+ range: named.range,
1349
+ },
1350
+ });
1351
+
1147
1352
  const parseDefinitionUnit = (isLocal: boolean): Definition | Instance => {
1148
1353
  const token = peek();
1149
1354
  const location = getLocation(token);
@@ -1163,28 +1368,27 @@ const parse = (source: string, isTlapm: boolean): Module => {
1163
1368
  peek(2).kind === "Identifier" &&
1164
1369
  isAt("==", 3)
1165
1370
  ) {
1166
- const left = expectIdentifier();
1371
+ const left = expectName();
1167
1372
  const operator = advance().text;
1168
- const right = expectIdentifier();
1373
+ const right = expectName();
1169
1374
  expect("==");
1170
- return parseOperator(operator, [
1171
- { name: left, arity: 0 },
1172
- { name: right, arity: 0 },
1173
- ]);
1375
+ return parseOperator(operator, [toParam(left), toParam(right)]);
1174
1376
  }
1175
- const isPrefixDefinition = token.kind === "Operator" && token.text === "-.";
1377
+ const isPrefixDefinition =
1378
+ token.kind !== "String" && DEFINABLE_PREFIX_OPERATORS.has(token.text);
1176
1379
  const isPostfixDefinition =
1177
1380
  token.kind === "Identifier" && POSTFIX_OPERATORS.has(peek(1).text) && isAt("==", 2);
1178
1381
  if (isPrefixDefinition || isPostfixDefinition) {
1179
1382
  const operator = isPrefixDefinition ? token.text : peek(1).text;
1180
- cursor.index += isPrefixDefinition ? 1 : 2;
1181
- const param = isPrefixDefinition ? expectIdentifier() : token.text;
1383
+ if (isPrefixDefinition) advance();
1384
+ const param = expectName();
1385
+ if (isPostfixDefinition) advance();
1182
1386
  expect("==");
1183
- return parseOperator(operator, [{ name: param, arity: 0 }]);
1387
+ return parseOperator(operator, [toParam(param)]);
1184
1388
  }
1185
1389
  const name = expectIdentifier();
1186
1390
  if (accept("[")) {
1187
- const bounds = withoutOffside(() => parseBounds());
1391
+ const bounds = withBracketLayout(() => parseBounds());
1188
1392
  expect("]");
1189
1393
  expect("==");
1190
1394
  return {
@@ -1215,12 +1419,14 @@ const parse = (source: string, isTlapm: boolean): Module => {
1215
1419
  ): Instance => {
1216
1420
  const start = cursor.index;
1217
1421
  expect("INSTANCE");
1218
- const module = expectIdentifier();
1422
+ const module = expectModuleName();
1219
1423
  const substitutions = accept("WITH")
1220
1424
  ? parseSeparated(() => {
1221
- const target = advance().text;
1425
+ const targetStart = cursor.index;
1426
+ const target = expectSubstitutionTarget();
1427
+ const nameRange = getRange(targetStart);
1222
1428
  expect("<-");
1223
- return { name: target, expression: parseArgument() };
1429
+ return { name: target, nameRange, expression: parseArgument() };
1224
1430
  })
1225
1431
  : [];
1226
1432
  return {
@@ -1236,6 +1442,11 @@ const parse = (source: string, isTlapm: boolean): Module => {
1236
1442
  };
1237
1443
 
1238
1444
  const parseDeclaration = (): Declaration => {
1445
+ const start = cursor.index;
1446
+ return withRange(parseDeclarationUnit(), start);
1447
+ };
1448
+
1449
+ const parseDeclarationUnit = (): Declaration => {
1239
1450
  const location = getLocation(peek());
1240
1451
  if (isAt("_") && peek(1).kind === "Operator") {
1241
1452
  advance();
@@ -1281,7 +1492,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
1281
1492
  const token = peek();
1282
1493
  const next = peek(1);
1283
1494
  if (token.kind !== "Identifier") {
1284
- return isAt("-.") && next.kind === "Identifier" && isAt("==", 2);
1495
+ return (
1496
+ token.kind !== "String" &&
1497
+ DEFINABLE_PREFIX_OPERATORS.has(token.text) &&
1498
+ next.kind === "Identifier" &&
1499
+ isAt("==", 2)
1500
+ );
1285
1501
  }
1286
1502
  if (isAt("(", 1) || isAt("[", 1)) return isAt("==", getClosingOffset(1));
1287
1503
  if (next.kind === "Operator" && POSTFIX_OPERATORS.has(next.text)) return isAt("==", 2);
@@ -1435,7 +1651,10 @@ const parse = (source: string, isTlapm: boolean): Module => {
1435
1651
  const parseDefs = () => {
1436
1652
  if (isTlapm) return parseSeparated(parseDefinable);
1437
1653
  const defs = parseSeparated(parseFact);
1438
- const invalid = defs.find((def) => def.kind === "Identifier" && isDeclaredSymbol(def.name));
1654
+ const invalid =
1655
+ mode === "tlc"
1656
+ ? defs.find((def) => def.kind === "Identifier" && isDeclaredSymbol(def.name))
1657
+ : undefined;
1439
1658
  if (invalid) {
1440
1659
  throw createError("DEF clause entry should describe a defined operator", invalid.location);
1441
1660
  }
@@ -1460,7 +1679,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1460
1679
  location: getLocation(keyword),
1461
1680
  };
1462
1681
  const invalid =
1463
- use.kind === "Hide" && !isTlapm ? use.facts.filter((fact) => !isHideFact(fact)) : [];
1682
+ use.kind === "Hide" && mode === "tlc" ? use.facts.filter((fact) => !isHideFact(fact)) : [];
1464
1683
  if (invalid.length > 0) {
1465
1684
  throw createSanyError(
1466
1685
  invalid.map((fact) => ({
@@ -1483,10 +1702,18 @@ const parse = (source: string, isTlapm: boolean): Module => {
1483
1702
  }
1484
1703
  if (level !== undefined) advance();
1485
1704
  if (level === "Variable") {
1486
- const name = expectIdentifier();
1487
- declareProofSymbol(name);
1705
+ const named = expectName();
1706
+ declareProofSymbol(named.name);
1488
1707
  return withRange(
1489
- { kind: "NewSymbol", name, arity: 0, level, set: undefined, location },
1708
+ {
1709
+ kind: "NewSymbol",
1710
+ name: named.name,
1711
+ arity: 0,
1712
+ level,
1713
+ set: undefined,
1714
+ nameRange: named.range,
1715
+ location,
1716
+ },
1490
1717
  start,
1491
1718
  );
1492
1719
  }
@@ -1504,6 +1731,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1504
1731
  arity: declaration.arity,
1505
1732
  level: level ?? "Constant",
1506
1733
  set: isBounded ? parseExpression() : undefined,
1734
+ nameRange: declaration.location.range,
1507
1735
  location,
1508
1736
  },
1509
1737
  start,
@@ -1546,7 +1774,8 @@ const parse = (source: string, isTlapm: boolean): Module => {
1546
1774
  const token = peek();
1547
1775
  if (isAt("USE") || isAt("HIDE")) return parseUseOrHide();
1548
1776
  if (isAt("INSTANCE")) {
1549
- return withRange(parseInstance(undefined, [], false, getLocation(token)), cursor.index);
1777
+ const start = cursor.index;
1778
+ return withRange(parseInstance(undefined, [], false, getLocation(token)), start);
1550
1779
  }
1551
1780
  if (isAt("DEFINE") || isDefinitionStart()) {
1552
1781
  const start = cursor.index;
@@ -1559,21 +1788,27 @@ const parse = (source: string, isTlapm: boolean): Module => {
1559
1788
  if (accept("HAVE")) return { kind: "Have", expression: parseExpression() };
1560
1789
  if (accept("TAKE")) {
1561
1790
  const isBounded = isBoundAhead();
1562
- const names = isBounded ? [] : parseSeparated(expectIdentifier);
1791
+ const names = getNames(isBounded ? [] : parseSeparated(expectName));
1563
1792
  const bounds = isBounded ? parseBounds() : [];
1564
- declareProofSymbols(names, bounds);
1565
- return { kind: "Take", names, bounds };
1793
+ declareProofSymbols(names.names, bounds);
1794
+ return { kind: "Take", names: names.names, nameRanges: names.ranges, bounds };
1566
1795
  }
1567
1796
  if (accept("WITNESS")) {
1568
1797
  return { kind: "Witness", expressions: parseSeparated(() => parseExpression()) };
1569
1798
  }
1570
1799
  if (accept("PICK")) {
1571
1800
  const isNames = isNameListAhead(":");
1572
- const names = isNames ? parseSeparated(expectIdentifier) : [];
1801
+ const names = getNames(isNames ? parseSeparated(expectName) : []);
1573
1802
  const bounds = isNames ? [] : parseBounds();
1574
- declareProofSymbols(names, bounds);
1803
+ declareProofSymbols(names.names, bounds);
1575
1804
  expect(":");
1576
- return { kind: "Pick", names, bounds, body: parseExpression() };
1805
+ return {
1806
+ kind: "Pick",
1807
+ names: names.names,
1808
+ nameRanges: names.ranges,
1809
+ bounds,
1810
+ body: parseExpression(),
1811
+ };
1577
1812
  }
1578
1813
  if (accept("CASE")) return { kind: "Case", expression: parseExpression() };
1579
1814
  return {
@@ -1651,6 +1886,13 @@ const parse = (source: string, isTlapm: boolean): Module => {
1651
1886
  return withRange(proof, start);
1652
1887
  };
1653
1888
 
1889
+ // SANY binds the name of a theorem or assumption that a module already defines to the first
1890
+ // definition, warning of the second.
1891
+ const addFactDefinition = (module: Module, definition: Definition) => {
1892
+ if (module.definitions.some((other) => other.name === definition.name)) return;
1893
+ module.definitions.push(definition);
1894
+ };
1895
+
1654
1896
  const parseTheorem = (module: Module) => {
1655
1897
  const start = cursor.index;
1656
1898
  const keyword = advance();
@@ -1672,7 +1914,8 @@ const parse = (source: string, isTlapm: boolean): Module => {
1672
1914
  module.theorems.push(theorem);
1673
1915
  module.units.push({ kind: "Theorem", theorem });
1674
1916
  if (name === undefined || statement.kind === "AssumeProve") return;
1675
- module.definitions.push(
1917
+ addFactDefinition(
1918
+ module,
1676
1919
  withRange(
1677
1920
  {
1678
1921
  kind: "Operator",
@@ -1709,7 +1952,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1709
1952
  const parseModuleBody = (): Module => {
1710
1953
  const location = getLocation(expect("----"));
1711
1954
  expect("MODULE");
1712
- const name = expectIdentifier();
1955
+ const name = expectModuleName();
1713
1956
  expect("----");
1714
1957
  const module: Module = {
1715
1958
  name,
@@ -1731,7 +1974,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1731
1974
  if (accept("EXTENDS")) {
1732
1975
  parseSeparated(() => {
1733
1976
  const start = cursor.index;
1734
- module.extends.push(expectIdentifier());
1977
+ module.extends.push(expectModuleName());
1735
1978
  module.extendsRanges.push(getRange(start));
1736
1979
  });
1737
1980
  }
@@ -1739,14 +1982,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
1739
1982
  const tokenIndex = cursor.index;
1740
1983
  unitStart.index = tokenIndex;
1741
1984
  const token = peek();
1742
- if (token.kind === "ModuleEnd" || token.kind === "End") {
1743
- if (token.kind === "ModuleEnd") {
1744
- location.range = {
1745
- module: name,
1746
- start: { line: location.line, column: location.column },
1747
- end: { line: token.line, column: token.endColumn },
1748
- };
1749
- }
1985
+ if (token.kind === "ModuleEnd") {
1986
+ location.range = {
1987
+ module: openModules[0].name,
1988
+ start: { line: location.line, column: location.column },
1989
+ end: { line: token.line, column: token.endColumn },
1990
+ };
1750
1991
  if (missingArguments.size > 0) throw createSanyError([...missingArguments.values()]);
1751
1992
  openModules.pop();
1752
1993
  recursiveScopes.pop();
@@ -1766,22 +2007,24 @@ const parse = (source: string, isTlapm: boolean): Module => {
1766
2007
  switch (token.text) {
1767
2008
  case "CONSTANT":
1768
2009
  case "CONSTANTS": {
1769
- advance();
2010
+ const unitLocation = getLocation(advance());
1770
2011
  const declarations = parseDeclarations();
1771
2012
  module.constants.push(...declarations);
1772
- module.units.push({ kind: "Constants", declarations });
2013
+ unitLocation.range = getRange(tokenIndex);
2014
+ module.units.push({ kind: "Constants", declarations, location: unitLocation });
1773
2015
  continue;
1774
2016
  }
1775
2017
  case "VARIABLE":
1776
2018
  case "VARIABLES": {
1777
- advance();
2019
+ const unitLocation = getLocation(advance());
1778
2020
  const declarations = parseSeparated(() => {
1779
2021
  const start = cursor.index;
1780
2022
  const location = getLocation(peek());
1781
2023
  return withRange({ name: expectIdentifier(), arity: 0, location }, start);
1782
2024
  });
1783
2025
  module.variables.push(...declarations);
1784
- module.units.push({ kind: "Variables", declarations });
2026
+ unitLocation.range = getRange(tokenIndex);
2027
+ module.units.push({ kind: "Variables", declarations, location: unitLocation });
1785
2028
  continue;
1786
2029
  }
1787
2030
  case "ASSUME":
@@ -1791,7 +2034,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1791
2034
  module.assumptions.push(assumption);
1792
2035
  module.units.push({ kind: "Assumption", assumption });
1793
2036
  if (assumption.name !== undefined) {
1794
- module.definitions.push({
2037
+ addFactDefinition(module, {
1795
2038
  kind: "Operator",
1796
2039
  name: assumption.name,
1797
2040
  params: [],
@@ -1805,6 +2048,10 @@ const parse = (source: string, isTlapm: boolean): Module => {
1805
2048
  }
1806
2049
  case "USE":
1807
2050
  case "HIDE": {
2051
+ // SANY's module body takes a USE only when ONLY doesn't follow it.
2052
+ if (isAt("USE") && isAt("ONLY", 1)) {
2053
+ throw createUnexpected(`Expected a module unit but found ${describe(token)}`);
2054
+ }
1808
2055
  const use = parseUseOrHide();
1809
2056
  module.uses.push(use);
1810
2057
  module.units.push({ kind: "Use", use });
@@ -1829,7 +2076,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1829
2076
  );
1830
2077
  continue;
1831
2078
  }
1832
- addDefinitionUnit(module, parseDefinition(true));
2079
+ addDefinitionUnit(module, withRange(parseDefinitionUnit(true), tokenIndex));
1833
2080
  continue;
1834
2081
  }
1835
2082
  }
@@ -1851,9 +2098,16 @@ const parse = (source: string, isTlapm: boolean): Module => {
1851
2098
  module.units.push({ kind: "Definition", definition: unit });
1852
2099
  };
1853
2100
 
1854
- return parseModuleBody();
2101
+ const module = parseModuleBody();
2102
+ // SANY's lexer marks where each definition begins before its parser runs, which can split a
2103
+ // module's name from a keyword that the parser would take for one.
2104
+ const sanyError = keywordModuleName.isUsed ? getSanyParseError(source) : undefined;
2105
+ if (sanyError !== undefined) throw new TlaSyntaxError(sanyError);
2106
+ return module;
1855
2107
  };
1856
2108
 
1857
- export const parseModule = (source: string) => parse(source, false);
2109
+ export const parseModule = (source: string) => parse(source, "tlc");
2110
+
2111
+ export const parseTlapmModule = (source: string) => parse(source, "tlapm");
1858
2112
 
1859
- export const parseTlapmModule = (source: string) => parse(source, true);
2113
+ export const parseSanyModule = (source: string) => parse(source, "sany");