src/HOL/Tools/lin_arith.ML
author haftmann
Wed May 05 18:25:34 2010 +0200 (2010-05-05)
changeset 36692 54b64d4ad524
parent 36001 992839c4be90
child 37388 793618618f78
permissions -rw-r--r--
farewell to old-style mem infixes -- type inference in situations with mem_int and mem_string should provide enough information to resolve the type of (op =)
     1 (*  Title:      HOL/Tools/lin_arith.ML
     2     Author:     Tjark Weber and Tobias Nipkow, TU Muenchen
     3 
     4 HOL setup for linear arithmetic (see Provers/Arith/fast_lin_arith.ML).
     5 *)
     6 
     7 signature LIN_ARITH =
     8 sig
     9   val pre_tac: simpset -> int -> tactic
    10   val simple_tac: Proof.context -> int -> tactic
    11   val tac: Proof.context -> int -> tactic
    12   val simproc: simpset -> term -> thm option
    13   val add_inj_thms: thm list -> Context.generic -> Context.generic
    14   val add_lessD: thm -> Context.generic -> Context.generic
    15   val add_simps: thm list -> Context.generic -> Context.generic
    16   val add_simprocs: simproc list -> Context.generic -> Context.generic
    17   val add_inj_const: string * typ -> Context.generic -> Context.generic
    18   val add_discrete_type: string -> Context.generic -> Context.generic
    19   val set_number_of: (theory -> typ -> int -> cterm) -> Context.generic ->
    20     Context.generic
    21   val setup: Context.generic -> Context.generic
    22   val global_setup: theory -> theory
    23   val split_limit: int Config.T
    24   val neq_limit: int Config.T
    25   val trace: bool Unsynchronized.ref
    26 end;
    27 
    28 structure Lin_Arith: LIN_ARITH =
    29 struct
    30 
    31 (* Parameters data for general linear arithmetic functor *)
    32 
    33 structure LA_Logic: LIN_ARITH_LOGIC =
    34 struct
    35 
    36 val ccontr = ccontr;
    37 val conjI = conjI;
    38 val notI = notI;
    39 val sym = sym;
    40 val trueI = TrueI;
    41 val not_lessD = @{thm linorder_not_less} RS iffD1;
    42 val not_leD = @{thm linorder_not_le} RS iffD1;
    43 
    44 fun mk_Eq thm = thm RS @{thm Eq_FalseI} handle THM _ => thm RS @{thm Eq_TrueI};
    45 
    46 val mk_Trueprop = HOLogic.mk_Trueprop;
    47 
    48 fun atomize thm = case Thm.prop_of thm of
    49     Const ("Trueprop", _) $ (Const (@{const_name "op &"}, _) $ _ $ _) =>
    50     atomize (thm RS conjunct1) @ atomize (thm RS conjunct2)
    51   | _ => [thm];
    52 
    53 fun neg_prop ((TP as Const("Trueprop", _)) $ (Const (@{const_name Not}, _) $ t)) = TP $ t
    54   | neg_prop ((TP as Const("Trueprop", _)) $ t) = TP $ (HOLogic.Not $t)
    55   | neg_prop t = raise TERM ("neg_prop", [t]);
    56 
    57 fun is_False thm =
    58   let val _ $ t = Thm.prop_of thm
    59   in t = HOLogic.false_const end;
    60 
    61 fun is_nat t = (fastype_of1 t = HOLogic.natT);
    62 
    63 fun mk_nat_thm thy t =
    64   let
    65     val cn = cterm_of thy (Var (("n", 0), HOLogic.natT))
    66     and ct = cterm_of thy t
    67   in instantiate ([], [(cn, ct)]) @{thm le0} end;
    68 
    69 end;  (* LA_Logic *)
    70 
    71 
    72 (* arith context data *)
    73 
    74 structure Lin_Arith_Data = Generic_Data
    75 (
    76   type T = {splits: thm list,
    77             inj_consts: (string * typ) list,
    78             discrete: string list};
    79   val empty = {splits = [], inj_consts = [], discrete = []};
    80   val extend = I;
    81   fun merge
    82    ({splits= splits1, inj_consts= inj_consts1, discrete= discrete1},
    83     {splits= splits2, inj_consts= inj_consts2, discrete= discrete2}) : T =
    84    {splits = Thm.merge_thms (splits1, splits2),
    85     inj_consts = Library.merge (op =) (inj_consts1, inj_consts2),
    86     discrete = Library.merge (op =) (discrete1, discrete2)};
    87 );
    88 
    89 val get_arith_data = Lin_Arith_Data.get o Context.Proof;
    90 
    91 fun add_split thm = Lin_Arith_Data.map (fn {splits, inj_consts, discrete} =>
    92   {splits = update Thm.eq_thm_prop thm splits,
    93    inj_consts = inj_consts, discrete = discrete});
    94 
    95 fun add_discrete_type d = Lin_Arith_Data.map (fn {splits, inj_consts, discrete} =>
    96   {splits = splits, inj_consts = inj_consts,
    97    discrete = update (op =) d discrete});
    98 
    99 fun add_inj_const c = Lin_Arith_Data.map (fn {splits, inj_consts, discrete} =>
   100   {splits = splits, inj_consts = update (op =) c inj_consts,
   101    discrete = discrete});
   102 
   103 val (split_limit, setup_split_limit) = Attrib.config_int "linarith_split_limit" (K 9);
   104 val (neq_limit, setup_neq_limit) = Attrib.config_int "linarith_neq_limit" (K 9);
   105 
   106 
   107 structure LA_Data =
   108 struct
   109 
   110 val fast_arith_neq_limit = neq_limit;
   111 
   112 
   113 (* Decomposition of terms *)
   114 
   115 (*internal representation of linear (in-)equations*)
   116 type decomp =
   117   ((term * Rat.rat) list * Rat.rat * string * (term * Rat.rat) list * Rat.rat * bool);
   118 
   119 fun nT (Type ("fun", [N, _])) = (N = HOLogic.natT)
   120   | nT _                      = false;
   121 
   122 fun add_atom (t : term) (m : Rat.rat) (p : (term * Rat.rat) list, i : Rat.rat) :
   123              (term * Rat.rat) list * Rat.rat =
   124   case AList.lookup Pattern.aeconv p t of
   125       NONE   => ((t, m) :: p, i)
   126     | SOME n => (AList.update Pattern.aeconv (t, Rat.add n m) p, i);
   127 
   128 (* decompose nested multiplications, bracketing them to the right and combining
   129    all their coefficients
   130 
   131    inj_consts: list of constants to be ignored when encountered
   132                (e.g. arithmetic type conversions that preserve value)
   133 
   134    m: multiplicity associated with the entire product
   135 
   136    returns either (SOME term, associated multiplicity) or (NONE, constant)
   137 *)
   138 fun demult (inj_consts : (string * typ) list) : term * Rat.rat -> term option * Rat.rat =
   139 let
   140   fun demult ((mC as Const (@{const_name Groups.times}, _)) $ s $ t, m) =
   141       (case s of Const (@{const_name Groups.times}, _) $ s1 $ s2 =>
   142         (* bracketing to the right: '(s1 * s2) * t' becomes 's1 * (s2 * t)' *)
   143         demult (mC $ s1 $ (mC $ s2 $ t), m)
   144       | _ =>
   145         (* product 's * t', where either factor can be 'NONE' *)
   146         (case demult (s, m) of
   147           (SOME s', m') =>
   148             (case demult (t, m') of
   149               (SOME t', m'') => (SOME (mC $ s' $ t'), m'')
   150             | (NONE,    m'') => (SOME s', m''))
   151         | (NONE,    m') => demult (t, m')))
   152     | demult ((mC as Const (@{const_name Rings.divide}, _)) $ s $ t, m) =
   153       (* FIXME: Shouldn't we simplify nested quotients, e.g. '(s/t)/u' could
   154          become 's/(t*u)', and '(s*t)/u' could become 's*(t/u)' ?   Note that
   155          if we choose to do so here, the simpset used by arith must be able to
   156          perform the same simplifications. *)
   157       (* FIXME: Currently we treat the numerator as atomic unless the
   158          denominator can be reduced to a numeric constant.  It might be better
   159          to demult the numerator in any case, and invent a new term of the form
   160          '1 / t' if the numerator can be reduced, but the denominator cannot. *)
   161       (* FIXME: Currently we even treat the whole fraction as atomic unless the
   162          denominator can be reduced to a numeric constant.  It might be better
   163          to use the partially reduced denominator (i.e. 's / (2*t)' could be
   164          demult'ed to 's / t' with multiplicity .5).   This would require a
   165          very simple change only below, but it breaks existing proofs. *)
   166       (* quotient 's / t', where the denominator t can be NONE *)
   167       (* Note: will raise Rat.DIVZERO iff m' is Rat.zero *)
   168       (case demult (t, Rat.one) of
   169         (SOME _, _) => (SOME (mC $ s $ t), m)
   170       | (NONE,  m') => apsnd (Rat.mult (Rat.inv m')) (demult (s, m)))
   171     (* terms that evaluate to numeric constants *)
   172     | demult (Const (@{const_name Groups.uminus}, _) $ t, m) = demult (t, Rat.neg m)
   173     | demult (Const (@{const_name Groups.zero}, _), m) = (NONE, Rat.zero)
   174     | demult (Const (@{const_name Groups.one}, _), m) = (NONE, m)
   175     (*Warning: in rare cases number_of encloses a non-numeral,
   176       in which case dest_numeral raises TERM; hence all the handles below.
   177       Same for Suc-terms that turn out not to be numerals -
   178       although the simplifier should eliminate those anyway ...*)
   179     | demult (t as Const ("Int.number_class.number_of", _) $ n, m) =
   180       ((NONE, Rat.mult m (Rat.rat_of_int (HOLogic.dest_numeral n)))
   181         handle TERM _ => (SOME t, m))
   182     | demult (t as Const (@{const_name Suc}, _) $ _, m) =
   183       ((NONE, Rat.mult m (Rat.rat_of_int (HOLogic.dest_nat t)))
   184         handle TERM _ => (SOME t, m))
   185     (* injection constants are ignored *)
   186     | demult (t as Const f $ x, m) =
   187       if member (op =) inj_consts f then demult (x, m) else (SOME t, m)
   188     (* everything else is considered atomic *)
   189     | demult (atom, m) = (SOME atom, m)
   190 in demult end;
   191 
   192 fun decomp0 (inj_consts : (string * typ) list) (rel : string, lhs : term, rhs : term) :
   193             ((term * Rat.rat) list * Rat.rat * string * (term * Rat.rat) list * Rat.rat) option =
   194 let
   195   (* Turns a term 'all' and associated multiplicity 'm' into a list 'p' of
   196      summands and associated multiplicities, plus a constant 'i' (with implicit
   197      multiplicity 1) *)
   198   fun poly (Const (@{const_name Groups.plus}, _) $ s $ t,
   199         m : Rat.rat, pi : (term * Rat.rat) list * Rat.rat) = poly (s, m, poly (t, m, pi))
   200     | poly (all as Const (@{const_name Groups.minus}, T) $ s $ t, m, pi) =
   201         if nT T then add_atom all m pi else poly (s, m, poly (t, Rat.neg m, pi))
   202     | poly (all as Const (@{const_name Groups.uminus}, T) $ t, m, pi) =
   203         if nT T then add_atom all m pi else poly (t, Rat.neg m, pi)
   204     | poly (Const (@{const_name Groups.zero}, _), _, pi) =
   205         pi
   206     | poly (Const (@{const_name Groups.one}, _), m, (p, i)) =
   207         (p, Rat.add i m)
   208     | poly (Const (@{const_name Suc}, _) $ t, m, (p, i)) =
   209         poly (t, m, (p, Rat.add i m))
   210     | poly (all as Const (@{const_name Groups.times}, _) $ _ $ _, m, pi as (p, i)) =
   211         (case demult inj_consts (all, m) of
   212            (NONE,   m') => (p, Rat.add i m')
   213          | (SOME u, m') => add_atom u m' pi)
   214     | poly (all as Const (@{const_name Rings.divide}, _) $ _ $ _, m, pi as (p, i)) =
   215         (case demult inj_consts (all, m) of
   216            (NONE,   m') => (p, Rat.add i m')
   217          | (SOME u, m') => add_atom u m' pi)
   218     | poly (all as Const ("Int.number_class.number_of", Type(_,[_,T])) $ t, m, pi as (p, i)) =
   219         (let val k = HOLogic.dest_numeral t
   220             val k2 = if k < 0 andalso T = HOLogic.natT then 0 else k
   221         in (p, Rat.add i (Rat.mult m (Rat.rat_of_int k2))) end
   222         handle TERM _ => add_atom all m pi)
   223     | poly (all as Const f $ x, m, pi) =
   224         if member (op =) inj_consts f then poly (x, m, pi) else add_atom all m pi
   225     | poly (all, m, pi) =
   226         add_atom all m pi
   227   val (p, i) = poly (lhs, Rat.one, ([], Rat.zero))
   228   val (q, j) = poly (rhs, Rat.one, ([], Rat.zero))
   229 in
   230   case rel of
   231     @{const_name Orderings.less}    => SOME (p, i, "<", q, j)
   232   | @{const_name Orderings.less_eq} => SOME (p, i, "<=", q, j)
   233   | "op ="              => SOME (p, i, "=", q, j)
   234   | _                   => NONE
   235 end handle Rat.DIVZERO => NONE;
   236 
   237 fun of_lin_arith_sort thy U =
   238   Sign.of_sort thy (U, @{sort Rings.linordered_idom});
   239 
   240 fun allows_lin_arith thy (discrete : string list) (U as Type (D, [])) : bool * bool =
   241       if of_lin_arith_sort thy U then (true, member (op =) discrete D)
   242       else if member (op =) discrete D then (true, true) else (false, false)
   243   | allows_lin_arith sg discrete U = (of_lin_arith_sort sg U, false);
   244 
   245 fun decomp_typecheck (thy, discrete, inj_consts) (T : typ, xxx) : decomp option =
   246   case T of
   247     Type ("fun", [U, _]) =>
   248       (case allows_lin_arith thy discrete U of
   249         (true, d) =>
   250           (case decomp0 inj_consts xxx of
   251             NONE                   => NONE
   252           | SOME (p, i, rel, q, j) => SOME (p, i, rel, q, j, d))
   253       | (false, _) =>
   254           NONE)
   255   | _ => NONE;
   256 
   257 fun negate (SOME (x, i, rel, y, j, d)) = SOME (x, i, "~" ^ rel, y, j, d)
   258   | negate NONE                        = NONE;
   259 
   260 fun decomp_negation data
   261   ((Const ("Trueprop", _)) $ (Const (rel, T) $ lhs $ rhs)) : decomp option =
   262       decomp_typecheck data (T, (rel, lhs, rhs))
   263   | decomp_negation data ((Const ("Trueprop", _)) $
   264   (Const ("Not", _) $ (Const (rel, T) $ lhs $ rhs))) =
   265       negate (decomp_typecheck data (T, (rel, lhs, rhs)))
   266   | decomp_negation data _ =
   267       NONE;
   268 
   269 fun decomp ctxt : term -> decomp option =
   270   let
   271     val thy = ProofContext.theory_of ctxt
   272     val {discrete, inj_consts, ...} = get_arith_data ctxt
   273   in decomp_negation (thy, discrete, inj_consts) end;
   274 
   275 fun domain_is_nat (_ $ (Const (_, T) $ _ $ _))                      = nT T
   276   | domain_is_nat (_ $ (Const ("Not", _) $ (Const (_, T) $ _ $ _))) = nT T
   277   | domain_is_nat _                                                 = false;
   278 
   279 
   280 (*---------------------------------------------------------------------------*)
   281 (* the following code performs splitting of certain constants (e.g., min,    *)
   282 (* max) in a linear arithmetic problem; similar to what split_tac later does *)
   283 (* to the proof state                                                        *)
   284 (*---------------------------------------------------------------------------*)
   285 
   286 (* checks if splitting with 'thm' is implemented                             *)
   287 
   288 fun is_split_thm thm =
   289   case concl_of thm of _ $ (_ $ (_ $ lhs) $ _) => (
   290     (* Trueprop $ ((op =) $ (?P $ lhs) $ rhs) *)
   291     case head_of lhs of
   292       Const (a, _) => member (op =) [@{const_name Orderings.max},
   293                                     @{const_name Orderings.min},
   294                                     @{const_name Groups.abs},
   295                                     @{const_name Groups.minus},
   296                                     "Int.nat" (*DYNAMIC BINDING!*),
   297                                     "Divides.div_class.mod" (*DYNAMIC BINDING!*),
   298                                     "Divides.div_class.div" (*DYNAMIC BINDING!*)] a
   299     | _            => (warning ("Lin. Arith.: wrong format for split rule " ^
   300                                  Display.string_of_thm_without_context thm);
   301                        false))
   302   | _ => (warning ("Lin. Arith.: wrong format for split rule " ^
   303                    Display.string_of_thm_without_context thm);
   304           false);
   305 
   306 (* substitute new for occurrences of old in a term, incrementing bound       *)
   307 (* variables as needed when substituting inside an abstraction               *)
   308 
   309 fun subst_term ([] : (term * term) list) (t : term) = t
   310   | subst_term pairs                     t          =
   311       (case AList.lookup Pattern.aeconv pairs t of
   312         SOME new =>
   313           new
   314       | NONE     =>
   315           (case t of Abs (a, T, body) =>
   316             let val pairs' = map (pairself (incr_boundvars 1)) pairs
   317             in  Abs (a, T, subst_term pairs' body)  end
   318           | t1 $ t2                   =>
   319             subst_term pairs t1 $ subst_term pairs t2
   320           | _ => t));
   321 
   322 (* approximates the effect of one application of split_tac (followed by NNF  *)
   323 (* normalization) on the subgoal represented by '(Ts, terms)'; returns a     *)
   324 (* list of new subgoals (each again represented by a typ list for bound      *)
   325 (* variables and a term list for premises), or NONE if split_tac would fail  *)
   326 (* on the subgoal                                                            *)
   327 
   328 (* FIXME: currently only the effect of certain split theorems is reproduced  *)
   329 (*        (which is why we need 'is_split_thm').  A more canonical           *)
   330 (*        implementation should analyze the right-hand side of the split     *)
   331 (*        theorem that can be applied, and modify the subgoal accordingly.   *)
   332 (*        Or even better, the splitter should be extended to provide         *)
   333 (*        splitting on terms as well as splitting on theorems (where the     *)
   334 (*        former can have a faster implementation as it does not need to be  *)
   335 (*        proof-producing).                                                  *)
   336 
   337 fun split_once_items ctxt (Ts : typ list, terms : term list) :
   338                      (typ list * term list) list option =
   339 let
   340   val thy = ProofContext.theory_of ctxt
   341   (* takes a list  [t1, ..., tn]  to the term                                *)
   342   (*   tn' --> ... --> t1' --> False  ,                                      *)
   343   (* where ti' = HOLogic.dest_Trueprop ti                                    *)
   344   fun REPEAT_DETERM_etac_rev_mp tms =
   345     fold (curry HOLogic.mk_imp) (map HOLogic.dest_Trueprop tms)
   346       HOLogic.false_const
   347   val split_thms  = filter is_split_thm (#splits (get_arith_data ctxt))
   348   val cmap        = Splitter.cmap_of_split_thms split_thms
   349   val goal_tm     = REPEAT_DETERM_etac_rev_mp terms
   350   val splits      = Splitter.split_posns cmap thy Ts goal_tm
   351   val split_limit = Config.get ctxt split_limit
   352 in
   353   if length splits > split_limit then (
   354     tracing ("linarith_split_limit exceeded (current value is " ^
   355       string_of_int split_limit ^ ")");
   356     NONE
   357   ) else case splits of
   358     [] =>
   359     (* split_tac would fail: no possible split *)
   360     NONE
   361   | (_, _::_, _, _, _) :: _ =>
   362     (* disallow a split that involves non-locally bound variables (except    *)
   363     (* when bound by outermost meta-quantifiers)                             *)
   364     NONE
   365   | (_, [], _, split_type, split_term) :: _ =>
   366     (* ignore all but the first possible split                               *)
   367     (case strip_comb split_term of
   368     (* ?P (max ?i ?j) = ((?i <= ?j --> ?P ?j) & (~ ?i <= ?j --> ?P ?i)) *)
   369       (Const (@{const_name Orderings.max}, _), [t1, t2]) =>
   370       let
   371         val rev_terms     = rev terms
   372         val terms1        = map (subst_term [(split_term, t1)]) rev_terms
   373         val terms2        = map (subst_term [(split_term, t2)]) rev_terms
   374         val t1_leq_t2     = Const (@{const_name Orderings.less_eq},
   375                                     split_type --> split_type --> HOLogic.boolT) $ t1 $ t2
   376         val not_t1_leq_t2 = HOLogic.Not $ t1_leq_t2
   377         val not_false     = HOLogic.mk_Trueprop (HOLogic.Not $ HOLogic.false_const)
   378         val subgoal1      = (HOLogic.mk_Trueprop t1_leq_t2) :: terms2 @ [not_false]
   379         val subgoal2      = (HOLogic.mk_Trueprop not_t1_leq_t2) :: terms1 @ [not_false]
   380       in
   381         SOME [(Ts, subgoal1), (Ts, subgoal2)]
   382       end
   383     (* ?P (min ?i ?j) = ((?i <= ?j --> ?P ?i) & (~ ?i <= ?j --> ?P ?j)) *)
   384     | (Const (@{const_name Orderings.min}, _), [t1, t2]) =>
   385       let
   386         val rev_terms     = rev terms
   387         val terms1        = map (subst_term [(split_term, t1)]) rev_terms
   388         val terms2        = map (subst_term [(split_term, t2)]) rev_terms
   389         val t1_leq_t2     = Const (@{const_name Orderings.less_eq},
   390                                     split_type --> split_type --> HOLogic.boolT) $ t1 $ t2
   391         val not_t1_leq_t2 = HOLogic.Not $ t1_leq_t2
   392         val not_false     = HOLogic.mk_Trueprop (HOLogic.Not $ HOLogic.false_const)
   393         val subgoal1      = (HOLogic.mk_Trueprop t1_leq_t2) :: terms1 @ [not_false]
   394         val subgoal2      = (HOLogic.mk_Trueprop not_t1_leq_t2) :: terms2 @ [not_false]
   395       in
   396         SOME [(Ts, subgoal1), (Ts, subgoal2)]
   397       end
   398     (* ?P (abs ?a) = ((0 <= ?a --> ?P ?a) & (?a < 0 --> ?P (- ?a))) *)
   399     | (Const (@{const_name Groups.abs}, _), [t1]) =>
   400       let
   401         val rev_terms   = rev terms
   402         val terms1      = map (subst_term [(split_term, t1)]) rev_terms
   403         val terms2      = map (subst_term [(split_term, Const (@{const_name Groups.uminus},
   404                             split_type --> split_type) $ t1)]) rev_terms
   405         val zero        = Const (@{const_name Groups.zero}, split_type)
   406         val zero_leq_t1 = Const (@{const_name Orderings.less_eq},
   407                             split_type --> split_type --> HOLogic.boolT) $ zero $ t1
   408         val t1_lt_zero  = Const (@{const_name Orderings.less},
   409                             split_type --> split_type --> HOLogic.boolT) $ t1 $ zero
   410         val not_false   = HOLogic.mk_Trueprop (HOLogic.Not $ HOLogic.false_const)
   411         val subgoal1    = (HOLogic.mk_Trueprop zero_leq_t1) :: terms1 @ [not_false]
   412         val subgoal2    = (HOLogic.mk_Trueprop t1_lt_zero) :: terms2 @ [not_false]
   413       in
   414         SOME [(Ts, subgoal1), (Ts, subgoal2)]
   415       end
   416     (* ?P (?a - ?b) = ((?a < ?b --> ?P 0) & (ALL d. ?a = ?b + d --> ?P d)) *)
   417     | (Const (@{const_name Groups.minus}, _), [t1, t2]) =>
   418       let
   419         (* "d" in the above theorem becomes a new bound variable after NNF   *)
   420         (* transformation, therefore some adjustment of indices is necessary *)
   421         val rev_terms       = rev terms
   422         val zero            = Const (@{const_name Groups.zero}, split_type)
   423         val d               = Bound 0
   424         val terms1          = map (subst_term [(split_term, zero)]) rev_terms
   425         val terms2          = map (subst_term [(incr_boundvars 1 split_term, d)])
   426                                 (map (incr_boundvars 1) rev_terms)
   427         val t1'             = incr_boundvars 1 t1
   428         val t2'             = incr_boundvars 1 t2
   429         val t1_lt_t2        = Const (@{const_name Orderings.less},
   430                                 split_type --> split_type --> HOLogic.boolT) $ t1 $ t2
   431         val t1_eq_t2_plus_d = Const ("op =", split_type --> split_type --> HOLogic.boolT) $ t1' $
   432                                 (Const (@{const_name Groups.plus},
   433                                   split_type --> split_type --> split_type) $ t2' $ d)
   434         val not_false       = HOLogic.mk_Trueprop (HOLogic.Not $ HOLogic.false_const)
   435         val subgoal1        = (HOLogic.mk_Trueprop t1_lt_t2) :: terms1 @ [not_false]
   436         val subgoal2        = (HOLogic.mk_Trueprop t1_eq_t2_plus_d) :: terms2 @ [not_false]
   437       in
   438         SOME [(Ts, subgoal1), (split_type :: Ts, subgoal2)]
   439       end
   440     (* ?P (nat ?i) = ((ALL n. ?i = of_nat n --> ?P n) & (?i < 0 --> ?P 0)) *)
   441     | (Const ("Int.nat", _), [t1]) =>
   442       let
   443         val rev_terms   = rev terms
   444         val zero_int    = Const (@{const_name Groups.zero}, HOLogic.intT)
   445         val zero_nat    = Const (@{const_name Groups.zero}, HOLogic.natT)
   446         val n           = Bound 0
   447         val terms1      = map (subst_term [(incr_boundvars 1 split_term, n)])
   448                             (map (incr_boundvars 1) rev_terms)
   449         val terms2      = map (subst_term [(split_term, zero_nat)]) rev_terms
   450         val t1'         = incr_boundvars 1 t1
   451         val t1_eq_nat_n = Const ("op =", HOLogic.intT --> HOLogic.intT --> HOLogic.boolT) $ t1' $
   452                             (Const (@{const_name of_nat}, HOLogic.natT --> HOLogic.intT) $ n)
   453         val t1_lt_zero  = Const (@{const_name Orderings.less},
   454                             HOLogic.intT --> HOLogic.intT --> HOLogic.boolT) $ t1 $ zero_int
   455         val not_false   = HOLogic.mk_Trueprop (HOLogic.Not $ HOLogic.false_const)
   456         val subgoal1    = (HOLogic.mk_Trueprop t1_eq_nat_n) :: terms1 @ [not_false]
   457         val subgoal2    = (HOLogic.mk_Trueprop t1_lt_zero) :: terms2 @ [not_false]
   458       in
   459         SOME [(HOLogic.natT :: Ts, subgoal1), (Ts, subgoal2)]
   460       end
   461     (* ?P ((?n::nat) mod (number_of ?k)) =
   462          ((number_of ?k = 0 --> ?P ?n) & (~ (number_of ?k = 0) -->
   463            (ALL i j. j < number_of ?k --> ?n = number_of ?k * i + j --> ?P j))) *)
   464     | (Const ("Divides.div_class.mod", Type ("fun", [Type ("nat", []), _])), [t1, t2]) =>
   465       let
   466         val rev_terms               = rev terms
   467         val zero                    = Const (@{const_name Groups.zero}, split_type)
   468         val i                       = Bound 1
   469         val j                       = Bound 0
   470         val terms1                  = map (subst_term [(split_term, t1)]) rev_terms
   471         val terms2                  = map (subst_term [(incr_boundvars 2 split_term, j)])
   472                                         (map (incr_boundvars 2) rev_terms)
   473         val t1'                     = incr_boundvars 2 t1
   474         val t2'                     = incr_boundvars 2 t2
   475         val t2_eq_zero              = Const ("op =",
   476                                         split_type --> split_type --> HOLogic.boolT) $ t2 $ zero
   477         val t2_neq_zero             = HOLogic.mk_not (Const ("op =",
   478                                         split_type --> split_type --> HOLogic.boolT) $ t2' $ zero)
   479         val j_lt_t2                 = Const (@{const_name Orderings.less},
   480                                         split_type --> split_type--> HOLogic.boolT) $ j $ t2'
   481         val t1_eq_t2_times_i_plus_j = Const ("op =", split_type --> split_type --> HOLogic.boolT) $ t1' $
   482                                        (Const (@{const_name Groups.plus}, split_type --> split_type --> split_type) $
   483                                          (Const (@{const_name Groups.times},
   484                                            split_type --> split_type --> split_type) $ t2' $ i) $ j)
   485         val not_false               = HOLogic.mk_Trueprop (HOLogic.Not $ HOLogic.false_const)
   486         val subgoal1                = (HOLogic.mk_Trueprop t2_eq_zero) :: terms1 @ [not_false]
   487         val subgoal2                = (map HOLogic.mk_Trueprop
   488                                         [t2_neq_zero, j_lt_t2, t1_eq_t2_times_i_plus_j])
   489                                           @ terms2 @ [not_false]
   490       in
   491         SOME [(Ts, subgoal1), (split_type :: split_type :: Ts, subgoal2)]
   492       end
   493     (* ?P ((?n::nat) div (number_of ?k)) =
   494          ((number_of ?k = 0 --> ?P 0) & (~ (number_of ?k = 0) -->
   495            (ALL i j. j < number_of ?k --> ?n = number_of ?k * i + j --> ?P i))) *)
   496     | (Const ("Divides.div_class.div", Type ("fun", [Type ("nat", []), _])), [t1, t2]) =>
   497       let
   498         val rev_terms               = rev terms
   499         val zero                    = Const (@{const_name Groups.zero}, split_type)
   500         val i                       = Bound 1
   501         val j                       = Bound 0
   502         val terms1                  = map (subst_term [(split_term, zero)]) rev_terms
   503         val terms2                  = map (subst_term [(incr_boundvars 2 split_term, i)])
   504                                         (map (incr_boundvars 2) rev_terms)
   505         val t1'                     = incr_boundvars 2 t1
   506         val t2'                     = incr_boundvars 2 t2
   507         val t2_eq_zero              = Const ("op =",
   508                                         split_type --> split_type --> HOLogic.boolT) $ t2 $ zero
   509         val t2_neq_zero             = HOLogic.mk_not (Const ("op =",
   510                                         split_type --> split_type --> HOLogic.boolT) $ t2' $ zero)
   511         val j_lt_t2                 = Const (@{const_name Orderings.less},
   512                                         split_type --> split_type--> HOLogic.boolT) $ j $ t2'
   513         val t1_eq_t2_times_i_plus_j = Const ("op =", split_type --> split_type --> HOLogic.boolT) $ t1' $
   514                                        (Const (@{const_name Groups.plus}, split_type --> split_type --> split_type) $
   515                                          (Const (@{const_name Groups.times},
   516                                            split_type --> split_type --> split_type) $ t2' $ i) $ j)
   517         val not_false               = HOLogic.mk_Trueprop (HOLogic.Not $ HOLogic.false_const)
   518         val subgoal1                = (HOLogic.mk_Trueprop t2_eq_zero) :: terms1 @ [not_false]
   519         val subgoal2                = (map HOLogic.mk_Trueprop
   520                                         [t2_neq_zero, j_lt_t2, t1_eq_t2_times_i_plus_j])
   521                                           @ terms2 @ [not_false]
   522       in
   523         SOME [(Ts, subgoal1), (split_type :: split_type :: Ts, subgoal2)]
   524       end
   525     (* ?P ((?n::int) mod (number_of ?k)) =
   526          ((number_of ?k = 0 --> ?P ?n) &
   527           (0 < number_of ?k -->
   528             (ALL i j.
   529               0 <= j & j < number_of ?k & ?n = number_of ?k * i + j --> ?P j)) &
   530           (number_of ?k < 0 -->
   531             (ALL i j.
   532               number_of ?k < j & j <= 0 & ?n = number_of ?k * i + j --> ?P j))) *)
   533     | (Const ("Divides.div_class.mod",
   534         Type ("fun", [Type ("Int.int", []), _])), [t1, t2]) =>
   535       let
   536         val rev_terms               = rev terms
   537         val zero                    = Const (@{const_name Groups.zero}, split_type)
   538         val i                       = Bound 1
   539         val j                       = Bound 0
   540         val terms1                  = map (subst_term [(split_term, t1)]) rev_terms
   541         val terms2_3                = map (subst_term [(incr_boundvars 2 split_term, j)])
   542                                         (map (incr_boundvars 2) rev_terms)
   543         val t1'                     = incr_boundvars 2 t1
   544         val t2'                     = incr_boundvars 2 t2
   545         val t2_eq_zero              = Const ("op =",
   546                                         split_type --> split_type --> HOLogic.boolT) $ t2 $ zero
   547         val zero_lt_t2              = Const (@{const_name Orderings.less},
   548                                         split_type --> split_type --> HOLogic.boolT) $ zero $ t2'
   549         val t2_lt_zero              = Const (@{const_name Orderings.less},
   550                                         split_type --> split_type --> HOLogic.boolT) $ t2' $ zero
   551         val zero_leq_j              = Const (@{const_name Orderings.less_eq},
   552                                         split_type --> split_type --> HOLogic.boolT) $ zero $ j
   553         val j_leq_zero              = Const (@{const_name Orderings.less_eq},
   554                                         split_type --> split_type --> HOLogic.boolT) $ j $ zero
   555         val j_lt_t2                 = Const (@{const_name Orderings.less},
   556                                         split_type --> split_type--> HOLogic.boolT) $ j $ t2'
   557         val t2_lt_j                 = Const (@{const_name Orderings.less},
   558                                         split_type --> split_type--> HOLogic.boolT) $ t2' $ j
   559         val t1_eq_t2_times_i_plus_j = Const ("op =", split_type --> split_type --> HOLogic.boolT) $ t1' $
   560                                        (Const (@{const_name Groups.plus}, split_type --> split_type --> split_type) $
   561                                          (Const (@{const_name Groups.times},
   562                                            split_type --> split_type --> split_type) $ t2' $ i) $ j)
   563         val not_false               = HOLogic.mk_Trueprop (HOLogic.Not $ HOLogic.false_const)
   564         val subgoal1                = (HOLogic.mk_Trueprop t2_eq_zero) :: terms1 @ [not_false]
   565         val subgoal2                = (map HOLogic.mk_Trueprop [zero_lt_t2, zero_leq_j])
   566                                         @ hd terms2_3
   567                                         :: (if tl terms2_3 = [] then [not_false] else [])
   568                                         @ (map HOLogic.mk_Trueprop [j_lt_t2, t1_eq_t2_times_i_plus_j])
   569                                         @ (if tl terms2_3 = [] then [] else tl terms2_3 @ [not_false])
   570         val subgoal3                = (map HOLogic.mk_Trueprop [t2_lt_zero, t2_lt_j])
   571                                         @ hd terms2_3
   572                                         :: (if tl terms2_3 = [] then [not_false] else [])
   573                                         @ (map HOLogic.mk_Trueprop [j_leq_zero, t1_eq_t2_times_i_plus_j])
   574                                         @ (if tl terms2_3 = [] then [] else tl terms2_3 @ [not_false])
   575         val Ts'                     = split_type :: split_type :: Ts
   576       in
   577         SOME [(Ts, subgoal1), (Ts', subgoal2), (Ts', subgoal3)]
   578       end
   579     (* ?P ((?n::int) div (number_of ?k)) =
   580          ((number_of ?k = 0 --> ?P 0) &
   581           (0 < number_of ?k -->
   582             (ALL i j.
   583               0 <= j & j < number_of ?k & ?n = number_of ?k * i + j --> ?P i)) &
   584           (number_of ?k < 0 -->
   585             (ALL i j.
   586               number_of ?k < j & j <= 0 & ?n = number_of ?k * i + j --> ?P i))) *)
   587     | (Const ("Divides.div_class.div",
   588         Type ("fun", [Type ("Int.int", []), _])), [t1, t2]) =>
   589       let
   590         val rev_terms               = rev terms
   591         val zero                    = Const (@{const_name Groups.zero}, split_type)
   592         val i                       = Bound 1
   593         val j                       = Bound 0
   594         val terms1                  = map (subst_term [(split_term, zero)]) rev_terms
   595         val terms2_3                = map (subst_term [(incr_boundvars 2 split_term, i)])
   596                                         (map (incr_boundvars 2) rev_terms)
   597         val t1'                     = incr_boundvars 2 t1
   598         val t2'                     = incr_boundvars 2 t2
   599         val t2_eq_zero              = Const ("op =",
   600                                         split_type --> split_type --> HOLogic.boolT) $ t2 $ zero
   601         val zero_lt_t2              = Const (@{const_name Orderings.less},
   602                                         split_type --> split_type --> HOLogic.boolT) $ zero $ t2'
   603         val t2_lt_zero              = Const (@{const_name Orderings.less},
   604                                         split_type --> split_type --> HOLogic.boolT) $ t2' $ zero
   605         val zero_leq_j              = Const (@{const_name Orderings.less_eq},
   606                                         split_type --> split_type --> HOLogic.boolT) $ zero $ j
   607         val j_leq_zero              = Const (@{const_name Orderings.less_eq},
   608                                         split_type --> split_type --> HOLogic.boolT) $ j $ zero
   609         val j_lt_t2                 = Const (@{const_name Orderings.less},
   610                                         split_type --> split_type--> HOLogic.boolT) $ j $ t2'
   611         val t2_lt_j                 = Const (@{const_name Orderings.less},
   612                                         split_type --> split_type--> HOLogic.boolT) $ t2' $ j
   613         val t1_eq_t2_times_i_plus_j = Const ("op =", split_type --> split_type --> HOLogic.boolT) $ t1' $
   614                                        (Const (@{const_name Groups.plus}, split_type --> split_type --> split_type) $
   615                                          (Const (@{const_name Groups.times},
   616                                            split_type --> split_type --> split_type) $ t2' $ i) $ j)
   617         val not_false               = HOLogic.mk_Trueprop (HOLogic.Not $ HOLogic.false_const)
   618         val subgoal1                = (HOLogic.mk_Trueprop t2_eq_zero) :: terms1 @ [not_false]
   619         val subgoal2                = (map HOLogic.mk_Trueprop [zero_lt_t2, zero_leq_j])
   620                                         @ hd terms2_3
   621                                         :: (if tl terms2_3 = [] then [not_false] else [])
   622                                         @ (map HOLogic.mk_Trueprop [j_lt_t2, t1_eq_t2_times_i_plus_j])
   623                                         @ (if tl terms2_3 = [] then [] else tl terms2_3 @ [not_false])
   624         val subgoal3                = (map HOLogic.mk_Trueprop [t2_lt_zero, t2_lt_j])
   625                                         @ hd terms2_3
   626                                         :: (if tl terms2_3 = [] then [not_false] else [])
   627                                         @ (map HOLogic.mk_Trueprop [j_leq_zero, t1_eq_t2_times_i_plus_j])
   628                                         @ (if tl terms2_3 = [] then [] else tl terms2_3 @ [not_false])
   629         val Ts'                     = split_type :: split_type :: Ts
   630       in
   631         SOME [(Ts, subgoal1), (Ts', subgoal2), (Ts', subgoal3)]
   632       end
   633     (* this will only happen if a split theorem can be applied for which no  *)
   634     (* code exists above -- in which case either the split theorem should be *)
   635     (* implemented above, or 'is_split_thm' should be modified to filter it  *)
   636     (* out                                                                   *)
   637     | (t, ts) => (
   638       warning ("Lin. Arith.: split rule for " ^ Syntax.string_of_term ctxt t ^
   639         " (with " ^ string_of_int (length ts) ^
   640         " argument(s)) not implemented; proof reconstruction is likely to fail");
   641       NONE
   642     ))
   643 end;  (* split_once_items *)
   644 
   645 (* remove terms that do not satisfy 'p'; change the order of the remaining   *)
   646 (* terms in the same way as filter_prems_tac does                            *)
   647 
   648 fun filter_prems_tac_items (p : term -> bool) (terms : term list) : term list =
   649 let
   650   fun filter_prems t (left, right) =
   651     if p t then (left, right @ [t]) else (left @ right, [])
   652   val (left, right) = fold filter_prems terms ([], [])
   653 in
   654   right @ left
   655 end;
   656 
   657 (* return true iff TRY (etac notE) THEN eq_assume_tac would succeed on a     *)
   658 (* subgoal that has 'terms' as premises                                      *)
   659 
   660 fun negated_term_occurs_positively (terms : term list) : bool =
   661   List.exists
   662     (fn (Trueprop $ (Const ("Not", _) $ t)) =>
   663       member Pattern.aeconv terms (Trueprop $ t)
   664       | _ => false)
   665     terms;
   666 
   667 fun pre_decomp ctxt (Ts : typ list, terms : term list) : (typ list * term list) list =
   668 let
   669   (* repeatedly split (including newly emerging subgoals) until no further   *)
   670   (* splitting is possible                                                   *)
   671   fun split_loop ([] : (typ list * term list) list) =
   672       ([] : (typ list * term list) list)
   673     | split_loop (subgoal::subgoals) =
   674       (case split_once_items ctxt subgoal of
   675         SOME new_subgoals => split_loop (new_subgoals @ subgoals)
   676       | NONE              => subgoal :: split_loop subgoals)
   677   fun is_relevant t  = is_some (decomp ctxt t)
   678   (* filter_prems_tac is_relevant: *)
   679   val relevant_terms = filter_prems_tac_items is_relevant terms
   680   (* split_tac, NNF normalization: *)
   681   val split_goals    = split_loop [(Ts, relevant_terms)]
   682   (* necessary because split_once_tac may normalize terms: *)
   683   val beta_eta_norm  = map (apsnd (map (Envir.eta_contract o Envir.beta_norm)))
   684     split_goals
   685   (* TRY (etac notE) THEN eq_assume_tac: *)
   686   val result         = filter_out (negated_term_occurs_positively o snd)
   687     beta_eta_norm
   688 in
   689   result
   690 end;
   691 
   692 (* takes the i-th subgoal  [| A1; ...; An |] ==> B  to                       *)
   693 (* An --> ... --> A1 --> B,  performs splitting with the given 'split_thms'  *)
   694 (* (resulting in a different subgoal P), takes  P  to  ~P ==> False,         *)
   695 (* performs NNF-normalization of ~P, and eliminates conjunctions,            *)
   696 (* disjunctions and existential quantifiers from the premises, possibly (in  *)
   697 (* the case of disjunctions) resulting in several new subgoals, each of the  *)
   698 (* general form  [| Q1; ...; Qm |] ==> False.  Fails if more than            *)
   699 (* !split_limit splits are possible.                              *)
   700 
   701 local
   702   val nnf_simpset =
   703     empty_ss setmkeqTrue mk_eq_True
   704     setmksimps (mksimps mksimps_pairs)
   705     addsimps [@{thm imp_conv_disj}, @{thm iff_conv_conj_imp}, @{thm de_Morgan_disj},
   706       @{thm de_Morgan_conj}, not_all, not_ex, not_not]
   707   fun prem_nnf_tac ss = full_simp_tac (Simplifier.inherit_context ss nnf_simpset)
   708 in
   709 
   710 fun split_once_tac ss split_thms =
   711   let
   712     val ctxt = Simplifier.the_context ss
   713     val thy = ProofContext.theory_of ctxt
   714     val cond_split_tac = SUBGOAL (fn (subgoal, i) =>
   715       let
   716         val Ts = rev (map snd (Logic.strip_params subgoal))
   717         val concl = HOLogic.dest_Trueprop (Logic.strip_assums_concl subgoal)
   718         val cmap = Splitter.cmap_of_split_thms split_thms
   719         val splits = Splitter.split_posns cmap thy Ts concl
   720       in
   721         if null splits orelse length splits > Config.get ctxt split_limit then
   722           no_tac
   723         else if null (#2 (hd splits)) then
   724           split_tac split_thms i
   725         else
   726           (* disallow a split that involves non-locally bound variables      *)
   727           (* (except when bound by outermost meta-quantifiers)               *)
   728           no_tac
   729       end)
   730   in
   731     EVERY' [
   732       REPEAT_DETERM o etac rev_mp,
   733       cond_split_tac,
   734       rtac ccontr,
   735       prem_nnf_tac ss,
   736       TRY o REPEAT_ALL_NEW (DETERM o (eresolve_tac [conjE, exE] ORELSE' etac disjE))
   737     ]
   738   end;
   739 
   740 end;  (* local *)
   741 
   742 (* remove irrelevant premises, then split the i-th subgoal (and all new      *)
   743 (* subgoals) by using 'split_once_tac' repeatedly.  Beta-eta-normalize new   *)
   744 (* subgoals and finally attempt to solve them by finding an immediate        *)
   745 (* contradiction (i.e., a term and its negation) in their premises.          *)
   746 
   747 fun pre_tac ss i =
   748 let
   749   val ctxt = Simplifier.the_context ss;
   750   val split_thms = filter is_split_thm (#splits (get_arith_data ctxt))
   751   fun is_relevant t = is_some (decomp ctxt t)
   752 in
   753   DETERM (
   754     TRY (filter_prems_tac is_relevant i)
   755       THEN (
   756         (TRY o REPEAT_ALL_NEW (split_once_tac ss split_thms))
   757           THEN_ALL_NEW
   758             (CONVERSION Drule.beta_eta_conversion
   759               THEN'
   760             (TRY o (etac notE THEN' eq_assume_tac)))
   761       ) i
   762   )
   763 end;
   764 
   765 end;  (* LA_Data *)
   766 
   767 
   768 val pre_tac = LA_Data.pre_tac;
   769 
   770 structure Fast_Arith = Fast_Lin_Arith(structure LA_Logic = LA_Logic and LA_Data = LA_Data);
   771 
   772 fun map_inj_thms f {add_mono_thms, mult_mono_thms, inj_thms, lessD, neqE, simpset, number_of} =
   773   {add_mono_thms = add_mono_thms, mult_mono_thms = mult_mono_thms, inj_thms = f inj_thms,
   774     lessD = lessD, neqE = neqE, simpset = simpset, number_of = number_of};
   775 
   776 fun map_lessD f {add_mono_thms, mult_mono_thms, inj_thms, lessD, neqE, simpset, number_of} =
   777   {add_mono_thms = add_mono_thms, mult_mono_thms = mult_mono_thms, inj_thms = inj_thms,
   778     lessD = f lessD, neqE = neqE, simpset = simpset, number_of = number_of};
   779 
   780 fun map_simpset f {add_mono_thms, mult_mono_thms, inj_thms, lessD, neqE, simpset, number_of} =
   781   {add_mono_thms = add_mono_thms, mult_mono_thms = mult_mono_thms, inj_thms = inj_thms,
   782     lessD = lessD, neqE = neqE, simpset = f simpset, number_of = number_of};
   783 
   784 fun map_number_of f {add_mono_thms, mult_mono_thms, inj_thms, lessD, neqE, simpset, number_of} =
   785   {add_mono_thms = add_mono_thms, mult_mono_thms = mult_mono_thms, inj_thms = inj_thms,
   786     lessD = lessD, neqE = neqE, simpset = simpset, number_of = f number_of};
   787 
   788 fun add_inj_thms thms = Fast_Arith.map_data (map_inj_thms (append thms));
   789 fun add_lessD thm = Fast_Arith.map_data (map_lessD (fn thms => thms @ [thm]));
   790 fun add_simps thms = Fast_Arith.map_data (map_simpset (fn simpset => simpset addsimps thms));
   791 fun add_simprocs procs = Fast_Arith.map_data (map_simpset (fn simpset => simpset addsimprocs procs));
   792 
   793 fun set_number_of f = Fast_Arith.map_data (map_number_of (K (serial (), f)))
   794 
   795 
   796 fun simple_tac ctxt = Fast_Arith.lin_arith_tac ctxt false;
   797 val lin_arith_tac = Fast_Arith.lin_arith_tac;
   798 val trace = Fast_Arith.trace;
   799 
   800 (* reduce contradictory <= to False.
   801    Most of the work is done by the cancel tactics. *)
   802 
   803 val init_arith_data =
   804   Fast_Arith.map_data (fn {add_mono_thms, mult_mono_thms, inj_thms, lessD, number_of, ...} =>
   805    {add_mono_thms = @{thms add_mono_thms_linordered_semiring} @ @{thms add_mono_thms_linordered_field} @ add_mono_thms,
   806     mult_mono_thms = @{thm mult_strict_left_mono} :: @{thm mult_left_mono} ::
   807       @{lemma "a = b ==> c*a = c*b" by (rule arg_cong)} :: mult_mono_thms,
   808     inj_thms = inj_thms,
   809     lessD = lessD @ [@{thm "Suc_leI"}],
   810     neqE = [@{thm linorder_neqE_nat}, @{thm linorder_neqE_linordered_idom}],
   811     simpset = HOL_basic_ss
   812       addsimps @{thms ring_distribs}
   813       addsimps [@{thm if_True}, @{thm if_False}]
   814       addsimps
   815        [@{thm add_0_left},
   816         @{thm add_0_right},
   817         @{thm "Zero_not_Suc"}, @{thm "Suc_not_Zero"}, @{thm "le_0_eq"}, @{thm "One_nat_def"},
   818         @{thm "order_less_irrefl"}, @{thm "zero_neq_one"}, @{thm "zero_less_one"},
   819         @{thm "zero_le_one"}, @{thm "zero_neq_one"} RS not_sym, @{thm "not_one_le_zero"},
   820         @{thm "not_one_less_zero"}]
   821       addsimprocs [ab_group_add_cancel.sum_conv, ab_group_add_cancel.rel_conv]
   822        (*abel_cancel helps it work in abstract algebraic domains*)
   823       addsimprocs Nat_Arith.nat_cancel_sums_add
   824       addcongs [@{thm if_weak_cong}],
   825     number_of = number_of}) #>
   826   add_discrete_type @{type_name nat};
   827 
   828 fun add_arith_facts ss =
   829   add_prems (Arith_Data.get_arith_facts (MetaSimplifier.the_context ss)) ss;
   830 
   831 val simproc = add_arith_facts #> Fast_Arith.lin_arith_simproc;
   832 
   833 
   834 (* generic refutation procedure *)
   835 
   836 (* parameters:
   837 
   838    test: term -> bool
   839    tests if a term is at all relevant to the refutation proof;
   840    if not, then it can be discarded. Can improve performance,
   841    esp. if disjunctions can be discarded (no case distinction needed!).
   842 
   843    prep_tac: int -> tactic
   844    A preparation tactic to be applied to the goal once all relevant premises
   845    have been moved to the conclusion.
   846 
   847    ref_tac: int -> tactic
   848    the actual refutation tactic. Should be able to deal with goals
   849    [| A1; ...; An |] ==> False
   850    where the Ai are atomic, i.e. no top-level &, | or EX
   851 *)
   852 
   853 local
   854   val nnf_simpset =
   855     empty_ss setmkeqTrue mk_eq_True
   856     setmksimps (mksimps mksimps_pairs)
   857     addsimps [@{thm imp_conv_disj}, @{thm iff_conv_conj_imp}, @{thm de_Morgan_disj},
   858       @{thm de_Morgan_conj}, @{thm not_all}, @{thm not_ex}, @{thm not_not}];
   859   fun prem_nnf_tac i st =
   860     full_simp_tac (Simplifier.global_context (Thm.theory_of_thm st) nnf_simpset) i st;
   861 in
   862 fun refute_tac test prep_tac ref_tac =
   863   let val refute_prems_tac =
   864         REPEAT_DETERM
   865               (eresolve_tac [@{thm conjE}, @{thm exE}] 1 ORELSE
   866                filter_prems_tac test 1 ORELSE
   867                etac @{thm disjE} 1) THEN
   868         (DETERM (etac @{thm notE} 1 THEN eq_assume_tac 1) ORELSE
   869          ref_tac 1);
   870   in EVERY'[TRY o filter_prems_tac test,
   871             REPEAT_DETERM o etac @{thm rev_mp}, prep_tac, rtac @{thm ccontr}, prem_nnf_tac,
   872             SELECT_GOAL (DEPTH_SOLVE refute_prems_tac)]
   873   end;
   874 end;
   875 
   876 
   877 (* arith proof method *)
   878 
   879 local
   880 
   881 fun raw_tac ctxt ex =
   882   (* FIXME: K true should be replaced by a sensible test (perhaps "is_some o
   883      decomp sg"? -- but note that the test is applied to terms already before
   884      they are split/normalized) to speed things up in case there are lots of
   885      irrelevant terms involved; elimination of min/max can be optimized:
   886      (max m n + k <= r) = (m+k <= r & n+k <= r)
   887      (l <= min m n + k) = (l <= m+k & l <= n+k)
   888   *)
   889   refute_tac (K true)
   890     (* Splitting is also done inside simple_tac, but not completely --    *)
   891     (* split_tac may use split theorems that have not been implemented in *)
   892     (* simple_tac (cf. pre_decomp and split_once_items above), and        *)
   893     (* split_limit may trigger.                                           *)
   894     (* Therefore splitting outside of simple_tac may allow us to prove    *)
   895     (* some goals that simple_tac alone would fail on.                    *)
   896     (REPEAT_DETERM o split_tac (#splits (get_arith_data ctxt)))
   897     (lin_arith_tac ctxt ex);
   898 
   899 in
   900 
   901 fun gen_tac ex ctxt = FIRST' [simple_tac ctxt,
   902   Object_Logic.full_atomize_tac THEN' (REPEAT_DETERM o rtac impI) THEN' raw_tac ctxt ex];
   903 
   904 val tac = gen_tac true;
   905 
   906 end;
   907 
   908 
   909 (* context setup *)
   910 
   911 val setup =
   912   init_arith_data #>
   913   Simplifier.map_ss (fn ss => ss addsimprocs [Simplifier.simproc (@{theory}) "fast_nat_arith"
   914     ["(m::nat) < n","(m::nat) <= n", "(m::nat) = n"] (K simproc)]
   915     (* Because of fast_nat_arith_simproc, the arithmetic solver is really only
   916     useful to detect inconsistencies among the premises for subgoals which are
   917     *not* themselves (in)equalities, because the latter activate
   918     fast_nat_arith_simproc anyway. However, it seems cheaper to activate the
   919     solver all the time rather than add the additional check. *)
   920     addSolver (mk_solver' "lin_arith"
   921       (add_arith_facts #> Fast_Arith.cut_lin_arith_tac)))
   922 
   923 val global_setup =
   924   setup_split_limit #> setup_neq_limit #>
   925   Attrib.setup @{binding arith_split} (Scan.succeed (Thm.declaration_attribute add_split))
   926     "declaration of split rules for arithmetic procedure" #>
   927   Method.setup @{binding linarith}
   928     (Scan.succeed (fn ctxt =>
   929       METHOD (fn facts =>
   930         HEADGOAL (Method.insert_tac (Arith_Data.get_arith_facts ctxt @ facts)
   931           THEN' tac ctxt)))) "linear arithmetic" #>
   932   Arith_Data.add_tactic "linear arithmetic" gen_tac;
   933 
   934 end;