src/HOL/Tools/Sledgehammer/sledgehammer_filter.ML
author blanchet
Tue Oct 05 12:50:45 2010 +0200 (2010-10-05 ago)
changeset 39958 88c9aa5666de
parent 39946 78faa9b31202
child 40070 bdb890782d4a
permissions -rw-r--r--
tuned comments
blanchet@38988
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_filter.ML
blanchet@38027
     2
    Author:     Jia Meng, Cambridge University Computer Laboratory and NICTA
blanchet@36393
     3
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@39958
     4
blanchet@39958
     5
Sledgehammer's relevance filter.
wenzelm@33309
     6
*)
paulson@15452
     7
blanchet@38988
     8
signature SLEDGEHAMMER_FILTER =
wenzelm@16802
     9
sig
blanchet@38993
    10
  datatype locality = General | Intro | Elim | Simp | Local | Assum | Chained
blanchet@38752
    11
blanchet@35966
    12
  type relevance_override =
blanchet@38996
    13
    {add: (Facts.ref * Attrib.src list) list,
blanchet@38996
    14
     del: (Facts.ref * Attrib.src list) list,
blanchet@35966
    15
     only: bool}
blanchet@35966
    16
blanchet@37616
    17
  val trace : bool Unsynchronized.ref
blanchet@38938
    18
  val worse_irrel_freq : real Unsynchronized.ref
blanchet@38939
    19
  val higher_order_irrel_weight : real Unsynchronized.ref
blanchet@38899
    20
  val abs_rel_weight : real Unsynchronized.ref
blanchet@38899
    21
  val abs_irrel_weight : real Unsynchronized.ref
blanchet@38899
    22
  val skolem_irrel_weight : real Unsynchronized.ref
blanchet@38992
    23
  val theory_const_rel_weight : real Unsynchronized.ref
blanchet@38992
    24
  val theory_const_irrel_weight : real Unsynchronized.ref
blanchet@38937
    25
  val intro_bonus : real Unsynchronized.ref
blanchet@38937
    26
  val elim_bonus : real Unsynchronized.ref
blanchet@38937
    27
  val simp_bonus : real Unsynchronized.ref
blanchet@38899
    28
  val local_bonus : real Unsynchronized.ref
blanchet@38993
    29
  val assum_bonus : real Unsynchronized.ref
blanchet@38899
    30
  val chained_bonus : real Unsynchronized.ref
blanchet@38904
    31
  val max_imperfect : real Unsynchronized.ref
blanchet@38904
    32
  val max_imperfect_exp : real Unsynchronized.ref
blanchet@38899
    33
  val threshold_divisor : real Unsynchronized.ref
blanchet@38899
    34
  val ridiculous_threshold : real Unsynchronized.ref
blanchet@38744
    35
  val name_thm_pairs_from_ref :
blanchet@38996
    36
    Proof.context -> unit Symtab.table -> thm list
blanchet@38996
    37
    -> Facts.ref * Attrib.src list -> ((string * locality) * thm) list
blanchet@37347
    38
  val relevant_facts :
blanchet@38997
    39
    Proof.context -> bool -> real * real -> int -> relevance_override
blanchet@38891
    40
    -> thm list -> term list -> term -> ((string * locality) * thm) list
paulson@15347
    41
end;
paulson@15347
    42
blanchet@38988
    43
structure Sledgehammer_Filter : SLEDGEHAMMER_FILTER =
paulson@15347
    44
struct
paulson@15347
    45
blanchet@38652
    46
open Sledgehammer_Util
blanchet@38652
    47
blanchet@37616
    48
val trace = Unsynchronized.ref false
blanchet@37616
    49
fun trace_msg msg = if !trace then tracing (msg ()) else ()
blanchet@35826
    50
blanchet@38997
    51
(* experimental features *)
blanchet@38889
    52
val term_patterns = false
blanchet@38997
    53
val respect_no_atp = true
blanchet@38827
    54
blanchet@38997
    55
(* FUDGE *)
blanchet@38997
    56
val worse_irrel_freq = Unsynchronized.ref 100.0
blanchet@38997
    57
val higher_order_irrel_weight = Unsynchronized.ref 1.05
blanchet@38997
    58
val abs_rel_weight = Unsynchronized.ref 0.5
blanchet@38997
    59
val abs_irrel_weight = Unsynchronized.ref 2.0
blanchet@38997
    60
val skolem_irrel_weight = Unsynchronized.ref 0.75
blanchet@38997
    61
val theory_const_rel_weight = Unsynchronized.ref 0.5
blanchet@38997
    62
val theory_const_irrel_weight = Unsynchronized.ref 0.25
blanchet@38997
    63
val intro_bonus = Unsynchronized.ref 0.15
blanchet@38997
    64
val elim_bonus = Unsynchronized.ref 0.15
blanchet@38997
    65
val simp_bonus = Unsynchronized.ref 0.15
blanchet@38997
    66
val local_bonus = Unsynchronized.ref 0.55
blanchet@38997
    67
val assum_bonus = Unsynchronized.ref 1.05
blanchet@38997
    68
val chained_bonus = Unsynchronized.ref 1.5
blanchet@38997
    69
val max_imperfect = Unsynchronized.ref 11.5
blanchet@38997
    70
val max_imperfect_exp = Unsynchronized.ref 1.0
blanchet@38997
    71
val threshold_divisor = Unsynchronized.ref 2.0
blanchet@38997
    72
val ridiculous_threshold = Unsynchronized.ref 0.1
blanchet@37505
    73
blanchet@38993
    74
datatype locality = General | Intro | Elim | Simp | Local | Assum | Chained
blanchet@38752
    75
blanchet@35966
    76
type relevance_override =
blanchet@38996
    77
  {add: (Facts.ref * Attrib.src list) list,
blanchet@38996
    78
   del: (Facts.ref * Attrib.src list) list,
blanchet@35966
    79
   only: bool}
paulson@21070
    80
blanchet@37616
    81
val sledgehammer_prefix = "Sledgehammer" ^ Long_Name.separator
blanchet@39896
    82
val abs_name = sledgehammer_prefix ^ "abs"
blanchet@39896
    83
val skolem_prefix = sledgehammer_prefix ^ "sko"
blanchet@38992
    84
val theory_const_suffix = Long_Name.separator ^ " 1"
blanchet@37616
    85
blanchet@38744
    86
fun repair_name reserved multi j name =
blanchet@38744
    87
  (name |> Symtab.defined reserved name ? quote) ^
