src/HOL/Tools/res_axioms.ML
author paulson
Fri Nov 10 20:58:48 2006 +0100 (2006-11-10)
changeset 21290 33b6bb5d6ab8
parent 21254 d53f76357f41
child 21430 77651b6d9d6c
permissions -rw-r--r--
Improvement to classrel clauses: now outputs the minimum needed.
Theorem names: trying to minimize the number of multiple theorem names presented
paulson@15347
     1
(*  Author: Jia Meng, Cambridge University Computer Laboratory
paulson@15347
     2
    ID: $Id$
paulson@15347
     3
    Copyright 2004 University of Cambridge
paulson@15347
     4
wenzelm@20461
     5
Transformation of axiom rules (elim/intro/etc) into CNF forms.
paulson@15347
     6
*)
paulson@15347
     7
paulson@20996
     8
(*unused during debugging*)
paulson@15997
     9
signature RES_AXIOMS =
paulson@15997
    10
  sig
paulson@15997
    11
  val elimRule_tac : thm -> Tactical.tactic
paulson@16012
    12
  val elimR2Fol : thm -> term
paulson@15997
    13
  val transform_elim : thm -> thm
paulson@15997
    14
  val cnf_axiom : (string * thm) -> thm list
paulson@21071
    15
  val cnf_name : string -> thm list
paulson@15997
    16
  val meta_cnf_axiom : thm -> thm list
paulson@15997
    17
  val claset_rules_of_thy : theory -> (string * thm) list
paulson@15997
    18
  val simpset_rules_of_thy : theory -> (string * thm) list
paulson@17484
    19
  val claset_rules_of_ctxt: Proof.context -> (string * thm) list
paulson@17484
    20
  val simpset_rules_of_ctxt : Proof.context -> (string * thm) list
mengj@17905
    21
  val pairname : thm -> (string * thm)
paulson@18510
    22
  val skolem_thm : thm -> thm list
paulson@20419
    23
  val to_nnf : thm -> thm
mengj@19353
    24
  val cnf_rules_pairs : (string * Thm.thm) list -> (Thm.thm * (string * int)) list list;
wenzelm@18708
    25
  val meson_method_setup : theory -> theory
wenzelm@18708
    26
  val setup : theory -> theory
mengj@19196
    27
mengj@19196
    28
  val atpset_rules_of_thy : theory -> (string * thm) list
mengj@19196
    29
  val atpset_rules_of_ctxt : Proof.context -> (string * thm) list
paulson@15997
    30
  end;
wenzelm@20461
    31
paulson@20419
    32
structure ResAxioms =
wenzelm@20461
    33
paulson@15997
    34
struct
paulson@15347
    35
paulson@20996
    36
(*For running the comparison between combinators and abstractions.
paulson@20996
    37
  CANNOT be a ref, as the setting is used while Isabelle is built.
paulson@20996
    38
  Currently FALSE, i.e. all the "abstraction" code below is unused, but so far
paulson@20996
    39
  it seems to be inferior to combinators...*)
paulson@20996
    40
val abstract_lambdas = false;
paulson@20419
    41
paulson@20419
    42
val trace_abs = ref false;
mengj@18000
    43
wenzelm@20902
    44
(* FIXME legacy *)
paulson@20863
    45
fun freeze_thm th = #1 (Drule.freeze_thaw th);
paulson@20863
    46
wenzelm@20902
    47
val lhs_of = #1 o Logic.dest_equals o Thm.prop_of;
wenzelm@20902
    48
val rhs_of = #2 o Logic.dest_equals o Thm.prop_of;
paulson@20863
    49
paulson@20863
    50
paulson@20445
    51
(*Store definitions of abstraction functions, ensuring that identical right-hand
paulson@20445
    52
  sides are denoted by the same functions and thereby reducing the need for
paulson@20445
    53
  extensionality in proofs.
paulson@20445
    54
  FIXME!  Store in theory data!!*)
paulson@20863
    55
paulson@20867
    56
(*Populate the abstraction cache with common combinators.*)
paulson@20863
    57
fun seed th net =
wenzelm@20902
    58
  let val (_,ct) = Thm.dest_abs NONE (Drule.rhs_of th)
paulson@20867
    59
      val t = Logic.legacy_varify (term_of ct)
paulson@20867
    60
  in  Net.insert_term eq_thm (t, th) net end;
paulson@20863
    61
  
paulson@20863
    62
val abstraction_cache = ref 
wenzelm@21254
    63
      (seed (thm"ATP_Linkup.I_simp") 
wenzelm@21254
    64
       (seed (thm"ATP_Linkup.B_simp") 
wenzelm@21254
    65
	(seed (thm"ATP_Linkup.K_simp") Net.empty)));
paulson@20867
    66
paulson@20445
    67
paulson@15997
    68
(**** Transformation of Elimination Rules into First-Order Formulas****)
paulson@15347
    69
paulson@15390
    70
(* a tactic used to prove an elim-rule. *)
paulson@16009
    71
fun elimRule_tac th =
paulson@20419
    72
    (resolve_tac [impI,notI] 1) THEN (etac th 1) THEN REPEAT(fast_tac HOL_cs 1);
paulson@15347
    73
paulson@15956
    74
fun add_EX tm [] = tm
paulson@15956
    75
  | add_EX tm ((x,xtp)::xs) = add_EX (HOLogic.exists_const xtp $ Abs(x,xtp,tm)) xs;
paulson@15347
    76
paulson@19894
    77
(*Checks for the premise ~P when the conclusion is P.*)
wenzelm@20461
    78
fun is_neg (Const("Trueprop",_) $ (Const("Not",_) $ Free(p,_)))
paulson@19894
    79
           (Const("Trueprop",_) $ Free(q,_)) = (p = q)
paulson@15371
    80
  | is_neg _ _ = false;
paulson@15371
    81
paulson@20017
    82
exception ELIMR2FOL;
paulson@20017
    83
paulson@20017
    84
(*Handles the case where the dummy "conclusion" variable appears negated in the
paulson@20017
    85
  premises, so the final consequent must be kept.*)
paulson@15371
    86
fun strip_concl' prems bvs (Const ("==>",_) $ P $ Q) =
paulson@19894
    87
      strip_concl' (HOLogic.dest_Trueprop P :: prems) bvs  Q
wenzelm@20461
    88
  | strip_concl' prems bvs P =
paulson@15956
    89
      let val P' = HOLogic.Not $ (HOLogic.dest_Trueprop P)
