tla-ts 0.0.3-dev.6a30eee → 0.0.3-dev.6f3cbdb

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tla-ts",
3
- "version": "0.0.3-dev.6a30eee",
3
+ "version": "0.0.3-dev.6f3cbdb",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/ast.ts CHANGED
@@ -486,3 +486,93 @@ export interface Module {
486
486
  uses: UseOrHide[];
487
487
  units: ModuleUnit[];
488
488
  }
489
+
490
+ export const getChildren = (expression: Expression): Expression[] => {
491
+ switch (expression.kind) {
492
+ case "Number":
493
+ case "Decimal":
494
+ case "String":
495
+ case "Identifier":
496
+ case "OperatorReference":
497
+ case "ExceptAt":
498
+ return [];
499
+ case "Apply":
500
+ return expression.args;
501
+ case "Lambda":
502
+ return [expression.body];
503
+ case "And":
504
+ case "Or":
505
+ return expression.operands;
506
+ case "Prime":
507
+ case "Unchanged":
508
+ case "Enabled":
509
+ case "Always":
510
+ case "Eventually":
511
+ return [expression.expression];
512
+ case "If":
513
+ return [expression.condition, expression.consequent, expression.alternative];
514
+ case "Case":
515
+ return [
516
+ ...expression.arms.flatMap((arm) => [arm.condition, arm.body]),
517
+ ...(expression.other ? [expression.other] : []),
518
+ ];
519
+ case "Let":
520
+ return [
521
+ ...expression.definitions.flatMap((definition) =>
522
+ definition.kind === "Function"
523
+ ? [...definition.bounds.map((bound) => bound.set), definition.body]
524
+ : [definition.body],
525
+ ),
526
+ expression.body,
527
+ ];
528
+ case "Forall":
529
+ case "Exists":
530
+ return [...expression.bounds.map((bound) => bound.set), expression.body];
531
+ case "UnboundedQuantifier":
532
+ return [expression.body];
533
+ case "Choose":
534
+ return [...(expression.set ? [expression.set] : []), expression.body];
535
+ case "SetEnumeration":
536
+ case "Tuple":
537
+ return expression.elements;
538
+ case "SetFilter":
539
+ return [expression.bound.set, expression.predicate];
540
+ case "SetMap":
541
+ return [expression.expression, ...expression.bounds.map((bound) => bound.set)];
542
+ case "FunctionConstruction":
543
+ return [...expression.bounds.map((bound) => bound.set), expression.body];
544
+ case "FunctionSet":
545
+ return [expression.domain, expression.range];
546
+ case "Record":
547
+ case "RecordSet":
548
+ return expression.fields.map((field) => field.value);
549
+ case "Except":
550
+ return [
551
+ expression.function,
552
+ ...expression.updates.flatMap((update) => [
553
+ ...update.path.flatMap((step) => (step.kind === "Index" ? step.args : [])),
554
+ update.value,
555
+ ]),
556
+ ];
557
+ case "FunctionApplication":
558
+ return [expression.function, ...expression.args];
559
+ case "FieldAccess":
560
+ return [expression.record];
561
+ case "Product":
562
+ return expression.factors;
563
+ case "BoxAction":
564
+ case "AngleAction":
565
+ return [expression.action, expression.subscript];
566
+ case "WeakFairness":
567
+ case "StrongFairness":
568
+ return [expression.subscript, expression.action];
569
+ case "Label":
570
+ return [expression.body];
571
+ case "Subexpression":
572
+ return expression.selectors.flatMap((selector) => ("args" in selector ? selector.args : []));
573
+ }
574
+ };
575
+
576
+ export const isLocallyResolved = (expression: Expression) =>
577
+ (expression.kind === "Identifier" || expression.kind === "Apply") &&
578
+ expression.resolution?.kind === "Local";
package/src/check.ts CHANGED
@@ -1,4 +1,11 @@
1
- import type { Assumption, Definition, Expression, SourceLocation } from "./ast";
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Assumption,
5
+ type Definition,
6
+ type Expression,
7
+ type SourceLocation,
8
+ } from "./ast";
2
9
  import { parseConfig, type ConfigValue, type ModelConfig } from "./config";
3
10
  import { getReadVariables } from "./dependencies";
4
11
  import { createEnvironment } from "./environment";
@@ -9,17 +16,15 @@ import {
9
16
  TlaModuleError,
10
17
  UNEXPECTED_EXCEPTION,
11
18
  } from "./errors";
