src/HOL/Tools/Sledgehammer/sledgehammer_prover.ML
author blanchet
Fri Jan 31 10:23:32 2014 +0100 (2014-01-31 ago)
changeset 55202 824c48a539c9
parent 55201 1ee776da8da7
child 55205 8450622db0c5
permissions -rw-r--r--
renamed many Sledgehammer ML files to clarify structure
blanchet@55201
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_prover.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@55201
     9
signature SLEDGEHAMMER_PROVER =
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
blanchet@54824
    16
  type play_outcome = Sledgehammer_Reconstructor.play_outcome
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,
blanchet@55183
    39
     compress_isar : real,
blanchet@55183
    40
     try0_isar : 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@54824
    60
     preplay : (reconstructor * play_outcome) Lazy.lazy,
blanchet@54824
    61
     message : reconstructor * play_outcome -> 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@55201
   117
structure Sledgehammer_Prover : SLEDGEHAMMER_PROVER =
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
blanchet@55202
   130
open Sledgehammer_Isar_Print
blanchet@55202
   131
open Sledgehammer_Isar
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,
blanchet@55183
   280
   compress_isar : real,
blanchet@55183
   281
   try0_isar : 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@54824
   301
   preplay : (reconstructor * play_outcome) Lazy.lazy,
blanchet@54824
   302
   message : reconstructor * play_outcome -> 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@54824
   361
fun extract_reconstructor ({type_enc, lam_trans, ...} : params) (Metis (type_enc', lam_trans')) =
blanchet@45561
   362
    let
blanchet@45561
   363
      val override_params =
