src/HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
author blanchet
Thu Jul 29 17:45:22 2010 +0200 (2010-07-29 ago)
changeset 38091 0508ff84036f
parent 38090 fe51c098b0ab
child 38095 7627881fe9d4
permissions -rw-r--r--
work around atomization failures
blanchet@35826
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
blanchet@38027
     2
    Author:     Jia Meng, Cambridge University Computer Laboratory and NICTA
blanchet@36393
     3
    Author:     Jasmin Blanchette, TU Muenchen
wenzelm@33309
     4
*)
paulson@15452
     5
blanchet@35826
     6
signature SLEDGEHAMMER_FACT_FILTER =
wenzelm@16802
     7
sig
blanchet@35966
     8
  type relevance_override =
blanchet@35966
     9
    {add: Facts.ref list,
blanchet@35966
    10
     del: Facts.ref list,
blanchet@35966
    11
     only: bool}
blanchet@35966
    12
blanchet@37616
    13
  val trace : bool Unsynchronized.ref
blanchet@37616
    14
  val chained_prefix : string
blanchet@37616
    15
  val name_thms_pair_from_ref :
blanchet@37616
    16
    Proof.context -> thm list -> Facts.ref -> string * thm list
blanchet@37347
    17
  val relevant_facts :
blanchet@37580
    18
    bool -> real -> real -> bool -> int -> bool -> relevance_override
blanchet@37995
    19
    -> Proof.context * (thm list * 'a) -> term list -> term
blanchet@37995
    20
    -> (string * thm) list
paulson@15347
    21
end;
paulson@15347
    22
blanchet@35826
    23
structure Sledgehammer_Fact_Filter : SLEDGEHAMMER_FACT_FILTER =
paulson@15347
    24
struct
paulson@15347
    25
blanchet@37616
    26
val trace = Unsynchronized.ref false
blanchet@37616
    27
fun trace_msg msg = if !trace then tracing (msg ()) else ()
blanchet@35826
    28
blanchet@37580
    29
val respect_no_atp = true
blanchet@37505
    30
blanchet@35966
    31
type relevance_override =
blanchet@35966
    32
  {add: Facts.ref list,
blanchet@35966
    33
   del: Facts.ref list,
blanchet@35966
    34
   only: bool}
paulson@21070
    35
blanchet@37616
    36
val sledgehammer_prefix = "Sledgehammer" ^ Long_Name.separator
blanchet@37616
    37
(* Used to label theorems chained into the goal. *)
blanchet@37616
    38
val chained_prefix = sledgehammer_prefix ^ "chained_"
blanchet@37616
    39
blanchet@37616
    40
fun name_thms_pair_from_ref ctxt chained_ths xref =
blanchet@37616
    41
  let
blanchet@37616
    42
    val ths = ProofContext.get_fact ctxt xref
blanchet@37616
    43
    val name = Facts.string_of_ref xref
blanchet@37616
    44
               |> forall (member Thm.eq_thm chained_ths) ths
blanchet@37616
    45
                  ? prefix chained_prefix
blanchet@37616
    46
  in (name, ths) end
blanchet@37616
    47
blanchet@37616
    48
wenzelm@28477
    49
(***************************************************************)
wenzelm@28477
    50
(* Relevance Filtering                                         *)
wenzelm@28477
    51
(***************************************************************)
mengj@19194
    52
blanchet@35865
    53
fun strip_Trueprop (@{const Trueprop} $ t) = t
paulson@24958
    54
  | strip_Trueprop t = t;
mengj@19194
    55
paulson@24287
    56
(*** constants with types ***)
paulson@24287
    57
paulson@24287
    58
(*An abstraction of Isabelle types*)
paulson@24287
    59
datatype const_typ =  CTVar | CType of string * const_typ list
paulson@24287
    60
paulson@24287
    61
(*Is the second type an instance of the first one?*)
blanchet@37505
    62
fun match_type (CType(con1,args1)) (CType(con2,args2)) =
paulson@24287
    63
      con1=con2 andalso match_types args1 args2
paulson@24287
    64
  | match_type CTVar _ = true
paulson@24287
    65
  | match_type _ CTVar = false
paulson@24287
    66
and match_types [] [] = true
paulson@24287
    67
  | match_types (a1::as1) (a2::as2) = match_type a1 a2 andalso match_types as1 as2;
paulson@24287
    68
paulson@24287
    69
(*Is there a unifiable constant?*)
blanchet@37505
    70
fun uni_mem goal_const_tab (c, c_typ) =
blanchet@37505
    71
  exists (match_types c_typ) (these (Symtab.lookup goal_const_tab c))
blanchet@37505
    72
paulson@24287
    73
(*Maps a "real" type to a const_typ*)
blanchet@37505
    74
fun const_typ_of (Type (c,typs)) = CType (c, map const_typ_of typs)
paulson@24287
    75
  | const_typ_of (TFree _) = CTVar
paulson@24287
    76
  | const_typ_of (TVar _) = CTVar
paulson@24287
    77
paulson@24287
    78
(*Pairs a constant with the list of its type instantiations (using const_typ)*)
blanchet@37505
    79
fun const_with_typ thy (c,typ) =
paulson@24287
    80
    let val tvars = Sign.const_typargs thy (c,typ)
paulson@24287
    81
    in (c, map const_typ_of tvars) end
blanchet@37505
    82
    handle TYPE _ => (c,[]);   (*Variable (locale constant): monomorphic*)
paulson@24287
    83
paulson@24287
    84
(*Add a const/type pair to the table, but a [] entry means a standard connective,
paulson@24287
    85
  which we ignore.*)
blanchet@37502
    86
fun add_const_type_to_table (c, ctyps) =
blanchet@37502
    87
  Symtab.map_default (c, [ctyps])
blanchet@37502
    88
                     (fn [] => [] | ctypss => insert (op =) ctyps ctypss)
paulson@24287
    89
blanchet@37551
    90
val fresh_prefix = "Sledgehammer.Fresh."
blanchet@37537
    91
val flip = Option.map not
blanchet@38091
    92
(* These are typically simplified away by "Meson.presimplify". *)
blanchet@38091
    93
val boring_consts = [@{const_name If}, @{const_name Let}]
blanchet@37537
    94
blanchet@37537
    95
fun get_consts_typs thy pos ts =
blanchet@37505
    96
  let
blanchet@37505
    97
    (* Free variables are included, as well as constants, to handle locales.
blanchet@37505
    98
       "skolem_id" is included to increase the complexity of theorems containing
blanchet@37505
    99
       Skolem functions. In non-CNF form, "Ex" is included but each occurrence
blanchet@37505
   100
       is considered fresh, to simulate the effect of Skolemization. *)
blanchet@37537
   101
    fun do_term t =
blanchet@37537
   102
      case t of
blanchet@37537
   103
        Const x => add_const_type_to_table (const_with_typ thy x)
blanchet@37537
   104
      | Free x => add_const_type_to_table (const_with_typ thy x)
blanchet@37537
   105
      | (t as Const (@{const_name skolem_id}, _)) $ _ => do_term t
blanchet@37537
   106
      | t1 $ t2 => do_term t1 #> do_term t2
blanchet@37551
   107
      | Abs (_, _, t) =>
blanchet@37551
   108
        (* Abstractions lead to combinators, so we add a penalty for them. *)
blanchet@37551
   109
        add_const_type_to_table (gensym fresh_prefix, [])
blanchet@37551
   110
        #> do_term t
blanchet@37537
   111
      | _ => I
blanchet@37537
   112
    fun do_quantifier sweet_pos pos body_t =
blanchet@37537
   113
      do_formula pos body_t
blanchet@37537
   114
      #> (if pos = SOME sweet_pos then I
blanchet@37551
   115
          else add_const_type_to_table (gensym fresh_prefix, []))
