]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_mir/src/transform/check_const_item_mutation.rs
New upstream version 1.48.0~beta.8+dfsg1
[rustc.git] / compiler / rustc_mir / src / transform / check_const_item_mutation.rs
CommitLineData
1b1a35ee
XL
1use rustc_errors::DiagnosticBuilder;
2use rustc_middle::lint::LintDiagnosticBuilder;
3use rustc_middle::mir::visit::Visitor;
4use rustc_middle::mir::*;
5use rustc_middle::ty::TyCtxt;
6use rustc_session::lint::builtin::CONST_ITEM_MUTATION;
7use rustc_span::def_id::DefId;
8
9use crate::transform::{MirPass, MirSource};
10
11pub struct CheckConstItemMutation;
12
13impl<'tcx> MirPass<'tcx> for CheckConstItemMutation {
14 fn run_pass(&self, tcx: TyCtxt<'tcx>, _src: MirSource<'tcx>, body: &mut 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<'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 let mut any_dtor = |_tcx, _def_id| Ok(());
38
39 // We avoid linting mutation of a const item if the const's type has a
40 // Drop impl. The Drop logic observes the 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 // FIXME(https://github.com/rust-lang/rust/issues/77425):
51 // Drop this exception once there is a stable attribute to suppress the
52 // const item mutation lint for a single specific const only. Something
53 // equivalent to:
54 //
55 // #[const_mutation_allowed]
56 // pub const LOG: Log = Log { msg: "" };
57 match self.tcx.calculate_dtor(def_id, &mut any_dtor) {
58 Some(_) => None,
59 None => Some(def_id),
60 }
61 }
62
63 fn lint_const_item_usage(
64 &self,
65 const_item: DefId,
66 location: Location,
67 decorate: impl for<'b> FnOnce(LintDiagnosticBuilder<'b>) -> DiagnosticBuilder<'b>,
68 ) {
69 let source_info = self.body.source_info(location);
70 let lint_root = self.body.source_scopes[source_info.scope]
71 .local_data
72 .as_ref()
73 .assert_crate_local()
74 .lint_root;
75
76 self.tcx.struct_span_lint_hir(CONST_ITEM_MUTATION, lint_root, source_info.span, |lint| {
77 decorate(lint)
78 .span_note(self.tcx.def_span(const_item), "`const` item defined here")
79 .emit()
80 });
81 }
82}
83
84impl<'a, 'tcx> Visitor<'tcx> for ConstMutationChecker<'a, 'tcx> {
85 fn visit_statement(&mut self, stmt: &Statement<'tcx>, loc: Location) {
86 if let StatementKind::Assign(box (lhs, _)) = &stmt.kind {
87 // Check for assignment to fields of a constant
88 // Assigning directly to a constant (e.g. `FOO = true;`) is a hard error,
89 // so emitting a lint would be redundant.
90 if !lhs.projection.is_empty() {
91 if let Some(def_id) = self.is_const_item_without_destructor(lhs.local) {
92 // Don't lint on writes through a pointer
93 // (e.g. `unsafe { *FOO = 0; *BAR.field = 1; }`)
94 if !matches!(lhs.projection.last(), Some(PlaceElem::Deref)) {
95 self.lint_const_item_usage(def_id, loc, |lint| {
96 let mut lint = lint.build("attempting to modify a `const` item");
97 lint.note("each usage of a `const` item creates a new temporary - the original `const` item will not be modified");
98 lint
99 })
100 }
101 }
102 }
103 // We are looking for MIR of the form:
104 //
105 // ```
106 // _1 = const FOO;
107 // _2 = &mut _1;
108 // method_call(_2, ..)
109 // ```
110 //
111 // Record our current LHS, so that we can detect this
112 // pattern in `visit_rvalue`
113 self.target_local = lhs.as_local();
114 }
115 self.super_statement(stmt, loc);
116 self.target_local = None;
117 }
118 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, loc: Location) {
119 if let Rvalue::Ref(_, BorrowKind::Mut { .. }, place) = rvalue {
120 let local = place.local;
121 if let Some(def_id) = self.is_const_item(local) {
122 // If this Rvalue is being used as the right-hand side of a
123 // `StatementKind::Assign`, see if it ends up getting used as
124 // the `self` parameter of a method call (as the terminator of our current
125 // BasicBlock). If so, we emit a more specific lint.
126 let method_did = self.target_local.and_then(|target_local| {
127 crate::util::find_self_call(self.tcx, &self.body, target_local, loc.block)
128 });
129 let lint_loc =
130 if method_did.is_some() { self.body.terminator_loc(loc.block) } else { loc };
131 self.lint_const_item_usage(def_id, lint_loc, |lint| {
132 let mut lint = lint.build("taking a mutable reference to a `const` item");
133 lint
134 .note("each usage of a `const` item creates a new temporary")
135 .note("the mutable reference will refer to this temporary, not the original `const` item");
136
137 if let Some((method_did, _substs)) = method_did {
138 lint.span_note(self.tcx.def_span(method_did), "mutable reference created due to call to this method");
139 }
140
141 lint
142 });
143 }
144 }
145 self.super_rvalue(rvalue, loc);
146 }
147}