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