Skip to main content

rustc_mir_transform/
check_const_item_mutation.rs

1use rustc_hir::HirId;
2use rustc_lint_defs::builtin::CONST_ITEM_MUTATION;
3use rustc_middle::mir::visit::Visitor;
4use rustc_middle::mir::*;
5use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
6use rustc_span::Span;
7use rustc_span::def_id::DefId;
8
9use crate::diagnostics;
10
11pub(super) struct CheckConstItemMutation;
12
13impl<'tcx> crate::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);
17    }
18}
19
20struct ConstMutationChecker<'a, 'tcx> {
21    body: &'a Body<'tcx>,
22    tcx: TyCtxt<'tcx>,
23    target_local: Option<Local>,
24}
25
26impl<'tcx> ConstMutationChecker<'_, 'tcx> {
27    fn is_const_item(&self, local: Local) -> Option<DefId> {
28        if let LocalInfo::ConstRef { def_id } = *self.body.local_decls[local].local_info() {
29            Some(def_id)
30        } else {
31            None
32        }
33    }
34
35    fn is_const_item_without_destructor(&self, local: Local) -> Option<DefId> {
36        let def_id = self.is_const_item(local)?;
37
38        // We avoid linting mutation of a const item if the const's type needs
39        // drop. Any drop logic (including that of fields) may observe the
40        // mutation which was performed.
41        //
42        //     pub struct Log { msg: &'static str }
43        //     pub const LOG: Log = Log { msg: "" };
44        //     impl Drop for Log {
45        //         fn drop(&mut self) { println!("{}", self.msg); }
46        //     }
47        //
48        //     LOG.msg = "wow";  // prints "wow"
49        //
50        // Likewise, if a field of the const type has its own Drop impl, that
51        // drop logic may also observe the mutation:
52        //
53        //     struct Inner { val: u32 }
54        //     impl Drop for Inner { fn drop(&mut self) { println!("{}", self.val); } }
55        //     struct Outer { inner: Inner }
56        //     const O: Outer = Outer { inner: Inner { val: 0 } };
57        //
58        //     O.inner.val = 42;  // Inner::drop prints "42"
59        //
60        // FIXME(https://github.com/rust-lang/rust/issues/77425):
61        // Drop this exception once there is a stable attribute to suppress the
62        // const item mutation lint for a single specific const only.
63        let ty = self.tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
64        // `needs_drop` is overly conservative for types that contain type
65        // parameters (e.g. `Self` in a trait associated const): it always
66        // returns `true` because the parameter *might* implement Drop, even
67        // when the concrete type at the call site does not. In that case we
68        // cannot suppress the lint, so fall through and warn.
69        if ty.has_param() {
70            return Some(def_id);
71        }
72        let typing_env = ty::TypingEnv::non_body_analysis(self.tcx, def_id);
73        if ty.needs_drop(self.tcx, typing_env) { None } else { Some(def_id) }
74    }
75
76    /// If we should lint on this usage, return the [`HirId`], source [`Span`]
77    /// and [`Span`] of the const item to use in the lint.
78    fn should_lint_const_item_usage(
79        &self,
80        place: &Place<'tcx>,
81        const_item: DefId,
82        location: Location,
83    ) -> Option<(HirId, Span, Span)> {
84        // Don't lint on borrowing/assigning when a dereference is involved.
85        // If we 'leave' the temporary via a dereference, we must
86        // be modifying something else
87        //
88        // `unsafe { *FOO = 0; *BAR.field = 1; }`
89        // `unsafe { &mut *FOO }`
90        // `unsafe { (*ARRAY)[0] = val; }`
91        if !place.projection.iter().any(|p| matches!(p, PlaceElem::Deref)) {
92            let source_info = self.body.source_info(location);
93            let lint_root = self.body.source_scopes[source_info.scope]
94                .local_data
95                .as_ref()
96                .unwrap_crate_local()
97                .lint_root;
98
99            Some((lint_root, source_info.span, self.tcx.def_span(const_item)))
100        } else {
101            None
102        }
103    }
104}
105
106impl<'tcx> Visitor<'tcx> for ConstMutationChecker<'_, 'tcx> {
107    fn visit_statement(&mut self, stmt: &Statement<'tcx>, loc: Location) {
108        if let StatementKind::Assign((lhs, _)) = &stmt.kind {
109            // Check for assignment to fields of a constant
110            // Assigning directly to a constant (e.g. `FOO = true;`) is a hard error,
111            // so emitting a lint would be redundant.
112            if !lhs.projection.is_empty()
113                && let Some(def_id) = self.is_const_item_without_destructor(lhs.local)
114                && let Some((lint_root, span, item)) =
115                    self.should_lint_const_item_usage(lhs, def_id, loc)
116            {
117                self.tcx.emit_node_span_lint(
118                    CONST_ITEM_MUTATION,
119                    lint_root,
120                    span,
121                    diagnostics::ConstMutate::Modify { konst: item },
122                );
123            }
124
125            // We are looking for MIR of the form:
126            //
127            // ```
128            // _1 = const FOO;
129            // _2 = &mut _1;
130            // method_call(_2, ..)
131            // ```
132            //
133            // Record our current LHS, so that we can detect this
134            // pattern in `visit_rvalue`
135            self.target_local = lhs.as_local();
136        }
137        self.super_statement(stmt, loc);
138        self.target_local = None;
139    }
140
141    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, loc: Location) {
142        if let Rvalue::Ref(_, BorrowKind::Mut { .. }, place) = rvalue {
143            let local = place.local;
144            if let Some(def_id) = self.is_const_item(local) {
145                // If this Rvalue is being used as the right-hand side of a
146                // `StatementKind::Assign`, see if it ends up getting used as
147                // the `self` parameter of a method call (as the terminator of our current
148                // BasicBlock). If so, we emit a more specific lint.
149                let method_did = self.target_local.and_then(|target_local| {
150                    find_self_call(self.tcx, self.body, target_local, loc.block)
151                });
152                let lint_loc =
153                    if method_did.is_some() { self.body.terminator_loc(loc.block) } else { loc };
154
155                let method_call = if let Some((method_did, _)) = method_did {
156                    Some(self.tcx.def_span(method_did))
157                } else {
158                    None
159                };
160                if let Some((lint_root, span, item)) =
161                    self.should_lint_const_item_usage(place, def_id, lint_loc)
162                {
163                    self.tcx.emit_node_span_lint(
164                        CONST_ITEM_MUTATION,
165                        lint_root,
166                        span,
167                        diagnostics::ConstMutate::MutBorrow { method_call, konst: item },
168                    );
169                }
170            }
171        }
172        self.super_rvalue(rvalue, loc);
173    }
174}