src/HOL/Tools/Sledgehammer/sledgehammer_fact.ML
author wenzelm
Mon Mar 10 18:06:23 2014 +0100 (2014-03-10 ago)
changeset 56032 b034b9f0fa2a
parent 56027 25889f5c39a8
child 56140 ed92ce2ac88e
permissions -rw-r--r--
clarified Args.check_src: retain name space information for error output;
tuned signature;
blanchet@48250
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_fact.ML
blanchet@48250
     2
    Author:     Jia Meng, Cambridge University Computer Laboratory and NICTA
blanchet@48250
     3
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@48250
     4
blanchet@48250
     5
Sledgehammer fact handling.
blanchet@48250
     6
*)
blanchet@48250
     7
blanchet@48250
     8
signature SLEDGEHAMMER_FACT =
blanchet@48250
     9
sig
blanchet@48250
    10
  type status = ATP_Problem_Generate.status
blanchet@48250
    11
  type stature = ATP_Problem_Generate.stature
blanchet@48250
    12
blanchet@51004
    13
  type raw_fact = ((unit -> string) * stature) * thm
blanchet@51004
    14
  type fact = (string * stature) * thm
blanchet@48296
    15
blanchet@48292
    16
  type fact_override =
blanchet@48250
    17
    {add : (Facts.ref * Attrib.src list) list,
blanchet@48250
    18
     del : (Facts.ref * Attrib.src list) list,
blanchet@48250
    19
     only : bool}
blanchet@48250
    20
blanchet@48250
    21
  val instantiate_inducts : bool Config.T
blanchet@48292
    22
  val no_fact_override : fact_override
blanchet@55212
    23
blanchet@55212
    24
  val fact_of_ref : Proof.context -> unit Symtab.table -> thm list -> status Termtab.table ->
blanchet@55212
    25
    Facts.ref * Attrib.src list -> ((string * stature) * thm) list
blanchet@50047
    26
  val backquote_thm : Proof.context -> thm -> string
blanchet@50511
    27
  val is_blacklisted_or_something : Proof.context -> bool -> string -> bool
blanchet@48250
    28
  val clasimpset_rule_table_of : Proof.context -> status Termtab.table
