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