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