src/HOL/Tools/Sledgehammer/sledgehammer_provers.ML
author blanchet
Thu Oct 17 20:49:19 2013 +0200 (2013-10-17 ago)
changeset 54141 f57f8e7a879f
parent 54126 6675cdc0d1ae
child 54434 e275d520f49d
permissions -rw-r--r--
generate a comment storing the goal nickname in "learn_prover"
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@53586
    11
  type atp_failure = ATP_Proof.atp_failure
blanchet@46340
    12
  type stature = ATP_Problem_Generate.stature
blanchet@46320
    13
  type type_enc = ATP_Problem_Generate.type_enc
blanchet@51005
    14
  type fact = Sledgehammer_Fact.fact
smolkas@52555
    15
  type reconstructor = Sledgehammer_Reconstructor.reconstructor
smolkas@52555
    16
  type play = Sledgehammer_Reconstructor.play
smolkas@52555
    17
  type minimize_command = Sledgehammer_Reconstructor.minimize_command
blanchet@39493
    18
wenzelm@53052
    19
  datatype mode = Auto_Try | Try | Normal | MaSh | Auto_Minimize | Minimize
blanchet@43021
    20
blanchet@35969
    21
  type params =
blanchet@48321
    22
    {debug : bool,
blanchet@48321
    23
     verbose : bool,
blanchet@48321
    24
     overlord : bool,
blanchet@53800
    25
     spy : bool,
blanchet@48321
    26
     blocking : bool,
blanchet@48321
    27
     provers : string list,
blanchet@48321
    28
     type_enc : string option,
blanchet@48321
    29
     strict : bool,
blanchet@48321
    30
     lam_trans : string option,
blanchet@48321
    31
     uncurried_aliases : bool option,
blanchet@48321
    32
     learn : bool,
blanchet@48321
    33
     fact_filter : string option,
blanchet@48321
    34
     max_facts : int option,
blanchet@48321
    35
     fact_thresholds : real * real,
blanchet@48321
    36
     max_mono_iters : int option,
blanchet@48321
    37
     max_new_mono_instances : int option,
blanchet@51190
    38
     isar_proofs : bool option,
smolkas@51130
    39
     isar_compress : real,
smolkas@52632
    40
     isar_try0 : bool,
blanchet@48321
    41
     slice : bool,
blanchet@48321
    42
     minimize : bool option,
blanchet@50557
    43
     timeout : Time.time option,
blanchet@50557
    44
     preplay_timeout : Time.time option,
blanchet@48321
    45
     expect : string}
blanchet@39493
    46
blanchet@40061
    47
  type prover_problem =
blanchet@54141
    48
    {comment : string,
blanchet@54141
    49
     state : Proof.state,
blanchet@48321
    50
     goal : thm,
blanchet@48321
    51
     subgoal : int,
blanchet@48321
    52
     subgoal_count : int,
blanchet@51010
    53
     factss : (string * fact list) list}
blanchet@39493
    54
blanchet@40061
    55
  type prover_result =
blanchet@53586
    56
    {outcome : atp_failure option,
blanchet@51009
    57
     used_facts : (string * stature) list,
blanchet@51009
    58
     used_from : fact list,
blanchet@48321
    59
     run_time : Time.time,
blanchet@50669
    60
     preplay : play Lazy.lazy,
blanchet@48321
    61
     message : play -> string,
blanchet@48321
    62
     message_tail : string}
blanchet@39493
    63
blanchet@43051
    64
  type prover =
blanchet@45520
    65
    params -> ((string * string list) list -> string -> minimize_command)
blanchet@45520
    66
    -> prover_problem -> prover_result
blanchet@35867
    67
blanchet@43092
    68
  val dest_dir : string Config.T
blanchet@43092
    69
  val problem_prefix : string Config.T
blanchet@48143
    70
  val completish : bool Config.T
blanchet@44592
    71
  val atp_full_names : bool Config.T
blanchet@54094
    72
  val smt_builtins : bool Config.T
blanchet@42646
    73
  val smt_triggers : bool Config.T
blanchet@42646
    74
  val smt_weights : bool Config.T
blanchet@42646
    75
  val smt_weight_min_facts : int Config.T
blanchet@42646
    76
  val smt_min_weight : int Config.T
blanchet@42646
    77
  val smt_max_weight : int Config.T
blanchet@42646
    78
  val smt_max_weight_index : int Config.T
blanchet@41256
    79
  val smt_weight_curve : (int -> int) Unsynchronized.ref
blanchet@42646
    80
  val smt_max_slices : int Config.T
blanchet@42646
    81
  val smt_slice_fact_frac : real Config.T
blanchet@42646
    82
  val smt_slice_time_frac : real Config.T
blanchet@42646
    83
  val smt_slice_min_secs : int Config.T
blanchet@48319
    84
  val SledgehammerN : string
blanchet@45519
    85
  val plain_metis : reconstructor
blanchet@41242
    86
  val select_smt_solver : string -> Proof.context -> Proof.context
blanchet@45520
    87
  val extract_reconstructor :
blanchet@45561
    88
    params -> reconstructor -> string * (string * string list) list
blanchet@45379
    89
  val is_reconstructor : string -> bool
blanchet@43050
    90
  val is_atp : theory -> string -> bool
blanchet@41087
    91
  val is_smt_prover : Proof.context -> string -> bool
blanchet@47962
    92
  val is_ho_atp: Proof.context -> string -> bool
blanchet@42944
    93
  val is_unit_equational_atp : Proof.context -> string -> bool
blanchet@41727
    94
  val is_prover_supported : Proof.context -> string -> bool
blanchet@40072
    95
  val is_prover_installed : Proof.context -> string -> bool
blanchet@51200
    96
  val remotify_prover_if_supported_and_not_already_remote :
blanchet@51200
    97
    Proof.context -> string -> string option
blanchet@51200
    98
  val remotify_prover_if_not_installed :
blanchet@51200
    99
    Proof.context -> string -> string option
blanchet@54126
   100
  val default_max_facts_of_prover : Proof.context -> string -> int
blanchet@42944
   101
  val is_unit_equality : term -> bool
blanchet@51998
   102
  val is_appropriate_prop_of_prover : Proof.context -> string -> term -> bool
blanchet@41256
   103
  val weight_smt_fact :
blanchet@46340
   104
    Proof.context -> int -> ((string * stature) * thm) * int
blanchet@46340
   105
    -> (string * stature) * (int option * thm)
blanchet@41727
   106
  val supported_provers : Proof.context -> unit
blanchet@40059
   107
  val kill_provers : unit -> unit
blanchet@40059
   108
  val running_provers : unit -> unit
blanchet@40059
   109
  val messages : int option -> unit
