src/HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
author blanchet
Wed Aug 25 17:49:52 2010 +0200 (2010-08-25 ago)
changeset 38744 2b6333f78a9e
parent 38743 69fa75354c58
child 38745 ad577fd62ee4
permissions -rw-r--r--
make relevance filter work in term of a "max_relevant" option + use Vampire SOS;
"max_relevant" is more reliable than "max_relevant_per_iter";
also made sure that the option is monotone -- larger values should lead to more axioms -- which wasn't always the case before;
SOS for Vampire makes a difference of about 3% (i.e. 3% more proofs are found)
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@38744
    14
  val name_thm_pairs_from_ref :
blanchet@38696
    15
    Proof.context -> unit Symtab.table -> thm list -> Facts.ref
blanchet@38744
    16
    -> ((unit -> string * bool) * (bool * thm)) list
blanchet@37347
    17
  val relevant_facts :
blanchet@38744
    18
    bool -> real -> real option -> int -> bool -> relevance_override
blanchet@37995
    19
    -> Proof.context * (thm list * 'a) -> term list -> term
blanchet@38698
    20
    -> ((string * bool) * 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@38652
    26
open Sledgehammer_Util
blanchet@38652
    27
blanchet@37616
    28
val trace = Unsynchronized.ref false
blanchet@37616
    29
fun trace_msg msg = if !trace then tracing (msg ()) else ()
blanchet@35826
    30
blanchet@37580
    31
val respect_no_atp = true
blanchet@37505
    32
blanchet@35966
    33
type relevance_override =
blanchet@35966
    34
  {add: Facts.ref list,
blanchet@35966
    35
   del: Facts.ref list,
blanchet@35966
    36
   only: bool}
paulson@21070
    37
blanchet@37616
    38
val sledgehammer_prefix = "Sledgehammer" ^ Long_Name.separator
blanchet@37616
    39
blanchet@38744
    40
fun repair_name reserved multi j name =
blanchet@38744
    41
  (name |> Symtab.defined reserved name ? quote) ^
blanchet@38744
    42
  (if multi then "(" ^ Int.toString j ^ ")" else "")
blanchet@38744
    43
blanchet@38744
    44
fun name_thm_pairs_from_ref ctxt reserved chained_ths xref =
blanchet@38744
    45
  let
blanchet@38744
    46
    val ths = ProofContext.get_fact ctxt xref
blanchet@38744
    47
    val name = Facts.string_of_ref xref
blanchet@38744
    48
    val multi = length ths > 1
blanchet@38744
    49
  in
blanchet@38744
    50
    fold (fn th => fn (j, rest) =>
blanchet@38744
    51
             (j + 1, (fn () => (repair_name reserved multi j name,
blanchet@38744
    52
                                member Thm.eq_thm chained_ths th),
blanchet@38744
    53
                      (multi, th)) :: rest))
blanchet@38744
    54
         ths (1, [])
blanchet@38744
    55
    |> snd
blanchet@38699
    56
  end
blanchet@37616
    57
wenzelm@28477
    58
(***************************************************************)
wenzelm@28477
    59
(* Relevance Filtering                                         *)
wenzelm@28477
    60
(***************************************************************)
mengj@19194
    61
paulson@24287
    62
(*** constants with types ***)
paulson@24287
    63
paulson@24287
    64
(*An abstraction of Isabelle types*)
blanchet@38744
    65
datatype pseudotype = PVar | PType of string * pseudotype list
blanchet@38744
    66
blanchet@38744
    67
fun string_for_pseudotype PVar = "?"
blanchet@38744
    68
  | string_for_pseudotype (PType (s, Ts)) =
blanchet@38744
    69
    (case Ts of
blanchet@38744
    70
       [] => ""
blanchet@38744
    71
     | [T] => string_for_pseudotype T
blanchet@38744
    72
     | Ts => string_for_pseudotypes Ts ^ " ") ^ s
blanchet@38744
    73
and string_for_pseudotypes Ts =
blanchet@38744
    74
  "(" ^ commas (map string_for_pseudotype Ts) ^ ")"
paulson@24287
    75
paulson@24287
    76
(*Is the second type an instance of the first one?*)
blanchet@38744
    77
fun match_pseudotype (PType (a, T), PType (b, U)) =
blanchet@38744
    78
    a = b andalso match_pseudotypes (T, U)
blanchet@38744
    79
  | match_pseudotype (PVar, _) = true
blanchet@38744
    80
  | match_pseudotype (_, PVar) = false
blanchet@38744
    81
and match_pseudotypes ([], []) = true
blanchet@38744
    82
  | match_pseudotypes (T :: Ts, U :: Us) =
blanchet@38744
    83
    match_pseudotype (T, U) andalso match_pseudotypes (Ts, Us)
paulson@24287
    84
paulson@24287
    85
(*Is there a unifiable constant?*)
blanchet@38744
    86
fun pseudoconst_mem f const_tab (c, c_typ) =
blanchet@38744
    87
  exists (curry (match_pseudotypes o f) c_typ)
blanchet@38744
    88
         (these (Symtab.lookup const_tab c))
blanchet@37505
    89
blanchet@38744
    90
fun pseudotype_for (Type (c,typs)) = PType (c, map pseudotype_for typs)
blanchet@38744
    91
  | pseudotype_for (TFree _) = PVar
blanchet@38744
    92
  | pseudotype_for (TVar _) = PVar
blanchet@38744
    93
(* Pairs a constant with the list of its type instantiations. *)
blanchet@38744
    94
fun pseudoconst_for thy (c, T) =
blanchet@38744
    95
  (c, map pseudotype_for (Sign.const_typargs thy (c, T)))
blanchet@38744
    96
  handle TYPE _ => (c, [])  (* Variable (locale constant): monomorphic *)
paulson@24287
    97
blanchet@38744
    98
fun string_for_pseudoconst (s, []) = s
blanchet@38744
    99
  | string_for_pseudoconst (s, Ts) = s ^ string_for_pseudotypes Ts
blanchet@38744
   100
fun string_for_super_pseudoconst (s, [[]]) = s
blanchet@38744
   101
  | string_for_super_pseudoconst (s, Tss) =
blanchet@38744
   102
    s ^ "{" ^ commas (map string_for_pseudotypes Tss) ^ "}"
paulson@24287
   103
paulson@24287
   104
(*Add a const/type pair to the table, but a [] entry means a standard connective,
paulson@24287
   105
  which we ignore.*)
blanchet@38687
   106
fun add_const_to_table (c, ctyps) =
blanchet@37502
   107
  Symtab.map_default (c, [ctyps])
blanchet@37502
   108
                     (fn [] => [] | ctypss => insert (op =) ctyps ctypss)
paulson@24287
   109
blanchet@38692
   110
fun is_formula_type T = (T = HOLogic.boolT orelse T = propT)
blanchet@38692
   111
blanchet@38744
   112
val fresh_prefix = "Sledgehammer.skolem."
blanchet@37537
   113
val flip = Option.map not
blanchet@38091
   114
(* These are typically simplified away by "Meson.presimplify". *)
blanchet@38682
   115
val boring_consts =
blanchet@38682
   116
  [@{const_name False}, @{const_name True}, @{const_name If}, @{const_name Let}]
blanchet@37537
   117
blanchet@38687
   118
fun get_consts thy pos ts =
blanchet@37505
   119
  let
blanchet@38587
   120
    (* We include free variables, as well as constants, to handle locales. For
blanchet@38587
   121
       each quantifiers that must necessarily be skolemized by the ATP, we
blanchet@38587
   122
       introduce a fresh constant to simulate the effect of Skolemization. *)
blanchet@37537
   123
    fun do_term t =
blanchet@37537
   124
      case t of
blanchet@38744
   125
        Const x => add_const_to_table (pseudoconst_for thy x)
blanchet@38687
   126
      | Free (s, _) => add_const_to_table (s, [])
blanchet@38688
   127
      | t1 $ t2 => fold do_term [t1, t2]
blanchet@38644
   128
      | Abs (_, _, t') => do_term t'
blanchet@37537
   129
      | _ => I
blanchet@38587
   130
    fun do_quantifier will_surely_be_skolemized body_t =
blanchet@37537
   131
      do_formula pos body_t
blanchet@38587
   132
      #> (if will_surely_be_skolemized then
blanchet@38687
   133
            add_const_to_table (gensym fresh_prefix, [])
blanchet@38587
   134
          else
blanchet@38587
   135
            I)
blanchet@38587
   136
    and do_term_or_formula T =
blanchet@38692
   137
      if is_formula_type T then do_formula NONE else do_term
blanchet@37537
   138
    and do_formula pos t =
blanchet@37537
   139
      case t of
blanchet@37537
   140
        Const (@{const_name all}, _) $ Abs (_, _, body_t) =>
blanchet@38587
   141
        do_quantifier (pos = SOME false) body_t
blanchet@37537
   142
      | @{const "==>"} $ t1 $ t2 =>
blanchet@37537
   143
        do_formula (flip pos) t1 #> do_formula pos t2
blanchet@37537
   144
      | Const (@{const_name "=="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38587
   145
        fold (do_term_or_formula T) [t1, t2]
blanchet@37537
   146
      | @{const Trueprop} $ t1 => do_formula pos t1
blanchet@37537
   147
      | @{const Not} $ t1 => do_formula (flip pos) t1
blanchet@37537
   148
      | Const (@{const_name All}, _) $ Abs (_, _, body_t) =>
blanchet@38587
   149
        do_quantifier (pos = SOME false) body_t
blanchet@37537
   150
      | Const (@{const_name Ex}, _) $ Abs (_, _, body_t) =>
blanchet@38587
   151
        do_quantifier (pos = SOME true) body_t
blanchet@37537
   152
      | @{const "op &"} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
blanchet@37537
   153
      | @{const "op |"} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
blanchet@37537
   154
      | @{const "op -->"} $ t1 $ t2 =>
blanchet@37537
   155
        do_formula (flip pos) t1 #> do_formula pos t2
blanchet@37537
   156
      | Const (@{const_name "op ="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38587
   157
        fold (do_term_or_formula T) [t1, t2]
blanchet@38587
   158
      | Const (@{const_name If}, Type (_, [_, Type (_, [T, _])]))
blanchet@38587
   159
        $ t1 $ t2 $ t3 =>
blanchet@38587
   160
        do_formula NONE t1 #> fold (do_term_or_formula T) [t2, t3]
blanchet@38587
   161
      | Const (@{const_name Ex1}, _) $ Abs (_, _, body_t) =>
blanchet@38587
   162
        do_quantifier (is_some pos) body_t
blanchet@38587
   163
      | Const (@{const_name Ball}, _) $ t1 $ Abs (_, _, body_t) =>
blanchet@38587
   164
        do_quantifier (pos = SOME false)
blanchet@38587
   165
                      (HOLogic.mk_imp (incr_boundvars 1 t1 $ Bound 0, body_t))
blanchet@38587
   166
      | Const (@{const_name Bex}, _) $ t1 $ Abs (_, _, body_t) =>
blanchet@38587
   167
        do_quantifier (pos = SOME true)
blanchet@38587
   168
                      (HOLogic.mk_conj (incr_boundvars 1 t1 $ Bound 0, body_t))
blanchet@37537
   169
      | (t0 as Const (_, @{typ bool})) $ t1 =>
blanchet@37537
   170
        do_term t0 #> do_formula pos t1  (* theory constant *)
blanchet@37537
   171
      | _ => do_term t
blanchet@37505
   172
  in
blanchet@38091
   173
    Symtab.empty |> fold (Symtab.update o rpair []) boring_consts
blanchet@37995
   174
                 |> fold (do_formula pos) ts
blanchet@37505
   175
  end
paulson@24287
   176
paulson@24287
   177
(*Inserts a dummy "constant" referring to the theory name, so that relevance
paulson@24287
   178
  takes the given theory into account.*)
blanchet@37616
   179
fun theory_const_prop_of theory_relevant th =
blanchet@37505
   180
  if theory_relevant then
blanchet@37505
   181
    let
blanchet@37505
   182
      val name = Context.theory_name (theory_of_thm th)
blanchet@37505
   183
      val t = Const (name ^ ". 1", @{typ bool})
blanchet@37505
   184
    in t $ prop_of th end
blanchet@37505
   185
  else
blanchet@37505
   186
    prop_of th
blanchet@37505
   187
paulson@24287
   188
(**** Constant / Type Frequencies ****)
paulson@24287
   189
blanchet@38743
   190
(* A two-dimensional symbol table counts frequencies of constants. It's keyed
blanchet@38743
   191
   first by constant name and second by its list of type instantiations. For the
blanchet@38744
   192
   latter, we need a linear ordering on "pseudotype list". *)
paulson@24287
   193
blanchet@38744
   194
fun pseudotype_ord p =
blanchet@38743
   195
  case p of
blanchet@38744
   196
    (PVar, PVar) => EQUAL
blanchet@38744
   197
  | (PVar, PType _) => LESS
blanchet@38744
   198
  | (PType _, PVar) => GREATER
blanchet@38744
   199
  | (PType q1, PType q2) =>
blanchet@38744
   200
    prod_ord fast_string_ord (dict_ord pseudotype_ord) (q1, q2)
paulson@24287
   201
blanchet@38743
   202
structure CTtab =
blanchet@38744
   203
  Table(type key = pseudotype list val ord = dict_ord pseudotype_ord)
paulson@24287
   204
blanchet@37616
   205
fun count_axiom_consts theory_relevant thy (_, th) =
blanchet@37503
   206
  let
blanchet@37503
   207
    fun do_const (a, T) =
blanchet@38744
   208
      let val (c, cts) = pseudoconst_for thy (a, T) in
blanchet@37503
   209
        (* Two-dimensional table update. Constant maps to types maps to
blanchet@37503
   210
           count. *)
blanchet@37503
   211
        CTtab.map_default (cts, 0) (Integer.add 1)
blanchet@37503
   212
        |> Symtab.map_default (c, CTtab.empty)
blanchet@37503
   213
      end
blanchet@37503
   214
    fun do_term (Const x) = do_const x
blanchet@37503
   215
      | do_term (Free x) = do_const x
blanchet@37503
   216
      | do_term (t $ u) = do_term t #> do_term u
blanchet@37503
   217
      | do_term (Abs (_, _, t)) = do_term t
blanchet@37503
   218
      | do_term _ = I
blanchet@37616
   219
  in th |> theory_const_prop_of theory_relevant |> do_term end
paulson@24287
   220
paulson@24287
   221
paulson@24287
   222
(**** Actual Filtering Code ****)
paulson@24287
   223
paulson@24287
   224
(*The frequency of a constant is the sum of those of all instances of its type.*)
blanchet@38744
   225
fun pseudoconst_freq match const_tab (c, cts) =
blanchet@38744
   226
  CTtab.fold (fn (cts', m) => match (cts, cts') ? Integer.add m)
blanchet@38686
   227
             (the (Symtab.lookup const_tab c)) 0
blanchet@38686
   228
  handle Option.Option => 0
blanchet@38686
   229
paulson@24287
   230
blanchet@38085
   231
(* A surprising number of theorems contain only a few significant constants.
blanchet@38085
   232
   These include all induction rules, and other general theorems. *)
blanchet@37503
   233
blanchet@37503
   234
(* "log" seems best in practice. A constant function of one ignores the constant
blanchet@37503
   235
   frequencies. *)
blanchet@38686
   236
fun rel_log (x : real) = 1.0 + 2.0 / Math.ln (x + 1.0)
blanchet@38686
   237
fun irrel_log (x : real) = Math.ln (x + 19.0) / 6.4
blanchet@37503
   238
blanchet@37503
   239
(* Computes a constant's weight, as determined by its frequency. *)
blanchet@38744
   240
val rel_weight = rel_log o real oo pseudoconst_freq match_pseudotypes
blanchet@38744
   241
val irrel_weight =
blanchet@38744
   242
  irrel_log o real oo pseudoconst_freq (match_pseudotypes o swap)
blanchet@38744
   243
(* fun irrel_weight _ _ = 1.0  FIXME: OLD CODE *)
paulson@24287
   244
blanchet@38687
   245
fun axiom_weight const_tab relevant_consts axiom_consts =
blanchet@38744
   246
  case axiom_consts |> List.partition (pseudoconst_mem I relevant_consts)
blanchet@38744
   247
                    ||> filter_out (pseudoconst_mem swap relevant_consts) of
blanchet@38744
   248
    ([], []) => 0.0
blanchet@38744
   249
  | (_, []) => 1.0
blanchet@38744
   250
  | (rel, irrel) =>
blanchet@38744
   251
    let
blanchet@38744
   252
      val rel_weight = fold (curry Real.+ o rel_weight const_tab) rel 0.0
blanchet@38744
   253
      val irrel_weight = fold (curry Real.+ o irrel_weight const_tab) irrel 0.0
blanchet@38744
   254
      val res = rel_weight / (rel_weight + irrel_weight)
blanchet@38744
   255
    in if Real.isFinite res then res else 0.0 end
blanchet@37505
   256
blanchet@38687
   257
fun consts_of_term thy t =
blanchet@38742
   258
  Symtab.fold (fn (x, ys) => fold (fn y => cons (x, y)) ys)
blanchet@38742
   259
              (get_consts thy (SOME true) [t]) []
paulson@24287
   260
blanchet@38687
   261
fun pair_consts_axiom theory_relevant thy axiom =
blanchet@37616
   262
  (axiom, axiom |> snd |> theory_const_prop_of theory_relevant
blanchet@38687
   263
                |> consts_of_term thy)
paulson@24287
   264
blanchet@38699
   265
type annotated_thm =
blanchet@38744
   266
  ((unit -> string * bool) * thm) * (string * pseudotype list) list
blanchet@37505
   267
blanchet@38744
   268
fun rev_compare_pairs ((_, w1), (_, w2)) = Real.compare (w2, w1)
paulson@24287
   269
blanchet@38744
   270
fun take_best max (new_pairs : (annotated_thm * real) list) =
blanchet@38744
   271
  let
blanchet@38744
   272
    val ((perfect, more_perfect), imperfect) =
blanchet@38744
   273
      new_pairs |> List.partition (fn (_, w) => w > 0.99999)
blanchet@38744
   274
                |>> chop (max - 1) ||> sort rev_compare_pairs
blanchet@38744
   275
    val (accepted, rejected) =
blanchet@38744
   276
      case more_perfect @ imperfect of
blanchet@38744
   277
        [] => (perfect, [])
blanchet@38744
   278
      | (q :: qs) => (q :: perfect, qs)
blanchet@38744
   279
  in
blanchet@38744
   280
    trace_msg (fn () => "Number of candidates: " ^
blanchet@38744
   281
                        string_of_int (length new_pairs));
blanchet@38744
   282
    trace_msg (fn () => "Effective threshold: " ^
blanchet@38744
   283
                        Real.toString (#2 (hd accepted)));
blanchet@38744
   284
    trace_msg (fn () => "Actually passed: " ^
blanchet@38744
   285
        (accepted |> map (fn (((name, _), _), weight) =>
blanchet@38744
   286
                             fst (name ()) ^ " [" ^ Real.toString weight ^ "]")
blanchet@38744
   287
                  |> commas));
blanchet@38744
   288
    (map #1 accepted, rejected)
blanchet@38744
   289
  end
paulson@24287
   290
blanchet@38683
   291
val threshold_divisor = 2.0
blanchet@38683
   292
val ridiculous_threshold = 0.1
blanchet@38683
   293
blanchet@38744
   294
fun relevance_filter ctxt relevance_threshold relevance_decay max_relevant
blanchet@38744
   295
                     theory_relevant ({add, del, ...} : relevance_override)
blanchet@38744
   296
                     axioms goal_ts =
blanchet@38739
   297
  let
blanchet@38739
   298
    val thy = ProofContext.theory_of ctxt
blanchet@38739
   299
    val const_tab = fold (count_axiom_consts theory_relevant thy) axioms
blanchet@38739
   300
                         Symtab.empty
blanchet@38739
   301
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@38739
   302
    val del_thms = maps (ProofContext.get_fact ctxt) del
blanchet@38744
   303
    fun iter j max threshold rel_const_tab rest =
blanchet@38739
   304
      let
blanchet@38744
   305
        fun game_over rejects =
blanchet@38744
   306
          if j = 0 andalso threshold >= ridiculous_threshold then
blanchet@38744
   307
            (* First iteration? Try again. *)
blanchet@38744
   308
            iter 0 max (threshold / threshold_divisor) rel_const_tab rejects
blanchet@38744
   309
          else
blanchet@38744
   310
            (* Add "add:" facts. *)
blanchet@38744
   311
            if null add_thms then
blanchet@38744
   312
              []
blanchet@38744
   313
            else
blanchet@38744
   314
              map_filter (fn ((p as (_, th), _), _) =>
blanchet@38744
   315
                             if member Thm.eq_thm add_thms th then SOME p
blanchet@38744
   316
                             else NONE) rejects
blanchet@38739
   317
        fun relevant ([], rejects) [] =
blanchet@38744
   318
            (* Nothing has been added this iteration. *)
blanchet@38744
   319
            game_over (map (apsnd SOME) rejects)
blanchet@38739
   320
          | relevant (new_pairs, rejects) [] =
blanchet@38739
   321
            let
blanchet@38744
   322
              val (new_rels, more_rejects) = take_best max new_pairs
blanchet@38739
   323
              val rel_const_tab' =
blanchet@38739
   324
                rel_const_tab |> fold add_const_to_table (maps snd new_rels)
blanchet@38744
   325
              fun is_dirty (c, _) =
blanchet@38744
   326
                Symtab.lookup rel_const_tab' c <> Symtab.lookup rel_const_tab c
blanchet@38739
   327
              val rejects =
blanchet@38739
   328
                more_rejects @ rejects
blanchet@38739
   329
                |> map (fn (ax as (_, consts), old_weight) =>
blanchet@38739
   330
                           (ax, if exists is_dirty consts then NONE
blanchet@38739
   331
                                else SOME old_weight))
blanchet@38739
   332
              val threshold = threshold + (1.0 - threshold) * relevance_decay
blanchet@38744
   333
              val max = max - length new_rels
blanchet@38739
   334
            in
blanchet@38744
   335
              trace_msg (fn () => "New or updated constants: " ^
blanchet@38744
   336
                  commas (rel_const_tab' |> Symtab.dest
blanchet@38744
   337
                          |> subtract (op =) (Symtab.dest rel_const_tab)
blanchet@38744
   338
                          |> map string_for_super_pseudoconst));
blanchet@38744
   339
              map #1 new_rels @
blanchet@38744
   340
              (if max = 0 then game_over rejects
blanchet@38744
   341
               else iter (j + 1) max threshold rel_const_tab' rejects)
blanchet@38739
   342
            end
blanchet@38739
   343
          | relevant (new_rels, rejects)
blanchet@38739
   344
                     (((ax as ((name, th), axiom_consts)), cached_weight)
blanchet@38739
   345
                      :: rest) =
blanchet@38739
   346
            let
blanchet@38739
   347
              val weight =
blanchet@38739
   348
                case cached_weight of
blanchet@38739
   349
                  SOME w => w
blanchet@38739
   350
                | NONE => axiom_weight const_tab rel_const_tab axiom_consts
blanchet@38739
   351
            in
blanchet@38741
   352
              if weight >= threshold then
blanchet@38744
   353
                relevant ((ax, weight) :: new_rels, rejects) rest
blanchet@38739
   354
              else
blanchet@38739
   355
                relevant (new_rels, (ax, weight) :: rejects) rest
blanchet@38739
   356
            end
blanchet@38739
   357
        in
blanchet@38744
   358
          trace_msg (fn () =>
blanchet@38744
   359
              "ITERATION " ^ string_of_int j ^ ": current threshold: " ^
blanchet@38744
   360
              Real.toString threshold ^ ", constants: " ^
blanchet@38744
   361
              commas (rel_const_tab |> Symtab.dest
blanchet@38744
   362
                      |> filter (curry (op <>) [] o snd)
blanchet@38744
   363
                      |> map string_for_super_pseudoconst));
blanchet@38744
   364
          relevant ([], []) rest
blanchet@38739
   365
        end
blanchet@38739
   366
  in
blanchet@38739
   367
    axioms |> filter_out (member Thm.eq_thm del_thms o snd)
blanchet@38739
   368
           |> map (rpair NONE o pair_consts_axiom theory_relevant thy)
blanchet@38744
   369
           |> iter 0 max_relevant relevance_threshold
blanchet@38744
   370
                   (get_consts thy (SOME false) goal_ts)
blanchet@38739
   371
           |> tap (fn res => trace_msg (fn () =>
blanchet@38686
   372
                                "Total relevant: " ^ Int.toString (length res)))
blanchet@38739
   373
  end
paulson@24287
   374
blanchet@38744
   375
paulson@24287
   376
(***************************************************************)
mengj@19768
   377
(* Retrieving and filtering lemmas                             *)
mengj@19768
   378
(***************************************************************)
mengj@19768
   379
paulson@33022
   380
(*** retrieve lemmas and filter them ***)
mengj@19768
   381
paulson@20757
   382
(*Reject theorems with names like "List.filter.filter_list_def" or
paulson@21690
   383
  "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
paulson@20757
   384
fun is_package_def a =
wenzelm@30364
   385
  let val names = Long_Name.explode a
paulson@21690
   386
  in
paulson@21690
   387
     length names > 2 andalso
paulson@21690
   388
     not (hd names = "local") andalso
paulson@21690
   389
     String.isSuffix "_def" a  orelse  String.isSuffix "_defs" a
paulson@21690
   390
  end;
paulson@20757
   391
blanchet@38085
   392
fun make_fact_table xs =
blanchet@37616
   393
  fold (Termtab.update o `(prop_of o snd)) xs Termtab.empty
blanchet@38085
   394
fun make_unique xs = Termtab.fold (cons o snd) (make_fact_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@38682
   399
   "split_asm", "cases", "ext_cases", "eq.simps", "eq.refl", "nchotomy",
blanchet@38682
   400
   "case_cong", "weak_case_cong"]
blanchet@38682
   401
  |> map (prefix ".")
blanchet@37626
   402
blanchet@37626
   403
val max_lambda_nesting = 3
blanchet@37626
   404
blanchet@37626
   405
fun term_has_too_many_lambdas max (t1 $ t2) =
blanchet@37626
   406
    exists (term_has_too_many_lambdas max) [t1, t2]
blanchet@37626
   407
  | term_has_too_many_lambdas max (Abs (_, _, t)) =
blanchet@37626
   408
    max = 0 orelse term_has_too_many_lambdas (max - 1) t
blanchet@37626
   409
  | term_has_too_many_lambdas _ _ = false
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@38692
   421
(* The max apply depth of any "metis" call in "Metis_Examples" (on 2007-10-31)
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@38085
   430
  apply_depth t > max_apply_depth orelse formula_has_too_many_lambdas [] t
blanchet@37626
   431
blanchet@37543
   432
val exists_sledgehammer_const =
blanchet@37626
   433
  exists_Const (fn (s, _) => String.isPrefix sledgehammer_prefix s)
blanchet@37626
   434
blanchet@38652
   435
fun is_strange_theorem th =
blanchet@37626
   436
  case head_of (concl_of th) of
blanchet@37626
   437
      Const (a, _) => (a <> @{const_name Trueprop} andalso
blanchet@37626
   438
                       a <> @{const_name "=="})
blanchet@37626
   439
    | _ => false
blanchet@37626
   440
blanchet@37626
   441
val type_has_top_sort =
blanchet@37626
   442
  exists_subtype (fn TFree (_, []) => true | TVar (_, []) => true | _ => false)
blanchet@37626
   443
blanchet@38085
   444
(**** Predicates to detect unwanted facts (prolific or likely to cause
blanchet@37347
   445
      unsoundness) ****)
paulson@21470
   446
blanchet@38289
   447
(* Too general means, positive equality literal with a variable X as one
blanchet@38289
   448
   operand, when X does not occur properly in the other operand. This rules out
blanchet@38289
   449
   clearly inconsistent facts such as X = a | X = b, though it by no means
blanchet@38289
   450
   guarantees soundness. *)
paulson@21470
   451
blanchet@38289
   452
(* Unwanted equalities are those between a (bound or schematic) variable that
blanchet@38289
   453
   does not properly occur in the second operand. *)
blanchet@38607
   454
val is_exhaustive_finite =
blanchet@38607
   455
  let
blanchet@38629
   456
    fun is_bad_equal (Var z) t =
blanchet@38629
   457
        not (exists_subterm (fn Var z' => z = z' | _ => false) t)
blanchet@38629
   458
      | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
blanchet@38629
   459
      | is_bad_equal _ _ = false
blanchet@38629
   460
    fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
blanchet@38607
   461
    fun do_formula pos t =
blanchet@38607
   462
      case (pos, t) of
blanchet@38615
   463
        (_, @{const Trueprop} $ t1) => do_formula pos t1
blanchet@38607
   464
      | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
blanchet@38607
   465
        do_formula pos t'
blanchet@38607
   466
      | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
blanchet@38607
   467
        do_formula pos t'
blanchet@38607
   468
      | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
blanchet@38607
   469
        do_formula pos t'
blanchet@38607
   470
      | (_, @{const "==>"} $ t1 $ t2) =>
blanchet@38629
   471
        do_formula (not pos) t1 andalso
blanchet@38629
   472
        (t2 = @{prop False} orelse do_formula pos t2)
blanchet@38607
   473
      | (_, @{const "op -->"} $ t1 $ t2) =>
blanchet@38629
   474
        do_formula (not pos) t1 andalso
blanchet@38629
   475
        (t2 = @{const False} orelse do_formula pos t2)
blanchet@38607
   476
      | (_, @{const Not} $ t1) => do_formula (not pos) t1
blanchet@38607
   477
      | (true, @{const "op |"} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@38607
   478
      | (false, @{const "op &"} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@38607
   479
      | (true, Const (@{const_name "op ="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38607
   480
      | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38607
   481
      | _ => false
blanchet@38607
   482
  in do_formula true end
blanchet@38607
   483
blanchet@38592
   484
fun has_bound_or_var_of_type tycons =
blanchet@38592
   485
  exists_subterm (fn Var (_, Type (s, _)) => member (op =) tycons s
blanchet@38592
   486
                   | Abs (_, Type (s, _), _) => member (op =) tycons s
blanchet@38592
   487
                   | _ => false)
paulson@21431
   488
blanchet@38085
   489
(* Facts are forbidden to contain variables of these types. The typical reason
blanchet@37347
   490
   is that they lead to unsoundness. Note that "unit" satisfies numerous
blanchet@38085
   491
   equations like "?x = ()". The resulting clauses will have no type constraint,
blanchet@37347
   492
   yielding false proofs. Even "bool" leads to many unsound proofs, though only
blanchet@37347
   493
   for higher-order problems. *)
blanchet@38592
   494
val dangerous_types = [@{type_name unit}, @{type_name bool}, @{type_name prop}];
paulson@22217
   495
blanchet@38085
   496
(* Facts containing variables of type "unit" or "bool" or of the form
blanchet@38290
   497
   "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
blanchet@38290
   498
   are omitted. *)
blanchet@38593
   499
fun is_dangerous_term full_types t =
blanchet@38609
   500
  not full_types andalso
blanchet@38679
   501
  let val t = transform_elim_term t in
blanchet@38679
   502
    has_bound_or_var_of_type dangerous_types t orelse
blanchet@38679
   503
    is_exhaustive_finite t
blanchet@38679
   504
  end
paulson@21470
   505
blanchet@38627
   506
fun is_theorem_bad_for_atps full_types thm =
blanchet@38627
   507
  let val t = prop_of thm in
blanchet@38627
   508
    is_formula_too_complex t orelse exists_type type_has_top_sort t orelse
blanchet@38627
   509
    is_dangerous_term full_types t orelse exists_sledgehammer_const t orelse
blanchet@38652
   510
    is_strange_theorem thm
blanchet@38627
   511
  end
blanchet@38627
   512
blanchet@38696
   513
fun all_name_thms_pairs ctxt reserved full_types add_thms chained_ths =
blanchet@38627
   514
  let
blanchet@38697
   515
    val is_chained = member Thm.eq_thm chained_ths
blanchet@38697
   516
    val global_facts = PureThy.facts_of (ProofContext.theory_of ctxt)
blanchet@38644
   517
    val local_facts = ProofContext.facts_of ctxt
blanchet@38644
   518
    val named_locals = local_facts |> Facts.dest_static []
blanchet@38697
   519
    (* Unnamed, not chained formulas with schematic variables are omitted,
blanchet@38697
   520
       because they are rejected by the backticks (`...`) parser for some
blanchet@38697
   521
       reason. *)
blanchet@38738
   522
    fun is_good_unnamed_local th =
blanchet@38738
   523
      forall (fn (_, ths) => not (member Thm.eq_thm ths th)) named_locals
blanchet@38738
   524
      andalso (not (exists_subterm is_Var (prop_of th)) orelse (is_chained th))
blanchet@38644
   525
    val unnamed_locals =
blanchet@38738
   526
      local_facts |> Facts.props |> filter is_good_unnamed_local
blanchet@38697
   527
                  |> map (pair "" o single)
blanchet@38627
   528
    val full_space =
blanchet@38738
   529
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts)
blanchet@38697
   530
    fun add_valid_facts foldx facts =
blanchet@38699
   531
      foldx (fn (name0, ths) =>
blanchet@38699
   532
        if name0 <> "" andalso
blanchet@38699
   533
           forall (not o member Thm.eq_thm add_thms) ths andalso
blanchet@38699
   534
           (Facts.is_concealed facts name0 orelse
blanchet@38699
   535
            (respect_no_atp andalso is_package_def name0) orelse
blanchet@38699
   536
            exists (fn s => String.isSuffix s name0) multi_base_blacklist orelse
blanchet@38699
   537
            String.isSuffix "_def_raw" (* FIXME: crude hack *) name0) then
blanchet@38627
   538
          I
blanchet@38627
   539
        else
blanchet@38627
   540
          let
blanchet@38699
   541
            val multi = length ths > 1
blanchet@38696
   542
            fun backquotify th =
blanchet@38696
   543
              "`" ^ Print_Mode.setmp [Print_Mode.input]
blanchet@38696
   544
                                 (Syntax.string_of_term ctxt) (prop_of th) ^ "`"
blanchet@38738
   545
              |> String.translate (fn c => if Char.isPrint c then str c else "")
blanchet@38738
   546
              |> simplify_spaces
blanchet@38699
   547
            fun check_thms a =
blanchet@38699
   548
              case try (ProofContext.get_thms ctxt) a of
blanchet@38699
   549
                NONE => false
blanchet@38699
   550
              | SOME ths' => Thm.eq_thms (ths, ths')
blanchet@38627
   551
          in
blanchet@38699
   552
            pair 1
blanchet@38699
   553
            #> fold (fn th => fn (j, rest) =>
blanchet@38699
   554
                 (j + 1,
blanchet@38699
   555
                  if is_theorem_bad_for_atps full_types th andalso
blanchet@38699
   556
                     not (member Thm.eq_thm add_thms th) then
blanchet@38699
   557
                    rest
blanchet@38699
   558
                  else
blanchet@38699
   559
                    (fn () =>
blanchet@38699
   560
                        (if name0 = "" then
blanchet@38699
   561
                           th |> backquotify
blanchet@38699
   562
                         else
blanchet@38699
   563
                           let
blanchet@38699
   564
                             val name1 = Facts.extern facts name0
blanchet@38699
   565
                             val name2 = Name_Space.extern full_space name0
blanchet@38699
   566
                           in
blanchet@38699
   567
                             case find_first check_thms [name1, name2, name0] of
blanchet@38744
   568
                               SOME name => repair_name reserved multi j name
blanchet@38699
   569
                             | NONE => ""
blanchet@38699
   570
                           end, is_chained th), (multi, th)) :: rest)) ths
blanchet@38699
   571
            #> snd
blanchet@38627
   572
          end)
blanchet@38644
   573
  in
blanchet@38688
   574
    [] |> add_valid_facts fold local_facts (unnamed_locals @ named_locals)
blanchet@38688
   575
       |> add_valid_facts Facts.fold_static global_facts global_facts
blanchet@38644
   576
  end
blanchet@38627
   577
blanchet@38627
   578
(* The single-name theorems go after the multiple-name ones, so that single
blanchet@38627
   579
   names are preferred when both are available. *)
blanchet@38699
   580
fun name_thm_pairs ctxt respect_no_atp =
blanchet@38744
   581
  List.partition (fst o snd) #> op @ #> map (apsnd snd)
blanchet@38699
   582
  #> respect_no_atp ? filter_out (No_ATPs.member ctxt o snd)
blanchet@38627
   583
blanchet@38627
   584
(***************************************************************)
blanchet@38627
   585
(* ATP invocation methods setup                                *)
blanchet@38627
   586
(***************************************************************)
blanchet@38627
   587
blanchet@38744
   588
fun relevant_facts full_types relevance_threshold relevance_decay max_relevant
blanchet@38744
   589
                   theory_relevant (relevance_override as {add, del, only})
blanchet@37995
   590
                   (ctxt, (chained_ths, _)) hyp_ts concl_t =
blanchet@37538
   591
  let
blanchet@38744
   592
    val relevance_decay =
blanchet@38744
   593
      case relevance_decay of
blanchet@38744
   594
        SOME x => x
blanchet@38744
   595
      | NONE => 0.35 / Math.ln (Real.fromInt (max_relevant + 1))
blanchet@37538
   596
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@38696
   597
    val reserved = reserved_isar_keyword_table ()
blanchet@37538
   598
    val axioms =
blanchet@38699
   599
      (if only then
blanchet@38744
   600
         maps (name_thm_pairs_from_ref ctxt reserved chained_ths) add
blanchet@38699
   601
       else
blanchet@38699
   602
         all_name_thms_pairs ctxt reserved full_types add_thms chained_ths)
blanchet@38688
   603
      |> name_thm_pairs ctxt (respect_no_atp andalso not only)
blanchet@38595
   604
      |> make_unique
blanchet@37538
   605
  in
blanchet@38688
   606
    trace_msg (fn () => "Considering " ^ Int.toString (length axioms) ^
blanchet@38688
   607
                        " theorems");
blanchet@38739
   608
    (if relevance_threshold > 1.0 then
blanchet@38739
   609
       []
blanchet@38739
   610
     else if relevance_threshold < 0.0 then
blanchet@38739
   611
       axioms
blanchet@38739
   612
     else
blanchet@38744
   613
       relevance_filter ctxt relevance_threshold relevance_decay max_relevant
blanchet@38744
   614
                        theory_relevant relevance_override axioms
blanchet@38744
   615
                                        (concl_t :: hyp_ts))
blanchet@38744
   616
    |> map (apfst (fn f => f ())) |> sort_wrt (fst o fst)
blanchet@37538
   617
  end
immler@30536
   618
paulson@15347
   619
end;