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

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/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,27 +851,111 @@ 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
+ ];
852
871
  });
853
- analyzer.analyze(assumeProve.conclusion, inner);
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));
879
+ });
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
+ ) => {
858
889
  const analyzer = createLevelAnalyzer(context);
890
+ const getLevel = (expressions: Expression[]) =>
891
+ Math.max(0, ...expressions.map((expression) => analyzer.analyze(expression, new Map()).level));
892
+ const getStepLevel = (step: ProofStep) => {
893
+ const body = step.body;
894
+ if (body.kind === "Have" || body.kind === "Case") return getLevel([body.expression]);
895
+ if (body.kind === "Witness") return getLevel(body.expressions);
896
+ if (body.kind === "Take") return getLevel(body.bounds.map((bound) => bound.set));
897
+ if (body.kind === "Pick") {
898
+ return getLevel([body.body, ...body.bounds.map((bound) => bound.set)]);
899
+ }
900
+ if (body.kind !== "Assert") return 0;
901
+ return body.statement.kind === "AssumeProve"
902
+ ? analyzeAssumeProve(body.statement, new Map(), analyzer).level
903
+ : getLevel([body.statement]);
904
+ };
905
+ // SANY's TheoremNode.LevelCheckTemporal: the proof of a temporal goal may only assume constants.
906
+ const checkTemporalGoal = (proof: Proof | undefined): SanyError[] =>
907
+ proof?.kind !== "Steps"
908
+ ? []
909
+ : proof.steps.flatMap((step) => {
910
+ const location = formatRange(step.statement);
911
+ const isConstant = () => getStepLevel(step) === 0;
912
+ if (
913
+ step.body.kind === "Have" ||
914
+ step.body.kind === "Take" ||
915
+ step.body.kind === "Witness"
916
+ ) {
917
+ return isConstant()
918
+ ? []
919
+ : [{ location, message: "Non-constant TAKE, WITNESS, or HAVE for temporal goal." }];
920
+ }
921
+ if (step.body.kind === "Case") {
922
+ return [
923
+ ...(isConstant()
924
+ ? []
925
+ : [{ location, message: "Non-constant CASE for temporal goal." }]),
926
+ ...checkTemporalGoal(step.proof),
927
+ ];
928
+ }
929
+ return step.body.kind === "Qed" ? checkTemporalGoal(step.proof) : [];
930
+ });
931
+ // SANY checks each step as a theorem of its own after the steps of its proof.
932
+ const checkProof = (proof: Proof | undefined): SanyError[] =>
933
+ proof?.kind !== "Steps"
934
+ ? []
935
+ : proof.steps.flatMap((step) => {
936
+ const body = step.body;
937
+ const isTemporal = () => getStepLevel(step) === TEMPORAL_LEVEL;
938
+ const pickErrors =
939
+ body.kind === "Pick" && body.bounds.length > 0 && isTemporal()
940
+ ? body.bounds
941
+ .filter((bound) => getLevel([bound.set]) !== 0)
942
+ .flatMap((bound) =>
943
+ bound.set.location.range
944
+ ? [
945
+ {
946
+ location: formatRange(bound.set.location.range),
947
+ message: "Non-constant bound of temporal PICK.",
948
+ },
949
+ ]
950
+ : [],
951
+ )
952
+ : [];
953
+ return [
954
+ ...checkProof(step.proof),
955
+ ...pickErrors,
956
+ ...(step.proof?.kind === "Steps" && isTemporal() ? checkTemporalGoal(step.proof) : []),
957
+ ];
958
+ });
859
959
  collectSemanticErrors([
860
960
  ...module.definitions
861
961
  .filter((definition) => !definition.name.includes("!"))
@@ -869,10 +969,18 @@ export const checkModuleLevels = (module: Module, context: LevelContext) => {
869
969
  })),
870
970
  ...module.theorems.map((theorem) => ({
871
971
  location: theorem.location,
872
- check: () =>
873
- theorem.statement.kind === "AssumeProve"
874
- ? analyzeAssumeProve(theorem.statement, new Map(), analyzer)
875
- : analyzer.analyze(theorem.statement, new Map()),
972
+ check: () => {
973
+ const data =
974
+ theorem.statement.kind === "AssumeProve"
975
+ ? analyzeAssumeProve(theorem.statement, new Map(), analyzer)
976
+ : analyzer.analyze(theorem.statement, new Map());
977
+ const errors = [
978
+ ...checkProof(theorem.proof),
979
+ ...(data.level === TEMPORAL_LEVEL ? checkTemporalGoal(theorem.proof) : []),
980
+ ];
981
+ if (errors.length > 0) throw createSanyError(errors);
982
+ },
876
983
  })),
984
+ ...instances,
877
985
  ]);
878
986
  };
package/src/parser.ts CHANGED
@@ -628,9 +628,15 @@ const parse = (source: string, isTlapm: boolean): Module => {
628
628
  const body = parseExpression();
629
629
  return withRange({ kind: "Lambda", params, body, location: getLocation(token) }, start);
630
630
  }
