tla-ts 0.0.7-dev.bd12468 → 0.0.8-dev.8067c48

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/dist/worker.cjs CHANGED
@@ -18,4 +18,7 @@ to an element in its putative domain.`;var S=class extends b{constructor(){super
18
18
  G))).Worker(e);return r.on(`message`,t),r.on(`error`,n),{postMessage:(e,t)=>r.postMessage(e,t),terminate:()=>void r.terminate()}},J=async()=>typeof globalThis.postMessage==`function`?globalThis:(await import(
19
19
  /* @vite-ignore */
20
20
  /* webpackIgnore: true */
21
- G)).parentPort;Object.defineProperty(exports,"A",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"B",{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"D",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"E",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"F",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"G",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"H",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"I",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"K",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"L",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"M",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"N",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"O",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"P",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"R",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"U",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"V",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"W",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,"j",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"k",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"z",{enumerable:!0,get:function(){return g}});
21
+ G)).parentPort,Y=()=>{let e=`Bun`in globalThis?import(
22
+ /* @vite-ignore */
23
+ /* webpackIgnore: true */
24
+ `bun:jsc`):void 0;return async()=>{(await e)?.edenGC(),await new Promise(e=>typeof setImmediate==`function`?setImmediate(e):setTimeout(e,0))}};Object.defineProperty(exports,"A",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"B",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"D",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"E",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"F",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"G",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"H",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"I",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"K",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"L",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"M",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"N",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"O",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"P",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"R",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"U",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"V",{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,"W",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,"j",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"k",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"q",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"z",{enumerable:!0,get:function(){return _}});
package/dist/worker.js CHANGED
@@ -18,4 +18,7 @@ to an element in its putative domain.`;var S=class extends b{constructor(){super
18
18
  G))).Worker(e);return r.on(`message`,t),r.on(`error`,n),{postMessage:(e,t)=>r.postMessage(e,t),terminate:()=>void r.terminate()}},J=async()=>typeof globalThis.postMessage==`function`?globalThis:(await import(
19
19
  /* @vite-ignore */
20
20
  /* webpackIgnore: true */
21
- G)).parentPort;export{j as A,V as B,O as C,d as D,S as E,m as F,n as G,l as H,v as I,a as K,C as L,c as M,s as N,T as O,h as P,_ as R,E as S,f as T,e as U,o as V,r as W,D as _,W as a,B as b,R as c,I as d,z as f,b as g,u as h,L as i,k as j,N as k,x as l,y as m,K as n,H as o,P as p,q as r,U as s,J as t,F as u,w as v,A as w,p as x,M as y,g as z};
21
+ G)).parentPort,Y=()=>{let e=`Bun`in globalThis?import(
22
+ /* @vite-ignore */
23
+ /* webpackIgnore: true */
24
+ `bun:jsc`):void 0;return async()=>{(await e)?.edenGC(),await new Promise(e=>typeof setImmediate==`function`?setImmediate(e):setTimeout(e,0))}};export{N as A,g as B,E as C,S as D,f as E,h as F,r as G,o as H,m as I,n as K,v as L,k as M,c as N,d as O,s as P,C as R,p as S,A as T,l as U,V,e as W,b as _,L as a,M as b,U as c,F as d,I as f,u as g,y as h,q as i,j,T as k,R as l,P as m,J as n,W as o,z as p,a as q,K as r,H as s,Y as t,x as u,D as v,O as w,B as x,w as y,_ as z};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tla-ts",
3
- "version": "0.0.7-dev.bd12468",
3
+ "version": "0.0.8-dev.8067c48",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/check.ts CHANGED
@@ -75,7 +75,7 @@ import {
75
75
  withUnexpectedException,
76
76
  type FailureMessage,
77
77
  } from "./tlc/messages";
78
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc/order";
78
+ import { createTlcOrder } from "./tlc/order";
79
79
  import { replayInitialStates, replaySuccessors } from "./tlc/replay";
80
80
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc/summary";
81
81
  import { createActionRecord, createCounterExample } from "./tlc/tlcext-operators";
