src/HOL/Tools/Sledgehammer/sledgehammer_filter.ML
author blanchet
Tue Oct 26 14:49:48 2010 +0200 (2010-10-26 ago)
changeset 40191 257d2e06bfb8
parent 40071 658a37c80b53
child 40204 da97d75e20e6
permissions -rw-r--r--
put theorems added using "add:" at the beginning of the list returned by the relevance filter, so that they don't get truncated away
blanchet@38988
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_filter.ML
blanchet@38027
     2
    Author:     Jia Meng, Cambridge University Computer Laboratory and NICTA
blanchet@36393
     3
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@39958
     4
blanchet@39958
     5
Sledgehammer's relevance filter.
wenzelm@33309
     6
*)
paulson@15452
     7
blanchet@38988
     8
signature SLEDGEHAMMER_FILTER =
wenzelm@16802
     9
sig
blanchet@38993
    10
  datatype locality = General | Intro | Elim | Simp | Local | Assum | Chained
blanchet@38752
    11
blanchet@40070
    12
  type relevance_fudge =
blanchet@40070
    13
    {worse_irrel_freq : real,
blanchet@40070
    14
     higher_order_irrel_weight : real,
blanchet@40070
    15
     abs_rel_weight : real,
blanchet@40070
    16
     abs_irrel_weight : real,
blanchet@40070
    17
     skolem_irrel_weight : real,
blanchet@40070
    18
     theory_const_rel_weight : real,
blanchet@40070
    19
     theory_const_irrel_weight : real,
blanchet@40070
    20
     intro_bonus : real,
blanchet@40070
    21
     elim_bonus : real,
blanchet@40070
    22
     simp_bonus : real,
blanchet@40070
    23
     local_bonus : real,
blanchet@40070
    24
     assum_bonus : real,
blanchet@40070
    25
     chained_bonus : real,
blanchet@40070
    26
     max_imperfect : real,
blanchet@40070
    27
     max_imperfect_exp : real,
blanchet@40070
    28
     threshold_divisor : real,
blanchet@40070
    29
     ridiculous_threshold : real}
blanchet@40070
    30
blanchet@35966
    31
  type relevance_override =
blanchet@40070
    32
    {add : (Facts.ref * Attrib.src list) list,
blanchet@40070
    33
     del : (Facts.ref * Attrib.src list) list,
blanchet@40070
    34
     only : bool}
blanchet@35966
    35
blanchet@37616
    36
  val trace : bool Unsynchronized.ref
blanchet@38744
    37
  val name_thm_pairs_from_ref :
blanchet@38996
    38
    Proof.context -> unit Symtab.table -> thm list
blanchet@38996
    39
    -> Facts.ref * Attrib.src list -> ((string * locality) * thm) list
blanchet@37347
    40
  val relevant_facts :
blanchet@40071
    41
    Proof.context -> bool -> real * real -> int -> string list
blanchet@40071
    42
    -> relevance_fudge -> relevance_override -> thm list -> term list -> term
blanchet@40070
    43
    -> ((string * locality) * thm) list
paulson@15347
    44
end;
paulson@15347
    45
blanchet@38988
    46
structure Sledgehammer_Filter : SLEDGEHAMMER_FILTER =
paulson@15347
    47
struct
paulson@15347
    48
blanchet@38652
    49
open Sledgehammer_Util
blanchet@38652
    50
blanchet@37616
    51
val trace = Unsynchronized.ref false
blanchet@37616
    52
fun trace_msg msg = if !trace then tracing (msg ()) else ()
blanchet@35826
    53
blanchet@38997
    54
(* experimental features *)
blanchet@38889
    55
val term_patterns = false
blanchet@38997
    56
val respect_no_atp = true
blanchet@38827
    57
blanchet@38993
    58
datatype locality = General | Intro | Elim | Simp | Local | Assum | Chained
blanchet@38752
    59
blanchet@40070
    60
type relevance_fudge =
blanchet@40070
    61
  {worse_irrel_freq : real,
blanchet@40070
    62
   higher_order_irrel_weight : real,
blanchet@40070
    63
   abs_rel_weight : real,
blanchet@40070
    64
   abs_irrel_weight : real,
blanchet@40070
    65
   skolem_irrel_weight : real,
blanchet@40070
    66
   theory_const_rel_weight : real,
blanchet@40070
    67
   theory_const_irrel_weight : real,
blanchet@40070
    68
   intro_bonus : real,
blanchet@40070
    69
   elim_bonus : real,
blanchet@40070
    70
   simp_bonus : real,
blanchet@40070
    71
   local_bonus : real,
blanchet@40070
    72
   assum_bonus : real,
blanchet@40070
    73
   chained_bonus : real,
blanchet@40070
    74
   max_imperfect : real,
blanchet@40070
    75
   max_imperfect_exp : real,
blanchet@40070
    76
   threshold_divisor : real,
blanchet@40070
    77
   ridiculous_threshold : real}
blanchet@40070
    78
blanchet@35966
    79
type relevance_override =
blanchet@40070
    80
  {add : (Facts.ref * Attrib.src list) list,
blanchet@40070
    81
   del : (Facts.ref * Attrib.src list) list,
blanchet@40070
    82
   only : bool}
paulson@21070
    83
blanchet@37616
    84
val sledgehammer_prefix = "Sledgehammer" ^ Long_Name.separator
blanchet@39896
    85
val abs_name = sledgehammer_prefix ^ "abs"
blanchet@39896
    86
val skolem_prefix = sledgehammer_prefix ^ "sko"
blanchet@38992
    87
val theory_const_suffix = Long_Name.separator ^ " 1"
blanchet@37616
    88
blanchet@38744
    89
fun repair_name reserved multi j name =
blanchet@38744
    90
  (name |> Symtab.defined reserved name ? quote) ^
blanchet@38744
    91
  (if multi then "(" ^ Int.toString j ^ ")" else "")
blanchet@38744
    92
blanchet@38996
    93
fun name_thm_pairs_from_ref ctxt reserved chained_ths (xthm as (xref, args)) =
blanchet@38744
    94
  let
blanchet@38996
    95
    val ths = Attrib.eval_thms ctxt [xthm]
blanchet@38996
    96
    val bracket =
blanchet@38996
    97
      implode (map (fn arg => "[" ^ Pretty.str_of (Args.pretty_src ctxt arg)
blanchet@38996
    98
                               ^ "]") args)
blanchet@38996
    99
    val name =
blanchet@38996
   100
      case xref of
blanchet@39264
   101
        Facts.Fact s => "`" ^ s ^ "`" ^ bracket
blanchet@38996
   102
      | Facts.Named (("", _), _) => "[" ^ bracket ^ "]"
blanchet@39264
   103
      | _ => Facts.string_of_ref xref ^ bracket
blanchet@38744
   104
    val multi = length ths > 1
blanchet@38744
   105
  in
blanchet@38752
   106
    (ths, (1, []))
blanchet@38752
   107
    |-> fold (fn th => fn (j, rest) =>
blanchet@38752
   108
                 (j + 1, ((repair_name reserved multi j name,
blanchet@38752
   109
                          if member Thm.eq_thm chained_ths th then Chained
blanchet@38752
   110
                          else General), th) :: rest))
