tla-ts 0.0.10-dev.28c823e4b → 0.0.10-dev.63a6693bd

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 (172) hide show
  1. package/dist/compile.cjs +6 -6
  2. package/dist/compile.js +10 -10
  3. package/dist/deciders.cjs +29 -29
  4. package/dist/deciders.js +40 -40
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/parallel-worker.cjs +1 -1
  8. package/dist/parallel-worker.js +1 -1
  9. package/dist/prove-worker.cjs +1 -1
  10. package/dist/prove-worker.js +1 -1
  11. package/dist/prove.cjs +54 -54
  12. package/dist/prove.js +52 -52
  13. package/dist/run.cjs +42 -42
  14. package/dist/run.js +44 -44
  15. package/dist/tlapm.cjs +2 -2
  16. package/dist/tlapm.js +2 -2
  17. package/dist/transfer.cjs +39 -39
  18. package/dist/transfer.js +41 -41
  19. package/dist/worker.cjs +4 -4
  20. package/dist/worker.js +4 -4
  21. package/package.json +1 -1
  22. package/src/ast.ts +44 -39
  23. package/src/builtins.ts +4 -13
  24. package/src/check-failure.ts +116 -0
  25. package/src/check-trace.ts +282 -0
  26. package/src/check.ts +152 -518
  27. package/src/cli/options.ts +6 -31
  28. package/src/cli/shared.ts +1 -1
  29. package/src/cli/tlapm.ts +14 -13
  30. package/src/cli/tlc-arguments.ts +222 -210
  31. package/src/cli/tlc-output.ts +687 -0
  32. package/src/cli/tlc-usage.ts +1 -1
  33. package/src/cli/tlc.ts +34 -701
  34. package/src/cli/xml-exporter.ts +23 -33
  35. package/src/codegen.ts +5 -10
  36. package/src/coverage.ts +3 -10
  37. package/src/dependencies.ts +8 -13
  38. package/src/dfid.ts +16 -16
  39. package/src/environment-config.ts +315 -0
  40. package/src/environment.ts +45 -333
  41. package/src/errors.ts +3 -2
  42. package/src/evaluate.ts +5 -4
  43. package/src/fingerprints.ts +65 -1
  44. package/src/instances.ts +47 -10
  45. package/src/java-hash.ts +7 -0
  46. package/src/json.ts +4 -7
  47. package/src/levels.ts +39 -42
  48. package/src/liveness-checker.ts +24 -37
  49. package/src/liveness.ts +47 -54
  50. package/src/obligations/action.ts +4 -11
  51. package/src/obligations/anonymize.ts +4 -2
  52. package/src/obligations/expression.ts +18 -2
  53. package/src/obligations/generate.ts +45 -38
  54. package/src/obligations/index.ts +2 -2
  55. package/src/obligations/module.ts +27 -38
  56. package/src/obligations/normalize.ts +2 -1
  57. package/src/obligations/simplify.ts +39 -44
  58. package/src/obligations/source.ts +47 -57
  59. package/src/obligations/temporal.ts +5 -5
  60. package/src/parallel-worker.ts +10 -30
  61. package/src/parallel.ts +22 -45
  62. package/src/parser.ts +19 -34
  63. package/src/prover/decide-pool.ts +3 -3
  64. package/src/prover/deciders.ts +3 -3
  65. package/src/prover/isabelle/encode.ts +1 -1
  66. package/src/prover/isabelle/isar/inner-syntax.ts +9 -4
  67. package/src/prover/isabelle/isar/method.ts +14 -25
  68. package/src/prover/isabelle/isar/theory.ts +11 -10
  69. package/src/prover/isabelle/isar/type-check.ts +6 -6
  70. package/src/prover/isabelle/provers/blast/blast.ts +7 -63
  71. package/src/prover/isabelle/provers/hypsubst.ts +17 -26
  72. package/src/prover/isabelle/pure/bicompose.ts +9 -25
  73. package/src/prover/isabelle/pure/conv.ts +2 -8
  74. package/src/prover/isabelle/pure/drule.ts +9 -2
  75. package/src/prover/isabelle/pure/logic.ts +1 -1
  76. package/src/prover/isabelle/pure/raw-simplifier.ts +4 -13
  77. package/src/prover/isabelle/pure/rewriter.ts +5 -9
  78. package/src/prover/isabelle/pure/table.ts +2 -1
  79. package/src/prover/isabelle/pure/tactical.ts +42 -35
  80. package/src/prover/isabelle/pure/thm.ts +14 -11
  81. package/src/prover/isabelle/tla/classical-setup.ts +17 -14
  82. package/src/prover/isabelle/tla/context.ts +7 -2
  83. package/src/prover/isabelle/tla/logic.ts +10 -21
  84. package/src/prover/isabelle/tla/simpdata.ts +1 -10
  85. package/src/prover/prep/action.ts +11 -19
  86. package/src/prover/prep/fingerprint.ts +2 -5
  87. package/src/prover/prep/methods.ts +24 -3
  88. package/src/prover/prove.ts +87 -64
  89. package/src/prover/smt/context.ts +1 -2
  90. package/src/prover/smt/data.ts +418 -406
  91. package/src/prover/smt/encode.ts +30 -18
  92. package/src/prover/smt/rewrite.ts +657 -626
  93. package/src/prover/smt/solver/ast.ts +0 -22
  94. package/src/prover/smt/solver/auf-solver.ts +2 -5
  95. package/src/prover/smt/solver/context.ts +3 -3
  96. package/src/prover/smt/solver/e-matching.ts +1 -1
  97. package/src/prover/smt/solver/expr-safe-replace.ts +1 -1
  98. package/src/prover/smt/solver/internalizer.ts +1 -2
  99. package/src/prover/smt/solver/lp/dioph-eq.ts +1 -8
  100. package/src/prover/smt/solver/lp/hnf-cutter.ts +1 -1
  101. package/src/prover/smt/solver/lp/nla-core.ts +2 -6
  102. package/src/prover/smt/solver/mam-compiler.ts +4 -2
  103. package/src/prover/smt/solver/model-checker.ts +1 -1
  104. package/src/prover/smt/solver/model-finder.ts +12 -17
  105. package/src/prover/smt/solver/model-macro-solver.ts +11 -19
  106. package/src/prover/smt/solver/nlsat/algebraic.ts +9 -9
  107. package/src/prover/smt/solver/nlsat/atoms.ts +20 -4
  108. package/src/prover/smt/solver/nlsat/explain.ts +7 -22
  109. package/src/prover/smt/solver/nlsat/levelwise.ts +1 -6
  110. package/src/prover/smt/solver/nlsat/polynomial.ts +12 -3
  111. package/src/prover/smt/solver/nlsat/solver.ts +12 -24
  112. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +1 -1
  113. package/src/prover/smt/solver/proto-model.ts +0 -4
  114. package/src/prover/smt/solver/quantifier-analyzer.ts +10 -10
  115. package/src/prover/smt/solver/quantifier-manager.ts +1 -5
  116. package/src/prover/smt/solver/smtlib-parser.ts +78 -94
  117. package/src/prover/smt/solver/theory-lra-bounds.ts +1 -2
  118. package/src/prover/smt/solver/theory-lra-internalize.ts +5 -16
  119. package/src/prover/tlapm/cache.ts +28 -18
  120. package/src/prover/tlapm/tlapm.ts +15 -9
  121. package/src/prover/verdict.ts +7 -0
  122. package/src/prover/zenon/check/check.ts +1 -2
  123. package/src/prover/zenon/check/records.ts +1 -1
  124. package/src/prover/zenon/check/relations.ts +2 -1
  125. package/src/prover/zenon/check/rewrites.ts +2 -15
  126. package/src/prover/zenon/check/sets.ts +40 -58
  127. package/src/prover/zenon/check/terms.ts +1 -2
  128. package/src/prover/zenon/eqrel.ts +2 -0
  129. package/src/prover/zenon/expr.ts +7 -0
  130. package/src/prover/zenon/index-table.ts +9 -19
  131. package/src/prover/zenon/isar.ts +35 -35
  132. package/src/prover/zenon/llproof.ts +2 -11
  133. package/src/prover/zenon/mltoll.ts +12 -28
  134. package/src/prover/zenon/parse.ts +3 -6
  135. package/src/prover/zenon/search.ts +4 -14
  136. package/src/prover/zenon/tla/functions.ts +2 -2
  137. package/src/prover/zenon/tla/llproof.ts +9 -11
  138. package/src/prover/zenon/tla/records.ts +1 -6
  139. package/src/prover/zenon/tla/sets.ts +15 -14
  140. package/src/prover/zenon/tla/tla.ts +7 -6
  141. package/src/resolve.ts +55 -72
  142. package/src/sany/generation.ts +394 -0
  143. package/src/sany/generator-def-entries.ts +210 -0
  144. package/src/sany/generator-definitions.ts +686 -0
  145. package/src/sany/generator-expressions.ts +1100 -0
  146. package/src/sany/generator-proofs.ts +662 -0
  147. package/src/sany/generator.ts +155 -2625
  148. package/src/sany/lexer.ts +17 -16
  149. package/src/sany/nodes.ts +6 -13
  150. package/src/sany/report.ts +3 -6
  151. package/src/sany/selectors.ts +35 -38
  152. package/src/sany/xml.ts +23 -55
  153. package/src/search.ts +65 -27
  154. package/src/simulate.ts +157 -133
  155. package/src/spec-description.ts +33 -48
  156. package/src/standard-modules.ts +16 -32
  157. package/src/state-graph.ts +2 -7
  158. package/src/substitution-levels.ts +5 -4
  159. package/src/successors.ts +5 -7
  160. package/src/tlc/messages.ts +20 -15
  161. package/src/tlc/order.ts +2 -9
  162. package/src/tlc/random.ts +4 -4
  163. package/src/tlc/replay.ts +8 -15
  164. package/src/tlc/tlc-operators.ts +2 -3
  165. package/src/tlc/trace-spec.ts +25 -45
  166. package/src/typescript/actions.ts +2 -4
  167. package/src/typescript/collections.ts +34 -20
  168. package/src/typescript/compile.ts +1 -3
  169. package/src/typescript/formula.ts +5 -3
  170. package/src/typescript/model.ts +4 -5
  171. package/src/typescript/steps.ts +20 -18
  172. package/src/values.ts +63 -158