@@ -114,6 +114,9 @@ export interface CheckOptions {
114
114
  dump?: StateDump;
115
115
  // TLC's -tool, which changes the messages of TLC's errors.
116
116
  isTool?: boolean;
117
+ // TLC's -continue: the search reports each violated invariant and action property through
118
+ // onProgress and goes on.
119
+ isContinued?: boolean;
117
120
  // Whether TLC records a binary trace for its trace exploration spec, for which it loads Integers.
118
121
  isTraceRecorded?: boolean;
119
122
  // Whether the caller printed SANY's report, its warnings included, before the check.
@@ -165,6 +168,8 @@ export type CheckProgress =
165
168
  | { kind: "liveness-finished" }
166
169
  // A warning TLC prints as it evaluates the spec, with its message code.
167
170
  | { kind: "warning"; code: number; text: string }
171
+ // A violation that the search goes on past with -continue.
172
+ | { kind: "violation"; status: CheckStatus; violation: Violation }
168
173
  // A method of the class named after a module, which TLC reports as it loads the class.
169
174
  | ({ kind: "java-override" } & JavaOverride);
170
175
 
@@ -406,11 +411,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
406
411
  capturedOutput.lines = outer;
407
412
  }
408
413
  };
409
- setStringOrder(getTlcStringOrder(options.source, config, options.loadModule));
414
+ const order = createTlcOrder(options.source, options.loadModule);
415
+ setStringOrder(order.getStringOrder(config));
410
416
  setValueVersion(options.version);
411
417
  const specification = createEnvironment(config, {
412
418
  source: options.source,
413
419
  loadModule: options.loadModule,
420
+ order,
414
421
  loadClass: options.loadClass,
415
422
  print,
416
423
  files: { readFile: options.readFile, writeFile: options.writeFile },
@@ -482,7 +489,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
482
489
  const search = createSearch(
483
490
  config,
484
491
  environment,
485
- () => getTlcVariableOrder(options.source, options.loadModule),
492
+ () => order.getDeclarationOrder("variable"),
486
493
  options.onProgress,
487
494
  );
488
495
  const findViolatedAssumption = () =>
@@ -549,6 +556,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
549
556
  ...(checked.postcondition && { postcondition: checked.postcondition }),
550
557
  });
551
558
  };
559
+ // With -continue, TLC prints the trace of a violation without checking the postconditions.
560
+ const reportContinuedViolation = (status: CheckStatus, violation: Omit<Violation, "loopStart">) =>
561
+ options.onProgress?.({
562
+ kind: "violation",
563
+ status,
564
+ violation: { ...violation, loopStart: undefined },
565
+ });
552
566
  const spec = search.spec;
553
567
  const getFingerprintState = search.getFingerprintState;
554
568
  const specNextActions = { value: undefined as SpecAction[] | undefined };
@@ -1162,7 +1176,15 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1162
1176
  liveness?.addInitialState(states.length, state);
1163
1177
  stateWriter?.writeInitialState(getGraphState(state, 1));
1164
1178
  }
