src/HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
author blanchet
Fri Jun 25 17:26:14 2010 +0200 (2010-06-25 ago)
changeset 37580 c2c1caff5dea
parent 37578 9367cb36b1c4
child 37616 c8d2d84d6011
permissions -rw-r--r--
got rid of "respect_no_atp" option, which even I don't use
blanchet@35826
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
wenzelm@33309
     2
    Author:     Jia Meng, Cambridge University Computer Laboratory, 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@37574
     8
  type cnf_thm = Clausifier.cnf_thm
blanchet@36473
     9
blanchet@35966
    10
  type relevance_override =
blanchet@35966
    11
    {add: Facts.ref list,
blanchet@35966
    12
     del: Facts.ref list,
blanchet@35966
    13
     only: bool}
blanchet@35966
    14
blanchet@37505
    15
  val use_natural_form : bool Unsynchronized.ref
blanchet@37347
    16
  val relevant_facts :
blanchet@37580
    17
    bool -> real -> real -> bool -> int -> bool -> relevance_override
blanchet@37500
    18
    -> Proof.context * (thm list * 'a) -> thm list -> cnf_thm list
paulson@15347
    19
end;
paulson@15347
    20
blanchet@35826
    21
structure Sledgehammer_Fact_Filter : SLEDGEHAMMER_FACT_FILTER =
paulson@15347
    22
struct
paulson@15347
    23
blanchet@37574
    24
open Clausifier
blanchet@37578
    25
open Metis_Clauses
blanchet@35826
    26
blanchet@37580
    27
val respect_no_atp = true
blanchet@37505
    28
(* Experimental feature: Filter theorems in natural form or in CNF? *)
blanchet@37506
    29
val use_natural_form = Unsynchronized.ref false
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
wenzelm@28477
    36
(***************************************************************)
wenzelm@28477
    37
(* Relevance Filtering                                         *)
wenzelm@28477
    38
(***************************************************************)
mengj@19194
    39
blanchet@35865
    40
fun strip_Trueprop (@{const Trueprop} $ t) = t
paulson@24958
    41
  | strip_Trueprop t = t;
mengj@19194
    42
paulson@24287
    43
(*** constants with types ***)
paulson@24287
    44
paulson@24287
    45
(*An abstraction of Isabelle types*)
paulson@24287
    46
datatype const_typ =  CTVar | CType of string * const_typ list
paulson@24287
    47
paulson@24287
    48
(*Is the second type an instance of the first one?*)
blanchet@37505
    49
fun match_type (CType(con1,args1)) (CType(con2,args2)) =
paulson@24287
    50
      con1=con2 andalso match_types args1 args2
paulson@24287
    51
  | match_type CTVar _ = true
paulson@24287
    52
  | match_type _ CTVar = false
paulson@24287
    53
and match_types [] [] = true
paulson@24287
    54
  | match_types (a1::as1) (a2::as2) = match_type a1 a2 andalso match_types as1 as2;
paulson@24287
    55
paulson@24287
    56
(*Is there a unifiable constant?*)
blanchet@37505
    57
fun uni_mem goal_const_tab (c, c_typ) =
blanchet@37505
    58
  exists (match_types c_typ) (these (Symtab.lookup goal_const_tab c))
blanchet@37505
    59
paulson@24287
    60
(*Maps a "real" type to a const_typ*)
blanchet@37505
    61
fun const_typ_of (Type (c,typs)) = CType (c, map const_typ_of typs)
paulson@24287
    62
  | const_typ_of (TFree _) = CTVar
paulson@24287
    63
  | const_typ_of (TVar _) = CTVar
paulson@24287
    64
paulson@24287
    65
(*Pairs a constant with the list of its type instantiations (using const_typ)*)
blanchet@37505
    66
fun const_with_typ thy (c,typ) =
paulson@24287
    67
    let val tvars = Sign.const_typargs thy (c,typ)
paulson@24287
    68
    in (c, map const_typ_of tvars) end
blanchet@37505
    69
    handle TYPE _ => (c,[]);   (*Variable (locale constant): monomorphic*)
paulson@24287
    70
paulson@24287
    71
(*Add a const/type pair to the table, but a [] entry means a standard connective,
paulson@24287
    72
  which we ignore.*)
blanchet@37502
    73
fun add_const_type_to_table (c, ctyps) =
blanchet@37502
    74
  Symtab.map_default (c, [ctyps])
blanchet@37502
    75
                     (fn [] => [] | ctypss => insert (op =) ctyps ctypss)
paulson@24287
    76
blanchet@37551
    77
val fresh_prefix = "Sledgehammer.Fresh."
blanchet@37537
    78
blanchet@37537
    79
val flip = Option.map not
paulson@24287
    80
blanchet@37551
    81
val boring_natural_consts = [@{const_name If}]
blanchet@37537
    82
(* Including equality in this list might be expected to stop rules like
blanchet@37537
    83
   subset_antisym from being chosen, but for some reason filtering works better
blanchet@37537
    84
   with them listed. The logical signs All, Ex, &, and --> are omitted for CNF
blanchet@37537
    85
   because any remaining occurrences must be within comprehensions. *)
blanchet@37537
    86
val boring_cnf_consts =
blanchet@37537
    87
  [@{const_name Trueprop}, @{const_name "==>"}, @{const_name all},
blanchet@37537
    88
   @{const_name "=="}, @{const_name "op |"}, @{const_name Not},
blanchet@37537
    89
   @{const_name "op ="}]
blanchet@37537
    90
blanchet@37537
    91
fun get_consts_typs thy pos ts =
blanchet@37505
    92
  let
blanchet@37505
    93
    (* Free variables are included, as well as constants, to handle locales.
blanchet@37505
    94
       "skolem_id" is included to increase the complexity of theorems containing
blanchet@37505
    95
       Skolem functions. In non-CNF form, "Ex" is included but each occurrence
blanchet@37505
    96
       is considered fresh, to simulate the effect of Skolemization. *)
blanchet@37537
    97
    fun do_term t =
blanchet@37537
    98
      case t of
blanchet@37537
    99
        Const x => add_const_type_to_table (const_with_typ thy x)
blanchet@37537
   100
      | Free x => add_const_type_to_table (const_with_typ thy x)
blanchet@37537
   101
      | (t as Const (@{const_name skolem_id}, _)) $ _ => do_term t
blanchet@37537
   102
      | t1 $ t2 => do_term t1 #> do_term t2
blanchet@37551
   103
      | Abs (_, _, t) =>
blanchet@37551
   104
        (* Abstractions lead to combinators, so we add a penalty for them. *)
blanchet@37551
   105
        add_const_type_to_table (gensym fresh_prefix, [])
blanchet@37551
   106
        #> do_term t
blanchet@37537
   107
      | _ => I
blanchet@37537
   108
    fun do_quantifier sweet_pos pos body_t =
blanchet@37537
   109
      do_formula pos body_t
blanchet@37537
   110
      #> (if pos = SOME sweet_pos then I
blanchet@37551
   111
          else add_const_type_to_table (gensym fresh_prefix, []))
