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