src/HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
author blanchet
Wed Aug 25 19:41:18 2010 +0200 (2010-08-25 ago)
changeset 38745 ad577fd62ee4
parent 38744 2b6333f78a9e
child 38747 b264ae66cede
permissions -rw-r--r--
reorganize options regarding to the relevance threshold and decay
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@38745
    18
    bool -> real * real -> 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@38745
   268
fun take_best max (candidates : (annotated_thm * real) list) =
blanchet@38744
   269
  let
blanchet@38744
   270
    val ((perfect, more_perfect), imperfect) =
blanchet@38745
   271
      candidates |> List.partition (fn (_, w) => w > 0.99999) |>> chop (max - 1)
blanchet@38745
   272
                 ||> sort (Real.compare o swap o pairself snd)
blanchet@38745
   273
    val (accepts, rejects) =
blanchet@38744
   274
      case more_perfect @ imperfect of
blanchet@38744
   275
        [] => (perfect, [])
blanchet@38744
   276
      | (q :: qs) => (q :: perfect, qs)
blanchet@38744
   277
  in
blanchet@38744
   278
    trace_msg (fn () => "Number of candidates: " ^
blanchet@38745
   279
                        string_of_int (length candidates));
blanchet@38744
   280
    trace_msg (fn () => "Effective threshold: " ^
blanchet@38745
   281
                        Real.toString (#2 (hd accepts)));
blanchet@38744
   282
    trace_msg (fn () => "Actually passed: " ^
blanchet@38745
   283
        (accepts |> map (fn (((name, _), _), weight) =>
blanchet@38745
   284
                            fst (name ()) ^ " [" ^ Real.toString weight ^ "]")
blanchet@38745
   285
                 |> commas));
blanchet@38745
   286
    (accepts, rejects)
blanchet@38744
   287
  end
paulson@24287
   288
blanchet@38683
   289
val threshold_divisor = 2.0
blanchet@38683
   290
val ridiculous_threshold = 0.1
blanchet@38683
   291
blanchet@38745
   292
fun relevance_filter ctxt threshold0 decay max_relevant theory_relevant
blanchet@38745
   293
                     ({add, del, ...} : relevance_override) axioms goal_ts =
blanchet@38739
   294
  let
blanchet@38739
   295
    val thy = ProofContext.theory_of ctxt
blanchet@38739
   296
    val const_tab = fold (count_axiom_consts theory_relevant thy) axioms
blanchet@38739
   297
                         Symtab.empty
blanchet@38739
   298
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@38739
   299
    val del_thms = maps (ProofContext.get_fact ctxt) del
blanchet@38745
   300
    fun iter j max threshold rel_const_tab hopeless hopeful =
blanchet@38739
   301
      let
blanchet@38744
   302
        fun game_over rejects =
blanchet@38744
   303
          if j = 0 andalso threshold >= ridiculous_threshold then
blanchet@38744
   304
            (* First iteration? Try again. *)
blanchet@38745
   305
            iter 0 max (threshold / threshold_divisor) rel_const_tab hopeless
blanchet@38745
   306
                 hopeful
blanchet@38744
   307
          else
blanchet@38744
   308
            (* Add "add:" facts. *)
blanchet@38744
   309
            if null add_thms then
blanchet@38744
   310
              []
blanchet@38744
   311
            else
blanchet@38744
   312
              map_filter (fn ((p as (_, th), _), _) =>
blanchet@38744
   313
                             if member Thm.eq_thm add_thms th then SOME p
blanchet@38744
   314
                             else NONE) rejects
blanchet@38745
   315
        fun relevant [] rejects [] hopeless =
blanchet@38744
   316
            (* Nothing has been added this iteration. *)
blanchet@38745
   317
            game_over (map (apsnd SOME) (rejects @ hopeless))
blanchet@38745
   318
          | relevant candidates rejects [] hopeless =
blanchet@38739
   319
            let
blanchet@38745
   320
              val (accepts, more_rejects) = take_best max candidates
blanchet@38739
   321
              val rel_const_tab' =
blanchet@38745
   322
                rel_const_tab
blanchet@38745
   323
                |> fold add_const_to_table (maps (snd o fst) accepts)
blanchet@38744
   324
              fun is_dirty (c, _) =
blanchet@38744
   325
                Symtab.lookup rel_const_tab' c <> Symtab.lookup rel_const_tab c
blanchet@38745
   326
              val (hopeful_rejects, hopeless_rejects) =
blanchet@38745
   327
                 (rejects @ hopeless, ([], []))
blanchet@38745
   328
                 |-> fold (fn (ax as (_, consts), old_weight) =>
blanchet@38745
   329
                              if exists is_dirty consts then
blanchet@38745
   330
                                apfst (cons (ax, NONE))
blanchet@38745
   331
                              else
blanchet@38745
   332
                                apsnd (cons (ax, old_weight)))
blanchet@38745
   333
                 |>> append (more_rejects
blanchet@38745
   334
                             |> map (fn (ax as (_, consts), old_weight) =>
blanchet@38745
   335
                                        (ax, if exists is_dirty consts then NONE
blanchet@38745
   336
                                             else SOME old_weight)))
blanchet@38745
   337
              val threshold = threshold + (1.0 - threshold) * decay
blanchet@38745
   338
              val max = max - length accepts
blanchet@38739
   339
            in
blanchet@38744
   340
              trace_msg (fn () => "New or updated constants: " ^
blanchet@38744
   341
                  commas (rel_const_tab' |> Symtab.dest
blanchet@38744
   342
                          |> subtract (op =) (Symtab.dest rel_const_tab)
blanchet@38744
   343
                          |> map string_for_super_pseudoconst));
blanchet@38745
   344
              map (fst o fst) accepts @
blanchet@38745
   345
              (if max = 0 then
blanchet@38745
   346
                 game_over (hopeful_rejects @ map (apsnd SOME) hopeless_rejects)
blanchet@38745
   347
               else
blanchet@38745
   348
                 iter (j + 1) max threshold rel_const_tab' hopeless_rejects
blanchet@38745
   349
                      hopeful_rejects)
blanchet@38739
   350
            end
blanchet@38745
   351
          | relevant candidates rejects
blanchet@38739
   352
                     (((ax as ((name, th), axiom_consts)), cached_weight)
blanchet@38745
   353
                      :: hopeful) hopeless =
blanchet@38739
   354
            let
blanchet@38739
   355
              val weight =
blanchet@38739
   356
                case cached_weight of
blanchet@38739
   357
                  SOME w => w
blanchet@38739
   358
                | NONE => axiom_weight const_tab rel_const_tab axiom_consts
blanchet@38739
   359
            in
blanchet@38741
   360
              if weight >= threshold then
blanchet@38745
   361
                relevant ((ax, weight) :: candidates) rejects hopeful hopeless
blanchet@38739
   362
              else
blanchet@38745
   363
                relevant candidates ((ax, weight) :: rejects) hopeful hopeless
blanchet@38739
   364
            end
blanchet@38739
   365
        in
blanchet@38744
   366
          trace_msg (fn () =>
blanchet@38744
   367
              "ITERATION " ^ string_of_int j ^ ": current threshold: " ^
blanchet@38744
   368
              Real.toString threshold ^ ", constants: " ^
blanchet@38744
   369
              commas (rel_const_tab |> Symtab.dest
blanchet@38744
   370
                      |> filter (curry (op <>) [] o snd)
blanchet@38744
   371
                      |> map string_for_super_pseudoconst));
blanchet@38745
   372
          relevant [] [] hopeful hopeless
blanchet@38739
   373
        end
blanchet@38739
   374
  in
blanchet@38739
   375
    axioms |> filter_out (member Thm.eq_thm del_thms o snd)
blanchet@38739
   376
           |> map (rpair NONE o pair_consts_axiom theory_relevant thy)
blanchet@38745
   377
           |> iter 0 max_relevant threshold0
blanchet@38745
   378
                   (get_consts thy (SOME false) goal_ts) []
blanchet@38739
   379
           |> tap (fn res => trace_msg (fn () =>
blanchet@38686
   380
                                "Total relevant: " ^ Int.toString (length res)))
blanchet@38739
   381
  end
paulson@24287
   382
blanchet@38744
   383
paulson@24287
   384
(***************************************************************)
mengj@19768
   385
(* Retrieving and filtering lemmas                             *)
mengj@19768
   386
(***************************************************************)
mengj@19768
   387
paulson@33022
   388
(*** retrieve lemmas and filter them ***)
mengj@19768
   389
paulson@20757
   390
(*Reject theorems with names like "List.filter.filter_list_def" or
paulson@21690
   391
  "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
paulson@20757
   392
fun is_package_def a =
wenzelm@30364
   393
  let val names = Long_Name.explode a
paulson@21690
   394
  in
paulson@21690
   395
     length names > 2 andalso
paulson@21690
   396
     not (hd names = "local") andalso
paulson@21690
   397
     String.isSuffix "_def" a  orelse  String.isSuffix "_defs" a
paulson@21690
   398
  end;
paulson@20757
   399
blanchet@38085
   400
fun make_fact_table xs =
blanchet@37616
   401
  fold (Termtab.update o `(prop_of o snd)) xs Termtab.empty
blanchet@38085
   402
fun make_unique xs = Termtab.fold (cons o snd) (make_fact_table xs) []
mengj@19768
   403
blanchet@37626
   404
(* FIXME: put other record thms here, or declare as "no_atp" *)
blanchet@37626
   405
val multi_base_blacklist =
blanchet@37626
   406
  ["defs", "select_defs", "update_defs", "induct", "inducts", "split", "splits",
blanchet@38682
   407
   "split_asm", "cases", "ext_cases", "eq.simps", "eq.refl", "nchotomy",
blanchet@38682
   408
   "case_cong", "weak_case_cong"]
blanchet@38682
   409
  |> map (prefix ".")
blanchet@37626
   410
blanchet@37626
   411
val max_lambda_nesting = 3
blanchet@37626
   412
blanchet@37626
   413
fun term_has_too_many_lambdas max (t1 $ t2) =
blanchet@37626
   414
    exists (term_has_too_many_lambdas max) [t1, t2]
blanchet@37626
   415
  | term_has_too_many_lambdas max (Abs (_, _, t)) =
blanchet@37626
   416
    max = 0 orelse term_has_too_many_lambdas (max - 1) t
blanchet@37626
   417
  | term_has_too_many_lambdas _ _ = false
blanchet@37626
   418
blanchet@37626
   419
(* Don't count nested lambdas at the level of formulas, since they are
blanchet@37626
   420
   quantifiers. *)
blanchet@37626
   421
fun formula_has_too_many_lambdas Ts (Abs (_, T, t)) =
blanchet@37626
   422
    formula_has_too_many_lambdas (T :: Ts) t
blanchet@37626
   423
  | formula_has_too_many_lambdas Ts t =
blanchet@37626
   424
    if is_formula_type (fastype_of1 (Ts, t)) then
blanchet@37626
   425
      exists (formula_has_too_many_lambdas Ts) (#2 (strip_comb t))
blanchet@37626
   426
    else
blanchet@37626
   427
      term_has_too_many_lambdas max_lambda_nesting t
blanchet@37626
   428
blanchet@38692
   429
(* The max apply depth of any "metis" call in "Metis_Examples" (on 2007-10-31)
blanchet@37626
   430
   was 11. *)
blanchet@37626
   431
val max_apply_depth = 15
blanchet@37626
   432
blanchet@37626
   433
fun apply_depth (f $ t) = Int.max (apply_depth f, apply_depth t + 1)
blanchet@37626
   434
  | apply_depth (Abs (_, _, t)) = apply_depth t
blanchet@37626
   435
  | apply_depth _ = 0
blanchet@37626
   436
blanchet@37626
   437
fun is_formula_too_complex t =
blanchet@38085
   438
  apply_depth t > max_apply_depth orelse formula_has_too_many_lambdas [] t
blanchet@37626
   439
blanchet@37543
   440
val exists_sledgehammer_const =
blanchet@37626
   441
  exists_Const (fn (s, _) => String.isPrefix sledgehammer_prefix s)
blanchet@37626
   442
blanchet@38652
   443
fun is_strange_theorem th =
blanchet@37626
   444
  case head_of (concl_of th) of
blanchet@37626
   445
      Const (a, _) => (a <> @{const_name Trueprop} andalso
blanchet@37626
   446
                       a <> @{const_name "=="})
blanchet@37626
   447
    | _ => false
blanchet@37626
   448
blanchet@37626
   449
val type_has_top_sort =
blanchet@37626
   450
  exists_subtype (fn TFree (_, []) => true | TVar (_, []) => true | _ => false)
blanchet@37626
   451
blanchet@38085
   452
(**** Predicates to detect unwanted facts (prolific or likely to cause
blanchet@37347
   453
      unsoundness) ****)
paulson@21470
   454
blanchet@38289
   455
(* Too general means, positive equality literal with a variable X as one
blanchet@38289
   456
   operand, when X does not occur properly in the other operand. This rules out
blanchet@38289
   457
   clearly inconsistent facts such as X = a | X = b, though it by no means
blanchet@38289
   458
   guarantees soundness. *)
paulson@21470
   459
blanchet@38289
   460
(* Unwanted equalities are those between a (bound or schematic) variable that
blanchet@38289
   461
   does not properly occur in the second operand. *)
blanchet@38607
   462
val is_exhaustive_finite =
blanchet@38607
   463
  let
blanchet@38629
   464
    fun is_bad_equal (Var z) t =
blanchet@38629
   465
        not (exists_subterm (fn Var z' => z = z' | _ => false) t)
blanchet@38629
   466
      | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
blanchet@38629
   467
      | is_bad_equal _ _ = false
blanchet@38629
   468
    fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
blanchet@38607
   469
    fun do_formula pos t =
blanchet@38607
   470
      case (pos, t) of
blanchet@38615
   471
        (_, @{const Trueprop} $ t1) => do_formula pos t1
blanchet@38607
   472
      | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
blanchet@38607
   473
        do_formula pos t'
blanchet@38607
   474
      | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
blanchet@38607
   475
        do_formula pos t'
blanchet@38607
   476
      | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
blanchet@38607
   477
        do_formula pos t'
blanchet@38607
   478
      | (_, @{const "==>"} $ t1 $ t2) =>
blanchet@38629
   479
        do_formula (not pos) t1 andalso
blanchet@38629
   480
        (t2 = @{prop False} orelse do_formula pos t2)
blanchet@38607
   481
      | (_, @{const "op -->"} $ t1 $ t2) =>
blanchet@38629
   482
        do_formula (not pos) t1 andalso
blanchet@38629
   483
        (t2 = @{const False} orelse do_formula pos t2)
blanchet@38607
   484
      | (_, @{const Not} $ t1) => do_formula (not pos) t1
blanchet@38607
   485
      | (true, @{const "op |"} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@38607
   486
      | (false, @{const "op &"} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
blanchet@38607
   487
      | (true, Const (@{const_name "op ="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38607
   488
      | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38607
   489
      | _ => false
blanchet@38607
   490
  in do_formula true end
blanchet@38607
   491
blanchet@38592
   492
fun has_bound_or_var_of_type tycons =
blanchet@38592
   493
  exists_subterm (fn Var (_, Type (s, _)) => member (op =) tycons s
blanchet@38592
   494
                   | Abs (_, Type (s, _), _) => member (op =) tycons s
blanchet@38592
   495
                   | _ => false)
paulson@21431
   496
blanchet@38085
   497
(* Facts are forbidden to contain variables of these types. The typical reason
blanchet@37347
   498
   is that they lead to unsoundness. Note that "unit" satisfies numerous
blanchet@38085
   499
   equations like "?x = ()". The resulting clauses will have no type constraint,
blanchet@37347
   500
   yielding false proofs. Even "bool" leads to many unsound proofs, though only
blanchet@37347
   501
   for higher-order problems. *)
blanchet@38592
   502
val dangerous_types = [@{type_name unit}, @{type_name bool}, @{type_name prop}];
paulson@22217
   503
blanchet@38085
   504
(* Facts containing variables of type "unit" or "bool" or of the form
blanchet@38290
   505
   "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
blanchet@38290
   506
   are omitted. *)
blanchet@38593
   507
fun is_dangerous_term full_types t =
blanchet@38609
   508
  not full_types andalso
blanchet@38679
   509
  let val t = transform_elim_term t in
blanchet@38679
   510
    has_bound_or_var_of_type dangerous_types t orelse
blanchet@38679
   511
    is_exhaustive_finite t
blanchet@38679
   512
  end
paulson@21470
   513
blanchet@38627
   514
fun is_theorem_bad_for_atps full_types thm =
blanchet@38627
   515
  let val t = prop_of thm in
blanchet@38627
   516
    is_formula_too_complex t orelse exists_type type_has_top_sort t orelse
blanchet@38627
   517
    is_dangerous_term full_types t orelse exists_sledgehammer_const t orelse
blanchet@38652
   518
    is_strange_theorem thm
blanchet@38627
   519
  end
blanchet@38627
   520
blanchet@38696
   521
fun all_name_thms_pairs ctxt reserved full_types add_thms chained_ths =
blanchet@38627
   522
  let
blanchet@38697
   523
    val is_chained = member Thm.eq_thm chained_ths
blanchet@38697
   524
    val global_facts = PureThy.facts_of (ProofContext.theory_of ctxt)
blanchet@38644
   525
    val local_facts = ProofContext.facts_of ctxt
blanchet@38644
   526
    val named_locals = local_facts |> Facts.dest_static []
blanchet@38697
   527
    (* Unnamed, not chained formulas with schematic variables are omitted,
blanchet@38697
   528
       because they are rejected by the backticks (`...`) parser for some
blanchet@38697
   529
       reason. *)
blanchet@38738
   530
    fun is_good_unnamed_local th =
blanchet@38738
   531
      forall (fn (_, ths) => not (member Thm.eq_thm ths th)) named_locals
blanchet@38738
   532
      andalso (not (exists_subterm is_Var (prop_of th)) orelse (is_chained th))
blanchet@38644
   533
    val unnamed_locals =
blanchet@38738
   534
      local_facts |> Facts.props |> filter is_good_unnamed_local
blanchet@38697
   535
                  |> map (pair "" o single)
blanchet@38627
   536
    val full_space =
blanchet@38738
   537
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts)
blanchet@38697
   538
    fun add_valid_facts foldx facts =
blanchet@38699
   539
      foldx (fn (name0, ths) =>
blanchet@38699
   540
        if name0 <> "" andalso
blanchet@38699
   541
           forall (not o member Thm.eq_thm add_thms) ths andalso
blanchet@38699
   542
           (Facts.is_concealed facts name0 orelse
blanchet@38699
   543
            (respect_no_atp andalso is_package_def name0) orelse
blanchet@38699
   544
            exists (fn s => String.isSuffix s name0) multi_base_blacklist orelse
blanchet@38699
   545
            String.isSuffix "_def_raw" (* FIXME: crude hack *) name0) then
blanchet@38627
   546
          I
blanchet@38627
   547
        else
blanchet@38627
   548
          let
blanchet@38699
   549
            val multi = length ths > 1
blanchet@38696
   550
            fun backquotify th =
blanchet@38696
   551
              "`" ^ Print_Mode.setmp [Print_Mode.input]
blanchet@38696
   552
                                 (Syntax.string_of_term ctxt) (prop_of th) ^ "`"
blanchet@38738
   553
              |> String.translate (fn c => if Char.isPrint c then str c else "")
blanchet@38738
   554
              |> simplify_spaces
blanchet@38699
   555
            fun check_thms a =
blanchet@38699
   556
              case try (ProofContext.get_thms ctxt) a of
blanchet@38699
   557
                NONE => false
blanchet@38699
   558
              | SOME ths' => Thm.eq_thms (ths, ths')
blanchet@38627
   559
          in
blanchet@38699
   560
            pair 1
blanchet@38699
   561
            #> fold (fn th => fn (j, rest) =>
blanchet@38699
   562
                 (j + 1,
blanchet@38699
   563
                  if is_theorem_bad_for_atps full_types th andalso
blanchet@38699
   564
                     not (member Thm.eq_thm add_thms th) then
blanchet@38699
   565
                    rest
blanchet@38699
   566
                  else
blanchet@38699
   567
                    (fn () =>
blanchet@38699
   568
                        (if name0 = "" then
blanchet@38699
   569
                           th |> backquotify
blanchet@38699
   570
                         else
blanchet@38699
   571
                           let
blanchet@38699
   572
                             val name1 = Facts.extern facts name0
blanchet@38699
   573
                             val name2 = Name_Space.extern full_space name0
blanchet@38699
   574
                           in
blanchet@38699
   575
                             case find_first check_thms [name1, name2, name0] of
blanchet@38744
   576
                               SOME name => repair_name reserved multi j name
blanchet@38699
   577
                             | NONE => ""
blanchet@38699
   578
                           end, is_chained th), (multi, th)) :: rest)) ths
blanchet@38699
   579
            #> snd
blanchet@38627
   580
          end)
blanchet@38644
   581
  in
blanchet@38688
   582
    [] |> add_valid_facts fold local_facts (unnamed_locals @ named_locals)
blanchet@38688
   583
       |> add_valid_facts Facts.fold_static global_facts global_facts
blanchet@38644
   584
  end
blanchet@38627
   585
blanchet@38627
   586
(* The single-name theorems go after the multiple-name ones, so that single
blanchet@38627
   587
   names are preferred when both are available. *)
blanchet@38699
   588
fun name_thm_pairs ctxt respect_no_atp =
blanchet@38744
   589
  List.partition (fst o snd) #> op @ #> map (apsnd snd)
blanchet@38699
   590
  #> respect_no_atp ? filter_out (No_ATPs.member ctxt o snd)
blanchet@38627
   591
blanchet@38627
   592
(***************************************************************)
blanchet@38627
   593
(* ATP invocation methods setup                                *)
blanchet@38627
   594
(***************************************************************)
blanchet@38627
   595
blanchet@38745
   596
fun relevant_facts full_types (threshold0, threshold1) max_relevant
blanchet@38744
   597
                   theory_relevant (relevance_override as {add, del, only})
blanchet@37995
   598
                   (ctxt, (chained_ths, _)) hyp_ts concl_t =
blanchet@37538
   599
  let
blanchet@38745
   600
    val decay = 1.0 - Math.pow ((1.0 - threshold1) / (1.0 - threshold0),
blanchet@38745
   601
                                1.0 / Real.fromInt (max_relevant + 1))
blanchet@37538
   602
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@38696
   603
    val reserved = reserved_isar_keyword_table ()
blanchet@37538
   604
    val axioms =
blanchet@38699
   605
      (if only then
blanchet@38744
   606
         maps (name_thm_pairs_from_ref ctxt reserved chained_ths) add
blanchet@38699
   607
       else
blanchet@38699
   608
         all_name_thms_pairs ctxt reserved full_types add_thms chained_ths)
blanchet@38688
   609
      |> name_thm_pairs ctxt (respect_no_atp andalso not only)
blanchet@38595
   610
      |> make_unique
blanchet@37538
   611
  in
blanchet@38688
   612
    trace_msg (fn () => "Considering " ^ Int.toString (length axioms) ^
blanchet@38688
   613
                        " theorems");
blanchet@38745
   614
    (if threshold0 > 1.0 orelse threshold0 > threshold1 then
blanchet@38739
   615
       []
blanchet@38745
   616
     else if threshold0 < 0.0 then
blanchet@38739
   617
       axioms
blanchet@38739
   618
     else
blanchet@38745
   619
       relevance_filter ctxt threshold0 decay max_relevant theory_relevant
blanchet@38745
   620
                        relevance_override axioms (concl_t :: hyp_ts))
blanchet@38744
   621
    |> map (apfst (fn f => f ())) |> sort_wrt (fst o fst)
blanchet@37538
   622
  end
immler@30536
   623
paulson@15347
   624
end;