src/HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
author blanchet
Mon Aug 23 14:54:17 2010 +0200 (2010-08-23 ago)
changeset 38652 e063be321438
parent 38644 25bbbaf7ce65
child 38679 2cfd0777580f
permissions -rw-r--r--
perform eta-expansion of quantifier bodies in Sledgehammer translation when needed + transform elim rules later;
it's a mistake to transform the elim rules too early because then we lose some info, e.g. "no_atp" attributes
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@38617
    15
  val name_thms_pair_from_ref :
blanchet@38617
    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@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
(* Used to label theorems chained into the goal. *)
blanchet@37616
    40
val chained_prefix = sledgehammer_prefix ^ "chained_"
blanchet@37616
    41
blanchet@38617
    42
fun name_thms_pair_from_ref ctxt chained_ths xref =
blanchet@38617
    43
  let
blanchet@38617
    44
    val ths = ProofContext.get_fact ctxt xref
blanchet@38617
    45
    val name = Facts.string_of_ref xref
blanchet@38617
    46
               |> forall (member Thm.eq_thm chained_ths) ths
blanchet@38617
    47
                  ? prefix chained_prefix
blanchet@38652
    48
  in (name, ths) end
blanchet@38617
    49
blanchet@37616
    50
wenzelm@28477
    51
(***************************************************************)
wenzelm@28477
    52
(* Relevance Filtering                                         *)
wenzelm@28477
    53
(***************************************************************)
mengj@19194
    54
paulson@24287
    55
(*** constants with types ***)
paulson@24287
    56
paulson@24287
    57
(*An abstraction of Isabelle types*)
paulson@24287
    58
datatype const_typ =  CTVar | CType of string * const_typ list
paulson@24287
    59
paulson@24287
    60
(*Is the second type an instance of the first one?*)
blanchet@37505
    61
fun match_type (CType(con1,args1)) (CType(con2,args2)) =
paulson@24287
    62
      con1=con2 andalso match_types args1 args2
paulson@24287
    63
  | match_type CTVar _ = true
paulson@24287
    64
  | match_type _ CTVar = false
paulson@24287
    65
and match_types [] [] = true
paulson@24287
    66
  | match_types (a1::as1) (a2::as2) = match_type a1 a2 andalso match_types as1 as2;
paulson@24287
    67
paulson@24287
    68
(*Is there a unifiable constant?*)
blanchet@37505
    69
fun uni_mem goal_const_tab (c, c_typ) =
blanchet@37505
    70
  exists (match_types c_typ) (these (Symtab.lookup goal_const_tab c))
blanchet@37505
    71
paulson@24287
    72
(*Maps a "real" type to a const_typ*)
blanchet@37505
    73
fun const_typ_of (Type (c,typs)) = CType (c, map const_typ_of typs)
paulson@24287
    74
  | const_typ_of (TFree _) = CTVar
paulson@24287
    75
  | const_typ_of (TVar _) = CTVar
paulson@24287
    76
paulson@24287
    77
(*Pairs a constant with the list of its type instantiations (using const_typ)*)
blanchet@37505
    78
fun const_with_typ thy (c,typ) =
blanchet@38606
    79
  let val tvars = Sign.const_typargs thy (c,typ) in
blanchet@38606
    80
    (c, map const_typ_of tvars) end
blanchet@38606
    81
  handle TYPE _ => (c, [])   (*Variable (locale constant): monomorphic*)
paulson@24287
    82
paulson@24287
    83
(*Add a const/type pair to the table, but a [] entry means a standard connective,
paulson@24287
    84
  which we ignore.*)
blanchet@37502
    85
fun add_const_type_to_table (c, ctyps) =
blanchet@37502
    86
  Symtab.map_default (c, [ctyps])
blanchet@37502
    87
                     (fn [] => [] | ctypss => insert (op =) ctyps ctypss)
paulson@24287
    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@38644
    92
val boring_consts = [@{const_name If}, @{const_name Let}]
blanchet@37537
    93
blanchet@37537
    94
fun get_consts_typs thy pos ts =
blanchet@37505
    95
  let
