src/HOL/Tools/res_axioms.ML
author haftmann
Tue May 09 10:09:37 2006 +0200 (2006-05-09)
changeset 19599 a5c7eb37d14f
parent 19442 ad8bb8346e51
child 19630 d370c3f5d3b2
permissions -rw-r--r--
added DatatypeHooks
     1 (*  Author: Jia Meng, Cambridge University Computer Laboratory
     2     ID: $Id$
     3     Copyright 2004 University of Cambridge
     4 
     5 Transformation of axiom rules (elim/intro/etc) into CNF forms.    
     6 *)
     7 
     8 signature RES_AXIOMS =
     9   sig
    10   exception ELIMR2FOL of string
    11   val tagging_enabled : bool
    12   val elimRule_tac : thm -> Tactical.tactic
    13   val elimR2Fol : thm -> term
    14   val transform_elim : thm -> thm
    15   val cnf_axiom : (string * thm) -> thm list
    16   val meta_cnf_axiom : thm -> thm list
    17   val claset_rules_of_thy : theory -> (string * thm) list
    18   val simpset_rules_of_thy : theory -> (string * thm) list
    19   val claset_rules_of_ctxt: Proof.context -> (string * thm) list
    20   val simpset_rules_of_ctxt : Proof.context -> (string * thm) list
    21   val pairname : thm -> (string * thm)
    22   val skolem_thm : thm -> thm list
    23   val cnf_rules_pairs : (string * Thm.thm) list -> (Thm.thm * (string * int)) list list;
    24   val meson_method_setup : theory -> theory
    25   val setup : theory -> theory
    26 
    27   val atpset_rules_of_thy : theory -> (string * thm) list
    28   val atpset_rules_of_ctxt : Proof.context -> (string * thm) list
    29   end;
    30 
    31 structure ResAxioms : RES_AXIOMS =
    32  
    33 struct
    34 
    35 
    36 val tagging_enabled = false (*compile_time option*)
    37 
    38 (**** Transformation of Elimination Rules into First-Order Formulas****)
    39 
    40 (* a tactic used to prove an elim-rule. *)
    41 fun elimRule_tac th =
    42     ((rtac impI 1) ORELSE (rtac notI 1)) THEN (etac th 1) THEN
    43     REPEAT(fast_tac HOL_cs 1);
    44 
    45 exception ELIMR2FOL of string;
    46 
    47 (* functions used to construct a formula *)
    48 
    49 fun make_disjs [x] = x
    50   | make_disjs (x :: xs) = HOLogic.mk_disj(x, make_disjs xs)
    51 
    52 fun make_conjs [x] = x
    53   | make_conjs (x :: xs) =  HOLogic.mk_conj(x, make_conjs xs)
    54 
    55 fun add_EX tm [] = tm
    56   | add_EX tm ((x,xtp)::xs) = add_EX (HOLogic.exists_const xtp $ Abs(x,xtp,tm)) xs;
    57 
    58 fun is_neg (Const("Trueprop",_) $ (Const("Not",_) $ Free(p,_))) (Const("Trueprop",_) $ Free(q,_)) = (p = q)
    59   | is_neg _ _ = false;
    60 
    61 
    62 exception STRIP_CONCL;
    63 
    64 
    65 fun strip_concl' prems bvs (Const ("==>",_) $ P $ Q) =
    66       let val P' = HOLogic.dest_Trueprop P
    67   	  val prems' = P'::prems
    68       in
    69 	strip_concl' prems' bvs  Q
    70       end
    71   | strip_concl' prems bvs P = 
    72       let val P' = HOLogic.Not $ (HOLogic.dest_Trueprop P)
    73       in
    74 	add_EX (make_conjs (P'::prems)) bvs
    75       end;
    76 
    77 
    78 fun strip_concl prems bvs concl (Const ("all", _) $ Abs (x,xtp,body)) = 
    79       strip_concl prems ((x,xtp)::bvs) concl body
    80   | strip_concl prems bvs concl (Const ("==>",_) $ P $ Q) =
    81       if (is_neg P concl) then (strip_concl' prems bvs Q)
    82       else strip_concl (HOLogic.dest_Trueprop P::prems) bvs  concl Q
    83   | strip_concl prems bvs concl _ = add_EX (make_conjs prems) bvs;
    84  
    85 
    86 fun trans_elim (main,others,concl) =
    87     let val others' = map (strip_concl [] [] concl) others
    88 	val disjs = make_disjs others'
    89     in
    90 	HOLogic.mk_imp (HOLogic.dest_Trueprop main, disjs)
    91     end;
    92 
    93 
    94 (* aux function of elim2Fol, take away predicate variable. *)
    95 fun elimR2Fol_aux prems concl = 
    96     let val nprems = length prems
    97 	val main = hd prems
    98     in
    99 	if (nprems = 1) then HOLogic.Not $ (HOLogic.dest_Trueprop main)
   100         else trans_elim (main, tl prems, concl)
   101     end;
   102 
   103     
   104 (* convert an elim rule into an equivalent formula, of type term. *)
   105 fun elimR2Fol elimR = 
   106     let val elimR' = Drule.freeze_all elimR
   107 	val (prems,concl) = (prems_of elimR', concl_of elimR')
   108     in
   109 	case concl of Const("Trueprop",_) $ Free(_,Type("bool",[])) 
   110 		      => HOLogic.mk_Trueprop (elimR2Fol_aux prems concl)
   111                     | Free(x,Type("prop",[])) => HOLogic.mk_Trueprop(elimR2Fol_aux prems concl) 
   112 		    | _ => raise ELIMR2FOL("Not an elimination rule!")
   113     end;
   114 
   115 
   116 (* check if a rule is an elim rule *)
   117 fun is_elimR th = 
   118     case (concl_of th) of (Const ("Trueprop", _) $ Var (idx,_)) => true
   119 			 | Var(indx,Type("prop",[])) => true
   120 			 | _ => false;
   121 
   122 (* convert an elim-rule into an equivalent theorem that does not have the 
   123    predicate variable.  Leave other theorems unchanged.*) 
   124 fun transform_elim th =
   125   if is_elimR th then
   126     let val tm = elimR2Fol th
   127 	val ctm = cterm_of (sign_of_thm th) tm	
   128     in Goal.prove_raw [] ctm (fn _ => elimRule_tac th) end
   129  else th;
   130 
   131 
   132 (**** Transformation of Clasets and Simpsets into First-Order Axioms ****)
   133 
   134 
   135 (*Transfer a theorem into theory Reconstruction.thy if it is not already
   136   inside that theory -- because it's needed for Skolemization *)
   137 
   138 (*This will refer to the final version of theory Reconstruction.*)
   139 val recon_thy_ref = Theory.self_ref (the_context ());  
   140 
   141 (*If called while Reconstruction is being created, it will transfer to the
   142   current version. If called afterward, it will transfer to the final version.*)
   143 fun transfer_to_Reconstruction th =
   144     transfer (Theory.deref recon_thy_ref) th handle THM _ => th;
   145 
   146 fun is_taut th =
   147       case (prop_of th) of
   148            (Const ("Trueprop", _) $ Const ("True", _)) => true
   149          | _ => false;
   150 
   151 (* remove tautologous clauses *)
   152 val rm_redundant_cls = List.filter (not o is_taut);
   153      
   154        
   155 (**** SKOLEMIZATION BY INFERENCE (lcp) ****)
   156 
   157 (*Traverse a theorem, declaring Skolem function definitions. String s is the suggested
   158   prefix for the Skolem constant. Result is a new theory*)
   159 fun declare_skofuns s th thy =
   160   let fun dec_sko (Const ("Ex",_) $ (xtp as Abs(_,T,p))) (n, (thy, axs)) =
   161 	    (*Existential: declare a Skolem function, then insert into body and continue*)
   162 	    let val cname = s ^ "_" ^ Int.toString n
   163 		val args = term_frees xtp  (*get the formal parameter list*)
   164 		val Ts = map type_of args
   165 		val cT = Ts ---> T
   166 		val c = Const (Sign.full_name thy cname, cT)
   167 		val rhs = list_abs_free (map dest_Free args, HOLogic.choice_const T $ xtp)
   168 		        (*Forms a lambda-abstraction over the formal parameters*)
   169 		val def = equals cT $ c $ rhs
   170 		val thy' = Theory.add_consts_i [(cname, cT, NoSyn)] thy
   171 		           (*Theory is augmented with the constant, then its def*)
   172 		val cdef = cname ^ "_def"
   173 		val thy'' = Theory.add_defs_i false [(cdef, def)] thy'
   174 	    in dec_sko (subst_bound (list_comb(c,args), p)) 
   175 	               (n+1, (thy'', get_axiom thy'' cdef :: axs)) 
   176 	    end
   177 	| dec_sko (Const ("All",_) $ (xtp as Abs(a,T,p))) (n, thx) =
   178 	    (*Universal quant: insert a free variable into body and continue*)
   179 	    let val fname = variant (add_term_names (p,[])) a
   180 	    in dec_sko (subst_bound (Free(fname,T), p)) (n, thx) end
   181 	| dec_sko (Const ("op &", _) $ p $ q) nthy = dec_sko q (dec_sko p nthy)
   182 	| dec_sko (Const ("op |", _) $ p $ q) nthy = dec_sko q (dec_sko p nthy)
   183 	| dec_sko (Const ("HOL.tag", _) $ p) nthy = dec_sko p nthy
   184 	| dec_sko (Const ("Trueprop", _) $ p) nthy = dec_sko p nthy
   185 	| dec_sko t nthx = nthx (*Do nothing otherwise*)
   186   in  #2 (dec_sko (#prop (rep_thm th)) (1, (thy,[])))  end;
   187 
   188 (*Traverse a theorem, accumulating Skolem function definitions.*)
   189 fun assume_skofuns th =
   190   let fun dec_sko (Const ("Ex",_) $ (xtp as Abs(_,T,p))) defs =
   191 	    (*Existential: declare a Skolem function, then insert into body and continue*)
   192 	    let val name = variant (add_term_names (p,[])) (gensym "sko_")
   193                 val skos = map (#1 o Logic.dest_equals) defs  (*existing sko fns*)
   194 		val args = term_frees xtp \\ skos  (*the formal parameters*)
   195 		val Ts = map type_of args
   196 		val cT = Ts ---> T
   197 		val c = Free (name, cT)
   198 		val rhs = list_abs_free (map dest_Free args,        
   199 		                         HOLogic.choice_const T $ xtp)
   200 		      (*Forms a lambda-abstraction over the formal parameters*)
   201 		val def = equals cT $ c $ rhs
   202 	    in dec_sko (subst_bound (list_comb(c,args), p)) 
   203 	               (def :: defs)
   204 	    end
   205 	| dec_sko (Const ("All",_) $ (xtp as Abs(a,T,p))) defs =
   206 	    (*Universal quant: insert a free variable into body and continue*)
   207 	    let val fname = variant (add_term_names (p,[])) a
   208 	    in dec_sko (subst_bound (Free(fname,T), p)) defs end
   209 	| dec_sko (Const ("op &", _) $ p $ q) defs = dec_sko q (dec_sko p defs)
   210 	| dec_sko (Const ("op |", _) $ p $ q) defs = dec_sko q (dec_sko p defs)
   211 	| dec_sko (Const ("HOL.tag", _) $ p) defs = dec_sko p defs
   212 	| dec_sko (Const ("Trueprop", _) $ p) defs = dec_sko p defs
   213 	| dec_sko t defs = defs (*Do nothing otherwise*)
   214   in  dec_sko (#prop (rep_thm th)) []  end;
   215 
   216 (*cterms are used throughout for efficiency*)
   217 val cTrueprop = Thm.cterm_of HOL.thy HOLogic.Trueprop;
   218 
   219 (*cterm version of mk_cTrueprop*)
   220 fun c_mkTrueprop A = Thm.capply cTrueprop A;
   221 
   222 (*Given an abstraction over n variables, replace the bound variables by free
   223   ones. Return the body, along with the list of free variables.*)
   224 fun c_variant_abs_multi (ct0, vars) = 
   225       let val (cv,ct) = Thm.dest_abs NONE ct0
   226       in  c_variant_abs_multi (ct, cv::vars)  end
   227       handle CTERM _ => (ct0, rev vars);
   228 
   229 (*Given the definition of a Skolem function, return a theorem to replace 
   230   an existential formula by a use of that function. 
   231    Example: "EX x. x : A & x ~: B ==> sko A B : A & sko A B ~: B"  [.] *)
   232 fun skolem_of_def def =  
   233   let val (c,rhs) = Drule.dest_equals (cprop_of (Drule.freeze_all def))
   234       val (ch, frees) = c_variant_abs_multi (rhs, [])
   235       val (chilbert,cabs) = Thm.dest_comb ch
   236       val {sign,t, ...} = rep_cterm chilbert
   237       val T = case t of Const ("Hilbert_Choice.Eps", Type("fun",[_,T])) => T
   238                       | _ => raise THM ("skolem_of_def: expected Eps", 0, [def])
   239       val cex = Thm.cterm_of sign (HOLogic.exists_const T)
   240       val ex_tm = c_mkTrueprop (Thm.capply cex cabs)
   241       and conc =  c_mkTrueprop (Drule.beta_conv cabs (Drule.list_comb(c,frees)));
   242       fun tacf [prem] = rewrite_goals_tac [def] THEN rtac (prem RS someI_ex) 1
   243   in  Goal.prove_raw [ex_tm] conc tacf 
   244        |> forall_intr_list frees
   245        |> forall_elim_vars 0  (*Introduce Vars, but don't discharge defs.*)
   246        |> Thm.varifyT
   247   end;
   248 
   249 (*Converts an Isabelle theorem (intro, elim or simp format) into nnf.*)
   250 (*It now works for HOL too. *)
   251 fun to_nnf th = 
   252     th |> transfer_to_Reconstruction
   253        |> transform_elim |> Drule.freeze_all
   254        |> ObjectLogic.atomize_thm |> make_nnf;
   255 
   256 (*The cache prevents repeated clausification of a theorem, 
   257   and also repeated declaration of Skolem functions*)  
   258   (* FIXME better use Termtab!? No, we MUST use theory data!!*)
   259 val clause_cache = ref (Symtab.empty : (thm * thm list) Symtab.table)
   260 
   261 
   262 (*Generate Skolem functions for a theorem supplied in nnf*)
   263 fun skolem_of_nnf th =
   264   map (skolem_of_def o assume o (cterm_of (theory_of_thm th))) (assume_skofuns th);
   265 
   266 (*Skolemize a named theorem, with Skolem functions as additional premises.*)
   267 (*also works for HOL*) 
   268 fun skolem_thm th = 
   269   let val nnfth = to_nnf th
   270   in  rm_redundant_cls (Meson.make_cnf (skolem_of_nnf nnfth) nnfth)
   271   end
   272   handle THM _ => [];
   273 
   274 (*Declare Skolem functions for a theorem, supplied in nnf and with its name.
   275   It returns a modified theory, unless skolemization fails.*)
   276 fun skolem thy (name,th) =
   277   let val cname = (case name of "" => gensym "sko" | s => Sign.base_name s)
   278   in Option.map 
   279         (fn nnfth => 
   280           let val (thy',defs) = declare_skofuns cname nnfth thy
   281               val skoths = map skolem_of_def defs
   282           in (thy', rm_redundant_cls (Meson.make_cnf skoths nnfth)) end)
   283       (SOME (to_nnf th)  handle THM _ => NONE) 
   284   end;
   285 
   286 (*Populate the clause cache using the supplied theorem. Return the clausal form
   287   and modified theory.*)
   288 fun skolem_cache_thm ((name,th), thy) = 
   289   case Symtab.lookup (!clause_cache) name of
   290       NONE => 
   291 	(case skolem thy (name, Thm.transfer thy th) of
   292 	     NONE => ([th],thy)
   293 	   | SOME (thy',cls) => 
   294 	       (change clause_cache (Symtab.update (name, (th, cls))); (cls,thy')))
   295     | SOME (th',cls) =>
   296         if eq_thm(th,th') then (cls,thy)
   297 	else (Output.debug ("skolem_cache: Ignoring variant of theorem " ^ name); 
   298 	      Output.debug (string_of_thm th);
   299 	      Output.debug (string_of_thm th');
   300 	      ([th],thy));
   301 	      
   302 fun skolem_cache ((name,th), thy) = #2 (skolem_cache_thm ((name,th), thy));
   303 
   304 
   305 (*Exported function to convert Isabelle theorems into axiom clauses*) 
   306 fun cnf_axiom_g cnf (name,th) =
   307   case name of
   308 	"" => cnf th (*no name, so can't cache*)
   309       | s  => case Symtab.lookup (!clause_cache) s of
   310 		NONE => 
   311 		  let val cls = cnf th
   312 		  in change clause_cache (Symtab.update (s, (th, cls))); cls end
   313 	      | SOME(th',cls) =>
   314 		  if eq_thm(th,th') then cls
   315 		  else (Output.debug ("cnf_axiom: duplicate or variant of theorem " ^ name); 
   316 		        Output.debug (string_of_thm th);
   317 		        Output.debug (string_of_thm th');
   318 		        cls);
   319 
   320 fun pairname th = (Thm.name_of_thm th, th);
   321 
   322 
   323 val cnf_axiom = cnf_axiom_g skolem_thm;
   324 
   325 
   326 fun meta_cnf_axiom th = 
   327     map Meson.make_meta_clause (cnf_axiom (pairname th));
   328 
   329 
   330 
   331 (**** Extract and Clausify theorems from a theory's claset and simpset ****)
   332 
   333 (*Preserve the name of "th" after the transformation "f"*)
   334 fun preserve_name f th = Thm.name_thm (Thm.name_of_thm th, f th);
   335 
   336 (*Tags identify the major premise or conclusion, as hints to resolution provers.
   337   However, they don't appear to help in recent tests, and they complicate the code.*)
   338 val tagI = thm "tagI";
   339 val tagD = thm "tagD";
   340 
   341 val tag_intro = preserve_name (fn th => th RS tagI);
   342 val tag_elim  = preserve_name (fn th => tagD RS th);
   343 
   344 fun rules_of_claset cs =
   345   let val {safeIs,safeEs,hazIs,hazEs,...} = rep_cs cs
   346       val intros = safeIs @ hazIs
   347       val elims  = map Classical.classical_rule (safeEs @ hazEs)
   348   in
   349      Output.debug ("rules_of_claset intros: " ^ Int.toString(length intros) ^ 
   350             " elims: " ^ Int.toString(length elims));
   351      if tagging_enabled 
   352      then map pairname (map tag_intro intros @ map tag_elim elims)
   353      else map pairname (intros @ elims)
   354   end;
   355 
   356 fun rules_of_simpset ss =
   357   let val ({rules,...}, _) = rep_ss ss
   358       val simps = Net.entries rules
   359   in 
   360       Output.debug ("rules_of_simpset: " ^ Int.toString(length simps));
   361       map (fn r => (#name r, #thm r)) simps
   362   end;
   363 
   364 fun claset_rules_of_thy thy = rules_of_claset (claset_of thy);
   365 fun simpset_rules_of_thy thy = rules_of_simpset (simpset_of thy);
   366 
   367 fun atpset_rules_of_thy thy = map pairname (ResAtpSet.atp_rules_of_thy thy);
   368 
   369 
   370 fun claset_rules_of_ctxt ctxt = rules_of_claset (local_claset_of ctxt);
   371 fun simpset_rules_of_ctxt ctxt = rules_of_simpset (local_simpset_of ctxt);
   372 
   373 fun atpset_rules_of_ctxt ctxt = map pairname (ResAtpSet.atp_rules_of_ctxt ctxt);
   374 
   375 (**** Translate a set of classical/simplifier rules into CNF (still as type "thm")  ****)
   376 
   377 (* classical rules *)
   378 fun cnf_rules_g cnf_axiom [] err_list = ([],err_list)
   379   | cnf_rules_g cnf_axiom ((name,th) :: ths) err_list = 
   380       let val (ts,es) = cnf_rules_g cnf_axiom ths err_list
   381       in  (cnf_axiom (name,th) :: ts,es) handle  _ => (ts, (th::es))  end;  
   382 
   383 
   384 (*works for both FOL and HOL*)
   385 val cnf_rules = cnf_rules_g cnf_axiom;
   386 
   387 fun cnf_rules_pairs_aux [] = []
   388   | cnf_rules_pairs_aux ((name,th)::ths) =
   389     let val ts = cnf_rules_pairs_aux ths
   390 	fun pair_name_cls k (n, []) = []
   391 	  | pair_name_cls k (n, cls::clss) =
   392 	    (cls, (n,k))::(pair_name_cls (k+1) (n, clss))
   393     in
   394 	(pair_name_cls 0 (name, cnf_axiom(name,th)))::ts
   395 	handle THM _ => ts | ResClause.CLAUSE _ => ts | ResHolClause.LAM2COMB _ => ts
   396     end;
   397     
   398 
   399 fun cnf_rules_pairs thms = rev (cnf_rules_pairs_aux thms);
   400 
   401 
   402 (**** Convert all theorems of a claset/simpset into clauses (ResClause.clause, or ResHolClause.clause) ****)
   403 
   404 
   405 (*These should include any plausibly-useful theorems, especially if they need
   406   Skolem functions. FIXME: this list is VERY INCOMPLETE*)
   407 val default_initial_thms = map pairname
   408   [refl_def, antisym_def, sym_def, trans_def, single_valued_def,
   409    subset_refl, Union_least, Inter_greatest];
   410 
   411 (*Setup function: takes a theory and installs ALL simprules and claset rules 
   412   into the clause cache*)
   413 fun clause_cache_setup thy =
   414   let val simps = simpset_rules_of_thy thy
   415       and clas  = claset_rules_of_thy thy
   416       and thy0  = List.foldl skolem_cache thy default_initial_thms
   417       val thy1  = List.foldl skolem_cache thy0 clas
   418   in List.foldl skolem_cache thy1 simps end;
   419 (*Could be duplicate theorem names, due to multiple attributes*)
   420   
   421 
   422 (*** meson proof methods ***)
   423 
   424 fun cnf_rules_of_ths ths = List.concat (#1 (cnf_rules (map pairname ths) []));
   425 
   426 fun meson_meth ths ctxt =
   427   Method.SIMPLE_METHOD' HEADGOAL
   428     (CHANGED_PROP o Meson.meson_claset_tac (cnf_rules_of_ths ths) (local_claset_of ctxt));
   429 
   430 val meson_method_setup =
   431   Method.add_methods
   432     [("meson", Method.thms_ctxt_args meson_meth, 
   433       "MESON resolution proof procedure")];
   434 
   435 
   436 
   437 (*** The Skolemization attribute ***)
   438 
   439 fun conj2_rule (th1,th2) = conjI OF [th1,th2];
   440 
   441 (*Conjoin a list of clauses to recreate a single theorem*)
   442 val conj_rule = foldr1 conj2_rule;
   443 
   444 fun skolem (Context.Theory thy, th) =
   445       let
   446         val name = Thm.name_of_thm th
   447         val (cls, thy') = skolem_cache_thm ((name, th), thy)
   448       in (Context.Theory thy', conj_rule cls) end
   449   | skolem (context, th) = (context, conj_rule (skolem_thm th));
   450 
   451 val setup_attrs = Attrib.add_attributes
   452   [("skolem", Attrib.no_args skolem, "skolemization of a theorem")];
   453 
   454 val setup = clause_cache_setup #> setup_attrs;
   455 
   456 end;