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