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