src/HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
author blanchet
Wed Aug 25 09:42:28 2010 +0200 (2010-08-25 ago)
changeset 38743 69fa75354c58
parent 38742 4fe1bb9e7434
child 38744 2b6333f78a9e
permissions -rw-r--r--
simplify more code
blanchet@35826
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
blanchet@38027
     2
    Author:     Jia Meng, Cambridge University Computer Laboratory and NICTA
blanchet@36393
     3
    Author:     Jasmin Blanchette, TU Muenchen
wenzelm@33309
     4
*)
paulson@15452
     5
blanchet@35826
     6
signature SLEDGEHAMMER_FACT_FILTER =
wenzelm@16802
     7
sig
blanchet@35966
     8
  type relevance_override =
blanchet@35966
     9
    {add: Facts.ref list,
blanchet@35966
    10
     del: Facts.ref list,
blanchet@35966
    11
     only: bool}
blanchet@35966
    12
blanchet@37616
    13
  val trace : bool Unsynchronized.ref
blanchet@38617
    14
  val name_thms_pair_from_ref :
blanchet@38696
    15
    Proof.context -> unit Symtab.table -> thm list -> Facts.ref
blanchet@38699
    16
    -> (unit -> string * bool) * thm list
blanchet@37347
    17
  val relevant_facts :
blanchet@38741
    18
    bool -> real -> real -> int -> bool -> relevance_override
