src/HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
author blanchet
Wed Mar 17 19:26:05 2010 +0100 (2010-03-17 ago)
changeset 35826 1590abc3d42a
parent 35825 a6aad5a70ed4
child 35828 46cfc4b8112e
permissions -rw-r--r--
renamed Sledgehammer structures
blanchet@35826
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
wenzelm@33309
     2
    Author:     Jia Meng, Cambridge University Computer Laboratory, NICTA
wenzelm@33309
     3
*)
paulson@15452
     4
blanchet@35826
     5
signature SLEDGEHAMMER_FACT_FILTER =
wenzelm@16802
     6
sig
blanchet@35826
     7
  type classrelClause = Sledgehammer_FOL_Clause.classrelClause
blanchet@35826
     8
  type arityClause = Sledgehammer_FOL_Clause.arityClause
blanchet@35826
     9
  type axiom_name = Sledgehammer_HOL_Clause.axiom_name
blanchet@35826
    10
  type clause = Sledgehammer_HOL_Clause.clause
blanchet@35826
    11
  type clause_id = Sledgehammer_HOL_Clause.clause_id
mengj@19194
    12
  datatype mode = Auto | Fol | Hol
paulson@22989
    13
  val tvar_classes_of_terms : term list -> string list
paulson@22989
    14
  val tfree_classes_of_terms : term list -> string list
paulson@22989
    15
  val type_consts_of_terms : theory -> term list -> string list
