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