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