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