• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
2 
3 #![feature(associated_type_bounds)]
4 #![feature(box_patterns)]
5 #![feature(let_chains)]
6 #![feature(min_specialization)]
7 #![feature(never_type)]
8 #![feature(lazy_cell)]
9 #![feature(rustc_attrs)]
10 #![feature(stmt_expr_attributes)]
11 #![feature(trusted_step)]
12 #![feature(try_blocks)]
13 #![recursion_limit = "256"]
14 
15 #[macro_use]
16 extern crate rustc_middle;
17 #[macro_use]
18 extern crate tracing;
19 
20 use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
21 use rustc_data_structures::graph::dominators::Dominators;
22 use rustc_errors::{Diagnostic, DiagnosticBuilder, DiagnosticMessage, SubdiagnosticMessage};
23 use rustc_fluent_macro::fluent_messages;
24 use rustc_hir as hir;
25 use rustc_hir::def_id::LocalDefId;
26 use rustc_index::bit_set::ChunkedBitSet;
27 use rustc_index::{IndexSlice, IndexVec};
28 use rustc_infer::infer::{
29     InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin, TyCtxtInferExt,
30 };
31 use rustc_middle::mir::{
32     traversal, Body, ClearCrossCrate, Local, Location, MutBorrowKind, Mutability,
33     NonDivergingIntrinsic, Operand, Place, PlaceElem, PlaceRef, VarDebugInfoContents,
34 };
35 use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
36 use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind};
37 use rustc_middle::mir::{ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
38 use rustc_middle::query::Providers;
39 use rustc_middle::traits::DefiningAnchor;
40 use rustc_middle::ty::{self, CapturedPlace, ParamEnv, RegionVid, TyCtxt};
41 use rustc_session::lint::builtin::UNUSED_MUT;
42 use rustc_span::{Span, Symbol};
43 use rustc_target::abi::FieldIdx;
44 
45 use either::Either;
46 use smallvec::SmallVec;
47 use std::cell::RefCell;
48 use std::collections::BTreeMap;
49 use std::ops::Deref;
50 use std::rc::Rc;
51 
52 use rustc_mir_dataflow::impls::{
53     EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces,
54 };
55 use rustc_mir_dataflow::move_paths::{InitIndex, MoveOutIndex, MovePathIndex};
56 use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveData, MoveError};
57 use rustc_mir_dataflow::Analysis;
58 use rustc_mir_dataflow::MoveDataParamEnv;
59 
60 use crate::session_diagnostics::VarNeedNotMut;
61 
62 use self::diagnostics::{AccessKind, RegionName};
63 use self::location::LocationTable;
64 use self::prefixes::PrefixSet;
65 use consumers::{BodyWithBorrowckFacts, ConsumerOptions};
66 
67 use self::path_utils::*;
68 
69 pub mod borrow_set;
70 mod borrowck_errors;
71 mod constraint_generation;
72 mod constraints;
73 mod dataflow;
74 mod def_use;
75 mod diagnostics;
76 mod facts;
77 mod invalidation;
78 mod location;
79 mod member_constraints;
80 mod nll;
81 mod path_utils;
82 mod place_ext;
83 mod places_conflict;
84 mod prefixes;
85 mod region_infer;
86 mod renumber;
87 mod session_diagnostics;
88 mod type_check;
89 mod universal_regions;
90 mod used_muts;
91 mod util;
92 
93 /// A public API provided for the Rust compiler consumers.
94 pub mod consumers;
95 
96 use borrow_set::{BorrowData, BorrowSet};
97 use dataflow::{BorrowIndex, BorrowckFlowState as Flows, BorrowckResults, Borrows};
98 use nll::PoloniusOutput;
99 use place_ext::PlaceExt;
100 use places_conflict::{places_conflict, PlaceConflictBias};
101 use region_infer::RegionInferenceContext;
102 use renumber::RegionCtxt;
103 
104 fluent_messages! { "../messages.ftl" }
105 
106 // FIXME(eddyb) perhaps move this somewhere more centrally.
107 #[derive(Debug)]
108 struct Upvar<'tcx> {
109     place: CapturedPlace<'tcx>,
110 
111     /// If true, the capture is behind a reference.
112     by_ref: bool,
113 }
114 
115 /// Associate some local constants with the `'tcx` lifetime
116 struct TyCtxtConsts<'tcx>(TyCtxt<'tcx>);
117 impl<'tcx> TyCtxtConsts<'tcx> {
118     const DEREF_PROJECTION: &'tcx [PlaceElem<'tcx>; 1] = &[ProjectionElem::Deref];
119 }
120 
provide(providers: &mut Providers)121 pub fn provide(providers: &mut Providers) {
122     *providers = Providers { mir_borrowck, ..*providers };
123 }
124 
mir_borrowck(tcx: TyCtxt<'_>, def: LocalDefId) -> &BorrowCheckResult<'_>125 fn mir_borrowck(tcx: TyCtxt<'_>, def: LocalDefId) -> &BorrowCheckResult<'_> {
126     let (input_body, promoted) = tcx.mir_promoted(def);
127     debug!("run query mir_borrowck: {}", tcx.def_path_str(def));
128 
129     if input_body.borrow().should_skip() {
130         debug!("Skipping borrowck because of injected body");
131         // Let's make up a borrowck result! Fun times!
132         let result = BorrowCheckResult {
133             concrete_opaque_types: FxIndexMap::default(),
134             closure_requirements: None,
135             used_mut_upvars: SmallVec::new(),
136             tainted_by_errors: None,
137         };
138         return tcx.arena.alloc(result);
139     }
140 
141     let hir_owner = tcx.hir().local_def_id_to_hir_id(def).owner;
142 
143     let infcx =
144         tcx.infer_ctxt().with_opaque_type_inference(DefiningAnchor::Bind(hir_owner.def_id)).build();
145     let input_body: &Body<'_> = &input_body.borrow();
146     let promoted: &IndexSlice<_, _> = &promoted.borrow();
147     let opt_closure_req = do_mir_borrowck(&infcx, input_body, promoted, None).0;
148     debug!("mir_borrowck done");
149 
150     tcx.arena.alloc(opt_closure_req)
151 }
152 
153 /// Perform the actual borrow checking.
154 ///
155 /// Use `consumer_options: None` for the default behavior of returning
156 /// [`BorrowCheckResult`] only. Otherwise, return [`BodyWithBorrowckFacts`] according
157 /// to the given [`ConsumerOptions`].
158 #[instrument(skip(infcx, input_body, input_promoted), fields(id=?input_body.source.def_id()), level = "debug")]
do_mir_borrowck<'tcx>( infcx: &InferCtxt<'tcx>, input_body: &Body<'tcx>, input_promoted: &IndexSlice<Promoted, Body<'tcx>>, consumer_options: Option<ConsumerOptions>, ) -> (BorrowCheckResult<'tcx>, Option<Box<BodyWithBorrowckFacts<'tcx>>>)159 fn do_mir_borrowck<'tcx>(
160     infcx: &InferCtxt<'tcx>,
161     input_body: &Body<'tcx>,
162     input_promoted: &IndexSlice<Promoted, Body<'tcx>>,
163     consumer_options: Option<ConsumerOptions>,
164 ) -> (BorrowCheckResult<'tcx>, Option<Box<BodyWithBorrowckFacts<'tcx>>>) {
165     let def = input_body.source.def_id().expect_local();
166     debug!(?def);
167 
168     let tcx = infcx.tcx;
169     let infcx = BorrowckInferCtxt::new(infcx);
170     let param_env = tcx.param_env(def);
171 
172     let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
173     for var_debug_info in &input_body.var_debug_info {
174         if let VarDebugInfoContents::Place(place) = var_debug_info.value {
175             if let Some(local) = place.as_local() {
176                 if let Some(prev_name) = local_names[local] && var_debug_info.name != prev_name {
177                     span_bug!(
178                         var_debug_info.source_info.span,
179                         "local {:?} has many names (`{}` vs `{}`)",
180                         local,
181                         prev_name,
182                         var_debug_info.name
183                     );
184                 }
185                 local_names[local] = Some(var_debug_info.name);
186             }
187         }
188     }
189 
190     let mut errors = error::BorrowckErrors::new(infcx.tcx);
191 
192     // Gather the upvars of a closure, if any.
193     if let Some(e) = input_body.tainted_by_errors {
194         infcx.set_tainted_by_errors(e);
195         errors.set_tainted_by_errors(e);
196     }
197     let upvars: Vec<_> = tcx
198         .closure_captures(def)
199         .iter()
200         .map(|&captured_place| {
201             let capture = captured_place.info.capture_kind;
202             let by_ref = match capture {
203                 ty::UpvarCapture::ByValue => false,
204                 ty::UpvarCapture::ByRef(..) => true,
205             };
206             Upvar { place: captured_place.clone(), by_ref }
207         })
208         .collect();
209 
210     // Replace all regions with fresh inference variables. This
211     // requires first making our own copy of the MIR. This copy will
212     // be modified (in place) to contain non-lexical lifetimes. It
213     // will have a lifetime tied to the inference context.
214     let mut body_owned = input_body.clone();
215     let mut promoted = input_promoted.to_owned();
216     let free_regions =
217         nll::replace_regions_in_mir(&infcx, param_env, &mut body_owned, &mut promoted);
218     let body = &body_owned; // no further changes
219 
220     let location_table_owned = LocationTable::new(body);
221     let location_table = &location_table_owned;
222 
223     let (move_data, move_errors): (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>) =
224         match MoveData::gather_moves(&body, tcx, param_env) {
225             Ok(move_data) => (move_data, Vec::new()),
226             Err((move_data, move_errors)) => (move_data, move_errors),
227         };
228     let promoted_errors = promoted
229         .iter_enumerated()
230         .map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env)));
231 
232     let mdpe = MoveDataParamEnv { move_data, param_env };
233 
234     let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe)
235         .into_engine(tcx, &body)
236         .pass_name("borrowck")
237         .iterate_to_fixpoint()
238         .into_results_cursor(&body);
239 
240     let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(def).is_fn_or_closure();
241     let borrow_set =
242         Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
243 
244     // Compute non-lexical lifetimes.
245     let nll::NllOutput {
246         regioncx,
247         opaque_type_values,
248         polonius_input,
249         polonius_output,
250         opt_closure_req,
251         nll_errors,
252     } = nll::compute_regions(
253         &infcx,
254         free_regions,
255         body,
256         &promoted,
257         location_table,
258         param_env,
259         &mut flow_inits,
260         &mdpe.move_data,
261         &borrow_set,
262         &upvars,
263         consumer_options,
264     );
265 
266     // Dump MIR results into a file, if that is enabled. This let us
267     // write unit-tests, as well as helping with debugging.
268     nll::dump_mir_results(&infcx, &body, &regioncx, &opt_closure_req);
269 
270     // We also have a `#[rustc_regions]` annotation that causes us to dump
271     // information.
272     nll::dump_annotation(
273         &infcx,
274         &body,
275         &regioncx,
276         &opt_closure_req,
277         &opaque_type_values,
278         &mut errors,
279     );
280 
281     // The various `flow_*` structures can be large. We drop `flow_inits` here
282     // so it doesn't overlap with the others below. This reduces peak memory
283     // usage significantly on some benchmarks.
284     drop(flow_inits);
285 
286     let regioncx = Rc::new(regioncx);
287 
288     let flow_borrows = Borrows::new(tcx, body, &regioncx, &borrow_set)
289         .into_engine(tcx, body)
290         .pass_name("borrowck")
291         .iterate_to_fixpoint();
292     let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &mdpe)
293         .into_engine(tcx, body)
294         .pass_name("borrowck")
295         .iterate_to_fixpoint();
296     let flow_ever_inits = EverInitializedPlaces::new(tcx, body, &mdpe)
297         .into_engine(tcx, body)
298         .pass_name("borrowck")
299         .iterate_to_fixpoint();
300 
301     let movable_generator =
302         // The first argument is the generator type passed by value
303         if let Some(local) = body.local_decls.raw.get(1)
304         // Get the interior types and substs which typeck computed
305         && let ty::Generator(_, _, hir::Movability::Static) = local.ty.kind()
306     {
307         false
308     } else {
309         true
310     };
311 
312     for (idx, move_data_results) in promoted_errors {
313         let promoted_body = &promoted[idx];
314 
315         if let Err((move_data, move_errors)) = move_data_results {
316             let mut promoted_mbcx = MirBorrowckCtxt {
317                 infcx: &infcx,
318                 param_env,
319                 body: promoted_body,
320                 move_data: &move_data,
321                 location_table, // no need to create a real one for the promoted, it is not used
322                 movable_generator,
323                 fn_self_span_reported: Default::default(),
324                 locals_are_invalidated_at_exit,
325                 access_place_error_reported: Default::default(),
326                 reservation_error_reported: Default::default(),
327                 uninitialized_error_reported: Default::default(),
328                 regioncx: regioncx.clone(),
329                 used_mut: Default::default(),
330                 used_mut_upvars: SmallVec::new(),
331                 borrow_set: Rc::clone(&borrow_set),
332                 upvars: Vec::new(),
333                 local_names: IndexVec::from_elem(None, &promoted_body.local_decls),
334                 region_names: RefCell::default(),
335                 next_region_name: RefCell::new(1),
336                 polonius_output: None,
337                 errors,
338             };
339             promoted_mbcx.report_move_errors(move_errors);
340             errors = promoted_mbcx.errors;
341         };
342     }
343 
344     let mut mbcx = MirBorrowckCtxt {
345         infcx: &infcx,
346         param_env,
347         body,
348         move_data: &mdpe.move_data,
349         location_table,
350         movable_generator,
351         locals_are_invalidated_at_exit,
352         fn_self_span_reported: Default::default(),
353         access_place_error_reported: Default::default(),
354         reservation_error_reported: Default::default(),
355         uninitialized_error_reported: Default::default(),
356         regioncx: Rc::clone(&regioncx),
357         used_mut: Default::default(),
358         used_mut_upvars: SmallVec::new(),
359         borrow_set: Rc::clone(&borrow_set),
360         upvars,
361         local_names,
362         region_names: RefCell::default(),
363         next_region_name: RefCell::new(1),
364         polonius_output,
365         errors,
366     };
367 
368     // Compute and report region errors, if any.
369     mbcx.report_region_errors(nll_errors);
370 
371     let mut results = BorrowckResults {
372         ever_inits: flow_ever_inits,
373         uninits: flow_uninits,
374         borrows: flow_borrows,
375     };
376 
377     mbcx.report_move_errors(move_errors);
378 
379     rustc_mir_dataflow::visit_results(
380         body,
381         traversal::reverse_postorder(body).map(|(bb, _)| bb),
382         &mut results,
383         &mut mbcx,
384     );
385 
386     // For each non-user used mutable variable, check if it's been assigned from
387     // a user-declared local. If so, then put that local into the used_mut set.
388     // Note that this set is expected to be small - only upvars from closures
389     // would have a chance of erroneously adding non-user-defined mutable vars
390     // to the set.
391     let temporary_used_locals: FxIndexSet<Local> = mbcx
392         .used_mut
393         .iter()
394         .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
395         .cloned()
396         .collect();
397     // For the remaining unused locals that are marked as mutable, we avoid linting any that
398     // were never initialized. These locals may have been removed as unreachable code; or will be
399     // linted as unused variables.
400     let unused_mut_locals =
401         mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
402     mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
403 
404     debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
405     let used_mut = std::mem::take(&mut mbcx.used_mut);
406     for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
407         let local_decl = &mbcx.body.local_decls[local];
408         let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data {
409             ClearCrossCrate::Set(data) => data.lint_root,
410             _ => continue,
411         };
412 
413         // Skip over locals that begin with an underscore or have no name
414         match mbcx.local_names[local] {
415             Some(name) => {
416                 if name.as_str().starts_with('_') {
417                     continue;
418                 }
419             }
420             None => continue,
421         }
422 
423         let span = local_decl.source_info.span;
424         if span.desugaring_kind().is_some() {
425             // If the `mut` arises as part of a desugaring, we should ignore it.
426             continue;
427         }
428 
429         let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
430 
431         tcx.emit_spanned_lint(UNUSED_MUT, lint_root, span, VarNeedNotMut { span: mut_span })
432     }
433 
434     let tainted_by_errors = mbcx.emit_errors();
435 
436     let result = BorrowCheckResult {
437         concrete_opaque_types: opaque_type_values,
438         closure_requirements: opt_closure_req,
439         used_mut_upvars: mbcx.used_mut_upvars,
440         tainted_by_errors,
441     };
442 
443     let body_with_facts = if consumer_options.is_some() {
444         let output_facts = mbcx.polonius_output;
445         Some(Box::new(BodyWithBorrowckFacts {
446             body: body_owned,
447             promoted,
448             borrow_set,
449             region_inference_context: regioncx,
450             location_table: polonius_input.as_ref().map(|_| location_table_owned),
451             input_facts: polonius_input,
452             output_facts,
453         }))
454     } else {
455         None
456     };
457 
458     debug!("do_mir_borrowck: result = {:#?}", result);
459 
460     (result, body_with_facts)
461 }
462 
463 pub struct BorrowckInferCtxt<'cx, 'tcx> {
464     pub(crate) infcx: &'cx InferCtxt<'tcx>,
465     pub(crate) reg_var_to_origin: RefCell<FxIndexMap<ty::RegionVid, RegionCtxt>>,
466 }
467 
468 impl<'cx, 'tcx> BorrowckInferCtxt<'cx, 'tcx> {
new(infcx: &'cx InferCtxt<'tcx>) -> Self469     pub(crate) fn new(infcx: &'cx InferCtxt<'tcx>) -> Self {
470         BorrowckInferCtxt { infcx, reg_var_to_origin: RefCell::new(Default::default()) }
471     }
472 
next_region_var<F>( &self, origin: RegionVariableOrigin, get_ctxt_fn: F, ) -> ty::Region<'tcx> where F: Fn() -> RegionCtxt,473     pub(crate) fn next_region_var<F>(
474         &self,
475         origin: RegionVariableOrigin,
476         get_ctxt_fn: F,
477     ) -> ty::Region<'tcx>
478     where
479         F: Fn() -> RegionCtxt,
480     {
481         let next_region = self.infcx.next_region_var(origin);
482         let vid = next_region.as_var();
483 
484         if cfg!(debug_assertions) {
485             debug!("inserting vid {:?} with origin {:?} into var_to_origin", vid, origin);
486             let ctxt = get_ctxt_fn();
487             let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
488             assert_eq!(var_to_origin.insert(vid, ctxt), None);
489         }
490 
491         next_region
492     }
493 
494     #[instrument(skip(self, get_ctxt_fn), level = "debug")]
next_nll_region_var<F>( &self, origin: NllRegionVariableOrigin, get_ctxt_fn: F, ) -> ty::Region<'tcx> where F: Fn() -> RegionCtxt,495     pub(crate) fn next_nll_region_var<F>(
496         &self,
497         origin: NllRegionVariableOrigin,
498         get_ctxt_fn: F,
499     ) -> ty::Region<'tcx>
500     where
501         F: Fn() -> RegionCtxt,
502     {
503         let next_region = self.infcx.next_nll_region_var(origin);
504         let vid = next_region.as_var();
505 
506         if cfg!(debug_assertions) {
507             debug!("inserting vid {:?} with origin {:?} into var_to_origin", vid, origin);
508             let ctxt = get_ctxt_fn();
509             let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
510             assert_eq!(var_to_origin.insert(vid, ctxt), None);
511         }
512 
513         next_region
514     }
515 }
516 
517 impl<'cx, 'tcx> Deref for BorrowckInferCtxt<'cx, 'tcx> {
518     type Target = InferCtxt<'tcx>;
519 
deref(&self) -> &'cx Self::Target520     fn deref(&self) -> &'cx Self::Target {
521         self.infcx
522     }
523 }
524 
525 struct MirBorrowckCtxt<'cx, 'tcx> {
526     infcx: &'cx BorrowckInferCtxt<'cx, 'tcx>,
527     param_env: ParamEnv<'tcx>,
528     body: &'cx Body<'tcx>,
529     move_data: &'cx MoveData<'tcx>,
530 
531     /// Map from MIR `Location` to `LocationIndex`; created
532     /// when MIR borrowck begins.
533     location_table: &'cx LocationTable,
534 
535     movable_generator: bool,
536     /// This keeps track of whether local variables are free-ed when the function
537     /// exits even without a `StorageDead`, which appears to be the case for
538     /// constants.
539     ///
540     /// I'm not sure this is the right approach - @eddyb could you try and
541     /// figure this out?
542     locals_are_invalidated_at_exit: bool,
543     /// This field keeps track of when borrow errors are reported in the access_place function
544     /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
545     /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
546     /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
547     /// errors.
548     access_place_error_reported: FxIndexSet<(Place<'tcx>, Span)>,
549     /// This field keeps track of when borrow conflict errors are reported
550     /// for reservations, so that we don't report seemingly duplicate
551     /// errors for corresponding activations.
552     //
553     // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
554     // but it is currently inconvenient to track down the `BorrowIndex`
555     // at the time we detect and report a reservation error.
556     reservation_error_reported: FxIndexSet<Place<'tcx>>,
557     /// This fields keeps track of the `Span`s that we have
558     /// used to report extra information for `FnSelfUse`, to avoid
559     /// unnecessarily verbose errors.
560     fn_self_span_reported: FxIndexSet<Span>,
561     /// This field keeps track of errors reported in the checking of uninitialized variables,
562     /// so that we don't report seemingly duplicate errors.
563     uninitialized_error_reported: FxIndexSet<PlaceRef<'tcx>>,
564     /// This field keeps track of all the local variables that are declared mut and are mutated.
565     /// Used for the warning issued by an unused mutable local variable.
566     used_mut: FxIndexSet<Local>,
567     /// If the function we're checking is a closure, then we'll need to report back the list of
568     /// mutable upvars that have been used. This field keeps track of them.
569     used_mut_upvars: SmallVec<[FieldIdx; 8]>,
570     /// Region inference context. This contains the results from region inference and lets us e.g.
571     /// find out which CFG points are contained in each borrow region.
572     regioncx: Rc<RegionInferenceContext<'tcx>>,
573 
574     /// The set of borrows extracted from the MIR
575     borrow_set: Rc<BorrowSet<'tcx>>,
576 
577     /// Information about upvars not necessarily preserved in types or MIR
578     upvars: Vec<Upvar<'tcx>>,
579 
580     /// Names of local (user) variables (extracted from `var_debug_info`).
581     local_names: IndexVec<Local, Option<Symbol>>,
582 
583     /// Record the region names generated for each region in the given
584     /// MIR def so that we can reuse them later in help/error messages.
585     region_names: RefCell<FxIndexMap<RegionVid, RegionName>>,
586 
587     /// The counter for generating new region names.
588     next_region_name: RefCell<usize>,
589 
590     /// Results of Polonius analysis.
591     polonius_output: Option<Rc<PoloniusOutput>>,
592 
593     errors: error::BorrowckErrors<'tcx>,
594 }
595 
596 // Check that:
597 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
598 // 2. loans made in overlapping scopes do not conflict
599 // 3. assignments do not affect things loaned out as immutable
600 // 4. moves do not affect things loaned out in any way
601 impl<'cx, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx, R> for MirBorrowckCtxt<'cx, 'tcx> {
602     type FlowState = Flows<'cx, 'tcx>;
603 
visit_statement_before_primary_effect( &mut self, _results: &R, flow_state: &Flows<'cx, 'tcx>, stmt: &'cx Statement<'tcx>, location: Location, )604     fn visit_statement_before_primary_effect(
605         &mut self,
606         _results: &R,
607         flow_state: &Flows<'cx, 'tcx>,
608         stmt: &'cx Statement<'tcx>,
609         location: Location,
610     ) {
611         debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state);
612         let span = stmt.source_info.span;
613 
614         self.check_activations(location, span, flow_state);
615 
616         match &stmt.kind {
617             StatementKind::Assign(box (lhs, rhs)) => {
618                 self.consume_rvalue(location, (rhs, span), flow_state);
619 
620                 self.mutate_place(location, (*lhs, span), Shallow(None), flow_state);
621             }
622             StatementKind::FakeRead(box (_, place)) => {
623                 // Read for match doesn't access any memory and is used to
624                 // assert that a place is safe and live. So we don't have to
625                 // do any checks here.
626                 //
627                 // FIXME: Remove check that the place is initialized. This is
628                 // needed for now because matches don't have never patterns yet.
629                 // So this is the only place we prevent
630                 //      let x: !;
631                 //      match x {};
632                 // from compiling.
633                 self.check_if_path_or_subpath_is_moved(
634                     location,
635                     InitializationRequiringAction::Use,
636                     (place.as_ref(), span),
637                     flow_state,
638                 );
639             }
640             StatementKind::Intrinsic(box kind) => match kind {
641                 NonDivergingIntrinsic::Assume(op) => self.consume_operand(location, (op, span), flow_state),
642                 NonDivergingIntrinsic::CopyNonOverlapping(..) => span_bug!(
643                     span,
644                     "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
645                 )
646             }
647             // Only relevant for mir typeck
648             StatementKind::AscribeUserType(..)
649             // Only relevant for liveness and unsafeck
650             | StatementKind::PlaceMention(..)
651             // Doesn't have any language semantics
652             | StatementKind::Coverage(..)
653             // These do not actually affect borrowck
654             | StatementKind::ConstEvalCounter
655             | StatementKind::StorageLive(..) => {}
656             StatementKind::StorageDead(local) => {
657                 self.access_place(
658                     location,
659                     (Place::from(*local), span),
660                     (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
661                     LocalMutationIsAllowed::Yes,
662                     flow_state,
663                 );
664             }
665             StatementKind::Nop
666             | StatementKind::Retag { .. }
667             | StatementKind::Deinit(..)
668             | StatementKind::SetDiscriminant { .. } => {
669                 bug!("Statement not allowed in this MIR phase")
670             }
671         }
672     }
673 
visit_terminator_before_primary_effect( &mut self, _results: &R, flow_state: &Flows<'cx, 'tcx>, term: &'cx Terminator<'tcx>, loc: Location, )674     fn visit_terminator_before_primary_effect(
675         &mut self,
676         _results: &R,
677         flow_state: &Flows<'cx, 'tcx>,
678         term: &'cx Terminator<'tcx>,
679         loc: Location,
680     ) {
681         debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
682         let span = term.source_info.span;
683 
684         self.check_activations(loc, span, flow_state);
685 
686         match &term.kind {
687             TerminatorKind::SwitchInt { discr, targets: _ } => {
688                 self.consume_operand(loc, (discr, span), flow_state);
689             }
690             TerminatorKind::Drop { place, target: _, unwind: _, replace } => {
691                 debug!(
692                     "visit_terminator_drop \
693                      loc: {:?} term: {:?} place: {:?} span: {:?}",
694                     loc, term, place, span
695                 );
696 
697                 let write_kind =
698                     if *replace { WriteKind::Replace } else { WriteKind::StorageDeadOrDrop };
699                 self.access_place(
700                     loc,
701                     (*place, span),
702                     (AccessDepth::Drop, Write(write_kind)),
703                     LocalMutationIsAllowed::Yes,
704                     flow_state,
705                 );
706             }
707             TerminatorKind::Call {
708                 func,
709                 args,
710                 destination,
711                 target: _,
712                 unwind: _,
713                 call_source: _,
714                 fn_span: _,
715             } => {
716                 self.consume_operand(loc, (func, span), flow_state);
717                 for arg in args {
718                     self.consume_operand(loc, (arg, span), flow_state);
719                 }
720                 self.mutate_place(loc, (*destination, span), Deep, flow_state);
721             }
722             TerminatorKind::Assert { cond, expected: _, msg, target: _, unwind: _ } => {
723                 self.consume_operand(loc, (cond, span), flow_state);
724                 use rustc_middle::mir::AssertKind;
725                 if let AssertKind::BoundsCheck { len, index } = &**msg {
726                     self.consume_operand(loc, (len, span), flow_state);
727                     self.consume_operand(loc, (index, span), flow_state);
728                 }
729             }
730 
731             TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
732                 self.consume_operand(loc, (value, span), flow_state);
733                 self.mutate_place(loc, (*resume_arg, span), Deep, flow_state);
734             }
735 
736             TerminatorKind::InlineAsm {
737                 template: _,
738                 operands,
739                 options: _,
740                 line_spans: _,
741                 destination: _,
742                 unwind: _,
743             } => {
744                 for op in operands {
745                     match op {
746                         InlineAsmOperand::In { reg: _, value } => {
747                             self.consume_operand(loc, (value, span), flow_state);
748                         }
749                         InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
750                             if let Some(place) = place {
751                                 self.mutate_place(loc, (*place, span), Shallow(None), flow_state);
752                             }
753                         }
754                         InlineAsmOperand::InOut { reg: _, late: _, in_value, out_place } => {
755                             self.consume_operand(loc, (in_value, span), flow_state);
756                             if let &Some(out_place) = out_place {
757                                 self.mutate_place(
758                                     loc,
759                                     (out_place, span),
760                                     Shallow(None),
761                                     flow_state,
762                                 );
763                             }
764                         }
765                         InlineAsmOperand::Const { value: _ }
766                         | InlineAsmOperand::SymFn { value: _ }
767                         | InlineAsmOperand::SymStatic { def_id: _ } => {}
768                     }
769                 }
770             }
771 
772             TerminatorKind::Goto { target: _ }
773             | TerminatorKind::Terminate
774             | TerminatorKind::Unreachable
775             | TerminatorKind::Resume
776             | TerminatorKind::Return
777             | TerminatorKind::GeneratorDrop
778             | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
779             | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
780                 // no data used, thus irrelevant to borrowck
781             }
782         }
783     }
784 
visit_terminator_after_primary_effect( &mut self, _results: &R, flow_state: &Flows<'cx, 'tcx>, term: &'cx Terminator<'tcx>, loc: Location, )785     fn visit_terminator_after_primary_effect(
786         &mut self,
787         _results: &R,
788         flow_state: &Flows<'cx, 'tcx>,
789         term: &'cx Terminator<'tcx>,
790         loc: Location,
791     ) {
792         let span = term.source_info.span;
793 
794         match term.kind {
795             TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
796                 if self.movable_generator {
797                     // Look for any active borrows to locals
798                     let borrow_set = self.borrow_set.clone();
799                     for i in flow_state.borrows.iter() {
800                         let borrow = &borrow_set[i];
801                         self.check_for_local_borrow(borrow, span);
802                     }
803                 }
804             }
805 
806             TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
807                 // Returning from the function implicitly kills storage for all locals and statics.
808                 // Often, the storage will already have been killed by an explicit
809                 // StorageDead, but we don't always emit those (notably on unwind paths),
810                 // so this "extra check" serves as a kind of backup.
811                 let borrow_set = self.borrow_set.clone();
812                 for i in flow_state.borrows.iter() {
813                     let borrow = &borrow_set[i];
814                     self.check_for_invalidation_at_exit(loc, borrow, span);
815                 }
816             }
817 
818             TerminatorKind::Terminate
819             | TerminatorKind::Assert { .. }
820             | TerminatorKind::Call { .. }
821             | TerminatorKind::Drop { .. }
822             | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
823             | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
824             | TerminatorKind::Goto { .. }
825             | TerminatorKind::SwitchInt { .. }
826             | TerminatorKind::Unreachable
827             | TerminatorKind::InlineAsm { .. } => {}
828         }
829     }
830 }
831 
832 use self::AccessDepth::{Deep, Shallow};
833 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
834 
835 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
836 enum ArtificialField {
837     ArrayLength,
838     ShallowBorrow,
839 }
840 
841 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
842 enum AccessDepth {
843     /// From the RFC: "A *shallow* access means that the immediate
844     /// fields reached at P are accessed, but references or pointers
845     /// found within are not dereferenced. Right now, the only access
846     /// that is shallow is an assignment like `x = ...;`, which would
847     /// be a *shallow write* of `x`."
848     Shallow(Option<ArtificialField>),
849 
850     /// From the RFC: "A *deep* access means that all data reachable
851     /// through the given place may be invalidated or accesses by
852     /// this action."
853     Deep,
854 
855     /// Access is Deep only when there is a Drop implementation that
856     /// can reach the data behind the reference.
857     Drop,
858 }
859 
860 /// Kind of access to a value: read or write
861 /// (For informational purposes only)
862 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
863 enum ReadOrWrite {
864     /// From the RFC: "A *read* means that the existing data may be
865     /// read, but will not be changed."
866     Read(ReadKind),
867 
868     /// From the RFC: "A *write* means that the data may be mutated to
869     /// new values or otherwise invalidated (for example, it could be
870     /// de-initialized, as in a move operation).
871     Write(WriteKind),
872 
873     /// For two-phase borrows, we distinguish a reservation (which is treated
874     /// like a Read) from an activation (which is treated like a write), and
875     /// each of those is furthermore distinguished from Reads/Writes above.
876     Reservation(WriteKind),
877     Activation(WriteKind, BorrowIndex),
878 }
879 
880 /// Kind of read access to a value
881 /// (For informational purposes only)
882 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
883 enum ReadKind {
884     Borrow(BorrowKind),
885     Copy,
886 }
887 
888 /// Kind of write access to a value
889 /// (For informational purposes only)
890 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
891 enum WriteKind {
892     StorageDeadOrDrop,
893     Replace,
894     MutableBorrow(BorrowKind),
895     Mutate,
896     Move,
897 }
898 
899 /// When checking permissions for a place access, this flag is used to indicate that an immutable
900 /// local place can be mutated.
901 //
902 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
903 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
904 //   `is_declared_mutable()`.
905 // - Take flow state into consideration in `is_assignable()` for local variables.
906 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
907 enum LocalMutationIsAllowed {
908     Yes,
909     /// We want use of immutable upvars to cause a "write to immutable upvar"
910     /// error, not an "reassignment" error.
911     ExceptUpvars,
912     No,
913 }
914 
915 #[derive(Copy, Clone, Debug)]
916 enum InitializationRequiringAction {
917     Borrow,
918     MatchOn,
919     Use,
920     Assignment,
921     PartialAssignment,
922 }
923 
924 #[derive(Debug)]
925 struct RootPlace<'tcx> {
926     place_local: Local,
927     place_projection: &'tcx [PlaceElem<'tcx>],
928     is_local_mutation_allowed: LocalMutationIsAllowed,
929 }
930 
931 impl InitializationRequiringAction {
as_noun(self) -> &'static str932     fn as_noun(self) -> &'static str {
933         match self {
934             InitializationRequiringAction::Borrow => "borrow",
935             InitializationRequiringAction::MatchOn => "use", // no good noun
936             InitializationRequiringAction::Use => "use",
937             InitializationRequiringAction::Assignment => "assign",
938             InitializationRequiringAction::PartialAssignment => "assign to part",
939         }
940     }
941 
as_verb_in_past_tense(self) -> &'static str942     fn as_verb_in_past_tense(self) -> &'static str {
943         match self {
944             InitializationRequiringAction::Borrow => "borrowed",
945             InitializationRequiringAction::MatchOn => "matched on",
946             InitializationRequiringAction::Use => "used",
947             InitializationRequiringAction::Assignment => "assigned",
948             InitializationRequiringAction::PartialAssignment => "partially assigned",
949         }
950     }
951 
as_general_verb_in_past_tense(self) -> &'static str952     fn as_general_verb_in_past_tense(self) -> &'static str {
953         match self {
954             InitializationRequiringAction::Borrow
955             | InitializationRequiringAction::MatchOn
956             | InitializationRequiringAction::Use => "used",
957             InitializationRequiringAction::Assignment => "assigned",
958             InitializationRequiringAction::PartialAssignment => "partially assigned",
959         }
960     }
961 }
962 
963 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
body(&self) -> &'cx Body<'tcx>964     fn body(&self) -> &'cx Body<'tcx> {
965         self.body
966     }
967 
968     /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
969     /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
970     /// place is initialized and (b) it is not borrowed in some way that would prevent this
971     /// access.
972     ///
973     /// Returns `true` if an error is reported.
access_place( &mut self, location: Location, place_span: (Place<'tcx>, Span), kind: (AccessDepth, ReadOrWrite), is_local_mutation_allowed: LocalMutationIsAllowed, flow_state: &Flows<'cx, 'tcx>, )974     fn access_place(
975         &mut self,
976         location: Location,
977         place_span: (Place<'tcx>, Span),
978         kind: (AccessDepth, ReadOrWrite),
979         is_local_mutation_allowed: LocalMutationIsAllowed,
980         flow_state: &Flows<'cx, 'tcx>,
981     ) {
982         let (sd, rw) = kind;
983 
984         if let Activation(_, borrow_index) = rw {
985             if self.reservation_error_reported.contains(&place_span.0) {
986                 debug!(
987                     "skipping access_place for activation of invalid reservation \
988                      place: {:?} borrow_index: {:?}",
989                     place_span.0, borrow_index
990                 );
991                 return;
992             }
993         }
994 
995         // Check is_empty() first because it's the common case, and doing that
996         // way we avoid the clone() call.
997         if !self.access_place_error_reported.is_empty()
998             && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
999         {
1000             debug!(
1001                 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
1002                 place_span, kind
1003             );
1004             return;
1005         }
1006 
1007         let mutability_error = self.check_access_permissions(
1008             place_span,
1009             rw,
1010             is_local_mutation_allowed,
1011             flow_state,
1012             location,
1013         );
1014         let conflict_error =
1015             self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
1016 
1017         if conflict_error || mutability_error {
1018             debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
1019             self.access_place_error_reported.insert((place_span.0, place_span.1));
1020         }
1021     }
1022 
1023     #[instrument(level = "debug", skip(self, flow_state))]
check_access_for_conflict( &mut self, location: Location, place_span: (Place<'tcx>, Span), sd: AccessDepth, rw: ReadOrWrite, flow_state: &Flows<'cx, 'tcx>, ) -> bool1024     fn check_access_for_conflict(
1025         &mut self,
1026         location: Location,
1027         place_span: (Place<'tcx>, Span),
1028         sd: AccessDepth,
1029         rw: ReadOrWrite,
1030         flow_state: &Flows<'cx, 'tcx>,
1031     ) -> bool {
1032         let mut error_reported = false;
1033         let tcx = self.infcx.tcx;
1034         let body = self.body;
1035         let borrow_set = self.borrow_set.clone();
1036 
1037         // Use polonius output if it has been enabled.
1038         let polonius_output = self.polonius_output.clone();
1039         let borrows_in_scope = if let Some(polonius) = &polonius_output {
1040             let location = self.location_table.start_index(location);
1041             Either::Left(polonius.errors_at(location).iter().copied())
1042         } else {
1043             Either::Right(flow_state.borrows.iter())
1044         };
1045 
1046         each_borrow_involving_path(
1047             self,
1048             tcx,
1049             body,
1050             location,
1051             (sd, place_span.0),
1052             &borrow_set,
1053             borrows_in_scope,
1054             |this, borrow_index, borrow| match (rw, borrow.kind) {
1055                 // Obviously an activation is compatible with its own
1056                 // reservation (or even prior activating uses of same
1057                 // borrow); so don't check if they interfere.
1058                 //
1059                 // NOTE: *reservations* do conflict with themselves;
1060                 // thus aren't injecting unsoundness w/ this check.)
1061                 (Activation(_, activating), _) if activating == borrow_index => {
1062                     debug!(
1063                         "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1064                          skipping {:?} b/c activation of same borrow_index",
1065                         place_span,
1066                         sd,
1067                         rw,
1068                         (borrow_index, borrow),
1069                     );
1070                     Control::Continue
1071                 }
1072 
1073                 (Read(_), BorrowKind::Shared | BorrowKind::Shallow)
1074                 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
1075                     Control::Continue
1076                 }
1077 
1078                 (Reservation(_), BorrowKind::Shallow | BorrowKind::Shared) => {
1079                     // This used to be a future compatibility warning (to be
1080                     // disallowed on NLL). See rust-lang/rust#56254
1081                     Control::Continue
1082                 }
1083 
1084                 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1085                     // Handled by initialization checks.
1086                     Control::Continue
1087                 }
1088 
1089                 (Read(kind), BorrowKind::Mut { .. }) => {
1090                     // Reading from mere reservations of mutable-borrows is OK.
1091                     if !is_active(this.dominators(), borrow, location) {
1092                         assert!(allow_two_phase_borrow(borrow.kind));
1093                         return Control::Continue;
1094                     }
1095 
1096                     error_reported = true;
1097                     match kind {
1098                         ReadKind::Copy => {
1099                             let err = this
1100                                 .report_use_while_mutably_borrowed(location, place_span, borrow);
1101                             this.buffer_error(err);
1102                         }
1103                         ReadKind::Borrow(bk) => {
1104                             let err =
1105                                 this.report_conflicting_borrow(location, place_span, bk, borrow);
1106                             this.buffer_error(err);
1107                         }
1108                     }
1109                     Control::Break
1110                 }
1111 
1112                 (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1113                     match rw {
1114                         Reservation(..) => {
1115                             debug!(
1116                                 "recording invalid reservation of \
1117                                  place: {:?}",
1118                                 place_span.0
1119                             );
1120                             this.reservation_error_reported.insert(place_span.0);
1121                         }
1122                         Activation(_, activating) => {
1123                             debug!(
1124                                 "observing check_place for activation of \
1125                                  borrow_index: {:?}",
1126                                 activating
1127                             );
1128                         }
1129                         Read(..) | Write(..) => {}
1130                     }
1131 
1132                     error_reported = true;
1133                     match kind {
1134                         WriteKind::MutableBorrow(bk) => {
1135                             let err =
1136                                 this.report_conflicting_borrow(location, place_span, bk, borrow);
1137                             this.buffer_error(err);
1138                         }
1139                         WriteKind::StorageDeadOrDrop => this
1140                             .report_borrowed_value_does_not_live_long_enough(
1141                                 location,
1142                                 borrow,
1143                                 place_span,
1144                                 Some(WriteKind::StorageDeadOrDrop),
1145                             ),
1146                         WriteKind::Mutate => {
1147                             this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1148                         }
1149                         WriteKind::Move => {
1150                             this.report_move_out_while_borrowed(location, place_span, borrow)
1151                         }
1152                         WriteKind::Replace => {
1153                             this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1154                         }
1155                     }
1156                     Control::Break
1157                 }
1158             },
1159         );
1160 
1161         error_reported
1162     }
1163 
mutate_place( &mut self, location: Location, place_span: (Place<'tcx>, Span), kind: AccessDepth, flow_state: &Flows<'cx, 'tcx>, )1164     fn mutate_place(
1165         &mut self,
1166         location: Location,
1167         place_span: (Place<'tcx>, Span),
1168         kind: AccessDepth,
1169         flow_state: &Flows<'cx, 'tcx>,
1170     ) {
1171         // Write of P[i] or *P requires P init'd.
1172         self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1173 
1174         self.access_place(
1175             location,
1176             place_span,
1177             (kind, Write(WriteKind::Mutate)),
1178             LocalMutationIsAllowed::No,
1179             flow_state,
1180         );
1181     }
1182 
consume_rvalue( &mut self, location: Location, (rvalue, span): (&'cx Rvalue<'tcx>, Span), flow_state: &Flows<'cx, 'tcx>, )1183     fn consume_rvalue(
1184         &mut self,
1185         location: Location,
1186         (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1187         flow_state: &Flows<'cx, 'tcx>,
1188     ) {
1189         match rvalue {
1190             &Rvalue::Ref(_ /*rgn*/, bk, place) => {
1191                 let access_kind = match bk {
1192                     BorrowKind::Shallow => {
1193                         (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1194                     }
1195                     BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1196                     BorrowKind::Mut { .. } => {
1197                         let wk = WriteKind::MutableBorrow(bk);
1198                         if allow_two_phase_borrow(bk) {
1199                             (Deep, Reservation(wk))
1200                         } else {
1201                             (Deep, Write(wk))
1202                         }
1203                     }
1204                 };
1205 
1206                 self.access_place(
1207                     location,
1208                     (place, span),
1209                     access_kind,
1210                     LocalMutationIsAllowed::No,
1211                     flow_state,
1212                 );
1213 
1214                 let action = if bk == BorrowKind::Shallow {
1215                     InitializationRequiringAction::MatchOn
1216                 } else {
1217                     InitializationRequiringAction::Borrow
1218                 };
1219 
1220                 self.check_if_path_or_subpath_is_moved(
1221                     location,
1222                     action,
1223                     (place.as_ref(), span),
1224                     flow_state,
1225                 );
1226             }
1227 
1228             &Rvalue::AddressOf(mutability, place) => {
1229                 let access_kind = match mutability {
1230                     Mutability::Mut => (
1231                         Deep,
1232                         Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1233                             kind: MutBorrowKind::Default,
1234                         })),
1235                     ),
1236                     Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1237                 };
1238 
1239                 self.access_place(
1240                     location,
1241                     (place, span),
1242                     access_kind,
1243                     LocalMutationIsAllowed::No,
1244                     flow_state,
1245                 );
1246 
1247                 self.check_if_path_or_subpath_is_moved(
1248                     location,
1249                     InitializationRequiringAction::Borrow,
1250                     (place.as_ref(), span),
1251                     flow_state,
1252                 );
1253             }
1254 
1255             Rvalue::ThreadLocalRef(_) => {}
1256 
1257             Rvalue::Use(operand)
1258             | Rvalue::Repeat(operand, _)
1259             | Rvalue::UnaryOp(_ /*un_op*/, operand)
1260             | Rvalue::Cast(_ /*cast_kind*/, operand, _ /*ty*/)
1261             | Rvalue::ShallowInitBox(operand, _ /*ty*/) => {
1262                 self.consume_operand(location, (operand, span), flow_state)
1263             }
1264 
1265             &Rvalue::CopyForDeref(place) => {
1266                 self.access_place(
1267                     location,
1268                     (place, span),
1269                     (Deep, Read(ReadKind::Copy)),
1270                     LocalMutationIsAllowed::No,
1271                     flow_state,
1272                 );
1273 
1274                 // Finally, check if path was already moved.
1275                 self.check_if_path_or_subpath_is_moved(
1276                     location,
1277                     InitializationRequiringAction::Use,
1278                     (place.as_ref(), span),
1279                     flow_state,
1280                 );
1281             }
1282 
1283             &(Rvalue::Len(place) | Rvalue::Discriminant(place)) => {
1284                 let af = match *rvalue {
1285                     Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1286                     Rvalue::Discriminant(..) => None,
1287                     _ => unreachable!(),
1288                 };
1289                 self.access_place(
1290                     location,
1291                     (place, span),
1292                     (Shallow(af), Read(ReadKind::Copy)),
1293                     LocalMutationIsAllowed::No,
1294                     flow_state,
1295                 );
1296                 self.check_if_path_or_subpath_is_moved(
1297                     location,
1298                     InitializationRequiringAction::Use,
1299                     (place.as_ref(), span),
1300                     flow_state,
1301                 );
1302             }
1303 
1304             Rvalue::BinaryOp(_bin_op, box (operand1, operand2))
1305             | Rvalue::CheckedBinaryOp(_bin_op, box (operand1, operand2)) => {
1306                 self.consume_operand(location, (operand1, span), flow_state);
1307                 self.consume_operand(location, (operand2, span), flow_state);
1308             }
1309 
1310             Rvalue::NullaryOp(_op, _ty) => {
1311                 // nullary ops take no dynamic input; no borrowck effect.
1312             }
1313 
1314             Rvalue::Aggregate(aggregate_kind, operands) => {
1315                 // We need to report back the list of mutable upvars that were
1316                 // moved into the closure and subsequently used by the closure,
1317                 // in order to populate our used_mut set.
1318                 match **aggregate_kind {
1319                     AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
1320                         let def_id = def_id.expect_local();
1321                         let BorrowCheckResult { used_mut_upvars, .. } =
1322                             self.infcx.tcx.mir_borrowck(def_id);
1323                         debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1324                         for field in used_mut_upvars {
1325                             self.propagate_closure_used_mut_upvar(&operands[*field]);
1326                         }
1327                     }
1328                     AggregateKind::Adt(..)
1329                     | AggregateKind::Array(..)
1330                     | AggregateKind::Tuple { .. } => (),
1331                 }
1332 
1333                 for operand in operands {
1334                     self.consume_operand(location, (operand, span), flow_state);
1335                 }
1336             }
1337         }
1338     }
1339 
propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>)1340     fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1341         let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1342             // We have three possibilities here:
1343             // a. We are modifying something through a mut-ref
1344             // b. We are modifying something that is local to our parent
1345             // c. Current body is a nested closure, and we are modifying path starting from
1346             //    a Place captured by our parent closure.
1347 
1348             // Handle (c), the path being modified is exactly the path captured by our parent
1349             if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1350                 this.used_mut_upvars.push(field);
1351                 return;
1352             }
1353 
1354             for (place_ref, proj) in place.iter_projections().rev() {
1355                 // Handle (a)
1356                 if proj == ProjectionElem::Deref {
1357                     match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1358                         // We aren't modifying a variable directly
1359                         ty::Ref(_, _, hir::Mutability::Mut) => return,
1360 
1361                         _ => {}
1362                     }
1363                 }
1364 
1365                 // Handle (c)
1366                 if let Some(field) = this.is_upvar_field_projection(place_ref) {
1367                     this.used_mut_upvars.push(field);
1368                     return;
1369                 }
1370             }
1371 
1372             // Handle(b)
1373             this.used_mut.insert(place.local);
1374         };
1375 
1376         // This relies on the current way that by-value
1377         // captures of a closure are copied/moved directly
1378         // when generating MIR.
1379         match *operand {
1380             Operand::Move(place) | Operand::Copy(place) => {
1381                 match place.as_local() {
1382                     Some(local) if !self.body.local_decls[local].is_user_variable() => {
1383                         if self.body.local_decls[local].ty.is_mutable_ptr() {
1384                             // The variable will be marked as mutable by the borrow.
1385                             return;
1386                         }
1387                         // This is an edge case where we have a `move` closure
1388                         // inside a non-move closure, and the inner closure
1389                         // contains a mutation:
1390                         //
1391                         // let mut i = 0;
1392                         // || { move || { i += 1; }; };
1393                         //
1394                         // In this case our usual strategy of assuming that the
1395                         // variable will be captured by mutable reference is
1396                         // wrong, since `i` can be copied into the inner
1397                         // closure from a shared reference.
1398                         //
1399                         // As such we have to search for the local that this
1400                         // capture comes from and mark it as being used as mut.
1401 
1402                         let temp_mpi = self.move_data.rev_lookup.find_local(local);
1403                         let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1404                             &self.move_data.inits[init_index]
1405                         } else {
1406                             bug!("temporary should be initialized exactly once")
1407                         };
1408 
1409                         let InitLocation::Statement(loc) = init.location else {
1410                             bug!("temporary initialized in arguments")
1411                         };
1412 
1413                         let body = self.body;
1414                         let bbd = &body[loc.block];
1415                         let stmt = &bbd.statements[loc.statement_index];
1416                         debug!("temporary assigned in: stmt={:?}", stmt);
1417 
1418                         if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, source))) = stmt.kind
1419                         {
1420                             propagate_closure_used_mut_place(self, source);
1421                         } else {
1422                             bug!(
1423                                 "closures should only capture user variables \
1424                                  or references to user variables"
1425                             );
1426                         }
1427                     }
1428                     _ => propagate_closure_used_mut_place(self, place),
1429                 }
1430             }
1431             Operand::Constant(..) => {}
1432         }
1433     }
1434 
consume_operand( &mut self, location: Location, (operand, span): (&'cx Operand<'tcx>, Span), flow_state: &Flows<'cx, 'tcx>, )1435     fn consume_operand(
1436         &mut self,
1437         location: Location,
1438         (operand, span): (&'cx Operand<'tcx>, Span),
1439         flow_state: &Flows<'cx, 'tcx>,
1440     ) {
1441         match *operand {
1442             Operand::Copy(place) => {
1443                 // copy of place: check if this is "copy of frozen path"
1444                 // (FIXME: see check_loans.rs)
1445                 self.access_place(
1446                     location,
1447                     (place, span),
1448                     (Deep, Read(ReadKind::Copy)),
1449                     LocalMutationIsAllowed::No,
1450                     flow_state,
1451                 );
1452 
1453                 // Finally, check if path was already moved.
1454                 self.check_if_path_or_subpath_is_moved(
1455                     location,
1456                     InitializationRequiringAction::Use,
1457                     (place.as_ref(), span),
1458                     flow_state,
1459                 );
1460             }
1461             Operand::Move(place) => {
1462                 // move of place: check if this is move of already borrowed path
1463                 self.access_place(
1464                     location,
1465                     (place, span),
1466                     (Deep, Write(WriteKind::Move)),
1467                     LocalMutationIsAllowed::Yes,
1468                     flow_state,
1469                 );
1470 
1471                 // Finally, check if path was already moved.
1472                 self.check_if_path_or_subpath_is_moved(
1473                     location,
1474                     InitializationRequiringAction::Use,
1475                     (place.as_ref(), span),
1476                     flow_state,
1477                 );
1478             }
1479             Operand::Constant(_) => {}
1480         }
1481     }
1482 
1483     /// Checks whether a borrow of this place is invalidated when the function
1484     /// exits
1485     #[instrument(level = "debug", skip(self))]
check_for_invalidation_at_exit( &mut self, location: Location, borrow: &BorrowData<'tcx>, span: Span, )1486     fn check_for_invalidation_at_exit(
1487         &mut self,
1488         location: Location,
1489         borrow: &BorrowData<'tcx>,
1490         span: Span,
1491     ) {
1492         let place = borrow.borrowed_place;
1493         let mut root_place = PlaceRef { local: place.local, projection: &[] };
1494 
1495         // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1496         // we just know that all locals are dropped at function exit (otherwise
1497         // we'll have a memory leak) and assume that all statics have a destructor.
1498         //
1499         // FIXME: allow thread-locals to borrow other thread locals?
1500 
1501         let (might_be_alive, will_be_dropped) =
1502             if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1503                 // Thread-locals might be dropped after the function exits
1504                 // We have to dereference the outer reference because
1505                 // borrows don't conflict behind shared references.
1506                 root_place.projection = TyCtxtConsts::DEREF_PROJECTION;
1507                 (true, true)
1508             } else {
1509                 (false, self.locals_are_invalidated_at_exit)
1510             };
1511 
1512         if !will_be_dropped {
1513             debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
1514             return;
1515         }
1516 
1517         let sd = if might_be_alive { Deep } else { Shallow(None) };
1518 
1519         if places_conflict::borrow_conflicts_with_place(
1520             self.infcx.tcx,
1521             &self.body,
1522             place,
1523             borrow.kind,
1524             root_place,
1525             sd,
1526             places_conflict::PlaceConflictBias::Overlap,
1527         ) {
1528             debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1529             // FIXME: should be talking about the region lifetime instead
1530             // of just a span here.
1531             let span = self.infcx.tcx.sess.source_map().end_point(span);
1532             self.report_borrowed_value_does_not_live_long_enough(
1533                 location,
1534                 borrow,
1535                 (place, span),
1536                 None,
1537             )
1538         }
1539     }
1540 
1541     /// Reports an error if this is a borrow of local data.
1542     /// This is called for all Yield expressions on movable generators
check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span)1543     fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1544         debug!("check_for_local_borrow({:?})", borrow);
1545 
1546         if borrow_of_local_data(borrow.borrowed_place) {
1547             let err = self.cannot_borrow_across_generator_yield(
1548                 self.retrieve_borrow_spans(borrow).var_or_use(),
1549                 yield_span,
1550             );
1551 
1552             self.buffer_error(err);
1553         }
1554     }
1555 
check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>)1556     fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1557         // Two-phase borrow support: For each activation that is newly
1558         // generated at this statement, check if it interferes with
1559         // another borrow.
1560         let borrow_set = self.borrow_set.clone();
1561         for &borrow_index in borrow_set.activations_at_location(location) {
1562             let borrow = &borrow_set[borrow_index];
1563 
1564             // only mutable borrows should be 2-phase
1565             assert!(match borrow.kind {
1566                 BorrowKind::Shared | BorrowKind::Shallow => false,
1567                 BorrowKind::Mut { .. } => true,
1568             });
1569 
1570             self.access_place(
1571                 location,
1572                 (borrow.borrowed_place, span),
1573                 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1574                 LocalMutationIsAllowed::No,
1575                 flow_state,
1576             );
1577             // We do not need to call `check_if_path_or_subpath_is_moved`
1578             // again, as we already called it when we made the
1579             // initial reservation.
1580         }
1581     }
1582 
check_if_full_path_is_moved( &mut self, location: Location, desired_action: InitializationRequiringAction, place_span: (PlaceRef<'tcx>, Span), flow_state: &Flows<'cx, 'tcx>, )1583     fn check_if_full_path_is_moved(
1584         &mut self,
1585         location: Location,
1586         desired_action: InitializationRequiringAction,
1587         place_span: (PlaceRef<'tcx>, Span),
1588         flow_state: &Flows<'cx, 'tcx>,
1589     ) {
1590         let maybe_uninits = &flow_state.uninits;
1591 
1592         // Bad scenarios:
1593         //
1594         // 1. Move of `a.b.c`, use of `a.b.c`
1595         // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1596         // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1597         //    partial initialization support, one might have `a.x`
1598         //    initialized but not `a.b`.
1599         //
1600         // OK scenarios:
1601         //
1602         // 4. Move of `a.b.c`, use of `a.b.d`
1603         // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1604         // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1605         //    must have been initialized for the use to be sound.
1606         // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1607 
1608         // The dataflow tracks shallow prefixes distinctly (that is,
1609         // field-accesses on P distinctly from P itself), in order to
1610         // track substructure initialization separately from the whole
1611         // structure.
1612         //
1613         // E.g., when looking at (*a.b.c).d, if the closest prefix for
1614         // which we have a MovePath is `a.b`, then that means that the
1615         // initialization state of `a.b` is all we need to inspect to
1616         // know if `a.b.c` is valid (and from that we infer that the
1617         // dereference and `.d` access is also valid, since we assume
1618         // `a.b.c` is assigned a reference to an initialized and
1619         // well-formed record structure.)
1620 
1621         // Therefore, if we seek out the *closest* prefix for which we
1622         // have a MovePath, that should capture the initialization
1623         // state for the place scenario.
1624         //
1625         // This code covers scenarios 1, 2, and 3.
1626 
1627         debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1628         let (prefix, mpi) = self.move_path_closest_to(place_span.0);
1629         if maybe_uninits.contains(mpi) {
1630             self.report_use_of_moved_or_uninitialized(
1631                 location,
1632                 desired_action,
1633                 (prefix, place_span.0, place_span.1),
1634                 mpi,
1635             );
1636         } // Only query longest prefix with a MovePath, not further
1637         // ancestors; dataflow recurs on children when parents
1638         // move (to support partial (re)inits).
1639         //
1640         // (I.e., querying parents breaks scenario 7; but may want
1641         // to do such a query based on partial-init feature-gate.)
1642     }
1643 
1644     /// Subslices correspond to multiple move paths, so we iterate through the
1645     /// elements of the base array. For each element we check
1646     ///
1647     /// * Does this element overlap with our slice.
1648     /// * Is any part of it uninitialized.
check_if_subslice_element_is_moved( &mut self, location: Location, desired_action: InitializationRequiringAction, place_span: (PlaceRef<'tcx>, Span), maybe_uninits: &ChunkedBitSet<MovePathIndex>, from: u64, to: u64, )1649     fn check_if_subslice_element_is_moved(
1650         &mut self,
1651         location: Location,
1652         desired_action: InitializationRequiringAction,
1653         place_span: (PlaceRef<'tcx>, Span),
1654         maybe_uninits: &ChunkedBitSet<MovePathIndex>,
1655         from: u64,
1656         to: u64,
1657     ) {
1658         if let Some(mpi) = self.move_path_for_place(place_span.0) {
1659             let move_paths = &self.move_data.move_paths;
1660 
1661             let root_path = &move_paths[mpi];
1662             for (child_mpi, child_move_path) in root_path.children(move_paths) {
1663                 let last_proj = child_move_path.place.projection.last().unwrap();
1664                 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
1665                     debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
1666 
1667                     if (from..to).contains(offset) {
1668                         let uninit_child =
1669                             self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
1670                                 maybe_uninits.contains(mpi)
1671                             });
1672 
1673                         if let Some(uninit_child) = uninit_child {
1674                             self.report_use_of_moved_or_uninitialized(
1675                                 location,
1676                                 desired_action,
1677                                 (place_span.0, place_span.0, place_span.1),
1678                                 uninit_child,
1679                             );
1680                             return; // don't bother finding other problems.
1681                         }
1682                     }
1683                 }
1684             }
1685         }
1686     }
1687 
check_if_path_or_subpath_is_moved( &mut self, location: Location, desired_action: InitializationRequiringAction, place_span: (PlaceRef<'tcx>, Span), flow_state: &Flows<'cx, 'tcx>, )1688     fn check_if_path_or_subpath_is_moved(
1689         &mut self,
1690         location: Location,
1691         desired_action: InitializationRequiringAction,
1692         place_span: (PlaceRef<'tcx>, Span),
1693         flow_state: &Flows<'cx, 'tcx>,
1694     ) {
1695         let maybe_uninits = &flow_state.uninits;
1696 
1697         // Bad scenarios:
1698         //
1699         // 1. Move of `a.b.c`, use of `a` or `a.b`
1700         //    partial initialization support, one might have `a.x`
1701         //    initialized but not `a.b`.
1702         // 2. All bad scenarios from `check_if_full_path_is_moved`
1703         //
1704         // OK scenarios:
1705         //
1706         // 3. Move of `a.b.c`, use of `a.b.d`
1707         // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1708         // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1709         //    must have been initialized for the use to be sound.
1710         // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1711 
1712         self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1713 
1714         if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
1715             place_span.0.last_projection()
1716         {
1717             let place_ty = place_base.ty(self.body(), self.infcx.tcx);
1718             if let ty::Array(..) = place_ty.ty.kind() {
1719                 self.check_if_subslice_element_is_moved(
1720                     location,
1721                     desired_action,
1722                     (place_base, place_span.1),
1723                     maybe_uninits,
1724                     from,
1725                     to,
1726                 );
1727                 return;
1728             }
1729         }
1730 
1731         // A move of any shallow suffix of `place` also interferes
1732         // with an attempt to use `place`. This is scenario 3 above.
1733         //
1734         // (Distinct from handling of scenarios 1+2+4 above because
1735         // `place` does not interfere with suffixes of its prefixes,
1736         // e.g., `a.b.c` does not interfere with `a.b.d`)
1737         //
1738         // This code covers scenario 1.
1739 
1740         debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1741         if let Some(mpi) = self.move_path_for_place(place_span.0) {
1742             let uninit_mpi = self
1743                 .move_data
1744                 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
1745 
1746             if let Some(uninit_mpi) = uninit_mpi {
1747                 self.report_use_of_moved_or_uninitialized(
1748                     location,
1749                     desired_action,
1750                     (place_span.0, place_span.0, place_span.1),
1751                     uninit_mpi,
1752                 );
1753                 return; // don't bother finding other problems.
1754             }
1755         }
1756     }
1757 
1758     /// Currently MoveData does not store entries for all places in
1759     /// the input MIR. For example it will currently filter out
1760     /// places that are Copy; thus we do not track places of shared
1761     /// reference type. This routine will walk up a place along its
1762     /// prefixes, searching for a foundational place that *is*
1763     /// tracked in the MoveData.
1764     ///
1765     /// An Err result includes a tag indicated why the search failed.
1766     /// Currently this can only occur if the place is built off of a
1767     /// static variable, as we do not track those in the MoveData.
move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex)1768     fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
1769         match self.move_data.rev_lookup.find(place) {
1770             LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
1771                 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
1772             }
1773             LookupResult::Parent(None) => panic!("should have move path for every Local"),
1774         }
1775     }
1776 
move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex>1777     fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
1778         // If returns None, then there is no move path corresponding
1779         // to a direct owner of `place` (which means there is nothing
1780         // that borrowck tracks for its analysis).
1781 
1782         match self.move_data.rev_lookup.find(place) {
1783             LookupResult::Parent(_) => None,
1784             LookupResult::Exact(mpi) => Some(mpi),
1785         }
1786     }
1787 
check_if_assigned_path_is_moved( &mut self, location: Location, (place, span): (Place<'tcx>, Span), flow_state: &Flows<'cx, 'tcx>, )1788     fn check_if_assigned_path_is_moved(
1789         &mut self,
1790         location: Location,
1791         (place, span): (Place<'tcx>, Span),
1792         flow_state: &Flows<'cx, 'tcx>,
1793     ) {
1794         debug!("check_if_assigned_path_is_moved place: {:?}", place);
1795 
1796         // None case => assigning to `x` does not require `x` be initialized.
1797         for (place_base, elem) in place.iter_projections().rev() {
1798             match elem {
1799                 ProjectionElem::Index(_/*operand*/) |
1800                 ProjectionElem::OpaqueCast(_) |
1801                 ProjectionElem::ConstantIndex { .. } |
1802                 // assigning to P[i] requires P to be valid.
1803                 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1804                 // assigning to (P->variant) is okay if assigning to `P` is okay
1805                 //
1806                 // FIXME: is this true even if P is an adt with a dtor?
1807                 { }
1808 
1809                 // assigning to (*P) requires P to be initialized
1810                 ProjectionElem::Deref => {
1811                     self.check_if_full_path_is_moved(
1812                         location, InitializationRequiringAction::Use,
1813                         (place_base, span), flow_state);
1814                     // (base initialized; no need to
1815                     // recur further)
1816                     break;
1817                 }
1818 
1819                 ProjectionElem::Subslice { .. } => {
1820                     panic!("we don't allow assignments to subslices, location: {:?}",
1821                            location);
1822                 }
1823 
1824                 ProjectionElem::Field(..) => {
1825                     // if type of `P` has a dtor, then
1826                     // assigning to `P.f` requires `P` itself
1827                     // be already initialized
1828                     let tcx = self.infcx.tcx;
1829                     let base_ty = place_base.ty(self.body(), tcx).ty;
1830                     match base_ty.kind() {
1831                         ty::Adt(def, _) if def.has_dtor(tcx) => {
1832                             self.check_if_path_or_subpath_is_moved(
1833                                 location, InitializationRequiringAction::Assignment,
1834                                 (place_base, span), flow_state);
1835 
1836                             // (base initialized; no need to
1837                             // recur further)
1838                             break;
1839                         }
1840 
1841                         // Once `let s; s.x = V; read(s.x);`,
1842                         // is allowed, remove this match arm.
1843                         ty::Adt(..) | ty::Tuple(..) => {
1844                             check_parent_of_field(self, location, place_base, span, flow_state);
1845                         }
1846 
1847                         _ => {}
1848                     }
1849                 }
1850             }
1851         }
1852 
1853         fn check_parent_of_field<'cx, 'tcx>(
1854             this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1855             location: Location,
1856             base: PlaceRef<'tcx>,
1857             span: Span,
1858             flow_state: &Flows<'cx, 'tcx>,
1859         ) {
1860             // rust-lang/rust#21232: Until Rust allows reads from the
1861             // initialized parts of partially initialized structs, we
1862             // will, starting with the 2018 edition, reject attempts
1863             // to write to structs that are not fully initialized.
1864             //
1865             // In other words, *until* we allow this:
1866             //
1867             // 1. `let mut s; s.x = Val; read(s.x);`
1868             //
1869             // we will for now disallow this:
1870             //
1871             // 2. `let mut s; s.x = Val;`
1872             //
1873             // and also this:
1874             //
1875             // 3. `let mut s = ...; drop(s); s.x=Val;`
1876             //
1877             // This does not use check_if_path_or_subpath_is_moved,
1878             // because we want to *allow* reinitializations of fields:
1879             // e.g., want to allow
1880             //
1881             // `let mut s = ...; drop(s.x); s.x=Val;`
1882             //
1883             // This does not use check_if_full_path_is_moved on
1884             // `base`, because that would report an error about the
1885             // `base` as a whole, but in this scenario we *really*
1886             // want to report an error about the actual thing that was
1887             // moved, which may be some prefix of `base`.
1888 
1889             // Shallow so that we'll stop at any dereference; we'll
1890             // report errors about issues with such bases elsewhere.
1891             let maybe_uninits = &flow_state.uninits;
1892 
1893             // Find the shortest uninitialized prefix you can reach
1894             // without going over a Deref.
1895             let mut shortest_uninit_seen = None;
1896             for prefix in this.prefixes(base, PrefixSet::Shallow) {
1897                 let Some(mpi) = this.move_path_for_place(prefix) else { continue };
1898 
1899                 if maybe_uninits.contains(mpi) {
1900                     debug!(
1901                         "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1902                         shortest_uninit_seen,
1903                         Some((prefix, mpi))
1904                     );
1905                     shortest_uninit_seen = Some((prefix, mpi));
1906                 } else {
1907                     debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1908                 }
1909             }
1910 
1911             if let Some((prefix, mpi)) = shortest_uninit_seen {
1912                 // Check for a reassignment into an uninitialized field of a union (for example,
1913                 // after a move out). In this case, do not report an error here. There is an
1914                 // exception, if this is the first assignment into the union (that is, there is
1915                 // no move out from an earlier location) then this is an attempt at initialization
1916                 // of the union - we should error in that case.
1917                 let tcx = this.infcx.tcx;
1918                 if base.ty(this.body(), tcx).ty.is_union() {
1919                     if this.move_data.path_map[mpi].iter().any(|moi| {
1920                         this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
1921                     }) {
1922                         return;
1923                     }
1924                 }
1925 
1926                 this.report_use_of_moved_or_uninitialized(
1927                     location,
1928                     InitializationRequiringAction::PartialAssignment,
1929                     (prefix, base, span),
1930                     mpi,
1931                 );
1932 
1933                 // rust-lang/rust#21232, #54499, #54986: during period where we reject
1934                 // partial initialization, do not complain about unnecessary `mut` on
1935                 // an attempt to do a partial initialization.
1936                 this.used_mut.insert(base.local);
1937             }
1938         }
1939     }
1940 
1941     /// Checks the permissions for the given place and read or write kind
1942     ///
1943     /// Returns `true` if an error is reported.
check_access_permissions( &mut self, (place, span): (Place<'tcx>, Span), kind: ReadOrWrite, is_local_mutation_allowed: LocalMutationIsAllowed, flow_state: &Flows<'cx, 'tcx>, location: Location, ) -> bool1944     fn check_access_permissions(
1945         &mut self,
1946         (place, span): (Place<'tcx>, Span),
1947         kind: ReadOrWrite,
1948         is_local_mutation_allowed: LocalMutationIsAllowed,
1949         flow_state: &Flows<'cx, 'tcx>,
1950         location: Location,
1951     ) -> bool {
1952         debug!(
1953             "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1954             place, kind, is_local_mutation_allowed
1955         );
1956 
1957         let error_access;
1958         let the_place_err;
1959 
1960         match kind {
1961             Reservation(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind }))
1962             | Write(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind })) => {
1963                 let is_local_mutation_allowed = match mut_borrow_kind {
1964                     // `ClosureCapture` is used for mutable variable with a immutable binding.
1965                     // This is only behaviour difference between `ClosureCapture` and mutable borrows.
1966                     MutBorrowKind::ClosureCapture => LocalMutationIsAllowed::Yes,
1967                     MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow => {
1968                         is_local_mutation_allowed
1969                     }
1970                 };
1971                 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1972                     Ok(root_place) => {
1973                         self.add_used_mut(root_place, flow_state);
1974                         return false;
1975                     }
1976                     Err(place_err) => {
1977                         error_access = AccessKind::MutableBorrow;
1978                         the_place_err = place_err;
1979                     }
1980                 }
1981             }
1982             Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1983                 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1984                     Ok(root_place) => {
1985                         self.add_used_mut(root_place, flow_state);
1986                         return false;
1987                     }
1988                     Err(place_err) => {
1989                         error_access = AccessKind::Mutate;
1990                         the_place_err = place_err;
1991                     }
1992                 }
1993             }
1994 
1995             Reservation(
1996                 WriteKind::Move
1997                 | WriteKind::Replace
1998                 | WriteKind::StorageDeadOrDrop
1999                 | WriteKind::MutableBorrow(BorrowKind::Shared)
2000                 | WriteKind::MutableBorrow(BorrowKind::Shallow),
2001             )
2002             | Write(
2003                 WriteKind::Move
2004                 | WriteKind::Replace
2005                 | WriteKind::StorageDeadOrDrop
2006                 | WriteKind::MutableBorrow(BorrowKind::Shared)
2007                 | WriteKind::MutableBorrow(BorrowKind::Shallow),
2008             ) => {
2009                 if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err()
2010                     && !self.has_buffered_errors()
2011                 {
2012                     // rust-lang/rust#46908: In pure NLL mode this code path should be
2013                     // unreachable, but we use `delay_span_bug` because we can hit this when
2014                     // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
2015                     // enabled. We don't want to ICE for that case, as other errors will have
2016                     // been emitted (#52262).
2017                     self.infcx.tcx.sess.delay_span_bug(
2018                         span,
2019                         format!(
2020                             "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2021                             place, kind,
2022                         ),
2023                     );
2024                 }
2025                 return false;
2026             }
2027             Activation(..) => {
2028                 // permission checks are done at Reservation point.
2029                 return false;
2030             }
2031             Read(
2032                 ReadKind::Borrow(BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Shallow)
2033                 | ReadKind::Copy,
2034             ) => {
2035                 // Access authorized
2036                 return false;
2037             }
2038         }
2039 
2040         // rust-lang/rust#21232, #54986: during period where we reject
2041         // partial initialization, do not complain about mutability
2042         // errors except for actual mutation (as opposed to an attempt
2043         // to do a partial initialization).
2044         let previously_initialized = self.is_local_ever_initialized(place.local, flow_state);
2045 
2046         // at this point, we have set up the error reporting state.
2047         if let Some(init_index) = previously_initialized {
2048             if let (AccessKind::Mutate, Some(_)) = (error_access, place.as_local()) {
2049                 // If this is a mutate access to an immutable local variable with no projections
2050                 // report the error as an illegal reassignment
2051                 let init = &self.move_data.inits[init_index];
2052                 let assigned_span = init.span(&self.body);
2053                 self.report_illegal_reassignment(location, (place, span), assigned_span, place);
2054             } else {
2055                 self.report_mutability_error(place, span, the_place_err, error_access, location)
2056             }
2057             true
2058         } else {
2059             false
2060         }
2061     }
2062 
is_local_ever_initialized( &self, local: Local, flow_state: &Flows<'cx, 'tcx>, ) -> Option<InitIndex>2063     fn is_local_ever_initialized(
2064         &self,
2065         local: Local,
2066         flow_state: &Flows<'cx, 'tcx>,
2067     ) -> Option<InitIndex> {
2068         let mpi = self.move_data.rev_lookup.find_local(local);
2069         let ii = &self.move_data.init_path_map[mpi];
2070         ii.into_iter().find(|&&index| flow_state.ever_inits.contains(index)).copied()
2071     }
2072 
2073     /// Adds the place into the used mutable variables set
add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>)2074     fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2075         match root_place {
2076             RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2077                 // If the local may have been initialized, and it is now currently being
2078                 // mutated, then it is justified to be annotated with the `mut`
2079                 // keyword, since the mutation may be a possible reassignment.
2080                 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2081                     && self.is_local_ever_initialized(local, flow_state).is_some()
2082                 {
2083                     self.used_mut.insert(local);
2084                 }
2085             }
2086             RootPlace {
2087                 place_local: _,
2088                 place_projection: _,
2089                 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2090             } => {}
2091             RootPlace {
2092                 place_local,
2093                 place_projection: place_projection @ [.., _],
2094                 is_local_mutation_allowed: _,
2095             } => {
2096                 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2097                     local: place_local,
2098                     projection: place_projection,
2099                 }) {
2100                     self.used_mut_upvars.push(field);
2101                 }
2102             }
2103         }
2104     }
2105 
2106     /// Whether this value can be written or borrowed mutably.
2107     /// Returns the root place if the place passed in is a projection.
is_mutable( &self, place: PlaceRef<'tcx>, is_local_mutation_allowed: LocalMutationIsAllowed, ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>>2108     fn is_mutable(
2109         &self,
2110         place: PlaceRef<'tcx>,
2111         is_local_mutation_allowed: LocalMutationIsAllowed,
2112     ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2113         debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2114         match place.last_projection() {
2115             None => {
2116                 let local = &self.body.local_decls[place.local];
2117                 match local.mutability {
2118                     Mutability::Not => match is_local_mutation_allowed {
2119                         LocalMutationIsAllowed::Yes => Ok(RootPlace {
2120                             place_local: place.local,
2121                             place_projection: place.projection,
2122                             is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2123                         }),
2124                         LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2125                             place_local: place.local,
2126                             place_projection: place.projection,
2127                             is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2128                         }),
2129                         LocalMutationIsAllowed::No => Err(place),
2130                     },
2131                     Mutability::Mut => Ok(RootPlace {
2132                         place_local: place.local,
2133                         place_projection: place.projection,
2134                         is_local_mutation_allowed,
2135                     }),
2136                 }
2137             }
2138             Some((place_base, elem)) => {
2139                 match elem {
2140                     ProjectionElem::Deref => {
2141                         let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2142 
2143                         // Check the kind of deref to decide
2144                         match base_ty.kind() {
2145                             ty::Ref(_, _, mutbl) => {
2146                                 match mutbl {
2147                                     // Shared borrowed data is never mutable
2148                                     hir::Mutability::Not => Err(place),
2149                                     // Mutably borrowed data is mutable, but only if we have a
2150                                     // unique path to the `&mut`
2151                                     hir::Mutability::Mut => {
2152                                         let mode = match self.is_upvar_field_projection(place) {
2153                                             Some(field) if self.upvars[field.index()].by_ref => {
2154                                                 is_local_mutation_allowed
2155                                             }
2156                                             _ => LocalMutationIsAllowed::Yes,
2157                                         };
2158 
2159                                         self.is_mutable(place_base, mode)
2160                                     }
2161                                 }
2162                             }
2163                             ty::RawPtr(tnm) => {
2164                                 match tnm.mutbl {
2165                                     // `*const` raw pointers are not mutable
2166                                     hir::Mutability::Not => Err(place),
2167                                     // `*mut` raw pointers are always mutable, regardless of
2168                                     // context. The users have to check by themselves.
2169                                     hir::Mutability::Mut => Ok(RootPlace {
2170                                         place_local: place.local,
2171                                         place_projection: place.projection,
2172                                         is_local_mutation_allowed,
2173                                     }),
2174                                 }
2175                             }
2176                             // `Box<T>` owns its content, so mutable if its location is mutable
2177                             _ if base_ty.is_box() => {
2178                                 self.is_mutable(place_base, is_local_mutation_allowed)
2179                             }
2180                             // Deref should only be for reference, pointers or boxes
2181                             _ => bug!("Deref of unexpected type: {:?}", base_ty),
2182                         }
2183                     }
2184                     // All other projections are owned by their base path, so mutable if
2185                     // base path is mutable
2186                     ProjectionElem::Field(..)
2187                     | ProjectionElem::Index(..)
2188                     | ProjectionElem::ConstantIndex { .. }
2189                     | ProjectionElem::Subslice { .. }
2190                     | ProjectionElem::OpaqueCast { .. }
2191                     | ProjectionElem::Downcast(..) => {
2192                         let upvar_field_projection = self.is_upvar_field_projection(place);
2193                         if let Some(field) = upvar_field_projection {
2194                             let upvar = &self.upvars[field.index()];
2195                             debug!(
2196                                 "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2197                                  place={:?}, place_base={:?}",
2198                                 upvar, is_local_mutation_allowed, place, place_base
2199                             );
2200                             match (upvar.place.mutability, is_local_mutation_allowed) {
2201                                 (
2202                                     Mutability::Not,
2203                                     LocalMutationIsAllowed::No
2204                                     | LocalMutationIsAllowed::ExceptUpvars,
2205                                 ) => Err(place),
2206                                 (Mutability::Not, LocalMutationIsAllowed::Yes)
2207                                 | (Mutability::Mut, _) => {
2208                                     // Subtle: this is an upvar
2209                                     // reference, so it looks like
2210                                     // `self.foo` -- we want to double
2211                                     // check that the location `*self`
2212                                     // is mutable (i.e., this is not a
2213                                     // `Fn` closure). But if that
2214                                     // check succeeds, we want to
2215                                     // *blame* the mutability on
2216                                     // `place` (that is,
2217                                     // `self.foo`). This is used to
2218                                     // propagate the info about
2219                                     // whether mutability declarations
2220                                     // are used outwards, so that we register
2221                                     // the outer variable as mutable. Otherwise a
2222                                     // test like this fails to record the `mut`
2223                                     // as needed:
2224                                     //
2225                                     // ```
2226                                     // fn foo<F: FnOnce()>(_f: F) { }
2227                                     // fn main() {
2228                                     //     let var = Vec::new();
2229                                     //     foo(move || {
2230                                     //         var.push(1);
2231                                     //     });
2232                                     // }
2233                                     // ```
2234                                     let _ =
2235                                         self.is_mutable(place_base, is_local_mutation_allowed)?;
2236                                     Ok(RootPlace {
2237                                         place_local: place.local,
2238                                         place_projection: place.projection,
2239                                         is_local_mutation_allowed,
2240                                     })
2241                                 }
2242                             }
2243                         } else {
2244                             self.is_mutable(place_base, is_local_mutation_allowed)
2245                         }
2246                     }
2247                 }
2248             }
2249         }
2250     }
2251 
2252     /// If `place` is a field projection, and the field is being projected from a closure type,
2253     /// then returns the index of the field being projected. Note that this closure will always
2254     /// be `self` in the current MIR, because that is the only time we directly access the fields
2255     /// of a closure type.
is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<FieldIdx>2256     fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<FieldIdx> {
2257         path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2258     }
2259 
dominators(&self) -> &Dominators<BasicBlock>2260     fn dominators(&self) -> &Dominators<BasicBlock> {
2261         // `BasicBlocks` computes dominators on-demand and caches them.
2262         self.body.basic_blocks.dominators()
2263     }
2264 }
2265 
2266 mod error {
2267     use rustc_errors::ErrorGuaranteed;
2268 
2269     use super::*;
2270 
2271     pub struct BorrowckErrors<'tcx> {
2272         tcx: TyCtxt<'tcx>,
2273         /// This field keeps track of move errors that are to be reported for given move indices.
2274         ///
2275         /// There are situations where many errors can be reported for a single move out (see #53807)
2276         /// and we want only the best of those errors.
2277         ///
2278         /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
2279         /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
2280         /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
2281         /// all move errors have been reported, any diagnostics in this map are added to the buffer
2282         /// to be emitted.
2283         ///
2284         /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
2285         /// when errors in the map are being re-added to the error buffer so that errors with the
2286         /// same primary span come out in a consistent order.
2287         buffered_move_errors:
2288             BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorGuaranteed>)>,
2289         buffered_mut_errors: FxIndexMap<Span, (DiagnosticBuilder<'tcx, ErrorGuaranteed>, usize)>,
2290         /// Diagnostics to be reported buffer.
2291         buffered: Vec<Diagnostic>,
2292         /// Set to Some if we emit an error during borrowck
2293         tainted_by_errors: Option<ErrorGuaranteed>,
2294     }
2295 
2296     impl<'tcx> BorrowckErrors<'tcx> {
new(tcx: TyCtxt<'tcx>) -> Self2297         pub fn new(tcx: TyCtxt<'tcx>) -> Self {
2298             BorrowckErrors {
2299                 tcx,
2300                 buffered_move_errors: BTreeMap::new(),
2301                 buffered_mut_errors: Default::default(),
2302                 buffered: Default::default(),
2303                 tainted_by_errors: None,
2304             }
2305         }
2306 
buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorGuaranteed>)2307         pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorGuaranteed>) {
2308             if let None = self.tainted_by_errors {
2309                 self.tainted_by_errors = Some(
2310                     self.tcx
2311                         .sess
2312                         .delay_span_bug(t.span.clone(), "diagnostic buffered but not emitted"),
2313                 )
2314             }
2315             t.buffer(&mut self.buffered);
2316         }
2317 
buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>)2318         pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) {
2319             t.buffer(&mut self.buffered);
2320         }
2321 
set_tainted_by_errors(&mut self, e: ErrorGuaranteed)2322         pub fn set_tainted_by_errors(&mut self, e: ErrorGuaranteed) {
2323             self.tainted_by_errors = Some(e);
2324         }
2325     }
2326 
2327     impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorGuaranteed>)2328         pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorGuaranteed>) {
2329             self.errors.buffer_error(t);
2330         }
2331 
buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>)2332         pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) {
2333             self.errors.buffer_non_error_diag(t);
2334         }
2335 
buffer_move_error( &mut self, move_out_indices: Vec<MoveOutIndex>, place_and_err: (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorGuaranteed>), ) -> bool2336         pub fn buffer_move_error(
2337             &mut self,
2338             move_out_indices: Vec<MoveOutIndex>,
2339             place_and_err: (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorGuaranteed>),
2340         ) -> bool {
2341             if let Some((_, diag)) =
2342                 self.errors.buffered_move_errors.insert(move_out_indices, place_and_err)
2343             {
2344                 // Cancel the old diagnostic so we don't ICE
2345                 diag.cancel();
2346                 false
2347             } else {
2348                 true
2349             }
2350         }
2351 
get_buffered_mut_error( &mut self, span: Span, ) -> Option<(DiagnosticBuilder<'tcx, ErrorGuaranteed>, usize)>2352         pub fn get_buffered_mut_error(
2353             &mut self,
2354             span: Span,
2355         ) -> Option<(DiagnosticBuilder<'tcx, ErrorGuaranteed>, usize)> {
2356             self.errors.buffered_mut_errors.remove(&span)
2357         }
2358 
buffer_mut_error( &mut self, span: Span, t: DiagnosticBuilder<'tcx, ErrorGuaranteed>, count: usize, )2359         pub fn buffer_mut_error(
2360             &mut self,
2361             span: Span,
2362             t: DiagnosticBuilder<'tcx, ErrorGuaranteed>,
2363             count: usize,
2364         ) {
2365             self.errors.buffered_mut_errors.insert(span, (t, count));
2366         }
2367 
emit_errors(&mut self) -> Option<ErrorGuaranteed>2368         pub fn emit_errors(&mut self) -> Option<ErrorGuaranteed> {
2369             // Buffer any move errors that we collected and de-duplicated.
2370             for (_, (_, diag)) in std::mem::take(&mut self.errors.buffered_move_errors) {
2371                 // We have already set tainted for this error, so just buffer it.
2372                 diag.buffer(&mut self.errors.buffered);
2373             }
2374             for (_, (mut diag, count)) in std::mem::take(&mut self.errors.buffered_mut_errors) {
2375                 if count > 10 {
2376                     diag.note(format!("...and {} other attempted mutable borrows", count - 10));
2377                 }
2378                 diag.buffer(&mut self.errors.buffered);
2379             }
2380 
2381             if !self.errors.buffered.is_empty() {
2382                 self.errors.buffered.sort_by_key(|diag| diag.sort_span);
2383 
2384                 for mut diag in self.errors.buffered.drain(..) {
2385                     self.infcx.tcx.sess.diagnostic().emit_diagnostic(&mut diag);
2386                 }
2387             }
2388 
2389             self.errors.tainted_by_errors
2390         }
2391 
has_buffered_errors(&self) -> bool2392         pub fn has_buffered_errors(&self) -> bool {
2393             self.errors.buffered.is_empty()
2394         }
2395 
has_move_error( &self, move_out_indices: &[MoveOutIndex], ) -> Option<&(PlaceRef<'tcx>, DiagnosticBuilder<'cx, ErrorGuaranteed>)>2396         pub fn has_move_error(
2397             &self,
2398             move_out_indices: &[MoveOutIndex],
2399         ) -> Option<&(PlaceRef<'tcx>, DiagnosticBuilder<'cx, ErrorGuaranteed>)> {
2400             self.errors.buffered_move_errors.get(move_out_indices)
2401         }
2402     }
2403 }
2404 
2405 /// The degree of overlap between 2 places for borrow-checking.
2406 enum Overlap {
2407     /// The places might partially overlap - in this case, we give
2408     /// up and say that they might conflict. This occurs when
2409     /// different fields of a union are borrowed. For example,
2410     /// if `u` is a union, we have no way of telling how disjoint
2411     /// `u.a.x` and `a.b.y` are.
2412     Arbitrary,
2413     /// The places have the same type, and are either completely disjoint
2414     /// or equal - i.e., they can't "partially" overlap as can occur with
2415     /// unions. This is the "base case" on which we recur for extensions
2416     /// of the place.
2417     EqualOrDisjoint,
2418     /// The places are disjoint, so we know all extensions of them
2419     /// will also be disjoint.
2420     Disjoint,
2421 }
2422