Rollup merge of #77251 - dtolnay:drop, r=Aaron1011
Bypass const_item_mutation if const's type has Drop impl Follow-up to #75573. This PR disables the const_item_mutation lint in cases that the const has a Drop impl which observes the mutation. ```rust struct Log { msg: &'static str } const LOG: Log = Log { msg: "" }; impl Drop for Log { fn drop(&mut self) { println!("{}", self.msg); } } LOG.msg = "wow"; // prints "wow" ``` r? @Aaron1011
This commit is contained in:
commit
6522868664
3 changed files with 102 additions and 14 deletions
|
@ -31,6 +31,35 @@ impl<'a, 'tcx> ConstMutationChecker<'a, 'tcx> {
|
|||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn is_const_item_without_destructor(&self, local: Local) -> Option<DefId> {
|
||||
let def_id = self.is_const_item(local)?;
|
||||
let mut any_dtor = |_tcx, _def_id| Ok(());
|
||||
|
||||
// We avoid linting mutation of a const item if the const's type has a
|
||||
// Drop impl. The Drop logic observes the mutation which was performed.
|
||||
//
|
||||
// pub struct Log { msg: &'static str }
|
||||
// pub const LOG: Log = Log { msg: "" };
|
||||
// impl Drop for Log {
|
||||
// fn drop(&mut self) { println!("{}", self.msg); }
|
||||
// }
|
||||
//
|
||||
// LOG.msg = "wow"; // prints "wow"
|
||||
//
|
||||
// FIXME(https://github.com/rust-lang/rust/issues/77425):
|
||||
// Drop this exception once there is a stable attribute to suppress the
|
||||
// const item mutation lint for a single specific const only. Something
|
||||
// equivalent to:
|
||||
//
|
||||
// #[const_mutation_allowed]
|
||||
// pub const LOG: Log = Log { msg: "" };
|
||||
match self.tcx.calculate_dtor(def_id, &mut any_dtor) {
|
||||
Some(_) => None,
|
||||
None => Some(def_id),
|
||||
}
|
||||
}
|
||||
|
||||
fn lint_const_item_usage(
|
||||
&self,
|
||||
const_item: DefId,
|
||||
|
@ -59,7 +88,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ConstMutationChecker<'a, 'tcx> {
|
|||
// Assigning directly to a constant (e.g. `FOO = true;`) is a hard error,
|
||||
// so emitting a lint would be redundant.
|
||||
if !lhs.projection.is_empty() {
|
||||
if let Some(def_id) = self.is_const_item(lhs.local) {
|
||||
if let Some(def_id) = self.is_const_item_without_destructor(lhs.local) {
|
||||
// Don't lint on writes through a pointer
|
||||
// (e.g. `unsafe { *FOO = 0; *BAR.field = 1; }`)
|
||||
if !matches!(lhs.projection.last(), Some(PlaceElem::Deref)) {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue