src/HOL/Tools/Sledgehammer/sledgehammer_provers.ML
author blanchet
Sun Jul 17 14:21:19 2011 +0200 (2011-07-17)
changeset 43864 58a7b3fdc193
parent 43863 a43d61270142
child 43928 24d6e759753f
permissions -rw-r--r--
fixed lambda-liftg: must ensure the formulas are in close form
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@43626
    27
     type_enc: type_enc 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@40062
    55
     run_time_in_msecs: int option,
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@43863
    63
  val concealedN : string
blanchet@43863
    64
  val liftingN : string
blanchet@43856
    65
  val combinatorsN : string
blanchet@43856
    66
  val lambdasN : string
blanchet@43856
    67
  val smartN : string
blanchet@43092
    68
  val dest_dir : string Config.T
blanchet@43092
    69
  val problem_prefix : string Config.T
blanchet@43092
    70
  val measure_run_time : bool Config.T
blanchet@43828
    71
  val atp_lambda_translation : string Config.T
blanchet@43092
    72
  val atp_readable_names : bool Config.T
blanchet@42646
    73
  val smt_triggers : bool Config.T
blanchet@42646
    74
  val smt_weights : bool Config.T
blanchet@42646
    75
  val smt_weight_min_facts : int Config.T
blanchet@42646
    76
  val smt_min_weight : int Config.T
blanchet@42646
    77
  val smt_max_weight : int Config.T
blanchet@42646
    78
  val smt_max_weight_index : int Config.T
blanchet@41256
    79
  val smt_weight_curve : (int -> int) Unsynchronized.ref
blanchet@42646
    80
  val smt_max_slices : int Config.T
blanchet@42646
    81
  val smt_slice_fact_frac : real Config.T
blanchet@42646
    82
  val smt_slice_time_frac : real Config.T
blanchet@42646
    83
  val smt_slice_min_secs : int Config.T
blanchet@43005
    84
  val das_tool : string
blanchet@41242
    85
  val select_smt_solver : string -> Proof.context -> Proof.context
blanchet@43233
    86
  val prover_name_for_reconstructor : reconstructor -> string option
blanchet@43050
    87
  val is_metis_prover : string -> bool
blanchet@43050
    88
  val is_atp : theory -> string -> bool
blanchet@41087
    89
  val is_smt_prover : Proof.context -> string -> bool
blanchet@42944
    90
  val is_unit_equational_atp : Proof.context -> string -> bool
blanchet@41727
    91
  val is_prover_supported : Proof.context -> string -> bool
blanchet@40072
    92
  val is_prover_installed : Proof.context -> string -> bool
blanchet@42443
    93
  val default_max_relevant_for_prover : Proof.context -> bool -> string -> int
blanchet@42944
    94
  val is_unit_equality : term -> bool
blanchet@42952
    95
  val is_appropriate_prop_for_prover : Proof.context -> string -> term -> bool
blanchet@40369
    96
  val is_built_in_const_for_prover :
blanchet@41336
    97
    Proof.context -> string -> string * typ -> term list -> bool * term list
blanchet@41087
    98
  val atp_relevance_fudge : relevance_fudge
blanchet@41087
    99
  val smt_relevance_fudge : relevance_fudge
blanchet@40941
   100
  val relevance_fudge_for_prover : Proof.context -> string -> relevance_fudge
blanchet@41256
   101
  val weight_smt_fact :
blanchet@42646
   102
    Proof.context -> int -> ((string * locality) * thm) * int
blanchet@41256
   103
    -> (string * locality) * (int option * thm)
blanchet@41091
   104
  val untranslated_fact : prover_fact -> (string * locality) * thm
blanchet@41242
   105
  val smt_weighted_fact :
blanchet@42646
   106
    Proof.context -> int -> prover_fact * int
blanchet@41256
   107
    -> (string * locality) * (int option * thm)
blanchet@41727
   108
  val supported_provers : Proof.context -> unit
blanchet@40059
   109
  val kill_provers : unit -> unit
blanchet@40059
   110
  val running_provers : unit -> unit
blanchet@40059
   111
  val messages : int option -> unit
blanchet@43033
   112
  val filter_used_facts : ''a list -> (''a * 'b) list -> (''a * 'b) list
blanchet@43021
   113
  val get_prover : Proof.context -> mode -> string -> prover
wenzelm@28477
   114
end;
wenzelm@28477
   115
blanchet@41087
   116
structure Sledgehammer_Provers : SLEDGEHAMMER_PROVERS =
wenzelm@28477
   117
struct
wenzelm@28477
   118
blanchet@43085
   119
open ATP_Util
blanchet@38028
   120
open ATP_Problem
blanchet@39491
   121
open ATP_Proof
blanchet@38028
   122
open ATP_Systems
blanchet@43085
   123
open ATP_Translate
blanchet@43085
   124
open ATP_Reconstruct
blanchet@38023
   125
open Sledgehammer_Util
blanchet@38988
   126
open Sledgehammer_Filter
blanchet@37583
   127
blanchet@37583
   128
(** The Sledgehammer **)
blanchet@37583
   129
blanchet@43021
   130
datatype mode = Auto_Try | Try | Normal | Minimize
blanchet@43021
   131
blanchet@38102
   132
(* Identifier to distinguish Sledgehammer from other tools using
blanchet@38102
   133
   "Async_Manager". *)
blanchet@43005
   134
val das_tool = "Sledgehammer"
blanchet@37585
   135
blanchet@43228
   136
val metisN = Metis_Tactics.metisN
blanchet@43228
   137
val metis_full_typesN = metisN ^ "_" ^ Metis_Tactics.full_typesN
blanchet@43228
   138
val metis_no_typesN = metisN ^ "_" ^ Metis_Tactics.no_typesN
blanchet@43050
   139
blanchet@43228
   140
val metis_prover_infos =
blanchet@43228
   141
  [(metisN, Metis),
blanchet@43228
   142
   (metis_full_typesN, Metis_Full_Types),
blanchet@43228
   143
   (metis_no_typesN, Metis_No_Types)]
blanchet@43228
   144
blanchet@43233
   145
val prover_name_for_reconstructor =
blanchet@43233
   146
  AList.find (op =) metis_prover_infos #> try hd
blanchet@43233
   147
blanchet@43228
   148
val metis_reconstructors = map snd metis_prover_infos
blanchet@43228
   149
blanchet@43228
   150
val is_metis_prover = AList.defined (op =) metis_prover_infos
blanchet@43050
   151
val is_atp = member (op =) o supported_atps
blanchet@43050
   152
blanchet@43233
   153
val select_smt_solver = Context.proof_map o SMT_Config.select_solver
blanchet@41242
   154
blanchet@40941
   155
fun is_smt_prover ctxt name =
boehmes@41432
   156
  member (op =) (SMT_Solver.available_solvers_of ctxt) name
blanchet@40062
   157
blanchet@42944
   158