blanchet@38587
    96
    (* We include free variables, as well as constants, to handle locales. For
blanchet@38587
    97
       each quantifiers that must necessarily be skolemized by the ATP, we
blanchet@38587
    98
       introduce a fresh constant to simulate the effect of Skolemization. *)
blanchet@37537
    99
    fun do_term t =
blanchet@37537
   100
      case t of
blanchet@38606
   101
        Const x => add_const_type_to_table (const_with_typ thy x)
blanchet@38606
   102
      | Free (s, _) => add_const_type_to_table (s, [])
blanchet@37537
   103
      | t1 $ t2 => do_term t1 #> do_term t2
blanchet@38644
   104
      | Abs (_, _, t') => do_term t'
blanchet@37537
   105
      | _ => I
blanchet@38587
   106
    fun do_quantifier will_surely_be_skolemized body_t =
blanchet@37537
   107
      do_formula pos body_t
blanchet@38587
   108
      #> (if will_surely_be_skolemized then
blanchet@38587
   109
            add_const_type_to_table (gensym fresh_prefix, [])
blanchet@38587
   110
          else
blanchet@38587
   111
            I)
blanchet@38587
   112
    and do_term_or_formula T =
blanchet@38592
   113
      if T = @{typ bool} orelse T = @{typ prop} then do_formula NONE
blanchet@38592
   114
      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@37505
   210
             (the (Symtab.lookup const_tab c)
blanchet@37505
   211
              handle Option.Option => raise Fail ("Const: " ^ c)) 0
paulson@24287
   212
blanchet@38085
   213
(* A surprising number of theorems contain only a few significant constants.
blanchet@38085
   214
   These include all induction rules, and other general theorems. *)
blanchet@37503
   215
blanchet@37503
   216
(* "log" seems best in practice. A constant function of one ignores the constant
blanchet@37503
   217
   frequencies. *)
blanchet@37503
   218
fun log_weight2 (x:real) = 1.0 + 2.0 / Math.ln (x + 1.0)
blanchet@37503
   219
blanchet@37503
   220
