src/HOL/Tools/Sledgehammer/sledgehammer.ML
author blanchet
Mon Dec 06 11:26:17 2010 +0100 (2010-12-06 ago)
changeset 40982 d06ffd777f1f
parent 40979 e3ee5bbeb06e
child 40983 07526f546680
permissions -rw-r--r--
honor the default max relevant facts setting from the SMT solvers in Sledgehammer
blanchet@38021
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer.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@38021
     6
Sledgehammer's heart.
wenzelm@28477
     7
*)
wenzelm@28477
     8
blanchet@38021
     9
signature SLEDGEHAMMER =
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@38988
    14
  type relevance_override = Sledgehammer_Filter.relevance_override
blanchet@40114
    15
  type translated_formula = Sledgehammer_ATP_Translate.translated_formula
blanchet@40068
    16
  type minimize_command = Sledgehammer_ATP_Reconstruct.minimize_command
blanchet@39493
    17
blanchet@35969
    18
  type params =
blanchet@38982
    19
    {blocking: bool,
blanchet@38982
    20
     debug: bool,
blanchet@35969
    21
     verbose: bool,
blanchet@36143
    22
     overlord: bool,
blanchet@40059
    23
     provers: string list,
blanchet@35969
    24
     full_types: bool,
blanchet@36235
    25
     explicit_apply: bool,
blanchet@38745
    26
     relevance_thresholds: real * real,
blanchet@38744
    27
     max_relevant: int option,
blanchet@35969
    28
     isar_proof: bool,
blanchet@36924
    29
     isar_shrink_factor: int,
blanchet@38985
    30
     timeout: Time.time,
blanchet@38985
    31
     expect: string}
blanchet@39493
    32
blanchet@40204
    33
  datatype fact =
blanchet@40114
    34
    Untranslated of (string * locality) * thm |
blanchet@40114
    35
    Translated of term * ((string * locality) * translated_formula) option
blanchet@40061
    36
blanchet@40061
    37
  type prover_problem =
blanchet@39318
    38
    {state: Proof.state,
blanchet@38998
    39
     goal: thm,
blanchet@38998
    40
     subgoal: int,
blanchet@40065
    41
     subgoal_count: int,
blanchet@40204
    42
     facts: fact list,
blanchet@39366
    43
     only: bool}
blanchet@39493
    44
blanchet@40061
    45
  type prover_result =
blanchet@36370
    46
    {outcome: failure option,
blanchet@40204
    47
     used_facts: (string * locality) list,
blanchet@40062
    48
     run_time_in_msecs: int option,
blanchet@40062
    49
     message: string}
blanchet@39493
    50
blanchet@40061
    51
  type prover = params -> minimize_command -> prover_problem -> prover_result
blanchet@35867
    52
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@40369
    57
    Proof.context -> string -> string * typ -> bool
blanchet@40941
    58
  val relevance_fudge_for_prover : Proof.context -> string -> relevance_fudge
blanchet@38023
    59
  val dest_dir : string Config.T
blanchet@38023
    60
  val problem_prefix : string Config.T
blanchet@39003
    61
  val measure_run_time : bool Config.T
blanchet@40941
    62
  val available_provers : Proof.context -> unit
blanchet@40059
    63
  val kill_provers : unit -> unit
blanchet@40059
    64
  val running_provers : unit -> unit
blanchet@40059
    65
  val messages : int option -> unit
blanchet@40941
    66
  val get_prover : Proof.context -> bool -> string -> prover
blanchet@38044
    67
  val run_sledgehammer :
blanchet@39318
    68
    params -> bool -> int -> relevance_override -> (string -> minimize_command)
blanchet@39318
    69
    -> Proof.state -> bool * Proof.state
blanchet@38023
    70
  val setup : theory -> theory
wenzelm@28477
    71
end;
wenzelm@28477
    72
blanchet@38021
    73
structure Sledgehammer : SLEDGEHAMMER =
wenzelm@28477
    74
struct
wenzelm@28477
    75
blanchet@38028
    76
open ATP_Problem
blanchet@39491
    77
open ATP_Proof
blanchet@38028
    78
open ATP_Systems
blanchet@39494
    79
open Metis_Translate
blanchet@38023
    80
open Sledgehammer_Util
blanchet@38988
    81
open Sledgehammer_Filter
blanchet@40068
    82
open Sledgehammer_ATP_Translate
blanchet@40068
    83
open Sledgehammer_ATP_Reconstruct
blanchet@37583
    84
blanchet@38023
    85
blanchet@37583
    86
(** The Sledgehammer **)
blanchet@37583
    87
blanchet@38102
    88
(* Identifier to distinguish Sledgehammer from other tools using
blanchet@38102
    89
   "Async_Manager". *)
blanchet@37585
    90
val das_Tool = "Sledgehammer"
blanchet@37585
    91
blanchet@40941
    92
fun is_smt_prover ctxt name =
blanchet@40941
    93
  let val smts = SMT_Solver.available_solvers_of ctxt in
blanchet@40941
    94
    case try (unprefix remote_prefix) name of
blanchet@40941
    95
      SOME suffix => member (op =) smts suffix andalso
blanchet@40941
    96
                     SMT_Solver.is_remotely_available ctxt suffix
blanchet@40941
    97
    | NONE => member (op =) smts name
blanchet@40941
    98
  end
blanchet@40062
    99
blanchet@40941
   100
fun is_prover_available ctxt name =
blanchet@40941
   101
  let val thy = ProofContext.theory_of ctxt in
blanchet@40941
   102
    is_smt_prover ctxt name orelse member (op =) (available_atps thy) name
blanchet@40941
   103
  end
blanchet@40072
   104
blanchet@40072
   105
fun is_prover_installed ctxt name =
blanchet@40072
   106
  let val thy = ProofContext.theory_of ctxt in
blanchet@40941
   107
    if is_smt_prover ctxt name then
blanchet@40941
   108
      String.isPrefix remote_prefix name orelse
blanchet@40941
   109
      SMT_Solver.is_locally_installed ctxt name
