tla-ts 0.0.3-dev.d9ff6f2 → 0.0.3-dev.e5b05b9

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
@@ -12,13 +12,14 @@ import {
12
12
  type RecordField,
13
13
  } from "./ast";
14
14
  import { getKindString } from "./builtins";
15
- import { formatRange, TlaEvaluationError } from "./errors";
15
+ import { formatRange, TlaEvaluationError, TlaUnassignedError } from "./errors";
16
16
  import { EXIT_STATUS, setExitCode, setOwnExitCode } from "./exit-codes";
17
17
  import { generateEvaluator } from "./codegen";
18
18
  import type { CheckerRuntime } from "./runtime";
19
19
  import { getReadVariables } from "./dependencies";
20
20
  import { contextualApplications, mapChildren, substitutedExpressions } from "./instances";
21
21
  import { isEnabled } from "./successors";
22
+ import { getFingerprintTrace, valueSources, withSource } from "./value-sources";
22
23
  import {
23
24
  applyFunction,
24
25
  combineHash,
@@ -34,6 +35,7 @@ import {
34
35
  getDomain,
35
36
  getFunctionDomain,
36
37
  getIntervalElements,
38
+ getLazySubsets,
37
39
  getSequenceElements,
38
40
  getValueHash,
39
41
  isFunctionValue,
@@ -341,9 +343,8 @@ export const getEnumeratedElements = (set: Value, expression: Expression) => {
341
343
  : `TLC encountered the non-enumerable quantifier bound\n${text}\n${describeRange(expression)}\n${explanation}`,
342
344
  );
343
345
  }
344
- return typeof set === "object" && set.kind === "Interval"
345
- ? getIntervalElements(set)
346
- : toFiniteSet(set).elements;
346
+ if (typeof set === "object" && set.kind === "Interval") return getIntervalElements(set);
347
+ return getLazySubsets(set) ?? toFiniteSet(set).elements;
347
348
  };
348
349
 
349
350
  export const forEachBinding = (
@@ -1028,6 +1029,44 @@ const filteredSetRetracers = new WeakMap<
1028
1029
  (environment: Environment) => FilteredSetValue
1029
1030
  >();
1030
1031
 
1032
+ const SOURCED_KINDS = new Set<Expression["kind"]>([
1033
+ "SetEnumeration",
1034
+ "SetMap",
1035
+ "SetFilter",
1036
+ "Tuple",
1037
+ "Record",
1038
+ "RecordSet",
1039
+ "FunctionSet",
1040
+ "Product",
1041
+ ]);
1042
+
1043
+ const SOURCED_OPERATORS = new Set(["SUBSET", "UNION", "DOMAIN", "\\cup", "\\cap", "\\"]);
1044
+
1045
+ // CallStackTool gives a set, tuple or record it builds the expression as its source, but not a lazy
1046
+ // set filter, which it returns as a copy.
1047
+ const isSourced = (expression: Expression, environment: Environment) =>
1048
+ SOURCED_KINDS.has(expression.kind) ||
1049
+ (expression.kind === "Apply" &&
1050
+ SOURCED_OPERATORS.has(expression.operator) &&
1051
+ !isLocallyResolved(expression) &&
1052
+ resolveGlobalOperator(expression.operator, environment)?.kind === "Builtin");
1053
+
1054
+ // When an evaluation fails, CallStackTool freezes the stack at the innermost expression and pushes
1055
+ // the source of each value whose method failed.
1056
+ const evaluateTraced = (
1057
+ evaluator: Evaluator,
1058
+ context: Context,
1059
+ trace: Expression[],
1060
+ depth: number,
1061
+ ) => {
1062
+ try {
1063
+ return evaluator(context);
1064
+ } catch (error) {
1065
+ if (trace.length === depth + 1) trace.push(...(getFingerprintTrace(error) ?? []));
1066
+ throw error;
1067
+ }
1068
+ };
1069
+
1031
1070
  export const getEvaluator = (expression: Expression, environment: Environment): Evaluator => {
1032
1071
  const cached = environment.evaluators.get(expression);
1033
1072
  if (cached) return cached;
@@ -1039,13 +1078,17 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1039
1078
  ? cacheStateValue(compiled)
1040
1079
  : compiled;
1041
1080
  const trace = environment.trace;
1081
+ const isSourcedExpression = trace !== undefined && isSourced(expression, environment);
1042
1082
  // TLC's CallStackTool pushes each expression it evaluates and keeps the stack when one fails.
1043
1083
  const evaluator: Evaluator = trace
1044
1084
  ? (context) => {
1045
1085
  const depth = trace.length;
1046
1086
  trace.push(expression);
1047
- const value = cachedEvaluator(context);
1087
+ const value = evaluateTraced(cachedEvaluator, context, trace, depth);
1048
1088
  trace.length = depth;
1089
+ if (isSourcedExpression && typeof value === "object" && value.kind !== "FilteredSet") {
1090
+ valueSources.current?.set(value, expression);
1091
+ }
1049
1092
  const retrace =
1050
1093
  typeof value === "object" && value.kind === "FilteredSet"
1051
1094
  ? filteredSetRetracers.get(value)
@@ -1169,11 +1212,32 @@ const getLazyArguments = (args: Expression[], context: Context): OperatorValue[]
1169
1212
  expression: arg,
1170
1213
  }));
