tla-ts 0.0.8-dev.d9bffda → 0.0.9-dev.0dd11f695

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 (119) hide show
  1. package/README.md +30 -0
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +15 -15
  5. package/dist/deciders.js +40 -40
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +80 -10
  8. package/dist/index.d.ts +80 -10
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +116 -36
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +1 -1
  20. package/dist/transfer.cjs +128 -103
  21. package/dist/transfer.js +128 -103
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +3 -1
  25. package/src/ast.ts +7 -21
  26. package/src/bags.ts +99 -99
  27. package/src/builtins.ts +44 -75
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check.ts +605 -311
  30. package/src/cli/options.ts +12 -3
  31. package/src/cli/run.ts +2 -2
  32. package/src/cli/runtime-invariants.ts +135 -0
  33. package/src/cli/shared.ts +20 -9
  34. package/src/cli/tlc-arguments.ts +646 -0
  35. package/src/cli/tlc-usage.ts +362 -0
  36. package/src/cli/tlc.ts +571 -185
  37. package/src/cli/typescript.ts +26 -0
  38. package/src/cli/xml-exporter.ts +4 -10
  39. package/src/codegen.ts +190 -46
  40. package/src/config.ts +101 -68
  41. package/src/coverage.ts +855 -0
  42. package/src/dependencies.ts +20 -28
  43. package/src/dfid.ts +636 -0
  44. package/src/environment.ts +266 -98
  45. package/src/errors.ts +142 -45
  46. package/src/evaluate.ts +632 -298
  47. package/src/exit-codes.ts +37 -1
  48. package/src/index.ts +3 -0
  49. package/src/instances.ts +85 -9
  50. package/src/java-overrides.ts +2 -12
  51. package/src/json-reader.ts +456 -0
  52. package/src/json.ts +262 -139
  53. package/src/levels.ts +2 -3
  54. package/src/lexer.ts +17 -26
  55. package/src/liveness-checker.ts +10 -18
  56. package/src/liveness.ts +121 -49
  57. package/src/parallel-worker.ts +14 -10
  58. package/src/parallel.ts +41 -17
  59. package/src/parser.ts +436 -90
  60. package/src/pcal/ast.ts +7 -28
  61. package/src/pcal/parse.ts +11 -39
  62. package/src/pcal/tokenize.ts +4 -20
  63. package/src/pcal/translate.ts +10 -42
  64. package/src/pcal/validate.ts +3 -21
  65. package/src/pretty-print.ts +1 -2
  66. package/src/prover/smt/solver/solver.ts +31 -27
  67. package/src/randomization.ts +84 -35
  68. package/src/resolve.ts +18 -60
  69. package/src/runtime.ts +11 -4
  70. package/src/sany/builtins.ts +3 -4
  71. package/src/sany/generator.ts +128 -176
  72. package/src/sany/levels.ts +6 -30
  73. package/src/sany/lexer.ts +7 -23
  74. package/src/sany/linter.ts +31 -29
  75. package/src/sany/modules.ts +1 -5
  76. package/src/sany/nodes.ts +4 -28
  77. package/src/sany/parse-error.ts +44 -100
  78. package/src/sany/report.ts +25 -40
  79. package/src/sany/selectors.ts +8 -22
  80. package/src/sany/source.ts +8 -15
  81. package/src/sany/xml.ts +11 -42
  82. package/src/search.ts +547 -144
  83. package/src/simulate.ts +694 -0
  84. package/src/spec-description.ts +166 -48
  85. package/src/standard-definitions.ts +2 -3
  86. package/src/standard-modules.ts +264 -68
  87. package/src/state-graph.ts +51 -18
  88. package/src/subexpressions.ts +31 -5
  89. package/src/successors.ts +267 -77
  90. package/src/symmetry.ts +31 -8
  91. package/src/tableau.ts +1 -2
  92. package/src/tlc/fingerprint.ts +183 -61
  93. package/src/tlc/jar-data.ts +113 -6
  94. package/src/tlc/messages.ts +122 -37
  95. package/src/tlc/order.ts +33 -38
  96. package/src/tlc/random.ts +16 -16
  97. package/src/tlc/replay.ts +563 -211
  98. package/src/tlc/summary.ts +2 -4
  99. package/src/tlc/tlc-operators.ts +81 -36
  100. package/src/tlc/tlcext-operators.ts +138 -117
  101. package/src/tlc/trace-spec.ts +273 -0
  102. package/src/tlc/value-stream.ts +143 -0
  103. package/src/tlc/version.ts +2 -4
  104. package/src/typescript/actions.ts +494 -0
  105. package/src/typescript/collections.ts +615 -0
  106. package/src/typescript/compile.ts +70 -0
  107. package/src/typescript/context.ts +106 -0
  108. package/src/typescript/emit.ts +122 -0
  109. package/src/typescript/expressions.ts +508 -0
  110. package/src/typescript/formula.ts +160 -0
  111. package/src/typescript/functions.ts +295 -0
  112. package/src/typescript/model.ts +164 -0
  113. package/src/typescript/names.ts +116 -0
  114. package/src/typescript/program.ts +51 -0
  115. package/src/typescript/properties.ts +148 -0
  116. package/src/typescript/scope.ts +117 -0
  117. package/src/typescript/steps.ts +175 -0
  118. package/src/typescript/types.ts +178 -0
  119. package/src/values.ts +832 -255
