Skip to content

Commit 1fa67d0

Browse files
authored
fix: overeager Nat.sub constant folding (#11043)
This PR fixes a case of overeager constant folding on Nat where the compiler would mistakenly assume `0 - x = x` (see also #11042 for the same bug on UInts).
1 parent 51ef1dc commit 1fa67d0

File tree

3 files changed

+27
-16
lines changed

3 files changed

+27
-16
lines changed

src/Lean/Compiler/LCNF/Simp/ConstantFold.lean

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,7 @@ def arithmeticFolders : List (Name × Folder) := [
355355
(``UInt16.add, Folder.first #[Folder.mkBinary UInt16.add, Folder.leftRightNeutral (0 : UInt16)]),
356356
(``UInt32.add, Folder.first #[Folder.mkBinary UInt32.add, Folder.leftRightNeutral (0 : UInt32)]),
357357
(``UInt64.add, Folder.first #[Folder.mkBinary UInt64.add, Folder.leftRightNeutral (0 : UInt64)]),
358-
(``Nat.sub, Folder.first #[Folder.mkBinary Nat.sub, Folder.leftRightNeutral 0]),
358+
(``Nat.sub, Folder.first #[Folder.mkBinary Nat.sub, Folder.leftAnnihilator 0 0, Folder.rightNeutral 0]),
359359
(``UInt8.sub, Folder.first #[Folder.mkBinary UInt8.sub, Folder.rightNeutral (0 : UInt8)]),
360360
(``UInt16.sub, Folder.first #[Folder.mkBinary UInt16.sub, Folder.rightNeutral (0 : UInt16)]),
361361
(``UInt32.sub, Folder.first #[Folder.mkBinary UInt32.sub, Folder.rightNeutral (0 : UInt32)]),
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/-!
2+
This test guards against a constant folding bug
3+
-/
4+
5+
6+
def danger : UInt64 := UInt64.ofNat UInt64.size - 1
7+
theorem danger_eq_large : danger = 18446744073709551615 := by decide +kernel
8+
/--
9+
error: Tactic `native_decide` evaluated that the proposition
10+
danger = 1
11+
is false
12+
-/
13+
#guard_msgs in
14+
theorem danger_eq_one : danger = 1 := by native_decide
15+
theorem bad : False := by simpa using danger_eq_large.symm.trans danger_eq_one
16+
17+
def danger2 (x : Nat) : Nat := 0 - x
18+
theorem danger2_eq_zero : danger2 1 = 0 := by decide +kernel
19+
/--
20+
error: Tactic `native_decide` evaluated that the proposition
21+
danger2 1 = 1
22+
is false
23+
-/
24+
#guard_msgs in
25+
theorem danger2_eq_one : danger2 1 = 1 := by native_decide
26+
theorem bad2 : False := by simpa using danger2_eq_zero.symm.trans danger2_eq_one

tests/lean/run/uint_bug_neutral.lean

Lines changed: 0 additions & 15 deletions
This file was deleted.

0 commit comments

Comments
 (0)