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