src/HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
author blanchet
Wed, 25 Aug 2010 17:49:52 +0200
changeset 38983 2b6333f78a9e
parent 38982 69fa75354c58
child 38984 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@38261
     2
    Author:     Jia Meng, Cambridge University Computer Laboratory and NICTA
blanchet@36393
     3
    Author:     Jasmin Blanchette, TU Muenchen
wenzelm@33317
     4
*)
paulson@15452
     5
blanchet@35826
     6
signature SLEDGEHAMMER_FACT_FILTER =
wenzelm@16802
     7
sig
blanchet@35964
     8
  type relevance_override =
blanchet@35964
     9
    {add: Facts.ref list,
blanchet@35964
    10
     del: Facts.ref list,
blanchet@35964
    11
     only: bool}
blanchet@35964
    12
blanchet@37616
    13
  val trace : bool Unsynchronized.ref
blanchet@38983
    14
  val name_thm_pairs_from_ref :
blanchet@38935
    15
    Proof.context -> unit Symtab.table -> thm list -> Facts.ref
blanchet@38983
    16
    -> ((unit -> string * bool) * (bool * thm)) list
blanchet@37347
    17
  val relevant_facts :
blanchet@38983
    18
    bool -> real -> real option -> int -> bool -> relevance_override
blanchet@38229
    19
    -> Proof.context * (thm list * 'a) -> term list -> term
blanchet@38937
    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@38890
    26
open Sledgehammer_Util
blanchet@38890
    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@35964
    33
type relevance_override =
blanchet@35964
    34
  {add: Facts.ref list,
blanchet@35964
    35
   del: Facts.ref list,
blanchet@35964
    36
   only: bool}
paulson@21070
    37
blanchet@37616
    38
val sledgehammer_prefix = "Sledgehammer" ^ Long_Name.separator
blanchet@37616
    39
blanchet@38983
    40
fun repair_name reserved multi j name =
blanchet@38983
    41
  (name |> Symtab.defined reserved name ? quote) ^
blanchet@38983
    42
  (if multi then "(" ^ Int.toString j ^ ")" else "")
blanchet@38983
    43
blanchet@38983
    44
fun name_thm_pairs_from_ref ctxt reserved chained_ths xref =
blanchet@38983
    45
  let
blanchet@38983
    46
    val ths = ProofContext.get_fact ctxt xref
blanchet@38983
    47
    val name = Facts.string_of_ref xref
blanchet@38983
    48
    val multi = length ths > 1
blanchet@38983
    49
  in
blanchet@38983
    50
    fold (fn th => fn (j, rest) =>
blanchet@38983
    51
             (j + 1, (fn () => (repair_name reserved multi j name,
blanchet@38983
    52
                                member Thm.eq_thm chained_ths th),
blanchet@38983
    53
                      (multi, th)) :: rest))
blanchet@38983
    54
         ths (1, [])
blanchet@38983
    55
    |> snd
blanchet@38938
    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@38983
    65
datatype pseudotype = PVar | PType of string * pseudotype list
blanchet@38983
    66
blanchet@38983
    67
fun string_for_pseudotype PVar = "?"
blanchet@38983
    68
  | string_for_pseudotype (PType (s, Ts)) =
blanchet@38983
    69
    (case Ts of
blanchet@38983
    70
       [] => ""
blanchet@38983
    71
     | [T] => string_for_pseudotype T
blanchet@38983
    72
     | Ts => string_for_pseudotypes Ts ^ " ") ^ s
blanchet@38983
    73
and string_for_pseudotypes Ts =
blanchet@38983
    74
  "(" ^ commas (map string_for_pseudotype Ts) ^ ")"
paulson@24287
    75
paulson@24287
    76
(*Is the second type an instance of the first one?*)
blanchet@38983
    77
fun match_pseudotype (PType (a, T), PType (b, U)) =
blanchet@38983
    78
    a = b andalso match_pseudotypes (T, U)
blanchet@38983
    79
  | match_pseudotype (PVar, _) = true
blanchet@38983
    80
  | match_pseudotype (_, PVar) = false
blanchet@38983
    81
and match_pseudotypes ([], []) = true
blanchet@38983
    82
  | match_pseudotypes (T :: Ts, U :: Us) =
blanchet@38983
    83
    match_pseudotype (T, U) andalso match_pseudotypes (Ts, Us)
paulson@24287
    84
paulson@24287
    85
(*Is there a unifiable constant?*)
blanchet@38983
    86
fun pseudoconst_mem f const_tab (c, c_typ) =
blanchet@38983
    87
  exists (curry (match_pseudotypes o f) c_typ)
blanchet@38983
    88
         (these (Symtab.lookup const_tab c))
blanchet@37505
    89
blanchet@38983
    90
fun pseudotype_for (Type (c,typs)) = PType (c, map pseudotype_for typs)
blanchet@38983
    91
  | pseudotype_for (TFree _) = PVar
blanchet@38983
    92
  | pseudotype_for (TVar _) = PVar
blanchet@38983
    93
(* Pairs a constant with the list of its type instantiations. *)
blanchet@38983
    94
fun pseudoconst_for thy (c, T) =
blanchet@38983
    95
  (c, map pseudotype_for (Sign.const_typargs thy (c, T)))
blanchet@38983
    96
  handle TYPE _ => (c, [])  (* Variable (locale constant): monomorphic *)
paulson@24287
    97
blanchet@38983
    98
fun string_for_pseudoconst (s, []) = s
blanchet@38983
    99
  | string_for_pseudoconst (s, Ts) = s ^ string_for_pseudotypes Ts
blanchet@38983
   100
fun string_for_super_pseudoconst (s, [[]]) = s
blanchet@38983
   101
  | string_for_super_pseudoconst (s, Tss) =
blanchet@38983
   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@38926
   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@38931
   110
fun is_formula_type T = (T = HOLogic.boolT orelse T = propT)
blanchet@38931
   111
blanchet@38983
   112
val fresh_prefix = "Sledgehammer.skolem."
blanchet@37533
   113
val flip = Option.map not
blanchet@38337
   114
(* These are typically simplified away by "Meson.presimplify". *)
blanchet@38921
   115
val boring_consts =
blanchet@38921
   116
  [@{const_name False}, @{const_name True}, @{const_name If}, @{const_name Let}]
blanchet@37533
   117
blanchet@38926
   118
fun get_consts thy pos ts =
blanchet@37505
   119
  let
blanchet@38810
   120
    (* We include free variables, as well as constants, to handle locales. For
blanchet@38810
   121
       each quantifiers that must necessarily be skolemized by the ATP, we
blanchet@38810
   122
       introduce a fresh constant to simulate the effect of Skolemization. *)
blanchet@37533
   123
    fun do_term t =
blanchet@37533
   124
      case t of
blanchet@38983
   125
        Const x => add_const_to_table (pseudoconst_for thy x)
blanchet@38926
   126
      | Free (s, _) => add_const_to_table (s, [])
blanchet@38927
   127
      | t1 $ t2 => fold do_term [t1, t2]
blanchet@38882
   128
      | Abs (_, _, t') => do_term t'
blanchet@37533
   129
      | _ => I
blanchet@38810
   130
    fun do_quantifier will_surely_be_skolemized body_t =
blanchet@37533
   131
      do_formula pos body_t
blanchet@38810
   132
      #> (if will_surely_be_skolemized then
blanchet@38926
   133
            add_const_to_table (gensym fresh_prefix, [])
blanchet@38810
   134
          else
blanchet@38810
   135
            I)
blanchet@38810
   136
    and do_term_or_formula T =
blanchet@38931
   137
      if is_formula_type T then do_formula NONE else do_term
blanchet@37533
   138
    and do_formula pos t =
blanchet@37533
   139
      case t of
blanchet@37533
   140
        Const (@{const_name all}, _) $ Abs (_, _, body_t) =>
blanchet@38810
   141
        do_quantifier (pos = SOME false) body_t
blanchet@37533
   142
      | @{const "==>"} $ t1 $ t2 =>
blanchet@37533
   143
        do_formula (flip pos) t1 #> do_formula pos t2
blanchet@37533
   144
      | Const (@{const_name "=="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38810
   145
        fold (do_term_or_formula T) [t1, t2]
blanchet@37533
   146
      | @{const Trueprop} $ t1 => do_formula pos t1
blanchet@37533
   147
      | @{const Not} $ t1 => do_formula (flip pos) t1
blanchet@37533
   148
      | Const (@{const_name All}, _) $ Abs (_, _, body_t) =>
blanchet@38810
   149
        do_quantifier (pos = SOME false) body_t
blanchet@37533
   150
      | Const (@{const_name Ex}, _) $ Abs (_, _, body_t) =>
blanchet@38810
   151
        do_quantifier (pos = SOME true) body_t
blanchet@37533
   152
      | @{const "op &"} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
blanchet@37533
   153
      | @{const "op |"} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
blanchet@37533
   154
      | @{const "op -->"} $ t1 $ t2 =>
blanchet@37533
   155
        do_formula (flip pos) t1 #> do_formula pos t2
blanchet@37533
   156
      | Const (@{const_name "op ="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38810
   157
        fold (do_term_or_formula T) [t1, t2]
blanchet@38810
   158
      | Const (@{const_name If}, Type (_, [_, Type (_, [T, _])]))
blanchet@38810
   159
        $ t1 $ t2 $ t3 =>
blanchet@38810
   160
        do_formula NONE t1 #> fold (do_term_or_formula T) [t2, t3]
blanchet@38810
   161
      | Const (@{const_name Ex1}, _) $ Abs (_, _, body_t) =>
blanchet@38810
   162
        do_quantifier (is_some pos) body_t
blanchet@38810
   163
      | Const (@{const_name Ball}, _) $ t1 $ Abs (_, _, body_t) =>
blanchet@38810
   164
        do_quantifier (pos = SOME false)
blanchet@38810
   165
                      (HOLogic.mk_imp (incr_boundvars 1 t1 $ Bound 0, body_t))
blanchet@38810
   166
      | Const (@{const_name Bex}, _) $ t1 $ Abs (_, _, body_t) =>
blanchet@38810
   167
        do_quantifier (pos = SOME true)
blanchet@38810
   168
                      (HOLogic.mk_conj (incr_boundvars 1 t1 $ Bound 0, body_t))
blanchet@37533
   169
      | (t0 as Const (_, @{typ bool})) $ t1 =>
blanchet@37533
   170
        do_term t0 #> do_formula pos t1  (* theory constant *)
blanchet@37533
   171
      | _ => do_term t
blanchet@37505
   172
  in
blanchet@38337
   173
    Symtab.empty |> fold (Symtab.update o rpair []) boring_consts
blanchet@38229
   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@38982
   190
(* A two-dimensional symbol table counts frequencies of constants. It's keyed
blanchet@38982
   191
   first by constant name and second by its list of type instantiations. For the
blanchet@38983
   192
   latter, we need a linear ordering on "pseudotype list". *)
blanchet@37505
   193
blanchet@38983
   194
fun pseudotype_ord p =
blanchet@38982
   195
  case p of
blanchet@38983
   196
    (PVar, PVar) => EQUAL
blanchet@38983
   197
  | (PVar, PType _) => LESS
blanchet@38983
   198
  | (PType _, PVar) => GREATER
blanchet@38983
   199
  | (PType q1, PType q2) =>
blanchet@38983
   200
    prod_ord fast_string_ord (dict_ord pseudotype_ord) (q1, q2)
paulson@24287
   201
blanchet@38982
   202
structure CTtab =
blanchet@38983
   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@38983
   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@38983
   225
fun pseudoconst_freq match const_tab (c, cts) =
blanchet@38983
   226
  CTtab.fold (fn (cts', m) => match (cts, cts') ? Integer.add m)
blanchet@38925
   227
             (the (Symtab.lookup const_tab c)) 0
blanchet@38925
   228
  handle Option.Option => 0
blanchet@38925
   229
paulson@24287
   230
blanchet@38331
   231
(* A surprising number of theorems contain only a few significant constants.
blanchet@38331
   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@38925
   236
fun rel_log (x : real) = 1.0 + 2.0 / Math.ln (x + 1.0)
blanchet@38925
   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@38983
   240
val rel_weight = rel_log o real oo pseudoconst_freq match_pseudotypes
blanchet@38983
   241
val irrel_weight =
blanchet@38983
   242
  irrel_log o real oo pseudoconst_freq (match_pseudotypes o swap)
blanchet@38983
   243
(* fun irrel_weight _ _ = 1.0  FIXME: OLD CODE *)
paulson@24287
   244
blanchet@38926
   245
fun axiom_weight const_tab relevant_consts axiom_consts =
blanchet@38983
   246
  case axiom_consts |> List.partition (pseudoconst_mem I relevant_consts)
blanchet@38983
   247
                    ||> filter_out (pseudoconst_mem swap relevant_consts) of
blanchet@38983
   248
    ([], []) => 0.0
blanchet@38983
   249
  | (_, []) => 1.0
blanchet@38983
   250
  | (rel, irrel) =>
blanchet@38983
   251
    let
blanchet@38983
   252
      val rel_weight = fold (curry Real.+ o rel_weight const_tab) rel 0.0
blanchet@38983
   253
      val irrel_weight = fold (curry Real.+ o irrel_weight const_tab) irrel 0.0
blanchet@38983
   254
      val res = rel_weight / (rel_weight + irrel_weight)
blanchet@38983
   255
    in if Real.isFinite res then res else 0.0 end
blanchet@37505
   256
blanchet@38926
   257
fun consts_of_term thy t =
blanchet@38981
   258
  Symtab.fold (fn (x, ys) => fold (fn y => cons (x, y)) ys)
blanchet@38981
   259
              (get_consts thy (SOME true) [t]) []
paulson@24287
   260
blanchet@38926
   261
fun pair_consts_axiom theory_relevant thy axiom =
blanchet@37616
   262
  (axiom, axiom |> snd |> theory_const_prop_of theory_relevant
blanchet@38926
   263
                |> consts_of_term thy)
paulson@24287
   264
blanchet@38938
   265
type annotated_thm =
blanchet@38983
   266
  ((unit -> string * bool) * thm) * (string * pseudotype list) list
blanchet@37505
   267
blanchet@38983
   268
fun rev_compare_pairs ((_, w1), (_, w2)) = Real.compare (w2, w1)
paulson@24287
   269
blanchet@38983
   270
fun take_best max (new_pairs : (annotated_thm * real) list) =
blanchet@38983
   271
  let
blanchet@38983
   272
    val ((perfect, more_perfect), imperfect) =
blanchet@38983
   273
      new_pairs |> List.partition (fn (_, w) => w > 0.99999)
blanchet@38983
   274
                |>> chop (max - 1) ||> sort rev_compare_pairs
blanchet@38983
   275
    val (accepted, rejected) =
blanchet@38983
   276
      case more_perfect @ imperfect of
blanchet@38983
   277
        [] => (perfect, [])
blanchet@38983
   278
      | (q :: qs) => (q :: perfect, qs)
blanchet@38983
   279
  in
blanchet@38983
   280
    trace_msg (fn () => "Number of candidates: " ^
blanchet@38983
   281
                        string_of_int (length new_pairs));
blanchet@38983
   282
    trace_msg (fn () => "Effective threshold: " ^
blanchet@38983
   283
                        Real.toString (#2 (hd accepted)));
blanchet@38983
   284
    trace_msg (fn () => "Actually passed: " ^
blanchet@38983
   285
        (accepted |> map (fn (((name, _), _), weight) =>
blanchet@38983
   286
                             fst (name ()) ^ " [" ^ Real.toString weight ^ "]")
blanchet@38983
   287
                  |> commas));
blanchet@38983
   288
    (map #1 accepted, rejected)
blanchet@38983
   289
  end
paulson@24287
   290
blanchet@38922
   291
val threshold_divisor = 2.0
blanchet@38922
   292
val ridiculous_threshold = 0.1
blanchet@38922
   293
blanchet@38983
   294
fun relevance_filter ctxt relevance_threshold relevance_decay max_relevant
blanchet@38983
   295
                     theory_relevant ({add, del, ...} : relevance_override)
blanchet@38983
   296
                     axioms goal_ts =
blanchet@38978
   297
  let
blanchet@38978
   298
    val thy = ProofContext.theory_of ctxt
blanchet@38978
   299
    val const_tab = fold (count_axiom_consts theory_relevant thy) axioms
blanchet@38978
   300
                         Symtab.empty
blanchet@38978
   301
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@38978
   302
    val del_thms = maps (ProofContext.get_fact ctxt) del
blanchet@38983
   303
    fun iter j max threshold rel_const_tab rest =
blanchet@38978
   304
      let
blanchet@38983
   305
        fun game_over rejects =
blanchet@38983
   306
          if j = 0 andalso threshold >= ridiculous_threshold then
blanchet@38983
   307
            (* First iteration? Try again. *)
blanchet@38983
   308
            iter 0 max (threshold / threshold_divisor) rel_const_tab rejects
blanchet@38983
   309
          else
blanchet@38983
   310
            (* Add "add:" facts. *)
blanchet@38983
   311
            if null add_thms then
blanchet@38983
   312
              []
blanchet@38983
   313
            else
blanchet@38983
   314
              map_filter (fn ((p as (_, th), _), _) =>
blanchet@38983
   315
                             if member Thm.eq_thm add_thms th then SOME p
blanchet@38983
   316
                             else NONE) rejects
blanchet@38978
   317
        fun relevant ([], rejects) [] =
blanchet@38983
   318
            (* Nothing has been added this iteration. *)
blanchet@38983
   319
            game_over (map (apsnd SOME) rejects)
blanchet@38978
   320
          | relevant (new_pairs, rejects) [] =
blanchet@38978
   321
            let
blanchet@38983
   322
              val (new_rels, more_rejects) = take_best max new_pairs
blanchet@38978
   323
              val rel_const_tab' =
blanchet@38978
   324
                rel_const_tab |> fold add_const_to_table (maps snd new_rels)
blanchet@38983
   325
              fun is_dirty (c, _) =
blanchet@38983
   326
                Symtab.lookup rel_const_tab' c <> Symtab.lookup rel_const_tab c
blanchet@38978
   327
              val rejects =
blanchet@38978
   328
                more_rejects @ rejects
blanchet@38978
   329
                |> map (fn (ax as (_, consts), old_weight) =>
blanchet@38978
   330
                           (ax, if exists is_dirty consts then NONE
blanchet@38978
   331
                                else SOME old_weight))
blanchet@38978
   332
              val threshold = threshold + (1.0 - threshold) * relevance_decay
blanchet@38983
   333
              val max = max - length new_rels
blanchet@38978
   334
            in
blanchet@38983
   335
              trace_msg (fn () => "New or updated constants: " ^
blanchet@38983
   336
                  commas (rel_const_tab' |> Symtab.dest
blanchet@38983
   337
                          |> subtract (op =) (Symtab.dest rel_const_tab)
blanchet@38983
   338
                          |> map string_for_super_pseudoconst));
blanchet@38983
   339
              map #1 new_rels @
blanchet@38983
   340
              (if max = 0 then game_over rejects
blanchet@38983
   341
               else iter (j + 1) max threshold rel_const_tab' rejects)
blanchet@38978
   342
            end
blanchet@38978
   343
          | relevant (new_rels, rejects)
blanchet@38978
   344
                     (((ax as ((name, th), axiom_consts)), cached_weight)
blanchet@38978
   345
                      :: rest) =
blanchet@38978
   346
            let
blanchet@38978
   347
              val weight =
blanchet@38978
   348
                case cached_weight of
blanchet@38978
   349
                  SOME w => w
blanchet@38978
   350
                | NONE => axiom_weight const_tab rel_const_tab axiom_consts
blanchet@38978
   351
            in
blanchet@38980
   352
              if weight >= threshold then
blanchet@38983
   353
                relevant ((ax, weight) :: new_rels, rejects) rest
blanchet@38978
   354
              else
blanchet@38978
   355
                relevant (new_rels, (ax, weight) :: rejects) rest
blanchet@38978
   356
            end
blanchet@38978
   357
        in
blanchet@38983
   358
          trace_msg (fn () =>
blanchet@38983
   359
              "ITERATION " ^ string_of_int j ^ ": current threshold: " ^
blanchet@38983
   360
              Real.toString threshold ^ ", constants: " ^
blanchet@38983
   361
              commas (rel_const_tab |> Symtab.dest
blanchet@38983
   362
                      |> filter (curry (op <>) [] o snd)
blanchet@38983
   363
                      |> map string_for_super_pseudoconst));
blanchet@38983
   364
          relevant ([], []) rest
blanchet@38978
   365
        end
blanchet@38978
   366
  in
blanchet@38978
   367
    axioms |> filter_out (member Thm.eq_thm del_thms o snd)
blanchet@38978
   368
           |> map (rpair NONE o pair_consts_axiom theory_relevant thy)
blanchet@38983
   369
           |> iter 0 max_relevant relevance_threshold
blanchet@38983
   370
                   (get_consts thy (SOME false) goal_ts)
blanchet@38978
   371
           |> tap (fn res => trace_msg (fn () =>
blanchet@38925
   372
                                "Total relevant: " ^ Int.toString (length res)))
blanchet@38978
   373
  end
paulson@24287
   374
blanchet@38983
   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@38331
   392
fun make_fact_table xs =
blanchet@37616
   393
  fold (Termtab.update o `(prop_of o snd)) xs Termtab.empty
blanchet@38331
   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@38921
   399
   "split_asm", "cases", "ext_cases", "eq.simps", "eq.refl", "nchotomy",
blanchet@38921
   400
   "case_cong", "weak_case_cong"]
blanchet@38921
   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@38931
   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@38331
   430
  apply_depth t > max_apply_depth orelse formula_has_too_many_lambdas [] t
blanchet@37626
   431
blanchet@37539
   432
val exists_sledgehammer_const =
blanchet@37626
   433
  exists_Const (fn (s, _) => String.isPrefix sledgehammer_prefix s)
blanchet@37626
   434
blanchet@38890
   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@38331
   444
(**** Predicates to detect unwanted facts (prolific or likely to cause
blanchet@37347
   445
      unsoundness) ****)
paulson@21470
   446
blanchet@38513
   447
(* Too general means, positive equality literal with a variable X as one
blanchet@38513
   448
   operand, when X does not occur properly in the other operand. This rules out
blanchet@38513
   449
   clearly inconsistent facts such as X = a | X = b, though it by no means
blanchet@38513
   450
   guarantees soundness. *)
paulson@21470
   451
blanchet@38513
   452
(* Unwanted equalities are those between a (bound or schematic) variable that
blanchet@38513
   453
   does not properly occur in the second operand. *)
blanchet@38830
   454
val is_exhaustive_finite =
blanchet@38830
   455
  let
blanchet@38852
   456
    fun is_bad_equal (Var z) t =
blanchet@38852
   457
        not (exists_subterm (fn Var z' => z = z' | _ => false) t)
blanchet@38852
   458
      | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
blanchet@38852
   459
      | is_bad_equal _ _ = false
blanchet@38852
   460
    fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
blanchet@38830
   461
    fun do_formula pos t =
blanchet@38830
   462
      case (pos, t) of
blanchet@38838
   463
        (_, @{const Trueprop} $ t1) => do_formula pos t1
blanchet@38830
   464
      | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
blanchet@38830
   465
        do_formula pos t'
blanchet@38830
   466
      | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
blanchet@38830
   467
        do_formula pos t'
blanchet@38830
   468
      | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
blanchet@38830
   469
        do_formula pos t'
blanchet@38830
   470
      | (_, @{const "==>"} $ t1 $ t2) =>
blanchet@38852
   471
        do_formula (not pos) t1 andalso
blanchet@38852
   472
        (t2 = @{prop False} orelse do_formula pos t2)
blanchet@38830
   473
      | (_, @{const "op -->"} $ t1 $ t2) =>
blanchet@38852
   474
        do_formula (not pos) t1 andalso
blanchet@38852
   475
        (t2 = @{const False} orelse do_formula pos t2)
blanchet@38830
   476
      | (_, @{const Not} $ t1) => do_formula (not pos) t1
blanchet@38830
   477
      | (true, @{const "op |"} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@38830
   478
      | (false, @{const "op &"} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@38830
   479
      | (true, Const (@{const_name "op ="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38830
   480
      | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38830
   481
      | _ => false
blanchet@38830
   482
  in do_formula true end
blanchet@38830
   483
blanchet@38815
   484
fun has_bound_or_var_of_type tycons =
blanchet@38815
   485
  exists_subterm (fn Var (_, Type (s, _)) => member (op =) tycons s
blanchet@38815
   486
                   | Abs (_, Type (s, _), _) => member (op =) tycons s
blanchet@38815
   487
                   | _ => false)
paulson@21431
   488
blanchet@38331
   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@38331
   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@38815
   494
val dangerous_types = [@{type_name unit}, @{type_name bool}, @{type_name prop}];
paulson@22217
   495
blanchet@38331
   496
(* Facts containing variables of type "unit" or "bool" or of the form
blanchet@38514
   497
   "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
blanchet@38514
   498
   are omitted. *)
blanchet@38816
   499
fun is_dangerous_term full_types t =
blanchet@38832
   500
  not full_types andalso
blanchet@38918
   501
  let val t = transform_elim_term t in
blanchet@38918
   502
    has_bound_or_var_of_type dangerous_types t orelse
blanchet@38918
   503
    is_exhaustive_finite t
blanchet@38918
   504
  end
paulson@21470
   505
blanchet@38850
   506
fun is_theorem_bad_for_atps full_types thm =
blanchet@38850
   507
  let val t = prop_of thm in
blanchet@38850
   508
    is_formula_too_complex t orelse exists_type type_has_top_sort t orelse
blanchet@38850
   509
    is_dangerous_term full_types t orelse exists_sledgehammer_const t orelse
blanchet@38890
   510
    is_strange_theorem thm
blanchet@38850
   511
  end
blanchet@38850
   512
blanchet@38935
   513
fun all_name_thms_pairs ctxt reserved full_types add_thms chained_ths =
blanchet@38850
   514
  let
blanchet@38936
   515
    val is_chained = member Thm.eq_thm chained_ths
blanchet@38936
   516
    val global_facts = PureThy.facts_of (ProofContext.theory_of ctxt)
blanchet@38882
   517
    val local_facts = ProofContext.facts_of ctxt
blanchet@38882
   518
    val named_locals = local_facts |> Facts.dest_static []
blanchet@38936
   519
    (* Unnamed, not chained formulas with schematic variables are omitted,
blanchet@38936
   520
       because they are rejected by the backticks (`...`) parser for some
blanchet@38936
   521
       reason. *)
blanchet@38977
   522
    fun is_good_unnamed_local th =
blanchet@38977
   523
      forall (fn (_, ths) => not (member Thm.eq_thm ths th)) named_locals
blanchet@38977
   524
      andalso (not (exists_subterm is_Var (prop_of th)) orelse (is_chained th))
blanchet@38882
   525
    val unnamed_locals =
blanchet@38977
   526
      local_facts |> Facts.props |> filter is_good_unnamed_local
blanchet@38936
   527
                  |> map (pair "" o single)
blanchet@38850
   528
    val full_space =
blanchet@38977
   529
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts)
blanchet@38936
   530
    fun add_valid_facts foldx facts =
blanchet@38938
   531
      foldx (fn (name0, ths) =>
blanchet@38938
   532
        if name0 <> "" andalso
blanchet@38938
   533
           forall (not o member Thm.eq_thm add_thms) ths andalso
blanchet@38938
   534
           (Facts.is_concealed facts name0 orelse
blanchet@38938
   535
            (respect_no_atp andalso is_package_def name0) orelse
blanchet@38938
   536
            exists (fn s => String.isSuffix s name0) multi_base_blacklist orelse
blanchet@38938
   537
            String.isSuffix "_def_raw" (* FIXME: crude hack *) name0) then
blanchet@38850
   538
          I
blanchet@38850
   539
        else
blanchet@38850
   540
          let
blanchet@38938
   541
            val multi = length ths > 1
blanchet@38935
   542
            fun backquotify th =
blanchet@38935
   543
              "`" ^ Print_Mode.setmp [Print_Mode.input]
blanchet@38935
   544
                                 (Syntax.string_of_term ctxt) (prop_of th) ^ "`"
blanchet@38977
   545
              |> String.translate (fn c => if Char.isPrint c then str c else "")
blanchet@38977
   546
              |> simplify_spaces
blanchet@38938
   547
            fun check_thms a =
blanchet@38938
   548
              case try (ProofContext.get_thms ctxt) a of
blanchet@38938
   549
                NONE => false
blanchet@38938
   550
              | SOME ths' => Thm.eq_thms (ths, ths')
blanchet@38850
   551
          in
blanchet@38938
   552
            pair 1
blanchet@38938
   553
            #> fold (fn th => fn (j, rest) =>
blanchet@38938
   554
                 (j + 1,
blanchet@38938
   555
                  if is_theorem_bad_for_atps full_types th andalso
blanchet@38938
   556
                     not (member Thm.eq_thm add_thms th) then
blanchet@38938
   557
                    rest
blanchet@38938
   558
                  else
blanchet@38938
   559
                    (fn () =>
blanchet@38938
   560
                        (if name0 = "" then
blanchet@38938
   561
                           th |> backquotify
blanchet@38938
   562
                         else
blanchet@38938
   563
                           let
blanchet@38938
   564
                             val name1 = Facts.extern facts name0
blanchet@38938
   565
                             val name2 = Name_Space.extern full_space name0
blanchet@38938
   566
                           in
blanchet@38938
   567
                             case find_first check_thms [name1, name2, name0] of
blanchet@38983
   568
                               SOME name => repair_name reserved multi j name
blanchet@38938
   569
                             | NONE => ""
blanchet@38938
   570
                           end, is_chained th), (multi, th)) :: rest)) ths
blanchet@38938
   571
            #> snd
blanchet@38850
   572
          end)
blanchet@38882
   573
  in
blanchet@38927
   574
    [] |> add_valid_facts fold local_facts (unnamed_locals @ named_locals)
blanchet@38927
   575
       |> add_valid_facts Facts.fold_static global_facts global_facts
blanchet@38882
   576
  end
blanchet@38850
   577
blanchet@38850
   578
(* The single-name theorems go after the multiple-name ones, so that single
blanchet@38850
   579
   names are preferred when both are available. *)
blanchet@38938
   580
fun name_thm_pairs ctxt respect_no_atp =
blanchet@38983
   581
  List.partition (fst o snd) #> op @ #> map (apsnd snd)
blanchet@38938
   582
  #> respect_no_atp ? filter_out (No_ATPs.member ctxt o snd)
blanchet@38850
   583
blanchet@38850
   584
(***************************************************************)
blanchet@38850
   585
(* ATP invocation methods setup                                *)
blanchet@38850
   586
(***************************************************************)
blanchet@38850
   587
blanchet@38983
   588
fun relevant_facts full_types relevance_threshold relevance_decay max_relevant
blanchet@38983
   589
                   theory_relevant (relevance_override as {add, del, only})
blanchet@38229
   590
                   (ctxt, (chained_ths, _)) hyp_ts concl_t =
blanchet@37534
   591
  let
blanchet@38983
   592
    val relevance_decay =
blanchet@38983
   593
      case relevance_decay of
blanchet@38983
   594
        SOME x => x
blanchet@38983
   595
      | NONE => 0.35 / Math.ln (Real.fromInt (max_relevant + 1))
blanchet@37534
   596
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@38935
   597
    val reserved = reserved_isar_keyword_table ()
blanchet@37534
   598
    val axioms =
blanchet@38938
   599
      (if only then
blanchet@38983
   600
         maps (name_thm_pairs_from_ref ctxt reserved chained_ths) add
blanchet@38938
   601
       else
blanchet@38938
   602
         all_name_thms_pairs ctxt reserved full_types add_thms chained_ths)
blanchet@38927
   603
      |> name_thm_pairs ctxt (respect_no_atp andalso not only)
blanchet@38818
   604
      |> make_unique
blanchet@37534
   605
  in
blanchet@38927
   606
    trace_msg (fn () => "Considering " ^ Int.toString (length axioms) ^
blanchet@38927
   607
                        " theorems");
blanchet@38978
   608
    (if relevance_threshold > 1.0 then
blanchet@38978
   609
       []
blanchet@38978
   610
     else if relevance_threshold < 0.0 then
blanchet@38978
   611
       axioms
blanchet@38978
   612
     else
blanchet@38983
   613
       relevance_filter ctxt relevance_threshold relevance_decay max_relevant
blanchet@38983
   614
                        theory_relevant relevance_override axioms
blanchet@38983
   615
                                        (concl_t :: hyp_ts))
blanchet@38983
   616
    |> map (apfst (fn f => f ())) |> sort_wrt (fst o fst)
blanchet@37534
   617
  end
immler@30536
   618
paulson@15347
   619
end;