src/HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
author blanchet
Wed Aug 25 09:32:43 2010 +0200 (2010-08-25 ago)
changeset 38741 7635bf8918a1
parent 38739 8b8ed80b5699
child 38742 4fe1bb9e7434
permissions -rw-r--r--
get rid of "defs_relevant" feature;
nobody uses it and it works poorly
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
paulson@24287
   167
(*A two-dimensional symbol table counts frequencies of constants. It's keyed first by
paulson@24287
   168
  constant name and second by its list of type instantiations. For the latter, we need
paulson@24287
   169
  a linear ordering on type const_typ list.*)
blanchet@37505
   170
paulson@24287
   171
local
paulson@24287
   172
paulson@24287
   173
fun cons_nr CTVar = 0
paulson@24287
   174
  | cons_nr (CType _) = 1;
paulson@24287
   175
paulson@24287
   176
in
paulson@24287
   177
paulson@24287
   178
fun const_typ_ord TU =
paulson@24287
   179
  case TU of
paulson@24287
   180
    (CType (a, Ts), CType (b, Us)) =>
paulson@24287
   181
      (case fast_string_ord(a,b) of EQUAL => dict_ord const_typ_ord (Ts,Us) | ord => ord)
paulson@24287
   182
  | (T, U) => int_ord (cons_nr T, cons_nr U);
paulson@24287
   183
paulson@24287
   184
end;
paulson@24287
   185
wenzelm@31971
   186
structure CTtab = Table(type key = const_typ list val ord = dict_ord const_typ_ord);
paulson@24287
   187
blanchet@37616
   188
fun count_axiom_consts theory_relevant thy (_, th) =
blanchet@37503
   189
  let
blanchet@37503
   190
    fun do_const (a, T) =
blanchet@38606
   191
      let val (c, cts) = const_with_typ thy (a, T) in
blanchet@37503
   192
        (* Two-dimensional table update. Constant maps to types maps to
blanchet@37503
   193
           count. *)
blanchet@37503
   194
        CTtab.map_default (cts, 0) (Integer.add 1)
blanchet@37503
   195
        |> Symtab.map_default (c, CTtab.empty)
blanchet@37503
   196
      end
blanchet@37503
   197
    fun do_term (Const x) = do_const x
blanchet@37503
   198
      | do_term (Free x) = do_const x
blanchet@37503
   199
      | do_term (t $ u) = do_term t #> do_term u
blanchet@37503
   200
      | do_term (Abs (_, _, t)) = do_term t
blanchet@37503
   201
      | do_term _ = I
blanchet@37616
   202
  in th |> theory_const_prop_of theory_relevant |> do_term end
paulson@24287
   203
paulson@24287
   204
paulson@24287
   205
(**** Actual Filtering Code ****)
paulson@24287
   206
paulson@24287
   207
(*The frequency of a constant is the sum of those of all instances of its type.*)
blanchet@37505
   208