blanchet@48798
   110
  val is_fact_chained : (('a * stature) * 'b) -> bool
blanchet@48798
   111
  val filter_used_facts :
blanchet@48798
   112
    bool -> (''a * stature) list -> ((''a * stature) * 'b) list ->
blanchet@48798
   113
    ((''a * stature) * 'b) list
blanchet@51200
   114
  val isar_proof_reconstructor : Proof.context -> string -> string
blanchet@43021
   115
  val get_prover : Proof.context -> mode -> string -> prover
wenzelm@28477
   116
end;
wenzelm@28477
   117
blanchet@41087
   118
structure Sledgehammer_Provers : SLEDGEHAMMER_PROVERS =
wenzelm@28477
   119
struct
wenzelm@28477
   120
blanchet@43085
   121
open ATP_Util
blanchet@38028
   122
open ATP_Problem
blanchet@39491
   123
open ATP_Proof
blanchet@38028
   124
open ATP_Systems
blanchet@46320
   125
open ATP_Problem_Generate
blanchet@46320
   126
open ATP_Proof_Reconstruct
blanchet@45521
   127
open Metis_Tactic
blanchet@38023
   128
open Sledgehammer_Util
blanchet@51005
   129
open Sledgehammer_Fact
smolkas@52555
   130
open Sledgehammer_Reconstructor
smolkas@52555
   131
open Sledgehammer_Print
blanchet@49881
   132
open Sledgehammer_Reconstruct
blanchet@48288
   133
blanchet@37583
   134
blanchet@37583
   135
(** The Sledgehammer **)
blanchet@37583
   136
blanchet@54000
   137
(* Empty string means create files in Isabelle's temporary files directory. *)
blanchet@54094
   138
val dest_dir = Attrib.setup_config_string @{binding sledgehammer_dest_dir} (K "")
blanchet@54094
   139
val problem_prefix = Attrib.setup_config_string @{binding sledgehammer_problem_prefix} (K "prob")
blanchet@54094
   140
val completish = Attrib.setup_config_bool @{binding sledgehammer_completish} (K false)
blanchet@54000
   141
blanchet@54000
   142
(* In addition to being easier to read, readable names are often much shorter,
blanchet@54000
   143
   especially if types are mangled in names. This makes a difference for some
blanchet@54000
   144
   provers (e.g., E). For these reason, short names are enabled by default. *)
blanchet@54094
   145
val atp_full_names = Attrib.setup_config_bool @{binding sledgehammer_atp_full_names} (K false)
blanchet@54000
   146
blanchet@54094
   147
val smt_builtins = Attrib.setup_config_bool @{binding sledgehammer_smt_builtins} (K true)
blanchet@54094
   148
val smt_triggers = Attrib.setup_config_bool @{binding sledgehammer_smt_triggers} (K true)
blanchet@54094
   149
val smt_weights = Attrib.setup_config_bool @{binding sledgehammer_smt_weights} (K true)
blanchet@54000
   150
val smt_weight_min_facts =
blanchet@54000
   151
  Attrib.setup_config_int @{binding sledgehammer_smt_weight_min_facts} (K 20)
blanchet@54000
   152
wenzelm@53052
   153
datatype mode = Auto_Try | Try | Normal | MaSh | Auto_Minimize | Minimize
blanchet@43021
   154
blanchet@45376
   155
(* Identifier that distinguishes Sledgehammer from other tools that could use
blanchet@38102
   156
   "Async_Manager". *)
blanchet@48319
   157
val SledgehammerN = "Sledgehammer"
blanchet@37585
   158
blanchet@45520
   159
val reconstructor_names = [metisN, smtN]
blanchet@46365
   160
val plain_metis = Metis (hd partial_type_encs, combsN)
blanchet@45561
   161
val is_reconstructor = member (op =) reconstructor_names
blanchet@43228
   162
blanchet@43050
   163
val is_atp = member (op =) o supported_atps
blanchet@43050
   164
blanchet@43233
   165
val select_smt_solver = Context.proof_map o SMT_Config.select_solver
blanchet@41242
   166
blanchet@45376
   167
fun is_smt_prover ctxt = member (op =) (SMT_Solver.available_solvers_of ctxt)
blanchet@40062
   168
blanchet@51998
   169
fun is_atp_of_format is_format ctxt name =
blanchet@42944
   170
  let val thy = Proof_Context.theory_of ctxt in
blanchet@42944
   171
    case try (get_atp thy) name of
blanchet@47606
   172
      SOME config =>
blanchet@48716
   173
      exists (fn (_, ((_, format, _, _, _), _)) => is_format format)
blanchet@47606
   174
             (#best_slices (config ()) ctxt)
blanchet@42944
   175
    | NONE => false
blanchet@42944
   176
  end
blanchet@42944
   177
blanchet@51998
   178
val is_unit_equational_atp = is_atp_of_format (curry (op =) CNF_UEQ)
blanchet@51998
   179
val is_ho_atp = is_atp_of_format is_format_higher_order
blanchet@44597
   180
blanchet@45376
   181
fun is_prover_supported ctxt =
wenzelm@42361
   182
  let val thy = Proof_Context.theory_of ctxt in
blanchet@45379
   183
    is_reconstructor orf is_atp thy orf is_smt_prover ctxt
blanchet@40941
   184
  end
blanchet@40072
   185
boehmes@41432
   186
fun is_prover_installed ctxt =
blanchet@45379
   187
  is_reconstructor orf is_smt_prover ctxt orf
blanchet@43050
   188
  is_atp_installed (Proof_Context.theory_of ctxt)
blanchet@40941
   189
blanchet@51200
   190
fun remotify_prover_if_supported_and_not_already_remote ctxt name =
blanchet@51200
   191
  if String.isPrefix remote_prefix name then
blanchet@51200
   192
    SOME name
blanchet@51200
   193
  else
blanchet@51200
   194
    let val remote_name = remote_prefix ^ name in
blanchet@51200
   195
      if is_prover_supported ctxt remote_name then SOME remote_name else NONE
blanchet@51200
   196
    end
blanchet@51200
   197
blanchet@51200
   198
fun remotify_prover_if_not_installed ctxt name =
blanchet@51200
   199
  if is_prover_supported ctxt name andalso is_prover_installed ctxt name then
blanchet@51200
   200
    SOME name
blanchet@51200
   201
  else
blanchet@51200
   202
    remotify_prover_if_supported_and_not_already_remote ctxt name
blanchet@51200
   203
blanchet@45706
   204
fun get_slices slice slices =
blanchet@45706
   205
  (0 upto length slices - 1) ~~ slices |> not slice ? (List.last #> single)
blanchet@42443
   206
blanchet@48293
   207
val reconstructor_default_max_facts = 20
blanchet@43050
   208
blanchet@54125
   209
fun slice_max_facts (_, ( ((max_facts, _), _, _, _, _), _)) = max_facts
blanchet@51186
   210
blanchet@54126
   211
fun default_max_facts_of_prover ctxt name =
wenzelm@42361
   212
  let val thy = Proof_Context.theory_of ctxt in
blanchet@45379
   213
    if is_reconstructor name then
blanchet@48293
   214
      reconstructor_default_max_facts
blanchet@43050
   215
    else if is_atp thy name then
blanchet@54126
   216
      fold (Integer.max o slice_max_facts) (#best_slices (get_atp thy name ()) ctxt) 0
blanchet@43050
   217
    else (* is_smt_prover ctxt name *)
blanchet@43050
   218
      SMT_Solver.default_max_relevant ctxt name
blanchet@40941
   219
  end
blanchet@40063
   220
blanchet@42956
   221
fun is_if (@{const_name If}, _) = true
blanchet@42956
   222
  | is_if _ = false
blanchet@42956
   223
blanchet@42956
   224
(* Beware of "if and only if" (which is translated as such) and "If" (which is
blanchet@42956
   225
   translated to conditional equations). *)
blanchet@42956
   226
fun is_good_unit_equality T t u =
blanchet@42956
   227
  T <> @{typ bool} andalso not (exists (exists_Const is_if) [t, u])
blanchet@42956
   228
blanchet@42944
   229
fun is_unit_equality (@{const Trueprop} $ t) = is_unit_equality t
blanchet@42944
   230
  | is_unit_equality (Const (@{const_name all}, _) $ Abs (_, _, t)) =
blanchet@42944
   231
    is_unit_equality t
blanchet@42944
   232
  | is_unit_equality (Const (@{const_name All}, _) $ Abs (_, _, t)) =
blanchet@42944
   233
    is_unit_equality t
blanchet@42956
   234
  | is_unit_equality (Const (@{const_name "=="}, Type (_, [T, _])) $ t $ u) =
blanchet@42956
   235
    is_good_unit_equality T t u
blanchet@42956
   236
  | is_unit_equality (Const (@{const_name HOL.eq}, Type (_ , [T, _])) $ t $ u) =
blanchet@42956
   237
    is_good_unit_equality T t u
blanchet@42944
   238
  | is_unit_equality _ = false
blanchet@42944
   239
blanchet@51998
   240
fun is_appropriate_prop_of_prover ctxt name =
blanchet@42944
   241
  if is_unit_equational_atp ctxt name then is_unit_equality else K true
blanchet@42944
   242
blanchet@41727
   243
fun supported_provers ctxt =
blanchet@40060
   244
  let
wenzelm@42361
   245
    val thy = Proof_Context.theory_of ctxt
blanchet@40060
   246
    val (remote_provers, local_provers) =
blanchet@45520
   247
      reconstructor_names @
blanchet@41727
   248
      sort_strings (supported_atps thy) @
blanchet@41727
   249
      sort_strings (SMT_Solver.available_solvers_of ctxt)
blanchet@40060
   250
      |> List.partition (String.isPrefix remote_prefix)
blanchet@40060
   251
  in
blanchet@41727
   252
    Output.urgent_message ("Supported provers: " ^
blanchet@40205
   253
                           commas (local_provers @ remote_provers) ^ ".")
blanchet@40060
   254
  end
blanchet@35969
   255
blanchet@48319
   256
fun kill_provers () = Async_Manager.kill_threads SledgehammerN "prover"
blanchet@48319
   257
fun running_provers () = Async_Manager.running_threads SledgehammerN "prover"
blanchet@48319
   258
val messages = Async_Manager.thread_messages SledgehammerN "prover"
blanchet@40059
   259
blanchet@48288
   260
blanchet@40059
   261
(** problems, results, ATPs, etc. **)
blanchet@35969
   262
blanchet@35969
   263
type params =
blanchet@48321
   264
  {debug : bool,
blanchet@48321
   265
   verbose : bool,
blanchet@48321
   266
   overlord : bool,
blanchet@53800
   267
   spy : bool,
blanchet@48321
   268
   blocking : bool,
blanchet@48321
   269
   provers : string list,
blanchet@48321
   270
   type_enc : string option,
blanchet@48321
   271
   strict : bool,
blanchet@48321
   272
   lam_trans : string option,
blanchet@48321
   273
   uncurried_aliases : bool option,
blanchet@48321
   274
   learn : bool,
blanchet@48321
   275
   fact_filter : string option,
blanchet@48321
   276
   max_facts : int option,
blanchet@48321
   277
   fact_thresholds : real * real,
blanchet@48321
   278
   max_mono_iters : int option,
blanchet@48321
   279
   max_new_mono_instances : int option,
blanchet@51190
   280
   isar_proofs : bool option,
smolkas@51130
   281
   isar_compress : real,
smolkas@52632
   282
   isar_try0 : bool,
blanchet@48321
   283
   slice : bool,
blanchet@48321
   284
   minimize : bool option,
blanchet@50557
   285
   timeout : Time.time option,
blanchet@50557
   286
   preplay_timeout : Time.time option,
blanchet@48321
   287
   expect : string}
blanchet@35867
   288
blanchet@40061
   289
type prover_problem =
blanchet@54141
   290
  {comment : string,
blanchet@54141
   291
   state : Proof.state,
blanchet@48321
   292
   goal : thm,
blanchet@48321
   293
   subgoal : int,
blanchet@48321
   294
   subgoal_count : int,
blanchet@51010
   295
   factss : (string * fact list) list}
blanchet@35867
   296
blanchet@40061
   297
type prover_result =
blanchet@53586
   298
  {outcome : atp_failure option,
blanchet@48321
   299
   used_facts : (string * stature) list,
blanchet@51009
   300
   used_from : fact list,
blanchet@48321
   301
   run_time : Time.time,
blanchet@50669
   302
   preplay : play Lazy.lazy,
blanchet@48321
   303
   message : play -> string,
blanchet@48321
   304
   message_tail : string}
blanchet@35867
   305
blanchet@43051
   306
type prover =
blanchet@45520
   307
  params -> ((string * string list) list -> string -> minimize_command)
blanchet@45520
   308
  -> prover_problem -> prover_result
blanchet@35867
   309
blanchet@41256
   310
(* FUDGE *)
blanchet@42646
   311
val smt_min_weight =
blanchet@42646
   312
  Attrib.setup_config_int @{binding sledgehammer_smt_min_weight} (K 0)
blanchet@42646
   313
val smt_max_weight =
blanchet@42646
   314
  Attrib.setup_config_int @{binding sledgehammer_smt_max_weight} (K 10)
blanchet@42646
   315
val smt_max_weight_index =
blanchet@42646
   316
  Attrib.setup_config_int @{binding sledgehammer_smt_max_weight_index} (K 200)
blanchet@41256
   317
val smt_weight_curve = Unsynchronized.ref (fn x : int => x * x)
blanchet@41256
   318
blanchet@42646
   319
fun smt_fact_weight ctxt j num_facts =
blanchet@42646
   320
  if Config.get ctxt smt_weights andalso
blanchet@42646
   321
     num_facts >= Config.get ctxt smt_weight_min_facts then
blanchet@42646
   322
    let
blanchet@42646
   323
      val min = Config.get ctxt smt_min_weight
blanchet@42646
   324
      val max = Config.get ctxt smt_max_weight
blanchet@42646
   325
      val max_index = Config.get ctxt smt_max_weight_index
blanchet@42646
   326
      val curve = !smt_weight_curve
blanchet@42646
   327
    in
blanchet@42646
   328
      SOME (max - (max - min + 1) * curve (Int.max (0, max_index - j - 1))
blanchet@42646
   329
            div curve max_index)
blanchet@42646
   330
    end
blanchet@41256
   331
  else
blanchet@41256
   332
    NONE
blanchet@41256
   333
blanchet@42646
   334
fun weight_smt_fact ctxt num_facts ((info, th), j) =
blanchet@42646
   335
  let val thy = Proof_Context.theory_of ctxt in
blanchet@42646
   336
    (info, (smt_fact_weight ctxt j num_facts, th |> Thm.transfer thy))
blanchet@42646
   337
  end
blanchet@38023
   338
blanchet@51998
   339
fun overlord_file_location_of_prover prover =
blanchet@41313
   340
  (getenv "ISABELLE_HOME_USER", "prob_" ^ prover)
blanchet@41313
   341
blanchet@43052
   342
fun proof_banner mode name =
blanchet@43033
   343
  case mode of
blanchet@43033
   344
    Auto_Try => "Auto Sledgehammer (" ^ quote name ^ ") found a proof"
blanchet@43033
   345
  | Try => "Sledgehammer (" ^ quote name ^ ") found a proof"
blanchet@43052
   346
  | _ => "Try this"
blanchet@43033
   347
blanchet@45561
   348
fun bunch_of_reconstructors needs_full_types lam_trans =
blanchet@48800
   349
  if needs_full_types then
blanchet@48802
   350
    [Metis (full_type_enc, lam_trans false),
blanchet@48802
   351
     Metis (really_full_type_enc, lam_trans false),
blanchet@48802
   352
     Metis (full_type_enc, lam_trans true),
blanchet@48802
   353
     Metis (really_full_type_enc, lam_trans true),
blanchet@48802
   354
     SMT]
blanchet@48802
   355
  else
blanchet@48800
   356
    [Metis (partial_type_enc, lam_trans false),
blanchet@48800
   357
     Metis (full_type_enc, lam_trans false),
blanchet@48800
   358
     Metis (no_typesN, lam_trans true),
blanchet@48800
   359
     Metis (really_full_type_enc, lam_trans true),
blanchet@48800
   360
     SMT]
blanchet@45561
   361
blanchet@45561
   362
fun extract_reconstructor ({type_enc, lam_trans, ...} : params)
blanchet@45561
   363
                          (Metis (type_enc', lam_trans')) =
blanchet@45561
   364
    let
blanchet@45561
   365
      val override_params =
blanchet@45561
   366
        (if is_none type_enc andalso type_enc' = hd partial_type_encs then
blanchet@45561
   367
           []
blanchet@45561
   368
         else
blanchet@45566
   369
           [("type_enc", [hd (unalias_type_enc type_enc')])]) @
blanchet@45561
   370
        (if is_none lam_trans andalso lam_trans' = metis_default_lam_trans then
blanchet@45561
   371
           []
blanchet@45561
   372
         else
blanchet@45561
   373
           [("lam_trans", [lam_trans'])])
blanchet@45561
   374
    in (metisN, override_params) end
blanchet@45561
   375
  | extract_reconstructor _ SMT = (smtN, [])
blanchet@45561
   376
blanchet@43033
   377
(* based on "Mirabelle.can_apply" and generalized *)
blanchet@43034
   378
fun timed_apply timeout tac state i =
blanchet@43033
   379
  let
blanchet@43033
   380
    val {context = ctxt, facts, goal} = Proof.goal state
blanchet@43033
   381
    val full_tac = Method.insert_tac facts i THEN tac ctxt i
blanchet@50557
   382
  in time_limit timeout (try (Seq.pull o full_tac)) goal end
blanchet@43033
   383
blanchet@51998
   384
fun tac_of_reconstructor (Metis (type_enc, lam_trans)) =
blanchet@45521
   385
    metis_tac [type_enc] lam_trans
blanchet@51998
   386
  | tac_of_reconstructor SMT = SMT_Solver.smt_tac
blanchet@43034
   387
blanchet@45520
   388
fun timed_reconstructor reconstr debug timeout ths =
blanchet@44651
   389
  (Config.put Metis_Tactic.verbose debug
blanchet@45557
   390
   #> Config.put SMT_Config.verbose debug
blanchet@51998
   391
   #> (fn ctxt => tac_of_reconstructor reconstr ctxt ths))
blanchet@43034
   392
  |> timed_apply timeout
blanchet@43033
   393
blanchet@48798
   394
fun is_fact_chained ((_, (sc, _)), _) = sc = Chained
blanchet@48798
   395
blanchet@48798
   396
fun filter_used_facts keep_chained used =
blanchet@48798
   397
  filter ((member (op =) used o fst) orf
blanchet@48798
   398
          (if keep_chained then is_fact_chained else K false))
blanchet@43033
   399
blanchet@45781
   400
fun play_one_line_proof mode debug verbose timeout pairs state i preferred
blanchet@45520
   401
                        reconstrs =
blanchet@43034
   402
  let
blanchet@45520
   403
    fun get_preferred reconstrs =
blanchet@45520
   404
      if member (op =) reconstrs preferred then preferred
blanchet@45520
   405
      else List.last reconstrs
blanchet@43034
   406
  in
blanchet@50557
   407
    if timeout = SOME Time.zeroTime then
blanchet@45520
   408
      Trust_Playable (get_preferred reconstrs, NONE)
blanchet@45379
   409
    else
blanchet@50557
   410
      let
blanchet@50557
   411
        val _ =
blanchet@50557
   412
          if mode = Minimize then Output.urgent_message "Preplaying proof..."
blanchet@50557
   413
          else ()
blanchet@50557
   414
        val ths = pairs |> sort_wrt (fst o fst) |> map snd
blanchet@50557
   415
        fun play [] [] = Failed_to_Play (get_preferred reconstrs)
blanchet@50557
   416
          | play timed_outs [] =
blanchet@50557
   417
            Trust_Playable (get_preferred timed_outs, timeout)
blanchet@50557
   418
          | play timed_out (reconstr :: reconstrs) =
blanchet@50557
   419
            let
blanchet@50557
   420
              val _ =
blanchet@50557
   421
                if verbose then
blanchet@51998
   422
                  "Trying \"" ^ string_of_reconstructor reconstr ^ "\"" ^
blanchet@50557
   423
                  (case timeout of
blanchet@52031
   424
                     SOME timeout => " for " ^ string_of_time timeout
blanchet@50557
   425
                   | NONE => "") ^ "..."
blanchet@50557
   426
                  |> Output.urgent_message
blanchet@50557
   427
                else
blanchet@50557
   428
                  ()
blanchet@50557
   429
              val timer = Timer.startRealTimer ()
blanchet@50557
   430
            in
blanchet@50557
   431
              case timed_reconstructor reconstr debug timeout ths state i of
blanchet@50557
   432
                SOME (SOME _) => Played (reconstr, Timer.checkRealTimer timer)
blanchet@50557
   433
              | _ => play timed_out reconstrs
blanchet@50557
   434
            end
blanchet@50557
   435
            handle TimeLimit.TimeOut => play (reconstr :: timed_out) reconstrs
blanchet@50557
   436
      in play [] reconstrs end
blanchet@43033
   437
  end
blanchet@43033
   438
blanchet@41313
   439
blanchet@41256
   440
(* generic TPTP-based ATPs *)
blanchet@40061
   441
blanchet@42730
   442
(* Too general means, positive equality literal with a variable X as one
blanchet@42730
   443
   operand, when X does not occur properly in the other operand. This rules out
blanchet@42730
   444
   clearly inconsistent facts such as X = a | X = b, though it by no means
blanchet@42730
   445
   guarantees soundness. *)
blanchet@42730
   446
blanchet@51998
   447
fun get_facts_of_filter _ [(_, facts)] = facts
blanchet@51998
   448
  | get_facts_of_filter fact_filter factss =
blanchet@51013
   449
    case AList.lookup (op =) factss fact_filter of
blanchet@51013
   450
      SOME facts => facts
blanchet@51013
   451
    | NONE => snd (hd factss)
blanchet@51013
   452
blanchet@42730
   453
(* Unwanted equalities are those between a (bound or schematic) variable that
blanchet@42730
   454
   does not properly occur in the second operand. *)
blanchet@42730
   455
val is_exhaustive_finite =
blanchet@42730
   456
  let
blanchet@42730
   457
    fun is_bad_equal (Var z) t =
blanchet@42730
   458
        not (exists_subterm (fn Var z' => z = z' | _ => false) t)
blanchet@42730
   459
      | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
blanchet@42730
   460
      | is_bad_equal _ _ = false
blanchet@42730
   461
    fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
blanchet@42730
   462
    fun do_formula pos t =
blanchet@42730
   463
      case (pos, t) of
blanchet@42730
   464
        (_, @{const Trueprop} $ t1) => do_formula pos t1
blanchet@42730
   465
      | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
blanchet@42730
   466
        do_formula pos t'
blanchet@42730
   467
      | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
blanchet@42730
   468
        do_formula pos t'
blanchet@42730
   469
      | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
blanchet@42730
   470
        do_formula pos t'
blanchet@42730
   471
      | (_, @{const "==>"} $ t1 $ t2) =>
blanchet@42730
   472
        do_formula (not pos) t1 andalso
blanchet@42730
   473
        (t2 = @{prop False} orelse do_formula pos t2)
blanchet@42730
   474
      | (_, @{const HOL.implies} $ t1 $ t2) =>
blanchet@42730
   475
        do_formula (not pos) t1 andalso
blanchet@42730
   476
        (t2 = @{const False} orelse do_formula pos t2)
blanchet@42730
   477
      | (_, @{const Not} $ t1) => do_formula (not pos) t1
blanchet@42730
   478
      | (true, @{const HOL.disj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@42730
   479
      | (false, @{const HOL.conj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@42730
   480
      | (true, Const (@{const_name HOL.eq}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@42730
   481
      | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@42730
   482
      | _ => false
blanchet@42730
   483
  in do_formula true end
blanchet@42730
   484
blanchet@42730
   485
fun has_bound_or_var_of_type pred =
blanchet@42730
   486
  exists_subterm (fn Var (_, T as Type _) => pred T
blanchet@42730
   487
                   | Abs (_, T as Type _, _) => pred T
blanchet@42730
   488
                   | _ => false)
blanchet@42730
   489
blanchet@42730
   490
(* Facts are forbidden to contain variables of these types. The typical reason
blanchet@42730
   491
   is that they lead to unsoundness. Note that "unit" satisfies numerous
blanchet@42730
   492
   equations like "?x = ()". The resulting clauses will have no type constraint,
blanchet@42730
   493
   yielding false proofs. Even "bool" leads to many unsound proofs, though only
blanchet@42730
   494
   for higher-order problems. *)
blanchet@42730
   495
blanchet@42730
   496
(* Facts containing variables of type "unit" or "bool" or of the form
blanchet@42730
   497
   "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
blanchet@42730
   498
   are omitted. *)
blanchet@42944
   499
fun is_dangerous_prop ctxt =
blanchet@42944
   500
  transform_elim_prop
blanchet@44393
   501
  #> (has_bound_or_var_of_type (is_type_surely_finite ctxt) orf
blanchet@42730
   502
      is_exhaustive_finite)
blanchet@42730
   503
blanchet@39492
   504
(* Important messages are important but not so important that users want to see
blanchet@39492
   505
   them each time. *)
blanchet@44649
   506
val atp_important_message_keep_quotient = 25
blanchet@39492
   507
blanchet@44416
   508
fun choose_type_enc soundness best_type_enc format =
blanchet@44397
   509
  the_default best_type_enc
blanchet@52031
   510
  #> type_enc_of_string soundness
blanchet@44416
   511
  #> adjust_type_enc format
blanchet@42548
   512
blanchet@51200
   513
fun isar_proof_reconstructor ctxt name =
blanchet@51200
   514
  let val thy = Proof_Context.theory_of ctxt in
blanchet@51200
   515
    if is_atp thy name then name
blanchet@51200
   516
    else remotify_prover_if_not_installed ctxt eN |> the_default name
blanchet@51200
   517
  end
blanchet@43051
   518
blanchet@51200
   519
(* See the analogous logic in the function "maybe_minimize" in
blanchet@51200
   520
  "sledgehammer_minimize.ML". *)
blanchet@51200
   521
fun choose_minimize_command ctxt (params as {isar_proofs, ...}) minimize_command
blanchet@51200
   522
                            name preplay =
blanchet@45520
   523
  let
blanchet@51200
   524
    val maybe_isar_name =
blanchet@51200
   525
      name |> isar_proofs = SOME true ? isar_proof_reconstructor ctxt
blanchet@51200
   526
    val (min_name, override_params) =
blanchet@45520
   527
      case preplay of
blanchet@51200
   528
        Played (reconstr, _) =>
blanchet@51200
   529
        if isar_proofs = SOME true then (maybe_isar_name, [])
blanchet@51200
   530
        else extract_reconstructor params reconstr
blanchet@51200
   531
      | _ => (maybe_isar_name, [])
blanchet@51200
   532
  in minimize_command override_params min_name end
blanchet@43051
   533
blanchet@53480
   534
val max_fact_instances = 10 (* FUDGE *)
blanchet@53480
   535
blanchet@52034
   536
fun repair_monomorph_context max_iters best_max_iters max_new_instances
blanchet@52034
   537
                             best_max_new_instances =
blanchet@52034
   538
  Config.put Monomorph.max_rounds (max_iters |> the_default best_max_iters)
blanchet@52034
   539
  #> Config.put Monomorph.max_new_instances
blanchet@52034
   540
         (max_new_instances |> the_default best_max_new_instances)
blanchet@53480
   541
  #> Config.put Monomorph.max_thm_instances max_fact_instances
blanchet@52034
   542
blanchet@51998
   543
fun suffix_of_mode Auto_Try = "_try"
blanchet@51998
   544
  | suffix_of_mode Try = "_try"
blanchet@51998
   545
  | suffix_of_mode Normal = ""
blanchet@51998
   546
  | suffix_of_mode MaSh = ""
blanchet@51998
   547
  | suffix_of_mode Auto_Minimize = "_min"
blanchet@51998
   548
  | suffix_of_mode Minimize = "_min"
blanchet@44509
   549
blanchet@44423
   550
(* Give the ATPs some slack before interrupting them the hard way. "z3_tptp" on
blanchet@43631
   551
   Linux appears to be the only ATP that does not honor its time limit. *)
blanchet@43690
   552
val atp_timeout_slack = seconds 1.0
blanchet@43631
   553
blanchet@48331
   554
val mono_max_privileged_facts = 10
blanchet@48331
   555
blanchet@51186
   556
(* For low values of "max_facts", this fudge value ensures that most slices are
blanchet@51186
   557
   invoked with a nontrivial amount of facts. *)
blanchet@51186
   558
val max_fact_factor_fudge = 5
blanchet@51186
   559
blanchet@43021
   560
fun run_atp mode name
blanchet@48376
   561
        ({exec, arguments, proof_delims, known_failures, prem_role, best_slices,
blanchet@48376
   562
          best_max_mono_iters, best_max_new_mono_instances, ...} : atp_config)
blanchet@46301
   563
        (params as {debug, verbose, overlord, type_enc, strict, lam_trans,
blanchet@51024
   564
                    uncurried_aliases, fact_filter, max_facts, max_mono_iters,
smolkas@51130
   565
                    max_new_mono_instances, isar_proofs, isar_compress,
blanchet@53764
   566
                    isar_try0, slice, timeout, preplay_timeout, ...})
blanchet@43037
   567
        minimize_command
blanchet@54141
   568
        ({comment, state, goal, subgoal, subgoal_count, factss, ...} : prover_problem) =
blanchet@38023
   569
  let
blanchet@42182
   570
    val thy = Proof.theory_of state
blanchet@39318
   571
    val ctxt = Proof.context_of state
blanchet@47946
   572
    val atp_mode =
blanchet@48143
   573
      if Config.get ctxt completish then Sledgehammer_Completish
blanchet@47946
   574
      else Sledgehammer
blanchet@52196
   575
    val (_, hyp_ts, concl_t) = strip_subgoal goal subgoal ctxt
blanchet@41159
   576
    val (dest_dir, problem_prefix) =
blanchet@51998
   577
      if overlord then overlord_file_location_of_prover name
blanchet@41159
   578
      else (Config.get ctxt dest_dir, Config.get ctxt problem_prefix)
blanchet@40061
   579
    val problem_file_name =
blanchet@41159
   580
      Path.basic (problem_prefix ^ (if overlord then "" else serial_string ()) ^
blanchet@51998
   581
                  suffix_of_mode mode ^ "_" ^ string_of_int subgoal)
blanchet@48656
   582
    val prob_path =
blanchet@40059
   583
      if dest_dir = "" then
blanchet@40061
   584
        File.tmp_path problem_file_name
blanchet@40059
   585
      else if File.exists (Path.explode dest_dir) then
blanchet@40061
   586
        Path.append (Path.explode dest_dir) problem_file_name
blanchet@39003
   587
      else
blanchet@40059
   588
        error ("No such directory: " ^ quote dest_dir ^ ".")
blanchet@52754
   589
    val exec = exec ()
blanchet@48376
   590
    val command0 =
blanchet@47055
   591
      case find_first (fn var => getenv var <> "") (fst exec) of
blanchet@48376
   592
        SOME var =>
blanchet@48376
   593
        let
blanchet@48376
   594
          val pref = getenv var ^ "/"
blanchet@48376
   595
          val paths = map (Path.explode o prefix pref) (snd exec)
blanchet@48376
   596
        in
blanchet@48376
   597
          case find_first File.exists paths of
blanchet@48376
   598
            SOME path => path
blanchet@48376
   599
          | NONE => error ("Bad executable: " ^ Path.print (hd paths) ^ ".")
blanchet@48376
   600
        end
blanchet@53989
   601
      | NONE => error ("The environment variable " ^ quote (List.last (fst exec)) ^
blanchet@47055
   602
                       " is not set.")
blanchet@38023
   603
    fun split_time s =
blanchet@38023
   604
      let
blanchet@42448
   605
        val split = String.tokens (fn c => str c = "\n")
blanchet@47737
   606
        val (output, t) =
blanchet@47737
   607
          s |> split |> (try split_last #> the_default ([], "0"))
blanchet@47737
   608
            |>> cat_lines
blanchet@42448
   609
        fun as_num f = f >> (fst o read_int)
blanchet@42448
   610
        val num = as_num (Scan.many1 Symbol.is_ascii_digit)
blanchet@42448
   611
        val digit = Scan.one Symbol.is_ascii_digit
blanchet@42448
   612
        val num3 = as_num (digit ::: digit ::: (digit >> single))
blanchet@42448
   613
        val time = num --| Scan.$$ "." -- num3 >> (fn (a, b) => a * 1000 + b)
blanchet@45381
   614
        val as_time =
blanchet@45381
   615
          raw_explode #> Scan.read Symbol.stopper time #> the_default 0
blanchet@47737
   616
      in (output, as_time t |> Time.fromMilliseconds) end
blanchet@48656
   617
    fun run () =
blanchet@48376
   618
      let
blanchet@48376
   619
        (* If slicing is disabled, we expand the last slice to fill the entire
blanchet@48376
   620
           time available. *)
blanchet@54125
   621
        val all_slices = best_slices ctxt
blanchet@54125
   622
        val actual_slices = get_slices slice all_slices
blanchet@54125
   623
        fun max_facts_of_slices f slices = fold (Integer.max o slice_max_facts o f) slices 0
blanchet@48376
   624
        val num_actual_slices = length actual_slices
blanchet@51186
   625
        val max_fact_factor =
blanchet@54125
   626
          Real.fromInt (case max_facts of
blanchet@54125
   627
              NONE => max_facts_of_slices I all_slices
blanchet@54125
   628
            | SOME max => max)
blanchet@54125
   629
          / Real.fromInt (max_facts_of_slices snd actual_slices)
blanchet@48376
   630
        fun monomorphize_facts facts =
blanchet@48376
   631
          let
blanchet@48376
   632
            val ctxt =
blanchet@48376
   633
              ctxt
blanchet@53478
   634
              |> repair_monomorph_context max_mono_iters
blanchet@52034
   635
                     best_max_mono_iters max_new_mono_instances
blanchet@52034
   636
                     best_max_new_mono_instances
blanchet@48376
   637
            (* pseudo-theorem involving the same constants as the subgoal *)
blanchet@48376
   638
            val subgoal_th =
blanchet@48376
   639
              Logic.list_implies (hyp_ts, concl_t) |> Skip_Proof.make_thm thy
blanchet@48376
   640
            val rths =
blanchet@48376
   641
              facts |> chop mono_max_privileged_facts
blanchet@48376
   642
                    |>> map (pair 1 o snd)
blanchet@48376
   643
                    ||> map (pair 2 o snd)
blanchet@48376
   644
                    |> op @
blanchet@48376
   645
                    |> cons (0, subgoal_th)
blanchet@48376
   646
          in
blanchet@53478
   647
            Monomorph.monomorph atp_schematic_consts_of ctxt rths
blanchet@53478
   648
            |> tl |> curry ListPair.zip (map fst facts)
blanchet@48376
   649
            |> maps (fn (name, rths) =>
blanchet@48376
   650
                        map (pair name o zero_var_indexes o snd) rths)
blanchet@48376
   651
          end
blanchet@48376
   652
        fun run_slice time_left (cache_key, cache_value)
blanchet@48716
   653
                (slice, (time_frac,
blanchet@51011
   654
                     (key as ((best_max_facts, best_fact_filter), format,
blanchet@51011
   655
                              best_type_enc, best_lam_trans,
blanchet@51011
   656
                              best_uncurried_aliases),
blanchet@48716
   657
                      extra))) =
blanchet@38032
   658
          let
blanchet@51024
   659
            val effective_fact_filter =
blanchet@51024
   660
              fact_filter |> the_default best_fact_filter
blanchet@51998
   661
            val facts = get_facts_of_filter effective_fact_filter factss
blanchet@48376
   662
            val num_facts =
blanchet@51186
   663
              Real.ceil (max_fact_factor * Real.fromInt best_max_facts) +
blanchet@51186
   664
              max_fact_factor_fudge
blanchet@51186
   665
              |> Integer.min (length facts)
blanchet@48376
   666
            val soundness = if strict then Strict else Non_Strict
blanchet@48376
   667
            val type_enc =
blanchet@48376
   668
              type_enc |> choose_type_enc soundness best_type_enc format
blanchet@48376
   669
            val sound = is_type_enc_sound type_enc
blanchet@48376
   670
            val real_ms = Real.fromInt o Time.toMilliseconds
blanchet@48376
   671
            val slice_timeout =
blanchet@50557
   672
              case time_left of
blanchet@50557
   673
                SOME time_left =>
blanchet@50557
   674
                ((real_ms time_left
blanchet@50557
   675
                  |> (if slice < num_actual_slices - 1 then
blanchet@50557
   676
                        curry Real.min (time_frac * real_ms (the timeout))
blanchet@50557
   677
                      else
blanchet@50557
   678
                        I))
blanchet@50557
   679
                 * 0.001)
blanchet@50557
   680
                |> seconds |> SOME
blanchet@50557
   681
              | NONE => NONE
blanchet@48376
   682
            val generous_slice_timeout =
blanchet@50558
   683
              if mode = MaSh then NONE
blanchet@50558
   684
              else Option.map (curry Time.+ atp_timeout_slack) slice_timeout
blanchet@48376
   685
            val _ =
blanchet@48376
   686
              if debug then
blanchet@48376
   687
                quote name ^ " slice #" ^ string_of_int (slice + 1) ^
blanchet@48376
   688
                " with " ^ string_of_int num_facts ^ " fact" ^
blanchet@50557
   689
                plural_s num_facts ^
blanchet@50557
   690
                (case slice_timeout of
blanchet@52031
   691
                   SOME timeout => " for " ^ string_of_time timeout
blanchet@50557
   692
                 | NONE => "") ^ "..."
blanchet@48376
   693
                |> Output.urgent_message
blanchet@48376
   694
              else
blanchet@48376
   695
                ()
blanchet@48376
   696
            val readable_names = not (Config.get ctxt atp_full_names)
blanchet@48376
   697
            val lam_trans =
blanchet@48376
   698
              case lam_trans of
blanchet@48376
   699
                SOME s => s
blanchet@48376
   700
              | NONE => best_lam_trans
blanchet@48376
   701
            val uncurried_aliases =
blanchet@48376
   702
              case uncurried_aliases of
blanchet@48376
   703
                SOME b => b
blanchet@48376
   704
              | NONE => best_uncurried_aliases
blanchet@48376
   705
            val value as (atp_problem, _, fact_names, _, _) =
blanchet@48376
   706
              if cache_key = SOME key then
blanchet@48376
   707
                cache_value
blanchet@48376
   708
              else
blanchet@48376
   709
                facts
blanchet@48376
   710
                |> not sound
blanchet@48376
   711
                   ? filter_out (is_dangerous_prop ctxt o prop_of o snd)
blanchet@48376
   712
                |> take num_facts
blanchet@48376
   713
                |> not (is_type_enc_polymorphic type_enc) ? monomorphize_facts
blanchet@48376
   714
                |> map (apsnd prop_of)
blanchet@48376
   715
                |> prepare_atp_problem ctxt format prem_role type_enc atp_mode
blanchet@48376
   716
                                       lam_trans uncurried_aliases
blanchet@48376
   717
                                       readable_names true hyp_ts concl_t
blanchet@48376
   718
            fun sel_weights () = atp_problem_selection_weights atp_problem
blanchet@48376
   719
            fun ord_info () = atp_problem_term_order_info atp_problem
blanchet@48376
   720
            val ord = effective_term_order ctxt name
blanchet@53492
   721
            val full_proof = isar_proofs |> the_default (mode = Minimize)
blanchet@50927
   722
            val args =
blanchet@50927
   723
              arguments ctxt full_proof extra
blanchet@50927
   724
                        (slice_timeout |> the_default one_day)
blanchet@50927
   725
                        (File.shell_path prob_path) (ord, ord_info, sel_weights)
blanchet@48376
   726
            val command =
blanchet@50927
   727
              "(exec 2>&1; " ^ File.shell_path command0 ^ " " ^ args ^ " " ^ ")"
blanchet@48532
   728
              |> enclose "TIMEFORMAT='%3R'; { time " " ; }"
blanchet@48376
   729
            val _ =
blanchet@48376
   730
              atp_problem
blanchet@51998
   731
              |> lines_of_atp_problem format ord ord_info
blanchet@54141
   732
              |> cons ("% " ^ command ^ "\n" ^
blanchet@54141
   733
                (if comment = "" then "" else "% " ^ comment ^ "\n"))
blanchet@48656
   734
              |> File.write_list prob_path
blanchet@52034
   735
            val ((output, run_time), (atp_proof, outcome)) =
blanchet@50557
   736
              time_limit generous_slice_timeout Isabelle_System.bash_output
blanchet@50557
   737
                         command
blanchet@48376
   738
              |>> (if overlord then
blanchet@48376
   739
                     prefix ("% " ^ command ^ "\n% " ^ timestamp () ^ "\n")
blanchet@48376
   740
                   else
blanchet@48376
   741
                     I)
blanchet@48376
   742
              |> fst |> split_time
blanchet@48376
   743
              |> (fn accum as (output, _) =>
blanchet@52034
   744
                     (accum,
blanchet@48716
   745
                      extract_tstplike_proof_and_outcome verbose proof_delims
blanchet@48716
   746
                                                         known_failures output
blanchet@52031
   747
                      |>> atp_proof_of_tstplike_proof atp_problem
blanchet@48376
   748
                      handle UNRECOGNIZED_ATP_PROOF () =>
blanchet@48376
   749
                             ([], SOME ProofIncomplete)))
blanchet@48376
   750
              handle TimeLimit.TimeOut =>
blanchet@52034
   751
                     (("", the slice_timeout), ([], SOME TimedOut))
blanchet@48376
   752
            val outcome =
blanchet@48376
   753
              case outcome of
blanchet@48376
   754
                NONE =>
blanchet@48376
   755
                (case used_facts_in_unsound_atp_proof ctxt fact_names atp_proof
blanchet@48376
   756
                      |> Option.map (sort string_ord) of
blanchet@48376
   757
                   SOME facts =>
blanchet@48376
   758
                   let
blanchet@48376
   759
                     val failure =
blanchet@48376
   760
                       UnsoundProof (is_type_enc_sound type_enc, facts)
blanchet@48376
   761
                   in
blanchet@53586
   762
                     if debug then
blanchet@53586
   763
                       (warning (string_of_atp_failure failure); NONE)
blanchet@53586
   764
                     else
blanchet@53586
   765
                       SOME failure
blanchet@48376
   766
                   end
blanchet@48376
   767
                 | NONE => NONE)
blanchet@48376
   768
              | _ => outcome
blanchet@51013
   769
          in
blanchet@51013
   770
            ((SOME key, value), (output, run_time, facts, atp_proof, outcome))
blanchet@51013
   771
          end
blanchet@48376
   772
        val timer = Timer.startRealTimer ()
blanchet@48376
   773
        fun maybe_run_slice slice
blanchet@51013
   774
                (result as (cache, (_, run_time0, _, _, SOME _))) =
blanchet@48376
   775
            let
blanchet@50557
   776
              val time_left =
blanchet@50557
   777
                Option.map
blanchet@50557
   778
                    (fn timeout => Time.- (timeout, Timer.checkRealTimer timer))
blanchet@50557
   779
                    timeout
blanchet@48376
   780
            in
blanchet@50557
   781
              if time_left <> NONE andalso
blanchet@50557
   782
                 Time.<= (the time_left, Time.zeroTime) then
blanchet@48376
   783
                result
blanchet@48376
   784
              else
blanchet@48376
   785
                run_slice time_left cache slice
blanchet@51013
   786
                |> (fn (cache, (output, run_time, used_from, atp_proof,
blanchet@51013
   787
                                outcome)) =>
blanchet@51013
   788
                       (cache, (output, Time.+ (run_time0, run_time), used_from,
blanchet@48376
   789
                                atp_proof, outcome)))
blanchet@48376
   790
            end
blanchet@48376
   791
          | maybe_run_slice _ result = result
blanchet@48376
   792
      in
blanchet@48376
   793
        ((NONE, ([], Symtab.empty, Vector.fromList [], [], Symtab.empty)),
blanchet@51013
   794
         ("", Time.zeroTime, [], [], SOME InternalError))
blanchet@48376
   795
        |> fold maybe_run_slice actual_slices
blanchet@48376
   796
      end
blanchet@38023
   797
    (* If the problem file has not been exported, remove it; otherwise, export
blanchet@38023
   798
       the proof file too. *)
blanchet@48656
   799
    fun clean_up () =
blanchet@48656
   800
      if dest_dir = "" then (try File.rm prob_path; ()) else ()
blanchet@51013
   801
    fun export (_, (output, _, _, _, _)) =
blanchet@48376
   802
      if dest_dir = "" then ()
blanchet@48656
   803
      else File.write (Path.explode (Path.implode prob_path ^ "_proof")) output
blanchet@52150
   804
    val ((_, (_, pool, fact_names, lifted, sym_tab)),
blanchet@51013
   805
         (output, run_time, used_from, atp_proof, outcome)) =
blanchet@48656
   806
      with_cleanup clean_up run () |> tap export
blanchet@39492
   807
    val important_message =
wenzelm@53052
   808
      if mode = Normal andalso random_range 0 (atp_important_message_keep_quotient - 1) = 0
wenzelm@53052
   809
      then
blanchet@39492
   810
        extract_important_message output
blanchet@39492
   811
      else
blanchet@39492
   812
        ""
blanchet@43261
   813
    val (used_facts, preplay, message, message_tail) =
blanchet@38023
   814
      case outcome of
blanchet@38023
   815
        NONE =>
blanchet@43033
   816
        let
blanchet@45551
   817
          val used_facts = used_facts_in_atp_proof ctxt fact_names atp_proof
blanchet@45590
   818
          val needs_full_types = is_typed_helper_used_in_atp_proof atp_proof
blanchet@45521
   819
          val reconstrs =
blanchet@45554
   820
            bunch_of_reconstructors needs_full_types
blanchet@52031
   821
                (lam_trans_of_atp_proof atp_proof
blanchet@46405
   822
                 o (fn desperate => if desperate then hide_lamsN
blanchet@46405
   823
                                    else metis_default_lam_trans))
blanchet@43033
   824
        in
blanchet@43052
   825
          (used_facts,
blanchet@50669
   826
           Lazy.lazy (fn () =>
blanchet@50669
   827
             let
blanchet@50669
   828
               val used_pairs =
blanchet@51013
   829
                 used_from |> filter_used_facts false used_facts
blanchet@50669
   830
             in
blanchet@50669
   831
               play_one_line_proof mode debug verbose preplay_timeout
blanchet@50669
   832
                   used_pairs state subgoal (hd reconstrs) reconstrs
blanchet@50669
   833
             end),
blanchet@43052
   834
           fn preplay =>
blanchet@43052
   835
              let
blanchet@49921
   836
                val _ =
blanchet@49921
   837
                  if verbose then
blanchet@51232
   838
                    Output.urgent_message "Generating proof text..."
blanchet@49921
   839
                  else
blanchet@49921
   840
                    ()
blanchet@43052
   841
                val isar_params =
blanchet@53763
   842
                  (debug, verbose, preplay_timeout, isar_compress, isar_try0,
blanchet@53764
   843
                   pool, fact_names, lifted, sym_tab, atp_proof, goal)
blanchet@43052
   844
                val one_line_params =
blanchet@43052
   845
                  (preplay, proof_banner mode name, used_facts,
blanchet@51200
   846
                   choose_minimize_command ctxt params minimize_command name
blanchet@51200
   847
                                           preplay,
blanchet@43052
   848
                   subgoal, subgoal_count)
blanchet@48799
   849
                val num_chained = length (#facts (Proof.goal state))
blanchet@48799
   850
              in
wenzelm@53052
   851
                proof_text ctxt isar_proofs isar_params
blanchet@52754
   852
                           num_chained one_line_params
blanchet@48799
   853
              end,
blanchet@43261
   854
           (if verbose then
blanchet@52031
   855
              "\nATP real CPU time: " ^ string_of_time run_time ^ "."
blanchet@43261
   856
            else
blanchet@43261
   857
              "") ^
blanchet@43261
   858
           (if important_message <> "" then
blanchet@43261
   859
              "\n\nImportant message from Dr. Geoff Sutcliffe:\n" ^
blanchet@43261
   860
              important_message
blanchet@43261
   861
            else
blanchet@43261
   862
              ""))
blanchet@43033
   863
        end
blanchet@43052
   864
      | SOME failure =>
blanchet@50669
   865
        ([], Lazy.value (Failed_to_Play plain_metis),
blanchet@53586
   866
         fn _ => string_of_atp_failure failure, "")
blanchet@38023
   867
  in
blanchet@51013
   868
    {outcome = outcome, used_facts = used_facts, used_from = used_from,
blanchet@51009
   869
     run_time = run_time, preplay = preplay, message = message,
blanchet@51009
   870
     message_tail = message_tail}
blanchet@38023
   871
  end
blanchet@38023
   872
blanchet@51014
   873
fun rotate_one (x :: xs) = xs @ [x]
blanchet@51014
   874
blanchet@40669
   875
(* "SMT_Failure.Abnormal_Termination" carries the solver's return code. Until
blanchet@40669
   876
   these are sorted out properly in the SMT module, we have to interpret these
blanchet@40669
   877
   ourselves. *)
blanchet@40684
   878
val remote_smt_failures =
blanchet@43631
   879
  [(2, NoLibwwwPerl),
blanchet@43631
   880
   (22, CantConnect)]
blanchet@40684
   881
val z3_failures =
blanchet@41236
   882
  [(101, OutOfResources),
blanchet@41236
   883
   (103, MalformedInput),
blanchet@50667
   884
   (110, MalformedInput),
blanchet@50667
   885
   (112, TimedOut)]
blanchet@40684
   886
val unix_failures =
blanchet@48797
   887
  [(138, Crashed),
blanchet@48797
   888
   (139, Crashed)]
blanchet@43631
   889
val smt_failures = remote_smt_failures @ z3_failures @ unix_failures
blanchet@40555
   890
blanchet@52031
   891
fun failure_of_smt_failure (SMT_Failure.Counterexample {is_real_cex, ...}) =
blanchet@43050
   892
    if is_real_cex then Unprovable else GaveUp
blanchet@52031
   893
  | failure_of_smt_failure SMT_Failure.Time_Out = TimedOut
blanchet@52031
   894
  | failure_of_smt_failure (SMT_Failure.Abnormal_Termination code) =
blanchet@41222
   895
    (case AList.lookup (op =) smt_failures code of
blanchet@40684
   896
       SOME failure => failure
blanchet@41259
   897
     | NONE => UnknownError ("Abnormal termination with exit code " ^
blanchet@41259
   898
                             string_of_int code ^ "."))
blanchet@52031
   899
  | failure_of_smt_failure SMT_Failure.Out_Of_Memory = OutOfResources
blanchet@52031
   900
  | failure_of_smt_failure (SMT_Failure.Other_Failure s) = UnknownError s
blanchet@40063
   901
blanchet@40698
   902
(* FUDGE *)
blanchet@42646
   903
val smt_max_slices =
blanchet@42646
   904
  Attrib.setup_config_int @{binding sledgehammer_smt_max_slices} (K 8)
blanchet@42646
   905
val smt_slice_fact_frac =
blanchet@51014
   906
  Attrib.setup_config_real @{binding sledgehammer_smt_slice_fact_frac}
blanchet@51014
   907
                           (K 0.667)
blanchet@42646
   908
val smt_slice_time_frac =
blanchet@51014
   909
  Attrib.setup_config_real @{binding sledgehammer_smt_slice_time_frac} (K 0.333)
blanchet@42646
   910
val smt_slice_min_secs =
blanchet@51014
   911
  Attrib.setup_config_int @{binding sledgehammer_smt_slice_min_secs} (K 3)
blanchet@40409
   912
blanchet@54000
   913
val is_boring_builtin_typ =
blanchet@54000
   914
  not o exists_subtype (member (op =) [@{typ nat}, @{typ int}, HOLogic.realT])
blanchet@54000
   915
blanchet@54089
   916
fun smt_filter_loop name ({debug, overlord, max_mono_iters, max_new_mono_instances, timeout, slice,
blanchet@54089
   917
      ...} : params) state goal i =
blanchet@40409
   918
  let
blanchet@50759
   919
    fun repair_context ctxt =
blanchet@50759
   920
      ctxt |> select_smt_solver name
blanchet@50759
   921
           |> Config.put SMT_Config.verbose debug
blanchet@50759
   922
           |> (if overlord then
blanchet@50759
   923
                 Config.put SMT_Config.debug_files
blanchet@51998
   924
                            (overlord_file_location_of_prover name
blanchet@50759
   925
                             |> (fn (path, name) => path ^ "/" ^ name))
blanchet@50759
   926
               else
blanchet@50759
   927
                 I)
blanchet@50759
   928
           |> Config.put SMT_Config.infer_triggers
blanchet@50759
   929
                         (Config.get ctxt smt_triggers)
blanchet@54094
   930
           |> not (Config.get ctxt smt_builtins)
blanchet@54000
   931
              ? (SMT_Builtin.filter_builtins is_boring_builtin_typ
blanchet@54000
   932
                 #> Config.put SMT_Config.datatypes false)
blanchet@52034
   933
           |> repair_monomorph_context max_mono_iters default_max_mono_iters
blanchet@52034
   934
                  max_new_mono_instances default_max_new_mono_instances
blanchet@52034
   935
    val state = Proof.map_context (repair_context) state
blanchet@52034
   936
    val ctxt = Proof.context_of state
blanchet@45706
   937
    val max_slices = if slice then Config.get ctxt smt_max_slices else 1
blanchet@51024
   938
    fun do_slice timeout slice outcome0 time_so_far
blanchet@51024
   939
                 (weighted_factss as (fact_filter, weighted_facts) :: _) =
blanchet@40553
   940
      let
blanchet@40553
   941
        val timer = Timer.startRealTimer ()
blanchet@42443
   942
        val slice_timeout =
blanchet@50557
   943
          if slice < max_slices andalso timeout <> NONE then
blanchet@50557
   944
            let val ms = timeout |> the |> Time.toMilliseconds in
blanchet@50557
   945
              Int.min (ms,
blanchet@50557
   946
                  Int.max (1000 * Config.get ctxt smt_slice_min_secs,
blanchet@50557
   947
                      Real.ceil (Config.get ctxt smt_slice_time_frac
blanchet@50557
   948
                                 * Real.fromInt ms)))
blanchet@50557
   949
              |> Time.fromMilliseconds |> SOME
blanchet@50557
   950
            end
blanchet@40553
   951
          else
blanchet@40553
   952
            timeout
blanchet@51009
   953
        val num_facts = length weighted_facts
blanchet@40553
   954
        val _ =
blanchet@42614
   955
          if debug then
blanchet@42614
   956
            quote name ^ " slice " ^ string_of_int slice ^ " with " ^
blanchet@50557
   957
            string_of_int num_facts ^ " fact" ^ plural_s num_facts ^
blanchet@50557
   958
            (case slice_timeout of
blanchet@52031
   959
               SOME timeout => " for " ^ string_of_time timeout
blanchet@50557
   960
             | NONE => "") ^ "..."
blanchet@40553
   961
            |> Output.urgent_message
blanchet@40553
   962
          else
blanchet@40553
   963
            ()
blanchet@41168
   964
        val birth = Timer.checkRealTimer timer
blanchet@41171
   965
        val _ =
blanchet@41211
   966
          if debug then Output.urgent_message "Invoking SMT solver..." else ()
blanchet@41209
   967
        val (outcome, used_facts) =
blanchet@51204
   968
          SMT_Solver.smt_filter_preprocess ctxt [] goal weighted_facts i
blanchet@50557
   969
          |> SMT_Solver.smt_filter_apply (slice_timeout |> the_default one_day)
blanchet@41239
   970
          |> (fn {outcome, used_facts} => (outcome, used_facts))
blanchet@41209
   971
          handle exn => if Exn.is_interrupt exn then
blanchet@41209
   972
                          reraise exn
blanchet@41209
   973
                        else
blanchet@42061
   974
                          (ML_Compiler.exn_message exn
blanchet@41209
   975
                           |> SMT_Failure.Other_Failure |> SOME, [])
blanchet@41168
   976
        val death = Timer.checkRealTimer timer
blanchet@40553
   977
        val outcome0 = if is_none outcome0 then SOME outcome else outcome0
blanchet@41168
   978
        val time_so_far = Time.+ (time_so_far, Time.- (death, birth))
blanchet@40553
   979
        val too_many_facts_perhaps =
blanchet@40553
   980
          case outcome of
blanchet@40553
   981
            NONE => false
blanchet@40553
   982
          | SOME (SMT_Failure.Counterexample _) => false
blanchet@42443
   983
          | SOME SMT_Failure.Time_Out => slice_timeout <> timeout
blanchet@42614
   984
          | SOME (SMT_Failure.Abnormal_Termination _) => true (* kind of *)
blanchet@40553
   985
          | SOME SMT_Failure.Out_Of_Memory => true
blanchet@41211
   986
          | SOME (SMT_Failure.Other_Failure _) => true
blanchet@50557
   987
        val timeout =
blanchet@50557
   988
          Option.map
blanchet@50557
   989
              (fn timeout => Time.- (timeout, Timer.checkRealTimer timer))
blanchet@50557
   990
              timeout
blanchet@40553
   991
      in
blanchet@42443
   992
        if too_many_facts_perhaps andalso slice < max_slices andalso
blanchet@50557
   993
           num_facts > 0 andalso
blanchet@50557
   994
           (timeout = NONE orelse Time.> (the timeout, Time.zeroTime)) then
blanchet@41169
   995
          let
blanchet@42614
   996
            val new_num_facts =
blanchet@42646
   997
              Real.ceil (Config.get ctxt smt_slice_fact_frac
blanchet@42646
   998
                         * Real.fromInt num_facts)
blanchet@51024
   999
            val weighted_factss as (new_fact_filter, _) :: _ =
blanchet@51024
  1000
              weighted_factss
blanchet@51024
  1001
              |> rotate_one
blanchet@51024
  1002
              |> app_hd (apsnd (take new_num_facts))
blanchet@51024
  1003
            val show_filter = fact_filter <> new_fact_filter
blanchet@51024
  1004
            fun num_of_facts fact_filter num_facts =
blanchet@51024
  1005
              string_of_int num_facts ^
blanchet@51024
  1006
              (if show_filter then " " ^ quote fact_filter else "") ^
blanchet@51024
  1007
              " fact" ^ plural_s num_facts
blanchet@42614
  1008
            val _ =
blanchet@53500
  1009
              if debug then
blanchet@51024
  1010
                quote name ^ " invoked with " ^
blanchet@51024
  1011
                num_of_facts fact_filter num_facts ^ ": " ^
blanchet@53586
  1012
                string_of_atp_failure (failure_of_smt_failure (the outcome)) ^
blanchet@51024
  1013
                " Retrying with " ^ num_of_facts new_fact_filter new_num_facts ^
blanchet@51024
  1014
                "..."
blanchet@42614
  1015
                |> Output.urgent_message
blanchet@42614
  1016
              else
blanchet@42614
  1017
                ()
blanchet@42443
  1018
          in
blanchet@51024
  1019
            do_slice timeout (slice + 1) outcome0 time_so_far weighted_factss
blanchet@42443
  1020
          end
blanchet@40553
  1021
        else
blanchet@40553
  1022
          {outcome = if is_none outcome then NONE else the outcome0,
blanchet@51009
  1023
           used_facts = used_facts, used_from = map (apsnd snd) weighted_facts,
blanchet@51009
  1024
           run_time = time_so_far}
blanchet@40409
  1025
      end
blanchet@42443
  1026
  in do_slice timeout 1 NONE Time.zeroTime end
blanchet@40409
  1027
blanchet@43052
  1028
fun run_smt_solver mode name (params as {debug, verbose, preplay_timeout, ...})
blanchet@43011
  1029
        minimize_command
blanchet@51014
  1030
        ({state, goal, subgoal, subgoal_count, factss, ...} : prover_problem) =
blanchet@36379
  1031
  let
blanchet@41242
  1032
    val ctxt = Proof.context_of state
blanchet@51014
  1033
    fun weight_facts facts =
blanchet@51014
  1034
      let val num_facts = length facts in
blanchet@51014
  1035
        facts ~~ (0 upto num_facts - 1)
blanchet@51014
  1036
        |> map (weight_smt_fact ctxt num_facts)
blanchet@51014
  1037
      end
blanchet@51024
  1038
    val weighted_factss = factss |> map (apsnd weight_facts)
blanchet@51009
  1039
    val {outcome, used_facts = used_pairs, used_from, run_time} =
blanchet@51014
  1040
      smt_filter_loop name params state goal subgoal weighted_factss
blanchet@45781
  1041
    val used_facts = used_pairs |> map fst
blanchet@52031
  1042
    val outcome = outcome |> Option.map failure_of_smt_failure
blanchet@43261
  1043
    val (preplay, message, message_tail) =
blanchet@40184
  1044
      case outcome of
blanchet@40184
  1045
        NONE =>
blanchet@50669
  1046
        (Lazy.lazy (fn () =>
blanchet@50669
  1047
           play_one_line_proof mode debug verbose preplay_timeout used_pairs
blanchet@50669
  1048
               state subgoal SMT
blanchet@50669
  1049
               (bunch_of_reconstructors false (fn desperate =>
blanchet@50669
  1050
                  if desperate then liftingN else metis_default_lam_trans))),
blanchet@43052
  1051
         fn preplay =>
blanchet@43052
  1052
            let
blanchet@43052
  1053
              val one_line_params =
blanchet@43052
  1054
                (preplay, proof_banner mode name, used_facts,
blanchet@51200
  1055
                 choose_minimize_command ctxt params minimize_command name
blanchet@51200
  1056
                                         preplay,
blanchet@43052
  1057
                 subgoal, subgoal_count)
blanchet@48799
  1058
              val num_chained = length (#facts (Proof.goal state))
blanchet@52754
  1059
            in
wenzelm@53052
  1060
              one_line_proof_text num_chained one_line_params
blanchet@52754
  1061
            end,
blanchet@43261
  1062
         if verbose then
blanchet@52031
  1063
           "\nSMT solver real CPU time: " ^ string_of_time run_time ^ "."
blanchet@43261
  1064
         else
blanchet@43261
  1065
           "")
blanchet@43166
  1066
      | SOME failure =>
blanchet@50669
  1067
        (Lazy.value (Failed_to_Play plain_metis),
blanchet@53586
  1068
         fn _ => string_of_atp_failure failure, "")
blanchet@40063
  1069
  in
blanchet@51009
  1070
    {outcome = outcome, used_facts = used_facts, used_from = used_from,
blanchet@51009
  1071
     run_time = run_time, preplay = preplay, message = message,
blanchet@51009
  1072
     message_tail = message_tail}
blanchet@40063
  1073
  end
blanchet@40063
  1074
blanchet@45520
  1075
fun run_reconstructor mode name
blanchet@45561
  1076
        (params as {debug, verbose, timeout, type_enc, lam_trans, ...})
blanchet@45379
  1077
        minimize_command
blanchet@51010
  1078
        ({state, subgoal, subgoal_count, factss = (_, facts) :: _, ...}
blanchet@51007
  1079
         : prover_problem) =
blanchet@43050
  1080
  let
blanchet@45520
  1081
    val reconstr =
blanchet@45520
  1082
      if name = metisN then
blanchet@45520
  1083
        Metis (type_enc |> the_default (hd partial_type_encs),
blanchet@45520
  1084
               lam_trans |> the_default metis_default_lam_trans)
blanchet@45520
  1085
      else if name = smtN then
blanchet@45520
  1086
        SMT
blanchet@45520
  1087
      else
blanchet@45520
  1088
        raise Fail ("unknown reconstructor: " ^ quote name)
blanchet@51005
  1089
    val used_facts = facts |> map fst
blanchet@43050
  1090
  in
blanchet@45379
  1091
    case play_one_line_proof (if mode = Minimize then Normal else mode) debug
blanchet@51005
  1092
                             verbose timeout facts state subgoal reconstr
blanchet@45520
  1093
                             [reconstr] of
blanchet@43050
  1094
      play as Played (_, time) =>
blanchet@51009
  1095
      {outcome = NONE, used_facts = used_facts, used_from = facts,
blanchet@51009
  1096
       run_time = time, preplay = Lazy.value play,
blanchet@45561
  1097
       message =
blanchet@45561
  1098
         fn play =>
blanchet@45561
  1099
            let
blanchet@45561
  1100
              val (_, override_params) = extract_reconstructor params reconstr
blanchet@45561
  1101
              val one_line_params =
blanchet@45561
  1102
                (play, proof_banner mode name, used_facts,
blanchet@45561
  1103
                 minimize_command override_params name, subgoal,
blanchet@45561
  1104
                 subgoal_count)
blanchet@48799
  1105
              val num_chained = length (#facts (Proof.goal state))
blanchet@52754
  1106
            in
wenzelm@53052
  1107
              one_line_proof_text num_chained one_line_params
blanchet@52754
  1108
            end,
blanchet@43261
  1109
       message_tail = ""}
blanchet@43052
  1110
    | play =>
blanchet@43166
  1111
      let
blanchet@43166
  1112
        val failure = case play of Failed_to_Play _ => GaveUp | _ => TimedOut
blanchet@43166
  1113
      in
blanchet@51009
  1114
        {outcome = SOME failure, used_facts = [], used_from = [],
blanchet@51009
  1115
         run_time = Time.zeroTime, preplay = Lazy.value play,
blanchet@53586
  1116
         message = fn _ => string_of_atp_failure failure, message_tail = ""}
blanchet@43050
  1117
      end
blanchet@43050
  1118
  end
blanchet@43050
  1119
blanchet@43021
  1120
fun get_prover ctxt mode name =
wenzelm@42361
  1121
  let val thy = Proof_Context.theory_of ctxt in
blanchet@45379
  1122
    if is_reconstructor name then run_reconstructor mode name
blanchet@47606
  1123
    else if is_atp thy name then run_atp mode name (get_atp thy name ())
blanchet@43052
  1124
    else if is_smt_prover ctxt name then run_smt_solver mode name
blanchet@43052
  1125
    else error ("No such prover: " ^ name ^ ".")
blanchet@40941
  1126
  end
blanchet@40063
  1127
wenzelm@28582
  1128
end;