src/HOL/Tools/groebner.ML
author huffman
Fri Mar 30 12:32:35 2012 +0200 (2012-03-30)
changeset 47220 52426c62b5d0
parent 46497 89ccf66aa73d
child 47432 e1576d13e933
permissions -rw-r--r--
replace lemmas eval_nat_numeral with a simpler reformulation
     1 (*  Title:      HOL/Tools/groebner.ML
     2     Author:     Amine Chaieb, TU Muenchen
     3 *)
     4 
     5 signature GROEBNER =
     6 sig
     7   val ring_and_ideal_conv:
     8     {idom: thm list, ring: cterm list * thm list, field: cterm list * thm list,
     9      vars: cterm list, semiring: cterm list * thm list, ideal : thm list} ->
    10     (cterm -> Rat.rat) -> (Rat.rat -> cterm) ->
    11     conv ->  conv ->
    12      {ring_conv : conv,
    13      simple_ideal: (cterm list -> cterm -> (cterm * cterm -> order) -> cterm list),
    14      multi_ideal: cterm list -> cterm list -> cterm list -> (cterm * cterm) list,
    15      poly_eq_ss: simpset, unwind_conv : conv}
    16   val ring_tac: thm list -> thm list -> Proof.context -> int -> tactic
    17   val ideal_tac: thm list -> thm list -> Proof.context -> int -> tactic
    18   val algebra_tac: thm list -> thm list -> Proof.context -> int -> tactic
    19   val algebra_method: (Proof.context -> Method.method) context_parser
    20 end
    21 
    22 structure Groebner : GROEBNER =
    23 struct
    24 
    25 fun is_comb ct =
    26   (case Thm.term_of ct of
    27     _ $ _ => true
    28   | _ => false);
    29 
    30 val concl = Thm.cprop_of #> Thm.dest_arg;
    31 
    32 fun is_binop ct ct' =
    33   (case Thm.term_of ct' of
    34     c $ _ $ _ => term_of ct aconv c
    35   | _ => false);
    36 
    37 fun dest_binary ct ct' =
    38   if is_binop ct ct' then Thm.dest_binop ct'
    39   else raise CTERM ("dest_binary: bad binop", [ct, ct'])
    40 
    41 fun inst_thm inst = Thm.instantiate ([], inst);
    42 
    43 val rat_0 = Rat.zero;
    44 val rat_1 = Rat.one;
    45 val minus_rat = Rat.neg;
    46 val denominator_rat = Rat.quotient_of_rat #> snd #> Rat.rat_of_int;
    47 fun int_of_rat a =
    48     case Rat.quotient_of_rat a of (i,1) => i | _ => error "int_of_rat: not an int";
    49 val lcm_rat = fn x => fn y => Rat.rat_of_int (Integer.lcm (int_of_rat x) (int_of_rat y));
    50 
    51 val (eqF_intr, eqF_elim) =
    52   let val [th1,th2] = @{thms PFalse}
    53   in (fn th => th COMP th2, fn th => th COMP th1) end;
    54 
    55 val (PFalse, PFalse') =
    56  let val PFalse_eq = nth @{thms simp_thms} 13
    57  in (PFalse_eq RS iffD1, PFalse_eq RS iffD2) end;
    58 
    59 
    60 (* Type for recording history, i.e. how a polynomial was obtained. *)
    61 
    62 datatype history =
    63    Start of int
    64  | Mmul of (Rat.rat * int list) * history
    65  | Add of history * history;
    66 
    67 
    68 (* Monomial ordering. *)
    69 
    70 fun morder_lt m1 m2=
    71     let fun lexorder l1 l2 =
    72             case (l1,l2) of
    73                 ([],[]) => false
    74               | (x1::o1,x2::o2) => x1 > x2 orelse x1 = x2 andalso lexorder o1 o2
    75               | _ => error "morder: inconsistent monomial lengths"
    76         val n1 = Integer.sum m1
    77         val n2 = Integer.sum m2 in
    78     n1 < n2 orelse n1 = n2 andalso lexorder m1 m2
    79     end;
    80 
    81 fun morder_le m1 m2 = morder_lt m1 m2 orelse (m1 = m2);
    82 
    83 fun morder_gt m1 m2 = morder_lt m2 m1;
    84 
    85 (* Arithmetic on canonical polynomials. *)
    86 
    87 fun grob_neg l = map (fn (c,m) => (minus_rat c,m)) l;
    88 
    89 fun grob_add l1 l2 =
    90   case (l1,l2) of
    91     ([],l2) => l2
    92   | (l1,[]) => l1
    93   | ((c1,m1)::o1,(c2,m2)::o2) =>
    94         if m1 = m2 then
    95           let val c = c1+/c2 val rest = grob_add o1 o2 in
    96           if c =/ rat_0 then rest else (c,m1)::rest end
    97         else if morder_lt m2 m1 then (c1,m1)::(grob_add o1 l2)
    98         else (c2,m2)::(grob_add l1 o2);
    99 
   100 fun grob_sub l1 l2 = grob_add l1 (grob_neg l2);
   101 
   102 fun grob_mmul (c1,m1) (c2,m2) = (c1*/c2, ListPair.map (op +) (m1, m2));
   103 
   104 fun grob_cmul cm pol = map (grob_mmul cm) pol;
   105 
   106 fun grob_mul l1 l2 =
   107   case l1 of
   108     [] => []
   109   | (h1::t1) => grob_add (grob_cmul h1 l2) (grob_mul t1 l2);
   110 
   111 fun grob_inv l =
   112   case l of
   113     [(c,vs)] => if (forall (fn x => x = 0) vs) then
   114                   if (c =/ rat_0) then error "grob_inv: division by zero"
   115                   else [(rat_1 // c,vs)]
   116               else error "grob_inv: non-constant divisor polynomial"
   117   | _ => error "grob_inv: non-constant divisor polynomial";
   118 
   119 fun grob_div l1 l2 =
   120   case l2 of
   121     [(c,l)] => if (forall (fn x => x = 0) l) then
   122                  if c =/ rat_0 then error "grob_div: division by zero"
   123                  else grob_cmul (rat_1 // c,l) l1
   124              else error "grob_div: non-constant divisor polynomial"
   125   | _ => error "grob_div: non-constant divisor polynomial";
   126 
   127 fun grob_pow vars l n =
   128   if n < 0 then error "grob_pow: negative power"
   129   else if n = 0 then [(rat_1,map (fn v => 0) vars)]
   130   else grob_mul l (grob_pow vars l (n - 1));
   131 
   132 fun degree vn p =
   133  case p of
   134   [] => error "Zero polynomial"
   135 | [(c,ns)] => nth ns vn
   136 | (c,ns)::p' => Int.max (nth ns vn, degree vn p');
   137 
   138 fun head_deg vn p = let val d = degree vn p in
   139  (d,fold (fn (c,r) => fn q => grob_add q [(c, map_index (fn (i,n) => if i = vn then 0 else n) r)]) (filter (fn (c,ns) => c <>/ rat_0 andalso nth ns vn = d) p) []) end;
   140 
   141 val is_zerop = forall (fn (c,ns) => c =/ rat_0 andalso forall (curry (op =) 0) ns);
   142 val grob_pdiv =
   143  let fun pdiv_aux vn (n,a) p k s =
   144   if is_zerop s then (k,s) else
   145   let val (m,b) = head_deg vn s
   146   in if m < n then (k,s) else
   147      let val p' = grob_mul p [(rat_1, map_index (fn (i,v) => if i = vn then m - n else 0)
   148                                                 (snd (hd s)))]
   149      in if a = b then pdiv_aux vn (n,a) p k (grob_sub s p')
   150         else pdiv_aux vn (n,a) p (k + 1) (grob_sub (grob_mul a s) (grob_mul b p'))
   151      end
   152   end
   153  in fn vn => fn s => fn p => pdiv_aux vn (head_deg vn p) p 0 s
   154  end;
   155 
   156 (* Monomial division operation. *)
   157 
   158 fun mdiv (c1,m1) (c2,m2) =
   159   (c1//c2,
   160    map2 (fn n1 => fn n2 => if n1 < n2 then error "mdiv" else n1 - n2) m1 m2);
   161 
   162 (* Lowest common multiple of two monomials. *)
   163 
   164 fun mlcm (c1,m1) (c2,m2) = (rat_1, ListPair.map Int.max (m1, m2));
   165 
   166 (* Reduce monomial cm by polynomial pol, returning replacement for cm.  *)
   167 
   168 fun reduce1 cm (pol,hpol) =
   169   case pol of
   170     [] => error "reduce1"
   171   | cm1::cms => ((let val (c,m) = mdiv cm cm1 in
   172                     (grob_cmul (minus_rat c,m) cms,
   173                      Mmul((minus_rat c,m),hpol)) end)
   174                 handle  ERROR _ => error "reduce1");
   175 
   176 (* Try this for all polynomials in a basis.  *)
   177 fun tryfind f l =
   178     case l of
   179         [] => error "tryfind"
   180       | (h::t) => ((f h) handle ERROR _ => tryfind f t);
   181 
   182 fun reduceb cm basis = tryfind (fn p => reduce1 cm p) basis;
   183 
   184 (* Reduction of a polynomial (always picking largest monomial possible).     *)
   185 
   186 fun reduce basis (pol,hist) =
   187   case pol of
   188     [] => (pol,hist)
   189   | cm::ptl => ((let val (q,hnew) = reduceb cm basis in
   190                    reduce basis (grob_add q ptl,Add(hnew,hist)) end)
   191                handle (ERROR _) =>
   192                    (let val (q,hist') = reduce basis (ptl,hist) in
   193                        (cm::q,hist') end));
   194 
   195 (* Check for orthogonality w.r.t. LCM.                                       *)
   196 
   197 fun orthogonal l p1 p2 =
   198   snd l = snd(grob_mmul (hd p1) (hd p2));
   199 
   200 (* Compute S-polynomial of two polynomials.                                  *)
   201 
   202 fun spoly cm ph1 ph2 =
   203   case (ph1,ph2) of
   204     (([],h),p) => ([],h)
   205   | (p,([],h)) => ([],h)
   206   | ((cm1::ptl1,his1),(cm2::ptl2,his2)) =>
   207         (grob_sub (grob_cmul (mdiv cm cm1) ptl1)
   208                   (grob_cmul (mdiv cm cm2) ptl2),
   209          Add(Mmul(mdiv cm cm1,his1),
   210              Mmul(mdiv (minus_rat(fst cm),snd cm) cm2,his2)));
   211 
   212 (* Make a polynomial monic.                                                  *)
   213 
   214 fun monic (pol,hist) =
   215   if null pol then (pol,hist) else
   216   let val (c',m') = hd pol in
   217   (map (fn (c,m) => (c//c',m)) pol,
   218    Mmul((rat_1 // c',map (K 0) m'),hist)) end;
   219 
   220 (* The most popular heuristic is to order critical pairs by LCM monomial.    *)
   221 
   222 fun forder ((c1,m1),_) ((c2,m2),_) = morder_lt m1 m2;
   223 
   224 fun poly_lt  p q =
   225   case (p,q) of
   226     (p,[]) => false
   227   | ([],q) => true
   228   | ((c1,m1)::o1,(c2,m2)::o2) =>
   229         c1 </ c2 orelse
   230         c1 =/ c2 andalso ((morder_lt m1 m2) orelse m1 = m2 andalso poly_lt o1 o2);
   231 
   232 fun align  ((p,hp),(q,hq)) =
   233   if poly_lt p q then ((p,hp),(q,hq)) else ((q,hq),(p,hp));
   234 
   235 fun poly_eq p1 p2 =
   236   eq_list (fn ((c1, m1), (c2, m2)) => c1 =/ c2 andalso (m1: int list) = m2) (p1, p2);
   237 
   238 fun memx ((p1,h1),(p2,h2)) ppairs =
   239   not (exists (fn ((q1,_),(q2,_)) => poly_eq p1 q1 andalso poly_eq p2 q2) ppairs);
   240 
   241 (* Buchberger's second criterion.                                            *)
   242 
   243 fun criterion2 basis (lcm,((p1,h1),(p2,h2))) opairs =
   244   exists (fn g => not(poly_eq (fst g) p1) andalso not(poly_eq (fst g) p2) andalso
   245                    can (mdiv lcm) (hd(fst g)) andalso
   246                    not(memx (align (g,(p1,h1))) (map snd opairs)) andalso
   247                    not(memx (align (g,(p2,h2))) (map snd opairs))) basis;
   248 
   249 (* Test for hitting constant polynomial.                                     *)
   250 
   251 fun constant_poly p =
   252   length p = 1 andalso forall (fn x => x = 0) (snd(hd p));
   253 
   254 (* Grobner basis algorithm.                                                  *)
   255 
   256 (* FIXME: try to get rid of mergesort? *)
   257 fun merge ord l1 l2 =
   258  case l1 of
   259   [] => l2
   260  | h1::t1 =>
   261    case l2 of
   262     [] => l1
   263    | h2::t2 => if ord h1 h2 then h1::(merge ord t1 l2)
   264                else h2::(merge ord l1 t2);
   265 fun mergesort ord l =
   266  let
   267  fun mergepairs l1 l2 =
   268   case (l1,l2) of
   269    ([s],[]) => s
   270  | (l,[]) => mergepairs [] l
   271  | (l,[s1]) => mergepairs (s1::l) []
   272  | (l,(s1::s2::ss)) => mergepairs ((merge ord s1 s2)::l) ss
   273  in if null l  then []  else mergepairs [] (map (fn x => [x]) l)
   274  end;
   275 
   276 
   277 fun grobner_basis basis pairs =
   278  case pairs of
   279    [] => basis
   280  | (l,(p1,p2))::opairs =>
   281    let val (sph as (sp,hist)) = monic (reduce basis (spoly l p1 p2))
   282    in
   283     if null sp orelse criterion2 basis (l,(p1,p2)) opairs
   284     then grobner_basis basis opairs
   285     else if constant_poly sp then grobner_basis (sph::basis) []
   286     else
   287      let
   288       val rawcps = map (fn p => (mlcm (hd(fst p)) (hd sp),align(p,sph)))
   289                               basis
   290       val newcps = filter (fn (l,(p,q)) => not(orthogonal l (fst p) (fst q)))
   291                         rawcps
   292      in grobner_basis (sph::basis)
   293                  (merge forder opairs (mergesort forder newcps))
   294      end
   295    end;
   296 
   297 (* Interreduce initial polynomials.                                          *)
   298 
   299 fun grobner_interreduce rpols ipols =
   300   case ipols of
   301     [] => map monic (rev rpols)
   302   | p::ps => let val p' = reduce (rpols @ ps) p in
   303              if null (fst p') then grobner_interreduce rpols ps
   304              else grobner_interreduce (p'::rpols) ps end;
   305 
   306 (* Overall function.                                                         *)
   307 
   308 fun grobner pols =
   309     let val npols = map_index (fn (n, p) => (p, Start n)) pols
   310         val phists = filter (fn (p,_) => not (null p)) npols
   311         val bas = grobner_interreduce [] (map monic phists)
   312         val prs0 = map_product pair bas bas
   313         val prs1 = filter (fn ((x,_),(y,_)) => poly_lt x y) prs0
   314         val prs2 = map (fn (p,q) => (mlcm (hd(fst p)) (hd(fst q)),(p,q))) prs1
   315         val prs3 =
   316             filter (fn (l,(p,q)) => not(orthogonal l (fst p) (fst q))) prs2 in
   317         grobner_basis bas (mergesort forder prs3) end;
   318 
   319 (* Get proof of contradiction from Grobner basis.                            *)
   320 
   321 fun find p l =
   322   case l of
   323       [] => error "find"
   324     | (h::t) => if p(h) then h else find p t;
   325 
   326 fun grobner_refute pols =
   327   let val gb = grobner pols in
   328   snd(find (fn (p,h) => length p = 1 andalso forall (fn x=> x=0) (snd(hd p))) gb)
   329   end;
   330 
   331 (* Turn proof into a certificate as sum of multipliers.                      *)
   332 (* In principle this is very inefficient: in a heavily shared proof it may   *)
   333 (* make the same calculation many times. Could put in a cache or something.  *)
   334 
   335 fun resolve_proof vars prf =
   336   case prf of
   337     Start(~1) => []
   338   | Start m => [(m,[(rat_1,map (K 0) vars)])]
   339   | Mmul(pol,lin) =>
   340         let val lis = resolve_proof vars lin in
   341             map (fn (n,p) => (n,grob_cmul pol p)) lis end
   342   | Add(lin1,lin2) =>
   343         let val lis1 = resolve_proof vars lin1
   344             val lis2 = resolve_proof vars lin2
   345             val dom = distinct (op =) (union (op =) (map fst lis1) (map fst lis2))
   346         in
   347             map (fn n => let val a = these (AList.lookup (op =) lis1 n)
   348                              val b = these (AList.lookup (op =) lis2 n)
   349                          in (n,grob_add a b) end) dom end;
   350 
   351 (* Run the procedure and produce Weak Nullstellensatz certificate.           *)
   352 
   353 fun grobner_weak vars pols =
   354     let val cert = resolve_proof vars (grobner_refute pols)
   355         val l =
   356             fold_rev (fold_rev (lcm_rat o denominator_rat o fst) o snd) cert (rat_1) in
   357         (l,map (fn (i,p) => (i,map (fn (d,m) => (l*/d,m)) p)) cert) end;
   358 
   359 (* Prove a polynomial is in ideal generated by others, using Grobner basis.  *)
   360 
   361 fun grobner_ideal vars pols pol =
   362   let val (pol',h) = reduce (grobner pols) (grob_neg pol,Start(~1)) in
   363   if not (null pol') then error "grobner_ideal: not in the ideal" else
   364   resolve_proof vars h end;
   365 
   366 (* Produce Strong Nullstellensatz certificate for a power of pol.            *)
   367 
   368 fun grobner_strong vars pols pol =
   369     let val vars' = @{cterm "True"}::vars
   370         val grob_z = [(rat_1,1::(map (fn x => 0) vars))]
   371         val grob_1 = [(rat_1,(map (fn x => 0) vars'))]
   372         fun augment p= map (fn (c,m) => (c,0::m)) p
   373         val pols' = map augment pols
   374         val pol' = augment pol
   375         val allpols = (grob_sub (grob_mul grob_z pol') grob_1)::pols'
   376         val (l,cert) = grobner_weak vars' allpols
   377         val d = fold (fold (Integer.max o hd o snd) o snd) cert 0
   378         fun transform_monomial (c,m) =
   379             grob_cmul (c,tl m) (grob_pow vars pol (d - hd m))
   380         fun transform_polynomial q = fold_rev (grob_add o transform_monomial) q []
   381         val cert' = map (fn (c,q) => (c-1,transform_polynomial q))
   382                         (filter (fn (k,_) => k <> 0) cert) in
   383         (d,l,cert') end;
   384 
   385 
   386 (* Overall parametrized universal procedure for (semi)rings.                 *)
   387 (* We return an ideal_conv and the actual ring prover.                       *)
   388 
   389 fun refute_disj rfn tm =
   390  case term_of tm of
   391   Const(@{const_name HOL.disj},_)$l$r =>
   392    Drule.compose_single
   393     (refute_disj rfn (Thm.dest_arg tm), 2,
   394       Drule.compose_single (refute_disj rfn (Thm.dest_arg1 tm), 2, disjE))
   395   | _ => rfn tm ;
   396 
   397 val notnotD = @{thm notnotD};
   398 fun mk_binop ct x y = Thm.apply (Thm.apply ct x) y
   399 
   400 fun is_neg t =
   401     case term_of t of
   402       (Const(@{const_name Not},_)$p) => true
   403     | _  => false;
   404 fun is_eq t =
   405  case term_of t of
   406  (Const(@{const_name HOL.eq},_)$_$_) => true
   407 | _  => false;
   408 
   409 fun end_itlist f l =
   410   case l of
   411         []     => error "end_itlist"
   412       | [x]    => x
   413       | (h::t) => f h (end_itlist f t);
   414 
   415 val list_mk_binop = fn b => end_itlist (mk_binop b);
   416 
   417 val list_dest_binop = fn b =>
   418  let fun h acc t =
   419   ((let val (l,r) = dest_binary b t in h (h acc r) l end)
   420    handle CTERM _ => (t::acc)) (* Why had I handle _ => ? *)
   421  in h []
   422  end;
   423 
   424 val strip_exists =
   425  let fun h (acc, t) =
   426       case term_of t of
   427        Const (@{const_name Ex}, _) $ Abs (x, T, p) =>
   428         h (Thm.dest_abs NONE (Thm.dest_arg t) |>> (fn v => v::acc))
   429      | _ => (acc,t)
   430  in fn t => h ([],t)
   431  end;
   432 
   433 fun is_forall t =
   434  case term_of t of
   435   (Const(@{const_name All},_)$Abs(_,_,_)) => true
   436 | _ => false;
   437 
   438 val mk_object_eq = fn th => th COMP meta_eq_to_obj_eq;
   439 val bool_simps = @{thms bool_simps};
   440 val nnf_simps = @{thms nnf_simps};
   441 val nnf_conv = Simplifier.rewrite (HOL_basic_ss addsimps bool_simps addsimps nnf_simps)
   442 val weak_dnf_conv = Simplifier.rewrite (HOL_basic_ss addsimps @{thms weak_dnf_simps});
   443 val initial_conv =
   444     Simplifier.rewrite
   445      (HOL_basic_ss addsimps nnf_simps
   446        addsimps [not_all, not_ex]
   447        addsimps map (fn th => th RS sym) (@{thms ex_simps} @ @{thms all_simps}));
   448 
   449 val specl = fold_rev (fn x => fn th => instantiate' [] [SOME x] (th RS spec));
   450 
   451 val cTrp = @{cterm "Trueprop"};
   452 val cConj = @{cterm HOL.conj};
   453 val (cNot,false_tm) = (@{cterm "Not"}, @{cterm "False"});
   454 val assume_Trueprop = Thm.apply cTrp #> Thm.assume;
   455 val list_mk_conj = list_mk_binop cConj;
   456 val conjs = list_dest_binop cConj;
   457 val mk_neg = Thm.apply cNot;
   458 
   459 fun striplist dest =
   460  let
   461   fun h acc x = case try dest x of
   462     SOME (a,b) => h (h acc b) a
   463   | NONE => x::acc
   464  in h [] end;
   465 fun list_mk_binop b = foldr1 (fn (s,t) => Thm.apply (Thm.apply b s) t);
   466 
   467 val eq_commute = mk_meta_eq @{thm eq_commute};
   468 
   469 fun sym_conv eq =
   470  let val (l,r) = Thm.dest_binop eq
   471  in instantiate' [SOME (ctyp_of_term l)] [SOME l, SOME r] eq_commute
   472  end;
   473 
   474   (* FIXME : copied from cqe.ML -- complex QE*)
   475 fun conjuncts ct =
   476  case term_of ct of
   477   @{term HOL.conj}$_$_ => (Thm.dest_arg1 ct)::(conjuncts (Thm.dest_arg ct))
   478 | _ => [ct];
   479 
   480 fun fold1 f = foldr1 (uncurry f);
   481 
   482 val list_conj = fold1 (fn c => fn c' => Thm.apply (Thm.apply @{cterm HOL.conj} c) c') ;
   483 
   484 fun mk_conj_tab th =
   485  let fun h acc th =
   486    case prop_of th of
   487    @{term "Trueprop"}$(@{term HOL.conj}$p$q) =>
   488      h (h acc (th RS conjunct2)) (th RS conjunct1)
   489   | @{term "Trueprop"}$p => (p,th)::acc
   490 in fold (Termtab.insert Thm.eq_thm) (h [] th) Termtab.empty end;
   491 
   492 fun is_conj (@{term HOL.conj}$_$_) = true
   493   | is_conj _ = false;
   494 
   495 fun prove_conj tab cjs =
   496  case cjs of
   497    [c] => if is_conj (term_of c) then prove_conj tab (conjuncts c) else tab c
   498  | c::cs => conjI OF [prove_conj tab [c], prove_conj tab cs];
   499 
   500 fun conj_ac_rule eq =
   501  let
   502   val (l,r) = Thm.dest_equals eq
   503   val ctabl = mk_conj_tab (Thm.assume (Thm.apply @{cterm Trueprop} l))
   504   val ctabr = mk_conj_tab (Thm.assume (Thm.apply @{cterm Trueprop} r))
   505   fun tabl c = the (Termtab.lookup ctabl (term_of c))
   506   fun tabr c = the (Termtab.lookup ctabr (term_of c))
   507   val thl  = prove_conj tabl (conjuncts r) |> implies_intr_hyps
   508   val thr  = prove_conj tabr (conjuncts l) |> implies_intr_hyps
   509   val eqI = instantiate' [] [SOME l, SOME r] @{thm iffI}
   510  in Thm.implies_elim (Thm.implies_elim eqI thl) thr |> mk_meta_eq end;
   511 
   512  (* END FIXME.*)
   513 
   514    (* Conversion for the equivalence of existential statements where
   515       EX quantifiers are rearranged differently *)
   516  fun ext T = Drule.cterm_rule (instantiate' [SOME T] []) @{cpat Ex}
   517  fun mk_ex v t = Thm.apply (ext (ctyp_of_term v)) (Thm.lambda v t)
   518 
   519 fun choose v th th' = case concl_of th of
   520   @{term Trueprop} $ (Const(@{const_name Ex},_)$_) =>
   521    let
   522     val p = (funpow 2 Thm.dest_arg o cprop_of) th
   523     val T = (hd o Thm.dest_ctyp o ctyp_of_term) p
   524     val th0 = Conv.fconv_rule (Thm.beta_conversion true)
   525         (instantiate' [SOME T] [SOME p, (SOME o Thm.dest_arg o cprop_of) th'] exE)
   526     val pv = (Thm.rhs_of o Thm.beta_conversion true)
   527           (Thm.apply @{cterm Trueprop} (Thm.apply p v))
   528     val th1 = Thm.forall_intr v (Thm.implies_intr pv th')
   529    in Thm.implies_elim (Thm.implies_elim th0 th) th1  end
   530 | _ => error ""  (* FIXME ? *)
   531 
   532 fun simple_choose v th =
   533    choose v (Thm.assume ((Thm.apply @{cterm Trueprop} o mk_ex v)
   534     ((Thm.dest_arg o hd o #hyps o Thm.crep_thm) th))) th
   535 
   536 
   537  fun mkexi v th =
   538   let
   539    val p = Thm.lambda v (Thm.dest_arg (Thm.cprop_of th))
   540   in Thm.implies_elim
   541     (Conv.fconv_rule (Thm.beta_conversion true)
   542       (instantiate' [SOME (ctyp_of_term v)] [SOME p, SOME v] @{thm exI}))
   543       th
   544   end
   545  fun ex_eq_conv t =
   546   let
   547   val (p0,q0) = Thm.dest_binop t
   548   val (vs',P) = strip_exists p0
   549   val (vs,_) = strip_exists q0
   550    val th = Thm.assume (Thm.apply @{cterm Trueprop} P)
   551    val th1 = implies_intr_hyps (fold simple_choose vs' (fold mkexi vs th))
   552    val th2 = implies_intr_hyps (fold simple_choose vs (fold mkexi vs' th))
   553    val p = (Thm.dest_arg o Thm.dest_arg1 o cprop_of) th1
   554    val q = (Thm.dest_arg o Thm.dest_arg o cprop_of) th1
   555   in Thm.implies_elim (Thm.implies_elim (instantiate' [] [SOME p, SOME q] iffI) th1) th2
   556      |> mk_meta_eq
   557   end;
   558 
   559 
   560  fun getname v = case term_of v of
   561   Free(s,_) => s
   562  | Var ((s,_),_) => s
   563  | _ => "x"
   564  fun mk_eq s t = Thm.apply (Thm.apply @{cterm "op == :: bool => _"} s) t
   565  fun mkeq s t = Thm.apply @{cterm Trueprop} (Thm.apply (Thm.apply @{cterm "op = :: bool => _"} s) t)
   566  fun mk_exists v th = Drule.arg_cong_rule (ext (ctyp_of_term v))
   567    (Thm.abstract_rule (getname v) v th)
   568  val simp_ex_conv =
   569      Simplifier.rewrite (HOL_basic_ss addsimps @{thms simp_thms(39)})
   570 
   571 fun frees t = Thm.add_cterm_frees t [];
   572 fun free_in v t = member op aconvc (frees t) v;
   573 
   574 val vsubst = let
   575  fun vsubst (t,v) tm =
   576    (Thm.rhs_of o Thm.beta_conversion false) (Thm.apply (Thm.lambda v tm) t)
   577 in fold vsubst end;
   578 
   579 
   580 (** main **)
   581 
   582 fun ring_and_ideal_conv
   583   {vars, semiring = (sr_ops, sr_rules), ring = (r_ops, r_rules),
   584    field = (f_ops, f_rules), idom, ideal}
   585   dest_const mk_const ring_eq_conv ring_normalize_conv =
   586 let
   587   val [add_pat, mul_pat, pow_pat, zero_tm, one_tm] = sr_ops;
   588   val [ring_add_tm, ring_mul_tm, ring_pow_tm] =
   589     map Thm.dest_fun2 [add_pat, mul_pat, pow_pat];
   590 
   591   val (ring_sub_tm, ring_neg_tm) =
   592     (case r_ops of
   593      [sub_pat, neg_pat] => (Thm.dest_fun2 sub_pat, Thm.dest_fun neg_pat)
   594     |_  => (@{cterm "True"}, @{cterm "True"}));
   595 
   596   val (field_div_tm, field_inv_tm) =
   597     (case f_ops of
   598        [div_pat, inv_pat] => (Thm.dest_fun2 div_pat, Thm.dest_fun inv_pat)
   599      | _ => (@{cterm "True"}, @{cterm "True"}));
   600 
   601   val [idom_thm, neq_thm] = idom;
   602   val [idl_sub, idl_add0] =
   603      if length ideal = 2 then ideal else [eq_commute, eq_commute]
   604   fun ring_dest_neg t =
   605     let val (l,r) = Thm.dest_comb t
   606     in if Term.could_unify(term_of l,term_of ring_neg_tm) then r
   607        else raise CTERM ("ring_dest_neg", [t])
   608     end
   609 
   610  val ring_mk_neg = fn tm => Thm.apply (ring_neg_tm) (tm);
   611  fun field_dest_inv t =
   612     let val (l,r) = Thm.dest_comb t in
   613         if Term.could_unify(term_of l, term_of field_inv_tm) then r
   614         else raise CTERM ("field_dest_inv", [t])
   615     end
   616  val ring_dest_add = dest_binary ring_add_tm;
   617  val ring_mk_add = mk_binop ring_add_tm;
   618  val ring_dest_sub = dest_binary ring_sub_tm;
   619  val ring_mk_sub = mk_binop ring_sub_tm;
   620  val ring_dest_mul = dest_binary ring_mul_tm;
   621  val ring_mk_mul = mk_binop ring_mul_tm;
   622  val field_dest_div = dest_binary field_div_tm;
   623  val field_mk_div = mk_binop field_div_tm;
   624  val ring_dest_pow = dest_binary ring_pow_tm;
   625  val ring_mk_pow = mk_binop ring_pow_tm ;
   626  fun grobvars tm acc =
   627     if can dest_const tm then acc
   628     else if can ring_dest_neg tm then grobvars (Thm.dest_arg tm) acc
   629     else if can ring_dest_pow tm then grobvars (Thm.dest_arg1 tm) acc
   630     else if can ring_dest_add tm orelse can ring_dest_sub tm
   631             orelse can ring_dest_mul tm
   632     then grobvars (Thm.dest_arg1 tm) (grobvars (Thm.dest_arg tm) acc)
   633     else if can field_dest_inv tm
   634          then
   635           let val gvs = grobvars (Thm.dest_arg tm) []
   636           in if null gvs then acc else tm::acc
   637           end
   638     else if can field_dest_div tm then
   639          let val lvs = grobvars (Thm.dest_arg1 tm) acc
   640              val gvs = grobvars (Thm.dest_arg tm) []
   641           in if null gvs then lvs else tm::acc
   642           end
   643     else tm::acc ;
   644 
   645 fun grobify_term vars tm =
   646 ((if not (member (op aconvc) vars tm) then raise CTERM ("Not a variable", [tm]) else
   647      [(rat_1,map (fn i => if i aconvc tm then 1 else 0) vars)])
   648 handle  CTERM _ =>
   649  ((let val x = dest_const tm
   650  in if x =/ rat_0 then [] else [(x,map (fn v => 0) vars)]
   651  end)
   652  handle ERROR _ =>
   653   ((grob_neg(grobify_term vars (ring_dest_neg tm)))
   654   handle CTERM _ =>
   655    (
   656    (grob_inv(grobify_term vars (field_dest_inv tm)))
   657    handle CTERM _ =>
   658     ((let val (l,r) = ring_dest_add tm
   659     in grob_add (grobify_term vars l) (grobify_term vars r)
   660     end)
   661     handle CTERM _ =>
   662      ((let val (l,r) = ring_dest_sub tm
   663      in grob_sub (grobify_term vars l) (grobify_term vars r)
   664      end)
   665      handle  CTERM _ =>
   666       ((let val (l,r) = ring_dest_mul tm
   667       in grob_mul (grobify_term vars l) (grobify_term vars r)
   668       end)
   669        handle CTERM _ =>
   670         (  (let val (l,r) = field_dest_div tm
   671           in grob_div (grobify_term vars l) (grobify_term vars r)
   672           end)
   673          handle CTERM _ =>
   674           ((let val (l,r) = ring_dest_pow tm
   675           in grob_pow vars (grobify_term vars l) ((term_of #> HOLogic.dest_number #> snd) r)
   676           end)
   677            handle CTERM _ => error "grobify_term: unknown or invalid term")))))))));
   678 val eq_tm = idom_thm |> concl |> Thm.dest_arg |> Thm.dest_arg |> Thm.dest_fun2;
   679 val dest_eq = dest_binary eq_tm;
   680 
   681 fun grobify_equation vars tm =
   682     let val (l,r) = dest_binary eq_tm tm
   683     in grob_sub (grobify_term vars l) (grobify_term vars r)
   684     end;
   685 
   686 fun grobify_equations tm =
   687  let
   688   val cjs = conjs tm
   689   val  rawvars =
   690     fold_rev (fn eq => fn a => grobvars (Thm.dest_arg1 eq) (grobvars (Thm.dest_arg eq) a)) cjs []
   691   val vars = sort (fn (x, y) => Term_Ord.term_ord (term_of x, term_of y))
   692                   (distinct (op aconvc) rawvars)
   693  in (vars,map (grobify_equation vars) cjs)
   694  end;
   695 
   696 val holify_polynomial =
   697  let fun holify_varpow (v,n) =
   698   if n = 1 then v else ring_mk_pow v (Numeral.mk_cnumber @{ctyp nat} n)  (* FIXME *)
   699  fun holify_monomial vars (c,m) =
   700   let val xps = map holify_varpow (filter (fn (_,n) => n <> 0) (vars ~~ m))
   701    in end_itlist ring_mk_mul (mk_const c :: xps)
   702   end
   703  fun holify_polynomial vars p =
   704      if null p then mk_const (rat_0)
   705      else end_itlist ring_mk_add (map (holify_monomial vars) p)
   706  in holify_polynomial
   707  end ;
   708 val idom_rule = simplify (HOL_basic_ss addsimps [idom_thm]);
   709 fun prove_nz n = eqF_elim
   710                  (ring_eq_conv(mk_binop eq_tm (mk_const n) (mk_const(rat_0))));
   711 val neq_01 = prove_nz (rat_1);
   712 fun neq_rule n th = [prove_nz n, th] MRS neq_thm;
   713 fun mk_add th1 = Thm.combination (Drule.arg_cong_rule ring_add_tm th1);
   714 
   715 fun refute tm =
   716  if tm aconvc false_tm then assume_Trueprop tm else
   717  ((let
   718    val (nths0,eths0) = List.partition (is_neg o concl) (HOLogic.conj_elims (assume_Trueprop tm))
   719    val  nths = filter (is_eq o Thm.dest_arg o concl) nths0
   720    val eths = filter (is_eq o concl) eths0
   721   in
   722    if null eths then
   723     let
   724       val th1 = end_itlist (fn th1 => fn th2 => idom_rule(HOLogic.conj_intr th1 th2)) nths
   725       val th2 =
   726         Conv.fconv_rule
   727           ((Conv.arg_conv #> Conv.arg_conv) (Conv.binop_conv ring_normalize_conv)) th1
   728       val conc = th2 |> concl |> Thm.dest_arg
   729       val (l,r) = conc |> dest_eq
   730     in Thm.implies_intr (Thm.apply cTrp tm)
   731                     (Thm.equal_elim (Drule.arg_cong_rule cTrp (eqF_intr th2))
   732                            (Thm.reflexive l |> mk_object_eq))
   733     end
   734    else
   735    let
   736     val (vars,l,cert,noteqth) =(
   737      if null nths then
   738       let val (vars,pols) = grobify_equations(list_mk_conj(map concl eths))
   739           val (l,cert) = grobner_weak vars pols
   740       in (vars,l,cert,neq_01)
   741       end
   742      else
   743       let
   744        val nth = end_itlist (fn th1 => fn th2 => idom_rule(HOLogic.conj_intr th1 th2)) nths
   745        val (vars,pol::pols) =
   746           grobify_equations(list_mk_conj(Thm.dest_arg(concl nth)::map concl eths))
   747        val (deg,l,cert) = grobner_strong vars pols pol
   748        val th1 =
   749         Conv.fconv_rule ((Conv.arg_conv o Conv.arg_conv) (Conv.binop_conv ring_normalize_conv)) nth
   750        val th2 = funpow deg (idom_rule o HOLogic.conj_intr th1) neq_01
   751       in (vars,l,cert,th2)
   752       end)
   753     val cert_pos = map (fn (i,p) => (i,filter (fn (c,m) => c >/ rat_0) p)) cert
   754     val cert_neg = map (fn (i,p) => (i,map (fn (c,m) => (minus_rat c,m))
   755                                             (filter (fn (c,m) => c </ rat_0) p))) cert
   756     val  herts_pos = map (fn (i,p) => (i,holify_polynomial vars p)) cert_pos
   757     val  herts_neg = map (fn (i,p) => (i,holify_polynomial vars p)) cert_neg
   758     fun thm_fn pols =
   759         if null pols then Thm.reflexive(mk_const rat_0) else
   760         end_itlist mk_add
   761             (map (fn (i,p) => Drule.arg_cong_rule (Thm.apply ring_mul_tm p)
   762               (nth eths i |> mk_meta_eq)) pols)
   763     val th1 = thm_fn herts_pos
   764     val th2 = thm_fn herts_neg
   765     val th3 = HOLogic.conj_intr(mk_add (Thm.symmetric th1) th2 |> mk_object_eq) noteqth
   766     val th4 =
   767       Conv.fconv_rule ((Conv.arg_conv o Conv.arg_conv o Conv.binop_conv) ring_normalize_conv)
   768         (neq_rule l th3)
   769     val (l,r) = dest_eq(Thm.dest_arg(concl th4))
   770    in Thm.implies_intr (Thm.apply cTrp tm)
   771                         (Thm.equal_elim (Drule.arg_cong_rule cTrp (eqF_intr th4))
   772                    (Thm.reflexive l |> mk_object_eq))
   773    end
   774   end) handle ERROR _ => raise CTERM ("Groebner-refute: unable to refute",[tm]))
   775 
   776 fun ring tm =
   777  let
   778   fun mk_forall x p =
   779     Thm.apply
   780       (Drule.cterm_rule (instantiate' [SOME (ctyp_of_term x)] [])
   781         @{cpat "All:: (?'a => bool) => _"}) (Thm.lambda x p)
   782   val avs = Thm.add_cterm_frees tm []
   783   val P' = fold mk_forall avs tm
   784   val th1 = initial_conv(mk_neg P')
   785   val (evs,bod) = strip_exists(concl th1) in
   786    if is_forall bod then raise CTERM("ring: non-universal formula",[tm])
   787    else
   788    let
   789     val th1a = weak_dnf_conv bod
   790     val boda = concl th1a
   791     val th2a = refute_disj refute boda
   792     val th2b = [mk_object_eq th1a, (th2a COMP notI) COMP PFalse'] MRS trans
   793     val th2 = fold (fn v => fn th => (Thm.forall_intr v th) COMP allI) evs (th2b RS PFalse)
   794     val th3 =
   795       Thm.equal_elim
   796         (Simplifier.rewrite (HOL_basic_ss addsimps [not_ex RS sym]) (th2 |> cprop_of)) th2
   797     in specl avs
   798              ([[[mk_object_eq th1, th3 RS PFalse'] MRS trans] MRS PFalse] MRS notnotD)
   799    end
   800  end
   801 fun ideal tms tm ord =
   802  let
   803   val rawvars = fold_rev grobvars (tm::tms) []
   804   val vars = sort ord (distinct (fn (x,y) => (term_of x) aconv (term_of y)) rawvars)
   805   val pols = map (grobify_term vars) tms
   806   val pol = grobify_term vars tm
   807   val cert = grobner_ideal vars pols pol
   808  in map_range (fn n => these (AList.lookup (op =) cert n) |> holify_polynomial vars)
   809    (length pols)
   810  end
   811 
   812 fun poly_eq_conv t =
   813  let val (a,b) = Thm.dest_binop t
   814  in Conv.fconv_rule (Conv.arg_conv (Conv.arg1_conv ring_normalize_conv))
   815      (instantiate' [] [SOME a, SOME b] idl_sub)
   816  end
   817  val poly_eq_simproc =
   818   let
   819    fun proc phi  ss t =
   820     let val th = poly_eq_conv t
   821     in if Thm.is_reflexive th then NONE else SOME th
   822     end
   823    in make_simproc {lhss = [Thm.lhs_of idl_sub],
   824                 name = "poly_eq_simproc", proc = proc, identifier = []}
   825    end;
   826   val poly_eq_ss = HOL_basic_ss addsimps @{thms simp_thms}
   827                         addsimprocs [poly_eq_simproc]
   828 
   829  local
   830   fun is_defined v t =
   831   let
   832    val mons = striplist(dest_binary ring_add_tm) t
   833   in member (op aconvc) mons v andalso
   834     forall (fn m => v aconvc m
   835           orelse not(member (op aconvc) (Thm.add_cterm_frees m []) v)) mons
   836   end
   837 
   838   fun isolate_variable vars tm =
   839   let
   840    val th = poly_eq_conv tm
   841    val th' = (sym_conv then_conv poly_eq_conv) tm
   842    val (v,th1) =
   843    case find_first(fn v=> is_defined v (Thm.dest_arg1 (Thm.rhs_of th))) vars of
   844     SOME v => (v,th')
   845    | NONE => (the (find_first
   846           (fn v => is_defined v (Thm.dest_arg1 (Thm.rhs_of th'))) vars) ,th)
   847    val th2 = Thm.transitive th1
   848         (instantiate' []  [(SOME o Thm.dest_arg1 o Thm.rhs_of) th1, SOME v]
   849           idl_add0)
   850    in Conv.fconv_rule(funpow 2 Conv.arg_conv ring_normalize_conv) th2
   851    end
   852  in
   853  fun unwind_polys_conv tm =
   854  let
   855   val (vars,bod) = strip_exists tm
   856   val cjs = striplist (dest_binary @{cterm HOL.conj}) bod
   857   val th1 = (the (get_first (try (isolate_variable vars)) cjs)
   858              handle Option => raise CTERM ("unwind_polys_conv",[tm]))
   859   val eq = Thm.lhs_of th1
   860   val bod' = list_mk_binop @{cterm HOL.conj} (eq::(remove op aconvc eq cjs))
   861   val th2 = conj_ac_rule (mk_eq bod bod')
   862   val th3 =
   863     Thm.transitive th2
   864       (Drule.binop_cong_rule @{cterm HOL.conj} th1
   865         (Thm.reflexive (Thm.dest_arg (Thm.rhs_of th2))))
   866   val v = Thm.dest_arg1(Thm.dest_arg1(Thm.rhs_of th3))
   867   val vars' = (remove op aconvc v vars) @ [v]
   868   val th4 = Conv.fconv_rule (Conv.arg_conv simp_ex_conv) (mk_exists v th3)
   869   val th5 = ex_eq_conv (mk_eq tm (fold mk_ex (remove op aconvc v vars) (Thm.lhs_of th4)))
   870  in Thm.transitive th5 (fold mk_exists (remove op aconvc v vars) th4)
   871  end;
   872 end
   873 
   874 local
   875  fun scrub_var v m =
   876   let
   877    val ps = striplist ring_dest_mul m
   878    val ps' = remove op aconvc v ps
   879   in if null ps' then one_tm else fold1 ring_mk_mul ps'
   880   end
   881  fun find_multipliers v mons =
   882   let
   883    val mons1 = filter (fn m => free_in v m) mons
   884    val mons2 = map (scrub_var v) mons1
   885    in  if null mons2 then zero_tm else fold1 ring_mk_add mons2
   886   end
   887 
   888  fun isolate_monomials vars tm =
   889  let
   890   val (cmons,vmons) =
   891     List.partition (fn m => null (inter (op aconvc) vars (frees m)))
   892                    (striplist ring_dest_add tm)
   893   val cofactors = map (fn v => find_multipliers v vmons) vars
   894   val cnc = if null cmons then zero_tm
   895              else Thm.apply ring_neg_tm
   896                     (list_mk_binop ring_add_tm cmons)
   897   in (cofactors,cnc)
   898   end;
   899 
   900 fun isolate_variables evs ps eq =
   901  let
   902   val vars = filter (fn v => free_in v eq) evs
   903   val (qs,p) = isolate_monomials vars eq
   904   val rs = ideal (qs @ ps) p
   905               (fn (s,t) => Term_Ord.term_ord (term_of s, term_of t))
   906  in (eq, take (length qs) rs ~~ vars)
   907  end;
   908  fun subst_in_poly i p = Thm.rhs_of (ring_normalize_conv (vsubst i p));
   909 in
   910  fun solve_idealism evs ps eqs =
   911   if null evs then [] else
   912   let
   913    val (eq,cfs) = get_first (try (isolate_variables evs ps)) eqs |> the
   914    val evs' = subtract op aconvc evs (map snd cfs)
   915    val eqs' = map (subst_in_poly cfs) (remove op aconvc eq eqs)
   916   in cfs @ solve_idealism evs' ps eqs'
   917   end;
   918 end;
   919 
   920 
   921 in {ring_conv = ring, simple_ideal = ideal, multi_ideal = solve_idealism,
   922     poly_eq_ss = poly_eq_ss, unwind_conv = unwind_polys_conv}
   923 end;
   924 
   925 
   926 fun find_term bounds tm =
   927   (case term_of tm of
   928     Const (@{const_name HOL.eq}, T) $ _ $ _ =>
   929       if domain_type T = HOLogic.boolT then find_args bounds tm
   930       else Thm.dest_arg tm
   931   | Const (@{const_name Not}, _) $ _ => find_term bounds (Thm.dest_arg tm)
   932   | Const (@{const_name All}, _) $ _ => find_body bounds (Thm.dest_arg tm)
   933   | Const (@{const_name Ex}, _) $ _ => find_body bounds (Thm.dest_arg tm)
   934   | Const (@{const_name HOL.conj}, _) $ _ $ _ => find_args bounds tm
   935   | Const (@{const_name HOL.disj}, _) $ _ $ _ => find_args bounds tm
   936   | Const (@{const_name HOL.implies}, _) $ _ $ _ => find_args bounds tm
   937   | @{term "op ==>"} $_$_ => find_args bounds tm
   938   | Const("op ==",_)$_$_ => find_args bounds tm
   939   | @{term Trueprop}$_ => find_term bounds (Thm.dest_arg tm)
   940   | _ => raise TERM ("find_term", []))
   941 and find_args bounds tm =
   942   let val (t, u) = Thm.dest_binop tm
   943   in (find_term bounds t handle TERM _ => find_term bounds u) end
   944 and find_body bounds b =
   945   let val (_, b') = Thm.dest_abs (SOME (Name.bound bounds)) b
   946   in find_term (bounds + 1) b' end;
   947 
   948 
   949 fun get_ring_ideal_convs ctxt form =
   950  case try (find_term 0) form of
   951   NONE => NONE
   952 | SOME tm =>
   953   (case Semiring_Normalizer.match ctxt tm of
   954     NONE => NONE
   955   | SOME (res as (theory, {is_const, dest_const,
   956           mk_const, conv = ring_eq_conv})) =>
   957      SOME (ring_and_ideal_conv theory
   958           dest_const (mk_const (ctyp_of_term tm)) (ring_eq_conv ctxt)
   959           (Semiring_Normalizer.semiring_normalize_wrapper ctxt res)))
   960 
   961 fun ring_solve ctxt form =
   962   (case try (find_term 0 (* FIXME !? *)) form of
   963     NONE => Thm.reflexive form
   964   | SOME tm =>
   965       (case Semiring_Normalizer.match ctxt tm of
   966         NONE => Thm.reflexive form
   967       | SOME (res as (theory, {is_const, dest_const, mk_const, conv = ring_eq_conv})) =>
   968         #ring_conv (ring_and_ideal_conv theory
   969           dest_const (mk_const (ctyp_of_term tm)) (ring_eq_conv ctxt)
   970           (Semiring_Normalizer.semiring_normalize_wrapper ctxt res)) form));
   971 
   972 fun presimplify ctxt add_thms del_thms = asm_full_simp_tac (Simplifier.context ctxt
   973   (HOL_basic_ss addsimps (Algebra_Simplification.get ctxt) delsimps del_thms addsimps add_thms));
   974 
   975 fun ring_tac add_ths del_ths ctxt =
   976   Object_Logic.full_atomize_tac
   977   THEN' presimplify ctxt add_ths del_ths
   978   THEN' CSUBGOAL (fn (p, i) =>
   979     rtac (let val form = Object_Logic.dest_judgment p
   980           in case get_ring_ideal_convs ctxt form of
   981            NONE => Thm.reflexive form
   982           | SOME thy => #ring_conv thy form
   983           end) i
   984       handle TERM _ => no_tac
   985         | CTERM _ => no_tac
   986         | THM _ => no_tac);
   987 
   988 local
   989  fun lhs t = case term_of t of
   990   Const(@{const_name HOL.eq},_)$_$_ => Thm.dest_arg1 t
   991  | _=> raise CTERM ("ideal_tac - lhs",[t])
   992  fun exitac NONE = no_tac
   993    | exitac (SOME y) = rtac (instantiate' [SOME (ctyp_of_term y)] [NONE,SOME y] exI) 1
   994 in
   995 fun ideal_tac add_ths del_ths ctxt =
   996   presimplify ctxt add_ths del_ths
   997  THEN'
   998  CSUBGOAL (fn (p, i) =>
   999   case get_ring_ideal_convs ctxt p of
  1000    NONE => no_tac
  1001  | SOME thy =>
  1002   let
  1003    fun poly_exists_tac {asms = asms, concl = concl, prems = prems,
  1004             params = params, context = ctxt, schematics = scs} =
  1005     let
  1006      val (evs,bod) = strip_exists (Thm.dest_arg concl)
  1007      val ps = map_filter (try (lhs o Thm.dest_arg)) asms
  1008      val cfs = (map swap o #multi_ideal thy evs ps)
  1009                    (map Thm.dest_arg1 (conjuncts bod))
  1010      val ws = map (exitac o AList.lookup op aconvc cfs) evs
  1011     in EVERY (rev ws) THEN Method.insert_tac prems 1
  1012         THEN ring_tac add_ths del_ths ctxt 1
  1013    end
  1014   in
  1015      clarify_tac @{context} i
  1016      THEN Object_Logic.full_atomize_tac i
  1017      THEN asm_full_simp_tac (Simplifier.context ctxt (#poly_eq_ss thy)) i
  1018      THEN clarify_tac @{context} i
  1019      THEN (REPEAT (CONVERSION (#unwind_conv thy) i))
  1020      THEN SUBPROOF poly_exists_tac ctxt i
  1021   end
  1022  handle TERM _ => no_tac
  1023      | CTERM _ => no_tac
  1024      | THM _ => no_tac);
  1025 end;
  1026 
  1027 fun algebra_tac add_ths del_ths ctxt i =
  1028  ring_tac add_ths del_ths ctxt i ORELSE ideal_tac add_ths del_ths ctxt i
  1029 
  1030 local
  1031 
  1032 fun keyword k = Scan.lift (Args.$$$ k -- Args.colon) >> K ()
  1033 val addN = "add"
  1034 val delN = "del"
  1035 val any_keyword = keyword addN || keyword delN
  1036 val thms = Scan.repeat (Scan.unless any_keyword Attrib.multi_thm) >> flat;
  1037 
  1038 in
  1039 
  1040 val algebra_method = ((Scan.optional (keyword addN |-- thms) []) --
  1041    (Scan.optional (keyword delN |-- thms) [])) >>
  1042   (fn (add_ths, del_ths) => fn ctxt =>
  1043        SIMPLE_METHOD' (algebra_tac add_ths del_ths ctxt))
  1044 
  1045 end;
  1046 
  1047 end;