src/HOL/Tools/res_axioms.ML
author wenzelm
Sun Jul 29 14:29:58 2007 +0200 (2007-07-29)
changeset 24042 968f42fe6836
parent 23592 ba0912262b2c
child 24137 8d7896398147
permissions -rw-r--r--
simplified ResAtpset via NamedThmsFun;
     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 trace_abs: bool ref
    11   val cnf_axiom : string * thm -> thm list
    12   val cnf_name : string -> thm list
    13   val meta_cnf_axiom : thm -> thm list
    14   val pairname : thm -> string * thm
    15   val skolem_thm : thm -> thm list
    16   val cnf_rules_pairs : (string * thm) list -> (thm * (string * int)) list
    17   val meson_method_setup : theory -> theory
    18   val setup : theory -> theory
    19   val assume_abstract_list: string -> thm list -> thm list
    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 end;
    25 
    26 structure ResAxioms =
    27 struct
    28 
    29 (*For running the comparison between combinators and abstractions.
    30   CANNOT be a ref, as the setting is used while Isabelle is built.
    31   Currently TRUE: the combinator code cannot be used with proof reconstruction
    32   because it is not performed by inference!!*)
    33 val abstract_lambdas = true;
    34 
    35 val trace_abs = ref false;
    36 
    37 (* FIXME legacy *)
    38 fun freeze_thm th = #1 (Drule.freeze_thaw th);
    39 
    40 val lhs_of = #1 o Logic.dest_equals o Thm.prop_of;
    41 val rhs_of = #2 o Logic.dest_equals o Thm.prop_of;
    42 
    43 
    44 (*Store definitions of abstraction functions, ensuring that identical right-hand
    45   sides are denoted by the same functions and thereby reducing the need for
    46   extensionality in proofs.
    47   FIXME!  Store in theory data!!*)
    48 
    49 (*Populate the abstraction cache with common combinators.*)
    50 fun seed th net =
    51   let val (_,ct) = Thm.dest_abs NONE (Thm.rhs_of th)
    52       val t = Logic.legacy_varify (term_of ct)
    53   in  Net.insert_term Thm.eq_thm (t, th) net end;
    54   
    55 val abstraction_cache = ref 
    56       (seed (thm"ATP_Linkup.I_simp") 
    57        (seed (thm"ATP_Linkup.B_simp") 
    58 	(seed (thm"ATP_Linkup.K_simp") Net.empty)));
    59 
    60 
    61 (**** Transformation of Elimination Rules into First-Order Formulas****)
    62 
    63 val cfalse = cterm_of HOL.thy HOLogic.false_const;
    64 val ctp_false = cterm_of HOL.thy (HOLogic.mk_Trueprop HOLogic.false_const);
    65 
    66 (*Converts an elim-rule into an equivalent theorem that does not have the
    67   predicate variable.  Leaves other theorems unchanged.  We simply instantiate the
    68   conclusion variable to False.*)
    69 fun transform_elim th =
    70   case concl_of th of    (*conclusion variable*)
    71        Const("Trueprop",_) $ (v as Var(_,Type("bool",[]))) => 
    72            Thm.instantiate ([], [(cterm_of HOL.thy v, cfalse)]) th
    73     | v as Var(_, Type("prop",[])) => 
    74            Thm.instantiate ([], [(cterm_of HOL.thy v, ctp_false)]) th
    75     | _ => th;
    76 
    77 (**** Transformation of Clasets and Simpsets into First-Order Axioms ****)
    78 
    79 (*Transfer a theorem into theory ATP_Linkup.thy if it is not already
    80   inside that theory -- because it's needed for Skolemization *)
    81 
    82 (*This will refer to the final version of theory ATP_Linkup.*)
    83 val recon_thy_ref = Theory.self_ref (the_context ());
    84 
    85 (*If called while ATP_Linkup is being created, it will transfer to the
    86   current version. If called afterward, it will transfer to the final version.*)
    87 fun transfer_to_ATP_Linkup th =
    88     transfer (Theory.deref recon_thy_ref) th handle THM _ => th;
    89 
    90 
    91 (**** SKOLEMIZATION BY INFERENCE (lcp) ****)
    92 
    93 (*Traverse a theorem, declaring Skolem function definitions. String s is the suggested
    94   prefix for the Skolem constant. Result is a new theory*)
    95 fun declare_skofuns s th thy =
    96   let val nref = ref 0
    97       fun dec_sko (Const ("Ex",_) $ (xtp as Abs(_,T,p))) (thy, axs) =
    98             (*Existential: declare a Skolem function, then insert into body and continue*)
    99             let val cname = Name.internal ("sko_" ^ s ^ "_" ^ Int.toString (inc nref))
   100                 val args = term_frees xtp  (*get the formal parameter list*)
   101                 val Ts = map type_of args
   102                 val cT = Ts ---> T
   103                 val c = Const (Sign.full_name thy cname, cT)
   104                 val rhs = list_abs_free (map dest_Free args, HOLogic.choice_const T $ xtp)
   105                         (*Forms a lambda-abstraction over the formal parameters*)
   106                 val thy' = Sign.add_consts_authentic [(cname, cT, NoSyn)] thy
   107                            (*Theory is augmented with the constant, then its def*)
   108                 val cdef = cname ^ "_def"
   109                 val thy'' = Theory.add_defs_i false false [(cdef, equals cT $ c $ rhs)] thy'
   110             in dec_sko (subst_bound (list_comb(c,args), p))
   111                        (thy'', get_axiom thy'' cdef :: axs)
   112             end
   113         | dec_sko (Const ("All",_) $ (xtp as Abs(a,T,p))) thx =
   114             (*Universal quant: insert a free variable into body and continue*)
   115             let val fname = Name.variant (add_term_names (p,[])) a
   116             in dec_sko (subst_bound (Free(fname,T), p)) thx end
   117         | dec_sko (Const ("op &", _) $ p $ q) thx = dec_sko q (dec_sko p thx)
   118         | dec_sko (Const ("op |", _) $ p $ q) thx = dec_sko q (dec_sko p thx)
   119         | dec_sko (Const ("Trueprop", _) $ p) thx = dec_sko p thx
   120         | dec_sko t thx = thx (*Do nothing otherwise*)
   121   in  dec_sko (prop_of th) (thy,[])  end;
   122 
   123 (*Traverse a theorem, accumulating Skolem function definitions.*)
   124 fun assume_skofuns s th =
   125   let val sko_count = ref 0
   126       fun dec_sko (Const ("Ex",_) $ (xtp as Abs(_,T,p))) defs =
   127             (*Existential: declare a Skolem function, then insert into body and continue*)
   128             let val skos = map (#1 o Logic.dest_equals) defs  (*existing sko fns*)
   129                 val args = term_frees xtp \\ skos  (*the formal parameters*)
   130                 val Ts = map type_of args
   131                 val cT = Ts ---> T
   132                 val id = "sko_" ^ s ^ "_" ^ Int.toString (inc sko_count)
   133                 val c = Free (id, cT)
   134                 val rhs = list_abs_free (map dest_Free args,
   135                                          HOLogic.choice_const T $ xtp)
   136                       (*Forms a lambda-abstraction over the formal parameters*)
   137                 val def = equals cT $ c $ rhs
   138             in dec_sko (subst_bound (list_comb(c,args), p))
   139                        (def :: defs)
   140             end
   141         | dec_sko (Const ("All",_) $ (xtp as Abs(a,T,p))) defs =
   142             (*Universal quant: insert a free variable into body and continue*)
   143             let val fname = Name.variant (add_term_names (p,[])) a
   144             in dec_sko (subst_bound (Free(fname,T), p)) defs end
   145         | dec_sko (Const ("op &", _) $ p $ q) defs = dec_sko q (dec_sko p defs)
   146         | dec_sko (Const ("op |", _) $ p $ q) defs = dec_sko q (dec_sko p defs)
   147         | dec_sko (Const ("Trueprop", _) $ p) defs = dec_sko p defs
   148         | dec_sko t defs = defs (*Do nothing otherwise*)
   149   in  dec_sko (prop_of th) []  end;
   150 
   151 
   152 (**** REPLACING ABSTRACTIONS BY FUNCTION DEFINITIONS ****)
   153 
   154 (*Returns the vars of a theorem*)
   155 fun vars_of_thm th =
   156   map (Thm.cterm_of (theory_of_thm th) o Var) (Thm.fold_terms Term.add_vars th []);
   157 
   158 (*Make a version of fun_cong with a given variable name*)
   159 local
   160     val fun_cong' = fun_cong RS asm_rl; (*renumber f, g to prevent clashes with (a,0)*)
   161     val cx = hd (vars_of_thm fun_cong');
   162     val ty = typ_of (ctyp_of_term cx);
   163     val thy = theory_of_thm fun_cong;
   164     fun mkvar a = cterm_of thy (Var((a,0),ty));
   165 in
   166 fun xfun_cong x = Thm.instantiate ([], [(cx, mkvar x)]) fun_cong'
   167 end;
   168 
   169 (*Removes the lambdas from an equation of the form t = (%x. u).  A non-negative n,
   170   serves as an upper bound on how many to remove.*)
   171 fun strip_lambdas 0 th = th
   172   | strip_lambdas n th = 
   173       case prop_of th of
   174 	  _ $ (Const ("op =", _) $ _ $ Abs (x,_,_)) =>
   175 	      strip_lambdas (n-1) (freeze_thm (th RS xfun_cong x))
   176 	| _ => th;
   177 
   178 (*Convert meta- to object-equality. Fails for theorems like split_comp_eq,
   179   where some types have the empty sort.*)
   180 val meta_eq_to_obj_eq = thm "meta_eq_to_obj_eq";
   181 fun mk_object_eq th = th RS meta_eq_to_obj_eq
   182     handle THM _ => error ("Theorem contains empty sort: " ^ string_of_thm th);
   183 
   184 (*Apply a function definition to an argument, beta-reducing the result.*)
   185 fun beta_comb cf x =
   186   let val th1 = combination cf (reflexive x)
   187       val th2 = beta_conversion false (Thm.rhs_of th1)
   188   in  transitive th1 th2  end;
   189 
   190 (*Apply a function definition to arguments, beta-reducing along the way.*)
   191 fun list_combination cf [] = cf
   192   | list_combination cf (x::xs) = list_combination (beta_comb cf x) xs;
   193 
   194 fun list_cabs ([] ,     t) = t
   195   | list_cabs (v::vars, t) = Thm.cabs v (list_cabs(vars,t));
   196 
   197 fun assert_eta_free ct =
   198   let val t = term_of ct
   199   in if (t aconv Envir.eta_contract t) then ()
   200      else error ("Eta redex in term: " ^ string_of_cterm ct)
   201   end;
   202 
   203 fun eq_absdef (th1, th2) =
   204     Context.joinable (theory_of_thm th1, theory_of_thm th2)  andalso
   205     rhs_of th1 aconv rhs_of th2;
   206 
   207 fun lambda_free (Abs _) = false
   208   | lambda_free (t $ u) = lambda_free t andalso lambda_free u
   209   | lambda_free _ = true;
   210 
   211 fun monomorphic t =
   212   Term.fold_types (Term.fold_atyps (fn TVar _ => K false | _ => I)) t true;
   213 
   214 fun dest_abs_list ct =
   215   let val (cv,ct') = Thm.dest_abs NONE ct
   216       val (cvs,cu) = dest_abs_list ct'
   217   in (cv::cvs, cu) end
   218   handle CTERM _ => ([],ct);
   219 
   220 fun lambda_list [] u = u
   221   | lambda_list (v::vs) u = lambda v (lambda_list vs u);
   222 
   223 fun abstract_rule_list [] [] th = th
   224   | abstract_rule_list (v::vs) (ct::cts) th = abstract_rule v ct (abstract_rule_list vs cts th)
   225   | abstract_rule_list _ _ th = raise THM ("abstract_rule_list", 0, [th]);
   226 
   227 
   228 val Envir.Envir {asol = tenv0, iTs = tyenv0, ...} = Envir.empty 0
   229 
   230 (*Does an existing abstraction definition have an RHS that matches the one we need now?
   231   thy is the current theory, which must extend that of theorem th.*)
   232 fun match_rhs thy t th =
   233   let val _ = if !trace_abs then warning ("match_rhs: " ^ string_of_cterm (cterm_of thy t) ^ 
   234                                           " against\n" ^ string_of_thm th) else ();
   235       val (tyenv,tenv) = Pattern.first_order_match thy (rhs_of th, t) (tyenv0,tenv0)
   236       val term_insts = map Meson.term_pair_of (Vartab.dest tenv)
   237       val ct_pairs = if subthy (theory_of_thm th, thy) andalso 
   238                         forall lambda_free (map #2 term_insts) 
   239                      then map (pairself (cterm_of thy)) term_insts
   240                      else raise Pattern.MATCH (*Cannot allow lambdas in the instantiation*)
   241       fun ctyp2 (ixn, (S, T)) = (ctyp_of thy (TVar (ixn, S)), ctyp_of thy T)
   242       val th' = cterm_instantiate ct_pairs th
   243   in  SOME (th, instantiate (map ctyp2 (Vartab.dest tyenv), []) th')  end
   244   handle _ => NONE;
   245 
   246 (*Traverse a theorem, declaring abstraction function definitions. String s is the suggested
   247   prefix for the constants. Resulting theory is returned in the first theorem. *)
   248 fun declare_absfuns s th =
   249   let val nref = ref 0
   250       fun abstract thy ct =
   251         if lambda_free (term_of ct) then (transfer thy (reflexive ct), [])
   252         else
   253         case term_of ct of
   254           Abs _ =>
   255             let val cname = Name.internal ("llabs_" ^ s ^ "_" ^ Int.toString (inc nref))
   256                 val _ = assert_eta_free ct;
   257                 val (cvs,cta) = dest_abs_list ct
   258                 val (vs,Tvs) = ListPair.unzip (map (dest_Free o term_of) cvs)
   259                 val _ = if !trace_abs then warning ("Nested lambda: " ^ string_of_cterm cta) else ();
   260                 val (u'_th,defs) = abstract thy cta
   261                 val _ = if !trace_abs then warning ("Returned " ^ string_of_thm u'_th) else ();
   262                 val cu' = Thm.rhs_of u'_th
   263                 val u' = term_of cu'
   264                 val abs_v_u = lambda_list (map term_of cvs) u'
   265                 (*get the formal parameters: ALL variables free in the term*)
   266                 val args = term_frees abs_v_u
   267                 val _ = if !trace_abs then warning (Int.toString (length args) ^ " arguments") else ();
   268                 val rhs = list_abs_free (map dest_Free args, abs_v_u)
   269                       (*Forms a lambda-abstraction over the formal parameters*)
   270                 val _ = if !trace_abs then warning ("Looking up " ^ string_of_cterm cu') else ();
   271                 val thy = theory_of_thm u'_th
   272                 val (ax,ax',thy) =
   273                  case List.mapPartial (match_rhs thy abs_v_u) 
   274                          (Net.match_term (!abstraction_cache) u') of
   275                      (ax,ax')::_ => 
   276                        (if !trace_abs then warning ("Re-using axiom " ^ string_of_thm ax) else ();
   277                         (ax,ax',thy))
   278                    | [] =>
   279                       let val _ = if !trace_abs then warning "Lookup was empty" else ();
   280                           val Ts = map type_of args
   281                           val cT = Ts ---> (Tvs ---> typ_of (ctyp_of_term cu'))
   282                           val c = Const (Sign.full_name thy cname, cT)
   283                           val thy = Sign.add_consts_authentic [(cname, cT, NoSyn)] thy
   284                                      (*Theory is augmented with the constant,
   285                                        then its definition*)
   286                           val cdef = cname ^ "_def"
   287                           val thy = Theory.add_defs_i false false
   288                                        [(cdef, equals cT $ c $ rhs)] thy
   289                           val _ = if !trace_abs then (warning ("Definition is " ^ 
   290                                                       string_of_thm (get_axiom thy cdef))) 
   291                                   else ();
   292                           val ax = get_axiom thy cdef |> freeze_thm
   293                                      |> mk_object_eq |> strip_lambdas (length args)
   294                                      |> mk_meta_eq |> Meson.generalize
   295                           val (_,ax') = Option.valOf (match_rhs thy abs_v_u ax)
   296                           val _ = if !trace_abs then 
   297                                     (warning ("Declaring: " ^ string_of_thm ax);
   298                                      warning ("Instance: " ^ string_of_thm ax')) 
   299                                   else ();
   300                           val _ = abstraction_cache := Net.insert_term eq_absdef 
   301                                             ((Logic.varify u'), ax) (!abstraction_cache)
   302                             handle Net.INSERT =>
   303                               raise THM ("declare_absfuns: INSERT", 0, [th,u'_th,ax])
   304                        in  (ax,ax',thy)  end
   305             in if !trace_abs then warning ("Lookup result: " ^ string_of_thm ax') else ();
   306                (transitive (abstract_rule_list vs cvs u'_th) (symmetric ax'), ax::defs) end
   307         | (t1$t2) =>
   308             let val (ct1,ct2) = Thm.dest_comb ct
   309                 val (th1,defs1) = abstract thy ct1
   310                 val (th2,defs2) = abstract (theory_of_thm th1) ct2
   311             in  (combination th1 th2, defs1@defs2)  end
   312       val _ = if !trace_abs then warning ("declare_absfuns, Abstracting: " ^ string_of_thm th) else ();
   313       val (eqth,defs) = abstract (theory_of_thm th) (cprop_of th)
   314       val ths = equal_elim eqth th :: map (strip_lambdas ~1 o mk_object_eq o freeze_thm) defs
   315       val _ = if !trace_abs then warning ("declare_absfuns, Result: " ^ string_of_thm (hd ths)) else ();
   316   in  (theory_of_thm eqth, map Drule.eta_contraction_rule ths)  end;
   317 
   318 fun name_of def = try (#1 o dest_Free o lhs_of) def;
   319 
   320 (*A name is valid provided it isn't the name of a defined abstraction.*)
   321 fun valid_name defs (Free(x,T)) = not (x mem_string (List.mapPartial name_of defs))
   322   | valid_name defs _ = false;
   323 
   324 (*s is the theorem name (hint) or the word "subgoal"*)
   325 fun assume_absfuns s th =
   326   let val thy = theory_of_thm th
   327       val cterm = cterm_of thy
   328       val abs_count = ref 0
   329       fun abstract ct =
   330         if lambda_free (term_of ct) then (reflexive ct, [])
   331         else
   332         case term_of ct of
   333           Abs (_,T,u) =>
   334             let val _ = assert_eta_free ct;
   335                 val (cvs,cta) = dest_abs_list ct
   336                 val (vs,Tvs) = ListPair.unzip (map (dest_Free o term_of) cvs)
   337                 val (u'_th,defs) = abstract cta
   338                 val cu' = Thm.rhs_of u'_th
   339                 val u' = term_of cu'
   340                 (*Could use Thm.cabs instead of lambda to work at level of cterms*)
   341                 val abs_v_u = lambda_list (map term_of cvs) (term_of cu')
   342                 (*get the formal parameters: free variables not present in the defs
   343                   (to avoid taking abstraction function names as parameters) *)
   344                 val args = filter (valid_name defs) (term_frees abs_v_u)
   345                 val crhs = list_cabs (map cterm args, cterm abs_v_u)
   346                       (*Forms a lambda-abstraction over the formal parameters*)
   347                 val rhs = term_of crhs
   348                 val (ax,ax') =
   349                  case List.mapPartial (match_rhs thy abs_v_u) 
   350                         (Net.match_term (!abstraction_cache) u') of
   351                      (ax,ax')::_ => 
   352                        (if !trace_abs then warning ("Re-using axiom " ^ string_of_thm ax) else ();
   353                         (ax,ax'))
   354                    | [] =>
   355                       let val Ts = map type_of args
   356                           val const_ty = Ts ---> (Tvs ---> typ_of (ctyp_of_term cu'))
   357                           val id = "llabs_" ^ s ^ "_" ^ Int.toString (inc abs_count)
   358                           val c = Free (id, const_ty)
   359                           val ax = assume (Thm.capply (cterm (equals const_ty $ c)) crhs)
   360                                      |> mk_object_eq |> strip_lambdas (length args)
   361                                      |> mk_meta_eq |> Meson.generalize
   362                           val (_,ax') = Option.valOf (match_rhs thy abs_v_u ax)
   363                           val _ = abstraction_cache := Net.insert_term eq_absdef (rhs,ax)
   364                                     (!abstraction_cache)
   365                             handle Net.INSERT =>
   366                               raise THM ("assume_absfuns: INSERT", 0, [th,u'_th,ax])
   367                       in (ax,ax') end
   368             in if !trace_abs then warning ("Lookup result: " ^ string_of_thm ax') else ();
   369                (transitive (abstract_rule_list vs cvs u'_th) (symmetric ax'), ax::defs) end
   370         | (t1$t2) =>
   371             let val (ct1,ct2) = Thm.dest_comb ct
   372                 val (t1',defs1) = abstract ct1
   373                 val (t2',defs2) = abstract ct2
   374             in  (combination t1' t2', defs1@defs2)  end
   375       val _ = if !trace_abs then warning ("assume_absfuns, Abstracting: " ^ string_of_thm th) else ();
   376       val (eqth,defs) = abstract (cprop_of th)
   377       val ths = equal_elim eqth th :: map (strip_lambdas ~1 o mk_object_eq o freeze_thm) defs
   378       val _ = if !trace_abs then warning ("assume_absfuns, Result: " ^ string_of_thm (hd ths)) else ();
   379   in  map Drule.eta_contraction_rule ths  end;
   380 
   381 
   382 (*cterms are used throughout for efficiency*)
   383 val cTrueprop = Thm.cterm_of HOL.thy HOLogic.Trueprop;
   384 
   385 (*cterm version of mk_cTrueprop*)
   386 fun c_mkTrueprop A = Thm.capply cTrueprop A;
   387 
   388 (*Given an abstraction over n variables, replace the bound variables by free
   389   ones. Return the body, along with the list of free variables.*)
   390 fun c_variant_abs_multi (ct0, vars) =
   391       let val (cv,ct) = Thm.dest_abs NONE ct0
   392       in  c_variant_abs_multi (ct, cv::vars)  end
   393       handle CTERM _ => (ct0, rev vars);
   394 
   395 (*Given the definition of a Skolem function, return a theorem to replace
   396   an existential formula by a use of that function.
   397    Example: "EX x. x : A & x ~: B ==> sko A B : A & sko A B ~: B"  [.] *)
   398 fun skolem_of_def def =
   399   let val (c,rhs) = Thm.dest_equals (cprop_of (freeze_thm def))
   400       val (ch, frees) = c_variant_abs_multi (rhs, [])
   401       val (chilbert,cabs) = Thm.dest_comb ch
   402       val {thy,t, ...} = rep_cterm chilbert
   403       val T = case t of Const ("Hilbert_Choice.Eps", Type("fun",[_,T])) => T
   404                       | _ => raise THM ("skolem_of_def: expected Eps", 0, [def])
   405       val cex = Thm.cterm_of thy (HOLogic.exists_const T)
   406       val ex_tm = c_mkTrueprop (Thm.capply cex cabs)
   407       and conc =  c_mkTrueprop (Drule.beta_conv cabs (Drule.list_comb(c,frees)));
   408       fun tacf [prem] = rewrite_goals_tac [def] THEN rtac (prem RS someI_ex) 1
   409   in  Goal.prove_internal [ex_tm] conc tacf
   410        |> forall_intr_list frees
   411        |> forall_elim_vars 0  (*Introduce Vars, but don't discharge defs.*)
   412        |> Thm.varifyT
   413   end;
   414 
   415 (*Converts an Isabelle theorem (intro, elim or simp format, even higher-order) into NNF.*)
   416 fun to_nnf th =
   417     th |> transfer_to_ATP_Linkup
   418        |> transform_elim |> zero_var_indexes |> freeze_thm
   419        |> Conv.fconv_rule ObjectLogic.atomize |> make_nnf |> strip_lambdas ~1;
   420 
   421 (*Generate Skolem functions for a theorem supplied in nnf*)
   422 fun skolem_of_nnf s th =
   423   map (skolem_of_def o assume o (cterm_of (theory_of_thm th))) (assume_skofuns s th);
   424 
   425 fun assert_lambda_free ths msg = 
   426   case filter (not o lambda_free o prop_of) ths of
   427       [] => ()
   428     | ths' => error (msg ^ "\n" ^ cat_lines (map string_of_thm ths'));
   429 
   430 fun assume_abstract s th =
   431   if lambda_free (prop_of th) then [th]
   432   else th |> Drule.eta_contraction_rule |> assume_absfuns s
   433           |> tap (fn ths => assert_lambda_free ths "assume_abstract: lambdas")
   434 
   435 (*Replace lambdas by assumed function definitions in the theorems*)
   436 fun assume_abstract_list s ths =
   437   if abstract_lambdas then List.concat (map (assume_abstract s) ths)
   438   else map Drule.eta_contraction_rule ths;
   439 
   440 (*Replace lambdas by declared function definitions in the theorems*)
   441 fun declare_abstract' s (thy, []) = (thy, [])
   442   | declare_abstract' s (thy, th::ths) =
   443       let val (thy', th_defs) =
   444             if lambda_free (prop_of th) then (thy, [th])
   445             else
   446                 th |> zero_var_indexes |> freeze_thm
   447                    |> Drule.eta_contraction_rule |> transfer thy |> declare_absfuns s
   448           val _ = assert_lambda_free th_defs "declare_abstract: lambdas"
   449           val (thy'', ths') = declare_abstract' s (thy', ths)
   450       in  (thy'', th_defs @ ths')  end;
   451 
   452 fun declare_abstract s (thy, ths) =
   453   if abstract_lambdas then declare_abstract' s (thy, ths)
   454   else (thy, map Drule.eta_contraction_rule ths);
   455 
   456 (*Keep the full complexity of the original name*)
   457 fun flatten_name s = space_implode "_X" (NameSpace.explode s);
   458 
   459 fun fake_name th =
   460   if PureThy.has_name_hint th then flatten_name (PureThy.get_name_hint th) 
   461   else gensym "unknown_thm_";
   462 
   463 (*Skolemize a named theorem, with Skolem functions as additional premises.*)
   464 fun skolem_thm th =
   465   let val nnfth = to_nnf th and s = fake_name th
   466   in  Meson.make_cnf (skolem_of_nnf s nnfth) nnfth |> assume_abstract_list s |> Meson.finish_cnf
   467   end
   468   handle THM _ => [];
   469 
   470 (*Declare Skolem functions for a theorem, supplied in nnf and with its name.
   471   It returns a modified theory, unless skolemization fails.*)
   472 fun skolem thy th =
   473      Option.map
   474         (fn (nnfth, s) =>
   475           let val _ = Output.debug (fn () => "skolemizing " ^ s ^ ": ")
   476               val (thy',defs) = declare_skofuns s nnfth thy
   477               val cnfs = Meson.make_cnf (map skolem_of_def defs) nnfth
   478               val (thy'',cnfs') = declare_abstract s (thy',cnfs)
   479           in (map Goal.close_result (Meson.finish_cnf cnfs'), thy'')
   480           end)
   481       (SOME (to_nnf th, fake_name th)  handle THM _ => NONE);
   482 
   483 structure ThmCache = TheoryDataFun
   484 (
   485   type T = (thm list) Thmtab.table ref;
   486   val empty : T = ref Thmtab.empty;
   487   fun copy (ref tab) : T = ref tab;
   488   val extend = copy;
   489   fun merge _ (ref tab1, ref tab2) : T = ref (Thmtab.merge (K true) (tab1, tab2));
   490 );
   491 
   492 (*The cache prevents repeated clausification of a theorem, and also repeated declaration of 
   493   Skolem functions. The global one holds theorems proved prior to this point. Theory data
   494   holds the remaining ones.*)
   495 val global_clause_cache = ref (Thmtab.empty : (thm list) Thmtab.table);
   496 
   497 (*Populate the clause cache using the supplied theorem. Return the clausal form
   498   and modified theory.*)
   499 fun skolem_cache_thm clause_cache th thy =
   500   case Thmtab.lookup (!clause_cache) th of
   501       NONE =>
   502         (case skolem thy (Thm.transfer thy th) of
   503              NONE => ([th],thy)
   504            | SOME (cls,thy') => 
   505                  (if null cls 
   506                   then warning ("skolem_cache: empty clause set for " ^ string_of_thm th)
   507                   else ();
   508                   change clause_cache (Thmtab.update (th, cls)); 
   509                   (cls,thy')))
   510     | SOME cls => (cls,thy);
   511 
   512 (*Exported function to convert Isabelle theorems into axiom clauses*)
   513 fun cnf_axiom th =
   514   let val cache = ThmCache.get (Thm.theory_of_thm th)
   515                   handle ERROR _ => global_clause_cache
   516       val in_cache = if cache = global_clause_cache then NONE else Thmtab.lookup (!cache) th
   517   in
   518      case in_cache of
   519        NONE => 
   520 	 (case Thmtab.lookup (!global_clause_cache) th of
   521 	   NONE => 
   522 	     let val cls = map Goal.close_result (skolem_thm th)
   523 	     in Output.debug (fn () => Int.toString (length cls) ^ " clauses inserted into cache: " ^ 
   524 	                         (if PureThy.has_name_hint th then PureThy.get_name_hint th
   525 	                          else string_of_thm th));
   526 		change cache (Thmtab.update (th, cls)); cls 
   527 	     end
   528 	 | SOME cls => cls)
   529      | SOME cls => cls
   530   end;
   531 
   532 fun pairname th = (PureThy.get_name_hint th, th);
   533 
   534 (**** Extract and Clausify theorems from a theory's claset and simpset ****)
   535 
   536 fun rules_of_claset cs =
   537   let val {safeIs,safeEs,hazIs,hazEs,...} = rep_cs cs
   538       val intros = safeIs @ hazIs
   539       val elims  = map Classical.classical_rule (safeEs @ hazEs)
   540   in
   541      Output.debug (fn () => "rules_of_claset intros: " ^ Int.toString(length intros) ^
   542             " elims: " ^ Int.toString(length elims));
   543      map pairname (intros @ elims)
   544   end;
   545 
   546 fun rules_of_simpset ss =
   547   let val ({rules,...}, _) = rep_ss ss
   548       val simps = Net.entries rules
   549   in
   550     Output.debug (fn () => "rules_of_simpset: " ^ Int.toString(length simps));
   551     map (fn r => (#name r, #thm r)) simps
   552   end;
   553 
   554 fun claset_rules_of ctxt = rules_of_claset (local_claset_of ctxt);
   555 fun simpset_rules_of ctxt = rules_of_simpset (local_simpset_of ctxt);
   556 
   557 fun atpset_rules_of ctxt = map pairname (ResAtpset.get ctxt);
   558 
   559 
   560 (**** Translate a set of theorems into CNF ****)
   561 
   562 (* classical rules: works for both FOL and HOL *)
   563 fun cnf_rules [] err_list = ([],err_list)
   564   | cnf_rules ((name,th) :: ths) err_list =
   565       let val (ts,es) = cnf_rules ths err_list
   566       in  (cnf_axiom th :: ts,es) handle  _ => (ts, (th::es))  end;
   567 
   568 fun pair_name_cls k (n, []) = []
   569   | pair_name_cls k (n, cls::clss) = (cls, (n,k)) :: pair_name_cls (k+1) (n, clss)
   570 
   571 fun cnf_rules_pairs_aux pairs [] = pairs
   572   | cnf_rules_pairs_aux pairs ((name,th)::ths) =
   573       let val pairs' = (pair_name_cls 0 (name, cnf_axiom th)) @ pairs
   574                        handle THM _ => pairs | ResClause.CLAUSE _ => pairs
   575       in  cnf_rules_pairs_aux pairs' ths  end;
   576 
   577 (*The combination of rev and tail recursion preserves the original order*)
   578 fun cnf_rules_pairs l = cnf_rules_pairs_aux [] (rev l);
   579 
   580 
   581 (**** Convert all theorems of a claset/simpset into clauses (ResClause.clause, or ResHolClause.clause) ****)
   582 
   583 (*Setup function: takes a theory and installs ALL known theorems into the clause cache*)
   584 
   585 fun skolem_cache clause_cache th thy = #2 (skolem_cache_thm clause_cache th thy);
   586 
   587 (*The cache can be kept smaller by inspecting the prop of each thm. Can ignore all that are
   588   lambda_free, but then the individual theory caches become much bigger.*)
   589 
   590 fun clause_cache_setup thy = 
   591   fold (skolem_cache global_clause_cache) (map #2 (PureThy.all_thms_of thy)) thy;
   592 
   593 
   594 (*** meson proof methods ***)
   595 
   596 fun cnf_rules_of_ths ths = List.concat (map cnf_axiom ths);
   597 
   598 (*Expand all new*definitions of abstraction or Skolem functions in a proof state.*)
   599 fun is_absko (Const ("==", _) $ Free (a,_) $ u) = String.isPrefix "llabs_" a orelse String.isPrefix "sko_" a
   600   | is_absko _ = false;
   601 
   602 fun is_okdef xs (Const ("==", _) $ t $ u) =   (*Definition of Free, not in certain terms*)
   603       is_Free t andalso not (member (op aconv) xs t)
   604   | is_okdef _ _ = false
   605 
   606 fun expand_defs_tac st0 st =
   607   let val hyps0 = #hyps (rep_thm st0)
   608       val hyps = #hyps (crep_thm st)
   609       val newhyps = filter_out (member (op aconv) hyps0 o Thm.term_of) hyps
   610       val defs = filter (is_absko o Thm.term_of) newhyps
   611       val remaining_hyps = filter_out (member (op aconv) (map Thm.term_of defs)) 
   612                                       (map Thm.term_of hyps)
   613       val fixed = term_frees (concl_of st) @
   614                   foldl (gen_union (op aconv)) [] (map term_frees remaining_hyps)
   615   in  Output.debug (fn _ => "expand_defs_tac: " ^ string_of_thm st);
   616       Output.debug (fn _ => "  st0: " ^ string_of_thm st0);
   617       Output.debug (fn _ => "  defs: " ^ commas (map string_of_cterm defs));
   618       Seq.of_list [LocalDefs.expand (filter (is_okdef fixed o Thm.term_of) defs) st]
   619   end;
   620 
   621 
   622 fun meson_general_tac ths i st0 =
   623  let val _ = Output.debug (fn () => "Meson called: " ^ cat_lines (map string_of_thm ths))
   624  in  (Meson.meson_claset_tac (cnf_rules_of_ths ths) HOL_cs i THEN expand_defs_tac st0) st0 end;
   625 
   626 val meson_method_setup = Method.add_methods
   627   [("meson", Method.thms_args (fn ths =>
   628       Method.SIMPLE_METHOD' (CHANGED_PROP o meson_general_tac ths)),
   629     "MESON resolution proof procedure")];
   630 
   631 (** Attribute for converting a theorem into clauses **)
   632 
   633 fun meta_cnf_axiom th = map Meson.make_meta_clause (cnf_axiom th);
   634 
   635 fun clausify_rule (th,i) = List.nth (meta_cnf_axiom th, i)
   636 
   637 val clausify = Attrib.syntax (Scan.lift Args.nat
   638   >> (fn i => Thm.rule_attribute (fn _ => fn th => clausify_rule (th, i))));
   639 
   640 
   641 (*** Converting a subgoal into negated conjecture clauses. ***)
   642 
   643 val neg_skolemize_tac = EVERY' [rtac ccontr, ObjectLogic.atomize_prems_tac, skolemize_tac];
   644 
   645 (*finish_cnf removes tautologies and functional reflexivity axioms, but by calling Thm.varifyT
   646   it can introduce TVars, which are useless in conjecture clauses.*)
   647 val no_tvars = null o term_tvars o prop_of;
   648 
   649 val neg_clausify = filter no_tvars o Meson.finish_cnf o assume_abstract_list "subgoal" o make_clauses;
   650 
   651 fun neg_conjecture_clauses st0 n =
   652   let val st = Seq.hd (neg_skolemize_tac n st0)
   653       val (params,_,_) = strip_context (Logic.nth_prem (n, Thm.prop_of st))
   654   in (neg_clausify (Option.valOf (metahyps_thms n st)), params) end
   655   handle Option => raise ERROR "unable to Skolemize subgoal";
   656 
   657 (*Conversion of a subgoal to conjecture clauses. Each clause has  
   658   leading !!-bound universal variables, to express generality. *)
   659 val neg_clausify_tac = 
   660   neg_skolemize_tac THEN' 
   661   SUBGOAL
   662     (fn (prop,_) =>
   663      let val ts = Logic.strip_assums_hyp prop
   664      in EVERY1 
   665 	 [METAHYPS
   666 	    (fn hyps => 
   667               (Method.insert_tac
   668                 (map forall_intr_vars (neg_clausify hyps)) 1)),
   669 	  REPEAT_DETERM_N (length ts) o (etac thin_rl)]
   670      end);
   671 
   672 (** The Skolemization attribute **)
   673 
   674 fun conj2_rule (th1,th2) = conjI OF [th1,th2];
   675 
   676 (*Conjoin a list of theorems to form a single theorem*)
   677 fun conj_rule []  = TrueI
   678   | conj_rule ths = foldr1 conj2_rule ths;
   679 
   680 fun skolem_attr (Context.Theory thy, th) =
   681       let val (cls, thy') = skolem_cache_thm (ThmCache.get thy) th thy
   682       in (Context.Theory thy', conj_rule cls) end
   683   | skolem_attr (context, th) = (context, th)
   684 
   685 val setup_attrs = Attrib.add_attributes
   686   [("skolem", Attrib.no_args skolem_attr, "skolemization of a theorem"),
   687    ("clausify", clausify, "conversion of theorem to clauses")];
   688 
   689 val setup_methods = Method.add_methods
   690   [("neg_clausify", Method.no_args (Method.SIMPLE_METHOD' neg_clausify_tac), 
   691     "conversion of goal to conjecture clauses")];
   692      
   693 val setup = clause_cache_setup #> ThmCache.init #> setup_attrs #> setup_methods;
   694 
   695 end;