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::{AssertMessage, 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: opt_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 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
264 for local in mbcx.mir.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)) {
265 if let ClearCrossCrate::Set(ref vsi) = mbcx.mir.visibility_scope_info {
266 let source_info = mbcx.mir.local_decls[local].source_info;
267 let mut_span = tcx.sess.codemap().span_until_non_whitespace(source_info.span);
269 tcx.struct_span_lint_node(
271 vsi[source_info.scope].lint_root,
273 "variable does not need to be mutable"
275 .span_suggestion_short(mut_span, "remove this `mut`", "".to_owned())
281 closure_requirements: opt_closure_req,
282 used_mut_upvars: mbcx.used_mut_upvars,
287 pub struct MirBorrowckCtxt<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
288 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
291 move_data: &'cx MoveData<'tcx>,
292 param_env: ParamEnv<'gcx>,
293 movable_generator: bool,
294 /// This keeps track of whether local variables are free-ed when the function
295 /// exits even without a `StorageDead`, which appears to be the case for
298 /// I'm not sure this is the right approach - @eddyb could you try and
300 locals_are_invalidated_at_exit: bool,
301 /// This field keeps track of when borrow errors are reported in the access_place function
302 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
303 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
304 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
306 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
307 /// This field keeps track of when borrow conflict errors are reported
308 /// for reservations, so that we don't report seemingly duplicate
309 /// errors for corresponding activations
311 /// FIXME: Ideally this would be a set of BorrowIndex, not Places,
312 /// but it is currently inconvenient to track down the BorrowIndex
313 /// at the time we detect and report a reservation error.
314 reservation_error_reported: FxHashSet<Place<'tcx>>,
315 /// This field keeps track of errors reported in the checking of moved variables,
316 /// so that we don't report report seemingly duplicate errors.
317 moved_error_reported: FxHashSet<Place<'tcx>>,
318 /// This field keeps track of all the local variables that are declared mut and are mutated.
319 /// Used for the warning issued by an unused mutable local variable.
320 used_mut: FxHashSet<Local>,
321 /// If the function we're checking is a closure, then we'll need to report back the list of
322 /// mutable upvars that have been used. This field keeps track of them.
323 used_mut_upvars: SmallVec<[Field; 8]>,
324 /// Non-lexical region inference context, if NLL is enabled. This
325 /// contains the results from region inference and lets us e.g.
326 /// find out which CFG points are contained in each borrow region.
327 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
328 nonlexical_cause_info: Option<RegionCausalInfo>,
330 /// The set of borrows extracted from the MIR
331 borrow_set: Rc<BorrowSet<'tcx>>,
333 /// Dominators for MIR
334 dominators: Dominators<BasicBlock>,
338 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
339 // 2. loans made in overlapping scopes do not conflict
340 // 3. assignments do not affect things loaned out as immutable
341 // 4. moves do not affect things loaned out in any way
342 impl<'cx, 'gcx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
343 type FlowState = Flows<'cx, 'gcx, 'tcx>;
345 fn mir(&self) -> &'cx Mir<'tcx> {
349 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
350 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
353 fn visit_statement_entry(
356 stmt: &Statement<'tcx>,
357 flow_state: &Self::FlowState,
360 "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
361 location, stmt, flow_state
363 let span = stmt.source_info.span;
365 self.check_activations(location, span, flow_state);
368 StatementKind::Assign(ref lhs, ref rhs) => {
370 ContextKind::AssignRhs.new(location),
377 ContextKind::AssignLhs.new(location),
384 StatementKind::SetDiscriminant {
389 ContextKind::SetDiscrim.new(location),
391 Shallow(Some(ArtificialField::Discriminant)),
396 StatementKind::InlineAsm {
401 let context = ContextKind::InlineAsm.new(location);
402 for (o, output) in asm.outputs.iter().zip(outputs) {
404 // FIXME(eddyb) indirect inline asm outputs should
405 // be encoeded through MIR place derefs instead.
409 (Deep, Read(ReadKind::Copy)),
410 LocalMutationIsAllowed::No,
413 self.check_if_path_or_subpath_is_moved(
415 InitializationRequiringAction::Use,
423 if o.is_rw { Deep } else { Shallow(None) },
424 if o.is_rw { WriteAndRead } else { JustWrite },
429 for input in inputs {
430 self.consume_operand(context, (input, span), flow_state);
433 StatementKind::EndRegion(ref _rgn) => {
434 // ignored when consuming results (update to
435 // flow_state already handled).
438 StatementKind::UserAssertTy(..) |
439 StatementKind::Validate(..) |
440 StatementKind::StorageLive(..) => {
441 // `Nop`, `UserAssertTy`, `Validate`, and `StorageLive` are irrelevant
444 StatementKind::StorageDead(local) => {
446 ContextKind::StorageDead.new(location),
447 (&Place::Local(local), span),
448 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
449 LocalMutationIsAllowed::Yes,
456 fn visit_terminator_entry(
459 term: &Terminator<'tcx>,
460 flow_state: &Self::FlowState,
464 "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
465 location, term, flow_state
467 let span = term.source_info.span;
469 self.check_activations(location, span, flow_state);
472 TerminatorKind::SwitchInt {
478 self.consume_operand(ContextKind::SwitchInt.new(loc), (discr, span), flow_state);
480 TerminatorKind::Drop {
481 location: ref drop_place,
485 let gcx = self.tcx.global_tcx();
487 // Compute the type with accurate region information.
488 let drop_place_ty = drop_place.ty(self.mir, self.tcx);
490 // Erase the regions.
491 let drop_place_ty = self.tcx.erase_regions(&drop_place_ty).to_ty(self.tcx);
493 // "Lift" into the gcx -- once regions are erased, this type should be in the
494 // global arenas; this "lift" operation basically just asserts that is true, but
495 // that is useful later.
496 let drop_place_ty = gcx.lift(&drop_place_ty).unwrap();
498 self.visit_terminator_drop(loc, term, flow_state, drop_place, drop_place_ty, span);
500 TerminatorKind::DropAndReplace {
501 location: ref drop_place,
502 value: ref new_value,
507 ContextKind::DropAndReplace.new(loc),
513 self.consume_operand(
514 ContextKind::DropAndReplace.new(loc),
519 TerminatorKind::Call {
525 self.consume_operand(ContextKind::CallOperator.new(loc), (func, span), flow_state);
527 self.consume_operand(
528 ContextKind::CallOperand.new(loc),
533 if let Some((ref dest, _ /*bb*/)) = *destination {
535 ContextKind::CallDest.new(loc),
543 TerminatorKind::Assert {
550 self.consume_operand(ContextKind::Assert.new(loc), (cond, span), flow_state);
552 AssertMessage::BoundsCheck { ref len, ref index } => {
553 self.consume_operand(ContextKind::Assert.new(loc), (len, span), flow_state);
554 self.consume_operand(
555 ContextKind::Assert.new(loc),
560 AssertMessage::Math(_ /*const_math_err*/) => {}
561 AssertMessage::GeneratorResumedAfterReturn => {}
562 AssertMessage::GeneratorResumedAfterPanic => {}
566 TerminatorKind::Yield {
571 self.consume_operand(ContextKind::Yield.new(loc), (value, span), flow_state);
573 if self.movable_generator {
574 // Look for any active borrows to locals
575 let borrow_set = self.borrow_set.clone();
576 flow_state.with_outgoing_borrows(|borrows| {
578 let borrow = &borrow_set[i];
579 self.check_for_local_borrow(borrow, span);
585 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
586 // Returning from the function implicitly kills storage for all locals and statics.
587 // Often, the storage will already have been killed by an explicit
588 // StorageDead, but we don't always emit those (notably on unwind paths),
589 // so this "extra check" serves as a kind of backup.
590 let borrow_set = self.borrow_set.clone();
591 flow_state.with_outgoing_borrows(|borrows| {
593 let borrow = &borrow_set[i];
594 let context = ContextKind::StorageDead.new(loc);
595 self.check_for_invalidation_at_exit(context, borrow, span);
599 TerminatorKind::Goto { target: _ }
600 | TerminatorKind::Abort
601 | TerminatorKind::Unreachable
602 | TerminatorKind::FalseEdges {
604 imaginary_targets: _,
606 | TerminatorKind::FalseUnwind {
610 // no data used, thus irrelevant to borrowck
616 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
622 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
628 use self::ShallowOrDeep::{Deep, Shallow};
629 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
631 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
632 enum ArtificialField {
637 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
639 /// From the RFC: "A *shallow* access means that the immediate
640 /// fields reached at P are accessed, but references or pointers
641 /// found within are not dereferenced. Right now, the only access
642 /// that is shallow is an assignment like `x = ...;`, which would
643 /// be a *shallow write* of `x`."
644 Shallow(Option<ArtificialField>),
646 /// From the RFC: "A *deep* access means that all data reachable
647 /// through the given place may be invalidated or accesses by
652 /// Kind of access to a value: read or write
653 /// (For informational purposes only)
654 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
656 /// From the RFC: "A *read* means that the existing data may be
657 /// read, but will not be changed."
660 /// From the RFC: "A *write* means that the data may be mutated to
661 /// new values or otherwise invalidated (for example, it could be
662 /// de-initialized, as in a move operation).
665 /// For two-phase borrows, we distinguish a reservation (which is treated
666 /// like a Read) from an activation (which is treated like a write), and
667 /// each of those is furthermore distinguished from Reads/Writes above.
668 Reservation(WriteKind),
669 Activation(WriteKind, BorrowIndex),
672 /// Kind of read access to a value
673 /// (For informational purposes only)
674 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
680 /// Kind of write access to a value
681 /// (For informational purposes only)
682 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
685 MutableBorrow(BorrowKind),
690 /// When checking permissions for a place access, this flag is used to indicate that an immutable
691 /// local place can be mutated.
693 /// FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
694 /// - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`
695 /// - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
696 /// `is_declared_mutable()`
697 /// - Take flow state into consideration in `is_assignable()` for local variables
698 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
699 enum LocalMutationIsAllowed {
701 /// We want use of immutable upvars to cause a "write to immutable upvar"
702 /// error, not an "reassignment" error.
707 struct AccessErrorsReported {
708 mutability_error: bool,
710 conflict_error: bool,
713 #[derive(Copy, Clone)]
714 enum InitializationRequiringAction {
721 impl InitializationRequiringAction {
722 fn as_noun(self) -> &'static str {
724 InitializationRequiringAction::Update => "update",
725 InitializationRequiringAction::Borrow => "borrow",
726 InitializationRequiringAction::Use => "use",
727 InitializationRequiringAction::Assignment => "assign",
731 fn as_verb_in_past_tense(self) -> &'static str {
733 InitializationRequiringAction::Update => "updated",
734 InitializationRequiringAction::Borrow => "borrowed",
735 InitializationRequiringAction::Use => "used",
736 InitializationRequiringAction::Assignment => "assigned",
741 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
742 /// Returns true if the borrow represented by `kind` is
743 /// allowed to be split into separate Reservation and
744 /// Activation phases.
745 fn allow_two_phase_borrow(&self, kind: BorrowKind) -> bool {
746 self.tcx.two_phase_borrows()
747 && (kind.allows_two_phase_borrow()
748 || self.tcx.sess.opts.debugging_opts.two_phase_beyond_autoref)
751 /// Invokes `access_place` as appropriate for dropping the value
752 /// at `drop_place`. Note that the *actual* `Drop` in the MIR is
753 /// always for a variable (e.g., `Drop(x)`) -- but we recursively
754 /// break this variable down into subpaths (e.g., `Drop(x.foo)`)
755 /// to indicate more precisely which fields might actually be
756 /// accessed by a destructor.
757 fn visit_terminator_drop(
760 term: &Terminator<'tcx>,
761 flow_state: &Flows<'cx, 'gcx, 'tcx>,
762 drop_place: &Place<'tcx>,
763 erased_drop_place_ty: ty::Ty<'gcx>,
766 let gcx = self.tcx.global_tcx();
768 mir: &mut MirBorrowckCtxt<'cx, 'gcx, 'tcx>,
769 (index, field): (usize, ty::Ty<'gcx>),
771 let field_ty = gcx.normalize_erasing_regions(mir.param_env, field);
772 let place = drop_place.clone().field(Field::new(index), field_ty);
774 mir.visit_terminator_drop(loc, term, flow_state, &place, field_ty, span);
777 match erased_drop_place_ty.sty {
778 // When a struct is being dropped, we need to check
779 // whether it has a destructor, if it does, then we can
780 // call it, if it does not then we need to check the
781 // individual fields instead. This way if `foo` has a
782 // destructor but `bar` does not, we will only check for
783 // borrows of `x.foo` and not `x.bar`. See #47703.
784 ty::TyAdt(def, substs) if def.is_struct() && !def.has_dtor(self.tcx) => {
786 .map(|field| field.ty(gcx, substs))
788 .for_each(|field| drop_field(self, field));
790 // Same as above, but for tuples.
791 ty::TyTuple(tys) => {
792 tys.iter().cloned().enumerate()
793 .for_each(|field| drop_field(self, field));
795 // Closures and generators also have disjoint fields, but they are only
796 // directly accessed in the body of the closure/generator.
797 ty::TyClosure(def, substs)
798 | ty::TyGenerator(def, substs, ..)
799 if *drop_place == Place::Local(Local::new(1)) && !self.mir.upvar_decls.is_empty()
801 substs.upvar_tys(def, self.tcx).enumerate()
802 .for_each(|field| drop_field(self, field));
805 // We have now refined the type of the value being
806 // dropped (potentially) to just the type of a
807 // subfield; so check whether that field's type still
808 // "needs drop". If so, we assume that the destructor
809 // may access any data it likes (i.e., a Deep Write).
810 if erased_drop_place_ty.needs_drop(gcx, self.param_env) {
812 ContextKind::Drop.new(loc),
814 (Deep, Write(WriteKind::StorageDeadOrDrop)),
815 LocalMutationIsAllowed::Yes,
823 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
824 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
825 /// place is initialized and (b) it is not borrowed in some way that would prevent this
828 /// Returns true if an error is reported, false otherwise.
832 place_span: (&Place<'tcx>, Span),
833 kind: (ShallowOrDeep, ReadOrWrite),
834 is_local_mutation_allowed: LocalMutationIsAllowed,
835 flow_state: &Flows<'cx, 'gcx, 'tcx>,
836 ) -> AccessErrorsReported {
839 if let Activation(_, borrow_index) = rw {
840 if self.reservation_error_reported.contains(&place_span.0) {
842 "skipping access_place for activation of invalid reservation \
843 place: {:?} borrow_index: {:?}",
844 place_span.0, borrow_index
846 return AccessErrorsReported {
847 mutability_error: false,
848 conflict_error: true,
853 if self.access_place_error_reported
854 .contains(&(place_span.0.clone(), place_span.1))
857 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
860 return AccessErrorsReported {
861 mutability_error: false,
862 conflict_error: true,
866 let mutability_error =
867 self.check_access_permissions(place_span, rw, is_local_mutation_allowed);
869 self.check_access_for_conflict(context, place_span, sd, rw, flow_state);
871 if conflict_error || mutability_error {
873 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
876 self.access_place_error_reported
877 .insert((place_span.0.clone(), place_span.1));
880 AccessErrorsReported {
886 fn check_access_for_conflict(
889 place_span: (&Place<'tcx>, Span),
892 flow_state: &Flows<'cx, 'gcx, 'tcx>,
895 "check_access_for_conflict(context={:?}, place_span={:?}, sd={:?}, rw={:?})",
902 let mut error_reported = false;
903 self.each_borrow_involving_path(
907 |this, borrow_index, borrow| match (rw, borrow.kind) {
908 // Obviously an activation is compatible with its own
909 // reservation (or even prior activating uses of same
910 // borrow); so don't check if they interfere.
912 // NOTE: *reservations* do conflict with themselves;
913 // thus aren't injecting unsoundenss w/ this check.)
914 (Activation(_, activating), _) if activating == borrow_index => {
916 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
917 skipping {:?} b/c activation of same borrow_index",
921 (borrow_index, borrow),
926 (Read(_), BorrowKind::Shared) | (Reservation(..), BorrowKind::Shared) => {
930 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
931 // Reading from mere reservations of mutable-borrows is OK.
932 if !this.is_active(borrow, context.loc) {
933 assert!(this.allow_two_phase_borrow(borrow.kind));
934 return Control::Continue;
939 error_reported = true;
940 this.report_use_while_mutably_borrowed(context, place_span, borrow)
942 ReadKind::Borrow(bk) => {
943 error_reported = true;
944 this.report_conflicting_borrow(
955 (Reservation(kind), BorrowKind::Unique)
956 | (Reservation(kind), BorrowKind::Mut { .. })
957 | (Activation(kind, _), _)
958 | (Write(kind), _) => {
962 "recording invalid reservation of \
966 this.reservation_error_reported.insert(place_span.0.clone());
968 Activation(_, activating) => {
970 "observing check_place for activation of \
975 Read(..) | Write(..) => {}
979 WriteKind::MutableBorrow(bk) => {
980 error_reported = true;
981 this.report_conflicting_borrow(
988 WriteKind::StorageDeadOrDrop => {
989 error_reported = true;
990 this.report_borrowed_value_does_not_live_long_enough(
996 WriteKind::Mutate => {
997 error_reported = true;
998 this.report_illegal_mutation_of_borrowed(context, place_span, borrow)
1000 WriteKind::Move => {
1001 error_reported = true;
1002 this.report_move_out_while_borrowed(context, place_span, &borrow)
1016 place_span: (&Place<'tcx>, Span),
1017 kind: ShallowOrDeep,
1019 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1021 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1023 MutateMode::WriteAndRead => {
1024 self.check_if_path_or_subpath_is_moved(
1026 InitializationRequiringAction::Update,
1031 MutateMode::JustWrite => {
1032 self.check_if_assigned_path_is_moved(context, place_span, flow_state);
1036 let errors_reported = self.access_place(
1039 (kind, Write(WriteKind::Mutate)),
1040 // We want immutable upvars to cause an "assignment to immutable var"
1041 // error, not an "reassignment of immutable var" error, because the
1042 // latter can't find a good previous assignment span.
1044 // There's probably a better way to do this.
1045 LocalMutationIsAllowed::ExceptUpvars,
1049 if !errors_reported.mutability_error {
1050 // check for reassignments to immutable local variables
1051 self.check_if_reassignment_to_immutable_state(context, place_span, flow_state);
1058 (rvalue, span): (&Rvalue<'tcx>, Span),
1059 _location: Location,
1060 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1063 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1064 let access_kind = match bk {
1065 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1066 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1067 let wk = WriteKind::MutableBorrow(bk);
1068 if self.allow_two_phase_borrow(bk) {
1069 (Deep, Reservation(wk))
1080 LocalMutationIsAllowed::No,
1084 self.check_if_path_or_subpath_is_moved(
1086 InitializationRequiringAction::Borrow,
1092 Rvalue::Use(ref operand)
1093 | Rvalue::Repeat(ref operand, _)
1094 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1095 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1096 self.consume_operand(context, (operand, span), flow_state)
1099 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1100 let af = match *rvalue {
1101 Rvalue::Len(..) => ArtificialField::ArrayLength,
1102 Rvalue::Discriminant(..) => ArtificialField::Discriminant,
1103 _ => unreachable!(),
1108 (Shallow(Some(af)), Read(ReadKind::Copy)),
1109 LocalMutationIsAllowed::No,
1112 self.check_if_path_or_subpath_is_moved(
1114 InitializationRequiringAction::Use,
1120 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1121 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1122 self.consume_operand(context, (operand1, span), flow_state);
1123 self.consume_operand(context, (operand2, span), flow_state);
1126 Rvalue::NullaryOp(_op, _ty) => {
1127 // nullary ops take no dynamic input; no borrowck effect.
1129 // FIXME: is above actually true? Do we want to track
1130 // the fact that uninitialized data can be created via
1134 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1135 // We need to report back the list of mutable upvars that were
1136 // moved into the closure and subsequently used by the closure,
1137 // in order to populate our used_mut set.
1138 if let AggregateKind::Closure(def_id, _) = &**aggregate_kind {
1139 let BorrowCheckResult { used_mut_upvars, .. } = self.tcx.mir_borrowck(*def_id);
1140 for field in used_mut_upvars {
1141 match operands[field.index()] {
1142 Operand::Move(Place::Local(local)) => {
1143 self.used_mut.insert(local);
1145 Operand::Move(Place::Projection(ref proj)) => {
1146 if let Some(field) = self.is_upvar_field_projection(&proj.base) {
1147 self.used_mut_upvars.push(field);
1150 Operand::Move(Place::Static(..)) |
1152 Operand::Constant(..) => {}
1157 for operand in operands {
1158 self.consume_operand(context, (operand, span), flow_state);
1167 (operand, span): (&Operand<'tcx>, Span),
1168 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1171 Operand::Copy(ref place) => {
1172 // copy of place: check if this is "copy of frozen path"
1173 // (FIXME: see check_loans.rs)
1177 (Deep, Read(ReadKind::Copy)),
1178 LocalMutationIsAllowed::No,
1182 // Finally, check if path was already moved.
1183 self.check_if_path_or_subpath_is_moved(
1185 InitializationRequiringAction::Use,
1190 Operand::Move(ref place) => {
1191 // move of place: check if this is move of already borrowed path
1195 (Deep, Write(WriteKind::Move)),
1196 LocalMutationIsAllowed::Yes,
1200 // Finally, check if path was already moved.
1201 self.check_if_path_or_subpath_is_moved(
1203 InitializationRequiringAction::Use,
1208 Operand::Constant(_) => {}
1212 /// Returns whether a borrow of this place is invalidated when the function
1214 fn check_for_invalidation_at_exit(
1217 borrow: &BorrowData<'tcx>,
1220 debug!("check_for_invalidation_at_exit({:?})", borrow);
1221 let place = &borrow.borrowed_place;
1222 let root_place = self.prefixes(place, PrefixSet::All).last().unwrap();
1224 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1225 // we just know that all locals are dropped at function exit (otherwise
1226 // we'll have a memory leak) and assume that all statics have a destructor.
1228 // FIXME: allow thread-locals to borrow other thread locals?
1229 let (might_be_alive, will_be_dropped) = match root_place {
1230 Place::Static(statik) => {
1231 // Thread-locals might be dropped after the function exits, but
1232 // "true" statics will never be.
1233 let is_thread_local = self.tcx
1234 .get_attrs(statik.def_id)
1236 .any(|attr| attr.check_name("thread_local"));
1238 (true, is_thread_local)
1240 Place::Local(_) => {
1241 // Locals are always dropped at function exit, and if they
1242 // have a destructor it would've been called already.
1243 (false, self.locals_are_invalidated_at_exit)
1245 Place::Projection(..) => {
1246 bug!("root of {:?} is a projection ({:?})?", place, root_place)
1250 if !will_be_dropped {
1252 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1258 // FIXME: replace this with a proper borrow_conflicts_with_place when
1260 let sd = if might_be_alive { Deep } else { Shallow(None) };
1262 if self.places_conflict(place, root_place, sd) {
1263 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1264 // FIXME: should be talking about the region lifetime instead
1265 // of just a span here.
1266 let span = self.tcx.sess.codemap().end_point(span);
1267 self.report_borrowed_value_does_not_live_long_enough(
1275 /// Reports an error if this is a borrow of local data.
1276 /// This is called for all Yield statements on movable generators
1277 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1278 fn borrow_of_local_data<'tcx>(place: &Place<'tcx>) -> bool {
1280 Place::Static(..) => false,
1281 Place::Local(..) => true,
1282 Place::Projection(box proj) => {
1284 // Reborrow of already borrowed data is ignored
1285 // Any errors will be caught on the initial borrow
1286 ProjectionElem::Deref => false,
1288 // For interior references and downcasts, find out if the base is local
1289 ProjectionElem::Field(..)
1290 | ProjectionElem::Index(..)
1291 | ProjectionElem::ConstantIndex { .. }
1292 | ProjectionElem::Subslice { .. }
1293 | ProjectionElem::Downcast(..) => borrow_of_local_data(&proj.base),
1299 debug!("check_for_local_borrow({:?})", borrow);
1301 if borrow_of_local_data(&borrow.borrowed_place) {
1303 .cannot_borrow_across_generator_yield(
1304 self.retrieve_borrow_span(borrow),
1312 fn check_activations(
1316 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1318 if !self.tcx.two_phase_borrows() {
1322 // Two-phase borrow support: For each activation that is newly
1323 // generated at this statement, check if it interferes with
1325 let borrow_set = self.borrow_set.clone();
1326 for &borrow_index in borrow_set.activations_at_location(location) {
1327 let borrow = &borrow_set[borrow_index];
1329 // only mutable borrows should be 2-phase
1330 assert!(match borrow.kind {
1331 BorrowKind::Shared => false,
1332 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1336 ContextKind::Activation.new(location),
1337 (&borrow.borrowed_place, span),
1340 Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1342 LocalMutationIsAllowed::No,
1345 // We do not need to call `check_if_path_or_subpath_is_moved`
1346 // again, as we already called it when we made the
1347 // initial reservation.
1352 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1353 fn check_if_reassignment_to_immutable_state(
1356 (place, span): (&Place<'tcx>, Span),
1357 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1359 debug!("check_if_reassignment_to_immutable_state({:?})", place);
1360 // determine if this path has a non-mut owner (and thus needs checking).
1361 if let Ok(()) = self.is_mutable(place, LocalMutationIsAllowed::No) {
1365 "check_if_reassignment_to_immutable_state({:?}) - is an imm local",
1369 for i in flow_state.ever_inits.iter_incoming() {
1370 let init = self.move_data.inits[i];
1371 let init_place = &self.move_data.move_paths[init.path].place;
1372 if self.places_conflict(&init_place, place, Deep) {
1373 self.report_illegal_reassignment(context, (place, span), init.span);
1379 fn check_if_full_path_is_moved(
1382 desired_action: InitializationRequiringAction,
1383 place_span: (&Place<'tcx>, Span),
1384 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1386 // FIXME: analogous code in check_loans first maps `place` to
1387 // its base_path ... but is that what we want here?
1388 let place = self.base_path(place_span.0);
1390 let maybe_uninits = &flow_state.uninits;
1391 let curr_move_outs = &flow_state.move_outs;
1395 // 1. Move of `a.b.c`, use of `a.b.c`
1396 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1397 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1398 // partial initialization support, one might have `a.x`
1399 // initialized but not `a.b`.
1403 // 4. Move of `a.b.c`, use of `a.b.d`
1404 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1405 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1406 // must have been initialized for the use to be sound.
1407 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1409 // The dataflow tracks shallow prefixes distinctly (that is,
1410 // field-accesses on P distinctly from P itself), in order to
1411 // track substructure initialization separately from the whole
1414 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1415 // which we have a MovePath is `a.b`, then that means that the
1416 // initialization state of `a.b` is all we need to inspect to
1417 // know if `a.b.c` is valid (and from that we infer that the
1418 // dereference and `.d` access is also valid, since we assume
1419 // `a.b.c` is assigned a reference to a initialized and
1420 // well-formed record structure.)
1422 // Therefore, if we seek out the *closest* prefix for which we
1423 // have a MovePath, that should capture the initialization
1424 // state for the place scenario.
1426 // This code covers scenarios 1, 2, and 3.
1428 debug!("check_if_full_path_is_moved place: {:?}", place);
1429 match self.move_path_closest_to(place) {
1431 if maybe_uninits.contains(&mpi) {
1432 self.report_use_of_moved_or_uninitialized(
1439 return; // don't bother finding other problems.
1442 Err(NoMovePathFound::ReachedStatic) => {
1443 // Okay: we do not build MoveData for static variables
1444 } // Only query longest prefix with a MovePath, not further
1445 // ancestors; dataflow recurs on children when parents
1446 // move (to support partial (re)inits).
1448 // (I.e. querying parents breaks scenario 7; but may want
1449 // to do such a query based on partial-init feature-gate.)
1453 fn check_if_path_or_subpath_is_moved(
1456 desired_action: InitializationRequiringAction,
1457 place_span: (&Place<'tcx>, Span),
1458 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1460 // FIXME: analogous code in check_loans first maps `place` to
1461 // its base_path ... but is that what we want here?
1462 let place = self.base_path(place_span.0);
1464 let maybe_uninits = &flow_state.uninits;
1465 let curr_move_outs = &flow_state.move_outs;
1469 // 1. Move of `a.b.c`, use of `a` or `a.b`
1470 // partial initialization support, one might have `a.x`
1471 // initialized but not `a.b`.
1472 // 2. All bad scenarios from `check_if_full_path_is_moved`
1476 // 3. Move of `a.b.c`, use of `a.b.d`
1477 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1478 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1479 // must have been initialized for the use to be sound.
1480 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1482 self.check_if_full_path_is_moved(context, desired_action, place_span, flow_state);
1484 // A move of any shallow suffix of `place` also interferes
1485 // with an attempt to use `place`. This is scenario 3 above.
1487 // (Distinct from handling of scenarios 1+2+4 above because
1488 // `place` does not interfere with suffixes of its prefixes,
1489 // e.g. `a.b.c` does not interfere with `a.b.d`)
1491 // This code covers scenario 1.
1493 debug!("check_if_path_or_subpath_is_moved place: {:?}", place);
1494 if let Some(mpi) = self.move_path_for_place(place) {
1495 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1496 self.report_use_of_moved_or_uninitialized(
1503 return; // don't bother finding other problems.
1508 /// Currently MoveData does not store entries for all places in
1509 /// the input MIR. For example it will currently filter out
1510 /// places that are Copy; thus we do not track places of shared
1511 /// reference type. This routine will walk up a place along its
1512 /// prefixes, searching for a foundational place that *is*
1513 /// tracked in the MoveData.
1515 /// An Err result includes a tag indicated why the search failed.
1516 /// Currently this can only occur if the place is built off of a
1517 /// static variable, as we do not track those in the MoveData.
1518 fn move_path_closest_to(
1520 place: &Place<'tcx>,
1521 ) -> Result<MovePathIndex, NoMovePathFound> {
1522 let mut last_prefix = place;
1523 for prefix in self.prefixes(place, PrefixSet::All) {
1524 if let Some(mpi) = self.move_path_for_place(prefix) {
1527 last_prefix = prefix;
1529 match *last_prefix {
1530 Place::Local(_) => panic!("should have move path for every Local"),
1531 Place::Projection(_) => panic!("PrefixSet::All meant don't stop for Projection"),
1532 Place::Static(_) => return Err(NoMovePathFound::ReachedStatic),
1536 fn move_path_for_place(&mut self, place: &Place<'tcx>) -> Option<MovePathIndex> {
1537 // If returns None, then there is no move path corresponding
1538 // to a direct owner of `place` (which means there is nothing
1539 // that borrowck tracks for its analysis).
1541 match self.move_data.rev_lookup.find(place) {
1542 LookupResult::Parent(_) => None,
1543 LookupResult::Exact(mpi) => Some(mpi),
1547 fn check_if_assigned_path_is_moved(
1550 (place, span): (&Place<'tcx>, Span),
1551 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1553 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1554 // recur down place; dispatch to external checks when necessary
1555 let mut place = place;
1558 Place::Local(_) | Place::Static(_) => {
1559 // assigning to `x` does not require `x` be initialized.
1562 Place::Projection(ref proj) => {
1563 let Projection { ref base, ref elem } = **proj;
1565 ProjectionElem::Index(_/*operand*/) |
1566 ProjectionElem::ConstantIndex { .. } |
1567 // assigning to P[i] requires P to be valid.
1568 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1569 // assigning to (P->variant) is okay if assigning to `P` is okay
1571 // FIXME: is this true even if P is a adt with a dtor?
1574 // assigning to (*P) requires P to be initialized
1575 ProjectionElem::Deref => {
1576 self.check_if_full_path_is_moved(
1577 context, InitializationRequiringAction::Use,
1578 (base, span), flow_state);
1579 // (base initialized; no need to
1584 ProjectionElem::Subslice { .. } => {
1585 panic!("we don't allow assignments to subslices, context: {:?}",
1589 ProjectionElem::Field(..) => {
1590 // if type of `P` has a dtor, then
1591 // assigning to `P.f` requires `P` itself
1592 // be already initialized
1594 match base.ty(self.mir, tcx).to_ty(tcx).sty {
1595 ty::TyAdt(def, _) if def.has_dtor(tcx) => {
1597 // FIXME: analogous code in
1598 // check_loans.rs first maps
1599 // `base` to its base_path.
1601 self.check_if_path_or_subpath_is_moved(
1602 context, InitializationRequiringAction::Assignment,
1603 (base, span), flow_state);
1605 // (base initialized; no need to
1621 fn specialized_description(&self, place:&Place<'tcx>) -> Option<String>{
1622 if let Some(_name) = self.describe_place(place) {
1623 Some(format!("data in a `&` reference"))
1629 fn get_default_err_msg(&self, place:&Place<'tcx>) -> String{
1630 match self.describe_place(place) {
1631 Some(name) => format!("immutable item `{}`", name),
1632 None => "immutable item".to_owned(),
1636 fn get_secondary_err_msg(&self, place:&Place<'tcx>) -> String{
1637 match self.specialized_description(place) {
1638 Some(_) => format!("data in a `&` reference"),
1639 None => self.get_default_err_msg(place)
1643 fn get_primary_err_msg(&self, place:&Place<'tcx>) -> String{
1644 if let Some(name) = self.describe_place(place) {
1645 format!("`{}` is a `&` reference, so the data it refers to cannot be written", name)
1647 format!("cannot assign through `&`-reference")
1651 /// Check the permissions for the given place and read or write kind
1653 /// Returns true if an error is reported, false otherwise.
1654 fn check_access_permissions(
1656 (place, span): (&Place<'tcx>, Span),
1658 is_local_mutation_allowed: LocalMutationIsAllowed,
1661 "check_access_permissions({:?}, {:?}, {:?})",
1662 place, kind, is_local_mutation_allowed
1664 let mut error_reported = false;
1666 Reservation(WriteKind::MutableBorrow(BorrowKind::Unique))
1667 | Write(WriteKind::MutableBorrow(BorrowKind::Unique)) => {
1668 if let Err(_place_err) = self.is_mutable(place, LocalMutationIsAllowed::Yes) {
1669 span_bug!(span, "&unique borrow for {:?} should not fail", place);
1672 Reservation(WriteKind::MutableBorrow(BorrowKind::Mut { .. }))
1673 | Write(WriteKind::MutableBorrow(BorrowKind::Mut { .. })) => if let Err(place_err) =
1674 self.is_mutable(place, is_local_mutation_allowed)
1676 error_reported = true;
1677 let item_msg = self.get_default_err_msg(place);
1678 let mut err = self.tcx
1679 .cannot_borrow_path_as_mutable(span, &item_msg, Origin::Mir);
1680 err.span_label(span, "cannot borrow as mutable");
1682 if place != place_err {
1683 if let Some(name) = self.describe_place(place_err) {
1684 err.note(&format!("the value which is causing this path not to be mutable \
1685 is...: `{}`", name));
1691 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1693 Place::Local(local) => {
1694 self.used_mut.insert(*local);
1696 Place::Projection(ref proj) => {
1697 if let Some(field) = self.is_upvar_field_projection(&proj.base) {
1698 self.used_mut_upvars.push(field);
1701 Place::Static(..) => {}
1703 if let Err(place_err) = self.is_mutable(place, is_local_mutation_allowed) {
1704 error_reported = true;
1705 let mut err_info = None;
1708 Place::Projection(box Projection {
1709 ref base, elem:ProjectionElem::Deref}) => {
1711 Place::Local(local) => {
1712 let locations = self.mir.find_assignments(local);
1713 if locations.len() > 0 {
1714 let item_msg = if error_reported {
1715 self.get_secondary_err_msg(base)
1717 self.get_default_err_msg(place)
1719 let sp = self.mir.source_info(locations[0]).span;
1720 let mut to_suggest_span = String::new();
1722 self.tcx.sess.codemap().span_to_snippet(sp) {
1723 to_suggest_span = src[1..].to_string();
1727 "consider changing this to be a \
1731 self.get_primary_err_msg(base)));
1740 if let Some((err_help_span,
1744 sec_span)) = err_info {
1745 let mut err = self.tcx.cannot_assign(span, &item_msg, Origin::Mir);
1746 err.span_suggestion(err_help_span,
1748 format!("&mut {}", to_suggest_span));
1749 if place != place_err {
1750 err.span_label(span, sec_span);
1754 let item_msg_ = self.get_default_err_msg(place);
1755 let mut err = self.tcx.cannot_assign(span, &item_msg_, Origin::Mir);
1756 err.span_label(span, "cannot mutate");
1757 if place != place_err {
1758 if let Some(name) = self.describe_place(place_err) {
1759 err.note(&format!("the value which is causing this path not to be \
1760 mutable is...: `{}`", name));
1767 Reservation(WriteKind::Move)
1768 | Reservation(WriteKind::StorageDeadOrDrop)
1769 | Reservation(WriteKind::MutableBorrow(BorrowKind::Shared))
1770 | Write(WriteKind::Move)
1771 | Write(WriteKind::StorageDeadOrDrop)
1772 | Write(WriteKind::MutableBorrow(BorrowKind::Shared)) => {
1773 if let Err(_place_err) = self.is_mutable(place, is_local_mutation_allowed) {
1774 self.tcx.sess.delay_span_bug(
1777 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
1783 Activation(..) => {} // permission checks are done at Reservation point.
1784 Read(ReadKind::Borrow(BorrowKind::Unique))
1785 | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
1786 | Read(ReadKind::Borrow(BorrowKind::Shared))
1787 | Read(ReadKind::Copy) => {} // Access authorized
1793 /// Can this value be written or borrowed mutably
1796 place: &'d Place<'tcx>,
1797 is_local_mutation_allowed: LocalMutationIsAllowed,
1798 ) -> Result<(), &'d Place<'tcx>> {
1800 Place::Local(local) => {
1801 let local = &self.mir.local_decls[local];
1802 match local.mutability {
1803 Mutability::Not => match is_local_mutation_allowed {
1804 LocalMutationIsAllowed::Yes | LocalMutationIsAllowed::ExceptUpvars => {
1807 LocalMutationIsAllowed::No => Err(place),
1809 Mutability::Mut => Ok(()),
1812 Place::Static(ref static_) =>
1813 if self.tcx.is_static(static_.def_id) != Some(hir::Mutability::MutMutable) {
1818 Place::Projection(ref proj) => {
1820 ProjectionElem::Deref => {
1821 let base_ty = proj.base.ty(self.mir, self.tcx).to_ty(self.tcx);
1823 // Check the kind of deref to decide
1825 ty::TyRef(_, tnm) => {
1827 // Shared borrowed data is never mutable
1828 hir::MutImmutable => Err(place),
1829 // Mutably borrowed data is mutable, but only if we have a
1830 // unique path to the `&mut`
1831 hir::MutMutable => {
1832 let mode = match self.is_upvar_field_projection(&proj.base)
1836 self.mir.upvar_decls[field.index()].by_ref
1839 is_local_mutation_allowed
1841 _ => LocalMutationIsAllowed::Yes,
1844 self.is_mutable(&proj.base, mode)
1848 ty::TyRawPtr(tnm) => {
1850 // `*const` raw pointers are not mutable
1851 hir::MutImmutable => return Err(place),
1852 // `*mut` raw pointers are always mutable, regardless of context
1853 // The users have to check by themselve.
1854 hir::MutMutable => return Ok(()),
1857 // `Box<T>` owns its content, so mutable if its location is mutable
1858 _ if base_ty.is_box() => {
1859 self.is_mutable(&proj.base, is_local_mutation_allowed)
1861 // Deref should only be for reference, pointers or boxes
1862 _ => bug!("Deref of unexpected type: {:?}", base_ty),
1865 // All other projections are owned by their base path, so mutable if
1866 // base path is mutable
1867 ProjectionElem::Field(..)
1868 | ProjectionElem::Index(..)
1869 | ProjectionElem::ConstantIndex { .. }
1870 | ProjectionElem::Subslice { .. }
1871 | ProjectionElem::Downcast(..) => {
1872 if let Some(field) = self.is_upvar_field_projection(place) {
1873 let decl = &self.mir.upvar_decls[field.index()];
1875 "decl.mutability={:?} local_mutation_is_allowed={:?} place={:?}",
1876 decl, is_local_mutation_allowed, place
1878 match (decl.mutability, is_local_mutation_allowed) {
1879 (Mutability::Not, LocalMutationIsAllowed::No)
1880 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
1883 (Mutability::Not, LocalMutationIsAllowed::Yes)
1884 | (Mutability::Mut, _) => {
1885 self.is_mutable(&proj.base, is_local_mutation_allowed)
1889 self.is_mutable(&proj.base, is_local_mutation_allowed)
1897 /// If this is a field projection, and the field is being projected from a closure type,
1898 /// then returns the index of the field being projected. Note that this closure will always
1899 /// be `self` in the current MIR, because that is the only time we directly access the fields
1900 /// of a closure type.
1901 fn is_upvar_field_projection(&self, place: &Place<'tcx>) -> Option<Field> {
1903 Place::Projection(ref proj) => match proj.elem {
1904 ProjectionElem::Field(field, _ty) => {
1905 let is_projection_from_ty_closure = proj.base
1906 .ty(self.mir, self.tcx)
1910 if is_projection_from_ty_closure {
1923 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1924 enum NoMovePathFound {
1928 /// The degree of overlap between 2 places for borrow-checking.
1930 /// The places might partially overlap - in this case, we give
1931 /// up and say that they might conflict. This occurs when
1932 /// different fields of a union are borrowed. For example,
1933 /// if `u` is a union, we have no way of telling how disjoint
1934 /// `u.a.x` and `a.b.y` are.
1936 /// The places have the same type, and are either completely disjoint
1937 /// or equal - i.e. they can't "partially" overlap as can occur with
1938 /// unions. This is the "base case" on which we recur for extensions
1941 /// The places are disjoint, so we know all extensions of them
1942 /// will also be disjoint.
1946 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1947 // Given that the bases of `elem1` and `elem2` are always either equal
1948 // or disjoint (and have the same type!), return the overlap situation
1949 // between `elem1` and `elem2`.
1950 fn place_element_conflict(&self, elem1: &Place<'tcx>, elem2: &Place<'tcx>) -> Overlap {
1951 match (elem1, elem2) {
1952 (Place::Local(l1), Place::Local(l2)) => {
1954 // the same local - base case, equal
1955 debug!("place_element_conflict: DISJOINT-OR-EQ-LOCAL");
1956 Overlap::EqualOrDisjoint
1958 // different locals - base case, disjoint
1959 debug!("place_element_conflict: DISJOINT-LOCAL");
1963 (Place::Static(static1), Place::Static(static2)) => {
1964 if static1.def_id != static2.def_id {
1965 debug!("place_element_conflict: DISJOINT-STATIC");
1967 } else if self.tcx.is_static(static1.def_id) == Some(hir::Mutability::MutMutable) {
1968 // We ignore mutable statics - they can only be unsafe code.
1969 debug!("place_element_conflict: IGNORE-STATIC-MUT");
1972 debug!("place_element_conflict: DISJOINT-OR-EQ-STATIC");
1973 Overlap::EqualOrDisjoint
1976 (Place::Local(_), Place::Static(_)) | (Place::Static(_), Place::Local(_)) => {
1977 debug!("place_element_conflict: DISJOINT-STATIC-LOCAL");
1980 (Place::Projection(pi1), Place::Projection(pi2)) => {
1981 match (&pi1.elem, &pi2.elem) {
1982 (ProjectionElem::Deref, ProjectionElem::Deref) => {
1983 // derefs (e.g. `*x` vs. `*x`) - recur.
1984 debug!("place_element_conflict: DISJOINT-OR-EQ-DEREF");
1985 Overlap::EqualOrDisjoint
1987 (ProjectionElem::Field(f1, _), ProjectionElem::Field(f2, _)) => {
1989 // same field (e.g. `a.y` vs. `a.y`) - recur.
1990 debug!("place_element_conflict: DISJOINT-OR-EQ-FIELD");
1991 Overlap::EqualOrDisjoint
1993 let ty = pi1.base.ty(self.mir, self.tcx).to_ty(self.tcx);
1995 ty::TyAdt(def, _) if def.is_union() => {
1996 // Different fields of a union, we are basically stuck.
1997 debug!("place_element_conflict: STUCK-UNION");
2001 // Different fields of a struct (`a.x` vs. `a.y`). Disjoint!
2002 debug!("place_element_conflict: DISJOINT-FIELD");
2008 (ProjectionElem::Downcast(_, v1), ProjectionElem::Downcast(_, v2)) => {
2009 // different variants are treated as having disjoint fields,
2010 // even if they occupy the same "space", because it's
2011 // impossible for 2 variants of the same enum to exist
2012 // (and therefore, to be borrowed) at the same time.
2014 // Note that this is different from unions - we *do* allow
2015 // this code to compile:
2018 // fn foo(x: &mut Result<i32, i32>) {
2019 // let mut v = None;
2020 // if let Ok(ref mut a) = *x {
2023 // // here, you would *think* that the
2024 // // *entirety* of `x` would be borrowed,
2025 // // but in fact only the `Ok` variant is,
2026 // // so the `Err` variant is *entirely free*:
2027 // if let Err(ref mut a) = *x {
2034 debug!("place_element_conflict: DISJOINT-OR-EQ-FIELD");
2035 Overlap::EqualOrDisjoint
2037 debug!("place_element_conflict: DISJOINT-FIELD");
2041 (ProjectionElem::Index(..), ProjectionElem::Index(..))
2042 | (ProjectionElem::Index(..), ProjectionElem::ConstantIndex { .. })
2043 | (ProjectionElem::Index(..), ProjectionElem::Subslice { .. })
2044 | (ProjectionElem::ConstantIndex { .. }, ProjectionElem::Index(..))
2046 ProjectionElem::ConstantIndex { .. },
2047 ProjectionElem::ConstantIndex { .. },
2049 | (ProjectionElem::ConstantIndex { .. }, ProjectionElem::Subslice { .. })
2050 | (ProjectionElem::Subslice { .. }, ProjectionElem::Index(..))
2051 | (ProjectionElem::Subslice { .. }, ProjectionElem::ConstantIndex { .. })
2052 | (ProjectionElem::Subslice { .. }, ProjectionElem::Subslice { .. }) => {
2053 // Array indexes (`a[0]` vs. `a[i]`). These can either be disjoint
2054 // (if the indexes differ) or equal (if they are the same), so this
2055 // is the recursive case that gives "equal *or* disjoint" its meaning.
2057 // Note that by construction, MIR at borrowck can't subdivide
2058 // `Subslice` accesses (e.g. `a[2..3][i]` will never be present) - they
2059 // are only present in slice patterns, and we "merge together" nested
2060 // slice patterns. That means we don't have to think about these. It's
2061 // probably a good idea to assert this somewhere, but I'm too lazy.
2063 // FIXME(#8636) we might want to return Disjoint if
2064 // both projections are constant and disjoint.
2065 debug!("place_element_conflict: DISJOINT-OR-EQ-ARRAY");
2066 Overlap::EqualOrDisjoint
2069 (ProjectionElem::Deref, _)
2070 | (ProjectionElem::Field(..), _)
2071 | (ProjectionElem::Index(..), _)
2072 | (ProjectionElem::ConstantIndex { .. }, _)
2073 | (ProjectionElem::Subslice { .. }, _)
2074 | (ProjectionElem::Downcast(..), _) => bug!(
2075 "mismatched projections in place_element_conflict: {:?} and {:?}",
2081 (Place::Projection(_), _) | (_, Place::Projection(_)) => bug!(
2082 "unexpected elements in place_element_conflict: {:?} and {:?}",
2089 /// Returns whether an access of kind `access` to `access_place` conflicts with
2090 /// a borrow/full access to `borrow_place` (for deep accesses to mutable
2091 /// locations, this function is symmetric between `borrow_place` & `access_place`).
2094 borrow_place: &Place<'tcx>,
2095 access_place: &Place<'tcx>,
2096 access: ShallowOrDeep,
2099 "places_conflict({:?},{:?},{:?})",
2100 borrow_place, access_place, access
2103 // Return all the prefixes of `place` in reverse order, including
2105 fn place_elements<'a, 'tcx>(place: &'a Place<'tcx>) -> Vec<&'a Place<'tcx>> {
2106 let mut result = vec![];
2107 let mut place = place;
2111 Place::Projection(interior) => {
2112 place = &interior.base;
2114 Place::Local(_) | Place::Static(_) => {
2122 let borrow_components = place_elements(borrow_place);
2123 let access_components = place_elements(access_place);
2125 "places_conflict: components {:?} / {:?}",
2126 borrow_components, access_components
2129 let borrow_components = borrow_components
2132 .chain(iter::repeat(None));
2133 let access_components = access_components
2136 .chain(iter::repeat(None));
2137 // The borrowck rules for proving disjointness are applied from the "root" of the
2138 // borrow forwards, iterating over "similar" projections in lockstep until
2139 // we can prove overlap one way or another. Essentially, we treat `Overlap` as
2140 // a monoid and report a conflict if the product ends up not being `Disjoint`.
2142 // At each step, if we didn't run out of borrow or place, we know that our elements
2143 // have the same type, and that they only overlap if they are the identical.
2145 // For example, if we are comparing these:
2146 // BORROW: (*x1[2].y).z.a
2147 // ACCESS: (*x1[i].y).w.b
2149 // Then our steps are:
2150 // x1 | x1 -- places are the same
2151 // x1[2] | x1[i] -- equal or disjoint (disjoint if indexes differ)
2152 // x1[2].y | x1[i].y -- equal or disjoint
2153 // *x1[2].y | *x1[i].y -- equal or disjoint
2154 // (*x1[2].y).z | (*x1[i].y).w -- we are disjoint and don't need to check more!
2156 // Because `zip` does potentially bad things to the iterator inside, this loop
2157 // also handles the case where the access might be a *prefix* of the borrow, e.g.
2159 // BORROW: (*x1[2].y).z.a
2162 // Then our steps are:
2163 // x1 | x1 -- places are the same
2164 // x1[2] | x1[i] -- equal or disjoint (disjoint if indexes differ)
2165 // x1[2].y | x1[i].y -- equal or disjoint
2167 // -- here we run out of access - the borrow can access a part of it. If this
2168 // is a full deep access, then we *know* the borrow conflicts with it. However,
2169 // if the access is shallow, then we can proceed:
2171 // x1[2].y | (*x1[i].y) -- a deref! the access can't get past this, so we
2174 // Our invariant is, that at each step of the iteration:
2175 // - If we didn't run out of access to match, our borrow and access are comparable
2176 // and either equal or disjoint.
2177 // - If we did run out of accesss, the borrow can access a part of it.
2178 for (borrow_c, access_c) in borrow_components.zip(access_components) {
2179 // loop invariant: borrow_c is always either equal to access_c or disjoint from it.
2180 debug!("places_conflict: {:?} vs. {:?}", borrow_c, access_c);
2181 match (borrow_c, access_c) {
2183 // If we didn't run out of access, the borrow can access all of our
2184 // place (e.g. a borrow of `a.b` with an access to `a.b.c`),
2185 // so we have a conflict.
2187 // If we did, then we still know that the borrow can access a *part*
2188 // of our place that our access cares about (a borrow of `a.b.c`
2189 // with an access to `a.b`), so we still have a conflict.
2191 // FIXME: Differs from AST-borrowck; includes drive-by fix
2192 // to #38899. Will probably need back-compat mode flag.
2193 debug!("places_conflict: full borrow, CONFLICT");
2196 (Some(borrow_c), None) => {
2197 // We know that the borrow can access a part of our place. This
2198 // is a conflict if that is a part our access cares about.
2200 let (base, elem) = match borrow_c {
2201 Place::Projection(box Projection { base, elem }) => (base, elem),
2202 _ => bug!("place has no base?"),
2204 let base_ty = base.ty(self.mir, self.tcx).to_ty(self.tcx);
2206 match (elem, &base_ty.sty, access) {
2207 (_, _, Shallow(Some(ArtificialField::Discriminant)))
2208 | (_, _, Shallow(Some(ArtificialField::ArrayLength))) => {
2209 // The discriminant and array length are like
2210 // additional fields on the type; they do not
2211 // overlap any existing data there. Furthermore,
2212 // they cannot actually be a prefix of any
2213 // borrowed place (at least in MIR as it is
2216 // e.g. a (mutable) borrow of `a[5]` while we read the
2217 // array length of `a`.
2218 debug!("places_conflict: implicit field");
2222 (ProjectionElem::Deref, _, Shallow(None)) => {
2223 // e.g. a borrow of `*x.y` while we shallowly access `x.y` or some
2224 // prefix thereof - the shallow access can't touch anything behind
2226 debug!("places_conflict: shallow access behind ptr");
2230 ProjectionElem::Deref,
2235 mutbl: hir::MutImmutable,
2240 // the borrow goes through a dereference of a shared reference.
2242 // I'm not sure why we are tracking these borrows - shared
2243 // references can *always* be aliased, which means the
2244 // permission check already account for this borrow.
2245 debug!("places_conflict: behind a shared ref");
2249 (ProjectionElem::Deref, _, Deep)
2250 | (ProjectionElem::Field { .. }, _, _)
2251 | (ProjectionElem::Index { .. }, _, _)
2252 | (ProjectionElem::ConstantIndex { .. }, _, _)
2253 | (ProjectionElem::Subslice { .. }, _, _)
2254 | (ProjectionElem::Downcast { .. }, _, _) => {
2255 // Recursive case. This can still be disjoint on a
2256 // further iteration if this a shallow access and
2257 // there's a deref later on, e.g. a borrow
2258 // of `*x.y` while accessing `x`.
2262 (Some(borrow_c), Some(access_c)) => {
2263 match self.place_element_conflict(&borrow_c, access_c) {
2264 Overlap::Arbitrary => {
2265 // We have encountered different fields of potentially
2266 // the same union - the borrow now partially overlaps.
2268 // There is no *easy* way of comparing the fields
2269 // further on, because they might have different types
2270 // (e.g. borrows of `u.a.0` and `u.b.y` where `.0` and
2271 // `.y` come from different structs).
2273 // We could try to do some things here - e.g. count
2274 // dereferences - but that's probably not a good
2275 // idea, at least for now, so just give up and
2276 // report a conflict. This is unsafe code anyway so
2277 // the user could always use raw pointers.
2278 debug!("places_conflict: arbitrary -> conflict");
2281 Overlap::EqualOrDisjoint => {
2282 // This is the recursive case - proceed to the next element.
2284 Overlap::Disjoint => {
2285 // We have proven the borrow disjoint - further
2286 // projections will remain disjoint.
2287 debug!("places_conflict: disjoint");
2294 unreachable!("iter::repeat returned None")
2297 /// This function iterates over all of the in-scope borrows that
2298 /// conflict with an access to a place, invoking the `op` callback
2301 /// "Current borrow" here means a borrow that reaches the point in
2302 /// the control-flow where the access occurs.
2304 /// The borrow's phase is represented by the IsActive parameter
2305 /// passed to the callback.
2306 fn each_borrow_involving_path<F>(
2309 access_place: (ShallowOrDeep, &Place<'tcx>),
2310 flow_state: &Flows<'cx, 'gcx, 'tcx>,
2313 F: FnMut(&mut Self, BorrowIndex, &BorrowData<'tcx>) -> Control,
2315 let (access, place) = access_place;
2317 // FIXME: analogous code in check_loans first maps `place` to
2320 // check for loan restricting path P being used. Accounts for
2321 // borrows of P, P.a.b, etc.
2322 let borrow_set = self.borrow_set.clone();
2323 for i in flow_state.borrows_in_scope() {
2324 let borrowed = &borrow_set[i];
2326 if self.places_conflict(&borrowed.borrowed_place, place, access) {
2328 "each_borrow_involving_path: {:?} @ {:?} vs. {:?}/{:?}",
2329 i, borrowed, place, access
2331 let ctrl = op(self, i, borrowed);
2332 if ctrl == Control::Break {
2341 borrow_data: &BorrowData<'tcx>,
2344 debug!("is_active(borrow_data={:?}, location={:?})", borrow_data, location);
2346 // If this is not a 2-phase borrow, it is always active.
2347 let activation_location = match borrow_data.activation_location {
2349 None => return true,
2352 // Otherwise, it is active for every location *except* in between
2353 // the reservation and the activation:
2357 // R <--+ Except for this
2364 // Note that we assume that:
2365 // - the reservation R dominates the activation A
2366 // - the activation A post-dominates the reservation R (ignoring unwinding edges).
2368 // This means that there can't be an edge that leaves A and
2369 // comes back into that diamond unless it passes through R.
2371 // Suboptimal: In some cases, this code walks the dominator
2372 // tree twice when it only has to be walked once. I am
2375 // If dominated by the activation A, then it is active. The
2376 // activation occurs upon entering the point A, so this is
2377 // also true if location == activation_location.
2378 if activation_location.dominates(location, &self.dominators) {
2382 // The reservation starts *on exiting* the reservation block,
2383 // so check if the location is dominated by R.successor. If so,
2384 // this point falls in between the reservation and location.
2385 let reserve_location = borrow_data.reserve_location.successor_within_block();
2386 if reserve_location.dominates(location, &self.dominators) {
2389 // Otherwise, this point is outside the diamond, so
2390 // consider the borrow active. This could happen for
2391 // example if the borrow remains active around a loop (in
2392 // which case it would be active also for the point R,
2393 // which would generate an error).
2399 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
2400 // FIXME (#16118): function intended to allow the borrow checker
2401 // to be less precise in its handling of Box while still allowing
2402 // moves out of a Box. They should be removed when/if we stop
2403 // treating Box specially (e.g. when/if DerefMove is added...)
2405 fn base_path<'d>(&self, place: &'d Place<'tcx>) -> &'d Place<'tcx> {
2406 //! Returns the base of the leftmost (deepest) dereference of an
2407 //! Box in `place`. If there is no dereference of an Box
2408 //! in `place`, then it just returns `place` itself.
2410 let mut cursor = place;
2411 let mut deepest = place;
2413 let proj = match *cursor {
2414 Place::Local(..) | Place::Static(..) => return deepest,
2415 Place::Projection(ref proj) => proj,
2417 if proj.elem == ProjectionElem::Deref
2418 && place.ty(self.mir, self.tcx).to_ty(self.tcx).is_box()
2420 deepest = &proj.base;
2422 cursor = &proj.base;
2427 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2433 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2452 fn new(self, loc: Location) -> Context {