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