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