tla-ts 0.0.3-dev.33ae522 → 0.0.3-dev.3539317

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/evaluate.ts CHANGED
@@ -35,6 +35,7 @@ import {
35
35
  getDomain,
36
36
  getFunctionDomain,
37
37
  getIntervalElements,
38
+ getLazySubsets,
38
39
  getSequenceElements,
39
40
  getValueHash,
40
41
  isFunctionValue,
@@ -342,9 +343,8 @@ export const getEnumeratedElements = (set: Value, expression: Expression) => {
342
343
  : `TLC encountered the non-enumerable quantifier bound\n${text}\n${describeRange(expression)}\n${explanation}`,
343
344
  );
344
345
  }
345
- return typeof set === "object" && set.kind === "Interval"
346
- ? getIntervalElements(set)
347
- : toFiniteSet(set).elements;
346
+ if (typeof set === "object" && set.kind === "Interval") return getIntervalElements(set);
347
+ return getLazySubsets(set) ?? toFiniteSet(set).elements;
348
348
  };
349
349
 
350
350
  export const forEachBinding = (
@@ -1,4 +1,4 @@
1
- import { getValueFingerprint, getValueHash, type Value } from "./values";
1
+ import { assertFingerprintable, getValueFingerprint, getValueHash, type Value } from "./values";
2
2
 
3
3
  const EMPTY = 0;
4
4
  const INITIAL_CAPACITY = 1 << 12;
@@ -20,6 +20,7 @@ export const writeStateFingerprint = (state: Value[], fingerprint: Int32Array) =
20
20
  first = Math.imul(first ^ getValueHash(state[index]), 0x01000193);
21
21
  second = Math.imul(second ^ getValueFingerprint(state[index]), 0x5bd1e995);
22
22
  }
23
+ assertFingerprintable(state);
23
24
  fingerprint[0] = mix(first) || 1;
24
25
  fingerprint[1] = mix(second);
25
26
  };
package/src/instances.ts CHANGED
@@ -705,7 +705,7 @@ const expandLetInstances = (
705
705
  const index = position === -1 ? current.length : position;
706
706
  return [...current.slice(0, index), ...instantiate(instance, inner), ...current.slice(index)];
707
707
  }, mapped.definitions);
708
- return { kind: "Let", definitions, body: mapped.body, location: mapped.location };
708
+ return { ...mapped, definitions };
709
709
  };
710
710
 
711
711
  // A named theorem's statement is linked as its definition.
package/src/levels.ts CHANGED
@@ -5,8 +5,17 @@ import {
5
5
  type Expression,
6
6
  type Module,
7
7
  type OperatorParam,
8
+ type Proof,
9
+ type ProofStep,
10
+ type SourceLocation,
8
11
  } from "./ast";
9
- import { createSemanticError, TlaSyntaxError } from "./errors";
12
+ import {
13
+ createSanyError,
14
+ createSemanticError,
15
+ formatRange,
16
+ TlaSyntaxError,
17
+ type SanyError,
18
+ } from "./errors";
10
19
  import { mapChildren } from "./instances";
11
20
  import { collectSemanticErrors, getBoundNames, getPatternNames } from "./resolve";
12
21
  import { STANDARD_LEVELS } from "./standard-levels";
@@ -33,6 +42,7 @@ interface LevelContext {
33
42
  constants: Set<string>;
34
43
  variables: Set<string>;
35
44
  getDefinition: (name: string) => Definition | undefined;
45
+ getQualifiedName?: (name: string) => string | undefined;
36
46
  }
37
47
 
38
48
  type ScopeEntry =
