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