moved old 'smt' method out of 'Main'
authorblanchet
Thu Aug 28 00:40:37 2014 +0200 (2014-08-28)
changeset 58055625bdd5c70b2
parent 58054 1d9edd486479
child 58056 fc6dd578d506
moved old 'smt' method out of 'Main'
src/HOL/Library/Library.thy
src/HOL/Library/SMT.thy
src/HOL/Library/SMT/smt_builtin.ML
src/HOL/Library/SMT/smt_config.ML
src/HOL/Library/SMT/smt_datatypes.ML
src/HOL/Library/SMT/smt_failure.ML
src/HOL/Library/SMT/smt_normalize.ML
src/HOL/Library/SMT/smt_real.ML
src/HOL/Library/SMT/smt_setup_solvers.ML
src/HOL/Library/SMT/smt_solver.ML
src/HOL/Library/SMT/smt_translate.ML
src/HOL/Library/SMT/smt_utils.ML
src/HOL/Library/SMT/smtlib_interface.ML
src/HOL/Library/SMT/z3_interface.ML
src/HOL/Library/SMT/z3_model.ML
src/HOL/Library/SMT/z3_proof_literals.ML
src/HOL/Library/SMT/z3_proof_methods.ML
src/HOL/Library/SMT/z3_proof_parser.ML
src/HOL/Library/SMT/z3_proof_reconstruction.ML
src/HOL/Library/SMT/z3_proof_tools.ML
src/HOL/Main.thy
src/HOL/Real.thy
src/HOL/SMT.thy
src/HOL/Tools/SMT/smt_builtin.ML
src/HOL/Tools/SMT/smt_config.ML
src/HOL/Tools/SMT/smt_datatypes.ML
src/HOL/Tools/SMT/smt_failure.ML
src/HOL/Tools/SMT/smt_normalize.ML
src/HOL/Tools/SMT/smt_real.ML
src/HOL/Tools/SMT/smt_setup_solvers.ML
src/HOL/Tools/SMT/smt_solver.ML
src/HOL/Tools/SMT/smt_translate.ML
src/HOL/Tools/SMT/smt_utils.ML
src/HOL/Tools/SMT/smtlib_interface.ML
src/HOL/Tools/SMT/z3_interface.ML
src/HOL/Tools/SMT/z3_model.ML
src/HOL/Tools/SMT/z3_proof_literals.ML
src/HOL/Tools/SMT/z3_proof_methods.ML
src/HOL/Tools/SMT/z3_proof_parser.ML
src/HOL/Tools/SMT/z3_proof_reconstruction.ML
src/HOL/Tools/SMT/z3_proof_tools.ML
     1.1 --- a/src/HOL/Library/Library.thy	Thu Aug 28 00:40:37 2014 +0200
     1.2 +++ b/src/HOL/Library/Library.thy	Thu Aug 28 00:40:37 2014 +0200
     1.3 @@ -61,6 +61,7 @@
     1.4    Reflection
     1.5    Saturated
     1.6    Set_Algebras
     1.7 +  SMT
     1.8    State_Monad
     1.9    Sublist
    1.10    Sum_of_Squares
     2.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     2.2 +++ b/src/HOL/Library/SMT.thy	Thu Aug 28 00:40:37 2014 +0200
     2.3 @@ -0,0 +1,429 @@
     2.4 +(*  Title:      HOL/Library/SMT.thy
     2.5 +    Author:     Sascha Boehme, TU Muenchen
     2.6 +*)
     2.7 +
     2.8 +header {* Old Version of Bindings to Satisfiability Modulo Theories (SMT) solvers *}
     2.9 +
    2.10 +theory SMT
    2.11 +imports "../Real"
    2.12 +keywords "smt_status" :: diag
    2.13 +begin
    2.14 +
    2.15 +ML_file "SMT/smt_utils.ML"
    2.16 +ML_file "SMT/smt_failure.ML"
    2.17 +ML_file "SMT/smt_config.ML"
    2.18 +
    2.19 +
    2.20 +subsection {* Triggers for quantifier instantiation *}
    2.21 +
    2.22 +text {*
    2.23 +Some SMT solvers support patterns as a quantifier instantiation
    2.24 +heuristics.  Patterns may either be positive terms (tagged by "pat")
    2.25 +triggering quantifier instantiations -- when the solver finds a
    2.26 +term matching a positive pattern, it instantiates the corresponding
    2.27 +quantifier accordingly -- or negative terms (tagged by "nopat")
    2.28 +inhibiting quantifier instantiations.  A list of patterns
    2.29 +of the same kind is called a multipattern, and all patterns in a
    2.30 +multipattern are considered conjunctively for quantifier instantiation.
    2.31 +A list of multipatterns is called a trigger, and their multipatterns
    2.32 +act disjunctively during quantifier instantiation.  Each multipattern
    2.33 +should mention at least all quantified variables of the preceding
    2.34 +quantifier block.
    2.35 +*}
    2.36 +
    2.37 +typedecl pattern
    2.38 +
    2.39 +consts
    2.40 +  pat :: "'a \<Rightarrow> pattern"
    2.41 +  nopat :: "'a \<Rightarrow> pattern"
    2.42 +
    2.43 +definition trigger :: "pattern list list \<Rightarrow> bool \<Rightarrow> bool" where "trigger _ P = P"
    2.44 +
    2.45 +
    2.46 +subsection {* Quantifier weights *}
    2.47 +
    2.48 +text {*
    2.49 +Weight annotations to quantifiers influence the priority of quantifier
    2.50 +instantiations.  They should be handled with care for solvers, which support
    2.51 +them, because incorrect choices of weights might render a problem unsolvable.
    2.52 +*}
    2.53 +
    2.54 +definition weight :: "int \<Rightarrow> bool \<Rightarrow> bool" where "weight _ P = P"
    2.55 +
    2.56 +text {*
    2.57 +Weights must be non-negative.  The value @{text 0} is equivalent to providing
    2.58 +no weight at all.
    2.59 +
    2.60 +Weights should only be used at quantifiers and only inside triggers (if the
    2.61 +quantifier has triggers).  Valid usages of weights are as follows:
    2.62 +
    2.63 +\begin{itemize}
    2.64 +\item
    2.65 +@{term "\<forall>x. trigger [[pat (P x)]] (weight 2 (P x))"}
    2.66 +\item
    2.67 +@{term "\<forall>x. weight 3 (P x)"}
    2.68 +\end{itemize}
    2.69 +*}
    2.70 +
    2.71 +
    2.72 +subsection {* Higher-order encoding *}
    2.73 +
    2.74 +text {*
    2.75 +Application is made explicit for constants occurring with varying
    2.76 +numbers of arguments.  This is achieved by the introduction of the
    2.77 +following constant.
    2.78 +*}
    2.79 +
    2.80 +definition fun_app where "fun_app f = f"
    2.81 +
    2.82 +text {*
    2.83 +Some solvers support a theory of arrays which can be used to encode
    2.84 +higher-order functions.  The following set of lemmas specifies the
    2.85 +properties of such (extensional) arrays.
    2.86 +*}
    2.87 +
    2.88 +lemmas array_rules = ext fun_upd_apply fun_upd_same fun_upd_other
    2.89 +  fun_upd_upd fun_app_def
    2.90 +
    2.91 +
    2.92 +subsection {* First-order logic *}
    2.93 +
    2.94 +text {*
    2.95 +Some SMT solvers only accept problems in first-order logic, i.e.,
    2.96 +where formulas and terms are syntactically separated. When
    2.97 +translating higher-order into first-order problems, all
    2.98 +uninterpreted constants (those not built-in in the target solver)
    2.99 +are treated as function symbols in the first-order sense.  Their
   2.100 +occurrences as head symbols in atoms (i.e., as predicate symbols) are
   2.101 +turned into terms by logically equating such atoms with @{term True}.
   2.102 +For technical reasons, @{term True} and @{term False} occurring inside
   2.103 +terms are replaced by the following constants.
   2.104 +*}
   2.105 +
   2.106 +definition term_true where "term_true = True"
   2.107 +definition term_false where "term_false = False"
   2.108 +
   2.109 +
   2.110 +subsection {* Integer division and modulo for Z3 *}
   2.111 +
   2.112 +definition z3div :: "int \<Rightarrow> int \<Rightarrow> int" where
   2.113 +  "z3div k l = (if 0 \<le> l then k div l else -(k div (-l)))"
   2.114 +
   2.115 +definition z3mod :: "int \<Rightarrow> int \<Rightarrow> int" where
   2.116 +  "z3mod k l = (if 0 \<le> l then k mod l else k mod (-l))"
   2.117 +
   2.118 +
   2.119 +subsection {* Setup *}
   2.120 +
   2.121 +ML_file "SMT/smt_builtin.ML"
   2.122 +ML_file "SMT/smt_datatypes.ML"
   2.123 +ML_file "SMT/smt_normalize.ML"
   2.124 +ML_file "SMT/smt_translate.ML"
   2.125 +ML_file "SMT/smt_solver.ML"
   2.126 +ML_file "SMT/smtlib_interface.ML"
   2.127 +ML_file "SMT/z3_interface.ML"
   2.128 +ML_file "SMT/z3_proof_parser.ML"
   2.129 +ML_file "SMT/z3_proof_tools.ML"
   2.130 +ML_file "SMT/z3_proof_literals.ML"
   2.131 +ML_file "SMT/z3_proof_methods.ML"
   2.132 +named_theorems z3_simp "simplification rules for Z3 proof reconstruction"
   2.133 +ML_file "SMT/z3_proof_reconstruction.ML"
   2.134 +ML_file "SMT/z3_model.ML"
   2.135 +ML_file "SMT/smt_setup_solvers.ML"
   2.136 +
   2.137 +setup {*
   2.138 +  SMT_Config.setup #>
   2.139 +  SMT_Normalize.setup #>
   2.140 +  SMTLIB_Interface.setup #>
   2.141 +  Z3_Interface.setup #>
   2.142 +  SMT_Setup_Solvers.setup
   2.143 +*}
   2.144 +
   2.145 +method_setup smt = {*
   2.146 +  Scan.optional Attrib.thms [] >>
   2.147 +    (fn thms => fn ctxt =>
   2.148 +      METHOD (fn facts => HEADGOAL (SMT_Solver.smt_tac ctxt (thms @ facts))))
   2.149 +*} "apply an SMT solver to the current goal"
   2.150 +
   2.151 +
   2.152 +subsection {* Configuration *}
   2.153 +
   2.154 +text {*
   2.155 +The current configuration can be printed by the command
   2.156 +@{text smt_status}, which shows the values of most options.
   2.157 +*}
   2.158 +
   2.159 +
   2.160 +
   2.161 +subsection {* General configuration options *}
   2.162 +
   2.163 +text {*
   2.164 +The option @{text smt_solver} can be used to change the target SMT
   2.165 +solver.  The possible values can be obtained from the @{text smt_status}
   2.166 +command.
   2.167 +
   2.168 +Due to licensing restrictions, Yices and Z3 are not installed/enabled
   2.169 +by default.  Z3 is free for non-commercial applications and can be enabled
   2.170 +by setting Isabelle system option @{text z3_non_commercial} to @{text yes}.
   2.171 +*}
   2.172 +
   2.173 +declare [[ smt_solver = z3 ]]
   2.174 +
   2.175 +text {*
   2.176 +Since SMT solvers are potentially non-terminating, there is a timeout
   2.177 +(given in seconds) to restrict their runtime.  A value greater than
   2.178 +120 (seconds) is in most cases not advisable.
   2.179 +*}
   2.180 +
   2.181 +declare [[ smt_timeout = 20 ]]
   2.182 +
   2.183 +text {*
   2.184 +SMT solvers apply randomized heuristics.  In case a problem is not
   2.185 +solvable by an SMT solver, changing the following option might help.
   2.186 +*}
   2.187 +
   2.188 +declare [[ smt_random_seed = 1 ]]
   2.189 +
   2.190 +text {*
   2.191 +In general, the binding to SMT solvers runs as an oracle, i.e, the SMT
   2.192 +solvers are fully trusted without additional checks.  The following
   2.193 +option can cause the SMT solver to run in proof-producing mode, giving
   2.194 +a checkable certificate.  This is currently only implemented for Z3.
   2.195 +*}
   2.196 +
   2.197 +declare [[ smt_oracle = false ]]
   2.198 +
   2.199 +text {*
   2.200 +Each SMT solver provides several commandline options to tweak its
   2.201 +behaviour.  They can be passed to the solver by setting the following
   2.202 +options.
   2.203 +*}
   2.204 +
   2.205 +declare [[ cvc3_options = "" ]]
   2.206 +declare [[ yices_options = "" ]]
   2.207 +declare [[ z3_options = "" ]]
   2.208 +
   2.209 +text {*
   2.210 +Enable the following option to use built-in support for datatypes and
   2.211 +records.  Currently, this is only implemented for Z3 running in oracle
   2.212 +mode.
   2.213 +*}
   2.214 +
   2.215 +declare [[ smt_datatypes = false ]]
   2.216 +
   2.217 +text {*
   2.218 +The SMT method provides an inference mechanism to detect simple triggers
   2.219 +in quantified formulas, which might increase the number of problems
   2.220 +solvable by SMT solvers (note: triggers guide quantifier instantiations
   2.221 +in the SMT solver).  To turn it on, set the following option.
   2.222 +*}
   2.223 +
   2.224 +declare [[ smt_infer_triggers = false ]]
   2.225 +
   2.226 +text {*
   2.227 +The SMT method monomorphizes the given facts, that is, it tries to
   2.228 +instantiate all schematic type variables with fixed types occurring
   2.229 +in the problem.  This is a (possibly nonterminating) fixed-point
   2.230 +construction whose cycles are limited by the following option.
   2.231 +*}
   2.232 +
   2.233 +declare [[ monomorph_max_rounds = 5 ]]
   2.234 +
   2.235 +text {*
   2.236 +In addition, the number of generated monomorphic instances is limited
   2.237 +by the following option.
   2.238 +*}
   2.239 +
   2.240 +declare [[ monomorph_max_new_instances = 500 ]]
   2.241 +
   2.242 +
   2.243 +
   2.244 +subsection {* Certificates *}
   2.245 +
   2.246 +text {*
   2.247 +By setting the option @{text smt_certificates} to the name of a file,
   2.248 +all following applications of an SMT solver a cached in that file.
   2.249 +Any further application of the same SMT solver (using the very same
   2.250 +configuration) re-uses the cached certificate instead of invoking the
   2.251 +solver.  An empty string disables caching certificates.
   2.252 +
   2.253 +The filename should be given as an explicit path.  It is good
   2.254 +practice to use the name of the current theory (with ending
   2.255 +@{text ".certs"} instead of @{text ".thy"}) as the certificates file.
   2.256 +Certificate files should be used at most once in a certain theory context,
   2.257 +to avoid race conditions with other concurrent accesses.
   2.258 +*}
   2.259 +
   2.260 +declare [[ smt_certificates = "" ]]
   2.261 +
   2.262 +text {*
   2.263 +The option @{text smt_read_only_certificates} controls whether only
   2.264 +stored certificates are should be used or invocation of an SMT solver
   2.265 +is allowed.  When set to @{text true}, no SMT solver will ever be
   2.266 +invoked and only the existing certificates found in the configured
   2.267 +cache are used;  when set to @{text false} and there is no cached
   2.268 +certificate for some proposition, then the configured SMT solver is
   2.269 +invoked.
   2.270 +*}
   2.271 +
   2.272 +declare [[ smt_read_only_certificates = false ]]
   2.273 +
   2.274 +
   2.275 +
   2.276 +subsection {* Tracing *}
   2.277 +
   2.278 +text {*
   2.279 +The SMT method, when applied, traces important information.  To
   2.280 +make it entirely silent, set the following option to @{text false}.
   2.281 +*}
   2.282 +
   2.283 +declare [[ smt_verbose = true ]]
   2.284 +
   2.285 +text {*
   2.286 +For tracing the generated problem file given to the SMT solver as
   2.287 +well as the returned result of the solver, the option
   2.288 +@{text smt_trace} should be set to @{text true}.
   2.289 +*}
   2.290 +
   2.291 +declare [[ smt_trace = false ]]
   2.292 +
   2.293 +text {*
   2.294 +From the set of assumptions given to the SMT solver, those assumptions
   2.295 +used in the proof are traced when the following option is set to
   2.296 +@{term true}.  This only works for Z3 when it runs in non-oracle mode
   2.297 +(see options @{text smt_solver} and @{text smt_oracle} above).
   2.298 +*}
   2.299 +
   2.300 +declare [[ smt_trace_used_facts = false ]]
   2.301 +
   2.302 +
   2.303 +
   2.304 +subsection {* Schematic rules for Z3 proof reconstruction *}
   2.305 +
   2.306 +text {*
   2.307 +Several prof rules of Z3 are not very well documented.  There are two
   2.308 +lemma groups which can turn failing Z3 proof reconstruction attempts
   2.309 +into succeeding ones: the facts in @{text z3_rule} are tried prior to
   2.310 +any implemented reconstruction procedure for all uncertain Z3 proof
   2.311 +rules;  the facts in @{text z3_simp} are only fed to invocations of
   2.312 +the simplifier when reconstructing theory-specific proof steps.
   2.313 +*}
   2.314 +
   2.315 +lemmas [z3_rule] =
   2.316 +  refl eq_commute conj_commute disj_commute simp_thms nnf_simps
   2.317 +  ring_distribs field_simps times_divide_eq_right times_divide_eq_left
   2.318 +  if_True if_False not_not
   2.319 +
   2.320 +lemma [z3_rule]:
   2.321 +  "(P \<and> Q) = (\<not>(\<not>P \<or> \<not>Q))"
   2.322 +  "(P \<and> Q) = (\<not>(\<not>Q \<or> \<not>P))"
   2.323 +  "(\<not>P \<and> Q) = (\<not>(P \<or> \<not>Q))"
   2.324 +  "(\<not>P \<and> Q) = (\<not>(\<not>Q \<or> P))"
   2.325 +  "(P \<and> \<not>Q) = (\<not>(\<not>P \<or> Q))"
   2.326 +  "(P \<and> \<not>Q) = (\<not>(Q \<or> \<not>P))"
   2.327 +  "(\<not>P \<and> \<not>Q) = (\<not>(P \<or> Q))"
   2.328 +  "(\<not>P \<and> \<not>Q) = (\<not>(Q \<or> P))"
   2.329 +  by auto
   2.330 +
   2.331 +lemma [z3_rule]:
   2.332 +  "(P \<longrightarrow> Q) = (Q \<or> \<not>P)"
   2.333 +  "(\<not>P \<longrightarrow> Q) = (P \<or> Q)"
   2.334 +  "(\<not>P \<longrightarrow> Q) = (Q \<or> P)"
   2.335 +  "(True \<longrightarrow> P) = P"
   2.336 +  "(P \<longrightarrow> True) = True"
   2.337 +  "(False \<longrightarrow> P) = True"
   2.338 +  "(P \<longrightarrow> P) = True"
   2.339 +  by auto
   2.340 +
   2.341 +lemma [z3_rule]:
   2.342 +  "((P = Q) \<longrightarrow> R) = (R | (Q = (\<not>P)))"
   2.343 +  by auto
   2.344 +
   2.345 +lemma [z3_rule]:
   2.346 +  "(\<not>True) = False"
   2.347 +  "(\<not>False) = True"
   2.348 +  "(x = x) = True"
   2.349 +  "(P = True) = P"
   2.350 +  "(True = P) = P"
   2.351 +  "(P = False) = (\<not>P)"
   2.352 +  "(False = P) = (\<not>P)"
   2.353 +  "((\<not>P) = P) = False"
   2.354 +  "(P = (\<not>P)) = False"
   2.355 +  "((\<not>P) = (\<not>Q)) = (P = Q)"
   2.356 +  "\<not>(P = (\<not>Q)) = (P = Q)"
   2.357 +  "\<not>((\<not>P) = Q) = (P = Q)"
   2.358 +  "(P \<noteq> Q) = (Q = (\<not>P))"
   2.359 +  "(P = Q) = ((\<not>P \<or> Q) \<and> (P \<or> \<not>Q))"
   2.360 +  "(P \<noteq> Q) = ((\<not>P \<or> \<not>Q) \<and> (P \<or> Q))"
   2.361 +  by auto
   2.362 +
   2.363 +lemma [z3_rule]:
   2.364 +  "(if P then P else \<not>P) = True"
   2.365 +  "(if \<not>P then \<not>P else P) = True"
   2.366 +  "(if P then True else False) = P"
   2.367 +  "(if P then False else True) = (\<not>P)"
   2.368 +  "(if P then Q else True) = ((\<not>P) \<or> Q)"
   2.369 +  "(if P then Q else True) = (Q \<or> (\<not>P))"
   2.370 +  "(if P then Q else \<not>Q) = (P = Q)"
   2.371 +  "(if P then Q else \<not>Q) = (Q = P)"
   2.372 +  "(if P then \<not>Q else Q) = (P = (\<not>Q))"
   2.373 +  "(if P then \<not>Q else Q) = ((\<not>Q) = P)"
   2.374 +  "(if \<not>P then x else y) = (if P then y else x)"
   2.375 +  "(if P then (if Q then x else y) else x) = (if P \<and> (\<not>Q) then y else x)"
   2.376 +  "(if P then (if Q then x else y) else x) = (if (\<not>Q) \<and> P then y else x)"
   2.377 +  "(if P then (if Q then x else y) else y) = (if P \<and> Q then x else y)"
   2.378 +  "(if P then (if Q then x else y) else y) = (if Q \<and> P then x else y)"
   2.379 +  "(if P then x else if P then y else z) = (if P then x else z)"
   2.380 +  "(if P then x else if Q then x else y) = (if P \<or> Q then x else y)"
   2.381 +  "(if P then x else if Q then x else y) = (if Q \<or> P then x else y)"
   2.382 +  "(if P then x = y else x = z) = (x = (if P then y else z))"
   2.383 +  "(if P then x = y else y = z) = (y = (if P then x else z))"
   2.384 +  "(if P then x = y else z = y) = (y = (if P then x else z))"
   2.385 +  by auto
   2.386 +
   2.387 +lemma [z3_rule]:
   2.388 +  "0 + (x::int) = x"
   2.389 +  "x + 0 = x"
   2.390 +  "x + x = 2 * x"
   2.391 +  "0 * x = 0"
   2.392 +  "1 * x = x"
   2.393 +  "x + y = y + x"
   2.394 +  by auto
   2.395 +
   2.396 +lemma [z3_rule]:  (* for def-axiom *)
   2.397 +  "P = Q \<or> P \<or> Q"
   2.398 +  "P = Q \<or> \<not>P \<or> \<not>Q"
   2.399 +  "(\<not>P) = Q \<or> \<not>P \<or> Q"
   2.400 +  "(\<not>P) = Q \<or> P \<or> \<not>Q"
   2.401 +  "P = (\<not>Q) \<or> \<not>P \<or> Q"
   2.402 +  "P = (\<not>Q) \<or> P \<or> \<not>Q"
   2.403 +  "P \<noteq> Q \<or> P \<or> \<not>Q"
   2.404 +  "P \<noteq> Q \<or> \<not>P \<or> Q"
   2.405 +  "P \<noteq> (\<not>Q) \<or> P \<or> Q"
   2.406 +  "(\<not>P) \<noteq> Q \<or> P \<or> Q"
   2.407 +  "P \<or> Q \<or> P \<noteq> (\<not>Q)"
   2.408 +  "P \<or> Q \<or> (\<not>P) \<noteq> Q"
   2.409 +  "P \<or> \<not>Q \<or> P \<noteq> Q"
   2.410 +  "\<not>P \<or> Q \<or> P \<noteq> Q"
   2.411 +  "P \<or> y = (if P then x else y)"
   2.412 +  "P \<or> (if P then x else y) = y"
   2.413 +  "\<not>P \<or> x = (if P then x else y)"
   2.414 +  "\<not>P \<or>  (if P then x else y) = x"
   2.415 +  "P \<or> R \<or> \<not>(if P then Q else R)"
   2.416 +  "\<not>P \<or> Q \<or> \<not>(if P then Q else R)"
   2.417 +  "\<not>(if P then Q else R) \<or> \<not>P \<or> Q"
   2.418 +  "\<not>(if P then Q else R) \<or> P \<or> R"
   2.419 +  "(if P then Q else R) \<or> \<not>P \<or> \<not>Q"
   2.420 +  "(if P then Q else R) \<or> P \<or> \<not>R"
   2.421 +  "(if P then \<not>Q else R) \<or> \<not>P \<or> Q"
   2.422 +  "(if P then Q else \<not>R) \<or> P \<or> R"
   2.423 +  by auto
   2.424 +
   2.425 +ML_file "SMT/smt_real.ML"
   2.426 +setup SMT_Real.setup
   2.427 +
   2.428 +hide_type (open) pattern
   2.429 +hide_const fun_app term_true term_false z3div z3mod
   2.430 +hide_const (open) trigger pat nopat weight
   2.431 +
   2.432 +end
     3.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.2 +++ b/src/HOL/Library/SMT/smt_builtin.ML	Thu Aug 28 00:40:37 2014 +0200
     3.3 @@ -0,0 +1,231 @@
     3.4 +(*  Title:      HOL/Library/SMT/smt_builtin.ML
     3.5 +    Author:     Sascha Boehme, TU Muenchen
     3.6 +
     3.7 +Tables of types and terms directly supported by SMT solvers.
     3.8 +*)
     3.9 +
    3.10 +signature SMT_BUILTIN =
    3.11 +sig
    3.12 +  (*for experiments*)
    3.13 +  val filter_builtins: (typ -> bool) -> Proof.context -> Proof.context
    3.14 +
    3.15 +  (*built-in types*)
    3.16 +  val add_builtin_typ: SMT_Utils.class ->
    3.17 +    typ * (typ -> string option) * (typ -> int -> string option) ->
    3.18 +    Context.generic -> Context.generic
    3.19 +  val add_builtin_typ_ext: typ * (typ -> bool) -> Context.generic ->
    3.20 +    Context.generic
    3.21 +  val dest_builtin_typ: Proof.context -> typ -> string option
    3.22 +  val is_builtin_typ_ext: Proof.context -> typ -> bool
    3.23 +
    3.24 +  (*built-in numbers*)
    3.25 +  val dest_builtin_num: Proof.context -> term -> (string * typ) option
    3.26 +  val is_builtin_num: Proof.context -> term -> bool
    3.27 +  val is_builtin_num_ext: Proof.context -> term -> bool
    3.28 +
    3.29 +  (*built-in functions*)
    3.30 +  type 'a bfun = Proof.context -> typ -> term list -> 'a
    3.31 +  type bfunr = string * int * term list * (term list -> term)
    3.32 +  val add_builtin_fun: SMT_Utils.class ->
    3.33 +    (string * typ) * bfunr option bfun -> Context.generic -> Context.generic
    3.34 +  val add_builtin_fun': SMT_Utils.class -> term * string -> Context.generic ->
    3.35 +    Context.generic
    3.36 +  val add_builtin_fun_ext: (string * typ) * term list bfun ->
    3.37 +    Context.generic -> Context.generic
    3.38 +  val add_builtin_fun_ext': string * typ -> Context.generic -> Context.generic
    3.39 +  val add_builtin_fun_ext'': string -> Context.generic -> Context.generic
    3.40 +  val dest_builtin_fun: Proof.context -> string * typ -> term list ->
    3.41 +    bfunr option
    3.42 +  val dest_builtin_eq: Proof.context -> term -> term -> bfunr option
    3.43 +  val dest_builtin_pred: Proof.context -> string * typ -> term list ->
    3.44 +    bfunr option
    3.45 +  val dest_builtin_conn: Proof.context -> string * typ -> term list ->
    3.46 +    bfunr option
    3.47 +  val dest_builtin: Proof.context -> string * typ -> term list -> bfunr option
    3.48 +  val dest_builtin_ext: Proof.context -> string * typ -> term list ->
    3.49 +    term list option
    3.50 +  val is_builtin_fun: Proof.context -> string * typ -> term list -> bool
    3.51 +  val is_builtin_fun_ext: Proof.context -> string * typ -> term list -> bool
    3.52 +end
    3.53 +
    3.54 +structure SMT_Builtin: SMT_BUILTIN =
    3.55 +struct
    3.56 +
    3.57 +
    3.58 +(* built-in tables *)
    3.59 +
    3.60 +datatype ('a, 'b) kind = Ext of 'a | Int of 'b
    3.61 +
    3.62 +type ('a, 'b) ttab = ((typ * ('a, 'b) kind) Ord_List.T) SMT_Utils.dict 
    3.63 +
    3.64 +fun typ_ord ((T, _), (U, _)) =
    3.65 +  let
    3.66 +    fun tord (TVar _, Type _) = GREATER
    3.67 +      | tord (Type _, TVar _) = LESS
    3.68 +      | tord (Type (n, Ts), Type (m, Us)) =
    3.69 +          if n = m then list_ord tord (Ts, Us)
    3.70 +          else Term_Ord.typ_ord (T, U)
    3.71 +      | tord TU = Term_Ord.typ_ord TU
    3.72 +  in tord (T, U) end
    3.73 +
    3.74 +fun insert_ttab cs T f =
    3.75 +  SMT_Utils.dict_map_default (cs, [])
    3.76 +    (Ord_List.insert typ_ord (perhaps (try Logic.varifyT_global) T, f))
    3.77 +
    3.78 +fun merge_ttab ttabp =
    3.79 +  SMT_Utils.dict_merge (Ord_List.merge typ_ord) ttabp
    3.80 +
    3.81 +fun lookup_ttab ctxt ttab T =
    3.82 +  let fun match (U, _) = Sign.typ_instance (Proof_Context.theory_of ctxt) (T, U)
    3.83 +  in
    3.84 +    get_first (find_first match)
    3.85 +      (SMT_Utils.dict_lookup ttab (SMT_Config.solver_class_of ctxt))
    3.86 +  end
    3.87 +
    3.88 +type ('a, 'b) btab = ('a, 'b) ttab Symtab.table
    3.89 +
    3.90 +fun insert_btab cs n T f =
    3.91 +  Symtab.map_default (n, []) (insert_ttab cs T f)
    3.92 +
    3.93 +fun merge_btab btabp = Symtab.join (K merge_ttab) btabp
    3.94 +
    3.95 +fun lookup_btab ctxt btab (n, T) =
    3.96 +  (case Symtab.lookup btab n of
    3.97 +    NONE => NONE
    3.98 +  | SOME ttab => lookup_ttab ctxt ttab T)
    3.99 +
   3.100 +type 'a bfun = Proof.context -> typ -> term list -> 'a
   3.101 +
   3.102 +type bfunr = string * int * term list * (term list -> term)
   3.103 +
   3.104 +structure Builtins = Generic_Data
   3.105 +(
   3.106 +  type T =
   3.107 +    (typ -> bool, (typ -> string option) * (typ -> int -> string option)) ttab *
   3.108 +    (term list bfun, bfunr option bfun) btab
   3.109 +  val empty = ([], Symtab.empty)
   3.110 +  val extend = I
   3.111 +  fun merge ((t1, b1), (t2, b2)) = (merge_ttab (t1, t2), merge_btab (b1, b2))
   3.112 +)
   3.113 +
   3.114 +fun filter_ttab keep_T = map (apsnd (filter (keep_T o fst)))
   3.115 +
   3.116 +fun filter_builtins keep_T =
   3.117 +  Context.proof_map (Builtins.map (fn (ttab, btab) =>
   3.118 +    (filter_ttab keep_T ttab, Symtab.map (K (filter_ttab keep_T)) btab)))
   3.119 +
   3.120 +
   3.121 +(* built-in types *)
   3.122 +
   3.123 +fun add_builtin_typ cs (T, f, g) =
   3.124 +  Builtins.map (apfst (insert_ttab cs T (Int (f, g))))
   3.125 +
   3.126 +fun add_builtin_typ_ext (T, f) =
   3.127 +  Builtins.map (apfst (insert_ttab SMT_Utils.basicC T (Ext f)))
   3.128 +
   3.129 +fun lookup_builtin_typ ctxt =
   3.130 +  lookup_ttab ctxt (fst (Builtins.get (Context.Proof ctxt)))
   3.131 +
   3.132 +fun dest_builtin_typ ctxt T =
   3.133 +  (case lookup_builtin_typ ctxt T of
   3.134 +    SOME (_, Int (f, _)) => f T
   3.135 +  | _ => NONE) 
   3.136 +
   3.137 +fun is_builtin_typ_ext ctxt T =
   3.138 +  (case lookup_builtin_typ ctxt T of
   3.139 +    SOME (_, Int (f, _)) => is_some (f T)
   3.140 +  | SOME (_, Ext f) => f T
   3.141 +  | NONE => false)
   3.142 +
   3.143 +
   3.144 +(* built-in numbers *)
   3.145 +
   3.146 +fun dest_builtin_num ctxt t =
   3.147 +  (case try HOLogic.dest_number t of
   3.148 +    NONE => NONE
   3.149 +  | SOME (T, i) =>
   3.150 +      if i < 0 then NONE else
   3.151 +        (case lookup_builtin_typ ctxt T of
   3.152 +          SOME (_, Int (_, g)) => g T i |> Option.map (rpair T)
   3.153 +        | _ => NONE))
   3.154 +
   3.155 +val is_builtin_num = is_some oo dest_builtin_num
   3.156 +
   3.157 +fun is_builtin_num_ext ctxt t =
   3.158 +  (case try HOLogic.dest_number t of
   3.159 +    NONE => false
   3.160 +  | SOME (T, _) => is_builtin_typ_ext ctxt T)
   3.161 +
   3.162 +
   3.163 +(* built-in functions *)
   3.164 +
   3.165 +fun add_builtin_fun cs ((n, T), f) =
   3.166 +  Builtins.map (apsnd (insert_btab cs n T (Int f)))
   3.167 +
   3.168 +fun add_builtin_fun' cs (t, n) =
   3.169 +  let
   3.170 +    val c as (m, T) = Term.dest_Const t
   3.171 +    fun app U ts = Term.list_comb (Const (m, U), ts)
   3.172 +    fun bfun _ U ts = SOME (n, length (Term.binder_types T), ts, app U)
   3.173 +  in add_builtin_fun cs (c, bfun) end
   3.174 +
   3.175 +fun add_builtin_fun_ext ((n, T), f) =
   3.176 +  Builtins.map (apsnd (insert_btab SMT_Utils.basicC n T (Ext f)))
   3.177 +
   3.178 +fun add_builtin_fun_ext' c = add_builtin_fun_ext (c, fn _ => fn _ => I)
   3.179 +
   3.180 +fun add_builtin_fun_ext'' n context =
   3.181 +  let val thy = Context.theory_of context
   3.182 +  in add_builtin_fun_ext' (n, Sign.the_const_type thy n) context end
   3.183 +
   3.184 +fun lookup_builtin_fun ctxt =
   3.185 +  lookup_btab ctxt (snd (Builtins.get (Context.Proof ctxt)))
   3.186 +
   3.187 +fun dest_builtin_fun ctxt (c as (_, T)) ts =
   3.188 +  (case lookup_builtin_fun ctxt c of
   3.189 +    SOME (_, Int f) => f ctxt T ts
   3.190 +  | _ => NONE)
   3.191 +
   3.192 +fun dest_builtin_eq ctxt t u =
   3.193 +  let
   3.194 +    val aT = TFree (Name.aT, @{sort type})
   3.195 +    val c = (@{const_name HOL.eq}, aT --> aT --> @{typ bool})
   3.196 +    fun mk ts = Term.list_comb (HOLogic.eq_const (Term.fastype_of (hd ts)), ts)
   3.197 +  in
   3.198 +    dest_builtin_fun ctxt c []
   3.199 +    |> Option.map (fn (n, i, _, _) => (n, i, [t, u], mk))
   3.200 +  end
   3.201 +
   3.202 +fun special_builtin_fun pred ctxt (c as (_, T)) ts =
   3.203 +  if pred (Term.body_type T, Term.binder_types T) then
   3.204 +    dest_builtin_fun ctxt c ts
   3.205 +  else NONE
   3.206 +
   3.207 +fun dest_builtin_pred ctxt = special_builtin_fun (equal @{typ bool} o fst) ctxt
   3.208 +
   3.209 +fun dest_builtin_conn ctxt =
   3.210 +  special_builtin_fun (forall (equal @{typ bool}) o (op ::)) ctxt
   3.211 +
   3.212 +fun dest_builtin ctxt c ts =
   3.213 +  let val t = Term.list_comb (Const c, ts)
   3.214 +  in
   3.215 +    (case dest_builtin_num ctxt t of
   3.216 +      SOME (n, _) => SOME (n, 0, [], K t)
   3.217 +    | NONE => dest_builtin_fun ctxt c ts)
   3.218 +  end
   3.219 +
   3.220 +fun dest_builtin_fun_ext ctxt (c as (_, T)) ts =    
   3.221 +  (case lookup_builtin_fun ctxt c of
   3.222 +    SOME (_, Int f) => f ctxt T ts |> Option.map (fn (_, _, us, _) => us)
   3.223 +  | SOME (_, Ext f) => SOME (f ctxt T ts)
   3.224 +  | NONE => NONE)
   3.225 +
   3.226 +fun dest_builtin_ext ctxt c ts =
   3.227 +  if is_builtin_num_ext ctxt (Term.list_comb (Const c, ts)) then SOME []
   3.228 +  else dest_builtin_fun_ext ctxt c ts
   3.229 +
   3.230 +fun is_builtin_fun ctxt c ts = is_some (dest_builtin_fun ctxt c ts)
   3.231 +
   3.232 +fun is_builtin_fun_ext ctxt c ts = is_some (dest_builtin_fun_ext ctxt c ts)
   3.233 +
   3.234 +end
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/src/HOL/Library/SMT/smt_config.ML	Thu Aug 28 00:40:37 2014 +0200
     4.3 @@ -0,0 +1,254 @@
     4.4 +(*  Title:      HOL/Library/SMT/smt_config.ML
     4.5 +    Author:     Sascha Boehme, TU Muenchen
     4.6 +
     4.7 +Configuration options and diagnostic tools for SMT.
     4.8 +*)
     4.9 +
    4.10 +signature SMT_CONFIG =
    4.11 +sig
    4.12 +  (*solver*)
    4.13 +  type solver_info = {
    4.14 +    name: string,
    4.15 +    class: Proof.context -> SMT_Utils.class,
    4.16 +    avail: unit -> bool,
    4.17 +    options: Proof.context -> string list }
    4.18 +  val add_solver: solver_info -> Context.generic -> Context.generic
    4.19 +  val set_solver_options: string * string -> Context.generic -> Context.generic
    4.20 +  val is_available: Proof.context -> string -> bool
    4.21 +  val available_solvers_of: Proof.context -> string list
    4.22 +  val select_solver: string -> Context.generic -> Context.generic
    4.23 +  val solver_of: Proof.context -> string
    4.24 +  val solver_class_of: Proof.context -> SMT_Utils.class
    4.25 +  val solver_options_of: Proof.context -> string list
    4.26 +
    4.27 +  (*options*)
    4.28 +  val oracle: bool Config.T
    4.29 +  val datatypes: bool Config.T
    4.30 +  val timeout: real Config.T
    4.31 +  val random_seed: int Config.T
    4.32 +  val read_only_certificates: bool Config.T
    4.33 +  val verbose: bool Config.T
    4.34 +  val trace: bool Config.T
    4.35 +  val trace_used_facts: bool Config.T
    4.36 +  val monomorph_limit: int Config.T
    4.37 +  val monomorph_instances: int Config.T
    4.38 +  val infer_triggers: bool Config.T
    4.39 +  val filter_only_facts: bool Config.T
    4.40 +  val debug_files: string Config.T
    4.41 +
    4.42 +  (*tools*)
    4.43 +  val with_timeout: Proof.context -> ('a -> 'b) -> 'a -> 'b
    4.44 +
    4.45 +  (*diagnostics*)
    4.46 +  val trace_msg: Proof.context -> ('a -> string) -> 'a -> unit
    4.47 +  val verbose_msg: Proof.context -> ('a -> string) -> 'a -> unit
    4.48 +
    4.49 +  (*certificates*)
    4.50 +  val select_certificates: string -> Context.generic -> Context.generic
    4.51 +  val certificates_of: Proof.context -> Cache_IO.cache option
    4.52 +
    4.53 +  (*setup*)
    4.54 +  val setup: theory -> theory
    4.55 +  val print_setup: Proof.context -> unit
    4.56 +end
    4.57 +
    4.58 +structure SMT_Config: SMT_CONFIG =
    4.59 +struct
    4.60 +
    4.61 +(* solver *)
    4.62 +
    4.63 +type solver_info = {
    4.64 +  name: string,
    4.65 +  class: Proof.context -> SMT_Utils.class,
    4.66 +  avail: unit -> bool,
    4.67 +  options: Proof.context -> string list }
    4.68 +
    4.69 +(* FIXME just one data slot (record) per program unit *)
    4.70 +structure Solvers = Generic_Data
    4.71 +(
    4.72 +  type T = (solver_info * string list) Symtab.table * string option
    4.73 +  val empty = (Symtab.empty, NONE)
    4.74 +  val extend = I
    4.75 +  fun merge ((ss1, s1), (ss2, s2)) =
    4.76 +    (Symtab.merge (K true) (ss1, ss2), merge_options (s1, s2))
    4.77 +)
    4.78 +
    4.79 +fun set_solver_options (name, options) =
    4.80 +  let val opts = String.tokens (Symbol.is_ascii_blank o str) options
    4.81 +  in Solvers.map (apfst (Symtab.map_entry name (apsnd (K opts)))) end
    4.82 +
    4.83 +fun add_solver (info as {name, ...} : solver_info) context =
    4.84 +  if Symtab.defined (fst (Solvers.get context)) name then
    4.85 +    error ("Solver already registered: " ^ quote name)
    4.86 +  else
    4.87 +    context
    4.88 +    |> Solvers.map (apfst (Symtab.update (name, (info, []))))
    4.89 +    |> Context.map_theory (Attrib.setup (Binding.name (name ^ "_options"))
    4.90 +        (Scan.lift (@{keyword "="} |-- Args.name) >>
    4.91 +          (Thm.declaration_attribute o K o set_solver_options o pair name))
    4.92 +        ("Additional command line options for SMT solver " ^ quote name))
    4.93 +
    4.94 +fun all_solvers_of ctxt = Symtab.keys (fst (Solvers.get (Context.Proof ctxt)))
    4.95 +
    4.96 +fun solver_name_of ctxt = snd (Solvers.get (Context.Proof ctxt))
    4.97 +
    4.98 +fun is_available ctxt name =
    4.99 +  (case Symtab.lookup (fst (Solvers.get (Context.Proof ctxt))) name of
   4.100 +    SOME ({avail, ...}, _) => avail ()
   4.101 +  | NONE => false)
   4.102 +
   4.103 +fun available_solvers_of ctxt =
   4.104 +  filter (is_available ctxt) (all_solvers_of ctxt)
   4.105 +
   4.106 +fun warn_solver (Context.Proof ctxt) name =
   4.107 +      if Context_Position.is_visible ctxt then
   4.108 +        warning ("The SMT solver " ^ quote name ^ " is not installed.")
   4.109 +      else ()
   4.110 +  | warn_solver _ _ = ();
   4.111 +
   4.112 +fun select_solver name context =
   4.113 +  let
   4.114 +    val ctxt = Context.proof_of context
   4.115 +    val upd = Solvers.map (apsnd (K (SOME name)))
   4.116 +  in
   4.117 +    if not (member (op =) (all_solvers_of ctxt) name) then
   4.118 +      error ("Trying to select unknown solver: " ^ quote name)
   4.119 +    else if not (is_available ctxt name) then
   4.120 +      (warn_solver context name; upd context)
   4.121 +    else upd context
   4.122 +  end
   4.123 +
   4.124 +fun no_solver_err () = error "No SMT solver selected"
   4.125 +
   4.126 +fun solver_of ctxt =
   4.127 +  (case solver_name_of ctxt of
   4.128 +    SOME name => name
   4.129 +  | NONE => no_solver_err ())
   4.130 +
   4.131 +fun solver_info_of default select ctxt =
   4.132 +  (case Solvers.get (Context.Proof ctxt) of
   4.133 +    (solvers, SOME name) => select (Symtab.lookup solvers name)
   4.134 +  | (_, NONE) => default ())
   4.135 +
   4.136 +fun solver_class_of ctxt =
   4.137 +  let fun class_of ({class, ...}: solver_info, _) = class ctxt
   4.138 +  in solver_info_of no_solver_err (class_of o the) ctxt end
   4.139 +
   4.140 +fun solver_options_of ctxt =
   4.141 +  let
   4.142 +    fun all_options NONE = []
   4.143 +      | all_options (SOME ({options, ...} : solver_info, opts)) =
   4.144 +          opts @ options ctxt
   4.145 +  in solver_info_of (K []) all_options ctxt end
   4.146 +
   4.147 +val setup_solver =
   4.148 +  Attrib.setup @{binding smt_solver}
   4.149 +    (Scan.lift (@{keyword "="} |-- Args.name) >>
   4.150 +      (Thm.declaration_attribute o K o select_solver))
   4.151 +    "SMT solver configuration"
   4.152 +
   4.153 +
   4.154 +(* options *)
   4.155 +
   4.156 +val oracle = Attrib.setup_config_bool @{binding smt_oracle} (K true)
   4.157 +val datatypes = Attrib.setup_config_bool @{binding smt_datatypes} (K false)
   4.158 +val timeout = Attrib.setup_config_real @{binding smt_timeout} (K 30.0)
   4.159 +val random_seed = Attrib.setup_config_int @{binding smt_random_seed} (K 1)
   4.160 +val read_only_certificates = Attrib.setup_config_bool @{binding smt_read_only_certificates} (K false)
   4.161 +val verbose = Attrib.setup_config_bool @{binding smt_verbose} (K true)
   4.162 +val trace = Attrib.setup_config_bool @{binding smt_trace} (K false)
   4.163 +val trace_used_facts = Attrib.setup_config_bool @{binding smt_trace_used_facts} (K false)
   4.164 +val monomorph_limit = Attrib.setup_config_int @{binding smt_monomorph_limit} (K 10)
   4.165 +val monomorph_instances = Attrib.setup_config_int @{binding smt_monomorph_instances} (K 500)
   4.166 +val infer_triggers = Attrib.setup_config_bool @{binding smt_infer_triggers} (K false)
   4.167 +val filter_only_facts = Attrib.setup_config_bool @{binding smt_filter_only_facts} (K false)
   4.168 +val debug_files = Attrib.setup_config_string @{binding smt_debug_files} (K "")
   4.169 +
   4.170 +
   4.171 +(* diagnostics *)
   4.172 +
   4.173 +fun cond_trace flag f x = if flag then tracing ("SMT: " ^ f x) else ()
   4.174 +
   4.175 +fun verbose_msg ctxt = cond_trace (Config.get ctxt verbose)
   4.176 +
   4.177 +fun trace_msg ctxt = cond_trace (Config.get ctxt trace)
   4.178 +
   4.179 +
   4.180 +(* tools *)
   4.181 +
   4.182 +fun with_timeout ctxt f x =
   4.183 +  TimeLimit.timeLimit (seconds (Config.get ctxt timeout)) f x
   4.184 +  handle TimeLimit.TimeOut => raise SMT_Failure.SMT SMT_Failure.Time_Out
   4.185 +
   4.186 +
   4.187 +(* certificates *)
   4.188 +
   4.189 +(* FIXME just one data slot (record) per program unit *)
   4.190 +structure Certificates = Generic_Data
   4.191 +(
   4.192 +  type T = Cache_IO.cache option
   4.193 +  val empty = NONE
   4.194 +  val extend = I
   4.195 +  fun merge (s, _) = s  (* FIXME merge options!? *)
   4.196 +)
   4.197 +
   4.198 +val get_certificates_path =
   4.199 +  Option.map (Cache_IO.cache_path_of) o Certificates.get o Context.Proof
   4.200 +
   4.201 +fun select_certificates name context = context |> Certificates.put (
   4.202 +  if name = "" then NONE
   4.203 +  else
   4.204 +    Path.explode name
   4.205 +    |> Path.append (Resources.master_directory (Context.theory_of context))
   4.206 +    |> SOME o Cache_IO.unsynchronized_init)
   4.207 +
   4.208 +val certificates_of = Certificates.get o Context.Proof
   4.209 +
   4.210 +val setup_certificates =
   4.211 +  Attrib.setup @{binding smt_certificates}
   4.212 +    (Scan.lift (@{keyword "="} |-- Args.name) >>
   4.213 +      (Thm.declaration_attribute o K o select_certificates))
   4.214 +    "SMT certificates configuration"
   4.215 +
   4.216 +
   4.217 +(* setup *)
   4.218 +
   4.219 +val setup =
   4.220 +  setup_solver #>
   4.221 +  setup_certificates
   4.222 +
   4.223 +fun print_setup ctxt =
   4.224 +  let
   4.225 +    fun string_of_bool b = if b then "true" else "false"
   4.226 +
   4.227 +    val names = available_solvers_of ctxt
   4.228 +    val ns = if null names then ["(none)"] else sort_strings names
   4.229 +    val n = the_default "(none)" (solver_name_of ctxt)
   4.230 +    val opts = solver_options_of ctxt
   4.231 +    
   4.232 +    val t = string_of_real (Config.get ctxt timeout)
   4.233 +
   4.234 +    val certs_filename =
   4.235 +      (case get_certificates_path ctxt of
   4.236 +        SOME path => Path.print path
   4.237 +      | NONE => "(disabled)")
   4.238 +  in
   4.239 +    Pretty.writeln (Pretty.big_list "SMT setup:" [
   4.240 +      Pretty.str ("Current SMT solver: " ^ n),
   4.241 +      Pretty.str ("Current SMT solver options: " ^ space_implode " " opts),
   4.242 +      Pretty.str_list "Available SMT solvers: "  "" ns,
   4.243 +      Pretty.str ("Current timeout: " ^ t ^ " seconds"),
   4.244 +      Pretty.str ("With proofs: " ^
   4.245 +        string_of_bool (not (Config.get ctxt oracle))),
   4.246 +      Pretty.str ("Certificates cache: " ^ certs_filename),
   4.247 +      Pretty.str ("Fixed certificates: " ^
   4.248 +        string_of_bool (Config.get ctxt read_only_certificates))])
   4.249 +  end
   4.250 +
   4.251 +val _ =
   4.252 +  Outer_Syntax.improper_command @{command_spec "smt_status"}
   4.253 +    "show the available SMT solvers, the currently selected SMT solver, \
   4.254 +    \and the values of SMT configuration options"
   4.255 +    (Scan.succeed (Toplevel.keep (print_setup o Toplevel.context_of)))
   4.256 +
   4.257 +end
     5.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     5.2 +++ b/src/HOL/Library/SMT/smt_datatypes.ML	Thu Aug 28 00:40:37 2014 +0200
     5.3 @@ -0,0 +1,96 @@
     5.4 +(*  Title:      HOL/Library/SMT/smt_datatypes.ML
     5.5 +    Author:     Sascha Boehme, TU Muenchen
     5.6 +
     5.7 +Collector functions for common type declarations and their representation
     5.8 +as algebraic datatypes.
     5.9 +*)
    5.10 +
    5.11 +signature SMT_DATATYPES =
    5.12 +sig
    5.13 +  val add_decls: typ ->
    5.14 +    (typ * (term * term list) list) list list * Proof.context ->
    5.15 +    (typ * (term * term list) list) list list * Proof.context
    5.16 +end
    5.17 +
    5.18 +structure SMT_Datatypes: SMT_DATATYPES =
    5.19 +struct
    5.20 +
    5.21 +val lhs_head_of = Term.head_of o fst o Logic.dest_equals o Thm.prop_of
    5.22 +
    5.23 +fun mk_selectors T Ts =
    5.24 +  Variable.variant_fixes (replicate (length Ts) "select")
    5.25 +  #>> map2 (fn U => fn n => Free (n, T --> U)) Ts
    5.26 +
    5.27 +
    5.28 +(* free constructor type declarations *)
    5.29 +
    5.30 +fun get_ctr_sugar_decl ({ctrs, ...} : Ctr_Sugar.ctr_sugar) T Ts ctxt =
    5.31 +  let
    5.32 +    fun mk_constr ctr0 =
    5.33 +      let val ctr = Ctr_Sugar.mk_ctr Ts ctr0 in
    5.34 +        mk_selectors T (binder_types (fastype_of ctr)) #>> pair ctr
    5.35 +      end
    5.36 +  in
    5.37 +    fold_map mk_constr ctrs ctxt
    5.38 +    |>> (pair T #> single)
    5.39 +  end
    5.40 +
    5.41 +
    5.42 +(* typedef declarations *)
    5.43 +
    5.44 +fun get_typedef_decl (({Abs_name, Rep_name, abs_type, rep_type, ...}, {Abs_inverse, ...})
    5.45 +    : Typedef.info) T Ts =
    5.46 +  if can (curry (op RS) @{thm UNIV_I}) Abs_inverse then
    5.47 +    let
    5.48 +      val env = snd (Term.dest_Type abs_type) ~~ Ts
    5.49 +      val instT = Term.map_atyps (perhaps (AList.lookup (op =) env))
    5.50 +
    5.51 +      val constr = Const (Abs_name, instT (rep_type --> abs_type))
    5.52 +      val select = Const (Rep_name, instT (abs_type --> rep_type))
    5.53 +    in [(T, [(constr, [select])])] end
    5.54 +  else
    5.55 +    []
    5.56 +
    5.57 +
    5.58 +(* collection of declarations *)
    5.59 +
    5.60 +fun declared declss T = exists (exists (equal T o fst)) declss
    5.61 +fun declared' dss T = exists (exists (equal T o fst) o snd) dss
    5.62 +
    5.63 +fun get_decls T n Ts ctxt =
    5.64 +  (case Ctr_Sugar.ctr_sugar_of ctxt n of
    5.65 +    SOME ctr_sugar => get_ctr_sugar_decl ctr_sugar T Ts ctxt
    5.66 +  | NONE =>
    5.67 +      (case Typedef.get_info ctxt n of
    5.68 +        [] => ([], ctxt)
    5.69 +      | info :: _ => (get_typedef_decl info T Ts, ctxt)))
    5.70 +
    5.71 +fun add_decls T (declss, ctxt) =
    5.72 +  let
    5.73 +    fun depends Ts ds = exists (member (op =) (map fst ds)) Ts
    5.74 +
    5.75 +    fun add (TFree _) = I
    5.76 +      | add (TVar _) = I
    5.77 +      | add (T as Type (@{type_name fun}, _)) =
    5.78 +          fold add (Term.body_type T :: Term.binder_types T)
    5.79 +      | add @{typ bool} = I
    5.80 +      | add (T as Type (n, Ts)) = (fn (dss, ctxt1) =>
    5.81 +          if declared declss T orelse declared' dss T then (dss, ctxt1)
    5.82 +          else if SMT_Builtin.is_builtin_typ_ext ctxt1 T then (dss, ctxt1)
    5.83 +          else
    5.84 +            (case get_decls T n Ts ctxt1 of
    5.85 +              ([], _) => (dss, ctxt1)
    5.86 +            | (ds, ctxt2) =>
    5.87 +                let
    5.88 +                  val constrTs =
    5.89 +                    maps (map (snd o Term.dest_Const o fst) o snd) ds
    5.90 +                  val Us = fold (union (op =) o Term.binder_types) constrTs []
    5.91 +
    5.92 +                  fun ins [] = [(Us, ds)]
    5.93 +                    | ins ((Uds as (Us', _)) :: Udss) =
    5.94 +                        if depends Us' ds then (Us, ds) :: Uds :: Udss
    5.95 +                        else Uds :: ins Udss
    5.96 +            in fold add Us (ins dss, ctxt2) end))
    5.97 +  in add T ([], ctxt) |>> append declss o map snd end
    5.98 +
    5.99 +end
     6.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     6.2 +++ b/src/HOL/Library/SMT/smt_failure.ML	Thu Aug 28 00:40:37 2014 +0200
     6.3 @@ -0,0 +1,61 @@
     6.4 +(*  Title:      HOL/Library/SMT/smt_failure.ML
     6.5 +    Author:     Sascha Boehme, TU Muenchen
     6.6 +
     6.7 +Failures and exception of SMT.
     6.8 +*)
     6.9 +
    6.10 +signature SMT_FAILURE =
    6.11 +sig
    6.12 +  type counterexample = {
    6.13 +    is_real_cex: bool,
    6.14 +    free_constraints: term list,
    6.15 +    const_defs: term list}
    6.16 +  datatype failure =
    6.17 +    Counterexample of counterexample |
    6.18 +    Time_Out |
    6.19 +    Out_Of_Memory |
    6.20 +    Abnormal_Termination of int |
    6.21 +    Other_Failure of string
    6.22 +  val pretty_counterexample: Proof.context -> counterexample -> Pretty.T
    6.23 +  val string_of_failure: Proof.context -> failure -> string
    6.24 +  exception SMT of failure
    6.25 +end
    6.26 +
    6.27 +structure SMT_Failure: SMT_FAILURE =
    6.28 +struct
    6.29 +
    6.30 +type counterexample = {
    6.31 +  is_real_cex: bool,
    6.32 +  free_constraints: term list,
    6.33 +  const_defs: term list}
    6.34 +
    6.35 +datatype failure =
    6.36 +  Counterexample of counterexample |
    6.37 +  Time_Out |
    6.38 +  Out_Of_Memory |
    6.39 +  Abnormal_Termination of int |
    6.40 +  Other_Failure of string
    6.41 +
    6.42 +fun pretty_counterexample ctxt {is_real_cex, free_constraints, const_defs} =
    6.43 +  let
    6.44 +    val msg =
    6.45 +      if is_real_cex then "Counterexample found (possibly spurious)"
    6.46 +      else "Potential counterexample found"
    6.47 +  in
    6.48 +    if null free_constraints andalso null const_defs then Pretty.str msg
    6.49 +    else
    6.50 +      Pretty.big_list (msg ^ ":")
    6.51 +        (map (Syntax.pretty_term ctxt) (free_constraints @ const_defs))
    6.52 +  end
    6.53 +
    6.54 +fun string_of_failure ctxt (Counterexample cex) =
    6.55 +      Pretty.string_of (pretty_counterexample ctxt cex)
    6.56 +  | string_of_failure _ Time_Out = "Timed out"
    6.57 +  | string_of_failure _ Out_Of_Memory = "Ran out of memory"
    6.58 +  | string_of_failure _ (Abnormal_Termination err) =
    6.59 +      "Solver terminated abnormally with error code " ^ string_of_int err
    6.60 +  | string_of_failure _ (Other_Failure msg) = msg
    6.61 +
    6.62 +exception SMT of failure
    6.63 +
    6.64 +end
     7.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     7.2 +++ b/src/HOL/Library/SMT/smt_normalize.ML	Thu Aug 28 00:40:37 2014 +0200
     7.3 @@ -0,0 +1,652 @@
     7.4 +(*  Title:      HOL/Library/SMT/smt_normalize.ML
     7.5 +    Author:     Sascha Boehme, TU Muenchen
     7.6 +
     7.7 +Normalization steps on theorems required by SMT solvers.
     7.8 +*)
     7.9 +
    7.10 +signature SMT_NORMALIZE =
    7.11 +sig
    7.12 +  val drop_fact_warning: Proof.context -> thm -> unit
    7.13 +  val atomize_conv: Proof.context -> conv
    7.14 +  type extra_norm = Proof.context -> thm list * thm list -> thm list * thm list
    7.15 +  val add_extra_norm: SMT_Utils.class * extra_norm -> Context.generic ->
    7.16 +    Context.generic
    7.17 +  val normalize: (int * (int option * thm)) list -> Proof.context ->
    7.18 +    (int * thm) list * Proof.context
    7.19 +  val setup: theory -> theory
    7.20 +end
    7.21 +
    7.22 +structure SMT_Normalize: SMT_NORMALIZE =
    7.23 +struct
    7.24 +
    7.25 +fun drop_fact_warning ctxt =
    7.26 +  SMT_Config.verbose_msg ctxt (prefix "Warning: dropping assumption: " o
    7.27 +    Display.string_of_thm ctxt)
    7.28 +
    7.29 +
    7.30 +(* general theorem normalizations *)
    7.31 +
    7.32 +(** instantiate elimination rules **)
    7.33 + 
    7.34 +local
    7.35 +  val (cpfalse, cfalse) =
    7.36 +    `SMT_Utils.mk_cprop (Thm.cterm_of @{theory} @{const False})
    7.37 +
    7.38 +  fun inst f ct thm =
    7.39 +    let val cv = f (Drule.strip_imp_concl (Thm.cprop_of thm))
    7.40 +    in Thm.instantiate ([], [(cv, ct)]) thm end
    7.41 +in
    7.42 +
    7.43 +fun instantiate_elim thm =
    7.44 +  (case Thm.concl_of thm of
    7.45 +    @{const Trueprop} $ Var (_, @{typ bool}) => inst Thm.dest_arg cfalse thm
    7.46 +  | Var _ => inst I cpfalse thm
    7.47 +  | _ => thm)
    7.48 +
    7.49 +end
    7.50 +
    7.51 +
    7.52 +(** normalize definitions **)
    7.53 +
    7.54 +fun norm_def thm =
    7.55 +  (case Thm.prop_of thm of
    7.56 +    @{const Trueprop} $ (Const (@{const_name HOL.eq}, _) $ _ $ Abs _) =>
    7.57 +      norm_def (thm RS @{thm fun_cong})
    7.58 +  | Const (@{const_name Pure.eq}, _) $ _ $ Abs _ =>
    7.59 +      norm_def (thm RS @{thm meta_eq_to_obj_eq})
    7.60 +  | _ => thm)
    7.61 +
    7.62 +
    7.63 +(** atomization **)
    7.64 +
    7.65 +fun atomize_conv ctxt ct =
    7.66 +  (case Thm.term_of ct of
    7.67 +    @{const Pure.imp} $ _ $ _ =>
    7.68 +      Conv.binop_conv (atomize_conv ctxt) then_conv
    7.69 +      Conv.rewr_conv @{thm atomize_imp}
    7.70 +  | Const (@{const_name Pure.eq}, _) $ _ $ _ =>
    7.71 +      Conv.binop_conv (atomize_conv ctxt) then_conv
    7.72 +      Conv.rewr_conv @{thm atomize_eq}
    7.73 +  | Const (@{const_name Pure.all}, _) $ Abs _ =>
    7.74 +      Conv.binder_conv (atomize_conv o snd) ctxt then_conv
    7.75 +      Conv.rewr_conv @{thm atomize_all}
    7.76 +  | _ => Conv.all_conv) ct
    7.77 +
    7.78 +val setup_atomize =
    7.79 +  fold SMT_Builtin.add_builtin_fun_ext'' [@{const_name Pure.imp},
    7.80 +    @{const_name Pure.eq}, @{const_name Pure.all}, @{const_name Trueprop}]
    7.81 +
    7.82 +
    7.83 +(** unfold special quantifiers **)
    7.84 +
    7.85 +local
    7.86 +  val ex1_def = mk_meta_eq @{lemma
    7.87 +    "Ex1 = (%P. EX x. P x & (ALL y. P y --> y = x))"
    7.88 +    by (rule ext) (simp only: Ex1_def)}
    7.89 +
    7.90 +  val ball_def = mk_meta_eq @{lemma "Ball = (%A P. ALL x. x : A --> P x)"
    7.91 +    by (rule ext)+ (rule Ball_def)}
    7.92 +
    7.93 +  val bex_def = mk_meta_eq @{lemma "Bex = (%A P. EX x. x : A & P x)"
    7.94 +    by (rule ext)+ (rule Bex_def)}
    7.95 +
    7.96 +  val special_quants = [(@{const_name Ex1}, ex1_def),
    7.97 +    (@{const_name Ball}, ball_def), (@{const_name Bex}, bex_def)]
    7.98 +  
    7.99 +  fun special_quant (Const (n, _)) = AList.lookup (op =) special_quants n
   7.100 +    | special_quant _ = NONE
   7.101 +
   7.102 +  fun special_quant_conv _ ct =
   7.103 +    (case special_quant (Thm.term_of ct) of
   7.104 +      SOME thm => Conv.rewr_conv thm
   7.105 +    | NONE => Conv.all_conv) ct
   7.106 +in
   7.107 +
   7.108 +fun unfold_special_quants_conv ctxt =
   7.109 +  SMT_Utils.if_exists_conv (is_some o special_quant)
   7.110 +    (Conv.top_conv special_quant_conv ctxt)
   7.111 +
   7.112 +val setup_unfolded_quants =
   7.113 +  fold (SMT_Builtin.add_builtin_fun_ext'' o fst) special_quants
   7.114 +
   7.115 +end
   7.116 +
   7.117 +
   7.118 +(** trigger inference **)
   7.119 +
   7.120 +local
   7.121 +  (*** check trigger syntax ***)
   7.122 +
   7.123 +  fun dest_trigger (Const (@{const_name pat}, _) $ _) = SOME true
   7.124 +    | dest_trigger (Const (@{const_name nopat}, _) $ _) = SOME false
   7.125 +    | dest_trigger _ = NONE
   7.126 +
   7.127 +  fun eq_list [] = false
   7.128 +    | eq_list (b :: bs) = forall (equal b) bs
   7.129 +
   7.130 +  fun proper_trigger t =
   7.131 +    t
   7.132 +    |> these o try HOLogic.dest_list
   7.133 +    |> map (map_filter dest_trigger o these o try HOLogic.dest_list)
   7.134 +    |> (fn [] => false | bss => forall eq_list bss)
   7.135 +
   7.136 +  fun proper_quant inside f t =
   7.137 +    (case t of
   7.138 +      Const (@{const_name All}, _) $ Abs (_, _, u) => proper_quant true f u
   7.139 +    | Const (@{const_name Ex}, _) $ Abs (_, _, u) => proper_quant true f u
   7.140 +    | @{const trigger} $ p $ u =>
   7.141 +        (if inside then f p else false) andalso proper_quant false f u
   7.142 +    | Abs (_, _, u) => proper_quant false f u
   7.143 +    | u1 $ u2 => proper_quant false f u1 andalso proper_quant false f u2
   7.144 +    | _ => true)
   7.145 +
   7.146 +  fun check_trigger_error ctxt t =
   7.147 +    error ("SMT triggers must only occur under quantifier and multipatterns " ^
   7.148 +      "must have the same kind: " ^ Syntax.string_of_term ctxt t)
   7.149 +
   7.150 +  fun check_trigger_conv ctxt ct =
   7.151 +    if proper_quant false proper_trigger (SMT_Utils.term_of ct) then
   7.152 +      Conv.all_conv ct
   7.153 +    else check_trigger_error ctxt (Thm.term_of ct)
   7.154 +
   7.155 +
   7.156 +  (*** infer simple triggers ***)
   7.157 +
   7.158 +  fun dest_cond_eq ct =
   7.159 +    (case Thm.term_of ct of
   7.160 +      Const (@{const_name HOL.eq}, _) $ _ $ _ => Thm.dest_binop ct
   7.161 +    | @{const HOL.implies} $ _ $ _ => dest_cond_eq (Thm.dest_arg ct)
   7.162 +    | _ => raise CTERM ("no equation", [ct]))
   7.163 +
   7.164 +  fun get_constrs thy (Type (n, _)) = these (Datatype_Data.get_constrs thy n)
   7.165 +    | get_constrs _ _ = []
   7.166 +
   7.167 +  fun is_constr thy (n, T) =
   7.168 +    let fun match (m, U) = m = n andalso Sign.typ_instance thy (T, U)
   7.169 +    in can (the o find_first match o get_constrs thy o Term.body_type) T end
   7.170 +
   7.171 +  fun is_constr_pat thy t =
   7.172 +    (case Term.strip_comb t of
   7.173 +      (Free _, []) => true
   7.174 +    | (Const c, ts) => is_constr thy c andalso forall (is_constr_pat thy) ts
   7.175 +    | _ => false)
   7.176 +
   7.177 +  fun is_simp_lhs ctxt t =
   7.178 +    (case Term.strip_comb t of
   7.179 +      (Const c, ts as _ :: _) =>
   7.180 +        not (SMT_Builtin.is_builtin_fun_ext ctxt c ts) andalso
   7.181 +        forall (is_constr_pat (Proof_Context.theory_of ctxt)) ts
   7.182 +    | _ => false)
   7.183 +
   7.184 +  fun has_all_vars vs t =
   7.185 +    subset (op aconv) (vs, map Free (Term.add_frees t []))
   7.186 +
   7.187 +  fun minimal_pats vs ct =
   7.188 +    if has_all_vars vs (Thm.term_of ct) then
   7.189 +      (case Thm.term_of ct of
   7.190 +        _ $ _ =>
   7.191 +          (case pairself (minimal_pats vs) (Thm.dest_comb ct) of
   7.192 +            ([], []) => [[ct]]
   7.193 +          | (ctss, ctss') => union (eq_set (op aconvc)) ctss ctss')
   7.194 +      | _ => [])
   7.195 +    else []
   7.196 +
   7.197 +  fun proper_mpat _ _ _ [] = false
   7.198 +    | proper_mpat thy gen u cts =
   7.199 +        let
   7.200 +          val tps = (op ~~) (`gen (map Thm.term_of cts))
   7.201 +          fun some_match u = tps |> exists (fn (t', t) =>
   7.202 +            Pattern.matches thy (t', u) andalso not (t aconv u))
   7.203 +        in not (Term.exists_subterm some_match u) end
   7.204 +
   7.205 +  val pat =
   7.206 +    SMT_Utils.mk_const_pat @{theory} @{const_name SMT.pat} SMT_Utils.destT1
   7.207 +  fun mk_pat ct = Thm.apply (SMT_Utils.instT' ct pat) ct
   7.208 +
   7.209 +  fun mk_clist T = pairself (Thm.cterm_of @{theory})
   7.210 +    (HOLogic.cons_const T, HOLogic.nil_const T)
   7.211 +  fun mk_list (ccons, cnil) f cts = fold_rev (Thm.mk_binop ccons o f) cts cnil
   7.212 +  val mk_pat_list = mk_list (mk_clist @{typ SMT.pattern})
   7.213 +  val mk_mpat_list = mk_list (mk_clist @{typ "SMT.pattern list"})  
   7.214 +  fun mk_trigger ctss = mk_mpat_list (mk_pat_list mk_pat) ctss
   7.215 +
   7.216 +  val trigger_eq =
   7.217 +    mk_meta_eq @{lemma "p = SMT.trigger t p" by (simp add: trigger_def)}
   7.218 +
   7.219 +  fun insert_trigger_conv [] ct = Conv.all_conv ct
   7.220 +    | insert_trigger_conv ctss ct =
   7.221 +        let val (ctr, cp) = Thm.dest_binop (Thm.rhs_of trigger_eq) ||> rpair ct
   7.222 +        in Thm.instantiate ([], [cp, (ctr, mk_trigger ctss)]) trigger_eq end
   7.223 +
   7.224 +  fun infer_trigger_eq_conv outer_ctxt (ctxt, cvs) ct =
   7.225 +    let
   7.226 +      val (lhs, rhs) = dest_cond_eq ct
   7.227 +
   7.228 +      val vs = map Thm.term_of cvs
   7.229 +      val thy = Proof_Context.theory_of ctxt
   7.230 +
   7.231 +      fun get_mpats ct =
   7.232 +        if is_simp_lhs ctxt (Thm.term_of ct) then minimal_pats vs ct
   7.233 +        else []
   7.234 +      val gen = Variable.export_terms ctxt outer_ctxt
   7.235 +      val filter_mpats = filter (proper_mpat thy gen (Thm.term_of rhs))
   7.236 +
   7.237 +    in insert_trigger_conv (filter_mpats (get_mpats lhs)) ct end
   7.238 +
   7.239 +  fun has_trigger (@{const SMT.trigger} $ _ $ _) = true
   7.240 +    | has_trigger _ = false
   7.241 +
   7.242 +  fun try_trigger_conv cv ct =
   7.243 +    if SMT_Utils.under_quant has_trigger (SMT_Utils.term_of ct) then
   7.244 +      Conv.all_conv ct
   7.245 +    else Conv.try_conv cv ct
   7.246 +
   7.247 +  fun infer_trigger_conv ctxt =
   7.248 +    if Config.get ctxt SMT_Config.infer_triggers then
   7.249 +      try_trigger_conv
   7.250 +        (SMT_Utils.under_quant_conv (infer_trigger_eq_conv ctxt) ctxt)
   7.251 +    else Conv.all_conv
   7.252 +in
   7.253 +
   7.254 +fun trigger_conv ctxt =
   7.255 +  SMT_Utils.prop_conv
   7.256 +    (check_trigger_conv ctxt then_conv infer_trigger_conv ctxt)
   7.257 +
   7.258 +val setup_trigger =
   7.259 +  fold SMT_Builtin.add_builtin_fun_ext''
   7.260 +    [@{const_name SMT.pat}, @{const_name SMT.nopat}, @{const_name SMT.trigger}]
   7.261 +
   7.262 +end
   7.263 +
   7.264 +
   7.265 +(** adding quantifier weights **)
   7.266 +
   7.267 +local
   7.268 +  (*** check weight syntax ***)
   7.269 +
   7.270 +  val has_no_weight =
   7.271 +    not o Term.exists_subterm (fn @{const SMT.weight} => true | _ => false)
   7.272 +
   7.273 +  fun is_weight (@{const SMT.weight} $ w $ t) =
   7.274 +        (case try HOLogic.dest_number w of
   7.275 +          SOME (_, i) => i >= 0 andalso has_no_weight t
   7.276 +        | _ => false)
   7.277 +    | is_weight t = has_no_weight t
   7.278 +
   7.279 +  fun proper_trigger (@{const SMT.trigger} $ _ $ t) = is_weight t
   7.280 +    | proper_trigger t = is_weight t 
   7.281 +
   7.282 +  fun check_weight_error ctxt t =
   7.283 +    error ("SMT weight must be a non-negative number and must only occur " ^
   7.284 +      "under the top-most quantifier and an optional trigger: " ^
   7.285 +      Syntax.string_of_term ctxt t)
   7.286 +
   7.287 +  fun check_weight_conv ctxt ct =
   7.288 +    if SMT_Utils.under_quant proper_trigger (SMT_Utils.term_of ct) then
   7.289 +      Conv.all_conv ct
   7.290 +    else check_weight_error ctxt (Thm.term_of ct)
   7.291 +
   7.292 +
   7.293 +  (*** insertion of weights ***)
   7.294 +
   7.295 +  fun under_trigger_conv cv ct =
   7.296 +    (case Thm.term_of ct of
   7.297 +      @{const SMT.trigger} $ _ $ _ => Conv.arg_conv cv
   7.298 +    | _ => cv) ct
   7.299 +
   7.300 +  val weight_eq =
   7.301 +    mk_meta_eq @{lemma "p = SMT.weight i p" by (simp add: weight_def)}
   7.302 +  fun mk_weight_eq w =
   7.303 +    let val cv = Thm.dest_arg1 (Thm.rhs_of weight_eq)
   7.304 +    in
   7.305 +      Thm.instantiate ([], [(cv, Numeral.mk_cnumber @{ctyp int} w)]) weight_eq
   7.306 +    end
   7.307 +
   7.308 +  fun add_weight_conv NONE _ = Conv.all_conv
   7.309 +    | add_weight_conv (SOME weight) ctxt =
   7.310 +        let val cv = Conv.rewr_conv (mk_weight_eq weight)
   7.311 +        in SMT_Utils.under_quant_conv (K (under_trigger_conv cv)) ctxt end
   7.312 +in
   7.313 +
   7.314 +fun weight_conv weight ctxt = 
   7.315 +  SMT_Utils.prop_conv
   7.316 +    (check_weight_conv ctxt then_conv add_weight_conv weight ctxt)
   7.317 +
   7.318 +val setup_weight = SMT_Builtin.add_builtin_fun_ext'' @{const_name SMT.weight}
   7.319 +
   7.320 +end
   7.321 +
   7.322 +
   7.323 +(** combined general normalizations **)
   7.324 +
   7.325 +fun gen_normalize1_conv ctxt weight =
   7.326 +  atomize_conv ctxt then_conv
   7.327 +  unfold_special_quants_conv ctxt then_conv
   7.328 +  Thm.beta_conversion true then_conv
   7.329 +  trigger_conv ctxt then_conv
   7.330 +  weight_conv weight ctxt
   7.331 +
   7.332 +fun gen_normalize1 ctxt weight thm =
   7.333 +  thm
   7.334 +  |> instantiate_elim
   7.335 +  |> norm_def
   7.336 +  |> Conv.fconv_rule (Thm.beta_conversion true then_conv Thm.eta_conversion)
   7.337 +  |> Drule.forall_intr_vars
   7.338 +  |> Conv.fconv_rule (gen_normalize1_conv ctxt weight)
   7.339 +
   7.340 +fun gen_norm1_safe ctxt (i, (weight, thm)) =
   7.341 +  (case try (gen_normalize1 ctxt weight) thm of
   7.342 +    SOME thm' => SOME (i, thm')
   7.343 +  | NONE => (drop_fact_warning ctxt thm; NONE))
   7.344 +
   7.345 +fun gen_normalize ctxt iwthms = map_filter (gen_norm1_safe ctxt) iwthms
   7.346 +
   7.347 +
   7.348 +
   7.349 +(* unfolding of definitions and theory-specific rewritings *)
   7.350 +
   7.351 +fun expand_head_conv cv ct =
   7.352 +  (case Thm.term_of ct of
   7.353 +    _ $ _ =>
   7.354 +      Conv.fun_conv (expand_head_conv cv) then_conv
   7.355 +      Conv.try_conv (Thm.beta_conversion false)
   7.356 +  | _ => cv) ct
   7.357 +
   7.358 +
   7.359 +(** rewrite bool case expressions as if expressions **)
   7.360 +
   7.361 +local
   7.362 +  fun is_case_bool (Const (@{const_name "bool.case_bool"}, _)) = true
   7.363 +    | is_case_bool _ = false
   7.364 +
   7.365 +  val thm = mk_meta_eq @{lemma
   7.366 +    "case_bool = (%x y P. if P then x else y)" by (rule ext)+ simp}
   7.367 +
   7.368 +  fun unfold_conv _ =
   7.369 +    SMT_Utils.if_true_conv (is_case_bool o Term.head_of)
   7.370 +      (expand_head_conv (Conv.rewr_conv thm))
   7.371 +in
   7.372 +
   7.373 +fun rewrite_case_bool_conv ctxt =
   7.374 +  SMT_Utils.if_exists_conv is_case_bool (Conv.top_conv unfold_conv ctxt)
   7.375 +
   7.376 +val setup_case_bool =
   7.377 +  SMT_Builtin.add_builtin_fun_ext'' @{const_name "bool.case_bool"}
   7.378 +
   7.379 +end
   7.380 +
   7.381 +
   7.382 +(** unfold abs, min and max **)
   7.383 +
   7.384 +local
   7.385 +  val abs_def = mk_meta_eq @{lemma
   7.386 +    "abs = (%a::'a::abs_if. if a < 0 then - a else a)"
   7.387 +    by (rule ext) (rule abs_if)}
   7.388 +
   7.389 +  val min_def = mk_meta_eq @{lemma "min = (%a b. if a <= b then a else b)"
   7.390 +    by (rule ext)+ (rule min_def)}
   7.391 +
   7.392 +  val max_def = mk_meta_eq  @{lemma "max = (%a b. if a <= b then b else a)"
   7.393 +    by (rule ext)+ (rule max_def)}
   7.394 +
   7.395 +  val defs = [(@{const_name min}, min_def), (@{const_name max}, max_def),
   7.396 +    (@{const_name abs}, abs_def)]
   7.397 +
   7.398 +  fun is_builtinT ctxt T =
   7.399 +    SMT_Builtin.is_builtin_typ_ext ctxt (Term.domain_type T)
   7.400 +
   7.401 +  fun abs_min_max ctxt (Const (n, T)) =
   7.402 +        (case AList.lookup (op =) defs n of
   7.403 +          NONE => NONE
   7.404 +        | SOME thm => if is_builtinT ctxt T then SOME thm else NONE)
   7.405 +    | abs_min_max _ _ = NONE
   7.406 +
   7.407 +  fun unfold_amm_conv ctxt ct =
   7.408 +    (case abs_min_max ctxt (Term.head_of (Thm.term_of ct)) of
   7.409 +      SOME thm => expand_head_conv (Conv.rewr_conv thm)
   7.410 +    | NONE => Conv.all_conv) ct
   7.411 +in
   7.412 +
   7.413 +fun unfold_abs_min_max_conv ctxt =
   7.414 +  SMT_Utils.if_exists_conv (is_some o abs_min_max ctxt)
   7.415 +    (Conv.top_conv unfold_amm_conv ctxt)
   7.416 +  
   7.417 +val setup_abs_min_max = fold (SMT_Builtin.add_builtin_fun_ext'' o fst) defs
   7.418 +
   7.419 +end
   7.420 +
   7.421 +
   7.422 +(** embedding of standard natural number operations into integer operations **)
   7.423 +
   7.424 +local
   7.425 +  val nat_embedding = @{lemma
   7.426 +    "ALL n. nat (int n) = n"
   7.427 +    "ALL i. i >= 0 --> int (nat i) = i"
   7.428 +    "ALL i. i < 0 --> int (nat i) = 0"
   7.429 +    by simp_all}
   7.430 +
   7.431 +  val simple_nat_ops = [
   7.432 +    @{const less (nat)}, @{const less_eq (nat)},
   7.433 +    @{const Suc}, @{const plus (nat)}, @{const minus (nat)}]
   7.434 +
   7.435 +  val mult_nat_ops =
   7.436 +    [@{const times (nat)}, @{const div (nat)}, @{const mod (nat)}]
   7.437 +
   7.438 +  val nat_ops = simple_nat_ops @ mult_nat_ops
   7.439 +
   7.440 +  val nat_consts = nat_ops @ [@{const numeral (nat)},
   7.441 +    @{const zero_class.zero (nat)}, @{const one_class.one (nat)}]
   7.442 +
   7.443 +  val nat_int_coercions = [@{const of_nat (int)}, @{const nat}]
   7.444 +
   7.445 +  val builtin_nat_ops = nat_int_coercions @ simple_nat_ops
   7.446 +
   7.447 +  val is_nat_const = member (op aconv) nat_consts
   7.448 +
   7.449 +  fun is_nat_const' @{const of_nat (int)} = true
   7.450 +    | is_nat_const' t = is_nat_const t
   7.451 +
   7.452 +  val expands = map mk_meta_eq @{lemma
   7.453 +    "0 = nat 0"
   7.454 +    "1 = nat 1"
   7.455 +    "(numeral :: num => nat) = (%i. nat (numeral i))"
   7.456 +    "op < = (%a b. int a < int b)"
   7.457 +    "op <= = (%a b. int a <= int b)"
   7.458 +    "Suc = (%a. nat (int a + 1))"
   7.459 +    "op + = (%a b. nat (int a + int b))"
   7.460 +    "op - = (%a b. nat (int a - int b))"
   7.461 +    "op * = (%a b. nat (int a * int b))"
   7.462 +    "op div = (%a b. nat (int a div int b))"
   7.463 +    "op mod = (%a b. nat (int a mod int b))"
   7.464 +    by (fastforce simp add: nat_mult_distrib nat_div_distrib nat_mod_distrib)+}
   7.465 +
   7.466 +  val ints = map mk_meta_eq @{lemma
   7.467 +    "int 0 = 0"
   7.468 +    "int 1 = 1"
   7.469 +    "int (Suc n) = int n + 1"
   7.470 +    "int (n + m) = int n + int m"
   7.471 +    "int (n - m) = int (nat (int n - int m))"
   7.472 +    "int (n * m) = int n * int m"
   7.473 +    "int (n div m) = int n div int m"
   7.474 +    "int (n mod m) = int n mod int m"
   7.475 +    by (auto simp add: int_mult zdiv_int zmod_int)}
   7.476 +
   7.477 +  val int_if = mk_meta_eq @{lemma
   7.478 +    "int (if P then n else m) = (if P then int n else int m)"
   7.479 +    by simp}
   7.480 +
   7.481 +  fun mk_number_eq ctxt i lhs =
   7.482 +    let
   7.483 +      val eq = SMT_Utils.mk_cequals lhs (Numeral.mk_cnumber @{ctyp int} i)
   7.484 +      val tac =
   7.485 +        Simplifier.simp_tac (put_simpset HOL_ss ctxt addsimps [@{thm Int.int_numeral}]) 1
   7.486 +    in Goal.norm_result ctxt (Goal.prove_internal ctxt [] eq (K tac)) end
   7.487 +
   7.488 +  fun ite_conv cv1 cv2 =
   7.489 +    Conv.combination_conv (Conv.combination_conv (Conv.arg_conv cv1) cv2) cv2
   7.490 +
   7.491 +  fun int_conv ctxt ct =
   7.492 +    (case Thm.term_of ct of
   7.493 +      @{const of_nat (int)} $ (n as (@{const numeral (nat)} $ _)) =>
   7.494 +        Conv.rewr_conv (mk_number_eq ctxt (snd (HOLogic.dest_number n)) ct)
   7.495 +    | @{const of_nat (int)} $ _ =>
   7.496 +        (Conv.rewrs_conv ints then_conv Conv.sub_conv ints_conv ctxt) else_conv
   7.497 +        (Conv.rewr_conv int_if then_conv
   7.498 +          ite_conv (nat_conv ctxt) (int_conv ctxt)) else_conv
   7.499 +        Conv.sub_conv (Conv.top_sweep_conv nat_conv) ctxt
   7.500 +    | _ => Conv.no_conv) ct
   7.501 +
   7.502 +  and ints_conv ctxt = Conv.top_sweep_conv int_conv ctxt
   7.503 +
   7.504 +  and expand_conv ctxt =
   7.505 +    SMT_Utils.if_conv (is_nat_const o Term.head_of)
   7.506 +      (expand_head_conv (Conv.rewrs_conv expands) then_conv ints_conv ctxt)
   7.507 +      (int_conv ctxt)
   7.508 +
   7.509 +  and nat_conv ctxt = SMT_Utils.if_exists_conv is_nat_const'
   7.510 +    (Conv.top_sweep_conv expand_conv ctxt)
   7.511 +
   7.512 +  val uses_nat_int = Term.exists_subterm (member (op aconv) nat_int_coercions)
   7.513 +in
   7.514 +
   7.515 +val nat_as_int_conv = nat_conv
   7.516 +
   7.517 +fun add_nat_embedding thms =
   7.518 +  if exists (uses_nat_int o Thm.prop_of) thms then (thms, nat_embedding)
   7.519 +  else (thms, [])
   7.520 +
   7.521 +val setup_nat_as_int =
   7.522 +  SMT_Builtin.add_builtin_typ_ext (@{typ nat}, K true) #>
   7.523 +  fold (SMT_Builtin.add_builtin_fun_ext' o Term.dest_Const) builtin_nat_ops
   7.524 +
   7.525 +end
   7.526 +
   7.527 +
   7.528 +(** normalize numerals **)
   7.529 +
   7.530 +local
   7.531 +  (*
   7.532 +    rewrite Numeral1 into 1
   7.533 +    rewrite - 0 into 0
   7.534 +  *)
   7.535 +
   7.536 +  fun is_irregular_number (Const (@{const_name numeral}, _) $ Const (@{const_name num.One}, _)) =
   7.537 +        true
   7.538 +    | is_irregular_number (Const (@{const_name uminus}, _) $ Const (@{const_name Groups.zero}, _)) =
   7.539 +        true
   7.540 +    | is_irregular_number _ =
   7.541 +        false;
   7.542 +
   7.543 +  fun is_strange_number ctxt t = is_irregular_number t andalso SMT_Builtin.is_builtin_num ctxt t;
   7.544 +
   7.545 +  val proper_num_ss =
   7.546 +    simpset_of (put_simpset HOL_ss @{context}
   7.547 +      addsimps @{thms Num.numeral_One minus_zero})
   7.548 +
   7.549 +  fun norm_num_conv ctxt =
   7.550 +    SMT_Utils.if_conv (is_strange_number ctxt)
   7.551 +      (Simplifier.rewrite (put_simpset proper_num_ss ctxt)) Conv.no_conv
   7.552 +in
   7.553 +
   7.554 +fun normalize_numerals_conv ctxt =
   7.555 +  SMT_Utils.if_exists_conv (is_strange_number ctxt)
   7.556 +    (Conv.top_sweep_conv norm_num_conv ctxt)
   7.557 +
   7.558 +end
   7.559 +
   7.560 +
   7.561 +(** combined unfoldings and rewritings **)
   7.562 +
   7.563 +fun unfold_conv ctxt =
   7.564 +  rewrite_case_bool_conv ctxt then_conv
   7.565 +  unfold_abs_min_max_conv ctxt then_conv
   7.566 +  nat_as_int_conv ctxt then_conv
   7.567 +  Thm.beta_conversion true
   7.568 +
   7.569 +fun unfold1 ctxt = map (apsnd (Conv.fconv_rule (unfold_conv ctxt)))
   7.570 +
   7.571 +fun burrow_ids f ithms =
   7.572 +  let
   7.573 +    val (is, thms) = split_list ithms
   7.574 +    val (thms', extra_thms) = f thms
   7.575 +  in (is ~~ thms') @ map (pair ~1) extra_thms end
   7.576 +
   7.577 +fun unfold2 ctxt ithms =
   7.578 +  ithms
   7.579 +  |> map (apsnd (Conv.fconv_rule (normalize_numerals_conv ctxt)))
   7.580 +  |> burrow_ids add_nat_embedding
   7.581 +
   7.582 +
   7.583 +
   7.584 +(* overall normalization *)
   7.585 +
   7.586 +type extra_norm = Proof.context -> thm list * thm list -> thm list * thm list
   7.587 +
   7.588 +structure Extra_Norms = Generic_Data
   7.589 +(
   7.590 +  type T = extra_norm SMT_Utils.dict
   7.591 +  val empty = []
   7.592 +  val extend = I
   7.593 +  fun merge data = SMT_Utils.dict_merge fst data
   7.594 +)
   7.595 +
   7.596 +fun add_extra_norm (cs, norm) =
   7.597 +  Extra_Norms.map (SMT_Utils.dict_update (cs, norm))
   7.598 +
   7.599 +fun apply_extra_norms ctxt ithms =
   7.600 +  let
   7.601 +    val cs = SMT_Config.solver_class_of ctxt
   7.602 +    val es = SMT_Utils.dict_lookup (Extra_Norms.get (Context.Proof ctxt)) cs
   7.603 +  in burrow_ids (fold (fn e => e ctxt) es o rpair []) ithms end
   7.604 +
   7.605 +local
   7.606 +  val ignored = member (op =) [@{const_name All}, @{const_name Ex},
   7.607 +    @{const_name Let}, @{const_name If}, @{const_name HOL.eq}]
   7.608 +
   7.609 +  val schematic_consts_of =
   7.610 +    let
   7.611 +      fun collect (@{const SMT.trigger} $ p $ t) =
   7.612 +            collect_trigger p #> collect t
   7.613 +        | collect (t $ u) = collect t #> collect u
   7.614 +        | collect (Abs (_, _, t)) = collect t
   7.615 +        | collect (t as Const (n, _)) = 
   7.616 +            if not (ignored n) then Monomorph.add_schematic_consts_of t else I
   7.617 +        | collect _ = I
   7.618 +      and collect_trigger t =
   7.619 +        let val dest = these o try HOLogic.dest_list 
   7.620 +        in fold (fold collect_pat o dest) (dest t) end
   7.621 +      and collect_pat (Const (@{const_name SMT.pat}, _) $ t) = collect t
   7.622 +        | collect_pat (Const (@{const_name SMT.nopat}, _) $ t) = collect t
   7.623 +        | collect_pat _ = I
   7.624 +    in (fn t => collect t Symtab.empty) end
   7.625 +in
   7.626 +
   7.627 +fun monomorph ctxt xthms =
   7.628 +  let val (xs, thms) = split_list xthms
   7.629 +  in
   7.630 +    map (pair 1) thms
   7.631 +    |> Monomorph.monomorph schematic_consts_of ctxt
   7.632 +    |> maps (uncurry (map o pair)) o map2 pair xs o map (map snd)
   7.633 +  end
   7.634 +
   7.635 +end
   7.636 +
   7.637 +fun normalize iwthms ctxt =
   7.638 +  iwthms
   7.639 +  |> gen_normalize ctxt
   7.640 +  |> unfold1 ctxt
   7.641 +  |> monomorph ctxt
   7.642 +  |> unfold2 ctxt
   7.643 +  |> apply_extra_norms ctxt
   7.644 +  |> rpair ctxt
   7.645 +
   7.646 +val setup = Context.theory_map (
   7.647 +  setup_atomize #>
   7.648 +  setup_unfolded_quants #>
   7.649 +  setup_trigger #>
   7.650 +  setup_weight #>
   7.651 +  setup_case_bool #>
   7.652 +  setup_abs_min_max #>
   7.653 +  setup_nat_as_int)
   7.654 +
   7.655 +end
     8.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     8.2 +++ b/src/HOL/Library/SMT/smt_real.ML	Thu Aug 28 00:40:37 2014 +0200
     8.3 @@ -0,0 +1,137 @@
     8.4 +(*  Title:      HOL/Library/SMT/smt_real.ML
     8.5 +    Author:     Sascha Boehme, TU Muenchen
     8.6 +
     8.7 +SMT setup for reals.
     8.8 +*)
     8.9 +
    8.10 +signature SMT_REAL =
    8.11 +sig
    8.12 +  val setup: theory -> theory
    8.13 +end
    8.14 +
    8.15 +structure SMT_Real: SMT_REAL =
    8.16 +struct
    8.17 +
    8.18 +
    8.19 +(* SMT-LIB logic *)
    8.20 +
    8.21 +fun smtlib_logic ts =
    8.22 +  if exists (Term.exists_type (Term.exists_subtype (equal @{typ real}))) ts
    8.23 +  then SOME "AUFLIRA"
    8.24 +  else NONE
    8.25 +
    8.26 +
    8.27 +(* SMT-LIB and Z3 built-ins *)
    8.28 +
    8.29 +local
    8.30 +  fun real_num _ i = SOME (string_of_int i ^ ".0")
    8.31 +
    8.32 +  fun is_linear [t] = SMT_Utils.is_number t
    8.33 +    | is_linear [t, u] = SMT_Utils.is_number t orelse SMT_Utils.is_number u
    8.34 +    | is_linear _ = false
    8.35 +
    8.36 +  fun mk_times ts = Term.list_comb (@{const times (real)}, ts)
    8.37 +
    8.38 +  fun times _ T ts = if is_linear ts then SOME ("*", 2, ts, mk_times) else NONE
    8.39 +    | times _ _ _  = NONE
    8.40 +in
    8.41 +
    8.42 +val setup_builtins =
    8.43 +  SMT_Builtin.add_builtin_typ SMTLIB_Interface.smtlibC
    8.44 +    (@{typ real}, K (SOME "Real"), real_num) #>
    8.45 +  fold (SMT_Builtin.add_builtin_fun' SMTLIB_Interface.smtlibC) [
    8.46 +    (@{const less (real)}, "<"),
    8.47 +    (@{const less_eq (real)}, "<="),
    8.48 +    (@{const uminus (real)}, "~"),
    8.49 +    (@{const plus (real)}, "+"),
    8.50 +    (@{const minus (real)}, "-") ] #>
    8.51 +  SMT_Builtin.add_builtin_fun SMTLIB_Interface.smtlibC
    8.52 +    (Term.dest_Const @{const times (real)}, times) #>
    8.53 +  SMT_Builtin.add_builtin_fun' Z3_Interface.smtlib_z3C
    8.54 +    (@{const times (real)}, "*") #>
    8.55 +  SMT_Builtin.add_builtin_fun' Z3_Interface.smtlib_z3C
    8.56 +    (@{const divide (real)}, "/")
    8.57 +
    8.58 +end
    8.59 +
    8.60 +
    8.61 +(* Z3 constructors *)
    8.62 +
    8.63 +local
    8.64 +  fun z3_mk_builtin_typ (Z3_Interface.Sym ("Real", _)) = SOME @{typ real}
    8.65 +    | z3_mk_builtin_typ (Z3_Interface.Sym ("real", _)) = SOME @{typ real}
    8.66 +        (*FIXME: delete*)
    8.67 +    | z3_mk_builtin_typ _ = NONE
    8.68 +
    8.69 +  fun z3_mk_builtin_num _ i T =
    8.70 +    if T = @{typ real} then SOME (Numeral.mk_cnumber @{ctyp real} i)
    8.71 +    else NONE
    8.72 +
    8.73 +  fun mk_nary _ cu [] = cu
    8.74 +    | mk_nary ct _ cts = uncurry (fold_rev (Thm.mk_binop ct)) (split_last cts)
    8.75 +
    8.76 +  val mk_uminus = Thm.apply (Thm.cterm_of @{theory} @{const uminus (real)})
    8.77 +  val add = Thm.cterm_of @{theory} @{const plus (real)}
    8.78 +  val real0 = Numeral.mk_cnumber @{ctyp real} 0
    8.79 +  val mk_sub = Thm.mk_binop (Thm.cterm_of @{theory} @{const minus (real)})
    8.80 +  val mk_mul = Thm.mk_binop (Thm.cterm_of @{theory} @{const times (real)})
    8.81 +  val mk_div = Thm.mk_binop (Thm.cterm_of @{theory} @{const divide (real)})
    8.82 +  val mk_lt = Thm.mk_binop (Thm.cterm_of @{theory} @{const less (real)})
    8.83 +  val mk_le = Thm.mk_binop (Thm.cterm_of @{theory} @{const less_eq (real)})
    8.84 +
    8.85 +  fun z3_mk_builtin_fun (Z3_Interface.Sym ("-", _)) [ct] = SOME (mk_uminus ct)
    8.86 +    | z3_mk_builtin_fun (Z3_Interface.Sym ("+", _)) cts =
    8.87 +        SOME (mk_nary add real0 cts)
    8.88 +    | z3_mk_builtin_fun (Z3_Interface.Sym ("-", _)) [ct, cu] =
    8.89 +        SOME (mk_sub ct cu)
    8.90 +    | z3_mk_builtin_fun (Z3_Interface.Sym ("*", _)) [ct, cu] =
    8.91 +        SOME (mk_mul ct cu)
    8.92 +    | z3_mk_builtin_fun (Z3_Interface.Sym ("/", _)) [ct, cu] =
    8.93 +        SOME (mk_div ct cu)
    8.94 +    | z3_mk_builtin_fun (Z3_Interface.Sym ("<", _)) [ct, cu] =
    8.95 +        SOME (mk_lt ct cu)
    8.96 +    | z3_mk_builtin_fun (Z3_Interface.Sym ("<=", _)) [ct, cu] =
    8.97 +        SOME (mk_le ct cu)
    8.98 +    | z3_mk_builtin_fun (Z3_Interface.Sym (">", _)) [ct, cu] =
    8.99 +        SOME (mk_lt cu ct)
   8.100 +    | z3_mk_builtin_fun (Z3_Interface.Sym (">=", _)) [ct, cu] =
   8.101 +        SOME (mk_le cu ct)
   8.102 +    | z3_mk_builtin_fun _ _ = NONE
   8.103 +in
   8.104 +
   8.105 +val z3_mk_builtins = {
   8.106 +  mk_builtin_typ = z3_mk_builtin_typ,
   8.107 +  mk_builtin_num = z3_mk_builtin_num,
   8.108 +  mk_builtin_fun = (fn _ => fn sym => fn cts =>
   8.109 +    (case try (#T o Thm.rep_cterm o hd) cts of
   8.110 +      SOME @{typ real} => z3_mk_builtin_fun sym cts
   8.111 +    | _ => NONE)) }
   8.112 +
   8.113 +end
   8.114 +
   8.115 +
   8.116 +(* Z3 proof reconstruction *)
   8.117 +
   8.118 +val real_rules = @{lemma
   8.119 +  "0 + (x::real) = x"
   8.120 +  "x + 0 = x"
   8.121 +  "0 * x = 0"
   8.122 +  "1 * x = x"
   8.123 +  "x + y = y + x"
   8.124 +  by auto}
   8.125 +
   8.126 +val real_linarith_proc = Simplifier.simproc_global @{theory} "fast_real_arith" [
   8.127 +  "(m::real) < n", "(m::real) <= n", "(m::real) = n"] Lin_Arith.simproc
   8.128 +
   8.129 +
   8.130 +(* setup *)
   8.131 +
   8.132 +val setup =
   8.133 +  Context.theory_map (
   8.134 +    SMTLIB_Interface.add_logic (10, smtlib_logic) #>
   8.135 +    setup_builtins #>
   8.136 +    Z3_Interface.add_mk_builtins z3_mk_builtins #>
   8.137 +    fold Z3_Proof_Reconstruction.add_z3_rule real_rules #>
   8.138 +    Z3_Proof_Tools.add_simproc real_linarith_proc)
   8.139 +
   8.140 +end
     9.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     9.2 +++ b/src/HOL/Library/SMT/smt_setup_solvers.ML	Thu Aug 28 00:40:37 2014 +0200
     9.3 @@ -0,0 +1,193 @@
     9.4 +(*  Title:      HOL/Library/SMT/smt_setup_solvers.ML
     9.5 +    Author:     Sascha Boehme, TU Muenchen
     9.6 +
     9.7 +Setup SMT solvers.
     9.8 +*)
     9.9 +
    9.10 +signature SMT_SETUP_SOLVERS =
    9.11 +sig
    9.12 +  datatype z3_non_commercial =
    9.13 +    Z3_Non_Commercial_Unknown |
    9.14 +    Z3_Non_Commercial_Accepted |
    9.15 +    Z3_Non_Commercial_Declined
    9.16 +  val z3_non_commercial: unit -> z3_non_commercial
    9.17 +  val z3_with_extensions: bool Config.T
    9.18 +  val setup: theory -> theory
    9.19 +end
    9.20 +
    9.21 +structure SMT_Setup_Solvers: SMT_SETUP_SOLVERS =
    9.22 +struct
    9.23 +
    9.24 +(* helper functions *)
    9.25 +
    9.26 +fun make_avail name () = getenv (name ^ "_SOLVER") <> ""
    9.27 +
    9.28 +fun make_command name () = [getenv (name ^ "_SOLVER")]
    9.29 +
    9.30 +fun outcome_of unsat sat unknown solver_name line =
    9.31 +  if String.isPrefix unsat line then SMT_Solver.Unsat
    9.32 +  else if String.isPrefix sat line then SMT_Solver.Sat
    9.33 +  else if String.isPrefix unknown line then SMT_Solver.Unknown
    9.34 +  else raise SMT_Failure.SMT (SMT_Failure.Other_Failure ("Solver " ^
    9.35 +    quote solver_name ^ " failed. Enable SMT tracing by setting the " ^
    9.36 +    "configuration option " ^ quote (Config.name_of SMT_Config.trace) ^ " and " ^
    9.37 +    "see the trace for details."))
    9.38 +
    9.39 +fun on_first_line test_outcome solver_name lines =
    9.40 +  let
    9.41 +    val empty_line = (fn "" => true | _ => false)
    9.42 +    val split_first = (fn [] => ("", []) | l :: ls => (l, ls))
    9.43 +    val (l, ls) = split_first (snd (take_prefix empty_line lines))
    9.44 +  in (test_outcome solver_name l, ls) end
    9.45 +
    9.46 +
    9.47 +(* CVC3 *)
    9.48 +
    9.49 +local
    9.50 +  fun cvc3_options ctxt = [
    9.51 +    "-seed", string_of_int (Config.get ctxt SMT_Config.random_seed),
    9.52 +    "-lang", "smtlib", "-output-lang", "presentation",
    9.53 +    "-timeout", string_of_int (Real.ceil (Config.get ctxt SMT_Config.timeout))]
    9.54 +in
    9.55 +
    9.56 +val cvc3: SMT_Solver.solver_config = {
    9.57 +  name = "cvc3",
    9.58 +  class = K SMTLIB_Interface.smtlibC,
    9.59 +  avail = make_avail "CVC3",
    9.60 +  command = make_command "CVC3",
    9.61 +  options = cvc3_options,
    9.62 +  default_max_relevant = 400 (* FUDGE *),
    9.63 +  supports_filter = false,
    9.64 +  outcome =
    9.65 +    on_first_line (outcome_of "Unsatisfiable." "Satisfiable." "Unknown."),
    9.66 +  cex_parser = NONE,
    9.67 +  reconstruct = NONE }
    9.68 +
    9.69 +end
    9.70 +
    9.71 +
    9.72 +(* Yices *)
    9.73 +
    9.74 +val yices: SMT_Solver.solver_config = {
    9.75 +  name = "yices",
    9.76 +  class = K SMTLIB_Interface.smtlibC,
    9.77 +  avail = make_avail "YICES",
    9.78 +  command = make_command "YICES",
    9.79 +  options = (fn ctxt => [
    9.80 +    "--rand-seed=" ^ string_of_int (Config.get ctxt SMT_Config.random_seed),
    9.81 +    "--timeout=" ^
    9.82 +      string_of_int (Real.ceil (Config.get ctxt SMT_Config.timeout)),
    9.83 +    "--smtlib"]),
    9.84 +  default_max_relevant = 350 (* FUDGE *),
    9.85 +  supports_filter = false,
    9.86 +  outcome = on_first_line (outcome_of "unsat" "sat" "unknown"),
    9.87 +  cex_parser = NONE,
    9.88 +  reconstruct = NONE }
    9.89 +
    9.90 +
    9.91 +(* Z3 *)
    9.92 +
    9.93 +datatype z3_non_commercial =
    9.94 +  Z3_Non_Commercial_Unknown |
    9.95 +  Z3_Non_Commercial_Accepted |
    9.96 +  Z3_Non_Commercial_Declined
    9.97 +
    9.98 +
    9.99 +local
   9.100 +  val accepted = member (op =) ["yes", "Yes", "YES"]
   9.101 +  val declined = member (op =) ["no", "No", "NO"]
   9.102 +in
   9.103 +
   9.104 +fun z3_non_commercial () =
   9.105 +  let
   9.106 +    val flag1 = Options.default_string @{system_option z3_non_commercial}
   9.107 +    val flag2 = getenv "Z3_NON_COMMERCIAL"
   9.108 +  in
   9.109 +    if accepted flag1 then Z3_Non_Commercial_Accepted
   9.110 +    else if declined flag1 then Z3_Non_Commercial_Declined
   9.111 +    else if accepted flag2 then Z3_Non_Commercial_Accepted
   9.112 +    else if declined flag2 then Z3_Non_Commercial_Declined
   9.113 +    else Z3_Non_Commercial_Unknown
   9.114 +  end
   9.115 +
   9.116 +fun if_z3_non_commercial f =
   9.117 +  (case z3_non_commercial () of
   9.118 +    Z3_Non_Commercial_Accepted => f ()
   9.119 +  | Z3_Non_Commercial_Declined =>
   9.120 +      error (Pretty.string_of (Pretty.para
   9.121 +        "The SMT solver Z3 may only be used for non-commercial applications."))
   9.122 +  | Z3_Non_Commercial_Unknown =>
   9.123 +      error
   9.124 +        (Pretty.string_of
   9.125 +          (Pretty.para
   9.126 +            ("The SMT solver Z3 is not activated. To activate it, set the Isabelle \
   9.127 +             \system option \"z3_non_commercial\" to \"yes\" (e.g. via \
   9.128 +             \the Isabelle/jEdit menu Plugin Options / Isabelle / General).")) ^
   9.129 +        "\n\nSee also " ^ Url.print (Url.explode "http://z3.codeplex.com/license")))
   9.130 +
   9.131 +end
   9.132 +
   9.133 +
   9.134 +val z3_with_extensions =
   9.135 +  Attrib.setup_config_bool @{binding z3_with_extensions} (K false)
   9.136 +
   9.137 +local
   9.138 +  fun z3_make_command name () = if_z3_non_commercial (make_command name)
   9.139 +
   9.140 +  fun z3_options ctxt =
   9.141 +    ["-rs:" ^ string_of_int (Config.get ctxt SMT_Config.random_seed),
   9.142 +      "MODEL=true",
   9.143 +      "SOFT_TIMEOUT=" ^
   9.144 +        string_of_int (Real.ceil (1000.0 * Config.get ctxt SMT_Config.timeout)),
   9.145 +      "-smt"]
   9.146 +    |> not (Config.get ctxt SMT_Config.oracle) ?
   9.147 +         append ["DISPLAY_PROOF=true", "PROOF_MODE=2"]
   9.148 +
   9.149 +  fun z3_on_first_or_last_line solver_name lines =
   9.150 +    let
   9.151 +      fun junk l =
   9.152 +        if String.isPrefix "WARNING: Out of allocated virtual memory" l
   9.153 +        then raise SMT_Failure.SMT SMT_Failure.Out_Of_Memory
   9.154 +        else
   9.155 +          String.isPrefix "WARNING" l orelse
   9.156 +          String.isPrefix "ERROR" l orelse
   9.157 +          forall Symbol.is_ascii_blank (Symbol.explode l)
   9.158 +      val lines = filter_out junk lines
   9.159 +      fun outcome split =
   9.160 +        the_default ("", []) (try split lines)
   9.161 +        |>> outcome_of "unsat" "sat" "unknown" solver_name
   9.162 +    in
   9.163 +      (* Starting with version 4.0, Z3 puts the outcome on the first line of the
   9.164 +         output rather than on the last line. *)
   9.165 +      outcome (fn lines => (hd lines, tl lines))
   9.166 +      handle SMT_Failure.SMT _ => outcome (swap o split_last)
   9.167 +    end
   9.168 +
   9.169 +  fun select_class ctxt =
   9.170 +    if Config.get ctxt z3_with_extensions then Z3_Interface.smtlib_z3C
   9.171 +    else SMTLIB_Interface.smtlibC
   9.172 +in
   9.173 +
   9.174 +val z3: SMT_Solver.solver_config = {
   9.175 +  name = "z3",
   9.176 +  class = select_class,
   9.177 +  avail = make_avail "Z3",
   9.178 +  command = z3_make_command "Z3",
   9.179 +  options = z3_options,
   9.180 +  default_max_relevant = 350 (* FUDGE *),
   9.181 +  supports_filter = true,
   9.182 +  outcome = z3_on_first_or_last_line,
   9.183 +  cex_parser = SOME Z3_Model.parse_counterex,
   9.184 +  reconstruct = SOME Z3_Proof_Reconstruction.reconstruct }
   9.185 +
   9.186 +end
   9.187 +
   9.188 +
   9.189 +(* overall setup *)
   9.190 +
   9.191 +val setup =
   9.192 +  SMT_Solver.add_solver cvc3 #>
   9.193 +  SMT_Solver.add_solver yices #>
   9.194 +  SMT_Solver.add_solver z3
   9.195 +
   9.196 +end
    10.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    10.2 +++ b/src/HOL/Library/SMT/smt_solver.ML	Thu Aug 28 00:40:37 2014 +0200
    10.3 @@ -0,0 +1,373 @@
    10.4 +(*  Title:      HOL/Library/SMT/smt_solver.ML
    10.5 +    Author:     Sascha Boehme, TU Muenchen
    10.6 +
    10.7 +SMT solvers registry and SMT tactic.
    10.8 +*)
    10.9 +
   10.10 +signature SMT_SOLVER =
   10.11 +sig
   10.12 +  (*configuration*)
   10.13 +  datatype outcome = Unsat | Sat | Unknown
   10.14 +  type solver_config = {
   10.15 +    name: string,
   10.16 +    class: Proof.context -> SMT_Utils.class,
   10.17 +    avail: unit -> bool,
   10.18 +    command: unit -> string list,
   10.19 +    options: Proof.context -> string list,
   10.20 +    default_max_relevant: int,
   10.21 +    supports_filter: bool,
   10.22 +    outcome: string -> string list -> outcome * string list,
   10.23 +    cex_parser: (Proof.context -> SMT_Translate.recon -> string list ->
   10.24 +      term list * term list) option,
   10.25 +    reconstruct: (Proof.context -> SMT_Translate.recon -> string list ->
   10.26 +      int list * thm) option }
   10.27 +
   10.28 +  (*registry*)
   10.29 +  val add_solver: solver_config -> theory -> theory
   10.30 +  val solver_name_of: Proof.context -> string
   10.31 +  val available_solvers_of: Proof.context -> string list
   10.32 +  val apply_solver: Proof.context -> (int * (int option * thm)) list ->
   10.33 +    int list * thm
   10.34 +  val default_max_relevant: Proof.context -> string -> int
   10.35 +
   10.36 +  (*filter*)
   10.37 +  type 'a smt_filter_data =
   10.38 +    ('a * thm) list * ((int * thm) list * Proof.context)
   10.39 +  val smt_filter_preprocess: Proof.context -> thm list -> thm ->
   10.40 +    ('a * (int option * thm)) list -> int -> 'a smt_filter_data
   10.41 +  val smt_filter_apply: Time.time -> 'a smt_filter_data ->
   10.42 +    {outcome: SMT_Failure.failure option, used_facts: ('a * thm) list}
   10.43 +
   10.44 +  (*tactic*)
   10.45 +  val smt_tac: Proof.context -> thm list -> int -> tactic
   10.46 +  val smt_tac': Proof.context -> thm list -> int -> tactic
   10.47 +end
   10.48 +
   10.49 +structure SMT_Solver: SMT_SOLVER =
   10.50 +struct
   10.51 +
   10.52 +
   10.53 +(* interface to external solvers *)
   10.54 +
   10.55 +local
   10.56 +
   10.57 +fun make_cmd command options problem_path proof_path = space_implode " " (
   10.58 +  "(exec 2>&1;" :: map File.shell_quote (command () @ options) @
   10.59 +  [File.shell_path problem_path, ")", ">", File.shell_path proof_path])
   10.60 +
   10.61 +fun trace_and ctxt msg f x =
   10.62 +  let val _ = SMT_Config.trace_msg ctxt (fn () => msg) ()
   10.63 +  in f x end
   10.64 +
   10.65 +fun run ctxt name mk_cmd input =
   10.66 +  (case SMT_Config.certificates_of ctxt of
   10.67 +    NONE =>
   10.68 +      if not (SMT_Config.is_available ctxt name) then
   10.69 +        error ("The SMT solver " ^ quote name ^ " is not installed.")
   10.70 +      else if Config.get ctxt SMT_Config.debug_files = "" then
   10.71 +        trace_and ctxt ("Invoking SMT solver " ^ quote name ^ " ...")
   10.72 +          (Cache_IO.run mk_cmd) input
   10.73 +      else
   10.74 +        let
   10.75 +          val base_path = Path.explode (Config.get ctxt SMT_Config.debug_files)
   10.76 +          val in_path = Path.ext "smt_in" base_path
   10.77 +          val out_path = Path.ext "smt_out" base_path
   10.78 +        in Cache_IO.raw_run mk_cmd input in_path out_path end
   10.79 +  | SOME certs =>
   10.80 +      (case Cache_IO.lookup certs input of
   10.81 +        (NONE, key) =>
   10.82 +          if Config.get ctxt SMT_Config.read_only_certificates then
   10.83 +            error ("Bad certificate cache: missing certificate")
   10.84 +          else
   10.85 +            Cache_IO.run_and_cache certs key mk_cmd input
   10.86 +      | (SOME output, _) =>
   10.87 +          trace_and ctxt ("Using cached certificate from " ^
   10.88 +            File.shell_path (Cache_IO.cache_path_of certs) ^ " ...")
   10.89 +            I output))
   10.90 +
   10.91 +fun run_solver ctxt name mk_cmd input =
   10.92 +  let
   10.93 +    fun pretty tag ls = Pretty.string_of (Pretty.big_list tag
   10.94 +      (map Pretty.str ls))
   10.95 +
   10.96 +    val _ = SMT_Config.trace_msg ctxt (pretty "Problem:" o split_lines) input
   10.97 +
   10.98 +    val {redirected_output=res, output=err, return_code} =
   10.99 +      SMT_Config.with_timeout ctxt (run ctxt name mk_cmd) input
  10.100 +    val _ = SMT_Config.trace_msg ctxt (pretty "Solver:") err
  10.101 +
  10.102 +    val ls = fst (take_suffix (equal "") res)
  10.103 +    val _ = SMT_Config.trace_msg ctxt (pretty "Result:") ls
  10.104 +
  10.105 +    val _ = return_code <> 0 andalso
  10.106 +      raise SMT_Failure.SMT (SMT_Failure.Abnormal_Termination return_code)
  10.107 +  in ls end
  10.108 +
  10.109 +fun trace_assms ctxt =
  10.110 +  SMT_Config.trace_msg ctxt (Pretty.string_of o
  10.111 +    Pretty.big_list "Assertions:" o map (Display.pretty_thm ctxt o snd))
  10.112 +
  10.113 +fun trace_recon_data ({context=ctxt, typs, terms, ...} : SMT_Translate.recon) =
  10.114 +  let
  10.115 +    fun pretty_eq n p = Pretty.block [Pretty.str n, Pretty.str " = ", p]
  10.116 +    fun p_typ (n, T) = pretty_eq n (Syntax.pretty_typ ctxt T)
  10.117 +    fun p_term (n, t) = pretty_eq n (Syntax.pretty_term ctxt t)
  10.118 +  in
  10.119 +    SMT_Config.trace_msg ctxt (fn () =>
  10.120 +      Pretty.string_of (Pretty.big_list "Names:" [
  10.121 +        Pretty.big_list "sorts:" (map p_typ (Symtab.dest typs)),
  10.122 +        Pretty.big_list "functions:" (map p_term (Symtab.dest terms))])) ()
  10.123 +  end
  10.124 +
  10.125 +in
  10.126 +
  10.127 +fun invoke name command ithms ctxt =
  10.128 +  let
  10.129 +    val options = SMT_Config.solver_options_of ctxt
  10.130 +    val comments = ("solver: " ^ name) ::
  10.131 +      ("timeout: " ^ string_of_real (Config.get ctxt SMT_Config.timeout)) ::
  10.132 +      ("random seed: " ^
  10.133 +        string_of_int (Config.get ctxt SMT_Config.random_seed)) ::
  10.134 +      "arguments:" :: options
  10.135 +
  10.136 +    val (str, recon as {context=ctxt', ...}) =
  10.137 +      ithms
  10.138 +      |> tap (trace_assms ctxt)
  10.139 +      |> SMT_Translate.translate ctxt comments
  10.140 +      ||> tap trace_recon_data
  10.141 +  in (run_solver ctxt' name (make_cmd command options) str, recon) end
  10.142 +
  10.143 +end
  10.144 +
  10.145 +
  10.146 +(* configuration *)
  10.147 +
  10.148 +datatype outcome = Unsat | Sat | Unknown
  10.149 +
  10.150 +type solver_config = {
  10.151 +  name: string,
  10.152 +  class: Proof.context -> SMT_Utils.class,
  10.153 +  avail: unit -> bool,
  10.154 +  command: unit -> string list,
  10.155 +  options: Proof.context -> string list,
  10.156 +  default_max_relevant: int,
  10.157 +  supports_filter: bool,
  10.158 +  outcome: string -> string list -> outcome * string list,
  10.159 +  cex_parser: (Proof.context -> SMT_Translate.recon -> string list ->
  10.160 +    term list * term list) option,
  10.161 +  reconstruct: (Proof.context -> SMT_Translate.recon -> string list ->
  10.162 +    int list * thm) option }
  10.163 +
  10.164 +
  10.165 +(* registry *)
  10.166 +
  10.167 +type solver_info = {
  10.168 +  command: unit -> string list,
  10.169 +  default_max_relevant: int,
  10.170 +  supports_filter: bool,
  10.171 +  reconstruct: Proof.context -> string list * SMT_Translate.recon ->
  10.172 +    int list * thm }
  10.173 +
  10.174 +structure Solvers = Generic_Data
  10.175 +(
  10.176 +  type T = solver_info Symtab.table
  10.177 +  val empty = Symtab.empty
  10.178 +  val extend = I
  10.179 +  fun merge data = Symtab.merge (K true) data
  10.180 +)
  10.181 +
  10.182 +local
  10.183 +  fun finish outcome cex_parser reconstruct ocl outer_ctxt
  10.184 +      (output, (recon as {context=ctxt, ...} : SMT_Translate.recon)) =
  10.185 +    (case outcome output of
  10.186 +      (Unsat, ls) =>
  10.187 +        if not (Config.get ctxt SMT_Config.oracle) andalso is_some reconstruct
  10.188 +        then the reconstruct outer_ctxt recon ls
  10.189 +        else ([], ocl ())
  10.190 +    | (result, ls) =>
  10.191 +        let
  10.192 +          val (ts, us) =
  10.193 +            (case cex_parser of SOME f => f ctxt recon ls | _ => ([], []))
  10.194 +         in
  10.195 +          raise SMT_Failure.SMT (SMT_Failure.Counterexample {
  10.196 +            is_real_cex = (result = Sat),
  10.197 +            free_constraints = ts,
  10.198 +            const_defs = us})
  10.199 +        end)
  10.200 +
  10.201 +  val cfalse = Thm.cterm_of @{theory} (@{const Trueprop} $ @{const False})
  10.202 +in
  10.203 +
  10.204 +fun add_solver cfg =
  10.205 +  let
  10.206 +    val {name, class, avail, command, options, default_max_relevant,
  10.207 +      supports_filter, outcome, cex_parser, reconstruct} = cfg
  10.208 +
  10.209 +    fun core_oracle () = cfalse
  10.210 +
  10.211 +    fun solver ocl = {
  10.212 +      command = command,
  10.213 +      default_max_relevant = default_max_relevant,
  10.214 +      supports_filter = supports_filter,
  10.215 +      reconstruct = finish (outcome name) cex_parser reconstruct ocl }
  10.216 +
  10.217 +    val info = {name=name, class=class, avail=avail, options=options}
  10.218 +  in
  10.219 +    Thm.add_oracle (Binding.name name, core_oracle) #-> (fn (_, ocl) =>
  10.220 +    Context.theory_map (Solvers.map (Symtab.update_new (name, solver ocl)))) #>
  10.221 +    Context.theory_map (SMT_Config.add_solver info)
  10.222 +  end
  10.223 +
  10.224 +end
  10.225 +
  10.226 +fun get_info ctxt name =
  10.227 +  the (Symtab.lookup (Solvers.get (Context.Proof ctxt)) name)
  10.228 +
  10.229 +val solver_name_of = SMT_Config.solver_of
  10.230 +
  10.231 +val available_solvers_of = SMT_Config.available_solvers_of
  10.232 +
  10.233 +fun name_and_info_of ctxt =
  10.234 +  let val name = solver_name_of ctxt
  10.235 +  in (name, get_info ctxt name) end
  10.236 +
  10.237 +fun gen_preprocess ctxt iwthms = SMT_Normalize.normalize iwthms ctxt
  10.238 +
  10.239 +fun gen_apply (ithms, ctxt) =
  10.240 +  let val (name, {command, reconstruct, ...}) = name_and_info_of ctxt
  10.241 +  in
  10.242 +    (ithms, ctxt)
  10.243 +    |-> invoke name command
  10.244 +    |> reconstruct ctxt
  10.245 +    |>> distinct (op =)
  10.246 +  end
  10.247 +
  10.248 +fun apply_solver ctxt = gen_apply o gen_preprocess ctxt
  10.249 +
  10.250 +val default_max_relevant = #default_max_relevant oo get_info
  10.251 +
  10.252 +val supports_filter = #supports_filter o snd o name_and_info_of 
  10.253 +
  10.254 +
  10.255 +(* check well-sortedness *)
  10.256 +
  10.257 +val has_topsort = Term.exists_type (Term.exists_subtype (fn
  10.258 +    TFree (_, []) => true
  10.259 +  | TVar (_, []) => true
  10.260 +  | _ => false))
  10.261 +
  10.262 +(* without this test, we would run into problems when atomizing the rules: *)
  10.263 +fun check_topsort ctxt thm =
  10.264 +  if has_topsort (Thm.prop_of thm) then
  10.265 +    (SMT_Normalize.drop_fact_warning ctxt thm; TrueI)
  10.266 +  else
  10.267 +    thm
  10.268 +
  10.269 +fun check_topsorts ctxt iwthms = map (apsnd (apsnd (check_topsort ctxt))) iwthms
  10.270 +
  10.271 +
  10.272 +(* filter *)
  10.273 +
  10.274 +val cnot = Thm.cterm_of @{theory} @{const Not}
  10.275 +
  10.276 +fun mk_result outcome xrules = { outcome = outcome, used_facts = xrules }
  10.277 +
  10.278 +type 'a smt_filter_data = ('a * thm) list * ((int * thm) list * Proof.context)
  10.279 +
  10.280 +fun smt_filter_preprocess ctxt facts goal xwthms i =
  10.281 +  let
  10.282 +    val ctxt =
  10.283 +      ctxt
  10.284 +      |> Config.put SMT_Config.oracle false
  10.285 +      |> Config.put SMT_Config.filter_only_facts true
  10.286 +
  10.287 +    val ({context=ctxt', prems, concl, ...}, _) = Subgoal.focus ctxt i goal
  10.288 +    fun negate ct = Thm.dest_comb ct ||> Thm.apply cnot |-> Thm.apply
  10.289 +    val cprop =
  10.290 +      (case try negate (Thm.rhs_of (SMT_Normalize.atomize_conv ctxt' concl)) of
  10.291 +        SOME ct => ct
  10.292 +      | NONE => raise SMT_Failure.SMT (SMT_Failure.Other_Failure (
  10.293 +          "goal is not a HOL term")))
  10.294 +  in
  10.295 +    map snd xwthms
  10.296 +    |> map_index I
  10.297 +    |> append (map (pair ~1 o pair NONE) (Thm.assume cprop :: prems @ facts))
  10.298 +    |> check_topsorts ctxt'
  10.299 +    |> gen_preprocess ctxt'
  10.300 +    |> pair (map (apsnd snd) xwthms)
  10.301 +  end
  10.302 +
  10.303 +fun smt_filter_apply time_limit (xthms, (ithms, ctxt)) =
  10.304 +  let
  10.305 +    val ctxt' =
  10.306 +      ctxt
  10.307 +      |> Config.put SMT_Config.timeout (Time.toReal time_limit)
  10.308 +
  10.309 +    fun filter_thms false = K xthms
  10.310 +      | filter_thms true = map_filter (try (nth xthms)) o fst
  10.311 +  in
  10.312 +    (ithms, ctxt')
  10.313 +    |> gen_apply
  10.314 +    |> filter_thms (supports_filter ctxt')
  10.315 +    |> mk_result NONE
  10.316 +  end
  10.317 +  handle SMT_Failure.SMT fail => mk_result (SOME fail) []
  10.318 +
  10.319 +
  10.320 +(* SMT tactic *)
  10.321 +
  10.322 +local
  10.323 +  fun trace_assumptions ctxt iwthms idxs =
  10.324 +    let
  10.325 +      val wthms =
  10.326 +        idxs
  10.327 +        |> filter (fn i => i >= 0)
  10.328 +        |> map_filter (AList.lookup (op =) iwthms)
  10.329 +    in
  10.330 +      if Config.get ctxt SMT_Config.trace_used_facts andalso length wthms > 0
  10.331 +      then
  10.332 +        tracing (Pretty.string_of (Pretty.big_list "SMT used facts:"
  10.333 +          (map (Display.pretty_thm ctxt o snd) wthms)))
  10.334 +      else ()
  10.335 +    end
  10.336 +
  10.337 +  fun solve ctxt iwthms =
  10.338 +    iwthms
  10.339 +    |> check_topsorts ctxt
  10.340 +    |> apply_solver ctxt
  10.341 +    |>> trace_assumptions ctxt iwthms
  10.342 +    |> snd
  10.343 +
  10.344 +  fun str_of ctxt fail =
  10.345 +    SMT_Failure.string_of_failure ctxt fail
  10.346 +    |> prefix ("Solver " ^ SMT_Config.solver_of ctxt ^ ": ")
  10.347 +
  10.348 +  fun safe_solve ctxt iwthms = SOME (solve ctxt iwthms)
  10.349 +    handle
  10.350 +      SMT_Failure.SMT (fail as SMT_Failure.Counterexample _) =>
  10.351 +        (SMT_Config.verbose_msg ctxt (str_of ctxt) fail; NONE)
  10.352 +    | SMT_Failure.SMT (fail as SMT_Failure.Time_Out) =>
  10.353 +        error ("SMT: Solver " ^ quote (SMT_Config.solver_of ctxt) ^ ": " ^
  10.354 +          SMT_Failure.string_of_failure ctxt fail ^ " (setting the " ^
  10.355 +          "configuration option " ^ quote (Config.name_of SMT_Config.timeout) ^ " might help)")
  10.356 +    | SMT_Failure.SMT fail => error (str_of ctxt fail)
  10.357 +
  10.358 +  fun tag_rules thms = map_index (apsnd (pair NONE)) thms
  10.359 +  fun tag_prems thms = map (pair ~1 o pair NONE) thms
  10.360 +
  10.361 +  fun resolve (SOME thm) = rtac thm 1
  10.362 +    | resolve NONE = no_tac
  10.363 +
  10.364 +  fun tac prove ctxt rules =
  10.365 +    CONVERSION (SMT_Normalize.atomize_conv ctxt)
  10.366 +    THEN' rtac @{thm ccontr}
  10.367 +    THEN' SUBPROOF (fn {context, prems, ...} =>
  10.368 +      resolve (prove context (tag_rules rules @ tag_prems prems))) ctxt
  10.369 +in
  10.370 +
  10.371 +val smt_tac = tac safe_solve
  10.372 +val smt_tac' = tac (SOME oo solve)
  10.373 +
  10.374 +end
  10.375 +
  10.376 +end
    11.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    11.2 +++ b/src/HOL/Library/SMT/smt_translate.ML	Thu Aug 28 00:40:37 2014 +0200
    11.3 @@ -0,0 +1,589 @@
    11.4 +(*  Title:      HOL/Library/SMT/smt_translate.ML
    11.5 +    Author:     Sascha Boehme, TU Muenchen
    11.6 +
    11.7 +Translate theorems into an SMT intermediate format and serialize them.
    11.8 +*)
    11.9 +
   11.10 +signature SMT_TRANSLATE =
   11.11 +sig
   11.12 +  (*intermediate term structure*)
   11.13 +  datatype squant = SForall | SExists
   11.14 +  datatype 'a spattern = SPat of 'a list | SNoPat of 'a list
   11.15 +  datatype sterm =
   11.16 +    SVar of int |
   11.17 +    SApp of string * sterm list |
   11.18 +    SLet of string * sterm * sterm |
   11.19 +    SQua of squant * string list * sterm spattern list * int option * sterm
   11.20 +
   11.21 +  (*translation configuration*)
   11.22 +  type prefixes = {sort_prefix: string, func_prefix: string}
   11.23 +  type sign = {
   11.24 +    header: string list,
   11.25 +    sorts: string list,
   11.26 +    dtyps: (string * (string * (string * string) list) list) list list,
   11.27 +    funcs: (string * (string list * string)) list }
   11.28 +  type config = {
   11.29 +    prefixes: prefixes,
   11.30 +    header: term list -> string list,
   11.31 +    is_fol: bool,
   11.32 +    has_datatypes: bool,
   11.33 +    serialize: string list -> sign -> sterm list -> string }
   11.34 +  type recon = {
   11.35 +    context: Proof.context,
   11.36 +    typs: typ Symtab.table,
   11.37 +    terms: term Symtab.table,
   11.38 +    rewrite_rules: thm list,
   11.39 +    assms: (int * thm) list }
   11.40 +
   11.41 +  (*translation*)
   11.42 +  val add_config: SMT_Utils.class * (Proof.context -> config) ->
   11.43 +    Context.generic -> Context.generic 
   11.44 +  val translate: Proof.context -> string list -> (int * thm) list ->
   11.45 +    string * recon
   11.46 +end
   11.47 +
   11.48 +structure SMT_Translate: SMT_TRANSLATE =
   11.49 +struct
   11.50 +
   11.51 +
   11.52 +(* intermediate term structure *)
   11.53 +
   11.54 +datatype squant = SForall | SExists
   11.55 +
   11.56 +datatype 'a spattern = SPat of 'a list | SNoPat of 'a list
   11.57 +
   11.58 +datatype sterm =
   11.59 +  SVar of int |
   11.60 +  SApp of string * sterm list |
   11.61 +  SLet of string * sterm * sterm |
   11.62 +  SQua of squant * string list * sterm spattern list * int option * sterm
   11.63 +
   11.64 +
   11.65 +
   11.66 +(* translation configuration *)
   11.67 +
   11.68 +type prefixes = {sort_prefix: string, func_prefix: string}
   11.69 +
   11.70 +type sign = {
   11.71 +  header: string list,
   11.72 +  sorts: string list,
   11.73 +  dtyps: (string * (string * (string * string) list) list) list list,
   11.74 +  funcs: (string * (string list * string)) list }
   11.75 +
   11.76 +type config = {
   11.77 +  prefixes: prefixes,
   11.78 +  header: term list -> string list,
   11.79 +  is_fol: bool,
   11.80 +  has_datatypes: bool,
   11.81 +  serialize: string list -> sign -> sterm list -> string }
   11.82 +
   11.83 +type recon = {
   11.84 +  context: Proof.context,
   11.85 +  typs: typ Symtab.table,
   11.86 +  terms: term Symtab.table,
   11.87 +  rewrite_rules: thm list,
   11.88 +  assms: (int * thm) list }
   11.89 +
   11.90 +
   11.91 +
   11.92 +(* translation context *)
   11.93 +
   11.94 +fun make_tr_context {sort_prefix, func_prefix} =
   11.95 +  (sort_prefix, 1, Typtab.empty, func_prefix, 1, Termtab.empty)
   11.96 +
   11.97 +fun string_of_index pre i = pre ^ string_of_int i
   11.98 +
   11.99 +fun add_typ T proper (cx as (sp, Tidx, typs, fp, idx, terms)) =
  11.100 +  (case Typtab.lookup typs T of
  11.101 +    SOME (n, _) => (n, cx)
  11.102 +  | NONE =>
  11.103 +      let
  11.104 +        val n = string_of_index sp Tidx
  11.105 +        val typs' = Typtab.update (T, (n, proper)) typs
  11.106 +      in (n, (sp, Tidx+1, typs', fp, idx, terms)) end)
  11.107 +
  11.108 +fun add_fun t sort (cx as (sp, Tidx, typs, fp, idx, terms)) =
  11.109 +  (case Termtab.lookup terms t of
  11.110 +    SOME (n, _) => (n, cx)
  11.111 +  | NONE => 
  11.112 +      let
  11.113 +        val n = string_of_index fp idx
  11.114 +        val terms' = Termtab.update (t, (n, sort)) terms
  11.115 +      in (n, (sp, Tidx, typs, fp, idx+1, terms')) end)
  11.116 +
  11.117 +fun sign_of header dtyps (_, _, typs, _, _, terms) = {
  11.118 +  header = header,
  11.119 +  sorts = Typtab.fold (fn (_, (n, true)) => cons n | _ => I) typs [],
  11.120 +  dtyps = dtyps,
  11.121 +  funcs = Termtab.fold (fn (_, (n, SOME ss)) => cons (n,ss) | _ => I) terms []}
  11.122 +
  11.123 +fun recon_of ctxt rules thms ithms (_, _, typs, _, _, terms) =
  11.124 +  let
  11.125 +    fun add_typ (T, (n, _)) = Symtab.update (n, T)
  11.126 +    val typs' = Typtab.fold add_typ typs Symtab.empty
  11.127 +
  11.128 +    fun add_fun (t, (n, _)) = Symtab.update (n, t)
  11.129 +    val terms' = Termtab.fold add_fun terms Symtab.empty
  11.130 +
  11.131 +    val assms = map (pair ~1) thms @ ithms
  11.132 +  in
  11.133 +    {context=ctxt, typs=typs', terms=terms', rewrite_rules=rules, assms=assms}
  11.134 +  end
  11.135 +
  11.136 +
  11.137 +
  11.138 +(* preprocessing *)
  11.139 +
  11.140 +(** datatype declarations **)
  11.141 +
  11.142 +fun collect_datatypes_and_records (tr_context, ctxt) ts =
  11.143 +  let
  11.144 +    val (declss, ctxt') =
  11.145 +      fold (Term.fold_types SMT_Datatypes.add_decls) ts ([], ctxt)
  11.146 +
  11.147 +    fun is_decl_typ T = exists (exists (equal T o fst)) declss
  11.148 +
  11.149 +    fun add_typ' T proper =
  11.150 +      (case SMT_Builtin.dest_builtin_typ ctxt' T of
  11.151 +        SOME n => pair n
  11.152 +      | NONE => add_typ T proper)
  11.153 +
  11.154 +    fun tr_select sel =
  11.155 +      let val T = Term.range_type (Term.fastype_of sel)
  11.156 +      in add_fun sel NONE ##>> add_typ' T (not (is_decl_typ T)) end
  11.157 +    fun tr_constr (constr, selects) =
  11.158 +      add_fun constr NONE ##>> fold_map tr_select selects
  11.159 +    fun tr_typ (T, cases) = add_typ' T false ##>> fold_map tr_constr cases
  11.160 +    val (declss', tr_context') = fold_map (fold_map tr_typ) declss tr_context
  11.161 +
  11.162 +    fun add (constr, selects) =
  11.163 +      Termtab.update (constr, length selects) #>
  11.164 +      fold (Termtab.update o rpair 1) selects
  11.165 +    val funcs = fold (fold (fold add o snd)) declss Termtab.empty
  11.166 +  in ((funcs, declss', tr_context', ctxt'), ts) end
  11.167 +    (* FIXME: also return necessary datatype and record theorems *)
  11.168 +
  11.169 +
  11.170 +(** eta-expand quantifiers, let expressions and built-ins *)
  11.171 +
  11.172 +local
  11.173 +  fun eta f T t = Abs (Name.uu, T, f (Term.incr_boundvars 1 t $ Bound 0))
  11.174 +
  11.175 +  fun exp f T = eta f (Term.domain_type (Term.domain_type T))
  11.176 +
  11.177 +  fun exp2 T q =
  11.178 +    let val U = Term.domain_type T
  11.179 +    in Abs (Name.uu, U, q $ eta I (Term.domain_type U) (Bound 0)) end
  11.180 +
  11.181 +  fun exp2' T l =
  11.182 +    let val (U1, U2) = Term.dest_funT T ||> Term.domain_type
  11.183 +    in Abs (Name.uu, U1, eta I U2 (l $ Bound 0)) end
  11.184 +
  11.185 +  fun expf k i T t =
  11.186 +    let val Ts = drop i (fst (SMT_Utils.dest_funT k T))
  11.187 +    in
  11.188 +      Term.incr_boundvars (length Ts) t
  11.189 +      |> fold_rev (fn i => fn u => u $ Bound i) (0 upto length Ts - 1)
  11.190 +      |> fold_rev (fn T => fn u => Abs (Name.uu, T, u)) Ts
  11.191 +    end
  11.192 +in
  11.193 +
  11.194 +fun eta_expand ctxt is_fol funcs =
  11.195 +  let
  11.196 +    fun exp_func t T ts =
  11.197 +      (case Termtab.lookup funcs t of
  11.198 +        SOME k =>
  11.199 +          Term.list_comb (t, ts)
  11.200 +          |> k <> length ts ? expf k (length ts) T
  11.201 +      | NONE => Term.list_comb (t, ts))
  11.202 +
  11.203 +    fun expand ((q as Const (@{const_name All}, _)) $ Abs a) = q $ abs_expand a
  11.204 +      | expand ((q as Const (@{const_name All}, T)) $ t) = q $ exp expand T t
  11.205 +      | expand (q as Const (@{const_name All}, T)) = exp2 T q
  11.206 +      | expand ((q as Const (@{const_name Ex}, _)) $ Abs a) = q $ abs_expand a
  11.207 +      | expand ((q as Const (@{const_name Ex}, T)) $ t) = q $ exp expand T t
  11.208 +      | expand (q as Const (@{const_name Ex}, T)) = exp2 T q
  11.209 +      | expand ((l as Const (@{const_name Let}, _)) $ t $ Abs a) =
  11.210 +          if is_fol then expand (Term.betapply (Abs a, t))
  11.211 +          else l $ expand t $ abs_expand a
  11.212 +      | expand ((l as Const (@{const_name Let}, T)) $ t $ u) =
  11.213 +          if is_fol then expand (u $ t)
  11.214 +          else l $ expand t $ exp expand (Term.range_type T) u
  11.215 +      | expand ((l as Const (@{const_name Let}, T)) $ t) =
  11.216 +          if is_fol then
  11.217 +            let val U = Term.domain_type (Term.range_type T)
  11.218 +            in Abs (Name.uu, U, Bound 0 $ Term.incr_boundvars 1 t) end
  11.219 +          else exp2 T (l $ expand t)
  11.220 +      | expand (l as Const (@{const_name Let}, T)) =
  11.221 +          if is_fol then 
  11.222 +            let val U = Term.domain_type (Term.range_type T)
  11.223 +            in
  11.224 +              Abs (Name.uu, Term.domain_type T, Abs (Name.uu, U,
  11.225 +                Bound 0 $ Bound 1))
  11.226 +            end
  11.227 +          else exp2' T l
  11.228 +      | expand t =
  11.229 +          (case Term.strip_comb t of
  11.230 +            (u as Const (c as (_, T)), ts) =>
  11.231 +              (case SMT_Builtin.dest_builtin ctxt c ts of
  11.232 +                SOME (_, k, us, mk) =>
  11.233 +                  if k = length us then mk (map expand us)
  11.234 +                  else if k < length us then
  11.235 +                    chop k (map expand us) |>> mk |> Term.list_comb
  11.236 +                  else expf k (length ts) T (mk (map expand us))
  11.237 +              | NONE => exp_func u T (map expand ts))
  11.238 +          | (u as Free (_, T), ts) => exp_func u T (map expand ts)
  11.239 +          | (Abs a, ts) => Term.list_comb (abs_expand a, map expand ts)
  11.240 +          | (u, ts) => Term.list_comb (u, map expand ts))
  11.241 +
  11.242 +    and abs_expand (n, T, t) = Abs (n, T, expand t)
  11.243 +  
  11.244 +  in map expand end
  11.245 +
  11.246 +end
  11.247 +
  11.248 +
  11.249 +(** introduce explicit applications **)
  11.250 +
  11.251 +local
  11.252 +  (*
  11.253 +    Make application explicit for functions with varying number of arguments.
  11.254 +  *)
  11.255 +
  11.256 +  fun add t i = apfst (Termtab.map_default (t, i) (Integer.min i))
  11.257 +  fun add_type T = apsnd (Typtab.update (T, ()))
  11.258 +
  11.259 +  fun min_arities t =
  11.260 +    (case Term.strip_comb t of
  11.261 +      (u as Const _, ts) => add u (length ts) #> fold min_arities ts
  11.262 +    | (u as Free _, ts) => add u (length ts) #> fold min_arities ts
  11.263 +    | (Abs (_, T, u), ts) => add_type T #> min_arities u #> fold min_arities ts
  11.264 +    | (_, ts) => fold min_arities ts)
  11.265 +
  11.266 +  fun minimize types t i =
  11.267 +    let
  11.268 +      fun find_min j [] _ = j
  11.269 +        | find_min j (U :: Us) T =
  11.270 +            if Typtab.defined types T then j
  11.271 +            else find_min (j + 1) Us (U --> T)
  11.272 +
  11.273 +      val (Ts, T) = Term.strip_type (Term.type_of t)
  11.274 +    in find_min 0 (take i (rev Ts)) T end
  11.275 +
  11.276 +  fun app u (t, T) =
  11.277 +    (Const (@{const_name SMT.fun_app}, T --> T) $ t $ u, Term.range_type T)
  11.278 +
  11.279 +  fun apply i t T ts =
  11.280 +    let
  11.281 +      val (ts1, ts2) = chop i ts
  11.282 +      val (_, U) = SMT_Utils.dest_funT i T
  11.283 +    in fst (fold app ts2 (Term.list_comb (t, ts1), U)) end
  11.284 +in
  11.285 +
  11.286 +fun intro_explicit_application ctxt funcs ts =
  11.287 +  let
  11.288 +    val (arities, types) = fold min_arities ts (Termtab.empty, Typtab.empty)
  11.289 +    val arities' = Termtab.map (minimize types) arities
  11.290 +
  11.291 +    fun app_func t T ts =
  11.292 +      if is_some (Termtab.lookup funcs t) then Term.list_comb (t, ts)
  11.293 +      else apply (the (Termtab.lookup arities' t)) t T ts
  11.294 +
  11.295 +    fun in_list T f t = HOLogic.mk_list T (map f (HOLogic.dest_list t))
  11.296 +
  11.297 +    fun traverse Ts t =
  11.298 +      (case Term.strip_comb t of
  11.299 +        (q as Const (@{const_name All}, _), [Abs (x, T, u)]) =>
  11.300 +          q $ Abs (x, T, in_trigger (T :: Ts) u)
  11.301 +      | (q as Const (@{const_name Ex}, _), [Abs (x, T, u)]) =>
  11.302 +          q $ Abs (x, T, in_trigger (T :: Ts) u)
  11.303 +      | (q as Const (@{const_name Let}, _), [u1, u2 as Abs _]) =>
  11.304 +          q $ traverse Ts u1 $ traverse Ts u2
  11.305 +      | (u as Const (c as (_, T)), ts) =>
  11.306 +          (case SMT_Builtin.dest_builtin ctxt c ts of
  11.307 +            SOME (_, k, us, mk) =>
  11.308 +              let
  11.309 +                val (ts1, ts2) = chop k (map (traverse Ts) us)
  11.310 +                val U = Term.strip_type T |>> snd o chop k |> (op --->)
  11.311 +              in apply 0 (mk ts1) U ts2 end
  11.312 +          | NONE => app_func u T (map (traverse Ts) ts))
  11.313 +      | (u as Free (_, T), ts) => app_func u T (map (traverse Ts) ts)
  11.314 +      | (u as Bound i, ts) => apply 0 u (nth Ts i) (map (traverse Ts) ts)
  11.315 +      | (Abs (n, T, u), ts) => traverses Ts (Abs (n, T, traverse (T::Ts) u)) ts
  11.316 +      | (u, ts) => traverses Ts u ts)
  11.317 +    and in_trigger Ts ((c as @{const SMT.trigger}) $ p $ t) =
  11.318 +          c $ in_pats Ts p $ in_weight Ts t
  11.319 +      | in_trigger Ts t = in_weight Ts t
  11.320 +    and in_pats Ts ps =
  11.321 +      in_list @{typ "SMT.pattern list"}
  11.322 +        (in_list @{typ SMT.pattern} (in_pat Ts)) ps
  11.323 +    and in_pat Ts ((p as Const (@{const_name SMT.pat}, _)) $ t) =
  11.324 +          p $ traverse Ts t
  11.325 +      | in_pat Ts ((p as Const (@{const_name SMT.nopat}, _)) $ t) =
  11.326 +          p $ traverse Ts t
  11.327 +      | in_pat _ t = raise TERM ("bad pattern", [t])
  11.328 +    and in_weight Ts ((c as @{const SMT.weight}) $ w $ t) =
  11.329 +          c $ w $ traverse Ts t
  11.330 +      | in_weight Ts t = traverse Ts t 
  11.331 +    and traverses Ts t ts = Term.list_comb (t, map (traverse Ts) ts)
  11.332 +  in map (traverse []) ts end
  11.333 +
  11.334 +val fun_app_eq = mk_meta_eq @{thm SMT.fun_app_def}
  11.335 +
  11.336 +end
  11.337 +
  11.338 +
  11.339 +(** map HOL formulas to FOL formulas (i.e., separate formulas froms terms) **)
  11.340 +
  11.341 +local
  11.342 +  val term_bool = @{lemma "SMT.term_true ~= SMT.term_false"
  11.343 +    by (simp add: SMT.term_true_def SMT.term_false_def)}
  11.344 +
  11.345 +  val is_quant = member (op =) [@{const_name All}, @{const_name Ex}]
  11.346 +
  11.347 +  val fol_rules = [
  11.348 +    Let_def,
  11.349 +    mk_meta_eq @{thm SMT.term_true_def},
  11.350 +    mk_meta_eq @{thm SMT.term_false_def},
  11.351 +    @{lemma "P = True == P" by (rule eq_reflection) simp},
  11.352 +    @{lemma "if P then True else False == P" by (rule eq_reflection) simp}]
  11.353 +
  11.354 +  fun as_term t = @{const HOL.eq (bool)} $ t $ @{const SMT.term_true}
  11.355 +
  11.356 +  exception BAD_PATTERN of unit
  11.357 +
  11.358 +  fun wrap_in_if pat t =
  11.359 +    if pat then
  11.360 +      raise BAD_PATTERN ()
  11.361 +    else
  11.362 +      @{const If (bool)} $ t $ @{const SMT.term_true} $ @{const SMT.term_false}
  11.363 +
  11.364 +  fun is_builtin_conn_or_pred ctxt c ts =
  11.365 +    is_some (SMT_Builtin.dest_builtin_conn ctxt c ts) orelse
  11.366 +    is_some (SMT_Builtin.dest_builtin_pred ctxt c ts)
  11.367 +
  11.368 +  fun builtin b ctxt c ts =
  11.369 +    (case (Const c, ts) of
  11.370 +      (@{const HOL.eq (bool)}, [t, u]) =>
  11.371 +        if t = @{const SMT.term_true} orelse u = @{const SMT.term_true} then
  11.372 +          SMT_Builtin.dest_builtin_eq ctxt t u
  11.373 +        else b ctxt c ts
  11.374 +    | _ => b ctxt c ts)
  11.375 +in
  11.376 +
  11.377 +fun folify ctxt =
  11.378 +  let
  11.379 +    fun in_list T f t = HOLogic.mk_list T (map_filter f (HOLogic.dest_list t))
  11.380 +
  11.381 +    fun in_term pat t =
  11.382 +      (case Term.strip_comb t of
  11.383 +        (@{const True}, []) => @{const SMT.term_true}
  11.384 +      | (@{const False}, []) => @{const SMT.term_false}
  11.385 +      | (u as Const (@{const_name If}, _), [t1, t2, t3]) =>
  11.386 +          if pat then raise BAD_PATTERN ()
  11.387 +          else u $ in_form t1 $ in_term pat t2 $ in_term pat t3
  11.388 +      | (Const (c as (n, _)), ts) =>
  11.389 +          if is_builtin_conn_or_pred ctxt c ts then wrap_in_if pat (in_form t)
  11.390 +          else if is_quant n then wrap_in_if pat (in_form t)
  11.391 +          else Term.list_comb (Const c, map (in_term pat) ts)
  11.392 +      | (Free c, ts) => Term.list_comb (Free c, map (in_term pat) ts)
  11.393 +      | _ => t)
  11.394 +
  11.395 +    and in_weight ((c as @{const SMT.weight}) $ w $ t) = c $ w $ in_form t
  11.396 +      | in_weight t = in_form t 
  11.397 +
  11.398 +    and in_pat ((p as Const (@{const_name SMT.pat}, _)) $ t) =
  11.399 +          p $ in_term true t
  11.400 +      | in_pat ((p as Const (@{const_name SMT.nopat}, _)) $ t) =
  11.401 +          p $ in_term true t
  11.402 +      | in_pat t = raise TERM ("bad pattern", [t])
  11.403 +
  11.404 +    and in_pats ps =
  11.405 +      in_list @{typ "SMT.pattern list"}
  11.406 +        (SOME o in_list @{typ SMT.pattern} (try in_pat)) ps
  11.407 +
  11.408 +    and in_trigger ((c as @{const SMT.trigger}) $ p $ t) =
  11.409 +          c $ in_pats p $ in_weight t
  11.410 +      | in_trigger t = in_weight t
  11.411 +
  11.412 +    and in_form t =
  11.413 +      (case Term.strip_comb t of
  11.414 +        (q as Const (qn, _), [Abs (n, T, u)]) =>
  11.415 +          if is_quant qn then q $ Abs (n, T, in_trigger u)
  11.416 +          else as_term (in_term false t)
  11.417 +      | (Const c, ts) =>
  11.418 +          (case SMT_Builtin.dest_builtin_conn ctxt c ts of
  11.419 +            SOME (_, _, us, mk) => mk (map in_form us)
  11.420 +          | NONE =>
  11.421 +              (case SMT_Builtin.dest_builtin_pred ctxt c ts of
  11.422 +                SOME (_, _, us, mk) => mk (map (in_term false) us)
  11.423 +              | NONE => as_term (in_term false t)))
  11.424 +      | _ => as_term (in_term false t))
  11.425 +  in
  11.426 +    map in_form #>
  11.427 +    cons (SMT_Utils.prop_of term_bool) #>
  11.428 +    pair (fol_rules, [term_bool], builtin)
  11.429 +  end
  11.430 +
  11.431 +end
  11.432 +
  11.433 +
  11.434 +(* translation into intermediate format *)
  11.435 +
  11.436 +(** utility functions **)
  11.437 +
  11.438 +val quantifier = (fn
  11.439 +    @{const_name All} => SOME SForall
  11.440 +  | @{const_name Ex} => SOME SExists
  11.441 +  | _ => NONE)
  11.442 +
  11.443 +fun group_quant qname Ts (t as Const (q, _) $ Abs (_, T, u)) =
  11.444 +      if q = qname then group_quant qname (T :: Ts) u else (Ts, t)
  11.445 +  | group_quant _ Ts t = (Ts, t)
  11.446 +
  11.447 +fun dest_weight (@{const SMT.weight} $ w $ t) =
  11.448 +      (SOME (snd (HOLogic.dest_number w)), t)
  11.449 +  | dest_weight t = (NONE, t)
  11.450 +
  11.451 +fun dest_pat (Const (@{const_name SMT.pat}, _) $ t) = (t, true)
  11.452 +  | dest_pat (Const (@{const_name SMT.nopat}, _) $ t) = (t, false)
  11.453 +  | dest_pat t = raise TERM ("bad pattern", [t])
  11.454 +
  11.455 +fun dest_pats [] = I
  11.456 +  | dest_pats ts =
  11.457 +      (case map dest_pat ts |> split_list ||> distinct (op =) of
  11.458 +        (ps, [true]) => cons (SPat ps)
  11.459 +      | (ps, [false]) => cons (SNoPat ps)
  11.460 +      | _ => raise TERM ("bad multi-pattern", ts))
  11.461 +
  11.462 +fun dest_trigger (@{const SMT.trigger} $ tl $ t) =
  11.463 +      (rev (fold (dest_pats o HOLogic.dest_list) (HOLogic.dest_list tl) []), t)
  11.464 +  | dest_trigger t = ([], t)
  11.465 +
  11.466 +fun dest_quant qn T t = quantifier qn |> Option.map (fn q =>
  11.467 +  let
  11.468 +    val (Ts, u) = group_quant qn [T] t
  11.469 +    val (ps, p) = dest_trigger u
  11.470 +    val (w, b) = dest_weight p
  11.471 +  in (q, rev Ts, ps, w, b) end)
  11.472 +
  11.473 +fun fold_map_pat f (SPat ts) = fold_map f ts #>> SPat
  11.474 +  | fold_map_pat f (SNoPat ts) = fold_map f ts #>> SNoPat
  11.475 +
  11.476 +
  11.477 +(** translation from Isabelle terms into SMT intermediate terms **)
  11.478 +
  11.479 +fun intermediate header dtyps builtin ctxt ts trx =
  11.480 +  let
  11.481 +    fun transT (T as TFree _) = add_typ T true
  11.482 +      | transT (T as TVar _) = (fn _ => raise TYPE ("bad SMT type", [T], []))
  11.483 +      | transT (T as Type _) =
  11.484 +          (case SMT_Builtin.dest_builtin_typ ctxt T of
  11.485 +            SOME n => pair n
  11.486 +          | NONE => add_typ T true)
  11.487 +
  11.488 +    fun app n ts = SApp (n, ts)
  11.489 +
  11.490 +    fun trans t =
  11.491 +      (case Term.strip_comb t of
  11.492 +        (Const (qn, _), [Abs (_, T, t1)]) =>
  11.493 +          (case dest_quant qn T t1 of
  11.494 +            SOME (q, Ts, ps, w, b) =>
  11.495 +              fold_map transT Ts ##>> fold_map (fold_map_pat trans) ps ##>>
  11.496 +              trans b #>> (fn ((Ts', ps'), b') => SQua (q, Ts', ps', w, b'))
  11.497 +          | NONE => raise TERM ("unsupported quantifier", [t]))
  11.498 +      | (Const (@{const_name Let}, _), [t1, Abs (_, T, t2)]) =>
  11.499 +          transT T ##>> trans t1 ##>> trans t2 #>>
  11.500 +          (fn ((U, u1), u2) => SLet (U, u1, u2))
  11.501 +      | (u as Const (c as (_, T)), ts) =>
  11.502 +          (case builtin ctxt c ts of
  11.503 +            SOME (n, _, us, _) => fold_map trans us #>> app n
  11.504 +          | NONE => transs u T ts)
  11.505 +      | (u as Free (_, T), ts) => transs u T ts
  11.506 +      | (Bound i, []) => pair (SVar i)
  11.507 +      | _ => raise TERM ("bad SMT term", [t]))
  11.508 + 
  11.509 +    and transs t T ts =
  11.510 +      let val (Us, U) = SMT_Utils.dest_funT (length ts) T
  11.511 +      in
  11.512 +        fold_map transT Us ##>> transT U #-> (fn Up =>
  11.513 +        add_fun t (SOME Up) ##>> fold_map trans ts #>> SApp)
  11.514 +      end
  11.515 +
  11.516 +    val (us, trx') = fold_map trans ts trx
  11.517 +  in ((sign_of (header ts) dtyps trx', us), trx') end
  11.518 +
  11.519 +
  11.520 +
  11.521 +(* translation *)
  11.522 +
  11.523 +structure Configs = Generic_Data
  11.524 +(
  11.525 +  type T = (Proof.context -> config) SMT_Utils.dict
  11.526 +  val empty = []
  11.527 +  val extend = I
  11.528 +  fun merge data = SMT_Utils.dict_merge fst data
  11.529 +)
  11.530 +
  11.531 +fun add_config (cs, cfg) = Configs.map (SMT_Utils.dict_update (cs, cfg))
  11.532 +
  11.533 +fun get_config ctxt = 
  11.534 +  let val cs = SMT_Config.solver_class_of ctxt
  11.535 +  in
  11.536 +    (case SMT_Utils.dict_get (Configs.get (Context.Proof ctxt)) cs of
  11.537 +      SOME cfg => cfg ctxt
  11.538 +    | NONE => error ("SMT: no translation configuration found " ^
  11.539 +        "for solver class " ^ quote (SMT_Utils.string_of_class cs)))
  11.540 +  end
  11.541 +
  11.542 +fun translate ctxt comments ithms =
  11.543 +  let
  11.544 +    val {prefixes, is_fol, header, has_datatypes, serialize} = get_config ctxt
  11.545 +
  11.546 +    val with_datatypes =
  11.547 +      has_datatypes andalso Config.get ctxt SMT_Config.datatypes
  11.548 +
  11.549 +    fun no_dtyps (tr_context, ctxt) ts =
  11.550 +      ((Termtab.empty, [], tr_context, ctxt), ts)
  11.551 +
  11.552 +    val ts1 = map (Envir.beta_eta_contract o SMT_Utils.prop_of o snd) ithms
  11.553 +
  11.554 +    val ((funcs, dtyps, tr_context, ctxt1), ts2) =
  11.555 +      ((make_tr_context prefixes, ctxt), ts1)
  11.556 +      |-> (if with_datatypes then collect_datatypes_and_records else no_dtyps)
  11.557 +
  11.558 +    fun is_binder (Const (@{const_name Let}, _) $ _) = true
  11.559 +      | is_binder t = Lambda_Lifting.is_quantifier t
  11.560 +
  11.561 +    fun mk_trigger ((q as Const (@{const_name All}, _)) $ Abs (n, T, t)) =
  11.562 +          q $ Abs (n, T, mk_trigger t)
  11.563 +      | mk_trigger (eq as (Const (@{const_name HOL.eq}, T) $ lhs $ _)) =
  11.564 +          Term.domain_type T --> @{typ SMT.pattern}
  11.565 +          |> (fn T => Const (@{const_name SMT.pat}, T) $ lhs)
  11.566 +          |> HOLogic.mk_list @{typ SMT.pattern} o single
  11.567 +          |> HOLogic.mk_list @{typ "SMT.pattern list"} o single
  11.568 +          |> (fn t => @{const SMT.trigger} $ t $ eq)
  11.569 +      | mk_trigger t = t
  11.570 +
  11.571 +    val (ctxt2, ts3) =
  11.572 +      ts2
  11.573 +      |> eta_expand ctxt1 is_fol funcs
  11.574 +      |> rpair ctxt1
  11.575 +      |-> Lambda_Lifting.lift_lambdas NONE is_binder
  11.576 +      |-> (fn (ts', defs) => fn ctxt' =>
  11.577 +          map mk_trigger defs @ ts'
  11.578 +          |> intro_explicit_application ctxt' funcs 
  11.579 +          |> pair ctxt')
  11.580 +
  11.581 +    val ((rewrite_rules, extra_thms, builtin), ts4) =
  11.582 +      (if is_fol then folify ctxt2 else pair ([], [], I)) ts3
  11.583 +
  11.584 +    val rewrite_rules' = fun_app_eq :: rewrite_rules
  11.585 +  in
  11.586 +    (ts4, tr_context)
  11.587 +    |-> intermediate header dtyps (builtin SMT_Builtin.dest_builtin) ctxt2
  11.588 +    |>> uncurry (serialize comments)
  11.589 +    ||> recon_of ctxt2 rewrite_rules' extra_thms ithms
  11.590 +  end
  11.591 +
  11.592 +end
    12.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    12.2 +++ b/src/HOL/Library/SMT/smt_utils.ML	Thu Aug 28 00:40:37 2014 +0200
    12.3 @@ -0,0 +1,227 @@
    12.4 +(*  Title:      HOL/Library/SMT/smt_utils.ML
    12.5 +    Author:     Sascha Boehme, TU Muenchen
    12.6 +
    12.7 +General utility functions.
    12.8 +*)
    12.9 +
   12.10 +signature SMT_UTILS =
   12.11 +sig
   12.12 +  (*basic combinators*)
   12.13 +  val repeat: ('a -> 'a option) -> 'a -> 'a
   12.14 +  val repeat_yield: ('a -> 'b -> ('a * 'b) option) -> 'a -> 'b -> 'a * 'b
   12.15 +
   12.16 +  (*class dictionaries*)
   12.17 +  type class = string list
   12.18 +  val basicC: class
   12.19 +  val string_of_class: class -> string
   12.20 +  type 'a dict = (class * 'a) Ord_List.T
   12.21 +  val dict_map_default: class * 'a -> ('a -> 'a) -> 'a dict -> 'a dict
   12.22 +  val dict_update: class * 'a -> 'a dict -> 'a dict
   12.23 +  val dict_merge: ('a * 'a -> 'a) -> 'a dict * 'a dict -> 'a dict
   12.24 +  val dict_lookup: 'a dict -> class -> 'a list
   12.25 +  val dict_get: 'a dict -> class -> 'a option
   12.26 +
   12.27 +  (*types*)
   12.28 +  val dest_funT: int -> typ -> typ list * typ
   12.29 +
   12.30 +  (*terms*)
   12.31 +  val dest_conj: term -> term * term
   12.32 +  val dest_disj: term -> term * term
   12.33 +  val under_quant: (term -> 'a) -> term -> 'a
   12.34 +  val is_number: term -> bool
   12.35 +
   12.36 +  (*patterns and instantiations*)
   12.37 +  val mk_const_pat: theory -> string -> (ctyp -> 'a) -> 'a * cterm
   12.38 +  val destT1: ctyp -> ctyp
   12.39 +  val destT2: ctyp -> ctyp
   12.40 +  val instTs: ctyp list -> ctyp list * cterm -> cterm
   12.41 +  val instT: ctyp -> ctyp * cterm -> cterm
   12.42 +  val instT': cterm -> ctyp * cterm -> cterm
   12.43 +
   12.44 +  (*certified terms*)
   12.45 +  val certify: Proof.context -> term -> cterm
   12.46 +  val typ_of: cterm -> typ
   12.47 +  val dest_cabs: cterm -> Proof.context -> cterm * Proof.context
   12.48 +  val dest_all_cabs: cterm -> Proof.context -> cterm * Proof.context
   12.49 +  val dest_cbinder: cterm -> Proof.context -> cterm * Proof.context
   12.50 +  val dest_all_cbinders: cterm -> Proof.context -> cterm * Proof.context
   12.51 +  val mk_cprop: cterm -> cterm
   12.52 +  val dest_cprop: cterm -> cterm
   12.53 +  val mk_cequals: cterm -> cterm -> cterm
   12.54 +  val term_of: cterm -> term
   12.55 +  val prop_of: thm -> term
   12.56 +
   12.57 +  (*conversions*)
   12.58 +  val if_conv: (term -> bool) -> conv -> conv -> conv
   12.59 +  val if_true_conv: (term -> bool) -> conv -> conv
   12.60 +  val if_exists_conv: (term -> bool) -> conv -> conv
   12.61 +  val binders_conv: (Proof.context -> conv) -> Proof.context -> conv
   12.62 +  val under_quant_conv: (Proof.context * cterm list -> conv) ->
   12.63 +    Proof.context -> conv
   12.64 +  val prop_conv: conv -> conv
   12.65 +end
   12.66 +
   12.67 +structure SMT_Utils: SMT_UTILS =
   12.68 +struct
   12.69 +
   12.70 +(* basic combinators *)
   12.71 +
   12.72 +fun repeat f =
   12.73 +  let fun rep x = (case f x of SOME y => rep y | NONE => x)
   12.74 +  in rep end
   12.75 +
   12.76 +fun repeat_yield f =
   12.77 +  let fun rep x y = (case f x y of SOME (x', y') => rep x' y' | NONE => (x, y))
   12.78 +  in rep end
   12.79 +
   12.80 +
   12.81 +(* class dictionaries *)
   12.82 +
   12.83 +type class = string list
   12.84 +
   12.85 +val basicC = []
   12.86 +
   12.87 +fun string_of_class [] = "basic"
   12.88 +  | string_of_class cs = "basic." ^ space_implode "." cs
   12.89 +
   12.90 +type 'a dict = (class * 'a) Ord_List.T
   12.91 +
   12.92 +fun class_ord ((cs1, _), (cs2, _)) =
   12.93 +  rev_order (list_ord fast_string_ord (cs1, cs2))
   12.94 +
   12.95 +fun dict_insert (cs, x) d =
   12.96 +  if AList.defined (op =) d cs then d
   12.97 +  else Ord_List.insert class_ord (cs, x) d
   12.98 +
   12.99 +fun dict_map_default (cs, x) f =
  12.100 +  dict_insert (cs, x) #> AList.map_entry (op =) cs f
  12.101 +
  12.102 +fun dict_update (e as (_, x)) = dict_map_default e (K x)
  12.103 +
  12.104 +fun dict_merge val_merge = sort class_ord o AList.join (op =) (K val_merge)
  12.105 +
  12.106 +fun dict_lookup d cs =
  12.107 +  let fun match (cs', x) = if is_prefix (op =) cs' cs then SOME x else NONE
  12.108 +  in map_filter match d end
  12.109 +
  12.110 +fun dict_get d cs =
  12.111 +  (case AList.lookup (op =) d cs of
  12.112 +    NONE => (case cs of [] => NONE | _ => dict_get d (take (length cs - 1) cs))
  12.113 +  | SOME x => SOME x)
  12.114 +
  12.115 +
  12.116 +(* types *)
  12.117 +
  12.118 +val dest_funT =
  12.119 +  let
  12.120 +    fun dest Ts 0 T = (rev Ts, T)
  12.121 +      | dest Ts i (Type ("fun", [T, U])) = dest (T::Ts) (i-1) U
  12.122 +      | dest _ _ T = raise TYPE ("not a function type", [T], [])
  12.123 +  in dest [] end
  12.124 +
  12.125 +
  12.126 +(* terms *)
  12.127 +
  12.128 +fun dest_conj (@{const HOL.conj} $ t $ u) = (t, u)
  12.129 +  | dest_conj t = raise TERM ("not a conjunction", [t])
  12.130 +
  12.131 +fun dest_disj (@{const HOL.disj} $ t $ u) = (t, u)
  12.132 +  | dest_disj t = raise TERM ("not a disjunction", [t])
  12.133 +
  12.134 +fun under_quant f t =
  12.135 +  (case t of
  12.136 +    Const (@{const_name All}, _) $ Abs (_, _, u) => under_quant f u
  12.137 +  | Const (@{const_name Ex}, _) $ Abs (_, _, u) => under_quant f u
  12.138 +  | _ => f t)
  12.139 +
  12.140 +val is_number =
  12.141 +  let
  12.142 +    fun is_num env (Const (@{const_name If}, _) $ _ $ t $ u) =
  12.143 +          is_num env t andalso is_num env u
  12.144 +      | is_num env (Const (@{const_name Let}, _) $ t $ Abs (_, _, u)) =
  12.145 +          is_num (t :: env) u
  12.146 +      | is_num env (Bound i) = i < length env andalso is_num env (nth env i)
  12.147 +      | is_num _ t = can HOLogic.dest_number t
  12.148 +  in is_num [] end
  12.149 +
  12.150 +
  12.151 +(* patterns and instantiations *)
  12.152 +
  12.153 +fun mk_const_pat thy name destT =
  12.154 +  let val cpat = Thm.cterm_of thy (Const (name, Sign.the_const_type thy name))
  12.155 +  in (destT (Thm.ctyp_of_term cpat), cpat) end
  12.156 +
  12.157 +val destT1 = hd o Thm.dest_ctyp
  12.158 +val destT2 = hd o tl o Thm.dest_ctyp
  12.159 +
  12.160 +fun instTs cUs (cTs, ct) = Thm.instantiate_cterm (cTs ~~ cUs, []) ct
  12.161 +fun instT cU (cT, ct) = instTs [cU] ([cT], ct)
  12.162 +fun instT' ct = instT (Thm.ctyp_of_term ct)
  12.163 +
  12.164 +
  12.165 +(* certified terms *)
  12.166 +
  12.167 +fun certify ctxt = Thm.cterm_of (Proof_Context.theory_of ctxt)
  12.168 +
  12.169 +fun typ_of ct = #T (Thm.rep_cterm ct) 
  12.170 +
  12.171 +fun dest_cabs ct ctxt =
  12.172 +  (case Thm.term_of ct of
  12.173 +    Abs _ =>
  12.174 +      let val (n, ctxt') = yield_singleton Variable.variant_fixes Name.uu ctxt
  12.175 +      in (snd (Thm.dest_abs (SOME n) ct), ctxt') end
  12.176 +  | _ => raise CTERM ("no abstraction", [ct]))
  12.177 +
  12.178 +val dest_all_cabs = repeat_yield (try o dest_cabs) 
  12.179 +
  12.180 +fun dest_cbinder ct ctxt =
  12.181 +  (case Thm.term_of ct of
  12.182 +    Const _ $ Abs _ => dest_cabs (Thm.dest_arg ct) ctxt
  12.183 +  | _ => raise CTERM ("not a binder", [ct]))
  12.184 +
  12.185 +val dest_all_cbinders = repeat_yield (try o dest_cbinder)
  12.186 +
  12.187 +val mk_cprop = Thm.apply (Thm.cterm_of @{theory} @{const Trueprop})
  12.188 +
  12.189 +fun dest_cprop ct =
  12.190 +  (case Thm.term_of ct of
  12.191 +    @{const Trueprop} $ _ => Thm.dest_arg ct
  12.192 +  | _ => raise CTERM ("not a property", [ct]))
  12.193 +
  12.194 +val equals = mk_const_pat @{theory} @{const_name Pure.eq} destT1
  12.195 +fun mk_cequals ct cu = Thm.mk_binop (instT' ct equals) ct cu
  12.196 +
  12.197 +val dest_prop = (fn @{const Trueprop} $ t => t | t => t)
  12.198 +fun term_of ct = dest_prop (Thm.term_of ct)
  12.199 +fun prop_of thm = dest_prop (Thm.prop_of thm)
  12.200 +
  12.201 +
  12.202 +(* conversions *)
  12.203 +
  12.204 +fun if_conv pred cv1 cv2 ct = if pred (Thm.term_of ct) then cv1 ct else cv2 ct
  12.205 +
  12.206 +fun if_true_conv pred cv = if_conv pred cv Conv.all_conv
  12.207 +
  12.208 +fun if_exists_conv pred = if_true_conv (Term.exists_subterm pred)
  12.209 +
  12.210 +fun binders_conv cv ctxt =
  12.211 +  Conv.binder_conv (binders_conv cv o snd) ctxt else_conv cv ctxt
  12.212 +
  12.213 +fun under_quant_conv cv ctxt =
  12.214 +  let
  12.215 +    fun quant_conv inside ctxt cvs ct =
  12.216 +      (case Thm.term_of ct of
  12.217 +        Const (@{const_name All}, _) $ Abs _ =>
  12.218 +          Conv.binder_conv (under_conv cvs) ctxt
  12.219 +      | Const (@{const_name Ex}, _) $ Abs _ =>
  12.220 +          Conv.binder_conv (under_conv cvs) ctxt
  12.221 +      | _ => if inside then cv (ctxt, cvs) else Conv.all_conv) ct
  12.222 +    and under_conv cvs (cv, ctxt) = quant_conv true ctxt (cv :: cvs)
  12.223 +  in quant_conv false ctxt [] end
  12.224 +
  12.225 +fun prop_conv cv ct =
  12.226 +  (case Thm.term_of ct of
  12.227 +    @{const Trueprop} $ _ => Conv.arg_conv cv ct
  12.228 +  | _ => raise CTERM ("not a property", [ct]))
  12.229 +
  12.230 +end
    13.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    13.2 +++ b/src/HOL/Library/SMT/smtlib_interface.ML	Thu Aug 28 00:40:37 2014 +0200
    13.3 @@ -0,0 +1,161 @@
    13.4 +(*  Title:      HOL/Library/SMT/smtlib_interface.ML
    13.5 +    Author:     Sascha Boehme, TU Muenchen
    13.6 +
    13.7 +Interface to SMT solvers based on the SMT-LIB format.
    13.8 +*)
    13.9 +
   13.10 +signature SMTLIB_INTERFACE =
   13.11 +sig
   13.12 +  val smtlibC: SMT_Utils.class
   13.13 +  val add_logic: int * (term list -> string option) -> Context.generic ->
   13.14 +    Context.generic
   13.15 +  val translate_config: Proof.context -> SMT_Translate.config
   13.16 +  val setup: theory -> theory
   13.17 +end
   13.18 +
   13.19 +structure SMTLIB_Interface: SMTLIB_INTERFACE =
   13.20 +struct
   13.21 +
   13.22 +
   13.23 +val smtlibC = ["smtlib"]
   13.24 +
   13.25 +
   13.26 +(* builtins *)
   13.27 +
   13.28 +local
   13.29 +  fun int_num _ i = SOME (string_of_int i)
   13.30 +
   13.31 +  fun is_linear [t] = SMT_Utils.is_number t
   13.32 +    | is_linear [t, u] = SMT_Utils.is_number t orelse SMT_Utils.is_number u
   13.33 +    | is_linear _ = false
   13.34 +
   13.35 +  fun times _ _ ts =
   13.36 +    let val mk = Term.list_comb o pair @{const times (int)}
   13.37 +    in if is_linear ts then SOME ("*", 2, ts, mk) else NONE end
   13.38 +in
   13.39 +
   13.40 +val setup_builtins =
   13.41 +  SMT_Builtin.add_builtin_typ smtlibC (@{typ int}, K (SOME "Int"), int_num) #>
   13.42 +  fold (SMT_Builtin.add_builtin_fun' smtlibC) [
   13.43 +    (@{const True}, "true"),
   13.44 +    (@{const False}, "false"),
   13.45 +    (@{const Not}, "not"),
   13.46 +    (@{const HOL.conj}, "and"),
   13.47 +    (@{const HOL.disj}, "or"),
   13.48 +    (@{const HOL.implies}, "implies"),
   13.49 +    (@{const HOL.eq (bool)}, "iff"),
   13.50 +    (@{const HOL.eq ('a)}, "="),
   13.51 +    (@{const If (bool)}, "if_then_else"),
   13.52 +    (@{const If ('a)}, "ite"),
   13.53 +    (@{const less (int)}, "<"),
   13.54 +    (@{const less_eq (int)}, "<="),
   13.55 +    (@{const uminus (int)}, "~"),
   13.56 +    (@{const plus (int)}, "+"),
   13.57 +    (@{const minus (int)}, "-") ] #>
   13.58 +  SMT_Builtin.add_builtin_fun smtlibC
   13.59 +    (Term.dest_Const @{const times (int)}, times)
   13.60 +
   13.61 +end
   13.62 +
   13.63 +
   13.64 +(* serialization *)
   13.65 +
   13.66 +(** header **)
   13.67 +
   13.68 +fun fst_int_ord ((i1, _), (i2, _)) = int_ord (i1, i2)
   13.69 +
   13.70 +structure Logics = Generic_Data
   13.71 +(
   13.72 +  type T = (int * (term list -> string option)) list
   13.73 +  val empty = []
   13.74 +  val extend = I
   13.75 +  fun merge data = Ord_List.merge fst_int_ord data
   13.76 +)
   13.77 +
   13.78 +fun add_logic pf = Logics.map (Ord_List.insert fst_int_ord pf)
   13.79 +
   13.80 +fun choose_logic ctxt ts =
   13.81 +  let
   13.82 +    fun choose [] = "AUFLIA"
   13.83 +      | choose ((_, f) :: fs) = (case f ts of SOME s => s | NONE => choose fs)
   13.84 +  in [":logic " ^ choose (Logics.get (Context.Proof ctxt))] end
   13.85 +
   13.86 +
   13.87 +(** serialization **)
   13.88 +
   13.89 +val add = Buffer.add
   13.90 +fun sep f = add " " #> f
   13.91 +fun enclose l r f = sep (add l #> f #> add r)
   13.92 +val par = enclose "(" ")"
   13.93 +fun app n f = (fn [] => sep (add n) | xs => par (add n #> fold f xs))
   13.94 +fun line f = f #> add "\n"
   13.95 +
   13.96 +fun var i = add "?v" #> add (string_of_int i)
   13.97 +
   13.98 +fun sterm l (SMT_Translate.SVar i) = sep (var (l - i - 1))
   13.99 +  | sterm l (SMT_Translate.SApp (n, ts)) = app n (sterm l) ts
  13.100 +  | sterm _ (SMT_Translate.SLet _) =
  13.101 +      raise Fail "SMT-LIB: unsupported let expression"
  13.102 +  | sterm l (SMT_Translate.SQua (q, ss, ps, w, t)) =
  13.103 +      let
  13.104 +        fun quant SMT_Translate.SForall = add "forall"
  13.105 +          | quant SMT_Translate.SExists = add "exists"
  13.106 +        val vs = map_index (apfst (Integer.add l)) ss
  13.107 +        fun var_decl (i, s) = par (var i #> sep (add s))
  13.108 +        val sub = sterm (l + length ss)
  13.109 +        fun pat kind ts = sep (add kind #> enclose "{" " }" (fold sub ts))
  13.110 +        fun pats (SMT_Translate.SPat ts) = pat ":pat" ts
  13.111 +          | pats (SMT_Translate.SNoPat ts) = pat ":nopat" ts
  13.112 +        fun weight NONE = I
  13.113 +          | weight (SOME i) =
  13.114 +              sep (add ":weight { " #> add (string_of_int i) #> add " }")
  13.115 +      in
  13.116 +        par (quant q #> fold var_decl vs #> sub t #> fold pats ps #> weight w)
  13.117 +      end
  13.118 +
  13.119 +fun ssort sorts = sort fast_string_ord sorts
  13.120 +fun fsort funcs = sort (prod_ord fast_string_ord (K EQUAL)) funcs
  13.121 +
  13.122 +fun sdatatypes decls =
  13.123 +  let
  13.124 +    fun con (n, []) = sep (add n)
  13.125 +      | con (n, sels) = par (add n #>
  13.126 +          fold (fn (n, s) => par (add n #> sep (add s))) sels)
  13.127 +    fun dtyp (n, decl) = add n #> fold con decl
  13.128 +  in line (add ":datatypes " #> par (fold (par o dtyp) decls)) end
  13.129 +
  13.130 +fun serialize comments {header, sorts, dtyps, funcs} ts =
  13.131 +  Buffer.empty
  13.132 +  |> line (add "(benchmark Isabelle")
  13.133 +  |> line (add ":status unknown")
  13.134 +  |> fold (line o add) header
  13.135 +  |> length sorts > 0 ?
  13.136 +       line (add ":extrasorts" #> par (fold (sep o add) (ssort sorts)))
  13.137 +  |> fold sdatatypes dtyps
  13.138 +  |> length funcs > 0 ? (
  13.139 +       line (add ":extrafuns" #> add " (") #>
  13.140 +       fold (fn (f, (ss, s)) =>
  13.141 +         line (sep (app f (sep o add) (ss @ [s])))) (fsort funcs) #>
  13.142 +       line (add ")"))
  13.143 +  |> fold (fn t => line (add ":assumption" #> sterm 0 t)) ts
  13.144 +  |> line (add ":formula true)")
  13.145 +  |> fold (fn str => line (add "; " #> add str)) comments
  13.146 +  |> Buffer.content
  13.147 +
  13.148 +
  13.149 +(* interface *)
  13.150 +
  13.151 +fun translate_config ctxt = {
  13.152 +  prefixes = {
  13.153 +    sort_prefix = "S",
  13.154 +    func_prefix = "f"},
  13.155 +  header = choose_logic ctxt,
  13.156 +  is_fol = true,
  13.157 +  has_datatypes = false,
  13.158 +  serialize = serialize}
  13.159 +
  13.160 +val setup = Context.theory_map (
  13.161 +  setup_builtins #>
  13.162 +  SMT_Translate.add_config (smtlibC, translate_config))
  13.163 +
  13.164 +end
    14.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    14.2 +++ b/src/HOL/Library/SMT/z3_interface.ML	Thu Aug 28 00:40:37 2014 +0200
    14.3 @@ -0,0 +1,239 @@
    14.4 +(*  Title:      HOL/Library/SMT/z3_interface.ML
    14.5 +    Author:     Sascha Boehme, TU Muenchen
    14.6 +
    14.7 +Interface to Z3 based on a relaxed version of SMT-LIB.
    14.8 +*)
    14.9 +
   14.10 +signature Z3_INTERFACE =
   14.11 +sig
   14.12 +  val smtlib_z3C: SMT_Utils.class
   14.13 +  val setup: theory -> theory
   14.14 +
   14.15 +  datatype sym = Sym of string * sym list
   14.16 +  type mk_builtins = {
   14.17 +    mk_builtin_typ: sym -> typ option,
   14.18 +    mk_builtin_num: theory -> int -> typ -> cterm option,
   14.19 +    mk_builtin_fun: theory -> sym -> cterm list -> cterm option }
   14.20 +  val add_mk_builtins: mk_builtins -> Context.generic -> Context.generic
   14.21 +  val mk_builtin_typ: Proof.context -> sym -> typ option
   14.22 +  val mk_builtin_num: Proof.context -> int -> typ -> cterm option
   14.23 +  val mk_builtin_fun: Proof.context -> sym -> cterm list -> cterm option
   14.24 +
   14.25 +  val is_builtin_theory_term: Proof.context -> term -> bool
   14.26 +end
   14.27 +
   14.28 +structure Z3_Interface: Z3_INTERFACE =
   14.29 +struct
   14.30 +
   14.31 +val smtlib_z3C = SMTLIB_Interface.smtlibC @ ["z3"]
   14.32 +
   14.33 +
   14.34 +
   14.35 +(* interface *)
   14.36 +
   14.37 +local
   14.38 +  fun translate_config ctxt =
   14.39 +    let
   14.40 +      val {prefixes, header, is_fol, serialize, ...} =
   14.41 +        SMTLIB_Interface.translate_config ctxt
   14.42 +    in
   14.43 +      {prefixes=prefixes, header=header, is_fol=is_fol, serialize=serialize,
   14.44 +        has_datatypes=true}
   14.45 +    end
   14.46 +
   14.47 +  fun is_div_mod @{const div (int)} = true
   14.48 +    | is_div_mod @{const mod (int)} = true
   14.49 +    | is_div_mod _ = false
   14.50 +
   14.51 +  val div_by_z3div = @{lemma
   14.52 +    "ALL k l. k div l = (
   14.53 +      if k = 0 | l = 0 then 0
   14.54 +      else if (0 < k & 0 < l) | (k < 0 & 0 < l) then z3div k l
   14.55 +      else z3div (-k) (-l))"
   14.56 +    by (simp add: SMT.z3div_def)}
   14.57 +
   14.58 +  val mod_by_z3mod = @{lemma
   14.59 +    "ALL k l. k mod l = (
   14.60 +      if l = 0 then k
   14.61 +      else if k = 0 then 0
   14.62 +      else if (0 < k & 0 < l) | (k < 0 & 0 < l) then z3mod k l
   14.63 +      else - z3mod (-k) (-l))"
   14.64 +    by (simp add: z3mod_def)}
   14.65 +
   14.66 +  val have_int_div_mod =
   14.67 +    exists (Term.exists_subterm is_div_mod o Thm.prop_of)
   14.68 +
   14.69 +  fun add_div_mod _ (thms, extra_thms) =
   14.70 +    if have_int_div_mod thms orelse have_int_div_mod extra_thms then
   14.71 +      (thms, div_by_z3div :: mod_by_z3mod :: extra_thms)
   14.72 +    else (thms, extra_thms)
   14.73 +
   14.74 +  val setup_builtins =
   14.75 +    SMT_Builtin.add_builtin_fun' smtlib_z3C (@{const times (int)}, "*") #>
   14.76 +    SMT_Builtin.add_builtin_fun' smtlib_z3C (@{const z3div}, "div") #>
   14.77 +    SMT_Builtin.add_builtin_fun' smtlib_z3C (@{const z3mod}, "mod")
   14.78 +in
   14.79 +
   14.80 +val setup = Context.theory_map (
   14.81 +  setup_builtins #>
   14.82 +  SMT_Normalize.add_extra_norm (smtlib_z3C, add_div_mod) #>
   14.83 +  SMT_Translate.add_config (smtlib_z3C, translate_config))
   14.84 +
   14.85 +end
   14.86 +
   14.87 +
   14.88 +
   14.89 +(* constructors *)
   14.90 +
   14.91 +datatype sym = Sym of string * sym list
   14.92 +
   14.93 +
   14.94 +(** additional constructors **)
   14.95 +
   14.96 +type mk_builtins = {
   14.97 +  mk_builtin_typ: sym -> typ option,
   14.98 +  mk_builtin_num: theory -> int -> typ -> cterm option,
   14.99 +  mk_builtin_fun: theory -> sym -> cterm list -> cterm option }
  14.100 +
  14.101 +fun chained _ [] = NONE
  14.102 +  | chained f (b :: bs) = (case f b of SOME y => SOME y | NONE => chained f bs)
  14.103 +
  14.104 +fun chained_mk_builtin_typ bs sym =
  14.105 +  chained (fn {mk_builtin_typ=mk, ...} : mk_builtins => mk sym) bs
  14.106 +
  14.107 +fun chained_mk_builtin_num ctxt bs i T =
  14.108 +  let val thy = Proof_Context.theory_of ctxt
  14.109 +  in chained (fn {mk_builtin_num=mk, ...} : mk_builtins => mk thy i T) bs end
  14.110 +
  14.111 +fun chained_mk_builtin_fun ctxt bs s cts =
  14.112 +  let val thy = Proof_Context.theory_of ctxt
  14.113 +  in chained (fn {mk_builtin_fun=mk, ...} : mk_builtins => mk thy s cts) bs end
  14.114 +
  14.115 +fun fst_int_ord ((i1, _), (i2, _)) = int_ord (i1, i2)
  14.116 +
  14.117 +structure Mk_Builtins = Generic_Data
  14.118 +(
  14.119 +  type T = (int * mk_builtins) list
  14.120 +  val empty = []
  14.121 +  val extend = I
  14.122 +  fun merge data = Ord_List.merge fst_int_ord data
  14.123 +)
  14.124 +
  14.125 +fun add_mk_builtins mk =
  14.126 +  Mk_Builtins.map (Ord_List.insert fst_int_ord (serial (), mk))
  14.127 +
  14.128 +fun get_mk_builtins ctxt = map snd (Mk_Builtins.get (Context.Proof ctxt))
  14.129 +
  14.130 +
  14.131 +(** basic and additional constructors **)
  14.132 +
  14.133 +fun mk_builtin_typ _ (Sym ("Bool", _)) = SOME @{typ bool}
  14.134 +  | mk_builtin_typ _ (Sym ("Int", _)) = SOME @{typ int}
  14.135 +  | mk_builtin_typ _ (Sym ("bool", _)) = SOME @{typ bool}  (*FIXME: legacy*)
  14.136 +  | mk_builtin_typ _ (Sym ("int", _)) = SOME @{typ int}  (*FIXME: legacy*)
  14.137 +  | mk_builtin_typ ctxt sym = chained_mk_builtin_typ (get_mk_builtins ctxt) sym
  14.138 +
  14.139 +fun mk_builtin_num _ i @{typ int} = SOME (Numeral.mk_cnumber @{ctyp int} i)
  14.140 +  | mk_builtin_num ctxt i T =
  14.141 +      chained_mk_builtin_num ctxt (get_mk_builtins ctxt) i T
  14.142 +
  14.143 +val mk_true = Thm.cterm_of @{theory} (@{const Not} $ @{const False})
  14.144 +val mk_false = Thm.cterm_of @{theory} @{const False}
  14.145 +val mk_not = Thm.apply (Thm.cterm_of @{theory} @{const Not})
  14.146 +val mk_implies = Thm.mk_binop (Thm.cterm_of @{theory} @{const HOL.implies})
  14.147 +val mk_iff = Thm.mk_binop (Thm.cterm_of @{theory} @{const HOL.eq (bool)})
  14.148 +val conj = Thm.cterm_of @{theory} @{const HOL.conj}
  14.149 +val disj = Thm.cterm_of @{theory} @{const HOL.disj}
  14.150 +
  14.151 +fun mk_nary _ cu [] = cu
  14.152 +  | mk_nary ct _ cts = uncurry (fold_rev (Thm.mk_binop ct)) (split_last cts)
  14.153 +
  14.154 +val eq = SMT_Utils.mk_const_pat @{theory} @{const_name HOL.eq} SMT_Utils.destT1
  14.155 +fun mk_eq ct cu = Thm.mk_binop (SMT_Utils.instT' ct eq) ct cu
  14.156 +
  14.157 +val if_term =
  14.158 +  SMT_Utils.mk_const_pat @{theory} @{const_name If}
  14.159 +    (SMT_Utils.destT1 o SMT_Utils.destT2)
  14.160 +fun mk_if cc ct cu =
  14.161 +  Thm.mk_binop (Thm.apply (SMT_Utils.instT' ct if_term) cc) ct cu
  14.162 +
  14.163 +val nil_term =
  14.164 +  SMT_Utils.mk_const_pat @{theory} @{const_name Nil} SMT_Utils.destT1
  14.165 +val cons_term =
  14.166 +  SMT_Utils.mk_const_pat @{theory} @{const_name Cons} SMT_Utils.destT1
  14.167 +fun mk_list cT cts =
  14.168 +  fold_rev (Thm.mk_binop (SMT_Utils.instT cT cons_term)) cts
  14.169 +    (SMT_Utils.instT cT nil_term)
  14.170 +
  14.171 +val distinct = SMT_Utils.mk_const_pat @{theory} @{const_name distinct}
  14.172 +  (SMT_Utils.destT1 o SMT_Utils.destT1)
  14.173 +fun mk_distinct [] = mk_true
  14.174 +  | mk_distinct (cts as (ct :: _)) =
  14.175 +      Thm.apply (SMT_Utils.instT' ct distinct)
  14.176 +        (mk_list (Thm.ctyp_of_term ct) cts)
  14.177 +
  14.178 +val access =
  14.179 +  SMT_Utils.mk_const_pat @{theory} @{const_name fun_app} SMT_Utils.destT1
  14.180 +fun mk_access array = Thm.apply (SMT_Utils.instT' array access) array
  14.181 +
  14.182 +val update = SMT_Utils.mk_const_pat @{theory} @{const_name fun_upd}
  14.183 +  (Thm.dest_ctyp o SMT_Utils.destT1)
  14.184 +fun mk_update array index value =
  14.185 +  let val cTs = Thm.dest_ctyp (Thm.ctyp_of_term array)
  14.186 +  in
  14.187 +    Thm.apply (Thm.mk_binop (SMT_Utils.instTs cTs update) array index) value
  14.188 +  end
  14.189 +
  14.190 +val mk_uminus = Thm.apply (Thm.cterm_of @{theory} @{const uminus (int)})
  14.191 +val add = Thm.cterm_of @{theory} @{const plus (int)}
  14.192 +val int0 = Numeral.mk_cnumber @{ctyp int} 0
  14.193 +val mk_sub = Thm.mk_binop (Thm.cterm_of @{theory} @{const minus (int)})
  14.194 +val mk_mul = Thm.mk_binop (Thm.cterm_of @{theory} @{const times (int)})
  14.195 +val mk_div = Thm.mk_binop (Thm.cterm_of @{theory} @{const z3div})
  14.196 +val mk_mod = Thm.mk_binop (Thm.cterm_of @{theory} @{const z3mod})
  14.197 +val mk_lt = Thm.mk_binop (Thm.cterm_of @{theory} @{const less (int)})
  14.198 +val mk_le = Thm.mk_binop (Thm.cterm_of @{theory} @{const less_eq (int)})
  14.199 +
  14.200 +fun mk_builtin_fun ctxt sym cts =
  14.201 +  (case (sym, cts) of
  14.202 +    (Sym ("true", _), []) => SOME mk_true
  14.203 +  | (Sym ("false", _), []) => SOME mk_false
  14.204 +  | (Sym ("not", _), [ct]) => SOME (mk_not ct)
  14.205 +  | (Sym ("and", _), _) => SOME (mk_nary conj mk_true cts)
  14.206 +  | (Sym ("or", _), _) => SOME (mk_nary disj mk_false cts)
  14.207 +  | (Sym ("implies", _), [ct, cu]) => SOME (mk_implies ct cu)
  14.208 +  | (Sym ("iff", _), [ct, cu]) => SOME (mk_iff ct cu)
  14.209 +  | (Sym ("~", _), [ct, cu]) => SOME (mk_iff ct cu)
  14.210 +  | (Sym ("xor", _), [ct, cu]) => SOME (mk_not (mk_iff ct cu))
  14.211 +  | (Sym ("if", _), [ct1, ct2, ct3]) => SOME (mk_if ct1 ct2 ct3)
  14.212 +  | (Sym ("ite", _), [ct1, ct2, ct3]) => SOME (mk_if ct1 ct2 ct3) (* FIXME: remove *)
  14.213 +  | (Sym ("=", _), [ct, cu]) => SOME (mk_eq ct cu)
  14.214 +  | (Sym ("distinct", _), _) => SOME (mk_distinct cts)
  14.215 +  | (Sym ("select", _), [ca, ck]) => SOME (Thm.apply (mk_access ca) ck)
  14.216 +  | (Sym ("store", _), [ca, ck, cv]) => SOME (mk_update ca ck cv)
  14.217 +  | _ =>
  14.218 +    (case (sym, try (#T o Thm.rep_cterm o hd) cts, cts) of
  14.219 +      (Sym ("+", _), SOME @{typ int}, _) => SOME (mk_nary add int0 cts)
  14.220 +    | (Sym ("-", _), SOME @{typ int}, [ct]) => SOME (mk_uminus ct)
  14.221 +    | (Sym ("-", _), SOME @{typ int}, [ct, cu]) => SOME (mk_sub ct cu)
  14.222 +    | (Sym ("*", _), SOME @{typ int}, [ct, cu]) => SOME (mk_mul ct cu)
  14.223 +    | (Sym ("div", _), SOME @{typ int}, [ct, cu]) => SOME (mk_div ct cu)
  14.224 +    | (Sym ("mod", _), SOME @{typ int}, [ct, cu]) => SOME (mk_mod ct cu)
  14.225 +    | (Sym ("<", _), SOME @{typ int}, [ct, cu]) => SOME (mk_lt ct cu)
  14.226 +    | (Sym ("<=", _), SOME @{typ int}, [ct, cu]) => SOME (mk_le ct cu)
  14.227 +    | (Sym (">", _), SOME @{typ int}, [ct, cu]) => SOME (mk_lt cu ct)
  14.228 +    | (Sym (">=", _), SOME @{typ int}, [ct, cu]) => SOME (mk_le cu ct)
  14.229 +    | _ => chained_mk_builtin_fun ctxt (get_mk_builtins ctxt) sym cts))
  14.230 +
  14.231 +
  14.232 +
  14.233 +(* abstraction *)
  14.234 +
  14.235 +fun is_builtin_theory_term ctxt t =
  14.236 +  if SMT_Builtin.is_builtin_num ctxt t then true
  14.237 +  else
  14.238 +    (case Term.strip_comb t of
  14.239 +      (Const c, ts) => SMT_Builtin.is_builtin_fun ctxt c ts
  14.240 +    | _ => false)
  14.241 +
  14.242 +end
    15.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    15.2 +++ b/src/HOL/Library/SMT/z3_model.ML	Thu Aug 28 00:40:37 2014 +0200
    15.3 @@ -0,0 +1,337 @@
    15.4 +(*  Title:      HOL/Library/SMT/z3_model.ML
    15.5 +    Author:     Sascha Boehme and Philipp Meyer, TU Muenchen
    15.6 +
    15.7 +Parser for counterexamples generated by Z3.
    15.8 +*)
    15.9 +
   15.10 +signature Z3_MODEL =
   15.11 +sig
   15.12 +  val parse_counterex: Proof.context -> SMT_Translate.recon -> string list ->
   15.13 +    term list * term list
   15.14 +end
   15.15 +
   15.16 +structure Z3_Model: Z3_MODEL =
   15.17 +struct
   15.18 +
   15.19 +
   15.20 +(* counterexample expressions *)
   15.21 +
   15.22 +datatype expr = True | False | Number of int * int option | Value of int |
   15.23 +  Array of array | App of string * expr list
   15.24 +and array = Fresh of expr | Store of (array * expr) * expr
   15.25 +
   15.26 +
   15.27 +(* parsing *)
   15.28 +
   15.29 +val space = Scan.many Symbol.is_ascii_blank
   15.30 +fun spaced p = p --| space
   15.31 +fun in_parens p = spaced (Scan.$$ "(") |-- p --| spaced (Scan.$$ ")")
   15.32 +fun in_braces p = spaced (Scan.$$ "{") |-- p --| spaced (Scan.$$ "}")
   15.33 +
   15.34 +val digit = (fn
   15.35 +  "0" => SOME 0 | "1" => SOME 1 | "2" => SOME 2 | "3" => SOME 3 |
   15.36 +  "4" => SOME 4 | "5" => SOME 5 | "6" => SOME 6 | "7" => SOME 7 |
   15.37 +  "8" => SOME 8 | "9" => SOME 9 | _ => NONE)
   15.38 +
   15.39 +val nat_num = spaced (Scan.repeat1 (Scan.some digit) >>
   15.40 +  (fn ds => fold (fn d => fn i => i * 10 + d) ds 0))
   15.41 +val int_num = spaced (Scan.optional ($$ "-" >> K (fn i => ~i)) I :|--
   15.42 +  (fn sign => nat_num >> sign))
   15.43 +
   15.44 +val is_char = Symbol.is_ascii_letter orf Symbol.is_ascii_digit orf
   15.45 +  member (op =) (raw_explode "_+*-/%~=<>$&|?!.@^#")
   15.46 +val name = spaced (Scan.many1 is_char >> implode)
   15.47 +
   15.48 +fun $$$ s = spaced (Scan.this_string s)
   15.49 +
   15.50 +fun array_expr st = st |> in_parens (
   15.51 +  $$$ "const" |-- expr >> Fresh ||
   15.52 +  $$$ "store" |-- array_expr -- expr -- expr >> Store)
   15.53 +
   15.54 +and expr st = st |> (
   15.55 +  $$$ "true" >> K True ||
   15.56 +  $$$ "false" >> K False ||
   15.57 +  int_num -- Scan.option ($$$ "/" |-- int_num) >> Number ||
   15.58 +  $$$ "val!" |-- nat_num >> Value ||
   15.59 +  name >> (App o rpair []) ||
   15.60 +  array_expr >> Array ||
   15.61 +  in_parens (name -- Scan.repeat1 expr) >> App)
   15.62 +
   15.63 +fun args st = ($$$ "->" >> K [] || expr ::: args) st
   15.64 +val args_case = args -- expr
   15.65 +val else_case = $$$ "else" -- $$$ "->" |-- expr >> pair ([] : expr list)
   15.66 +
   15.67 +val func =
   15.68 +  let fun cases st = (else_case >> single || args_case ::: cases) st
   15.69 +  in in_braces cases end
   15.70 +
   15.71 +val cex = space |--
   15.72 +  Scan.repeat (name --| $$$ "->" -- (func || expr >> (single o pair [])))
   15.73 +
   15.74 +fun resolve terms ((n, k), cases) =
   15.75 +  (case Symtab.lookup terms n of
   15.76 +    NONE => NONE
   15.77 +  | SOME t => SOME ((t, k), cases))
   15.78 +
   15.79 +fun annotate _ (_, []) = NONE
   15.80 +  | annotate terms (n, [([], c)]) = resolve terms ((n, 0), (c, []))
   15.81 +  | annotate _ (_, [_]) = NONE
   15.82 +  | annotate terms (n, cases as (args, _) :: _) =
   15.83 +      let val (cases', (_, else_case)) = split_last cases
   15.84 +      in resolve terms ((n, length args), (else_case, cases')) end
   15.85 +
   15.86 +fun read_cex terms ls =
   15.87 +  maps (cons "\n" o raw_explode) ls
   15.88 +  |> try (fst o Scan.finite Symbol.stopper cex)
   15.89 +  |> the_default []
   15.90 +  |> map_filter (annotate terms)
   15.91 +
   15.92 +
   15.93 +(* translation into terms *)
   15.94 +
   15.95 +fun max_value vs =
   15.96 +  let
   15.97 +    fun max_val_expr (Value i) = Integer.max i
   15.98 +      | max_val_expr (App (_, es)) = fold max_val_expr es
   15.99 +      | max_val_expr (Array a) = max_val_array a
  15.100 +      | max_val_expr _ = I
  15.101 +
  15.102 +    and max_val_array (Fresh e) = max_val_expr e
  15.103 +      | max_val_array (Store ((a, e1), e2)) =
  15.104 +          max_val_array a #> max_val_expr e1 #> max_val_expr e2
  15.105 +
  15.106 +    fun max_val (_, (ec, cs)) =
  15.107 +      max_val_expr ec #> fold (fn (es, e) => fold max_val_expr (e :: es)) cs
  15.108 +
  15.109 +  in fold max_val vs ~1 end
  15.110 +
  15.111 +fun with_context terms f vs = fst (fold_map f vs (terms, max_value vs + 1))
  15.112 +
  15.113 +fun get_term n T es (cx as (terms, next_val)) =
  15.114 +  (case Symtab.lookup terms n of
  15.115 +    SOME t => ((t, es), cx)
  15.116 +  | NONE =>
  15.117 +      let val t = Var (("skolem", next_val), T)
  15.118 +      in ((t, []), (Symtab.update (n, t) terms, next_val + 1)) end)
  15.119 +
  15.120 +fun trans_expr _ True = pair @{const True}
  15.121 +  | trans_expr _ False = pair @{const False}
  15.122 +  | trans_expr T (Number (i, NONE)) = pair (HOLogic.mk_number T i)
  15.123 +  | trans_expr T (Number (i, SOME j)) =
  15.124 +      pair (Const (@{const_name divide}, [T, T] ---> T) $
  15.125 +        HOLogic.mk_number T i $ HOLogic.mk_number T j)
  15.126 +  | trans_expr T (Value i) = pair (Var (("value", i), T))
  15.127 +  | trans_expr T (Array a) = trans_array T a
  15.128 +  | trans_expr T (App (n, es)) = get_term n T es #-> (fn (t, es') =>
  15.129 +      let val Ts = fst (SMT_Utils.dest_funT (length es') (Term.fastype_of t))
  15.130 +      in
  15.131 +        fold_map (uncurry trans_expr) (Ts ~~ es') #>> Term.list_comb o pair t
  15.132 +      end)
  15.133 +
  15.134 +and trans_array T a =
  15.135 +  let val (dT, rT) = Term.dest_funT T
  15.136 +  in
  15.137 +    (case a of
  15.138 +      Fresh e => trans_expr rT e #>> (fn t => Abs ("x", dT, t))
  15.139 +    | Store ((a', e1), e2) =>
  15.140 +        trans_array T a' ##>> trans_expr dT e1 ##>> trans_expr rT e2 #>>
  15.141 +        (fn ((m, k), v) =>
  15.142 +          Const (@{const_name fun_upd}, [T, dT, rT] ---> T) $ m $ k $ v))
  15.143 +  end
  15.144 +
  15.145 +fun trans_pattern T ([], e) = trans_expr T e #>> pair []
  15.146 +  | trans_pattern T (arg :: args, e) =
  15.147 +      trans_expr (Term.domain_type T) arg ##>>
  15.148 +      trans_pattern (Term.range_type T) (args, e) #>>
  15.149 +      (fn (arg', (args', e')) => (arg' :: args', e'))
  15.150 +
  15.151 +fun mk_fun_upd T U = Const (@{const_name fun_upd}, [T --> U, T, U, T] ---> U)
  15.152 +
  15.153 +fun mk_update ([], u) _ = u
  15.154 +  | mk_update ([t], u) f =
  15.155 +      uncurry mk_fun_upd (Term.dest_funT (Term.fastype_of f)) $ f $ t $ u
  15.156 +  | mk_update (t :: ts, u) f =
  15.157 +      let
  15.158 +        val (dT, rT) = Term.dest_funT (Term.fastype_of f)
  15.159 +        val (dT', rT') = Term.dest_funT rT
  15.160 +      in
  15.161 +        mk_fun_upd dT rT $ f $ t $
  15.162 +          mk_update (ts, u) (absdummy dT' (Const ("_", rT')))
  15.163 +      end
  15.164 +
  15.165 +fun mk_lambda Ts (t, pats) =
  15.166 +  fold_rev absdummy Ts t |> fold mk_update pats
  15.167 +
  15.168 +fun translate ((t, k), (e, cs)) =
  15.169 +  let
  15.170 +    val T = Term.fastype_of t
  15.171 +    val (Us, U) = SMT_Utils.dest_funT k (Term.fastype_of t)
  15.172 +
  15.173 +    fun mk_full_def u' pats =
  15.174 +      pats
  15.175 +      |> filter_out (fn (_, u) => u aconv u')
  15.176 +      |> HOLogic.mk_eq o pair t o mk_lambda Us o pair u'
  15.177 +
  15.178 +    fun mk_eq (us, u) = HOLogic.mk_eq (Term.list_comb (t, us), u)
  15.179 +    fun mk_eqs u' [] = [HOLogic.mk_eq (t, u')]
  15.180 +      | mk_eqs _ pats = map mk_eq pats
  15.181 +  in
  15.182 +    trans_expr U e ##>>
  15.183 +    (if k = 0 then pair [] else fold_map (trans_pattern T) cs) #>>
  15.184 +    (fn (u', pats) => (mk_eqs u' pats, mk_full_def u' pats))
  15.185 +  end
  15.186 +
  15.187 +
  15.188 +(* normalization *)
  15.189 +
  15.190 +fun partition_eqs f =
  15.191 +  let
  15.192 +    fun part t (xs, ts) =
  15.193 +      (case try HOLogic.dest_eq t of
  15.194 +        SOME (l, r) => (case f l r of SOME x => (x::xs, ts) | _ => (xs, t::ts))
  15.195 +      | NONE => (xs, t :: ts))
  15.196 +  in (fn ts => fold part ts ([], [])) end
  15.197 +
  15.198 +fun first_eq pred =
  15.199 +  let
  15.200 +    fun part _ [] = NONE
  15.201 +      | part us (t :: ts) =
  15.202 +          (case try (pred o HOLogic.dest_eq) t of
  15.203 +            SOME (SOME lr) => SOME (lr, fold cons us ts)
  15.204 +          | _ => part (t :: us) ts)
  15.205 +  in (fn ts => part [] ts) end
  15.206 +
  15.207 +fun replace_vars tab =
  15.208 +  let
  15.209 +    fun repl v = the_default v (AList.lookup (op aconv) tab v)
  15.210 +    fun replace (v as Var _) = repl v
  15.211 +      | replace (v as Free _) = repl v
  15.212 +      | replace t = t
  15.213 +  in map (Term.map_aterms replace) end
  15.214 +
  15.215 +fun remove_int_nat_coercions (eqs, defs) =
  15.216 +  let
  15.217 +    fun mk_nat_num t i =
  15.218 +      (case try HOLogic.dest_number i of
  15.219 +        SOME (_, n) => SOME (t, HOLogic.mk_number @{typ nat} n)
  15.220 +      | NONE => NONE)
  15.221 +    fun nat_of (@{const of_nat (int)} $ (t as Var _)) i = mk_nat_num t i
  15.222 +      | nat_of (@{const nat} $ i) (t as Var _) = mk_nat_num t i
  15.223 +      | nat_of _ _ = NONE
  15.224 +    val (nats, eqs') = partition_eqs nat_of eqs
  15.225 +
  15.226 +    fun is_coercion t =
  15.227 +      (case try HOLogic.dest_eq t of
  15.228 +        SOME (@{const of_nat (int)}, _) => true
  15.229 +      | SOME (@{const nat}, _) => true
  15.230 +      | _ => false)
  15.231 +  in pairself (replace_vars nats) (eqs', filter_out is_coercion defs) end
  15.232 +
  15.233 +fun unfold_funapp (eqs, defs) =
  15.234 +  let
  15.235 +    fun unfold_app (Const (@{const_name SMT.fun_app}, _) $ f $ t) = f $ t
  15.236 +      | unfold_app t = t
  15.237 +    fun unfold_eq ((eq as Const (@{const_name HOL.eq}, _)) $ t $ u) =
  15.238 +          eq $ unfold_app t $ u
  15.239 +      | unfold_eq t = t
  15.240 +
  15.241 +    fun is_fun_app t =
  15.242 +      (case try HOLogic.dest_eq t of
  15.243 +        SOME (Const (@{const_name SMT.fun_app}, _), _) => true
  15.244 +      | _ => false)
  15.245 +
  15.246 +  in (map unfold_eq eqs, filter_out is_fun_app defs) end
  15.247 +
  15.248 +val unfold_eqs =
  15.249 +  let
  15.250 +    val is_ground = not o Term.exists_subterm Term.is_Var
  15.251 +    fun is_non_rec (v, t) = not (Term.exists_subterm (equal v) t)
  15.252 +
  15.253 +    fun rewr_var (l as Var _, r) = if is_ground r then SOME (l, r) else NONE
  15.254 +      | rewr_var (r, l as Var _) = if is_ground r then SOME (l, r) else NONE
  15.255 +      | rewr_var _ = NONE
  15.256 +
  15.257 +    fun rewr_free' e = if is_non_rec e then SOME e else NONE
  15.258 +    fun rewr_free (e as (Free _, _)) = rewr_free' e
  15.259 +      | rewr_free (e as (_, Free _)) = rewr_free' (swap e)
  15.260 +      | rewr_free _ = NONE
  15.261 +
  15.262 +    fun is_trivial (Const (@{const_name HOL.eq}, _) $ t $ u) = t aconv u
  15.263 +      | is_trivial _ = false
  15.264 +
  15.265 +    fun replace r = replace_vars [r] #> filter_out is_trivial
  15.266 +
  15.267 +    fun unfold_vars (es, ds) =
  15.268 +      (case first_eq rewr_var es of
  15.269 +        SOME (lr, es') => unfold_vars (pairself (replace lr) (es', ds))
  15.270 +      | NONE => (es, ds))
  15.271 +
  15.272 +    fun unfold_frees ues (es, ds) =
  15.273 +      (case first_eq rewr_free es of
  15.274 +        SOME (lr, es') =>
  15.275 +          pairself (replace lr) (es', ds)
  15.276 +          |> unfold_frees (HOLogic.mk_eq lr :: replace lr ues)
  15.277 +      | NONE => (ues @ es, ds))
  15.278 +
  15.279 +  in unfold_vars #> unfold_frees [] end
  15.280 +
  15.281 +fun swap_free ((eq as Const (@{const_name HOL.eq}, _)) $ t $ (u as Free _)) =
  15.282 +      eq $ u $ t
  15.283 +  | swap_free t = t
  15.284 +
  15.285 +fun frees_for_vars ctxt (eqs, defs) =
  15.286 +  let
  15.287 +    fun fresh_free i T (cx as (frees, ctxt)) =
  15.288 +      (case Inttab.lookup frees i of
  15.289 +        SOME t => (t, cx)
  15.290 +      | NONE =>
  15.291 +          let
  15.292 +            val (n, ctxt') = yield_singleton Variable.variant_fixes "" ctxt
  15.293 +            val t = Free (n, T)
  15.294 +          in (t, (Inttab.update (i, t) frees, ctxt')) end)
  15.295 +
  15.296 +    fun repl_var (Var ((_, i), T)) = fresh_free i T
  15.297 +      | repl_var (t $ u) = repl_var t ##>> repl_var u #>> op $
  15.298 +      | repl_var (Abs (n, T, t)) = repl_var t #>> (fn t' => Abs (n, T, t'))
  15.299 +      | repl_var t = pair t
  15.300 +  in
  15.301 +    (Inttab.empty, ctxt)
  15.302 +    |> fold_map repl_var eqs
  15.303 +    ||>> fold_map repl_var defs
  15.304 +    |> fst
  15.305 +  end
  15.306 +
  15.307 +
  15.308 +(* overall procedure *)
  15.309 +
  15.310 +val is_free_constraint = Term.exists_subterm (fn Free _ => true | _ => false)
  15.311 +
  15.312 +fun is_free_def (Const (@{const_name HOL.eq}, _) $ Free _ $ _) = true
  15.313 +  | is_free_def _ = false
  15.314 +
  15.315 +fun defined tp =
  15.316 +  try (pairself (fst o HOLogic.dest_eq)) tp
  15.317 +  |> the_default false o Option.map (op aconv)
  15.318 +
  15.319 +fun add_free_defs free_cs defs =
  15.320 +  let val (free_defs, defs') = List.partition is_free_def defs
  15.321 +  in (free_cs @ filter_out (member defined free_cs) free_defs, defs') end
  15.322 +
  15.323 +fun is_const_def (Const (@{const_name HOL.eq}, _) $ Const _ $ _) = true
  15.324 +  | is_const_def _ = false
  15.325 +
  15.326 +fun parse_counterex ctxt ({terms, ...} : SMT_Translate.recon) ls =
  15.327 +  read_cex terms ls
  15.328 +  |> with_context terms translate
  15.329 +  |> apfst flat o split_list
  15.330 +  |> remove_int_nat_coercions
  15.331 +  |> unfold_funapp
  15.332 +  |> unfold_eqs
  15.333 +  |>> map swap_free
  15.334 +  |>> filter is_free_constraint
  15.335 +  |-> add_free_defs
  15.336 +  |> frees_for_vars ctxt
  15.337 +  ||> filter is_const_def
  15.338 +
  15.339 +end
  15.340 +
    16.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    16.2 +++ b/src/HOL/Library/SMT/z3_proof_literals.ML	Thu Aug 28 00:40:37 2014 +0200
    16.3 @@ -0,0 +1,361 @@
    16.4 +(*  Title:      HOL/Library/SMT/z3_proof_literals.ML
    16.5 +    Author:     Sascha Boehme, TU Muenchen
    16.6 +
    16.7 +Proof tools related to conjunctions and disjunctions.
    16.8 +*)
    16.9 +
   16.10 +signature Z3_PROOF_LITERALS =
   16.11 +sig
   16.12 +  (*literal table*)
   16.13 +  type littab = thm Termtab.table
   16.14 +  val make_littab: thm list -> littab
   16.15 +  val insert_lit: thm -> littab -> littab
   16.16 +  val delete_lit: thm -> littab -> littab
   16.17 +  val lookup_lit: littab -> term -> thm option
   16.18 +  val get_first_lit: (term -> bool) -> littab -> thm option
   16.19 +
   16.20 +  (*rules*)
   16.21 +  val true_thm: thm
   16.22 +  val rewrite_true: thm
   16.23 +
   16.24 +  (*properties*)
   16.25 +  val is_conj: term -> bool
   16.26 +  val is_disj: term -> bool
   16.27 +  val exists_lit: bool -> (term -> bool) -> term -> bool
   16.28 +  val negate: cterm -> cterm
   16.29 +
   16.30 +  (*proof tools*)
   16.31 +  val explode: bool -> bool -> bool -> term list -> thm -> thm list
   16.32 +  val join: bool -> littab -> term -> thm
   16.33 +  val prove_conj_disj_eq: cterm -> thm
   16.34 +end
   16.35 +
   16.36 +structure Z3_Proof_Literals: Z3_PROOF_LITERALS =
   16.37 +struct
   16.38 +
   16.39 +
   16.40 +
   16.41 +(* literal table *)
   16.42 +
   16.43 +type littab = thm Termtab.table
   16.44 +
   16.45 +fun make_littab thms =
   16.46 +  fold (Termtab.update o `SMT_Utils.prop_of) thms Termtab.empty
   16.47 +
   16.48 +fun insert_lit thm = Termtab.update (`SMT_Utils.prop_of thm)
   16.49 +fun delete_lit thm = Termtab.delete (SMT_Utils.prop_of thm)
   16.50 +fun lookup_lit lits = Termtab.lookup lits
   16.51 +fun get_first_lit f =
   16.52 +  Termtab.get_first (fn (t, thm) => if f t then SOME thm else NONE)
   16.53 +
   16.54 +
   16.55 +
   16.56 +(* rules *)
   16.57 +
   16.58 +val true_thm = @{lemma "~False" by simp}
   16.59 +val rewrite_true = @{lemma "True == ~ False" by simp}
   16.60 +
   16.61 +
   16.62 +
   16.63 +(* properties and term operations *)
   16.64 +
   16.65 +val is_neg = (fn @{const Not} $ _ => true | _ => false)
   16.66 +fun is_neg' f = (fn @{const Not} $ t => f t | _ => false)
   16.67 +val is_dneg = is_neg' is_neg
   16.68 +val is_conj = (fn @{const HOL.conj} $ _ $ _ => true | _ => false)
   16.69 +val is_disj = (fn @{const HOL.disj} $ _ $ _ => true | _ => false)
   16.70 +
   16.71 +fun dest_disj_term' f = (fn
   16.72 +    @{const Not} $ (@{const HOL.disj} $ t $ u) => SOME (f t, f u)
   16.73 +  | _ => NONE)
   16.74 +
   16.75 +val dest_conj_term = (fn @{const HOL.conj} $ t $ u => SOME (t, u) | _ => NONE)
   16.76 +val dest_disj_term =
   16.77 +  dest_disj_term' (fn @{const Not} $ t => t | t => @{const Not} $ t)
   16.78 +
   16.79 +fun exists_lit is_conj P =
   16.80 +  let
   16.81 +    val dest = if is_conj then dest_conj_term else dest_disj_term
   16.82 +    fun exists t = P t orelse
   16.83 +      (case dest t of
   16.84 +        SOME (t1, t2) => exists t1 orelse exists t2
   16.85 +      | NONE => false)
   16.86 +  in exists end
   16.87 +
   16.88 +val negate = Thm.apply (Thm.cterm_of @{theory} @{const Not})
   16.89 +
   16.90 +
   16.91 +
   16.92 +(* proof tools *)
   16.93 +
   16.94 +(** explosion of conjunctions and disjunctions **)
   16.95 +
   16.96 +local
   16.97 +  val precomp = Z3_Proof_Tools.precompose2
   16.98 +
   16.99 +  fun destc ct = Thm.dest_binop (Thm.dest_arg ct)
  16.100 +  val dest_conj1 = precomp destc @{thm conjunct1}
  16.101 +  val dest_conj2 = precomp destc @{thm conjunct2}
  16.102 +  fun dest_conj_rules t =
  16.103 +    dest_conj_term t |> Option.map (K (dest_conj1, dest_conj2))
  16.104 +    
  16.105 +  fun destd f ct = f (Thm.dest_binop (Thm.dest_arg (Thm.dest_arg ct)))
  16.106 +  val dn1 = apfst Thm.dest_arg and dn2 = apsnd Thm.dest_arg
  16.107 +  val dest_disj1 = precomp (destd I) @{lemma "~(P | Q) ==> ~P" by fast}
  16.108 +  val dest_disj2 = precomp (destd dn1) @{lemma "~(~P | Q) ==> P" by fast}
  16.109 +  val dest_disj3 = precomp (destd I) @{lemma "~(P | Q) ==> ~Q" by fast}
  16.110 +  val dest_disj4 = precomp (destd dn2) @{lemma "~(P | ~Q) ==> Q" by fast}
  16.111 +
  16.112 +  fun dest_disj_rules t =
  16.113 +    (case dest_disj_term' is_neg t of
  16.114 +      SOME (true, true) => SOME (dest_disj2, dest_disj4)
  16.115 +    | SOME (true, false) => SOME (dest_disj2, dest_disj3)
  16.116 +    | SOME (false, true) => SOME (dest_disj1, dest_disj4)
  16.117 +    | SOME (false, false) => SOME (dest_disj1, dest_disj3)
  16.118 +    | NONE => NONE)
  16.119 +
  16.120 +  fun destn ct = [Thm.dest_arg (Thm.dest_arg (Thm.dest_arg ct))]
  16.121 +  val dneg_rule = Z3_Proof_Tools.precompose destn @{thm notnotD}
  16.122 +in
  16.123 +
  16.124 +(*
  16.125 +  explode a term into literals and collect all rules to be able to deduce
  16.126 +  particular literals afterwards
  16.127 +*)
  16.128 +fun explode_term is_conj =
  16.129 +  let
  16.130 +    val dest = if is_conj then dest_conj_term else dest_disj_term
  16.131 +    val dest_rules = if is_conj then dest_conj_rules else dest_disj_rules
  16.132 +
  16.133 +    fun add (t, rs) = Termtab.map_default (t, rs)
  16.134 +      (fn rs' => if length rs' < length rs then rs' else rs)
  16.135 +
  16.136 +    fun explode1 rules t =
  16.137 +      (case dest t of
  16.138 +        SOME (t1, t2) =>
  16.139 +          let val (rule1, rule2) = the (dest_rules t)
  16.140 +          in
  16.141 +            explode1 (rule1 :: rules) t1 #>
  16.142 +            explode1 (rule2 :: rules) t2 #>
  16.143 +            add (t, rev rules)
  16.144 +          end
  16.145 +      | NONE => add (t, rev rules))
  16.146 +
  16.147 +    fun explode0 (@{const Not} $ (@{const Not} $ t)) =
  16.148 +          Termtab.make [(t, [dneg_rule])]
  16.149 +      | explode0 t = explode1 [] t Termtab.empty
  16.150 +
  16.151 +  in explode0 end
  16.152 +
  16.153 +(*
  16.154 +  extract a literal by applying previously collected rules
  16.155 +*)
  16.156 +fun extract_lit thm rules = fold Z3_Proof_Tools.compose rules thm
  16.157 +
  16.158 +
  16.159 +(*
  16.160 +  explode a theorem into its literals
  16.161 +*)
  16.162 +fun explode is_conj full keep_intermediate stop_lits =
  16.163 +  let
  16.164 +    val dest_rules = if is_conj then dest_conj_rules else dest_disj_rules
  16.165 +    val tab = fold (Termtab.update o rpair ()) stop_lits Termtab.empty
  16.166 +
  16.167 +    fun explode1 thm =
  16.168 +      if Termtab.defined tab (SMT_Utils.prop_of thm) then cons thm
  16.169 +      else
  16.170 +        (case dest_rules (SMT_Utils.prop_of thm) of
  16.171 +          SOME (rule1, rule2) =>
  16.172 +            explode2 rule1 thm #>
  16.173 +            explode2 rule2 thm #>
  16.174 +            keep_intermediate ? cons thm
  16.175 +        | NONE => cons thm)
  16.176 +
  16.177 +    and explode2 dest_rule thm =
  16.178 +      if full orelse
  16.179 +        exists_lit is_conj (Termtab.defined tab) (SMT_Utils.prop_of thm)
  16.180 +      then explode1 (Z3_Proof_Tools.compose dest_rule thm)
  16.181 +      else cons (Z3_Proof_Tools.compose dest_rule thm)
  16.182 +
  16.183 +    fun explode0 thm =
  16.184 +      if not is_conj andalso is_dneg (SMT_Utils.prop_of thm)
  16.185 +      then [Z3_Proof_Tools.compose dneg_rule thm]
  16.186 +      else explode1 thm []
  16.187 +
  16.188 +  in explode0 end
  16.189 +
  16.190 +end
  16.191 +
  16.192 +
  16.193 +
  16.194 +(** joining of literals to conjunctions or disjunctions **)
  16.195 +
  16.196 +local
  16.197 +  fun on_cprem i f thm = f (Thm.cprem_of thm i)
  16.198 +  fun on_cprop f thm = f (Thm.cprop_of thm)
  16.199 +  fun precomp2 f g thm = (on_cprem 1 f thm, on_cprem 2 g thm, f, g, thm)
  16.200 +  fun comp2 (cv1, cv2, f, g, rule) thm1 thm2 =
  16.201 +    Thm.instantiate ([], [(cv1, on_cprop f thm1), (cv2, on_cprop g thm2)]) rule
  16.202 +    |> Z3_Proof_Tools.discharge thm1 |> Z3_Proof_Tools.discharge thm2
  16.203 +
  16.204 +  fun d1 ct = Thm.dest_arg ct and d2 ct = Thm.dest_arg (Thm.dest_arg ct)
  16.205 +
  16.206 +  val conj_rule = precomp2 d1 d1 @{thm conjI}
  16.207 +  fun comp_conj ((_, thm1), (_, thm2)) = comp2 conj_rule thm1 thm2
  16.208 +
  16.209 +  val disj1 = precomp2 d2 d2 @{lemma "~P ==> ~Q ==> ~(P | Q)" by fast}
  16.210 +  val disj2 = precomp2 d2 d1 @{lemma "~P ==> Q ==> ~(P | ~Q)" by fast}
  16.211 +  val disj3 = precomp2 d1 d2 @{lemma "P ==> ~Q ==> ~(~P | Q)" by fast}
  16.212 +  val disj4 = precomp2 d1 d1 @{lemma "P ==> Q ==> ~(~P | ~Q)" by fast}
  16.213 +
  16.214 +  fun comp_disj ((false, thm1), (false, thm2)) = comp2 disj1 thm1 thm2
  16.215 +    | comp_disj ((false, thm1), (true, thm2)) = comp2 disj2 thm1 thm2
  16.216 +    | comp_disj ((true, thm1), (false, thm2)) = comp2 disj3 thm1 thm2
  16.217 +    | comp_disj ((true, thm1), (true, thm2)) = comp2 disj4 thm1 thm2
  16.218 +
  16.219 +  fun dest_conj (@{const HOL.conj} $ t $ u) = ((false, t), (false, u))
  16.220 +    | dest_conj t = raise TERM ("dest_conj", [t])
  16.221 +
  16.222 +  val neg = (fn @{const Not} $ t => (true, t) | t => (false, @{const Not} $ t))
  16.223 +  fun dest_disj (@{const Not} $ (@{const HOL.disj} $ t $ u)) = (neg t, neg u)
  16.224 +    | dest_disj t = raise TERM ("dest_disj", [t])
  16.225 +
  16.226 +  val precomp = Z3_Proof_Tools.precompose
  16.227 +  val dnegE = precomp (single o d2 o d1) @{thm notnotD}
  16.228 +  val dnegI = precomp (single o d1) @{lemma "P ==> ~~P" by fast}
  16.229 +  fun as_dneg f t = f (@{const Not} $ (@{const Not} $ t))
  16.230 +
  16.231 +  val precomp2 = Z3_Proof_Tools.precompose2
  16.232 +  fun dni f = apsnd f o Thm.dest_binop o f o d1
  16.233 +  val negIffE = precomp2 (dni d1) @{lemma "~(P = (~Q)) ==> Q = P" by fast}
  16.234 +  val negIffI = precomp2 (dni I) @{lemma "P = Q ==> ~(Q = (~P))" by fast}
  16.235 +  val iff_const = @{const HOL.eq (bool)}
  16.236 +  fun as_negIff f (@{const HOL.eq (bool)} $ t $ u) =
  16.237 +        f (@{const Not} $ (iff_const $ u $ (@{const Not} $ t)))
  16.238 +    | as_negIff _ _ = NONE
  16.239 +in
  16.240 +
  16.241 +fun join is_conj littab t =
  16.242 +  let
  16.243 +    val comp = if is_conj then comp_conj else comp_disj
  16.244 +    val dest = if is_conj then dest_conj else dest_disj
  16.245 +
  16.246 +    val lookup = lookup_lit littab
  16.247 +
  16.248 +    fun lookup_rule t =
  16.249 +      (case t of
  16.250 +        @{const Not} $ (@{const Not} $ t) =>
  16.251 +          (Z3_Proof_Tools.compose dnegI, lookup t)
  16.252 +      | @{const Not} $ (@{const HOL.eq (bool)} $ t $ (@{const Not} $ u)) =>
  16.253 +          (Z3_Proof_Tools.compose negIffI, lookup (iff_const $ u $ t))
  16.254 +      | @{const Not} $ ((eq as Const (@{const_name HOL.eq}, _)) $ t $ u) =>
  16.255 +          let fun rewr lit = lit COMP @{thm not_sym}
  16.256 +          in (rewr, lookup (@{const Not} $ (eq $ u $ t))) end
  16.257 +      | _ =>
  16.258 +          (case as_dneg lookup t of
  16.259 +            NONE => (Z3_Proof_Tools.compose negIffE, as_negIff lookup t)
  16.260 +          | x => (Z3_Proof_Tools.compose dnegE, x)))
  16.261 +
  16.262 +    fun join1 (s, t) =
  16.263 +      (case lookup t of
  16.264 +        SOME lit => (s, lit)
  16.265 +      | NONE => 
  16.266 +          (case lookup_rule t of
  16.267 +            (rewrite, SOME lit) => (s, rewrite lit)
  16.268 +          | (_, NONE) => (s, comp (pairself join1 (dest t)))))
  16.269 +
  16.270 +  in snd (join1 (if is_conj then (false, t) else (true, t))) end
  16.271 +
  16.272 +end
  16.273 +
  16.274 +
  16.275 +
  16.276 +(** proving equality of conjunctions or disjunctions **)
  16.277 +
  16.278 +fun iff_intro thm1 thm2 = thm2 COMP (thm1 COMP @{thm iffI})
  16.279 +
  16.280 +local
  16.281 +  val cp1 = @{lemma "(~P) = (~Q) ==> P = Q" by simp}
  16.282 +  val cp2 = @{lemma "(~P) = Q ==> P = (~Q)" by fastforce}
  16.283 +  val cp3 = @{lemma "P = (~Q) ==> (~P) = Q" by simp}
  16.284 +in
  16.285 +fun contrapos1 prove (ct, cu) = prove (negate ct, negate cu) COMP cp1
  16.286 +fun contrapos2 prove (ct, cu) = prove (negate ct, Thm.dest_arg cu) COMP cp2
  16.287 +fun contrapos3 prove (ct, cu) = prove (Thm.dest_arg ct, negate cu) COMP cp3
  16.288 +end
  16.289 +
  16.290 +
  16.291 +local
  16.292 +  val contra_rule = @{lemma "P ==> ~P ==> False" by (rule notE)}
  16.293 +  fun contra_left conj thm =
  16.294 +    let
  16.295 +      val rules = explode_term conj (SMT_Utils.prop_of thm)
  16.296 +      fun contra_lits (t, rs) =
  16.297 +        (case t of
  16.298 +          @{const Not} $ u => Termtab.lookup rules u |> Option.map (pair rs)
  16.299 +        | _ => NONE)
  16.300 +    in
  16.301 +      (case Termtab.lookup rules @{const False} of
  16.302 +        SOME rs => extract_lit thm rs
  16.303 +      | NONE =>
  16.304 +          the (Termtab.get_first contra_lits rules)
  16.305 +          |> pairself (extract_lit thm)
  16.306 +          |> (fn (nlit, plit) => nlit COMP (plit COMP contra_rule)))
  16.307 +    end
  16.308 +
  16.309 +  val falseE_v = Thm.dest_arg (Thm.dest_arg (Thm.cprop_of @{thm FalseE}))
  16.310 +  fun contra_right ct = Thm.instantiate ([], [(falseE_v, ct)]) @{thm FalseE}
  16.311 +in
  16.312 +fun contradict conj ct =
  16.313 +  iff_intro (Z3_Proof_Tools.under_assumption (contra_left conj) ct)
  16.314 +    (contra_right ct)
  16.315 +end
  16.316 +
  16.317 +
  16.318 +local
  16.319 +  fun prove_eq l r (cl, cr) =
  16.320 +    let
  16.321 +      fun explode' is_conj = explode is_conj true (l <> r) []
  16.322 +      fun make_tab is_conj thm = make_littab (true_thm :: explode' is_conj thm)
  16.323 +      fun prove is_conj ct tab = join is_conj tab (Thm.term_of ct)
  16.324 +
  16.325 +      val thm1 = Z3_Proof_Tools.under_assumption (prove r cr o make_tab l) cl
  16.326 +      val thm2 = Z3_Proof_Tools.under_assumption (prove l cl o make_tab r) cr
  16.327 +    in iff_intro thm1 thm2 end
  16.328 +
  16.329 +  datatype conj_disj = CONJ | DISJ | NCON | NDIS
  16.330 +  fun kind_of t =
  16.331 +    if is_conj t then SOME CONJ
  16.332 +    else if is_disj t then SOME DISJ
  16.333 +    else if is_neg' is_conj t then SOME NCON
  16.334 +    else if is_neg' is_disj t then SOME NDIS
  16.335 +    else NONE
  16.336 +in
  16.337 +
  16.338 +fun prove_conj_disj_eq ct =
  16.339 +  let val cp as (cl, cr) = Thm.dest_binop (Thm.dest_arg ct)
  16.340 +  in
  16.341 +    (case (kind_of (Thm.term_of cl), Thm.term_of cr) of
  16.342 +      (SOME CONJ, @{const False}) => contradict true cl
  16.343 +    | (SOME DISJ, @{const Not} $ @{const False}) =>
  16.344 +        contrapos2 (contradict false o fst) cp
  16.345 +    | (kl, _) =>
  16.346 +        (case (kl, kind_of (Thm.term_of cr)) of
  16.347 +          (SOME CONJ, SOME CONJ) => prove_eq true true cp
  16.348 +        | (SOME CONJ, SOME NDIS) => prove_eq true false cp
  16.349 +        | (SOME CONJ, _) => prove_eq true true cp
  16.350 +        | (SOME DISJ, SOME DISJ) => contrapos1 (prove_eq false false) cp
  16.351 +        | (SOME DISJ, SOME NCON) => contrapos2 (prove_eq false true) cp
  16.352 +        | (SOME DISJ, _) => contrapos1 (prove_eq false false) cp
  16.353 +        | (SOME NCON, SOME NCON) => contrapos1 (prove_eq true true) cp
  16.354 +        | (SOME NCON, SOME DISJ) => contrapos3 (prove_eq true false) cp
  16.355 +        | (SOME NCON, NONE) => contrapos3 (prove_eq true false) cp
  16.356 +        | (SOME NDIS, SOME NDIS) => prove_eq false false cp
  16.357 +        | (SOME NDIS, SOME CONJ) => prove_eq false true cp
  16.358 +        | (SOME NDIS, NONE) => prove_eq false true cp
  16.359 +        | _ => raise CTERM ("prove_conj_disj_eq", [ct])))
  16.360 +  end
  16.361 +
  16.362 +end
  16.363 +
  16.364 +end
    17.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    17.2 +++ b/src/HOL/Library/SMT/z3_proof_methods.ML	Thu Aug 28 00:40:37 2014 +0200
    17.3 @@ -0,0 +1,149 @@
    17.4 +(*  Title:      HOL/Library/SMT/z3_proof_methods.ML
    17.5 +    Author:     Sascha Boehme, TU Muenchen
    17.6 +
    17.7 +Proof methods for Z3 proof reconstruction.
    17.8 +*)
    17.9 +
   17.10 +signature Z3_PROOF_METHODS =
   17.11 +sig
   17.12 +  val prove_injectivity: Proof.context -> cterm -> thm
   17.13 +  val prove_ite: Proof.context -> cterm -> thm
   17.14 +end
   17.15 +
   17.16 +structure Z3_Proof_Methods: Z3_PROOF_METHODS =
   17.17 +struct
   17.18 +
   17.19 +
   17.20 +fun apply tac st =
   17.21 +  (case Seq.pull (tac 1 st) of
   17.22 +    NONE => raise THM ("tactic failed", 1, [st])
   17.23 +  | SOME (st', _) => st')
   17.24 +
   17.25 +
   17.26 +
   17.27 +(* if-then-else *)
   17.28 +
   17.29 +val pull_ite = mk_meta_eq
   17.30 +  @{lemma "f (if P then x else y) = (if P then f x else f y)" by simp}
   17.31 +
   17.32 +fun pull_ites_conv ct =
   17.33 +  (Conv.rewr_conv pull_ite then_conv
   17.34 +   Conv.binop_conv (Conv.try_conv pull_ites_conv)) ct
   17.35 +
   17.36 +fun prove_ite ctxt =
   17.37 +  Z3_Proof_Tools.by_tac ctxt (
   17.38 +    CONVERSION (Conv.arg_conv (Conv.arg1_conv pull_ites_conv))
   17.39 +    THEN' rtac @{thm refl})
   17.40 +
   17.41 +
   17.42 +
   17.43 +(* injectivity *)
   17.44 +
   17.45 +local
   17.46 +
   17.47 +val B = @{typ bool}
   17.48 +fun mk_univ T = Const (@{const_name top}, HOLogic.mk_setT T)
   17.49 +fun mk_inj_on T U =
   17.50 +  Const (@{const_name inj_on}, (T --> U) --> HOLogic.mk_setT T --> B)
   17.51 +fun mk_inv_into T U =
   17.52 +  Const (@{const_name inv_into}, [HOLogic.mk_setT T, T --> U, U] ---> T)
   17.53 +
   17.54 +fun mk_inv_of ctxt ct =
   17.55 +  let
   17.56 +    val (dT, rT) = Term.dest_funT (SMT_Utils.typ_of ct)
   17.57 +    val inv = SMT_Utils.certify ctxt (mk_inv_into dT rT)
   17.58 +    val univ = SMT_Utils.certify ctxt (mk_univ dT)
   17.59 +  in Thm.mk_binop inv univ ct end
   17.60 +
   17.61 +fun mk_inj_prop ctxt ct =
   17.62 +  let
   17.63 +    val (dT, rT) = Term.dest_funT (SMT_Utils.typ_of ct)
   17.64 +    val inj = SMT_Utils.certify ctxt (mk_inj_on dT rT)
   17.65 +    val univ = SMT_Utils.certify ctxt (mk_univ dT)
   17.66 +  in SMT_Utils.mk_cprop (Thm.mk_binop inj ct univ) end
   17.67 +
   17.68 +
   17.69 +val disjE = @{lemma "~P | Q ==> P ==> Q" by fast}
   17.70 +
   17.71 +fun prove_inj_prop ctxt def lhs =
   17.72 +  let
   17.73 +    val (ct, ctxt') = SMT_Utils.dest_all_cabs (Thm.rhs_of def) ctxt
   17.74 +    val rule = disjE OF [Object_Logic.rulify ctxt' (Thm.assume lhs)]
   17.75 +  in
   17.76 +    Goal.init (mk_inj_prop ctxt' (Thm.dest_arg ct))
   17.77 +    |> apply (rtac @{thm injI})
   17.78 +    |> apply (Tactic.solve_tac [rule, rule RS @{thm sym}])
   17.79 +    |> Goal.norm_result ctxt' o Goal.finish ctxt'
   17.80 +    |> singleton (Variable.export ctxt' ctxt)
   17.81 +  end
   17.82 +
   17.83 +fun prove_rhs ctxt def lhs =
   17.84 +  Z3_Proof_Tools.by_tac ctxt (
   17.85 +    CONVERSION (Conv.top_sweep_conv (K (Conv.rewr_conv def)) ctxt)
   17.86 +    THEN' REPEAT_ALL_NEW (match_tac @{thms allI})
   17.87 +    THEN' rtac (@{thm inv_f_f} OF [prove_inj_prop ctxt def lhs]))
   17.88 +
   17.89 +
   17.90 +fun expand thm ct =
   17.91 +  let
   17.92 +    val cpat = Thm.dest_arg (Thm.rhs_of thm)
   17.93 +    val (cl, cr) = Thm.dest_binop (Thm.dest_arg (Thm.dest_arg1 ct))
   17.94 +    val thm1 = Thm.instantiate (Thm.match (cpat, cl)) thm
   17.95 +    val thm2 = Thm.instantiate (Thm.match (cpat, cr)) thm
   17.96 +  in Conv.arg_conv (Conv.binop_conv (Conv.rewrs_conv [thm1, thm2])) ct end
   17.97 +
   17.98 +fun prove_lhs ctxt rhs =
   17.99 +  let
  17.100 +    val eq = Thm.symmetric (mk_meta_eq (Object_Logic.rulify ctxt (Thm.assume rhs)))
  17.101 +    val conv = SMT_Utils.binders_conv (K (expand eq)) ctxt
  17.102 +  in
  17.103 +    Z3_Proof_Tools.by_tac ctxt (
  17.104 +      CONVERSION (SMT_Utils.prop_conv conv)
  17.105 +      THEN' Simplifier.simp_tac (put_simpset HOL_ss ctxt))
  17.106 +  end
  17.107 +
  17.108 +
  17.109 +fun mk_inv_def ctxt rhs =
  17.110 +  let
  17.111 +    val (ct, ctxt') =
  17.112 +      SMT_Utils.dest_all_cbinders (SMT_Utils.dest_cprop rhs) ctxt
  17.113 +    val (cl, cv) = Thm.dest_binop ct
  17.114 +    val (cg, (cargs, cf)) = Drule.strip_comb cl ||> split_last
  17.115 +    val cu = fold_rev Thm.lambda cargs (mk_inv_of ctxt' (Thm.lambda cv cf))
  17.116 +  in Thm.assume (SMT_Utils.mk_cequals cg cu) end
  17.117 +
  17.118 +fun prove_inj_eq ctxt ct =
  17.119 +  let
  17.120 +    val (lhs, rhs) =
  17.121 +      pairself SMT_Utils.mk_cprop (Thm.dest_binop (SMT_Utils.dest_cprop ct))
  17.122 +    val lhs_thm = Thm.implies_intr rhs (prove_lhs ctxt rhs lhs)
  17.123 +    val rhs_thm =
  17.124 +      Thm.implies_intr lhs (prove_rhs ctxt (mk_inv_def ctxt rhs) lhs rhs)
  17.125 +  in lhs_thm COMP (rhs_thm COMP @{thm iffI}) end
  17.126 +
  17.127 +
  17.128 +val swap_eq_thm = mk_meta_eq @{thm eq_commute}
  17.129 +val swap_disj_thm = mk_meta_eq @{thm disj_commute}
  17.130 +
  17.131 +fun swap_conv dest eq =
  17.132 +  SMT_Utils.if_true_conv ((op <) o pairself Term.size_of_term o dest)
  17.133 +    (Conv.rewr_conv eq)
  17.134 +
  17.135 +val swap_eq_conv = swap_conv HOLogic.dest_eq swap_eq_thm
  17.136 +val swap_disj_conv = swap_conv SMT_Utils.dest_disj swap_disj_thm
  17.137 +
  17.138 +fun norm_conv ctxt =
  17.139 +  swap_eq_conv then_conv
  17.140 +  Conv.arg1_conv (SMT_Utils.binders_conv (K swap_disj_conv) ctxt) then_conv
  17.141 +  Conv.arg_conv (SMT_Utils.binders_conv (K swap_eq_conv) ctxt)
  17.142 +
  17.143 +in
  17.144 +
  17.145 +fun prove_injectivity ctxt =
  17.146 +  Z3_Proof_Tools.by_tac ctxt (
  17.147 +    CONVERSION (SMT_Utils.prop_conv (norm_conv ctxt))
  17.148 +    THEN' CSUBGOAL (uncurry (rtac o prove_inj_eq ctxt)))
  17.149 +
  17.150 +end
  17.151 +
  17.152 +end
    18.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    18.2 +++ b/src/HOL/Library/SMT/z3_proof_parser.ML	Thu Aug 28 00:40:37 2014 +0200
    18.3 @@ -0,0 +1,445 @@
    18.4 +(*  Title:      HOL/Library/SMT/z3_proof_parser.ML
    18.5 +    Author:     Sascha Boehme, TU Muenchen
    18.6 +
    18.7 +Parser for Z3 proofs.
    18.8 +*)
    18.9 +
   18.10 +signature Z3_PROOF_PARSER =
   18.11 +sig
   18.12 +  (*proof rules*)
   18.13 +  datatype rule = True_Axiom | Asserted | Goal | Modus_Ponens | Reflexivity |
   18.14 +    Symmetry | Transitivity | Transitivity_Star | Monotonicity | Quant_Intro |
   18.15 +    Distributivity | And_Elim | Not_Or_Elim | Rewrite | Rewrite_Star |
   18.16 +    Pull_Quant | Pull_Quant_Star | Push_Quant | Elim_Unused_Vars |
   18.17 +    Dest_Eq_Res | Quant_Inst | Hypothesis | Lemma | Unit_Resolution |
   18.18 +    Iff_True | Iff_False | Commutativity | Def_Axiom | Intro_Def | Apply_Def |
   18.19 +    Iff_Oeq | Nnf_Pos | Nnf_Neg | Nnf_Star | Cnf_Star | Skolemize |
   18.20 +    Modus_Ponens_Oeq | Th_Lemma of string list
   18.21 +  val string_of_rule: rule -> string
   18.22 +
   18.23 +  (*proof parser*)
   18.24 +  datatype proof_step = Proof_Step of {
   18.25 +    rule: rule,
   18.26 +    args: cterm list,
   18.27 +    prems: int list,
   18.28 +    prop: cterm }
   18.29 +  val parse: Proof.context -> typ Symtab.table -> term Symtab.table ->
   18.30 +    string list ->
   18.31 +    (int * cterm) list * (int * proof_step) list * string list * Proof.context
   18.32 +end
   18.33 +
   18.34 +structure Z3_Proof_Parser: Z3_PROOF_PARSER =
   18.35 +struct
   18.36 +
   18.37 +
   18.38 +(* proof rules *)
   18.39 +
   18.40 +datatype rule = True_Axiom | Asserted | Goal | Modus_Ponens | Reflexivity |
   18.41 +  Symmetry | Transitivity | Transitivity_Star | Monotonicity | Quant_Intro |
   18.42 +  Distributivity | And_Elim | Not_Or_Elim | Rewrite | Rewrite_Star |
   18.43 +  Pull_Quant | Pull_Quant_Star | Push_Quant | Elim_Unused_Vars | Dest_Eq_Res |
   18.44 +  Quant_Inst | Hypothesis | Lemma | Unit_Resolution | Iff_True | Iff_False |
   18.45 +  Commutativity | Def_Axiom | Intro_Def | Apply_Def | Iff_Oeq | Nnf_Pos |
   18.46 +  Nnf_Neg | Nnf_Star | Cnf_Star | Skolemize | Modus_Ponens_Oeq |
   18.47 +  Th_Lemma of string list
   18.48 +
   18.49 +val rule_names = Symtab.make [
   18.50 +  ("true-axiom", True_Axiom),
   18.51 +  ("asserted", Asserted),
   18.52 +  ("goal", Goal),
   18.53 +  ("mp", Modus_Ponens),
   18.54 +  ("refl", Reflexivity),
   18.55 +  ("symm", Symmetry),
   18.56 +  ("trans", Transitivity),
   18.57 +  ("trans*", Transitivity_Star),
   18.58 +  ("monotonicity", Monotonicity),
   18.59 +  ("quant-intro", Quant_Intro),
   18.60 +  ("distributivity", Distributivity),
   18.61 +  ("and-elim", And_Elim),
   18.62 +  ("not-or-elim", Not_Or_Elim),
   18.63 +  ("rewrite", Rewrite),
   18.64 +  ("rewrite*", Rewrite_Star),
   18.65 +  ("pull-quant", Pull_Quant),
   18.66 +  ("pull-quant*", Pull_Quant_Star),
   18.67 +  ("push-quant", Push_Quant),
   18.68 +  ("elim-unused", Elim_Unused_Vars),
   18.69 +  ("der", Dest_Eq_Res),
   18.70 +  ("quant-inst", Quant_Inst),
   18.71 +  ("hypothesis", Hypothesis),
   18.72 +  ("lemma", Lemma),
   18.73 +  ("unit-resolution", Unit_Resolution),
   18.74 +  ("iff-true", Iff_True),
   18.75 +  ("iff-false", Iff_False),
   18.76 +  ("commutativity", Commutativity),
   18.77 +  ("def-axiom", Def_Axiom),
   18.78 +  ("intro-def", Intro_Def),
   18.79 +  ("apply-def", Apply_Def),
   18.80 +  ("iff~", Iff_Oeq),
   18.81 +  ("nnf-pos", Nnf_Pos),
   18.82 +  ("nnf-neg", Nnf_Neg),
   18.83 +  ("nnf*", Nnf_Star),
   18.84 +  ("cnf*", Cnf_Star),
   18.85 +  ("sk", Skolemize),
   18.86 +  ("mp~", Modus_Ponens_Oeq),
   18.87 +  ("th-lemma", Th_Lemma [])]
   18.88 +
   18.89 +fun string_of_rule (Th_Lemma args) = space_implode " " ("th-lemma" :: args)
   18.90 +  | string_of_rule r =
   18.91 +      let fun eq_rule (s, r') = if r = r' then SOME s else NONE 
   18.92 +      in the (Symtab.get_first eq_rule rule_names) end
   18.93 +
   18.94 +
   18.95 +
   18.96 +(* certified terms and variables *)
   18.97 +
   18.98 +val (var_prefix, decl_prefix) = ("v", "sk")
   18.99 +(*
  18.100 +  "decl_prefix" is for skolem constants (represented by free variables),
  18.101 +  "var_prefix" is for pseudo-schematic variables (schematic with respect
  18.102 +  to the Z3 proof, but represented by free variables).
  18.103 +
  18.104 +  Both prefixes must be distinct to avoid name interferences.
  18.105 +  More precisely, the naming of pseudo-schematic variables must be
  18.106 +  context-independent modulo the current proof context to be able to
  18.107 +  use fast inference kernel rules during proof reconstruction.
  18.108 +*)
  18.109 +
  18.110 +val maxidx_of = #maxidx o Thm.rep_cterm
  18.111 +
  18.112 +fun mk_inst ctxt vars =
  18.113 +  let
  18.114 +    val max = fold (Integer.max o fst) vars 0
  18.115 +    val ns = fst (Variable.variant_fixes (replicate (max + 1) var_prefix) ctxt)
  18.116 +    fun mk (i, v) =
  18.117 +      (v, SMT_Utils.certify ctxt (Free (nth ns i, #T (Thm.rep_cterm v))))
  18.118 +  in map mk vars end
  18.119 +
  18.120 +fun close ctxt (ct, vars) =
  18.121 +  let
  18.122 +    val inst = mk_inst ctxt vars
  18.123 +    val names = fold (Term.add_free_names o Thm.term_of o snd) inst []
  18.124 +  in (Thm.instantiate_cterm ([], inst) ct, names) end
  18.125 +
  18.126 +
  18.127 +fun mk_bound ctxt (i, T) =
  18.128 +  let val ct = SMT_Utils.certify ctxt (Var ((Name.uu, 0), T))
  18.129 +  in (ct, [(i, ct)]) end
  18.130 +
  18.131 +local
  18.132 +  fun mk_quant1 ctxt q T (ct, vars) =
  18.133 +    let
  18.134 +      val cv =
  18.135 +        (case AList.lookup (op =) vars 0 of
  18.136 +          SOME cv => cv
  18.137 +        | _ => SMT_Utils.certify ctxt (Var ((Name.uu, maxidx_of ct + 1), T)))
  18.138 +      fun dec (i, v) = if i = 0 then NONE else SOME (i-1, v)
  18.139 +      val vars' = map_filter dec vars
  18.140 +    in (Thm.apply (SMT_Utils.instT' cv q) (Thm.lambda cv ct), vars') end
  18.141 +
  18.142 +  fun quant name =
  18.143 +    SMT_Utils.mk_const_pat @{theory} name (SMT_Utils.destT1 o SMT_Utils.destT1)
  18.144 +  val forall = quant @{const_name All}
  18.145 +  val exists = quant @{const_name Ex}
  18.146 +in
  18.147 +
  18.148 +fun mk_quant is_forall ctxt =
  18.149 +  fold_rev (mk_quant1 ctxt (if is_forall then forall else exists))
  18.150 +
  18.151 +end
  18.152 +
  18.153 +local
  18.154 +  fun prep (ct, vars) (maxidx, all_vars) =
  18.155 +    let
  18.156 +      val maxidx' = maxidx + maxidx_of ct + 1
  18.157 +
  18.158 +      fun part (i, cv) =
  18.159 +        (case AList.lookup (op =) all_vars i of
  18.160 +          SOME cu => apfst (if cu aconvc cv then I else cons (cv, cu))
  18.161 +        | NONE =>
  18.162 +            let val cv' = Thm.incr_indexes_cterm maxidx cv
  18.163 +            in apfst (cons (cv, cv')) #> apsnd (cons (i, cv')) end)
  18.164 +
  18.165 +      val (inst, vars') =
  18.166 +        if null vars then ([], vars)
  18.167 +        else fold part vars ([], [])
  18.168 +
  18.169 +    in (Thm.instantiate_cterm ([], inst) ct, (maxidx', vars' @ all_vars)) end
  18.170 +in
  18.171 +fun mk_fun f ts =
  18.172 +  let val (cts, (_, vars)) = fold_map prep ts (0, [])
  18.173 +  in f cts |> Option.map (rpair vars) end
  18.174 +end
  18.175 +
  18.176 +
  18.177 +
  18.178 +(* proof parser *)
  18.179 +
  18.180 +datatype proof_step = Proof_Step of {
  18.181 +  rule: rule,
  18.182 +  args: cterm list,
  18.183 +  prems: int list,
  18.184 +  prop: cterm }
  18.185 +
  18.186 +
  18.187 +(** parser context **)
  18.188 +
  18.189 +val not_false = Thm.cterm_of @{theory} (@{const Not} $ @{const False})
  18.190 +
  18.191 +fun make_context ctxt typs terms =
  18.192 +  let
  18.193 +    val ctxt' = 
  18.194 +      ctxt
  18.195 +      |> Symtab.fold (Variable.declare_typ o snd) typs
  18.196 +      |> Symtab.fold (Variable.declare_term o snd) terms
  18.197 +
  18.198 +    fun cert @{const True} = not_false
  18.199 +      | cert t = SMT_Utils.certify ctxt' t
  18.200 +
  18.201 +  in (typs, Symtab.map (K cert) terms, Inttab.empty, [], [], ctxt') end
  18.202 +
  18.203 +fun fresh_name n (typs, terms, exprs, steps, vars, ctxt) =
  18.204 +  let val (n', ctxt') = yield_singleton Variable.variant_fixes n ctxt
  18.205 +  in (n', (typs, terms, exprs, steps, vars, ctxt')) end
  18.206 +
  18.207 +fun context_of (_, _, _, _, _, ctxt) = ctxt
  18.208 +
  18.209 +fun add_decl (n, T) (cx as (_, terms, _, _, _, _)) =
  18.210 +  (case Symtab.lookup terms n of
  18.211 +    SOME _ => cx
  18.212 +  | NONE => cx |> fresh_name (decl_prefix ^ n)
  18.213 +      |> (fn (m, (typs, terms, exprs, steps, vars, ctxt)) =>
  18.214 +           let
  18.215 +             val upd = Symtab.update (n, SMT_Utils.certify ctxt (Free (m, T)))
  18.216 +           in (typs, upd terms, exprs, steps, vars, ctxt) end))
  18.217 +
  18.218 +fun mk_typ (typs, _, _, _, _, ctxt) (s as Z3_Interface.Sym (n, _)) = 
  18.219 +  (case Z3_Interface.mk_builtin_typ ctxt s of
  18.220 +    SOME T => SOME T
  18.221 +  | NONE => Symtab.lookup typs n)
  18.222 +
  18.223 +fun mk_num (_, _, _, _, _, ctxt) (i, T) =
  18.224 +  mk_fun (K (Z3_Interface.mk_builtin_num ctxt i T)) []
  18.225 +
  18.226 +fun mk_app (_, terms, _, _, _, ctxt) (s as Z3_Interface.Sym (n, _), es) =
  18.227 +  mk_fun (fn cts =>
  18.228 +    (case Z3_Interface.mk_builtin_fun ctxt s cts of
  18.229 +      SOME ct => SOME ct
  18.230 +    | NONE =>
  18.231 +        Symtab.lookup terms n |> Option.map (Drule.list_comb o rpair cts))) es
  18.232 +
  18.233 +fun add_expr k t (typs, terms, exprs, steps, vars, ctxt) =
  18.234 +  (typs, terms, Inttab.update (k, t) exprs, steps, vars, ctxt)
  18.235 +
  18.236 +fun lookup_expr (_, _, exprs, _, _, _) = Inttab.lookup exprs
  18.237 +
  18.238 +fun add_proof_step k ((r, args), prop) cx =
  18.239 +  let
  18.240 +    val (typs, terms, exprs, steps, vars, ctxt) = cx
  18.241 +    val (ct, vs) = close ctxt prop
  18.242 +    fun part (SOME e, _) (cts, ps) = (close ctxt e :: cts, ps)
  18.243 +      | part (NONE, i) (cts, ps) = (cts, i :: ps)
  18.244 +    val (args', prems) = fold (part o `(lookup_expr cx)) args ([], [])
  18.245 +    val (cts, vss) = split_list args'
  18.246 +    val step = Proof_Step {rule=r, args=rev cts, prems=rev prems,
  18.247 +      prop = SMT_Utils.mk_cprop ct}
  18.248 +    val vars' = fold (union (op =)) (vs :: vss) vars
  18.249 +  in (typs, terms, exprs, (k, step) :: steps, vars', ctxt) end
  18.250 +
  18.251 +fun finish (_, _, _, steps, vars, ctxt) =
  18.252 +  let
  18.253 +    fun coll (p as (k, Proof_Step {prems, rule, prop, ...})) (ars, ps, ids) =
  18.254 +      (case rule of
  18.255 +        Asserted => ((k, prop) :: ars, ps, ids)
  18.256 +      | Goal => ((k, prop) :: ars, ps, ids)
  18.257 +      | _ =>
  18.258 +          if Inttab.defined ids k then
  18.259 +            (ars, p :: ps, fold (Inttab.update o rpair ()) prems ids)
  18.260 +          else (ars, ps, ids))
  18.261 +
  18.262 +    val (ars, steps', _) = fold coll steps ([], [], Inttab.make [(~1, ())])
  18.263 +  in (ars, steps', vars, ctxt) end
  18.264 +
  18.265 +
  18.266 +(** core parser **)
  18.267 +
  18.268 +fun parse_exn line_no msg = raise SMT_Failure.SMT (SMT_Failure.Other_Failure
  18.269 +  ("Z3 proof parser (line " ^ string_of_int line_no ^ "): " ^ msg))
  18.270 +
  18.271 +fun scan_exn msg ((line_no, _), _) = parse_exn line_no msg
  18.272 +
  18.273 +fun with_info f cx =
  18.274 +  (case f ((NONE, 1), cx) of
  18.275 +    ((SOME _, _), cx') => cx'
  18.276 +  | ((_, line_no), _) => parse_exn line_no "bad proof")
  18.277 +
  18.278 +fun parse_line _ _ (st as ((SOME _, _), _)) = st
  18.279 +  | parse_line scan line ((_, line_no), cx) =
  18.280 +      let val st = ((line_no, cx), raw_explode line)
  18.281 +      in
  18.282 +        (case Scan.catch (Scan.finite' Symbol.stopper (Scan.option scan)) st of
  18.283 +          (SOME r, ((_, cx'), _)) => ((r, line_no+1), cx')
  18.284 +        | (NONE, _) => parse_exn line_no ("bad proof line: " ^ quote line))
  18.285 +      end
  18.286 +
  18.287 +fun with_context f x ((line_no, cx), st) =
  18.288 +  let val (y, cx') = f x cx
  18.289 +  in (y, ((line_no, cx'), st)) end
  18.290 +  
  18.291 +
  18.292 +fun lookup_context f x (st as ((_, cx), _)) = (f cx x, st)
  18.293 +
  18.294 +
  18.295 +(** parser combinators and parsers for basic entities **)
  18.296 +
  18.297 +fun $$ s = Scan.lift (Scan.$$ s)
  18.298 +fun this s = Scan.lift (Scan.this_string s)
  18.299 +val is_blank = Symbol.is_ascii_blank
  18.300 +fun blank st = Scan.lift (Scan.many1 is_blank) st
  18.301 +fun sep scan = blank |-- scan
  18.302 +fun seps scan = Scan.repeat (sep scan)
  18.303 +fun seps1 scan = Scan.repeat1 (sep scan)
  18.304 +fun seps_by scan_sep scan = scan ::: Scan.repeat (scan_sep |-- scan)
  18.305 +
  18.306 +val lpar = "(" and rpar = ")"
  18.307 +val lbra = "[" and rbra = "]"
  18.308 +fun par scan = $$ lpar |-- scan --| $$ rpar
  18.309 +fun bra scan = $$ lbra |-- scan --| $$ rbra
  18.310 +
  18.311 +val digit = (fn
  18.312 +  "0" => SOME 0 | "1" => SOME 1 | "2" => SOME 2 | "3" => SOME 3 |
  18.313 +  "4" => SOME 4 | "5" => SOME 5 | "6" => SOME 6 | "7" => SOME 7 |
  18.314 +  "8" => SOME 8 | "9" => SOME 9 | _ => NONE)
  18.315 +
  18.316 +fun digits st = (Scan.lift (Scan.many1 Symbol.is_ascii_digit) >> implode) st
  18.317 +
  18.318 +fun nat_num st = (Scan.lift (Scan.repeat1 (Scan.some digit)) >> (fn ds =>
  18.319 +  fold (fn d => fn i => i * 10 + d) ds 0)) st
  18.320 +
  18.321 +fun int_num st = (Scan.optional ($$ "-" >> K (fn i => ~i)) I :|--
  18.322 +  (fn sign => nat_num >> sign)) st
  18.323 +
  18.324 +val is_char = Symbol.is_ascii_letter orf Symbol.is_ascii_digit orf
  18.325 +  member (op =) (raw_explode "_+*-/%~=<>$&|?!.@^#")
  18.326 +
  18.327 +fun name st = (Scan.lift (Scan.many1 is_char) >> implode) st
  18.328 +
  18.329 +fun sym st = (name --
  18.330 +  Scan.optional (bra (seps_by ($$ ":") sym)) [] >> Z3_Interface.Sym) st
  18.331 +
  18.332 +fun id st = ($$ "#" |-- nat_num) st
  18.333 +
  18.334 +
  18.335 +(** parsers for various parts of Z3 proofs **)
  18.336 +
  18.337 +fun sort st = Scan.first [
  18.338 +  this "array" |-- bra (sort --| $$ ":" -- sort) >> (op -->),
  18.339 +  par (this "->" |-- seps1 sort) >> ((op --->) o split_last),
  18.340 +  sym :|-- (fn s as Z3_Interface.Sym (n, _) => lookup_context mk_typ s :|-- (fn
  18.341 +    SOME T => Scan.succeed T
  18.342 +  | NONE => scan_exn ("unknown sort: " ^ quote n)))] st
  18.343 +
  18.344 +fun bound st = (par (this ":var" |-- sep nat_num -- sep sort) :|--
  18.345 +  lookup_context (mk_bound o context_of)) st
  18.346 +
  18.347 +fun numb (n as (i, _)) = lookup_context mk_num n :|-- (fn
  18.348 +    SOME n' => Scan.succeed n'
  18.349 +  | NONE => scan_exn ("unknown number: " ^ quote (string_of_int i)))
  18.350 +
  18.351 +fun appl (app as (Z3_Interface.Sym (n, _), _)) =
  18.352 +  lookup_context mk_app app :|-- (fn 
  18.353 +      SOME app' => Scan.succeed app'
  18.354 +    | NONE => scan_exn ("unknown function symbol: " ^ quote n))
  18.355 +
  18.356 +fun bv_size st = (digits >> (fn sz =>
  18.357 +  Z3_Interface.Sym ("bv", [Z3_Interface.Sym (sz, [])]))) st
  18.358 +
  18.359 +fun bv_number_sort st = (bv_size :|-- lookup_context mk_typ :|-- (fn
  18.360 +    SOME cT => Scan.succeed cT
  18.361 +  | NONE => scan_exn ("unknown sort: " ^ quote "bv"))) st
  18.362 +
  18.363 +fun bv_number st =
  18.364 +  (this "bv" |-- bra (nat_num --| $$ ":" -- bv_number_sort) :|-- numb) st
  18.365 +
  18.366 +fun frac_number st = (
  18.367 +  int_num --| $$ "/" -- int_num --| this "::" -- sort :|-- (fn ((i, j), T) =>
  18.368 +    numb (i, T) -- numb (j, T) :|-- (fn (n, m) =>
  18.369 +      appl (Z3_Interface.Sym ("/", []), [n, m])))) st
  18.370 +
  18.371 +fun plain_number st = (int_num --| this "::" -- sort :|-- numb) st
  18.372 +
  18.373 +fun number st = Scan.first [bv_number, frac_number, plain_number] st
  18.374 +
  18.375 +fun constant st = ((sym >> rpair []) :|-- appl) st
  18.376 +
  18.377 +fun expr_id st = (id :|-- (fn i => lookup_context lookup_expr i :|-- (fn
  18.378 +    SOME e => Scan.succeed e
  18.379 +  | NONE => scan_exn ("unknown term id: " ^ quote (string_of_int i))))) st
  18.380 +
  18.381 +fun arg st = Scan.first [expr_id, number, constant] st
  18.382 +
  18.383 +fun application st = par ((sym -- Scan.repeat1 (sep arg)) :|-- appl) st
  18.384 +
  18.385 +fun variables st = par (this "vars" |-- seps1 (par (name |-- sep sort))) st
  18.386 +
  18.387 +fun pats st = seps (par ((this ":pat" || this ":nopat") |-- seps1 id)) st
  18.388 +
  18.389 +val ctrue = Thm.cterm_of @{theory} @{const True}
  18.390 +
  18.391 +fun pattern st = par (this "pattern" |-- Scan.repeat1 (sep arg) >>
  18.392 +  (the o mk_fun (K (SOME ctrue)))) st
  18.393 +
  18.394 +fun quant_kind st = st |> (
  18.395 +  this "forall" >> K (mk_quant true o context_of) ||
  18.396 +  this "exists" >> K (mk_quant false o context_of))
  18.397 +
  18.398 +fun quantifier st =
  18.399 +  (par (quant_kind -- sep variables --| pats -- sep arg) :|--
  18.400 +     lookup_context (fn cx => fn ((mk_q, Ts), body) => mk_q cx Ts body)) st
  18.401 +
  18.402 +fun expr k =
  18.403 +  Scan.first [bound, quantifier, pattern, application, number, constant] :|--
  18.404 +  with_context (pair NONE oo add_expr k)
  18.405 +
  18.406 +val rule_arg = id
  18.407 +  (* if this is modified, then 'th_lemma_arg' needs reviewing *)
  18.408 +
  18.409 +fun th_lemma_arg st = Scan.unless (sep rule_arg >> K "" || $$ rbra) (sep name) st
  18.410 +
  18.411 +fun rule_name st = ((name >> `(Symtab.lookup rule_names)) :|-- (fn 
  18.412 +    (SOME (Th_Lemma _), _) => Scan.repeat th_lemma_arg >> Th_Lemma
  18.413 +  | (SOME r, _) => Scan.succeed r
  18.414 +  | (NONE, n) => scan_exn ("unknown proof rule: " ^ quote n))) st
  18.415 +
  18.416 +fun rule f k =
  18.417 +  bra (rule_name -- seps id) --| $$ ":" -- sep arg #->
  18.418 +  with_context (pair (f k) oo add_proof_step k)
  18.419 +
  18.420 +fun decl st = (this "decl" |-- sep name --| sep (this "::") -- sep sort :|--
  18.421 +  with_context (pair NONE oo add_decl)) st
  18.422 +
  18.423 +fun def st = (id --| sep (this ":=")) st
  18.424 +
  18.425 +fun node st = st |> (
  18.426 +  decl ||
  18.427 +  def :|-- (fn k => sep (expr k) || sep (rule (K NONE) k)) ||
  18.428 +  rule SOME ~1)
  18.429 +
  18.430 +
  18.431 +(** overall parser **)
  18.432 +
  18.433 +(*
  18.434 +  Currently, terms are parsed bottom-up (i.e., along with parsing the proof
  18.435 +  text line by line), but proofs are reconstructed top-down (i.e. by an
  18.436 +  in-order top-down traversal of the proof tree/graph).  The latter approach
  18.437 +  was taken because some proof texts comprise irrelevant proof steps which
  18.438 +  will thus not be reconstructed.  This approach might also be beneficial
  18.439 +  for constructing terms, but it would also increase the complexity of the
  18.440 +  (otherwise rather modular) code.
  18.441 +*)
  18.442 +
  18.443 +fun parse ctxt typs terms proof_text =
  18.444 +  make_context ctxt typs terms
  18.445 +  |> with_info (fold (parse_line node) proof_text)
  18.446 +  |> finish
  18.447 +
  18.448 +end
    19.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    19.2 +++ b/src/HOL/Library/SMT/z3_proof_reconstruction.ML	Thu Aug 28 00:40:37 2014 +0200
    19.3 @@ -0,0 +1,888 @@
    19.4 +(*  Title:      HOL/Library/SMT/z3_proof_reconstruction.ML
    19.5 +    Author:     Sascha Boehme, TU Muenchen
    19.6 +
    19.7 +Proof reconstruction for proofs found by Z3.
    19.8 +*)
    19.9 +
   19.10 +signature Z3_PROOF_RECONSTRUCTION =
   19.11 +sig
   19.12 +  val add_z3_rule: thm -> Context.generic -> Context.generic
   19.13 +  val reconstruct: Proof.context -> SMT_Translate.recon -> string list -> int list * thm
   19.14 +end
   19.15 +
   19.16 +structure Z3_Proof_Reconstruction: Z3_PROOF_RECONSTRUCTION =
   19.17 +struct
   19.18 +
   19.19 +
   19.20 +fun z3_exn msg = raise SMT_Failure.SMT (SMT_Failure.Other_Failure
   19.21 +  ("Z3 proof reconstruction: " ^ msg))
   19.22 +
   19.23 +
   19.24 +
   19.25 +(* net of schematic rules *)
   19.26 +
   19.27 +local
   19.28 +  val description = "declaration of Z3 proof rules"
   19.29 +
   19.30 +  val eq = Thm.eq_thm
   19.31 +
   19.32 +  structure Z3_Rules = Generic_Data
   19.33 +  (
   19.34 +    type T = thm Net.net
   19.35 +    val empty = Net.empty
   19.36 +    val extend = I
   19.37 +    val merge = Net.merge eq
   19.38 +  )
   19.39 +
   19.40 +  fun prep context =
   19.41 +    `Thm.prop_of o rewrite_rule (Context.proof_of context) [Z3_Proof_Literals.rewrite_true]
   19.42 +
   19.43 +  fun ins thm context =
   19.44 +    context |> Z3_Rules.map (fn net => Net.insert_term eq (prep context thm) net handle Net.INSERT => net)
   19.45 +  fun rem thm context =
   19.46 +    context |> Z3_Rules.map (fn net => Net.delete_term eq (prep context thm) net handle Net.DELETE => net)
   19.47 +
   19.48 +  val add = Thm.declaration_attribute ins
   19.49 +  val del = Thm.declaration_attribute rem
   19.50 +in
   19.51 +
   19.52 +val add_z3_rule = ins
   19.53 +
   19.54 +fun by_schematic_rule ctxt ct =
   19.55 +  the (Z3_Proof_Tools.net_instance (Z3_Rules.get (Context.Proof ctxt)) ct)
   19.56 +
   19.57 +val _ = Theory.setup
   19.58 + (Attrib.setup @{binding z3_rule} (Attrib.add_del add del) description #>
   19.59 +  Global_Theory.add_thms_dynamic (@{binding z3_rule}, Net.content o Z3_Rules.get))
   19.60 +
   19.61 +end
   19.62 +
   19.63 +
   19.64 +
   19.65 +(* proof tools *)
   19.66 +
   19.67 +fun named ctxt name prover ct =
   19.68 +  let val _ = SMT_Config.trace_msg ctxt I ("Z3: trying " ^ name ^ " ...")
   19.69 +  in prover ct end
   19.70 +
   19.71 +fun NAMED ctxt name tac i st =
   19.72 +  let val _ = SMT_Config.trace_msg ctxt I ("Z3: trying " ^ name ^ " ...")
   19.73 +  in tac i st end
   19.74 +
   19.75 +fun pretty_goal ctxt thms t =
   19.76 +  [Pretty.block [Pretty.str "proposition: ", Syntax.pretty_term ctxt t]]
   19.77 +  |> not (null thms) ? cons (Pretty.big_list "assumptions:"
   19.78 +       (map (Display.pretty_thm ctxt) thms))
   19.79 +
   19.80 +fun try_apply ctxt thms =
   19.81 +  let
   19.82 +    fun try_apply_err ct = Pretty.string_of (Pretty.chunks [
   19.83 +      Pretty.big_list ("Z3 found a proof," ^
   19.84 +        " but proof reconstruction failed at the following subgoal:")
   19.85 +        (pretty_goal ctxt thms (Thm.term_of ct)),
   19.86 +      Pretty.str ("Declaring a rule as [z3_rule] might solve this problem.")])
   19.87 +
   19.88 +    fun apply [] ct = error (try_apply_err ct)
   19.89 +      | apply (prover :: provers) ct =
   19.90 +          (case try prover ct of
   19.91 +            SOME thm => (SMT_Config.trace_msg ctxt I "Z3: succeeded"; thm)
   19.92 +          | NONE => apply provers ct)
   19.93 +
   19.94 +    fun schematic_label full = "schematic rules" |> full ? suffix " (full)"
   19.95 +    fun schematic ctxt full ct =
   19.96 +      ct
   19.97 +      |> full ? fold_rev (curry Drule.mk_implies o Thm.cprop_of) thms
   19.98 +      |> named ctxt (schematic_label full) (by_schematic_rule ctxt)
   19.99 +      |> fold Thm.elim_implies thms
  19.100 +
  19.101 +  in apply o cons (schematic ctxt false) o cons (schematic ctxt true) end
  19.102 +
  19.103 +local
  19.104 +  val rewr_if =
  19.105 +    @{lemma "(if P then Q1 else Q2) = ((P --> Q1) & (~P --> Q2))" by simp}
  19.106 +in
  19.107 +
  19.108 +fun HOL_fast_tac ctxt =
  19.109 +  Classical.fast_tac (put_claset HOL_cs ctxt)
  19.110 +
  19.111 +fun simp_fast_tac ctxt =
  19.112 +  Simplifier.simp_tac (put_simpset HOL_ss ctxt addsimps [rewr_if])
  19.113 +  THEN_ALL_NEW HOL_fast_tac ctxt
  19.114 +
  19.115 +end
  19.116 +
  19.117 +
  19.118 +
  19.119 +(* theorems and proofs *)
  19.120 +
  19.121 +(** theorem incarnations **)
  19.122 +
  19.123 +datatype theorem =
  19.124 +  Thm of thm | (* theorem without special features *)
  19.125 +  MetaEq of thm | (* meta equality "t == s" *)
  19.126 +  Literals of thm * Z3_Proof_Literals.littab
  19.127 +    (* "P1 & ... & Pn" and table of all literals P1, ..., Pn *)
  19.128 +
  19.129 +fun thm_of (Thm thm) = thm
  19.130 +  | thm_of (MetaEq thm) = thm COMP @{thm meta_eq_to_obj_eq}
  19.131 +  | thm_of (Literals (thm, _)) = thm
  19.132 +
  19.133 +fun meta_eq_of (MetaEq thm) = thm
  19.134 +  | meta_eq_of p = mk_meta_eq (thm_of p)
  19.135 +
  19.136 +fun literals_of (Literals (_, lits)) = lits
  19.137 +  | literals_of p = Z3_Proof_Literals.make_littab [thm_of p]
  19.138 +
  19.139 +
  19.140 +
  19.141 +(** core proof rules **)
  19.142 +
  19.143 +(* assumption *)
  19.144 +
  19.145 +local
  19.146 +  val remove_trigger = mk_meta_eq @{thm SMT.trigger_def}
  19.147 +  val remove_weight = mk_meta_eq @{thm SMT.weight_def}
  19.148 +  val remove_fun_app = mk_meta_eq @{thm SMT.fun_app_def}
  19.149 +
  19.150 +  fun rewrite_conv _ [] = Conv.all_conv
  19.151 +    | rewrite_conv ctxt eqs = Simplifier.full_rewrite (empty_simpset ctxt addsimps eqs)
  19.152 +
  19.153 +  val prep_rules = [@{thm Let_def}, remove_trigger, remove_weight,
  19.154 +    remove_fun_app, Z3_Proof_Literals.rewrite_true]
  19.155 +
  19.156 +  fun rewrite _ [] = I
  19.157 +    | rewrite ctxt eqs = Conv.fconv_rule (rewrite_conv ctxt eqs)
  19.158 +
  19.159 +  fun lookup_assm assms_net ct =
  19.160 +    Z3_Proof_Tools.net_instances assms_net ct
  19.161 +    |> map (fn ithm as (_, thm) => (ithm, Thm.cprop_of thm aconvc ct))
  19.162 +in
  19.163 +
  19.164 +fun add_asserted outer_ctxt rewrite_rules assms asserted ctxt =
  19.165 +  let
  19.166 +    val eqs = map (rewrite ctxt [Z3_Proof_Literals.rewrite_true]) rewrite_rules
  19.167 +    val eqs' = union Thm.eq_thm eqs prep_rules
  19.168 +
  19.169 +    val assms_net =
  19.170 +      assms
  19.171 +      |> map (apsnd (rewrite ctxt eqs'))
  19.172 +      |> map (apsnd (Conv.fconv_rule Thm.eta_conversion))
  19.173 +      |> Z3_Proof_Tools.thm_net_of snd 
  19.174 +
  19.175 +    fun revert_conv ctxt = rewrite_conv ctxt eqs' then_conv Thm.eta_conversion
  19.176 +
  19.177 +    fun assume thm ctxt =
  19.178 +      let
  19.179 +        val ct = Thm.cprem_of thm 1
  19.180 +        val (thm', ctxt') = yield_singleton Assumption.add_assumes ct ctxt
  19.181 +      in (Thm.implies_elim thm thm', ctxt') end
  19.182 +
  19.183 +    fun add1 idx thm1 ((i, th), exact) ((is, thms), (ctxt, ptab)) =
  19.184 +      let
  19.185 +        val (thm, ctxt') =
  19.186 +          if exact then (Thm.implies_elim thm1 th, ctxt)
  19.187 +          else assume thm1 ctxt
  19.188 +        val thms' = if exact then thms else th :: thms
  19.189 +      in 
  19.190 +        ((insert (op =) i is, thms'),
  19.191 +          (ctxt', Inttab.update (idx, Thm thm) ptab))
  19.192 +      end
  19.193 +
  19.194 +    fun add (idx, ct) (cx as ((is, thms), (ctxt, ptab))) =
  19.195 +      let
  19.196 +        val thm1 = 
  19.197 +          Thm.trivial ct
  19.198 +          |> Conv.fconv_rule (Conv.arg1_conv (revert_conv outer_ctxt))
  19.199 +        val thm2 = singleton (Variable.export ctxt outer_ctxt) thm1
  19.200 +      in
  19.201 +        (case lookup_assm assms_net (Thm.cprem_of thm2 1) of
  19.202 +          [] =>
  19.203 +            let val (thm, ctxt') = assume thm1 ctxt
  19.204 +            in ((is, thms), (ctxt', Inttab.update (idx, Thm thm) ptab)) end
  19.205 +        | ithms => fold (add1 idx thm1) ithms cx)
  19.206 +      end
  19.207 +  in fold add asserted (([], []), (ctxt, Inttab.empty)) end
  19.208 +
  19.209 +end
  19.210 +
  19.211 +
  19.212 +(* P = Q ==> P ==> Q   or   P --> Q ==> P ==> Q *)
  19.213 +local
  19.214 +  val precomp = Z3_Proof_Tools.precompose2
  19.215 +  val comp = Z3_Proof_Tools.compose
  19.216 +
  19.217 +  val meta_iffD1 = @{lemma "P == Q ==> P ==> (Q::bool)" by simp}
  19.218 +  val meta_iffD1_c = precomp Thm.dest_binop meta_iffD1
  19.219 +
  19.220 +  val iffD1_c = precomp (Thm.dest_binop o Thm.dest_arg) @{thm iffD1}
  19.221 +  val mp_c = precomp (Thm.dest_binop o Thm.dest_arg) @{thm mp}
  19.222 +in
  19.223 +fun mp (MetaEq thm) p = Thm (Thm.implies_elim (comp meta_iffD1_c thm) p)
  19.224 +  | mp p_q p = 
  19.225 +      let
  19.226 +        val pq = thm_of p_q
  19.227 +        val thm = comp iffD1_c pq handle THM _ => comp mp_c pq
  19.228 +      in Thm (Thm.implies_elim thm p) end
  19.229 +end
  19.230 +
  19.231 +
  19.232 +(* and_elim:     P1 & ... & Pn ==> Pi *)
  19.233 +(* not_or_elim:  ~(P1 | ... | Pn) ==> ~Pi *)
  19.234 +local
  19.235 +  fun is_sublit conj t = Z3_Proof_Literals.exists_lit conj (fn u => u aconv t)
  19.236 +
  19.237 +  fun derive conj t lits idx ptab =
  19.238 +    let
  19.239 +      val lit = the (Z3_Proof_Literals.get_first_lit (is_sublit conj t) lits)
  19.240 +      val ls = Z3_Proof_Literals.explode conj false false [t] lit
  19.241 +      val lits' = fold Z3_Proof_Literals.insert_lit ls
  19.242 +        (Z3_Proof_Literals.delete_lit lit lits)
  19.243 +
  19.244 +      fun upd thm = Literals (thm_of thm, lits')
  19.245 +      val ptab' = Inttab.map_entry idx upd ptab
  19.246 +    in (the (Z3_Proof_Literals.lookup_lit lits' t), ptab') end
  19.247 +
  19.248 +  fun lit_elim conj (p, idx) ct ptab =
  19.249 +    let val lits = literals_of p
  19.250 +    in
  19.251 +      (case Z3_Proof_Literals.lookup_lit lits (SMT_Utils.term_of ct) of
  19.252 +        SOME lit => (Thm lit, ptab)
  19.253 +      | NONE => apfst Thm (derive conj (SMT_Utils.term_of ct) lits idx ptab))
  19.254 +    end
  19.255 +in
  19.256 +val and_elim = lit_elim true
  19.257 +val not_or_elim = lit_elim false
  19.258 +end
  19.259 +
  19.260 +
  19.261 +(* P1, ..., Pn |- False ==> |- ~P1 | ... | ~Pn *)
  19.262 +local
  19.263 +  fun step lit thm =
  19.264 +    Thm.implies_elim (Thm.implies_intr (Thm.cprop_of lit) thm) lit
  19.265 +  val explode_disj = Z3_Proof_Literals.explode false false false
  19.266 +  fun intro hyps thm th = fold step (explode_disj hyps th) thm
  19.267 +
  19.268 +  fun dest_ccontr ct = [Thm.dest_arg (Thm.dest_arg (Thm.dest_arg1 ct))]
  19.269 +  val ccontr = Z3_Proof_Tools.precompose dest_ccontr @{thm ccontr}
  19.270 +in
  19.271 +fun lemma thm ct =
  19.272 +  let
  19.273 +    val cu = Z3_Proof_Literals.negate (Thm.dest_arg ct)
  19.274 +    val hyps = map_filter (try HOLogic.dest_Trueprop) (Thm.hyps_of thm)
  19.275 +    val th = Z3_Proof_Tools.under_assumption (intro hyps thm) cu
  19.276 +  in Thm (Z3_Proof_Tools.compose ccontr th) end
  19.277 +end
  19.278 +
  19.279 +
  19.280 +(* \/{P1, ..., Pn, Q1, ..., Qn}, ~P1, ..., ~Pn ==> \/{Q1, ..., Qn} *)
  19.281 +local
  19.282 +  val explode_disj = Z3_Proof_Literals.explode false true false
  19.283 +  val join_disj = Z3_Proof_Literals.join false
  19.284 +  fun unit thm thms th =
  19.285 +    let
  19.286 +      val t = @{const Not} $ SMT_Utils.prop_of thm
  19.287 +      val ts = map SMT_Utils.prop_of thms
  19.288 +    in
  19.289 +      join_disj (Z3_Proof_Literals.make_littab (thms @ explode_disj ts th)) t
  19.290 +    end
  19.291 +
  19.292 +  fun dest_arg2 ct = Thm.dest_arg (Thm.dest_arg ct)
  19.293 +  fun dest ct = pairself dest_arg2 (Thm.dest_binop ct)
  19.294 +  val contrapos =
  19.295 +    Z3_Proof_Tools.precompose2 dest @{lemma "(~P ==> ~Q) ==> Q ==> P" by fast}
  19.296 +in
  19.297 +fun unit_resolution thm thms ct =
  19.298 +  Z3_Proof_Literals.negate (Thm.dest_arg ct)
  19.299 +  |> Z3_Proof_Tools.under_assumption (unit thm thms)
  19.300 +  |> Thm o Z3_Proof_Tools.discharge thm o Z3_Proof_Tools.compose contrapos
  19.301 +end
  19.302 +
  19.303 +
  19.304 +(* P ==> P == True   or   P ==> P == False *)
  19.305 +local
  19.306 +  val iff1 = @{lemma "P ==> P == (~ False)" by simp}
  19.307 +  val iff2 = @{lemma "~P ==> P == False" by simp}
  19.308 +in
  19.309 +fun iff_true thm = MetaEq (thm COMP iff1)
  19.310 +fun iff_false thm = MetaEq (thm COMP iff2)
  19.311 +end
  19.312 +
  19.313 +
  19.314 +(* distributivity of | over & *)
  19.315 +fun distributivity ctxt = Thm o try_apply ctxt [] [
  19.316 +  named ctxt "fast" (Z3_Proof_Tools.by_tac ctxt (HOL_fast_tac ctxt))]
  19.317 +    (* FIXME: not very well tested *)
  19.318 +
  19.319 +
  19.320 +(* Tseitin-like axioms *)
  19.321 +local
  19.322 +  val disjI1 = @{lemma "(P ==> Q) ==> ~P | Q" by fast}
  19.323 +  val disjI2 = @{lemma "(~P ==> Q) ==> P | Q" by fast}
  19.324 +  val disjI3 = @{lemma "(~Q ==> P) ==> P | Q" by fast}
  19.325 +  val disjI4 = @{lemma "(Q ==> P) ==> P | ~Q" by fast}
  19.326 +
  19.327 +  fun prove' conj1 conj2 ct2 thm =
  19.328 +    let
  19.329 +      val littab =
  19.330 +        Z3_Proof_Literals.explode conj1 true (conj1 <> conj2) [] thm
  19.331 +        |> cons Z3_Proof_Literals.true_thm
  19.332 +        |> Z3_Proof_Literals.make_littab
  19.333 +    in Z3_Proof_Literals.join conj2 littab (Thm.term_of ct2) end
  19.334 +
  19.335 +  fun prove rule (ct1, conj1) (ct2, conj2) =
  19.336 +    Z3_Proof_Tools.under_assumption (prove' conj1 conj2 ct2) ct1 COMP rule
  19.337 +
  19.338 +  fun prove_def_axiom ct =
  19.339 +    let val (ct1, ct2) = Thm.dest_binop (Thm.dest_arg ct)
  19.340 +    in
  19.341 +      (case Thm.term_of ct1 of
  19.342 +        @{const Not} $ (@{const HOL.conj} $ _ $ _) =>
  19.343 +          prove disjI1 (Thm.dest_arg ct1, true) (ct2, true)
  19.344 +      | @{const HOL.conj} $ _ $ _ =>
  19.345 +          prove disjI3 (Z3_Proof_Literals.negate ct2, false) (ct1, true)
  19.346 +      | @{const Not} $ (@{const HOL.disj} $ _ $ _) =>
  19.347 +          prove disjI3 (Z3_Proof_Literals.negate ct2, false) (ct1, false)
  19.348 +      | @{const HOL.disj} $ _ $ _ =>
  19.349 +          prove disjI2 (Z3_Proof_Literals.negate ct1, false) (ct2, true)
  19.350 +      | Const (@{const_name distinct}, _) $ _ =>
  19.351 +          let
  19.352 +            fun dis_conv cv = Conv.arg_conv (Conv.arg1_conv cv)
  19.353 +            val unfold_dis_conv = dis_conv Z3_Proof_Tools.unfold_distinct_conv
  19.354 +            fun prv cu =
  19.355 +              let val (cu1, cu2) = Thm.dest_binop (Thm.dest_arg cu)
  19.356 +              in prove disjI4 (Thm.dest_arg cu2, true) (cu1, true) end
  19.357 +          in Z3_Proof_Tools.with_conv unfold_dis_conv prv ct end
  19.358 +      | @{const Not} $ (Const (@{const_name distinct}, _) $ _) =>
  19.359 +          let
  19.360 +            fun dis_conv cv = Conv.arg_conv (Conv.arg1_conv (Conv.arg_conv cv))
  19.361 +            val unfold_dis_conv = dis_conv Z3_Proof_Tools.unfold_distinct_conv
  19.362 +            fun prv cu =
  19.363 +              let val (cu1, cu2) = Thm.dest_binop (Thm.dest_arg cu)
  19.364 +              in prove disjI1 (Thm.dest_arg cu1, true) (cu2, true) end
  19.365 +          in Z3_Proof_Tools.with_conv unfold_dis_conv prv ct end
  19.366 +      | _ => raise CTERM ("prove_def_axiom", [ct]))
  19.367 +    end
  19.368 +in
  19.369 +fun def_axiom ctxt = Thm o try_apply ctxt [] [
  19.370 +  named ctxt "conj/disj/distinct" prove_def_axiom,
  19.371 +  Z3_Proof_Tools.by_abstraction 0 (true, false) ctxt [] (fn ctxt' =>
  19.372 +    named ctxt' "simp+fast" (Z3_Proof_Tools.by_tac ctxt (simp_fast_tac ctxt')))]
  19.373 +end
  19.374 +
  19.375 +
  19.376 +(* local definitions *)
  19.377 +local
  19.378 +  val intro_rules = [
  19.379 +    @{lemma "n == P ==> (~n | P) & (n | ~P)" by simp},
  19.380 +    @{lemma "n == (if P then s else t) ==> (~P | n = s) & (P | n = t)"
  19.381 +      by simp},
  19.382 +    @{lemma "n == P ==> n = P" by (rule meta_eq_to_obj_eq)} ]
  19.383 +
  19.384 +  val apply_rules = [
  19.385 +    @{lemma "(~n | P) & (n | ~P) ==> P == n" by (atomize(full)) fast},
  19.386 +    @{lemma "(~P | n = s) & (P | n = t) ==> (if P then s else t) == n"
  19.387 +      by (atomize(full)) fastforce} ]
  19.388 +
  19.389 +  val inst_rule = Z3_Proof_Tools.match_instantiate Thm.dest_arg
  19.390 +
  19.391 +  fun apply_rule ct =
  19.392 +    (case get_first (try (inst_rule ct)) intro_rules of
  19.393 +      SOME thm => thm
  19.394 +    | NONE => raise CTERM ("intro_def", [ct]))
  19.395 +in
  19.396 +fun intro_def ct = Z3_Proof_Tools.make_hyp_def (apply_rule ct) #>> Thm
  19.397 +
  19.398 +fun apply_def thm =
  19.399 +  get_first (try (fn rule => MetaEq (thm COMP rule))) apply_rules
  19.400 +  |> the_default (Thm thm)
  19.401 +end
  19.402 +
  19.403 +
  19.404 +(* negation normal form *)
  19.405 +local
  19.406 +  val quant_rules1 = ([
  19.407 +    @{lemma "(!!x. P x == Q) ==> ALL x. P x == Q" by simp},
  19.408 +    @{lemma "(!!x. P x == Q) ==> EX x. P x == Q" by simp}], [
  19.409 +    @{lemma "(!!x. P x == Q x) ==> ALL x. P x == ALL x. Q x" by simp},
  19.410 +    @{lemma "(!!x. P x == Q x) ==> EX x. P x == EX x. Q x" by simp}])
  19.411 +
  19.412 +  val quant_rules2 = ([
  19.413 +    @{lemma "(!!x. ~P x == Q) ==> ~(ALL x. P x) == Q" by simp},
  19.414 +    @{lemma "(!!x. ~P x == Q) ==> ~(EX x. P x) == Q" by simp}], [
  19.415 +    @{lemma "(!!x. ~P x == Q x) ==> ~(ALL x. P x) == EX x. Q x" by simp},
  19.416 +    @{lemma "(!!x. ~P x == Q x) ==> ~(EX x. P x) == ALL x. Q x" by simp}])
  19.417 +
  19.418 +  fun nnf_quant_tac thm (qs as (qs1, qs2)) i st = (
  19.419 +    rtac thm ORELSE'
  19.420 +    (match_tac qs1 THEN' nnf_quant_tac thm qs) ORELSE'
  19.421 +    (match_tac qs2 THEN' nnf_quant_tac thm qs)) i st
  19.422 +
  19.423 +  fun nnf_quant_tac_varified vars eq =
  19.424 +    nnf_quant_tac (Z3_Proof_Tools.varify vars eq)
  19.425 +
  19.426 +  fun nnf_quant ctxt vars qs p ct =
  19.427 +    Z3_Proof_Tools.as_meta_eq ct
  19.428 +    |> Z3_Proof_Tools.by_tac ctxt (nnf_quant_tac_varified vars (meta_eq_of p) qs)
  19.429 +
  19.430 +  fun prove_nnf ctxt = try_apply ctxt [] [
  19.431 +    named ctxt "conj/disj" Z3_Proof_Literals.prove_conj_disj_eq,
  19.432 +    Z3_Proof_Tools.by_abstraction 0 (true, false) ctxt [] (fn ctxt' =>
  19.433 +      named ctxt' "simp+fast" (Z3_Proof_Tools.by_tac ctxt' (simp_fast_tac ctxt')))]
  19.434 +in
  19.435 +fun nnf ctxt vars ps ct =
  19.436 +  (case SMT_Utils.term_of ct of
  19.437 +    _ $ (l as Const _ $ Abs _) $ (r as Const _ $ Abs _) =>
  19.438 +      if l aconv r
  19.439 +      then MetaEq (Thm.reflexive (Thm.dest_arg (Thm.dest_arg ct)))
  19.440 +      else MetaEq (nnf_quant ctxt vars quant_rules1 (hd ps) ct)
  19.441 +  | _ $ (@{const Not} $ (Const _ $ Abs _)) $ (Const _ $ Abs _) =>
  19.442 +      MetaEq (nnf_quant ctxt vars quant_rules2 (hd ps) ct)
  19.443 +  | _ =>
  19.444 +      let
  19.445 +        val nnf_rewr_conv = Conv.arg_conv (Conv.arg_conv
  19.446 +          (Z3_Proof_Tools.unfold_eqs ctxt
  19.447 +            (map (Thm.symmetric o meta_eq_of) ps)))
  19.448 +      in Thm (Z3_Proof_Tools.with_conv nnf_rewr_conv (prove_nnf ctxt) ct) end)
  19.449 +end
  19.450 +
  19.451 +
  19.452 +
  19.453 +(** equality proof rules **)
  19.454 +
  19.455 +(* |- t = t *)
  19.456 +fun refl ct = MetaEq (Thm.reflexive (Thm.dest_arg (Thm.dest_arg ct)))
  19.457 +
  19.458 +
  19.459 +(* s = t ==> t = s *)
  19.460 +local
  19.461 +  val symm_rule = @{lemma "s = t ==> t == s" by simp}
  19.462 +in
  19.463 +fun symm (MetaEq thm) = MetaEq (Thm.symmetric thm)
  19.464 +  | symm p = MetaEq (thm_of p COMP symm_rule)
  19.465 +end
  19.466 +
  19.467 +
  19.468 +(* s = t ==> t = u ==> s = u *)
  19.469 +local
  19.470 +  val trans1 = @{lemma "s == t ==> t =  u ==> s == u" by simp}
  19.471 +  val trans2 = @{lemma "s =  t ==> t == u ==> s == u" by simp}
  19.472 +  val trans3 = @{lemma "s =  t ==> t =  u ==> s == u" by simp}
  19.473 +in
  19.474 +fun trans (MetaEq thm1) (MetaEq thm2) = MetaEq (Thm.transitive thm1 thm2)
  19.475 +  | trans (MetaEq thm) q = MetaEq (thm_of q COMP (thm COMP trans1))
  19.476 +  | trans p (MetaEq thm) = MetaEq (thm COMP (thm_of p COMP trans2))
  19.477 +  | trans p q = MetaEq (thm_of q COMP (thm_of p COMP trans3))
  19.478 +end
  19.479 +
  19.480 +
  19.481 +(* t1 = s1 ==> ... ==> tn = sn ==> f t1 ... tn = f s1 .. sn
  19.482 +   (reflexive antecendents are droppped) *)
  19.483 +local
  19.484 +  exception MONO
  19.485 +
  19.486 +  fun prove_refl (ct, _) = Thm.reflexive ct
  19.487 +  fun prove_comb f g cp =
  19.488 +    let val ((ct1, ct2), (cu1, cu2)) = pairself Thm.dest_comb cp
  19.489 +    in Thm.combination (f (ct1, cu1)) (g (ct2, cu2)) end
  19.490 +  fun prove_arg f = prove_comb prove_refl f
  19.491 +
  19.492 +  fun prove f cp = prove_comb (prove f) f cp handle CTERM _ => prove_refl cp
  19.493 +
  19.494 +  fun prove_nary is_comb f =
  19.495 +    let
  19.496 +      fun prove (cp as (ct, _)) = f cp handle MONO =>
  19.497 +        if is_comb (Thm.term_of ct)
  19.498 +        then prove_comb (prove_arg prove) prove cp
  19.499 +        else prove_refl cp
  19.500 +    in prove end
  19.501 +
  19.502 +  fun prove_list f n cp =
  19.503 +    if n = 0 then prove_refl cp
  19.504 +    else prove_comb (prove_arg f) (prove_list f (n-1)) cp
  19.505 +
  19.506 +  fun with_length f (cp as (cl, _)) =
  19.507 +    f (length (HOLogic.dest_list (Thm.term_of cl))) cp
  19.508 +
  19.509 +  fun prove_distinct f = prove_arg (with_length (prove_list f))
  19.510 +
  19.511 +  fun prove_eq exn lookup cp =
  19.512 +    (case lookup (Logic.mk_equals (pairself Thm.term_of cp)) of
  19.513 +      SOME eq => eq
  19.514 +    | NONE => if exn then raise MONO else prove_refl cp)
  19.515 +  
  19.516 +  val prove_exn = prove_eq true
  19.517 +  and prove_safe = prove_eq false
  19.518 +
  19.519 +  fun mono f (cp as (cl, _)) =
  19.520 +    (case Term.head_of (Thm.term_of cl) of
  19.521 +      @{const HOL.conj} => prove_nary Z3_Proof_Literals.is_conj (prove_exn f)
  19.522 +    | @{const HOL.disj} => prove_nary Z3_Proof_Literals.is_disj (prove_exn f)
  19.523 +    | Const (@{const_name distinct}, _) => prove_distinct (prove_safe f)
  19.524 +    | _ => prove (prove_safe f)) cp
  19.525 +in
  19.526 +fun monotonicity eqs ct =
  19.527 +  let
  19.528 +    fun and_symmetric (t, thm) = [(t, thm), (t, Thm.symmetric thm)]
  19.529 +    val teqs = maps (and_symmetric o `Thm.prop_of o meta_eq_of) eqs
  19.530 +    val lookup = AList.lookup (op aconv) teqs
  19.531 +    val cp = Thm.dest_binop (Thm.dest_arg ct)
  19.532 +  in MetaEq (prove_exn lookup cp handle MONO => mono lookup cp) end
  19.533 +end
  19.534 +
  19.535 +
  19.536 +(* |- f a b = f b a (where f is equality) *)
  19.537 +local
  19.538 +  val rule = @{lemma "a = b == b = a" by (atomize(full)) (rule eq_commute)}
  19.539 +in
  19.540 +fun commutativity ct =
  19.541 +  MetaEq (Z3_Proof_Tools.match_instantiate I
  19.542 +    (Z3_Proof_Tools.as_meta_eq ct) rule)
  19.543 +end
  19.544 +
  19.545 +
  19.546 +
  19.547 +(** quantifier proof rules **)
  19.548 +
  19.549 +(* P ?x = Q ?x ==> (ALL x. P x) = (ALL x. Q x)
  19.550 +   P ?x = Q ?x ==> (EX x. P x) = (EX x. Q x)    *)
  19.551 +local
  19.552 +  val rules = [
  19.553 +    @{lemma "(!!x. P x == Q x) ==> (ALL x. P x) == (ALL x. Q x)" by simp},
  19.554 +    @{lemma "(!!x. P x == Q x) ==> (EX x. P x) == (EX x. Q x)" by simp}]
  19.555 +in
  19.556 +fun quant_intro ctxt vars p ct =
  19.557 +  let
  19.558 +    val thm = meta_eq_of p
  19.559 +    val rules' = Z3_Proof_Tools.varify vars thm :: rules
  19.560 +    val cu = Z3_Proof_Tools.as_meta_eq ct
  19.561 +    val tac = REPEAT_ALL_NEW (match_tac rules')
  19.562 +  in MetaEq (Z3_Proof_Tools.by_tac ctxt tac cu) end
  19.563 +end
  19.564 +
  19.565 +
  19.566 +(* |- ((ALL x. P x) | Q) = (ALL x. P x | Q) *)
  19.567 +fun pull_quant ctxt = Thm o try_apply ctxt [] [
  19.568 +  named ctxt "fast" (Z3_Proof_Tools.by_tac ctxt (HOL_fast_tac ctxt))]
  19.569 +    (* FIXME: not very well tested *)
  19.570 +
  19.571 +
  19.572 +(* |- (ALL x. P x & Q x) = ((ALL x. P x) & (ALL x. Q x)) *)
  19.573 +fun push_quant ctxt = Thm o try_apply ctxt [] [
  19.574 +  named ctxt "fast" (Z3_Proof_Tools.by_tac ctxt (HOL_fast_tac ctxt))]
  19.575 +    (* FIXME: not very well tested *)
  19.576 +
  19.577 +
  19.578 +(* |- (ALL x1 ... xn y1 ... yn. P x1 ... xn) = (ALL x1 ... xn. P x1 ... xn) *)
  19.579 +local
  19.580 +  val elim_all = @{lemma "P = Q ==> (ALL x. P) = Q" by fast}
  19.581 +  val elim_ex = @{lemma "P = Q ==> (EX x. P) = Q" by fast}
  19.582 +
  19.583 +  fun elim_unused_tac i st = (
  19.584 +    match_tac [@{thm refl}]
  19.585 +    ORELSE' (match_tac [elim_all, elim_ex] THEN' elim_unused_tac)
  19.586 +    ORELSE' (
  19.587 +      match_tac [@{thm iff_allI}, @{thm iff_exI}]
  19.588 +      THEN' elim_unused_tac)) i st
  19.589 +in
  19.590 +
  19.591 +fun elim_unused_vars ctxt = Thm o Z3_Proof_Tools.by_tac ctxt elim_unused_tac
  19.592 +
  19.593 +end
  19.594 +
  19.595 +
  19.596 +(* |- (ALL x1 ... xn. ~(x1 = t1 & ... xn = tn) | P x1 ... xn) = P t1 ... tn *)
  19.597 +fun dest_eq_res ctxt = Thm o try_apply ctxt [] [
  19.598 +  named ctxt "fast" (Z3_Proof_Tools.by_tac ctxt (HOL_fast_tac ctxt))]
  19.599 +    (* FIXME: not very well tested *)
  19.600 +
  19.601 +
  19.602 +(* |- ~(ALL x1...xn. P x1...xn) | P a1...an *)
  19.603 +local
  19.604 +  val rule = @{lemma "~ P x | Q ==> ~(ALL x. P x) | Q" by fast}
  19.605 +in
  19.606 +fun quant_inst ctxt = Thm o Z3_Proof_Tools.by_tac ctxt (
  19.607 +  REPEAT_ALL_NEW (match_tac [rule])
  19.608 +  THEN' rtac @{thm excluded_middle})
  19.609 +end
  19.610 +
  19.611 +
  19.612 +(* |- (EX x. P x) = P c     |- ~(ALL x. P x) = ~ P c *)
  19.613 +local
  19.614 +  val forall =
  19.615 +    SMT_Utils.mk_const_pat @{theory} @{const_name Pure.all}
  19.616 +      (SMT_Utils.destT1 o SMT_Utils.destT1)
  19.617 +  fun mk_forall cv ct =
  19.618 +    Thm.apply (SMT_Utils.instT' cv forall) (Thm.lambda cv ct)
  19.619 +
  19.620 +  fun get_vars f mk pred ctxt t =
  19.621 +    Term.fold_aterms f t []
  19.622 +    |> map_filter (fn v =>
  19.623 +         if pred v then SOME (SMT_Utils.certify ctxt (mk v)) else NONE)
  19.624 +
  19.625 +  fun close vars f ct ctxt =
  19.626 +    let
  19.627 +      val frees_of = get_vars Term.add_frees Free (member (op =) vars o fst)
  19.628 +      val vs = frees_of ctxt (Thm.term_of ct)
  19.629 +      val (thm, ctxt') = f (fold_rev mk_forall vs ct) ctxt
  19.630 +      val vars_of = get_vars Term.add_vars Var (K true) ctxt'
  19.631 +    in (Thm.instantiate ([], vars_of (Thm.prop_of thm) ~~ vs) thm, ctxt') end
  19.632 +
  19.633 +  val sk_rules = @{lemma
  19.634 +    "c = (SOME x. P x) ==> (EX x. P x) = P c"
  19.635 +    "c = (SOME x. ~P x) ==> (~(ALL x. P x)) = (~P c)"
  19.636 +    by (metis someI_ex)+}
  19.637 +in
  19.638 +
  19.639 +fun skolemize vars =
  19.640 +  apfst Thm oo close vars (yield_singleton Assumption.add_assumes)
  19.641 +
  19.642 +fun discharge_sk_tac i st = (
  19.643 +  rtac @{thm trans} i
  19.644 +  THEN resolve_tac sk_rules i
  19.645 +  THEN (rtac @{thm refl} ORELSE' discharge_sk_tac) (i+1)
  19.646 +  THEN rtac @{thm refl} i) st
  19.647 +
  19.648 +end
  19.649 +
  19.650 +
  19.651 +
  19.652 +(** theory proof rules **)
  19.653 +
  19.654 +(* theory lemmas: linear arithmetic, arrays *)
  19.655 +fun th_lemma ctxt simpset thms = Thm o try_apply ctxt thms [
  19.656 +  Z3_Proof_Tools.by_abstraction 0 (false, true) ctxt thms (fn ctxt' =>
  19.657 +    Z3_Proof_Tools.by_tac ctxt' (
  19.658 +      NAMED ctxt' "arith" (Arith_Data.arith_tac ctxt')
  19.659 +      ORELSE' NAMED ctxt' "simp+arith" (
  19.660 +        Simplifier.asm_full_simp_tac (put_simpset simpset ctxt')
  19.661 +        THEN_ALL_NEW Arith_Data.arith_tac ctxt')))]
  19.662 +
  19.663 +
  19.664 +(* rewriting: prove equalities:
  19.665 +     * ACI of conjunction/disjunction
  19.666 +     * contradiction, excluded middle
  19.667 +     * logical rewriting rules (for negation, implication, equivalence,
  19.668 +         distinct)
  19.669 +     * normal forms for polynoms (integer/real arithmetic)
  19.670 +     * quantifier elimination over linear arithmetic
  19.671 +     * ... ? **)
  19.672 +local
  19.673 +  fun spec_meta_eq_of thm =
  19.674 +    (case try (fn th => th RS @{thm spec}) thm of
  19.675 +      SOME thm' => spec_meta_eq_of thm'
  19.676 +    | NONE => mk_meta_eq thm)
  19.677 +
  19.678 +  fun prep (Thm thm) = spec_meta_eq_of thm
  19.679 +    | prep (MetaEq thm) = thm
  19.680 +    | prep (Literals (thm, _)) = spec_meta_eq_of thm
  19.681 +
  19.682 +  fun unfold_conv ctxt ths =
  19.683 +    Conv.arg_conv (Conv.binop_conv (Z3_Proof_Tools.unfold_eqs ctxt
  19.684 +      (map prep ths)))
  19.685 +
  19.686 +  fun with_conv _ [] prv = prv
  19.687 +    | with_conv ctxt ths prv =
  19.688 +        Z3_Proof_Tools.with_conv (unfold_conv ctxt ths) prv
  19.689 +
  19.690 +  val unfold_conv =
  19.691 +    Conv.arg_conv (Conv.binop_conv
  19.692 +      (Conv.try_conv Z3_Proof_Tools.unfold_distinct_conv))
  19.693 +  val prove_conj_disj_eq =
  19.694 +    Z3_Proof_Tools.with_conv unfold_conv Z3_Proof_Literals.prove_conj_disj_eq
  19.695 +
  19.696 +  fun declare_hyps ctxt thm =
  19.697 +    (thm, snd (Assumption.add_assumes (#hyps (Thm.crep_thm thm)) ctxt))
  19.698 +in
  19.699 +
  19.700 +val abstraction_depth = 3
  19.701 +  (*
  19.702 +    This value was chosen large enough to potentially catch exceptions,
  19.703 +    yet small enough to not cause too much harm.  The value might be
  19.704 +    increased in the future, if reconstructing 'rewrite' fails on problems
  19.705 +    that get too much abstracted to be reconstructable.
  19.706 +  *)
  19.707 +
  19.708 +fun rewrite simpset ths ct ctxt =
  19.709 +  apfst Thm (declare_hyps ctxt (with_conv ctxt ths (try_apply ctxt [] [
  19.710 +    named ctxt "conj/disj/distinct" prove_conj_disj_eq,
  19.711 +    named ctxt "pull-ite" Z3_Proof_Methods.prove_ite ctxt,
  19.712 +    Z3_Proof_Tools.by_abstraction 0 (true, false) ctxt [] (fn ctxt' =>
  19.713 +      Z3_Proof_Tools.by_tac ctxt' (
  19.714 +        NAMED ctxt' "simp (logic)" (Simplifier.simp_tac (put_simpset simpset ctxt'))
  19.715 +        THEN_ALL_NEW NAMED ctxt' "fast (logic)" (fast_tac ctxt'))),
  19.716 +    Z3_Proof_Tools.by_abstraction 0 (false, true) ctxt [] (fn ctxt' =>
  19.717 +      Z3_Proof_Tools.by_tac ctxt' (
  19.718 +        (rtac @{thm iff_allI} ORELSE' K all_tac)
  19.719 +        THEN' NAMED ctxt' "simp (theory)" (Simplifier.simp_tac (put_simpset simpset ctxt'))
  19.720 +        THEN_ALL_NEW (
  19.721 +          NAMED ctxt' "fast (theory)" (HOL_fast_tac ctxt')
  19.722 +          ORELSE' NAMED ctxt' "arith (theory)" (Arith_Data.arith_tac ctxt')))),
  19.723 +    Z3_Proof_Tools.by_abstraction 0 (true, true) ctxt [] (fn ctxt' =>
  19.724 +      Z3_Proof_Tools.by_tac ctxt' (
  19.725 +        (rtac @{thm iff_allI} ORELSE' K all_tac)
  19.726 +        THEN' NAMED ctxt' "simp (full)" (Simplifier.simp_tac (put_simpset simpset ctxt'))
  19.727 +        THEN_ALL_NEW (
  19.728 +          NAMED ctxt' "fast (full)" (HOL_fast_tac ctxt')
  19.729 +          ORELSE' NAMED ctxt' "arith (full)" (Arith_Data.arith_tac ctxt')))),
  19.730 +    named ctxt "injectivity" (Z3_Proof_Methods.prove_injectivity ctxt),
  19.731 +    Z3_Proof_Tools.by_abstraction abstraction_depth (true, true) ctxt []
  19.732 +      (fn ctxt' =>
  19.733 +        Z3_Proof_Tools.by_tac ctxt' (
  19.734 +          (rtac @{thm iff_allI} ORELSE' K all_tac)
  19.735 +          THEN' NAMED ctxt' "simp (deepen)" (Simplifier.simp_tac (put_simpset simpset ctxt'))
  19.736 +          THEN_ALL_NEW (
  19.737 +            NAMED ctxt' "fast (deepen)" (HOL_fast_tac ctxt')
  19.738 +            ORELSE' NAMED ctxt' "arith (deepen)" (Arith_Data.arith_tac
  19.739 +              ctxt'))))]) ct))
  19.740 +
  19.741 +end
  19.742 +
  19.743 +
  19.744 +
  19.745 +(* proof reconstruction *)
  19.746 +
  19.747 +(** tracing and checking **)
  19.748 +
  19.749 +fun trace_before ctxt idx = SMT_Config.trace_msg ctxt (fn r =>
  19.750 +  "Z3: #" ^ string_of_int idx ^ ": " ^ Z3_Proof_Parser.string_of_rule r)
  19.751 +
  19.752 +fun check_after idx r ps ct (p, (ctxt, _)) =
  19.753 +  if not (Config.get ctxt SMT_Config.trace) then ()
  19.754 +  else
  19.755 +    let val thm = thm_of p |> tap (Thm.join_proofs o single)
  19.756 +    in
  19.757 +      if (Thm.cprop_of thm) aconvc ct then ()
  19.758 +      else
  19.759 +        z3_exn (Pretty.string_of (Pretty.big_list
  19.760 +          ("proof step failed: " ^ quote (Z3_Proof_Parser.string_of_rule r) ^
  19.761 +            " (#" ^ string_of_int idx ^ ")")
  19.762 +          (pretty_goal ctxt (map (thm_of o fst) ps) (Thm.prop_of thm) @
  19.763 +            [Pretty.block [Pretty.str "expected: ",
  19.764 +              Syntax.pretty_term ctxt (Thm.term_of ct)]])))
  19.765 +    end
  19.766 +
  19.767 +
  19.768 +(** overall reconstruction procedure **)
  19.769 +
  19.770 +local
  19.771 +  fun not_supported r = raise Fail ("Z3: proof rule not implemented: " ^
  19.772 +    quote (Z3_Proof_Parser.string_of_rule r))
  19.773 +
  19.774 +  fun prove_step simpset vars r ps ct (cxp as (cx, ptab)) =
  19.775 +    (case (r, ps) of
  19.776 +      (* core rules *)
  19.777 +      (Z3_Proof_Parser.True_Axiom, _) => (Thm Z3_Proof_Literals.true_thm, cxp)
  19.778 +    | (Z3_Proof_Parser.Asserted, _) => raise Fail "bad assertion"
  19.779 +    | (Z3_Proof_Parser.Goal, _) => raise Fail "bad assertion"
  19.780 +    | (Z3_Proof_Parser.Modus_Ponens, [(p, _), (q, _)]) =>
  19.781 +        (mp q (thm_of p), cxp)
  19.782 +    | (Z3_Proof_Parser.Modus_Ponens_Oeq, [(p, _), (q, _)]) =>
  19.783 +        (mp q (thm_of p), cxp)
  19.784 +    | (Z3_Proof_Parser.And_Elim, [(p, i)]) =>
  19.785 +        and_elim (p, i) ct ptab ||> pair cx
  19.786 +    | (Z3_Proof_Parser.Not_Or_Elim, [(p, i)]) =>
  19.787 +        not_or_elim (p, i) ct ptab ||> pair cx
  19.788 +    | (Z3_Proof_Parser.Hypothesis, _) => (Thm (Thm.assume ct), cxp)
  19.789 +    | (Z3_Proof_Parser.Lemma, [(p, _)]) => (lemma (thm_of p) ct, cxp)
  19.790 +    | (Z3_Proof_Parser.Unit_Resolution, (p, _) :: ps) =>
  19.791 +        (unit_resolution (thm_of p) (map (thm_of o fst) ps) ct, cxp)
  19.792 +    | (Z3_Proof_Parser.Iff_True, [(p, _)]) => (iff_true (thm_of p), cxp)
  19.793 +    | (Z3_Proof_Parser.Iff_False, [(p, _)]) => (iff_false (thm_of p), cxp)
  19.794 +    | (Z3_Proof_Parser.Distributivity, _) => (distributivity cx ct, cxp)
  19.795 +    | (Z3_Proof_Parser.Def_Axiom, _) => (def_axiom cx ct, cxp)
  19.796 +    | (Z3_Proof_Parser.Intro_Def, _) => intro_def ct cx ||> rpair ptab
  19.797 +    | (Z3_Proof_Parser.Apply_Def, [(p, _)]) => (apply_def (thm_of p), cxp)
  19.798 +    | (Z3_Proof_Parser.Iff_Oeq, [(p, _)]) => (p, cxp)
  19.799 +    | (Z3_Proof_Parser.Nnf_Pos, _) => (nnf cx vars (map fst ps) ct, cxp)
  19.800 +    | (Z3_Proof_Parser.Nnf_Neg, _) => (nnf cx vars (map fst ps) ct, cxp)
  19.801 +
  19.802 +      (* equality rules *)
  19.803 +    | (Z3_Proof_Parser.Reflexivity, _) => (refl ct, cxp)
  19.804 +    | (Z3_Proof_Parser.Symmetry, [(p, _)]) => (symm p, cxp)
  19.805 +    | (Z3_Proof_Parser.Transitivity, [(p, _), (q, _)]) => (trans p q, cxp)
  19.806 +    | (Z3_Proof_Parser.Monotonicity, _) => (monotonicity (map fst ps) ct, cxp)
  19.807 +    | (Z3_Proof_Parser.Commutativity, _) => (commutativity ct, cxp)
  19.808 +
  19.809 +      (* quantifier rules *)
  19.810 +    | (Z3_Proof_Parser.Quant_Intro, [(p, _)]) => (quant_intro cx vars p ct, cxp)
  19.811 +    | (Z3_Proof_Parser.Pull_Quant, _) => (pull_quant cx ct, cxp)
  19.812 +    | (Z3_Proof_Parser.Push_Quant, _) => (push_quant cx ct, cxp)
  19.813 +    | (Z3_Proof_Parser.Elim_Unused_Vars, _) => (elim_unused_vars cx ct, cxp)
  19.814 +    | (Z3_Proof_Parser.Dest_Eq_Res, _) => (dest_eq_res cx ct, cxp)
  19.815 +    | (Z3_Proof_Parser.Quant_Inst, _) => (quant_inst cx ct, cxp)
  19.816 +    | (Z3_Proof_Parser.Skolemize, _) => skolemize vars ct cx ||> rpair ptab
  19.817 +
  19.818 +      (* theory rules *)
  19.819 +    | (Z3_Proof_Parser.Th_Lemma _, _) =>  (* FIXME: use arguments *)
  19.820 +        (th_lemma cx simpset (map (thm_of o fst) ps) ct, cxp)
  19.821 +    | (Z3_Proof_Parser.Rewrite, _) => rewrite simpset [] ct cx ||> rpair ptab
  19.822 +    | (Z3_Proof_Parser.Rewrite_Star, ps) =>
  19.823 +        rewrite simpset (map fst ps) ct cx ||> rpair ptab
  19.824 +
  19.825 +    | (Z3_Proof_Parser.Nnf_Star, _) => not_supported r
  19.826 +    | (Z3_Proof_Parser.Cnf_Star, _) => not_supported r
  19.827 +    | (Z3_Proof_Parser.Transitivity_Star, _) => not_supported r
  19.828 +    | (Z3_Proof_Parser.Pull_Quant_Star, _) => not_supported r
  19.829 +
  19.830 +    | _ => raise Fail ("Z3: proof rule " ^
  19.831 +        quote (Z3_Proof_Parser.string_of_rule r) ^
  19.832 +        " has an unexpected number of arguments."))
  19.833 +
  19.834 +  fun lookup_proof ptab idx =
  19.835 +    (case Inttab.lookup ptab idx of
  19.836 +      SOME p => (p, idx)
  19.837 +    | NONE => z3_exn ("unknown proof id: " ^ quote (string_of_int idx)))
  19.838 +
  19.839 +  fun prove simpset vars (idx, step) (_, cxp as (ctxt, ptab)) =
  19.840 +    let
  19.841 +      val Z3_Proof_Parser.Proof_Step {rule=r, prems, prop, ...} = step
  19.842 +      val ps = map (lookup_proof ptab) prems
  19.843 +      val _ = trace_before ctxt idx r
  19.844 +      val (thm, (ctxt', ptab')) =
  19.845 +        cxp
  19.846 +        |> prove_step simpset vars r ps prop
  19.847 +        |> tap (check_after idx r ps prop)
  19.848 +    in (thm, (ctxt', Inttab.update (idx, thm) ptab')) end
  19.849 +
  19.850 +  fun make_discharge_rules rules = rules @ [@{thm allI}, @{thm refl},
  19.851 +    @{thm reflexive}, Z3_Proof_Literals.true_thm]
  19.852 +
  19.853 +  fun discharge_assms_tac rules =
  19.854 +    REPEAT (HEADGOAL (resolve_tac rules ORELSE' SOLVED' discharge_sk_tac))
  19.855 +    
  19.856 +  fun discharge_assms ctxt rules thm =
  19.857 +    if Thm.nprems_of thm = 0 then Goal.norm_result ctxt thm
  19.858 +    else
  19.859 +      (case Seq.pull (discharge_assms_tac rules thm) of
  19.860 +        SOME (thm', _) => Goal.norm_result ctxt thm'
  19.861 +      | NONE => raise THM ("failed to discharge premise", 1, [thm]))
  19.862 +
  19.863 +  fun discharge rules outer_ctxt (p, (inner_ctxt, _)) =
  19.864 +    thm_of p
  19.865 +    |> singleton (Proof_Context.export inner_ctxt outer_ctxt)
  19.866 +    |> discharge_assms outer_ctxt (make_discharge_rules rules)
  19.867 +in
  19.868 +
  19.869 +fun reconstruct outer_ctxt recon output =
  19.870 +  let
  19.871 +    val {context=ctxt, typs, terms, rewrite_rules, assms} = recon
  19.872 +    val (asserted, steps, vars, ctxt1) =
  19.873 +      Z3_Proof_Parser.parse ctxt typs terms output
  19.874 +
  19.875 +    val simpset =
  19.876 +      Z3_Proof_Tools.make_simpset ctxt1 (Named_Theorems.get ctxt1 @{named_theorems z3_simp})
  19.877 +
  19.878 +    val ((is, rules), cxp as (ctxt2, _)) =
  19.879 +      add_asserted outer_ctxt rewrite_rules assms asserted ctxt1
  19.880 +  in
  19.881 +    if Config.get ctxt2 SMT_Config.filter_only_facts then (is, @{thm TrueI})
  19.882 +    else
  19.883 +      (Thm @{thm TrueI}, cxp)
  19.884 +      |> fold (prove simpset vars) steps 
  19.885 +      |> discharge rules outer_ctxt
  19.886 +      |> pair []
  19.887 +  end
  19.888 +
  19.889 +end
  19.890 +
  19.891 +end
    20.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    20.2 +++ b/src/HOL/Library/SMT/z3_proof_tools.ML	Thu Aug 28 00:40:37 2014 +0200
    20.3 @@ -0,0 +1,371 @@
    20.4 +(*  Title:      HOL/Library/SMT/z3_proof_tools.ML
    20.5 +    Author:     Sascha Boehme, TU Muenchen
    20.6 +
    20.7 +Helper functions required for Z3 proof reconstruction.
    20.8 +*)
    20.9 +
   20.10 +signature Z3_PROOF_TOOLS =
   20.11 +sig
   20.12 +  (*modifying terms*)
   20.13 +  val as_meta_eq: cterm -> cterm
   20.14 +
   20.15 +  (*theorem nets*)
   20.16 +  val thm_net_of: ('a -> thm) -> 'a list -> 'a Net.net
   20.17 +  val net_instances: (int * thm) Net.net -> cterm -> (int * thm) list
   20.18 +  val net_instance: thm Net.net -> cterm -> thm option
   20.19 +
   20.20 +  (*proof combinators*)
   20.21 +  val under_assumption: (thm -> thm) -> cterm -> thm
   20.22 +  val with_conv: conv -> (cterm -> thm) -> cterm -> thm
   20.23 +  val discharge: thm -> thm -> thm
   20.24 +  val varify: string list -> thm -> thm
   20.25 +  val unfold_eqs: Proof.context -> thm list -> conv
   20.26 +  val match_instantiate: (cterm -> cterm) -> cterm -> thm -> thm
   20.27 +  val by_tac: Proof.context -> (int -> tactic) -> cterm -> thm
   20.28 +  val make_hyp_def: thm -> Proof.context -> thm * Proof.context
   20.29 +  val by_abstraction: int -> bool * bool -> Proof.context -> thm list ->
   20.30 +    (Proof.context -> cterm -> thm) -> cterm -> thm
   20.31 +
   20.32 +  (*a faster COMP*)
   20.33 +  type compose_data
   20.34 +  val precompose: (cterm -> cterm list) -> thm -> compose_data
   20.35 +  val precompose2: (cterm -> cterm * cterm) -> thm -> compose_data
   20.36 +  val compose: compose_data -> thm -> thm
   20.37 +
   20.38 +  (*unfolding of 'distinct'*)
   20.39 +  val unfold_distinct_conv: conv
   20.40 +
   20.41 +  (*simpset*)
   20.42 +  val add_simproc: Simplifier.simproc -> Context.generic -> Context.generic
   20.43 +  val make_simpset: Proof.context -> thm list -> simpset
   20.44 +end
   20.45 +
   20.46 +structure Z3_Proof_Tools: Z3_PROOF_TOOLS =
   20.47 +struct
   20.48 +
   20.49 +
   20.50 +
   20.51 +(* modifying terms *)
   20.52 +
   20.53 +fun as_meta_eq ct =
   20.54 +  uncurry SMT_Utils.mk_cequals (Thm.dest_binop (SMT_Utils.dest_cprop ct))
   20.55 +
   20.56 +
   20.57 +
   20.58 +(* theorem nets *)
   20.59 +
   20.60 +fun thm_net_of f xthms =
   20.61 +  let fun insert xthm = Net.insert_term (K false) (Thm.prop_of (f xthm), xthm)
   20.62 +  in fold insert xthms Net.empty end
   20.63 +
   20.64 +fun maybe_instantiate ct thm =
   20.65 +  try Thm.first_order_match (Thm.cprop_of thm, ct)
   20.66 +  |> Option.map (fn inst => Thm.instantiate inst thm)
   20.67 +
   20.68 +local
   20.69 +  fun instances_from_net match f net ct =
   20.70 +    let
   20.71 +      val lookup = if match then Net.match_term else Net.unify_term
   20.72 +      val xthms = lookup net (Thm.term_of ct)
   20.73 +      fun select ct = map_filter (f (maybe_instantiate ct)) xthms 
   20.74 +      fun select' ct =
   20.75 +        let val thm = Thm.trivial ct
   20.76 +        in map_filter (f (try (fn rule => rule COMP thm))) xthms end
   20.77 +    in (case select ct of [] => select' ct | xthms' => xthms') end
   20.78 +in
   20.79 +
   20.80 +fun net_instances net =
   20.81 +  instances_from_net false (fn f => fn (i, thm) => Option.map (pair i) (f thm))
   20.82 +    net
   20.83 +
   20.84 +fun net_instance net = try hd o instances_from_net true I net
   20.85 +
   20.86 +end
   20.87 +
   20.88 +
   20.89 +
   20.90 +(* proof combinators *)
   20.91 +
   20.92 +fun under_assumption f ct =
   20.93 +  let val ct' = SMT_Utils.mk_cprop ct
   20.94 +  in Thm.implies_intr ct' (f (Thm.assume ct')) end
   20.95 +
   20.96 +fun with_conv conv prove ct =
   20.97 +  let val eq = Thm.symmetric (conv ct)
   20.98 +  in Thm.equal_elim eq (prove (Thm.lhs_of eq)) end
   20.99 +
  20.100 +fun discharge p pq = Thm.implies_elim pq p
  20.101 +
  20.102 +fun varify vars = Drule.generalize ([], vars)
  20.103 +
  20.104 +fun unfold_eqs _ [] = Conv.all_conv
  20.105 +  | unfold_eqs ctxt eqs =
  20.106 +      Conv.top_sweep_conv (K (Conv.rewrs_conv eqs)) ctxt
  20.107 +
  20.108 +fun match_instantiate f ct thm =
  20.109 +  Thm.instantiate (Thm.match (f (Thm.cprop_of thm), ct)) thm
  20.110 +
  20.111 +fun by_tac ctxt tac ct = Goal.norm_result ctxt (Goal.prove_internal ctxt [] ct (K (tac 1)))
  20.112 +
  20.113 +(*
  20.114 +   |- c x == t x ==> P (c x)
  20.115 +  ---------------------------
  20.116 +      c == t |- P (c x)
  20.117 +*) 
  20.118 +fun make_hyp_def thm ctxt =
  20.119 +  let
  20.120 +    val (lhs, rhs) = Thm.dest_binop (Thm.cprem_of thm 1)
  20.121 +    val (cf, cvs) = Drule.strip_comb lhs
  20.122 +    val eq = SMT_Utils.mk_cequals cf (fold_rev Thm.lambda cvs rhs)
  20.123 +    fun apply cv th =
  20.124 +      Thm.combination th (Thm.reflexive cv)
  20.125 +      |> Conv.fconv_rule (Conv.arg_conv (Thm.beta_conversion false))
  20.126 +  in
  20.127 +    yield_singleton Assumption.add_assumes eq ctxt
  20.128 +    |>> Thm.implies_elim thm o fold apply cvs
  20.129 +  end
  20.130 +
  20.131 +
  20.132 +
  20.133 +(* abstraction *)
  20.134 +
  20.135 +local
  20.136 +
  20.137 +fun abs_context ctxt = (ctxt, Termtab.empty, 1, false)
  20.138 +
  20.139 +fun context_of (ctxt, _, _, _) = ctxt
  20.140 +
  20.141 +fun replace (_, (cv, ct)) = Thm.forall_elim ct o Thm.forall_intr cv
  20.142 +
  20.143 +fun abs_instantiate (_, tab, _, beta_norm) =
  20.144 +  fold replace (Termtab.dest tab) #>
  20.145 +  beta_norm ? Conv.fconv_rule (Thm.beta_conversion true)
  20.146 +
  20.147 +fun lambda_abstract cvs t =
  20.148 +  let
  20.149 +    val frees = map Free (Term.add_frees t [])
  20.150 +    val cvs' = filter (fn cv => member (op aconv) frees (Thm.term_of cv)) cvs
  20.151 +    val vs = map (Term.dest_Free o Thm.term_of) cvs'
  20.152 +  in (fold_rev absfree vs t, cvs') end
  20.153 +
  20.154 +fun fresh_abstraction (_, cvs) ct (cx as (ctxt, tab, idx, beta_norm)) =
  20.155 +  let val (t, cvs') = lambda_abstract cvs (Thm.term_of ct)
  20.156 +  in
  20.157 +    (case Termtab.lookup tab t of
  20.158 +      SOME (cv, _) => (Drule.list_comb (cv, cvs'), cx)
  20.159 +    | NONE =>
  20.160 +        let
  20.161 +          val (n, ctxt') = yield_singleton Variable.variant_fixes "x" ctxt
  20.162 +          val cv = SMT_Utils.certify ctxt'
  20.163 +            (Free (n, map SMT_Utils.typ_of cvs' ---> SMT_Utils.typ_of ct))
  20.164 +          val cu = Drule.list_comb (cv, cvs')
  20.165 +          val e = (t, (cv, fold_rev Thm.lambda cvs' ct))
  20.166 +          val beta_norm' = beta_norm orelse not (null cvs')
  20.167 +        in (cu, (ctxt', Termtab.update e tab, idx + 1, beta_norm')) end)
  20.168 +  end
  20.169 +
  20.170 +fun abs_comb f g dcvs ct =
  20.171 +  let val (cf, cu) = Thm.dest_comb ct
  20.172 +  in f dcvs cf ##>> g dcvs cu #>> uncurry Thm.apply end
  20.173 +
  20.174 +fun abs_arg f = abs_comb (K pair) f
  20.175 +
  20.176 +fun abs_args f dcvs ct =
  20.177 +  (case Thm.term_of ct of
  20.178 +    _ $ _ => abs_comb (abs_args f) f dcvs ct
  20.179 +  | _ => pair ct)
  20.180 +
  20.181 +fun abs_list f g dcvs ct =
  20.182 +  (case Thm.term_of ct of
  20.183 +    Const (@{const_name Nil}, _) => pair ct
  20.184 +  | Const (@{const_name Cons}, _) $ _ $ _ =>
  20.185 +      abs_comb (abs_arg f) (abs_list f g) dcvs ct
  20.186 +  | _ => g dcvs ct)
  20.187 +
  20.188 +fun abs_abs f (depth, cvs) ct =
  20.189 +  let val (cv, cu) = Thm.dest_abs NONE ct
  20.190 +  in f (depth, cv :: cvs) cu #>> Thm.lambda cv end
  20.191 +
  20.192 +val is_atomic =
  20.193 +  (fn Free _ => true | Var _ => true | Bound _ => true | _ => false)
  20.194 +
  20.195 +fun abstract depth (ext_logic, with_theories) =
  20.196 +  let
  20.197 +    fun abstr1 cvs ct = abs_arg abstr cvs ct
  20.198 +    and abstr2 cvs ct = abs_comb abstr1 abstr cvs ct
  20.199 +    and abstr3 cvs ct = abs_comb abstr2 abstr cvs ct
  20.200 +    and abstr_abs cvs ct = abs_arg (abs_abs abstr) cvs ct
  20.201 +
  20.202 +    and abstr (dcvs as (d, cvs)) ct =
  20.203 +      (case Thm.term_of ct of
  20.204 +        @{const Trueprop} $ _ => abstr1 dcvs ct
  20.205 +      | @{const Pure.imp} $ _ $ _ => abstr2 dcvs ct
  20.206 +      | @{const True} => pair ct
  20.207 +      | @{const False} => pair ct
  20.208 +      | @{const Not} $ _ => abstr1 dcvs ct
  20.209 +      | @{const HOL.conj} $ _ $ _ => abstr2 dcvs ct
  20.210 +      | @{const HOL.disj} $ _ $ _ => abstr2 dcvs ct
  20.211 +      | @{const HOL.implies} $ _ $ _ => abstr2 dcvs ct
  20.212 +      | Const (@{const_name HOL.eq}, _) $ _ $ _ => abstr2 dcvs ct
  20.213 +      | Const (@{const_name distinct}, _) $ _ =>
  20.214 +          if ext_logic then abs_arg (abs_list abstr fresh_abstraction) dcvs ct
  20.215 +          else fresh_abstraction dcvs ct
  20.216 +      | Const (@{const_name If}, _) $ _ $ _ $ _ =>
  20.217 +          if ext_logic then abstr3 dcvs ct else fresh_abstraction dcvs ct
  20.218 +      | Const (@{const_name All}, _) $ _ =>
  20.219 +          if ext_logic then abstr_abs dcvs ct else fresh_abstraction dcvs ct
  20.220 +      | Const (@{const_name Ex}, _) $ _ =>
  20.221 +          if ext_logic then abstr_abs dcvs ct else fresh_abstraction dcvs ct
  20.222 +      | t => (fn cx =>
  20.223 +          if is_atomic t orelse can HOLogic.dest_number t then (ct, cx)
  20.224 +          else if with_theories andalso
  20.225 +            Z3_Interface.is_builtin_theory_term (context_of cx) t
  20.226 +          then abs_args abstr dcvs ct cx
  20.227 +          else if d = 0 then fresh_abstraction dcvs ct cx
  20.228 +          else
  20.229 +            (case Term.strip_comb t of
  20.230 +              (Const _, _) => abs_args abstr (d-1, cvs) ct cx
  20.231 +            | (Free _, _) => abs_args abstr (d-1, cvs) ct cx
  20.232 +            | _ => fresh_abstraction dcvs ct cx)))
  20.233 +  in abstr (depth, []) end
  20.234 +
  20.235 +val cimp = Thm.cterm_of @{theory} @{const Pure.imp}
  20.236 +
  20.237 +fun deepen depth f x =
  20.238 +  if depth = 0 then f depth x
  20.239 +  else (case try (f depth) x of SOME y => y | NONE => deepen (depth - 1) f x)
  20.240 +
  20.241 +fun with_prems depth thms f ct =
  20.242 +  fold_rev (Thm.mk_binop cimp o Thm.cprop_of) thms ct
  20.243 +  |> deepen depth f
  20.244 +  |> fold (fn prem => fn th => Thm.implies_elim th prem) thms
  20.245 +
  20.246 +in
  20.247 +
  20.248 +fun by_abstraction depth mode ctxt thms prove =
  20.249 +  with_prems depth thms (fn d => fn ct =>
  20.250 +    let val (cu, cx) = abstract d mode ct (abs_context ctxt)
  20.251 +    in abs_instantiate cx (prove (context_of cx) cu) end)
  20.252 +
  20.253 +end
  20.254 +
  20.255 +
  20.256 +
  20.257 +(* a faster COMP *)
  20.258 +
  20.259 +type compose_data = cterm list * (cterm -> cterm list) * thm
  20.260 +
  20.261 +fun list2 (x, y) = [x, y]
  20.262 +
  20.263 +fun precompose f rule = (f (Thm.cprem_of rule 1), f, rule)
  20.264 +fun precompose2 f rule = precompose (list2 o f) rule
  20.265 +
  20.266 +fun compose (cvs, f, rule) thm =
  20.267 +  discharge thm (Thm.instantiate ([], cvs ~~ f (Thm.cprop_of thm)) rule)
  20.268 +
  20.269 +
  20.270 +
  20.271 +(* unfolding of 'distinct' *)
  20.272 +
  20.273 +local
  20.274 +  val set1 = @{lemma "x ~: set [] == ~False" by simp}
  20.275 +  val set2 = @{lemma "x ~: set [x] == False" by simp}
  20.276 +  val set3 = @{lemma "x ~: set [y] == x ~= y" by simp}
  20.277 +  val set4 = @{lemma "x ~: set (x # ys) == False" by simp}
  20.278 +  val set5 = @{lemma "x ~: set (y # ys) == x ~= y & x ~: set ys" by simp}
  20.279 +
  20.280 +  fun set_conv ct =
  20.281 +    (Conv.rewrs_conv [set1, set2, set3, set4] else_conv
  20.282 +    (Conv.rewr_conv set5 then_conv Conv.arg_conv set_conv)) ct
  20.283 +
  20.284 +  val dist1 = @{lemma "distinct [] == ~False" by (simp add: distinct_def)}
  20.285 +  val dist2 = @{lemma "distinct [x] == ~False" by (simp add: distinct_def)}
  20.286 +  val dist3 = @{lemma "distinct (x # xs) == x ~: set xs & distinct xs"
  20.287 +    by (simp add: distinct_def)}
  20.288 +
  20.289 +  fun binop_conv cv1 cv2 = Conv.combination_conv (Conv.arg_conv cv1) cv2
  20.290 +in
  20.291 +fun unfold_distinct_conv ct =
  20.292 +  (Conv.rewrs_conv [dist1, dist2] else_conv
  20.293 +  (Conv.rewr_conv dist3 then_conv binop_conv set_conv unfold_distinct_conv)) ct
  20.294 +end
  20.295 +
  20.296 +
  20.297 +
  20.298 +(* simpset *)
  20.299 +
  20.300 +local
  20.301 +  val antisym_le1 = mk_meta_eq @{thm order_class.antisym_conv}
  20.302 +  val antisym_le2 = mk_meta_eq @{thm linorder_class.antisym_conv2}
  20.303 +  val antisym_less1 = mk_meta_eq @{thm linorder_class.antisym_conv1}
  20.304 +  val antisym_less2 = mk_meta_eq @{thm linorder_class.antisym_conv3}
  20.305 +
  20.306 +  fun eq_prop t thm = HOLogic.mk_Trueprop t aconv Thm.prop_of thm
  20.307 +  fun dest_binop ((c as Const _) $ t $ u) = (c, t, u)
  20.308 +    | dest_binop t = raise TERM ("dest_binop", [t])
  20.309 +
  20.310 +  fun prove_antisym_le ctxt t =
  20.311 +    let
  20.312 +      val (le, r, s) = dest_binop t
  20.313 +      val less = Const (@{const_name less}, Term.fastype_of le)
  20.314 +      val prems = Simplifier.prems_of ctxt
  20.315 +    in
  20.316 +      (case find_first (eq_prop (le $ s $ r)) prems of
  20.317 +        NONE =>
  20.318 +          find_first (eq_prop (HOLogic.mk_not (less $ r $ s))) prems
  20.319 +          |> Option.map (fn thm => thm RS antisym_less1)
  20.320 +      | SOME thm => SOME (thm RS antisym_le1))
  20.321 +    end
  20.322 +    handle THM _ => NONE
  20.323 +
  20.324 +  fun prove_antisym_less ctxt t =
  20.325 +    let
  20.326 +      val (less, r, s) = dest_binop (HOLogic.dest_not t)
  20.327 +      val le = Const (@{const_name less_eq}, Term.fastype_of less)
  20.328 +      val prems = Simplifier.prems_of ctxt
  20.329 +    in
  20.330 +      (case find_first (eq_prop (le $ r $ s)) prems of
  20.331 +        NONE =>
  20.332 +          find_first (eq_prop (HOLogic.mk_not (less $ s $ r))) prems
  20.333 +          |> Option.map (fn thm => thm RS antisym_less2)
  20.334 +      | SOME thm => SOME (thm RS antisym_le2))
  20.335 +  end
  20.336 +  handle THM _ => NONE
  20.337 +
  20.338 +  val basic_simpset =
  20.339 +    simpset_of (put_simpset HOL_ss @{context}
  20.340 +      addsimps @{thms field_simps}
  20.341 +      addsimps [@{thm times_divide_eq_right}, @{thm times_divide_eq_left}]
  20.342 +      addsimps @{thms arith_special} addsimps @{thms arith_simps}
  20.343 +      addsimps @{thms rel_simps}
  20.344 +      addsimps @{thms array_rules}
  20.345 +      addsimps @{thms term_true_def} addsimps @{thms term_false_def}
  20.346 +      addsimps @{thms z3div_def} addsimps @{thms z3mod_def}
  20.347 +      addsimprocs [@{simproc binary_int_div}, @{simproc binary_int_mod}]
  20.348 +      addsimprocs [
  20.349 +        Simplifier.simproc_global @{theory} "fast_int_arith" [
  20.350 +          "(m::int) < n", "(m::int) <= n", "(m::int) = n"] Lin_Arith.simproc,
  20.351 +        Simplifier.simproc_global @{theory} "antisym_le" ["(x::'a::order) <= y"]
  20.352 +          prove_antisym_le,
  20.353 +        Simplifier.simproc_global @{theory} "antisym_less" ["~ (x::'a::linorder) < y"]
  20.354 +          prove_antisym_less])
  20.355 +
  20.356 +  structure Simpset = Generic_Data
  20.357 +  (
  20.358 +    type T = simpset
  20.359 +    val empty = basic_simpset
  20.360 +    val extend = I
  20.361 +    val merge = Simplifier.merge_ss
  20.362 +  )
  20.363 +in
  20.364 +
  20.365 +fun add_simproc simproc context =
  20.366 +  Simpset.map (simpset_map (Context.proof_of context)
  20.367 +    (fn ctxt => ctxt addsimprocs [simproc])) context
  20.368 +
  20.369 +fun make_simpset ctxt rules =
  20.370 +  simpset_of (put_simpset (Simpset.get (Context.Proof ctxt)) ctxt addsimps rules)
  20.371 +
  20.372 +end
  20.373 +
  20.374 +end
    21.1 --- a/src/HOL/Main.thy	Thu Aug 28 00:40:37 2014 +0200
    21.2 +++ b/src/HOL/Main.thy	Thu Aug 28 00:40:37 2014 +0200
    21.3 @@ -1,7 +1,7 @@
    21.4  header {* Main HOL *}
    21.5  
    21.6  theory Main
    21.7 -imports Predicate_Compile Quickcheck_Narrowing Extraction Lifting_Sum Coinduction Nitpick BNF_GFP SMT
    21.8 +imports Predicate_Compile Quickcheck_Narrowing Extraction Lifting_Sum Coinduction Nitpick BNF_GFP
    21.9  begin
   21.10  
   21.11  text {*
    22.1 --- a/src/HOL/Real.thy	Thu Aug 28 00:40:37 2014 +0200
    22.2 +++ b/src/HOL/Real.thy	Thu Aug 28 00:40:37 2014 +0200
    22.3 @@ -2180,8 +2180,6 @@
    22.4  
    22.5  subsection {* Setup for SMT *}
    22.6  
    22.7 -ML_file "Tools/SMT/smt_real.ML"
    22.8 -setup SMT_Real.setup
    22.9  ML_file "Tools/SMT2/smt2_real.ML"
   22.10  ML_file "Tools/SMT2/z3_new_real.ML"
   22.11  
    23.1 --- a/src/HOL/SMT.thy	Thu Aug 28 00:40:37 2014 +0200
    23.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
    23.3 @@ -1,426 +0,0 @@
    23.4 -(*  Title:      HOL/SMT.thy
    23.5 -    Author:     Sascha Boehme, TU Muenchen
    23.6 -*)
    23.7 -
    23.8 -header {* Bindings to Satisfiability Modulo Theories (SMT) solvers *}
    23.9 -
   23.10 -theory SMT
   23.11 -imports Record
   23.12 -keywords "smt_status" :: diag
   23.13 -begin
   23.14 -
   23.15 -ML_file "Tools/SMT/smt_utils.ML"
   23.16 -ML_file "Tools/SMT/smt_failure.ML"
   23.17 -ML_file "Tools/SMT/smt_config.ML"
   23.18 -
   23.19 -
   23.20 -subsection {* Triggers for quantifier instantiation *}
   23.21 -
   23.22 -text {*
   23.23 -Some SMT solvers support patterns as a quantifier instantiation
   23.24 -heuristics.  Patterns may either be positive terms (tagged by "pat")
   23.25 -triggering quantifier instantiations -- when the solver finds a
   23.26 -term matching a positive pattern, it instantiates the corresponding
   23.27 -quantifier accordingly -- or negative terms (tagged by "nopat")
   23.28 -inhibiting quantifier instantiations.  A list of patterns
   23.29 -of the same kind is called a multipattern, and all patterns in a
   23.30 -multipattern are considered conjunctively for quantifier instantiation.
   23.31 -A list of multipatterns is called a trigger, and their multipatterns
   23.32 -act disjunctively during quantifier instantiation.  Each multipattern
   23.33 -should mention at least all quantified variables of the preceding
   23.34 -quantifier block.
   23.35 -*}
   23.36 -
   23.37 -typedecl pattern
   23.38 -
   23.39 -consts
   23.40 -  pat :: "'a \<Rightarrow> pattern"
   23.41 -  nopat :: "'a \<Rightarrow> pattern"
   23.42 -
   23.43 -definition trigger :: "pattern list list \<Rightarrow> bool \<Rightarrow> bool" where "trigger _ P = P"
   23.44 -
   23.45 -
   23.46 -subsection {* Quantifier weights *}
   23.47 -
   23.48 -text {*
   23.49 -Weight annotations to quantifiers influence the priority of quantifier
   23.50 -instantiations.  They should be handled with care for solvers, which support
   23.51 -them, because incorrect choices of weights might render a problem unsolvable.
   23.52 -*}
   23.53 -
   23.54 -definition weight :: "int \<Rightarrow> bool \<Rightarrow> bool" where "weight _ P = P"
   23.55 -
   23.56 -text {*
   23.57 -Weights must be non-negative.  The value @{text 0} is equivalent to providing
   23.58 -no weight at all.
   23.59 -
   23.60 -Weights should only be used at quantifiers and only inside triggers (if the
   23.61 -quantifier has triggers).  Valid usages of weights are as follows:
   23.62 -
   23.63 -\begin{itemize}
   23.64 -\item
   23.65 -@{term "\<forall>x. trigger [[pat (P x)]] (weight 2 (P x))"}
   23.66 -\item
   23.67 -@{term "\<forall>x. weight 3 (P x)"}
   23.68 -\end{itemize}
   23.69 -*}
   23.70 -
   23.71 -
   23.72 -subsection {* Higher-order encoding *}
   23.73 -
   23.74 -text {*
   23.75 -Application is made explicit for constants occurring with varying
   23.76 -numbers of arguments.  This is achieved by the introduction of the
   23.77 -following constant.
   23.78 -*}
   23.79 -
   23.80 -definition fun_app where "fun_app f = f"
   23.81 -
   23.82 -text {*
   23.83 -Some solvers support a theory of arrays which can be used to encode
   23.84 -higher-order functions.  The following set of lemmas specifies the
   23.85 -properties of such (extensional) arrays.
   23.86 -*}
   23.87 -
   23.88 -lemmas array_rules = ext fun_upd_apply fun_upd_same fun_upd_other
   23.89 -  fun_upd_upd fun_app_def
   23.90 -
   23.91 -
   23.92 -subsection {* First-order logic *}
   23.93 -
   23.94 -text {*
   23.95 -Some SMT solvers only accept problems in first-order logic, i.e.,
   23.96 -where formulas and terms are syntactically separated. When
   23.97 -translating higher-order into first-order problems, all
   23.98 -uninterpreted constants (those not built-in in the target solver)
   23.99 -are treated as function symbols in the first-order sense.  Their
  23.100 -occurrences as head symbols in atoms (i.e., as predicate symbols) are
  23.101 -turned into terms by logically equating such atoms with @{term True}.
  23.102 -For technical reasons, @{term True} and @{term False} occurring inside
  23.103 -terms are replaced by the following constants.
  23.104 -*}
  23.105 -
  23.106 -definition term_true where "term_true = True"
  23.107 -definition term_false where "term_false = False"
  23.108 -
  23.109 -
  23.110 -subsection {* Integer division and modulo for Z3 *}
  23.111 -
  23.112 -definition z3div :: "int \<Rightarrow> int \<Rightarrow> int" where
  23.113 -  "z3div k l = (if 0 \<le> l then k div l else -(k div (-l)))"
  23.114 -
  23.115 -definition z3mod :: "int \<Rightarrow> int \<Rightarrow> int" where
  23.116 -  "z3mod k l = (if 0 \<le> l then k mod l else k mod (-l))"
  23.117 -
  23.118 -
  23.119 -subsection {* Setup *}
  23.120 -
  23.121 -ML_file "Tools/SMT/smt_builtin.ML"
  23.122 -ML_file "Tools/SMT/smt_datatypes.ML"
  23.123 -ML_file "Tools/SMT/smt_normalize.ML"
  23.124 -ML_file "Tools/SMT/smt_translate.ML"
  23.125 -ML_file "Tools/SMT/smt_solver.ML"
  23.126 -ML_file "Tools/SMT/smtlib_interface.ML"
  23.127 -ML_file "Tools/SMT/z3_interface.ML"
  23.128 -ML_file "Tools/SMT/z3_proof_parser.ML"
  23.129 -ML_file "Tools/SMT/z3_proof_tools.ML"
  23.130 -ML_file "Tools/SMT/z3_proof_literals.ML"
  23.131 -ML_file "Tools/SMT/z3_proof_methods.ML"
  23.132 -named_theorems z3_simp "simplification rules for Z3 proof reconstruction"
  23.133 -ML_file "Tools/SMT/z3_proof_reconstruction.ML"
  23.134 -ML_file "Tools/SMT/z3_model.ML"
  23.135 -ML_file "Tools/SMT/smt_setup_solvers.ML"
  23.136 -
  23.137 -setup {*
  23.138 -  SMT_Config.setup #>
  23.139 -  SMT_Normalize.setup #>
  23.140 -  SMTLIB_Interface.setup #>
  23.141 -  Z3_Interface.setup #>
  23.142 -  SMT_Setup_Solvers.setup
  23.143 -*}
  23.144 -
  23.145 -method_setup smt = {*
  23.146 -  Scan.optional Attrib.thms [] >>
  23.147 -    (fn thms => fn ctxt =>
  23.148 -      METHOD (fn facts => HEADGOAL (SMT_Solver.smt_tac ctxt (thms @ facts))))
  23.149 -*} "apply an SMT solver to the current goal"
  23.150 -
  23.151 -
  23.152 -subsection {* Configuration *}
  23.153 -
  23.154 -text {*
  23.155 -The current configuration can be printed by the command
  23.156 -@{text smt_status}, which shows the values of most options.
  23.157 -*}
  23.158 -
  23.159 -
  23.160 -
  23.161 -subsection {* General configuration options *}
  23.162 -
  23.163 -text {*
  23.164 -The option @{text smt_solver} can be used to change the target SMT
  23.165 -solver.  The possible values can be obtained from the @{text smt_status}
  23.166 -command.
  23.167 -
  23.168 -Due to licensing restrictions, Yices and Z3 are not installed/enabled
  23.169 -by default.  Z3 is free for non-commercial applications and can be enabled
  23.170 -by setting Isabelle system option @{text z3_non_commercial} to @{text yes}.
  23.171 -*}
  23.172 -
  23.173 -declare [[ smt_solver = z3 ]]
  23.174 -
  23.175 -text {*
  23.176 -Since SMT solvers are potentially non-terminating, there is a timeout
  23.177 -(given in seconds) to restrict their runtime.  A value greater than
  23.178 -120 (seconds) is in most cases not advisable.
  23.179 -*}
  23.180 -
  23.181 -declare [[ smt_timeout = 20 ]]
  23.182 -
  23.183 -text {*
  23.184 -SMT solvers apply randomized heuristics.  In case a problem is not
  23.185 -solvable by an SMT solver, changing the following option might help.
  23.186 -*}
  23.187 -
  23.188 -declare [[ smt_random_seed = 1 ]]
  23.189 -
  23.190 -text {*
  23.191 -In general, the binding to SMT solvers runs as an oracle, i.e, the SMT
  23.192 -solvers are fully trusted without additional checks.  The following
  23.193 -option can cause the SMT solver to run in proof-producing mode, giving
  23.194 -a checkable certificate.  This is currently only implemented for Z3.
  23.195 -*}
  23.196 -
  23.197 -declare [[ smt_oracle = false ]]
  23.198 -
  23.199 -text {*
  23.200 -Each SMT solver provides several commandline options to tweak its
  23.201 -behaviour.  They can be passed to the solver by setting the following
  23.202 -options.
  23.203 -*}
  23.204 -
  23.205 -declare [[ cvc3_options = "" ]]
  23.206 -declare [[ yices_options = "" ]]
  23.207 -declare [[ z3_options = "" ]]
  23.208 -
  23.209 -text {*
  23.210 -Enable the following option to use built-in support for datatypes and
  23.211 -records.  Currently, this is only implemented for Z3 running in oracle
  23.212 -mode.
  23.213 -*}
  23.214 -
  23.215 -declare [[ smt_datatypes = false ]]
  23.216 -
  23.217 -text {*
  23.218 -The SMT method provides an inference mechanism to detect simple triggers
  23.219 -in quantified formulas, which might increase the number of problems
  23.220 -solvable by SMT solvers (note: triggers guide quantifier instantiations
  23.221 -in the SMT solver).  To turn it on, set the following option.
  23.222 -*}
  23.223 -
  23.224 -declare [[ smt_infer_triggers = false ]]
  23.225 -
  23.226 -text {*
  23.227 -The SMT method monomorphizes the given facts, that is, it tries to
  23.228 -instantiate all schematic type variables with fixed types occurring
  23.229 -in the problem.  This is a (possibly nonterminating) fixed-point
  23.230 -construction whose cycles are limited by the following option.
  23.231 -*}
  23.232 -
  23.233 -declare [[ monomorph_max_rounds = 5 ]]
  23.234 -
  23.235 -text {*
  23.236 -In addition, the number of generated monomorphic instances is limited
  23.237 -by the following option.
  23.238 -*}
  23.239 -
  23.240 -declare [[ monomorph_max_new_instances = 500 ]]
  23.241 -
  23.242 -
  23.243 -
  23.244 -subsection {* Certificates *}
  23.245 -
  23.246 -text {*
  23.247 -By setting the option @{text smt_certificates} to the name of a file,
  23.248 -all following applications of an SMT solver a cached in that file.
  23.249 -Any further application of the same SMT solver (using the very same
  23.250 -configuration) re-uses the cached certificate instead of invoking the
  23.251 -solver.  An empty string disables caching certificates.
  23.252 -
  23.253 -The filename should be given as an explicit path.  It is good
  23.254 -practice to use the name of the current theory (with ending
  23.255 -@{text ".certs"} instead of @{text ".thy"}) as the certificates file.
  23.256 -Certificate files should be used at most once in a certain theory context,
  23.257 -to avoid race conditions with other concurrent accesses.
  23.258 -*}
  23.259 -
  23.260 -declare [[ smt_certificates = "" ]]
  23.261 -
  23.262 -text {*
  23.263 -The option @{text smt_read_only_certificates} controls whether only
  23.264 -stored certificates are should be used or invocation of an SMT solver
  23.265 -is allowed.  When set to @{text true}, no SMT solver will ever be
  23.266 -invoked and only the existing certificates found in the configured
  23.267 -cache are used;  when set to @{text false} and there is no cached
  23.268 -certificate for some proposition, then the configured SMT solver is
  23.269 -invoked.
  23.270 -*}
  23.271 -
  23.272 -declare [[ smt_read_only_certificates = false ]]
  23.273 -
  23.274 -
  23.275 -
  23.276 -subsection {* Tracing *}
  23.277 -
  23.278 -text {*
  23.279 -The SMT method, when applied, traces important information.  To
  23.280 -make it entirely silent, set the following option to @{text false}.
  23.281 -*}
  23.282 -
  23.283 -declare [[ smt_verbose = true ]]
  23.284 -
  23.285 -text {*
  23.286 -For tracing the generated problem file given to the SMT solver as
  23.287 -well as the returned result of the solver, the option
  23.288 -@{text smt_trace} should be set to @{text true}.
  23.289 -*}
  23.290 -
  23.291 -declare [[ smt_trace = false ]]
  23.292 -
  23.293 -text {*
  23.294 -From the set of assumptions given to the SMT solver, those assumptions
  23.295 -used in the proof are traced when the following option is set to
  23.296 -@{term true}.  This only works for Z3 when it runs in non-oracle mode
  23.297 -(see options @{text smt_solver} and @{text smt_oracle} above).
  23.298 -*}
  23.299 -
  23.300 -declare [[ smt_trace_used_facts = false ]]
  23.301 -
  23.302 -
  23.303 -
  23.304 -subsection {* Schematic rules for Z3 proof reconstruction *}
  23.305 -
  23.306 -text {*
  23.307 -Several prof rules of Z3 are not very well documented.  There are two
  23.308 -lemma groups which can turn failing Z3 proof reconstruction attempts
  23.309 -into succeeding ones: the facts in @{text z3_rule} are tried prior to
  23.310 -any implemented reconstruction procedure for all uncertain Z3 proof
  23.311 -rules;  the facts in @{text z3_simp} are only fed to invocations of
  23.312 -the simplifier when reconstructing theory-specific proof steps.
  23.313 -*}
  23.314 -
  23.315 -lemmas [z3_rule] =
  23.316 -  refl eq_commute conj_commute disj_commute simp_thms nnf_simps
  23.317 -  ring_distribs field_simps times_divide_eq_right times_divide_eq_left
  23.318 -  if_True if_False not_not
  23.319 -
  23.320 -lemma [z3_rule]:
  23.321 -  "(P \<and> Q) = (\<not>(\<not>P \<or> \<not>Q))"
  23.322 -  "(P \<and> Q) = (\<not>(\<not>Q \<or> \<not>P))"
  23.323 -  "(\<not>P \<and> Q) = (\<not>(P \<or> \<not>Q))"
  23.324 -  "(\<not>P \<and> Q) = (\<not>(\<not>Q \<or> P))"
  23.325 -  "(P \<and> \<not>Q) = (\<not>(\<not>P \<or> Q))"
  23.326 -  "(P \<and> \<not>Q) = (\<not>(Q \<or> \<not>P))"
  23.327 -  "(\<not>P \<and> \<not>Q) = (\<not>(P \<or> Q))"
  23.328 -  "(\<not>P \<and> \<not>Q) = (\<not>(Q \<or> P))"
  23.329 -  by auto
  23.330 -
  23.331 -lemma [z3_rule]:
  23.332 -  "(P \<longrightarrow> Q) = (Q \<or> \<not>P)"
  23.333 -  "(\<not>P \<longrightarrow> Q) = (P \<or> Q)"
  23.334 -  "(\<not>P \<longrightarrow> Q) = (Q \<or> P)"
  23.335 -  "(True \<longrightarrow> P) = P"
  23.336 -  "(P \<longrightarrow> True) = True"
  23.337 -  "(False \<longrightarrow> P) = True"
  23.338 -  "(P \<longrightarrow> P) = True"
  23.339 -  by auto
  23.340 -
  23.341 -lemma [z3_rule]:
  23.342 -  "((P = Q) \<longrightarrow> R) = (R | (Q = (\<not>P)))"
  23.343 -  by auto
  23.344 -
  23.345 -lemma [z3_rule]:
  23.346 -  "(\<not>True) = False"
  23.347 -  "(\<not>False) = True"
  23.348 -  "(x = x) = True"
  23.349 -  "(P = True) = P"
  23.350 -  "(True = P) = P"
  23.351 -  "(P = False) = (\<not>P)"
  23.352 -  "(False = P) = (\<not>P)"
  23.353 -  "((\<not>P) = P) = False"
  23.354 -  "(P = (\<not>P)) = False"
  23.355 -  "((\<not>P) = (\<not>Q)) = (P = Q)"
  23.356 -  "\<not>(P = (\<not>Q)) = (P = Q)"
  23.357 -  "\<not>((\<not>P) = Q) = (P = Q)"
  23.358 -  "(P \<noteq> Q) = (Q = (\<not>P))"
  23.359 -  "(P = Q) = ((\<not>P \<or> Q) \<and> (P \<or> \<not>Q))"
  23.360 -  "(P \<noteq> Q) = ((\<not>P \<or> \<not>Q) \<and> (P \<or> Q))"
  23.361 -  by auto
  23.362 -
  23.363 -lemma [z3_rule]:
  23.364 -  "(if P then P else \<not>P) = True"
  23.365 -  "(if \<not>P then \<not>P else P) = True"
  23.366 -  "(if P then True else False) = P"
  23.367 -  "(if P then False else True) = (\<not>P)"
  23.368 -  "(if P then Q else True) = ((\<not>P) \<or> Q)"
  23.369 -  "(if P then Q else True) = (Q \<or> (\<not>P))"
  23.370 -  "(if P then Q else \<not>Q) = (P = Q)"
  23.371 -  "(if P then Q else \<not>Q) = (Q = P)"
  23.372 -  "(if P then \<not>Q else Q) = (P = (\<not>Q))"
  23.373 -  "(if P then \<not>Q else Q) = ((\<not>Q) = P)"
  23.374 -  "(if \<not>P then x else y) = (if P then y else x)"
  23.375 -  "(if P then (if Q then x else y) else x) = (if P \<and> (\<not>Q) then y else x)"
  23.376 -  "(if P then (if Q then x else y) else x) = (if (\<not>Q) \<and> P then y else x)"
  23.377 -  "(if P then (if Q then x else y) else y) = (if P \<and> Q then x else y)"
  23.378 -  "(if P then (if Q then x else y) else y) = (if Q \<and> P then x else y)"
  23.379 -  "(if P then x else if P then y else z) = (if P then x else z)"
  23.380 -  "(if P then x else if Q then x else y) = (if P \<or> Q then x else y)"
  23.381 -  "(if P then x else if Q then x else y) = (if Q \<or> P then x else y)"
  23.382 -  "(if P then x = y else x = z) = (x = (if P then y else z))"
  23.383 -  "(if P then x = y else y = z) = (y = (if P then x else z))"
  23.384 -  "(if P then x = y else z = y) = (y = (if P then x else z))"
  23.385 -  by auto
  23.386 -
  23.387 -lemma [z3_rule]:
  23.388 -  "0 + (x::int) = x"
  23.389 -  "x + 0 = x"
  23.390 -  "x + x = 2 * x"
  23.391 -  "0 * x = 0"
  23.392 -  "1 * x = x"
  23.393 -  "x + y = y + x"
  23.394 -  by auto
  23.395 -
  23.396 -lemma [z3_rule]:  (* for def-axiom *)
  23.397 -  "P = Q \<or> P \<or> Q"
  23.398 -  "P = Q \<or> \<not>P \<or> \<not>Q"
  23.399 -  "(\<not>P) = Q \<or> \<not>P \<or> Q"
  23.400 -  "(\<not>P) = Q \<or> P \<or> \<not>Q"
  23.401 -  "P = (\<not>Q) \<or> \<not>P \<or> Q"
  23.402 -  "P = (\<not>Q) \<or> P \<or> \<not>Q"
  23.403 -  "P \<noteq> Q \<or> P \<or> \<not>Q"
  23.404 -  "P \<noteq> Q \<or> \<not>P \<or> Q"
  23.405 -  "P \<noteq> (\<not>Q) \<or> P \<or> Q"
  23.406 -  "(\<not>P) \<noteq> Q \<or> P \<or> Q"
  23.407 -  "P \<or> Q \<or> P \<noteq> (\<not>Q)"
  23.408 -  "P \<or> Q \<or> (\<not>P) \<noteq> Q"
  23.409 -  "P \<or> \<not>Q \<or> P \<noteq> Q"
  23.410 -  "\<not>P \<or> Q \<or> P \<noteq> Q"
  23.411 -  "P \<or> y = (if P then x else y)"
  23.412 -  "P \<or> (if P then x else y) = y"
  23.413 -  "\<not>P \<or> x = (if P then x else y)"
  23.414 -  "\<not>P \<or>  (if P then x else y) = x"
  23.415 -  "P \<or> R \<or> \<not>(if P then Q else R)"
  23.416 -  "\<not>P \<or> Q \<or> \<not>(if P then Q else R)"
  23.417 -  "\<not>(if P then Q else R) \<or> \<not>P \<or> Q"
  23.418 -  "\<not>(if P then Q else R) \<or> P \<or> R"
  23.419 -  "(if P then Q else R) \<or> \<not>P \<or> \<not>Q"
  23.420 -  "(if P then Q else R) \<or> P \<or> \<not>R"
  23.421 -  "(if P then \<not>Q else R) \<or> \<not>P \<or> Q"
  23.422 -  "(if P then Q else \<not>R) \<or> P \<or> R"
  23.423 -  by auto
  23.424 -
  23.425 -hide_type (open) pattern
  23.426 -hide_const fun_app term_true term_false z3div z3mod
  23.427 -hide_const (open) trigger pat nopat weight
  23.428 -
  23.429 -end
    24.1 --- a/src/HOL/Tools/SMT/smt_builtin.ML	Thu Aug 28 00:40:37 2014 +0200
    24.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
    24.3 @@ -1,231 +0,0 @@
    24.4 -(*  Title:      HOL/Tools/SMT/smt_builtin.ML
    24.5 -    Author:     Sascha Boehme, TU Muenchen
    24.6 -
    24.7 -Tables of types and terms directly supported by SMT solvers.
    24.8 -*)
    24.9 -
   24.10 -signature SMT_BUILTIN =
   24.11 -sig
   24.12 -  (*for experiments*)
   24.13 -  val filter_builtins: (typ -> bool) -> Proof.context -> Proof.context
   24.14 -
   24.15 -  (*built-in types*)
   24.16 -  val add_builtin_typ: SMT_Utils.class ->
   24.17 -    typ * (typ -> string option) * (typ -> int -> string option) ->
   24.18 -    Context.generic -> Context.generic
   24.19 -  val add_builtin_typ_ext: typ * (typ -> bool) -> Context.generic ->
   24.20 -    Context.generic
   24.21 -  val dest_builtin_typ: Proof.context -> typ -> string option
   24.22 -  val is_builtin_typ_ext: Proof.context -> typ -> bool
   24.23 -
   24.24 -  (*built-in numbers*)
   24.25 -  val dest_builtin_num: Proof.context -> term -> (string * typ) option
   24.26 -  val is_builtin_num: Proof.context -> term -> bool
   24.27 -  val is_builtin_num_ext: Proof.context -> term -> bool
   24.28 -
   24.29 -  (*built-in functions*)
   24.30 -  type 'a bfun = Proof.context -> typ -> term list -> 'a
   24.31 -  type bfunr = string * int * term list * (term list -> term)
   24.32 -  val add_builtin_fun: SMT_Utils.class ->
   24.33 -    (string * typ) * bfunr option bfun -> Context.generic -> Context.generic
   24.34 -  val add_builtin_fun': SMT_Utils.class -> term * string -> Context.generic ->
   24.35 -    Context.generic
   24.36 -  val add_builtin_fun_ext: (string * typ) * term list bfun ->
   24.37 -    Context.generic -> Context.generic
   24.38 -  val add_builtin_fun_ext': string * typ -> Context.generic -> Context.generic
   24.39 -  val add_builtin_fun_ext'': string -> Context.generic -> Context.generic
   24.40 -  val dest_builtin_fun: Proof.context -> string * typ -> term list ->
   24.41 -    bfunr option
   24.42 -  val dest_builtin_eq: Proof.context -> term -> term -> bfunr option
   24.43 -  val dest_builtin_pred: Proof.context -> string * typ -> term list ->
   24.44 -    bfunr option
   24.45 -  val dest_builtin_conn: Proof.context -> string * typ -> term list ->
   24.46 -    bfunr option
   24.47 -  val dest_builtin: Proof.context -> string * typ -> term list -> bfunr option
   24.48 -  val dest_builtin_ext: Proof.context -> string * typ -> term list ->
   24.49 -    term list option
   24.50 -  val is_builtin_fun: Proof.context -> string * typ -> term list -> bool
   24.51 -  val is_builtin_fun_ext: Proof.context -> string * typ -> term list -> bool
   24.52 -end
   24.53 -
   24.54 -structure SMT_Builtin: SMT_BUILTIN =
   24.55 -struct
   24.56 -
   24.57 -
   24.58 -(* built-in tables *)
   24.59 -
   24.60 -datatype ('a, 'b) kind = Ext of 'a | Int of 'b
   24.61 -
   24.62 -type ('a, 'b) ttab = ((typ * ('a, 'b) kind) Ord_List.T) SMT_Utils.dict 
   24.63 -
   24.64 -fun typ_ord ((T, _), (U, _)) =
   24.65 -  let
   24.66 -    fun tord (TVar _, Type _) = GREATER
   24.67 -      | tord (Type _, TVar _) = LESS
   24.68 -      | tord (Type (n, Ts), Type (m, Us)) =
   24.69 -          if n = m then list_ord tord (Ts, Us)
   24.70 -          else Term_Ord.typ_ord (T, U)
   24.71 -      | tord TU = Term_Ord.typ_ord TU
   24.72 -  in tord (T, U) end
   24.73 -
   24.74 -fun insert_ttab cs T f =
   24.75 -  SMT_Utils.dict_map_default (cs, [])
   24.76 -    (Ord_List.insert typ_ord (perhaps (try Logic.varifyT_global) T, f))
   24.77 -
   24.78 -fun merge_ttab ttabp =
   24.79 -  SMT_Utils.dict_merge (Ord_List.merge typ_ord) ttabp
   24.80 -
   24.81 -fun lookup_ttab ctxt ttab T =
   24.82 -  let fun match (U, _) = Sign.typ_instance (Proof_Context.theory_of ctxt) (T, U)
   24.83 -  in
   24.84 -    get_first (find_first match)
   24.85 -      (SMT_Utils.dict_lookup ttab (SMT_Config.solver_class_of ctxt))
   24.86 -  end
   24.87 -
   24.88 -type ('a, 'b) btab = ('a, 'b) ttab Symtab.table
   24.89 -
   24.90 -fun insert_btab cs n T f =
   24.91 -  Symtab.map_default (n, []) (insert_ttab cs T f)
   24.92 -
   24.93 -fun merge_btab btabp = Symtab.join (K merge_ttab) btabp
   24.94 -
   24.95 -fun lookup_btab ctxt btab (n, T) =
   24.96 -  (case Symtab.lookup btab n of
   24.97 -    NONE => NONE
   24.98 -  | SOME ttab => lookup_ttab ctxt ttab T)
   24.99 -
  24.100 -type 'a bfun = Proof.context -> typ -> term list -> 'a
  24.101 -
  24.102 -type bfunr = string * int * term list * (term list -> term)
  24.103 -
  24.104 -structure Builtins = Generic_Data
  24.105 -(
  24.106 -  type T =
  24.107 -    (typ -> bool, (typ -> string option) * (typ -> int -> string option)) ttab *
  24.108 -    (term list bfun, bfunr option bfun) btab
  24.109 -  val empty = ([], Symtab.empty)
  24.110 -  val extend = I
  24.111 -  fun merge ((t1, b1), (t2, b2)) = (merge_ttab (t1, t2), merge_btab (b1, b2))
  24.112 -)
  24.113 -
  24.114 -fun filter_ttab keep_T = map (apsnd (filter (keep_T o fst)))
  24.115 -
  24.116 -fun filter_builtins keep_T =
  24.117 -  Context.proof_map (Builtins.map (fn (ttab, btab) =>
  24.118 -    (filter_ttab keep_T ttab, Symtab.map (K (filter_ttab keep_T)) btab)))
  24.119 -
  24.120 -
  24.121 -(* built-in types *)
  24.122 -
  24.123 -fun add_builtin_typ cs (T, f, g) =
  24.124 -  Builtins.map (apfst (insert_ttab cs T (Int (f, g))))
  24.125 -
  24.126 -fun add_builtin_typ_ext (T, f) =
  24.127 -  Builtins.map (apfst (insert_ttab SMT_Utils.basicC T (Ext f)))
  24.128 -
  24.129 -fun lookup_builtin_typ ctxt =
  24.130 -  lookup_ttab ctxt (fst (Builtins.get (Context.Proof ctxt)))
  24.131 -
  24.132 -fun dest_builtin_typ ctxt T =
  24.133 -  (case lookup_builtin_typ ctxt T of
  24.134 -    SOME (_, Int (f, _)) => f T
  24.135 -  | _ => NONE) 
  24.136 -
  24.137 -fun is_builtin_typ_ext ctxt T =
  24.138 -  (case lookup_builtin_typ ctxt T of
  24.139 -    SOME (_, Int (f, _)) => is_some (f T)
  24.140 -  | SOME (_, Ext f) => f T
  24.141 -  | NONE => false)
  24.142 -
  24.143 -
  24.144 -(* built-in numbers *)
  24.145 -
  24.146 -fun dest_builtin_num ctxt t =
  24.147 -  (case try HOLogic.dest_number t of
  24.148 -    NONE => NONE
  24.149 -  | SOME (T, i) =>
  24.150 -      if i < 0 then NONE else
  24.151 -        (case lookup_builtin_typ ctxt T of
  24.152 -          SOME (_, Int (_, g)) => g T i |> Option.map (rpair T)
  24.153 -        | _ => NONE))
  24.154 -
  24.155 -val is_builtin_num = is_some oo dest_builtin_num
  24.156 -
  24.157 -fun is_builtin_num_ext ctxt t =
  24.158 -  (case try HOLogic.dest_number t of
  24.159 -    NONE => false
  24.160 -  | SOME (T, _) => is_builtin_typ_ext ctxt T)
  24.161 -
  24.162 -
  24.163 -(* built-in functions *)
  24.164 -
  24.165 -fun add_builtin_fun cs ((n, T), f) =
  24.166 -  Builtins.map (apsnd (insert_btab cs n T (Int f)))
  24.167 -
  24.168 -fun add_builtin_fun' cs (t, n) =
  24.169 -  let
  24.170 -    val c as (m, T) = Term.dest_Const t
  24.171 -    fun app U ts = Term.list_comb (Const (m, U), ts)
  24.172 -    fun bfun _ U ts = SOME (n, length (Term.binder_types T), ts, app U)
  24.173 -  in add_builtin_fun cs (c, bfun) end
  24.174 -
  24.175 -fun add_builtin_fun_ext ((n, T), f) =
  24.176 -  Builtins.map (apsnd (insert_btab SMT_Utils.basicC n T (Ext f)))
  24.177 -
  24.178 -fun add_builtin_fun_ext' c = add_builtin_fun_ext (c, fn _ => fn _ => I)
  24.179 -
  24.180 -fun add_builtin_fun_ext'' n context =
  24.181 -  let val thy = Context.theory_of context
  24.182 -  in add_builtin_fun_ext' (n, Sign.the_const_type thy n) context end
  24.183 -
  24.184 -fun lookup_builtin_fun ctxt =
  24.185 -  lookup_btab ctxt (snd (Builtins.get (Context.Proof ctxt)))
  24.186 -
  24.187 -fun dest_builtin_fun ctxt (c as (_, T)) ts =
  24.188 -  (case lookup_builtin_fun ctxt c of
  24.189 -    SOME (_, Int f) => f ctxt T ts
  24.190 -  | _ => NONE)
  24.191 -
  24.192 -fun dest_builtin_eq ctxt t u =
  24.193 -  let
  24.194 -    val aT = TFree (Name.aT, @{sort type})
  24.195 -    val c = (@{const_name HOL.eq}, aT --> aT --> @{typ bool})
  24.196 -    fun mk ts = Term.list_comb (HOLogic.eq_const (Term.fastype_of (hd ts)), ts)
  24.197 -  in
  24.198 -    dest_builtin_fun ctxt c []
  24.199 -    |> Option.map (fn (n, i, _, _) => (n, i, [t, u], mk))
  24.200 -  end
  24.201 -
  24.202 -fun special_builtin_fun pred ctxt (c as (_, T)) ts =
  24.203 -  if pred (Term.body_type T, Term.binder_types T) then
  24.204 -    dest_builtin_fun ctxt c ts
  24.205 -  else NONE
  24.206 -
  24.207 -fun dest_builtin_pred ctxt = special_builtin_fun (equal @{typ bool} o fst) ctxt
  24.208 -
  24.209 -fun dest_builtin_conn ctxt =
  24.210 -  special_builtin_fun (forall (equal @{typ bool}) o (op ::)) ctxt
  24.211 -
  24.212 -fun dest_builtin ctxt c ts =
  24.213 -  let val t = Term.list_comb (Const c, ts)
  24.214 -  in
  24.215 -    (case dest_builtin_num ctxt t of
  24.216 -      SOME (n, _) => SOME (n, 0, [], K t)
  24.217 -    | NONE => dest_builtin_fun ctxt c ts)
  24.218 -  end
  24.219 -
  24.220 -fun dest_builtin_fun_ext ctxt (c as (_, T)) ts =    
  24.221 -  (case lookup_builtin_fun ctxt c of
  24.222 -    SOME (_, Int f) => f ctxt T ts |> Option.map (fn (_, _, us, _) => us)
  24.223 -  | SOME (_, Ext f) => SOME (f ctxt T ts)
  24.224 -  | NONE => NONE)
  24.225 -
  24.226 -fun dest_builtin_ext ctxt c ts =
  24.227 -  if is_builtin_num_ext ctxt (Term.list_comb (Const c, ts)) then SOME []
  24.228 -  else dest_builtin_fun_ext ctxt c ts
  24.229 -
  24.230 -fun is_builtin_fun ctxt c ts = is_some (dest_builtin_fun ctxt c ts)
  24.231 -
  24.232 -fun is_builtin_fun_ext ctxt c ts = is_some (dest_builtin_fun_ext ctxt c ts)
  24.233 -
  24.234 -end
    25.1 --- a/src/HOL/Tools/SMT/smt_config.ML	Thu Aug 28 00:40:37 2014 +0200
    25.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
    25.3 @@ -1,254 +0,0 @@
    25.4 -(*  Title:      HOL/Tools/SMT/smt_config.ML
    25.5 -    Author:     Sascha Boehme, TU Muenchen
    25.6 -
    25.7 -Configuration options and diagnostic tools for SMT.
    25.8 -*)
    25.9 -
   25.10 -signature SMT_CONFIG =
   25.11 -sig
   25.12 -  (*solver*)
   25.13 -  type solver_info = {
   25.14 -    name: string,
   25.15 -    class: Proof.context -> SMT_Utils.class,
   25.16 -    avail: unit -> bool,
   25.17 -    options: Proof.context -> string list }
   25.18 -  val add_solver: solver_info -> Context.generic -> Context.generic
   25.19 -  val set_solver_options: string * string -> Context.generic -> Context.generic
   25.20 -  val is_available: Proof.context -> string -> bool
   25.21 -  val available_solvers_of: Proof.context -> string list
   25.22 -  val select_solver: string -> Context.generic -> Context.generic
   25.23 -  val solver_of: Proof.context -> string
   25.24 -  val solver_class_of: Proof.context -> SMT_Utils.class
   25.25 -  val solver_options_of: Proof.context -> string list
   25.26 -
   25.27 -  (*options*)
   25.28 -  val oracle: bool Config.T
   25.29 -  val datatypes: bool Config.T
   25.30 -  val timeout: real Config.T
   25.31 -  val random_seed: int Config.T
   25.32 -  val read_only_certificates: bool Config.T
   25.33 -  val verbose: bool Config.T
   25.34 -  val trace: bool Config.T
   25.35 -  val trace_used_facts: bool Config.T
   25.36 -  val monomorph_limit: int Config.T
   25.37 -  val monomorph_instances: int Config.T
   25.38 -  val infer_triggers: bool Config.T
   25.39 -  val filter_only_facts: bool Config.T
   25.40 -  val debug_files: string Config.T
   25.41 -
   25.42 -  (*tools*)
   25.43 -  val with_timeout: Proof.context -> ('a -> 'b) -> 'a -> 'b
   25.44 -
   25.45 -  (*diagnostics*)
   25.46 -  val trace_msg: Proof.context -> ('a -> string) -> 'a -> unit
   25.47 -  val verbose_msg: Proof.context -> ('a -> string) -> 'a -> unit
   25.48 -
   25.49 -  (*certificates*)
   25.50 -  val select_certificates: string -> Context.generic -> Context.generic
   25.51 -  val certificates_of: Proof.context -> Cache_IO.cache option
   25.52 -
   25.53 -  (*setup*)
   25.54 -  val setup: theory -> theory
   25.55 -  val print_setup: Proof.context -> unit
   25.56 -end
   25.57 -
   25.58 -structure SMT_Config: SMT_CONFIG =
   25.59 -struct
   25.60 -
   25.61 -(* solver *)
   25.62 -
   25.63 -type solver_info = {
   25.64 -  name: string,
   25.65 -  class: Proof.context -> SMT_Utils.class,
   25.66 -  avail: unit -> bool,
   25.67 -  options: Proof.context -> string list }
   25.68 -
   25.69 -(* FIXME just one data slot (record) per program unit *)
   25.70 -structure Solvers = Generic_Data
   25.71 -(
   25.72 -  type T = (solver_info * string list) Symtab.table * string option
   25.73 -  val empty = (Symtab.empty, NONE)
   25.74 -  val extend = I
   25.75 -  fun merge ((ss1, s1), (ss2, s2)) =
   25.76 -    (Symtab.merge (K true) (ss1, ss2), merge_options (s1, s2))
   25.77 -)
   25.78 -
   25.79 -fun set_solver_options (name, options) =
   25.80 -  let val opts = String.tokens (Symbol.is_ascii_blank o str) options
   25.81 -  in Solvers.map (apfst (Symtab.map_entry name (apsnd (K opts)))) end
   25.82 -
   25.83 -fun add_solver (info as {name, ...} : solver_info) context =
   25.84 -  if Symtab.defined (fst (Solvers.get context)) name then
   25.85 -    error ("Solver already registered: " ^ quote name)
   25.86 -  else
   25.87 -    context
   25.88 -    |> Solvers.map (apfst (Symtab.update (name, (info, []))))
   25.89 -    |> Context.map_theory (Attrib.setup (Binding.name (name ^ "_options"))
   25.90 -        (Scan.lift (@{keyword "="} |-- Args.name) >>
   25.91 -          (Thm.declaration_attribute o K o set_solver_options o pair name))
   25.92 -        ("Additional command line options for SMT solver " ^ quote name))
   25.93 -
   25.94 -fun all_solvers_of ctxt = Symtab.keys (fst (Solvers.get (Context.Proof ctxt)))
   25.95 -
   25.96 -fun solver_name_of ctxt = snd (Solvers.get (Context.Proof ctxt))
   25.97 -
   25.98 -fun is_available ctxt name =
   25.99 -  (case Symtab.lookup (fst (Solvers.get (Context.Proof ctxt))) name of
  25.100 -    SOME ({avail, ...}, _) => avail ()
  25.101 -  | NONE => false)
  25.102 -
  25.103 -fun available_solvers_of ctxt =
  25.104 -  filter (is_available ctxt) (all_solvers_of ctxt)
  25.105 -
  25.106 -fun warn_solver (Context.Proof ctxt) name =
  25.107 -      if Context_Position.is_visible ctxt then
  25.108 -        warning ("The SMT solver " ^ quote name ^ " is not installed.")
  25.109 -      else ()
  25.110 -  | warn_solver _ _ = ();
  25.111 -
  25.112 -fun select_solver name context =
  25.113 -  let
  25.114 -    val ctxt = Context.proof_of context
  25.115 -    val upd = Solvers.map (apsnd (K (SOME name)))
  25.116 -  in
  25.117 -    if not (member (op =) (all_solvers_of ctxt) name) then
  25.118 -      error ("Trying to select unknown solver: " ^ quote name)
  25.119 -    else if not (is_available ctxt name) then
  25.120 -      (warn_solver context name; upd context)
  25.121 -    else upd context
  25.122 -  end
  25.123 -
  25.124 -fun no_solver_err () = error "No SMT solver selected"
  25.125 -
  25.126 -fun solver_of ctxt =
  25.127 -  (case solver_name_of ctxt of
  25.128 -    SOME name => name
  25.129 -  | NONE => no_solver_err ())
  25.130 -
  25.131 -fun solver_info_of default select ctxt =
  25.132 -  (case Solvers.get (Context.Proof ctxt) of
  25.133 -    (solvers, SOME name) => select (Symtab.lookup solvers name)
  25.134 -  | (_, NONE) => default ())
  25.135 -
  25.136 -fun solver_class_of ctxt =
  25.137 -  let fun class_of ({class, ...}: solver_info, _) = class ctxt
  25.138 -  in solver_info_of no_solver_err (class_of o the) ctxt end
  25.139 -
  25.140 -fun solver_options_of ctxt =
  25.141 -  let
  25.142 -    fun all_options NONE = []
  25.143 -      | all_options (SOME ({options, ...} : solver_info, opts)) =
  25.144 -          opts @ options ctxt
  25.145 -  in solver_info_of (K []) all_options ctxt end
  25.146 -
  25.147 -val setup_solver =
  25.148 -  Attrib.setup @{binding smt_solver}
  25.149 -    (Scan.lift (@{keyword "="} |-- Args.name) >>
  25.150 -      (Thm.declaration_attribute o K o select_solver))
  25.151 -    "SMT solver configuration"
  25.152 -
  25.153 -
  25.154 -(* options *)
  25.155 -
  25.156 -val oracle = Attrib.setup_config_bool @{binding smt_oracle} (K true)
  25.157 -val datatypes = Attrib.setup_config_bool @{binding smt_datatypes} (K false)
  25.158 -val timeout = Attrib.setup_config_real @{binding smt_timeout} (K 30.0)
  25.159 -val random_seed = Attrib.setup_config_int @{binding smt_random_seed} (K 1)
  25.160 -val read_only_certificates = Attrib.setup_config_bool @{binding smt_read_only_certificates} (K false)
  25.161 -val verbose = Attrib.setup_config_bool @{binding smt_verbose} (K true)
  25.162 -val trace = Attrib.setup_config_bool @{binding smt_trace} (K false)
  25.163 -val trace_used_facts = Attrib.setup_config_bool @{binding smt_trace_used_facts} (K false)
  25.164 -val monomorph_limit = Attrib.setup_config_int @{binding smt_monomorph_limit} (K 10)
  25.165 -val monomorph_instances = Attrib.setup_config_int @{binding smt_monomorph_instances} (K 500)
  25.166 -val infer_triggers = Attrib.setup_config_bool @{binding smt_infer_triggers} (K false)
  25.167 -val filter_only_facts = Attrib.setup_config_bool @{binding smt_filter_only_facts} (K false)
  25.168 -val debug_files = Attrib.setup_config_string @{binding smt_debug_files} (K "")
  25.169 -
  25.170 -
  25.171 -(* diagnostics *)
  25.172 -
  25.173 -fun cond_trace flag f x = if flag then tracing ("SMT: " ^ f x) else ()
  25.174 -
  25.175 -fun verbose_msg ctxt = cond_trace (Config.get ctxt verbose)
  25.176 -
  25.177 -fun trace_msg ctxt = cond_trace (Config.get ctxt trace)
  25.178 -
  25.179 -
  25.180 -(* tools *)
  25.181 -
  25.182 -fun with_timeout ctxt f x =
  25.183 -  TimeLimit.timeLimit (seconds (Config.get ctxt timeout)) f x
  25.184 -  handle TimeLimit.TimeOut => raise SMT_Failure.SMT SMT_Failure.Time_Out
  25.185 -
  25.186 -
  25.187 -(* certificates *)
  25.188 -
  25.189 -(* FIXME just one data slot (record) per program unit *)
  25.190 -structure Certificates = Generic_Data
  25.191 -(
  25.192 -  type T = Cache_IO.cache option
  25.193 -  val empty = NONE
  25.194 -  val extend = I
  25.195 -  fun merge (s, _) = s  (* FIXME merge options!? *)
  25.196 -)
  25.197 -
  25.198 -val get_certificates_path =
  25.199 -  Option.map (Cache_IO.cache_path_of) o Certificates.get o Context.Proof
  25.200 -
  25.201 -fun select_certificates name context = context |> Certificates.put (
  25.202 -  if name = "" then NONE
  25.203 -  else
  25.204 -    Path.explode name
  25.205 -    |> Path.append (Resources.master_directory (Context.theory_of context))
  25.206 -    |> SOME o Cache_IO.unsynchronized_init)
  25.207 -
  25.208 -val certificates_of = Certificates.get o Context.Proof
  25.209 -
  25.210 -val setup_certificates =
  25.211 -  Attrib.setup @{binding smt_certificates}
  25.212 -    (Scan.lift (@{keyword "="} |-- Args.name) >>
  25.213 -      (Thm.declaration_attribute o K o select_certificates))
  25.214 -    "SMT certificates configuration"
  25.215 -
  25.216 -
  25.217 -(* setup *)
  25.218 -
  25.219 -val setup =
  25.220 -  setup_solver #>
  25.221 -  setup_certificates
  25.222 -
  25.223 -fun print_setup ctxt =
  25.224 -  let
  25.225 -    fun string_of_bool b = if b then "true" else "false"
  25.226 -
  25.227 -    val names = available_solvers_of ctxt
  25.228 -    val ns = if null names then ["(none)"] else sort_strings names
  25.229 -    val n = the_default "(none)" (solver_name_of ctxt)
  25.230 -    val opts = solver_options_of ctxt
  25.231 -    
  25.232 -    val t = string_of_real (Config.get ctxt timeout)
  25.233 -
  25.234 -    val certs_filename =
  25.235 -      (case get_certificates_path ctxt of
  25.236 -        SOME path => Path.print path
  25.237 -      | NONE => "(disabled)")
  25.238 -  in
  25.239 -    Pretty.writeln (Pretty.big_list "SMT setup:" [
  25.240 -      Pretty.str ("Current SMT solver: " ^ n),
  25.241 -      Pretty.str ("Current SMT solver options: " ^ space_implode " " opts),
  25.242 -      Pretty.str_list "Available SMT solvers: "  "" ns,
  25.243 -      Pretty.str ("Current timeout: " ^ t ^ " seconds"),
  25.244 -      Pretty.str ("With proofs: " ^
  25.245 -        string_of_bool (not (Config.get ctxt oracle))),
  25.246 -      Pretty.str ("Certificates cache: " ^ certs_filename),
  25.247 -      Pretty.str ("Fixed certificates: " ^
  25.248 -        string_of_bool (Config.get ctxt read_only_certificates))])
  25.249 -  end
  25.250 -
  25.251 -val _ =
  25.252 -  Outer_Syntax.improper_command @{command_spec "smt_status"}
  25.253 -    "show the available SMT solvers, the currently selected SMT solver, \
  25.254 -    \and the values of SMT configuration options"
  25.255 -    (Scan.succeed (Toplevel.keep (print_setup o Toplevel.context_of)))
  25.256 -
  25.257 -end
    26.1 --- a/src/HOL/Tools/SMT/smt_datatypes.ML	Thu Aug 28 00:40:37 2014 +0200
    26.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
    26.3 @@ -1,96 +0,0 @@
    26.4 -(*  Title:      HOL/Tools/SMT/smt_datatypes.ML
    26.5 -    Author:     Sascha Boehme, TU Muenchen
    26.6 -
    26.7 -Collector functions for common type declarations and their representation
    26.8 -as algebraic datatypes.
    26.9 -*)
   26.10 -
   26.11 -signature SMT_DATATYPES =
   26.12 -sig
   26.13 -  val add_decls: typ ->
   26.14 -    (typ * (term * term list) list) list list * Proof.context ->
   26.15 -    (typ * (term * term list) list) list list * Proof.context
   26.16 -end
   26.17 -
   26.18 -structure SMT_Datatypes: SMT_DATATYPES =
   26.19 -struct
   26.20 -
   26.21 -val lhs_head_of = Term.head_of o fst o Logic.dest_equals o Thm.prop_of
   26.22 -
   26.23 -fun mk_selectors T Ts =
   26.24 -  Variable.variant_fixes (replicate (length Ts) "select")
   26.25 -  #>> map2 (fn U => fn n => Free (n, T --> U)) Ts
   26.26 -
   26.27 -
   26.28 -(* free constructor type declarations *)
   26.29 -
   26.30 -fun get_ctr_sugar_decl ({ctrs, ...} : Ctr_Sugar.ctr_sugar) T Ts ctxt =
   26.31 -  let
   26.32 -    fun mk_constr ctr0 =
   26.33 -      let val ctr = Ctr_Sugar.mk_ctr Ts ctr0 in
   26.34 -        mk_selectors T (binder_types (fastype_of ctr)) #>> pair ctr
   26.35 -      end
   26.36 -  in
   26.37 -    fold_map mk_constr ctrs ctxt
   26.38 -    |>> (pair T #> single)
   26.39 -  end
   26.40 -
   26.41 -
   26.42 -(* typedef declarations *)
   26.43 -
   26.44 -fun get_typedef_decl (({Abs_name, Rep_name, abs_type, rep_type, ...}, {Abs_inverse, ...})
   26.45 -    : Typedef.info) T Ts =
   26.46 -  if can (curry (op RS) @{thm UNIV_I}) Abs_inverse then
   26.47 -    let
   26.48 -      val env = snd (Term.dest_Type abs_type) ~~ Ts
   26.49 -      val instT = Term.map_atyps (perhaps (AList.lookup (op =) env))
   26.50 -
   26.51 -      val constr = Const (Abs_name, instT (rep_type --> abs_type))
   26.52 -      val select = Const (Rep_name, instT (abs_type --> rep_type))
   26.53 -    in [(T, [(constr, [select])])] end
   26.54 -  else
   26.55 -    []
   26.56 -
   26.57 -
   26.58 -(* collection of declarations *)
   26.59 -
   26.60 -fun declared declss T = exists (exists (equal T o fst)) declss
   26.61 -fun declared' dss T = exists (exists (equal T o fst) o snd) dss
   26.62 -
   26.63 -fun get_decls T n Ts ctxt =
   26.64 -  (case Ctr_Sugar.ctr_sugar_of ctxt n of
   26.65 -    SOME ctr_sugar => get_ctr_sugar_decl ctr_sugar T Ts ctxt
   26.66 -  | NONE =>
   26.67 -      (case Typedef.get_info ctxt n of
   26.68 -        [] => ([], ctxt)
   26.69 -      | info :: _ => (get_typedef_decl info T Ts, ctxt)))
   26.70 -
   26.71 -fun add_decls T (declss, ctxt) =
   26.72 -  let
   26.73 -    fun depends Ts ds = exists (member (op =) (map fst ds)) Ts
   26.74 -
   26.75 -    fun add (TFree _) = I
   26.76 -      | add (TVar _) = I
   26.77 -      | add (T as Type (@{type_name fun}, _)) =
   26.78 -          fold add (Term.body_type T :: Term.binder_types T)
   26.79 -      | add @{typ bool} = I
   26.80 -      | add (T as Type (n, Ts)) = (fn (dss, ctxt1) =>
   26.81 -          if declared declss T orelse declared' dss T then (dss, ctxt1)
   26.82 -          else if SMT_Builtin.is_builtin_typ_ext ctxt1 T then (dss, ctxt1)
   26.83 -          else
   26.84 -            (case get_decls T n Ts ctxt1 of
   26.85 -              ([], _) => (dss, ctxt1)
   26.86 -            | (ds, ctxt2) =>
   26.87 -                let
   26.88 -                  val constrTs =
   26.89 -                    maps (map (snd o Term.dest_Const o fst) o snd) ds
   26.90 -                  val Us = fold (union (op =) o Term.binder_types) constrTs []
   26.91 -
   26.92 -                  fun ins [] = [(Us, ds)]
   26.93 -                    | ins ((Uds as (Us', _)) :: Udss) =
   26.94 -                        if depends Us' ds then (Us, ds) :: Uds :: Udss
   26.95 -                        else Uds :: ins Udss
   26.96 -            in fold add Us (ins dss, ctxt2) end))
   26.97 -  in add T ([], ctxt) |>> append declss o map snd end
   26.98 -
   26.99 -end
    27.1 --- a/src/HOL/Tools/SMT/smt_failure.ML	Thu Aug 28 00:40:37 2014 +0200
    27.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
    27.3 @@ -1,61 +0,0 @@
    27.4 -(*  Title:      HOL/Tools/SMT/smt_failure.ML
    27.5 -    Author:     Sascha Boehme, TU Muenchen
    27.6 -
    27.7 -Failures and exception of SMT.
    27.8 -*)
    27.9 -
   27.10 -signature SMT_FAILURE =
   27.11 -sig
   27.12 -  type counterexample = {
   27.13 -    is_real_cex: bool,
   27.14 -    free_constraints: term list,
   27.15 -    const_defs: term list}
   27.16 -  datatype failure =
   27.17 -    Counterexample of counterexample |
   27.18 -    Time_Out |
   27.19 -    Out_Of_Memory |
   27.20 -    Abnormal_Termination of int |
   27.21 -    Other_Failure of string
   27.22 -  val pretty_counterexample: Proof.context -> counterexample -> Pretty.T
   27.23 -  val string_of_failure: Proof.context -> failure -> string
   27.24 -  exception SMT of failure
   27.25 -end
   27.26 -
   27.27 -structure SMT_Failure: SMT_FAILURE =
   27.28 -struct
   27.29 -
   27.30 -type counterexample = {
   27.31 -  is_real_cex: bool,
   27.32 -  free_constraints: term list,
   27.33 -  const_defs: term list}
   27.34 -
   27.35 -datatype failure =
   27.36 -  Counterexample of counterexample |
   27.37 -  Time_Out |
   27.38 -  Out_Of_Memory |
   27.39 -  Abnormal_Termination of int |
   27.40 -  Other_Failure of string
   27.41 -
   27.42 -fun pretty_counterexample ctxt {is_real_cex, free_constraints, const_defs} =
   27.43 -  let
   27.44 -    val msg =
   27.45 -      if is_real_cex then "Counterexample found (possibly spurious)"
   27.46 -      else "Potential counterexample found"
   27.47 -  in
   27.48 -    if null free_constraints andalso null const_defs then Pretty.str msg
   27.49 -    else
   27.50 -      Pretty.big_list (msg ^ ":")
   27.51 -        (map (Syntax.pretty_term ctxt) (free_constraints @ const_defs))
   27.52 -  end
   27.53 -
   27.54 -fun string_of_failure ctxt (Counterexample cex) =
   27.55 -      Pretty.string_of (pretty_counterexample ctxt cex)
   27.56 -  | string_of_failure _ Time_Out = "Timed out"
   27.57 -  | string_of_failure _ Out_Of_Memory = "Ran out of memory"
   27.58 -  | string_of_failure _ (Abnormal_Termination err) =
   27.59 -      "Solver terminated abnormally with error code " ^ string_of_int err
   27.60 -  | string_of_failure _ (Other_Failure msg) = msg
   27.61 -
   27.62 -exception SMT of failure
   27.63 -
   27.64 -end
    28.1 --- a/src/HOL/Tools/SMT/smt_normalize.ML	Thu Aug 28 00:40:37 2014 +0200
    28.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
    28.3 @@ -1,652 +0,0 @@
    28.4 -(*  Title:      HOL/Tools/SMT/smt_normalize.ML
    28.5 -    Author:     Sascha Boehme, TU Muenchen
    28.6 -
    28.7 -Normalization steps on theorems required by SMT solvers.
    28.8 -*)
    28.9 -
   28.10 -signature SMT_NORMALIZE =
   28.11 -sig
   28.12 -  val drop_fact_warning: Proof.context -> thm -> unit
   28.13 -  val atomize_conv: Proof.context -> conv
   28.14 -  type extra_norm = Proof.context -> thm list * thm list -> thm list * thm list
   28.15 -  val add_extra_norm: SMT_Utils.class * extra_norm -> Context.generic ->
   28.16 -    Context.generic
   28.17 -  val normalize: (int * (int option * thm)) list -> Proof.context ->
   28.18 -    (int * thm) list * Proof.context
   28.19 -  val setup: theory -> theory
   28.20 -end
   28.21 -
   28.22 -structure SMT_Normalize: SMT_NORMALIZE =
   28.23 -struct
   28.24 -
   28.25 -fun drop_fact_warning ctxt =
   28.26 -  SMT_Config.verbose_msg ctxt (prefix "Warning: dropping assumption: " o
   28.27 -    Display.string_of_thm ctxt)
   28.28 -
   28.29 -
   28.30 -(* general theorem normalizations *)
   28.31 -
   28.32 -(** instantiate elimination rules **)
   28.33 - 
   28.34 -local
   28.35 -  val (cpfalse, cfalse) =
   28.36 -    `SMT_Utils.mk_cprop (Thm.cterm_of @{theory} @{const False})
   28.37 -
   28.38 -  fun inst f ct thm =
   28.39 -    let val cv = f (Drule.strip_imp_concl (Thm.cprop_of thm))
   28.40 -    in Thm.instantiate ([], [(cv, ct)]) thm end
   28.41 -in
   28.42 -
   28.43 -fun instantiate_elim thm =
   28.44 -  (case Thm.concl_of thm of
   28.45 -    @{const Trueprop} $ Var (_, @{typ bool}) => inst Thm.dest_arg cfalse thm
   28.46 -  | Var _ => inst I cpfalse thm
   28.47 -  | _ => thm)
   28.48 -
   28.49 -end
   28.50 -
   28.51 -
   28.52 -(** normalize definitions **)
   28.53 -
   28.54 -fun norm_def thm =
   28.55 -  (case Thm.prop_of thm of
   28.56 -    @{const Trueprop} $ (Const (@{const_name HOL.eq}, _) $ _ $ Abs _) =>
   28.57 -      norm_def (thm RS @{thm fun_cong})
   28.58 -  | Const (@{const_name Pure.eq}, _) $ _ $ Abs _ =>
   28.59 -      norm_def (thm RS @{thm meta_eq_to_obj_eq})
   28.60 -  | _ => thm)
   28.61 -
   28.62 -
   28.63 -(** atomization **)
   28.64 -
   28.65 -fun atomize_conv ctxt ct =
   28.66 -  (case Thm.term_of ct of
   28.67 -    @{const Pure.imp} $ _ $ _ =>
   28.68 -      Conv.binop_conv (atomize_conv ctxt) then_conv
   28.69 -      Conv.rewr_conv @{thm atomize_imp}
   28.70 -  | Const (@{const_name Pure.eq}, _) $ _ $ _ =>
   28.71 -      Conv.binop_conv (atomize_conv ctxt) then_conv
   28.72 -      Conv.rewr_conv @{thm atomize_eq}
   28.73 -  | Const (@{const_name Pure.all}, _) $ Abs _ =>
   28.74 -      Conv.binder_conv (atomize_conv o snd) ctxt then_conv
   28.75 -      Conv.rewr_conv @{thm atomize_all}
   28.76 -  | _ => Conv.all_conv) ct
   28.77 -
   28.78 -val setup_atomize =
   28.79 -  fold SMT_Builtin.add_builtin_fun_ext'' [@{const_name Pure.imp},
   28.80 -    @{const_name Pure.eq}, @{const_name Pure.all}, @{const_name Trueprop}]
   28.81 -
   28.82 -
   28.83 -(** unfold special quantifiers **)
   28.84 -
   28.85 -local
   28.86 -  val ex1_def = mk_meta_eq @{lemma
   28.87 -    "Ex1 = (%P. EX x. P x & (ALL y. P y --> y = x))"
   28.88 -    by (rule ext) (simp only: Ex1_def)}
   28.89 -
   28.90 -  val ball_def = mk_meta_eq @{lemma "Ball = (%A P. ALL x. x : A --> P x)"
   28.91 -    by (rule ext)+ (rule Ball_def)}
   28.92 -
   28.93 -  val bex_def = mk_meta_eq @{lemma "Bex = (%A P. EX x. x : A & P x)"
   28.94 -    by (rule ext)+ (rule Bex_def)}
   28.95 -
   28.96 -  val special_quants = [(@{const_name Ex1}, ex1_def),
   28.97 -    (@{const_name Ball}, ball_def), (@{const_name Bex}, bex_def)]
   28.98 -  
   28.99 -  fun special_quant (Const (n, _)) = AList.lookup (op =) special_quants n
  28.100 -    | special_quant _ = NONE
  28.101 -
  28.102 -  fun special_quant_conv _ ct =
  28.103 -    (case special_quant (Thm.term_of ct) of
  28.104 -      SOME thm => Conv.rewr_conv thm
  28.105 -    | NONE => Conv.all_conv) ct
  28.106 -in
  28.107 -
  28.108 -fun unfold_special_quants_conv ctxt =
  28.109 -  SMT_Utils.if_exists_conv (is_some o special_quant)
  28.110 -    (Conv.top_conv special_quant_conv ctxt)
  28.111 -
  28.112 -val setup_unfolded_quants =
  28.113 -  fold (SMT_Builtin.add_builtin_fun_ext'' o fst) special_quants
  28.114 -
  28.115 -end
  28.116 -
  28.117 -
  28.118 -(** trigger inference **)
  28.119 -
  28.120 -local
  28.121 -  (*** check trigger syntax ***)
  28.122 -
  28.123 -  fun dest_trigger (Const (@{const_name pat}, _) $ _) = SOME true
  28.124 -    | dest_trigger (Const (@{const_name nopat}, _) $ _) = SOME false
  28.125 -    | dest_trigger _ = NONE
  28.126 -
  28.127 -  fun eq_list [] = false
  28.128 -    | eq_list (b :: bs) = forall (equal b) bs
  28.129 -
  28.130 -  fun proper_trigger t =
  28.131 -    t
  28.132 -    |> these o try HOLogic.dest_list
  28.133 -    |> map (map_filter dest_trigger o these o try HOLogic.dest_list)
  28.134 -    |> (fn [] => false | bss => forall eq_list bss)
  28.135 -
  28.136 -  fun proper_quant inside f t =
  28.137 -    (case t of
  28.138 -      Const (@{const_name All}, _) $ Abs (_, _, u) => proper_quant true f u
  28.139 -    | Const (@{const_name Ex}, _) $ Abs (_, _, u) => proper_quant true f u
  28.140 -    | @{const trigger} $ p $ u =>
  28.141 -        (if inside then f p else false) andalso proper_quant false f u
  28.142 -    | Abs (_, _, u) => proper_quant false f u
  28.143 -    | u1 $ u2 => proper_quant false f u1 andalso proper_quant false f u2
  28.144 -    | _ => true)
  28.145 -
  28.146 -  fun check_trigger_error ctxt t =
  28.147 -    error ("SMT triggers must only occur under quantifier and multipatterns " ^
  28.148 -      "must have the same kind: " ^ Syntax.string_of_term ctxt t)
  28.149 -
  28.150 -  fun check_trigger_conv ctxt ct =
  28.151 -    if proper_quant false proper_trigger (SMT_Utils.term_of ct) then
  28.152 -      Conv.all_conv ct
  28.153 -    else check_trigger_error ctxt (Thm.term_of ct)
  28.154 -
  28.155 -
  28.156 -  (*** infer simple triggers ***)
  28.157 -
  28.158 -  fun dest_cond_eq ct =
  28.159 -    (case Thm.term_of ct of
  28.160 -      Const (@{const_name HOL.eq}, _) $ _ $ _ => Thm.dest_binop ct
  28.161 -    | @{const HOL.implies} $ _ $ _ => dest_cond_eq (Thm.dest_arg ct)
  28.162 -    | _ => raise CTERM ("no equation", [ct]))
  28.163 -
  28.164 -  fun get_constrs thy (Type (n, _)) = these (Datatype_Data.get_constrs thy n)
  28.165 -    | get_constrs _ _ = []
  28.166 -
  28.167 -  fun is_constr thy (n, T) =
  28.168 -    let fun match (m, U) = m = n andalso Sign.typ_instance thy (T, U)
  28.169 -    in can (the o find_first match o get_constrs thy o Term.body_type) T end
  28.170 -
  28.171 -  fun is_constr_pat thy t =
  28.172 -    (case Term.strip_comb t of
  28.173 -      (Free _, []) => true
  28.174 -    | (Const c, ts) => is_constr thy c andalso forall (is_constr_pat thy) ts
  28.175 -    | _ => false)
  28.176 -
  28.177 -  fun is_simp_lhs ctxt t =
  28.178 -    (case Term.strip_comb t of
  28.179 -      (Const c, ts as _ :: _) =>
  28.180 -        not (SMT_Builtin.is_builtin_fun_ext ctxt c ts) andalso
  28.181 -        forall (is_constr_pat (Proof_Context.theory_of ctxt)) ts
  28.182 -    | _ => false)
  28.183 -
  28.184 -  fun has_all_vars vs t =
  28.185 -    subset (op aconv) (vs, map Free (Term.add_frees t []))
  28.186 -
  28.187 -  fun minimal_pats vs ct =
  28.188 -    if has_all_vars vs (Thm.term_of ct) then
  28.189 -      (case Thm.term_of ct of
  28.190 -        _ $ _ =>
  28.191 -          (case pairself (minimal_pats vs) (Thm.dest_comb ct) of
  28.192 -            ([], []) => [[ct]]
  28.193 -          | (ctss, ctss') => union (eq_set (op aconvc)) ctss ctss')
  28.194 -      | _ => [])
  28.195 -    else []
  28.196 -
  28.197 -  fun proper_mpat _ _ _ [] = false
  28.198 -    | proper_mpat thy gen u cts =
  28.199 -        let
  28.200 -          val tps = (op ~~) (`gen (map Thm.term_of cts))
  28.201 -          fun some_match u = tps |> exists (fn (t', t) =>
  28.202 -            Pattern.matches thy (t', u) andalso not (t aconv u))
  28.203 -        in not (Term.exists_subterm some_match u) end
  28.204 -
  28.205 -  val pat =
  28.206 -    SMT_Utils.mk_const_pat @{theory} @{const_name SMT.pat} SMT_Utils.destT1
  28.207 -  fun mk_pat ct = Thm.apply (SMT_Utils.instT' ct pat) ct
  28.208 -
  28.209 -  fun mk_clist T = pairself (Thm.cterm_of @{theory})
  28.210 -    (HOLogic.cons_const T, HOLogic.nil_const T)
  28.211 -  fun mk_list (ccons, cnil) f cts = fold_rev (Thm.mk_binop ccons o f) cts cnil
  28.212 -  val mk_pat_list = mk_list (mk_clist @{typ SMT.pattern})
  28.213 -  val mk_mpat_list = mk_list (mk_clist @{typ "SMT.pattern list"})  
  28.214 -  fun mk_trigger ctss = mk_mpat_list (mk_pat_list mk_pat) ctss
  28.215 -
  28.216 -  val trigger_eq =
  28.217 -    mk_meta_eq @{lemma "p = SMT.trigger t p" by (simp add: trigger_def)}
  28.218 -
  28.219 -  fun insert_trigger_conv [] ct = Conv.all_conv ct
  28.220 -    | insert_trigger_conv ctss ct =
  28.221 -        let val (ctr, cp) = Thm.dest_binop (Thm.rhs_of trigger_eq) ||> rpair ct
  28.222 -        in Thm.instantiate ([], [cp, (ctr, mk_trigger ctss)]) trigger_eq end
  28.223 -
  28.224 -  fun infer_trigger_eq_conv outer_ctxt (ctxt, cvs) ct =
  28.225 -    let
  28.226 -      val (lhs, rhs) = dest_cond_eq ct
  28.227 -
  28.228 -      val vs = map Thm.term_of cvs
  28.229 -      val thy = Proof_Context.theory_of ctxt
  28.230 -
  28.231 -      fun get_mpats ct =
  28.232 -        if is_simp_lhs ctxt (Thm.term_of ct) then minimal_pats vs ct
  28.233 -        else []
  28.234 -      val gen = Variable.export_terms ctxt outer_ctxt
  28.235 -      val filter_mpats = filter (proper_mpat thy gen (Thm.term_of rhs))
  28.236 -
  28.237 -    in insert_trigger_conv (filter_mpats (get_mpats lhs)) ct end
  28.238 -
  28.239 -  fun has_trigger (@{const SMT.trigger} $ _ $ _) = true
  28.240 -    | has_trigger _ = false
  28.241 -
  28.242 -  fun try_trigger_conv cv ct =
  28.243 -    if SMT_Utils.under_quant has_trigger (SMT_Utils.term_of ct) then
  28.244 -      Conv.all_conv ct
  28.245 -    else Conv.try_conv cv ct
  28.246 -
  28.247 -  fun infer_trigger_conv ctxt =
  28.248 -    if Config.get ctxt SMT_Config.infer_triggers then
  28.249 -      try_trigger_conv
  28.250 -        (SMT_Utils.under_quant_conv (infer_trigger_eq_conv ctxt) ctxt)
  28.251 -    else Conv.all_conv
  28.252 -in
  28.253 -
  28.254 -fun trigger_conv ctxt =
  28.255 -  SMT_Utils.prop_conv
  28.256 -    (check_trigger_conv ctxt then_conv infer_trigger_conv ctxt)
  28.257 -
  28.258 -val setup_trigger =
  28.259 -  fold SMT_Builtin.add_builtin_fun_ext''
  28.260 -    [@{const_name SMT.pat}, @{const_name SMT.nopat}, @{const_name SMT.trigger}]
  28.261 -
  28.262 -end
  28.263 -
  28.264 -
  28.265 -(** adding quantifier weights **)
  28.266 -
  28.267 -local
  28.268 -  (*** check weight syntax ***)
  28.269 -
  28.270 -  val has_no_weight =
  28.271 -    not o Term.exists_subterm (fn @{const SMT.weight} => true | _ => false)
  28.272 -
  28.273 -  fun is_weight (@{const SMT.weight} $ w $ t) =
  28.274 -        (case try HOLogic.dest_number w of
  28.275 -          SOME (_, i) => i >= 0 andalso has_no_weight t
  28.276 -        | _ => false)
  28.277 -    | is_weight t = has_no_weight t
  28.278 -
  28.279 -  fun proper_trigger (@{const SMT.trigger} $ _ $ t) = is_weight t
  28.280 -    | proper_trigger t = is_weight t 
  28.281 -
  28.282 -  fun check_weight_error ctxt t =
  28.283 -    error ("SMT weight must be a non-negative number and must only occur " ^
  28.284 -      "under the top-most quantifier and an optional trigger: " ^
  28.285 -      Syntax.string_of_term ctxt t)
  28.286 -
  28.287 -  fun check_weight_conv ctxt ct =
  28.288 -    if SMT_Utils.under_quant proper_trigger (SMT_Utils.term_of ct) then
  28.289 -      Conv.all_conv ct
  28.290 -    else check_weight_error ctxt (Thm.term_of ct)
  28.291 -
  28.292 -
  28.293 -  (*** insertion of weights ***)
  28.294 -
  28.295 -  fun under_trigger_conv cv ct =
  28.296 -    (case Thm.term_of ct of
  28.297 -      @{const SMT.trigger} $ _ $ _ => Conv.arg_conv cv
  28.298 -    | _ => cv) ct
  28.299 -
  28.300 -  val weight_eq =
  28.301 -    mk_meta_eq @{lemma "p = SMT.weight i p" by (simp add: weight_def)}
  28.302 -  fun mk_weight_eq w =
  28.303 -    let val cv = Thm.dest_arg1 (Thm.rhs_of weight_eq)
  28.304 -    in
  28.305 -      Thm.instantiate ([], [(cv, Numeral.mk_cnumber @{ctyp int} w)]) weight_eq
  28.306 -    end
  28.307 -
  28.308 -  fun add_weight_conv NONE _ = Conv.all_conv
  28.309 -    | add_weight_conv (SOME weight) ctxt =
  28.310 -        let val cv = Conv.rewr_conv (mk_weight_eq weight)
  28.311 -        in SMT_Utils.under_quant_conv (K (under_trigger_conv cv)) ctxt end
  28.312 -in
  28.313 -
  28.314 -fun weight_conv weight ctxt = 
  28.315 -  SMT_Utils.prop_conv
  28.316 -    (check_weight_conv ctxt then_conv add_weight_conv weight ctxt)
  28.317 -
  28.318 -val setup_weight = SMT_Builtin.add_builtin_fun_ext'' @{const_name SMT.weight}
  28.319 -
  28.320 -end
  28.321 -
  28.322 -
  28.323 -(** combined general normalizations **)
  28.324 -
  28.325 -fun gen_normalize1_conv ctxt weight =
  28.326 -  atomize_conv ctxt then_conv
  28.327 -  unfold_special_quants_conv ctxt then_conv
  28.328 -  Thm.beta_conversion true then_conv
  28.329 -  trigger_conv ctxt then_conv
  28.330 -  weight_conv weight ctxt
  28.331 -
  28.332 -fun gen_normalize1 ctxt weight thm =
  28.333 -  thm
  28.334 -  |> instantiate_elim
  28.335 -  |> norm_def
  28.336 -  |> Conv.fconv_rule (Thm.beta_conversion true then_conv Thm.eta_conversion)
  28.337 -  |> Drule.forall_intr_vars
  28.338 -  |> Conv.fconv_rule (gen_normalize1_conv ctxt weight)
  28.339 -
  28.340 -fun gen_norm1_safe ctxt (i, (weight, thm)) =
  28.341 -  (case try (gen_normalize1 ctxt weight) thm of
  28.342 -    SOME thm' => SOME (i, thm')
  28.343 -  | NONE => (drop_fact_warning ctxt thm; NONE))
  28.344 -
  28.345 -fun gen_normalize ctxt iwthms = map_filter (gen_norm1_safe ctxt) iwthms
  28.346 -
  28.347 -
  28.348 -
  28.349 -(* unfolding of definitions and theory-specific rewritings *)
  28.350 -
  28.351 -fun expand_head_conv cv ct =
  28.352 -  (case Thm.term_of ct of
  28.353 -    _ $ _ =>
  28.354 -      Conv.fun_conv (expand_head_conv cv) then_conv
  28.355 -      Conv.try_conv (Thm.beta_conversion false)
  28.356 -  | _ => cv) ct
  28.357 -
  28.358 -
  28.359 -(** rewrite bool case expressions as if expressions **)
  28.360 -
  28.361 -local
  28.362 -  fun is_case_bool (Const (@{const_name "bool.case_bool"}, _)) = true
  28.363 -    | is_case_bool _ = false
  28.364 -
  28.365 -  val thm = mk_meta_eq @{lemma
  28.366 -    "case_bool = (%x y P. if P then x else y)" by (rule ext)+ simp}
  28.367 -
  28.368 -  fun unfold_conv _ =
  28.369 -    SMT_Utils.if_true_conv (is_case_bool o Term.head_of)
  28.370 -      (expand_head_conv (Conv.rewr_conv thm))
  28.371 -in
  28.372 -
  28.373 -fun rewrite_case_bool_conv ctxt =
  28.374 -  SMT_Utils.if_exists_conv is_case_bool (Conv.top_conv unfold_conv ctxt)
  28.375 -
  28.376 -val setup_case_bool =
  28.377 -  SMT_Builtin.add_builtin_fun_ext'' @{const_name "bool.case_bool"}
  28.378 -
  28.379 -end
  28.380 -
  28.381 -
  28.382 -(** unfold abs, min and max **)
  28.383 -
  28.384 -local
  28.385 -  val abs_def = mk_meta_eq @{lemma
  28.386 -    "abs = (%a::'a::abs_if. if a < 0 then - a else a)"
  28.387 -    by (rule ext) (rule abs_if)}
  28.388 -
  28.389 -  val min_def = mk_meta_eq @{lemma "min = (%a b. if a <= b then a else b)"
  28.390 -    by (rule ext)+ (rule min_def)}
  28.391 -
  28.392 -  val max_def = mk_meta_eq  @{lemma "max = (%a b. if a <= b then b else a)"
  28.393 -    by (rule ext)+ (rule max_def)}
  28.394 -
  28.395 -  val defs = [(@{const_name min}, min_def), (@{const_name max}, max_def),
  28.396 -    (@{const_name abs}, abs_def)]
  28.397 -
  28.398 -  fun is_builtinT ctxt T =
  28.399 -    SMT_Builtin.is_builtin_typ_ext ctxt (Term.domain_type T)
  28.400 -
  28.401 -  fun abs_min_max ctxt (Const (n, T)) =
  28.402 -        (case AList.lookup (op =) defs n of
  28.403 -          NONE => NONE
  28.404 -        | SOME thm => if is_builtinT ctxt T then SOME thm else NONE)
  28.405 -    | abs_min_max _ _ = NONE
  28.406 -
  28.407 -  fun unfold_amm_conv ctxt ct =
  28.408 -    (case abs_min_max ctxt (Term.head_of (Thm.term_of ct)) of
  28.409 -      SOME thm => expand_head_conv (Conv.rewr_conv thm)
  28.410 -    | NONE => Conv.all_conv) ct
  28.411 -in
  28.412 -
  28.413 -fun unfold_abs_min_max_conv ctxt =
  28.414 -  SMT_Utils.if_exists_conv (is_some o abs_min_max ctxt)
  28.415 -    (Conv.top_conv unfold_amm_conv ctxt)
  28.416 -  
  28.417 -val setup_abs_min_max = fold (SMT_Builtin.add_builtin_fun_ext'' o fst) defs
  28.418 -
  28.419 -end
  28.420 -
  28.421 -
  28.422 -(** embedding of standard natural number operations into integer operations **)
  28.423 -
  28.424 -local
  28.425 -  val nat_embedding = @{lemma
  28.426 -    "ALL n. nat (int n) = n"
  28.427 -    "ALL i. i >= 0 --> int (nat i) = i"
  28.428 -    "ALL i. i < 0 --> int (nat i) = 0"
  28.429 -    by simp_all}
  28.430 -
  28.431 -  val simple_nat_ops = [
  28.432 -    @{const less (nat)}, @{const less_eq (nat)},
  28.433 -    @{const Suc}, @{const plus (nat)}, @{const minus (nat)}]
  28.434 -
  28.435 -  val mult_nat_ops =
  28.436 -    [@{const times (nat)}, @{const div (nat)}, @{const mod (nat)}]
  28.437 -
  28.438 -  val nat_ops = simple_nat_ops @ mult_nat_ops
  28.439 -
  28.440 -  val nat_consts = nat_ops @ [@{const numeral (nat)},
  28.441 -    @{const zero_class.zero (nat)}, @{const one_class.one (nat)}]
  28.442 -
  28.443 -  val nat_int_coercions = [@{const of_nat (int)}, @{const nat}]
  28.444 -
  28.445 -  val builtin_nat_ops = nat_int_coercions @ simple_nat_ops
  28.446 -
  28.447 -  val is_nat_const = member (op aconv) nat_consts
  28.448 -
  28.449 -  fun is_nat_const' @{const of_nat (int)} = true
  28.450 -    | is_nat_const' t = is_nat_const t
  28.451 -
  28.452 -  val expands = map mk_meta_eq @{lemma
  28.453 -    "0 = nat 0"
  28.454 -    "1 = nat 1"
  28.455 -    "(numeral :: num => nat) = (%i. nat (numeral i))"
  28.456 -    "op < = (%a b. int a < int b)"
  28.457 -    "op <= = (%a b. int a <= int b)"
  28.458 -    "Suc = (%a. nat (int a + 1))"
  28.459 -    "op + = (%a b. nat (int a + int b))"
  28.460 -    "op - = (%a b. nat (int a - int b))"
  28.461 -    "op * = (%a b. nat (int a * int b))"
  28.462 -    "op div = (%a b. nat (int a div int b))"
  28.463 -    "op mod = (%a b. nat (int a mod int b))"
  28.464 -    by (fastforce simp add: nat_mult_distrib nat_div_distrib nat_mod_distrib)+}
  28.465 -
  28.466 -  val ints = map mk_meta_eq @{lemma
  28.467 -    "int 0 = 0"
  28.468 -    "int 1 = 1"
  28.469 -    "int (Suc n) = int n + 1"
  28.470 -    "int (n + m) = int n + int m"
  28.471 -    "int (n - m) = int (nat (int n - int m))"
  28.472 -    "int (n * m) = int n * int m"
  28.473 -    "int (n div m) = int n div int m"
  28.474 -    "int (n mod m) = int n mod int m"
  28.475 -    by (auto simp add: int_mult zdiv_int zmod_int)}
  28.476 -
  28.477 -  val int_if = mk_meta_eq @{lemma
  28.478 -    "int (if P then n else m) = (if P then int n else int m)"
  28.479 -    by simp}
  28.480 -
  28.481 -  fun mk_number_eq ctxt i lhs =
  28.482 -    let
  28.483 -      val eq = SMT_Utils.mk_cequals lhs (Numeral.mk_cnumber @{ctyp int} i)
  28.484 -      val tac =
  28.485 -        Simplifier.simp_tac (put_simpset HOL_ss ctxt addsimps [@{thm Int.int_numeral}]) 1
  28.486 -    in Goal.norm_result ctxt (Goal.prove_internal ctxt [] eq (K tac)) end
  28.487 -
  28.488 -  fun ite_conv cv1 cv2 =
  28.489 -    Conv.combination_conv (Conv.combination_conv (Conv.arg_conv cv1) cv2) cv2
  28.490 -
  28.491 -  fun int_conv ctxt ct =
  28.492 -    (case Thm.term_of ct of
  28.493 -      @{const of_nat (int)} $ (n as (@{const numeral (nat)} $ _)) =>
  28.494 -        Conv.rewr_conv (mk_number_eq ctxt (snd (HOLogic.dest_number n)) ct)
  28.495 -    | @{const of_nat (int)} $ _ =>
  28.496 -        (Conv.rewrs_conv ints then_conv Conv.sub_conv ints_conv ctxt) else_conv
  28.497 -        (Conv.rewr_conv int_if then_conv