src/HOL/Tools/Sledgehammer/sledgehammer_provers.ML
author blanchet
Mon May 30 17:00:38 2011 +0200 (2011-05-30 ago)
changeset 43051 d7075adac3bd
parent 43050 59284a13abc4
child 43052 8d6a4978cc65
permissions -rw-r--r--
minimize with Metis if possible
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@43021
    18
  datatype mode = Auto_Try | Try | Normal | Minimize
blanchet@43021
    19
blanchet@42579
    20
  datatype rich_type_system =
blanchet@42579
    21
    Dumb_Type_Sys of type_system |
blanchet@42579
    22
    Smart_Type_Sys of bool
blanchet@42579
    23
blanchet@35969
    24
  type params =
blanchet@41208
    25
    {debug: bool,
blanchet@35969
    26
     verbose: bool,
blanchet@36143
    27
     overlord: bool,
blanchet@41208
    28
     blocking: bool,
blanchet@40059
    29
     provers: string list,
blanchet@42579
    30
     type_sys: rich_type_system,
blanchet@42180
    31
     relevance_thresholds: real * real,
blanchet@42180
    32
     max_relevant: int option,
blanchet@42724
    33
     max_mono_iters: int,
blanchet@42740
    34
     max_new_mono_instances: int,
blanchet@36235
    35
     explicit_apply: bool,
blanchet@35969
    36
     isar_proof: bool,
blanchet@36924
    37
     isar_shrink_factor: int,
blanchet@42443
    38
     slicing: bool,
blanchet@38985
    39
     timeout: Time.time,
blanchet@43015
    40
     preplay_timeout: Time.time,
blanchet@38985
    41
     expect: string}
blanchet@39493
    42
blanchet@41090
    43
  datatype prover_fact =
blanchet@41090
    44
    Untranslated_Fact of (string * locality) * thm |
blanchet@41242
    45
    SMT_Weighted_Fact of (string * locality) * (int option * thm)
blanchet@40061
    46
blanchet@40061
    47
  type prover_problem =
blanchet@39318
    48
    {state: Proof.state,
blanchet@38998
    49
     goal: thm,
blanchet@38998
    50
     subgoal: int,
blanchet@40065
    51
     subgoal_count: int,
blanchet@41242
    52
     facts: prover_fact list,
blanchet@41741
    53
     smt_filter: (string * locality) SMT_Solver.smt_filter_data option}
blanchet@39493
    54
blanchet@40061
    55
  type prover_result =
blanchet@36370
    56
    {outcome: failure option,
blanchet@40204
    57
     used_facts: (string * locality) list,
blanchet@40062
    58
     run_time_in_msecs: int option,
blanchet@40062
    59
     message: string}
blanchet@39493
    60
blanchet@43051
    61
  type prover =
blanchet@43051
    62
    params -> (string -> minimize_command) -> prover_problem -> prover_result
blanchet@35867
    63
blanchet@42646
    64
  val smt_triggers : bool Config.T
blanchet@42646
    65
  val smt_weights : bool Config.T
blanchet@42646
    66
  val smt_weight_min_facts : int Config.T
blanchet@42646
    67
  val smt_min_weight : int Config.T
blanchet@42646
    68
  val smt_max_weight : int Config.T
blanchet@42646
    69
  val smt_max_weight_index : int Config.T
blanchet@41256
    70
  val smt_weight_curve : (int -> int) Unsynchronized.ref
blanchet@42646
    71
  val smt_max_slices : int Config.T
blanchet@42646
    72
  val smt_slice_fact_frac : real Config.T
blanchet@42646
    73
  val smt_slice_time_frac : real Config.T
blanchet@42646
    74
  val smt_slice_min_secs : int Config.T
blanchet@43005
    75
  val das_tool : string
blanchet@41242
    76
  val select_smt_solver : string -> Proof.context -> Proof.context
blanchet@43050
    77
  val is_metis_prover : string -> bool
blanchet@43050
    78
  val is_atp : theory -> string -> bool
blanchet@41087
    79
  val is_smt_prover : Proof.context -> string -> bool
blanchet@42944
    80
  val is_unit_equational_atp : Proof.context -> string -> bool
blanchet@41727
    81
  val is_prover_supported : Proof.context -> string -> bool
blanchet@40072
    82
  val is_prover_installed : Proof.context -> string -> bool
blanchet@42443
    83
  val default_max_relevant_for_prover : Proof.context -> bool -> string -> int
blanchet@42944
    84
  val is_unit_equality : term -> bool
blanchet@42952
    85
  val is_appropriate_prop_for_prover : Proof.context -> string -> term -> bool
blanchet@40369
    86
  val is_built_in_const_for_prover :
blanchet@41336
    87
    Proof.context -> string -> string * typ -> term list -> bool * term list
blanchet@41087
    88
  val atp_relevance_fudge : relevance_fudge
blanchet@41087
    89
  val smt_relevance_fudge : relevance_fudge
blanchet@40941
    90
  val relevance_fudge_for_prover : Proof.context -> string -> relevance_fudge
blanchet@38023
    91
  val dest_dir : string Config.T
blanchet@38023
    92
  val problem_prefix : string Config.T
blanchet@39003
    93
  val measure_run_time : bool Config.T
blanchet@41256
    94
  val weight_smt_fact :
blanchet@42646
    95
    Proof.context -> int -> ((string * locality) * thm) * int
blanchet@41256
    96
    -> (string * locality) * (int option * thm)
blanchet@41091
    97
  val untranslated_fact : prover_fact -> (string * locality) * thm
blanchet@41242
    98
  val smt_weighted_fact :
blanchet@42646
    99
    Proof.context -> int -> prover_fact * int
blanchet@41256
   100
    -> (string * locality) * (int option * thm)
blanchet@41727
   101
  val supported_provers : Proof.context -> unit
blanchet@40059
   102
  val kill_provers : unit -> unit
blanchet@40059
   103
  val running_provers : unit -> unit
blanchet@40059
   104
  val messages : int option -> unit
blanchet@43033
   105
  val filter_used_facts : ''a list -> (''a * 'b) list -> (''a * 'b) list
blanchet@43021
   106
  val get_prover : Proof.context -> mode -> string -> prover
wenzelm@28477
   107
end;
wenzelm@28477
   108
blanchet@41087
   109
structure Sledgehammer_Provers : SLEDGEHAMMER_PROVERS =
wenzelm@28477
   110
struct
wenzelm@28477
   111
blanchet@38028
   112
open ATP_Problem
blanchet@39491
   113
open ATP_Proof
blanchet@38028
   114
open ATP_Systems
blanchet@39494
   115
open Metis_Translate
blanchet@38023
   116
open Sledgehammer_Util
blanchet@38988
   117
open Sledgehammer_Filter
blanchet@40068
   118
open Sledgehammer_ATP_Translate
blanchet@40068
   119
open Sledgehammer_ATP_Reconstruct
blanchet@37583
   120
blanchet@37583
   121
(** The Sledgehammer **)
blanchet@37583
   122
blanchet@43021
   123
datatype mode = Auto_Try | Try | Normal | Minimize
blanchet@43021
   124
blanchet@38102
   125
(* Identifier to distinguish Sledgehammer from other tools using
blanchet@38102
   126
   "Async_Manager". *)
blanchet@43005
   127
val das_tool = "Sledgehammer"
blanchet@37585
   128
blanchet@43050
   129
val metis_prover_names = [Metis_Tactics.metisN, Metis_Tactics.metisFT_N]
blanchet@43050
   130
blanchet@43050
   131
val is_metis_prover = member (op =) metis_prover_names
blanchet@43050
   132
val is_atp = member (op =) o supported_atps
blanchet@43050
   133
blanchet@41242
   134
val select_smt_solver =
boehmes@41432
   135
  Context.proof_map o SMT_Config.select_solver
blanchet@41242
   136
blanchet@40941
   137
fun is_smt_prover ctxt name =
boehmes@41432
   138
  member (op =) (SMT_Solver.available_solvers_of ctxt) name
blanchet@40062
   139
blanchet@42944
   140
fun is_unit_equational_atp ctxt name =
blanchet@42944
   141
  let val thy = Proof_Context.theory_of ctxt in
blanchet@42944
   142
    case try (get_atp thy) name of
blanchet@42944
   143
      SOME {formats, ...} => member (op =) formats CNF_UEQ
blanchet@42944
   144
    | NONE => false
blanchet@42944
   145
  end
blanchet@42944
   146
blanchet@41727
   147
fun is_prover_supported ctxt name =
wenzelm@42361
   148
  let val thy = Proof_Context.theory_of ctxt in
blanchet@43050
   149
    is_metis_prover name orelse is_atp thy name orelse is_smt_prover ctxt name
blanchet@40941
   150
  end
