Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions compiler/rustc_lint/src/interior_mutable_consts.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use rustc_hir::attrs::AttributeKind;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::{Expr, ExprKind, ItemKind, Node, find_attr};
use rustc_middle::ty::adjustment::Adjust;
use rustc_session::{declare_lint, declare_lint_pass};

use crate::lints::{ConstItemInteriorMutationsDiag, ConstItemInteriorMutationsSuggestionStatic};
Expand Down Expand Up @@ -77,6 +78,13 @@ impl<'tcx> LateLintPass<'tcx> for InteriorMutableConsts {
if let ExprKind::Path(qpath) = &receiver.kind
&& let Res::Def(DefKind::Const | DefKind::AssocConst, const_did) =
typeck.qpath_res(qpath, receiver.hir_id)
// Don't consider derefs as those can do arbitrary things
// like using thread local (see rust-lang/rust#150157)
&& !cx
.typeck_results()
.expr_adjustments(receiver)
.into_iter()
.any(|adj| matches!(adj.kind, Adjust::Deref(_)))
// Let's do the attribute check after the other checks for perf reasons
&& find_attr!(
cx.tcx.get_all_attrs(method_did),
Expand Down
28 changes: 28 additions & 0 deletions tests/ui/lint/const-item-interior-mutations-const-deref.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Regression test for <https://github.com/rust-lang/rust/issues/150157>
//
// We shouldn't lint on user types, including through deref.

//@ check-pass

use std::cell::Cell;
use std::ops::Deref;

// Cut down version of the issue reproducer without the thread local to just a Deref
pub struct LocalKey<T> {
inner: T,
}

impl<T> Deref for LocalKey<T> {
type Target = T;

fn deref(&self) -> &Self::Target {
&self.inner
}
}

const LOCAL_COUNT: LocalKey<Cell<usize>> = LocalKey { inner: Cell::new(8) };

fn main() {
let count = LOCAL_COUNT.get();
LOCAL_COUNT.set(count);
}
Loading