src/HOL/Tools/Sledgehammer/sledgehammer_provers.ML
author blanchet
Wed Dec 08 22:17:52 2010 +0100 (2010-12-08 ago)
changeset 41089 2e69fb6331cb
parent 41088 54eb8e7c7f9b
child 41090 b98fe4de1ecd
permissions -rw-r--r--
moved function to later module
blanchet@41087
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_provers.ML
wenzelm@28477
     2
    Author:     Fabian Immler, TU Muenchen
wenzelm@32996
     3
    Author:     Makarius
blanchet@35969
     4
    Author:     Jasmin Blanchette, TU Muenchen
wenzelm@28477
     5
blanchet@41087
     6
Generic prover abstraction for Sledgehammer.
wenzelm@28477
     7
*)
wenzelm@28477
     8
blanchet@41087
     9
signature SLEDGEHAMMER_PROVERS =
wenzelm@28477
    10
sig
blanchet@40181
    11
  type failure = ATP_Proof.failure
blanchet@38988
    12
  type locality = Sledgehammer_Filter.locality
blanchet@40070
    13
  type relevance_fudge = Sledgehammer_Filter.relevance_fudge
blanchet@40114
    14
  type translated_formula = Sledgehammer_ATP_Translate.translated_formula
blanchet@40068
    15
  type minimize_command = Sledgehammer_ATP_Reconstruct.minimize_command
blanchet@39493
    16
blanchet@35969
    17
  type params =
blanchet@38982
    18
    {blocking: bool,
blanchet@38982
    19
     debug: bool,
blanchet@35969
    20
     verbose: bool,
blanchet@36143
    21
     overlord: bool,
blanchet@40059
    22
     provers: string list,
blanchet@35969
    23
     full_types: bool,
blanchet@36235
    24
     explicit_apply: bool,
blanchet@38745
    25
     relevance_thresholds: real * real,
blanchet@38744
    26
     max_relevant: int option,
blanchet@35969
    27
     isar_proof: bool,
blanchet@36924
    28
     isar_shrink_factor: int,
blanchet@38985
    29
     timeout: Time.time,
blanchet@38985
    30
     expect: string}
blanchet@39493
    31
blanchet@40204
    32
  datatype fact =
blanchet@40114
    33
    Untranslated of (string * locality) * thm |
blanchet@41088
    34
    ATP_Translated of term * ((string * locality) * translated_formula) option
blanchet@40061
    35
blanchet@40061
    36
  type prover_problem =
blanchet@39318
    37
    {state: Proof.state,
blanchet@38998
    38
     goal: thm,
blanchet@38998
    39
     subgoal: int,
blanchet@40065
    40
     subgoal_count: int,
blanchet@40983
    41
     facts: fact list}
blanchet@39493
    42
blanchet@40061
    43
  type prover_result =
blanchet@36370
    44
    {outcome: failure option,
blanchet@40204
    45
     used_facts: (string * locality) list,
blanchet@40062
    46
     run_time_in_msecs: int option,
blanchet@40062
    47
     message: string}
blanchet@39493
    48
blanchet@40061
    49
  type prover = params -> minimize_command -> prover_problem -> prover_result
blanchet@35867
    50
blanchet@41089
    51
  val das_Tool : string
blanchet@41087
    52
  val is_smt_prover : Proof.context -> string -> bool
blanchet@40941
    53
  val is_prover_available : Proof.context -> string -> bool
blanchet@40072
    54
  val is_prover_installed : Proof.context -> string -> bool
blanchet@40941
    55
  val default_max_relevant_for_prover : Proof.context -> string -> int
blanchet@40369
    56
  val is_built_in_const_for_prover :
blanchet@41066
    57
    Proof.context -> string -> string * typ -> term list -> bool
blanchet@41087
    58
  val atp_relevance_fudge : relevance_fudge
blanchet@41087
    59
  val smt_relevance_fudge : relevance_fudge
blanchet@40941
    60
  val relevance_fudge_for_prover : Proof.context -> string -> relevance_fudge
blanchet@38023
    61
  val dest_dir : string Config.T
blanchet@38023
    62
  val problem_prefix : string Config.T
blanchet@39003
    63
  val measure_run_time : bool Config.T
blanchet@40941
    64
  val available_provers : Proof.context -> unit
blanchet@40059
    65
  val kill_provers : unit -> unit
blanchet@40059
    66
  val running_provers : unit -> unit
blanchet@40059
    67
  val messages : int option -> unit
blanchet@40941
    68
  val get_prover : Proof.context -> bool -> string -> prover
blanchet@38023
    69
  val setup : theory -> theory
wenzelm@28477
    70
end;
wenzelm@28477
    71
blanchet@41087
    72
structure Sledgehammer_Provers : SLEDGEHAMMER_PROVERS =
wenzelm@28477
    73
