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