blanchet@38744
    88
  (if multi then "(" ^ Int.toString j ^ ")" else "")
blanchet@38744
    89
blanchet@38996
    90
fun name_thm_pairs_from_ref ctxt reserved chained_ths (xthm as (xref, args)) =
blanchet@38744
    91
  let
blanchet@38996
    92
    val ths = Attrib.eval_thms ctxt [xthm]
blanchet@38996
    93
    val bracket =
blanchet@38996
    94
      implode (map (fn arg => "[" ^ Pretty.str_of (Args.pretty_src ctxt arg)
blanchet@38996
    95
                               ^ "]") args)
blanchet@38996
    96
    val name =
blanchet@38996
    97
      case xref of
blanchet@39264
    98
        Facts.Fact s => "`" ^ s ^ "`" ^ bracket
blanchet@38996
    99
      | Facts.Named (("", _), _) => "[" ^ bracket ^ "]"
blanchet@39264
   100
      | _ => Facts.string_of_ref xref ^ bracket
blanchet@38744
   101
    val multi = length ths > 1
blanchet@38744
   102
  in
blanchet@38752
   103
    (ths, (1, []))
blanchet@38752
   104
    |-> fold (fn th => fn (j, rest) =>
blanchet@38752
   105
                 (j + 1, ((repair_name reserved multi j name,
blanchet@38752
   106
                          if member Thm.eq_thm chained_ths th then Chained
blanchet@38752
   107
                          else General), th) :: rest))
blanchet@38744
   108
    |> snd
blanchet@38699
   109
  end
blanchet@37616
   110
wenzelm@28477
   111
(***************************************************************)
wenzelm@28477
   112
(* Relevance Filtering                                         *)
wenzelm@28477
   113
(***************************************************************)
mengj@19194
   114
paulson@24287
   115
(*** constants with types ***)
paulson@24287
   116
blanchet@38939
   117
fun order_of_type (Type (@{type_name fun}, [T1, @{typ bool}])) =
blanchet@38939
   118
    order_of_type T1 (* cheat: pretend sets are first-order *)
blanchet@38939
   119
  | order_of_type (Type (@{type_name fun}, [T1, T2])) =
blanchet@38939
   120
    Int.max (order_of_type T1 + 1, order_of_type T2)
blanchet@38939
   121
  | order_of_type (Type (_, Ts)) = fold (Integer.max o order_of_type) Ts 0
blanchet@38939
   122
  | order_of_type _ = 0
blanchet@38939
   123
blanchet@38823
   124
(* An abstraction of Isabelle types and first-order terms *)
blanchet@38823
   125
datatype pattern = PVar | PApp of string * pattern list
blanchet@38939
   126
datatype ptype = PType of int * pattern list
blanchet@38744
   127
blanchet@38823
   128
fun string_for_pattern PVar = "_"
blanchet@38823
   129
  | string_for_pattern (PApp (s, ps)) =
blanchet@38823
   130
    if null ps then s else s ^ string_for_patterns ps
blanchet@38823
   131
and string_for_patterns ps = "(" ^ commas (map string_for_pattern ps) ^ ")"
blanchet@38939
   132
fun string_for_ptype (PType (_, ps)) = string_for_patterns ps
paulson@24287
   133
paulson@24287
   134
(*Is the second type an instance of the first one?*)
blanchet@38824
   135
fun match_pattern (PVar, _) = true
blanchet@38824
   136
  | match_pattern (PApp _, PVar) = false
blanchet@38824
   137
  | match_pattern (PApp (s, ps), PApp (t, qs)) =
blanchet@38824
   138
    s = t andalso match_patterns (ps, qs)
blanchet@38824
   139
and match_patterns (_, []) = true
blanchet@38824
   140
  | match_patterns ([], _) = false
blanchet@38824
   141
  | match_patterns (p :: ps, q :: qs) =
blanchet@38824
   142
    match_pattern (p, q) andalso match_patterns (ps, qs)
blanchet@38939
   143
fun match_ptype (PType (_, ps), PType (_, qs)) = match_patterns (ps, qs)
paulson@24287
   144
blanchet@38823
   145
(* Is there a unifiable constant? *)
blanchet@38827
   146
fun pconst_mem f consts (s, ps) =
blanchet@38939
   147
  exists (curry (match_ptype o f) ps)
blanchet@38827
   148
         (map snd (filter (curry (op =) s o fst) consts))
blanchet@38827
   149
fun pconst_hyper_mem f const_tab (s, ps) =
blanchet@38939
   150
  exists (curry (match_ptype o f) ps) (these (Symtab.lookup const_tab s))
blanchet@37505
   151
blanchet@38939
   152
fun pattern_for_type (Type (s, Ts)) = PApp (s, map pattern_for_type Ts)
blanchet@38939
   153
  | pattern_for_type (TFree (s, _)) = PApp (s, [])
blanchet@38939
   154
  | pattern_for_type (TVar _) = PVar
blanchet@38827
   155
blanchet@38827
   156
fun pterm thy t =
blanchet@38827
   157
  case strip_comb t of
blanchet@38827
   158
    (Const x, ts) => PApp (pconst thy true x ts)
blanchet@38827
   159
  | (Free x, ts) => PApp (pconst thy false x ts)
blanchet@39367
   160
  | (Var _, []) => PVar
blanchet@38827
   161
  | _ => PApp ("?", [])  (* equivalence class of higher-order constructs *)
blanchet@38744
   162
(* Pairs a constant with the list of its type instantiations. *)
blanchet@38939
   163
and ptype thy const x ts =
blanchet@38939
   164
  (if const then map pattern_for_type (these (try (Sign.const_typargs thy) x))
blanchet@38828
   165
   else []) @
blanchet@38889
   166
  (if term_patterns then map (pterm thy) ts else [])
blanchet@38939
   167
and pconst thy const (s, T) ts = (s, ptype thy const (s, T) ts)
blanchet@38939
   168
and rich_ptype thy const (s, T) ts =
blanchet@38939
   169
  PType (order_of_type T, ptype thy const (s, T) ts)
blanchet@38939
   170
and rich_pconst thy const (s, T) ts = (s, rich_ptype thy const (s, T) ts)
paulson@24287
   171
blanchet@38939
   172
fun string_for_hyper_pconst (s, ps) =
blanchet@38939
   173
  s ^ "{" ^ commas (map string_for_ptype ps) ^ "}"
paulson@24287
   174
blanchet@38822
   175
(* These are typically simplified away by "Meson.presimplify". Equality is
blanchet@38822
   176
   handled specially via "fequal". *)