1171
1214
 
1215
+ const RECEIVING_OPERATORS = new Set(["=", "#", "\\in", "\\notin", "\\cup", "\\cap", "\\"]);
1216
+
1217
+ // The argument whose method TLC calls to apply a built-in operator.
1218
+ const getReceiver = (name: string, left: Value, right: Value) =>
1219
+ name === "\\in" ||
1220
+ name === "\\notin" ||
1221
+ ((name === "\\cup" || name === "\\cap") && !isReducible(left))
1222
+ ? right
1223
+ : left;
1224
+
1172
1225
  const compileBuiltinCall = (
1173
1226
  builtin: Builtin,
1174
1227
  args: Expression[],
1175
1228
  environment: Environment,
1176
1229
  ): Evaluator => {
1230
+ if (environment.trace && RECEIVING_OPERATORS.has(builtin.name) && args.length === 2) {
1231
+ const evaluateLeft = getEvaluator(args[0], environment);
1232
+ const evaluateRight = getEvaluator(args[1], environment);
1233
+ return (context) => {
1234
+ const left = evaluateLeft(context);
1235
+ const right = evaluateRight(context);
1236
+ return withSource(getReceiver(builtin.name, left, right), () =>
1237
+ builtin.evaluate([left, right], context),
1238
+ );
1239
+ };
1240
+ }
1177
1241
  if (builtin.isLazy) {
1178
1242
  return (context) => builtin.evaluate(getLazyArguments(args, context), context);
1179
1243
  }
@@ -1333,6 +1397,13 @@ const compileApply = (
1333
1397
  if (global?.kind === "Builtin" && global.name === "DOMAIN") {
1334
1398
  const operand = getEvaluator(args[0], environment);
1335
1399
  const domain = getDomainOperator(expression);
1400
+ // TLC builds a new interval for the domain of a tuple, so the source it gives one stays its own.
1401
+ if (environment.trace) {
1402
+ return (context) => {
1403
+ const value = domain(operand(context));
1404
+ return typeof value === "object" && value.kind === "Interval" ? { ...value } : value;
1405
+ };
1406
+ }
1336
1407
  return (context) => domain(operand(context));
1337
1408
  }
1338
1409
  // TLC sorts the value of a constant TLCEval argument only where no context binds a name.
@@ -1348,6 +1419,13 @@ const compileApply = (
1348
1419
  const left = getEvaluator(args[0], environment);
1349
1420
  const right = getEvaluator(args[1], environment);
1350
1421
  const subset = getSubsetOperator(expression, global);
1422
+ if (environment.trace) {
1423
+ return (context) => {
1424
+ const subsetValue = left(context);
1425
+ const superset = right(context);
1426
+ return withSource(subsetValue, () => subset(subsetValue, superset));
1427
+ };
1428
+ }
1351
1429
  return (context) => subset(left(context), right(context));
1352
1430
  }
1353
1431
  if (global?.kind === "Builtin") return compileBuiltinCall(global, args, environment);
@@ -1621,8 +1699,9 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1621
1699
 
1622
1700
  export const createUnassignedError = (name: string, expression: Expression) =>
1623
1701
  setOwnExitCode(
1624
- new TlaEvaluationError(
1702
+ new TlaUnassignedError(
1625
1703
  `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1704
+ name,
1626
1705
  ),
1627
1706
  EXIT_STATUS.configParseError,
1628
1707
  );
@@ -1814,6 +1893,16 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1814
1893
  const evaluateFunction = child(expression.function);
1815
1894
  const args = expression.args.map(child);
1816
1895
  const describeNonFunction = getNonFunctionError(expression);
1896
+ if (args.length === 1 && environment.trace) {
1897
+ const argument = args[0];
1898
+ return (context) => {
1899
+ const functionValue = evaluateFunction(context);
1900
+ const argumentValue = argument(context);
1901
+ const apply = () =>
1902
+ applyFunction(functionValue, argumentValue, undefined, describeNonFunction);
1903
+ return isFunctionValue(functionValue) ? withSource(functionValue, apply) : apply();
1904
+ };
1905
+ }
1817
1906
  if (args.length === 1) {
1818
1907
  const argument = args[0];
1819
1908
  return (context) =>
@@ -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/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
  };