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