blanchet@40941
   110
    else
blanchet@40941
   111
      is_atp_installed thy name
blanchet@40941
   112
  end
blanchet@40941
   113
blanchet@40941
   114
fun available_smt_solvers ctxt =
blanchet@40941
   115
  let val smts = SMT_Solver.available_solvers_of ctxt in
blanchet@40941
   116
    smts @ map (prefix remote_prefix)
blanchet@40941
   117
               (filter (SMT_Solver.is_remotely_available ctxt) smts)
blanchet@40072
   118
  end
blanchet@40072
   119
blanchet@40698
   120
(* FUDGE *)
blanchet@40698
   121
val auto_max_relevant_divisor = 2
blanchet@40060
   122
blanchet@40941
   123
fun default_max_relevant_for_prover ctxt name =
blanchet@40941
   124
  let val thy = ProofContext.theory_of ctxt in
blanchet@40982
   125
    if is_smt_prover ctxt name then
blanchet@40982
   126
      SMT_Solver.default_max_relevant ctxt
blanchet@40982
   127
          (perhaps (try (unprefix remote_prefix)) name)
blanchet@40982
   128
    else
blanchet@40982
   129
      #default_max_relevant (get_atp thy name)
blanchet@40941
   130
  end
blanchet@40063
   131
blanchet@40071
   132
(* These are typically simplified away by "Meson.presimplify". Equality is
blanchet@40071
   133
   handled specially via "fequal". *)
blanchet@40071
   134
val atp_irrelevant_consts =
blanchet@40071
   135
  [@{const_name False}, @{const_name True}, @{const_name If}, @{const_name Let},
blanchet@40071
   136
   @{const_name HOL.eq}]
blanchet@40206
   137
blanchet@40369
   138
fun is_built_in_const_for_prover ctxt name (s, T) =
blanchet@40941
   139
  if is_smt_prover ctxt name then SMT_Builtin.is_builtin ctxt (s, T)
blanchet@40369
   140
  else member (op =) atp_irrelevant_consts s
blanchet@40071
   141
blanchet@40070
   142
(* FUDGE *)
blanchet@40070
   143
val atp_relevance_fudge =
blanchet@40070
   144
  {worse_irrel_freq = 100.0,
blanchet@40070
   145
   higher_order_irrel_weight = 1.05,
blanchet@40070
   146
   abs_rel_weight = 0.5,
blanchet@40070
   147
   abs_irrel_weight = 2.0,
blanchet@40070
   148
   skolem_irrel_weight = 0.75,
blanchet@40070
   149
   theory_const_rel_weight = 0.5,
blanchet@40070
   150
   theory_const_irrel_weight = 0.25,
blanchet@40070
   151
   intro_bonus = 0.15,
blanchet@40070
   152
   elim_bonus = 0.15,
blanchet@40070
   153
   simp_bonus = 0.15,
blanchet@40070
   154
   local_bonus = 0.55,
blanchet@40070
   155
   assum_bonus = 1.05,
blanchet@40070
   156
   chained_bonus = 1.5,
blanchet@40070
   157
   max_imperfect = 11.5,
blanchet@40070
   158
   max_imperfect_exp = 1.0,
blanchet@40070
   159
   threshold_divisor = 2.0,
blanchet@40070
   160
   ridiculous_threshold = 0.1}
blanchet@40070
   161
blanchet@40071
   162
(* FUDGE (FIXME) *)
blanchet@40070
   163
