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