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