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