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