src/HOL/Tools/Sledgehammer/sledgehammer_fact_preprocessor.ML
author blanchet
Mon Jun 07 10:37:06 2010 +0200 (2010-06-07)
changeset 37349 3d7058e24b7a
parent 37348 3ad1bfd2de46
child 37399 34f080a12063
permissions -rw-r--r--
cosmetics
blanchet@35826
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_fact_preprocessor.ML
wenzelm@33311
     2
    Author:     Jia Meng, Cambridge University Computer Laboratory
blanchet@36393
     3
    Author:     Jasmin Blanchette, TU Muenchen
paulson@15347
     4
wenzelm@20461
     5
Transformation of axiom rules (elim/intro/etc) into CNF forms.
paulson@15347
     6
*)
paulson@15347
     7
blanchet@35826
     8
signature SLEDGEHAMMER_FACT_PREPROCESSOR =
wenzelm@21505
     9
sig
blanchet@37171
    10
  val chained_prefix: string
wenzelm@32955
    11
  val trace: bool Unsynchronized.ref
wenzelm@32955
    12
  val trace_msg: (unit -> string) -> unit
blanchet@35865
    13
  val skolem_prefix: string
blanchet@36492
    14
  val skolem_infix: string
wenzelm@27179
    15
  val cnf_axiom: theory -> thm -> thm list
wenzelm@27184
    16
  val multi_base_blacklist: string list
blanchet@37348
    17
  val is_theorem_bad_for_atps: thm -> bool
wenzelm@35568
    18
  val type_has_topsort: typ -> bool
blanchet@37348
    19
  val cnf_rules_pairs:
blanchet@37348
    20
    theory -> (string * thm) list -> (thm * (string * int)) list
blanchet@37348
    21
  val use_skolem_cache: bool Unsynchronized.ref
blanchet@37348
    22
    (* for emergency use where the Skolem cache causes problems *)
blanchet@36478
    23
  val strip_subgoal : thm -> int -> (string * typ) list * term list * term
blanchet@36398
    24
  val neg_clausify: thm -> thm list
blanchet@36398
    25
  val neg_conjecture_clauses:
blanchet@36398
    26
    Proof.context -> thm -> int -> thm list list * (string * typ) list
blanchet@36394
    27
  val neg_clausify_tac: Proof.context -> int -> tactic
wenzelm@24669
    28
  val setup: theory -> theory
wenzelm@21505
    29
end;
mengj@19196
    30
blanchet@35826
    31
structure Sledgehammer_Fact_Preprocessor : SLEDGEHAMMER_FACT_PREPROCESSOR =
paulson@15997
    32
struct
paulson@15347
    33
blanchet@35865
    34
open Sledgehammer_FOL_Clause
blanchet@35865
    35
blanchet@37171
    36
(* Used to label theorems chained into the goal. *)
blanchet@37171
    37
val chained_prefix = "Sledgehammer.chained_"
blanchet@37171
    38
wenzelm@32955
    39
val trace = Unsynchronized.ref false;
blanchet@35865
    40
fun trace_msg msg = if !trace then tracing (msg ()) else ();
blanchet@35865
    41
blanchet@35865
    42
val skolem_prefix = "sko_"
blanchet@36492
    43
val skolem_infix = "$"
wenzelm@32955
    44
wenzelm@33832
    45
fun freeze_thm th = #1 (Drule.legacy_freeze_thaw th);
paulson@20863
    46
wenzelm@35568
    47
val type_has_topsort = Term.exists_subtype
wenzelm@35568
    48
  (fn TFree (_, []) => true
wenzelm@35568
    49
    | TVar (_, []) => true
wenzelm@35568
    50
    | _ => false);
wenzelm@27184
    51
wenzelm@28544
    52
paulson@15997
    53
(**** Transformation of Elimination Rules into First-Order Formulas****)
paulson@15347
    54
wenzelm@29064
    55
val cfalse = cterm_of @{theory HOL} HOLogic.false_const;
wenzelm@29064
    56
val ctp_false = cterm_of @{theory HOL} (HOLogic.mk_Trueprop HOLogic.false_const);
wenzelm@20461
    57
paulson@21430
    58
(*Converts an elim-rule into an equivalent theorem that does not have the
paulson@21430
    59
  predicate variable.  Leaves other theorems unchanged.  We simply instantiate the
paulson@21430
    60
  conclusion variable to False.*)
paulson@16009
    61
fun transform_elim th =
paulson@21430
    62
  case concl_of th of    (*conclusion variable*)
blanchet@35963
    63
       @{const Trueprop} $ (v as Var (_, @{typ bool})) =>
wenzelm@29064
    64
           Thm.instantiate ([], [(cterm_of @{theory HOL} v, cfalse)]) th
blanchet@35963
    65
    | v as Var(_, @{typ prop}) =>
wenzelm@29064
    66
           Thm.instantiate ([], [(cterm_of @{theory HOL} v, ctp_false)]) th
paulson@21430
    67
    | _ => th;
