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