tla-ts 0.0.10-dev.8aec06f77 → 0.0.10-dev.94c3dd828

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 (196) hide show
  1. package/dist/deciders.cjs +37 -36
  2. package/dist/deciders.js +55 -54
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +3 -0
  5. package/dist/index.d.ts +3 -0
  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.cjs +146 -58
  10. package/dist/prove.js +142 -54
  11. package/dist/run.cjs +45 -43
  12. package/dist/run.js +47 -45
  13. package/dist/transfer.cjs +39 -36
  14. package/dist/transfer.js +23 -20
  15. package/dist/worker.cjs +1 -1
  16. package/dist/worker.js +1 -1
  17. package/package.json +1 -1
  18. package/src/ast.ts +3 -3
  19. package/src/check.ts +203 -33
  20. package/src/cli/tlapm.ts +261 -68
  21. package/src/dependencies.ts +23 -2
  22. package/src/errors.ts +1 -1
  23. package/src/exit-codes.ts +1 -0
  24. package/src/liveness-checker.ts +530 -201
  25. package/src/liveness.ts +47 -32
  26. package/src/obligations/anonymize.ts +2 -4
  27. package/src/obligations/index.ts +5 -3
  28. package/src/obligations/pragma.ts +2 -2
  29. package/src/parallel.ts +2 -2
  30. package/src/parser.ts +151 -42
  31. package/src/prover/deciders.ts +1 -8
  32. package/src/prover/isabelle/isar/attrib.ts +86 -45
  33. package/src/prover/isabelle/isar/context.ts +25 -22
  34. package/src/prover/isabelle/isar/induct.ts +2 -5
  35. package/src/prover/isabelle/isar/method.ts +5 -7
  36. package/src/prover/isabelle/isar/proof.ts +33 -16
  37. package/src/prover/isabelle/isar/rule-cases.ts +6 -14
  38. package/src/prover/isabelle/isar/theory.ts +16 -17
  39. package/src/prover/isabelle/isar/toplevel.ts +46 -52
  40. package/src/prover/isabelle/provers/classical.ts +1 -1
  41. package/src/prover/ocaml.ts +4 -1
  42. package/src/prover/prep/action.ts +1 -0
  43. package/src/prover/prep/methods.ts +50 -3
  44. package/src/prover/prep/normalize.ts +4 -1
  45. package/src/prover/prove.ts +58 -32
  46. package/src/prover/ptl/decide.ts +43 -63
  47. package/src/prover/smt/data.ts +51 -45
  48. package/src/prover/smt/encode.ts +1 -2
  49. package/src/prover/smt/rewrite.ts +1 -0
  50. package/src/prover/smt/solver/aig-tactic.ts +25 -15
  51. package/src/prover/smt/solver/arith-rewriter.ts +3 -5
  52. package/src/prover/smt/solver/asserted-formulas.ts +1 -1
  53. package/src/prover/smt/solver/ast-util.ts +3 -1
  54. package/src/prover/smt/solver/ast.ts +110 -152
  55. package/src/prover/smt/solver/bound-manager.ts +39 -28
  56. package/src/prover/smt/solver/bv-bound-chk.ts +2 -8
  57. package/src/prover/smt/solver/bv-rewriter.ts +14 -16
  58. package/src/prover/smt/solver/bv1-blast.ts +1 -9
  59. package/src/prover/smt/solver/cg-table.ts +19 -14
  60. package/src/prover/smt/solver/check-logic.ts +6 -1
  61. package/src/prover/smt/solver/context.ts +20 -10
  62. package/src/prover/smt/solver/demodulator.ts +2 -2
  63. package/src/prover/smt/solver/dependent-expr-state.ts +16 -0
  64. package/src/prover/smt/solver/distribute-forall.ts +1 -10
  65. package/src/prover/smt/solver/dom-simplify.ts +1 -1
  66. package/src/prover/smt/solver/dt2bv-tactic.ts +2 -7
  67. package/src/prover/smt/solver/e-matching.ts +6 -6
  68. package/src/prover/smt/solver/elim-uncnstr.ts +3 -14
  69. package/src/prover/smt/solver/enode.ts +15 -1
  70. package/src/prover/smt/solver/euf/array-internalize.ts +19 -8
  71. package/src/prover/smt/solver/euf/dt-solver.ts +19 -19
  72. package/src/prover/smt/solver/euf/egraph.ts +65 -32
  73. package/src/prover/smt/solver/euf/euf-solver.ts +35 -18
  74. package/src/prover/smt/solver/euf/fpa-solver.ts +37 -51
  75. package/src/prover/smt/solver/euf/mam.ts +6 -48
  76. package/src/prover/smt/solver/euf/q-ematch.ts +21 -94
  77. package/src/prover/smt/solver/euf/q-mbi.ts +4 -2
  78. package/src/prover/smt/solver/euf/q-model-fixer.ts +1 -1
  79. package/src/prover/smt/solver/euf/q-solver.ts +2 -0
  80. package/src/prover/smt/solver/euf/th-solver.ts +1 -1
  81. package/src/prover/smt/solver/factor.ts +1 -11
  82. package/src/prover/smt/solver/fd-solver.ts +1 -2
  83. package/src/prover/smt/solver/fm-tactic.ts +19 -13
  84. package/src/prover/smt/solver/fpa-rewriter.ts +3 -1
  85. package/src/prover/smt/solver/fpa2bv-converter.ts +10 -6
  86. package/src/prover/smt/solver/internalizer.ts +41 -2
  87. package/src/prover/smt/solver/lia2pb.ts +18 -4
  88. package/src/prover/smt/solver/lp/lar-solver.ts +1 -1
  89. package/src/prover/smt/solver/lp/nla-powers.ts +144 -107
  90. package/src/prover/smt/solver/lp/nla-transcendentals.ts +50 -17
  91. package/src/prover/smt/solver/macro-finder.ts +1 -1
  92. package/src/prover/smt/solver/mam-compiler.ts +13 -13
  93. package/src/prover/smt/solver/max-bv-sharing-tactic.ts +1 -11
  94. package/src/prover/smt/solver/maxcore.ts +4 -12
  95. package/src/prover/smt/solver/maxlex.ts +0 -7
  96. package/src/prover/smt/solver/maxsmt-base.ts +7 -0
  97. package/src/prover/smt/solver/mbp/mbp-arith.ts +2 -11
  98. package/src/prover/smt/solver/mbp/mbp-plugin.ts +9 -0
  99. package/src/prover/smt/solver/mbp/mbp-solve-plugin.ts +1 -9
  100. package/src/prover/smt/solver/model-evaluator.ts +9 -5
  101. package/src/prover/smt/solver/model-macro-solver.ts +3 -3
  102. package/src/prover/smt/solver/muz/dl-context.ts +57 -3
  103. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +68 -20
  104. package/src/prover/smt/solver/muz/dl-mk-elim-term-ite.ts +7 -1
  105. package/src/prover/smt/solver/muz/dl-mk-rule-inliner.ts +39 -10
  106. package/src/prover/smt/solver/muz/dl-mk-slice.ts +76 -13
  107. package/src/prover/smt/solver/muz/dl-mk-subsumption-checker.ts +9 -2
  108. package/src/prover/smt/solver/muz/dl-rule-transformer.ts +0 -2
  109. package/src/prover/smt/solver/muz/dl-rule.ts +93 -29
  110. package/src/prover/smt/solver/muz/hnf.ts +6 -5
  111. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +178 -0
  112. package/src/prover/smt/solver/muz/horn-tactic.ts +14 -3
  113. package/src/prover/smt/solver/muz/rule-properties.ts +194 -36
  114. package/src/prover/smt/solver/muz/spacer-context.ts +102 -84
  115. package/src/prover/smt/solver/muz/spacer-dl-interface.ts +15 -2
  116. package/src/prover/smt/solver/muz/spacer-pdr.ts +3 -3
  117. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +2 -7
  118. package/src/prover/smt/solver/muz/spacer-util.ts +2 -2
  119. package/src/prover/smt/solver/muz/substitution.ts +88 -37
  120. package/src/prover/smt/solver/nlqsat.ts +2 -2
  121. package/src/prover/smt/solver/nlsat/algebraic.ts +1 -2
  122. package/src/prover/smt/solver/nlsat/explain.ts +5 -0
  123. package/src/prover/smt/solver/nlsat/solver.ts +36 -25
  124. package/src/prover/smt/solver/opt-context.ts +9 -8
  125. package/src/prover/smt/solver/opt-nlsat.ts +68 -58
  126. package/src/prover/smt/solver/opt-solver.ts +16 -7
  127. package/src/prover/smt/solver/optsmt.ts +12 -9
  128. package/src/prover/smt/solver/pattern-inference.ts +2 -2
  129. package/src/prover/smt/solver/pb-rewriter.ts +13 -13
  130. package/src/prover/smt/solver/poly-rewriter.ts +2 -2
  131. package/src/prover/smt/solver/probes.ts +1 -1
  132. package/src/prover/smt/solver/propagate-values.ts +4 -0
  133. package/src/prover/smt/solver/proto-model.ts +5 -5
  134. package/src/prover/smt/solver/purify-arith.ts +50 -15
  135. package/src/prover/smt/solver/qe-arith-plugin.ts +2 -1
  136. package/src/prover/smt/solver/qe-mbp.ts +13 -23
  137. package/src/prover/smt/solver/qe.ts +45 -53
  138. package/src/prover/smt/solver/qsat.ts +70 -90
  139. package/src/prover/smt/solver/quantifier-analyzer.ts +9 -9
  140. package/src/prover/smt/solver/quasi-macros.ts +9 -18
  141. package/src/prover/smt/solver/rational.ts +17 -0
  142. package/src/prover/smt/solver/recfun-decl-plugin.ts +33 -19
  143. package/src/prover/smt/solver/recfun-rewriter.ts +1 -1
  144. package/src/prover/smt/solver/rewriter-tpl.ts +6 -2
  145. package/src/prover/smt/solver/rewriter.ts +1 -1
  146. package/src/prover/smt/solver/sat/asymm-branch.ts +59 -46
  147. package/src/prover/smt/solver/sat/clause-use-list.ts +0 -6
  148. package/src/prover/smt/solver/sat/clause.ts +1 -3
  149. package/src/prover/smt/solver/sat/config.ts +3 -3
  150. package/src/prover/smt/solver/sat/consequences.ts +1 -1
  151. package/src/prover/smt/solver/sat/goal2sat.ts +1 -1
  152. package/src/prover/smt/solver/sat/inc-sat-solver.ts +4 -12
  153. package/src/prover/smt/solver/sat/model-converter.ts +1 -15
  154. package/src/prover/smt/solver/sat/pb-solver.ts +49 -23
  155. package/src/prover/smt/solver/sat/probing.ts +22 -19
  156. package/src/prover/smt/solver/sat/sat2goal.ts +9 -10
  157. package/src/prover/smt/solver/sat/simplifier.ts +15 -56
  158. package/src/prover/smt/solver/sat/solver.ts +20 -19
  159. package/src/prover/smt/solver/sat/watch-list.ts +7 -0
  160. package/src/prover/smt/solver/seq-decl-plugin.ts +7 -7
  161. package/src/prover/smt/solver/seq-derive.ts +6 -7
  162. package/src/prover/smt/solver/seq-eq-solver.ts +7 -7
  163. package/src/prover/smt/solver/seq-range-predicate.ts +14 -1
  164. package/src/prover/smt/solver/seq-re-rewriter.ts +1 -10
  165. package/src/prover/smt/solver/seq-re-util.ts +1 -2
  166. package/src/prover/smt/solver/seq-regex-bisim.ts +1 -1
  167. package/src/prover/smt/solver/seq-regex-live.ts +4 -4
  168. package/src/prover/smt/solver/seq-rewriter.ts +1 -4
  169. package/src/prover/smt/solver/smt-setup.ts +15 -9
  170. package/src/prover/smt/solver/smtlib-parser.ts +1174 -579
  171. package/src/prover/smt/solver/smtlib-script.ts +866 -728
  172. package/src/prover/smt/solver/tactic.ts +66 -14
  173. package/src/prover/smt/solver/theory-array.ts +25 -58
  174. package/src/prover/smt/solver/theory-bv.ts +13 -50
  175. package/src/prover/smt/solver/theory-fpa.ts +46 -78
  176. package/src/prover/smt/solver/theory-pb.ts +10 -6
  177. package/src/prover/smt/solver/theory-recfun.ts +2 -2
  178. package/src/prover/smt/solver/theory-seq-regex.ts +3 -6
  179. package/src/prover/smt/solver/theory-seq-solve.ts +5 -5
  180. package/src/prover/smt/solver/theory-seq-state.ts +6 -3
  181. package/src/prover/smt/solver/theory-seq.ts +32 -54
  182. package/src/prover/smt/solver/theory.ts +16 -1
  183. package/src/prover/smt/solver/tseitin-cnf.ts +3 -3
  184. package/src/prover/smt/solver/var-subst.ts +2 -2
  185. package/src/prover/smt/table.ts +3 -2
  186. package/src/prover/zenon/decide.ts +9 -11
  187. package/src/prover/zenon/node.ts +12 -11
  188. package/src/prover/zenon/tla/sets.ts +1 -1
  189. package/src/search.ts +131 -16
  190. package/src/successors.ts +1 -1
  191. package/src/symmetry.ts +2 -2
  192. package/src/tableau.ts +2 -2
  193. package/src/tlc/fingerprint.ts +81 -9
  194. package/src/tlc/summary.ts +29 -14
  195. package/src/typed-tier.ts +6535 -0
  196. package/src/prover/smt/solver/seq-regex-witness.ts +0 -100