blanchet@55212
    29
  val build_name_tables : (thm -> string) -> ('a * thm) list ->
blanchet@55212
    30
    string Symtab.table * string Symtab.table
blanchet@55212
    31
  val maybe_instantiate_inducts : Proof.context -> term list -> term ->
blanchet@55212
    32
    (((unit -> string) * 'a) * thm) list -> (((unit -> string) * 'a) * thm) list
blanchet@51004
    33
  val fact_of_raw_fact : raw_fact -> fact
blanchet@55212
    34
blanchet@55212
    35
  val all_facts : Proof.context -> bool -> bool -> unit Symtab.table -> thm list -> thm list ->
blanchet@55212
    36
    status Termtab.table -> raw_fact list
blanchet@55212
    37
  val nearly_all_facts : Proof.context -> bool -> fact_override -> unit Symtab.table ->
blanchet@55212
    38
    status Termtab.table -> thm list -> term list -> term -> raw_fact list
blanchet@54142
    39
  val drop_duplicate_facts : raw_fact list -> raw_fact list
blanchet@48250
    40
end;
blanchet@48250
    41
blanchet@48250
    42
structure Sledgehammer_Fact : SLEDGEHAMMER_FACT =
blanchet@48250
    43
struct
blanchet@48250
    44
blanchet@50495
    45
open ATP_Util
blanchet@48250
    46
open ATP_Problem_Generate
blanchet@48250
    47
open Sledgehammer_Util
blanchet@48250
    48
blanchet@51004
    49
type raw_fact = ((unit -> string) * stature) * thm
blanchet@51004
    50
type fact = (string * stature) * thm
blanchet@48296
    51
blanchet@48292
    52
type fact_override =
blanchet@48250
    53
  {add : (Facts.ref * Attrib.src list) list,
blanchet@48250
    54
   del : (Facts.ref * Attrib.src list) list,
blanchet@48250
    55
   only : bool}
blanchet@48250
    56
blanchet@54080
    57
(* gracefully handle huge background theories *)
blanchet@54080
    58
val max_facts_for_duplicates = 50000
blanchet@54080
    59
val max_facts_for_complex_check = 25000
blanchet@54083
    60
val max_simps_for_clasimpset = 10000
blanchet@54080
    61
blanchet@53511
    62
(* experimental feature *)
blanchet@48250
    63
val instantiate_inducts =
blanchet@48250
    64
  Attrib.setup_config_bool @{binding sledgehammer_instantiate_inducts} (K false)
blanchet@48250
    65
blanchet@48292
    66
val no_fact_override = {add = [], del = [], only = false}
blanchet@48250
    67
blanchet@48250
    68
fun needs_quoting reserved s =
blanchet@48250
    69
  Symtab.defined reserved s orelse
wenzelm@50239
    70
  exists (not o Symbol_Pos.is_identifier) (Long_Name.explode s)
blanchet@48250
    71
blanchet@48250
    72
fun make_name reserved multi j name =
blanchet@48250
    73
  (name |> needs_quoting reserved name ? quote) ^
blanchet@48250
    74
  (if multi then "(" ^ string_of_int j ^ ")" else "")
blanchet@48250
    75
blanchet@48250
    76
fun explode_interval _ (Facts.FromTo (i, j)) = i upto j
blanchet@48250
    77
  | explode_interval max (Facts.From i) = i upto i + max - 1
blanchet@48250
    78
  | explode_interval _ (Facts.Single i) = [i]
blanchet@48250
    79
blanchet@48250
    80
val backquote =
blanchet@48250
    81
  raw_explode #> map (fn "`" => "\\`" | s => s) #> implode #> enclose "`" "`"
blanchet@48250
    82
blanchet@48250
    83
(* unfolding these can yield really huge terms *)
blanchet@48250
    84
val risky_defs = @{thms Bit0_def Bit1_def}
blanchet@48250
    85
blanchet@48250
    86
fun is_rec_eq lhs = Term.exists_subterm (curry (op =) (head_of lhs))
blanchet@48250
    87
fun is_rec_def (@{const Trueprop} $ t) = is_rec_def t
blanchet@48250
    88
  | is_rec_def (@{const ==>} $ _ $ t2) = is_rec_def t2
blanchet@48250
    89
  | is_rec_def (Const (@{const_name "=="}, _) $ t1 $ t2) = is_rec_eq t1 t2
blanchet@48250
    90
  | is_rec_def (Const (@{const_name HOL.eq}, _) $ t1 $ t2) = is_rec_eq t1 t2
blanchet@48250
    91
  | is_rec_def _ = false
blanchet@48250
    92
blanchet@48250
    93
fun is_assum assms th = exists (fn ct => prop_of th aconv term_of ct) assms
blanchet@48396
    94
fun is_chained chained = member Thm.eq_thm_prop chained
blanchet@48250
    95
blanchet@48396
    96
fun scope_of_thm global assms chained th =
blanchet@48396
    97
  if is_chained chained th then Chained
blanchet@48250
    98
  else if global then Global
blanchet@48250
    99
  else if is_assum assms th then Assum
blanchet@48250
   100
  else Local
blanchet@48250
   101
blanchet@48250
   102
val may_be_induction =
blanchet@48250
   103
  exists_subterm (fn Var (_, Type (@{type_name fun}, [_, T])) =>
blanchet@48250
   104
                     body_type T = @{typ bool}
blanchet@48250
   105
                   | _ => false)
blanchet@48250
   106
blanchet@54077
   107
(* TODO: get rid of *)
blanchet@53501
   108
fun normalize_vars t =
blanchet@53501
   109
  let
blanchet@53501
   110
    fun normT (Type (s, Ts)) = fold_map normT Ts #>> curry Type s
blanchet@53501
   111
      | normT (TVar (z as (_, S))) =
blanchet@53501
   112
        (fn ((knownT, nT), accum) =>
blanchet@55286
   113
            (case find_index (equal z) knownT of
blanchet@53501
   114
              ~1 => (TVar ((Name.uu, nT), S), ((z :: knownT, nT + 1), accum))
blanchet@55286
   115
            | j => (TVar ((Name.uu, nT - j - 1), S), ((knownT, nT), accum))))
blanchet@53501
   116
      | normT (T as TFree _) = pair T
blanchet@53501
   117
    fun norm (t $ u) = norm t ##>> norm u #>> op $
blanchet@53501
   118
      | norm (Const (s, T)) = normT T #>> curry Const s
blanchet@53501
   119
      | norm (Var (z as (_, T))) =
blanchet@53501
   120
        normT T
blanchet@53501
   121
        #> (fn (T, (accumT, (known, n))) =>
blanchet@55286
   122
               (case find_index (equal z) known of
blanchet@53501
   123
                 ~1 => (Var ((Name.uu, n), T), (accumT, (z :: known, n + 1)))
blanchet@55286
   124
               | j => (Var ((Name.uu, n - j - 1), T), (accumT, (known, n)))))
blanchet@53501
   125
      | norm (Abs (_, T, t)) =
blanchet@53501
   126
        norm t ##>> normT T #>> (fn (t, T) => Abs (Name.uu, T, t))
blanchet@53501
   127
      | norm (Bound j) = pair (Bound j)
blanchet@53501
   128
      | norm (Free (s, T)) = normT T #>> curry Free s
blanchet@53501
   129
  in fst (norm t (([], 0), ([], 0))) end
blanchet@53501
   130
blanchet@48396
   131
fun status_of_thm css name th =
blanchet@54081
   132
  if Termtab.is_empty css then
blanchet@54081
   133
    General
blanchet@54081
   134
  else
blanchet@54081
   135
    let val t = prop_of th in
blanchet@54081
   136
      (* FIXME: use structured name *)
