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