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