| 1 |
From Coq Require Import ZArith Lia. |
| 2 |
Require Import Crypto.Util.ZUtil.Hints.Core. |
| 3 |
Require Import Crypto.Util.ZUtil.Hints.ZArith. |
| 4 |
Require Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem. |
| 5 |
Local Open Scope Z_scope. |
| 6 |
|
| 7 |
Module Z. |
| 8 |
Lemma mod_mod_small a n m |
| 9 |
(Hnm : (m mod n = 0)%Z) |
| 10 |
(Hnm_le : (0 < n <= m)%Z) |
| 11 |
(H : (a mod m < n)%Z) |
| 12 |
: ((a mod n) mod m = a mod m)%Z. |
| 13 |
Proof. |
| 14 |
assert ((a mod n) < m)%Z |
| 15 |
by (eapply Z.lt_le_trans; [ apply Z.mod_pos_bound | ]; lia). |
| 16 |
rewrite (Z.mod_small _ m) by auto with zarith. |
| 17 |
apply Z.mod_divide in Hnm; [ | lia ]. |
| 18 |
destruct Hnm as [x ?]; subst. |
| 19 |
repeat match goal with |
| 20 |
| [ H : context[(_ mod _)%Z] |- _ ] |
| 21 |
=> revert H |
| 22 |
end. |
| 23 |
Z.div_mod_to_quot_rem_in_goal. |
| 24 |
lazymatch goal with |
| 25 |
| [ H : a = (?x * ?n * ?q) + _, H' : a = (?n * ?q') + _ |- _ ] |
| 26 |
=> assert (q' = x * q) by nia; subst q'; nia |
| 27 |
end. |
| 28 |
Qed. |
| 29 |
|
| 30 |
(** [rewrite_mod_small] is a better version of [rewrite Z.mod_small |
| 31 |
by rewrite_mod_small_solver]; it backtracks across occurences |
| 32 |
that the solver fails to solve the side-conditions on. *) |
| 33 |
Ltac rewrite_mod_small_solver := |
| 34 |
zutil_arith_more_inequalities. |
| 35 |
Ltac rewrite_mod_small := |
| 36 |
repeat match goal with |
| 37 |
| [ |- context[?x mod ?y] ] |
| 38 |
=> rewrite (Z.mod_small x y) by rewrite_mod_small_solver |
| 39 |
end. |
| 40 |
Ltac rewrite_mod_mod_small := |
| 41 |
repeat match goal with |
| 42 |
| [ |- context[(?a mod ?n) mod ?m] ] |
| 43 |
=> rewrite (mod_mod_small a n m) by rewrite_mod_small_solver |
| 44 |
end. |
| 45 |
Ltac rewrite_mod_small_more := |
| 46 |
repeat (rewrite_mod_small || rewrite_mod_mod_small). |
| 47 |
Ltac rewrite_mod_small_in_hyps := |
| 48 |
repeat match goal with |
| 49 |
| [ H : context[?x mod ?y] |- _ ] |
| 50 |
=> rewrite (Z.mod_small x y) in H by rewrite_mod_small_solver |
| 51 |
end. |
| 52 |
Ltac rewrite_mod_mod_small_in_hyps := |
| 53 |
repeat match goal with |
| 54 |
| [ H : context[(?a mod ?n) mod ?m] |- _ ] |
| 55 |
=> rewrite (mod_mod_small a n m) in H by rewrite_mod_small_solver |
| 56 |
end. |
| 57 |
Ltac rewrite_mod_small_more_in_hyps := |
| 58 |
repeat (rewrite_mod_small_in_hyps || rewrite_mod_mod_small_in_hyps). |
| 59 |
Ltac rewrite_mod_small_in_all := repeat (rewrite_mod_small || rewrite_mod_small_in_hyps). |
| 60 |
Ltac rewrite_mod_mod_small_in_all := repeat (rewrite_mod_mod_small || rewrite_mod_mod_small_in_hyps). |
| 61 |
Ltac rewrite_mod_small_more_in_all := repeat (rewrite_mod_small_more || rewrite_mod_small_more_in_hyps). |
| 62 |
End Z. |