]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_mir_transform/src/check_const_item_mutation.rs
New upstream version 1.70.0+dfsg1
[rustc.git] / compiler / rustc_mir_transform / src / check_const_item_mutation.rs
CommitLineData
2b03887a 1use rustc_errors::{DiagnosticBuilder, DiagnosticMessage};
1b1a35ee
XL
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::def_id::DefId;
7
a2a8927a 8use crate::MirLint;
1b1a35ee
XL
9
10pub struct CheckConstItemMutation;
11
a2a8927a
XL
12impl<'tcx> MirLint<'tcx> for CheckConstItemMutation {
13 fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
1b1a35ee
XL
14 let mut checker = ConstMutationChecker { body, tcx, target_local: None };
15 checker.visit_body(&body);
16 }
17}
18
19struct ConstMutationChecker<'a, 'tcx> {
20 body: &'a Body<'tcx>,
21 tcx: TyCtxt<'tcx>,
22 target_local: Option<Local>,
23}
24
a2a8927a 25impl<'tcx> ConstMutationChecker<'_, 'tcx> {
1b1a35ee 26 fn is_const_item(&self, local: Local) -> Option<DefId> {
353b0b11 27 if let LocalInfo::ConstRef { def_id } = *self.body.local_decls[local].local_info() {
1b1a35ee
XL
28 Some(def_id)
29 } else {
30 None
31 }
32 }
33
34 fn is_const_item_without_destructor(&self, local: Local) -> Option<DefId> {
35 let def_id = self.is_const_item(local)?;
1b1a35ee
XL
36
37 // We avoid linting mutation of a const item if the const's type has a
38 // Drop impl. The Drop logic observes the mutation which was performed.
39 //
40 // pub struct Log { msg: &'static str }
41 // pub const LOG: Log = Log { msg: "" };
42 // impl Drop for Log {
43 // fn drop(&mut self) { println!("{}", self.msg); }
44 // }
45 //
46 // LOG.msg = "wow"; // prints "wow"
47 //
48 // FIXME(https://github.com/rust-lang/rust/issues/77425):
49 // Drop this exception once there is a stable attribute to suppress the
50 // const item mutation lint for a single specific const only. Something
51 // equivalent to:
52 //
53 // #[const_mutation_allowed]
54 // pub const LOG: Log = Log { msg: "" };
29967ef6 55 match self.tcx.calculate_dtor(def_id, |_, _| Ok(())) {
1b1a35ee
XL
56 Some(_) => None,
57 None => Some(def_id),
58 }
59 }
60
61 fn lint_const_item_usage(
62 &self,
29967ef6 63 place: &Place<'tcx>,
1b1a35ee
XL
64 const_item: DefId,
65 location: Location,
2b03887a
FG
66 msg: impl Into<DiagnosticMessage>,
67 decorate: impl for<'a, 'b> FnOnce(
68 &'a mut DiagnosticBuilder<'b, ()>,
69 ) -> &'a mut DiagnosticBuilder<'b, ()>,
1b1a35ee 70 ) {
fc512014
XL
71 // Don't lint on borrowing/assigning when a dereference is involved.
72 // If we 'leave' the temporary via a dereference, we must
73 // be modifying something else
29967ef6
XL
74 //
75 // `unsafe { *FOO = 0; *BAR.field = 1; }`
76 // `unsafe { &mut *FOO }`
9ffffee4 77 // `unsafe { (*ARRAY)[0] = val; }`
fc512014 78 if !place.projection.iter().any(|p| matches!(p, PlaceElem::Deref)) {
29967ef6
XL
79 let source_info = self.body.source_info(location);
80 let lint_root = self.body.source_scopes[source_info.scope]
81 .local_data
82 .as_ref()
83 .assert_crate_local()
84 .lint_root;
1b1a35ee 85
29967ef6
XL
86 self.tcx.struct_span_lint_hir(
87 CONST_ITEM_MUTATION,
88 lint_root,
89 source_info.span,
2b03887a 90 msg,
29967ef6
XL
91 |lint| {
92 decorate(lint)
93 .span_note(self.tcx.def_span(const_item), "`const` item defined here")
29967ef6
XL
94 },
95 );
96 }
1b1a35ee
XL
97 }
98}
99
a2a8927a 100impl<'tcx> Visitor<'tcx> for ConstMutationChecker<'_, 'tcx> {
1b1a35ee
XL
101 fn visit_statement(&mut self, stmt: &Statement<'tcx>, loc: Location) {
102 if let StatementKind::Assign(box (lhs, _)) = &stmt.kind {
103 // Check for assignment to fields of a constant
104 // Assigning directly to a constant (e.g. `FOO = true;`) is a hard error,
105 // so emitting a lint would be redundant.
106 if !lhs.projection.is_empty() {
107 if let Some(def_id) = self.is_const_item_without_destructor(lhs.local) {
2b03887a
FG
108 self.lint_const_item_usage(&lhs, def_id, loc, "attempting to modify a `const` item",|lint| {
109 lint.note("each usage of a `const` item creates a new temporary; the original `const` item will not be modified")
29967ef6 110 })
1b1a35ee
XL
111 }
112 }
113 // We are looking for MIR of the form:
114 //
115 // ```
116 // _1 = const FOO;
117 // _2 = &mut _1;
118 // method_call(_2, ..)
119 // ```
120 //
121 // Record our current LHS, so that we can detect this
122 // pattern in `visit_rvalue`
123 self.target_local = lhs.as_local();
124 }
125 self.super_statement(stmt, loc);
126 self.target_local = None;
127 }
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)
138 });
139 let lint_loc =
140 if method_did.is_some() { self.body.terminator_loc(loc.block) } else { loc };
2b03887a 141 self.lint_const_item_usage(place, def_id, lint_loc, "taking a mutable reference to a `const` item", |lint| {
1b1a35ee
XL
142 lint
143 .note("each usage of a `const` item creates a new temporary")
144 .note("the mutable reference will refer to this temporary, not the original `const` item");
145
146 if let Some((method_did, _substs)) = method_did {
147 lint.span_note(self.tcx.def_span(method_did), "mutable reference created due to call to this method");
148 }
149
150 lint
151 });
152 }
153 }
154 self.super_rvalue(rvalue, loc);
155 }
156}