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