]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/mod.rs
c907c97d6d3ed58b7942b3c4bdf7acf39321cd2d
[rust.git] / src / librustc_mir / borrow_check / mod.rs
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.
4 //
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.
10
11 //! This query borrow-checks the MIR to (further) ensure it is not broken.
12
13 use borrow_check::nll::region_infer::RegionInferenceContext;
14 use rustc::hir;
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;
24
25 use rustc_data_structures::fx::FxHashSet;
26 use rustc_data_structures::indexed_set::IdxSetBuf;
27 use rustc_data_structures::indexed_vec::Idx;
28
29 use std::rc::Rc;
30
31 use syntax::ast;
32 use syntax_pos::Span;
33
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};
46
47 use std::iter;
48
49 use self::flows::Flows;
50 use self::prefixes::PrefixSet;
51 use self::MutateMode::{JustWrite, WriteAndRead};
52
53 mod error_reporting;
54 mod flows;
55 mod prefixes;
56
57 use std::borrow::Cow;
58
59 pub(crate) mod nll;
60
61 pub fn provide(providers: &mut Providers) {
62     *providers = Providers {
63         mir_borrowck,
64         ..*providers
65     };
66 }
67
68 fn mir_borrowck<'a, 'tcx>(
69     tcx: TyCtxt<'a, 'tcx, 'tcx>,
70     def_id: DefId,
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));
74
75     if !tcx.has_attr(def_id, "rustc_mir_borrowck") && !tcx.sess.use_mir() {
76         return None;
77     }
78
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)
82     });
83     debug!("mir_borrowck done");
84
85     opt_closure_req
86 }
87
88 fn do_mir_borrowck<'a, 'gcx, 'tcx>(
89     infcx: &InferCtxt<'a, 'gcx, 'tcx>,
90     input_mir: &Mir<'gcx>,
91     def_id: DefId,
92 ) -> Option<ClosureRegionRequirements<'gcx>> {
93     let tcx = infcx.tcx;
94     let attributes = tcx.get_attrs(def_id);
95     let param_env = tcx.param_env(def_id);
96     let id = tcx.hir
97         .as_local_node_id(def_id)
98         .expect("do_mir_borrowck: non-local DefId");
99
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() {
105         None
106     } else {
107         let mir = &mut mir;
108
109         // Replace all regions with fresh inference variables.
110         Some(nll::replace_regions_in_mir(infcx, def_id, param_env, mir))
111     };
112     let mir = &mir;
113
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.")
121                     }
122                     MoveError::IllegalMove {
123                         cannot_move_out_of: o,
124                     } => (o.span, o.kind),
125                 };
126                 let origin = Origin::Mir;
127                 let mut err = match kind {
128                     IllegalMoveOriginKind::Static => {
129                         tcx.cannot_move_out_of(span, "static item", origin)
130                     }
131                     IllegalMoveOriginKind::BorrowedContent => {
132                         tcx.cannot_move_out_of(span, "borrowed content", origin)
133                     }
134                     IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
135                         tcx.cannot_move_out_of_interior_of_drop(span, ty, origin)
136                     }
137                     IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => {
138                         tcx.cannot_move_out_of_interior_noncopy(span, ty, is_index, origin)
139                     }
140                 };
141                 err.emit();
142             }
143             move_data
144         }
145     };
146
147     let mdpe = MoveDataParamEnv {
148         move_data: move_data,
149         param_env: param_env,
150     };
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)),
154     };
155
156     let dead_unwinds = IdxSetBuf::new_empty(mir.basic_blocks().len());
157     let mut flow_inits = FlowAtLocation::new(do_dataflow(
158         tcx,
159         mir,
160         id,
161         &attributes,
162         &dead_unwinds,
163         MaybeInitializedLvals::new(tcx, mir, &mdpe),
164         |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
165     ));
166     let flow_uninits = FlowAtLocation::new(do_dataflow(
167         tcx,
168         mir,
169         id,
170         &attributes,
171         &dead_unwinds,
172         MaybeUninitializedLvals::new(tcx, mir, &mdpe),
173         |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]),
174     ));
175     let flow_move_outs = FlowAtLocation::new(do_dataflow(
176         tcx,
177         mir,
178         id,
179         &attributes,
180         &dead_unwinds,
181         MovingOutStatements::new(tcx, mir, &mdpe),
182         |bd, i| DebugFormatted::new(&bd.move_data().moves[i]),
183     ));
184     let flow_ever_inits = FlowAtLocation::new(do_dataflow(
185         tcx,
186         mir,
187         id,
188         &attributes,
189         &dead_unwinds,
190         EverInitializedLvals::new(tcx, mir, &mdpe),
191         |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
192     ));
193
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(
197             infcx,
198             def_id,
199             free_regions,
200             mir,
201             param_env,
202             &mut flow_inits,
203             &mdpe.move_data,
204         );
205         (Some(Rc::new(regioncx)), opt_closure_req)
206     } else {
207         assert!(!tcx.sess.nll());
208         (None, None)
209     };
210     let flow_inits = flow_inits; // remove mut
211
212     let mut mbcx = MirBorrowckCtxt {
213         tcx: tcx,
214         mir: mir,
215         node_id: id,
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,
221         },
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(),
226     };
227
228     let borrows = Borrows::new(tcx, mir, opt_regioncx, def_id, body_id);
229     let flow_reservations = do_dataflow(
230         tcx,
231         mir,
232         id,
233         &attributes,
234         &dead_unwinds,
235         Reservations::new(borrows),
236         |rs, i| {
237             // In principle we could make the dataflow ensure that
238             // only reservation bits show up, and assert so here.
239             //
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)))
243         },
244     );
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(
249             mir,
250             &dead_unwinds,
251             Cow::Borrowed(reservations_on_entry),
252             ActiveBorrows::new(reservations),
253         );
254         let results = a.run(tcx, id, &attributes, |ab, i| {
255             DebugFormatted::new(&(i.kind(), ab.location(i)))
256         });
257         FlowAtLocation::new(results)
258     };
259
260     let mut state = Flows::new(
261         flow_active_borrows,
262         flow_inits,
263         flow_uninits,
264         flow_move_outs,
265         flow_ever_inits,
266     );
267
268     mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
269
270     opt_closure_req
271 }
272
273 #[allow(dead_code)]
274 pub struct MirBorrowckCtxt<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
275     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
276     mir: &'cx Mir<'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
282     /// constants.
283     ///
284     /// I'm not sure this is the right approach - @eddyb could you try and
285     /// figure this out?
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
296     ///
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>>>,
305 }
306
307 // Check that:
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>;
314
315     fn mir(&self) -> &'cx Mir<'tcx> {
316         self.mir
317     }
318
319     fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
320         debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
321     }
322
323     fn visit_statement_entry(
324         &mut self,
325         location: Location,
326         stmt: &Statement<'tcx>,
327         flow_state: &Self::FlowState,
328     ) {
329         debug!(
330             "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
331             location,
332             stmt,
333             flow_state
334         );
335         let span = stmt.source_info.span;
336
337         self.check_activations(location, span, flow_state);
338
339         match stmt.kind {
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."
346                 self.mutate_place(
347                     ContextKind::AssignLhs.new(location),
348                     (lhs, span),
349                     Deep,
350                     JustWrite,
351                     flow_state,
352                 );
353
354                 self.consume_rvalue(
355                     ContextKind::AssignRhs.new(location),
356                     (rhs, span),
357                     location,
358                     flow_state,
359                 );
360             }
361             StatementKind::SetDiscriminant {
362                 ref place,
363                 variant_index: _,
364             } => {
365                 self.mutate_place(
366                     ContextKind::SetDiscrim.new(location),
367                     (place, span),
368                     Shallow(Some(ArtificialField::Discriminant)),
369                     JustWrite,
370                     flow_state,
371                 );
372             }
373             StatementKind::InlineAsm {
374                 ref asm,
375                 ref outputs,
376                 ref inputs,
377             } => {
378                 let context = ContextKind::InlineAsm.new(location);
379                 for (o, output) in asm.outputs.iter().zip(outputs) {
380                     if o.is_indirect {
381                         // FIXME(eddyb) indirect inline asm outputs should
382                         // be encoeded through MIR place derefs instead.
383                         self.access_place(
384                             context,
385                             (output, span),
386                             (Deep, Read(ReadKind::Copy)),
387                             LocalMutationIsAllowed::No,
388                             flow_state,
389                         );
390                         self.check_if_path_is_moved(
391                             context,
392                             InitializationRequiringAction::Use,
393                             (output, span),
394                             flow_state,
395                         );
396                     } else {
397                         self.mutate_place(
398                             context,
399                             (output, span),
400                             Deep,
401                             if o.is_rw { WriteAndRead } else { JustWrite },
402                             flow_state,
403                         );
404                     }
405                 }
406                 for input in inputs {
407                     self.consume_operand(context, (input, span), flow_state);
408                 }
409             }
410             StatementKind::EndRegion(ref _rgn) => {
411                 // ignored when consuming results (update to
412                 // flow_state already handled).
413             }
414             StatementKind::Nop | StatementKind::Validate(..) | StatementKind::StorageLive(..) => {
415                 // `Nop`, `Validate`, and `StorageLive` are irrelevant
416                 // to borrow check.
417             }
418
419             StatementKind::StorageDead(local) => {
420                 self.access_place(
421                     ContextKind::StorageDead.new(location),
422                     (&Place::Local(local), span),
423                     (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
424                     LocalMutationIsAllowed::Yes,
425                     flow_state,
426                 );
427             }
428         }
429     }
430
431     fn visit_terminator_entry(
432         &mut self,
433         location: Location,
434         term: &Terminator<'tcx>,
435         flow_state: &Self::FlowState,
436     ) {
437         let loc = location;
438         debug!(
439             "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
440             location,
441             term,
442             flow_state
443         );
444         let span = term.source_info.span;
445
446         self.check_activations(location, span, flow_state);
447
448         match term.kind {
449             TerminatorKind::SwitchInt {
450                 ref discr,
451                 switch_ty: _,
452                 values: _,
453                 targets: _,
454             } => {
455                 self.consume_operand(ContextKind::SwitchInt.new(loc), (discr, span), flow_state);
456             }
457             TerminatorKind::Drop {
458                 location: ref drop_place,
459                 target: _,
460                 unwind: _,
461             } => {
462                 self.access_place(
463                     ContextKind::Drop.new(loc),
464                     (drop_place, span),
465                     (Deep, Write(WriteKind::StorageDeadOrDrop)),
466                     LocalMutationIsAllowed::Yes,
467                     flow_state,
468                 );
469             }
470             TerminatorKind::DropAndReplace {
471                 location: ref drop_place,
472                 value: ref new_value,
473                 target: _,
474                 unwind: _,
475             } => {
476                 self.mutate_place(
477                     ContextKind::DropAndReplace.new(loc),
478                     (drop_place, span),
479                     Deep,
480                     JustWrite,
481                     flow_state,
482                 );
483                 self.consume_operand(
484                     ContextKind::DropAndReplace.new(loc),
485                     (new_value, span),
486                     flow_state,
487                 );
488             }
489             TerminatorKind::Call {
490                 ref func,
491                 ref args,
492                 ref destination,
493                 cleanup: _,
494             } => {
495                 self.consume_operand(ContextKind::CallOperator.new(loc), (func, span), flow_state);
496                 for arg in args {
497                     self.consume_operand(
498                         ContextKind::CallOperand.new(loc),
499                         (arg, span),
500                         flow_state,
501                     );
502                 }
503                 if let Some((ref dest, _ /*bb*/)) = *destination {
504                     self.mutate_place(
505                         ContextKind::CallDest.new(loc),
506                         (dest, span),
507                         Deep,
508                         JustWrite,
509                         flow_state,
510                     );
511                 }
512             }
513             TerminatorKind::Assert {
514                 ref cond,
515                 expected: _,
516                 ref msg,
517                 target: _,
518                 cleanup: _,
519             } => {
520                 self.consume_operand(ContextKind::Assert.new(loc), (cond, span), flow_state);
521                 match *msg {
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),
526                             (index, span),
527                             flow_state,
528                         );
529                     }
530                     AssertMessage::Math(_ /*const_math_err*/) => {}
531                     AssertMessage::GeneratorResumedAfterReturn => {}
532                     AssertMessage::GeneratorResumedAfterPanic => {}
533                 }
534             }
535
536             TerminatorKind::Yield {
537                 ref value,
538                 resume: _,
539                 drop: _,
540             } => {
541                 self.consume_operand(ContextKind::Yield.new(loc), (value, span), flow_state);
542             }
543
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| {
552                     for i in 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);
556                     }
557                 });
558             }
559             TerminatorKind::Goto { target: _ }
560             | TerminatorKind::Unreachable
561             | TerminatorKind::FalseEdges { .. } => {
562                 // no data used, thus irrelevant to borrowck
563             }
564         }
565     }
566 }
567
568 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
569 enum MutateMode {
570     JustWrite,
571     WriteAndRead,
572 }
573
574 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
575 enum Control {
576     Continue,
577     Break,
578 }
579
580 use self::ShallowOrDeep::{Deep, Shallow};
581 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
582
583 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
584 enum ArtificialField {
585     Discriminant,
586     ArrayLength,
587 }
588
589 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
590 enum ShallowOrDeep {
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>),
597
598     /// From the RFC: "A *deep* access means that all data reachable
599     /// through the given place may be invalidated or accesses by
600     /// this action."
601     Deep,
602 }
603
604 /// Kind of access to a value: read or write
605 /// (For informational purposes only)
606 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
607 enum ReadOrWrite {
608     /// From the RFC: "A *read* means that the existing data may be
609     /// read, but will not be changed."
610     Read(ReadKind),
611
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).
615     Write(WriteKind),
616
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),
622 }
623
624 /// Kind of read access to a value
625 /// (For informational purposes only)
626 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
627 enum ReadKind {
628     Borrow(BorrowKind),
629     Copy,
630 }
631
632 /// Kind of write access to a value
633 /// (For informational purposes only)
634 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
635 enum WriteKind {
636     StorageDeadOrDrop,
637     MutableBorrow(BorrowKind),
638     Mutate,
639     Move,
640 }
641
642 /// When checking permissions for a place access, this flag is used to indicate that an immutable
643 /// local place can be mutated.
644 ///
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 {
652     Yes,
653     /// We want use of immutable upvars to cause a "write to immutable upvar"
654     /// error, not an "reassignment" error.
655     ExceptUpvars,
656     No,
657 }
658
659 struct AccessErrorsReported {
660     mutability_error: bool,
661     #[allow(dead_code)] conflict_error: bool,
662 }
663
664 #[derive(Copy, Clone)]
665 enum InitializationRequiringAction {
666     Update,
667     Borrow,
668     Use,
669     Assignment,
670 }
671
672 impl InitializationRequiringAction {
673     fn as_noun(self) -> &'static str {
674         match self {
675             InitializationRequiringAction::Update => "update",
676             InitializationRequiringAction::Borrow => "borrow",
677             InitializationRequiringAction::Use => "use",
678             InitializationRequiringAction::Assignment => "assign",
679         }
680     }
681
682     fn as_verb_in_past_tense(self) -> &'static str {
683         match self {
684             InitializationRequiringAction::Update => "updated",
685             InitializationRequiringAction::Borrow => "borrowed",
686             InitializationRequiringAction::Use => "used",
687             InitializationRequiringAction::Assignment => "assigned",
688         }
689     }
690 }
691
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
696     /// access.
697     ///
698     /// Returns true if an error is reported, false otherwise.
699     fn access_place(
700         &mut self,
701         context: Context,
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 {
707         let (sd, rw) = kind;
708
709         if let Activation(_, borrow_index) = rw {
710             if self.reservation_error_reported.contains(&place_span.0) {
711                 debug!(
712                     "skipping access_place for activation of invalid reservation \
713                      place: {:?} borrow_index: {:?}",
714                     place_span.0,
715                     borrow_index
716                 );
717                 return AccessErrorsReported {
718                     mutability_error: false,
719                     conflict_error: true,
720                 };
721             }
722         }
723
724         let mutability_error =
725             self.check_access_permissions(place_span, rw, is_local_mutation_allowed);
726         let conflict_error =
727             self.check_access_for_conflict(context, place_span, sd, rw, flow_state);
728
729         AccessErrorsReported {
730             mutability_error,
731             conflict_error,
732         }
733     }
734
735     fn check_access_for_conflict(
736         &mut self,
737         context: Context,
738         place_span: (&Place<'tcx>, Span),
739         sd: ShallowOrDeep,
740         rw: ReadOrWrite,
741         flow_state: &Flows<'cx, 'gcx, 'tcx>,
742     ) -> bool {
743         let mut error_reported = false;
744         self.each_borrow_involving_path(
745             context,
746             (sd, place_span.0),
747             flow_state,
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.
752                 //
753                 // NOTE: *reservations* do conflict with themselves;
754                 // thus aren't injecting unsoundenss w/ this check.)
755                 (Activation(_, activating), _) if activating == index.borrow_index() => {
756                     debug!(
757                         "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
758                          skipping {:?} b/c activation of same borrow_index: {:?}",
759                         place_span,
760                         sd,
761                         rw,
762                         (index, borrow),
763                         index.borrow_index()
764                     );
765                     Control::Continue
766                 }
767
768                 (Read(_), BorrowKind::Shared) | (Reservation(..), BorrowKind::Shared) => {
769                     Control::Continue
770                 }
771
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()
775                     {
776                         return Control::Continue;
777                     }
778
779                     match kind {
780                         ReadKind::Copy => {
781                             error_reported = true;
782                             this.report_use_while_mutably_borrowed(context, place_span, borrow)
783                         }
784                         ReadKind::Borrow(bk) => {
785                             let end_issued_loan_span = flow_state
786                                 .borrows
787                                 .operator()
788                                 .opt_region_end_span(&borrow.region);
789                             error_reported = true;
790                             this.report_conflicting_borrow(
791                                 context,
792                                 place_span,
793                                 bk,
794                                 &borrow,
795                                 end_issued_loan_span,
796                             )
797                         }
798                     }
799                     Control::Break
800                 }
801
802                 (Reservation(kind), BorrowKind::Unique)
803                 | (Reservation(kind), BorrowKind::Mut)
804                 | (Activation(kind, _), _)
805                 | (Write(kind), _) => {
806                     match rw {
807                         Reservation(_) => {
808                             debug!(
809                                 "recording invalid reservation of \
810                                  place: {:?}",
811                                 place_span.0
812                             );
813                             this.reservation_error_reported.insert(place_span.0.clone());
814                         }
815                         Activation(_, activating) => {
816                             debug!(
817                                 "observing check_place for activation of \
818                                  borrow_index: {:?}",
819                                 activating
820                             );
821                         }
822                         Read(..) | Write(..) => {}
823                     }
824
825                     match kind {
826                         WriteKind::MutableBorrow(bk) => {
827                             let end_issued_loan_span = flow_state
828                                 .borrows
829                                 .operator()
830                                 .opt_region_end_span(&borrow.region);
831
832                             error_reported = true;
833                             this.report_conflicting_borrow(
834                                 context,
835                                 place_span,
836                                 bk,
837                                 &borrow,
838                                 end_issued_loan_span,
839                             )
840                         }
841                         WriteKind::StorageDeadOrDrop => {
842                             error_reported = true;
843                             this.report_borrowed_value_does_not_live_long_enough(
844                                 context,
845                                 borrow,
846                                 place_span.1,
847                                 flow_state.borrows.operator(),
848                             );
849                         }
850                         WriteKind::Mutate => {
851                             error_reported = true;
852                             this.report_illegal_mutation_of_borrowed(context, place_span, borrow)
853                         }
854                         WriteKind::Move => {
855                             error_reported = true;
856                             this.report_move_out_while_borrowed(context, place_span, &borrow)
857                         }
858                     }
859                     Control::Break
860                 }
861             },
862         );
863
864         error_reported
865     }
866
867     fn mutate_place(
868         &mut self,
869         context: Context,
870         place_span: (&Place<'tcx>, Span),
871         kind: ShallowOrDeep,
872         mode: MutateMode,
873         flow_state: &Flows<'cx, 'gcx, 'tcx>,
874     ) {
875         // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
876         match mode {
877             MutateMode::WriteAndRead => {
878                 self.check_if_path_is_moved(
879                     context,
880                     InitializationRequiringAction::Update,
881                     place_span,
882                     flow_state,
883                 );
884             }
885             MutateMode::JustWrite => {
886                 self.check_if_assigned_path_is_moved(context, place_span, flow_state);
887             }
888         }
889
890         let errors_reported = self.access_place(
891             context,
892             place_span,
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.
897             //
898             // There's probably a better way to do this.
899             LocalMutationIsAllowed::ExceptUpvars,
900             flow_state,
901         );
902
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);
906         }
907     }
908
909     fn consume_rvalue(
910         &mut self,
911         context: Context,
912         (rvalue, span): (&Rvalue<'tcx>, Span),
913         _location: Location,
914         flow_state: &Flows<'cx, 'gcx, 'tcx>,
915     ) {
916         match *rvalue {
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))
924                         } else {
925                             (Deep, Write(wk))
926                         }
927                     }
928                 };
929
930                 self.access_place(
931                     context,
932                     (place, span),
933                     access_kind,
934                     LocalMutationIsAllowed::No,
935                     flow_state,
936                 );
937
938                 self.check_if_path_is_moved(
939                     context,
940                     InitializationRequiringAction::Borrow,
941                     (place, span),
942                     flow_state,
943                 );
944             }
945
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)
951             }
952
953             Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
954                 let af = match *rvalue {
955                     Rvalue::Len(..) => ArtificialField::ArrayLength,
956                     Rvalue::Discriminant(..) => ArtificialField::Discriminant,
957                     _ => unreachable!(),
958                 };
959                 self.access_place(
960                     context,
961                     (place, span),
962                     (Shallow(Some(af)), Read(ReadKind::Copy)),
963                     LocalMutationIsAllowed::No,
964                     flow_state,
965                 );
966                 self.check_if_path_is_moved(
967                     context,
968                     InitializationRequiringAction::Use,
969                     (place, span),
970                     flow_state,
971                 );
972             }
973
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);
978             }
979
980             Rvalue::NullaryOp(_op, _ty) => {
981                 // nullary ops take no dynamic input; no borrowck effect.
982                 //
983                 // FIXME: is above actually true? Do we want to track
984                 // the fact that uninitialized data can be created via
985                 // `NullOp::Box`?
986             }
987
988             Rvalue::Aggregate(ref _aggregate_kind, ref operands) => for operand in operands {
989                 self.consume_operand(context, (operand, span), flow_state);
990             },
991         }
992     }
993
994     fn consume_operand(
995         &mut self,
996         context: Context,
997         (operand, span): (&Operand<'tcx>, Span),
998         flow_state: &Flows<'cx, 'gcx, 'tcx>,
999     ) {
1000         match *operand {
1001             Operand::Copy(ref place) => {
1002                 // copy of place: check if this is "copy of frozen path"
1003                 // (FIXME: see check_loans.rs)
1004                 self.access_place(
1005                     context,
1006                     (place, span),
1007                     (Deep, Read(ReadKind::Copy)),
1008                     LocalMutationIsAllowed::No,
1009                     flow_state,
1010                 );
1011
1012                 // Finally, check if path was already moved.
1013                 self.check_if_path_is_moved(
1014                     context,
1015                     InitializationRequiringAction::Use,
1016                     (place, span),
1017                     flow_state,
1018                 );
1019             }
1020             Operand::Move(ref place) => {
1021                 // move of place: check if this is move of already borrowed path
1022                 self.access_place(
1023                     context,
1024                     (place, span),
1025                     (Deep, Write(WriteKind::Move)),
1026                     LocalMutationIsAllowed::Yes,
1027                     flow_state,
1028                 );
1029
1030                 // Finally, check if path was already moved.
1031                 self.check_if_path_is_moved(
1032                     context,
1033                     InitializationRequiringAction::Use,
1034                     (place, span),
1035                     flow_state,
1036                 );
1037             }
1038             Operand::Constant(_) => {}
1039         }
1040     }
1041
1042     /// Returns whether a borrow of this place is invalidated when the function
1043     /// exits
1044     fn check_for_invalidation_at_exit(
1045         &mut self,
1046         context: Context,
1047         borrow: &BorrowData<'tcx>,
1048         span: Span,
1049         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1050     ) {
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();
1054
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.
1058         //
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)
1066                     .iter()
1067                     .any(|attr| attr.check_name("thread_local"));
1068
1069                 (true, is_thread_local)
1070             }
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)
1075             }
1076             Place::Projection(..) => {
1077                 bug!("root of {:?} is a projection ({:?})?", place, root_place)
1078             }
1079         };
1080
1081         if !will_be_dropped {
1082             debug!(
1083                 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1084                 place
1085             );
1086             return;
1087         }
1088
1089         // FIXME: replace this with a proper borrow_conflicts_with_place when
1090         // that is merged.
1091         let sd = if might_be_alive { Deep } else { Shallow(None) };
1092
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(
1098                 context,
1099                 borrow,
1100                 span.end_point(),
1101                 flow_state.borrows.operator(),
1102             )
1103         }
1104     }
1105
1106     fn check_activations(
1107         &mut self,
1108         location: Location,
1109         span: Span,
1110         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1111     ) {
1112         if !self.tcx.sess.two_phase_borrows() {
1113             return;
1114         }
1115
1116         // Two-phase borrow support: For each activation that is newly
1117         // generated at this statement, check if it interferes with
1118         // another borrow.
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.
1129                 match borrow.kind {
1130                     BorrowKind::Shared => return,
1131                     BorrowKind::Unique | BorrowKind::Mut => {}
1132                 }
1133
1134                 self.access_place(
1135                     ContextKind::Activation.new(location),
1136                     (&borrow.borrowed_place, span),
1137                     (
1138                         Deep,
1139                         Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1140                     ),
1141                     LocalMutationIsAllowed::No,
1142                     flow_state,
1143                 );
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.
1147             }
1148         });
1149     }
1150 }
1151
1152 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1153     fn check_if_reassignment_to_immutable_state(
1154         &mut self,
1155         context: Context,
1156         (place, span): (&Place<'tcx>, Span),
1157         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1158     ) {
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) {
1162             return;
1163         }
1164         debug!(
1165             "check_if_reassignment_to_immutable_state({:?}) - is an imm local",
1166             place
1167         );
1168
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);
1174                 break;
1175             }
1176         }
1177     }
1178
1179     fn check_if_path_is_moved(
1180         &mut self,
1181         context: Context,
1182         desired_action: InitializationRequiringAction,
1183         place_span: (&Place<'tcx>, Span),
1184         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1185     ) {
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);
1189
1190         let maybe_uninits = &flow_state.uninits;
1191         let curr_move_outs = &flow_state.move_outs;
1192
1193         // Bad scenarios:
1194         //
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`.
1201         //
1202         // OK scenarios:
1203         //
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`
1209
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
1213         // structure.
1214         //
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.)
1222
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.
1226         //
1227         // This code covers scenarios 1, 2, and 4.
1228
1229         debug!("check_if_path_is_moved part1 place: {:?}", place);
1230         match self.move_path_closest_to(place) {
1231             Ok(mpi) => {
1232                 if maybe_uninits.contains(&mpi) {
1233                     self.report_use_of_moved_or_uninitialized(
1234                         context,
1235                         desired_action,
1236                         place_span,
1237                         mpi,
1238                         curr_move_outs,
1239                     );
1240                     return; // don't bother finding other problems.
1241                 }
1242             }
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).
1248               //
1249               // (I.e. querying parents breaks scenario 8; but may want
1250               // to do such a query based on partial-init feature-gate.)
1251         }
1252
1253         // A move of any shallow suffix of `place` also interferes
1254         // with an attempt to use `place`. This is scenario 3 above.
1255         //
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`)
1259
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(
1264                     context,
1265                     desired_action,
1266                     place_span,
1267                     child_mpi,
1268                     curr_move_outs,
1269                 );
1270                 return; // don't bother finding other problems.
1271             }
1272         }
1273     }
1274
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.
1281     ///
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(
1286         &mut self,
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) {
1292                 return Ok(mpi);
1293             }
1294             last_prefix = prefix;
1295         }
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),
1300         }
1301     }
1302
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).
1307
1308         match self.move_data.rev_lookup.find(place) {
1309             LookupResult::Parent(_) => None,
1310             LookupResult::Exact(mpi) => Some(mpi),
1311         }
1312     }
1313
1314     fn check_if_assigned_path_is_moved(
1315         &mut self,
1316         context: Context,
1317         (place, span): (&Place<'tcx>, Span),
1318         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1319     ) {
1320         // recur down place; dispatch to check_if_path_is_moved when necessary
1321         let mut place = place;
1322         loop {
1323             match *place {
1324                 Place::Local(_) | Place::Static(_) => {
1325                     // assigning to `x` does not require `x` be initialized.
1326                     break;
1327                 }
1328                 Place::Projection(ref proj) => {
1329                     let Projection { ref base, ref elem } = **proj;
1330                     match *elem {
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
1338                         //
1339                         // FIXME: is this true even if P is a adt with a dtor?
1340                         { }
1341
1342                         ProjectionElem::Subslice { .. } => {
1343                             panic!("we dont allow assignments to subslices, context: {:?}",
1344                                    context);
1345                         }
1346
1347                         ProjectionElem::Field(..) => {
1348                             // if type of `P` has a dtor, then
1349                             // assigning to `P.f` requires `P` itself
1350                             // be already initialized
1351                             let tcx = self.tcx;
1352                             match base.ty(self.mir, tcx).to_ty(tcx).sty {
1353                                 ty::TyAdt(def, _) if def.has_dtor(tcx) => {
1354
1355                                     // FIXME: analogous code in
1356                                     // check_loans.rs first maps
1357                                     // `base` to its base_path.
1358
1359                                     self.check_if_path_is_moved(
1360                                         context, InitializationRequiringAction::Assignment,
1361                                         (base, span), flow_state);
1362
1363                                     // (base initialized; no need to
1364                                     // recur further)
1365                                     break;
1366                                 }
1367                                 _ => {}
1368                             }
1369                         }
1370                     }
1371
1372                     place = base;
1373                     continue;
1374                 }
1375             }
1376         }
1377     }
1378
1379     /// Check the permissions for the given place and read or write kind
1380     ///
1381     /// Returns true if an error is reported, false otherwise.
1382     fn check_access_permissions(
1383         &self,
1384         (place, span): (&Place<'tcx>, Span),
1385         kind: ReadOrWrite,
1386         is_local_mutation_allowed: LocalMutationIsAllowed,
1387     ) -> bool {
1388         debug!(
1389             "check_access_permissions({:?}, {:?}, {:?})",
1390             place,
1391             kind,
1392             is_local_mutation_allowed
1393         );
1394         let mut error_reported = false;
1395         match kind {
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);
1400                 }
1401             }
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)
1405             {
1406                 error_reported = true;
1407
1408                 let item_msg = match self.describe_place(place) {
1409                     Some(name) => format!("immutable item `{}`", name),
1410                     None => "immutable item".to_owned(),
1411                 };
1412
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");
1416
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));
1420                     }
1421                 }
1422
1423                 err.emit();
1424             },
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;
1428
1429                     let item_msg = match self.describe_place(place) {
1430                         Some(name) => format!("immutable item `{}`", name),
1431                         None => "immutable item".to_owned(),
1432                     };
1433
1434                     let mut err = self.tcx.cannot_assign(span, &item_msg, Origin::Mir);
1435                     err.span_label(span, "cannot mutate");
1436
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));
1440                         }
1441                     }
1442
1443                     err.emit();
1444                 }
1445             }
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(
1454                         span,
1455                         &format!(
1456                             "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
1457                             place,
1458                             kind
1459                         ),
1460                     );
1461                 }
1462             }
1463
1464             Activation(..) => {} // permission checks are done at Reservation point.
1465
1466             Read(ReadKind::Borrow(BorrowKind::Unique))
1467             | Read(ReadKind::Borrow(BorrowKind::Mut))
1468             | Read(ReadKind::Borrow(BorrowKind::Shared))
1469             | Read(ReadKind::Copy) => {} // Access authorized
1470         }
1471
1472         error_reported
1473     }
1474
1475     /// Can this value be written or borrowed mutably
1476     fn is_mutable<'d>(
1477         &self,
1478         place: &'d Place<'tcx>,
1479         is_local_mutation_allowed: LocalMutationIsAllowed,
1480     ) -> Result<(), &'d Place<'tcx>> {
1481         match *place {
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 => {
1487                             Ok(())
1488                         }
1489                         LocalMutationIsAllowed::No => Err(place),
1490                     },
1491                     Mutability::Mut => Ok(()),
1492                 }
1493             }
1494             Place::Static(ref static_) => if !self.tcx.is_static_mut(static_.def_id) {
1495                 Err(place)
1496             } else {
1497                 Ok(())
1498             },
1499             Place::Projection(ref proj) => {
1500                 match proj.elem {
1501                     ProjectionElem::Deref => {
1502                         let base_ty = proj.base.ty(self.mir, self.tcx).to_ty(self.tcx);
1503
1504                         // Check the kind of deref to decide
1505                         match base_ty.sty {
1506                             ty::TyRef(_, tnm) => {
1507                                 match tnm.mutbl {
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)
1514                                         {
1515                                             Some(field)
1516                                                 if {
1517                                                     self.mir.upvar_decls[field.index()].by_ref
1518                                                 } =>
1519                                             {
1520                                                 is_local_mutation_allowed
1521                                             }
1522                                             _ => LocalMutationIsAllowed::Yes,
1523                                         };
1524
1525                                         self.is_mutable(&proj.base, mode)
1526                                     }
1527                                 }
1528                             }
1529                             ty::TyRawPtr(tnm) => {
1530                                 match tnm.mutbl {
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(()),
1536                                 }
1537                             }
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)
1541                             }
1542                             // Deref should only be for reference, pointers or boxes
1543                             _ => bug!("Deref of unexpected type: {:?}", base_ty),
1544                         }
1545                     }
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()];
1555                             debug!(
1556                                 "decl.mutability={:?} local_mutation_is_allowed={:?} place={:?}",
1557                                 decl,
1558                                 is_local_mutation_allowed,
1559                                 place
1560                             );
1561                             match (decl.mutability, is_local_mutation_allowed) {
1562                                 (Mutability::Not, LocalMutationIsAllowed::No)
1563                                 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
1564                                     Err(place)
1565                                 }
1566                                 (Mutability::Not, LocalMutationIsAllowed::Yes)
1567                                 | (Mutability::Mut, _) => {
1568                                     self.is_mutable(&proj.base, is_local_mutation_allowed)
1569                                 }
1570                             }
1571                         } else {
1572                             self.is_mutable(&proj.base, is_local_mutation_allowed)
1573                         }
1574                     }
1575                 }
1576             }
1577         }
1578     }
1579
1580
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> {
1586         match *place {
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)
1591                         .to_ty(self.tcx)
1592                         .is_closure();
1593
1594                     if is_projection_from_ty_closure {
1595                         Some(field)
1596                     } else {
1597                         None
1598                     }
1599                 }
1600                 _ => None,
1601             },
1602             _ => None,
1603         }
1604     }
1605 }
1606
1607 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1608 enum NoMovePathFound {
1609     ReachedStatic,
1610 }
1611
1612 /// The degree of overlap between 2 places for borrow-checking.
1613 enum Overlap {
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.
1619     Arbitrary,
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
1623     /// of the place.
1624     EqualOrDisjoint,
1625     /// The places are disjoint, so we know all extensions of them
1626     /// will also be disjoint.
1627     Disjoint,
1628 }
1629
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)) => {
1637                 if l1 == l2 {
1638                     // the same local - base case, equal
1639                     debug!("place_element_conflict: DISJOINT-OR-EQ-LOCAL");
1640                     Overlap::EqualOrDisjoint
1641                 } else {
1642                     // different locals - base case, disjoint
1643                     debug!("place_element_conflict: DISJOINT-LOCAL");
1644                     Overlap::Disjoint
1645                 }
1646             }
1647             (Place::Static(static1), Place::Static(static2)) => {
1648                 if static1.def_id != static2.def_id {
1649                     debug!("place_element_conflict: DISJOINT-STATIC");
1650                     Overlap::Disjoint
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");
1654                     Overlap::Disjoint
1655                 } else {
1656                     debug!("place_element_conflict: DISJOINT-OR-EQ-STATIC");
1657                     Overlap::EqualOrDisjoint
1658                 }
1659             }
1660             (Place::Local(_), Place::Static(_)) | (Place::Static(_), Place::Local(_)) => {
1661                 debug!("place_element_conflict: DISJOINT-STATIC-LOCAL");
1662                 Overlap::Disjoint
1663             }
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
1670                     }
1671                     (ProjectionElem::Field(f1, _), ProjectionElem::Field(f2, _)) => {
1672                         if f1 == f2 {
1673                             // same field (e.g. `a.y` vs. `a.y`) - recur.
1674                             debug!("place_element_conflict: DISJOINT-OR-EQ-FIELD");
1675                             Overlap::EqualOrDisjoint
1676                         } else {
1677                             let ty = pi1.base.ty(self.mir, self.tcx).to_ty(self.tcx);
1678                             match ty.sty {
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");
1682                                     Overlap::Arbitrary
1683                                 }
1684                                 _ => {
1685                                     // Different fields of a struct (`a.x` vs. `a.y`). Disjoint!
1686                                     debug!("place_element_conflict: DISJOINT-FIELD");
1687                                     Overlap::Disjoint
1688                                 }
1689                             }
1690                         }
1691                     }
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.
1697                         //
1698                         // Note that this is different from unions - we *do* allow
1699                         // this code to compile:
1700                         //
1701                         // ```
1702                         // fn foo(x: &mut Result<i32, i32>) {
1703                         //     let mut v = None;
1704                         //     if let Ok(ref mut a) = *x {
1705                         //         v = Some(a);
1706                         //     }
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 {
1712                         //         v = Some(a);
1713                         //     }
1714                         //     drop(v);
1715                         // }
1716                         // ```
1717                         if v1 == v2 {
1718                             debug!("place_element_conflict: DISJOINT-OR-EQ-FIELD");
1719                             Overlap::EqualOrDisjoint
1720                         } else {
1721                             debug!("place_element_conflict: DISJOINT-FIELD");
1722                             Overlap::Disjoint
1723                         }
1724                     }
1725                     (ProjectionElem::Index(..), ProjectionElem::Index(..))
1726                     | (ProjectionElem::Index(..), ProjectionElem::ConstantIndex { .. })
1727                     | (ProjectionElem::Index(..), ProjectionElem::Subslice { .. })
1728                     | (ProjectionElem::ConstantIndex { .. }, ProjectionElem::Index(..))
1729                     | (
1730                         ProjectionElem::ConstantIndex { .. },
1731                         ProjectionElem::ConstantIndex { .. },
1732                     )
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.
1740                         //
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.
1746                         //
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
1751                     }
1752
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 {:?}",
1760                         elem1,
1761                         elem2
1762                     ),
1763                 }
1764             }
1765             (Place::Projection(_), _) | (_, Place::Projection(_)) => bug!(
1766                 "unexpected elements in place_element_conflict: {:?} and {:?}",
1767                 elem1,
1768                 elem2
1769             ),
1770         }
1771     }
1772
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`).
1776     fn places_conflict(
1777         &mut self,
1778         borrow_place: &Place<'tcx>,
1779         access_place: &Place<'tcx>,
1780         access: ShallowOrDeep,
1781     ) -> bool {
1782         debug!(
1783             "places_conflict({:?},{:?},{:?})",
1784             borrow_place,
1785             access_place,
1786             access
1787         );
1788
1789         // Return all the prefixes of `place` in reverse order, including
1790         // downcasts.
1791         fn place_elements<'a, 'tcx>(place: &'a Place<'tcx>) -> Vec<&'a Place<'tcx>> {
1792             let mut result = vec![];
1793             let mut place = place;
1794             loop {
1795                 result.push(place);
1796                 match place {
1797                     Place::Projection(interior) => {
1798                         place = &interior.base;
1799                     }
1800                     Place::Local(_) | Place::Static(_) => {
1801                         result.reverse();
1802                         return result;
1803                     }
1804                 }
1805             }
1806         }
1807
1808         let borrow_components = place_elements(borrow_place);
1809         let access_components = place_elements(access_place);
1810         debug!(
1811             "places_conflict: components {:?} / {:?}",
1812             borrow_components,
1813             access_components
1814         );
1815
1816         let borrow_components = borrow_components
1817             .into_iter()
1818             .map(Some)
1819             .chain(iter::repeat(None));
1820         let access_components = access_components
1821             .into_iter()
1822             .map(Some)
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`.
1828         //
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.
1831         //
1832         // For example, if we are comparing these:
1833         // BORROW:  (*x1[2].y).z.a
1834         // ACCESS:  (*x1[i].y).w.b
1835         //
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!
1842         //
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.
1845         //
1846         // BORROW:  (*x1[2].y).z.a
1847         // ACCESS:  x1[i].y
1848         //
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
1853         //
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:
1857         //
1858         //       x1[2].y    | (*x1[i].y)    -- a deref! the access can't get past this, so we
1859         //                                     are disjoint
1860         //
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) {
1869                 (None, _) => {
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.
1873                     //
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.
1877                     //
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");
1881                     return true;
1882                 }
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.
1886
1887                     let (base, elem) = match borrow_c {
1888                         Place::Projection(box Projection { base, elem }) => (base, elem),
1889                         _ => bug!("place has no base?"),
1890                     };
1891                     let base_ty = base.ty(self.mir, self.tcx).to_ty(self.tcx);
1892
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
1901                             // currently.)
1902                             //
1903                             // e.g. a (mutable) borrow of `a[5]` while we read the
1904                             // array length of `a`.
1905                             debug!("places_conflict: implicit field");
1906                             return false;
1907                         }
1908
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
1912                             // the pointer.
1913                             debug!("places_conflict: shallow access behind ptr");
1914                             return false;
1915                         }
1916                         (
1917                             ProjectionElem::Deref,
1918                             ty::TyRef(
1919                                 _,
1920                                 ty::TypeAndMut {
1921                                     ty: _,
1922                                     mutbl: hir::MutImmutable,
1923                                 },
1924                             ),
1925                             _,
1926                         ) => {
1927                             // the borrow goes through a dereference of a shared reference.
1928                             //
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");
1933                             return false;
1934                         }
1935
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`.
1946                         }
1947                     }
1948                 }
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.
1954                             //
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).
1959                             //
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");
1966                             return true;
1967                         }
1968                         Overlap::EqualOrDisjoint => {
1969                             // This is the recursive case - proceed to the next element.
1970                         }
1971                         Overlap::Disjoint => {
1972                             // We have proven the borrow disjoint - further
1973                             // projections will remain disjoint.
1974                             debug!("places_conflict: disjoint");
1975                             return false;
1976                         }
1977                     }
1978                 }
1979             }
1980         }
1981         unreachable!("iter::repeat returned None")
1982     }
1983
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
1987     /// one.
1988     ///
1989     /// "Current borrow" here means a borrow that reaches the point in
1990     /// the control-flow where the access occurs.
1991     ///
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>(
1997         &mut self,
1998         _context: Context,
1999         access_place: (ShallowOrDeep, &Place<'tcx>),
2000         flow_state: &Flows<'cx, 'gcx, 'tcx>,
2001         mut op: F,
2002     ) where
2003         F: FnMut(&mut Self, ReserveOrActivateIndex, &BorrowData<'tcx>) -> Control,
2004     {
2005         let (access, place) = access_place;
2006
2007         // FIXME: analogous code in check_loans first maps `place` to
2008         // its base_path.
2009
2010         let data = flow_state.borrows.operator().borrows();
2011
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()];
2017
2018             if self.places_conflict(&borrowed.borrowed_place, place, access) {
2019                 let ctrl = op(self, i, borrowed);
2020                 if ctrl == Control::Break {
2021                     return;
2022                 }
2023             }
2024         }
2025     }
2026 }
2027
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...)
2033
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.
2038
2039         let mut cursor = place;
2040         let mut deepest = place;
2041         loop {
2042             let proj = match *cursor {
2043                 Place::Local(..) | Place::Static(..) => return deepest,
2044                 Place::Projection(ref proj) => proj,
2045             };
2046             if proj.elem == ProjectionElem::Deref
2047                 && place.ty(self.mir, self.tcx).to_ty(self.tcx).is_box()
2048             {
2049                 deepest = &proj.base;
2050             }
2051             cursor = &proj.base;
2052         }
2053     }
2054 }
2055
2056 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2057 struct Context {
2058     kind: ContextKind,
2059     loc: Location,
2060 }
2061
2062 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2063 enum ContextKind {
2064     Activation,
2065     AssignLhs,
2066     AssignRhs,
2067     SetDiscrim,
2068     InlineAsm,
2069     SwitchInt,
2070     Drop,
2071     DropAndReplace,
2072     CallOperator,
2073     CallOperand,
2074     CallDest,
2075     Assert,
2076     Yield,
2077     StorageDead,
2078 }
2079
2080 impl ContextKind {
2081     fn new(self, loc: Location) -> Context {
2082         Context {
2083             kind: self,
2084             loc: loc,
2085         }
2086     }
2087 }