@@ -6,7 +6,7 @@ import {
6
6
  getSymbolHash,
7
7
  FAMILY_ARITH,
8
8
  FAMILY_BASIC,
9
- FAMILY_DATATYPE,
9
+ KIND_APP,
10
10
  KIND_QUANTIFIER,
11
11
  KIND_VAR,
12
12
  OP_ABS,
@@ -23,6 +23,7 @@ import {
23
23
  OP_DISTINCT,
24
24
  OP_DIV,
25
25
  OP_DT_ACCESSOR,
26
+ OP_DT_CONSTRUCTOR,
26
27
  OP_EQ,
27
28
  OP_GE,
28
29
  OP_GT,
@@ -37,6 +38,7 @@ import {
37
38
  OP_MUL,
38
39
  OP_NOT,
39
40
  OP_OR,
41
+ OP_PATTERN,
40
42
  OP_POWER,
41
43
  OP_POWER0,
42
44
  OP_SIN,
@@ -62,8 +64,6 @@ import {
62
64
  OP_TRUE,
63
65
  OP_FALSE,
64
66
  OP_UMINUS,
65
- OP_UNINTERPRETED,
66
- OP_FUN_DEFINED,
67
67
  OP_XOR,
68
68
  SORT_BOOL,
69
69
  SORT_INT,
@@ -100,6 +100,7 @@ import {
100
100
  mkFpaAppOf,
101
101
  } from "./fpa-decl-plugin";
102
102
  import { createLogicChecker } from "./check-logic";
103
+ import { shrink } from "./array";
103
104
  import { ObjMap } from "./hashtable";
104
105
  import {
105
106
  CHAR_OP_NAMES,
@@ -120,6 +121,7 @@ import {
120
121
  isSupportedLogic,
121
122
  } from "./smt-logics";
122
123
  import { setRecFunDefinition } from "./recfun-decl-plugin";
124
+ import { DEFAULT_PRINT_OPTIONS, printExpr } from "./smt2-printer";
123
125
  import { replaceFreeVars, VarSubst } from "./var-subst";
124
126
  import { UpolynomialManager } from "./nlsat/upolynomial";
125
127
 
@@ -147,25 +149,27 @@ export interface SmtList {
147
149
  offset: number;
148
150
  // Z3 reports an error in making an application at its closing parenthesis.
149
151
  end: SmtToken;
152
+ // The token after a root-obj or an indexed or qualified identifier, where Z3 reports an error in
153
+ // making it.
150
154
  follower?: SmtToken;
155
+ // The command that a list a command reader read is part of.
156
+ root?: SmtList;
151
157
  }
152
158
 
153
159
  export type SExpr = SmtToken | SmtList;
154
160
 
155
- interface VarBinding {
156
- kind: "var";
157
- depth: number;
158
- sort: number;
161
+ // smt2parser's local: a term, and the number of binders around it where it was bound.
162
+ interface Local {
163
+ expr: number;
164
+ level: number;
159
165
  }
160
166
 
161
- interface LetBinding {
162
- kind: "let";
163
- depth: number;
167
+ interface ParsedTerm {
164
168
  expr: number;
169
+ isOwned: boolean;
170
+ root: SmtList | undefined;
165
171
  }
166
172
 
167
- type Binding = VarBinding | LetBinding;
168
-
169
173
  interface Macro {
170
174
  domain: number[];
171
175
  range: number;
@@ -214,15 +218,103 @@ interface SmtProblem {
214
218
  rlimit: number;
215
219
  }
216
220
 
217
- interface ApplicationFrame {
221
+ interface QualifiedHead {
218
222
  head: SmtToken;
219
223
  indices: number[];
220
224
  build?: (args: number[]) => number;
225
+ }
226
+
227
+ interface ApplicationFrame extends QualifiedHead {
228
+ kind: "application";
229
+ list: SmtList;
230
+ isTail: boolean;
231
+ start: number;
232
+ next: number;
233
+ }
234
+
235
+ // An application whose head is a term, which selects from the array it stands for.
236
+ interface SelectionFrame {
237
+ kind: "selection";
238
+ list: SmtList;
239
+ isTail: boolean;
240
+ start: number;
241
+ next: number;
242
+ }
243
+
244
+ interface LetFrame {
245
+ kind: "let";
246
+ list: SmtList;
247
+ bindings: SmtList;
248
+ names: string[];
249
+ isInDecls: boolean;
250
+ isTail: boolean;
251
+ start: number;
252
+ next: number;
253
+ }
254
+
255
+ interface LetDeclFrame {
256
+ kind: "let-decl";
257
+ list: SmtList;
258
+ next: number;
259
+ }
260
+
261
+ interface QuantifierFrame {
262
+ kind: "quantifier";
263
+ list: SmtList;
264
+ quantifierKind: number;
265
+ names: string[];
266
+ varSorts: number[];
267
+ weight: number;
268
+ qid: string;
269
+ skid: string | undefined;
270
+ isTail: boolean;
271
+ start: number;
272
+ patternStart: number;
273
+ noPatternStart: number;
274
+ next: number;
275
+ }
276
+
277
+ interface AttributeFrame {
278
+ kind: "attribute";
279
+ list: SmtList;
280
+ quantifier: QuantifierFrame | undefined;
281
+ lastKeyword: string;
282
+ isTail: boolean;
283
+ start: number;
284
+ next: number;
285
+ }
286
+
287
+ interface PatternFrame {
288
+ kind: "pattern";
221
289
  list: SmtList;
222
290
  start: number;
223
291
  next: number;
224
292
  }
225
293
 
294
+ // smt2parser.cpp's expr_frame.
295
+ type TermFrame =
296
+ | ApplicationFrame
297
+ | SelectionFrame
298
+ | LetFrame
299
+ | LetDeclFrame
300
+ | QuantifierFrame
301
+ | AttributeFrame
302
+ | PatternFrame;
303
+
304
+ const QUANTIFIER_KINDS = new Map([
305
+ ["forall", QUANTIFIER_FORALL],
306
+ ["exists", QUANTIFIER_EXISTS],
307
+ ["lambda", QUANTIFIER_LAMBDA],
308
+ ]);
309
+
310
+ const LET_MESSAGE = "invalid let declaration, symbol expected";
311
+
312
+ // The attributes that consume_attributes takes only in the body of a quantifier.
313
+ const QUANTIFIER_ATTRIBUTES = new Set([":weight", ":skolemid", ":qid", ":pattern", ":no-pattern"]);
314
+
315
+ const IS_PARAMETER_MESSAGE =
316
+ "invalid parameter to datatype function arity == 1 && num_parameters == 1 && parameters[0].is_ast() && is_func_decl(parameters[0].get_ast())";
317
+
226
318
  const BUILTIN_OPS = new Map<string, number>([
227
319
  ["and", OP_AND],
228
320
  ["-", OP_SUB],
@@ -389,17 +481,19 @@ const THEORY_OPERATORS = new Set([
389
481
  "transitive-closure",
390
482
  ]);
391
483
 
392
- // The operators that are associative but not flat: xor and => nest to the right, the others to the
393
- // left.
394
- const NESTED_OPS = new Set([OP_XOR, OP_IMPLIES, OP_SUB, OP_DIV, OP_IDIV]);
484
+ // func_decl_info of the builtin declarations: associative to both sides, flat, and associative to
485
+ // the left only. => alone is associative to the right only.
486
+ const ASSOCIATIVE_OPS = new Set([OP_AND, OP_OR, OP_XOR, OP_ADD, OP_MUL]);
487
+ const FLAT_OPS = new Set([OP_AND, OP_OR, OP_ADD, OP_MUL]);
488
+ const LEFT_ASSOCIATIVE_OPS = new Set([OP_SUB, OP_DIV, OP_IDIV]);
395
489
 
490
+ // arith_decl_plugin's use_coercion.
396
491
  const COERCING_OPS = new Set([
397
492
  OP_ADD,
398
493
  OP_SUB,
399
494
  OP_UMINUS,
400
495
  OP_MUL,
401
496
  OP_POWER,
402
- OP_POWER0,
403
497
  OP_LE,
404
498
  OP_GE,
405
499
  OP_LT,
@@ -424,30 +518,12 @@ const REAL_FUNCTION_OPS = new Set([
424
518
  OP_LOG,
425
519
  ]);
426
520
 
427
- const ARITIES = new Map<number, [number, number]>([
428
- [OP_AND, [0, Infinity]],
429
- [OP_OR, [0, Infinity]],
430
- [OP_ITE, [3, 3]],
431
- [OP_EQ, [2, Infinity]],
432
- [OP_DISTINCT, [1, Infinity]],
521
+ // The arity of each builtin declaration but distinct, which takes the arguments it is given.
522
+ const ARITIES = new Map<number, number>([
523
+ [OP_ITE, 3],
433
524
  ...[OP_NOT, OP_UMINUS, OP_ABS, OP_TO_REAL, OP_TO_INT, OP_IS_INT, ...REAL_FUNCTION_OPS]
434
525
  .filter((op) => op !== OP_ATAN2)
435
- .map((op): [number, [number, number]] => [op, [1, 1]]),
436
- ...[
437
- OP_IMPLIES,
438
- OP_XOR,
439
- OP_IDIV,
440
- OP_MOD,
441
- OP_REM,
442
- OP_DIV,
443
- OP_LE,
444
- OP_GE,
445
- OP_LT,
446
- OP_GT,
447
- OP_POWER,
448
- OP_POWER0,
449
- OP_ATAN2,
450
- ].map((op): [number, [number, number]] => [op, [2, 2]]),
526
+ .map((op): [number, number] => [op, 1]),
451
527
  ]);
452
528
 
453
529
  const RANGES = new Map<number, number>([
@@ -483,6 +559,7 @@ const CHAINABLE_OPS = new Map<string, number>([
483
559
  ["<", OP_LT],
484
560
  [">", OP_GT],
485
561
  ]);
562
+ const CHAINABLE_DECLS = new Set(CHAINABLE_OPS.values());
486
563
 
487
564
  const BV_EXTENSION_NAMES = new Set([
488
565
  "bvumul_noovfl",
@@ -544,6 +621,9 @@ interface MappedDecl {
544
621
  }
545
622
  const ARRAY_EXTENSION_LOGICS = new Set(["HORN", "ALL"]);
546
623
 
624
+ // arith_decl_plugin::get_sort_names gives these logics no Int.
625
+ const INT_FREE_LOGICS = new Set(["NRA", "QF_NRA", "QF_NTA", "QF_UFNRA"]);
626
+
547
627
  const BUILTIN_NAMES = new Set([
548
628
  "true",
549
629
  "false",
@@ -558,6 +638,14 @@ const BUILTIN_NAMES = new Set([
558
638
  ...CHAR_OP_NAMES.keys(),
559
639
  ]);
560
640
 
641
+ const FOLLOWED_HEADS = new Set(["root-obj", "_", "as"]);
642
+
643
+ const FF_LITERAL = /^#f-?[0-9]+m[0-9]+$/;
644
+ const FF_LOGICS = new Set(["QF_FF", "QF_FFA", "ALL", "HO_ALL"]);
645
+
646
+ // rational::is_unsigned of a numeral token.
647
+ const isUnsigned = (numeral: string) => BigInt(numeral) >= 0n && BigInt(numeral) <= 0xffffffffn;
648
+
561
649
  const SYMBOL_CHARACTER = /[A-Za-z0-9~!@$%^&*_\-+=<>.?/,]/;
562
650
 
563
651
  const createScanner = (text: string) => {
@@ -607,6 +695,11 @@ const createScanner = (text: string) => {
607
695
  { line: state.line, column: getColumn() },
608
696
  );
609
697
  const current = text[state.index];
698
+ if (character === "|" && current === "\\")
699
+ throw new SmtParseError("invalid character '\\' in quoted symbol", {
700
+ line: state.line,
701
+ column: getColumn(),
702
+ });
610
703
  advance();
611
704
  // Z3's scanner starts the line before it reads past a newline in a quoted symbol or a
612
705
  // string, so the columns of the rest of the line count one more.
@@ -695,13 +788,13 @@ export const createCommandReader = (text: string) => {
695
788
  offset: open.offset,
696
789
  end: open,
697
790
  };
698
- let rootObject: SmtList | undefined;
791
+ let followed: SmtList | undefined;
699
792
  for (let current = root; ;) {
700
793
  const token = take();
701
794
  if (token === undefined)
702
795
  throw new SmtParseError("unexpected end of file", scanner.getPosition());
703
- if (rootObject !== undefined) rootObject.follower = token;
704
- rootObject = undefined;
796
+ if (followed !== undefined) followed.follower = token;
797
+ followed = undefined;
705
798
  if (token.kind === "(") {
706
799
  const list: SmtList = {
707
800
  kind: "list",
@@ -710,6 +803,7 @@ export const createCommandReader = (text: string) => {
710
803
  column: token.column,
711
804
  offset: token.offset,
712
805
  end: token,
806
+ root,
713
807
  };
714
808
  current.items.push(list);
715
809
  stack.push(current);
@@ -722,7 +816,8 @@ export const createCommandReader = (text: string) => {
722
816
  continue;
723
817
  }
724
818
  current.end = token;
725
- if (isSymbol(current.items[0], "root-obj")) rootObject = current;
819
+ if (isSymbol(current.items[0]) && FOLLOWED_HEADS.has(current.items[0].text))
820
+ followed = current;
726
821
  state.depth--;
727
822
  const parent = stack.pop();
728
823
  if (parent === undefined) return root;
@@ -759,6 +854,28 @@ export const createCommandReader = (text: string) => {
759
854
  export const isSymbol = (sexpr: SExpr | undefined, text?: string): sexpr is SmtToken =>
760
855
  sexpr !== undefined && sexpr.kind === "symbol" && (text === undefined || sexpr.text === text);
761
856
 
857
+ // The identifier Z3's scanner read last, which check_next prints after "got".
858
+ const getLastId = (sexpr: SExpr | undefined): string | undefined => {
859
+ if (sexpr === undefined) return undefined;
860
+ if (sexpr.kind !== "list")
861
+ return sexpr.kind === "symbol" || sexpr.kind === "keyword" ? sexpr.text : undefined;
862
+ return getLastIdBefore(sexpr.items, sexpr.items.length);
863
+ };
864
+
865
+ const getLastIdBefore = (items: SExpr[], end: number): string | undefined => {
866
+ for (let index = end - 1; index >= 0; index--) {
867
+ const id = getLastId(items[index]);
868
+ if (id !== undefined) return id;
869
+ }
870
+ return undefined;
871
+ };
872
+
873
+ const isSimpleIndex = (index: SExpr) =>
874
+ index.kind === "numeral" ||
875
+ index.kind === "bitvector" ||
876
+ index.kind === "decimal" ||
877
+ index.kind === "keyword";
878
+
762
879
  const expectList = (sexpr: SExpr | undefined, message: string, at: SExpr): SmtList => {
763
880
  if (sexpr?.kind !== "list") throw new SmtParseError(message, sexpr ?? at);
764
881
  return sexpr;
@@ -776,16 +893,13 @@ export const createSmtlibReader = (
776
893
  ) => {
777
894
  const hasArith = logic === undefined || logicHasArith(logic);
778
895
  const hasBv = logic === undefined || logicHasBv(logic);
779
- const isNumeralAsReal = logic !== undefined && logicHasRealsOnly(logic);
780
896
  const logicChecker = createLogicChecker(manager, logic);
781
897
  const sortDecls = new Map<string, SortDecl>([
782
898
  ["Bool", { kind: "sort", sort: SORT_BOOL }],
783
- ...(hasArith
784
- ? [
785
- ["Int", { kind: "sort", sort: SORT_INT }] as const,
786
- ["Real", { kind: "sort", sort: SORT_REAL }] as const,
787
- ]
899
+ ...(hasArith && !(logic !== undefined && INT_FREE_LOGICS.has(logic))
900
+ ? [["Int", { kind: "sort", sort: SORT_INT }] as const]
788
901
  : []),
902
+ ...(hasArith ? [["Real", { kind: "sort", sort: SORT_REAL }] as const] : []),
789
903
  ...(logic === undefined ? [["List", { kind: "list" }] as const] : []),
790
904
  ]);
791
905
  const funcs = new Map<string, readonly number[]>();
@@ -794,8 +908,25 @@ export const createSmtlibReader = (
794
908
  const notifiedSorts = new Set<number>();
795
909
  const undo: (() => void)[] = [];
796
910
  const scopeStarts: number[] = [];
797
- const scopes: Map<string, Binding>[] = [];
911
+ // smt2parser's m_env, a scoped symbol table: one map, and the trail of what each scope shadowed.
912
+ const locals = new Map<string, Local>();
913
+ const shadowedNames: string[] = [];
914
+ const shadowedLocals: (Local | undefined)[] = [];
915
+ const localScopes: number[] = [];
798
916
  const binders = { depth: 0 };
917
+ // smt2parser's expr_stack, pattern_stack and nopattern_stack, which hold a reference to each term.
918
+ // -1 on the first stands for a pattern that Z3 ignores.
919
+ const exprStack: number[] = [];
920
+ const patternStack: number[] = [];
921
+ const noPatternStack: number[] = [];
922
+ // The term that parseTerm returns leaves the stack before its caller takes a reference. One that
923
+ // only the stack held keeps a reference in pending until a term of another command is parsed, and
924
+ // one that nothing held, in floating or, where its command is not known, in unrooted, gets one
925
+ // there when another term is parsed while its caller may still read it.
926
+ const parsed: ParsedTerm = { expr: -1, isOwned: false, root: undefined };
927
+ const floating: number[] = [];
928
+ const unrooted: number[] = [];
929
+ const pending: number[] = [];
799
930
 
800
931
  const declare = <Value>(names: Map<string, Value>, name: string, value: Value) => {
801
932
  const previous = names.get(name);
@@ -810,9 +941,20 @@ export const createSmtlibReader = (
810
941
  const hasFpa = logic === undefined || logicHasFpa(logic);
811
942
  const hasArrayExtensions = logic === undefined || ARRAY_EXTENSION_LOGICS.has(logic);
812
943
  const hasSeq = logic === undefined || logicHasSeq(logic);
944
+ const restricted = {
945
+ isNumeralAsReal: logic !== undefined && logicHasRealsOnly(logic),
946
+ hasSetSort: hasArrayExtensions,
947
+ hasFf: logic === undefined || FF_LOGICS.has(logic),
948
+ };
813
949
 
814
950
  const getFirstFunc = (name: string) => funcs.get(name)?.[0];
815
951
 
952
+ // func_decls::signatures_collide: the domain, and the range unless it is -1.
953
+ const hasSignature = (decl: number, domain: readonly number[], range: number) =>
954
+ (range === -1 || manager.funcDecls[decl].range === range) &&
955
+ manager.funcDecls[decl].domain.length === domain.length &&
956
+ manager.funcDecls[decl].domain.every((sort, index) => sort === domain[index]);
957
+
816
958
  const checkDecl = (decl: number, at: SExpr) => {
817
959
  const error = logicChecker.checkDecl(decl);
818
960
  if (error !== undefined) throw new SmtParseError(error, at);
@@ -938,7 +1080,8 @@ export const createSmtlibReader = (
938
1080
  ): number => {
939
1081
  const head = sexpr.items[0];
940
1082
  if (!isSymbol(head)) throw new SmtParseError("invalid sort, symbol or '_' expected", head);
941
- const isArray = ARRAY_SORT_NAMES.has(head.text) || (head.text === "Set" && hasArrayExtensions);
1083
+ const isArray =
1084
+ ARRAY_SORT_NAMES.has(head.text) || (head.text === "Set" && restricted.hasSetSort);
942
1085
  if (isArray && hasArrays) {
943
1086
  const parameters = sexpr.items.slice(1).map((item) => parseSort(item, context, bindings));
944
1087
  if (head.text === "Set" ? parameters.length !== 1 : parameters.length < 2)
@@ -970,7 +1113,7 @@ export const createSmtlibReader = (
970
1113
  return parseSort(head, context, bindings);
971
1114
  }
972
1115
  if (decl === undefined) {
973
- if (THEORY_SORTS.has(head.text) && !isArray)
1116
+ if (THEORY_SORTS.has(head.text) && !isLackingSort(head.text))
974
1117
  throw new SmtUnsupportedError(`the sort ${head.text}`);
975
1118
  throw new SmtParseError(`unknown sort '${head.text}'`, head);
976
1119
  }
@@ -997,8 +1140,20 @@ export const createSmtlibReader = (
997
1140
  for (const item of (sexpr as SmtList).items.slice(1)) checkPsort(item, bindings);
998
1141
  };
999
1142
 
1143
+ // Z3 does not know the sorts of a theory that the logic lacks.
1144
+ const isLackingSort = (name: string) =>
1145
+ name === "Set"
1146
+ ? !hasArrays || !restricted.hasSetSort
1147
+ : ARRAY_SORT_NAMES.has(name)
1148
+ ? !hasArrays
1149
+ : name === "BitVec"
1150
+ ? !hasBv
1151
+ : SEQ_SORT_NAMES.has(name) || name === "Unicode"
1152
+ ? !hasSeq
1153
+ : FPA_SORT_NAMES.has(name) && !hasFpa;
1154
+
1000
1155
  const isBuiltinParametricSort = (name: string) =>
1001
- (hasArrays && (ARRAY_SORT_NAMES.has(name) || (name === "Set" && hasArrayExtensions))) ||
1156
+ (hasArrays && (ARRAY_SORT_NAMES.has(name) || (name === "Set" && restricted.hasSetSort))) ||
1002
1157
  (hasSeq && (name === "Seq" || name === "RegEx")) ||
1003
1158
  (hasFpa && FPA_SORT_NAMES.has(name));
1004
1159
 
@@ -1022,19 +1177,31 @@ export const createSmtlibReader = (
1022
1177
  context: string,
1023
1178
  bindings: ReadonlyMap<string, number> = NO_BINDINGS,
1024
1179
  ): number => {
1180
+ if (sexpr.kind === ")")
1181
+ throw new SmtParseError(`${context} invalid sort, unexpected ')'`, sexpr);
1025
1182
  if (sexpr.kind === "list") {
1026
1183
  if (!isSymbol(sexpr.items[0], "_")) return parseParametricSort(sexpr, context, bindings);
1027
- if (hasFpa && isSymbol(sexpr.items[1], "FloatingPoint"))
1028
- return mkFloatSort(sexpr.items.slice(2), sexpr);
1029
- const width = sexpr.items[2];
1030
- if (!hasBv && isSymbol(sexpr.items[1], "BitVec"))
1031
- throw new SmtParseError("unknown sort 'BitVec'", width ?? sexpr.end);
1032
- if (
1033
- !isSymbol(sexpr.items[1], "BitVec") ||
1034
- sexpr.items.length !== 3 ||
1035
- width.kind !== "numeral"
1036
- )
1037
- throw new SmtUnsupportedError("indexed sorts");
1184
+ // parse_indexed_sort.
1185
+ const name = sexpr.items[1];
1186
+ if (!isSymbol(name))
1187
+ throw new SmtParseError("invalid indexed sort, symbol expected", name ?? sexpr.end);
1188
+ if (hasFpa && name.text === "FloatingPoint") return mkFloatSort(sexpr.items.slice(2), sexpr);
1189
+ const indices = sexpr.items.slice(2);
1190
+ if (isLackingSort(name.text) || !(THEORY_SORTS.has(name.text) || sortDecls.has(name.text)))
1191
+ throw new SmtParseError(`unknown sort '${name.text}'`, indices[0] ?? sexpr.end);
1192
+ if (name.text !== "BitVec") throw new SmtUnsupportedError("indexed sorts");
1193
+ for (const index of indices) {
1194
+ if (index.kind !== "numeral")
1195
+ throw new SmtParseError("invalid indexed sort, integer or ')' expected", index);
1196
+ if (!isUnsigned(index.text))
1197
+ throw new SmtParseError(
1198
+ "invalid indexed identifier, index is too big to fit in an unsigned machine integer",
1199
+ index,
1200
+ );
1201
+ }
1202
+ const width = indices[0];
1203
+ if (indices.length !== 1 || width.kind !== "numeral")
1204
+ throw new SmtParseError("expecting one integer parameter to bit-vector sort", sexpr.end);
1038
1205
  if (BigInt(width.text) === 0n)
1039
1206
  throw new SmtParseError("bit-vector size must be greater than zero", sexpr.end);
1040
1207
  return manager.mkBvSort(Number(width.text));
@@ -1063,106 +1230,222 @@ export const createSmtlibReader = (
1063
1230
  const bits = FPA_SORT_NAMES.get(sexpr.text);
1064
1231
  return bits === undefined ? mkFloatSort([], sexpr) : manager.mkFpSort(bits[0], bits[1]);
1065
1232
  }
1066
- if (THEORY_SORTS.has(sexpr.text)) throw new SmtUnsupportedError(`the sort ${sexpr.text}`);
1233
+ if (THEORY_SORTS.has(sexpr.text) && !isLackingSort(sexpr.text))
1234
+ throw new SmtUnsupportedError(`the sort ${sexpr.text}`);
1067
1235
  throw new SmtParseError(
1068
1236
  `${context === "" ? "" : `${context}: `}unknown sort '${sexpr.text}'`,
1069
1237
  sexpr,
1070
1238
  );
1071
1239
  };
1072
1240
 
1073
- const lookup = (name: string) => {
1074
- for (let index = scopes.length - 1; index >= 0; index--) {
1075
- const binding = scopes[index].get(name);
1076
- if (binding !== undefined) return binding;
1241
+ const beginScope = () => localScopes.push(shadowedNames.length);
1242
+
1243
+ const insertLocal = (name: string, expr: number) => {
1244
+ shadowedNames.push(name);
1245
+ shadowedLocals.push(locals.get(name));
1246
+ locals.set(name, { expr, level: binders.depth });
1247
+ };
1248
+
1249
+ const endScope = () => {
1250
+ const start = localScopes.pop() ?? 0;
1251
+ for (let index = shadowedNames.length - 1; index >= start; index--) {
1252
+ const shadowed = shadowedLocals[index];
1253
+ if (shadowed === undefined) locals.delete(shadowedNames[index]);
1254
+ else locals.set(shadowedNames[index], shadowed);
1077
1255
  }
1078
- return undefined;
1256
+ shrink(shadowedNames, start);
1257
+ shrink(shadowedLocals, start);
1079
1258
  };
1080
1259
 
1081
- const getJoin = (args: number[]) => {
1082
- const argSorts = args.map((arg) => manager.sorts[arg]);
1083
- if (!argSorts.every(isArithSort)) return argSorts[0];
1084
- return argSorts.includes(SORT_REAL) ? SORT_REAL : SORT_INT;
1260
+ const pushRef = (stack: number[], expr: number) => {
1261
+ if (expr !== -1) manager.incRef(expr);
1262
+ stack.push(expr);
1085
1263
  };
1086
1264
 
1087
- const getDomainSort = (op: number, args: number[]) => {
1088
- if (op === OP_ITE) return getJoin(args.slice(1));
1089
- if (op === OP_EQ || op === OP_DISTINCT) return getJoin(args);
1090
- if (COERCING_OPS.has(op)) return getJoin(args) === SORT_REAL ? SORT_REAL : SORT_INT;
1091
- if (op === OP_ABS || op === OP_TO_REAL || op === OP_TO_INT) return manager.sorts[args[0]];
1092
- if (op === OP_IDIV || op === OP_MOD || op === OP_REM) return SORT_INT;
1265
+ // ref_vector::shrink, which releases from the new end on.
1266
+ const shrinkRefs = (stack: number[], size: number) => {
1267
+ for (let index = size; index < stack.length; index++)
1268
+ if (stack[index] !== -1) manager.decRef(stack[index]);
1269
+ shrink(stack, size);
1270
+ };
1271
+
1272
+ const releasePending = () => {
1273
+ for (const expr of pending) manager.decRef(expr);
1274
+ shrink(pending, 0);
1275
+ };
1276
+
1277
+ const protect = (exprs: number[]) => {
1278
+ for (const expr of exprs)
1279
+ if (manager.ids[expr] !== -1 && manager.getRefCount(expr) === 0) pushRef(pending, expr);
1280
+ shrink(exprs, 0);
1281
+ };
1282
+
1283
+ // push_local: var_shifter moves the free variables of a term that was bound under fewer binders.
1284
+ // Its cache holds the terms it makes, which replaceFreeVars rebuilds.
1285
+ const getLocalTerm = (local: Local) => {
1286
+ if (local.level === binders.depth) return local.expr;
1287
+ if (manager.kinds[local.expr] === KIND_VAR)
1288
+ return manager.mkVar(
1289
+ manager.values[local.expr] + binders.depth - local.level,
1290
+ manager.sorts[local.expr],
1291
+ );
1292
+ return replaceFreeVars(manager, local.expr, (variable, index, shift) =>
1293
+ manager.mkVar(index + shift + binders.depth - local.level, manager.sorts[variable]),
1294
+ );
1295
+ };
1296
+
1297
+ // basic_decl_plugin::join.
1298
+ const getJoin = (left: number, right: number, at: SExpr) => {
1299
+ if (left === right) return left;
1300
+ if (isArithSort(left) && isArithSort(right)) return left === SORT_REAL ? left : right;
1301
+ if (left === SORT_BOOL && isArithSort(right)) return right;
1302
+ if (right === SORT_BOOL && isArithSort(left)) return left;
1303
+ throw new SmtParseError(
1304
+ `Sorts ${manager.getSortName(left)} and ${manager.getSortName(right)} are incompatible`,
1305
+ at,
1306
+ );
1307
+ };
1308
+
1309
+ const getJoinOfArgs = (args: number[], at: SExpr) =>
1310
+ args.reduce((join, arg) => getJoin(join, manager.sorts[arg], at), manager.sorts[args[0]]);
1311
+
1312
+ // basic_decl_plugin::mk_func_decl and arith_decl_plugin::mk_func_decl: the sort of the arguments
1313
+ // that the declaration takes, the condition of ite aside, or -1 where the plugin makes none.
1314
+ const getDomainSort = (op: number, args: number[], at: SExpr) => {
1315
+ if (op === OP_ITE)
1316
+ return args.length === 3 ? getJoin(manager.sorts[args[1]], manager.sorts[args[2]], at) : -1;
1317
+ if (op === OP_EQ) return args.length >= 2 ? getJoinOfArgs(args, at) : -1;
1318
+ if (op === OP_DISTINCT) return args.length === 0 ? SORT_BOOL : getJoinOfArgs(args, at);
1319
+ if (manager.funcDecls[op].family === FAMILY_BASIC) return SORT_BOOL;
1320
+ if (COERCING_OPS.has(op))
1321
+ return args.some((arg) => manager.sorts[arg] === SORT_REAL) ? SORT_REAL : SORT_INT;
1093
1322
  if (op === OP_DIV || op === OP_IS_INT || REAL_FUNCTION_OPS.has(op)) return SORT_REAL;
1094
- return SORT_BOOL;
1323
+ if (op === OP_IDIV || op === OP_MOD || op === OP_REM) return SORT_INT;
1324
+ return manager.sorts[args[0]] === SORT_REAL ? SORT_REAL : SORT_INT;
1095
1325
  };
1096
1326
 
1327
+ // ast_manager::coerce_to.
1097
1328
  const coerce = (arg: number, sort: number) => {
1098
1329
  const argSort = manager.sorts[arg];
1099
- if (argSort === sort || !isArithSort(argSort) || !isArithSort(sort)) return arg;
1100
- return sort === SORT_REAL
1101
- ? manager.mkApp(OP_TO_REAL, [arg], SORT_REAL)
1102
- : manager.mkApp(OP_TO_INT, [arg], SORT_INT);
1103
- };
1104
-
1105
- const mkApp = (decl: number, inputArgs: number[], at: SExpr, domainSort?: number) => {
1106
- const op = manager.funcDecls[decl].op;
1107
- const name = manager.funcDecls[decl].name;
1108
- const isUninterpreted =
1109
- op === OP_UNINTERPRETED ||
1110
- op === OP_FUN_DEFINED ||
1111
- manager.funcDecls[decl].family === FAMILY_DATATYPE;
1112
- const domain = manager.funcDecls[decl].domain;
1113
- const builtinSort = isUninterpreted ? -1 : (domainSort ?? getDomainSort(op, inputArgs));
1114
- const getExpected = (index: number) =>
1115
- isUninterpreted ? domain[index] : op === OP_ITE && index === 0 ? SORT_BOOL : builtinSort;
1116
- const args = inputArgs.map((arg, index) =>
1117
- getExpected(index) === undefined ? arg : coerce(arg, getExpected(index)),
1330
+ if (argSort === sort || !isArithSort(sort)) return arg;
1331
+ if (isArithSort(argSort))
1332
+ return sort === SORT_REAL
1333
+ ? manager.mkApp(OP_TO_REAL, [arg], SORT_REAL)
1334
+ : manager.mkApp(OP_TO_INT, [arg], SORT_INT);
1335
+ if (argSort !== SORT_BOOL) return arg;
1336
+ const one = manager.mkNumeralOfSort(Rational.of(1n), sort);
1337
+ return manager.mkApp(OP_ITE, [arg, one, manager.mkNumeralOfSort(Rational.of(0n), sort)], sort);
1338
+ };
1339
+
1340
+ // A declaration of the script has its own domain, and a builtin one takes domainSort.
1341
+ const getArity = (decl: number, numArgs: number, domainSort: number) =>
1342
+ domainSort === -1
1343
+ ? manager.funcDecls[decl].domain.length
1344
+ : decl === OP_DISTINCT
1345
+ ? numArgs
1346
+ : (ARITIES.get(decl) ?? 2);
1347
+
1348
+ const getExpectedSort = (decl: number, index: number, domainSort: number) =>
1349
+ domainSort === -1
1350
+ ? manager.funcDecls[decl].domain[index]
1351
+ : decl === OP_ITE && index === 0
1352
+ ? SORT_BOOL
1353
+ : domainSort;
1354
+
1355
+ const formatDecl = (decl: number, numArgs: number, domainSort: number) => {
1356
+ const domain = Array.from({ length: getArity(decl, numArgs, domainSort) }, (_unused, index) =>
1357
+ manager.getSortName(getExpectedSort(decl, index, domainSort)),
1118
1358
  );
1119
- const arity = ARITIES.get(op) ?? [1, Infinity];
1120
- const isArityOk = isUninterpreted
1121
- ? args.length === domain.length
1122
- : args.length >= arity[0] && args.length <= arity[1];
1123
- const isBuiltinArith = manager.funcDecls[decl].family === FAMILY_ARITH;
1124
- const isWellSorted =
1125
- isArityOk &&
1126
- (!isBuiltinArith || isArithSort(builtinSort)) &&
1127
- args.every((arg, index) => manager.sorts[arg] === getExpected(index));
1128
- if (!isWellSorted) throw new SmtParseError(`ill-sorted application of ${name}`, at);
1359
+ const range =
1360
+ domainSort === -1 ? manager.funcDecls[decl].range : (RANGES.get(decl) ?? domainSort);
1361
+ return `(declare-fun ${String(manager.funcDecls[decl].name)} (${domain.join(" ")}) ${manager.getSortName(range)})`;
1362
+ };
1363
+
1364
+ // ast_manager::mk_app_core: coercion_needed, coerce_to and check_args.
1365
+ const mkAppCore = (decl: number, args: number[], at: SExpr, domainSort: number) => {
1366
+ const isAssociative = domainSort !== -1 && ASSOCIATIVE_OPS.has(decl);
1367
+ const isCoercing =
1368
+ (isAssociative || getArity(decl, args.length, domainSort) === args.length) &&
1369
+ args.some((arg, index) => {
1370
+ const expected = getExpectedSort(decl, index, domainSort);
1371
+ return isArithSort(expected) && expected !== manager.sorts[arg];
1372
+ });
1373
+ const coerced = isCoercing
1374
+ ? args.map((arg, index) => coerce(arg, getExpectedSort(decl, index, domainSort)))
1375
+ : args;
1376
+ for (let index = 0; index < coerced.length; index++) {
1377
+ const sort = manager.sorts[coerced[index]];
1378
+ if (sort !== getExpectedSort(decl, index, domainSort))
1379
+ throw new SmtParseError(
1380
+ `Sort mismatch at argument #${index + 1} for function ${formatDecl(decl, args.length, domainSort)} supplied sort is ${manager.getSortName(sort)}`,
1381
+ at,
1382
+ );
1383
+ }
1384
+ // Z3 keeps xor, / and div of fewer than two arguments until its rewriters make false or the
1385
+ // argument of them, which those of this port do not.
1386
+ if (
1387
+ coerced.length < 2 &&
1388
+ domainSort !== -1 &&
1389
+ (decl === OP_XOR || LEFT_ASSOCIATIVE_OPS.has(decl))
1390
+ )
1391
+ return coerced[0] ?? manager.falseExpr;
1129
1392
  return manager.mkApp(
1130
1393
  decl,
1131
- args,
1132
- isUninterpreted ? manager.funcDecls[decl].range : (RANGES.get(op) ?? builtinSort),
1394
+ coerced,
1395
+ domainSort === -1 ? manager.funcDecls[decl].range : (RANGES.get(decl) ?? domainSort),
1133
1396
  );
1134
1397
  };
1135
1398
 
1136
- const mkChain = (op: number, args: number[], at: SExpr) => {
1137
- const domainSort = getDomainSort(op, args);
1399
+ // ast_manager::mk_app.
1400
+ const mkApp = (decl: number, args: number[], at: SExpr, domainSort = -1): number => {
1401
+ const isBuiltin = domainSort !== -1;
1402
+ const isAssociative = isBuiltin && ASSOCIATIVE_OPS.has(decl);
1403
+ const isLeftAssociative = isAssociative || (isBuiltin && LEFT_ASSOCIATIVE_OPS.has(decl));
1404
+ const isRightAssociative = isAssociative || (isBuiltin && decl === OP_IMPLIES);
1405
+ const isChainable = isBuiltin && CHAINABLE_DECLS.has(decl);
1406
+ if (
1407
+ getArity(decl, args.length, domainSort) !== args.length &&
1408
+ ((!isLeftAssociative && !isRightAssociative && !isChainable) ||
1409
+ (args.length < 2 && manager.funcDecls[decl].family === FAMILY_BASIC && !isAssociative))
1410
+ ) {
1411
+ const environment = { options: DEFAULT_PRINT_OPTIONS, isUsed, isClashing };
1412
+ // Z3 prints an error without the newlines that end it.
1413
+ throw new SmtParseError(
1414
+ `Wrong number of arguments (${args.length}) passed to function ${formatDecl(decl, args.length, domainSort)} ${args
1415
+ .map((arg) => `\narg: ${printExpr(manager, environment, arg)}\n`)
1416
+ .join("")}`.replace(/\n+$/, ""),
1417
+ at,
1418
+ );
1419
+ }
1420
+ if (args.length === 1 && isChainable) return manager.trueExpr;
1421
+ if (args.length <= 2 || (isBuiltin && FLAT_OPS.has(decl)))
1422
+ return mkAppCore(decl, args, at, domainSort);
1423
+ if (isRightAssociative)
1424
+ return args
1425
+ .slice(0, -2)
1426
+ .reduceRight(
1427
+ (right, left) => mkAppCore(decl, [left, right], at, domainSort),
1428
+ mkAppCore(decl, args.slice(-2), at, domainSort),
1429
+ );
1430
+ if (isLeftAssociative)
1431
+ return args
1432
+ .slice(2)
1433
+ .reduce(
1434
+ (left, right) => mkAppCore(decl, [left, right], at, domainSort),
1435
+ mkAppCore(decl, args.slice(0, 2), at, domainSort),
1436
+ );
1437
+ if (!isChainable) return mkAppCore(decl, args, at, domainSort);
1138
1438
  const pairs: number[] = [];
1139
- for (let index = 0; index + 1 < args.length; index++)
1140
- pairs.push(mkApp(op, [args[index], args[index + 1]], at, domainSort));
1141
- return pairs.length === 1 ? pairs[0] : mkApp(OP_AND, pairs, at);
1142
- };
1143
-
1144
- const rejectPattern = (message: string, at: SExpr) => {
1145
- if (!options.isIgnoringBadPatterns) throw new SmtParseError(message, at);
1146
- return undefined;
1439
+ for (let index = 1; index < args.length; index++)
1440
+ pairs.push(mkAppCore(decl, [args[index - 1], args[index]], at, domainSort));
1441
+ return mkApp(OP_AND, pairs, at, SORT_BOOL);
1147
1442
  };
1148
1443
 
1149
- const parsePattern = (sexpr: SExpr, at: SExpr) => {
1150
- if (sexpr.kind === ")") {
1151
- // Z3 skips a bad pattern as an s-expression, which cannot start with ')'.
1152
- if (options.isIgnoringBadPatterns)
1153
- throw new SmtParseError("invalid s-expression, unexpected ')'", sexpr);
1154
- throw new SmtParseError("invalid pattern, '(' expected", sexpr);
1155
- }
1156
- if (sexpr.kind !== "list") return rejectPattern("invalid pattern, '(' expected", sexpr);
1157
- if (sexpr.items.length === 0) return rejectPattern("invalid empty pattern", at);
1158
- const head = sexpr.items[0];
1159
- if (head.kind === "list") return manager.mkPattern(sexpr.items.map(parseTerm));
1160
- const decl = head.text === "true" || head.text === "false" ? -1 : getFirstFunc(head.text);
1161
- if (decl === -1 || (decl !== undefined && manager.funcDecls[decl].domain.length === 0))
1162
- return rejectPattern("invalid constant pattern", head);
1163
- if (head.kind !== "symbol")
1164
- throw new SmtParseError("invalid pattern, '(' or identifier expected", head);
1165
- return manager.mkPattern([parseTerm(sexpr)]);
1444
+ // ast_manager::mk_pattern.
1445
+ const mkPattern = (terms: number[], at: SExpr) => {
1446
+ if (terms.some((term) => manager.kinds[term] !== KIND_APP))
1447
+ throw new SmtParseError("patterns cannot be variables or quantifiers", at);
1448
+ return manager.mkPattern(terms);
1166
1449
  };
1167
1450
 
1168
1451
  const isValidPattern = (pattern: number, numDecls: number) => {
@@ -1187,151 +1470,90 @@ export const createSmtlibReader = (
1187
1470
  return manager.everyArg(pattern, isValid) && found.size === numDecls;
1188
1471
  };
1189
1472
 
1190
- const bindSortedVars = (sexpr: SExpr | undefined, at: SExpr) => {
1191
- const message = "invalid sorted variables, syntax error: ((<symbol> <sort>)*) expected";
1192
- const declarations = expectList(sexpr, message, at).items.map((declaration) =>
1193
- expectList(declaration, message, declaration),
1194
- );
1195
- const scope = new Map<string, Binding>();
1196
- const names = declarations.map(
1197
- (declaration) => expectSymbol(declaration.items[0], message, declaration).text,
1198
- );
1199
- const varSorts = declarations.map((declaration, index) => {
1200
- if (declaration.items.length !== 2) throw new SmtParseError(message, declaration.end);
1201
- const sort = parseSort(declaration.items[1], "invalid sorted variables");
1202
- scope.set(names[index], { kind: "var", depth: binders.depth + index, sort });
1203
- return sort;
1204
- });
1205
- scopes.push(scope);
1473
+ // parse_sorted_vars: the variables are created the first declared with the largest index, and
1474
+ // the stack holds them. previousId is the identifier before the list.
1475
+ const bindSortedVars = (sexpr: SExpr | undefined, at: SExpr, previousId: string) => {
1476
+ if (sexpr?.kind !== "list")
1477
+ throw new SmtParseError(
1478
+ `invalid list of sorted variables, '(' expected got ${getLastId(sexpr) ?? previousId}`,
1479
+ sexpr ?? at,
1480
+ );
1481
+ const names: string[] = [];
1482
+ const varSorts: number[] = [];
1483
+ for (const [index, declaration] of sexpr.items.entries()) {
1484
+ if (declaration.kind !== "list")
1485
+ throw new SmtParseError(
1486
+ `invalid sorted variable, '(' expected got ${getLastId(declaration) ?? getLastIdBefore(sexpr.items, index) ?? previousId}`,
1487
+ declaration,
1488
+ );
1489
+ const name = declaration.items[0];
1490
+ if (!isSymbol(name))
1491
+ throw new SmtParseError(
1492
+ "invalid sorted variable, symbol expected",
1493
+ name ?? declaration.end,
1494
+ );
1495
+ names.push(name.text);
1496
+ varSorts.push(parseSort(declaration.items[1] ?? declaration.end, "invalid sorted variables"));
1497
+ const extra = declaration.items[2];
1498
+ if (extra !== undefined)
1499
+ throw new SmtParseError(
1500
+ `invalid sorted variable, ')' expected got ${getLastId(extra) ?? getLastId(declaration.items[1]) ?? name.text}`,
1501
+ extra,
1502
+ );
1503
+ }
1504
+ beginScope();
1206
1505
  binders.depth += varSorts.length;
1506
+ for (const [index, sort] of varSorts.entries()) {
1507
+ const boundVar = manager.mkVar(varSorts.length - 1 - index, sort);
1508
+ pushRef(exprStack, boundVar);
1509
+ insertLocal(names[index], boundVar);
1510
+ }
1207
1511
  return { names, varSorts };
1208
1512
  };
1209
1513
 
1210
1514
  const unbindSortedVars = (count: number) => {
1211
- scopes.pop();
1515
+ endScope();
1212
1516
  binders.depth -= count;
1213
1517
  };
1214
1518
 
1215
- const parseQuantifier = (list: SmtList, kind: number) => {
1216
- if (list.items.length !== 3)
1519
+ // pop_quant_frame, up to the quantifier.
1520
+ const mkParsedQuantifier = (frame: QuantifierFrame) => {
1521
+ const list = frame.list;
1522
+ const numDecls = frame.varSorts.length;
1523
+ if (exprStack.length - frame.start !== numDecls + 1)
1217
1524
  throw new SmtParseError(
1218
1525
  "invalid quantified expression, syntax error: (forall|exists ((<symbol> <sort>)*) <expr>) expected",
1219
1526
  list.end,
1220
1527
  );
1221
- const bound = bindSortedVars(list.items[1], list);
1222
- const varSorts = bound.varSorts;
1223
- // parse_sorted_vars: the variables are created first, the first declared with the largest index,
1224
- // and the parser's stack holds them until the quantifier is created.
1225
- const boundVars = varSorts.map((sort, index) =>
1226
- manager.mkVar(varSorts.length - 1 - index, sort),
1227
- );
1228
- for (const boundVar of boundVars) manager.incRef(boundVar);
1229
- const bodySExpr = list.items[2];
1230
- const isAnnotated = bodySExpr.kind === "list" && isSymbol(bodySExpr.items[0], "!");
1231
- const annotations = bodySExpr.kind === "list" && isAnnotated ? bodySExpr.items : [];
1232
- const parsedBody = parseTerm(isAnnotated ? annotations[1] : bodySExpr);
1233
- if (kind !== QUANTIFIER_LAMBDA && manager.sorts[parsedBody] !== SORT_BOOL)
1234
- throw new SmtParseError("expected a formula", bodySExpr);
1235
- const attributes = Array.from(
1236
- { length: Math.ceil((annotations.length - 2) / 2) },
1237
- (_unused, index) => ({
1238
- keyword: annotations[2 + 2 * index],
1239
- value: annotations[3 + 2 * index],
1240
- }),
1241
- );
1242
- const body = attributes.reduce(
1243
- (labeled, attribute) =>
1244
- attribute.keyword.kind === "keyword" &&
1245
- (attribute.keyword.text === ":lblpos" || attribute.keyword.text === ":lblneg")
1246
- ? mkLabel(labeled, attribute.keyword.text === ":lblpos", attribute.value, bodySExpr)
1247
- : labeled,
1248
- parsedBody,
1249
- );
1250
- const patterns: number[] = [];
1251
- const noPatterns: number[] = [];
1252
- for (const attribute of attributes) {
1253
- if (attribute.keyword.kind !== "keyword") continue;
1254
- if (attribute.keyword.text === ":no-pattern") {
1255
- const noPattern = parseTerm(attribute.value ?? list.end);
1256
- manager.incRef(noPattern);
1257
- noPatterns.push(noPattern);
1258
- continue;
1259
- }
1260
- if (attribute.keyword.text !== ":pattern") continue;
1261
- const pattern = parsePattern(
1262
- attribute.value ?? (bodySExpr.kind === "list" ? bodySExpr.end : list.end),
1263
- list.end,
1264
- );
1265
- if (pattern === undefined) continue;
1266
- manager.incRef(pattern);
1267
- patterns.push(pattern);
1268
- }
1269
- const getAttribute = (name: string) => {
1270
- const value = attributes
1271
- .filter(
1272
- (attribute) =>
1273
- attribute.keyword.kind === "keyword" &&
1274
- attribute.keyword.text === name &&
1275
- attribute.value?.kind !== "list",
1276
- )
1277
- .at(-1)?.value;
1278
- return value?.kind === "list" ? undefined : value?.text;
1279
- };
1280
- const weight = Number(getAttribute(":weight") ?? 1);
1281
- const qid = getAttribute(":qid") ?? "";
1282
- const skid = getAttribute(":skolemid");
1283
- unbindSortedVars(varSorts.length);
1284
- // pop_quant_frame: the invalid patterns leave the parser's stack before the quantifier is made,
1285
- // and the valid ones after.
1286
- let numKept = 0;
1287
- for (const pattern of patterns) {
1288
- if (!isValidPattern(pattern, varSorts.length)) {
1289
- rejectPattern("invalid pattern", list.end);
1528
+ let numKept = frame.patternStart;
1529
+ for (let index = frame.patternStart; index < patternStack.length; index++) {
1530
+ const pattern = patternStack[index];
1531
+ if (!isValidPattern(pattern, numDecls)) {
1532
+ if (!options.isIgnoringBadPatterns) throw new SmtParseError("invalid pattern", list.end);
1290
1533
  continue;
1291
1534
  }
1292
1535
  manager.incRef(pattern);
1293
- manager.decRef(patterns[numKept]);
1294
- patterns[numKept] = pattern;
1536
+ manager.decRef(patternStack[numKept]);
1537
+ patternStack[numKept] = pattern;
1295
1538
  numKept++;
1296
1539
  }
1297
- for (const removed of patterns.splice(numKept)) manager.decRef(removed);
1298
- if (patterns.length > 0 && noPatterns.length > 0)
1540
+ shrinkRefs(patternStack, numKept);
1541
+ const body = exprStack[exprStack.length - 1];
1542
+ if (frame.quantifierKind !== QUANTIFIER_LAMBDA && manager.sorts[body] !== SORT_BOOL)
1543
+ throw new SmtParseError("quantifier body must be a Boolean expression", list.end);
1544
+ if (patternStack.length > frame.patternStart && noPatternStack.length > frame.noPatternStart)
1299
1545
  throw new SmtParseError("simultaneous patterns and no-patterns not supported", list.end);
1300
- const quantifier = manager.mkQuantifier({
1301
- kind,
1302
- sorts: varSorts,
1303
- names: bound.names,
1546
+ return manager.mkQuantifier({
1547
+ kind: frame.quantifierKind,
1548
+ sorts: frame.varSorts,
1549
+ names: frame.names,
1304
1550
  body,
1305
- patterns,
1306
- noPatterns,
1307
- weight,
1308
- qid,
1309
- ...(skid === undefined ? {} : { skid }),
1551
+ patterns: patternStack.slice(frame.patternStart),
1552
+ noPatterns: noPatternStack.slice(frame.noPatternStart),
1553
+ weight: frame.weight,
1554
+ qid: frame.qid,
1555
+ ...(frame.skid === undefined ? {} : { skid: frame.skid }),
1310
1556
  });
1311
- for (const pattern of patterns) manager.decRef(pattern);
1312
- for (const noPattern of noPatterns) manager.decRef(noPattern);
1313
- for (const boundVar of boundVars) manager.decRef(boundVar);
1314
- return quantifier;
1315
- };
1316
-
1317
- const parseLet = (list: SmtList) => {
1318
- const message = "invalid let declaration, symbol expected";
1319
- const scope = new Map<string, Binding>();
1320
- const exprs: number[] = [];
1321
- for (const binding of expectList(list.items[1], message, list).items) {
1322
- const pair = expectList(binding, message, binding);
1323
- const name = expectSymbol(pair.items[0], message, pair);
1324
- const expr = parseTerm(pair.items[1] ?? pair.end);
1325
- exprs.push(expr);
1326
- scope.set(name.text, { kind: "let", depth: binders.depth, expr });
1327
- }
1328
- scopes.push(scope);
1329
- // Z3 takes the last expression on its stack, so a let without a body is its last binding.
1330
- for (const body of list.items.slice(2)) exprs.push(parseTerm(body));
1331
- scopes.pop();
1332
- const result = exprs.at(-1);
1333
- if (result === undefined) throw new SmtParseError("invalid let expression", list.end);
1334
- return result;
1335
1557
  };
1336
1558
 
1337
1559
  const expandMacro = (macro: Macro, args: number[]) =>
@@ -1405,7 +1627,7 @@ export const createSmtlibReader = (
1405
1627
  const pair = [args[index], args[index + 1]];
1406
1628
  pairs.push(mkFpaAppOf(manager, getSignature(pair), pair));
1407
1629
  }
1408
- return mkApp(OP_AND, pairs, at);
1630
+ return mkApp(OP_AND, pairs, at, SORT_BOOL);
1409
1631
  };
1410
1632
 
1411
1633
  const isSeqOpName = (name: string) =>
@@ -1525,43 +1747,136 @@ export const createSmtlibReader = (
1525
1747
  return manager.mkAlgebraicNumeral(root);
1526
1748
  };
1527
1749
 
1528
- const parseBvNumeral = (list: SmtList) => {
1750
+ const isKnownOperator = (name: string) => BUILTIN_NAMES.has(name) || THEORY_OPERATOR.test(name);
1751
+
1752
+ // parse_indexed_identifier_core.
1753
+ const getIndexedName = (list: SmtList) => {
1529
1754
  const name = list.items[1];
1755
+ if (!isSymbol(name))
1756
+ throw new SmtParseError("invalid indexed identifier, symbol expected", name ?? list.end);
1757
+ for (const index of list.items.slice(2)) {
1758
+ if (index.kind === "string")
1759
+ throw new SmtParseError(
1760
+ "invalid indexed identifier, integer, identifier or '(' expected",
1761
+ index,
1762
+ );
1763
+ // parse_func_decl_ref of an index that is a symbol.
1764
+ if (
1765
+ index.kind === "symbol" &&
1766
+ name.text !== "is" &&
1767
+ !isUsed(index.text) &&
1768
+ !macros.has(index.text)
1769
+ )
1770
+ throw new SmtParseError(
1771
+ `invalid function declaration reference, unknown function ${index.text}`,
1772
+ index,
1773
+ );
1774
+ }
1775
+ return name;
1776
+ };
1777
+
1778
+ // parse_qualified_identifier_core on (as <identifier> <sort>), up to the sort.
1779
+ const parseQualifierSort = (list: SmtList) => {
1780
+ const target = list.items[1];
1781
+ if (target === undefined || (target.kind !== "symbol" && target.kind !== "list"))
1782
+ throw new SmtParseError(
1783
+ `invalid (indexed) identifier, '(_' or symbol expected got ${getLastId(target) ?? "as"}`,
1784
+ target ?? list.end,
1785
+ );
1786
+ if (target.kind === "list") {
1787
+ if (!isSymbol(target.items[0], "_"))
1788
+ throw new SmtParseError(
1789
+ "invalid indexed identifier, '_' expected",
1790
+ target.items[0] ?? target.end,
1791
+ );
1792
+ getIndexedName(target);
1793
+ }
1794
+ const sort = parseSort(list.items[2] ?? list.end, "Invalid qualified identifier");
1795
+ const extra = list.items[3];
1796
+ if (extra !== undefined)
1797
+ throw new SmtParseError(
1798
+ `invalid qualified identifier, ')' expected got ${getLastId(extra) ?? getLastIdBefore(list.items, 3) ?? "as"}`,
1799
+ extra,
1800
+ );
1801
+ return sort;
1802
+ };
1803
+
1804
+ // parse_qualified_name on (_ <symbol> <index>*). Z3 makes the term once it has read past the
1805
+ // closing parenthesis, where at is.
1806
+ const parseIndexedTerm = (list: SmtList, at: SExpr, range?: number) => {
1807
+ const name = getIndexedName(list);
1530
1808
  const indices = list.items.slice(2);
1531
- if (
1532
- isSymbol(name) &&
1533
- isSeqOpName(name.text) &&
1534
- indices.every((index) => index.kind === "numeral")
1535
- )
1809
+ const local = locals.get(name.text);
1810
+ if (local !== undefined) {
1811
+ if (indices.length > 0)
1812
+ throw new SmtParseError("invalid indexed identifier, symbol is a local declaration", at);
1813
+ return getLocalTerm(local);
1814
+ }
1815
+ const value = /^bv([0-9]+)$/.exec(name.text);
1816
+ if (value !== null) {
1817
+ const width = indices[0];
1818
+ const digits =
1819
+ indices.length !== 1
1820
+ ? "-1"
1821
+ : width.kind === "bitvector"
1822
+ ? `0${width.text.slice(1)}`
1823
+ : width.kind === "numeral"
1824
+ ? width.text
1825
+ : "-1";
1826
+ if (!isUnsigned(digits))
1827
+ throw new SmtParseError("invalid bit-vector constant, index expected", at);
1828
+ if (BigInt(digits) === 0n)
1829
+ throw new SmtParseError("bit-vector size must be greater than zero", at);
1830
+ return manager.mkBvNumeral(BigInt(value[1]), Number(BigInt(digits)));
1831
+ }
1832
+ const isNumbered = indices.every((index) => index.kind === "numeral");
1833
+ if (isNumbered && isSeqOpName(name.text))
1536
1834
  return mkSeqTerm(
1537
1835
  name.text,
1538
1836
  [],
1539
1837
  indices.map((index) => (index.kind === "list" ? 0 : Number(index.text))),
1540
- list.end,
1838
+ at,
1541
1839
  );
1542
- if (
1543
- isSymbol(name) &&
1544
- isFpaOpName(name.text) &&
1545
- indices.every((index) => index.kind === "numeral")
1546
- ) {
1840
+ if (isNumbered && isFpaOpName(name.text)) {
1547
1841
  const signature = getFpaSignature(
1548
1842
  manager,
1549
1843
  FPA_OP_NAMES.get(name.text) ?? -1,
1550
1844
  indices.map((index) => (index.kind === "list" ? 0 : Number(index.text))),
1551
1845
  [],
1552
1846
  );
1553
- if (typeof signature === "string")
1554
- throw new SmtParseError(signature, { line: list.end.line, column: list.end.column + 1 });
1847
+ if (typeof signature === "string") throw new SmtParseError(signature, at);
1555
1848
  return mkFpaAppOf(manager, signature, []);
1556
1849
  }
1557
- const value = isSymbol(name) ? /^bv([0-9]+)$/.exec(name.text) : null;
1558
- if (value === null) throw new SmtUnsupportedError("indexed identifiers");
1559
- const width = list.items[2];
1560
- if (list.items.length !== 3 || width.kind !== "numeral")
1561
- throw new SmtParseError("invalid bit-vector constant, index expected", list.end);
1562
- if (BigInt(width.text) === 0n)
1563
- throw new SmtParseError("bit-vector size must be greater than zero", list.end);
1564
- return manager.mkBvNumeral(BigInt(value[1]), Number(width.text));
1850
+ if (isKnownOperator(name.text) || !indices.every(isSimpleIndex))
1851
+ throw new SmtUnsupportedError("indexed identifiers");
1852
+ return parseApp(name, [], at, [], range);
1853
+ };
1854
+
1855
+ // parse_qualified_name.
1856
+ const parseQualifiedName = (list: SmtList) => {
1857
+ const at = list.follower ?? list.end;
1858
+ if (isSymbol(list.items[0], "_")) return parseIndexedTerm(list, at);
1859
+ const sort = parseQualifierSort(list);
1860
+ const target = list.items[1];
1861
+ const local = isSymbol(target) ? locals.get(target.text) : undefined;
1862
+ if (isSymbol(target) && local === undefined)
1863
+ return hasArrays && target.text === "const"
1864
+ ? mkArrayTerm(OP_CONST_ARRAY, [], [sort], at)
1865
+ : parseApp(target, [], at, [], sort);
1866
+ const term =
1867
+ local === undefined
1868
+ ? parseIndexedTerm(
1869
+ expectList(target, "invalid indexed identifier, '_' expected", list),
1870
+ at,
1871
+ sort,
1872
+ )
1873
+ : getLocalTerm(local);
1874
+ if (manager.sorts[term] !== sort)
1875
+ throw new SmtParseError(
1876
+ `sort mismatch in qualified identifier, expected: ${manager.getSortName(sort)}, got: ${manager.getSortName(manager.sorts[term])}`,
1877
+ at,
1878
+ );
1879
+ return term;
1565
1880
  };
1566
1881
 
1567
1882
  const mkArrayTerm = (op: number, inputArgs: number[], parameters: number[], at: SExpr) => {
@@ -1624,10 +1939,7 @@ export const createSmtlibReader = (
1624
1939
  sort === argSorts[index] || (isArithSort(sort) && isArithSort(argSorts[index])),
1625
1940
  ),
1626
1941
  );
1627
- const found =
1628
- candidates.find((decl) =>
1629
- manager.funcDecls[decl].domain.every((sort, index) => sort === argSorts[index]),
1630
- ) ?? candidates.at(-1);
1942
+ const found = candidates.find((decl) => hasSignature(decl, argSorts, -1)) ?? candidates.at(-1);
1631
1943
  if (found !== undefined) return mkApp(found, args, at);
1632
1944
  if (args.length === 0 || range !== undefined) return undefined;
1633
1945
  if (decls.length > 1) throwAmbiguousConstant(name, at);
@@ -1678,10 +1990,23 @@ export const createSmtlibReader = (
1678
1990
 
1679
1991
  const mkIsApp = (constructorName: SmtToken, args: number[], at: SExpr) => {
1680
1992
  const declared = findFuncDecl(constructorName);
1681
- if (declared !== undefined) return mkApp(getConstructorIs(manager, declared), args, at);
1993
+ // datatype::decl::plugin::mk_is.
1994
+ if (declared !== undefined) {
1995
+ if (args.length !== 1) throw new SmtParseError(IS_PARAMETER_MESSAGE, at);
1996
+ if (!manager.isDatatypeSort(manager.sorts[args[0]]))
1997
+ throw new SmtParseError(
1998
+ "invalid parameter to datatype function u().is_datatype(domain[0])",
1999
+ at,
2000
+ );
2001
+ if (manager.sorts[args[0]] !== manager.funcDecls[declared].range)
2002
+ throw new SmtParseError("invalid sort argument passed to recognizer", at);
2003
+ if (manager.funcDecls[declared].op !== OP_DT_CONSTRUCTOR)
2004
+ throw new SmtParseError("expecting constructor argument to recognizer", at);
2005
+ return manager.mkApp(getConstructorIs(manager, declared), args, SORT_BOOL);
2006
+ }
1682
2007
  const argSort = args.length === 1 ? manager.sorts[args[0]] : -1;
1683
2008
  if (argSort === -1 || !manager.isDatatypeSort(argSort))
1684
- throw new SmtUnsupportedError("the operator is");
2009
+ throw new SmtParseError(IS_PARAMETER_MESSAGE, at);
1685
2010
  const constructor = getDatatypeConstructors(manager, argSort).find(
1686
2011
  (decl) => manager.funcDecls[decl].name === constructorName.text,
1687
2012
  );
@@ -1700,9 +2025,23 @@ export const createSmtlibReader = (
1700
2025
  `invalid function declaration reference, unknown function ${accessorName.text}`,
1701
2026
  accessorName,
1702
2027
  );
1703
- if (manager.funcDecls[accessor].op !== OP_DT_ACCESSOR)
1704
- throw new SmtUnsupportedError("the operator update-field");
1705
- return mkApp(mkUpdateField(manager, accessor), args, at);
2028
+ // datatype::decl::plugin::mk_update_field.
2029
+ if (args.length !== 2)
2030
+ throw new SmtParseError("invalid number of arguments for datatype field update", at);
2031
+ const funcDecl = manager.funcDecls[accessor];
2032
+ if (funcDecl.op !== OP_DT_ACCESSOR)
2033
+ throw new SmtParseError(
2034
+ "datatype field update requires a datatype accessor as the second argument",
2035
+ at,
2036
+ );
2037
+ if (funcDecl.domain[0] !== manager.sorts[args[0]])
2038
+ throw new SmtParseError("first argument to field update should be a data-type", at);
2039
+ if (funcDecl.range !== manager.sorts[args[1]])
2040
+ throw new SmtParseError(
2041
+ `second argument to field update should be ${manager.getSortName(funcDecl.range)} instead of ${manager.getSortName(manager.sorts[args[1]])}`,
2042
+ at,
2043
+ );
2044
+ return manager.mkApp(mkUpdateField(manager, accessor), args, funcDecl.domain[0]);
1706
2045
  };
1707
2046
 
1708
2047
  const getUnknownConstantMessage = (name: string, args: number[], range: number | undefined) => {
@@ -1735,14 +2074,7 @@ export const createSmtlibReader = (
1735
2074
  throw new SmtUnsupportedError("the declaration reference");
1736
2075
  const domain = domainList.items.map((item) => parseSort(item, "Invalid function name"));
1737
2076
  const range = parseSort(rangeSort, "Invalid function name");
1738
- const declared = funcs
1739
- .get(name.text)
1740
- ?.find(
1741
- (decl) =>
1742
- manager.funcDecls[decl].range === range &&
1743
- manager.funcDecls[decl].domain.length === domain.length &&
1744
- manager.funcDecls[decl].domain.every((sort, index) => sort === domain[index]),
1745
- );
2077
+ const declared = funcs.get(name.text)?.find((decl) => hasSignature(decl, domain, range));
1746
2078
  if (declared !== undefined) return { decl: declared, domain, range };
1747
2079
  const builtin = CHAINABLE_OPS.get(name.text) ?? BUILTIN_OPS.get(name.text);
1748
2080
  if (builtin === undefined)
@@ -1781,10 +2113,11 @@ export const createSmtlibReader = (
1781
2113
  ) => {
1782
2114
  const name = head.text;
1783
2115
  // A bound variable applied to arguments selects from the array it stands for, one at a time.
1784
- if (args.length > 0 && lookup(name) !== undefined)
2116
+ const local = locals.get(name);
2117
+ if (args.length > 0 && local !== undefined)
1785
2118
  return args.reduce(
1786
2119
  (array, arg) => mkArrayTerm(OP_SELECT, [array, arg], [], at),
1787
- parseLeaf(head),
2120
+ getLocalTerm(local),
1788
2121
  );
1789
2122
  if (indices.length > 0)
1790
2123
  return isFpaOpName(name)
@@ -1793,19 +2126,31 @@ export const createSmtlibReader = (
1793
2126
  ? mkSeqTerm(name, args, indices, at)
1794
2127
  : mkBvApp(name, args, indices, at);
1795
2128
  const macro = macros.get(name);
1796
- // macros_find: a macro of another arity leaves the name to a declaration.
1797
- if (macro !== undefined && (macro.domain.length === args.length || !funcs.has(name))) {
1798
- const coerced = args.map((arg, index) => coerce(arg, macro.domain[index]));
1799
- if (
1800
- coerced.length !== macro.domain.length ||
1801
- coerced.some((arg, index) => manager.sorts[arg] !== macro.domain[index])
2129
+ // macros_find: a macro takes its own sorts, and Int for Real or Real for Int. Any other
2130
+ // application leaves the name to a declaration.
2131
+ if (
2132
+ macro !== undefined &&
2133
+ macro.domain.length === args.length &&
2134
+ args.every(
2135
+ (arg, index) =>
2136
+ manager.sorts[arg] === macro.domain[index] ||
2137
+ (isArithSort(manager.sorts[arg]) && isArithSort(macro.domain[index])),
1802
2138
  )
1803
- throw new SmtParseError(`ill-sorted application of ${name}`, at);
1804
- return expandMacro(macro, coerced);
1805
- }
2139
+ )
2140
+ return expandMacro(
2141
+ macro,
2142
+ args.map((arg, index) => coerce(arg, macro.domain[index])),
2143
+ );
1806
2144
  const decls = funcs.get(name);
1807
2145
  const declared = decls === undefined ? undefined : mkDeclaredApp(name, decls, args, range, at);
1808
2146
  if (declared !== undefined) return declared;
2147
+ // cmd_context::mk_app: a constant that starts with #f is a finite-field literal.
2148
+ if (args.length === 0 && name.startsWith("#f")) {
2149
+ if (!FF_LITERAL.test(name))
2150
+ throw new SmtParseError("invalid finite-field literal, expected #f<integer>m<prime>", at);
2151
+ if (!restricted.hasFf) throw new SmtParseError("logic does not support finite fields", at);
2152
+ throw new SmtUnsupportedError("finite-field literals");
2153
+ }
1809
2154
  if (isSeqOpName(name)) return mkSeqTerm(name, args, indices, at, range);
1810
2155
  if (range !== undefined)
1811
2156
  throw new SmtParseError(getUnknownConstantMessage(name, args, range), at);
@@ -1820,56 +2165,30 @@ export const createSmtlibReader = (
1820
2165
  const transcendentalOp = isTranscendental ? TRANSCENDENTAL_OPS.get(builtin) : undefined;
1821
2166
  if (isTranscendental && transcendentalOp === undefined)
1822
2167
  throw new SmtUnsupportedError(`the operator ${name}`);
1823
- const chainable = CHAINABLE_OPS.get(builtin);
1824
- const arithOp =
1825
- chainable ?? (builtin === "~" ? OP_UMINUS : (BUILTIN_OPS.get(builtin) ?? transcendentalOp));
2168
+ const named =
2169
+ builtin === "~"
2170
+ ? OP_UMINUS
2171
+ : (CHAINABLE_OPS.get(builtin) ?? BUILTIN_OPS.get(builtin) ?? transcendentalOp);
1826
2172
  if (
1827
2173
  args.length === 0 &&
1828
- arithOp !== undefined &&
1829
- manager.funcDecls[arithOp].family === FAMILY_ARITH
2174
+ named !== undefined &&
2175
+ manager.funcDecls[named].family === FAMILY_ARITH
1830
2176
  )
1831
2177
  throw new SmtParseError("no arguments supplied to arithmetical operator", head);
1832
- if (chainable === OP_EQ && args.length < 2)
1833
- throw new SmtParseError(
1834
- getUnknownConstantMessage(name, args, undefined),
1835
- args.length === 0 ? head : at,
1836
- );
1837
- if (chainable !== undefined) return mkChain(chainable, args, at);
1838
- if (builtin === "~") return mkApp(OP_UMINUS, args, at);
1839
- if (builtin === "-" && args.length === 1) return mkApp(OP_UMINUS, args, at);
1840
- const op = BUILTIN_OPS.get(builtin) ?? transcendentalOp;
1841
- if (op === undefined) {
1842
- if (THEORY_OPERATOR.test(name) || THEORY_OPERATORS.has(name))
1843
- throw new SmtUnsupportedError(`the operator ${name}`);
1844
- const instance = mkDatatypeInstanceApp(name, args, at);
1845
- if (instance !== undefined) return instance;
1846
- throw new SmtParseError(
1847
- getUnknownConstantMessage(name, args, undefined),
1848
- args.length === 0 ? head : at,
1849
- );
1850
- }
1851
- // xor is associative, so ast_manager::mk_app takes fewer than two arguments, which
1852
- // bool_rewriter reduces to false or the argument.
1853
- if (op === OP_XOR && args.length < 2) {
1854
- if (args.some((arg) => manager.sorts[arg] !== SORT_BOOL))
1855
- throw new SmtParseError(`ill-sorted application of ${name}`, at);
1856
- return args[0] ?? manager.falseExpr;
1857
- }
1858
- if (args.length <= 2 || !NESTED_OPS.has(op)) return mkApp(op, args, at);
1859
- const domainSort = getDomainSort(op, args);
1860
- return op === OP_XOR || op === OP_IMPLIES
1861
- ? args
1862
- .slice(0, -1)
1863
- .reduceRight(
1864
- (right, left) => mkApp(op, [left, right], at, domainSort),
1865
- args[args.length - 1],
1866
- )
1867
- : args.slice(1).reduce((left, right) => mkApp(op, [left, right], at, domainSort), args[0]);
2178
+ // arith_decl_plugin::fix_kind.
2179
+ const op = named === OP_SUB && args.length === 1 ? OP_UMINUS : named;
2180
+ const domainSort = op === undefined ? -1 : getDomainSort(op, args, at);
2181
+ if (op !== undefined && domainSort !== -1) return mkApp(op, args, at, domainSort);
2182
+ if (op === undefined && (THEORY_OPERATOR.test(name) || THEORY_OPERATORS.has(name)))
2183
+ throw new SmtUnsupportedError(`the operator ${name}`);
2184
+ const instance = mkDatatypeInstanceApp(name, args, at);
2185
+ if (instance !== undefined) return instance;
2186
+ throw new SmtParseError(getUnknownConstantMessage(name, args, undefined), at);
1868
2187
  };
1869
2188
 
1870
- const parseLeaf = (sexpr: SExpr): number => {
2189
+ const parseLeaf = (sexpr: SmtToken): number => {
1871
2190
  if (sexpr.kind === "numeral")
1872
- return isNumeralAsReal
2191
+ return restricted.isNumeralAsReal
1873
2192
  ? manager.mkRealNumeral(Rational.of(BigInt(sexpr.text), 1n))
1874
2193
  : manager.mkNumeral(BigInt(sexpr.text));
1875
2194
  if (sexpr.kind === "decimal") {
@@ -1888,222 +2207,452 @@ export const createSmtlibReader = (
1888
2207
  }
1889
2208
  if (sexpr.kind === "string") return manager.mkString(parseZstring(sexpr.text, manager.maxChar));
1890
2209
  if (sexpr.kind === "symbol") {
2210
+ const local = locals.get(sexpr.text);
2211
+ if (local !== undefined) return getLocalTerm(local);
1891
2212
  if (sexpr.text === "true") return manager.trueExpr;
1892
2213
  if (sexpr.text === "false") return manager.falseExpr;
1893
- const binding = lookup(sexpr.text);
1894
- if (binding?.kind === "var")
1895
- return manager.mkVar(binders.depth - 1 - binding.depth, binding.sort);
1896
- // Z3's var_shifter moves the free variables of a let binding up by the binders since. Its cache
1897
- // holds the terms it makes, but this parser holds no references, so it rebuilds the binding
1898
- // with replaceFreeVars.
1899
- if (binding !== undefined)
1900
- return binders.depth === binding.depth
1901
- ? binding.expr
1902
- : replaceFreeVars(manager, binding.expr, (variable, index, shift) =>
1903
- manager.mkVar(index + shift + binders.depth - binding.depth, manager.sorts[variable]),
1904
- );
1905
2214
  return parseApp(sexpr, [], sexpr);
1906
2215
  }
1907
- if (sexpr.kind !== "list") throw new SmtParseError("invalid expression", sexpr);
1908
- const head = sexpr.items[0];
1909
- if (isSymbol(head, "forall") || isSymbol(head, "exists") || isSymbol(head, "lambda"))
1910
- return parseQuantifier(
1911
- sexpr,
1912
- head.text === "forall"
1913
- ? QUANTIFIER_FORALL
1914
- : head.text === "exists"
1915
- ? QUANTIFIER_EXISTS
1916
- : QUANTIFIER_LAMBDA,
1917
- );
1918
- if (isSymbol(head, "let")) return parseLet(sexpr);
1919
- // Each attribute applies to the expression the attributes before it made.
1920
- return sexpr.items.slice(2).reduce(
1921
- (annotated, keyword, index, attributes) => {
1922
- if (keyword.kind !== "keyword") return annotated;
1923
- const value = attributes[index + 1];
1924
- if (keyword.text === ":lblpos" || keyword.text === ":lblneg")
1925
- return mkLabel(annotated, keyword.text === ":lblpos", value, sexpr);
1926
- if (keyword.text !== ":named") return annotated;
1927
- const name = expectSymbol(value, "invalid attribute value, symbol expected", sexpr).text;
1928
- manager.incRef(annotated);
1929
- lastNamed.name = name;
1930
- lastNamed.expr = annotated;
1931
- manager.mkMacro(name, annotated);
1932
- declare(macros, name, { domain: [], range: manager.sorts[annotated], body: annotated });
1933
- return annotated;
1934
- },
1935
- parseTerm(sexpr.items[1] ?? sexpr.end),
2216
+ throw new SmtParseError(
2217
+ sexpr.kind === "keyword"
2218
+ ? "invalid expression, unexpected keyword"
2219
+ : "invalid expression, unexpected ')'",
2220
+ sexpr,
1936
2221
  );
1937
2222
  };
1938
2223
 
1939
- const mkLabel = (expr: number, isPositive: boolean, value: SExpr | undefined, at: SExpr) => {
1940
- const name = expectSymbol(value, "invalid attribute value, symbol expected", at).text;
1941
- if (manager.sorts[expr] !== SORT_BOOL)
1942
- throw new SmtParseError("invalid labeled expression, expression must have Bool sort", at);
1943
- return manager.mkLabel(isPositive, [name], expr);
1944
- };
1945
-
1946
- const parseTerm = (sexpr: SExpr): number => {
1947
- const frames: ApplicationFrame[] = [];
1948
- const results: number[] = [];
1949
- const enter = (current: SExpr) => {
2224
+ // name_expr and cmd_context::insert of a named term. Z3 reports an error at the token after the
2225
+ // name.
2226
+ const nameExpr = (expr: number, name: string, at: SExpr) => {
2227
+ if (manager.freeVarBounds[expr] > 0)
2228
+ throw new SmtParseError("invalid named expression, expression contains free variables", at);
2229
+ if (macros.get(name)?.domain.length === 0)
2230
+ throw new SmtParseError("named expression already defined", at);
2231
+ if ((funcs.get(name) ?? []).some((decl) => hasSignature(decl, [], manager.sorts[expr])))
2232
+ throw new SmtParseError(
2233
+ `invalid named expression, declaration already defined with this name ${name}`,
2234
+ at,
2235
+ );
2236
+ manager.incRef(expr);
2237
+ lastNamed.name = name;
2238
+ lastNamed.expr = expr;
2239
+ manager.mkMacro(name, expr);
2240
+ declare(macros, name, { domain: [], range: manager.sorts[expr], body: expr });
2241
+ };
2242
+
2243
+ // push_app_frame's parse_qualified_identifier_core, on a head that is (_ <symbol> <index>*) or
2244
+ // (as <identifier> <sort>).
2245
+ const parseQualifiedHead = (list: SmtList, head: SmtList): QualifiedHead => {
2246
+ if (isSymbol(head.items[0], "as")) {
2247
+ const range = parseQualifierSort(head);
2248
+ const target = head.items[1];
2249
+ if (!isSymbol(target)) throw new SmtUnsupportedError("indexed and qualified identifiers");
2250
+ return {
2251
+ head: target,
2252
+ indices: [],
2253
+ build:
2254
+ hasArrays && target.text === "const"
2255
+ ? (args) => mkArrayTerm(OP_CONST_ARRAY, args, [range], list.end)
2256
+ : (args) => parseApp(target, args, list.end, [], range),
2257
+ };
2258
+ }
2259
+ const name = getIndexedName(head);
2260
+ const indices = head.items.slice(2);
2261
+ const indexed = indices[0];
2262
+ if (hasArrays && hasArrayExtensions && name.text === "map" && indices.length === 1) {
2263
+ const mapped = parseFuncDeclRef(indexed);
2264
+ return { head: name, indices: [], build: (args) => mkMapTerm(mapped, args, list.end) };
2265
+ }
2266
+ if ((name.text === "is" || name.text === "update-field") && indices.length === 1) {
2267
+ if (!isSymbol(indexed)) throw new SmtUnsupportedError("indexed and qualified identifiers");
2268
+ return {
2269
+ head: name,
2270
+ indices: [],
2271
+ build: (args) =>
2272
+ name.text === "is"
2273
+ ? mkIsApp(indexed, args, list.end)
2274
+ : mkUpdateFieldApp(indexed, args, list.end),
2275
+ };
2276
+ }
2277
+ const isNumbered = indices.every((index) => index.kind === "numeral");
2278
+ if (isNumbered && isPbOpName(name.text)) {
2279
+ const parameters = indices.map((index) =>
2280
+ Rational.of(BigInt(index.kind === "list" ? 0 : index.text)),
2281
+ );
2282
+ return {
2283
+ head: name,
2284
+ indices: [],
2285
+ build: (args) => mkPbTerm(name.text, args, parameters, list.end),
2286
+ };
2287
+ }
2288
+ if (isNumbered && (isBvOpName(name.text) || isFpaOpName(name.text) || isSeqOpName(name.text)))
2289
+ return {
2290
+ head: name,
2291
+ indices: indices.map((index) => (index.kind === "list" ? 0 : Number(index.text))),
2292
+ };
2293
+ // cmd_context::mk_app finds a name that no theory knows among the declarations, whatever its
2294
+ // indices are.
2295
+ if (isKnownOperator(name.text) || !indices.every(isSimpleIndex))
2296
+ throw new SmtUnsupportedError("indexed and qualified identifiers");
2297
+ return { head: name, indices: [] };
2298
+ };
2299
+
2300
+ // parse_expr. Z3 leaves the term on its stack until the command ends. A tail term is one whose
2301
+ // value is the value of the whole: it stays off the stack, in parsed, so that the caller of
2302
+ // parseTerm can have a term that nothing else holds without a reference of the parser's.
2303
+ const runTerm = (sexpr: SExpr, isRootTail: boolean) => {
2304
+ const root = sexpr.kind === "list" ? sexpr.root : undefined;
2305
+ if (root === undefined || root === parsed.root) protect(floating);
2306
+ else {
2307
+ releasePending();
2308
+ shrink(floating, 0);
2309
+ parsed.root = root;
2310
+ }
2311
+ protect(unrooted);
2312
+ const frames: TermFrame[] = [];
2313
+ // The value of a frame replaces what the frame left on the stack. Z3 holds it in an expr_ref
2314
+ // meanwhile.
2315
+ const deliver = (expr: number, isTail: boolean, start: number) => {
2316
+ const isOwned = !isTail || manager.getRefCount(expr) > 0;
2317
+ if (isOwned) manager.incRef(expr);
2318
+ shrinkRefs(exprStack, start);
2319
+ if (!isTail) {
2320
+ exprStack.push(expr);
2321
+ return;
2322
+ }
2323
+ parsed.expr = expr;
2324
+ parsed.isOwned = isOwned;
2325
+ };
2326
+ // push_pattern_frame.
2327
+ const enterPattern = (value: SExpr, frame: AttributeFrame) => {
2328
+ if (value.kind !== "list") {
2329
+ if (!options.isIgnoringBadPatterns)
2330
+ throw new SmtParseError("invalid pattern, '(' expected", value);
2331
+ // Z3 skips a bad pattern as an s-expression, which cannot start with ')'.
2332
+ if (value.kind === ")")
2333
+ throw new SmtParseError("invalid s-expression, unexpected ')'", value);
2334
+ frame.next++;
2335
+ exprStack.push(-1);
2336
+ return;
2337
+ }
2338
+ frame.next++;
2339
+ const first = value.items[0];
2340
+ if (first === undefined) {
2341
+ exprStack.push(-1);
2342
+ return;
2343
+ }
2344
+ if (first.kind === "list") {
2345
+ frames.push({ kind: "pattern", list: value, start: exprStack.length, next: 0 });
2346
+ return;
2347
+ }
2348
+ const decl = first.text === "true" || first.text === "false" ? -1 : getFirstFunc(first.text);
2349
+ if (decl === -1 || (decl !== undefined && manager.funcDecls[decl].domain.length === 0)) {
2350
+ if (!options.isIgnoringBadPatterns)
2351
+ throw new SmtParseError("invalid constant pattern", first);
2352
+ exprStack.push(-1);
2353
+ return;
2354
+ }
2355
+ if (first.kind !== "symbol")
2356
+ throw new SmtParseError("invalid pattern, '(' or identifier expected", first);
2357
+ frames.push({
2358
+ kind: "application",
2359
+ list: value,
2360
+ head: first,
2361
+ indices: [],
2362
+ isTail: false,
2363
+ start: exprStack.length,
2364
+ next: 1,
2365
+ });
2366
+ };
2367
+ const enter = (current: SExpr, isTail: boolean) => {
1950
2368
  if (current.kind !== "list") {
1951
- results.push(parseLeaf(current));
2369
+ deliver(parseLeaf(current), isTail, exprStack.length);
1952
2370
  return;
1953
2371
  }
1954
2372
  const head = current.items[0];
1955
- if (head === undefined)
1956
- throw new SmtParseError("invalid expression, unexpected ')'", current.end);
2373
+ if (head === undefined || (head.kind !== "symbol" && head.kind !== "list"))
2374
+ throw new SmtParseError("invalid expression, '(' or symbol expected", head ?? current.end);
1957
2375
  if (head.kind === "list") {
1958
- const name = head.items[1];
1959
- const indices = head.items.slice(2);
1960
- if (
1961
- hasArrays &&
1962
- isSymbol(head.items[0], "as") &&
1963
- isSymbol(name, "const") &&
1964
- head.items.length === 3
1965
- ) {
1966
- const sort = parseSort(head.items[2], "");
1967
- frames.push({
1968
- head: name,
1969
- indices: [],
1970
- build: (args) => mkArrayTerm(OP_CONST_ARRAY, args, [sort], current.end),
1971
- list: current,
1972
- start: results.length,
1973
- next: 1,
1974
- });
1975
- return;
1976
- }
1977
- if (
1978
- hasArrays &&
1979
- hasArrayExtensions &&
1980
- isSymbol(head.items[0], "_") &&
1981
- isSymbol(name, "map") &&
1982
- head.items.length === 3
1983
- ) {
1984
- const mapped = parseFuncDeclRef(head.items[2]);
1985
- frames.push({
1986
- head: name,
1987
- indices: [],
1988
- build: (args) => mkMapTerm(mapped, args, current.end),
1989
- list: current,
1990
- start: results.length,
1991
- next: 1,
1992
- });
1993
- return;
1994
- }
1995
- const indexed = head.items[2];
1996
- if (
1997
- isSymbol(head.items[0], "_") &&
1998
- (isSymbol(name, "is") || isSymbol(name, "update-field")) &&
1999
- isSymbol(indexed) &&
2000
- head.items.length === 3
2001
- ) {
2002
- frames.push({
2003
- head: name,
2004
- indices: [],
2005
- build: (args) =>
2006
- name.text === "is"
2007
- ? mkIsApp(indexed, args, current.end)
2008
- : mkUpdateFieldApp(indexed, args, current.end),
2009
- list: current,
2010
- start: results.length,
2011
- next: 1,
2012
- });
2013
- return;
2014
- }
2015
- if (isSymbol(head.items[0], "as") && isSymbol(name) && head.items.length === 3) {
2016
- const range = parseSort(head.items[2], "Invalid qualified identifier");
2017
- frames.push({
2018
- head: name,
2019
- indices: [],
2020
- build: (args) => parseApp(name, args, current.end, [], range),
2021
- list: current,
2022
- start: results.length,
2023
- next: 1,
2024
- });
2025
- return;
2026
- }
2027
- if (
2028
- isSymbol(head.items[0], "_") &&
2029
- isSymbol(name) &&
2030
- isPbOpName(name.text) &&
2031
- indices.every((index) => index.kind === "numeral")
2032
- ) {
2033
- const parameters = indices.map((index) =>
2034
- Rational.of(BigInt(index.kind === "list" ? 0 : index.text)),
2035
- );
2036
- frames.push({
2037
- head: name,
2038
- indices: [],
2039
- build: (args) => mkPbTerm(name.text, args, parameters, current.end),
2040
- list: current,
2041
- start: results.length,
2042
- next: 1,
2043
- });
2044
- return;
2045
- }
2046
- if (
2047
- !isSymbol(head.items[0], "_") ||
2048
- !isSymbol(name) ||
2049
- !(isBvOpName(name.text) || isFpaOpName(name.text) || isSeqOpName(name.text)) ||
2050
- !indices.every((index) => index.kind === "numeral")
2051
- )
2376
+ // push_app_frame: Z3 reads a head that is neither indexed nor qualified as a term.
2377
+ if (isSymbol(head.items[0], "lambda"))
2052
2378
  throw new SmtUnsupportedError("indexed and qualified identifiers");
2379
+ frames.push(
2380
+ isSymbol(head.items[0], "_") || isSymbol(head.items[0], "as")
2381
+ ? {
2382
+ kind: "application",
2383
+ list: current,
2384
+ ...parseQualifiedHead(current, head),
2385
+ isTail,
2386
+ start: exprStack.length,
2387
+ next: 1,
2388
+ }
2389
+ : { kind: "selection", list: current, isTail, start: exprStack.length, next: 0 },
2390
+ );
2391
+ return;
2392
+ }
2393
+ if (head.text === "_" || head.text === "as") {
2394
+ deliver(parseQualifiedName(current), isTail, exprStack.length);
2395
+ return;
2396
+ }
2397
+ if (head.text === "root-obj") {
2398
+ deliver(parseRootObj(current), isTail, exprStack.length);
2399
+ return;
2400
+ }
2401
+ if (head.text === "match") throw new SmtUnsupportedError("the expression match");
2402
+ if (head.text === "let") {
2403
+ const bindings = current.items[1];
2404
+ if (bindings?.kind !== "list")
2405
+ throw new SmtParseError(
2406
+ `invalid let declaration, '(' expected got ${getLastId(bindings) ?? "let"}`,
2407
+ bindings ?? current.end,
2408
+ );
2053
2409
  frames.push({
2054
- head: name,
2055
- indices: indices.map((index) => (index.kind === "list" ? 0 : Number(index.text))),
2410
+ kind: "let",
2056
2411
  list: current,
2057
- start: results.length,
2058
- next: 1,
2412
+ bindings,
2413
+ names: [],
2414
+ isInDecls: true,
2415
+ isTail,
2416
+ start: exprStack.length,
2417
+ next: 0,
2059
2418
  });
2060
2419
  return;
2061
2420
  }
2062
- if (head.kind !== "symbol")
2063
- throw new SmtParseError("invalid function application, symbol expected", head);
2064
- if (head.text === "_") {
2065
- results.push(parseBvNumeral(current));
2066
- return;
2067
- }
2068
- const qualified = current.items[1];
2069
- if (head.text === "as" && isSymbol(qualified) && current.items.length === 3) {
2070
- results.push(
2071
- parseApp(
2072
- qualified,
2073
- [],
2074
- qualified,
2075
- [],
2076
- parseSort(current.items[2], "Invalid qualified identifier"),
2077
- ),
2078
- );
2421
+ if (head.text === "!") {
2422
+ const parent = frames[frames.length - 1];
2423
+ frames.push({
2424
+ kind: "attribute",
2425
+ list: current,
2426
+ quantifier: parent?.kind === "quantifier" ? parent : undefined,
2427
+ lastKeyword: "",
2428
+ isTail,
2429
+ start: exprStack.length,
2430
+ next: 1,
2431
+ });
2079
2432
  return;
2080
2433
  }
2081
- if (head.text === "root-obj") {
2082
- results.push(parseRootObj(current));
2434
+ const quantifierKind = QUANTIFIER_KINDS.get(head.text);
2435
+ if (quantifierKind === undefined) {
2436
+ frames.push({
2437
+ kind: "application",
2438
+ list: current,
2439
+ head,
2440
+ indices: [],
2441
+ isTail,
2442
+ start: exprStack.length,
2443
+ next: 1,
2444
+ });
2083
2445
  return;
2084
2446
  }
2085
- if (head.text === "as" || head.text === "match")
2086
- throw new SmtUnsupportedError(`the expression ${head.text}`);
2087
- if (["forall", "exists", "lambda", "let", "!"].includes(head.text))
2088
- results.push(parseLeaf(current));
2089
- else frames.push({ head, indices: [], list: current, start: results.length, next: 1 });
2447
+ // push_quant_frame.
2448
+ const start = exprStack.length;
2449
+ const bound = bindSortedVars(current.items[1], current.end, head.text);
2450
+ if (bound.varSorts.length === 0)
2451
+ throw new SmtParseError(
2452
+ "invalid quantifier, list of sorted variables is empty",
2453
+ current.items[2] ?? current.end,
2454
+ );
2455
+ frames.push({
2456
+ kind: "quantifier",
2457
+ list: current,
2458
+ quantifierKind,
2459
+ names: bound.names,
2460
+ varSorts: bound.varSorts,
2461
+ weight: 1,
2462
+ qid: "",
2463
+ skid: undefined,
2464
+ isTail,
2465
+ start,
2466
+ patternStart: patternStack.length,
2467
+ noPatternStart: noPatternStack.length,
2468
+ next: 2,
2469
+ });
2090
2470
  };
2091
- enter(sexpr);
2471
+ enter(sexpr, isRootTail);
2092
2472
  while (frames.length > 0) {
2093
2473
  const frame = frames[frames.length - 1];
2094
- if (frame.next < frame.list.items.length) {
2095
- enter(frame.list.items[frame.next++]);
2474
+ if (frame.kind === "let") {
2475
+ if (frame.isInDecls) {
2476
+ const declaration = frame.bindings.items[frame.next];
2477
+ if (declaration !== undefined) {
2478
+ // push_let_decl_frame.
2479
+ if (declaration.kind !== "list")
2480
+ throw new SmtParseError(
2481
+ `invalid let declaration, '(' expected got ${getLastId(declaration) ?? getLastIdBefore(frame.bindings.items, frame.next) ?? "let"}`,
2482
+ declaration,
2483
+ );
2484
+ const name = declaration.items[0];
2485
+ if (!isSymbol(name)) throw new SmtParseError(LET_MESSAGE, name ?? declaration.end);
2486
+ frame.names.push(name.text);
2487
+ frame.next++;
2488
+ frames.push({ kind: "let-decl", list: declaration, next: 1 });
2489
+ continue;
2490
+ }
2491
+ // pop_let_frame at the end of the declarations.
2492
+ if (frame.names.length !== exprStack.length - frame.start)
2493
+ throw new SmtParseError("malformed let expression", frame.bindings.end);
2494
+ beginScope();
2495
+ for (const [index, name] of frame.names.entries())
2496
+ insertLocal(name, exprStack[frame.start + index]);
2497
+ frame.isInDecls = false;
2498
+ frame.next = 2;
2499
+ continue;
2500
+ }
2501
+ const body = frame.list.items[frame.next];
2502
+ if (body !== undefined) {
2503
+ frame.next++;
2504
+ enter(body, frame.isTail && frame.next === frame.list.items.length);
2505
+ continue;
2506
+ }
2507
+ frames.pop();
2508
+ // Z3 takes the last expression on its stack, so a let without a body is its last binding.
2509
+ if (frame.isTail && frame.list.items.length > 2) shrinkRefs(exprStack, frame.start);
2510
+ else if (exprStack.length === frame.start)
2511
+ throw new SmtParseError("invalid let expression", frame.list.end);
2512
+ else deliver(exprStack[exprStack.length - 1], frame.isTail, frame.start);
2513
+ endScope();
2514
+ continue;
2515
+ }
2516
+ const items = frame.list.items;
2517
+ if (frame.kind === "attribute") {
2518
+ // consume_attributes.
2519
+ if (exprStack.length === frame.start) {
2520
+ if (frame.next >= items.length)
2521
+ throw new SmtParseError("invalid expression", frame.list.end);
2522
+ enter(items[frame.next++], false);
2523
+ continue;
2524
+ }
2525
+ // process_last_symbol.
2526
+ const last = exprStack[exprStack.length - 1];
2527
+ if (frame.lastKeyword === ":pattern") {
2528
+ const at = items[frame.next] ?? frame.list.end;
2529
+ if (last === -1 && !options.isIgnoringBadPatterns)
2530
+ throw new SmtParseError("invalid empty pattern", at);
2531
+ if (last !== -1)
2532
+ pushRef(
2533
+ patternStack,
2534
+ manager.kinds[last] === KIND_APP && manager.decls[last] === OP_PATTERN
2535
+ ? last
2536
+ : mkPattern([last], at),
2537
+ );
2538
+ shrinkRefs(exprStack, exprStack.length - 1);
2539
+ } else if (frame.lastKeyword === ":no-pattern") {
2540
+ pushRef(noPatternStack, last);
2541
+ shrinkRefs(exprStack, exprStack.length - 1);
2542
+ }
2543
+ frame.lastKeyword = "";
2544
+ if (frame.next >= items.length) {
2545
+ frames.pop();
2546
+ if (frame.isTail) deliver(exprStack[exprStack.length - 1], true, frame.start);
2547
+ continue;
2548
+ }
2549
+ while (frame.next < items.length && frame.lastKeyword === "") {
2550
+ const keyword = items[frame.next];
2551
+ if (keyword.kind !== "keyword")
2552
+ throw new SmtParseError("invalid attributed expression, keyword expected", keyword);
2553
+ const value = items[frame.next + 1] ?? frame.list.end;
2554
+ const annotated = exprStack[exprStack.length - 1];
2555
+ const quantifier = frame.quantifier;
2556
+ if (keyword.text === ":named") {
2557
+ if (!isSymbol(value))
2558
+ throw new SmtParseError("invalid attribute value, symbol expected", value);
2559
+ nameExpr(annotated, value.text, items[frame.next + 2] ?? frame.list.end);
2560
+ frame.next += 2;
2561
+ } else if (keyword.text === ":lblpos" || keyword.text === ":lblneg") {
2562
+ if (!isSymbol(value))
2563
+ throw new SmtParseError("invalid attribute value, symbol expected", value);
2564
+ if (manager.sorts[annotated] !== SORT_BOOL)
2565
+ throw new SmtParseError(
2566
+ "invalid labeled expression, expression must have Bool sort",
2567
+ value,
2568
+ );
2569
+ deliver(
2570
+ manager.mkLabel(keyword.text === ":lblpos", [value.text], annotated),
2571
+ false,
2572
+ exprStack.length - 1,
2573
+ );
2574
+ frame.next += 2;
2575
+ } else if (!QUANTIFIER_ATTRIBUTES.has(keyword.text)) {
2576
+ // Z3 warns of an unknown attribute and skips its value as an s-expression.
2577
+ if (value.kind === ")")
2578
+ throw new SmtParseError("invalid s-expression, unexpected ')'", value);
2579
+ frame.next += 2;
2580
+ } else if (quantifier === undefined)
2581
+ throw new SmtParseError("invalid attribute, not in the scope of a quantifier", keyword);
2582
+ else if (keyword.text === ":weight") {
2583
+ // check_int, and curr_unsigned.
2584
+ if (value.kind !== "numeral")
2585
+ throw new SmtParseError("invalid weight attribute, integer expected", value);
2586
+ if (!isUnsigned(value.text))
2587
+ throw new SmtParseError(
2588
+ "invalid indexed identifier, index is too big to fit in an unsigned machine integer",
2589
+ value,
2590
+ );
2591
+ quantifier.weight = Number(value.text);
2592
+ frame.next += 2;
2593
+ } else if (keyword.text === ":skolemid" || keyword.text === ":qid") {
2594
+ if (!isSymbol(value))
2595
+ throw new SmtParseError("invalid attribute value, symbol expected", value);
2596
+ if (keyword.text === ":qid") quantifier.qid = value.text;
2597
+ else quantifier.skid = value.text;
2598
+ frame.next += 2;
2599
+ } else {
2600
+ frame.lastKeyword = keyword.text;
2601
+ frame.next++;
2602
+ if (keyword.text === ":pattern") enterPattern(value, frame);
2603
+ else if (value.kind === ")")
2604
+ throw new SmtParseError("invalid expression, unexpected input", value);
2605
+ else enter(items[frame.next++], false);
2606
+ }
2607
+ }
2608
+ continue;
2609
+ }
2610
+ if (frame.next < items.length) {
2611
+ enter(items[frame.next++], false);
2096
2612
  continue;
2097
2613
  }
2098
2614
  frames.pop();
2099
- if (frame.list.items.length === 1)
2615
+ if (frame.kind === "let-decl") continue;
2616
+ if (frame.kind === "pattern") {
2617
+ deliver(mkPattern(exprStack.slice(frame.start), frame.list.end), false, frame.start);
2618
+ continue;
2619
+ }
2620
+ if (frame.kind === "quantifier") {
2621
+ // pop_quant_frame.
2622
+ deliver(mkParsedQuantifier(frame), frame.isTail, frame.start);
2623
+ shrinkRefs(patternStack, frame.patternStart);
2624
+ shrinkRefs(noPatternStack, frame.noPatternStart);
2625
+ unbindSortedVars(frame.varSorts.length);
2626
+ continue;
2627
+ }
2628
+ // pop_app_frame.
2629
+ const args = exprStack.slice(frame.start);
2630
+ if (args.length < (frame.kind === "selection" ? 2 : 1))
2100
2631
  throw new SmtParseError("invalid function application, arguments missing", frame.list.end);
2101
- const args = results.splice(frame.start);
2102
- results.push(
2103
- frame.build?.(args) ?? parseApp(frame.head, args, frame.list.end, frame.indices),
2632
+ deliver(
2633
+ frame.kind === "selection"
2634
+ ? args
2635
+ .slice(1)
2636
+ .reduce(
2637
+ (array, arg) => mkArrayTerm(OP_SELECT, [array, arg], [], frame.list.end),
2638
+ args[0],
2639
+ )
2640
+ : (frame.build?.(args) ?? parseApp(frame.head, args, frame.list.end, frame.indices)),
2641
+ frame.isTail,
2642
+ frame.start,
2104
2643
  );
2105
2644
  }
2106
- return results[0];
2645
+ };
2646
+
2647
+ const parseTerm = (sexpr: SExpr) => {
2648
+ runTerm(sexpr, true);
2649
+ const expr = parsed.expr;
2650
+ parsed.expr = -1;
2651
+ if (!parsed.isOwned)
2652
+ (sexpr.kind === "list" && sexpr.root !== undefined ? floating : unrooted).push(expr);
2653
+ else if (manager.getRefCount(expr) > 1) manager.decRef(expr);
2654
+ else pending.push(expr);
2655
+ return expr;
2107
2656
  };
2108
2657
 
2109
2658
  const parseDomain = (sexpr: SExpr | undefined, at: SExpr) => {
@@ -2381,14 +2930,15 @@ export const createSmtlibReader = (
2381
2930
  );
2382
2931
  };
2383
2932
 
2384
- // parse_rec_fun_decl: the variables are bound only while the range is parsed.
2933
+ // parse_rec_fun_decl: the variables are bound only while the range is parsed, and Z3 holds them
2934
+ // until the command ends, as the stack does here.
2385
2935
  const declareRecFun = (items: SExpr[], at: SExpr) => {
2386
2936
  const symbol = expectSymbol(
2387
2937
  items[0],
2388
2938
  "invalid function/constant definition, symbol expected",
2389
2939
  at,
2390
2940
  );
2391
- const bound = bindSortedVars(items[1], at);
2941
+ const bound = bindSortedVars(items[1], at, symbol.text);
2392
2942
  const range = parseSort(items[2] ?? at, "Invalid recursive function definition");
2393
2943
  unbindSortedVars(bound.varSorts.length);
2394
2944
  return manager.mkRecFuncDecl(symbol.text, bound.varSorts, range);
@@ -2396,16 +2946,19 @@ export const createSmtlibReader = (
2396
2946
 
2397
2947
  // parse_rec_fun_body: Z3 reports a body of another sort at the token after it.
2398
2948
  const defineRecFun = (decl: number, variables: SExpr, body: SExpr, next: SExpr) => {
2399
- const bound = bindSortedVars(variables, body);
2400
- const parsed = parseTerm(body);
2949
+ const start = exprStack.length;
2950
+ const bound = bindSortedVars(variables, body, "");
2951
+ runTerm(body, false);
2952
+ const parsedBody = exprStack[exprStack.length - 1];
2401
2953
  unbindSortedVars(bound.varSorts.length);
2402
2954
  const range = manager.funcDecls[decl].range;
2403
- if (manager.sorts[parsed] !== range)
2955
+ if (manager.sorts[parsedBody] !== range)
2404
2956
  throw new SmtParseError(
2405
- `invalid function definition, sort mismatch. Expcected ${manager.getSortName(range)} but function body has sort ${manager.getSortName(manager.sorts[parsed])}`,
2957
+ `invalid function definition, sort mismatch. Expcected ${manager.getSortName(range)} but function body has sort ${manager.getSortName(manager.sorts[parsedBody])}`,
2406
2958
  next,
2407
2959
  );
2408
- setRecFunDefinition(manager, manager.recFunDefs.get(decl)!, false, parsed);
2960
+ setRecFunDefinition(manager, manager.recFunDefs.get(decl)!, false, parsedBody);
2961
+ shrinkRefs(exprStack, start);
2409
2962
  };
2410
2963
 
2411
2964
  // parse_define and insert_macro: Z3 declares a macro as a recursive function with one case, which
@@ -2431,11 +2984,13 @@ export const createSmtlibReader = (
2431
2984
  };
2432
2985
 
2433
2986
  const declareCommand = (list: SmtList) => {
2987
+ releasePending();
2434
2988
  const name = list.items[0].kind === "list" ? "" : list.items[0].text;
2435
2989
  if (name === "define-fun-rec") {
2436
2990
  const decl = declareRecFun(list.items.slice(1), list.end);
2437
2991
  insertFunc(decl, list.items[4] ?? list.end);
2438
2992
  defineRecFun(decl, list.items[2], list.items[4] ?? list.end, list.items[5] ?? list.end);
2993
+ shrinkRefs(exprStack, 0);
2439
2994
  return;
2440
2995
  }
2441
2996
  if (name === "define-funs-rec") {
@@ -2466,6 +3021,7 @@ export const createSmtlibReader = (
2466
3021
  const extra = bodies.items[signatures.length];
2467
3022
  if (extra !== undefined)
2468
3023
  throw new SmtParseError("invalid recursive function definition, ')' expected", extra);
3024
+ shrinkRefs(exprStack, 0);
2469
3025
  return;
2470
3026
  }
2471
3027
  if (name === "declare-datatypes") {
@@ -2512,24 +3068,27 @@ export const createSmtlibReader = (
2512
3068
  }
2513
3069
  if (name === "define-fun" || name === "define-const") {
2514
3070
  const isConst = name === "define-const";
2515
- const bound = isConst ? { names: [], varSorts: [] } : bindSortedVars(list.items[2], list);
3071
+ const bound = isConst
3072
+ ? { names: [], varSorts: [] }
3073
+ : bindSortedVars(list.items[2], list.end, symbol.text);
2516
3074
  const range = parseSort(
2517
3075
  list.items[isConst ? 2 : 3] ?? list.end,
2518
3076
  isConst ? "Invalid constant definition" : "Invalid function definition",
2519
3077
  );
2520
- const body = parseTerm(list.items[isConst ? 3 : 4] ?? list.end);
3078
+ runTerm(list.items[isConst ? 3 : 4] ?? list.end, false);
3079
+ const body = exprStack[exprStack.length - 1];
2521
3080
  if (!isConst) unbindSortedVars(bound.varSorts.length);
2522
- const coerced = coerce(body, range);
2523
- if (manager.sorts[coerced] !== range)
3081
+ if (manager.sorts[body] !== range)
2524
3082
  throw new SmtParseError(
2525
3083
  isConst
2526
3084
  ? "invalid constant definition, sort mismatch"
2527
3085
  : "invalid function/constant definition, sort mismatch",
2528
3086
  list.end,
2529
3087
  );
2530
- manager.incRef(coerced);
2531
- declare(macros, symbol.text, { domain: bound.varSorts, range, body: coerced });
2532
- defineMacroFunc(symbol.text, bound.varSorts, coerced);
3088
+ manager.incRef(body);
3089
+ declare(macros, symbol.text, { domain: bound.varSorts, range, body });
3090
+ defineMacroFunc(symbol.text, bound.varSorts, body);
3091
+ shrinkRefs(exprStack, 0);
2533
3092
  return;
2534
3093
  }
2535
3094
  const domain = name === "declare-fun" ? parseDomain(list.items[2], list) : [];
@@ -2548,14 +3107,7 @@ export const createSmtlibReader = (
2548
3107
  if (macros.has(symbol.text))
2549
3108
  throw new SmtUnsupportedError(`the overloaded symbol ${symbol.text}`);
2550
3109
  const existing = funcs.get(symbol.text) ?? [];
2551
- if (
2552
- existing.some(
2553
- (decl) =>
2554
- manager.funcDecls[decl].range === range &&
2555
- manager.funcDecls[decl].domain.length === domain.length &&
2556
- manager.funcDecls[decl].domain.every((sort, index) => sort === domain[index]),
2557
- )
2558
- )
3110
+ if (existing.some((other) => hasSignature(other, domain, range)))
2559
3111
  throw new SmtParseError(
2560
3112
  `invalid declaration, ${domain.length === 0 ? "constant" : "function"} '${symbol.text}' (with the given signature) already declared`,
2561
3113
  list.end,
@@ -2563,28 +3115,66 @@ export const createSmtlibReader = (
2563
3115
  declare(funcs, symbol.text, [...existing, decl]);
2564
3116
  };
2565
3117
 
3118
+ // The caller takes the reference of the stack.
2566
3119
  const parseFormula = (sexpr: SExpr) => {
2567
- const assertion = parseTerm(sexpr);
3120
+ runTerm(sexpr, false);
3121
+ const assertion = exprStack[exprStack.length - 1];
2568
3122
  if (manager.sorts[assertion] !== SORT_BOOL)
2569
3123
  throw new SmtParseError("invalid assert command, term is not Boolean", sexpr);
2570
- manager.incRef(assertion);
3124
+ exprStack.pop();
2571
3125
  return assertion;
2572
3126
  };
2573
3127
 
2574
3128
  // An assertion is named when the last name of its term is its own.
2575
3129
  const parseAssertion = (sexpr: SExpr) => {
3130
+ releasePending();
2576
3131
  lastNamed.expr = -1;
2577
3132
  const formula = parseFormula(sexpr);
2578
3133
  return { formula, name: lastNamed.expr === formula ? lastNamed.name : undefined };
2579
3134
  };
2580
3135
 
2581
- const push = () => scopeStarts.push(undo.length);
3136
+ const push = () => {
3137
+ releasePending();
3138
+ scopeStarts.push(undo.length);
3139
+ };
2582
3140
 
2583
3141
  const pop = () => {
3142
+ releasePending();
2584
3143
  const start = scopeStarts.pop() ?? 0;
2585
3144
  for (const restore of undo.splice(start).reverse()) restore();
2586
3145
  };
2587
3146
 
3147
+ // parser::reset, after an error: Z3 frees its stacks, and with them the terms that only the
3148
+ // command that failed held.
3149
+ const reset = () => {
3150
+ protect(floating);
3151
+ protect(unrooted);
3152
+ releasePending();
3153
+ shrinkRefs(exprStack, 0);
3154
+ if (parsed.expr !== -1) {
3155
+ if (!parsed.isOwned) manager.incRef(parsed.expr);
3156
+ manager.decRef(parsed.expr);
3157
+ parsed.expr = -1;
3158
+ }
3159
+ shrinkRefs(patternStack, 0);
3160
+ shrinkRefs(noPatternStack, 0);
3161
+ locals.clear();
3162
+ shrink(shadowedNames, 0);
3163
+ shrink(shadowedLocals, 0);
3164
+ shrink(localScopes, 0);
3165
+ binders.depth = 0;
3166
+ };
3167
+
3168
+ // cmd_context::set_logic on a manager that is in use: restrict_builtin_sorts takes the sorts the
3169
+ // logic lacks, and the declarations and the operators stay.
3170
+ const restrictSorts = (name: string) => {
3171
+ releasePending();
3172
+ if (logicHasRealsOnly(name)) restricted.isNumeralAsReal = true;
3173
+ if (!ARRAY_EXTENSION_LOGICS.has(name)) restricted.hasSetSort = false;
3174
+ if (INT_FREE_LOGICS.has(name)) sortDecls.delete("Int");
3175
+ restricted.hasFf = FF_LOGICS.has(name);
3176
+ };
3177
+
2588
3178
  const isUsed = (name: string) => funcs.has(name) || BUILTIN_NAMES.has(name);
2589
3179
 
2590
3180
  const isClashing = (decl: number) => {
@@ -2592,12 +3182,7 @@ export const createSmtlibReader = (
2592
3182
  const decls = funcs.get(String(manager.funcDecls[decl].name)) ?? [];
2593
3183
  return (
2594
3184
  decls.includes(decl) &&
2595
- decls.some(
2596
- (other) =>
2597
- other !== decl &&
2598
- manager.funcDecls[other].domain.length === domain.length &&
2599
- manager.funcDecls[other].domain.every((sort, index) => sort === domain[index]),
2600
- )
3185
+ decls.some((other) => other !== decl && hasSignature(other, domain, -1))
2601
3186
  );
2602
3187
  };
2603
3188
 
@@ -2625,6 +3210,8 @@ export const createSmtlibReader = (
2625
3210
  getLogicError: logicChecker.checkExpr,
2626
3211
  push,
2627
3212
  pop,
3213
+ reset,
3214
+ restrictSorts,
2628
3215
  isUsed,
2629
3216
  isClashing,
2630
3217
  getDeclaredFuncs,
@@ -2654,7 +3241,7 @@ export const parseSmtlib = (
2654
3241
  report: (error: SmtParseError) => void,
2655
3242
  ): SmtProblem => {
2656
3243
  const commands = createCommandReader(text);
2657
- const state = { reader: createSmtlibReader(manager), logic: "", rlimit: 0 };
3244
+ const state = { reader: createSmtlibReader(manager), logic: "", rlimit: 0, isInUse: false };
2658
3245
  const assertions: number[] = [];
2659
3246
  const runCommand = (list: SmtList) => {
2660
3247
  const name = expectSymbol(list.items[0], "invalid command, symbol expected", list).text;
@@ -2668,19 +3255,26 @@ export const parseSmtlib = (
2668
3255
  )
2669
3256
  state.rlimit = Number(value.text);
2670
3257
  if (name === "set-logic") {
3258
+ if (option === undefined)
3259
+ throw new SmtParseError("invalid command, argument(s) missing", list.end);
2671
3260
  if (!isSymbol(option))
2672
- throw new SmtParseError("invalid logic name, symbol expected", option ?? list.end);
2673
- if (state.logic !== "") throw new SmtParseError("the logic has already been set", list.end);
3261
+ throw new SmtParseError("invalid command argument, symbol expected", option);
3262
+ if (value !== undefined)
3263
+ throw new SmtParseError("invalid command, too many arguments", value);
3264
+ if (state.logic !== "") throw new SmtParseError("the logic has already been set", option);
2674
3265
  if (assertions.length > 0)
2675
- throw new SmtParseError("logic must be set before initialization", list.end);
3266
+ throw new SmtParseError("logic must be set before initialization", option);
2676
3267
  if (!isSupportedLogic(option.text)) return;
2677
3268
  state.logic = option.text;
2678
- state.reader = createSmtlibReader(manager, option.text);
3269
+ if (state.isInUse) state.reader.restrictSorts(option.text);
3270
+ else state.reader = createSmtlibReader(manager, option.text);
2679
3271
  } else if (DECLARATIONS.has(name)) {
3272
+ state.isInUse = true;
2680
3273
  if (name.startsWith("define-"))
2681
3274
  throw new SmtUnsupportedError(`the command ${name} is not supported`);
2682
3275
  state.reader.declareCommand(list);
2683
3276
  } else if (name === "assert") {
3277
+ state.isInUse = true;
2684
3278
  const assertion = state.reader.parseFormula(list.items[1] ?? list.end);
2685
3279
  const logicError = state.reader.getLogicError(assertion);
2686
3280
  if (logicError !== undefined) {
@@ -2702,6 +3296,7 @@ export const parseSmtlib = (
2702
3296
  } catch (error) {
2703
3297
  if (!(error instanceof SmtParseError)) throw error;
2704
3298
  report(error);
3299
+ state.reader.reset();
2705
3300
  commands.skip(report);
2706
3301
  }
2707
3302
  }