src/HOL/Tools/Sledgehammer/sledgehammer_filter.ML
author blanchet
Mon May 02 22:52:15 2011 +0200 (2011-05-02 ago)
changeset 42641 2cd4e6463842
parent 42638 a7a30721767a
child 42646 4781fcd53572
permissions -rw-r--r--
recognize simplification rules even if they look a bit different from the theorems in the theories (meta equality, variable numbers)
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@40070
    12
  type relevance_fudge =
blanchet@41159
    13
    {allow_ext : bool,
blanchet@41790
    14
     local_const_multiplier : real,
blanchet@41159
    15
     worse_irrel_freq : real,
blanchet@40070
    16
     higher_order_irrel_weight : real,
blanchet@40070
    17
     abs_rel_weight : real,
blanchet@40070
    18
     abs_irrel_weight : real,
blanchet@40070
    19
     skolem_irrel_weight : real,
blanchet@40070
    20
     theory_const_rel_weight : real,
blanchet@40070
    21
     theory_const_irrel_weight : real,
blanchet@40070
    22
     intro_bonus : real,
blanchet@40070
    23
     elim_bonus : real,
blanchet@40070
    24
     simp_bonus : real,
blanchet@40070
    25
     local_bonus : real,
blanchet@40070
    26
     assum_bonus : real,
blanchet@40070
    27
     chained_bonus : real,
blanchet@40070
    28
     max_imperfect : real,
blanchet@40070
    29
     max_imperfect_exp : real,
blanchet@40070
    30
     threshold_divisor : real,
blanchet@40070
    31
     ridiculous_threshold : real}
blanchet@40070
    32
blanchet@35966
    33
  type relevance_override =
blanchet@40070
    34
    {add : (Facts.ref * Attrib.src list) list,
blanchet@40070
    35
     del : (Facts.ref * Attrib.src list) list,
blanchet@40070
    36
     only : bool}
blanchet@35966
    37
blanchet@37616
    38
  val trace : bool Unsynchronized.ref
blanchet@42449
    39
  val is_global_locality : locality -> bool
blanchet@40205
    40
  val fact_from_ref :
blanchet@38996
    41
    Proof.context -> unit Symtab.table -> thm list
blanchet@38996
    42
    -> Facts.ref * Attrib.src list -> ((string * locality) * thm) list
blanchet@41767
    43
  val all_facts :
blanchet@42641
    44
    Proof.context -> 'a Symtab.table -> bool -> thm list -> thm list
blanchet@42641
    45
    -> (((unit -> string) * locality) * (bool * thm)) list
blanchet@41768
    46
  val const_names_in_fact :
blanchet@41768
    47
    theory -> (string * typ -> term list -> bool * term list) -> term
blanchet@41768
    48
    -> string list
blanchet@42638
    49
  val is_dangerous_term : term -> bool
blanchet@37347
    50
  val relevant_facts :
blanchet@42638
    51
    Proof.context -> real * real -> int
blanchet@41336
    52
    -> (string * typ -> term list -> bool * term list) -> relevance_fudge
blanchet@41066
    53
    -> relevance_override -> thm list -> term list -> term
blanchet@40070
    54
    -> ((string * locality) * thm) list
paulson@15347
    55
end;
paulson@15347
    56
blanchet@38988
    57
structure Sledgehammer_Filter : SLEDGEHAMMER_FILTER =
paulson@15347
    58
struct
paulson@15347
    59
blanchet@38652
    60
open Sledgehammer_Util
blanchet@38652
    61
blanchet@37616
    62
val trace = Unsynchronized.ref false
blanchet@37616
    63
fun trace_msg msg = if !trace then tracing (msg ()) else ()
blanchet@35826
    64
blanchet@41273
    65
(* experimental features *)
blanchet@38997
    66
val respect_no_atp = true
blanchet@41273
    67
val instantiate_inducts = false
blanchet@38827
    68
blanchet@38993
    69
datatype locality = General | Intro | Elim | Simp | Local | Assum | Chained
blanchet@38752
    70
blanchet@42449
    71
(* (quasi-)underapproximation of the truth *)
blanchet@42449
    72
fun is_global_locality Local = false
blanchet@42449
    73
  | is_global_locality Assum = false
blanchet@42449
    74
  | is_global_locality Chained = false
blanchet@42449
    75
  | is_global_locality _ = true
blanchet@42449
    76
blanchet@40070
    77
type relevance_fudge =
blanchet@41159
    78
  {allow_ext : bool,
blanchet@41790
    79
   local_const_multiplier : real,
blanchet@41159
    80
   worse_irrel_freq : real,
blanchet@40070
    81
   higher_order_irrel_weight : real,
blanchet@40070
    82
   abs_rel_weight : real,
blanchet@40070
    83
   abs_irrel_weight : real,
blanchet@40070
    84
   skolem_irrel_weight : real,
blanchet@40070
    85
   theory_const_rel_weight : real,
blanchet@40070
    86
   theory_const_irrel_weight : real,
blanchet@40070
    87
   intro_bonus : real,
blanchet@40070
    88
   elim_bonus : real,
blanchet@40070
    89
   simp_bonus : real,
blanchet@40070
    90
   local_bonus : real,
blanchet@40070
    91
   assum_bonus : real,
blanchet@40070
    92
   chained_bonus : real,
blanchet@40070
    93
   max_imperfect : real,
blanchet@40070
    94
   max_imperfect_exp : real,
blanchet@40070
    95
   threshold_divisor : real,
blanchet@40070
    96
   ridiculous_threshold : real}
blanchet@40070
    97
blanchet@35966
    98
type relevance_override =
blanchet@40070
    99
  {add : (Facts.ref * Attrib.src list) list,
blanchet@40070
   100
   del : (Facts.ref * Attrib.src list) list,
blanchet@40070
   101
   only : bool}
paulson@21070
   102
blanchet@37616
   103
val sledgehammer_prefix = "Sledgehammer" ^ Long_Name.separator
blanchet@39896
   104
val abs_name = sledgehammer_prefix ^ "abs"
blanchet@39896
   105
val skolem_prefix = sledgehammer_prefix ^ "sko"
blanchet@38992
   106
val theory_const_suffix = Long_Name.separator ^ " 1"
blanchet@37616
   107
blanchet@40227
   108
fun needs_quoting reserved s =
blanchet@40375
   109
  Symtab.defined reserved s orelse
wenzelm@42290
   110
  exists (not o Lexicon.is_identifier) (Long_Name.explode s)
blanchet@40227
   111
blanchet@40375
   112
fun make_name reserved multi j name =
blanchet@40227
   113
  (name |> needs_quoting reserved name ? quote) ^
wenzelm@41491
   114
  (if multi then "(" ^ string_of_int j ^ ")" else "")
blanchet@38744
   115
blanchet@40375
   116
fun explode_interval _ (Facts.FromTo (i, j)) = i upto j
blanchet@40375
   117
  | explode_interval max (Facts.From i) = i upto i + max - 1
blanchet@40375
   118
  | explode_interval _ (Facts.Single i) = [i]
blanchet@40375
   119
blanchet@41279
   120
val backquote =
blanchet@41279
   121
  raw_explode #> map (fn "`" => "\\`" | s => s) #> implode #> enclose "`" "`"
blanchet@40205
   122
fun fact_from_ref ctxt reserved chained_ths (xthm as (xref, args)) =
blanchet@38744
   123
  let
blanchet@38996
   124
    val ths = Attrib.eval_thms ctxt [xthm]
blanchet@38996
   125
    val bracket =
blanchet@41999
   126
      map (enclose "[" "]" o Pretty.str_of o Args.pretty_src ctxt) args
blanchet@41999
   127
      |> implode
blanchet@40375
   128
    fun nth_name j =
blanchet@38996
   129
      case xref of
blanchet@41279
   130
        Facts.Fact s => backquote s ^ bracket
blanchet@38996
   131
      | Facts.Named (("", _), _) => "[" ^ bracket ^ "]"
blanchet@40375
   132
      | Facts.Named ((name, _), NONE) =>
blanchet@40375
   133
        make_name reserved (length ths > 1) (j + 1) name ^ bracket