fun is_unit_equational_atp ctxt name =
blanchet@42944
   159
  let val thy = Proof_Context.theory_of ctxt in
blanchet@42944
   160
    case try (get_atp thy) name of
blanchet@42944
   161
      SOME {formats, ...} => member (op =) formats CNF_UEQ
blanchet@42944
   162
    | NONE => false
blanchet@42944
   163
  end
blanchet@42944
   164
blanchet@41727
   165
fun is_prover_supported ctxt name =
wenzelm@42361
   166
  let val thy = Proof_Context.theory_of ctxt in
blanchet@43050
   167
    is_metis_prover name orelse is_atp thy name orelse is_smt_prover ctxt name
blanchet@40941
   168
  end
blanchet@40072
   169
boehmes@41432
   170
fun is_prover_installed ctxt =
blanchet@43050
   171
  is_metis_prover 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@43050
   177
val metis_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@43050
   181
    if is_metis_prover name then
blanchet@43050
   182
      metis_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@43228
   277
      map fst metis_prover_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@43626
   298
   type_enc: type_enc 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@43052
   326
   run_time_in_msecs: int option,
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@43033
   334
blanchet@38023
   335
(* configuration attributes *)
blanchet@38023
   336
blanchet@43863
   337
val concealedN = "concealed"
blanchet@43863
   338
val liftingN = "lifting"
blanchet@43856
   339
val combinatorsN = "combinators"
blanchet@43856
   340
val lambdasN = "lambdas"
blanchet@43856
   341
val smartN = "smart"
blanchet@43856
   342
blanchet@43092
   343
