]>
Commit | Line | Data |
---|---|---|
ff7c6d11 XL |
1 | //! This query borrow-checks the MIR to (further) ensure it is not broken. |
2 | ||
532ac7d7 | 3 | use rustc_data_structures::fx::{FxHashMap, FxHashSet}; |
0bf4aa26 | 4 | use rustc_data_structures::graph::dominators::Dominators; |
ba9703b0 | 5 | use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorReported}; |
dfeec247 | 6 | use rustc_hir as hir; |
f9f354fc XL |
7 | use rustc_hir::def_id::LocalDefId; |
8 | use rustc_hir::{HirId, Node}; | |
dfeec247 | 9 | use rustc_index::bit_set::BitSet; |
e74abb32 | 10 | use rustc_index::vec::IndexVec; |
74b04a01 | 11 | use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; |
ba9703b0 | 12 | use rustc_middle::mir::{ |
f9f354fc XL |
13 | traversal, Body, ClearCrossCrate, Local, Location, Mutability, Operand, Place, PlaceElem, |
14 | PlaceRef, | |
ba9703b0 XL |
15 | }; |
16 | use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind}; | |
17 | use rustc_middle::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind}; | |
f9f354fc | 18 | use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind}; |
ba9703b0 | 19 | use rustc_middle::ty::query::Providers; |
3dfed10e | 20 | use rustc_middle::ty::{self, InstanceDef, RegionVid, TyCtxt}; |
ba9703b0 | 21 | use rustc_session::lint::builtin::{MUTABLE_BORROW_RESERVATION_CONFLICT, UNUSED_MUT}; |
f9f354fc | 22 | use rustc_span::{Span, Symbol, DUMMY_SP}; |
ff7c6d11 | 23 | |
74b04a01 | 24 | use either::Either; |
dfeec247 XL |
25 | use smallvec::SmallVec; |
26 | use std::cell::RefCell; | |
0bf4aa26 | 27 | use std::collections::BTreeMap; |
532ac7d7 XL |
28 | use std::mem; |
29 | use std::rc::Rc; | |
ff7c6d11 | 30 | |
74b04a01 | 31 | use crate::dataflow; |
f9f354fc XL |
32 | use crate::dataflow::impls::{ |
33 | Borrows, EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces, | |
34 | }; | |
9fa01778 | 35 | use crate::dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex}; |
74b04a01 | 36 | use crate::dataflow::move_paths::{InitLocation, LookupResult, MoveData, MoveError}; |
9fa01778 | 37 | use crate::dataflow::MoveDataParamEnv; |
ba9703b0 | 38 | use crate::dataflow::{Analysis, BorrowckFlowState as Flows, BorrowckResults}; |
dfeec247 | 39 | use crate::transform::MirSource; |
ff7c6d11 | 40 | |
dfeec247 | 41 | use self::diagnostics::{AccessKind, RegionName}; |
83c7162d | 42 | use self::location::LocationTable; |
ff7c6d11 XL |
43 | use self::prefixes::PrefixSet; |
44 | use self::MutateMode::{JustWrite, WriteAndRead}; | |
45 | ||
94b46f34 XL |
46 | use self::path_utils::*; |
47 | ||
dfeec247 XL |
48 | mod borrow_set; |
49 | mod constraint_generation; | |
50 | mod constraints; | |
f9f354fc | 51 | mod def_use; |
60c5eb7d | 52 | mod diagnostics; |
dfeec247 | 53 | mod facts; |
dfeec247 | 54 | mod invalidation; |
83c7162d | 55 | mod location; |
dfeec247 XL |
56 | mod member_constraints; |
57 | mod nll; | |
8faf50e0 | 58 | mod path_utils; |
dfeec247 XL |
59 | mod place_ext; |
60 | mod places_conflict; | |
ff7c6d11 | 61 | mod prefixes; |
dfeec247 | 62 | mod region_infer; |
60c5eb7d | 63 | mod renumber; |
60c5eb7d | 64 | mod type_check; |
dfeec247 XL |
65 | mod universal_regions; |
66 | mod used_muts; | |
60c5eb7d | 67 | |
dfeec247 | 68 | crate use borrow_set::{BorrowData, BorrowSet}; |
74b04a01 | 69 | crate use nll::{PoloniusOutput, ToRegionVid}; |
dfeec247 XL |
70 | crate use place_ext::PlaceExt; |
71 | crate use places_conflict::{places_conflict, PlaceConflictBias}; | |
72 | crate use region_infer::RegionInferenceContext; | |
ff7c6d11 | 73 | |
48663c56 XL |
74 | // FIXME(eddyb) perhaps move this somewhere more centrally. |
75 | #[derive(Debug)] | |
76 | crate struct Upvar { | |
f9f354fc | 77 | name: Symbol, |
48663c56 XL |
78 | |
79 | var_hir_id: HirId, | |
80 | ||
81 | /// If true, the capture is behind a reference. | |
82 | by_ref: bool, | |
83 | ||
84 | mutability: Mutability, | |
85 | } | |
86 | ||
74b04a01 XL |
87 | const DEREF_PROJECTION: &[PlaceElem<'_>; 1] = &[ProjectionElem::Deref]; |
88 | ||
f035d41b | 89 | pub fn provide(providers: &mut Providers) { |
3dfed10e XL |
90 | *providers = Providers { |
91 | mir_borrowck: |tcx, did| { | |
92 | if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) { | |
93 | tcx.mir_borrowck_const_arg(def) | |
94 | } else { | |
95 | mir_borrowck(tcx, ty::WithOptConstParam::unknown(did)) | |
96 | } | |
97 | }, | |
98 | mir_borrowck_const_arg: |tcx, (did, param_did)| { | |
99 | mir_borrowck(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) }) | |
100 | }, | |
101 | ..*providers | |
102 | }; | |
ff7c6d11 XL |
103 | } |
104 | ||
3dfed10e XL |
105 | fn mir_borrowck<'tcx>( |
106 | tcx: TyCtxt<'tcx>, | |
107 | def: ty::WithOptConstParam<LocalDefId>, | |
108 | ) -> &'tcx BorrowCheckResult<'tcx> { | |
109 | let (input_body, promoted) = tcx.mir_promoted(def); | |
110 | debug!("run query mir_borrowck: {}", tcx.def_path_str(def.did.to_def_id())); | |
ff7c6d11 | 111 | |
ff7c6d11 | 112 | let opt_closure_req = tcx.infer_ctxt().enter(|infcx| { |
dc9dc135 | 113 | let input_body: &Body<'_> = &input_body.borrow(); |
e1599b0c | 114 | let promoted: &IndexVec<_, _> = &promoted.borrow(); |
3dfed10e | 115 | do_mir_borrowck(&infcx, input_body, promoted, def) |
ff7c6d11 XL |
116 | }); |
117 | debug!("mir_borrowck done"); | |
118 | ||
3dfed10e | 119 | tcx.arena.alloc(opt_closure_req) |
ff7c6d11 XL |
120 | } |
121 | ||
dc9dc135 XL |
122 | fn do_mir_borrowck<'a, 'tcx>( |
123 | infcx: &InferCtxt<'a, 'tcx>, | |
124 | input_body: &Body<'tcx>, | |
f9f354fc | 125 | input_promoted: &IndexVec<Promoted, Body<'tcx>>, |
3dfed10e | 126 | def: ty::WithOptConstParam<LocalDefId>, |
dc9dc135 | 127 | ) -> BorrowCheckResult<'tcx> { |
3dfed10e | 128 | debug!("do_mir_borrowck(def = {:?})", def); |
8faf50e0 | 129 | |
ff7c6d11 | 130 | let tcx = infcx.tcx; |
3dfed10e XL |
131 | let param_env = tcx.param_env(def.did); |
132 | let id = tcx.hir().local_def_id_to_hir_id(def.did); | |
ff7c6d11 | 133 | |
60c5eb7d XL |
134 | let mut local_names = IndexVec::from_elem(None, &input_body.local_decls); |
135 | for var_debug_info in &input_body.var_debug_info { | |
136 | if let Some(local) = var_debug_info.place.as_local() { | |
137 | if let Some(prev_name) = local_names[local] { | |
138 | if var_debug_info.name != prev_name { | |
dfeec247 XL |
139 | span_bug!( |
140 | var_debug_info.source_info.span, | |
60c5eb7d | 141 | "local {:?} has many names (`{}` vs `{}`)", |
dfeec247 XL |
142 | local, |
143 | prev_name, | |
144 | var_debug_info.name | |
145 | ); | |
60c5eb7d XL |
146 | } |
147 | } | |
148 | local_names[local] = Some(var_debug_info.name); | |
149 | } | |
150 | } | |
151 | ||
48663c56 | 152 | // Gather the upvars of a closure, if any. |
3dfed10e | 153 | let tables = tcx.typeck_opt_const_arg(def); |
ba9703b0 | 154 | if let Some(ErrorReported) = tables.tainted_by_errors { |
74b04a01 XL |
155 | infcx.set_tainted_by_errors(); |
156 | } | |
48663c56 | 157 | let upvars: Vec<_> = tables |
f9f354fc | 158 | .closure_captures |
3dfed10e | 159 | .get(&def.did.to_def_id()) |
48663c56 | 160 | .into_iter() |
dc9dc135 | 161 | .flat_map(|v| v.values()) |
48663c56 XL |
162 | .map(|upvar_id| { |
163 | let var_hir_id = upvar_id.var_path.hir_id; | |
48663c56 XL |
164 | let capture = tables.upvar_capture(*upvar_id); |
165 | let by_ref = match capture { | |
166 | ty::UpvarCapture::ByValue => false, | |
167 | ty::UpvarCapture::ByRef(..) => true, | |
168 | }; | |
169 | let mut upvar = Upvar { | |
dc9dc135 | 170 | name: tcx.hir().name(var_hir_id), |
48663c56 XL |
171 | var_hir_id, |
172 | by_ref, | |
173 | mutability: Mutability::Not, | |
174 | }; | |
dfeec247 XL |
175 | let bm = *tables.pat_binding_modes().get(var_hir_id).expect("missing binding mode"); |
176 | if bm == ty::BindByValue(hir::Mutability::Mut) { | |
48663c56 XL |
177 | upvar.mutability = Mutability::Mut; |
178 | } | |
179 | upvar | |
180 | }) | |
181 | .collect(); | |
182 | ||
83c7162d XL |
183 | // Replace all regions with fresh inference variables. This |
184 | // requires first making our own copy of the MIR. This copy will | |
185 | // be modified (in place) to contain non-lexical lifetimes. It | |
186 | // will have a lifetime tied to the inference context. | |
f9f354fc | 187 | let mut body = input_body.clone(); |
60c5eb7d | 188 | let mut promoted = input_promoted.clone(); |
3dfed10e | 189 | let free_regions = nll::replace_regions_in_mir(infcx, def, param_env, &mut body, &mut promoted); |
f9f354fc | 190 | let body = &body; // no further changes |
60c5eb7d XL |
191 | |
192 | let location_table = &LocationTable::new(&body); | |
ff7c6d11 | 193 | |
8faf50e0 | 194 | let mut errors_buffer = Vec::new(); |
f9f354fc | 195 | let (move_data, move_errors): (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>) = |
60c5eb7d | 196 | match MoveData::gather_moves(&body, tcx, param_env) { |
f9f354fc XL |
197 | Ok(move_data) => (move_data, Vec::new()), |
198 | Err((move_data, move_errors)) => (move_data, move_errors), | |
8faf50e0 | 199 | }; |
f9f354fc XL |
200 | let promoted_errors = promoted |
201 | .iter_enumerated() | |
202 | .map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env))); | |
ff7c6d11 | 203 | |
dfeec247 | 204 | let mdpe = MoveDataParamEnv { move_data, param_env }; |
ff7c6d11 | 205 | |
74b04a01 | 206 | let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe) |
3dfed10e | 207 | .into_engine(tcx, &body, def.did.to_def_id()) |
74b04a01 XL |
208 | .iterate_to_fixpoint() |
209 | .into_results_cursor(&body); | |
ff7c6d11 | 210 | |
dc9dc135 | 211 | let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure(); |
dfeec247 XL |
212 | let borrow_set = |
213 | Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data)); | |
214 | ||
215 | // Compute non-lexical lifetimes. | |
74b04a01 XL |
216 | let nll::NllOutput { |
217 | regioncx, | |
218 | opaque_type_values, | |
219 | polonius_output, | |
220 | opt_closure_req, | |
221 | nll_errors, | |
222 | } = nll::compute_regions( | |
223 | infcx, | |
3dfed10e | 224 | def.did, |
74b04a01 XL |
225 | free_regions, |
226 | body, | |
227 | &promoted, | |
228 | location_table, | |
229 | param_env, | |
230 | &mut flow_inits, | |
231 | &mdpe.move_data, | |
232 | &borrow_set, | |
f035d41b | 233 | &upvars, |
74b04a01 | 234 | ); |
83c7162d | 235 | |
dfeec247 XL |
236 | // Dump MIR results into a file, if that is enabled. This let us |
237 | // write unit-tests, as well as helping with debugging. | |
f9f354fc XL |
238 | nll::dump_mir_results( |
239 | infcx, | |
3dfed10e | 240 | MirSource { instance: InstanceDef::Item(def.to_global()), promoted: None }, |
f9f354fc XL |
241 | &body, |
242 | ®ioncx, | |
243 | &opt_closure_req, | |
244 | ); | |
dfeec247 | 245 | |
74b04a01 | 246 | // We also have a `#[rustc_regions]` annotation that causes us to dump |
dfeec247 | 247 | // information. |
74b04a01 XL |
248 | nll::dump_annotation( |
249 | infcx, | |
250 | &body, | |
3dfed10e | 251 | def.did.to_def_id(), |
74b04a01 XL |
252 | ®ioncx, |
253 | &opt_closure_req, | |
254 | &opaque_type_values, | |
255 | &mut errors_buffer, | |
256 | ); | |
b7449926 XL |
257 | |
258 | // The various `flow_*` structures can be large. We drop `flow_inits` here | |
259 | // so it doesn't overlap with the others below. This reduces peak memory | |
260 | // usage significantly on some benchmarks. | |
261 | drop(flow_inits); | |
262 | ||
83c7162d | 263 | let regioncx = Rc::new(regioncx); |
ff7c6d11 | 264 | |
74b04a01 | 265 | let flow_borrows = Borrows::new(tcx, &body, regioncx.clone(), &borrow_set) |
3dfed10e | 266 | .into_engine(tcx, &body, def.did.to_def_id()) |
74b04a01 XL |
267 | .iterate_to_fixpoint(); |
268 | let flow_uninits = MaybeUninitializedPlaces::new(tcx, &body, &mdpe) | |
3dfed10e | 269 | .into_engine(tcx, &body, def.did.to_def_id()) |
74b04a01 XL |
270 | .iterate_to_fixpoint(); |
271 | let flow_ever_inits = EverInitializedPlaces::new(tcx, &body, &mdpe) | |
3dfed10e | 272 | .into_engine(tcx, &body, def.did.to_def_id()) |
74b04a01 | 273 | .iterate_to_fixpoint(); |
0531ce1d | 274 | |
dc9dc135 | 275 | let movable_generator = match tcx.hir().get(id) { |
b7449926 | 276 | Node::Expr(&hir::Expr { |
60c5eb7d | 277 | kind: hir::ExprKind::Closure(.., Some(hir::Movability::Static)), |
2c00a5a8 | 278 | .. |
83c7162d XL |
279 | }) => false, |
280 | _ => true, | |
2c00a5a8 XL |
281 | }; |
282 | ||
f9f354fc XL |
283 | for (idx, move_data_results) in promoted_errors { |
284 | let promoted_body = &promoted[idx]; | |
285 | let dominators = promoted_body.dominators(); | |
286 | ||
287 | if let Err((move_data, move_errors)) = move_data_results { | |
288 | let mut promoted_mbcx = MirBorrowckCtxt { | |
289 | infcx, | |
290 | body: promoted_body, | |
3dfed10e | 291 | mir_def_id: def.did, |
f9f354fc XL |
292 | move_data: &move_data, |
293 | location_table: &LocationTable::new(promoted_body), | |
294 | movable_generator, | |
f035d41b | 295 | fn_self_span_reported: Default::default(), |
f9f354fc XL |
296 | locals_are_invalidated_at_exit, |
297 | access_place_error_reported: Default::default(), | |
298 | reservation_error_reported: Default::default(), | |
299 | reservation_warnings: Default::default(), | |
300 | move_error_reported: BTreeMap::new(), | |
301 | uninitialized_error_reported: Default::default(), | |
302 | errors_buffer, | |
303 | regioncx: regioncx.clone(), | |
304 | used_mut: Default::default(), | |
305 | used_mut_upvars: SmallVec::new(), | |
306 | borrow_set: borrow_set.clone(), | |
307 | dominators, | |
308 | upvars: Vec::new(), | |
309 | local_names: IndexVec::from_elem(None, &promoted_body.local_decls), | |
310 | region_names: RefCell::default(), | |
311 | next_region_name: RefCell::new(1), | |
312 | polonius_output: None, | |
313 | }; | |
314 | promoted_mbcx.report_move_errors(move_errors); | |
315 | errors_buffer = promoted_mbcx.errors_buffer; | |
316 | }; | |
317 | } | |
318 | ||
dc9dc135 | 319 | let dominators = body.dominators(); |
83c7162d | 320 | |
ff7c6d11 | 321 | let mut mbcx = MirBorrowckCtxt { |
0bf4aa26 | 322 | infcx, |
dc9dc135 | 323 | body, |
3dfed10e | 324 | mir_def_id: def.did, |
ff7c6d11 | 325 | move_data: &mdpe.move_data, |
8faf50e0 | 326 | location_table, |
2c00a5a8 | 327 | movable_generator, |
b7449926 | 328 | locals_are_invalidated_at_exit, |
f035d41b | 329 | fn_self_span_reported: Default::default(), |
0bf4aa26 XL |
330 | access_place_error_reported: Default::default(), |
331 | reservation_error_reported: Default::default(), | |
532ac7d7 | 332 | reservation_warnings: Default::default(), |
0bf4aa26 XL |
333 | move_error_reported: BTreeMap::new(), |
334 | uninitialized_error_reported: Default::default(), | |
8faf50e0 | 335 | errors_buffer, |
dfeec247 | 336 | regioncx, |
0bf4aa26 | 337 | used_mut: Default::default(), |
83c7162d | 338 | used_mut_upvars: SmallVec::new(), |
83c7162d XL |
339 | borrow_set, |
340 | dominators, | |
48663c56 | 341 | upvars, |
60c5eb7d | 342 | local_names, |
dfeec247 XL |
343 | region_names: RefCell::default(), |
344 | next_region_name: RefCell::new(1), | |
74b04a01 | 345 | polonius_output, |
ff7c6d11 XL |
346 | }; |
347 | ||
dfeec247 XL |
348 | // Compute and report region errors, if any. |
349 | mbcx.report_region_errors(nll_errors); | |
350 | ||
74b04a01 XL |
351 | let results = BorrowckResults { |
352 | ever_inits: flow_ever_inits, | |
353 | uninits: flow_uninits, | |
354 | borrows: flow_borrows, | |
355 | }; | |
ff7c6d11 | 356 | |
f9f354fc | 357 | mbcx.report_move_errors(move_errors); |
74b04a01 | 358 | |
ba9703b0 XL |
359 | dataflow::visit_results( |
360 | &body, | |
361 | traversal::reverse_postorder(&body).map(|(bb, _)| bb), | |
74b04a01 XL |
362 | &results, |
363 | &mut mbcx, | |
364 | ); | |
ff7c6d11 | 365 | |
532ac7d7 | 366 | // Convert any reservation warnings into lints. |
416331ca | 367 | let reservation_warnings = mem::take(&mut mbcx.reservation_warnings); |
48663c56 | 368 | for (_, (place, span, location, bk, borrow)) in reservation_warnings { |
ba9703b0 | 369 | let mut initial_diag = mbcx.report_conflicting_borrow(location, (place, span), bk, &borrow); |
532ac7d7 | 370 | |
60c5eb7d XL |
371 | let scope = mbcx.body.source_info(location).scope; |
372 | let lint_root = match &mbcx.body.source_scopes[scope].local_data { | |
373 | ClearCrossCrate::Set(data) => data.lint_root, | |
374 | _ => id, | |
532ac7d7 XL |
375 | }; |
376 | ||
377 | // Span and message don't matter; we overwrite them below anyway | |
74b04a01 | 378 | mbcx.infcx.tcx.struct_span_lint_hir( |
dfeec247 XL |
379 | MUTABLE_BORROW_RESERVATION_CONFLICT, |
380 | lint_root, | |
381 | DUMMY_SP, | |
74b04a01 XL |
382 | |lint| { |
383 | let mut diag = lint.build(""); | |
532ac7d7 | 384 | |
74b04a01 XL |
385 | diag.message = initial_diag.styled_message().clone(); |
386 | diag.span = initial_diag.span.clone(); | |
532ac7d7 | 387 | |
74b04a01 XL |
388 | diag.buffer(&mut mbcx.errors_buffer); |
389 | }, | |
390 | ); | |
532ac7d7 | 391 | initial_diag.cancel(); |
532ac7d7 XL |
392 | } |
393 | ||
83c7162d XL |
394 | // For each non-user used mutable variable, check if it's been assigned from |
395 | // a user-declared local. If so, then put that local into the used_mut set. | |
396 | // Note that this set is expected to be small - only upvars from closures | |
397 | // would have a chance of erroneously adding non-user-defined mutable vars | |
398 | // to the set. | |
dfeec247 XL |
399 | let temporary_used_locals: FxHashSet<Local> = mbcx |
400 | .used_mut | |
401 | .iter() | |
60c5eb7d | 402 | .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable()) |
8faf50e0 XL |
403 | .cloned() |
404 | .collect(); | |
a1dfa0c6 XL |
405 | // For the remaining unused locals that are marked as mutable, we avoid linting any that |
406 | // were never initialized. These locals may have been removed as unreachable code; or will be | |
407 | // linted as unused variables. | |
dfeec247 XL |
408 | let unused_mut_locals = |
409 | mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect(); | |
a1dfa0c6 | 410 | mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals); |
83c7162d XL |
411 | |
412 | debug!("mbcx.used_mut: {:?}", mbcx.used_mut); | |
8faf50e0 | 413 | let used_mut = mbcx.used_mut; |
dfeec247 | 414 | for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) { |
60c5eb7d XL |
415 | let local_decl = &mbcx.body.local_decls[local]; |
416 | let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data { | |
417 | ClearCrossCrate::Set(data) => data.lint_root, | |
418 | _ => continue, | |
419 | }; | |
83c7162d | 420 | |
60c5eb7d XL |
421 | // Skip over locals that begin with an underscore or have no name |
422 | match mbcx.local_names[local] { | |
dfeec247 | 423 | Some(name) => { |
74b04a01 | 424 | if name.as_str().starts_with('_') { |
dfeec247 XL |
425 | continue; |
426 | } | |
427 | } | |
60c5eb7d XL |
428 | None => continue, |
429 | } | |
83c7162d | 430 | |
60c5eb7d XL |
431 | let span = local_decl.source_info.span; |
432 | if span.desugaring_kind().is_some() { | |
433 | // If the `mut` arises as part of a desugaring, we should ignore it. | |
434 | continue; | |
8faf50e0 | 435 | } |
60c5eb7d | 436 | |
74b04a01 XL |
437 | tcx.struct_span_lint_hir(UNUSED_MUT, lint_root, span, |lint| { |
438 | let mut_span = tcx.sess.source_map().span_until_non_whitespace(span); | |
439 | lint.build("variable does not need to be mutable") | |
440 | .span_suggestion_short( | |
441 | mut_span, | |
442 | "remove this `mut`", | |
443 | String::new(), | |
444 | Applicability::MachineApplicable, | |
445 | ) | |
446 | .emit(); | |
447 | }) | |
8faf50e0 XL |
448 | } |
449 | ||
0bf4aa26 XL |
450 | // Buffer any move errors that we collected and de-duplicated. |
451 | for (_, (_, diag)) in mbcx.move_error_reported { | |
452 | diag.buffer(&mut mbcx.errors_buffer); | |
453 | } | |
454 | ||
455 | if !mbcx.errors_buffer.is_empty() { | |
60c5eb7d | 456 | mbcx.errors_buffer.sort_by_key(|diag| diag.sort_span); |
b7449926 | 457 | |
8faf50e0 | 458 | for diag in mbcx.errors_buffer.drain(..) { |
e1599b0c | 459 | mbcx.infcx.tcx.sess.diagnostic().emit_diagnostic(&diag); |
83c7162d XL |
460 | } |
461 | } | |
462 | ||
8faf50e0 | 463 | let result = BorrowCheckResult { |
74b04a01 | 464 | concrete_opaque_types: opaque_type_values, |
83c7162d XL |
465 | closure_requirements: opt_closure_req, |
466 | used_mut_upvars: mbcx.used_mut_upvars, | |
8faf50e0 XL |
467 | }; |
468 | ||
469 | debug!("do_mir_borrowck: result = {:#?}", result); | |
470 | ||
471 | result | |
ff7c6d11 XL |
472 | } |
473 | ||
416331ca XL |
474 | crate struct MirBorrowckCtxt<'cx, 'tcx> { |
475 | crate infcx: &'cx InferCtxt<'cx, 'tcx>, | |
f9f354fc XL |
476 | body: &'cx Body<'tcx>, |
477 | mir_def_id: LocalDefId, | |
ff7c6d11 | 478 | move_data: &'cx MoveData<'tcx>, |
8faf50e0 XL |
479 | |
480 | /// Map from MIR `Location` to `LocationIndex`; created | |
481 | /// when MIR borrowck begins. | |
482 | location_table: &'cx LocationTable, | |
483 | ||
2c00a5a8 | 484 | movable_generator: bool, |
ff7c6d11 XL |
485 | /// This keeps track of whether local variables are free-ed when the function |
486 | /// exits even without a `StorageDead`, which appears to be the case for | |
487 | /// constants. | |
488 | /// | |
489 | /// I'm not sure this is the right approach - @eddyb could you try and | |
490 | /// figure this out? | |
491 | locals_are_invalidated_at_exit: bool, | |
2c00a5a8 XL |
492 | /// This field keeps track of when borrow errors are reported in the access_place function |
493 | /// so that there is no duplicate reporting. This field cannot also be used for the conflicting | |
494 | /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion | |
495 | /// of the `Span` type (while required to mute some errors) stops the muting of the reservation | |
496 | /// errors. | |
497 | access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>, | |
ff7c6d11 XL |
498 | /// This field keeps track of when borrow conflict errors are reported |
499 | /// for reservations, so that we don't report seemingly duplicate | |
9fa01778 XL |
500 | /// errors for corresponding activations. |
501 | // | |
502 | // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s, | |
503 | // but it is currently inconvenient to track down the `BorrowIndex` | |
504 | // at the time we detect and report a reservation error. | |
ff7c6d11 | 505 | reservation_error_reported: FxHashSet<Place<'tcx>>, |
f035d41b XL |
506 | /// This fields keeps track of the `Span`s that we have |
507 | /// used to report extra information for `FnSelfUse`, to avoid | |
508 | /// unnecessarily verbose errors. | |
509 | fn_self_span_reported: FxHashSet<Span>, | |
532ac7d7 XL |
510 | /// Migration warnings to be reported for #56254. We delay reporting these |
511 | /// so that we can suppress the warning if there's a corresponding error | |
512 | /// for the activation of the borrow. | |
dfeec247 XL |
513 | reservation_warnings: |
514 | FxHashMap<BorrowIndex, (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)>, | |
74b04a01 | 515 | /// This field keeps track of move errors that are to be reported for given move indices. |
0bf4aa26 XL |
516 | /// |
517 | /// There are situations where many errors can be reported for a single move out (see #53807) | |
518 | /// and we want only the best of those errors. | |
519 | /// | |
520 | /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the | |
521 | /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the | |
522 | /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once | |
523 | /// all move errors have been reported, any diagnostics in this map are added to the buffer | |
524 | /// to be emitted. | |
525 | /// | |
526 | /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary | |
527 | /// when errors in the map are being re-added to the error buffer so that errors with the | |
528 | /// same primary span come out in a consistent order. | |
74b04a01 | 529 | move_error_reported: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'cx>)>, |
0bf4aa26 | 530 | /// This field keeps track of errors reported in the checking of uninitialized variables, |
8faf50e0 | 531 | /// so that we don't report seemingly duplicate errors. |
74b04a01 | 532 | uninitialized_error_reported: FxHashSet<PlaceRef<'tcx>>, |
8faf50e0 XL |
533 | /// Errors to be reported buffer |
534 | errors_buffer: Vec<Diagnostic>, | |
83c7162d XL |
535 | /// This field keeps track of all the local variables that are declared mut and are mutated. |
536 | /// Used for the warning issued by an unused mutable local variable. | |
537 | used_mut: FxHashSet<Local>, | |
538 | /// If the function we're checking is a closure, then we'll need to report back the list of | |
539 | /// mutable upvars that have been used. This field keeps track of them. | |
540 | used_mut_upvars: SmallVec<[Field; 8]>, | |
dfeec247 | 541 | /// Region inference context. This contains the results from region inference and lets us e.g. |
ff7c6d11 | 542 | /// find out which CFG points are contained in each borrow region. |
dfeec247 | 543 | regioncx: Rc<RegionInferenceContext<'tcx>>, |
83c7162d XL |
544 | |
545 | /// The set of borrows extracted from the MIR | |
546 | borrow_set: Rc<BorrowSet<'tcx>>, | |
547 | ||
548 | /// Dominators for MIR | |
549 | dominators: Dominators<BasicBlock>, | |
48663c56 XL |
550 | |
551 | /// Information about upvars not necessarily preserved in types or MIR | |
552 | upvars: Vec<Upvar>, | |
60c5eb7d XL |
553 | |
554 | /// Names of local (user) variables (extracted from `var_debug_info`). | |
f9f354fc | 555 | local_names: IndexVec<Local, Option<Symbol>>, |
dfeec247 XL |
556 | |
557 | /// Record the region names generated for each region in the given | |
558 | /// MIR def so that we can reuse them later in help/error messages. | |
559 | region_names: RefCell<FxHashMap<RegionVid, RegionName>>, | |
560 | ||
561 | /// The counter for generating new region names. | |
562 | next_region_name: RefCell<usize>, | |
74b04a01 XL |
563 | |
564 | /// Results of Polonius analysis. | |
565 | polonius_output: Option<Rc<PoloniusOutput>>, | |
ff7c6d11 XL |
566 | } |
567 | ||
568 | // Check that: | |
569 | // 1. assignments are always made to mutable locations (FIXME: does that still really go here?) | |
570 | // 2. loans made in overlapping scopes do not conflict | |
571 | // 3. assignments do not affect things loaned out as immutable | |
572 | // 4. moves do not affect things loaned out in any way | |
ba9703b0 | 573 | impl<'cx, 'tcx> dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> { |
dc9dc135 | 574 | type FlowState = Flows<'cx, 'tcx>; |
ff7c6d11 | 575 | |
f9f354fc | 576 | fn visit_statement_before_primary_effect( |
ff7c6d11 | 577 | &mut self, |
74b04a01 | 578 | flow_state: &Flows<'cx, 'tcx>, |
416331ca | 579 | stmt: &'cx Statement<'tcx>, |
74b04a01 | 580 | location: Location, |
ff7c6d11 | 581 | ) { |
74b04a01 | 582 | debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state); |
ff7c6d11 XL |
583 | let span = stmt.source_info.span; |
584 | ||
585 | self.check_activations(location, span, flow_state); | |
586 | ||
ba9703b0 XL |
587 | match &stmt.kind { |
588 | StatementKind::Assign(box (lhs, ref rhs)) => { | |
dfeec247 | 589 | self.consume_rvalue(location, (rhs, span), flow_state); |
2c00a5a8 | 590 | |
ba9703b0 | 591 | self.mutate_place(location, (*lhs, span), Shallow(None), JustWrite, flow_state); |
ff7c6d11 | 592 | } |
e1599b0c | 593 | StatementKind::FakeRead(_, box ref place) => { |
0bf4aa26 XL |
594 | // Read for match doesn't access any memory and is used to |
595 | // assert that a place is safe and live. So we don't have to | |
596 | // do any checks here. | |
597 | // | |
598 | // FIXME: Remove check that the place is initialized. This is | |
599 | // needed for now because matches don't have never patterns yet. | |
600 | // So this is the only place we prevent | |
601 | // let x: !; | |
602 | // match x {}; | |
603 | // from compiling. | |
604 | self.check_if_path_or_subpath_is_moved( | |
48663c56 | 605 | location, |
0bf4aa26 | 606 | InitializationRequiringAction::Use, |
416331ca | 607 | (place.as_ref(), span), |
8faf50e0 XL |
608 | flow_state, |
609 | ); | |
94b46f34 | 610 | } |
ba9703b0 XL |
611 | StatementKind::SetDiscriminant { place, variant_index: _ } => { |
612 | self.mutate_place(location, (**place, span), Shallow(None), JustWrite, flow_state); | |
ff7c6d11 | 613 | } |
ba9703b0 | 614 | StatementKind::LlvmInlineAsm(ref asm) => { |
532ac7d7 | 615 | for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) { |
ff7c6d11 XL |
616 | if o.is_indirect { |
617 | // FIXME(eddyb) indirect inline asm outputs should | |
532ac7d7 | 618 | // be encoded through MIR place derefs instead. |
ff7c6d11 | 619 | self.access_place( |
48663c56 | 620 | location, |
ba9703b0 | 621 | (*output, o.span), |
ff7c6d11 XL |
622 | (Deep, Read(ReadKind::Copy)), |
623 | LocalMutationIsAllowed::No, | |
624 | flow_state, | |
625 | ); | |
83c7162d | 626 | self.check_if_path_or_subpath_is_moved( |
48663c56 | 627 | location, |
ff7c6d11 | 628 | InitializationRequiringAction::Use, |
416331ca | 629 | (output.as_ref(), o.span), |
ff7c6d11 XL |
630 | flow_state, |
631 | ); | |
632 | } else { | |
633 | self.mutate_place( | |
48663c56 | 634 | location, |
ba9703b0 | 635 | (*output, o.span), |
ff7c6d11 XL |
636 | if o.is_rw { Deep } else { Shallow(None) }, |
637 | if o.is_rw { WriteAndRead } else { JustWrite }, | |
638 | flow_state, | |
639 | ); | |
640 | } | |
641 | } | |
532ac7d7 | 642 | for (_, input) in asm.inputs.iter() { |
48663c56 | 643 | self.consume_operand(location, (input, span), flow_state); |
ff7c6d11 XL |
644 | } |
645 | } | |
8faf50e0 | 646 | StatementKind::Nop |
3dfed10e | 647 | | StatementKind::Coverage(..) |
b7449926 | 648 | | StatementKind::AscribeUserType(..) |
a1dfa0c6 | 649 | | StatementKind::Retag { .. } |
8faf50e0 | 650 | | StatementKind::StorageLive(..) => { |
a1dfa0c6 | 651 | // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant |
ff7c6d11 XL |
652 | // to borrow check. |
653 | } | |
ff7c6d11 XL |
654 | StatementKind::StorageDead(local) => { |
655 | self.access_place( | |
48663c56 | 656 | location, |
ba9703b0 | 657 | (Place::from(*local), span), |
ff7c6d11 XL |
658 | (Shallow(None), Write(WriteKind::StorageDeadOrDrop)), |
659 | LocalMutationIsAllowed::Yes, | |
660 | flow_state, | |
661 | ); | |
662 | } | |
663 | } | |
664 | } | |
665 | ||
f9f354fc | 666 | fn visit_terminator_before_primary_effect( |
ff7c6d11 | 667 | &mut self, |
74b04a01 | 668 | flow_state: &Flows<'cx, 'tcx>, |
416331ca | 669 | term: &'cx Terminator<'tcx>, |
74b04a01 | 670 | loc: Location, |
ff7c6d11 | 671 | ) { |
74b04a01 | 672 | debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state); |
ff7c6d11 XL |
673 | let span = term.source_info.span; |
674 | ||
74b04a01 | 675 | self.check_activations(loc, span, flow_state); |
ff7c6d11 XL |
676 | |
677 | match term.kind { | |
dfeec247 | 678 | TerminatorKind::SwitchInt { ref discr, switch_ty: _, values: _, targets: _ } => { |
48663c56 | 679 | self.consume_operand(loc, (discr, span), flow_state); |
ff7c6d11 | 680 | } |
f035d41b | 681 | TerminatorKind::Drop { place: ref drop_place, target: _, unwind: _ } => { |
e74abb32 | 682 | let tcx = self.infcx.tcx; |
0531ce1d XL |
683 | |
684 | // Compute the type with accurate region information. | |
f9f354fc | 685 | let drop_place_ty = drop_place.ty(self.body, self.infcx.tcx); |
0531ce1d XL |
686 | |
687 | // Erase the regions. | |
532ac7d7 | 688 | let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty; |
0531ce1d | 689 | |
e74abb32 | 690 | // "Lift" into the tcx -- once regions are erased, this type should be in the |
0531ce1d XL |
691 | // global arenas; this "lift" operation basically just asserts that is true, but |
692 | // that is useful later. | |
e74abb32 | 693 | tcx.lift(&drop_place_ty).unwrap(); |
0531ce1d | 694 | |
dfeec247 XL |
695 | debug!( |
696 | "visit_terminator_drop \ | |
697 | loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}", | |
698 | loc, term, drop_place, drop_place_ty, span | |
699 | ); | |
b7449926 | 700 | |
0bf4aa26 | 701 | self.access_place( |
48663c56 | 702 | loc, |
ba9703b0 | 703 | (*drop_place, span), |
0bf4aa26 XL |
704 | (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)), |
705 | LocalMutationIsAllowed::Yes, | |
706 | flow_state, | |
707 | ); | |
ff7c6d11 XL |
708 | } |
709 | TerminatorKind::DropAndReplace { | |
f035d41b | 710 | place: drop_place, |
ff7c6d11 XL |
711 | value: ref new_value, |
712 | target: _, | |
713 | unwind: _, | |
714 | } => { | |
dfeec247 XL |
715 | self.mutate_place(loc, (drop_place, span), Deep, JustWrite, flow_state); |
716 | self.consume_operand(loc, (new_value, span), flow_state); | |
ff7c6d11 XL |
717 | } |
718 | TerminatorKind::Call { | |
719 | ref func, | |
720 | ref args, | |
721 | ref destination, | |
722 | cleanup: _, | |
0bf4aa26 | 723 | from_hir_call: _, |
f035d41b | 724 | fn_span: _, |
ff7c6d11 | 725 | } => { |
48663c56 | 726 | self.consume_operand(loc, (func, span), flow_state); |
ff7c6d11 | 727 | for arg in args { |
dfeec247 | 728 | self.consume_operand(loc, (arg, span), flow_state); |
ff7c6d11 | 729 | } |
ba9703b0 | 730 | if let Some((dest, _ /*bb*/)) = *destination { |
dfeec247 | 731 | self.mutate_place(loc, (dest, span), Deep, JustWrite, flow_state); |
ff7c6d11 XL |
732 | } |
733 | } | |
dfeec247 | 734 | TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => { |
48663c56 | 735 | self.consume_operand(loc, (cond, span), flow_state); |
ba9703b0 | 736 | use rustc_middle::mir::AssertKind; |
74b04a01 | 737 | if let AssertKind::BoundsCheck { ref len, ref index } = *msg { |
48663c56 XL |
738 | self.consume_operand(loc, (len, span), flow_state); |
739 | self.consume_operand(loc, (index, span), flow_state); | |
ff7c6d11 XL |
740 | } |
741 | } | |
742 | ||
ba9703b0 | 743 | TerminatorKind::Yield { ref value, resume: _, resume_arg, drop: _ } => { |
48663c56 | 744 | self.consume_operand(loc, (value, span), flow_state); |
74b04a01 XL |
745 | self.mutate_place(loc, (resume_arg, span), Deep, JustWrite, flow_state); |
746 | } | |
2c00a5a8 | 747 | |
f9f354fc XL |
748 | TerminatorKind::InlineAsm { |
749 | template: _, | |
750 | ref operands, | |
751 | options: _, | |
752 | line_spans: _, | |
753 | destination: _, | |
754 | } => { | |
755 | for op in operands { | |
756 | match *op { | |
757 | InlineAsmOperand::In { reg: _, ref value } | |
758 | | InlineAsmOperand::Const { ref value } => { | |
759 | self.consume_operand(loc, (value, span), flow_state); | |
760 | } | |
761 | InlineAsmOperand::Out { reg: _, late: _, place, .. } => { | |
762 | if let Some(place) = place { | |
763 | self.mutate_place( | |
764 | loc, | |
765 | (place, span), | |
766 | Shallow(None), | |
767 | JustWrite, | |
768 | flow_state, | |
769 | ); | |
770 | } | |
771 | } | |
772 | InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => { | |
773 | self.consume_operand(loc, (in_value, span), flow_state); | |
774 | if let Some(out_place) = out_place { | |
775 | self.mutate_place( | |
776 | loc, | |
777 | (out_place, span), | |
778 | Shallow(None), | |
779 | JustWrite, | |
780 | flow_state, | |
781 | ); | |
782 | } | |
783 | } | |
784 | InlineAsmOperand::SymFn { value: _ } | |
f035d41b | 785 | | InlineAsmOperand::SymStatic { def_id: _ } => {} |
f9f354fc XL |
786 | } |
787 | } | |
788 | } | |
789 | ||
74b04a01 XL |
790 | TerminatorKind::Goto { target: _ } |
791 | | TerminatorKind::Abort | |
792 | | TerminatorKind::Unreachable | |
793 | | TerminatorKind::Resume | |
794 | | TerminatorKind::Return | |
795 | | TerminatorKind::GeneratorDrop | |
f035d41b | 796 | | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ } |
74b04a01 XL |
797 | | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => { |
798 | // no data used, thus irrelevant to borrowck | |
799 | } | |
800 | } | |
801 | } | |
802 | ||
f9f354fc | 803 | fn visit_terminator_after_primary_effect( |
74b04a01 XL |
804 | &mut self, |
805 | flow_state: &Flows<'cx, 'tcx>, | |
806 | term: &'cx Terminator<'tcx>, | |
807 | loc: Location, | |
808 | ) { | |
809 | let span = term.source_info.span; | |
810 | ||
811 | match term.kind { | |
812 | TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => { | |
2c00a5a8 XL |
813 | if self.movable_generator { |
814 | // Look for any active borrows to locals | |
83c7162d | 815 | let borrow_set = self.borrow_set.clone(); |
74b04a01 XL |
816 | for i in flow_state.borrows.iter() { |
817 | let borrow = &borrow_set[i]; | |
818 | self.check_for_local_borrow(borrow, span); | |
819 | } | |
2c00a5a8 | 820 | } |
ff7c6d11 XL |
821 | } |
822 | ||
823 | TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => { | |
824 | // Returning from the function implicitly kills storage for all locals and statics. | |
825 | // Often, the storage will already have been killed by an explicit | |
826 | // StorageDead, but we don't always emit those (notably on unwind paths), | |
827 | // so this "extra check" serves as a kind of backup. | |
83c7162d | 828 | let borrow_set = self.borrow_set.clone(); |
74b04a01 XL |
829 | for i in flow_state.borrows.iter() { |
830 | let borrow = &borrow_set[i]; | |
831 | self.check_for_invalidation_at_exit(loc, borrow, span); | |
832 | } | |
ff7c6d11 | 833 | } |
74b04a01 XL |
834 | |
835 | TerminatorKind::Abort | |
836 | | TerminatorKind::Assert { .. } | |
837 | | TerminatorKind::Call { .. } | |
838 | | TerminatorKind::Drop { .. } | |
839 | | TerminatorKind::DropAndReplace { .. } | |
f035d41b | 840 | | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ } |
74b04a01 XL |
841 | | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } |
842 | | TerminatorKind::Goto { .. } | |
843 | | TerminatorKind::SwitchInt { .. } | |
f9f354fc XL |
844 | | TerminatorKind::Unreachable |
845 | | TerminatorKind::InlineAsm { .. } => {} | |
ff7c6d11 XL |
846 | } |
847 | } | |
848 | } | |
849 | ||
850 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
851 | enum MutateMode { | |
852 | JustWrite, | |
853 | WriteAndRead, | |
854 | } | |
855 | ||
0bf4aa26 | 856 | use self::AccessDepth::{Deep, Shallow}; |
dfeec247 | 857 | use self::ReadOrWrite::{Activation, Read, Reservation, Write}; |
ff7c6d11 XL |
858 | |
859 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
860 | enum ArtificialField { | |
ff7c6d11 | 861 | ArrayLength, |
0bf4aa26 | 862 | ShallowBorrow, |
ff7c6d11 XL |
863 | } |
864 | ||
865 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
0bf4aa26 | 866 | enum AccessDepth { |
ff7c6d11 | 867 | /// From the RFC: "A *shallow* access means that the immediate |
2c00a5a8 | 868 | /// fields reached at P are accessed, but references or pointers |
ff7c6d11 XL |
869 | /// found within are not dereferenced. Right now, the only access |
870 | /// that is shallow is an assignment like `x = ...;`, which would | |
871 | /// be a *shallow write* of `x`." | |
872 | Shallow(Option<ArtificialField>), | |
873 | ||
874 | /// From the RFC: "A *deep* access means that all data reachable | |
875 | /// through the given place may be invalidated or accesses by | |
876 | /// this action." | |
877 | Deep, | |
0bf4aa26 XL |
878 | |
879 | /// Access is Deep only when there is a Drop implementation that | |
880 | /// can reach the data behind the reference. | |
881 | Drop, | |
ff7c6d11 XL |
882 | } |
883 | ||
884 | /// Kind of access to a value: read or write | |
885 | /// (For informational purposes only) | |
886 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
887 | enum ReadOrWrite { | |
888 | /// From the RFC: "A *read* means that the existing data may be | |
889 | /// read, but will not be changed." | |
890 | Read(ReadKind), | |
891 | ||
892 | /// From the RFC: "A *write* means that the data may be mutated to | |
893 | /// new values or otherwise invalidated (for example, it could be | |
894 | /// de-initialized, as in a move operation). | |
895 | Write(WriteKind), | |
896 | ||
897 | /// For two-phase borrows, we distinguish a reservation (which is treated | |
898 | /// like a Read) from an activation (which is treated like a write), and | |
899 | /// each of those is furthermore distinguished from Reads/Writes above. | |
900 | Reservation(WriteKind), | |
901 | Activation(WriteKind, BorrowIndex), | |
902 | } | |
903 | ||
904 | /// Kind of read access to a value | |
905 | /// (For informational purposes only) | |
906 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
907 | enum ReadKind { | |
908 | Borrow(BorrowKind), | |
909 | Copy, | |
910 | } | |
911 | ||
912 | /// Kind of write access to a value | |
913 | /// (For informational purposes only) | |
914 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
915 | enum WriteKind { | |
916 | StorageDeadOrDrop, | |
917 | MutableBorrow(BorrowKind), | |
918 | Mutate, | |
919 | Move, | |
920 | } | |
921 | ||
922 | /// When checking permissions for a place access, this flag is used to indicate that an immutable | |
923 | /// local place can be mutated. | |
9fa01778 XL |
924 | // |
925 | // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications: | |
926 | // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`. | |
927 | // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and | |
928 | // `is_declared_mutable()`. | |
929 | // - Take flow state into consideration in `is_assignable()` for local variables. | |
ff7c6d11 XL |
930 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] |
931 | enum LocalMutationIsAllowed { | |
932 | Yes, | |
933 | /// We want use of immutable upvars to cause a "write to immutable upvar" | |
934 | /// error, not an "reassignment" error. | |
935 | ExceptUpvars, | |
936 | No, | |
937 | } | |
938 | ||
0bf4aa26 | 939 | #[derive(Copy, Clone, Debug)] |
ff7c6d11 XL |
940 | enum InitializationRequiringAction { |
941 | Update, | |
942 | Borrow, | |
0bf4aa26 | 943 | MatchOn, |
ff7c6d11 XL |
944 | Use, |
945 | Assignment, | |
0bf4aa26 | 946 | PartialAssignment, |
ff7c6d11 XL |
947 | } |
948 | ||
74b04a01 XL |
949 | struct RootPlace<'tcx> { |
950 | place_local: Local, | |
951 | place_projection: &'tcx [PlaceElem<'tcx>], | |
83c7162d XL |
952 | is_local_mutation_allowed: LocalMutationIsAllowed, |
953 | } | |
954 | ||
ff7c6d11 XL |
955 | impl InitializationRequiringAction { |
956 | fn as_noun(self) -> &'static str { | |
957 | match self { | |
958 | InitializationRequiringAction::Update => "update", | |
959 | InitializationRequiringAction::Borrow => "borrow", | |
0bf4aa26 | 960 | InitializationRequiringAction::MatchOn => "use", // no good noun |
ff7c6d11 XL |
961 | InitializationRequiringAction::Use => "use", |
962 | InitializationRequiringAction::Assignment => "assign", | |
0bf4aa26 | 963 | InitializationRequiringAction::PartialAssignment => "assign to part", |
ff7c6d11 XL |
964 | } |
965 | } | |
966 | ||
967 | fn as_verb_in_past_tense(self) -> &'static str { | |
968 | match self { | |
969 | InitializationRequiringAction::Update => "updated", | |
970 | InitializationRequiringAction::Borrow => "borrowed", | |
0bf4aa26 | 971 | InitializationRequiringAction::MatchOn => "matched on", |
ff7c6d11 XL |
972 | InitializationRequiringAction::Use => "used", |
973 | InitializationRequiringAction::Assignment => "assigned", | |
0bf4aa26 | 974 | InitializationRequiringAction::PartialAssignment => "partially assigned", |
b7449926 XL |
975 | } |
976 | } | |
977 | } | |
978 | ||
dc9dc135 | 979 | impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { |
74b04a01 | 980 | fn body(&self) -> &'cx Body<'tcx> { |
f9f354fc | 981 | self.body |
74b04a01 XL |
982 | } |
983 | ||
ff7c6d11 XL |
984 | /// Checks an access to the given place to see if it is allowed. Examines the set of borrows |
985 | /// that are in scope, as well as which paths have been initialized, to ensure that (a) the | |
986 | /// place is initialized and (b) it is not borrowed in some way that would prevent this | |
987 | /// access. | |
988 | /// | |
9fa01778 | 989 | /// Returns `true` if an error is reported. |
ff7c6d11 XL |
990 | fn access_place( |
991 | &mut self, | |
48663c56 | 992 | location: Location, |
ba9703b0 | 993 | place_span: (Place<'tcx>, Span), |
0bf4aa26 | 994 | kind: (AccessDepth, ReadOrWrite), |
ff7c6d11 | 995 | is_local_mutation_allowed: LocalMutationIsAllowed, |
dc9dc135 | 996 | flow_state: &Flows<'cx, 'tcx>, |
b7449926 | 997 | ) { |
ff7c6d11 XL |
998 | let (sd, rw) = kind; |
999 | ||
1000 | if let Activation(_, borrow_index) = rw { | |
1001 | if self.reservation_error_reported.contains(&place_span.0) { | |
0531ce1d XL |
1002 | debug!( |
1003 | "skipping access_place for activation of invalid reservation \ | |
1004 | place: {:?} borrow_index: {:?}", | |
1005 | place_span.0, borrow_index | |
1006 | ); | |
b7449926 | 1007 | return; |
ff7c6d11 XL |
1008 | } |
1009 | } | |
1010 | ||
b7449926 XL |
1011 | // Check is_empty() first because it's the common case, and doing that |
1012 | // way we avoid the clone() call. | |
dfeec247 | 1013 | if !self.access_place_error_reported.is_empty() |
ba9703b0 | 1014 | && self.access_place_error_reported.contains(&(place_span.0, place_span.1)) |
0531ce1d XL |
1015 | { |
1016 | debug!( | |
1017 | "access_place: suppressing error place_span=`{:?}` kind=`{:?}`", | |
1018 | place_span, kind | |
1019 | ); | |
b7449926 | 1020 | return; |
2c00a5a8 XL |
1021 | } |
1022 | ||
dfeec247 XL |
1023 | let mutability_error = self.check_access_permissions( |
1024 | place_span, | |
1025 | rw, | |
1026 | is_local_mutation_allowed, | |
1027 | flow_state, | |
1028 | location, | |
1029 | ); | |
ff7c6d11 | 1030 | let conflict_error = |
48663c56 | 1031 | self.check_access_for_conflict(location, place_span, sd, rw, flow_state); |
ff7c6d11 | 1032 | |
532ac7d7 | 1033 | if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) { |
60c5eb7d | 1034 | // Suppress this warning when there's an error being emitted for the |
532ac7d7 XL |
1035 | // same borrow: fixing the error is likely to fix the warning. |
1036 | self.reservation_warnings.remove(&borrow_idx); | |
1037 | } | |
1038 | ||
2c00a5a8 | 1039 | if conflict_error || mutability_error { |
dfeec247 | 1040 | debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind); |
532ac7d7 | 1041 | |
ba9703b0 | 1042 | self.access_place_error_reported.insert((place_span.0, place_span.1)); |
2c00a5a8 | 1043 | } |
ff7c6d11 XL |
1044 | } |
1045 | ||
1046 | fn check_access_for_conflict( | |
1047 | &mut self, | |
48663c56 | 1048 | location: Location, |
ba9703b0 | 1049 | place_span: (Place<'tcx>, Span), |
0bf4aa26 | 1050 | sd: AccessDepth, |
ff7c6d11 | 1051 | rw: ReadOrWrite, |
dc9dc135 | 1052 | flow_state: &Flows<'cx, 'tcx>, |
ff7c6d11 | 1053 | ) -> bool { |
83c7162d | 1054 | debug!( |
48663c56 XL |
1055 | "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})", |
1056 | location, place_span, sd, rw, | |
83c7162d XL |
1057 | ); |
1058 | ||
ff7c6d11 | 1059 | let mut error_reported = false; |
0bf4aa26 | 1060 | let tcx = self.infcx.tcx; |
dc9dc135 | 1061 | let body = self.body; |
94b46f34 | 1062 | let borrow_set = self.borrow_set.clone(); |
74b04a01 XL |
1063 | |
1064 | // Use polonius output if it has been enabled. | |
1065 | let polonius_output = self.polonius_output.clone(); | |
1066 | let borrows_in_scope = if let Some(polonius) = &polonius_output { | |
1067 | let location = self.location_table.start_index(location); | |
1068 | Either::Left(polonius.errors_at(location).iter().copied()) | |
1069 | } else { | |
1070 | Either::Right(flow_state.borrows.iter()) | |
1071 | }; | |
1072 | ||
94b46f34 XL |
1073 | each_borrow_involving_path( |
1074 | self, | |
1075 | tcx, | |
dc9dc135 | 1076 | body, |
48663c56 | 1077 | location, |
ff7c6d11 | 1078 | (sd, place_span.0), |
94b46f34 | 1079 | &borrow_set, |
74b04a01 | 1080 | borrows_in_scope, |
8faf50e0 | 1081 | |this, borrow_index, borrow| match (rw, borrow.kind) { |
ff7c6d11 XL |
1082 | // Obviously an activation is compatible with its own |
1083 | // reservation (or even prior activating uses of same | |
1084 | // borrow); so don't check if they interfere. | |
1085 | // | |
1086 | // NOTE: *reservations* do conflict with themselves; | |
1087 | // thus aren't injecting unsoundenss w/ this check.) | |
83c7162d | 1088 | (Activation(_, activating), _) if activating == borrow_index => { |
ff7c6d11 XL |
1089 | debug!( |
1090 | "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \ | |
83c7162d | 1091 | skipping {:?} b/c activation of same borrow_index", |
ff7c6d11 XL |
1092 | place_span, |
1093 | sd, | |
1094 | rw, | |
83c7162d | 1095 | (borrow_index, borrow), |
ff7c6d11 XL |
1096 | ); |
1097 | Control::Continue | |
1098 | } | |
1099 | ||
ba9703b0 XL |
1100 | (Read(_), BorrowKind::Shared | BorrowKind::Shallow) |
1101 | | ( | |
1102 | Read(ReadKind::Borrow(BorrowKind::Shallow)), | |
1103 | BorrowKind::Unique | BorrowKind::Mut { .. }, | |
1104 | ) => Control::Continue, | |
0bf4aa26 XL |
1105 | |
1106 | (Write(WriteKind::Move), BorrowKind::Shallow) => { | |
1107 | // Handled by initialization checks. | |
ff7c6d11 XL |
1108 | Control::Continue |
1109 | } | |
1110 | ||
ba9703b0 | 1111 | (Read(kind), BorrowKind::Unique | BorrowKind::Mut { .. }) => { |
ff7c6d11 | 1112 | // Reading from mere reservations of mutable-borrows is OK. |
48663c56 XL |
1113 | if !is_active(&this.dominators, borrow, location) { |
1114 | assert!(allow_two_phase_borrow(borrow.kind)); | |
ff7c6d11 XL |
1115 | return Control::Continue; |
1116 | } | |
1117 | ||
0bf4aa26 | 1118 | error_reported = true; |
ff7c6d11 | 1119 | match kind { |
dfeec247 | 1120 | ReadKind::Copy => { |
48663c56 | 1121 | this.report_use_while_mutably_borrowed(location, place_span, borrow) |
532ac7d7 | 1122 | .buffer(&mut this.errors_buffer); |
ff7c6d11 XL |
1123 | } |
1124 | ReadKind::Borrow(bk) => { | |
48663c56 | 1125 | this.report_conflicting_borrow(location, place_span, bk, borrow) |
532ac7d7 | 1126 | .buffer(&mut this.errors_buffer); |
ff7c6d11 XL |
1127 | } |
1128 | } | |
1129 | Control::Break | |
1130 | } | |
1131 | ||
ba9703b0 XL |
1132 | ( |
1133 | Reservation(WriteKind::MutableBorrow(bk)), | |
1134 | BorrowKind::Shallow | BorrowKind::Shared, | |
3dfed10e XL |
1135 | ) if { tcx.migrate_borrowck() && this.borrow_set.contains(&location) } => { |
1136 | let bi = this.borrow_set.get_index_of(&location).unwrap(); | |
532ac7d7 XL |
1137 | debug!( |
1138 | "recording invalid reservation of place: {:?} with \ | |
1139 | borrow index {:?} as warning", | |
dfeec247 | 1140 | place_span.0, bi, |
532ac7d7 XL |
1141 | ); |
1142 | // rust-lang/rust#56254 - This was previously permitted on | |
1143 | // the 2018 edition so we emit it as a warning. We buffer | |
1144 | // these sepately so that we only emit a warning if borrow | |
1145 | // checking was otherwise successful. | |
dfeec247 | 1146 | this.reservation_warnings |
ba9703b0 | 1147 | .insert(bi, (place_span.0, place_span.1, location, bk, borrow.clone())); |
532ac7d7 XL |
1148 | |
1149 | // Don't suppress actual errors. | |
1150 | Control::Continue | |
1151 | } | |
1152 | ||
ba9703b0 | 1153 | (Reservation(kind) | Activation(kind, _) | Write(kind), _) => { |
ff7c6d11 | 1154 | match rw { |
532ac7d7 | 1155 | Reservation(..) => { |
ff7c6d11 XL |
1156 | debug!( |
1157 | "recording invalid reservation of \ | |
1158 | place: {:?}", | |
1159 | place_span.0 | |
1160 | ); | |
ba9703b0 | 1161 | this.reservation_error_reported.insert(place_span.0); |
0531ce1d | 1162 | } |
ff7c6d11 XL |
1163 | Activation(_, activating) => { |
1164 | debug!( | |
1165 | "observing check_place for activation of \ | |
1166 | borrow_index: {:?}", | |
1167 | activating | |
1168 | ); | |
0531ce1d XL |
1169 | } |
1170 | Read(..) | Write(..) => {} | |
ff7c6d11 XL |
1171 | } |
1172 | ||
0bf4aa26 | 1173 | error_reported = true; |
ff7c6d11 XL |
1174 | match kind { |
1175 | WriteKind::MutableBorrow(bk) => { | |
48663c56 | 1176 | this.report_conflicting_borrow(location, place_span, bk, borrow) |
532ac7d7 | 1177 | .buffer(&mut this.errors_buffer); |
ff7c6d11 | 1178 | } |
dfeec247 XL |
1179 | WriteKind::StorageDeadOrDrop => this |
1180 | .report_borrowed_value_does_not_live_long_enough( | |
48663c56 | 1181 | location, |
ff7c6d11 | 1182 | borrow, |
94b46f34 | 1183 | place_span, |
dfeec247 XL |
1184 | Some(kind), |
1185 | ), | |
ff7c6d11 | 1186 | WriteKind::Mutate => { |
48663c56 | 1187 | this.report_illegal_mutation_of_borrowed(location, place_span, borrow) |
ff7c6d11 XL |
1188 | } |
1189 | WriteKind::Move => { | |
48663c56 | 1190 | this.report_move_out_while_borrowed(location, place_span, borrow) |
ff7c6d11 XL |
1191 | } |
1192 | } | |
1193 | Control::Break | |
1194 | } | |
1195 | }, | |
1196 | ); | |
1197 | ||
1198 | error_reported | |
1199 | } | |
1200 | ||
1201 | fn mutate_place( | |
1202 | &mut self, | |
48663c56 | 1203 | location: Location, |
ba9703b0 | 1204 | place_span: (Place<'tcx>, Span), |
0bf4aa26 | 1205 | kind: AccessDepth, |
ff7c6d11 | 1206 | mode: MutateMode, |
dc9dc135 | 1207 | flow_state: &Flows<'cx, 'tcx>, |
ff7c6d11 XL |
1208 | ) { |
1209 | // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd. | |
1210 | match mode { | |
1211 | MutateMode::WriteAndRead => { | |
83c7162d | 1212 | self.check_if_path_or_subpath_is_moved( |
48663c56 | 1213 | location, |
ff7c6d11 | 1214 | InitializationRequiringAction::Update, |
416331ca | 1215 | (place_span.0.as_ref(), place_span.1), |
ff7c6d11 XL |
1216 | flow_state, |
1217 | ); | |
1218 | } | |
1219 | MutateMode::JustWrite => { | |
48663c56 | 1220 | self.check_if_assigned_path_is_moved(location, place_span, flow_state); |
ff7c6d11 XL |
1221 | } |
1222 | } | |
1223 | ||
b7449926 XL |
1224 | // Special case: you can assign a immutable local variable |
1225 | // (e.g., `x = ...`) so long as it has never been initialized | |
1226 | // before (at this point in the flow). | |
e74abb32 XL |
1227 | if let Some(local) = place_span.0.as_local() { |
1228 | if let Mutability::Not = self.body.local_decls[local].mutability { | |
b7449926 XL |
1229 | // check for reassignments to immutable local variables |
1230 | self.check_if_reassignment_to_immutable_state( | |
dfeec247 | 1231 | location, local, place_span, flow_state, |
b7449926 XL |
1232 | ); |
1233 | return; | |
1234 | } | |
1235 | } | |
1236 | ||
1237 | // Otherwise, use the normal access permission rules. | |
1238 | self.access_place( | |
48663c56 | 1239 | location, |
ff7c6d11 XL |
1240 | place_span, |
1241 | (kind, Write(WriteKind::Mutate)), | |
b7449926 | 1242 | LocalMutationIsAllowed::No, |
ff7c6d11 XL |
1243 | flow_state, |
1244 | ); | |
ff7c6d11 XL |
1245 | } |
1246 | ||
1247 | fn consume_rvalue( | |
1248 | &mut self, | |
48663c56 | 1249 | location: Location, |
416331ca | 1250 | (rvalue, span): (&'cx Rvalue<'tcx>, Span), |
dc9dc135 | 1251 | flow_state: &Flows<'cx, 'tcx>, |
ff7c6d11 XL |
1252 | ) { |
1253 | match *rvalue { | |
ba9703b0 | 1254 | Rvalue::Ref(_ /*rgn*/, bk, place) => { |
ff7c6d11 | 1255 | let access_kind = match bk { |
0bf4aa26 XL |
1256 | BorrowKind::Shallow => { |
1257 | (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk))) | |
dfeec247 | 1258 | } |
ff7c6d11 | 1259 | BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))), |
2c00a5a8 | 1260 | BorrowKind::Unique | BorrowKind::Mut { .. } => { |
ff7c6d11 | 1261 | let wk = WriteKind::MutableBorrow(bk); |
48663c56 | 1262 | if allow_two_phase_borrow(bk) { |
ff7c6d11 XL |
1263 | (Deep, Reservation(wk)) |
1264 | } else { | |
1265 | (Deep, Write(wk)) | |
1266 | } | |
1267 | } | |
1268 | }; | |
1269 | ||
1270 | self.access_place( | |
48663c56 | 1271 | location, |
ff7c6d11 XL |
1272 | (place, span), |
1273 | access_kind, | |
1274 | LocalMutationIsAllowed::No, | |
1275 | flow_state, | |
1276 | ); | |
1277 | ||
0bf4aa26 XL |
1278 | let action = if bk == BorrowKind::Shallow { |
1279 | InitializationRequiringAction::MatchOn | |
1280 | } else { | |
1281 | InitializationRequiringAction::Borrow | |
1282 | }; | |
1283 | ||
83c7162d | 1284 | self.check_if_path_or_subpath_is_moved( |
48663c56 | 1285 | location, |
0bf4aa26 | 1286 | action, |
416331ca | 1287 | (place.as_ref(), span), |
ff7c6d11 XL |
1288 | flow_state, |
1289 | ); | |
1290 | } | |
1291 | ||
ba9703b0 | 1292 | Rvalue::AddressOf(mutability, place) => { |
dfeec247 XL |
1293 | let access_kind = match mutability { |
1294 | Mutability::Mut => ( | |
1295 | Deep, | |
1296 | Write(WriteKind::MutableBorrow(BorrowKind::Mut { | |
1297 | allow_two_phase_borrow: false, | |
1298 | })), | |
1299 | ), | |
1300 | Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))), | |
1301 | }; | |
1302 | ||
1303 | self.access_place( | |
1304 | location, | |
1305 | (place, span), | |
1306 | access_kind, | |
1307 | LocalMutationIsAllowed::No, | |
1308 | flow_state, | |
1309 | ); | |
1310 | ||
1311 | self.check_if_path_or_subpath_is_moved( | |
1312 | location, | |
1313 | InitializationRequiringAction::Borrow, | |
1314 | (place.as_ref(), span), | |
1315 | flow_state, | |
1316 | ); | |
1317 | } | |
1318 | ||
f9f354fc XL |
1319 | Rvalue::ThreadLocalRef(_) => {} |
1320 | ||
ff7c6d11 XL |
1321 | Rvalue::Use(ref operand) |
1322 | | Rvalue::Repeat(ref operand, _) | |
1323 | | Rvalue::UnaryOp(_ /*un_op*/, ref operand) | |
1324 | | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => { | |
48663c56 | 1325 | self.consume_operand(location, (operand, span), flow_state) |
ff7c6d11 XL |
1326 | } |
1327 | ||
ba9703b0 | 1328 | Rvalue::Len(place) | Rvalue::Discriminant(place) => { |
ff7c6d11 | 1329 | let af = match *rvalue { |
0731742a XL |
1330 | Rvalue::Len(..) => Some(ArtificialField::ArrayLength), |
1331 | Rvalue::Discriminant(..) => None, | |
ff7c6d11 XL |
1332 | _ => unreachable!(), |
1333 | }; | |
1334 | self.access_place( | |
48663c56 | 1335 | location, |
ff7c6d11 | 1336 | (place, span), |
0731742a | 1337 | (Shallow(af), Read(ReadKind::Copy)), |
ff7c6d11 XL |
1338 | LocalMutationIsAllowed::No, |
1339 | flow_state, | |
1340 | ); | |
83c7162d | 1341 | self.check_if_path_or_subpath_is_moved( |
48663c56 | 1342 | location, |
ff7c6d11 | 1343 | InitializationRequiringAction::Use, |
416331ca | 1344 | (place.as_ref(), span), |
ff7c6d11 XL |
1345 | flow_state, |
1346 | ); | |
1347 | } | |
1348 | ||
1349 | Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2) | |
1350 | | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => { | |
48663c56 XL |
1351 | self.consume_operand(location, (operand1, span), flow_state); |
1352 | self.consume_operand(location, (operand2, span), flow_state); | |
ff7c6d11 XL |
1353 | } |
1354 | ||
1355 | Rvalue::NullaryOp(_op, _ty) => { | |
1356 | // nullary ops take no dynamic input; no borrowck effect. | |
1357 | // | |
1358 | // FIXME: is above actually true? Do we want to track | |
1359 | // the fact that uninitialized data can be created via | |
1360 | // `NullOp::Box`? | |
1361 | } | |
1362 | ||
83c7162d XL |
1363 | Rvalue::Aggregate(ref aggregate_kind, ref operands) => { |
1364 | // We need to report back the list of mutable upvars that were | |
1365 | // moved into the closure and subsequently used by the closure, | |
1366 | // in order to populate our used_mut set. | |
8faf50e0 | 1367 | match **aggregate_kind { |
dfeec247 XL |
1368 | AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => { |
1369 | let BorrowCheckResult { used_mut_upvars, .. } = | |
f9f354fc | 1370 | self.infcx.tcx.mir_borrowck(def_id.expect_local()); |
8faf50e0 XL |
1371 | debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars); |
1372 | for field in used_mut_upvars { | |
48663c56 | 1373 | self.propagate_closure_used_mut_upvar(&operands[field.index()]); |
83c7162d XL |
1374 | } |
1375 | } | |
8faf50e0 XL |
1376 | AggregateKind::Adt(..) |
1377 | | AggregateKind::Array(..) | |
1378 | | AggregateKind::Tuple { .. } => (), | |
83c7162d XL |
1379 | } |
1380 | ||
1381 | for operand in operands { | |
48663c56 XL |
1382 | self.consume_operand(location, (operand, span), flow_state); |
1383 | } | |
1384 | } | |
1385 | } | |
1386 | } | |
1387 | ||
1388 | fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) { | |
ba9703b0 | 1389 | let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| { |
e1599b0c | 1390 | if !place.projection.is_empty() { |
416331ca XL |
1391 | if let Some(field) = this.is_upvar_field_projection(place.as_ref()) { |
1392 | this.used_mut_upvars.push(field); | |
48663c56 | 1393 | } |
dfeec247 XL |
1394 | } else { |
1395 | this.used_mut.insert(place.local); | |
48663c56 XL |
1396 | } |
1397 | }; | |
1398 | ||
1399 | // This relies on the current way that by-value | |
1400 | // captures of a closure are copied/moved directly | |
1401 | // when generating MIR. | |
1402 | match *operand { | |
ba9703b0 | 1403 | Operand::Move(place) | Operand::Copy(place) => { |
e74abb32 | 1404 | match place.as_local() { |
60c5eb7d | 1405 | Some(local) if !self.body.local_decls[local].is_user_variable() => { |
e74abb32 XL |
1406 | if self.body.local_decls[local].ty.is_mutable_ptr() { |
1407 | // The variable will be marked as mutable by the borrow. | |
1408 | return; | |
1409 | } | |
1410 | // This is an edge case where we have a `move` closure | |
1411 | // inside a non-move closure, and the inner closure | |
1412 | // contains a mutation: | |
1413 | // | |
1414 | // let mut i = 0; | |
1415 | // || { move || { i += 1; }; }; | |
1416 | // | |
1417 | // In this case our usual strategy of assuming that the | |
1418 | // variable will be captured by mutable reference is | |
1419 | // wrong, since `i` can be copied into the inner | |
1420 | // closure from a shared reference. | |
1421 | // | |
1422 | // As such we have to search for the local that this | |
1423 | // capture comes from and mark it as being used as mut. | |
1424 | ||
1425 | let temp_mpi = self.move_data.rev_lookup.find_local(local); | |
1426 | let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] { | |
1427 | &self.move_data.inits[init_index] | |
1428 | } else { | |
1429 | bug!("temporary should be initialized exactly once") | |
1430 | }; | |
48663c56 | 1431 | |
e74abb32 XL |
1432 | let loc = match init.location { |
1433 | InitLocation::Statement(stmt) => stmt, | |
1434 | _ => bug!("temporary initialized in arguments"), | |
1435 | }; | |
48663c56 | 1436 | |
60c5eb7d XL |
1437 | let body = self.body; |
1438 | let bbd = &body[loc.block]; | |
e74abb32 XL |
1439 | let stmt = &bbd.statements[loc.statement_index]; |
1440 | debug!("temporary assigned in: stmt={:?}", stmt); | |
48663c56 | 1441 | |
ba9703b0 | 1442 | if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, source))) = stmt.kind |
e74abb32 XL |
1443 | { |
1444 | propagate_closure_used_mut_place(self, source); | |
1445 | } else { | |
1446 | bug!( | |
1447 | "closures should only capture user variables \ | |
1448 | or references to user variables" | |
1449 | ); | |
1450 | } | |
1451 | } | |
1452 | _ => propagate_closure_used_mut_place(self, place), | |
83c7162d XL |
1453 | } |
1454 | } | |
48663c56 | 1455 | Operand::Constant(..) => {} |
ff7c6d11 XL |
1456 | } |
1457 | } | |
1458 | ||
1459 | fn consume_operand( | |
1460 | &mut self, | |
48663c56 | 1461 | location: Location, |
416331ca | 1462 | (operand, span): (&'cx Operand<'tcx>, Span), |
dc9dc135 | 1463 | flow_state: &Flows<'cx, 'tcx>, |
ff7c6d11 XL |
1464 | ) { |
1465 | match *operand { | |
ba9703b0 | 1466 | Operand::Copy(place) => { |
ff7c6d11 XL |
1467 | // copy of place: check if this is "copy of frozen path" |
1468 | // (FIXME: see check_loans.rs) | |
1469 | self.access_place( | |
48663c56 | 1470 | location, |
ff7c6d11 XL |
1471 | (place, span), |
1472 | (Deep, Read(ReadKind::Copy)), | |
1473 | LocalMutationIsAllowed::No, | |
1474 | flow_state, | |
1475 | ); | |
1476 | ||
1477 | // Finally, check if path was already moved. | |
83c7162d | 1478 | self.check_if_path_or_subpath_is_moved( |
48663c56 | 1479 | location, |
ff7c6d11 | 1480 | InitializationRequiringAction::Use, |
416331ca | 1481 | (place.as_ref(), span), |
ff7c6d11 XL |
1482 | flow_state, |
1483 | ); | |
1484 | } | |
ba9703b0 | 1485 | Operand::Move(place) => { |
ff7c6d11 XL |
1486 | // move of place: check if this is move of already borrowed path |
1487 | self.access_place( | |
48663c56 | 1488 | location, |
ff7c6d11 XL |
1489 | (place, span), |
1490 | (Deep, Write(WriteKind::Move)), | |
1491 | LocalMutationIsAllowed::Yes, | |
1492 | flow_state, | |
1493 | ); | |
1494 | ||
1495 | // Finally, check if path was already moved. | |
83c7162d | 1496 | self.check_if_path_or_subpath_is_moved( |
48663c56 | 1497 | location, |
ff7c6d11 | 1498 | InitializationRequiringAction::Use, |
416331ca | 1499 | (place.as_ref(), span), |
ff7c6d11 XL |
1500 | flow_state, |
1501 | ); | |
1502 | } | |
1503 | Operand::Constant(_) => {} | |
1504 | } | |
1505 | } | |
1506 | ||
0bf4aa26 | 1507 | /// Checks whether a borrow of this place is invalidated when the function |
ff7c6d11 XL |
1508 | /// exits |
1509 | fn check_for_invalidation_at_exit( | |
1510 | &mut self, | |
48663c56 | 1511 | location: Location, |
ff7c6d11 XL |
1512 | borrow: &BorrowData<'tcx>, |
1513 | span: Span, | |
ff7c6d11 XL |
1514 | ) { |
1515 | debug!("check_for_invalidation_at_exit({:?})", borrow); | |
ba9703b0 | 1516 | let place = borrow.borrowed_place; |
74b04a01 | 1517 | let mut root_place = PlaceRef { local: place.local, projection: &[] }; |
ff7c6d11 XL |
1518 | |
1519 | // FIXME(nll-rfc#40): do more precise destructor tracking here. For now | |
1520 | // we just know that all locals are dropped at function exit (otherwise | |
1521 | // we'll have a memory leak) and assume that all statics have a destructor. | |
1522 | // | |
1523 | // FIXME: allow thread-locals to borrow other thread locals? | |
416331ca | 1524 | |
dfeec247 | 1525 | let (might_be_alive, will_be_dropped) = |
74b04a01 | 1526 | if self.body.local_decls[root_place.local].is_ref_to_thread_local() { |
dfeec247 XL |
1527 | // Thread-locals might be dropped after the function exits |
1528 | // We have to dereference the outer reference because | |
1529 | // borrows don't conflict behind shared references. | |
74b04a01 | 1530 | root_place.projection = DEREF_PROJECTION; |
dfeec247 XL |
1531 | (true, true) |
1532 | } else { | |
1533 | (false, self.locals_are_invalidated_at_exit) | |
1534 | }; | |
ff7c6d11 XL |
1535 | |
1536 | if !will_be_dropped { | |
dfeec247 | 1537 | debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place); |
ff7c6d11 XL |
1538 | return; |
1539 | } | |
1540 | ||
ff7c6d11 XL |
1541 | let sd = if might_be_alive { Deep } else { Shallow(None) }; |
1542 | ||
0bf4aa26 XL |
1543 | if places_conflict::borrow_conflicts_with_place( |
1544 | self.infcx.tcx, | |
60c5eb7d | 1545 | &self.body, |
0bf4aa26 XL |
1546 | place, |
1547 | borrow.kind, | |
1548 | root_place, | |
0731742a XL |
1549 | sd, |
1550 | places_conflict::PlaceConflictBias::Overlap, | |
0bf4aa26 | 1551 | ) { |
ff7c6d11 XL |
1552 | debug!("check_for_invalidation_at_exit({:?}): INVALID", place); |
1553 | // FIXME: should be talking about the region lifetime instead | |
1554 | // of just a span here. | |
0bf4aa26 | 1555 | let span = self.infcx.tcx.sess.source_map().end_point(span); |
ff7c6d11 | 1556 | self.report_borrowed_value_does_not_live_long_enough( |
48663c56 | 1557 | location, |
ff7c6d11 | 1558 | borrow, |
94b46f34 XL |
1559 | (place, span), |
1560 | None, | |
ff7c6d11 XL |
1561 | ) |
1562 | } | |
1563 | } | |
1564 | ||
2c00a5a8 | 1565 | /// Reports an error if this is a borrow of local data. |
dfeec247 | 1566 | /// This is called for all Yield expressions on movable generators |
0531ce1d | 1567 | fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) { |
2c00a5a8 XL |
1568 | debug!("check_for_local_borrow({:?})", borrow); |
1569 | ||
ba9703b0 | 1570 | if borrow_of_local_data(borrow.borrowed_place) { |
416331ca | 1571 | let err = self.cannot_borrow_across_generator_yield( |
dfeec247 XL |
1572 | self.retrieve_borrow_spans(borrow).var_or_use(), |
1573 | yield_span, | |
1574 | ); | |
8faf50e0 XL |
1575 | |
1576 | err.buffer(&mut self.errors_buffer); | |
2c00a5a8 XL |
1577 | } |
1578 | } | |
1579 | ||
dc9dc135 | 1580 | fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) { |
ff7c6d11 XL |
1581 | // Two-phase borrow support: For each activation that is newly |
1582 | // generated at this statement, check if it interferes with | |
1583 | // another borrow. | |
83c7162d XL |
1584 | let borrow_set = self.borrow_set.clone(); |
1585 | for &borrow_index in borrow_set.activations_at_location(location) { | |
1586 | let borrow = &borrow_set[borrow_index]; | |
1587 | ||
1588 | // only mutable borrows should be 2-phase | |
1589 | assert!(match borrow.kind { | |
0bf4aa26 | 1590 | BorrowKind::Shared | BorrowKind::Shallow => false, |
83c7162d XL |
1591 | BorrowKind::Unique | BorrowKind::Mut { .. } => true, |
1592 | }); | |
1593 | ||
1594 | self.access_place( | |
48663c56 | 1595 | location, |
ba9703b0 | 1596 | (borrow.borrowed_place, span), |
dfeec247 | 1597 | (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)), |
83c7162d XL |
1598 | LocalMutationIsAllowed::No, |
1599 | flow_state, | |
1600 | ); | |
1601 | // We do not need to call `check_if_path_or_subpath_is_moved` | |
1602 | // again, as we already called it when we made the | |
1603 | // initial reservation. | |
1604 | } | |
ff7c6d11 | 1605 | } |
ff7c6d11 | 1606 | |
ff7c6d11 XL |
1607 | fn check_if_reassignment_to_immutable_state( |
1608 | &mut self, | |
48663c56 | 1609 | location: Location, |
b7449926 | 1610 | local: Local, |
ba9703b0 | 1611 | place_span: (Place<'tcx>, Span), |
dc9dc135 | 1612 | flow_state: &Flows<'cx, 'tcx>, |
ff7c6d11 | 1613 | ) { |
b7449926 XL |
1614 | debug!("check_if_reassignment_to_immutable_state({:?})", local); |
1615 | ||
1616 | // Check if any of the initializiations of `local` have happened yet: | |
0bf4aa26 | 1617 | if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) { |
b7449926 XL |
1618 | // And, if so, report an error. |
1619 | let init = &self.move_data.inits[init_index]; | |
dc9dc135 | 1620 | let span = init.span(&self.body); |
dfeec247 | 1621 | self.report_illegal_reassignment(location, place_span, span, place_span.0); |
ff7c6d11 XL |
1622 | } |
1623 | } | |
1624 | ||
83c7162d | 1625 | fn check_if_full_path_is_moved( |
ff7c6d11 | 1626 | &mut self, |
48663c56 | 1627 | location: Location, |
ff7c6d11 | 1628 | desired_action: InitializationRequiringAction, |
74b04a01 | 1629 | place_span: (PlaceRef<'tcx>, Span), |
dc9dc135 | 1630 | flow_state: &Flows<'cx, 'tcx>, |
ff7c6d11 | 1631 | ) { |
ff7c6d11 | 1632 | let maybe_uninits = &flow_state.uninits; |
ff7c6d11 XL |
1633 | |
1634 | // Bad scenarios: | |
1635 | // | |
1636 | // 1. Move of `a.b.c`, use of `a.b.c` | |
1637 | // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`) | |
83c7162d | 1638 | // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with |
ff7c6d11 XL |
1639 | // partial initialization support, one might have `a.x` |
1640 | // initialized but not `a.b`. | |
1641 | // | |
1642 | // OK scenarios: | |
1643 | // | |
83c7162d XL |
1644 | // 4. Move of `a.b.c`, use of `a.b.d` |
1645 | // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b` | |
1646 | // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b` | |
ff7c6d11 | 1647 | // must have been initialized for the use to be sound. |
83c7162d | 1648 | // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d` |
ff7c6d11 XL |
1649 | |
1650 | // The dataflow tracks shallow prefixes distinctly (that is, | |
1651 | // field-accesses on P distinctly from P itself), in order to | |
1652 | // track substructure initialization separately from the whole | |
1653 | // structure. | |
1654 | // | |
1655 | // E.g., when looking at (*a.b.c).d, if the closest prefix for | |
1656 | // which we have a MovePath is `a.b`, then that means that the | |
1657 | // initialization state of `a.b` is all we need to inspect to | |
1658 | // know if `a.b.c` is valid (and from that we infer that the | |
1659 | // dereference and `.d` access is also valid, since we assume | |
1660 | // `a.b.c` is assigned a reference to a initialized and | |
1661 | // well-formed record structure.) | |
1662 | ||
1663 | // Therefore, if we seek out the *closest* prefix for which we | |
1664 | // have a MovePath, that should capture the initialization | |
1665 | // state for the place scenario. | |
1666 | // | |
83c7162d | 1667 | // This code covers scenarios 1, 2, and 3. |
ff7c6d11 | 1668 | |
b7449926 | 1669 | debug!("check_if_full_path_is_moved place: {:?}", place_span.0); |
dfeec247 XL |
1670 | let (prefix, mpi) = self.move_path_closest_to(place_span.0); |
1671 | if maybe_uninits.contains(mpi) { | |
1672 | self.report_use_of_moved_or_uninitialized( | |
1673 | location, | |
1674 | desired_action, | |
1675 | (prefix, place_span.0, place_span.1), | |
1676 | mpi, | |
1677 | ); | |
1678 | } // Only query longest prefix with a MovePath, not further | |
1679 | // ancestors; dataflow recurs on children when parents | |
1680 | // move (to support partial (re)inits). | |
1681 | // | |
1682 | // (I.e., querying parents breaks scenario 7; but may want | |
1683 | // to do such a query based on partial-init feature-gate.) | |
83c7162d XL |
1684 | } |
1685 | ||
60c5eb7d XL |
1686 | /// Subslices correspond to multiple move paths, so we iterate through the |
1687 | /// elements of the base array. For each element we check | |
1688 | /// | |
1689 | /// * Does this element overlap with our slice. | |
1690 | /// * Is any part of it uninitialized. | |
1691 | fn check_if_subslice_element_is_moved( | |
1692 | &mut self, | |
1693 | location: Location, | |
1694 | desired_action: InitializationRequiringAction, | |
74b04a01 XL |
1695 | place_span: (PlaceRef<'tcx>, Span), |
1696 | maybe_uninits: &BitSet<MovePathIndex>, | |
60c5eb7d XL |
1697 | from: u32, |
1698 | to: u32, | |
1699 | ) { | |
1700 | if let Some(mpi) = self.move_path_for_place(place_span.0) { | |
74b04a01 XL |
1701 | let move_paths = &self.move_data.move_paths; |
1702 | ||
1703 | let root_path = &move_paths[mpi]; | |
1704 | for (child_mpi, child_move_path) in root_path.children(move_paths) { | |
1705 | let last_proj = child_move_path.place.projection.last().unwrap(); | |
60c5eb7d XL |
1706 | if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj { |
1707 | debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`."); | |
1708 | ||
1709 | if (from..to).contains(offset) { | |
74b04a01 XL |
1710 | let uninit_child = |
1711 | self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| { | |
1712 | maybe_uninits.contains(mpi) | |
1713 | }); | |
1714 | ||
1715 | if let Some(uninit_child) = uninit_child { | |
60c5eb7d XL |
1716 | self.report_use_of_moved_or_uninitialized( |
1717 | location, | |
1718 | desired_action, | |
1719 | (place_span.0, place_span.0, place_span.1), | |
1720 | uninit_child, | |
1721 | ); | |
1722 | return; // don't bother finding other problems. | |
1723 | } | |
1724 | } | |
1725 | } | |
60c5eb7d XL |
1726 | } |
1727 | } | |
1728 | } | |
1729 | ||
83c7162d XL |
1730 | fn check_if_path_or_subpath_is_moved( |
1731 | &mut self, | |
48663c56 | 1732 | location: Location, |
83c7162d | 1733 | desired_action: InitializationRequiringAction, |
74b04a01 | 1734 | place_span: (PlaceRef<'tcx>, Span), |
dc9dc135 | 1735 | flow_state: &Flows<'cx, 'tcx>, |
83c7162d | 1736 | ) { |
83c7162d | 1737 | let maybe_uninits = &flow_state.uninits; |
83c7162d XL |
1738 | |
1739 | // Bad scenarios: | |
1740 | // | |
1741 | // 1. Move of `a.b.c`, use of `a` or `a.b` | |
1742 | // partial initialization support, one might have `a.x` | |
1743 | // initialized but not `a.b`. | |
1744 | // 2. All bad scenarios from `check_if_full_path_is_moved` | |
1745 | // | |
1746 | // OK scenarios: | |
1747 | // | |
1748 | // 3. Move of `a.b.c`, use of `a.b.d` | |
1749 | // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b` | |
1750 | // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b` | |
1751 | // must have been initialized for the use to be sound. | |
1752 | // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d` | |
1753 | ||
48663c56 | 1754 | self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state); |
ff7c6d11 | 1755 | |
dfeec247 XL |
1756 | if let [base_proj @ .., ProjectionElem::Subslice { from, to, from_end: false }] = |
1757 | place_span.0.projection | |
1758 | { | |
1759 | let place_ty = | |
1760 | Place::ty_from(place_span.0.local, base_proj, self.body(), self.infcx.tcx); | |
60c5eb7d | 1761 | if let ty::Array(..) = place_ty.ty.kind { |
dfeec247 | 1762 | let array_place = PlaceRef { local: place_span.0.local, projection: base_proj }; |
60c5eb7d XL |
1763 | self.check_if_subslice_element_is_moved( |
1764 | location, | |
1765 | desired_action, | |
1766 | (array_place, place_span.1), | |
1767 | maybe_uninits, | |
1768 | *from, | |
1769 | *to, | |
1770 | ); | |
1771 | return; | |
1772 | } | |
1773 | } | |
1774 | ||
ff7c6d11 XL |
1775 | // A move of any shallow suffix of `place` also interferes |
1776 | // with an attempt to use `place`. This is scenario 3 above. | |
1777 | // | |
1778 | // (Distinct from handling of scenarios 1+2+4 above because | |
1779 | // `place` does not interfere with suffixes of its prefixes, | |
0731742a | 1780 | // e.g., `a.b.c` does not interfere with `a.b.d`) |
83c7162d XL |
1781 | // |
1782 | // This code covers scenario 1. | |
ff7c6d11 | 1783 | |
b7449926 XL |
1784 | debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0); |
1785 | if let Some(mpi) = self.move_path_for_place(place_span.0) { | |
74b04a01 XL |
1786 | let uninit_mpi = self |
1787 | .move_data | |
1788 | .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi)); | |
1789 | ||
1790 | if let Some(uninit_mpi) = uninit_mpi { | |
ff7c6d11 | 1791 | self.report_use_of_moved_or_uninitialized( |
48663c56 | 1792 | location, |
ff7c6d11 | 1793 | desired_action, |
0bf4aa26 | 1794 | (place_span.0, place_span.0, place_span.1), |
74b04a01 | 1795 | uninit_mpi, |
ff7c6d11 XL |
1796 | ); |
1797 | return; // don't bother finding other problems. | |
1798 | } | |
1799 | } | |
1800 | } | |
1801 | ||
1802 | /// Currently MoveData does not store entries for all places in | |
1803 | /// the input MIR. For example it will currently filter out | |
1804 | /// places that are Copy; thus we do not track places of shared | |
1805 | /// reference type. This routine will walk up a place along its | |
1806 | /// prefixes, searching for a foundational place that *is* | |
1807 | /// tracked in the MoveData. | |
1808 | /// | |
1809 | /// An Err result includes a tag indicated why the search failed. | |
0531ce1d | 1810 | /// Currently this can only occur if the place is built off of a |
ff7c6d11 | 1811 | /// static variable, as we do not track those in the MoveData. |
74b04a01 | 1812 | fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) { |
60c5eb7d | 1813 | match self.move_data.rev_lookup.find(place) { |
dfeec247 XL |
1814 | LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => { |
1815 | (self.move_data.move_paths[mpi].place.as_ref(), mpi) | |
1816 | } | |
1817 | LookupResult::Parent(None) => panic!("should have move path for every Local"), | |
ff7c6d11 XL |
1818 | } |
1819 | } | |
1820 | ||
74b04a01 | 1821 | fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> { |
ff7c6d11 XL |
1822 | // If returns None, then there is no move path corresponding |
1823 | // to a direct owner of `place` (which means there is nothing | |
1824 | // that borrowck tracks for its analysis). | |
1825 | ||
1826 | match self.move_data.rev_lookup.find(place) { | |
1827 | LookupResult::Parent(_) => None, | |
1828 | LookupResult::Exact(mpi) => Some(mpi), | |
1829 | } | |
1830 | } | |
1831 | ||
1832 | fn check_if_assigned_path_is_moved( | |
1833 | &mut self, | |
48663c56 | 1834 | location: Location, |
ba9703b0 | 1835 | (place, span): (Place<'tcx>, Span), |
dc9dc135 | 1836 | flow_state: &Flows<'cx, 'tcx>, |
ff7c6d11 | 1837 | ) { |
83c7162d | 1838 | debug!("check_if_assigned_path_is_moved place: {:?}", place); |
416331ca XL |
1839 | |
1840 | // None case => assigning to `x` does not require `x` be initialized. | |
e74abb32 | 1841 | let mut cursor = &*place.projection.as_ref(); |
e1599b0c XL |
1842 | while let [proj_base @ .., elem] = cursor { |
1843 | cursor = proj_base; | |
1844 | ||
1845 | match elem { | |
416331ca XL |
1846 | ProjectionElem::Index(_/*operand*/) | |
1847 | ProjectionElem::ConstantIndex { .. } | | |
1848 | // assigning to P[i] requires P to be valid. | |
1849 | ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) => | |
1850 | // assigning to (P->variant) is okay if assigning to `P` is okay | |
1851 | // | |
1852 | // FIXME: is this true even if P is a adt with a dtor? | |
1853 | { } | |
1854 | ||
1855 | // assigning to (*P) requires P to be initialized | |
1856 | ProjectionElem::Deref => { | |
1857 | self.check_if_full_path_is_moved( | |
1858 | location, InitializationRequiringAction::Use, | |
1859 | (PlaceRef { | |
74b04a01 | 1860 | local: place.local, |
e1599b0c | 1861 | projection: proj_base, |
416331ca XL |
1862 | }, span), flow_state); |
1863 | // (base initialized; no need to | |
1864 | // recur further) | |
ff7c6d11 XL |
1865 | break; |
1866 | } | |
416331ca XL |
1867 | |
1868 | ProjectionElem::Subslice { .. } => { | |
1869 | panic!("we don't allow assignments to subslices, location: {:?}", | |
1870 | location); | |
1871 | } | |
1872 | ||
1873 | ProjectionElem::Field(..) => { | |
1874 | // if type of `P` has a dtor, then | |
1875 | // assigning to `P.f` requires `P` itself | |
1876 | // be already initialized | |
1877 | let tcx = self.infcx.tcx; | |
74b04a01 | 1878 | let base_ty = Place::ty_from(place.local, proj_base, self.body(), tcx).ty; |
e74abb32 | 1879 | match base_ty.kind { |
416331ca XL |
1880 | ty::Adt(def, _) if def.has_dtor(tcx) => { |
1881 | self.check_if_path_or_subpath_is_moved( | |
1882 | location, InitializationRequiringAction::Assignment, | |
1883 | (PlaceRef { | |
74b04a01 | 1884 | local: place.local, |
e1599b0c | 1885 | projection: proj_base, |
416331ca XL |
1886 | }, span), flow_state); |
1887 | ||
83c7162d XL |
1888 | // (base initialized; no need to |
1889 | // recur further) | |
1890 | break; | |
1891 | } | |
1892 | ||
416331ca XL |
1893 | // Once `let s; s.x = V; read(s.x);`, |
1894 | // is allowed, remove this match arm. | |
1895 | ty::Adt(..) | ty::Tuple(..) => { | |
1896 | check_parent_of_field(self, location, PlaceRef { | |
74b04a01 | 1897 | local: place.local, |
e1599b0c | 1898 | projection: proj_base, |
416331ca XL |
1899 | }, span, flow_state); |
1900 | ||
dfeec247 XL |
1901 | // rust-lang/rust#21232, #54499, #54986: during period where we reject |
1902 | // partial initialization, do not complain about unnecessary `mut` on | |
1903 | // an attempt to do a partial initialization. | |
1904 | self.used_mut.insert(place.local); | |
ff7c6d11 | 1905 | } |
ff7c6d11 | 1906 | |
416331ca XL |
1907 | _ => {} |
1908 | } | |
ff7c6d11 XL |
1909 | } |
1910 | } | |
1911 | } | |
ff7c6d11 | 1912 | |
dc9dc135 XL |
1913 | fn check_parent_of_field<'cx, 'tcx>( |
1914 | this: &mut MirBorrowckCtxt<'cx, 'tcx>, | |
48663c56 | 1915 | location: Location, |
74b04a01 | 1916 | base: PlaceRef<'tcx>, |
a1dfa0c6 | 1917 | span: Span, |
dc9dc135 | 1918 | flow_state: &Flows<'cx, 'tcx>, |
a1dfa0c6 | 1919 | ) { |
0bf4aa26 XL |
1920 | // rust-lang/rust#21232: Until Rust allows reads from the |
1921 | // initialized parts of partially initialized structs, we | |
1922 | // will, starting with the 2018 edition, reject attempts | |
1923 | // to write to structs that are not fully initialized. | |
1924 | // | |
1925 | // In other words, *until* we allow this: | |
1926 | // | |
1927 | // 1. `let mut s; s.x = Val; read(s.x);` | |
1928 | // | |
1929 | // we will for now disallow this: | |
1930 | // | |
1931 | // 2. `let mut s; s.x = Val;` | |
1932 | // | |
1933 | // and also this: | |
1934 | // | |
1935 | // 3. `let mut s = ...; drop(s); s.x=Val;` | |
1936 | // | |
1937 | // This does not use check_if_path_or_subpath_is_moved, | |
1938 | // because we want to *allow* reinitializations of fields: | |
0731742a | 1939 | // e.g., want to allow |
0bf4aa26 XL |
1940 | // |
1941 | // `let mut s = ...; drop(s.x); s.x=Val;` | |
1942 | // | |
1943 | // This does not use check_if_full_path_is_moved on | |
1944 | // `base`, because that would report an error about the | |
1945 | // `base` as a whole, but in this scenario we *really* | |
1946 | // want to report an error about the actual thing that was | |
1947 | // moved, which may be some prefix of `base`. | |
1948 | ||
1949 | // Shallow so that we'll stop at any dereference; we'll | |
1950 | // report errors about issues with such bases elsewhere. | |
1951 | let maybe_uninits = &flow_state.uninits; | |
1952 | ||
1953 | // Find the shortest uninitialized prefix you can reach | |
1954 | // without going over a Deref. | |
1955 | let mut shortest_uninit_seen = None; | |
1956 | for prefix in this.prefixes(base, PrefixSet::Shallow) { | |
1957 | let mpi = match this.move_path_for_place(prefix) { | |
dfeec247 XL |
1958 | Some(mpi) => mpi, |
1959 | None => continue, | |
0bf4aa26 XL |
1960 | }; |
1961 | ||
1962 | if maybe_uninits.contains(mpi) { | |
dfeec247 XL |
1963 | debug!( |
1964 | "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}", | |
1965 | shortest_uninit_seen, | |
1966 | Some((prefix, mpi)) | |
1967 | ); | |
0bf4aa26 XL |
1968 | shortest_uninit_seen = Some((prefix, mpi)); |
1969 | } else { | |
1970 | debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi)); | |
1971 | } | |
1972 | } | |
1973 | ||
1974 | if let Some((prefix, mpi)) = shortest_uninit_seen { | |
a1dfa0c6 XL |
1975 | // Check for a reassignment into a uninitialized field of a union (for example, |
1976 | // after a move out). In this case, do not report a error here. There is an | |
1977 | // exception, if this is the first assignment into the union (that is, there is | |
1978 | // no move out from an earlier location) then this is an attempt at initialization | |
1979 | // of the union - we should error in that case. | |
1980 | let tcx = this.infcx.tcx; | |
416331ca | 1981 | if let ty::Adt(def, _) = |
dfeec247 | 1982 | Place::ty_from(base.local, base.projection, this.body(), tcx).ty.kind |
416331ca | 1983 | { |
a1dfa0c6 XL |
1984 | if def.is_union() { |
1985 | if this.move_data.path_map[mpi].iter().any(|moi| { | |
dfeec247 | 1986 | this.move_data.moves[*moi].source.is_predecessor_of(location, this.body) |
a1dfa0c6 XL |
1987 | }) { |
1988 | return; | |
1989 | } | |
1990 | } | |
1991 | } | |
1992 | ||
0bf4aa26 | 1993 | this.report_use_of_moved_or_uninitialized( |
48663c56 | 1994 | location, |
0bf4aa26 XL |
1995 | InitializationRequiringAction::PartialAssignment, |
1996 | (prefix, base, span), | |
1997 | mpi, | |
1998 | ); | |
1999 | } | |
2000 | } | |
2001 | } | |
8faf50e0 | 2002 | |
9fa01778 | 2003 | /// Checks the permissions for the given place and read or write kind |
ff7c6d11 | 2004 | /// |
9fa01778 | 2005 | /// Returns `true` if an error is reported. |
ff7c6d11 | 2006 | fn check_access_permissions( |
83c7162d | 2007 | &mut self, |
ba9703b0 | 2008 | (place, span): (Place<'tcx>, Span), |
ff7c6d11 XL |
2009 | kind: ReadOrWrite, |
2010 | is_local_mutation_allowed: LocalMutationIsAllowed, | |
dc9dc135 | 2011 | flow_state: &Flows<'cx, 'tcx>, |
8faf50e0 | 2012 | location: Location, |
ff7c6d11 XL |
2013 | ) -> bool { |
2014 | debug!( | |
0bf4aa26 | 2015 | "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})", |
0531ce1d | 2016 | place, kind, is_local_mutation_allowed |
ff7c6d11 | 2017 | ); |
94b46f34 | 2018 | |
94b46f34 XL |
2019 | let error_access; |
2020 | let the_place_err; | |
2021 | ||
ff7c6d11 | 2022 | match kind { |
ba9703b0 XL |
2023 | Reservation(WriteKind::MutableBorrow( |
2024 | borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }), | |
2025 | )) | |
2026 | | Write(WriteKind::MutableBorrow( | |
2027 | borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }), | |
2028 | )) => { | |
94b46f34 XL |
2029 | let is_local_mutation_allowed = match borrow_kind { |
2030 | BorrowKind::Unique => LocalMutationIsAllowed::Yes, | |
2031 | BorrowKind::Mut { .. } => is_local_mutation_allowed, | |
0bf4aa26 | 2032 | BorrowKind::Shared | BorrowKind::Shallow => unreachable!(), |
94b46f34 | 2033 | }; |
416331ca | 2034 | match self.is_mutable(place.as_ref(), is_local_mutation_allowed) { |
94b46f34 XL |
2035 | Ok(root_place) => { |
2036 | self.add_used_mut(root_place, flow_state); | |
2037 | return false; | |
2038 | } | |
83c7162d | 2039 | Err(place_err) => { |
94b46f34 XL |
2040 | error_access = AccessKind::MutableBorrow; |
2041 | the_place_err = place_err; | |
ff7c6d11 XL |
2042 | } |
2043 | } | |
83c7162d | 2044 | } |
ff7c6d11 | 2045 | Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => { |
416331ca | 2046 | match self.is_mutable(place.as_ref(), is_local_mutation_allowed) { |
94b46f34 XL |
2047 | Ok(root_place) => { |
2048 | self.add_used_mut(root_place, flow_state); | |
2049 | return false; | |
2050 | } | |
83c7162d | 2051 | Err(place_err) => { |
94b46f34 XL |
2052 | error_access = AccessKind::Mutate; |
2053 | the_place_err = place_err; | |
ff7c6d11 | 2054 | } |
ff7c6d11 XL |
2055 | } |
2056 | } | |
94b46f34 | 2057 | |
ba9703b0 XL |
2058 | Reservation( |
2059 | WriteKind::Move | |
2060 | | WriteKind::StorageDeadOrDrop | |
2061 | | WriteKind::MutableBorrow(BorrowKind::Shared) | |
2062 | | WriteKind::MutableBorrow(BorrowKind::Shallow), | |
2063 | ) | |
2064 | | Write( | |
2065 | WriteKind::Move | |
2066 | | WriteKind::StorageDeadOrDrop | |
2067 | | WriteKind::MutableBorrow(BorrowKind::Shared) | |
2068 | | WriteKind::MutableBorrow(BorrowKind::Shallow), | |
2069 | ) => { | |
e74abb32 | 2070 | if let (Err(_), true) = ( |
416331ca | 2071 | self.is_mutable(place.as_ref(), is_local_mutation_allowed), |
dfeec247 | 2072 | self.errors_buffer.is_empty(), |
a1dfa0c6 | 2073 | ) { |
e74abb32 XL |
2074 | // rust-lang/rust#46908: In pure NLL mode this code path should be |
2075 | // unreachable, but we use `delay_span_bug` because we can hit this when | |
2076 | // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug` | |
2077 | // enabled. We don't want to ICE for that case, as other errors will have | |
2078 | // been emitted (#52262). | |
dfeec247 XL |
2079 | self.infcx.tcx.sess.delay_span_bug( |
2080 | span, | |
2081 | &format!( | |
2082 | "Accessing `{:?}` with the kind `{:?}` shouldn't be possible", | |
2083 | place, kind, | |
2084 | ), | |
2085 | ); | |
ff7c6d11 | 2086 | } |
94b46f34 XL |
2087 | return false; |
2088 | } | |
2089 | Activation(..) => { | |
2090 | // permission checks are done at Reservation point. | |
2091 | return false; | |
ff7c6d11 | 2092 | } |
ba9703b0 XL |
2093 | Read( |
2094 | ReadKind::Borrow( | |
2095 | BorrowKind::Unique | |
2096 | | BorrowKind::Mut { .. } | |
2097 | | BorrowKind::Shared | |
2098 | | BorrowKind::Shallow, | |
2099 | ) | |
2100 | | ReadKind::Copy, | |
2101 | ) => { | |
94b46f34 XL |
2102 | // Access authorized |
2103 | return false; | |
2104 | } | |
ff7c6d11 XL |
2105 | } |
2106 | ||
60c5eb7d XL |
2107 | // rust-lang/rust#21232, #54986: during period where we reject |
2108 | // partial initialization, do not complain about mutability | |
2109 | // errors except for actual mutation (as opposed to an attempt | |
2110 | // to do a partial initialization). | |
dfeec247 XL |
2111 | let previously_initialized = |
2112 | self.is_local_ever_initialized(place.local, flow_state).is_some(); | |
60c5eb7d | 2113 | |
94b46f34 | 2114 | // at this point, we have set up the error reporting state. |
60c5eb7d | 2115 | if previously_initialized { |
dfeec247 | 2116 | self.report_mutability_error(place, span, the_place_err, error_access, location); |
0bf4aa26 XL |
2117 | true |
2118 | } else { | |
2119 | false | |
60c5eb7d | 2120 | } |
0bf4aa26 XL |
2121 | } |
2122 | ||
dc9dc135 XL |
2123 | fn is_local_ever_initialized( |
2124 | &self, | |
2125 | local: Local, | |
2126 | flow_state: &Flows<'cx, 'tcx>, | |
2127 | ) -> Option<InitIndex> { | |
0bf4aa26 XL |
2128 | let mpi = self.move_data.rev_lookup.find_local(local); |
2129 | let ii = &self.move_data.init_path_map[mpi]; | |
2130 | for &index in ii { | |
2131 | if flow_state.ever_inits.contains(index) { | |
2132 | return Some(index); | |
2133 | } | |
2134 | } | |
2135 | None | |
ff7c6d11 XL |
2136 | } |
2137 | ||
83c7162d | 2138 | /// Adds the place into the used mutable variables set |
74b04a01 | 2139 | fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) { |
83c7162d | 2140 | match root_place { |
dfeec247 | 2141 | RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => { |
0bf4aa26 XL |
2142 | // If the local may have been initialized, and it is now currently being |
2143 | // mutated, then it is justified to be annotated with the `mut` | |
2144 | // keyword, since the mutation may be a possible reassignment. | |
dfeec247 | 2145 | if is_local_mutation_allowed != LocalMutationIsAllowed::Yes |
74b04a01 | 2146 | && self.is_local_ever_initialized(local, flow_state).is_some() |
0bf4aa26 | 2147 | { |
74b04a01 | 2148 | self.used_mut.insert(local); |
83c7162d XL |
2149 | } |
2150 | } | |
8faf50e0 | 2151 | RootPlace { |
dfeec247 | 2152 | place_local: _, |
416331ca | 2153 | place_projection: _, |
8faf50e0 XL |
2154 | is_local_mutation_allowed: LocalMutationIsAllowed::Yes, |
2155 | } => {} | |
83c7162d | 2156 | RootPlace { |
dfeec247 | 2157 | place_local, |
e1599b0c | 2158 | place_projection: place_projection @ [.., _], |
83c7162d XL |
2159 | is_local_mutation_allowed: _, |
2160 | } => { | |
416331ca | 2161 | if let Some(field) = self.is_upvar_field_projection(PlaceRef { |
dfeec247 XL |
2162 | local: place_local, |
2163 | projection: place_projection, | |
416331ca | 2164 | }) { |
83c7162d XL |
2165 | self.used_mut_upvars.push(field); |
2166 | } | |
2167 | } | |
83c7162d XL |
2168 | } |
2169 | } | |
2170 | ||
0bf4aa26 | 2171 | /// Whether this value can be written or borrowed mutably. |
83c7162d | 2172 | /// Returns the root place if the place passed in is a projection. |
74b04a01 | 2173 | fn is_mutable( |
ff7c6d11 | 2174 | &self, |
74b04a01 | 2175 | place: PlaceRef<'tcx>, |
ff7c6d11 | 2176 | is_local_mutation_allowed: LocalMutationIsAllowed, |
74b04a01 | 2177 | ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> { |
416331ca | 2178 | match place { |
dfeec247 | 2179 | PlaceRef { local, projection: [] } => { |
74b04a01 | 2180 | let local = &self.body.local_decls[local]; |
ff7c6d11 XL |
2181 | match local.mutability { |
2182 | Mutability::Not => match is_local_mutation_allowed { | |
8faf50e0 | 2183 | LocalMutationIsAllowed::Yes => Ok(RootPlace { |
dfeec247 | 2184 | place_local: place.local, |
416331ca | 2185 | place_projection: place.projection, |
8faf50e0 XL |
2186 | is_local_mutation_allowed: LocalMutationIsAllowed::Yes, |
2187 | }), | |
2188 | LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace { | |
dfeec247 | 2189 | place_local: place.local, |
416331ca | 2190 | place_projection: place.projection, |
8faf50e0 XL |
2191 | is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars, |
2192 | }), | |
ff7c6d11 XL |
2193 | LocalMutationIsAllowed::No => Err(place), |
2194 | }, | |
8faf50e0 | 2195 | Mutability::Mut => Ok(RootPlace { |
dfeec247 | 2196 | place_local: place.local, |
416331ca | 2197 | place_projection: place.projection, |
8faf50e0 XL |
2198 | is_local_mutation_allowed, |
2199 | }), | |
ff7c6d11 XL |
2200 | } |
2201 | } | |
dfeec247 | 2202 | PlaceRef { local: _, projection: [proj_base @ .., elem] } => { |
e1599b0c | 2203 | match elem { |
ff7c6d11 | 2204 | ProjectionElem::Deref => { |
416331ca | 2205 | let base_ty = |
dfeec247 | 2206 | Place::ty_from(place.local, proj_base, self.body(), self.infcx.tcx).ty; |
ff7c6d11 XL |
2207 | |
2208 | // Check the kind of deref to decide | |
e74abb32 | 2209 | match base_ty.kind { |
b7449926 | 2210 | ty::Ref(_, _, mutbl) => { |
94b46f34 | 2211 | match mutbl { |
ff7c6d11 | 2212 | // Shared borrowed data is never mutable |
dfeec247 | 2213 | hir::Mutability::Not => Err(place), |
ff7c6d11 XL |
2214 | // Mutably borrowed data is mutable, but only if we have a |
2215 | // unique path to the `&mut` | |
dfeec247 | 2216 | hir::Mutability::Mut => { |
48663c56 | 2217 | let mode = match self.is_upvar_field_projection(place) { |
dfeec247 | 2218 | Some(field) if self.upvars[field.index()].by_ref => { |
ff7c6d11 XL |
2219 | is_local_mutation_allowed |
2220 | } | |
2221 | _ => LocalMutationIsAllowed::Yes, | |
2222 | }; | |
2223 | ||
dfeec247 XL |
2224 | self.is_mutable( |
2225 | PlaceRef { local: place.local, projection: proj_base }, | |
2226 | mode, | |
2227 | ) | |
ff7c6d11 XL |
2228 | } |
2229 | } | |
2230 | } | |
b7449926 | 2231 | ty::RawPtr(tnm) => { |
ff7c6d11 XL |
2232 | match tnm.mutbl { |
2233 | // `*const` raw pointers are not mutable | |
dfeec247 | 2234 | hir::Mutability::Not => Err(place), |
83c7162d XL |
2235 | // `*mut` raw pointers are always mutable, regardless of |
2236 | // context. The users have to check by themselves. | |
dfeec247 XL |
2237 | hir::Mutability::Mut => Ok(RootPlace { |
2238 | place_local: place.local, | |
2239 | place_projection: place.projection, | |
2240 | is_local_mutation_allowed, | |
2241 | }), | |
ff7c6d11 XL |
2242 | } |
2243 | } | |
2244 | // `Box<T>` owns its content, so mutable if its location is mutable | |
dfeec247 XL |
2245 | _ if base_ty.is_box() => self.is_mutable( |
2246 | PlaceRef { local: place.local, projection: proj_base }, | |
2247 | is_local_mutation_allowed, | |
2248 | ), | |
ff7c6d11 XL |
2249 | // Deref should only be for reference, pointers or boxes |
2250 | _ => bug!("Deref of unexpected type: {:?}", base_ty), | |
2251 | } | |
2252 | } | |
2253 | // All other projections are owned by their base path, so mutable if | |
2254 | // base path is mutable | |
2255 | ProjectionElem::Field(..) | |
2256 | | ProjectionElem::Index(..) | |
2257 | | ProjectionElem::ConstantIndex { .. } | |
2258 | | ProjectionElem::Subslice { .. } | |
2259 | | ProjectionElem::Downcast(..) => { | |
48663c56 | 2260 | let upvar_field_projection = self.is_upvar_field_projection(place); |
8faf50e0 | 2261 | if let Some(field) = upvar_field_projection { |
48663c56 | 2262 | let upvar = &self.upvars[field.index()]; |
ff7c6d11 | 2263 | debug!( |
416331ca | 2264 | "upvar.mutability={:?} local_mutation_is_allowed={:?} \ |
dfeec247 | 2265 | place={:?}", |
48663c56 | 2266 | upvar, is_local_mutation_allowed, place |
ff7c6d11 | 2267 | ); |
48663c56 | 2268 | match (upvar.mutability, is_local_mutation_allowed) { |
ba9703b0 XL |
2269 | ( |
2270 | Mutability::Not, | |
2271 | LocalMutationIsAllowed::No | |
2272 | | LocalMutationIsAllowed::ExceptUpvars, | |
2273 | ) => Err(place), | |
ff7c6d11 XL |
2274 | (Mutability::Not, LocalMutationIsAllowed::Yes) |
2275 | | (Mutability::Mut, _) => { | |
83c7162d XL |
2276 | // Subtle: this is an upvar |
2277 | // reference, so it looks like | |
2278 | // `self.foo` -- we want to double | |
48663c56 | 2279 | // check that the location `*self` |
83c7162d XL |
2280 | // is mutable (i.e., this is not a |
2281 | // `Fn` closure). But if that | |
2282 | // check succeeds, we want to | |
2283 | // *blame* the mutability on | |
2284 | // `place` (that is, | |
2285 | // `self.foo`). This is used to | |
2286 | // propagate the info about | |
2287 | // whether mutability declarations | |
2288 | // are used outwards, so that we register | |
2289 | // the outer variable as mutable. Otherwise a | |
2290 | // test like this fails to record the `mut` | |
2291 | // as needed: | |
2292 | // | |
2293 | // ``` | |
2294 | // fn foo<F: FnOnce()>(_f: F) { } | |
2295 | // fn main() { | |
2296 | // let var = Vec::new(); | |
2297 | // foo(move || { | |
2298 | // var.push(1); | |
2299 | // }); | |
2300 | // } | |
2301 | // ``` | |
dfeec247 XL |
2302 | let _ = self.is_mutable( |
2303 | PlaceRef { local: place.local, projection: proj_base }, | |
2304 | is_local_mutation_allowed, | |
2305 | )?; | |
8faf50e0 | 2306 | Ok(RootPlace { |
dfeec247 | 2307 | place_local: place.local, |
416331ca | 2308 | place_projection: place.projection, |
8faf50e0 XL |
2309 | is_local_mutation_allowed, |
2310 | }) | |
ff7c6d11 XL |
2311 | } |
2312 | } | |
2313 | } else { | |
dfeec247 XL |
2314 | self.is_mutable( |
2315 | PlaceRef { local: place.local, projection: proj_base }, | |
2316 | is_local_mutation_allowed, | |
2317 | ) | |
ff7c6d11 XL |
2318 | } |
2319 | } | |
2320 | } | |
2321 | } | |
2322 | } | |
2323 | } | |
48663c56 XL |
2324 | |
2325 | /// If `place` is a field projection, and the field is being projected from a closure type, | |
2326 | /// then returns the index of the field being projected. Note that this closure will always | |
2327 | /// be `self` in the current MIR, because that is the only time we directly access the fields | |
2328 | /// of a closure type. | |
74b04a01 | 2329 | pub fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> { |
f035d41b | 2330 | path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body()) |
48663c56 | 2331 | } |
ff7c6d11 XL |
2332 | } |
2333 | ||
ff7c6d11 XL |
2334 | /// The degree of overlap between 2 places for borrow-checking. |
2335 | enum Overlap { | |
2336 | /// The places might partially overlap - in this case, we give | |
2337 | /// up and say that they might conflict. This occurs when | |
2338 | /// different fields of a union are borrowed. For example, | |
2339 | /// if `u` is a union, we have no way of telling how disjoint | |
2340 | /// `u.a.x` and `a.b.y` are. | |
2341 | Arbitrary, | |
2342 | /// The places have the same type, and are either completely disjoint | |
0731742a | 2343 | /// or equal - i.e., they can't "partially" overlap as can occur with |
ff7c6d11 XL |
2344 | /// unions. This is the "base case" on which we recur for extensions |
2345 | /// of the place. | |
2346 | EqualOrDisjoint, | |
2347 | /// The places are disjoint, so we know all extensions of them | |
2348 | /// will also be disjoint. | |
2349 | Disjoint, | |
2350 | } |