blanchet@37537
   112
    and do_equality T t1 t2 =
blanchet@37537
   113
      fold (if T = @{typ bool} orelse T = @{typ prop} then do_formula NONE
blanchet@37537
   114
            else do_term) [t1, t2]
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@37537
   118
        do_quantifier false pos 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@37537
   122
        do_equality 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@37537
   126
        do_quantifier false pos body_t
blanchet@37537
   127
      | Const (@{const_name Ex}, _) $ Abs (_, _, body_t) =>
blanchet@37537
   128
        do_quantifier true pos 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@37537
   134
        do_equality T t1 t2
blanchet@37537
   135
      | (t0 as Const (_, @{typ bool})) $ t1 =>
blanchet@37537
   136
        do_term t0 #> do_formula pos t1  (* theory constant *)
blanchet@37537
   137
      | _ => do_term t
blanchet@37505
   138
  in
blanchet@37537
   139
    Symtab.empty
blanchet@37537
   140
    |> (if !use_natural_form then
blanchet@37551
   141
          fold (Symtab.update o rpair []) boring_natural_consts
blanchet@37551
   142
          #> fold (do_formula pos) ts
blanchet@37537
   143
        else
blanchet@37537
   144
          fold (Symtab.update o rpair []) boring_cnf_consts
blanchet@37537
   145
          #> fold do_term ts)
blanchet@37505
   146
  end
paulson@24287
   147
paulson@24287
   148
(*Inserts a dummy "constant" referring to the theory name, so that relevance
paulson@24287
   149
  takes the given theory into account.*)
blanchet@36220
   150
fun const_prop_of theory_relevant th =
blanchet@37505
   151
  if theory_relevant then
blanchet@37505
   152
    let
blanchet@37505
   153
      val name = Context.theory_name (theory_of_thm th)
blanchet@37505
   154
      val t = Const (name ^ ". 1", @{typ bool})
blanchet@37505
   155
    in t $ prop_of th end
blanchet@37505
   156
  else
blanchet@37505
   157
    prop_of th
blanchet@37505
   158
blanchet@37505
   159
fun appropriate_prop_of theory_relevant (cnf_thm, (_, orig_thm)) =
blanchet@37505
   160
  (if !use_natural_form then orig_thm else cnf_thm)
blanchet@37505
   161
  |> const_prop_of theory_relevant
paulson@24287
   162
paulson@24287
   163
(**** Constant / Type Frequencies ****)
paulson@24287
   164
paulson@24287
   165
(*A two-dimensional symbol table counts frequencies of constants. It's keyed first by
paulson@24287
   166
  constant name and second by its list of type instantiations. For the latter, we need
paulson@24287
   167
  a linear ordering on type const_typ list.*)
blanchet@37505
   168
paulson@24287
   169
local
paulson@24287
   170
paulson@24287
   171
fun cons_nr CTVar = 0
paulson@24287
   172
  | cons_nr (CType _) = 1;
paulson@24287
   173
paulson@24287
   174
in
paulson@24287
   175
paulson@24287
   176
fun const_typ_ord TU =
paulson@24287
   177
  case TU of
paulson@24287
   178
    (CType (a, Ts), CType (b, Us)) =>
paulson@24287
   179
      (case fast_string_ord(a,b) of EQUAL => dict_ord const_typ_ord (Ts,Us) | ord => ord)
paulson@24287
   180
  | (T, U) => int_ord (cons_nr T, cons_nr U);
paulson@24287
   181
paulson@24287
   182
end;
paulson@24287
   183
wenzelm@31971
   184
structure CTtab = Table(type key = const_typ list val ord = dict_ord const_typ_ord);
paulson@24287
   185
blanchet@37505
   186
fun count_axiom_consts theory_relevant thy axiom =
blanchet@37503
   187
  let
blanchet@37503
   188
    fun do_const (a, T) =
blanchet@37503
   189
      let val (c, cts) = const_with_typ thy (a,T) in
blanchet@37503
   190
        (* Two-dimensional table update. Constant maps to types maps to
blanchet@37503
   191
           count. *)
blanchet@37503
   192
        CTtab.map_default (cts, 0) (Integer.add 1)
blanchet@37503
   193
        |> Symtab.map_default (c, CTtab.empty)
blanchet@37503
   194
      end
blanchet@37503
   195
    fun do_term (Const x) = do_const x
blanchet@37503
   196
      | do_term (Free x) = do_const x
blanchet@37515
   197
      | do_term (Const (x as (@{const_name skolem_id}, _)) $ _) = do_const x
blanchet@37503
   198
      | do_term (t $ u) = do_term t #> do_term u
blanchet@37503
   199
      | do_term (Abs (_, _, t)) = do_term t
blanchet@37503
   200
      | do_term _ = I
blanchet@37505
   201
  in axiom |> appropriate_prop_of theory_relevant |> do_term end
paulson@24287
   202
paulson@24287
   203
paulson@24287
   204
(**** Actual Filtering Code ****)
paulson@24287
   205
paulson@24287
   206
(*The frequency of a constant is the sum of those of all instances of its type.*)
blanchet@37505
   207
fun const_frequency const_tab (c, cts) =
blanchet@36185
   208
  CTtab.fold (fn (cts', m) => match_types cts cts' ? Integer.add m)
blanchet@37505
   209
             (the (Symtab.lookup const_tab c)
blanchet@37505
   210
              handle Option.Option => raise Fail ("Const: " ^ c)) 0
paulson@24287
   211
blanchet@37503
   212
(*A surprising number of theorems contain only a few significant constants.
blanchet@37503
   213
  These include all induction rules, and other general theorems. Filtering
blanchet@37505
   214
  theorems in clause form reveals these complexities in the form of Skolem
blanchet@37503
   215
  functions. If we were instead to filter theorems in their natural form,
blanchet@37503
   216
  some other method of measuring theorem complexity would become necessary.*)
blanchet@37503
   217
blanchet@37503
   218
(* "log" seems best in practice. A constant function of one ignores the constant
blanchet@37503
   219
   frequencies. *)
blanchet@37503
   220
fun log_weight2 (x:real) = 1.0 + 2.0 / Math.ln (x + 1.0)
blanchet@37503
   221
blanchet@37503
   222
(* Computes a constant's weight, as determined by its frequency. *)
blanchet@37503
   223
val ct_weight = log_weight2 o real oo const_frequency
paulson@24287
   224
blanchet@37505
   225
(*Relevant constants are weighted according to frequency,
paulson@24287
   226
  but irrelevant constants are simply counted. Otherwise, Skolem functions,
paulson@24287
   227
  which are rare, would harm a clause's chances of being picked.*)
blanchet@37505
   228
fun clause_weight const_tab gctyps consts_typs =
paulson@24287
   229
    let val rel = filter (uni_mem gctyps) consts_typs
blanchet@37505
   230
        val rel_weight = fold (curry Real.+ o ct_weight const_tab) rel 0.0
paulson@24287
   231
    in
wenzelm@32960
   232
        rel_weight / (rel_weight + real (length consts_typs - length rel))
paulson@24287
   233
    end;
blanchet@37505
   234
paulson@24287
   235
(*Multiplies out to a list of pairs: 'a * 'b list -> ('a * 'b) list -> ('a * 'b) list*)
wenzelm@30190
   236
fun add_expand_pairs (x,ys) xys = List.foldl (fn (y,acc) => (x,y)::acc) xys ys;
paulson@24287
   237
blanchet@37505
   238
fun consts_typs_of_term thy t =
blanchet@37537
   239
  Symtab.fold add_expand_pairs (get_consts_typs thy (SOME false) [t]) []
paulson@24287
   240
blanchet@37505
   241
fun pair_consts_typs_axiom theory_relevant thy axiom =
blanchet@37505
   242
  (axiom, axiom |> appropriate_prop_of theory_relevant
blanchet@37505
   243
                |> consts_typs_of_term thy)
paulson@24287
   244
blanchet@37505
   245
exception CONST_OR_FREE of unit
blanchet@37505
   246
blanchet@37505
   247
fun dest_Const_or_Free (Const x) = x
blanchet@37505
   248
  | dest_Const_or_Free (Free x) = x
blanchet@37505
   249
  | dest_Const_or_Free _ = raise CONST_OR_FREE ()
paulson@24287
   250
paulson@24287
   251
(*Look for definitions of the form f ?x1 ... ?xn = t, but not reversed.*)
wenzelm@32994
   252
fun defines thy thm gctypes =
paulson@24287
   253
    let val tm = prop_of thm
wenzelm@32960
   254
        fun defs lhs rhs =
paulson@24287
   255
            let val (rator,args) = strip_comb lhs
blanchet@37505
   256
                val ct = const_with_typ thy (dest_Const_or_Free rator)
haftmann@33037
   257
            in
haftmann@33037
   258
              forall is_Var args andalso uni_mem gctypes ct andalso
haftmann@33038
   259
                subset (op =) (Term.add_vars rhs [], Term.add_vars lhs [])
paulson@24287
   260
            end
blanchet@37505
   261
            handle CONST_OR_FREE () => false
blanchet@37505
   262
    in
blanchet@35963
   263
        case tm of
blanchet@37505
   264
          @{const Trueprop} $ (Const (@{const_name "op ="}, _) $ lhs $ rhs) =>
blanchet@37505
   265
            defs lhs rhs
blanchet@35963
   266
        | _ => false
paulson@24287
   267
    end;
paulson@24287
   268
blanchet@37568
   269
type annotated_cnf_thm = cnf_thm * ((string * const_typ list) list)
blanchet@37505
   270
paulson@24287
   271
(*For a reverse sort, putting the largest values first.*)
blanchet@37500
   272
fun compare_pairs ((_, w1), (_, w2)) = Real.compare (w2, w1)
paulson@24287
   273
paulson@24287
   274
(*Limit the number of new clauses, to prevent runaway acceptance.*)
blanchet@37568
   275
fun take_best max_new (newpairs : (annotated_cnf_thm * real) list) =
paulson@24287
   276
  let val nnew = length newpairs
paulson@24287
   277
  in
wenzelm@28477
   278
    if nnew <= max_new then (map #1 newpairs, [])
blanchet@37505
   279
    else
paulson@24287
   280
      let val cls = sort compare_pairs newpairs
wenzelm@28477
   281
          val accepted = List.take (cls, max_new)
paulson@24287
   282
      in
blanchet@37505
   283
        trace_msg (fn () => ("Number of candidates, " ^ Int.toString nnew ^
wenzelm@32960
   284
                       ", exceeds the limit of " ^ Int.toString (max_new)));
blanchet@35865
   285
        trace_msg (fn () => ("Effective pass mark: " ^ Real.toString (#2 (List.last accepted))));
blanchet@35865
   286
        trace_msg (fn () => "Actually passed: " ^
blanchet@37500
   287
          space_implode ", " (map (fn (((_,((name,_), _)),_),_) => name) accepted));
paulson@24287
   288
wenzelm@32960
   289
        (map #1 accepted, map #1 (List.drop (cls, max_new)))
paulson@24287
   290
      end
paulson@24287
   291
  end;
paulson@24287
   292
blanchet@36922
   293
fun relevant_clauses ctxt relevance_convergence defs_relevant max_new
blanchet@37505
   294
                     ({add, del, ...} : relevance_override) const_tab =
blanchet@36182
   295
  let
blanchet@37344
   296
    val thy = ProofContext.theory_of ctxt
blanchet@37501
   297
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@37501
   298
    val del_thms = maps (ProofContext.get_fact ctxt) del
blanchet@37505
   299
    fun iter threshold rel_const_tab =
blanchet@36182
   300
      let
blanchet@36182
   301
        fun relevant ([], _) [] = []  (* Nothing added this iteration *)
blanchet@37344
   302
          | relevant (newpairs, rejects) [] =
blanchet@36182
   303
            let
blanchet@36182
   304
              val (newrels, more_rejects) = take_best max_new newpairs
blanchet@36182
   305
              val new_consts = maps #2 newrels
blanchet@37505
   306
              val rel_const_tab =
blanchet@37505
   307
                rel_const_tab |> fold add_const_type_to_table new_consts
blanchet@37344
   308
              val threshold =
blanchet@37344
   309
                threshold + (1.0 - threshold) / relevance_convergence
wenzelm@32960
   310
            in
blanchet@36182
   311
              trace_msg (fn () => "relevant this iteration: " ^
blanchet@36182
   312
                                  Int.toString (length newrels));
blanchet@37505
   313
              map #1 newrels @ iter threshold rel_const_tab
blanchet@37344
   314
                  (more_rejects @ rejects)
wenzelm@32960
   315
            end
blanchet@36182
   316
          | relevant (newrels, rejects)
blanchet@37503
   317
                     ((ax as (clsthm as (_, ((name, n), orig_th)),
blanchet@37501
   318
                              consts_typs)) :: axs) =
blanchet@35966
   319
            let
blanchet@37505
   320
              val weight =
blanchet@37505
   321
                if member Thm.eq_thm add_thms orig_th then 1.0
blanchet@37505
   322
                else if member Thm.eq_thm del_thms orig_th then 0.0
blanchet@37505
   323
                else clause_weight const_tab rel_const_tab consts_typs
wenzelm@32960
   324
            in
blanchet@37344
   325
              if weight >= threshold orelse
blanchet@37505
   326
                 (defs_relevant andalso
blanchet@37505
   327
                  defines thy (#1 clsthm) rel_const_tab) then
blanchet@37537
   328
                (trace_msg (fn () =>
blanchet@37537
   329
                     name ^ " clause " ^ Int.toString n ^
blanchet@37537
   330
                     " passes: " ^ Real.toString weight
blanchet@37537
   331
                     (* ^ " consts: " ^ commas (map fst consts_typs) *));
blanchet@37537
   332
                 relevant ((ax, weight) :: newrels, rejects) axs)
blanchet@36182
   333
              else
blanchet@36182
   334
                relevant (newrels, ax :: rejects) axs
wenzelm@32960
   335
            end
blanchet@36182
   336
        in
blanchet@37344
   337
          trace_msg (fn () => "relevant_clauses, current threshold: " ^
blanchet@37344
   338
                              Real.toString threshold);
blanchet@36182
   339
          relevant ([], [])
blanchet@36182
   340
        end
blanchet@36182
   341
  in iter end
blanchet@37505
   342
blanchet@36922
   343
fun relevance_filter ctxt relevance_threshold relevance_convergence
blanchet@36922
   344
                     defs_relevant max_new theory_relevant relevance_override
blanchet@37505
   345
                     thy (axioms : cnf_thm list) goals =
blanchet@37538
   346
  if relevance_threshold > 1.0 then
blanchet@37538
   347
    []
blanchet@37538
   348
  else if relevance_threshold < 0.0 then
blanchet@37538
   349
    axioms
blanchet@37538
   350
  else
blanchet@35963
   351
    let
blanchet@37503
   352
      val const_tab = fold (count_axiom_consts theory_relevant thy) axioms
blanchet@37503
   353
                           Symtab.empty
blanchet@37537
   354
      val goal_const_tab = get_consts_typs thy (SOME true) goals
blanchet@37551
   355
      val relevance_threshold =
blanchet@37551
   356
        if !use_natural_form then 0.9 * relevance_threshold (* experimental *)
blanchet@37551
   357
        else relevance_threshold
blanchet@35963
   358
      val _ =
blanchet@35963
   359
        trace_msg (fn () => "Initial constants: " ^
blanchet@37551
   360
                            commas (goal_const_tab
blanchet@37551
   361
                                    |> Symtab.dest
blanchet@37551
   362
                                    |> filter (curry (op <>) [] o snd)
blanchet@37551
   363
                                    |> map fst))
blanchet@35963
   364
      val relevant =
blanchet@36922
   365
        relevant_clauses ctxt relevance_convergence defs_relevant max_new
blanchet@37344
   366
                         relevance_override const_tab relevance_threshold
blanchet@36922
   367
                         goal_const_tab
blanchet@36220
   368
                         (map (pair_consts_typs_axiom theory_relevant thy)
blanchet@36220
   369
                              axioms)
blanchet@35963
   370
    in
blanchet@35963
   371
      trace_msg (fn () => "Total relevant: " ^ Int.toString (length relevant));
blanchet@35963
   372
      relevant
blanchet@35963
   373
    end
paulson@24287
   374
paulson@24287
   375
(***************************************************************)
mengj@19768
   376
(* Retrieving and filtering lemmas                             *)
mengj@19768
   377
(***************************************************************)
mengj@19768
   378
paulson@33022
   379
(*** retrieve lemmas and filter them ***)
mengj@19768
   380
paulson@20757
   381
(*Reject theorems with names like "List.filter.filter_list_def" or
paulson@21690
   382
  "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
paulson@20757
   383
fun is_package_def a =
wenzelm@30364
   384
  let val names = Long_Name.explode a
paulson@21690
   385
  in
paulson@21690
   386
     length names > 2 andalso
paulson@21690
   387
     not (hd names = "local") andalso
paulson@21690
   388
     String.isSuffix "_def" a  orelse  String.isSuffix "_defs" a
paulson@21690
   389
  end;
paulson@20757
   390
blanchet@37566
   391
fun make_unique xs = Termtab.fold (cons o snd) (make_clause_table xs) []
mengj@19768
   392
blanchet@37543
   393
val exists_sledgehammer_const =
blanchet@37543
   394
  exists_Const (fn (s, _) => String.isPrefix sledgehammer_prefix s) o prop_of
blanchet@37543
   395
blanchet@37580
   396
fun all_name_thms_pairs ctxt chained_ths =
paulson@22382
   397
  let
wenzelm@26675
   398
    val global_facts = PureThy.facts_of (ProofContext.theory_of ctxt);
wenzelm@26278
   399
    val local_facts = ProofContext.facts_of ctxt;
wenzelm@33641
   400
    val full_space =
wenzelm@33641
   401
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts);
wenzelm@33641
   402
wenzelm@33641
   403
    fun valid_facts facts =
wenzelm@33641
   404
      (facts, []) |-> Facts.fold_static (fn (name, ths0) =>
blanchet@37399
   405
        if Facts.is_concealed facts name orelse
blanchet@37399
   406
           (respect_no_atp andalso is_package_def name) orelse
blanchet@37399
   407
           member (op =) multi_base_blacklist (Long_Name.base_name name) then
blanchet@37399
   408
          I
blanchet@37399
   409
        else
blanchet@37399
   410
          let
blanchet@37399
   411
            fun check_thms a =
blanchet@37399
   412
              (case try (ProofContext.get_thms ctxt) a of
blanchet@37399
   413
                NONE => false
blanchet@37399
   414
              | SOME ths1 => Thm.eq_thms (ths0, ths1));
wenzelm@33641
   415
blanchet@37399
   416
            val name1 = Facts.extern facts name;
blanchet@37399
   417
            val name2 = Name_Space.extern full_space name;
blanchet@37543
   418
            val ths = filter_out (is_theorem_bad_for_atps orf
blanchet@37543
   419
                                  exists_sledgehammer_const) ths0
blanchet@37399
   420
          in
blanchet@37399
   421
            case find_first check_thms [name1, name2, name] of
blanchet@37399
   422
              NONE => I
blanchet@37399
   423
            | SOME name' =>
blanchet@37399
   424
              cons (name' |> forall (member Thm.eq_thm chained_ths) ths
blanchet@37399
   425
                             ? prefix chained_prefix, ths)
blanchet@37399
   426
          end)
wenzelm@26675
   427
  in valid_facts global_facts @ valid_facts local_facts end;
paulson@21224
   428
wenzelm@33309
   429
fun multi_name a th (n, pairs) =
wenzelm@33309
   430
  (n + 1, (a ^ "(" ^ Int.toString n ^ ")", th) :: pairs);
paulson@21224
   431
blanchet@37498
   432
fun add_names (_, []) pairs = pairs
blanchet@37399
   433
  | add_names (a, [th]) pairs = (a, th) :: pairs
blanchet@37399
   434
  | add_names (a, ths) pairs = #2 (fold (multi_name a) ths (1, pairs))
paulson@21224
   435
paulson@21290
   436
fun is_multi (a, ths) = length ths > 1 orelse String.isSuffix ".axioms" a;
paulson@21290
   437
blanchet@36550
   438
(* The single-name theorems go after the multiple-name ones, so that single
blanchet@36550
   439
   names are preferred when both are available. *)
blanchet@37580
   440
fun name_thm_pairs ctxt respect_no_atp name_thms_pairs =
wenzelm@33309
   441
  let
blanchet@37344
   442
    val (mults, singles) = List.partition is_multi name_thms_pairs
blanchet@37399
   443
    val ps = [] |> fold add_names singles |> fold add_names mults
blanchet@36060
   444
  in ps |> respect_no_atp ? filter_out (No_ATPs.member ctxt o snd) end;
paulson@21224
   445
blanchet@37344
   446
fun is_named ("", th) =
blanchet@37344
   447
    (warning ("No name for theorem " ^
blanchet@37344
   448
              Display.string_of_thm_without_context th); false)
blanchet@37344
   449
  | is_named _ = true
blanchet@37344
   450
fun checked_name_thm_pairs respect_no_atp ctxt =
blanchet@37580
   451
  name_thm_pairs ctxt respect_no_atp
blanchet@37344
   452
  #> tap (fn ps => trace_msg
blanchet@37344
   453
                        (fn () => ("Considering " ^ Int.toString (length ps) ^
blanchet@37344
   454
                                   " theorems")))
blanchet@37344
   455
  #> filter is_named
paulson@19894
   456
paulson@21290
   457
(***************************************************************)
mengj@19194
   458
(* ATP invocation methods setup                                *)
mengj@19194
   459
(***************************************************************)
mengj@19194
   460
blanchet@37347
   461
(**** Predicates to detect unwanted clauses (prolific or likely to cause
blanchet@37347
   462
      unsoundness) ****)
paulson@21470
   463
paulson@21470
   464
(** Too general means, positive equality literal with a variable X as one operand,
paulson@21470
   465
  when X does not occur properly in the other operand. This rules out clearly
paulson@21470
   466
  inconsistent clauses such as V=a|V=b, though it by no means guarantees soundness. **)
wenzelm@21588
   467
blanchet@37348
   468
fun var_occurs_in_term ix =
blanchet@37348
   469
  let
blanchet@37348
   470
    fun aux (Var (jx, _)) = (ix = jx)
blanchet@37348
   471
      | aux (t1 $ t2) = aux t1 orelse aux t2
blanchet@37348
   472
      | aux (Abs (_, _, t)) = aux t
blanchet@37348
   473
      | aux _ = false
blanchet@37348
   474
  in aux end
paulson@21470
   475
blanchet@37348
   476
fun is_record_type T = not (null (Record.dest_recTs T))
paulson@21470
   477
paulson@21470
   478
(*Unwanted equalities include
paulson@21470
   479
  (1) those between a variable that does not properly occur in the second operand,
paulson@21470
   480
  (2) those between a variable and a record, since these seem to be prolific "cases" thms
wenzelm@21588
   481
*)
blanchet@37348
   482
fun too_general_eqterms (Var (ix,T), t) =
blanchet@37348
   483
    not (var_occurs_in_term ix t) orelse is_record_type T
paulson@21470
   484
  | too_general_eqterms _ = false;
paulson@21470
   485
blanchet@35865
   486
fun too_general_equality (Const (@{const_name "op ="}, _) $ x $ y) =
paulson@21470
   487
      too_general_eqterms (x,y) orelse too_general_eqterms(y,x)
paulson@21470
   488
  | too_general_equality _ = false;
paulson@21470
   489
wenzelm@29267
   490
fun has_typed_var tycons = exists_subterm
wenzelm@29267
   491
  (fn Var (_, Type (a, _)) => member (op =) tycons a | _ => false);
paulson@21431
   492
blanchet@37347
   493
(* Clauses are forbidden to contain variables of these types. The typical reason
blanchet@37347
   494
   is that they lead to unsoundness. Note that "unit" satisfies numerous
blanchet@37347
   495
   equations like "?x = ()". The resulting clause will have no type constraint,
blanchet@37347
   496
   yielding false proofs. Even "bool" leads to many unsound proofs, though only
blanchet@37347
   497
   for higher-order problems. *)
blanchet@37347
   498
val dangerous_types = [@{type_name unit}, @{type_name bool}];
paulson@22217
   499
blanchet@37347
   500
(* Clauses containing variables of type "unit" or "bool" or of the form
blanchet@37347
   501
   "?x = A | ?x = B | ?x = C" are likely to lead to unsound proofs if types are
blanchet@37347
   502
   omitted. *)
blanchet@37347
   503
fun is_dangerous_term _ @{prop True} = true
blanchet@37347
   504
  | is_dangerous_term full_types t =
blanchet@37505
   505
    not full_types andalso
blanchet@37347
   506
    (has_typed_var dangerous_types t orelse
blanchet@37347
   507
     forall too_general_equality (HOLogic.disjuncts (strip_Trueprop t)))
paulson@21470
   508
blanchet@37580
   509
fun relevant_facts full_types relevance_threshold relevance_convergence
blanchet@37580
   510
                   defs_relevant max_new theory_relevant
blanchet@37347
   511
                   (relevance_override as {add, del, only})
blanchet@37347
   512
                   (ctxt, (chained_ths, _)) goal_cls =
blanchet@37538
   513
  let
blanchet@37538
   514
    val thy = ProofContext.theory_of ctxt
blanchet@37538
   515
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@37538
   516
    val has_override = not (null add) orelse not (null del)
blanchet@37566
   517
    val is_FO = forall (Meson.is_fol_term thy o prop_of) goal_cls
blanchet@37538
   518
    val axioms =
blanchet@37538
   519
      checked_name_thm_pairs (respect_no_atp andalso not only) ctxt
blanchet@37538
   520
          (map (name_thms_pair_from_ref ctxt chained_ths) add @
blanchet@37580
   521
           (if only then [] else all_name_thms_pairs ctxt chained_ths))
blanchet@37538
   522
      |> cnf_rules_pairs thy
blanchet@37538
   523
      |> not has_override ? make_unique
blanchet@37538
   524
      |> filter (fn (cnf_thm, (_, orig_thm)) =>
blanchet@37538
   525
                    member Thm.eq_thm add_thms orig_thm orelse
blanchet@37538
   526
                    ((not is_FO orelse is_quasi_fol_theorem thy cnf_thm) andalso
blanchet@37538
   527
                     not (is_dangerous_term full_types (prop_of cnf_thm))))
blanchet@37538
   528
  in
blanchet@37538
   529
    relevance_filter ctxt relevance_threshold relevance_convergence
blanchet@37538
   530
                     defs_relevant max_new theory_relevant relevance_override
blanchet@37538
   531
                     thy axioms (map prop_of goal_cls)
blanchet@37538
   532
    |> has_override ? make_unique
blanchet@37538
   533
    |> sort (prod_ord string_ord int_ord o pairself (fst o snd))
blanchet@37538
   534
  end
immler@30536
   535
paulson@15347
   536
end;