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