12
- import { EXIT_STATUS, setExitCode, setNextStatePhase, withLivenessExitCode } from "./exit-codes";
19
+ import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
13
20
  import {
14
21
  describeRange,
15
22
  evaluate,
16
23
  expectBoolean,
17
24
  formatRange,
18
- getChildren,
19
25
  getDefinition,
20
26
  isConstantLevel,
21
27
  isImpure,
22
- isLocallyResolved,
23
28
  type Context,
24
29
  type Environment,
25
30
  type Scope,
@@ -42,10 +47,17 @@ import {
42
47
  } from "./successors";
43
48
  import {
44
49
  getActionLabel,
50
+ getActionSignature,
45
51
  getNextActions,
46
52
  getSpecificationValue,
47
53
  type SpecAction,
48
54
  } from "./spec-description";
55
+ import {
56
+ createStateWriter,
57
+ type GraphState,
58
+ type StateDump,
59
+ type StateWriter,
60
+ } from "./state-graph";
49
61
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
50
62
  import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
51
63
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
@@ -55,6 +67,7 @@ import { createCounterExample } from "./tlc-ext";
55
67
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
56
68
  import {
57
69
  combineHash,
70
+ formatState,
58
71
  formatValue,
59
72
  getValueHash,
60
73
  isFunctionValue,
@@ -78,6 +91,8 @@ export interface CheckOptions {
78
91
  workers?: number;
79
92
  // TLC's -lncheck: "final" checks liveness only on the complete state graph.
80
93
  livenessCheck?: "default" | "final";
94
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
95
+ dump?: StateDump;
81
96
  }
82
97
 
83
98
  export type CheckStatus =
@@ -431,12 +446,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
431
446
  config.properties.forEach((name) => {
432
447
  const definition = getConfigPredicate("property", name, environment);
433
448
  if (!definition) return;
434
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
449
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
435
450
  const conjunct = item.expression;
436
451
  if (isConstantTrue(item, environment, "property")) return;
437
452
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
438
453
  properties.actionProperties.push({
439
- name,
454
+ name: item.name,
440
455
  box: conjunct.expression,
441
456
  action: conjunct.expression.action,
442
457
  subscript: conjunct.expression.subscript,
@@ -448,12 +463,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
448
463
  conjunct.kind === "Always" &&
449
464
  getLevel(conjunct.expression, item.scope, environment) <= 1
450
465
  ) {
451
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
466
+ // TLC names the invariant []P after P when P is an operator name.
467
+ const expression = conjunct.expression;
468
+ properties.invariants.push({
469
+ name: expression.kind === "Identifier" ? expression.name : item.name,
470
+ expression,
471
+ scope: item.scope,
472
+ });
452
473
  return;
453
474
  }
454
475
  const level = getLevel(conjunct, item.scope, environment);
455
476
  if (level < ACTION_LEVEL) {
456
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
477
+ properties.initialPredicates.push({
478
+ name: item.name,
479
+ expression: conjunct,
480
+ scope: item.scope,
481
+ });
457
482
  return;
458
483
  }
459
484
  if (level === ACTION_LEVEL) {
@@ -513,7 +538,9 @@ const getMembership = (
513
538
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
514
539
  named.flatMap((item) =>
515
540
  getConjuncts(item.expression, environment).map((expression) => {
516
- const variables = getReadVariables(expression, environment);
541
+ // A LET or an argument in the scope can read variables the expression doesn't name.
542
+ const variables =
543
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
517
544
  return {
518
545
  name: item.name,
519
546
  expression,
@@ -826,7 +853,10 @@ export const createSearch = (
826
853
  )
827
854
  );
828
855
  } catch (error) {
829
- throw withHeadline(error, `Evaluating action property ${property.name} failed.`);
856
+ throw withHeadline(
857
+ withNextStateExitCode(error),
858
+ `Evaluating action property ${property.name} failed.`,
859
+ );
830
860
  }
831
861
  }),
832
862
  satisfiesActionConstraints: (state, next) =>
@@ -862,6 +892,11 @@ export const createSearch = (
862
892
  };
863
893
  };
864
894
 
895
+ // TLC exits with the code of a standard module's failure only when the failure escapes the
896
+ // computation of next states. In every other phase, the phase decides the code.
897
+ const withNextStateExitCode = (error: unknown) =>
898
+ error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
899
+
865
900
  const withHeadline = (error: unknown, headline: string) =>
866
901
  error instanceof TlaEvaluationError
867
902
  ? setExitCode(
@@ -870,8 +905,15 @@ const withHeadline = (error: unknown, headline: string) =>
870
905
  )
871
906
  : error;
872
907
 
908
+ // TLC finishes the -dump file whether or not the search finds a violation.
873
909
  export const checkSequentially = (options: CheckOptions): CheckResult => {
874
- setNextStatePhase(false);
910
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
911
+ const result = searchStates(options, stateWriter);
912
+ stateWriter?.close();
913
+ return result;
914
+ };
915
+
916
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
875
917
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
876
918
  const onPrint = options.onPrint ?? console.log;
877
919
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
@@ -1005,7 +1047,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1005
1047
  const parents: number[] = [];
1006
1048
  const actions: (string | undefined)[] = [];
1007
1049
  const depths: number[] = [];
1008
- const buckets = new Map<number, number | number[]>();
1050
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1051
+ // and its index plus one side by side, probed by the hash.
1052
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
1009
1053
  const canonicalizeState = createCanonicalizer();
1010
1054
 
1011
1055
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -1018,11 +1062,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1018
1062
  position: number,
1019
1063
  loopStart: number | undefined,
1020
1064
  ) => {
1021
- const state = steps[position].state;
1022
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
1023
1065
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
1024
1066
  runtime.getLevel = () => position + 1;
1025
1067
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1068
+ return evaluateAlias(
1069
+ alias,
1070
+ steps[position].state,
1071
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1072
+ );
1073
+ };
1074
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
1026
1075
  try {
1027
1076
  const body = getConfigDefinition("alias", alias, environment).body;
1028
1077
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -1160,19 +1209,35 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1160
1209
  }
1161
1210
  return true;
1162
1211
  };
1212
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1163
1213
  const findStateIndex = (hash: number, state: Value[]) => {
1164
- const bucket = buckets.get(hash);
1165
- if (bucket === undefined) return -1;
1166
- if (typeof bucket === "number") {
1167
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1214
+ const mask = seen.slots.length - 1;
1215
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1216
+ const entry = seen.slots[slot + 1];
1217
+ if (entry === 0) return -1;
1218
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1219
+ return entry - 1;
1220
+ }
1168
1221
  }
1169
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1222
+ };
1223
+ const insertSeen = (hash: number, entry: number) => {
1224
+ const mask = seen.slots.length - 1;
1225
+ let slot = getSlot(hash);
1226
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1227
+ seen.slots[slot] = hash;
1228
+ seen.slots[slot + 1] = entry;
1170
1229
  };
1171
1230
  const markSeen = (hash: number, index: number) => {
1172
- const bucket = buckets.get(hash);
1173
- if (bucket === undefined) buckets.set(hash, index);
1174
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1175
- else bucket.push(index);
1231
+ seen.size++;
1232
+ if (seen.size * 4 > seen.slots.length) {
1233
+ const slots = seen.slots;
1234
+ seen.slots = new Int32Array(slots.length * 2);
1235
+ seen.shift--;
1236
+ for (let slot = 0; slot < slots.length; slot += 2) {
1237
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1238
+ }
1239
+ }
1240
+ insertSeen(hash, index + 1);
1176
1241
  };
1177
1242
  const countDistinctState = (depth: number) => {
1178
1243
  runtime.distinctStates = states.length + 1;
@@ -1223,6 +1288,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1223
1288
  return current.isExpanding ? depths[current.index] + 1 : 0;
1224
1289
  };
1225
1290
 
1291
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1292
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1293
+ level,
1294
+ getLabel: () =>
1295
+ formatState(
1296
+ config.alias === undefined
1297
+ ? toRecord(state)
1298
+ : evaluateAlias(config.alias, state, undefined),
1299
+ ),
1300
+ getText: () => formatState(toRecord(state)),
1301
+ });
1302
+
1226
1303
  const visitInitialState = (state: Value[]) => {
1227
1304
  canonicalizeState(state);
1228
1305
  runtime.generatedStates++;
@@ -1239,6 +1316,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1239
1316
  countDistinctState(1);
1240
1317
  runtime.queueSize++;
1241
1318
  liveness?.addInitialState(states.length, state);
1319
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1242
1320
  }
1243
1321
  const violated = search.findViolatedInvariant(state);
1244
1322
  if (violated) {
@@ -1259,7 +1337,13 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1259
1337
  addState(state, fingerprintState, -1, undefined);
1260
1338
  return undefined;
1261
1339
  };
1262
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
1340
+ const visitSuccessor = (
1341
+ index: number,
1342
+ successor: Successor,
1343
+ liveSuccessors: LiveSuccessor[],
1344
+ source: GraphState | undefined,
1345
+ action: SpecAction | undefined,
1346
+ ) => {
1263
1347
  const state = states[index];
1264
1348
  runtime.generatedStates++;
1265
1349
  current.candidate = successor.state;
@@ -1273,6 +1357,14 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1273
1357
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1274
1358
  if (isInModel) search.trackActionPossible(state, successor.state);
1275
1359
  const existing = isInModel ? found : -1;
1360
+ if (source && isInModel) {
1361
+ stateWriter?.writeSuccessor(
1362
+ source,
1363
+ getGraphState(successor.state, depths[index] + 1),
1364
+ existing !== -1,
1365
+ action && { name: action.name, signature: getActionSignature(action) },
1366
+ );
1367
+ }
1276
1368
  if (existing !== -1 && liveness) {
1277
1369
  const stored = states[existing];
1278
1370
  const isStored = stored.every((value, position) => value === successor.state[position]);
@@ -1344,23 +1436,55 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1344
1436
  }
1345
1437
  return createSuccess();
1346
1438
  }
1439
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1440
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1441
+ const isNamingEdges = Boolean(
1442
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1443
+ );
1444
+ const forEachActionSuccessor = (
1445
+ state: Value[],
1446
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1447
+ ) => {
1448
+ if (!isNamingEdges) {
1449
+ return forEachSuccessor(
1450
+ next,
1451
+ state,
1452
+ environment,
1453
+ (successor) => onSuccessor(successor, undefined),
1454
+ spec.scope,
1455
+ );
1456
+ }
1457
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1458
+ const progress = { isStopped: false };
1459
+ return nextActions.value.reduce((count, action) => {
1460
+ if (progress.isStopped) return count;
1461
+ return (
1462
+ count +
1463
+ forEachSuccessor(
1464
+ action.expression,
1465
+ state,
1466
+ environment,
1467
+ (successor) => {
1468
+ progress.isStopped = onSuccessor(successor, action);
1469
+ return progress.isStopped;
1470
+ },
1471
+ action.scope,
1472
+ )
1473
+ );
1474
+ }, 0);
1475
+ };
1347
1476
  const expandState = (index: number) => {
1348
1477
  const state = states[index];
1349
1478
  const liveSuccessors: LiveSuccessor[] = [];
1350
- const successorCount = forEachSuccessor(
1351
- next,
1352
- state,
1353
- environment,
1354
- (successor) => {
1355
- try {
1356
- outcome.result = visitSuccessor(index, successor, liveSuccessors);
1357
- } catch (error) {
1358
- outcome.result = toFailure(error, getTrace(index, successor));
1359
- }
1360
- return outcome.result !== undefined;
1361
- },
1362
- spec.scope,
1363
- );
1479
+ const source = stateWriter && getGraphState(state, depths[index]);
1480
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1481
+ try {
1482
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1483
+ } catch (error) {
1484
+ outcome.result = toFailure(error, getTrace(index, successor));
1485
+ }
1486
+ return outcome.result !== undefined;
1487
+ });
1364
1488
  current.isExpanding = false;
