src/HOL/Tools/res_axioms.ML
author paulson
Fri Aug 25 18:48:58 2006 +0200 (2006-08-25)
changeset 20419 df257a9cf0e9
parent 20373 dcb321249aa9
child 20421 d9606c64bc23
permissions -rw-r--r--
abstraction of lambda-expressions
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
paulson@15347
     5
Transformation of axiom rules (elim/intro/etc) into CNF forms.    
paulson@15347
     6
*)
paulson@15347
     7
paulson@15997
     8
signature RES_AXIOMS =
paulson@15997
     9
  sig
paulson@15997
    10
  val elimRule_tac : thm -> Tactical.tactic
paulson@16012
    11
  val elimR2Fol : thm -> term
paulson@15997
    12
  val transform_elim : thm -> thm
paulson@15997
    13
  val cnf_axiom : (string * thm) -> thm list
paulson@15997
    14
  val meta_cnf_axiom : thm -> thm list
paulson@15997
    15
  val claset_rules_of_thy : theory -> (string * thm) list
paulson@15997
    16
  val simpset_rules_of_thy : theory -> (string * thm) list
paulson@17484
    17
  val claset_rules_of_ctxt: Proof.context -> (string * thm) list
paulson@17484
    18
  val simpset_rules_of_ctxt : Proof.context -> (string * thm) list
mengj@17905
    19
  val pairname : thm -> (string * thm)
paulson@18510
    20
  val skolem_thm : thm -> thm list
paulson@20419
    21
  val to_nnf : thm -> thm
mengj@19353
    22
  val cnf_rules_pairs : (string * Thm.thm) list -> (Thm.thm * (string * int)) list list;
wenzelm@18708
    23
  val meson_method_setup : theory -> theory
wenzelm@18708
    24
  val setup : theory -> theory
mengj@19196
    25
mengj@19196
    26
  val atpset_rules_of_thy : theory -> (string * thm) list
mengj@19196
    27
  val atpset_rules_of_ctxt : Proof.context -> (string * thm) list
paulson@15997
    28
  end;
paulson@20419
    29
 
paulson@20419
    30
structure ResAxioms =
paulson@15997
    31
 
paulson@15997
    32
struct
paulson@15347
    33
paulson@20419
    34
(*FIXME DELETE: For running the comparison between combinators and abstractions.
paulson@20419
    35
  CANNOT be a ref, as the setting is used while Isabelle is built.*)
paulson@20419
    36
val abstract_lambdas = true;
paulson@20419
    37
paulson@20419
    38
val trace_abs = ref false;
mengj@18000
    39
paulson@15997
    40
(**** Transformation of Elimination Rules into First-Order Formulas****)
paulson@15347
    41
paulson@15390
    42
(* a tactic used to prove an elim-rule. *)
paulson@16009
    43
fun elimRule_tac th =
paulson@20419
    44
    (resolve_tac [impI,notI] 1) THEN (etac th 1) THEN REPEAT(fast_tac HOL_cs 1);
paulson@15347
    45
paulson@15956
    46
fun add_EX tm [] = tm
paulson@15956
    47
  | add_EX tm ((x,xtp)::xs) = add_EX (HOLogic.exists_const xtp $ Abs(x,xtp,tm)) xs;
paulson@15347
    48
paulson@19894
    49
(*Checks for the premise ~P when the conclusion is P.*)
paulson@19894
    50
fun is_neg (Const("Trueprop",_) $ (Const("Not",_) $ Free(p,_))) 
paulson@19894
    51
           (Const("Trueprop",_) $ Free(q,_)) = (p = q)
paulson@15371
    52
  | is_neg _ _ = false;
paulson@15371
    53
paulson@20017
    54
exception ELIMR2FOL;
paulson@20017
    55
paulson@20017
    56
(*Handles the case where the dummy "conclusion" variable appears negated in the
paulson@20017
    57
  premises, so the final consequent must be kept.*)
paulson@15371
    58
fun strip_concl' prems bvs (Const ("==>",_) $ P $ Q) =
paulson@19894
    59
      strip_concl' (HOLogic.dest_Trueprop P :: prems) bvs  Q
paulson@15371
    60
  | strip_concl' prems bvs P = 
paulson@15956
    61
      let val P' = HOLogic.Not $ (HOLogic.dest_Trueprop P)
