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