blanchet@38682
   177
val boring_consts =
blanchet@38822
   178
  [@{const_name False}, @{const_name True}, @{const_name If}, @{const_name Let},
haftmann@38864
   179
   @{const_name HOL.eq}]
blanchet@37537
   180
blanchet@38823
   181
(* Add a pconstant to the table, but a [] entry means a standard
blanchet@38819
   182
   connective, which we ignore.*)
blanchet@38939
   183
fun add_pconst_to_table also_skolem (c, p) =
blanchet@38819
   184
  if member (op =) boring_consts c orelse
blanchet@38819
   185
     (not also_skolem andalso String.isPrefix skolem_prefix c) then
blanchet@38819
   186
    I
blanchet@38819
   187
  else
blanchet@38939
   188
    Symtab.map_default (c, [p]) (insert (op =) p)
blanchet@38819
   189
blanchet@38819
   190
fun is_formula_type T = (T = HOLogic.boolT orelse T = propT)
blanchet@38819
   191
blanchet@38906
   192
fun pconsts_in_terms thy also_skolems pos ts =
blanchet@37505
   193
  let
blanchet@38819
   194
    val flip = Option.map not
blanchet@38587
   195
    (* We include free variables, as well as constants, to handle locales. For
blanchet@38587
   196
       each quantifiers that must necessarily be skolemized by the ATP, we
blanchet@38587
   197
       introduce a fresh constant to simulate the effect of Skolemization. *)
blanchet@38827
   198
    fun do_const const (s, T) ts =
blanchet@38939
   199
      add_pconst_to_table also_skolems (rich_pconst thy const (s, T) ts)
blanchet@38827
   200
      #> fold do_term ts
blanchet@38827
   201
    and do_term t =
blanchet@38827
   202
      case strip_comb t of
blanchet@38827
   203
        (Const x, ts) => do_const true x ts
blanchet@38827
   204
      | (Free x, ts) => do_const false x ts