immler@31409
    16
  val get_relevant : int -> bool -> Proof.context * (thm list * 'a) -> thm list ->
immler@31409
    17
    (thm * (string * int)) list
immler@31410
    18
  val prepare_clauses : bool -> thm list -> thm list ->
blanchet@35826
    19
    (thm * (axiom_name * clause_id)) list ->
blanchet@35826
    20
    (thm * (axiom_name * clause_id)) list -> theory ->
blanchet@35826
    21
    axiom_name vector *
blanchet@35826
    22
      (clause list * clause list * clause list *
blanchet@35826
    23
      clause list * classrelClause list * arityClause 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@35826
    29
structure SFC = Sledgehammer_FOL_Clause
blanchet@35826
    30
structure SFP = Sledgehammer_Fact_Preprocessor
blanchet@35826
    31
structure SHC = Sledgehammer_HOL_Clause
blanchet@35826
    32
blanchet@35826
    33
type classrelClause = SFC.classrelClause
blanchet@35826
    34
type arityClause = SFC.arityClause
blanchet@35826
    35
type axiom_name = SHC.axiom_name
blanchet@35826
    36
type clause = SHC.clause
blanchet@35826
    37
type clause_id = SHC.clause_id
paulson@21070
    38
mengj@19194
    39
(********************************************************************)
mengj@19194
    40
(* some settings for both background automatic ATP calling procedure*)
mengj@19194
    41
(* and also explicit ATP invocation methods                         *)
mengj@19194
    42
(********************************************************************)
mengj@19194
    43
wenzelm@28477
    44
(*Translation mode can be auto-detected, or forced to be first-order or higher-order*)
wenzelm@28477
    45
datatype mode = Auto | Fol | Hol;
wenzelm@28477
    46
wenzelm@28477
    47
val linkup_logic_mode = Auto;
wenzelm@28477
    48
mengj@19194
    49
(*** background linkup ***)
wenzelm@28477
    50
val run_blacklist_filter = true;
paulson@21224
    51
paulson@24287
    52
(*** relevance filter parameters ***)
wenzelm@28477
    53
val run_relevance_filter = true;
wenzelm@28477
    54
val pass_mark = 0.5;
wenzelm@28477
    55
val convergence = 3.2;    (*Higher numbers allow longer inference chains*)
wenzelm@28477
    56
val follow_defs = false;  (*Follow definitions. Makes problems bigger.*)
wenzelm@28477
    57
  
wenzelm@28477
    58
(***************************************************************)
wenzelm@28477
    59
(* Relevance Filtering                                         *)
wenzelm@28477
    60
(***************************************************************)
mengj@19194
    61
paulson@24958
    62
fun strip_Trueprop (Const("Trueprop",_) $ t) = t
paulson@24958
    63
  | strip_Trueprop t = t;
mengj@19194
    64
paulson@24287
    65
(*A surprising number of theorems contain only a few significant constants.
paulson@24287
    66
  These include all induction rules, and other general theorems. Filtering
paulson@24287
    67
  theorems in clause form reveals these complexities in the form of Skolem 
paulson@24287
    68
  functions. If we were instead to filter theorems in their natural form,
paulson@24287
    69
  some other method of measuring theorem complexity would become necessary.*)
paulson@24287
    70
paulson@24287
    71
fun log_weight2 (x:real) = 1.0 + 2.0/Math.ln (x+1.0);
paulson@24287
    72
paulson@24287
    73
(*The default seems best in practice. A constant function of one ignores
paulson@24287
    74
  the constant frequencies.*)
wenzelm@28477
    75
val weight_fn = log_weight2;
paulson@24287
    76
paulson@24287
    77
paulson@24287
    78
(*Including equality in this list might be expected to stop rules like subset_antisym from
paulson@24287
    79
  being chosen, but for some reason filtering works better with them listed. The
paulson@24287
    80
  logical signs All, Ex, &, and --> are omitted because any remaining occurrrences
paulson@24287
    81
  must be within comprehensions.*)
paulson@24287
    82
val standard_consts = ["Trueprop","==>","all","==","op |","Not","op ="];
paulson@24287
    83
paulson@24287
    84
paulson@24287
    85
(*** constants with types ***)
paulson@24287
    86
paulson@24287
    87
(*An abstraction of Isabelle types*)
paulson@24287
    88
datatype const_typ =  CTVar | CType of string * const_typ list
paulson@24287
    89
paulson@24287
    90
(*Is the second type an instance of the first one?*)
paulson@24287
    91
fun match_type (CType(con1,args1)) (CType(con2,args2)) = 
paulson@24287
    92
      con1=con2 andalso match_types args1 args2
paulson@24287
    93
  | match_type CTVar _ = true
paulson@24287
    94
  | match_type _ CTVar = false
paulson@24287
    95
and match_types [] [] = true
paulson@24287
    96
  | match_types (a1::as1) (a2::as2) = match_type a1 a2 andalso match_types as1 as2;
paulson@24287
    97
paulson@24287
    98
(*Is there a unifiable constant?*)
paulson@24287
    99
fun uni_mem gctab (c,c_typ) =
paulson@24287
   100
  case Symtab.lookup gctab c of
paulson@24287
   101
      NONE => false
paulson@24287
   102
    | SOME ctyps_list => exists (match_types c_typ) ctyps_list;
paulson@24287
   103
  
paulson@24287
   104
(*Maps a "real" type to a const_typ*)
paulson@24287
   105
fun const_typ_of (Type (c,typs)) = CType (c, map const_typ_of typs) 
paulson@24287
   106
  | const_typ_of (TFree _) = CTVar
paulson@24287
   107
  | const_typ_of (TVar _) = CTVar
paulson@24287
   108
paulson@24287
   109
(*Pairs a constant with the list of its type instantiations (using const_typ)*)
paulson@24287
   110
fun const_with_typ thy (c,typ) = 
paulson@24287
   111
    let val tvars = Sign.const_typargs thy (c,typ)
paulson@24287
   112
    in (c, map const_typ_of tvars) end
paulson@24287
   113
    handle TYPE _ => (c,[]);   (*Variable (locale constant): monomorphic*)   
paulson@24287
   114
paulson@24287
   115
(*Add a const/type pair to the table, but a [] entry means a standard connective,
paulson@24287
   116
  which we ignore.*)
paulson@24287
   117
fun add_const_typ_table ((c,ctyps), tab) =
paulson@24287
   118
  Symtab.map_default (c, [ctyps]) (fn [] => [] | ctyps_list => insert (op =) ctyps ctyps_list) 
paulson@24287
   119
    tab;
paulson@24287
   120
paulson@24287
   121
(*Free variables are included, as well as constants, to handle locales*)
paulson@24287
   122
fun add_term_consts_typs_rm thy (Const(c, typ), tab) =
paulson@24287
   123
      add_const_typ_table (const_with_typ thy (c,typ), tab) 
paulson@24287
   124
  | add_term_consts_typs_rm thy (Free(c, typ), tab) =
paulson@24287
   125
      add_const_typ_table (const_with_typ thy (c,typ), tab) 
paulson@24287
   126
  | add_term_consts_typs_rm thy (t $ u, tab) =
paulson@24287
   127
      add_term_consts_typs_rm thy (t, add_term_consts_typs_rm thy (u, tab))
paulson@24287
   128
  | add_term_consts_typs_rm thy (Abs(_,_,t), tab) = add_term_consts_typs_rm thy (t, tab)
wenzelm@32994
   129
  | add_term_consts_typs_rm _ (_, tab) = tab;
paulson@24287
   130
paulson@24287
   131
(*The empty list here indicates that the constant is being ignored*)
paulson@24287
   132
fun add_standard_const (s,tab) = Symtab.update (s,[]) tab;
paulson@24287
   133
paulson@24287
   134
val null_const_tab : const_typ list list Symtab.table = 
wenzelm@30190
   135
    List.foldl add_standard_const Symtab.empty standard_consts;
paulson@24287
   136
wenzelm@30190
   137
fun get_goal_consts_typs thy = List.foldl (add_term_consts_typs_rm thy) null_const_tab;
paulson@24287
   138
paulson@24287
   139
(*Inserts a dummy "constant" referring to the theory name, so that relevance
paulson@24287
   140
  takes the given theory into account.*)
wenzelm@28477
   141
fun const_prop_of theory_const th =
wenzelm@28477
   142
 if theory_const then
paulson@24287
   143
  let val name = Context.theory_name (theory_of_thm th)
paulson@24287
   144
      val t = Const (name ^ ". 1", HOLogic.boolT)
paulson@24287
   145
  in  t $ prop_of th  end
paulson@24287
   146
 else prop_of th;
paulson@24287
   147
paulson@24287
   148
(**** Constant / Type Frequencies ****)
paulson@24287
   149
paulson@24287
   150
(*A two-dimensional symbol table counts frequencies of constants. It's keyed first by
paulson@24287
   151
  constant name and second by its list of type instantiations. For the latter, we need
paulson@24287
   152
  a linear ordering on type const_typ list.*)
paulson@24287
   153
  
paulson@24287
   154
local
paulson@24287
   155
paulson@24287
   156
fun cons_nr CTVar = 0
paulson@24287
   157
  | cons_nr (CType _) = 1;
paulson@24287
   158
paulson@24287
   159
in
paulson@24287
   160
paulson@24287
   161
fun const_typ_ord TU =
paulson@24287
   162
  case TU of
paulson@24287
   163
    (CType (a, Ts), CType (b, Us)) =>
paulson@24287
   164
      (case fast_string_ord(a,b) of EQUAL => dict_ord const_typ_ord (Ts,Us) | ord => ord)
paulson@24287
   165
  | (T, U) => int_ord (cons_nr T, cons_nr U);
paulson@24287
   166
paulson@24287
   167
end;
paulson@24287
   168
wenzelm@31971
   169
structure CTtab = Table(type key = const_typ list val ord = dict_ord const_typ_ord);
paulson@24287
   170
wenzelm@28477
   171
fun count_axiom_consts theory_const thy ((thm,_), tab) = 
paulson@24287
   172
  let fun count_const (a, T, tab) =
wenzelm@32960
   173
        let val (c, cts) = const_with_typ thy (a,T)
wenzelm@32960
   174
        in  (*Two-dimensional table update. Constant maps to types maps to count.*)
wenzelm@32960
   175
            Symtab.map_default (c, CTtab.empty) 
wenzelm@32960
   176
                               (CTtab.map_default (cts,0) (fn n => n+1)) tab
wenzelm@32960
   177
        end
paulson@24287
   178
      fun count_term_consts (Const(a,T), tab) = count_const(a,T,tab)
wenzelm@32960
   179
        | count_term_consts (Free(a,T), tab) = count_const(a,T,tab)
wenzelm@32960
   180
        | count_term_consts (t $ u, tab) =
wenzelm@32960
   181
            count_term_consts (t, count_term_consts (u, tab))
wenzelm@32960
   182
        | count_term_consts (Abs(_,_,t), tab) = count_term_consts (t, tab)
wenzelm@32960
   183
        | count_term_consts (_, tab) = tab
wenzelm@28477
   184
  in  count_term_consts (const_prop_of theory_const thm, tab)  end;
paulson@24287
   185
paulson@24287
   186
paulson@24287
   187
(**** Actual Filtering Code ****)
paulson@24287
   188
paulson@24287
   189
(*The frequency of a constant is the sum of those of all instances of its type.*)
paulson@24287
   190
fun const_frequency ctab (c, cts) =
paulson@24287
   191
  let val pairs = CTtab.dest (the (Symtab.lookup ctab c))
paulson@24287
   192
      fun add ((cts',m), n) = if match_types cts cts' then m+n else n
paulson@24287
   193
  in  List.foldl add 0 pairs  end;
paulson@24287
   194
paulson@24287
   195
(*Add in a constant's weight, as determined by its frequency.*)
paulson@24287
   196
fun add_ct_weight ctab ((c,T), w) =
wenzelm@28477
   197
  w + weight_fn (real (const_frequency ctab (c,T)));
paulson@24287
   198
paulson@24287
   199
(*Relevant constants are weighted according to frequency, 
paulson@24287
   200
  but irrelevant constants are simply counted. Otherwise, Skolem functions,
paulson@24287
   201
  which are rare, would harm a clause's chances of being picked.*)
paulson@24287
   202
fun clause_weight ctab gctyps consts_typs =
paulson@24287
   203
    let val rel = filter (uni_mem gctyps) consts_typs
paulson@24287
   204
        val rel_weight = List.foldl (add_ct_weight ctab) 0.0 rel
paulson@24287
   205
    in
wenzelm@32960
   206
        rel_weight / (rel_weight + real (length consts_typs - length rel))
paulson@24287
   207
    end;
paulson@24287
   208
    
paulson@24287
   209
(*Multiplies out to a list of pairs: 'a * 'b list -> ('a * 'b) list -> ('a * 'b) list*)
wenzelm@30190
   210
fun add_expand_pairs (x,ys) xys = List.foldl (fn (y,acc) => (x,y)::acc) xys ys;
paulson@24287
   211
paulson@24287
   212
fun consts_typs_of_term thy t = 
paulson@24287
   213
  let val tab = add_term_consts_typs_rm thy (t, null_const_tab)
paulson@24287
   214
  in  Symtab.fold add_expand_pairs tab []  end;
paulson@24287
   215
wenzelm@28477
   216
fun pair_consts_typs_axiom theory_const thy (thm,name) =
wenzelm@28477
   217
    ((thm,name), (consts_typs_of_term thy (const_prop_of theory_const thm)));
paulson@24287
   218
paulson@24287
   219
exception ConstFree;
paulson@24287
   220
fun dest_ConstFree (Const aT) = aT
paulson@24287
   221
  | dest_ConstFree (Free aT) = aT
paulson@24287
   222
  | dest_ConstFree _ = raise ConstFree;
paulson@24287
   223
paulson@24287
   224
(*Look for definitions of the form f ?x1 ... ?xn = t, but not reversed.*)
wenzelm@32994
   225
fun defines thy thm gctypes =
paulson@24287
   226
    let val tm = prop_of thm
wenzelm@32960
   227
        fun defs lhs rhs =
paulson@24287
   228
            let val (rator,args) = strip_comb lhs
wenzelm@32960
   229
                val ct = const_with_typ thy (dest_ConstFree rator)
haftmann@33037
   230
            in
haftmann@33037
   231
              forall is_Var args andalso uni_mem gctypes ct andalso
haftmann@33038
   232
                subset (op =) (Term.add_vars rhs [], Term.add_vars lhs [])
paulson@24287
   233
            end
wenzelm@32960
   234
            handle ConstFree => false
paulson@24287
   235
    in    
wenzelm@32960
   236
        case tm of Const ("Trueprop",_) $ (Const("op =",_) $ lhs $ rhs) => 
wenzelm@32960
   237
                   defs lhs rhs 
wenzelm@32960
   238
                 | _ => false
paulson@24287
   239
    end;
paulson@24287
   240
paulson@24287
   241
type annotd_cls = (thm * (string * int)) * ((string * const_typ list) list);
paulson@24287
   242
       
paulson@24287
   243
(*For a reverse sort, putting the largest values first.*)
paulson@24287
   244
fun compare_pairs ((_,w1),(_,w2)) = Real.compare (w2,w1);
paulson@24287
   245
paulson@24287
   246
(*Limit the number of new clauses, to prevent runaway acceptance.*)
wenzelm@28477
   247
fun take_best max_new (newpairs : (annotd_cls*real) list) =
paulson@24287
   248
  let val nnew = length newpairs
paulson@24287
   249
  in
wenzelm@28477
   250
    if nnew <= max_new then (map #1 newpairs, [])
paulson@24287
   251
    else 
paulson@24287
   252
      let val cls = sort compare_pairs newpairs
wenzelm@28477
   253
          val accepted = List.take (cls, max_new)
paulson@24287
   254
      in
blanchet@35826
   255
        SFP.trace_msg (fn () => ("Number of candidates, " ^ Int.toString nnew ^ 
wenzelm@32960
   256
                       ", exceeds the limit of " ^ Int.toString (max_new)));
blanchet@35826
   257
        SFP.trace_msg (fn () => ("Effective pass mark: " ^ Real.toString (#2 (List.last accepted))));
blanchet@35826
   258
        SFP.trace_msg (fn () => "Actually passed: " ^
paulson@24287
   259
          space_implode ", " (map (fn (((_,(name,_)),_),_) => name) accepted));
paulson@24287
   260
wenzelm@32960
   261
        (map #1 accepted, map #1 (List.drop (cls, max_new)))
paulson@24287
   262
      end
paulson@24287
   263
  end;
paulson@24287
   264
wenzelm@28477
   265
fun relevant_clauses max_new thy ctab p rel_consts =
paulson@24287
   266
  let fun relevant ([],_) [] = [] : (thm * (string * int)) list  (*Nothing added this iteration*)
wenzelm@32960
   267
        | relevant (newpairs,rejects) [] =
wenzelm@32960
   268
            let val (newrels,more_rejects) = take_best max_new newpairs
wenzelm@32960
   269
                val new_consts = maps #2 newrels
wenzelm@32960
   270
                val rel_consts' = List.foldl add_const_typ_table rel_consts new_consts
wenzelm@32960
   271
                val newp = p + (1.0-p) / convergence
wenzelm@32960
   272
            in
blanchet@35826
   273
              SFP.trace_msg (fn () => "relevant this iteration: " ^ Int.toString (length newrels));
wenzelm@32960
   274
               (map #1 newrels) @ 
wenzelm@32960
   275
               (relevant_clauses max_new thy ctab newp rel_consts' (more_rejects@rejects))
wenzelm@32960
   276
            end
wenzelm@32960
   277
        | relevant (newrels,rejects) ((ax as (clsthm as (_,(name,n)),consts_typs)) :: axs) =
wenzelm@32960
   278
            let val weight = clause_weight ctab rel_consts consts_typs
wenzelm@32960
   279
            in
wenzelm@32994
   280
              if p <= weight orelse (follow_defs andalso defines thy (#1 clsthm) rel_consts)
blanchet@35826
   281
              then (SFP.trace_msg (fn () => (name ^ " clause " ^ Int.toString n ^ 
wenzelm@32960
   282
                                            " passes: " ^ Real.toString weight));
wenzelm@32960
   283
                    relevant ((ax,weight)::newrels, rejects) axs)
wenzelm@32960
   284
              else relevant (newrels, ax::rejects) axs
wenzelm@32960
   285
            end
blanchet@35826
   286
    in  SFP.trace_msg (fn () => ("relevant_clauses, current pass mark = " ^ Real.toString p));
paulson@24287
   287
        relevant ([],[]) 
paulson@24287
   288
    end;
wenzelm@32960
   289
        
wenzelm@28477
   290
fun relevance_filter max_new theory_const thy axioms goals = 
wenzelm@28477
   291
 if run_relevance_filter andalso pass_mark >= 0.1
paulson@24287
   292
 then
paulson@31910
   293
  let val const_tab = List.foldl (count_axiom_consts theory_const thy) Symtab.empty axioms
paulson@24287
   294
      val goal_const_tab = get_goal_consts_typs thy goals
blanchet@35826
   295
      val _ = SFP.trace_msg (fn () => ("Initial constants: " ^
paulson@24287
   296
                                 space_implode ", " (Symtab.keys goal_const_tab)));
wenzelm@28477
   297
      val rels = relevant_clauses max_new thy const_tab (pass_mark) 
wenzelm@28477
   298
                   goal_const_tab  (map (pair_consts_typs_axiom theory_const thy) axioms)
paulson@24287
   299
  in
blanchet@35826
   300
      SFP.trace_msg (fn () => ("Total relevant: " ^ Int.toString (length rels)));
paulson@24287
   301
      rels
paulson@24287
   302
  end
paulson@24287
   303
 else axioms;
paulson@24287
   304
paulson@24287
   305
(***************************************************************)
mengj@19768
   306
(* Retrieving and filtering lemmas                             *)
mengj@19768
   307
(***************************************************************)
mengj@19768
   308
paulson@33022
   309
(*** retrieve lemmas and filter them ***)
mengj@19768
   310
mengj@19768
   311
(*Hashing to detect duplicate and variant clauses, e.g. from the [iff] attribute*)
mengj@19768
   312
paulson@22382
   313
fun setinsert (x,s) = Symtab.update (x,()) s;
mengj@19768
   314
paulson@20757
   315
(*Reject theorems with names like "List.filter.filter_list_def" or
paulson@21690
   316
  "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
paulson@20757
   317
fun is_package_def a =
wenzelm@30364
   318
  let val names = Long_Name.explode a
paulson@21690
   319
  in
paulson@21690
   320
     length names > 2 andalso
paulson@21690
   321
     not (hd names = "local") andalso
paulson@21690
   322
     String.isSuffix "_def" a  orelse  String.isSuffix "_defs" a
paulson@21690
   323
  end;
paulson@20757
   324
mengj@19768
   325
(** a hash function from Term.term to int, and also a hash table **)
mengj@19768
   326
val xor_words = List.foldl Word.xorb 0w0;
mengj@19768
   327
mengj@19768
   328
fun hashw_term ((Const(c,_)), w) = Polyhash.hashw_string (c,w)
paulson@20661
   329
  | hashw_term ((Free(a,_)), w) = Polyhash.hashw_string (a,w)
mengj@19768
   330
  | hashw_term ((Var(_,_)), w) = w
paulson@20661
   331
  | hashw_term ((Bound i), w) = Polyhash.hashw_int(i,w)
mengj@19768
   332
  | hashw_term ((Abs(_,_,t)), w) = hashw_term (t, w)
mengj@19768
   333
  | hashw_term ((P$Q), w) = hashw_term (Q, (hashw_term (P, w)));
mengj@19768
   334
paulson@21070
   335
fun hash_literal (Const("Not",_)$P) = Word.notb(hashw_term(P,0w0))
paulson@21070
   336
  | hash_literal P = hashw_term(P,0w0);
mengj@19768
   337
paulson@24958
   338
fun hash_term t = Word.toIntX (xor_words (map hash_literal (HOLogic.disjuncts (strip_Trueprop t))));
mengj@19768
   339
mengj@19768
   340
fun equal_thm (thm1,thm2) = Term.aconv(prop_of thm1, prop_of thm2);
paulson@20457
   341
paulson@22382
   342
exception HASH_CLAUSE;
paulson@22382
   343
mengj@19768
   344
(*Create a hash table for clauses, of the given size*)
mengj@19768
   345
fun mk_clause_table n =
paulson@20457
   346
      Polyhash.mkTable (hash_term o prop_of, equal_thm)
mengj@19768
   347
                       (n, HASH_CLAUSE);
mengj@19768
   348
paulson@20457
   349
(*Use a hash table to eliminate duplicates from xs. Argument is a list of
paulson@20868
   350
  (thm * (string * int)) tuples. The theorems are hashed into the table. *)
wenzelm@21588
   351
fun make_unique xs =
paulson@20868
   352
  let val ht = mk_clause_table 7000
paulson@20457
   353
  in
blanchet@35826
   354
      SFP.trace_msg (fn () => ("make_unique gets " ^ Int.toString (length xs) ^ " clauses"));
wenzelm@21588
   355
      app (ignore o Polyhash.peekInsert ht) xs;
paulson@20868
   356
      Polyhash.listItems ht
paulson@20457
   357
  end;
mengj@19768
   358
paulson@20868
   359
(*Remove existing axiom clauses from the conjecture clauses, as this can dramatically
paulson@20868
   360
  boost an ATP's performance (for some reason)*)
wenzelm@21588
   361
fun subtract_cls c_clauses ax_clauses =
paulson@20868
   362
  let val ht = mk_clause_table 2200
wenzelm@33035
   363
      fun known x = is_some (Polyhash.peek ht x)
paulson@20868
   364
  in
wenzelm@21588
   365
      app (ignore o Polyhash.peekInsert ht) ax_clauses;
wenzelm@21588
   366
      filter (not o known) c_clauses
paulson@20868
   367
  end;
mengj@19768
   368
paulson@21224
   369
fun all_valid_thms ctxt =
paulson@22382
   370
  let
wenzelm@26675
   371
    val global_facts = PureThy.facts_of (ProofContext.theory_of ctxt);
wenzelm@26278
   372
    val local_facts = ProofContext.facts_of ctxt;
wenzelm@33641
   373
    val full_space =
wenzelm@33641
   374
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts);
wenzelm@33641
   375
wenzelm@33641
   376
    fun valid_facts facts =
wenzelm@33641
   377
      (facts, []) |-> Facts.fold_static (fn (name, ths0) =>
wenzelm@33641
   378
        let
wenzelm@33641
   379
          fun check_thms a =
wenzelm@33641
   380
            (case try (ProofContext.get_thms ctxt) a of
wenzelm@33641
   381
              NONE => false
wenzelm@33641
   382
            | SOME ths1 => Thm.eq_thms (ths0, ths1));
wenzelm@33641
   383
wenzelm@33641
   384
          val name1 = Facts.extern facts name;
wenzelm@33641
   385
          val name2 = Name_Space.extern full_space name;
blanchet@35826
   386
          val ths = filter_out SFP.bad_for_atp ths0;
wenzelm@33641
   387
        in
wenzelm@33641
   388
          if Facts.is_concealed facts name orelse null ths orelse
wenzelm@33641
   389
            run_blacklist_filter andalso is_package_def name then I
wenzelm@33641
   390
          else
wenzelm@33641
   391
            (case find_first check_thms [name1, name2, name] of
wenzelm@33641
   392
              NONE => I
wenzelm@33641
   393
            | SOME a => cons (a, ths))
wenzelm@33641
   394
        end);
wenzelm@26675
   395
  in valid_facts global_facts @ valid_facts local_facts end;
paulson@21224
   396
wenzelm@33309
   397
fun multi_name a th (n, pairs) =
wenzelm@33309
   398
  (n + 1, (a ^ "(" ^ Int.toString n ^ ")", th) :: pairs);
paulson@21224
   399
wenzelm@33309
   400
fun add_single_names (a, []) pairs = pairs
wenzelm@33309
   401
  | add_single_names (a, [th]) pairs = (a, th) :: pairs
wenzelm@33309
   402
  | add_single_names (a, ths) pairs = #2 (fold (multi_name a) ths (1, pairs));
paulson@21431
   403
paulson@22382
   404
(*Ignore blacklisted basenames*)
wenzelm@33309
   405
fun add_multi_names (a, ths) pairs =
blanchet@35826
   406
  if (Long_Name.base_name a) mem_string SFP.multi_base_blacklist then pairs
wenzelm@33309
   407
  else add_single_names (a, ths) pairs;
paulson@21224
   408
paulson@21290
   409
fun is_multi (a, ths) = length ths > 1 orelse String.isSuffix ".axioms" a;
paulson@21290
   410
paulson@24286
   411
(*The single theorems go BEFORE the multiple ones. Blacklist is applied to all.*)
wenzelm@21588
   412
fun name_thm_pairs ctxt =
wenzelm@33309
   413
  let
wenzelm@33309
   414
    val (mults, singles) = List.partition is_multi (all_valid_thms ctxt)
wenzelm@33309
   415
    fun blacklisted (_, th) =
wenzelm@33316
   416
      run_blacklist_filter andalso Res_Blacklist.blacklisted ctxt th
paulson@24286
   417
  in
wenzelm@33309
   418
    filter_out blacklisted
wenzelm@33309
   419
      (fold add_single_names singles (fold add_multi_names mults []))
paulson@24286
   420
  end;
paulson@21224
   421
wenzelm@32091
   422
fun check_named ("", th) =
wenzelm@32091
   423
      (warning ("No name for theorem " ^ Display.string_of_thm_without_context th); false)
wenzelm@32994
   424
  | check_named _ = true;
paulson@19894
   425
paulson@33022
   426
fun get_all_lemmas ctxt =
paulson@19894
   427
  let val included_thms =
blanchet@35826
   428
        tap (fn ths => SFP.trace_msg
paulson@33022
   429
                     (fn () => ("Including all " ^ Int.toString (length ths) ^ " theorems")))
paulson@33022
   430
            (name_thm_pairs ctxt)
paulson@19894
   431
  in
immler@31410
   432
    filter check_named included_thms
paulson@19894
   433
  end;
mengj@19768
   434
paulson@21290
   435
(***************************************************************)
paulson@21290
   436
(* Type Classes Present in the Axiom or Conjecture Clauses     *)
paulson@21290
   437
(***************************************************************)
paulson@21290
   438
wenzelm@32952
   439
fun add_classes (sorts, cset) = List.foldl setinsert cset (flat sorts);
paulson@21290
   440
paulson@21290
   441
(*Remove this trivial type class*)
paulson@21290
   442
fun delete_type cset = Symtab.delete_safe "HOL.type" cset;
paulson@21290
   443
paulson@21290
   444
fun tvar_classes_of_terms ts =
wenzelm@29270
   445
  let val sorts_list = map (map #2 o OldTerm.term_tvars) ts
wenzelm@30190
   446
  in  Symtab.keys (delete_type (List.foldl add_classes Symtab.empty sorts_list))  end;
paulson@21290
   447
paulson@21290
   448
fun tfree_classes_of_terms ts =
wenzelm@29270
   449
  let val sorts_list = map (map #2 o OldTerm.term_tfrees) ts
wenzelm@30190
   450
  in  Symtab.keys (delete_type (List.foldl add_classes Symtab.empty sorts_list))  end;
paulson@20526
   451
paulson@21373
   452
(*fold type constructors*)
paulson@21373
   453
fun fold_type_consts f (Type (a, Ts)) x = fold (fold_type_consts f) Ts (f (a,x))
wenzelm@32994
   454
  | fold_type_consts _ _ x = x;
paulson@21373
   455
paulson@21373
   456
val add_type_consts_in_type = fold_type_consts setinsert;
paulson@21373
   457
paulson@21397
   458
(*Type constructors used to instantiate overloaded constants are the only ones needed.*)
paulson@21397
   459
fun add_type_consts_in_term thy =
paulson@21397
   460
  let val const_typargs = Sign.const_typargs thy
paulson@21397
   461
      fun add_tcs (Const cT) x = fold add_type_consts_in_type (const_typargs cT) x
wenzelm@32994
   462
        | add_tcs (Abs (_, _, u)) x = add_tcs u x
paulson@21397
   463
        | add_tcs (t $ u) x = add_tcs t (add_tcs u x)
paulson@21397
   464
        | add_tcs _ x = x
paulson@21397
   465
  in  add_tcs  end
paulson@21373
   466
paulson@21397
   467
fun type_consts_of_terms thy ts =
paulson@21397
   468
  Symtab.keys (fold (add_type_consts_in_term thy) ts Symtab.empty);
paulson@21373
   469
paulson@21373
   470
mengj@19194
   471
(***************************************************************)
mengj@19194
   472
(* ATP invocation methods setup                                *)
mengj@19194
   473
(***************************************************************)
mengj@19194
   474
paulson@20526
   475
(*Ensures that no higher-order theorems "leak out"*)
paulson@24958
   476
fun restrict_to_logic thy true cls = filter (Meson.is_fol_term thy o prop_of o fst) cls
paulson@24958
   477
  | restrict_to_logic thy false cls = cls;
paulson@20526
   478
paulson@21470
   479
(**** Predicates to detect unwanted clauses (prolific or likely to cause unsoundness) ****)
paulson@21470
   480
paulson@21470
   481
(** Too general means, positive equality literal with a variable X as one operand,
paulson@21470
   482
  when X does not occur properly in the other operand. This rules out clearly
paulson@21470
   483
  inconsistent clauses such as V=a|V=b, though it by no means guarantees soundness. **)
wenzelm@21588
   484
paulson@21470
   485
fun occurs ix =
paulson@21470
   486
    let fun occ(Var (jx,_)) = (ix=jx)
paulson@21470
   487
          | occ(t1$t2)      = occ t1 orelse occ t2
paulson@21470
   488
          | occ(Abs(_,_,t)) = occ t
paulson@21470
   489
          | occ _           = false
paulson@21470
   490
    in occ end;
paulson@21470
   491
haftmann@31723
   492
fun is_recordtype T = not (null (Record.dest_recTs T));
paulson@21470
   493
paulson@21470
   494
(*Unwanted equalities include
paulson@21470
   495
  (1) those between a variable that does not properly occur in the second operand,
paulson@21470
   496
  (2) those between a variable and a record, since these seem to be prolific "cases" thms
wenzelm@21588
   497
*)
paulson@21470
   498
fun too_general_eqterms (Var (ix,T), t) = not (occurs ix t) orelse is_recordtype T
paulson@21470
   499
  | too_general_eqterms _ = false;
paulson@21470
   500
paulson@21470
   501
fun too_general_equality (Const ("op =", _) $ x $ y) =
paulson@21470
   502
      too_general_eqterms (x,y) orelse too_general_eqterms(y,x)
paulson@21470
   503
  | too_general_equality _ = false;
paulson@21470
   504
paulson@21470
   505
(* tautologous? *)
paulson@21470
   506
fun is_taut (Const ("Trueprop", _) $ Const ("True", _)) = true
paulson@21470
   507
  | is_taut _ = false;
paulson@21470
   508
wenzelm@29267
   509
fun has_typed_var tycons = exists_subterm
wenzelm@29267
   510
  (fn Var (_, Type (a, _)) => member (op =) tycons a | _ => false);
paulson@21431
   511
paulson@22217
   512
(*Clauses are forbidden to contain variables of these types. The typical reason is that
paulson@22217
   513
  they lead to unsoundness. Note that "unit" satisfies numerous equations like ?X=().
paulson@22217
   514
  The resulting clause will have no type constraint, yielding false proofs. Even "bool"
paulson@22217
   515
  leads to many unsound proofs, though (obviously) only for higher-order problems.*)
paulson@24215
   516
val unwanted_types = ["Product_Type.unit","bool"];
paulson@22217
   517
paulson@21470
   518
fun unwanted t =
paulson@24958
   519
  is_taut t orelse has_typed_var unwanted_types t orelse
paulson@24958
   520
  forall too_general_equality (HOLogic.disjuncts (strip_Trueprop t));
paulson@21470
   521
paulson@21431
   522
(*Clauses containing variables of type "unit" or "bool" are unlikely to be useful and
paulson@21431
   523
  likely to lead to unsound proofs.*)
paulson@22217
   524
fun remove_unwanted_clauses cls = filter (not o unwanted o prop_of o fst) cls;
paulson@21431
   525
immler@30536
   526
fun isFO thy goal_cls = case linkup_logic_mode of
immler@30536
   527
      Auto => forall (Meson.is_fol_term thy) (map prop_of goal_cls)
immler@30536
   528
    | Fol => true
immler@30536
   529
    | Hol => false
immler@30536
   530
immler@31409
   531
fun get_relevant max_new theory_const (ctxt, (chain_ths, th)) goal_cls =
immler@30536
   532
  let
immler@30536
   533
    val thy = ProofContext.theory_of ctxt
Philipp@32552
   534
    val isFO = isFO thy goal_cls
wenzelm@33306
   535
    val included_cls = get_all_lemmas ctxt
blanchet@35826
   536
      |> SFP.cnf_rules_pairs thy |> make_unique
wenzelm@33306
   537
      |> restrict_to_logic thy isFO
wenzelm@33306
   538
      |> remove_unwanted_clauses
mengj@19194
   539
  in
paulson@33046
   540
    relevance_filter max_new theory_const thy included_cls (map prop_of goal_cls) 
immler@30536
   541
  end;
immler@30536
   542
immler@31752
   543
(* prepare for passing to writer,
immler@31752
   544
   create additional clauses based on the information from extra_cls *)
immler@31752
   545
fun prepare_clauses dfg goal_cls chain_ths axcls extra_cls thy =
immler@31409
   546
  let
Philipp@32866
   547
    (* add chain thms *)
wenzelm@33306
   548
    val chain_cls =
blanchet@35826
   549
      SFP.cnf_rules_pairs thy (filter check_named (map SFP.pairname chain_ths))
Philipp@32866
   550
    val axcls = chain_cls @ axcls
Philipp@32866
   551
    val extra_cls = chain_cls @ extra_cls
immler@31837
   552
    val isFO = isFO thy goal_cls
immler@31752
   553
    val ccls = subtract_cls goal_cls extra_cls
blanchet@35826
   554
    val _ = app (fn th => SFP.trace_msg (fn _ => Display.string_of_thm_global thy th)) ccls
immler@30536
   555
    val ccltms = map prop_of ccls
immler@31752
   556
    and axtms = map (prop_of o #1) extra_cls
immler@30536
   557
    val subs = tfree_classes_of_terms ccltms
immler@30536
   558
    and supers = tvar_classes_of_terms axtms
immler@30536
   559
    and tycons = type_consts_of_terms thy (ccltms@axtms)
immler@30536
   560
    (*TFrees in conjecture clauses; TVars in axiom clauses*)
blanchet@35826
   561
    val conjectures = SHC.make_conjecture_clauses dfg thy ccls
blanchet@35826
   562
    val (_, extra_clauses) = ListPair.unzip (SHC.make_axiom_clauses dfg thy extra_cls)
blanchet@35826
   563
    val (clnames,axiom_clauses) = ListPair.unzip (SHC.make_axiom_clauses dfg thy axcls)
blanchet@35826
   564
    val helper_clauses = SHC.get_helper_clauses dfg thy isFO (conjectures, extra_cls, [])
blanchet@35826
   565
    val (supers',arity_clauses) = SFC.make_arity_clauses_dfg dfg thy tycons supers
blanchet@35826
   566
    val classrel_clauses = SFC.make_classrel_clauses thy subs supers'
immler@30536
   567
  in
immler@31752
   568
    (Vector.fromList clnames,
immler@31865
   569
      (conjectures, axiom_clauses, extra_clauses, helper_clauses, classrel_clauses, arity_clauses))
immler@31409
   570
  end
quigley@15644
   571
paulson@15347
   572
end;
immler@30536
   573