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