blanchet@54081
   137
      if String.isSubstring ".induct" name andalso may_be_induction t then
blanchet@54081
   138
        Induction
blanchet@54081
   139
      else
blanchet@54081
   140
        let val t = normalize_vars t in
blanchet@55286
   141
          (case Termtab.lookup css t of
blanchet@54081
   142
            SOME status => status
blanchet@54081
   143
          | NONE =>
blanchet@54081
   144
            let val concl = Logic.strip_imp_concl t in
blanchet@55286
   145
              (case try (HOLogic.dest_eq o HOLogic.dest_Trueprop) concl of
blanchet@54081
   146
                SOME lrhss =>
blanchet@54081
   147
                let
blanchet@54081
   148
                  val prems = Logic.strip_imp_prems t
blanchet@54081
   149
                  val t' = Logic.list_implies (prems, Logic.mk_equals lrhss)
blanchet@54081
   150
                in
blanchet@54081
   151
                  Termtab.lookup css t' |> the_default General
blanchet@54081
   152
                end
blanchet@55286
   153
              | NONE => General)
blanchet@55286
   154
            end)
blanchet@54081
   155
        end
blanchet@54081
   156
    end
blanchet@48250
   157
blanchet@48396
   158
fun stature_of_thm global assms chained css name th =
blanchet@48396
   159
  (scope_of_thm global assms chained th, status_of_thm css name th)
blanchet@48250
   160
blanchet@52031
   161
fun fact_of_ref ctxt reserved chained css (xthm as (xref, args)) =
blanchet@48250
   162
  let
blanchet@48250
   163
    val ths = Attrib.eval_thms ctxt [xthm]
blanchet@48250
   164
    val bracket =
wenzelm@56032
   165
      map (enclose "[" "]" o Pretty.str_of o Args.pretty_src ctxt) args
blanchet@48250
   166
      |> implode
blanchet@48250
   167
    fun nth_name j =
blanchet@55286
   168
      (case xref of
blanchet@48250
   169
        Facts.Fact s => backquote s ^ bracket
blanchet@48250
   170
      | Facts.Named (("", _), _) => "[" ^ bracket ^ "]"
blanchet@48250
   171
      | Facts.Named ((name, _), NONE) =>
blanchet@48250
   172
        make_name reserved (length ths > 1) (j + 1) name ^ bracket
blanchet@48250
   173
      | Facts.Named ((name, _), SOME intervals) =>
blanchet@48250
   174
        make_name reserved true
blanchet@55286
   175
          (nth (maps (explode_interval (length ths)) intervals) j) name ^ bracket)
blanchet@48396
   176
    fun add_nth th (j, rest) =
blanchet@48396
   177
      let val name = nth_name j in
blanchet@48396
   178
        (j + 1, ((name, stature_of_thm false [] chained css name th), th)
blanchet@48396
   179
                :: rest)
blanchet@48396
   180
      end
blanchet@48396
   181
  in (0, []) |> fold add_nth ths |> snd end
blanchet@48250
   182
blanchet@48250
   183
(* Reject theorems with names like "List.filter.filter_list_def" or
blanchet@48250
   184
  "Accessible_Part.acc.defs", as these are definitions arising from packages. *)
blanchet@50736
   185
fun is_package_def s =
blanchet@50736
   186
  let val ss = Long_Name.explode s in
blanchet@50736
   187
    length ss > 2 andalso not (hd ss = "local") andalso
blanchet@50736
   188
    exists (fn suf => String.isSuffix suf s)
blanchet@50736
   189
           ["_case_def", "_rec_def", "_size_def", "_size_overloaded_def"]
blanchet@48250
   190
  end
blanchet@48250
   191
blanchet@48250
   192
(* FIXME: put other record thms here, or declare as "no_atp" *)
blanchet@48250
   193
fun multi_base_blacklist ctxt ho_atp =
blanchet@48250
   194
  ["defs", "select_defs", "update_defs", "split", "splits", "split_asm",
blanchet@50442
   195
   "ext_cases", "eq.simps", "eq.refl", "nchotomy", "case_cong",
haftmann@51160
   196
   "weak_case_cong", "nat_of_char_simps", "nibble.simps",
blanchet@48440
   197
   "nibble.distinct"]
blanchet@53531
   198
  |> not (ho_atp orelse Config.get ctxt instantiate_inducts) ?
blanchet@48250
   199
        append ["induct", "inducts"]
blanchet@48440
   200
  |> map (prefix Long_Name.separator)
blanchet@48250
   201
blanchet@53529
   202
(* The maximum apply depth of any "metis" call in "Metis_Examples" (on
blanchet@53529
   203
   2007-10-31) was 11. *)
blanchet@53529
   204
val max_apply_depth = 18
blanchet@53529
   205
blanchet@53529
   206
fun apply_depth (f $ t) = Int.max (apply_depth f, apply_depth t + 1)
blanchet@53529
   207
  | apply_depth (Abs (_, _, t)) = apply_depth t
blanchet@53529
   208
  | apply_depth _ = 0