blanchet@40375
   134
      | Facts.Named ((name, _), SOME intervals) =>
blanchet@40375
   135
        make_name reserved true
blanchet@40375
   136
                 (nth (maps (explode_interval (length ths)) intervals) j) name ^
blanchet@40375
   137
        bracket
blanchet@38744
   138
  in
blanchet@40375
   139
    (ths, (0, []))
blanchet@38752
   140
    |-> fold (fn th => fn (j, rest) =>
blanchet@40375
   141
                 (j + 1, ((nth_name j,
blanchet@38752
   142
                          if member Thm.eq_thm chained_ths th then Chained
blanchet@38752
   143
                          else General), th) :: rest))
blanchet@38744
   144
    |> snd
blanchet@38699
   145
  end
blanchet@37616
   146
blanchet@41199
   147
(* This is a terrible hack. Free variables are sometimes code as "M__" when they
blanchet@41199
   148
   are displayed as "M" and we want to avoid clashes with these. But sometimes
blanchet@41199
   149
   it's even worse: "Ma__" encodes "M". So we simply reserve all prefixes of all
blanchet@41199
   150
   free variables. In the worse case scenario, where the fact won't be resolved
blanchet@41199
   151
   correctly, the user can fix it manually, e.g., by naming the fact in
blanchet@41199
   152
   question. Ideally we would need nothing of it, but backticks just don't work
blanchet@41199
   153
   with schematic variables. *)
blanchet@41199
   154
fun all_prefixes_of s =
blanchet@41199
   155
  map (fn i => String.extract (s, 0, SOME i)) (1 upto size s - 1)
blanchet@41199
   156
fun close_form t =
blanchet@41199
   157
  (t, [] |> Term.add_free_names t |> maps all_prefixes_of)
