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