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