1365
1489
  if (outcome.result) return outcome.result;
1366
1490
  if (successorCount === 0 && config.checkDeadlock) {
@@ -1420,7 +1544,6 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1420
1544
  periodic.time += performance.now() - now;
1421
1545
  return lasso;
1422
1546
  };
1423
- setNextStatePhase(true);
1424
1547
  for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1425
1548
  current.index = index;
1426
1549
  current.candidate = undefined;
@@ -1429,7 +1552,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1429
1552
  try {
1430
1553
  outcome.result = expandState(index);
1431
1554
  } catch (error) {
1432
- outcome.result = toFailure(error, getStateTrace(index));
1555
+ outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1433
1556
  }
1434
1557
  if (outcome.result) return outcome.result;
1435
1558
  outDegrees[getOutDegreeBucket()]++;
@@ -2,6 +2,8 @@ export interface OptionSpec {
2
2
  flag: string;
3
3
  isRequired?: boolean;
4
4
  isRepeatable?: boolean;
5
+ // How many of the arguments after the flag the option takes, when that depends on them.
6
+ getArity?: (rest: string[]) => number;
5
7
  }
6
8
 
7
9
  export interface ParsedOption {
@@ -29,27 +31,31 @@ export const defineCommand = (usage: string, specs: OptionSpec[]) => {
29
31
  const arities = new Map(
30
32
  specs.map((spec) => {
31
33
  const [name, ...values] = spec.flag.split(" ");
32
- return [name, values.length];
34
+ return [name, spec.getArity ?? (() => values.length)];
33
35
  }),
34
36
  );
35
37
  const parse = (args: string[]): ParsedArgs => {
36
38
  const options: ParsedOption[] = [];
37
39
  const positionals: string[] = [];
38
40
  const unknown: string[] = [];
41
+ const incomplete: ParsedOption[] = [];
39
42
  for (let index = 0; index < args.length; index++) {
40
- const arity = arities.get(args[index]);
41
- if (arity === undefined) {
43
+ const getArity = arities.get(args[index]);
44
+ if (getArity === undefined) {
42
45
  (args[index].startsWith("-") ? unknown : positionals).push(args[index]);
43
46
  continue;
44
47
  }
45
- options.push({ name: args[index], values: args.slice(index + 1, index + 1 + arity) });
48
+ const arity = getArity(args.slice(index + 1));
49
+ const option = { name: args[index], values: args.slice(index + 1, index + 1 + arity) };
50
+ options.push(option);
51
+ if (option.values.length < arity) incomplete.push(option);
46
52
  index += arity;
47
53
  }
48
54
  return {
49
55
  options,
50
56
  positionals,
51
57
  unknown,
52
- incomplete: options.find((option) => option.values.length < (arities.get(option.name) ?? 0)),
58
+ incomplete: incomplete[0],
53
59
  has: (name) => options.some((option) => option.name === name),
54
60
  get: (name) => options.findLast((option) => option.name === name)?.values,
55
61
  };
package/src/codegen.ts CHANGED
@@ -1,11 +1,8 @@
1
- import type { Expression } from "./ast";
2
- import { TlaEvaluationError } from "./errors";
1
+ import { getChildren, isLocallyResolved, type Expression } from "./ast";
3
2
  import {
4
- describeLocation,
5
3
  bindValue,
6
4
  expectBoolean,
7
5
  findGlobalName,
8
- getChildren,
9
6
  getEnumeratedElements,
10
7
  getConditionError,
11
8
  getConjunctError,
@@ -14,19 +11,21 @@ import {
14
11
  getEvaluator,
15
12
  getFieldError,
16
13
  isClosedConstant,
17
- isLocallyResolved,
18
14
  isTlcInteger,
19
15
  isValueArgument,
20
16
  isWorthCaching,
21
17
  keepLazy,
22
18
  resolveGlobalOperator,
19
+ createPrimeOutsideActionError,
20
+ createUnassignedError,
21
+ getSortedFields,
22
+ hasDuplicateFields,
23
23
  type Context,
24
24
  type Environment,
25
25
  type Evaluator,
26
26
  } from "./evaluate";
27
27
  import {
28
28
  applyFunction,
29
- compareValues,
30
29
  createEnumeratedSet,
31
30
  createSortedFunction,
32
31
  createTuple,
@@ -84,14 +83,10 @@ const createRuntime = () => ({
84
83
  equal: valuesEqual,
85
84
  enumerate: getEnumeratedElements,
86
85
  unassigned: (name: string, expression: Expression): never => {
87
- throw new TlaEvaluationError(
88
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
89
- );
86
+ throw createUnassignedError(name, expression);
90
87
  },
91
88
  primeOutsideAction: (expression: Expression): never => {
92
- throw new TlaEvaluationError(
93
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
94
- );
89
+ throw createPrimeOutsideActionError(expression);
95
90
  },
96
91
  prime: (context: Context): Context => ({
97
92
  environment: context.environment,
@@ -262,13 +257,8 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
262
257
  case "FieldAccess":
263
258
  return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))})`;
264
259
  case "Record": {
265
- const fields = [...expression.fields].sort((left, right) =>
266
- compareValues(left.name, right.name),
267
- );
268
- const hasDuplicates = fields.some(
269
- (field, index) => index > 0 && fields[index - 1].name === field.name,
270
- );
271
- if (hasDuplicates) return generateDelegate(generator, expression, frame);
260
+ const fields = getSortedFields(expression.fields);
261
+ if (hasDuplicateFields(fields)) return generateDelegate(generator, expression, frame);
272
262
  const names = addReference(
273
263
  generator,
274
264
  fields.map((field) => field.name),
@@ -1,5 +1,5 @@
1
- import type { Definition, Expression } from "./ast";
2
- import { getChildren, isImpureBuiltin, type Environment } from "./evaluate";
1
+ import { getChildren, type Definition, type Expression } from "./ast";
2
+ import { isImpureBuiltin, type Environment } from "./evaluate";
3
3
 
4
4
  const STATE_INDEPENDENT_KINDS = new Set([
5
5
  "Prime",