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