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