1165
- const violated = search.findViolatedInvariant(state);
1179
+ if (options.isContinued) {
1180
+ search.getViolatedInvariants(state).forEach((invariant) =>
1181
+ reportContinuedViolation("invariant-violation", {
1182
+ name: invariant.name,
1183
+ ...toTrace([{ action: undefined, state }], []),
1184
+ }),
1185
+ );
1186
+ }
1187
+ const violated = options.isContinued ? undefined : search.findViolatedInvariant(state);
1166
1188
  if (violated) {
1167
1189
  return reportViolation("invariant-violation", {
1168
1190
  name: violated.name,
@@ -1229,14 +1251,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1229
1251
  if (existing === -1) {
1230
1252
  try {
1231
1253
  const violated = search.findViolatedInvariant(successor.state, state);
1232
- if (violated) {
1233
- return withOutDegrees(
1234
- reportViolation("invariant-violation", {
1235
- name: violated.name,
1236
- ...getTrace(index, successor),
1237
- }),
1238
- );
1254
+ const violation = violated && { name: violated.name, ...getTrace(index, successor) };
1255
+ if (violation && !options.isContinued) {
1256
+ return withOutDegrees(reportViolation("invariant-violation", violation));
1239
1257
  }
1258
+ if (violation) reportContinuedViolation("invariant-violation", violation);
1240
1259
  } catch (error) {
1241
1260
  if (isStackOverflow(error)) throw error;
1242
1261
  // TLC replays the expansion and skips the invariants of a state it has seen, the failed one
@@ -1251,14 +1270,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1251
1270
  }
1252
1271
  }
1253
1272
  const violatedProperty = search.findViolatedActionProperty(state, successor.state);
1254
- if (violatedProperty) {
1255
- return withOutDegrees(
1256
- reportViolation("liveness-violation", {
1257
- name: violatedProperty.name,
1258
- ...getTrace(index, successor),
1259
- }),
1260
- );
1273
+ const propertyViolation = violatedProperty && {
1274
+ name: violatedProperty.name,
1275
+ ...getTrace(index, successor),
1276
+ };
1277
+ if (propertyViolation && !options.isContinued) {
1278
+ return withOutDegrees(reportViolation("liveness-violation", propertyViolation));
1261
1279
  }
1280
+ if (propertyViolation) reportContinuedViolation("liveness-violation", propertyViolation);
1262
1281
  if (!isNew) return undefined;
1263
1282
  if (!isCanonicalizedFirst) canonicalizeState(successor.state);
1264
1283
  markSeen(hash, states.length);
@@ -65,6 +65,7 @@ export const defineCommand = (usage: string, specs: OptionSpec[]) => {
65
65
 
66
66
  export const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options}", [
67
67
  { flag: "-config <Spec.cfg>" },
68
+ { flag: "-continue" },
68
69
  { flag: "-deadlock" },
69
70
  // Like TLC, -dump takes a format only when the next argument starts with dot and a file follows.
70
71
  {
package/src/cli/tlc.ts CHANGED
@@ -353,6 +353,9 @@ const printCheckProgress = (
353
353
  return;
354
354
  case "warning":
355
355
  print(progress.code, MESSAGE_LEVEL.warning, progress.text);
356
+ return;
357
+ case "violation":
358
+ printViolation(progress.status, progress.violation, printer);
356
359
  }
357
360
  };
358
361
 
@@ -823,6 +826,7 @@ const checkSpec = async (
823
826
  seed: BigInt(seed),
824
827
  dump: dumpValues && getStateDump(dumpValues),
825
828
  isTool: printer.isTool,
829
+ isContinued: args.has("-continue"),
826
830
  isTraceRecorded: isRecorded,
827
831
  isSanyReported: true,
828
832
  isWarningEnabled: !args.has("-nowarning"),
package/src/codegen.ts CHANGED
@@ -11,9 +11,7 @@ import {
11
11
  getFieldSelector,
12
12
  getMissingArgumentDescriber,
13
13
  getQuantifierElements,
14
- isClosedConstant,
15
14
  isValueArgument,
16
- isWorthCaching,
17
15
  keepLazy,
18
16
  resolveGlobalOperator,
19
17
  expectFunction,
@@ -116,6 +114,18 @@ const generatedHelpers = {
116
114
  value: undefined as ReturnType<typeof createGeneratedHelpers> | undefined,
117
115
  };
118
116
 
117
+ const codeGeneration = { isAllowed: undefined as boolean | undefined };
118
+
119
+ // Hosts such as Cloudflare Workers, or a page whose CSP lacks 'unsafe-eval', throw an EvalError.
120
+ const getIsCodeGenerationAllowed = () => {
121
+ try {
122
+ return Boolean(new Function(""));
123
+ } catch (error) {
124
+ if (error instanceof EvalError) return false;
125
+ throw error;
126
+ }
127
+ };
128
+
119
129
  const addReference = (generator: Generator, value: unknown) => {
120
130
  generator.references.push(value);
121
131
  return `reference${generator.references.length - 1}`;
@@ -269,9 +279,6 @@ const isReadOnly = (expression: Expression): boolean => {
269
279
  const generateExpression = (generator: Generator, expression: Expression, frame: Frame): string => {
270
280
  const generate = (node: Expression, nodeFrame = frame) =>
271
281
  generateExpression(generator, node, nodeFrame);
272
- if (isWorthCaching(expression) && isClosedConstant(expression, generator.environment)) {
273
- return generateDelegate(generator, expression, frame);
274
- }
275
282
  switch (expression.kind) {
276
283
  case "Number":
277
284
  if (isTlcInteger(expression.value)) {
@@ -381,6 +388,8 @@ export const generateEvaluator = (
381
388
  environment: Environment,
382
389
  ): Evaluator | undefined => {
383
390
  if (!GENERATED_KINDS.has(expression.kind)) return undefined;
391
+ codeGeneration.isAllowed ??= getIsCodeGenerationAllowed();
392
+ if (!codeGeneration.isAllowed) return undefined;
384
393
  const generator: Generator = { environment, references: [], helpers: [], counter: 0 };
385
394
  const frame: Frame = {
386
395
  context: "context",
@@ -1,18 +1,79 @@
1
1
  import { getChildren, isLocallyResolved, type Definition, type Expression } from "./ast";
2
- import { isImpureBuiltin, type Environment } from "./evaluate";
2
+ import type { Environment } from "./evaluate";
3
+ import { ACTION_LEVEL, CONSTANT_LEVEL, TEMPORAL_LEVEL, VARIABLE_LEVEL } from "./levels";
3
4
 
4
- const ACTION_AND_TEMPORAL_KINDS = new Set([
5
+ // The names of a spec that the facts depend on, which are final before the environment is built.
6
+ interface DefinitionNames extends Pick<
7
+ Environment,
8
+ "definitions" | "substitutions" | "constants" | "variableIndex" | "builtins" | "variables"
9
+ > {}
10
+
11
+ // What TLC's evaluation needs to know about each definition of a spec: whether it is constant-level,
12
+ // which effects evaluating it has, which variables it reads and its liveness level. Each fact is
13
+ // reachability over the definitions it calls, so one pass over the spec's call graph computes them
14
+ // all, once, when the environment is created. A row of words holds a definition's facts: the first
15
+ // word holds the flags below, and the rest a bitset of the variables it reads.
16
+ export interface DefinitionFacts {
17
+ ids: Map<Definition, number>;
18
+ rows: Uint32Array;
19
+ // The words of each row: one of flags, then one per 32 variables.
20
+ words: number;
21
+ }
22
+
23
+ // The definition reads a variable, a state-level builtin, or an action or temporal operator.
24
+ const NONCONSTANT = 1;
25
+ // Evaluating the definition again can print, assert, read the clock or choose at random.
26
+ const IMPURE = 2;
27
+ // Like IMPURE, but an Assert that held holds again, so repeating it looks the same.
28
+ const REPEATED_EFFECT = 4;
29
+ // The definition builds a set with UNION or \cup, which streams until TLC caches it.
30
+ const STREAMED = 8;
31
+ // The variables the definition reads don't decide its value: it has an effect, or it is an action.
32
+ const READS_IMPURE = 16;
33
+ // The liveness level of the definition, as thresholds so that reachability is a bitwise or.
34
+ const VARIABLE_LEVEL_FLAGS = 32;
35
+ const ACTION_LEVEL_FLAGS = VARIABLE_LEVEL_FLAGS | 64;
36
+ const TEMPORAL_LEVEL_FLAGS = ACTION_LEVEL_FLAGS | 128;
37
+
38
+ const ACTION_KINDS = new Set<Expression["kind"]>([
5
39
  "Prime",
6
40
  "Unchanged",
7
- "Enabled",
8
- "Always",
9
- "Eventually",
10
41
  "BoxAction",
11
42
  "AngleAction",
43
+ ]);
44
+
45
+ const TEMPORAL_KINDS = new Set<Expression["kind"]>([
46
+ "Always",
47
+ "Eventually",
12
48
  "WeakFairness",
13
49
  "StrongFairness",
14
50
  ]);
15
51
 
52
+ // TLC bounds the level of every action and temporal operator above constant, whatever its operands.
53
+ const NONCONSTANT_KINDS = new Set<Expression["kind"]>([
54
+ ...ACTION_KINDS,
55
+ ...TEMPORAL_KINDS,
56
+ "Enabled",
57
+ ]);
58
+
59
+ const TEMPORAL_OPERATORS = new Set(["~>", "-+->"]);
60
+
61
+ const NONCONSTANT_OPERATORS = new Set([...TEMPORAL_OPERATORS, "\\cdot"]);
62
+
63
+ const IMPURE_BUILTINS = new Set([
64
+ "Print",
65
+ "PrintT",
66
+ "Assert",
67
+ "JavaTime",
68
+ "RandomElement",
69
+ "TLCGet",
70
+ "TLCSet",
71
+ ]);
72
+
73
+ // UNION and \cup build sets that stream the sets they combine until TLC caches them, and TLC
74
+ // builds a new one at each evaluation.
75
+ const STREAMED_BUILTINS = new Set(["UNION", "\\cup"]);
76
+
16
77
  const getReferencedName = (expression: Expression) => {
17
78
  if (expression.kind === "Identifier") return expression.name;
18
79
  if (expression.kind === "Apply" || expression.kind === "OperatorReference")
@@ -20,30 +81,293 @@ const getReferencedName = (expression: Expression) => {
20
81
  return undefined;
21
82
  };
22
83
 
23
- export const getReadVariables = (
24
- expression: Expression,
25
- environment: Environment,
26
- ): number[] | undefined => {
27
- const variables = new Set<number>();
28
- const visited = new Set<Definition>();
29
- const visit = (node: Expression): boolean => {
30
- if (ACTION_AND_TEMPORAL_KINDS.has(node.kind)) return false;
84
+ const isImpureBuiltin = (name: string, environment: DefinitionNames) =>
85
+ IMPURE_BUILTINS.has(name) || environment.builtins.get(name)?.isStateLevel === true;
86
+
87
+ interface Edge {
88
+ callee: Definition;
89
+ // The configuration replaces the name by a constant value, which TLC's level and variable
90
+ // analyses take for a constant and its effect analysis evaluates.
91
+ isOverridden: boolean;
92
+ // Whether the reference is outside every action and temporal operator, where the level of the
93
+ // callee counts. An operator such as ENABLED fixes the level of what it holds.
94
+ isLevelCounted: boolean;
95
+ }
96
+
97
+ // The facts an expression's own nodes establish, with the definitions it refers to.
98
+ const collectLocalFacts = (
99
+ expressions: Expression[],
100
+ environment: DefinitionNames,
101
+ words: number,
102
+ ) => {
103
+ const row = new Uint32Array(words);
104
+ const edges: Edge[] = [];
105
+ // The level flags of a node, or undefined for a node whose level the nodes it holds decide. An
106
+ // action or temporal operator has its own level whatever it holds, as does ENABLED, so nothing
107
+ // below one counts towards the level, variables and callees included.
108
+ const getOwnLevelFlags = (node: Expression) => {
109
+ const kind = node.kind;
110
+ if (ACTION_KINDS.has(kind) || (kind === "Apply" && node.operator === "\\cdot")) {
111
+ return ACTION_LEVEL_FLAGS;
112
+ }
113
+ if (kind === "Enabled") return VARIABLE_LEVEL_FLAGS;
114
+ if (
115
+ TEMPORAL_KINDS.has(kind) ||
116
+ (kind === "UnboundedQuantifier" && node.isTemporal === true) ||
117
+ (kind === "Apply" && TEMPORAL_OPERATORS.has(node.operator))
118
+ ) {
119
+ return TEMPORAL_LEVEL_FLAGS;
120
+ }
121
+ return undefined;
122
+ };
123
+ const visit = (node: Expression, isLevelCounted: boolean) => {
124
+ const kind = node.kind;
125
+ if (
126
+ NONCONSTANT_KINDS.has(kind) ||
127
+ (kind === "UnboundedQuantifier" && node.isTemporal === true) ||
128
+ (kind === "Apply" && NONCONSTANT_OPERATORS.has(node.operator))
129
+ ) {
130
+ row[0] |= NONCONSTANT;
131
+ }
132
+ if (NONCONSTANT_KINDS.has(kind)) row[0] |= READS_IMPURE;
133
+ const ownLevelFlags = getOwnLevelFlags(node);
134
+ if (isLevelCounted && ownLevelFlags !== undefined) row[0] |= ownLevelFlags;
135
+ const isInnerLevelCounted = isLevelCounted && ownLevelFlags === undefined;
31
136
  const name = getReferencedName(node);
32
- if (name !== undefined && !isLocallyResolved(node) && !environment.constants.has(name)) {
137
+ if (name !== undefined && !isLocallyResolved(node)) {
33
138
  const target = environment.substitutions.get(name) ?? name;
34
139
  const definition = environment.definitions.get(target);
35
- if (!definition && isImpureBuiltin(target, environment)) return false;
140
+ const isOverridden = environment.constants.has(name);
36
141
  const variableIndex = environment.variableIndex.get(name);
37
- if (variableIndex !== undefined) variables.add(variableIndex);
38
- if (definition && !visited.has(definition)) {
39
- visited.add(definition);
40
- const isPure =
41
- visit(definition.body) &&
42
- (definition.kind === "Operator" || definition.bounds.every((bound) => visit(bound.set)));
43
- if (!isPure) return false;
142
+ if (variableIndex !== undefined || environment.builtins.get(name)?.isStateLevel) {
143
+ row[0] |= NONCONSTANT;
144
+ }
145
+ if (variableIndex !== undefined) {
146
+ if (isInnerLevelCounted) row[0] |= VARIABLE_LEVEL_FLAGS;
147
+ if (!isOverridden) row[1 + (variableIndex >>> 5)] |= 1 << (variableIndex & 31);
148
+ }
149
+ if (definition) {
150
+ edges.push({ callee: definition, isOverridden, isLevelCounted: isInnerLevelCounted });
151
+ } else {
152
+ if (isImpureBuiltin(name, environment)) {
153
+ row[0] |= IMPURE | (name === "Assert" ? 0 : REPEATED_EFFECT);
154
+ }
155
+ if (STREAMED_BUILTINS.has(name)) row[0] |= STREAMED;
156
+ if (!isOverridden && isImpureBuiltin(target, environment)) row[0] |= READS_IMPURE;
157
+ const builtin = environment.builtins.get(target);
158
+ if (
159
+ isInnerLevelCounted &&
160
+ !isOverridden &&
161
+ variableIndex === undefined &&
162
+ builtin?.isStateLevel &&
163
+ !builtin.isLevelConstant
164
+ ) {
165
+ row[0] |= VARIABLE_LEVEL_FLAGS;
166
+ }
44
167
  }
45
168
  }
46
- return getChildren(node).every(visit);
169
+ getChildren(node).forEach((child) => visit(child, isInnerLevelCounted));
47
170
  };
48
- return visit(expression) ? [...variables] : undefined;
171
+ expressions.forEach((expression) => visit(expression, true));
172
+ return { row, edges };
49
173
  };
174
+
175
+ const getDefinitionExpressions = (definition: Definition) =>
176
+ definition.kind === "Function"
177
+ ? [...definition.bounds.map((bound) => bound.set), definition.body]
178
+ : [definition.body];
179
+
180
+ // Closes each row under bitwise or along the edges: a definition's facts are its own and those of
181
+ // every definition it reaches. Tarjan's algorithm lists the strongly connected components with the
182
+ // callees first, so each component ors in components that are already final.
183
+ const closeRows = (local: Uint32Array, words: number, edges: Int32Array[], mask: number) => {
184
+ const count = edges.length;
185
+ const closed = local.slice();
186
+ const index = new Int32Array(count).fill(-1);
187
+ const lowLink = new Int32Array(count);
188
+ const component = new Int32Array(count).fill(-1);
189
+ const stack: number[] = [];
190
+ // The frame of a depth-first visit: the node and the edge it resumes at.
191
+ const frames: number[] = [];
192
+ let nextIndex = 0;
193
+ let componentCount = 0;
194
+ const orRow = (into: number, from: number) => {
195
+ for (let word = 0; word < words; word++) {
196
+ const bits = closed[from * words + word];
197
+ closed[into * words + word] |= word === 0 ? bits & mask : bits;
198
+ }
199
+ };
200
+ const enter = (node: number) => {
201
+ frames.push(node, 0);
202
+ index[node] = lowLink[node] = nextIndex++;
203
+ stack.push(node);
204
+ };
205
+ for (let root = 0; root < count; root++) {
206
+ if (index[root] !== -1) continue;
207
+ enter(root);
208
+ while (frames.length > 0) {
209
+ const node = frames[frames.length - 2];
210
+ const position = frames[frames.length - 1];
211
+ const nodeEdges = edges[node];
212
+ if (position < nodeEdges.length) {
213
+ frames[frames.length - 1] = position + 1;
214
+ const callee = nodeEdges[position];
215
+ if (index[callee] === -1) {
216
+ enter(callee);
217
+ } else if (component[callee] === -1) {
218
+ // A visited node without a component is still on the stack.
219
+ lowLink[node] = Math.min(lowLink[node], index[callee]);
220
+ }
221
+ continue;
222
+ }
223
+ frames.length -= 2;
224
+ if (frames.length > 0) {
225
+ const caller = frames[frames.length - 2];
226
+ lowLink[caller] = Math.min(lowLink[caller], lowLink[node]);
227
+ }
228
+ if (lowLink[node] !== index[node]) continue;
229
+ // The component is complete: its members share one row, which ors in their callees' rows.
230
+ const members: number[] = [];
231
+ for (;;) {
232
+ const member = stack.pop() ?? node;
233
+ component[member] = componentCount;
234
+ members.push(member);
235
+ if (member === node) break;
236
+ }
237
+ componentCount++;
238
+ const first = members[0];
239
+ members.forEach((member) => {
240
+ if (member !== first) orRow(first, member);
241
+ edges[member].forEach((callee) => {
242
+ if (component[callee] !== component[first]) orRow(first, callee);
243
+ });
244
+ });
245
+ members.forEach((member) => {
246
+ if (member !== first) orRow(member, first);
247
+ });
248
+ }
249
+ }
250
+ return closed;
251
+ };
252
+
253
+ const PURITY_MASK = IMPURE | REPEATED_EFFECT | STREAMED;
254
+ const READ_MASK = NONCONSTANT | READS_IMPURE;
255
+
256
+ // TLC evaluates a constant definition without parameters once, so only other definitions pass
257
+ // on the side effects and random choices of the builtins they call.
258
+ const isEvaluatedOnce = (definition: Definition, flags: number) =>
259
+ definition.kind === "Operator" && definition.params.length === 0 && (flags & NONCONSTANT) === 0;
260
+
261
+ export const createDefinitionFacts = (environment: DefinitionNames): DefinitionFacts => {
262
+ const definitions = [...new Set(environment.definitions.values())];
263
+ const ids = new Map(definitions.map((definition, id) => [definition, id]));
264
+ const words = 1 + ((environment.variables.length + 31) >>> 5);
265
+ const local = new Uint32Array(definitions.length * words);
266
+ const localImpurity = new Uint32Array(definitions.length * words);
267
+ const edges = definitions.map((definition, id) => {
268
+ const facts = collectLocalFacts(getDefinitionExpressions(definition), environment, words);
269
+ local.set(facts.row, id * words);
270
+ localImpurity[id * words] = facts.row[0] & PURITY_MASK;
271
+ return facts.edges;
272
+ });
273
+ const getId = (edge: Edge) => ids.get(edge.callee) ?? -1;
274
+ const readEdges = edges.map(
275
+ (own) => new Int32Array(own.filter((edge) => !edge.isOverridden).map(getId)),
276
+ );
277
+ const reads = closeRows(local, words, readEdges, READ_MASK);
278
+ const levelEdges = edges.map(
279
+ (own) =>
280
+ new Int32Array(own.filter((edge) => !edge.isOverridden && edge.isLevelCounted).map(getId)),
281
+ );
282
+ const levels = closeRows(local, words, levelEdges, TEMPORAL_LEVEL_FLAGS);
283
+ const purityEdges = edges.map(
284
+ (own) =>
285
+ new Int32Array(
286
+ own
287
+ .map(getId)
288
+ .filter((callee) => !isEvaluatedOnce(definitions[callee], reads[callee * words])),
289
+ ),
290
+ );
291
+ const purity = closeRows(localImpurity, words, purityEdges, PURITY_MASK);
292
+ const rows = reads.map((word, position) =>
293
+ position % words === 0
294
+ ? (word & READ_MASK) |
295
+ (levels[position] & TEMPORAL_LEVEL_FLAGS) |
296
+ (purity[position] & PURITY_MASK)
297
+ : word,
298
+ );
299
+ return { ids, rows, words };
300
+ };
301
+
302
+ // The facts of a definition: from the table, or for a LET definition from its own body and the
303
+ // table's rows of the definitions it calls.
304
+ const getRow = (definition: Definition, environment: Environment): Uint32Array => {
305
+ const facts = environment.facts;
306
+ const id = facts.ids.get(definition);
307
+ return id === undefined
308
+ ? getExpressionsRow(getDefinitionExpressions(definition), environment)
309
+ : facts.rows.subarray(id * facts.words, (id + 1) * facts.words);
310
+ };
311
+
312
+ // The facts of expressions: their own, with the rows of the definitions they call ored in.
313
+ const getExpressionsRow = (expressions: Expression[], environment: Environment) => {
314
+ const words = environment.facts.words;
315
+ const local = collectLocalFacts(expressions, environment, words);
316
+ const row = local.row;
317
+ local.edges.forEach((edge) => {
318
+ const callee = getRow(edge.callee, environment);
319
+ if (!edge.isOverridden) {
320
+ row[0] |= callee[0] & READ_MASK;
321
+ if (edge.isLevelCounted) row[0] |= callee[0] & TEMPORAL_LEVEL_FLAGS;
322
+ for (let word = 1; word < words; word++) row[word] |= callee[word];
323
+ }
324
+ if (!isEvaluatedOnce(edge.callee, callee[0])) row[0] |= callee[0] & PURITY_MASK;
325
+ });
326
+ return row;
327
+ };
328
+
329
+ export const isConstantLevel = (definition: Definition, environment: Environment) =>
330
+ (getRow(definition, environment)[0] & NONCONSTANT) === 0;
331
+
332
+ const EFFECT_FLAGS = { any: IMPURE, repeated: REPEATED_EFFECT, streamed: STREAMED };
333
+
334
+ export const isImpureDefinition = (
335
+ definition: Definition,
336
+ environment: Environment,
337
+ effect: keyof typeof EFFECT_FLAGS = "any",
338
+ ) => (getRow(definition, environment)[0] & EFFECT_FLAGS[effect]) !== 0;
339
+
340
+ // The liveness level of a definition: constant, variable, action or temporal.
341
+ export const getDefinitionLevel = (definition: Definition, environment: Environment) => {
342
+ const flags = getRow(definition, environment)[0] & TEMPORAL_LEVEL_FLAGS;
343
+ return flags === TEMPORAL_LEVEL_FLAGS
344
+ ? TEMPORAL_LEVEL
345
+ : flags === ACTION_LEVEL_FLAGS
346
+ ? ACTION_LEVEL
347
+ : flags === VARIABLE_LEVEL_FLAGS
348
+ ? VARIABLE_LEVEL
349
+ : CONSTANT_LEVEL;
350
+ };
351
+
352
+ const toVariables = (row: Uint32Array) => {
353
+ const variables: number[] = [];
354
+ for (let word = 1; word < row.length; word++) {
355
+ for (let bits = row[word]; bits !== 0; bits &= bits - 1) {
356
+ variables.push(((word - 1) << 5) + (31 - Math.clz32(bits & -bits)));
357
+ }
358
+ }
359
+ return variables;
360
+ };
361
+
362
+ // The variables an expression reads, through the definitions it calls, when they and its scope
363
+ // decide its value, or undefined when it has an effect or is an action.
364
+ export const getReadVariables = (
365
+ expression: Expression,
366
+ environment: Environment,
367
+ ): number[] | undefined => {
368
+ const row = getExpressionsRow([expression], environment);
369
+ return row[0] & READS_IMPURE ? undefined : toVariables(row);
370
+ };
371
+
372
+ export const isNonconstant = (expression: Expression, environment: Environment) =>
373
+ (getExpressionsRow([expression], environment)[0] & NONCONSTANT) !== 0;