631
- return parseExpression();
631
+ const argument = parseExpression();
632
+ // SANY reads an argument that only names an operator of a parameterized instance, such as
633
+ // I!Op, as that operator, which takes the arguments of the instance too.
634
+ if (argument.kind === "Identifier") missingArguments.delete(argument);
635
+ return argument;
632
636
  };
633
637
 
638
+ const missingArguments = new Map<Expression, { location: string; message: string }>();
639
+
634
640
  const lastArguments: { range: SourceRange | undefined } = { range: undefined };
635
641
 
636
642
  const parseArguments = () =>
@@ -830,7 +836,8 @@ const parse = (source: string, isTlapm: boolean): Module => {
830
836
  };
831
837
 
832
838
  const parsePrimary = (): Expression => {
833
- const isFactStart = cursor.index === factStart.index;
839
+ const start = cursor.index;
840
+ const isFactStart = start === factStart.index;
834
841
  const token = advance();
835
842
  const location = getLocation(token);
836
843
  if (isTlapm && token.kind === "Keyword" && token.text === "LAMBDA") {
@@ -869,7 +876,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
869
876
  const instance = openModules
870
877
  .flatMap((module) => module.instances)
871
878
  .find((candidate) => candidate.name === name);
872
- if (instance && !isFactStart && !isTlapm && instance.params.length !== args.length) {
879
+ const isMissingArguments =
880
+ instance !== undefined &&
881
+ !isFactStart &&
882
+ !isTlapm &&
883
+ instance.params.length !== args.length;
884
+ if (isMissingArguments && args.length > 0) {
873
885
  throw createError(
874
886
  `The operator ${name} requires ${instance.params.length} arguments`,
875
887
  token,
@@ -883,19 +895,36 @@ const parse = (source: string, isTlapm: boolean): Module => {
883
895
  const names = selectors.flatMap((selector) =>
884
896
  selector.kind === "Name" ? [selector.name] : [],
885
897
  );
886
- if (names.length < selectors.length) return { kind: "Subexpression", selectors, location };
887
898
  const operator = names.join("!");
888
899
  const qualifiedArgs = selectors.flatMap((selector) =>
889
900
  "args" in selector ? selector.args : [],
890
901
  );
891
- if (qualifiedArgs.length === 0) return { kind: "Identifier", name: operator, location };
892
902
  const argumentCounts = selectors.map((selector) =>
893
903
  "args" in selector ? selector.args.length : 0,
894
904
  );
895
905
  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 };
906
+ const reference: Expression =
907
+ names.length < selectors.length
908
+ ? { kind: "Subexpression", selectors, location }
909
+ : qualifiedArgs.length === 0
910
+ ? { kind: "Identifier", name: operator, location }
911
+ : argumentCounts.slice(0, -1).some((count) => count > 0)
912
+ ? {
913
+ kind: "Apply",
914
+ operator,
915
+ args: qualifiedArgs,
916
+ argumentCounts,
917
+ argumentsRange,
918
+ location,
919
+ }
920
+ : { kind: "Apply", operator, args: qualifiedArgs, argumentsRange, location };
921
+ if (isMissingArguments) {
922
+ missingArguments.set(reference, {
923
+ location: formatRange(getRange(start)),
924
+ message: `The operator ${name} requires ${instance.params.length} arguments.`,
925
+ });
926
+ }
927
+ return reference;
899
928
  }
900
929
  if (token.kind === "Operator" && isOperatorName(token.text) && isAt("("))
901
930
  return { kind: "Apply", operator: token.text, args: parseArguments(), location };
@@ -1574,10 +1603,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
1574
1603
  const parseStep = (): ProofStep => {
1575
1604
  const start = cursor.index;
1576
1605
  const step = parseStepStart(isAt("QED", 1));
1606
+ const statementStart = cursor.index;
1577
1607
  const scope = new Set<string>();
1578
1608
  proofScopes.push(scope);
1579
1609
  const body: StepBody = accept("QED") ? { kind: "Qed" } : parseStepBody();
1580
1610
  const head = getRange(start);
1611
+ const statement = getRange(statementStart);
1581
1612
  const hasProof = isProofStart(peek());
1582
1613
  if (hasProof && !PROVABLE_STEPS.has(body.kind)) {
1583
1614
  throw createError("Proof of a step that does not take a proof");
@@ -1585,7 +1616,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1585
1616
  const proof = hasProof ? parseProof() : undefined;
1586
1617
  proofScopes.pop();
1587
1618
  if (body.kind !== "Assert" || body.isSuffices) scope.forEach(declareProofSymbol);
1588
- return withRange({ ...step, body, head, proof }, start);
1619
+ return withRange({ ...step, body, head, statement, proof }, start);
1589
1620
  };
1590
1621
 
1591
1622
  const parseProofBody = (): Proof => {
@@ -1716,6 +1747,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1716
1747
  end: { line: token.line, column: token.endColumn },
1717
1748
  };
1718
1749
  }
1750
+ if (missingArguments.size > 0) throw createSanyError([...missingArguments.values()]);
1719
1751
  openModules.pop();
1720
1752
  recursiveScopes.pop();
1721
1753
  return module;
package/src/resolve.ts CHANGED
@@ -822,14 +822,16 @@ export const collectSemanticErrors = (units: { location: SourceLocation; check:
822
822
  unit.check();
823
823
  } catch (error) {
824
824
  if (!(error instanceof TlaSyntaxError) || !error.sany) throw error;
825
- error.sany.errors
826
- .filter((item) =>
825
+ error.sany.errors.forEach((item) => {
826
+ if (
827
827
  errors.every(
828
828
  (existing) =>
829
829
  existing.location !== item.location || existing.message !== item.message,
830
- ),
831
- )
832
- .forEach((item) => errors.push(item));
830
+ )
831
+ ) {
832
+ errors.push(item);
833
+ }
834
+ });
833
835
  }
834
836
  });
835
837
  if (errors.length > 0) throw createSanyError(errors);
package/src/run-cli.ts CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  import { spawnSync } from "node:child_process";
11
11
  import { basename, delimiter, dirname, join, resolve } from "node:path";
12
12
  import { availableParallelism } from "node:os";
13
- import type { CheckResult, CheckStatus, TraceStep } from "./check";
13
+ import type { CheckResult, CheckStatus, Replay, TraceStep } from "./check";
14
14
  import { defineCommand, type ParsedArgs } from "./cli-options";
15
15
  import { parseConfig } from "./config";
16
16
  import {
@@ -28,7 +28,7 @@ import type { LineRange } from "./obligation-generate";
28
28
  import { getAtPrefix, getLocusText } from "./obligation-expression";
29
29
  import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
30
30
  import { check } from "./parallel";
31
- import { parseModule } from "./parser";
31
+ import { parseModuleFile } from "./sany-parse-error";
32
32
  import type { StateDump } from "./state-graph";
33
33
  import {
34
34
  formatProbability,
@@ -137,22 +137,41 @@ const getTemporalHeadline = (names: string[]) =>
137
137
  ? `Error: Temporal property ${names[0]} was violated.\n`
138
138
  : `Error: Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
139
139
 
140
+ const getFrames = (callStack: string[]) =>
141
+ callStack.map((frame, index) => `${index}. ${frame}\n`).join("");
142
+
143
+ const printCallStack = (frames: string) =>
144
+ console.log(
145
+ `Error: The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${frames ? `${frames}\n` : " The error call stack is empty.\n"}`,
146
+ );
147
+
148
+ const printReplay = (replay: Replay) => {
149
+ replay.output.forEach((line) => console.log(line));
150
+ const frames = getFrames(replay.callStack ?? []);
151
+ const fingerprint = replay.fingerprint;
152
+ if (replay.isBeforeError) {
153
+ if (frames) printCallStack(frames);
154
+ } else if (replay.callStack && fingerprint) {
155
+ const sources = fingerprint.sources.map((source) => `${source}\n`).join("");
156
+ console.log(
157
+ `Error: TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${frames ? `${frames}\n` : sources}\nReason:\n${fingerprint.reason}`,
158
+ );
159
+ } else if (replay.callStack) {
160
+ printCallStack(frames);
161
+ }
162
+ };
163
+
140
164
  const printResult = (result: CheckResult) => {
141
165
  if (result.failure) {
166
+ const replay = result.failure.replay;
167
+ if (replay?.isBeforeError) printReplay(replay);
142
168
  console.log(`Error: ${result.failure.message}`);
143
169
  if (result.failure.initialState) {
144
170
  console.log("While working on the initial state:");
145
171
  printState(result.failure.initialState);
146
172
  }
147
173
  printTrace(result.failure.trace);
148
- const replay = result.failure.replay;
149
- replay?.output.forEach((line) => console.log(line));
150
- if (replay?.callStack) {
151
- const frames = replay.callStack.map((frame, index) => `${index}. ${frame}\n`).join("");
152
- console.log(
153
- `Error: The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${frames ? `${frames}\n` : " The error call stack is empty.\n"}`,
154
- );
155
- }
174
+ if (replay && !replay.isBeforeError) printReplay(replay);
156
175
  if (result.failure.isWithoutStatistics) return;
157
176
  } else if (result.violation) {
158
177
  const violation = result.violation;
@@ -228,7 +247,7 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
228
247
  }
229
248
  const source = readFileSync(specPath, "utf8");
230
249
  const fileName = basename(specPath, ".tla");
231
- const moduleName = parseModule(source).name;
250
+ const moduleName = parseModuleFile(source, fileName).name;
232
251
  if (moduleName !== fileName) {
233
252
  throw createSanyError(
234
253
  [
@@ -314,6 +333,7 @@ const printError = (error: TlaError, path?: string) => {
314
333
  }
315
334
  const report = error instanceof TlaSyntaxError ? error.sany : undefined;
316
335
  if (!report || path === undefined) return console.error(`${error.name}: ${error.message}`);
336
+ if (report.parseError !== undefined) console.log(report.parseError);
317
337
  console.log(
318
338
  report.isFatal
319
339
  ? `\nFatal errors while parsing TLA+ spec in file ${basename(path, ".tla")}\n\n${report.errors.map((item) => `${item.location}\n\n${item.message}\n`).join("")}${formatSanyErrors(report)}\n`