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