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