paulson@15997
    68
paulson@24742
    69
(*To enforce single-threading*)
paulson@24742
    70
exception Clausify_failure of theory;
wenzelm@20461
    71
wenzelm@28544
    72
paulson@16009
    73
(**** SKOLEMIZATION BY INFERENCE (lcp) ****)
paulson@16009
    74
blanchet@36492
    75
(*Keep the full complexity of the original name*)
blanchet@36492
    76
fun flatten_name s = space_implode "_X" (Long_Name.explode s);
blanchet@36492
    77
blanchet@36492
    78
fun skolem_name thm_name nref var_name =
blanchet@36492
    79
  skolem_prefix ^ thm_name ^ "_" ^ Int.toString (Unsynchronized.inc nref) ^
blanchet@36492
    80
  skolem_infix ^ (if var_name = "" then "g" else flatten_name var_name)
blanchet@36492
    81
paulson@24742
    82
fun rhs_extra_types lhsT rhs =
paulson@24742
    83
  let val lhs_vars = Term.add_tfreesT lhsT []
paulson@24742
    84
      fun add_new_TFrees (TFree v) =
wenzelm@24821
    85
            if member (op =) lhs_vars v then I else insert (op =) (TFree v)
wenzelm@24821
    86
        | add_new_TFrees _ = I
paulson@24742
    87
      val rhs_consts = fold_aterms (fn Const c => insert (op =) c | _ => I) rhs []
