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