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