]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/check_const_item_mutation.rs
Add find_map_relevant_impl
[rust.git] / compiler / rustc_mir / src / transform / check_const_item_mutation.rs
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;
8
9 use crate::transform::MirPass;
10
11 pub struct CheckConstItemMutation;
12
13 impl<'tcx> MirPass<'tcx> for CheckConstItemMutation {
14     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
15         let mut checker = ConstMutationChecker { body, tcx, target_local: None };
16         checker.visit_body(&body);
17     }
18 }
19
20 struct ConstMutationChecker<'a, 'tcx> {
21     body: &'a Body<'tcx>,
22     tcx: TyCtxt<'tcx>,
23     target_local: Option<Local>,
24 }
25
26 impl<'a, 'tcx> ConstMutationChecker<'a, '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 {
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         match self.tcx.calculate_dtor(def_id, |_, _| Ok(())) {
57             Some(_) => None,
58             None => Some(def_id),
59         }
60     }
61
62     fn lint_const_item_usage(
63         &self,
64         const_item: DefId,
65         location: Location,
66         decorate: impl for<'b> FnOnce(LintDiagnosticBuilder<'b>) -> DiagnosticBuilder<'b>,
67     ) {
68         let source_info = self.body.source_info(location);
69         let lint_root = self.body.source_scopes[source_info.scope]
70             .local_data
71             .as_ref()
72             .assert_crate_local()
73             .lint_root;
74
75         self.tcx.struct_span_lint_hir(CONST_ITEM_MUTATION, lint_root, source_info.span, |lint| {
76             decorate(lint)
77                 .span_note(self.tcx.def_span(const_item), "`const` item defined here")
78                 .emit()
79         });
80     }
81 }
82
83 impl<'a, 'tcx> Visitor<'tcx> for ConstMutationChecker<'a, 'tcx> {
84     fn visit_statement(&mut self, stmt: &Statement<'tcx>, loc: Location) {
85         if let StatementKind::Assign(box (lhs, _)) = &stmt.kind {
86             // Check for assignment to fields of a constant
87             // Assigning directly to a constant (e.g. `FOO = true;`) is a hard error,
88             // so emitting a lint would be redundant.
89             if !lhs.projection.is_empty() {
90                 if let Some(def_id) = self.is_const_item_without_destructor(lhs.local) {
91                     // Don't lint on writes through a pointer
92                     // (e.g. `unsafe { *FOO = 0; *BAR.field = 1; }`)
93                     if !matches!(lhs.projection.last(), Some(PlaceElem::Deref)) {
94                         self.lint_const_item_usage(def_id, loc, |lint| {
95                             let mut lint = lint.build("attempting to modify a `const` item");
96                             lint.note("each usage of a `const` item creates a new temporary - the original `const` item will not be modified");
97                             lint
98                         })
99                     }
100                 }
101             }
102             // We are looking for MIR of the form:
103             //
104             // ```
105             // _1 = const FOO;
106             // _2 = &mut _1;
107             // method_call(_2, ..)
108             // ```
109             //
110             // Record our current LHS, so that we can detect this
111             // pattern in `visit_rvalue`
112             self.target_local = lhs.as_local();
113         }
114         self.super_statement(stmt, loc);
115         self.target_local = None;
116     }
117     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, loc: Location) {
118         if let Rvalue::Ref(_, BorrowKind::Mut { .. }, place) = rvalue {
119             let local = place.local;
120             if let Some(def_id) = self.is_const_item(local) {
121                 // If this Rvalue is being used as the right-hand side of a
122                 // `StatementKind::Assign`, see if it ends up getting used as
123                 // the `self` parameter of a method call (as the terminator of our current
124                 // BasicBlock). If so, we emit a more specific lint.
125                 let method_did = self.target_local.and_then(|target_local| {
126                     crate::util::find_self_call(self.tcx, &self.body, target_local, loc.block)
127                 });
128                 let lint_loc =
129                     if method_did.is_some() { self.body.terminator_loc(loc.block) } else { loc };
130                 self.lint_const_item_usage(def_id, lint_loc, |lint| {
131                     let mut lint = lint.build("taking a mutable reference to a `const` item");
132                     lint
133                         .note("each usage of a `const` item creates a new temporary")
134                         .note("the mutable reference will refer to this temporary, not the original `const` item");
135
136                     if let Some((method_did, _substs)) = method_did {
137                         lint.span_note(self.tcx.def_span(method_did), "mutable reference created due to call to this method");
138                     }
139
140                     lint
141                 });
142             }
143         }
144         self.super_rvalue(rvalue, loc);
145     }
146 }