tla-ts 0.0.10-dev.09e53c2a6 → 0.0.10-dev.11307be75

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 (214) hide show
  1. package/dist/compile.cjs +3 -3
  2. package/dist/compile.js +1 -1
  3. package/dist/deciders.cjs +36 -36
  4. package/dist/deciders.js +54 -54
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.d.cts +2 -1
  7. package/dist/index.d.ts +2 -1
  8. package/dist/index.js +1 -1
  9. package/dist/parallel-worker.cjs +1 -1
  10. package/dist/parallel-worker.js +1 -1
  11. package/dist/prove-worker.cjs +1 -1
  12. package/dist/prove-worker.js +1 -1
  13. package/dist/prove.cjs +43 -43
  14. package/dist/prove.js +78 -78
  15. package/dist/run.cjs +33 -35
  16. package/dist/run.js +44 -46
  17. package/dist/tlapm.cjs +1 -1
  18. package/dist/tlapm.js +2 -2
  19. package/dist/transfer.cjs +43 -43
  20. package/dist/transfer.js +38 -38
  21. package/dist/worker.cjs +6 -6
  22. package/dist/worker.js +6 -6
  23. package/package.json +1 -1
  24. package/src/ast.ts +1 -0
  25. package/src/bags.ts +46 -28
  26. package/src/check-trace.ts +2 -16
  27. package/src/check.ts +152 -64
  28. package/src/cli/runtime-invariants.ts +20 -56
  29. package/src/cli/tlc-arguments.ts +2 -2
  30. package/src/cli/tlc-output.ts +1 -2
  31. package/src/cli/tlc.ts +13 -8
  32. package/src/cli/xml-exporter.ts +1 -1
  33. package/src/codegen.ts +9 -5
  34. package/src/dependencies.ts +49 -9
  35. package/src/dfid.ts +9 -2
  36. package/src/environment.ts +57 -33
  37. package/src/errors.ts +7 -0
  38. package/src/evaluate.ts +92 -32
  39. package/src/exit-codes.ts +4 -2
  40. package/src/instances.ts +5 -5
  41. package/src/java-overrides.ts +2 -2
  42. package/src/levels.ts +138 -90
  43. package/src/liveness-checker.ts +43 -4
  44. package/src/liveness.ts +1 -1
  45. package/src/obligations/index.ts +1 -1
  46. package/src/obligations/normalize.ts +1 -4
  47. package/src/obligations/printer.ts +5 -5
  48. package/src/parallel-worker.ts +8 -2
  49. package/src/parallel.ts +5 -0
  50. package/src/parser.ts +106 -144
  51. package/src/prover/isabelle/isar/attrib.ts +4 -4
  52. package/src/prover/isabelle/isar/rule-cases.ts +8 -6
  53. package/src/prover/isabelle/provers/clasimp.ts +1 -1
  54. package/src/prover/isabelle/provers/hypsubst.ts +2 -2
  55. package/src/prover/isabelle/pure/rewriter.ts +3 -3
  56. package/src/prover/isabelle/pure/term.ts +3 -3
  57. package/src/prover/prep/md5.ts +26 -29
  58. package/src/prover/smt/rewrite.ts +2 -7
  59. package/src/prover/smt/simplify.ts +1 -1
  60. package/src/prover/smt/solver/asserted-formulas.ts +66 -1
  61. package/src/prover/smt/solver/ast-lt.ts +1 -1
  62. package/src/prover/smt/solver/ast.ts +58 -11
  63. package/src/prover/smt/solver/blast-term-ite.ts +47 -0
  64. package/src/prover/smt/solver/bound-simplifier.ts +2 -3
  65. package/src/prover/smt/solver/bv-decl-plugin.ts +13 -10
  66. package/src/prover/smt/solver/bv-rewriter.ts +1 -1
  67. package/src/prover/smt/solver/card2bv.ts +3 -5
  68. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +2 -3
  69. package/src/prover/smt/solver/context.ts +24 -3
  70. package/src/prover/smt/solver/ctx-simplify.ts +1 -2
  71. package/src/prover/smt/solver/datatype-decl-plugin.ts +15 -7
  72. package/src/prover/smt/solver/dependent-expr-state.ts +9 -4
  73. package/src/prover/smt/solver/diff-neq.ts +1 -2
  74. package/src/prover/smt/solver/elim-term-ite-tactic.ts +48 -0
  75. package/src/prover/smt/solver/elim-uncnstr.ts +4 -7
  76. package/src/prover/smt/solver/euf/arith-internalize.ts +1 -1
  77. package/src/prover/smt/solver/euf/array-internalize.ts +1 -1
  78. package/src/prover/smt/solver/euf/bv-internalize.ts +1 -1
  79. package/src/prover/smt/solver/euf/egraph.ts +4 -10
  80. package/src/prover/smt/solver/euf/euf-solver.ts +1 -2
  81. package/src/prover/smt/solver/euf/mam.ts +1 -5
  82. package/src/prover/smt/solver/euf/q-ematch.ts +1 -2
  83. package/src/prover/smt/solver/euf/th-solver.ts +0 -7
  84. package/src/prover/smt/solver/expr2polynomial.ts +204 -79
  85. package/src/prover/smt/solver/factor.ts +36 -14
  86. package/src/prover/smt/solver/fd-solver.ts +2 -0
  87. package/src/prover/smt/solver/fix-dl-var.ts +1 -2
  88. package/src/prover/smt/solver/fpa-rewriter.ts +1 -2
  89. package/src/prover/smt/solver/fpa2bv-converter.ts +3 -1
  90. package/src/prover/smt/solver/fpa2bv-rewriter.ts +1 -0
  91. package/src/prover/smt/solver/goal.ts +6 -3
  92. package/src/prover/smt/solver/goal2nlsat.ts +57 -30
  93. package/src/prover/smt/solver/hashtable.ts +4 -0
  94. package/src/prover/smt/solver/logic-tactics.ts +9 -2
  95. package/src/prover/smt/solver/lp/containers.ts +7 -1
  96. package/src/prover/smt/solver/lp/cross-nested.ts +1 -3
  97. package/src/prover/smt/solver/lp/lp-settings.ts +1 -1
  98. package/src/prover/smt/solver/lp/nex-creator.ts +3 -2
  99. package/src/prover/smt/solver/lp/nex.ts +2 -1
  100. package/src/prover/smt/solver/lp/nla-core.ts +1 -1
  101. package/src/prover/smt/solver/lp/nla-grobner.ts +158 -80
  102. package/src/prover/smt/solver/lp/nra-solver.ts +45 -39
  103. package/src/prover/smt/solver/lp/pdd-interval.ts +6 -2
  104. package/src/prover/smt/solver/lp/pdd-simplifier.ts +60 -20
  105. package/src/prover/smt/solver/lp/pdd-solver.ts +72 -39
  106. package/src/prover/smt/solver/lp/pdd.ts +725 -290
  107. package/src/prover/smt/solver/lp/union-find.ts +1 -1
  108. package/src/prover/smt/solver/mam-compiler.ts +1 -1
  109. package/src/prover/smt/solver/model-based-opt.ts +1 -1
  110. package/src/prover/smt/solver/model-generator.ts +3 -1
  111. package/src/prover/smt/solver/mpf.ts +2 -4
  112. package/src/prover/smt/solver/mus.ts +2 -3
  113. package/src/prover/smt/solver/muz/dl-context.ts +10 -4
  114. package/src/prover/smt/solver/muz/dl-mk-slice.ts +3 -3
  115. package/src/prover/smt/solver/muz/dl-rule.ts +2 -2
  116. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +1 -1
  117. package/src/prover/smt/solver/muz/horn-tactic.ts +1 -1
  118. package/src/prover/smt/solver/muz/spacer-context.ts +2 -4
  119. package/src/prover/smt/solver/muz/spacer-pdr.ts +1 -0
  120. package/src/prover/smt/solver/nlqsat.ts +1 -1
  121. package/src/prover/smt/solver/nlsat/algebraic.ts +196 -92
  122. package/src/prover/smt/solver/nlsat/atoms.ts +52 -33
  123. package/src/prover/smt/solver/nlsat/explain.ts +375 -217
  124. package/src/prover/smt/solver/nlsat/levelwise.ts +460 -240
  125. package/src/prover/smt/solver/nlsat/polynomial.ts +2366 -681
  126. package/src/prover/smt/solver/nlsat/solver.ts +74 -64
  127. package/src/prover/smt/solver/nlsat/transcendentals.ts +41 -17
  128. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +8 -4
  129. package/src/prover/smt/solver/nlsat/upolynomial.ts +41 -18
  130. package/src/prover/smt/solver/nlsat-tactic.ts +1 -1
  131. package/src/prover/smt/solver/nnf.ts +6 -2
  132. package/src/prover/smt/solver/opt-context.ts +9 -3
  133. package/src/prover/smt/solver/opt-nlsat.ts +29 -18
  134. package/src/prover/smt/solver/opt-preprocess.ts +1 -1
  135. package/src/prover/smt/solver/opt-solver.ts +6 -3
  136. package/src/prover/smt/solver/optsmt.ts +1 -1
  137. package/src/prover/smt/solver/pb-rewriter.ts +1 -4
  138. package/src/prover/smt/solver/poly-rewriter.ts +74 -18
  139. package/src/prover/smt/solver/probes.ts +88 -23
  140. package/src/prover/smt/solver/proto-model.ts +4 -6
  141. package/src/prover/smt/solver/qe-arith-plugin.ts +2 -4
  142. package/src/prover/smt/solver/qe-lite.ts +2 -2
  143. package/src/prover/smt/solver/qe.ts +3 -2
  144. package/src/prover/smt/solver/quantifier-manager.ts +14 -9
  145. package/src/prover/smt/solver/recfun-decl-plugin.ts +2 -1
  146. package/src/prover/smt/solver/rlimit.ts +4 -0
  147. package/src/prover/smt/solver/sat/config.ts +1 -1
  148. package/src/prover/smt/solver/sat/inc-sat-solver.ts +26 -1
  149. package/src/prover/smt/solver/sat/model-converter.ts +1 -1
  150. package/src/prover/smt/solver/sat/pb-solver.ts +1 -1
  151. package/src/prover/smt/solver/sat/sat-tactic.ts +4 -3
  152. package/src/prover/smt/solver/sat/simplifier.ts +1 -1
  153. package/src/prover/smt/solver/sat/solver.ts +25 -47
  154. package/src/prover/smt/solver/seq-axioms.ts +20 -35
  155. package/src/prover/smt/solver/seq-decl-plugin.ts +1 -1
  156. package/src/prover/smt/solver/seq-derive.ts +4 -7
  157. package/src/prover/smt/solver/seq-eq-solver.ts +2 -2
  158. package/src/prover/smt/solver/seq-monadic.ts +7 -5
  159. package/src/prover/smt/solver/seq-re-rewriter.ts +2 -1
  160. package/src/prover/smt/solver/seq-re-util.ts +1 -1
  161. package/src/prover/smt/solver/seq-regex-bisim.ts +1 -1
  162. package/src/prover/smt/solver/seq-regex-live.ts +2 -2
  163. package/src/prover/smt/solver/seq-rewriter.ts +31 -29
  164. package/src/prover/smt/solver/seq-skolem.ts +0 -23
  165. package/src/prover/smt/solver/seq-view-witness.ts +4 -4
  166. package/src/prover/smt/solver/smt-kernel.ts +9 -3
  167. package/src/prover/smt/solver/smt-setup.ts +68 -6
  168. package/src/prover/smt/solver/smtlib-parser.ts +558 -220
  169. package/src/prover/smt/solver/smtlib-script.ts +495 -153
  170. package/src/prover/smt/solver/solve-eqs.ts +13 -21
  171. package/src/prover/smt/solver/tactic.ts +219 -130
  172. package/src/prover/smt/solver/theory-bv.ts +2 -2
  173. package/src/prover/smt/solver/theory-lra-final-check.ts +1 -1
  174. package/src/prover/smt/solver/theory-lra-internalize.ts +1 -0
  175. package/src/prover/smt/solver/theory-lra-propagate.ts +6 -4
  176. package/src/prover/smt/solver/theory-lra.ts +0 -1
  177. package/src/prover/smt/solver/theory-pb.ts +24 -7
  178. package/src/prover/smt/solver/theory-seq-solve.ts +1 -1
  179. package/src/prover/smt/solver/theory-seq-state.ts +2 -21
  180. package/src/prover/tlapm/cache.ts +8 -8
  181. package/src/prover/zenon/equality-rules.ts +24 -0
  182. package/src/prover/zenon/expr.ts +21 -0
  183. package/src/prover/zenon/index-table.ts +7 -2
  184. package/src/prover/zenon/isar-case.ts +1 -1
  185. package/src/prover/zenon/isar.ts +2 -2
  186. package/src/prover/zenon/phrase.ts +1 -1
  187. package/src/prover/zenon/rules.ts +2 -1
  188. package/src/resolve.ts +779 -225
  189. package/src/runtime.ts +3 -1
  190. package/src/sany/builtins.ts +10 -10
  191. package/src/sany/generation.ts +2 -13
  192. package/src/sany/generator-definitions.ts +3 -1
  193. package/src/sany/generator-expressions.ts +36 -30
  194. package/src/sany/generator-proofs.ts +5 -3
  195. package/src/sany/generator.ts +2 -1
  196. package/src/sany/lexer.ts +3 -3
  197. package/src/sany/modules.ts +4 -2
  198. package/src/sany/nodes.ts +1 -1
  199. package/src/sany/selectors.ts +11 -6
  200. package/src/sany/xml.ts +2 -3
  201. package/src/search.ts +51 -22
  202. package/src/spec-description.ts +2 -2
  203. package/src/subexpressions.ts +337 -102
  204. package/src/successors.ts +1 -0
  205. package/src/symmetry.ts +1 -1
  206. package/src/tlc/jar-data.ts +10 -0
  207. package/src/tlc/messages.ts +3 -3
  208. package/src/tlc/order.ts +14 -3
  209. package/src/tlc/tlc-operators.ts +3 -1
  210. package/src/tlc/tlcext-operators.ts +18 -5
  211. package/src/tlc/trace-spec.ts +5 -5
  212. package/src/typed-tier.ts +29 -23
  213. package/src/typescript/types.ts +2 -2
  214. package/src/values.ts +46 -27
