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