(* Computes a constant's weight, as determined by its frequency. *)
blanchet@37503
   221
val ct_weight = log_weight2 o real oo const_frequency
paulson@24287
   222
blanchet@37505
   223
(*Relevant constants are weighted according to frequency,
paulson@24287
   224
  but irrelevant constants are simply counted. Otherwise, Skolem functions,
blanchet@38085
   225
  which are rare, would harm a formula's chances of being picked.*)
blanchet@38085
   226
fun formula_weight const_tab gctyps consts_typs =
blanchet@38101
   227
  let
blanchet@38101
   228
    val rel = filter (uni_mem gctyps) consts_typs
blanchet@38101
   229
    val rel_weight = fold (curry Real.+ o ct_weight const_tab) rel 0.0
blanchet@38101
   230
    val res = rel_weight / (rel_weight + real (length consts_typs - length rel))
blanchet@38101
   231
  in if Real.isFinite res then res else 0.0 end
blanchet@37505
   232
paulson@24287
   233
(*Multiplies out to a list of pairs: 'a * 'b list -> ('a * 'b) list -> ('a * 'b) list*)
wenzelm@30190
   234
fun add_expand_pairs (x,ys) xys = List.foldl (fn (y,acc) => (x,y)::acc) xys ys;
paulson@24287
   235
blanchet@37505
   236
fun consts_typs_of_term thy t =
blanchet@38587
   237
  Symtab.fold add_expand_pairs (get_consts_typs thy (SOME true) [t]) []
paulson@24287
   238
blanchet@37505
   239
fun pair_consts_typs_axiom theory_relevant thy axiom =
blanchet@37616
   240
  (axiom, axiom |> snd |> theory_const_prop_of theory_relevant
blanchet@37505
   241
                |> consts_typs_of_term thy)
paulson@24287
   242
blanchet@37505
   243
exception CONST_OR_FREE of unit
blanchet@37505
   244
blanchet@37505
   245
fun dest_Const_or_Free (Const x) = x
blanchet@37505
   246
  | dest_Const_or_Free (Free x) = x
blanchet@37505
   247
  | dest_Const_or_Free _ = raise CONST_OR_FREE ()
paulson@24287
   248
paulson@24287
   249
(*Look for definitions of the form f ?x1 ... ?xn = t, but not reversed.*)
wenzelm@32994
   250
fun defines thy thm gctypes =
paulson@24287
   251
    let val tm = prop_of thm
wenzelm@32960
   252
        fun defs lhs rhs =
paulson@24287
   253
            let val (rator,args) = strip_comb lhs
blanchet@37505
   254
                val ct = const_with_typ thy (dest_Const_or_Free rator)
haftmann@33037
   255
            in
haftmann@33037
   256
              forall is_Var args andalso uni_mem gctypes ct andalso
haftmann@33038
   257
                subset (op =) (Term.add_vars rhs [], Term.add_vars lhs [])
paulson@24287
   258
            end
blanchet@37505
   259
            handle CONST_OR_FREE () => false
blanchet@37505
   260
    in
blanchet@35963
   261
        case tm of
blanchet@37505
   262
          @{const Trueprop} $ (Const (@{const_name "op ="}, _) $ lhs $ rhs) =>
blanchet@37505
   263
            defs lhs rhs
blanchet@35963
   264
        | _ => false
paulson@24287
   265
    end;
paulson@24287
   266
blanchet@38085
   267
type annotated_thm = (string * thm) * (string * const_typ list) list
blanchet@37505
   268
paulson@24287
   269
(*For a reverse sort, putting the largest values first.*)
blanchet@37500
   270
fun compare_pairs ((_, w1), (_, w2)) = Real.compare (w2, w1)
paulson@24287
   271
blanchet@38085
   272
(* Limit the number of new facts, to prevent runaway acceptance. *)
blanchet@38085
   273
fun take_best max_new (newpairs : (annotated_thm * real) list) =
blanchet@38587
   274
  let val nnew = length newpairs in
blanchet@38587
   275
    if nnew <= max_new then
blanchet@38587
   276
      (map #1 newpairs, [])
blanchet@37505
   277
    else
blanchet@38587
   278
      let
blanchet@38587
   279
        val newpairs = sort compare_pairs newpairs
blanchet@38587
   280
        val accepted = List.take (newpairs, max_new)
paulson@24287
   281
      in
blanchet@37505
   282
        trace_msg (fn () => ("Number of candidates, " ^ Int.toString nnew ^
blanchet@38587
   283
                       ", exceeds the limit of " ^ Int.toString max_new));
blanchet@35865
   284
        trace_msg (fn () => ("Effective pass mark: " ^ Real.toString (#2 (List.last accepted))));
blanchet@35865
   285
        trace_msg (fn () => "Actually passed: " ^
blanchet@37616
   286
          space_implode ", " (map (fst o fst o fst) accepted));
blanchet@38587
   287
        (map #1 accepted, map #1 (List.drop (newpairs, max_new)))
paulson@24287
   288
      end
paulson@24287
   289
  end;
paulson@24287
   290
blanchet@36922
   291
fun relevance_filter ctxt relevance_threshold relevance_convergence
blanchet@38594
   292
                     defs_relevant max_new theory_relevant
blanchet@38594
   293
                     ({add, del, ...} : relevance_override) axioms goal_ts =
blanchet@37538
   294
  if relevance_threshold > 1.0 then
blanchet@37538
   295
    []
blanchet@37538
   296
  else if relevance_threshold < 0.0 then
blanchet@37538
   297
    axioms
blanchet@37538
   298
  else
blanchet@35963
   299
    let
blanchet@38587
   300
      val thy = ProofContext.theory_of ctxt
blanchet@37503
   301
      val const_tab = fold (count_axiom_consts theory_relevant thy) axioms
blanchet@37503
   302
                           Symtab.empty
blanchet@38587
   303
      val goal_const_tab = get_consts_typs thy (SOME false) goal_ts
blanchet@38090
   304
      val relevance_threshold = 0.8 * relevance_threshold (* FIXME *)
blanchet@35963
   305
      val _ =
blanchet@35963
   306
        trace_msg (fn () => "Initial constants: " ^
blanchet@37551
   307
                            commas (goal_const_tab
blanchet@37551
   308
                                    |> Symtab.dest
blanchet@37551
   309
                                    |> filter (curry (op <>) [] o snd)
blanchet@37551
   310
                                    |> map fst))
blanchet@38594
   311
      val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@38594
   312
      val del_thms = maps (ProofContext.get_fact ctxt) del
blanchet@38594
   313
      fun iter threshold rel_const_tab =
blanchet@38594
   314
        let
blanchet@38594
   315
          fun relevant ([], rejects) [] =
blanchet@38594
   316
              (* Nothing was added this iteration: Add "add:" facts. *)
blanchet@38594
   317
              if null add_thms then
blanchet@38594
   318
                []
blanchet@38594
   319
              else
blanchet@38594
   320
                map_filter (fn (p as (name, th), _) =>
blanchet@38594
   321
                               if member Thm.eq_thm add_thms th then SOME p
blanchet@38594
   322
                               else NONE) rejects
blanchet@38594
   323
            | relevant (newpairs, rejects) [] =
blanchet@38594
   324
              let
blanchet@38594
   325
                val (newrels, more_rejects) = take_best max_new newpairs
blanchet@38594
   326
                val new_consts = maps #2 newrels
blanchet@38594
   327
                val rel_const_tab =
blanchet@38594
   328
                  rel_const_tab |> fold add_const_type_to_table new_consts
blanchet@38594
   329
                val threshold =
blanchet@38594
   330
                  threshold + (1.0 - threshold) / relevance_convergence
blanchet@38594
   331
              in
blanchet@38594
   332
                trace_msg (fn () => "relevant this iteration: " ^
blanchet@38594
   333
                                    Int.toString (length newrels));
blanchet@38594
   334
                map #1 newrels @ iter threshold rel_const_tab
blanchet@38594
   335
                    (more_rejects @ rejects)
blanchet@38594
   336
              end
blanchet@38594
   337
            | relevant (newrels, rejects)
blanchet@38594
   338
                       ((ax as ((name, th), consts_typs)) :: axs) =
blanchet@38594
   339
              let
blanchet@38594
   340
                val weight =
blanchet@38594
   341
                  if member Thm.eq_thm del_thms th then 0.0
blanchet@38594
   342
                  else formula_weight const_tab rel_const_tab consts_typs
blanchet@38594
   343
              in
blanchet@38594
   344
                if weight >= threshold orelse
blanchet@38594
   345
                   (defs_relevant andalso defines thy th rel_const_tab) then
blanchet@38594
   346
                  (trace_msg (fn () =>
blanchet@38594
   347
                       name ^ " passes: " ^ Real.toString weight
blanchet@38594
   348
                       (* ^ " consts: " ^ commas (map fst consts_typs) *));
blanchet@38594
   349
                   relevant ((ax, weight) :: newrels, rejects) axs)
blanchet@38594
   350
                else
blanchet@38594
   351
                  relevant (newrels, ax :: rejects) axs
blanchet@38594
   352
              end
blanchet@38594
   353
          in
blanchet@38594
   354
            trace_msg (fn () => "relevant_facts, current threshold: " ^
blanchet@38594
   355
                                Real.toString threshold);
blanchet@38594
   356
            relevant ([], [])
blanchet@38594
   357
          end
blanchet@38594
   358
      val relevant = iter relevance_threshold goal_const_tab
blanchet@38594
   359
                          (map (pair_consts_typs_axiom theory_relevant thy)
blanchet@38594
   360
                               axioms)
blanchet@35963
   361
    in
blanchet@35963
   362
      trace_msg (fn () => "Total relevant: " ^ Int.toString (length relevant));
blanchet@35963
   363
      relevant
blanchet@35963
   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@37626
   389
   "split_asm", "cases", "ext_cases"]
blanchet@37626
   390
blanchet@37626
   391
val max_lambda_nesting = 3
blanchet@37626
   392
blanchet@37626
   393
fun term_has_too_many_lambdas max (t1 $ t2) =
blanchet@37626
   394
    exists (term_has_too_many_lambdas max) [t1, t2]
blanchet@37626
   395
  | term_has_too_many_lambdas max (Abs (_, _, t)) =
blanchet@37626
   396
    max = 0 orelse term_has_too_many_lambdas (max - 1) t
blanchet@37626
   397
  | term_has_too_many_lambdas _ _ = false
blanchet@37626
   398
blanchet@37626
   399
fun is_formula_type T = (T = HOLogic.boolT orelse T = propT)
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@37626
   411
(* The max apply depth of any "metis" call in "Metis_Examples" (on 31-10-2007)
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@38652
   491
  ((has_bound_or_var_of_type dangerous_types t andalso
blanchet@38652
   492
    has_bound_or_var_of_type dangerous_types (transform_elim_term t))
blanchet@38652
   493
   orelse is_exhaustive_finite t)
paulson@21470
   494
blanchet@38627
   495
fun is_theorem_bad_for_atps full_types thm =
blanchet@38627
   496
  let val t = prop_of thm in
blanchet@38627
   497
    is_formula_too_complex t orelse exists_type type_has_top_sort t orelse
blanchet@38627
   498
    is_dangerous_term full_types t orelse exists_sledgehammer_const t orelse
blanchet@38652
   499
    is_strange_theorem thm
blanchet@38627
   500
  end
blanchet@38627
   501
blanchet@38627
   502
fun all_name_thms_pairs ctxt full_types add_thms chained_ths =
blanchet@38627
   503
  let
blanchet@38627
   504
    val global_facts = PureThy.facts_of (ProofContext.theory_of ctxt);
blanchet@38644
   505
    val local_facts = ProofContext.facts_of ctxt
blanchet@38644
   506
    val named_locals = local_facts |> Facts.dest_static []
blanchet@38644
   507
    val unnamed_locals =
blanchet@38644
   508
      local_facts |> Facts.props
blanchet@38644
   509
      |> filter_out (fn th => exists (fn (_, ths) => member Thm.eq_thm ths th)
blanchet@38644
   510
                                     named_locals)
blanchet@38644
   511
      |> map (pair "" o single)
blanchet@38627
   512
    val full_space =
blanchet@38627
   513
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts);
blanchet@38644
   514
    fun valid_facts facts pairs =
blanchet@38644
   515
      (pairs, []) |-> fold (fn (name, ths0) =>
blanchet@38644
   516
        if name <> "" andalso
blanchet@38644
   517
           forall (not o member Thm.eq_thm add_thms) ths0 andalso
blanchet@38644
   518
           (Facts.is_concealed facts name orelse
blanchet@38627
   519
            (respect_no_atp andalso is_package_def name) orelse
blanchet@38627
   520
            member (op =) multi_base_blacklist (Long_Name.base_name name) orelse
blanchet@38644
   521
            String.isSuffix "_def_raw" (* FIXME: crude hack *) name) then
blanchet@38627
   522
          I
blanchet@38627
   523
        else
blanchet@38627
   524
          let
blanchet@38627
   525
            fun check_thms a =
blanchet@38627
   526
              (case try (ProofContext.get_thms ctxt) a of
blanchet@38627
   527
                NONE => false
blanchet@38627
   528
              | SOME ths1 => Thm.eq_thms (ths0, ths1))
blanchet@38627
   529
            val name1 = Facts.extern facts name;
blanchet@38627
   530
            val name2 = Name_Space.extern full_space name;
blanchet@38627
   531
            val ths =
blanchet@38652
   532
              ths0 |> filter ((not o is_theorem_bad_for_atps full_types) orf
blanchet@38644
   533
                              member Thm.eq_thm add_thms)
blanchet@38644
   534
            val name' =
blanchet@38644
   535
              case find_first check_thms [name1, name2, name] of
blanchet@38644
   536
                SOME name' => name'
blanchet@38644
   537
              | NONE =>
blanchet@38644
   538
                ths |> map (fn th =>
blanchet@38644
   539
                               "`" ^ Print_Mode.setmp [Print_Mode.input]
blanchet@38644
   540
                                         (Syntax.string_of_term ctxt)
blanchet@38644
   541
                                         (prop_of th) ^ "`")
blanchet@38644
   542
                    |> space_implode " "
blanchet@38627
   543
          in
blanchet@38652
   544
            cons (name' |> forall (member Thm.eq_thm chained_ths) ths0
blanchet@38644
   545
                           ? prefix chained_prefix, ths)
blanchet@38627
   546
          end)
blanchet@38644
   547
  in
blanchet@38644
   548
    valid_facts local_facts (unnamed_locals @ named_locals) @
blanchet@38644
   549
    valid_facts global_facts (Facts.dest_static [] global_facts)
blanchet@38644
   550
  end
blanchet@38627
   551
blanchet@38627
   552
fun multi_name a th (n, pairs) =
blanchet@38627
   553
  (n + 1, (a ^ "(" ^ Int.toString n ^ ")", th) :: pairs);
blanchet@38627
   554
blanchet@38627
   555
fun add_names (_, []) pairs = pairs
blanchet@38627
   556
  | add_names (a, [th]) pairs = (a, th) :: pairs
blanchet@38627
   557
  | add_names (a, ths) pairs = #2 (fold (multi_name a) ths (1, pairs))
blanchet@38627
   558
blanchet@38627
   559
fun is_multi (a, ths) = length ths > 1 orelse String.isSuffix ".axioms" a;
blanchet@38627
   560
blanchet@38627
   561
(* The single-name theorems go after the multiple-name ones, so that single
blanchet@38627
   562
   names are preferred when both are available. *)
blanchet@38627
   563
fun name_thm_pairs ctxt respect_no_atp name_thms_pairs =
blanchet@38627
   564
  let
blanchet@38627
   565
    val (mults, singles) = List.partition is_multi name_thms_pairs
blanchet@38627
   566
    val ps = [] |> fold add_names singles |> fold add_names mults
blanchet@38627
   567
  in ps |> respect_no_atp ? filter_out (No_ATPs.member ctxt o snd) end;
blanchet@38627
   568
blanchet@38627
   569
fun is_named ("", th) =
blanchet@38627
   570
    (warning ("No name for theorem " ^
blanchet@38627
   571
              Display.string_of_thm_without_context th); false)
blanchet@38627
   572
  | is_named _ = true
blanchet@38627
   573
fun checked_name_thm_pairs respect_no_atp ctxt =
blanchet@38627
   574
  name_thm_pairs ctxt respect_no_atp
blanchet@38627
   575
  #> tap (fn ps => trace_msg
blanchet@38627
   576
                        (fn () => ("Considering " ^ Int.toString (length ps) ^
blanchet@38627
   577
                                   " theorems")))
blanchet@38627
   578
  #> filter is_named
blanchet@38627
   579
blanchet@38627
   580
(***************************************************************)
blanchet@38627
   581
(* ATP invocation methods setup                                *)
blanchet@38627
   582
(***************************************************************)
blanchet@38627
   583
blanchet@37580
   584
fun relevant_facts full_types relevance_threshold relevance_convergence
blanchet@37580
   585
                   defs_relevant max_new theory_relevant
blanchet@37347
   586
                   (relevance_override as {add, del, only})
blanchet@37995
   587
                   (ctxt, (chained_ths, _)) hyp_ts concl_t =
blanchet@37538
   588
  let
blanchet@37538
   589
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@37538
   590
    val axioms =
blanchet@37538
   591
      checked_name_thm_pairs (respect_no_atp andalso not only) ctxt
blanchet@38617
   592
          (if only then map (name_thms_pair_from_ref ctxt chained_ths) add
blanchet@38627
   593
           else all_name_thms_pairs ctxt full_types add_thms chained_ths)
blanchet@38595
   594
      |> make_unique
blanchet@37538
   595
  in
blanchet@37538
   596
    relevance_filter ctxt relevance_threshold relevance_convergence
blanchet@37538
   597
                     defs_relevant max_new theory_relevant relevance_override
blanchet@38587
   598
                     axioms (concl_t :: hyp_ts)
blanchet@38595
   599
    |> sort_wrt fst
blanchet@37538
   600
  end
immler@30536
   601
paulson@15347
   602
end;