blanchet@53529
   209
blanchet@53533
   210
fun is_too_complex t = apply_depth t > max_apply_depth
blanchet@53529
   211
blanchet@48667
   212
(* FIXME: Ad hoc list *)
blanchet@48667
   213
val technical_prefixes =
haftmann@51126
   214
  ["ATP", "Code_Evaluation", "Datatype", "Enum", "Lazy_Sequence",
haftmann@51126
   215
   "Limited_Sequence", "Meson", "Metis", "Nitpick",
haftmann@51126
   216
   "Quickcheck_Random", "Quickcheck_Exhaustive", "Quickcheck_Narrowing",
blanchet@50736
   217
   "Random_Sequence", "Sledgehammer", "SMT"]
blanchet@48667
   218
  |> map (suffix Long_Name.separator)
blanchet@48440
   219
blanchet@53507
   220
fun is_technical_const (s, _) =
blanchet@48667
   221
  exists (fn pref => String.isPrefix pref s) technical_prefixes
blanchet@48250
   222
blanchet@48250
   223
(* FIXME: make more reliable *)
blanchet@53507
   224
val sep_class_sep = Long_Name.separator ^ "class" ^ Long_Name.separator
blanchet@53507
   225
fun is_low_level_class_const (s, _) =
blanchet@53507
   226
  s = @{const_name equal_class.equal} orelse String.isSubstring sep_class_sep s
blanchet@48250
   227
blanchet@53509
   228
val sep_that = Long_Name.separator ^ Obtain.thatN
blanchet@53509
   229
blanchet@54081
   230
val skolem_thesis = Name.skolem Auto_Bind.thesisN
blanchet@54081
   231
blanchet@48250
   232
fun is_that_fact th =
blanchet@54081
   233
  exists_subterm (fn Free (s, _) => s = skolem_thesis | _ => false) (prop_of th)
blanchet@54081
   234
  andalso String.isSuffix sep_that (Thm.get_name_hint th)
blanchet@48250
   235
blanchet@53513
   236
datatype interest = Deal_Breaker | Interesting | Boring
blanchet@53513
   237
blanchet@53513
   238
fun combine_interests Deal_Breaker _ = Deal_Breaker
blanchet@53513
   239
  | combine_interests _ Deal_Breaker = Deal_Breaker
blanchet@53513
   240
  | combine_interests Interesting _ = Interesting
blanchet@53513
   241
  | combine_interests _ Interesting = Interesting
blanchet@53513
   242
  | combine_interests Boring Boring = Boring
blanchet@53513
   243
blanchet@54914
   244
val type_has_top_sort =
blanchet@54914
   245
  exists_subtype (fn TFree (_, []) => true | TVar (_, []) => true | _ => false)
blanchet@54914
   246
blanchet@50523
   247
fun is_likely_tautology_too_meta_or_too_technical th =
blanchet@48406
   248
  let
blanchet@50053
   249
    fun is_interesting_subterm (Const (s, _)) =
blanchet@50053
   250
        not (member (op =) atp_widely_irrelevant_consts s)
blanchet@50053
   251
      | is_interesting_subterm (Free _) = true
blanchet@50053
   252
      | is_interesting_subterm _ = false
blanchet@53513
   253
    fun interest_of_bool t =
blanchet@53545
   254
      if exists_Const (is_technical_const orf is_low_level_class_const orf
blanchet@53545
   255
                       type_has_top_sort o snd) t then
blanchet@53513
   256
        Deal_Breaker
blanchet@53513
   257
      else if exists_type (exists_subtype (curry (op =) @{typ prop})) t orelse
blanchet@53513
   258
              not (exists_subterm is_interesting_subterm t) then
blanchet@53513
   259
        Boring
blanchet@53513
   260
      else
blanchet@53513
   261
        Interesting
blanchet@53513
   262
    fun interest_of_prop _ (@{const Trueprop} $ t) = interest_of_bool t
blanchet@53513
   263
      | interest_of_prop Ts (@{const "==>"} $ t $ u) =
blanchet@53513
   264
        combine_interests (interest_of_prop Ts t) (interest_of_prop Ts u)
blanchet@53513
   265
      | interest_of_prop Ts (Const (@{const_name all}, _) $ Abs (_, T, t)) =
blanchet@54040
   266
        if type_has_top_sort T then Deal_Breaker else interest_of_prop (T :: Ts) t
blanchet@53513
   267
      | interest_of_prop Ts ((t as Const (@{const_name all}, _)) $ u) =
blanchet@53513
   268
        interest_of_prop Ts (t $ eta_expand Ts u 1)
blanchet@53513
   269
      | interest_of_prop _ (Const (@{const_name "=="}, _) $ t $ u) =
blanchet@53513
   270
        combine_interests (interest_of_bool t) (interest_of_bool u)
blanchet@53513
   271
      | interest_of_prop _ _ = Deal_Breaker
blanchet@50523
   272
    val t = prop_of th
blanchet@48406
   273
  in