val smt_relevance_fudge =
blanchet@40071
   164
  {worse_irrel_freq = #worse_irrel_freq atp_relevance_fudge,
blanchet@40071
   165
   higher_order_irrel_weight = #higher_order_irrel_weight atp_relevance_fudge,
blanchet@40071
   166
   abs_rel_weight = #abs_rel_weight atp_relevance_fudge,
blanchet@40071
   167
   abs_irrel_weight = #abs_irrel_weight atp_relevance_fudge,
blanchet@40071
   168
   skolem_irrel_weight = #skolem_irrel_weight atp_relevance_fudge,
blanchet@40071
   169
   theory_const_rel_weight = #theory_const_rel_weight atp_relevance_fudge,
blanchet@40071
   170
   theory_const_irrel_weight = #theory_const_irrel_weight atp_relevance_fudge,
blanchet@40071
   171
   intro_bonus = #intro_bonus atp_relevance_fudge,
blanchet@40071
   172
   elim_bonus = #elim_bonus atp_relevance_fudge,
blanchet@40071
   173
   simp_bonus = #simp_bonus atp_relevance_fudge,
blanchet@40071
   174
   local_bonus = #local_bonus atp_relevance_fudge,
blanchet@40071
   175
   assum_bonus = #assum_bonus atp_relevance_fudge,
blanchet@40071
   176
   chained_bonus = #chained_bonus atp_relevance_fudge,
blanchet@40071
   177
   max_imperfect = #max_imperfect atp_relevance_fudge,
blanchet@40071
   178
   max_imperfect_exp = #max_imperfect_exp atp_relevance_fudge,
blanchet@40071
   179
   threshold_divisor = #threshold_divisor atp_relevance_fudge,
blanchet@40071
   180
   ridiculous_threshold = #ridiculous_threshold atp_relevance_fudge}
blanchet@40070
   181
blanchet@40941
   182
fun relevance_fudge_for_prover ctxt name =
blanchet@40941
   183
  if is_smt_prover ctxt name then smt_relevance_fudge else atp_relevance_fudge
blanchet@40070
   184
blanchet@40941
   185
fun available_provers ctxt =
blanchet@40060
   186
  let
blanchet@40941
   187
    val thy = ProofContext.theory_of ctxt
blanchet@40060
   188
    val (remote_provers, local_provers) =
blanchet@40941
   189
      sort_strings (available_atps thy) @
blanchet@40941
   190
      sort_strings (available_smt_solvers ctxt)
blanchet@40060
   191
      |> List.partition (String.isPrefix remote_prefix)
blanchet@40060
   192
  in
blanchet@40205
   193
    Output.urgent_message ("Available provers: " ^
blanchet@40205
   194
                           commas (local_provers @ remote_provers) ^ ".")
blanchet@40060
   195
  end
blanchet@35969
   196
blanchet@40059
   197
fun kill_provers () = Async_Manager.kill_threads das_Tool "provers"
blanchet@40059
   198
fun running_provers () = Async_Manager.running_threads das_Tool "provers"
blanchet@40059
   199
val messages = Async_Manager.thread_messages das_Tool "prover"
blanchet@40059
   200
blanchet@40059
   201
(** problems, results, ATPs, etc. **)
blanchet@35969
   202
blanchet@35969
   203
type params =
blanchet@38982
   204
  {blocking: bool,
blanchet@38982
   205
   debug: bool,
blanchet@35969
   206
   verbose: bool,
blanchet@36143
   207
   overlord: bool,
blanchet@40059
   208
   provers: string list,
blanchet@35969
   209
   full_types: bool,
blanchet@36235
   210
   explicit_apply: bool,
blanchet@38745
   211
   relevance_thresholds: real * real,
blanchet@38744
   212
   max_relevant: int option,
blanchet@35969
   213
   isar_proof: bool,
blanchet@36924
   214
   isar_shrink_factor: int,
blanchet@38985
   215
   timeout: Time.time,
blanchet@38985
   216
   expect: string}
blanchet@35867
   217
blanchet@40204
   218
datatype fact =
blanchet@40114
   219
  Untranslated of (string * locality) * thm |
blanchet@40114
   220
  Translated of term * ((string * locality) * translated_formula) option
blanchet@40061
   221
blanchet@40061
   222
type prover_problem =
blanchet@39318
   223
  {state: Proof.state,
blanchet@38998
   224
   goal: thm,
blanchet@38998
   225
   subgoal: int,
blanchet@40065
   226
   subgoal_count: int,
blanchet@40204
   227
   facts: fact list,
blanchet@39366
   228
   only: bool}
blanchet@35867
   229
blanchet@40061
   230
type prover_result =
blanchet@36370
   231
  {outcome: failure option,
blanchet@35969
   232
   message: string,
blanchet@40204
   233
   used_facts: (string * locality) list,
blanchet@40062
   234
   run_time_in_msecs: int option}
blanchet@35867
   235
blanchet@40061
   236
type prover = params -> minimize_command -> prover_problem -> prover_result
blanchet@35867
   237
blanchet@38023
   238
(* configuration attributes *)
blanchet@38023
   239
blanchet@38991
   240
val (dest_dir, dest_dir_setup) =
blanchet@39003
   241
  Attrib.config_string "sledgehammer_dest_dir" (K "")
blanchet@38991
   242
  (* Empty string means create files in Isabelle's temporary files directory. *)
blanchet@38023
   243
blanchet@38023
   244
val (problem_prefix, problem_prefix_setup) =
blanchet@39003
   245
  Attrib.config_string "sledgehammer_problem_prefix" (K "prob")
blanchet@38023
   246
blanchet@39003
   247
val (measure_run_time, measure_run_time_setup) =
blanchet@39003
   248
  Attrib.config_bool "sledgehammer_measure_run_time" (K false)
wenzelm@28484
   249
blanchet@38023
   250
fun with_path cleanup after f path =
blanchet@38023
   251
  Exn.capture f path
blanchet@38023
   252
  |> tap (fn _ => cleanup path)
blanchet@38023
   253
  |> Exn.release
blanchet@38023
   254
  |> tap (after path)
blanchet@38023
   255
blanchet@40204
   256
fun prover_description ctxt ({blocking, verbose, ...} : params) name num_facts i
blanchet@40204
   257
                       n goal =
blanchet@40060
   258
  quote name ^
blanchet@40060
   259
  (if verbose then
blanchet@40204
   260
     " with " ^ string_of_int num_facts ^ " fact" ^ plural_s num_facts
blanchet@40060
   261
   else
blanchet@40060
   262
     "") ^
blanchet@40060
   263
  " on " ^ (if n = 1 then "goal" else "subgoal " ^ string_of_int i) ^ ":" ^
blanchet@40060
   264
  (if blocking then
blanchet@40060
   265
     ""
blanchet@40060
   266
   else
blanchet@40060
   267
     "\n" ^ Syntax.string_of_term ctxt (Thm.term_of (Thm.cprem_of goal i)))
blanchet@40060
   268
blanchet@40060
   269
fun proof_banner auto =
blanchet@40224
   270
  if auto then "Auto Sledgehammer found a proof" else "Try this command"
blanchet@40060
   271
blanchet@40059
   272
(* generic TPTP-based ATPs *)
blanchet@38023
   273
blanchet@40114
   274
fun dest_Untranslated (Untranslated p) = p
blanchet@40114
   275
  | dest_Untranslated (Translated _) = raise Fail "dest_Untranslated"
blanchet@40204
   276
fun translated_fact ctxt (Untranslated p) = translate_fact ctxt p
blanchet@40204
   277
  | translated_fact _ (Translated p) = p
blanchet@40205
   278
fun fact_name (Untranslated ((name, _), _)) = SOME name
blanchet@40205
   279
  | fact_name (Translated (_, p)) = Option.map (fst o fst) p
blanchet@40061
   280
blanchet@40409
   281
fun int_opt_add (SOME m) (SOME n) = SOME (m + n)
blanchet@40409
   282
  | int_opt_add _ _ = NONE
blanchet@40062
   283
blanchet@39492
   284
(* Important messages are important but not so important that users want to see
blanchet@39492
   285
   them each time. *)
blanchet@39493
   286
val important_message_keep_factor = 0.1
blanchet@39492
   287
blanchet@40063
   288
fun run_atp auto atp_name
blanchet@38645
   289
        {exec, required_execs, arguments, has_incomplete_mode, proof_delims,
blanchet@38997
   290
         known_failures, default_max_relevant, explicit_forall,
blanchet@38997
   291
         use_conjecture_for_hypotheses}
blanchet@38455
   292
        ({debug, verbose, overlord, full_types, explicit_apply,
blanchet@38998
   293
          max_relevant, isar_proof, isar_shrink_factor, timeout, ...} : params)
blanchet@40061
   294
        minimize_command
blanchet@40204
   295
        ({state, goal, subgoal, facts, only, ...} : prover_problem) =
blanchet@38023
   296
  let
blanchet@39318
   297
    val ctxt = Proof.context_of state
blanchet@38998
   298
    val (_, hyp_ts, concl_t) = strip_subgoal goal subgoal
blanchet@40204
   299
    val facts =
blanchet@40204
   300
      facts |> not only ? take (the_default default_max_relevant max_relevant)
blanchet@40204
   301
            |> map (translated_fact ctxt)
blanchet@40059
   302
    val dest_dir = if overlord then getenv "ISABELLE_HOME_USER"
blanchet@40059
   303
                   else Config.get ctxt dest_dir
blanchet@40059
   304
    val problem_prefix = Config.get ctxt problem_prefix
blanchet@40061
   305
    val problem_file_name =
blanchet@39003
   306
      Path.basic ((if overlord then "prob_" ^ atp_name
blanchet@40059
   307
                   else problem_prefix ^ serial_string ())
blanchet@39003
   308
                  ^ "_" ^ string_of_int subgoal)
blanchet@40061
   309
    val problem_path_name =
blanchet@40059
   310
      if dest_dir = "" then
blanchet@40061
   311
        File.tmp_path problem_file_name
blanchet@40059
   312
      else if File.exists (Path.explode dest_dir) then
blanchet@40061
   313
        Path.append (Path.explode dest_dir) problem_file_name
blanchet@39003
   314
      else
blanchet@40059
   315
        error ("No such directory: " ^ quote dest_dir ^ ".")
blanchet@39003
   316
    val measure_run_time = verbose orelse Config.get ctxt measure_run_time
blanchet@38092
   317
    val command = Path.explode (getenv (fst exec) ^ "/" ^ snd exec)
blanchet@40059
   318
    (* write out problem file and call ATP *)
blanchet@38645
   319
    fun command_line complete timeout probfile =
blanchet@38023
   320
      let
blanchet@38023
   321
        val core = File.shell_path command ^ " " ^ arguments complete timeout ^
blanchet@38023
   322
                   " " ^ File.shell_path probfile
blanchet@38023
   323
      in
blanchet@39010
   324
        (if measure_run_time then "TIMEFORMAT='%3R'; { time " ^ core ^ " ; }"
blanchet@38744
   325
         else "exec " ^ core) ^ " 2>&1"
blanchet@38023
   326
      end
blanchet@38023
   327
    fun split_time s =
blanchet@38023
   328
      let
blanchet@38023
   329
        val split = String.tokens (fn c => str c = "\n");
blanchet@38023
   330
        val (output, t) = s |> split |> split_last |> apfst cat_lines;
blanchet@38023
   331
        fun as_num f = f >> (fst o read_int);
blanchet@38023
   332
        val num = as_num (Scan.many1 Symbol.is_ascii_digit);
blanchet@38023
   333
        val digit = Scan.one Symbol.is_ascii_digit;
blanchet@38023
   334
        val num3 = as_num (digit ::: digit ::: (digit >> single));
blanchet@38023
   335
        val time = num --| Scan.$$ "." -- num3 >> (fn (a, b) => a * 1000 + b);
wenzelm@40627
   336
        val as_time = Scan.read Symbol.stopper time o raw_explode
blanchet@38023
   337
      in (output, as_time t) end;
blanchet@38023
   338
    fun run_on probfile =
blanchet@38092
   339
      case filter (curry (op =) "" o getenv o fst) (exec :: required_execs) of
blanchet@38032
   340
        (home_var, _) :: _ =>
blanchet@38023
   341
        error ("The environment variable " ^ quote home_var ^ " is not set.")
blanchet@38032
   342
      | [] =>
blanchet@38032
   343
        if File.exists command then
blanchet@38032
   344
          let
blanchet@39318
   345
            fun run complete timeout =
blanchet@38032
   346
              let
blanchet@38645
   347
                val command = command_line complete timeout probfile
blanchet@38032
   348
                val ((output, msecs), res_code) =
blanchet@38032
   349
                  bash_output command
blanchet@38032
   350
                  |>> (if overlord then
blanchet@38032
   351
                         prefix ("% " ^ command ^ "\n% " ^ timestamp () ^ "\n")
blanchet@38032
   352
                       else
blanchet@38032
   353
                         I)
blanchet@40062
   354
                  |>> (if measure_run_time then split_time else rpair NONE)
blanchet@39452
   355
                val (tstplike_proof, outcome) =
blanchet@39452
   356
                  extract_tstplike_proof_and_outcome complete res_code
blanchet@39452
   357
                      proof_delims known_failures output
blanchet@39452
   358
              in (output, msecs, tstplike_proof, outcome) end
blanchet@38032
   359
            val readable_names = debug andalso overlord
blanchet@40204
   360
            val (atp_problem, pool, conjecture_offset, fact_names) =
blanchet@40059
   361
              prepare_atp_problem ctxt readable_names explicit_forall full_types
blanchet@40204
   362
                                  explicit_apply hyp_ts concl_t facts
blanchet@39452
   363
            val ss = tptp_strings_for_atp_problem use_conjecture_for_hypotheses
blanchet@40059
   364
                                                  atp_problem
blanchet@38631
   365
            val _ = File.write_list probfile ss
blanchet@38032
   366
            val conjecture_shape =
blanchet@38032
   367
              conjecture_offset + 1 upto conjecture_offset + length hyp_ts + 1
blanchet@38040
   368
              |> map single
blanchet@39318
   369
            val run_twice = has_incomplete_mode andalso not auto
blanchet@38645
   370
            val timer = Timer.startRealTimer ()
blanchet@38032
   371
            val result =
blanchet@39318
   372
              run false (if run_twice then
blanchet@39318
   373
                           Time.fromMilliseconds
blanchet@38645
   374
                                         (2 * Time.toMilliseconds timeout div 3)
blanchet@39318
   375
                         else
blanchet@39318
   376
                           timeout)
blanchet@39318
   377
              |> run_twice
blanchet@38645
   378
                 ? (fn (_, msecs0, _, SOME _) =>
blanchet@39318
   379
                       run true (Time.- (timeout, Timer.checkRealTimer timer))
blanchet@39452
   380
                       |> (fn (output, msecs, tstplike_proof, outcome) =>
blanchet@40409
   381
                              (output, int_opt_add msecs0 msecs, tstplike_proof,
blanchet@40409
   382
                               outcome))
blanchet@38645
   383
                     | result => result)
blanchet@40204
   384
          in ((pool, conjecture_shape, fact_names), result) end
blanchet@38032
   385
        else
blanchet@38032
   386
          error ("Bad executable: " ^ Path.implode command ^ ".")
blanchet@38023
   387
blanchet@38023
   388
    (* If the problem file has not been exported, remove it; otherwise, export
blanchet@38023
   389
       the proof file too. *)
blanchet@38023
   390
    fun cleanup probfile =
blanchet@40059
   391
      if dest_dir = "" then try File.rm probfile else NONE
blanchet@38023
   392
    fun export probfile (_, (output, _, _, _)) =
blanchet@40059
   393
      if dest_dir = "" then
blanchet@38023
   394
        ()
blanchet@38023
   395
      else
blanchet@38023
   396
        File.write (Path.explode (Path.implode probfile ^ "_proof")) output
blanchet@40204
   397
    val ((pool, conjecture_shape, fact_names),
blanchet@39452
   398
         (output, msecs, tstplike_proof, outcome)) =
blanchet@40061
   399
      with_path cleanup export run_on problem_path_name
blanchet@40204
   400
    val (conjecture_shape, fact_names) =
blanchet@40204
   401
      repair_conjecture_shape_and_fact_names output conjecture_shape fact_names
blanchet@39492
   402
    val important_message =
blanchet@40224
   403
      if not auto andalso random () <= important_message_keep_factor then
blanchet@39492
   404
        extract_important_message output
blanchet@39492
   405
      else
blanchet@39492
   406
        ""
blanchet@40204
   407
    val (message, used_facts) =
blanchet@38023
   408
      case outcome of
blanchet@38023
   409
        NONE =>
blanchet@38023
   410
        proof_text isar_proof
blanchet@38023
   411
            (pool, debug, isar_shrink_factor, ctxt, conjecture_shape)
blanchet@40060
   412
            (proof_banner auto, full_types, minimize_command, tstplike_proof,
blanchet@40204
   413
             fact_names, goal, subgoal)
blanchet@38744
   414
        |>> (fn message =>
blanchet@40341
   415
                message ^
blanchet@40341
   416
                (if verbose then
blanchet@40341
   417
                   "\nATP real CPU time: " ^
blanchet@40341
   418
                   string_from_time (Time.fromMilliseconds (the msecs)) ^ "."
blanchet@40341
   419
                 else
blanchet@40341
   420
                   "") ^
blanchet@39107
   421
                (if important_message <> "" then
blanchet@39107
   422
                   "\n\nImportant message from Dr. Geoff Sutcliffe:\n" ^
blanchet@39107
   423
                   important_message
blanchet@39107
   424
                 else
blanchet@39107
   425
                   ""))
blanchet@40669
   426
      | SOME failure => (string_for_failure "ATP" failure, [])
blanchet@38023
   427
  in
blanchet@40204
   428
    {outcome = outcome, message = message, used_facts = used_facts,
blanchet@40061
   429
     run_time_in_msecs = msecs}
blanchet@38023
   430
  end
blanchet@38023
   431
blanchet@40669
   432
(* "SMT_Failure.Abnormal_Termination" carries the solver's return code. Until
blanchet@40669
   433
   these are sorted out properly in the SMT module, we have to interpret these
blanchet@40669
   434
   ourselves. *)
blanchet@40684
   435
val remote_smt_failures =
blanchet@40684
   436
  [(22, CantConnect),
blanchet@40684
   437
   (127, NoPerl),
blanchet@40684
   438
   (2, NoLibwwwPerl)]
blanchet@40684
   439
val z3_failures =
blanchet@40684
   440
  [(103, MalformedInput),
blanchet@40684
   441
   (110, MalformedInput)]
blanchet@40684
   442
val unix_failures =
blanchet@40684
   443
  [(139, Crashed)]
blanchet@40684
   444
val smt_failures = remote_smt_failures @ z3_failures @ unix_failures
blanchet@40555
   445
boehmes@40424
   446
fun failure_from_smt_failure (SMT_Failure.Counterexample _) = Unprovable
boehmes@40424
   447
  | failure_from_smt_failure SMT_Failure.Time_Out = TimedOut
boehmes@40561
   448
  | failure_from_smt_failure (SMT_Failure.Abnormal_Termination code) =
blanchet@40684
   449
    (case AList.lookup (op =) smt_failures code of
blanchet@40684
   450
       SOME failure => failure
blanchet@40684
   451
     | NONE => UnknownError)
boehmes@40424
   452
  | failure_from_smt_failure SMT_Failure.Out_Of_Memory = OutOfResources
blanchet@40207
   453
  | failure_from_smt_failure _ = UnknownError
blanchet@40063
   454
blanchet@40698
   455
(* FUDGE *)
blanchet@40553
   456
val smt_max_iter = 8
blanchet@40419
   457
val smt_iter_fact_divisor = 2
blanchet@40419
   458
val smt_iter_min_msecs = 5000
blanchet@40419
   459
val smt_iter_timeout_divisor = 2
blanchet@40439
   460
val smt_monomorph_limit = 4
blanchet@40409
   461
blanchet@40723
   462
fun smt_filter_loop ({verbose, timeout, ...} : params) remote state i =
blanchet@40409
   463
  let
blanchet@40553
   464
    val ctxt = Proof.context_of state
blanchet@40553
   465
    fun iter timeout iter_num outcome0 msecs_so_far facts =
blanchet@40553
   466
      let
blanchet@40553
   467
        val timer = Timer.startRealTimer ()
blanchet@40553
   468
        val ms = timeout |> Time.toMilliseconds
blanchet@40553
   469
        val iter_timeout =
blanchet@40553
   470
          if iter_num < smt_max_iter then
blanchet@40553
   471
            Int.min (ms, Int.max (smt_iter_min_msecs,
blanchet@40553
   472
                                  ms div smt_iter_timeout_divisor))
blanchet@40553
   473
            |> Time.fromMilliseconds
blanchet@40553
   474
          else
blanchet@40553
   475
            timeout
blanchet@40553
   476
        val num_facts = length facts
blanchet@40553
   477
        val _ =
blanchet@40553
   478
          if verbose then
blanchet@40553
   479
            "SMT iteration with " ^ string_of_int num_facts ^ " fact" ^
blanchet@40668
   480
            plural_s num_facts ^ " for " ^ string_from_time iter_timeout ^ "..."
blanchet@40553
   481
            |> Output.urgent_message
blanchet@40553
   482
          else
blanchet@40553
   483
            ()
blanchet@40553
   484
        val {outcome, used_facts, run_time_in_msecs} =
blanchet@40979
   485
          SMT_Solver.smt_filter remote iter_timeout state facts i
blanchet@40553
   486
        val _ =
blanchet@40553
   487
          if verbose andalso is_some outcome then
blanchet@40553
   488
            "SMT outcome: " ^ SMT_Failure.string_of_failure ctxt (the outcome)
blanchet@40553
   489
            |> Output.urgent_message
blanchet@40553
   490
          else
blanchet@40553
   491
            ()
blanchet@40553
   492
        val outcome0 = if is_none outcome0 then SOME outcome else outcome0
blanchet@40553
   493
        val msecs_so_far = int_opt_add run_time_in_msecs msecs_so_far
blanchet@40553
   494
        val too_many_facts_perhaps =
blanchet@40553
   495
          case outcome of
blanchet@40553
   496
            NONE => false
blanchet@40553
   497
          | SOME (SMT_Failure.Counterexample _) => false
blanchet@40553
   498
          | SOME SMT_Failure.Time_Out => iter_timeout <> timeout
boehmes@40561
   499
          | SOME (SMT_Failure.Abnormal_Termination code) =>
blanchet@40553
   500
            (if verbose then
blanchet@40555
   501
               "The SMT solver invoked with " ^ string_of_int num_facts ^
blanchet@40692
   502
               " fact" ^ plural_s num_facts ^ " terminated abnormally with \
blanchet@40692
   503
               \exit code " ^ string_of_int code ^ "."
blanchet@40692
   504
               |> warning
blanchet@40553
   505
             else
blanchet@40553
   506
               ();
blanchet@40553
   507
             true (* kind of *))
blanchet@40553
   508
          | SOME SMT_Failure.Out_Of_Memory => true
blanchet@40553
   509
          | SOME _ => true
blanchet@40553
   510
        val timeout = Time.- (timeout, Timer.checkRealTimer timer)
blanchet@40553
   511
      in
blanchet@40553
   512
        if too_many_facts_perhaps andalso iter_num < smt_max_iter andalso
blanchet@40553
   513
           num_facts > 0 andalso Time.> (timeout, Time.zeroTime) then
blanchet@40553
   514
          let val facts = take (num_facts div smt_iter_fact_divisor) facts in
blanchet@40553
   515
            iter timeout (iter_num + 1) outcome0 msecs_so_far facts
blanchet@40553
   516
          end
blanchet@40553
   517
        else
blanchet@40553
   518
          {outcome = if is_none outcome then NONE else the outcome0,
blanchet@40553
   519
           used_facts = used_facts, run_time_in_msecs = msecs_so_far}
blanchet@40409
   520
      end
blanchet@40553
   521
  in iter timeout 1 NONE (SOME 0) end
blanchet@40409
   522
blanchet@40666
   523
(* taken from "Mirabelle" and generalized *)
blanchet@40666
   524
fun can_apply timeout tac state i =
blanchet@40666
   525
  let
blanchet@40666
   526
    val {context = ctxt, facts, goal} = Proof.goal state
blanchet@40666
   527
    val full_tac = Method.insert_tac facts i THEN tac ctxt i
blanchet@40666
   528
  in
blanchet@40666
   529
    case try (TimeLimit.timeLimit timeout (Seq.pull o full_tac)) goal of
blanchet@40666
   530
      SOME (SOME _) => true
blanchet@40666
   531
    | _ => false
blanchet@40666
   532
  end
blanchet@40666
   533
blanchet@40666
   534
val smt_metis_timeout = seconds 0.5
blanchet@40666
   535
blanchet@40693
   536
fun can_apply_metis debug state i ths =
blanchet@40693
   537
  can_apply smt_metis_timeout
blanchet@40693
   538
            (Config.put Metis_Tactics.verbose debug
blanchet@40693
   539
             #> (fn ctxt => Metis_Tactics.metis_tac ctxt ths)) state i
blanchet@40666
   540
blanchet@40982
   541
fun run_smt_solver auto name (params as {debug, max_relevant, ...})
blanchet@40982
   542
        minimize_command
blanchet@40982
   543
        ({state, subgoal, subgoal_count, facts, only, ...} : prover_problem) =
blanchet@36379
   544
  let
blanchet@40941
   545
    val (remote, suffix) =
blanchet@40941
   546
      case try (unprefix remote_prefix) name of
blanchet@40941
   547
        SOME suffix => (true, suffix)
blanchet@40941
   548
      | NONE => (false, name)
blanchet@40439
   549
    val repair_context =
blanchet@40941
   550
      Context.proof_map (SMT_Config.select_solver suffix)
blanchet@40941
   551
      #> Config.put SMT_Config.verbose debug
blanchet@40439
   552
      #> Config.put SMT_Config.monomorph_limit smt_monomorph_limit
blanchet@40439
   553
    val state = state |> Proof.map_context repair_context
blanchet@40982
   554
    val ctxt = Proof.context_of state
blanchet@40668
   555
    val thy = Proof.theory_of state
blanchet@40982
   556
    val get_fact = Option.map (apsnd (Thm.transfer thy)) o try dest_Untranslated
blanchet@40982
   557
    val default_max_relevant = SMT_Solver.default_max_relevant ctxt suffix
blanchet@40982
   558
    val facts =
blanchet@40982
   559
      facts |> map_filter get_fact
blanchet@40982
   560
            |> not only ? take (the_default default_max_relevant max_relevant)
blanchet@40181
   561
    val {outcome, used_facts, run_time_in_msecs} =
blanchet@40982
   562
      smt_filter_loop params remote state subgoal facts
blanchet@40723
   563
    val (chained_lemmas, other_lemmas) = split_used_facts (map fst used_facts)
blanchet@40669
   564
    val outcome = outcome |> Option.map failure_from_smt_failure
blanchet@40063
   565
    val message =
blanchet@40184
   566
      case outcome of
blanchet@40184
   567
        NONE =>
blanchet@40666
   568
        let
blanchet@40666
   569
          val method =
blanchet@40693
   570
            if can_apply_metis debug state subgoal (map snd used_facts) then
blanchet@40693
   571
              "metis"
blanchet@40693
   572
            else
blanchet@40693
   573
              "smt"
blanchet@40666
   574
        in
blanchet@40666
   575
          try_command_line (proof_banner auto)
blanchet@40666
   576
                           (apply_on_subgoal subgoal subgoal_count ^
blanchet@40723
   577
                            command_call method (map fst other_lemmas)) ^
blanchet@40723
   578
          minimize_line minimize_command
blanchet@40723
   579
                        (map fst (other_lemmas @ chained_lemmas))
blanchet@40666
   580
        end
blanchet@40669
   581
      | SOME failure => string_for_failure "SMT solver" failure
blanchet@40063
   582
  in
blanchet@40666
   583
    {outcome = outcome, used_facts = map fst used_facts,
blanchet@40204
   584
     run_time_in_msecs = run_time_in_msecs, message = message}
blanchet@40063
   585
  end
blanchet@40063
   586
blanchet@40941
   587
fun get_prover ctxt auto name =
blanchet@40941
   588
  let val thy = ProofContext.theory_of ctxt in
blanchet@40941
   589
    if is_smt_prover ctxt name then
blanchet@40941
   590
      run_smt_solver auto name
blanchet@40941
   591
    else if member (op =) (available_atps thy) name then
blanchet@40941
   592
      run_atp auto name (get_atp thy name)
blanchet@40941
   593
    else
blanchet@40941
   594
      error ("No such prover: " ^ name ^ ".")
blanchet@40941
   595
  end
blanchet@40063
   596
blanchet@40063
   597
fun run_prover (params as {blocking, debug, max_relevant, timeout, expect, ...})
blanchet@40065
   598
               auto minimize_command
blanchet@40204
   599
               (problem as {state, goal, subgoal, subgoal_count, facts, ...})
blanchet@40063
   600
               name =
blanchet@40063
   601
  let
blanchet@39318
   602
    val ctxt = Proof.context_of state
blanchet@37584
   603
    val birth_time = Time.now ()
blanchet@37584
   604
    val death_time = Time.+ (birth_time, timeout)
blanchet@40063
   605
    val max_relevant =
blanchet@40941
   606
      the_default (default_max_relevant_for_prover ctxt name) max_relevant
blanchet@40204
   607
    val num_facts = Int.min (length facts, max_relevant)
blanchet@40065
   608
    val desc =
blanchet@40204
   609
      prover_description ctxt params name num_facts subgoal subgoal_count goal
blanchet@40941
   610
    val prover = get_prover ctxt auto name
blanchet@39318
   611
    fun go () =
blanchet@38982
   612
      let
blanchet@39453
   613
        fun really_go () =
blanchet@40941
   614
          prover params (minimize_command name) problem
blanchet@38985
   615
          |> (fn {outcome, message, ...} =>
blanchet@38985
   616
                 (if is_some outcome then "none" else "some", message))
blanchet@39453
   617
        val (outcome_code, message) =
blanchet@39453
   618
          if debug then
blanchet@39453
   619
            really_go ()
blanchet@39453
   620
          else
blanchet@39453
   621
            (really_go ()
blanchet@39453
   622
             handle ERROR message => ("unknown", "Error: " ^ message ^ "\n")
blanchet@40978
   623
                  | exn =>
blanchet@40978
   624
                    if Exn.is_interrupt exn then
blanchet@40978
   625
                      reraise exn
blanchet@40978
   626
                    else
blanchet@40978
   627
                      ("unknown", "Internal error:\n" ^
blanchet@40978
   628
                                  ML_Compiler.exn_message exn ^ "\n"))
blanchet@39318
   629
        val _ =
blanchet@39318
   630
          if expect = "" orelse outcome_code = expect then
blanchet@39318
   631
            ()
blanchet@39318
   632
          else if blocking then
blanchet@39318
   633
            error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
blanchet@39318
   634
          else
blanchet@39318
   635
            warning ("Unexpected outcome: " ^ quote outcome_code ^ ".");
blanchet@39318
   636
      in (outcome_code = "some", message) end
blanchet@39318
   637
  in
blanchet@39318
   638
    if auto then
blanchet@39318
   639
      let val (success, message) = TimeLimit.timeLimit timeout go () in
blanchet@39318
   640
        (success, state |> success ? Proof.goal_message (fn () =>
blanchet@39318
   641
             Pretty.chunks [Pretty.str "", Pretty.mark Markup.hilite
blanchet@39327
   642
                 (Pretty.str message)]))
blanchet@38982
   643
      end
blanchet@39318
   644
    else if blocking then
blanchet@39318
   645
      let val (success, message) = TimeLimit.timeLimit timeout go () in
wenzelm@40132
   646
        List.app Output.urgent_message
blanchet@39370
   647
                 (Async_Manager.break_into_chunks [desc ^ "\n" ^ message]);
blanchet@39370
   648
        (success, state)
blanchet@39318
   649
      end
blanchet@39318
   650
    else
blanchet@39318
   651
      (Async_Manager.launch das_Tool birth_time death_time desc (snd o go);
blanchet@39318
   652
       (false, state))
blanchet@37584
   653
  end
wenzelm@28582
   654
blanchet@40205
   655
fun run_sledgehammer (params as {blocking, debug, provers, full_types,
blanchet@40069
   656
                                 relevance_thresholds, max_relevant, ...})
blanchet@39366
   657
                     auto i (relevance_override as {only, ...}) minimize_command
blanchet@39366
   658
                     state =
blanchet@40059
   659
  if null provers then
blanchet@40059
   660
    error "No prover is set."
blanchet@39318
   661
  else case subgoal_count state of
wenzelm@40132
   662
    0 => (Output.urgent_message "No subgoal!"; (false, state))
blanchet@39318
   663
  | n =>
blanchet@39318
   664
    let
blanchet@39364
   665
      val _ = Proof.assert_backward state
blanchet@40200
   666
      val ctxt = Proof.context_of state
blanchet@40200
   667
      val {facts = chained_ths, goal, ...} = Proof.goal state
blanchet@40060
   668
      val (_, hyp_ts, concl_t) = strip_subgoal goal i
blanchet@40059
   669
      val _ = () |> not blocking ? kill_provers
blanchet@40941
   670
      val _ = case find_first (not o is_prover_available ctxt) provers of
blanchet@40941
   671
                SOME name => error ("No such prover: " ^ name ^ ".")
blanchet@40941
   672
              | NONE => ()
wenzelm@40132
   673
      val _ = if auto then () else Output.urgent_message "Sledgehammering..."
blanchet@40941
   674
      val (smts, atps) = provers |> List.partition (is_smt_prover ctxt)
blanchet@40369
   675
      fun run_provers label full_types relevance_fudge maybe_translate provers
blanchet@40369
   676
                      (res as (success, state)) =
blanchet@40065
   677
        if success orelse null provers then
blanchet@40060
   678
          res
blanchet@40060
   679
        else
blanchet@40060
   680
          let
blanchet@40060
   681
            val max_max_relevant =
blanchet@40060
   682
              case max_relevant of
blanchet@40060
   683
                SOME n => n
blanchet@40060
   684
              | NONE =>
blanchet@40941
   685
                0 |> fold (Integer.max o default_max_relevant_for_prover ctxt)
blanchet@40065
   686
                          provers
blanchet@40060
   687
                  |> auto ? (fn n => n div auto_max_relevant_divisor)
blanchet@40369
   688
            val is_built_in_const =
blanchet@40369
   689
              is_built_in_const_for_prover ctxt (hd provers)
blanchet@40204
   690
            val facts =
blanchet@40065
   691
              relevant_facts ctxt full_types relevance_thresholds
blanchet@40369
   692
                             max_max_relevant is_built_in_const relevance_fudge
blanchet@40071
   693
                             relevance_override chained_ths hyp_ts concl_t
blanchet@40114
   694
              |> map maybe_translate
blanchet@40062
   695
            val problem =
blanchet@40065
   696
              {state = state, goal = goal, subgoal = i, subgoal_count = n,
blanchet@40204
   697
               facts = facts, only = only}
blanchet@40065
   698
            val run_prover = run_prover params auto minimize_command
blanchet@40060
   699
          in
blanchet@40205
   700
            if debug then
blanchet@40370
   701
              Output.urgent_message (label ^ plural_s (length provers) ^ ": " ^
blanchet@40205
   702
                  (if null facts then
blanchet@40205
   703
                     "Found no relevant facts."
blanchet@40205
   704
                   else
blanchet@40205
   705
                     "Including (up to) " ^ string_of_int (length facts) ^
blanchet@40205
   706
                     " relevant fact" ^ plural_s (length facts) ^ ":\n" ^
blanchet@40205
   707
                     (facts |> map_filter fact_name
blanchet@40205
   708
                            |> space_implode " ") ^ "."))
blanchet@40205
   709
            else
blanchet@40205
   710
              ();
blanchet@40060
   711
            if auto then
blanchet@40061
   712
              fold (fn prover => fn (true, state) => (true, state)
blanchet@40064
   713
                                  | (false, _) => run_prover problem prover)
blanchet@40065
   714
                   provers (false, state)
blanchet@40060
   715
            else
blanchet@40065
   716
              provers |> (if blocking then Par_List.map else map)
blanchet@40065
   717
                             (run_prover problem)
blanchet@40065
   718
                      |> exists fst |> rpair state
blanchet@40060
   719
          end
blanchet@40071
   720
      val run_atps =
blanchet@40370
   721
        run_provers "ATP" full_types atp_relevance_fudge
blanchet@40204
   722
                    (Translated o translate_fact ctxt) atps
blanchet@40071
   723
      val run_smts =
blanchet@40370
   724
        run_provers "SMT solver" true smt_relevance_fudge Untranslated smts
blanchet@40060
   725
      fun run_atps_and_smt_solvers () =
blanchet@40065
   726
        [run_atps, run_smts] |> Par_List.map (fn f => f (false, state) |> K ())
blanchet@40060
   727
    in
blanchet@40065
   728
      (false, state)
blanchet@40065
   729
      |> (if blocking then run_atps #> not auto ? run_smts
blanchet@40065
   730
          else (fn p => Future.fork (tap run_atps_and_smt_solvers) |> K p))
blanchet@40060
   731
    end
blanchet@38044
   732
blanchet@38023
   733
val setup =
blanchet@38023
   734
  dest_dir_setup
blanchet@38023
   735
  #> problem_prefix_setup
blanchet@39003
   736
  #> measure_run_time_setup
blanchet@38023
   737
wenzelm@28582
   738
end;