1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
3 use rustc::infer::{opaque_types, InferCtxt};
4 use rustc::lint::builtin::MUTABLE_BORROW_RESERVATION_CONFLICT;
5 use rustc::lint::builtin::UNUSED_MUT;
7 read_only, Body, BodyAndCache, ClearCrossCrate, Local, Location, Mutability, Operand, Place,
8 PlaceElem, PlaceRef, ReadOnlyBodyAndCache,
10 use rustc::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
11 use rustc::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
12 use rustc::mir::{Terminator, TerminatorKind};
13 use rustc::ty::query::Providers;
14 use rustc::ty::{self, TyCtxt};
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
16 use rustc_data_structures::graph::dominators::Dominators;
17 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder};
19 use rustc_hir::{def_id::DefId, HirId, Node};
20 use rustc_index::bit_set::BitSet;
21 use rustc_index::vec::IndexVec;
23 use smallvec::SmallVec;
24 use std::collections::BTreeMap;
28 use rustc_span::{Span, DUMMY_SP};
29 use syntax::ast::Name;
31 use crate::dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex};
32 use crate::dataflow::move_paths::{HasMoveData, InitLocation, LookupResult, MoveData, MoveError};
33 use crate::dataflow::Borrows;
34 use crate::dataflow::DataflowResultsConsumer;
35 use crate::dataflow::EverInitializedPlaces;
36 use crate::dataflow::FlowAtLocation;
37 use crate::dataflow::MoveDataParamEnv;
38 use crate::dataflow::{do_dataflow, DebugFormatted};
39 use crate::dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
40 use crate::transform::MirSource;
42 use self::diagnostics::{
43 AccessKind, OutlivesSuggestionBuilder, RegionErrorKind, RegionErrorNamingCtx, RegionErrors,
45 use self::flows::Flows;
46 use self::location::LocationTable;
47 use self::prefixes::PrefixSet;
48 use self::MutateMode::{JustWrite, WriteAndRead};
50 use self::path_utils::*;
53 mod constraint_generation;
60 mod member_constraints;
69 mod universal_regions;
72 crate use borrow_set::{BorrowData, BorrowSet};
73 crate use nll::ToRegionVid;
74 crate use place_ext::PlaceExt;
75 crate use places_conflict::{places_conflict, PlaceConflictBias};
76 crate use region_infer::RegionInferenceContext;
78 // FIXME(eddyb) perhaps move this somewhere more centrally.
85 /// If true, the capture is behind a reference.
88 mutability: Mutability,
91 pub fn provide(providers: &mut Providers<'_>) {
92 *providers = Providers { mir_borrowck, ..*providers };
95 fn mir_borrowck(tcx: TyCtxt<'_>, def_id: DefId) -> BorrowCheckResult<'_> {
96 let (input_body, promoted) = tcx.mir_validated(def_id);
97 debug!("run query mir_borrowck: {}", tcx.def_path_str(def_id));
99 let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
100 let input_body: &Body<'_> = &input_body.borrow();
101 let promoted: &IndexVec<_, _> = &promoted.borrow();
102 do_mir_borrowck(&infcx, input_body, promoted, def_id)
104 debug!("mir_borrowck done");
109 fn do_mir_borrowck<'a, 'tcx>(
110 infcx: &InferCtxt<'a, 'tcx>,
111 input_body: &Body<'tcx>,
112 input_promoted: &IndexVec<Promoted, BodyAndCache<'tcx>>,
114 ) -> BorrowCheckResult<'tcx> {
115 debug!("do_mir_borrowck(def_id = {:?})", def_id);
118 let attributes = tcx.get_attrs(def_id);
119 let param_env = tcx.param_env(def_id);
120 let id = tcx.hir().as_local_hir_id(def_id).expect("do_mir_borrowck: non-local DefId");
122 let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
123 for var_debug_info in &input_body.var_debug_info {
124 if let Some(local) = var_debug_info.place.as_local() {
125 if let Some(prev_name) = local_names[local] {
126 if var_debug_info.name != prev_name {
128 var_debug_info.source_info.span,
129 "local {:?} has many names (`{}` vs `{}`)",
136 local_names[local] = Some(var_debug_info.name);
140 // Gather the upvars of a closure, if any.
141 let tables = tcx.typeck_tables_of(def_id);
142 let upvars: Vec<_> = tables
146 .flat_map(|v| v.values())
148 let var_hir_id = upvar_id.var_path.hir_id;
149 let capture = tables.upvar_capture(*upvar_id);
150 let by_ref = match capture {
151 ty::UpvarCapture::ByValue => false,
152 ty::UpvarCapture::ByRef(..) => true,
154 let mut upvar = Upvar {
155 name: tcx.hir().name(var_hir_id),
158 mutability: Mutability::Not,
160 let bm = *tables.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
161 if bm == ty::BindByValue(hir::Mutability::Mut) {
162 upvar.mutability = Mutability::Mut;
168 // Replace all regions with fresh inference variables. This
169 // requires first making our own copy of the MIR. This copy will
170 // be modified (in place) to contain non-lexical lifetimes. It
171 // will have a lifetime tied to the inference context.
172 let body_clone: Body<'tcx> = input_body.clone();
173 let mut promoted = input_promoted.clone();
174 let mut body = BodyAndCache::new(body_clone);
176 nll::replace_regions_in_mir(infcx, def_id, param_env, &mut body, &mut promoted);
177 let body = read_only!(body); // no further changes
178 let promoted: IndexVec<_, _> = promoted.iter_mut().map(|body| read_only!(body)).collect();
180 let location_table = &LocationTable::new(&body);
182 let mut errors_buffer = Vec::new();
183 let (move_data, move_errors): (MoveData<'tcx>, Option<Vec<(Place<'tcx>, MoveError<'tcx>)>>) =
184 match MoveData::gather_moves(&body, tcx, param_env) {
185 Ok(move_data) => (move_data, None),
186 Err((move_data, move_errors)) => (move_data, Some(move_errors)),
189 let mdpe = MoveDataParamEnv { move_data, param_env };
191 let dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
192 let mut flow_inits = FlowAtLocation::new(do_dataflow(
198 MaybeInitializedPlaces::new(tcx, &body, &mdpe),
199 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
202 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
204 Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
206 // Compute non-lexical lifetimes.
207 let nll::NllOutput { regioncx, polonius_output, opt_closure_req, nll_errors } =
208 nll::compute_regions(
221 // Dump MIR results into a file, if that is enabled. This let us
222 // write unit-tests, as well as helping with debugging.
223 nll::dump_mir_results(infcx, MirSource::item(def_id), &body, ®ioncx, &opt_closure_req);
225 // We also have a `#[rustc_nll]` annotation that causes us to dump
227 nll::dump_annotation(infcx, &body, def_id, ®ioncx, &opt_closure_req, &mut errors_buffer);
229 // The various `flow_*` structures can be large. We drop `flow_inits` here
230 // so it doesn't overlap with the others below. This reduces peak memory
231 // usage significantly on some benchmarks.
234 let regioncx = Rc::new(regioncx);
236 let flow_borrows = FlowAtLocation::new(do_dataflow(
242 Borrows::new(tcx, &body, regioncx.clone(), &borrow_set),
243 |rs, i| DebugFormatted::new(&rs.location(i)),
245 let flow_uninits = FlowAtLocation::new(do_dataflow(
251 MaybeUninitializedPlaces::new(tcx, &body, &mdpe),
252 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
254 let flow_ever_inits = FlowAtLocation::new(do_dataflow(
260 EverInitializedPlaces::new(tcx, &body, &mdpe),
261 |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
264 let movable_generator = match tcx.hir().get(id) {
265 Node::Expr(&hir::Expr {
266 kind: hir::ExprKind::Closure(.., Some(hir::Movability::Static)),
272 let dominators = body.dominators();
274 let mut mbcx = MirBorrowckCtxt {
278 move_data: &mdpe.move_data,
281 locals_are_invalidated_at_exit,
282 access_place_error_reported: Default::default(),
283 reservation_error_reported: Default::default(),
284 reservation_warnings: Default::default(),
285 move_error_reported: BTreeMap::new(),
286 uninitialized_error_reported: Default::default(),
288 nonlexical_regioncx: regioncx,
289 used_mut: Default::default(),
290 used_mut_upvars: SmallVec::new(),
297 // Compute and report region errors, if any.
298 mbcx.report_region_errors(nll_errors);
300 let mut state = Flows::new(flow_borrows, flow_uninits, flow_ever_inits, polonius_output);
302 if let Some(errors) = move_errors {
303 mbcx.report_move_errors(errors);
305 mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
307 // Convert any reservation warnings into lints.
308 let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
309 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
310 let mut initial_diag =
311 mbcx.report_conflicting_borrow(location, (&place, span), bk, &borrow);
313 let scope = mbcx.body.source_info(location).scope;
314 let lint_root = match &mbcx.body.source_scopes[scope].local_data {
315 ClearCrossCrate::Set(data) => data.lint_root,
319 // Span and message don't matter; we overwrite them below anyway
320 let mut diag = mbcx.infcx.tcx.struct_span_lint_hir(
321 MUTABLE_BORROW_RESERVATION_CONFLICT,
327 diag.message = initial_diag.styled_message().clone();
328 diag.span = initial_diag.span.clone();
330 initial_diag.cancel();
331 diag.buffer(&mut mbcx.errors_buffer);
334 // For each non-user used mutable variable, check if it's been assigned from
335 // a user-declared local. If so, then put that local into the used_mut set.
336 // Note that this set is expected to be small - only upvars from closures
337 // would have a chance of erroneously adding non-user-defined mutable vars
339 let temporary_used_locals: FxHashSet<Local> = mbcx
342 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
345 // For the remaining unused locals that are marked as mutable, we avoid linting any that
346 // were never initialized. These locals may have been removed as unreachable code; or will be
347 // linted as unused variables.
348 let unused_mut_locals =
349 mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
350 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
352 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
353 let used_mut = mbcx.used_mut;
354 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
355 let local_decl = &mbcx.body.local_decls[local];
356 let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data {
357 ClearCrossCrate::Set(data) => data.lint_root,
361 // Skip over locals that begin with an underscore or have no name
362 match mbcx.local_names[local] {
364 if name.as_str().starts_with("_") {
371 let span = local_decl.source_info.span;
372 if span.desugaring_kind().is_some() {
373 // If the `mut` arises as part of a desugaring, we should ignore it.
377 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
378 tcx.struct_span_lint_hir(
382 "variable does not need to be mutable",
384 .span_suggestion_short(
388 Applicability::MachineApplicable,
393 // Buffer any move errors that we collected and de-duplicated.
394 for (_, (_, diag)) in mbcx.move_error_reported {
395 diag.buffer(&mut mbcx.errors_buffer);
398 if !mbcx.errors_buffer.is_empty() {
399 mbcx.errors_buffer.sort_by_key(|diag| diag.sort_span);
401 for diag in mbcx.errors_buffer.drain(..) {
402 mbcx.infcx.tcx.sess.diagnostic().emit_diagnostic(&diag);
406 let result = BorrowCheckResult {
407 closure_requirements: opt_closure_req,
408 used_mut_upvars: mbcx.used_mut_upvars,
411 debug!("do_mir_borrowck: result = {:#?}", result);
416 crate struct MirBorrowckCtxt<'cx, 'tcx> {
417 crate infcx: &'cx InferCtxt<'cx, 'tcx>,
418 body: ReadOnlyBodyAndCache<'cx, 'tcx>,
420 move_data: &'cx MoveData<'tcx>,
422 /// Map from MIR `Location` to `LocationIndex`; created
423 /// when MIR borrowck begins.
424 location_table: &'cx LocationTable,
426 movable_generator: bool,
427 /// This keeps track of whether local variables are free-ed when the function
428 /// exits even without a `StorageDead`, which appears to be the case for
431 /// I'm not sure this is the right approach - @eddyb could you try and
433 locals_are_invalidated_at_exit: bool,
434 /// This field keeps track of when borrow errors are reported in the access_place function
435 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
436 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
437 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
439 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
440 /// This field keeps track of when borrow conflict errors are reported
441 /// for reservations, so that we don't report seemingly duplicate
442 /// errors for corresponding activations.
444 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
445 // but it is currently inconvenient to track down the `BorrowIndex`
446 // at the time we detect and report a reservation error.
447 reservation_error_reported: FxHashSet<Place<'tcx>>,
448 /// Migration warnings to be reported for #56254. We delay reporting these
449 /// so that we can suppress the warning if there's a corresponding error
450 /// for the activation of the borrow.
451 reservation_warnings:
452 FxHashMap<BorrowIndex, (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)>,
453 /// This field keeps track of move errors that are to be reported for given move indicies.
455 /// There are situations where many errors can be reported for a single move out (see #53807)
456 /// and we want only the best of those errors.
458 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
459 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
460 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
461 /// all move errors have been reported, any diagnostics in this map are added to the buffer
464 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
465 /// when errors in the map are being re-added to the error buffer so that errors with the
466 /// same primary span come out in a consistent order.
467 move_error_reported: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'cx, 'tcx>, DiagnosticBuilder<'cx>)>,
468 /// This field keeps track of errors reported in the checking of uninitialized variables,
469 /// so that we don't report seemingly duplicate errors.
470 uninitialized_error_reported: FxHashSet<PlaceRef<'cx, 'tcx>>,
471 /// Errors to be reported buffer
472 errors_buffer: Vec<Diagnostic>,
473 /// This field keeps track of all the local variables that are declared mut and are mutated.
474 /// Used for the warning issued by an unused mutable local variable.
475 used_mut: FxHashSet<Local>,
476 /// If the function we're checking is a closure, then we'll need to report back the list of
477 /// mutable upvars that have been used. This field keeps track of them.
478 used_mut_upvars: SmallVec<[Field; 8]>,
479 /// Non-lexical region inference context, if NLL is enabled. This
480 /// contains the results from region inference and lets us e.g.
481 /// find out which CFG points are contained in each borrow region.
482 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
484 /// The set of borrows extracted from the MIR
485 borrow_set: Rc<BorrowSet<'tcx>>,
487 /// Dominators for MIR
488 dominators: Dominators<BasicBlock>,
490 /// Information about upvars not necessarily preserved in types or MIR
493 /// Names of local (user) variables (extracted from `var_debug_info`).
494 local_names: IndexVec<Local, Option<Name>>,
498 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
499 // 2. loans made in overlapping scopes do not conflict
500 // 3. assignments do not affect things loaned out as immutable
501 // 4. moves do not affect things loaned out in any way
502 impl<'cx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
503 type FlowState = Flows<'cx, 'tcx>;
505 fn body(&self) -> &'cx Body<'tcx> {
509 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
510 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
513 fn visit_statement_entry(
516 stmt: &'cx Statement<'tcx>,
517 flow_state: &Self::FlowState,
519 debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {}", location, stmt, flow_state);
520 let span = stmt.source_info.span;
522 self.check_activations(location, span, flow_state);
525 StatementKind::Assign(box (ref lhs, ref rhs)) => {
526 self.consume_rvalue(location, (rhs, span), flow_state);
528 self.mutate_place(location, (lhs, span), Shallow(None), JustWrite, flow_state);
530 StatementKind::FakeRead(_, box ref place) => {
531 // Read for match doesn't access any memory and is used to
532 // assert that a place is safe and live. So we don't have to
533 // do any checks here.
535 // FIXME: Remove check that the place is initialized. This is
536 // needed for now because matches don't have never patterns yet.
537 // So this is the only place we prevent
541 self.check_if_path_or_subpath_is_moved(
543 InitializationRequiringAction::Use,
544 (place.as_ref(), span),
548 StatementKind::SetDiscriminant { ref place, variant_index: _ } => {
549 self.mutate_place(location, (place, span), Shallow(None), JustWrite, flow_state);
551 StatementKind::InlineAsm(ref asm) => {
552 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
554 // FIXME(eddyb) indirect inline asm outputs should
555 // be encoded through MIR place derefs instead.
559 (Deep, Read(ReadKind::Copy)),
560 LocalMutationIsAllowed::No,
563 self.check_if_path_or_subpath_is_moved(
565 InitializationRequiringAction::Use,
566 (output.as_ref(), o.span),
573 if o.is_rw { Deep } else { Shallow(None) },
574 if o.is_rw { WriteAndRead } else { JustWrite },
579 for (_, input) in asm.inputs.iter() {
580 self.consume_operand(location, (input, span), flow_state);
584 | StatementKind::AscribeUserType(..)
585 | StatementKind::Retag { .. }
586 | StatementKind::StorageLive(..) => {
587 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
590 StatementKind::StorageDead(local) => {
593 (&Place::from(local), span),
594 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
595 LocalMutationIsAllowed::Yes,
602 fn visit_terminator_entry(
605 term: &'cx Terminator<'tcx>,
606 flow_state: &Self::FlowState,
609 debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {}", location, term, flow_state);
610 let span = term.source_info.span;
612 self.check_activations(location, span, flow_state);
615 TerminatorKind::SwitchInt { ref discr, switch_ty: _, values: _, targets: _ } => {
616 self.consume_operand(loc, (discr, span), flow_state);
618 TerminatorKind::Drop { location: ref drop_place, target: _, unwind: _ } => {
619 let tcx = self.infcx.tcx;
621 // Compute the type with accurate region information.
622 let drop_place_ty = drop_place.ty(*self.body, self.infcx.tcx);
624 // Erase the regions.
625 let drop_place_ty = self.infcx.tcx.erase_regions(&drop_place_ty).ty;
627 // "Lift" into the tcx -- once regions are erased, this type should be in the
628 // global arenas; this "lift" operation basically just asserts that is true, but
629 // that is useful later.
630 tcx.lift(&drop_place_ty).unwrap();
633 "visit_terminator_drop \
634 loc: {:?} term: {:?} drop_place: {:?} drop_place_ty: {:?} span: {:?}",
635 loc, term, drop_place, drop_place_ty, span
641 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
642 LocalMutationIsAllowed::Yes,
646 TerminatorKind::DropAndReplace {
647 location: ref drop_place,
648 value: ref new_value,
652 self.mutate_place(loc, (drop_place, span), Deep, JustWrite, flow_state);
653 self.consume_operand(loc, (new_value, span), flow_state);
655 TerminatorKind::Call {
662 self.consume_operand(loc, (func, span), flow_state);
664 self.consume_operand(loc, (arg, span), flow_state);
666 if let Some((ref dest, _ /*bb*/)) = *destination {
667 self.mutate_place(loc, (dest, span), Deep, JustWrite, flow_state);
670 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
671 self.consume_operand(loc, (cond, span), flow_state);
672 use rustc::mir::interpret::PanicInfo;
673 if let PanicInfo::BoundsCheck { ref len, ref index } = *msg {
674 self.consume_operand(loc, (len, span), flow_state);
675 self.consume_operand(loc, (index, span), flow_state);
679 TerminatorKind::Yield { ref value, resume: _, drop: _ } => {
680 self.consume_operand(loc, (value, span), flow_state);
682 if self.movable_generator {
683 // Look for any active borrows to locals
684 let borrow_set = self.borrow_set.clone();
685 flow_state.with_outgoing_borrows(|borrows| {
687 let borrow = &borrow_set[i];
688 self.check_for_local_borrow(borrow, span);
694 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
695 // Returning from the function implicitly kills storage for all locals and statics.
696 // Often, the storage will already have been killed by an explicit
697 // StorageDead, but we don't always emit those (notably on unwind paths),
698 // so this "extra check" serves as a kind of backup.
699 let borrow_set = self.borrow_set.clone();
700 flow_state.with_outgoing_borrows(|borrows| {
702 let borrow = &borrow_set[i];
703 self.check_for_invalidation_at_exit(loc, borrow, span);
707 TerminatorKind::Goto { target: _ }
708 | TerminatorKind::Abort
709 | TerminatorKind::Unreachable
710 | TerminatorKind::FalseEdges { real_target: _, imaginary_target: _ }
711 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
712 // no data used, thus irrelevant to borrowck
718 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
724 use self::AccessDepth::{Deep, Shallow};
725 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
727 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
728 enum ArtificialField {
733 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
735 /// From the RFC: "A *shallow* access means that the immediate
736 /// fields reached at P are accessed, but references or pointers
737 /// found within are not dereferenced. Right now, the only access
738 /// that is shallow is an assignment like `x = ...;`, which would
739 /// be a *shallow write* of `x`."
740 Shallow(Option<ArtificialField>),
742 /// From the RFC: "A *deep* access means that all data reachable
743 /// through the given place may be invalidated or accesses by
747 /// Access is Deep only when there is a Drop implementation that
748 /// can reach the data behind the reference.
752 /// Kind of access to a value: read or write
753 /// (For informational purposes only)
754 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
756 /// From the RFC: "A *read* means that the existing data may be
757 /// read, but will not be changed."
760 /// From the RFC: "A *write* means that the data may be mutated to
761 /// new values or otherwise invalidated (for example, it could be
762 /// de-initialized, as in a move operation).
765 /// For two-phase borrows, we distinguish a reservation (which is treated
766 /// like a Read) from an activation (which is treated like a write), and
767 /// each of those is furthermore distinguished from Reads/Writes above.
768 Reservation(WriteKind),
769 Activation(WriteKind, BorrowIndex),
772 /// Kind of read access to a value
773 /// (For informational purposes only)
774 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
780 /// Kind of write access to a value
781 /// (For informational purposes only)
782 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
785 MutableBorrow(BorrowKind),
790 /// When checking permissions for a place access, this flag is used to indicate that an immutable
791 /// local place can be mutated.
793 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
794 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
795 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
796 // `is_declared_mutable()`.
797 // - Take flow state into consideration in `is_assignable()` for local variables.
798 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
799 enum LocalMutationIsAllowed {
801 /// We want use of immutable upvars to cause a "write to immutable upvar"
802 /// error, not an "reassignment" error.
807 #[derive(Copy, Clone, Debug)]
808 enum InitializationRequiringAction {
817 struct RootPlace<'d, 'tcx> {
818 place_local: &'d Local,
819 place_projection: &'d [PlaceElem<'tcx>],
820 is_local_mutation_allowed: LocalMutationIsAllowed,
823 impl InitializationRequiringAction {
824 fn as_noun(self) -> &'static str {
826 InitializationRequiringAction::Update => "update",
827 InitializationRequiringAction::Borrow => "borrow",
828 InitializationRequiringAction::MatchOn => "use", // no good noun
829 InitializationRequiringAction::Use => "use",
830 InitializationRequiringAction::Assignment => "assign",
831 InitializationRequiringAction::PartialAssignment => "assign to part",
835 fn as_verb_in_past_tense(self) -> &'static str {
837 InitializationRequiringAction::Update => "updated",
838 InitializationRequiringAction::Borrow => "borrowed",
839 InitializationRequiringAction::MatchOn => "matched on",
840 InitializationRequiringAction::Use => "used",
841 InitializationRequiringAction::Assignment => "assigned",
842 InitializationRequiringAction::PartialAssignment => "partially assigned",
847 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
848 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
849 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
850 /// place is initialized and (b) it is not borrowed in some way that would prevent this
853 /// Returns `true` if an error is reported.
857 place_span: (&Place<'tcx>, Span),
858 kind: (AccessDepth, ReadOrWrite),
859 is_local_mutation_allowed: LocalMutationIsAllowed,
860 flow_state: &Flows<'cx, 'tcx>,
864 if let Activation(_, borrow_index) = rw {
865 if self.reservation_error_reported.contains(&place_span.0) {
867 "skipping access_place for activation of invalid reservation \
868 place: {:?} borrow_index: {:?}",
869 place_span.0, borrow_index
875 // Check is_empty() first because it's the common case, and doing that
876 // way we avoid the clone() call.
877 if !self.access_place_error_reported.is_empty()
878 && self.access_place_error_reported.contains(&(place_span.0.clone(), place_span.1))
881 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
887 let mutability_error = self.check_access_permissions(
890 is_local_mutation_allowed,
895 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
897 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
898 // Suppress this warning when there's an error being emitted for the
899 // same borrow: fixing the error is likely to fix the warning.
900 self.reservation_warnings.remove(&borrow_idx);
903 if conflict_error || mutability_error {
904 debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
906 self.access_place_error_reported.insert((place_span.0.clone(), place_span.1));
910 fn check_access_for_conflict(
913 place_span: (&Place<'tcx>, Span),
916 flow_state: &Flows<'cx, 'tcx>,
919 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
920 location, place_span, sd, rw,
923 let mut error_reported = false;
924 let tcx = self.infcx.tcx;
925 let body = self.body;
926 let body: &Body<'_> = &body;
927 let location_table = self.location_table.start_index(location);
928 let borrow_set = self.borrow_set.clone();
929 each_borrow_involving_path(
936 flow_state.borrows_in_scope(location_table),
937 |this, borrow_index, borrow| match (rw, borrow.kind) {
938 // Obviously an activation is compatible with its own
939 // reservation (or even prior activating uses of same
940 // borrow); so don't check if they interfere.
942 // NOTE: *reservations* do conflict with themselves;
943 // thus aren't injecting unsoundenss w/ this check.)
944 (Activation(_, activating), _) if activating == borrow_index => {
946 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
947 skipping {:?} b/c activation of same borrow_index",
951 (borrow_index, borrow),
956 (Read(_), BorrowKind::Shared)
957 | (Read(_), BorrowKind::Shallow)
958 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
959 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
963 (Write(WriteKind::Move), BorrowKind::Shallow) => {
964 // Handled by initialization checks.
968 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
969 // Reading from mere reservations of mutable-borrows is OK.
970 if !is_active(&this.dominators, borrow, location) {
971 assert!(allow_two_phase_borrow(borrow.kind));
972 return Control::Continue;
975 error_reported = true;
978 this.report_use_while_mutably_borrowed(location, place_span, borrow)
979 .buffer(&mut this.errors_buffer);
981 ReadKind::Borrow(bk) => {
982 this.report_conflicting_borrow(location, place_span, bk, borrow)
983 .buffer(&mut this.errors_buffer);
989 (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow)
990 | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared)
992 tcx.migrate_borrowck()
993 && this.borrow_set.location_map.contains_key(&location)
996 let bi = this.borrow_set.location_map[&location];
998 "recording invalid reservation of place: {:?} with \
999 borrow index {:?} as warning",
1002 // rust-lang/rust#56254 - This was previously permitted on
1003 // the 2018 edition so we emit it as a warning. We buffer
1004 // these sepately so that we only emit a warning if borrow
1005 // checking was otherwise successful.
1006 this.reservation_warnings.insert(
1008 (place_span.0.clone(), place_span.1, location, bk, borrow.clone()),
1011 // Don't suppress actual errors.
1015 (Reservation(kind), _) | (Activation(kind, _), _) | (Write(kind), _) => {
1017 Reservation(..) => {
1019 "recording invalid reservation of \
1023 this.reservation_error_reported.insert(place_span.0.clone());
1025 Activation(_, activating) => {
1027 "observing check_place for activation of \
1028 borrow_index: {:?}",
1032 Read(..) | Write(..) => {}
1035 error_reported = true;
1037 WriteKind::MutableBorrow(bk) => {
1038 this.report_conflicting_borrow(location, place_span, bk, borrow)
1039 .buffer(&mut this.errors_buffer);
1041 WriteKind::StorageDeadOrDrop => this
1042 .report_borrowed_value_does_not_live_long_enough(
1048 WriteKind::Mutate => {
1049 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1051 WriteKind::Move => {
1052 this.report_move_out_while_borrowed(location, place_span, borrow)
1066 place_span: (&'cx Place<'tcx>, Span),
1069 flow_state: &Flows<'cx, 'tcx>,
1071 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1073 MutateMode::WriteAndRead => {
1074 self.check_if_path_or_subpath_is_moved(
1076 InitializationRequiringAction::Update,
1077 (place_span.0.as_ref(), place_span.1),
1081 MutateMode::JustWrite => {
1082 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1086 // Special case: you can assign a immutable local variable
1087 // (e.g., `x = ...`) so long as it has never been initialized
1088 // before (at this point in the flow).
1089 if let Some(local) = place_span.0.as_local() {
1090 if let Mutability::Not = self.body.local_decls[local].mutability {
1091 // check for reassignments to immutable local variables
1092 self.check_if_reassignment_to_immutable_state(
1093 location, local, place_span, flow_state,
1099 // Otherwise, use the normal access permission rules.
1103 (kind, Write(WriteKind::Mutate)),
1104 LocalMutationIsAllowed::No,
1112 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1113 flow_state: &Flows<'cx, 'tcx>,
1116 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1117 let access_kind = match bk {
1118 BorrowKind::Shallow => {
1119 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1121 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1122 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1123 let wk = WriteKind::MutableBorrow(bk);
1124 if allow_two_phase_borrow(bk) {
1125 (Deep, Reservation(wk))
1136 LocalMutationIsAllowed::No,
1140 let action = if bk == BorrowKind::Shallow {
1141 InitializationRequiringAction::MatchOn
1143 InitializationRequiringAction::Borrow
1146 self.check_if_path_or_subpath_is_moved(
1149 (place.as_ref(), span),
1154 Rvalue::AddressOf(mutability, ref place) => {
1155 let access_kind = match mutability {
1156 Mutability::Mut => (
1158 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1159 allow_two_phase_borrow: false,
1162 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1169 LocalMutationIsAllowed::No,
1173 self.check_if_path_or_subpath_is_moved(
1175 InitializationRequiringAction::Borrow,
1176 (place.as_ref(), span),
1181 Rvalue::Use(ref operand)
1182 | Rvalue::Repeat(ref operand, _)
1183 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1184 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1185 self.consume_operand(location, (operand, span), flow_state)
1188 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1189 let af = match *rvalue {
1190 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1191 Rvalue::Discriminant(..) => None,
1192 _ => unreachable!(),
1197 (Shallow(af), Read(ReadKind::Copy)),
1198 LocalMutationIsAllowed::No,
1201 self.check_if_path_or_subpath_is_moved(
1203 InitializationRequiringAction::Use,
1204 (place.as_ref(), span),
1209 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1210 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1211 self.consume_operand(location, (operand1, span), flow_state);
1212 self.consume_operand(location, (operand2, span), flow_state);
1215 Rvalue::NullaryOp(_op, _ty) => {
1216 // nullary ops take no dynamic input; no borrowck effect.
1218 // FIXME: is above actually true? Do we want to track
1219 // the fact that uninitialized data can be created via
1223 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1224 // We need to report back the list of mutable upvars that were
1225 // moved into the closure and subsequently used by the closure,
1226 // in order to populate our used_mut set.
1227 match **aggregate_kind {
1228 AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
1229 let BorrowCheckResult { used_mut_upvars, .. } =
1230 self.infcx.tcx.mir_borrowck(def_id);
1231 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1232 for field in used_mut_upvars {
1233 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1236 AggregateKind::Adt(..)
1237 | AggregateKind::Array(..)
1238 | AggregateKind::Tuple { .. } => (),
1241 for operand in operands {
1242 self.consume_operand(location, (operand, span), flow_state);
1248 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1249 let propagate_closure_used_mut_place = |this: &mut Self, place: &Place<'tcx>| {
1250 if !place.projection.is_empty() {
1251 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1252 this.used_mut_upvars.push(field);
1255 this.used_mut.insert(place.local);
1259 // This relies on the current way that by-value
1260 // captures of a closure are copied/moved directly
1261 // when generating MIR.
1263 Operand::Move(ref place) | Operand::Copy(ref place) => {
1264 match place.as_local() {
1265 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1266 if self.body.local_decls[local].ty.is_mutable_ptr() {
1267 // The variable will be marked as mutable by the borrow.
1270 // This is an edge case where we have a `move` closure
1271 // inside a non-move closure, and the inner closure
1272 // contains a mutation:
1275 // || { move || { i += 1; }; };
1277 // In this case our usual strategy of assuming that the
1278 // variable will be captured by mutable reference is
1279 // wrong, since `i` can be copied into the inner
1280 // closure from a shared reference.
1282 // As such we have to search for the local that this
1283 // capture comes from and mark it as being used as mut.
1285 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1286 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1287 &self.move_data.inits[init_index]
1289 bug!("temporary should be initialized exactly once")
1292 let loc = match init.location {
1293 InitLocation::Statement(stmt) => stmt,
1294 _ => bug!("temporary initialized in arguments"),
1297 let body = self.body;
1298 let bbd = &body[loc.block];
1299 let stmt = &bbd.statements[loc.statement_index];
1300 debug!("temporary assigned in: stmt={:?}", stmt);
1302 if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, ref source))) =
1305 propagate_closure_used_mut_place(self, source);
1308 "closures should only capture user variables \
1309 or references to user variables"
1313 _ => propagate_closure_used_mut_place(self, place),
1316 Operand::Constant(..) => {}
1323 (operand, span): (&'cx Operand<'tcx>, Span),
1324 flow_state: &Flows<'cx, 'tcx>,
1327 Operand::Copy(ref place) => {
1328 // copy of place: check if this is "copy of frozen path"
1329 // (FIXME: see check_loans.rs)
1333 (Deep, Read(ReadKind::Copy)),
1334 LocalMutationIsAllowed::No,
1338 // Finally, check if path was already moved.
1339 self.check_if_path_or_subpath_is_moved(
1341 InitializationRequiringAction::Use,
1342 (place.as_ref(), span),
1346 Operand::Move(ref place) => {
1347 // move of place: check if this is move of already borrowed path
1351 (Deep, Write(WriteKind::Move)),
1352 LocalMutationIsAllowed::Yes,
1356 // Finally, check if path was already moved.
1357 self.check_if_path_or_subpath_is_moved(
1359 InitializationRequiringAction::Use,
1360 (place.as_ref(), span),
1364 Operand::Constant(_) => {}
1368 /// Checks whether a borrow of this place is invalidated when the function
1370 fn check_for_invalidation_at_exit(
1373 borrow: &BorrowData<'tcx>,
1376 debug!("check_for_invalidation_at_exit({:?})", borrow);
1377 let place = &borrow.borrowed_place;
1378 let deref = [ProjectionElem::Deref];
1379 let mut root_place = PlaceRef { local: &place.local, projection: &[] };
1381 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1382 // we just know that all locals are dropped at function exit (otherwise
1383 // we'll have a memory leak) and assume that all statics have a destructor.
1385 // FIXME: allow thread-locals to borrow other thread locals?
1387 let (might_be_alive, will_be_dropped) =
1388 if self.body.local_decls[*root_place.local].is_ref_to_thread_local() {
1389 // Thread-locals might be dropped after the function exits
1390 // We have to dereference the outer reference because
1391 // borrows don't conflict behind shared references.
1392 root_place.projection = &deref;
1395 (false, self.locals_are_invalidated_at_exit)
1398 if !will_be_dropped {
1399 debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
1403 let sd = if might_be_alive { Deep } else { Shallow(None) };
1405 if places_conflict::borrow_conflicts_with_place(
1412 places_conflict::PlaceConflictBias::Overlap,
1414 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1415 // FIXME: should be talking about the region lifetime instead
1416 // of just a span here.
1417 let span = self.infcx.tcx.sess.source_map().end_point(span);
1418 self.report_borrowed_value_does_not_live_long_enough(
1427 /// Reports an error if this is a borrow of local data.
1428 /// This is called for all Yield expressions on movable generators
1429 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1430 debug!("check_for_local_borrow({:?})", borrow);
1432 if borrow_of_local_data(&borrow.borrowed_place) {
1433 let err = self.cannot_borrow_across_generator_yield(
1434 self.retrieve_borrow_spans(borrow).var_or_use(),
1438 err.buffer(&mut self.errors_buffer);
1442 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1443 // Two-phase borrow support: For each activation that is newly
1444 // generated at this statement, check if it interferes with
1446 let borrow_set = self.borrow_set.clone();
1447 for &borrow_index in borrow_set.activations_at_location(location) {
1448 let borrow = &borrow_set[borrow_index];
1450 // only mutable borrows should be 2-phase
1451 assert!(match borrow.kind {
1452 BorrowKind::Shared | BorrowKind::Shallow => false,
1453 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1458 (&borrow.borrowed_place, span),
1459 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1460 LocalMutationIsAllowed::No,
1463 // We do not need to call `check_if_path_or_subpath_is_moved`
1464 // again, as we already called it when we made the
1465 // initial reservation.
1469 /// Produces nice borrowck error diagnostics for all the errors collected in `nll_errors`.
1470 fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
1471 // Iterate through all the errors, producing a diagnostic for each one. The diagnostics are
1472 // buffered in the `MirBorrowckCtxt`.
1474 // FIXME(mark-i-m): Would be great to get rid of the naming context.
1475 let mut region_naming = RegionErrorNamingCtx::new();
1476 let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
1478 for nll_error in nll_errors.into_iter() {
1480 RegionErrorKind::TypeTestError { type_test } => {
1481 // Try to convert the lower-bound region into something named we can print for the user.
1482 let lower_bound_region =
1483 self.nonlexical_regioncx.to_error_region(type_test.lower_bound);
1485 // Skip duplicate-ish errors.
1486 let type_test_span = type_test.locations.span(&self.body);
1488 if let Some(lower_bound_region) = lower_bound_region {
1489 let region_scope_tree = &self.infcx.tcx.region_scope_tree(self.mir_def_id);
1491 .construct_generic_bound_failure(
1495 type_test.generic_kind,
1498 .buffer(&mut self.errors_buffer);
1500 // FIXME. We should handle this case better. It indicates that we have
1501 // e.g., some region variable whose value is like `'a+'b` where `'a` and
1502 // `'b` are distinct unrelated univesal regions that are not known to
1503 // outlive one another. It'd be nice to have some examples where this
1504 // arises to decide how best to report it; we could probably handle it by
1505 // iterating over the universal regions and reporting an error that
1506 // multiple bounds are required.
1512 &format!("`{}` does not live long enough", type_test.generic_kind),
1514 .buffer(&mut self.errors_buffer);
1518 RegionErrorKind::UnexpectedHiddenRegion {
1523 let region_scope_tree = &self.infcx.tcx.region_scope_tree(self.mir_def_id);
1524 opaque_types::unexpected_hidden_region_diagnostic(
1526 Some(region_scope_tree),
1531 .buffer(&mut self.errors_buffer);
1534 RegionErrorKind::BoundUniversalRegionError {
1540 self.nonlexical_regioncx.region_from_element(longer_fr, error_element);
1542 // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
1543 let (_, span) = self.nonlexical_regioncx.find_outlives_blame_span(
1550 // FIXME: improve this error message
1554 .struct_span_err(span, "higher-ranked subtype error")
1555 .buffer(&mut self.errors_buffer);
1558 RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
1560 let db = self.nonlexical_regioncx.report_error(
1565 &mut outlives_suggestion,
1569 db.buffer(&mut self.errors_buffer);
1571 // We only report the first error, so as not to overwhelm the user. See
1572 // `RegRegionErrorKind` docs.
1574 // FIXME: currently we do nothing with these, but perhaps we can do better?
1575 // FIXME: try collecting these constraints on the outlives suggestion
1576 // builder. Does it make the suggestions any better?
1578 "Unreported region error: can't prove that {:?}: {:?}",
1579 longer_fr, shorter_fr
1586 // Emit one outlives suggestions for each MIR def we borrowck
1587 outlives_suggestion.add_suggestion(self, &mut region_naming);
1591 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
1592 fn check_if_reassignment_to_immutable_state(
1596 place_span: (&Place<'tcx>, Span),
1597 flow_state: &Flows<'cx, 'tcx>,
1599 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1601 // Check if any of the initializiations of `local` have happened yet:
1602 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1603 // And, if so, report an error.
1604 let init = &self.move_data.inits[init_index];
1605 let span = init.span(&self.body);
1606 self.report_illegal_reassignment(location, place_span, span, place_span.0);
1610 fn check_if_full_path_is_moved(
1613 desired_action: InitializationRequiringAction,
1614 place_span: (PlaceRef<'cx, 'tcx>, Span),
1615 flow_state: &Flows<'cx, 'tcx>,
1617 let maybe_uninits = &flow_state.uninits;
1621 // 1. Move of `a.b.c`, use of `a.b.c`
1622 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1623 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1624 // partial initialization support, one might have `a.x`
1625 // initialized but not `a.b`.
1629 // 4. Move of `a.b.c`, use of `a.b.d`
1630 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1631 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1632 // must have been initialized for the use to be sound.
1633 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1635 // The dataflow tracks shallow prefixes distinctly (that is,
1636 // field-accesses on P distinctly from P itself), in order to
1637 // track substructure initialization separately from the whole
1640 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1641 // which we have a MovePath is `a.b`, then that means that the
1642 // initialization state of `a.b` is all we need to inspect to
1643 // know if `a.b.c` is valid (and from that we infer that the
1644 // dereference and `.d` access is also valid, since we assume
1645 // `a.b.c` is assigned a reference to a initialized and
1646 // well-formed record structure.)
1648 // Therefore, if we seek out the *closest* prefix for which we
1649 // have a MovePath, that should capture the initialization
1650 // state for the place scenario.
1652 // This code covers scenarios 1, 2, and 3.
1654 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1655 let (prefix, mpi) = self.move_path_closest_to(place_span.0);
1656 if maybe_uninits.contains(mpi) {
1657 self.report_use_of_moved_or_uninitialized(
1660 (prefix, place_span.0, place_span.1),
1663 } // Only query longest prefix with a MovePath, not further
1664 // ancestors; dataflow recurs on children when parents
1665 // move (to support partial (re)inits).
1667 // (I.e., querying parents breaks scenario 7; but may want
1668 // to do such a query based on partial-init feature-gate.)
1671 /// Subslices correspond to multiple move paths, so we iterate through the
1672 /// elements of the base array. For each element we check
1674 /// * Does this element overlap with our slice.
1675 /// * Is any part of it uninitialized.
1676 fn check_if_subslice_element_is_moved(
1679 desired_action: InitializationRequiringAction,
1680 place_span: (PlaceRef<'cx, 'tcx>, Span),
1681 maybe_uninits: &FlowAtLocation<'tcx, MaybeUninitializedPlaces<'cx, 'tcx>>,
1685 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1686 let mut child = self.move_data.move_paths[mpi].first_child;
1687 while let Some(child_mpi) = child {
1688 let child_move_place = &self.move_data.move_paths[child_mpi];
1689 let child_place = &child_move_place.place;
1690 let last_proj = child_place.projection.last().unwrap();
1691 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
1692 debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
1694 if (from..to).contains(offset) {
1695 if let Some(uninit_child) = maybe_uninits.has_any_child_of(child_mpi) {
1696 self.report_use_of_moved_or_uninitialized(
1699 (place_span.0, place_span.0, place_span.1),
1702 return; // don't bother finding other problems.
1706 child = child_move_place.next_sibling;
1711 fn check_if_path_or_subpath_is_moved(
1714 desired_action: InitializationRequiringAction,
1715 place_span: (PlaceRef<'cx, 'tcx>, Span),
1716 flow_state: &Flows<'cx, 'tcx>,
1718 let maybe_uninits = &flow_state.uninits;
1722 // 1. Move of `a.b.c`, use of `a` or `a.b`
1723 // partial initialization support, one might have `a.x`
1724 // initialized but not `a.b`.
1725 // 2. All bad scenarios from `check_if_full_path_is_moved`
1729 // 3. Move of `a.b.c`, use of `a.b.d`
1730 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1731 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1732 // must have been initialized for the use to be sound.
1733 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1735 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1737 if let [base_proj @ .., ProjectionElem::Subslice { from, to, from_end: false }] =
1738 place_span.0.projection
1741 Place::ty_from(place_span.0.local, base_proj, self.body(), self.infcx.tcx);
1742 if let ty::Array(..) = place_ty.ty.kind {
1743 let array_place = PlaceRef { local: place_span.0.local, projection: base_proj };
1744 self.check_if_subslice_element_is_moved(
1747 (array_place, place_span.1),
1756 // A move of any shallow suffix of `place` also interferes
1757 // with an attempt to use `place`. This is scenario 3 above.
1759 // (Distinct from handling of scenarios 1+2+4 above because
1760 // `place` does not interfere with suffixes of its prefixes,
1761 // e.g., `a.b.c` does not interfere with `a.b.d`)
1763 // This code covers scenario 1.
1765 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1766 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1767 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1768 self.report_use_of_moved_or_uninitialized(
1771 (place_span.0, place_span.0, place_span.1),
1774 return; // don't bother finding other problems.
1779 /// Currently MoveData does not store entries for all places in
1780 /// the input MIR. For example it will currently filter out
1781 /// places that are Copy; thus we do not track places of shared
1782 /// reference type. This routine will walk up a place along its
1783 /// prefixes, searching for a foundational place that *is*
1784 /// tracked in the MoveData.
1786 /// An Err result includes a tag indicated why the search failed.
1787 /// Currently this can only occur if the place is built off of a
1788 /// static variable, as we do not track those in the MoveData.
1789 fn move_path_closest_to(
1791 place: PlaceRef<'_, 'tcx>,
1792 ) -> (PlaceRef<'cx, 'tcx>, MovePathIndex) {
1793 match self.move_data.rev_lookup.find(place) {
1794 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
1795 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
1797 LookupResult::Parent(None) => panic!("should have move path for every Local"),
1801 fn move_path_for_place(&mut self, place: PlaceRef<'_, 'tcx>) -> Option<MovePathIndex> {
1802 // If returns None, then there is no move path corresponding
1803 // to a direct owner of `place` (which means there is nothing
1804 // that borrowck tracks for its analysis).
1806 match self.move_data.rev_lookup.find(place) {
1807 LookupResult::Parent(_) => None,
1808 LookupResult::Exact(mpi) => Some(mpi),
1812 fn check_if_assigned_path_is_moved(
1815 (place, span): (&'cx Place<'tcx>, Span),
1816 flow_state: &Flows<'cx, 'tcx>,
1818 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1820 // None case => assigning to `x` does not require `x` be initialized.
1821 let mut cursor = &*place.projection.as_ref();
1822 while let [proj_base @ .., elem] = cursor {
1826 ProjectionElem::Index(_/*operand*/) |
1827 ProjectionElem::ConstantIndex { .. } |
1828 // assigning to P[i] requires P to be valid.
1829 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1830 // assigning to (P->variant) is okay if assigning to `P` is okay
1832 // FIXME: is this true even if P is a adt with a dtor?
1835 // assigning to (*P) requires P to be initialized
1836 ProjectionElem::Deref => {
1837 self.check_if_full_path_is_moved(
1838 location, InitializationRequiringAction::Use,
1840 local: &place.local,
1841 projection: proj_base,
1842 }, span), flow_state);
1843 // (base initialized; no need to
1848 ProjectionElem::Subslice { .. } => {
1849 panic!("we don't allow assignments to subslices, location: {:?}",
1853 ProjectionElem::Field(..) => {
1854 // if type of `P` has a dtor, then
1855 // assigning to `P.f` requires `P` itself
1856 // be already initialized
1857 let tcx = self.infcx.tcx;
1858 let base_ty = Place::ty_from(&place.local, proj_base, self.body(), tcx).ty;
1859 match base_ty.kind {
1860 ty::Adt(def, _) if def.has_dtor(tcx) => {
1861 self.check_if_path_or_subpath_is_moved(
1862 location, InitializationRequiringAction::Assignment,
1864 local: &place.local,
1865 projection: proj_base,
1866 }, span), flow_state);
1868 // (base initialized; no need to
1873 // Once `let s; s.x = V; read(s.x);`,
1874 // is allowed, remove this match arm.
1875 ty::Adt(..) | ty::Tuple(..) => {
1876 check_parent_of_field(self, location, PlaceRef {
1877 local: &place.local,
1878 projection: proj_base,
1879 }, span, flow_state);
1881 // rust-lang/rust#21232, #54499, #54986: during period where we reject
1882 // partial initialization, do not complain about unnecessary `mut` on
1883 // an attempt to do a partial initialization.
1884 self.used_mut.insert(place.local);
1893 fn check_parent_of_field<'cx, 'tcx>(
1894 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1896 base: PlaceRef<'cx, 'tcx>,
1898 flow_state: &Flows<'cx, 'tcx>,
1900 // rust-lang/rust#21232: Until Rust allows reads from the
1901 // initialized parts of partially initialized structs, we
1902 // will, starting with the 2018 edition, reject attempts
1903 // to write to structs that are not fully initialized.
1905 // In other words, *until* we allow this:
1907 // 1. `let mut s; s.x = Val; read(s.x);`
1909 // we will for now disallow this:
1911 // 2. `let mut s; s.x = Val;`
1915 // 3. `let mut s = ...; drop(s); s.x=Val;`
1917 // This does not use check_if_path_or_subpath_is_moved,
1918 // because we want to *allow* reinitializations of fields:
1919 // e.g., want to allow
1921 // `let mut s = ...; drop(s.x); s.x=Val;`
1923 // This does not use check_if_full_path_is_moved on
1924 // `base`, because that would report an error about the
1925 // `base` as a whole, but in this scenario we *really*
1926 // want to report an error about the actual thing that was
1927 // moved, which may be some prefix of `base`.
1929 // Shallow so that we'll stop at any dereference; we'll
1930 // report errors about issues with such bases elsewhere.
1931 let maybe_uninits = &flow_state.uninits;
1933 // Find the shortest uninitialized prefix you can reach
1934 // without going over a Deref.
1935 let mut shortest_uninit_seen = None;
1936 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1937 let mpi = match this.move_path_for_place(prefix) {
1942 if maybe_uninits.contains(mpi) {
1944 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1945 shortest_uninit_seen,
1948 shortest_uninit_seen = Some((prefix, mpi));
1950 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1954 if let Some((prefix, mpi)) = shortest_uninit_seen {
1955 // Check for a reassignment into a uninitialized field of a union (for example,
1956 // after a move out). In this case, do not report a error here. There is an
1957 // exception, if this is the first assignment into the union (that is, there is
1958 // no move out from an earlier location) then this is an attempt at initialization
1959 // of the union - we should error in that case.
1960 let tcx = this.infcx.tcx;
1961 if let ty::Adt(def, _) =
1962 Place::ty_from(base.local, base.projection, this.body(), tcx).ty.kind
1965 if this.move_data.path_map[mpi].iter().any(|moi| {
1966 this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
1973 this.report_use_of_moved_or_uninitialized(
1975 InitializationRequiringAction::PartialAssignment,
1976 (prefix, base, span),
1983 /// Checks the permissions for the given place and read or write kind
1985 /// Returns `true` if an error is reported.
1986 fn check_access_permissions(
1988 (place, span): (&Place<'tcx>, Span),
1990 is_local_mutation_allowed: LocalMutationIsAllowed,
1991 flow_state: &Flows<'cx, 'tcx>,
1995 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1996 place, kind, is_local_mutation_allowed
2003 Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
2004 | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
2005 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
2006 | Write(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. })) => {
2007 let is_local_mutation_allowed = match borrow_kind {
2008 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
2009 BorrowKind::Mut { .. } => is_local_mutation_allowed,
2010 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
2012 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2014 self.add_used_mut(root_place, flow_state);
2018 error_access = AccessKind::MutableBorrow;
2019 the_place_err = place_err;
2023 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
2024 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2026 self.add_used_mut(root_place, flow_state);
2030 error_access = AccessKind::Mutate;
2031 the_place_err = place_err;
2036 Reservation(WriteKind::Move)
2037 | Write(WriteKind::Move)
2038 | Reservation(WriteKind::StorageDeadOrDrop)
2039 | Reservation(WriteKind::MutableBorrow(BorrowKind::Shared))
2040 | Reservation(WriteKind::MutableBorrow(BorrowKind::Shallow))
2041 | Write(WriteKind::StorageDeadOrDrop)
2042 | Write(WriteKind::MutableBorrow(BorrowKind::Shared))
2043 | Write(WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
2044 if let (Err(_), true) = (
2045 self.is_mutable(place.as_ref(), is_local_mutation_allowed),
2046 self.errors_buffer.is_empty(),
2048 // rust-lang/rust#46908: In pure NLL mode this code path should be
2049 // unreachable, but we use `delay_span_bug` because we can hit this when
2050 // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
2051 // enabled. We don't want to ICE for that case, as other errors will have
2052 // been emitted (#52262).
2053 self.infcx.tcx.sess.delay_span_bug(
2056 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2064 // permission checks are done at Reservation point.
2067 Read(ReadKind::Borrow(BorrowKind::Unique))
2068 | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
2069 | Read(ReadKind::Borrow(BorrowKind::Shared))
2070 | Read(ReadKind::Borrow(BorrowKind::Shallow))
2071 | Read(ReadKind::Copy) => {
2072 // Access authorized
2077 // rust-lang/rust#21232, #54986: during period where we reject
2078 // partial initialization, do not complain about mutability
2079 // errors except for actual mutation (as opposed to an attempt
2080 // to do a partial initialization).
2081 let previously_initialized =
2082 self.is_local_ever_initialized(place.local, flow_state).is_some();
2084 // at this point, we have set up the error reporting state.
2085 if previously_initialized {
2086 self.report_mutability_error(place, span, the_place_err, error_access, location);
2093 fn is_local_ever_initialized(
2096 flow_state: &Flows<'cx, 'tcx>,
2097 ) -> Option<InitIndex> {
2098 let mpi = self.move_data.rev_lookup.find_local(local);
2099 let ii = &self.move_data.init_path_map[mpi];
2101 if flow_state.ever_inits.contains(index) {
2108 /// Adds the place into the used mutable variables set
2109 fn add_used_mut<'d>(&mut self, root_place: RootPlace<'d, 'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2111 RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2112 // If the local may have been initialized, and it is now currently being
2113 // mutated, then it is justified to be annotated with the `mut`
2114 // keyword, since the mutation may be a possible reassignment.
2115 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2116 && self.is_local_ever_initialized(*local, flow_state).is_some()
2118 self.used_mut.insert(*local);
2123 place_projection: _,
2124 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2128 place_projection: place_projection @ [.., _],
2129 is_local_mutation_allowed: _,
2131 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2133 projection: place_projection,
2135 self.used_mut_upvars.push(field);
2141 /// Whether this value can be written or borrowed mutably.
2142 /// Returns the root place if the place passed in is a projection.
2145 place: PlaceRef<'d, 'tcx>,
2146 is_local_mutation_allowed: LocalMutationIsAllowed,
2147 ) -> Result<RootPlace<'d, 'tcx>, PlaceRef<'d, 'tcx>> {
2149 PlaceRef { local, projection: [] } => {
2150 let local = &self.body.local_decls[*local];
2151 match local.mutability {
2152 Mutability::Not => match is_local_mutation_allowed {
2153 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2154 place_local: place.local,
2155 place_projection: place.projection,
2156 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2158 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2159 place_local: place.local,
2160 place_projection: place.projection,
2161 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2163 LocalMutationIsAllowed::No => Err(place),
2165 Mutability::Mut => Ok(RootPlace {
2166 place_local: place.local,
2167 place_projection: place.projection,
2168 is_local_mutation_allowed,
2172 PlaceRef { local: _, projection: [proj_base @ .., elem] } => {
2174 ProjectionElem::Deref => {
2176 Place::ty_from(place.local, proj_base, self.body(), self.infcx.tcx).ty;
2178 // Check the kind of deref to decide
2179 match base_ty.kind {
2180 ty::Ref(_, _, mutbl) => {
2182 // Shared borrowed data is never mutable
2183 hir::Mutability::Not => Err(place),
2184 // Mutably borrowed data is mutable, but only if we have a
2185 // unique path to the `&mut`
2186 hir::Mutability::Mut => {
2187 let mode = match self.is_upvar_field_projection(place) {
2188 Some(field) if self.upvars[field.index()].by_ref => {
2189 is_local_mutation_allowed
2191 _ => LocalMutationIsAllowed::Yes,
2195 PlaceRef { local: place.local, projection: proj_base },
2201 ty::RawPtr(tnm) => {
2203 // `*const` raw pointers are not mutable
2204 hir::Mutability::Not => Err(place),
2205 // `*mut` raw pointers are always mutable, regardless of
2206 // context. The users have to check by themselves.
2207 hir::Mutability::Mut => Ok(RootPlace {
2208 place_local: place.local,
2209 place_projection: place.projection,
2210 is_local_mutation_allowed,
2214 // `Box<T>` owns its content, so mutable if its location is mutable
2215 _ if base_ty.is_box() => self.is_mutable(
2216 PlaceRef { local: place.local, projection: proj_base },
2217 is_local_mutation_allowed,
2219 // Deref should only be for reference, pointers or boxes
2220 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2223 // All other projections are owned by their base path, so mutable if
2224 // base path is mutable
2225 ProjectionElem::Field(..)
2226 | ProjectionElem::Index(..)
2227 | ProjectionElem::ConstantIndex { .. }
2228 | ProjectionElem::Subslice { .. }
2229 | ProjectionElem::Downcast(..) => {
2230 let upvar_field_projection = self.is_upvar_field_projection(place);
2231 if let Some(field) = upvar_field_projection {
2232 let upvar = &self.upvars[field.index()];
2234 "upvar.mutability={:?} local_mutation_is_allowed={:?} \
2236 upvar, is_local_mutation_allowed, place
2238 match (upvar.mutability, is_local_mutation_allowed) {
2239 (Mutability::Not, LocalMutationIsAllowed::No)
2240 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
2243 (Mutability::Not, LocalMutationIsAllowed::Yes)
2244 | (Mutability::Mut, _) => {
2245 // Subtle: this is an upvar
2246 // reference, so it looks like
2247 // `self.foo` -- we want to double
2248 // check that the location `*self`
2249 // is mutable (i.e., this is not a
2250 // `Fn` closure). But if that
2251 // check succeeds, we want to
2252 // *blame* the mutability on
2253 // `place` (that is,
2254 // `self.foo`). This is used to
2255 // propagate the info about
2256 // whether mutability declarations
2257 // are used outwards, so that we register
2258 // the outer variable as mutable. Otherwise a
2259 // test like this fails to record the `mut`
2263 // fn foo<F: FnOnce()>(_f: F) { }
2265 // let var = Vec::new();
2271 let _ = self.is_mutable(
2272 PlaceRef { local: place.local, projection: proj_base },
2273 is_local_mutation_allowed,
2276 place_local: place.local,
2277 place_projection: place.projection,
2278 is_local_mutation_allowed,
2284 PlaceRef { local: place.local, projection: proj_base },
2285 is_local_mutation_allowed,
2294 /// If `place` is a field projection, and the field is being projected from a closure type,
2295 /// then returns the index of the field being projected. Note that this closure will always
2296 /// be `self` in the current MIR, because that is the only time we directly access the fields
2297 /// of a closure type.
2298 pub fn is_upvar_field_projection(&self, place_ref: PlaceRef<'cx, 'tcx>) -> Option<Field> {
2299 let mut place_projection = place_ref.projection;
2300 let mut by_ref = false;
2302 if let [proj_base @ .., ProjectionElem::Deref] = place_projection {
2303 place_projection = proj_base;
2307 match place_projection {
2308 [base @ .., ProjectionElem::Field(field, _ty)] => {
2309 let tcx = self.infcx.tcx;
2310 let base_ty = Place::ty_from(place_ref.local, base, self.body(), tcx).ty;
2312 if (base_ty.is_closure() || base_ty.is_generator())
2313 && (!by_ref || self.upvars[field.index()].by_ref)
2326 /// The degree of overlap between 2 places for borrow-checking.
2328 /// The places might partially overlap - in this case, we give
2329 /// up and say that they might conflict. This occurs when
2330 /// different fields of a union are borrowed. For example,
2331 /// if `u` is a union, we have no way of telling how disjoint
2332 /// `u.a.x` and `a.b.y` are.
2334 /// The places have the same type, and are either completely disjoint
2335 /// or equal - i.e., they can't "partially" overlap as can occur with
2336 /// unions. This is the "base case" on which we recur for extensions
2339 /// The places are disjoint, so we know all extensions of them
2340 /// will also be disjoint.