src/HOL/Tools/Sledgehammer/sledgehammer_prover.ML
changeset 55201 1ee776da8da7
parent 55183 17ec4a29ef71
child 55202 824c48a539c9
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/HOL/Tools/Sledgehammer/sledgehammer_prover.ML	Fri Jan 31 10:23:32 2014 +0100
     1.3 @@ -0,0 +1,1063 @@
     1.4 +(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_prover.ML
     1.5 +    Author:     Fabian Immler, TU Muenchen
     1.6 +    Author:     Makarius
     1.7 +    Author:     Jasmin Blanchette, TU Muenchen
     1.8 +
     1.9 +Generic prover abstraction for Sledgehammer.
    1.10 +*)
    1.11 +
    1.12 +signature SLEDGEHAMMER_PROVER =
    1.13 +sig
    1.14 +  type atp_failure = ATP_Proof.atp_failure
    1.15 +  type stature = ATP_Problem_Generate.stature
    1.16 +  type type_enc = ATP_Problem_Generate.type_enc
    1.17 +  type fact = Sledgehammer_Fact.fact
    1.18 +  type reconstructor = Sledgehammer_Reconstructor.reconstructor
    1.19 +  type play_outcome = Sledgehammer_Reconstructor.play_outcome
    1.20 +  type minimize_command = Sledgehammer_Reconstructor.minimize_command
    1.21 +
    1.22 +  datatype mode = Auto_Try | Try | Normal | MaSh | Auto_Minimize | Minimize
    1.23 +
    1.24 +  type params =
    1.25 +    {debug : bool,
    1.26 +     verbose : bool,
    1.27 +     overlord : bool,
    1.28 +     spy : bool,
    1.29 +     blocking : bool,
    1.30 +     provers : string list,
    1.31 +     type_enc : string option,
    1.32 +     strict : bool,
    1.33 +     lam_trans : string option,
    1.34 +     uncurried_aliases : bool option,
    1.35 +     learn : bool,
    1.36 +     fact_filter : string option,
    1.37 +     max_facts : int option,
    1.38 +     fact_thresholds : real * real,
    1.39 +     max_mono_iters : int option,
    1.40 +     max_new_mono_instances : int option,
    1.41 +     isar_proofs : bool option,
    1.42 +     compress_isar : real,
    1.43 +     try0_isar : bool,
    1.44 +     slice : bool,
    1.45 +     minimize : bool option,
    1.46 +     timeout : Time.time,
    1.47 +     preplay_timeout : Time.time,
    1.48 +     expect : string}
    1.49 +
    1.50 +  type prover_problem =
    1.51 +    {comment : string,
    1.52 +     state : Proof.state,
    1.53 +     goal : thm,
    1.54 +     subgoal : int,
    1.55 +     subgoal_count : int,
    1.56 +     factss : (string * fact list) list}
    1.57 +
    1.58 +  type prover_result =
    1.59 +    {outcome : atp_failure option,
    1.60 +     used_facts : (string * stature) list,
    1.61 +     used_from : fact list,
    1.62 +     run_time : Time.time,
    1.63 +     preplay : (reconstructor * play_outcome) Lazy.lazy,
    1.64 +     message : reconstructor * play_outcome -> string,
    1.65 +     message_tail : string}
    1.66 +
    1.67 +  type prover =
    1.68 +    params -> ((string * string list) list -> string -> minimize_command)
    1.69 +    -> prover_problem -> prover_result
    1.70 +
    1.71 +  val dest_dir : string Config.T
    1.72 +  val problem_prefix : string Config.T
    1.73 +  val completish : bool Config.T
    1.74 +  val atp_full_names : bool Config.T
    1.75 +  val smt_builtins : bool Config.T
    1.76 +  val smt_triggers : bool Config.T
    1.77 +  val smt_weights : bool Config.T
    1.78 +  val smt_weight_min_facts : int Config.T
    1.79 +  val smt_min_weight : int Config.T
    1.80 +  val smt_max_weight : int Config.T
    1.81 +  val smt_max_weight_index : int Config.T
    1.82 +  val smt_weight_curve : (int -> int) Unsynchronized.ref
    1.83 +  val smt_max_slices : int Config.T
    1.84 +  val smt_slice_fact_frac : real Config.T
    1.85 +  val smt_slice_time_frac : real Config.T
    1.86 +  val smt_slice_min_secs : int Config.T
    1.87 +  val SledgehammerN : string
    1.88 +  val plain_metis : reconstructor
    1.89 +  val select_smt_solver : string -> Proof.context -> Proof.context
    1.90 +  val extract_reconstructor : params -> reconstructor -> string * (string * string list) list
    1.91 +  val is_reconstructor : string -> bool
    1.92 +  val is_atp : theory -> string -> bool
    1.93 +  val is_smt_prover : Proof.context -> string -> bool
    1.94 +  val is_ho_atp: Proof.context -> string -> bool
    1.95 +  val is_unit_equational_atp : Proof.context -> string -> bool
    1.96 +  val is_prover_supported : Proof.context -> string -> bool
    1.97 +  val is_prover_installed : Proof.context -> string -> bool
    1.98 +  val remotify_prover_if_supported_and_not_already_remote :
    1.99 +    Proof.context -> string -> string option
   1.100 +  val remotify_prover_if_not_installed :
   1.101 +    Proof.context -> string -> string option
   1.102 +  val default_max_facts_of_prover : Proof.context -> string -> int
   1.103 +  val is_unit_equality : term -> bool
   1.104 +  val is_appropriate_prop_of_prover : Proof.context -> string -> term -> bool
   1.105 +  val weight_smt_fact :
   1.106 +    Proof.context -> int -> ((string * stature) * thm) * int
   1.107 +    -> (string * stature) * (int option * thm)
   1.108 +  val supported_provers : Proof.context -> unit
   1.109 +  val kill_provers : unit -> unit
   1.110 +  val running_provers : unit -> unit
   1.111 +  val messages : int option -> unit
   1.112 +  val is_fact_chained : (('a * stature) * 'b) -> bool
   1.113 +  val filter_used_facts :
   1.114 +    bool -> (''a * stature) list -> ((''a * stature) * 'b) list ->
   1.115 +    ((''a * stature) * 'b) list
   1.116 +  val isar_proof_reconstructor : Proof.context -> string -> string
   1.117 +  val get_prover : Proof.context -> mode -> string -> prover
   1.118 +end;
   1.119 +
   1.120 +structure Sledgehammer_Prover : SLEDGEHAMMER_PROVER =
   1.121 +struct
   1.122 +
   1.123 +open ATP_Util
   1.124 +open ATP_Problem
   1.125 +open ATP_Proof
   1.126 +open ATP_Systems
   1.127 +open ATP_Problem_Generate
   1.128 +open ATP_Proof_Reconstruct
   1.129 +open Metis_Tactic
   1.130 +open Sledgehammer_Util
   1.131 +open Sledgehammer_Fact
   1.132 +open Sledgehammer_Reconstructor
   1.133 +open Sledgehammer_Print
   1.134 +open Sledgehammer_Reconstruct
   1.135 +
   1.136 +
   1.137 +(** The Sledgehammer **)
   1.138 +
   1.139 +(* Empty string means create files in Isabelle's temporary files directory. *)
   1.140 +val dest_dir = Attrib.setup_config_string @{binding sledgehammer_dest_dir} (K "")
   1.141 +val problem_prefix = Attrib.setup_config_string @{binding sledgehammer_problem_prefix} (K "prob")
   1.142 +val completish = Attrib.setup_config_bool @{binding sledgehammer_completish} (K false)
   1.143 +
   1.144 +(* In addition to being easier to read, readable names are often much shorter,
   1.145 +   especially if types are mangled in names. This makes a difference for some
   1.146 +   provers (e.g., E). For these reason, short names are enabled by default. *)
   1.147 +val atp_full_names = Attrib.setup_config_bool @{binding sledgehammer_atp_full_names} (K false)
   1.148 +
   1.149 +val smt_builtins = Attrib.setup_config_bool @{binding sledgehammer_smt_builtins} (K true)
   1.150 +val smt_triggers = Attrib.setup_config_bool @{binding sledgehammer_smt_triggers} (K true)
   1.151 +val smt_weights = Attrib.setup_config_bool @{binding sledgehammer_smt_weights} (K true)
   1.152 +val smt_weight_min_facts =
   1.153 +  Attrib.setup_config_int @{binding sledgehammer_smt_weight_min_facts} (K 20)
   1.154 +
   1.155 +datatype mode = Auto_Try | Try | Normal | MaSh | Auto_Minimize | Minimize
   1.156 +
   1.157 +(* Identifier that distinguishes Sledgehammer from other tools that could use
   1.158 +   "Async_Manager". *)
   1.159 +val SledgehammerN = "Sledgehammer"
   1.160 +
   1.161 +val reconstructor_names = [metisN, smtN]
   1.162 +val plain_metis = Metis (hd partial_type_encs, combsN)
   1.163 +val is_reconstructor = member (op =) reconstructor_names
   1.164 +
   1.165 +val is_atp = member (op =) o supported_atps
   1.166 +
   1.167 +val select_smt_solver = Context.proof_map o SMT_Config.select_solver
   1.168 +
   1.169 +fun is_smt_prover ctxt = member (op =) (SMT_Solver.available_solvers_of ctxt)
   1.170 +
   1.171 +fun is_atp_of_format is_format ctxt name =
   1.172 +  let val thy = Proof_Context.theory_of ctxt in
   1.173 +    case try (get_atp thy) name of
   1.174 +      SOME config =>
   1.175 +      exists (fn (_, ((_, format, _, _, _), _)) => is_format format)
   1.176 +             (#best_slices (config ()) ctxt)
   1.177 +    | NONE => false
   1.178 +  end
   1.179 +
   1.180 +val is_unit_equational_atp = is_atp_of_format (curry (op =) CNF_UEQ)
   1.181 +val is_ho_atp = is_atp_of_format is_format_higher_order
   1.182 +
   1.183 +fun is_prover_supported ctxt =
   1.184 +  let val thy = Proof_Context.theory_of ctxt in
   1.185 +    is_reconstructor orf is_atp thy orf is_smt_prover ctxt
   1.186 +  end
   1.187 +
   1.188 +fun is_prover_installed ctxt =
   1.189 +  is_reconstructor orf is_smt_prover ctxt orf
   1.190 +  is_atp_installed (Proof_Context.theory_of ctxt)
   1.191 +
   1.192 +fun remotify_prover_if_supported_and_not_already_remote ctxt name =
   1.193 +  if String.isPrefix remote_prefix name then
   1.194 +    SOME name
   1.195 +  else
   1.196 +    let val remote_name = remote_prefix ^ name in
   1.197 +      if is_prover_supported ctxt remote_name then SOME remote_name else NONE
   1.198 +    end
   1.199 +
   1.200 +fun remotify_prover_if_not_installed ctxt name =
   1.201 +  if is_prover_supported ctxt name andalso is_prover_installed ctxt name then
   1.202 +    SOME name
   1.203 +  else
   1.204 +    remotify_prover_if_supported_and_not_already_remote ctxt name
   1.205 +
   1.206 +fun get_slices slice slices =
   1.207 +  (0 upto length slices - 1) ~~ slices |> not slice ? (List.last #> single)
   1.208 +
   1.209 +val reconstructor_default_max_facts = 20
   1.210 +
   1.211 +fun slice_max_facts (_, ( ((max_facts, _), _, _, _, _), _)) = max_facts
   1.212 +
   1.213 +fun default_max_facts_of_prover ctxt name =
   1.214 +  let val thy = Proof_Context.theory_of ctxt in
   1.215 +    if is_reconstructor name then
   1.216 +      reconstructor_default_max_facts
   1.217 +    else if is_atp thy name then
   1.218 +      fold (Integer.max o slice_max_facts) (#best_slices (get_atp thy name ()) ctxt) 0
   1.219 +    else (* is_smt_prover ctxt name *)
   1.220 +      SMT_Solver.default_max_relevant ctxt name
   1.221 +  end
   1.222 +
   1.223 +fun is_if (@{const_name If}, _) = true
   1.224 +  | is_if _ = false
   1.225 +
   1.226 +(* Beware of "if and only if" (which is translated as such) and "If" (which is
   1.227 +   translated to conditional equations). *)
   1.228 +fun is_good_unit_equality T t u =
   1.229 +  T <> @{typ bool} andalso not (exists (exists_Const is_if) [t, u])
   1.230 +
   1.231 +fun is_unit_equality (@{const Trueprop} $ t) = is_unit_equality t
   1.232 +  | is_unit_equality (Const (@{const_name all}, _) $ Abs (_, _, t)) =
   1.233 +    is_unit_equality t
   1.234 +  | is_unit_equality (Const (@{const_name All}, _) $ Abs (_, _, t)) =
   1.235 +    is_unit_equality t
   1.236 +  | is_unit_equality (Const (@{const_name "=="}, Type (_, [T, _])) $ t $ u) =
   1.237 +    is_good_unit_equality T t u
   1.238 +  | is_unit_equality (Const (@{const_name HOL.eq}, Type (_ , [T, _])) $ t $ u) =
   1.239 +    is_good_unit_equality T t u
   1.240 +  | is_unit_equality _ = false
   1.241 +
   1.242 +fun is_appropriate_prop_of_prover ctxt name =
   1.243 +  if is_unit_equational_atp ctxt name then is_unit_equality else K true
   1.244 +
   1.245 +fun supported_provers ctxt =
   1.246 +  let
   1.247 +    val thy = Proof_Context.theory_of ctxt
   1.248 +    val (remote_provers, local_provers) =
   1.249 +      reconstructor_names @
   1.250 +      sort_strings (supported_atps thy) @
   1.251 +      sort_strings (SMT_Solver.available_solvers_of ctxt)
   1.252 +      |> List.partition (String.isPrefix remote_prefix)
   1.253 +  in
   1.254 +    Output.urgent_message ("Supported provers: " ^
   1.255 +                           commas (local_provers @ remote_provers) ^ ".")
   1.256 +  end
   1.257 +
   1.258 +fun kill_provers () = Async_Manager.kill_threads SledgehammerN "prover"
   1.259 +fun running_provers () = Async_Manager.running_threads SledgehammerN "prover"
   1.260 +val messages = Async_Manager.thread_messages SledgehammerN "prover"
   1.261 +
   1.262 +
   1.263 +(** problems, results, ATPs, etc. **)
   1.264 +
   1.265 +type params =
   1.266 +  {debug : bool,
   1.267 +   verbose : bool,
   1.268 +   overlord : bool,
   1.269 +   spy : bool,
   1.270 +   blocking : bool,
   1.271 +   provers : string list,
   1.272 +   type_enc : string option,
   1.273 +   strict : bool,
   1.274 +   lam_trans : string option,
   1.275 +   uncurried_aliases : bool option,
   1.276 +   learn : bool,
   1.277 +   fact_filter : string option,
   1.278 +   max_facts : int option,
   1.279 +   fact_thresholds : real * real,
   1.280 +   max_mono_iters : int option,
   1.281 +   max_new_mono_instances : int option,
   1.282 +   isar_proofs : bool option,
   1.283 +   compress_isar : real,
   1.284 +   try0_isar : bool,
   1.285 +   slice : bool,
   1.286 +   minimize : bool option,
   1.287 +   timeout : Time.time,
   1.288 +   preplay_timeout : Time.time,
   1.289 +   expect : string}
   1.290 +
   1.291 +type prover_problem =
   1.292 +  {comment : string,
   1.293 +   state : Proof.state,
   1.294 +   goal : thm,
   1.295 +   subgoal : int,
   1.296 +   subgoal_count : int,
   1.297 +   factss : (string * fact list) list}
   1.298 +
   1.299 +type prover_result =
   1.300 +  {outcome : atp_failure option,
   1.301 +   used_facts : (string * stature) list,
   1.302 +   used_from : fact list,
   1.303 +   run_time : Time.time,
   1.304 +   preplay : (reconstructor * play_outcome) Lazy.lazy,
   1.305 +   message : reconstructor * play_outcome -> string,
   1.306 +   message_tail : string}
   1.307 +
   1.308 +type prover =
   1.309 +  params -> ((string * string list) list -> string -> minimize_command)
   1.310 +  -> prover_problem -> prover_result
   1.311 +
   1.312 +(* FUDGE *)
   1.313 +val smt_min_weight =
   1.314 +  Attrib.setup_config_int @{binding sledgehammer_smt_min_weight} (K 0)
   1.315 +val smt_max_weight =
   1.316 +  Attrib.setup_config_int @{binding sledgehammer_smt_max_weight} (K 10)
   1.317 +val smt_max_weight_index =
   1.318 +  Attrib.setup_config_int @{binding sledgehammer_smt_max_weight_index} (K 200)
   1.319 +val smt_weight_curve = Unsynchronized.ref (fn x : int => x * x)
   1.320 +
   1.321 +fun smt_fact_weight ctxt j num_facts =
   1.322 +  if Config.get ctxt smt_weights andalso
   1.323 +     num_facts >= Config.get ctxt smt_weight_min_facts then
   1.324 +    let
   1.325 +      val min = Config.get ctxt smt_min_weight
   1.326 +      val max = Config.get ctxt smt_max_weight
   1.327 +      val max_index = Config.get ctxt smt_max_weight_index
   1.328 +      val curve = !smt_weight_curve
   1.329 +    in
   1.330 +      SOME (max - (max - min + 1) * curve (Int.max (0, max_index - j - 1))
   1.331 +            div curve max_index)
   1.332 +    end
   1.333 +  else
   1.334 +    NONE
   1.335 +
   1.336 +fun weight_smt_fact ctxt num_facts ((info, th), j) =
   1.337 +  let val thy = Proof_Context.theory_of ctxt in
   1.338 +    (info, (smt_fact_weight ctxt j num_facts, th |> Thm.transfer thy))
   1.339 +  end
   1.340 +
   1.341 +fun overlord_file_location_of_prover prover =
   1.342 +  (getenv "ISABELLE_HOME_USER", "prob_" ^ prover)
   1.343 +
   1.344 +fun proof_banner mode name =
   1.345 +  case mode of
   1.346 +    Auto_Try => "Auto Sledgehammer (" ^ quote name ^ ") found a proof"
   1.347 +  | Try => "Sledgehammer (" ^ quote name ^ ") found a proof"
   1.348 +  | _ => "Try this"
   1.349 +
   1.350 +fun bunch_of_reconstructors needs_full_types lam_trans =
   1.351 +  if needs_full_types then
   1.352 +    [Metis (full_type_enc, lam_trans false),
   1.353 +     Metis (really_full_type_enc, lam_trans false),
   1.354 +     Metis (full_type_enc, lam_trans true),
   1.355 +     Metis (really_full_type_enc, lam_trans true),
   1.356 +     SMT]
   1.357 +  else
   1.358 +    [Metis (partial_type_enc, lam_trans false),
   1.359 +     Metis (full_type_enc, lam_trans false),
   1.360 +     Metis (no_typesN, lam_trans true),
   1.361 +     Metis (really_full_type_enc, lam_trans true),
   1.362 +     SMT]
   1.363 +
   1.364 +fun extract_reconstructor ({type_enc, lam_trans, ...} : params) (Metis (type_enc', lam_trans')) =
   1.365 +    let
   1.366 +      val override_params =
   1.367 +        (if is_none type_enc andalso type_enc' = hd partial_type_encs then []
   1.368 +         else [("type_enc", [hd (unalias_type_enc type_enc')])]) @
   1.369 +        (if is_none lam_trans andalso lam_trans' = default_metis_lam_trans then []
   1.370 +         else [("lam_trans", [lam_trans'])])
   1.371 +    in (metisN, override_params) end
   1.372 +  | extract_reconstructor _ SMT = (smtN, [])
   1.373 +
   1.374 +(* based on "Mirabelle.can_apply" and generalized *)
   1.375 +fun timed_apply timeout tac state i =
   1.376 +  let
   1.377 +    val {context = ctxt, facts, goal} = Proof.goal state
   1.378 +    val full_tac = Method.insert_tac facts i THEN tac ctxt i
   1.379 +  in
   1.380 +    TimeLimit.timeLimit timeout (try (Seq.pull o full_tac)) goal
   1.381 +  end
   1.382 +
   1.383 +fun tac_of_reconstructor (Metis (type_enc, lam_trans)) = metis_tac [type_enc] lam_trans
   1.384 +  | tac_of_reconstructor SMT = SMT_Solver.smt_tac
   1.385 +
   1.386 +fun timed_reconstructor reconstr debug timeout ths =
   1.387 +  timed_apply timeout (silence_reconstructors debug
   1.388 +    #> (fn ctxt => tac_of_reconstructor reconstr ctxt ths))
   1.389 +
   1.390 +fun is_fact_chained ((_, (sc, _)), _) = sc = Chained
   1.391 +
   1.392 +fun filter_used_facts keep_chained used =
   1.393 +  filter ((member (op =) used o fst) orf (if keep_chained then is_fact_chained else K false))
   1.394 +
   1.395 +fun play_one_line_proof mode debug verbose timeout pairs state i preferred reconstrs =
   1.396 +  let
   1.397 +    fun get_preferred reconstrs =
   1.398 +      if member (op =) reconstrs preferred then preferred
   1.399 +      else List.last reconstrs
   1.400 +  in
   1.401 +    if timeout = Time.zeroTime then
   1.402 +      (get_preferred reconstrs, Not_Played)
   1.403 +    else
   1.404 +      let
   1.405 +        val _ = if mode = Minimize then Output.urgent_message "Preplaying proof..." else ()
   1.406 +        val ths = pairs |> sort_wrt (fst o fst) |> map snd
   1.407 +        fun play [] [] = (get_preferred reconstrs, Play_Failed)
   1.408 +          | play timed_outs [] = (get_preferred timed_outs, Play_Timed_Out timeout)
   1.409 +          | play timed_out (reconstr :: reconstrs) =
   1.410 +            let
   1.411 +              val _ =
   1.412 +                if verbose then
   1.413 +                  Output.urgent_message ("Trying \"" ^ string_of_reconstructor reconstr ^
   1.414 +                    "\" for " ^ string_of_time timeout ^ "...")
   1.415 +                else
   1.416 +                  ()
   1.417 +              val timer = Timer.startRealTimer ()
   1.418 +            in
   1.419 +              case timed_reconstructor reconstr debug timeout ths state i of
   1.420 +                SOME (SOME _) => (reconstr, Played (Timer.checkRealTimer timer))
   1.421 +              | _ => play timed_out reconstrs
   1.422 +            end
   1.423 +            handle TimeLimit.TimeOut => play (reconstr :: timed_out) reconstrs
   1.424 +      in
   1.425 +        play [] reconstrs
   1.426 +      end
   1.427 +  end
   1.428 +
   1.429 +
   1.430 +(* generic TPTP-based ATPs *)
   1.431 +
   1.432 +(* Too general means, positive equality literal with a variable X as one
   1.433 +   operand, when X does not occur properly in the other operand. This rules out
   1.434 +   clearly inconsistent facts such as X = a | X = b, though it by no means
   1.435 +   guarantees soundness. *)
   1.436 +
   1.437 +fun get_facts_of_filter _ [(_, facts)] = facts
   1.438 +  | get_facts_of_filter fact_filter factss =
   1.439 +    case AList.lookup (op =) factss fact_filter of
   1.440 +      SOME facts => facts
   1.441 +    | NONE => snd (hd factss)
   1.442 +
   1.443 +(* Unwanted equalities are those between a (bound or schematic) variable that
   1.444 +   does not properly occur in the second operand. *)
   1.445 +val is_exhaustive_finite =
   1.446 +  let
   1.447 +    fun is_bad_equal (Var z) t =
   1.448 +        not (exists_subterm (fn Var z' => z = z' | _ => false) t)
   1.449 +      | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
   1.450 +      | is_bad_equal _ _ = false
   1.451 +    fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
   1.452 +    fun do_formula pos t =
   1.453 +      case (pos, t) of
   1.454 +        (_, @{const Trueprop} $ t1) => do_formula pos t1
   1.455 +      | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
   1.456 +        do_formula pos t'
   1.457 +      | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
   1.458 +        do_formula pos t'
   1.459 +      | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
   1.460 +        do_formula pos t'
   1.461 +      | (_, @{const "==>"} $ t1 $ t2) =>
   1.462 +        do_formula (not pos) t1 andalso
   1.463 +        (t2 = @{prop False} orelse do_formula pos t2)
   1.464 +      | (_, @{const HOL.implies} $ t1 $ t2) =>
   1.465 +        do_formula (not pos) t1 andalso
   1.466 +        (t2 = @{const False} orelse do_formula pos t2)
   1.467 +      | (_, @{const Not} $ t1) => do_formula (not pos) t1
   1.468 +      | (true, @{const HOL.disj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
   1.469 +      | (false, @{const HOL.conj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
   1.470 +      | (true, Const (@{const_name HOL.eq}, _) $ t1 $ t2) => do_equals t1 t2
   1.471 +      | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
   1.472 +      | _ => false
   1.473 +  in do_formula true end
   1.474 +
   1.475 +fun has_bound_or_var_of_type pred =
   1.476 +  exists_subterm (fn Var (_, T as Type _) => pred T
   1.477 +                   | Abs (_, T as Type _, _) => pred T
   1.478 +                   | _ => false)
   1.479 +
   1.480 +(* Facts are forbidden to contain variables of these types. The typical reason
   1.481 +   is that they lead to unsoundness. Note that "unit" satisfies numerous
   1.482 +   equations like "?x = ()". The resulting clauses will have no type constraint,
   1.483 +   yielding false proofs. Even "bool" leads to many unsound proofs, though only
   1.484 +   for higher-order problems. *)
   1.485 +
   1.486 +(* Facts containing variables of type "unit" or "bool" or of the form
   1.487 +   "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
   1.488 +   are omitted. *)
   1.489 +fun is_dangerous_prop ctxt =
   1.490 +  transform_elim_prop
   1.491 +  #> (has_bound_or_var_of_type (is_type_surely_finite ctxt) orf
   1.492 +      is_exhaustive_finite)
   1.493 +
   1.494 +(* Important messages are important but not so important that users want to see
   1.495 +   them each time. *)
   1.496 +val atp_important_message_keep_quotient = 25
   1.497 +
   1.498 +fun choose_type_enc strictness best_type_enc format =
   1.499 +  the_default best_type_enc
   1.500 +  #> type_enc_of_string strictness
   1.501 +  #> adjust_type_enc format
   1.502 +
   1.503 +fun isar_proof_reconstructor ctxt name =
   1.504 +  let val thy = Proof_Context.theory_of ctxt in
   1.505 +    if is_atp thy name then name
   1.506 +    else remotify_prover_if_not_installed ctxt eN |> the_default name
   1.507 +  end
   1.508 +
   1.509 +(* See the analogous logic in the function "maybe_minimize" in
   1.510 +  "sledgehammer_minimize.ML". *)
   1.511 +fun choose_minimize_command ctxt (params as {isar_proofs, ...}) minimize_command name preplay =
   1.512 +  let
   1.513 +    val maybe_isar_name = name |> isar_proofs = SOME true ? isar_proof_reconstructor ctxt
   1.514 +    val (min_name, override_params) =
   1.515 +      (case preplay of
   1.516 +        (reconstr, Played _) =>
   1.517 +        if isar_proofs = SOME true then (maybe_isar_name, [])
   1.518 +        else extract_reconstructor params reconstr
   1.519 +      | _ => (maybe_isar_name, []))
   1.520 +  in minimize_command override_params min_name end
   1.521 +
   1.522 +val max_fact_instances = 10 (* FUDGE *)
   1.523 +
   1.524 +fun repair_monomorph_context max_iters best_max_iters max_new_instances
   1.525 +                             best_max_new_instances =
   1.526 +  Config.put Monomorph.max_rounds (max_iters |> the_default best_max_iters)
   1.527 +  #> Config.put Monomorph.max_new_instances
   1.528 +         (max_new_instances |> the_default best_max_new_instances)
   1.529 +  #> Config.put Monomorph.max_thm_instances max_fact_instances
   1.530 +
   1.531 +fun suffix_of_mode Auto_Try = "_try"
   1.532 +  | suffix_of_mode Try = "_try"
   1.533 +  | suffix_of_mode Normal = ""
   1.534 +  | suffix_of_mode MaSh = ""
   1.535 +  | suffix_of_mode Auto_Minimize = "_min"
   1.536 +  | suffix_of_mode Minimize = "_min"
   1.537 +
   1.538 +(* Give the ATPs some slack before interrupting them the hard way. "z3_tptp" on
   1.539 +   Linux appears to be the only ATP that does not honor its time limit. *)
   1.540 +val atp_timeout_slack = seconds 1.0
   1.541 +
   1.542 +val mono_max_privileged_facts = 10
   1.543 +
   1.544 +(* For low values of "max_facts", this fudge value ensures that most slices are
   1.545 +   invoked with a nontrivial amount of facts. *)
   1.546 +val max_fact_factor_fudge = 5
   1.547 +
   1.548 +fun run_atp mode name
   1.549 +    ({exec, arguments, proof_delims, known_failures, prem_role, best_slices, best_max_mono_iters,
   1.550 +      best_max_new_mono_instances, ...} : atp_config)
   1.551 +    (params as {debug, verbose, overlord, type_enc, strict, lam_trans, uncurried_aliases,
   1.552 +       fact_filter, max_facts, max_mono_iters, max_new_mono_instances, isar_proofs, compress_isar,
   1.553 +       try0_isar, slice, timeout, preplay_timeout, ...})
   1.554 +    minimize_command
   1.555 +    ({comment, state, goal, subgoal, subgoal_count, factss, ...} : prover_problem) =
   1.556 +  let
   1.557 +    val thy = Proof.theory_of state
   1.558 +    val ctxt = Proof.context_of state
   1.559 +    val atp_mode =
   1.560 +      if Config.get ctxt completish then Sledgehammer_Completish
   1.561 +      else Sledgehammer
   1.562 +    val (_, hyp_ts, concl_t) = strip_subgoal goal subgoal ctxt
   1.563 +    val (dest_dir, problem_prefix) =
   1.564 +      if overlord then overlord_file_location_of_prover name
   1.565 +      else (Config.get ctxt dest_dir, Config.get ctxt problem_prefix)
   1.566 +    val problem_file_name =
   1.567 +      Path.basic (problem_prefix ^ (if overlord then "" else serial_string ()) ^
   1.568 +                  suffix_of_mode mode ^ "_" ^ string_of_int subgoal)
   1.569 +    val prob_path =
   1.570 +      if dest_dir = "" then
   1.571 +        File.tmp_path problem_file_name
   1.572 +      else if File.exists (Path.explode dest_dir) then
   1.573 +        Path.append (Path.explode dest_dir) problem_file_name
   1.574 +      else
   1.575 +        error ("No such directory: " ^ quote dest_dir ^ ".")
   1.576 +    val exec = exec ()
   1.577 +    val command0 =
   1.578 +      case find_first (fn var => getenv var <> "") (fst exec) of
   1.579 +        SOME var =>
   1.580 +        let
   1.581 +          val pref = getenv var ^ "/"
   1.582 +          val paths = map (Path.explode o prefix pref) (snd exec)
   1.583 +        in
   1.584 +          case find_first File.exists paths of
   1.585 +            SOME path => path
   1.586 +          | NONE => error ("Bad executable: " ^ Path.print (hd paths) ^ ".")
   1.587 +        end
   1.588 +      | NONE => error ("The environment variable " ^ quote (List.last (fst exec)) ^
   1.589 +                       " is not set.")
   1.590 +    fun split_time s =
   1.591 +      let
   1.592 +        val split = String.tokens (fn c => str c = "\n")
   1.593 +        val (output, t) =
   1.594 +          s |> split |> (try split_last #> the_default ([], "0"))
   1.595 +            |>> cat_lines
   1.596 +        fun as_num f = f >> (fst o read_int)
   1.597 +        val num = as_num (Scan.many1 Symbol.is_ascii_digit)
   1.598 +        val digit = Scan.one Symbol.is_ascii_digit
   1.599 +        val num3 = as_num (digit ::: digit ::: (digit >> single))
   1.600 +        val time = num --| Scan.$$ "." -- num3 >> (fn (a, b) => a * 1000 + b)
   1.601 +        val as_time =
   1.602 +          raw_explode #> Scan.read Symbol.stopper time #> the_default 0
   1.603 +      in (output, as_time t |> Time.fromMilliseconds) end
   1.604 +    fun run () =
   1.605 +      let
   1.606 +        (* If slicing is disabled, we expand the last slice to fill the entire
   1.607 +           time available. *)
   1.608 +        val all_slices = best_slices ctxt
   1.609 +        val actual_slices = get_slices slice all_slices
   1.610 +        fun max_facts_of_slices f slices = fold (Integer.max o slice_max_facts o f) slices 0
   1.611 +        val num_actual_slices = length actual_slices
   1.612 +        val max_fact_factor =
   1.613 +          Real.fromInt (case max_facts of
   1.614 +              NONE => max_facts_of_slices I all_slices
   1.615 +            | SOME max => max)
   1.616 +          / Real.fromInt (max_facts_of_slices snd actual_slices)
   1.617 +        fun monomorphize_facts facts =
   1.618 +          let
   1.619 +            val ctxt =
   1.620 +              ctxt
   1.621 +              |> repair_monomorph_context max_mono_iters
   1.622 +                     best_max_mono_iters max_new_mono_instances
   1.623 +                     best_max_new_mono_instances
   1.624 +            (* pseudo-theorem involving the same constants as the subgoal *)
   1.625 +            val subgoal_th =
   1.626 +              Logic.list_implies (hyp_ts, concl_t) |> Skip_Proof.make_thm thy
   1.627 +            val rths =
   1.628 +              facts |> chop mono_max_privileged_facts
   1.629 +                    |>> map (pair 1 o snd)
   1.630 +                    ||> map (pair 2 o snd)
   1.631 +                    |> op @
   1.632 +                    |> cons (0, subgoal_th)
   1.633 +          in
   1.634 +            Monomorph.monomorph atp_schematic_consts_of ctxt rths
   1.635 +            |> tl |> curry ListPair.zip (map fst facts)
   1.636 +            |> maps (fn (name, rths) =>
   1.637 +                        map (pair name o zero_var_indexes o snd) rths)
   1.638 +          end
   1.639 +        fun run_slice time_left (cache_key, cache_value)
   1.640 +                (slice, (time_frac,
   1.641 +                     (key as ((best_max_facts, best_fact_filter), format,
   1.642 +                              best_type_enc, best_lam_trans,
   1.643 +                              best_uncurried_aliases),
   1.644 +                      extra))) =
   1.645 +          let
   1.646 +            val effective_fact_filter =
   1.647 +              fact_filter |> the_default best_fact_filter
   1.648 +            val facts = get_facts_of_filter effective_fact_filter factss
   1.649 +            val num_facts =
   1.650 +              Real.ceil (max_fact_factor * Real.fromInt best_max_facts) +
   1.651 +              max_fact_factor_fudge
   1.652 +              |> Integer.min (length facts)
   1.653 +            val strictness = if strict then Strict else Non_Strict
   1.654 +            val type_enc =
   1.655 +              type_enc |> choose_type_enc strictness best_type_enc format
   1.656 +            val sound = is_type_enc_sound type_enc
   1.657 +            val real_ms = Real.fromInt o Time.toMilliseconds
   1.658 +            val slice_timeout =
   1.659 +              (real_ms time_left
   1.660 +               |> (if slice < num_actual_slices - 1 then
   1.661 +                     curry Real.min (time_frac * real_ms timeout)
   1.662 +                   else
   1.663 +                     I))
   1.664 +              * 0.001
   1.665 +              |> seconds
   1.666 +            val generous_slice_timeout =
   1.667 +              if mode = MaSh then one_day else Time.+ (slice_timeout, atp_timeout_slack)
   1.668 +            val _ =
   1.669 +              if debug then
   1.670 +                quote name ^ " slice #" ^ string_of_int (slice + 1) ^
   1.671 +                " with " ^ string_of_int num_facts ^ " fact" ^
   1.672 +                plural_s num_facts ^ " for " ^ string_of_time slice_timeout ^ "..."
   1.673 +                |> Output.urgent_message
   1.674 +              else
   1.675 +                ()
   1.676 +            val readable_names = not (Config.get ctxt atp_full_names)
   1.677 +            val lam_trans =
   1.678 +              case lam_trans of
   1.679 +                SOME s => s
   1.680 +              | NONE => best_lam_trans
   1.681 +            val uncurried_aliases =
   1.682 +              case uncurried_aliases of
   1.683 +                SOME b => b
   1.684 +              | NONE => best_uncurried_aliases
   1.685 +            val value as (atp_problem, _, fact_names, _, _) =
   1.686 +              if cache_key = SOME key then
   1.687 +                cache_value
   1.688 +              else
   1.689 +                facts
   1.690 +                |> not sound
   1.691 +                   ? filter_out (is_dangerous_prop ctxt o prop_of o snd)
   1.692 +                |> take num_facts
   1.693 +                |> not (is_type_enc_polymorphic type_enc) ? monomorphize_facts
   1.694 +                |> map (apsnd prop_of)
   1.695 +                |> prepare_atp_problem ctxt format prem_role type_enc atp_mode
   1.696 +                                       lam_trans uncurried_aliases
   1.697 +                                       readable_names true hyp_ts concl_t
   1.698 +            fun sel_weights () = atp_problem_selection_weights atp_problem
   1.699 +            fun ord_info () = atp_problem_term_order_info atp_problem
   1.700 +            val ord = effective_term_order ctxt name
   1.701 +            val full_proof = isar_proofs |> the_default (mode = Minimize)
   1.702 +            val args =
   1.703 +              arguments ctxt full_proof extra slice_timeout (File.shell_path prob_path)
   1.704 +                (ord, ord_info, sel_weights)
   1.705 +            val command =
   1.706 +              "(exec 2>&1; " ^ File.shell_path command0 ^ " " ^ args ^ " " ^ ")"
   1.707 +              |> enclose "TIMEFORMAT='%3R'; { time " " ; }"
   1.708 +            val _ =
   1.709 +              atp_problem
   1.710 +              |> lines_of_atp_problem format ord ord_info
   1.711 +              |> cons ("% " ^ command ^ "\n" ^ (if comment = "" then "" else "% " ^ comment ^ "\n"))
   1.712 +              |> File.write_list prob_path
   1.713 +            val ((output, run_time), (atp_proof, outcome)) =
   1.714 +              TimeLimit.timeLimit generous_slice_timeout Isabelle_System.bash_output command
   1.715 +              |>> (if overlord then prefix ("% " ^ command ^ "\n% " ^ timestamp () ^ "\n") else I)
   1.716 +              |> fst |> split_time
   1.717 +              |> (fn accum as (output, _) =>
   1.718 +                     (accum,
   1.719 +                      extract_tstplike_proof_and_outcome verbose proof_delims known_failures output
   1.720 +                      |>> atp_proof_of_tstplike_proof atp_problem
   1.721 +                      handle UNRECOGNIZED_ATP_PROOF () => ([], SOME ProofIncomplete)))
   1.722 +              handle TimeLimit.TimeOut => (("", slice_timeout), ([], SOME TimedOut))
   1.723 +            val outcome =
   1.724 +              (case outcome of
   1.725 +                NONE =>
   1.726 +                (case used_facts_in_unsound_atp_proof ctxt fact_names atp_proof
   1.727 +                      |> Option.map (sort string_ord) of
   1.728 +                   SOME facts =>
   1.729 +                   let val failure = UnsoundProof (is_type_enc_sound type_enc, facts) in
   1.730 +                     if debug then (warning (string_of_atp_failure failure); NONE) else SOME failure
   1.731 +                   end
   1.732 +                 | NONE => NONE)
   1.733 +              | _ => outcome)
   1.734 +          in
   1.735 +            ((SOME key, value), (output, run_time, facts, atp_proof, outcome))
   1.736 +          end
   1.737 +        val timer = Timer.startRealTimer ()
   1.738 +        fun maybe_run_slice slice
   1.739 +                (result as (cache, (_, run_time0, _, _, SOME _))) =
   1.740 +            let
   1.741 +              val time_left = Time.- (timeout, Timer.checkRealTimer timer)
   1.742 +            in
   1.743 +              if Time.<= (time_left, Time.zeroTime) then
   1.744 +                result
   1.745 +              else
   1.746 +                run_slice time_left cache slice
   1.747 +                |> (fn (cache, (output, run_time, used_from, atp_proof, outcome)) =>
   1.748 +                  (cache, (output, Time.+ (run_time0, run_time), used_from, atp_proof, outcome)))
   1.749 +            end
   1.750 +          | maybe_run_slice _ result = result
   1.751 +      in
   1.752 +        ((NONE, ([], Symtab.empty, Vector.fromList [], [], Symtab.empty)),
   1.753 +         ("", Time.zeroTime, [], [], SOME InternalError))
   1.754 +        |> fold maybe_run_slice actual_slices
   1.755 +      end
   1.756 +    (* If the problem file has not been exported, remove it; otherwise, export
   1.757 +       the proof file too. *)
   1.758 +    fun clean_up () =
   1.759 +      if dest_dir = "" then (try File.rm prob_path; ()) else ()
   1.760 +    fun export (_, (output, _, _, _, _)) =
   1.761 +      if dest_dir = "" then ()
   1.762 +      else File.write (Path.explode (Path.implode prob_path ^ "_proof")) output
   1.763 +    val ((_, (_, pool, fact_names, lifted, sym_tab)),
   1.764 +         (output, run_time, used_from, atp_proof, outcome)) =
   1.765 +      with_cleanup clean_up run () |> tap export
   1.766 +    val important_message =
   1.767 +      if mode = Normal andalso random_range 0 (atp_important_message_keep_quotient - 1) = 0
   1.768 +      then
   1.769 +        extract_important_message output
   1.770 +      else
   1.771 +        ""
   1.772 +    val (used_facts, preplay, message, message_tail) =
   1.773 +      (case outcome of
   1.774 +        NONE =>
   1.775 +        let
   1.776 +          val used_facts = used_facts_in_atp_proof ctxt fact_names atp_proof
   1.777 +          val needs_full_types = is_typed_helper_used_in_atp_proof atp_proof
   1.778 +          val reconstrs =
   1.779 +            bunch_of_reconstructors needs_full_types (lam_trans_of_atp_proof atp_proof
   1.780 +              o (fn desperate => if desperate then hide_lamsN else default_metis_lam_trans))
   1.781 +        in
   1.782 +          (used_facts,
   1.783 +           Lazy.lazy (fn () =>
   1.784 +             let val used_pairs = used_from |> filter_used_facts false used_facts in
   1.785 +               play_one_line_proof mode debug verbose preplay_timeout used_pairs state subgoal
   1.786 +                 (hd reconstrs) reconstrs
   1.787 +             end),
   1.788 +           fn preplay =>
   1.789 +              let
   1.790 +                val _ = if verbose then Output.urgent_message "Generating proof text..." else ()
   1.791 +                fun isar_params () =
   1.792 +                  let
   1.793 +                    val metis_type_enc =
   1.794 +                      if is_typed_helper_used_in_atp_proof atp_proof then full_typesN
   1.795 +                      else partial_typesN
   1.796 +                    val metis_lam_trans = lam_trans_of_atp_proof atp_proof default_metis_lam_trans
   1.797 +                    val atp_proof =
   1.798 +                      atp_proof
   1.799 +                      |> termify_atp_proof ctxt pool lifted sym_tab
   1.800 +                      |> introduce_spass_skolem
   1.801 +                      |> factify_atp_proof fact_names hyp_ts concl_t
   1.802 +                  in
   1.803 +                    (verbose, metis_type_enc, metis_lam_trans, preplay_timeout, compress_isar,
   1.804 +                     try0_isar, atp_proof, goal)
   1.805 +                  end
   1.806 +                val one_line_params =
   1.807 +                  (preplay, proof_banner mode name, used_facts,
   1.808 +                   choose_minimize_command ctxt params minimize_command name preplay,
   1.809 +                   subgoal, subgoal_count)
   1.810 +                val num_chained = length (#facts (Proof.goal state))
   1.811 +              in
   1.812 +                proof_text ctxt debug isar_proofs isar_params num_chained one_line_params
   1.813 +              end,
   1.814 +           (if verbose then "\nATP real CPU time: " ^ string_of_time run_time ^ "." else "") ^
   1.815 +           (if important_message <> "" then
   1.816 +              "\n\nImportant message from Dr. Geoff Sutcliffe:\n" ^ important_message
   1.817 +            else
   1.818 +              ""))
   1.819 +        end
   1.820 +      | SOME failure =>
   1.821 +        ([], Lazy.value (plain_metis, Play_Failed), fn _ => string_of_atp_failure failure, ""))
   1.822 +  in
   1.823 +    {outcome = outcome, used_facts = used_facts, used_from = used_from, run_time = run_time,
   1.824 +     preplay = preplay, message = message, message_tail = message_tail}
   1.825 +  end
   1.826 +
   1.827 +(* "SMT_Failure.Abnormal_Termination" carries the solver's return code. Until
   1.828 +   these are sorted out properly in the SMT module, we have to interpret these
   1.829 +   ourselves. *)
   1.830 +val remote_smt_failures =
   1.831 +  [(2, NoLibwwwPerl),
   1.832 +   (22, CantConnect)]
   1.833 +val z3_failures =
   1.834 +  [(101, OutOfResources),
   1.835 +   (103, MalformedInput),
   1.836 +   (110, MalformedInput),
   1.837 +   (112, TimedOut)]
   1.838 +val unix_failures =
   1.839 +  [(138, Crashed),
   1.840 +   (139, Crashed)]
   1.841 +val smt_failures = remote_smt_failures @ z3_failures @ unix_failures
   1.842 +
   1.843 +fun failure_of_smt_failure (SMT_Failure.Counterexample {is_real_cex, ...}) =
   1.844 +    if is_real_cex then Unprovable else GaveUp
   1.845 +  | failure_of_smt_failure SMT_Failure.Time_Out = TimedOut
   1.846 +  | failure_of_smt_failure (SMT_Failure.Abnormal_Termination code) =
   1.847 +    (case AList.lookup (op =) smt_failures code of
   1.848 +       SOME failure => failure
   1.849 +     | NONE => UnknownError ("Abnormal termination with exit code " ^
   1.850 +                             string_of_int code ^ "."))
   1.851 +  | failure_of_smt_failure SMT_Failure.Out_Of_Memory = OutOfResources
   1.852 +  | failure_of_smt_failure (SMT_Failure.Other_Failure s) = UnknownError s
   1.853 +
   1.854 +(* FUDGE *)
   1.855 +val smt_max_slices =
   1.856 +  Attrib.setup_config_int @{binding sledgehammer_smt_max_slices} (K 8)
   1.857 +val smt_slice_fact_frac =
   1.858 +  Attrib.setup_config_real @{binding sledgehammer_smt_slice_fact_frac}
   1.859 +                           (K 0.667)
   1.860 +val smt_slice_time_frac =
   1.861 +  Attrib.setup_config_real @{binding sledgehammer_smt_slice_time_frac} (K 0.333)
   1.862 +val smt_slice_min_secs =
   1.863 +  Attrib.setup_config_int @{binding sledgehammer_smt_slice_min_secs} (K 3)
   1.864 +
   1.865 +val is_boring_builtin_typ =
   1.866 +  not o exists_subtype (member (op =) [@{typ nat}, @{typ int}, HOLogic.realT])
   1.867 +
   1.868 +fun smt_filter_loop name ({debug, overlord, max_mono_iters, max_new_mono_instances, timeout, slice,
   1.869 +      ...} : params) state goal i =
   1.870 +  let
   1.871 +    fun repair_context ctxt =
   1.872 +      ctxt |> select_smt_solver name
   1.873 +           |> Config.put SMT_Config.verbose debug
   1.874 +           |> (if overlord then
   1.875 +                 Config.put SMT_Config.debug_files
   1.876 +                            (overlord_file_location_of_prover name
   1.877 +                             |> (fn (path, name) => path ^ "/" ^ name))
   1.878 +               else
   1.879 +                 I)
   1.880 +           |> Config.put SMT_Config.infer_triggers
   1.881 +                         (Config.get ctxt smt_triggers)
   1.882 +           |> not (Config.get ctxt smt_builtins)
   1.883 +              ? (SMT_Builtin.filter_builtins is_boring_builtin_typ
   1.884 +                 #> Config.put SMT_Config.datatypes false)
   1.885 +           |> repair_monomorph_context max_mono_iters default_max_mono_iters
   1.886 +                  max_new_mono_instances default_max_new_mono_instances
   1.887 +    val state = Proof.map_context (repair_context) state
   1.888 +    val ctxt = Proof.context_of state
   1.889 +    val max_slices = if slice then Config.get ctxt smt_max_slices else 1
   1.890 +    fun do_slice timeout slice outcome0 time_so_far
   1.891 +                 (weighted_factss as (fact_filter, weighted_facts) :: _) =
   1.892 +      let
   1.893 +        val timer = Timer.startRealTimer ()
   1.894 +        val slice_timeout =
   1.895 +          if slice < max_slices then
   1.896 +            let val ms = Time.toMilliseconds timeout in
   1.897 +              Int.min (ms,
   1.898 +                  Int.max (1000 * Config.get ctxt smt_slice_min_secs,
   1.899 +                      Real.ceil (Config.get ctxt smt_slice_time_frac
   1.900 +                                 * Real.fromInt ms)))
   1.901 +              |> Time.fromMilliseconds
   1.902 +            end
   1.903 +          else
   1.904 +            timeout
   1.905 +        val num_facts = length weighted_facts
   1.906 +        val _ =
   1.907 +          if debug then
   1.908 +            quote name ^ " slice " ^ string_of_int slice ^ " with " ^ string_of_int num_facts ^
   1.909 +            " fact" ^ plural_s num_facts ^ " for " ^ string_of_time slice_timeout
   1.910 +            |> Output.urgent_message
   1.911 +          else
   1.912 +            ()
   1.913 +        val birth = Timer.checkRealTimer timer
   1.914 +        val _ =
   1.915 +          if debug then Output.urgent_message "Invoking SMT solver..." else ()
   1.916 +        val (outcome, used_facts) =
   1.917 +          SMT_Solver.smt_filter_preprocess ctxt [] goal weighted_facts i
   1.918 +          |> SMT_Solver.smt_filter_apply slice_timeout
   1.919 +          |> (fn {outcome, used_facts} => (outcome, used_facts))
   1.920 +          handle exn => if Exn.is_interrupt exn then
   1.921 +                          reraise exn
   1.922 +                        else
   1.923 +                          (ML_Compiler.exn_message exn
   1.924 +                           |> SMT_Failure.Other_Failure |> SOME, [])
   1.925 +        val death = Timer.checkRealTimer timer
   1.926 +        val outcome0 = if is_none outcome0 then SOME outcome else outcome0
   1.927 +        val time_so_far = Time.+ (time_so_far, Time.- (death, birth))
   1.928 +        val too_many_facts_perhaps =
   1.929 +          case outcome of
   1.930 +            NONE => false
   1.931 +          | SOME (SMT_Failure.Counterexample _) => false
   1.932 +          | SOME SMT_Failure.Time_Out => slice_timeout <> timeout
   1.933 +          | SOME (SMT_Failure.Abnormal_Termination _) => true (* kind of *)
   1.934 +          | SOME SMT_Failure.Out_Of_Memory => true
   1.935 +          | SOME (SMT_Failure.Other_Failure _) => true
   1.936 +        val timeout = Time.- (timeout, Timer.checkRealTimer timer)
   1.937 +      in
   1.938 +        if too_many_facts_perhaps andalso slice < max_slices andalso num_facts > 0 andalso
   1.939 +           Time.> (timeout, Time.zeroTime) then
   1.940 +          let
   1.941 +            val new_num_facts =
   1.942 +              Real.ceil (Config.get ctxt smt_slice_fact_frac * Real.fromInt num_facts)
   1.943 +            val weighted_factss as (new_fact_filter, _) :: _ =
   1.944 +              weighted_factss
   1.945 +              |> (fn (x :: xs) => xs @ [x])
   1.946 +              |> app_hd (apsnd (take new_num_facts))
   1.947 +            val show_filter = fact_filter <> new_fact_filter
   1.948 +            fun num_of_facts fact_filter num_facts =
   1.949 +              string_of_int num_facts ^
   1.950 +              (if show_filter then " " ^ quote fact_filter else "") ^
   1.951 +              " fact" ^ plural_s num_facts
   1.952 +            val _ =
   1.953 +              if debug then
   1.954 +                quote name ^ " invoked with " ^
   1.955 +                num_of_facts fact_filter num_facts ^ ": " ^
   1.956 +                string_of_atp_failure (failure_of_smt_failure (the outcome)) ^
   1.957 +                " Retrying with " ^ num_of_facts new_fact_filter new_num_facts ^
   1.958 +                "..."
   1.959 +                |> Output.urgent_message
   1.960 +              else
   1.961 +                ()
   1.962 +          in
   1.963 +            do_slice timeout (slice + 1) outcome0 time_so_far weighted_factss
   1.964 +          end
   1.965 +        else
   1.966 +          {outcome = if is_none outcome then NONE else the outcome0, used_facts = used_facts,
   1.967 +           used_from = map (apsnd snd) weighted_facts, run_time = time_so_far}
   1.968 +      end
   1.969 +  in
   1.970 +    do_slice timeout 1 NONE Time.zeroTime
   1.971 +  end
   1.972 +
   1.973 +fun run_smt_solver mode name (params as {debug, verbose, preplay_timeout, ...}) minimize_command
   1.974 +    ({state, goal, subgoal, subgoal_count, factss, ...} : prover_problem) =
   1.975 +  let
   1.976 +    val ctxt = Proof.context_of state
   1.977 +    fun weight_facts facts =
   1.978 +      let val num_facts = length facts in
   1.979 +        facts ~~ (0 upto num_facts - 1)
   1.980 +        |> map (weight_smt_fact ctxt num_facts)
   1.981 +      end
   1.982 +    val weighted_factss = factss |> map (apsnd weight_facts)
   1.983 +    val {outcome, used_facts = used_pairs, used_from, run_time} =
   1.984 +      smt_filter_loop name params state goal subgoal weighted_factss
   1.985 +    val used_facts = used_pairs |> map fst
   1.986 +    val outcome = outcome |> Option.map failure_of_smt_failure
   1.987 +    val (preplay, message, message_tail) =
   1.988 +      case outcome of
   1.989 +        NONE =>
   1.990 +        (Lazy.lazy (fn () =>
   1.991 +           play_one_line_proof mode debug verbose preplay_timeout used_pairs
   1.992 +               state subgoal SMT
   1.993 +               (bunch_of_reconstructors false (fn desperate =>
   1.994 +                  if desperate then liftingN else default_metis_lam_trans))),
   1.995 +         fn preplay =>
   1.996 +            let
   1.997 +              val one_line_params =
   1.998 +                (preplay, proof_banner mode name, used_facts,
   1.999 +                 choose_minimize_command ctxt params minimize_command name preplay,
  1.1000 +                 subgoal, subgoal_count)
  1.1001 +              val num_chained = length (#facts (Proof.goal state))
  1.1002 +            in
  1.1003 +              one_line_proof_text num_chained one_line_params
  1.1004 +            end,
  1.1005 +         if verbose then "\nSMT solver real CPU time: " ^ string_of_time run_time ^ "." else "")
  1.1006 +      | SOME failure =>
  1.1007 +        (Lazy.value (plain_metis, Play_Failed),
  1.1008 +         fn _ => string_of_atp_failure failure, "")
  1.1009 +  in
  1.1010 +    {outcome = outcome, used_facts = used_facts, used_from = used_from,
  1.1011 +     run_time = run_time, preplay = preplay, message = message,
  1.1012 +     message_tail = message_tail}
  1.1013 +  end
  1.1014 +
  1.1015 +fun run_reconstructor mode name
  1.1016 +        (params as {debug, verbose, timeout, type_enc, lam_trans, ...})
  1.1017 +        minimize_command
  1.1018 +        ({state, subgoal, subgoal_count, factss = (_, facts) :: _, ...}
  1.1019 +         : prover_problem) =
  1.1020 +  let
  1.1021 +    val reconstr =
  1.1022 +      if name = metisN then
  1.1023 +        Metis (type_enc |> the_default (hd partial_type_encs),
  1.1024 +               lam_trans |> the_default default_metis_lam_trans)
  1.1025 +      else if name = smtN then
  1.1026 +        SMT
  1.1027 +      else
  1.1028 +        raise Fail ("unknown reconstructor: " ^ quote name)
  1.1029 +    val used_facts = facts |> map fst
  1.1030 +  in
  1.1031 +    (case play_one_line_proof (if mode = Minimize then Normal else mode) debug verbose timeout facts
  1.1032 +       state subgoal reconstr [reconstr] of
  1.1033 +      play as (_, Played time) =>
  1.1034 +      {outcome = NONE, used_facts = used_facts, used_from = facts, run_time = time,
  1.1035 +       preplay = Lazy.value play,
  1.1036 +       message =
  1.1037 +         fn play =>
  1.1038 +            let
  1.1039 +              val (_, override_params) = extract_reconstructor params reconstr
  1.1040 +              val one_line_params =
  1.1041 +                (play, proof_banner mode name, used_facts, minimize_command override_params name,
  1.1042 +                 subgoal, subgoal_count)
  1.1043 +              val num_chained = length (#facts (Proof.goal state))
  1.1044 +            in
  1.1045 +              one_line_proof_text num_chained one_line_params
  1.1046 +            end,
  1.1047 +       message_tail = ""}
  1.1048 +    | play =>
  1.1049 +      let
  1.1050 +        val failure = (case play of (_, Play_Failed) => GaveUp | _ => TimedOut)
  1.1051 +      in
  1.1052 +        {outcome = SOME failure, used_facts = [], used_from = [],
  1.1053 +         run_time = Time.zeroTime, preplay = Lazy.value play,
  1.1054 +         message = fn _ => string_of_atp_failure failure, message_tail = ""}
  1.1055 +      end)
  1.1056 +  end
  1.1057 +
  1.1058 +fun get_prover ctxt mode name =
  1.1059 +  let val thy = Proof_Context.theory_of ctxt in
  1.1060 +    if is_reconstructor name then run_reconstructor mode name
  1.1061 +    else if is_atp thy name then run_atp mode name (get_atp thy name ())
  1.1062 +    else if is_smt_prover ctxt name then run_smt_solver mode name
  1.1063 +    else error ("No such prover: " ^ name ^ ".")
  1.1064 +  end
  1.1065 +
  1.1066 +end;