tla-ts 0.0.9-dev.2813db5 → 0.0.9-dev.4ce0657
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/README.md +21 -0
- package/dist/compile.cjs +23 -0
- package/dist/compile.js +23 -0
- package/dist/deciders.cjs +15 -15
- package/dist/deciders.js +48 -48
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/prove.cjs +16 -16
- package/dist/prove.js +20 -20
- package/dist/run.cjs +28 -28
- package/dist/run.js +31 -31
- package/dist/tlapm.cjs +2 -2
- package/dist/tlapm.js +1 -1
- package/dist/transfer.cjs +18 -18
- package/dist/transfer.js +26 -26
- package/dist/worker.cjs +4 -4
- package/dist/worker.js +4 -4
- package/package.json +3 -1
- package/src/check.ts +44 -31
- package/src/cli/options.ts +1 -1
- package/src/cli/tlc.ts +17 -8
- package/src/cli/typescript.ts +26 -0
- package/src/environment.ts +4 -0
- package/src/errors.ts +15 -0
- package/src/evaluate.ts +65 -10
- package/src/instances.ts +67 -6
- package/src/liveness-checker.ts +6 -3
- package/src/liveness.ts +7 -3
- package/src/prover/smt/solver/solver.ts +31 -27
- package/src/successors.ts +3 -3
- package/src/typescript/actions.ts +494 -0
- package/src/typescript/collections.ts +615 -0
- package/src/typescript/compile.ts +70 -0
- package/src/typescript/context.ts +106 -0
- package/src/typescript/emit.ts +122 -0
- package/src/typescript/expressions.ts +508 -0
- package/src/typescript/formula.ts +160 -0
- package/src/typescript/functions.ts +295 -0
- package/src/typescript/model.ts +164 -0
- package/src/typescript/names.ts +116 -0
- package/src/typescript/program.ts +51 -0
- package/src/typescript/properties.ts +141 -0
- package/src/typescript/scope.ts +117 -0
- package/src/typescript/steps.ts +175 -0
- package/src/typescript/types.ts +178 -0
- package/src/values.ts +11 -9
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import ts from "@typescript/typescript6";
|
|
2
|
+
import { type Context, getSymbol } from "./context";
|
|
3
|
+
import type { Sections } from "./emit";
|
|
4
|
+
import { TlaTypeScriptError } from "../errors";
|
|
5
|
+
import { translateCondition } from "./expressions";
|
|
6
|
+
import { indent } from "./formula";
|
|
7
|
+
import { getDefinition, translateBody } from "./functions";
|
|
8
|
+
import type { Exported, Model } from "./model";
|
|
9
|
+
import { bindNames, createStateScope, declareParameter, type Scope } from "./scope";
|
|
10
|
+
import { getDomain } from "./types";
|
|
11
|
+
|
|
12
|
+
const TEMPORAL_OPERATORS = new Map([
|
|
13
|
+
["eventually", "<>"],
|
|
14
|
+
["alwaysEventually", "[]<>"],
|
|
15
|
+
["eventuallyAlways", "<>[]"],
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
// Tags whose functions become named predicates that the config lists in a section.
|
|
19
|
+
const PREDICATE_TAGS = new Map<string, keyof Sections>([
|
|
20
|
+
["constraint", "constraints"],
|
|
21
|
+
["actionConstraint", "actionConstraints"],
|
|
22
|
+
["view", "views"],
|
|
23
|
+
["postcondition", "postconditions"],
|
|
24
|
+
["assume", "assumptions"],
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
// Tags that make an exported function a property of the spec rather than an action.
|
|
28
|
+
export const VALUE_TAGS = new Set([
|
|
29
|
+
...TEMPORAL_OPERATORS.keys(),
|
|
30
|
+
...PREDICATE_TAGS.keys(),
|
|
31
|
+
"initially",
|
|
32
|
+
"always",
|
|
33
|
+
"leadsTo",
|
|
34
|
+
]);
|
|
35
|
+
|
|
36
|
+
// The scope of an action property, whose one parameter names the state before the step, and whose
|
|
37
|
+
// variables are the state after it.
|
|
38
|
+
const getPreviousScope = (definition: Exported, context: Context): Scope => {
|
|
39
|
+
const parameters = definition.node.parameters;
|
|
40
|
+
if (parameters.length === 0) return createStateScope(context);
|
|
41
|
+
if (parameters.length > 1 || !ts.isIdentifier(parameters[0].name)) {
|
|
42
|
+
throw new TlaTypeScriptError("Take the state before the step as one parameter", parameters[0]);
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
bindings: new Map([...context.variables].map((entry) => [entry[0], `${entry[1]}'`])),
|
|
46
|
+
previous: getSymbol(parameters[0].name, context.checker),
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// The operator that a @leadsTo tag names, applied to the parameters that it shares.
|
|
51
|
+
const getLeadsToTarget = (
|
|
52
|
+
definition: Exported,
|
|
53
|
+
parameters: string[],
|
|
54
|
+
model: Model,
|
|
55
|
+
context: Context,
|
|
56
|
+
) => {
|
|
57
|
+
const targetName = definition.tags.get("leadsTo") ?? "";
|
|
58
|
+
const target = model.topLevel.get(targetName);
|
|
59
|
+
if (target === undefined) {
|
|
60
|
+
throw new TlaTypeScriptError(
|
|
61
|
+
`@leadsTo names an unknown function: ${targetName}`,
|
|
62
|
+
definition.node,
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
const exported = model.exported.find((candidate) => candidate.declaration === target);
|
|
66
|
+
if (exported !== undefined) return exported.name;
|
|
67
|
+
const targetDefinition = getDefinition(target, context);
|
|
68
|
+
const values = parameters.slice(0, targetDefinition.parameters.length);
|
|
69
|
+
return values.length === 0
|
|
70
|
+
? targetDefinition.name
|
|
71
|
+
: `${targetDefinition.name}(${values.join(", ")})`;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
export const translateProperty = (
|
|
75
|
+
definition: Exported,
|
|
76
|
+
tag: string,
|
|
77
|
+
model: Model,
|
|
78
|
+
sections: Sections,
|
|
79
|
+
context: Context,
|
|
80
|
+
) => {
|
|
81
|
+
const name = definition.name;
|
|
82
|
+
const node = definition.node;
|
|
83
|
+
const hasPreviousState = tag === "always" || tag === "actionConstraint";
|
|
84
|
+
// A temporal property's parameters hold for every value, as in \A p \in P : []<>Eats(p).
|
|
85
|
+
const isQuantified = TEMPORAL_OPERATORS.has(tag) || tag === "leadsTo";
|
|
86
|
+
if (!hasPreviousState && !isQuantified && node.parameters.length > 0) {
|
|
87
|
+
throw new TlaTypeScriptError(`@${tag} functions can't take parameters`, node.parameters[0]);
|
|
88
|
+
}
|
|
89
|
+
const quantified = (isQuantified ? node.parameters : []).map((parameter) => ({
|
|
90
|
+
...declareParameter(parameter, context),
|
|
91
|
+
domain: getDomain(context.checker.getTypeAtLocation(parameter.name), parameter, context),
|
|
92
|
+
}));
|
|
93
|
+
const scope = hasPreviousState
|
|
94
|
+
? getPreviousScope(definition, context)
|
|
95
|
+
: bindNames(createStateScope(context), quantified);
|
|
96
|
+
const forAll =
|
|
97
|
+
quantified.length === 0
|
|
98
|
+
? ""
|
|
99
|
+
: `\\A ${quantified.map((parameter) => `${parameter.name} \\in ${parameter.domain}`).join(", ")} : `;
|
|
100
|
+
const value = indent(translateBody(definition.body, scope, context), " ");
|
|
101
|
+
const operator = TEMPORAL_OPERATORS.get(tag);
|
|
102
|
+
const predicate = PREDICATE_TAGS.get(tag);
|
|
103
|
+
if (operator !== undefined) {
|
|
104
|
+
sections.temporal.push(`${name} ==\n ${forAll}${operator}(${value})`);
|
|
105
|
+
sections.properties.push(name);
|
|
106
|
+
}
|
|
107
|
+
if (tag === "leadsTo") {
|
|
108
|
+
const parameters = quantified.map((parameter) => parameter.name);
|
|
109
|
+
const target = getLeadsToTarget(definition, parameters, model, context);
|
|
110
|
+
sections.temporal.push(`${name} ==\n ${forAll}(${value}) ~> ${target}`);
|
|
111
|
+
sections.properties.push(name);
|
|
112
|
+
}
|
|
113
|
+
if (tag === "always") {
|
|
114
|
+
sections.temporal.push(
|
|
115
|
+
node.parameters.length === 0
|
|
116
|
+
? `${name} ==\n [](${value})`
|
|
117
|
+
: `${name} ==\n [][${value}]_vars`,
|
|
118
|
+
);
|
|
119
|
+
sections.properties.push(name);
|
|
120
|
+
}
|
|
121
|
+
if (tag === "initially") sections.init.push(value);
|
|
122
|
+
if (predicate !== undefined) {
|
|
123
|
+
sections.predicates.push(`${name} ==\n ${value}`);
|
|
124
|
+
sections[predicate].push(name);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
// An exported function that returns a boolean, which holds in every state.
|
|
129
|
+
export const translateInvariant = (definition: Exported, sections: Sections, context: Context) => {
|
|
130
|
+
const parameters = definition.node.parameters;
|
|
131
|
+
if (parameters.length > 0) {
|
|
132
|
+
throw new TlaTypeScriptError("Invariants can't take parameters", parameters[0]);
|
|
133
|
+
}
|
|
134
|
+
const body = definition.body;
|
|
135
|
+
const scope = createStateScope(context);
|
|
136
|
+
const value = ts.isBlock(body)
|
|
137
|
+
? translateBody(body, scope, context)
|
|
138
|
+
: translateCondition(body, scope, context);
|
|
139
|
+
sections.predicates.push(`${definition.name} ==\n ${indent(value, " ")}`);
|
|
140
|
+
sections.invariants.push(definition.name);
|
|
141
|
+
};
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import ts from "@typescript/typescript6";
|
|
2
|
+
import { type Context, getSymbol } from "./context";
|
|
3
|
+
import { TlaTypeScriptError } from "../errors";
|
|
4
|
+
import { indent, wrap } from "./formula";
|
|
5
|
+
|
|
6
|
+
export interface Scope {
|
|
7
|
+
// The TLA+ expression for each variable, parameter, and local in scope.
|
|
8
|
+
bindings: Map<ts.Symbol, string>;
|
|
9
|
+
// The parameter that names the state before a step, in action properties and constraints.
|
|
10
|
+
previous: ts.Symbol | undefined;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface Bound {
|
|
14
|
+
definitions: string[];
|
|
15
|
+
scope: Scope;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface Parameter {
|
|
19
|
+
node: ts.ParameterDeclaration;
|
|
20
|
+
name: string;
|
|
21
|
+
symbol: ts.Symbol | undefined;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface Named {
|
|
25
|
+
name: string;
|
|
26
|
+
symbol: ts.Symbol | undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const createStateScope = (context: Context): Scope => ({
|
|
30
|
+
bindings: new Map(context.variables),
|
|
31
|
+
previous: undefined,
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
export const bindNames = (scope: Scope, named: Named[]): Scope => ({
|
|
35
|
+
bindings: new Map([
|
|
36
|
+
...scope.bindings,
|
|
37
|
+
...named.flatMap((item): [ts.Symbol, string][] =>
|
|
38
|
+
item.symbol === undefined ? [] : [[item.symbol, item.name]],
|
|
39
|
+
),
|
|
40
|
+
]),
|
|
41
|
+
previous: scope.previous,
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
export const declareParameter = (
|
|
45
|
+
parameter: ts.ParameterDeclaration,
|
|
46
|
+
context: Context,
|
|
47
|
+
): Parameter => {
|
|
48
|
+
if (
|
|
49
|
+
!ts.isIdentifier(parameter.name) ||
|
|
50
|
+
parameter.initializer !== undefined ||
|
|
51
|
+
parameter.questionToken !== undefined ||
|
|
52
|
+
parameter.dotDotDotToken !== undefined
|
|
53
|
+
) {
|
|
54
|
+
throw new TlaTypeScriptError(`Use a plain parameter here: ${parameter.getText()}`, parameter);
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
node: parameter,
|
|
58
|
+
name: context.names.getFresh(parameter.name.text),
|
|
59
|
+
symbol: getSymbol(parameter.name, context.checker),
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export const declareParameters = (
|
|
64
|
+
parameters: readonly ts.ParameterDeclaration[],
|
|
65
|
+
context: Context,
|
|
66
|
+
) => parameters.map((parameter) => declareParameter(parameter, context));
|
|
67
|
+
|
|
68
|
+
// Binds the names in a destructuring pattern to parts of a value, without LET definitions.
|
|
69
|
+
export const bindPatternInline = (
|
|
70
|
+
pattern: ts.BindingName,
|
|
71
|
+
value: string,
|
|
72
|
+
scope: Scope,
|
|
73
|
+
context: Context,
|
|
74
|
+
): Scope => {
|
|
75
|
+
if (ts.isIdentifier(pattern)) {
|
|
76
|
+
return bindNames(scope, [{ name: value, symbol: getSymbol(pattern, context.checker) }]);
|
|
77
|
+
}
|
|
78
|
+
return pattern.elements.reduce((current, element, index) => {
|
|
79
|
+
if (ts.isOmittedExpression(element)) return current;
|
|
80
|
+
if (element.dotDotDotToken !== undefined || element.initializer !== undefined) {
|
|
81
|
+
throw new TlaTypeScriptError("Rest elements and default values aren't supported", element);
|
|
82
|
+
}
|
|
83
|
+
const part = ts.isArrayBindingPattern(pattern)
|
|
84
|
+
? `${wrap(value)}[${index + 1}]`
|
|
85
|
+
: `${wrap(value)}.${(element.propertyName ?? element.name).getText()}`;
|
|
86
|
+
return bindPatternInline(element.name, part, current, context);
|
|
87
|
+
}, scope);
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
// Binds the names in a declaration to LET definitions.
|
|
91
|
+
export const bindPattern = (
|
|
92
|
+
pattern: ts.BindingName,
|
|
93
|
+
value: string,
|
|
94
|
+
scope: Scope,
|
|
95
|
+
context: Context,
|
|
96
|
+
): Bound => {
|
|
97
|
+
const name = context.names.getFresh(ts.isIdentifier(pattern) ? pattern.text : "value");
|
|
98
|
+
return {
|
|
99
|
+
definitions: [`${name} == ${indent(value, " ")}`],
|
|
100
|
+
scope: bindPatternInline(pattern, name, scope, context),
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
// Binds parameters to argument values with LET definitions, as when inlining a call.
|
|
105
|
+
export const bindValues = (
|
|
106
|
+
patterns: ts.BindingName[],
|
|
107
|
+
values: string[],
|
|
108
|
+
scope: Scope,
|
|
109
|
+
context: Context,
|
|
110
|
+
) =>
|
|
111
|
+
patterns.reduce<Bound>(
|
|
112
|
+
(current, pattern, index) => {
|
|
113
|
+
const bound = bindPattern(pattern, values[index], current.scope, context);
|
|
114
|
+
return { definitions: [...current.definitions, ...bound.definitions], scope: bound.scope };
|
|
115
|
+
},
|
|
116
|
+
{ definitions: [], scope },
|
|
117
|
+
);
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import ts from "@typescript/typescript6";
|
|
2
|
+
import { translateAction } from "./actions";
|
|
3
|
+
import { type Context, getSymbol, isMethodCall } from "./context";
|
|
4
|
+
import type { Sections } from "./emit";
|
|
5
|
+
import { translateExpression } from "./expressions";
|
|
6
|
+
import { indent, render, wrap } from "./formula";
|
|
7
|
+
import type { Exported } from "./model";
|
|
8
|
+
import { bindNames, createStateScope, declareParameters, type Parameter } from "./scope";
|
|
9
|
+
import { findDomain, getDomain, isSet } from "./types";
|
|
10
|
+
|
|
11
|
+
interface Guard {
|
|
12
|
+
parameter: Parameter;
|
|
13
|
+
set: ts.Expression;
|
|
14
|
+
isDependent: boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface Chosen {
|
|
18
|
+
domain: string;
|
|
19
|
+
// Whether the set uses parameters that earlier guards chose.
|
|
20
|
+
isDependent: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface Guards {
|
|
24
|
+
chosen: Map<Parameter, Chosen>;
|
|
25
|
+
remaining: readonly ts.Statement[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const isBareReturn = (statement: ts.Statement): boolean =>
|
|
29
|
+
ts.isReturnStatement(statement)
|
|
30
|
+
? statement.expression === undefined
|
|
31
|
+
: ts.isBlock(statement) &&
|
|
32
|
+
statement.statements.length === 1 &&
|
|
33
|
+
isBareReturn(statement.statements[0]);
|
|
34
|
+
|
|
35
|
+
// A leading `if (!set.has(parameter)) return;` chooses the parameter from that set, as
|
|
36
|
+
// `\E parameter \in set` does, so TLC doesn't enumerate the parameter's whole type.
|
|
37
|
+
const getGuard = (
|
|
38
|
+
statement: ts.Statement,
|
|
39
|
+
parameters: Parameter[],
|
|
40
|
+
chosen: Map<Parameter, Chosen>,
|
|
41
|
+
context: Context,
|
|
42
|
+
): Guard | undefined => {
|
|
43
|
+
if (
|
|
44
|
+
!ts.isIfStatement(statement) ||
|
|
45
|
+
statement.elseStatement !== undefined ||
|
|
46
|
+
!isBareReturn(statement.thenStatement)
|
|
47
|
+
) {
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
const condition = statement.expression;
|
|
51
|
+
if (
|
|
52
|
+
!ts.isPrefixUnaryExpression(condition) ||
|
|
53
|
+
condition.operator !== ts.SyntaxKind.ExclamationToken
|
|
54
|
+
) {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
const call = ts.isParenthesizedExpression(condition.operand)
|
|
58
|
+
? condition.operand.expression
|
|
59
|
+
: condition.operand;
|
|
60
|
+
if (!isMethodCall(call) || call.expression.name.text !== "has" || call.arguments.length !== 1) {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
const getParameters = (node: ts.Node): Parameter[] => [
|
|
64
|
+
...parameters.filter(
|
|
65
|
+
(parameter) => ts.isIdentifier(node) && parameter.symbol === getSymbol(node, context.checker),
|
|
66
|
+
),
|
|
67
|
+
...node.getChildren().flatMap(getParameters),
|
|
68
|
+
];
|
|
69
|
+
const argument = call.arguments[0];
|
|
70
|
+
const parameter = parameters.find(
|
|
71
|
+
(candidate) => candidate.symbol === getSymbol(argument, context.checker),
|
|
72
|
+
);
|
|
73
|
+
const set = call.expression.expression;
|
|
74
|
+
// The set may use parameters that earlier guards chose, as in \E a \in A : \E b \in B(a).
|
|
75
|
+
const used = getParameters(set);
|
|
76
|
+
if (
|
|
77
|
+
parameter === undefined ||
|
|
78
|
+
chosen.has(parameter) ||
|
|
79
|
+
!used.every((candidate) => chosen.has(candidate)) ||
|
|
80
|
+
!isSet(set, context)
|
|
81
|
+
) {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
return { parameter, set, isDependent: used.length > 0 };
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
// The parameters that leading guards choose, and the statements after the guards.
|
|
88
|
+
const readGuards = (
|
|
89
|
+
statements: readonly ts.Statement[],
|
|
90
|
+
parameters: Parameter[],
|
|
91
|
+
chosen: Map<Parameter, Chosen>,
|
|
92
|
+
context: Context,
|
|
93
|
+
): Guards => {
|
|
94
|
+
const guard =
|
|
95
|
+
statements.length === 0 ? undefined : getGuard(statements[0], parameters, chosen, context);
|
|
96
|
+
if (guard === undefined) return { chosen, remaining: statements };
|
|
97
|
+
const scope = bindNames(createStateScope(context), [...chosen.keys()]);
|
|
98
|
+
const domain = translateExpression(guard.set, scope, context);
|
|
99
|
+
return readGuards(
|
|
100
|
+
statements.slice(1),
|
|
101
|
+
parameters,
|
|
102
|
+
new Map([...chosen, [guard.parameter, { domain, isDependent: guard.isDependent }]]),
|
|
103
|
+
context,
|
|
104
|
+
);
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
// An exported function that changes state, as an action and its disjunct of Next. Each parameter
|
|
108
|
+
// ranges over its type, or over the set that a guard chooses it from.
|
|
109
|
+
export const translateStep = (definition: Exported, sections: Sections, context: Context) => {
|
|
110
|
+
const name = definition.name;
|
|
111
|
+
const body = definition.body;
|
|
112
|
+
const parameters = declareParameters(definition.node.parameters, context);
|
|
113
|
+
const guards = readGuards(
|
|
114
|
+
ts.isBlock(body) ? body.statements : [ts.factory.createExpressionStatement(body)],
|
|
115
|
+
parameters,
|
|
116
|
+
new Map(),
|
|
117
|
+
context,
|
|
118
|
+
);
|
|
119
|
+
const formula = translateAction(
|
|
120
|
+
guards.remaining,
|
|
121
|
+
bindNames(createStateScope(context), parameters),
|
|
122
|
+
context,
|
|
123
|
+
);
|
|
124
|
+
const head =
|
|
125
|
+
parameters.length === 0
|
|
126
|
+
? name
|
|
127
|
+
: `${name}(${parameters.map((parameter) => parameter.name).join(", ")})`;
|
|
128
|
+
sections.actions.push(`${head} ==\n ${indent(render(formula), " ")}`);
|
|
129
|
+
const fairness = definition.tags.has("strongFair")
|
|
130
|
+
? "SF_vars"
|
|
131
|
+
: definition.tags.has("fair")
|
|
132
|
+
? "WF_vars"
|
|
133
|
+
: undefined;
|
|
134
|
+
if (parameters.length === 0) {
|
|
135
|
+
sections.next.push(name);
|
|
136
|
+
if (fairness !== undefined) sections.fairness.push(`${fairness}(${name})`);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const getType = (parameter: Parameter) => context.checker.getTypeAtLocation(parameter.node.name);
|
|
140
|
+
const domains = parameters.map(
|
|
141
|
+
(parameter) =>
|
|
142
|
+
guards.chosen.get(parameter)?.domain ??
|
|
143
|
+
getDomain(getType(parameter), parameter.node, context),
|
|
144
|
+
);
|
|
145
|
+
const independent = parameters.flatMap((parameter, index) =>
|
|
146
|
+
guards.chosen.get(parameter)?.isDependent === true
|
|
147
|
+
? []
|
|
148
|
+
: [`${parameter.name} \\in ${domains[index]}`],
|
|
149
|
+
);
|
|
150
|
+
// Guards run in order, so each dependent parameter is chosen after the ones its set uses.
|
|
151
|
+
const dependent = [...guards.chosen]
|
|
152
|
+
.filter((entry) => entry[1].isDependent)
|
|
153
|
+
.map((entry) => `\\E ${entry[0].name} \\in ${entry[1].domain} : `);
|
|
154
|
+
const step = `\\E ${independent.join(", ")} : ${dependent.join("")}${head}`;
|
|
155
|
+
sections.next.push(step);
|
|
156
|
+
if (fairness === undefined) return;
|
|
157
|
+
// Fairness holds for each parameter value when every parameter has a finite type, with the
|
|
158
|
+
// guards that chose parameters kept inside the action.
|
|
159
|
+
const typeDomains = parameters.map((parameter, index) =>
|
|
160
|
+
guards.chosen.has(parameter) ? findDomain(getType(parameter), context) : domains[index],
|
|
161
|
+
);
|
|
162
|
+
const conditions = parameters.flatMap((parameter, index) =>
|
|
163
|
+
guards.chosen.has(parameter) ? [`${parameter.name} \\in ${wrap(domains[index])}`] : [],
|
|
164
|
+
);
|
|
165
|
+
if (!typeDomains.every((domain): domain is string => typeof domain === "string")) {
|
|
166
|
+
sections.fairness.push(`${fairness}(${step})`);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const forAll = parameters.map(
|
|
170
|
+
(parameter, index) => `${parameter.name} \\in ${typeDomains[index]}`,
|
|
171
|
+
);
|
|
172
|
+
sections.fairness.push(
|
|
173
|
+
`\\A ${forAll.join(", ")} : ${fairness}(${[...conditions, head].join(" /\\ ")})`,
|
|
174
|
+
);
|
|
175
|
+
};
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import ts from "@typescript/typescript6";
|
|
2
|
+
import { type Context, translateString } from "./context";
|
|
3
|
+
import { TlaTypeScriptError } from "../errors";
|
|
4
|
+
import { wrap } from "./formula";
|
|
5
|
+
|
|
6
|
+
export type Kind = "sequence" | "set" | "map" | "string" | "other";
|
|
7
|
+
|
|
8
|
+
// Why a type has no finite set of values.
|
|
9
|
+
interface Infinite {
|
|
10
|
+
message: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// The checker only gives type arguments of type references, which the public API can't detect.
|
|
14
|
+
const isTypeReference = (type: ts.Type): type is ts.TypeReference =>
|
|
15
|
+
(type.flags & ts.TypeFlags.Object) !== 0 &&
|
|
16
|
+
((type as ts.ObjectType).objectFlags & ts.ObjectFlags.Reference) !== 0;
|
|
17
|
+
|
|
18
|
+
const getTypeName = (type: ts.Type) => type.getSymbol()?.getName() ?? "";
|
|
19
|
+
|
|
20
|
+
const isSetType = (type: ts.Type) => ["Set", "ReadonlySet"].includes(getTypeName(type));
|
|
21
|
+
|
|
22
|
+
const isMapType = (type: ts.Type) => ["Map", "ReadonlyMap"].includes(getTypeName(type));
|
|
23
|
+
|
|
24
|
+
// Arrays, tuples, and unions of them, such as [] | [number] | [number, number].
|
|
25
|
+
const isSequenceType = (type: ts.Type, checker: ts.TypeChecker): boolean =>
|
|
26
|
+
type.isUnion()
|
|
27
|
+
? type.types.every((member) => isSequenceType(member, checker))
|
|
28
|
+
: checker.isArrayType(type) || checker.isTupleType(type);
|
|
29
|
+
|
|
30
|
+
// Whether every member of a type, such as each literal in a union, has the given flags.
|
|
31
|
+
const isEvery = (type: ts.Type, flags: ts.TypeFlags): boolean =>
|
|
32
|
+
type.isUnion()
|
|
33
|
+
? type.types.every((member) => isEvery(member, flags))
|
|
34
|
+
: (type.flags & flags) !== 0;
|
|
35
|
+
|
|
36
|
+
export const getKind = (node: ts.Expression, context: Context): Kind => {
|
|
37
|
+
const checker = context.checker;
|
|
38
|
+
const type = checker.getNonNullableType(checker.getTypeAtLocation(node));
|
|
39
|
+
if (isSequenceType(type, checker)) return "sequence";
|
|
40
|
+
if (isSetType(type)) return "set";
|
|
41
|
+
if (isMapType(type)) return "map";
|
|
42
|
+
if (isEvery(type, ts.TypeFlags.StringLike)) return "string";
|
|
43
|
+
return "other";
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export const isBooleanLike = (node: ts.Expression, context: Context) =>
|
|
47
|
+
isEvery(context.checker.getTypeAtLocation(node), ts.TypeFlags.BooleanLike);
|
|
48
|
+
|
|
49
|
+
export const isSet = (node: ts.Expression, context: Context) =>
|
|
50
|
+
isSetType(context.checker.getTypeAtLocation(node));
|
|
51
|
+
|
|
52
|
+
// TLA+ records only have identifier fields, so an object with numeric keys becomes a function.
|
|
53
|
+
export const isNumericKey = (key: string) => /^-?\d+$/.test(key);
|
|
54
|
+
|
|
55
|
+
const getLiteral = (type: ts.Type, context: Context) => {
|
|
56
|
+
if (type.isStringLiteral()) return translateString(type.value, context);
|
|
57
|
+
if (type.isNumberLiteral()) return Number.isInteger(type.value) ? String(type.value) : undefined;
|
|
58
|
+
if (type.flags & ts.TypeFlags.BooleanLiteral) {
|
|
59
|
+
return context.checker.typeToString(type) === "true" ? "TRUE" : "FALSE";
|
|
60
|
+
}
|
|
61
|
+
if (type.flags & ts.TypeFlags.Null) {
|
|
62
|
+
context.prelude.add("Null");
|
|
63
|
+
return "Null";
|
|
64
|
+
}
|
|
65
|
+
if (type.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Void)) {
|
|
66
|
+
context.prelude.add("Undefined");
|
|
67
|
+
return "Undefined";
|
|
68
|
+
}
|
|
69
|
+
return undefined;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const getInfinite = (type: ts.Type, reason: string, context: Context): Infinite => ({
|
|
73
|
+
message: `${context.checker.typeToString(type)} isn't finite: ${reason}`,
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
// The first type that has no end, or the domains of every type.
|
|
77
|
+
const findDomains = (types: readonly ts.Type[], context: Context) =>
|
|
78
|
+
types.reduce<string[] | Infinite>((domains, type) => {
|
|
79
|
+
if (!Array.isArray(domains)) return domains;
|
|
80
|
+
const domain = findDomain(type, context);
|
|
81
|
+
return typeof domain === "string" ? [...domains, domain] : domain;
|
|
82
|
+
}, []);
|
|
83
|
+
|
|
84
|
+
// The set of every value that a finite type allows, which TLC enumerates.
|
|
85
|
+
export const findDomain = (type: ts.Type, context: Context): string | Infinite => {
|
|
86
|
+
const checker = context.checker;
|
|
87
|
+
if (type.flags & ts.TypeFlags.Boolean) return "BOOLEAN";
|
|
88
|
+
if (type.isUnion()) {
|
|
89
|
+
const literals = type.types.map((member) => getLiteral(member, context));
|
|
90
|
+
const others = findDomains(
|
|
91
|
+
type.types.filter((_, index) => literals[index] === undefined),
|
|
92
|
+
context,
|
|
93
|
+
);
|
|
94
|
+
if (!Array.isArray(others)) return others;
|
|
95
|
+
const enumerated = literals
|
|
96
|
+
.filter((literal) => literal !== undefined)
|
|
97
|
+
.sort((left, right) =>
|
|
98
|
+
/^-?\d+$/.test(left) && /^-?\d+$/.test(right) ? Number(left) - Number(right) : 0,
|
|
99
|
+
);
|
|
100
|
+
return [...(enumerated.length > 0 ? [`{${enumerated.join(", ")}}`] : []), ...others]
|
|
101
|
+
.map((domain, _, domains) => (domains.length > 1 ? wrap(domain) : domain))
|
|
102
|
+
.join(" \\cup ");
|
|
103
|
+
}
|
|
104
|
+
const literal = getLiteral(type, context);
|
|
105
|
+
if (literal !== undefined) return `{${literal}}`;
|
|
106
|
+
if (isSetType(type) || isMapType(type) || checker.isTupleType(type)) {
|
|
107
|
+
const elements = findDomains(
|
|
108
|
+
isTypeReference(type) ? checker.getTypeArguments(type) : [],
|
|
109
|
+
context,
|
|
110
|
+
);
|
|
111
|
+
if (!Array.isArray(elements)) return elements;
|
|
112
|
+
if (isSetType(type)) return `SUBSET ${wrap(elements[0])}`;
|
|
113
|
+
if (isMapType(type)) {
|
|
114
|
+
const keys = context.names.getFresh("keys");
|
|
115
|
+
return `UNION {[${keys} -> ${elements[1]}] : ${keys} \\in SUBSET ${wrap(elements[0])}}`;
|
|
116
|
+
}
|
|
117
|
+
const isFixed =
|
|
118
|
+
isTypeReference(type) &&
|
|
119
|
+
(type.target as ts.TupleType).elementFlags.every(
|
|
120
|
+
(flags) => (flags & ts.ElementFlags.Required) !== 0,
|
|
121
|
+
);
|
|
122
|
+
if (!isFixed) {
|
|
123
|
+
return getInfinite(
|
|
124
|
+
type,
|
|
125
|
+
"tuples with optional or rest elements can have any length",
|
|
126
|
+
context,
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
if (elements.length === 0) return "{<<>>}";
|
|
130
|
+
if (elements.length > 1) return elements.map(wrap).join(" \\X ");
|
|
131
|
+
const element = context.names.getFresh("element");
|
|
132
|
+
return `{<<${element}>> : ${element} \\in ${elements[0]}}`;
|
|
133
|
+
}
|
|
134
|
+
if (checker.isArrayType(type)) {
|
|
135
|
+
return getInfinite(type, "arrays can have any length, so use a tuple", context);
|
|
136
|
+
}
|
|
137
|
+
const properties = type.getProperties();
|
|
138
|
+
const isRecord =
|
|
139
|
+
type.flags & ts.TypeFlags.Object &&
|
|
140
|
+
type.getCallSignatures().length === 0 &&
|
|
141
|
+
checker.getIndexInfosOfType(type).length === 0 &&
|
|
142
|
+
properties.length > 0;
|
|
143
|
+
if (!isRecord) {
|
|
144
|
+
return getInfinite(
|
|
145
|
+
type,
|
|
146
|
+
"use a union of literals, or records, tuples, and sets of them",
|
|
147
|
+
context,
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
const optional = properties.find((property) => property.flags & ts.SymbolFlags.Optional);
|
|
151
|
+
if (optional !== undefined) {
|
|
152
|
+
return getInfinite(type, `the optional field ${optional.name} may be missing`, context);
|
|
153
|
+
}
|
|
154
|
+
const fields = findDomains(
|
|
155
|
+
properties.map((property) => checker.getTypeOfSymbol(property)),
|
|
156
|
+
context,
|
|
157
|
+
);
|
|
158
|
+
if (!Array.isArray(fields)) return fields;
|
|
159
|
+
const keys = properties.map((property) => property.name);
|
|
160
|
+
if (!keys.some(isNumericKey)) {
|
|
161
|
+
return `[${keys.map((key, index) => `${key} : ${fields[index]}`).join(", ")}]`;
|
|
162
|
+
}
|
|
163
|
+
if (!keys.every(isNumericKey) || fields.some((field) => field !== fields[0])) {
|
|
164
|
+
return {
|
|
165
|
+
message: `${checker.typeToString(type)} has numeric keys, so every key must be a number with the same value type`,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
return `[{${keys
|
|
169
|
+
.map(Number)
|
|
170
|
+
.sort((left, right) => left - right)
|
|
171
|
+
.join(", ")}} -> ${fields[0]}]`;
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
export const getDomain = (type: ts.Type, node: ts.Node, context: Context) => {
|
|
175
|
+
const domain = findDomain(type, context);
|
|
176
|
+
if (typeof domain !== "string") throw new TlaTypeScriptError(domain.message, node);
|
|
177
|
+
return domain;
|
|
178
|
+
};
|
package/src/values.ts
CHANGED
|
@@ -591,12 +591,6 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
|
|
|
591
591
|
}
|
|
592
592
|
return compareValues(left, right) === 0;
|
|
593
593
|
}
|
|
594
|
-
const isHashed =
|
|
595
|
-
(left.kind === "Set" || left.kind === "Function") &&
|
|
596
|
-
(right.kind === "Set" || right.kind === "Function") &&
|
|
597
|
-
left.hash !== 0 &&
|
|
598
|
-
right.hash !== 0;
|
|
599
|
-
if (isHashed && left.hash !== right.hash) return false;
|
|
600
594
|
if (left.kind === "Function" && right.kind === "Function")
|
|
601
595
|
return compareFunctions(left, right) === 0;
|
|
602
596
|
if (left.kind === "Set" && right.kind === "Set") return compareSets(left, right) === 0;
|
|
@@ -1229,18 +1223,23 @@ export const createWrittenFunction = (pairs: [Value, Value][]) => {
|
|
|
1229
1223
|
);
|
|
1230
1224
|
};
|
|
1231
1225
|
|
|
1226
|
+
const MAX_SHARED_INTERVAL_LENGTH = 1024;
|
|
1232
1227
|
const intervalDomains: Value[][] = [];
|
|
1228
|
+
const longIntervalDomains = new Map<number, WeakRef<Value[]>>();
|
|
1233
1229
|
const intervalValues: IntervalValue[] = [];
|
|
1234
1230
|
const intervalArrays = new WeakMap<Value[], IntervalValue>();
|
|
1235
1231
|
|
|
1236
1232
|
// TLC keeps the domain of a tuple, or of a function built over an interval, as an interval. Every
|
|
1237
1233
|
// function over 1..n shares one domain array per length, and the elements of any other interval
|
|
1238
1234
|
// map to it, so the array's identity records it. Callers must not mutate the returned array.
|
|
1235
|
+
// Longer domains are held weakly: a sequence that grows one element at a time would otherwise keep
|
|
1236
|
+
// an array of every length it passed through, n * n / 2 numbers in all.
|
|
1239
1237
|
const getIntervalDomain = (length: number): Value[] => {
|
|
1240
|
-
const cached = intervalDomains[length];
|
|
1238
|
+
const cached = intervalDomains[length] ?? longIntervalDomains.get(length)?.deref();
|
|
1241
1239
|
if (cached) return cached;
|
|
1242
1240
|
const domain = Array.from({ length }, (_, index) => index + 1);
|
|
1243
|
-
|
|
1241
|
+
if (length > MAX_SHARED_INTERVAL_LENGTH) longIntervalDomains.set(length, new WeakRef(domain));
|
|
1242
|
+
else intervalDomains[length] = domain;
|
|
1244
1243
|
return domain;
|
|
1245
1244
|
};
|
|
1246
1245
|
|
|
@@ -1255,7 +1254,10 @@ export const getIntervalElements = (value: IntervalValue): Value[] => {
|
|
|
1255
1254
|
};
|
|
1256
1255
|
|
|
1257
1256
|
const isIntervalDomain = (domain: Value[]) =>
|
|
1258
|
-
domain.length > 0 &&
|
|
1257
|
+
domain.length > 0 &&
|
|
1258
|
+
(domain === intervalDomains[domain.length] ||
|
|
1259
|
+
domain === longIntervalDomains.get(domain.length)?.deref() ||
|
|
1260
|
+
intervalArrays.has(domain));
|
|
1259
1261
|
|
|
1260
1262
|
// TLC keeps an interval domain only for a function built over an interval itself, so a set
|
|
1261
1263
|
// such as (1..2) \cap S, whose elements are the shared array, gets a copy.
|