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::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::mir::{AssertMessage, BasicBlock, BorrowKind, Local, Location, Place};
21 use rustc::mir::{Mir, Mutability, Operand, Projection, ProjectionElem, Rvalue};
22 use rustc::mir::{Field, Statement, StatementKind, Terminator, TerminatorKind};
23 use rustc::mir::ClosureRegionRequirements;
25 use rustc_data_structures::fx::FxHashSet;
26 use rustc_data_structures::indexed_set::IdxSetBuf;
27 use rustc_data_structures::indexed_vec::Idx;
34 use dataflow::{do_dataflow, DebugFormatted};
35 use dataflow::FlowAtLocation;
36 use dataflow::MoveDataParamEnv;
37 use dataflow::{DataflowAnalysis, DataflowResultsConsumer};
38 use dataflow::{MaybeInitializedLvals, MaybeUninitializedLvals};
39 use dataflow::{EverInitializedLvals, MovingOutStatements};
40 use dataflow::{BorrowData, Borrows, ReserveOrActivateIndex};
41 use dataflow::{ActiveBorrows, Reservations};
42 use dataflow::indexes::BorrowIndex;
43 use dataflow::move_paths::{IllegalMoveOriginKind, MoveError};
44 use dataflow::move_paths::{HasMoveData, LookupResult, MoveData, MovePathIndex};
45 use util::borrowck_errors::{BorrowckErrors, Origin};
49 use self::flows::Flows;
50 use self::prefixes::PrefixSet;
51 use self::MutateMode::{JustWrite, WriteAndRead};
61 pub fn provide(providers: &mut Providers) {
62 *providers = Providers {
68 fn mir_borrowck<'a, 'tcx>(
69 tcx: TyCtxt<'a, 'tcx, 'tcx>,
71 ) -> Option<ClosureRegionRequirements<'tcx>> {
72 let input_mir = tcx.mir_validated(def_id);
73 debug!("run query mir_borrowck: {}", tcx.item_path_str(def_id));
75 if !tcx.has_attr(def_id, "rustc_mir_borrowck") && !tcx.sess.use_mir() {
79 let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
80 let input_mir: &Mir = &input_mir.borrow();
81 do_mir_borrowck(&infcx, input_mir, def_id)
83 debug!("mir_borrowck done");
88 fn do_mir_borrowck<'a, 'gcx, 'tcx>(
89 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
90 input_mir: &Mir<'gcx>,
92 ) -> Option<ClosureRegionRequirements<'gcx>> {
94 let attributes = tcx.get_attrs(def_id);
95 let param_env = tcx.param_env(def_id);
97 .as_local_node_id(def_id)
98 .expect("do_mir_borrowck: non-local DefId");
100 // Make our own copy of the MIR. This copy will be modified (in place) to
101 // contain non-lexical lifetimes. It will have a lifetime tied
102 // to the inference context.
103 let mut mir: Mir<'tcx> = input_mir.clone();
104 let free_regions = if !tcx.sess.nll() {
109 // Replace all regions with fresh inference variables.
110 Some(nll::replace_regions_in_mir(infcx, def_id, param_env, mir))
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!("dont 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 MaybeInitializedLvals::new(tcx, mir, &mdpe),
164 |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
166 let flow_uninits = FlowAtLocation::new(do_dataflow(
172 MaybeUninitializedLvals::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 EverInitializedLvals::new(tcx, mir, &mdpe),
191 |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
194 // If we are in non-lexical mode, compute the non-lexical lifetimes.
195 let (opt_regioncx, opt_closure_req) = if let Some(free_regions) = free_regions {
196 let (regioncx, opt_closure_req) = nll::compute_regions(
205 (Some(Rc::new(regioncx)), opt_closure_req)
207 assert!(!tcx.sess.nll());
210 let flow_inits = flow_inits; // remove mut
212 let mut mbcx = MirBorrowckCtxt {
216 move_data: &mdpe.move_data,
217 param_env: param_env,
218 locals_are_invalidated_at_exit: match tcx.hir.body_owner_kind(id) {
219 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => false,
220 hir::BodyOwnerKind::Fn => true,
222 storage_dead_or_drop_error_reported_l: FxHashSet(),
223 storage_dead_or_drop_error_reported_s: FxHashSet(),
224 reservation_error_reported: FxHashSet(),
225 nonlexical_regioncx: opt_regioncx.clone(),
228 let borrows = Borrows::new(tcx, mir, opt_regioncx, def_id, body_id);
229 let flow_reservations = do_dataflow(
235 Reservations::new(borrows),
237 // In principle we could make the dataflow ensure that
238 // only reservation bits show up, and assert so here.
240 // In practice it is easier to be looser; in particular,
241 // it is okay for the kill-sets to hold activation bits.
242 DebugFormatted::new(&(i.kind(), rs.location(i)))
245 let flow_active_borrows = {
246 let reservations_on_entry = flow_reservations.0.sets.entry_set_state();
247 let reservations = flow_reservations.0.operator;
248 let a = DataflowAnalysis::new_with_entry_sets(
251 Cow::Borrowed(reservations_on_entry),
252 ActiveBorrows::new(reservations),
254 let results = a.run(tcx, id, &attributes, |ab, i| {
255 DebugFormatted::new(&(i.kind(), ab.location(i)))
257 FlowAtLocation::new(results)
260 let mut state = Flows::new(
268 mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
274 pub struct MirBorrowckCtxt<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
275 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
277 node_id: ast::NodeId,
278 move_data: &'cx MoveData<'tcx>,
279 param_env: ParamEnv<'gcx>,
280 /// This keeps track of whether local variables are free-ed when the function
281 /// exits even without a `StorageDead`, which appears to be the case for
284 /// I'm not sure this is the right approach - @eddyb could you try and
286 locals_are_invalidated_at_exit: bool,
287 /// This field keeps track of when storage dead or drop errors are reported
288 /// in order to stop duplicate error reporting and identify the conditions required
289 /// for a "temporary value dropped here while still borrowed" error. See #45360.
290 storage_dead_or_drop_error_reported_l: FxHashSet<Local>,
291 /// Same as the above, but for statics (thread-locals)
292 storage_dead_or_drop_error_reported_s: FxHashSet<DefId>,
293 /// This field keeps track of when borrow conflict errors are reported
294 /// for reservations, so that we don't report seemingly duplicate
295 /// errors for corresponding activations
297 /// FIXME: Ideally this would be a set of BorrowIndex, not Places,
298 /// but it is currently inconvenient to track down the BorrowIndex
299 /// at the time we detect and report a reservation error.
300 reservation_error_reported: FxHashSet<Place<'tcx>>,
301 /// Non-lexical region inference context, if NLL is enabled. This
302 /// contains the results from region inference and lets us e.g.
303 /// find out which CFG points are contained in each borrow region.
304 nonlexical_regioncx: Option<Rc<RegionInferenceContext<'tcx>>>,
308 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
309 // 2. loans made in overlapping scopes do not conflict
310 // 3. assignments do not affect things loaned out as immutable
311 // 4. moves do not affect things loaned out in any way
312 impl<'cx, 'gcx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
313 type FlowState = Flows<'cx, 'gcx, 'tcx>;
315 fn mir(&self) -> &'cx Mir<'tcx> {
319 fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
320 debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
323 fn visit_statement_entry(
326 stmt: &Statement<'tcx>,
327 flow_state: &Self::FlowState,
330 "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
335 let span = stmt.source_info.span;
337 self.check_activations(location, span, flow_state);
340 StatementKind::Assign(ref lhs, ref rhs) => {
341 // NOTE: NLL RFC calls for *shallow* write; using Deep
342 // for short-term compat w/ AST-borrowck. Also, switch
343 // to shallow requires to dataflow: "if this is an
344 // assignment `place = <rvalue>`, then any loan for some
345 // path P of which `place` is a prefix is killed."
347 ContextKind::AssignLhs.new(location),
355 ContextKind::AssignRhs.new(location),
361 StatementKind::SetDiscriminant {
366 ContextKind::SetDiscrim.new(location),
368 Shallow(Some(ArtificialField::Discriminant)),
373 StatementKind::InlineAsm {
378 let context = ContextKind::InlineAsm.new(location);
379 for (o, output) in asm.outputs.iter().zip(outputs) {
381 // FIXME(eddyb) indirect inline asm outputs should
382 // be encoeded through MIR place derefs instead.
386 (Deep, Read(ReadKind::Copy)),
387 LocalMutationIsAllowed::No,
390 self.check_if_path_is_moved(
392 InitializationRequiringAction::Use,
401 if o.is_rw { WriteAndRead } else { JustWrite },
406 for input in inputs {
407 self.consume_operand(context, (input, span), flow_state);
410 StatementKind::EndRegion(ref _rgn) => {
411 // ignored when consuming results (update to
412 // flow_state already handled).
414 StatementKind::Nop | StatementKind::Validate(..) | StatementKind::StorageLive(..) => {
415 // `Nop`, `Validate`, and `StorageLive` are irrelevant
419 StatementKind::StorageDead(local) => {
421 ContextKind::StorageDead.new(location),
422 (&Place::Local(local), span),
423 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
424 LocalMutationIsAllowed::Yes,
431 fn visit_terminator_entry(
434 term: &Terminator<'tcx>,
435 flow_state: &Self::FlowState,
439 "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
444 let span = term.source_info.span;
446 self.check_activations(location, span, flow_state);
449 TerminatorKind::SwitchInt {
455 self.consume_operand(ContextKind::SwitchInt.new(loc), (discr, span), flow_state);
457 TerminatorKind::Drop {
458 location: ref drop_place,
463 ContextKind::Drop.new(loc),
465 (Deep, Write(WriteKind::StorageDeadOrDrop)),
466 LocalMutationIsAllowed::Yes,
470 TerminatorKind::DropAndReplace {
471 location: ref drop_place,
472 value: ref new_value,
477 ContextKind::DropAndReplace.new(loc),
483 self.consume_operand(
484 ContextKind::DropAndReplace.new(loc),
489 TerminatorKind::Call {
495 self.consume_operand(ContextKind::CallOperator.new(loc), (func, span), flow_state);
497 self.consume_operand(
498 ContextKind::CallOperand.new(loc),
503 if let Some((ref dest, _ /*bb*/)) = *destination {
505 ContextKind::CallDest.new(loc),
513 TerminatorKind::Assert {
520 self.consume_operand(ContextKind::Assert.new(loc), (cond, span), flow_state);
522 AssertMessage::BoundsCheck { ref len, ref index } => {
523 self.consume_operand(ContextKind::Assert.new(loc), (len, span), flow_state);
524 self.consume_operand(
525 ContextKind::Assert.new(loc),
530 AssertMessage::Math(_ /*const_math_err*/) => {}
531 AssertMessage::GeneratorResumedAfterReturn => {}
532 AssertMessage::GeneratorResumedAfterPanic => {}
536 TerminatorKind::Yield {
541 self.consume_operand(ContextKind::Yield.new(loc), (value, span), flow_state);
544 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
545 // Returning from the function implicitly kills storage for all locals and statics.
546 // Often, the storage will already have been killed by an explicit
547 // StorageDead, but we don't always emit those (notably on unwind paths),
548 // so this "extra check" serves as a kind of backup.
549 let domain = flow_state.borrows.operator();
550 let data = domain.borrows();
551 flow_state.borrows.with_elems_outgoing(|borrows| {
553 let borrow = &data[i.borrow_index()];
554 let context = ContextKind::StorageDead.new(loc);
555 self.check_for_invalidation_at_exit(context, borrow, span, flow_state);
559 TerminatorKind::Goto { target: _ }
560 | TerminatorKind::Unreachable
561 | TerminatorKind::FalseEdges { .. } => {
562 // no data used, thus irrelevant to borrowck
568 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
574 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
580 use self::ShallowOrDeep::{Deep, Shallow};
581 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
583 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
584 enum ArtificialField {
589 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
591 /// From the RFC: "A *shallow* access means that the immediate
592 /// fields reached at LV are accessed, but references or pointers
593 /// found within are not dereferenced. Right now, the only access
594 /// that is shallow is an assignment like `x = ...;`, which would
595 /// be a *shallow write* of `x`."
596 Shallow(Option<ArtificialField>),
598 /// From the RFC: "A *deep* access means that all data reachable
599 /// through the given place may be invalidated or accesses by
604 /// Kind of access to a value: read or write
605 /// (For informational purposes only)
606 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
608 /// From the RFC: "A *read* means that the existing data may be
609 /// read, but will not be changed."
612 /// From the RFC: "A *write* means that the data may be mutated to
613 /// new values or otherwise invalidated (for example, it could be
614 /// de-initialized, as in a move operation).
617 /// For two-phase borrows, we distinguish a reservation (which is treated
618 /// like a Read) from an activation (which is treated like a write), and
619 /// each of those is furthermore distinguished from Reads/Writes above.
620 Reservation(WriteKind),
621 Activation(WriteKind, BorrowIndex),
624 /// Kind of read access to a value
625 /// (For informational purposes only)
626 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
632 /// Kind of write access to a value
633 /// (For informational purposes only)
634 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
637 MutableBorrow(BorrowKind),
642 /// When checking permissions for a place access, this flag is used to indicate that an immutable
643 /// local place can be mutated.
645 /// FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
646 /// - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`
647 /// - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
648 /// `is_declared_mutable()`
649 /// - Take flow state into consideration in `is_assignable()` for local variables
650 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
651 enum LocalMutationIsAllowed {
653 /// We want use of immutable upvars to cause a "write to immutable upvar"
654 /// error, not an "reassignment" error.
659 struct AccessErrorsReported {
660 mutability_error: bool,
661 #[allow(dead_code)] conflict_error: bool,
664 #[derive(Copy, Clone)]
665 enum InitializationRequiringAction {
672 impl InitializationRequiringAction {
673 fn as_noun(self) -> &'static str {
675 InitializationRequiringAction::Update => "update",
676 InitializationRequiringAction::Borrow => "borrow",
677 InitializationRequiringAction::Use => "use",
678 InitializationRequiringAction::Assignment => "assign",
682 fn as_verb_in_past_tense(self) -> &'static str {
684 InitializationRequiringAction::Update => "updated",
685 InitializationRequiringAction::Borrow => "borrowed",
686 InitializationRequiringAction::Use => "used",
687 InitializationRequiringAction::Assignment => "assigned",
692 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
693 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
694 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
695 /// place is initialized and (b) it is not borrowed in some way that would prevent this
698 /// Returns true if an error is reported, false otherwise.
702 place_span: (&Place<'tcx>, Span),
703 kind: (ShallowOrDeep, ReadOrWrite),
704 is_local_mutation_allowed: LocalMutationIsAllowed,
705 flow_state: &Flows<'cx, 'gcx, 'tcx>,
706 ) -> AccessErrorsReported {
709 if let Activation(_, borrow_index) = rw {
710 if self.reservation_error_reported.contains(&place_span.0) {
712 "skipping access_place for activation of invalid reservation \
713 place: {:?} borrow_index: {:?}",
717 return AccessErrorsReported {
718 mutability_error: false,
719 conflict_error: true,
724 let mutability_error =
725 self.check_access_permissions(place_span, rw, is_local_mutation_allowed);
727 self.check_access_for_conflict(context, place_span, sd, rw, flow_state);
729 AccessErrorsReported {
735 fn check_access_for_conflict(
738 place_span: (&Place<'tcx>, Span),
741 flow_state: &Flows<'cx, 'gcx, 'tcx>,
743 let mut error_reported = false;
744 self.each_borrow_involving_path(
748 |this, index, borrow| match (rw, borrow.kind) {
749 // Obviously an activation is compatible with its own
750 // reservation (or even prior activating uses of same
751 // borrow); so don't check if they interfere.
753 // NOTE: *reservations* do conflict with themselves;
754 // thus aren't injecting unsoundenss w/ this check.)
755 (Activation(_, activating), _) if activating == index.borrow_index() => {
757 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
758 skipping {:?} b/c activation of same borrow_index: {:?}",
768 (Read(_), BorrowKind::Shared) | (Reservation(..), BorrowKind::Shared) => {
772 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut) => {
773 // Reading from mere reservations of mutable-borrows is OK.
774 if this.tcx.sess.two_phase_borrows() && index.is_reservation()
776 return Control::Continue;
781 error_reported = true;
782 this.report_use_while_mutably_borrowed(context, place_span, borrow)
784 ReadKind::Borrow(bk) => {
785 let end_issued_loan_span = flow_state
788 .opt_region_end_span(&borrow.region);
789 error_reported = true;
790 this.report_conflicting_borrow(
795 end_issued_loan_span,
802 (Reservation(kind), BorrowKind::Unique)
803 | (Reservation(kind), BorrowKind::Mut)
804 | (Activation(kind, _), _)
805 | (Write(kind), _) => {
809 "recording invalid reservation of \
813 this.reservation_error_reported.insert(place_span.0.clone());
815 Activation(_, activating) => {
817 "observing check_place for activation of \
822 Read(..) | Write(..) => {}
826 WriteKind::MutableBorrow(bk) => {
827 let end_issued_loan_span = flow_state
830 .opt_region_end_span(&borrow.region);
832 error_reported = true;
833 this.report_conflicting_borrow(
838 end_issued_loan_span,
841 WriteKind::StorageDeadOrDrop => {
842 error_reported = true;
843 this.report_borrowed_value_does_not_live_long_enough(
847 flow_state.borrows.operator(),
850 WriteKind::Mutate => {
851 error_reported = true;
852 this.report_illegal_mutation_of_borrowed(context, place_span, borrow)
855 error_reported = true;
856 this.report_move_out_while_borrowed(context, place_span, &borrow)
870 place_span: (&Place<'tcx>, Span),
873 flow_state: &Flows<'cx, 'gcx, 'tcx>,
875 // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
877 MutateMode::WriteAndRead => {
878 self.check_if_path_is_moved(
880 InitializationRequiringAction::Update,
885 MutateMode::JustWrite => {
886 self.check_if_assigned_path_is_moved(context, place_span, flow_state);
890 let errors_reported = self.access_place(
893 (kind, Write(WriteKind::Mutate)),
894 // We want immutable upvars to cause an "assignment to immutable var"
895 // error, not an "reassignment of immutable var" error, because the
896 // latter can't find a good previous assignment span.
898 // There's probably a better way to do this.
899 LocalMutationIsAllowed::ExceptUpvars,
903 if !errors_reported.mutability_error {
904 // check for reassignments to immutable local variables
905 self.check_if_reassignment_to_immutable_state(context, place_span, flow_state);
912 (rvalue, span): (&Rvalue<'tcx>, Span),
914 flow_state: &Flows<'cx, 'gcx, 'tcx>,
917 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
918 let access_kind = match bk {
919 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
920 BorrowKind::Unique | BorrowKind::Mut => {
921 let wk = WriteKind::MutableBorrow(bk);
922 if self.tcx.sess.two_phase_borrows() {
923 (Deep, Reservation(wk))
934 LocalMutationIsAllowed::No,
938 self.check_if_path_is_moved(
940 InitializationRequiringAction::Borrow,
946 Rvalue::Use(ref operand)
947 | Rvalue::Repeat(ref operand, _)
948 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
949 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
950 self.consume_operand(context, (operand, span), flow_state)
953 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
954 let af = match *rvalue {
955 Rvalue::Len(..) => ArtificialField::ArrayLength,
956 Rvalue::Discriminant(..) => ArtificialField::Discriminant,
962 (Shallow(Some(af)), Read(ReadKind::Copy)),
963 LocalMutationIsAllowed::No,
966 self.check_if_path_is_moved(
968 InitializationRequiringAction::Use,
974 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
975 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
976 self.consume_operand(context, (operand1, span), flow_state);
977 self.consume_operand(context, (operand2, span), flow_state);
980 Rvalue::NullaryOp(_op, _ty) => {
981 // nullary ops take no dynamic input; no borrowck effect.
983 // FIXME: is above actually true? Do we want to track
984 // the fact that uninitialized data can be created via
988 Rvalue::Aggregate(ref _aggregate_kind, ref operands) => for operand in operands {
989 self.consume_operand(context, (operand, span), flow_state);
997 (operand, span): (&Operand<'tcx>, Span),
998 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1001 Operand::Copy(ref place) => {
1002 // copy of place: check if this is "copy of frozen path"
1003 // (FIXME: see check_loans.rs)
1007 (Deep, Read(ReadKind::Copy)),
1008 LocalMutationIsAllowed::No,
1012 // Finally, check if path was already moved.
1013 self.check_if_path_is_moved(
1015 InitializationRequiringAction::Use,
1020 Operand::Move(ref place) => {
1021 // move of place: check if this is move of already borrowed path
1025 (Deep, Write(WriteKind::Move)),
1026 LocalMutationIsAllowed::Yes,
1030 // Finally, check if path was already moved.
1031 self.check_if_path_is_moved(
1033 InitializationRequiringAction::Use,
1038 Operand::Constant(_) => {}
1042 /// Returns whether a borrow of this place is invalidated when the function
1044 fn check_for_invalidation_at_exit(
1047 borrow: &BorrowData<'tcx>,
1049 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1051 debug!("check_for_invalidation_at_exit({:?})", borrow);
1052 let place = &borrow.borrowed_place;
1053 let root_place = self.prefixes(place, PrefixSet::All).last().unwrap();
1055 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1056 // we just know that all locals are dropped at function exit (otherwise
1057 // we'll have a memory leak) and assume that all statics have a destructor.
1059 // FIXME: allow thread-locals to borrow other thread locals?
1060 let (might_be_alive, will_be_dropped) = match root_place {
1061 Place::Static(statik) => {
1062 // Thread-locals might be dropped after the function exits, but
1063 // "true" statics will never be.
1064 let is_thread_local = self.tcx
1065 .get_attrs(statik.def_id)
1067 .any(|attr| attr.check_name("thread_local"));
1069 (true, is_thread_local)
1071 Place::Local(_) => {
1072 // Locals are always dropped at function exit, and if they
1073 // have a destructor it would've been called already.
1074 (false, self.locals_are_invalidated_at_exit)
1076 Place::Projection(..) => {
1077 bug!("root of {:?} is a projection ({:?})?", place, root_place)
1081 if !will_be_dropped {
1083 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1089 // FIXME: replace this with a proper borrow_conflicts_with_place when
1091 let sd = if might_be_alive { Deep } else { Shallow(None) };
1093 if self.places_conflict(place, root_place, sd) {
1094 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1095 // FIXME: should be talking about the region lifetime instead
1096 // of just a span here.
1097 self.report_borrowed_value_does_not_live_long_enough(
1101 flow_state.borrows.operator(),
1106 fn check_activations(
1110 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1112 if !self.tcx.sess.two_phase_borrows() {
1116 // Two-phase borrow support: For each activation that is newly
1117 // generated at this statement, check if it interferes with
1119 let domain = flow_state.borrows.operator();
1120 let data = domain.borrows();
1121 flow_state.borrows.each_gen_bit(|gen| {
1122 if gen.is_activation() {
1123 let borrow_index = gen.borrow_index();
1124 let borrow = &data[borrow_index];
1125 // currently the flow analysis registers
1126 // activations for both mutable and immutable
1127 // borrows. So make sure we are talking about a
1128 // mutable borrow before we check it.
1130 BorrowKind::Shared => return,
1131 BorrowKind::Unique | BorrowKind::Mut => {}
1135 ContextKind::Activation.new(location),
1136 (&borrow.borrowed_place, span),
1139 Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1141 LocalMutationIsAllowed::No,
1144 // We do not need to call `check_if_path_is_moved`
1145 // again, as we already called it when we made the
1146 // initial reservation.
1152 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1153 fn check_if_reassignment_to_immutable_state(
1156 (place, span): (&Place<'tcx>, Span),
1157 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1159 debug!("check_if_reassignment_to_immutable_state({:?})", place);
1160 // determine if this path has a non-mut owner (and thus needs checking).
1161 if let Ok(()) = self.is_mutable(place, LocalMutationIsAllowed::No) {
1165 "check_if_reassignment_to_immutable_state({:?}) - is an imm local",
1169 for i in flow_state.ever_inits.elems_incoming() {
1170 let init = self.move_data.inits[i];
1171 let init_place = &self.move_data.move_paths[init.path].place;
1172 if self.places_conflict(&init_place, place, Deep) {
1173 self.report_illegal_reassignment(context, (place, span), init.span);
1179 fn check_if_path_is_moved(
1182 desired_action: InitializationRequiringAction,
1183 place_span: (&Place<'tcx>, Span),
1184 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1186 // FIXME: analogous code in check_loans first maps `place` to
1187 // its base_path ... but is that what we want here?
1188 let place = self.base_path(place_span.0);
1190 let maybe_uninits = &flow_state.uninits;
1191 let curr_move_outs = &flow_state.move_outs;
1195 // 1. Move of `a.b.c`, use of `a.b.c`
1196 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1197 // 3. Move of `a.b.c`, use of `a` or `a.b`
1198 // 4. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1199 // partial initialization support, one might have `a.x`
1200 // initialized but not `a.b`.
1204 // 5. Move of `a.b.c`, use of `a.b.d`
1205 // 6. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1206 // 7. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1207 // must have been initialized for the use to be sound.
1208 // 8. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1210 // The dataflow tracks shallow prefixes distinctly (that is,
1211 // field-accesses on P distinctly from P itself), in order to
1212 // track substructure initialization separately from the whole
1215 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1216 // which we have a MovePath is `a.b`, then that means that the
1217 // initialization state of `a.b` is all we need to inspect to
1218 // know if `a.b.c` is valid (and from that we infer that the
1219 // dereference and `.d` access is also valid, since we assume
1220 // `a.b.c` is assigned a reference to a initialized and
1221 // well-formed record structure.)
1223 // Therefore, if we seek out the *closest* prefix for which we
1224 // have a MovePath, that should capture the initialization
1225 // state for the place scenario.
1227 // This code covers scenarios 1, 2, and 4.
1229 debug!("check_if_path_is_moved part1 place: {:?}", place);
1230 match self.move_path_closest_to(place) {
1232 if maybe_uninits.contains(&mpi) {
1233 self.report_use_of_moved_or_uninitialized(
1240 return; // don't bother finding other problems.
1243 Err(NoMovePathFound::ReachedStatic) => {
1244 // Okay: we do not build MoveData for static variables
1245 } // Only query longest prefix with a MovePath, not further
1246 // ancestors; dataflow recurs on children when parents
1247 // move (to support partial (re)inits).
1249 // (I.e. querying parents breaks scenario 8; but may want
1250 // to do such a query based on partial-init feature-gate.)
1253 // A move of any shallow suffix of `place` also interferes
1254 // with an attempt to use `place`. This is scenario 3 above.
1256 // (Distinct from handling of scenarios 1+2+4 above because
1257 // `place` does not interfere with suffixes of its prefixes,
1258 // e.g. `a.b.c` does not interfere with `a.b.d`)
1260 debug!("check_if_path_is_moved part2 place: {:?}", place);
1261 if let Some(mpi) = self.move_path_for_place(place) {
1262 if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1263 self.report_use_of_moved_or_uninitialized(
1270 return; // don't bother finding other problems.
1275 /// Currently MoveData does not store entries for all places in
1276 /// the input MIR. For example it will currently filter out
1277 /// places that are Copy; thus we do not track places of shared
1278 /// reference type. This routine will walk up a place along its
1279 /// prefixes, searching for a foundational place that *is*
1280 /// tracked in the MoveData.
1282 /// An Err result includes a tag indicated why the search failed.
1283 /// Currenly this can only occur if the place is built off of a
1284 /// static variable, as we do not track those in the MoveData.
1285 fn move_path_closest_to(
1287 place: &Place<'tcx>,
1288 ) -> Result<MovePathIndex, NoMovePathFound> {
1289 let mut last_prefix = place;
1290 for prefix in self.prefixes(place, PrefixSet::All) {
1291 if let Some(mpi) = self.move_path_for_place(prefix) {
1294 last_prefix = prefix;
1296 match *last_prefix {
1297 Place::Local(_) => panic!("should have move path for every Local"),
1298 Place::Projection(_) => panic!("PrefixSet::All meant dont stop for Projection"),
1299 Place::Static(_) => return Err(NoMovePathFound::ReachedStatic),
1303 fn move_path_for_place(&mut self, place: &Place<'tcx>) -> Option<MovePathIndex> {
1304 // If returns None, then there is no move path corresponding
1305 // to a direct owner of `place` (which means there is nothing
1306 // that borrowck tracks for its analysis).
1308 match self.move_data.rev_lookup.find(place) {
1309 LookupResult::Parent(_) => None,
1310 LookupResult::Exact(mpi) => Some(mpi),
1314 fn check_if_assigned_path_is_moved(
1317 (place, span): (&Place<'tcx>, Span),
1318 flow_state: &Flows<'cx, 'gcx, 'tcx>,
1320 // recur down place; dispatch to check_if_path_is_moved when necessary
1321 let mut place = place;
1324 Place::Local(_) | Place::Static(_) => {
1325 // assigning to `x` does not require `x` be initialized.
1328 Place::Projection(ref proj) => {
1329 let Projection { ref base, ref elem } = **proj;
1331 ProjectionElem::Deref |
1332 // assigning to *P requires `P` initialized.
1333 ProjectionElem::Index(_/*operand*/) |
1334 ProjectionElem::ConstantIndex { .. } |
1335 // assigning to P[i] requires `P` initialized.
1336 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1337 // assigning to (P->variant) is okay if assigning to `P` is okay
1339 // FIXME: is this true even if P is a adt with a dtor?
1342 ProjectionElem::Subslice { .. } => {
1343 panic!("we dont allow assignments to subslices, context: {:?}",
1347 ProjectionElem::Field(..) => {
1348 // if type of `P` has a dtor, then
1349 // assigning to `P.f` requires `P` itself
1350 // be already initialized
1352 match base.ty(self.mir, tcx).to_ty(tcx).sty {
1353 ty::TyAdt(def, _) if def.has_dtor(tcx) => {
1355 // FIXME: analogous code in
1356 // check_loans.rs first maps
1357 // `base` to its base_path.
1359 self.check_if_path_is_moved(
1360 context, InitializationRequiringAction::Assignment,
1361 (base, span), flow_state);
1363 // (base initialized; no need to
1379 /// Check the permissions for the given place and read or write kind
1381 /// Returns true if an error is reported, false otherwise.
1382 fn check_access_permissions(
1384 (place, span): (&Place<'tcx>, Span),
1386 is_local_mutation_allowed: LocalMutationIsAllowed,
1389 "check_access_permissions({:?}, {:?}, {:?})",
1392 is_local_mutation_allowed
1394 let mut error_reported = false;
1396 Reservation(WriteKind::MutableBorrow(BorrowKind::Unique))
1397 | Write(WriteKind::MutableBorrow(BorrowKind::Unique)) => {
1398 if let Err(_place_err) = self.is_mutable(place, LocalMutationIsAllowed::Yes) {
1399 span_bug!(span, "&unique borrow for {:?} should not fail", place);
1402 Reservation(WriteKind::MutableBorrow(BorrowKind::Mut))
1403 | Write(WriteKind::MutableBorrow(BorrowKind::Mut)) => if let Err(place_err) =
1404 self.is_mutable(place, is_local_mutation_allowed)
1406 error_reported = true;
1408 let item_msg = match self.describe_place(place) {
1409 Some(name) => format!("immutable item `{}`", name),
1410 None => "immutable item".to_owned(),
1413 let mut err = self.tcx
1414 .cannot_borrow_path_as_mutable(span, &item_msg, Origin::Mir);
1415 err.span_label(span, "cannot borrow as mutable");
1417 if place != place_err {
1418 if let Some(name) = self.describe_place(place_err) {
1419 err.note(&format!("Value not mutable causing this error: `{}`", name));
1425 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1426 if let Err(place_err) = self.is_mutable(place, is_local_mutation_allowed) {
1427 error_reported = true;
1429 let item_msg = match self.describe_place(place) {
1430 Some(name) => format!("immutable item `{}`", name),
1431 None => "immutable item".to_owned(),
1434 let mut err = self.tcx.cannot_assign(span, &item_msg, Origin::Mir);
1435 err.span_label(span, "cannot mutate");
1437 if place != place_err {
1438 if let Some(name) = self.describe_place(place_err) {
1439 err.note(&format!("Value not mutable causing this error: `{}`", name));
1446 Reservation(WriteKind::Move)
1447 | Reservation(WriteKind::StorageDeadOrDrop)
1448 | Reservation(WriteKind::MutableBorrow(BorrowKind::Shared))
1449 | Write(WriteKind::Move)
1450 | Write(WriteKind::StorageDeadOrDrop)
1451 | Write(WriteKind::MutableBorrow(BorrowKind::Shared)) => {
1452 if let Err(_place_err) = self.is_mutable(place, is_local_mutation_allowed) {
1453 self.tcx.sess.delay_span_bug(
1456 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
1464 Activation(..) => {} // permission checks are done at Reservation point.
1466 Read(ReadKind::Borrow(BorrowKind::Unique))
1467 | Read(ReadKind::Borrow(BorrowKind::Mut))
1468 | Read(ReadKind::Borrow(BorrowKind::Shared))
1469 | Read(ReadKind::Copy) => {} // Access authorized
1475 /// Can this value be written or borrowed mutably
1478 place: &'d Place<'tcx>,
1479 is_local_mutation_allowed: LocalMutationIsAllowed,
1480 ) -> Result<(), &'d Place<'tcx>> {
1482 Place::Local(local) => {
1483 let local = &self.mir.local_decls[local];
1484 match local.mutability {
1485 Mutability::Not => match is_local_mutation_allowed {
1486 LocalMutationIsAllowed::Yes | LocalMutationIsAllowed::ExceptUpvars => {
1489 LocalMutationIsAllowed::No => Err(place),
1491 Mutability::Mut => Ok(()),
1494 Place::Static(ref static_) => if !self.tcx.is_static_mut(static_.def_id) {
1499 Place::Projection(ref proj) => {
1501 ProjectionElem::Deref => {
1502 let base_ty = proj.base.ty(self.mir, self.tcx).to_ty(self.tcx);
1504 // Check the kind of deref to decide
1506 ty::TyRef(_, tnm) => {
1508 // Shared borrowed data is never mutable
1509 hir::MutImmutable => Err(place),
1510 // Mutably borrowed data is mutable, but only if we have a
1511 // unique path to the `&mut`
1512 hir::MutMutable => {
1513 let mode = match self.is_upvar_field_projection(&proj.base)
1517 self.mir.upvar_decls[field.index()].by_ref
1520 is_local_mutation_allowed
1522 _ => LocalMutationIsAllowed::Yes,
1525 self.is_mutable(&proj.base, mode)
1529 ty::TyRawPtr(tnm) => {
1531 // `*const` raw pointers are not mutable
1532 hir::MutImmutable => return Err(place),
1533 // `*mut` raw pointers are always mutable, regardless of context
1534 // The users have to check by themselve.
1535 hir::MutMutable => return Ok(()),
1538 // `Box<T>` owns its content, so mutable if its location is mutable
1539 _ if base_ty.is_box() => {
1540 self.is_mutable(&proj.base, is_local_mutation_allowed)
1542 // Deref should only be for reference, pointers or boxes
1543 _ => bug!("Deref of unexpected type: {:?}", base_ty),
1546 // All other projections are owned by their base path, so mutable if
1547 // base path is mutable
1548 ProjectionElem::Field(..)
1549 | ProjectionElem::Index(..)
1550 | ProjectionElem::ConstantIndex { .. }
1551 | ProjectionElem::Subslice { .. }
1552 | ProjectionElem::Downcast(..) => {
1553 if let Some(field) = self.is_upvar_field_projection(place) {
1554 let decl = &self.mir.upvar_decls[field.index()];
1556 "decl.mutability={:?} local_mutation_is_allowed={:?} place={:?}",
1558 is_local_mutation_allowed,
1561 match (decl.mutability, is_local_mutation_allowed) {
1562 (Mutability::Not, LocalMutationIsAllowed::No)
1563 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
1566 (Mutability::Not, LocalMutationIsAllowed::Yes)
1567 | (Mutability::Mut, _) => {
1568 self.is_mutable(&proj.base, is_local_mutation_allowed)
1572 self.is_mutable(&proj.base, is_local_mutation_allowed)
1581 /// If this is a field projection, and the field is being projected from a closure type,
1582 /// then returns the index of the field being projected. Note that this closure will always
1583 /// be `self` in the current MIR, because that is the only time we directly access the fields
1584 /// of a closure type.
1585 fn is_upvar_field_projection(&self, place: &Place<'tcx>) -> Option<Field> {
1587 Place::Projection(ref proj) => match proj.elem {
1588 ProjectionElem::Field(field, _ty) => {
1589 let is_projection_from_ty_closure = proj.base
1590 .ty(self.mir, self.tcx)
1594 if is_projection_from_ty_closure {
1607 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1608 enum NoMovePathFound {
1612 /// The degree of overlap between 2 places for borrow-checking.
1614 /// The places might partially overlap - in this case, we give
1615 /// up and say that they might conflict. This occurs when
1616 /// different fields of a union are borrowed. For example,
1617 /// if `u` is a union, we have no way of telling how disjoint
1618 /// `u.a.x` and `a.b.y` are.
1620 /// The places have the same type, and are either completely disjoint
1621 /// or equal - i.e. they can't "partially" overlap as can occur with
1622 /// unions. This is the "base case" on which we recur for extensions
1625 /// The places are disjoint, so we know all extensions of them
1626 /// will also be disjoint.
1630 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1631 // Given that the bases of `elem1` and `elem2` are always either equal
1632 // or disjoint (and have the same type!), return the overlap situation
1633 // between `elem1` and `elem2`.
1634 fn place_element_conflict(&self, elem1: &Place<'tcx>, elem2: &Place<'tcx>) -> Overlap {
1635 match (elem1, elem2) {
1636 (Place::Local(l1), Place::Local(l2)) => {
1638 // the same local - base case, equal
1639 debug!("place_element_conflict: DISJOINT-OR-EQ-LOCAL");
1640 Overlap::EqualOrDisjoint
1642 // different locals - base case, disjoint
1643 debug!("place_element_conflict: DISJOINT-LOCAL");
1647 (Place::Static(static1), Place::Static(static2)) => {
1648 if static1.def_id != static2.def_id {
1649 debug!("place_element_conflict: DISJOINT-STATIC");
1651 } else if self.tcx.is_static_mut(static1.def_id) {
1652 // We ignore mutable statics - they can only be unsafe code.
1653 debug!("place_element_conflict: IGNORE-STATIC-MUT");
1656 debug!("place_element_conflict: DISJOINT-OR-EQ-STATIC");
1657 Overlap::EqualOrDisjoint
1660 (Place::Local(_), Place::Static(_)) | (Place::Static(_), Place::Local(_)) => {
1661 debug!("place_element_conflict: DISJOINT-STATIC-LOCAL");
1664 (Place::Projection(pi1), Place::Projection(pi2)) => {
1665 match (&pi1.elem, &pi2.elem) {
1666 (ProjectionElem::Deref, ProjectionElem::Deref) => {
1667 // derefs (e.g. `*x` vs. `*x`) - recur.
1668 debug!("place_element_conflict: DISJOINT-OR-EQ-DEREF");
1669 Overlap::EqualOrDisjoint
1671 (ProjectionElem::Field(f1, _), ProjectionElem::Field(f2, _)) => {
1673 // same field (e.g. `a.y` vs. `a.y`) - recur.
1674 debug!("place_element_conflict: DISJOINT-OR-EQ-FIELD");
1675 Overlap::EqualOrDisjoint
1677 let ty = pi1.base.ty(self.mir, self.tcx).to_ty(self.tcx);
1679 ty::TyAdt(def, _) if def.is_union() => {
1680 // Different fields of a union, we are basically stuck.
1681 debug!("place_element_conflict: STUCK-UNION");
1685 // Different fields of a struct (`a.x` vs. `a.y`). Disjoint!
1686 debug!("place_element_conflict: DISJOINT-FIELD");
1692 (ProjectionElem::Downcast(_, v1), ProjectionElem::Downcast(_, v2)) => {
1693 // different variants are treated as having disjoint fields,
1694 // even if they occupy the same "space", because it's
1695 // impossible for 2 variants of the same enum to exist
1696 // (and therefore, to be borrowed) at the same time.
1698 // Note that this is different from unions - we *do* allow
1699 // this code to compile:
1702 // fn foo(x: &mut Result<i32, i32>) {
1703 // let mut v = None;
1704 // if let Ok(ref mut a) = *x {
1707 // // here, you would *think* that the
1708 // // *entirety* of `x` would be borrowed,
1709 // // but in fact only the `Ok` variant is,
1710 // // so the `Err` variant is *entirely free*:
1711 // if let Err(ref mut a) = *x {
1718 debug!("place_element_conflict: DISJOINT-OR-EQ-FIELD");
1719 Overlap::EqualOrDisjoint
1721 debug!("place_element_conflict: DISJOINT-FIELD");
1725 (ProjectionElem::Index(..), ProjectionElem::Index(..))
1726 | (ProjectionElem::Index(..), ProjectionElem::ConstantIndex { .. })
1727 | (ProjectionElem::Index(..), ProjectionElem::Subslice { .. })
1728 | (ProjectionElem::ConstantIndex { .. }, ProjectionElem::Index(..))
1730 ProjectionElem::ConstantIndex { .. },
1731 ProjectionElem::ConstantIndex { .. },
1733 | (ProjectionElem::ConstantIndex { .. }, ProjectionElem::Subslice { .. })
1734 | (ProjectionElem::Subslice { .. }, ProjectionElem::Index(..))
1735 | (ProjectionElem::Subslice { .. }, ProjectionElem::ConstantIndex { .. })
1736 | (ProjectionElem::Subslice { .. }, ProjectionElem::Subslice { .. }) => {
1737 // Array indexes (`a[0]` vs. `a[i]`). These can either be disjoint
1738 // (if the indexes differ) or equal (if they are the same), so this
1739 // is the recursive case that gives "equal *or* disjoint" its meaning.
1741 // Note that by construction, MIR at borrowck can't subdivide
1742 // `Subslice` accesses (e.g. `a[2..3][i]` will never be present) - they
1743 // are only present in slice patterns, and we "merge together" nested
1744 // slice patterns. That means we don't have to think about these. It's
1745 // probably a good idea to assert this somewhere, but I'm too lazy.
1747 // FIXME(#8636) we might want to return Disjoint if
1748 // both projections are constant and disjoint.
1749 debug!("place_element_conflict: DISJOINT-OR-EQ-ARRAY");
1750 Overlap::EqualOrDisjoint
1753 (ProjectionElem::Deref, _)
1754 | (ProjectionElem::Field(..), _)
1755 | (ProjectionElem::Index(..), _)
1756 | (ProjectionElem::ConstantIndex { .. }, _)
1757 | (ProjectionElem::Subslice { .. }, _)
1758 | (ProjectionElem::Downcast(..), _) => bug!(
1759 "mismatched projections in place_element_conflict: {:?} and {:?}",
1765 (Place::Projection(_), _) | (_, Place::Projection(_)) => bug!(
1766 "unexpected elements in place_element_conflict: {:?} and {:?}",
1773 /// Returns whether an access of kind `access` to `access_place` conflicts with
1774 /// a borrow/full access to `borrow_place` (for deep accesses to mutable
1775 /// locations, this function is symmetric between `borrow_place` & `access_place`).
1778 borrow_place: &Place<'tcx>,
1779 access_place: &Place<'tcx>,
1780 access: ShallowOrDeep,
1783 "places_conflict({:?},{:?},{:?})",
1789 // Return all the prefixes of `place` in reverse order, including
1791 fn place_elements<'a, 'tcx>(place: &'a Place<'tcx>) -> Vec<&'a Place<'tcx>> {
1792 let mut result = vec![];
1793 let mut place = place;
1797 Place::Projection(interior) => {
1798 place = &interior.base;
1800 Place::Local(_) | Place::Static(_) => {
1808 let borrow_components = place_elements(borrow_place);
1809 let access_components = place_elements(access_place);
1811 "places_conflict: components {:?} / {:?}",
1816 let borrow_components = borrow_components
1819 .chain(iter::repeat(None));
1820 let access_components = access_components
1823 .chain(iter::repeat(None));
1824 // The borrowck rules for proving disjointness are applied from the "root" of the
1825 // borrow forwards, iterating over "similar" projections in lockstep until
1826 // we can prove overlap one way or another. Essentially, we treat `Overlap` as
1827 // a monoid and report a conflict if the product ends up not being `Disjoint`.
1829 // At each step, if we didn't run out of borrow or place, we know that our elements
1830 // have the same type, and that they only overlap if they are the identical.
1832 // For example, if we are comparing these:
1833 // BORROW: (*x1[2].y).z.a
1834 // ACCESS: (*x1[i].y).w.b
1836 // Then our steps are:
1837 // x1 | x1 -- places are the same
1838 // x1[2] | x1[i] -- equal or disjoint (disjoint if indexes differ)
1839 // x1[2].y | x1[i].y -- equal or disjoint
1840 // *x1[2].y | *x1[i].y -- equal or disjoint
1841 // (*x1[2].y).z | (*x1[i].y).w -- we are disjoint and don't need to check more!
1843 // Because `zip` does potentially bad things to the iterator inside, this loop
1844 // also handles the case where the access might be a *prefix* of the borrow, e.g.
1846 // BORROW: (*x1[2].y).z.a
1849 // Then our steps are:
1850 // x1 | x1 -- places are the same
1851 // x1[2] | x1[i] -- equal or disjoint (disjoint if indexes differ)
1852 // x1[2].y | x1[i].y -- equal or disjoint
1854 // -- here we run out of access - the borrow can access a part of it. If this
1855 // is a full deep access, then we *know* the borrow conflicts with it. However,
1856 // if the access is shallow, then we can proceed:
1858 // x1[2].y | (*x1[i].y) -- a deref! the access can't get past this, so we
1861 // Our invariant is, that at each step of the iteration:
1862 // - If we didn't run out of access to match, our borrow and access are comparable
1863 // and either equal or disjoint.
1864 // - If we did run out of accesss, the borrow can access a part of it.
1865 for (borrow_c, access_c) in borrow_components.zip(access_components) {
1866 // loop invariant: borrow_c is always either equal to access_c or disjoint from it.
1867 debug!("places_conflict: {:?} vs. {:?}", borrow_c, access_c);
1868 match (borrow_c, access_c) {
1870 // If we didn't run out of access, the borrow can access all of our
1871 // place (e.g. a borrow of `a.b` with an access to `a.b.c`),
1872 // so we have a conflict.
1874 // If we did, then we still know that the borrow can access a *part*
1875 // of our place that our access cares about (a borrow of `a.b.c`
1876 // with an access to `a.b`), so we still have a conflict.
1878 // FIXME: Differs from AST-borrowck; includes drive-by fix
1879 // to #38899. Will probably need back-compat mode flag.
1880 debug!("places_conflict: full borrow, CONFLICT");
1883 (Some(borrow_c), None) => {
1884 // We know that the borrow can access a part of our place. This
1885 // is a conflict if that is a part our access cares about.
1887 let (base, elem) = match borrow_c {
1888 Place::Projection(box Projection { base, elem }) => (base, elem),
1889 _ => bug!("place has no base?"),
1891 let base_ty = base.ty(self.mir, self.tcx).to_ty(self.tcx);
1893 match (elem, &base_ty.sty, access) {
1894 (_, _, Shallow(Some(ArtificialField::Discriminant)))
1895 | (_, _, Shallow(Some(ArtificialField::ArrayLength))) => {
1896 // The discriminant and array length are like
1897 // additional fields on the type; they do not
1898 // overlap any existing data there. Furthermore,
1899 // they cannot actually be a prefix of any
1900 // borrowed place (at least in MIR as it is
1903 // e.g. a (mutable) borrow of `a[5]` while we read the
1904 // array length of `a`.
1905 debug!("places_conflict: implicit field");
1909 (ProjectionElem::Deref, _, Shallow(None)) => {
1910 // e.g. a borrow of `*x.y` while we shallowly access `x.y` or some
1911 // prefix thereof - the shallow access can't touch anything behind
1913 debug!("places_conflict: shallow access behind ptr");
1917 ProjectionElem::Deref,
1922 mutbl: hir::MutImmutable,
1927 // the borrow goes through a dereference of a shared reference.
1929 // I'm not sure why we are tracking these borrows - shared
1930 // references can *always* be aliased, which means the
1931 // permission check already account for this borrow.
1932 debug!("places_conflict: behind a shared ref");
1936 (ProjectionElem::Deref, _, Deep)
1937 | (ProjectionElem::Field { .. }, _, _)
1938 | (ProjectionElem::Index { .. }, _, _)
1939 | (ProjectionElem::ConstantIndex { .. }, _, _)
1940 | (ProjectionElem::Subslice { .. }, _, _)
1941 | (ProjectionElem::Downcast { .. }, _, _) => {
1942 // Recursive case. This can still be disjoint on a
1943 // further iteration if this a shallow access and
1944 // there's a deref later on, e.g. a borrow
1945 // of `*x.y` while accessing `x`.
1949 (Some(borrow_c), Some(access_c)) => {
1950 match self.place_element_conflict(&borrow_c, access_c) {
1951 Overlap::Arbitrary => {
1952 // We have encountered different fields of potentially
1953 // the same union - the borrow now partially overlaps.
1955 // There is no *easy* way of comparing the fields
1956 // further on, because they might have different types
1957 // (e.g. borrows of `u.a.0` and `u.b.y` where `.0` and
1958 // `.y` come from different structs).
1960 // We could try to do some things here - e.g. count
1961 // dereferences - but that's probably not a good
1962 // idea, at least for now, so just give up and
1963 // report a conflict. This is unsafe code anyway so
1964 // the user could always use raw pointers.
1965 debug!("places_conflict: arbitrary -> conflict");
1968 Overlap::EqualOrDisjoint => {
1969 // This is the recursive case - proceed to the next element.
1971 Overlap::Disjoint => {
1972 // We have proven the borrow disjoint - further
1973 // projections will remain disjoint.
1974 debug!("places_conflict: disjoint");
1981 unreachable!("iter::repeat returned None")
1984 /// This function iterates over all of the current borrows
1985 /// (represented by 1-bits in `flow_state.borrows`) that conflict
1986 /// with an access to a place, invoking the `op` callback for each
1989 /// "Current borrow" here means a borrow that reaches the point in
1990 /// the control-flow where the access occurs.
1992 /// The borrow's phase is represented by the ReserveOrActivateIndex
1993 /// passed to the callback: one can call `is_reservation()` and
1994 /// `is_activation()` to determine what phase the borrow is
1995 /// currently in, when such distinction matters.
1996 fn each_borrow_involving_path<F>(
1999 access_place: (ShallowOrDeep, &Place<'tcx>),
2000 flow_state: &Flows<'cx, 'gcx, 'tcx>,
2003 F: FnMut(&mut Self, ReserveOrActivateIndex, &BorrowData<'tcx>) -> Control,
2005 let (access, place) = access_place;
2007 // FIXME: analogous code in check_loans first maps `place` to
2010 let data = flow_state.borrows.operator().borrows();
2012 // check for loan restricting path P being used. Accounts for
2013 // borrows of P, P.a.b, etc.
2014 let mut elems_incoming = flow_state.borrows.elems_incoming();
2015 while let Some(i) = elems_incoming.next() {
2016 let borrowed = &data[i.borrow_index()];
2018 if self.places_conflict(&borrowed.borrowed_place, place, access) {
2019 let ctrl = op(self, i, borrowed);
2020 if ctrl == Control::Break {
2028 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
2029 // FIXME (#16118): function intended to allow the borrow checker
2030 // to be less precise in its handling of Box while still allowing
2031 // moves out of a Box. They should be removed when/if we stop
2032 // treating Box specially (e.g. when/if DerefMove is added...)
2034 fn base_path<'d>(&self, place: &'d Place<'tcx>) -> &'d Place<'tcx> {
2035 //! Returns the base of the leftmost (deepest) dereference of an
2036 //! Box in `place`. If there is no dereference of an Box
2037 //! in `place`, then it just returns `place` itself.
2039 let mut cursor = place;
2040 let mut deepest = place;
2042 let proj = match *cursor {
2043 Place::Local(..) | Place::Static(..) => return deepest,
2044 Place::Projection(ref proj) => proj,
2046 if proj.elem == ProjectionElem::Deref
2047 && place.ty(self.mir, self.tcx).to_ty(self.tcx).is_box()
2049 deepest = &proj.base;
2051 cursor = &proj.base;
2056 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2062 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2081 fn new(self, loc: Location) -> Context {