tla-ts 0.0.9-dev.2813db5 → 0.0.9-dev.331c500

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 (52) hide show
  1. package/README.md +22 -1
  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 +48 -48
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +1 -0
  8. package/dist/index.d.ts +1 -0
  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.cjs +29 -29
  13. package/dist/prove.js +20 -20
  14. package/dist/run.cjs +28 -28
  15. package/dist/run.js +31 -31
  16. package/dist/tlapm.cjs +2 -2
  17. package/dist/tlapm.js +1 -1
  18. package/dist/transfer.cjs +27 -27
  19. package/dist/transfer.js +26 -26
  20. package/dist/worker.cjs +4 -4
  21. package/dist/worker.js +4 -4
  22. package/package.json +3 -1
  23. package/src/check.ts +44 -31
  24. package/src/cli/options.ts +1 -1
  25. package/src/cli/tlc.ts +18 -9
  26. package/src/cli/typescript.ts +26 -0
  27. package/src/environment.ts +4 -0
  28. package/src/errors.ts +15 -0
  29. package/src/evaluate.ts +65 -10
  30. package/src/instances.ts +67 -6
  31. package/src/liveness-checker.ts +6 -3
  32. package/src/liveness.ts +7 -3
  33. package/src/parallel-worker.ts +5 -6
  34. package/src/parallel.ts +5 -4
  35. package/src/prover/smt/solver/solver.ts +31 -27
  36. package/src/successors.ts +3 -3
  37. package/src/typescript/actions.ts +494 -0
  38. package/src/typescript/collections.ts +615 -0
  39. package/src/typescript/compile.ts +70 -0
  40. package/src/typescript/context.ts +106 -0
  41. package/src/typescript/emit.ts +122 -0
  42. package/src/typescript/expressions.ts +508 -0
  43. package/src/typescript/formula.ts +160 -0
  44. package/src/typescript/functions.ts +295 -0
  45. package/src/typescript/model.ts +164 -0
  46. package/src/typescript/names.ts +116 -0
  47. package/src/typescript/program.ts +51 -0
  48. package/src/typescript/properties.ts +142 -0
  49. package/src/typescript/scope.ts +117 -0
  50. package/src/typescript/steps.ts +175 -0
  51. package/src/typescript/types.ts +178 -0
  52. package/src/values.ts +39 -15