blanchet@41199
   158
  |> fold (fn ((s, i), T) => fn (t', taken) =>
blanchet@41199
   159
              let val s' = Name.variant taken s in
blanchet@41199
   160
                ((if fastype_of t' = HOLogic.boolT then HOLogic.all_const
blanchet@41199
   161
                  else Term.all) T
blanchet@41199
   162
                 $ Abs (s', T, abstract_over (Var ((s, i), T), t')),
blanchet@41199
   163
                 s' :: taken)
blanchet@41199
   164
              end)
blanchet@41199
   165
          (Term.add_vars t [] |> sort_wrt (fst o fst))
blanchet@41199
   166
  |> fst
blanchet@41199
   167
blanchet@41199
   168
fun string_for_term ctxt t =
blanchet@41199
   169
  Print_Mode.setmp (filter (curry (op =) Symbol.xsymbolsN)
blanchet@41199
   170
                   (print_mode_value ())) (Syntax.string_of_term ctxt) t
blanchet@41199
   171
  |> String.translate (fn c => if Char.isPrint c then str c else "")
blanchet@41199
   172
  |> simplify_spaces
blanchet@41199
   173
blanchet@41199
   174
(** Structural induction rules **)
blanchet@41199
   175
blanchet@41200
   176
fun struct_induct_rule_on th =
blanchet@41199
   177
  case Logic.strip_horn (prop_of th) of
blanchet@41199
   178
    (prems, @{const Trueprop}
blanchet@41199
   179
            $ ((p as Var ((p_name, 0), _)) $ (a as Var (_, ind_T)))) =>
blanchet@41199
   180
    if not (is_TVar ind_T) andalso length prems > 1 andalso
blanchet@41199
   181
       exists (exists_subterm (curry (op aconv) p)) prems andalso
blanchet@41199
   182
       not (exists (exists_subterm (curry (op aconv) a)) prems) then
blanchet@41199
   183
      SOME (p_name, ind_T)
blanchet@41199
   184
    else
blanchet@41199
   185
      NONE
blanchet@41199
   186
  | _ => NONE
blanchet@41199
   187
blanchet@41207
   188
fun instantiate_induct_rule ctxt concl_prop p_name ((name, loc), (multi, th))
blanchet@41199
   189
                            ind_x =
blanchet@41199
   190
  let
blanchet@41199
   191
    fun varify_noninducts (t as Free (s, T)) =
blanchet@41199
   192
        if (s, T) = ind_x orelse can dest_funT T then t else Var ((s, 0), T)
blanchet@41199
   193
      | varify_noninducts t = t
blanchet@41199
   194
    val p_inst =
blanchet@41199
   195
      concl_prop |> map_aterms varify_noninducts |> close_form
blanchet@41199
   196
                 |> lambda (Free ind_x)
blanchet@41199
   197
                 |> string_for_term ctxt
blanchet@41199
   198
  in
blanchet@41207
   199
    ((fn () => name () ^ "[where " ^ p_name ^ " = " ^ quote p_inst ^ "]", loc),
blanchet@41199
   200
     (multi, th |> read_instantiate ctxt [((p_name, 0), p_inst)]))
blanchet@41199
   201
  end
blanchet@41199
   202
blanchet@41199
   203
fun type_match thy (T1, T2) =
blanchet@41199
   204
  (Sign.typ_match thy (T2, T1) Vartab.empty; true)
blanchet@41199
   205
  handle Type.TYPE_MATCH => false
blanchet@41199
   206
blanchet@41199
   207
fun instantiate_if_induct_rule ctxt stmt stmt_xs (ax as (_, (_, th))) =
blanchet@41200
   208
  case struct_induct_rule_on th of
blanchet@41199
   209
    SOME (p_name, ind_T) =>
wenzelm@42361
   210
    let val thy = Proof_Context.theory_of ctxt in
blanchet@41199
   211
      stmt_xs |> filter (fn (_, T) => type_match thy (T, ind_T))
blanchet@41199
   212
              |> map_filter (try (instantiate_induct_rule ctxt stmt p_name ax))
blanchet@41199
   213
    end
blanchet@41199
   214
  | NONE => [ax]
blanchet@41199
   215
wenzelm@28477
   216
(***************************************************************)
wenzelm@28477
   217
(* Relevance Filtering                                         *)
wenzelm@28477
   218
(***************************************************************)
mengj@19194
   219
paulson@24287
   220
(*** constants with types ***)
paulson@24287
   221
blanchet@38939
   222
fun order_of_type (Type (@{type_name fun}, [T1, @{typ bool}])) =
blanchet@38939
   223
    order_of_type T1 (* cheat: pretend sets are first-order *)
blanchet@38939
   224
  | order_of_type (Type (@{type_name fun}, [T1, T2])) =
blanchet@38939
   225
    Int.max (order_of_type T1 + 1, order_of_type T2)
blanchet@38939
   226
  | order_of_type (Type (_, Ts)) = fold (Integer.max o order_of_type) Ts 0
blanchet@38939
   227
  | order_of_type _ = 0
blanchet@38939
   228
blanchet@38823
   229
(* An abstraction of Isabelle types and first-order terms *)
blanchet@38823
   230
datatype pattern = PVar | PApp of string * pattern list
blanchet@38939
   231
datatype ptype = PType of int * pattern list
blanchet@38744
   232
blanchet@38823
   233
fun string_for_pattern PVar = "_"
blanchet@38823
   234
  | string_for_pattern (PApp (s, ps)) =
blanchet@38823
   235
    if null ps then s else s ^ string_for_patterns ps
blanchet@38823
   236
and string_for_patterns ps = "(" ^ commas (map string_for_pattern ps) ^ ")"
blanchet@38939
   237
fun string_for_ptype (PType (_, ps)) = string_for_patterns ps
paulson@24287
   238
paulson@24287
   239
(*Is the second type an instance of the first one?*)
blanchet@38824
   240
fun match_pattern (PVar, _) = true
blanchet@38824
   241
  | match_pattern (PApp _, PVar) = false
blanchet@38824
   242
  | match_pattern (PApp (s, ps), PApp (t, qs)) =
blanchet@38824
   243
    s = t andalso match_patterns (ps, qs)
blanchet@38824
   244
and match_patterns (_, []) = true
blanchet@38824
   245
  | match_patterns ([], _) = false
blanchet@38824
   246
  | match_patterns (p :: ps, q :: qs) =
blanchet@38824
   247
    match_pattern (p, q) andalso match_patterns (ps, qs)
blanchet@38939
   248
fun match_ptype (PType (_, ps), PType (_, qs)) = match_patterns (ps, qs)
paulson@24287
   249
blanchet@38823
   250
(* Is there a unifiable constant? *)
blanchet@38827
   251
fun pconst_mem f consts (s, ps) =
blanchet@38939
   252
  exists (curry (match_ptype o f) ps)
blanchet@38827
   253
         (map snd (filter (curry (op =) s o fst) consts))
blanchet@38827
   254
fun pconst_hyper_mem f const_tab (s, ps) =
blanchet@38939
   255
  exists (curry (match_ptype o f) ps) (these (Symtab.lookup const_tab s))
blanchet@37505
   256
blanchet@38939
   257
fun pattern_for_type (Type (s, Ts)) = PApp (s, map pattern_for_type Ts)
blanchet@38939
   258
  | pattern_for_type (TFree (s, _)) = PApp (s, [])
blanchet@38939
   259
  | pattern_for_type (TVar _) = PVar
blanchet@38827
   260
blanchet@38744
   261
(* Pairs a constant with the list of its type instantiations. *)
blanchet@41204
   262
fun ptype thy const x =
blanchet@38939
   263
  (if const then map pattern_for_type (these (try (Sign.const_typargs thy) x))
blanchet@41204
   264
   else [])
blanchet@41204
   265
fun rich_ptype thy const (s, T) =
blanchet@41204
   266
  PType (order_of_type T, ptype thy const (s, T))
blanchet@41204
   267
fun rich_pconst thy const (s, T) = (s, rich_ptype thy const (s, T))
paulson@24287
   268
blanchet@38939
   269
fun string_for_hyper_pconst (s, ps) =
blanchet@38939
   270
  s ^ "{" ^ commas (map string_for_ptype ps) ^ "}"
paulson@24287
   271
blanchet@38823
   272
(* Add a pconstant to the table, but a [] entry means a standard
blanchet@38819
   273
   connective, which we ignore.*)
blanchet@41066
   274
fun add_pconst_to_table also_skolem (s, p) =
blanchet@41066
   275
  if (not also_skolem andalso String.isPrefix skolem_prefix s) then I
blanchet@41066
   276
  else Symtab.map_default (s, [p]) (insert (op =) p)
blanchet@38819
   277
blanchet@40369
   278
fun pconsts_in_terms thy is_built_in_const also_skolems pos ts =
blanchet@37505
   279
  let
blanchet@38819
   280
    val flip = Option.map not
blanchet@38587
   281
    (* We include free variables, as well as constants, to handle locales. For
blanchet@41205
   282
       each quantifiers that must necessarily be skolemized by the automatic
blanchet@41205
   283
       prover, we introduce a fresh constant to simulate the effect of
blanchet@41205
   284
       Skolemization. *)
blanchet@40373
   285
    fun do_const const x ts =
blanchet@41336
   286
      let val (built_in, ts) = is_built_in_const x ts in
blanchet@41336
   287
        (not built_in
blanchet@41336
   288
         ? add_pconst_to_table also_skolems (rich_pconst thy const x))
blanchet@41336
   289
        #> fold do_term ts
blanchet@41336
   290
      end
blanchet@38827
   291
    and do_term t =
blanchet@38827
   292
      case strip_comb t of
blanchet@38827
   293
        (Const x, ts) => do_const true x ts
blanchet@38827
   294
      | (Free x, ts) => do_const false x ts
blanchet@38939
   295
      | (Abs (_, T, t'), ts) =>
blanchet@38939
   296
        (null ts
blanchet@41066
   297
         ? add_pconst_to_table true (abs_name, PType (order_of_type T + 1, [])))
blanchet@38827
   298
        #> fold do_term (t' :: ts)
blanchet@38827
   299
      | (_, ts) => fold do_term ts
blanchet@38939
   300
    fun do_quantifier will_surely_be_skolemized abs_T body_t =
blanchet@37537
   301
      do_formula pos body_t
blanchet@38747
   302
      #> (if also_skolems andalso will_surely_be_skolemized then
blanchet@41066
   303
            add_pconst_to_table true
blanchet@41207
   304
                (gensym skolem_prefix, PType (order_of_type abs_T, []))
blanchet@38587
   305
          else
blanchet@38587
   306
            I)
blanchet@38587
   307
    and do_term_or_formula T =
blanchet@41273
   308
      if T = HOLogic.boolT then do_formula NONE else do_term
blanchet@37537
   309
    and do_formula pos t =
blanchet@37537
   310
      case t of
blanchet@38939
   311
        Const (@{const_name all}, _) $ Abs (_, T, t') =>
blanchet@38939
   312
        do_quantifier (pos = SOME false) T t'
blanchet@37537
   313
      | @{const "==>"} $ t1 $ t2 =>
blanchet@37537
   314
        do_formula (flip pos) t1 #> do_formula pos t2
blanchet@37537
   315
      | Const (@{const_name "=="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38587
   316
        fold (do_term_or_formula T) [t1, t2]
blanchet@37537
   317
      | @{const Trueprop} $ t1 => do_formula pos t1
blanchet@41140
   318
      | @{const False} => I
blanchet@41140
   319
      | @{const True} => I
blanchet@37537
   320
      | @{const Not} $ t1 => do_formula (flip pos) t1
blanchet@38939
   321
      | Const (@{const_name All}, _) $ Abs (_, T, t') =>
blanchet@38939
   322
        do_quantifier (pos = SOME false) T t'
blanchet@38939
   323
      | Const (@{const_name Ex}, _) $ Abs (_, T, t') =>
blanchet@38939
   324
        do_quantifier (pos = SOME true) T t'
haftmann@38795
   325
      | @{const HOL.conj} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
haftmann@38795
   326
      | @{const HOL.disj} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
haftmann@38786
   327
      | @{const HOL.implies} $ t1 $ t2 =>
blanchet@37537
   328
        do_formula (flip pos) t1 #> do_formula pos t2
haftmann@38864
   329
      | Const (@{const_name HOL.eq}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38587
   330
        fold (do_term_or_formula T) [t1, t2]
blanchet@38587
   331
      | Const (@{const_name If}, Type (_, [_, Type (_, [T, _])]))
blanchet@38587
   332
        $ t1 $ t2 $ t3 =>
blanchet@38587
   333
        do_formula NONE t1 #> fold (do_term_or_formula T) [t2, t3]
blanchet@38939
   334
      | Const (@{const_name Ex1}, _) $ Abs (_, T, t') =>
blanchet@38939
   335
        do_quantifier (is_some pos) T t'
blanchet@38939
   336
      | Const (@{const_name Ball}, _) $ t1 $ Abs (_, T, t') =>
blanchet@38939
   337
        do_quantifier (pos = SOME false) T
blanchet@38939
   338
                      (HOLogic.mk_imp (incr_boundvars 1 t1 $ Bound 0, t'))
blanchet@38939
   339
      | Const (@{const_name Bex}, _) $ t1 $ Abs (_, T, t') =>
blanchet@38939
   340
        do_quantifier (pos = SOME true) T
blanchet@38939
   341
                      (HOLogic.mk_conj (incr_boundvars 1 t1 $ Bound 0, t'))
blanchet@37537
   342
      | (t0 as Const (_, @{typ bool})) $ t1 =>
blanchet@37537
   343
        do_term t0 #> do_formula pos t1  (* theory constant *)
blanchet@37537
   344
      | _ => do_term t
blanchet@38819
   345
  in Symtab.empty |> fold (do_formula pos) ts end
paulson@24287
   346
paulson@24287
   347
(*Inserts a dummy "constant" referring to the theory name, so that relevance
paulson@24287
   348
  takes the given theory into account.*)
blanchet@41200
   349
fun theory_constify ({theory_const_rel_weight, theory_const_irrel_weight, ...}
blanchet@41200
   350
                     : relevance_fudge) thy_name t =
blanchet@40070
   351
  if exists (curry (op <) 0.0) [theory_const_rel_weight,
blanchet@40070
   352
                                theory_const_irrel_weight] then
blanchet@41200
   353
    Const (thy_name ^ theory_const_suffix, @{typ bool}) $ t
blanchet@37505
   354
  else
blanchet@41200
   355
    t
blanchet@41200
   356
blanchet@41200
   357
fun theory_const_prop_of fudge th =
blanchet@41200
   358
  theory_constify fudge (Context.theory_name (theory_of_thm th)) (prop_of th)
blanchet@37505
   359
paulson@24287
   360
(**** Constant / Type Frequencies ****)
paulson@24287
   361
blanchet@38743
   362
(* A two-dimensional symbol table counts frequencies of constants. It's keyed
blanchet@38743
   363
   first by constant name and second by its list of type instantiations. For the
blanchet@38823
   364
   latter, we need a linear ordering on "pattern list". *)
paulson@24287
   365
blanchet@38823
   366
fun pattern_ord p =
blanchet@38743
   367
  case p of
blanchet@38744
   368
    (PVar, PVar) => EQUAL
blanchet@38823
   369
  | (PVar, PApp _) => LESS
blanchet@38823
   370
  | (PApp _, PVar) => GREATER
blanchet@38823
   371
  | (PApp q1, PApp q2) =>
blanchet@38823
   372
    prod_ord fast_string_ord (dict_ord pattern_ord) (q1, q2)
blanchet@38939
   373
fun ptype_ord (PType p, PType q) =
blanchet@38939
   374
  prod_ord (dict_ord pattern_ord) int_ord (swap p, swap q)
paulson@24287
   375
blanchet@38939
   376
structure PType_Tab = Table(type key = ptype val ord = ptype_ord)
paulson@24287
   377
blanchet@40204
   378
fun count_fact_consts thy fudge =
blanchet@37503
   379
  let
blanchet@38827
   380
    fun do_const const (s, T) ts =
blanchet@38827
   381
      (* Two-dimensional table update. Constant maps to types maps to count. *)
blanchet@41204
   382
      PType_Tab.map_default (rich_ptype thy const (s, T), 0) (Integer.add 1)
blanchet@38939
   383
      |> Symtab.map_default (s, PType_Tab.empty)
blanchet@38827
   384
      #> fold do_term ts
blanchet@38827
   385
    and do_term t =
blanchet@38827
   386
      case strip_comb t of
blanchet@38827
   387
        (Const x, ts) => do_const true x ts
blanchet@38827
   388
      | (Free x, ts) => do_const false x ts
blanchet@38827
   389
      | (Abs (_, _, t'), ts) => fold do_term (t' :: ts)
blanchet@38827
   390
      | (_, ts) => fold do_term ts
blanchet@40070
   391
  in do_term o theory_const_prop_of fudge o snd end
paulson@24287
   392
paulson@24287
   393
paulson@24287
   394
(**** Actual Filtering Code ****)
paulson@24287
   395
blanchet@39367
   396
fun pow_int _ 0 = 1.0
blanchet@38939
   397
  | pow_int x 1 = x
blanchet@38939
   398
  | pow_int x n = if n > 0 then x * pow_int x (n - 1) else pow_int x (n + 1) / x
blanchet@38939
   399
paulson@24287
   400
(*The frequency of a constant is the sum of those of all instances of its type.*)
blanchet@38824
   401
fun pconst_freq match const_tab (c, ps) =
blanchet@38939
   402
  PType_Tab.fold (fn (qs, m) => match (ps, qs) ? Integer.add m)
blanchet@38939
   403
                 (the (Symtab.lookup const_tab c)) 0
blanchet@38686
   404
paulson@24287
   405
blanchet@38085
   406
(* A surprising number of theorems contain only a few significant constants.
blanchet@38085
   407
   These include all induction rules, and other general theorems. *)
blanchet@37503
   408
blanchet@37503
   409
(* "log" seems best in practice. A constant function of one ignores the constant
blanchet@38938
   410
   frequencies. Rare constants give more points if they are relevant than less
blanchet@38938
   411
   rare ones. *)
blanchet@39367
   412
fun rel_weight_for _ freq = 1.0 + 2.0 / Math.ln (Real.fromInt freq + 1.0)
blanchet@38938
   413
blanchet@38938
   414
(* Irrelevant constants are treated differently. We associate lower penalties to
blanchet@38938
   415
   very rare constants and very common ones -- the former because they can't
blanchet@38938
   416
   lead to the inclusion of too many new facts, and the latter because they are
blanchet@38938
   417
   so common as to be of little interest. *)
blanchet@40070
   418
fun irrel_weight_for ({worse_irrel_freq, higher_order_irrel_weight, ...}
blanchet@40070
   419
                      : relevance_fudge) order freq =
blanchet@40070
   420
  let val (k, x) = worse_irrel_freq |> `Real.ceil in
blanchet@38939
   421
    (if freq < k then Math.ln (Real.fromInt (freq + 1)) / Math.ln x
blanchet@38939
   422
     else rel_weight_for order freq / rel_weight_for order k)
blanchet@40070
   423
    * pow_int higher_order_irrel_weight (order - 1)
blanchet@38938
   424
  end
blanchet@37503
   425
blanchet@41790
   426
fun multiplier_for_const_name local_const_multiplier s =
blanchet@41790
   427
  if String.isSubstring "." s then 1.0 else local_const_multiplier
blanchet@38821
   428
blanchet@41790
   429
(* Computes a constant's weight, as determined by its frequency. *)
blanchet@41790
   430
fun generic_pconst_weight local_const_multiplier abs_weight skolem_weight
blanchet@41790
   431
                          theory_const_weight weight_for f const_tab
blanchet@41790
   432
                          (c as (s, PType (m, _))) =
blanchet@41790
   433
  if s = abs_name then
blanchet@41790
   434
    abs_weight
blanchet@41790
   435
  else if String.isPrefix skolem_prefix s then
blanchet@41790
   436
    skolem_weight
blanchet@41790
   437
  else if String.isSuffix theory_const_suffix s then
blanchet@41790
   438
    theory_const_weight
blanchet@41790
   439
  else
blanchet@41790
   440
    multiplier_for_const_name local_const_multiplier s
blanchet@41790
   441
    * weight_for m (pconst_freq (match_ptype o f) const_tab c)
blanchet@41790
   442
blanchet@41790
   443
fun rel_pconst_weight ({local_const_multiplier, abs_rel_weight,
blanchet@41790
   444
                        theory_const_rel_weight, ...} : relevance_fudge)
blanchet@41790
   445
                      const_tab =
blanchet@41790
   446
  generic_pconst_weight local_const_multiplier abs_rel_weight 0.0
blanchet@41790
   447
                        theory_const_rel_weight rel_weight_for I const_tab
blanchet@41790
   448
fun irrel_pconst_weight (fudge as {local_const_multiplier, abs_irrel_weight,
blanchet@41790
   449
                                   skolem_irrel_weight,
blanchet@40070
   450
                                   theory_const_irrel_weight, ...}) const_tab =
blanchet@41790
   451
  generic_pconst_weight local_const_multiplier abs_irrel_weight
blanchet@41790
   452
                        skolem_irrel_weight theory_const_irrel_weight
blanchet@41790
   453
                        (irrel_weight_for fudge) swap const_tab
paulson@24287
   454
blanchet@40070
   455
fun locality_bonus (_ : relevance_fudge) General = 0.0
blanchet@40070
   456
  | locality_bonus {intro_bonus, ...} Intro = intro_bonus
blanchet@40070
   457
  | locality_bonus {elim_bonus, ...} Elim = elim_bonus
blanchet@40070
   458
  | locality_bonus {simp_bonus, ...} Simp = simp_bonus
blanchet@40070
   459
  | locality_bonus {local_bonus, ...} Local = local_bonus
blanchet@40070
   460
  | locality_bonus {assum_bonus, ...} Assum = assum_bonus
blanchet@40070
   461
  | locality_bonus {chained_bonus, ...} Chained = chained_bonus
blanchet@38751
   462
blanchet@40418
   463
fun is_odd_const_name s =
blanchet@40418
   464
  s = abs_name orelse String.isPrefix skolem_prefix s orelse
blanchet@40418
   465
  String.isSuffix theory_const_suffix s
blanchet@40418
   466
blanchet@40204
   467
fun fact_weight fudge loc const_tab relevant_consts fact_consts =
blanchet@40204
   468
  case fact_consts |> List.partition (pconst_hyper_mem I relevant_consts)
blanchet@40204
   469
                   ||> filter_out (pconst_hyper_mem swap relevant_consts) of
blanchet@38827
   470
    ([], _) => 0.0
blanchet@38744
   471
  | (rel, irrel) =>
blanchet@40418
   472
    if forall (forall (is_odd_const_name o fst)) [rel, irrel] then
blanchet@40371
   473
      0.0
blanchet@40371
   474
    else
blanchet@40371
   475
      let
blanchet@40371
   476
        val irrel = irrel |> filter_out (pconst_mem swap rel)
blanchet@40371
   477
        val rel_weight =
blanchet@40371
   478
          0.0 |> fold (curry (op +) o rel_pconst_weight fudge const_tab) rel
blanchet@40371
   479
        val irrel_weight =
blanchet@40371
   480
          ~ (locality_bonus fudge loc)
blanchet@40371
   481
          |> fold (curry (op +) o irrel_pconst_weight fudge const_tab) irrel
blanchet@40371
   482
        val res = rel_weight / (rel_weight + irrel_weight)
blanchet@40371
   483
      in if Real.isFinite res then res else 0.0 end
blanchet@38747
   484
blanchet@40369
   485
fun pconsts_in_fact thy is_built_in_const t =
blanchet@38825
   486
  Symtab.fold (fn (s, pss) => fold (cons o pair s) pss)
blanchet@40369
   487
              (pconsts_in_terms thy is_built_in_const true (SOME true) [t]) []
blanchet@40369
   488
fun pair_consts_fact thy is_built_in_const fudge fact =
blanchet@40204
   489
  case fact |> snd |> theory_const_prop_of fudge
blanchet@40369
   490
            |> pconsts_in_fact thy is_built_in_const of
blanchet@38827
   491
    [] => NONE
blanchet@40204
   492
  | consts => SOME ((fact, consts), NONE)
paulson@24287
   493
blanchet@41768
   494
val const_names_in_fact = map fst ooo pconsts_in_fact
blanchet@41768
   495
blanchet@38699
   496
type annotated_thm =
blanchet@38939
   497
  (((unit -> string) * locality) * thm) * (string * ptype) list
blanchet@37505
   498
blanchet@38904
   499
fun take_most_relevant max_relevant remaining_max
blanchet@40070
   500
        ({max_imperfect, max_imperfect_exp, ...} : relevance_fudge) 
blanchet@40070
   501
        (candidates : (annotated_thm * real) list) =
blanchet@38744
   502
  let
blanchet@38747
   503
    val max_imperfect =
blanchet@40070
   504
      Real.ceil (Math.pow (max_imperfect,
blanchet@38904
   505
                    Math.pow (Real.fromInt remaining_max
blanchet@40070
   506
                              / Real.fromInt max_relevant, max_imperfect_exp)))
blanchet@38747
   507
    val (perfect, imperfect) =
blanchet@38889
   508
      candidates |> sort (Real.compare o swap o pairself snd)
blanchet@38889
   509
                 |> take_prefix (fn (_, w) => w > 0.99999)
blanchet@38747
   510
    val ((accepts, more_rejects), rejects) =
blanchet@38747
   511
      chop max_imperfect imperfect |>> append perfect |>> chop remaining_max
blanchet@38744
   512
  in
blanchet@38889
   513
    trace_msg (fn () =>
wenzelm@41491
   514
        "Actually passed (" ^ string_of_int (length accepts) ^ " of " ^
wenzelm@41491
   515
        string_of_int (length candidates) ^ "): " ^
blanchet@38889
   516
        (accepts |> map (fn ((((name, _), _), _), weight) =>
blanchet@38752
   517
                            name () ^ " [" ^ Real.toString weight ^ "]")
blanchet@38745
   518
                 |> commas));
blanchet@38747
   519
    (accepts, more_rejects @ rejects)
blanchet@38744
   520
  end
paulson@24287
   521
blanchet@40369
   522
fun if_empty_replace_with_locality thy is_built_in_const facts loc tab =
blanchet@38819
   523
  if Symtab.is_empty tab then
blanchet@40369
   524
    pconsts_in_terms thy is_built_in_const false (SOME false)
blanchet@38819
   525
        (map_filter (fn ((_, loc'), th) =>
blanchet@40204
   526
                        if loc' = loc then SOME (prop_of th) else NONE) facts)
blanchet@38819
   527
  else
blanchet@38819
   528
    tab
blanchet@38819
   529
blanchet@41158
   530
fun add_arities is_built_in_const th =
blanchet@41158
   531
  let
blanchet@41158
   532
    fun aux _ _ NONE = NONE
blanchet@41158
   533
      | aux t args (SOME tab) =
blanchet@41158
   534
        case t of
blanchet@41158
   535
          t1 $ t2 => SOME tab |> aux t1 (t2 :: args) |> aux t2 []
blanchet@41158
   536
        | Const (x as (s, _)) =>
blanchet@41336
   537
          (if is_built_in_const x args |> fst then
blanchet@41158
   538
             SOME tab
blanchet@41158
   539
           else case Symtab.lookup tab s of
blanchet@41158
   540
             NONE => SOME (Symtab.update (s, length args) tab)
blanchet@41158
   541
           | SOME n => if n = length args then SOME tab else NONE)
blanchet@41158
   542
        | _ => SOME tab
blanchet@41158
   543
  in aux (prop_of th) [] end
blanchet@41158
   544
blanchet@41158
   545
fun needs_ext is_built_in_const facts =
blanchet@41158
   546
  fold (add_arities is_built_in_const o snd) facts (SOME Symtab.empty)
blanchet@41158
   547
  |> is_none
blanchet@41158
   548
blanchet@40369
   549
fun relevance_filter ctxt threshold0 decay max_relevant is_built_in_const
blanchet@40070
   550
        (fudge as {threshold_divisor, ridiculous_threshold, ...})
blanchet@40204
   551
        ({add, del, ...} : relevance_override) facts goal_ts =
blanchet@38739
   552
  let
wenzelm@42361
   553
    val thy = Proof_Context.theory_of ctxt
blanchet@40204
   554
    val const_tab = fold (count_fact_consts thy fudge) facts Symtab.empty
blanchet@38819
   555
    val goal_const_tab =
blanchet@40369
   556
      pconsts_in_terms thy is_built_in_const false (SOME false) goal_ts
blanchet@40369
   557
      |> fold (if_empty_replace_with_locality thy is_built_in_const facts)
blanchet@38993
   558
              [Chained, Assum, Local]
blanchet@39012
   559
    val add_ths = Attrib.eval_thms ctxt add
blanchet@39012
   560
    val del_ths = Attrib.eval_thms ctxt del
blanchet@40204
   561
    val facts = facts |> filter_out (member Thm.eq_thm del_ths o snd)
blanchet@38747
   562
    fun iter j remaining_max threshold rel_const_tab hopeless hopeful =
blanchet@38739
   563
      let
blanchet@40191
   564
        fun relevant [] _ [] =
blanchet@38747
   565
            (* Nothing has been added this iteration. *)
blanchet@40070
   566
            if j = 0 andalso threshold >= ridiculous_threshold then
blanchet@38747
   567
              (* First iteration? Try again. *)
blanchet@40070
   568
              iter 0 max_relevant (threshold / threshold_divisor) rel_const_tab
blanchet@38747
   569
                   hopeless hopeful
blanchet@38744
   570
            else
blanchet@40191
   571
              []
blanchet@38889
   572
          | relevant candidates rejects [] =
blanchet@38739
   573
            let
blanchet@38747
   574
              val (accepts, more_rejects) =
blanchet@40070
   575
                take_most_relevant max_relevant remaining_max fudge candidates
blanchet@38739
   576
              val rel_const_tab' =
blanchet@38745
   577
                rel_const_tab
blanchet@41066
   578
                |> fold (add_pconst_to_table false) (maps (snd o fst) accepts)
blanchet@38744
   579
              fun is_dirty (c, _) =
blanchet@38744
   580
                Symtab.lookup rel_const_tab' c <> Symtab.lookup rel_const_tab c
blanchet@38745
   581
              val (hopeful_rejects, hopeless_rejects) =
blanchet@38745
   582
                 (rejects @ hopeless, ([], []))
blanchet@38745
   583
                 |-> fold (fn (ax as (_, consts), old_weight) =>
blanchet@38745
   584
                              if exists is_dirty consts then
blanchet@38745
   585
                                apfst (cons (ax, NONE))
blanchet@38745
   586
                              else
blanchet@38745
   587
                                apsnd (cons (ax, old_weight)))
blanchet@38745
   588
                 |>> append (more_rejects
blanchet@38745
   589
                             |> map (fn (ax as (_, consts), old_weight) =>
blanchet@38745
   590
                                        (ax, if exists is_dirty consts then NONE
blanchet@38745
   591
                                             else SOME old_weight)))
blanchet@38747
   592
              val threshold =
blanchet@38822
   593
                1.0 - (1.0 - threshold)
blanchet@38822
   594
                      * Math.pow (decay, Real.fromInt (length accepts))
blanchet@38747
   595
              val remaining_max = remaining_max - length accepts
blanchet@38739
   596
            in
blanchet@38744
   597
              trace_msg (fn () => "New or updated constants: " ^
blanchet@38744
   598
                  commas (rel_const_tab' |> Symtab.dest
blanchet@38822
   599
                          |> subtract (op =) (rel_const_tab |> Symtab.dest)
blanchet@38827
   600
                          |> map string_for_hyper_pconst));
blanchet@38745
   601
              map (fst o fst) accepts @
blanchet@38747
   602
              (if remaining_max = 0 then
blanchet@40191
   603
                 []
blanchet@38745
   604
               else
blanchet@38747
   605
                 iter (j + 1) remaining_max threshold rel_const_tab'
blanchet@38747
   606
                      hopeless_rejects hopeful_rejects)
blanchet@38739
   607
            end
blanchet@38889
   608
          | relevant candidates rejects
blanchet@40204
   609
                     (((ax as (((_, loc), _), fact_consts)), cached_weight)
blanchet@38747
   610
                      :: hopeful) =
blanchet@38739
   611
            let
blanchet@38739
   612
              val weight =
blanchet@38739
   613
                case cached_weight of
blanchet@38739
   614
                  SOME w => w
blanchet@40204
   615
                | NONE => fact_weight fudge loc const_tab rel_const_tab
blanchet@40204
   616
                                      fact_consts
blanchet@38739
   617
            in
blanchet@38741
   618
              if weight >= threshold then
blanchet@38889
   619
                relevant ((ax, weight) :: candidates) rejects hopeful
blanchet@38739
   620
              else
blanchet@38889
   621
                relevant candidates ((ax, weight) :: rejects) hopeful
blanchet@38739
   622
            end
blanchet@38739
   623
        in
blanchet@38744
   624
          trace_msg (fn () =>
blanchet@38744
   625
              "ITERATION " ^ string_of_int j ^ ": current threshold: " ^
blanchet@38744
   626
              Real.toString threshold ^ ", constants: " ^
blanchet@38744
   627
              commas (rel_const_tab |> Symtab.dest
blanchet@38744
   628
                      |> filter (curry (op <>) [] o snd)
blanchet@38827
   629
                      |> map string_for_hyper_pconst));
blanchet@38889
   630
          relevant [] [] hopeful
blanchet@38739
   631
        end
blanchet@41158
   632
    fun add_facts ths accepts =
blanchet@41167
   633
      (facts |> filter (member Thm.eq_thm ths o snd)) @
blanchet@41167
   634
      (accepts |> filter_out (member Thm.eq_thm ths o snd))
blanchet@40408
   635
      |> take max_relevant
blanchet@38739
   636
  in
blanchet@40369
   637
    facts |> map_filter (pair_consts_fact thy is_built_in_const fudge)
blanchet@40204
   638
          |> iter 0 max_relevant threshold0 goal_const_tab []
blanchet@41158
   639
          |> not (null add_ths) ? add_facts add_ths
blanchet@41158
   640
          |> (fn accepts =>
blanchet@41158
   641
                 accepts |> needs_ext is_built_in_const accepts
blanchet@41158
   642
                            ? add_facts @{thms ext})
blanchet@41158
   643
          |> tap (fn accepts => trace_msg (fn () =>
wenzelm@41491
   644
                      "Total relevant: " ^ string_of_int (length accepts)))
blanchet@38739
   645
  end
paulson@24287
   646
blanchet@38744
   647
paulson@24287
   648
(***************************************************************)
mengj@19768
   649
(* Retrieving and filtering lemmas                             *)
mengj@19768
   650
(***************************************************************)
mengj@19768
   651
paulson@33022
   652
(*** retrieve lemmas and filter them ***)
mengj@19768
   653
paulson@20757
   654
(*Reject theorems with names like "List.filter.filter_list_def" or
paulson@21690
   655
  "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
paulson@20757
   656
fun is_package_def a =
blanchet@40205
   657
  let val names = Long_Name.explode a in
blanchet@40205
   658
    (length names > 2 andalso not (hd names = "local") andalso
blanchet@40205
   659
     String.isSuffix "_def" a) orelse String.isSuffix "_defs" a
blanchet@40205
   660
  end
paulson@20757
   661
blanchet@42641
   662
fun mk_fact_table g f xs =
blanchet@42641
   663
  fold (Termtab.update o `(g o prop_of o f)) xs Termtab.empty
blanchet@42641
   664
fun uniquify xs = Termtab.fold (cons o snd) (mk_fact_table I snd xs) []
mengj@19768
   665
blanchet@37626
   666
(* FIXME: put other record thms here, or declare as "no_atp" *)
blanchet@37626
   667
val multi_base_blacklist =
blanchet@41199
   668
  ["defs", "select_defs", "update_defs", "split", "splits", "split_asm",
blanchet@41199
   669
   "cases", "ext_cases", "eq.simps", "eq.refl", "nchotomy", "case_cong",
blanchet@41199
   670
   "weak_case_cong"]
blanchet@41273
   671
  |> not instantiate_inducts ? append ["induct", "inducts"]
blanchet@38682
   672
  |> map (prefix ".")
blanchet@37626
   673
blanchet@37626
   674
val max_lambda_nesting = 3
blanchet@37626
   675
blanchet@37626
   676
fun term_has_too_many_lambdas max (t1 $ t2) =
blanchet@37626
   677
    exists (term_has_too_many_lambdas max) [t1, t2]
blanchet@37626
   678
  | term_has_too_many_lambdas max (Abs (_, _, t)) =
blanchet@37626
   679
    max = 0 orelse term_has_too_many_lambdas (max - 1) t
blanchet@37626
   680
  | term_has_too_many_lambdas _ _ = false
blanchet@37626
   681
blanchet@37626
   682
(* Don't count nested lambdas at the level of formulas, since they are
blanchet@37626
   683
   quantifiers. *)
blanchet@37626
   684
fun formula_has_too_many_lambdas Ts (Abs (_, T, t)) =
blanchet@37626
   685
    formula_has_too_many_lambdas (T :: Ts) t
blanchet@37626
   686
  | formula_has_too_many_lambdas Ts t =
blanchet@41273
   687
    if member (op =) [HOLogic.boolT, propT] (fastype_of1 (Ts, t)) then
blanchet@37626
   688
      exists (formula_has_too_many_lambdas Ts) (#2 (strip_comb t))
blanchet@37626
   689
    else
blanchet@37626
   690
      term_has_too_many_lambdas max_lambda_nesting t
blanchet@37626
   691
blanchet@38692
   692
(* The max apply depth of any "metis" call in "Metis_Examples" (on 2007-10-31)
blanchet@37626
   693
   was 11. *)
blanchet@37626
   694
val max_apply_depth = 15
blanchet@37626
   695
blanchet@37626
   696
fun apply_depth (f $ t) = Int.max (apply_depth f, apply_depth t + 1)
blanchet@37626
   697
  | apply_depth (Abs (_, _, t)) = apply_depth t
blanchet@37626
   698
  | apply_depth _ = 0
blanchet@37626
   699
blanchet@37626
   700
fun is_formula_too_complex t =
blanchet@38085
   701
  apply_depth t > max_apply_depth orelse formula_has_too_many_lambdas [] t
blanchet@37626
   702
blanchet@39946
   703
(* FIXME: Extend to "Meson" and "Metis" *)
blanchet@37543
   704
val exists_sledgehammer_const =
blanchet@37626
   705
  exists_Const (fn (s, _) => String.isPrefix sledgehammer_prefix s)
blanchet@37626
   706
blanchet@38904
   707
(* FIXME: make more reliable *)
blanchet@38904
   708
val exists_low_level_class_const =
blanchet@38904
   709
  exists_Const (fn (s, _) =>
blanchet@38904
   710
     String.isSubstring (Long_Name.separator ^ "class" ^ Long_Name.separator) s)
blanchet@38904
   711
blanchet@38821
   712
fun is_metastrange_theorem th =
blanchet@37626
   713
  case head_of (concl_of th) of
blanchet@37626
   714
      Const (a, _) => (a <> @{const_name Trueprop} andalso
blanchet@37626
   715
                       a <> @{const_name "=="})
blanchet@37626
   716
    | _ => false
blanchet@37626
   717
blanchet@38821
   718
fun is_that_fact th =
blanchet@38821
   719
  String.isSuffix (Long_Name.separator ^ Obtain.thatN) (Thm.get_name_hint th)
blanchet@38821
   720
  andalso exists_subterm (fn Free (s, _) => s = Name.skolem Auto_Bind.thesisN
blanchet@38821
   721
                           | _ => false) (prop_of th)
blanchet@38821
   722
blanchet@37626
   723
val type_has_top_sort =
blanchet@37626
   724
  exists_subtype (fn TFree (_, []) => true | TVar (_, []) => true | _ => false)
blanchet@37626
   725
blanchet@38085
   726
(**** Predicates to detect unwanted facts (prolific or likely to cause
blanchet@37347
   727
      unsoundness) ****)
paulson@21470
   728
blanchet@38289
   729
(* Too general means, positive equality literal with a variable X as one
blanchet@38289
   730
   operand, when X does not occur properly in the other operand. This rules out
blanchet@38289
   731
   clearly inconsistent facts such as X = a | X = b, though it by no means
blanchet@38289
   732
   guarantees soundness. *)
paulson@21470
   733
blanchet@38289
   734
(* Unwanted equalities are those between a (bound or schematic) variable that
blanchet@38289
   735
   does not properly occur in the second operand. *)
blanchet@38607
   736
val is_exhaustive_finite =
blanchet@38607
   737
  let
blanchet@38629
   738
    fun is_bad_equal (Var z) t =
blanchet@38629
   739
        not (exists_subterm (fn Var z' => z = z' | _ => false) t)
blanchet@38629
   740
      | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
blanchet@38629
   741
      | is_bad_equal _ _ = false
blanchet@38629
   742
    fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
blanchet@38607
   743
    fun do_formula pos t =
blanchet@38607
   744
      case (pos, t) of
blanchet@38615
   745
        (_, @{const Trueprop} $ t1) => do_formula pos t1
blanchet@38607
   746
      | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
blanchet@38607
   747
        do_formula pos t'
blanchet@38607
   748
      | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
blanchet@38607
   749
        do_formula pos t'
blanchet@38607
   750
      | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
blanchet@38607
   751
        do_formula pos t'
blanchet@38607
   752
      | (_, @{const "==>"} $ t1 $ t2) =>
blanchet@38629
   753
        do_formula (not pos) t1 andalso
blanchet@38629
   754
        (t2 = @{prop False} orelse do_formula pos t2)
haftmann@38786
   755
      | (_, @{const HOL.implies} $ t1 $ t2) =>
blanchet@38629
   756
        do_formula (not pos) t1 andalso
blanchet@38629
   757
        (t2 = @{const False} orelse do_formula pos t2)
blanchet@38607
   758
      | (_, @{const Not} $ t1) => do_formula (not pos) t1
haftmann@38795
   759
      | (true, @{const HOL.disj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
haftmann@38795
   760
      | (false, @{const HOL.conj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
haftmann@38864
   761
      | (true, Const (@{const_name HOL.eq}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38607
   762
      | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38607
   763
      | _ => false
blanchet@38607
   764
  in do_formula true end
blanchet@38607
   765
blanchet@38592
   766
fun has_bound_or_var_of_type tycons =
blanchet@38592
   767
  exists_subterm (fn Var (_, Type (s, _)) => member (op =) tycons s
blanchet@38592
   768
                   | Abs (_, Type (s, _), _) => member (op =) tycons s
blanchet@38592
   769
                   | _ => false)
paulson@21431
   770
blanchet@38085
   771
(* Facts are forbidden to contain variables of these types. The typical reason
blanchet@37347
   772
   is that they lead to unsoundness. Note that "unit" satisfies numerous
blanchet@38085
   773
   equations like "?x = ()". The resulting clauses will have no type constraint,
blanchet@37347
   774
   yielding false proofs. Even "bool" leads to many unsound proofs, though only
blanchet@37347
   775
   for higher-order problems. *)
blanchet@42638
   776
val dangerous_types = [@{type_name unit}, @{type_name bool}, @{type_name prop}]
paulson@22217
   777
blanchet@38085
   778
(* Facts containing variables of type "unit" or "bool" or of the form
blanchet@38290
   779
   "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
blanchet@38290
   780
   are omitted. *)
blanchet@42638
   781
val is_dangerous_term =
blanchet@42638
   782
  transform_elim_term
blanchet@42638
   783
  #> has_bound_or_var_of_type dangerous_types orf is_exhaustive_finite
paulson@21470
   784
blanchet@42638
   785
fun is_theorem_bad_for_atps thm =
blanchet@38627
   786
  let val t = prop_of thm in
blanchet@38627
   787
    is_formula_too_complex t orelse exists_type type_has_top_sort t orelse
blanchet@42638
   788
    exists_sledgehammer_const t orelse exists_low_level_class_const t orelse
blanchet@42638
   789
    is_metastrange_theorem thm orelse is_that_fact thm
blanchet@38627
   790
  end
blanchet@38627
   791
blanchet@42641
   792
fun meta_equify (@{const Trueprop}
blanchet@42641
   793
                 $ (Const (@{const_name HOL.eq}, Type (_, [T, _])) $ t1 $ t2)) =
blanchet@42641
   794
    Const (@{const_name "=="}, T --> T --> @{typ prop}) $ t1 $ t2
blanchet@42641
   795
  | meta_equify t = t
blanchet@42641
   796
blanchet@42641
   797
val normalize_simp_prop =
blanchet@42641
   798
  meta_equify
blanchet@42641
   799
  #> map_aterms (fn Var ((s, _), T) => Var ((s, 0), T) | t => t)
blanchet@42641
   800
  #> map_types (map_type_tvar (fn ((s, _), S) => TVar ((s, 0), S)))
blanchet@42641
   801
blanchet@38937
   802
fun clasimpset_rules_of ctxt =
blanchet@38937
   803
  let
blanchet@38937
   804
    val {safeIs, safeEs, hazIs, hazEs, ...} = ctxt |> claset_of |> rep_cs
blanchet@38937
   805
    val intros = safeIs @ hazIs
blanchet@38937
   806
    val elims = map Classical.classical_rule (safeEs @ hazEs)
blanchet@42641
   807
    val simps = ctxt |> simpset_of |> dest_ss |> #simps
blanchet@42641
   808
  in
blanchet@42641
   809
    (mk_fact_table I I intros,
blanchet@42641
   810
     mk_fact_table I I elims,
blanchet@42641
   811
     mk_fact_table normalize_simp_prop snd simps)
blanchet@42641
   812
  end
blanchet@38937
   813
blanchet@42641
   814
fun all_facts ctxt reserved really_all add_ths chained_ths =
blanchet@38627
   815
  let
wenzelm@42361
   816
    val thy = Proof_Context.theory_of ctxt
wenzelm@39557
   817
    val global_facts = Global_Theory.facts_of thy
wenzelm@42361
   818
    val local_facts = Proof_Context.facts_of ctxt
blanchet@38644
   819
    val named_locals = local_facts |> Facts.dest_static []
blanchet@38993
   820
    val assms = Assumption.all_assms_of ctxt
blanchet@38993
   821
    fun is_assum th = exists (fn ct => prop_of th aconv term_of ct) assms
blanchet@38752
   822
    val is_chained = member Thm.eq_thm chained_ths
blanchet@42641
   823
    val (intros, elims, simps) = clasimpset_rules_of ctxt
blanchet@42641
   824
    fun locality_of_theorem global th =
blanchet@42641
   825
      if is_chained th then
blanchet@42641
   826
        Chained
blanchet@42641
   827
      else if global then
blanchet@42641
   828
        let val t = prop_of th in
blanchet@42641
   829
          if Termtab.defined intros t then Intro
blanchet@42641
   830
          else if Termtab.defined elims t then Elim
blanchet@42641
   831
          else if Termtab.defined simps (normalize_simp_prop t) then Simp
blanchet@42641
   832
          else General
blanchet@42641
   833
        end
blanchet@38937
   834
      else
blanchet@42641
   835
        if is_assum th then Assum else Local
blanchet@38738
   836
    fun is_good_unnamed_local th =
blanchet@38820
   837
      not (Thm.has_name_hint th) andalso
blanchet@38738
   838
      forall (fn (_, ths) => not (member Thm.eq_thm ths th)) named_locals
blanchet@38644
   839
    val unnamed_locals =
blanchet@38820
   840
      union Thm.eq_thm (Facts.props local_facts) chained_ths
blanchet@38820
   841
      |> filter is_good_unnamed_local |> map (pair "" o single)
blanchet@38627
   842
    val full_space =
blanchet@38738
   843
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts)
blanchet@38752
   844
    fun add_facts global foldx facts =
blanchet@38699
   845
      foldx (fn (name0, ths) =>
blanchet@41989
   846
        if not really_all andalso name0 <> "" andalso
blanchet@39012
   847
           forall (not o member Thm.eq_thm add_ths) ths andalso
blanchet@38699
   848
           (Facts.is_concealed facts name0 orelse
blanchet@38699
   849
            (respect_no_atp andalso is_package_def name0) orelse
blanchet@38699
   850
            exists (fn s => String.isSuffix s name0) multi_base_blacklist orelse
blanchet@38699
   851
            String.isSuffix "_def_raw" (* FIXME: crude hack *) name0) then
blanchet@38627
   852
          I
blanchet@38627
   853
        else
blanchet@38627
   854
          let
blanchet@38699
   855
            val multi = length ths > 1
blanchet@41279
   856
            val backquote_thm =
blanchet@41279
   857
              backquote o string_for_term ctxt o close_form o prop_of
blanchet@38699
   858
            fun check_thms a =
wenzelm@42361
   859
              case try (Proof_Context.get_thms ctxt) a of
blanchet@38699
   860
                NONE => false
blanchet@38699
   861
              | SOME ths' => Thm.eq_thms (ths, ths')
blanchet@38627
   862
          in
blanchet@38699
   863
            pair 1
blanchet@38699
   864
            #> fold (fn th => fn (j, rest) =>
blanchet@42641
   865
                        (j + 1,
blanchet@42641
   866
                         if is_theorem_bad_for_atps th andalso
blanchet@42641
   867
                            not (member Thm.eq_thm add_ths th) then
blanchet@42641
   868
                           rest
blanchet@42641
   869
                         else
blanchet@42641
   870
                           (((fn () =>
blanchet@42641
   871
                                 if name0 = "" then
blanchet@42641
   872
                                   th |> backquote_thm
blanchet@42641
   873
                                 else
blanchet@42641
   874
                                   [Facts.extern ctxt facts name0,
blanchet@42641
   875
                                    Name_Space.extern ctxt full_space name0,
blanchet@42641
   876
                                    name0]
blanchet@42641
   877
                                   |> find_first check_thms
blanchet@42641
   878
                                   |> (fn SOME name =>
blanchet@42641
   879
                                          make_name reserved multi j name
blanchet@42641
   880
                                        | NONE => "")),
blanchet@42641
   881
                              locality_of_theorem global th),
blanchet@42641
   882
                              (multi, th)) :: rest)) ths
blanchet@38699
   883
            #> snd
blanchet@38627
   884
          end)
blanchet@38644
   885
  in
blanchet@38752
   886
    [] |> add_facts false fold local_facts (unnamed_locals @ named_locals)
blanchet@38752
   887
       |> add_facts true Facts.fold_static global_facts global_facts
blanchet@38644
   888
  end
blanchet@38627
   889
blanchet@38627
   890
(* The single-name theorems go after the multiple-name ones, so that single
blanchet@38627
   891
   names are preferred when both are available. *)
blanchet@40205
   892
fun rearrange_facts ctxt respect_no_atp =
blanchet@38744
   893
  List.partition (fst o snd) #> op @ #> map (apsnd snd)
blanchet@38699
   894
  #> respect_no_atp ? filter_out (No_ATPs.member ctxt o snd)
blanchet@38627
   895
blanchet@41199
   896
fun external_frees t =
blanchet@41199
   897
  [] |> Term.add_frees t |> filter_out (can Name.dest_internal o fst)
blanchet@41199
   898
blanchet@42638
   899
fun relevant_facts ctxt (threshold0, threshold1) max_relevant is_built_in_const
blanchet@42638
   900
                   fudge (override as {add, only, ...}) chained_ths hyp_ts
blanchet@42638
   901
                   concl_t =
blanchet@37538
   902
  let
wenzelm@42361
   903
    val thy = Proof_Context.theory_of ctxt
blanchet@38822
   904
    val decay = Math.pow ((1.0 - threshold1) / (1.0 - threshold0),
blanchet@38822
   905
                          1.0 / Real.fromInt (max_relevant + 1))
blanchet@39012
   906
    val add_ths = Attrib.eval_thms ctxt add
blanchet@38696
   907
    val reserved = reserved_isar_keyword_table ()
blanchet@41199
   908
    val ind_stmt =
blanchet@41199
   909
      Logic.list_implies (hyp_ts |> filter_out (null o external_frees), concl_t)
blanchet@41211
   910
      |> Object_Logic.atomize_term thy
blanchet@41199
   911
    val ind_stmt_xs = external_frees ind_stmt
blanchet@40204
   912
    val facts =
blanchet@38699
   913
      (if only then
blanchet@38752
   914
         maps (map (fn ((name, loc), th) => ((K name, loc), (true, th)))
blanchet@40205
   915
               o fact_from_ref ctxt reserved chained_ths) add
blanchet@38699
   916
       else
blanchet@42641
   917
         all_facts ctxt reserved false add_ths chained_ths)
blanchet@41273
   918
      |> instantiate_inducts
blanchet@41273
   919
         ? maps (instantiate_if_induct_rule ctxt ind_stmt ind_stmt_xs)
blanchet@40205
   920
      |> rearrange_facts ctxt (respect_no_atp andalso not only)
blanchet@38937
   921
      |> uniquify
blanchet@37538
   922
  in
wenzelm@41491
   923
    trace_msg (fn () => "Considering " ^ string_of_int (length facts) ^
blanchet@40204
   924
                        " facts");
blanchet@39366
   925
    (if only orelse threshold1 < 0.0 then
blanchet@40204
   926
       facts
blanchet@39366
   927
     else if threshold0 > 1.0 orelse threshold0 > threshold1 orelse
blanchet@39366
   928
             max_relevant = 0 then
blanchet@38739
   929
       []
blanchet@38739
   930
     else
blanchet@41200
   931
       ((concl_t |> theory_constify fudge (Context.theory_name thy)) :: hyp_ts)
blanchet@41200
   932
       |> relevance_filter ctxt threshold0 decay max_relevant is_built_in_const
blanchet@41200
   933
                           fudge override facts)
blanchet@38822
   934
    |> map (apfst (apfst (fn f => f ())))
blanchet@37538
   935
  end
immler@30536
   936
paulson@15347
   937
end;