paulson@19894
    62
      in add_EX (foldr1 HOLogic.mk_conj (P'::prems)) bvs end;
paulson@15371
    63
paulson@20017
    64
(*Recurrsion over the minor premise of an elimination rule. Final consequent
paulson@20017
    65
  is ignored, as it is the dummy "conclusion" variable.*)
paulson@18141
    66
fun strip_concl prems bvs concl (Const ("all", _) $ Abs (x,xtp,body)) = 
paulson@18141
    67
      strip_concl prems ((x,xtp)::bvs) concl body
paulson@15371
    68
  | strip_concl prems bvs concl (Const ("==>",_) $ P $ Q) =
paulson@18141
    69
      if (is_neg P concl) then (strip_concl' prems bvs Q)
paulson@18141
    70
      else strip_concl (HOLogic.dest_Trueprop P::prems) bvs  concl Q
paulson@20017
    71
  | strip_concl prems bvs concl Q = 
paulson@20017
    72
      if concl aconv Q then add_EX (foldr1 HOLogic.mk_conj prems) bvs
paulson@20017
    73
      else raise ELIMR2FOL (*expected conclusion not found!*)
paulson@15347
    74
 
paulson@20017
    75
fun trans_elim (major,[],_) = HOLogic.Not $ major
paulson@20017
    76
  | trans_elim (major,minors,concl) =
paulson@20017
    77
      let val disjs = foldr1 HOLogic.mk_disj (map (strip_concl [] [] concl) minors)
paulson@20017
    78
      in  HOLogic.mk_imp (major, disjs)  end;
paulson@15347
    79
paulson@16012
    80
(* convert an elim rule into an equivalent formula, of type term. *)
paulson@15347
    81
fun elimR2Fol elimR = 
wenzelm@20292
    82
  let val elimR' = #1 (Drule.freeze_thaw elimR)
paulson@19894
    83
      val (prems,concl) = (prems_of elimR', concl_of elimR')
paulson@20017
    84
      val cv = case concl of    (*conclusion variable*)
paulson@20017
    85
		  Const("Trueprop",_) $ (v as Free(_,Type("bool",[]))) => v
paulson@20017
    86
		| v as Free(_, Type("prop",[])) => v
paulson@20017
    87
		| _ => raise ELIMR2FOL
paulson@20017
    88
  in case prems of
paulson@20017
    89
      [] => raise ELIMR2FOL
paulson@20017
    90
    | (Const("Trueprop",_) $ major) :: minors => 
paulson@20017
    91
        if member (op aconv) (term_frees major) cv then raise ELIMR2FOL
paulson@20017
    92
        else (trans_elim (major, minors, concl) handle TERM _ => raise ELIMR2FOL)
paulson@20017
    93
    | _ => raise ELIMR2FOL
paulson@20017
    94
  end;
paulson@15347
    95
paulson@15997
    96
(* convert an elim-rule into an equivalent theorem that does not have the 
paulson@15997
    97
   predicate variable.  Leave other theorems unchanged.*) 
paulson@16009
    98
fun transform_elim th =
paulson@20017
    99
    let val ctm = cterm_of (sign_of_thm th) (HOLogic.mk_Trueprop (elimR2Fol th))
paulson@18009
   100
    in Goal.prove_raw [] ctm (fn _ => elimRule_tac th) end
paulson@20017
   101
    handle ELIMR2FOL => th (*not an elimination rule*)
paulson@20017
   102
         | exn => (warning ("transform_elim failed: " ^ Toplevel.exn_message exn ^ 
paulson@20017
   103
                            " for theorem " ^ string_of_thm th); th) 
paulson@20017
   104
paulson@15997
   105
paulson@15997
   106
(**** Transformation of Clasets and Simpsets into First-Order Axioms ****)
paulson@15997
   107
paulson@16563
   108
(*Transfer a theorem into theory Reconstruction.thy if it is not already
paulson@15359
   109
  inside that theory -- because it's needed for Skolemization *)
paulson@15359
   110
paulson@16563
   111
(*This will refer to the final version of theory Reconstruction.*)
paulson@16563
   112
val recon_thy_ref = Theory.self_ref (the_context ());  
paulson@15359
   113
paulson@16563
   114
(*If called while Reconstruction is being created, it will transfer to the
paulson@16563
   115
  current version. If called afterward, it will transfer to the final version.*)
paulson@16009
   116
fun transfer_to_Reconstruction th =
paulson@16563
   117
    transfer (Theory.deref recon_thy_ref) th handle THM _ => th;
paulson@15347
   118
paulson@15955
   119
fun is_taut th =
paulson@15955
   120
      case (prop_of th) of
paulson@15955
   121
           (Const ("Trueprop", _) $ Const ("True", _)) => true
paulson@15955
   122
         | _ => false;
paulson@15955
   123
paulson@15955
   124
(* remove tautologous clauses *)
paulson@15955
   125
val rm_redundant_cls = List.filter (not o is_taut);
paulson@18141
   126
     
paulson@15997
   127
       
paulson@16009
   128
(**** SKOLEMIZATION BY INFERENCE (lcp) ****)
paulson@16009
   129
paulson@18141
   130
(*Traverse a theorem, declaring Skolem function definitions. String s is the suggested
paulson@18141
   131
  prefix for the Skolem constant. Result is a new theory*)
paulson@18141
   132
fun declare_skofuns s th thy =
paulson@20419
   133
  let fun dec_sko (Const ("Ex",_) $ (xtp as Abs(_,T,p))) (thy, axs) =
paulson@16009
   134
	    (*Existential: declare a Skolem function, then insert into body and continue*)
paulson@20419
   135
	    let val cname = gensym ("sko_" ^ s ^ "_")
paulson@16012
   136
		val args = term_frees xtp  (*get the formal parameter list*)
paulson@16009
   137
		val Ts = map type_of args
paulson@16009
   138
		val cT = Ts ---> T
paulson@18141
   139
		val c = Const (Sign.full_name thy cname, cT)
paulson@16009
   140
		val rhs = list_abs_free (map dest_Free args, HOLogic.choice_const T $ xtp)
paulson@16012
   141
		        (*Forms a lambda-abstraction over the formal parameters*)
paulson@16009
   142
		val thy' = Theory.add_consts_i [(cname, cT, NoSyn)] thy
paulson@16012
   143
		           (*Theory is augmented with the constant, then its def*)
paulson@17404
   144
		val cdef = cname ^ "_def"
paulson@20419
   145
		val thy'' = Theory.add_defs_i false false [(cdef, equals cT $ c $ rhs)] thy'
paulson@17404
   146
	    in dec_sko (subst_bound (list_comb(c,args), p)) 
paulson@20419
   147
	               (thy'', get_axiom thy'' cdef :: axs)
paulson@17404
   148
	    end
paulson@20419
   149
	| dec_sko (Const ("All",_) $ (xtp as Abs(a,T,p))) thx =
paulson@16012
   150
	    (*Universal quant: insert a free variable into body and continue*)
wenzelm@20071
   151
	    let val fname = Name.variant (add_term_names (p,[])) a
paulson@20419
   152
	    in dec_sko (subst_bound (Free(fname,T), p)) thx end
paulson@20419
   153
	| dec_sko (Const ("op &", _) $ p $ q) thx = dec_sko q (dec_sko p thx)
paulson@20419
   154
	| dec_sko (Const ("op |", _) $ p $ q) thx = dec_sko q (dec_sko p thx)
paulson@20419
   155
	| dec_sko (Const ("Trueprop", _) $ p) thx = dec_sko p thx
paulson@20419
   156
	| dec_sko t thx = thx (*Do nothing otherwise*)
paulson@20419
   157
  in  dec_sko (prop_of th) (thy,[])  end;
paulson@18141
   158
paulson@18141
   159
(*Traverse a theorem, accumulating Skolem function definitions.*)
paulson@18141
   160
fun assume_skofuns th =
paulson@18141
   161
  let fun dec_sko (Const ("Ex",_) $ (xtp as Abs(_,T,p))) defs =
paulson@18141
   162
	    (*Existential: declare a Skolem function, then insert into body and continue*)
paulson@20419
   163
	    let val skos = map (#1 o Logic.dest_equals) defs  (*existing sko fns*)
paulson@18141
   164
		val args = term_frees xtp \\ skos  (*the formal parameters*)
paulson@18141
   165
		val Ts = map type_of args
paulson@18141
   166
		val cT = Ts ---> T
paulson@20419
   167
		val c = Free (gensym "sko_", cT)
paulson@18141
   168
		val rhs = list_abs_free (map dest_Free args,        
paulson@18141
   169
		                         HOLogic.choice_const T $ xtp)
paulson@18141
   170
		      (*Forms a lambda-abstraction over the formal parameters*)
paulson@18141
   171
		val def = equals cT $ c $ rhs
paulson@18141
   172
	    in dec_sko (subst_bound (list_comb(c,args), p)) 
paulson@18141
   173
	               (def :: defs)
paulson@18141
   174
	    end
paulson@18141
   175
	| dec_sko (Const ("All",_) $ (xtp as Abs(a,T,p))) defs =
paulson@18141
   176
	    (*Universal quant: insert a free variable into body and continue*)
wenzelm@20071
   177
	    let val fname = Name.variant (add_term_names (p,[])) a
paulson@18141
   178
	    in dec_sko (subst_bound (Free(fname,T), p)) defs end
paulson@18141
   179
	| dec_sko (Const ("op &", _) $ p $ q) defs = dec_sko q (dec_sko p defs)
paulson@18141
   180
	| dec_sko (Const ("op |", _) $ p $ q) defs = dec_sko q (dec_sko p defs)
paulson@18141
   181
	| dec_sko (Const ("Trueprop", _) $ p) defs = dec_sko p defs
paulson@18141
   182
	| dec_sko t defs = defs (*Do nothing otherwise*)
paulson@20419
   183
  in  dec_sko (prop_of th) []  end;
paulson@20419
   184
paulson@20419
   185
paulson@20419
   186
(**** REPLACING ABSTRACTIONS BY FUNCTION DEFINITIONS ****)
paulson@20419
   187
paulson@20419
   188
(*Returns the vars of a theorem*)
paulson@20419
   189
fun vars_of_thm th =
paulson@20419
   190
  map (Thm.cterm_of (Thm.theory_of_thm th) o Var) (Drule.fold_terms Term.add_vars th []);
paulson@20419
   191
paulson@20419
   192
(*Make a version of fun_cong with a given variable name*)
paulson@20419
   193
local
paulson@20419
   194
    val fun_cong' = fun_cong RS asm_rl; (*renumber f, g to prevent clashes with (a,0)*)
paulson@20419
   195
    val cx = hd (vars_of_thm fun_cong');
paulson@20419
   196
    val ty = typ_of (ctyp_of_term cx);
paulson@20419
   197
    val thy = Thm.theory_of_thm fun_cong;
paulson@20419
   198
    fun mkvar a = cterm_of thy (Var((a,0),ty));
paulson@20419
   199
in
paulson@20419
   200
fun xfun_cong x = Thm.instantiate ([], [(cx, mkvar x)]) fun_cong'
paulson@20419
   201
end;
paulson@20419
   202
paulson@20419
   203
(*Removes the lambdas from an equation of the form t = (%x. u)*)
paulson@20419
   204
fun strip_lambdas th = 
paulson@20419
   205
  case prop_of th of
paulson@20419
   206
      _ $ (Const ("op =", _) $ _ $ Abs (x,_,_)) => 
paulson@20419
   207
          strip_lambdas (#1 (Drule.freeze_thaw (th RS xfun_cong x)))
paulson@20419
   208
    | _ => th;
paulson@20419
   209
paulson@20419
   210
(*Convert meta- to object-equality. Fails for theorems like split_comp_eq, 
paulson@20419
   211
  where some types have the empty sort.*)
paulson@20419
   212
fun object_eq th = th RS def_imp_eq 
paulson@20419
   213
    handle THM _ => error ("Theorem contains empty sort: " ^ string_of_thm th);
paulson@20419
   214
  
paulson@20419
   215
fun valid_name vs (Free(x,T)) = x mem_string vs
paulson@20419
   216
  | valid_name vs _ = false;
paulson@20419
   217
paulson@20419
   218
(*Contract all eta-redexes in the theorem, lest they give rise to needless abstractions*)
paulson@20419
   219
fun eta_conversion_rule th =
paulson@20419
   220
  equal_elim (eta_conversion (cprop_of th)) th;
paulson@20419
   221
  
paulson@20419
   222
fun crhs th =
paulson@20419
   223
  case Drule.strip_comb (cprop_of th) of
paulson@20419
   224
      (f, [_, rhs]) => 
paulson@20419
   225
          (case term_of f of
paulson@20419
   226
               Const ("==", _) => rhs
paulson@20419
   227
             | _ => raise THM ("crhs", 0, [th]))
paulson@20419
   228
    | _ => raise THM ("crhs", 1, [th]);
paulson@20419
   229
paulson@20419
   230
(*Apply a function definition to an argument, beta-reducing the result.*)
paulson@20419
   231
fun beta_comb cf x =
paulson@20419
   232
  let val th1 = combination cf (reflexive x)
paulson@20419
   233
      val th2 = beta_conversion false (crhs th1)
paulson@20419
   234
  in  transitive th1 th2  end;
paulson@20419
   235
paulson@20419
   236
(*Apply a function definition to arguments, beta-reducing along the way.*)
paulson@20419
   237
fun list_combination cf [] = cf
paulson@20419
   238
  | list_combination cf (x::xs) = list_combination (beta_comb cf x) xs;
paulson@20419
   239
paulson@20419
   240
fun list_cabs ([] ,     t) = t
paulson@20419
   241
  | list_cabs (v::vars, t) = Thm.cabs v (list_cabs(vars,t));
paulson@20419
   242
paulson@20419
   243
(*FIXME DELETE*)
paulson@20419
   244
fun check_eta ct = 
paulson@20419
   245
  let val t = term_of ct 
paulson@20419
   246
  in if (t aconv Envir.eta_contract t) then ()  
paulson@20419
   247
     else error ("Eta redex in term: " ^ string_of_cterm ct)
paulson@20419
   248
  end;
paulson@20419
   249
paulson@20419
   250
(*Traverse a theorem, declaring abstraction function definitions. String s is the suggested
paulson@20419
   251
  prefix for the constants. Resulting theory is returned in the first theorem. *)
paulson@20419
   252
fun declare_absfuns th =
paulson@20419
   253
  let fun abstract thy ct = case term_of ct of
paulson@20419
   254
          Abs (_,T,u) =>
paulson@20419
   255
	    let val cname = gensym "abs_"
paulson@20419
   256
	        val _ = check_eta ct;
paulson@20419
   257
		val (cv,cta) = Thm.dest_abs NONE ct
paulson@20419
   258
		val v = (#1 o dest_Free o term_of) cv
paulson@20419
   259
		val (u'_th,defs) = abstract thy cta
paulson@20419
   260
                val cu' = crhs u'_th
paulson@20419
   261
		val abs_v_u = lambda (term_of cv) (term_of cu')
paulson@20419
   262
		(*get the formal parameters: ALL variables free in the term*)
paulson@20419
   263
		val args = term_frees abs_v_u
paulson@20419
   264
		val Ts = map type_of args
paulson@20419
   265
		val cT = Ts ---> (T --> typ_of (ctyp_of_term cu'))
paulson@20419
   266
		val thy = theory_of_thm u'_th
paulson@20419
   267
		val c = Const (Sign.full_name thy cname, cT)
paulson@20419
   268
		val thy = Theory.add_consts_i [(cname, cT, NoSyn)] thy
paulson@20419
   269
		           (*Theory is augmented with the constant, then its def*)
paulson@20419
   270
		val rhs = list_abs_free (map dest_Free args, abs_v_u)
paulson@20419
   271
		      (*Forms a lambda-abstraction over the formal parameters*)
paulson@20419
   272
		val cdef = cname ^ "_def"
paulson@20419
   273
		val thy = Theory.add_defs_i false false [(cdef, equals cT $ c $ rhs)] thy		      
paulson@20419
   274
		val def = #1 (Drule.freeze_thaw (get_axiom thy cdef))
paulson@20419
   275
		val def_args = list_combination def (map (cterm_of thy) args)
paulson@20419
   276
	    in (transitive (abstract_rule v cv u'_th) (symmetric def_args), 
paulson@20419
   277
	        def :: defs) end
paulson@20419
   278
	| (t1$t2) =>
paulson@20419
   279
	    let val (ct1,ct2) = Thm.dest_comb ct
paulson@20419
   280
	        val (th1,defs1) = abstract thy ct1
paulson@20419
   281
		val (th2,defs2) = abstract (theory_of_thm th1) ct2
paulson@20419
   282
	    in  (combination th1 th2, defs1@defs2)  end
paulson@20419
   283
	| _ => (transfer thy (reflexive ct), [])
paulson@20419
   284
      val _ = if !trace_abs then warning (string_of_thm th) else ();
paulson@20419
   285
      val (eqth,defs) = abstract (theory_of_thm th) (cprop_of th)
paulson@20419
   286
      val ths = equal_elim eqth th ::
paulson@20419
   287
                map (forall_intr_vars o strip_lambdas o object_eq) defs
paulson@20419
   288
  in  (theory_of_thm eqth, ths)  end;
paulson@20419
   289
paulson@20419
   290
fun assume_absfuns th =
paulson@20419
   291
  let val cterm = cterm_of (Thm.theory_of_thm th)
paulson@20419
   292
      fun abstract vs ct = case term_of ct of
paulson@20419
   293
          Abs (_,T,u) =>
paulson@20419
   294
	    let val (cv,cta) = Thm.dest_abs NONE ct
paulson@20419
   295
	        val _ = check_eta ct;
paulson@20419
   296
		val v = (#1 o dest_Free o term_of) cv
paulson@20419
   297
		val (u'_th,defs) = abstract (v::vs) cta
paulson@20419
   298
                val cu' = crhs u'_th
paulson@20419
   299
		val abs_v_u = Thm.cabs cv cu'
paulson@20419
   300
		(*get the formal parameters: bound variables also present in the term*)
paulson@20419
   301
		val args = filter (valid_name vs) (term_frees (term_of abs_v_u))
paulson@20419
   302
		val Ts = map type_of args
paulson@20419
   303
		val const_ty = Ts ---> (T --> typ_of (ctyp_of_term cu'))
paulson@20419
   304
		val c = Free (gensym "abs_", const_ty)
paulson@20419
   305
		val rhs = list_cabs (map cterm args, abs_v_u)
paulson@20419
   306
		      (*Forms a lambda-abstraction over the formal parameters*)
paulson@20419
   307
		val def = assume (Thm.capply (cterm (equals const_ty $ c)) rhs)
paulson@20419
   308
		val def_args = list_combination def (map cterm args)
paulson@20419
   309
	    in (transitive (abstract_rule v cv u'_th) (symmetric def_args), 
paulson@20419
   310
	        def :: defs) end
paulson@20419
   311
	| (t1$t2) =>
paulson@20419
   312
	    let val (ct1,ct2) = Thm.dest_comb ct
paulson@20419
   313
	        val (t1',defs1) = abstract vs ct1
paulson@20419
   314
		val (t2',defs2) = abstract vs ct2
paulson@20419
   315
	    in  (combination t1' t2', defs1@defs2)  end
paulson@20419
   316
	| _ => (reflexive ct, [])
paulson@20419
   317
      val (eqth,defs) = abstract [] (cprop_of th)
paulson@20419
   318
  in  equal_elim eqth th ::
paulson@20419
   319
      map (forall_intr_vars o strip_lambdas o object_eq) defs
paulson@20419
   320
  end;
paulson@20419
   321
paulson@16009
   322
paulson@16009
   323
(*cterms are used throughout for efficiency*)
paulson@18141
   324
val cTrueprop = Thm.cterm_of HOL.thy HOLogic.Trueprop;
paulson@16009
   325
paulson@16009
   326
(*cterm version of mk_cTrueprop*)
paulson@16009
   327
fun c_mkTrueprop A = Thm.capply cTrueprop A;
paulson@16009
   328
paulson@16009
   329
(*Given an abstraction over n variables, replace the bound variables by free
paulson@16009
   330
  ones. Return the body, along with the list of free variables.*)
paulson@16009
   331
fun c_variant_abs_multi (ct0, vars) = 
paulson@16009
   332
      let val (cv,ct) = Thm.dest_abs NONE ct0
paulson@16009
   333
      in  c_variant_abs_multi (ct, cv::vars)  end
paulson@16009
   334
      handle CTERM _ => (ct0, rev vars);
paulson@16009
   335
paulson@16009
   336
(*Given the definition of a Skolem function, return a theorem to replace 
paulson@18141
   337
  an existential formula by a use of that function. 
paulson@18141
   338
   Example: "EX x. x : A & x ~: B ==> sko A B : A & sko A B ~: B"  [.] *)
paulson@16588
   339
fun skolem_of_def def =  
wenzelm@20292
   340
  let val (c,rhs) = Drule.dest_equals (cprop_of (#1 (Drule.freeze_thaw def)))
paulson@16009
   341
      val (ch, frees) = c_variant_abs_multi (rhs, [])
paulson@18141
   342
      val (chilbert,cabs) = Thm.dest_comb ch
paulson@18141
   343
      val {sign,t, ...} = rep_cterm chilbert
paulson@18141
   344
      val T = case t of Const ("Hilbert_Choice.Eps", Type("fun",[_,T])) => T
paulson@18141
   345
                      | _ => raise THM ("skolem_of_def: expected Eps", 0, [def])
paulson@16009
   346
      val cex = Thm.cterm_of sign (HOLogic.exists_const T)
paulson@16009
   347
      val ex_tm = c_mkTrueprop (Thm.capply cex cabs)
paulson@16009
   348
      and conc =  c_mkTrueprop (Drule.beta_conv cabs (Drule.list_comb(c,frees)));
paulson@18141
   349
      fun tacf [prem] = rewrite_goals_tac [def] THEN rtac (prem RS someI_ex) 1
paulson@18141
   350
  in  Goal.prove_raw [ex_tm] conc tacf 
paulson@18141
   351
       |> forall_intr_list frees
paulson@18141
   352
       |> forall_elim_vars 0  (*Introduce Vars, but don't discharge defs.*)
paulson@18141
   353
       |> Thm.varifyT
paulson@18141
   354
  end;
paulson@16009
   355
mengj@18198
   356
(*Converts an Isabelle theorem (intro, elim or simp format) into nnf.*)
mengj@18198
   357
(*It now works for HOL too. *)
paulson@18141
   358
fun to_nnf th = 
paulson@18141
   359
    th |> transfer_to_Reconstruction
paulson@20419
   360
       |> transform_elim |> zero_var_indexes |> Drule.freeze_thaw |> #1
paulson@16588
   361
       |> ObjectLogic.atomize_thm |> make_nnf;
paulson@16009
   362
paulson@16009
   363
(*The cache prevents repeated clausification of a theorem, 
paulson@18510
   364
  and also repeated declaration of Skolem functions*)  
paulson@18510
   365
  (* FIXME better use Termtab!? No, we MUST use theory data!!*)
paulson@15955
   366
val clause_cache = ref (Symtab.empty : (thm * thm list) Symtab.table)
paulson@15955
   367
paulson@18141
   368
paulson@18141
   369
(*Generate Skolem functions for a theorem supplied in nnf*)
paulson@18141
   370
fun skolem_of_nnf th =
paulson@18141
   371
  map (skolem_of_def o assume o (cterm_of (theory_of_thm th))) (assume_skofuns th);
paulson@18141
   372
paulson@20419
   373
(*Replace lambdas by assumed function definitions in the theorems*)
paulson@20419
   374
fun assume_abstract ths =
paulson@20419
   375
  if abstract_lambdas then List.concat (map (assume_absfuns o eta_conversion_rule) ths)
paulson@20419
   376
  else map eta_conversion_rule ths;
paulson@20419
   377
paulson@20419
   378
(*Replace lambdas by declared function definitions in the theorems*)
paulson@20419
   379
fun declare_abstract' (thy, []) = (thy, [])
paulson@20419
   380
  | declare_abstract' (thy, th::ths) =
paulson@20419
   381
      let val (thy', th_defs) = 
paulson@20419
   382
            th |> zero_var_indexes |> Drule.freeze_thaw |> #1
paulson@20419
   383
               |> eta_conversion_rule |> transfer thy |> declare_absfuns
paulson@20419
   384
	  val (thy'', ths') = declare_abstract' (thy', ths)
paulson@20419
   385
      in  (thy'', th_defs @ ths')  end;
paulson@20419
   386
paulson@20419
   387
(*FIXME DELETE*)
paulson@20419
   388
fun declare_abstract (thy, ths) =
paulson@20419
   389
  if abstract_lambdas then declare_abstract' (thy, ths)
paulson@20419
   390
  else (thy, map eta_conversion_rule ths);
paulson@20419
   391
paulson@18510
   392
(*Skolemize a named theorem, with Skolem functions as additional premises.*)
mengj@18198
   393
(*also works for HOL*) 
paulson@18141
   394
fun skolem_thm th = 
paulson@18510
   395
  let val nnfth = to_nnf th
paulson@20419
   396
  in  Meson.make_cnf (skolem_of_nnf nnfth) nnfth
paulson@20419
   397
      |> assume_abstract |> Meson.finish_cnf |> rm_redundant_cls
paulson@18510
   398
  end
paulson@18510
   399
  handle THM _ => [];
paulson@18141
   400
paulson@18510
   401
(*Declare Skolem functions for a theorem, supplied in nnf and with its name.
paulson@18510
   402
  It returns a modified theory, unless skolemization fails.*)
paulson@16009
   403
fun skolem thy (name,th) =
paulson@20419
   404
  let val cname = (case name of "" => gensym "" | s => Sign.base_name s)
paulson@20419
   405
      val _ = Output.debug ("skolemizing " ^ name ^ ": ")
paulson@18141
   406
  in Option.map 
paulson@18141
   407
        (fn nnfth => 
paulson@18141
   408
          let val (thy',defs) = declare_skofuns cname nnfth thy
paulson@20419
   409
              val cnfs = Meson.make_cnf (map skolem_of_def defs) nnfth
paulson@20419
   410
              val (thy'',cnfs') = declare_abstract (thy',cnfs)
paulson@20419
   411
          in (thy'', rm_redundant_cls (Meson.finish_cnf cnfs'))
paulson@20419
   412
          end)
mengj@18198
   413
      (SOME (to_nnf th)  handle THM _ => NONE) 
paulson@18141
   414
  end;
paulson@16009
   415
paulson@18510
   416
(*Populate the clause cache using the supplied theorem. Return the clausal form
paulson@18510
   417
  and modified theory.*)
paulson@18510
   418
fun skolem_cache_thm ((name,th), thy) = 
paulson@18144
   419
  case Symtab.lookup (!clause_cache) name of
paulson@18144
   420
      NONE => 
paulson@18144
   421
	(case skolem thy (name, Thm.transfer thy th) of
paulson@18510
   422
	     NONE => ([th],thy)
paulson@18144
   423
	   | SOME (thy',cls) => 
paulson@18510
   424
	       (change clause_cache (Symtab.update (name, (th, cls))); (cls,thy')))
paulson@18144
   425
    | SOME (th',cls) =>
paulson@18510
   426
        if eq_thm(th,th') then (cls,thy)
paulson@19232
   427
	else (Output.debug ("skolem_cache: Ignoring variant of theorem " ^ name); 
paulson@19232
   428
	      Output.debug (string_of_thm th);
paulson@19232
   429
	      Output.debug (string_of_thm th');
paulson@18510
   430
	      ([th],thy));
paulson@18510
   431
	      
paulson@18510
   432
fun skolem_cache ((name,th), thy) = #2 (skolem_cache_thm ((name,th), thy));
paulson@18141
   433
paulson@16009
   434
paulson@16009
   435
(*Exported function to convert Isabelle theorems into axiom clauses*) 
paulson@19894
   436
fun cnf_axiom (name,th) =
paulson@18144
   437
  case name of
paulson@19894
   438
	"" => skolem_thm th (*no name, so can't cache*)
paulson@18144
   439
      | s  => case Symtab.lookup (!clause_cache) s of
paulson@18144
   440
		NONE => 
paulson@19894
   441
		  let val cls = skolem_thm th
paulson@18144
   442
		  in change clause_cache (Symtab.update (s, (th, cls))); cls end
paulson@18144
   443
	      | SOME(th',cls) =>
paulson@18144
   444
		  if eq_thm(th,th') then cls
paulson@19232
   445
		  else (Output.debug ("cnf_axiom: duplicate or variant of theorem " ^ name); 
paulson@19232
   446
		        Output.debug (string_of_thm th);
paulson@19232
   447
		        Output.debug (string_of_thm th');
paulson@18144
   448
		        cls);
paulson@15347
   449
paulson@18141
   450
fun pairname th = (Thm.name_of_thm th, th);
paulson@18141
   451
paulson@15956
   452
fun meta_cnf_axiom th = 
paulson@15956
   453
    map Meson.make_meta_clause (cnf_axiom (pairname th));
paulson@15499
   454
paulson@15347
   455
paulson@15872
   456
(**** Extract and Clausify theorems from a theory's claset and simpset ****)
paulson@15347
   457
paulson@17404
   458
(*Preserve the name of "th" after the transformation "f"*)
paulson@17404
   459
fun preserve_name f th = Thm.name_thm (Thm.name_of_thm th, f th);
paulson@17404
   460
paulson@17484
   461
fun rules_of_claset cs =
paulson@17484
   462
  let val {safeIs,safeEs,hazIs,hazEs,...} = rep_cs cs
paulson@19175
   463
      val intros = safeIs @ hazIs
wenzelm@18532
   464
      val elims  = map Classical.classical_rule (safeEs @ hazEs)
paulson@17404
   465
  in
wenzelm@18680
   466
     Output.debug ("rules_of_claset intros: " ^ Int.toString(length intros) ^ 
paulson@17484
   467
            " elims: " ^ Int.toString(length elims));
paulson@20017
   468
     map pairname (intros @ elims)
paulson@17404
   469
  end;
paulson@15347
   470
paulson@17484
   471
fun rules_of_simpset ss =
paulson@17484
   472
  let val ({rules,...}, _) = rep_ss ss
paulson@17484
   473
      val simps = Net.entries rules
paulson@17484
   474
  in 
wenzelm@18680
   475
      Output.debug ("rules_of_simpset: " ^ Int.toString(length simps));
paulson@17484
   476
      map (fn r => (#name r, #thm r)) simps
paulson@17484
   477
  end;
paulson@17484
   478
paulson@17484
   479
fun claset_rules_of_thy thy = rules_of_claset (claset_of thy);
paulson@17484
   480
fun simpset_rules_of_thy thy = rules_of_simpset (simpset_of thy);
paulson@17484
   481
mengj@19196
   482
fun atpset_rules_of_thy thy = map pairname (ResAtpSet.atp_rules_of_thy thy);
mengj@19196
   483
mengj@19196
   484
paulson@17484
   485
fun claset_rules_of_ctxt ctxt = rules_of_claset (local_claset_of ctxt);
paulson@17484
   486
fun simpset_rules_of_ctxt ctxt = rules_of_simpset (local_simpset_of ctxt);
paulson@15347
   487
mengj@19196
   488
fun atpset_rules_of_ctxt ctxt = map pairname (ResAtpSet.atp_rules_of_ctxt ctxt);
paulson@15347
   489
paulson@15872
   490
(**** Translate a set of classical/simplifier rules into CNF (still as type "thm")  ****)
paulson@15347
   491
paulson@19894
   492
(* classical rules: works for both FOL and HOL *)
paulson@19894
   493
fun cnf_rules [] err_list = ([],err_list)
paulson@19894
   494
  | cnf_rules ((name,th) :: ths) err_list = 
paulson@19894
   495
      let val (ts,es) = cnf_rules ths err_list
paulson@17404
   496
      in  (cnf_axiom (name,th) :: ts,es) handle  _ => (ts, (th::es))  end;  
paulson@15347
   497
paulson@19894
   498
fun pair_name_cls k (n, []) = []
paulson@19894
   499
  | pair_name_cls k (n, cls::clss) = (cls, (n,k)) :: pair_name_cls (k+1) (n, clss)
paulson@19894
   500
 	    
paulson@19894
   501
fun cnf_rules_pairs_aux pairs [] = pairs
paulson@19894
   502
  | cnf_rules_pairs_aux pairs ((name,th)::ths) =
paulson@19894
   503
      let val pairs' = (pair_name_cls 0 (name, cnf_axiom(name,th))) :: pairs
paulson@19894
   504
		       handle THM _ => pairs | ResClause.CLAUSE _ => pairs
paulson@19894
   505
			    | ResHolClause.LAM2COMB _ => pairs
paulson@19894
   506
      in  cnf_rules_pairs_aux pairs' ths  end;
mengj@19353
   507
    
paulson@19894
   508
val cnf_rules_pairs = cnf_rules_pairs_aux [];
mengj@19353
   509
mengj@19196
   510
mengj@18198
   511
(**** Convert all theorems of a claset/simpset into clauses (ResClause.clause, or ResHolClause.clause) ****)
paulson@15347
   512
paulson@20419
   513
(*Setup function: takes a theory and installs ALL known theorems into the clause cache*)
paulson@20419
   514
fun clause_cache_setup thy = List.foldl skolem_cache thy (PureThy.all_thms_of thy);
paulson@16009
   515
  
paulson@16563
   516
paulson@16563
   517
(*** meson proof methods ***)
paulson@16563
   518
paulson@16563
   519
fun cnf_rules_of_ths ths = List.concat (#1 (cnf_rules (map pairname ths) []));
paulson@16563
   520
paulson@16563
   521
fun meson_meth ths ctxt =
paulson@16563
   522
  Method.SIMPLE_METHOD' HEADGOAL
paulson@16563
   523
    (CHANGED_PROP o Meson.meson_claset_tac (cnf_rules_of_ths ths) (local_claset_of ctxt));
paulson@16563
   524
paulson@16563
   525
val meson_method_setup =
wenzelm@18708
   526
  Method.add_methods
wenzelm@18708
   527
    [("meson", Method.thms_ctxt_args meson_meth, 
wenzelm@18833
   528
      "MESON resolution proof procedure")];
paulson@15347
   529
paulson@18510
   530
paulson@18510
   531
paulson@18510
   532
(*** The Skolemization attribute ***)
paulson@18510
   533
paulson@18510
   534
fun conj2_rule (th1,th2) = conjI OF [th1,th2];
paulson@18510
   535
paulson@18510
   536
(*Conjoin a list of clauses to recreate a single theorem*)
paulson@18510
   537
val conj_rule = foldr1 conj2_rule;
paulson@18510
   538
paulson@20419
   539
fun skolem_attr (Context.Theory thy, th) =
paulson@20419
   540
      let val name = Thm.name_of_thm th
paulson@20419
   541
          val (cls, thy') = skolem_cache_thm ((name, th), thy)
wenzelm@18728
   542
      in (Context.Theory thy', conj_rule cls) end
paulson@20419
   543
  | skolem_attr (context, th) = (context, conj_rule (skolem_thm th));
paulson@18510
   544
paulson@18510
   545
val setup_attrs = Attrib.add_attributes
paulson@20419
   546
  [("skolem", Attrib.no_args skolem_attr, "skolemization of a theorem")];
paulson@18510
   547
wenzelm@18708
   548
val setup = clause_cache_setup #> setup_attrs;
paulson@18510
   549
paulson@15347
   550
end;