blanchet@53513
   274
    (interest_of_prop [] t <> Interesting andalso
blanchet@53513
   275
     not (Thm.eq_thm_prop (@{thm ext}, th))) orelse
blanchet@53507
   276
    is_that_fact th
blanchet@48438
   277
  end
blanchet@48438
   278
blanchet@53512
   279
fun is_blacklisted_or_something ctxt ho_atp =
blanchet@53512
   280
  let
blanchet@53512
   281
    val blist = multi_base_blacklist ctxt ho_atp
blanchet@53512
   282
    fun is_blisted name =
blanchet@53512
   283
      is_package_def name orelse exists (fn s => String.isSuffix s name) blist
blanchet@53512
   284
  in is_blisted end
blanchet@50510
   285
blanchet@48250
   286
(* This is a terrible hack. Free variables are sometimes coded as "M__" when
blanchet@48250
   287
   they are displayed as "M" and we want to avoid clashes with these. But
blanchet@48250
   288
   sometimes it's even worse: "Ma__" encodes "M". So we simply reserve all
blanchet@48250
   289
   prefixes of all free variables. In the worse case scenario, where the fact
blanchet@49981
   290
   won't be resolved correctly, the user can fix it manually, e.g., by giving a
blanchet@49981
   291
   name to the offending fact. *)
blanchet@48250
   292
fun all_prefixes_of s =
blanchet@48250
   293
  map (fn i => String.extract (s, 0, SOME i)) (1 upto size s - 1)
blanchet@48250
   294
blanchet@48250
   295
fun close_form t =
blanchet@48250
   296
  (t, [] |> Term.add_free_names t |> maps all_prefixes_of)
