1 use rustc_errors::DiagnosticBuilder;
2 use rustc_middle::lint::LintDiagnosticBuilder;
3 use rustc_middle::mir::visit::Visitor;
4 use rustc_middle::mir::*;
5 use rustc_middle::ty::TyCtxt;
6 use rustc_session::lint::builtin::CONST_ITEM_MUTATION;
7 use rustc_span::def_id::DefId;
11 pub struct CheckConstItemMutation;
13 impl<'tcx> MirLint<'tcx> for CheckConstItemMutation {
14 fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
15 let mut checker = ConstMutationChecker { body, tcx, target_local: None };
16 checker.visit_body(&body);
20 struct ConstMutationChecker<'a, 'tcx> {
23 target_local: Option<Local>,
26 impl<'tcx> ConstMutationChecker<'_, 'tcx> {
27 fn is_const_item(&self, local: Local) -> Option<DefId> {
28 if let Some(box LocalInfo::ConstRef { def_id }) = self.body.local_decls[local].local_info {
35 fn is_const_item_without_destructor(&self, local: Local) -> Option<DefId> {
36 let def_id = self.is_const_item(local)?;
38 // We avoid linting mutation of a const item if the const's type has a
39 // Drop impl. The Drop logic observes the mutation which was performed.
41 // pub struct Log { msg: &'static str }
42 // pub const LOG: Log = Log { msg: "" };
43 // impl Drop for Log {
44 // fn drop(&mut self) { println!("{}", self.msg); }
47 // LOG.msg = "wow"; // prints "wow"
49 // FIXME(https://github.com/rust-lang/rust/issues/77425):
50 // Drop this exception once there is a stable attribute to suppress the
51 // const item mutation lint for a single specific const only. Something
54 // #[const_mutation_allowed]
55 // pub const LOG: Log = Log { msg: "" };
56 match self.tcx.calculate_dtor(def_id, |_, _| Ok(())) {
62 fn lint_const_item_usage(
67 decorate: impl for<'b> FnOnce(LintDiagnosticBuilder<'b, ()>) -> DiagnosticBuilder<'b, ()>,
69 // Don't lint on borrowing/assigning when a dereference is involved.
70 // If we 'leave' the temporary via a dereference, we must
71 // be modifying something else
73 // `unsafe { *FOO = 0; *BAR.field = 1; }`
74 // `unsafe { &mut *FOO }`
75 // `unsafe { (*ARRAY)[0] = val; }
76 if !place.projection.iter().any(|p| matches!(p, PlaceElem::Deref)) {
77 let source_info = self.body.source_info(location);
78 let lint_root = self.body.source_scopes[source_info.scope]
84 self.tcx.struct_span_lint_hir(
90 .span_note(self.tcx.def_span(const_item), "`const` item defined here")
98 impl<'tcx> Visitor<'tcx> for ConstMutationChecker<'_, 'tcx> {
99 fn visit_statement(&mut self, stmt: &Statement<'tcx>, loc: Location) {
100 if let StatementKind::Assign(box (lhs, _)) = &stmt.kind {
101 // Check for assignment to fields of a constant
102 // Assigning directly to a constant (e.g. `FOO = true;`) is a hard error,
103 // so emitting a lint would be redundant.
104 if !lhs.projection.is_empty() {
105 if let Some(def_id) = self.is_const_item_without_destructor(lhs.local) {
106 self.lint_const_item_usage(&lhs, def_id, loc, |lint| {
107 let mut lint = lint.build("attempting to modify a `const` item");
108 lint.note("each usage of a `const` item creates a new temporary; the original `const` item will not be modified");
113 // We are looking for MIR of the form:
118 // method_call(_2, ..)
121 // Record our current LHS, so that we can detect this
122 // pattern in `visit_rvalue`
123 self.target_local = lhs.as_local();
125 self.super_statement(stmt, loc);
126 self.target_local = None;
128 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, loc: Location) {
129 if let Rvalue::Ref(_, BorrowKind::Mut { .. }, place) = rvalue {
130 let local = place.local;
131 if let Some(def_id) = self.is_const_item(local) {
132 // If this Rvalue is being used as the right-hand side of a
133 // `StatementKind::Assign`, see if it ends up getting used as
134 // the `self` parameter of a method call (as the terminator of our current
135 // BasicBlock). If so, we emit a more specific lint.
136 let method_did = self.target_local.and_then(|target_local| {
137 crate::util::find_self_call(self.tcx, &self.body, target_local, loc.block)
140 if method_did.is_some() { self.body.terminator_loc(loc.block) } else { loc };
141 self.lint_const_item_usage(place, def_id, lint_loc, |lint| {
142 let mut lint = lint.build("taking a mutable reference to a `const` item");
144 .note("each usage of a `const` item creates a new temporary")
145 .note("the mutable reference will refer to this temporary, not the original `const` item");
147 if let Some((method_did, _substs)) = method_did {
148 lint.span_note(self.tcx.def_span(method_did), "mutable reference created due to call to this method");
155 self.super_rvalue(rvalue, loc);