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