blanchet@38744
   111
    |> snd
blanchet@38699
   112
  end
blanchet@37616
   113
wenzelm@28477
   114
(***************************************************************)
wenzelm@28477
   115
(* Relevance Filtering                                         *)
wenzelm@28477
   116
(***************************************************************)
mengj@19194
   117
paulson@24287
   118
(*** constants with types ***)
paulson@24287
   119
blanchet@38939
   120
fun order_of_type (Type (@{type_name fun}, [T1, @{typ bool}])) =
blanchet@38939
   121
    order_of_type T1 (* cheat: pretend sets are first-order *)
blanchet@38939
   122
  | order_of_type (Type (@{type_name fun}, [T1, T2])) =
blanchet@38939
   123
    Int.max (order_of_type T1 + 1, order_of_type T2)
blanchet@38939
   124
  | order_of_type (Type (_, Ts)) = fold (Integer.max o order_of_type) Ts 0
blanchet@38939
   125
  | order_of_type _ = 0
blanchet@38939
   126
blanchet@38823
   127
(* An abstraction of Isabelle types and first-order terms *)
blanchet@38823
   128
datatype pattern = PVar | PApp of string * pattern list
blanchet@38939
   129
datatype ptype = PType of int * pattern list
blanchet@38744
   130
blanchet@38823
   131
fun string_for_pattern PVar = "_"
blanchet@38823
   132
  | string_for_pattern (PApp (s, ps)) =
blanchet@38823
   133
    if null ps then s else s ^ string_for_patterns ps
blanchet@38823
   134
and string_for_patterns ps = "(" ^ commas (map string_for_pattern ps) ^ ")"
blanchet@38939
   135
fun string_for_ptype (PType (_, ps)) = string_for_patterns ps
paulson@24287
   136
paulson@24287
   137
(*Is the second type an instance of the first one?*)
blanchet@38824
   138
fun match_pattern (PVar, _) = true
blanchet@38824
   139
  | match_pattern (PApp _, PVar) = false
blanchet@38824
   140
  | match_pattern (PApp (s, ps), PApp (t, qs)) =
blanchet@38824
   141
    s = t andalso match_patterns (ps, qs)
blanchet@38824
   142
and match_patterns (_, []) = true
blanchet@38824
   143
  | match_patterns ([], _) = false
blanchet@38824
   144
  | match_patterns (p :: ps, q :: qs) =
blanchet@38824
   145
    match_pattern (p, q) andalso match_patterns (ps, qs)
blanchet@38939
   146
fun match_ptype (PType (_, ps), PType (_, qs)) = match_patterns (ps, qs)
paulson@24287
   147
blanchet@38823
   148
(* Is there a unifiable constant? *)
blanchet@38827
   149
fun pconst_mem f consts (s, ps) =
blanchet@38939
   150
  exists (curry (match_ptype o f) ps)
blanchet@38827
   151
         (map snd (filter (curry (op =) s o fst) consts))
blanchet@38827
   152
fun pconst_hyper_mem f const_tab (s, ps) =
blanchet@38939
   153
  exists (curry (match_ptype o f) ps) (these (Symtab.lookup const_tab s))
blanchet@37505
   154
blanchet@38939
   155
fun pattern_for_type (Type (s, Ts)) = PApp (s, map pattern_for_type Ts)
blanchet@38939
   156
  | pattern_for_type (TFree (s, _)) = PApp (s, [])
blanchet@38939
   157
  | pattern_for_type (TVar _) = PVar
blanchet@38827
   158
blanchet@38827
   159
fun pterm thy t =
blanchet@38827
   160
  case strip_comb t of
blanchet@38827
   161
    (Const x, ts) => PApp (pconst thy true x ts)
blanchet@38827
   162
  | (Free x, ts) => PApp (pconst thy false x ts)
blanchet@39367
   163
  | (Var _, []) => PVar
blanchet@38827
   164
  | _ => PApp ("?", [])  (* equivalence class of higher-order constructs *)
blanchet@38744
   165
(* Pairs a constant with the list of its type instantiations. *)
blanchet@38939
   166
and ptype thy const x ts =
blanchet@38939
   167
  (if const then map pattern_for_type (these (try (Sign.const_typargs thy) x))
blanchet@38828
   168
   else []) @
blanchet@38889
   169
  (if term_patterns then map (pterm thy) ts else [])
blanchet@38939
   170
and pconst thy const (s, T) ts = (s, ptype thy const (s, T) ts)
blanchet@38939
   171
and rich_ptype thy const (s, T) ts =
blanchet@38939
   172
  PType (order_of_type T, ptype thy const (s, T) ts)
blanchet@38939
   173
and rich_pconst thy const (s, T) ts = (s, rich_ptype thy const (s, T) ts)
paulson@24287
   174
blanchet@38939
   175
fun string_for_hyper_pconst (s, ps) =
blanchet@38939
   176
  s ^ "{" ^ commas (map string_for_ptype ps) ^ "}"
paulson@24287
   177
blanchet@38823
   178
(* Add a pconstant to the table, but a [] entry means a standard
blanchet@38819
   179
   connective, which we ignore.*)
blanchet@40071
   180
fun add_pconst_to_table irrelevant_consts also_skolem (c, p) =
blanchet@40071
   181
  if member (op =) irrelevant_consts c orelse
blanchet@38819
   182
     (not also_skolem andalso String.isPrefix skolem_prefix c) then
blanchet@38819
   183
    I
blanchet@38819
   184
  else
blanchet@38939
   185
    Symtab.map_default (c, [p]) (insert (op =) p)
blanchet@38819
   186
blanchet@38819
   187
fun is_formula_type T = (T = HOLogic.boolT orelse T = propT)
blanchet@38819
   188
blanchet@40071
   189
fun pconsts_in_terms thy irrelevant_consts also_skolems pos ts =
blanchet@37505
   190
  let
blanchet@38819
   191
    val flip = Option.map not
blanchet@38587
   192
    (* We include free variables, as well as constants, to handle locales. For
blanchet@38587
   193
       each quantifiers that must necessarily be skolemized by the ATP, we
blanchet@38587
   194
       introduce a fresh constant to simulate the effect of Skolemization. *)
blanchet@38827
   195
    fun do_const const (s, T) ts =
blanchet@40071
   196
      add_pconst_to_table irrelevant_consts also_skolems
blanchet@40071
   197
                          (rich_pconst thy const (s, T) ts)
blanchet@38827
   198
      #> fold do_term ts
blanchet@38827
   199
    and do_term t =
blanchet@38827
   200
      case strip_comb t of
blanchet@38827
   201
        (Const x, ts) => do_const true x ts
blanchet@38827
   202
      | (Free x, ts) => do_const false x ts