paulson@24742
    88
  in fold (#2 #> Term.fold_atyps add_new_TFrees) rhs_consts [] end;
paulson@24742
    89
blanchet@37348
    90
(* Traverse a theorem, declaring Skolem function definitions. String "s" is the
blanchet@37348
    91
   suggested prefix for the Skolem constants. *)
blanchet@37349
    92
fun declare_skolem_funs s th thy =
wenzelm@27174
    93
  let
wenzelm@33222
    94
    val nref = Unsynchronized.ref 0    (* FIXME ??? *)
blanchet@36492
    95
    fun dec_sko (Const (@{const_name Ex}, _) $ (xtp as Abs (s', T, p))) (axs, thy) =
wenzelm@27174
    96
          (*Existential: declare a Skolem function, then insert into body and continue*)
wenzelm@27174
    97
          let
blanchet@36492
    98
            val cname = skolem_name s nref s'
wenzelm@29265
    99
            val args0 = OldTerm.term_frees xtp  (*get the formal parameter list*)
wenzelm@27174
   100
            val Ts = map type_of args0
wenzelm@27174
   101
            val extraTs = rhs_extra_types (Ts ---> T) xtp
wenzelm@27174
   102
            val argsx = map (fn T => Free (gensym "vsk", T)) extraTs
wenzelm@27174
   103
            val args = argsx @ args0
wenzelm@27174
   104
            val cT = extraTs ---> Ts ---> T
wenzelm@27174
   105
            val rhs = list_abs_free (map dest_Free args, HOLogic.choice_const T $ xtp)
wenzelm@27174
   106
                    (*Forms a lambda-abstraction over the formal parameters*)
blanchet@37349
   107
            val (c, thy) =
wenzelm@33173
   108
              Sign.declare_const ((Binding.conceal (Binding.name cname), cT), NoSyn) thy
wenzelm@27174
   109
            val cdef = cname ^ "_def"
blanchet@37349
   110
            val ((_, ax), thy) =
blanchet@37349
   111
              Thm.add_def true false (Binding.name cdef, Logic.mk_equals (c, rhs)) thy
wenzelm@35984
   112
            val ax' = Drule.export_without_context ax
blanchet@37349
   113
          in dec_sko (subst_bound (list_comb (c, args), p)) (ax' :: axs, thy) end
blanchet@35963
   114
      | dec_sko (Const (@{const_name All}, _) $ (Abs (a, T, p))) thx =
wenzelm@27174
   115
          (*Universal quant: insert a free variable into body and continue*)
wenzelm@29270
   116
          let val fname = Name.variant (OldTerm.add_term_names (p, [])) a
wenzelm@27174
   117
          in dec_sko (subst_bound (Free (fname, T), p)) thx end
blanchet@35963
   118
      | dec_sko (@{const "op &"} $ p $ q) thx = dec_sko q (dec_sko p thx)
blanchet@35963
   119
      | dec_sko (@{const "op |"} $ p $ q) thx = dec_sko q (dec_sko p thx)
blanchet@35963
   120
      | dec_sko (@{const Trueprop} $ p) thx = dec_sko p thx
blanchet@37349
   121
      | dec_sko t thx = thx
blanchet@37349
   122
  in dec_sko (prop_of th) ([], thy) end
paulson@18141
   123
paulson@18141
   124
(*Traverse a theorem, accumulating Skolem function definitions.*)
blanchet@37348
   125
fun assume_skolem_funs s th =
wenzelm@33222
   126
  let val sko_count = Unsynchronized.ref 0   (* FIXME ??? *)
blanchet@36492
   127
      fun dec_sko (Const (@{const_name Ex}, _) $ (xtp as Abs (s', T, p))) defs =
wenzelm@20461
   128
            (*Existential: declare a Skolem function, then insert into body and continue*)
wenzelm@20461
   129
            let val skos = map (#1 o Logic.dest_equals) defs  (*existing sko fns*)
haftmann@33040
   130
                val args = subtract (op =) skos (OldTerm.term_frees xtp) (*the formal parameters*)
wenzelm@20461
   131
                val Ts = map type_of args
wenzelm@20461
   132
                val cT = Ts ---> T
blanchet@36492
   133
                val id = skolem_name s sko_count s'
paulson@22731
   134
                val c = Free (id, cT)
wenzelm@20461
   135
                val rhs = list_abs_free (map dest_Free args,
wenzelm@20461
   136
                                         HOLogic.choice_const T $ xtp)
wenzelm@20461
   137
                      (*Forms a lambda-abstraction over the formal parameters*)
wenzelm@27330
   138
                val def = Logic.mk_equals (c, rhs)
blanchet@37349
   139
            in dec_sko (subst_bound (list_comb(c,args), p)) (def :: defs) end
blanchet@35963
   140
        | dec_sko (Const (@{const_name All},_) $ Abs (a, T, p)) defs =
wenzelm@20461
   141
            (*Universal quant: insert a free variable into body and continue*)
wenzelm@29270
   142
            let val fname = Name.variant (OldTerm.add_term_names (p,[])) a
wenzelm@20461
   143
            in dec_sko (subst_bound (Free(fname,T), p)) defs end
blanchet@35963
   144
        | dec_sko (@{const "op &"} $ p $ q) defs = dec_sko q (dec_sko p defs)
blanchet@35963
   145
        | dec_sko (@{const "op |"} $ p $ q) defs = dec_sko q (dec_sko p defs)
blanchet@35963
   146
        | dec_sko (@{const Trueprop} $ p) defs = dec_sko p defs
wenzelm@20461
   147
        | dec_sko t defs = defs (*Do nothing otherwise*)
paulson@20419
   148
  in  dec_sko (prop_of th) []  end;
paulson@20419
   149
paulson@20419
   150
paulson@24827
   151
(**** REPLACING ABSTRACTIONS BY COMBINATORS ****)
paulson@20419
   152
paulson@20419
   153
(*Returns the vars of a theorem*)
paulson@20419
   154
fun vars_of_thm th =
wenzelm@22691
   155
  map (Thm.cterm_of (theory_of_thm th) o Var) (Thm.fold_terms Term.add_vars th []);
paulson@20419
   156
paulson@20419
   157
(*Make a version of fun_cong with a given variable name*)
paulson@20419
   158
local
paulson@20419
   159
    val fun_cong' = fun_cong RS asm_rl; (*renumber f, g to prevent clashes with (a,0)*)
paulson@20419
   160
    val cx = hd (vars_of_thm fun_cong');
paulson@20419
   161
    val ty = typ_of (ctyp_of_term cx);
paulson@20445
   162
    val thy = theory_of_thm fun_cong;
paulson@20419
   163
    fun mkvar a = cterm_of thy (Var((a,0),ty));
paulson@20419
   164
in
paulson@20419
   165
fun xfun_cong x = Thm.instantiate ([], [(cx, mkvar x)]) fun_cong'
paulson@20419
   166
end;
paulson@20419
   167
paulson@20863
   168
(*Removes the lambdas from an equation of the form t = (%x. u).  A non-negative n,
paulson@20863
   169
  serves as an upper bound on how many to remove.*)
paulson@20863
   170
fun strip_lambdas 0 th = th
wenzelm@24669
   171
  | strip_lambdas n th =
paulson@20863
   172
      case prop_of th of
blanchet@35963
   173
          _ $ (Const (@{const_name "op ="}, _) $ _ $ Abs (x, _, _)) =>
wenzelm@24669
   174
              strip_lambdas (n-1) (freeze_thm (th RS xfun_cong x))
wenzelm@24669
   175
        | _ => th;
paulson@20419
   176
wenzelm@24669
   177
val lambda_free = not o Term.has_abs;
wenzelm@20461
   178
wenzelm@32010
   179
val [f_B,g_B] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_B}));
wenzelm@32010
   180
val [g_C,f_C] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_C}));
wenzelm@32010
   181
val [f_S,g_S] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_S}));
paulson@20863
   182
paulson@24827
   183
(*FIXME: requires more use of cterm constructors*)
paulson@24827
   184
fun abstract ct =
wenzelm@28544
   185
  let
wenzelm@28544
   186
      val thy = theory_of_cterm ct
paulson@25256
   187
      val Abs(x,_,body) = term_of ct
blanchet@35963
   188
      val Type(@{type_name fun}, [xT,bodyT]) = typ_of (ctyp_of_term ct)
paulson@24827
   189
      val cxT = ctyp_of thy xT and cbodyT = ctyp_of thy bodyT
wenzelm@27184
   190
      fun makeK() = instantiate' [SOME cxT, SOME cbodyT] [SOME (cterm_of thy body)] @{thm abs_K}
paulson@24827
   191
  in
paulson@24827
   192
      case body of
paulson@24827
   193
          Const _ => makeK()
paulson@24827
   194
        | Free _ => makeK()
paulson@24827
   195
        | Var _ => makeK()  (*though Var isn't expected*)
wenzelm@27184
   196
        | Bound 0 => instantiate' [SOME cxT] [] @{thm abs_I} (*identity: I*)
paulson@24827
   197
        | rator$rand =>
wenzelm@27184
   198
            if loose_bvar1 (rator,0) then (*C or S*)
wenzelm@27179
   199
               if loose_bvar1 (rand,0) then (*S*)
wenzelm@27179
   200
                 let val crator = cterm_of thy (Abs(x,xT,rator))
wenzelm@27179
   201
                     val crand = cterm_of thy (Abs(x,xT,rand))
wenzelm@27184
   202
                     val abs_S' = cterm_instantiate [(f_S,crator),(g_S,crand)] @{thm abs_S}
wenzelm@27184
   203
                     val (_,rhs) = Thm.dest_equals (cprop_of abs_S')
wenzelm@27179
   204
                 in
wenzelm@27179
   205
                   Thm.transitive abs_S' (Conv.binop_conv abstract rhs)
wenzelm@27179
   206
                 end
wenzelm@27179
   207
               else (*C*)
wenzelm@27179
   208
                 let val crator = cterm_of thy (Abs(x,xT,rator))
wenzelm@27184
   209
                     val abs_C' = cterm_instantiate [(f_C,crator),(g_C,cterm_of thy rand)] @{thm abs_C}
wenzelm@27184
   210
                     val (_,rhs) = Thm.dest_equals (cprop_of abs_C')
wenzelm@27179
   211
                 in
wenzelm@27179
   212
                   Thm.transitive abs_C' (Conv.fun_conv (Conv.arg_conv abstract) rhs)
wenzelm@27179
   213
                 end
wenzelm@27184
   214
            else if loose_bvar1 (rand,0) then (*B or eta*)
wenzelm@36945
   215
               if rand = Bound 0 then Thm.eta_conversion ct
wenzelm@27179
   216
               else (*B*)
wenzelm@27179
   217
                 let val crand = cterm_of thy (Abs(x,xT,rand))
wenzelm@27179
   218
                     val crator = cterm_of thy rator
wenzelm@27184
   219
                     val abs_B' = cterm_instantiate [(f_B,crator),(g_B,crand)] @{thm abs_B}
wenzelm@27184
   220
                     val (_,rhs) = Thm.dest_equals (cprop_of abs_B')
blanchet@37349
   221
                 in Thm.transitive abs_B' (Conv.arg_conv abstract rhs) end
wenzelm@27179
   222
            else makeK()
blanchet@37349
   223
        | _ => raise Fail "abstract: Bad term"
paulson@24827
   224
  end;
paulson@20863
   225
blanchet@37349
   226
(* Traverse a theorem, remplacing lambda-abstractions with combinators. *)
blanchet@37349
   227
fun do_introduce_combinators ct =
blanchet@37349
   228
  if lambda_free (term_of ct) then
blanchet@37349
   229
    Thm.reflexive ct
blanchet@37349
   230
  else case term_of ct of
blanchet@37349
   231
    Abs _ =>
blanchet@37349
   232
    let
blanchet@37349
   233
      val (cv, cta) = Thm.dest_abs NONE ct
blanchet@37349
   234
      val (v, _) = dest_Free (term_of cv)
blanchet@37349
   235
      val u_th = do_introduce_combinators cta
blanchet@37349
   236
      val cu = Thm.rhs_of u_th
blanchet@37349
   237
      val comb_eq = abstract (Thm.cabs cv cu)
blanchet@37349
   238
    in Thm.transitive (Thm.abstract_rule v cv u_th) comb_eq end
blanchet@37349
   239
  | _ $ _ =>
blanchet@37349
   240
    let val (ct1, ct2) = Thm.dest_comb ct in
blanchet@37349
   241
        Thm.combination (do_introduce_combinators ct1)
blanchet@37349
   242
                        (do_introduce_combinators ct2)
blanchet@37349
   243
    end
blanchet@37349
   244
blanchet@37349
   245
fun introduce_combinators th =
blanchet@37349
   246
  if lambda_free (prop_of th) then
blanchet@37349
   247
    th
paulson@24827
   248
  else
blanchet@37349
   249
    let
blanchet@37349
   250
      val th = Drule.eta_contraction_rule th
blanchet@37349
   251
      val eqth = do_introduce_combinators (cprop_of th)
blanchet@37349
   252
    in Thm.equal_elim eqth th end
blanchet@37349
   253
    handle THM (msg, _, _) =>
blanchet@37349
   254
           (warning ("Error in the combinator translation of " ^
blanchet@37349
   255
                     Display.string_of_thm_without_context th ^
blanchet@37349
   256
                     "\nException message: " ^ msg ^ ".");
blanchet@37349
   257
            (* A type variable of sort "{}" will make abstraction fail. *)
blanchet@37349
   258
            TrueI)
paulson@16009
   259
paulson@16009
   260
(*cterms are used throughout for efficiency*)
wenzelm@29064
   261
val cTrueprop = Thm.cterm_of @{theory HOL} HOLogic.Trueprop;
paulson@16009
   262
paulson@16009
   263
(*cterm version of mk_cTrueprop*)
paulson@16009
   264
fun c_mkTrueprop A = Thm.capply cTrueprop A;
paulson@16009
   265
paulson@16009
   266
(*Given an abstraction over n variables, replace the bound variables by free
paulson@16009
   267
  ones. Return the body, along with the list of free variables.*)
wenzelm@20461
   268
fun c_variant_abs_multi (ct0, vars) =
paulson@16009
   269
      let val (cv,ct) = Thm.dest_abs NONE ct0
paulson@16009
   270
      in  c_variant_abs_multi (ct, cv::vars)  end
paulson@16009
   271
      handle CTERM _ => (ct0, rev vars);
paulson@16009
   272
wenzelm@20461
   273
(*Given the definition of a Skolem function, return a theorem to replace
wenzelm@20461
   274
  an existential formula by a use of that function.
paulson@18141
   275
   Example: "EX x. x : A & x ~: B ==> sko A B : A & sko A B ~: B"  [.] *)
wenzelm@20461
   276
fun skolem_of_def def =
wenzelm@22902
   277
  let val (c,rhs) = Thm.dest_equals (cprop_of (freeze_thm def))
paulson@16009
   278
      val (ch, frees) = c_variant_abs_multi (rhs, [])
paulson@18141
   279
      val (chilbert,cabs) = Thm.dest_comb ch
wenzelm@26627
   280
      val thy = Thm.theory_of_cterm chilbert
wenzelm@26627
   281
      val t = Thm.term_of chilbert
blanchet@35963
   282
      val T = case t of
blanchet@35963
   283
                Const (@{const_name Eps}, Type (@{type_name fun},[_,T])) => T
blanchet@35963
   284
              | _ => raise THM ("skolem_of_def: expected Eps", 0, [def])
wenzelm@22596
   285
      val cex = Thm.cterm_of thy (HOLogic.exists_const T)
paulson@16009
   286
      val ex_tm = c_mkTrueprop (Thm.capply cex cabs)
paulson@16009
   287
      and conc =  c_mkTrueprop (Drule.beta_conv cabs (Drule.list_comb(c,frees)));
haftmann@31454
   288
      fun tacf [prem] = rewrite_goals_tac [def] THEN rtac (prem RS @{thm someI_ex}) 1
wenzelm@23352
   289
  in  Goal.prove_internal [ex_tm] conc tacf
paulson@18141
   290
       |> forall_intr_list frees
wenzelm@26653
   291
       |> Thm.forall_elim_vars 0  (*Introduce Vars, but don't discharge defs.*)
wenzelm@35845
   292
       |> Thm.varifyT_global
paulson@18141
   293
  end;
paulson@16009
   294
paulson@24742
   295
paulson@20863
   296
(*Converts an Isabelle theorem (intro, elim or simp format, even higher-order) into NNF.*)
paulson@24937
   297
fun to_nnf th ctxt0 =
wenzelm@27179
   298
  let val th1 = th |> transform_elim |> zero_var_indexes
wenzelm@32262
   299
      val ((_, [th2]), ctxt) = Variable.import true [th1] ctxt0
wenzelm@32262
   300
      val th3 = th2
wenzelm@35625
   301
        |> Conv.fconv_rule Object_Logic.atomize
wenzelm@32262
   302
        |> Meson.make_nnf ctxt |> strip_lambdas ~1
paulson@24937
   303
  in  (th3, ctxt)  end;
paulson@16009
   304
paulson@18141
   305
(*Generate Skolem functions for a theorem supplied in nnf*)
paulson@24937
   306
fun assume_skolem_of_def s th =
blanchet@37349
   307
  map (skolem_of_def o Thm.assume o cterm_of (theory_of_thm th))
blanchet@37348
   308
      (assume_skolem_funs s th)
paulson@18141
   309
paulson@25007
   310
blanchet@37349
   311
(*** Blacklisting (more in "Sledgehammer_Fact_Filter") ***)
paulson@25007
   312
blanchet@37348
   313
val max_lambda_nesting = 3
wenzelm@27184
   314
blanchet@37348
   315
fun term_has_too_many_lambdas max (t1 $ t2) =
blanchet@37348
   316
    exists (term_has_too_many_lambdas max) [t1, t2]
blanchet@37348
   317
  | term_has_too_many_lambdas max (Abs (_, _, t)) =
blanchet@37348
   318
    max = 0 orelse term_has_too_many_lambdas (max - 1) t
blanchet@37348
   319
  | term_has_too_many_lambdas _ _ = false
paulson@25007
   320
blanchet@37348
   321
fun is_formula_type T = (T = HOLogic.boolT orelse T = propT)
paulson@25007
   322
blanchet@37348
   323
(* Don't count nested lambdas at the level of formulas, since they are
blanchet@37348
   324
   quantifiers. *)
blanchet@37348
   325
fun formula_has_too_many_lambdas Ts (Abs (_, T, t)) =
blanchet@37348
   326
    formula_has_too_many_lambdas (T :: Ts) t
blanchet@37348
   327
  | formula_has_too_many_lambdas Ts t =
blanchet@37348
   328
    if is_formula_type (fastype_of1 (Ts, t)) then
blanchet@37348
   329
      exists (formula_has_too_many_lambdas Ts) (#2 (strip_comb t))
blanchet@37348
   330
    else
blanchet@37348
   331
      term_has_too_many_lambdas max_lambda_nesting t
paulson@25007
   332
blanchet@37348
   333
(* The max apply depth of any "metis" call in "Metis_Examples" (on 31-10-2007)
blanchet@37348
   334
   was 11. *)
blanchet@37348
   335
val max_apply_depth = 15
wenzelm@27184
   336
blanchet@37348
   337
fun apply_depth (f $ t) = Int.max (apply_depth f, apply_depth t + 1)
blanchet@37348
   338
  | apply_depth (Abs (_, _, t)) = apply_depth t
blanchet@37348
   339
  | apply_depth _ = 0
paulson@25256
   340
blanchet@37348
   341
fun is_formula_too_complex t =
blanchet@37348
   342
  apply_depth t > max_apply_depth orelse Meson.too_many_clauses NONE t orelse
blanchet@37348
   343
  formula_has_too_many_lambdas [] t
wenzelm@27184
   344
paulson@25243
   345
fun is_strange_thm th =
paulson@25243
   346
  case head_of (concl_of th) of
blanchet@35963
   347
      Const (a, _) => (a <> @{const_name Trueprop} andalso
blanchet@35963
   348
                       a <> @{const_name "=="})
paulson@25243
   349
    | _ => false;
paulson@25243
   350
blanchet@37348
   351
fun is_theorem_bad_for_atps thm =
blanchet@37348
   352
  let val t = prop_of thm in
blanchet@37348
   353
    is_formula_too_complex t orelse exists_type type_has_topsort t orelse
blanchet@37348
   354
    is_strange_thm thm
blanchet@37348
   355
  end
paulson@25243
   356
blanchet@35963
   357
(* FIXME: put other record thms here, or declare as "no_atp" *)
paulson@25007
   358
val multi_base_blacklist =
blanchet@35963
   359
  ["defs", "select_defs", "update_defs", "induct", "inducts", "split", "splits",
blanchet@35963
   360
   "split_asm", "cases", "ext_cases"];
paulson@25007
   361
paulson@22731
   362
fun fake_name th =
wenzelm@27865
   363
  if Thm.has_name_hint th then flatten_name (Thm.get_name_hint th)
paulson@22731
   364
  else gensym "unknown_thm_";
paulson@22731
   365
wenzelm@27184
   366
(*Skolemize a named theorem, with Skolem functions as additional premises.*)
wenzelm@27184
   367
fun skolem_thm (s, th) =
blanchet@37345
   368
  if member (op =) multi_base_blacklist (Long_Name.base_name s) orelse
blanchet@37348
   369
     is_theorem_bad_for_atps th then
blanchet@37345
   370
    []
wenzelm@27184
   371
  else
wenzelm@27184
   372
    let
wenzelm@36603
   373
      val ctxt0 = Variable.global_thm_context th
blanchet@37349
   374
      val (nnfth, ctxt) = to_nnf th ctxt0
blanchet@37349
   375
      val defs = assume_skolem_of_def s nnfth
blanchet@37349
   376
      val (cnfs, ctxt) = Meson.make_cnf defs nnfth ctxt
blanchet@37349
   377
    in
blanchet@37349
   378
      cnfs |> map introduce_combinators
blanchet@37349
   379
           |> Variable.export ctxt ctxt0
blanchet@37349
   380
           |> Meson.finish_cnf
blanchet@37349
   381
    end
blanchet@37349
   382
    handle THM _ => []
wenzelm@27184
   383
paulson@24742
   384
(*The cache prevents repeated clausification of a theorem, and also repeated declaration of
paulson@24742
   385
  Skolem functions.*)
wenzelm@33522
   386
structure ThmCache = Theory_Data
wenzelm@22846
   387
(
wenzelm@28544
   388
  type T = thm list Thmtab.table * unit Symtab.table;
wenzelm@28544
   389
  val empty = (Thmtab.empty, Symtab.empty);
wenzelm@26618
   390
  val extend = I;
wenzelm@33522
   391
  fun merge ((cache1, seen1), (cache2, seen2)) : T =
wenzelm@27184
   392
    (Thmtab.merge (K true) (cache1, cache2), Symtab.merge (K true) (seen1, seen2));
wenzelm@22846
   393
);
paulson@22516
   394
wenzelm@27184
   395
val lookup_cache = Thmtab.lookup o #1 o ThmCache.get;
wenzelm@27184
   396
val already_seen = Symtab.defined o #2 o ThmCache.get;
wenzelm@20461
   397
wenzelm@27184
   398
val update_cache = ThmCache.map o apfst o Thmtab.update;
wenzelm@27184
   399
fun mark_seen name = ThmCache.map (apsnd (Symtab.update (name, ())));
paulson@25007
   400
blanchet@36228
   401
(* Convert Isabelle theorems into axiom clauses. *)
wenzelm@27179
   402
fun cnf_axiom thy th0 =
wenzelm@27184
   403
  let val th = Thm.transfer thy th0 in
wenzelm@27184
   404
    case lookup_cache thy th of
wenzelm@27184
   405
      NONE => map Thm.close_derivation (skolem_thm (fake_name th, th))
wenzelm@27184
   406
    | SOME cls => cls
paulson@22516
   407
  end;
paulson@15347
   408
paulson@18141
   409
paulson@22471
   410
(**** Translate a set of theorems into CNF ****)
paulson@15347
   411
paulson@19894
   412
fun pair_name_cls k (n, []) = []
paulson@19894
   413
  | pair_name_cls k (n, cls::clss) = (cls, (n,k)) :: pair_name_cls (k+1) (n, clss)
wenzelm@20461
   414
wenzelm@27179
   415
fun cnf_rules_pairs_aux _ pairs [] = pairs
wenzelm@27179
   416
  | cnf_rules_pairs_aux thy pairs ((name,th)::ths) =
wenzelm@27179
   417
      let val pairs' = (pair_name_cls 0 (name, cnf_axiom thy th)) @ pairs
blanchet@35826
   418
                       handle THM _ => pairs |
blanchet@35865
   419
                              CLAUSE _ => pairs
wenzelm@27179
   420
      in  cnf_rules_pairs_aux thy pairs' ths  end;
wenzelm@20461
   421
paulson@21290
   422
(*The combination of rev and tail recursion preserves the original order*)
wenzelm@27179
   423
fun cnf_rules_pairs thy l = cnf_rules_pairs_aux thy [] (rev l);
mengj@19353
   424
mengj@19196
   425
blanchet@35865
   426
(**** Convert all facts of the theory into FOL or HOL clauses ****)
paulson@15347
   427
wenzelm@28544
   428
local
wenzelm@28544
   429
wenzelm@28544
   430
fun skolem_def (name, th) thy =
wenzelm@36603
   431
  let val ctxt0 = Variable.global_thm_context th in
blanchet@37348
   432
    case try (to_nnf th) ctxt0 of
wenzelm@28544
   433
      NONE => (NONE, thy)
blanchet@37349
   434
    | SOME (nnfth, ctxt) =>
blanchet@37348
   435
      let val (defs, thy') = declare_skolem_funs (flatten_name name) nnfth thy
blanchet@37349
   436
      in (SOME (th, ctxt0, ctxt, nnfth, defs), thy') end
wenzelm@28544
   437
  end;
paulson@24742
   438
blanchet@37349
   439
fun skolem_cnfs (th, ctxt0, ctxt, nnfth, defs) =
wenzelm@28544
   440
  let
blanchet@37349
   441
    val (cnfs, ctxt) = Meson.make_cnf (map skolem_of_def defs) nnfth ctxt;
wenzelm@28544
   442
    val cnfs' = cnfs
blanchet@37349
   443
      |> map introduce_combinators
blanchet@37349
   444
      |> Variable.export ctxt ctxt0
wenzelm@28544
   445
      |> Meson.finish_cnf
wenzelm@28544
   446
      |> map Thm.close_derivation;
wenzelm@28544
   447
    in (th, cnfs') end;
wenzelm@28544
   448
wenzelm@28544
   449
in
paulson@24742
   450
wenzelm@27184
   451
fun saturate_skolem_cache thy =
wenzelm@28544
   452
  let
wenzelm@33306
   453
    val facts = PureThy.facts_of thy;
wenzelm@33306
   454
    val new_facts = (facts, []) |-> Facts.fold_static (fn (name, ths) =>
wenzelm@33306
   455
      if Facts.is_concealed facts name orelse already_seen thy name then I
wenzelm@33306
   456
      else cons (name, ths));
wenzelm@28544
   457
    val new_thms = (new_facts, []) |-> fold (fn (name, ths) =>
wenzelm@30364
   458
      if member (op =) multi_base_blacklist (Long_Name.base_name name) then I
wenzelm@28544
   459
      else fold_index (fn (i, th) =>
blanchet@37348
   460
        if is_theorem_bad_for_atps th orelse is_some (lookup_cache thy th) then
blanchet@37348
   461
          I
blanchet@37348
   462
        else
blanchet@37348
   463
          cons (name ^ "_" ^ string_of_int (i + 1), Thm.transfer thy th)) ths)
wenzelm@28544
   464
  in
wenzelm@28544
   465
    if null new_facts then NONE
wenzelm@28544
   466
    else
wenzelm@28544
   467
      let
wenzelm@28544
   468
        val (defs, thy') = thy
wenzelm@28544
   469
          |> fold (mark_seen o #1) new_facts
wenzelm@28544
   470
          |> fold_map skolem_def (sort_distinct (Thm.thm_ord o pairself snd) new_thms)
wenzelm@28544
   471
          |>> map_filter I;
wenzelm@29368
   472
        val cache_entries = Par_List.map skolem_cnfs defs;
wenzelm@28544
   473
      in SOME (fold update_cache cache_entries thy') end
wenzelm@28544
   474
  end;
wenzelm@27184
   475
wenzelm@28544
   476
end;
paulson@24854
   477
blanchet@37348
   478
val use_skolem_cache = Unsynchronized.ref true
wenzelm@27184
   479
wenzelm@27184
   480
fun clause_cache_endtheory thy =
blanchet@37348
   481
  if !use_skolem_cache then saturate_skolem_cache thy else NONE
wenzelm@27184
   482
paulson@20457
   483
paulson@22516
   484
(*The cache can be kept smaller by inspecting the prop of each thm. Can ignore all that are
paulson@22516
   485
  lambda_free, but then the individual theory caches become much bigger.*)
paulson@21071
   486
wenzelm@27179
   487
blanchet@36398
   488
fun strip_subgoal goal i =
blanchet@36398
   489
  let
blanchet@36398
   490
    val (t, frees) = Logic.goal_params (prop_of goal) i
blanchet@36398
   491
    val hyp_ts = t |> Logic.strip_assums_hyp |> map (curry subst_bounds frees)
blanchet@36398
   492
    val concl_t = t |> Logic.strip_assums_concl |> curry subst_bounds frees
blanchet@36478
   493
  in (rev (map dest_Free frees), hyp_ts, concl_t) end
blanchet@36398
   494
paulson@21999
   495
(*** Converting a subgoal into negated conjecture clauses. ***)
paulson@21999
   496
wenzelm@32262
   497
fun neg_skolemize_tac ctxt =
blanchet@37332
   498
  EVERY' [rtac ccontr, Object_Logic.atomize_prems_tac, Meson.skolemize_tac ctxt]
blanchet@36398
   499
blanchet@35869
   500
val neg_clausify =
blanchet@37349
   501
  single
blanchet@37349
   502
  #> Meson.make_clauses_unsorted
blanchet@37349
   503
  #> map introduce_combinators
blanchet@37349
   504
  #> Meson.finish_cnf
paulson@21999
   505
wenzelm@32257
   506
fun neg_conjecture_clauses ctxt st0 n =
wenzelm@32257
   507
  let
blanchet@37332
   508
    (* "Option" is thrown if the assumptions contain schematic variables. *)
blanchet@37332
   509
    val st = Seq.hd (neg_skolemize_tac ctxt n st0) handle Option.Option => st0
blanchet@37332
   510
    val ({params, prems, ...}, _) =
blanchet@37332
   511
      Subgoal.focus (Variable.set_body false ctxt) n st
blanchet@37332
   512
  in (map neg_clausify prems, map (dest_Free o term_of o #2) params) end
paulson@21999
   513
wenzelm@24669
   514
(*Conversion of a subgoal to conjecture clauses. Each clause has
paulson@21999
   515
  leading !!-bound universal variables, to express generality. *)
wenzelm@32257
   516
fun neg_clausify_tac ctxt =
wenzelm@32262
   517
  neg_skolemize_tac ctxt THEN'
wenzelm@32257
   518
  SUBGOAL (fn (prop, i) =>
wenzelm@32257
   519
    let val ts = Logic.strip_assums_hyp prop in
wenzelm@32257
   520
      EVERY'
wenzelm@32283
   521
       [Subgoal.FOCUS
wenzelm@32257
   522
         (fn {prems, ...} =>
wenzelm@32257
   523
           (Method.insert_tac
blanchet@36398
   524
             (map forall_intr_vars (maps neg_clausify prems)) i)) ctxt,
wenzelm@32257
   525
        REPEAT_DETERM_N (length ts) o etac thin_rl] i
paulson@21999
   526
     end);
paulson@21999
   527
wenzelm@27184
   528
wenzelm@27184
   529
(** setup **)
wenzelm@27184
   530
wenzelm@27184
   531
val setup =
blanchet@37348
   532
  perhaps saturate_skolem_cache
blanchet@37348
   533
  #> Theory.at_end clause_cache_endtheory
paulson@18510
   534
wenzelm@20461
   535
end;