src/HOL/Tools/Sledgehammer/sledgehammer_provers.ML
author wenzelm
Thu Jul 18 20:53:22 2013 +0200 (2013-07-18 ago)
changeset 52697 6fb98a20c349
parent 52632 23393c31c7fe
child 52754 d9d90d29860e
permissions -rw-r--r--
explicit padding on command boundary for "auto" generated sendback -- do not replace the corresponding goal command, but append to it;
     1 (*  Title:      HOL/Tools/Sledgehammer/sledgehammer_provers.ML
     2     Author:     Fabian Immler, TU Muenchen
     3     Author:     Makarius
     4     Author:     Jasmin Blanchette, TU Muenchen
     5 
     6 Generic prover abstraction for Sledgehammer.
     7 *)
     8 
     9 signature SLEDGEHAMMER_PROVERS =
    10 sig
    11   type failure = ATP_Proof.failure
    12   type stature = ATP_Problem_Generate.stature
    13   type type_enc = ATP_Problem_Generate.type_enc
    14   type fact = Sledgehammer_Fact.fact
    15   type reconstructor = Sledgehammer_Reconstructor.reconstructor
    16   type play = Sledgehammer_Reconstructor.play
    17   type minimize_command = Sledgehammer_Reconstructor.minimize_command
    18 
    19   datatype mode = Auto_Try | Try | Normal | MaSh | Auto_Minimize | Minimize
    20 
    21   type params =
    22     {debug : bool,
    23      verbose : bool,
    24      overlord : bool,
    25      blocking : bool,
    26      provers : string list,
    27      type_enc : string option,
    28      strict : bool,
    29      lam_trans : string option,
    30      uncurried_aliases : bool option,
    31      learn : bool,
    32      fact_filter : string option,
    33      max_facts : int option,
    34      fact_thresholds : real * real,
    35      max_mono_iters : int option,
    36      max_new_mono_instances : int option,
    37      isar_proofs : bool option,
    38      isar_compress : real,
    39      isar_compress_degree : int,
    40      merge_timeout_slack : real,
    41      isar_try0 : bool,
    42      isar_minimize : bool,
    43      slice : bool,
    44      minimize : bool option,
    45      timeout : Time.time option,
    46      preplay_timeout : Time.time option,
    47      preplay_trace : bool,
    48      expect : string}
    49 
    50   type relevance_fudge =
    51     {local_const_multiplier : real,
    52      worse_irrel_freq : real,
    53      higher_order_irrel_weight : real,
    54      abs_rel_weight : real,
    55      abs_irrel_weight : real,
    56      skolem_irrel_weight : real,
    57      theory_const_rel_weight : real,
    58      theory_const_irrel_weight : real,
    59      chained_const_irrel_weight : real,
    60      intro_bonus : real,
    61      elim_bonus : real,
    62      simp_bonus : real,
    63      local_bonus : real,
    64      assum_bonus : real,
    65      chained_bonus : real,
    66      max_imperfect : real,
    67      max_imperfect_exp : real,
    68      threshold_divisor : real,
    69      ridiculous_threshold : real}
    70 
    71   type prover_problem =
    72     {state : Proof.state,
    73      goal : thm,
    74      subgoal : int,
    75      subgoal_count : int,
    76      factss : (string * fact list) list}
    77 
    78   type prover_result =
    79     {outcome : failure option,
    80      used_facts : (string * stature) list,
    81      used_from : fact list,
    82      run_time : Time.time,
    83      preplay : play Lazy.lazy,
    84      message : play -> string,
    85      message_tail : string}
    86 
    87   type prover =
    88     params -> ((string * string list) list -> string -> minimize_command)
    89     -> prover_problem -> prover_result
    90 
    91   val dest_dir : string Config.T
    92   val problem_prefix : string Config.T
    93   val completish : bool Config.T
    94   val atp_full_names : bool Config.T
    95   val smt_triggers : bool Config.T
    96   val smt_weights : bool Config.T
    97   val smt_weight_min_facts : int Config.T
    98   val smt_min_weight : int Config.T
    99   val smt_max_weight : int Config.T
   100   val smt_max_weight_index : int Config.T
   101   val smt_weight_curve : (int -> int) Unsynchronized.ref
   102   val smt_max_slices : int Config.T
   103   val smt_slice_fact_frac : real Config.T
   104   val smt_slice_time_frac : real Config.T
   105   val smt_slice_min_secs : int Config.T
   106   val SledgehammerN : string
   107   val plain_metis : reconstructor
   108   val select_smt_solver : string -> Proof.context -> Proof.context
   109   val extract_reconstructor :
   110     params -> reconstructor -> string * (string * string list) list
   111   val is_reconstructor : string -> bool
   112   val is_atp : theory -> string -> bool
   113   val is_smt_prover : Proof.context -> string -> bool
   114   val is_ho_atp: Proof.context -> string -> bool
   115   val is_unit_equational_atp : Proof.context -> string -> bool
   116   val is_prover_supported : Proof.context -> string -> bool
   117   val is_prover_installed : Proof.context -> string -> bool
   118   val remotify_prover_if_supported_and_not_already_remote :
   119     Proof.context -> string -> string option
   120   val remotify_prover_if_not_installed :
   121     Proof.context -> string -> string option
   122   val default_max_facts_of_prover : Proof.context -> bool -> string -> int
   123   val is_unit_equality : term -> bool
   124   val is_appropriate_prop_of_prover : Proof.context -> string -> term -> bool
   125   val is_built_in_const_of_prover :
   126     Proof.context -> string -> string * typ -> term list -> bool * term list
   127   val atp_relevance_fudge : relevance_fudge
   128   val smt_relevance_fudge : relevance_fudge
   129   val relevance_fudge_of_prover : Proof.context -> string -> relevance_fudge
   130   val weight_smt_fact :
   131     Proof.context -> int -> ((string * stature) * thm) * int
   132     -> (string * stature) * (int option * thm)
   133   val supported_provers : Proof.context -> unit
   134   val kill_provers : unit -> unit
   135   val running_provers : unit -> unit
   136   val messages : int option -> unit
   137   val is_fact_chained : (('a * stature) * 'b) -> bool
   138   val filter_used_facts :
   139     bool -> (''a * stature) list -> ((''a * stature) * 'b) list ->
   140     ((''a * stature) * 'b) list
   141   val isar_proof_reconstructor : Proof.context -> string -> string
   142   val get_prover : Proof.context -> mode -> string -> prover
   143 end;
   144 
   145 structure Sledgehammer_Provers : SLEDGEHAMMER_PROVERS =
   146 struct
   147 
   148 open ATP_Util
   149 open ATP_Problem
   150 open ATP_Proof
   151 open ATP_Systems
   152 open ATP_Problem_Generate
   153 open ATP_Proof_Reconstruct
   154 open Metis_Tactic
   155 open Sledgehammer_Util
   156 open Sledgehammer_Fact
   157 open Sledgehammer_Reconstructor
   158 open Sledgehammer_Print
   159 open Sledgehammer_Reconstruct
   160 
   161 
   162 (** The Sledgehammer **)
   163 
   164 datatype mode = Auto_Try | Try | Normal | MaSh | Auto_Minimize | Minimize
   165 
   166 (* Identifier that distinguishes Sledgehammer from other tools that could use
   167    "Async_Manager". *)
   168 val SledgehammerN = "Sledgehammer"
   169 
   170 val reconstructor_names = [metisN, smtN]
   171 val plain_metis = Metis (hd partial_type_encs, combsN)
   172 val is_reconstructor = member (op =) reconstructor_names
   173 
   174 val is_atp = member (op =) o supported_atps
   175 
   176 val select_smt_solver = Context.proof_map o SMT_Config.select_solver
   177 
   178 fun is_smt_prover ctxt = member (op =) (SMT_Solver.available_solvers_of ctxt)
   179 
   180 fun is_atp_of_format is_format ctxt name =
   181   let val thy = Proof_Context.theory_of ctxt in
   182     case try (get_atp thy) name of
   183       SOME config =>
   184       exists (fn (_, ((_, format, _, _, _), _)) => is_format format)
   185              (#best_slices (config ()) ctxt)
   186     | NONE => false
   187   end
   188 
   189 val is_unit_equational_atp = is_atp_of_format (curry (op =) CNF_UEQ)
   190 val is_ho_atp = is_atp_of_format is_format_higher_order
   191 
   192 fun is_prover_supported ctxt =
   193   let val thy = Proof_Context.theory_of ctxt in
   194     is_reconstructor orf is_atp thy orf is_smt_prover ctxt
   195   end
   196 
   197 fun is_prover_installed ctxt =
   198   is_reconstructor orf is_smt_prover ctxt orf
   199   is_atp_installed (Proof_Context.theory_of ctxt)
   200 
   201 fun remotify_prover_if_supported_and_not_already_remote ctxt name =
   202   if String.isPrefix remote_prefix name then
   203     SOME name
   204   else
   205     let val remote_name = remote_prefix ^ name in
   206       if is_prover_supported ctxt remote_name then SOME remote_name else NONE
   207     end
   208 
   209 fun remotify_prover_if_not_installed ctxt name =
   210   if is_prover_supported ctxt name andalso is_prover_installed ctxt name then
   211     SOME name
   212   else
   213     remotify_prover_if_supported_and_not_already_remote ctxt name
   214 
   215 fun get_slices slice slices =
   216   (0 upto length slices - 1) ~~ slices |> not slice ? (List.last #> single)
   217 
   218 val reconstructor_default_max_facts = 20
   219 
   220 fun slice_max_facts (_, (_, ( ((max_facts, _), _, _, _, _), _))) = max_facts
   221 
   222 fun default_max_facts_of_prover ctxt slice name =
   223   let val thy = Proof_Context.theory_of ctxt in
   224     if is_reconstructor name then
   225       reconstructor_default_max_facts
   226     else if is_atp thy name then
   227       fold (Integer.max o slice_max_facts)
   228            (get_slices slice (#best_slices (get_atp thy name ()) ctxt)) 0
   229     else (* is_smt_prover ctxt name *)
   230       SMT_Solver.default_max_relevant ctxt name
   231   end
   232 
   233 fun is_if (@{const_name If}, _) = true
   234   | is_if _ = false
   235 
   236 (* Beware of "if and only if" (which is translated as such) and "If" (which is
   237    translated to conditional equations). *)
   238 fun is_good_unit_equality T t u =
   239   T <> @{typ bool} andalso not (exists (exists_Const is_if) [t, u])
   240 
   241 fun is_unit_equality (@{const Trueprop} $ t) = is_unit_equality t
   242   | is_unit_equality (Const (@{const_name all}, _) $ Abs (_, _, t)) =
   243     is_unit_equality t
   244   | is_unit_equality (Const (@{const_name All}, _) $ Abs (_, _, t)) =
   245     is_unit_equality t
   246   | is_unit_equality (Const (@{const_name "=="}, Type (_, [T, _])) $ t $ u) =
   247     is_good_unit_equality T t u
   248   | is_unit_equality (Const (@{const_name HOL.eq}, Type (_ , [T, _])) $ t $ u) =
   249     is_good_unit_equality T t u
   250   | is_unit_equality _ = false
   251 
   252 fun is_appropriate_prop_of_prover ctxt name =
   253   if is_unit_equational_atp ctxt name then is_unit_equality else K true
   254 
   255 fun is_built_in_const_of_prover ctxt name =
   256   if is_smt_prover ctxt name then
   257     let val ctxt = ctxt |> select_smt_solver name in
   258       fn x => fn ts =>
   259          if SMT_Builtin.is_builtin_num_ext ctxt (list_comb (Const x, ts)) then
   260            (true, [])
   261          else if SMT_Builtin.is_builtin_fun_ext ctxt x ts then
   262            (true, ts)
   263          else
   264            (false, ts)
   265     end
   266   else
   267     fn (s, _) => fn ts => (member (op =) atp_irrelevant_consts s, ts)
   268 
   269 (* FUDGE *)
   270 val atp_relevance_fudge =
   271   {local_const_multiplier = 1.5,
   272    worse_irrel_freq = 100.0,
   273    higher_order_irrel_weight = 1.05,
   274    abs_rel_weight = 0.5,
   275    abs_irrel_weight = 2.0,
   276    skolem_irrel_weight = 0.05,
   277    theory_const_rel_weight = 0.5,
   278    theory_const_irrel_weight = 0.25,
   279    chained_const_irrel_weight = 0.25,
   280    intro_bonus = 0.15,
   281    elim_bonus = 0.15,
   282    simp_bonus = 0.15,
   283    local_bonus = 0.55,
   284    assum_bonus = 1.05,
   285    chained_bonus = 1.5,
   286    max_imperfect = 11.5,
   287    max_imperfect_exp = 1.0,
   288    threshold_divisor = 2.0,
   289    ridiculous_threshold = 0.01}
   290 
   291 (* FUDGE (FIXME) *)
   292 val smt_relevance_fudge =
   293   {local_const_multiplier = #local_const_multiplier atp_relevance_fudge,
   294    worse_irrel_freq = #worse_irrel_freq atp_relevance_fudge,
   295    higher_order_irrel_weight = #higher_order_irrel_weight atp_relevance_fudge,
   296    abs_rel_weight = #abs_rel_weight atp_relevance_fudge,
   297    abs_irrel_weight = #abs_irrel_weight atp_relevance_fudge,
   298    skolem_irrel_weight = #skolem_irrel_weight atp_relevance_fudge,
   299    theory_const_rel_weight = #theory_const_rel_weight atp_relevance_fudge,
   300    theory_const_irrel_weight = #theory_const_irrel_weight atp_relevance_fudge,
   301    chained_const_irrel_weight = #chained_const_irrel_weight atp_relevance_fudge,
   302    intro_bonus = #intro_bonus atp_relevance_fudge,
   303    elim_bonus = #elim_bonus atp_relevance_fudge,
   304    simp_bonus = #simp_bonus atp_relevance_fudge,
   305    local_bonus = #local_bonus atp_relevance_fudge,
   306    assum_bonus = #assum_bonus atp_relevance_fudge,
   307    chained_bonus = #chained_bonus atp_relevance_fudge,
   308    max_imperfect = #max_imperfect atp_relevance_fudge,
   309    max_imperfect_exp = #max_imperfect_exp atp_relevance_fudge,
   310    threshold_divisor = #threshold_divisor atp_relevance_fudge,
   311    ridiculous_threshold = #ridiculous_threshold atp_relevance_fudge}
   312 
   313 fun relevance_fudge_of_prover ctxt name =
   314   if is_smt_prover ctxt name then smt_relevance_fudge else atp_relevance_fudge
   315 
   316 fun supported_provers ctxt =
   317   let
   318     val thy = Proof_Context.theory_of ctxt
   319     val (remote_provers, local_provers) =
   320       reconstructor_names @
   321       sort_strings (supported_atps thy) @
   322       sort_strings (SMT_Solver.available_solvers_of ctxt)
   323       |> List.partition (String.isPrefix remote_prefix)
   324   in
   325     Output.urgent_message ("Supported provers: " ^
   326                            commas (local_provers @ remote_provers) ^ ".")
   327   end
   328 
   329 fun kill_provers () = Async_Manager.kill_threads SledgehammerN "prover"
   330 fun running_provers () = Async_Manager.running_threads SledgehammerN "prover"
   331 val messages = Async_Manager.thread_messages SledgehammerN "prover"
   332 
   333 
   334 (** problems, results, ATPs, etc. **)
   335 
   336 type params =
   337   {debug : bool,
   338    verbose : bool,
   339    overlord : bool,
   340    blocking : bool,
   341    provers : string list,
   342    type_enc : string option,
   343    strict : bool,
   344    lam_trans : string option,
   345    uncurried_aliases : bool option,
   346    learn : bool,
   347    fact_filter : string option,
   348    max_facts : int option,
   349    fact_thresholds : real * real,
   350    max_mono_iters : int option,
   351    max_new_mono_instances : int option,
   352    isar_proofs : bool option,
   353    isar_compress : real,
   354    isar_compress_degree : int,
   355    merge_timeout_slack : real,
   356    isar_try0 : bool,
   357    isar_minimize : bool,
   358    slice : bool,
   359    minimize : bool option,
   360    timeout : Time.time option,
   361    preplay_timeout : Time.time option,
   362    preplay_trace : bool,
   363    expect : string}
   364 
   365 type relevance_fudge =
   366   {local_const_multiplier : real,
   367    worse_irrel_freq : real,
   368    higher_order_irrel_weight : real,
   369    abs_rel_weight : real,
   370    abs_irrel_weight : real,
   371    skolem_irrel_weight : real,
   372    theory_const_rel_weight : real,
   373    theory_const_irrel_weight : real,
   374    chained_const_irrel_weight : real,
   375    intro_bonus : real,
   376    elim_bonus : real,
   377    simp_bonus : real,
   378    local_bonus : real,
   379    assum_bonus : real,
   380    chained_bonus : real,
   381    max_imperfect : real,
   382    max_imperfect_exp : real,
   383    threshold_divisor : real,
   384    ridiculous_threshold : real}
   385 
   386 type prover_problem =
   387   {state : Proof.state,
   388    goal : thm,
   389    subgoal : int,
   390    subgoal_count : int,
   391    factss : (string * fact list) list}
   392 
   393 type prover_result =
   394   {outcome : failure option,
   395    used_facts : (string * stature) list,
   396    used_from : fact list,
   397    run_time : Time.time,
   398    preplay : play Lazy.lazy,
   399    message : play -> string,
   400    message_tail : string}
   401 
   402 type prover =
   403   params -> ((string * string list) list -> string -> minimize_command)
   404   -> prover_problem -> prover_result
   405 
   406 (* configuration attributes *)
   407 
   408 (* Empty string means create files in Isabelle's temporary files directory. *)
   409 val dest_dir =
   410   Attrib.setup_config_string @{binding sledgehammer_dest_dir} (K "")
   411 val problem_prefix =
   412   Attrib.setup_config_string @{binding sledgehammer_problem_prefix} (K "prob")
   413 val completish =
   414   Attrib.setup_config_bool @{binding sledgehammer_completish} (K false)
   415 
   416 (* In addition to being easier to read, readable names are often much shorter,
   417    especially if types are mangled in names. This makes a difference for some
   418    provers (e.g., E). For these reason, short names are enabled by default. *)
   419 val atp_full_names =
   420   Attrib.setup_config_bool @{binding sledgehammer_atp_full_names} (K false)
   421 
   422 val smt_triggers =
   423   Attrib.setup_config_bool @{binding sledgehammer_smt_triggers} (K true)
   424 val smt_weights =
   425   Attrib.setup_config_bool @{binding sledgehammer_smt_weights} (K true)
   426 val smt_weight_min_facts =
   427   Attrib.setup_config_int @{binding sledgehammer_smt_weight_min_facts} (K 20)
   428 
   429 (* FUDGE *)
   430 val smt_min_weight =
   431   Attrib.setup_config_int @{binding sledgehammer_smt_min_weight} (K 0)
   432 val smt_max_weight =
   433   Attrib.setup_config_int @{binding sledgehammer_smt_max_weight} (K 10)
   434 val smt_max_weight_index =
   435   Attrib.setup_config_int @{binding sledgehammer_smt_max_weight_index} (K 200)
   436 val smt_weight_curve = Unsynchronized.ref (fn x : int => x * x)
   437 
   438 fun smt_fact_weight ctxt j num_facts =
   439   if Config.get ctxt smt_weights andalso
   440      num_facts >= Config.get ctxt smt_weight_min_facts then
   441     let
   442       val min = Config.get ctxt smt_min_weight
   443       val max = Config.get ctxt smt_max_weight
   444       val max_index = Config.get ctxt smt_max_weight_index
   445       val curve = !smt_weight_curve
   446     in
   447       SOME (max - (max - min + 1) * curve (Int.max (0, max_index - j - 1))
   448             div curve max_index)
   449     end
   450   else
   451     NONE
   452 
   453 fun weight_smt_fact ctxt num_facts ((info, th), j) =
   454   let val thy = Proof_Context.theory_of ctxt in
   455     (info, (smt_fact_weight ctxt j num_facts, th |> Thm.transfer thy))
   456   end
   457 
   458 fun overlord_file_location_of_prover prover =
   459   (getenv "ISABELLE_HOME_USER", "prob_" ^ prover)
   460 
   461 fun proof_banner mode name =
   462   case mode of
   463     Auto_Try => "Auto Sledgehammer (" ^ quote name ^ ") found a proof"
   464   | Try => "Sledgehammer (" ^ quote name ^ ") found a proof"
   465   | _ => "Try this"
   466 
   467 fun bunch_of_reconstructors needs_full_types lam_trans =
   468   if needs_full_types then
   469     [Metis (full_type_enc, lam_trans false),
   470      Metis (really_full_type_enc, lam_trans false),
   471      Metis (full_type_enc, lam_trans true),
   472      Metis (really_full_type_enc, lam_trans true),
   473      SMT]
   474   else
   475     [Metis (partial_type_enc, lam_trans false),
   476      Metis (full_type_enc, lam_trans false),
   477      Metis (no_typesN, lam_trans true),
   478      Metis (really_full_type_enc, lam_trans true),
   479      SMT]
   480 
   481 fun extract_reconstructor ({type_enc, lam_trans, ...} : params)
   482                           (Metis (type_enc', lam_trans')) =
   483     let
   484       val override_params =
   485         (if is_none type_enc andalso type_enc' = hd partial_type_encs then
   486            []
   487          else
   488            [("type_enc", [hd (unalias_type_enc type_enc')])]) @
   489         (if is_none lam_trans andalso lam_trans' = metis_default_lam_trans then
   490            []
   491          else
   492            [("lam_trans", [lam_trans'])])
   493     in (metisN, override_params) end
   494   | extract_reconstructor _ SMT = (smtN, [])
   495 
   496 (* based on "Mirabelle.can_apply" and generalized *)
   497 fun timed_apply timeout tac state i =
   498   let
   499     val {context = ctxt, facts, goal} = Proof.goal state
   500     val full_tac = Method.insert_tac facts i THEN tac ctxt i
   501   in time_limit timeout (try (Seq.pull o full_tac)) goal end
   502 
   503 fun tac_of_reconstructor (Metis (type_enc, lam_trans)) =
   504     metis_tac [type_enc] lam_trans
   505   | tac_of_reconstructor SMT = SMT_Solver.smt_tac
   506 
   507 fun timed_reconstructor reconstr debug timeout ths =
   508   (Config.put Metis_Tactic.verbose debug
   509    #> Config.put SMT_Config.verbose debug
   510    #> (fn ctxt => tac_of_reconstructor reconstr ctxt ths))
   511   |> timed_apply timeout
   512 
   513 fun is_fact_chained ((_, (sc, _)), _) = sc = Chained
   514 
   515 fun filter_used_facts keep_chained used =
   516   filter ((member (op =) used o fst) orf
   517           (if keep_chained then is_fact_chained else K false))
   518 
   519 fun play_one_line_proof mode debug verbose timeout pairs state i preferred
   520                         reconstrs =
   521   let
   522     fun get_preferred reconstrs =
   523       if member (op =) reconstrs preferred then preferred
   524       else List.last reconstrs
   525   in
   526     if timeout = SOME Time.zeroTime then
   527       Trust_Playable (get_preferred reconstrs, NONE)
   528     else
   529       let
   530         val _ =
   531           if mode = Minimize then Output.urgent_message "Preplaying proof..."
   532           else ()
   533         val ths = pairs |> sort_wrt (fst o fst) |> map snd
   534         fun play [] [] = Failed_to_Play (get_preferred reconstrs)
   535           | play timed_outs [] =
   536             Trust_Playable (get_preferred timed_outs, timeout)
   537           | play timed_out (reconstr :: reconstrs) =
   538             let
   539               val _ =
   540                 if verbose then
   541                   "Trying \"" ^ string_of_reconstructor reconstr ^ "\"" ^
   542                   (case timeout of
   543                      SOME timeout => " for " ^ string_of_time timeout
   544                    | NONE => "") ^ "..."
   545                   |> Output.urgent_message
   546                 else
   547                   ()
   548               val timer = Timer.startRealTimer ()
   549             in
   550               case timed_reconstructor reconstr debug timeout ths state i of
   551                 SOME (SOME _) => Played (reconstr, Timer.checkRealTimer timer)
   552               | _ => play timed_out reconstrs
   553             end
   554             handle TimeLimit.TimeOut => play (reconstr :: timed_out) reconstrs
   555       in play [] reconstrs end
   556   end
   557 
   558 
   559 (* generic TPTP-based ATPs *)
   560 
   561 (* Too general means, positive equality literal with a variable X as one
   562    operand, when X does not occur properly in the other operand. This rules out
   563    clearly inconsistent facts such as X = a | X = b, though it by no means
   564    guarantees soundness. *)
   565 
   566 fun get_facts_of_filter _ [(_, facts)] = facts
   567   | get_facts_of_filter fact_filter factss =
   568     case AList.lookup (op =) factss fact_filter of
   569       SOME facts => facts
   570     | NONE => snd (hd factss)
   571 
   572 (* Unwanted equalities are those between a (bound or schematic) variable that
   573    does not properly occur in the second operand. *)
   574 val is_exhaustive_finite =
   575   let
   576     fun is_bad_equal (Var z) t =
   577         not (exists_subterm (fn Var z' => z = z' | _ => false) t)
   578       | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
   579       | is_bad_equal _ _ = false
   580     fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
   581     fun do_formula pos t =
   582       case (pos, t) of
   583         (_, @{const Trueprop} $ t1) => do_formula pos t1
   584       | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
   585         do_formula pos t'
   586       | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
   587         do_formula pos t'
   588       | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
   589         do_formula pos t'
   590       | (_, @{const "==>"} $ t1 $ t2) =>
   591         do_formula (not pos) t1 andalso
   592         (t2 = @{prop False} orelse do_formula pos t2)
   593       | (_, @{const HOL.implies} $ t1 $ t2) =>
   594         do_formula (not pos) t1 andalso
   595         (t2 = @{const False} orelse do_formula pos t2)
   596       | (_, @{const Not} $ t1) => do_formula (not pos) t1
   597       | (true, @{const HOL.disj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
   598       | (false, @{const HOL.conj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
   599       | (true, Const (@{const_name HOL.eq}, _) $ t1 $ t2) => do_equals t1 t2
   600       | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
   601       | _ => false
   602   in do_formula true end
   603 
   604 fun has_bound_or_var_of_type pred =
   605   exists_subterm (fn Var (_, T as Type _) => pred T
   606                    | Abs (_, T as Type _, _) => pred T
   607                    | _ => false)
   608 
   609 (* Facts are forbidden to contain variables of these types. The typical reason
   610    is that they lead to unsoundness. Note that "unit" satisfies numerous
   611    equations like "?x = ()". The resulting clauses will have no type constraint,
   612    yielding false proofs. Even "bool" leads to many unsound proofs, though only
   613    for higher-order problems. *)
   614 
   615 (* Facts containing variables of type "unit" or "bool" or of the form
   616    "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
   617    are omitted. *)
   618 fun is_dangerous_prop ctxt =
   619   transform_elim_prop
   620   #> (has_bound_or_var_of_type (is_type_surely_finite ctxt) orf
   621       is_exhaustive_finite)
   622 
   623 (* Important messages are important but not so important that users want to see
   624    them each time. *)
   625 val atp_important_message_keep_quotient = 25
   626 
   627 fun choose_type_enc soundness best_type_enc format =
   628   the_default best_type_enc
   629   #> type_enc_of_string soundness
   630   #> adjust_type_enc format
   631 
   632 fun isar_proof_reconstructor ctxt name =
   633   let val thy = Proof_Context.theory_of ctxt in
   634     if is_atp thy name then name
   635     else remotify_prover_if_not_installed ctxt eN |> the_default name
   636   end
   637 
   638 (* See the analogous logic in the function "maybe_minimize" in
   639   "sledgehammer_minimize.ML". *)
   640 fun choose_minimize_command ctxt (params as {isar_proofs, ...}) minimize_command
   641                             name preplay =
   642   let
   643     val maybe_isar_name =
   644       name |> isar_proofs = SOME true ? isar_proof_reconstructor ctxt
   645     val (min_name, override_params) =
   646       case preplay of
   647         Played (reconstr, _) =>
   648         if isar_proofs = SOME true then (maybe_isar_name, [])
   649         else extract_reconstructor params reconstr
   650       | _ => (maybe_isar_name, [])
   651   in minimize_command override_params min_name end
   652 
   653 fun repair_legacy_monomorph_context max_iters best_max_iters max_new_instances
   654                                     best_max_new_instances =
   655   Config.put Legacy_Monomorph.max_rounds
   656       (max_iters |> the_default best_max_iters)
   657   #> Config.put Legacy_Monomorph.max_new_instances
   658          (max_new_instances |> the_default best_max_new_instances)
   659   #> Config.put Legacy_Monomorph.keep_partial_instances false
   660 
   661 fun repair_monomorph_context max_iters best_max_iters max_new_instances
   662                              best_max_new_instances =
   663   Config.put Monomorph.max_rounds (max_iters |> the_default best_max_iters)
   664   #> Config.put Monomorph.max_new_instances
   665          (max_new_instances |> the_default best_max_new_instances)
   666 
   667 fun suffix_of_mode Auto_Try = "_try"
   668   | suffix_of_mode Try = "_try"
   669   | suffix_of_mode Normal = ""
   670   | suffix_of_mode MaSh = ""
   671   | suffix_of_mode Auto_Minimize = "_min"
   672   | suffix_of_mode Minimize = "_min"
   673 
   674 (* Give the ATPs some slack before interrupting them the hard way. "z3_tptp" on
   675    Linux appears to be the only ATP that does not honor its time limit. *)
   676 val atp_timeout_slack = seconds 1.0
   677 
   678 val mono_max_privileged_facts = 10
   679 
   680 (* For low values of "max_facts", this fudge value ensures that most slices are
   681    invoked with a nontrivial amount of facts. *)
   682 val max_fact_factor_fudge = 5
   683 
   684 fun run_atp mode name
   685         ({exec, arguments, proof_delims, known_failures, prem_role, best_slices,
   686           best_max_mono_iters, best_max_new_mono_instances, ...} : atp_config)
   687         (params as {debug, verbose, overlord, type_enc, strict, lam_trans,
   688                     uncurried_aliases, fact_filter, max_facts, max_mono_iters,
   689                     max_new_mono_instances, isar_proofs, isar_compress,
   690                     isar_compress_degree, merge_timeout_slack,
   691                     isar_try0, isar_minimize,
   692                     slice, timeout, preplay_timeout, preplay_trace, ...})
   693         minimize_command
   694         ({state, goal, subgoal, subgoal_count, factss, ...} : prover_problem) =
   695   let
   696     val thy = Proof.theory_of state
   697     val ctxt = Proof.context_of state
   698     val atp_mode =
   699       if Config.get ctxt completish then Sledgehammer_Completish
   700       else Sledgehammer
   701     val (_, hyp_ts, concl_t) = strip_subgoal goal subgoal ctxt
   702     val (dest_dir, problem_prefix) =
   703       if overlord then overlord_file_location_of_prover name
   704       else (Config.get ctxt dest_dir, Config.get ctxt problem_prefix)
   705     val problem_file_name =
   706       Path.basic (problem_prefix ^ (if overlord then "" else serial_string ()) ^
   707                   suffix_of_mode mode ^ "_" ^ string_of_int subgoal)
   708     val prob_path =
   709       if dest_dir = "" then
   710         File.tmp_path problem_file_name
   711       else if File.exists (Path.explode dest_dir) then
   712         Path.append (Path.explode dest_dir) problem_file_name
   713       else
   714         error ("No such directory: " ^ quote dest_dir ^ ".")
   715     val command0 =
   716       case find_first (fn var => getenv var <> "") (fst exec) of
   717         SOME var =>
   718         let
   719           val pref = getenv var ^ "/"
   720           val paths = map (Path.explode o prefix pref) (snd exec)
   721         in
   722           case find_first File.exists paths of
   723             SOME path => path
   724           | NONE => error ("Bad executable: " ^ Path.print (hd paths) ^ ".")
   725         end
   726       | NONE => error ("The environment variable " ^ quote (hd (fst exec)) ^
   727                        " is not set.")
   728     fun split_time s =
   729       let
   730         val split = String.tokens (fn c => str c = "\n")
   731         val (output, t) =
   732           s |> split |> (try split_last #> the_default ([], "0"))
   733             |>> cat_lines
   734         fun as_num f = f >> (fst o read_int)
   735         val num = as_num (Scan.many1 Symbol.is_ascii_digit)
   736         val digit = Scan.one Symbol.is_ascii_digit
   737         val num3 = as_num (digit ::: digit ::: (digit >> single))
   738         val time = num --| Scan.$$ "." -- num3 >> (fn (a, b) => a * 1000 + b)
   739         val as_time =
   740           raw_explode #> Scan.read Symbol.stopper time #> the_default 0
   741       in (output, as_time t |> Time.fromMilliseconds) end
   742     fun run () =
   743       let
   744         (* If slicing is disabled, we expand the last slice to fill the entire
   745            time available. *)
   746         val actual_slices = get_slices slice (best_slices ctxt)
   747         val num_actual_slices = length actual_slices
   748         val max_fact_factor =
   749           case max_facts of
   750             NONE => 1.0
   751           | SOME max =>
   752             Real.fromInt max
   753             / Real.fromInt (fold (Integer.max o slice_max_facts)
   754                                  actual_slices 0)
   755         fun monomorphize_facts facts =
   756           let
   757             val ctxt =
   758               ctxt
   759               |> repair_legacy_monomorph_context max_mono_iters
   760                      best_max_mono_iters max_new_mono_instances
   761                      best_max_new_mono_instances
   762             (* pseudo-theorem involving the same constants as the subgoal *)
   763             val subgoal_th =
   764               Logic.list_implies (hyp_ts, concl_t) |> Skip_Proof.make_thm thy
   765             val rths =
   766               facts |> chop mono_max_privileged_facts
   767                     |>> map (pair 1 o snd)
   768                     ||> map (pair 2 o snd)
   769                     |> op @
   770                     |> cons (0, subgoal_th)
   771           in
   772             Legacy_Monomorph.monomorph atp_schematic_consts_of rths ctxt |> fst |> tl
   773             |> curry ListPair.zip (map fst facts)
   774             |> maps (fn (name, rths) =>
   775                         map (pair name o zero_var_indexes o snd) rths)
   776           end
   777         fun run_slice time_left (cache_key, cache_value)
   778                 (slice, (time_frac,
   779                      (key as ((best_max_facts, best_fact_filter), format,
   780                               best_type_enc, best_lam_trans,
   781                               best_uncurried_aliases),
   782                       extra))) =
   783           let
   784             val effective_fact_filter =
   785               fact_filter |> the_default best_fact_filter
   786             val facts = get_facts_of_filter effective_fact_filter factss
   787             val num_facts =
   788               Real.ceil (max_fact_factor * Real.fromInt best_max_facts) +
   789               max_fact_factor_fudge
   790               |> Integer.min (length facts)
   791             val soundness = if strict then Strict else Non_Strict
   792             val type_enc =
   793               type_enc |> choose_type_enc soundness best_type_enc format
   794             val sound = is_type_enc_sound type_enc
   795             val real_ms = Real.fromInt o Time.toMilliseconds
   796             val slice_timeout =
   797               case time_left of
   798                 SOME time_left =>
   799                 ((real_ms time_left
   800                   |> (if slice < num_actual_slices - 1 then
   801                         curry Real.min (time_frac * real_ms (the timeout))
   802                       else
   803                         I))
   804                  * 0.001)
   805                 |> seconds |> SOME
   806               | NONE => NONE
   807             val generous_slice_timeout =
   808               if mode = MaSh then NONE
   809               else Option.map (curry Time.+ atp_timeout_slack) slice_timeout
   810             val _ =
   811               if debug then
   812                 quote name ^ " slice #" ^ string_of_int (slice + 1) ^
   813                 " with " ^ string_of_int num_facts ^ " fact" ^
   814                 plural_s num_facts ^
   815                 (case slice_timeout of
   816                    SOME timeout => " for " ^ string_of_time timeout
   817                  | NONE => "") ^ "..."
   818                 |> Output.urgent_message
   819               else
   820                 ()
   821             val readable_names = not (Config.get ctxt atp_full_names)
   822             val lam_trans =
   823               case lam_trans of
   824                 SOME s => s
   825               | NONE => best_lam_trans
   826             val uncurried_aliases =
   827               case uncurried_aliases of
   828                 SOME b => b
   829               | NONE => best_uncurried_aliases
   830             val value as (atp_problem, _, fact_names, _, _) =
   831               if cache_key = SOME key then
   832                 cache_value
   833               else
   834                 facts
   835                 |> not sound
   836                    ? filter_out (is_dangerous_prop ctxt o prop_of o snd)
   837                 |> take num_facts
   838                 |> not (is_type_enc_polymorphic type_enc) ? monomorphize_facts
   839                 |> map (apsnd prop_of)
   840                 |> prepare_atp_problem ctxt format prem_role type_enc atp_mode
   841                                        lam_trans uncurried_aliases
   842                                        readable_names true hyp_ts concl_t
   843             fun sel_weights () = atp_problem_selection_weights atp_problem
   844             fun ord_info () = atp_problem_term_order_info atp_problem
   845             val ord = effective_term_order ctxt name
   846             val full_proof =
   847               debug orelse (isar_proofs |> the_default (mode = Minimize))
   848             val args =
   849               arguments ctxt full_proof extra
   850                         (slice_timeout |> the_default one_day)
   851                         (File.shell_path prob_path) (ord, ord_info, sel_weights)
   852             val command =
   853               "(exec 2>&1; " ^ File.shell_path command0 ^ " " ^ args ^ " " ^ ")"
   854               |> enclose "TIMEFORMAT='%3R'; { time " " ; }"
   855             val _ =
   856               atp_problem
   857               |> lines_of_atp_problem format ord ord_info
   858               |> cons ("% " ^ command ^ "\n")
   859               |> File.write_list prob_path
   860             val ((output, run_time), (atp_proof, outcome)) =
   861               time_limit generous_slice_timeout Isabelle_System.bash_output
   862                          command
   863               |>> (if overlord then
   864                      prefix ("% " ^ command ^ "\n% " ^ timestamp () ^ "\n")
   865                    else
   866                      I)
   867               |> fst |> split_time
   868               |> (fn accum as (output, _) =>
   869                      (accum,
   870                       extract_tstplike_proof_and_outcome verbose proof_delims
   871                                                          known_failures output
   872                       |>> atp_proof_of_tstplike_proof atp_problem
   873                       handle UNRECOGNIZED_ATP_PROOF () =>
   874                              ([], SOME ProofIncomplete)))
   875               handle TimeLimit.TimeOut =>
   876                      (("", the slice_timeout), ([], SOME TimedOut))
   877             val outcome =
   878               case outcome of
   879                 NONE =>
   880                 (case used_facts_in_unsound_atp_proof ctxt fact_names atp_proof
   881                       |> Option.map (sort string_ord) of
   882                    SOME facts =>
   883                    let
   884                      val failure =
   885                        UnsoundProof (is_type_enc_sound type_enc, facts)
   886                    in
   887                      if debug then (warning (string_of_failure failure); NONE)
   888                      else SOME failure
   889                    end
   890                  | NONE => NONE)
   891               | _ => outcome
   892           in
   893             ((SOME key, value), (output, run_time, facts, atp_proof, outcome))
   894           end
   895         val timer = Timer.startRealTimer ()
   896         fun maybe_run_slice slice
   897                 (result as (cache, (_, run_time0, _, _, SOME _))) =
   898             let
   899               val time_left =
   900                 Option.map
   901                     (fn timeout => Time.- (timeout, Timer.checkRealTimer timer))
   902                     timeout
   903             in
   904               if time_left <> NONE andalso
   905                  Time.<= (the time_left, Time.zeroTime) then
   906                 result
   907               else
   908                 run_slice time_left cache slice
   909                 |> (fn (cache, (output, run_time, used_from, atp_proof,
   910                                 outcome)) =>
   911                        (cache, (output, Time.+ (run_time0, run_time), used_from,
   912                                 atp_proof, outcome)))
   913             end
   914           | maybe_run_slice _ result = result
   915       in
   916         ((NONE, ([], Symtab.empty, Vector.fromList [], [], Symtab.empty)),
   917          ("", Time.zeroTime, [], [], SOME InternalError))
   918         |> fold maybe_run_slice actual_slices
   919       end
   920     (* If the problem file has not been exported, remove it; otherwise, export
   921        the proof file too. *)
   922     fun clean_up () =
   923       if dest_dir = "" then (try File.rm prob_path; ()) else ()
   924     fun export (_, (output, _, _, _, _)) =
   925       if dest_dir = "" then ()
   926       else File.write (Path.explode (Path.implode prob_path ^ "_proof")) output
   927     val ((_, (_, pool, fact_names, lifted, sym_tab)),
   928          (output, run_time, used_from, atp_proof, outcome)) =
   929       with_cleanup clean_up run () |> tap export
   930     val important_message =
   931       if mode = Normal andalso
   932          random_range 0 (atp_important_message_keep_quotient - 1) = 0 then
   933         extract_important_message output
   934       else
   935         ""
   936     val (used_facts, preplay, message, message_tail) =
   937       case outcome of
   938         NONE =>
   939         let
   940           val used_facts = used_facts_in_atp_proof ctxt fact_names atp_proof
   941           val needs_full_types = is_typed_helper_used_in_atp_proof atp_proof
   942           val reconstrs =
   943             bunch_of_reconstructors needs_full_types
   944                 (lam_trans_of_atp_proof atp_proof
   945                  o (fn desperate => if desperate then hide_lamsN
   946                                     else metis_default_lam_trans))
   947         in
   948           (used_facts,
   949            Lazy.lazy (fn () =>
   950              let
   951                val used_pairs =
   952                  used_from |> filter_used_facts false used_facts
   953              in
   954                play_one_line_proof mode debug verbose preplay_timeout
   955                    used_pairs state subgoal (hd reconstrs) reconstrs
   956              end),
   957            fn preplay =>
   958               let
   959                 val _ =
   960                   if verbose then
   961                     Output.urgent_message "Generating proof text..."
   962                   else
   963                     ()
   964                 val isar_params =
   965                   (debug, verbose, preplay_timeout, preplay_trace, isar_compress,
   966                    isar_compress_degree, merge_timeout_slack,
   967                    isar_try0,isar_minimize,
   968                    pool, fact_names, lifted, sym_tab, atp_proof, goal)
   969                 val one_line_params =
   970                   (preplay, proof_banner mode name, used_facts,
   971                    choose_minimize_command ctxt params minimize_command name
   972                                            preplay,
   973                    subgoal, subgoal_count)
   974                 val num_chained = length (#facts (Proof.goal state))
   975               in
   976                 proof_text ctxt (mode = Auto_Try) isar_proofs isar_params num_chained
   977                            one_line_params
   978               end,
   979            (if verbose then
   980               "\nATP real CPU time: " ^ string_of_time run_time ^ "."
   981             else
   982               "") ^
   983            (if important_message <> "" then
   984               "\n\nImportant message from Dr. Geoff Sutcliffe:\n" ^
   985               important_message
   986             else
   987               ""))
   988         end
   989       | SOME failure =>
   990         ([], Lazy.value (Failed_to_Play plain_metis),
   991          fn _ => string_of_failure failure, "")
   992   in
   993     {outcome = outcome, used_facts = used_facts, used_from = used_from,
   994      run_time = run_time, preplay = preplay, message = message,
   995      message_tail = message_tail}
   996   end
   997 
   998 fun rotate_one (x :: xs) = xs @ [x]
   999 
  1000 (* "SMT_Failure.Abnormal_Termination" carries the solver's return code. Until
  1001    these are sorted out properly in the SMT module, we have to interpret these
  1002    ourselves. *)
  1003 val remote_smt_failures =
  1004   [(2, NoLibwwwPerl),
  1005    (22, CantConnect)]
  1006 val z3_failures =
  1007   [(101, OutOfResources),
  1008    (103, MalformedInput),
  1009    (110, MalformedInput),
  1010    (112, TimedOut)]
  1011 val unix_failures =
  1012   [(138, Crashed),
  1013    (139, Crashed)]
  1014 val smt_failures = remote_smt_failures @ z3_failures @ unix_failures
  1015 
  1016 fun failure_of_smt_failure (SMT_Failure.Counterexample {is_real_cex, ...}) =
  1017     if is_real_cex then Unprovable else GaveUp
  1018   | failure_of_smt_failure SMT_Failure.Time_Out = TimedOut
  1019   | failure_of_smt_failure (SMT_Failure.Abnormal_Termination code) =
  1020     (case AList.lookup (op =) smt_failures code of
  1021        SOME failure => failure
  1022      | NONE => UnknownError ("Abnormal termination with exit code " ^
  1023                              string_of_int code ^ "."))
  1024   | failure_of_smt_failure SMT_Failure.Out_Of_Memory = OutOfResources
  1025   | failure_of_smt_failure (SMT_Failure.Other_Failure s) = UnknownError s
  1026 
  1027 (* FUDGE *)
  1028 val smt_max_slices =
  1029   Attrib.setup_config_int @{binding sledgehammer_smt_max_slices} (K 8)
  1030 val smt_slice_fact_frac =
  1031   Attrib.setup_config_real @{binding sledgehammer_smt_slice_fact_frac}
  1032                            (K 0.667)
  1033 val smt_slice_time_frac =
  1034   Attrib.setup_config_real @{binding sledgehammer_smt_slice_time_frac} (K 0.333)
  1035 val smt_slice_min_secs =
  1036   Attrib.setup_config_int @{binding sledgehammer_smt_slice_min_secs} (K 3)
  1037 
  1038 fun smt_filter_loop name
  1039                     ({debug, verbose, overlord, max_mono_iters,
  1040                       max_new_mono_instances, timeout, slice, ...} : params)
  1041                     state goal i =
  1042   let
  1043     fun repair_context ctxt =
  1044       ctxt |> select_smt_solver name
  1045            |> Config.put SMT_Config.verbose debug
  1046            |> (if overlord then
  1047                  Config.put SMT_Config.debug_files
  1048                             (overlord_file_location_of_prover name
  1049                              |> (fn (path, name) => path ^ "/" ^ name))
  1050                else
  1051                  I)
  1052            |> Config.put SMT_Config.infer_triggers
  1053                          (Config.get ctxt smt_triggers)
  1054            |> repair_monomorph_context max_mono_iters default_max_mono_iters
  1055                   max_new_mono_instances default_max_new_mono_instances
  1056     val state = Proof.map_context (repair_context) state
  1057     val ctxt = Proof.context_of state
  1058     val max_slices = if slice then Config.get ctxt smt_max_slices else 1
  1059     fun do_slice timeout slice outcome0 time_so_far
  1060                  (weighted_factss as (fact_filter, weighted_facts) :: _) =
  1061       let
  1062         val timer = Timer.startRealTimer ()
  1063         val slice_timeout =
  1064           if slice < max_slices andalso timeout <> NONE then
  1065             let val ms = timeout |> the |> Time.toMilliseconds in
  1066               Int.min (ms,
  1067                   Int.max (1000 * Config.get ctxt smt_slice_min_secs,
  1068                       Real.ceil (Config.get ctxt smt_slice_time_frac
  1069                                  * Real.fromInt ms)))
  1070               |> Time.fromMilliseconds |> SOME
  1071             end
  1072           else
  1073             timeout
  1074         val num_facts = length weighted_facts
  1075         val _ =
  1076           if debug then
  1077             quote name ^ " slice " ^ string_of_int slice ^ " with " ^
  1078             string_of_int num_facts ^ " fact" ^ plural_s num_facts ^
  1079             (case slice_timeout of
  1080                SOME timeout => " for " ^ string_of_time timeout
  1081              | NONE => "") ^ "..."
  1082             |> Output.urgent_message
  1083           else
  1084             ()
  1085         val birth = Timer.checkRealTimer timer
  1086         val _ =
  1087           if debug then Output.urgent_message "Invoking SMT solver..." else ()
  1088         val (outcome, used_facts) =
  1089           SMT_Solver.smt_filter_preprocess ctxt [] goal weighted_facts i
  1090           |> SMT_Solver.smt_filter_apply (slice_timeout |> the_default one_day)
  1091           |> (fn {outcome, used_facts} => (outcome, used_facts))
  1092           handle exn => if Exn.is_interrupt exn then
  1093                           reraise exn
  1094                         else
  1095                           (ML_Compiler.exn_message exn
  1096                            |> SMT_Failure.Other_Failure |> SOME, [])
  1097         val death = Timer.checkRealTimer timer
  1098         val outcome0 = if is_none outcome0 then SOME outcome else outcome0
  1099         val time_so_far = Time.+ (time_so_far, Time.- (death, birth))
  1100         val too_many_facts_perhaps =
  1101           case outcome of
  1102             NONE => false
  1103           | SOME (SMT_Failure.Counterexample _) => false
  1104           | SOME SMT_Failure.Time_Out => slice_timeout <> timeout
  1105           | SOME (SMT_Failure.Abnormal_Termination _) => true (* kind of *)
  1106           | SOME SMT_Failure.Out_Of_Memory => true
  1107           | SOME (SMT_Failure.Other_Failure _) => true
  1108         val timeout =
  1109           Option.map
  1110               (fn timeout => Time.- (timeout, Timer.checkRealTimer timer))
  1111               timeout
  1112       in
  1113         if too_many_facts_perhaps andalso slice < max_slices andalso
  1114            num_facts > 0 andalso
  1115            (timeout = NONE orelse Time.> (the timeout, Time.zeroTime)) then
  1116           let
  1117             val new_num_facts =
  1118               Real.ceil (Config.get ctxt smt_slice_fact_frac
  1119                          * Real.fromInt num_facts)
  1120             val weighted_factss as (new_fact_filter, _) :: _ =
  1121               weighted_factss
  1122               |> rotate_one
  1123               |> app_hd (apsnd (take new_num_facts))
  1124             val show_filter = fact_filter <> new_fact_filter
  1125             fun num_of_facts fact_filter num_facts =
  1126               string_of_int num_facts ^
  1127               (if show_filter then " " ^ quote fact_filter else "") ^
  1128               " fact" ^ plural_s num_facts
  1129             val _ =
  1130               if verbose andalso is_some outcome then
  1131                 quote name ^ " invoked with " ^
  1132                 num_of_facts fact_filter num_facts ^ ": " ^
  1133                 string_of_failure (failure_of_smt_failure (the outcome)) ^
  1134                 " Retrying with " ^ num_of_facts new_fact_filter new_num_facts ^
  1135                 "..."
  1136                 |> Output.urgent_message
  1137               else
  1138                 ()
  1139           in
  1140             do_slice timeout (slice + 1) outcome0 time_so_far weighted_factss
  1141           end
  1142         else
  1143           {outcome = if is_none outcome then NONE else the outcome0,
  1144            used_facts = used_facts, used_from = map (apsnd snd) weighted_facts,
  1145            run_time = time_so_far}
  1146       end
  1147   in do_slice timeout 1 NONE Time.zeroTime end
  1148 
  1149 fun run_smt_solver mode name (params as {debug, verbose, preplay_timeout, ...})
  1150         minimize_command
  1151         ({state, goal, subgoal, subgoal_count, factss, ...} : prover_problem) =
  1152   let
  1153     val ctxt = Proof.context_of state
  1154     fun weight_facts facts =
  1155       let val num_facts = length facts in
  1156         facts ~~ (0 upto num_facts - 1)
  1157         |> map (weight_smt_fact ctxt num_facts)
  1158       end
  1159     val weighted_factss = factss |> map (apsnd weight_facts)
  1160     val {outcome, used_facts = used_pairs, used_from, run_time} =
  1161       smt_filter_loop name params state goal subgoal weighted_factss
  1162     val used_facts = used_pairs |> map fst
  1163     val outcome = outcome |> Option.map failure_of_smt_failure
  1164     val (preplay, message, message_tail) =
  1165       case outcome of
  1166         NONE =>
  1167         (Lazy.lazy (fn () =>
  1168            play_one_line_proof mode debug verbose preplay_timeout used_pairs
  1169                state subgoal SMT
  1170                (bunch_of_reconstructors false (fn desperate =>
  1171                   if desperate then liftingN else metis_default_lam_trans))),
  1172          fn preplay =>
  1173             let
  1174               val one_line_params =
  1175                 (preplay, proof_banner mode name, used_facts,
  1176                  choose_minimize_command ctxt params minimize_command name
  1177                                          preplay,
  1178                  subgoal, subgoal_count)
  1179               val num_chained = length (#facts (Proof.goal state))
  1180             in one_line_proof_text (mode = Auto_Try) num_chained one_line_params end,
  1181          if verbose then
  1182            "\nSMT solver real CPU time: " ^ string_of_time run_time ^ "."
  1183          else
  1184            "")
  1185       | SOME failure =>
  1186         (Lazy.value (Failed_to_Play plain_metis),
  1187          fn _ => string_of_failure failure, "")
  1188   in
  1189     {outcome = outcome, used_facts = used_facts, used_from = used_from,
  1190      run_time = run_time, preplay = preplay, message = message,
  1191      message_tail = message_tail}
  1192   end
  1193 
  1194 fun run_reconstructor mode name
  1195         (params as {debug, verbose, timeout, type_enc, lam_trans, ...})
  1196         minimize_command
  1197         ({state, subgoal, subgoal_count, factss = (_, facts) :: _, ...}
  1198          : prover_problem) =
  1199   let
  1200     val reconstr =
  1201       if name = metisN then
  1202         Metis (type_enc |> the_default (hd partial_type_encs),
  1203                lam_trans |> the_default metis_default_lam_trans)
  1204       else if name = smtN then
  1205         SMT
  1206       else
  1207         raise Fail ("unknown reconstructor: " ^ quote name)
  1208     val used_facts = facts |> map fst
  1209   in
  1210     case play_one_line_proof (if mode = Minimize then Normal else mode) debug
  1211                              verbose timeout facts state subgoal reconstr
  1212                              [reconstr] of
  1213       play as Played (_, time) =>
  1214       {outcome = NONE, used_facts = used_facts, used_from = facts,
  1215        run_time = time, preplay = Lazy.value play,
  1216        message =
  1217          fn play =>
  1218             let
  1219               val (_, override_params) = extract_reconstructor params reconstr
  1220               val one_line_params =
  1221                 (play, proof_banner mode name, used_facts,
  1222                  minimize_command override_params name, subgoal,
  1223                  subgoal_count)
  1224               val num_chained = length (#facts (Proof.goal state))
  1225             in one_line_proof_text (mode = Auto_Try) num_chained one_line_params end,
  1226        message_tail = ""}
  1227     | play =>
  1228       let
  1229         val failure = case play of Failed_to_Play _ => GaveUp | _ => TimedOut
  1230       in
  1231         {outcome = SOME failure, used_facts = [], used_from = [],
  1232          run_time = Time.zeroTime, preplay = Lazy.value play,
  1233          message = fn _ => string_of_failure failure, message_tail = ""}
  1234       end
  1235   end
  1236 
  1237 fun get_prover ctxt mode name =
  1238   let val thy = Proof_Context.theory_of ctxt in
  1239     if is_reconstructor name then run_reconstructor mode name
  1240     else if is_atp thy name then run_atp mode name (get_atp thy name ())
  1241     else if is_smt_prover ctxt name then run_smt_solver mode name
  1242     else error ("No such prover: " ^ name ^ ".")
  1243   end
  1244 
  1245 end;