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