paulson@19894
    90
      in add_EX (foldr1 HOLogic.mk_conj (P'::prems)) bvs end;
paulson@15371
    91
paulson@20017
    92
(*Recurrsion over the minor premise of an elimination rule. Final consequent
paulson@20017
    93
  is ignored, as it is the dummy "conclusion" variable.*)
wenzelm@20461
    94
fun strip_concl prems bvs concl (Const ("all", _) $ Abs (x,xtp,body)) =
paulson@18141
    95
      strip_concl prems ((x,xtp)::bvs) concl body
paulson@15371
    96
  | strip_concl prems bvs concl (Const ("==>",_) $ P $ Q) =
paulson@18141
    97
      if (is_neg P concl) then (strip_concl' prems bvs Q)
paulson@18141
    98
      else strip_concl (HOLogic.dest_Trueprop P::prems) bvs  concl Q
wenzelm@20461
    99
  | strip_concl prems bvs concl Q =
paulson@21071
   100
      if concl aconv Q andalso not (null prems) 
paulson@21071
   101
      then add_EX (foldr1 HOLogic.mk_conj prems) bvs
paulson@20017
   102
      else raise ELIMR2FOL (*expected conclusion not found!*)
wenzelm@20461
   103
paulson@20017
   104
fun trans_elim (major,[],_) = HOLogic.Not $ major
paulson@20017
   105
  | trans_elim (major,minors,concl) =
paulson@20017
   106
      let val disjs = foldr1 HOLogic.mk_disj (map (strip_concl [] [] concl) minors)
paulson@20017
   107
      in  HOLogic.mk_imp (major, disjs)  end;
paulson@15347
   108
paulson@16012
   109
(* convert an elim rule into an equivalent formula, of type term. *)
wenzelm@20461
   110
fun elimR2Fol elimR =
paulson@20863
   111
  let val elimR' = freeze_thm elimR
paulson@19894
   112
      val (prems,concl) = (prems_of elimR', concl_of elimR')
paulson@20017
   113
      val cv = case concl of    (*conclusion variable*)
wenzelm@20461
   114
                  Const("Trueprop",_) $ (v as Free(_,Type("bool",[]))) => v
wenzelm@20461
   115
                | v as Free(_, Type("prop",[])) => v
wenzelm@20461
   116
                | _ => raise ELIMR2FOL
paulson@20017
   117
  in case prems of
paulson@20017
   118
      [] => raise ELIMR2FOL
wenzelm@20461
   119
    | (Const("Trueprop",_) $ major) :: minors =>
paulson@20017
   120
        if member (op aconv) (term_frees major) cv then raise ELIMR2FOL
paulson@20017
   121
        else (trans_elim (major, minors, concl) handle TERM _ => raise ELIMR2FOL)
paulson@20017
   122
    | _ => raise ELIMR2FOL
paulson@20017
   123
  end;
paulson@15347
   124
wenzelm@20461
   125
(* convert an elim-rule into an equivalent theorem that does not have the
wenzelm@20461
   126
   predicate variable.  Leave other theorems unchanged.*)
paulson@16009
   127
fun transform_elim th =
paulson@21071
   128
    let val t = HOLogic.mk_Trueprop (elimR2Fol th)
paulson@21071
   129
    in 
paulson@21071
   130
        if Meson.too_many_clauses t then TrueI
paulson@21071
   131
        else Goal.prove_raw [] (cterm_of (sign_of_thm th) t) (fn _ => elimRule_tac th) 
paulson@21071
   132
    end
paulson@20017
   133
    handle ELIMR2FOL => th (*not an elimination rule*)
wenzelm@20461
   134
         | exn => (warning ("transform_elim failed: " ^ Toplevel.exn_message exn ^
paulson@21071
   135
                            " for theorem " ^ Thm.name_of_thm th ^ ": " ^ string_of_thm th); th)
paulson@20017
   136
paulson@15997
   137
paulson@15997
   138
(**** Transformation of Clasets and Simpsets into First-Order Axioms ****)
paulson@15997
   139
wenzelm@21254
   140
(*Transfer a theorem into theory ATP_Linkup.thy if it is not already
paulson@15359
   141
  inside that theory -- because it's needed for Skolemization *)
paulson@15359
   142
wenzelm@21254
   143
(*This will refer to the final version of theory ATP_Linkup.*)
wenzelm@20461
   144
val recon_thy_ref = Theory.self_ref (the_context ());
paulson@15359
   145
wenzelm@21254
   146
(*If called while ATP_Linkup is being created, it will transfer to the
paulson@16563
   147
  current version. If called afterward, it will transfer to the final version.*)
wenzelm@21254
   148
fun transfer_to_ATP_Linkup th =
paulson@16563
   149
    transfer (Theory.deref recon_thy_ref) th handle THM _ => th;
paulson@15347
   150
paulson@15955
   151
fun is_taut th =
paulson@15955
   152
      case (prop_of th) of
paulson@15955
   153
           (Const ("Trueprop", _) $ Const ("True", _)) => true
paulson@15955
   154
         | _ => false;
paulson@15955
   155
paulson@15955
   156
(* remove tautologous clauses *)
paulson@15955
   157
val rm_redundant_cls = List.filter (not o is_taut);
wenzelm@20461
   158
wenzelm@20461
   159
paulson@16009
   160
(**** SKOLEMIZATION BY INFERENCE (lcp) ****)
paulson@16009
   161
paulson@18141
   162
(*Traverse a theorem, declaring Skolem function definitions. String s is the suggested
paulson@18141
   163
  prefix for the Skolem constant. Result is a new theory*)
paulson@18141
   164
fun declare_skofuns s th thy =
paulson@21071
   165
  let val nref = ref 0
paulson@21071
   166
      fun dec_sko (Const ("Ex",_) $ (xtp as Abs(_,T,p))) (thy, axs) =
wenzelm@20461
   167
            (*Existential: declare a Skolem function, then insert into body and continue*)
paulson@21071
   168
            let val cname = Name.internal (s ^ "_sko" ^ Int.toString (inc nref))
wenzelm@20461
   169
                val args = term_frees xtp  (*get the formal parameter list*)
wenzelm@20461
   170
                val Ts = map type_of args
wenzelm@20461
   171
                val cT = Ts ---> T
wenzelm@20461
   172
                val c = Const (Sign.full_name thy cname, cT)
wenzelm@20461
   173
                val rhs = list_abs_free (map dest_Free args, HOLogic.choice_const T $ xtp)
wenzelm@20461
   174
                        (*Forms a lambda-abstraction over the formal parameters*)
wenzelm@20783
   175
                val thy' = Sign.add_consts_authentic [(cname, cT, NoSyn)] thy
wenzelm@20461
   176
                           (*Theory is augmented with the constant, then its def*)
wenzelm@20461
   177
                val cdef = cname ^ "_def"
wenzelm@20461
   178
                val thy'' = Theory.add_defs_i false false [(cdef, equals cT $ c $ rhs)] thy'
wenzelm@20461
   179
            in dec_sko (subst_bound (list_comb(c,args), p))
wenzelm@20461
   180
                       (thy'', get_axiom thy'' cdef :: axs)
wenzelm@20461
   181
            end
wenzelm@20461
   182
        | dec_sko (Const ("All",_) $ (xtp as Abs(a,T,p))) thx =
wenzelm@20461
   183
            (*Universal quant: insert a free variable into body and continue*)
wenzelm@20461
   184
            let val fname = Name.variant (add_term_names (p,[])) a
wenzelm@20461
   185
            in dec_sko (subst_bound (Free(fname,T), p)) thx end
wenzelm@20461
   186
        | dec_sko (Const ("op &", _) $ p $ q) thx = dec_sko q (dec_sko p thx)
wenzelm@20461
   187
        | dec_sko (Const ("op |", _) $ p $ q) thx = dec_sko q (dec_sko p thx)
wenzelm@20461
   188
        | dec_sko (Const ("Trueprop", _) $ p) thx = dec_sko p thx
wenzelm@20461
   189
        | dec_sko t thx = thx (*Do nothing otherwise*)
paulson@20419
   190
  in  dec_sko (prop_of th) (thy,[])  end;
paulson@18141
   191
paulson@18141
   192
(*Traverse a theorem, accumulating Skolem function definitions.*)
paulson@18141
   193
fun assume_skofuns th =
paulson@18141
   194
  let fun dec_sko (Const ("Ex",_) $ (xtp as Abs(_,T,p))) defs =
wenzelm@20461
   195
            (*Existential: declare a Skolem function, then insert into body and continue*)
wenzelm@20461
   196
            let val skos = map (#1 o Logic.dest_equals) defs  (*existing sko fns*)
wenzelm@20461
   197
                val args = term_frees xtp \\ skos  (*the formal parameters*)
wenzelm@20461
   198
                val Ts = map type_of args
wenzelm@20461
   199
                val cT = Ts ---> T
wenzelm@20461
   200
                val c = Free (gensym "sko_", cT)
wenzelm@20461
   201
                val rhs = list_abs_free (map dest_Free args,
wenzelm@20461
   202
                                         HOLogic.choice_const T $ xtp)
wenzelm@20461
   203
                      (*Forms a lambda-abstraction over the formal parameters*)
wenzelm@20461
   204
                val def = equals cT $ c $ rhs
wenzelm@20461
   205
            in dec_sko (subst_bound (list_comb(c,args), p))
wenzelm@20461
   206
                       (def :: defs)
wenzelm@20461
   207
            end
wenzelm@20461
   208
        | dec_sko (Const ("All",_) $ (xtp as Abs(a,T,p))) defs =
wenzelm@20461
   209
            (*Universal quant: insert a free variable into body and continue*)
wenzelm@20461
   210
            let val fname = Name.variant (add_term_names (p,[])) a
wenzelm@20461
   211
            in dec_sko (subst_bound (Free(fname,T), p)) defs end
wenzelm@20461
   212
        | dec_sko (Const ("op &", _) $ p $ q) defs = dec_sko q (dec_sko p defs)
wenzelm@20461
   213
        | dec_sko (Const ("op |", _) $ p $ q) defs = dec_sko q (dec_sko p defs)
wenzelm@20461
   214
        | dec_sko (Const ("Trueprop", _) $ p) defs = dec_sko p defs
wenzelm@20461
   215
        | dec_sko t defs = defs (*Do nothing otherwise*)
paulson@20419
   216
  in  dec_sko (prop_of th) []  end;
paulson@20419
   217
paulson@20419
   218
paulson@20419
   219
(**** REPLACING ABSTRACTIONS BY FUNCTION DEFINITIONS ****)
paulson@20419
   220
paulson@20419
   221
(*Returns the vars of a theorem*)
paulson@20419
   222
fun vars_of_thm th =
paulson@20445
   223
  map (Thm.cterm_of (theory_of_thm th) o Var) (Drule.fold_terms Term.add_vars th []);
paulson@20419
   224
paulson@20419
   225
(*Make a version of fun_cong with a given variable name*)
paulson@20419
   226
local
paulson@20419
   227
    val fun_cong' = fun_cong RS asm_rl; (*renumber f, g to prevent clashes with (a,0)*)
paulson@20419
   228
    val cx = hd (vars_of_thm fun_cong');
paulson@20419
   229
    val ty = typ_of (ctyp_of_term cx);
paulson@20445
   230
    val thy = theory_of_thm fun_cong;
paulson@20419
   231
    fun mkvar a = cterm_of thy (Var((a,0),ty));
paulson@20419
   232
in
paulson@20419
   233
fun xfun_cong x = Thm.instantiate ([], [(cx, mkvar x)]) fun_cong'
paulson@20419
   234
end;
paulson@20419
   235
paulson@20863
   236
(*Removes the lambdas from an equation of the form t = (%x. u).  A non-negative n,
paulson@20863
   237
  serves as an upper bound on how many to remove.*)
paulson@20863
   238
fun strip_lambdas 0 th = th
paulson@20863
   239
  | strip_lambdas n th = 
paulson@20863
   240
      case prop_of th of
paulson@20863
   241
	  _ $ (Const ("op =", _) $ _ $ Abs (x,_,_)) =>
paulson@20863
   242
	      strip_lambdas (n-1) (freeze_thm (th RS xfun_cong x))
paulson@20863
   243
	| _ => th;
paulson@20419
   244
wenzelm@20461
   245
(*Convert meta- to object-equality. Fails for theorems like split_comp_eq,
paulson@20419
   246
  where some types have the empty sort.*)
paulson@20863
   247
fun mk_object_eq th = th RS def_imp_eq
paulson@20419
   248
    handle THM _ => error ("Theorem contains empty sort: " ^ string_of_thm th);
wenzelm@20461
   249
paulson@20419
   250
(*Apply a function definition to an argument, beta-reducing the result.*)
paulson@20419
   251
fun beta_comb cf x =
paulson@20419
   252
  let val th1 = combination cf (reflexive x)
wenzelm@20902
   253
      val th2 = beta_conversion false (Drule.rhs_of th1)
paulson@20419
   254
  in  transitive th1 th2  end;
paulson@20419
   255
paulson@20419
   256
(*Apply a function definition to arguments, beta-reducing along the way.*)
paulson@20419
   257
fun list_combination cf [] = cf
paulson@20419
   258
  | list_combination cf (x::xs) = list_combination (beta_comb cf x) xs;
paulson@20419
   259
paulson@20419
   260
fun list_cabs ([] ,     t) = t
paulson@20419
   261
  | list_cabs (v::vars, t) = Thm.cabs v (list_cabs(vars,t));
paulson@20419
   262
wenzelm@20461
   263
fun assert_eta_free ct =
wenzelm@20461
   264
  let val t = term_of ct
wenzelm@20461
   265
  in if (t aconv Envir.eta_contract t) then ()
paulson@20419
   266
     else error ("Eta redex in term: " ^ string_of_cterm ct)
paulson@20419
   267
  end;
paulson@20419
   268
wenzelm@20461
   269
fun eq_absdef (th1, th2) =
paulson@20445
   270
    Context.joinable (theory_of_thm th1, theory_of_thm th2)  andalso
paulson@20445
   271
    rhs_of th1 aconv rhs_of th2;
paulson@20445
   272
paulson@20445
   273
fun lambda_free (Abs _) = false
paulson@20445
   274
  | lambda_free (t $ u) = lambda_free t andalso lambda_free u
paulson@20445
   275
  | lambda_free _ = true;
wenzelm@20461
   276
wenzelm@20461
   277
fun monomorphic t =
wenzelm@20461
   278
  Term.fold_types (Term.fold_atyps (fn TVar _ => K false | _ => I)) t true;
wenzelm@20461
   279
paulson@20710
   280
fun dest_abs_list ct =
paulson@20710
   281
  let val (cv,ct') = Thm.dest_abs NONE ct
paulson@20710
   282
      val (cvs,cu) = dest_abs_list ct'
paulson@20710
   283
  in (cv::cvs, cu) end
paulson@20710
   284
  handle CTERM _ => ([],ct);
paulson@20710
   285
paulson@20710
   286
fun lambda_list [] u = u
paulson@20710
   287
  | lambda_list (v::vs) u = lambda v (lambda_list vs u);
paulson@20710
   288
paulson@20710
   289
fun abstract_rule_list [] [] th = th
paulson@20710
   290
  | abstract_rule_list (v::vs) (ct::cts) th = abstract_rule v ct (abstract_rule_list vs cts th)
paulson@20710
   291
  | abstract_rule_list _ _ th = raise THM ("abstract_rule_list", 0, [th]);
paulson@20710
   292
paulson@20863
   293
paulson@20863
   294
val Envir.Envir {asol = tenv0, iTs = tyenv0, ...} = Envir.empty 0
paulson@20863
   295
paulson@20969
   296
(*Does an existing abstraction definition have an RHS that matches the one we need now?
paulson@20969
   297
  thy is the current theory, which must extend that of theorem th.*)
paulson@20969
   298
fun match_rhs thy t th =
paulson@20969
   299
  let val _ = if !trace_abs then warning ("match_rhs: " ^ string_of_cterm (cterm_of thy t) ^ 
paulson@20863
   300
                                          " against\n" ^ string_of_thm th) else ();
paulson@20867
   301
      val (tyenv,tenv) = Pattern.first_order_match thy (rhs_of th, t) (tyenv0,tenv0)
paulson@20863
   302
      val term_insts = map Meson.term_pair_of (Vartab.dest tenv)
paulson@20969
   303
      val ct_pairs = if subthy (theory_of_thm th, thy) andalso 
paulson@20969
   304
                        forall lambda_free (map #2 term_insts) 
paulson@20969
   305
                     then map (pairself (cterm_of thy)) term_insts
paulson@20863
   306
                     else raise Pattern.MATCH (*Cannot allow lambdas in the instantiation*)
paulson@20863
   307
      fun ctyp2 (ixn, (S, T)) = (ctyp_of thy (TVar (ixn, S)), ctyp_of thy T)
paulson@20863
   308
      val th' = cterm_instantiate ct_pairs th
paulson@20863
   309
  in  SOME (th, instantiate (map ctyp2 (Vartab.dest tyenv), []) th')  end
paulson@20863
   310
  handle _ => NONE;
paulson@20863
   311
paulson@20419
   312
(*Traverse a theorem, declaring abstraction function definitions. String s is the suggested
paulson@20419
   313
  prefix for the constants. Resulting theory is returned in the first theorem. *)
paulson@20419
   314
fun declare_absfuns th =
wenzelm@20461
   315
  let fun abstract thy ct =
paulson@20445
   316
        if lambda_free (term_of ct) then (transfer thy (reflexive ct), [])
paulson@20445
   317
        else
paulson@20445
   318
        case term_of ct of
paulson@20710
   319
          Abs _ =>
wenzelm@20624
   320
            let val cname = Name.internal (gensym "abs_");
wenzelm@20461
   321
                val _ = assert_eta_free ct;
paulson@20710
   322
                val (cvs,cta) = dest_abs_list ct
paulson@20710
   323
                val (vs,Tvs) = ListPair.unzip (map (dest_Free o term_of) cvs)
paulson@20863
   324
                val _ = if !trace_abs then warning ("Nested lambda: " ^ string_of_cterm cta) else ();
wenzelm@20461
   325
                val (u'_th,defs) = abstract thy cta
paulson@20863
   326
                val _ = if !trace_abs then warning ("Returned " ^ string_of_thm u'_th) else ();
wenzelm@20902
   327
                val cu' = Drule.rhs_of u'_th
paulson@20863
   328
                val u' = term_of cu'
paulson@20863
   329
                val abs_v_u = lambda_list (map term_of cvs) u'
wenzelm@20461
   330
                (*get the formal parameters: ALL variables free in the term*)
wenzelm@20461
   331
                val args = term_frees abs_v_u
paulson@20863
   332
                val _ = if !trace_abs then warning (Int.toString (length args) ^ " arguments") else ();
wenzelm@20461
   333
                val rhs = list_abs_free (map dest_Free args, abs_v_u)
wenzelm@20461
   334
                      (*Forms a lambda-abstraction over the formal parameters*)
paulson@20863
   335
                val _ = if !trace_abs then warning ("Looking up " ^ string_of_cterm cu') else ();
paulson@20969
   336
                val thy = theory_of_thm u'_th
paulson@20863
   337
                val (ax,ax',thy) =
paulson@20969
   338
                 case List.mapPartial (match_rhs thy abs_v_u) 
paulson@20969
   339
                         (Net.match_term (!abstraction_cache) u') of
paulson@20863
   340
                     (ax,ax')::_ => 
paulson@20863
   341
                       (if !trace_abs then warning ("Re-using axiom " ^ string_of_thm ax) else ();
paulson@20863
   342
                        (ax,ax',thy))
paulson@20863
   343
                   | [] =>
paulson@20863
   344
                      let val _ = if !trace_abs then warning "Lookup was empty" else ();
paulson@20863
   345
                          val Ts = map type_of args
paulson@20710
   346
                          val cT = Ts ---> (Tvs ---> typ_of (ctyp_of_term cu'))
wenzelm@20461
   347
                          val c = Const (Sign.full_name thy cname, cT)
wenzelm@20783
   348
                          val thy = Sign.add_consts_authentic [(cname, cT, NoSyn)] thy
wenzelm@20461
   349
                                     (*Theory is augmented with the constant,
wenzelm@20461
   350
                                       then its definition*)
wenzelm@20461
   351
                          val cdef = cname ^ "_def"
wenzelm@20461
   352
                          val thy = Theory.add_defs_i false false
wenzelm@20461
   353
                                       [(cdef, equals cT $ c $ rhs)] thy
paulson@20863
   354
                          val _ = if !trace_abs then (warning ("Definition is " ^ 
paulson@20863
   355
                                                      string_of_thm (get_axiom thy cdef))) 
paulson@20863
   356
                                  else ();
paulson@20863
   357
                          val ax = get_axiom thy cdef |> freeze_thm
paulson@20863
   358
                                     |> mk_object_eq |> strip_lambdas (length args)
paulson@20863
   359
                                     |> mk_meta_eq |> Meson.generalize
paulson@20969
   360
                          val (_,ax') = Option.valOf (match_rhs thy abs_v_u ax)
paulson@20863
   361
                          val _ = if !trace_abs then 
paulson@20863
   362
                                    (warning ("Declaring: " ^ string_of_thm ax);
paulson@20863
   363
                                     warning ("Instance: " ^ string_of_thm ax')) 
paulson@20863
   364
                                  else ();
paulson@20863
   365
                          val _ = abstraction_cache := Net.insert_term eq_absdef 
paulson@20863
   366
                                            ((Logic.varify u'), ax) (!abstraction_cache)
wenzelm@20461
   367
                            handle Net.INSERT =>
wenzelm@20461
   368
                              raise THM ("declare_absfuns: INSERT", 0, [th,u'_th,ax])
paulson@20863
   369
                       in  (ax,ax',thy)  end
paulson@20863
   370
            in if !trace_abs then warning ("Lookup result: " ^ string_of_thm ax') else ();
paulson@20863
   371
               (transitive (abstract_rule_list vs cvs u'_th) (symmetric ax'), ax::defs) end
wenzelm@20461
   372
        | (t1$t2) =>
wenzelm@20461
   373
            let val (ct1,ct2) = Thm.dest_comb ct
wenzelm@20461
   374
                val (th1,defs1) = abstract thy ct1
wenzelm@20461
   375
                val (th2,defs2) = abstract (theory_of_thm th1) ct2
wenzelm@20461
   376
            in  (combination th1 th2, defs1@defs2)  end
paulson@20863
   377
      val _ = if !trace_abs then warning ("declare_absfuns, Abstracting: " ^ string_of_thm th) else ();
paulson@20419
   378
      val (eqth,defs) = abstract (theory_of_thm th) (cprop_of th)
paulson@20863
   379
      val ths = equal_elim eqth th :: map (strip_lambdas ~1 o mk_object_eq o freeze_thm) defs
paulson@20863
   380
      val _ = if !trace_abs then warning ("declare_absfuns, Result: " ^ string_of_thm (hd ths)) else ();
paulson@20863
   381
  in  (theory_of_thm eqth, map Drule.eta_contraction_rule ths)  end;
paulson@20419
   382
wenzelm@20902
   383
fun name_of def = try (#1 o dest_Free o lhs_of) def;
paulson@20567
   384
paulson@20525
   385
(*A name is valid provided it isn't the name of a defined abstraction.*)
paulson@20567
   386
fun valid_name defs (Free(x,T)) = not (x mem_string (List.mapPartial name_of defs))
paulson@20525
   387
  | valid_name defs _ = false;
paulson@20525
   388
paulson@20419
   389
fun assume_absfuns th =
paulson@20445
   390
  let val thy = theory_of_thm th
paulson@20445
   391
      val cterm = cterm_of thy
paulson@20525
   392
      fun abstract ct =
paulson@20445
   393
        if lambda_free (term_of ct) then (reflexive ct, [])
paulson@20445
   394
        else
paulson@20445
   395
        case term_of ct of
paulson@20419
   396
          Abs (_,T,u) =>
paulson@20710
   397
            let val _ = assert_eta_free ct;
paulson@20710
   398
                val (cvs,cta) = dest_abs_list ct
paulson@20710
   399
                val (vs,Tvs) = ListPair.unzip (map (dest_Free o term_of) cvs)
paulson@20525
   400
                val (u'_th,defs) = abstract cta
wenzelm@20902
   401
                val cu' = Drule.rhs_of u'_th
paulson@20863
   402
                val u' = term_of cu'
paulson@20710
   403
                (*Could use Thm.cabs instead of lambda to work at level of cterms*)
paulson@20710
   404
                val abs_v_u = lambda_list (map term_of cvs) (term_of cu')
paulson@20525
   405
                (*get the formal parameters: free variables not present in the defs
paulson@20525
   406
                  (to avoid taking abstraction function names as parameters) *)
paulson@20710
   407
                val args = filter (valid_name defs) (term_frees abs_v_u)
paulson@20710
   408
                val crhs = list_cabs (map cterm args, cterm abs_v_u)
wenzelm@20461
   409
                      (*Forms a lambda-abstraction over the formal parameters*)
wenzelm@20461
   410
                val rhs = term_of crhs
paulson@20863
   411
                val (ax,ax') =
paulson@20969
   412
                 case List.mapPartial (match_rhs thy abs_v_u) 
paulson@20863
   413
                        (Net.match_term (!abstraction_cache) u') of
paulson@20863
   414
                     (ax,ax')::_ => 
paulson@20863
   415
                       (if !trace_abs then warning ("Re-using axiom " ^ string_of_thm ax) else ();
paulson@20863
   416
                        (ax,ax'))
paulson@20863
   417
                   | [] =>
wenzelm@20461
   418
                      let val Ts = map type_of args
paulson@20710
   419
                          val const_ty = Ts ---> (Tvs ---> typ_of (ctyp_of_term cu'))
wenzelm@20461
   420
                          val c = Free (gensym "abs_", const_ty)
wenzelm@20461
   421
                          val ax = assume (Thm.capply (cterm (equals const_ty $ c)) crhs)
paulson@20863
   422
                                     |> mk_object_eq |> strip_lambdas (length args)
paulson@20863
   423
                                     |> mk_meta_eq |> Meson.generalize
paulson@20969
   424
                          val (_,ax') = Option.valOf (match_rhs thy abs_v_u ax)
wenzelm@20461
   425
                          val _ = abstraction_cache := Net.insert_term eq_absdef (rhs,ax)
wenzelm@20461
   426
                                    (!abstraction_cache)
wenzelm@20461
   427
                            handle Net.INSERT =>
wenzelm@20461
   428
                              raise THM ("assume_absfuns: INSERT", 0, [th,u'_th,ax])
paulson@20863
   429
                      in (ax,ax') end
paulson@20863
   430
            in if !trace_abs then warning ("Lookup result: " ^ string_of_thm ax') else ();
paulson@20863
   431
               (transitive (abstract_rule_list vs cvs u'_th) (symmetric ax'), ax::defs) end
wenzelm@20461
   432
        | (t1$t2) =>
wenzelm@20461
   433
            let val (ct1,ct2) = Thm.dest_comb ct
paulson@20525
   434
                val (t1',defs1) = abstract ct1
paulson@20525
   435
                val (t2',defs2) = abstract ct2
wenzelm@20461
   436
            in  (combination t1' t2', defs1@defs2)  end
paulson@20863
   437
      val _ = if !trace_abs then warning ("assume_absfuns, Abstracting: " ^ string_of_thm th) else ();
paulson@20525
   438
      val (eqth,defs) = abstract (cprop_of th)
paulson@20863
   439
      val ths = equal_elim eqth th :: map (strip_lambdas ~1 o mk_object_eq o freeze_thm) defs
paulson@20863
   440
      val _ = if !trace_abs then warning ("assume_absfuns, Result: " ^ string_of_thm (hd ths)) else ();
paulson@20863
   441
  in  map Drule.eta_contraction_rule ths  end;
paulson@20419
   442
paulson@16009
   443
paulson@16009
   444
(*cterms are used throughout for efficiency*)
paulson@18141
   445
val cTrueprop = Thm.cterm_of HOL.thy HOLogic.Trueprop;
paulson@16009
   446
paulson@16009
   447
(*cterm version of mk_cTrueprop*)
paulson@16009
   448
fun c_mkTrueprop A = Thm.capply cTrueprop A;
paulson@16009
   449
paulson@16009
   450
(*Given an abstraction over n variables, replace the bound variables by free
paulson@16009
   451
  ones. Return the body, along with the list of free variables.*)
wenzelm@20461
   452
fun c_variant_abs_multi (ct0, vars) =
paulson@16009
   453
      let val (cv,ct) = Thm.dest_abs NONE ct0
paulson@16009
   454
      in  c_variant_abs_multi (ct, cv::vars)  end
paulson@16009
   455
      handle CTERM _ => (ct0, rev vars);
paulson@16009
   456
wenzelm@20461
   457
(*Given the definition of a Skolem function, return a theorem to replace
wenzelm@20461
   458
  an existential formula by a use of that function.
paulson@18141
   459
   Example: "EX x. x : A & x ~: B ==> sko A B : A & sko A B ~: B"  [.] *)
wenzelm@20461
   460
fun skolem_of_def def =
paulson@20863
   461
  let val (c,rhs) = Drule.dest_equals (cprop_of (freeze_thm def))
paulson@16009
   462
      val (ch, frees) = c_variant_abs_multi (rhs, [])
paulson@18141
   463
      val (chilbert,cabs) = Thm.dest_comb ch
paulson@18141
   464
      val {sign,t, ...} = rep_cterm chilbert
paulson@18141
   465
      val T = case t of Const ("Hilbert_Choice.Eps", Type("fun",[_,T])) => T
paulson@18141
   466
                      | _ => raise THM ("skolem_of_def: expected Eps", 0, [def])
paulson@16009
   467
      val cex = Thm.cterm_of sign (HOLogic.exists_const T)
paulson@16009
   468
      val ex_tm = c_mkTrueprop (Thm.capply cex cabs)
paulson@16009
   469
      and conc =  c_mkTrueprop (Drule.beta_conv cabs (Drule.list_comb(c,frees)));
paulson@18141
   470
      fun tacf [prem] = rewrite_goals_tac [def] THEN rtac (prem RS someI_ex) 1
wenzelm@20461
   471
  in  Goal.prove_raw [ex_tm] conc tacf
paulson@18141
   472
       |> forall_intr_list frees
paulson@18141
   473
       |> forall_elim_vars 0  (*Introduce Vars, but don't discharge defs.*)
paulson@18141
   474
       |> Thm.varifyT
paulson@18141
   475
  end;
paulson@16009
   476
paulson@20863
   477
(*Converts an Isabelle theorem (intro, elim or simp format, even higher-order) into NNF.*)
wenzelm@20461
   478
fun to_nnf th =
wenzelm@21254
   479
    th |> transfer_to_ATP_Linkup
paulson@20863
   480
       |> transform_elim |> zero_var_indexes |> freeze_thm
paulson@20863
   481
       |> ObjectLogic.atomize_thm |> make_nnf |> strip_lambdas ~1;
paulson@16009
   482
wenzelm@20461
   483
(*The cache prevents repeated clausification of a theorem,
wenzelm@20461
   484
  and also repeated declaration of Skolem functions*)
paulson@18510
   485
  (* FIXME better use Termtab!? No, we MUST use theory data!!*)
paulson@15955
   486
val clause_cache = ref (Symtab.empty : (thm * thm list) Symtab.table)
paulson@15955
   487
paulson@18141
   488
paulson@18141
   489
(*Generate Skolem functions for a theorem supplied in nnf*)
paulson@18141
   490
fun skolem_of_nnf th =
paulson@18141
   491
  map (skolem_of_def o assume o (cterm_of (theory_of_thm th))) (assume_skofuns th);
paulson@18141
   492
paulson@20863
   493
fun assert_lambda_free ths msg = 
paulson@20863
   494
  case filter (not o lambda_free o prop_of) ths of
paulson@20863
   495
      [] => ()
paulson@20863
   496
     | ths' => error (msg ^ "\n" ^ space_implode "\n" (map string_of_thm ths'));
paulson@20457
   497
paulson@20445
   498
fun assume_abstract th =
paulson@20457
   499
  if lambda_free (prop_of th) then [th]
paulson@20863
   500
  else th |> Drule.eta_contraction_rule |> assume_absfuns
paulson@20457
   501
          |> tap (fn ths => assert_lambda_free ths "assume_abstract: lambdas")
paulson@20445
   502
paulson@20419
   503
(*Replace lambdas by assumed function definitions in the theorems*)
paulson@20445
   504
fun assume_abstract_list ths =
paulson@20445
   505
  if abstract_lambdas then List.concat (map assume_abstract ths)
paulson@20863
   506
  else map Drule.eta_contraction_rule ths;
paulson@20419
   507
paulson@20419
   508
(*Replace lambdas by declared function definitions in the theorems*)
paulson@20419
   509
fun declare_abstract' (thy, []) = (thy, [])
paulson@20419
   510
  | declare_abstract' (thy, th::ths) =
wenzelm@20461
   511
      let val (thy', th_defs) =
paulson@20457
   512
            if lambda_free (prop_of th) then (thy, [th])
paulson@20445
   513
            else
paulson@20863
   514
                th |> zero_var_indexes |> freeze_thm
paulson@20863
   515
                   |> Drule.eta_contraction_rule |> transfer thy |> declare_absfuns
wenzelm@20461
   516
          val _ = assert_lambda_free th_defs "declare_abstract: lambdas"
wenzelm@20461
   517
          val (thy'', ths') = declare_abstract' (thy', ths)
paulson@20419
   518
      in  (thy'', th_defs @ ths')  end;
paulson@20419
   519
paulson@20419
   520
fun declare_abstract (thy, ths) =
paulson@20419
   521
  if abstract_lambdas then declare_abstract' (thy, ths)
paulson@20863
   522
  else (thy, map Drule.eta_contraction_rule ths);
paulson@20419
   523
paulson@18510
   524
(*Skolemize a named theorem, with Skolem functions as additional premises.*)
wenzelm@20461
   525
fun skolem_thm th =
paulson@18510
   526
  let val nnfth = to_nnf th
paulson@20419
   527
  in  Meson.make_cnf (skolem_of_nnf nnfth) nnfth
paulson@20445
   528
      |> assume_abstract_list |> Meson.finish_cnf |> rm_redundant_cls
paulson@18510
   529
  end
paulson@18510
   530
  handle THM _ => [];
paulson@18141
   531
paulson@21071
   532
(*Keep the full complexity of the original name*)
paulson@21071
   533
fun flatten_name s = space_implode "_X" (NameSpace.unpack s);
paulson@21071
   534
paulson@18510
   535
(*Declare Skolem functions for a theorem, supplied in nnf and with its name.
paulson@18510
   536
  It returns a modified theory, unless skolemization fails.*)
paulson@16009
   537
fun skolem thy (name,th) =
paulson@21071
   538
  let val cname = (case name of "" => gensym "" | s => flatten_name s)
paulson@20419
   539
      val _ = Output.debug ("skolemizing " ^ name ^ ": ")
wenzelm@20461
   540
  in Option.map
wenzelm@20461
   541
        (fn nnfth =>
paulson@18141
   542
          let val (thy',defs) = declare_skofuns cname nnfth thy
paulson@20419
   543
              val cnfs = Meson.make_cnf (map skolem_of_def defs) nnfth
paulson@20419
   544
              val (thy'',cnfs') = declare_abstract (thy',cnfs)
paulson@20419
   545
          in (thy'', rm_redundant_cls (Meson.finish_cnf cnfs'))
paulson@20419
   546
          end)
wenzelm@20461
   547
      (SOME (to_nnf th)  handle THM _ => NONE)
paulson@18141
   548
  end;
paulson@16009
   549
paulson@18510
   550
(*Populate the clause cache using the supplied theorem. Return the clausal form
paulson@18510
   551
  and modified theory.*)
wenzelm@20461
   552
fun skolem_cache_thm (name,th) thy =
paulson@18144
   553
  case Symtab.lookup (!clause_cache) name of
wenzelm@20461
   554
      NONE =>
wenzelm@20461
   555
        (case skolem thy (name, Thm.transfer thy th) of
wenzelm@20461
   556
             NONE => ([th],thy)
paulson@20473
   557
           | SOME (thy',cls) => 
paulson@20473
   558
               let val cls = map Drule.local_standard cls
paulson@20473
   559
               in
paulson@20473
   560
                  if null cls then warning ("skolem_cache: empty clause set for " ^ name)
paulson@20473
   561
                  else ();
paulson@20473
   562
                  change clause_cache (Symtab.update (name, (th, cls))); 
paulson@20473
   563
                  (cls,thy')
paulson@20473
   564
               end)
paulson@18144
   565
    | SOME (th',cls) =>
paulson@18510
   566
        if eq_thm(th,th') then (cls,thy)
wenzelm@20461
   567
        else (Output.debug ("skolem_cache: Ignoring variant of theorem " ^ name);
wenzelm@20461
   568
              Output.debug (string_of_thm th);
wenzelm@20461
   569
              Output.debug (string_of_thm th');
wenzelm@20461
   570
              ([th],thy));
wenzelm@20461
   571
wenzelm@20461
   572
(*Exported function to convert Isabelle theorems into axiom clauses*)
paulson@19894
   573
fun cnf_axiom (name,th) =
paulson@21071
   574
 (Output.debug ("cnf_axiom called, theorem name = " ^ name);
paulson@18144
   575
  case name of
wenzelm@20461
   576
        "" => skolem_thm th (*no name, so can't cache*)
paulson@18144
   577
      | s  => case Symtab.lookup (!clause_cache) s of
paulson@20473
   578
                NONE => 
paulson@20473
   579
                  let val cls = map Drule.local_standard (skolem_thm th)
paulson@21071
   580
                  in Output.debug "inserted into cache";
paulson@21071
   581
                     change clause_cache (Symtab.update (s, (th, cls))); cls 
paulson@21071
   582
                  end
wenzelm@20461
   583
              | SOME(th',cls) =>
wenzelm@20461
   584
                  if eq_thm(th,th') then cls
wenzelm@20461
   585
                  else (Output.debug ("cnf_axiom: duplicate or variant of theorem " ^ name);
wenzelm@20461
   586
                        Output.debug (string_of_thm th);
wenzelm@20461
   587
                        Output.debug (string_of_thm th');
paulson@21071
   588
                        cls)
paulson@21071
   589
 );
paulson@15347
   590
paulson@18141
   591
fun pairname th = (Thm.name_of_thm th, th);
paulson@18141
   592
paulson@21071
   593
(*Principally for debugging*)
paulson@21071
   594
fun cnf_name s = 
paulson@21071
   595
  let val th = thm s
paulson@21071
   596
  in cnf_axiom (Thm.name_of_thm th, th) end;
paulson@15347
   597
paulson@15872
   598
(**** Extract and Clausify theorems from a theory's claset and simpset ****)
paulson@15347
   599
paulson@17404
   600
(*Preserve the name of "th" after the transformation "f"*)
paulson@17404
   601
fun preserve_name f th = Thm.name_thm (Thm.name_of_thm th, f th);
paulson@17404
   602
paulson@17484
   603
fun rules_of_claset cs =
paulson@17484
   604
  let val {safeIs,safeEs,hazIs,hazEs,...} = rep_cs cs
paulson@19175
   605
      val intros = safeIs @ hazIs
wenzelm@18532
   606
      val elims  = map Classical.classical_rule (safeEs @ hazEs)
paulson@17404
   607
  in
wenzelm@20461
   608
     Output.debug ("rules_of_claset intros: " ^ Int.toString(length intros) ^
paulson@17484
   609
            " elims: " ^ Int.toString(length elims));
paulson@20017
   610
     map pairname (intros @ elims)
paulson@17404
   611
  end;
paulson@15347
   612
paulson@17484
   613
fun rules_of_simpset ss =
paulson@17484
   614
  let val ({rules,...}, _) = rep_ss ss
paulson@17484
   615
      val simps = Net.entries rules
wenzelm@20461
   616
  in
wenzelm@18680
   617
      Output.debug ("rules_of_simpset: " ^ Int.toString(length simps));
paulson@17484
   618
      map (fn r => (#name r, #thm r)) simps
paulson@17484
   619
  end;
paulson@17484
   620
paulson@17484
   621
fun claset_rules_of_thy thy = rules_of_claset (claset_of thy);
paulson@17484
   622
fun simpset_rules_of_thy thy = rules_of_simpset (simpset_of thy);
paulson@17484
   623
wenzelm@20774
   624
fun atpset_rules_of_thy thy = map pairname (ResAtpset.get_atpset (Context.Theory thy));
mengj@19196
   625
mengj@19196
   626
paulson@17484
   627
fun claset_rules_of_ctxt ctxt = rules_of_claset (local_claset_of ctxt);
paulson@17484
   628
fun simpset_rules_of_ctxt ctxt = rules_of_simpset (local_simpset_of ctxt);
paulson@15347
   629
wenzelm@20774
   630
fun atpset_rules_of_ctxt ctxt = map pairname (ResAtpset.get_atpset (Context.Proof ctxt));
wenzelm@20774
   631
paulson@15347
   632
paulson@15872
   633
(**** Translate a set of classical/simplifier rules into CNF (still as type "thm")  ****)
paulson@15347
   634
paulson@19894
   635
(* classical rules: works for both FOL and HOL *)
paulson@19894
   636
fun cnf_rules [] err_list = ([],err_list)
wenzelm@20461
   637
  | cnf_rules ((name,th) :: ths) err_list =
paulson@19894
   638
      let val (ts,es) = cnf_rules ths err_list
wenzelm@20461
   639
      in  (cnf_axiom (name,th) :: ts,es) handle  _ => (ts, (th::es))  end;
paulson@15347
   640
paulson@19894
   641
fun pair_name_cls k (n, []) = []
paulson@19894
   642
  | pair_name_cls k (n, cls::clss) = (cls, (n,k)) :: pair_name_cls (k+1) (n, clss)
wenzelm@20461
   643
paulson@19894
   644
fun cnf_rules_pairs_aux pairs [] = pairs
paulson@19894
   645
  | cnf_rules_pairs_aux pairs ((name,th)::ths) =
paulson@20457
   646
      let val pairs' = (pair_name_cls 0 (name, cnf_axiom(name,th))) @ pairs
wenzelm@20461
   647
                       handle THM _ => pairs | ResClause.CLAUSE _ => pairs
paulson@19894
   648
      in  cnf_rules_pairs_aux pairs' ths  end;
wenzelm@20461
   649
paulson@21290
   650
(*The combination of rev and tail recursion preserves the original order*)
paulson@21290
   651
fun cnf_rules_pairs l = cnf_rules_pairs_aux [] (rev l);
mengj@19353
   652
mengj@19196
   653
mengj@18198
   654
(**** Convert all theorems of a claset/simpset into clauses (ResClause.clause, or ResHolClause.clause) ****)
paulson@15347
   655
paulson@20419
   656
(*Setup function: takes a theory and installs ALL known theorems into the clause cache*)
paulson@20457
   657
wenzelm@20461
   658
fun skolem_cache (name,th) thy =
wenzelm@20461
   659
  let val prop = Thm.prop_of th
paulson@20457
   660
  in
paulson@21071
   661
      if lambda_free prop 
paulson@20969
   662
         (*Monomorphic theorems can be Skolemized on demand,
paulson@20867
   663
           but there are problems with re-use of abstraction functions if we don't
paulson@20867
   664
           do them now, even for monomorphic theorems.*)
paulson@20867
   665
      then thy  
wenzelm@20461
   666
      else #2 (skolem_cache_thm (name,th) thy)
paulson@20457
   667
  end;
paulson@20457
   668
paulson@21071
   669
(*The cache can be kept smaller by augmenting the condition above with 
paulson@21071
   670
    orelse (not abstract_lambdas andalso monomorphic prop).
paulson@21071
   671
  However, while this step does not reduce the time needed to build HOL, 
paulson@21071
   672
  it doubles the time taken by the first call to the ATP link-up.*)
paulson@21071
   673
wenzelm@20461
   674
fun clause_cache_setup thy = fold skolem_cache (PureThy.all_thms_of thy) thy;
wenzelm@20461
   675
paulson@16563
   676
paulson@16563
   677
(*** meson proof methods ***)
paulson@16563
   678
paulson@21071
   679
fun skolem_use_cache_thm th =
paulson@21071
   680
  case Symtab.lookup (!clause_cache) (Thm.name_of_thm th) of
paulson@21071
   681
      NONE => skolem_thm th
paulson@21071
   682
    | SOME (th',cls) =>
paulson@21071
   683
        if eq_thm(th,th') then cls else skolem_thm th;
paulson@21071
   684
paulson@21071
   685
fun cnf_rules_of_ths ths = List.concat (map skolem_use_cache_thm ths);
paulson@16563
   686
paulson@16563
   687
fun meson_meth ths ctxt =
paulson@16563
   688
  Method.SIMPLE_METHOD' HEADGOAL
paulson@21096
   689
    (CHANGED_PROP o Meson.meson_claset_tac (cnf_rules_of_ths ths) HOL_cs);
paulson@16563
   690
paulson@16563
   691
val meson_method_setup =
wenzelm@18708
   692
  Method.add_methods
wenzelm@20461
   693
    [("meson", Method.thms_ctxt_args meson_meth,
wenzelm@18833
   694
      "MESON resolution proof procedure")];
paulson@15347
   695
paulson@21102
   696
(** Attribute for converting a theorem into clauses **)
paulson@18510
   697
paulson@21102
   698
fun meta_cnf_axiom th = map Meson.make_meta_clause (cnf_axiom (pairname th));
paulson@18510
   699
paulson@21102
   700
fun clausify_rule (th,i) = List.nth (meta_cnf_axiom th, i)
paulson@21102
   701
paulson@21102
   702
val clausify = Attrib.syntax (Scan.lift Args.nat
paulson@21102
   703
  >> (fn i => Thm.rule_attribute (fn _ => fn th => clausify_rule (th, i))));
paulson@21102
   704
paulson@21102
   705
(** The Skolemization attribute **)
paulson@18510
   706
paulson@18510
   707
fun conj2_rule (th1,th2) = conjI OF [th1,th2];
paulson@18510
   708
paulson@20457
   709
(*Conjoin a list of theorems to form a single theorem*)
paulson@20457
   710
fun conj_rule []  = TrueI
paulson@20445
   711
  | conj_rule ths = foldr1 conj2_rule ths;
paulson@18510
   712
paulson@20419
   713
fun skolem_attr (Context.Theory thy, th) =
paulson@20419
   714
      let val name = Thm.name_of_thm th
wenzelm@20461
   715
          val (cls, thy') = skolem_cache_thm (name, th) thy
wenzelm@18728
   716
      in (Context.Theory thy', conj_rule cls) end
paulson@21071
   717
  | skolem_attr (context, th) = (context, conj_rule (skolem_use_cache_thm th));
paulson@18510
   718
paulson@18510
   719
val setup_attrs = Attrib.add_attributes
paulson@21102
   720
  [("skolem", Attrib.no_args skolem_attr, "skolemization of a theorem"),
paulson@21102
   721
   ("clausify", clausify, "conversion to clauses")];
paulson@21102
   722
     
wenzelm@18708
   723
val setup = clause_cache_setup #> setup_attrs;
paulson@18510
   724
wenzelm@20461
   725
end;