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