1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This query borrow-checks the MIR to (further) ensure it is not broken.
13 use borrow_check::nll::region_infer::{RegionCausalInfo, RegionInferenceContext};
15 use rustc::hir::def_id::DefId;
16 use rustc::hir::map::definitions::DefPathData;
17 use rustc::infer::InferCtxt;
18 use rustc::ty::{self, ParamEnv, TyCtxt};
19 use rustc::ty::maps::Providers;
20 use rustc::lint::builtin::UNUSED_MUT;
21 use rustc::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
22 use rustc::mir::{ClearCrossCrate, Local, Location, Place, Mir, Mutability, Operand};
23 use rustc::mir::{Projection, ProjectionElem, Rvalue, Field, Statement, StatementKind};
24 use rustc::mir::{Terminator, TerminatorKind};
26 use rustc_data_structures::control_flow_graph::dominators::Dominators;
27 use rustc_data_structures::fx::FxHashSet;
28 use rustc_data_structures::indexed_set::IdxSetBuf;
29 use rustc_data_structures::indexed_vec::Idx;
30 use rustc_data_structures::small_vec::SmallVec;
36 use dataflow::{do_dataflow, DebugFormatted};
37 use dataflow::FlowAtLocation;
38 use dataflow::MoveDataParamEnv;
39 use dataflow::{DataflowResultsConsumer};
40 use dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
41 use dataflow::{EverInitializedPlaces, MovingOutStatements};
42 use dataflow::Borrows;
43 use dataflow::indexes::BorrowIndex;
44 use dataflow::move_paths::{IllegalMoveOriginKind, MoveError};
45 use dataflow::move_paths::{HasMoveData, LookupResult, MoveData, MovePathIndex};
46 use util::borrowck_errors::{BorrowckErrors, Origin};
47 use util::collect_writes::FindAssignments;
51 use self::borrow_set::{BorrowSet, BorrowData};
52 use self::flows::Flows;
53 use self::prefixes::PrefixSet;
54 use self::MutateMode::{JustWrite, WriteAndRead};
64 pub fn provide(providers: &mut Providers) {
65 *providers = Providers {
71 fn mir_borrowck<'a, 'tcx>(
72 tcx: TyCtxt<'a, 'tcx, 'tcx>,
74 ) -> BorrowCheckResult<'tcx> {
75 let input_mir = tcx.mir_validated(def_id);
76 debug!("run query mir_borrowck: {}", tcx.item_path_str(def_id));
78 if !tcx.has_attr(def_id, "rustc_mir_borrowck") && !tcx.use_mir_borrowck() {
79 return BorrowCheckResult {
80 closure_requirements: None,
81 used_mut_upvars: SmallVec::new(),
85 let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
86 let input_mir: &Mir = &input_mir.borrow();
87 do_mir_borrowck(&infcx, input_mir, def_id)
89 debug!("mir_borrowck done");
94 fn do_mir_borrowck<'a, 'gcx, 'tcx>(
95 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
96 input_mir: &Mir<'gcx>,
98 ) -> BorrowCheckResult<'gcx> {
100 let attributes = tcx.get_attrs(def_id);
101 let param_env = tcx.param_env(def_id);
103 .as_local_node_id(def_id)
104 .expect("do_mir_borrowck: non-local DefId");
106 // Replace all regions with fresh inference variables. This
107 // requires first making our own copy of the MIR. This copy will
108 // be modified (in place) to contain non-lexical lifetimes. It
109 // will have a lifetime tied to the inference context.
110 let mut mir: Mir<'tcx> = input_mir.clone();
111 let free_regions = nll::replace_regions_in_mir(infcx, def_id, param_env, &mut mir);
112 let mir = &mir; // no further changes
114 let move_data: MoveData<'tcx> = match MoveData::gather_moves(mir, tcx) {
115 Ok(move_data) => move_data,
116 Err((move_data, move_errors)) => {
117 for move_error in move_errors {
118 let (span, kind): (Span, IllegalMoveOriginKind) = match move_error {
119 MoveError::UnionMove { .. } => {
120 unimplemented!("don't know how to report union move errors yet.")
122 MoveError::IllegalMove {
123 cannot_move_out_of: o,
124 } => (o.span, o.kind),
126 let origin = Origin::Mir;
127 let mut err = match kind {
128 IllegalMoveOriginKind::Static => {
129 tcx.cannot_move_out_of(span, "static item", origin)
131 IllegalMoveOriginKind::BorrowedContent => {
132 tcx.cannot_move_out_of(span, "borrowed content", origin)
134 IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
135 tcx.cannot_move_out_of_interior_of_drop(span, ty, origin)
137 IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => {
138 tcx.cannot_move_out_of_interior_noncopy(span, ty, is_index, origin)
147 let mdpe = MoveDataParamEnv {
148 move_data: move_data,
149 param_env: param_env,
151 let body_id = match tcx.def_key(def_id).disambiguated_data.data {
152 DefPathData::StructCtor | DefPathData::EnumVariant(_) => None,
153 _ => Some(tcx.hir.body_owned_by(id)),
156 let dead_unwinds = IdxSetBuf::new_empty(mir.basic_blocks().len());
157 let mut flow_inits = FlowAtLocation::new(do_dataflow(
163 MaybeInitializedPlaces::new(tcx, mir, &mdpe),
164 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
166 let flow_uninits = FlowAtLocation::new(do_dataflow(
172 MaybeUninitializedPlaces::new(tcx, mir, &mdpe),
173 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
175 let flow_move_outs = FlowAtLocation::new(do_dataflow(
181 MovingOutStatements::new(tcx, mir, &mdpe),
182 |bd, i| DebugFormatted::new(&bd.move_data().moves[i]),
184 let flow_ever_inits = FlowAtLocation::new(do_dataflow(
190 EverInitializedPlaces::new(tcx, mir, &mdpe),
191 |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
194 let borrow_set = Rc::new(BorrowSet::build(tcx, mir));
196 // If we are in non-lexical mode, compute the non-lexical lifetimes.
197 let (regioncx, opt_closure_req) = nll::compute_regions(
207 let regioncx = Rc::new(regioncx);
208 let flow_inits = flow_inits; // remove mut
210 let flow_borrows = FlowAtLocation::new(do_dataflow(
216 Borrows::new(tcx, mir, regioncx.clone(), def_id, body_id, &borrow_set),
217 |rs, i| DebugFormatted::new(&rs.location(i)),
220 let movable_generator = match tcx.hir.get(id) {
221 hir::map::Node::NodeExpr(&hir::Expr {
222 node: hir::ExprClosure(.., Some(hir::GeneratorMovability::Static)),
228 let dominators = mir.dominators();
230 let mut mbcx = MirBorrowckCtxt {
234 move_data: &mdpe.move_data,
235 param_env: param_env,
237 locals_are_invalidated_at_exit: match tcx.hir.body_owner_kind(id) {
238 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => false,
239 hir::BodyOwnerKind::Fn => true,
241 access_place_error_reported: FxHashSet(),
242 reservation_error_reported: FxHashSet(),
243 moved_error_reported: FxHashSet(),
244 nonlexical_regioncx: regioncx,
245 used_mut: FxHashSet(),
246 used_mut_upvars: SmallVec::new(),
247 nonlexical_cause_info: None,
252 let mut state = Flows::new(
260 mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
262 // For each non-user used mutable variable, check if it's been assigned from
263 // a user-declared local. If so, then put that local into the used_mut set.
264 // Note that this set is expected to be small - only upvars from closures
265 // would have a chance of erroneously adding non-user-defined mutable vars
267 let temporary_used_locals: FxHashSet<Local> =
269 .filter(|&local| !mbcx.mir.local_decls[*local].is_user_variable)
273 for local in temporary_used_locals {
274 for location in mbcx.mir.find_assignments(local) {
275 for moi in &mbcx.move_data.loc_map[location] {
276 let mpi = &mbcx.move_data.moves[*moi].path;
277 let path = &mbcx.move_data.move_paths[*mpi];
278 debug!("assignment of {:?} to {:?}, adding {:?} to used mutable set",
279 path.place, local, path.place);
280 if let Place::Local(user_local) = path.place {
281 mbcx.used_mut.insert(user_local);
287 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
289 for local in mbcx.mir.mut_vars_and_args_iter().filter(|local| !mbcx.used_mut.contains(local)) {
290 if let ClearCrossCrate::Set(ref vsi) = mbcx.mir.visibility_scope_info {
291 let local_decl = &mbcx.mir.local_decls[local];
293 // Skip implicit `self` argument for closures
294 if local.index() == 1 && tcx.is_closure(mbcx.mir_def_id) {
298 // Skip over locals that begin with an underscore
299 match local_decl.name {
300 Some(name) if name.as_str().starts_with("_") => continue,
304 let source_info = local_decl.source_info;
305 let mut_span = tcx.sess.codemap().span_until_non_whitespace(source_info.span);
307 tcx.struct_span_lint_node(
309 vsi[local_decl.syntactic_scope].lint_root,
311 "variable does not need to be mutable"
313 .span_suggestion_short(mut_span, "remove this `mut`", "".to_owned())
319 closure_requirements: opt_closure_req,
320 used_mut_upvars: mbcx.used_mut_upvars,
325 pub struct MirBorrowckCtxt<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
326 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
329 move_data: &'cx MoveData<'tcx>,
330 param_env: ParamEnv<'gcx>,
331 movable_generator: bool,
332 /// This keeps track of whether local variables are free-ed when the function
333 /// exits even without a `StorageDead`, which appears to be the case for
336 /// I'm not sure this is the right approach - @eddyb could you try and
338 locals_are_invalidated_at_exit: bool,
339 /// This field keeps track of when borrow errors are reported in the access_place function
340 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
341 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
342 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
344 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
345 /// This field keeps track of when borrow conflict errors are reported
346 /// for reservations, so that we don't report seemingly duplicate
347 /// errors for corresponding activations
349 /// FIXME: Ideally this would be a set of BorrowIndex, not Places,
350 /// but it is currently inconvenient to track down the BorrowIndex
351 /// at the time we detect and report a reservation error.
352 reservation_error_reported: FxHashSet<Place<'tcx>>,
353 /// This field keeps track of errors reported in the checking of moved variables,
354 /// so that we don't report report seemingly duplicate errors.
355 moved_error_reported: FxHashSet<Place<'tcx>>,
356 /// This field keeps track of all the local variables that are declared mut and are mutated.
357 /// Used for the warning issued by an unused mutable local variable.
358 used_mut: FxHashSet<Local>,
359 /// If the function we're checking is a closure, then we'll need to report back the list of
360 /// mutable upvars that have been used. This field keeps track of them.
361 used_mut_upvars: SmallVec<[Field; 8]>,
362 /// Non-lexical region inference context, if NLL is enabled. This
363 /// contains the results from region inference and lets us e.g.
364 /// find out which CFG points are contained in each borrow region.
365 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
366 nonlexical_cause_info: Option<RegionCausalInfo>,
368 /// The set of borrows extracted from the MIR
369 borrow_set: Rc<BorrowSet<'tcx>>,
371 /// Dominators for MIR
372 dominators: Dominators<BasicBlock>,
376 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
377 // 2. loans made in overlapping scopes do not conflict
378 // 3. assignments do not affect things loaned out as immutable
379 // 4. moves do not affect things loaned out in any way
380 impl<'cx, 'gcx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
381 type FlowState = Flows<'cx, 'gcx, 'tcx>;
383 fn mir(&self) -> &'cx Mir<'tcx> {
387 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
388 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
391 fn visit_statement_entry(
394 stmt: &Statement<'tcx>,
395 flow_state: &Self::FlowState,
398 "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
399 location, stmt, flow_state
401 let span = stmt.source_info.span;
403 self.check_activations(location, span, flow_state);
406 StatementKind::Assign(ref lhs, ref rhs) => {
408 ContextKind::AssignRhs.new(location),
415 ContextKind::AssignLhs.new(location),
422 StatementKind::SetDiscriminant {
427 ContextKind::SetDiscrim.new(location),
429 Shallow(Some(ArtificialField::Discriminant)),
434 StatementKind::InlineAsm {
439 let context = ContextKind::InlineAsm.new(location);
440 for (o, output) in asm.outputs.iter().zip(outputs) {
442 // FIXME(eddyb) indirect inline asm outputs should
443 // be encoeded through MIR place derefs instead.
447 (Deep, Read(ReadKind::Copy)),
448 LocalMutationIsAllowed::No,
451 self.check_if_path_or_subpath_is_moved(
453 InitializationRequiringAction::Use,
461 if o.is_rw { Deep } else { Shallow(None) },
462 if o.is_rw { WriteAndRead } else { JustWrite },
467 for input in inputs {
468 self.consume_operand(context, (input, span), flow_state);
471 StatementKind::EndRegion(ref _rgn) => {
472 // ignored when consuming results (update to
473 // flow_state already handled).
476 StatementKind::UserAssertTy(..) |
477 StatementKind::Validate(..) |
478 StatementKind::StorageLive(..) => {
479 // `Nop`, `UserAssertTy`, `Validate`, and `StorageLive` are irrelevant
482 StatementKind::StorageDead(local) => {
484 ContextKind::StorageDead.new(location),
485 (&Place::Local(local), span),
486 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
487 LocalMutationIsAllowed::Yes,
494 fn visit_terminator_entry(
497 term: &Terminator<'tcx>,
498 flow_state: &Self::FlowState,
502 "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
503 location, term, flow_state
505 let span = term.source_info.span;
507 self.check_activations(location, span, flow_state);
510 TerminatorKind::SwitchInt {
516 self.consume_operand(ContextKind::SwitchInt.new(loc), (discr, span), flow_state);
518 TerminatorKind::Drop {
519 location: ref drop_place,
523 let gcx = self.tcx.global_tcx();
525 // Compute the type with accurate region information.
526 let drop_place_ty = drop_place.ty(self.mir, self.tcx);
528 // Erase the regions.
529 let drop_place_ty = self.tcx.erase_regions(&drop_place_ty).to_ty(self.tcx);
531 // "Lift" into the gcx -- once regions are erased, this type should be in the
532 // global arenas; this "lift" operation basically just asserts that is true, but
533 // that is useful later.
534 let drop_place_ty = gcx.lift(&drop_place_ty).unwrap();
536 self.visit_terminator_drop(loc, term, flow_state, drop_place, drop_place_ty, span);
538 TerminatorKind::DropAndReplace {
539 location: ref drop_place,
540 value: ref new_value,
545 ContextKind::DropAndReplace.new(loc),
551 self.consume_operand(
552 ContextKind::DropAndReplace.new(loc),
557 TerminatorKind::Call {
563 self.consume_operand(ContextKind::CallOperator.new(loc), (func, span), flow_state);
565 self.consume_operand(
566 ContextKind::CallOperand.new(loc),
571 if let Some((ref dest, _ /*bb*/)) = *destination {
573 ContextKind::CallDest.new(loc),
581 TerminatorKind::Assert {
588 self.consume_operand(ContextKind::Assert.new(loc), (cond, span), flow_state);
589 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
590 if let BoundsCheck { ref len, ref index } = *msg {
591 self.consume_operand(ContextKind::Assert.new(loc), (len, span), flow_state);
592 self.consume_operand(
593 ContextKind::Assert.new(loc),
600 TerminatorKind::Yield {
605 self.consume_operand(ContextKind::Yield.new(loc), (value, span), flow_state);
607 if self.movable_generator {
608 // Look for any active borrows to locals
609 let borrow_set = self.borrow_set.clone();
610 flow_state.with_outgoing_borrows(|borrows| {
612 let borrow = &borrow_set[i];
613 self.check_for_local_borrow(borrow, span);
619 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
620 // Returning from the function implicitly kills storage for all locals and statics.
621 // Often, the storage will already have been killed by an explicit
622 // StorageDead, but we don't always emit those (notably on unwind paths),
623 // so this "extra check" serves as a kind of backup.
624 let borrow_set = self.borrow_set.clone();
625 flow_state.with_outgoing_borrows(|borrows| {
627 let borrow = &borrow_set[i];
628 let context = ContextKind::StorageDead.new(loc);
629 self.check_for_invalidation_at_exit(context, borrow, span);
633 TerminatorKind::Goto { target: _ }
634 | TerminatorKind::Abort
635 | TerminatorKind::Unreachable
636 | TerminatorKind::FalseEdges {
638 imaginary_targets: _,
640 | TerminatorKind::FalseUnwind {
644 // no data used, thus irrelevant to borrowck
650 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
656 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
662 use self::ShallowOrDeep::{Deep, Shallow};
663 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
665 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
666 enum ArtificialField {
671 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
673 /// From the RFC: "A *shallow* access means that the immediate
674 /// fields reached at P are accessed, but references or pointers
675 /// found within are not dereferenced. Right now, the only access
676 /// that is shallow is an assignment like `x = ...;`, which would
677 /// be a *shallow write* of `x`."
678 Shallow(Option<ArtificialField>),
680 /// From the RFC: "A *deep* access means that all data reachable
681 /// through the given place may be invalidated or accesses by
686 /// Kind of access to a value: read or write
687 /// (For informational purposes only)
688 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
690 /// From the RFC: "A *read* means that the existing data may be
691 /// read, but will not be changed."
694 /// From the RFC: "A *write* means that the data may be mutated to
695 /// new values or otherwise invalidated (for example, it could be
696 /// de-initialized, as in a move operation).
699 /// For two-phase borrows, we distinguish a reservation (which is treated
700 /// like a Read) from an activation (which is treated like a write), and
701 /// each of those is furthermore distinguished from Reads/Writes above.
702 Reservation(WriteKind),
703 Activation(WriteKind, BorrowIndex),
706 /// Kind of read access to a value
707 /// (For informational purposes only)
708 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
714 /// Kind of write access to a value
715 /// (For informational purposes only)
716 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
719 MutableBorrow(BorrowKind),
724 /// When checking permissions for a place access, this flag is used to indicate that an immutable
725 /// local place can be mutated.
727 /// FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
728 /// - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`
729 /// - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
730 /// `is_declared_mutable()`
731 /// - Take flow state into consideration in `is_assignable()` for local variables
732 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
733 enum LocalMutationIsAllowed {
735 /// We want use of immutable upvars to cause a "write to immutable upvar"
736 /// error, not an "reassignment" error.
741 struct AccessErrorsReported {
742 mutability_error: bool,
744 conflict_error: bool,
747 #[derive(Copy, Clone)]
748 enum InitializationRequiringAction {
755 struct RootPlace<'d, 'tcx: 'd> {
756 place: &'d Place<'tcx>,
757 is_local_mutation_allowed: LocalMutationIsAllowed,
760 impl InitializationRequiringAction {
761 fn as_noun(self) -> &'static str {
763 InitializationRequiringAction::Update => "update",
764 InitializationRequiringAction::Borrow => "borrow",
765 InitializationRequiringAction::Use => "use",
766 InitializationRequiringAction::Assignment => "assign",
770 fn as_verb_in_past_tense(self) -> &'static str {
772 InitializationRequiringAction::Update => "updated",
773 InitializationRequiringAction::Borrow => "borrowed",
774 InitializationRequiringAction::Use => "used",
775 InitializationRequiringAction::Assignment => "assigned",
780 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
781 /// Returns true if the borrow represented by `kind` is
782 /// allowed to be split into separate Reservation and
783 /// Activation phases.
784 fn allow_two_phase_borrow(&self, kind: BorrowKind) -> bool {
785 self.tcx.two_phase_borrows()
786 && (kind.allows_two_phase_borrow()
787 || self.tcx.sess.opts.debugging_opts.two_phase_beyond_autoref)
790 /// Invokes `access_place` as appropriate for dropping the value
791 /// at `drop_place`. Note that the *actual* `Drop` in the MIR is
792 /// always for a variable (e.g., `Drop(x)`) -- but we recursively
793 /// break this variable down into subpaths (e.g., `Drop(x.foo)`)
794 /// to indicate more precisely which fields might actually be
795 /// accessed by a destructor.
796 fn visit_terminator_drop(
799 term: &Terminator<'tcx>,
800 flow_state: &Flows<'cx, 'gcx, 'tcx>,
801 drop_place: &Place<'tcx>,
802 erased_drop_place_ty: ty::Ty<'gcx>,
805 let gcx = self.tcx.global_tcx();
807 mir: &mut MirBorrowckCtxt<'cx, 'gcx, 'tcx>,
808 (index, field): (usize, ty::Ty<'gcx>),
810 let field_ty = gcx.normalize_erasing_regions(mir.param_env, field);
811 let place = drop_place.clone().field(Field::new(index), field_ty);
813 mir.visit_terminator_drop(loc, term, flow_state, &place, field_ty, span);
816 match erased_drop_place_ty.sty {
817 // When a struct is being dropped, we need to check
818 // whether it has a destructor, if it does, then we can
819 // call it, if it does not then we need to check the
820 // individual fields instead. This way if `foo` has a
821 // destructor but `bar` does not, we will only check for
822 // borrows of `x.foo` and not `x.bar`. See #47703.
823 ty::TyAdt(def, substs) if def.is_struct() && !def.has_dtor(self.tcx) => {
825 .map(|field| field.ty(gcx, substs))
827 .for_each(|field| drop_field(self, field));
829 // Same as above, but for tuples.
830 ty::TyTuple(tys) => {
831 tys.iter().cloned().enumerate()
832 .for_each(|field| drop_field(self, field));
834 // Closures and generators also have disjoint fields, but they are only
835 // directly accessed in the body of the closure/generator.
836 ty::TyClosure(def, substs)
837 | ty::TyGenerator(def, substs, ..)
838 if *drop_place == Place::Local(Local::new(1)) && !self.mir.upvar_decls.is_empty()
840 substs.upvar_tys(def, self.tcx).enumerate()
841 .for_each(|field| drop_field(self, field));
844 // We have now refined the type of the value being
845 // dropped (potentially) to just the type of a
846 // subfield; so check whether that field's type still
847 // "needs drop". If so, we assume that the destructor
848 // may access any data it likes (i.e., a Deep Write).
849 if erased_drop_place_ty.needs_drop(gcx, self.param_env) {
851 ContextKind::Drop.new(loc),
853 (Deep, Write(WriteKind::StorageDeadOrDrop)),
854 LocalMutationIsAllowed::Yes,
862 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
863 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
864 /// place is initialized and (b) it is not borrowed in some way that would prevent this
867 /// Returns true if an error is reported, false otherwise.
871 place_span: (&Place<'tcx>, Span),
872 kind: (ShallowOrDeep, ReadOrWrite),
873 is_local_mutation_allowed: LocalMutationIsAllowed,
874 flow_state: &Flows<'cx, 'gcx, 'tcx>,
875 ) -> AccessErrorsReported {
878 if let Activation(_, borrow_index) = rw {
879 if self.reservation_error_reported.contains(&place_span.0) {
881 "skipping access_place for activation of invalid reservation \
882 place: {:?} borrow_index: {:?}",
883 place_span.0, borrow_index
885 return AccessErrorsReported {
886 mutability_error: false,
887 conflict_error: true,
892 if self.access_place_error_reported
893 .contains(&(place_span.0.clone(), place_span.1))
896 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
899 return AccessErrorsReported {
900 mutability_error: false,
901 conflict_error: true,
905 let mutability_error =
906 self.check_access_permissions(place_span, rw, is_local_mutation_allowed, flow_state);
908 self.check_access_for_conflict(context, place_span, sd, rw, flow_state);
910 if conflict_error || mutability_error {
912 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
915 self.access_place_error_reported
916 .insert((place_span.0.clone(), place_span.1));
919 AccessErrorsReported {
925 fn check_access_for_conflict(
928 place_span: (&Place<'tcx>, Span),
931 flow_state: &Flows<'cx, 'gcx, 'tcx>,
934 "check_access_for_conflict(context={:?}, place_span={:?}, sd={:?}, rw={:?})",
941 let mut error_reported = false;
942 self.each_borrow_involving_path(
946 |this, borrow_index, borrow| match (rw, borrow.kind) {
947 // Obviously an activation is compatible with its own
948 // reservation (or even prior activating uses of same
949 // borrow); so don't check if they interfere.
951 // NOTE: *reservations* do conflict with themselves;
952 // thus aren't injecting unsoundenss w/ this check.)
953 (Activation(_, activating), _) if activating == borrow_index => {
955 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
956 skipping {:?} b/c activation of same borrow_index",
960 (borrow_index, borrow),
965 (Read(_), BorrowKind::Shared) | (Reservation(..), BorrowKind::Shared) => {
969 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
970 // Reading from mere reservations of mutable-borrows is OK.
971 if !this.is_active(borrow, context.loc) {
972 assert!(this.allow_two_phase_borrow(borrow.kind));
973 return Control::Continue;
978 error_reported = true;
979 this.report_use_while_mutably_borrowed(context, place_span, borrow)
981 ReadKind::Borrow(bk) => {
982 error_reported = true;
983 this.report_conflicting_borrow(
994 (Reservation(kind), BorrowKind::Unique)
995 | (Reservation(kind), BorrowKind::Mut { .. })
996 | (Activation(kind, _), _)
997 | (Write(kind), _) => {
1001 "recording invalid reservation of \
1005 this.reservation_error_reported.insert(place_span.0.clone());
1007 Activation(_, activating) => {
1009 "observing check_place for activation of \
1010 borrow_index: {:?}",
1014 Read(..) | Write(..) => {}
1018 WriteKind::MutableBorrow(bk) => {
1019 error_reported = true;
1020 this.report_conflicting_borrow(
1027 WriteKind::StorageDeadOrDrop => {
1028 error_reported = true;
1029 this.report_borrowed_value_does_not_live_long_enough(
1035 WriteKind::Mutate => {
1036 error_reported = true;
1037 this.report_illegal_mutation_of_borrowed(context, place_span, borrow)
1039 WriteKind::Move => {
1040 error_reported = true;
1041 this.report_move_out_while_borrowed(context, place_span, &borrow)
1055 place_span: (&Place<'tcx>, Span),
1056 kind: ShallowOrDeep,
1058 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1060 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1062 MutateMode::WriteAndRead => {
1063 self.check_if_path_or_subpath_is_moved(
1065 InitializationRequiringAction::Update,
1070 MutateMode::JustWrite => {
1071 self.check_if_assigned_path_is_moved(context, place_span, flow_state);
1075 let errors_reported = self.access_place(
1078 (kind, Write(WriteKind::Mutate)),
1079 // We want immutable upvars to cause an "assignment to immutable var"
1080 // error, not an "reassignment of immutable var" error, because the
1081 // latter can't find a good previous assignment span.
1083 // There's probably a better way to do this.
1084 LocalMutationIsAllowed::ExceptUpvars,
1088 if !errors_reported.mutability_error {
1089 // check for reassignments to immutable local variables
1090 self.check_if_reassignment_to_immutable_state(context, place_span, flow_state);
1097 (rvalue, span): (&Rvalue<'tcx>, Span),
1098 _location: Location,
1099 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1102 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1103 let access_kind = match bk {
1104 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1105 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1106 let wk = WriteKind::MutableBorrow(bk);
1107 if self.allow_two_phase_borrow(bk) {
1108 (Deep, Reservation(wk))
1119 LocalMutationIsAllowed::No,
1123 self.check_if_path_or_subpath_is_moved(
1125 InitializationRequiringAction::Borrow,
1131 Rvalue::Use(ref operand)
1132 | Rvalue::Repeat(ref operand, _)
1133 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1134 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1135 self.consume_operand(context, (operand, span), flow_state)
1138 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1139 let af = match *rvalue {
1140 Rvalue::Len(..) => ArtificialField::ArrayLength,
1141 Rvalue::Discriminant(..) => ArtificialField::Discriminant,
1142 _ => unreachable!(),
1147 (Shallow(Some(af)), Read(ReadKind::Copy)),
1148 LocalMutationIsAllowed::No,
1151 self.check_if_path_or_subpath_is_moved(
1153 InitializationRequiringAction::Use,
1159 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1160 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1161 self.consume_operand(context, (operand1, span), flow_state);
1162 self.consume_operand(context, (operand2, span), flow_state);
1165 Rvalue::NullaryOp(_op, _ty) => {
1166 // nullary ops take no dynamic input; no borrowck effect.
1168 // FIXME: is above actually true? Do we want to track
1169 // the fact that uninitialized data can be created via
1173 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1174 // We need to report back the list of mutable upvars that were
1175 // moved into the closure and subsequently used by the closure,
1176 // in order to populate our used_mut set.
1177 if let AggregateKind::Closure(def_id, _) = &**aggregate_kind {
1178 let BorrowCheckResult { used_mut_upvars, .. } = self.tcx.mir_borrowck(*def_id);
1179 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1180 for field in used_mut_upvars {
1181 match operands[field.index()] {
1182 Operand::Move(Place::Local(local)) => {
1183 self.used_mut.insert(local);
1185 Operand::Move(ref place @ Place::Projection(_)) => {
1186 if let Some(field) = self.is_upvar_field_projection(place) {
1187 self.used_mut_upvars.push(field);
1190 Operand::Move(Place::Static(..)) |
1192 Operand::Constant(..) => {}
1197 for operand in operands {
1198 self.consume_operand(context, (operand, span), flow_state);
1207 (operand, span): (&Operand<'tcx>, Span),
1208 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1211 Operand::Copy(ref place) => {
1212 // copy of place: check if this is "copy of frozen path"
1213 // (FIXME: see check_loans.rs)
1217 (Deep, Read(ReadKind::Copy)),
1218 LocalMutationIsAllowed::No,
1222 // Finally, check if path was already moved.
1223 self.check_if_path_or_subpath_is_moved(
1225 InitializationRequiringAction::Use,
1230 Operand::Move(ref place) => {
1231 // move of place: check if this is move of already borrowed path
1235 (Deep, Write(WriteKind::Move)),
1236 LocalMutationIsAllowed::Yes,
1240 // Finally, check if path was already moved.
1241 self.check_if_path_or_subpath_is_moved(
1243 InitializationRequiringAction::Use,
1248 Operand::Constant(_) => {}
1252 /// Returns whether a borrow of this place is invalidated when the function
1254 fn check_for_invalidation_at_exit(
1257 borrow: &BorrowData<'tcx>,
1260 debug!("check_for_invalidation_at_exit({:?})", borrow);
1261 let place = &borrow.borrowed_place;
1262 let root_place = self.prefixes(place, PrefixSet::All).last().unwrap();
1264 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1265 // we just know that all locals are dropped at function exit (otherwise
1266 // we'll have a memory leak) and assume that all statics have a destructor.
1268 // FIXME: allow thread-locals to borrow other thread locals?
1269 let (might_be_alive, will_be_dropped) = match root_place {
1270 Place::Static(statik) => {
1271 // Thread-locals might be dropped after the function exits, but
1272 // "true" statics will never be.
1273 let is_thread_local = self.tcx
1274 .get_attrs(statik.def_id)
1276 .any(|attr| attr.check_name("thread_local"));
1278 (true, is_thread_local)
1280 Place::Local(_) => {
1281 // Locals are always dropped at function exit, and if they
1282 // have a destructor it would've been called already.
1283 (false, self.locals_are_invalidated_at_exit)
1285 Place::Projection(..) => {
1286 bug!("root of {:?} is a projection ({:?})?", place, root_place)
1290 if !will_be_dropped {
1292 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1298 // FIXME: replace this with a proper borrow_conflicts_with_place when
1300 let sd = if might_be_alive { Deep } else { Shallow(None) };
1302 if self.places_conflict(place, root_place, sd) {
1303 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1304 // FIXME: should be talking about the region lifetime instead
1305 // of just a span here.
1306 let span = self.tcx.sess.codemap().end_point(span);
1307 self.report_borrowed_value_does_not_live_long_enough(
1315 /// Reports an error if this is a borrow of local data.
1316 /// This is called for all Yield statements on movable generators
1317 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1318 fn borrow_of_local_data<'tcx>(place: &Place<'tcx>) -> bool {
1320 Place::Static(..) => false,
1321 Place::Local(..) => true,
1322 Place::Projection(box proj) => {
1324 // Reborrow of already borrowed data is ignored
1325 // Any errors will be caught on the initial borrow
1326 ProjectionElem::Deref => false,
1328 // For interior references and downcasts, find out if the base is local
1329 ProjectionElem::Field(..)
1330 | ProjectionElem::Index(..)
1331 | ProjectionElem::ConstantIndex { .. }
1332 | ProjectionElem::Subslice { .. }
1333 | ProjectionElem::Downcast(..) => borrow_of_local_data(&proj.base),
1339 debug!("check_for_local_borrow({:?})", borrow);
1341 if borrow_of_local_data(&borrow.borrowed_place) {
1343 .cannot_borrow_across_generator_yield(
1344 self.retrieve_borrow_span(borrow),
1352 fn check_activations(
1356 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1358 if !self.tcx.two_phase_borrows() {
1362 // Two-phase borrow support: For each activation that is newly
1363 // generated at this statement, check if it interferes with
1365 let borrow_set = self.borrow_set.clone();
1366 for &borrow_index in borrow_set.activations_at_location(location) {
1367 let borrow = &borrow_set[borrow_index];
1369 // only mutable borrows should be 2-phase
1370 assert!(match borrow.kind {
1371 BorrowKind::Shared => false,
1372 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1376 ContextKind::Activation.new(location),
1377 (&borrow.borrowed_place, span),
1380 Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1382 LocalMutationIsAllowed::No,
1385 // We do not need to call `check_if_path_or_subpath_is_moved`
1386 // again, as we already called it when we made the
1387 // initial reservation.
1392 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1393 fn check_if_reassignment_to_immutable_state(
1396 (place, span): (&Place<'tcx>, Span),
1397 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1399 debug!("check_if_reassignment_to_immutable_state({:?})", place);
1400 // determine if this path has a non-mut owner (and thus needs checking).
1401 if let Ok(..) = self.is_mutable(place, LocalMutationIsAllowed::No) {
1405 "check_if_reassignment_to_immutable_state({:?}) - is an imm local",
1409 for i in flow_state.ever_inits.iter_incoming() {
1410 let init = self.move_data.inits[i];
1411 let init_place = &self.move_data.move_paths[init.path].place;
1412 if self.places_conflict(&init_place, place, Deep) {
1413 self.report_illegal_reassignment(context, (place, span), init.span);
1419 fn check_if_full_path_is_moved(
1422 desired_action: InitializationRequiringAction,
1423 place_span: (&Place<'tcx>, Span),
1424 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1426 // FIXME: analogous code in check_loans first maps `place` to
1427 // its base_path ... but is that what we want here?
1428 let place = self.base_path(place_span.0);
1430 let maybe_uninits = &flow_state.uninits;
1431 let curr_move_outs = &flow_state.move_outs;
1435 // 1. Move of `a.b.c`, use of `a.b.c`
1436 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1437 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1438 // partial initialization support, one might have `a.x`
1439 // initialized but not `a.b`.
1443 // 4. Move of `a.b.c`, use of `a.b.d`
1444 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1445 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1446 // must have been initialized for the use to be sound.
1447 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1449 // The dataflow tracks shallow prefixes distinctly (that is,
1450 // field-accesses on P distinctly from P itself), in order to
1451 // track substructure initialization separately from the whole
1454 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1455 // which we have a MovePath is `a.b`, then that means that the
1456 // initialization state of `a.b` is all we need to inspect to
1457 // know if `a.b.c` is valid (and from that we infer that the
1458 // dereference and `.d` access is also valid, since we assume
1459 // `a.b.c` is assigned a reference to a initialized and
1460 // well-formed record structure.)
1462 // Therefore, if we seek out the *closest* prefix for which we
1463 // have a MovePath, that should capture the initialization
1464 // state for the place scenario.
1466 // This code covers scenarios 1, 2, and 3.
1468 debug!("check_if_full_path_is_moved place: {:?}", place);
1469 match self.move_path_closest_to(place) {
1471 if maybe_uninits.contains(&mpi) {
1472 self.report_use_of_moved_or_uninitialized(
1479 return; // don't bother finding other problems.
1482 Err(NoMovePathFound::ReachedStatic) => {
1483 // Okay: we do not build MoveData for static variables
1484 } // Only query longest prefix with a MovePath, not further
1485 // ancestors; dataflow recurs on children when parents
1486 // move (to support partial (re)inits).
1488 // (I.e. querying parents breaks scenario 7; but may want
1489 // to do such a query based on partial-init feature-gate.)
1493 fn check_if_path_or_subpath_is_moved(
1496 desired_action: InitializationRequiringAction,
1497 place_span: (&Place<'tcx>, Span),
1498 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1500 // FIXME: analogous code in check_loans first maps `place` to
1501 // its base_path ... but is that what we want here?
1502 let place = self.base_path(place_span.0);
1504 let maybe_uninits = &flow_state.uninits;
1505 let curr_move_outs = &flow_state.move_outs;
1509 // 1. Move of `a.b.c`, use of `a` or `a.b`
1510 // partial initialization support, one might have `a.x`
1511 // initialized but not `a.b`.
1512 // 2. All bad scenarios from `check_if_full_path_is_moved`
1516 // 3. Move of `a.b.c`, use of `a.b.d`
1517 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1518 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1519 // must have been initialized for the use to be sound.
1520 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1522 self.check_if_full_path_is_moved(context, desired_action, place_span, flow_state);
1524 // A move of any shallow suffix of `place` also interferes
1525 // with an attempt to use `place`. This is scenario 3 above.
1527 // (Distinct from handling of scenarios 1+2+4 above because
1528 // `place` does not interfere with suffixes of its prefixes,
1529 // e.g. `a.b.c` does not interfere with `a.b.d`)
1531 // This code covers scenario 1.
1533 debug!("check_if_path_or_subpath_is_moved place: {:?}", place);
1534 if let Some(mpi) = self.move_path_for_place(place) {
1535 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1536 self.report_use_of_moved_or_uninitialized(
1543 return; // don't bother finding other problems.
1548 /// Currently MoveData does not store entries for all places in
1549 /// the input MIR. For example it will currently filter out
1550 /// places that are Copy; thus we do not track places of shared
1551 /// reference type. This routine will walk up a place along its
1552 /// prefixes, searching for a foundational place that *is*
1553 /// tracked in the MoveData.
1555 /// An Err result includes a tag indicated why the search failed.
1556 /// Currently this can only occur if the place is built off of a
1557 /// static variable, as we do not track those in the MoveData.
1558 fn move_path_closest_to(
1560 place: &Place<'tcx>,
1561 ) -> Result<MovePathIndex, NoMovePathFound> {
1562 let mut last_prefix = place;
1563 for prefix in self.prefixes(place, PrefixSet::All) {
1564 if let Some(mpi) = self.move_path_for_place(prefix) {
1567 last_prefix = prefix;
1569 match *last_prefix {
1570 Place::Local(_) => panic!("should have move path for every Local"),
1571 Place::Projection(_) => panic!("PrefixSet::All meant don't stop for Projection"),
1572 Place::Static(_) => return Err(NoMovePathFound::ReachedStatic),
1576 fn move_path_for_place(&mut self, place: &Place<'tcx>) -> Option<MovePathIndex> {
1577 // If returns None, then there is no move path corresponding
1578 // to a direct owner of `place` (which means there is nothing
1579 // that borrowck tracks for its analysis).
1581 match self.move_data.rev_lookup.find(place) {
1582 LookupResult::Parent(_) => None,
1583 LookupResult::Exact(mpi) => Some(mpi),
1587 fn check_if_assigned_path_is_moved(
1590 (place, span): (&Place<'tcx>, Span),
1591 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1593 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1594 // recur down place; dispatch to external checks when necessary
1595 let mut place = place;
1598 Place::Local(_) | Place::Static(_) => {
1599 // assigning to `x` does not require `x` be initialized.
1602 Place::Projection(ref proj) => {
1603 let Projection { ref base, ref elem } = **proj;
1605 ProjectionElem::Index(_/*operand*/) |
1606 ProjectionElem::ConstantIndex { .. } |
1607 // assigning to P[i] requires P to be valid.
1608 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1609 // assigning to (P->variant) is okay if assigning to `P` is okay
1611 // FIXME: is this true even if P is a adt with a dtor?
1614 // assigning to (*P) requires P to be initialized
1615 ProjectionElem::Deref => {
1616 self.check_if_full_path_is_moved(
1617 context, InitializationRequiringAction::Use,
1618 (base, span), flow_state);
1619 // (base initialized; no need to
1624 ProjectionElem::Subslice { .. } => {
1625 panic!("we don't allow assignments to subslices, context: {:?}",
1629 ProjectionElem::Field(..) => {
1630 // if type of `P` has a dtor, then
1631 // assigning to `P.f` requires `P` itself
1632 // be already initialized
1634 match base.ty(self.mir, tcx).to_ty(tcx).sty {
1635 ty::TyAdt(def, _) if def.has_dtor(tcx) => {
1637 // FIXME: analogous code in
1638 // check_loans.rs first maps
1639 // `base` to its base_path.
1641 self.check_if_path_or_subpath_is_moved(
1642 context, InitializationRequiringAction::Assignment,
1643 (base, span), flow_state);
1645 // (base initialized; no need to
1661 fn specialized_description(&self, place:&Place<'tcx>) -> Option<String>{
1662 if let Some(_name) = self.describe_place(place) {
1663 Some(format!("data in a `&` reference"))
1669 fn get_default_err_msg(&self, place:&Place<'tcx>) -> String{
1670 match self.describe_place(place) {
1671 Some(name) => format!("immutable item `{}`", name),
1672 None => "immutable item".to_owned(),
1676 fn get_secondary_err_msg(&self, place:&Place<'tcx>) -> String{
1677 match self.specialized_description(place) {
1678 Some(_) => format!("data in a `&` reference"),
1679 None => self.get_default_err_msg(place)
1683 fn get_primary_err_msg(&self, place:&Place<'tcx>) -> String{
1684 if let Some(name) = self.describe_place(place) {
1685 format!("`{}` is a `&` reference, so the data it refers to cannot be written", name)
1687 format!("cannot assign through `&`-reference")
1691 /// Check the permissions for the given place and read or write kind
1693 /// Returns true if an error is reported, false otherwise.
1694 fn check_access_permissions(
1696 (place, span): (&Place<'tcx>, Span),
1698 is_local_mutation_allowed: LocalMutationIsAllowed,
1699 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1702 "check_access_permissions({:?}, {:?}, {:?})",
1703 place, kind, is_local_mutation_allowed
1705 let mut error_reported = false;
1707 Reservation(WriteKind::MutableBorrow(BorrowKind::Unique))
1708 | Write(WriteKind::MutableBorrow(BorrowKind::Unique)) => {
1709 if let Err(_place_err) = self.is_mutable(place, LocalMutationIsAllowed::Yes) {
1710 span_bug!(span, "&unique borrow for {:?} should not fail", place);
1713 Reservation(WriteKind::MutableBorrow(BorrowKind::Mut { .. }))
1714 | Write(WriteKind::MutableBorrow(BorrowKind::Mut { .. })) => {
1715 match self.is_mutable(place, is_local_mutation_allowed) {
1716 Ok(root_place) => self.add_used_mut(root_place, flow_state),
1718 error_reported = true;
1719 let item_msg = self.get_default_err_msg(place);
1720 let mut err = self.tcx
1721 .cannot_borrow_path_as_mutable(span, &item_msg, Origin::Mir);
1722 err.span_label(span, "cannot borrow as mutable");
1724 if place != place_err {
1725 if let Some(name) = self.describe_place(place_err) {
1726 err.note(&format!("the value which is causing this path not to be \
1727 mutable is...: `{}`", name));
1735 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1736 match self.is_mutable(place, is_local_mutation_allowed) {
1737 Ok(root_place) => self.add_used_mut(root_place, flow_state),
1739 error_reported = true;
1741 let err_info = if let Place::Projection(
1743 base: Place::Local(local),
1744 elem: ProjectionElem::Deref
1747 let locations = self.mir.find_assignments(local);
1748 if locations.len() > 0 {
1749 let item_msg = if error_reported {
1750 self.get_secondary_err_msg(&Place::Local(local))
1752 self.get_default_err_msg(place)
1754 let sp = self.mir.source_info(locations[0]).span;
1755 let mut to_suggest_span = String::new();
1757 self.tcx.sess.codemap().span_to_snippet(sp) {
1758 to_suggest_span = src[1..].to_string();
1761 "consider changing this to be a \
1765 self.get_primary_err_msg(&Place::Local(local))))
1773 if let Some((err_help_span,
1777 sec_span)) = err_info {
1778 let mut err = self.tcx.cannot_assign(span, &item_msg, Origin::Mir);
1779 err.span_suggestion(err_help_span,
1781 format!("&mut {}", to_suggest_span));
1782 if place != place_err {
1783 err.span_label(span, sec_span);
1787 let item_msg = self.get_default_err_msg(place);
1788 let mut err = self.tcx.cannot_assign(span, &item_msg, Origin::Mir);
1789 err.span_label(span, "cannot mutate");
1790 if place != place_err {
1791 if let Some(name) = self.describe_place(place_err) {
1792 err.note(&format!("the value which is causing this path not \
1793 to be mutable is...: `{}`", name));
1801 Reservation(WriteKind::Move)
1802 | Reservation(WriteKind::StorageDeadOrDrop)
1803 | Reservation(WriteKind::MutableBorrow(BorrowKind::Shared))
1804 | Write(WriteKind::Move)
1805 | Write(WriteKind::StorageDeadOrDrop)
1806 | Write(WriteKind::MutableBorrow(BorrowKind::Shared)) => {
1807 if let Err(_place_err) = self.is_mutable(place, is_local_mutation_allowed) {
1808 self.tcx.sess.delay_span_bug(
1811 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
1817 Activation(..) => {} // permission checks are done at Reservation point.
1818 Read(ReadKind::Borrow(BorrowKind::Unique))
1819 | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
1820 | Read(ReadKind::Borrow(BorrowKind::Shared))
1821 | Read(ReadKind::Copy) => {} // Access authorized
1827 /// Adds the place into the used mutable variables set
1828 fn add_used_mut<'d>(
1830 root_place: RootPlace<'d, 'tcx>,
1831 flow_state: &Flows<'cx, 'gcx, 'tcx>
1835 place: Place::Local(local),
1836 is_local_mutation_allowed,
1838 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes {
1839 // If the local may be initialized, and it is now currently being
1840 // mutated, then it is justified to be annotated with the `mut`
1841 // keyword, since the mutation may be a possible reassignment.
1842 let mpi = self.move_data.rev_lookup.find_local(*local);
1843 if flow_state.inits.contains(&mpi) {
1844 self.used_mut.insert(*local);
1849 place: place @ Place::Projection(_),
1850 is_local_mutation_allowed: _,
1852 if let Some(field) = self.is_upvar_field_projection(&place) {
1853 self.used_mut_upvars.push(field);
1857 place: Place::Static(..),
1858 is_local_mutation_allowed: _,
1863 /// Whether this value be written or borrowed mutably.
1864 /// Returns the root place if the place passed in is a projection.
1867 place: &'d Place<'tcx>,
1868 is_local_mutation_allowed: LocalMutationIsAllowed,
1869 ) -> Result<RootPlace<'d, 'tcx>, &'d Place<'tcx>> {
1871 Place::Local(local) => {
1872 let local = &self.mir.local_decls[local];
1873 match local.mutability {
1874 Mutability::Not => match is_local_mutation_allowed {
1875 LocalMutationIsAllowed::Yes => {
1878 is_local_mutation_allowed: LocalMutationIsAllowed::Yes
1881 LocalMutationIsAllowed::ExceptUpvars => {
1884 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars
1887 LocalMutationIsAllowed::No => Err(place),
1889 Mutability::Mut => Ok(RootPlace { place, is_local_mutation_allowed }),
1892 Place::Static(ref static_) =>
1893 if self.tcx.is_static(static_.def_id) != Some(hir::Mutability::MutMutable) {
1896 Ok(RootPlace { place, is_local_mutation_allowed })
1898 Place::Projection(ref proj) => {
1900 ProjectionElem::Deref => {
1901 let base_ty = proj.base.ty(self.mir, self.tcx).to_ty(self.tcx);
1903 // Check the kind of deref to decide
1905 ty::TyRef(_, tnm) => {
1907 // Shared borrowed data is never mutable
1908 hir::MutImmutable => Err(place),
1909 // Mutably borrowed data is mutable, but only if we have a
1910 // unique path to the `&mut`
1911 hir::MutMutable => {
1912 let mode = match self.is_upvar_field_projection(&proj.base)
1916 self.mir.upvar_decls[field.index()].by_ref
1919 is_local_mutation_allowed
1921 _ => LocalMutationIsAllowed::Yes,
1924 self.is_mutable(&proj.base, mode)
1928 ty::TyRawPtr(tnm) => {
1930 // `*const` raw pointers are not mutable
1931 hir::MutImmutable => return Err(place),
1932 // `*mut` raw pointers are always mutable, regardless of
1933 // context. The users have to check by themselves.
1934 hir::MutMutable => {
1935 return Ok(RootPlace { place, is_local_mutation_allowed });
1939 // `Box<T>` owns its content, so mutable if its location is mutable
1940 _ if base_ty.is_box() => {
1941 self.is_mutable(&proj.base, is_local_mutation_allowed)
1943 // Deref should only be for reference, pointers or boxes
1944 _ => bug!("Deref of unexpected type: {:?}", base_ty),
1947 // All other projections are owned by their base path, so mutable if
1948 // base path is mutable
1949 ProjectionElem::Field(..)
1950 | ProjectionElem::Index(..)
1951 | ProjectionElem::ConstantIndex { .. }
1952 | ProjectionElem::Subslice { .. }
1953 | ProjectionElem::Downcast(..) => {
1954 if let Some(field) = self.is_upvar_field_projection(place) {
1955 let decl = &self.mir.upvar_decls[field.index()];
1957 "decl.mutability={:?} local_mutation_is_allowed={:?} place={:?}",
1958 decl, is_local_mutation_allowed, place
1960 match (decl.mutability, is_local_mutation_allowed) {
1961 (Mutability::Not, LocalMutationIsAllowed::No)
1962 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
1965 (Mutability::Not, LocalMutationIsAllowed::Yes)
1966 | (Mutability::Mut, _) => {
1967 // Subtle: this is an upvar
1968 // reference, so it looks like
1969 // `self.foo` -- we want to double
1970 // check that the context `*self`
1971 // is mutable (i.e., this is not a
1972 // `Fn` closure). But if that
1973 // check succeeds, we want to
1974 // *blame* the mutability on
1975 // `place` (that is,
1976 // `self.foo`). This is used to
1977 // propagate the info about
1978 // whether mutability declarations
1979 // are used outwards, so that we register
1980 // the outer variable as mutable. Otherwise a
1981 // test like this fails to record the `mut`
1985 // fn foo<F: FnOnce()>(_f: F) { }
1987 // let var = Vec::new();
1993 let _ = self.is_mutable(&proj.base, is_local_mutation_allowed)?;
1994 Ok(RootPlace { place, is_local_mutation_allowed })
1998 self.is_mutable(&proj.base, is_local_mutation_allowed)
2006 /// If this is a field projection, and the field is being projected from a closure type,
2007 /// then returns the index of the field being projected. Note that this closure will always
2008 /// be `self` in the current MIR, because that is the only time we directly access the fields
2009 /// of a closure type.
2010 fn is_upvar_field_projection(&self, place: &Place<'tcx>) -> Option<Field> {
2012 Place::Projection(ref proj) => match proj.elem {
2013 ProjectionElem::Field(field, _ty) => {
2014 let is_projection_from_ty_closure = proj.base
2015 .ty(self.mir, self.tcx)
2019 if is_projection_from_ty_closure {
2032 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2033 enum NoMovePathFound {
2037 /// The degree of overlap between 2 places for borrow-checking.
2039 /// The places might partially overlap - in this case, we give
2040 /// up and say that they might conflict. This occurs when
2041 /// different fields of a union are borrowed. For example,
2042 /// if `u` is a union, we have no way of telling how disjoint
2043 /// `u.a.x` and `a.b.y` are.
2045 /// The places have the same type, and are either completely disjoint
2046 /// or equal - i.e. they can't "partially" overlap as can occur with
2047 /// unions. This is the "base case" on which we recur for extensions
2050 /// The places are disjoint, so we know all extensions of them
2051 /// will also be disjoint.
2055 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
2056 // Given that the bases of `elem1` and `elem2` are always either equal
2057 // or disjoint (and have the same type!), return the overlap situation
2058 // between `elem1` and `elem2`.
2059 fn place_element_conflict(&self, elem1: &Place<'tcx>, elem2: &Place<'tcx>) -> Overlap {
2060 match (elem1, elem2) {
2061 (Place::Local(l1), Place::Local(l2)) => {
2063 // the same local - base case, equal
2064 debug!("place_element_conflict: DISJOINT-OR-EQ-LOCAL");
2065 Overlap::EqualOrDisjoint
2067 // different locals - base case, disjoint
2068 debug!("place_element_conflict: DISJOINT-LOCAL");
2072 (Place::Static(static1), Place::Static(static2)) => {
2073 if static1.def_id != static2.def_id {
2074 debug!("place_element_conflict: DISJOINT-STATIC");
2076 } else if self.tcx.is_static(static1.def_id) == Some(hir::Mutability::MutMutable) {
2077 // We ignore mutable statics - they can only be unsafe code.
2078 debug!("place_element_conflict: IGNORE-STATIC-MUT");
2081 debug!("place_element_conflict: DISJOINT-OR-EQ-STATIC");
2082 Overlap::EqualOrDisjoint
2085 (Place::Local(_), Place::Static(_)) | (Place::Static(_), Place::Local(_)) => {
2086 debug!("place_element_conflict: DISJOINT-STATIC-LOCAL");
2089 (Place::Projection(pi1), Place::Projection(pi2)) => {
2090 match (&pi1.elem, &pi2.elem) {
2091 (ProjectionElem::Deref, ProjectionElem::Deref) => {
2092 // derefs (e.g. `*x` vs. `*x`) - recur.
2093 debug!("place_element_conflict: DISJOINT-OR-EQ-DEREF");
2094 Overlap::EqualOrDisjoint
2096 (ProjectionElem::Field(f1, _), ProjectionElem::Field(f2, _)) => {
2098 // same field (e.g. `a.y` vs. `a.y`) - recur.
2099 debug!("place_element_conflict: DISJOINT-OR-EQ-FIELD");
2100 Overlap::EqualOrDisjoint
2102 let ty = pi1.base.ty(self.mir, self.tcx).to_ty(self.tcx);
2104 ty::TyAdt(def, _) if def.is_union() => {
2105 // Different fields of a union, we are basically stuck.
2106 debug!("place_element_conflict: STUCK-UNION");
2110 // Different fields of a struct (`a.x` vs. `a.y`). Disjoint!
2111 debug!("place_element_conflict: DISJOINT-FIELD");
2117 (ProjectionElem::Downcast(_, v1), ProjectionElem::Downcast(_, v2)) => {
2118 // different variants are treated as having disjoint fields,
2119 // even if they occupy the same "space", because it's
2120 // impossible for 2 variants of the same enum to exist
2121 // (and therefore, to be borrowed) at the same time.
2123 // Note that this is different from unions - we *do* allow
2124 // this code to compile:
2127 // fn foo(x: &mut Result<i32, i32>) {
2128 // let mut v = None;
2129 // if let Ok(ref mut a) = *x {
2132 // // here, you would *think* that the
2133 // // *entirety* of `x` would be borrowed,
2134 // // but in fact only the `Ok` variant is,
2135 // // so the `Err` variant is *entirely free*:
2136 // if let Err(ref mut a) = *x {
2143 debug!("place_element_conflict: DISJOINT-OR-EQ-FIELD");
2144 Overlap::EqualOrDisjoint
2146 debug!("place_element_conflict: DISJOINT-FIELD");
2150 (ProjectionElem::Index(..), ProjectionElem::Index(..))
2151 | (ProjectionElem::Index(..), ProjectionElem::ConstantIndex { .. })
2152 | (ProjectionElem::Index(..), ProjectionElem::Subslice { .. })
2153 | (ProjectionElem::ConstantIndex { .. }, ProjectionElem::Index(..))
2155 ProjectionElem::ConstantIndex { .. },
2156 ProjectionElem::ConstantIndex { .. },
2158 | (ProjectionElem::ConstantIndex { .. }, ProjectionElem::Subslice { .. })
2159 | (ProjectionElem::Subslice { .. }, ProjectionElem::Index(..))
2160 | (ProjectionElem::Subslice { .. }, ProjectionElem::ConstantIndex { .. })
2161 | (ProjectionElem::Subslice { .. }, ProjectionElem::Subslice { .. }) => {
2162 // Array indexes (`a[0]` vs. `a[i]`). These can either be disjoint
2163 // (if the indexes differ) or equal (if they are the same), so this
2164 // is the recursive case that gives "equal *or* disjoint" its meaning.
2166 // Note that by construction, MIR at borrowck can't subdivide
2167 // `Subslice` accesses (e.g. `a[2..3][i]` will never be present) - they
2168 // are only present in slice patterns, and we "merge together" nested
2169 // slice patterns. That means we don't have to think about these. It's
2170 // probably a good idea to assert this somewhere, but I'm too lazy.
2172 // FIXME(#8636) we might want to return Disjoint if
2173 // both projections are constant and disjoint.
2174 debug!("place_element_conflict: DISJOINT-OR-EQ-ARRAY");
2175 Overlap::EqualOrDisjoint
2178 (ProjectionElem::Deref, _)
2179 | (ProjectionElem::Field(..), _)
2180 | (ProjectionElem::Index(..), _)
2181 | (ProjectionElem::ConstantIndex { .. }, _)
2182 | (ProjectionElem::Subslice { .. }, _)
2183 | (ProjectionElem::Downcast(..), _) => bug!(
2184 "mismatched projections in place_element_conflict: {:?} and {:?}",
2190 (Place::Projection(_), _) | (_, Place::Projection(_)) => bug!(
2191 "unexpected elements in place_element_conflict: {:?} and {:?}",
2198 /// Returns whether an access of kind `access` to `access_place` conflicts with
2199 /// a borrow/full access to `borrow_place` (for deep accesses to mutable
2200 /// locations, this function is symmetric between `borrow_place` & `access_place`).
2203 borrow_place: &Place<'tcx>,
2204 access_place: &Place<'tcx>,
2205 access: ShallowOrDeep,
2208 "places_conflict({:?},{:?},{:?})",
2209 borrow_place, access_place, access
2212 // Return all the prefixes of `place` in reverse order, including
2214 fn place_elements<'a, 'tcx>(place: &'a Place<'tcx>) -> Vec<&'a Place<'tcx>> {
2215 let mut result = vec![];
2216 let mut place = place;
2220 Place::Projection(interior) => {
2221 place = &interior.base;
2223 Place::Local(_) | Place::Static(_) => {
2231 let borrow_components = place_elements(borrow_place);
2232 let access_components = place_elements(access_place);
2234 "places_conflict: components {:?} / {:?}",
2235 borrow_components, access_components
2238 let borrow_components = borrow_components
2241 .chain(iter::repeat(None));
2242 let access_components = access_components
2245 .chain(iter::repeat(None));
2246 // The borrowck rules for proving disjointness are applied from the "root" of the
2247 // borrow forwards, iterating over "similar" projections in lockstep until
2248 // we can prove overlap one way or another. Essentially, we treat `Overlap` as
2249 // a monoid and report a conflict if the product ends up not being `Disjoint`.
2251 // At each step, if we didn't run out of borrow or place, we know that our elements
2252 // have the same type, and that they only overlap if they are the identical.
2254 // For example, if we are comparing these:
2255 // BORROW: (*x1[2].y).z.a
2256 // ACCESS: (*x1[i].y).w.b
2258 // Then our steps are:
2259 // x1 | x1 -- places are the same
2260 // x1[2] | x1[i] -- equal or disjoint (disjoint if indexes differ)
2261 // x1[2].y | x1[i].y -- equal or disjoint
2262 // *x1[2].y | *x1[i].y -- equal or disjoint
2263 // (*x1[2].y).z | (*x1[i].y).w -- we are disjoint and don't need to check more!
2265 // Because `zip` does potentially bad things to the iterator inside, this loop
2266 // also handles the case where the access might be a *prefix* of the borrow, e.g.
2268 // BORROW: (*x1[2].y).z.a
2271 // Then our steps are:
2272 // x1 | x1 -- places are the same
2273 // x1[2] | x1[i] -- equal or disjoint (disjoint if indexes differ)
2274 // x1[2].y | x1[i].y -- equal or disjoint
2276 // -- here we run out of access - the borrow can access a part of it. If this
2277 // is a full deep access, then we *know* the borrow conflicts with it. However,
2278 // if the access is shallow, then we can proceed:
2280 // x1[2].y | (*x1[i].y) -- a deref! the access can't get past this, so we
2283 // Our invariant is, that at each step of the iteration:
2284 // - If we didn't run out of access to match, our borrow and access are comparable
2285 // and either equal or disjoint.
2286 // - If we did run out of accesss, the borrow can access a part of it.
2287 for (borrow_c, access_c) in borrow_components.zip(access_components) {
2288 // loop invariant: borrow_c is always either equal to access_c or disjoint from it.
2289 debug!("places_conflict: {:?} vs. {:?}", borrow_c, access_c);
2290 match (borrow_c, access_c) {
2292 // If we didn't run out of access, the borrow can access all of our
2293 // place (e.g. a borrow of `a.b` with an access to `a.b.c`),
2294 // so we have a conflict.
2296 // If we did, then we still know that the borrow can access a *part*
2297 // of our place that our access cares about (a borrow of `a.b.c`
2298 // with an access to `a.b`), so we still have a conflict.
2300 // FIXME: Differs from AST-borrowck; includes drive-by fix
2301 // to #38899. Will probably need back-compat mode flag.
2302 debug!("places_conflict: full borrow, CONFLICT");
2305 (Some(borrow_c), None) => {
2306 // We know that the borrow can access a part of our place. This
2307 // is a conflict if that is a part our access cares about.
2309 let (base, elem) = match borrow_c {
2310 Place::Projection(box Projection { base, elem }) => (base, elem),
2311 _ => bug!("place has no base?"),
2313 let base_ty = base.ty(self.mir, self.tcx).to_ty(self.tcx);
2315 match (elem, &base_ty.sty, access) {
2316 (_, _, Shallow(Some(ArtificialField::Discriminant)))
2317 | (_, _, Shallow(Some(ArtificialField::ArrayLength))) => {
2318 // The discriminant and array length are like
2319 // additional fields on the type; they do not
2320 // overlap any existing data there. Furthermore,
2321 // they cannot actually be a prefix of any
2322 // borrowed place (at least in MIR as it is
2325 // e.g. a (mutable) borrow of `a[5]` while we read the
2326 // array length of `a`.
2327 debug!("places_conflict: implicit field");
2331 (ProjectionElem::Deref, _, Shallow(None)) => {
2332 // e.g. a borrow of `*x.y` while we shallowly access `x.y` or some
2333 // prefix thereof - the shallow access can't touch anything behind
2335 debug!("places_conflict: shallow access behind ptr");
2339 ProjectionElem::Deref,
2344 mutbl: hir::MutImmutable,
2349 // the borrow goes through a dereference of a shared reference.
2351 // I'm not sure why we are tracking these borrows - shared
2352 // references can *always* be aliased, which means the
2353 // permission check already account for this borrow.
2354 debug!("places_conflict: behind a shared ref");
2358 (ProjectionElem::Deref, _, Deep)
2359 | (ProjectionElem::Field { .. }, _, _)
2360 | (ProjectionElem::Index { .. }, _, _)
2361 | (ProjectionElem::ConstantIndex { .. }, _, _)
2362 | (ProjectionElem::Subslice { .. }, _, _)
2363 | (ProjectionElem::Downcast { .. }, _, _) => {
2364 // Recursive case. This can still be disjoint on a
2365 // further iteration if this a shallow access and
2366 // there's a deref later on, e.g. a borrow
2367 // of `*x.y` while accessing `x`.
2371 (Some(borrow_c), Some(access_c)) => {
2372 match self.place_element_conflict(&borrow_c, access_c) {
2373 Overlap::Arbitrary => {
2374 // We have encountered different fields of potentially
2375 // the same union - the borrow now partially overlaps.
2377 // There is no *easy* way of comparing the fields
2378 // further on, because they might have different types
2379 // (e.g. borrows of `u.a.0` and `u.b.y` where `.0` and
2380 // `.y` come from different structs).
2382 // We could try to do some things here - e.g. count
2383 // dereferences - but that's probably not a good
2384 // idea, at least for now, so just give up and
2385 // report a conflict. This is unsafe code anyway so
2386 // the user could always use raw pointers.
2387 debug!("places_conflict: arbitrary -> conflict");
2390 Overlap::EqualOrDisjoint => {
2391 // This is the recursive case - proceed to the next element.
2393 Overlap::Disjoint => {
2394 // We have proven the borrow disjoint - further
2395 // projections will remain disjoint.
2396 debug!("places_conflict: disjoint");
2403 unreachable!("iter::repeat returned None")
2406 /// This function iterates over all of the in-scope borrows that
2407 /// conflict with an access to a place, invoking the `op` callback
2410 /// "Current borrow" here means a borrow that reaches the point in
2411 /// the control-flow where the access occurs.
2413 /// The borrow's phase is represented by the IsActive parameter
2414 /// passed to the callback.
2415 fn each_borrow_involving_path<F>(
2418 access_place: (ShallowOrDeep, &Place<'tcx>),
2419 flow_state: &Flows<'cx, 'gcx, 'tcx>,
2422 F: FnMut(&mut Self, BorrowIndex, &BorrowData<'tcx>) -> Control,
2424 let (access, place) = access_place;
2426 // FIXME: analogous code in check_loans first maps `place` to
2429 // check for loan restricting path P being used. Accounts for
2430 // borrows of P, P.a.b, etc.
2431 let borrow_set = self.borrow_set.clone();
2432 for i in flow_state.borrows_in_scope() {
2433 let borrowed = &borrow_set[i];
2435 if self.places_conflict(&borrowed.borrowed_place, place, access) {
2437 "each_borrow_involving_path: {:?} @ {:?} vs. {:?}/{:?}",
2438 i, borrowed, place, access
2440 let ctrl = op(self, i, borrowed);
2441 if ctrl == Control::Break {
2450 borrow_data: &BorrowData<'tcx>,
2453 debug!("is_active(borrow_data={:?}, location={:?})", borrow_data, location);
2455 // If this is not a 2-phase borrow, it is always active.
2456 let activation_location = match borrow_data.activation_location {
2458 None => return true,
2461 // Otherwise, it is active for every location *except* in between
2462 // the reservation and the activation:
2466 // R <--+ Except for this
2473 // Note that we assume that:
2474 // - the reservation R dominates the activation A
2475 // - the activation A post-dominates the reservation R (ignoring unwinding edges).
2477 // This means that there can't be an edge that leaves A and
2478 // comes back into that diamond unless it passes through R.
2480 // Suboptimal: In some cases, this code walks the dominator
2481 // tree twice when it only has to be walked once. I am
2484 // If dominated by the activation A, then it is active. The
2485 // activation occurs upon entering the point A, so this is
2486 // also true if location == activation_location.
2487 if activation_location.dominates(location, &self.dominators) {
2491 // The reservation starts *on exiting* the reservation block,
2492 // so check if the location is dominated by R.successor. If so,
2493 // this point falls in between the reservation and location.
2494 let reserve_location = borrow_data.reserve_location.successor_within_block();
2495 if reserve_location.dominates(location, &self.dominators) {
2498 // Otherwise, this point is outside the diamond, so
2499 // consider the borrow active. This could happen for
2500 // example if the borrow remains active around a loop (in
2501 // which case it would be active also for the point R,
2502 // which would generate an error).
2508 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
2509 // FIXME (#16118): function intended to allow the borrow checker
2510 // to be less precise in its handling of Box while still allowing
2511 // moves out of a Box. They should be removed when/if we stop
2512 // treating Box specially (e.g. when/if DerefMove is added...)
2514 fn base_path<'d>(&self, place: &'d Place<'tcx>) -> &'d Place<'tcx> {
2515 //! Returns the base of the leftmost (deepest) dereference of an
2516 //! Box in `place`. If there is no dereference of an Box
2517 //! in `place`, then it just returns `place` itself.
2519 let mut cursor = place;
2520 let mut deepest = place;
2522 let proj = match *cursor {
2523 Place::Local(..) | Place::Static(..) => return deepest,
2524 Place::Projection(ref proj) => proj,
2526 if proj.elem == ProjectionElem::Deref
2527 && place.ty(self.mir, self.tcx).to_ty(self.tcx).is_box()
2529 deepest = &proj.base;
2531 cursor = &proj.base;
2536 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2542 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2561 fn new(self, loc: Location) -> Context {