blanchet@40072
   151
boehmes@41432
   152
fun is_prover_installed ctxt =
blanchet@43050
   153
  is_metis_prover orf is_smt_prover ctxt orf
blanchet@43050
   154
  is_atp_installed (Proof_Context.theory_of ctxt)
blanchet@40941
   155
blanchet@42443
   156
fun get_slices slicing slices =
blanchet@42447
   157
  (0 upto length slices - 1) ~~ slices |> not slicing ? (List.last #> single)
blanchet@42443
   158
blanchet@43050
   159
val metis_default_max_relevant = 20
blanchet@43050
   160
blanchet@42443
   161
fun default_max_relevant_for_prover ctxt slicing name =
wenzelm@42361
   162
  let val thy = Proof_Context.theory_of ctxt in
blanchet@43050
   163
    if is_metis_prover name then
blanchet@43050
   164
      metis_default_max_relevant
blanchet@43050
   165
    else if is_atp thy name then
blanchet@42723
   166
      fold (Integer.max o fst o snd o snd o snd)
blanchet@42646
   167
           (get_slices slicing (#best_slices (get_atp thy name) ctxt)) 0
blanchet@43050
   168
    else (* is_smt_prover ctxt name *)
blanchet@43050
   169
      SMT_Solver.default_max_relevant ctxt name
blanchet@40941
   170
  end
blanchet@40063
   171
blanchet@41140
   172
(* These are either simplified away by "Meson.presimplify" (most of the time) or
blanchet@41140
   173
   handled specially via "fFalse", "fTrue", ..., "fequal". *)
blanchet@40071
   174
val atp_irrelevant_consts =
blanchet@41140
   175
  [@{const_name False}, @{const_name True}, @{const_name Not},
blanchet@41140
   176
   @{const_name conj}, @{const_name disj}, @{const_name implies},
blanchet@41140
   177
   @{const_name HOL.eq}, @{const_name If}, @{const_name Let}]
blanchet@40206
   178
blanchet@42956
   179
fun is_if (@{const_name If}, _) = true
blanchet@42956
   180
  | is_if _ = false
blanchet@42956
   181
blanchet@42956
   182
(* Beware of "if and only if" (which is translated as such) and "If" (which is
blanchet@42956
   183
   translated to conditional equations). *)
blanchet@42956
   184
fun is_good_unit_equality T t u =
blanchet@42956
   185
  T <> @{typ bool} andalso not (exists (exists_Const is_if) [t, u])
blanchet@42956
   186
blanchet@42944
   187
fun is_unit_equality (@{const Trueprop} $ t) = is_unit_equality t
blanchet@42944
   188
  | is_unit_equality (Const (@{const_name all}, _) $ Abs (_, _, t)) =
blanchet@42944
   189
    is_unit_equality t
blanchet@42944
   190
  | is_unit_equality (Const (@{const_name All}, _) $ Abs (_, _, t)) =
blanchet@42944
   191
    is_unit_equality t
blanchet@42956
   192
  | is_unit_equality (Const (@{const_name "=="}, Type (_, [T, _])) $ t $ u) =
blanchet@42956
   193
    is_good_unit_equality T t u
blanchet@42956
   194
  | is_unit_equality (Const (@{const_name HOL.eq}, Type (_ , [T, _])) $ t $ u) =
blanchet@42956
   195
    is_good_unit_equality T t u
blanchet@42944
   196
  | is_unit_equality _ = false
blanchet@42944
   197
blanchet@42952
   198
fun is_appropriate_prop_for_prover ctxt name =
blanchet@42944
   199
  if is_unit_equational_atp ctxt name then is_unit_equality else K true
blanchet@42944
   200
blanchet@41242
   201
fun is_built_in_const_for_prover ctxt name =
blanchet@41242
   202
  if is_smt_prover ctxt name then
blanchet@41336
   203
    let val ctxt = ctxt |> select_smt_solver name in
blanchet@41336
   204
      fn x => fn ts =>
blanchet@41336
   205
         if SMT_Builtin.is_builtin_num_ext ctxt (list_comb (Const x, ts)) then
blanchet@41336
   206
           (true, [])
blanchet@41336
   207
         else if SMT_Builtin.is_builtin_fun_ext ctxt x ts then
blanchet@41336
   208
           (true, ts)
blanchet@41336
   209
         else
blanchet@41336
   210
           (false, ts)
blanchet@41336
   211
    end
blanchet@41242
   212
  else
blanchet@41336
   213
    fn (s, _) => fn ts => (member (op =) atp_irrelevant_consts s, ts)
blanchet@40071
   214
blanchet@40070
   215
(* FUDGE *)
blanchet@40070
   216
val atp_relevance_fudge =
blanchet@42738
   217
  {local_const_multiplier = 1.5,
blanchet@41159
   218
   worse_irrel_freq = 100.0,
blanchet@40070
   219
   higher_order_irrel_weight = 1.05,
blanchet@40070
   220
   abs_rel_weight = 0.5,
blanchet@40070
   221
   abs_irrel_weight = 2.0,
blanchet@42746
   222
   skolem_irrel_weight = 0.25,
blanchet@40070
   223
   theory_const_rel_weight = 0.5,
blanchet@40070
   224
   theory_const_irrel_weight = 0.25,
blanchet@42735
   225
   chained_const_irrel_weight = 0.25,
blanchet@40070
   226
   intro_bonus = 0.15,
blanchet@40070
   227
   elim_bonus = 0.15,
blanchet@40070
   228
   simp_bonus = 0.15,
blanchet@40070
   229
   local_bonus = 0.55,
blanchet@40070
   230
   assum_bonus = 1.05,
blanchet@40070
   231
   chained_bonus = 1.5,
blanchet@40070
   232
   max_imperfect = 11.5,
blanchet@40070
   233
   max_imperfect_exp = 1.0,
blanchet@40070
   234
   threshold_divisor = 2.0,
blanchet@41093
   235
   ridiculous_threshold = 0.01}
blanchet@40070
   236
blanchet@40071
   237
(* FUDGE (FIXME) *)
blanchet@40070
   238
val smt_relevance_fudge =
blanchet@42738
   239
  {local_const_multiplier = #local_const_multiplier atp_relevance_fudge,
blanchet@41159
   240
   worse_irrel_freq = #worse_irrel_freq atp_relevance_fudge,
blanchet@40071
   241
   higher_order_irrel_weight = #higher_order_irrel_weight atp_relevance_fudge,
blanchet@40071
   242
   abs_rel_weight = #abs_rel_weight atp_relevance_fudge,
blanchet@40071
   243
   abs_irrel_weight = #abs_irrel_weight atp_relevance_fudge,
blanchet@40071
   244
   skolem_irrel_weight = #skolem_irrel_weight atp_relevance_fudge,
blanchet@40071
   245
   theory_const_rel_weight = #theory_const_rel_weight atp_relevance_fudge,
blanchet@40071
   246
   theory_const_irrel_weight = #theory_const_irrel_weight atp_relevance_fudge,
blanchet@42735
   247
   chained_const_irrel_weight = #chained_const_irrel_weight atp_relevance_fudge,
blanchet@40071
   248
   intro_bonus = #intro_bonus atp_relevance_fudge,
blanchet@40071
   249
   elim_bonus = #elim_bonus atp_relevance_fudge,
blanchet@40071
   250
   simp_bonus = #simp_bonus atp_relevance_fudge,
blanchet@40071
   251
   local_bonus = #local_bonus atp_relevance_fudge,
blanchet@40071
   252
   assum_bonus = #assum_bonus atp_relevance_fudge,
blanchet@40071
   253
   chained_bonus = #chained_bonus atp_relevance_fudge,
blanchet@40071
   254
   max_imperfect = #max_imperfect atp_relevance_fudge,
blanchet@40071
   255
   max_imperfect_exp = #max_imperfect_exp atp_relevance_fudge,
blanchet@40071
   256
   threshold_divisor = #threshold_divisor atp_relevance_fudge,
blanchet@40071
   257
   ridiculous_threshold = #ridiculous_threshold atp_relevance_fudge}
blanchet@40070
   258
blanchet@40941
   259
fun relevance_fudge_for_prover ctxt name =
blanchet@40941
   260
  if is_smt_prover ctxt name then smt_relevance_fudge else atp_relevance_fudge
blanchet@40070
   261
blanchet@41727
   262
fun supported_provers ctxt =
blanchet@40060
   263
  let
wenzelm@42361
   264
    val thy = Proof_Context.theory_of ctxt
blanchet@40060
   265
    val (remote_provers, local_provers) =
blanchet@43050
   266
      metis_prover_names @
blanchet@41727
   267
      sort_strings (supported_atps thy) @
blanchet@41727
   268
      sort_strings (SMT_Solver.available_solvers_of ctxt)
blanchet@40060
   269
      |> List.partition (String.isPrefix remote_prefix)
blanchet@40060
   270
  in
blanchet@41727
   271
    Output.urgent_message ("Supported provers: " ^
blanchet@40205
   272
                           commas (local_provers @ remote_provers) ^ ".")
blanchet@40060
   273
  end
blanchet@35969
   274
blanchet@43005
   275
fun kill_provers () = Async_Manager.kill_threads das_tool "prover"
blanchet@43005
   276
fun running_provers () = Async_Manager.running_threads das_tool "prover"
blanchet@43005
   277
val messages = Async_Manager.thread_messages das_tool "prover"
blanchet@40059
   278
blanchet@40059
   279
(** problems, results, ATPs, etc. **)
blanchet@35969
   280
blanchet@42579
   281
datatype rich_type_system =
blanchet@42579
   282
  Dumb_Type_Sys of type_system |
blanchet@42579
   283
  Smart_Type_Sys of bool
blanchet@42579
   284
blanchet@35969
   285
type params =
blanchet@41208
   286
  {debug: bool,
blanchet@35969
   287
   verbose: bool,
blanchet@36143
   288
   overlord: bool,
blanchet@41208
   289
   blocking: bool,
blanchet@40059
   290
   provers: string list,
blanchet@42579
   291
   type_sys: rich_type_system,
blanchet@42180
   292
   relevance_thresholds: real * real,
blanchet@42180
   293
   max_relevant: int option,
blanchet@42724
   294
   max_mono_iters: int,
blanchet@42740
   295
   max_new_mono_instances: int,
blanchet@36235
   296
   explicit_apply: bool,
blanchet@35969
   297
   isar_proof: bool,
blanchet@36924
   298
   isar_shrink_factor: int,
blanchet@42443
   299
   slicing: bool,
blanchet@38985
   300
   timeout: Time.time,
blanchet@43015
   301
   preplay_timeout: Time.time,
blanchet@38985
   302
   expect: string}
blanchet@35867
   303
blanchet@41090
   304
datatype prover_fact =
blanchet@41090
   305
  Untranslated_Fact of (string * locality) * thm |
blanchet@41242
   306
  SMT_Weighted_Fact of (string * locality) * (int option * thm)
blanchet@40061
   307
blanchet@40061
   308
type prover_problem =
blanchet@39318
   309
  {state: Proof.state,
blanchet@38998
   310
   goal: thm,
blanchet@38998
   311
   subgoal: int,
blanchet@40065
   312
   subgoal_count: int,
blanchet@41242
   313
   facts: prover_fact list,
blanchet@41741
   314
   smt_filter: (string * locality) SMT_Solver.smt_filter_data option}
blanchet@35867
   315
blanchet@40061
   316
type prover_result =
blanchet@36370
   317
  {outcome: failure option,
blanchet@35969
   318
   message: string,
blanchet@40204
   319
   used_facts: (string * locality) list,
blanchet@40062
   320
   run_time_in_msecs: int option}
blanchet@35867
   321
blanchet@43051
   322
type prover =
blanchet@43051
   323
  params -> (string -> minimize_command) -> prover_problem -> prover_result
blanchet@35867
   324
blanchet@43033
   325
blanchet@38023
   326
(* configuration attributes *)
blanchet@38023
   327
wenzelm@42616
   328
val dest_dir =
wenzelm@42616
   329
  Attrib.setup_config_string @{binding sledgehammer_dest_dir} (K "")
blanchet@38991
   330
  (* Empty string means create files in Isabelle's temporary files directory. *)
blanchet@38023
   331
wenzelm@42616
   332
val problem_prefix =
wenzelm@42616
   333
  Attrib.setup_config_string @{binding sledgehammer_problem_prefix} (K "prob")
blanchet@38023
   334
wenzelm@42616
   335
val measure_run_time =
wenzelm@42616
   336
  Attrib.setup_config_bool @{binding sledgehammer_measure_run_time} (K false)
wenzelm@28484
   337
blanchet@42646
   338
val smt_triggers =
blanchet@42646
   339
  Attrib.setup_config_bool @{binding sledgehammer_smt_triggers} (K true)
blanchet@42646
   340
val smt_weights =
blanchet@42646
   341
  Attrib.setup_config_bool @{binding sledgehammer_smt_weights} (K true)
blanchet@42646
   342
val smt_weight_min_facts =
blanchet@42646
   343
  Attrib.setup_config_int @{binding sledgehammer_smt_weight_min_facts} (K 20)
blanchet@41256
   344
blanchet@41256
   345
(* FUDGE *)
blanchet@42646
   346
val smt_min_weight =
blanchet@42646
   347
  Attrib.setup_config_int @{binding sledgehammer_smt_min_weight} (K 0)
blanchet@42646
   348
val smt_max_weight =
blanchet@42646
   349
  Attrib.setup_config_int @{binding sledgehammer_smt_max_weight} (K 10)
blanchet@42646
   350
val smt_max_weight_index =
blanchet@42646
   351
  Attrib.setup_config_int @{binding sledgehammer_smt_max_weight_index} (K 200)
blanchet@41256
   352
val smt_weight_curve = Unsynchronized.ref (fn x : int => x * x)
blanchet@41256
   353
blanchet@42646
   354
fun smt_fact_weight ctxt j num_facts =
blanchet@42646
   355
  if Config.get ctxt smt_weights andalso
blanchet@42646
   356
     num_facts >= Config.get ctxt smt_weight_min_facts then
blanchet@42646
   357
    let
blanchet@42646
   358
      val min = Config.get ctxt smt_min_weight
blanchet@42646
   359
      val max = Config.get ctxt smt_max_weight
blanchet@42646
   360
      val max_index = Config.get ctxt smt_max_weight_index
blanchet@42646
   361
      val curve = !smt_weight_curve
blanchet@42646
   362
    in
blanchet@42646
   363
      SOME (max - (max - min + 1) * curve (Int.max (0, max_index - j - 1))
blanchet@42646
   364
            div curve max_index)
blanchet@42646
   365
    end
blanchet@41256
   366
  else
blanchet@41256
   367
    NONE
blanchet@41256
   368
blanchet@42646
   369
fun weight_smt_fact ctxt num_facts ((info, th), j) =
blanchet@42646
   370
  let val thy = Proof_Context.theory_of ctxt in
blanchet@42646
   371
    (info, (smt_fact_weight ctxt j num_facts, th |> Thm.transfer thy))
blanchet@42646
   372
  end
blanchet@38023
   373
blanchet@41091
   374
fun untranslated_fact (Untranslated_Fact p) = p
blanchet@41242
   375
  | untranslated_fact (SMT_Weighted_Fact (info, (_, th))) = (info, th)
blanchet@42994
   376
fun atp_translated_fact ctxt format type_sys fact =
blanchet@42994
   377
  translate_atp_fact ctxt format type_sys false (untranslated_fact fact)
blanchet@41256
   378
fun smt_weighted_fact _ _ (SMT_Weighted_Fact p, _) = p
blanchet@42646
   379
  | smt_weighted_fact ctxt num_facts (fact, j) =
blanchet@42646
   380
    (untranslated_fact fact, j) |> weight_smt_fact ctxt num_facts
blanchet@41256
   381
blanchet@41313
   382
fun overlord_file_location_for_prover prover =
blanchet@41313
   383
  (getenv "ISABELLE_HOME_USER", "prob_" ^ prover)
blanchet@41313
   384
blanchet@43033
   385
fun with_path cleanup after f path =
blanchet@43033
   386
  Exn.capture f path
blanchet@43033
   387
  |> tap (fn _ => cleanup path)
blanchet@43033
   388
  |> Exn.release
blanchet@43033
   389
  |> tap (after path)
blanchet@43033
   390
blanchet@43033
   391
fun proof_banner mode blocking name =
blanchet@43033
   392
  case mode of
blanchet@43033
   393
    Auto_Try => "Auto Sledgehammer (" ^ quote name ^ ") found a proof"
blanchet@43033
   394
  | Try => "Sledgehammer (" ^ quote name ^ ") found a proof"
blanchet@43033
   395
  | Normal => if blocking then quote name ^ " found a proof"
blanchet@43033
   396
              else "Try this"
blanchet@43033
   397
  | Minimize => "Try this"
blanchet@43033
   398
blanchet@43033
   399
(* based on "Mirabelle.can_apply" and generalized *)
blanchet@43034
   400
fun timed_apply timeout tac state i =
blanchet@43033
   401
  let
blanchet@43033
   402
    val {context = ctxt, facts, goal} = Proof.goal state
blanchet@43033
   403
    val full_tac = Method.insert_tac facts i THEN tac ctxt i
blanchet@43034
   404
  in TimeLimit.timeLimit timeout (try (Seq.pull o full_tac)) goal end
blanchet@43033
   405
blanchet@43034
   406
fun tac_for_reconstructor Metis = Metis_Tactics.metisHO_tac
blanchet@43034
   407
  | tac_for_reconstructor MetisFT = Metis_Tactics.metisFT_tac
blanchet@43034
   408
  | tac_for_reconstructor _ = raise Fail "unexpected reconstructor"
blanchet@43034
   409
blanchet@43034
   410
fun timed_reconstructor reconstructor debug timeout ths =
blanchet@43034
   411
  (Config.put Metis_Tactics.verbose debug
blanchet@43034
   412
   #> (fn ctxt => tac_for_reconstructor reconstructor ctxt ths))
blanchet@43034
   413
  |> timed_apply timeout
blanchet@43033
   414
blanchet@43033
   415
fun filter_used_facts used = filter (member (op =) used o fst)
blanchet@43033
   416
blanchet@43050
   417
fun play_one_line_proof debug timeout ths state i reconstructors =
blanchet@43034
   418
  let
blanchet@43050
   419
    fun play [] [] = Failed_to_Play
blanchet@43050
   420
      | play (timed_out :: _) [] = Trust_Playable (timed_out, SOME timeout)
blanchet@43050
   421
      | play timed_out (reconstructor :: reconstructors) =
blanchet@43044
   422
        let val timer = Timer.startRealTimer () in
blanchet@43044
   423
          case timed_reconstructor reconstructor debug timeout ths state i of
blanchet@43050
   424
            SOME (SOME _) => Played (reconstructor, Timer.checkRealTimer timer)
blanchet@43050
   425
          | _ => play timed_out reconstructors
blanchet@43044
   426
        end
blanchet@43044
   427
        handle TimeLimit.TimeOut =>
blanchet@43050
   428
               play (reconstructor :: timed_out) reconstructors
blanchet@43034
   429
  in
blanchet@43044
   430
    if timeout = Time.zeroTime then Trust_Playable (hd reconstructors, NONE)
blanchet@43050
   431
    else play [] reconstructors
blanchet@43033
   432
  end
blanchet@43033
   433
blanchet@41313
   434
blanchet@41256
   435
(* generic TPTP-based ATPs *)
blanchet@40061
   436
blanchet@42730
   437
(* Too general means, positive equality literal with a variable X as one
blanchet@42730
   438
   operand, when X does not occur properly in the other operand. This rules out
blanchet@42730
   439
   clearly inconsistent facts such as X = a | X = b, though it by no means
blanchet@42730
   440
   guarantees soundness. *)
blanchet@42730
   441
blanchet@42730
   442
(* Unwanted equalities are those between a (bound or schematic) variable that
blanchet@42730
   443
   does not properly occur in the second operand. *)
blanchet@42730
   444
val is_exhaustive_finite =
blanchet@42730
   445
  let
blanchet@42730
   446
    fun is_bad_equal (Var z) t =
blanchet@42730
   447
        not (exists_subterm (fn Var z' => z = z' | _ => false) t)
blanchet@42730
   448
      | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
blanchet@42730
   449
      | is_bad_equal _ _ = false
blanchet@42730
   450
    fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
blanchet@42730
   451
    fun do_formula pos t =
blanchet@42730
   452
      case (pos, t) of
blanchet@42730
   453
        (_, @{const Trueprop} $ t1) => do_formula pos t1
blanchet@42730
   454
      | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
blanchet@42730
   455
        do_formula pos t'
blanchet@42730
   456
      | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
blanchet@42730
   457
        do_formula pos t'
blanchet@42730
   458
      | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
blanchet@42730
   459
        do_formula pos t'
blanchet@42730
   460
      | (_, @{const "==>"} $ t1 $ t2) =>
blanchet@42730
   461
        do_formula (not pos) t1 andalso
blanchet@42730
   462
        (t2 = @{prop False} orelse do_formula pos t2)
blanchet@42730
   463
      | (_, @{const HOL.implies} $ t1 $ t2) =>
blanchet@42730
   464
        do_formula (not pos) t1 andalso
blanchet@42730
   465
        (t2 = @{const False} orelse do_formula pos t2)
blanchet@42730
   466
      | (_, @{const Not} $ t1) => do_formula (not pos) t1
blanchet@42730
   467
      | (true, @{const HOL.disj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@42730
   468
      | (false, @{const HOL.conj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@42730
   469
      | (true, Const (@{const_name HOL.eq}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@42730
   470
      | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@42730
   471
      | _ => false
blanchet@42730
   472
  in do_formula true end
blanchet@42730
   473
blanchet@42730
   474
fun has_bound_or_var_of_type pred =
blanchet@42730
   475
  exists_subterm (fn Var (_, T as Type _) => pred T
blanchet@42730
   476
                   | Abs (_, T as Type _, _) => pred T
blanchet@42730
   477
                   | _ => false)
blanchet@42730
   478
blanchet@42730
   479
(* Facts are forbidden to contain variables of these types. The typical reason
blanchet@42730
   480
   is that they lead to unsoundness. Note that "unit" satisfies numerous
blanchet@42730
   481
   equations like "?x = ()". The resulting clauses will have no type constraint,
blanchet@42730
   482
   yielding false proofs. Even "bool" leads to many unsound proofs, though only
blanchet@42730
   483
   for higher-order problems. *)
blanchet@42730
   484
blanchet@42730
   485
(* Facts containing variables of type "unit" or "bool" or of the form
blanchet@42730
   486
   "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
blanchet@42730
   487
   are omitted. *)
blanchet@42944
   488
fun is_dangerous_prop ctxt =
blanchet@42944
   489
  transform_elim_prop
blanchet@42730
   490
  #> (has_bound_or_var_of_type (is_type_surely_finite ctxt) orf
blanchet@42730
   491
      is_exhaustive_finite)
blanchet@42730
   492
blanchet@40409
   493
fun int_opt_add (SOME m) (SOME n) = SOME (m + n)
blanchet@40409
   494
  | int_opt_add _ _ = NONE
blanchet@40062
   495
blanchet@42452
   496
val atp_blacklist_max_iters = 10
blanchet@39492
   497
(* Important messages are important but not so important that users want to see
blanchet@39492
   498
   them each time. *)
blanchet@42609
   499
val atp_important_message_keep_quotient = 10
blanchet@39492
   500
blanchet@42589
   501
val fallback_best_type_systems =
blanchet@42853
   502
  [Preds (Mangled_Monomorphic, Nonmonotonic_Types, Light)]
blanchet@42579
   503
blanchet@42722
   504
fun adjust_dumb_type_sys formats (Simple_Types level) =
blanchet@42963
   505
    if member (op =) formats THF then
blanchet@42963
   506
      (THF, Simple_Types level)
blanchet@42963
   507
    else if member (op =) formats TFF then
blanchet@42963
   508
      (TFF, Simple_Types level)
blanchet@42963
   509
    else
blanchet@42963
   510
      adjust_dumb_type_sys formats (Preds (Mangled_Monomorphic, level, Heavy))
blanchet@42849
   511
  | adjust_dumb_type_sys formats type_sys =
blanchet@42998
   512
    (case hd formats of
blanchet@42998
   513
       CNF_UEQ =>
blanchet@42998
   514
       (CNF_UEQ, case type_sys of
blanchet@42998
   515
                   Preds stuff =>
blanchet@42998
   516
                   (if is_type_sys_fairly_sound type_sys then Preds else Tags)
blanchet@42998
   517
                       stuff
blanchet@42998
   518
                 | _ => type_sys)
blanchet@42998
   519
     | format => (format, type_sys))
blanchet@42994
   520
blanchet@43051
   521
fun choose_format_and_type_sys _ formats (Dumb_Type_Sys type_sys) =
blanchet@42579
   522
    adjust_dumb_type_sys formats type_sys
blanchet@43051
   523
  | choose_format_and_type_sys best_type_systems formats
blanchet@43051
   524
                               (Smart_Type_Sys full_types) =
blanchet@42613
   525
    map type_sys_from_string best_type_systems @ fallback_best_type_systems
blanchet@42589
   526
    |> find_first (if full_types then is_type_sys_virtually_sound else K true)
blanchet@42589
   527
    |> the |> adjust_dumb_type_sys formats
blanchet@42548
   528
blanchet@43051
   529
val metis_minimize_max_time = seconds 2.0
blanchet@43051
   530
blanchet@43051
   531
fun choose_minimize_command minimize_command name preplay =
blanchet@43051
   532
  (case preplay of
blanchet@43051
   533
     Played (reconstructor, time) =>
blanchet@43051
   534
     if Time.<= (time, metis_minimize_max_time) then
blanchet@43051
   535
       reconstructor_name reconstructor
blanchet@43051
   536
     else
blanchet@43051
   537
       name
blanchet@43051
   538
   | _ => name)
blanchet@43051
   539
  |> minimize_command
blanchet@43051
   540
blanchet@42740
   541
fun repair_smt_monomorph_context debug max_mono_iters max_mono_instances =
blanchet@42724
   542
  Config.put SMT_Config.verbose debug
blanchet@42724
   543
  #> Config.put SMT_Config.monomorph_full false
blanchet@42724
   544
  #> Config.put SMT_Config.monomorph_limit max_mono_iters
blanchet@42740
   545
  #> Config.put SMT_Config.monomorph_instances max_mono_instances
blanchet@42724
   546
blanchet@43021
   547
fun run_atp mode name
blanchet@42578
   548
        ({exec, required_execs, arguments, proof_delims, known_failures,
blanchet@42723
   549
          conj_sym_kind, prem_kind, formats, best_slices, ...} : atp_config)
blanchet@43006
   550
        ({debug, verbose, overlord, blocking, type_sys, max_relevant,
blanchet@43006
   551
          max_mono_iters, max_new_mono_instances, explicit_apply, isar_proof,
blanchet@43033
   552
          isar_shrink_factor, slicing, timeout, preplay_timeout, ...} : params)
blanchet@43037
   553
        minimize_command
blanchet@43037
   554
        ({state, goal, subgoal, subgoal_count, facts, ...} : prover_problem) =
blanchet@38023
   555
  let
blanchet@42182
   556
    val thy = Proof.theory_of state
blanchet@39318
   557
    val ctxt = Proof.context_of state
blanchet@43004
   558
    val (_, hyp_ts, concl_t) = strip_subgoal ctxt goal subgoal
blanchet@41159
   559
    val (dest_dir, problem_prefix) =
blanchet@41159
   560
      if overlord then overlord_file_location_for_prover name
blanchet@41159
   561
      else (Config.get ctxt dest_dir, Config.get ctxt problem_prefix)
blanchet@40061
   562
    val problem_file_name =
blanchet@41159
   563
      Path.basic (problem_prefix ^ (if overlord then "" else serial_string ()) ^
blanchet@41159
   564
                  "_" ^ string_of_int subgoal)
blanchet@40061
   565
    val problem_path_name =
blanchet@40059
   566
      if dest_dir = "" then
blanchet@40061
   567
        File.tmp_path problem_file_name
blanchet@40059
   568
      else if File.exists (Path.explode dest_dir) then
blanchet@40061
   569
        Path.append (Path.explode dest_dir) problem_file_name
blanchet@39003
   570
      else
blanchet@40059
   571
        error ("No such directory: " ^ quote dest_dir ^ ".")
blanchet@39003
   572
    val measure_run_time = verbose orelse Config.get ctxt measure_run_time
blanchet@38092
   573
    val command = Path.explode (getenv (fst exec) ^ "/" ^ snd exec)
blanchet@38023
   574
    fun split_time s =
blanchet@38023
   575
      let
blanchet@42448
   576
        val split = String.tokens (fn c => str c = "\n")
blanchet@42448
   577
        val (output, t) = s |> split |> split_last |> apfst cat_lines
blanchet@42448
   578
        fun as_num f = f >> (fst o read_int)
blanchet@42448
   579
        val num = as_num (Scan.many1 Symbol.is_ascii_digit)
blanchet@42448
   580
        val digit = Scan.one Symbol.is_ascii_digit
blanchet@42448
   581
        val num3 = as_num (digit ::: digit ::: (digit >> single))
blanchet@42448
   582
        val time = num --| Scan.$$ "." -- num3 >> (fn (a, b) => a * 1000 + b)
wenzelm@40627
   583
        val as_time = Scan.read Symbol.stopper time o raw_explode
blanchet@42448
   584
      in (output, as_time t) end
blanchet@41313
   585
    fun run_on prob_file =
blanchet@38092
   586
      case filter (curry (op =) "" o getenv o fst) (exec :: required_execs) of
blanchet@38032
   587
        (home_var, _) :: _ =>
blanchet@38023
   588
        error ("The environment variable " ^ quote home_var ^ " is not set.")
blanchet@38032
   589
      | [] =>
blanchet@38032
   590
        if File.exists command then
blanchet@38032
   591
          let
blanchet@42443
   592
            (* If slicing is disabled, we expand the last slice to fill the
blanchet@42443
   593
               entire time available. *)
blanchet@42646
   594
            val actual_slices = get_slices slicing (best_slices ctxt)
blanchet@42443
   595
            val num_actual_slices = length actual_slices
blanchet@42445
   596
            fun monomorphize_facts facts =
blanchet@42445
   597
              let
blanchet@42445
   598
                val facts = facts |> map untranslated_fact
blanchet@42445
   599
                (* pseudo-theorem involving the same constants as the subgoal *)
blanchet@42445
   600
                val subgoal_th =
blanchet@42445
   601
                  Logic.list_implies (hyp_ts, concl_t)
blanchet@42445
   602
                  |> Skip_Proof.make_thm thy
blanchet@42445
   603
                val indexed_facts =
blanchet@42445
   604
                  (~1, subgoal_th) :: (0 upto length facts - 1 ~~ map snd facts)
blanchet@42740
   605
                val max_mono_instances = max_new_mono_instances + length facts
blanchet@42445
   606
              in
blanchet@42724
   607
                ctxt |> repair_smt_monomorph_context debug max_mono_iters
blanchet@42740
   608
                                                     max_mono_instances
blanchet@42724
   609
                     |> SMT_Monomorph.monomorph indexed_facts
blanchet@42724
   610
                     |> fst |> sort (int_ord o pairself fst)
blanchet@42724
   611
                     |> filter_out (curry (op =) ~1 o fst)
blanchet@42724
   612
                     |> map (Untranslated_Fact o apfst (fst o nth facts))
blanchet@42445
   613
              end
blanchet@42723
   614
            fun run_slice blacklist (slice, (time_frac, (complete,
blanchet@42723
   615
                                       (best_max_relevant, best_type_systems))))
blanchet@42443
   616
                          time_left =
blanchet@38032
   617
              let
blanchet@42443
   618
                val num_facts =
blanchet@42443
   619
                  length facts |> is_none max_relevant
blanchet@42723
   620
                                  ? Integer.min best_max_relevant
blanchet@42723
   621
                val (format, type_sys) =
blanchet@43051
   622
                  choose_format_and_type_sys best_type_systems formats type_sys
blanchet@42638
   623
                val fairly_sound = is_type_sys_fairly_sound type_sys
blanchet@42451
   624
                val facts =
blanchet@42671
   625
                  facts |> not fairly_sound
blanchet@42944
   626
                           ? filter_out (is_dangerous_prop ctxt o prop_of o snd
blanchet@42638
   627
                                         o untranslated_fact)
blanchet@42638
   628
                        |> take num_facts
blanchet@42452
   629
                        |> not (null blacklist)
blanchet@42452
   630
                           ? filter_out (member (op =) blacklist o fst
blanchet@42452
   631
                                         o untranslated_fact)
blanchet@42589
   632
                        |> polymorphism_of_type_sys type_sys <> Polymorphic
blanchet@42589
   633
                           ? monomorphize_facts
blanchet@42994
   634
                        |> map (atp_translated_fact ctxt format type_sys)
blanchet@42443
   635
                val real_ms = Real.fromInt o Time.toMilliseconds
blanchet@42443
   636
                val slice_timeout =
blanchet@42443
   637
                  ((real_ms time_left
blanchet@42443
   638
                    |> (if slice < num_actual_slices - 1 then
blanchet@42443
   639
                          curry Real.min (time_frac * real_ms timeout)
blanchet@42443
   640
                        else
blanchet@42443
   641
                          I))
blanchet@42443
   642
                   * 0.001) |> seconds
blanchet@42443
   643
                val _ =
blanchet@42614
   644
                  if debug then
blanchet@42699
   645
                    quote name ^ " slice #" ^ string_of_int (slice + 1) ^
blanchet@42699
   646
                    " with " ^ string_of_int num_facts ^ " fact" ^
blanchet@42699
   647
                    plural_s num_facts ^ " for " ^
blanchet@42699
   648
                    string_from_time slice_timeout ^ "..."
blanchet@42443
   649
                    |> Output.urgent_message
blanchet@42443
   650
                  else
blanchet@42443
   651
                    ()
blanchet@42541
   652
                val (atp_problem, pool, conjecture_offset, facts_offset,
blanchet@42881
   653
                     fact_names, typed_helpers, sym_tab) =
blanchet@42939
   654
                  prepare_atp_problem ctxt format conj_sym_kind prem_kind
blanchet@42939
   655
                      type_sys explicit_apply hyp_ts concl_t facts
blanchet@41313
   656
                fun weights () = atp_problem_weights atp_problem
blanchet@41313
   657
                val core =
blanchet@41313
   658
                  File.shell_path command ^ " " ^
blanchet@42646
   659
                  arguments ctxt slice slice_timeout weights ^ " " ^
blanchet@41313
   660
                  File.shell_path prob_file
blanchet@41313
   661
                val command =
blanchet@41313
   662
                  (if measure_run_time then
blanchet@41313
   663
                     "TIMEFORMAT='%3R'; { time " ^ core ^ " ; }"
blanchet@41313
   664
                   else
blanchet@41313
   665
                     "exec " ^ core) ^ " 2>&1"
blanchet@42443
   666
                val _ =
blanchet@42443
   667
                  atp_problem
blanchet@42709
   668
                  |> tptp_strings_for_atp_problem format
blanchet@42443
   669
                  |> cons ("% " ^ command ^ "\n")
blanchet@42443
   670
                  |> File.write_list prob_file
blanchet@42443
   671
                val conjecture_shape =
blanchet@42443
   672
                  conjecture_offset + 1
blanchet@42443
   673
                    upto conjecture_offset + length hyp_ts + 1
blanchet@42443
   674
                  |> map single
blanchet@38032
   675
                val ((output, msecs), res_code) =
blanchet@38032
   676
                  bash_output command
blanchet@38032
   677
                  |>> (if overlord then
blanchet@38032
   678
                         prefix ("% " ^ command ^ "\n% " ^ timestamp () ^ "\n")
blanchet@38032
   679
                       else
blanchet@38032
   680
                         I)
blanchet@40062
   681
                  |>> (if measure_run_time then split_time else rpair NONE)
blanchet@42449
   682
                val (atp_proof, outcome) =
blanchet@42849
   683
                  extract_tstplike_proof_and_outcome verbose complete res_code
blanchet@42849
   684
                      proof_delims known_failures output
blanchet@42943
   685
                  |>> atp_proof_from_tstplike_proof atp_problem
blanchet@42965
   686
                  handle UNRECOGNIZED_ATP_PROOF () => ([], SOME ProofIncomplete)
blanchet@42881
   687
                val (conjecture_shape, facts_offset, fact_names,
blanchet@42881
   688
                     typed_helpers) =
blanchet@42449
   689
                  if is_none outcome then
blanchet@42647
   690
                    repair_conjecture_shape_and_fact_names type_sys output
blanchet@42881
   691
                        conjecture_shape facts_offset fact_names typed_helpers
blanchet@42449
   692
                  else
blanchet@42587
   693
                    (* don't bother repairing *)
blanchet@42881
   694
                    (conjecture_shape, facts_offset, fact_names, typed_helpers)
blanchet@42449
   695
                val outcome =
blanchet@42451
   696
                  case outcome of
blanchet@42587
   697
                    NONE =>
blanchet@42968
   698
                    used_facts_in_unsound_atp_proof ctxt type_sys
blanchet@42876
   699
                        conjecture_shape facts_offset fact_names atp_proof
blanchet@42876
   700
                    |> Option.map (fn facts =>
blanchet@42876
   701
                           UnsoundProof (is_type_sys_virtually_sound type_sys,
blanchet@42943
   702
                                         facts |> sort string_ord))
blanchet@42451
   703
                  | SOME Unprovable =>
blanchet@43050
   704
                    if null blacklist then outcome else SOME GaveUp
blanchet@42451
   705
                  | _ => outcome
blanchet@42443
   706
              in
blanchet@42881
   707
                ((pool, conjecture_shape, facts_offset, fact_names,
blanchet@42881
   708
                  typed_helpers, sym_tab),
blanchet@42723
   709
                 (output, msecs, type_sys, atp_proof, outcome))
blanchet@42443
   710
              end
blanchet@38645
   711
            val timer = Timer.startRealTimer ()
blanchet@42452
   712
            fun maybe_run_slice blacklist slice
blanchet@42723
   713
                                (result as (_, (_, msecs0, _, _, SOME _))) =
blanchet@42452
   714
                let
blanchet@42452
   715
                  val time_left = Time.- (timeout, Timer.checkRealTimer timer)
blanchet@42452
   716
                in
blanchet@42452
   717
                  if Time.<= (time_left, Time.zeroTime) then
blanchet@42452
   718
                    result
blanchet@42452
   719
                  else
blanchet@42452
   720
                    (run_slice blacklist slice time_left
blanchet@42723
   721
                     |> (fn (stuff, (output, msecs, type_sys, atp_proof,
blanchet@42723
   722
                                     outcome)) =>
blanchet@42723
   723
                            (stuff, (output, int_opt_add msecs0 msecs, type_sys,
blanchet@42723
   724
                                     atp_proof, outcome))))
blanchet@42452
   725
                end
blanchet@42450
   726
              | maybe_run_slice _ _ result = result
blanchet@42452
   727
            fun maybe_blacklist_facts_and_retry iter blacklist
blanchet@42881
   728
                    (result as ((_, _, facts_offset, fact_names, _, _),
blanchet@42723
   729
                                (_, _, type_sys, atp_proof,
blanchet@42876
   730
                                 SOME (UnsoundProof (false, _))))) =
blanchet@42968
   731
                (case used_facts_in_atp_proof ctxt type_sys facts_offset
blanchet@42968
   732
                                              fact_names atp_proof of
blanchet@42452
   733
                   [] => result
blanchet@42452
   734
                 | new_baddies =>
blanchet@42835
   735
                   if slicing andalso iter < atp_blacklist_max_iters - 1 then
blanchet@42777
   736
                     let val blacklist = new_baddies @ blacklist in
blanchet@42777
   737
                       result
blanchet@42777
   738
                       |> maybe_run_slice blacklist (List.last actual_slices)
blanchet@42777
   739
                       |> maybe_blacklist_facts_and_retry (iter + 1) blacklist
blanchet@42777
   740
                     end
blanchet@42777
   741
                   else
blanchet@42777
   742
                     result)
blanchet@42452
   743
              | maybe_blacklist_facts_and_retry _ _ result = result
blanchet@42443
   744
          in
blanchet@42881
   745
            ((Symtab.empty, [], 0, Vector.fromList [], [], Symtab.empty),
blanchet@42723
   746
             ("", SOME 0, hd fallback_best_type_systems, [],
blanchet@42723
   747
              SOME InternalError))
blanchet@42451
   748
            |> fold (maybe_run_slice []) actual_slices
blanchet@42451
   749
               (* The ATP found an unsound proof? Automatically try again
blanchet@42451
   750
                  without the offending facts! *)
blanchet@42452
   751
            |> maybe_blacklist_facts_and_retry 0 []
blanchet@42443
   752
          end
blanchet@38032
   753
        else
wenzelm@41944
   754
          error ("Bad executable: " ^ Path.print command ^ ".")
blanchet@38023
   755
blanchet@38023
   756
    (* If the problem file has not been exported, remove it; otherwise, export
blanchet@38023
   757
       the proof file too. *)
blanchet@41313
   758
    fun cleanup prob_file =
blanchet@41313
   759
      if dest_dir = "" then try File.rm prob_file else NONE
blanchet@42723
   760
    fun export prob_file (_, (output, _, _, _, _)) =
blanchet@40059
   761
      if dest_dir = "" then
blanchet@38023
   762
        ()
blanchet@38023
   763
      else
blanchet@41313
   764
        File.write (Path.explode (Path.implode prob_file ^ "_proof")) output
blanchet@42881
   765
    val ((pool, conjecture_shape, facts_offset, fact_names, typed_helpers,
blanchet@42881
   766
          sym_tab),
blanchet@42723
   767
         (output, msecs, type_sys, atp_proof, outcome)) =
blanchet@40061
   768
      with_path cleanup export run_on problem_path_name
blanchet@39492
   769
    val important_message =
blanchet@43021
   770
      if mode = Normal andalso
blanchet@42609
   771
         random_range 0 (atp_important_message_keep_quotient - 1) = 0 then
blanchet@39492
   772
        extract_important_message output
blanchet@39492
   773
      else
blanchet@39492
   774
        ""
blanchet@43037
   775
    val (message, used_facts) =
blanchet@38023
   776
      case outcome of
blanchet@38023
   777
        NONE =>
blanchet@43033
   778
        let
blanchet@43033
   779
          val used_facts =
blanchet@43033
   780
            used_facts_in_atp_proof ctxt type_sys facts_offset fact_names
blanchet@43033
   781
                                    atp_proof
blanchet@43044
   782
          val reconstructors =
blanchet@43044
   783
            if uses_typed_helpers typed_helpers atp_proof then [MetisFT, Metis]
blanchet@43044
   784
            else [Metis, MetisFT]
blanchet@43037
   785
          val used_ths =
blanchet@43037
   786
            facts |> map untranslated_fact
blanchet@43037
   787
                  |> filter_used_facts used_facts
blanchet@43037
   788
                  |> map snd
blanchet@43033
   789
          val preplay =
blanchet@43050
   790
            play_one_line_proof debug preplay_timeout used_ths state subgoal
blanchet@43050
   791
                                reconstructors
blanchet@43033
   792
          val full_types = uses_typed_helpers typed_helpers atp_proof
blanchet@43033
   793
          val isar_params =
blanchet@43033
   794
            (debug, full_types, isar_shrink_factor, type_sys, pool,
blanchet@43037
   795
             conjecture_shape, facts_offset, fact_names, sym_tab, atp_proof,
blanchet@43037
   796
             goal)
blanchet@43033
   797
          val one_line_params =
blanchet@43033
   798
            (preplay, proof_banner mode blocking name, used_facts,
blanchet@43051
   799
             choose_minimize_command minimize_command name preplay,
blanchet@43051
   800
             subgoal, subgoal_count)
blanchet@43033
   801
        in
blanchet@43037
   802
          (proof_text ctxt isar_proof isar_params one_line_params ^
blanchet@43037
   803
           (if verbose then
blanchet@43037
   804
              "\nATP real CPU time: " ^
blanchet@43037
   805
              string_from_time (Time.fromMilliseconds (the msecs)) ^ "."
blanchet@43037
   806
            else
blanchet@43037
   807
              "") ^
blanchet@43037
   808
           (if important_message <> "" then
blanchet@43037
   809
              "\n\nImportant message from Dr. Geoff Sutcliffe:\n" ^
blanchet@43037
   810
              important_message
blanchet@43037
   811
            else
blanchet@43037
   812
              ""),
blanchet@43037
   813
           used_facts)
blanchet@43033
   814
        end
blanchet@43037
   815
      | SOME failure => (string_for_failure failure, [])
blanchet@38023
   816
  in
blanchet@40204
   817
    {outcome = outcome, message = message, used_facts = used_facts,
blanchet@40061
   818
     run_time_in_msecs = msecs}
blanchet@38023
   819
  end
blanchet@38023
   820
blanchet@40669
   821
(* "SMT_Failure.Abnormal_Termination" carries the solver's return code. Until
blanchet@40669
   822
   these are sorted out properly in the SMT module, we have to interpret these
blanchet@40669
   823
   ourselves. *)
blanchet@40684
   824
val remote_smt_failures =
blanchet@40684
   825
  [(22, CantConnect),
blanchet@40684
   826
   (2, NoLibwwwPerl)]
blanchet@41222
   827
val z3_wrapper_failures =
blanchet@41222
   828
  [(10, NoRealZ3),
blanchet@41222
   829
   (11, InternalError),
blanchet@41222
   830
   (12, InternalError),
blanchet@41222
   831
   (13, InternalError)]
blanchet@40684
   832
val z3_failures =
blanchet@41236
   833
  [(101, OutOfResources),
blanchet@41236
   834
   (103, MalformedInput),
blanchet@41222
   835
   (110, MalformedInput)]
blanchet@40684
   836
val unix_failures =
blanchet@40684
   837
  [(139, Crashed)]
blanchet@41222
   838
val smt_failures =
blanchet@41799
   839
  remote_smt_failures @ z3_wrapper_failures @ z3_failures @ unix_failures
blanchet@40555
   840
blanchet@42100
   841
fun failure_from_smt_failure (SMT_Failure.Counterexample {is_real_cex, ...}) =
blanchet@43050
   842
    if is_real_cex then Unprovable else GaveUp
blanchet@41222
   843
  | failure_from_smt_failure SMT_Failure.Time_Out = TimedOut
blanchet@41222
   844
  | failure_from_smt_failure (SMT_Failure.Abnormal_Termination code) =
blanchet@41222
   845
    (case AList.lookup (op =) smt_failures code of
blanchet@40684
   846
       SOME failure => failure
blanchet@41259
   847
     | NONE => UnknownError ("Abnormal termination with exit code " ^
blanchet@41259
   848
                             string_of_int code ^ "."))
blanchet@41222
   849
  | failure_from_smt_failure SMT_Failure.Out_Of_Memory = OutOfResources
blanchet@41222
   850
  | failure_from_smt_failure (SMT_Failure.Other_Failure msg) =
blanchet@42061
   851
    UnknownError msg
blanchet@40063
   852
blanchet@40698
   853
(* FUDGE *)
blanchet@42646
   854
val smt_max_slices =
blanchet@42646
   855
  Attrib.setup_config_int @{binding sledgehammer_smt_max_slices} (K 8)
blanchet@42646
   856
val smt_slice_fact_frac =
blanchet@42646
   857
  Attrib.setup_config_real @{binding sledgehammer_smt_slice_fact_frac} (K 0.5)
blanchet@42646
   858
val smt_slice_time_frac =
blanchet@42646
   859
  Attrib.setup_config_real @{binding sledgehammer_smt_slice_time_frac} (K 0.5)
blanchet@42646
   860
val smt_slice_min_secs =
blanchet@42646
   861
  Attrib.setup_config_int @{binding sledgehammer_smt_slice_min_secs} (K 5)
blanchet@40409
   862
blanchet@42646
   863
fun smt_filter_loop ctxt name
blanchet@42724
   864
                    ({debug, verbose, overlord, max_mono_iters,
blanchet@42740
   865
                      max_new_mono_instances, timeout, slicing, ...} : params)
blanchet@41741
   866
                    state i smt_filter =
blanchet@40409
   867
  let
blanchet@42646
   868
    val max_slices = if slicing then Config.get ctxt smt_max_slices else 1
blanchet@41242
   869
    val repair_context =
blanchet@42724
   870
          select_smt_solver name
blanchet@42724
   871
          #> (if overlord then
blanchet@42724
   872
                Config.put SMT_Config.debug_files
blanchet@42724
   873
                           (overlord_file_location_for_prover name
blanchet@42724
   874
                            |> (fn (path, name) => path ^ "/" ^ name))
blanchet@42724
   875
              else
blanchet@42724
   876
                I)
blanchet@42724
   877
          #> Config.put SMT_Config.infer_triggers (Config.get ctxt smt_triggers)
blanchet@41242
   878
    val state = state |> Proof.map_context repair_context
blanchet@42443
   879
    fun do_slice timeout slice outcome0 time_so_far facts =
blanchet@40553
   880
      let
blanchet@40553
   881
        val timer = Timer.startRealTimer ()
blanchet@42724
   882
        val state =
blanchet@42724
   883
          state |> Proof.map_context
blanchet@42724
   884
                       (repair_smt_monomorph_context debug max_mono_iters
blanchet@42740
   885
                            (max_new_mono_instances + length facts))
blanchet@40553
   886
        val ms = timeout |> Time.toMilliseconds
blanchet@42443
   887
        val slice_timeout =
blanchet@42443
   888
          if slice < max_slices then
blanchet@41169
   889
            Int.min (ms,
blanchet@42646
   890
                Int.max (1000 * Config.get ctxt smt_slice_min_secs,
blanchet@42646
   891
                    Real.ceil (Config.get ctxt smt_slice_time_frac
blanchet@42646
   892
                               * Real.fromInt ms)))
blanchet@40553
   893
            |> Time.fromMilliseconds
blanchet@40553
   894
          else
blanchet@40553
   895
            timeout
blanchet@40553
   896
        val num_facts = length facts
blanchet@40553
   897
        val _ =
blanchet@42614
   898
          if debug then
blanchet@42614
   899
            quote name ^ " slice " ^ string_of_int slice ^ " with " ^
blanchet@42614
   900
            string_of_int num_facts ^ " fact" ^ plural_s num_facts ^ " for " ^
blanchet@42614
   901
            string_from_time slice_timeout ^ "..."
blanchet@40553
   902
            |> Output.urgent_message
blanchet@40553
   903
          else
blanchet@40553
   904
            ()
blanchet@41168
   905
        val birth = Timer.checkRealTimer timer
blanchet@41171
   906
        val _ =
blanchet@41211
   907
          if debug then Output.urgent_message "Invoking SMT solver..." else ()
blanchet@41209
   908
        val (outcome, used_facts) =
blanchet@42443
   909
          (case (slice, smt_filter) of
boehmes@41432
   910
             (1, SOME head) => head |> apsnd (apsnd repair_context)
boehmes@41432
   911
           | _ => SMT_Solver.smt_filter_preprocess state facts i)
blanchet@42443
   912
          |> SMT_Solver.smt_filter_apply slice_timeout
blanchet@41239
   913
          |> (fn {outcome, used_facts} => (outcome, used_facts))
blanchet@41209
   914
          handle exn => if Exn.is_interrupt exn then
blanchet@41209
   915
                          reraise exn
blanchet@41209
   916
                        else
blanchet@42061
   917
                          (ML_Compiler.exn_message exn
blanchet@41209
   918
                           |> SMT_Failure.Other_Failure |> SOME, [])
blanchet@41168
   919
        val death = Timer.checkRealTimer timer
blanchet@40553
   920
        val outcome0 = if is_none outcome0 then SOME outcome else outcome0
blanchet@41168
   921
        val time_so_far = Time.+ (time_so_far, Time.- (death, birth))
blanchet@40553
   922
        val too_many_facts_perhaps =
blanchet@40553
   923
          case outcome of
blanchet@40553
   924
            NONE => false
blanchet@40553
   925
          | SOME (SMT_Failure.Counterexample _) => false
blanchet@42443
   926
          | SOME SMT_Failure.Time_Out => slice_timeout <> timeout
blanchet@42614
   927
          | SOME (SMT_Failure.Abnormal_Termination _) => true (* kind of *)
blanchet@40553
   928
          | SOME SMT_Failure.Out_Of_Memory => true
blanchet@41211
   929
          | SOME (SMT_Failure.Other_Failure _) => true
blanchet@40553
   930
        val timeout = Time.- (timeout, Timer.checkRealTimer timer)
blanchet@40553
   931
      in
blanchet@42443
   932
        if too_many_facts_perhaps andalso slice < max_slices andalso
blanchet@40553
   933
           num_facts > 0 andalso Time.> (timeout, Time.zeroTime) then
blanchet@41169
   934
          let
blanchet@42614
   935
            val new_num_facts =
blanchet@42646
   936
              Real.ceil (Config.get ctxt smt_slice_fact_frac
blanchet@42646
   937
                         * Real.fromInt num_facts)
blanchet@42614
   938
            val _ =
blanchet@42614
   939
              if verbose andalso is_some outcome then
blanchet@42614
   940
                quote name ^ " invoked with " ^ string_of_int num_facts ^
blanchet@42614
   941
                " fact" ^ plural_s num_facts ^ ": " ^
blanchet@42614
   942
                string_for_failure (failure_from_smt_failure (the outcome)) ^
blanchet@42614
   943
                " Retrying with " ^ string_of_int new_num_facts ^ " fact" ^
blanchet@42638
   944
                plural_s new_num_facts ^ "..."
blanchet@42614
   945
                |> Output.urgent_message
blanchet@42614
   946
              else
blanchet@42614
   947
                ()
blanchet@42443
   948
          in
blanchet@42614
   949
            facts |> take new_num_facts
blanchet@42614
   950
                  |> do_slice timeout (slice + 1) outcome0 time_so_far
blanchet@42443
   951
          end
blanchet@40553
   952
        else
blanchet@40553
   953
          {outcome = if is_none outcome then NONE else the outcome0,
blanchet@41168
   954
           used_facts = used_facts,
blanchet@41168
   955
           run_time_in_msecs = SOME (Time.toMilliseconds time_so_far)}
blanchet@40409
   956
      end
blanchet@42443
   957
  in do_slice timeout 1 NONE Time.zeroTime end
blanchet@40409
   958
blanchet@43021
   959
fun run_smt_solver mode name
blanchet@43015
   960
        (params as {debug, verbose, blocking, preplay_timeout, ...})
blanchet@43011
   961
        minimize_command
blanchet@43011
   962
        ({state, subgoal, subgoal_count, facts, smt_filter, ...}
blanchet@43011
   963
         : prover_problem) =
blanchet@36379
   964
  let
blanchet@41242
   965
    val ctxt = Proof.context_of state
blanchet@41256
   966
    val num_facts = length facts
blanchet@41256
   967
    val facts = facts ~~ (0 upto num_facts - 1)
blanchet@42646
   968
                |> map (smt_weighted_fact ctxt num_facts)
blanchet@40181
   969
    val {outcome, used_facts, run_time_in_msecs} =
blanchet@42646
   970
      smt_filter_loop ctxt name params state subgoal smt_filter facts
blanchet@43037
   971
    val (used_facts, used_ths) = used_facts |> ListPair.unzip
blanchet@41222
   972
    val outcome = outcome |> Option.map failure_from_smt_failure
blanchet@40063
   973
    val message =
blanchet@40184
   974
      case outcome of
blanchet@40184
   975
        NONE =>
blanchet@40666
   976
        let
blanchet@43037
   977
          fun smt_settings () =
blanchet@43037
   978
            if name = SMT_Solver.solver_name_of ctxt then ""
blanchet@43037
   979
            else "smt_solver = " ^ maybe_quote name
blanchet@43037
   980
          val preplay =
blanchet@43050
   981
            case play_one_line_proof debug preplay_timeout used_ths state
blanchet@43050
   982
                                     subgoal [Metis, MetisFT] of
blanchet@43050
   983
              p as Played _ => p
blanchet@43037
   984
            | _ => Trust_Playable (SMT (smt_settings ()), NONE)
blanchet@43037
   985
          val one_line_params =
blanchet@43037
   986
            (preplay, proof_banner mode blocking name, used_facts,
blanchet@43051
   987
             choose_minimize_command minimize_command name preplay,
blanchet@43051
   988
             subgoal, subgoal_count)
blanchet@40666
   989
        in
blanchet@43037
   990
          one_line_proof_text one_line_params ^
blanchet@41168
   991
          (if verbose then
blanchet@41168
   992
             "\nSMT solver real CPU time: " ^
blanchet@41168
   993
             string_from_time (Time.fromMilliseconds (the run_time_in_msecs)) ^
blanchet@41168
   994
             "."
blanchet@41168
   995
           else
blanchet@41168
   996
             "")
blanchet@40666
   997
        end
blanchet@41744
   998
      | SOME failure => string_for_failure failure
blanchet@40063
   999
  in
blanchet@43037
  1000
    {outcome = outcome, used_facts = used_facts,
blanchet@40204
  1001
     run_time_in_msecs = run_time_in_msecs, message = message}
blanchet@40063
  1002
  end
blanchet@40063
  1003
blanchet@43050
  1004
fun run_metis mode name ({debug, blocking, timeout, ...} : params)
blanchet@43050
  1005
              minimize_command
blanchet@43050
  1006
              ({state, subgoal, subgoal_count, facts, ...} : prover_problem) =
blanchet@43050
  1007
  let
blanchet@43050
  1008
    val reconstructor = if name = Metis_Tactics.metisN then Metis
blanchet@43050
  1009
                        else if name = Metis_Tactics.metisFT_N then MetisFT
blanchet@43050
  1010
                        else raise Fail ("unknown Metis version: " ^ quote name)
blanchet@43050
  1011
    val (used_facts, used_ths) =
blanchet@43050
  1012
      facts |> map untranslated_fact |> ListPair.unzip
blanchet@43050
  1013
  in
blanchet@43050
  1014
    case play_one_line_proof debug timeout used_ths state subgoal
blanchet@43050
  1015
                             [reconstructor] of
blanchet@43050
  1016
      play as Played (_, time) =>
blanchet@43050
  1017
      let
blanchet@43050
  1018
        val one_line_params =
blanchet@43050
  1019
          (play, proof_banner mode blocking name, used_facts,
blanchet@43051
  1020
           minimize_command name, subgoal, subgoal_count)
blanchet@43050
  1021
      in
blanchet@43050
  1022
        {outcome = NONE, used_facts = used_facts,
blanchet@43050
  1023
         run_time_in_msecs = SOME (Time.toMilliseconds time),
blanchet@43050
  1024
         message = one_line_proof_text one_line_params}
blanchet@43050
  1025
      end
blanchet@43050
  1026
    | play =>
blanchet@43050
  1027
      {outcome = SOME (if play = Failed_to_Play then GaveUp else TimedOut),
blanchet@43050
  1028
       used_facts = [], run_time_in_msecs = NONE, message = ""}
blanchet@43050
  1029
  end
blanchet@43050
  1030
blanchet@43021
  1031
fun get_prover ctxt mode name =
wenzelm@42361
  1032
  let val thy = Proof_Context.theory_of ctxt in
blanchet@43050
  1033
    if is_metis_prover name then
blanchet@43050
  1034
      run_metis mode name
blanchet@43050
  1035
    else if is_atp thy name then
blanchet@43050
  1036
      run_atp mode name (get_atp thy name)
blanchet@43050
  1037
    else if is_smt_prover ctxt name then
blanchet@43021
  1038
      run_smt_solver mode name
blanchet@40941
  1039
    else
blanchet@40941
  1040
      error ("No such prover: " ^ name ^ ".")
blanchet@40941
  1041
  end
blanchet@40063
  1042
wenzelm@28582
  1043
end;