blanchet@37995
    19
    -> Proof.context * (thm list * 'a) -> term list -> term
blanchet@38698
    20
    -> ((string * bool) * thm) list
paulson@15347
    21
end;
paulson@15347
    22
blanchet@35826
    23
structure Sledgehammer_Fact_Filter : SLEDGEHAMMER_FACT_FILTER =
paulson@15347
    24
struct
paulson@15347
    25
blanchet@38652
    26
open Sledgehammer_Util
blanchet@38652
    27
blanchet@37616
    28
val trace = Unsynchronized.ref false
blanchet@37616
    29
fun trace_msg msg = if !trace then tracing (msg ()) else ()
blanchet@35826
    30
blanchet@37580
    31
val respect_no_atp = true
blanchet@37505
    32
blanchet@35966
    33
type relevance_override =
blanchet@35966
    34
  {add: Facts.ref list,
blanchet@35966
    35
   del: Facts.ref list,
blanchet@35966
    36
   only: bool}
paulson@21070
    37
blanchet@37616
    38
val sledgehammer_prefix = "Sledgehammer" ^ Long_Name.separator
blanchet@37616
    39
blanchet@38696
    40
fun name_thms_pair_from_ref ctxt reserved chained_ths xref =
blanchet@38699
    41
  let val ths = ProofContext.get_fact ctxt xref in
blanchet@38699
    42
    (fn () => let
blanchet@38699
    43
                val name = Facts.string_of_ref xref
blanchet@38699
    44
                val name = name |> Symtab.defined reserved name ? quote
blanchet@38699
    45
                val chained = forall (member Thm.eq_thm chained_ths) ths
blanchet@38699
    46
              in (name, chained) end, ths)
blanchet@38699
    47
  end
blanchet@37616
    48
wenzelm@28477
    49
(***************************************************************)
wenzelm@28477
    50
(* Relevance Filtering                                         *)
wenzelm@28477
    51
(***************************************************************)
mengj@19194
    52
paulson@24287
    53
(*** constants with types ***)
paulson@24287
    54
paulson@24287
    55
(*An abstraction of Isabelle types*)
paulson@24287
    56
datatype const_typ =  CTVar | CType of string * const_typ list
paulson@24287
    57
paulson@24287
    58
(*Is the second type an instance of the first one?*)
blanchet@37505
    59
fun match_type (CType(con1,args1)) (CType(con2,args2)) =
paulson@24287
    60
      con1=con2 andalso match_types args1 args2
paulson@24287
    61
  | match_type CTVar _ = true
paulson@24287
    62
  | match_type _ CTVar = false
paulson@24287
    63
and match_types [] [] = true
paulson@24287
    64
  | match_types (a1::as1) (a2::as2) = match_type a1 a2 andalso match_types as1 as2;
paulson@24287
    65
paulson@24287
    66
(*Is there a unifiable constant?*)
blanchet@38687
    67
fun const_mem const_tab (c, c_typ) =
blanchet@38687
    68
  exists (match_types c_typ) (these (Symtab.lookup const_tab c))
blanchet@37505
    69
paulson@24287
    70
(*Maps a "real" type to a const_typ*)
blanchet@37505
    71
fun const_typ_of (Type (c,typs)) = CType (c, map const_typ_of typs)
paulson@24287
    72
  | const_typ_of (TFree _) = CTVar
paulson@24287
    73
  | const_typ_of (TVar _) = CTVar
paulson@24287
    74
paulson@24287
    75
(*Pairs a constant with the list of its type instantiations (using const_typ)*)
blanchet@37505
    76
fun const_with_typ thy (c,typ) =
blanchet@38606
    77
  let val tvars = Sign.const_typargs thy (c,typ) in
blanchet@38606
    78
    (c, map const_typ_of tvars) end
blanchet@38606
    79
  handle TYPE _ => (c, [])   (*Variable (locale constant): monomorphic*)
paulson@24287
    80
paulson@24287
    81
(*Add a const/type pair to the table, but a [] entry means a standard connective,
paulson@24287
    82
  which we ignore.*)
blanchet@38687
    83
fun add_const_to_table (c, ctyps) =
blanchet@37502
    84
  Symtab.map_default (c, [ctyps])
blanchet@37502
    85
                     (fn [] => [] | ctypss => insert (op =) ctyps ctypss)
paulson@24287
    86
blanchet@38692
    87
fun is_formula_type T = (T = HOLogic.boolT orelse T = propT)
blanchet@38692
    88
blanchet@38644
    89
val fresh_prefix = "Sledgehammer.FRESH."
blanchet@37537
    90
val flip = Option.map not
blanchet@38091
    91
(* These are typically simplified away by "Meson.presimplify". *)
blanchet@38682
    92
val boring_consts =
blanchet@38682
    93
  [@{const_name False}, @{const_name True}, @{const_name If}, @{const_name Let}]
blanchet@37537
    94
blanchet@38687
    95
fun get_consts thy pos ts =
blanchet@37505
    96
  let
blanchet@38587
    97
    (* We include free variables, as well as constants, to handle locales. For
blanchet@38587
    98
       each quantifiers that must necessarily be skolemized by the ATP, we
blanchet@38587
    99
       introduce a fresh constant to simulate the effect of Skolemization. *)
blanchet@37537
   100
    fun do_term t =
blanchet@37537
   101
      case t of
blanchet@38687
   102
        Const x => add_const_to_table (const_with_typ thy x)
blanchet@38687
   103
      | Free (s, _) => add_const_to_table (s, [])
blanchet@38688
   104
      | t1 $ t2 => fold do_term [t1, t2]
blanchet@38644
   105
      | Abs (_, _, t') => do_term t'
blanchet@37537
   106
      | _ => I
blanchet@38587
   107
    fun do_quantifier will_surely_be_skolemized body_t =
blanchet@37537
   108
      do_formula pos body_t
blanchet@38587
   109
      #> (if will_surely_be_skolemized then
blanchet@38687
   110
            add_const_to_table (gensym fresh_prefix, [])
blanchet@38587
   111
          else
blanchet@38587
   112
            I)
blanchet@38587
   113
    and do_term_or_formula T =
blanchet@38692
   114
      if is_formula_type T then do_formula NONE else do_term
blanchet@37537
   115
    and do_formula pos t =
blanchet@37537
   116
      case t of
blanchet@37537
   117
        Const (@{const_name all}, _) $ Abs (_, _, body_t) =>
blanchet@38587
   118
        do_quantifier (pos = SOME false) body_t
blanchet@37537
   119
      | @{const "==>"} $ t1 $ t2 =>
blanchet@37537
   120
        do_formula (flip pos) t1 #> do_formula pos t2
blanchet@37537
   121
      | Const (@{const_name "=="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38587
   122
        fold (do_term_or_formula T) [t1, t2]
blanchet@37537
   123
      | @{const Trueprop} $ t1 => do_formula pos t1
blanchet@37537
   124
      | @{const Not} $ t1 => do_formula (flip pos) t1
blanchet@37537
   125
      | Const (@{const_name All}, _) $ Abs (_, _, body_t) =>
blanchet@38587
   126
        do_quantifier (pos = SOME false) body_t
blanchet@37537
   127
      | Const (@{const_name Ex}, _) $ Abs (_, _, body_t) =>
blanchet@38587
   128
        do_quantifier (pos = SOME true) body_t
blanchet@37537
   129
      | @{const "op &"} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
blanchet@37537
   130
      | @{const "op |"} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
blanchet@37537
   131
      | @{const "op -->"} $ t1 $ t2 =>
blanchet@37537
   132
        do_formula (flip pos) t1 #> do_formula pos t2
blanchet@37537
   133
      | Const (@{const_name "op ="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38587
   134
        fold (do_term_or_formula T) [t1, t2]
blanchet@38587
   135
      | Const (@{const_name If}, Type (_, [_, Type (_, [T, _])]))
blanchet@38587
   136
        $ t1 $ t2 $ t3 =>
blanchet@38587
   137
        do_formula NONE t1 #> fold (do_term_or_formula T) [t2, t3]
blanchet@38587
   138
      | Const (@{const_name Ex1}, _) $ Abs (_, _, body_t) =>
blanchet@38587
   139
        do_quantifier (is_some pos) body_t
blanchet@38587
   140
      | Const (@{const_name Ball}, _) $ t1 $ Abs (_, _, body_t) =>
blanchet@38587
   141
        do_quantifier (pos = SOME false)
blanchet@38587
   142
                      (HOLogic.mk_imp (incr_boundvars 1 t1 $ Bound 0, body_t))
blanchet@38587
   143
      | Const (@{const_name Bex}, _) $ t1 $ Abs (_, _, body_t) =>
blanchet@38587
   144
        do_quantifier (pos = SOME true)
blanchet@38587
   145
                      (HOLogic.mk_conj (incr_boundvars 1 t1 $ Bound 0, body_t))
blanchet@37537
   146
      | (t0 as Const (_, @{typ bool})) $ t1 =>
blanchet@37537
   147
        do_term t0 #> do_formula pos t1  (* theory constant *)
blanchet@37537
   148
      | _ => do_term t
blanchet@37505
   149
  in
blanchet@38091
   150
    Symtab.empty |> fold (Symtab.update o rpair []) boring_consts
blanchet@37995
   151
                 |> fold (do_formula pos) ts
blanchet@37505
   152
  end
paulson@24287
   153
paulson@24287
   154
(*Inserts a dummy "constant" referring to the theory name, so that relevance
paulson@24287
   155
  takes the given theory into account.*)
blanchet@37616
   156
fun theory_const_prop_of theory_relevant th =
blanchet@37505
   157
  if theory_relevant then
blanchet@37505
   158
    let
blanchet@37505
   159
      val name = Context.theory_name (theory_of_thm th)
blanchet@37505
   160
      val t = Const (name ^ ". 1", @{typ bool})
blanchet@37505
   161
    in t $ prop_of th end
blanchet@37505
   162
  else
blanchet@37505
   163
    prop_of th
blanchet@37505
   164
paulson@24287
   165
(**** Constant / Type Frequencies ****)
paulson@24287
   166
blanchet@38743
   167
(* A two-dimensional symbol table counts frequencies of constants. It's keyed
blanchet@38743
   168
   first by constant name and second by its list of type instantiations. For the
blanchet@38743
   169
   latter, we need a linear ordering on "const_typ list". *)
paulson@24287
   170
blanchet@38743
   171
fun const_typ_ord p =
blanchet@38743
   172
  case p of
blanchet@38743
   173
    (CTVar, CTVar) => EQUAL
blanchet@38743
   174
  | (CTVar, CType _) => LESS
blanchet@38743
   175
  | (CType _, CTVar) => GREATER
blanchet@38743
   176
  | (CType q1, CType q2) =>
blanchet@38743
   177
    prod_ord fast_string_ord (dict_ord const_typ_ord) (q1, q2)
paulson@24287
   178
blanchet@38743
   179
structure CTtab =
blanchet@38743
   180
  Table(type key = const_typ list val ord = dict_ord const_typ_ord)
paulson@24287
   181
blanchet@37616
   182
fun count_axiom_consts theory_relevant thy (_, th) =
blanchet@37503
   183
  let
blanchet@37503
   184
    fun do_const (a, T) =
blanchet@38606
   185
      let val (c, cts) = const_with_typ thy (a, T) in
blanchet@37503
   186
        (* Two-dimensional table update. Constant maps to types maps to
blanchet@37503
   187
           count. *)
blanchet@37503
   188
        CTtab.map_default (cts, 0) (Integer.add 1)
blanchet@37503
   189
        |> Symtab.map_default (c, CTtab.empty)
blanchet@37503
   190
      end
blanchet@37503
   191
    fun do_term (Const x) = do_const x
blanchet@37503
   192
      | do_term (Free x) = do_const x
blanchet@37503
   193
      | do_term (t $ u) = do_term t #> do_term u
blanchet@37503
   194
      | do_term (Abs (_, _, t)) = do_term t
blanchet@37503
   195
      | do_term _ = I
blanchet@37616
   196
  in th |> theory_const_prop_of theory_relevant |> do_term end
paulson@24287
   197
paulson@24287
   198
paulson@24287
   199
(**** Actual Filtering Code ****)
paulson@24287
   200
paulson@24287
   201
(*The frequency of a constant is the sum of those of all instances of its type.*)
blanchet@37505
   202
fun const_frequency const_tab (c, cts) =
blanchet@36185
   203
  CTtab.fold (fn (cts', m) => match_types cts cts' ? Integer.add m)
blanchet@38686
   204
             (the (Symtab.lookup const_tab c)) 0
blanchet@38686
   205
  handle Option.Option => 0
blanchet@38686
   206
paulson@24287
   207
blanchet@38085
   208
(* A surprising number of theorems contain only a few significant constants.
blanchet@38085
   209
   These include all induction rules, and other general theorems. *)
blanchet@37503
   210
blanchet@37503
   211
(* "log" seems best in practice. A constant function of one ignores the constant
blanchet@37503
   212
   frequencies. *)
blanchet@38686
   213
fun rel_log (x : real) = 1.0 + 2.0 / Math.ln (x + 1.0)
blanchet@38686
   214
fun irrel_log (x : real) = Math.ln (x + 19.0) / 6.4
blanchet@37503
   215
blanchet@37503
   216
(* Computes a constant's weight, as determined by its frequency. *)
blanchet@38686
   217
val rel_const_weight = rel_log o real oo const_frequency
blanchet@38686
   218
val irrel_const_weight = irrel_log o real oo const_frequency
blanchet@38692
   219
(* fun irrel_const_weight _ _ = 1.0  FIXME: OLD CODE *)
paulson@24287
   220
blanchet@38687
   221
fun axiom_weight const_tab relevant_consts axiom_consts =
blanchet@38686
   222
  let
blanchet@38687
   223
    val (rel, irrel) = List.partition (const_mem relevant_consts) axiom_consts
blanchet@38686
   224
    val rel_weight = fold (curry Real.+ o rel_const_weight const_tab) rel 0.0
blanchet@38686
   225
    val irrel_weight = fold (curry Real.+ o irrel_const_weight const_tab) irrel 0.0
blanchet@38686
   226
    val res = rel_weight / (rel_weight + irrel_weight)
blanchet@38686
   227
  in if Real.isFinite res then res else 0.0 end
blanchet@38686
   228
blanchet@38686
   229
(* OLD CODE:
blanchet@37505
   230
(*Relevant constants are weighted according to frequency,
paulson@24287
   231
  but irrelevant constants are simply counted. Otherwise, Skolem functions,
blanchet@38085
   232
  which are rare, would harm a formula's chances of being picked.*)
blanchet@38687
   233
fun axiom_weight const_tab relevant_consts axiom_consts =
blanchet@38101
   234
  let
blanchet@38687
   235
    val rel = filter (const_mem relevant_consts) axiom_consts
blanchet@38686
   236
    val rel_weight = fold (curry Real.+ o rel_const_weight const_tab) rel 0.0
blanchet@38687
   237
    val res = rel_weight / (rel_weight + real (length axiom_consts - length rel))
blanchet@38101
   238
  in if Real.isFinite res then res else 0.0 end
blanchet@38686
   239
*)
blanchet@37505
   240
blanchet@38687
   241
fun consts_of_term thy t =
blanchet@38742
   242
  Symtab.fold (fn (x, ys) => fold (fn y => cons (x, y)) ys)
blanchet@38742
   243
              (get_consts thy (SOME true) [t]) []
paulson@24287
   244
blanchet@38687
   245
fun pair_consts_axiom theory_relevant thy axiom =
blanchet@37616
   246
  (axiom, axiom |> snd |> theory_const_prop_of theory_relevant
blanchet@38687
   247
                |> consts_of_term thy)
paulson@24287
   248
blanchet@38699
   249
type annotated_thm =
blanchet@38699
   250
  ((unit -> string * bool) * thm) * (string * const_typ list) list
blanchet@37505
   251
paulson@24287
   252
(*For a reverse sort, putting the largest values first.*)
blanchet@37500
   253
fun compare_pairs ((_, w1), (_, w2)) = Real.compare (w2, w1)
paulson@24287
   254
blanchet@38085
   255
(* Limit the number of new facts, to prevent runaway acceptance. *)
blanchet@38739
   256
fun take_best max_relevant_per_iter (new_pairs : (annotated_thm * real) list) =
blanchet@38687
   257
  let val nnew = length new_pairs in
blanchet@38739
   258
    if nnew <= max_relevant_per_iter then
blanchet@38687
   259
      (map #1 new_pairs, [])
blanchet@37505
   260
    else
blanchet@38587
   261
      let
blanchet@38687
   262
        val new_pairs = sort compare_pairs new_pairs
blanchet@38739
   263
        val accepted = List.take (new_pairs, max_relevant_per_iter)
paulson@24287
   264
      in
blanchet@37505
   265
        trace_msg (fn () => ("Number of candidates, " ^ Int.toString nnew ^
blanchet@38739
   266
               ", exceeds the limit of " ^ Int.toString max_relevant_per_iter));
blanchet@35865
   267
        trace_msg (fn () => ("Effective pass mark: " ^ Real.toString (#2 (List.last accepted))));
blanchet@35865
   268
        trace_msg (fn () => "Actually passed: " ^
blanchet@38699
   269
          space_implode ", " (map (fst o (fn f => f ()) o fst o fst o fst) accepted));
blanchet@38739
   270
        (map #1 accepted, List.drop (new_pairs, max_relevant_per_iter))
paulson@24287
   271
      end
paulson@24287
   272
  end;
paulson@24287
   273
blanchet@38683
   274
val threshold_divisor = 2.0
blanchet@38683
   275
val ridiculous_threshold = 0.1
blanchet@38683
   276
blanchet@38741
   277
fun relevance_filter ctxt relevance_threshold relevance_decay
blanchet@38739
   278
                     max_relevant_per_iter theory_relevant
blanchet@38594
   279
                     ({add, del, ...} : relevance_override) axioms goal_ts =
blanchet@38739
   280
  let
blanchet@38739
   281
    val thy = ProofContext.theory_of ctxt
blanchet@38739
   282
    val const_tab = fold (count_axiom_consts theory_relevant thy) axioms
blanchet@38739
   283
                         Symtab.empty
blanchet@38739
   284
    val goal_const_tab = get_consts thy (SOME false) goal_ts
blanchet@38739
   285
    val _ =
blanchet@38739
   286
      trace_msg (fn () => "Initial constants: " ^
blanchet@38739
   287
                          commas (goal_const_tab |> Symtab.dest
blanchet@38739
   288
                                  |> filter (curry (op <>) [] o snd)
blanchet@38739
   289
                                  |> map fst))
blanchet@38739
   290
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@38739
   291
    val del_thms = maps (ProofContext.get_fact ctxt) del
blanchet@38739
   292
    fun iter j threshold rel_const_tab =
blanchet@38739
   293
      let
blanchet@38739
   294
        fun relevant ([], rejects) [] =
blanchet@38739
   295
            (* Nothing was added this iteration. *)
blanchet@38739
   296
            if j = 0 andalso threshold >= ridiculous_threshold then
blanchet@38739
   297
              (* First iteration? Try again. *)
blanchet@38739
   298
              iter 0 (threshold / threshold_divisor) rel_const_tab
blanchet@38739
   299
                   (map (apsnd SOME) rejects)
blanchet@38739
   300
            else
blanchet@38739
   301
              (* Add "add:" facts. *)
blanchet@38739
   302
              if null add_thms then
blanchet@38739
   303
                []
blanchet@38594
   304
              else
blanchet@38739
   305
                map_filter (fn ((p as (_, th), _), _) =>
blanchet@38739
   306
                               if member Thm.eq_thm add_thms th then SOME p
blanchet@38739
   307
                               else NONE) rejects
blanchet@38739
   308
          | relevant (new_pairs, rejects) [] =
blanchet@38739
   309
            let
blanchet@38739
   310
              val (new_rels, more_rejects) =
blanchet@38739
   311
                take_best max_relevant_per_iter new_pairs
blanchet@38739
   312
              val rel_const_tab' =
blanchet@38739
   313
                rel_const_tab |> fold add_const_to_table (maps snd new_rels)
blanchet@38739
   314
              fun is_dirty c =
blanchet@38739
   315
                const_mem rel_const_tab' c andalso
blanchet@38739
   316
                not (const_mem rel_const_tab c)
blanchet@38739
   317
              val rejects =
blanchet@38739
   318
                more_rejects @ rejects
blanchet@38739
   319
                |> map (fn (ax as (_, consts), old_weight) =>
blanchet@38739
   320
                           (ax, if exists is_dirty consts then NONE
blanchet@38739
   321
                                else SOME old_weight))
blanchet@38739
   322
              val threshold = threshold + (1.0 - threshold) * relevance_decay
blanchet@38739
   323
            in
blanchet@38739
   324
              trace_msg (fn () => "relevant this iteration: " ^
blanchet@38739
   325
                                  Int.toString (length new_rels));
blanchet@38739
   326
              map #1 new_rels @ iter (j + 1) threshold rel_const_tab' rejects
blanchet@38739
   327
            end
blanchet@38739
   328
          | relevant (new_rels, rejects)
blanchet@38739
   329
                     (((ax as ((name, th), axiom_consts)), cached_weight)
blanchet@38739
   330
                      :: rest) =
blanchet@38739
   331
            let
blanchet@38739
   332
              val weight =
blanchet@38739
   333
                case cached_weight of
blanchet@38739
   334
                  SOME w => w
blanchet@38739
   335
                | NONE => axiom_weight const_tab rel_const_tab axiom_consts
blanchet@38739
   336
            in
blanchet@38741
   337
              if weight >= threshold then
blanchet@38739
   338
                (trace_msg (fn () =>
blanchet@38739
   339
                     fst (name ()) ^ " passes: " ^ Real.toString weight
blanchet@38739
   340
                     ^ " consts: " ^ commas (map fst axiom_consts));
blanchet@38739
   341
                 relevant ((ax, weight) :: new_rels, rejects) rest)
blanchet@38739
   342
              else
blanchet@38739
   343
                relevant (new_rels, (ax, weight) :: rejects) rest
blanchet@38739
   344
            end
blanchet@38739
   345
        in
blanchet@38739
   346
          trace_msg (fn () => "relevant_facts, current threshold: " ^
blanchet@38739
   347
                              Real.toString threshold);
blanchet@38739
   348
          relevant ([], [])
blanchet@38739
   349
        end
blanchet@38739
   350
  in
blanchet@38739
   351
    axioms |> filter_out (member Thm.eq_thm del_thms o snd)
blanchet@38739
   352
           |> map (rpair NONE o pair_consts_axiom theory_relevant thy)
blanchet@38739
   353
           |> iter 0 relevance_threshold goal_const_tab
blanchet@38739
   354
           |> tap (fn res => trace_msg (fn () =>
blanchet@38686
   355
                                "Total relevant: " ^ Int.toString (length res)))
blanchet@38739
   356
  end
paulson@24287
   357
paulson@24287
   358
(***************************************************************)
mengj@19768
   359
(* Retrieving and filtering lemmas                             *)
mengj@19768
   360
(***************************************************************)
mengj@19768
   361
paulson@33022
   362
(*** retrieve lemmas and filter them ***)
mengj@19768
   363
paulson@20757
   364
(*Reject theorems with names like "List.filter.filter_list_def" or
paulson@21690
   365
  "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
paulson@20757
   366
fun is_package_def a =
wenzelm@30364
   367
  let val names = Long_Name.explode a
paulson@21690
   368
  in
paulson@21690
   369
     length names > 2 andalso
paulson@21690
   370
     not (hd names = "local") andalso
paulson@21690
   371
     String.isSuffix "_def" a  orelse  String.isSuffix "_defs" a
paulson@21690
   372
  end;
paulson@20757
   373
blanchet@38085
   374
fun make_fact_table xs =
blanchet@37616
   375
  fold (Termtab.update o `(prop_of o snd)) xs Termtab.empty
blanchet@38085
   376
fun make_unique xs = Termtab.fold (cons o snd) (make_fact_table xs) []
mengj@19768
   377
blanchet@37626
   378
(* FIXME: put other record thms here, or declare as "no_atp" *)
blanchet@37626
   379
val multi_base_blacklist =
blanchet@37626
   380
  ["defs", "select_defs", "update_defs", "induct", "inducts", "split", "splits",
blanchet@38682
   381
   "split_asm", "cases", "ext_cases", "eq.simps", "eq.refl", "nchotomy",
blanchet@38682
   382
   "case_cong", "weak_case_cong"]
blanchet@38682
   383
  |> map (prefix ".")
blanchet@37626
   384
blanchet@37626
   385
val max_lambda_nesting = 3
blanchet@37626
   386
blanchet@37626
   387
fun term_has_too_many_lambdas max (t1 $ t2) =
blanchet@37626
   388
    exists (term_has_too_many_lambdas max) [t1, t2]
blanchet@37626
   389
  | term_has_too_many_lambdas max (Abs (_, _, t)) =
blanchet@37626
   390
    max = 0 orelse term_has_too_many_lambdas (max - 1) t
blanchet@37626
   391
  | term_has_too_many_lambdas _ _ = false
blanchet@37626
   392
blanchet@37626
   393
(* Don't count nested lambdas at the level of formulas, since they are
blanchet@37626
   394
   quantifiers. *)
blanchet@37626
   395
fun formula_has_too_many_lambdas Ts (Abs (_, T, t)) =
blanchet@37626
   396
    formula_has_too_many_lambdas (T :: Ts) t
blanchet@37626
   397
  | formula_has_too_many_lambdas Ts t =
blanchet@37626
   398
    if is_formula_type (fastype_of1 (Ts, t)) then
blanchet@37626
   399
      exists (formula_has_too_many_lambdas Ts) (#2 (strip_comb t))
blanchet@37626
   400
    else
blanchet@37626
   401
      term_has_too_many_lambdas max_lambda_nesting t
blanchet@37626
   402
blanchet@38692
   403
(* The max apply depth of any "metis" call in "Metis_Examples" (on 2007-10-31)
blanchet@37626
   404
   was 11. *)
blanchet@37626
   405
val max_apply_depth = 15
blanchet@37626
   406
blanchet@37626
   407
fun apply_depth (f $ t) = Int.max (apply_depth f, apply_depth t + 1)
blanchet@37626
   408
  | apply_depth (Abs (_, _, t)) = apply_depth t
blanchet@37626
   409
  | apply_depth _ = 0
blanchet@37626
   410
blanchet@37626
   411
fun is_formula_too_complex t =
blanchet@38085
   412
  apply_depth t > max_apply_depth orelse formula_has_too_many_lambdas [] t
blanchet@37626
   413
blanchet@37543
   414
val exists_sledgehammer_const =
blanchet@37626
   415
  exists_Const (fn (s, _) => String.isPrefix sledgehammer_prefix s)
blanchet@37626
   416
blanchet@38652
   417
fun is_strange_theorem th =
blanchet@37626
   418
  case head_of (concl_of th) of
blanchet@37626
   419
      Const (a, _) => (a <> @{const_name Trueprop} andalso
blanchet@37626
   420
                       a <> @{const_name "=="})
blanchet@37626
   421
    | _ => false
blanchet@37626
   422
blanchet@37626
   423
val type_has_top_sort =
blanchet@37626
   424
  exists_subtype (fn TFree (_, []) => true | TVar (_, []) => true | _ => false)
blanchet@37626
   425
blanchet@38085
   426
(**** Predicates to detect unwanted facts (prolific or likely to cause
blanchet@37347
   427
      unsoundness) ****)
paulson@21470
   428
blanchet@38289
   429
(* Too general means, positive equality literal with a variable X as one
blanchet@38289
   430
   operand, when X does not occur properly in the other operand. This rules out
blanchet@38289
   431
   clearly inconsistent facts such as X = a | X = b, though it by no means
blanchet@38289
   432
   guarantees soundness. *)
paulson@21470
   433
blanchet@38289
   434
(* Unwanted equalities are those between a (bound or schematic) variable that
blanchet@38289
   435
   does not properly occur in the second operand. *)
blanchet@38607
   436
val is_exhaustive_finite =
blanchet@38607
   437
  let
blanchet@38629
   438
    fun is_bad_equal (Var z) t =
blanchet@38629
   439
        not (exists_subterm (fn Var z' => z = z' | _ => false) t)
blanchet@38629
   440
      | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
blanchet@38629
   441
      | is_bad_equal _ _ = false
blanchet@38629
   442
    fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
blanchet@38607
   443
    fun do_formula pos t =
blanchet@38607
   444
      case (pos, t) of
blanchet@38615
   445
        (_, @{const Trueprop} $ t1) => do_formula pos t1
blanchet@38607
   446
      | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
blanchet@38607
   447
        do_formula pos t'
blanchet@38607
   448
      | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
blanchet@38607
   449
        do_formula pos t'
blanchet@38607
   450
      | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
blanchet@38607
   451
        do_formula pos t'
blanchet@38607
   452
      | (_, @{const "==>"} $ t1 $ t2) =>
blanchet@38629
   453
        do_formula (not pos) t1 andalso
blanchet@38629
   454
        (t2 = @{prop False} orelse do_formula pos t2)
blanchet@38607
   455
      | (_, @{const "op -->"} $ t1 $ t2) =>
blanchet@38629
   456
        do_formula (not pos) t1 andalso
blanchet@38629
   457
        (t2 = @{const False} orelse do_formula pos t2)
blanchet@38607
   458
      | (_, @{const Not} $ t1) => do_formula (not pos) t1
blanchet@38607
   459
      | (true, @{const "op |"} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@38607
   460
      | (false, @{const "op &"} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@38607
   461
      | (true, Const (@{const_name "op ="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38607
   462
      | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38607
   463
      | _ => false
blanchet@38607
   464
  in do_formula true end
blanchet@38607
   465
blanchet@38592
   466
fun has_bound_or_var_of_type tycons =
blanchet@38592
   467
  exists_subterm (fn Var (_, Type (s, _)) => member (op =) tycons s
blanchet@38592
   468
                   | Abs (_, Type (s, _), _) => member (op =) tycons s
blanchet@38592
   469
                   | _ => false)
paulson@21431
   470
blanchet@38085
   471
(* Facts are forbidden to contain variables of these types. The typical reason
blanchet@37347
   472
   is that they lead to unsoundness. Note that "unit" satisfies numerous
blanchet@38085
   473
   equations like "?x = ()". The resulting clauses will have no type constraint,
blanchet@37347
   474
   yielding false proofs. Even "bool" leads to many unsound proofs, though only
blanchet@37347
   475
   for higher-order problems. *)
blanchet@38592
   476
val dangerous_types = [@{type_name unit}, @{type_name bool}, @{type_name prop}];
paulson@22217
   477
blanchet@38085
   478
(* Facts containing variables of type "unit" or "bool" or of the form
blanchet@38290
   479
   "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
blanchet@38290
   480
   are omitted. *)
blanchet@38593
   481
fun is_dangerous_term full_types t =
blanchet@38609
   482
  not full_types andalso
blanchet@38679
   483
  let val t = transform_elim_term t in
blanchet@38679
   484
    has_bound_or_var_of_type dangerous_types t orelse
blanchet@38679
   485
    is_exhaustive_finite t
blanchet@38679
   486
  end
paulson@21470
   487
blanchet@38627
   488
fun is_theorem_bad_for_atps full_types thm =
blanchet@38627
   489
  let val t = prop_of thm in
blanchet@38627
   490
    is_formula_too_complex t orelse exists_type type_has_top_sort t orelse
blanchet@38627
   491
    is_dangerous_term full_types t orelse exists_sledgehammer_const t orelse
blanchet@38652
   492
    is_strange_theorem thm
blanchet@38627
   493
  end
blanchet@38627
   494
blanchet@38696
   495
fun all_name_thms_pairs ctxt reserved full_types add_thms chained_ths =
blanchet@38627
   496
  let
blanchet@38697
   497
    val is_chained = member Thm.eq_thm chained_ths
blanchet@38697
   498
    val global_facts = PureThy.facts_of (ProofContext.theory_of ctxt)
blanchet@38644
   499
    val local_facts = ProofContext.facts_of ctxt
blanchet@38644
   500
    val named_locals = local_facts |> Facts.dest_static []
blanchet@38697
   501
    (* Unnamed, not chained formulas with schematic variables are omitted,
blanchet@38697
   502
       because they are rejected by the backticks (`...`) parser for some
blanchet@38697
   503
       reason. *)
blanchet@38738
   504
    fun is_good_unnamed_local th =
blanchet@38738
   505
      forall (fn (_, ths) => not (member Thm.eq_thm ths th)) named_locals
blanchet@38738
   506
      andalso (not (exists_subterm is_Var (prop_of th)) orelse (is_chained th))
blanchet@38644
   507
    val unnamed_locals =
blanchet@38738
   508
      local_facts |> Facts.props |> filter is_good_unnamed_local
blanchet@38697
   509
                  |> map (pair "" o single)
blanchet@38627
   510
    val full_space =
blanchet@38738
   511
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts)
blanchet@38697
   512
    fun add_valid_facts foldx facts =
blanchet@38699
   513
      foldx (fn (name0, ths) =>
blanchet@38699
   514
        if name0 <> "" andalso
blanchet@38699
   515
           forall (not o member Thm.eq_thm add_thms) ths andalso
blanchet@38699
   516
           (Facts.is_concealed facts name0 orelse
blanchet@38699
   517
            (respect_no_atp andalso is_package_def name0) orelse
blanchet@38699
   518
            exists (fn s => String.isSuffix s name0) multi_base_blacklist orelse
blanchet@38699
   519
            String.isSuffix "_def_raw" (* FIXME: crude hack *) name0) then
blanchet@38627
   520
          I
blanchet@38627
   521
        else
blanchet@38627
   522
          let
blanchet@38699
   523
            val multi = length ths > 1
blanchet@38696
   524
            fun backquotify th =
blanchet@38696
   525
              "`" ^ Print_Mode.setmp [Print_Mode.input]
blanchet@38696
   526
                                 (Syntax.string_of_term ctxt) (prop_of th) ^ "`"
blanchet@38738
   527
              |> String.translate (fn c => if Char.isPrint c then str c else "")
blanchet@38738
   528
              |> simplify_spaces
blanchet@38699
   529
            fun check_thms a =
blanchet@38699
   530
              case try (ProofContext.get_thms ctxt) a of
blanchet@38699
   531
                NONE => false
blanchet@38699
   532
              | SOME ths' => Thm.eq_thms (ths, ths')
blanchet@38627
   533
          in
blanchet@38699
   534
            pair 1
blanchet@38699
   535
            #> fold (fn th => fn (j, rest) =>
blanchet@38699
   536
                 (j + 1,
blanchet@38699
   537
                  if is_theorem_bad_for_atps full_types th andalso
blanchet@38699
   538
                     not (member Thm.eq_thm add_thms th) then
blanchet@38699
   539
                    rest
blanchet@38699
   540
                  else
blanchet@38699
   541
                    (fn () =>
blanchet@38699
   542
                        (if name0 = "" then
blanchet@38699
   543
                           th |> backquotify
blanchet@38699
   544
                         else
blanchet@38699
   545
                           let
blanchet@38699
   546
                             val name1 = Facts.extern facts name0
blanchet@38699
   547
                             val name2 = Name_Space.extern full_space name0
blanchet@38699
   548
                           in
blanchet@38699
   549
                             case find_first check_thms [name1, name2, name0] of
blanchet@38699
   550
                               SOME name =>
blanchet@38699
   551
                               let
blanchet@38699
   552
                                 val name =
blanchet@38699
   553
                                   name |> Symtab.defined reserved name ? quote
blanchet@38699
   554
                               in
blanchet@38699
   555
                                 if multi then name ^ "(" ^ Int.toString j ^ ")"
blanchet@38699
   556
                                 else name
blanchet@38699
   557
                               end
blanchet@38699
   558
                             | NONE => ""
blanchet@38699
   559
                           end, is_chained th), (multi, th)) :: rest)) ths
blanchet@38699
   560
            #> snd
blanchet@38627
   561
          end)
blanchet@38644
   562
  in
blanchet@38688
   563
    [] |> add_valid_facts fold local_facts (unnamed_locals @ named_locals)
blanchet@38688
   564
       |> add_valid_facts Facts.fold_static global_facts global_facts
blanchet@38644
   565
  end
blanchet@38627
   566
blanchet@38627
   567
(* The single-name theorems go after the multiple-name ones, so that single
blanchet@38627
   568
   names are preferred when both are available. *)
blanchet@38699
   569
fun name_thm_pairs ctxt respect_no_atp =
blanchet@38699
   570
  List.partition (fst o snd) #> op @
blanchet@38699
   571
  #> map (apsnd snd)
blanchet@38699
   572
  #> respect_no_atp ? filter_out (No_ATPs.member ctxt o snd)
blanchet@38627
   573
blanchet@38627
   574
(***************************************************************)
blanchet@38627
   575
(* ATP invocation methods setup                                *)
blanchet@38627
   576
(***************************************************************)
blanchet@38627
   577
blanchet@38741
   578
fun relevant_facts full_types relevance_threshold relevance_decay
blanchet@38739
   579
                   max_relevant_per_iter theory_relevant
blanchet@37347
   580
                   (relevance_override as {add, del, only})
blanchet@37995
   581
                   (ctxt, (chained_ths, _)) hyp_ts concl_t =
blanchet@37538
   582
  let
blanchet@37538
   583
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@38696
   584
    val reserved = reserved_isar_keyword_table ()
blanchet@37538
   585
    val axioms =
blanchet@38699
   586
      (if only then
blanchet@38699
   587
         maps ((fn (n, ths) => map (pair n o pair false) ths)
blanchet@38699
   588
               o name_thms_pair_from_ref ctxt reserved chained_ths) add
blanchet@38699
   589
       else
blanchet@38699
   590
         all_name_thms_pairs ctxt reserved full_types add_thms chained_ths)
blanchet@38688
   591
      |> name_thm_pairs ctxt (respect_no_atp andalso not only)
blanchet@38595
   592
      |> make_unique
blanchet@37538
   593
  in
blanchet@38688
   594
    trace_msg (fn () => "Considering " ^ Int.toString (length axioms) ^
blanchet@38688
   595
                        " theorems");
blanchet@38739
   596
    (if relevance_threshold > 1.0 then
blanchet@38739
   597
       []
blanchet@38739
   598
     else if relevance_threshold < 0.0 then
blanchet@38739
   599
       axioms
blanchet@38739
   600
     else
blanchet@38741
   601
       relevance_filter ctxt relevance_threshold relevance_decay
blanchet@38739
   602
                        max_relevant_per_iter theory_relevant relevance_override
blanchet@38739
   603
                        axioms (concl_t :: hyp_ts))
blanchet@38699
   604
    |> map (apfst (fn f => f ()))
blanchet@38698
   605
    |> sort_wrt (fst o fst)
blanchet@37538
   606
  end
immler@30536
   607
paulson@15347
   608
end;