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