(* Empty string means create files in Isabelle's temporary files directory. *)
wenzelm@42616
   344
val dest_dir =
wenzelm@42616
   345
  Attrib.setup_config_string @{binding sledgehammer_dest_dir} (K "")
wenzelm@42616
   346
val problem_prefix =
wenzelm@42616
   347
  Attrib.setup_config_string @{binding sledgehammer_problem_prefix} (K "prob")
wenzelm@42616
   348
val measure_run_time =
wenzelm@42616
   349
  Attrib.setup_config_bool @{binding sledgehammer_measure_run_time} (K false)
wenzelm@28484
   350
blanchet@43828
   351
val atp_lambda_translation =
blanchet@43828
   352
  Attrib.setup_config_string @{binding sledgehammer_atp_lambda_translation}
blanchet@43828
   353
                             (K smartN)
blanchet@43092
   354
(* In addition to being easier to read, readable names are often much shorter,
blanchet@43092
   355
   especially if types are mangled in names. For these reason, they are enabled
blanchet@43092
   356
   by default. *)
blanchet@43092
   357
val atp_readable_names =
blanchet@43092
   358
  Attrib.setup_config_bool @{binding sledgehammer_atp_readable_names} (K true)
blanchet@43092
   359
blanchet@42646
   360
val smt_triggers =
blanchet@42646
   361
  Attrib.setup_config_bool @{binding sledgehammer_smt_triggers} (K true)
blanchet@42646
   362
val smt_weights =
blanchet@42646
   363
  Attrib.setup_config_bool @{binding sledgehammer_smt_weights} (K true)
blanchet@42646
   364
val smt_weight_min_facts =
blanchet@42646
   365
  Attrib.setup_config_int @{binding sledgehammer_smt_weight_min_facts} (K 20)
blanchet@41256
   366
blanchet@41256
   367
(* FUDGE *)
blanchet@42646
   368
val smt_min_weight =
blanchet@42646
   369
  Attrib.setup_config_int @{binding sledgehammer_smt_min_weight} (K 0)
blanchet@42646
   370
val smt_max_weight =
blanchet@42646
   371
  Attrib.setup_config_int @{binding sledgehammer_smt_max_weight} (K 10)
blanchet@42646
   372
val smt_max_weight_index =
blanchet@42646
   373
  Attrib.setup_config_int @{binding sledgehammer_smt_max_weight_index} (K 200)
blanchet@41256
   374
val smt_weight_curve = Unsynchronized.ref (fn x : int => x * x)
blanchet@41256
   375
blanchet@42646
   376
fun smt_fact_weight ctxt j num_facts =
blanchet@42646
   377
  if Config.get ctxt smt_weights andalso
blanchet@42646
   378
     num_facts >= Config.get ctxt smt_weight_min_facts then
blanchet@42646
   379
    let
blanchet@42646
   380
      val min = Config.get ctxt smt_min_weight
blanchet@42646
   381
      val max = Config.get ctxt smt_max_weight
blanchet@42646
   382
      val max_index = Config.get ctxt smt_max_weight_index
blanchet@42646
   383
      val curve = !smt_weight_curve
blanchet@42646
   384
    in
blanchet@42646
   385
      SOME (max - (max - min + 1) * curve (Int.max (0, max_index - j - 1))
blanchet@42646
   386
            div curve max_index)
blanchet@42646
   387
    end
blanchet@41256
   388
  else
blanchet@41256
   389
    NONE
blanchet@41256
   390
blanchet@42646
   391
fun weight_smt_fact ctxt num_facts ((info, th), j) =
blanchet@42646
   392
  let val thy = Proof_Context.theory_of ctxt in
blanchet@42646
   393
    (info, (smt_fact_weight ctxt j num_facts, th |> Thm.transfer thy))
blanchet@42646
   394
  end
blanchet@38023
   395
blanchet@41091
   396
fun untranslated_fact (Untranslated_Fact p) = p
blanchet@41242
   397
  | untranslated_fact (SMT_Weighted_Fact (info, (_, th))) = (info, th)
blanchet@41256
   398
fun smt_weighted_fact _ _ (SMT_Weighted_Fact p, _) = p
blanchet@42646
   399
  | smt_weighted_fact ctxt num_facts (fact, j) =
blanchet@42646
   400
    (untranslated_fact fact, j) |> weight_smt_fact ctxt num_facts
blanchet@41256
   401
blanchet@41313
   402
fun overlord_file_location_for_prover prover =
blanchet@41313
   403
  (getenv "ISABELLE_HOME_USER", "prob_" ^ prover)
blanchet@41313
   404
blanchet@43033
   405
fun with_path cleanup after f path =
blanchet@43033
   406
  Exn.capture f path
blanchet@43033
   407
  |> tap (fn _ => cleanup path)
blanchet@43033
   408
  |> Exn.release
blanchet@43033
   409
  |> tap (after path)
blanchet@43033
   410
blanchet@43052
   411
fun proof_banner mode name =
blanchet@43033
   412
  case mode of
blanchet@43033
   413
    Auto_Try => "Auto Sledgehammer (" ^ quote name ^ ") found a proof"
blanchet@43033
   414
  | Try => "Sledgehammer (" ^ quote name ^ ") found a proof"
blanchet@43052
   415
  | _ => "Try this"
blanchet@43033
   416
blanchet@43033
   417
(* based on "Mirabelle.can_apply" and generalized *)
blanchet@43034
   418
fun timed_apply timeout tac state i =
blanchet@43033
   419
  let
blanchet@43033
   420
    val {context = ctxt, facts, goal} = Proof.goal state
blanchet@43033
   421
    val full_tac = Method.insert_tac facts i THEN tac ctxt i
blanchet@43034
   422
  in TimeLimit.timeLimit timeout (try (Seq.pull o full_tac)) goal end
blanchet@43033
   423
blanchet@43211
   424
fun tac_for_reconstructor Metis =
blanchet@43626
   425
    Metis_Tactics.metis_tac [Metis_Tactics.partial_type_enc]
blanchet@43228
   426
  | tac_for_reconstructor Metis_Full_Types =
blanchet@43303
   427
    Metis_Tactics.metis_tac Metis_Tactics.full_type_syss
blanchet@43228
   428
  | tac_for_reconstructor Metis_No_Types =
blanchet@43626
   429
    Metis_Tactics.metis_tac [Metis_Tactics.no_type_enc]
blanchet@43034
   430
  | tac_for_reconstructor _ = raise Fail "unexpected reconstructor"
blanchet@43034
   431
blanchet@43034
   432
fun timed_reconstructor reconstructor debug timeout ths =
blanchet@43034
   433
  (Config.put Metis_Tactics.verbose debug
blanchet@43034
   434
   #> (fn ctxt => tac_for_reconstructor reconstructor ctxt ths))
blanchet@43034
   435
  |> timed_apply timeout
blanchet@43033
   436
blanchet@43033
   437
fun filter_used_facts used = filter (member (op =) used o fst)
blanchet@43033
   438
blanchet@43050
   439
fun play_one_line_proof debug timeout ths state i reconstructors =
blanchet@43034
   440
  let
blanchet@43166
   441
    fun play [] [] = Failed_to_Play (hd reconstructors)
blanchet@43219
   442
      | play timed_outs [] = Trust_Playable (List.last timed_outs, SOME timeout)
blanchet@43050
   443
      | play timed_out (reconstructor :: reconstructors) =
blanchet@43044
   444
        let val timer = Timer.startRealTimer () in
blanchet@43044
   445
          case timed_reconstructor reconstructor debug timeout ths state i of
blanchet@43050
   446
            SOME (SOME _) => Played (reconstructor, Timer.checkRealTimer timer)
blanchet@43050
   447
          | _ => play timed_out reconstructors
blanchet@43044
   448
        end
blanchet@43044
   449
        handle TimeLimit.TimeOut =>
blanchet@43050
   450
               play (reconstructor :: timed_out) reconstructors
blanchet@43034
   451
  in
blanchet@43044
   452
    if timeout = Time.zeroTime then Trust_Playable (hd reconstructors, NONE)
blanchet@43050
   453
    else play [] reconstructors
blanchet@43033
   454
  end
blanchet@43033
   455
blanchet@41313
   456
blanchet@41256
   457
(* generic TPTP-based ATPs *)
blanchet@40061
   458
blanchet@42730
   459
(* Too general means, positive equality literal with a variable X as one
blanchet@42730
   460
   operand, when X does not occur properly in the other operand. This rules out
blanchet@42730
   461
   clearly inconsistent facts such as X = a | X = b, though it by no means
blanchet@42730
   462
   guarantees soundness. *)
blanchet@42730
   463
blanchet@42730
   464
(* Unwanted equalities are those between a (bound or schematic) variable that
blanchet@42730
   465
   does not properly occur in the second operand. *)
blanchet@42730
   466
val is_exhaustive_finite =
blanchet@42730
   467
  let
blanchet@42730
   468
    fun is_bad_equal (Var z) t =
blanchet@42730
   469
        not (exists_subterm (fn Var z' => z = z' | _ => false) t)
blanchet@42730
   470
      | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
blanchet@42730
   471
      | is_bad_equal _ _ = false
blanchet@42730
   472
    fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
blanchet@42730
   473
    fun do_formula pos t =
blanchet@42730
   474
      case (pos, t) of
blanchet@42730
   475
        (_, @{const Trueprop} $ t1) => do_formula pos t1
blanchet@42730
   476
      | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
blanchet@42730
   477
        do_formula pos t'
blanchet@42730
   478
      | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
blanchet@42730
   479
        do_formula pos t'
blanchet@42730
   480
      | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
blanchet@42730
   481
        do_formula pos t'
blanchet@42730
   482
      | (_, @{const "==>"} $ t1 $ t2) =>
blanchet@42730
   483
        do_formula (not pos) t1 andalso
blanchet@42730
   484
        (t2 = @{prop False} orelse do_formula pos t2)
blanchet@42730
   485
      | (_, @{const HOL.implies} $ t1 $ t2) =>
blanchet@42730
   486
        do_formula (not pos) t1 andalso
blanchet@42730
   487
        (t2 = @{const False} orelse do_formula pos t2)
blanchet@42730
   488
      | (_, @{const Not} $ t1) => do_formula (not pos) t1
blanchet@42730
   489
      | (true, @{const HOL.disj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@42730
   490
      | (false, @{const HOL.conj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@42730
   491
      | (true, Const (@{const_name HOL.eq}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@42730
   492
      | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@42730
   493
      | _ => false
blanchet@42730
   494
  in do_formula true end
blanchet@42730
   495
blanchet@42730
   496
fun has_bound_or_var_of_type pred =
blanchet@42730
   497
  exists_subterm (fn Var (_, T as Type _) => pred T
blanchet@42730
   498
                   | Abs (_, T as Type _, _) => pred T
blanchet@42730
   499
                   | _ => false)
blanchet@42730
   500
blanchet@42730
   501
(* Facts are forbidden to contain variables of these types. The typical reason
blanchet@42730
   502
   is that they lead to unsoundness. Note that "unit" satisfies numerous
blanchet@42730
   503
   equations like "?x = ()". The resulting clauses will have no type constraint,
blanchet@42730
   504
   yielding false proofs. Even "bool" leads to many unsound proofs, though only
blanchet@42730
   505
   for higher-order problems. *)
blanchet@42730
   506
blanchet@42730
   507
(* Facts containing variables of type "unit" or "bool" or of the form
blanchet@42730
   508
   "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
blanchet@42730
   509
   are omitted. *)
blanchet@42944
   510
fun is_dangerous_prop ctxt =
blanchet@42944
   511
  transform_elim_prop
blanchet@43572
   512
  #> (has_bound_or_var_of_type (is_type_surely_finite ctxt false) orf
blanchet@42730
   513
      is_exhaustive_finite)
blanchet@42730
   514
blanchet@40409
   515
fun int_opt_add (SOME m) (SOME n) = SOME (m + n)
blanchet@40409
   516
  | int_opt_add _ _ = NONE
blanchet@40062
   517
blanchet@39492
   518
(* Important messages are important but not so important that users want to see
blanchet@39492
   519
   them each time. *)
blanchet@42609
   520
val atp_important_message_keep_quotient = 10
blanchet@39492
   521
blanchet@43626
   522
fun choose_format_and_type_enc best_type_enc formats type_enc_opt =
blanchet@43626
   523
  (case type_enc_opt of
blanchet@43569
   524
     SOME ts => ts
blanchet@43626
   525
   | NONE => type_enc_from_string best_type_enc)
blanchet@43569
   526
  |> choose_format formats
blanchet@42548
   527
blanchet@43856
   528
fun translate_atp_lambdas ctxt type_enc =
blanchet@43828
   529
  Config.get ctxt atp_lambda_translation
blanchet@43828
   530
  |> (fn trans =>
blanchet@43828
   531
         if trans = smartN then
blanchet@43828
   532
           if is_type_enc_higher_order type_enc then lambdasN else combinatorsN
blanchet@43830
   533
         else if trans = lambdasN andalso
blanchet@43830
   534
                 not (is_type_enc_higher_order type_enc) then
blanchet@43864
   535
           error ("Lambda translation method incompatible with first-order \
blanchet@43864
   536
                  \encoding.")
blanchet@43828
   537
         else
blanchet@43828
   538
           trans)
blanchet@43856
   539
  |> (fn trans =>
blanchet@43863
   540
         if trans = concealedN then
blanchet@43863
   541
           rpair [] o map (conceal_lambdas ctxt)
blanchet@43863
   542
         else if trans = liftingN then
blanchet@43864
   543
           map (close_form o Envir.eta_contract)
blanchet@43864
   544
           #> SMT_Translate.lift_lambdas ctxt false #> snd #> swap
blanchet@43862
   545
         else if trans = combinatorsN then
blanchet@43863
   546
           rpair [] o map (introduce_combinators ctxt)
blanchet@43862
   547
         else if trans = lambdasN then
blanchet@43863
   548
           rpair [] o map (Envir.eta_contract)
blanchet@43862
   549
         else
blanchet@43862
   550
           error ("Unknown lambda translation method: " ^ quote trans ^ "."))
blanchet@43828
   551
blanchet@43051
   552
val metis_minimize_max_time = seconds 2.0
blanchet@43051
   553
blanchet@43051
   554
fun choose_minimize_command minimize_command name preplay =
blanchet@43051
   555
  (case preplay of
blanchet@43051
   556
     Played (reconstructor, time) =>
blanchet@43051
   557
     if Time.<= (time, metis_minimize_max_time) then
blanchet@43233
   558
       prover_name_for_reconstructor reconstructor |> the_default name
blanchet@43051
   559
     else
blanchet@43051
   560
       name
blanchet@43051
   561
   | _ => name)
blanchet@43051
   562
  |> minimize_command
blanchet@43051
   563
blanchet@43267
   564
fun repair_monomorph_context max_iters max_new_instances =
blanchet@43232
   565
  Config.put Monomorph.max_rounds max_iters
blanchet@43267
   566
  #> Config.put Monomorph.max_new_instances max_new_instances
boehmes@43230
   567
  #> Config.put Monomorph.keep_partial_instances false
blanchet@43226
   568
blanchet@43631
   569
(* Give the ATPs some slack before interrupting them the hard way. "z3_atp" on
blanchet@43631
   570
   Linux appears to be the only ATP that does not honor its time limit. *)
blanchet@43690
   571
val atp_timeout_slack = seconds 1.0
blanchet@43631
   572
blanchet@43021
   573
fun run_atp mode name
blanchet@42578
   574
        ({exec, required_execs, arguments, proof_delims, known_failures,
blanchet@42723
   575
          conj_sym_kind, prem_kind, formats, best_slices, ...} : atp_config)
blanchet@43626
   576
        ({debug, verbose, overlord, type_enc, sound, max_relevant,
blanchet@43572
   577
          max_mono_iters, max_new_mono_instances, isar_proof,
blanchet@43572
   578
          isar_shrink_factor, slicing, timeout, preplay_timeout, ...} : params)
blanchet@43037
   579
        minimize_command
blanchet@43037
   580
        ({state, goal, subgoal, subgoal_count, facts, ...} : prover_problem) =
blanchet@38023
   581
  let
blanchet@42182
   582
    val thy = Proof.theory_of state
blanchet@39318
   583
    val ctxt = Proof.context_of state
blanchet@43004
   584
    val (_, hyp_ts, concl_t) = strip_subgoal ctxt goal subgoal
blanchet@41159
   585
    val (dest_dir, problem_prefix) =
blanchet@41159
   586
      if overlord then overlord_file_location_for_prover name
blanchet@41159
   587
      else (Config.get ctxt dest_dir, Config.get ctxt problem_prefix)
blanchet@40061
   588
    val problem_file_name =
blanchet@41159
   589
      Path.basic (problem_prefix ^ (if overlord then "" else serial_string ()) ^
blanchet@41159
   590
                  "_" ^ string_of_int subgoal)
blanchet@40061
   591
    val problem_path_name =
blanchet@40059
   592
      if dest_dir = "" then
blanchet@40061
   593
        File.tmp_path problem_file_name
blanchet@40059
   594
      else if File.exists (Path.explode dest_dir) then
blanchet@40061
   595
        Path.append (Path.explode dest_dir) problem_file_name
blanchet@39003
   596
      else
blanchet@40059
   597
        error ("No such directory: " ^ quote dest_dir ^ ".")
blanchet@39003
   598
    val measure_run_time = verbose orelse Config.get ctxt measure_run_time
blanchet@38092
   599
    val command = Path.explode (getenv (fst exec) ^ "/" ^ snd exec)
blanchet@38023
   600
    fun split_time s =
blanchet@38023
   601
      let
blanchet@42448
   602
        val split = String.tokens (fn c => str c = "\n")
blanchet@42448
   603
        val (output, t) = s |> split |> split_last |> apfst cat_lines
blanchet@42448
   604
        fun as_num f = f >> (fst o read_int)
blanchet@42448
   605
        val num = as_num (Scan.many1 Symbol.is_ascii_digit)
blanchet@42448
   606
        val digit = Scan.one Symbol.is_ascii_digit
blanchet@42448
   607
        val num3 = as_num (digit ::: digit ::: (digit >> single))
blanchet@42448
   608
        val time = num --| Scan.$$ "." -- num3 >> (fn (a, b) => a * 1000 + b)
wenzelm@40627
   609
        val as_time = Scan.read Symbol.stopper time o raw_explode
blanchet@42448
   610
      in (output, as_time t) end
blanchet@41313
   611
    fun run_on prob_file =
blanchet@38092
   612
      case filter (curry (op =) "" o getenv o fst) (exec :: required_execs) of
blanchet@38032
   613
        (home_var, _) :: _ =>
blanchet@38023
   614
        error ("The environment variable " ^ quote home_var ^ " is not set.")
blanchet@38032
   615
      | [] =>
blanchet@38032
   616
        if File.exists command then
blanchet@38032
   617
          let
blanchet@42443
   618
            (* If slicing is disabled, we expand the last slice to fill the
blanchet@42443
   619
               entire time available. *)
blanchet@43222
   620
            val actual_slices = get_slices slicing (best_slices ctxt)
blanchet@42443
   621
            val num_actual_slices = length actual_slices
blanchet@42445
   622
            fun monomorphize_facts facts =
blanchet@42445
   623
              let
blanchet@43226
   624
                val ctxt =
blanchet@43267
   625
                  ctxt |> repair_monomorph_context max_mono_iters
blanchet@43226
   626
                                                   max_new_mono_instances
blanchet@42445
   627
                (* pseudo-theorem involving the same constants as the subgoal *)
blanchet@42445
   628
                val subgoal_th =
blanchet@42445
   629
                  Logic.list_implies (hyp_ts, concl_t)
blanchet@42445
   630
                  |> Skip_Proof.make_thm thy
blanchet@43249
   631
                val rths =
blanchet@43249
   632
                  facts |> chop (length facts div 4)
blanchet@43249
   633
                        |>> map (pair 1 o snd)
blanchet@43249
   634
                        ||> map (pair 2 o snd)
blanchet@43249
   635
                        |> op @
blanchet@43249
   636
                        |> cons (0, subgoal_th)
blanchet@42445
   637
              in
blanchet@43249
   638
                Monomorph.monomorph atp_schematic_consts_of rths ctxt
blanchet@43226
   639
                |> fst |> tl
blanchet@43226
   640
                |> curry ListPair.zip (map fst facts)
blanchet@43226
   641
                |> maps (fn (name, rths) => map (pair name o snd) rths)
blanchet@42445
   642
              end
blanchet@43480
   643
            fun run_slice (slice, (time_frac, (complete,
blanchet@43626
   644
                                    (best_max_relevant, best_type_enc, extra))))
blanchet@42443
   645
                          time_left =
blanchet@38032
   646
              let
blanchet@42443
   647
                val num_facts =
blanchet@42443
   648
                  length facts |> is_none max_relevant
blanchet@42723
   649
                                  ? Integer.min best_max_relevant
blanchet@43626
   650
                val (format, type_enc) =
blanchet@43626
   651
                  choose_format_and_type_enc best_type_enc formats type_enc
blanchet@43626
   652
                val fairly_sound = is_type_enc_fairly_sound type_enc
blanchet@42451
   653
                val facts =
blanchet@43214
   654
                  facts |> map untranslated_fact
blanchet@43214
   655
                        |> not fairly_sound
blanchet@43214
   656
                           ? filter_out (is_dangerous_prop ctxt o prop_of o snd)
blanchet@42638
   657
                        |> take num_facts
blanchet@43626
   658
                        |> polymorphism_of_type_enc type_enc <> Polymorphic
blanchet@42589
   659
                           ? monomorphize_facts
blanchet@43226
   660
                        |> map (apsnd prop_of)
blanchet@42443
   661
                val real_ms = Real.fromInt o Time.toMilliseconds
blanchet@42443
   662
                val slice_timeout =
blanchet@42443
   663
                  ((real_ms time_left
blanchet@42443
   664
                    |> (if slice < num_actual_slices - 1 then
blanchet@42443
   665
                          curry Real.min (time_frac * real_ms timeout)
blanchet@42443
   666
                        else
blanchet@42443
   667
                          I))
blanchet@42443
   668
                   * 0.001) |> seconds
blanchet@43655
   669
                val generous_slice_timeout =
blanchet@43655
   670
                  Time.+ (slice_timeout, atp_timeout_slack)
blanchet@42443
   671
                val _ =
blanchet@42614
   672
                  if debug then
blanchet@42699
   673
                    quote name ^ " slice #" ^ string_of_int (slice + 1) ^
blanchet@42699
   674
                    " with " ^ string_of_int num_facts ^ " fact" ^
blanchet@42699
   675
                    plural_s num_facts ^ " for " ^
blanchet@42699
   676
                    string_from_time slice_timeout ^ "..."
blanchet@42443
   677
                    |> Output.urgent_message
blanchet@42443
   678
                  else
blanchet@42443
   679
                    ()
blanchet@42541
   680
                val (atp_problem, pool, conjecture_offset, facts_offset,
blanchet@42881
   681
                     fact_names, typed_helpers, sym_tab) =
blanchet@42939
   682
                  prepare_atp_problem ctxt format conj_sym_kind prem_kind
blanchet@43856
   683
                      type_enc sound false (translate_atp_lambdas ctxt type_enc)
blanchet@43828
   684
                      (Config.get ctxt atp_readable_names) true hyp_ts concl_t
blanchet@43828
   685
                      facts
blanchet@41313
   686
                fun weights () = atp_problem_weights atp_problem
blanchet@43360
   687
                val full_proof = debug orelse isar_proof
blanchet@41313
   688
                val core =
blanchet@41313
   689
                  File.shell_path command ^ " " ^
blanchet@43473
   690
                  arguments ctxt full_proof extra slice_timeout weights ^ " " ^
blanchet@41313
   691
                  File.shell_path prob_file
blanchet@41313
   692
                val command =
blanchet@41313
   693
                  (if measure_run_time then
blanchet@41313
   694
                     "TIMEFORMAT='%3R'; { time " ^ core ^ " ; }"
blanchet@41313
   695
                   else
blanchet@41313
   696
                     "exec " ^ core) ^ " 2>&1"
blanchet@42443
   697
                val _ =
blanchet@42443
   698
                  atp_problem
blanchet@43224
   699
                  |> tptp_lines_for_atp_problem format
blanchet@42443
   700
                  |> cons ("% " ^ command ^ "\n")
blanchet@42443
   701
                  |> File.write_list prob_file
blanchet@42443
   702
                val conjecture_shape =
blanchet@42443
   703
                  conjecture_offset + 1
blanchet@42443
   704
                    upto conjecture_offset + length hyp_ts + 1
blanchet@42443
   705
                  |> map single
blanchet@43631
   706
                val ((output, msecs), (atp_proof, outcome)) =
wenzelm@43850
   707
                  TimeLimit.timeLimit generous_slice_timeout Isabelle_System.bash_output command
blanchet@38032
   708
                  |>> (if overlord then
blanchet@38032
   709
                         prefix ("% " ^ command ^ "\n% " ^ timestamp () ^ "\n")
blanchet@38032
   710
                       else
blanchet@38032
   711
                         I)
blanchet@43631
   712
                  |> fst
blanchet@43631
   713
                  |> (if measure_run_time then split_time else rpair NONE)
blanchet@43631
   714
                  |> (fn accum as (output, _) =>
blanchet@43631
   715
                         (accum,
blanchet@43631
   716
                          extract_tstplike_proof_and_outcome verbose complete
blanchet@43631
   717
                              proof_delims known_failures output
blanchet@43631
   718
                          |>> atp_proof_from_tstplike_proof atp_problem output
blanchet@43631
   719
                          handle UNRECOGNIZED_ATP_PROOF () =>
blanchet@43631
   720
                                 ([], SOME ProofIncomplete)))
blanchet@43631
   721
                  handle TimeLimit.TimeOut =>
blanchet@43631
   722
                         (("", SOME (Time.toMilliseconds slice_timeout)),
blanchet@43631
   723
                          ([], SOME TimedOut))
blanchet@42449
   724
                val outcome =
blanchet@42451
   725
                  case outcome of
blanchet@42587
   726
                    NONE =>
blanchet@43304
   727
                    used_facts_in_unsound_atp_proof ctxt
blanchet@42876
   728
                        conjecture_shape facts_offset fact_names atp_proof
blanchet@42876
   729
                    |> Option.map (fn facts =>
blanchet@43823
   730
                           UnsoundProof
blanchet@43823
   731
                               (if is_type_enc_virtually_sound type_enc then
blanchet@43823
   732
                                  SOME sound
blanchet@43823
   733
                                else
blanchet@43823
   734
                                  NONE, facts |> sort string_ord))
blanchet@42451
   735
                  | _ => outcome
blanchet@42443
   736
              in
blanchet@42881
   737
                ((pool, conjecture_shape, facts_offset, fact_names,
blanchet@42881
   738
                  typed_helpers, sym_tab),
blanchet@43304
   739
                 (output, msecs, atp_proof, outcome))
blanchet@42443
   740
              end
blanchet@38645
   741
            val timer = Timer.startRealTimer ()
blanchet@43480
   742
            fun maybe_run_slice slice (result as (_, (_, msecs0, _, SOME _))) =
blanchet@42452
   743
                let
blanchet@42452
   744
                  val time_left = Time.- (timeout, Timer.checkRealTimer timer)
blanchet@42452
   745
                in
blanchet@42452
   746
                  if Time.<= (time_left, Time.zeroTime) then
blanchet@42452
   747
                    result
blanchet@42452
   748
                  else
blanchet@43480
   749
                    (run_slice slice time_left
blanchet@43304
   750
                     |> (fn (stuff, (output, msecs, atp_proof, outcome)) =>
blanchet@43304
   751
                            (stuff, (output, int_opt_add msecs0 msecs,
blanchet@42723
   752
                                     atp_proof, outcome))))
blanchet@42452
   753
                end
blanchet@43480
   754
              | maybe_run_slice _ result = result
blanchet@42443
   755
          in
blanchet@42881
   756
            ((Symtab.empty, [], 0, Vector.fromList [], [], Symtab.empty),
blanchet@43304
   757
             ("", SOME 0, [], SOME InternalError))
blanchet@43480
   758
            |> fold maybe_run_slice actual_slices
blanchet@42443
   759
          end
blanchet@38032
   760
        else
wenzelm@43602
   761
          error ("Bad executable: " ^ Path.print command)
blanchet@38023
   762
blanchet@38023
   763
    (* If the problem file has not been exported, remove it; otherwise, export
blanchet@38023
   764
       the proof file too. *)
blanchet@41313
   765
    fun cleanup prob_file =
blanchet@41313
   766
      if dest_dir = "" then try File.rm prob_file else NONE
blanchet@43304
   767
    fun export prob_file (_, (output, _, _, _)) =
blanchet@40059
   768
      if dest_dir = "" then
blanchet@38023
   769
        ()
blanchet@38023
   770
      else
blanchet@41313
   771
        File.write (Path.explode (Path.implode prob_file ^ "_proof")) output
blanchet@42881
   772
    val ((pool, conjecture_shape, facts_offset, fact_names, typed_helpers,
blanchet@42881
   773
          sym_tab),
blanchet@43304
   774
         (output, msecs, atp_proof, outcome)) =
blanchet@40061
   775
      with_path cleanup export run_on problem_path_name
blanchet@39492
   776
    val important_message =
blanchet@43021
   777
      if mode = Normal andalso
blanchet@42609
   778
         random_range 0 (atp_important_message_keep_quotient - 1) = 0 then
blanchet@39492
   779
        extract_important_message output
blanchet@39492
   780
      else
blanchet@39492
   781
        ""
blanchet@43261
   782
    val (used_facts, preplay, message, message_tail) =
blanchet@38023
   783
      case outcome of
blanchet@38023
   784
        NONE =>
blanchet@43033
   785
        let
blanchet@43033
   786
          val used_facts =
blanchet@43304
   787
            used_facts_in_atp_proof ctxt facts_offset fact_names atp_proof
blanchet@43033
   788
        in
blanchet@43052
   789
          (used_facts,
blanchet@43052
   790
           fn () =>
blanchet@43052
   791
              let
blanchet@43052
   792
                val used_ths =
blanchet@43052
   793
                  facts |> map untranslated_fact |> filter_used_facts used_facts
blanchet@43052
   794
                        |> map snd
blanchet@43052
   795
              in
blanchet@43577
   796
                (if mode = Minimize then
blanchet@43577
   797
                   Output.urgent_message "Preplaying proof..."
blanchet@43577
   798
                 else
blanchet@43577
   799
                   ());
blanchet@43052
   800
                play_one_line_proof debug preplay_timeout used_ths state subgoal
blanchet@43228
   801
                                    metis_reconstructors
blanchet@43052
   802
              end,
blanchet@43052
   803
           fn preplay =>
blanchet@43052
   804
              let
blanchet@43052
   805
                val full_types = uses_typed_helpers typed_helpers atp_proof
blanchet@43052
   806
                val isar_params =
blanchet@43304
   807
                  (debug, full_types, isar_shrink_factor, pool,
blanchet@43304
   808
                   conjecture_shape, facts_offset, fact_names, sym_tab,
blanchet@43304
   809
                   atp_proof, goal)
blanchet@43052
   810
                val one_line_params =
blanchet@43052
   811
                  (preplay, proof_banner mode name, used_facts,
blanchet@43052
   812
                   choose_minimize_command minimize_command name preplay,
blanchet@43052
   813
                   subgoal, subgoal_count)
blanchet@43261
   814
              in proof_text ctxt isar_proof isar_params one_line_params end,
blanchet@43261
   815
           (if verbose then
blanchet@43261
   816
              "\nATP real CPU time: " ^
blanchet@43261
   817
              string_from_time (Time.fromMilliseconds (the msecs)) ^ "."
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@43261
   827
        ([], K (Failed_to_Play Metis), fn _ => string_for_failure failure, "")
blanchet@38023
   828
  in
blanchet@43052
   829
    {outcome = outcome, used_facts = used_facts, run_time_in_msecs = msecs,
blanchet@43261
   830
     preplay = preplay, message = message, message_tail = message_tail}
blanchet@38023
   831
  end
blanchet@38023
   832
blanchet@40669
   833
(* "SMT_Failure.Abnormal_Termination" carries the solver's return code. Until
blanchet@40669
   834
   these are sorted out properly in the SMT module, we have to interpret these
blanchet@40669
   835
   ourselves. *)
blanchet@40684
   836
val remote_smt_failures =
blanchet@43631
   837
  [(2, NoLibwwwPerl),
blanchet@43631
   838
   (22, CantConnect)]
blanchet@40684
   839
val z3_failures =
blanchet@41236
   840
  [(101, OutOfResources),
blanchet@41236
   841
   (103, MalformedInput),
blanchet@41222
   842
   (110, MalformedInput)]
blanchet@40684
   843
val unix_failures =
blanchet@40684
   844
  [(139, Crashed)]
blanchet@43631
   845
val smt_failures = remote_smt_failures @ z3_failures @ unix_failures
blanchet@40555
   846
blanchet@42100
   847
fun failure_from_smt_failure (SMT_Failure.Counterexample {is_real_cex, ...}) =
blanchet@43050
   848
    if is_real_cex then Unprovable else GaveUp
blanchet@41222
   849
  | failure_from_smt_failure SMT_Failure.Time_Out = TimedOut
blanchet@41222
   850
  | failure_from_smt_failure (SMT_Failure.Abnormal_Termination code) =
blanchet@41222
   851
    (case AList.lookup (op =) smt_failures code of
blanchet@40684
   852
       SOME failure => failure
blanchet@41259
   853
     | NONE => UnknownError ("Abnormal termination with exit code " ^
blanchet@41259
   854
                             string_of_int code ^ "."))
blanchet@41222
   855
  | failure_from_smt_failure SMT_Failure.Out_Of_Memory = OutOfResources
blanchet@41222
   856
  | failure_from_smt_failure (SMT_Failure.Other_Failure msg) =
blanchet@42061
   857
    UnknownError msg
blanchet@40063
   858
blanchet@40698
   859
(* FUDGE *)
blanchet@42646
   860
val smt_max_slices =
blanchet@42646
   861
  Attrib.setup_config_int @{binding sledgehammer_smt_max_slices} (K 8)
blanchet@42646
   862
val smt_slice_fact_frac =
blanchet@42646
   863
  Attrib.setup_config_real @{binding sledgehammer_smt_slice_fact_frac} (K 0.5)
blanchet@42646
   864
val smt_slice_time_frac =
blanchet@42646
   865
  Attrib.setup_config_real @{binding sledgehammer_smt_slice_time_frac} (K 0.5)
blanchet@42646
   866
val smt_slice_min_secs =
blanchet@42646
   867
  Attrib.setup_config_int @{binding sledgehammer_smt_slice_min_secs} (K 5)
blanchet@40409
   868
blanchet@42646
   869
fun smt_filter_loop ctxt name
blanchet@42724
   870
                    ({debug, verbose, overlord, max_mono_iters,
blanchet@42740
   871
                      max_new_mono_instances, timeout, slicing, ...} : params)
blanchet@41741
   872
                    state i smt_filter =
blanchet@40409
   873
  let
blanchet@42646
   874
    val max_slices = if slicing then Config.get ctxt smt_max_slices else 1
blanchet@41242
   875
    val repair_context =
blanchet@43233
   876
      select_smt_solver name
blanchet@43233
   877
      #> (if overlord then
blanchet@43233
   878
            Config.put SMT_Config.debug_files
blanchet@43233
   879
                       (overlord_file_location_for_prover name
blanchet@43233
   880
                        |> (fn (path, name) => path ^ "/" ^ name))
blanchet@43233
   881
          else
blanchet@43233
   882
            I)
blanchet@43233
   883
      #> Config.put SMT_Config.infer_triggers (Config.get ctxt smt_triggers)
blanchet@41242
   884
    val state = state |> Proof.map_context repair_context
blanchet@42443
   885
    fun do_slice timeout slice outcome0 time_so_far facts =
blanchet@40553
   886
      let
blanchet@40553
   887
        val timer = Timer.startRealTimer ()
blanchet@42724
   888
        val state =
blanchet@42724
   889
          state |> Proof.map_context
blanchet@43267
   890
                       (repair_monomorph_context max_mono_iters
blanchet@43267
   891
                                                 max_new_mono_instances)
blanchet@40553
   892
        val ms = timeout |> Time.toMilliseconds
blanchet@42443
   893
        val slice_timeout =
blanchet@42443
   894
          if slice < max_slices then
blanchet@41169
   895
            Int.min (ms,
blanchet@42646
   896
                Int.max (1000 * Config.get ctxt smt_slice_min_secs,
blanchet@42646
   897
                    Real.ceil (Config.get ctxt smt_slice_time_frac
blanchet@42646
   898
                               * Real.fromInt ms)))
blanchet@40553
   899
            |> Time.fromMilliseconds
blanchet@40553
   900
          else
blanchet@40553
   901
            timeout
blanchet@40553
   902
        val num_facts = length facts
blanchet@40553
   903
        val _ =
blanchet@42614
   904
          if debug then
blanchet@42614
   905
            quote name ^ " slice " ^ string_of_int slice ^ " with " ^
blanchet@42614
   906
            string_of_int num_facts ^ " fact" ^ plural_s num_facts ^ " for " ^
blanchet@42614
   907
            string_from_time slice_timeout ^ "..."
blanchet@40553
   908
            |> Output.urgent_message
blanchet@40553
   909
          else
blanchet@40553
   910
            ()
blanchet@41168
   911
        val birth = Timer.checkRealTimer timer
blanchet@41171
   912
        val _ =
blanchet@41211
   913
          if debug then Output.urgent_message "Invoking SMT solver..." else ()
blanchet@41209
   914
        val (outcome, used_facts) =
blanchet@42443
   915
          (case (slice, smt_filter) of
boehmes@41432
   916
             (1, SOME head) => head |> apsnd (apsnd repair_context)
boehmes@41432
   917
           | _ => SMT_Solver.smt_filter_preprocess state facts i)
blanchet@42443
   918
          |> SMT_Solver.smt_filter_apply slice_timeout
blanchet@41239
   919
          |> (fn {outcome, used_facts} => (outcome, used_facts))
blanchet@41209
   920
          handle exn => if Exn.is_interrupt exn then
blanchet@41209
   921
                          reraise exn
blanchet@41209
   922
                        else
blanchet@42061
   923
                          (ML_Compiler.exn_message exn
blanchet@41209
   924
                           |> SMT_Failure.Other_Failure |> SOME, [])
blanchet@41168
   925
        val death = Timer.checkRealTimer timer
blanchet@40553
   926
        val outcome0 = if is_none outcome0 then SOME outcome else outcome0
blanchet@41168
   927
        val time_so_far = Time.+ (time_so_far, Time.- (death, birth))
blanchet@40553
   928
        val too_many_facts_perhaps =
blanchet@40553
   929
          case outcome of
blanchet@40553
   930
            NONE => false
blanchet@40553
   931
          | SOME (SMT_Failure.Counterexample _) => false
blanchet@42443
   932
          | SOME SMT_Failure.Time_Out => slice_timeout <> timeout
blanchet@42614
   933
          | SOME (SMT_Failure.Abnormal_Termination _) => true (* kind of *)
blanchet@40553
   934
          | SOME SMT_Failure.Out_Of_Memory => true
blanchet@41211
   935
          | SOME (SMT_Failure.Other_Failure _) => true
blanchet@40553
   936
        val timeout = Time.- (timeout, Timer.checkRealTimer timer)
blanchet@40553
   937
      in
blanchet@42443
   938
        if too_many_facts_perhaps andalso slice < max_slices andalso
blanchet@40553
   939
           num_facts > 0 andalso Time.> (timeout, Time.zeroTime) then
blanchet@41169
   940
          let
blanchet@42614
   941
            val new_num_facts =
blanchet@42646
   942
              Real.ceil (Config.get ctxt smt_slice_fact_frac
blanchet@42646
   943
                         * Real.fromInt num_facts)
blanchet@42614
   944
            val _ =
blanchet@42614
   945
              if verbose andalso is_some outcome then
blanchet@42614
   946
                quote name ^ " invoked with " ^ string_of_int num_facts ^
blanchet@42614
   947
                " fact" ^ plural_s num_facts ^ ": " ^
blanchet@42614
   948
                string_for_failure (failure_from_smt_failure (the outcome)) ^
blanchet@42614
   949
                " Retrying with " ^ string_of_int new_num_facts ^ " fact" ^
blanchet@42638
   950
                plural_s new_num_facts ^ "..."
blanchet@42614
   951
                |> Output.urgent_message
blanchet@42614
   952
              else
blanchet@42614
   953
                ()
blanchet@42443
   954
          in
blanchet@42614
   955
            facts |> take new_num_facts
blanchet@42614
   956
                  |> do_slice timeout (slice + 1) outcome0 time_so_far
blanchet@42443
   957
          end
blanchet@40553
   958
        else
blanchet@40553
   959
          {outcome = if is_none outcome then NONE else the outcome0,
blanchet@41168
   960
           used_facts = used_facts,
blanchet@41168
   961
           run_time_in_msecs = SOME (Time.toMilliseconds 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@40181
   974
    val {outcome, used_facts, run_time_in_msecs} =
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@43052
   982
            let
blanchet@43052
   983
              fun smt_settings () =
blanchet@43052
   984
                if name = SMT_Solver.solver_name_of ctxt then ""
blanchet@43052
   985
                else "smt_solver = " ^ maybe_quote name
blanchet@43052
   986
            in
blanchet@43052
   987
              case play_one_line_proof debug preplay_timeout used_ths state
blanchet@43228
   988
                                       subgoal metis_reconstructors of
blanchet@43168
   989
                p as Played _ => p
blanchet@43168
   990
              | _ => Trust_Playable (SMT (smt_settings ()), NONE)
blanchet@43052
   991
            end,
blanchet@43052
   992
         fn preplay =>
blanchet@43052
   993
            let
blanchet@43052
   994
              val one_line_params =
blanchet@43052
   995
                (preplay, proof_banner mode name, used_facts,
blanchet@43052
   996
                 choose_minimize_command minimize_command name preplay,
blanchet@43052
   997
                 subgoal, subgoal_count)
blanchet@43261
   998
            in one_line_proof_text one_line_params end,
blanchet@43261
   999
         if verbose then
blanchet@43261
  1000
           "\nSMT solver real CPU time: " ^
blanchet@43261
  1001
           string_from_time (Time.fromMilliseconds
blanchet@43261
  1002
                                 (the run_time_in_msecs)) ^ "."
blanchet@43261
  1003
         else
blanchet@43261
  1004
           "")
blanchet@43166
  1005
      | SOME failure =>
blanchet@43261
  1006
        (K (Failed_to_Play Metis), fn _ => string_for_failure failure, "")
blanchet@40063
  1007
  in
blanchet@43037
  1008
    {outcome = outcome, used_facts = used_facts,
blanchet@43052
  1009
     run_time_in_msecs = run_time_in_msecs, preplay = preplay,
blanchet@43261
  1010
     message = message, message_tail = message_tail}
blanchet@40063
  1011
  end
blanchet@40063
  1012
blanchet@43052
  1013
fun run_metis mode name ({debug, timeout, ...} : params) minimize_command
blanchet@43050
  1014
              ({state, subgoal, subgoal_count, facts, ...} : prover_problem) =
blanchet@43050
  1015
  let
blanchet@43228
  1016
    val reconstructor =
blanchet@43228
  1017
      case AList.lookup (op =) metis_prover_infos name of
blanchet@43228
  1018
        SOME r => r
blanchet@43228
  1019
      | NONE => raise Fail ("unknown Metis version: " ^ quote name)
blanchet@43050
  1020
    val (used_facts, used_ths) =
blanchet@43050
  1021
      facts |> map untranslated_fact |> ListPair.unzip
blanchet@43050
  1022
  in
blanchet@43050
  1023
    case play_one_line_proof debug timeout used_ths state subgoal
blanchet@43050
  1024
                             [reconstructor] of
blanchet@43050
  1025
      play as Played (_, time) =>
blanchet@43052
  1026
      {outcome = NONE, used_facts = used_facts,
blanchet@43052
  1027
       run_time_in_msecs = SOME (Time.toMilliseconds time),
blanchet@43052
  1028
       preplay = K play,
blanchet@43052
  1029
       message = fn play =>
blanchet@43052
  1030
                    let
blanchet@43052
  1031
                      val one_line_params =
blanchet@43052
  1032
                         (play, proof_banner mode name, used_facts,
blanchet@43052
  1033
                          minimize_command name, subgoal, subgoal_count)
blanchet@43261
  1034
                    in one_line_proof_text one_line_params end,
blanchet@43261
  1035
       message_tail = ""}
blanchet@43052
  1036
    | play =>
blanchet@43166
  1037
      let
blanchet@43166
  1038
        val failure = case play of Failed_to_Play _ => GaveUp | _ => TimedOut
blanchet@43166
  1039
      in
blanchet@43052
  1040
        {outcome = SOME failure, used_facts = [], run_time_in_msecs = NONE,
blanchet@43261
  1041
         preplay = K play, message = fn _ => string_for_failure failure,
blanchet@43261
  1042
         message_tail = ""}
blanchet@43050
  1043
      end
blanchet@43050
  1044
  end
blanchet@43050
  1045
blanchet@43021
  1046
fun get_prover ctxt mode name =
wenzelm@42361
  1047
  let val thy = Proof_Context.theory_of ctxt in
blanchet@43052
  1048
    if is_metis_prover name then run_metis mode name
blanchet@43052
  1049
    else if is_atp thy name then run_atp mode name (get_atp thy name)
blanchet@43052
  1050
    else if is_smt_prover ctxt name then run_smt_solver mode name
blanchet@43052
  1051
    else error ("No such prover: " ^ name ^ ".")
blanchet@40941
  1052
  end
blanchet@40063
  1053
wenzelm@28582
  1054
end;