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