@@ -205,7 +215,13 @@ export const createLevelAnalyzer = (context: LevelContext) => {
205
215
  if (context.variables.has(name)) return { kind: "Declared", name, level: 1, arity: 0 };
206
216
  const definition = context.getDefinition(name);
207
217
  if (definition) {
208
- return { kind: "Defined", levels: analyzeDefinition(definition, new Map()) };
218
+ const levels = analyzeDefinition(definition, new Map());
219
+ // SANY names a definition of an instance by its qualified name, as in I!Foo.
220
+ const qualifiedName = context.getQualifiedName?.(name);
221
+ return {
222
+ kind: "Defined",
223
+ levels: qualifiedName ? { ...levels, name: qualifiedName } : levels,
224
+ };
209
225
  }
210
226
  const signature = CORE_SIGNATURES.get(name) ?? STANDARD_LEVELS.get(name);
211
227
  if (signature) return { kind: "Defined", levels: signature };
@@ -835,44 +851,141 @@ export const createLevelAnalyzer = (context: LevelContext) => {
835
851
  return { analyze, analyzeDefinition, toOperand };
836
852
  };
837
853
 
838
- const analyzeAssumeProve = (
854
+ export const analyzeAssumeProve = (
839
855
  assumeProve: AssumeProve,
840
856
  scope: Scope,
841
857
  analyzer: ReturnType<typeof createLevelAnalyzer>,
842
- ) => {
858
+ ): LevelData => {
843
859
  const inner = new Map(scope);
844
- assumeProve.assumptions.forEach((assumption) => {
860
+ const parts = assumeProve.assumptions.flatMap((assumption) => {
845
861
  if (assumption.kind === "NewSymbol") {
846
- if (assumption.set) analyzer.analyze(assumption.set, inner);
862
+ const set = assumption.set && analyzer.analyze(assumption.set, inner);
847
863
  inner.set(assumption.name, { kind: "Formal", arity: assumption.arity });
848
- return;
864
+ return set ? [set] : [];
849
865
  }
850
- if (assumption.kind === "AssumeProve") analyzeAssumeProve(assumption, inner, analyzer);
851
- else analyzer.analyze(assumption, inner);
866
+ return [
867
+ assumption.kind === "AssumeProve"
868
+ ? analyzeAssumeProve(assumption, inner, analyzer)
869
+ : analyzer.analyze(assumption, inner),
870
+ ];
871
+ });
872
+ parts.push(analyzer.analyze(assumeProve.conclusion, inner));
873
+ const data = createData(Math.max(...parts.map((part) => part.level)));
874
+ parts.forEach((part) => {
875
+ part.params.forEach((param) => data.params.add(param));
876
+ part.constraints.forEach((value, key) => putConstraint(data.constraints, key, value));
877
+ part.argConstraints.forEach((value, key) => putArgConstraint(data.argConstraints, key, value));
878
+ part.argParams.forEach((key) => data.argParams.add(key));
852
879
  });
853
- analyzer.analyze(assumeProve.conclusion, inner);
880
+ return data;
854
881
  };
855
882
 
856
- // SANY checks the level of every definition, assumption, and theorem of a module.
857
- export const checkModuleLevels = (module: Module, context: LevelContext) => {
883
+ // SANY checks the level of every definition, assumption, theorem, and instance of a module.
884
+ export const checkModuleLevels = (
885
+ module: Module,
886
+ context: LevelContext,
887
+ instances: { location: SourceLocation; check: () => void }[],
888
+ warnings: SanyError[],
889
+ ) => {
858
890
  const analyzer = createLevelAnalyzer(context);
859
- collectSemanticErrors([
860
- ...module.definitions
861
- .filter((definition) => !definition.name.includes("!"))
862
- .map((definition) => ({
863
- location: definition.location,
864
- check: () => analyzer.analyzeDefinition(definition, new Map()),
891
+ const getLevel = (expressions: Expression[]) =>
892
+ Math.max(0, ...expressions.map((expression) => analyzer.analyze(expression, new Map()).level));
893
+ const getStepLevel = (step: ProofStep) => {
894
+ const body = step.body;
895
+ if (body.kind === "Have" || body.kind === "Case") return getLevel([body.expression]);
896
+ if (body.kind === "Witness") return getLevel(body.expressions);
897
+ if (body.kind === "Take") return getLevel(body.bounds.map((bound) => bound.set));
898
+ if (body.kind === "Pick") {
899
+ return getLevel([body.body, ...body.bounds.map((bound) => bound.set)]);
900
+ }
901
+ if (body.kind !== "Assert") return 0;
902
+ return body.statement.kind === "AssumeProve"
903
+ ? analyzeAssumeProve(body.statement, new Map(), analyzer).level
904
+ : getLevel([body.statement]);
905
+ };
906
+ // SANY's TheoremNode.LevelCheckTemporal: the proof of a temporal goal may only assume constants.
907
+ const checkTemporalGoal = (proof: Proof | undefined): SanyError[] =>
908
+ proof?.kind !== "Steps"
909
+ ? []
910
+ : proof.steps.flatMap((step) => {
911
+ const location = formatRange(step.statement);
912
+ const isConstant = () => getStepLevel(step) === 0;
913
+ if (
914
+ step.body.kind === "Have" ||
915
+ step.body.kind === "Take" ||
916
+ step.body.kind === "Witness"
917
+ ) {
918
+ return isConstant()
919
+ ? []
920
+ : [{ location, message: "Non-constant TAKE, WITNESS, or HAVE for temporal goal." }];
921
+ }
922
+ if (step.body.kind === "Case") {
923
+ return [
924
+ ...(isConstant()
925
+ ? []
926
+ : [{ location, message: "Non-constant CASE for temporal goal." }]),
927
+ ...checkTemporalGoal(step.proof),
928
+ ];
929
+ }
930
+ return step.body.kind === "Qed" ? checkTemporalGoal(step.proof) : [];
931
+ });
932
+ // SANY checks each step as a theorem of its own after the steps of its proof.
933
+ const checkProof = (proof: Proof | undefined): SanyError[] =>
934
+ proof?.kind !== "Steps"
935
+ ? []
936
+ : proof.steps.flatMap((step) => {
937
+ const body = step.body;
938
+ const isTemporal = () => getStepLevel(step) === TEMPORAL_LEVEL;
939
+ const pickErrors =
940
+ body.kind === "Pick" && body.bounds.length > 0 && isTemporal()
941
+ ? body.bounds
942
+ .filter((bound) => getLevel([bound.set]) !== 0)
943
+ .flatMap((bound) =>
944
+ bound.set.location.range
945
+ ? [
946
+ {
947
+ location: formatRange(bound.set.location.range),
948
+ message: "Non-constant bound of temporal PICK.",
949
+ },
950
+ ]
951
+ : [],
952
+ )
953
+ : [];
954
+ return [
955
+ ...checkProof(step.proof),
956
+ ...pickErrors,
957
+ ...(step.proof?.kind === "Steps" && isTemporal() ? checkTemporalGoal(step.proof) : []),
958
+ ];
959
+ });
960
+ const errors = collectSemanticErrors(
961
+ [
962
+ ...module.definitions
963
+ .filter((definition) => !definition.name.includes("!"))
964
+ .map((definition) => ({
965
+ location: definition.location,
966
+ check: () => analyzer.analyzeDefinition(definition, new Map()),
967
+ })),
968
+ ...module.assumptions.map((assumption) => ({
969
+ location: assumption.location,
970
+ check: () => analyzer.analyze(assumption.expression, new Map()),
971
+ })),
972
+ ...module.theorems.map((theorem) => ({
973
+ location: theorem.location,
974
+ check: () => {
975
+ const data =
976
+ theorem.statement.kind === "AssumeProve"
977
+ ? analyzeAssumeProve(theorem.statement, new Map(), analyzer)
978
+ : analyzer.analyze(theorem.statement, new Map());
979
+ const errors = [
980
+ ...checkProof(theorem.proof),
981
+ ...(data.level === TEMPORAL_LEVEL ? checkTemporalGoal(theorem.proof) : []),
982
+ ];
983
+ if (errors.length > 0) throw createSanyError(errors);
984
+ },
865
985
  })),
866
- ...module.assumptions.map((assumption) => ({
867
- location: assumption.location,
868
- check: () => analyzer.analyze(assumption.expression, new Map()),
869
- })),
870
- ...module.theorems.map((theorem) => ({
871
- location: theorem.location,
872
- check: () =>
873
- theorem.statement.kind === "AssumeProve"
874
- ? analyzeAssumeProve(theorem.statement, new Map(), analyzer)
875
- : analyzer.analyze(theorem.statement, new Map()),
876
- })),
877
- ]);
986
+ ...instances,
987
+ ],
988
+ warnings,
989
+ );
990
+ if (errors.length > 0) throw createSanyError(errors, false, undefined, warnings);
878
991
  };
package/src/parser.ts CHANGED
@@ -315,6 +315,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
315
315
  const proofScopes: Set<string>[] = [];
316
316
  // A fact may cite an operator of a parameterized instance without the instance's arguments.
317
317
  const factStart = { index: -1 };
318
+ // SANY reports a location in a nested module as one in the module of its file.
318
319
  const openModules: Module[] = [];
319
320
 
320
321
  const isRecursiveName = (name: string) => recursiveScopes[recursiveScopes.length - 1].has(name);
@@ -329,15 +330,14 @@ const parse = (source: string, isTlapm: boolean): Module => {
329
330
  const tokenEnds: SourceLocation[] = [];
330
331
  const tokenRanges: SourceRange[] = [];
331
332
 
332
- const getRange = (startIndex: number) => {
333
- const endIndex = cursor.index - 1;
333
+ const getRange = (startIndex: number, endIndex = cursor.index - 1) => {
334
334
  const cached = startIndex === endIndex ? tokenRanges[startIndex] : undefined;
335
335
  if (cached) return cached;
336
336
  const last = tokens[endIndex];
337
337
  tokenStarts[startIndex] ??= getLocation(tokens[startIndex]);
338
338
  tokenEnds[endIndex] ??= { line: last.line, column: last.endColumn };
339
339
  const range = {
340
- module: openModules[openModules.length - 1].name,
340
+ module: openModules[0].name,
341
341
  start: tokenStarts[startIndex],
342
342
  end: tokenEnds[endIndex],
343
343
  };
@@ -472,6 +472,16 @@ const parse = (source: string, isTlapm: boolean): Module => {
472
472
  return token.text;
473
473
  };
474
474
 
475
+ const expectName = () => {
476
+ const start = cursor.index;
477
+ return { name: expectIdentifier(), range: getRange(start) };
478
+ };
479
+
480
+ const getNames = (names: { name: string; range: SourceRange }[]) => ({
481
+ names: names.map((item) => item.name),
482
+ ranges: names.map((item) => item.range),
483
+ });
484
+
475
485
  const withoutOffside = <Result>(parse: () => Result) => {
476
486
  cursor.offsideColumns.push(NO_OFFSIDE);
477
487
  const result = parse();
@@ -514,10 +524,13 @@ const parse = (source: string, isTlapm: boolean): Module => {
514
524
  };
515
525
 
516
526
  const parsePattern = (): BoundPattern => {
517
- if (!accept("<<")) return { kind: "Name", name: expectIdentifier() };
518
- const names = parseSeparated(expectIdentifier);
527
+ if (!accept("<<")) {
528
+ const named = expectName();
529
+ return { kind: "Name", name: named.name, ranges: [named.range] };
530
+ }
531
+ const names = getNames(parseSeparated(expectName));
519
532
  expect(">>");
520
- return { kind: "Tuple", names };
533
+ return { kind: "Tuple", names: names.names, ranges: names.ranges };
521
534
  };
522
535
 
523
536
  const parseBounds = () =>
@@ -623,14 +636,29 @@ const parse = (source: string, isTlapm: boolean): Module => {
623
636
  if (isAt("LAMBDA")) {
624
637
  const start = cursor.index;
625
638
  advance();
626
- const params = parseSeparated(expectIdentifier);
639
+ const params = getNames(parseSeparated(expectName));
627
640
  expect(":");
628
641
  const body = parseExpression();
629
- return withRange({ kind: "Lambda", params, body, location: getLocation(token) }, start);
642
+ return withRange(
643
+ {
644
+ kind: "Lambda",
645
+ params: params.names,
646
+ paramRanges: params.ranges,
647
+ body,
648
+ location: getLocation(token),
649
+ },
650
+ start,
651
+ );
630
652
  }
631
- return parseExpression();
653
+ const argument = parseExpression();
654
+ // SANY reads an argument that only names an operator of a parameterized instance, such as
655
+ // I!Op, as that operator, which takes the arguments of the instance too.
656
+ if (argument.kind === "Identifier") missingArguments.delete(argument);
657
+ return argument;
632
658
  };
633
659
 
660
+ const missingArguments = new Map<Expression, { location: string; message: string }>();
661
+
634
662
  const lastArguments: { range: SourceRange | undefined } = { range: undefined };
635
663
 
636
664
  const parseArguments = () =>
@@ -770,12 +798,13 @@ const parse = (source: string, isTlapm: boolean): Module => {
770
798
  expect(":");
771
799
  return { kind, bounds, body: parseExpression(), location };
772
800
  }
773
- const names = parseSeparated(expectIdentifier);
801
+ const names = getNames(parseSeparated(expectName));
774
802
  expect(":");
775
803
  return {
776
804
  kind: "UnboundedQuantifier",
777
805
  quantifier: start.text === "\\A" || start.text === "\\AA" ? "Forall" : "Exists",
778
- names,
806
+ names: names.names,
807
+ nameRanges: names.ranges,
779
808
  body: parseExpression(),
780
809
  isTemporal,
781
810
  location,
@@ -830,7 +859,8 @@ const parse = (source: string, isTlapm: boolean): Module => {
830
859
  };
831
860
 
832
861
  const parsePrimary = (): Expression => {
833
- const isFactStart = cursor.index === factStart.index;
862
+ const start = cursor.index;
863
+ const isFactStart = start === factStart.index;
834
864
  const token = advance();
835
865
  const location = getLocation(token);
836
866
  if (isTlapm && token.kind === "Keyword" && token.text === "LAMBDA") {
@@ -854,13 +884,21 @@ const parse = (source: string, isTlapm: boolean): Module => {
854
884
  if (token.kind === "Identifier" || isStep) {
855
885
  const name = isStep ? (getStepName(token) ?? token.text) : token.text;
856
886
  if (isLabelAhead()) {
857
- const params = accept("(") ? parseSeparated(expectIdentifier) : [];
858
- if (params.length > 0) expect(")");
887
+ const params = getNames(accept("(") ? parseSeparated(expectName) : []);
888
+ if (params.names.length > 0) expect(")");
859
889
  expect("::");
860
- return { kind: "Label", name, params, body: parseExpression(), location };
890
+ return {
891
+ kind: "Label",
892
+ name,
893
+ params: params.names,
894
+ paramRanges: params.ranges,
895
+ body: parseExpression(),
896
+ location,
897
+ };
861
898
  }
862
899
  const hasArguments = isAt("(");
863
900
  const args = hasArguments ? parseArguments() : [];
901
+ const argumentRanges = [hasArguments ? lastArguments.range : undefined];
864
902
  if (!isSelectorAhead()) {
865
903
  return hasArguments
866
904
  ? { kind: "Apply", operator: name, args, argumentsRange: lastArguments.range, location }
@@ -869,33 +907,69 @@ const parse = (source: string, isTlapm: boolean): Module => {
869
907
  const instance = openModules
870
908
  .flatMap((module) => module.instances)
871
909
  .find((candidate) => candidate.name === name);
872
- if (instance && !isFactStart && !isTlapm && instance.params.length !== args.length) {
910
+ const isMissingArguments =
911
+ instance !== undefined &&
912
+ !isFactStart &&
913
+ !isTlapm &&
914
+ instance.params.length !== args.length;
915
+ if (isMissingArguments && args.length > 0) {
873
916
  throw createError(
874
917
  `The operator ${name} requires ${instance.params.length} arguments`,
875
918
  token,
876
919
  );
877
920
  }
878
921
  const selectors: Selector[] = [{ kind: "Name", name, args }];
922
+ const selectorRanges = [getRange(start, start)];
879
923
  while (isSelectorAhead()) {
880
924
  advance();
925
+ selectorRanges.push(getRange(cursor.index, cursor.index));
926
+ lastArguments.range = undefined;
881
927
  selectors.push(parseSelector());
928
+ argumentRanges.push(lastArguments.range);
882
929
  }
883
930
  const names = selectors.flatMap((selector) =>
884
931
  selector.kind === "Name" ? [selector.name] : [],
885
932
  );
886
- if (names.length < selectors.length) return { kind: "Subexpression", selectors, location };
887
933
  const operator = names.join("!");
888
934
  const qualifiedArgs = selectors.flatMap((selector) =>
889
935
  "args" in selector ? selector.args : [],
890
936
  );
891
- if (qualifiedArgs.length === 0) return { kind: "Identifier", name: operator, location };
892
937
  const argumentCounts = selectors.map((selector) =>
893
938
  "args" in selector ? selector.args.length : 0,
894
939
  );
895
- const argumentsRange = lastArguments.range;
896
- return argumentCounts.slice(0, -1).some((count) => count > 0)
897
- ? { kind: "Apply", operator, args: qualifiedArgs, argumentCounts, argumentsRange, location }
898
- : { kind: "Apply", operator, args: qualifiedArgs, argumentsRange, location };
940
+ const argumentsRange = argumentRanges.findLast((range) => range !== undefined);
941
+ const reference: Expression =
942
+ names.length < selectors.length
943
+ ? { kind: "Subexpression", selectors, selectorRanges, argumentRanges, location }
944
+ : qualifiedArgs.length === 0
945
+ ? { kind: "Identifier", name: operator, selectorRanges, location }
946
+ : argumentCounts.slice(0, -1).some((count) => count > 0)
947
+ ? {
948
+ kind: "Apply",
949
+ operator,
950
+ args: qualifiedArgs,
951
+ argumentCounts,
952
+ argumentsRange,
953
+ selectorRanges,
954
+ argumentRanges,
955
+ location,
956
+ }
957
+ : {
958
+ kind: "Apply",
959
+ operator,
960
+ args: qualifiedArgs,
961
+ argumentsRange,
962
+ selectorRanges,
963
+ argumentRanges,
964
+ location,
965
+ };
966
+ if (isMissingArguments) {
967
+ missingArguments.set(reference, {
968
+ location: formatRange(getRange(start)),
969
+ message: `The operator ${name} requires ${instance.params.length} arguments.`,
970
+ });
971
+ }
972
+ return reference;
899
973
  }
900
974
  if (token.kind === "Operator" && isOperatorName(token.text) && isAt("("))
901
975
  return { kind: "Apply", operator: token.text, args: parseArguments(), location };
@@ -1107,7 +1181,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1107
1181
  const body = parseExpression();
1108
1182
  const last = tokens[cursor.index - 1];
1109
1183
  const end = { line: last.line, column: last.endColumn };
1110
- return { body, bodyRange: { module: openModules[openModules.length - 1].name, start, end } };
1184
+ return { body, bodyRange: { module: openModules[0].name, start, end } };
1111
1185
  };
1112
1186
 
1113
1187
  const parseDefinition = (isLocal: boolean): Definition | Instance => {
@@ -1115,6 +1189,16 @@ const parse = (source: string, isTlapm: boolean): Module => {
1115
1189
  return withRange(parseDefinitionUnit(isLocal), start);
1116
1190
  };
1117
1191
 
1192
+ const toParam = (named: { name: string; range: SourceRange }): OperatorParam => ({
1193
+ name: named.name,
1194
+ arity: 0,
1195
+ location: {
1196
+ line: named.range.start.line,
1197
+ column: named.range.start.column,
1198
+ range: named.range,
1199
+ },
1200
+ });
1201
+
1118
1202
  const parseDefinitionUnit = (isLocal: boolean): Definition | Instance => {
1119
1203
  const token = peek();
1120
1204
  const location = getLocation(token);
@@ -1134,24 +1218,22 @@ const parse = (source: string, isTlapm: boolean): Module => {
1134
1218
  peek(2).kind === "Identifier" &&
1135
1219
  isAt("==", 3)
1136
1220
  ) {
1137
- const left = expectIdentifier();
1221
+ const left = expectName();
1138
1222
  const operator = advance().text;
1139
- const right = expectIdentifier();
1223
+ const right = expectName();
1140
1224
  expect("==");
1141
- return parseOperator(operator, [
1142
- { name: left, arity: 0 },
1143
- { name: right, arity: 0 },
1144
- ]);
1225
+ return parseOperator(operator, [toParam(left), toParam(right)]);
1145
1226
  }
1146
1227
  const isPrefixDefinition = token.kind === "Operator" && token.text === "-.";
1147
1228
  const isPostfixDefinition =
1148
1229
  token.kind === "Identifier" && POSTFIX_OPERATORS.has(peek(1).text) && isAt("==", 2);
1149
1230
  if (isPrefixDefinition || isPostfixDefinition) {
1150
1231
  const operator = isPrefixDefinition ? token.text : peek(1).text;
1151
- cursor.index += isPrefixDefinition ? 1 : 2;
1152
- const param = isPrefixDefinition ? expectIdentifier() : token.text;
1232
+ if (isPrefixDefinition) advance();
1233
+ const param = expectName();
1234
+ if (isPostfixDefinition) advance();
1153
1235
  expect("==");
1154
- return parseOperator(operator, [{ name: param, arity: 0 }]);
1236
+ return parseOperator(operator, [toParam(param)]);
1155
1237
  }
1156
1238
  const name = expectIdentifier();
1157
1239
  if (accept("[")) {
@@ -1189,9 +1271,11 @@ const parse = (source: string, isTlapm: boolean): Module => {
1189
1271
  const module = expectIdentifier();
1190
1272
  const substitutions = accept("WITH")
1191
1273
  ? parseSeparated(() => {
1274
+ const targetStart = cursor.index;
1192
1275
  const target = advance().text;
1276
+ const nameRange = getRange(targetStart);
1193
1277
  expect("<-");
1194
- return { name: target, expression: parseArgument() };
1278
+ return { name: target, nameRange, expression: parseArgument() };
1195
1279
  })
1196
1280
  : [];
1197
1281
  return {
@@ -1207,6 +1291,11 @@ const parse = (source: string, isTlapm: boolean): Module => {
1207
1291
  };
1208
1292
 
1209
1293
  const parseDeclaration = (): Declaration => {
1294
+ const start = cursor.index;
1295
+ return withRange(parseDeclarationUnit(), start);
1296
+ };
1297
+
1298
+ const parseDeclarationUnit = (): Declaration => {
1210
1299
  const location = getLocation(peek());
1211
1300
  if (isAt("_") && peek(1).kind === "Operator") {
1212
1301
  advance();
@@ -1454,10 +1543,18 @@ const parse = (source: string, isTlapm: boolean): Module => {
1454
1543
  }
1455
1544
  if (level !== undefined) advance();
1456
1545
  if (level === "Variable") {
1457
- const name = expectIdentifier();
1458
- declareProofSymbol(name);
1546
+ const named = expectName();
1547
+ declareProofSymbol(named.name);
1459
1548
  return withRange(
1460
- { kind: "NewSymbol", name, arity: 0, level, set: undefined, location },
1549
+ {
1550
+ kind: "NewSymbol",
1551
+ name: named.name,
1552
+ arity: 0,
1553
+ level,
1554
+ set: undefined,
1555
+ nameRange: named.range,
1556
+ location,
1557
+ },
1461
1558
  start,
1462
1559
  );
1463
1560
  }
@@ -1475,6 +1572,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1475
1572
  arity: declaration.arity,
1476
1573
  level: level ?? "Constant",
1477
1574
  set: isBounded ? parseExpression() : undefined,
1575
+ nameRange: declaration.location.range,
1478
1576
  location,
1479
1577
  },
1480
1578
  start,
@@ -1517,7 +1615,8 @@ const parse = (source: string, isTlapm: boolean): Module => {
1517
1615
  const token = peek();
1518
1616
  if (isAt("USE") || isAt("HIDE")) return parseUseOrHide();
1519
1617
  if (isAt("INSTANCE")) {
1520
- return withRange(parseInstance(undefined, [], false, getLocation(token)), cursor.index);
1618
+ const start = cursor.index;
1619
+ return withRange(parseInstance(undefined, [], false, getLocation(token)), start);
1521
1620
  }
1522
1621
  if (isAt("DEFINE") || isDefinitionStart()) {
1523
1622
  const start = cursor.index;
@@ -1530,21 +1629,27 @@ const parse = (source: string, isTlapm: boolean): Module => {
1530
1629
  if (accept("HAVE")) return { kind: "Have", expression: parseExpression() };
1531
1630
  if (accept("TAKE")) {
1532
1631
  const isBounded = isBoundAhead();
1533
- const names = isBounded ? [] : parseSeparated(expectIdentifier);
1632
+ const names = getNames(isBounded ? [] : parseSeparated(expectName));
1534
1633
  const bounds = isBounded ? parseBounds() : [];
1535
- declareProofSymbols(names, bounds);
1536
- return { kind: "Take", names, bounds };
1634
+ declareProofSymbols(names.names, bounds);
1635
+ return { kind: "Take", names: names.names, nameRanges: names.ranges, bounds };
1537
1636
  }
1538
1637
  if (accept("WITNESS")) {
1539
1638
  return { kind: "Witness", expressions: parseSeparated(() => parseExpression()) };
1540
1639
  }
1541
1640
  if (accept("PICK")) {
1542
1641
  const isNames = isNameListAhead(":");
1543
- const names = isNames ? parseSeparated(expectIdentifier) : [];
1642
+ const names = getNames(isNames ? parseSeparated(expectName) : []);
1544
1643
  const bounds = isNames ? [] : parseBounds();
1545
- declareProofSymbols(names, bounds);
1644
+ declareProofSymbols(names.names, bounds);
1546
1645
  expect(":");
1547
- return { kind: "Pick", names, bounds, body: parseExpression() };
1646
+ return {
1647
+ kind: "Pick",
1648
+ names: names.names,
1649
+ nameRanges: names.ranges,
1650
+ bounds,
1651
+ body: parseExpression(),
1652
+ };
1548
1653
  }
1549
1654
  if (accept("CASE")) return { kind: "Case", expression: parseExpression() };
1550
1655
  return {
@@ -1574,10 +1679,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
1574
1679
  const parseStep = (): ProofStep => {
1575
1680
  const start = cursor.index;
1576
1681
  const step = parseStepStart(isAt("QED", 1));
1682
+ const statementStart = cursor.index;
1577
1683
  const scope = new Set<string>();
1578
1684
  proofScopes.push(scope);
1579
1685
  const body: StepBody = accept("QED") ? { kind: "Qed" } : parseStepBody();
1580
1686
  const head = getRange(start);
1687
+ const statement = getRange(statementStart);
1581
1688
  const hasProof = isProofStart(peek());
1582
1689
  if (hasProof && !PROVABLE_STEPS.has(body.kind)) {
1583
1690
  throw createError("Proof of a step that does not take a proof");
@@ -1585,7 +1692,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1585
1692
  const proof = hasProof ? parseProof() : undefined;
1586
1693
  proofScopes.pop();
1587
1694
  if (body.kind !== "Assert" || body.isSuffices) scope.forEach(declareProofSymbol);
1588
- return withRange({ ...step, body, head, proof }, start);
1695
+ return withRange({ ...step, body, head, statement, proof }, start);
1589
1696
  };
1590
1697
 
1591
1698
  const parseProofBody = (): Proof => {
@@ -1711,11 +1818,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
1711
1818
  if (token.kind === "ModuleEnd" || token.kind === "End") {
1712
1819
  if (token.kind === "ModuleEnd") {
1713
1820
  location.range = {
1714
- module: name,
1821
+ module: openModules[0].name,
1715
1822
  start: { line: location.line, column: location.column },
1716
1823
  end: { line: token.line, column: token.endColumn },
1717
1824
  };
1718
1825
  }
1826
+ if (missingArguments.size > 0) throw createSanyError([...missingArguments.values()]);
1719
1827
  openModules.pop();
1720
1828
  recursiveScopes.pop();
1721
1829
  return module;
@@ -1797,7 +1905,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1797
1905
  );
1798
1906
  continue;
1799
1907
  }
1800
- addDefinitionUnit(module, parseDefinition(true));
1908
+ addDefinitionUnit(module, withRange(parseDefinitionUnit(true), tokenIndex));
1801
1909
  continue;
1802
1910
  }
1803
1911
  }