@@ -31,7 +31,6 @@ import {
31
31
  type PcalWhile,
32
32
  } from "./ast";
33
33
 
34
- // PcalSymTab's symbol types, which index PCAL_SYMBOL_TYPE_NAMES.
35
34
  const PCAL_SYMBOL = {
36
35
  global: 0,
37
36
  label: 1,
@@ -69,7 +68,7 @@ interface PcalSymbol {
69
68
  useThis: string;
70
69
  }
71
70
 
72
- // PcalSymTab.ProcedureEntry. initialPC is the first label, which a body with no statements lacks.
71
+ // initialPC is the first label, which a body with no statements lacks.
73
72
  interface PcalProcedureEntry {
74
73
  name: string;
75
74
  params: PcalPVarDecl[];
@@ -128,8 +127,6 @@ const useThisVar = (table: PcalSymbolTable, id: string, context: string) => {
128
127
  return PCAL_VARIABLE_SYMBOLS.has(symbol.type) ? symbol.useThis : id;
129
128
  };
130
129
 
131
- // The PcalSymTab constructor: collects the algorithm's variables, labels, procedures and processes,
132
- // reporting every redefinition at once.
133
130
  const createPcalSymbolTable = (ast: PcalAlgorithm) => {
134
131
  const table: PcalSymbolTable = {
135
132
  symbols: [],
@@ -249,8 +246,6 @@ const createPcalSymbolTable = (ast: PcalAlgorithm) => {
249
246
  return table;
250
247
  };
251
248
 
252
- // PcalSymTab.Disambiguate: renames each symbol whose name another symbol already uses, by
253
- // appending "_", then the letters of its context, then its type. Returns whether it renamed any.
254
249
  const disambiguatePcalSymbols = (table: PcalSymbolTable) => {
255
250
  const isAmbiguous = (id: string) =>
256
251
  table.symbols.filter((symbol) => symbol.useThis === id).length > 1;
@@ -269,7 +264,6 @@ const disambiguatePcalSymbols = (table: PcalSymbolTable) => {
269
264
  return renamed.isAny;
270
265
  };
271
266
 
272
- // PcalSymTab.CheckForDefaultInitValue.
273
267
  const checkForDefaultInitValue = (table: PcalSymbolTable) => {
274
268
  const uses = table.symbols
275
269
  .filter((symbol) => symbol.id === "defaultInitValue")
@@ -279,8 +273,6 @@ const checkForDefaultInitValue = (table: PcalSymbolTable) => {
279
273
  }
280
274
  };
281
275
 
282
- // PcalFixIDs.Fix: replaces every identifier with the name PcalSymTab.Disambiguate chose for it, and
283
- // closes each process's set of called procedures over the procedures they call.
284
276
  const fixPcalIds = (ast: PcalAlgorithm, table: PcalSymbolTable, log: (line: string) => void) => {
285
277
  const fixExpr = (expr: PcalExpr, context: string) => {
286
278
  const names: string[] = [];
@@ -425,8 +417,8 @@ const fixPcalIds = (ast: PcalAlgorithm, table: PcalSymbolTable, log: (line: stri
425
417
  process.name = useThis(table, PCAL_SYMBOL.process, process.name, "");
426
418
  };
427
419
 
428
- // PcalFixIDs.FixMultiprocess: a process calling an unknown procedure stops the fixing of the
429
- // remaining processes with an error message, but not the translation.
420
+ // A process calling an unknown procedure stops the fixing of the remaining processes with an
421
+ // error message, but not the translation.
430
422
  const fixMultiprocess = (procedures: PcalProcedure[], processes: PcalProcess[]) => {
431
423
  procedures.forEach(fixProcedure);
432
424
  const procedureNames = procedures.map((procedure) => procedure.name);
@@ -473,13 +465,11 @@ const fixPcalIds = (ast: PcalAlgorithm, table: PcalSymbolTable, log: (line: stri
473
465
  }
474
466
  };
475
467
 
476
- // PcalTranslate's token constructors, which leave the column 0.
477
468
  const stringToken = (string: string) => createPcalToken(string, 0, PCAL_TOKEN.string);
478
469
  const addedToken = (string: string) => createPcalToken(string, 0, PCAL_TOKEN.added);
479
470
  const builtInToken = (string: string) => createPcalToken(string, 0, PCAL_TOKEN.builtin);
480
471
  const identToken = (string: string) => createPcalToken(string, 0, PCAL_TOKEN.ident);
481
472
 
482
- // PcalTranslate.TokVectorToExpr: copies the tokens onto one line, spaces columns apart.
483
473
  const tokensToExpr = (tokens: PcalToken[], spaces: number) => {
484
474
  const line: PcalToken[] = [];
485
475
  tokens.forEach((token) => {
@@ -491,8 +481,6 @@ const tokensToExpr = (tokens: PcalToken[], spaces: number) => {
491
481
  return createNormalizedPcalExpr([line]);
492
482
  };
493
483
 
494
- // PcalTranslate.MakeNewStackTopExprPretty: lays out a pushed stack frame one field per line with
495
- // the "|->" aligned.
496
484
  const prettifyStackTopExpr = (expr: PcalExpr) =>
497
485
  expr.tokens.forEach((line, lineIndex) => {
498
486
  const cursor = { column: lineIndex === 0 || lineIndex === expr.tokens.length - 1 ? 1 : 6 };
@@ -522,7 +510,6 @@ const prettifyStackTopExpr = (expr: PcalExpr) =>
522
510
  });
523
511
  });
524
512
 
525
- // A new AST.SingleAssign and AST.Assign, whose line and column default to 0.
526
513
  const createSingleAssign = (
527
514
  variable: string,
528
515
  sub: PcalExpr,
@@ -553,7 +540,7 @@ const makeAssign = (variable: string, expr: PcalExpr, line = 0, col = 0) =>
553
540
  col,
554
541
  );
555
542
 
556
- // PcalTranslate.IsTRUE, which indexes the first line of an expression without checking it has one.
543
+ // PcalTranslate.IsTRUE indexes the first line of an expression without checking it has one.
557
544
  const isTrue = (expr: PcalExpr) => {
558
545
  if (expr.tokens.length > 1) return false;
559
546
  const line = getElement(expr.tokens, 0);
@@ -575,7 +562,6 @@ const checkPC = (label: string): PcalWhen => ({
575
562
  const updatePC = (next: string | undefined) =>
576
563
  makeAssign("pc", createNormalizedPcalExpr([[stringToken(next ?? "null")]]));
577
564
 
578
- // `Head(stack).field`.
579
565
  const getStackHeadTokens = (field: string) => [
580
566
  identToken("Head"),
581
567
  builtInToken("("),
@@ -585,7 +571,6 @@ const getStackHeadTokens = (field: string) => [
585
571
  identToken(field),
586
572
  ];
587
573
 
588
- // `Tail(stack)`.
589
574
  const getStackTailTokens = () => [
590
575
  identToken("Tail"),
591
576
  builtInToken("("),
@@ -596,8 +581,6 @@ const getStackTailTokens = () => [
596
581
  const createStackHeadExpr = (field: string) =>
597
582
  createNormalizedPcalExpr([getStackHeadTokens(field)]);
598
583
 
599
- // The `<< [ procedure |-> "name", pc |-> ..., var |-> var ] >> \o ...` that ExplodeCall and
600
- // ExplodeCallReturn push onto the stack.
601
584
  const createStackPushExpr = (
602
585
  procedure: string,
603
586
  pcTokens: PcalToken[],
@@ -627,8 +610,6 @@ const createStackPushExpr = (
627
610
  return expr;
628
611
  };
629
612
 
630
- // The statements a call explodes into after its stack push: the parameters' and the procedure
631
- // variables' initial values and the jump to the procedure's first label.
632
613
  const createCallStmts = (
633
614
  assign: PcalAssign,
634
615
  entry: PcalProcedureEntry,
@@ -655,23 +636,19 @@ const createCallStmts = (
655
636
  ];
656
637
  };
657
638
 
658
- // CopyAndExplodeLastStmt's triple: the statements with their last one exploded, the labeled
659
- // statements the explosion split off, and whether control falls off the end needing a pc update.
660
639
  interface PcalExplodedStmts {
661
640
  stmts: PcalStmt[];
662
641
  labeledStmts: PcalLabeledStmt[];
663
642
  needsGoto: boolean;
664
643
  }
665
644
 
666
- // PcalTranslate.Explode: turns each labeled statement into an atomic action that checks and sets
667
- // pc, and calls, returns and gotos into stack and pc assignments. Statement lists nested in the
668
- // original AST are exploded in place, as the Java does, so the original AST changes too.
645
+ // Statement lists nested in the original AST are exploded in place, as the Java does, so the
646
+ // original AST changes too.
669
647
  const explodePcalAlgorithm = (
670
648
  ast: PcalAlgorithm,
671
649
  table: PcalSymbolTable,
672
650
  omitPC: boolean,
673
651
  ): PcalAlgorithm => {
674
- // The procedure being exploded, which a return comes from.
675
652
  const context: { procedure: string | undefined } = { procedure: undefined };
676
653
 
677
654
  const explodeCall = (call: PcalCall, next: string) => {
@@ -752,8 +729,6 @@ const explodePcalAlgorithm = (
752
729
  return createCallStmts(assign, toEntry, stmt);
753
730
  };
754
731
 
755
- // PcalTranslate.CopyAndExplodeLastStmt: explodes the last statement of stmts in place, recursing
756
- // into the branches of a trailing if, either or with.
757
732
  const copyAndExplodeLastStmt = (stmts: PcalStmt[], next: string): PcalExplodedStmts => {
758
733
  if (stmts.length === 0) return { stmts: [], labeledStmts: [], needsGoto: !omitPC };
759
734
  const result: PcalExplodedStmts = { stmts, labeledStmts: [], needsGoto: false };
@@ -877,8 +852,6 @@ const explodePcalAlgorithm = (
877
852
  explodeLabeledStmt(labeledStmt, index < seq.length - 1 ? seq[index + 1].label : next),
878
853
  );
879
854
 
880
- // PcalTranslate.ExplodeWhile: the loop's label tests the condition, running the unlabeled body
881
- // or the statements after the loop.
882
855
  const explodeWhile = (labeledStmt: PcalLabeledStmt, loop: PcalWhile, next: string) => {
883
856
  const unlabDoNext = loop.labDo.length === 0 ? labeledStmt.label : loop.labDo[0].label;
884
857
  const explodedBody = copyAndExplodeLastStmtWithGoto([...loop.unlabDo], unlabDoNext);
@@ -1024,10 +997,7 @@ const explodePcalAlgorithm = (
1024
997
  };
1025
998
  };
1026
999
 
1027
- // The parts of PcalTLAGen.generate that change the AST or throw: GenVarsAndDefs's check that
1028
- // there are variables, and GenAssign's sorting of multiple assignments and its checks that each
1029
- // variable is declared and assigned at most once per step. Changed counts the assignments to each
1030
- // variable along the paths through a labeled statement.
1000
+ // Only the parts of PcalTLAGen.generate that change the AST or throw.
1031
1001
  const checkPcalTlaGen = (explodedAst: PcalAlgorithm, omitPC: boolean) => {
1032
1002
  const vars = omitPC ? [] : ["pc"];
1033
1003
  vars.push(...explodedAst.decls.map((decl) => decl.var));
@@ -1041,7 +1011,7 @@ const checkPcalTlaGen = (explodedAst: PcalAlgorithm, omitPC: boolean) => {
1041
1011
  }
1042
1012
  if (vars.length === 0) throw new PcalError("The algorithm has no variables.");
1043
1013
 
1044
- // Changed.Set, which counts only the first of duplicate variable names.
1014
+ // Changed.Set counts only the first of duplicate variable names.
1045
1015
  const setChanged = (changed: number[], variable: string) => {
1046
1016
  const index = vars.indexOf(variable);
1047
1017
  if (index === -1) return 0;
@@ -1063,7 +1033,6 @@ const checkPcalTlaGen = (explodedAst: PcalAlgorithm, omitPC: boolean) => {
1063
1033
  const genAssign = (assign: PcalAssign, changed: number[]) => {
1064
1034
  const thisChanged = [...changed];
1065
1035
  assign.ass = sortSass(assign.ass);
1066
- // The sort puts the assignments to each variable next to each other.
1067
1036
  new Set(assign.ass.map((single) => single.lhs.var)).forEach((variable) => {
1068
1037
  const group = assign.ass.filter((single) => single.lhs.var === variable);
1069
1038
  if (!vars.includes(variable)) {
@@ -1134,9 +1103,8 @@ const checkPcalTlaGen = (explodedAst: PcalAlgorithm, omitPC: boolean) => {
1134
1103
  ).forEach(genBody);
1135
1104
  };
1136
1105
 
1137
- // PCalTLAGenerator.removeNameConflicts followed by translate, for what they do to the AST and the
1138
- // errors they report: the symbol table's renaming, PcalFixIDs, PcalTranslate.Explode and the checks
1139
- // PcalTLAGen makes while generating the TLA+ translation, which SANY discards.
1106
+ // What removeNameConflicts and translate do to the AST, and the errors they report, without the
1107
+ // TLA+ translation, which SANY discards.
1140
1108
  export const translatePcalAlgorithm = (
1141
1109
  ast: PcalAlgorithm,
1142
1110
  omitPC: boolean,
@@ -11,7 +11,6 @@ import { createPcalCharReader } from "./tokenize";
11
11
  import { translatePcalAlgorithm } from "./translate";
12
12
  import type { TlcVersion } from "../tlc/version";
13
13
 
14
- // Validator.ValidationResult.
15
14
  type PcalValidationResult =
16
15
  | "NO_PLUSCAL_EXISTS"
17
16
  | "NO_TRANSLATION_EXISTS"
@@ -29,15 +28,14 @@ const CHECKSUM_PATTERN = new RegExp(
29
28
  `\\\\\\* BEGIN TRANSLATION${SPACE}+\\(${SPACE}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([pP]([lL][uU][sS])?[cC][aA][lL]\\))${SPACE}*(=${SPACE}*"(?<pcal>[0-9A-Fa-f]*)"|\\\\in${SPACE}*STRING)${SPACE}*\\/\\\\${SPACE}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([tT][lL][aA]\\+?\\))${SPACE}*(=${SPACE}*"(?<tla>[0-9A-Fa-f]*)"|\\\\in${SPACE}*STRING)${SPACE}*\\)`,
30
29
  );
31
30
 
32
- // Validator.checksum: CRC32 of the string's bytes, in Long.toHexString's unpadded lowercase hex.
33
- // Only a spec with PlusCal needs node:zlib, so it loads then rather than at startup.
31
+ // CRC32 in Long.toHexString's unpadded lowercase hex. Only a spec with PlusCal needs node:zlib,
32
+ // so it loads then rather than at startup.
34
33
  const getChecksum = (text: string) =>
35
34
  process.getBuiltinModule("node:zlib").crc32(Buffer.from(text, "utf8")).toString(16);
36
35
 
37
36
  const reportUnrecoverableError = (session: PcalSession, message: string) =>
38
37
  session.log(`\nUnrecoverable error:\n -- ${message}.\n`);
39
38
 
40
- // PcalDebug.reportError: an UnrecoverablePositionedException names its statement's position.
41
39
  const reportPcalError = (session: PcalSession, error: PcalError) =>
42
40
  reportUnrecoverableError(
43
41
  session,
@@ -57,7 +55,6 @@ const removeTabs = (lines: string[]) =>
57
55
  )} `,
58
56
  );
59
57
 
60
- // trans.findTokenPair: the first line from start with first followed by second after spaces.
61
58
  const findTokenPair = (lines: string[], start: number, first: string, second: string) => {
62
59
  for (let index = Math.max(start, 0); index < lines.length; index++) {
63
60
  const line = lines[index];
@@ -75,8 +72,6 @@ interface PcalSearchLocation {
75
72
  column: number;
76
73
  }
77
74
 
78
- // ParseAlgorithm.GotoNextNonSpace: moves the location to the next character that isn't a space,
79
- // returning its line, or "" past the last line.
80
75
  const gotoNextNonSpace = (lines: string[], location: PcalSearchLocation) => {
81
76
  while (location.line < lines.length) {
82
77
  const line = lines[location.line];
@@ -88,8 +83,6 @@ const gotoNextNonSpace = (lines: string[], location: PcalSearchLocation) => {
88
83
  return "";
89
84
  };
90
85
 
91
- // ParseAlgorithm.NextSpaceCol and NextDelimiterCol: the first delimiter from column on, or the
92
- // end of the line.
93
86
  const getNextDelimiter = (line: string, column: number, delimiters: string) => {
94
87
  const index = Array.from(line.slice(column)).findIndex((char) => delimiters.includes(char));
95
88
  return index === -1 ? line.length : column + line.slice(column, column + index).length;
@@ -97,8 +90,6 @@ const getNextDelimiter = (line: string, column: number, delimiters: string) => {
97
90
 
98
91
  const isIdChar = (char: string) => /^[\p{L}\p{Nd}_]$/u.test(char);
99
92
 
100
- // ParseAlgorithm.FindToken: moves the location past the next occurrence of token that starts a
101
- // word and isn't followed by a letter or "_".
102
93
  const findToken = (lines: string[], location: PcalSearchLocation, token: string) => {
103
94
  while (location.line < lines.length) {
104
95
  const line = gotoNextNonSpace(lines, location);
@@ -114,12 +105,10 @@ const findToken = (lines: string[], location: PcalSearchLocation, token: string)
114
105
  return false;
115
106
  };
116
107
 
117
- // trans.CommandLineError.
118
108
  const reportCommandLineError = (session: PcalSession, message: string) =>
119
109
  reportUnrecoverableError(session, `Command-line error: ${message}`);
120
110
 
121
- // trans.parseAndProcessArguments for the options of a "PlusCal options" statement, which set the
122
- // translator's options for the rest of SANY's run.
111
+ // These options set the translator's options for the rest of SANY's run.
123
112
  const processOptionArguments = (session: PcalSession, args: string[]) => {
124
113
  const params = session.params;
125
114
  const fairness = { isFirst: true, isExplicitNof: false };
@@ -208,7 +197,6 @@ const processOptionArguments = (session: PcalSession, args: string[]) => {
208
197
  reportCommandLineError(session, "Version number must follow `-version' option");
209
198
  return;
210
199
  }
211
- // PcalParams.ProcessVersion.
212
200
  const version = getPcalVersionNumber(argument);
213
201
  if (version < 0 || version > PCAL_VERSION_WEIGHT) {
214
202
  reportUnrecoverableError(
@@ -248,7 +236,6 @@ const processOptionArguments = (session: PcalSession, args: string[]) => {
248
236
  }
249
237
  };
250
238
 
251
- // ParseAlgorithm.ProcessOptions: the location is just past "PlusCal".
252
239
  const processOptions = (session: PcalSession, lines: string[], location: PcalSearchLocation) => {
253
240
  gotoNextNonSpace(lines, location);
254
241
  location.column += "options".length;
@@ -277,9 +264,6 @@ const processOptions = (session: PcalSession, lines: string[], location: PcalSea
277
264
  processOptionArguments(session, args);
278
265
  };
279
266
 
280
- // ParseAlgorithm.uncomment: blanks out the comment delimiters and nested comments from the
281
- // algorithm's start to the "*)" that ends the comment it is in, dropping the rest of that line,
282
- // and returns the error it throws for a line that ends in a string.
283
267
  const uncomment = (lines: string[], startLine: number, startColumn: number) => {
284
268
  const scan = { depth: 0, isDone: false, isInString: false };
285
269
  for (let index = startLine; !scan.isDone && index < lines.length; index++) {
@@ -338,8 +322,6 @@ const throwIndexOutOfBounds = (index: number, size: number): never => {
338
322
  );
339
323
  };
340
324
 
341
- // Validator.validate: checks the PlusCal algorithm of the module whose lines are given, from its
342
- // first to its last, against the checksums its translation records.
343
325
  export const validatePcalModule = (
344
326
  session: PcalSession,
345
327
  specificationText: string[],
@@ -1,5 +1,4 @@
1
- // A port of TLC's tlc2.pprint package, which re-parses a printed value and breaks it across
2
- // lines of at most 80 columns. TLC prints the original text whenever the parse fails.
1
+ // A port of TLC's tlc2.pprint package. TLC prints the original text whenever the parse fails.
3
2
 
4
3
  import { skipWhile } from "./lexer";
5
4
 
@@ -21,36 +21,40 @@ export const checkSmt = (text: string, options: DecideOptions): SmtCheck => {
21
21
  const manager = new AstManager(
22
22
  new ResourceLimit(Date.now() + options.timeLimitMs, options.signal),
23
23
  );
24
- // combined_solver gives each assertion to the incremental smt kernel as well, which rewrites it
25
- // when it is asserted and keeps it, though check-sat then runs the tactic on the assertions. The
26
- // kernel's model finder counts a step of the resource limit when it is made, and
27
- // solver::assert_expr counts one for each assertion.
28
- const incremental = new AssertedFormulas(manager);
29
- manager.limit.inc();
30
- const problem = parseSmtlib(text, manager, (assertion) => {
24
+ // The limit stops watching the collector however the check ends, as an unsupported input or a
25
+ // problem without check-sat ends it early.
26
+ try {
27
+ // combined_solver gives each assertion to the incremental smt kernel as well, which rewrites it
28
+ // when it is asserted and keeps it, though check-sat then runs the tactic on the assertions. The
29
+ // kernel's model finder counts a step of the resource limit when it is made, and
30
+ // solver::assert_expr counts one for each assertion.
31
+ const incremental = new AssertedFormulas(manager);
31
32
  manager.limit.inc();
32
- incremental.assertExpr(assertion);
33
- });
34
- if (!problem.hasCheckSat) return { verdict: "unknown", numInstances: 0 };
35
- const goal = applyUfniaTactic(manager, problem.assertions);
36
- // and_then runs smt_tactic only on a goal that the preprocessing left undecided.
37
- if (goal.isInconsistent || goal.forms.size === 0) {
33
+ const problem = parseSmtlib(text, manager, (assertion) => {
34
+ manager.limit.inc();
35
+ incremental.assertExpr(assertion);
36
+ });
37
+ if (!problem.hasCheckSat) return { verdict: "unknown", numInstances: 0 };
38
+ const goal = applyUfniaTactic(manager, problem.assertions);
39
+ // and_then runs smt_tactic only on a goal that the preprocessing left undecided.
40
+ if (goal.isInconsistent || goal.forms.size === 0) {
41
+ return { verdict: goal.isInconsistent ? "unsat" : "sat", numInstances: 0 };
42
+ }
43
+ // smt_tactic makes the context, which makes its asserted formulas first, and asserts the goal.
44
+ // setup_context then makes the theories, before the formulas are reduced.
45
+ const asserted = new AssertedFormulas(manager);
46
+ const context = new Context(manager, { isMbqi: true, relevancyLevel: 2 });
47
+ for (const assertion of goal.forms.items) asserted.assertExpr(assertion);
48
+ context.setupContext();
49
+ context.internalizeAssertions(asserted);
50
+ const result = context.search();
51
+ return {
52
+ verdict: result === L_FALSE ? "unsat" : result === L_TRUE ? "sat" : "unknown",
53
+ numInstances: context.qmanager.getNumInstances(),
54
+ };
55
+ } finally {
38
56
  manager.limit.release();
39
- return { verdict: goal.isInconsistent ? "unsat" : "sat", numInstances: 0 };
40
57
  }
41
- // smt_tactic makes the context, which makes its asserted formulas first, and asserts the goal.
42
- // setup_context then makes the theories, before the formulas are reduced.
43
- const asserted = new AssertedFormulas(manager);
44
- const context = new Context(manager, { isMbqi: true, relevancyLevel: 2 });
45
- for (const assertion of goal.forms.items) asserted.assertExpr(assertion);
46
- context.setupContext();
47
- context.internalizeAssertions(asserted);
48
- const result = context.search();
49
- manager.limit.release();
50
- return {
51
- verdict: result === L_FALSE ? "unsat" : result === L_TRUE ? "sat" : "unknown",
52
- numInstances: context.qmanager.getNumInstances(),
53
- };
54
58
  };
55
59
 
56
60
  // Throws SmtParseError on malformed input. Input outside the subset the solver supports is unknown,
@@ -1,18 +1,19 @@
1
- import {
2
- createJavaOverrideError,
3
- createModuleArgumentError,
4
- defineStateOperator,
5
- getValue,
6
- } from "./builtins";
1
+ import { createModuleArgumentError, defineOperator, getValue, overrideWithJava } from "./builtins";
2
+ import { TlaEvaluationError } from "./errors";
7
3
  import type { Builtin, BuiltinArgument } from "./evaluate";
8
4
  import type { CheckerRuntime } from "./runtime";
9
5
  import { getEnumeratedFactors, getRandomSubset, type JavaRandom } from "./tlc/random";
10
6
  import {
11
7
  createSet,
12
8
  createTuple,
13
- isEmptySet,
9
+ getCardinality,
10
+ isTlcEnumerable,
14
11
  isEnumerable,
12
+ isFiniteSet,
13
+ isOverriddenSet,
15
14
  isSetValue,
15
+ getMaximumSetSize,
16
+ getSetBoundMessage,
16
17
  toFiniteSet,
17
18
  type Value,
18
19
  } from "./values";
@@ -20,9 +21,6 @@ import {
20
21
  const RANDOM_SUBSET_SIGNATURE =
21
22
  "public static tlc2.value.impl.Value tlc2.module.Randomization.RandomSubset(tlc2.value.impl.Value,tlc2.value.impl.Value)";
22
23
 
23
- // TLCGlobals.setBound: TLC 1.7.4's ValueVec holds at most this many elements of a set.
24
- const SET_BOUND_174 = 1000000;
25
-
26
24
  const getCount = (value: Value, position: string, name: string) => {
27
25
  if (typeof value !== "number" || value < 0) {
28
26
  throw createModuleArgumentError(position, name, "nonnegative integer", value);
@@ -30,7 +28,6 @@ const getCount = (value: Value, position: string, name: string) => {
30
28
  return value;
31
29
  };
32
30
 
33
- // SubsetValue.CoinTossingSubsetEnumerator: each pick keeps each element with the probability.
34
31
  const tossSubsets = (elements: Value[], picks: number, probability: number, random: JavaRandom) =>
35
32
  createSet(
36
33
  Array.from({ length: picks }, () =>
@@ -71,36 +68,88 @@ const getRandomSetOfSubsets = (args: BuiltinArgument[], runtime: CheckerRuntime)
71
68
  );
72
69
  };
73
70
 
74
- export const createRandomizationOperators = (runtime: CheckerRuntime): Builtin[] => [
75
- defineStateOperator("RandomSubset", 2, (args) => {
76
- const count = getValue(args, 0, "RandomSubset");
77
- if (typeof count !== "number") {
78
- throw createModuleArgumentError("first", "RandomSubset", "nonnegative integer", count);
71
+ const JAVA_DECIMAL = /^[+-]?(?:NaN|Infinity|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?[fFdD]?)$/;
72
+ const JAVA_HEXADECIMAL = /^([+-]?)0[xX]([0-9a-fA-F]*)(?:\.([0-9a-fA-F]*))?[pP]([+-]?\d+)[fFdD]?$/;
73
+
74
+ const parseJavaDouble = (text: string) => {
75
+ const trimmed = text.replace(/^[^!-\uffff]+|[^!-\uffff]+$/g, "");
76
+ if (JAVA_DECIMAL.test(trimmed)) return Number(trimmed.replace(/[fFdD]$/, ""));
77
+ const hexadecimal = JAVA_HEXADECIMAL.exec(trimmed);
78
+ if (!hexadecimal) return undefined;
79
+ const fraction = hexadecimal[3] ?? "";
80
+ const digits = `${hexadecimal[2]}${fraction}`;
81
+ if (digits === "") return undefined;
82
+ const magnitude =
83
+ Number.parseInt(digits, 16) * 2 ** (Number(hexadecimal[4]) - 4 * fraction.length);
84
+ return hexadecimal[1] === "-" ? -magnitude : magnitude;
85
+ };
86
+
87
+ // TLC's Java class names the operator RandomSubsetSetProbability in its errors.
88
+ export const createRandomSubsetSet = (runtime: CheckerRuntime) =>
89
+ defineOperator("RandomSubsetSet", 3, (args) => {
90
+ const name = "RandomSubsetSetProbability";
91
+ const picks = getCount(getValue(args, 0, name), "first", name);
92
+ const text = getValue(args, 1, name);
93
+ if (typeof text !== "string") {
94
+ throw createModuleArgumentError(
95
+ "second",
96
+ name,
97
+ "string literal representing a probability",
98
+ text,
99
+ );
79
100
  }
80
- if (count < 0) {
81
- throw createJavaOverrideError(RANDOM_SUBSET_SIGNATURE, String(count));
101
+ const probability = parseJavaDouble(text);
102
+ if (probability === undefined || probability < 0 || probability > 1) {
103
+ throw createModuleArgumentError(
104
+ "second",
105
+ name,
106
+ "string literal does not represent a parsable probability",
107
+ text,
108
+ );
82
109
  }
83
- const set = getValue(args, 1, "RandomSubset");
84
- if (!isSetValue(set) || (!isEmptySet(set) && !isEnumerable(set))) {
85
- throw createModuleArgumentError("second", "RandomSubset", "a finite set", set);
110
+ const set = getValue(args, 2, name);
111
+ if (!isSetValue(set) || isOverriddenSet(set) || !isFiniteSet(set)) {
112
+ throw createModuleArgumentError("third", name, "finite set", set);
86
113
  }
87
- const factors = getEnumeratedFactors(set, runtime.version);
88
- if (factors) {
89
- const size = factors.reduce<number>(
90
- (total, factor) => total * toFiniteSet(factor).elements.length,
91
- 1,
114
+ const size = getCardinality(set);
115
+ if (32 - Math.clz32(picks) > size && picks > 1 << size) {
116
+ throw createModuleArgumentError(
117
+ "first",
118
+ name,
119
+ `nonnegative integer that is smaller than the subset's size of 2^${size}`,
120
+ picks,
92
121
  );
93
- if (size > SET_BOUND_174) {
94
- throw createJavaOverrideError(
95
- RANDOM_SUBSET_SIGNATURE,
96
- `Attempted to construct a set with too many elements (>${SET_BOUND_174}).`,
122
+ }
123
+ return tossSubsets(toFiniteSet(set).elements, picks, probability, runtime.getRandom());
124
+ });
125
+
126
+ export const createRandomizationOperators = (runtime: CheckerRuntime): Builtin[] => [
127
+ overrideWithJava(
128
+ defineOperator("RandomSubset", 2, (args) => {
129
+ const count = getValue(args, 0, "RandomSubset");
130
+ if (typeof count !== "number" || count < 0) {
131
+ throw createModuleArgumentError("first", "RandomSubset", "nonnegative integer", count);
132
+ }
133
+ const set = getValue(args, 1, "RandomSubset");
134
+ if (!isTlcEnumerable(set) || !isFiniteSet(set)) {
135
+ throw createModuleArgumentError("second", "RandomSubset", "a finite set", set);
136
+ }
137
+ const factors = getEnumeratedFactors(set, runtime.version);
138
+ if (factors) {
139
+ const size = factors.reduce<number>(
140
+ (total, factor) => total * toFiniteSet(factor).elements.length,
141
+ 1,
97
142
  );
143
+ if (size > getMaximumSetSize()) {
144
+ throw new TlaEvaluationError(getSetBoundMessage());
145
+ }
98
146
  }
99
- }
100
- return createSet(getRandomSubset(count, set, runtime.getRandom(), runtime.version));
101
- }),
102
- defineStateOperator("RandomSetOfSubsets", 3, (args) => getRandomSetOfSubsets(args, runtime)),
103
- defineStateOperator("TestRandomSetOfSubsets", 3, (args) =>
147
+ return createSet(getRandomSubset(count, set, runtime.getRandom(), runtime.version));
148
+ }),
149
+ RANDOM_SUBSET_SIGNATURE,
150
+ ),
151
+ defineOperator("RandomSetOfSubsets", 3, (args) => getRandomSetOfSubsets(args, runtime)),
152
+ defineOperator("TestRandomSetOfSubsets", 3, (args) =>
104
153
  createTuple(
105
154
  Array.from(
106
155
  { length: 5 },