blanchet@37537
   116
    and do_equality T t1 t2 =
blanchet@37537
   117
      fold (if T = @{typ bool} orelse T = @{typ prop} then do_formula NONE
blanchet@37537
   118
            else do_term) [t1, t2]
blanchet@37537
   119
    and do_formula pos t =
blanchet@37537
   120
      case t of
blanchet@37537
   121
        Const (@{const_name all}, _) $ Abs (_, _, body_t) =>
blanchet@37537
   122
        do_quantifier false pos body_t
blanchet@37537
   123
      | @{const "==>"} $ t1 $ t2 =>
blanchet@37537
   124
        do_formula (flip pos) t1 #> do_formula pos t2
blanchet@37537
   125
      | Const (@{const_name "=="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@37537
   126
        do_equality T t1 t2
blanchet@37537
   127
      | @{const Trueprop} $ t1 => do_formula pos t1
blanchet@37537
   128
      | @{const Not} $ t1 => do_formula (flip pos) t1
blanchet@37537
   129
      | Const (@{const_name All}, _) $ Abs (_, _, body_t) =>
blanchet@37537
   130
        do_quantifier false pos body_t
blanchet@37537
   131
      | Const (@{const_name Ex}, _) $ Abs (_, _, body_t) =>
blanchet@37537
   132
        do_quantifier true pos body_t
blanchet@37537
   133
      | @{const "op &"} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
blanchet@37537
   134
      | @{const "op |"} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
blanchet@37537
   135
      | @{const "op -->"} $ t1 $ t2 =>
blanchet@37537
   136
        do_formula (flip pos) t1 #> do_formula pos t2
blanchet@37537
   137
      | Const (@{const_name "op ="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@37537
   138
        do_equality T t1 t2
blanchet@37537
   139
      | (t0 as Const (_, @{typ bool})) $ t1 =>
blanchet@37537
   140
        do_term t0 #> do_formula pos t1  (* theory constant *)
blanchet@37537
   141
      | _ => do_term t
blanchet@37505
   142
  in
blanchet@38091
   143
    Symtab.empty |> fold (Symtab.update o rpair []) boring_consts
blanchet@37995
   144
                 |> fold (do_formula pos) ts
blanchet@37505
   145
  end
paulson@24287
   146
paulson@24287
   147
(*Inserts a dummy "constant" referring to the theory name, so that relevance
paulson@24287
   148
  takes the given theory into account.*)
blanchet@37616
   149
fun theory_const_prop_of theory_relevant th =
blanchet@37505
   150
  if theory_relevant then
blanchet@37505
   151
    let
blanchet@37505
   152
      val name = Context.theory_name (theory_of_thm th)
blanchet@37505
   153
      val t = Const (name ^ ". 1", @{typ bool})
blanchet@37505
   154
    in t $ prop_of th end
blanchet@37505
   155
  else
blanchet@37505
   156
    prop_of th
blanchet@37505
   157
paulson@24287
   158
(**** Constant / Type Frequencies ****)
paulson@24287
   159
paulson@24287
   160
(*A two-dimensional symbol table counts frequencies of constants. It's keyed first by
paulson@24287
   161
  constant name and second by its list of type instantiations. For the latter, we need
paulson@24287
   162
  a linear ordering on type const_typ list.*)
blanchet@37505
   163
paulson@24287
   164
local
paulson@24287
   165
paulson@24287
   166
fun cons_nr CTVar = 0
paulson@24287
   167
  | cons_nr (CType _) = 1;
paulson@24287
   168
paulson@24287
   169
in
paulson@24287
   170
paulson@24287
   171
fun const_typ_ord TU =
paulson@24287
   172
  case TU of
paulson@24287
   173
    (CType (a, Ts), CType (b, Us)) =>
paulson@24287
   174
      (case fast_string_ord(a,b) of EQUAL => dict_ord const_typ_ord (Ts,Us) | ord => ord)
paulson@24287
   175
  | (T, U) => int_ord (cons_nr T, cons_nr U);
paulson@24287
   176
paulson@24287
   177
end;
paulson@24287
   178
wenzelm@31971
   179
structure CTtab = Table(type key = const_typ list val ord = dict_ord const_typ_ord);
paulson@24287
   180
blanchet@37616
   181
fun count_axiom_consts theory_relevant thy (_, th) =
blanchet@37503
   182
  let
blanchet@37503
   183
    fun do_const (a, T) =
blanchet@37503
   184
      let val (c, cts) = const_with_typ thy (a,T) in
blanchet@37503
   185
        (* Two-dimensional table update. Constant maps to types maps to
blanchet@37503
   186
           count. *)
blanchet@37503
   187
        CTtab.map_default (cts, 0) (Integer.add 1)
blanchet@37503
   188
        |> Symtab.map_default (c, CTtab.empty)
blanchet@37503
   189
      end
blanchet@37503
   190
    fun do_term (Const x) = do_const x
blanchet@37503
   191
      | do_term (Free x) = do_const x
blanchet@37515
   192
      | do_term (Const (x as (@{const_name skolem_id}, _)) $ _) = do_const x
blanchet@37503
   193
      | do_term (t $ u) = do_term t #> do_term u
blanchet@37503
   194
      | do_term (Abs (_, _, t)) = do_term t
blanchet@37503
   195
      | do_term _ = I
blanchet@37616
   196
  in th |> theory_const_prop_of theory_relevant |> do_term end
paulson@24287
   197
paulson@24287
   198
paulson@24287
   199
(**** Actual Filtering Code ****)
paulson@24287
   200
paulson@24287
   201
(*The frequency of a constant is the sum of those of all instances of its type.*)
blanchet@37505
   202
fun const_frequency const_tab (c, cts) =
blanchet@36185
   203
  CTtab.fold (fn (cts', m) => match_types cts cts' ? Integer.add m)
blanchet@37505
   204
             (the (Symtab.lookup const_tab c)
blanchet@37505
   205
              handle Option.Option => raise Fail ("Const: " ^ c)) 0
paulson@24287
   206
blanchet@38085
   207
(* A surprising number of theorems contain only a few significant constants.
blanchet@38085
   208
   These include all induction rules, and other general theorems. *)
blanchet@37503
   209
blanchet@37503
   210
(* "log" seems best in practice. A constant function of one ignores the constant
blanchet@37503
   211
   frequencies. *)
blanchet@37503
   212
fun log_weight2 (x:real) = 1.0 + 2.0 / Math.ln (x + 1.0)
blanchet@37503
   213
blanchet@37503
   214
(* Computes a constant's weight, as determined by its frequency. *)
blanchet@37503
   215
val ct_weight = log_weight2 o real oo const_frequency
paulson@24287
   216
blanchet@37505
   217
(*Relevant constants are weighted according to frequency,
paulson@24287
   218
  but irrelevant constants are simply counted. Otherwise, Skolem functions,
blanchet@38085
   219
  which are rare, would harm a formula's chances of being picked.*)
blanchet@38085
   220
fun formula_weight const_tab gctyps consts_typs =
paulson@24287
   221
    let val rel = filter (uni_mem gctyps) consts_typs
blanchet@37505
   222
        val rel_weight = fold (curry Real.+ o ct_weight const_tab) rel 0.0
paulson@24287
   223
    in
wenzelm@32960
   224
        rel_weight / (rel_weight + real (length consts_typs - length rel))
paulson@24287
   225
    end;
blanchet@37505
   226
paulson@24287
   227
(*Multiplies out to a list of pairs: 'a * 'b list -> ('a * 'b) list -> ('a * 'b) list*)
wenzelm@30190
   228
fun add_expand_pairs (x,ys) xys = List.foldl (fn (y,acc) => (x,y)::acc) xys ys;
paulson@24287
   229
blanchet@37505
   230
fun consts_typs_of_term thy t =
blanchet@37537
   231
  Symtab.fold add_expand_pairs (get_consts_typs thy (SOME false) [t]) []
paulson@24287
   232
blanchet@37505
   233
fun pair_consts_typs_axiom theory_relevant thy axiom =
blanchet@37616
   234
  (axiom, axiom |> snd |> theory_const_prop_of theory_relevant
blanchet@37505
   235
                |> consts_typs_of_term thy)
paulson@24287
   236
blanchet@37505
   237
exception CONST_OR_FREE of unit
blanchet@37505
   238
blanchet@37505
   239
fun dest_Const_or_Free (Const x) = x
blanchet@37505
   240
  | dest_Const_or_Free (Free x) = x
blanchet@37505
   241
  | dest_Const_or_Free _ = raise CONST_OR_FREE ()
paulson@24287
   242
paulson@24287
   243
(*Look for definitions of the form f ?x1 ... ?xn = t, but not reversed.*)
wenzelm@32994
   244
fun defines thy thm gctypes =
paulson@24287
   245
    let val tm = prop_of thm
wenzelm@32960
   246
        fun defs lhs rhs =
paulson@24287
   247
            let val (rator,args) = strip_comb lhs
blanchet@37505
   248
                val ct = const_with_typ thy (dest_Const_or_Free rator)
haftmann@33037
   249
            in
haftmann@33037
   250
              forall is_Var args andalso uni_mem gctypes ct andalso
haftmann@33038
   251
                subset (op =) (Term.add_vars rhs [], Term.add_vars lhs [])
paulson@24287
   252
            end
blanchet@37505
   253
            handle CONST_OR_FREE () => false
blanchet@37505
   254
    in
blanchet@35963
   255
        case tm of
blanchet@37505
   256
          @{const Trueprop} $ (Const (@{const_name "op ="}, _) $ lhs $ rhs) =>
blanchet@37505
   257
            defs lhs rhs
blanchet@35963
   258
        | _ => false
paulson@24287
   259
    end;
paulson@24287
   260
blanchet@38085
   261
type annotated_thm = (string * thm) * (string * const_typ list) list
blanchet@37505
   262
paulson@24287
   263
(*For a reverse sort, putting the largest values first.*)
blanchet@37500
   264
fun compare_pairs ((_, w1), (_, w2)) = Real.compare (w2, w1)
paulson@24287
   265
blanchet@38085
   266
(* Limit the number of new facts, to prevent runaway acceptance. *)
blanchet@38085
   267
fun take_best max_new (newpairs : (annotated_thm * real) list) =
paulson@24287
   268
  let val nnew = length newpairs
paulson@24287
   269
  in
wenzelm@28477
   270
    if nnew <= max_new then (map #1 newpairs, [])
blanchet@37505
   271
    else
paulson@24287
   272
      let val cls = sort compare_pairs newpairs
wenzelm@28477
   273
          val accepted = List.take (cls, max_new)
paulson@24287
   274
      in
blanchet@37505
   275
        trace_msg (fn () => ("Number of candidates, " ^ Int.toString nnew ^
wenzelm@32960
   276
                       ", exceeds the limit of " ^ Int.toString (max_new)));
blanchet@35865
   277
        trace_msg (fn () => ("Effective pass mark: " ^ Real.toString (#2 (List.last accepted))));
blanchet@35865
   278
        trace_msg (fn () => "Actually passed: " ^
blanchet@37616
   279
          space_implode ", " (map (fst o fst o fst) accepted));
paulson@24287
   280
wenzelm@32960
   281
        (map #1 accepted, map #1 (List.drop (cls, max_new)))
paulson@24287
   282
      end
paulson@24287
   283
  end;
paulson@24287
   284
blanchet@38085
   285
fun relevant_facts ctxt relevance_convergence defs_relevant max_new
blanchet@38085
   286
                   ({add, del, ...} : relevance_override) const_tab =
blanchet@36182
   287
  let
blanchet@37344
   288
    val thy = ProofContext.theory_of ctxt
blanchet@37501
   289
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@37501
   290
    val del_thms = maps (ProofContext.get_fact ctxt) del
blanchet@37505
   291
    fun iter threshold rel_const_tab =
blanchet@36182
   292
      let
blanchet@36182
   293
        fun relevant ([], _) [] = []  (* Nothing added this iteration *)
blanchet@37344
   294
          | relevant (newpairs, rejects) [] =
blanchet@36182
   295
            let
blanchet@36182
   296
              val (newrels, more_rejects) = take_best max_new newpairs
blanchet@36182
   297
              val new_consts = maps #2 newrels
blanchet@37505
   298
              val rel_const_tab =
blanchet@37505
   299
                rel_const_tab |> fold add_const_type_to_table new_consts
blanchet@37344
   300
              val threshold =
blanchet@37344
   301
                threshold + (1.0 - threshold) / relevance_convergence
wenzelm@32960
   302
            in
blanchet@36182
   303
              trace_msg (fn () => "relevant this iteration: " ^
blanchet@36182
   304
                                  Int.toString (length newrels));
blanchet@37505
   305
              map #1 newrels @ iter threshold rel_const_tab
blanchet@37344
   306
                  (more_rejects @ rejects)
wenzelm@32960
   307
            end
blanchet@36182
   308
          | relevant (newrels, rejects)
blanchet@37616
   309
                     ((ax as (clsthm as (name, th), consts_typs)) :: axs) =
blanchet@35966
   310
            let
blanchet@37505
   311
              val weight =
blanchet@37616
   312
                if member Thm.eq_thm add_thms th then 1.0
blanchet@37616
   313
                else if member Thm.eq_thm del_thms th then 0.0
blanchet@38085
   314
                else formula_weight const_tab rel_const_tab consts_typs
wenzelm@32960
   315
            in
blanchet@37344
   316
              if weight >= threshold orelse
blanchet@37616
   317
                 (defs_relevant andalso defines thy th rel_const_tab) then
blanchet@37537
   318
                (trace_msg (fn () =>
blanchet@37616
   319
                     name ^ " passes: " ^ Real.toString weight
blanchet@37537
   320
                     (* ^ " consts: " ^ commas (map fst consts_typs) *));
blanchet@37537
   321
                 relevant ((ax, weight) :: newrels, rejects) axs)
blanchet@36182
   322
              else
blanchet@36182
   323
                relevant (newrels, ax :: rejects) axs
wenzelm@32960
   324
            end
blanchet@36182
   325
        in
blanchet@38085
   326
          trace_msg (fn () => "relevant_facts, current threshold: " ^
blanchet@37344
   327
                              Real.toString threshold);
blanchet@36182
   328
          relevant ([], [])
blanchet@36182
   329
        end
blanchet@36182
   330
  in iter end
blanchet@37505
   331
blanchet@36922
   332
fun relevance_filter ctxt relevance_threshold relevance_convergence
blanchet@36922
   333
                     defs_relevant max_new theory_relevant relevance_override
blanchet@37995
   334
                     thy axioms goal_ts =
blanchet@37538
   335
  if relevance_threshold > 1.0 then
blanchet@37538
   336
    []
blanchet@37538
   337
  else if relevance_threshold < 0.0 then
blanchet@37538
   338
    axioms
blanchet@37538
   339
  else
blanchet@35963
   340
    let
blanchet@37503
   341
      val const_tab = fold (count_axiom_consts theory_relevant thy) axioms
blanchet@37503
   342
                           Symtab.empty
blanchet@37995
   343
      val goal_const_tab = get_consts_typs thy (SOME true) goal_ts
blanchet@38090
   344
      val relevance_threshold = 0.8 * relevance_threshold (* FIXME *)
blanchet@35963
   345
      val _ =
blanchet@35963
   346
        trace_msg (fn () => "Initial constants: " ^
blanchet@37551
   347
                            commas (goal_const_tab
blanchet@37551
   348
                                    |> Symtab.dest
blanchet@37551
   349
                                    |> filter (curry (op <>) [] o snd)
blanchet@37551
   350
                                    |> map fst))
blanchet@35963
   351
      val relevant =
blanchet@38085
   352
        relevant_facts ctxt relevance_convergence defs_relevant max_new
blanchet@38085
   353
                       relevance_override const_tab relevance_threshold
blanchet@38085
   354
                       goal_const_tab
blanchet@38085
   355
                       (map (pair_consts_typs_axiom theory_relevant thy)
blanchet@38085
   356
                            axioms)
blanchet@35963
   357
    in
blanchet@35963
   358
      trace_msg (fn () => "Total relevant: " ^ Int.toString (length relevant));
blanchet@35963
   359
      relevant
blanchet@35963
   360
    end
paulson@24287
   361
paulson@24287
   362
(***************************************************************)
mengj@19768
   363
(* Retrieving and filtering lemmas                             *)
mengj@19768
   364
(***************************************************************)
mengj@19768
   365
paulson@33022
   366
(*** retrieve lemmas and filter them ***)
mengj@19768
   367
paulson@20757
   368
(*Reject theorems with names like "List.filter.filter_list_def" or
paulson@21690
   369
  "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
paulson@20757
   370
fun is_package_def a =
wenzelm@30364
   371
  let val names = Long_Name.explode a
paulson@21690
   372
  in
paulson@21690
   373
     length names > 2 andalso
paulson@21690
   374
     not (hd names = "local") andalso
paulson@21690
   375
     String.isSuffix "_def" a  orelse  String.isSuffix "_defs" a
paulson@21690
   376
  end;
paulson@20757
   377
blanchet@38085
   378
fun make_fact_table xs =
blanchet@37616
   379
  fold (Termtab.update o `(prop_of o snd)) xs Termtab.empty
blanchet@38085
   380
fun make_unique xs = Termtab.fold (cons o snd) (make_fact_table xs) []
mengj@19768
   381
blanchet@37626
   382
(* FIXME: put other record thms here, or declare as "no_atp" *)
blanchet@37626
   383
val multi_base_blacklist =
blanchet@37626
   384
  ["defs", "select_defs", "update_defs", "induct", "inducts", "split", "splits",
blanchet@37626
   385
   "split_asm", "cases", "ext_cases"]
blanchet@37626
   386
blanchet@37626
   387
val max_lambda_nesting = 3
blanchet@37626
   388
blanchet@37626
   389
fun term_has_too_many_lambdas max (t1 $ t2) =
blanchet@37626
   390
    exists (term_has_too_many_lambdas max) [t1, t2]
blanchet@37626
   391
  | term_has_too_many_lambdas max (Abs (_, _, t)) =
blanchet@37626
   392
    max = 0 orelse term_has_too_many_lambdas (max - 1) t
blanchet@37626
   393
  | term_has_too_many_lambdas _ _ = false
blanchet@37626
   394
blanchet@37626
   395
fun is_formula_type T = (T = HOLogic.boolT orelse T = propT)
blanchet@37626
   396
blanchet@37626
   397
(* Don't count nested lambdas at the level of formulas, since they are
blanchet@37626
   398
   quantifiers. *)
blanchet@37626
   399
fun formula_has_too_many_lambdas Ts (Abs (_, T, t)) =
blanchet@37626
   400
    formula_has_too_many_lambdas (T :: Ts) t
blanchet@37626
   401
  | formula_has_too_many_lambdas Ts t =
blanchet@37626
   402
    if is_formula_type (fastype_of1 (Ts, t)) then
blanchet@37626
   403
      exists (formula_has_too_many_lambdas Ts) (#2 (strip_comb t))
blanchet@37626
   404
    else
blanchet@37626
   405
      term_has_too_many_lambdas max_lambda_nesting t
blanchet@37626
   406
blanchet@37626
   407
(* The max apply depth of any "metis" call in "Metis_Examples" (on 31-10-2007)
blanchet@37626
   408
   was 11. *)
blanchet@37626
   409
val max_apply_depth = 15
blanchet@37626
   410
blanchet@37626
   411
fun apply_depth (f $ t) = Int.max (apply_depth f, apply_depth t + 1)
blanchet@37626
   412
  | apply_depth (Abs (_, _, t)) = apply_depth t
blanchet@37626
   413
  | apply_depth _ = 0
blanchet@37626
   414
blanchet@37626
   415
fun is_formula_too_complex t =
blanchet@38085
   416
  apply_depth t > max_apply_depth orelse formula_has_too_many_lambdas [] t
blanchet@37626
   417
blanchet@37543
   418
val exists_sledgehammer_const =
blanchet@37626
   419
  exists_Const (fn (s, _) => String.isPrefix sledgehammer_prefix s)
blanchet@37626
   420
blanchet@37626
   421
fun is_strange_thm th =
blanchet@37626
   422
  case head_of (concl_of th) of
blanchet@37626
   423
      Const (a, _) => (a <> @{const_name Trueprop} andalso
blanchet@37626
   424
                       a <> @{const_name "=="})
blanchet@37626
   425
    | _ => false
blanchet@37626
   426
blanchet@37626
   427
val type_has_top_sort =
blanchet@37626
   428
  exists_subtype (fn TFree (_, []) => true | TVar (_, []) => true | _ => false)
blanchet@37626
   429
blanchet@37626
   430
fun is_theorem_bad_for_atps thm =
blanchet@37626
   431
  let val t = prop_of thm in
blanchet@37626
   432
    is_formula_too_complex t orelse exists_type type_has_top_sort t orelse
blanchet@37626
   433
    exists_sledgehammer_const t orelse is_strange_thm thm
blanchet@37626
   434
  end
blanchet@37543
   435
blanchet@37580
   436
fun all_name_thms_pairs ctxt chained_ths =
paulson@22382
   437
  let
wenzelm@26675
   438
    val global_facts = PureThy.facts_of (ProofContext.theory_of ctxt);
wenzelm@26278
   439
    val local_facts = ProofContext.facts_of ctxt;
wenzelm@33641
   440
    val full_space =
wenzelm@33641
   441
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts);
wenzelm@33641
   442
wenzelm@33641
   443
    fun valid_facts facts =
wenzelm@33641
   444
      (facts, []) |-> Facts.fold_static (fn (name, ths0) =>
blanchet@37399
   445
        if Facts.is_concealed facts name orelse
blanchet@37399
   446
           (respect_no_atp andalso is_package_def name) orelse
blanchet@37626
   447
           member (op =) multi_base_blacklist (Long_Name.base_name name) then
blanchet@37399
   448
          I
blanchet@37399
   449
        else
blanchet@37399
   450
          let
blanchet@37399
   451
            fun check_thms a =
blanchet@37399
   452
              (case try (ProofContext.get_thms ctxt) a of
blanchet@37399
   453
                NONE => false
blanchet@37399
   454
              | SOME ths1 => Thm.eq_thms (ths0, ths1));
wenzelm@33641
   455
blanchet@37399
   456
            val name1 = Facts.extern facts name;
blanchet@37399
   457
            val name2 = Name_Space.extern full_space name;
blanchet@37626
   458
            val ths = filter_out is_theorem_bad_for_atps ths0
blanchet@37399
   459
          in
blanchet@37399
   460
            case find_first check_thms [name1, name2, name] of
blanchet@37399
   461
              NONE => I
blanchet@37399
   462
            | SOME name' =>
blanchet@37399
   463
              cons (name' |> forall (member Thm.eq_thm chained_ths) ths
blanchet@37399
   464
                             ? prefix chained_prefix, ths)
blanchet@37399
   465
          end)
wenzelm@26675
   466
  in valid_facts global_facts @ valid_facts local_facts end;
paulson@21224
   467
wenzelm@33309
   468
fun multi_name a th (n, pairs) =
wenzelm@33309
   469
  (n + 1, (a ^ "(" ^ Int.toString n ^ ")", th) :: pairs);
paulson@21224
   470
blanchet@37498
   471
fun add_names (_, []) pairs = pairs
blanchet@37399
   472
  | add_names (a, [th]) pairs = (a, th) :: pairs
blanchet@37399
   473
  | add_names (a, ths) pairs = #2 (fold (multi_name a) ths (1, pairs))
paulson@21224
   474
paulson@21290
   475
fun is_multi (a, ths) = length ths > 1 orelse String.isSuffix ".axioms" a;
paulson@21290
   476
blanchet@36550
   477
(* The single-name theorems go after the multiple-name ones, so that single
blanchet@36550
   478
   names are preferred when both are available. *)
blanchet@37580
   479
fun name_thm_pairs ctxt respect_no_atp name_thms_pairs =
wenzelm@33309
   480
  let
blanchet@37344
   481
    val (mults, singles) = List.partition is_multi name_thms_pairs
blanchet@37399
   482
    val ps = [] |> fold add_names singles |> fold add_names mults
blanchet@36060
   483
  in ps |> respect_no_atp ? filter_out (No_ATPs.member ctxt o snd) end;
paulson@21224
   484
blanchet@37344
   485
fun is_named ("", th) =
blanchet@37344
   486
    (warning ("No name for theorem " ^
blanchet@37344
   487
              Display.string_of_thm_without_context th); false)
blanchet@37344
   488
  | is_named _ = true
blanchet@37344
   489
fun checked_name_thm_pairs respect_no_atp ctxt =
blanchet@37580
   490
  name_thm_pairs ctxt respect_no_atp
blanchet@37344
   491
  #> tap (fn ps => trace_msg
blanchet@37344
   492
                        (fn () => ("Considering " ^ Int.toString (length ps) ^
blanchet@37344
   493
                                   " theorems")))
blanchet@37344
   494
  #> filter is_named
paulson@19894
   495
paulson@21290
   496
(***************************************************************)
mengj@19194
   497
(* ATP invocation methods setup                                *)
mengj@19194
   498
(***************************************************************)
mengj@19194
   499
blanchet@38085
   500
(**** Predicates to detect unwanted facts (prolific or likely to cause
blanchet@37347
   501
      unsoundness) ****)
paulson@21470
   502
paulson@21470
   503
(** Too general means, positive equality literal with a variable X as one operand,
paulson@21470
   504
  when X does not occur properly in the other operand. This rules out clearly
blanchet@38085
   505
  inconsistent facts such as V = a | V = b, though it by no means guarantees
blanchet@38085
   506
  soundness. **)
wenzelm@21588
   507
blanchet@37348
   508
fun var_occurs_in_term ix =
blanchet@37348
   509
  let
blanchet@37348
   510
    fun aux (Var (jx, _)) = (ix = jx)
blanchet@37348
   511
      | aux (t1 $ t2) = aux t1 orelse aux t2
blanchet@37348
   512
      | aux (Abs (_, _, t)) = aux t
blanchet@37348
   513
      | aux _ = false
blanchet@37348
   514
  in aux end
paulson@21470
   515
blanchet@37348
   516
fun is_record_type T = not (null (Record.dest_recTs T))
paulson@21470
   517
paulson@21470
   518
(*Unwanted equalities include
paulson@21470
   519
  (1) those between a variable that does not properly occur in the second operand,
paulson@21470
   520
  (2) those between a variable and a record, since these seem to be prolific "cases" thms
blanchet@38085
   521
  (* FIXME: still a problem? *)
wenzelm@21588
   522
*)
blanchet@37348
   523
fun too_general_eqterms (Var (ix,T), t) =
blanchet@37348
   524
    not (var_occurs_in_term ix t) orelse is_record_type T
paulson@21470
   525
  | too_general_eqterms _ = false;
paulson@21470
   526
blanchet@35865
   527
fun too_general_equality (Const (@{const_name "op ="}, _) $ x $ y) =
paulson@21470
   528
      too_general_eqterms (x,y) orelse too_general_eqterms(y,x)
paulson@21470
   529
  | too_general_equality _ = false;
paulson@21470
   530
wenzelm@29267
   531
fun has_typed_var tycons = exists_subterm
wenzelm@29267
   532
  (fn Var (_, Type (a, _)) => member (op =) tycons a | _ => false);
paulson@21431
   533
blanchet@38085
   534
(* Facts are forbidden to contain variables of these types. The typical reason
blanchet@37347
   535
   is that they lead to unsoundness. Note that "unit" satisfies numerous
blanchet@38085
   536
   equations like "?x = ()". The resulting clauses will have no type constraint,
blanchet@37347
   537
   yielding false proofs. Even "bool" leads to many unsound proofs, though only
blanchet@37347
   538
   for higher-order problems. *)
blanchet@37347
   539
val dangerous_types = [@{type_name unit}, @{type_name bool}];
paulson@22217
   540
blanchet@38085
   541
(* Facts containing variables of type "unit" or "bool" or of the form
blanchet@37347
   542
   "?x = A | ?x = B | ?x = C" are likely to lead to unsound proofs if types are
blanchet@37347
   543
   omitted. *)
blanchet@37347
   544
fun is_dangerous_term _ @{prop True} = true
blanchet@37347
   545
  | is_dangerous_term full_types t =
blanchet@37505
   546
    not full_types andalso
blanchet@37347
   547
    (has_typed_var dangerous_types t orelse
blanchet@37347
   548
     forall too_general_equality (HOLogic.disjuncts (strip_Trueprop t)))
paulson@21470
   549
blanchet@37580
   550
fun relevant_facts full_types relevance_threshold relevance_convergence
blanchet@37580
   551
                   defs_relevant max_new theory_relevant
blanchet@37347
   552
                   (relevance_override as {add, del, only})
blanchet@37995
   553
                   (ctxt, (chained_ths, _)) hyp_ts concl_t =
blanchet@37538
   554
  let
blanchet@37538
   555
    val thy = ProofContext.theory_of ctxt
blanchet@37538
   556
    val add_thms = maps (ProofContext.get_fact ctxt) add
blanchet@37538
   557
    val has_override = not (null add) orelse not (null del)
blanchet@37995
   558
(*###
blanchet@37995
   559
    val is_FO = forall Meson.is_fol_term thy (concl_t :: hyp_ts)
blanchet@37995
   560
*)
blanchet@37538
   561
    val axioms =
blanchet@37538
   562
      checked_name_thm_pairs (respect_no_atp andalso not only) ctxt
blanchet@37538
   563
          (map (name_thms_pair_from_ref ctxt chained_ths) add @
blanchet@37580
   564
           (if only then [] else all_name_thms_pairs ctxt chained_ths))
blanchet@37538
   565
      |> not has_override ? make_unique
blanchet@37616
   566
      |> filter (fn (_, th) =>
blanchet@37616
   567
                    member Thm.eq_thm add_thms th orelse
blanchet@37616
   568
                    ((* ### FIXME: keep? (not is_FO orelse is_quasi_fol_theorem thy th) andalso*)
blanchet@37616
   569
                     not (is_dangerous_term full_types (prop_of th))))
blanchet@37538
   570
  in
blanchet@37538
   571
    relevance_filter ctxt relevance_threshold relevance_convergence
blanchet@37538
   572
                     defs_relevant max_new theory_relevant relevance_override
blanchet@37995
   573
                     thy axioms (concl_t :: hyp_ts)
blanchet@37538
   574
    |> has_override ? make_unique
blanchet@37616
   575
    |> sort_wrt fst
blanchet@37538
   576
  end
immler@30536
   577
paulson@15347
   578
end;