blanchet@38939
   205
      | (Abs (_, T, t'), ts) =>
blanchet@38939
   206
        (null ts
blanchet@38939
   207
         ? add_pconst_to_table true (abs_name, PType (order_of_type T + 1, [])))
blanchet@38827
   208
        #> fold do_term (t' :: ts)
blanchet@38827
   209
      | (_, ts) => fold do_term ts
blanchet@38939
   210
    fun do_quantifier will_surely_be_skolemized abs_T body_t =
blanchet@37537
   211
      do_formula pos body_t
blanchet@38747
   212
      #> (if also_skolems andalso will_surely_be_skolemized then
blanchet@38939
   213
            add_pconst_to_table true
blanchet@38939
   214
                         (gensym skolem_prefix, PType (order_of_type abs_T, []))
blanchet@38587
   215
          else
blanchet@38587
   216
            I)
blanchet@38587
   217
    and do_term_or_formula T =
blanchet@38692
   218
      if is_formula_type T then do_formula NONE else do_term
blanchet@37537
   219
    and do_formula pos t =
blanchet@37537
   220
      case t of
blanchet@38939
   221
        Const (@{const_name all}, _) $ Abs (_, T, t') =>
blanchet@38939
   222
        do_quantifier (pos = SOME false) T t'
blanchet@37537
   223
      | @{const "==>"} $ t1 $ t2 =>
blanchet@37537
   224
        do_formula (flip pos) t1 #> do_formula pos t2
blanchet@37537
   225
      | Const (@{const_name "=="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38587
   226
        fold (do_term_or_formula T) [t1, t2]
blanchet@37537
   227
      | @{const Trueprop} $ t1 => do_formula pos t1
blanchet@37537
   228
      | @{const Not} $ t1 => do_formula (flip pos) t1
blanchet@38939
   229
      | Const (@{const_name All}, _) $ Abs (_, T, t') =>
blanchet@38939
   230
        do_quantifier (pos = SOME false) T t'
blanchet@38939
   231
      | Const (@{const_name Ex}, _) $ Abs (_, T, t') =>
blanchet@38939
   232
        do_quantifier (pos = SOME true) T t'
haftmann@38795
   233
      | @{const HOL.conj} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
haftmann@38795
   234
      | @{const HOL.disj} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
haftmann@38786
   235
      | @{const HOL.implies} $ t1 $ t2 =>
blanchet@37537
   236
        do_formula (flip pos) t1 #> do_formula pos t2
haftmann@38864
   237
      | Const (@{const_name HOL.eq}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38587
   238
        fold (do_term_or_formula T) [t1, t2]
blanchet@38587
   239
      | Const (@{const_name If}, Type (_, [_, Type (_, [T, _])]))
blanchet@38587
   240
        $ t1 $ t2 $ t3 =>
blanchet@38587
   241
        do_formula NONE t1 #> fold (do_term_or_formula T) [t2, t3]
blanchet@38939
   242
      | Const (@{const_name Ex1}, _) $ Abs (_, T, t') =>
blanchet@38939
   243
        do_quantifier (is_some pos) T t'
blanchet@38939
   244
      | Const (@{const_name Ball}, _) $ t1 $ Abs (_, T, t') =>
blanchet@38939
   245
        do_quantifier (pos = SOME false) T
blanchet@38939
   246
                      (HOLogic.mk_imp (incr_boundvars 1 t1 $ Bound 0, t'))
blanchet@38939
   247
      | Const (@{const_name Bex}, _) $ t1 $ Abs (_, T, t') =>
blanchet@38939
   248
        do_quantifier (pos = SOME true) T
blanchet@38939
   249
                      (HOLogic.mk_conj (incr_boundvars 1 t1 $ Bound 0, t'))
blanchet@37537
   250
      | (t0 as Const (_, @{typ bool})) $ t1 =>
blanchet@37537
   251
        do_term t0 #> do_formula pos t1  (* theory constant *)
blanchet@37537
   252
      | _ => do_term t
blanchet@38819
   253
  in Symtab.empty |> fold (do_formula pos) ts end
paulson@24287
   254
paulson@24287
   255
(*Inserts a dummy "constant" referring to the theory name, so that relevance
paulson@24287
   256
  takes the given theory into account.*)
blanchet@38997
   257
fun theory_const_prop_of th =
blanchet@38997
   258
  if exists (curry (op <) 0.0) [!theory_const_rel_weight,
blanchet@38997
   259
                                !theory_const_irrel_weight] then
blanchet@37505
   260
    let
blanchet@37505
   261
      val name = Context.theory_name (theory_of_thm th)
blanchet@38992
   262
      val t = Const (name ^ theory_const_suffix, @{typ bool})
blanchet@37505
   263
    in t $ prop_of th end
blanchet@37505
   264
  else
blanchet@37505
   265
    prop_of th
blanchet@37505
   266
paulson@24287
   267
(**** Constant / Type Frequencies ****)
paulson@24287
   268
blanchet@38743
   269
(* A two-dimensional symbol table counts frequencies of constants. It's keyed
blanchet@38743
   270
   first by constant name and second by its list of type instantiations. For the
blanchet@38823
   271
   latter, we need a linear ordering on "pattern list". *)
paulson@24287
   272
blanchet@38823
   273
fun pattern_ord p =
blanchet@38743
   274
  case p of
blanchet@38744
   275
    (PVar, PVar) => EQUAL
blanchet@38823
   276
  | (PVar, PApp _) => LESS
blanchet@38823
   277
  | (PApp _, PVar) => GREATER
blanchet@38823
   278
  | (PApp q1, PApp q2) =>
blanchet@38823
   279
    prod_ord fast_string_ord (dict_ord pattern_ord) (q1, q2)
blanchet@38939
   280
fun ptype_ord (PType p, PType q) =
blanchet@38939
   281
  prod_ord (dict_ord pattern_ord) int_ord (swap p, swap q)
paulson@24287
   282
blanchet@38939
   283
structure PType_Tab = Table(type key = ptype val ord = ptype_ord)
paulson@24287
   284
blanchet@38997
   285
fun count_axiom_consts thy =
blanchet@37503
   286
  let
blanchet@38827
   287
    fun do_const const (s, T) ts =
blanchet@38827
   288
      (* Two-dimensional table update. Constant maps to types maps to count. *)
blanchet@38939
   289
      PType_Tab.map_default (rich_ptype thy const (s, T) ts, 0) (Integer.add 1)
blanchet@38939
   290
      |> Symtab.map_default (s, PType_Tab.empty)
blanchet@38827
   291
      #> fold do_term ts
blanchet@38827
   292
    and do_term t =
blanchet@38827
   293
      case strip_comb t of
blanchet@38827
   294
        (Const x, ts) => do_const true x ts
blanchet@38827
   295
      | (Free x, ts) => do_const false x ts
blanchet@38827
   296
      | (Abs (_, _, t'), ts) => fold do_term (t' :: ts)
blanchet@38827
   297
      | (_, ts) => fold do_term ts
blanchet@38997
   298
  in do_term o theory_const_prop_of o snd end
paulson@24287
   299
paulson@24287
   300
paulson@24287
   301
(**** Actual Filtering Code ****)
paulson@24287
   302
blanchet@39367
   303
fun pow_int _ 0 = 1.0
blanchet@38939
   304
  | pow_int x 1 = x
blanchet@38939
   305
  | pow_int x n = if n > 0 then x * pow_int x (n - 1) else pow_int x (n + 1) / x
blanchet@38939
   306
paulson@24287
   307
(*The frequency of a constant is the sum of those of all instances of its type.*)
blanchet@38824
   308
fun pconst_freq match const_tab (c, ps) =
blanchet@38939
   309
  PType_Tab.fold (fn (qs, m) => match (ps, qs) ? Integer.add m)
blanchet@38939
   310
                 (the (Symtab.lookup const_tab c)) 0
blanchet@38686
   311
paulson@24287
   312
blanchet@38085
   313
(* A surprising number of theorems contain only a few significant constants.
blanchet@38085
   314
   These include all induction rules, and other general theorems. *)
blanchet@37503
   315
blanchet@37503
   316
(* "log" seems best in practice. A constant function of one ignores the constant
blanchet@38938
   317
   frequencies. Rare constants give more points if they are relevant than less
blanchet@38938
   318
   rare ones. *)
blanchet@39367
   319
fun rel_weight_for _ freq = 1.0 + 2.0 / Math.ln (Real.fromInt freq + 1.0)
blanchet@38938
   320
blanchet@38938
   321
(* Irrelevant constants are treated differently. We associate lower penalties to
blanchet@38938
   322
   very rare constants and very common ones -- the former because they can't
blanchet@38938
   323
   lead to the inclusion of too many new facts, and the latter because they are
blanchet@38938
   324
   so common as to be of little interest. *)
blanchet@38939
   325
fun irrel_weight_for order freq =
blanchet@38938
   326
  let val (k, x) = !worse_irrel_freq |> `Real.ceil in
blanchet@38939
   327
    (if freq < k then Math.ln (Real.fromInt (freq + 1)) / Math.ln x
blanchet@38939
   328
     else rel_weight_for order freq / rel_weight_for order k)
blanchet@38939
   329
    * pow_int (!higher_order_irrel_weight) (order - 1)
blanchet@38938
   330
  end
blanchet@37503
   331
blanchet@37503
   332
(* Computes a constant's weight, as determined by its frequency. *)
blanchet@38992
   333
fun generic_pconst_weight abs_weight skolem_weight theory_const_weight
blanchet@38992
   334
                          weight_for f const_tab (c as (s, PType (m, _))) =
blanchet@38816
   335
  if s = abs_name then abs_weight
blanchet@38816
   336
  else if String.isPrefix skolem_prefix s then skolem_weight
blanchet@38992
   337
  else if String.isSuffix theory_const_suffix s then theory_const_weight
blanchet@38939
   338
  else weight_for m (pconst_freq (match_ptype o f) const_tab c)
blanchet@38821
   339
blanchet@38938
   340
fun rel_pconst_weight const_tab =
blanchet@38992
   341
  generic_pconst_weight (!abs_rel_weight) 0.0 (!theory_const_rel_weight)
blanchet@38992
   342
                        rel_weight_for I const_tab
blanchet@38938
   343
fun irrel_pconst_weight const_tab =
blanchet@38938
   344
  generic_pconst_weight (!abs_irrel_weight) (!skolem_irrel_weight)
blanchet@38992
   345
                    (!theory_const_irrel_weight) irrel_weight_for swap const_tab
paulson@24287
   346
blanchet@38889
   347
fun locality_bonus General = 0.0
blanchet@38937
   348
  | locality_bonus Intro = !intro_bonus
blanchet@38937
   349
  | locality_bonus Elim = !elim_bonus
blanchet@38937
   350
  | locality_bonus Simp = !simp_bonus
blanchet@38899
   351
  | locality_bonus Local = !local_bonus
blanchet@38993
   352
  | locality_bonus Assum = !assum_bonus
blanchet@38899
   353
  | locality_bonus Chained = !chained_bonus
blanchet@38751
   354
blanchet@38752
   355
fun axiom_weight loc const_tab relevant_consts axiom_consts =
blanchet@38827
   356
  case axiom_consts |> List.partition (pconst_hyper_mem I relevant_consts)
blanchet@38827
   357
                    ||> filter_out (pconst_hyper_mem swap relevant_consts) of
blanchet@38827
   358
    ([], _) => 0.0
blanchet@38744
   359
  | (rel, irrel) =>
blanchet@38889
   360
    let
blanchet@38889
   361
      val irrel = irrel |> filter_out (pconst_mem swap rel)
blanchet@38938
   362
      val rel_weight =
blanchet@38938
   363
        0.0 |> fold (curry (op +) o rel_pconst_weight const_tab) rel
blanchet@38889
   364
      val irrel_weight =
blanchet@38889
   365
        ~ (locality_bonus loc)
blanchet@38938
   366
        |> fold (curry (op +) o irrel_pconst_weight const_tab) irrel
blanchet@38889
   367
      val res = rel_weight / (rel_weight + irrel_weight)
blanchet@38889
   368
    in if Real.isFinite res then res else 0.0 end
blanchet@38747
   369
blanchet@38904
   370
(* FIXME: experiment
blanchet@38904
   371
fun debug_axiom_weight loc const_tab relevant_consts axiom_consts =
blanchet@38904
   372
  case axiom_consts |> List.partition (pconst_hyper_mem I relevant_consts)
blanchet@38904
   373
                    ||> filter_out (pconst_hyper_mem swap relevant_consts) of
blanchet@38904
   374
    ([], _) => 0.0
blanchet@38904
   375
  | (rel, irrel) =>
blanchet@38904
   376
    let
blanchet@38904
   377
      val irrel = irrel |> filter_out (pconst_mem swap rel)
blanchet@38938
   378
      val rels_weight =
blanchet@38938
   379
        0.0 |> fold (curry (op +) o rel_pconst_weight const_tab) rel
blanchet@38938
   380
      val irrels_weight =
blanchet@38904
   381
        ~ (locality_bonus loc)
blanchet@38938
   382
        |> fold (curry (op +) o irrel_pconst_weight const_tab) irrel
blanchet@38938
   383
val _ = tracing (PolyML.makestring ("REL: ", map (`(rel_pconst_weight const_tab)) rel))
blanchet@38939
   384
val _ = tracing (PolyML.makestring ("IRREL: ", map (`(irrel_pconst_weight const_tab)) irrel))
blanchet@38938
   385
      val res = rels_weight / (rels_weight + irrels_weight)
blanchet@38904
   386
    in if Real.isFinite res then res else 0.0 end
blanchet@38904
   387
*)
blanchet@38904
   388
blanchet@38823
   389
fun pconsts_in_axiom thy t =
blanchet@38825
   390
  Symtab.fold (fn (s, pss) => fold (cons o pair s) pss)
blanchet@38906
   391
              (pconsts_in_terms thy true (SOME true) [t]) []
blanchet@38997
   392
fun pair_consts_axiom thy axiom =
blanchet@38997
   393
  case axiom |> snd |> theory_const_prop_of |> 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
fun take_most_relevant max_relevant remaining_max
blanchet@38747
   401
                       (candidates : (annotated_thm * real) list) =
blanchet@38744
   402
  let
blanchet@38747
   403
    val max_imperfect =
blanchet@38904
   404
      Real.ceil (Math.pow (!max_imperfect,
blanchet@38904
   405
                    Math.pow (Real.fromInt remaining_max
blanchet@38904
   406
                              / Real.fromInt max_relevant, !max_imperfect_exp)))
blanchet@38747
   407
    val (perfect, imperfect) =
blanchet@38889
   408
      candidates |> sort (Real.compare o swap o pairself snd)
blanchet@38889
   409
                 |> take_prefix (fn (_, w) => w > 0.99999)
blanchet@38747
   410
    val ((accepts, more_rejects), rejects) =
blanchet@38747
   411
      chop max_imperfect imperfect |>> append perfect |>> chop remaining_max
blanchet@38744
   412
  in
blanchet@38889
   413
    trace_msg (fn () =>
blanchet@38889
   414
        "Actually passed (" ^ Int.toString (length accepts) ^ " of " ^
blanchet@38889
   415
        Int.toString (length candidates) ^ "): " ^
blanchet@38889
   416
        (accepts |> map (fn ((((name, _), _), _), weight) =>
blanchet@38752
   417
                            name () ^ " [" ^ Real.toString weight ^ "]")
blanchet@38745
   418
                 |> commas));
blanchet@38747
   419
    (accepts, more_rejects @ rejects)
blanchet@38744
   420
  end
paulson@24287
   421
blanchet@38819
   422
fun if_empty_replace_with_locality thy axioms loc tab =
blanchet@38819
   423
  if Symtab.is_empty tab then
blanchet@38906
   424
    pconsts_in_terms thy false (SOME false)
blanchet@38819
   425
        (map_filter (fn ((_, loc'), th) =>
blanchet@38819
   426
                        if loc' = loc then SOME (prop_of th) else NONE) axioms)
blanchet@38819
   427
  else
blanchet@38819
   428
    tab
blanchet@38819
   429
blanchet@38997
   430
fun relevance_filter ctxt threshold0 decay max_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@38997
   434
    val const_tab = fold (count_axiom_consts thy) axioms Symtab.empty
blanchet@38819
   435
    val goal_const_tab =
blanchet@38906
   436
      pconsts_in_terms thy false (SOME false) goal_ts
blanchet@38993
   437
      |> fold (if_empty_replace_with_locality thy axioms)
blanchet@38993
   438
              [Chained, Assum, Local]
blanchet@39012
   439
    val add_ths = Attrib.eval_thms ctxt add
blanchet@39012
   440
    val del_ths = Attrib.eval_thms ctxt del
blanchet@38747
   441
    fun iter j remaining_max threshold rel_const_tab hopeless hopeful =
blanchet@38739
   442
      let
blanchet@38744
   443
        fun game_over rejects =
blanchet@38747
   444
          (* Add "add:" facts. *)
blanchet@39012
   445
          if null add_ths then
blanchet@38747
   446
            []
blanchet@38744
   447
          else
blanchet@38747
   448
            map_filter (fn ((p as (_, th), _), _) =>
blanchet@39012
   449
                           if member Thm.eq_thm add_ths th then SOME p
blanchet@38747
   450
                           else NONE) rejects
blanchet@38889
   451
        fun relevant [] rejects [] =
blanchet@38747
   452
            (* Nothing has been added this iteration. *)
blanchet@38899
   453
            if j = 0 andalso threshold >= !ridiculous_threshold then
blanchet@38747
   454
              (* First iteration? Try again. *)
blanchet@38899
   455
              iter 0 max_relevant (threshold / !threshold_divisor) rel_const_tab
blanchet@38747
   456
                   hopeless hopeful
blanchet@38744
   457
            else
blanchet@38747
   458
              game_over (rejects @ hopeless)
blanchet@38889
   459
          | relevant candidates rejects [] =
blanchet@38739
   460
            let
blanchet@38747
   461
              val (accepts, more_rejects) =
blanchet@38904
   462
                take_most_relevant max_relevant remaining_max candidates
blanchet@38739
   463
              val rel_const_tab' =
blanchet@38745
   464
                rel_const_tab
blanchet@38901
   465
                |> fold (add_pconst_to_table false) (maps (snd o fst) accepts)
blanchet@38744
   466
              fun is_dirty (c, _) =
blanchet@38744
   467
                Symtab.lookup rel_const_tab' c <> Symtab.lookup rel_const_tab c
blanchet@38745
   468
              val (hopeful_rejects, hopeless_rejects) =
blanchet@38745
   469
                 (rejects @ hopeless, ([], []))
blanchet@38745
   470
                 |-> fold (fn (ax as (_, consts), old_weight) =>
blanchet@38745
   471
                              if exists is_dirty consts then
blanchet@38745
   472
                                apfst (cons (ax, NONE))
blanchet@38745
   473
                              else
blanchet@38745
   474
                                apsnd (cons (ax, old_weight)))
blanchet@38745
   475
                 |>> append (more_rejects
blanchet@38745
   476
                             |> map (fn (ax as (_, consts), old_weight) =>
blanchet@38745
   477
                                        (ax, if exists is_dirty consts then NONE
blanchet@38745
   478
                                             else SOME old_weight)))
blanchet@38747
   479
              val threshold =
blanchet@38822
   480
                1.0 - (1.0 - threshold)
blanchet@38822
   481
                      * Math.pow (decay, Real.fromInt (length accepts))
blanchet@38747
   482
              val remaining_max = remaining_max - length accepts
blanchet@38739
   483
            in
blanchet@38744
   484
              trace_msg (fn () => "New or updated constants: " ^
blanchet@38744
   485
                  commas (rel_const_tab' |> Symtab.dest
blanchet@38822
   486
                          |> subtract (op =) (rel_const_tab |> Symtab.dest)
blanchet@38827
   487
                          |> map string_for_hyper_pconst));
blanchet@38745
   488
              map (fst o fst) accepts @
blanchet@38747
   489
              (if remaining_max = 0 then
blanchet@38745
   490
                 game_over (hopeful_rejects @ map (apsnd SOME) hopeless_rejects)
blanchet@38745
   491
               else
blanchet@38747
   492
                 iter (j + 1) remaining_max threshold rel_const_tab'
blanchet@38747
   493
                      hopeless_rejects hopeful_rejects)
blanchet@38739
   494
            end
blanchet@38889
   495
          | relevant candidates rejects
blanchet@39367
   496
                     (((ax as (((_, loc), _), axiom_consts)), cached_weight)
blanchet@38747
   497
                      :: hopeful) =
blanchet@38739
   498
            let
blanchet@38739
   499
              val weight =
blanchet@38739
   500
                case cached_weight of
blanchet@38739
   501
                  SOME w => w
blanchet@38752
   502
                | NONE => axiom_weight loc const_tab rel_const_tab axiom_consts
blanchet@38904
   503
(* FIXME: experiment
blanchet@38752
   504
val name = fst (fst (fst ax)) ()
blanchet@38938
   505
val _ = if String.isSubstring "positive_minus" name orelse String.isSubstring "not_exp_le_zero" name then
blanchet@38901
   506
tracing ("*** " ^ name ^ PolyML.makestring (debug_axiom_weight loc const_tab rel_const_tab axiom_consts))
blanchet@38747
   507
else
blanchet@38747
   508
()
blanchet@38747
   509
*)
blanchet@38739
   510
            in
blanchet@38741
   511
              if weight >= threshold then
blanchet@38889
   512
                relevant ((ax, weight) :: candidates) rejects hopeful
blanchet@38739
   513
              else
blanchet@38889
   514
                relevant candidates ((ax, weight) :: rejects) hopeful
blanchet@38739
   515
            end
blanchet@38739
   516
        in
blanchet@38744
   517
          trace_msg (fn () =>
blanchet@38744
   518
              "ITERATION " ^ string_of_int j ^ ": current threshold: " ^
blanchet@38744
   519
              Real.toString threshold ^ ", constants: " ^
blanchet@38744
   520
              commas (rel_const_tab |> Symtab.dest
blanchet@38744
   521
                      |> filter (curry (op <>) [] o snd)
blanchet@38827
   522
                      |> map string_for_hyper_pconst));
blanchet@38889
   523
          relevant [] [] hopeful
blanchet@38739
   524
        end
blanchet@38739
   525
  in
blanchet@39012
   526
    axioms |> filter_out (member Thm.eq_thm del_ths o snd)
blanchet@38997
   527
           |> map_filter (pair_consts_axiom thy)
blanchet@38819
   528
           |> iter 0 max_relevant threshold0 goal_const_tab []
blanchet@38739
   529
           |> tap (fn res => trace_msg (fn () =>
blanchet@38686
   530
                                "Total relevant: " ^ Int.toString (length res)))
blanchet@38739
   531
  end
paulson@24287
   532
blanchet@38744
   533
paulson@24287
   534
(***************************************************************)
mengj@19768
   535
(* Retrieving and filtering lemmas                             *)
mengj@19768
   536
(***************************************************************)
mengj@19768
   537
paulson@33022
   538
(*** retrieve lemmas and filter them ***)
mengj@19768
   539
paulson@20757
   540
(*Reject theorems with names like "List.filter.filter_list_def" or
paulson@21690
   541
  "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
paulson@20757
   542
fun is_package_def a =
wenzelm@30364
   543
  let val names = Long_Name.explode a
paulson@21690
   544
  in
paulson@21690
   545
     length names > 2 andalso
paulson@21690
   546
     not (hd names = "local") andalso
paulson@21690
   547
     String.isSuffix "_def" a  orelse  String.isSuffix "_defs" a
paulson@21690
   548
  end;
paulson@20757
   549
blanchet@38937
   550
fun mk_fact_table f xs =
blanchet@38937
   551
  fold (Termtab.update o `(prop_of o f)) xs Termtab.empty
blanchet@38937
   552
fun uniquify xs = Termtab.fold (cons o snd) (mk_fact_table snd xs) []
mengj@19768
   553
blanchet@37626
   554
(* FIXME: put other record thms here, or declare as "no_atp" *)
blanchet@37626
   555
val multi_base_blacklist =
blanchet@37626
   556
  ["defs", "select_defs", "update_defs", "induct", "inducts", "split", "splits",
blanchet@38682
   557
   "split_asm", "cases", "ext_cases", "eq.simps", "eq.refl", "nchotomy",
blanchet@38682
   558
   "case_cong", "weak_case_cong"]
blanchet@38682
   559
  |> map (prefix ".")
blanchet@37626
   560
blanchet@37626
   561
val max_lambda_nesting = 3
blanchet@37626
   562
blanchet@37626
   563
fun term_has_too_many_lambdas max (t1 $ t2) =
blanchet@37626
   564
    exists (term_has_too_many_lambdas max) [t1, t2]
blanchet@37626
   565
  | term_has_too_many_lambdas max (Abs (_, _, t)) =
blanchet@37626
   566
    max = 0 orelse term_has_too_many_lambdas (max - 1) t
blanchet@37626
   567
  | term_has_too_many_lambdas _ _ = false
blanchet@37626
   568
blanchet@37626
   569
(* Don't count nested lambdas at the level of formulas, since they are
blanchet@37626
   570
   quantifiers. *)
blanchet@37626
   571
fun formula_has_too_many_lambdas Ts (Abs (_, T, t)) =
blanchet@37626
   572
    formula_has_too_many_lambdas (T :: Ts) t
blanchet@37626
   573
  | formula_has_too_many_lambdas Ts t =
blanchet@37626
   574
    if is_formula_type (fastype_of1 (Ts, t)) then
blanchet@37626
   575
      exists (formula_has_too_many_lambdas Ts) (#2 (strip_comb t))
blanchet@37626
   576
    else
blanchet@37626
   577
      term_has_too_many_lambdas max_lambda_nesting t
blanchet@37626
   578
blanchet@38692
   579
(* The max apply depth of any "metis" call in "Metis_Examples" (on 2007-10-31)
blanchet@37626
   580
   was 11. *)
blanchet@37626
   581
val max_apply_depth = 15
blanchet@37626
   582
blanchet@37626
   583
fun apply_depth (f $ t) = Int.max (apply_depth f, apply_depth t + 1)
blanchet@37626
   584
  | apply_depth (Abs (_, _, t)) = apply_depth t
blanchet@37626
   585
  | apply_depth _ = 0
blanchet@37626
   586
blanchet@37626
   587
fun is_formula_too_complex t =
blanchet@38085
   588
  apply_depth t > max_apply_depth orelse formula_has_too_many_lambdas [] t
blanchet@37626
   589
blanchet@39946
   590
(* FIXME: Extend to "Meson" and "Metis" *)
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@39265
   691
fun all_prefixes_of s =
blanchet@39265
   692
  map (fn i => String.extract (s, 0, SOME i)) (1 upto size s - 1)
blanchet@39265
   693
blanchet@39265
   694
(* This is a terrible hack. Free variables are sometimes code as "M__" when they
blanchet@39265
   695
   are displayed as "M" and we want to avoid clashes with these. But sometimes
blanchet@39265
   696
   it's even worse: "Ma__" encodes "M". So we simply reserve all prefixes of all
blanchet@39265
   697
   free variables. In the worse case scenario, where the fact won't be resolved
blanchet@39265
   698
   correctly, the user can fix it manually, e.g., by naming the fact in
blanchet@39265
   699
   question. Ideally we would need nothing of it, but backticks just don't work
blanchet@39265
   700
   with schematic variables. *)
blanchet@39265
   701
fun close_form t =
blanchet@39265
   702
  (t, [] |> Term.add_free_names t |> maps all_prefixes_of)
blanchet@39265
   703
  |> fold (fn ((s, i), T) => fn (t', taken) =>
blanchet@39265
   704
              let val s' = Name.variant taken s in
blanchet@39265
   705
                (Term.all T $ Abs (s', T, abstract_over (Var ((s, i), T), t')),
blanchet@39265
   706
                 s' :: taken)
blanchet@39265
   707
              end)
blanchet@39265
   708
          (Term.add_vars t [] |> sort_wrt (fst o fst))
blanchet@39265
   709
  |> fst
blanchet@39265
   710
blanchet@39012
   711
fun all_name_thms_pairs ctxt reserved full_types add_ths chained_ths =
blanchet@38627
   712
  let
blanchet@38752
   713
    val thy = ProofContext.theory_of ctxt
wenzelm@39557
   714
    val global_facts = Global_Theory.facts_of thy
blanchet@38644
   715
    val local_facts = ProofContext.facts_of ctxt
blanchet@38644
   716
    val named_locals = local_facts |> Facts.dest_static []
blanchet@38993
   717
    val assms = Assumption.all_assms_of ctxt
blanchet@38993
   718
    fun is_assum th = exists (fn ct => prop_of th aconv term_of ct) assms
blanchet@38752
   719
    val is_chained = member Thm.eq_thm chained_ths
blanchet@38937
   720
    val (intros, elims, simps) =
blanchet@38937
   721
      if exists (curry (op <) 0.0) [!intro_bonus, !elim_bonus, !simp_bonus] then
blanchet@38937
   722
        clasimpset_rules_of ctxt
blanchet@38937
   723
      else
blanchet@38937
   724
        (Termtab.empty, Termtab.empty, Termtab.empty)
blanchet@38738
   725
    fun is_good_unnamed_local th =
blanchet@38820
   726
      not (Thm.has_name_hint th) andalso
blanchet@38738
   727
      forall (fn (_, ths) => not (member Thm.eq_thm ths th)) named_locals
blanchet@38644
   728
    val unnamed_locals =
blanchet@38820
   729
      union Thm.eq_thm (Facts.props local_facts) chained_ths
blanchet@38820
   730
      |> filter is_good_unnamed_local |> map (pair "" o single)
blanchet@38627
   731
    val full_space =
blanchet@38738
   732
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts)
blanchet@38752
   733
    fun add_facts global foldx facts =
blanchet@38699
   734
      foldx (fn (name0, ths) =>
blanchet@38699
   735
        if name0 <> "" andalso
blanchet@39012
   736
           forall (not o member Thm.eq_thm add_ths) ths andalso
blanchet@38699
   737
           (Facts.is_concealed facts name0 orelse
blanchet@38699
   738
            (respect_no_atp andalso is_package_def name0) orelse
blanchet@38699
   739
            exists (fn s => String.isSuffix s name0) multi_base_blacklist orelse
blanchet@38699
   740
            String.isSuffix "_def_raw" (* FIXME: crude hack *) name0) then
blanchet@38627
   741
          I
blanchet@38627
   742
        else
blanchet@38627
   743
          let
blanchet@38699
   744
            val multi = length ths > 1
blanchet@38696
   745
            fun backquotify th =
blanchet@39718
   746
              "`" ^ Print_Mode.setmp (filter (curry (op =) Symbol.xsymbolsN)
blanchet@39265
   747
                                             (print_mode_value ()))
blanchet@39265
   748
                   (Syntax.string_of_term ctxt) (close_form (prop_of th)) ^ "`"
blanchet@38738
   749
              |> String.translate (fn c => if Char.isPrint c then str c else "")
blanchet@38738
   750
              |> simplify_spaces
blanchet@38699
   751
            fun check_thms a =
blanchet@38699
   752
              case try (ProofContext.get_thms ctxt) a of
blanchet@38699
   753
                NONE => false
blanchet@38699
   754
              | SOME ths' => Thm.eq_thms (ths, ths')
blanchet@38627
   755
          in
blanchet@38699
   756
            pair 1
blanchet@38699
   757
            #> fold (fn th => fn (j, rest) =>
blanchet@38699
   758
                 (j + 1,
blanchet@38699
   759
                  if is_theorem_bad_for_atps full_types th andalso
blanchet@39012
   760
                     not (member Thm.eq_thm add_ths th) then
blanchet@38699
   761
                    rest
blanchet@38699
   762
                  else
blanchet@38752
   763
                    (((fn () =>
blanchet@38752
   764
                          if name0 = "" then
blanchet@38752
   765
                            th |> backquotify
blanchet@38752
   766
                          else
blanchet@38752
   767
                            let
blanchet@38752
   768
                              val name1 = Facts.extern facts name0
blanchet@38752
   769
                              val name2 = Name_Space.extern full_space name0
blanchet@38752
   770
                            in
blanchet@38752
   771
                              case find_first check_thms [name1, name2, name0] of
blanchet@38752
   772
                                SOME name => repair_name reserved multi j name
blanchet@38752
   773
                              | NONE => ""
blanchet@38937
   774
                            end),
blanchet@38937
   775
                      let val t = prop_of th in
blanchet@38937
   776
                        if is_chained th then Chained
blanchet@38993
   777
                        else if global then
blanchet@38993
   778
                          if Termtab.defined intros t then Intro
blanchet@38993
   779
                          else if Termtab.defined elims t then Elim
blanchet@38993
   780
                          else if Termtab.defined simps t then Simp
blanchet@38993
   781
                          else General
blanchet@38993
   782
                        else
blanchet@38993
   783
                          if is_assum th then Assum else Local
blanchet@38937
   784
                      end),
blanchet@38752
   785
                      (multi, th)) :: rest)) ths
blanchet@38699
   786
            #> snd
blanchet@38627
   787
          end)
blanchet@38644
   788
  in
blanchet@38752
   789
    [] |> add_facts false fold local_facts (unnamed_locals @ named_locals)
blanchet@38752
   790
       |> add_facts true Facts.fold_static global_facts global_facts
blanchet@38644
   791
  end
blanchet@38627
   792
blanchet@38627
   793
(* The single-name theorems go after the multiple-name ones, so that single
blanchet@38627
   794
   names are preferred when both are available. *)
blanchet@38699
   795
fun name_thm_pairs ctxt respect_no_atp =
blanchet@38744
   796
  List.partition (fst o snd) #> op @ #> map (apsnd snd)
blanchet@38699
   797
  #> respect_no_atp ? filter_out (No_ATPs.member ctxt o snd)
blanchet@38627
   798
blanchet@38627
   799
(***************************************************************)
blanchet@38627
   800
(* ATP invocation methods setup                                *)
blanchet@38627
   801
(***************************************************************)
blanchet@38627
   802
blanchet@38891
   803
fun relevant_facts ctxt full_types (threshold0, threshold1) max_relevant
blanchet@39367
   804
                   (relevance_override as {add, only, ...}) chained_ths hyp_ts
blanchet@38997
   805
                   concl_t =
blanchet@37538
   806
  let
blanchet@38822
   807
    val decay = Math.pow ((1.0 - threshold1) / (1.0 - threshold0),
blanchet@38822
   808
                          1.0 / Real.fromInt (max_relevant + 1))
blanchet@39012
   809
    val add_ths = Attrib.eval_thms ctxt add
blanchet@38696
   810
    val reserved = reserved_isar_keyword_table ()
blanchet@37538
   811
    val axioms =
blanchet@38699
   812
      (if only then
blanchet@38752
   813
         maps (map (fn ((name, loc), th) => ((K name, loc), (true, th)))
blanchet@38752
   814
               o name_thm_pairs_from_ref ctxt reserved chained_ths) add
blanchet@38699
   815
       else
blanchet@39012
   816
         all_name_thms_pairs ctxt reserved full_types add_ths chained_ths)
blanchet@38688
   817
      |> name_thm_pairs ctxt (respect_no_atp andalso not only)
blanchet@38937
   818
      |> uniquify
blanchet@37538
   819
  in
blanchet@38688
   820
    trace_msg (fn () => "Considering " ^ Int.toString (length axioms) ^
blanchet@38688
   821
                        " theorems");
blanchet@39366
   822
    (if only orelse threshold1 < 0.0 then
blanchet@39366
   823
       axioms
blanchet@39366
   824
     else if threshold0 > 1.0 orelse threshold0 > threshold1 orelse
blanchet@39366
   825
             max_relevant = 0 then
blanchet@38739
   826
       []
blanchet@38739
   827
     else
blanchet@38997
   828
       relevance_filter ctxt threshold0 decay max_relevant relevance_override
blanchet@38997
   829
                        axioms (concl_t :: hyp_ts))
blanchet@38822
   830
    |> map (apfst (apfst (fn f => f ())))
blanchet@37538
   831
  end
immler@30536
   832
paulson@15347
   833
end;