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