[gccrs COMMIT] gccrs: Fix duplicate unused assignment removals

[email protected] Sun, 2 Aug 2026 03:47:25 +0000
Newsgroups gmane.comp.gcc.rust,gmane.comp.gcc.patches
Message-ID <[email protected]>
From: Aiman Najjar <[email protected]>

Fixes Rust-GCC/gccrs#4674

gcc/rust/ChangeLog:

	* checks/lints/unused/rust-unused-context.cc
	(UnusedContext::remove_assign): Fix issue with duplicate
	removal of unused-assignment for the same id.

gcc/testsuite/ChangeLog:

	* rust/compile/issue-4674.rs: New test.

Signed-off-by: Aiman Najjar <[email protected]>
---
This change was merged into the gccrs repository and is posted here for
upstream visibility and potential drive-by review, as requested by GCC
release managers.
Each commit email contains a link to its details on github from where you can
find the Pull-Request and associated discussions.


Commit on github: https://github.com/Rust-GCC/gccrs/commit/481e776ea58e78dd2a76aab9b9e307571dabe7d5

The commit has been mentioned in the following issue(s):
 - Rust-GCC/gccrs#4674: https://github.com/Rust-GCC/gccrs/issues/4674

The commit has been mentioned in the following pull-request(s):
 - https://github.com/Rust-GCC/gccrs/pull/4744

 .../checks/lints/unused/rust-unused-context.cc    |  7 ++++++-
 gcc/testsuite/rust/compile/issue-4674.rs          | 15 +++++++++++++++
 2 files changed, 21 insertions(+), 1 deletion(-)
 create mode 100644 gcc/testsuite/rust/compile/issue-4674.rs

diff --git a/gcc/rust/checks/lints/unused/rust-unused-context.cc b/gcc/rust/checks/lints/unused/rust-unused-context.cc
index 9b26e01bc..8a68a601a 100644
--- a/gcc/rust/checks/lints/unused/rust-unused-context.cc
+++ b/gcc/rust/checks/lints/unused/rust-unused-context.cc
@@ -44,7 +44,12 @@ void
 UnusedContext::remove_assign (HirId id_def)
 {
   if (assigned_vars.find (id_def) != assigned_vars.end ())
-    assigned_vars[id_def].pop_back ();
+    {
+      assigned_vars[id_def].pop_back ();
+
+      if (assigned_vars[id_def].empty ())
+	assigned_vars.erase (id_def);
+    }
 }
 
 bool
diff --git a/gcc/testsuite/rust/compile/issue-4674.rs b/gcc/testsuite/rust/compile/issue-4674.rs
new file mode 100644
index 000000000..f787c5c4b
--- /dev/null
+++ b/gcc/testsuite/rust/compile/issue-4674.rs
@@ -0,0 +1,15 @@
+// { dg-additional-options "-frust-unused-check-2.0" }
+#![feature(no_core)]
+#![no_core]
+
+fn foo(mut n: i32) {
+    // { dg-warning "function is never used: .foo." "" { target *-*-* } .-1 }
+    if false {
+        n = 0i32;
+    }
+
+    if n > 0i32 {
+        let _ = 1i32 / n;
+    }
+}
+

base-commit: ab5ba74bab35eecfc3eb0893354cdeec22280821
-- 
2.54.0