@@ -0,0 +1,686 @@
1
+ import { TEMPORAL_LEVEL } from "../levels";
2
+ import type {
3
+ Declaration,
4
+ FunctionDefinition,
5
+ Instance,
6
+ OperatorDefinition,
7
+ SourceLocation,
8
+ } from "../ast";
9
+ import { createLevelFields } from "./builtins";
10
+ import {
11
+ CONSTANT_DECL_KIND,
12
+ type Context,
13
+ createContext,
14
+ type ExprNode,
15
+ type ExprOrOpArgNode,
16
+ formatSanyLocation,
17
+ getContextSymbol,
18
+ getHashtableValues,
19
+ getSymbolArity,
20
+ type InstanceNode,
21
+ isAbsent,
22
+ type LevelNode,
23
+ type ModuleNode,
24
+ type OpDeclNode,
25
+ type OpDefNode,
26
+ type SanyLocation,
27
+ type Subst,
28
+ type SubstInNode,
29
+ type SymbolNode,
30
+ type ThmOrAssumpDefNode,
31
+ VARIABLE_DECL_KIND,
32
+ } from "./nodes";
33
+ import {
34
+ findToken,
35
+ getExpressionSpan,
36
+ getMatchingIndex,
37
+ getPreComments,
38
+ getSpanLocation,
39
+ getTokenIndex,
40
+ getTokenLocation,
41
+ getTokenSource,
42
+ isToken,
43
+ type SourceFile,
44
+ type TokenSpan,
45
+ } from "./source";
46
+ import {
47
+ addSymbol,
48
+ applyBuiltin,
49
+ createFormalParam,
50
+ createOpAppl,
51
+ createOpArg,
52
+ createOpDef,
53
+ getLocation,
54
+ getModule,
55
+ getUnitLocation,
56
+ getUnitSpan,
57
+ isParameterFree,
58
+ matchArguments,
59
+ type ModuleGeneration,
60
+ popLabels,
61
+ pushLabelScope,
62
+ resolveSymbol,
63
+ resolveSynonym,
64
+ setRecursionFields,
65
+ withContext,
66
+ } from "./generation";
67
+ import {
68
+ findNameOrKeyword,
69
+ generateBounds,
70
+ generateExpression,
71
+ generateOperatorArgument,
72
+ generateWithParams,
73
+ } from "./generator-expressions";
74
+
75
+ const getParams = (
76
+ generation: ModuleGeneration,
77
+ definition: OperatorDefinition | Instance,
78
+ span: TokenSpan,
79
+ isAdded: boolean,
80
+ ) => {
81
+ let cursor = span.start;
82
+ return definition.params.map((param) => {
83
+ const index = param.location
84
+ ? getTokenIndex(generation.file, param.location)
85
+ : findNameOrKeyword(generation.file, cursor, param.name);
86
+ const paramSpan = getOperatorSpan(generation.file, index, param.arity);
87
+ cursor = paramSpan.end + 1;
88
+ const isPrefix = param.arity === 1 && isToken(generation.file, index + 1, "_");
89
+ return createFormalParam(
90
+ generation,
91
+ isPrefix
92
+ ? (generation.file.tokens[index].spelling ?? param.name)
93
+ : resolveSynonym(param.name),
94
+ param.arity,
95
+ getSpanLocation(generation.file, paramSpan),
96
+ isAdded,
97
+ );
98
+ });
99
+ };
100
+
101
+ export const getDefinitionSpan = (
102
+ file: SourceFile,
103
+ definition: { location: SourceLocation; isLocal?: boolean },
104
+ ) => {
105
+ const span = getUnitSpan(file, definition.location);
106
+ return definition.isLocal &&
107
+ !isToken(file, span.start, "LOCAL") &&
108
+ isToken(file, span.start - 1, "LOCAL")
109
+ ? { start: span.start - 1, end: span.end }
110
+ : span;
111
+ };
112
+
113
+ export const processOperator = (
114
+ generation: ModuleGeneration,
115
+ definition: OperatorDefinition,
116
+ definitions: (OpDefNode | ThmOrAssumpDefNode)[] | undefined,
117
+ ) => {
118
+ const span = getDefinitionSpan(generation.file, definition);
119
+ const location = getSpanLocation(generation.file, span);
120
+ const name = resolveSynonym(definition.name);
121
+ const paramsSpan = { start: definition.isLocal ? span.start + 1 : span.start, end: span.end };
122
+ const generated = withContext(generation, createContext(), () => {
123
+ const params = getParams(generation, definition, paramsSpan, true);
124
+ const existing = resolveSymbol(generation.contexts, name);
125
+ if (existing?.kind === "OpDef" && existing.inRecursive && !existing.isDefined) {
126
+ const isMatching =
127
+ existing.params?.length === params.length && params.every((param) => param.arity === 0);
128
+ if (existing.letInLevel !== generation.curLevel) {
129
+ generation.addError(location, `Recursive operator ${name} defined at wrong LET/IN level.`);
130
+ } else {
131
+ if (!isMatching) {
132
+ generation.addError(
133
+ location,
134
+ `Definition of ${existing.name} has different arity than its RECURSIVE declaration.`,
135
+ );
136
+ }
137
+ existing.params = params;
138
+ }
139
+ } else if (existing !== undefined) {
140
+ generation.addError(location, `Operator ${name} already defined or declared.`);
141
+ }
142
+ pushLabelScope(generation);
143
+ return { params, body: generateExpression(generation, definition.body), existing };
144
+ });
145
+ const labels = popLabels(generation);
146
+ const existing = generated.existing;
147
+ const params = generated.params;
148
+ const preComments = getPreComments(generation.file, span.start);
149
+ if (
150
+ existing?.kind === "OpDef" &&
151
+ existing.inRecursive &&
152
+ !existing.isDefined &&
153
+ existing.letInLevel === generation.curLevel
154
+ ) {
155
+ existing.weights = params.map(() => 0);
156
+ existing.maxLevels = params.map(() => TEMPORAL_LEVEL);
157
+ existing.isLeibnizArg = params.map(() => true);
158
+ existing.labels = labels;
159
+ endOpDefNode(generation, existing, generated.body, location, preComments);
160
+ generation.currentModule.definitions.push(existing);
161
+ definitions?.push(existing);
162
+ return;
163
+ }
164
+ const node = createOpDef(generation, {
165
+ name,
166
+ params,
167
+ body: generated.body,
168
+ isLocal: definition.isLocal,
169
+ location,
170
+ preComments,
171
+ labels,
172
+ });
173
+ addSymbol(generation, node);
174
+ setRecursionFields(generation, node);
175
+ generation.currentModule.definitions.push(node);
176
+ definitions?.push(node);
177
+ };
178
+
179
+ const endOpDefNode = (
180
+ generation: ModuleGeneration,
181
+ node: OpDefNode,
182
+ body: ExprNode,
183
+ location: SanyLocation,
184
+ preComments: string[],
185
+ ) => {
186
+ node.isDefined = true;
187
+ node.body = body;
188
+ node.location = location;
189
+ node.preComments = preComments;
190
+ if (node.inRecursive) {
191
+ generation.unresolvedCount[generation.curLevel]--;
192
+ generation.unresolvedSum--;
193
+ }
194
+ };
195
+
196
+ export const processFunction = (
197
+ generation: ModuleGeneration,
198
+ definition: FunctionDefinition,
199
+ definitions: (OpDefNode | ThmOrAssumpDefNode)[] | undefined,
200
+ ) => {
201
+ const span = getDefinitionSpan(generation.file, definition);
202
+ const location = getSpanLocation(generation.file, span);
203
+ const context = createContext();
204
+ const nameIndex = definition.isLocal ? span.start + 1 : span.start;
205
+ const bounds = withContext(generation, context, () =>
206
+ generateBounds(generation, definition.bounds, nameIndex + 1),
207
+ );
208
+ const existing = withContext(generation, context, () =>
209
+ resolveSymbol(generation.contexts, definition.name),
210
+ );
211
+ const recursionParam = withContext(generation, context, () =>
212
+ createFormalParam(generation, definition.name, 0, location, existing === undefined),
213
+ );
214
+ const node = applyBuiltin(generation, "$NonRecursiveFcnSpec", [], location, {
215
+ unbounded: [recursionParam],
216
+ ...bounds,
217
+ });
218
+ const isPendingRecursive =
219
+ existing?.kind === "OpDef" && existing.inRecursive && !existing.isDefined;
220
+ const isRecursive = isPendingRecursive && existing.letInLevel === generation.curLevel;
221
+ if (isRecursive) {
222
+ if (existing.arity !== 0) {
223
+ generation.addError(
224
+ location,
225
+ `Function ${existing.name} has operator arguments in its RECURSIVE declaration.`,
226
+ );
227
+ }
228
+ } else if (isPendingRecursive) {
229
+ generation.addError(
230
+ location,
231
+ `Recursive function ${definition.name} defined at wrong LET/IN level.`,
232
+ );
233
+ } else if (existing !== undefined) {
234
+ generation.addError(
235
+ location,
236
+ `Function name \`${definition.name}' already defined or declared.`,
237
+ );
238
+ }
239
+ const preComments = getPreComments(generation.file, span.start);
240
+ const definitionNode =
241
+ existing === undefined
242
+ ? createOpDef(generation, {
243
+ name: definition.name,
244
+ params: [],
245
+ body: node,
246
+ isLocal: definition.isLocal,
247
+ location,
248
+ preComments,
249
+ })
250
+ : existing.kind === "OpDef" && (isRecursive || !isPendingRecursive)
251
+ ? existing
252
+ : undefined;
253
+ if (isRecursive) {
254
+ if (existing.arity === 0) endOpDefNode(generation, existing, node, location, preComments);
255
+ } else if (existing === undefined && definitionNode !== undefined) {
256
+ addSymbol(generation, definitionNode);
257
+ setRecursionFields(generation, definitionNode);
258
+ }
259
+ if (definitionNode !== undefined) {
260
+ generation.currentModule.definitions.push(definitionNode);
261
+ definitions?.push(definitionNode);
262
+ }
263
+ generation.functions.unshift({ name: definition.name, node });
264
+ pushLabelScope(generation);
265
+ const generateBody = () => generateWithParams(generation, bounds.bounded.flat(), definition.body);
266
+ const body =
267
+ definitionNode === undefined ? generateBody() : withContext(generation, context, generateBody);
268
+ const labels = popLabels(generation);
269
+ if (definitionNode !== undefined) definitionNode.labels = labels;
270
+ generation.functions.shift();
271
+ node.operands = [body];
272
+ if (node.operator.name === "$NonRecursiveFcnSpec") node.unbounded = undefined;
273
+ };
274
+
275
+ export const processRecursive = (generation: ModuleGeneration, declarations: Declaration[]) => {
276
+ if (generation.unresolvedSum === 0) generation.recursiveSectionCount++;
277
+ generation.unresolvedCount[generation.curLevel] += declarations.length;
278
+ generation.unresolvedSum += declarations.length;
279
+ declarations.forEach((declaration) => {
280
+ const span = getDeclarationSpan(generation.file, declaration);
281
+ // The OpDeclNode buildParameter makes of the declaration to read its name and arity.
282
+ generation.getId();
283
+ const params = Array.from({ length: declaration.arity }, () =>
284
+ createFormalParam(generation, "", 0, undefined, false),
285
+ );
286
+ const node = createOpDef(generation, {
287
+ name: resolveSynonym(declaration.name),
288
+ params,
289
+ location: getSpanLocation(generation.file, span),
290
+ isDefined: false,
291
+ inRecursive: true,
292
+ inRecursiveSection: true,
293
+ recursiveSection: generation.recursiveSectionCount,
294
+ letInLevel: generation.curLevel,
295
+ });
296
+ addSymbol(generation, node);
297
+ generation.recursiveDeclarations.push(node);
298
+ generation.currentModule.opDefsInRecursiveSection.push(node);
299
+ });
300
+ };
301
+
302
+ export const checkForUndefinedRecursiveOps = (generation: ModuleGeneration) => {
303
+ if (generation.unresolvedCount[generation.curLevel] === 0) return;
304
+ generation.recursiveDeclarations
305
+ .filter((node) => node.letInLevel === generation.curLevel && !node.isDefined)
306
+ .forEach((node) =>
307
+ generation.addError(
308
+ node.location,
309
+ `Symbol ${node.name} declared in RECURSIVE statement but not defined.`,
310
+ ),
311
+ );
312
+ generation.unresolvedSum -= generation.unresolvedCount[generation.curLevel];
313
+ };
314
+
315
+ const processSubstitutions = (
316
+ generation: ModuleGeneration,
317
+ instance: Instance,
318
+ instanceeContext: Context,
319
+ location: SanyLocation,
320
+ ) => {
321
+ // The SubstInNode processSubst creates, which only the substitutions' templates use.
322
+ generation.getId();
323
+ const declarations = getHashtableValues(instanceeContext.table).filter(
324
+ (symbol): symbol is OpDeclNode => symbol.kind === "OpDecl",
325
+ );
326
+ const substs: Subst[] = declarations.flatMap((declaration) => {
327
+ const symbol = resolveSymbol(generation.contexts, declaration.name);
328
+ if (symbol === undefined) return [];
329
+ const isExpression =
330
+ declaration.declKind === VARIABLE_DECL_KIND ||
331
+ (declaration.declKind === CONSTANT_DECL_KIND && declaration.arity === 0);
332
+ if (isExpression) matchArguments(generation, symbol, [], location);
333
+ return [
334
+ {
335
+ op: declaration,
336
+ expr: isExpression
337
+ ? createOpAppl(generation, symbol, [], location)
338
+ : createOpArg(generation, symbol, location),
339
+ isImplicit: true,
340
+ },
341
+ ];
342
+ });
343
+ const checkArity = (target: OpDeclNode, substitute: ExprOrOpArgNode) => {
344
+ const arity = substitute.kind === "OpArg" ? getSymbolArity(substitute.op) : 0;
345
+ if (arity !== target.arity) {
346
+ generation.addError(
347
+ substitute.location,
348
+ `An operator must be substituted for symbol '${target.name}', and it must have arity ${target.arity}.`,
349
+ );
350
+ }
351
+ };
352
+ const span = getDefinitionSpan(generation.file, instance);
353
+ let cursor = findToken(generation.file, span.start, span.end, "WITH") + 1;
354
+ instance.substitutions.forEach((substitution) => {
355
+ const targetIndex = findToken(generation.file, cursor, span.end, substitution.name);
356
+ if (targetIndex !== -1) {
357
+ cursor = getExpressionSpan(generation.file, substitution.expression).end + 1;
358
+ }
359
+ const target = getContextSymbol(instanceeContext, resolveSynonym(substitution.name));
360
+ if (target?.kind !== "OpDecl") {
361
+ generation.addError(
362
+ targetIndex === -1 ? location : getTokenLocation(generation.file, targetIndex),
363
+ `Identifier '${targetIndex === -1 ? substitution.name : getTokenSource(generation.file, targetIndex)}' is not a legal target of a substitution. \nA legal target must be a declared CONSTANT or VARIABLE in the module being instantiated. \n(Also, check for warnings about multiple declarations of this same identifier.)`,
364
+ );
365
+ return;
366
+ }
367
+ const substitute =
368
+ target.arity === 0
369
+ ? generateExpression(generation, substitution.expression)
370
+ : generateOperatorArgument(generation, substitution.expression, target);
371
+ checkArity(target, substitute);
372
+ const existing = substs.find((subst) => subst.op.name === target.name);
373
+ if (existing && !existing.isImplicit) {
374
+ generation.addError(
375
+ getLocation(generation.file, substitution.expression),
376
+ `Multiple substitutions for symbol '${target.name}' in substitution.`,
377
+ );
378
+ } else if (existing) {
379
+ existing.expr = substitute;
380
+ existing.isImplicit = false;
381
+ } else substs.push({ op: target, expr: substitute, isImplicit: false });
382
+ });
383
+ substs
384
+ .filter((subst) => subst.isImplicit && generation.version !== "1.7.4")
385
+ .forEach((subst) => checkArity(subst.op, subst.expr));
386
+ declarations
387
+ .filter((declaration) => !substs.some((subst) => subst.op.name === declaration.name))
388
+ .forEach((declaration) =>
389
+ generation.addError(
390
+ location,
391
+ `Substitution missing for symbol ${declaration.name} declared at ${formatSanyLocation(declaration.location)} \nand instantiated in module ${generation.currentModule.name}.`,
392
+ ),
393
+ );
394
+ return substs;
395
+ };
396
+
397
+ export const createSubstIn = (
398
+ generation: ModuleGeneration,
399
+ kind: "SubstIn" | "APSubstIn",
400
+ substs: Subst[],
401
+ body: LevelNode,
402
+ instantiatedModule: ModuleNode,
403
+ location: SanyLocation,
404
+ instantiatingModule = generation.currentModule,
405
+ ): SubstInNode => {
406
+ if (isAbsent(body)) {
407
+ generation.addError(
408
+ location,
409
+ kind === "SubstIn"
410
+ ? "Substitution error, probably due to error \nin module being instantiated."
411
+ : "Substitution error, probably due to error in module being instantiated.",
412
+ );
413
+ }
414
+ return {
415
+ ...createLevelFields(generation.getId()),
416
+ kind,
417
+ substs,
418
+ body,
419
+ instantiatingModule,
420
+ instantiatedModule,
421
+ location,
422
+ };
423
+ };
424
+
425
+ export const processModuleDefinition = (
426
+ generation: ModuleGeneration,
427
+ instance: Instance,
428
+ definitions: (OpDefNode | ThmOrAssumpDefNode)[] | undefined,
429
+ instances: InstanceNode[] | undefined,
430
+ ) => {
431
+ const span = getDefinitionSpan(generation.file, instance);
432
+ const location = getSpanLocation(generation.file, span);
433
+ const preComments = getPreComments(generation.file, span.start);
434
+ const name = instance.name ?? "";
435
+ const parameterContext = createContext();
436
+ const nameIndex = instance.isLocal ? span.start + 1 : span.start;
437
+ if (instance.params.length > 0) generation.contexts.push(parameterContext);
438
+ const args = getParams(
439
+ generation,
440
+ instance,
441
+ { start: nameIndex, end: span.end },
442
+ instance.params.length > 0,
443
+ );
444
+ const instanceeModule = getModule(generation, instance.module);
445
+ const instanceeContext = instanceeModule.context;
446
+ const substs = processSubstitutions(generation, instance, instanceeContext, location);
447
+ if (instance.params.length > 0) generation.contexts.pop();
448
+ getHashtableValues(instanceeContext.table).forEach((symbol) => {
449
+ if (symbol.kind !== "OpDef" || symbol.isLocal) return;
450
+ if (symbol.defKind !== "UserDefined" && symbol.defKind !== "ModuleInstance") return;
451
+ const params = [...args, ...(symbol.params ?? [])];
452
+ const qualifiedName = `${name}!${symbol.name}`;
453
+ const node =
454
+ symbol.defKind === "UserDefined"
455
+ ? createOpDef(generation, {
456
+ name: qualifiedName,
457
+ params,
458
+ body:
459
+ substs.length > 0 && symbol.body
460
+ ? createSubstIn(
461
+ generation,
462
+ "SubstIn",
463
+ substs,
464
+ symbol.body,
465
+ instanceeModule,
466
+ location,
467
+ )
468
+ : symbol.body,
469
+ isLocal: instance.isLocal,
470
+ location,
471
+ source: symbol.source ?? symbol,
472
+ preComments,
473
+ labels: symbol.labels,
474
+ })
475
+ : createOpDef(generation, {
476
+ defKind: "ModuleInstance",
477
+ name: qualifiedName,
478
+ params,
479
+ isLocal: instance.isLocal,
480
+ location,
481
+ module: symbol.module,
482
+ source: symbol.source ?? symbol,
483
+ preComments,
484
+ });
485
+ addSymbol(generation, node);
486
+ if (symbol.defKind === "UserDefined") setRecursionFields(generation, node);
487
+ (definitions ?? generation.currentModule.definitions).push(node);
488
+ });
489
+ getHashtableValues(instanceeContext.table).forEach((symbol) => {
490
+ if (symbol.kind !== "ThmOrAssumpDef" || symbol.isLocal) return;
491
+ // SANY creates the APSubstInNode before the ThmOrAssumpDefNode that holds it.
492
+ const body =
493
+ substs.length > 0
494
+ ? createSubstIn(generation, "APSubstIn", substs, symbol.body, instanceeModule, location)
495
+ : symbol.body;
496
+ const node: ThmOrAssumpDefNode = {
497
+ ...createLevelFields(generation.getId()),
498
+ kind: "ThmOrAssumpDef",
499
+ name: `${name}!${symbol.name}`,
500
+ isTheorem: symbol.isTheorem,
501
+ body,
502
+ params: [...args, ...symbol.params],
503
+ isLocal: instance.isLocal,
504
+ location,
505
+ module: generation.currentModule,
506
+ source: symbol.source ?? symbol,
507
+ labels: symbol.labels,
508
+ isLeibnizArg: [],
509
+ isLeibniz: false,
510
+ opLevelCond: [],
511
+ maxLevels: [],
512
+ minMaxLevel: [],
513
+ };
514
+ addSymbol(generation, node);
515
+ (definitions ?? generation.currentModule.definitions).push(node);
516
+ });
517
+ const instanceNode: InstanceNode = {
518
+ ...createLevelFields(generation.getId()),
519
+ kind: "Instance",
520
+ name,
521
+ isLocal: instance.isLocal,
522
+ params: args,
523
+ module: instanceeModule,
524
+ substs,
525
+ location,
526
+ };
527
+ (instances ?? generation.currentModule.topLevel).push(instanceNode);
528
+ const moduleDefinition = createOpDef(generation, {
529
+ defKind: "ModuleInstance",
530
+ name,
531
+ params: args,
532
+ isLocal: instance.isLocal,
533
+ location,
534
+ preComments,
535
+ });
536
+ addSymbol(generation, moduleDefinition);
537
+ if (generation.version !== "1.7.4") definitions?.push(moduleDefinition);
538
+ };
539
+
540
+ const reuseSymbol = <Node extends SymbolNode>(generation: ModuleGeneration, symbol: Node) => {
541
+ addSymbol(generation, symbol);
542
+ return symbol;
543
+ };
544
+
545
+ export const generateInstance = (
546
+ generation: ModuleGeneration,
547
+ instance: Instance,
548
+ isTopLevel = true,
549
+ stepLocation?: SanyLocation,
550
+ ) => {
551
+ const span = getDefinitionSpan(generation.file, instance);
552
+ const location = stepLocation ?? getSpanLocation(generation.file, span);
553
+ const preComments = getPreComments(generation.file, span.start);
554
+ const instanceeModule = getModule(generation, instance.module);
555
+ const instanceeContext = instanceeModule.context;
556
+ const substs = processSubstitutions(generation, instance, instanceeContext, location);
557
+ const isLocal = instance.isLocal;
558
+ const isInstanceeParameterFree = isParameterFree(instanceeModule);
559
+ getHashtableValues(instanceeContext.table).forEach((symbol) => {
560
+ if (symbol.kind !== "OpDef" || symbol.defKind !== "UserDefined" || symbol.isLocal) return;
561
+ const copyFrom = (module: ModuleNode | undefined, body: ExprNode | undefined) => {
562
+ const node = createOpDef(generation, {
563
+ name: symbol.name,
564
+ params: symbol.params,
565
+ body,
566
+ isLocal,
567
+ location,
568
+ module,
569
+ source: symbol.source ?? symbol,
570
+ preComments,
571
+ labels: symbol.labels,
572
+ });
573
+ addSymbol(generation, node);
574
+ return node;
575
+ };
576
+ const isOriginParameterFree = symbol.module === undefined || isParameterFree(symbol.module);
577
+ const node =
578
+ isInstanceeParameterFree || isOriginParameterFree
579
+ ? isLocal
580
+ ? copyFrom(symbol.module, symbol.body)
581
+ : reuseSymbol(generation, symbol)
582
+ : copyFrom(
583
+ generation.currentModule,
584
+ symbol.body &&
585
+ createSubstIn(generation, "SubstIn", substs, symbol.body, instanceeModule, location),
586
+ );
587
+ generation.currentModule.definitions.push(node);
588
+ setRecursionFields(generation, node);
589
+ });
590
+ getHashtableValues(instanceeContext.table).forEach((symbol) => {
591
+ if (symbol.kind !== "ThmOrAssumpDef" || symbol.isLocal) return;
592
+ const copyFrom = (module: ModuleNode, body: LevelNode) => {
593
+ const node: ThmOrAssumpDefNode = {
594
+ ...symbol,
595
+ ...createLevelFields(generation.getId()),
596
+ body,
597
+ isLocal,
598
+ location,
599
+ module,
600
+ source: symbol.source ?? symbol,
601
+ };
602
+ addSymbol(generation, node);
603
+ return node;
604
+ };
605
+ const node = !isInstanceeParameterFree
606
+ ? isParameterFree(symbol.module)
607
+ ? isLocal
608
+ ? copyFrom(generation.currentModule, symbol.body)
609
+ : symbol
610
+ : copyFrom(
611
+ generation.currentModule,
612
+ createSubstIn(generation, "APSubstIn", substs, symbol.body, instanceeModule, location),
613
+ )
614
+ : isLocal
615
+ ? copyFrom(symbol.module, symbol.body)
616
+ : reuseSymbol(generation, symbol);
617
+ if (isTopLevel) generation.currentModule.definitions.push(node);
618
+ });
619
+ const instanceNode: InstanceNode = {
620
+ ...createLevelFields(generation.getId()),
621
+ kind: "Instance",
622
+ name: undefined,
623
+ isLocal,
624
+ params: [],
625
+ module: instanceeModule,
626
+ substs,
627
+ location,
628
+ };
629
+ if (isTopLevel) generation.currentModule.topLevel.push(instanceNode);
630
+ return instanceNode;
631
+ };
632
+
633
+ export const getOperatorSpan = (file: SourceFile, start: number, arity: number) => {
634
+ if (arity === 0) return { start, end: start };
635
+ if (isToken(file, start, "_")) {
636
+ return { start, end: isToken(file, start + 2, "_") ? start + 2 : start + 1 };
637
+ }
638
+ if (isToken(file, start + 1, "(")) return { start, end: getMatchingIndex(file, start + 1) };
639
+ return { start, end: isToken(file, start + 1, "_") ? start + 1 : start };
640
+ };
641
+
642
+ const getDeclarationSpan = (file: SourceFile, declaration: Declaration) =>
643
+ getOperatorSpan(file, getUnitSpan(file, declaration.location).start, declaration.arity);
644
+
645
+ export const createDeclaration = (
646
+ generation: ModuleGeneration,
647
+ declaration: Declaration,
648
+ declKind: number,
649
+ ): OpDeclNode => {
650
+ const span = getDeclarationSpan(generation.file, declaration);
651
+ if (declaration.name === "@" && declKind === VARIABLE_DECL_KIND) {
652
+ generation.addError(
653
+ getSpanLocation(generation.file, span),
654
+ "Attempted to declare '@' as a variable.",
655
+ );
656
+ }
657
+ const node: OpDeclNode = {
658
+ ...createLevelFields(generation.getId()),
659
+ levelChecked: 1,
660
+ level: declKind === VARIABLE_DECL_KIND ? 1 : 0,
661
+ kind: "OpDecl",
662
+ name: resolveSynonym(declaration.name),
663
+ arity: declaration.arity,
664
+ declKind,
665
+ location: getSpanLocation(generation.file, span),
666
+ module: generation.currentModule,
667
+ };
668
+ if (declKind === CONSTANT_DECL_KIND) {
669
+ node.levelParams.add(node);
670
+ node.allParams.add(node);
671
+ }
672
+ addSymbol(generation, node);
673
+ return node;
674
+ };
675
+
676
+ export const checkRecursiveSection = (
677
+ generation: ModuleGeneration,
678
+ location: SourceLocation,
679
+ type: string,
680
+ ) => {
681
+ if (generation.unresolvedSum === 0) return;
682
+ generation.addError(
683
+ getUnitLocation(generation.file, location),
684
+ `${type} may not appear within a recursive definition section.`,
685
+ );
686
+ };