fun const_frequency const_tab (c, cts) =
blanchet@36185
   209
  CTtab.fold (fn (cts', m) => match_types cts cts' ? Integer.add m)
blanchet@38686
   210
             (the (Symtab.lookup const_tab c)) 0
blanchet@38686
   211
  handle Option.Option => 0
blanchet@38686
   212
paulson@24287
   213
blanchet@38085
   214
(* A surprising number of theorems contain only a few significant constants.
blanchet@38085
   215
   These include all induction rules, and other general theorems. *)
blanchet@37503
   216
blanchet@37503
   217
(* "log" seems best in practice. A constant function of one ignores the constant
blanchet@37503
   218
   frequencies. *)
blanchet@38686
   219
fun rel_log (x : real) = 1.0 + 2.0 / Math.ln (x + 1.0)
blanchet@38686
   220
fun irrel_log (x : real) = Math.ln (x + 19.0) / 6.4
blanchet@37503
   221
blanchet@37503
   222
(* Computes a constant's weight, as determined by its frequency. *)
blanchet@38686
   223
val rel_const_weight = rel_log o real oo const_frequency
blanchet@38686
   224
val irrel_const_weight = irrel_log o real oo const_frequency
blanchet@38692
   225
(* fun irrel_const_weight _ _ = 1.0  FIXME: OLD CODE *)
paulson@24287
   226
blanchet@38687
   227
fun axiom_weight const_tab relevant_consts axiom_consts =
blanchet@38686
   228
  let
blanchet@38687
   229
    val (rel, irrel) = List.partition (const_mem relevant_consts) axiom_consts
blanchet@38686
   230
    val rel_weight = fold (curry Real.+ o rel_const_weight const_tab) rel 0.0
blanchet@38686
   231
    val irrel_weight = fold (curry Real.+ o irrel_const_weight const_tab) irrel 0.0
blanchet@38686
   232
    val res = rel_weight / (rel_weight + irrel_weight)
blanchet@38686
   233
  in if Real.isFinite res then res else 0.0 end
blanchet@38686
   234
blanchet@38686
   235
(* OLD CODE:
blanchet@37505
   236
(*Relevant constants are weighted according to frequency,
paulson@24287
   237
  but irrelevant constants are simply counted. Otherwise, Skolem functions,
blanchet@38085
   238
  which are rare, would harm a formula's chances of being picked.*)
blanchet@38687
   239
fun axiom_weight const_tab relevant_consts axiom_consts =
blanchet@38101
   240
  let
blanchet@38687
   241
    val rel = filter (const_mem relevant_consts) axiom_consts
blanchet@38686
   242
    val rel_weight = fold (curry Real.+ o rel_const_weight const_tab) rel 0.0
blanchet@38687
   243
    val res = rel_weight / (rel_weight + real (length axiom_consts - length rel))
blanchet@38101
   244
  in if Real.isFinite res then res else 0.0 end
blanchet@38686
   245
*)
blanchet@37505
   246
blanchet@38741
   247
(* Multiplies out to a list of pairs: 'a * 'b list -> ('a * 'b) list
blanchet@38741
   248
   -> ('a * 'b) list. *)
blanchet@38679
   249
fun add_expand_pairs (x, ys) xys = List.foldl (fn (y,acc) => (x,y)::acc) xys ys
blanchet@38687
   250
fun consts_of_term thy t =
blanchet@38687
   251
  Symtab.fold add_expand_pairs (get_consts thy (SOME true) [t]) []
paulson@24287
   252
blanchet@38687
   253
fun pair_consts_axiom theory_relevant thy axiom =
blanchet@37616
   254
  (axiom, axiom |> snd |> theory_const_prop_of theory_relevant
blanchet@38687
   255
                |> consts_of_term thy)
paulson@24287
   256
blanchet@38699
   257
type annotated_thm =
blanchet@38699
   258
  ((unit -> string * bool) * thm) * (string * const_typ list) list
blanchet@37505
   259
paulson@24287
   260
(*For a reverse sort, putting the largest values first.*)
blanchet@37500
   261
fun compare_pairs ((_, w1), (_, w2)) = Real.compare (w2, w1)
paulson@24287
   262
blanchet@38085
   263
(* Limit the number of new facts, to prevent runaway acceptance. *)
blanchet@38739
   264
fun take_best max_relevant_per_iter (new_pairs : (annotated_thm * real) list) =
blanchet@38687
   265
  let val nnew = length new_pairs in
blanchet@38739
   266
    if nnew <= max_relevant_per_iter then
blanchet@38687
   267
      (map #1 new_pairs, [])
blanchet@37505
   268
    else
blanchet@38587
   269
      let
blanchet@38687
   270
        val new_pairs = sort compare_pairs new_pairs
blanchet@38739
   271
        val accepted = List.take (new_pairs, max_relevant_per_iter)
paulson@24287
   272
      in
blanchet@37505
   273
        trace_msg (fn () => ("Number of candidates, " ^ Int.toString nnew ^
blanchet@38739
   274
               ", exceeds the limit of " ^ Int.toString max_relevant_per_iter));
blanchet@35865
   275
        trace_msg (fn () => ("Effective pass mark: " ^ Real.toString (#2 (List.last accepted))));
blanchet@35865
   276
        trace_msg (fn () => "Actually passed: " ^
blanchet@38699
   277
          space_implode ", " (map (fst o (fn f => f ()) o fst o fst o fst) accepted));
blanchet@38739
   278
        (map #1 accepted, List.drop (new_pairs, max_relevant_per_iter))
paulson@24287
   279
      end
paulson@24287
   280
  end;
paulson@24287
   281
blanchet@38683
   282
val threshold_divisor = 2.0
blanchet@38683
   283
val ridiculous_threshold = 0.1
blanchet@38683
   284
blanchet@38741
   285
fun relevance_filter ctxt relevance_threshold relevance_decay
blanchet@38739
   286
                     max_relevant_per_iter theory_relevant
blanchet@38594
   287
                     ({add, del, ...} : relevance_override) axioms goal_ts =
blanchet@38739
   288
  let
blanchet@38739
   289
    val thy = ProofContext.theory_of ctxt
blanchet@38739
   290
    val const_tab = fold (count_axiom_consts theory_relevant thy) axioms
blanchet@38739
   291
                         Symtab.empty
blanchet@38739
   292
    val goal_const_tab = get_consts thy (SOME false) goal_ts
blanchet@38739
   293
    val _ =
blanchet@38739
   294
      trace_msg (fn () => "Initial constants: " ^
blanchet@38739
   295
                          commas (goal_const_tab |> Symtab.dest
blanchet@38739
   296
                                  |> filter (curry (op <>) [] o snd)
blanchet@38739
   297
                                  |> map fst))
blanchet@38739
   298
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@38739
   299
    val del_thms = maps (ProofContext.get_fact ctxt) del
blanchet@38739
   300
    fun iter j threshold rel_const_tab =
blanchet@38739
   301
      let
blanchet@38739
   302
        fun relevant ([], rejects) [] =
blanchet@38739
   303
            (* Nothing was added this iteration. *)
blanchet@38739
   304
            if j = 0 andalso threshold >= ridiculous_threshold then
blanchet@38739
   305
              (* First iteration? Try again. *)
blanchet@38739
   306
              iter 0 (threshold / threshold_divisor) rel_const_tab
blanchet@38739
   307
                   (map (apsnd SOME) rejects)
blanchet@38739
   308
            else
blanchet@38739
   309
              (* Add "add:" facts. *)
blanchet@38739
   310
              if null add_thms then
blanchet@38739
   311
                []
blanchet@38594
   312
              else
blanchet@38739
   313
                map_filter (fn ((p as (_, th), _), _) =>
blanchet@38739
   314
                               if member Thm.eq_thm add_thms th then SOME p
blanchet@38739
   315
                               else NONE) rejects
blanchet@38739
   316
          | relevant (new_pairs, rejects) [] =
blanchet@38739
   317
            let
blanchet@38739
   318
              val (new_rels, more_rejects) =
blanchet@38739
   319
                take_best max_relevant_per_iter new_pairs
blanchet@38739
   320
              val rel_const_tab' =
blanchet@38739
   321
                rel_const_tab |> fold add_const_to_table (maps snd new_rels)
blanchet@38739
   322
              fun is_dirty c =
blanchet@38739
   323
                const_mem rel_const_tab' c andalso
blanchet@38739
   324
                not (const_mem rel_const_tab c)
blanchet@38739
   325
              val rejects =
blanchet@38739
   326
                more_rejects @ rejects
blanchet@38739
   327
                |> map (fn (ax as (_, consts), old_weight) =>
blanchet@38739
   328
                           (ax, if exists is_dirty consts then NONE
blanchet@38739
   329
                                else SOME old_weight))
blanchet@38739
   330
              val threshold = threshold + (1.0 - threshold) * relevance_decay
blanchet@38739
   331
            in
blanchet@38739
   332
              trace_msg (fn () => "relevant this iteration: " ^
blanchet@38739
   333
                                  Int.toString (length new_rels));
blanchet@38739
   334
              map #1 new_rels @ iter (j + 1) threshold rel_const_tab' rejects
blanchet@38739
   335
            end
blanchet@38739
   336
          | relevant (new_rels, rejects)
blanchet@38739
   337
                     (((ax as ((name, th), axiom_consts)), cached_weight)
blanchet@38739
   338
                      :: rest) =
blanchet@38739
   339
            let
blanchet@38739
   340
              val weight =
blanchet@38739
   341
                case cached_weight of
blanchet@38739
   342
                  SOME w => w
blanchet@38739
   343
                | NONE => axiom_weight const_tab rel_const_tab axiom_consts
blanchet@38739
   344
            in
blanchet@38741
   345
              if weight >= threshold then
blanchet@38739
   346
                (trace_msg (fn () =>
blanchet@38739
   347
                     fst (name ()) ^ " passes: " ^ Real.toString weight
blanchet@38739
   348
                     ^ " consts: " ^ commas (map fst axiom_consts));
blanchet@38739
   349
                 relevant ((ax, weight) :: new_rels, rejects) rest)
blanchet@38739
   350
              else
blanchet@38739
   351
                relevant (new_rels, (ax, weight) :: rejects) rest
blanchet@38739
   352
            end
blanchet@38739
   353
        in
blanchet@38739
   354
          trace_msg (fn () => "relevant_facts, current threshold: " ^
blanchet@38739
   355
                              Real.toString threshold);
blanchet@38739
   356
          relevant ([], [])
blanchet@38739
   357
        end
blanchet@38739
   358
  in
blanchet@38739
   359
    axioms |> filter_out (member Thm.eq_thm del_thms o snd)
blanchet@38739
   360
           |> map (rpair NONE o pair_consts_axiom theory_relevant thy)
blanchet@38739
   361
           |> iter 0 relevance_threshold goal_const_tab
blanchet@38739
   362
           |> tap (fn res => trace_msg (fn () =>
blanchet@38686
   363
                                "Total relevant: " ^ Int.toString (length res)))
blanchet@38739
   364
  end
paulson@24287
   365
paulson@24287
   366
(***************************************************************)
mengj@19768
   367
(* Retrieving and filtering lemmas                             *)
mengj@19768
   368
(***************************************************************)
mengj@19768
   369
paulson@33022
   370
(*** retrieve lemmas and filter them ***)
mengj@19768
   371
paulson@20757
   372
(*Reject theorems with names like "List.filter.filter_list_def" or
paulson@21690
   373
  "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
paulson@20757
   374
fun is_package_def a =
wenzelm@30364
   375
  let val names = Long_Name.explode a
paulson@21690
   376
  in
paulson@21690
   377
     length names > 2 andalso
paulson@21690
   378
     not (hd names = "local") andalso
paulson@21690
   379
     String.isSuffix "_def" a  orelse  String.isSuffix "_defs" a
paulson@21690
   380
  end;
paulson@20757
   381
blanchet@38085
   382
fun make_fact_table xs =
blanchet@37616
   383
  fold (Termtab.update o `(prop_of o snd)) xs Termtab.empty
blanchet@38085
   384
fun make_unique xs = Termtab.fold (cons o snd) (make_fact_table xs) []
mengj@19768
   385
blanchet@37626
   386
(* FIXME: put other record thms here, or declare as "no_atp" *)
blanchet@37626
   387
val multi_base_blacklist =
blanchet@37626
   388
  ["defs", "select_defs", "update_defs", "induct", "inducts", "split", "splits",
blanchet@38682
   389
   "split_asm", "cases", "ext_cases", "eq.simps", "eq.refl", "nchotomy",
blanchet@38682
   390
   "case_cong", "weak_case_cong"]
blanchet@38682
   391
  |> map (prefix ".")
blanchet@37626
   392
blanchet@37626
   393
val max_lambda_nesting = 3
blanchet@37626
   394
blanchet@37626
   395
fun term_has_too_many_lambdas max (t1 $ t2) =
blanchet@37626
   396
    exists (term_has_too_many_lambdas max) [t1, t2]
blanchet@37626
   397
  | term_has_too_many_lambdas max (Abs (_, _, t)) =
blanchet@37626
   398
    max = 0 orelse term_has_too_many_lambdas (max - 1) t
blanchet@37626
   399
  | term_has_too_many_lambdas _ _ = false
blanchet@37626
   400
blanchet@37626
   401
(* Don't count nested lambdas at the level of formulas, since they are
blanchet@37626
   402
   quantifiers. *)
blanchet@37626
   403
fun formula_has_too_many_lambdas Ts (Abs (_, T, t)) =
blanchet@37626
   404
    formula_has_too_many_lambdas (T :: Ts) t
blanchet@37626
   405
  | formula_has_too_many_lambdas Ts t =
blanchet@37626
   406
    if is_formula_type (fastype_of1 (Ts, t)) then
blanchet@37626
   407
      exists (formula_has_too_many_lambdas Ts) (#2 (strip_comb t))
blanchet@37626
   408
    else
blanchet@37626
   409
      term_has_too_many_lambdas max_lambda_nesting t
blanchet@37626
   410
blanchet@38692
   411
(* The max apply depth of any "metis" call in "Metis_Examples" (on 2007-10-31)
blanchet@37626
   412
   was 11. *)
blanchet@37626
   413
val max_apply_depth = 15
blanchet@37626
   414
blanchet@37626
   415
fun apply_depth (f $ t) = Int.max (apply_depth f, apply_depth t + 1)
blanchet@37626
   416
  | apply_depth (Abs (_, _, t)) = apply_depth t
blanchet@37626
   417
  | apply_depth _ = 0
blanchet@37626
   418
blanchet@37626
   419
fun is_formula_too_complex t =
blanchet@38085
   420
  apply_depth t > max_apply_depth orelse formula_has_too_many_lambdas [] t
blanchet@37626
   421
blanchet@37543
   422
val exists_sledgehammer_const =
blanchet@37626
   423
  exists_Const (fn (s, _) => String.isPrefix sledgehammer_prefix s)
blanchet@37626
   424
blanchet@38652
   425
fun is_strange_theorem th =
blanchet@37626
   426
  case head_of (concl_of th) of
blanchet@37626
   427
      Const (a, _) => (a <> @{const_name Trueprop} andalso
blanchet@37626
   428
                       a <> @{const_name "=="})
blanchet@37626
   429
    | _ => false
blanchet@37626
   430
blanchet@37626
   431
val type_has_top_sort =
blanchet@37626
   432
  exists_subtype (fn TFree (_, []) => true | TVar (_, []) => true | _ => false)
blanchet@37626
   433
blanchet@38085
   434
(**** Predicates to detect unwanted facts (prolific or likely to cause
blanchet@37347
   435
      unsoundness) ****)
paulson@21470
   436
blanchet@38289
   437
(* Too general means, positive equality literal with a variable X as one
blanchet@38289
   438
   operand, when X does not occur properly in the other operand. This rules out
blanchet@38289
   439
   clearly inconsistent facts such as X = a | X = b, though it by no means
blanchet@38289
   440
   guarantees soundness. *)
paulson@21470
   441
blanchet@38289
   442
(* Unwanted equalities are those between a (bound or schematic) variable that
blanchet@38289
   443
   does not properly occur in the second operand. *)
blanchet@38607
   444
val is_exhaustive_finite =
blanchet@38607
   445
  let
blanchet@38629
   446
    fun is_bad_equal (Var z) t =
blanchet@38629
   447
        not (exists_subterm (fn Var z' => z = z' | _ => false) t)
blanchet@38629
   448
      | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
blanchet@38629
   449
      | is_bad_equal _ _ = false
blanchet@38629
   450
    fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
blanchet@38607
   451
    fun do_formula pos t =
blanchet@38607
   452
      case (pos, t) of
blanchet@38615
   453
        (_, @{const Trueprop} $ t1) => do_formula pos t1
blanchet@38607
   454
      | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
blanchet@38607
   455
        do_formula pos t'
blanchet@38607
   456
      | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
blanchet@38607
   457
        do_formula pos t'
blanchet@38607
   458
      | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
blanchet@38607
   459
        do_formula pos t'
blanchet@38607
   460
      | (_, @{const "==>"} $ t1 $ t2) =>
blanchet@38629
   461
        do_formula (not pos) t1 andalso
blanchet@38629
   462
        (t2 = @{prop False} orelse do_formula pos t2)
blanchet@38607
   463
      | (_, @{const "op -->"} $ t1 $ t2) =>
blanchet@38629
   464
        do_formula (not pos) t1 andalso
blanchet@38629
   465
        (t2 = @{const False} orelse do_formula pos t2)
blanchet@38607
   466
      | (_, @{const Not} $ t1) => do_formula (not pos) t1
blanchet@38607
   467
      | (true, @{const "op |"} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@38607
   468
      | (false, @{const "op &"} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@38607
   469
      | (true, Const (@{const_name "op ="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38607
   470
      | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38607
   471
      | _ => false
blanchet@38607
   472
  in do_formula true end
blanchet@38607
   473
blanchet@38592
   474
fun has_bound_or_var_of_type tycons =
blanchet@38592
   475
  exists_subterm (fn Var (_, Type (s, _)) => member (op =) tycons s
blanchet@38592
   476
                   | Abs (_, Type (s, _), _) => member (op =) tycons s
blanchet@38592
   477
                   | _ => false)
paulson@21431
   478
blanchet@38085
   479
(* Facts are forbidden to contain variables of these types. The typical reason
blanchet@37347
   480
   is that they lead to unsoundness. Note that "unit" satisfies numerous
blanchet@38085
   481
   equations like "?x = ()". The resulting clauses will have no type constraint,
blanchet@37347
   482
   yielding false proofs. Even "bool" leads to many unsound proofs, though only
blanchet@37347
   483
   for higher-order problems. *)
blanchet@38592
   484
val dangerous_types = [@{type_name unit}, @{type_name bool}, @{type_name prop}];
paulson@22217
   485
blanchet@38085
   486
(* Facts containing variables of type "unit" or "bool" or of the form
blanchet@38290
   487
   "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
blanchet@38290
   488
   are omitted. *)
blanchet@38593
   489
fun is_dangerous_term full_types t =
blanchet@38609
   490
  not full_types andalso
blanchet@38679
   491
  let val t = transform_elim_term t in
blanchet@38679
   492
    has_bound_or_var_of_type dangerous_types t orelse
blanchet@38679
   493
    is_exhaustive_finite t
blanchet@38679
   494
  end
paulson@21470
   495
blanchet@38627
   496
fun is_theorem_bad_for_atps full_types thm =
blanchet@38627
   497
  let val t = prop_of thm in
blanchet@38627
   498
    is_formula_too_complex t orelse exists_type type_has_top_sort t orelse
blanchet@38627
   499
    is_dangerous_term full_types t orelse exists_sledgehammer_const t orelse
blanchet@38652
   500
    is_strange_theorem thm
blanchet@38627
   501
  end
blanchet@38627
   502
blanchet@38696
   503
fun all_name_thms_pairs ctxt reserved full_types add_thms chained_ths =
blanchet@38627
   504
  let
blanchet@38697
   505
    val is_chained = member Thm.eq_thm chained_ths
blanchet@38697
   506
    val global_facts = PureThy.facts_of (ProofContext.theory_of ctxt)
blanchet@38644
   507
    val local_facts = ProofContext.facts_of ctxt
blanchet@38644
   508
    val named_locals = local_facts |> Facts.dest_static []
blanchet@38697
   509
    (* Unnamed, not chained formulas with schematic variables are omitted,
blanchet@38697
   510
       because they are rejected by the backticks (`...`) parser for some
blanchet@38697
   511
       reason. *)
blanchet@38738
   512
    fun is_good_unnamed_local th =
blanchet@38738
   513
      forall (fn (_, ths) => not (member Thm.eq_thm ths th)) named_locals
blanchet@38738
   514
      andalso (not (exists_subterm is_Var (prop_of th)) orelse (is_chained th))
blanchet@38644
   515
    val unnamed_locals =
blanchet@38738
   516
      local_facts |> Facts.props |> filter is_good_unnamed_local
blanchet@38697
   517
                  |> map (pair "" o single)
blanchet@38627
   518
    val full_space =
blanchet@38738
   519
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts)
blanchet@38697
   520
    fun add_valid_facts foldx facts =
blanchet@38699
   521
      foldx (fn (name0, ths) =>
blanchet@38699
   522
        if name0 <> "" andalso
blanchet@38699
   523
           forall (not o member Thm.eq_thm add_thms) ths andalso
blanchet@38699
   524
           (Facts.is_concealed facts name0 orelse
blanchet@38699
   525
            (respect_no_atp andalso is_package_def name0) orelse
blanchet@38699
   526
            exists (fn s => String.isSuffix s name0) multi_base_blacklist orelse
blanchet@38699
   527
            String.isSuffix "_def_raw" (* FIXME: crude hack *) name0) then
blanchet@38627
   528
          I
blanchet@38627
   529
        else
blanchet@38627
   530
          let
blanchet@38699
   531
            val multi = length ths > 1
blanchet@38696
   532
            fun backquotify th =
blanchet@38696
   533
              "`" ^ Print_Mode.setmp [Print_Mode.input]
blanchet@38696
   534
                                 (Syntax.string_of_term ctxt) (prop_of th) ^ "`"
blanchet@38738
   535
              |> String.translate (fn c => if Char.isPrint c then str c else "")
blanchet@38738
   536
              |> simplify_spaces
blanchet@38699
   537
            fun check_thms a =
blanchet@38699
   538
              case try (ProofContext.get_thms ctxt) a of
blanchet@38699
   539
                NONE => false
blanchet@38699
   540
              | SOME ths' => Thm.eq_thms (ths, ths')
blanchet@38627
   541
          in
blanchet@38699
   542
            pair 1
blanchet@38699
   543
            #> fold (fn th => fn (j, rest) =>
blanchet@38699
   544
                 (j + 1,
blanchet@38699
   545
                  if is_theorem_bad_for_atps full_types th andalso
blanchet@38699
   546
                     not (member Thm.eq_thm add_thms th) then
blanchet@38699
   547
                    rest
blanchet@38699
   548
                  else
blanchet@38699
   549
                    (fn () =>
blanchet@38699
   550
                        (if name0 = "" then
blanchet@38699
   551
                           th |> backquotify
blanchet@38699
   552
                         else
blanchet@38699
   553
                           let
blanchet@38699
   554
                             val name1 = Facts.extern facts name0
blanchet@38699
   555
                             val name2 = Name_Space.extern full_space name0
blanchet@38699
   556
                           in
blanchet@38699
   557
                             case find_first check_thms [name1, name2, name0] of
blanchet@38699
   558
                               SOME name =>
blanchet@38699
   559
                               let
blanchet@38699
   560
                                 val name =
blanchet@38699
   561
                                   name |> Symtab.defined reserved name ? quote
blanchet@38699
   562
                               in
blanchet@38699
   563
                                 if multi then name ^ "(" ^ Int.toString j ^ ")"
blanchet@38699
   564
                                 else name
blanchet@38699
   565
                               end
blanchet@38699
   566
                             | NONE => ""
blanchet@38699
   567
                           end, is_chained th), (multi, th)) :: rest)) ths
blanchet@38699
   568
            #> snd
blanchet@38627
   569
          end)
blanchet@38644
   570
  in
blanchet@38688
   571
    [] |> add_valid_facts fold local_facts (unnamed_locals @ named_locals)
blanchet@38688
   572
       |> add_valid_facts Facts.fold_static global_facts global_facts
blanchet@38644
   573
  end
blanchet@38627
   574
blanchet@38627
   575
(* The single-name theorems go after the multiple-name ones, so that single
blanchet@38627
   576
   names are preferred when both are available. *)
blanchet@38699
   577
fun name_thm_pairs ctxt respect_no_atp =
blanchet@38699
   578
  List.partition (fst o snd) #> op @
blanchet@38699
   579
  #> map (apsnd snd)
blanchet@38699
   580
  #> respect_no_atp ? filter_out (No_ATPs.member ctxt o snd)
blanchet@38627
   581
blanchet@38627
   582
(***************************************************************)
blanchet@38627
   583
(* ATP invocation methods setup                                *)
blanchet@38627
   584
(***************************************************************)
blanchet@38627
   585
blanchet@38741
   586
fun relevant_facts full_types relevance_threshold relevance_decay
blanchet@38739
   587
                   max_relevant_per_iter theory_relevant
blanchet@37347
   588
                   (relevance_override as {add, del, only})
blanchet@37995
   589
                   (ctxt, (chained_ths, _)) hyp_ts concl_t =
blanchet@37538
   590
  let
blanchet@37538
   591
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@38696
   592
    val reserved = reserved_isar_keyword_table ()
blanchet@37538
   593
    val axioms =
blanchet@38699
   594
      (if only then
blanchet@38699
   595
         maps ((fn (n, ths) => map (pair n o pair false) ths)
blanchet@38699
   596
               o name_thms_pair_from_ref ctxt reserved chained_ths) add
blanchet@38699
   597
       else
blanchet@38699
   598
         all_name_thms_pairs ctxt reserved full_types add_thms chained_ths)
blanchet@38688
   599
      |> name_thm_pairs ctxt (respect_no_atp andalso not only)
blanchet@38595
   600
      |> make_unique
blanchet@37538
   601
  in
blanchet@38688
   602
    trace_msg (fn () => "Considering " ^ Int.toString (length axioms) ^
blanchet@38688
   603
                        " theorems");
blanchet@38739
   604
    (if relevance_threshold > 1.0 then
blanchet@38739
   605
       []
blanchet@38739
   606
     else if relevance_threshold < 0.0 then
blanchet@38739
   607
       axioms
blanchet@38739
   608
     else
blanchet@38741
   609
       relevance_filter ctxt relevance_threshold relevance_decay
blanchet@38739
   610
                        max_relevant_per_iter theory_relevant relevance_override
blanchet@38739
   611
                        axioms (concl_t :: hyp_ts))
blanchet@38699
   612
    |> map (apfst (fn f => f ()))
blanchet@38698
   613
    |> sort_wrt (fst o fst)
blanchet@37538
   614
  end
immler@30536
   615
paulson@15347
   616
end;