src/HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
author haftmann
Sat Aug 28 16:14:32 2010 +0200 (2010-08-28 ago)
changeset 38864 4abe644fcea5
parent 38829 c18e8f90f4dc
child 38907 245fca4ce86f
permissions -rw-r--r--
formerly unnamed infix equality now named HOL.eq
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@38752
     8
  datatype locality = General | Theory | Local | Chained
blanchet@38752
     9
blanchet@35966
    10
  type relevance_override =
blanchet@35966
    11
    {add: Facts.ref list,
blanchet@35966
    12
     del: Facts.ref list,
blanchet@35966
    13
     only: bool}
blanchet@35966
    14
blanchet@37616
    15
  val trace : bool Unsynchronized.ref
blanchet@38827
    16
  val term_patterns : bool Unsynchronized.ref
blanchet@38744
    17
  val name_thm_pairs_from_ref :
blanchet@38696
    18
    Proof.context -> unit Symtab.table -> thm list -> Facts.ref
blanchet@38752
    19
    -> ((string * locality) * thm) list
blanchet@37347
    20
  val relevant_facts :
blanchet@38745
    21
    bool -> real * real -> int -> bool -> relevance_override
blanchet@37995
    22
    -> Proof.context * (thm list * 'a) -> term list -> term
blanchet@38752
    23
    -> ((string * locality) * thm) list
paulson@15347
    24
end;
paulson@15347
    25
blanchet@35826
    26
structure Sledgehammer_Fact_Filter : SLEDGEHAMMER_FACT_FILTER =
paulson@15347
    27
struct
paulson@15347
    28
blanchet@38652
    29
open Sledgehammer_Util
blanchet@38652
    30
blanchet@37616
    31
val trace = Unsynchronized.ref false
blanchet@37616
    32
fun trace_msg msg = if !trace then tracing (msg ()) else ()
blanchet@35826
    33
blanchet@38828
    34
(* experimental feature *)
blanchet@38828
    35
val term_patterns = Unsynchronized.ref false
blanchet@38827
    36
blanchet@37580
    37
val respect_no_atp = true
blanchet@37505
    38
blanchet@38752
    39
datatype locality = General | Theory | Local | Chained
blanchet@38752
    40
blanchet@35966
    41
type relevance_override =
blanchet@35966
    42
  {add: Facts.ref list,
blanchet@35966
    43
   del: Facts.ref list,
blanchet@35966
    44
   only: bool}
paulson@21070
    45
blanchet@37616
    46
val sledgehammer_prefix = "Sledgehammer" ^ Long_Name.separator
blanchet@37616
    47
blanchet@38744
    48
fun repair_name reserved multi j name =
blanchet@38744
    49
  (name |> Symtab.defined reserved name ? quote) ^
blanchet@38744
    50
  (if multi then "(" ^ Int.toString j ^ ")" else "")
blanchet@38744
    51
blanchet@38744
    52
fun name_thm_pairs_from_ref ctxt reserved chained_ths xref =
blanchet@38744
    53
  let
blanchet@38744
    54
    val ths = ProofContext.get_fact ctxt xref
blanchet@38744
    55
    val name = Facts.string_of_ref xref
blanchet@38744
    56
    val multi = length ths > 1
blanchet@38744
    57
  in
blanchet@38752
    58
    (ths, (1, []))
blanchet@38752
    59
    |-> fold (fn th => fn (j, rest) =>
blanchet@38752
    60
                 (j + 1, ((repair_name reserved multi j name,
blanchet@38752
    61
                          if member Thm.eq_thm chained_ths th then Chained
blanchet@38752
    62
                          else General), th) :: rest))
blanchet@38744
    63
    |> snd
blanchet@38699
    64
  end
blanchet@37616
    65
wenzelm@28477
    66
(***************************************************************)
wenzelm@28477
    67
(* Relevance Filtering                                         *)
wenzelm@28477
    68
(***************************************************************)
mengj@19194
    69
paulson@24287
    70
(*** constants with types ***)
paulson@24287
    71
blanchet@38823
    72
(* An abstraction of Isabelle types and first-order terms *)
blanchet@38823
    73
datatype pattern = PVar | PApp of string * pattern list
blanchet@38744
    74
blanchet@38823
    75
fun string_for_pattern PVar = "_"
blanchet@38823
    76
  | string_for_pattern (PApp (s, ps)) =
blanchet@38823
    77
    if null ps then s else s ^ string_for_patterns ps
blanchet@38823
    78
and string_for_patterns ps = "(" ^ commas (map string_for_pattern ps) ^ ")"
paulson@24287
    79
paulson@24287
    80
(*Is the second type an instance of the first one?*)
blanchet@38824
    81
fun match_pattern (PVar, _) = true
blanchet@38824
    82
  | match_pattern (PApp _, PVar) = false
blanchet@38824
    83
  | match_pattern (PApp (s, ps), PApp (t, qs)) =
blanchet@38824
    84
    s = t andalso match_patterns (ps, qs)
blanchet@38824
    85
and match_patterns (_, []) = true
blanchet@38824
    86
  | match_patterns ([], _) = false
blanchet@38824
    87
  | match_patterns (p :: ps, q :: qs) =
blanchet@38824
    88
    match_pattern (p, q) andalso match_patterns (ps, qs)
paulson@24287
    89
blanchet@38823
    90
(* Is there a unifiable constant? *)
blanchet@38827
    91
fun pconst_mem f consts (s, ps) =
blanchet@38827
    92
  exists (curry (match_patterns o f) ps)
blanchet@38827
    93
         (map snd (filter (curry (op =) s o fst) consts))
blanchet@38827
    94
fun pconst_hyper_mem f const_tab (s, ps) =
blanchet@38823
    95
  exists (curry (match_patterns o f) ps) (these (Symtab.lookup const_tab s))
blanchet@37505
    96
blanchet@38827
    97
fun ptype (Type (s, Ts)) = PApp (s, map ptype Ts)
blanchet@38827
    98
  | ptype (TFree (s, _)) = PApp (s, [])
blanchet@38827
    99
  | ptype (TVar _) = PVar
blanchet@38827
   100
blanchet@38827
   101
fun pterm thy t =
blanchet@38827
   102
  case strip_comb t of
blanchet@38827
   103
    (Const x, ts) => PApp (pconst thy true x ts)
blanchet@38827
   104
  | (Free x, ts) => PApp (pconst thy false x ts)
blanchet@38827
   105
  | (Var x, []) => PVar
blanchet@38827
   106
  | _ => PApp ("?", [])  (* equivalence class of higher-order constructs *)
blanchet@38744
   107
(* Pairs a constant with the list of its type instantiations. *)
blanchet@38827
   108
and pconst_args thy const (s, T) ts =
blanchet@38828
   109
  (if const then map ptype (these (try (Sign.const_typargs thy) (s, T)))
blanchet@38828
   110
   else []) @
blanchet@38827
   111
  (if !term_patterns then map (pterm thy) ts else [])
blanchet@38827
   112
and pconst thy const (s, T) ts = (s, pconst_args thy const (s, T) ts)
paulson@24287
   113
blanchet@38827
   114
fun string_for_hyper_pconst (s, pss) =
blanchet@38823
   115
  s ^ "{" ^ commas (map string_for_patterns pss) ^ "}"
paulson@24287
   116
blanchet@38816
   117
val abs_name = "Sledgehammer.abs"
blanchet@38749
   118
val skolem_prefix = "Sledgehammer.sko"
blanchet@38747
   119
blanchet@38822
   120
(* These are typically simplified away by "Meson.presimplify". Equality is
blanchet@38822
   121
   handled specially via "fequal". *)
blanchet@38682
   122
val boring_consts =
blanchet@38822
   123
  [@{const_name False}, @{const_name True}, @{const_name If}, @{const_name Let},
haftmann@38864
   124
   @{const_name HOL.eq}]
blanchet@37537
   125
blanchet@38823
   126
(* Add a pconstant to the table, but a [] entry means a standard
blanchet@38819
   127
   connective, which we ignore.*)
blanchet@38824
   128
fun add_pconst_to_table also_skolem (c, ps) =
blanchet@38819
   129
  if member (op =) boring_consts c orelse
blanchet@38819
   130
     (not also_skolem andalso String.isPrefix skolem_prefix c) then
blanchet@38819
   131
    I
blanchet@38819
   132
  else
blanchet@38824
   133
    Symtab.map_default (c, [ps]) (insert (op =) ps)
blanchet@38819
   134
blanchet@38819
   135
fun is_formula_type T = (T = HOLogic.boolT orelse T = propT)
blanchet@38819
   136
blanchet@38823
   137
fun get_pconsts thy also_skolems pos ts =
blanchet@37505
   138
  let
blanchet@38819
   139
    val flip = Option.map not
blanchet@38587
   140
    (* We include free variables, as well as constants, to handle locales. For
blanchet@38587
   141
       each quantifiers that must necessarily be skolemized by the ATP, we
blanchet@38587
   142
       introduce a fresh constant to simulate the effect of Skolemization. *)
blanchet@38827
   143
    fun do_const const (s, T) ts =
blanchet@38827
   144
      add_pconst_to_table also_skolems (pconst thy const (s, T) ts)
blanchet@38827
   145
      #> fold do_term ts
blanchet@38827
   146
    and do_term t =
blanchet@38827
   147
      case strip_comb t of
blanchet@38827
   148
        (Const x, ts) => do_const true x ts
blanchet@38827
   149
      | (Free x, ts) => do_const false x ts
blanchet@38827
   150
      | (Abs (_, _, t'), ts) =>
blanchet@38827
   151
        null ts ? add_pconst_to_table true (abs_name, [])
blanchet@38827
   152
        #> fold do_term (t' :: ts)
blanchet@38827
   153
      | (_, ts) => fold do_term ts
blanchet@38587
   154
    fun do_quantifier will_surely_be_skolemized body_t =
blanchet@37537
   155
      do_formula pos body_t
blanchet@38747
   156
      #> (if also_skolems andalso will_surely_be_skolemized then
blanchet@38823
   157
            add_pconst_to_table true (gensym skolem_prefix, [])
blanchet@38587
   158
          else
blanchet@38587
   159
            I)
blanchet@38587
   160
    and do_term_or_formula T =
blanchet@38692
   161
      if is_formula_type T then do_formula NONE else do_term
blanchet@37537
   162
    and do_formula pos t =
blanchet@37537
   163
      case t of
blanchet@37537
   164
        Const (@{const_name all}, _) $ Abs (_, _, body_t) =>
blanchet@38587
   165
        do_quantifier (pos = SOME false) body_t
blanchet@37537
   166
      | @{const "==>"} $ t1 $ t2 =>
blanchet@37537
   167
        do_formula (flip pos) t1 #> do_formula pos t2
blanchet@37537
   168
      | Const (@{const_name "=="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38587
   169
        fold (do_term_or_formula T) [t1, t2]
blanchet@37537
   170
      | @{const Trueprop} $ t1 => do_formula pos t1
blanchet@37537
   171
      | @{const Not} $ t1 => do_formula (flip pos) t1
blanchet@37537
   172
      | Const (@{const_name All}, _) $ Abs (_, _, body_t) =>
blanchet@38587
   173
        do_quantifier (pos = SOME false) body_t
blanchet@37537
   174
      | Const (@{const_name Ex}, _) $ Abs (_, _, body_t) =>
blanchet@38587
   175
        do_quantifier (pos = SOME true) body_t
haftmann@38795
   176
      | @{const HOL.conj} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
haftmann@38795
   177
      | @{const HOL.disj} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
haftmann@38786
   178
      | @{const HOL.implies} $ t1 $ t2 =>
blanchet@37537
   179
        do_formula (flip pos) t1 #> do_formula pos t2
haftmann@38864
   180
      | Const (@{const_name HOL.eq}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@38587
   181
        fold (do_term_or_formula T) [t1, t2]
blanchet@38587
   182
      | Const (@{const_name If}, Type (_, [_, Type (_, [T, _])]))
blanchet@38587
   183
        $ t1 $ t2 $ t3 =>
blanchet@38587
   184
        do_formula NONE t1 #> fold (do_term_or_formula T) [t2, t3]
blanchet@38587
   185
      | Const (@{const_name Ex1}, _) $ Abs (_, _, body_t) =>
blanchet@38587
   186
        do_quantifier (is_some pos) body_t
blanchet@38587
   187
      | Const (@{const_name Ball}, _) $ t1 $ Abs (_, _, body_t) =>
blanchet@38587
   188
        do_quantifier (pos = SOME false)
blanchet@38587
   189
                      (HOLogic.mk_imp (incr_boundvars 1 t1 $ Bound 0, body_t))
blanchet@38587
   190
      | Const (@{const_name Bex}, _) $ t1 $ Abs (_, _, body_t) =>
blanchet@38587
   191
        do_quantifier (pos = SOME true)
blanchet@38587
   192
                      (HOLogic.mk_conj (incr_boundvars 1 t1 $ Bound 0, body_t))
blanchet@37537
   193
      | (t0 as Const (_, @{typ bool})) $ t1 =>
blanchet@37537
   194
        do_term t0 #> do_formula pos t1  (* theory constant *)
blanchet@37537
   195
      | _ => do_term t
blanchet@38819
   196
  in Symtab.empty |> fold (do_formula pos) ts end
paulson@24287
   197
paulson@24287
   198
(*Inserts a dummy "constant" referring to the theory name, so that relevance
paulson@24287
   199
  takes the given theory into account.*)
blanchet@37616
   200
fun theory_const_prop_of theory_relevant th =
blanchet@37505
   201
  if theory_relevant then
blanchet@37505
   202
    let
blanchet@37505
   203
      val name = Context.theory_name (theory_of_thm th)
blanchet@37505
   204
      val t = Const (name ^ ". 1", @{typ bool})
blanchet@37505
   205
    in t $ prop_of th end
blanchet@37505
   206
  else
blanchet@37505
   207
    prop_of th
blanchet@37505
   208
paulson@24287
   209
(**** Constant / Type Frequencies ****)
paulson@24287
   210
blanchet@38743
   211
(* A two-dimensional symbol table counts frequencies of constants. It's keyed
blanchet@38743
   212
   first by constant name and second by its list of type instantiations. For the
blanchet@38823
   213
   latter, we need a linear ordering on "pattern list". *)
paulson@24287
   214
blanchet@38823
   215
fun pattern_ord p =
blanchet@38743
   216
  case p of
blanchet@38744
   217
    (PVar, PVar) => EQUAL
blanchet@38823
   218
  | (PVar, PApp _) => LESS
blanchet@38823
   219
  | (PApp _, PVar) => GREATER
blanchet@38823
   220
  | (PApp q1, PApp q2) =>
blanchet@38823
   221
    prod_ord fast_string_ord (dict_ord pattern_ord) (q1, q2)
paulson@24287
   222
blanchet@38743
   223
structure CTtab =
blanchet@38823
   224
  Table(type key = pattern list val ord = dict_ord pattern_ord)
paulson@24287
   225
blanchet@38827
   226
fun count_axiom_consts theory_relevant thy =
blanchet@37503
   227
  let
blanchet@38827
   228
    fun do_const const (s, T) ts =
blanchet@38827
   229
      (* Two-dimensional table update. Constant maps to types maps to count. *)
blanchet@38827
   230
      CTtab.map_default (pconst_args thy const (s, T) ts, 0) (Integer.add 1)
blanchet@38827
   231
      |> Symtab.map_default (s, CTtab.empty)
blanchet@38827
   232
      #> fold do_term ts
blanchet@38827
   233
    and do_term t =
blanchet@38827
   234
      case strip_comb t of
blanchet@38827
   235
        (Const x, ts) => do_const true x ts
blanchet@38827
   236
      | (Free x, ts) => do_const false x ts
blanchet@38827
   237
      | (Abs (_, _, t'), ts) => fold do_term (t' :: ts)
blanchet@38827
   238
      | (_, ts) => fold do_term ts
blanchet@38827
   239
  in do_term o theory_const_prop_of theory_relevant o snd end
paulson@24287
   240
paulson@24287
   241
paulson@24287
   242
(**** Actual Filtering Code ****)
paulson@24287
   243
paulson@24287
   244
(*The frequency of a constant is the sum of those of all instances of its type.*)
blanchet@38824
   245
fun pconst_freq match const_tab (c, ps) =
blanchet@38824
   246
  CTtab.fold (fn (qs, m) => match (ps, qs) ? Integer.add m)
blanchet@38686
   247
             (the (Symtab.lookup const_tab c)) 0
blanchet@38686
   248
paulson@24287
   249
blanchet@38085
   250
(* A surprising number of theorems contain only a few significant constants.
blanchet@38085
   251
   These include all induction rules, and other general theorems. *)
blanchet@37503
   252
blanchet@37503
   253
(* "log" seems best in practice. A constant function of one ignores the constant
blanchet@37503
   254
   frequencies. *)
blanchet@38747
   255
fun rel_log n = 1.0 + 2.0 / Math.ln (Real.fromInt n + 1.0)
blanchet@38747
   256
fun irrel_log n = Math.ln (Real.fromInt n + 19.0) / 6.4
blanchet@37503
   257
blanchet@38752
   258
(* FUDGE *)
blanchet@38821
   259
val abs_rel_weight = 0.5
blanchet@38821
   260
val abs_irrel_weight = 2.0
blanchet@38821
   261
val skolem_rel_weight = 2.0  (* impossible *)
blanchet@38821
   262
val skolem_irrel_weight = 0.5
blanchet@38752
   263
blanchet@37503
   264
(* Computes a constant's weight, as determined by its frequency. *)
blanchet@38821
   265
fun generic_weight abs_weight skolem_weight logx f const_tab (c as (s, _)) =
blanchet@38816
   266
  if s = abs_name then abs_weight
blanchet@38816
   267
  else if String.isPrefix skolem_prefix s then skolem_weight
blanchet@38823
   268
  else logx (pconst_freq (match_patterns o f) const_tab c)
blanchet@38821
   269
blanchet@38821
   270
val rel_weight = generic_weight abs_rel_weight skolem_rel_weight rel_log I
blanchet@38821
   271
val irrel_weight = generic_weight abs_irrel_weight skolem_irrel_weight irrel_log
blanchet@38821
   272
                                  swap
paulson@24287
   273
blanchet@38752
   274
(* FUDGE *)
blanchet@38752
   275
fun locality_multiplier General = 1.0
blanchet@38752
   276
  | locality_multiplier Theory = 1.1
blanchet@38752
   277
  | locality_multiplier Local = 1.3
blanchet@38752
   278
  | locality_multiplier Chained = 2.0
blanchet@38751
   279
blanchet@38752
   280
fun axiom_weight loc const_tab relevant_consts axiom_consts =
blanchet@38827
   281
  case axiom_consts |> List.partition (pconst_hyper_mem I relevant_consts)
blanchet@38827
   282
                    ||> filter_out (pconst_hyper_mem swap relevant_consts) of
blanchet@38827
   283
    ([], _) => 0.0
blanchet@38744
   284
  | (rel, irrel) =>
blanchet@38827
   285
    case irrel |> filter_out (pconst_mem swap rel) of
blanchet@38827
   286
      [] => 1.0
blanchet@38827
   287
    | irrel =>
blanchet@38827
   288
      let
blanchet@38827
   289
        val rel_weight =
blanchet@38827
   290
          fold (curry Real.+ o rel_weight const_tab) rel 0.0
blanchet@38827
   291
          |> curry Real.* (locality_multiplier loc)
blanchet@38827
   292
        val irrel_weight =
blanchet@38827
   293
          fold (curry Real.+ o irrel_weight const_tab) irrel 0.0
blanchet@38827
   294
        val res = rel_weight / (rel_weight + irrel_weight)
blanchet@38827
   295
      in if Real.isFinite res then res else 0.0 end
blanchet@38747
   296
blanchet@38823
   297
fun pconsts_in_axiom thy t =
blanchet@38825
   298
  Symtab.fold (fn (s, pss) => fold (cons o pair s) pss)
blanchet@38823
   299
              (get_pconsts thy true (SOME true) [t]) []
blanchet@38687
   300
fun pair_consts_axiom theory_relevant thy axiom =
blanchet@38827
   301
  case axiom |> snd |> theory_const_prop_of theory_relevant
blanchet@38827
   302
             |> pconsts_in_axiom thy of
blanchet@38827
   303
    [] => NONE
blanchet@38827
   304
  | consts => SOME ((axiom, consts), NONE)
paulson@24287
   305
blanchet@38699
   306
type annotated_thm =
blanchet@38823
   307
  (((unit -> string) * locality) * thm) * (string * pattern list) list
blanchet@37505
   308
blanchet@38747
   309
fun take_most_relevant max_max_imperfect max_relevant remaining_max
blanchet@38747
   310
                       (candidates : (annotated_thm * real) list) =
blanchet@38744
   311
  let
blanchet@38747
   312
    val max_imperfect =
blanchet@38747
   313
      Real.ceil (Math.pow (max_max_imperfect,
blanchet@38747
   314
                           Real.fromInt remaining_max
blanchet@38747
   315
                           / Real.fromInt max_relevant))
blanchet@38747
   316
    val (perfect, imperfect) =
blanchet@38747
   317
      candidates |> List.partition (fn (_, w) => w > 0.99999)
blanchet@38745
   318
                 ||> sort (Real.compare o swap o pairself snd)
blanchet@38747
   319
    val ((accepts, more_rejects), rejects) =
blanchet@38747
   320
      chop max_imperfect imperfect |>> append perfect |>> chop remaining_max
blanchet@38744
   321
  in
blanchet@38747
   322
    trace_msg (fn () => "Actually passed (" ^ Int.toString (length accepts) ^
blanchet@38827
   323
        " of " ^ Int.toString (length candidates) ^ "): " ^ (accepts
blanchet@38752
   324
                 |> map (fn ((((name, _), _), _), weight) =>
blanchet@38752
   325
                            name () ^ " [" ^ Real.toString weight ^ "]")
blanchet@38745
   326
                 |> commas));
blanchet@38747
   327
    (accepts, more_rejects @ rejects)
blanchet@38744
   328
  end
paulson@24287
   329
blanchet@38819
   330
fun if_empty_replace_with_locality thy axioms loc tab =
blanchet@38819
   331
  if Symtab.is_empty tab then
blanchet@38823
   332
    get_pconsts thy false (SOME false)
blanchet@38819
   333
        (map_filter (fn ((_, loc'), th) =>
blanchet@38819
   334
                        if loc' = loc then SOME (prop_of th) else NONE) axioms)
blanchet@38819
   335
  else
blanchet@38819
   336
    tab
blanchet@38819
   337
blanchet@38752
   338
(* FUDGE *)
blanchet@38683
   339
val threshold_divisor = 2.0
blanchet@38683
   340
val ridiculous_threshold = 0.1
blanchet@38747
   341
val max_max_imperfect_fudge_factor = 0.66
blanchet@38683
   342
blanchet@38745
   343
fun relevance_filter ctxt threshold0 decay max_relevant theory_relevant
blanchet@38745
   344
                     ({add, del, ...} : relevance_override) axioms goal_ts =
blanchet@38739
   345
  let
blanchet@38739
   346
    val thy = ProofContext.theory_of ctxt
blanchet@38819
   347
    val const_tab =
blanchet@38819
   348
      fold (count_axiom_consts theory_relevant thy) axioms Symtab.empty
blanchet@38819
   349
    val goal_const_tab =
blanchet@38823
   350
      get_pconsts thy false (SOME false) goal_ts
blanchet@38819
   351
      |> fold (if_empty_replace_with_locality thy axioms)
blanchet@38819
   352
              [Chained, Local, Theory]
blanchet@38739
   353
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@38739
   354
    val del_thms = maps (ProofContext.get_fact ctxt) del
blanchet@38747
   355
    val max_max_imperfect =
blanchet@38747
   356
      Math.sqrt (Real.fromInt max_relevant * max_max_imperfect_fudge_factor)
blanchet@38747
   357
    fun iter j remaining_max threshold rel_const_tab hopeless hopeful =
blanchet@38739
   358
      let
blanchet@38744
   359
        fun game_over rejects =
blanchet@38747
   360
          (* Add "add:" facts. *)
blanchet@38747
   361
          if null add_thms then
blanchet@38747
   362
            []
blanchet@38744
   363
          else
blanchet@38747
   364
            map_filter (fn ((p as (_, th), _), _) =>
blanchet@38747
   365
                           if member Thm.eq_thm add_thms th then SOME p
blanchet@38747
   366
                           else NONE) rejects
blanchet@38747
   367
        fun relevant [] rejects hopeless [] =
blanchet@38747
   368
            (* Nothing has been added this iteration. *)
blanchet@38747
   369
            if j = 0 andalso threshold >= ridiculous_threshold then
blanchet@38747
   370
              (* First iteration? Try again. *)
blanchet@38747
   371
              iter 0 max_relevant (threshold / threshold_divisor) rel_const_tab
blanchet@38747
   372
                   hopeless hopeful
blanchet@38744
   373
            else
blanchet@38747
   374
              game_over (rejects @ hopeless)
blanchet@38747
   375
          | relevant candidates rejects hopeless [] =
blanchet@38739
   376
            let
blanchet@38747
   377
              val (accepts, more_rejects) =
blanchet@38747
   378
                take_most_relevant max_max_imperfect max_relevant remaining_max
blanchet@38747
   379
                                   candidates
blanchet@38739
   380
              val rel_const_tab' =
blanchet@38745
   381
                rel_const_tab
blanchet@38823
   382
                |> fold (add_pconst_to_table false)
blanchet@38747
   383
                        (maps (snd o fst) accepts)
blanchet@38744
   384
              fun is_dirty (c, _) =
blanchet@38744
   385
                Symtab.lookup rel_const_tab' c <> Symtab.lookup rel_const_tab c
blanchet@38745
   386
              val (hopeful_rejects, hopeless_rejects) =
blanchet@38745
   387
                 (rejects @ hopeless, ([], []))
blanchet@38745
   388
                 |-> fold (fn (ax as (_, consts), old_weight) =>
blanchet@38745
   389
                              if exists is_dirty consts then
blanchet@38745
   390
                                apfst (cons (ax, NONE))
blanchet@38745
   391
                              else
blanchet@38745
   392
                                apsnd (cons (ax, old_weight)))
blanchet@38745
   393
                 |>> append (more_rejects
blanchet@38745
   394
                             |> map (fn (ax as (_, consts), old_weight) =>
blanchet@38745
   395
                                        (ax, if exists is_dirty consts then NONE
blanchet@38745
   396
                                             else SOME old_weight)))
blanchet@38747
   397
              val threshold =
blanchet@38822
   398
                1.0 - (1.0 - threshold)
blanchet@38822
   399
                      * Math.pow (decay, Real.fromInt (length accepts))
blanchet@38747
   400
              val remaining_max = remaining_max - length accepts
blanchet@38739
   401
            in
blanchet@38744
   402
              trace_msg (fn () => "New or updated constants: " ^
blanchet@38744
   403
                  commas (rel_const_tab' |> Symtab.dest
blanchet@38822
   404
                          |> subtract (op =) (rel_const_tab |> Symtab.dest)
blanchet@38827
   405
                          |> map string_for_hyper_pconst));
blanchet@38745
   406
              map (fst o fst) accepts @
blanchet@38747
   407
              (if remaining_max = 0 then
blanchet@38745
   408
                 game_over (hopeful_rejects @ map (apsnd SOME) hopeless_rejects)
blanchet@38745
   409
               else
blanchet@38747
   410
                 iter (j + 1) remaining_max threshold rel_const_tab'
blanchet@38747
   411
                      hopeless_rejects hopeful_rejects)
blanchet@38739
   412
            end
blanchet@38747
   413
          | relevant candidates rejects hopeless
blanchet@38752
   414
                     (((ax as (((_, loc), th), axiom_consts)), cached_weight)
blanchet@38747
   415
                      :: hopeful) =
blanchet@38739
   416
            let
blanchet@38739
   417
              val weight =
blanchet@38739
   418
                case cached_weight of
blanchet@38739
   419
                  SOME w => w
blanchet@38752
   420
                | NONE => axiom_weight loc const_tab rel_const_tab axiom_consts
blanchet@38747
   421
(* TODO: experiment
blanchet@38752
   422
val name = fst (fst (fst ax)) ()
blanchet@38752
   423
val _ = if String.isPrefix "lift.simps(3" name then
blanchet@38752
   424
tracing ("*** " ^ name ^ PolyML.makestring (debug_axiom_weight const_tab rel_const_tab axiom_consts))
blanchet@38747
   425
else
blanchet@38747
   426
()
blanchet@38747
   427
*)
blanchet@38739
   428
            in
blanchet@38741
   429
              if weight >= threshold then
blanchet@38747
   430
                relevant ((ax, weight) :: candidates) rejects hopeless hopeful
blanchet@38739
   431
              else
blanchet@38747
   432
                relevant candidates ((ax, weight) :: rejects) hopeless hopeful
blanchet@38739
   433
            end
blanchet@38739
   434
        in
blanchet@38744
   435
          trace_msg (fn () =>
blanchet@38744
   436
              "ITERATION " ^ string_of_int j ^ ": current threshold: " ^
blanchet@38744
   437
              Real.toString threshold ^ ", constants: " ^
blanchet@38744
   438
              commas (rel_const_tab |> Symtab.dest
blanchet@38744
   439
                      |> filter (curry (op <>) [] o snd)
blanchet@38827
   440
                      |> map string_for_hyper_pconst));
blanchet@38747
   441
          relevant [] [] hopeless hopeful
blanchet@38739
   442
        end
blanchet@38739
   443
  in
blanchet@38739
   444
    axioms |> filter_out (member Thm.eq_thm del_thms o snd)
blanchet@38827
   445
           |> map_filter (pair_consts_axiom theory_relevant thy)
blanchet@38819
   446
           |> iter 0 max_relevant threshold0 goal_const_tab []
blanchet@38739
   447
           |> tap (fn res => trace_msg (fn () =>
blanchet@38686
   448
                                "Total relevant: " ^ Int.toString (length res)))
blanchet@38739
   449
  end
paulson@24287
   450
blanchet@38744
   451
paulson@24287
   452
(***************************************************************)
mengj@19768
   453
(* Retrieving and filtering lemmas                             *)
mengj@19768
   454
(***************************************************************)
mengj@19768
   455
paulson@33022
   456
(*** retrieve lemmas and filter them ***)
mengj@19768
   457
paulson@20757
   458
(*Reject theorems with names like "List.filter.filter_list_def" or
paulson@21690
   459
  "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
paulson@20757
   460
fun is_package_def a =
wenzelm@30364
   461
  let val names = Long_Name.explode a
paulson@21690
   462
  in
paulson@21690
   463
     length names > 2 andalso
paulson@21690
   464
     not (hd names = "local") andalso
paulson@21690
   465
     String.isSuffix "_def" a  orelse  String.isSuffix "_defs" a
paulson@21690
   466
  end;
paulson@20757
   467
blanchet@38085
   468
fun make_fact_table xs =
blanchet@37616
   469
  fold (Termtab.update o `(prop_of o snd)) xs Termtab.empty
blanchet@38085
   470
fun make_unique xs = Termtab.fold (cons o snd) (make_fact_table xs) []
mengj@19768
   471
blanchet@37626
   472
(* FIXME: put other record thms here, or declare as "no_atp" *)
blanchet@37626
   473
val multi_base_blacklist =
blanchet@37626
   474
  ["defs", "select_defs", "update_defs", "induct", "inducts", "split", "splits",
blanchet@38682
   475
   "split_asm", "cases", "ext_cases", "eq.simps", "eq.refl", "nchotomy",
blanchet@38682
   476
   "case_cong", "weak_case_cong"]
blanchet@38682
   477
  |> map (prefix ".")
blanchet@37626
   478
blanchet@37626
   479
val max_lambda_nesting = 3
blanchet@37626
   480
blanchet@37626
   481
fun term_has_too_many_lambdas max (t1 $ t2) =
blanchet@37626
   482
    exists (term_has_too_many_lambdas max) [t1, t2]
blanchet@37626
   483
  | term_has_too_many_lambdas max (Abs (_, _, t)) =
blanchet@37626
   484
    max = 0 orelse term_has_too_many_lambdas (max - 1) t
blanchet@37626
   485
  | term_has_too_many_lambdas _ _ = false
blanchet@37626
   486
blanchet@37626
   487
(* Don't count nested lambdas at the level of formulas, since they are
blanchet@37626
   488
   quantifiers. *)
blanchet@37626
   489
fun formula_has_too_many_lambdas Ts (Abs (_, T, t)) =
blanchet@37626
   490
    formula_has_too_many_lambdas (T :: Ts) t
blanchet@37626
   491
  | formula_has_too_many_lambdas Ts t =
blanchet@37626
   492
    if is_formula_type (fastype_of1 (Ts, t)) then
blanchet@37626
   493
      exists (formula_has_too_many_lambdas Ts) (#2 (strip_comb t))
blanchet@37626
   494
    else
blanchet@37626
   495
      term_has_too_many_lambdas max_lambda_nesting t
blanchet@37626
   496
blanchet@38692
   497
(* The max apply depth of any "metis" call in "Metis_Examples" (on 2007-10-31)
blanchet@37626
   498
   was 11. *)
blanchet@37626
   499
val max_apply_depth = 15
blanchet@37626
   500
blanchet@37626
   501
fun apply_depth (f $ t) = Int.max (apply_depth f, apply_depth t + 1)
blanchet@37626
   502
  | apply_depth (Abs (_, _, t)) = apply_depth t
blanchet@37626
   503
  | apply_depth _ = 0
blanchet@37626
   504
blanchet@37626
   505
fun is_formula_too_complex t =
blanchet@38085
   506
  apply_depth t > max_apply_depth orelse formula_has_too_many_lambdas [] t
blanchet@37626
   507
blanchet@37543
   508
val exists_sledgehammer_const =
blanchet@37626
   509
  exists_Const (fn (s, _) => String.isPrefix sledgehammer_prefix s)
blanchet@37626
   510
blanchet@38821
   511
fun is_metastrange_theorem th =
blanchet@37626
   512
  case head_of (concl_of th) of
blanchet@37626
   513
      Const (a, _) => (a <> @{const_name Trueprop} andalso
blanchet@37626
   514
                       a <> @{const_name "=="})
blanchet@37626
   515
    | _ => false
blanchet@37626
   516
blanchet@38821
   517
fun is_that_fact th =
blanchet@38821
   518
  String.isSuffix (Long_Name.separator ^ Obtain.thatN) (Thm.get_name_hint th)
blanchet@38821
   519
  andalso exists_subterm (fn Free (s, _) => s = Name.skolem Auto_Bind.thesisN
blanchet@38821
   520
                           | _ => false) (prop_of th)
blanchet@38821
   521
blanchet@37626
   522
val type_has_top_sort =
blanchet@37626
   523
  exists_subtype (fn TFree (_, []) => true | TVar (_, []) => true | _ => false)
blanchet@37626
   524
blanchet@38085
   525
(**** Predicates to detect unwanted facts (prolific or likely to cause
blanchet@37347
   526
      unsoundness) ****)
paulson@21470
   527
blanchet@38289
   528
(* Too general means, positive equality literal with a variable X as one
blanchet@38289
   529
   operand, when X does not occur properly in the other operand. This rules out
blanchet@38289
   530
   clearly inconsistent facts such as X = a | X = b, though it by no means
blanchet@38289
   531
   guarantees soundness. *)
paulson@21470
   532
blanchet@38289
   533
(* Unwanted equalities are those between a (bound or schematic) variable that
blanchet@38289
   534
   does not properly occur in the second operand. *)
blanchet@38607
   535
val is_exhaustive_finite =
blanchet@38607
   536
  let
blanchet@38629
   537
    fun is_bad_equal (Var z) t =
blanchet@38629
   538
        not (exists_subterm (fn Var z' => z = z' | _ => false) t)
blanchet@38629
   539
      | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
blanchet@38629
   540
      | is_bad_equal _ _ = false
blanchet@38629
   541
    fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
blanchet@38607
   542
    fun do_formula pos t =
blanchet@38607
   543
      case (pos, t) of
blanchet@38615
   544
        (_, @{const Trueprop} $ t1) => do_formula pos t1
blanchet@38607
   545
      | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
blanchet@38607
   546
        do_formula pos t'
blanchet@38607
   547
      | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
blanchet@38607
   548
        do_formula pos t'
blanchet@38607
   549
      | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
blanchet@38607
   550
        do_formula pos t'
blanchet@38607
   551
      | (_, @{const "==>"} $ t1 $ t2) =>
blanchet@38629
   552
        do_formula (not pos) t1 andalso
blanchet@38629
   553
        (t2 = @{prop False} orelse do_formula pos t2)
haftmann@38786
   554
      | (_, @{const HOL.implies} $ t1 $ t2) =>
blanchet@38629
   555
        do_formula (not pos) t1 andalso
blanchet@38629
   556
        (t2 = @{const False} orelse do_formula pos t2)
blanchet@38607
   557
      | (_, @{const Not} $ t1) => do_formula (not pos) t1
haftmann@38795
   558
      | (true, @{const HOL.disj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
haftmann@38795
   559
      | (false, @{const HOL.conj} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
haftmann@38864
   560
      | (true, Const (@{const_name HOL.eq}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38607
   561
      | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
blanchet@38607
   562
      | _ => false
blanchet@38607
   563
  in do_formula true end
blanchet@38607
   564
blanchet@38592
   565
fun has_bound_or_var_of_type tycons =
blanchet@38592
   566
  exists_subterm (fn Var (_, Type (s, _)) => member (op =) tycons s
blanchet@38592
   567
                   | Abs (_, Type (s, _), _) => member (op =) tycons s
blanchet@38592
   568
                   | _ => false)
paulson@21431
   569
blanchet@38085
   570
(* Facts are forbidden to contain variables of these types. The typical reason
blanchet@37347
   571
   is that they lead to unsoundness. Note that "unit" satisfies numerous
blanchet@38085
   572
   equations like "?x = ()". The resulting clauses will have no type constraint,
blanchet@37347
   573
   yielding false proofs. Even "bool" leads to many unsound proofs, though only
blanchet@37347
   574
   for higher-order problems. *)
blanchet@38592
   575
val dangerous_types = [@{type_name unit}, @{type_name bool}, @{type_name prop}];
paulson@22217
   576
blanchet@38085
   577
(* Facts containing variables of type "unit" or "bool" or of the form
blanchet@38290
   578
   "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
blanchet@38290
   579
   are omitted. *)
blanchet@38593
   580
fun is_dangerous_term full_types t =
blanchet@38609
   581
  not full_types andalso
blanchet@38679
   582
  let val t = transform_elim_term t in
blanchet@38679
   583
    has_bound_or_var_of_type dangerous_types t orelse
blanchet@38679
   584
    is_exhaustive_finite t
blanchet@38679
   585
  end
paulson@21470
   586
blanchet@38627
   587
fun is_theorem_bad_for_atps full_types thm =
blanchet@38627
   588
  let val t = prop_of thm in
blanchet@38627
   589
    is_formula_too_complex t orelse exists_type type_has_top_sort t orelse
blanchet@38627
   590
    is_dangerous_term full_types t orelse exists_sledgehammer_const t orelse
blanchet@38821
   591
    is_metastrange_theorem thm orelse is_that_fact thm
blanchet@38627
   592
  end
blanchet@38627
   593
blanchet@38696
   594
fun all_name_thms_pairs ctxt reserved full_types add_thms chained_ths =
blanchet@38627
   595
  let
blanchet@38752
   596
    val thy = ProofContext.theory_of ctxt
blanchet@38752
   597
    val thy_prefix = Context.theory_name thy ^ Long_Name.separator
blanchet@38752
   598
    val global_facts = PureThy.facts_of thy
blanchet@38644
   599
    val local_facts = ProofContext.facts_of ctxt
blanchet@38644
   600
    val named_locals = local_facts |> Facts.dest_static []
blanchet@38752
   601
    val is_chained = member Thm.eq_thm chained_ths
blanchet@38818
   602
    (* Unnamed nonchained formulas with schematic variables are omitted, because
blanchet@38818
   603
       they are rejected by the backticks (`...`) parser for some reason. *)
blanchet@38738
   604
    fun is_good_unnamed_local th =
blanchet@38820
   605
      not (Thm.has_name_hint th) andalso
blanchet@38820
   606
      (not (exists_subterm is_Var (prop_of th)) orelse (is_chained th)) andalso
blanchet@38738
   607
      forall (fn (_, ths) => not (member Thm.eq_thm ths th)) named_locals
blanchet@38644
   608
    val unnamed_locals =
blanchet@38820
   609
      union Thm.eq_thm (Facts.props local_facts) chained_ths
blanchet@38820
   610
      |> filter is_good_unnamed_local |> map (pair "" o single)
blanchet@38627
   611
    val full_space =
blanchet@38738
   612
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts)
blanchet@38752
   613
    fun add_facts global foldx facts =
blanchet@38699
   614
      foldx (fn (name0, ths) =>
blanchet@38699
   615
        if name0 <> "" andalso
blanchet@38699
   616
           forall (not o member Thm.eq_thm add_thms) ths andalso
blanchet@38699
   617
           (Facts.is_concealed facts name0 orelse
blanchet@38699
   618
            (respect_no_atp andalso is_package_def name0) orelse
blanchet@38699
   619
            exists (fn s => String.isSuffix s name0) multi_base_blacklist orelse
blanchet@38699
   620
            String.isSuffix "_def_raw" (* FIXME: crude hack *) name0) then
blanchet@38627
   621
          I
blanchet@38627
   622
        else
blanchet@38627
   623
          let
blanchet@38752
   624
            val base_loc =
blanchet@38752
   625
              if not global then Local
blanchet@38752
   626
              else if String.isPrefix thy_prefix name0 then Theory
blanchet@38752
   627
              else General
blanchet@38699
   628
            val multi = length ths > 1
blanchet@38696
   629
            fun backquotify th =
blanchet@38696
   630
              "`" ^ Print_Mode.setmp [Print_Mode.input]
blanchet@38696
   631
                                 (Syntax.string_of_term ctxt) (prop_of th) ^ "`"
blanchet@38738
   632
              |> String.translate (fn c => if Char.isPrint c then str c else "")
blanchet@38738
   633
              |> simplify_spaces
blanchet@38699
   634
            fun check_thms a =
blanchet@38699
   635
              case try (ProofContext.get_thms ctxt) a of
blanchet@38699
   636
                NONE => false
blanchet@38699
   637
              | SOME ths' => Thm.eq_thms (ths, ths')
blanchet@38627
   638
          in
blanchet@38699
   639
            pair 1
blanchet@38699
   640
            #> fold (fn th => fn (j, rest) =>
blanchet@38699
   641
                 (j + 1,
blanchet@38699
   642
                  if is_theorem_bad_for_atps full_types th andalso
blanchet@38699
   643
                     not (member Thm.eq_thm add_thms th) then
blanchet@38699
   644
                    rest
blanchet@38699
   645
                  else
blanchet@38752
   646
                    (((fn () =>
blanchet@38752
   647
                          if name0 = "" then
blanchet@38752
   648
                            th |> backquotify
blanchet@38752
   649
                          else
blanchet@38752
   650
                            let
blanchet@38752
   651
                              val name1 = Facts.extern facts name0
blanchet@38752
   652
                              val name2 = Name_Space.extern full_space name0
blanchet@38752
   653
                            in
blanchet@38752
   654
                              case find_first check_thms [name1, name2, name0] of
blanchet@38752
   655
                                SOME name => repair_name reserved multi j name
blanchet@38752
   656
                              | NONE => ""
blanchet@38752
   657
                            end), if is_chained th then Chained else base_loc),
blanchet@38752
   658
                      (multi, th)) :: rest)) ths
blanchet@38699
   659
            #> snd
blanchet@38627
   660
          end)
blanchet@38644
   661
  in
blanchet@38752
   662
    [] |> add_facts false fold local_facts (unnamed_locals @ named_locals)
blanchet@38752
   663
       |> add_facts true Facts.fold_static global_facts global_facts
blanchet@38644
   664
  end
blanchet@38627
   665
blanchet@38627
   666
(* The single-name theorems go after the multiple-name ones, so that single
blanchet@38627
   667
   names are preferred when both are available. *)
blanchet@38699
   668
fun name_thm_pairs ctxt respect_no_atp =
blanchet@38744
   669
  List.partition (fst o snd) #> op @ #> map (apsnd snd)
blanchet@38699
   670
  #> respect_no_atp ? filter_out (No_ATPs.member ctxt o snd)
blanchet@38627
   671
blanchet@38627
   672
(***************************************************************)
blanchet@38627
   673
(* ATP invocation methods setup                                *)
blanchet@38627
   674
(***************************************************************)
blanchet@38627
   675
blanchet@38745
   676
fun relevant_facts full_types (threshold0, threshold1) max_relevant
blanchet@38744
   677
                   theory_relevant (relevance_override as {add, del, only})
blanchet@37995
   678
                   (ctxt, (chained_ths, _)) hyp_ts concl_t =
blanchet@37538
   679
  let
blanchet@38822
   680
    val decay = Math.pow ((1.0 - threshold1) / (1.0 - threshold0),
blanchet@38822
   681
                          1.0 / Real.fromInt (max_relevant + 1))
blanchet@37538
   682
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@38696
   683
    val reserved = reserved_isar_keyword_table ()
blanchet@37538
   684
    val axioms =
blanchet@38699
   685
      (if only then
blanchet@38752
   686
         maps (map (fn ((name, loc), th) => ((K name, loc), (true, th)))
blanchet@38752
   687
               o name_thm_pairs_from_ref ctxt reserved chained_ths) add
blanchet@38699
   688
       else
blanchet@38699
   689
         all_name_thms_pairs ctxt reserved full_types add_thms chained_ths)
blanchet@38688
   690
      |> name_thm_pairs ctxt (respect_no_atp andalso not only)
blanchet@38595
   691
      |> make_unique
blanchet@37538
   692
  in
blanchet@38688
   693
    trace_msg (fn () => "Considering " ^ Int.toString (length axioms) ^
blanchet@38688
   694
                        " theorems");
blanchet@38745
   695
    (if threshold0 > 1.0 orelse threshold0 > threshold1 then
blanchet@38739
   696
       []
blanchet@38745
   697
     else if threshold0 < 0.0 then
blanchet@38739
   698
       axioms
blanchet@38739
   699
     else
blanchet@38745
   700
       relevance_filter ctxt threshold0 decay max_relevant theory_relevant
blanchet@38745
   701
                        relevance_override axioms (concl_t :: hyp_ts))
blanchet@38822
   702
    |> map (apfst (apfst (fn f => f ())))
blanchet@37538
   703
  end
immler@30536
   704
paulson@15347
   705
end;