src/HOL/Tools/res_axioms.ML
author wenzelm
Thu Jun 12 16:41:54 2008 +0200 (2008-06-12)
changeset 27174 c2c484480f40
parent 26939 1035c89b4c02
child 27179 8f29fed3dc9a
permissions -rw-r--r--
declare_skofuns/skolem: canonical argument order;
minor tuning;
     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 cnf_axiom: thm -> thm list
    11   val pairname: thm -> string * thm
    12   val multi_base_blacklist: string list 
    13   val bad_for_atp: thm -> bool
    14   val type_has_empty_sort: typ -> bool
    15   val cnf_rules_pairs: (string * thm) list -> (thm * (string * int)) list
    16   val cnf_rules_of_ths: thm list -> thm list
    17   val neg_clausify: thm list -> thm list
    18   val expand_defs_tac: thm -> tactic
    19   val combinators: thm -> thm
    20   val neg_conjecture_clauses: thm -> int -> thm list * (string * typ) list
    21   val claset_rules_of: Proof.context -> (string * thm) list   (*FIXME DELETE*)
    22   val simpset_rules_of: Proof.context -> (string * thm) list  (*FIXME DELETE*)
    23   val atpset_rules_of: Proof.context -> (string * thm) list
    24   val meson_method_setup: theory -> theory
    25   val clause_cache_endtheory: theory -> theory option
    26   val suppress_endtheory: bool ref     (*for emergency use where endtheory causes problems*)
    27   val setup: theory -> theory
    28 end;
    29 
    30 structure ResAxioms: RES_AXIOMS =
    31 struct
    32 
    33 (* FIXME legacy *)
    34 fun freeze_thm th = #1 (Drule.freeze_thaw th);
    35 
    36 fun type_has_empty_sort (TFree (_, [])) = true
    37   | type_has_empty_sort (TVar (_, [])) = true
    38   | type_has_empty_sort (Type (_, Ts)) = exists type_has_empty_sort Ts
    39   | type_has_empty_sort _ = false;
    40   
    41 (**** Transformation of Elimination Rules into First-Order Formulas****)
    42 
    43 val cfalse = cterm_of HOL.thy HOLogic.false_const;
    44 val ctp_false = cterm_of HOL.thy (HOLogic.mk_Trueprop HOLogic.false_const);
    45 
    46 (*Converts an elim-rule into an equivalent theorem that does not have the
    47   predicate variable.  Leaves other theorems unchanged.  We simply instantiate the
    48   conclusion variable to False.*)
    49 fun transform_elim th =
    50   case concl_of th of    (*conclusion variable*)
    51        Const("Trueprop",_) $ (v as Var(_,Type("bool",[]))) =>
    52            Thm.instantiate ([], [(cterm_of HOL.thy v, cfalse)]) th
    53     | v as Var(_, Type("prop",[])) =>
    54            Thm.instantiate ([], [(cterm_of HOL.thy v, ctp_false)]) th
    55     | _ => th;
    56 
    57 (*To enforce single-threading*)
    58 exception Clausify_failure of theory;
    59 
    60 (**** SKOLEMIZATION BY INFERENCE (lcp) ****)
    61 
    62 fun rhs_extra_types lhsT rhs =
    63   let val lhs_vars = Term.add_tfreesT lhsT []
    64       fun add_new_TFrees (TFree v) =
    65             if member (op =) lhs_vars v then I else insert (op =) (TFree v)
    66         | add_new_TFrees _ = I
    67       val rhs_consts = fold_aterms (fn Const c => insert (op =) c | _ => I) rhs []
    68   in fold (#2 #> Term.fold_atyps add_new_TFrees) rhs_consts [] end;
    69 
    70 (*Traverse a theorem, declaring Skolem function definitions. String s is the suggested
    71   prefix for the Skolem constant.*)
    72 fun declare_skofuns s th =
    73   let
    74     val nref = ref 0
    75     fun dec_sko (Const ("Ex",_) $ (xtp as Abs (_, T, p))) (axs, thy) =
    76           (*Existential: declare a Skolem function, then insert into body and continue*)
    77           let
    78             val cname = "sko_" ^ s ^ "_" ^ Int.toString (inc nref)
    79             val args0 = term_frees xtp  (*get the formal parameter list*)
    80             val Ts = map type_of args0
    81             val extraTs = rhs_extra_types (Ts ---> T) xtp
    82             val _ = if null extraTs then () else
    83               warning ("Skolemization: extra type vars: " ^
    84                 commas_quote (map (Syntax.string_of_typ_global thy) extraTs))
    85             val argsx = map (fn T => Free (gensym "vsk", T)) extraTs
    86             val args = argsx @ args0
    87             val cT = extraTs ---> Ts ---> T
    88             val rhs = list_abs_free (map dest_Free args, HOLogic.choice_const T $ xtp)
    89                     (*Forms a lambda-abstraction over the formal parameters*)
    90             val (c, thy') = Sign.declare_const [Markup.property_internal] (cname, cT, NoSyn) thy
    91             val cdef = cname ^ "_def"
    92             val thy'' = Theory.add_defs_i true false [(cdef, equals cT $ c $ rhs)] thy'
    93               handle ERROR _ => raise Clausify_failure thy'
    94             val ax = Thm.get_axiom_i thy'' (Sign.full_name thy'' cdef)
    95           in dec_sko (subst_bound (list_comb (c, args), p)) (ax :: axs, thy'') end
    96       | dec_sko (Const ("All", _) $ (xtp as Abs (a, T, p))) thx =
    97           (*Universal quant: insert a free variable into body and continue*)
    98           let val fname = Name.variant (add_term_names (p, [])) a
    99           in dec_sko (subst_bound (Free (fname, T), p)) thx end
   100       | dec_sko (Const ("op &", _) $ p $ q) thx = dec_sko q (dec_sko p thx)
   101       | dec_sko (Const ("op |", _) $ p $ q) thx = dec_sko q (dec_sko p thx)
   102       | dec_sko (Const ("Trueprop", _) $ p) thx = dec_sko p thx
   103       | dec_sko t thx = thx (*Do nothing otherwise*)
   104   in fn thy => dec_sko (Thm.prop_of th) ([], thy) end;
   105 
   106 (*Traverse a theorem, accumulating Skolem function definitions.*)
   107 fun assume_skofuns s th =
   108   let val sko_count = ref 0
   109       fun dec_sko (Const ("Ex",_) $ (xtp as Abs(_,T,p))) defs =
   110             (*Existential: declare a Skolem function, then insert into body and continue*)
   111             let val skos = map (#1 o Logic.dest_equals) defs  (*existing sko fns*)
   112                 val args = term_frees xtp \\ skos  (*the formal parameters*)
   113                 val Ts = map type_of args
   114                 val cT = Ts ---> T
   115                 val id = "sko_" ^ s ^ "_" ^ Int.toString (inc sko_count)
   116                 val c = Free (id, cT)
   117                 val rhs = list_abs_free (map dest_Free args,
   118                                          HOLogic.choice_const T $ xtp)
   119                       (*Forms a lambda-abstraction over the formal parameters*)
   120                 val def = equals cT $ c $ rhs
   121             in dec_sko (subst_bound (list_comb(c,args), p))
   122                        (def :: defs)
   123             end
   124         | dec_sko (Const ("All",_) $ (xtp as Abs(a,T,p))) defs =
   125             (*Universal quant: insert a free variable into body and continue*)
   126             let val fname = Name.variant (add_term_names (p,[])) a
   127             in dec_sko (subst_bound (Free(fname,T), p)) defs end
   128         | dec_sko (Const ("op &", _) $ p $ q) defs = dec_sko q (dec_sko p defs)
   129         | dec_sko (Const ("op |", _) $ p $ q) defs = dec_sko q (dec_sko p defs)
   130         | dec_sko (Const ("Trueprop", _) $ p) defs = dec_sko p defs
   131         | dec_sko t defs = defs (*Do nothing otherwise*)
   132   in  dec_sko (prop_of th) []  end;
   133 
   134 
   135 (**** REPLACING ABSTRACTIONS BY COMBINATORS ****)
   136 
   137 (*Returns the vars of a theorem*)
   138 fun vars_of_thm th =
   139   map (Thm.cterm_of (theory_of_thm th) o Var) (Thm.fold_terms Term.add_vars th []);
   140 
   141 (*Make a version of fun_cong with a given variable name*)
   142 local
   143     val fun_cong' = fun_cong RS asm_rl; (*renumber f, g to prevent clashes with (a,0)*)
   144     val cx = hd (vars_of_thm fun_cong');
   145     val ty = typ_of (ctyp_of_term cx);
   146     val thy = theory_of_thm fun_cong;
   147     fun mkvar a = cterm_of thy (Var((a,0),ty));
   148 in
   149 fun xfun_cong x = Thm.instantiate ([], [(cx, mkvar x)]) fun_cong'
   150 end;
   151 
   152 (*Removes the lambdas from an equation of the form t = (%x. u).  A non-negative n,
   153   serves as an upper bound on how many to remove.*)
   154 fun strip_lambdas 0 th = th
   155   | strip_lambdas n th =
   156       case prop_of th of
   157           _ $ (Const ("op =", _) $ _ $ Abs (x,_,_)) =>
   158               strip_lambdas (n-1) (freeze_thm (th RS xfun_cong x))
   159         | _ => th;
   160 
   161 val lambda_free = not o Term.has_abs;
   162 
   163 val monomorphic = not o Term.exists_type (Term.exists_subtype Term.is_TVar);
   164 
   165 val abs_S = @{thm"abs_S"};
   166 val abs_K = @{thm"abs_K"};
   167 val abs_I = @{thm"abs_I"};
   168 val abs_B = @{thm"abs_B"};
   169 val abs_C = @{thm"abs_C"};
   170 
   171 val [f_B,g_B] = map (cterm_of @{theory}) (term_vars (prop_of abs_B));
   172 val [g_C,f_C] = map (cterm_of @{theory}) (term_vars (prop_of abs_C));
   173 val [f_S,g_S] = map (cterm_of @{theory}) (term_vars (prop_of abs_S));
   174 
   175 (*FIXME: requires more use of cterm constructors*)
   176 fun abstract ct =
   177   let val _ = Output.debug (fn()=>"  abstraction: " ^ Display.string_of_cterm ct)
   178       val Abs(x,_,body) = term_of ct
   179       val thy = theory_of_cterm ct
   180       val Type("fun",[xT,bodyT]) = typ_of (ctyp_of_term ct)
   181       val cxT = ctyp_of thy xT and cbodyT = ctyp_of thy bodyT
   182       fun makeK() = instantiate' [SOME cxT, SOME cbodyT] [SOME (cterm_of thy body)] abs_K
   183   in
   184       case body of
   185           Const _ => makeK()
   186         | Free _ => makeK()
   187         | Var _ => makeK()  (*though Var isn't expected*)
   188         | Bound 0 => instantiate' [SOME cxT] [] abs_I (*identity: I*)
   189         | rator$rand =>
   190 	    if loose_bvar1 (rator,0) then (*C or S*) 
   191 	       if loose_bvar1 (rand,0) then (*S*)
   192 	         let val crator = cterm_of thy (Abs(x,xT,rator))
   193 	             val crand = cterm_of thy (Abs(x,xT,rand))
   194 	             val abs_S' = cterm_instantiate [(f_S,crator),(g_S,crand)] abs_S
   195 	             val (_,rhs) = Thm.dest_equals (cprop_of abs_S') 
   196 	         in
   197 	           Thm.transitive abs_S' (Conv.binop_conv abstract rhs)
   198 	         end
   199 	       else (*C*)
   200 	         let val crator = cterm_of thy (Abs(x,xT,rator))
   201 	             val abs_C' = cterm_instantiate [(f_C,crator),(g_C,cterm_of thy rand)] abs_C
   202 	             val (_,rhs) = Thm.dest_equals (cprop_of abs_C') 
   203 	         in
   204 	           Thm.transitive abs_C' (Conv.fun_conv (Conv.arg_conv abstract) rhs)
   205 	         end
   206 	    else if loose_bvar1 (rand,0) then (*B or eta*) 
   207 	       if rand = Bound 0 then eta_conversion ct
   208 	       else (*B*)
   209 	         let val crand = cterm_of thy (Abs(x,xT,rand))
   210 	             val crator = cterm_of thy rator
   211 	             val abs_B' = cterm_instantiate [(f_B,crator),(g_B,crand)] abs_B
   212 	             val (_,rhs) = Thm.dest_equals (cprop_of abs_B') 
   213 	         in
   214 	           Thm.transitive abs_B' (Conv.arg_conv abstract rhs)
   215 	         end
   216 	    else makeK()
   217         | _ => error "abstract: Bad term"
   218   end;
   219 
   220 (*Traverse a theorem, declaring abstraction function definitions. String s is the suggested
   221   prefix for the constants. Resulting theory is returned in the first theorem. *)
   222 fun combinators_aux ct =
   223   if lambda_free (term_of ct) then reflexive ct
   224   else
   225   case term_of ct of
   226       Abs _ =>
   227 	let val (cv,cta) = Thm.dest_abs NONE ct
   228 	    val (v,Tv) = (dest_Free o term_of) cv
   229 	    val _ = Output.debug (fn()=>"  recursion: " ^ Display.string_of_cterm cta);
   230 	    val u_th = combinators_aux cta
   231 	    val _ = Output.debug (fn()=>"  returned " ^ Display.string_of_thm u_th);
   232 	    val cu = Thm.rhs_of u_th
   233 	    val comb_eq = abstract (Thm.cabs cv cu)
   234 	in Output.debug (fn()=>"  abstraction result: " ^ Display.string_of_thm comb_eq);
   235 	   (transitive (abstract_rule v cv u_th) comb_eq) end
   236     | t1 $ t2 =>
   237 	let val (ct1,ct2) = Thm.dest_comb ct
   238 	in  combination (combinators_aux ct1) (combinators_aux ct2)  end;
   239             
   240 fun combinators th =
   241   if lambda_free (prop_of th) then th 
   242   else
   243     let val _ = Output.debug (fn()=>"Conversion to combinators: " ^ Display.string_of_thm th);
   244 	val th = Drule.eta_contraction_rule th
   245 	val eqth = combinators_aux (cprop_of th)
   246 	val _ = Output.debug (fn()=>"Conversion result: " ^ Display.string_of_thm eqth);
   247     in  equal_elim eqth th   end
   248     handle THM (msg,_,_) => 
   249       (warning ("Error in the combinator translation of " ^ Display.string_of_thm th);
   250        warning ("  Exception message: " ^ msg);
   251        TrueI);  (*A type variable of sort {} will cause make abstraction fail.*)
   252 
   253 (*cterms are used throughout for efficiency*)
   254 val cTrueprop = Thm.cterm_of HOL.thy HOLogic.Trueprop;
   255 
   256 (*cterm version of mk_cTrueprop*)
   257 fun c_mkTrueprop A = Thm.capply cTrueprop A;
   258 
   259 (*Given an abstraction over n variables, replace the bound variables by free
   260   ones. Return the body, along with the list of free variables.*)
   261 fun c_variant_abs_multi (ct0, vars) =
   262       let val (cv,ct) = Thm.dest_abs NONE ct0
   263       in  c_variant_abs_multi (ct, cv::vars)  end
   264       handle CTERM _ => (ct0, rev vars);
   265 
   266 (*Given the definition of a Skolem function, return a theorem to replace
   267   an existential formula by a use of that function.
   268    Example: "EX x. x : A & x ~: B ==> sko A B : A & sko A B ~: B"  [.] *)
   269 fun skolem_of_def def =
   270   let val (c,rhs) = Thm.dest_equals (cprop_of (freeze_thm def))
   271       val (ch, frees) = c_variant_abs_multi (rhs, [])
   272       val (chilbert,cabs) = Thm.dest_comb ch
   273       val thy = Thm.theory_of_cterm chilbert
   274       val t = Thm.term_of chilbert
   275       val T = case t of Const ("Hilbert_Choice.Eps", Type("fun",[_,T])) => T
   276                       | _ => raise THM ("skolem_of_def: expected Eps", 0, [def])
   277       val cex = Thm.cterm_of thy (HOLogic.exists_const T)
   278       val ex_tm = c_mkTrueprop (Thm.capply cex cabs)
   279       and conc =  c_mkTrueprop (Drule.beta_conv cabs (Drule.list_comb(c,frees)));
   280       fun tacf [prem] = rewrite_goals_tac [def] THEN rtac (prem RS someI_ex) 1
   281   in  Goal.prove_internal [ex_tm] conc tacf
   282        |> forall_intr_list frees
   283        |> Thm.forall_elim_vars 0  (*Introduce Vars, but don't discharge defs.*)
   284        |> Thm.varifyT
   285   end;
   286 
   287 
   288 (*This will refer to the final version of theory ATP_Linkup.*)
   289 val atp_linkup_thy_ref = @{theory_ref}
   290 
   291 (*Transfer a theorem into theory ATP_Linkup.thy if it is not already
   292   inside that theory -- because it's needed for Skolemization.
   293   If called while ATP_Linkup is being created, it will transfer to the
   294   current version. If called afterward, it will transfer to the final version.*)
   295 fun transfer_to_ATP_Linkup th =
   296     transfer (Theory.deref atp_linkup_thy_ref) th handle THM _ => th;
   297 
   298 (*Converts an Isabelle theorem (intro, elim or simp format, even higher-order) into NNF.*)
   299 fun to_nnf th ctxt0 =
   300   let val th1 = th |> transfer_to_ATP_Linkup |> transform_elim |> zero_var_indexes
   301       val ((_,[th2]),ctxt) = Variable.import_thms false [th1] ctxt0
   302       val th3 = th2 |> Conv.fconv_rule ObjectLogic.atomize |> Meson.make_nnf |> strip_lambdas ~1
   303   in  (th3, ctxt)  end;
   304 
   305 (*Generate Skolem functions for a theorem supplied in nnf*)
   306 fun assume_skolem_of_def s th =
   307   map (skolem_of_def o assume o (cterm_of (theory_of_thm th))) (assume_skofuns s th);
   308 
   309 fun assert_lambda_free ths msg =
   310   case filter (not o lambda_free o prop_of) ths of
   311       [] => ()
   312     | ths' => error (msg ^ "\n" ^ cat_lines (map Display.string_of_thm ths'));
   313 
   314 
   315 (*** Blacklisting (duplicated in ResAtp? ***)
   316 
   317 val max_lambda_nesting = 3;
   318      
   319 fun excessive_lambdas (f$t, k) = excessive_lambdas (f,k) orelse excessive_lambdas (t,k)
   320   | excessive_lambdas (Abs(_,_,t), k) = k=0 orelse excessive_lambdas (t,k-1)
   321   | excessive_lambdas _ = false;
   322 
   323 fun is_formula_type T = (T = HOLogic.boolT orelse T = propT);
   324 
   325 (*Don't count nested lambdas at the level of formulas, as they are quantifiers*)
   326 fun excessive_lambdas_fm Ts (Abs(_,T,t)) = excessive_lambdas_fm (T::Ts) t
   327   | excessive_lambdas_fm Ts t =
   328       if is_formula_type (fastype_of1 (Ts, t))
   329       then exists (excessive_lambdas_fm Ts) (#2 (strip_comb t))
   330       else excessive_lambdas (t, max_lambda_nesting);
   331 
   332 (*The max apply_depth of any metis call in MetisExamples (on 31-10-2007) was 11.*)
   333 val max_apply_depth = 15;
   334      
   335 fun apply_depth (f$t) = Int.max (apply_depth f, apply_depth t + 1)
   336   | apply_depth (Abs(_,_,t)) = apply_depth t
   337   | apply_depth _ = 0;
   338 
   339 fun too_complex t = 
   340   apply_depth t > max_apply_depth orelse 
   341   Meson.too_many_clauses NONE t orelse
   342   excessive_lambdas_fm [] t;
   343   
   344 fun is_strange_thm th =
   345   case head_of (concl_of th) of
   346       Const (a,_) => (a <> "Trueprop" andalso a <> "==")
   347     | _ => false;
   348 
   349 fun bad_for_atp th = 
   350   PureThy.is_internal th     
   351   orelse too_complex (prop_of th)   
   352   orelse exists_type type_has_empty_sort (prop_of th)  
   353   orelse is_strange_thm th;
   354 
   355 val multi_base_blacklist =
   356   ["defs","select_defs","update_defs","induct","inducts","split","splits","split_asm",
   357    "cases","ext_cases"];  (*FIXME: put other record thms here, or use the "Internal" marker*)
   358 
   359 (*Keep the full complexity of the original name*)
   360 fun flatten_name s = space_implode "_X" (NameSpace.explode s);
   361 
   362 fun fake_name th =
   363   if PureThy.has_name_hint th then flatten_name (PureThy.get_name_hint th)
   364   else gensym "unknown_thm_";
   365 
   366 fun name_or_string th =
   367   if PureThy.has_name_hint th then PureThy.get_name_hint th
   368   else Display.string_of_thm th;
   369 
   370 (*Declare Skolem functions for a theorem, supplied in nnf and with its name.
   371   It returns a modified theory, unless skolemization fails.*)
   372 fun skolem th thy =
   373   let val ctxt0 = Variable.thm_context th
   374       val _ = Output.debug (fn () => "skolemizing " ^ name_or_string th)
   375   in
   376      Option.map
   377         (fn (nnfth,ctxt1) =>
   378           let 
   379               val _ = Output.debug (fn () => "  initial nnf: " ^ Display.string_of_thm nnfth)
   380               val s = fake_name th
   381               val (defs,thy') = declare_skofuns s nnfth thy
   382               val (cnfs,ctxt2) = Meson.make_cnf (map skolem_of_def defs) nnfth ctxt1
   383               val _ = Output.debug (fn () => Int.toString (length cnfs) ^ " clauses yielded")
   384               val cnfs' = cnfs |> map combinators |> Variable.export ctxt2 ctxt0 
   385                                |> Meson.finish_cnf |> map Thm.close_derivation
   386           in (cnfs', thy') end
   387           handle Clausify_failure thy_e => ([],thy_e)
   388         )
   389       (try (to_nnf th) ctxt0)
   390   end;
   391 
   392 (*The cache prevents repeated clausification of a theorem, and also repeated declaration of
   393   Skolem functions.*)
   394 structure ThmCache = TheoryDataFun
   395 (
   396   type T = thm list Thmtab.table;
   397   val empty = Thmtab.empty;
   398   val copy = I;
   399   val extend = I;
   400   fun merge _ tabs : T = Thmtab.merge (K true) tabs;
   401 );
   402 
   403 (*Populate the clause cache using the supplied theorem. Return the clausal form
   404   and modified theory.*)
   405 fun skolem_cache_thm th thy =
   406   case Thmtab.lookup (ThmCache.get thy) th of
   407       NONE =>
   408         (case skolem (Thm.transfer thy th) thy of
   409              NONE => ([th],thy)
   410            | SOME (cls,thy') =>
   411                  (Output.debug (fn () => "skolem_cache_thm: " ^ Int.toString (length cls) ^
   412                                          " clauses inserted into cache: " ^ name_or_string th);
   413                   (cls, ThmCache.map (Thmtab.update (th,cls)) thy')))
   414     | SOME cls => (cls,thy);
   415 
   416 (*Skolemize a named theorem, with Skolem functions as additional premises.*)
   417 fun skolem_thm (s,th) =
   418   if (Sign.base_name s) mem_string multi_base_blacklist orelse bad_for_atp th then []
   419   else 
   420       let val ctxt0 = Variable.thm_context th
   421 	  val (nnfth,ctxt1) = to_nnf th ctxt0
   422 	  val (cnfs,ctxt2) = Meson.make_cnf (assume_skolem_of_def s nnfth) nnfth ctxt1
   423       in  cnfs |> map combinators |> Variable.export ctxt2 ctxt0 |> Meson.finish_cnf  end
   424       handle THM _ => [];
   425 
   426 (*Exported function to convert Isabelle theorems into axiom clauses*)
   427 fun cnf_axiom th =
   428   let val thy = Theory.merge (Theory.deref atp_linkup_thy_ref, Thm.theory_of_thm th)
   429   in
   430       case Thmtab.lookup (ThmCache.get thy) th of
   431           NONE => (Output.debug (fn () => "cnf_axiom: " ^ name_or_string th);
   432                    map Thm.close_derivation (skolem_thm (fake_name th, th)))
   433         | SOME cls => cls
   434   end;
   435 
   436 fun pairname th = (PureThy.get_name_hint th, th);
   437 
   438 (**** Extract and Clausify theorems from a theory's claset and simpset ****)
   439 
   440 fun rules_of_claset cs =
   441   let val {safeIs,safeEs,hazIs,hazEs,...} = rep_cs cs
   442       val intros = safeIs @ hazIs
   443       val elims  = map Classical.classical_rule (safeEs @ hazEs)
   444   in
   445      Output.debug (fn () => "rules_of_claset intros: " ^ Int.toString(length intros) ^
   446             " elims: " ^ Int.toString(length elims));
   447      map pairname (intros @ elims)
   448   end;
   449 
   450 fun rules_of_simpset ss =
   451   let val ({rules,...}, _) = rep_ss ss
   452       val simps = Net.entries rules
   453   in
   454     Output.debug (fn () => "rules_of_simpset: " ^ Int.toString(length simps));
   455     map (fn r => (#name r, #thm r)) simps
   456   end;
   457 
   458 fun claset_rules_of ctxt = rules_of_claset (local_claset_of ctxt);
   459 fun simpset_rules_of ctxt = rules_of_simpset (local_simpset_of ctxt);
   460 
   461 fun atpset_rules_of ctxt = map pairname (ResAtpset.get ctxt);
   462 
   463 
   464 (**** Translate a set of theorems into CNF ****)
   465 
   466 fun pair_name_cls k (n, []) = []
   467   | pair_name_cls k (n, cls::clss) = (cls, (n,k)) :: pair_name_cls (k+1) (n, clss)
   468 
   469 fun cnf_rules_pairs_aux pairs [] = pairs
   470   | cnf_rules_pairs_aux pairs ((name,th)::ths) =
   471       let val pairs' = (pair_name_cls 0 (name, cnf_axiom th)) @ pairs
   472                        handle THM _ => pairs | ResClause.CLAUSE _ => pairs
   473       in  cnf_rules_pairs_aux pairs' ths  end;
   474 
   475 (*The combination of rev and tail recursion preserves the original order*)
   476 fun cnf_rules_pairs l = cnf_rules_pairs_aux [] (rev l);
   477 
   478 
   479 (**** Convert all theorems of a claset/simpset into clauses (ResClause.clause, or ResHolClause.clause) ****)
   480 
   481 (*Setup function: takes a theory and installs ALL known theorems into the clause cache*)
   482 
   483 val mark_skolemized = Sign.add_consts_i [("ResAxioms_endtheory", HOLogic.boolT, NoSyn)];
   484 
   485 fun skolem_cache th thy =
   486   if bad_for_atp th then thy else #2 (skolem_cache_thm th thy);
   487 
   488 fun skolem_cache_list (a,ths) thy =
   489   if (Sign.base_name a) mem_string multi_base_blacklist then thy
   490   else fold skolem_cache ths thy;
   491 
   492 val skolem_cache_theorems_of = Symtab.fold skolem_cache_list o #2 o PureThy.theorems_of;
   493 fun skolem_cache_node thy = skolem_cache_theorems_of thy thy;
   494 fun skolem_cache_all thy = fold skolem_cache_theorems_of (thy :: Theory.ancestors_of thy) thy;
   495 
   496 (*The cache can be kept smaller by inspecting the prop of each thm. Can ignore all that are
   497   lambda_free, but then the individual theory caches become much bigger.*)
   498 
   499 val suppress_endtheory = ref false;
   500 
   501 (*The new constant is a hack to prevent multiple execution*)
   502 fun clause_cache_endtheory thy =
   503   if !suppress_endtheory then NONE
   504   else
   505    (Output.debug (fn () => "RexAxioms end theory action: " ^ Context.str_of_thy thy);
   506     Option.map skolem_cache_node (try mark_skolemized thy) );
   507 
   508 (*** meson proof methods ***)
   509 
   510 fun cnf_rules_of_ths ths = List.concat (map cnf_axiom ths);
   511 
   512 (*Expand all new*definitions of abstraction or Skolem functions in a proof state.*)
   513 fun is_absko (Const ("==", _) $ Free (a,_) $ u) = String.isPrefix "sko_" a
   514   | is_absko _ = false;
   515 
   516 fun is_okdef xs (Const ("==", _) $ t $ u) =   (*Definition of Free, not in certain terms*)
   517       is_Free t andalso not (member (op aconv) xs t)
   518   | is_okdef _ _ = false
   519 
   520 (*This function tries to cope with open locales, which introduce hypotheses of the form
   521   Free == t, conjecture clauses, which introduce various hypotheses, and also definitions
   522   of sko_ functions. *)
   523 fun expand_defs_tac st0 st =
   524   let val hyps0 = #hyps (rep_thm st0)
   525       val hyps = #hyps (crep_thm st)
   526       val newhyps = filter_out (member (op aconv) hyps0 o Thm.term_of) hyps
   527       val defs = filter (is_absko o Thm.term_of) newhyps
   528       val remaining_hyps = filter_out (member (op aconv) (map Thm.term_of defs))
   529                                       (map Thm.term_of hyps)
   530       val fixed = term_frees (concl_of st) @
   531                   foldl (gen_union (op aconv)) [] (map term_frees remaining_hyps)
   532   in  Output.debug (fn _ => "expand_defs_tac: " ^ Display.string_of_thm st);
   533       Output.debug (fn _ => "  st0: " ^ Display.string_of_thm st0);
   534       Output.debug (fn _ => "  defs: " ^ commas (map Display.string_of_cterm defs));
   535       Seq.of_list [LocalDefs.expand (filter (is_okdef fixed o Thm.term_of) defs) st]
   536   end;
   537 
   538 
   539 fun meson_general_tac ths i st0 =
   540  let val _ = Output.debug (fn () => "Meson called: " ^ cat_lines (map Display.string_of_thm ths))
   541  in  (Meson.meson_claset_tac (cnf_rules_of_ths ths) HOL_cs i THEN expand_defs_tac st0) st0 end;
   542 
   543 val meson_method_setup = Method.add_methods
   544   [("meson", Method.thms_args (fn ths =>
   545       Method.SIMPLE_METHOD' (CHANGED_PROP o meson_general_tac ths)),
   546     "MESON resolution proof procedure")];
   547 
   548 (** Attribute for converting a theorem into clauses **)
   549 
   550 fun meta_cnf_axiom th = map Meson.make_meta_clause (cnf_axiom th);
   551 
   552 fun clausify_rule (th,i) = List.nth (meta_cnf_axiom th, i)
   553 
   554 val clausify = Attrib.syntax (Scan.lift Args.nat
   555   >> (fn i => Thm.rule_attribute (fn _ => fn th => clausify_rule (th, i))));
   556 
   557 
   558 (*** Converting a subgoal into negated conjecture clauses. ***)
   559 
   560 val neg_skolemize_tac = EVERY' [rtac ccontr, ObjectLogic.atomize_prems_tac, Meson.skolemize_tac];
   561 
   562 fun neg_clausify sts =
   563   sts |> Meson.make_clauses |> map combinators |> Meson.finish_cnf;
   564 
   565 fun neg_conjecture_clauses st0 n =
   566   let val st = Seq.hd (neg_skolemize_tac n st0)
   567       val (params,_,_) = strip_context (Logic.nth_prem (n, Thm.prop_of st))
   568   in (neg_clausify (Option.valOf (metahyps_thms n st)), params) end
   569   handle Option => raise ERROR "unable to Skolemize subgoal";
   570 
   571 (*Conversion of a subgoal to conjecture clauses. Each clause has
   572   leading !!-bound universal variables, to express generality. *)
   573 val neg_clausify_tac =
   574   neg_skolemize_tac THEN'
   575   SUBGOAL
   576     (fn (prop,_) =>
   577      let val ts = Logic.strip_assums_hyp prop
   578      in EVERY1
   579          [METAHYPS
   580             (fn hyps =>
   581               (Method.insert_tac
   582                 (map forall_intr_vars (neg_clausify hyps)) 1)),
   583           REPEAT_DETERM_N (length ts) o (etac thin_rl)]
   584      end);
   585 
   586 (** The Skolemization attribute **)
   587 
   588 fun conj2_rule (th1,th2) = conjI OF [th1,th2];
   589 
   590 (*Conjoin a list of theorems to form a single theorem*)
   591 fun conj_rule []  = TrueI
   592   | conj_rule ths = foldr1 conj2_rule ths;
   593 
   594 fun skolem_attr (Context.Theory thy, th) =
   595       let val (cls, thy') = skolem_cache_thm th thy
   596       in (Context.Theory thy', conj_rule cls) end
   597   | skolem_attr (context, th) = (context, th)
   598 
   599 val setup_attrs = Attrib.add_attributes
   600   [("skolem", Attrib.no_args skolem_attr, "skolemization of a theorem"),
   601    ("clausify", clausify, "conversion of theorem to clauses")];
   602 
   603 val setup_methods = Method.add_methods
   604   [("neg_clausify", Method.no_args (Method.SIMPLE_METHOD' neg_clausify_tac),
   605     "conversion of goal to conjecture clauses")];
   606 
   607 val setup = mark_skolemized #> skolem_cache_all #> ThmCache.init #> setup_attrs #> setup_methods;
   608 
   609 end;