blanchet@48250
   297
  |> fold (fn ((s, i), T) => fn (t', taken) =>
blanchet@48250
   298
              let val s' = singleton (Name.variant_list taken) s in
blanchet@48250
   299
                ((if fastype_of t' = HOLogic.boolT then HOLogic.all_const
blanchet@48250
   300
                  else Logic.all_const) T
blanchet@48250
   301
                 $ Abs (s', T, abstract_over (Var ((s, i), T), t')),
blanchet@48250
   302
                 s' :: taken)
blanchet@48250
   303
              end)
blanchet@48250
   304
          (Term.add_vars t [] |> sort_wrt (fst o fst))
blanchet@48250
   305
  |> fst
blanchet@48250
   306
blanchet@51998
   307
fun backquote_term ctxt = close_form #> hackish_string_of_term ctxt #> backquote
blanchet@51998
   308
fun backquote_thm ctxt = backquote_term ctxt o prop_of
blanchet@48394
   309
blanchet@54084
   310
(* TODO: rewrite to use nets and/or to reuse existing data structures *)
blanchet@48250
   311
fun clasimpset_rule_table_of ctxt =
blanchet@53502
   312
  let val simps = ctxt |> simpset_of |> dest_ss |> #simps in
blanchet@53502
   313
    if length simps >= max_simps_for_clasimpset then
blanchet@53502
   314
      Termtab.empty
blanchet@53502
   315
    else
blanchet@53502
   316
      let
blanchet@53502
   317
        fun add stature th =
blanchet@53502
   318
          Termtab.update (normalize_vars (prop_of th), stature)
blanchet@53502
   319
        val {safeIs, (* safeEs, *) hazIs, (* hazEs, *) ...} =
blanchet@53502
   320
          ctxt |> claset_of |> Classical.rep_cs
blanchet@53502
   321
        val intros = Item_Net.content safeIs @ Item_Net.content hazIs
blanchet@48250
   322
(* Add once it is used:
blanchet@53502
   323
        val elims =
blanchet@53502
   324
          Item_Net.content safeEs @ Item_Net.content hazEs
blanchet@53502
   325
          |> map Classical.classical_rule
blanchet@48250
   326
*)
blanchet@53502
   327
        val specs = ctxt |> Spec_Rules.get
blanchet@53502
   328
        val (rec_defs, nonrec_defs) =
blanchet@53502
   329
          specs |> filter (curry (op =) Spec_Rules.Equational o fst)
blanchet@53502
   330
                |> maps (snd o snd)
blanchet@53502
   331
                |> filter_out (member Thm.eq_thm_prop risky_defs)
blanchet@53502
   332
                |> List.partition (is_rec_def o prop_of)
blanchet@53502
   333
        val spec_intros =
blanchet@53502
   334
          specs |> filter (member (op =) [Spec_Rules.Inductive,
blanchet@53502
   335
                                          Spec_Rules.Co_Inductive] o fst)
blanchet@53502
   336
                |> maps (snd o snd)
blanchet@53502
   337
      in
blanchet@53502
   338
        Termtab.empty |> fold (add Simp o snd) simps
blanchet@53502
   339
                      |> fold (add Rec_Def) rec_defs
blanchet@53502
   340
                      |> fold (add Non_Rec_Def) nonrec_defs
blanchet@48250
   341
(* Add once it is used:
blanchet@53502
   342
                      |> fold (add Elim) elims
blanchet@48250
   343
*)
blanchet@53502
   344
                      |> fold (add Intro) intros
blanchet@53502
   345
                      |> fold (add Inductive) spec_intros
blanchet@53502
   346
      end
blanchet@48250
   347
  end
blanchet@48250
   348
blanchet@54092
   349
fun normalize_eq (@{const Trueprop} $ (t as (t0 as Const (@{const_name HOL.eq}, _)) $ t1 $ t2)) =
blanchet@54092
   350
    if Term_Ord.fast_term_ord (t1, t2) <> GREATER then t else t0 $ t2 $ t1
blanchet@54092
   351
  | normalize_eq (@{const Trueprop} $ (t as @{const Not}
blanchet@50481
   352
        $ ((t0 as Const (@{const_name HOL.eq}, _)) $ t1 $ t2))) =
blanchet@54092
   353
    if Term_Ord.fast_term_ord (t1, t2) <> GREATER then t else HOLogic.mk_not (t0 $ t2 $ t1)
blanchet@54092
   354
  | normalize_eq (Const (@{const_name "=="}, Type (_, [T, _])) $ t1 $ t2) =
blanchet@54092
   355
    (if Term_Ord.fast_term_ord (t1, t2) <> GREATER then (t1, t2) else (t2, t1))
blanchet@54092
   356
    |> (fn (t1, t2) => HOLogic.eq_const T $ t1 $ t2)
blanchet@50481
   357
  | normalize_eq t = t
blanchet@50481
   358
blanchet@50485
   359
fun if_thm_before th th' =
blanchet@50485
   360
  if Theory.subthy (pairself Thm.theory_of_thm (th, th')) then th else th'
blanchet@50485
   361
blanchet@50734
   362
(* Hack: Conflate the facts about a class as seen from the outside with the
blanchet@50734
   363
   corresponding low-level facts, so that MaSh can learn from the low-level
blanchet@50734
   364
   proofs. *)
blanchet@50734
   365
fun un_class_ify s =
blanchet@55286
   366
  (case first_field "_class" s of
blanchet@50734
   367
    SOME (pref, suf) => [s, pref ^ suf]
blanchet@55286
   368
  | NONE => [s])
blanchet@50734
   369
blanchet@50735
   370
fun build_name_tables name_of facts =
blanchet@50733
   371
  let
blanchet@54092
   372
    fun cons_thm (_, th) = Termtab.cons_list (normalize_vars (normalize_eq (prop_of th)), th)
blanchet@50735
   373
    fun add_plain canon alias =
blanchet@54092
   374
      Symtab.update (Thm.get_name_hint alias, name_of (if_thm_before canon alias))
blanchet@50735
   375
    fun add_plains (_, aliases as canon :: _) = fold (add_plain canon) aliases
blanchet@54092
   376
    fun add_inclass (name, target) = fold (fn s => Symtab.update (s, target)) (un_class_ify name)
blanchet@50815
   377
    val prop_tab = fold cons_thm facts Termtab.empty
blanchet@50735
   378
    val plain_name_tab = Termtab.fold add_plains prop_tab Symtab.empty
blanchet@50735
   379
    val inclass_name_tab = Symtab.fold add_inclass plain_name_tab Symtab.empty
blanchet@50735
   380
  in (plain_name_tab, inclass_name_tab) end
blanchet@50485
   381
blanchet@54080
   382
fun fact_distinct eq facts =
blanchet@54076
   383
  fold (fn fact as (_, th) =>
blanchet@54080
   384
      Net.insert_term_safe (eq o pairself (normalize_eq o prop_of o snd))
blanchet@54077
   385
        (normalize_eq (prop_of th), fact))
blanchet@54077
   386
    facts Net.empty
blanchet@54076
   387
  |> Net.entries
blanchet@53504
   388
blanchet@48250
   389
fun struct_induct_rule_on th =
blanchet@55286
   390
  (case Logic.strip_horn (prop_of th) of
blanchet@48250
   391
    (prems, @{const Trueprop}
blanchet@48250
   392
            $ ((p as Var ((p_name, 0), _)) $ (a as Var (_, ind_T)))) =>
blanchet@48250
   393
    if not (is_TVar ind_T) andalso length prems > 1 andalso
blanchet@48250
   394
       exists (exists_subterm (curry (op aconv) p)) prems andalso
blanchet@48250
   395
       not (exists (exists_subterm (curry (op aconv) a)) prems) then
blanchet@48250
   396
      SOME (p_name, ind_T)
blanchet@48250
   397
    else
blanchet@48250
   398
      NONE
blanchet@55286
   399
  | _ => NONE)
blanchet@48250
   400
blanchet@50586
   401
val instantiate_induct_timeout = seconds 0.01
blanchet@50586
   402
blanchet@48250
   403
fun instantiate_induct_rule ctxt concl_prop p_name ((name, stature), th) ind_x =
blanchet@48250
   404
  let
blanchet@48250
   405
    fun varify_noninducts (t as Free (s, T)) =
blanchet@48250
   406
        if (s, T) = ind_x orelse can dest_funT T then t else Var ((s, 0), T)
blanchet@48250
   407
      | varify_noninducts t = t
blanchet@48250
   408
    val p_inst =
blanchet@48250
   409
      concl_prop |> map_aterms varify_noninducts |> close_form
blanchet@48250
   410
                 |> lambda (Free ind_x)
blanchet@51998
   411
                 |> hackish_string_of_term ctxt
blanchet@48250
   412
  in
blanchet@48250
   413
    ((fn () => name () ^ "[where " ^ p_name ^ " = " ^ quote p_inst ^ "]",
wenzelm@55151
   414
      stature), th |> Rule_Insts.read_instantiate ctxt [((p_name, 0), p_inst)] [])
blanchet@48250
   415
  end
blanchet@48250
   416
blanchet@48250
   417
fun type_match thy (T1, T2) =
blanchet@48250
   418
  (Sign.typ_match thy (T2, T1) Vartab.empty; true)
blanchet@48250
   419
  handle Type.TYPE_MATCH => false
blanchet@48250
   420
blanchet@48250
   421
fun instantiate_if_induct_rule ctxt stmt stmt_xs (ax as (_, th)) =
blanchet@55286
   422
  (case struct_induct_rule_on th of
blanchet@48250
   423
    SOME (p_name, ind_T) =>
blanchet@48250
   424
    let val thy = Proof_Context.theory_of ctxt in
blanchet@55286
   425
      stmt_xs
blanchet@55286
   426
      |> filter (fn (_, T) => type_match thy (T, ind_T))
blanchet@55286
   427
      |> map_filter (try (TimeLimit.timeLimit instantiate_induct_timeout
blanchet@55286
   428
           (instantiate_induct_rule ctxt stmt p_name ax)))
blanchet@48250
   429
    end
blanchet@55286
   430
  | NONE => [ax])
blanchet@48250
   431
blanchet@48250
   432
fun external_frees t =
wenzelm@55948
   433
  [] |> Term.add_frees t |> filter_out (Name.is_internal o fst)
blanchet@48250
   434
blanchet@48250
   435
fun maybe_instantiate_inducts ctxt hyp_ts concl_t =
blanchet@48250
   436
  if Config.get ctxt instantiate_inducts then
blanchet@48250
   437
    let
blanchet@48250
   438
      val thy = Proof_Context.theory_of ctxt
blanchet@48250
   439
      val ind_stmt =
blanchet@48250
   440
        (hyp_ts |> filter_out (null o external_frees), concl_t)
blanchet@48250
   441
        |> Logic.list_implies |> Object_Logic.atomize_term thy
blanchet@48250
   442
      val ind_stmt_xs = external_frees ind_stmt
blanchet@48250
   443
    in maps (instantiate_if_induct_rule ctxt ind_stmt ind_stmt_xs) end
blanchet@48250
   444
  else
blanchet@48250
   445
    I
blanchet@48250
   446
blanchet@51004
   447
fun fact_of_raw_fact ((name, stature), th) = ((name (), stature), th)
blanchet@51004
   448
blanchet@53532
   449
fun fact_count facts = Facts.fold_static (K (Integer.add 1)) facts 0
blanchet@53532
   450
blanchet@50523
   451
fun all_facts ctxt generous ho_atp reserved add_ths chained css =
blanchet@48251
   452
  let
blanchet@48251
   453
    val thy = Proof_Context.theory_of ctxt
blanchet@48251
   454
    val global_facts = Global_Theory.facts_of thy
blanchet@53532
   455
    val is_too_complex =
blanchet@53532
   456
      if generous orelse
blanchet@53532
   457
         fact_count global_facts >= max_facts_for_complex_check then
blanchet@53532
   458
        K false
blanchet@53532
   459
      else
blanchet@53533
   460
        is_too_complex
blanchet@48251
   461
    val local_facts = Proof_Context.facts_of ctxt
blanchet@48251
   462
    val named_locals = local_facts |> Facts.dest_static []
blanchet@48251
   463
    val assms = Assumption.all_assms_of ctxt
blanchet@48251
   464
    fun is_good_unnamed_local th =
blanchet@48251
   465
      not (Thm.has_name_hint th) andalso
blanchet@48251
   466
      forall (fn (_, ths) => not (member Thm.eq_thm_prop ths th)) named_locals
blanchet@48251
   467
    val unnamed_locals =
blanchet@48396
   468
      union Thm.eq_thm_prop (Facts.props local_facts) chained
blanchet@48251
   469
      |> filter is_good_unnamed_local |> map (pair "" o single)
blanchet@48251
   470
    val full_space =
blanchet@48251
   471
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts)
blanchet@53512
   472
    val is_blacklisted_or_something = is_blacklisted_or_something ctxt ho_atp
blanchet@48251
   473
    fun add_facts global foldx facts =
blanchet@54081
   474
      foldx (fn (name0, ths) => fn accum =>
blanchet@50512
   475
        if name0 <> "" andalso
blanchet@48251
   476
           forall (not o member Thm.eq_thm_prop add_ths) ths andalso
blanchet@50511
   477
           (Facts.is_concealed facts name0 orelse
blanchet@53512
   478
            (not generous andalso is_blacklisted_or_something name0)) then
blanchet@54081
   479
          accum
blanchet@48251
   480
        else
blanchet@48251
   481
          let
blanchet@50485
   482
            val n = length ths
blanchet@50485
   483
            val multi = n > 1
blanchet@48251
   484
            fun check_thms a =
blanchet@55286
   485
              (case try (Proof_Context.get_thms ctxt) a of
blanchet@48251
   486
                NONE => false
blanchet@55286
   487
              | SOME ths' => eq_list Thm.eq_thm_prop (ths, ths'))
blanchet@48251
   488
          in
blanchet@54081
   489
            snd (fold_rev (fn th => fn (j, accum as (uni_accum, multi_accum)) =>
blanchet@54081
   490
              (j - 1,
blanchet@54081
   491
               if not (member Thm.eq_thm_prop add_ths th) andalso
blanchet@54081
   492
                  (is_likely_tautology_too_meta_or_too_technical th orelse
blanchet@54081
   493
                   is_too_complex (prop_of th)) then
blanchet@54081
   494
                 accum
blanchet@54081
   495
               else
blanchet@54081
   496
                 let
blanchet@54081
   497
                   val new =
blanchet@54081
   498
                     (((fn () =>
blanchet@54081
   499
                           if name0 = "" then
blanchet@54081
   500
                             backquote_thm ctxt th
blanchet@54081
   501
                           else
blanchet@54081
   502
                             [Facts.extern ctxt facts name0,
blanchet@54081
   503
                              Name_Space.extern ctxt full_space name0]
blanchet@54081
   504
                             |> find_first check_thms
blanchet@54081
   505
                             |> the_default name0
blanchet@54081
   506
                             |> make_name reserved multi j),
blanchet@54081
   507
                        stature_of_thm global assms chained css name0 th),
blanchet@54081
   508
                      th)
blanchet@54081
   509
                 in
blanchet@54081
   510
                   if multi then (uni_accum, new :: multi_accum)
blanchet@54081
   511
                   else (new :: uni_accum, multi_accum)
blanchet@54081
   512
                 end)) ths (n, accum))
blanchet@48251
   513
          end)
blanchet@48251
   514
  in
blanchet@50756
   515
    (* The single-theorem names go before the multiple-theorem ones (e.g.,
blanchet@50756
   516
       "xxx" vs. "xxx(3)"), so that single names are preferred when both are
blanchet@50756
   517
       available. *)
blanchet@50756
   518
    `I [] |> add_facts false fold local_facts (unnamed_locals @ named_locals)
blanchet@50756
   519
          |> add_facts true Facts.fold_static global_facts global_facts
blanchet@50756
   520
          |> op @
blanchet@48251
   521
  end
blanchet@48251
   522
blanchet@48396
   523
fun nearly_all_facts ctxt ho_atp {add, del, only} reserved css chained hyp_ts
blanchet@48396
   524
                     concl_t =
blanchet@48250
   525
  if only andalso null add then
blanchet@48250
   526
    []
blanchet@48250
   527
  else
blanchet@48250
   528
    let
blanchet@48396
   529
      val chained =
blanchet@48396
   530
        chained
blanchet@48292
   531
        |> maps (fn th => insert Thm.eq_thm_prop (zero_var_indexes th) [th])
blanchet@48250
   532
    in
blanchet@48250
   533
      (if only then
blanchet@48250
   534
         maps (map (fn ((name, stature), th) => ((K name, stature), th))
blanchet@52031
   535
               o fact_of_ref ctxt reserved chained css) add
blanchet@48250
   536
       else
blanchet@54080
   537
         let
blanchet@54080
   538
           val (add, del) = pairself (Attrib.eval_thms ctxt) (add, del)
blanchet@54080
   539
           val facts =
blanchet@54080
   540
             all_facts ctxt false ho_atp reserved add chained css
blanchet@54143
   541
             |> filter_out ((member Thm.eq_thm_prop del orf
blanchet@54143
   542
               (No_ATPs.member ctxt andf not o member Thm.eq_thm_prop add)) o snd)
blanchet@54080
   543
         in
blanchet@54080
   544
           facts
blanchet@48292
   545
         end)
blanchet@48250
   546
      |> maybe_instantiate_inducts ctxt hyp_ts concl_t
blanchet@48250
   547
    end
blanchet@48250
   548
blanchet@54142
   549
fun drop_duplicate_facts facts =
blanchet@54112
   550
  let val num_facts = length facts in
blanchet@54142
   551
    facts |> num_facts <= max_facts_for_duplicates ? fact_distinct (op aconv)
blanchet@54112
   552
  end
blanchet@54112
   553
blanchet@48250
   554
end;