]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/mod.rs
Auto merge of #50339 - nnethercote:lazy-Printer-buf, r=michaelwoerister
[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::{RegionCausalInfo, 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::lint::builtin::UNUSED_MUT;
21 use rustc::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
22 use rustc::mir::{ClearCrossCrate, Local, Location, Place, Mir, Mutability, Operand};
23 use rustc::mir::{Projection, ProjectionElem, Rvalue, Field, Statement, StatementKind};
24 use rustc::mir::{Terminator, TerminatorKind};
25
26 use rustc_data_structures::control_flow_graph::dominators::Dominators;
27 use rustc_data_structures::fx::FxHashSet;
28 use rustc_data_structures::indexed_set::IdxSetBuf;
29 use rustc_data_structures::indexed_vec::Idx;
30 use rustc_data_structures::small_vec::SmallVec;
31
32 use std::rc::Rc;
33
34 use syntax_pos::Span;
35
36 use dataflow::{do_dataflow, DebugFormatted};
37 use dataflow::FlowAtLocation;
38 use dataflow::MoveDataParamEnv;
39 use dataflow::{DataflowResultsConsumer};
40 use dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
41 use dataflow::{EverInitializedPlaces, MovingOutStatements};
42 use dataflow::Borrows;
43 use dataflow::indexes::BorrowIndex;
44 use dataflow::move_paths::{IllegalMoveOriginKind, MoveError};
45 use dataflow::move_paths::{HasMoveData, LookupResult, MoveData, MovePathIndex};
46 use util::borrowck_errors::{BorrowckErrors, Origin};
47 use util::collect_writes::FindAssignments;
48
49 use std::iter;
50
51 use self::borrow_set::{BorrowSet, BorrowData};
52 use self::flows::Flows;
53 use self::prefixes::PrefixSet;
54 use self::MutateMode::{JustWrite, WriteAndRead};
55
56 crate mod borrow_set;
57 mod error_reporting;
58 mod flows;
59 crate mod place_ext;
60 mod prefixes;
61
62 pub(crate) mod nll;
63
64 pub fn provide(providers: &mut Providers) {
65     *providers = Providers {
66         mir_borrowck,
67         ..*providers
68     };
69 }
70
71 fn mir_borrowck<'a, 'tcx>(
72     tcx: TyCtxt<'a, 'tcx, 'tcx>,
73     def_id: DefId,
74 ) -> BorrowCheckResult<'tcx> {
75     let input_mir = tcx.mir_validated(def_id);
76     debug!("run query mir_borrowck: {}", tcx.item_path_str(def_id));
77
78     if !tcx.has_attr(def_id, "rustc_mir_borrowck") && !tcx.use_mir_borrowck() {
79         return BorrowCheckResult {
80             closure_requirements: None,
81             used_mut_upvars: SmallVec::new(),
82         };
83     }
84
85     let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
86         let input_mir: &Mir = &input_mir.borrow();
87         do_mir_borrowck(&infcx, input_mir, def_id)
88     });
89     debug!("mir_borrowck done");
90
91     opt_closure_req
92 }
93
94 fn do_mir_borrowck<'a, 'gcx, 'tcx>(
95     infcx: &InferCtxt<'a, 'gcx, 'tcx>,
96     input_mir: &Mir<'gcx>,
97     def_id: DefId,
98 ) -> BorrowCheckResult<'gcx> {
99     let tcx = infcx.tcx;
100     let attributes = tcx.get_attrs(def_id);
101     let param_env = tcx.param_env(def_id);
102     let id = tcx.hir
103         .as_local_node_id(def_id)
104         .expect("do_mir_borrowck: non-local DefId");
105
106     // Replace all regions with fresh inference variables. This
107     // requires first making our own copy of the MIR. This copy will
108     // be modified (in place) to contain non-lexical lifetimes. It
109     // will have a lifetime tied to the inference context.
110     let mut mir: Mir<'tcx> = input_mir.clone();
111     let free_regions = nll::replace_regions_in_mir(infcx, def_id, param_env, &mut mir);
112     let mir = &mir; // no further changes
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!("don't 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         MaybeInitializedPlaces::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         MaybeUninitializedPlaces::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         EverInitializedPlaces::new(tcx, mir, &mdpe),
191         |bd, i| DebugFormatted::new(&bd.move_data().inits[i]),
192     ));
193
194     let borrow_set = Rc::new(BorrowSet::build(tcx, mir));
195
196     // If we are in non-lexical mode, compute the non-lexical lifetimes.
197     let (regioncx, opt_closure_req) = nll::compute_regions(
198         infcx,
199         def_id,
200         free_regions,
201         mir,
202         param_env,
203         &mut flow_inits,
204         &mdpe.move_data,
205         &borrow_set,
206     );
207     let regioncx = Rc::new(regioncx);
208     let flow_inits = flow_inits; // remove mut
209
210     let flow_borrows = FlowAtLocation::new(do_dataflow(
211         tcx,
212         mir,
213         id,
214         &attributes,
215         &dead_unwinds,
216         Borrows::new(tcx, mir, regioncx.clone(), def_id, body_id, &borrow_set),
217         |rs, i| DebugFormatted::new(&rs.location(i)),
218     ));
219
220     let movable_generator = match tcx.hir.get(id) {
221         hir::map::Node::NodeExpr(&hir::Expr {
222             node: hir::ExprClosure(.., Some(hir::GeneratorMovability::Static)),
223             ..
224         }) => false,
225         _ => true,
226     };
227
228     let dominators = mir.dominators();
229
230     let mut mbcx = MirBorrowckCtxt {
231         tcx: tcx,
232         mir: mir,
233         mir_def_id: def_id,
234         move_data: &mdpe.move_data,
235         param_env: param_env,
236         movable_generator,
237         locals_are_invalidated_at_exit: match tcx.hir.body_owner_kind(id) {
238             hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => false,
239             hir::BodyOwnerKind::Fn => true,
240         },
241         access_place_error_reported: FxHashSet(),
242         reservation_error_reported: FxHashSet(),
243         moved_error_reported: FxHashSet(),
244         nonlexical_regioncx: regioncx,
245         used_mut: FxHashSet(),
246         used_mut_upvars: SmallVec::new(),
247         nonlexical_cause_info: None,
248         borrow_set,
249         dominators,
250     };
251
252     let mut state = Flows::new(
253         flow_borrows,
254         flow_inits,
255         flow_uninits,
256         flow_move_outs,
257         flow_ever_inits,
258     );
259
260     mbcx.analyze_results(&mut state); // entry point for DataflowResultsConsumer
261
262     // For each non-user used mutable variable, check if it's been assigned from
263     // a user-declared local. If so, then put that local into the used_mut set.
264     // Note that this set is expected to be small - only upvars from closures
265     // would have a chance of erroneously adding non-user-defined mutable vars
266     // to the set.
267     let temporary_used_locals: FxHashSet<Local> =
268         mbcx.used_mut.iter()
269             .filter(|&local| !mbcx.mir.local_decls[*local].is_user_variable)
270             .cloned()
271             .collect();
272
273     for local in temporary_used_locals {
274         for location in mbcx.mir.find_assignments(local) {
275             for moi in &mbcx.move_data.loc_map[location] {
276                 let mpi = &mbcx.move_data.moves[*moi].path;
277                 let path = &mbcx.move_data.move_paths[*mpi];
278                 debug!("assignment of {:?} to {:?}, adding {:?} to used mutable set",
279                        path.place, local, path.place);
280                 if let Place::Local(user_local) = path.place {
281                     mbcx.used_mut.insert(user_local);
282                 }
283             }
284         }
285     }
286
287     debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
288
289     for local in mbcx.mir.mut_vars_and_args_iter().filter(|local| !mbcx.used_mut.contains(local)) {
290         if let ClearCrossCrate::Set(ref vsi) = mbcx.mir.visibility_scope_info {
291             let local_decl = &mbcx.mir.local_decls[local];
292
293             // Skip implicit `self` argument for closures
294             if local.index() == 1 && tcx.is_closure(mbcx.mir_def_id) {
295                 continue;
296             }
297
298             // Skip over locals that begin with an underscore
299             match local_decl.name {
300                 Some(name) if name.as_str().starts_with("_") => continue,
301                 _ => {},
302             }
303
304             let source_info = local_decl.source_info;
305             let mut_span = tcx.sess.codemap().span_until_non_whitespace(source_info.span);
306
307             tcx.struct_span_lint_node(
308                 UNUSED_MUT,
309                 vsi[local_decl.syntactic_scope].lint_root,
310                 source_info.span,
311                 "variable does not need to be mutable"
312             )
313             .span_suggestion_short(mut_span, "remove this `mut`", "".to_owned())
314             .emit();
315         }
316     }
317
318     BorrowCheckResult {
319         closure_requirements: opt_closure_req,
320         used_mut_upvars: mbcx.used_mut_upvars,
321     }
322 }
323
324 #[allow(dead_code)]
325 pub struct MirBorrowckCtxt<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
326     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
327     mir: &'cx Mir<'tcx>,
328     mir_def_id: DefId,
329     move_data: &'cx MoveData<'tcx>,
330     param_env: ParamEnv<'gcx>,
331     movable_generator: bool,
332     /// This keeps track of whether local variables are free-ed when the function
333     /// exits even without a `StorageDead`, which appears to be the case for
334     /// constants.
335     ///
336     /// I'm not sure this is the right approach - @eddyb could you try and
337     /// figure this out?
338     locals_are_invalidated_at_exit: bool,
339     /// This field keeps track of when borrow errors are reported in the access_place function
340     /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
341     /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
342     /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
343     /// errors.
344     access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
345     /// This field keeps track of when borrow conflict errors are reported
346     /// for reservations, so that we don't report seemingly duplicate
347     /// errors for corresponding activations
348     ///
349     /// FIXME: Ideally this would be a set of BorrowIndex, not Places,
350     /// but it is currently inconvenient to track down the BorrowIndex
351     /// at the time we detect and report a reservation error.
352     reservation_error_reported: FxHashSet<Place<'tcx>>,
353     /// This field keeps track of errors reported in the checking of moved variables,
354     /// so that we don't report report seemingly duplicate errors.
355     moved_error_reported: FxHashSet<Place<'tcx>>,
356     /// This field keeps track of all the local variables that are declared mut and are mutated.
357     /// Used for the warning issued by an unused mutable local variable.
358     used_mut: FxHashSet<Local>,
359     /// If the function we're checking is a closure, then we'll need to report back the list of
360     /// mutable upvars that have been used. This field keeps track of them.
361     used_mut_upvars: SmallVec<[Field; 8]>,
362     /// Non-lexical region inference context, if NLL is enabled.  This
363     /// contains the results from region inference and lets us e.g.
364     /// find out which CFG points are contained in each borrow region.
365     nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
366     nonlexical_cause_info: Option<RegionCausalInfo>,
367
368     /// The set of borrows extracted from the MIR
369     borrow_set: Rc<BorrowSet<'tcx>>,
370
371     /// Dominators for MIR
372     dominators: Dominators<BasicBlock>,
373 }
374
375 // Check that:
376 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
377 // 2. loans made in overlapping scopes do not conflict
378 // 3. assignments do not affect things loaned out as immutable
379 // 4. moves do not affect things loaned out in any way
380 impl<'cx, 'gcx, 'tcx> DataflowResultsConsumer<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
381     type FlowState = Flows<'cx, 'gcx, 'tcx>;
382
383     fn mir(&self) -> &'cx Mir<'tcx> {
384         self.mir
385     }
386
387     fn visit_block_entry(&mut self, bb: BasicBlock, flow_state: &Self::FlowState) {
388         debug!("MirBorrowckCtxt::process_block({:?}): {}", bb, flow_state);
389     }
390
391     fn visit_statement_entry(
392         &mut self,
393         location: Location,
394         stmt: &Statement<'tcx>,
395         flow_state: &Self::FlowState,
396     ) {
397         debug!(
398             "MirBorrowckCtxt::process_statement({:?}, {:?}): {}",
399             location, stmt, flow_state
400         );
401         let span = stmt.source_info.span;
402
403         self.check_activations(location, span, flow_state);
404
405         match stmt.kind {
406             StatementKind::Assign(ref lhs, ref rhs) => {
407                 self.consume_rvalue(
408                     ContextKind::AssignRhs.new(location),
409                     (rhs, span),
410                     location,
411                     flow_state,
412                 );
413
414                 self.mutate_place(
415                     ContextKind::AssignLhs.new(location),
416                     (lhs, span),
417                     Shallow(None),
418                     JustWrite,
419                     flow_state,
420                 );
421             }
422             StatementKind::SetDiscriminant {
423                 ref place,
424                 variant_index: _,
425             } => {
426                 self.mutate_place(
427                     ContextKind::SetDiscrim.new(location),
428                     (place, span),
429                     Shallow(Some(ArtificialField::Discriminant)),
430                     JustWrite,
431                     flow_state,
432                 );
433             }
434             StatementKind::InlineAsm {
435                 ref asm,
436                 ref outputs,
437                 ref inputs,
438             } => {
439                 let context = ContextKind::InlineAsm.new(location);
440                 for (o, output) in asm.outputs.iter().zip(outputs) {
441                     if o.is_indirect {
442                         // FIXME(eddyb) indirect inline asm outputs should
443                         // be encoeded through MIR place derefs instead.
444                         self.access_place(
445                             context,
446                             (output, span),
447                             (Deep, Read(ReadKind::Copy)),
448                             LocalMutationIsAllowed::No,
449                             flow_state,
450                         );
451                         self.check_if_path_or_subpath_is_moved(
452                             context,
453                             InitializationRequiringAction::Use,
454                             (output, span),
455                             flow_state,
456                         );
457                     } else {
458                         self.mutate_place(
459                             context,
460                             (output, span),
461                             if o.is_rw { Deep } else { Shallow(None) },
462                             if o.is_rw { WriteAndRead } else { JustWrite },
463                             flow_state,
464                         );
465                     }
466                 }
467                 for input in inputs {
468                     self.consume_operand(context, (input, span), flow_state);
469                 }
470             }
471             StatementKind::EndRegion(ref _rgn) => {
472                 // ignored when consuming results (update to
473                 // flow_state already handled).
474             }
475             StatementKind::Nop |
476             StatementKind::UserAssertTy(..) |
477             StatementKind::Validate(..) |
478             StatementKind::StorageLive(..) => {
479                 // `Nop`, `UserAssertTy`, `Validate`, and `StorageLive` are irrelevant
480                 // to borrow check.
481             }
482             StatementKind::StorageDead(local) => {
483                 self.access_place(
484                     ContextKind::StorageDead.new(location),
485                     (&Place::Local(local), span),
486                     (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
487                     LocalMutationIsAllowed::Yes,
488                     flow_state,
489                 );
490             }
491         }
492     }
493
494     fn visit_terminator_entry(
495         &mut self,
496         location: Location,
497         term: &Terminator<'tcx>,
498         flow_state: &Self::FlowState,
499     ) {
500         let loc = location;
501         debug!(
502             "MirBorrowckCtxt::process_terminator({:?}, {:?}): {}",
503             location, term, flow_state
504         );
505         let span = term.source_info.span;
506
507         self.check_activations(location, span, flow_state);
508
509         match term.kind {
510             TerminatorKind::SwitchInt {
511                 ref discr,
512                 switch_ty: _,
513                 values: _,
514                 targets: _,
515             } => {
516                 self.consume_operand(ContextKind::SwitchInt.new(loc), (discr, span), flow_state);
517             }
518             TerminatorKind::Drop {
519                 location: ref drop_place,
520                 target: _,
521                 unwind: _,
522             } => {
523                 let gcx = self.tcx.global_tcx();
524
525                 // Compute the type with accurate region information.
526                 let drop_place_ty = drop_place.ty(self.mir, self.tcx);
527
528                 // Erase the regions.
529                 let drop_place_ty = self.tcx.erase_regions(&drop_place_ty).to_ty(self.tcx);
530
531                 // "Lift" into the gcx -- once regions are erased, this type should be in the
532                 // global arenas; this "lift" operation basically just asserts that is true, but
533                 // that is useful later.
534                 let drop_place_ty = gcx.lift(&drop_place_ty).unwrap();
535
536                 self.visit_terminator_drop(loc, term, flow_state, drop_place, drop_place_ty, span);
537             }
538             TerminatorKind::DropAndReplace {
539                 location: ref drop_place,
540                 value: ref new_value,
541                 target: _,
542                 unwind: _,
543             } => {
544                 self.mutate_place(
545                     ContextKind::DropAndReplace.new(loc),
546                     (drop_place, span),
547                     Deep,
548                     JustWrite,
549                     flow_state,
550                 );
551                 self.consume_operand(
552                     ContextKind::DropAndReplace.new(loc),
553                     (new_value, span),
554                     flow_state,
555                 );
556             }
557             TerminatorKind::Call {
558                 ref func,
559                 ref args,
560                 ref destination,
561                 cleanup: _,
562             } => {
563                 self.consume_operand(ContextKind::CallOperator.new(loc), (func, span), flow_state);
564                 for arg in args {
565                     self.consume_operand(
566                         ContextKind::CallOperand.new(loc),
567                         (arg, span),
568                         flow_state,
569                     );
570                 }
571                 if let Some((ref dest, _ /*bb*/)) = *destination {
572                     self.mutate_place(
573                         ContextKind::CallDest.new(loc),
574                         (dest, span),
575                         Deep,
576                         JustWrite,
577                         flow_state,
578                     );
579                 }
580             }
581             TerminatorKind::Assert {
582                 ref cond,
583                 expected: _,
584                 ref msg,
585                 target: _,
586                 cleanup: _,
587             } => {
588                 self.consume_operand(ContextKind::Assert.new(loc), (cond, span), flow_state);
589                 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
590                 if let BoundsCheck { ref len, ref index } = *msg {
591                     self.consume_operand(ContextKind::Assert.new(loc), (len, span), flow_state);
592                     self.consume_operand(
593                         ContextKind::Assert.new(loc),
594                         (index, span),
595                         flow_state,
596                     );
597                 }
598             }
599
600             TerminatorKind::Yield {
601                 ref value,
602                 resume: _,
603                 drop: _,
604             } => {
605                 self.consume_operand(ContextKind::Yield.new(loc), (value, span), flow_state);
606
607                 if self.movable_generator {
608                     // Look for any active borrows to locals
609                     let borrow_set = self.borrow_set.clone();
610                     flow_state.with_outgoing_borrows(|borrows| {
611                         for i in borrows {
612                             let borrow = &borrow_set[i];
613                             self.check_for_local_borrow(borrow, span);
614                         }
615                     });
616                 }
617             }
618
619             TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
620                 // Returning from the function implicitly kills storage for all locals and statics.
621                 // Often, the storage will already have been killed by an explicit
622                 // StorageDead, but we don't always emit those (notably on unwind paths),
623                 // so this "extra check" serves as a kind of backup.
624                 let borrow_set = self.borrow_set.clone();
625                 flow_state.with_outgoing_borrows(|borrows| {
626                     for i in borrows {
627                         let borrow = &borrow_set[i];
628                         let context = ContextKind::StorageDead.new(loc);
629                         self.check_for_invalidation_at_exit(context, borrow, span);
630                     }
631                 });
632             }
633             TerminatorKind::Goto { target: _ }
634             | TerminatorKind::Abort
635             | TerminatorKind::Unreachable
636             | TerminatorKind::FalseEdges {
637                 real_target: _,
638                 imaginary_targets: _,
639             }
640             | TerminatorKind::FalseUnwind {
641                 real_target: _,
642                 unwind: _,
643             } => {
644                 // no data used, thus irrelevant to borrowck
645             }
646         }
647     }
648 }
649
650 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
651 enum MutateMode {
652     JustWrite,
653     WriteAndRead,
654 }
655
656 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
657 enum Control {
658     Continue,
659     Break,
660 }
661
662 use self::ShallowOrDeep::{Deep, Shallow};
663 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
664
665 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
666 enum ArtificialField {
667     Discriminant,
668     ArrayLength,
669 }
670
671 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
672 enum ShallowOrDeep {
673     /// From the RFC: "A *shallow* access means that the immediate
674     /// fields reached at P are accessed, but references or pointers
675     /// found within are not dereferenced. Right now, the only access
676     /// that is shallow is an assignment like `x = ...;`, which would
677     /// be a *shallow write* of `x`."
678     Shallow(Option<ArtificialField>),
679
680     /// From the RFC: "A *deep* access means that all data reachable
681     /// through the given place may be invalidated or accesses by
682     /// this action."
683     Deep,
684 }
685
686 /// Kind of access to a value: read or write
687 /// (For informational purposes only)
688 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
689 enum ReadOrWrite {
690     /// From the RFC: "A *read* means that the existing data may be
691     /// read, but will not be changed."
692     Read(ReadKind),
693
694     /// From the RFC: "A *write* means that the data may be mutated to
695     /// new values or otherwise invalidated (for example, it could be
696     /// de-initialized, as in a move operation).
697     Write(WriteKind),
698
699     /// For two-phase borrows, we distinguish a reservation (which is treated
700     /// like a Read) from an activation (which is treated like a write), and
701     /// each of those is furthermore distinguished from Reads/Writes above.
702     Reservation(WriteKind),
703     Activation(WriteKind, BorrowIndex),
704 }
705
706 /// Kind of read access to a value
707 /// (For informational purposes only)
708 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
709 enum ReadKind {
710     Borrow(BorrowKind),
711     Copy,
712 }
713
714 /// Kind of write access to a value
715 /// (For informational purposes only)
716 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
717 enum WriteKind {
718     StorageDeadOrDrop,
719     MutableBorrow(BorrowKind),
720     Mutate,
721     Move,
722 }
723
724 /// When checking permissions for a place access, this flag is used to indicate that an immutable
725 /// local place can be mutated.
726 ///
727 /// FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
728 /// - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`
729 /// - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
730 ///   `is_declared_mutable()`
731 /// - Take flow state into consideration in `is_assignable()` for local variables
732 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
733 enum LocalMutationIsAllowed {
734     Yes,
735     /// We want use of immutable upvars to cause a "write to immutable upvar"
736     /// error, not an "reassignment" error.
737     ExceptUpvars,
738     No,
739 }
740
741 struct AccessErrorsReported {
742     mutability_error: bool,
743     #[allow(dead_code)]
744     conflict_error: bool,
745 }
746
747 #[derive(Copy, Clone)]
748 enum InitializationRequiringAction {
749     Update,
750     Borrow,
751     Use,
752     Assignment,
753 }
754
755 struct RootPlace<'d, 'tcx: 'd> {
756     place: &'d Place<'tcx>,
757     is_local_mutation_allowed: LocalMutationIsAllowed,
758 }
759
760 impl InitializationRequiringAction {
761     fn as_noun(self) -> &'static str {
762         match self {
763             InitializationRequiringAction::Update => "update",
764             InitializationRequiringAction::Borrow => "borrow",
765             InitializationRequiringAction::Use => "use",
766             InitializationRequiringAction::Assignment => "assign",
767         }
768     }
769
770     fn as_verb_in_past_tense(self) -> &'static str {
771         match self {
772             InitializationRequiringAction::Update => "updated",
773             InitializationRequiringAction::Borrow => "borrowed",
774             InitializationRequiringAction::Use => "used",
775             InitializationRequiringAction::Assignment => "assigned",
776         }
777     }
778 }
779
780 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
781     /// Returns true if the borrow represented by `kind` is
782     /// allowed to be split into separate Reservation and
783     /// Activation phases.
784     fn allow_two_phase_borrow(&self, kind: BorrowKind) -> bool {
785         self.tcx.two_phase_borrows()
786             && (kind.allows_two_phase_borrow()
787                 || self.tcx.sess.opts.debugging_opts.two_phase_beyond_autoref)
788     }
789
790     /// Invokes `access_place` as appropriate for dropping the value
791     /// at `drop_place`. Note that the *actual* `Drop` in the MIR is
792     /// always for a variable (e.g., `Drop(x)`) -- but we recursively
793     /// break this variable down into subpaths (e.g., `Drop(x.foo)`)
794     /// to indicate more precisely which fields might actually be
795     /// accessed by a destructor.
796     fn visit_terminator_drop(
797         &mut self,
798         loc: Location,
799         term: &Terminator<'tcx>,
800         flow_state: &Flows<'cx, 'gcx, 'tcx>,
801         drop_place: &Place<'tcx>,
802         erased_drop_place_ty: ty::Ty<'gcx>,
803         span: Span,
804     ) {
805         let gcx = self.tcx.global_tcx();
806         let drop_field = |
807             mir: &mut MirBorrowckCtxt<'cx, 'gcx, 'tcx>,
808             (index, field): (usize, ty::Ty<'gcx>),
809         | {
810             let field_ty = gcx.normalize_erasing_regions(mir.param_env, field);
811             let place = drop_place.clone().field(Field::new(index), field_ty);
812
813             mir.visit_terminator_drop(loc, term, flow_state, &place, field_ty, span);
814         };
815
816         match erased_drop_place_ty.sty {
817             // When a struct is being dropped, we need to check
818             // whether it has a destructor, if it does, then we can
819             // call it, if it does not then we need to check the
820             // individual fields instead. This way if `foo` has a
821             // destructor but `bar` does not, we will only check for
822             // borrows of `x.foo` and not `x.bar`. See #47703.
823             ty::TyAdt(def, substs) if def.is_struct() && !def.has_dtor(self.tcx) => {
824                 def.all_fields()
825                     .map(|field| field.ty(gcx, substs))
826                     .enumerate()
827                     .for_each(|field| drop_field(self, field));
828             }
829             // Same as above, but for tuples.
830             ty::TyTuple(tys) => {
831                 tys.iter().cloned().enumerate()
832                     .for_each(|field| drop_field(self, field));
833             }
834             // Closures and generators also have disjoint fields, but they are only
835             // directly accessed in the body of the closure/generator.
836             ty::TyClosure(def, substs)
837             | ty::TyGenerator(def, substs, ..)
838                 if *drop_place == Place::Local(Local::new(1)) && !self.mir.upvar_decls.is_empty()
839             => {
840                 substs.upvar_tys(def, self.tcx).enumerate()
841                     .for_each(|field| drop_field(self, field));
842             }
843             _ => {
844                 // We have now refined the type of the value being
845                 // dropped (potentially) to just the type of a
846                 // subfield; so check whether that field's type still
847                 // "needs drop". If so, we assume that the destructor
848                 // may access any data it likes (i.e., a Deep Write).
849                 if erased_drop_place_ty.needs_drop(gcx, self.param_env) {
850                     self.access_place(
851                         ContextKind::Drop.new(loc),
852                         (drop_place, span),
853                         (Deep, Write(WriteKind::StorageDeadOrDrop)),
854                         LocalMutationIsAllowed::Yes,
855                         flow_state,
856                     );
857                 }
858             }
859         }
860     }
861
862     /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
863     /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
864     /// place is initialized and (b) it is not borrowed in some way that would prevent this
865     /// access.
866     ///
867     /// Returns true if an error is reported, false otherwise.
868     fn access_place(
869         &mut self,
870         context: Context,
871         place_span: (&Place<'tcx>, Span),
872         kind: (ShallowOrDeep, ReadOrWrite),
873         is_local_mutation_allowed: LocalMutationIsAllowed,
874         flow_state: &Flows<'cx, 'gcx, 'tcx>,
875     ) -> AccessErrorsReported {
876         let (sd, rw) = kind;
877
878         if let Activation(_, borrow_index) = rw {
879             if self.reservation_error_reported.contains(&place_span.0) {
880                 debug!(
881                     "skipping access_place for activation of invalid reservation \
882                      place: {:?} borrow_index: {:?}",
883                     place_span.0, borrow_index
884                 );
885                 return AccessErrorsReported {
886                     mutability_error: false,
887                     conflict_error: true,
888                 };
889             }
890         }
891
892         if self.access_place_error_reported
893             .contains(&(place_span.0.clone(), place_span.1))
894         {
895             debug!(
896                 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
897                 place_span, kind
898             );
899             return AccessErrorsReported {
900                 mutability_error: false,
901                 conflict_error: true,
902             };
903         }
904
905         let mutability_error =
906             self.check_access_permissions(place_span, rw, is_local_mutation_allowed, flow_state);
907         let conflict_error =
908             self.check_access_for_conflict(context, place_span, sd, rw, flow_state);
909
910         if conflict_error || mutability_error {
911             debug!(
912                 "access_place: logging error place_span=`{:?}` kind=`{:?}`",
913                 place_span, kind
914             );
915             self.access_place_error_reported
916                 .insert((place_span.0.clone(), place_span.1));
917         }
918
919         AccessErrorsReported {
920             mutability_error,
921             conflict_error,
922         }
923     }
924
925     fn check_access_for_conflict(
926         &mut self,
927         context: Context,
928         place_span: (&Place<'tcx>, Span),
929         sd: ShallowOrDeep,
930         rw: ReadOrWrite,
931         flow_state: &Flows<'cx, 'gcx, 'tcx>,
932     ) -> bool {
933         debug!(
934             "check_access_for_conflict(context={:?}, place_span={:?}, sd={:?}, rw={:?})",
935             context,
936             place_span,
937             sd,
938             rw,
939         );
940
941         let mut error_reported = false;
942         self.each_borrow_involving_path(
943             context,
944             (sd, place_span.0),
945             flow_state,
946             |this, borrow_index, borrow| match (rw, borrow.kind) {
947                 // Obviously an activation is compatible with its own
948                 // reservation (or even prior activating uses of same
949                 // borrow); so don't check if they interfere.
950                 //
951                 // NOTE: *reservations* do conflict with themselves;
952                 // thus aren't injecting unsoundenss w/ this check.)
953                 (Activation(_, activating), _) if activating == borrow_index => {
954                     debug!(
955                         "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
956                          skipping {:?} b/c activation of same borrow_index",
957                         place_span,
958                         sd,
959                         rw,
960                         (borrow_index, borrow),
961                     );
962                     Control::Continue
963                 }
964
965                 (Read(_), BorrowKind::Shared) | (Reservation(..), BorrowKind::Shared) => {
966                     Control::Continue
967                 }
968
969                 (Read(kind), BorrowKind::Unique) | (Read(kind), BorrowKind::Mut { .. }) => {
970                     // Reading from mere reservations of mutable-borrows is OK.
971                     if !this.is_active(borrow, context.loc) {
972                         assert!(this.allow_two_phase_borrow(borrow.kind));
973                         return Control::Continue;
974                     }
975
976                     match kind {
977                         ReadKind::Copy => {
978                             error_reported = true;
979                             this.report_use_while_mutably_borrowed(context, place_span, borrow)
980                         }
981                         ReadKind::Borrow(bk) => {
982                             error_reported = true;
983                             this.report_conflicting_borrow(
984                                 context,
985                                 place_span,
986                                 bk,
987                                 &borrow,
988                             )
989                         }
990                     }
991                     Control::Break
992                 }
993
994                 (Reservation(kind), BorrowKind::Unique)
995                 | (Reservation(kind), BorrowKind::Mut { .. })
996                 | (Activation(kind, _), _)
997                 | (Write(kind), _) => {
998                     match rw {
999                         Reservation(_) => {
1000                             debug!(
1001                                 "recording invalid reservation of \
1002                                  place: {:?}",
1003                                 place_span.0
1004                             );
1005                             this.reservation_error_reported.insert(place_span.0.clone());
1006                         }
1007                         Activation(_, activating) => {
1008                             debug!(
1009                                 "observing check_place for activation of \
1010                                  borrow_index: {:?}",
1011                                 activating
1012                             );
1013                         }
1014                         Read(..) | Write(..) => {}
1015                     }
1016
1017                     match kind {
1018                         WriteKind::MutableBorrow(bk) => {
1019                             error_reported = true;
1020                             this.report_conflicting_borrow(
1021                                 context,
1022                                 place_span,
1023                                 bk,
1024                                 &borrow,
1025                             )
1026                         }
1027                         WriteKind::StorageDeadOrDrop => {
1028                             error_reported = true;
1029                             this.report_borrowed_value_does_not_live_long_enough(
1030                                 context,
1031                                 borrow,
1032                                 place_span.1,
1033                             );
1034                         }
1035                         WriteKind::Mutate => {
1036                             error_reported = true;
1037                             this.report_illegal_mutation_of_borrowed(context, place_span, borrow)
1038                         }
1039                         WriteKind::Move => {
1040                             error_reported = true;
1041                             this.report_move_out_while_borrowed(context, place_span, &borrow)
1042                         }
1043                     }
1044                     Control::Break
1045                 }
1046             },
1047         );
1048
1049         error_reported
1050     }
1051
1052     fn mutate_place(
1053         &mut self,
1054         context: Context,
1055         place_span: (&Place<'tcx>, Span),
1056         kind: ShallowOrDeep,
1057         mode: MutateMode,
1058         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1059     ) {
1060         // Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
1061         match mode {
1062             MutateMode::WriteAndRead => {
1063                 self.check_if_path_or_subpath_is_moved(
1064                     context,
1065                     InitializationRequiringAction::Update,
1066                     place_span,
1067                     flow_state,
1068                 );
1069             }
1070             MutateMode::JustWrite => {
1071                 self.check_if_assigned_path_is_moved(context, place_span, flow_state);
1072             }
1073         }
1074
1075         let errors_reported = self.access_place(
1076             context,
1077             place_span,
1078             (kind, Write(WriteKind::Mutate)),
1079             // We want immutable upvars to cause an "assignment to immutable var"
1080             // error, not an "reassignment of immutable var" error, because the
1081             // latter can't find a good previous assignment span.
1082             //
1083             // There's probably a better way to do this.
1084             LocalMutationIsAllowed::ExceptUpvars,
1085             flow_state,
1086         );
1087
1088         if !errors_reported.mutability_error {
1089             // check for reassignments to immutable local variables
1090             self.check_if_reassignment_to_immutable_state(context, place_span, flow_state);
1091         }
1092     }
1093
1094     fn consume_rvalue(
1095         &mut self,
1096         context: Context,
1097         (rvalue, span): (&Rvalue<'tcx>, Span),
1098         _location: Location,
1099         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1100     ) {
1101         match *rvalue {
1102             Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
1103                 let access_kind = match bk {
1104                     BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1105                     BorrowKind::Unique | BorrowKind::Mut { .. } => {
1106                         let wk = WriteKind::MutableBorrow(bk);
1107                         if self.allow_two_phase_borrow(bk) {
1108                             (Deep, Reservation(wk))
1109                         } else {
1110                             (Deep, Write(wk))
1111                         }
1112                     }
1113                 };
1114
1115                 self.access_place(
1116                     context,
1117                     (place, span),
1118                     access_kind,
1119                     LocalMutationIsAllowed::No,
1120                     flow_state,
1121                 );
1122
1123                 self.check_if_path_or_subpath_is_moved(
1124                     context,
1125                     InitializationRequiringAction::Borrow,
1126                     (place, span),
1127                     flow_state,
1128                 );
1129             }
1130
1131             Rvalue::Use(ref operand)
1132             | Rvalue::Repeat(ref operand, _)
1133             | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1134             | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
1135                 self.consume_operand(context, (operand, span), flow_state)
1136             }
1137
1138             Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
1139                 let af = match *rvalue {
1140                     Rvalue::Len(..) => ArtificialField::ArrayLength,
1141                     Rvalue::Discriminant(..) => ArtificialField::Discriminant,
1142                     _ => unreachable!(),
1143                 };
1144                 self.access_place(
1145                     context,
1146                     (place, span),
1147                     (Shallow(Some(af)), Read(ReadKind::Copy)),
1148                     LocalMutationIsAllowed::No,
1149                     flow_state,
1150                 );
1151                 self.check_if_path_or_subpath_is_moved(
1152                     context,
1153                     InitializationRequiringAction::Use,
1154                     (place, span),
1155                     flow_state,
1156                 );
1157             }
1158
1159             Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
1160             | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
1161                 self.consume_operand(context, (operand1, span), flow_state);
1162                 self.consume_operand(context, (operand2, span), flow_state);
1163             }
1164
1165             Rvalue::NullaryOp(_op, _ty) => {
1166                 // nullary ops take no dynamic input; no borrowck effect.
1167                 //
1168                 // FIXME: is above actually true? Do we want to track
1169                 // the fact that uninitialized data can be created via
1170                 // `NullOp::Box`?
1171             }
1172
1173             Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1174                 // We need to report back the list of mutable upvars that were
1175                 // moved into the closure and subsequently used by the closure,
1176                 // in order to populate our used_mut set.
1177                 if let AggregateKind::Closure(def_id, _) = &**aggregate_kind {
1178                     let BorrowCheckResult { used_mut_upvars, .. } = self.tcx.mir_borrowck(*def_id);
1179                     debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1180                     for field in used_mut_upvars {
1181                         match operands[field.index()] {
1182                             Operand::Move(Place::Local(local)) => {
1183                                 self.used_mut.insert(local);
1184                             }
1185                             Operand::Move(ref place @ Place::Projection(_)) => {
1186                                 if let Some(field) = self.is_upvar_field_projection(place) {
1187                                     self.used_mut_upvars.push(field);
1188                                 }
1189                             }
1190                             Operand::Move(Place::Static(..)) |
1191                             Operand::Copy(..) |
1192                             Operand::Constant(..) => {}
1193                         }
1194                     }
1195                 }
1196
1197                 for operand in operands {
1198                     self.consume_operand(context, (operand, span), flow_state);
1199                 }
1200             }
1201         }
1202     }
1203
1204     fn consume_operand(
1205         &mut self,
1206         context: Context,
1207         (operand, span): (&Operand<'tcx>, Span),
1208         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1209     ) {
1210         match *operand {
1211             Operand::Copy(ref place) => {
1212                 // copy of place: check if this is "copy of frozen path"
1213                 // (FIXME: see check_loans.rs)
1214                 self.access_place(
1215                     context,
1216                     (place, span),
1217                     (Deep, Read(ReadKind::Copy)),
1218                     LocalMutationIsAllowed::No,
1219                     flow_state,
1220                 );
1221
1222                 // Finally, check if path was already moved.
1223                 self.check_if_path_or_subpath_is_moved(
1224                     context,
1225                     InitializationRequiringAction::Use,
1226                     (place, span),
1227                     flow_state,
1228                 );
1229             }
1230             Operand::Move(ref place) => {
1231                 // move of place: check if this is move of already borrowed path
1232                 self.access_place(
1233                     context,
1234                     (place, span),
1235                     (Deep, Write(WriteKind::Move)),
1236                     LocalMutationIsAllowed::Yes,
1237                     flow_state,
1238                 );
1239
1240                 // Finally, check if path was already moved.
1241                 self.check_if_path_or_subpath_is_moved(
1242                     context,
1243                     InitializationRequiringAction::Use,
1244                     (place, span),
1245                     flow_state,
1246                 );
1247             }
1248             Operand::Constant(_) => {}
1249         }
1250     }
1251
1252     /// Returns whether a borrow of this place is invalidated when the function
1253     /// exits
1254     fn check_for_invalidation_at_exit(
1255         &mut self,
1256         context: Context,
1257         borrow: &BorrowData<'tcx>,
1258         span: Span,
1259     ) {
1260         debug!("check_for_invalidation_at_exit({:?})", borrow);
1261         let place = &borrow.borrowed_place;
1262         let root_place = self.prefixes(place, PrefixSet::All).last().unwrap();
1263
1264         // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1265         // we just know that all locals are dropped at function exit (otherwise
1266         // we'll have a memory leak) and assume that all statics have a destructor.
1267         //
1268         // FIXME: allow thread-locals to borrow other thread locals?
1269         let (might_be_alive, will_be_dropped) = match root_place {
1270             Place::Static(statik) => {
1271                 // Thread-locals might be dropped after the function exits, but
1272                 // "true" statics will never be.
1273                 let is_thread_local = self.tcx
1274                     .get_attrs(statik.def_id)
1275                     .iter()
1276                     .any(|attr| attr.check_name("thread_local"));
1277
1278                 (true, is_thread_local)
1279             }
1280             Place::Local(_) => {
1281                 // Locals are always dropped at function exit, and if they
1282                 // have a destructor it would've been called already.
1283                 (false, self.locals_are_invalidated_at_exit)
1284             }
1285             Place::Projection(..) => {
1286                 bug!("root of {:?} is a projection ({:?})?", place, root_place)
1287             }
1288         };
1289
1290         if !will_be_dropped {
1291             debug!(
1292                 "place_is_invalidated_at_exit({:?}) - won't be dropped",
1293                 place
1294             );
1295             return;
1296         }
1297
1298         // FIXME: replace this with a proper borrow_conflicts_with_place when
1299         // that is merged.
1300         let sd = if might_be_alive { Deep } else { Shallow(None) };
1301
1302         if self.places_conflict(place, root_place, sd) {
1303             debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1304             // FIXME: should be talking about the region lifetime instead
1305             // of just a span here.
1306             let span = self.tcx.sess.codemap().end_point(span);
1307             self.report_borrowed_value_does_not_live_long_enough(
1308                 context,
1309                 borrow,
1310                 span,
1311             )
1312         }
1313     }
1314
1315     /// Reports an error if this is a borrow of local data.
1316     /// This is called for all Yield statements on movable generators
1317     fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1318         fn borrow_of_local_data<'tcx>(place: &Place<'tcx>) -> bool {
1319             match place {
1320                 Place::Static(..) => false,
1321                 Place::Local(..) => true,
1322                 Place::Projection(box proj) => {
1323                     match proj.elem {
1324                         // Reborrow of already borrowed data is ignored
1325                         // Any errors will be caught on the initial borrow
1326                         ProjectionElem::Deref => false,
1327
1328                         // For interior references and downcasts, find out if the base is local
1329                         ProjectionElem::Field(..)
1330                         | ProjectionElem::Index(..)
1331                         | ProjectionElem::ConstantIndex { .. }
1332                         | ProjectionElem::Subslice { .. }
1333                         | ProjectionElem::Downcast(..) => borrow_of_local_data(&proj.base),
1334                     }
1335                 }
1336             }
1337         }
1338
1339         debug!("check_for_local_borrow({:?})", borrow);
1340
1341         if borrow_of_local_data(&borrow.borrowed_place) {
1342             self.tcx
1343                 .cannot_borrow_across_generator_yield(
1344                     self.retrieve_borrow_span(borrow),
1345                     yield_span,
1346                     Origin::Mir,
1347                 )
1348                 .emit();
1349         }
1350     }
1351
1352     fn check_activations(
1353         &mut self,
1354         location: Location,
1355         span: Span,
1356         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1357     ) {
1358         if !self.tcx.two_phase_borrows() {
1359             return;
1360         }
1361
1362         // Two-phase borrow support: For each activation that is newly
1363         // generated at this statement, check if it interferes with
1364         // another borrow.
1365         let borrow_set = self.borrow_set.clone();
1366         for &borrow_index in borrow_set.activations_at_location(location) {
1367             let borrow = &borrow_set[borrow_index];
1368
1369             // only mutable borrows should be 2-phase
1370             assert!(match borrow.kind {
1371                 BorrowKind::Shared => false,
1372                 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1373             });
1374
1375             self.access_place(
1376                 ContextKind::Activation.new(location),
1377                 (&borrow.borrowed_place, span),
1378                 (
1379                     Deep,
1380                     Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index),
1381                 ),
1382                 LocalMutationIsAllowed::No,
1383                 flow_state,
1384             );
1385             // We do not need to call `check_if_path_or_subpath_is_moved`
1386             // again, as we already called it when we made the
1387             // initial reservation.
1388         }
1389     }
1390 }
1391
1392 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
1393     fn check_if_reassignment_to_immutable_state(
1394         &mut self,
1395         context: Context,
1396         (place, span): (&Place<'tcx>, Span),
1397         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1398     ) {
1399         debug!("check_if_reassignment_to_immutable_state({:?})", place);
1400         // determine if this path has a non-mut owner (and thus needs checking).
1401         if let Ok(..) = self.is_mutable(place, LocalMutationIsAllowed::No) {
1402             return;
1403         }
1404         debug!(
1405             "check_if_reassignment_to_immutable_state({:?}) - is an imm local",
1406             place
1407         );
1408
1409         for i in flow_state.ever_inits.iter_incoming() {
1410             let init = self.move_data.inits[i];
1411             let init_place = &self.move_data.move_paths[init.path].place;
1412             if self.places_conflict(&init_place, place, Deep) {
1413                 self.report_illegal_reassignment(context, (place, span), init.span);
1414                 break;
1415             }
1416         }
1417     }
1418
1419     fn check_if_full_path_is_moved(
1420         &mut self,
1421         context: Context,
1422         desired_action: InitializationRequiringAction,
1423         place_span: (&Place<'tcx>, Span),
1424         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1425     ) {
1426         // FIXME: analogous code in check_loans first maps `place` to
1427         // its base_path ... but is that what we want here?
1428         let place = self.base_path(place_span.0);
1429
1430         let maybe_uninits = &flow_state.uninits;
1431         let curr_move_outs = &flow_state.move_outs;
1432
1433         // Bad scenarios:
1434         //
1435         // 1. Move of `a.b.c`, use of `a.b.c`
1436         // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1437         // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1438         //    partial initialization support, one might have `a.x`
1439         //    initialized but not `a.b`.
1440         //
1441         // OK scenarios:
1442         //
1443         // 4. Move of `a.b.c`, use of `a.b.d`
1444         // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1445         // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1446         //    must have been initialized for the use to be sound.
1447         // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1448
1449         // The dataflow tracks shallow prefixes distinctly (that is,
1450         // field-accesses on P distinctly from P itself), in order to
1451         // track substructure initialization separately from the whole
1452         // structure.
1453         //
1454         // E.g., when looking at (*a.b.c).d, if the closest prefix for
1455         // which we have a MovePath is `a.b`, then that means that the
1456         // initialization state of `a.b` is all we need to inspect to
1457         // know if `a.b.c` is valid (and from that we infer that the
1458         // dereference and `.d` access is also valid, since we assume
1459         // `a.b.c` is assigned a reference to a initialized and
1460         // well-formed record structure.)
1461
1462         // Therefore, if we seek out the *closest* prefix for which we
1463         // have a MovePath, that should capture the initialization
1464         // state for the place scenario.
1465         //
1466         // This code covers scenarios 1, 2, and 3.
1467
1468         debug!("check_if_full_path_is_moved place: {:?}", place);
1469         match self.move_path_closest_to(place) {
1470             Ok(mpi) => {
1471                 if maybe_uninits.contains(&mpi) {
1472                     self.report_use_of_moved_or_uninitialized(
1473                         context,
1474                         desired_action,
1475                         place_span,
1476                         mpi,
1477                         curr_move_outs,
1478                     );
1479                     return; // don't bother finding other problems.
1480                 }
1481             }
1482             Err(NoMovePathFound::ReachedStatic) => {
1483                 // Okay: we do not build MoveData for static variables
1484             } // Only query longest prefix with a MovePath, not further
1485               // ancestors; dataflow recurs on children when parents
1486               // move (to support partial (re)inits).
1487               //
1488               // (I.e. querying parents breaks scenario 7; but may want
1489               // to do such a query based on partial-init feature-gate.)
1490         }
1491     }
1492
1493     fn check_if_path_or_subpath_is_moved(
1494         &mut self,
1495         context: Context,
1496         desired_action: InitializationRequiringAction,
1497         place_span: (&Place<'tcx>, Span),
1498         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1499     ) {
1500         // FIXME: analogous code in check_loans first maps `place` to
1501         // its base_path ... but is that what we want here?
1502         let place = self.base_path(place_span.0);
1503
1504         let maybe_uninits = &flow_state.uninits;
1505         let curr_move_outs = &flow_state.move_outs;
1506
1507         // Bad scenarios:
1508         //
1509         // 1. Move of `a.b.c`, use of `a` or `a.b`
1510         //    partial initialization support, one might have `a.x`
1511         //    initialized but not `a.b`.
1512         // 2. All bad scenarios from `check_if_full_path_is_moved`
1513         //
1514         // OK scenarios:
1515         //
1516         // 3. Move of `a.b.c`, use of `a.b.d`
1517         // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1518         // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1519         //    must have been initialized for the use to be sound.
1520         // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1521
1522         self.check_if_full_path_is_moved(context, desired_action, place_span, flow_state);
1523
1524         // A move of any shallow suffix of `place` also interferes
1525         // with an attempt to use `place`. This is scenario 3 above.
1526         //
1527         // (Distinct from handling of scenarios 1+2+4 above because
1528         // `place` does not interfere with suffixes of its prefixes,
1529         // e.g. `a.b.c` does not interfere with `a.b.d`)
1530         //
1531         // This code covers scenario 1.
1532
1533         debug!("check_if_path_or_subpath_is_moved place: {:?}", place);
1534         if let Some(mpi) = self.move_path_for_place(place) {
1535             if let Some(child_mpi) = maybe_uninits.has_any_child_of(mpi) {
1536                 self.report_use_of_moved_or_uninitialized(
1537                     context,
1538                     desired_action,
1539                     place_span,
1540                     child_mpi,
1541                     curr_move_outs,
1542                 );
1543                 return; // don't bother finding other problems.
1544             }
1545         }
1546     }
1547
1548     /// Currently MoveData does not store entries for all places in
1549     /// the input MIR. For example it will currently filter out
1550     /// places that are Copy; thus we do not track places of shared
1551     /// reference type. This routine will walk up a place along its
1552     /// prefixes, searching for a foundational place that *is*
1553     /// tracked in the MoveData.
1554     ///
1555     /// An Err result includes a tag indicated why the search failed.
1556     /// Currently this can only occur if the place is built off of a
1557     /// static variable, as we do not track those in the MoveData.
1558     fn move_path_closest_to(
1559         &mut self,
1560         place: &Place<'tcx>,
1561     ) -> Result<MovePathIndex, NoMovePathFound> {
1562         let mut last_prefix = place;
1563         for prefix in self.prefixes(place, PrefixSet::All) {
1564             if let Some(mpi) = self.move_path_for_place(prefix) {
1565                 return Ok(mpi);
1566             }
1567             last_prefix = prefix;
1568         }
1569         match *last_prefix {
1570             Place::Local(_) => panic!("should have move path for every Local"),
1571             Place::Projection(_) => panic!("PrefixSet::All meant don't stop for Projection"),
1572             Place::Static(_) => return Err(NoMovePathFound::ReachedStatic),
1573         }
1574     }
1575
1576     fn move_path_for_place(&mut self, place: &Place<'tcx>) -> Option<MovePathIndex> {
1577         // If returns None, then there is no move path corresponding
1578         // to a direct owner of `place` (which means there is nothing
1579         // that borrowck tracks for its analysis).
1580
1581         match self.move_data.rev_lookup.find(place) {
1582             LookupResult::Parent(_) => None,
1583             LookupResult::Exact(mpi) => Some(mpi),
1584         }
1585     }
1586
1587     fn check_if_assigned_path_is_moved(
1588         &mut self,
1589         context: Context,
1590         (place, span): (&Place<'tcx>, Span),
1591         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1592     ) {
1593         debug!("check_if_assigned_path_is_moved place: {:?}", place);
1594         // recur down place; dispatch to external checks when necessary
1595         let mut place = place;
1596         loop {
1597             match *place {
1598                 Place::Local(_) | Place::Static(_) => {
1599                     // assigning to `x` does not require `x` be initialized.
1600                     break;
1601                 }
1602                 Place::Projection(ref proj) => {
1603                     let Projection { ref base, ref elem } = **proj;
1604                     match *elem {
1605                         ProjectionElem::Index(_/*operand*/) |
1606                         ProjectionElem::ConstantIndex { .. } |
1607                         // assigning to P[i] requires P to be valid.
1608                         ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1609                         // assigning to (P->variant) is okay if assigning to `P` is okay
1610                         //
1611                         // FIXME: is this true even if P is a adt with a dtor?
1612                         { }
1613
1614                         // assigning to (*P) requires P to be initialized
1615                         ProjectionElem::Deref => {
1616                             self.check_if_full_path_is_moved(
1617                                 context, InitializationRequiringAction::Use,
1618                                 (base, span), flow_state);
1619                             // (base initialized; no need to
1620                             // recur further)
1621                             break;
1622                         }
1623
1624                         ProjectionElem::Subslice { .. } => {
1625                             panic!("we don't allow assignments to subslices, context: {:?}",
1626                                    context);
1627                         }
1628
1629                         ProjectionElem::Field(..) => {
1630                             // if type of `P` has a dtor, then
1631                             // assigning to `P.f` requires `P` itself
1632                             // be already initialized
1633                             let tcx = self.tcx;
1634                             match base.ty(self.mir, tcx).to_ty(tcx).sty {
1635                                 ty::TyAdt(def, _) if def.has_dtor(tcx) => {
1636
1637                                     // FIXME: analogous code in
1638                                     // check_loans.rs first maps
1639                                     // `base` to its base_path.
1640
1641                                     self.check_if_path_or_subpath_is_moved(
1642                                         context, InitializationRequiringAction::Assignment,
1643                                         (base, span), flow_state);
1644
1645                                     // (base initialized; no need to
1646                                     // recur further)
1647                                     break;
1648                                 }
1649                                 _ => {}
1650                             }
1651                         }
1652                     }
1653
1654                     place = base;
1655                     continue;
1656                 }
1657             }
1658         }
1659     }
1660
1661     fn specialized_description(&self, place:&Place<'tcx>) -> Option<String>{
1662         if let Some(_name) = self.describe_place(place) {
1663             Some(format!("data in a `&` reference"))
1664         } else {
1665             None
1666         }
1667     }
1668
1669     fn get_default_err_msg(&self, place:&Place<'tcx>) -> String{
1670         match self.describe_place(place) {
1671             Some(name) => format!("immutable item `{}`", name),
1672             None => "immutable item".to_owned(),
1673         }
1674     }
1675
1676     fn get_secondary_err_msg(&self, place:&Place<'tcx>) -> String{
1677         match self.specialized_description(place) {
1678             Some(_) => format!("data in a `&` reference"),
1679             None => self.get_default_err_msg(place)
1680         }
1681     }
1682
1683     fn get_primary_err_msg(&self, place:&Place<'tcx>) -> String{
1684         if let Some(name) = self.describe_place(place) {
1685             format!("`{}` is a `&` reference, so the data it refers to cannot be written", name)
1686         } else {
1687             format!("cannot assign through `&`-reference")
1688         }
1689     }
1690
1691     /// Check the permissions for the given place and read or write kind
1692     ///
1693     /// Returns true if an error is reported, false otherwise.
1694     fn check_access_permissions(
1695         &mut self,
1696         (place, span): (&Place<'tcx>, Span),
1697         kind: ReadOrWrite,
1698         is_local_mutation_allowed: LocalMutationIsAllowed,
1699         flow_state: &Flows<'cx, 'gcx, 'tcx>,
1700     ) -> bool {
1701         debug!(
1702             "check_access_permissions({:?}, {:?}, {:?})",
1703             place, kind, is_local_mutation_allowed
1704         );
1705         let mut error_reported = false;
1706         match kind {
1707             Reservation(WriteKind::MutableBorrow(BorrowKind::Unique))
1708             | Write(WriteKind::MutableBorrow(BorrowKind::Unique)) => {
1709                 if let Err(_place_err) = self.is_mutable(place, LocalMutationIsAllowed::Yes) {
1710                     span_bug!(span, "&unique borrow for {:?} should not fail", place);
1711                 }
1712             }
1713             Reservation(WriteKind::MutableBorrow(BorrowKind::Mut { .. }))
1714             | Write(WriteKind::MutableBorrow(BorrowKind::Mut { .. })) => {
1715                 match self.is_mutable(place, is_local_mutation_allowed) {
1716                     Ok(root_place) => self.add_used_mut(root_place, flow_state),
1717                     Err(place_err) => {
1718                         error_reported = true;
1719                         let item_msg = self.get_default_err_msg(place);
1720                         let mut err = self.tcx
1721                             .cannot_borrow_path_as_mutable(span, &item_msg, Origin::Mir);
1722                         err.span_label(span, "cannot borrow as mutable");
1723
1724                         if place != place_err {
1725                             if let Some(name) = self.describe_place(place_err) {
1726                                 err.note(&format!("the value which is causing this path not to be \
1727                                     mutable is...: `{}`", name));
1728                             }
1729                         }
1730
1731                         err.emit();
1732                     }
1733                 }
1734             }
1735             Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1736                 match self.is_mutable(place, is_local_mutation_allowed) {
1737                     Ok(root_place) => self.add_used_mut(root_place, flow_state),
1738                     Err(place_err) => {
1739                         error_reported = true;
1740
1741                         let err_info = if let Place::Projection(
1742                             box Projection {
1743                                 base: Place::Local(local),
1744                                 elem: ProjectionElem::Deref
1745                             }
1746                         ) = *place_err {
1747                             let locations = self.mir.find_assignments(local);
1748                             if locations.len() > 0 {
1749                                 let item_msg = if error_reported {
1750                                     self.get_secondary_err_msg(&Place::Local(local))
1751                                 } else {
1752                                     self.get_default_err_msg(place)
1753                                 };
1754                                 let sp = self.mir.source_info(locations[0]).span;
1755                                 let mut to_suggest_span = String::new();
1756                                 if let Ok(src) =
1757                                     self.tcx.sess.codemap().span_to_snippet(sp) {
1758                                         to_suggest_span = src[1..].to_string();
1759                                 };
1760                                 Some((sp,
1761                                       "consider changing this to be a \
1762                                       mutable reference",
1763                                       to_suggest_span,
1764                                       item_msg,
1765                                       self.get_primary_err_msg(&Place::Local(local))))
1766                             } else {
1767                                 None
1768                             }
1769                         } else {
1770                             None
1771                         };
1772
1773                         if let Some((err_help_span,
1774                                      err_help_stmt,
1775                                      to_suggest_span,
1776                                      item_msg,
1777                                      sec_span)) = err_info {
1778                             let mut err = self.tcx.cannot_assign(span, &item_msg, Origin::Mir);
1779                             err.span_suggestion(err_help_span,
1780                                                 err_help_stmt,
1781                                                 format!("&mut {}", to_suggest_span));
1782                             if place != place_err {
1783                                 err.span_label(span, sec_span);
1784                             }
1785                             err.emit()
1786                         } else {
1787                             let item_msg = self.get_default_err_msg(place);
1788                             let mut err = self.tcx.cannot_assign(span, &item_msg, Origin::Mir);
1789                             err.span_label(span, "cannot mutate");
1790                             if place != place_err {
1791                                 if let Some(name) = self.describe_place(place_err) {
1792                                     err.note(&format!("the value which is causing this path not \
1793                                                        to be mutable is...: `{}`", name));
1794                                 }
1795                             }
1796                             err.emit();
1797                         }
1798                     }
1799                 }
1800             }
1801             Reservation(WriteKind::Move)
1802             | Reservation(WriteKind::StorageDeadOrDrop)
1803             | Reservation(WriteKind::MutableBorrow(BorrowKind::Shared))
1804             | Write(WriteKind::Move)
1805             | Write(WriteKind::StorageDeadOrDrop)
1806             | Write(WriteKind::MutableBorrow(BorrowKind::Shared)) => {
1807                 if let Err(_place_err) = self.is_mutable(place, is_local_mutation_allowed) {
1808                     self.tcx.sess.delay_span_bug(
1809                         span,
1810                         &format!(
1811                             "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
1812                             place, kind
1813                         ),
1814                     );
1815                 }
1816             }
1817             Activation(..) => {} // permission checks are done at Reservation point.
1818             Read(ReadKind::Borrow(BorrowKind::Unique))
1819             | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
1820             | Read(ReadKind::Borrow(BorrowKind::Shared))
1821             | Read(ReadKind::Copy) => {} // Access authorized
1822         }
1823
1824         error_reported
1825     }
1826
1827     /// Adds the place into the used mutable variables set
1828     fn add_used_mut<'d>(
1829         &mut self,
1830         root_place: RootPlace<'d, 'tcx>,
1831         flow_state: &Flows<'cx, 'gcx, 'tcx>
1832     ) {
1833         match root_place {
1834             RootPlace {
1835                 place: Place::Local(local),
1836                 is_local_mutation_allowed,
1837             } => {
1838                 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes {
1839                     // If the local may be initialized, and it is now currently being
1840                     // mutated, then it is justified to be annotated with the `mut`
1841                     // keyword, since the mutation may be a possible reassignment.
1842                     let mpi = self.move_data.rev_lookup.find_local(*local);
1843                     if flow_state.inits.contains(&mpi) {
1844                         self.used_mut.insert(*local);
1845                     }
1846                 }
1847             }
1848             RootPlace {
1849                 place: place @ Place::Projection(_),
1850                 is_local_mutation_allowed: _,
1851             } => {
1852                 if let Some(field) = self.is_upvar_field_projection(&place) {
1853                     self.used_mut_upvars.push(field);
1854                 }
1855             }
1856             RootPlace {
1857                 place: Place::Static(..),
1858                 is_local_mutation_allowed: _,
1859             } => {}
1860         }
1861     }
1862
1863     /// Whether this value be written or borrowed mutably.
1864     /// Returns the root place if the place passed in is a projection.
1865     fn is_mutable<'d>(
1866         &self,
1867         place: &'d Place<'tcx>,
1868         is_local_mutation_allowed: LocalMutationIsAllowed,
1869     ) -> Result<RootPlace<'d, 'tcx>, &'d Place<'tcx>> {
1870         match *place {
1871             Place::Local(local) => {
1872                 let local = &self.mir.local_decls[local];
1873                 match local.mutability {
1874                     Mutability::Not => match is_local_mutation_allowed {
1875                         LocalMutationIsAllowed::Yes => {
1876                             Ok(RootPlace {
1877                                 place,
1878                                 is_local_mutation_allowed: LocalMutationIsAllowed::Yes
1879                             })
1880                         }
1881                         LocalMutationIsAllowed::ExceptUpvars => {
1882                             Ok(RootPlace {
1883                                 place,
1884                                 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars
1885                             })
1886                         }
1887                         LocalMutationIsAllowed::No => Err(place),
1888                     },
1889                     Mutability::Mut => Ok(RootPlace { place, is_local_mutation_allowed }),
1890                 }
1891             }
1892             Place::Static(ref static_) =>
1893                 if self.tcx.is_static(static_.def_id) != Some(hir::Mutability::MutMutable) {
1894                     Err(place)
1895                 } else {
1896                     Ok(RootPlace { place, is_local_mutation_allowed })
1897                 },
1898             Place::Projection(ref proj) => {
1899                 match proj.elem {
1900                     ProjectionElem::Deref => {
1901                         let base_ty = proj.base.ty(self.mir, self.tcx).to_ty(self.tcx);
1902
1903                         // Check the kind of deref to decide
1904                         match base_ty.sty {
1905                             ty::TyRef(_, tnm) => {
1906                                 match tnm.mutbl {
1907                                     // Shared borrowed data is never mutable
1908                                     hir::MutImmutable => Err(place),
1909                                     // Mutably borrowed data is mutable, but only if we have a
1910                                     // unique path to the `&mut`
1911                                     hir::MutMutable => {
1912                                         let mode = match self.is_upvar_field_projection(&proj.base)
1913                                         {
1914                                             Some(field)
1915                                                 if {
1916                                                     self.mir.upvar_decls[field.index()].by_ref
1917                                                 } =>
1918                                             {
1919                                                 is_local_mutation_allowed
1920                                             }
1921                                             _ => LocalMutationIsAllowed::Yes,
1922                                         };
1923
1924                                         self.is_mutable(&proj.base, mode)
1925                                     }
1926                                 }
1927                             }
1928                             ty::TyRawPtr(tnm) => {
1929                                 match tnm.mutbl {
1930                                     // `*const` raw pointers are not mutable
1931                                     hir::MutImmutable => return Err(place),
1932                                     // `*mut` raw pointers are always mutable, regardless of
1933                                     // context. The users have to check by themselves.
1934                                     hir::MutMutable => {
1935                                         return Ok(RootPlace { place, is_local_mutation_allowed });
1936                                     }
1937                                 }
1938                             }
1939                             // `Box<T>` owns its content, so mutable if its location is mutable
1940                             _ if base_ty.is_box() => {
1941                                 self.is_mutable(&proj.base, is_local_mutation_allowed)
1942                             }
1943                             // Deref should only be for reference, pointers or boxes
1944                             _ => bug!("Deref of unexpected type: {:?}", base_ty),
1945                         }
1946                     }
1947                     // All other projections are owned by their base path, so mutable if
1948                     // base path is mutable
1949                     ProjectionElem::Field(..)
1950                     | ProjectionElem::Index(..)
1951                     | ProjectionElem::ConstantIndex { .. }
1952                     | ProjectionElem::Subslice { .. }
1953                     | ProjectionElem::Downcast(..) => {
1954                         if let Some(field) = self.is_upvar_field_projection(place) {
1955                             let decl = &self.mir.upvar_decls[field.index()];
1956                             debug!(
1957                                 "decl.mutability={:?} local_mutation_is_allowed={:?} place={:?}",
1958                                 decl, is_local_mutation_allowed, place
1959                             );
1960                             match (decl.mutability, is_local_mutation_allowed) {
1961                                 (Mutability::Not, LocalMutationIsAllowed::No)
1962                                 | (Mutability::Not, LocalMutationIsAllowed::ExceptUpvars) => {
1963                                     Err(place)
1964                                 }
1965                                 (Mutability::Not, LocalMutationIsAllowed::Yes)
1966                                 | (Mutability::Mut, _) => {
1967                                     // Subtle: this is an upvar
1968                                     // reference, so it looks like
1969                                     // `self.foo` -- we want to double
1970                                     // check that the context `*self`
1971                                     // is mutable (i.e., this is not a
1972                                     // `Fn` closure).  But if that
1973                                     // check succeeds, we want to
1974                                     // *blame* the mutability on
1975                                     // `place` (that is,
1976                                     // `self.foo`). This is used to
1977                                     // propagate the info about
1978                                     // whether mutability declarations
1979                                     // are used outwards, so that we register
1980                                     // the outer variable as mutable. Otherwise a
1981                                     // test like this fails to record the `mut`
1982                                     // as needed:
1983                                     //
1984                                     // ```
1985                                     // fn foo<F: FnOnce()>(_f: F) { }
1986                                     // fn main() {
1987                                     //     let var = Vec::new();
1988                                     //     foo(move || {
1989                                     //         var.push(1);
1990                                     //     });
1991                                     // }
1992                                     // ```
1993                                     let _ = self.is_mutable(&proj.base, is_local_mutation_allowed)?;
1994                                     Ok(RootPlace { place, is_local_mutation_allowed })
1995                                 }
1996                             }
1997                         } else {
1998                             self.is_mutable(&proj.base, is_local_mutation_allowed)
1999                         }
2000                     }
2001                 }
2002             }
2003         }
2004     }
2005
2006     /// If this is a field projection, and the field is being projected from a closure type,
2007     /// then returns the index of the field being projected. Note that this closure will always
2008     /// be `self` in the current MIR, because that is the only time we directly access the fields
2009     /// of a closure type.
2010     fn is_upvar_field_projection(&self, place: &Place<'tcx>) -> Option<Field> {
2011         match *place {
2012             Place::Projection(ref proj) => match proj.elem {
2013                 ProjectionElem::Field(field, _ty) => {
2014                     let is_projection_from_ty_closure = proj.base
2015                         .ty(self.mir, self.tcx)
2016                         .to_ty(self.tcx)
2017                         .is_closure();
2018
2019                     if is_projection_from_ty_closure {
2020                         Some(field)
2021                     } else {
2022                         None
2023                     }
2024                 }
2025                 _ => None,
2026             },
2027             _ => None,
2028         }
2029     }
2030 }
2031
2032 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2033 enum NoMovePathFound {
2034     ReachedStatic,
2035 }
2036
2037 /// The degree of overlap between 2 places for borrow-checking.
2038 enum Overlap {
2039     /// The places might partially overlap - in this case, we give
2040     /// up and say that they might conflict. This occurs when
2041     /// different fields of a union are borrowed. For example,
2042     /// if `u` is a union, we have no way of telling how disjoint
2043     /// `u.a.x` and `a.b.y` are.
2044     Arbitrary,
2045     /// The places have the same type, and are either completely disjoint
2046     /// or equal - i.e. they can't "partially" overlap as can occur with
2047     /// unions. This is the "base case" on which we recur for extensions
2048     /// of the place.
2049     EqualOrDisjoint,
2050     /// The places are disjoint, so we know all extensions of them
2051     /// will also be disjoint.
2052     Disjoint,
2053 }
2054
2055 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
2056     // Given that the bases of `elem1` and `elem2` are always either equal
2057     // or disjoint (and have the same type!), return the overlap situation
2058     // between `elem1` and `elem2`.
2059     fn place_element_conflict(&self, elem1: &Place<'tcx>, elem2: &Place<'tcx>) -> Overlap {
2060         match (elem1, elem2) {
2061             (Place::Local(l1), Place::Local(l2)) => {
2062                 if l1 == l2 {
2063                     // the same local - base case, equal
2064                     debug!("place_element_conflict: DISJOINT-OR-EQ-LOCAL");
2065                     Overlap::EqualOrDisjoint
2066                 } else {
2067                     // different locals - base case, disjoint
2068                     debug!("place_element_conflict: DISJOINT-LOCAL");
2069                     Overlap::Disjoint
2070                 }
2071             }
2072             (Place::Static(static1), Place::Static(static2)) => {
2073                 if static1.def_id != static2.def_id {
2074                     debug!("place_element_conflict: DISJOINT-STATIC");
2075                     Overlap::Disjoint
2076                 } else if self.tcx.is_static(static1.def_id) == Some(hir::Mutability::MutMutable) {
2077                     // We ignore mutable statics - they can only be unsafe code.
2078                     debug!("place_element_conflict: IGNORE-STATIC-MUT");
2079                     Overlap::Disjoint
2080                 } else {
2081                     debug!("place_element_conflict: DISJOINT-OR-EQ-STATIC");
2082                     Overlap::EqualOrDisjoint
2083                 }
2084             }
2085             (Place::Local(_), Place::Static(_)) | (Place::Static(_), Place::Local(_)) => {
2086                 debug!("place_element_conflict: DISJOINT-STATIC-LOCAL");
2087                 Overlap::Disjoint
2088             }
2089             (Place::Projection(pi1), Place::Projection(pi2)) => {
2090                 match (&pi1.elem, &pi2.elem) {
2091                     (ProjectionElem::Deref, ProjectionElem::Deref) => {
2092                         // derefs (e.g. `*x` vs. `*x`) - recur.
2093                         debug!("place_element_conflict: DISJOINT-OR-EQ-DEREF");
2094                         Overlap::EqualOrDisjoint
2095                     }
2096                     (ProjectionElem::Field(f1, _), ProjectionElem::Field(f2, _)) => {
2097                         if f1 == f2 {
2098                             // same field (e.g. `a.y` vs. `a.y`) - recur.
2099                             debug!("place_element_conflict: DISJOINT-OR-EQ-FIELD");
2100                             Overlap::EqualOrDisjoint
2101                         } else {
2102                             let ty = pi1.base.ty(self.mir, self.tcx).to_ty(self.tcx);
2103                             match ty.sty {
2104                                 ty::TyAdt(def, _) if def.is_union() => {
2105                                     // Different fields of a union, we are basically stuck.
2106                                     debug!("place_element_conflict: STUCK-UNION");
2107                                     Overlap::Arbitrary
2108                                 }
2109                                 _ => {
2110                                     // Different fields of a struct (`a.x` vs. `a.y`). Disjoint!
2111                                     debug!("place_element_conflict: DISJOINT-FIELD");
2112                                     Overlap::Disjoint
2113                                 }
2114                             }
2115                         }
2116                     }
2117                     (ProjectionElem::Downcast(_, v1), ProjectionElem::Downcast(_, v2)) => {
2118                         // different variants are treated as having disjoint fields,
2119                         // even if they occupy the same "space", because it's
2120                         // impossible for 2 variants of the same enum to exist
2121                         // (and therefore, to be borrowed) at the same time.
2122                         //
2123                         // Note that this is different from unions - we *do* allow
2124                         // this code to compile:
2125                         //
2126                         // ```
2127                         // fn foo(x: &mut Result<i32, i32>) {
2128                         //     let mut v = None;
2129                         //     if let Ok(ref mut a) = *x {
2130                         //         v = Some(a);
2131                         //     }
2132                         //     // here, you would *think* that the
2133                         //     // *entirety* of `x` would be borrowed,
2134                         //     // but in fact only the `Ok` variant is,
2135                         //     // so the `Err` variant is *entirely free*:
2136                         //     if let Err(ref mut a) = *x {
2137                         //         v = Some(a);
2138                         //     }
2139                         //     drop(v);
2140                         // }
2141                         // ```
2142                         if v1 == v2 {
2143                             debug!("place_element_conflict: DISJOINT-OR-EQ-FIELD");
2144                             Overlap::EqualOrDisjoint
2145                         } else {
2146                             debug!("place_element_conflict: DISJOINT-FIELD");
2147                             Overlap::Disjoint
2148                         }
2149                     }
2150                     (ProjectionElem::Index(..), ProjectionElem::Index(..))
2151                     | (ProjectionElem::Index(..), ProjectionElem::ConstantIndex { .. })
2152                     | (ProjectionElem::Index(..), ProjectionElem::Subslice { .. })
2153                     | (ProjectionElem::ConstantIndex { .. }, ProjectionElem::Index(..))
2154                     | (
2155                         ProjectionElem::ConstantIndex { .. },
2156                         ProjectionElem::ConstantIndex { .. },
2157                     )
2158                     | (ProjectionElem::ConstantIndex { .. }, ProjectionElem::Subslice { .. })
2159                     | (ProjectionElem::Subslice { .. }, ProjectionElem::Index(..))
2160                     | (ProjectionElem::Subslice { .. }, ProjectionElem::ConstantIndex { .. })
2161                     | (ProjectionElem::Subslice { .. }, ProjectionElem::Subslice { .. }) => {
2162                         // Array indexes (`a[0]` vs. `a[i]`). These can either be disjoint
2163                         // (if the indexes differ) or equal (if they are the same), so this
2164                         // is the recursive case that gives "equal *or* disjoint" its meaning.
2165                         //
2166                         // Note that by construction, MIR at borrowck can't subdivide
2167                         // `Subslice` accesses (e.g. `a[2..3][i]` will never be present) - they
2168                         // are only present in slice patterns, and we "merge together" nested
2169                         // slice patterns. That means we don't have to think about these. It's
2170                         // probably a good idea to assert this somewhere, but I'm too lazy.
2171                         //
2172                         // FIXME(#8636) we might want to return Disjoint if
2173                         // both projections are constant and disjoint.
2174                         debug!("place_element_conflict: DISJOINT-OR-EQ-ARRAY");
2175                         Overlap::EqualOrDisjoint
2176                     }
2177
2178                     (ProjectionElem::Deref, _)
2179                     | (ProjectionElem::Field(..), _)
2180                     | (ProjectionElem::Index(..), _)
2181                     | (ProjectionElem::ConstantIndex { .. }, _)
2182                     | (ProjectionElem::Subslice { .. }, _)
2183                     | (ProjectionElem::Downcast(..), _) => bug!(
2184                         "mismatched projections in place_element_conflict: {:?} and {:?}",
2185                         elem1,
2186                         elem2
2187                     ),
2188                 }
2189             }
2190             (Place::Projection(_), _) | (_, Place::Projection(_)) => bug!(
2191                 "unexpected elements in place_element_conflict: {:?} and {:?}",
2192                 elem1,
2193                 elem2
2194             ),
2195         }
2196     }
2197
2198     /// Returns whether an access of kind `access` to `access_place` conflicts with
2199     /// a borrow/full access to `borrow_place` (for deep accesses to mutable
2200     /// locations, this function is symmetric between `borrow_place` & `access_place`).
2201     fn places_conflict(
2202         &mut self,
2203         borrow_place: &Place<'tcx>,
2204         access_place: &Place<'tcx>,
2205         access: ShallowOrDeep,
2206     ) -> bool {
2207         debug!(
2208             "places_conflict({:?},{:?},{:?})",
2209             borrow_place, access_place, access
2210         );
2211
2212         // Return all the prefixes of `place` in reverse order, including
2213         // downcasts.
2214         fn place_elements<'a, 'tcx>(place: &'a Place<'tcx>) -> Vec<&'a Place<'tcx>> {
2215             let mut result = vec![];
2216             let mut place = place;
2217             loop {
2218                 result.push(place);
2219                 match place {
2220                     Place::Projection(interior) => {
2221                         place = &interior.base;
2222                     }
2223                     Place::Local(_) | Place::Static(_) => {
2224                         result.reverse();
2225                         return result;
2226                     }
2227                 }
2228             }
2229         }
2230
2231         let borrow_components = place_elements(borrow_place);
2232         let access_components = place_elements(access_place);
2233         debug!(
2234             "places_conflict: components {:?} / {:?}",
2235             borrow_components, access_components
2236         );
2237
2238         let borrow_components = borrow_components
2239             .into_iter()
2240             .map(Some)
2241             .chain(iter::repeat(None));
2242         let access_components = access_components
2243             .into_iter()
2244             .map(Some)
2245             .chain(iter::repeat(None));
2246         // The borrowck rules for proving disjointness are applied from the "root" of the
2247         // borrow forwards, iterating over "similar" projections in lockstep until
2248         // we can prove overlap one way or another. Essentially, we treat `Overlap` as
2249         // a monoid and report a conflict if the product ends up not being `Disjoint`.
2250         //
2251         // At each step, if we didn't run out of borrow or place, we know that our elements
2252         // have the same type, and that they only overlap if they are the identical.
2253         //
2254         // For example, if we are comparing these:
2255         // BORROW:  (*x1[2].y).z.a
2256         // ACCESS:  (*x1[i].y).w.b
2257         //
2258         // Then our steps are:
2259         //       x1         |   x1          -- places are the same
2260         //       x1[2]      |   x1[i]       -- equal or disjoint (disjoint if indexes differ)
2261         //       x1[2].y    |   x1[i].y     -- equal or disjoint
2262         //      *x1[2].y    |  *x1[i].y     -- equal or disjoint
2263         //     (*x1[2].y).z | (*x1[i].y).w  -- we are disjoint and don't need to check more!
2264         //
2265         // Because `zip` does potentially bad things to the iterator inside, this loop
2266         // also handles the case where the access might be a *prefix* of the borrow, e.g.
2267         //
2268         // BORROW:  (*x1[2].y).z.a
2269         // ACCESS:  x1[i].y
2270         //
2271         // Then our steps are:
2272         //       x1         |   x1          -- places are the same
2273         //       x1[2]      |   x1[i]       -- equal or disjoint (disjoint if indexes differ)
2274         //       x1[2].y    |   x1[i].y     -- equal or disjoint
2275         //
2276         // -- here we run out of access - the borrow can access a part of it. If this
2277         // is a full deep access, then we *know* the borrow conflicts with it. However,
2278         // if the access is shallow, then we can proceed:
2279         //
2280         //       x1[2].y    | (*x1[i].y)    -- a deref! the access can't get past this, so we
2281         //                                     are disjoint
2282         //
2283         // Our invariant is, that at each step of the iteration:
2284         //  - If we didn't run out of access to match, our borrow and access are comparable
2285         //    and either equal or disjoint.
2286         //  - If we did run out of accesss, the borrow can access a part of it.
2287         for (borrow_c, access_c) in borrow_components.zip(access_components) {
2288             // loop invariant: borrow_c is always either equal to access_c or disjoint from it.
2289             debug!("places_conflict: {:?} vs. {:?}", borrow_c, access_c);
2290             match (borrow_c, access_c) {
2291                 (None, _) => {
2292                     // If we didn't run out of access, the borrow can access all of our
2293                     // place (e.g. a borrow of `a.b` with an access to `a.b.c`),
2294                     // so we have a conflict.
2295                     //
2296                     // If we did, then we still know that the borrow can access a *part*
2297                     // of our place that our access cares about (a borrow of `a.b.c`
2298                     // with an access to `a.b`), so we still have a conflict.
2299                     //
2300                     // FIXME: Differs from AST-borrowck; includes drive-by fix
2301                     // to #38899. Will probably need back-compat mode flag.
2302                     debug!("places_conflict: full borrow, CONFLICT");
2303                     return true;
2304                 }
2305                 (Some(borrow_c), None) => {
2306                     // We know that the borrow can access a part of our place. This
2307                     // is a conflict if that is a part our access cares about.
2308
2309                     let (base, elem) = match borrow_c {
2310                         Place::Projection(box Projection { base, elem }) => (base, elem),
2311                         _ => bug!("place has no base?"),
2312                     };
2313                     let base_ty = base.ty(self.mir, self.tcx).to_ty(self.tcx);
2314
2315                     match (elem, &base_ty.sty, access) {
2316                         (_, _, Shallow(Some(ArtificialField::Discriminant)))
2317                         | (_, _, Shallow(Some(ArtificialField::ArrayLength))) => {
2318                             // The discriminant and array length are like
2319                             // additional fields on the type; they do not
2320                             // overlap any existing data there. Furthermore,
2321                             // they cannot actually be a prefix of any
2322                             // borrowed place (at least in MIR as it is
2323                             // currently.)
2324                             //
2325                             // e.g. a (mutable) borrow of `a[5]` while we read the
2326                             // array length of `a`.
2327                             debug!("places_conflict: implicit field");
2328                             return false;
2329                         }
2330
2331                         (ProjectionElem::Deref, _, Shallow(None)) => {
2332                             // e.g. a borrow of `*x.y` while we shallowly access `x.y` or some
2333                             // prefix thereof - the shallow access can't touch anything behind
2334                             // the pointer.
2335                             debug!("places_conflict: shallow access behind ptr");
2336                             return false;
2337                         }
2338                         (
2339                             ProjectionElem::Deref,
2340                             ty::TyRef(
2341                                 _,
2342                                 ty::TypeAndMut {
2343                                     ty: _,
2344                                     mutbl: hir::MutImmutable,
2345                                 },
2346                             ),
2347                             _,
2348                         ) => {
2349                             // the borrow goes through a dereference of a shared reference.
2350                             //
2351                             // I'm not sure why we are tracking these borrows - shared
2352                             // references can *always* be aliased, which means the
2353                             // permission check already account for this borrow.
2354                             debug!("places_conflict: behind a shared ref");
2355                             return false;
2356                         }
2357
2358                         (ProjectionElem::Deref, _, Deep)
2359                         | (ProjectionElem::Field { .. }, _, _)
2360                         | (ProjectionElem::Index { .. }, _, _)
2361                         | (ProjectionElem::ConstantIndex { .. }, _, _)
2362                         | (ProjectionElem::Subslice { .. }, _, _)
2363                         | (ProjectionElem::Downcast { .. }, _, _) => {
2364                             // Recursive case. This can still be disjoint on a
2365                             // further iteration if this a shallow access and
2366                             // there's a deref later on, e.g. a borrow
2367                             // of `*x.y` while accessing `x`.
2368                         }
2369                     }
2370                 }
2371                 (Some(borrow_c), Some(access_c)) => {
2372                     match self.place_element_conflict(&borrow_c, access_c) {
2373                         Overlap::Arbitrary => {
2374                             // We have encountered different fields of potentially
2375                             // the same union - the borrow now partially overlaps.
2376                             //
2377                             // There is no *easy* way of comparing the fields
2378                             // further on, because they might have different types
2379                             // (e.g. borrows of `u.a.0` and `u.b.y` where `.0` and
2380                             // `.y` come from different structs).
2381                             //
2382                             // We could try to do some things here - e.g. count
2383                             // dereferences - but that's probably not a good
2384                             // idea, at least for now, so just give up and
2385                             // report a conflict. This is unsafe code anyway so
2386                             // the user could always use raw pointers.
2387                             debug!("places_conflict: arbitrary -> conflict");
2388                             return true;
2389                         }
2390                         Overlap::EqualOrDisjoint => {
2391                             // This is the recursive case - proceed to the next element.
2392                         }
2393                         Overlap::Disjoint => {
2394                             // We have proven the borrow disjoint - further
2395                             // projections will remain disjoint.
2396                             debug!("places_conflict: disjoint");
2397                             return false;
2398                         }
2399                     }
2400                 }
2401             }
2402         }
2403         unreachable!("iter::repeat returned None")
2404     }
2405
2406     /// This function iterates over all of the in-scope borrows that
2407     /// conflict with an access to a place, invoking the `op` callback
2408     /// for each one.
2409     ///
2410     /// "Current borrow" here means a borrow that reaches the point in
2411     /// the control-flow where the access occurs.
2412     ///
2413     /// The borrow's phase is represented by the IsActive parameter
2414     /// passed to the callback.
2415     fn each_borrow_involving_path<F>(
2416         &mut self,
2417         _context: Context,
2418         access_place: (ShallowOrDeep, &Place<'tcx>),
2419         flow_state: &Flows<'cx, 'gcx, 'tcx>,
2420         mut op: F,
2421     ) where
2422         F: FnMut(&mut Self, BorrowIndex, &BorrowData<'tcx>) -> Control,
2423     {
2424         let (access, place) = access_place;
2425
2426         // FIXME: analogous code in check_loans first maps `place` to
2427         // its base_path.
2428
2429         // check for loan restricting path P being used. Accounts for
2430         // borrows of P, P.a.b, etc.
2431         let borrow_set = self.borrow_set.clone();
2432         for i in flow_state.borrows_in_scope() {
2433             let borrowed = &borrow_set[i];
2434
2435             if self.places_conflict(&borrowed.borrowed_place, place, access) {
2436                 debug!(
2437                     "each_borrow_involving_path: {:?} @ {:?} vs. {:?}/{:?}",
2438                     i, borrowed, place, access
2439                 );
2440                 let ctrl = op(self, i, borrowed);
2441                 if ctrl == Control::Break {
2442                     return;
2443                 }
2444             }
2445         }
2446     }
2447
2448     fn is_active(
2449         &self,
2450         borrow_data: &BorrowData<'tcx>,
2451         location: Location
2452     ) -> bool {
2453         debug!("is_active(borrow_data={:?}, location={:?})", borrow_data, location);
2454
2455         // If this is not a 2-phase borrow, it is always active.
2456         let activation_location = match borrow_data.activation_location {
2457             Some(v) => v,
2458             None => return true,
2459         };
2460
2461         // Otherwise, it is active for every location *except* in between
2462         // the reservation and the activation:
2463         //
2464         //       X
2465         //      /
2466         //     R      <--+ Except for this
2467         //    / \        | diamond
2468         //    \ /        |
2469         //     A  <------+
2470         //     |
2471         //     Z
2472         //
2473         // Note that we assume that:
2474         // - the reservation R dominates the activation A
2475         // - the activation A post-dominates the reservation R (ignoring unwinding edges).
2476         //
2477         // This means that there can't be an edge that leaves A and
2478         // comes back into that diamond unless it passes through R.
2479         //
2480         // Suboptimal: In some cases, this code walks the dominator
2481         // tree twice when it only has to be walked once. I am
2482         // lazy. -nmatsakis
2483
2484         // If dominated by the activation A, then it is active. The
2485         // activation occurs upon entering the point A, so this is
2486         // also true if location == activation_location.
2487         if activation_location.dominates(location, &self.dominators) {
2488             return true;
2489         }
2490
2491         // The reservation starts *on exiting* the reservation block,
2492         // so check if the location is dominated by R.successor. If so,
2493         // this point falls in between the reservation and location.
2494         let reserve_location = borrow_data.reserve_location.successor_within_block();
2495         if reserve_location.dominates(location, &self.dominators) {
2496             false
2497         } else {
2498             // Otherwise, this point is outside the diamond, so
2499             // consider the borrow active. This could happen for
2500             // example if the borrow remains active around a loop (in
2501             // which case it would be active also for the point R,
2502             // which would generate an error).
2503             true
2504         }
2505     }
2506 }
2507
2508 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
2509     // FIXME (#16118): function intended to allow the borrow checker
2510     // to be less precise in its handling of Box while still allowing
2511     // moves out of a Box. They should be removed when/if we stop
2512     // treating Box specially (e.g. when/if DerefMove is added...)
2513
2514     fn base_path<'d>(&self, place: &'d Place<'tcx>) -> &'d Place<'tcx> {
2515         //! Returns the base of the leftmost (deepest) dereference of an
2516         //! Box in `place`. If there is no dereference of an Box
2517         //! in `place`, then it just returns `place` itself.
2518
2519         let mut cursor = place;
2520         let mut deepest = place;
2521         loop {
2522             let proj = match *cursor {
2523                 Place::Local(..) | Place::Static(..) => return deepest,
2524                 Place::Projection(ref proj) => proj,
2525             };
2526             if proj.elem == ProjectionElem::Deref
2527                 && place.ty(self.mir, self.tcx).to_ty(self.tcx).is_box()
2528             {
2529                 deepest = &proj.base;
2530             }
2531             cursor = &proj.base;
2532         }
2533     }
2534 }
2535
2536 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2537 struct Context {
2538     kind: ContextKind,
2539     loc: Location,
2540 }
2541
2542 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2543 enum ContextKind {
2544     Activation,
2545     AssignLhs,
2546     AssignRhs,
2547     SetDiscrim,
2548     InlineAsm,
2549     SwitchInt,
2550     Drop,
2551     DropAndReplace,
2552     CallOperator,
2553     CallOperand,
2554     CallDest,
2555     Assert,
2556     Yield,
2557     StorageDead,
2558 }
2559
2560 impl ContextKind {
2561     fn new(self, loc: Location) -> Context {
2562         Context {
2563             kind: self,
2564             loc: loc,
2565         }
2566     }
2567 }
2568