blanchet@54824
   364
        (if is_none type_enc andalso type_enc' = hd partial_type_encs then []
blanchet@54824
   365
         else [("type_enc", [hd (unalias_type_enc type_enc')])]) @
blanchet@54824
   366
        (if is_none lam_trans andalso lam_trans' = default_metis_lam_trans then []
blanchet@54824
   367
         else [("lam_trans", [lam_trans'])])
blanchet@45561
   368
    in (metisN, override_params) end
blanchet@45561
   369
  | extract_reconstructor _ SMT = (smtN, [])
blanchet@45561
   370
blanchet@43033
   371
(* based on "Mirabelle.can_apply" and generalized *)
blanchet@43034
   372
fun timed_apply timeout tac state i =
blanchet@43033
   373
  let
blanchet@43033
   374
    val {context = ctxt, facts, goal} = Proof.goal state
blanchet@43033
   375
    val full_tac = Method.insert_tac facts i THEN tac ctxt i
blanchet@54816
   376
  in
blanchet@54816
   377
    TimeLimit.timeLimit timeout (try (Seq.pull o full_tac)) goal
blanchet@54816
   378
  end
blanchet@43033
   379
blanchet@54824
   380
fun tac_of_reconstructor (Metis (type_enc, lam_trans)) = metis_tac [type_enc] lam_trans
blanchet@51998
   381
  | tac_of_reconstructor SMT = SMT_Solver.smt_tac
blanchet@43034
   382
blanchet@45520
   383
fun timed_reconstructor reconstr debug timeout ths =
blanchet@55170
   384
  timed_apply timeout (silence_reconstructors debug
blanchet@55170
   385
    #> (fn ctxt => tac_of_reconstructor reconstr ctxt ths))
blanchet@43033
   386
blanchet@48798
   387
fun is_fact_chained ((_, (sc, _)), _) = sc = Chained
blanchet@48798
   388
blanchet@48798
   389
fun filter_used_facts keep_chained used =
blanchet@54773
   390
  filter ((member (op =) used o fst) orf (if keep_chained then is_fact_chained else K false))
blanchet@43033
   391
blanchet@54815
   392
fun play_one_line_proof mode debug verbose timeout pairs state i preferred reconstrs =
blanchet@43034
   393
  let
blanchet@45520
   394
    fun get_preferred reconstrs =
blanchet@45520
   395
      if member (op =) reconstrs preferred then preferred
blanchet@45520
   396
      else List.last reconstrs
blanchet@43034
   397
  in
blanchet@54816
   398
    if timeout = Time.zeroTime then
blanchet@54824
   399
      (get_preferred reconstrs, Not_Played)
blanchet@45379
   400
    else
blanchet@50557
   401
      let
blanchet@54815
   402
        val _ = if mode = Minimize then Output.urgent_message "Preplaying proof..." else ()
blanchet@50557
   403
        val ths = pairs |> sort_wrt (fst o fst) |> map snd
blanchet@54824
   404
        fun play [] [] = (get_preferred reconstrs, Play_Failed)
blanchet@54824
   405
          | play timed_outs [] = (get_preferred timed_outs, Play_Timed_Out timeout)
blanchet@50557
   406
          | play timed_out (reconstr :: reconstrs) =
blanchet@50557
   407
            let
blanchet@50557
   408
              val _ =
blanchet@50557
   409
                if verbose then
blanchet@54816
   410
                  Output.urgent_message ("Trying \"" ^ string_of_reconstructor reconstr ^
blanchet@54816
   411
                    "\" for " ^ string_of_time timeout ^ "...")
blanchet@50557
   412
                else
blanchet@50557
   413
                  ()
blanchet@50557
   414
              val timer = Timer.startRealTimer ()
blanchet@50557
   415
            in
blanchet@50557
   416
              case timed_reconstructor reconstr debug timeout ths state i of
blanchet@54824
   417
                SOME (SOME _) => (reconstr, Played (Timer.checkRealTimer timer))
blanchet@50557
   418
              | _ => play timed_out reconstrs
blanchet@50557
   419
            end
blanchet@50557
   420
            handle TimeLimit.TimeOut => play (reconstr :: timed_out) reconstrs
blanchet@54824
   421
      in
blanchet@54824
   422
        play [] reconstrs
blanchet@54824
   423
      end
blanchet@43033
   424
  end
blanchet@43033
   425
blanchet@41313
   426
blanchet@41256
   427
(* generic TPTP-based ATPs *)
blanchet@40061
   428
blanchet@42730
   429
(* Too general means, positive equality literal with a variable X as one
blanchet@42730
   430
   operand, when X does not occur properly in the other operand. This rules out
blanchet@42730
   431
   clearly inconsistent facts such as X = a | X = b, though it by no means
blanchet@42730
   432
   guarantees soundness. *)
blanchet@42730
   433
blanchet@51998
   434
fun get_facts_of_filter _ [(_, facts)] = facts
blanchet@51998
   435
  | get_facts_of_filter fact_filter factss =
blanchet@51013
   436
    case AList.lookup (op =) factss fact_filter of
blanchet@51013
   437
      SOME facts => facts
blanchet@51013
   438
    | NONE => snd (hd factss)
blanchet@51013
   439
blanchet@42730
   440
(* Unwanted equalities are those between a (bound or schematic) variable that
blanchet@42730
   441
   does not properly occur in the second operand. *)
blanchet@42730
   442
val is_exhaustive_finite =
blanchet@42730
   443
  let
blanchet@42730
   444
    fun is_bad_equal (Var z) t =
blanchet@42730
   445
        not (exists_subterm (fn Var z' => z = z' | _ => false) t)
blanchet@42730
   446
      | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
blanchet@42730
   447
      | is_bad_equal _ _ = false
blanchet@42730
   448
    fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
blanchet@42730
   449
    fun do_formula pos t =
blanchet@42730
   450
      case (pos, t) of
blanchet@42730
   451
        (_, @{const Trueprop} $ t1) => do_formula pos t1
blanchet@42730
   452
      | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
blanchet@42730
   453
        do_formula pos t'
blanchet@42730
   454
      | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
blanchet@42730
   455
        do_formula pos t'
blanchet@42730
   456
      | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
blanchet@42730
   457
        do_formula pos t'
blanchet@42730
   458
      | (_, @{const "==>"} $ t1 $ t2) =>
blanchet@42730
   459
        do_formula (not pos) t1 andalso
blanchet@42730
   460
        (t2 = @{prop False} orelse do_formula pos t2)
blanchet@42730
   461
      | (_, @{const HOL.implies} $ t1 $ t2) =>
blanchet@42730
   462
        do_formula (not pos) t1 andalso
blanchet@42730
   463
        (t2 = @{const False} orelse do_formula pos t2)
blanchet@42730
   464
      | (_, @{const Not} $ t1) => do_formula (not pos) t1
blanchet@42730
   465
      | (true, @{const HOL.disj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@42730
   466
      | (false, @{const HOL.conj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@42730
   467
      | (true, Const (@{const_name HOL.eq}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@42730
   468
      | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@42730
   469
      | _ => false
blanchet@42730
   470
  in do_formula true end
blanchet@42730
   471
blanchet@42730
   472
fun has_bound_or_var_of_type pred =
blanchet@42730
   473
  exists_subterm (fn Var (_, T as Type _) => pred T
blanchet@42730
   474
                   | Abs (_, T as Type _, _) => pred T
blanchet@42730
   475
                   | _ => false)
blanchet@42730
   476
blanchet@42730
   477
(* Facts are forbidden to contain variables of these types. The typical reason
blanchet@42730
   478
   is that they lead to unsoundness. Note that "unit" satisfies numerous
blanchet@42730
   479
   equations like "?x = ()". The resulting clauses will have no type constraint,
blanchet@42730
   480
   yielding false proofs. Even "bool" leads to many unsound proofs, though only
blanchet@42730
   481
   for higher-order problems. *)
blanchet@42730
   482
blanchet@42730
   483
(* Facts containing variables of type "unit" or "bool" or of the form
blanchet@42730
   484
   "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
blanchet@42730
   485
   are omitted. *)
blanchet@42944
   486
fun is_dangerous_prop ctxt =
blanchet@42944
   487
  transform_elim_prop
blanchet@44393
   488
  #> (has_bound_or_var_of_type (is_type_surely_finite ctxt) orf
blanchet@42730
   489
      is_exhaustive_finite)
blanchet@42730
   490
blanchet@39492
   491
(* Important messages are important but not so important that users want to see
blanchet@39492
   492
   them each time. *)
blanchet@44649
   493
val atp_important_message_keep_quotient = 25
blanchet@39492
   494
blanchet@54434
   495
fun choose_type_enc strictness best_type_enc format =
blanchet@44397
   496
  the_default best_type_enc
blanchet@54434
   497
  #> type_enc_of_string strictness
blanchet@44416
   498
  #> adjust_type_enc format
blanchet@42548
   499
blanchet@51200
   500
fun isar_proof_reconstructor ctxt name =
blanchet@51200
   501
  let val thy = Proof_Context.theory_of ctxt in
blanchet@51200
   502
    if is_atp thy name then name
blanchet@51200
   503
    else remotify_prover_if_not_installed ctxt eN |> the_default name
blanchet@51200
   504
  end
blanchet@43051
   505
blanchet@55202
   506
(* FIXME: See the analogous logic in the function "maybe_minimize" in
blanchet@55202
   507
   "sledgehammer_prover_minimize.ML". *)
blanchet@54824
   508
fun choose_minimize_command ctxt (params as {isar_proofs, ...}) minimize_command name preplay =
blanchet@45520
   509
  let
blanchet@54824
   510
    val maybe_isar_name = name |> isar_proofs = SOME true ? isar_proof_reconstructor ctxt
blanchet@51200
   511
    val (min_name, override_params) =
blanchet@54824
   512
      (case preplay of
blanchet@54824
   513
        (reconstr, Played _) =>
blanchet@51200
   514
        if isar_proofs = SOME true then (maybe_isar_name, [])
blanchet@51200
   515
        else extract_reconstructor params reconstr
blanchet@54824
   516
      | _ => (maybe_isar_name, []))
blanchet@51200
   517
  in minimize_command override_params min_name end
blanchet@43051
   518
blanchet@53480
   519
val max_fact_instances = 10 (* FUDGE *)
blanchet@53480
   520
blanchet@52034
   521
fun repair_monomorph_context max_iters best_max_iters max_new_instances
blanchet@52034
   522
                             best_max_new_instances =
blanchet@52034
   523
  Config.put Monomorph.max_rounds (max_iters |> the_default best_max_iters)
blanchet@52034
   524
  #> Config.put Monomorph.max_new_instances
blanchet@52034
   525
         (max_new_instances |> the_default best_max_new_instances)
blanchet@53480
   526
  #> Config.put Monomorph.max_thm_instances max_fact_instances
blanchet@52034
   527
blanchet@51998
   528
fun suffix_of_mode Auto_Try = "_try"
blanchet@51998
   529
  | suffix_of_mode Try = "_try"
blanchet@51998
   530
  | suffix_of_mode Normal = ""
blanchet@51998
   531
  | suffix_of_mode MaSh = ""
blanchet@51998
   532
  | suffix_of_mode Auto_Minimize = "_min"
blanchet@51998
   533
  | suffix_of_mode Minimize = "_min"
blanchet@44509
   534
blanchet@44423
   535
(* Give the ATPs some slack before interrupting them the hard way. "z3_tptp" on
blanchet@43631
   536
   Linux appears to be the only ATP that does not honor its time limit. *)
blanchet@43690
   537
val atp_timeout_slack = seconds 1.0
blanchet@43631
   538
blanchet@48331
   539
val mono_max_privileged_facts = 10
blanchet@48331
   540
blanchet@51186
   541
(* For low values of "max_facts", this fudge value ensures that most slices are
blanchet@51186
   542
   invoked with a nontrivial amount of facts. *)
blanchet@51186
   543
val max_fact_factor_fudge = 5
blanchet@51186
   544
blanchet@43021
   545
fun run_atp mode name
blanchet@54824
   546
    ({exec, arguments, proof_delims, known_failures, prem_role, best_slices, best_max_mono_iters,
blanchet@54824
   547
      best_max_new_mono_instances, ...} : atp_config)
blanchet@54824
   548
    (params as {debug, verbose, overlord, type_enc, strict, lam_trans, uncurried_aliases,
blanchet@55183
   549
       fact_filter, max_facts, max_mono_iters, max_new_mono_instances, isar_proofs, compress_isar,
blanchet@55183
   550
       try0_isar, slice, timeout, preplay_timeout, ...})
blanchet@54824
   551
    minimize_command
blanchet@54824
   552
    ({comment, state, goal, subgoal, subgoal_count, factss, ...} : prover_problem) =
blanchet@38023
   553
  let
blanchet@42182
   554
    val thy = Proof.theory_of state
blanchet@39318
   555
    val ctxt = Proof.context_of state
blanchet@47946
   556
    val atp_mode =
blanchet@48143
   557
      if Config.get ctxt completish then Sledgehammer_Completish
blanchet@47946
   558
      else Sledgehammer
blanchet@52196
   559
    val (_, hyp_ts, concl_t) = strip_subgoal goal subgoal ctxt
blanchet@41159
   560
    val (dest_dir, problem_prefix) =
blanchet@51998
   561
      if overlord then overlord_file_location_of_prover name
blanchet@41159
   562
      else (Config.get ctxt dest_dir, Config.get ctxt problem_prefix)
blanchet@40061
   563
    val problem_file_name =
blanchet@41159
   564
      Path.basic (problem_prefix ^ (if overlord then "" else serial_string ()) ^
blanchet@51998
   565
                  suffix_of_mode mode ^ "_" ^ string_of_int subgoal)
blanchet@48656
   566
    val prob_path =
blanchet@40059
   567
      if dest_dir = "" then
blanchet@40061
   568
        File.tmp_path problem_file_name
blanchet@40059
   569
      else if File.exists (Path.explode dest_dir) then
blanchet@40061
   570
        Path.append (Path.explode dest_dir) problem_file_name
blanchet@39003
   571
      else
blanchet@40059
   572
        error ("No such directory: " ^ quote dest_dir ^ ".")
blanchet@52754
   573
    val exec = exec ()
blanchet@48376
   574
    val command0 =
blanchet@47055
   575
      case find_first (fn var => getenv var <> "") (fst exec) of
blanchet@48376
   576
        SOME var =>
blanchet@48376
   577
        let
blanchet@48376
   578
          val pref = getenv var ^ "/"
blanchet@48376
   579
          val paths = map (Path.explode o prefix pref) (snd exec)
blanchet@48376
   580
        in
blanchet@48376
   581
          case find_first File.exists paths of
blanchet@48376
   582
            SOME path => path
blanchet@48376
   583
          | NONE => error ("Bad executable: " ^ Path.print (hd paths) ^ ".")
blanchet@48376
   584
        end
blanchet@53989
   585
      | NONE => error ("The environment variable " ^ quote (List.last (fst exec)) ^
blanchet@47055
   586
                       " is not set.")
blanchet@38023
   587
    fun split_time s =
blanchet@38023
   588
      let
blanchet@42448
   589
        val split = String.tokens (fn c => str c = "\n")
blanchet@47737
   590
        val (output, t) =
blanchet@47737
   591
          s |> split |> (try split_last #> the_default ([], "0"))
blanchet@47737
   592
            |>> cat_lines
blanchet@42448
   593
        fun as_num f = f >> (fst o read_int)
blanchet@42448
   594
        val num = as_num (Scan.many1 Symbol.is_ascii_digit)
blanchet@42448
   595
        val digit = Scan.one Symbol.is_ascii_digit
blanchet@42448
   596
        val num3 = as_num (digit ::: digit ::: (digit >> single))
blanchet@42448
   597
        val time = num --| Scan.$$ "." -- num3 >> (fn (a, b) => a * 1000 + b)
blanchet@45381
   598
        val as_time =
blanchet@45381
   599
          raw_explode #> Scan.read Symbol.stopper time #> the_default 0
blanchet@47737
   600
      in (output, as_time t |> Time.fromMilliseconds) end
blanchet@48656
   601
    fun run () =
blanchet@48376
   602
      let
blanchet@48376
   603
        (* If slicing is disabled, we expand the last slice to fill the entire
blanchet@48376
   604
           time available. *)
blanchet@54125
   605
        val all_slices = best_slices ctxt
blanchet@54125
   606
        val actual_slices = get_slices slice all_slices
blanchet@54125
   607
        fun max_facts_of_slices f slices = fold (Integer.max o slice_max_facts o f) slices 0
blanchet@48376
   608
        val num_actual_slices = length actual_slices
blanchet@51186
   609
        val max_fact_factor =
blanchet@54125
   610
          Real.fromInt (case max_facts of
blanchet@54125
   611
              NONE => max_facts_of_slices I all_slices
blanchet@54125
   612
            | SOME max => max)
blanchet@54125
   613
          / Real.fromInt (max_facts_of_slices snd actual_slices)
blanchet@48376
   614
        fun monomorphize_facts facts =
blanchet@48376
   615
          let
blanchet@48376
   616
            val ctxt =
blanchet@48376
   617
              ctxt
blanchet@53478
   618
              |> repair_monomorph_context max_mono_iters
blanchet@52034
   619
                     best_max_mono_iters max_new_mono_instances
blanchet@52034
   620
                     best_max_new_mono_instances
blanchet@48376
   621
            (* pseudo-theorem involving the same constants as the subgoal *)
blanchet@48376
   622
            val subgoal_th =
blanchet@48376
   623
              Logic.list_implies (hyp_ts, concl_t) |> Skip_Proof.make_thm thy
blanchet@48376
   624
            val rths =
blanchet@48376
   625
              facts |> chop mono_max_privileged_facts
blanchet@48376
   626
                    |>> map (pair 1 o snd)
blanchet@48376
   627
                    ||> map (pair 2 o snd)
blanchet@48376
   628
                    |> op @
blanchet@48376
   629
                    |> cons (0, subgoal_th)
blanchet@48376
   630
          in
blanchet@53478
   631
            Monomorph.monomorph atp_schematic_consts_of ctxt rths
blanchet@53478
   632
            |> tl |> curry ListPair.zip (map fst facts)
blanchet@48376
   633
            |> maps (fn (name, rths) =>
blanchet@48376
   634
                        map (pair name o zero_var_indexes o snd) rths)
blanchet@48376
   635
          end
blanchet@48376
   636
        fun run_slice time_left (cache_key, cache_value)
blanchet@48716
   637
                (slice, (time_frac,
blanchet@51011
   638
                     (key as ((best_max_facts, best_fact_filter), format,
blanchet@51011
   639
                              best_type_enc, best_lam_trans,
blanchet@51011
   640
                              best_uncurried_aliases),
blanchet@48716
   641
                      extra))) =
blanchet@38032
   642
          let
blanchet@51024
   643
            val effective_fact_filter =
blanchet@51024
   644
              fact_filter |> the_default best_fact_filter
blanchet@51998
   645
            val facts = get_facts_of_filter effective_fact_filter factss
blanchet@48376
   646
            val num_facts =
blanchet@51186
   647
              Real.ceil (max_fact_factor * Real.fromInt best_max_facts) +
blanchet@51186
   648
              max_fact_factor_fudge
blanchet@51186
   649
              |> Integer.min (length facts)
blanchet@54434
   650
            val strictness = if strict then Strict else Non_Strict
blanchet@48376
   651
            val type_enc =
blanchet@54434
   652
              type_enc |> choose_type_enc strictness best_type_enc format
blanchet@48376
   653
            val sound = is_type_enc_sound type_enc
blanchet@48376
   654
            val real_ms = Real.fromInt o Time.toMilliseconds
blanchet@48376
   655
            val slice_timeout =
blanchet@54816
   656
              (real_ms time_left
blanchet@54816
   657
               |> (if slice < num_actual_slices - 1 then
blanchet@54816
   658
                     curry Real.min (time_frac * real_ms timeout)
blanchet@54816
   659
                   else
blanchet@54816
   660
                     I))
blanchet@54816
   661
              * 0.001
blanchet@54816
   662
              |> seconds
blanchet@48376
   663
            val generous_slice_timeout =
blanchet@54816
   664
              if mode = MaSh then one_day else Time.+ (slice_timeout, atp_timeout_slack)
blanchet@48376
   665
            val _ =
blanchet@48376
   666
              if debug then
blanchet@48376
   667
                quote name ^ " slice #" ^ string_of_int (slice + 1) ^
blanchet@48376
   668
                " with " ^ string_of_int num_facts ^ " fact" ^
blanchet@54816
   669
                plural_s num_facts ^ " for " ^ string_of_time slice_timeout ^ "..."
blanchet@48376
   670
                |> Output.urgent_message
blanchet@48376
   671
              else
blanchet@48376
   672
                ()
blanchet@48376
   673
            val readable_names = not (Config.get ctxt atp_full_names)
blanchet@48376
   674
            val lam_trans =
blanchet@48376
   675
              case lam_trans of
blanchet@48376
   676
                SOME s => s
blanchet@48376
   677
              | NONE => best_lam_trans
blanchet@48376
   678
            val uncurried_aliases =
blanchet@48376
   679
              case uncurried_aliases of
blanchet@48376
   680
                SOME b => b
blanchet@48376
   681
              | NONE => best_uncurried_aliases
blanchet@48376
   682
            val value as (atp_problem, _, fact_names, _, _) =
blanchet@48376
   683
              if cache_key = SOME key then
blanchet@48376
   684
                cache_value
blanchet@48376
   685
              else
blanchet@48376
   686
                facts
blanchet@48376
   687
                |> not sound
blanchet@48376
   688
                   ? filter_out (is_dangerous_prop ctxt o prop_of o snd)
blanchet@48376
   689
                |> take num_facts
blanchet@48376
   690
                |> not (is_type_enc_polymorphic type_enc) ? monomorphize_facts
blanchet@48376
   691
                |> map (apsnd prop_of)
blanchet@48376
   692
                |> prepare_atp_problem ctxt format prem_role type_enc atp_mode
blanchet@48376
   693
                                       lam_trans uncurried_aliases
blanchet@48376
   694
                                       readable_names true hyp_ts concl_t
blanchet@48376
   695
            fun sel_weights () = atp_problem_selection_weights atp_problem
blanchet@48376
   696
            fun ord_info () = atp_problem_term_order_info atp_problem
blanchet@48376
   697
            val ord = effective_term_order ctxt name
blanchet@53492
   698
            val full_proof = isar_proofs |> the_default (mode = Minimize)
blanchet@50927
   699
            val args =
blanchet@54816
   700
              arguments ctxt full_proof extra slice_timeout (File.shell_path prob_path)
blanchet@54816
   701
                (ord, ord_info, sel_weights)
blanchet@48376
   702
            val command =
blanchet@50927
   703
              "(exec 2>&1; " ^ File.shell_path command0 ^ " " ^ args ^ " " ^ ")"
blanchet@48532
   704
              |> enclose "TIMEFORMAT='%3R'; { time " " ; }"
blanchet@48376
   705
            val _ =
blanchet@48376
   706
              atp_problem
blanchet@51998
   707
              |> lines_of_atp_problem format ord ord_info
blanchet@54811
   708
              |> cons ("% " ^ command ^ "\n" ^ (if comment = "" then "" else "% " ^ comment ^ "\n"))
blanchet@48656
   709
              |> File.write_list prob_path
blanchet@52034
   710
            val ((output, run_time), (atp_proof, outcome)) =
blanchet@54816
   711
              TimeLimit.timeLimit generous_slice_timeout Isabelle_System.bash_output command
blanchet@54811
   712
              |>> (if overlord then prefix ("% " ^ command ^ "\n% " ^ timestamp () ^ "\n") else I)
blanchet@48376
   713
              |> fst |> split_time
blanchet@48376
   714
              |> (fn accum as (output, _) =>
blanchet@52034
   715
                     (accum,
blanchet@54811
   716
                      extract_tstplike_proof_and_outcome verbose proof_delims known_failures output
blanchet@52031
   717
                      |>> atp_proof_of_tstplike_proof atp_problem
blanchet@54811
   718
                      handle UNRECOGNIZED_ATP_PROOF () => ([], SOME ProofIncomplete)))
blanchet@54816
   719
              handle TimeLimit.TimeOut => (("", slice_timeout), ([], SOME TimedOut))
blanchet@48376
   720
            val outcome =
blanchet@54818
   721
              (case outcome of
blanchet@48376
   722
                NONE =>
blanchet@48376
   723
                (case used_facts_in_unsound_atp_proof ctxt fact_names atp_proof
blanchet@48376
   724
                      |> Option.map (sort string_ord) of
blanchet@48376
   725
                   SOME facts =>
blanchet@54818
   726
                   let val failure = UnsoundProof (is_type_enc_sound type_enc, facts) in
blanchet@54818
   727
                     if debug then (warning (string_of_atp_failure failure); NONE) else SOME failure
blanchet@48376
   728
                   end
blanchet@48376
   729
                 | NONE => NONE)
blanchet@54818
   730
              | _ => outcome)
blanchet@51013
   731
          in
blanchet@51013
   732
            ((SOME key, value), (output, run_time, facts, atp_proof, outcome))
blanchet@51013
   733
          end
blanchet@48376
   734
        val timer = Timer.startRealTimer ()
blanchet@48376
   735
        fun maybe_run_slice slice
blanchet@51013
   736
                (result as (cache, (_, run_time0, _, _, SOME _))) =
blanchet@48376
   737
            let
blanchet@54816
   738
              val time_left = Time.- (timeout, Timer.checkRealTimer timer)
blanchet@48376
   739
            in
blanchet@54816
   740
              if Time.<= (time_left, Time.zeroTime) then
blanchet@48376
   741
                result
blanchet@48376
   742
              else
blanchet@48376
   743
                run_slice time_left cache slice
blanchet@54818
   744
                |> (fn (cache, (output, run_time, used_from, atp_proof, outcome)) =>
blanchet@54818
   745
                  (cache, (output, Time.+ (run_time0, run_time), used_from, atp_proof, outcome)))
blanchet@48376
   746
            end
blanchet@48376
   747
          | maybe_run_slice _ result = result
blanchet@48376
   748
      in
blanchet@48376
   749
        ((NONE, ([], Symtab.empty, Vector.fromList [], [], Symtab.empty)),
blanchet@51013
   750
         ("", Time.zeroTime, [], [], SOME InternalError))
blanchet@48376
   751
        |> fold maybe_run_slice actual_slices
blanchet@48376
   752
      end
blanchet@38023
   753
    (* If the problem file has not been exported, remove it; otherwise, export
blanchet@38023
   754
       the proof file too. *)
blanchet@48656
   755
    fun clean_up () =
blanchet@48656
   756
      if dest_dir = "" then (try File.rm prob_path; ()) else ()
blanchet@51013
   757
    fun export (_, (output, _, _, _, _)) =
blanchet@48376
   758
      if dest_dir = "" then ()
blanchet@48656
   759
      else File.write (Path.explode (Path.implode prob_path ^ "_proof")) output
blanchet@52150
   760
    val ((_, (_, pool, fact_names, lifted, sym_tab)),
blanchet@51013
   761
         (output, run_time, used_from, atp_proof, outcome)) =
blanchet@48656
   762
      with_cleanup clean_up run () |> tap export
blanchet@39492
   763
    val important_message =
wenzelm@53052
   764
      if mode = Normal andalso random_range 0 (atp_important_message_keep_quotient - 1) = 0
wenzelm@53052
   765
      then
blanchet@39492
   766
        extract_important_message output
blanchet@39492
   767
      else
blanchet@39492
   768
        ""
blanchet@43261
   769
    val (used_facts, preplay, message, message_tail) =
blanchet@54824
   770
      (case outcome of
blanchet@38023
   771
        NONE =>
blanchet@43033
   772
        let
blanchet@45551
   773
          val used_facts = used_facts_in_atp_proof ctxt fact_names atp_proof
blanchet@45590
   774
          val needs_full_types = is_typed_helper_used_in_atp_proof atp_proof
blanchet@45521
   775
          val reconstrs =
blanchet@54818
   776
            bunch_of_reconstructors needs_full_types (lam_trans_of_atp_proof atp_proof
blanchet@54818
   777
              o (fn desperate => if desperate then hide_lamsN else default_metis_lam_trans))
blanchet@43033
   778
        in
blanchet@43052
   779
          (used_facts,
blanchet@50669
   780
           Lazy.lazy (fn () =>
blanchet@54824
   781
             let val used_pairs = used_from |> filter_used_facts false used_facts in
blanchet@54824
   782
               play_one_line_proof mode debug verbose preplay_timeout used_pairs state subgoal
blanchet@54824
   783
                 (hd reconstrs) reconstrs
blanchet@50669
   784
             end),
blanchet@43052
   785
           fn preplay =>
blanchet@43052
   786
              let
blanchet@54824
   787
                val _ = if verbose then Output.urgent_message "Generating proof text..." else ()
blanchet@54500
   788
                fun isar_params () =
blanchet@54500
   789
                  let
blanchet@54500
   790
                    val metis_type_enc =
blanchet@54500
   791
                      if is_typed_helper_used_in_atp_proof atp_proof then full_typesN
blanchet@54500
   792
                      else partial_typesN
blanchet@54500
   793
                    val metis_lam_trans = lam_trans_of_atp_proof atp_proof default_metis_lam_trans
blanchet@54505
   794
                    val atp_proof =
blanchet@54505
   795
                      atp_proof
blanchet@54505
   796
                      |> termify_atp_proof ctxt pool lifted sym_tab
blanchet@54772
   797
                      |> introduce_spass_skolem
blanchet@54505
   798
                      |> factify_atp_proof fact_names hyp_ts concl_t
blanchet@54500
   799
                  in
blanchet@55183
   800
                    (verbose, metis_type_enc, metis_lam_trans, preplay_timeout, compress_isar,
blanchet@55183
   801
                     try0_isar, atp_proof, goal)
blanchet@54500
   802
                  end
blanchet@43052
   803
                val one_line_params =
blanchet@43052
   804
                  (preplay, proof_banner mode name, used_facts,
blanchet@54500
   805
                   choose_minimize_command ctxt params minimize_command name preplay,
blanchet@43052
   806
                   subgoal, subgoal_count)
blanchet@48799
   807
                val num_chained = length (#facts (Proof.goal state))
blanchet@48799
   808
              in
blanchet@55168
   809
                proof_text ctxt debug isar_proofs isar_params num_chained one_line_params
blanchet@48799
   810
              end,
blanchet@54824
   811
           (if verbose then "\nATP real CPU time: " ^ string_of_time run_time ^ "." else "") ^
blanchet@43261
   812
           (if important_message <> "" then
blanchet@54824
   813
              "\n\nImportant message from Dr. Geoff Sutcliffe:\n" ^ important_message
blanchet@43261
   814
            else
blanchet@43261
   815
              ""))
blanchet@43033
   816
        end
blanchet@43052
   817
      | SOME failure =>
blanchet@54824
   818
        ([], Lazy.value (plain_metis, Play_Failed), fn _ => string_of_atp_failure failure, ""))
blanchet@38023
   819
  in
blanchet@54824
   820
    {outcome = outcome, used_facts = used_facts, used_from = used_from, run_time = run_time,
blanchet@54824
   821
     preplay = preplay, message = message, message_tail = message_tail}
blanchet@38023
   822
  end
blanchet@38023
   823
blanchet@40669
   824
(* "SMT_Failure.Abnormal_Termination" carries the solver's return code. Until
blanchet@40669
   825
   these are sorted out properly in the SMT module, we have to interpret these
blanchet@40669
   826
   ourselves. *)
blanchet@40684
   827
val remote_smt_failures =
blanchet@43631
   828
  [(2, NoLibwwwPerl),
blanchet@43631
   829
   (22, CantConnect)]
blanchet@40684
   830
val z3_failures =
blanchet@41236
   831
  [(101, OutOfResources),
blanchet@41236
   832
   (103, MalformedInput),
blanchet@50667
   833
   (110, MalformedInput),
blanchet@50667
   834
   (112, TimedOut)]
blanchet@40684
   835
val unix_failures =
blanchet@48797
   836
  [(138, Crashed),
blanchet@48797
   837
   (139, Crashed)]
blanchet@43631
   838
val smt_failures = remote_smt_failures @ z3_failures @ unix_failures
blanchet@40555
   839
blanchet@52031
   840
fun failure_of_smt_failure (SMT_Failure.Counterexample {is_real_cex, ...}) =
blanchet@43050
   841
    if is_real_cex then Unprovable else GaveUp
blanchet@52031
   842
  | failure_of_smt_failure SMT_Failure.Time_Out = TimedOut
blanchet@52031
   843
  | failure_of_smt_failure (SMT_Failure.Abnormal_Termination code) =
blanchet@41222
   844
    (case AList.lookup (op =) smt_failures code of
blanchet@40684
   845
       SOME failure => failure
blanchet@41259
   846
     | NONE => UnknownError ("Abnormal termination with exit code " ^
blanchet@41259
   847
                             string_of_int code ^ "."))
blanchet@52031
   848
  | failure_of_smt_failure SMT_Failure.Out_Of_Memory = OutOfResources
blanchet@52031
   849
  | failure_of_smt_failure (SMT_Failure.Other_Failure s) = UnknownError s
blanchet@40063
   850
blanchet@40698
   851
(* FUDGE *)
blanchet@42646
   852
val smt_max_slices =
blanchet@42646
   853
  Attrib.setup_config_int @{binding sledgehammer_smt_max_slices} (K 8)
blanchet@42646
   854
val smt_slice_fact_frac =
blanchet@51014
   855
  Attrib.setup_config_real @{binding sledgehammer_smt_slice_fact_frac}
blanchet@51014
   856
                           (K 0.667)
blanchet@42646
   857
val smt_slice_time_frac =
blanchet@51014
   858
  Attrib.setup_config_real @{binding sledgehammer_smt_slice_time_frac} (K 0.333)
blanchet@42646
   859
val smt_slice_min_secs =
blanchet@51014
   860
  Attrib.setup_config_int @{binding sledgehammer_smt_slice_min_secs} (K 3)
blanchet@40409
   861
blanchet@54000
   862
val is_boring_builtin_typ =
blanchet@54000
   863
  not o exists_subtype (member (op =) [@{typ nat}, @{typ int}, HOLogic.realT])
blanchet@54000
   864
blanchet@54089
   865
fun smt_filter_loop name ({debug, overlord, max_mono_iters, max_new_mono_instances, timeout, slice,
blanchet@54089
   866
      ...} : params) state goal i =
blanchet@40409
   867
  let
blanchet@50759
   868
    fun repair_context ctxt =
blanchet@50759
   869
      ctxt |> select_smt_solver name
blanchet@50759
   870
           |> Config.put SMT_Config.verbose debug
blanchet@50759
   871
           |> (if overlord then
blanchet@50759
   872
                 Config.put SMT_Config.debug_files
blanchet@51998
   873
                            (overlord_file_location_of_prover name
blanchet@50759
   874
                             |> (fn (path, name) => path ^ "/" ^ name))
blanchet@50759
   875
               else
blanchet@50759
   876
                 I)
blanchet@50759
   877
           |> Config.put SMT_Config.infer_triggers
blanchet@50759
   878
                         (Config.get ctxt smt_triggers)
blanchet@54094
   879
           |> not (Config.get ctxt smt_builtins)
blanchet@54000
   880
              ? (SMT_Builtin.filter_builtins is_boring_builtin_typ
blanchet@54000
   881
                 #> Config.put SMT_Config.datatypes false)
blanchet@52034
   882
           |> repair_monomorph_context max_mono_iters default_max_mono_iters
blanchet@52034
   883
                  max_new_mono_instances default_max_new_mono_instances
blanchet@52034
   884
    val state = Proof.map_context (repair_context) state
blanchet@52034
   885
    val ctxt = Proof.context_of state
blanchet@45706
   886
    val max_slices = if slice then Config.get ctxt smt_max_slices else 1
blanchet@51024
   887
    fun do_slice timeout slice outcome0 time_so_far
blanchet@51024
   888
                 (weighted_factss as (fact_filter, weighted_facts) :: _) =
blanchet@40553
   889
      let
blanchet@40553
   890
        val timer = Timer.startRealTimer ()
blanchet@42443
   891
        val slice_timeout =
blanchet@54816
   892
          if slice < max_slices then
blanchet@54816
   893
            let val ms = Time.toMilliseconds timeout in
blanchet@50557
   894
              Int.min (ms,
blanchet@50557
   895
                  Int.max (1000 * Config.get ctxt smt_slice_min_secs,
blanchet@50557
   896
                      Real.ceil (Config.get ctxt smt_slice_time_frac
blanchet@50557
   897
                                 * Real.fromInt ms)))
blanchet@54816
   898
              |> Time.fromMilliseconds
blanchet@50557
   899
            end
blanchet@40553
   900
          else
blanchet@40553
   901
            timeout
blanchet@51009
   902
        val num_facts = length weighted_facts
blanchet@40553
   903
        val _ =
blanchet@42614
   904
          if debug then
blanchet@54816
   905
            quote name ^ " slice " ^ string_of_int slice ^ " with " ^ string_of_int num_facts ^
blanchet@54816
   906
            " fact" ^ plural_s num_facts ^ " for " ^ string_of_time slice_timeout
blanchet@40553
   907
            |> Output.urgent_message
blanchet@40553
   908
          else
blanchet@40553
   909
            ()
blanchet@41168
   910
        val birth = Timer.checkRealTimer timer
blanchet@41171
   911
        val _ =
blanchet@41211
   912
          if debug then Output.urgent_message "Invoking SMT solver..." else ()
blanchet@41209
   913
        val (outcome, used_facts) =
blanchet@51204
   914
          SMT_Solver.smt_filter_preprocess ctxt [] goal weighted_facts i
blanchet@54816
   915
          |> SMT_Solver.smt_filter_apply slice_timeout
blanchet@41239
   916
          |> (fn {outcome, used_facts} => (outcome, used_facts))
blanchet@41209
   917
          handle exn => if Exn.is_interrupt exn then
blanchet@41209
   918
                          reraise exn
blanchet@41209
   919
                        else
blanchet@42061
   920
                          (ML_Compiler.exn_message exn
blanchet@41209
   921
                           |> SMT_Failure.Other_Failure |> SOME, [])
blanchet@41168
   922
        val death = Timer.checkRealTimer timer
blanchet@40553
   923
        val outcome0 = if is_none outcome0 then SOME outcome else outcome0
blanchet@41168
   924
        val time_so_far = Time.+ (time_so_far, Time.- (death, birth))
blanchet@40553
   925
        val too_many_facts_perhaps =
blanchet@40553
   926
          case outcome of
blanchet@40553
   927
            NONE => false
blanchet@40553
   928
          | SOME (SMT_Failure.Counterexample _) => false
blanchet@42443
   929
          | SOME SMT_Failure.Time_Out => slice_timeout <> timeout
blanchet@42614
   930
          | SOME (SMT_Failure.Abnormal_Termination _) => true (* kind of *)
blanchet@40553
   931
          | SOME SMT_Failure.Out_Of_Memory => true
blanchet@41211
   932
          | SOME (SMT_Failure.Other_Failure _) => true
blanchet@54816
   933
        val timeout = Time.- (timeout, Timer.checkRealTimer timer)
blanchet@40553
   934
      in
blanchet@54816
   935
        if too_many_facts_perhaps andalso slice < max_slices andalso num_facts > 0 andalso
blanchet@54816
   936
           Time.> (timeout, Time.zeroTime) then
blanchet@41169
   937
          let
blanchet@42614
   938
            val new_num_facts =
blanchet@54816
   939
              Real.ceil (Config.get ctxt smt_slice_fact_frac * Real.fromInt num_facts)
blanchet@51024
   940
            val weighted_factss as (new_fact_filter, _) :: _ =
blanchet@51024
   941
              weighted_factss
blanchet@54824
   942
              |> (fn (x :: xs) => xs @ [x])
blanchet@51024
   943
              |> app_hd (apsnd (take new_num_facts))
blanchet@51024
   944
            val show_filter = fact_filter <> new_fact_filter
blanchet@51024
   945
            fun num_of_facts fact_filter num_facts =
blanchet@51024
   946
              string_of_int num_facts ^
blanchet@51024
   947
              (if show_filter then " " ^ quote fact_filter else "") ^
blanchet@51024
   948
              " fact" ^ plural_s num_facts
blanchet@42614
   949
            val _ =
blanchet@53500
   950
              if debug then
blanchet@51024
   951
                quote name ^ " invoked with " ^
blanchet@51024
   952
                num_of_facts fact_filter num_facts ^ ": " ^
blanchet@53586
   953
                string_of_atp_failure (failure_of_smt_failure (the outcome)) ^
blanchet@51024
   954
                " Retrying with " ^ num_of_facts new_fact_filter new_num_facts ^
blanchet@51024
   955
                "..."
blanchet@42614
   956
                |> Output.urgent_message
blanchet@42614
   957
              else
blanchet@42614
   958
                ()
blanchet@42443
   959
          in
blanchet@51024
   960
            do_slice timeout (slice + 1) outcome0 time_so_far weighted_factss
blanchet@42443
   961
          end
blanchet@40553
   962
        else
blanchet@54824
   963
          {outcome = if is_none outcome then NONE else the outcome0, used_facts = used_facts,
blanchet@54824
   964
           used_from = map (apsnd snd) weighted_facts, run_time = time_so_far}
blanchet@40409
   965
      end
blanchet@54824
   966
  in
blanchet@54824
   967
    do_slice timeout 1 NONE Time.zeroTime
blanchet@54824
   968
  end
blanchet@40409
   969
blanchet@54824
   970
fun run_smt_solver mode name (params as {debug, verbose, preplay_timeout, ...}) minimize_command
blanchet@54824
   971
    ({state, goal, subgoal, subgoal_count, factss, ...} : prover_problem) =
blanchet@36379
   972
  let
blanchet@41242
   973
    val ctxt = Proof.context_of state
blanchet@51014
   974
    fun weight_facts facts =
blanchet@51014
   975
      let val num_facts = length facts in
blanchet@51014
   976
        facts ~~ (0 upto num_facts - 1)
blanchet@51014
   977
        |> map (weight_smt_fact ctxt num_facts)
blanchet@51014
   978
      end
blanchet@51024
   979
    val weighted_factss = factss |> map (apsnd weight_facts)
blanchet@51009
   980
    val {outcome, used_facts = used_pairs, used_from, run_time} =
blanchet@51014
   981
      smt_filter_loop name params state goal subgoal weighted_factss
blanchet@45781
   982
    val used_facts = used_pairs |> map fst
blanchet@52031
   983
    val outcome = outcome |> Option.map failure_of_smt_failure
blanchet@43261
   984
    val (preplay, message, message_tail) =
blanchet@40184
   985
      case outcome of
blanchet@40184
   986
        NONE =>
blanchet@50669
   987
        (Lazy.lazy (fn () =>
blanchet@50669
   988
           play_one_line_proof mode debug verbose preplay_timeout used_pairs
blanchet@50669
   989
               state subgoal SMT
blanchet@50669
   990
               (bunch_of_reconstructors false (fn desperate =>
blanchet@54500
   991
                  if desperate then liftingN else default_metis_lam_trans))),
blanchet@43052
   992
         fn preplay =>
blanchet@43052
   993
            let
blanchet@43052
   994
              val one_line_params =
blanchet@43052
   995
                (preplay, proof_banner mode name, used_facts,
blanchet@54824
   996
                 choose_minimize_command ctxt params minimize_command name preplay,
blanchet@43052
   997
                 subgoal, subgoal_count)
blanchet@48799
   998
              val num_chained = length (#facts (Proof.goal state))
blanchet@52754
   999
            in
wenzelm@53052
  1000
              one_line_proof_text num_chained one_line_params
blanchet@52754
  1001
            end,
blanchet@54824
  1002
         if verbose then "\nSMT solver real CPU time: " ^ string_of_time run_time ^ "." else "")
blanchet@43166
  1003
      | SOME failure =>
blanchet@54824
  1004
        (Lazy.value (plain_metis, Play_Failed),
blanchet@53586
  1005
         fn _ => string_of_atp_failure failure, "")
blanchet@40063
  1006
  in
blanchet@51009
  1007
    {outcome = outcome, used_facts = used_facts, used_from = used_from,
blanchet@51009
  1008
     run_time = run_time, preplay = preplay, message = message,
blanchet@51009
  1009
     message_tail = message_tail}
blanchet@40063
  1010
  end
blanchet@40063
  1011
blanchet@45520
  1012
fun run_reconstructor mode name
blanchet@45561
  1013
        (params as {debug, verbose, timeout, type_enc, lam_trans, ...})
blanchet@45379
  1014
        minimize_command
blanchet@51010
  1015
        ({state, subgoal, subgoal_count, factss = (_, facts) :: _, ...}
blanchet@51007
  1016
         : prover_problem) =
blanchet@43050
  1017
  let
blanchet@45520
  1018
    val reconstr =
blanchet@45520
  1019
      if name = metisN then
blanchet@45520
  1020
        Metis (type_enc |> the_default (hd partial_type_encs),
blanchet@54500
  1021
               lam_trans |> the_default default_metis_lam_trans)
blanchet@45520
  1022
      else if name = smtN then
blanchet@45520
  1023
        SMT
blanchet@45520
  1024
      else
blanchet@45520
  1025
        raise Fail ("unknown reconstructor: " ^ quote name)
blanchet@51005
  1026
    val used_facts = facts |> map fst
blanchet@43050
  1027
  in
blanchet@54828
  1028
    (case play_one_line_proof (if mode = Minimize then Normal else mode) debug verbose timeout facts
blanchet@54828
  1029
       state subgoal reconstr [reconstr] of
blanchet@54824
  1030
      play as (_, Played time) =>
blanchet@54824
  1031
      {outcome = NONE, used_facts = used_facts, used_from = facts, run_time = time,
blanchet@54824
  1032
       preplay = Lazy.value play,
blanchet@45561
  1033
       message =
blanchet@45561
  1034
         fn play =>
blanchet@45561
  1035
            let
blanchet@45561
  1036
              val (_, override_params) = extract_reconstructor params reconstr
blanchet@45561
  1037
              val one_line_params =
blanchet@54824
  1038
                (play, proof_banner mode name, used_facts, minimize_command override_params name,
blanchet@54824
  1039
                 subgoal, subgoal_count)
blanchet@48799
  1040
              val num_chained = length (#facts (Proof.goal state))
blanchet@52754
  1041
            in
wenzelm@53052
  1042
              one_line_proof_text num_chained one_line_params
blanchet@52754
  1043
            end,
blanchet@43261
  1044
       message_tail = ""}
blanchet@43052
  1045
    | play =>
blanchet@43166
  1046
      let
blanchet@54824
  1047
        val failure = (case play of (_, Play_Failed) => GaveUp | _ => TimedOut)
blanchet@43166
  1048
      in
blanchet@51009
  1049
        {outcome = SOME failure, used_facts = [], used_from = [],
blanchet@51009
  1050
         run_time = Time.zeroTime, preplay = Lazy.value play,
blanchet@53586
  1051
         message = fn _ => string_of_atp_failure failure, message_tail = ""}
blanchet@54824
  1052
      end)
blanchet@43050
  1053
  end
blanchet@43050
  1054
blanchet@43021
  1055
fun get_prover ctxt mode name =
wenzelm@42361
  1056
  let val thy = Proof_Context.theory_of ctxt in
blanchet@45379
  1057
    if is_reconstructor name then run_reconstructor mode name
blanchet@47606
  1058
    else if is_atp thy name then run_atp mode name (get_atp thy name ())
blanchet@43052
  1059
    else if is_smt_prover ctxt name then run_smt_solver mode name
blanchet@43052
  1060
    else error ("No such prover: " ^ name ^ ".")
blanchet@40941
  1061
  end
blanchet@40063
  1062
wenzelm@28582
  1063
end;