@@ -1,4 +1,9 @@
1
- import { SmtParseError, SmtUnsupportedError } from "../../../errors";
1
+ import {
2
+ SmtDefaultError,
3
+ SmtParseError,
4
+ type SmtPosition,
5
+ SmtUnsupportedError,
6
+ } from "../../../errors";
2
7
  import {
3
8
  type AstManager,
4
9
  getSymbolHash,
@@ -72,7 +77,7 @@ import {
72
77
  QUANTIFIER_LAMBDA,
73
78
  } from "./ast";
74
79
  import { getArraySignature, getMapSignature, mkAsArray } from "./array-decl-plugin";
75
- import { BV_OP_NAMES, getBvSignature } from "./bv-decl-plugin";
80
+ import { BV_OP_NAMES, getBvSignature, getMismatchedArgument } from "./bv-decl-plugin";
76
81
  import {
77
82
  type ConstructorDef,
78
83
  type DatatypeDef,
@@ -88,6 +93,7 @@ import {
88
93
  mkDatatypes,
89
94
  mkUpdateField,
90
95
  removeDatatype,
96
+ resetDatatypePlugin,
91
97
  substituteSort,
92
98
  } from "./datatype-decl-plugin";
93
99
  import {
@@ -120,6 +126,7 @@ import {
120
126
  } from "./smt-logics";
121
127
  import { setRecFunDefinition } from "./recfun-decl-plugin";
122
128
  import { DEFAULT_PRINT_OPTIONS, printExpr } from "./smt2-printer";
129
+ import { InvVarShifter } from "./rewriter-tpl";
123
130
  import { replaceFreeVars, VarSubst } from "./var-subst";
124
131
  import { UpolynomialManager } from "./nlsat/upolynomial";
125
132
 
@@ -131,12 +138,13 @@ const DEFAULT_PARSER_OPTIONS: ParserOptions = { isIgnoringBadPatterns: true };
131
138
 
132
139
  // Z3 counts the columns of the first line from 1 and of the others from 0.
133
140
  export interface SmtToken {
134
- kind: "(" | ")" | "symbol" | "keyword" | "string" | "numeral" | "decimal" | "bitvector";
141
+ kind: "(" | ")" | "symbol" | "keyword" | "string" | "numeral" | "decimal" | "bitvector" | "eof";
135
142
  text: string;
136
143
  line: number;
137
144
  column: number;
138
145
  offset: number;
139
146
  endOffset: number;
147
+ lastId: string;
140
148
  }
141
149
 
142
150
  export interface SmtList {
@@ -145,6 +153,7 @@ export interface SmtList {
145
153
  line: number;
146
154
  column: number;
147
155
  offset: number;
156
+ lastId: string;
148
157
  // Z3 reports an error in making an application at its closing parenthesis.
149
158
  end: SmtToken;
150
159
  // The token after a root-obj or an indexed or qualified identifier, where Z3 reports an error in
@@ -208,8 +217,6 @@ type SortDecl = ConstantSortDecl | UserSortDecl | DatatypeSortDecl | DefinedSort
208
217
 
209
218
  const NO_BINDINGS: ReadonlyMap<string, number> = new Map();
210
219
 
211
- const UPOLYNOMIALS = new UpolynomialManager();
212
-
213
220
  interface SmtProblem {
214
221
  assertions: number[];
215
222
  hasCheckSat: boolean;
@@ -289,6 +296,17 @@ interface PatternFrame {
289
296
  next: number;
290
297
  }
291
298
 
299
+ interface MatchFrame {
300
+ kind: "match";
301
+ list: SmtList;
302
+ cases: SExpr[];
303
+ isCaseForm: boolean;
304
+ depth: number;
305
+ isTail: boolean;
306
+ start: number;
307
+ next: number;
308
+ }
309
+
292
310
  // smt2parser.cpp's expr_frame.
293
311
  type TermFrame =
294
312
  | ApplicationFrame
@@ -297,7 +315,8 @@ type TermFrame =
297
315
  | LetDeclFrame
298
316
  | QuantifierFrame
299
317
  | AttributeFrame
300
- | PatternFrame;
318
+ | PatternFrame
319
+ | MatchFrame;
301
320
 
302
321
  const QUANTIFIER_KINDS = new Map([
303
322
  ["forall", QUANTIFIER_FORALL],
@@ -588,6 +607,14 @@ const ARRAY_OPS = new Map([
588
607
  ]);
589
608
  const ARRAY_EXTENSION_OPS = new Map([["default", OP_ARRAY_DEFAULT]]);
590
609
 
610
+ const isPortedTheoryOperator = (name: string) =>
611
+ BV_OP_NAMES.has(name) ||
612
+ FPA_OP_NAMES.has(name) ||
613
+ SEQ_OP_NAMES.has(name) ||
614
+ CHAR_OP_NAMES.has(name) ||
615
+ ARRAY_OPS.has(name) ||
616
+ ARRAY_EXTENSION_OPS.has(name);
617
+
591
618
  const UNARY_BOOL_REFS = new Map([["not", OP_NOT]]);
592
619
  const BINARY_BOOL_REFS = new Map([
593
620
  ["and", OP_AND],
@@ -642,12 +669,14 @@ const FF_LITERAL = /^#f-?[0-9]+m[0-9]+$/;
642
669
  const FF_LOGICS = new Set(["QF_FF", "QF_FFA", "ALL", "HO_ALL"]);
643
670
 
644
671
  // rational::is_unsigned of a numeral token.
645
- const isUnsigned = (numeral: string) => BigInt(numeral) >= 0n && BigInt(numeral) <= 0xffffffffn;
672
+ export const isUnsigned = (numeral: string) =>
673
+ BigInt(numeral) >= 0n && BigInt(numeral) <= 0xffffffffn;
646
674
 
647
675
  const SYMBOL_CHARACTER = /[A-Za-z0-9~!@$%^&*_\-+=<>.?/,]/;
648
676
 
649
677
  const createScanner = (text: string) => {
650
- const state = { index: 0, line: 1, lineStart: -1 };
678
+ // Z3 prints the null symbol its scanner starts with as null.
679
+ const state = { index: 0, line: 1, lineStart: -1, lastId: "null" };
651
680
  const getColumn = () => state.index - state.lineStart - (state.line === 1 ? 0 : 1);
652
681
  const advance = () => {
653
682
  if (text[state.index] === "\n") {
@@ -673,13 +702,17 @@ const createScanner = (text: string) => {
673
702
  }
674
703
  const start = state.index;
675
704
  const position = { line: state.line, column: getColumn() };
676
- const getToken = (kind: SmtToken["kind"], tokenText = text.slice(start, state.index)) => ({
677
- kind,
678
- text: tokenText,
679
- ...position,
680
- offset: start,
681
- endOffset: state.index,
682
- });
705
+ const getToken = (kind: SmtToken["kind"], tokenText = text.slice(start, state.index)) => {
706
+ if (kind === "symbol" || kind === "keyword") state.lastId = tokenText;
707
+ return {
708
+ kind,
709
+ text: tokenText,
710
+ ...position,
711
+ offset: start,
712
+ endOffset: state.index,
713
+ lastId: state.lastId,
714
+ };
715
+ };
683
716
  if (character === "(" || character === ")") {
684
717
  advance();
685
718
  return getToken(character);
@@ -703,6 +736,9 @@ const createScanner = (text: string) => {
703
736
  // string, so the columns of the rest of the line count one more.
704
737
  if (current === "\n") state.lineStart--;
705
738
  if (current !== character) continue;
739
+ // Z3's scanner rereads the last character at the end of the file, as if the quote were doubled.
740
+ if (character === '"' && state.index === text.length)
741
+ throw new SmtParseError("unexpected end of file", position);
706
742
  if (character !== '"' || text[state.index] !== '"') break;
707
743
  advance();
708
744
  }
@@ -733,25 +769,23 @@ const createScanner = (text: string) => {
733
769
  }
734
770
  continue;
735
771
  }
736
- if (radix === "f") {
737
- advance();
738
- readWhile(/[0-9m-]/);
739
- return getToken("symbol");
740
- }
741
- if (radix !== "x" && radix !== "b")
772
+ if (radix !== "f" && radix !== "x" && radix !== "b")
742
773
  throw new SmtParseError("invalid bit-vector literal, expecting 'x' or 'b'", {
743
774
  line: state.line,
744
775
  column: getColumn(),
745
776
  });
746
777
  advance();
747
778
  const digitsStart = state.index;
748
- readWhile(radix === "x" ? /[0-9a-fA-F]/ : /[01]/);
749
- if (state.index === digitsStart)
779
+ readWhile(radix === "f" ? /[0-9m-]/ : radix === "x" ? /[0-9a-fA-F]/ : /[01]/);
780
+ if (state.index === digitsStart && radix !== "f")
750
781
  throw new SmtParseError("invalid empty bit-vector literal", {
751
782
  line: state.line,
752
783
  column: getColumn(),
753
784
  });
754
- return getToken("bitvector");
785
+ // Z3's scanner rereads the last digit at the end of the file.
786
+ if (state.index === text.length && state.index !== digitsStart)
787
+ throw new SmtParseError("unexpected end of file", position);
788
+ return getToken(radix === "f" ? "symbol" : "bitvector");
755
789
  }
756
790
  if (character === ":" || SYMBOL_CHARACTER.test(character)) {
757
791
  advance();
@@ -762,7 +796,11 @@ const createScanner = (text: string) => {
762
796
  throw new SmtParseError("unexpected character", position);
763
797
  }
764
798
  };
765
- return { next, getPosition: () => ({ line: state.line, column: getColumn() }) };
799
+ return {
800
+ next,
801
+ getPosition: () => ({ line: state.line, column: getColumn() }),
802
+ getLastId: () => state.lastId,
803
+ };
766
804
  };
767
805
 
768
806
  export const createCommandReader = (text: string) => {
@@ -784,13 +822,29 @@ export const createCommandReader = (text: string) => {
784
822
  line: open.line,
785
823
  column: open.column,
786
824
  offset: open.offset,
825
+ lastId: open.lastId,
787
826
  end: open,
788
827
  };
789
828
  let followed: SmtList | undefined;
790
829
  for (let current = root; ;) {
791
830
  const token = take();
792
- if (token === undefined)
793
- throw new SmtParseError("unexpected end of file", scanner.getPosition());
831
+ if (token === undefined) {
832
+ // Z3 parses a command as it reads it, and sees the end of the file where it wants a token.
833
+ const eof: SmtToken = {
834
+ kind: "eof",
835
+ text: "",
836
+ ...scanner.getPosition(),
837
+ offset: text.length,
838
+ endOffset: text.length,
839
+ lastId: scanner.getLastId(),
840
+ };
841
+ if (followed !== undefined) followed.follower = eof;
842
+ current.items.push(eof);
843
+ const end = { ...eof };
844
+ current.end = end;
845
+ for (const list of stack) list.end = end;
846
+ return root;
847
+ }
794
848
  if (followed !== undefined) followed.follower = token;
795
849
  followed = undefined;
796
850
  if (token.kind === "(") {
@@ -800,6 +854,7 @@ export const createCommandReader = (text: string) => {
800
854
  line: token.line,
801
855
  column: token.column,
802
856
  offset: token.offset,
857
+ lastId: token.lastId,
803
858
  end: token,
804
859
  root,
805
860
  };
@@ -822,12 +877,28 @@ export const createCommandReader = (text: string) => {
822
877
  current = parent;
823
878
  }
824
879
  };
825
- const read = (): SmtList | undefined => {
880
+ const readOpen = () => {
826
881
  const token = take();
827
882
  if (token === undefined) return undefined;
828
883
  if (token.kind !== "(") throw new SmtParseError("invalid command, '(' expected", token);
829
884
  state.depth = 1;
830
- return readList(token);
885
+ return token;
886
+ };
887
+ const read = () => {
888
+ const open = readOpen();
889
+ return open === undefined ? undefined : readList(open);
890
+ };
891
+ // parse_cmd checks the head of a command before it reads the rest.
892
+ const readCommand = () => {
893
+ const open = readOpen();
894
+ if (open === undefined) return undefined;
895
+ state.lookahead = take();
896
+ if (!isSymbol(state.lookahead))
897
+ throw new SmtParseError(
898
+ "invalid command, symbol expected",
899
+ state.lookahead ?? scanner.getPosition(),
900
+ );
901
+ return readList(open);
831
902
  };
832
903
  const skip = (report: (error: SmtParseError) => void) => {
833
904
  for (;;) {
@@ -846,27 +917,17 @@ export const createCommandReader = (text: string) => {
846
917
  }
847
918
  }
848
919
  };
849
- return { read, skip };
920
+ return { read, readCommand, skip };
850
921
  };
851
922
 
852
- export const isSymbol = (sexpr: SExpr | undefined, text?: string): sexpr is SmtToken =>
853
- sexpr !== undefined && sexpr.kind === "symbol" && (text === undefined || sexpr.text === text);
854
-
855
- // The identifier Z3's scanner read last, which check_next prints after "got".
856
- const getLastId = (sexpr: SExpr | undefined): string | undefined => {
857
- if (sexpr === undefined) return undefined;
858
- if (sexpr.kind !== "list")
859
- return sexpr.kind === "symbol" || sexpr.kind === "keyword" ? sexpr.text : undefined;
860
- return getLastIdBefore(sexpr.items, sexpr.items.length);
923
+ export const expectClosed = (sexpr: SExpr) => {
924
+ const end = sexpr.kind === "list" ? sexpr.end : sexpr;
925
+ if (end.kind === "eof")
926
+ throw new SmtParseError("invalid s-expression, unexpected end of file", end);
861
927
  };
862
928
 
863
- const getLastIdBefore = (items: SExpr[], end: number): string | undefined => {
864
- for (let index = end - 1; index >= 0; index--) {
865
- const id = getLastId(items[index]);
866
- if (id !== undefined) return id;
867
- }
868
- return undefined;
869
- };
929
+ export const isSymbol = (sexpr: SExpr | undefined, text?: string): sexpr is SmtToken =>
930
+ sexpr !== undefined && sexpr.kind === "symbol" && (text === undefined || sexpr.text === text);
870
931
 
871
932
  const isSimpleIndex = (index: SExpr) =>
872
933
  index.kind === "numeral" ||
@@ -879,11 +940,20 @@ const expectList = (sexpr: SExpr | undefined, message: string, at: SExpr): SmtLi
879
940
  return sexpr;
880
941
  };
881
942
 
943
+ const expectListNext = (sexpr: SExpr, message: string) => {
944
+ if (sexpr.kind !== "list") throw new SmtParseError(`${message} got ${sexpr.lastId}`, sexpr);
945
+ return sexpr;
946
+ };
947
+
882
948
  const expectSymbol = (sexpr: SExpr | undefined, message: string, at: SExpr): SmtToken => {
883
949
  if (!isSymbol(sexpr)) throw new SmtParseError(message, sexpr ?? at);
884
950
  return sexpr;
885
951
  };
886
952
 
953
+ const expectEnd = (extra: SExpr | undefined, message: string) => {
954
+ if (extra !== undefined) throw new SmtParseError(message, extra);
955
+ };
956
+
887
957
  export const createSmtlibReader = (
888
958
  manager: AstManager,
889
959
  logic?: string,
@@ -926,6 +996,9 @@ export const createSmtlibReader = (
926
996
  const unrooted: number[] = [];
927
997
  const pending: number[] = [];
928
998
 
999
+ const scopedFuncs: number[] = [];
1000
+ const scopedFuncStarts: number[] = [];
1001
+
929
1002
  const declare = <Value>(names: Map<string, Value>, name: string, value: Value) => {
930
1003
  const previous = names.get(name);
931
1004
  undo.push(() => {
@@ -974,6 +1047,7 @@ export const createSmtlibReader = (
974
1047
  at,
975
1048
  );
976
1049
  declare(funcs, name, [...existing, decl]);
1050
+ scopedFuncs.push(decl);
977
1051
  };
978
1052
 
979
1053
  const insertDatatypeDecls = (sort: number, at: SExpr) => {
@@ -1030,38 +1104,40 @@ export const createSmtlibReader = (
1030
1104
  ? decl.parameters.length
1031
1105
  : decl.arity;
1032
1106
 
1107
+ const registerList = () => {
1108
+ const element = manager.mkTypeParameter(0);
1109
+ mkDatatypes(manager, [
1110
+ mkDatatypeDef(
1111
+ manager,
1112
+ "List",
1113
+ [element],
1114
+ [
1115
+ { name: "nil", recognizer: "is-nil", accessors: [] },
1116
+ {
1117
+ name: "insert",
1118
+ recognizer: "is-insert",
1119
+ accessors: [
1120
+ { name: "head", range: element },
1121
+ { name: "tail", range: -1 },
1122
+ ],
1123
+ },
1124
+ ],
1125
+ ),
1126
+ ]);
1127
+ const list: DatatypeSortDecl = {
1128
+ kind: "datatype",
1129
+ name: "List",
1130
+ arity: 1,
1131
+ siblings: [],
1132
+ instances: new Map(),
1133
+ };
1134
+ sortDecls.set("List", list);
1135
+ return list;
1136
+ };
1137
+
1033
1138
  const instantiateSort = (decl: SortDecl, parameters: number[], at: SExpr): number => {
1034
1139
  if (decl.kind === "sort") return decl.sort;
1035
- if (decl.kind === "list") {
1036
- const element = manager.mkTypeParameter(0);
1037
- mkDatatypes(manager, [
1038
- mkDatatypeDef(
1039
- manager,
1040
- "List",
1041
- [element],
1042
- [
1043
- { name: "nil", recognizer: "is-nil", accessors: [] },
1044
- {
1045
- name: "insert",
1046
- recognizer: "is-insert",
1047
- accessors: [
1048
- { name: "head", range: element },
1049
- { name: "tail", range: -1 },
1050
- ],
1051
- },
1052
- ],
1053
- ),
1054
- ]);
1055
- const list: DatatypeSortDecl = {
1056
- kind: "datatype",
1057
- name: "List",
1058
- arity: 1,
1059
- siblings: [],
1060
- instances: new Map(),
1061
- };
1062
- sortDecls.set("List", list);
1063
- return instantiateSort(list, parameters, at);
1064
- }
1140
+ if (decl.kind === "list") return instantiateSort(registerList(), parameters, at);
1065
1141
  if (decl.kind === "user") return manager.mkUninterpretedSort(decl.name, parameters);
1066
1142
  if (decl.kind === "datatype") return instantiateDatatype(decl, parameters, at);
1067
1143
  return parseSort(
@@ -1077,7 +1153,11 @@ export const createSmtlibReader = (
1077
1153
  bindings: ReadonlyMap<string, number>,
1078
1154
  ): number => {
1079
1155
  const head = sexpr.items[0];
1080
- if (!isSymbol(head)) throw new SmtParseError("invalid sort, symbol or '_' expected", head);
1156
+ if (!isSymbol(head))
1157
+ throw new SmtParseError(
1158
+ `${context === "" ? "" : `${context} `}invalid sort, symbol or '_' expected`,
1159
+ head ?? sexpr.end,
1160
+ );
1081
1161
  const isArray =
1082
1162
  ARRAY_SORT_NAMES.has(head.text) || (head.text === "Set" && restricted.hasSetSort);
1083
1163
  if (isArray && hasArrays) {
@@ -1204,6 +1284,11 @@ export const createSmtlibReader = (
1204
1284
  throw new SmtParseError("bit-vector size must be greater than zero", sexpr.end);
1205
1285
  return manager.mkBvSort(Number(width.text));
1206
1286
  }
1287
+ if (sexpr.kind !== "symbol")
1288
+ throw new SmtParseError(
1289
+ `invalid sort, symbol, '_' or '(' expected got ${sexpr.lastId}`,
1290
+ sexpr,
1291
+ );
1207
1292
  const decl = sortDecls.get(sexpr.text);
1208
1293
  if (decl !== undefined) {
1209
1294
  if (getSortDeclArity(decl) !== 0)
@@ -1278,19 +1363,18 @@ export const createSmtlibReader = (
1278
1363
  shrink(exprs, 0);
1279
1364
  };
1280
1365
 
1281
- // push_local: var_shifter moves the free variables of a term that was bound under fewer binders.
1282
- // Its cache holds the terms it makes, which replaceFreeVars rebuilds.
1283
- const getLocalTerm = (local: Local) => {
1284
- if (local.level === binders.depth) return local.expr;
1285
- if (manager.kinds[local.expr] === KIND_VAR)
1286
- return manager.mkVar(
1287
- manager.values[local.expr] + binders.depth - local.level,
1288
- manager.sorts[local.expr],
1289
- );
1290
- return replaceFreeVars(manager, local.expr, (variable, index, shift) =>
1291
- manager.mkVar(index + shift + binders.depth - local.level, manager.sorts[variable]),
1292
- );
1293
- };
1366
+ // The parser's var_shifter, whose cache holds the terms it makes, which replaceFreeVars rebuilds.
1367
+ const shiftFreeVars = (expr: number, amount: number) =>
1368
+ manager.kinds[expr] === KIND_VAR
1369
+ ? manager.mkVar(manager.values[expr] + amount, manager.sorts[expr])
1370
+ : replaceFreeVars(manager, expr, (variable, index, shift) =>
1371
+ manager.mkVar(index + shift + amount, manager.sorts[variable]),
1372
+ );
1373
+
1374
+ const getLocalTerm = (local: Local) =>
1375
+ local.level === binders.depth
1376
+ ? local.expr
1377
+ : shiftFreeVars(local.expr, binders.depth - local.level);
1294
1378
 
1295
1379
  // basic_decl_plugin::join.
1296
1380
  const getJoin = (left: number, right: number, at: SExpr) => {
@@ -1469,19 +1553,19 @@ export const createSmtlibReader = (
1469
1553
  };
1470
1554
 
1471
1555
  // parse_sorted_vars: the variables are created the first declared with the largest index, and
1472
- // the stack holds them. previousId is the identifier before the list.
1473
- const bindSortedVars = (sexpr: SExpr | undefined, at: SExpr, previousId: string) => {
1556
+ // the stack holds them.
1557
+ const bindSortedVars = (sexpr: SExpr | undefined, at: SExpr) => {
1474
1558
  if (sexpr?.kind !== "list")
1475
1559
  throw new SmtParseError(
1476
- `invalid list of sorted variables, '(' expected got ${getLastId(sexpr) ?? previousId}`,
1560
+ `invalid list of sorted variables, '(' expected got ${(sexpr ?? at).lastId}`,
1477
1561
  sexpr ?? at,
1478
1562
  );
1479
1563
  const names: string[] = [];
1480
1564
  const varSorts: number[] = [];
1481
- for (const [index, declaration] of sexpr.items.entries()) {
1565
+ for (const declaration of sexpr.items) {
1482
1566
  if (declaration.kind !== "list")
1483
1567
  throw new SmtParseError(
1484
- `invalid sorted variable, '(' expected got ${getLastId(declaration) ?? getLastIdBefore(sexpr.items, index) ?? previousId}`,
1568
+ `invalid sorted variable, '(' expected got ${declaration.lastId}`,
1485
1569
  declaration,
1486
1570
  );
1487
1571
  const name = declaration.items[0];
@@ -1494,10 +1578,7 @@ export const createSmtlibReader = (
1494
1578
  varSorts.push(parseSort(declaration.items[1] ?? declaration.end, "invalid sorted variables"));
1495
1579
  const extra = declaration.items[2];
1496
1580
  if (extra !== undefined)
1497
- throw new SmtParseError(
1498
- `invalid sorted variable, ')' expected got ${getLastId(extra) ?? getLastId(declaration.items[1]) ?? name.text}`,
1499
- extra,
1500
- );
1581
+ throw new SmtParseError(`invalid sorted variable, ')' expected got ${extra.lastId}`, extra);
1501
1582
  }
1502
1583
  beginScope();
1503
1584
  binders.depth += varSorts.length;
@@ -1571,13 +1652,15 @@ export const createSmtlibReader = (
1571
1652
 
1572
1653
  const mkBvApp = (name: string, args: number[], indices: number[], at: SExpr) => {
1573
1654
  const op = BV_OP_NAMES.get(name) ?? -1;
1574
- const signature = getBvSignature(
1575
- manager,
1576
- op,
1577
- args.map((arg) => manager.sorts[arg]),
1578
- indices,
1579
- );
1655
+ const argSorts = args.map((arg) => manager.sorts[arg]);
1656
+ const signature = getBvSignature(manager, op, argSorts, indices);
1580
1657
  if (typeof signature === "string") throw new SmtParseError(signature, at);
1658
+ const mismatched = getMismatchedArgument(signature, argSorts);
1659
+ if (mismatched !== -1)
1660
+ throw new SmtParseError(
1661
+ `Argument ${printExpr(manager, { options: DEFAULT_PRINT_OPTIONS, isUsed, isClashing }, args[mismatched])} at position ${mismatched} has sort ${manager.getSortName(argSorts[mismatched])} it does not match declaration (declare-fun ${signature.name} (${signature.domain.map((sort) => manager.getSortName(sort)).join(" ")}) ${manager.getSortName(signature.range)})`,
1662
+ at,
1663
+ );
1581
1664
  const decl = manager.mkBvDecl(op, signature.name, indices, signature.domain, signature.range);
1582
1665
  return manager.mkApp(decl, args, signature.range);
1583
1666
  };
@@ -1649,8 +1732,10 @@ export const createSmtlibReader = (
1649
1732
  return mkSeqAppOf(manager, signature, args);
1650
1733
  };
1651
1734
 
1735
+ const upolynomials = new UpolynomialManager(manager.limit);
1736
+
1652
1737
  const parseUpolynomial = (sexpr: SExpr): bigint[] => {
1653
- if (sexpr.kind === "numeral") return UPOLYNOMIALS.set([BigInt(sexpr.text)]);
1738
+ if (sexpr.kind === "numeral") return upolynomials.set([BigInt(sexpr.text)]);
1654
1739
  if (sexpr.kind === "decimal") {
1655
1740
  const parts = sexpr.text.split(".");
1656
1741
  const value = Rational.of(BigInt(parts[0] + parts[1]), 10n ** BigInt(parts[1].length));
@@ -1659,7 +1744,7 @@ export const createSmtlibReader = (
1659
1744
  "invalid univariate polynomial, integer coefficient expected",
1660
1745
  sexpr,
1661
1746
  );
1662
- return UPOLYNOMIALS.set([value.num]);
1747
+ return upolynomials.set([value.num]);
1663
1748
  }
1664
1749
  if (sexpr.kind === "symbol") {
1665
1750
  if (sexpr.text !== "x")
@@ -1684,15 +1769,15 @@ export const createSmtlibReader = (
1684
1769
  "invalid univariate polynomial, exponent must be an unsigned integer",
1685
1770
  exponent,
1686
1771
  );
1687
- return UPOLYNOMIALS.pw(parseUpolynomial(operands[0]), Number(exponent.text));
1772
+ return upolynomials.pw(parseUpolynomial(operands[0]), Number(exponent.text));
1688
1773
  }
1689
1774
  const combine =
1690
1775
  head.text === "+"
1691
- ? UPOLYNOMIALS.add
1776
+ ? upolynomials.add
1692
1777
  : head.text === "-"
1693
- ? UPOLYNOMIALS.sub
1778
+ ? upolynomials.sub
1694
1779
  : head.text === "*"
1695
- ? UPOLYNOMIALS.mul
1780
+ ? upolynomials.mul
1696
1781
  : undefined;
1697
1782
  if (combine === undefined)
1698
1783
  throw new SmtParseError(
@@ -1705,11 +1790,11 @@ export const createSmtlibReader = (
1705
1790
  sexpr,
1706
1791
  );
1707
1792
  const first = parseUpolynomial(operands[0]);
1708
- if (head.text === "-" && operands.length === 1) return UPOLYNOMIALS.neg(first);
1793
+ if (head.text === "-" && operands.length === 1) return upolynomials.neg(first);
1709
1794
  return operands
1710
1795
  .slice(1)
1711
1796
  .reduce(
1712
- (result, operand) => combine.call(UPOLYNOMIALS, result, parseUpolynomial(operand)),
1797
+ (result, operand) => combine.call(upolynomials, result, parseUpolynomial(operand)),
1713
1798
  first,
1714
1799
  );
1715
1800
  };
@@ -1727,7 +1812,10 @@ export const createSmtlibReader = (
1727
1812
  if (BigInt(index.text) === 0n)
1728
1813
  throw new SmtParseError("invalid root-obj, index must be >= 1", index);
1729
1814
  if (list.items.length > 3)
1730
- throw new SmtParseError("invalid root-obj, ')' expected", list.items[3]);
1815
+ throw new SmtParseError(
1816
+ `invalid root-obj, ')' expected got ${list.items[3].lastId}`,
1817
+ list.items[3],
1818
+ );
1731
1819
  const coeffs = parseUpolynomial(polynomial);
1732
1820
  const follower = list.follower ?? list.end;
1733
1821
  if (coeffs.length === 0)
@@ -1753,7 +1841,7 @@ export const createSmtlibReader = (
1753
1841
  if (!isSymbol(name))
1754
1842
  throw new SmtParseError("invalid indexed identifier, symbol expected", name ?? list.end);
1755
1843
  for (const index of list.items.slice(2)) {
1756
- if (index.kind === "string")
1844
+ if (index.kind === "string" || index.kind === "eof")
1757
1845
  throw new SmtParseError(
1758
1846
  "invalid indexed identifier, integer, identifier or '(' expected",
1759
1847
  index,
@@ -1778,7 +1866,7 @@ export const createSmtlibReader = (
1778
1866
  const target = list.items[1];
1779
1867
  if (target === undefined || (target.kind !== "symbol" && target.kind !== "list"))
1780
1868
  throw new SmtParseError(
1781
- `invalid (indexed) identifier, '(_' or symbol expected got ${getLastId(target) ?? "as"}`,
1869
+ `invalid (indexed) identifier, '(_' or symbol expected got ${(target ?? list.end).lastId}`,
1782
1870
  target ?? list.end,
1783
1871
  );
1784
1872
  if (target.kind === "list") {
@@ -1793,7 +1881,7 @@ export const createSmtlibReader = (
1793
1881
  const extra = list.items[3];
1794
1882
  if (extra !== undefined)
1795
1883
  throw new SmtParseError(
1796
- `invalid qualified identifier, ')' expected got ${getLastId(extra) ?? getLastIdBefore(list.items, 3) ?? "as"}`,
1884
+ `invalid qualified identifier, ')' expected got ${extra.lastId}`,
1797
1885
  extra,
1798
1886
  );
1799
1887
  return sort;
@@ -1857,18 +1945,19 @@ export const createSmtlibReader = (
1857
1945
  const sort = parseQualifierSort(list);
1858
1946
  const target = list.items[1];
1859
1947
  const local = isSymbol(target) ? locals.get(target.text) : undefined;
1860
- if (isSymbol(target) && local === undefined)
1861
- return hasArrays && target.text === "const"
1862
- ? mkArrayTerm(OP_CONST_ARRAY, [], [sort], at)
1863
- : parseApp(target, [], at, [], sort);
1948
+ if (isSymbol(target) && local === undefined && hasArrays && target.text === "const")
1949
+ return mkArrayTerm(OP_CONST_ARRAY, [], [sort], at);
1950
+ // A macro takes no range, so check_qualifier catches the sort of the term it stands for.
1864
1951
  const term =
1865
- local === undefined
1866
- ? parseIndexedTerm(
1867
- expectList(target, "invalid indexed identifier, '_' expected", list),
1868
- at,
1869
- sort,
1870
- )
1871
- : getLocalTerm(local);
1952
+ local !== undefined
1953
+ ? getLocalTerm(local)
1954
+ : isSymbol(target)
1955
+ ? parseApp(target, [], at, [], sort)
1956
+ : parseIndexedTerm(
1957
+ expectList(target, "invalid indexed identifier, '_' expected", list),
1958
+ at,
1959
+ sort,
1960
+ );
1872
1961
  if (manager.sorts[term] !== sort)
1873
1962
  throw new SmtParseError(
1874
1963
  `sort mismatch in qualified identifier, expected: ${manager.getSortName(sort)}, got: ${manager.getSortName(manager.sorts[term])}`,
@@ -2005,7 +2094,15 @@ export const createSmtlibReader = (
2005
2094
  const argSort = args.length === 1 ? manager.sorts[args[0]] : -1;
2006
2095
  if (argSort === -1 || !manager.isDatatypeSort(argSort))
2007
2096
  throw new SmtParseError(IS_PARAMETER_MESSAGE, at);
2008
- const constructor = getDatatypeConstructors(manager, argSort).find(
2097
+ const constructors = (() => {
2098
+ try {
2099
+ return getDatatypeConstructors(manager, argSort);
2100
+ } catch (error) {
2101
+ if (!(error instanceof SmtDefaultError)) throw error;
2102
+ throw new SmtParseError(error.message, at);
2103
+ }
2104
+ })();
2105
+ const constructor = constructors.find(
2009
2106
  (decl) => manager.funcDecls[decl].name === constructorName.text,
2010
2107
  );
2011
2108
  if (constructor === undefined)
@@ -2163,10 +2260,15 @@ export const createSmtlibReader = (
2163
2260
  const transcendentalOp = isTranscendental ? TRANSCENDENTAL_OPS.get(builtin) : undefined;
2164
2261
  if (isTranscendental && transcendentalOp === undefined)
2165
2262
  throw new SmtUnsupportedError(`the operator ${name}`);
2166
- const named =
2263
+ const builtinOp =
2167
2264
  builtin === "~"
2168
2265
  ? OP_UMINUS
2169
2266
  : (CHAINABLE_OPS.get(builtin) ?? BUILTIN_OPS.get(builtin) ?? transcendentalOp);
2267
+ // load_plugin registers the operators of arithmetic only for a logic that has it.
2268
+ const named =
2269
+ builtinOp !== undefined && manager.funcDecls[builtinOp].family === FAMILY_ARITH && !hasArith
2270
+ ? undefined
2271
+ : builtinOp;
2170
2272
  if (
2171
2273
  args.length === 0 &&
2172
2274
  named !== undefined &&
@@ -2177,7 +2279,17 @@ export const createSmtlibReader = (
2177
2279
  const op = named === OP_SUB && args.length === 1 ? OP_UMINUS : named;
2178
2280
  const domainSort = op === undefined ? -1 : getDomainSort(op, args, at);
2179
2281
  if (op !== undefined && domainSort !== -1) return mkApp(op, args, at, domainSort);
2180
- if (op === undefined && (THEORY_OPERATOR.test(name) || THEORY_OPERATORS.has(name)))
2282
+ if (
2283
+ op === undefined &&
2284
+ !isPortedTheoryOperator(name) &&
2285
+ ((THEORY_OPERATOR.test(name) &&
2286
+ (name.startsWith("bv")
2287
+ ? hasBv
2288
+ : name.startsWith("fp.")
2289
+ ? hasFpa
2290
+ : name.startsWith("ff.") || hasSeq)) ||
2291
+ THEORY_OPERATORS.has(name))
2292
+ )
2181
2293
  throw new SmtUnsupportedError(`the operator ${name}`);
2182
2294
  const instance = mkDatatypeInstanceApp(name, args, at);
2183
2295
  if (instance !== undefined) return instance;
@@ -2214,7 +2326,9 @@ export const createSmtlibReader = (
2214
2326
  throw new SmtParseError(
2215
2327
  sexpr.kind === "keyword"
2216
2328
  ? "invalid expression, unexpected keyword"
2217
- : "invalid expression, unexpected ')'",
2329
+ : sexpr.kind === "eof"
2330
+ ? "invalid expression, unexpected input"
2331
+ : "invalid expression, unexpected ')'",
2218
2332
  sexpr,
2219
2333
  );
2220
2334
  };
@@ -2234,7 +2348,9 @@ export const createSmtlibReader = (
2234
2348
  manager.incRef(expr);
2235
2349
  lastNamed.name = name;
2236
2350
  lastNamed.expr = expr;
2237
- manager.mkMacro(name, expr);
2351
+ const decl = manager.mkMacro(name, expr);
2352
+ declare(funcs, name, [...(funcs.get(name) ?? []), decl]);
2353
+ scopedFuncs.push(decl);
2238
2354
  declare(macros, name, { domain: [], range: manager.sorts[expr], body: expr });
2239
2355
  };
2240
2356
 
@@ -2295,6 +2411,106 @@ export const createSmtlibReader = (
2295
2411
  return { head: name, indices: [] };
2296
2412
  };
2297
2413
 
2414
+ const parseMatchPattern = (sexpr: SExpr, sort: number, after: SExpr) => {
2415
+ if (sexpr.kind !== "list" && sexpr.kind !== "symbol")
2416
+ throw new SmtParseError(
2417
+ "expecting a constructor, _, variable or constructor application",
2418
+ sexpr,
2419
+ );
2420
+ const name = sexpr.kind === "list" ? (sexpr.items[0] ?? sexpr.end) : sexpr;
2421
+ if (!isSymbol(name)) throw new SmtParseError("constructor symbol expected", name);
2422
+ const vars: string[] = [];
2423
+ if (sexpr.kind === "list")
2424
+ for (const [index, item] of sexpr.items.slice(1).entries()) {
2425
+ if (!isSymbol(item)) throw new SmtParseError("variable symbol expected", item);
2426
+ if (item.text !== "_" && vars.includes(item.text))
2427
+ throw new SmtParseError(
2428
+ "unexpected repeated variable in pattern expression",
2429
+ sexpr.items[index + 2] ?? sexpr.end,
2430
+ );
2431
+ vars.push(item.text);
2432
+ }
2433
+ const decl = funcs
2434
+ .get(name.text)
2435
+ ?.find(
2436
+ (candidate) =>
2437
+ manager.funcDecls[candidate].range === sort &&
2438
+ manager.funcDecls[candidate].domain.length === vars.length,
2439
+ );
2440
+ if (decl === undefined && vars.length > 0)
2441
+ throw new SmtParseError(
2442
+ `invalid function declaration reference, unknown indexed function ${name.text}`,
2443
+ after,
2444
+ );
2445
+ if (decl === undefined && (name.text === "true" || name.text === "false"))
2446
+ throw new SmtParseError("expecting a constructor", after);
2447
+ if (decl === undefined && BUILTIN_NAMES.has(name.text))
2448
+ throw new SmtUnsupportedError("a builtin name as a pattern of match");
2449
+ if (decl === undefined) {
2450
+ binders.depth++;
2451
+ const variable = manager.mkVar(0, sort);
2452
+ if (name.text !== "_") insertLocal(name.text, variable);
2453
+ return variable;
2454
+ }
2455
+ if (manager.funcDecls[decl].op !== OP_DT_CONSTRUCTOR)
2456
+ throw new SmtParseError("expecting a constructor", after);
2457
+ binders.depth += vars.length;
2458
+ const args = vars.map((variable, index) => {
2459
+ const boundVar = manager.mkVar(index, manager.funcDecls[decl].domain[index]);
2460
+ if (variable !== "_") insertLocal(variable, boundVar);
2461
+ return boundVar;
2462
+ });
2463
+ return manager.mkApp(decl, args, sort);
2464
+ };
2465
+
2466
+ const compileMatch = (term: number, patterns: number[], bodies: number[], at: SExpr) => {
2467
+ const sort = manager.sorts[term];
2468
+ if (!manager.isDatatypeSort(sort))
2469
+ throw new SmtParseError("pattern matching is only supported for algebraic datatypes", at);
2470
+ const constructors = getDatatypeConstructors(manager, sort);
2471
+ if (!patterns.some((pattern) => manager.kinds[pattern] === KIND_VAR)) {
2472
+ if (patterns.length < constructors.length)
2473
+ throw new SmtParseError("non-exhaustive pattern match", at);
2474
+ const marked = new Set(patterns.map((pattern) => manager.decls[pattern]));
2475
+ if (constructors.some((constructor) => !marked.has(constructor)))
2476
+ throw new SmtParseError("a constructor is missing from pattern match", at);
2477
+ }
2478
+ const subst = new VarSubst(manager, false);
2479
+ let result = -1;
2480
+ for (let index = patterns.length - 1; index >= 0; index--) {
2481
+ const pattern = patterns[index];
2482
+ const isVar = manager.kinds[pattern] === KIND_VAR;
2483
+ const recognizer = isVar ? -1 : getConstructorIs(manager, manager.decls[pattern]);
2484
+ const accessors = isVar ? [] : getConstructorAccessors(manager, manager.decls[pattern]);
2485
+ const shifted = shiftFreeVars(term, isVar ? 1 : accessors.length);
2486
+ manager.incRef(shifted);
2487
+ const substitution = isVar
2488
+ ? [shifted]
2489
+ : accessors.map((accessor) =>
2490
+ manager.mkApp(accessor, [shifted], manager.funcDecls[accessor].range),
2491
+ );
2492
+ for (const expr of substitution) manager.incRef(expr);
2493
+ const condition = isVar ? manager.trueExpr : manager.mkApp(recognizer, [term], SORT_BOOL);
2494
+ manager.incRef(condition);
2495
+ manager.decRef(shifted);
2496
+ const substituted = subst.apply(bodies[index], substitution);
2497
+ const shifter = new InvVarShifter(manager);
2498
+ const body = shifter.shift(substituted, substitution.length);
2499
+ manager.decRef(substituted);
2500
+ shifter.release();
2501
+ const args = [condition, body, result];
2502
+ const next = result === -1 ? body : mkApp(OP_ITE, args, at, getDomainSort(OP_ITE, args, at));
2503
+ manager.incRef(next);
2504
+ if (result !== -1) manager.decRef(result);
2505
+ result = next;
2506
+ manager.decRef(body);
2507
+ manager.decRef(condition);
2508
+ for (const expr of substitution) manager.decRef(expr);
2509
+ }
2510
+ subst.release();
2511
+ return result;
2512
+ };
2513
+
2298
2514
  // parse_expr. Z3 leaves the term on its stack until the command ends. A tail term is one whose
2299
2515
  // value is the value of the whole: it stays off the stack, in parsed, so that the caller of
2300
2516
  // parseTerm can have a term that nothing else holds without a reference of the parser's.
@@ -2329,6 +2545,7 @@ export const createSmtlibReader = (
2329
2545
  // Z3 skips a bad pattern as an s-expression, which cannot start with ')'.
2330
2546
  if (value.kind === ")")
2331
2547
  throw new SmtParseError("invalid s-expression, unexpected ')'", value);
2548
+ expectClosed(value);
2332
2549
  frame.next++;
2333
2550
  exprStack.push(-1);
2334
2551
  return;
@@ -2396,12 +2613,25 @@ export const createSmtlibReader = (
2396
2613
  deliver(parseRootObj(current), isTail, exprStack.length);
2397
2614
  return;
2398
2615
  }
2399
- if (head.text === "match") throw new SmtUnsupportedError("the expression match");
2616
+ if (head.text === "match") {
2617
+ frames.push({
2618
+ kind: "match",
2619
+ list: current,
2620
+ cases: [],
2621
+ isCaseForm: false,
2622
+ depth: -1,
2623
+ isTail,
2624
+ start: exprStack.length,
2625
+ next: -1,
2626
+ });
2627
+ enter(current.items[1] ?? current.end, false);
2628
+ return;
2629
+ }
2400
2630
  if (head.text === "let") {
2401
2631
  const bindings = current.items[1];
2402
2632
  if (bindings?.kind !== "list")
2403
2633
  throw new SmtParseError(
2404
- `invalid let declaration, '(' expected got ${getLastId(bindings) ?? "let"}`,
2634
+ `invalid let declaration, '(' expected got ${(bindings ?? current.end).lastId}`,
2405
2635
  bindings ?? current.end,
2406
2636
  );
2407
2637
  frames.push({
@@ -2444,7 +2674,7 @@ export const createSmtlibReader = (
2444
2674
  }
2445
2675
  // push_quant_frame.
2446
2676
  const start = exprStack.length;
2447
- const bound = bindSortedVars(current.items[1], current.end, head.text);
2677
+ const bound = bindSortedVars(current.items[1], current.end);
2448
2678
  if (bound.varSorts.length === 0)
2449
2679
  throw new SmtParseError(
2450
2680
  "invalid quantifier, list of sorted variables is empty",
@@ -2476,7 +2706,7 @@ export const createSmtlibReader = (
2476
2706
  // push_let_decl_frame.
2477
2707
  if (declaration.kind !== "list")
2478
2708
  throw new SmtParseError(
2479
- `invalid let declaration, '(' expected got ${getLastId(declaration) ?? getLastIdBefore(frame.bindings.items, frame.next) ?? "let"}`,
2709
+ `invalid let declaration, '(' expected got ${declaration.lastId}`,
2480
2710
  declaration,
2481
2711
  );
2482
2712
  const name = declaration.items[0];
@@ -2512,6 +2742,64 @@ export const createSmtlibReader = (
2512
2742
  continue;
2513
2743
  }
2514
2744
  const items = frame.list.items;
2745
+ if (frame.kind === "match") {
2746
+ if (frame.next === -1) {
2747
+ const bindings = items[2] ?? frame.list.end;
2748
+ if (bindings.kind !== "list")
2749
+ throw new SmtParseError(
2750
+ `pattern bindings should be enclosed in a parenthesis got ${bindings.lastId}`,
2751
+ bindings,
2752
+ );
2753
+ // curr_id_is_case reads the last identifier, which a '(' leaves as it was.
2754
+ frame.isCaseForm = (bindings.items[0] ?? bindings.end).lastId === "case";
2755
+ frame.cases = frame.isCaseForm ? items.slice(2) : bindings.items;
2756
+ frame.next = 0;
2757
+ } else if (frame.depth !== -1) {
2758
+ binders.depth = frame.depth;
2759
+ frame.depth = -1;
2760
+ endScope();
2761
+ const binding = frame.cases[frame.next - 1];
2762
+ const extra =
2763
+ binding.kind === "list" ? binding.items[frame.isCaseForm ? 3 : 2] : undefined;
2764
+ if (extra !== undefined)
2765
+ throw new SmtParseError(
2766
+ `invalid pattern binding, ')' expected got ${extra.lastId}`,
2767
+ extra,
2768
+ );
2769
+ }
2770
+ const binding = frame.cases[frame.next];
2771
+ if (binding !== undefined) {
2772
+ if (frame.isCaseForm && !(binding.kind === "list" && isSymbol(binding.items[0], "case")))
2773
+ throw new SmtUnsupportedError("the terms after the cases of match");
2774
+ if (binding.kind !== "list")
2775
+ throw new SmtParseError(
2776
+ `invalid pattern binding, '(' expected got ${binding.lastId}`,
2777
+ binding,
2778
+ );
2779
+ frame.next++;
2780
+ beginScope();
2781
+ frame.depth = binders.depth;
2782
+ const offset = frame.isCaseForm ? 1 : 0;
2783
+ const body = binding.items[offset + 1] ?? binding.end;
2784
+ const sort = manager.sorts[exprStack[frame.start]];
2785
+ pushRef(exprStack, parseMatchPattern(binding.items[offset] ?? binding.end, sort, body));
2786
+ enter(body, false);
2787
+ continue;
2788
+ }
2789
+ if (!frame.isCaseForm && items.length > 3)
2790
+ throw new SmtUnsupportedError("the terms after the cases of match");
2791
+ frames.pop();
2792
+ const term = exprStack[frame.start];
2793
+ const cases = exprStack.slice(frame.start + 1);
2794
+ const patterns = cases.filter((_expr, index) => index % 2 === 0);
2795
+ const bodies = cases.filter((_expr, index) => index % 2 === 1);
2796
+ const result = compileMatch(term, patterns, bodies, frame.list.end);
2797
+ // push_match_frame releases the bodies, then the patterns, then the term.
2798
+ exprStack.splice(frame.start, cases.length + 1, ...bodies, ...patterns, term);
2799
+ deliver(result, frame.isTail, frame.start);
2800
+ manager.decRef(result);
2801
+ continue;
2802
+ }
2515
2803
  if (frame.kind === "attribute") {
2516
2804
  // consume_attributes.
2517
2805
  if (exprStack.length === frame.start) {
@@ -2574,6 +2862,7 @@ export const createSmtlibReader = (
2574
2862
  // Z3 warns of an unknown attribute and skips its value as an s-expression.
2575
2863
  if (value.kind === ")")
2576
2864
  throw new SmtParseError("invalid s-expression, unexpected ')'", value);
2865
+ expectClosed(value);
2577
2866
  frame.next += 2;
2578
2867
  } else if (quantifier === undefined)
2579
2868
  throw new SmtParseError("invalid attribute, not in the scope of a quantifier", keyword);
@@ -2653,13 +2942,13 @@ export const createSmtlibReader = (
2653
2942
  return expr;
2654
2943
  };
2655
2944
 
2656
- const parseDomain = (sexpr: SExpr | undefined, at: SExpr) => {
2945
+ const parseDomain = (sexpr: SExpr) => {
2657
2946
  const context = "Parsing function declaration. Expecting sort list '('";
2658
- return expectList(sexpr, context, at).items.map((item) => parseSort(item, context));
2947
+ return expectListNext(sexpr, context).items.map((item) => parseSort(item, context));
2659
2948
  };
2660
2949
 
2661
- const parseSortParameters = (sexpr: SExpr | undefined, message: string, at: SExpr) =>
2662
- expectList(sexpr, "invalid sort declaration, parameters missing", at).items.map(
2950
+ const parseSortParameters = (sexpr: SExpr, message: string) =>
2951
+ expectListNext(sexpr, "invalid sort declaration, parameters missing").items.map(
2663
2952
  (item) => expectSymbol(item, message, item).text,
2664
2953
  );
2665
2954
 
@@ -2673,8 +2962,12 @@ export const createSmtlibReader = (
2673
2962
  missing: string[],
2674
2963
  ) => {
2675
2964
  if (sexpr.kind === "list") return parseSort(sexpr, "", bindings);
2965
+ if (sexpr.kind === ")") throw new SmtParseError("invalid sort, unexpected ')'", sexpr);
2676
2966
  if (sexpr.kind !== "symbol")
2677
- throw new SmtParseError("invalid sort, symbol, '_' or '(' expected", sexpr);
2967
+ throw new SmtParseError(
2968
+ `invalid sort, symbol, '_' or '(' expected got ${sexpr.lastId}`,
2969
+ sexpr,
2970
+ );
2678
2971
  if (sortDecls.has(sexpr.text) || bindings.has(sexpr.text))
2679
2972
  return parseSort(sexpr, "", bindings);
2680
2973
  const index = datatypeIndexes.get(sexpr.text);
@@ -2697,21 +2990,16 @@ export const createSmtlibReader = (
2697
2990
  );
2698
2991
  return items.map((item) => {
2699
2992
  if (isSymbol(item)) return { name: item.text, recognizer: `is-${item.text}`, accessors: [] };
2700
- const constructor = expectList(
2701
- item,
2702
- "invalid datatype declaration, '(' or ')' expected",
2703
- item,
2704
- );
2993
+ const constructor = expectListNext(item, "invalid datatype declaration, '(' or ')' expected");
2705
2994
  const name = expectSymbol(
2706
2995
  constructor.items[0],
2707
2996
  "invalid constructor declaration, symbol (constructor name) expected",
2708
2997
  constructor,
2709
2998
  ).text;
2710
2999
  const accessors = constructor.items.slice(1).map((accessorItem) => {
2711
- const accessor = expectList(
3000
+ const accessor = expectListNext(
2712
3001
  accessorItem,
2713
3002
  "invalid datatype declaration, '(' or ')' expected",
2714
- accessorItem,
2715
3003
  );
2716
3004
  const accessorName = expectSymbol(
2717
3005
  accessor.items[0],
@@ -2725,7 +3013,10 @@ export const createSmtlibReader = (
2725
3013
  missing,
2726
3014
  );
2727
3015
  if (accessor.items.length > 2)
2728
- throw new SmtParseError("invalid accessor declaration, ')' expected", accessor.items[2]);
3016
+ throw new SmtParseError(
3017
+ `invalid accessor declaration, ')' expected got ${accessor.items[2].lastId}`,
3018
+ accessor.items[2],
3019
+ );
2729
3020
  return { name: accessorName, range };
2730
3021
  });
2731
3022
  return { name, recognizer: `is-${name}`, accessors };
@@ -2733,27 +3024,29 @@ export const createSmtlibReader = (
2733
3024
  };
2734
3025
 
2735
3026
  const parseDatatypeBody = (
2736
- sexpr: SExpr | undefined,
3027
+ sexpr: SExpr,
2737
3028
  datatypeIndexes: ReadonlyMap<string, number>,
2738
3029
  missing: string[],
2739
- at: SExpr,
3030
+ name?: string,
2740
3031
  ) => {
2741
- const body = expectList(sexpr, "invalid datatype declaration, '(' expected", at);
2742
- if (!isSymbol(body.items[0], "par"))
3032
+ const body = expectListNext(sexpr, "invalid datatype declaration, '(' expected");
3033
+ if (!isSymbol(body.items[0], "par")) {
3034
+ if (name !== undefined) declareDatatypeSort(name, 0, body.items[0] ?? body.end);
2743
3035
  return {
2744
3036
  parameters: [],
2745
3037
  constructors: parseConstructors(body.items, NO_BINDINGS, datatypeIndexes, missing, body),
2746
3038
  };
3039
+ }
2747
3040
  const parameters = parseSortParameters(
2748
- body.items[1],
3041
+ body.items[1] ?? body.end,
2749
3042
  "invalid sort parameter, symbol or ')' expected",
2750
- body,
2751
3043
  );
2752
- const constructors = expectList(
2753
- body.items[2],
3044
+ const constructors = expectListNext(
3045
+ body.items[2] ?? body.end,
2754
3046
  "invalid constructor declaration after par, '(' expected",
2755
- body,
2756
3047
  );
3048
+ if (name !== undefined && parameters.length > 0)
3049
+ declareDatatypeSort(name, parameters.length, constructors.items[0] ?? constructors.end);
2757
3050
  return {
2758
3051
  parameters: parameters.map((_name, index) => manager.mkTypeParameter(index)),
2759
3052
  constructors: parseConstructors(
@@ -2793,11 +3086,17 @@ export const createSmtlibReader = (
2793
3086
  declare(sortDecls, name, decl);
2794
3087
  };
2795
3088
 
3089
+ const declareDatatypeSort = (name: string, arity: number, at: SExpr) =>
3090
+ declareSortDecl(
3091
+ name,
3092
+ { kind: "datatype", name, arity, siblings: [], instances: new Map() },
3093
+ at,
3094
+ );
3095
+
2796
3096
  const declareDatatypes = (list: SmtList) => {
2797
- const declaration = expectList(
2798
- list.items[1],
3097
+ const declaration = expectListNext(
3098
+ list.items[1] ?? list.end,
2799
3099
  "invalid sort declaration, parameters missing",
2800
- list,
2801
3100
  );
2802
3101
  const isSmt26 = declaration.items[0]?.kind === "list";
2803
3102
  const datatypeIndexes = new Map<string, number>();
@@ -2811,11 +3110,11 @@ export const createSmtlibReader = (
2811
3110
  );
2812
3111
  return;
2813
3112
  }
2814
- const sortDeclaration = expectList(item, "invalid sort declaration, '(' expected", item);
3113
+ const sortDeclaration = expectListNext(item, "invalid sort declaration, '(' expected");
2815
3114
  const name = expectSymbol(
2816
3115
  sortDeclaration.items[0],
2817
3116
  "invalid sort name, identified expected",
2818
- sortDeclaration,
3117
+ sortDeclaration.end,
2819
3118
  ).text;
2820
3119
  const arity = sortDeclaration.items[1];
2821
3120
  if (arity?.kind !== "numeral")
@@ -2823,26 +3122,25 @@ export const createSmtlibReader = (
2823
3122
  "invalid sort declaration, arity expected",
2824
3123
  arity ?? sortDeclaration.end,
2825
3124
  );
2826
- if (sortDeclaration.items.length > 2)
2827
- throw new SmtParseError("invalid sort declaration, ')' expected", sortDeclaration.items[2]);
2828
3125
  datatypeIndexes.set(name, index);
2829
3126
  names.push(name);
2830
3127
  arities.push(Number(arity.text));
2831
- declareSortDecl(
3128
+ declareDatatypeSort(
2832
3129
  name,
2833
- { kind: "datatype", name, arity: Number(arity.text), siblings: [], instances: new Map() },
2834
- sortDeclaration,
3130
+ Number(arity.text),
3131
+ sortDeclaration.items[2] ?? sortDeclaration.end,
2835
3132
  );
3133
+ if (sortDeclaration.items.length > 2)
3134
+ throw new SmtParseError("invalid sort declaration, ')' expected", sortDeclaration.items[2]);
2836
3135
  });
2837
- const bodies = expectList(list.items[2], "invalid datatype declaration, '(' expected", list);
3136
+ const bodies = expectListNext(
3137
+ list.items[2] ?? list.end,
3138
+ "invalid datatype declaration, '(' expected",
3139
+ );
2838
3140
  // A datatype of the older syntax may refer to any datatype of its declaration.
2839
3141
  if (!isSmt26)
2840
3142
  bodies.items.forEach((item, index) => {
2841
- const datatype = expectList(
2842
- item,
2843
- "invalid datatype declaration, '(' or ')' expected",
2844
- item,
2845
- );
3143
+ const datatype = expectListNext(item, "invalid datatype declaration, '(' or ')' expected");
2846
3144
  const name = expectSymbol(
2847
3145
  datatype.items[0],
2848
3146
  "invalid datatype declaration, symbol (datatype name) expected",
@@ -2867,10 +3165,10 @@ export const createSmtlibReader = (
2867
3165
  Array.from({ length: arities[index] }, (_unused, parameter) =>
2868
3166
  manager.mkTypeParameter(parameter),
2869
3167
  ),
2870
- parseDatatypeBody(item, datatypeIndexes, missing, list).constructors,
3168
+ parseDatatypeBody(item, datatypeIndexes, missing).constructors,
2871
3169
  );
2872
3170
  }
2873
- const datatype = expectList(item, "invalid datatype declaration, '(' or ')' expected", item);
3171
+ const datatype = expectListNext(item, "invalid datatype declaration, '(' or ')' expected");
2874
3172
  return mkDatatypeDef(
2875
3173
  manager,
2876
3174
  names[index],
@@ -2903,29 +3201,21 @@ export const createSmtlibReader = (
2903
3201
  };
2904
3202
 
2905
3203
  const declareDatatype = (list: SmtList) => {
2906
- const name = expectSymbol(list.items[1], "unexpected token used as datatype name", list);
3204
+ const name = expectSymbol(list.items[1], "unexpected token used as datatype name", list.end);
2907
3205
  const missing: string[] = [];
2908
- const bodyList = list.items[2];
2909
- const arity =
2910
- bodyList?.kind === "list" &&
2911
- isSymbol(bodyList.items[0], "par") &&
2912
- bodyList.items[1]?.kind === "list"
2913
- ? bodyList.items[1].items.length
2914
- : 0;
2915
- declareSortDecl(
3206
+ const body = parseDatatypeBody(
3207
+ list.items[2] ?? list.end,
3208
+ new Map([[name.text, 0]]),
3209
+ missing,
2916
3210
  name.text,
2917
- { kind: "datatype", name: name.text, arity, siblings: [], instances: new Map() },
2918
- name,
2919
3211
  );
2920
- const body = parseDatatypeBody(bodyList, new Map([[name.text, 0]]), missing, list);
2921
- if (list.items.length > 3)
2922
- throw new SmtParseError("invalid end of datatype declaration, ')' expected", list.items[3]);
2923
3212
  commitDatatypes(
2924
3213
  [mkDatatypeDef(manager, name.text, body.parameters, body.constructors)],
2925
3214
  missing,
2926
3215
  name,
2927
- list.end,
3216
+ list.items[3] ?? list.end,
2928
3217
  );
3218
+ expectEnd(list.items[3], "invalid end of datatype declaration, ')' expected");
2929
3219
  };
2930
3220
 
2931
3221
  // parse_rec_fun_decl: the variables are bound only while the range is parsed, and Z3 holds them
@@ -2936,7 +3226,7 @@ export const createSmtlibReader = (
2936
3226
  "invalid function/constant definition, symbol expected",
2937
3227
  at,
2938
3228
  );
2939
- const bound = bindSortedVars(items[1], at, symbol.text);
3229
+ const bound = bindSortedVars(items[1], at);
2940
3230
  const range = parseSort(items[2] ?? at, "Invalid recursive function definition");
2941
3231
  unbindSortedVars(bound.varSorts.length);
2942
3232
  return manager.mkRecFuncDecl(symbol.text, bound.varSorts, range);
@@ -2945,7 +3235,7 @@ export const createSmtlibReader = (
2945
3235
  // parse_rec_fun_body: Z3 reports a body of another sort at the token after it.
2946
3236
  const defineRecFun = (decl: number, variables: SExpr, body: SExpr, next: SExpr) => {
2947
3237
  const start = exprStack.length;
2948
- const bound = bindSortedVars(variables, body, "");
3238
+ const bound = bindSortedVars(variables, body);
2949
3239
  runTerm(body, false);
2950
3240
  const parsedBody = exprStack[exprStack.length - 1];
2951
3241
  unbindSortedVars(bound.varSorts.length);
@@ -2973,12 +3263,15 @@ export const createSmtlibReader = (
2973
3263
  subst.release();
2974
3264
  }
2975
3265
  for (const [index, sort] of domain.entries()) manager.incRef(manager.mkVar(index, sort));
2976
- const reversedVars = domain.map((_, index) => manager.mkVar(index, domain[count - index - 1]));
3266
+ const reversedVars = domain.map((_value, index) =>
3267
+ manager.mkVar(index, domain[count - index - 1]),
3268
+ );
2977
3269
  for (const reversedVar of reversedVars) manager.incRef(reversedVar);
2978
3270
  const decl = manager.mkRecFuncDecl(name, domain, manager.sorts[body]);
2979
3271
  for (const reversedVar of reversedVars) manager.decRef(reversedVar);
2980
3272
  setRecFunDefinition(manager, manager.recFunDefs.get(decl)!, true, body);
2981
3273
  declare(funcs, name, [...(funcs.get(name) ?? []), decl]);
3274
+ scopedFuncs.push(decl);
2982
3275
  };
2983
3276
 
2984
3277
  const declareCommand = (list: SmtList) => {
@@ -2988,6 +3281,7 @@ export const createSmtlibReader = (
2988
3281
  const decl = declareRecFun(list.items.slice(1), list.end);
2989
3282
  insertFunc(decl, list.items[4] ?? list.end);
2990
3283
  defineRecFun(decl, list.items[2], list.items[4] ?? list.end, list.items[5] ?? list.end);
3284
+ expectEnd(list.items[5], "invalid function/constant definition, ')' expected");
2991
3285
  shrinkRefs(exprStack, 0);
2992
3286
  return;
2993
3287
  }
@@ -3016,9 +3310,11 @@ export const createSmtlibReader = (
3016
3310
  bodies.items[index + 1] ?? bodies.end,
3017
3311
  );
3018
3312
  });
3019
- const extra = bodies.items[signatures.length];
3020
- if (extra !== undefined)
3021
- throw new SmtParseError("invalid recursive function definition, ')' expected", extra);
3313
+ expectEnd(
3314
+ bodies.items[signatures.length],
3315
+ "invalid recursive function definition, ')' expected",
3316
+ );
3317
+ expectEnd(list.items[3], "invalid function/constant definition, ')' expected");
3022
3318
  shrinkRefs(exprStack, 0);
3023
3319
  return;
3024
3320
  }
@@ -3030,7 +3326,26 @@ export const createSmtlibReader = (
3030
3326
  declareDatatype(list);
3031
3327
  return;
3032
3328
  }
3033
- const symbol = expectSymbol(list.items[1], "invalid declaration, symbol expected", list);
3329
+ const symbol = list.items[1];
3330
+ // check_nonreserved_identifier rejects _ and as, which define-const's check_identifier takes.
3331
+ if (
3332
+ !isSymbol(symbol) ||
3333
+ (name !== "define-const" && (symbol.text === "_" || symbol.text === "as"))
3334
+ )
3335
+ throw new SmtParseError(
3336
+ name === "declare-sort"
3337
+ ? "invalid sort declaration, symbol expected"
3338
+ : name === "define-sort"
3339
+ ? "invalid sort definition, symbol expected"
3340
+ : name === "define-fun"
3341
+ ? "invalid function/constant definition, symbol expected"
3342
+ : name === "define-const"
3343
+ ? "invalid constant definition, symbol expected"
3344
+ : name === "declare-fun"
3345
+ ? "invalid function declaration, symbol expected"
3346
+ : "invalid constant declaration, symbol expected",
3347
+ symbol ?? list.end,
3348
+ );
3034
3349
  if (name === "declare-sort") {
3035
3350
  if (sortDecls.has(symbol.text))
3036
3351
  throw new SmtParseError("invalid sort declaration, sort already declared/defined", symbol);
@@ -3040,8 +3355,6 @@ export const createSmtlibReader = (
3040
3355
  "invalid sort declaration, arity (<numeral>) or ')' expected",
3041
3356
  arity,
3042
3357
  );
3043
- if (list.items.length > 3)
3044
- throw new SmtParseError("invalid sort declaration, ')' expected", list.items[3]);
3045
3358
  declare(
3046
3359
  sortDecls,
3047
3360
  symbol.text,
@@ -3049,26 +3362,25 @@ export const createSmtlibReader = (
3049
3362
  ? { kind: "sort", sort: manager.mkSort(symbol.text) }
3050
3363
  : { kind: "user", name: symbol.text, arity: Number(arity.text) },
3051
3364
  );
3365
+ expectEnd(list.items[3], "invalid sort declaration, ')' expected");
3052
3366
  return;
3053
3367
  }
3054
3368
  if (name === "define-sort") {
3055
3369
  if (sortDecls.has(symbol.text))
3056
3370
  throw new SmtParseError("invalid sort definition, sort already declared/defined", symbol);
3057
3371
  const parameters = parseSortParameters(
3058
- list.items[2],
3372
+ list.items[2] ?? list.end,
3059
3373
  "invalid sort parameter, symbol or ')' expected",
3060
- list,
3061
3374
  );
3062
3375
  const body = list.items[3] ?? list.end;
3063
3376
  checkPsort(body, bindTypeParameters(parameters));
3064
3377
  declare(sortDecls, symbol.text, { kind: "definition", parameters, body });
3378
+ expectEnd(list.items[4], "invalid sort definition, ')' expected");
3065
3379
  return;
3066
3380
  }
3067
3381
  if (name === "define-fun" || name === "define-const") {
3068
3382
  const isConst = name === "define-const";
3069
- const bound = isConst
3070
- ? { names: [], varSorts: [] }
3071
- : bindSortedVars(list.items[2], list.end, symbol.text);
3383
+ const bound = isConst ? { names: [], varSorts: [] } : bindSortedVars(list.items[2], list.end);
3072
3384
  const range = parseSort(
3073
3385
  list.items[isConst ? 2 : 3] ?? list.end,
3074
3386
  isConst ? "Invalid constant definition" : "Invalid function definition",
@@ -3076,20 +3388,27 @@ export const createSmtlibReader = (
3076
3388
  runTerm(list.items[isConst ? 3 : 4] ?? list.end, false);
3077
3389
  const body = exprStack[exprStack.length - 1];
3078
3390
  if (!isConst) unbindSortedVars(bound.varSorts.length);
3391
+ const extra = list.items[isConst ? 4 : 5];
3079
3392
  if (manager.sorts[body] !== range)
3080
3393
  throw new SmtParseError(
3081
3394
  isConst
3082
3395
  ? "invalid constant definition, sort mismatch"
3083
3396
  : "invalid function/constant definition, sort mismatch",
3084
- list.end,
3397
+ extra ?? list.end,
3085
3398
  );
3086
3399
  manager.incRef(body);
3087
3400
  declare(macros, symbol.text, { domain: bound.varSorts, range, body });
3088
3401
  defineMacroFunc(symbol.text, bound.varSorts, body);
3402
+ expectEnd(
3403
+ extra,
3404
+ isConst
3405
+ ? "invalid constant definition, ')' expected"
3406
+ : "invalid function/constant definition, ')' expected",
3407
+ );
3089
3408
  shrinkRefs(exprStack, 0);
3090
3409
  return;
3091
3410
  }
3092
- const domain = name === "declare-fun" ? parseDomain(list.items[2], list) : [];
3411
+ const domain = name === "declare-fun" ? parseDomain(list.items[2] ?? list.end) : [];
3093
3412
  const range = parseSort(
3094
3413
  list.items[name === "declare-fun" ? 3 : 2] ?? list.end,
3095
3414
  name === "declare-fun" ? "Invalid function declaration" : "Invalid constant declaration",
@@ -3101,45 +3420,60 @@ export const createSmtlibReader = (
3101
3420
  for (const domainVar of vars) manager.decRef(domainVar);
3102
3421
  }
3103
3422
  const decl = manager.mkFuncDecl(symbol.text, domain, range);
3104
- checkDecl(decl, list.end);
3423
+ const extra = list.items[name === "declare-fun" ? 4 : 3];
3424
+ checkDecl(decl, extra ?? list.end);
3105
3425
  if (macros.has(symbol.text))
3106
3426
  throw new SmtUnsupportedError(`the overloaded symbol ${symbol.text}`);
3107
3427
  const existing = funcs.get(symbol.text) ?? [];
3108
3428
  if (existing.some((other) => hasSignature(other, domain, range)))
3109
3429
  throw new SmtParseError(
3110
3430
  `invalid declaration, ${domain.length === 0 ? "constant" : "function"} '${symbol.text}' (with the given signature) already declared`,
3111
- list.end,
3431
+ extra ?? list.end,
3112
3432
  );
3113
3433
  declare(funcs, symbol.text, [...existing, decl]);
3434
+ expectEnd(
3435
+ extra,
3436
+ name === "declare-fun"
3437
+ ? "invalid function declaration, ')' expected"
3438
+ : "invalid constant declaration, ')' expected",
3439
+ );
3114
3440
  };
3115
3441
 
3116
- // The caller takes the reference of the stack.
3117
- const parseFormula = (sexpr: SExpr) => {
3442
+ // The caller takes the stack's reference. Z3 reports a non-Boolean term at the token after it.
3443
+ const parseFormula = (
3444
+ sexpr: SExpr,
3445
+ follower: SmtPosition,
3446
+ message = "invalid assert command, term is not Boolean",
3447
+ ) => {
3118
3448
  runTerm(sexpr, false);
3119
3449
  const assertion = exprStack[exprStack.length - 1];
3120
- if (manager.sorts[assertion] !== SORT_BOOL)
3121
- throw new SmtParseError("invalid assert command, term is not Boolean", sexpr);
3450
+ if (manager.sorts[assertion] !== SORT_BOOL) throw new SmtParseError(message, follower);
3122
3451
  exprStack.pop();
3123
3452
  return assertion;
3124
3453
  };
3125
3454
 
3126
3455
  // An assertion is named when the last name of its term is its own.
3127
- const parseAssertion = (sexpr: SExpr) => {
3456
+ const parseAssertion = (sexpr: SExpr, follower: SmtPosition) => {
3128
3457
  releasePending();
3129
3458
  lastNamed.expr = -1;
3130
- const formula = parseFormula(sexpr);
3459
+ const formula = parseFormula(sexpr, follower);
3131
3460
  return { formula, name: lastNamed.expr === formula ? lastNamed.name : undefined };
3132
3461
  };
3133
3462
 
3134
3463
  const push = () => {
3135
3464
  releasePending();
3136
3465
  scopeStarts.push(undo.length);
3466
+ scopedFuncStarts.push(scopedFuncs.length);
3137
3467
  };
3138
3468
 
3139
- const pop = () => {
3469
+ const pop = (count: number) => {
3140
3470
  releasePending();
3141
- const start = scopeStarts.pop() ?? 0;
3471
+ const funcStart = scopedFuncStarts.splice(scopedFuncStarts.length - count)[0];
3472
+ for (const decl of scopedFuncs.splice(funcStart)) manager.eraseRecFunDef(decl);
3473
+ const start = scopeStarts.splice(scopeStarts.length - count)[0];
3142
3474
  for (const restore of undo.splice(start).reverse()) restore();
3475
+ // cmd_context::pop resets the plugin through its datatype handler.
3476
+ resetDatatypePlugin(manager);
3143
3477
  };
3144
3478
 
3145
3479
  // parser::reset, after an error: Z3 frees its stacks, and with them the terms that only the
@@ -3210,6 +3544,7 @@ export const createSmtlibReader = (
3210
3544
  pop,
3211
3545
  reset,
3212
3546
  restrictSorts,
3547
+ registerList,
3213
3548
  isUsed,
3214
3549
  isClashing,
3215
3550
  getDeclaredFuncs,
@@ -3273,7 +3608,10 @@ export const parseSmtlib = (
3273
3608
  state.reader.declareCommand(list);
3274
3609
  } else if (name === "assert") {
3275
3610
  state.isInUse = true;
3276
- const assertion = state.reader.parseFormula(list.items[1] ?? list.end);
3611
+ const assertion = state.reader.parseFormula(
3612
+ list.items[1] ?? list.end,
3613
+ list.items[2] ?? list.end,
3614
+ );
3277
3615
  const logicError = state.reader.getLogicError(assertion);
3278
3616
  if (logicError !== undefined) {
3279
3617
  manager.decRef(assertion);
@@ -3286,7 +3624,7 @@ export const parseSmtlib = (
3286
3624
  };
3287
3625
  for (;;) {
3288
3626
  try {
3289
- const list = commands.read();
3627
+ const list = commands.readCommand();
3290
3628
  if (list === undefined) return { assertions, hasCheckSat: false, rlimit: state.rlimit };
3291
3629
  if (isSymbol(list.items[0], "check-sat"))
3292
3630
  return { assertions, hasCheckSat: true, rlimit: state.rlimit };