struct
wenzelm@28477
    74
blanchet@38028
    75
open ATP_Problem
blanchet@39491
    76
open ATP_Proof
blanchet@38028
    77
open ATP_Systems
blanchet@39494
    78
open Metis_Translate
blanchet@38023
    79
open Sledgehammer_Util
blanchet@38988
    80
open Sledgehammer_Filter
blanchet@40068
    81
open Sledgehammer_ATP_Translate
blanchet@40068
    82
open Sledgehammer_ATP_Reconstruct
blanchet@37583
    83
blanchet@37583
    84
(** The Sledgehammer **)
blanchet@37583
    85
blanchet@38102
    86
(* Identifier to distinguish Sledgehammer from other tools using
blanchet@38102
    87
   "Async_Manager". *)
blanchet@37585
    88
val das_Tool = "Sledgehammer"
blanchet@37585
    89
blanchet@40941
    90
fun is_smt_prover ctxt name =
blanchet@40941
    91
  let val smts = SMT_Solver.available_solvers_of ctxt in
blanchet@40941
    92
    case try (unprefix remote_prefix) name of
blanchet@40941
    93
      SOME suffix => member (op =) smts suffix andalso
blanchet@40941
    94
                     SMT_Solver.is_remotely_available ctxt suffix
blanchet@40941
    95
    | NONE => member (op =) smts name
blanchet@40941
    96
  end
blanchet@40062
    97
blanchet@40941
    98
fun is_prover_available ctxt name =
blanchet@40941
    99
  let val thy = ProofContext.theory_of ctxt in
blanchet@40941
   100
    is_smt_prover ctxt name orelse member (op =) (available_atps thy) name
blanchet@40941
   101
  end
blanchet@40072
   102
blanchet@40072
   103
fun is_prover_installed ctxt name =
blanchet@40072
   104
  let val thy = ProofContext.theory_of ctxt in
blanchet@40941
   105
    if is_smt_prover ctxt name then
blanchet@40941
   106
      String.isPrefix remote_prefix name orelse
blanchet@40941
   107
      SMT_Solver.is_locally_installed ctxt name
blanchet@40941
   108
    else
blanchet@40941
   109
      is_atp_installed thy name
blanchet@40941
   110
  end
blanchet@40941
   111
blanchet@40941
   112
fun available_smt_solvers ctxt =
blanchet@40941
   113
  let val smts = SMT_Solver.available_solvers_of ctxt in
blanchet@40941
   114
    smts @ map (prefix remote_prefix)
blanchet@40941
   115
               (filter (SMT_Solver.is_remotely_available ctxt) smts)
blanchet@40072
   116
  end
blanchet@40072
   117
blanchet@40941
   118
fun default_max_relevant_for_prover ctxt name =
blanchet@40941
   119
  let val thy = ProofContext.theory_of ctxt in
blanchet@40982
   120
    if is_smt_prover ctxt name then
blanchet@40982
   121
      SMT_Solver.default_max_relevant ctxt
blanchet@40982
   122
          (perhaps (try (unprefix remote_prefix)) name)
blanchet@40982
   123
    else
blanchet@40982
   124
      #default_max_relevant (get_atp thy name)
blanchet@40941
   125
  end
blanchet@40063
   126
blanchet@40071
   127
(* These are typically simplified away by "Meson.presimplify". Equality is
blanchet@40071
   128
   handled specially via "fequal". *)
blanchet@40071
   129
val atp_irrelevant_consts =
blanchet@40071
   130
  [@{const_name False}, @{const_name True}, @{const_name If}, @{const_name Let},
blanchet@40071
   131
   @{const_name HOL.eq}]
blanchet@40206
   132
blanchet@41066
   133
fun is_built_in_const_for_prover ctxt name (s, T) args =
blanchet@41066
   134
  if is_smt_prover ctxt name then SMT_Builtin.is_builtin_ext ctxt (s, T) args
blanchet@40369
   135
  else member (op =) atp_irrelevant_consts s
blanchet@40071
   136
blanchet@40070
   137
(* FUDGE *)
blanchet@40070
   138
val atp_relevance_fudge =
blanchet@40070
   139
  {worse_irrel_freq = 100.0,
blanchet@40070
   140
   higher_order_irrel_weight = 1.05,
blanchet@40070
   141
   abs_rel_weight = 0.5,
blanchet@40070
   142
   abs_irrel_weight = 2.0,
blanchet@40070
   143
   skolem_irrel_weight = 0.75,
blanchet@40070
   144
   theory_const_rel_weight = 0.5,
blanchet@40070
   145
   theory_const_irrel_weight = 0.25,
blanchet@40070
   146
   intro_bonus = 0.15,
blanchet@40070
   147
   elim_bonus = 0.15,
blanchet@40070
   148
   simp_bonus = 0.15,
blanchet@40070
   149
   local_bonus = 0.55,
blanchet@40070
   150
   assum_bonus = 1.05,
blanchet@40070
   151
   chained_bonus = 1.5,
blanchet@40070
   152
   max_imperfect = 11.5,
blanchet@40070
   153
   max_imperfect_exp = 1.0,
blanchet@40070
   154
   threshold_divisor = 2.0,
blanchet@40070
   155
   ridiculous_threshold = 0.1}
