Skip to content

Commit 75c2fdf

Browse files
committed
Warn on method call mutating const, even if it has destructor
1 parent eef5104 commit 75c2fdf

File tree

3 files changed

+28
-3
lines changed

3 files changed

+28
-3
lines changed

compiler/rustc_mir/src/transform/check_const_item_mutation.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ConstMutationChecker<'a, 'tcx> {
111111
fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, loc: Location) {
112112
if let Rvalue::Ref(_, BorrowKind::Mut { .. }, place) = rvalue {
113113
let local = place.local;
114-
if let Some(def_id) = self.is_const_item_without_destructor(local) {
114+
if let Some(def_id) = self.is_const_item(local) {
115115
// If this Rvalue is being used as the right-hand side of a
116116
// `StatementKind::Assign`, see if it ends up getting used as
117117
// the `self` parameter of a method call (as the terminator of our current

src/test/ui/lint/lint-const-item-mutation.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,5 +49,5 @@ fn main() {
4949

5050
MUTABLE.msg = "wow"; // no warning, because Drop observes the mutation
5151
MUTABLE2.msg = "wow"; //~ WARN attempting to modify
52-
VEC.push(0); // no warning
52+
VEC.push(0); //~ WARN taking a mutable reference to a `const` item
5353
}

src/test/ui/lint/lint-const-item-mutation.stderr

+26-1
Original file line numberDiff line numberDiff line change
@@ -98,5 +98,30 @@ note: `const` item defined here
9898
LL | const MUTABLE2: Mutable2 = Mutable2 { msg: "", other: String::new() };
9999
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
100100

101-
warning: 7 warnings emitted
101+
warning: taking a mutable reference to a `const` item
102+
--> $DIR/lint-const-item-mutation.rs:52:5
103+
|
104+
LL | VEC.push(0);
105+
| ^^^^^^^^^^^
106+
|
107+
= note: each usage of a `const` item creates a new temporary
108+
= note: the mutable reference will refer to this temporary, not the original `const` item
109+
note: mutable reference created due to call to this method
110+
--> $SRC_DIR/alloc/src/vec.rs:LL:COL
111+
|
112+
LL | / pub fn push(&mut self, value: T) {
113+
LL | | // This will panic or abort if we would allocate > isize::MAX bytes
114+
LL | | // or if the length increment would overflow for zero-sized types.
115+
LL | | if self.len == self.buf.capacity() {
116+
... |
117+
LL | | }
118+
LL | | }
119+
| |_____^
120+
note: `const` item defined here
121+
--> $DIR/lint-const-item-mutation.rs:31:1
122+
|
123+
LL | const VEC: Vec<i32> = Vec::new();
124+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
125+
126+
warning: 8 warnings emitted
102127

0 commit comments

Comments
 (0)