@@ -0,0 +1,295 @@
1
+ import ts from "@typescript/typescript6";
2
+ import {
3
+ type Context,
4
+ type Definition,
5
+ type FunctionNode,
6
+ getCallee,
7
+ getFunction,
8
+ getSymbol,
9
+ getTopLevelDeclaration,
10
+ type HelperDeclaration,
11
+ } from "./context";
12
+ import { TlaTypeScriptError } from "../errors";
13
+ import { translateCondition, translateExpression, translateNegatedCondition } from "./expressions";
14
+ import { type Formula, ifThenElse, indent, letIn, render, text, wrap } from "./formula";
15
+ import {
16
+ type Bound,
17
+ bindNames,
18
+ bindPattern,
19
+ bindValues,
20
+ createStateScope,
21
+ declareParameters,
22
+ type Scope,
23
+ } from "./scope";
24
+
25
+ // Whether a step has changed a state variable, so that helpers reading state must see the change.
26
+ const isStateModified = (scope: Scope, context: Context) =>
27
+ [...context.variables].some((entry) => scope.bindings.get(entry[0]) !== entry[1]);
28
+
29
+ const readsState = (node: ts.Node, context: Context, visited: Set<ts.Declaration>): boolean => {
30
+ if (ts.isIdentifier(node)) {
31
+ const symbol = getSymbol(node, context.checker);
32
+ if (symbol !== undefined && context.variables.has(symbol)) return true;
33
+ const declaration = getTopLevelDeclaration(symbol);
34
+ if (declaration !== undefined && !visited.has(declaration)) {
35
+ visited.add(declaration);
36
+ return readsState(declaration, context, visited);
37
+ }
38
+ }
39
+ return (
40
+ ts.forEachChild(node, (child) => readsState(child, context, visited) || undefined) ?? false
41
+ );
42
+ };
43
+
44
+ const getInitializer = (declaration: HelperDeclaration) =>
45
+ ts.isVariableDeclaration(declaration) ? declaration.initializer : undefined;
46
+
47
+ // Compiles a top-level helper function or constant into a TLA+ definition, after the definitions
48
+ // it uses.
49
+ export const getDefinition = (declaration: HelperDeclaration, context: Context): Definition => {
50
+ const existing = context.definitions.get(declaration);
51
+ if (existing !== undefined) {
52
+ if (context.inProgress.has(declaration)) context.recursive.add(declaration);
53
+ return existing;
54
+ }
55
+ if (declaration.name === undefined)
56
+ throw new TlaTypeScriptError("Name this function", declaration);
57
+ const callee = getFunction(declaration);
58
+ const parameters = declareParameters(callee?.parameters ?? [], context);
59
+ // An operator parameter declares how many arguments it takes, as in F(_, _).
60
+ const declared = parameters.map((parameter) => {
61
+ const signatures = context.checker.getTypeAtLocation(parameter.node.name).getCallSignatures();
62
+ return signatures.length === 0
63
+ ? parameter.name
64
+ : `${parameter.name}(${signatures[0].parameters.map(() => "_").join(", ")})`;
65
+ });
66
+ const definition: Definition = {
67
+ name: context.names.getFresh(declaration.name.getText()),
68
+ parameters: declared,
69
+ readsState: readsState(declaration, context, new Set([declaration])),
70
+ };
71
+ context.definitions.set(declaration, definition);
72
+ context.inProgress.add(declaration);
73
+ const body = callee === undefined ? getInitializer(declaration) : callee.body;
74
+ if (body === undefined) throw new TlaTypeScriptError("Give this a value", declaration);
75
+ const value = translateBody(body, bindNames(createStateScope(context), parameters), context);
76
+ context.inProgress.delete(declaration);
77
+ const head =
78
+ declared.length === 0 ? definition.name : `${definition.name}(${declared.join(", ")})`;
79
+ context.output.push(`${head} ==\n ${indent(value, " ")}`);
80
+ return definition;
81
+ };
82
+
83
+ // Substitutes the arguments into a function's body, which then reads the state as it is now.
84
+ const inlineCall = (
85
+ callee: FunctionNode,
86
+ argumentNodes: readonly ts.Expression[],
87
+ scope: Scope,
88
+ context: Context,
89
+ ) => {
90
+ if (callee.body === undefined) throw new TlaTypeScriptError("Give this a body", callee);
91
+ const bound = bindValues(
92
+ callee.parameters.map((parameter) => parameter.name),
93
+ argumentNodes.map((argument) => translateExpression(argument, scope, context)),
94
+ scope,
95
+ context,
96
+ );
97
+ const value = translateBody(callee.body, bound.scope, context);
98
+ return bound.definitions.length === 0 ? value : render(letIn(bound.definitions, text(value)));
99
+ };
100
+
101
+ // A function argument to an operator parameter, as a LAMBDA or an operator's name.
102
+ const translateOperatorArgument = (node: ts.Expression, scope: Scope, context: Context) => {
103
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
104
+ const parameters = declareParameters(node.parameters, context);
105
+ const body = translateBody(node.body, bindNames(scope, parameters), context);
106
+ return `LAMBDA ${parameters.map((parameter) => parameter.name).join(", ")} : ${body}`;
107
+ }
108
+ const symbol = getSymbol(node, context.checker);
109
+ const declaration = getTopLevelDeclaration(symbol);
110
+ if (declaration !== undefined) return getDefinition(declaration, context).name;
111
+ const binding = symbol === undefined ? undefined : scope.bindings.get(symbol);
112
+ if (binding === undefined) throw new TlaTypeScriptError("Pass a function here", node);
113
+ return binding;
114
+ };
115
+
116
+ // A call to a top-level helper, or a reference to a top-level constant when node is undefined.
117
+ // A helper that reads state after the step has changed it is inlined, so it reads the new values.
118
+ export const translateHelperCall = (
119
+ declaration: HelperDeclaration,
120
+ node: ts.CallExpression | undefined,
121
+ scope: Scope,
122
+ context: Context,
123
+ ) => {
124
+ const definition = getDefinition(declaration, context);
125
+ const argumentNodes = node?.arguments ?? [];
126
+ if (definition.readsState && isStateModified(scope, context)) {
127
+ const callee = getFunction(declaration);
128
+ if (callee !== undefined) return inlineCall(callee, argumentNodes, scope, context);
129
+ const initializer = getInitializer(declaration);
130
+ if (initializer === undefined) throw new TlaTypeScriptError("Give this a body", declaration);
131
+ return translateExpression(initializer, scope, context);
132
+ }
133
+ if (definition.parameters.length === 0) return definition.name;
134
+ const values = argumentNodes.map((argument, index) =>
135
+ definition.parameters[index].includes("(")
136
+ ? translateOperatorArgument(argument, scope, context)
137
+ : translateExpression(argument, scope, context),
138
+ );
139
+ return `${definition.name}(${values.join(", ")})`;
140
+ };
141
+
142
+ // A call to a function declared inside another, which is inlined.
143
+ export const translateLocalCall = (node: ts.CallExpression, scope: Scope, context: Context) => {
144
+ const callee = getCallee(node.expression, context);
145
+ if (callee === undefined) {
146
+ throw new TlaTypeScriptError(`Unsupported call: ${node.expression.getText()}`, node);
147
+ }
148
+ if (context.inProgress.has(callee)) {
149
+ throw new TlaTypeScriptError(
150
+ "A local function can't call itself, so declare it at the top level",
151
+ node,
152
+ );
153
+ }
154
+ context.inProgress.add(callee);
155
+ const value = inlineCall(callee, node.arguments, scope, context);
156
+ context.inProgress.delete(callee);
157
+ return value;
158
+ };
159
+
160
+ // A function body that computes a value, as a TLA+ expression.
161
+ export const translateBody = (body: ts.ConciseBody, scope: Scope, context: Context): string => {
162
+ if (!ts.isBlock(body)) return translateExpression(body, scope, context);
163
+ return render(
164
+ translatePure(body.statements, scope, context, () => {
165
+ throw new TlaTypeScriptError("This function must return a value on every path", body);
166
+ }),
167
+ );
168
+ };
169
+
170
+ const translatePure = (
171
+ statements: readonly ts.Statement[],
172
+ scope: Scope,
173
+ context: Context,
174
+ next: (scope: Scope) => Formula,
175
+ ): Formula => {
176
+ if (statements.length === 0) return next(scope);
177
+ const statement = statements[0];
178
+ const continueWith = (inner: Scope) => translatePure(statements.slice(1), inner, context, next);
179
+ if (ts.isBlock(statement)) {
180
+ return translatePure(statement.statements, scope, context, continueWith);
181
+ }
182
+ if (ts.isVariableStatement(statement)) {
183
+ const bound = statement.declarationList.declarations.reduce<Bound>(
184
+ (current, declaration) => {
185
+ if (declaration.initializer === undefined) {
186
+ throw new TlaTypeScriptError("Declare locals with a value", declaration);
187
+ }
188
+ if (getFunction(declaration.initializer) !== undefined) return current;
189
+ const value = translateExpression(declaration.initializer, current.scope, context);
190
+ const added = bindPattern(declaration.name, value, current.scope, context);
191
+ return { definitions: [...current.definitions, ...added.definitions], scope: added.scope };
192
+ },
193
+ { definitions: [], scope },
194
+ );
195
+ return letIn(bound.definitions, continueWith(bound.scope));
196
+ }
197
+ if (ts.isIfStatement(statement)) {
198
+ return translateIf(
199
+ statement,
200
+ scope,
201
+ context,
202
+ (branch) => translatePure([branch], scope, context, continueWith),
203
+ () => continueWith(scope),
204
+ );
205
+ }
206
+ if (ts.isReturnStatement(statement)) {
207
+ if (statement.expression === undefined)
208
+ throw new TlaTypeScriptError("Return a value", statement);
209
+ return text(translateExpression(statement.expression, scope, context));
210
+ }
211
+ if (ts.isThrowStatement(statement)) return text(translateThrow(statement, scope, context));
212
+ if (ts.isSwitchStatement(statement)) {
213
+ return translateSwitch(
214
+ statement,
215
+ scope,
216
+ context,
217
+ (clause) => translatePure(clause, scope, context, continueWith),
218
+ () => continueWith(scope),
219
+ );
220
+ }
221
+ throw new TlaTypeScriptError(`Unsupported statement: ${statement.getText()}`, statement);
222
+ };
223
+
224
+ export const translateThrow = (statement: ts.ThrowStatement, scope: Scope, context: Context) => {
225
+ const thrown = statement.expression;
226
+ const message =
227
+ ts.isNewExpression(thrown) && thrown.arguments?.[0] !== undefined
228
+ ? translateExpression(thrown.arguments[0], scope, context)
229
+ : JSON.stringify(thrown.getText());
230
+ return `Assert(FALSE, ${message})`;
231
+ };
232
+
233
+ // An if statement as an IF. Without an else, the false branch is the rest of the statements.
234
+ export const translateIf = (
235
+ statement: ts.IfStatement,
236
+ scope: Scope,
237
+ context: Context,
238
+ translateBranch: (branch: ts.Statement) => Formula,
239
+ translateRest: () => Formula,
240
+ ) => {
241
+ const condition = translateCondition(statement.expression, scope, context);
242
+ const whenTrue = translateBranch(statement.thenStatement);
243
+ const whenFalse =
244
+ statement.elseStatement === undefined
245
+ ? translateRest()
246
+ : translateBranch(statement.elseStatement);
247
+ return ifThenElse(
248
+ condition,
249
+ whenTrue,
250
+ whenFalse,
251
+ translateNegatedCondition(statement.expression, scope, context),
252
+ );
253
+ };
254
+
255
+ // A switch as nested IFs. Each clause but the last must end in break, return, or throw.
256
+ export const translateSwitch = (
257
+ statement: ts.SwitchStatement,
258
+ scope: Scope,
259
+ context: Context,
260
+ translateClause: (statements: readonly ts.Statement[]) => Formula,
261
+ translateRest: () => Formula,
262
+ ): Formula => {
263
+ const subject = wrap(translateExpression(statement.expression, scope, context));
264
+ const clauses = statement.caseBlock.clauses;
265
+ const translateFrom = (start: number): Formula => {
266
+ if (start === clauses.length) return translateRest();
267
+ // Empty clauses fall through to the next clause with statements.
268
+ const end = clauses.findIndex(
269
+ (clause, index) => index >= start && clause.statements.length > 0,
270
+ );
271
+ const group = clauses.slice(start, end === -1 ? clauses.length : end + 1);
272
+ const lastClause = group[group.length - 1];
273
+ const body = lastClause.statements;
274
+ const last = body.at(-1);
275
+ const isTerminated =
276
+ last !== undefined &&
277
+ (ts.isBreakStatement(last) || ts.isReturnStatement(last) || ts.isThrowStatement(last));
278
+ const isLast = start + group.length === clauses.length;
279
+ if (body.length > 0 && !isTerminated && !isLast) {
280
+ throw new TlaTypeScriptError("End each case with break, return, or throw", lastClause);
281
+ }
282
+ const formula = translateClause(
283
+ last !== undefined && ts.isBreakStatement(last) ? body.slice(0, -1) : body,
284
+ );
285
+ if (group.some(ts.isDefaultClause)) return formula;
286
+ const condition = group
287
+ .filter(ts.isCaseClause)
288
+ .map(
289
+ (clause) => `${subject} = ${wrap(translateExpression(clause.expression, scope, context))}`,
290
+ )
291
+ .join(" \\/ ");
292
+ return ifThenElse(condition, formula, translateFrom(start + group.length));
293
+ };
294
+ return translateFrom(0);
295
+ };
@@ -0,0 +1,164 @@
1
+ import ts from "@typescript/typescript6";
2
+ import {
3
+ type Context,
4
+ type FunctionNode,
5
+ getFunction,
6
+ getSymbol,
7
+ type HelperDeclaration,
8
+ } from "./context";
9
+ import { TlaTypeScriptError } from "../errors";
10
+ import { VALUE_TAGS } from "./properties";
11
+
12
+ export interface Variable {
13
+ name: string;
14
+ declaration: ts.VariableDeclaration;
15
+ }
16
+
17
+ // An exported function, which becomes an action, an invariant, or a property its tag names.
18
+ export interface Exported {
19
+ name: string;
20
+ declaration: HelperDeclaration;
21
+ node: FunctionNode;
22
+ body: ts.ConciseBody;
23
+ tags: Map<string, string>;
24
+ }
25
+
26
+ interface Declared {
27
+ name: string;
28
+ declaration: HelperDeclaration;
29
+ }
30
+
31
+ export interface Model {
32
+ variables: Variable[];
33
+ exported: Exported[];
34
+ // Top-level functions and constants by their TypeScript names, which @leadsTo refers to.
35
+ topLevel: Map<string, HelperDeclaration>;
36
+ // The model values of each @symmetric type, as a TLA+ set.
37
+ symmetrySets: string[];
38
+ isDeadlockChecked: boolean;
39
+ }
40
+
41
+ const KNOWN_TAGS = new Set([
42
+ ...VALUE_TAGS,
43
+ "fair",
44
+ "strongFair",
45
+ "symmetric",
46
+ "noDeadlock",
47
+ "param",
48
+ "returns",
49
+ "return",
50
+ "example",
51
+ "see",
52
+ "deprecated",
53
+ "remarks",
54
+ "throws",
55
+ "link",
56
+ "description",
57
+ ]);
58
+
59
+ const getTags = (node: ts.Node) =>
60
+ new Map(
61
+ ts.getJSDocTags(node).map((tag) => {
62
+ if (!KNOWN_TAGS.has(tag.tagName.text)) {
63
+ throw new TlaTypeScriptError(`Unknown tag: @${tag.tagName.text}`, tag);
64
+ }
65
+ return [tag.tagName.text, ts.getTextOfJSDocComment(tag.comment)?.trim() ?? ""];
66
+ }),
67
+ );
68
+
69
+ const isExported = (node: ts.Declaration) =>
70
+ (ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export) !== 0;
71
+
72
+ const isLet = (declared: Declared) =>
73
+ ts.isVariableDeclaration(declared.declaration) &&
74
+ (declared.declaration.parent.flags & ts.NodeFlags.Let) !== 0;
75
+
76
+ // The string literals of a @symmetric type become model values, which TLC can permute.
77
+ const declareModelValues = (statement: ts.TypeAliasDeclaration, context: Context) => {
78
+ const type = context.checker.getTypeAtLocation(statement.name);
79
+ const names = (type.isUnion() ? type.types : [type]).map((member) => {
80
+ if (!member.isStringLiteral()) {
81
+ throw new TlaTypeScriptError("A @symmetric type must be a union of strings", statement);
82
+ }
83
+ const name = context.names.getFresh(member.value);
84
+ if (name !== member.value) {
85
+ throw new TlaTypeScriptError(`"${member.value}" can't name a TLA+ model value`, statement);
86
+ }
87
+ context.modelValues.set(member.value, name);
88
+ return name;
89
+ });
90
+ return `{${names.join(", ")}}`;
91
+ };
92
+
93
+ // The functions and constants a statement declares. Types and imports declare none.
94
+ const getDeclarations = (statement: ts.Statement): Declared[] => {
95
+ if (
96
+ ts.isImportDeclaration(statement) ||
97
+ ts.isTypeAliasDeclaration(statement) ||
98
+ ts.isInterfaceDeclaration(statement) ||
99
+ ts.isEnumDeclaration(statement) ||
100
+ (ts.isExportDeclaration(statement) && statement.isTypeOnly)
101
+ ) {
102
+ return [];
103
+ }
104
+ if (ts.isFunctionDeclaration(statement) && statement.name !== undefined && statement.body) {
105
+ return [{ name: statement.name.text, declaration: statement }];
106
+ }
107
+ if (!ts.isVariableStatement(statement)) {
108
+ throw new TlaTypeScriptError(`Unsupported statement: ${statement.getText()}`, statement);
109
+ }
110
+ const flags = statement.declarationList.flags;
111
+ return statement.declarationList.declarations.map((declaration) => {
112
+ if (!ts.isIdentifier(declaration.name)) {
113
+ throw new TlaTypeScriptError("Declare one name at a time", declaration);
114
+ }
115
+ if ((flags & (ts.NodeFlags.Let | ts.NodeFlags.Const)) === 0) {
116
+ throw new TlaTypeScriptError("Use let for state and const for everything else", declaration);
117
+ }
118
+ return { name: declaration.name.text, declaration };
119
+ });
120
+ };
121
+
122
+ // Reads a model's state variables, exported functions, and tags, and names them in TLA+.
123
+ export const readModel = (sourceFile: ts.SourceFile, context: Context): Model => {
124
+ const statements = sourceFile.statements;
125
+ const tags = new Map(statements.map((statement) => [statement, getTags(statement)]));
126
+ const symmetrySets = statements
127
+ .filter(
128
+ (statement): statement is ts.TypeAliasDeclaration =>
129
+ ts.isTypeAliasDeclaration(statement) && tags.get(statement)?.has("symmetric") === true,
130
+ )
131
+ .map((statement) => declareModelValues(statement, context));
132
+ const declarations = statements.flatMap(getDeclarations);
133
+ const variables = declarations.flatMap((declared) => {
134
+ const declaration = declared.declaration;
135
+ if (!isLet(declared) || !ts.isVariableDeclaration(declaration)) return [];
136
+ const symbol = getSymbol(declaration.name, context.checker);
137
+ if (isExported(declaration) || symbol === undefined) {
138
+ throw new TlaTypeScriptError("State variables can't be exported", declaration);
139
+ }
140
+ const name = context.names.getFresh(declared.name);
141
+ context.variables.set(symbol, name);
142
+ return [{ name, declaration }];
143
+ });
144
+ const helpers = declarations.filter((declared) => !isLet(declared));
145
+ const exported = helpers.flatMap((declared) => {
146
+ const declaration = declared.declaration;
147
+ const node = getFunction(declaration);
148
+ if (!isExported(declaration) || node?.body === undefined) return [];
149
+ const statement = ts.isVariableDeclaration(declaration)
150
+ ? declaration.parent.parent
151
+ : declaration;
152
+ return [{ ...declared, node, body: node.body, tags: tags.get(statement) ?? new Map() }];
153
+ });
154
+ return {
155
+ variables,
156
+ exported: exported.map((definition) => ({
157
+ ...definition,
158
+ name: context.names.getFresh(definition.name),
159
+ })),
160
+ topLevel: new Map(helpers.map((declared) => [declared.name, declared.declaration])),
161
+ symmetrySets,
162
+ isDeadlockChecked: ![...tags.values()].some((statementTags) => statementTags.has("noDeadlock")),
163
+ };
164
+ };
@@ -0,0 +1,116 @@
1
+ // TLA+ keywords, the operators of the modules every spec extends, and the names tla-ts
2
+ // generates. A TypeScript name that collides with one of these gets a suffix.
3
+ const RESERVED = new Set([
4
+ "ACTION",
5
+ "ASSUME",
6
+ "ASSUMPTION",
7
+ "AXIOM",
8
+ "BOOLEAN",
9
+ "BY",
10
+ "CASE",
11
+ "CHOOSE",
12
+ "CONSTANT",
13
+ "CONSTANTS",
14
+ "COROLLARY",
15
+ "DEF",
16
+ "DEFINE",
17
+ "DEFS",
18
+ "DOMAIN",
19
+ "ELSE",
20
+ "ENABLED",
21
+ "EXCEPT",
22
+ "EXTENDS",
23
+ "FALSE",
24
+ "HAVE",
25
+ "HIDE",
26
+ "IF",
27
+ "IN",
28
+ "INSTANCE",
29
+ "LAMBDA",
30
+ "LEMMA",
31
+ "LET",
32
+ "LOCAL",
33
+ "MODULE",
34
+ "NEW",
35
+ "OBVIOUS",
36
+ "OMITTED",
37
+ "ONLY",
38
+ "OTHER",
39
+ "PICK",
40
+ "PROOF",
41
+ "PROPOSITION",
42
+ "PROVE",
43
+ "QED",
44
+ "RECURSIVE",
45
+ "SF_",
46
+ "STATE",
47
+ "STRING",
48
+ "SUBSET",
49
+ "SUFFICES",
50
+ "TAKE",
51
+ "TEMPORAL",
52
+ "THEN",
53
+ "THEOREM",
54
+ "TRUE",
55
+ "UNCHANGED",
56
+ "UNION",
57
+ "USE",
58
+ "VARIABLE",
59
+ "VARIABLES",
60
+ "WF_",
61
+ "WITH",
62
+ "WITNESS",
63
+ "Nat",
64
+ "Int",
65
+ "Seq",
66
+ "Len",
67
+ "Append",
68
+ "Head",
69
+ "Tail",
70
+ "SubSeq",
71
+ "SelectSeq",
72
+ "Cardinality",
73
+ "IsFiniteSet",
74
+ "Print",
75
+ "PrintT",
76
+ "Assert",
77
+ "JavaTime",
78
+ "TLCGet",
79
+ "TLCSet",
80
+ "Permutations",
81
+ "SortSeq",
82
+ "RandomElement",
83
+ "Any",
84
+ "ToString",
85
+ "TLCEval",
86
+ "Init",
87
+ "Next",
88
+ "Spec",
89
+ "vars",
90
+ "Null",
91
+ "Undefined",
92
+ "Perms",
93
+ "Rem",
94
+ "Quot",
95
+ ]);
96
+
97
+ export interface Names {
98
+ getFresh: (base: string) => string;
99
+ }
100
+
101
+ export const createNames = (): Names => {
102
+ const used = new Set<string>();
103
+ return {
104
+ getFresh: (base) => {
105
+ const sanitized = base.replace(/[^A-Za-z0-9_]/g, "_");
106
+ const name = /[A-Za-z]/.test(sanitized) ? sanitized : `v${sanitized}`;
107
+ const getCandidate = (index: number): string => {
108
+ const candidate = index === 0 ? name : `${name}_${index}`;
109
+ return used.has(candidate) || RESERVED.has(candidate) ? getCandidate(index + 1) : candidate;
110
+ };
111
+ const fresh = getCandidate(0);
112
+ used.add(fresh);
113
+ return fresh;
114
+ },
115
+ };
116
+ };
@@ -0,0 +1,51 @@
1
+ import { dirname } from "node:path";
2
+ import ts from "@typescript/typescript6";
3
+ import { TlaTypeScriptError } from "../errors";
4
+
5
+ const COMPILER_OPTIONS: ts.CompilerOptions = {
6
+ strict: true,
7
+ noEmit: true,
8
+ target: ts.ScriptTarget.ESNext,
9
+ module: ts.ModuleKind.ESNext,
10
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
11
+ moduleDetection: ts.ModuleDetectionKind.Force,
12
+ allowImportingTsExtensions: true,
13
+ resolveJsonModule: true,
14
+ skipLibCheck: true,
15
+ lib: ["lib.esnext.d.ts"],
16
+ types: [],
17
+ };
18
+
19
+ const LIBRARY_DIRECTORY = dirname(ts.getDefaultLibFilePath(COMPILER_OPTIONS));
20
+
21
+ // TypeScript's own declaration files, parsed once and shared by every program, since parsing them
22
+ // takes most of a compile.
23
+ const libraryFiles = new Map<string, ts.SourceFile>();
24
+
25
+ // Type checks a model, with the files it imports, and throws its type errors.
26
+ export const createProgram = (source: string, path: string) => {
27
+ const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.ESNext, true);
28
+ const host = ts.createCompilerHost(COMPILER_OPTIONS);
29
+ const program = ts.createProgram({
30
+ rootNames: [path],
31
+ options: COMPILER_OPTIONS,
32
+ host: {
33
+ ...host,
34
+ getSourceFile: (fileName, languageVersion) => {
35
+ if (fileName === path) return sourceFile;
36
+ const cached = libraryFiles.get(fileName);
37
+ if (cached !== undefined) return cached;
38
+ const file = host.getSourceFile(fileName, languageVersion);
39
+ if (file !== undefined && fileName.startsWith(LIBRARY_DIRECTORY)) {
40
+ libraryFiles.set(fileName, file);
41
+ }
42
+ return file;
43
+ },
44
+ fileExists: (fileName) => fileName === path || host.fileExists(fileName),
45
+ readFile: (fileName) => (fileName === path ? source : host.readFile(fileName)),
46
+ },
47
+ });
48
+ const diagnostics = ts.getPreEmitDiagnostics(program);
49
+ if (diagnostics.length > 0) throw new TlaTypeScriptError(ts.formatDiagnostics(diagnostics, host));
50
+ return { sourceFile, checker: program.getTypeChecker() };
51
+ };