rustc_mir_transform/check_const_item_mutation.rs
1use rustc_hir::HirId;
2use rustc_middle::mir::visit::Visitor;
3use rustc_middle::mir::*;
4use rustc_middle::ty::TyCtxt;
5use rustc_session::lint::builtin::CONST_ITEM_MUTATION;
6use rustc_span::Span;
7use rustc_span::def_id::DefId;
8
9use crate::errors;
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 has a
39 // Drop impl. The Drop logic observes the mutation which was performed.
40 //
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); }
45 // }
46 //
47 // LOG.msg = "wow"; // prints "wow"
48 //
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
52 // equivalent to:
53 //
54 // #[const_mutation_allowed]
55 // pub const LOG: Log = Log { msg: "" };
56 // FIXME: this should not be checking for `Drop` impls,
57 // but whether it or any field has a Drop impl (`needs_drop`)
58 // as fields' Drop impls may make this observable, too.
59 match self.tcx.type_of(def_id).skip_binder().ty_adt_def().map(|adt| adt.has_dtor(self.tcx))
60 {
61 Some(true) => None,
62 Some(false) | None => Some(def_id),
63 }
64 }
65
66 /// If we should lint on this usage, return the [`HirId`], source [`Span`]
67 /// and [`Span`] of the const item to use in the lint.
68 fn should_lint_const_item_usage(
69 &self,
70 place: &Place<'tcx>,
71 const_item: DefId,
72 location: Location,
73 ) -> Option<(HirId, Span, Span)> {
74 // Don't lint on borrowing/assigning when a dereference is involved.
75 // If we 'leave' the temporary via a dereference, we must
76 // be modifying something else
77 //
78 // `unsafe { *FOO = 0; *BAR.field = 1; }`
79 // `unsafe { &mut *FOO }`
80 // `unsafe { (*ARRAY)[0] = val; }`
81 if !place.projection.iter().any(|p| matches!(p, PlaceElem::Deref)) {
82 let source_info = self.body.source_info(location);
83 let lint_root = self.body.source_scopes[source_info.scope]
84 .local_data
85 .as_ref()
86 .unwrap_crate_local()
87 .lint_root;
88
89 Some((lint_root, source_info.span, self.tcx.def_span(const_item)))
90 } else {
91 None
92 }
93 }
94}
95
96impl<'tcx> Visitor<'tcx> for ConstMutationChecker<'_, 'tcx> {
97 fn visit_statement(&mut self, stmt: &Statement<'tcx>, loc: Location) {
98 if let StatementKind::Assign(box (lhs, _)) = &stmt.kind {
99 // Check for assignment to fields of a constant
100 // Assigning directly to a constant (e.g. `FOO = true;`) is a hard error,
101 // so emitting a lint would be redundant.
102 if !lhs.projection.is_empty()
103 && let Some(def_id) = self.is_const_item_without_destructor(lhs.local)
104 && let Some((lint_root, span, item)) =
105 self.should_lint_const_item_usage(lhs, def_id, loc)
106 {
107 self.tcx.emit_node_span_lint(
108 CONST_ITEM_MUTATION,
109 lint_root,
110 span,
111 errors::ConstMutate::Modify { konst: item },
112 );
113 }
114
115 // We are looking for MIR of the form:
116 //
117 // ```
118 // _1 = const FOO;
119 // _2 = &mut _1;
120 // method_call(_2, ..)
121 // ```
122 //
123 // Record our current LHS, so that we can detect this
124 // pattern in `visit_rvalue`
125 self.target_local = lhs.as_local();
126 }
127 self.super_statement(stmt, loc);
128 self.target_local = None;
129 }
130
131 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, loc: Location) {
132 if let Rvalue::Ref(_, BorrowKind::Mut { .. }, place) = rvalue {
133 let local = place.local;
134 if let Some(def_id) = self.is_const_item(local) {
135 // If this Rvalue is being used as the right-hand side of a
136 // `StatementKind::Assign`, see if it ends up getting used as
137 // the `self` parameter of a method call (as the terminator of our current
138 // BasicBlock). If so, we emit a more specific lint.
139 let method_did = self.target_local.and_then(|target_local| {
140 find_self_call(self.tcx, self.body, target_local, loc.block)
141 });
142 let lint_loc =
143 if method_did.is_some() { self.body.terminator_loc(loc.block) } else { loc };
144
145 let method_call = if let Some((method_did, _)) = method_did {
146 Some(self.tcx.def_span(method_did))
147 } else {
148 None
149 };
150 if let Some((lint_root, span, item)) =
151 self.should_lint_const_item_usage(place, def_id, lint_loc)
152 {
153 self.tcx.emit_node_span_lint(
154 CONST_ITEM_MUTATION,
155 lint_root,
156 span,
157 errors::ConstMutate::MutBorrow { method_call, konst: item },
158 );
159 }
160 }
161 }
162 self.super_rvalue(rvalue, loc);
163 }
164}