blanchet@38939
   203
      | (Abs (_, T, t'), ts) =>
blanchet@38939
   204
        (null ts
blanchet@40071
   205
         ? add_pconst_to_table irrelevant_consts true
blanchet@40071
   206
                               (abs_name, PType (order_of_type T + 1, [])))
blanchet@38827
   207
        #> fold do_term (t' :: ts)
blanchet@38827
   208
      | (_, ts) => fold do_term ts
blanchet@38939
   209
    fun do_quantifier will_surely_be_skolemized abs_T body_t =
blanchet@37537
   210
      do_formula pos body_t
blanchet@38747
   211
      #> (if also_skolems andalso will_surely_be_skolemized then
blanchet@40071
   212
            add_pconst_to_table irrelevant_consts true
blanchet@38939
   213
                         (gensym skolem_prefix, PType (order_of_type abs_T, []))
blanchet@38587
   214
          else
blanchet@38587
   215
            I)
blanchet@38587
   216
    and do_term_or_formula T =
blanchet@38692
   217
      if is_formula_type T then do_formula NONE else do_term
blanchet@37537
   218
    and do_formula pos t =
blanchet@37537
   219
      case t of
blanchet@38939
   220
        Const (@{const_name all}, _) $ Abs (_, T, t') =>
blanchet@38939
   221
        do_quantifier (pos = SOME false) T t'
blanchet@37537
   222
      | @{const "==>"} $ t1 $ t2 =>
blanchet@37537
   223
        do_formula (flip pos) t1 #> do_formula pos t2
blanchet@37537
   224
      | Const (@{const_name "=="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38587
   225
        fold (do_term_or_formula T) [t1, t2]
blanchet@37537
   226
      | @{const Trueprop} $ t1 => do_formula pos t1
blanchet@37537
   227
      | @{const Not} $ t1 => do_formula (flip pos) t1
blanchet@38939
   228
      | Const (@{const_name All}, _) $ Abs (_, T, t') =>
blanchet@38939
   229
        do_quantifier (pos = SOME false) T t'
blanchet@38939
   230
      | Const (@{const_name Ex}, _) $ Abs (_, T, t') =>
blanchet@38939
   231
        do_quantifier (pos = SOME true) T t'
haftmann@38795
   232
      | @{const HOL.conj} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
haftmann@38795
   233
      | @{const HOL.disj} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
haftmann@38786
   234
      | @{const HOL.implies} $ t1 $ t2 =>
blanchet@37537
   235
        do_formula (flip pos) t1 #> do_formula pos t2
haftmann@38864
   236
      | Const (@{const_name HOL.eq}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38587
   237
        fold (do_term_or_formula T) [t1, t2]
blanchet@38587
   238
      | Const (@{const_name If}, Type (_, [_, Type (_, [T, _])]))
blanchet@38587
   239
        $ t1 $ t2 $ t3 =>
blanchet@38587
   240
        do_formula NONE t1 #> fold (do_term_or_formula T) [t2, t3]
blanchet@38939
   241
      | Const (@{const_name Ex1}, _) $ Abs (_, T, t') =>
blanchet@38939
   242
        do_quantifier (is_some pos) T t'
blanchet@38939
   243
      | Const (@{const_name Ball}, _) $ t1 $ Abs (_, T, t') =>
blanchet@38939
   244
        do_quantifier (pos = SOME false) T
blanchet@38939
   245
                      (HOLogic.mk_imp (incr_boundvars 1 t1 $ Bound 0, t'))
blanchet@38939
   246
      | Const (@{const_name Bex}, _) $ t1 $ Abs (_, T, t') =>
blanchet@38939
   247
        do_quantifier (pos = SOME true) T
blanchet@38939
   248
                      (HOLogic.mk_conj (incr_boundvars 1 t1 $ Bound 0, t'))
blanchet@37537
   249
      | (t0 as Const (_, @{typ bool})) $ t1 =>
blanchet@37537
   250
        do_term t0 #> do_formula pos t1  (* theory constant *)
blanchet@37537
   251
      | _ => do_term t
blanchet@38819
   252
  in Symtab.empty |> fold (do_formula pos) ts end
paulson@24287
   253
paulson@24287
   254
(*Inserts a dummy "constant" referring to the theory name, so that relevance
paulson@24287
   255
  takes the given theory into account.*)
blanchet@40070
   256
fun theory_const_prop_of ({theory_const_rel_weight,
blanchet@40070
   257
                           theory_const_irrel_weight, ...} : relevance_fudge)
blanchet@40070
   258
                         th =
blanchet@40070
   259
  if exists (curry (op <) 0.0) [theory_const_rel_weight,
blanchet@40070
   260
                                theory_const_irrel_weight] then
blanchet@37505
   261
    let
blanchet@37505
   262
      val name = Context.theory_name (theory_of_thm th)
blanchet@38992
   263
      val t = Const (name ^ theory_const_suffix, @{typ bool})
blanchet@37505
   264
    in t $ prop_of th end
blanchet@37505
   265
  else
blanchet@37505
   266
    prop_of th
blanchet@37505
   267
paulson@24287
   268
(**** Constant / Type Frequencies ****)
paulson@24287
   269
blanchet@38743
   270
(* A two-dimensional symbol table counts frequencies of constants. It's keyed
blanchet@38743
   271
   first by constant name and second by its list of type instantiations. For the
blanchet@38823
   272
   latter, we need a linear ordering on "pattern list". *)
paulson@24287
   273
blanchet@38823
   274
fun pattern_ord p =
blanchet@38743
   275
  case p of
blanchet@38744
   276
    (PVar, PVar) => EQUAL
blanchet@38823
   277
  | (PVar, PApp _) => LESS
blanchet@38823
   278
  | (PApp _, PVar) => GREATER
blanchet@38823
   279
  | (PApp q1, PApp q2) =>
blanchet@38823
   280
    prod_ord fast_string_ord (dict_ord pattern_ord) (q1, q2)
blanchet@38939
   281
fun ptype_ord (PType p, PType q) =
blanchet@38939
   282
  prod_ord (dict_ord pattern_ord) int_ord (swap p, swap q)
paulson@24287
   283
blanchet@38939
   284
structure PType_Tab = Table(type key = ptype val ord = ptype_ord)
paulson@24287
   285
blanchet@40070
   286
fun count_axiom_consts thy fudge =
blanchet@37503
   287
  let
blanchet@38827
   288
    fun do_const const (s, T) ts =
blanchet@38827
   289
      (* Two-dimensional table update. Constant maps to types maps to count. *)
blanchet@38939
   290
      PType_Tab.map_default (rich_ptype thy const (s, T) ts, 0) (Integer.add 1)
blanchet@38939
   291
      |> Symtab.map_default (s, PType_Tab.empty)
blanchet@38827
   292
      #> fold do_term ts
blanchet@38827
   293
    and do_term t =
blanchet@38827
   294
      case strip_comb t of
blanchet@38827
   295
        (Const x, ts) => do_const true x ts
blanchet@38827
   296
      | (Free x, ts) => do_const false x ts
blanchet@38827
   297
      | (Abs (_, _, t'), ts) => fold do_term (t' :: ts)
blanchet@38827
   298
      | (_, ts) => fold do_term ts
blanchet@40070
   299
  in do_term o theory_const_prop_of fudge o snd end
paulson@24287
   300
paulson@24287
   301
paulson@24287
   302
(**** Actual Filtering Code ****)
paulson@24287
   303
blanchet@39367
   304
fun pow_int _ 0 = 1.0
blanchet@38939
   305
  | pow_int x 1 = x
blanchet@38939
   306
  | pow_int x n = if n > 0 then x * pow_int x (n - 1) else pow_int x (n + 1) / x
blanchet@38939
   307
paulson@24287
   308
(*The frequency of a constant is the sum of those of all instances of its type.*)
blanchet@38824
   309
fun pconst_freq match const_tab (c, ps) =
blanchet@38939
   310
  PType_Tab.fold (fn (qs, m) => match (ps, qs) ? Integer.add m)
blanchet@38939
   311
                 (the (Symtab.lookup const_tab c)) 0
blanchet@38686
   312
paulson@24287
   313
blanchet@38085
   314
(* A surprising number of theorems contain only a few significant constants.
blanchet@38085
   315
   These include all induction rules, and other general theorems. *)
blanchet@37503
   316
blanchet@37503
   317
(* "log" seems best in practice. A constant function of one ignores the constant
blanchet@38938
   318
   frequencies. Rare constants give more points if they are relevant than less
blanchet@38938
   319
   rare ones. *)
blanchet@39367
   320
fun rel_weight_for _ freq = 1.0 + 2.0 / Math.ln (Real.fromInt freq + 1.0)
blanchet@38938
   321
blanchet@38938
   322
(* Irrelevant constants are treated differently. We associate lower penalties to
blanchet@38938
   323
   very rare constants and very common ones -- the former because they can't
blanchet@38938
   324
   lead to the inclusion of too many new facts, and the latter because they are
blanchet@38938
   325
   so common as to be of little interest. *)
blanchet@40070
   326
fun irrel_weight_for ({worse_irrel_freq, higher_order_irrel_weight, ...}
blanchet@40070
   327
                      : relevance_fudge) order freq =
blanchet@40070
   328
  let val (k, x) = worse_irrel_freq |> `Real.ceil in
blanchet@38939
   329
    (if freq < k then Math.ln (Real.fromInt (freq + 1)) / Math.ln x
blanchet@38939
   330
     else rel_weight_for order freq / rel_weight_for order k)
blanchet@40070
   331
    * pow_int higher_order_irrel_weight (order - 1)
blanchet@38938
   332
  end
blanchet@37503
   333
blanchet@37503
   334
(* Computes a constant's weight, as determined by its frequency. *)
blanchet@38992
   335
fun generic_pconst_weight abs_weight skolem_weight theory_const_weight
blanchet@38992
   336
                          weight_for f const_tab (c as (s, PType (m, _))) =
blanchet@38816
   337
  if s = abs_name then abs_weight
blanchet@38816
   338
  else if String.isPrefix skolem_prefix s then skolem_weight
blanchet@38992
   339
  else if String.isSuffix theory_const_suffix s then theory_const_weight
blanchet@38939
   340
  else weight_for m (pconst_freq (match_ptype o f) const_tab c)
blanchet@38821
   341
blanchet@40070
   342
fun rel_pconst_weight ({abs_rel_weight, theory_const_rel_weight, ...}
blanchet@40070
   343
                       : relevance_fudge) const_tab =
blanchet@40070
   344
  generic_pconst_weight abs_rel_weight 0.0 theory_const_rel_weight
blanchet@38992
   345
                        rel_weight_for I const_tab
blanchet@40070
   346
fun irrel_pconst_weight (fudge as {abs_irrel_weight, skolem_irrel_weight,
blanchet@40070
   347
                                   theory_const_irrel_weight, ...}) const_tab =
blanchet@40070
   348
  generic_pconst_weight abs_irrel_weight skolem_irrel_weight
blanchet@40070
   349
                        theory_const_irrel_weight (irrel_weight_for fudge) swap
blanchet@40070
   350
                        const_tab
paulson@24287
   351
blanchet@40070
   352
fun locality_bonus (_ : relevance_fudge) General = 0.0
blanchet@40070
   353
  | locality_bonus {intro_bonus, ...} Intro = intro_bonus
blanchet@40070
   354
  | locality_bonus {elim_bonus, ...} Elim = elim_bonus
blanchet@40070
   355
  | locality_bonus {simp_bonus, ...} Simp = simp_bonus
blanchet@40070
   356
  | locality_bonus {local_bonus, ...} Local = local_bonus
blanchet@40070
   357
  | locality_bonus {assum_bonus, ...} Assum = assum_bonus
blanchet@40070
   358
  | locality_bonus {chained_bonus, ...} Chained = chained_bonus
blanchet@38751
   359
blanchet@40070
   360
fun axiom_weight fudge loc const_tab relevant_consts axiom_consts =
blanchet@38827
   361
  case axiom_consts |> List.partition (pconst_hyper_mem I relevant_consts)
blanchet@38827
   362
                    ||> filter_out (pconst_hyper_mem swap relevant_consts) of
blanchet@38827
   363
    ([], _) => 0.0
blanchet@38744
   364
  | (rel, irrel) =>
blanchet@38889
   365
    let
blanchet@38889
   366
      val irrel = irrel |> filter_out (pconst_mem swap rel)
blanchet@38938
   367
      val rel_weight =
blanchet@40070
   368
        0.0 |> fold (curry (op +) o rel_pconst_weight fudge const_tab) rel
blanchet@38889
   369
      val irrel_weight =
blanchet@40070
   370
        ~ (locality_bonus fudge loc)
blanchet@40070
   371
        |> fold (curry (op +) o irrel_pconst_weight fudge const_tab) irrel
blanchet@38889
   372
      val res = rel_weight / (rel_weight + irrel_weight)
blanchet@38889
   373
    in if Real.isFinite res then res else 0.0 end
blanchet@38747
   374
blanchet@40071
   375
fun pconsts_in_axiom thy irrelevant_consts t =
blanchet@38825
   376
  Symtab.fold (fn (s, pss) => fold (cons o pair s) pss)
blanchet@40071
   377
              (pconsts_in_terms thy irrelevant_consts true (SOME true) [t]) []
blanchet@40071
   378
fun pair_consts_axiom thy irrelevant_consts fudge axiom =
blanchet@40071
   379
  case axiom |> snd |> theory_const_prop_of fudge
blanchet@40071
   380
             |> pconsts_in_axiom thy irrelevant_consts of
blanchet@38827
   381
    [] => NONE
blanchet@38827
   382
  | consts => SOME ((axiom, consts), NONE)
paulson@24287
   383
blanchet@38699
   384
type annotated_thm =
blanchet@38939
   385
  (((unit -> string) * locality) * thm) * (string * ptype) list
blanchet@37505
   386
blanchet@38904
   387
fun take_most_relevant max_relevant remaining_max
blanchet@40070
   388
        ({max_imperfect, max_imperfect_exp, ...} : relevance_fudge) 
blanchet@40070
   389
        (candidates : (annotated_thm * real) list) =
blanchet@38744
   390
  let
blanchet@38747
   391
    val max_imperfect =
blanchet@40070
   392
      Real.ceil (Math.pow (max_imperfect,
blanchet@38904
   393
                    Math.pow (Real.fromInt remaining_max
blanchet@40070
   394
                              / Real.fromInt max_relevant, max_imperfect_exp)))
blanchet@38747
   395
    val (perfect, imperfect) =
blanchet@38889
   396
      candidates |> sort (Real.compare o swap o pairself snd)
blanchet@38889
   397
                 |> take_prefix (fn (_, w) => w > 0.99999)
blanchet@38747
   398
    val ((accepts, more_rejects), rejects) =
blanchet@38747
   399
      chop max_imperfect imperfect |>> append perfect |>> chop remaining_max
blanchet@38744
   400
  in
blanchet@38889
   401
    trace_msg (fn () =>
blanchet@38889
   402
        "Actually passed (" ^ Int.toString (length accepts) ^ " of " ^
blanchet@38889
   403
        Int.toString (length candidates) ^ "): " ^
blanchet@38889
   404
        (accepts |> map (fn ((((name, _), _), _), weight) =>
blanchet@38752
   405
                            name () ^ " [" ^ Real.toString weight ^ "]")
blanchet@38745
   406
                 |> commas));
blanchet@38747
   407
    (accepts, more_rejects @ rejects)
blanchet@38744
   408
  end
paulson@24287
   409
blanchet@40071
   410
fun if_empty_replace_with_locality thy irrelevant_consts axioms loc tab =
blanchet@38819
   411
  if Symtab.is_empty tab then
blanchet@40071
   412
    pconsts_in_terms thy irrelevant_consts false (SOME false)
blanchet@38819
   413
        (map_filter (fn ((_, loc'), th) =>
blanchet@38819
   414
                        if loc' = loc then SOME (prop_of th) else NONE) axioms)
blanchet@38819
   415
  else
blanchet@38819
   416
    tab
blanchet@38819
   417
blanchet@40071
   418
fun relevance_filter ctxt threshold0 decay max_relevant irrelevant_consts
blanchet@40070
   419
        (fudge as {threshold_divisor, ridiculous_threshold, ...})
blanchet@40070
   420
        ({add, del, ...} : relevance_override) axioms goal_ts =
blanchet@38739
   421
  let
blanchet@38739
   422
    val thy = ProofContext.theory_of ctxt
blanchet@40070
   423
    val const_tab = fold (count_axiom_consts thy fudge) axioms Symtab.empty
blanchet@38819
   424
    val goal_const_tab =
blanchet@40071
   425
      pconsts_in_terms thy irrelevant_consts false (SOME false) goal_ts
blanchet@40071
   426
      |> fold (if_empty_replace_with_locality thy irrelevant_consts axioms)
blanchet@38993
   427
              [Chained, Assum, Local]
blanchet@39012
   428
    val add_ths = Attrib.eval_thms ctxt add
blanchet@39012
   429
    val del_ths = Attrib.eval_thms ctxt del
blanchet@40191
   430
    val axioms = axioms |> filter_out (member Thm.eq_thm del_ths o snd)
blanchet@38747
   431
    fun iter j remaining_max threshold rel_const_tab hopeless hopeful =
blanchet@38739
   432
      let
blanchet@40191
   433
        fun relevant [] _ [] =
blanchet@38747
   434
            (* Nothing has been added this iteration. *)
blanchet@40070
   435
            if j = 0 andalso threshold >= ridiculous_threshold then
blanchet@38747
   436
              (* First iteration? Try again. *)
blanchet@40070
   437
              iter 0 max_relevant (threshold / threshold_divisor) rel_const_tab
blanchet@38747
   438
                   hopeless hopeful
blanchet@38744
   439
            else
blanchet@40191
   440
              []
blanchet@38889
   441
          | relevant candidates rejects [] =
blanchet@38739
   442
            let
blanchet@38747
   443
              val (accepts, more_rejects) =
blanchet@40070
   444
                take_most_relevant max_relevant remaining_max fudge candidates
blanchet@38739
   445
              val rel_const_tab' =
blanchet@38745
   446
                rel_const_tab
blanchet@40071
   447
                |> fold (add_pconst_to_table irrelevant_consts false)
blanchet@40071
   448
                        (maps (snd o fst) accepts)
blanchet@38744
   449
              fun is_dirty (c, _) =
blanchet@38744
   450
                Symtab.lookup rel_const_tab' c <> Symtab.lookup rel_const_tab c
blanchet@38745
   451
              val (hopeful_rejects, hopeless_rejects) =
blanchet@38745
   452
                 (rejects @ hopeless, ([], []))
blanchet@38745
   453
                 |-> fold (fn (ax as (_, consts), old_weight) =>
blanchet@38745
   454
                              if exists is_dirty consts then
blanchet@38745
   455
                                apfst (cons (ax, NONE))
blanchet@38745
   456
                              else
blanchet@38745
   457
                                apsnd (cons (ax, old_weight)))
blanchet@38745
   458
                 |>> append (more_rejects
blanchet@38745
   459
                             |> map (fn (ax as (_, consts), old_weight) =>
blanchet@38745
   460
                                        (ax, if exists is_dirty consts then NONE
blanchet@38745
   461
                                             else SOME old_weight)))
blanchet@38747
   462
              val threshold =
blanchet@38822
   463
                1.0 - (1.0 - threshold)
blanchet@38822
   464
                      * Math.pow (decay, Real.fromInt (length accepts))
blanchet@38747
   465
              val remaining_max = remaining_max - length accepts
blanchet@38739
   466
            in
blanchet@38744
   467
              trace_msg (fn () => "New or updated constants: " ^
blanchet@38744
   468
                  commas (rel_const_tab' |> Symtab.dest
blanchet@38822
   469
                          |> subtract (op =) (rel_const_tab |> Symtab.dest)
blanchet@38827
   470
                          |> map string_for_hyper_pconst));
blanchet@38745
   471
              map (fst o fst) accepts @
blanchet@38747
   472
              (if remaining_max = 0 then
blanchet@40191
   473
                 []
blanchet@38745
   474
               else
blanchet@38747
   475
                 iter (j + 1) remaining_max threshold rel_const_tab'
blanchet@38747
   476
                      hopeless_rejects hopeful_rejects)
blanchet@38739
   477
            end
blanchet@38889
   478
          | relevant candidates rejects
blanchet@39367
   479
                     (((ax as (((_, loc), _), axiom_consts)), cached_weight)
blanchet@38747
   480
                      :: hopeful) =
blanchet@38739
   481
            let
blanchet@38739
   482
              val weight =
blanchet@38739
   483
                case cached_weight of
blanchet@38739
   484
                  SOME w => w
blanchet@40070
   485
                | NONE => axiom_weight fudge loc const_tab rel_const_tab
blanchet@40070
   486
                                       axiom_consts
blanchet@38739
   487
            in
blanchet@38741
   488
              if weight >= threshold then
blanchet@38889
   489
                relevant ((ax, weight) :: candidates) rejects hopeful
blanchet@38739
   490
              else
blanchet@38889
   491
                relevant candidates ((ax, weight) :: rejects) hopeful
blanchet@38739
   492
            end
blanchet@38739
   493
        in
blanchet@38744
   494
          trace_msg (fn () =>
blanchet@38744
   495
              "ITERATION " ^ string_of_int j ^ ": current threshold: " ^
blanchet@38744
   496
              Real.toString threshold ^ ", constants: " ^
blanchet@38744
   497
              commas (rel_const_tab |> Symtab.dest
blanchet@38744
   498
                      |> filter (curry (op <>) [] o snd)
blanchet@38827
   499
                      |> map string_for_hyper_pconst));
blanchet@38889
   500
          relevant [] [] hopeful
blanchet@38739
   501
        end
blanchet@40191
   502
    fun add_add_ths accepts =
blanchet@40191
   503
      (axioms |> filter ((member Thm.eq_thm add_ths
blanchet@40191
   504
                          andf (not o member (Thm.eq_thm o apsnd snd) accepts))
blanchet@40191
   505
                         o snd))
blanchet@40191
   506
      @ accepts
blanchet@38739
   507
  in
blanchet@40191
   508
    axioms |> map_filter (pair_consts_axiom thy irrelevant_consts fudge)
blanchet@38819
   509
           |> iter 0 max_relevant threshold0 goal_const_tab []
blanchet@40191
   510
           |> not (null add_ths) ? add_add_ths
blanchet@38739
   511
           |> tap (fn res => trace_msg (fn () =>
blanchet@38686
   512
                                "Total relevant: " ^ Int.toString (length res)))
blanchet@38739
   513
  end
paulson@24287
   514
blanchet@38744
   515
paulson@24287
   516
(***************************************************************)
mengj@19768
   517
(* Retrieving and filtering lemmas                             *)
mengj@19768
   518
(***************************************************************)
mengj@19768
   519
paulson@33022
   520
(*** retrieve lemmas and filter them ***)
mengj@19768
   521
paulson@20757
   522
(*Reject theorems with names like "List.filter.filter_list_def" or
paulson@21690
   523
  "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
paulson@20757
   524
fun is_package_def a =
wenzelm@30364
   525
  let val names = Long_Name.explode a
paulson@21690
   526
  in
paulson@21690
   527
     length names > 2 andalso
paulson@21690
   528
     not (hd names = "local") andalso
paulson@21690
   529
     String.isSuffix "_def" a  orelse  String.isSuffix "_defs" a
paulson@21690
   530
  end;
paulson@20757
   531
blanchet@38937
   532
fun mk_fact_table f xs =
blanchet@38937
   533
  fold (Termtab.update o `(prop_of o f)) xs Termtab.empty
blanchet@38937
   534
fun uniquify xs = Termtab.fold (cons o snd) (mk_fact_table snd xs) []
mengj@19768
   535
blanchet@37626
   536
(* FIXME: put other record thms here, or declare as "no_atp" *)
blanchet@37626
   537
val multi_base_blacklist =
blanchet@37626
   538
  ["defs", "select_defs", "update_defs", "induct", "inducts", "split", "splits",
blanchet@38682
   539
   "split_asm", "cases", "ext_cases", "eq.simps", "eq.refl", "nchotomy",
blanchet@38682
   540
   "case_cong", "weak_case_cong"]
blanchet@38682
   541
  |> map (prefix ".")
blanchet@37626
   542
blanchet@37626
   543
val max_lambda_nesting = 3
blanchet@37626
   544
blanchet@37626
   545
fun term_has_too_many_lambdas max (t1 $ t2) =
blanchet@37626
   546
    exists (term_has_too_many_lambdas max) [t1, t2]
blanchet@37626
   547
  | term_has_too_many_lambdas max (Abs (_, _, t)) =
blanchet@37626
   548
    max = 0 orelse term_has_too_many_lambdas (max - 1) t
blanchet@37626
   549
  | term_has_too_many_lambdas _ _ = false
blanchet@37626
   550
blanchet@37626
   551
(* Don't count nested lambdas at the level of formulas, since they are
blanchet@37626
   552
   quantifiers. *)
blanchet@37626
   553
fun formula_has_too_many_lambdas Ts (Abs (_, T, t)) =
blanchet@37626
   554
    formula_has_too_many_lambdas (T :: Ts) t
blanchet@37626
   555
  | formula_has_too_many_lambdas Ts t =
blanchet@37626
   556
    if is_formula_type (fastype_of1 (Ts, t)) then
blanchet@37626
   557
      exists (formula_has_too_many_lambdas Ts) (#2 (strip_comb t))
blanchet@37626
   558
    else
blanchet@37626
   559
      term_has_too_many_lambdas max_lambda_nesting t
blanchet@37626
   560
blanchet@38692
   561
(* The max apply depth of any "metis" call in "Metis_Examples" (on 2007-10-31)
blanchet@37626
   562
   was 11. *)
blanchet@37626
   563
val max_apply_depth = 15
blanchet@37626
   564
blanchet@37626
   565
fun apply_depth (f $ t) = Int.max (apply_depth f, apply_depth t + 1)
blanchet@37626
   566
  | apply_depth (Abs (_, _, t)) = apply_depth t
blanchet@37626
   567
  | apply_depth _ = 0
blanchet@37626
   568
blanchet@37626
   569
fun is_formula_too_complex t =
blanchet@38085
   570
  apply_depth t > max_apply_depth orelse formula_has_too_many_lambdas [] t
blanchet@37626
   571
blanchet@39946
   572
(* FIXME: Extend to "Meson" and "Metis" *)
blanchet@37543
   573
val exists_sledgehammer_const =
blanchet@37626
   574
  exists_Const (fn (s, _) => String.isPrefix sledgehammer_prefix s)
blanchet@37626
   575
blanchet@38904
   576
(* FIXME: make more reliable *)
blanchet@38904
   577
val exists_low_level_class_const =
blanchet@38904
   578
  exists_Const (fn (s, _) =>
blanchet@38904
   579
     String.isSubstring (Long_Name.separator ^ "class" ^ Long_Name.separator) s)
blanchet@38904
   580
blanchet@38821
   581
fun is_metastrange_theorem th =
blanchet@37626
   582
  case head_of (concl_of th) of
blanchet@37626
   583
      Const (a, _) => (a <> @{const_name Trueprop} andalso
blanchet@37626
   584
                       a <> @{const_name "=="})
blanchet@37626
   585
    | _ => false
blanchet@37626
   586
blanchet@38821
   587
fun is_that_fact th =
blanchet@38821
   588
  String.isSuffix (Long_Name.separator ^ Obtain.thatN) (Thm.get_name_hint th)
blanchet@38821
   589
  andalso exists_subterm (fn Free (s, _) => s = Name.skolem Auto_Bind.thesisN
blanchet@38821
   590
                           | _ => false) (prop_of th)
blanchet@38821
   591
blanchet@37626
   592
val type_has_top_sort =
blanchet@37626
   593
  exists_subtype (fn TFree (_, []) => true | TVar (_, []) => true | _ => false)
blanchet@37626
   594
blanchet@38085
   595
(**** Predicates to detect unwanted facts (prolific or likely to cause
blanchet@37347
   596
      unsoundness) ****)
paulson@21470
   597
blanchet@38289
   598
(* Too general means, positive equality literal with a variable X as one
blanchet@38289
   599
   operand, when X does not occur properly in the other operand. This rules out
blanchet@38289
   600
   clearly inconsistent facts such as X = a | X = b, though it by no means
blanchet@38289
   601
   guarantees soundness. *)
paulson@21470
   602
blanchet@38289
   603
(* Unwanted equalities are those between a (bound or schematic) variable that
blanchet@38289
   604
   does not properly occur in the second operand. *)
blanchet@38607
   605
val is_exhaustive_finite =
blanchet@38607
   606
  let
blanchet@38629
   607
    fun is_bad_equal (Var z) t =
blanchet@38629
   608
        not (exists_subterm (fn Var z' => z = z' | _ => false) t)
blanchet@38629
   609
      | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
blanchet@38629
   610
      | is_bad_equal _ _ = false
blanchet@38629
   611
    fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
blanchet@38607
   612
    fun do_formula pos t =
blanchet@38607
   613
      case (pos, t) of
blanchet@38615
   614
        (_, @{const Trueprop} $ t1) => do_formula pos t1
blanchet@38607
   615
      | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
blanchet@38607
   616
        do_formula pos t'
blanchet@38607
   617
      | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
blanchet@38607
   618
        do_formula pos t'
blanchet@38607
   619
      | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
blanchet@38607
   620
        do_formula pos t'
blanchet@38607
   621
      | (_, @{const "==>"} $ t1 $ t2) =>
blanchet@38629
   622
        do_formula (not pos) t1 andalso
blanchet@38629
   623
        (t2 = @{prop False} orelse do_formula pos t2)
haftmann@38786
   624
      | (_, @{const HOL.implies} $ t1 $ t2) =>
blanchet@38629
   625
        do_formula (not pos) t1 andalso
blanchet@38629
   626
        (t2 = @{const False} orelse do_formula pos t2)
blanchet@38607
   627
      | (_, @{const Not} $ t1) => do_formula (not pos) t1
haftmann@38795
   628
      | (true, @{const HOL.disj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
haftmann@38795
   629
      | (false, @{const HOL.conj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
haftmann@38864
   630
      | (true, Const (@{const_name HOL.eq}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38607
   631
      | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38607
   632
      | _ => false
blanchet@38607
   633
  in do_formula true end
blanchet@38607
   634
blanchet@38592
   635
fun has_bound_or_var_of_type tycons =
blanchet@38592
   636
  exists_subterm (fn Var (_, Type (s, _)) => member (op =) tycons s
blanchet@38592
   637
                   | Abs (_, Type (s, _), _) => member (op =) tycons s
blanchet@38592
   638
                   | _ => false)
paulson@21431
   639
blanchet@38085
   640
(* Facts are forbidden to contain variables of these types. The typical reason
blanchet@37347
   641
   is that they lead to unsoundness. Note that "unit" satisfies numerous
blanchet@38085
   642
   equations like "?x = ()". The resulting clauses will have no type constraint,
blanchet@37347
   643
   yielding false proofs. Even "bool" leads to many unsound proofs, though only
blanchet@37347
   644
   for higher-order problems. *)
blanchet@38592
   645
val dangerous_types = [@{type_name unit}, @{type_name bool}, @{type_name prop}];
paulson@22217
   646
blanchet@38085
   647
(* Facts containing variables of type "unit" or "bool" or of the form
blanchet@38290
   648
   "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
blanchet@38290
   649
   are omitted. *)
blanchet@38593
   650
fun is_dangerous_term full_types t =
blanchet@38609
   651
  not full_types andalso
blanchet@38679
   652
  let val t = transform_elim_term t in
blanchet@38679
   653
    has_bound_or_var_of_type dangerous_types t orelse
blanchet@38679
   654
    is_exhaustive_finite t
blanchet@38679
   655
  end
paulson@21470
   656
blanchet@38627
   657
fun is_theorem_bad_for_atps full_types thm =
blanchet@38627
   658
  let val t = prop_of thm in
blanchet@38627
   659
    is_formula_too_complex t orelse exists_type type_has_top_sort t orelse
blanchet@38627
   660
    is_dangerous_term full_types t orelse exists_sledgehammer_const t orelse
blanchet@38904
   661
    exists_low_level_class_const t orelse is_metastrange_theorem thm orelse
blanchet@38904
   662
    is_that_fact thm
blanchet@38627
   663
  end
blanchet@38627
   664
blanchet@38937
   665
fun clasimpset_rules_of ctxt =
blanchet@38937
   666
  let
blanchet@38937
   667
    val {safeIs, safeEs, hazIs, hazEs, ...} = ctxt |> claset_of |> rep_cs
blanchet@38937
   668
    val intros = safeIs @ hazIs
blanchet@38937
   669
    val elims = map Classical.classical_rule (safeEs @ hazEs)
blanchet@38937
   670
    val simps = ctxt |> simpset_of |> dest_ss |> #simps |> map snd
blanchet@38937
   671
  in (mk_fact_table I intros, mk_fact_table I elims, mk_fact_table I simps) end
blanchet@38937
   672
blanchet@39265
   673
fun all_prefixes_of s =
blanchet@39265
   674
  map (fn i => String.extract (s, 0, SOME i)) (1 upto size s - 1)
blanchet@39265
   675
blanchet@39265
   676
(* This is a terrible hack. Free variables are sometimes code as "M__" when they
blanchet@39265
   677
   are displayed as "M" and we want to avoid clashes with these. But sometimes
blanchet@39265
   678
   it's even worse: "Ma__" encodes "M". So we simply reserve all prefixes of all
blanchet@39265
   679
   free variables. In the worse case scenario, where the fact won't be resolved
blanchet@39265
   680
   correctly, the user can fix it manually, e.g., by naming the fact in
blanchet@39265
   681
   question. Ideally we would need nothing of it, but backticks just don't work
blanchet@39265
   682
   with schematic variables. *)
blanchet@39265
   683
fun close_form t =
blanchet@39265
   684
  (t, [] |> Term.add_free_names t |> maps all_prefixes_of)
blanchet@39265
   685
  |> fold (fn ((s, i), T) => fn (t', taken) =>
blanchet@39265
   686
              let val s' = Name.variant taken s in
blanchet@39265
   687
                (Term.all T $ Abs (s', T, abstract_over (Var ((s, i), T), t')),
blanchet@39265
   688
                 s' :: taken)
blanchet@39265
   689
              end)
blanchet@39265
   690
          (Term.add_vars t [] |> sort_wrt (fst o fst))
blanchet@39265
   691
  |> fst
blanchet@39265
   692
blanchet@40070
   693
fun all_name_thms_pairs ctxt reserved full_types
blanchet@40070
   694
        ({intro_bonus, elim_bonus, simp_bonus, ...} : relevance_fudge) add_ths
blanchet@40070
   695
        chained_ths =
blanchet@38627
   696
  let
blanchet@38752
   697
    val thy = ProofContext.theory_of ctxt
wenzelm@39557
   698
    val global_facts = Global_Theory.facts_of thy
blanchet@38644
   699
    val local_facts = ProofContext.facts_of ctxt
blanchet@38644
   700
    val named_locals = local_facts |> Facts.dest_static []
blanchet@38993
   701
    val assms = Assumption.all_assms_of ctxt
blanchet@38993
   702
    fun is_assum th = exists (fn ct => prop_of th aconv term_of ct) assms
blanchet@38752
   703
    val is_chained = member Thm.eq_thm chained_ths
blanchet@38937
   704
    val (intros, elims, simps) =
blanchet@40070
   705
      if exists (curry (op <) 0.0) [intro_bonus, elim_bonus, simp_bonus] then
blanchet@38937
   706
        clasimpset_rules_of ctxt
blanchet@38937
   707
      else
blanchet@38937
   708
        (Termtab.empty, Termtab.empty, Termtab.empty)
blanchet@38738
   709
    fun is_good_unnamed_local th =
blanchet@38820
   710
      not (Thm.has_name_hint th) andalso
blanchet@38738
   711
      forall (fn (_, ths) => not (member Thm.eq_thm ths th)) named_locals
blanchet@38644
   712
    val unnamed_locals =
blanchet@38820
   713
      union Thm.eq_thm (Facts.props local_facts) chained_ths
blanchet@38820
   714
      |> filter is_good_unnamed_local |> map (pair "" o single)
blanchet@38627
   715
    val full_space =
blanchet@38738
   716
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts)
blanchet@38752
   717
    fun add_facts global foldx facts =
blanchet@38699
   718
      foldx (fn (name0, ths) =>
blanchet@38699
   719
        if name0 <> "" andalso
blanchet@39012
   720
           forall (not o member Thm.eq_thm add_ths) ths andalso
blanchet@38699
   721
           (Facts.is_concealed facts name0 orelse
blanchet@38699
   722
            (respect_no_atp andalso is_package_def name0) orelse
blanchet@38699
   723
            exists (fn s => String.isSuffix s name0) multi_base_blacklist orelse
blanchet@38699
   724
            String.isSuffix "_def_raw" (* FIXME: crude hack *) name0) then
blanchet@38627
   725
          I
blanchet@38627
   726
        else
blanchet@38627
   727
          let
blanchet@38699
   728
            val multi = length ths > 1
blanchet@38696
   729
            fun backquotify th =
blanchet@39718
   730
              "`" ^ Print_Mode.setmp (filter (curry (op =) Symbol.xsymbolsN)
blanchet@39265
   731
                                             (print_mode_value ()))
blanchet@39265
   732
                   (Syntax.string_of_term ctxt) (close_form (prop_of th)) ^ "`"
blanchet@38738
   733
              |> String.translate (fn c => if Char.isPrint c then str c else "")
blanchet@38738
   734
              |> simplify_spaces
blanchet@38699
   735
            fun check_thms a =
blanchet@38699
   736
              case try (ProofContext.get_thms ctxt) a of
blanchet@38699
   737
                NONE => false
blanchet@38699
   738
              | SOME ths' => Thm.eq_thms (ths, ths')
blanchet@38627
   739
          in
blanchet@38699
   740
            pair 1
blanchet@38699
   741
            #> fold (fn th => fn (j, rest) =>
blanchet@38699
   742
                 (j + 1,
blanchet@38699
   743
                  if is_theorem_bad_for_atps full_types th andalso
blanchet@39012
   744
                     not (member Thm.eq_thm add_ths th) then
blanchet@38699
   745
                    rest
blanchet@38699
   746
                  else
blanchet@38752
   747
                    (((fn () =>
blanchet@38752
   748
                          if name0 = "" then
blanchet@38752
   749
                            th |> backquotify
blanchet@38752
   750
                          else
blanchet@38752
   751
                            let
blanchet@38752
   752
                              val name1 = Facts.extern facts name0
blanchet@38752
   753
                              val name2 = Name_Space.extern full_space name0
blanchet@38752
   754
                            in
blanchet@38752
   755
                              case find_first check_thms [name1, name2, name0] of
blanchet@38752
   756
                                SOME name => repair_name reserved multi j name
blanchet@38752
   757
                              | NONE => ""
blanchet@38937
   758
                            end),
blanchet@38937
   759
                      let val t = prop_of th in
blanchet@40071
   760
                        if is_chained th then
blanchet@40071
   761
                          Chained
blanchet@38993
   762
                        else if global then
blanchet@38993
   763
                          if Termtab.defined intros t then Intro
blanchet@38993
   764
                          else if Termtab.defined elims t then Elim
blanchet@38993
   765
                          else if Termtab.defined simps t then Simp
blanchet@38993
   766
                          else General
blanchet@38993
   767
                        else
blanchet@38993
   768
                          if is_assum th then Assum else Local
blanchet@38937
   769
                      end),
blanchet@38752
   770
                      (multi, th)) :: rest)) ths
blanchet@38699
   771
            #> snd
blanchet@38627
   772
          end)
blanchet@38644
   773
  in
blanchet@38752
   774
    [] |> add_facts false fold local_facts (unnamed_locals @ named_locals)
blanchet@38752
   775
       |> add_facts true Facts.fold_static global_facts global_facts
blanchet@38644
   776
  end
blanchet@38627
   777
blanchet@38627
   778
(* The single-name theorems go after the multiple-name ones, so that single
blanchet@38627
   779
   names are preferred when both are available. *)
blanchet@38699
   780
fun name_thm_pairs ctxt respect_no_atp =
blanchet@38744
   781
  List.partition (fst o snd) #> op @ #> map (apsnd snd)
blanchet@38699
   782
  #> respect_no_atp ? filter_out (No_ATPs.member ctxt o snd)
blanchet@38627
   783
blanchet@38627
   784
(***************************************************************)
blanchet@38627
   785
(* ATP invocation methods setup                                *)
blanchet@38627
   786
(***************************************************************)
blanchet@38627
   787
blanchet@40071
   788
fun relevant_facts ctxt full_types (threshold0, threshold1) max_relevant
blanchet@40071
   789
                   irrelevant_consts fudge (override as {add, only, ...})
blanchet@40071
   790
                   chained_ths hyp_ts concl_t =
blanchet@37538
   791
  let
blanchet@38822
   792
    val decay = Math.pow ((1.0 - threshold1) / (1.0 - threshold0),
blanchet@38822
   793
                          1.0 / Real.fromInt (max_relevant + 1))
blanchet@39012
   794
    val add_ths = Attrib.eval_thms ctxt add
blanchet@38696
   795
    val reserved = reserved_isar_keyword_table ()
blanchet@37538
   796
    val axioms =
blanchet@38699
   797
      (if only then
blanchet@38752
   798
         maps (map (fn ((name, loc), th) => ((K name, loc), (true, th)))
blanchet@38752
   799
               o name_thm_pairs_from_ref ctxt reserved chained_ths) add
blanchet@38699
   800
       else
blanchet@40070
   801
         all_name_thms_pairs ctxt reserved full_types fudge add_ths chained_ths)
blanchet@38688
   802
      |> name_thm_pairs ctxt (respect_no_atp andalso not only)
blanchet@38937
   803
      |> uniquify
blanchet@37538
   804
  in
blanchet@38688
   805
    trace_msg (fn () => "Considering " ^ Int.toString (length axioms) ^
blanchet@38688
   806
                        " theorems");
blanchet@39366
   807
    (if only orelse threshold1 < 0.0 then
blanchet@39366
   808
       axioms
blanchet@39366
   809
     else if threshold0 > 1.0 orelse threshold0 > threshold1 orelse
blanchet@39366
   810
             max_relevant = 0 then
blanchet@38739
   811
       []
blanchet@38739
   812
     else
blanchet@40071
   813
       relevance_filter ctxt threshold0 decay max_relevant irrelevant_consts
blanchet@40071
   814
                        fudge override axioms (concl_t :: hyp_ts))
blanchet@38822
   815
    |> map (apfst (apfst (fn f => f ())))
blanchet@37538
   816
  end
immler@30536
   817
paulson@15347
   818
end;