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