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