blanchet@40070
   156
blanchet@40071
   157
(* FUDGE (FIXME) *)
blanchet@40070
   158
val smt_relevance_fudge =
blanchet@40071
   159
  {worse_irrel_freq = #worse_irrel_freq atp_relevance_fudge,
blanchet@40071
   160
   higher_order_irrel_weight = #higher_order_irrel_weight atp_relevance_fudge,
blanchet@40071
   161
   abs_rel_weight = #abs_rel_weight atp_relevance_fudge,
blanchet@40071
   162
   abs_irrel_weight = #abs_irrel_weight atp_relevance_fudge,
blanchet@40071
   163
   skolem_irrel_weight = #skolem_irrel_weight atp_relevance_fudge,
blanchet@40071
   164
   theory_const_rel_weight = #theory_const_rel_weight atp_relevance_fudge,
blanchet@40071
   165
   theory_const_irrel_weight = #theory_const_irrel_weight atp_relevance_fudge,
blanchet@40071
   166
   intro_bonus = #intro_bonus atp_relevance_fudge,
blanchet@40071
   167
   elim_bonus = #elim_bonus atp_relevance_fudge,
blanchet@40071
   168
   simp_bonus = #simp_bonus atp_relevance_fudge,
blanchet@40071
   169
   local_bonus = #local_bonus atp_relevance_fudge,
blanchet@40071
   170
   assum_bonus = #assum_bonus atp_relevance_fudge,
blanchet@40071
   171
   chained_bonus = #chained_bonus atp_relevance_fudge,
blanchet@40071
   172
   max_imperfect = #max_imperfect atp_relevance_fudge,
blanchet@40071
   173
   max_imperfect_exp = #max_imperfect_exp atp_relevance_fudge,
blanchet@40071
   174
   threshold_divisor = #threshold_divisor atp_relevance_fudge,
blanchet@40071
   175
   ridiculous_threshold = #ridiculous_threshold atp_relevance_fudge}
blanchet@40070
   176
blanchet@40941
   177
fun relevance_fudge_for_prover ctxt name =
blanchet@40941
   178
  if is_smt_prover ctxt name then smt_relevance_fudge else atp_relevance_fudge
blanchet@40070
   179
blanchet@40941
   180
fun available_provers ctxt =
blanchet@40060
   181
  let
blanchet@40941
   182
    val thy = ProofContext.theory_of ctxt
blanchet@40060
   183
    val (remote_provers, local_provers) =
blanchet@40941
   184
      sort_strings (available_atps thy) @
blanchet@40941
   185
      sort_strings (available_smt_solvers ctxt)
blanchet@40060
   186
      |> List.partition (String.isPrefix remote_prefix)
blanchet@40060
   187
  in
blanchet@40205
   188
    Output.urgent_message ("Available provers: " ^
blanchet@40205
   189
                           commas (local_provers @ remote_provers) ^ ".")
blanchet@40060
   190
  end
blanchet@35969
   191
blanchet@40059
   192
fun kill_provers () = Async_Manager.kill_threads das_Tool "provers"
blanchet@40059
   193
fun running_provers () = Async_Manager.running_threads das_Tool "provers"
blanchet@40059
   194
val messages = Async_Manager.thread_messages das_Tool "prover"
blanchet@40059
   195
blanchet@40059
   196
(** problems, results, ATPs, etc. **)
blanchet@35969
   197
blanchet@35969
   198
type params =
blanchet@38982
   199
  {blocking: bool,
blanchet@38982
   200
   debug: bool,
blanchet@35969
   201
   verbose: bool,
blanchet@36143
   202
   overlord: bool,
blanchet@40059
   203
   provers: string list,
blanchet@35969
   204
   full_types: bool,
blanchet@36235
   205
   explicit_apply: bool,
blanchet@38745
   206
   relevance_thresholds: real * real,
blanchet@38744
   207
   max_relevant: int option,
blanchet@35969
   208
   isar_proof: bool,
blanchet@36924
   209
   isar_shrink_factor: int,
blanchet@38985
   210
   timeout: Time.time,
blanchet@38985
   211
   expect: string}
blanchet@35867
   212
blanchet@40204
   213
datatype fact =
blanchet@40114
   214
  Untranslated of (string * locality) * thm |
blanchet@41088
   215
  ATP_Translated of term * ((string * locality) * translated_formula) option
blanchet@40061
   216
blanchet@40061
   217
type prover_problem =
blanchet@39318
   218
  {state: Proof.state,
blanchet@38998
   219
   goal: thm,
blanchet@38998
   220
   subgoal: int,
blanchet@40065
   221
   subgoal_count: int,
blanchet@40983
   222
   facts: fact list}
blanchet@35867
   223
blanchet@40061
   224
type prover_result =
blanchet@36370
   225
  {outcome: failure option,
blanchet@35969
   226
   message: string,
blanchet@40204
   227
   used_facts: (string * locality) list,
blanchet@40062
   228
   run_time_in_msecs: int option}
blanchet@35867
   229
blanchet@40061
   230
type prover = params -> minimize_command -> prover_problem -> prover_result
blanchet@35867
   231
blanchet@38023
   232
(* configuration attributes *)
blanchet@38023
   233
blanchet@38991
   234
val (dest_dir, dest_dir_setup) =
blanchet@39003
   235
  Attrib.config_string "sledgehammer_dest_dir" (K "")
blanchet@38991
   236
  (* Empty string means create files in Isabelle's temporary files directory. *)
blanchet@38023
   237
blanchet@38023
   238
val (problem_prefix, problem_prefix_setup) =
blanchet@39003
   239
  Attrib.config_string "sledgehammer_problem_prefix" (K "prob")
blanchet@38023
   240
blanchet@39003
   241
val (measure_run_time, measure_run_time_setup) =
blanchet@39003
   242
  Attrib.config_bool "sledgehammer_measure_run_time" (K false)
wenzelm@28484
   243
blanchet@38023
   244
fun with_path cleanup after f path =
blanchet@38023
   245
  Exn.capture f path
blanchet@38023
   246
  |> tap (fn _ => cleanup path)
blanchet@38023
   247
  |> Exn.release
blanchet@38023
   248
  |> tap (after path)
blanchet@38023
   249
blanchet@40060
   250
fun proof_banner auto =
blanchet@40224
   251
  if auto then "Auto Sledgehammer found a proof" else "Try this command"
blanchet@40060
   252
blanchet@40059
   253
(* generic TPTP-based ATPs *)
blanchet@38023
   254
blanchet@40114
   255
fun dest_Untranslated (Untranslated p) = p
blanchet@41088
   256
  | dest_Untranslated (ATP_Translated _) = raise Fail "dest_Untranslated"
blanchet@41088
   257
fun atp_translated_fact ctxt (Untranslated p) = translate_atp_fact ctxt p
blanchet@41088
   258
  | atp_translated_fact _ (ATP_Translated p) = p
blanchet@40061
   259
blanchet@40409
   260
fun int_opt_add (SOME m) (SOME n) = SOME (m + n)
blanchet@40409
   261
  | int_opt_add _ _ = NONE
blanchet@40062
   262
blanchet@39492
   263
(* Important messages are important but not so important that users want to see
blanchet@39492
   264
   them each time. *)
blanchet@39493
   265
val important_message_keep_factor = 0.1
blanchet@39492
   266
blanchet@40063
   267
fun run_atp auto atp_name
blanchet@38645
   268
        {exec, required_execs, arguments, has_incomplete_mode, proof_delims,
blanchet@40983
   269
         known_failures, explicit_forall, use_conjecture_for_hypotheses, ...}
blanchet@40983
   270
        ({debug, verbose, overlord, full_types, explicit_apply, isar_proof,
blanchet@40983
   271
          isar_shrink_factor, timeout, ...} : params)
blanchet@40983
   272
        minimize_command ({state, goal, subgoal, facts, ...} : prover_problem) =
blanchet@38023
   273
  let
blanchet@39318
   274
    val ctxt = Proof.context_of state
blanchet@38998
   275
    val (_, hyp_ts, concl_t) = strip_subgoal goal subgoal
blanchet@40204
   276
    val facts =
blanchet@41088
   277
      facts |> map (atp_translated_fact ctxt)
blanchet@40059
   278
    val dest_dir = if overlord then getenv "ISABELLE_HOME_USER"
blanchet@40059
   279
                   else Config.get ctxt dest_dir
blanchet@40059
   280
    val problem_prefix = Config.get ctxt problem_prefix
blanchet@40061
   281
    val problem_file_name =
blanchet@39003
   282
      Path.basic ((if overlord then "prob_" ^ atp_name
blanchet@40059
   283
                   else problem_prefix ^ serial_string ())
blanchet@39003
   284
                  ^ "_" ^ string_of_int subgoal)
blanchet@40061
   285
    val problem_path_name =
blanchet@40059
   286
      if dest_dir = "" then
blanchet@40061
   287
        File.tmp_path problem_file_name
blanchet@40059
   288
      else if File.exists (Path.explode dest_dir) then
blanchet@40061
   289
        Path.append (Path.explode dest_dir) problem_file_name
blanchet@39003
   290
      else
blanchet@40059
   291
        error ("No such directory: " ^ quote dest_dir ^ ".")
blanchet@39003
   292
    val measure_run_time = verbose orelse Config.get ctxt measure_run_time
blanchet@38092
   293
    val command = Path.explode (getenv (fst exec) ^ "/" ^ snd exec)
blanchet@40059
   294
    (* write out problem file and call ATP *)
blanchet@38645
   295
    fun command_line complete timeout probfile =
blanchet@38023
   296
      let
blanchet@38023
   297
        val core = File.shell_path command ^ " " ^ arguments complete timeout ^
blanchet@38023
   298
                   " " ^ File.shell_path probfile
blanchet@38023
   299
      in
blanchet@39010
   300
        (if measure_run_time then "TIMEFORMAT='%3R'; { time " ^ core ^ " ; }"
blanchet@38744
   301
         else "exec " ^ core) ^ " 2>&1"
blanchet@38023
   302
      end
blanchet@38023
   303
    fun split_time s =
blanchet@38023
   304
      let
blanchet@38023
   305
        val split = String.tokens (fn c => str c = "\n");
blanchet@38023
   306
        val (output, t) = s |> split |> split_last |> apfst cat_lines;
blanchet@38023
   307
        fun as_num f = f >> (fst o read_int);
blanchet@38023
   308
        val num = as_num (Scan.many1 Symbol.is_ascii_digit);
blanchet@38023
   309
        val digit = Scan.one Symbol.is_ascii_digit;
blanchet@38023
   310
        val num3 = as_num (digit ::: digit ::: (digit >> single));
blanchet@38023
   311
        val time = num --| Scan.$$ "." -- num3 >> (fn (a, b) => a * 1000 + b);
wenzelm@40627
   312
        val as_time = Scan.read Symbol.stopper time o raw_explode
blanchet@38023
   313
      in (output, as_time t) end;
blanchet@38023
   314
    fun run_on probfile =
blanchet@38092
   315
      case filter (curry (op =) "" o getenv o fst) (exec :: required_execs) of
blanchet@38032
   316
        (home_var, _) :: _ =>
blanchet@38023
   317
        error ("The environment variable " ^ quote home_var ^ " is not set.")
blanchet@38032
   318
      | [] =>
blanchet@38032
   319
        if File.exists command then
blanchet@38032
   320
          let
blanchet@39318
   321
            fun run complete timeout =
blanchet@38032
   322
              let
blanchet@38645
   323
                val command = command_line complete timeout probfile
blanchet@38032
   324
                val ((output, msecs), res_code) =
blanchet@38032
   325
                  bash_output command
blanchet@38032
   326
                  |>> (if overlord then
blanchet@38032
   327
                         prefix ("% " ^ command ^ "\n% " ^ timestamp () ^ "\n")
blanchet@38032
   328
                       else
blanchet@38032
   329
                         I)
blanchet@40062
   330
                  |>> (if measure_run_time then split_time else rpair NONE)
blanchet@39452
   331
                val (tstplike_proof, outcome) =
blanchet@39452
   332
                  extract_tstplike_proof_and_outcome complete res_code
blanchet@39452
   333
                      proof_delims known_failures output
blanchet@39452
   334
              in (output, msecs, tstplike_proof, outcome) end
blanchet@38032
   335
            val readable_names = debug andalso overlord
blanchet@40204
   336
            val (atp_problem, pool, conjecture_offset, fact_names) =
blanchet@40059
   337
              prepare_atp_problem ctxt readable_names explicit_forall full_types
blanchet@40204
   338
                                  explicit_apply hyp_ts concl_t facts
blanchet@39452
   339
            val ss = tptp_strings_for_atp_problem use_conjecture_for_hypotheses
blanchet@40059
   340
                                                  atp_problem
blanchet@38631
   341
            val _ = File.write_list probfile ss
blanchet@38032
   342
            val conjecture_shape =
blanchet@38032
   343
              conjecture_offset + 1 upto conjecture_offset + length hyp_ts + 1
blanchet@38040
   344
              |> map single
blanchet@39318
   345
            val run_twice = has_incomplete_mode andalso not auto
blanchet@38645
   346
            val timer = Timer.startRealTimer ()
blanchet@38032
   347
            val result =
blanchet@39318
   348
              run false (if run_twice then
blanchet@39318
   349
                           Time.fromMilliseconds
blanchet@38645
   350
                                         (2 * Time.toMilliseconds timeout div 3)
blanchet@39318
   351
                         else
blanchet@39318
   352
                           timeout)
blanchet@39318
   353
              |> run_twice
blanchet@38645
   354
                 ? (fn (_, msecs0, _, SOME _) =>
blanchet@39318
   355
                       run true (Time.- (timeout, Timer.checkRealTimer timer))
blanchet@39452
   356
                       |> (fn (output, msecs, tstplike_proof, outcome) =>
blanchet@40409
   357
                              (output, int_opt_add msecs0 msecs, tstplike_proof,
blanchet@40409
   358
                               outcome))
blanchet@38645
   359
                     | result => result)
blanchet@40204
   360
          in ((pool, conjecture_shape, fact_names), result) end
blanchet@38032
   361
        else
blanchet@38032
   362
          error ("Bad executable: " ^ Path.implode command ^ ".")
blanchet@38023
   363
blanchet@38023
   364
    (* If the problem file has not been exported, remove it; otherwise, export
blanchet@38023
   365
       the proof file too. *)
blanchet@38023
   366
    fun cleanup probfile =
blanchet@40059
   367
      if dest_dir = "" then try File.rm probfile else NONE
blanchet@38023
   368
    fun export probfile (_, (output, _, _, _)) =
blanchet@40059
   369
      if dest_dir = "" then
blanchet@38023
   370
        ()
blanchet@38023
   371
      else
blanchet@38023
   372
        File.write (Path.explode (Path.implode probfile ^ "_proof")) output
blanchet@40204
   373
    val ((pool, conjecture_shape, fact_names),
blanchet@39452
   374
         (output, msecs, tstplike_proof, outcome)) =
blanchet@40061
   375
      with_path cleanup export run_on problem_path_name
blanchet@40204
   376
    val (conjecture_shape, fact_names) =
blanchet@40204
   377
      repair_conjecture_shape_and_fact_names output conjecture_shape fact_names
blanchet@39492
   378
    val important_message =
blanchet@40224
   379
      if not auto andalso random () <= important_message_keep_factor then
blanchet@39492
   380
        extract_important_message output
blanchet@39492
   381
      else
blanchet@39492
   382
        ""
blanchet@40204
   383
    val (message, used_facts) =
blanchet@38023
   384
      case outcome of
blanchet@38023
   385
        NONE =>
blanchet@38023
   386
        proof_text isar_proof
blanchet@38023
   387
            (pool, debug, isar_shrink_factor, ctxt, conjecture_shape)
blanchet@40060
   388
            (proof_banner auto, full_types, minimize_command, tstplike_proof,
blanchet@40204
   389
             fact_names, goal, subgoal)
blanchet@38744
   390
        |>> (fn message =>
blanchet@40341
   391
                message ^
blanchet@40341
   392
                (if verbose then
blanchet@40341
   393
                   "\nATP real CPU time: " ^
blanchet@40341
   394
                   string_from_time (Time.fromMilliseconds (the msecs)) ^ "."
blanchet@40341
   395
                 else
blanchet@40341
   396
                   "") ^
blanchet@39107
   397
                (if important_message <> "" then
blanchet@39107
   398
                   "\n\nImportant message from Dr. Geoff Sutcliffe:\n" ^
blanchet@39107
   399
                   important_message
blanchet@39107
   400
                 else
blanchet@39107
   401
                   ""))
blanchet@40669
   402
      | SOME failure => (string_for_failure "ATP" failure, [])
blanchet@38023
   403
  in
blanchet@40204
   404
    {outcome = outcome, message = message, used_facts = used_facts,
blanchet@40061
   405
     run_time_in_msecs = msecs}
blanchet@38023
   406
  end
blanchet@38023
   407
blanchet@40669
   408
(* "SMT_Failure.Abnormal_Termination" carries the solver's return code. Until
blanchet@40669
   409
   these are sorted out properly in the SMT module, we have to interpret these
blanchet@40669
   410
   ourselves. *)
blanchet@40684
   411
val remote_smt_failures =
blanchet@40684
   412
  [(22, CantConnect),
blanchet@40684
   413
   (127, NoPerl),
blanchet@40684
   414
   (2, NoLibwwwPerl)]
blanchet@40684
   415
val z3_failures =
blanchet@40684
   416
  [(103, MalformedInput),
blanchet@40684
   417
   (110, MalformedInput)]
blanchet@40684
   418
val unix_failures =
blanchet@40684
   419
  [(139, Crashed)]
blanchet@40684
   420
val smt_failures = remote_smt_failures @ z3_failures @ unix_failures
blanchet@40555
   421
boehmes@40424
   422
fun failure_from_smt_failure (SMT_Failure.Counterexample _) = Unprovable
boehmes@40424
   423
  | failure_from_smt_failure SMT_Failure.Time_Out = TimedOut
boehmes@40561
   424
  | failure_from_smt_failure (SMT_Failure.Abnormal_Termination code) =
blanchet@40684
   425
    (case AList.lookup (op =) smt_failures code of
blanchet@40684
   426
       SOME failure => failure
blanchet@40684
   427
     | NONE => UnknownError)
boehmes@40424
   428
  | failure_from_smt_failure SMT_Failure.Out_Of_Memory = OutOfResources
blanchet@40207
   429
  | failure_from_smt_failure _ = UnknownError
blanchet@40063
   430
blanchet@40698
   431
(* FUDGE *)
blanchet@40553
   432
val smt_max_iter = 8
blanchet@40419
   433
val smt_iter_fact_divisor = 2
blanchet@40419
   434
val smt_iter_min_msecs = 5000
blanchet@40419
   435
val smt_iter_timeout_divisor = 2
blanchet@40439
   436
val smt_monomorph_limit = 4
blanchet@40409
   437
blanchet@40723
   438
fun smt_filter_loop ({verbose, timeout, ...} : params) remote state i =
blanchet@40409
   439
  let
blanchet@40553
   440
    val ctxt = Proof.context_of state
blanchet@40553
   441
    fun iter timeout iter_num outcome0 msecs_so_far facts =
blanchet@40553
   442
      let
blanchet@40553
   443
        val timer = Timer.startRealTimer ()
blanchet@40553
   444
        val ms = timeout |> Time.toMilliseconds
blanchet@40553
   445
        val iter_timeout =
blanchet@40553
   446
          if iter_num < smt_max_iter then
blanchet@40553
   447
            Int.min (ms, Int.max (smt_iter_min_msecs,
blanchet@40553
   448
                                  ms div smt_iter_timeout_divisor))
blanchet@40553
   449
            |> Time.fromMilliseconds
blanchet@40553
   450
          else
blanchet@40553
   451
            timeout
blanchet@40553
   452
        val num_facts = length facts
blanchet@40553
   453
        val _ =
blanchet@40553
   454
          if verbose then
blanchet@40553
   455
            "SMT iteration with " ^ string_of_int num_facts ^ " fact" ^
blanchet@40668
   456
            plural_s num_facts ^ " for " ^ string_from_time iter_timeout ^ "..."
blanchet@40553
   457
            |> Output.urgent_message
blanchet@40553
   458
          else
blanchet@40553
   459
            ()
blanchet@40553
   460
        val {outcome, used_facts, run_time_in_msecs} =
blanchet@40979
   461
          SMT_Solver.smt_filter remote iter_timeout state facts i
blanchet@40553
   462
        val _ =
blanchet@40553
   463
          if verbose andalso is_some outcome then
blanchet@40553
   464
            "SMT outcome: " ^ SMT_Failure.string_of_failure ctxt (the outcome)
blanchet@40553
   465
            |> Output.urgent_message
blanchet@40553
   466
          else
blanchet@40553
   467
            ()
blanchet@40553
   468
        val outcome0 = if is_none outcome0 then SOME outcome else outcome0
blanchet@40553
   469
        val msecs_so_far = int_opt_add run_time_in_msecs msecs_so_far
blanchet@40553
   470
        val too_many_facts_perhaps =
blanchet@40553
   471
          case outcome of
blanchet@40553
   472
            NONE => false
blanchet@40553
   473
          | SOME (SMT_Failure.Counterexample _) => false
blanchet@40553
   474
          | SOME SMT_Failure.Time_Out => iter_timeout <> timeout
boehmes@40561
   475
          | SOME (SMT_Failure.Abnormal_Termination code) =>
blanchet@40553
   476
            (if verbose then
blanchet@40555
   477
               "The SMT solver invoked with " ^ string_of_int num_facts ^
blanchet@40692
   478
               " fact" ^ plural_s num_facts ^ " terminated abnormally with \
blanchet@40692
   479
               \exit code " ^ string_of_int code ^ "."
blanchet@40692
   480
               |> warning
blanchet@40553
   481
             else
blanchet@40553
   482
               ();
blanchet@40553
   483
             true (* kind of *))
blanchet@40553
   484
          | SOME SMT_Failure.Out_Of_Memory => true
blanchet@40553
   485
          | SOME _ => true
blanchet@40553
   486
        val timeout = Time.- (timeout, Timer.checkRealTimer timer)
blanchet@40553
   487
      in
blanchet@40553
   488
        if too_many_facts_perhaps andalso iter_num < smt_max_iter andalso
blanchet@40553
   489
           num_facts > 0 andalso Time.> (timeout, Time.zeroTime) then
blanchet@40553
   490
          let val facts = take (num_facts div smt_iter_fact_divisor) facts in
blanchet@40553
   491
            iter timeout (iter_num + 1) outcome0 msecs_so_far facts
blanchet@40553
   492
          end
blanchet@40553
   493
        else
blanchet@40553
   494
          {outcome = if is_none outcome then NONE else the outcome0,
blanchet@40553
   495
           used_facts = used_facts, run_time_in_msecs = msecs_so_far}
blanchet@40409
   496
      end
blanchet@40553
   497
  in iter timeout 1 NONE (SOME 0) end
blanchet@40409
   498
blanchet@40666
   499
(* taken from "Mirabelle" and generalized *)
blanchet@40666
   500
fun can_apply timeout tac state i =
blanchet@40666
   501
  let
blanchet@40666
   502
    val {context = ctxt, facts, goal} = Proof.goal state
blanchet@40666
   503
    val full_tac = Method.insert_tac facts i THEN tac ctxt i
blanchet@40666
   504
  in
blanchet@40666
   505
    case try (TimeLimit.timeLimit timeout (Seq.pull o full_tac)) goal of
blanchet@40666
   506
      SOME (SOME _) => true
blanchet@40666
   507
    | _ => false
blanchet@40666
   508
  end
blanchet@40666
   509
blanchet@40666
   510
val smt_metis_timeout = seconds 0.5
blanchet@40666
   511
blanchet@40693
   512
fun can_apply_metis debug state i ths =
blanchet@40693
   513
  can_apply smt_metis_timeout
blanchet@40693
   514
            (Config.put Metis_Tactics.verbose debug
blanchet@40693
   515
             #> (fn ctxt => Metis_Tactics.metis_tac ctxt ths)) state i
blanchet@40666
   516
blanchet@40983
   517
fun run_smt_solver auto name (params as {debug, ...}) minimize_command
blanchet@40983
   518
        ({state, subgoal, subgoal_count, facts, ...} : prover_problem) =
blanchet@36379
   519
  let
blanchet@40941
   520
    val (remote, suffix) =
blanchet@40941
   521
      case try (unprefix remote_prefix) name of
blanchet@40941
   522
        SOME suffix => (true, suffix)
blanchet@40941
   523
      | NONE => (false, name)
blanchet@40439
   524
    val repair_context =
blanchet@40941
   525
      Context.proof_map (SMT_Config.select_solver suffix)
blanchet@40941
   526
      #> Config.put SMT_Config.verbose debug
blanchet@40439
   527
      #> Config.put SMT_Config.monomorph_limit smt_monomorph_limit
blanchet@40439
   528
    val state = state |> Proof.map_context repair_context
blanchet@40668
   529
    val thy = Proof.theory_of state
blanchet@40982
   530
    val get_fact = Option.map (apsnd (Thm.transfer thy)) o try dest_Untranslated
blanchet@40983
   531
    val facts = facts |> map_filter get_fact
blanchet@40181
   532
    val {outcome, used_facts, run_time_in_msecs} =
blanchet@40982
   533
      smt_filter_loop params remote state subgoal facts
blanchet@40723
   534
    val (chained_lemmas, other_lemmas) = split_used_facts (map fst used_facts)
blanchet@40669
   535
    val outcome = outcome |> Option.map failure_from_smt_failure
blanchet@40063
   536
    val message =
blanchet@40184
   537
      case outcome of
blanchet@40184
   538
        NONE =>
blanchet@40666
   539
        let
blanchet@40666
   540
          val method =
blanchet@40693
   541
            if can_apply_metis debug state subgoal (map snd used_facts) then
blanchet@40693
   542
              "metis"
blanchet@40693
   543
            else
blanchet@40693
   544
              "smt"
blanchet@40666
   545
        in
blanchet@40666
   546
          try_command_line (proof_banner auto)
blanchet@40666
   547
                           (apply_on_subgoal subgoal subgoal_count ^
blanchet@40723
   548
                            command_call method (map fst other_lemmas)) ^
blanchet@40723
   549
          minimize_line minimize_command
blanchet@40723
   550
                        (map fst (other_lemmas @ chained_lemmas))
blanchet@40666
   551
        end
blanchet@40669
   552
      | SOME failure => string_for_failure "SMT solver" failure
blanchet@40063
   553
  in
blanchet@40666
   554
    {outcome = outcome, used_facts = map fst used_facts,
blanchet@40204
   555
     run_time_in_msecs = run_time_in_msecs, message = message}
blanchet@40063
   556
  end
blanchet@40063
   557
blanchet@40941
   558
fun get_prover ctxt auto name =
blanchet@40941
   559
  let val thy = ProofContext.theory_of ctxt in
blanchet@40941
   560
    if is_smt_prover ctxt name then
blanchet@40941
   561
      run_smt_solver auto name
blanchet@40941
   562
    else if member (op =) (available_atps thy) name then
blanchet@40941
   563
      run_atp auto name (get_atp thy name)
blanchet@40941
   564
    else
blanchet@40941
   565
      error ("No such prover: " ^ name ^ ".")
blanchet@40941
   566
  end
blanchet@40063
   567
blanchet@38023
   568
val setup =
blanchet@38023
   569
  dest_dir_setup
blanchet@38023
   570
  #> problem_prefix_setup
blanchet@39003
   571
  #> measure_run_time_setup
blanchet@38023
   572
wenzelm@28582
   573
end;