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