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