src/HOL/Tools/Sledgehammer/sledgehammer.ML
author blanchet
Wed Nov 24 16:15:15 2010 +0100 (2010-11-24 ago)
changeset 40684 c7ba327eb58c
parent 40669 5c316d1327d4
child 40692 7fa054c3f810
permissions -rw-r--r--
more precise error handling in Sledgehammer/SMT for Z3 and remote SMT provers
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);
wenzelm@40627
   316
        val as_time = Scan.read Symbol.stopper time o raw_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@40669
   406
      | SOME failure => (string_for_failure "ATP" 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@40669
   412
(* "SMT_Failure.Abnormal_Termination" carries the solver's return code. Until
blanchet@40669
   413
   these are sorted out properly in the SMT module, we have to interpret these
blanchet@40669
   414
   ourselves. *)
blanchet@40684
   415
val remote_smt_failures =
blanchet@40684
   416
  [(22, CantConnect),
blanchet@40684
   417
   (127, NoPerl),
blanchet@40684
   418
   (2, NoLibwwwPerl)]
blanchet@40684
   419
val z3_failures =
blanchet@40684
   420
  [(103, MalformedInput),
blanchet@40684
   421
   (110, MalformedInput)]
blanchet@40684
   422
val unix_failures =
blanchet@40684
   423
  [(139, Crashed)]
blanchet@40684
   424
val smt_failures = remote_smt_failures @ z3_failures @ unix_failures
blanchet@40555
   425
boehmes@40424
   426
fun failure_from_smt_failure (SMT_Failure.Counterexample _) = Unprovable
boehmes@40424
   427
  | failure_from_smt_failure SMT_Failure.Time_Out = TimedOut
boehmes@40561
   428
  | failure_from_smt_failure (SMT_Failure.Abnormal_Termination code) =
blanchet@40684
   429
    (case AList.lookup (op =) smt_failures code of
blanchet@40684
   430
       SOME failure => failure
blanchet@40684
   431
     | NONE => UnknownError)
boehmes@40424
   432
  | failure_from_smt_failure SMT_Failure.Out_Of_Memory = OutOfResources
blanchet@40207
   433
  | failure_from_smt_failure _ = UnknownError
blanchet@40063
   434
blanchet@40553
   435
val smt_max_iter = 8
blanchet@40419
   436
val smt_iter_fact_divisor = 2
blanchet@40419
   437
val smt_iter_min_msecs = 5000
blanchet@40419
   438
val smt_iter_timeout_divisor = 2
blanchet@40439
   439
val smt_monomorph_limit = 4
blanchet@40409
   440
blanchet@40553
   441
fun smt_filter_loop ({debug, verbose, timeout, ...} : params) remote state i =
blanchet@40409
   442
  let
blanchet@40553
   443
    val ctxt = Proof.context_of state
blanchet@40553
   444
    fun iter timeout iter_num outcome0 msecs_so_far facts =
blanchet@40553
   445
      let
blanchet@40553
   446
        val timer = Timer.startRealTimer ()
blanchet@40553
   447
        val ms = timeout |> Time.toMilliseconds
blanchet@40553
   448
        val iter_timeout =
blanchet@40553
   449
          if iter_num < smt_max_iter then
blanchet@40553
   450
            Int.min (ms, Int.max (smt_iter_min_msecs,
blanchet@40553
   451
                                  ms div smt_iter_timeout_divisor))
blanchet@40553
   452
            |> Time.fromMilliseconds
blanchet@40553
   453
          else
blanchet@40553
   454
            timeout
blanchet@40553
   455
        val num_facts = length facts
blanchet@40553
   456
        val _ =
blanchet@40553
   457
          if verbose then
blanchet@40553
   458
            "SMT iteration with " ^ string_of_int num_facts ^ " fact" ^
blanchet@40668
   459
            plural_s num_facts ^ " for " ^ string_from_time iter_timeout ^ "..."
blanchet@40553
   460
            |> Output.urgent_message
blanchet@40553
   461
          else
blanchet@40553
   462
            ()
blanchet@40553
   463
        val {outcome, used_facts, run_time_in_msecs} =
blanchet@40553
   464
          TimeLimit.timeLimit iter_timeout
blanchet@40553
   465
              (SMT_Solver.smt_filter remote iter_timeout state facts) i
blanchet@40553
   466
          handle TimeLimit.TimeOut =>
blanchet@40553
   467
                 {outcome = SOME SMT_Failure.Time_Out, used_facts = [],
blanchet@40553
   468
                  run_time_in_msecs = NONE}
blanchet@40553
   469
        val _ =
blanchet@40553
   470
          if verbose andalso is_some outcome then
blanchet@40553
   471
            "SMT outcome: " ^ SMT_Failure.string_of_failure ctxt (the outcome)
blanchet@40553
   472
            |> Output.urgent_message
blanchet@40553
   473
          else
blanchet@40553
   474
            ()
blanchet@40553
   475
        val outcome0 = if is_none outcome0 then SOME outcome else outcome0
blanchet@40553
   476
        val msecs_so_far = int_opt_add run_time_in_msecs msecs_so_far
blanchet@40553
   477
        val too_many_facts_perhaps =
blanchet@40553
   478
          case outcome of
blanchet@40553
   479
            NONE => false
blanchet@40553
   480
          | SOME (SMT_Failure.Counterexample _) => false
blanchet@40553
   481
          | SOME SMT_Failure.Time_Out => iter_timeout <> timeout
boehmes@40561
   482
          | SOME (SMT_Failure.Abnormal_Termination code) =>
blanchet@40553
   483
            (if verbose then
blanchet@40555
   484
               "The SMT solver invoked with " ^ string_of_int num_facts ^
blanchet@40668
   485
               " fact" ^ plural_s num_facts ^ " terminated abnormally with exit\
blanchet@40668
   486
               \code " ^ string_of_int code ^ "."
blanchet@40553
   487
               |> (if debug then error else warning)
blanchet@40553
   488
             else
blanchet@40553
   489
               ();
blanchet@40553
   490
             true (* kind of *))
blanchet@40553
   491
          | SOME SMT_Failure.Out_Of_Memory => true
blanchet@40553
   492
          | SOME _ => true
blanchet@40553
   493
        val timeout = Time.- (timeout, Timer.checkRealTimer timer)
blanchet@40553
   494
      in
blanchet@40553
   495
        if too_many_facts_perhaps andalso iter_num < smt_max_iter andalso
blanchet@40553
   496
           num_facts > 0 andalso Time.> (timeout, Time.zeroTime) then
blanchet@40553
   497
          let val facts = take (num_facts div smt_iter_fact_divisor) facts in
blanchet@40553
   498
            iter timeout (iter_num + 1) outcome0 msecs_so_far facts
blanchet@40553
   499
          end
blanchet@40553
   500
        else
blanchet@40553
   501
          {outcome = if is_none outcome then NONE else the outcome0,
blanchet@40553
   502
           used_facts = used_facts, run_time_in_msecs = msecs_so_far}
blanchet@40409
   503
      end
blanchet@40553
   504
  in iter timeout 1 NONE (SOME 0) end
blanchet@40409
   505
blanchet@40666
   506
(* taken from "Mirabelle" and generalized *)
blanchet@40666
   507
fun can_apply timeout tac state i =
blanchet@40666
   508
  let
blanchet@40666
   509
    val {context = ctxt, facts, goal} = Proof.goal state
blanchet@40666
   510
    val full_tac = Method.insert_tac facts i THEN tac ctxt i
blanchet@40666
   511
  in
blanchet@40666
   512
    case try (TimeLimit.timeLimit timeout (Seq.pull o full_tac)) goal of
blanchet@40666
   513
      SOME (SOME _) => true
blanchet@40666
   514
    | _ => false
blanchet@40666
   515
  end
blanchet@40666
   516
blanchet@40666
   517
val smt_metis_timeout = seconds 0.5
blanchet@40666
   518
blanchet@40666
   519
fun can_apply_metis state i ths =
blanchet@40666
   520
  can_apply smt_metis_timeout (fn ctxt => Metis_Tactics.metis_tac ctxt ths)
blanchet@40666
   521
            state i
blanchet@40666
   522
blanchet@40553
   523
fun run_smt_solver auto remote (params as {debug, ...}) minimize_command
blanchet@40553
   524
        ({state, subgoal, subgoal_count, facts, ...} : prover_problem) =
blanchet@36379
   525
  let
blanchet@40439
   526
    val repair_context =
blanchet@40668
   527
      Config.put Metis_Tactics.verbose debug
blanchet@40668
   528
      #> Config.put SMT_Config.verbose debug
blanchet@40439
   529
      #> Config.put SMT_Config.monomorph_limit smt_monomorph_limit
blanchet@40439
   530
    val state = state |> Proof.map_context repair_context
blanchet@40668
   531
    val thy = Proof.theory_of state
blanchet@40668
   532
    val smt_fact = Option.map (apsnd (Thm.transfer thy)) o try dest_Untranslated
blanchet@40181
   533
    val {outcome, used_facts, run_time_in_msecs} =
blanchet@40668
   534
      smt_filter_loop params remote state subgoal (map_filter smt_fact facts)
blanchet@40669
   535
    val outcome = outcome |> Option.map failure_from_smt_failure
blanchet@40063
   536
    val message =
blanchet@40184
   537
      case outcome of
blanchet@40184
   538
        NONE =>
blanchet@40666
   539
        let
blanchet@40666
   540
          val method =
blanchet@40666
   541
            if can_apply_metis state subgoal (map snd used_facts) then "metis"
blanchet@40666
   542
            else "smt"
blanchet@40666
   543
        in
blanchet@40666
   544
          try_command_line (proof_banner auto)
blanchet@40666
   545
                           (apply_on_subgoal subgoal subgoal_count ^
blanchet@40666
   546
                            command_call method (map (fst o fst) used_facts)) ^
blanchet@40666
   547
          minimize_line minimize_command (map (fst o fst) used_facts)
blanchet@40666
   548
        end
blanchet@40669
   549
      | SOME failure => string_for_failure "SMT solver" failure
blanchet@40063
   550
  in
blanchet@40666
   551
    {outcome = outcome, used_facts = map fst used_facts,
blanchet@40204
   552
     run_time_in_msecs = run_time_in_msecs, message = message}
blanchet@40063
   553
  end
blanchet@40063
   554
blanchet@40200
   555
fun get_prover thy auto name =
blanchet@40224
   556
  if is_smt_prover name then
blanchet@40224
   557
    run_smt_solver auto (String.isPrefix remote_prefix name)
blanchet@40224
   558
  else
blanchet@40224
   559
    run_atp auto name (get_atp thy name)
blanchet@40063
   560
blanchet@40063
   561
fun run_prover (params as {blocking, debug, max_relevant, timeout, expect, ...})
blanchet@40065
   562
               auto minimize_command
blanchet@40204
   563
               (problem as {state, goal, subgoal, subgoal_count, facts, ...})
blanchet@40063
   564
               name =
blanchet@40063
   565
  let
blanchet@40063
   566
    val thy = Proof.theory_of state
blanchet@39318
   567
    val ctxt = Proof.context_of state
blanchet@37584
   568
    val birth_time = Time.now ()
blanchet@37584
   569
    val death_time = Time.+ (birth_time, timeout)
blanchet@40063
   570
    val max_relevant =
blanchet@40063
   571
      the_default (default_max_relevant_for_prover thy name) max_relevant
blanchet@40204
   572
    val num_facts = Int.min (length facts, max_relevant)
blanchet@40065
   573
    val desc =
blanchet@40204
   574
      prover_description ctxt params name num_facts subgoal subgoal_count goal
blanchet@39318
   575
    fun go () =
blanchet@38982
   576
      let
blanchet@39453
   577
        fun really_go () =
blanchet@40200
   578
          get_prover thy auto name params (minimize_command name) problem
blanchet@38985
   579
          |> (fn {outcome, message, ...} =>
blanchet@38985
   580
                 (if is_some outcome then "none" else "some", message))
blanchet@39453
   581
        val (outcome_code, message) =
blanchet@39453
   582
          if debug then
blanchet@39453
   583
            really_go ()
blanchet@39453
   584
          else
blanchet@39453
   585
            (really_go ()
blanchet@39453
   586
             handle ERROR message => ("unknown", "Error: " ^ message ^ "\n")
blanchet@39453
   587
                  | exn => ("unknown", "Internal error:\n" ^
blanchet@39453
   588
                                       ML_Compiler.exn_message exn ^ "\n"))
blanchet@39318
   589
        val _ =
blanchet@39318
   590
          if expect = "" orelse outcome_code = expect then
blanchet@39318
   591
            ()
blanchet@39318
   592
          else if blocking then
blanchet@39318
   593
            error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
blanchet@39318
   594
          else
blanchet@39318
   595
            warning ("Unexpected outcome: " ^ quote outcome_code ^ ".");
blanchet@39318
   596
      in (outcome_code = "some", message) end
blanchet@39318
   597
  in
blanchet@39318
   598
    if auto then
blanchet@39318
   599
      let val (success, message) = TimeLimit.timeLimit timeout go () in
blanchet@39318
   600
        (success, state |> success ? Proof.goal_message (fn () =>
blanchet@39318
   601
             Pretty.chunks [Pretty.str "", Pretty.mark Markup.hilite
blanchet@39327
   602
                 (Pretty.str message)]))
blanchet@38982
   603
      end
blanchet@39318
   604
    else if blocking then
blanchet@39318
   605
      let val (success, message) = TimeLimit.timeLimit timeout go () in
wenzelm@40132
   606
        List.app Output.urgent_message
blanchet@39370
   607
                 (Async_Manager.break_into_chunks [desc ^ "\n" ^ message]);
blanchet@39370
   608
        (success, state)
blanchet@39318
   609
      end
blanchet@39318
   610
    else
blanchet@39318
   611
      (Async_Manager.launch das_Tool birth_time death_time desc (snd o go);
blanchet@39318
   612
       (false, state))
blanchet@37584
   613
  end
wenzelm@28582
   614
blanchet@40205
   615
fun run_sledgehammer (params as {blocking, debug, provers, full_types,
blanchet@40069
   616
                                 relevance_thresholds, max_relevant, ...})
blanchet@39366
   617
                     auto i (relevance_override as {only, ...}) minimize_command
blanchet@39366
   618
                     state =
blanchet@40059
   619
  if null provers then
blanchet@40059
   620
    error "No prover is set."
blanchet@39318
   621
  else case subgoal_count state of
wenzelm@40132
   622
    0 => (Output.urgent_message "No subgoal!"; (false, state))
blanchet@39318
   623
  | n =>
blanchet@39318
   624
    let
blanchet@39364
   625
      val _ = Proof.assert_backward state
blanchet@39318
   626
      val thy = Proof.theory_of state
blanchet@40200
   627
      val ctxt = Proof.context_of state
blanchet@40200
   628
      val {facts = chained_ths, goal, ...} = Proof.goal state
blanchet@40060
   629
      val (_, hyp_ts, concl_t) = strip_subgoal goal i
blanchet@40059
   630
      val _ = () |> not blocking ? kill_provers
wenzelm@40132
   631
      val _ = if auto then () else Output.urgent_message "Sledgehammering..."
blanchet@40070
   632
      val (smts, atps) = provers |> List.partition is_smt_prover
blanchet@40369
   633
      fun run_provers label full_types relevance_fudge maybe_translate provers
blanchet@40369
   634
                      (res as (success, state)) =
blanchet@40065
   635
        if success orelse null provers then
blanchet@40060
   636
          res
blanchet@40060
   637
        else
blanchet@40060
   638
          let
blanchet@40060
   639
            val max_max_relevant =
blanchet@40060
   640
              case max_relevant of
blanchet@40060
   641
                SOME n => n
blanchet@40060
   642
              | NONE =>
blanchet@40063
   643
                0 |> fold (Integer.max o default_max_relevant_for_prover thy)
blanchet@40065
   644
                          provers
blanchet@40060
   645
                  |> auto ? (fn n => n div auto_max_relevant_divisor)
blanchet@40369
   646
            val is_built_in_const =
blanchet@40369
   647
              is_built_in_const_for_prover ctxt (hd provers)
blanchet@40204
   648
            val facts =
blanchet@40065
   649
              relevant_facts ctxt full_types relevance_thresholds
blanchet@40369
   650
                             max_max_relevant is_built_in_const relevance_fudge
blanchet@40071
   651
                             relevance_override chained_ths hyp_ts concl_t
blanchet@40114
   652
              |> map maybe_translate
blanchet@40062
   653
            val problem =
blanchet@40065
   654
              {state = state, goal = goal, subgoal = i, subgoal_count = n,
blanchet@40204
   655
               facts = facts, only = only}
blanchet@40065
   656
            val run_prover = run_prover params auto minimize_command
blanchet@40060
   657
          in
blanchet@40205
   658
            if debug then
blanchet@40370
   659
              Output.urgent_message (label ^ plural_s (length provers) ^ ": " ^
blanchet@40205
   660
                  (if null facts then
blanchet@40205
   661
                     "Found no relevant facts."
blanchet@40205
   662
                   else
blanchet@40205
   663
                     "Including (up to) " ^ string_of_int (length facts) ^
blanchet@40205
   664
                     " relevant fact" ^ plural_s (length facts) ^ ":\n" ^
blanchet@40205
   665
                     (facts |> map_filter fact_name
blanchet@40205
   666
                            |> space_implode " ") ^ "."))
blanchet@40205
   667
            else
blanchet@40205
   668
              ();
blanchet@40060
   669
            if auto then
blanchet@40061
   670
              fold (fn prover => fn (true, state) => (true, state)
blanchet@40064
   671
                                  | (false, _) => run_prover problem prover)
blanchet@40065
   672
                   provers (false, state)
blanchet@40060
   673
            else
blanchet@40065
   674
              provers |> (if blocking then Par_List.map else map)
blanchet@40065
   675
                             (run_prover problem)
blanchet@40065
   676
                      |> exists fst |> rpair state
blanchet@40060
   677
          end
blanchet@40071
   678
      val run_atps =
blanchet@40370
   679
        run_provers "ATP" full_types atp_relevance_fudge
blanchet@40204
   680
                    (Translated o translate_fact ctxt) atps
blanchet@40071
   681
      val run_smts =
blanchet@40370
   682
        run_provers "SMT solver" true smt_relevance_fudge Untranslated smts
blanchet@40060
   683
      fun run_atps_and_smt_solvers () =
blanchet@40065
   684
        [run_atps, run_smts] |> Par_List.map (fn f => f (false, state) |> K ())
blanchet@40060
   685
    in
blanchet@40065
   686
      (false, state)
blanchet@40065
   687
      |> (if blocking then run_atps #> not auto ? run_smts
blanchet@40065
   688
          else (fn p => Future.fork (tap run_atps_and_smt_solvers) |> K p))
blanchet@40060
   689
    end
blanchet@38044
   690
blanchet@38023
   691
val setup =
blanchet@38023
   692
  dest_dir_setup
blanchet@38023
   693
  #> problem_prefix_setup
blanchet@39003
   694
  #> measure_run_time_setup
blanchet@38023
   695
wenzelm@28582
   696
end;