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