1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
3 #![allow(rustc::potential_query_instability)]
4 #![feature(box_patterns)]
5 #![feature(let_chains)]
6 #![feature(min_specialization)]
7 #![feature(never_type)]
9 #![feature(rustc_attrs)]
10 #![feature(stmt_expr_attributes)]
11 #![feature(trusted_step)]
12 #![feature(try_blocks)]
13 #![recursion_limit = "256"]
16 extern crate rustc_middle;
20 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
21 use rustc_data_structures::graph::dominators::Dominators;
22 use rustc_data_structures::vec_map::VecMap;
23 use rustc_errors::{Diagnostic, DiagnosticBuilder};
25 use rustc_hir::def_id::LocalDefId;
26 use rustc_index::bit_set::ChunkedBitSet;
27 use rustc_index::vec::IndexVec;
28 use rustc_infer::infer::{DefiningAnchor, InferCtxt, TyCtxtInferExt};
29 use rustc_middle::mir::{
30 traversal, Body, ClearCrossCrate, Local, Location, Mutability, NonDivergingIntrinsic, Operand,
31 Place, PlaceElem, PlaceRef, VarDebugInfoContents,
33 use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
34 use rustc_middle::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
35 use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind};
36 use rustc_middle::ty::query::Providers;
37 use rustc_middle::ty::{self, CapturedPlace, ParamEnv, RegionVid, TyCtxt};
38 use rustc_session::lint::builtin::UNUSED_MUT;
39 use rustc_span::{Span, Symbol};
42 use smallvec::SmallVec;
43 use std::cell::OnceCell;
44 use std::cell::RefCell;
45 use std::collections::BTreeMap;
48 use rustc_mir_dataflow::impls::{
49 EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces,
51 use rustc_mir_dataflow::move_paths::{InitIndex, MoveOutIndex, MovePathIndex};
52 use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveData, MoveError};
53 use rustc_mir_dataflow::Analysis;
54 use rustc_mir_dataflow::MoveDataParamEnv;
56 use crate::session_diagnostics::VarNeedNotMut;
58 use self::diagnostics::{AccessKind, RegionName};
59 use self::location::LocationTable;
60 use self::prefixes::PrefixSet;
63 use self::path_utils::*;
67 mod constraint_generation;
75 mod member_constraints;
83 mod session_diagnostics;
85 mod universal_regions;
88 /// A public API provided for the Rust compiler consumers.
91 use borrow_set::{BorrowData, BorrowSet};
92 use dataflow::{BorrowIndex, BorrowckFlowState as Flows, BorrowckResults, Borrows};
93 use nll::{PoloniusOutput, ToRegionVid};
94 use place_ext::PlaceExt;
95 use places_conflict::{places_conflict, PlaceConflictBias};
96 use region_infer::RegionInferenceContext;
98 // FIXME(eddyb) perhaps move this somewhere more centrally.
101 place: CapturedPlace<'tcx>,
103 /// If true, the capture is behind a reference.
107 /// Associate some local constants with the `'tcx` lifetime
108 struct TyCtxtConsts<'tcx>(TyCtxt<'tcx>);
109 impl<'tcx> TyCtxtConsts<'tcx> {
110 const DEREF_PROJECTION: &'tcx [PlaceElem<'tcx>; 1] = &[ProjectionElem::Deref];
113 pub fn provide(providers: &mut Providers) {
114 *providers = Providers {
115 mir_borrowck: |tcx, did| {
116 if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
117 tcx.mir_borrowck_const_arg(def)
119 mir_borrowck(tcx, ty::WithOptConstParam::unknown(did))
122 mir_borrowck_const_arg: |tcx, (did, param_did)| {
123 mir_borrowck(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
129 fn mir_borrowck(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> &BorrowCheckResult<'_> {
130 let (input_body, promoted) = tcx.mir_promoted(def);
131 debug!("run query mir_borrowck: {}", tcx.def_path_str(def.did.to_def_id()));
133 if input_body.borrow().should_skip() {
134 debug!("Skipping borrowck because of injected body");
135 // Let's make up a borrowck result! Fun times!
136 let result = BorrowCheckResult {
137 concrete_opaque_types: VecMap::new(),
138 closure_requirements: None,
139 used_mut_upvars: SmallVec::new(),
140 tainted_by_errors: None,
142 return tcx.arena.alloc(result);
145 let hir_owner = tcx.hir().local_def_id_to_hir_id(def.did).owner;
148 tcx.infer_ctxt().with_opaque_type_inference(DefiningAnchor::Bind(hir_owner.def_id)).build();
149 let input_body: &Body<'_> = &input_body.borrow();
150 let promoted: &IndexVec<_, _> = &promoted.borrow();
151 let opt_closure_req = do_mir_borrowck(&infcx, input_body, promoted, false).0;
152 debug!("mir_borrowck done");
154 tcx.arena.alloc(opt_closure_req)
157 /// Perform the actual borrow checking.
159 /// If `return_body_with_facts` is true, then return the body with non-erased
160 /// region ids on which the borrow checking was performed together with Polonius
162 #[instrument(skip(infcx, input_body, input_promoted), fields(id=?input_body.source.with_opt_param().as_local().unwrap()), level = "debug")]
163 fn do_mir_borrowck<'tcx>(
164 infcx: &InferCtxt<'tcx>,
165 input_body: &Body<'tcx>,
166 input_promoted: &IndexVec<Promoted, Body<'tcx>>,
167 return_body_with_facts: bool,
168 ) -> (BorrowCheckResult<'tcx>, Option<Box<BodyWithBorrowckFacts<'tcx>>>) {
169 let def = input_body.source.with_opt_param().as_local().unwrap();
174 let param_env = tcx.param_env(def.did);
176 let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
177 for var_debug_info in &input_body.var_debug_info {
178 if let VarDebugInfoContents::Place(place) = var_debug_info.value {
179 if let Some(local) = place.as_local() {
180 if let Some(prev_name) = local_names[local] && var_debug_info.name != prev_name {
182 var_debug_info.source_info.span,
183 "local {:?} has many names (`{}` vs `{}`)",
189 local_names[local] = Some(var_debug_info.name);
194 let mut errors = error::BorrowckErrors::new(infcx.tcx);
196 // Gather the upvars of a closure, if any.
197 let tables = tcx.typeck_opt_const_arg(def);
198 if let Some(e) = tables.tainted_by_errors {
199 infcx.set_tainted_by_errors(e);
200 errors.set_tainted_by_errors(e);
202 let upvars: Vec<_> = tables
203 .closure_min_captures_flattened(def.did)
204 .map(|captured_place| {
205 let capture = captured_place.info.capture_kind;
206 let by_ref = match capture {
207 ty::UpvarCapture::ByValue => false,
208 ty::UpvarCapture::ByRef(..) => true,
210 Upvar { place: captured_place.clone(), by_ref }
214 // Replace all regions with fresh inference variables. This
215 // requires first making our own copy of the MIR. This copy will
216 // be modified (in place) to contain non-lexical lifetimes. It
217 // will have a lifetime tied to the inference context.
218 let mut body_owned = input_body.clone();
219 let mut promoted = input_promoted.clone();
221 nll::replace_regions_in_mir(infcx, param_env, &mut body_owned, &mut promoted);
222 let body = &body_owned; // no further changes
224 let location_table_owned = LocationTable::new(body);
225 let location_table = &location_table_owned;
227 let (move_data, move_errors): (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>) =
228 match MoveData::gather_moves(&body, tcx, param_env) {
229 Ok((_, move_data)) => (move_data, Vec::new()),
230 Err((move_data, move_errors)) => (move_data, move_errors),
232 let promoted_errors = promoted
234 .map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env)));
236 let mdpe = MoveDataParamEnv { move_data, param_env };
238 let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe)
239 .into_engine(tcx, &body)
240 .pass_name("borrowck")
241 .iterate_to_fixpoint()
242 .into_results_cursor(&body);
244 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(def.did).is_fn_or_closure();
246 Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
248 let use_polonius = return_body_with_facts || infcx.tcx.sess.opts.unstable_opts.polonius;
250 // Compute non-lexical lifetimes.
258 } = nll::compute_regions(
272 // Dump MIR results into a file, if that is enabled. This let us
273 // write unit-tests, as well as helping with debugging.
274 nll::dump_mir_results(infcx, &body, ®ioncx, &opt_closure_req);
276 // We also have a `#[rustc_regions]` annotation that causes us to dump
278 nll::dump_annotation(
287 // The various `flow_*` structures can be large. We drop `flow_inits` here
288 // so it doesn't overlap with the others below. This reduces peak memory
289 // usage significantly on some benchmarks.
292 let regioncx = Rc::new(regioncx);
294 let flow_borrows = Borrows::new(tcx, body, ®ioncx, &borrow_set)
295 .into_engine(tcx, body)
296 .pass_name("borrowck")
297 .iterate_to_fixpoint();
298 let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &mdpe)
299 .into_engine(tcx, body)
300 .pass_name("borrowck")
301 .iterate_to_fixpoint();
302 let flow_ever_inits = EverInitializedPlaces::new(tcx, body, &mdpe)
303 .into_engine(tcx, body)
304 .pass_name("borrowck")
305 .iterate_to_fixpoint();
307 let movable_generator =
308 // The first argument is the generator type passed by value
309 if let Some(local) = body.local_decls.raw.get(1)
310 // Get the interior types and substs which typeck computed
311 && let ty::Generator(_, _, hir::Movability::Static) = local.ty.kind()
318 for (idx, move_data_results) in promoted_errors {
319 let promoted_body = &promoted[idx];
321 if let Err((move_data, move_errors)) = move_data_results {
322 let mut promoted_mbcx = MirBorrowckCtxt {
326 move_data: &move_data,
327 location_table, // no need to create a real one for the promoted, it is not used
329 fn_self_span_reported: Default::default(),
330 locals_are_invalidated_at_exit,
331 access_place_error_reported: Default::default(),
332 reservation_error_reported: Default::default(),
333 uninitialized_error_reported: Default::default(),
334 regioncx: regioncx.clone(),
335 used_mut: Default::default(),
336 used_mut_upvars: SmallVec::new(),
337 borrow_set: Rc::clone(&borrow_set),
338 dominators: Default::default(),
340 local_names: IndexVec::from_elem(None, &promoted_body.local_decls),
341 region_names: RefCell::default(),
342 next_region_name: RefCell::new(1),
343 polonius_output: None,
346 promoted_mbcx.report_move_errors(move_errors);
347 errors = promoted_mbcx.errors;
351 let mut mbcx = MirBorrowckCtxt {
355 move_data: &mdpe.move_data,
358 locals_are_invalidated_at_exit,
359 fn_self_span_reported: Default::default(),
360 access_place_error_reported: Default::default(),
361 reservation_error_reported: Default::default(),
362 uninitialized_error_reported: Default::default(),
363 regioncx: Rc::clone(®ioncx),
364 used_mut: Default::default(),
365 used_mut_upvars: SmallVec::new(),
366 borrow_set: Rc::clone(&borrow_set),
367 dominators: Default::default(),
370 region_names: RefCell::default(),
371 next_region_name: RefCell::new(1),
376 // Compute and report region errors, if any.
377 mbcx.report_region_errors(nll_errors);
379 let results = BorrowckResults {
380 ever_inits: flow_ever_inits,
381 uninits: flow_uninits,
382 borrows: flow_borrows,
385 mbcx.report_move_errors(move_errors);
387 rustc_mir_dataflow::visit_results(
389 traversal::reverse_postorder(body).map(|(bb, _)| bb),
394 // For each non-user used mutable variable, check if it's been assigned from
395 // a user-declared local. If so, then put that local into the used_mut set.
396 // Note that this set is expected to be small - only upvars from closures
397 // would have a chance of erroneously adding non-user-defined mutable vars
399 let temporary_used_locals: FxHashSet<Local> = mbcx
402 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
405 // For the remaining unused locals that are marked as mutable, we avoid linting any that
406 // were never initialized. These locals may have been removed as unreachable code; or will be
407 // linted as unused variables.
408 let unused_mut_locals =
409 mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
410 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
412 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
413 let used_mut = std::mem::take(&mut mbcx.used_mut);
414 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
415 let local_decl = &mbcx.body.local_decls[local];
416 let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data {
417 ClearCrossCrate::Set(data) => data.lint_root,
421 // Skip over locals that begin with an underscore or have no name
422 match mbcx.local_names[local] {
424 if name.as_str().starts_with('_') {
431 let span = local_decl.source_info.span;
432 if span.desugaring_kind().is_some() {
433 // If the `mut` arises as part of a desugaring, we should ignore it.
437 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
439 tcx.emit_spanned_lint(UNUSED_MUT, lint_root, span, VarNeedNotMut { span: mut_span })
442 let tainted_by_errors = mbcx.emit_errors();
444 let result = BorrowCheckResult {
445 concrete_opaque_types: opaque_type_values,
446 closure_requirements: opt_closure_req,
447 used_mut_upvars: mbcx.used_mut_upvars,
451 let body_with_facts = if return_body_with_facts {
452 let output_facts = mbcx.polonius_output.expect("Polonius output was not computed");
453 Some(Box::new(BodyWithBorrowckFacts {
455 input_facts: *polonius_input.expect("Polonius input facts were not generated"),
457 location_table: location_table_owned,
463 debug!("do_mir_borrowck: result = {:#?}", result);
465 (result, body_with_facts)
468 /// A `Body` with information computed by the borrow checker. This struct is
469 /// intended to be consumed by compiler consumers.
471 /// We need to include the MIR body here because the region identifiers must
472 /// match the ones in the Polonius facts.
473 pub struct BodyWithBorrowckFacts<'tcx> {
474 /// A mir body that contains region identifiers.
475 pub body: Body<'tcx>,
476 /// Polonius input facts.
477 pub input_facts: AllFacts,
478 /// Polonius output facts.
479 pub output_facts: Rc<self::nll::PoloniusOutput>,
480 /// The table that maps Polonius points to locations in the table.
481 pub location_table: LocationTable,
484 struct MirBorrowckCtxt<'cx, 'tcx> {
485 infcx: &'cx InferCtxt<'tcx>,
486 param_env: ParamEnv<'tcx>,
487 body: &'cx Body<'tcx>,
488 move_data: &'cx MoveData<'tcx>,
490 /// Map from MIR `Location` to `LocationIndex`; created
491 /// when MIR borrowck begins.
492 location_table: &'cx LocationTable,
494 movable_generator: bool,
495 /// This keeps track of whether local variables are free-ed when the function
496 /// exits even without a `StorageDead`, which appears to be the case for
499 /// I'm not sure this is the right approach - @eddyb could you try and
501 locals_are_invalidated_at_exit: bool,
502 /// This field keeps track of when borrow errors are reported in the access_place function
503 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
504 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
505 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
507 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
508 /// This field keeps track of when borrow conflict errors are reported
509 /// for reservations, so that we don't report seemingly duplicate
510 /// errors for corresponding activations.
512 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
513 // but it is currently inconvenient to track down the `BorrowIndex`
514 // at the time we detect and report a reservation error.
515 reservation_error_reported: FxHashSet<Place<'tcx>>,
516 /// This fields keeps track of the `Span`s that we have
517 /// used to report extra information for `FnSelfUse`, to avoid
518 /// unnecessarily verbose errors.
519 fn_self_span_reported: FxHashSet<Span>,
520 /// This field keeps track of errors reported in the checking of uninitialized variables,
521 /// so that we don't report seemingly duplicate errors.
522 uninitialized_error_reported: FxHashSet<PlaceRef<'tcx>>,
523 /// This field keeps track of all the local variables that are declared mut and are mutated.
524 /// Used for the warning issued by an unused mutable local variable.
525 used_mut: FxHashSet<Local>,
526 /// If the function we're checking is a closure, then we'll need to report back the list of
527 /// mutable upvars that have been used. This field keeps track of them.
528 used_mut_upvars: SmallVec<[Field; 8]>,
529 /// Region inference context. This contains the results from region inference and lets us e.g.
530 /// find out which CFG points are contained in each borrow region.
531 regioncx: Rc<RegionInferenceContext<'tcx>>,
533 /// The set of borrows extracted from the MIR
534 borrow_set: Rc<BorrowSet<'tcx>>,
536 /// Dominators for MIR
537 dominators: OnceCell<Dominators<BasicBlock>>,
539 /// Information about upvars not necessarily preserved in types or MIR
540 upvars: Vec<Upvar<'tcx>>,
542 /// Names of local (user) variables (extracted from `var_debug_info`).
543 local_names: IndexVec<Local, Option<Symbol>>,
545 /// Record the region names generated for each region in the given
546 /// MIR def so that we can reuse them later in help/error messages.
547 region_names: RefCell<FxHashMap<RegionVid, RegionName>>,
549 /// The counter for generating new region names.
550 next_region_name: RefCell<usize>,
552 /// Results of Polonius analysis.
553 polonius_output: Option<Rc<PoloniusOutput>>,
555 errors: error::BorrowckErrors<'tcx>,
559 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
560 // 2. loans made in overlapping scopes do not conflict
561 // 3. assignments do not affect things loaned out as immutable
562 // 4. moves do not affect things loaned out in any way
563 impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
564 type FlowState = Flows<'cx, 'tcx>;
566 fn visit_statement_before_primary_effect(
568 flow_state: &Flows<'cx, 'tcx>,
569 stmt: &'cx Statement<'tcx>,
572 debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state);
573 let span = stmt.source_info.span;
575 self.check_activations(location, span, flow_state);
578 StatementKind::Assign(box (lhs, rhs)) => {
579 self.consume_rvalue(location, (rhs, span), flow_state);
581 self.mutate_place(location, (*lhs, span), Shallow(None), flow_state);
583 StatementKind::FakeRead(box (_, place)) => {
584 // Read for match doesn't access any memory and is used to
585 // assert that a place is safe and live. So we don't have to
586 // do any checks here.
588 // FIXME: Remove check that the place is initialized. This is
589 // needed for now because matches don't have never patterns yet.
590 // So this is the only place we prevent
594 self.check_if_path_or_subpath_is_moved(
596 InitializationRequiringAction::Use,
597 (place.as_ref(), span),
601 StatementKind::Intrinsic(box kind) => match kind {
602 NonDivergingIntrinsic::Assume(op) => self.consume_operand(location, (op, span), flow_state),
603 NonDivergingIntrinsic::CopyNonOverlapping(..) => span_bug!(
605 "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
608 // Only relevant for mir typeck
609 StatementKind::AscribeUserType(..)
610 // Doesn't have any language semantics
611 | StatementKind::Coverage(..)
612 // These do not actually affect borrowck
613 | StatementKind::ConstEvalCounter
614 | StatementKind::StorageLive(..) => {}
615 StatementKind::StorageDead(local) => {
618 (Place::from(*local), span),
619 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
620 LocalMutationIsAllowed::Yes,
625 | StatementKind::Retag { .. }
626 | StatementKind::Deinit(..)
627 | StatementKind::SetDiscriminant { .. } => {
628 bug!("Statement not allowed in this MIR phase")
633 fn visit_terminator_before_primary_effect(
635 flow_state: &Flows<'cx, 'tcx>,
636 term: &'cx Terminator<'tcx>,
639 debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
640 let span = term.source_info.span;
642 self.check_activations(loc, span, flow_state);
645 TerminatorKind::SwitchInt { discr, targets: _ } => {
646 self.consume_operand(loc, (discr, span), flow_state);
648 TerminatorKind::Drop { place, target: _, unwind: _ } => {
650 "visit_terminator_drop \
651 loc: {:?} term: {:?} place: {:?} span: {:?}",
652 loc, term, place, span
658 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
659 LocalMutationIsAllowed::Yes,
663 TerminatorKind::DropAndReplace {
669 self.mutate_place(loc, (*drop_place, span), Deep, flow_state);
670 self.consume_operand(loc, (new_value, span), flow_state);
672 TerminatorKind::Call {
681 self.consume_operand(loc, (func, span), flow_state);
683 self.consume_operand(loc, (arg, span), flow_state);
685 self.mutate_place(loc, (*destination, span), Deep, flow_state);
687 TerminatorKind::Assert { cond, expected: _, msg, target: _, cleanup: _ } => {
688 self.consume_operand(loc, (cond, span), flow_state);
689 use rustc_middle::mir::AssertKind;
690 if let AssertKind::BoundsCheck { len, index } = msg {
691 self.consume_operand(loc, (len, span), flow_state);
692 self.consume_operand(loc, (index, span), flow_state);
696 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
697 self.consume_operand(loc, (value, span), flow_state);
698 self.mutate_place(loc, (*resume_arg, span), Deep, flow_state);
701 TerminatorKind::InlineAsm {
711 InlineAsmOperand::In { reg: _, value } => {
712 self.consume_operand(loc, (value, span), flow_state);
714 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
715 if let Some(place) = place {
716 self.mutate_place(loc, (*place, span), Shallow(None), flow_state);
719 InlineAsmOperand::InOut { reg: _, late: _, in_value, out_place } => {
720 self.consume_operand(loc, (in_value, span), flow_state);
721 if let &Some(out_place) = out_place {
730 InlineAsmOperand::Const { value: _ }
731 | InlineAsmOperand::SymFn { value: _ }
732 | InlineAsmOperand::SymStatic { def_id: _ } => {}
737 TerminatorKind::Goto { target: _ }
738 | TerminatorKind::Abort
739 | TerminatorKind::Unreachable
740 | TerminatorKind::Resume
741 | TerminatorKind::Return
742 | TerminatorKind::GeneratorDrop
743 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
744 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
745 // no data used, thus irrelevant to borrowck
750 fn visit_terminator_after_primary_effect(
752 flow_state: &Flows<'cx, 'tcx>,
753 term: &'cx Terminator<'tcx>,
756 let span = term.source_info.span;
759 TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
760 if self.movable_generator {
761 // Look for any active borrows to locals
762 let borrow_set = self.borrow_set.clone();
763 for i in flow_state.borrows.iter() {
764 let borrow = &borrow_set[i];
765 self.check_for_local_borrow(borrow, span);
770 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
771 // Returning from the function implicitly kills storage for all locals and statics.
772 // Often, the storage will already have been killed by an explicit
773 // StorageDead, but we don't always emit those (notably on unwind paths),
774 // so this "extra check" serves as a kind of backup.
775 let borrow_set = self.borrow_set.clone();
776 for i in flow_state.borrows.iter() {
777 let borrow = &borrow_set[i];
778 self.check_for_invalidation_at_exit(loc, borrow, span);
782 TerminatorKind::Abort
783 | TerminatorKind::Assert { .. }
784 | TerminatorKind::Call { .. }
785 | TerminatorKind::Drop { .. }
786 | TerminatorKind::DropAndReplace { .. }
787 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
788 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
789 | TerminatorKind::Goto { .. }
790 | TerminatorKind::SwitchInt { .. }
791 | TerminatorKind::Unreachable
792 | TerminatorKind::InlineAsm { .. } => {}
797 use self::AccessDepth::{Deep, Shallow};
798 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
800 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
801 enum ArtificialField {
806 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
808 /// From the RFC: "A *shallow* access means that the immediate
809 /// fields reached at P are accessed, but references or pointers
810 /// found within are not dereferenced. Right now, the only access
811 /// that is shallow is an assignment like `x = ...;`, which would
812 /// be a *shallow write* of `x`."
813 Shallow(Option<ArtificialField>),
815 /// From the RFC: "A *deep* access means that all data reachable
816 /// through the given place may be invalidated or accesses by
820 /// Access is Deep only when there is a Drop implementation that
821 /// can reach the data behind the reference.
825 /// Kind of access to a value: read or write
826 /// (For informational purposes only)
827 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
829 /// From the RFC: "A *read* means that the existing data may be
830 /// read, but will not be changed."
833 /// From the RFC: "A *write* means that the data may be mutated to
834 /// new values or otherwise invalidated (for example, it could be
835 /// de-initialized, as in a move operation).
838 /// For two-phase borrows, we distinguish a reservation (which is treated
839 /// like a Read) from an activation (which is treated like a write), and
840 /// each of those is furthermore distinguished from Reads/Writes above.
841 Reservation(WriteKind),
842 Activation(WriteKind, BorrowIndex),
845 /// Kind of read access to a value
846 /// (For informational purposes only)
847 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
853 /// Kind of write access to a value
854 /// (For informational purposes only)
855 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
858 MutableBorrow(BorrowKind),
863 /// When checking permissions for a place access, this flag is used to indicate that an immutable
864 /// local place can be mutated.
866 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
867 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
868 // `is_declared_mutable()`.
869 // - Take flow state into consideration in `is_assignable()` for local variables.
870 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
871 enum LocalMutationIsAllowed {
873 /// We want use of immutable upvars to cause a "write to immutable upvar"
874 /// error, not an "reassignment" error.
879 #[derive(Copy, Clone, Debug)]
880 enum InitializationRequiringAction {
888 struct RootPlace<'tcx> {
890 place_projection: &'tcx [PlaceElem<'tcx>],
891 is_local_mutation_allowed: LocalMutationIsAllowed,
894 impl InitializationRequiringAction {
895 fn as_noun(self) -> &'static str {
897 InitializationRequiringAction::Borrow => "borrow",
898 InitializationRequiringAction::MatchOn => "use", // no good noun
899 InitializationRequiringAction::Use => "use",
900 InitializationRequiringAction::Assignment => "assign",
901 InitializationRequiringAction::PartialAssignment => "assign to part",
905 fn as_verb_in_past_tense(self) -> &'static str {
907 InitializationRequiringAction::Borrow => "borrowed",
908 InitializationRequiringAction::MatchOn => "matched on",
909 InitializationRequiringAction::Use => "used",
910 InitializationRequiringAction::Assignment => "assigned",
911 InitializationRequiringAction::PartialAssignment => "partially assigned",
915 fn as_general_verb_in_past_tense(self) -> &'static str {
917 InitializationRequiringAction::Borrow
918 | InitializationRequiringAction::MatchOn
919 | InitializationRequiringAction::Use => "used",
920 InitializationRequiringAction::Assignment => "assigned",
921 InitializationRequiringAction::PartialAssignment => "partially assigned",
926 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
927 fn body(&self) -> &'cx Body<'tcx> {
931 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
932 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
933 /// place is initialized and (b) it is not borrowed in some way that would prevent this
936 /// Returns `true` if an error is reported.
940 place_span: (Place<'tcx>, Span),
941 kind: (AccessDepth, ReadOrWrite),
942 is_local_mutation_allowed: LocalMutationIsAllowed,
943 flow_state: &Flows<'cx, 'tcx>,
947 if let Activation(_, borrow_index) = rw {
948 if self.reservation_error_reported.contains(&place_span.0) {
950 "skipping access_place for activation of invalid reservation \
951 place: {:?} borrow_index: {:?}",
952 place_span.0, borrow_index
958 // Check is_empty() first because it's the common case, and doing that
959 // way we avoid the clone() call.
960 if !self.access_place_error_reported.is_empty()
961 && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
964 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
970 let mutability_error = self.check_access_permissions(
973 is_local_mutation_allowed,
978 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
980 if conflict_error || mutability_error {
981 debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
982 self.access_place_error_reported.insert((place_span.0, place_span.1));
986 #[instrument(level = "debug", skip(self, flow_state))]
987 fn check_access_for_conflict(
990 place_span: (Place<'tcx>, Span),
993 flow_state: &Flows<'cx, 'tcx>,
995 let mut error_reported = false;
996 let tcx = self.infcx.tcx;
997 let body = self.body;
998 let borrow_set = self.borrow_set.clone();
1000 // Use polonius output if it has been enabled.
1001 let polonius_output = self.polonius_output.clone();
1002 let borrows_in_scope = if let Some(polonius) = &polonius_output {
1003 let location = self.location_table.start_index(location);
1004 Either::Left(polonius.errors_at(location).iter().copied())
1006 Either::Right(flow_state.borrows.iter())
1009 each_borrow_involving_path(
1017 |this, borrow_index, borrow| match (rw, borrow.kind) {
1018 // Obviously an activation is compatible with its own
1019 // reservation (or even prior activating uses of same
1020 // borrow); so don't check if they interfere.
1022 // NOTE: *reservations* do conflict with themselves;
1023 // thus aren't injecting unsoundness w/ this check.)
1024 (Activation(_, activating), _) if activating == borrow_index => {
1026 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1027 skipping {:?} b/c activation of same borrow_index",
1031 (borrow_index, borrow),
1036 (Read(_), BorrowKind::Shared | BorrowKind::Shallow)
1038 Read(ReadKind::Borrow(BorrowKind::Shallow)),
1039 BorrowKind::Unique | BorrowKind::Mut { .. },
1040 ) => Control::Continue,
1042 (Reservation(_), BorrowKind::Shallow | BorrowKind::Shared) => {
1043 // This used to be a future compatibility warning (to be
1044 // disallowed on NLL). See rust-lang/rust#56254
1048 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1049 // Handled by initialization checks.
1053 (Read(kind), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
1054 // Reading from mere reservations of mutable-borrows is OK.
1055 if !is_active(this.dominators(), borrow, location) {
1056 assert!(allow_two_phase_borrow(borrow.kind));
1057 return Control::Continue;
1060 error_reported = true;
1064 .report_use_while_mutably_borrowed(location, place_span, borrow);
1065 this.buffer_error(err);
1067 ReadKind::Borrow(bk) => {
1069 this.report_conflicting_borrow(location, place_span, bk, borrow);
1070 this.buffer_error(err);
1076 (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1078 Reservation(..) => {
1080 "recording invalid reservation of \
1084 this.reservation_error_reported.insert(place_span.0);
1086 Activation(_, activating) => {
1088 "observing check_place for activation of \
1089 borrow_index: {:?}",
1093 Read(..) | Write(..) => {}
1096 error_reported = true;
1098 WriteKind::MutableBorrow(bk) => {
1100 this.report_conflicting_borrow(location, place_span, bk, borrow);
1101 this.buffer_error(err);
1103 WriteKind::StorageDeadOrDrop => this
1104 .report_borrowed_value_does_not_live_long_enough(
1110 WriteKind::Mutate => {
1111 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1113 WriteKind::Move => {
1114 this.report_move_out_while_borrowed(location, place_span, borrow)
1128 place_span: (Place<'tcx>, Span),
1130 flow_state: &Flows<'cx, 'tcx>,
1132 // Write of P[i] or *P requires P init'd.
1133 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1138 (kind, Write(WriteKind::Mutate)),
1139 LocalMutationIsAllowed::No,
1147 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1148 flow_state: &Flows<'cx, 'tcx>,
1151 &Rvalue::Ref(_ /*rgn*/, bk, place) => {
1152 let access_kind = match bk {
1153 BorrowKind::Shallow => {
1154 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1156 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1157 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1158 let wk = WriteKind::MutableBorrow(bk);
1159 if allow_two_phase_borrow(bk) {
1160 (Deep, Reservation(wk))
1171 LocalMutationIsAllowed::No,
1175 let action = if bk == BorrowKind::Shallow {
1176 InitializationRequiringAction::MatchOn
1178 InitializationRequiringAction::Borrow
1181 self.check_if_path_or_subpath_is_moved(
1184 (place.as_ref(), span),
1189 &Rvalue::AddressOf(mutability, place) => {
1190 let access_kind = match mutability {
1191 Mutability::Mut => (
1193 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1194 allow_two_phase_borrow: false,
1197 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1204 LocalMutationIsAllowed::No,
1208 self.check_if_path_or_subpath_is_moved(
1210 InitializationRequiringAction::Borrow,
1211 (place.as_ref(), span),
1216 Rvalue::ThreadLocalRef(_) => {}
1218 Rvalue::Use(operand)
1219 | Rvalue::Repeat(operand, _)
1220 | Rvalue::UnaryOp(_ /*un_op*/, operand)
1221 | Rvalue::Cast(_ /*cast_kind*/, operand, _ /*ty*/)
1222 | Rvalue::ShallowInitBox(operand, _ /*ty*/) => {
1223 self.consume_operand(location, (operand, span), flow_state)
1226 &Rvalue::CopyForDeref(place) => {
1230 (Deep, Read(ReadKind::Copy)),
1231 LocalMutationIsAllowed::No,
1235 // Finally, check if path was already moved.
1236 self.check_if_path_or_subpath_is_moved(
1238 InitializationRequiringAction::Use,
1239 (place.as_ref(), span),
1244 &(Rvalue::Len(place) | Rvalue::Discriminant(place)) => {
1245 let af = match *rvalue {
1246 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1247 Rvalue::Discriminant(..) => None,
1248 _ => unreachable!(),
1253 (Shallow(af), Read(ReadKind::Copy)),
1254 LocalMutationIsAllowed::No,
1257 self.check_if_path_or_subpath_is_moved(
1259 InitializationRequiringAction::Use,
1260 (place.as_ref(), span),
1265 Rvalue::BinaryOp(_bin_op, box (operand1, operand2))
1266 | Rvalue::CheckedBinaryOp(_bin_op, box (operand1, operand2)) => {
1267 self.consume_operand(location, (operand1, span), flow_state);
1268 self.consume_operand(location, (operand2, span), flow_state);
1271 Rvalue::NullaryOp(_op, _ty) => {
1272 // nullary ops take no dynamic input; no borrowck effect.
1275 Rvalue::Aggregate(aggregate_kind, operands) => {
1276 // We need to report back the list of mutable upvars that were
1277 // moved into the closure and subsequently used by the closure,
1278 // in order to populate our used_mut set.
1279 match **aggregate_kind {
1280 AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
1281 let BorrowCheckResult { used_mut_upvars, .. } =
1282 self.infcx.tcx.mir_borrowck(def_id);
1283 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1284 for field in used_mut_upvars {
1285 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1288 AggregateKind::Adt(..)
1289 | AggregateKind::Array(..)
1290 | AggregateKind::Tuple { .. } => (),
1293 for operand in operands {
1294 self.consume_operand(location, (operand, span), flow_state);
1300 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1301 let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1302 // We have three possibilities here:
1303 // a. We are modifying something through a mut-ref
1304 // b. We are modifying something that is local to our parent
1305 // c. Current body is a nested closure, and we are modifying path starting from
1306 // a Place captured by our parent closure.
1308 // Handle (c), the path being modified is exactly the path captured by our parent
1309 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1310 this.used_mut_upvars.push(field);
1314 for (place_ref, proj) in place.iter_projections().rev() {
1316 if proj == ProjectionElem::Deref {
1317 match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1318 // We aren't modifying a variable directly
1319 ty::Ref(_, _, hir::Mutability::Mut) => return,
1326 if let Some(field) = this.is_upvar_field_projection(place_ref) {
1327 this.used_mut_upvars.push(field);
1333 this.used_mut.insert(place.local);
1336 // This relies on the current way that by-value
1337 // captures of a closure are copied/moved directly
1338 // when generating MIR.
1340 Operand::Move(place) | Operand::Copy(place) => {
1341 match place.as_local() {
1342 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1343 if self.body.local_decls[local].ty.is_mutable_ptr() {
1344 // The variable will be marked as mutable by the borrow.
1347 // This is an edge case where we have a `move` closure
1348 // inside a non-move closure, and the inner closure
1349 // contains a mutation:
1352 // || { move || { i += 1; }; };
1354 // In this case our usual strategy of assuming that the
1355 // variable will be captured by mutable reference is
1356 // wrong, since `i` can be copied into the inner
1357 // closure from a shared reference.
1359 // As such we have to search for the local that this
1360 // capture comes from and mark it as being used as mut.
1362 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1363 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1364 &self.move_data.inits[init_index]
1366 bug!("temporary should be initialized exactly once")
1369 let InitLocation::Statement(loc) = init.location else {
1370 bug!("temporary initialized in arguments")
1373 let body = self.body;
1374 let bbd = &body[loc.block];
1375 let stmt = &bbd.statements[loc.statement_index];
1376 debug!("temporary assigned in: stmt={:?}", stmt);
1378 if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, source))) = stmt.kind
1380 propagate_closure_used_mut_place(self, source);
1383 "closures should only capture user variables \
1384 or references to user variables"
1388 _ => propagate_closure_used_mut_place(self, place),
1391 Operand::Constant(..) => {}
1398 (operand, span): (&'cx Operand<'tcx>, Span),
1399 flow_state: &Flows<'cx, 'tcx>,
1402 Operand::Copy(place) => {
1403 // copy of place: check if this is "copy of frozen path"
1404 // (FIXME: see check_loans.rs)
1408 (Deep, Read(ReadKind::Copy)),
1409 LocalMutationIsAllowed::No,
1413 // Finally, check if path was already moved.
1414 self.check_if_path_or_subpath_is_moved(
1416 InitializationRequiringAction::Use,
1417 (place.as_ref(), span),
1421 Operand::Move(place) => {
1422 // move of place: check if this is move of already borrowed path
1426 (Deep, Write(WriteKind::Move)),
1427 LocalMutationIsAllowed::Yes,
1431 // Finally, check if path was already moved.
1432 self.check_if_path_or_subpath_is_moved(
1434 InitializationRequiringAction::Use,
1435 (place.as_ref(), span),
1439 Operand::Constant(_) => {}
1443 /// Checks whether a borrow of this place is invalidated when the function
1445 #[instrument(level = "debug", skip(self))]
1446 fn check_for_invalidation_at_exit(
1449 borrow: &BorrowData<'tcx>,
1452 let place = borrow.borrowed_place;
1453 let mut root_place = PlaceRef { local: place.local, projection: &[] };
1455 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1456 // we just know that all locals are dropped at function exit (otherwise
1457 // we'll have a memory leak) and assume that all statics have a destructor.
1459 // FIXME: allow thread-locals to borrow other thread locals?
1461 let (might_be_alive, will_be_dropped) =
1462 if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1463 // Thread-locals might be dropped after the function exits
1464 // We have to dereference the outer reference because
1465 // borrows don't conflict behind shared references.
1466 root_place.projection = TyCtxtConsts::DEREF_PROJECTION;
1469 (false, self.locals_are_invalidated_at_exit)
1472 if !will_be_dropped {
1473 debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
1477 let sd = if might_be_alive { Deep } else { Shallow(None) };
1479 if places_conflict::borrow_conflicts_with_place(
1486 places_conflict::PlaceConflictBias::Overlap,
1488 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1489 // FIXME: should be talking about the region lifetime instead
1490 // of just a span here.
1491 let span = self.infcx.tcx.sess.source_map().end_point(span);
1492 self.report_borrowed_value_does_not_live_long_enough(
1501 /// Reports an error if this is a borrow of local data.
1502 /// This is called for all Yield expressions on movable generators
1503 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1504 debug!("check_for_local_borrow({:?})", borrow);
1506 if borrow_of_local_data(borrow.borrowed_place) {
1507 let err = self.cannot_borrow_across_generator_yield(
1508 self.retrieve_borrow_spans(borrow).var_or_use(),
1512 self.buffer_error(err);
1516 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1517 // Two-phase borrow support: For each activation that is newly
1518 // generated at this statement, check if it interferes with
1520 let borrow_set = self.borrow_set.clone();
1521 for &borrow_index in borrow_set.activations_at_location(location) {
1522 let borrow = &borrow_set[borrow_index];
1524 // only mutable borrows should be 2-phase
1525 assert!(match borrow.kind {
1526 BorrowKind::Shared | BorrowKind::Shallow => false,
1527 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1532 (borrow.borrowed_place, span),
1533 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1534 LocalMutationIsAllowed::No,
1537 // We do not need to call `check_if_path_or_subpath_is_moved`
1538 // again, as we already called it when we made the
1539 // initial reservation.
1543 fn check_if_full_path_is_moved(
1546 desired_action: InitializationRequiringAction,
1547 place_span: (PlaceRef<'tcx>, Span),
1548 flow_state: &Flows<'cx, 'tcx>,
1550 let maybe_uninits = &flow_state.uninits;
1554 // 1. Move of `a.b.c`, use of `a.b.c`
1555 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1556 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1557 // partial initialization support, one might have `a.x`
1558 // initialized but not `a.b`.
1562 // 4. Move of `a.b.c`, use of `a.b.d`
1563 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1564 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1565 // must have been initialized for the use to be sound.
1566 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1568 // The dataflow tracks shallow prefixes distinctly (that is,
1569 // field-accesses on P distinctly from P itself), in order to
1570 // track substructure initialization separately from the whole
1573 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1574 // which we have a MovePath is `a.b`, then that means that the
1575 // initialization state of `a.b` is all we need to inspect to
1576 // know if `a.b.c` is valid (and from that we infer that the
1577 // dereference and `.d` access is also valid, since we assume
1578 // `a.b.c` is assigned a reference to an initialized and
1579 // well-formed record structure.)
1581 // Therefore, if we seek out the *closest* prefix for which we
1582 // have a MovePath, that should capture the initialization
1583 // state for the place scenario.
1585 // This code covers scenarios 1, 2, and 3.
1587 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1588 let (prefix, mpi) = self.move_path_closest_to(place_span.0);
1589 if maybe_uninits.contains(mpi) {
1590 self.report_use_of_moved_or_uninitialized(
1593 (prefix, place_span.0, place_span.1),
1596 } // Only query longest prefix with a MovePath, not further
1597 // ancestors; dataflow recurs on children when parents
1598 // move (to support partial (re)inits).
1600 // (I.e., querying parents breaks scenario 7; but may want
1601 // to do such a query based on partial-init feature-gate.)
1604 /// Subslices correspond to multiple move paths, so we iterate through the
1605 /// elements of the base array. For each element we check
1607 /// * Does this element overlap with our slice.
1608 /// * Is any part of it uninitialized.
1609 fn check_if_subslice_element_is_moved(
1612 desired_action: InitializationRequiringAction,
1613 place_span: (PlaceRef<'tcx>, Span),
1614 maybe_uninits: &ChunkedBitSet<MovePathIndex>,
1618 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1619 let move_paths = &self.move_data.move_paths;
1621 let root_path = &move_paths[mpi];
1622 for (child_mpi, child_move_path) in root_path.children(move_paths) {
1623 let last_proj = child_move_path.place.projection.last().unwrap();
1624 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
1625 debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
1627 if (from..to).contains(offset) {
1629 self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
1630 maybe_uninits.contains(mpi)
1633 if let Some(uninit_child) = uninit_child {
1634 self.report_use_of_moved_or_uninitialized(
1637 (place_span.0, place_span.0, place_span.1),
1640 return; // don't bother finding other problems.
1648 fn check_if_path_or_subpath_is_moved(
1651 desired_action: InitializationRequiringAction,
1652 place_span: (PlaceRef<'tcx>, Span),
1653 flow_state: &Flows<'cx, 'tcx>,
1655 let maybe_uninits = &flow_state.uninits;
1659 // 1. Move of `a.b.c`, use of `a` or `a.b`
1660 // partial initialization support, one might have `a.x`
1661 // initialized but not `a.b`.
1662 // 2. All bad scenarios from `check_if_full_path_is_moved`
1666 // 3. Move of `a.b.c`, use of `a.b.d`
1667 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1668 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1669 // must have been initialized for the use to be sound.
1670 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1672 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1674 if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
1675 place_span.0.last_projection()
1677 let place_ty = place_base.ty(self.body(), self.infcx.tcx);
1678 if let ty::Array(..) = place_ty.ty.kind() {
1679 self.check_if_subslice_element_is_moved(
1682 (place_base, place_span.1),
1691 // A move of any shallow suffix of `place` also interferes
1692 // with an attempt to use `place`. This is scenario 3 above.
1694 // (Distinct from handling of scenarios 1+2+4 above because
1695 // `place` does not interfere with suffixes of its prefixes,
1696 // e.g., `a.b.c` does not interfere with `a.b.d`)
1698 // This code covers scenario 1.
1700 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1701 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1702 let uninit_mpi = self
1704 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
1706 if let Some(uninit_mpi) = uninit_mpi {
1707 self.report_use_of_moved_or_uninitialized(
1710 (place_span.0, place_span.0, place_span.1),
1713 return; // don't bother finding other problems.
1718 /// Currently MoveData does not store entries for all places in
1719 /// the input MIR. For example it will currently filter out
1720 /// places that are Copy; thus we do not track places of shared
1721 /// reference type. This routine will walk up a place along its
1722 /// prefixes, searching for a foundational place that *is*
1723 /// tracked in the MoveData.
1725 /// An Err result includes a tag indicated why the search failed.
1726 /// Currently this can only occur if the place is built off of a
1727 /// static variable, as we do not track those in the MoveData.
1728 fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
1729 match self.move_data.rev_lookup.find(place) {
1730 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
1731 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
1733 LookupResult::Parent(None) => panic!("should have move path for every Local"),
1737 fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
1738 // If returns None, then there is no move path corresponding
1739 // to a direct owner of `place` (which means there is nothing
1740 // that borrowck tracks for its analysis).
1742 match self.move_data.rev_lookup.find(place) {
1743 LookupResult::Parent(_) => None,
1744 LookupResult::Exact(mpi) => Some(mpi),
1748 fn check_if_assigned_path_is_moved(
1751 (place, span): (Place<'tcx>, Span),
1752 flow_state: &Flows<'cx, 'tcx>,
1754 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1756 // None case => assigning to `x` does not require `x` be initialized.
1757 for (place_base, elem) in place.iter_projections().rev() {
1759 ProjectionElem::Index(_/*operand*/) |
1760 ProjectionElem::OpaqueCast(_) |
1761 ProjectionElem::ConstantIndex { .. } |
1762 // assigning to P[i] requires P to be valid.
1763 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1764 // assigning to (P->variant) is okay if assigning to `P` is okay
1766 // FIXME: is this true even if P is an adt with a dtor?
1769 // assigning to (*P) requires P to be initialized
1770 ProjectionElem::Deref => {
1771 self.check_if_full_path_is_moved(
1772 location, InitializationRequiringAction::Use,
1773 (place_base, span), flow_state);
1774 // (base initialized; no need to
1779 ProjectionElem::Subslice { .. } => {
1780 panic!("we don't allow assignments to subslices, location: {:?}",
1784 ProjectionElem::Field(..) => {
1785 // if type of `P` has a dtor, then
1786 // assigning to `P.f` requires `P` itself
1787 // be already initialized
1788 let tcx = self.infcx.tcx;
1789 let base_ty = place_base.ty(self.body(), tcx).ty;
1790 match base_ty.kind() {
1791 ty::Adt(def, _) if def.has_dtor(tcx) => {
1792 self.check_if_path_or_subpath_is_moved(
1793 location, InitializationRequiringAction::Assignment,
1794 (place_base, span), flow_state);
1796 // (base initialized; no need to
1801 // Once `let s; s.x = V; read(s.x);`,
1802 // is allowed, remove this match arm.
1803 ty::Adt(..) | ty::Tuple(..) => {
1804 check_parent_of_field(self, location, place_base, span, flow_state);
1806 // rust-lang/rust#21232, #54499, #54986: during period where we reject
1807 // partial initialization, do not complain about unnecessary `mut` on
1808 // an attempt to do a partial initialization.
1809 self.used_mut.insert(place.local);
1818 fn check_parent_of_field<'cx, 'tcx>(
1819 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1821 base: PlaceRef<'tcx>,
1823 flow_state: &Flows<'cx, 'tcx>,
1825 // rust-lang/rust#21232: Until Rust allows reads from the
1826 // initialized parts of partially initialized structs, we
1827 // will, starting with the 2018 edition, reject attempts
1828 // to write to structs that are not fully initialized.
1830 // In other words, *until* we allow this:
1832 // 1. `let mut s; s.x = Val; read(s.x);`
1834 // we will for now disallow this:
1836 // 2. `let mut s; s.x = Val;`
1840 // 3. `let mut s = ...; drop(s); s.x=Val;`
1842 // This does not use check_if_path_or_subpath_is_moved,
1843 // because we want to *allow* reinitializations of fields:
1844 // e.g., want to allow
1846 // `let mut s = ...; drop(s.x); s.x=Val;`
1848 // This does not use check_if_full_path_is_moved on
1849 // `base`, because that would report an error about the
1850 // `base` as a whole, but in this scenario we *really*
1851 // want to report an error about the actual thing that was
1852 // moved, which may be some prefix of `base`.
1854 // Shallow so that we'll stop at any dereference; we'll
1855 // report errors about issues with such bases elsewhere.
1856 let maybe_uninits = &flow_state.uninits;
1858 // Find the shortest uninitialized prefix you can reach
1859 // without going over a Deref.
1860 let mut shortest_uninit_seen = None;
1861 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1862 let Some(mpi) = this.move_path_for_place(prefix) else { continue };
1864 if maybe_uninits.contains(mpi) {
1866 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1867 shortest_uninit_seen,
1870 shortest_uninit_seen = Some((prefix, mpi));
1872 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1876 if let Some((prefix, mpi)) = shortest_uninit_seen {
1877 // Check for a reassignment into an uninitialized field of a union (for example,
1878 // after a move out). In this case, do not report an error here. There is an
1879 // exception, if this is the first assignment into the union (that is, there is
1880 // no move out from an earlier location) then this is an attempt at initialization
1881 // of the union - we should error in that case.
1882 let tcx = this.infcx.tcx;
1883 if base.ty(this.body(), tcx).ty.is_union() {
1884 if this.move_data.path_map[mpi].iter().any(|moi| {
1885 this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
1891 this.report_use_of_moved_or_uninitialized(
1893 InitializationRequiringAction::PartialAssignment,
1894 (prefix, base, span),
1901 /// Checks the permissions for the given place and read or write kind
1903 /// Returns `true` if an error is reported.
1904 fn check_access_permissions(
1906 (place, span): (Place<'tcx>, Span),
1908 is_local_mutation_allowed: LocalMutationIsAllowed,
1909 flow_state: &Flows<'cx, 'tcx>,
1913 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1914 place, kind, is_local_mutation_allowed
1921 Reservation(WriteKind::MutableBorrow(
1922 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
1924 | Write(WriteKind::MutableBorrow(
1925 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
1927 let is_local_mutation_allowed = match borrow_kind {
1928 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1929 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1930 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1932 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1934 self.add_used_mut(root_place, flow_state);
1938 error_access = AccessKind::MutableBorrow;
1939 the_place_err = place_err;
1943 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1944 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1946 self.add_used_mut(root_place, flow_state);
1950 error_access = AccessKind::Mutate;
1951 the_place_err = place_err;
1958 | WriteKind::StorageDeadOrDrop
1959 | WriteKind::MutableBorrow(BorrowKind::Shared)
1960 | WriteKind::MutableBorrow(BorrowKind::Shallow),
1964 | WriteKind::StorageDeadOrDrop
1965 | WriteKind::MutableBorrow(BorrowKind::Shared)
1966 | WriteKind::MutableBorrow(BorrowKind::Shallow),
1968 if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err()
1969 && !self.has_buffered_errors()
1971 // rust-lang/rust#46908: In pure NLL mode this code path should be
1972 // unreachable, but we use `delay_span_bug` because we can hit this when
1973 // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
1974 // enabled. We don't want to ICE for that case, as other errors will have
1975 // been emitted (#52262).
1976 self.infcx.tcx.sess.delay_span_bug(
1979 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
1987 // permission checks are done at Reservation point.
1993 | BorrowKind::Mut { .. }
1994 | BorrowKind::Shared
1995 | BorrowKind::Shallow,
1999 // Access authorized
2004 // rust-lang/rust#21232, #54986: during period where we reject
2005 // partial initialization, do not complain about mutability
2006 // errors except for actual mutation (as opposed to an attempt
2007 // to do a partial initialization).
2008 let previously_initialized = self.is_local_ever_initialized(place.local, flow_state);
2010 // at this point, we have set up the error reporting state.
2011 if let Some(init_index) = previously_initialized {
2012 if let (AccessKind::Mutate, Some(_)) = (error_access, place.as_local()) {
2013 // If this is a mutate access to an immutable local variable with no projections
2014 // report the error as an illegal reassignment
2015 let init = &self.move_data.inits[init_index];
2016 let assigned_span = init.span(&self.body);
2017 self.report_illegal_reassignment(location, (place, span), assigned_span, place);
2019 self.report_mutability_error(place, span, the_place_err, error_access, location)
2027 fn is_local_ever_initialized(
2030 flow_state: &Flows<'cx, 'tcx>,
2031 ) -> Option<InitIndex> {
2032 let mpi = self.move_data.rev_lookup.find_local(local);
2033 let ii = &self.move_data.init_path_map[mpi];
2034 ii.into_iter().find(|&&index| flow_state.ever_inits.contains(index)).copied()
2037 /// Adds the place into the used mutable variables set
2038 fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2040 RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2041 // If the local may have been initialized, and it is now currently being
2042 // mutated, then it is justified to be annotated with the `mut`
2043 // keyword, since the mutation may be a possible reassignment.
2044 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2045 && self.is_local_ever_initialized(local, flow_state).is_some()
2047 self.used_mut.insert(local);
2052 place_projection: _,
2053 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2057 place_projection: place_projection @ [.., _],
2058 is_local_mutation_allowed: _,
2060 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2062 projection: place_projection,
2064 self.used_mut_upvars.push(field);
2070 /// Whether this value can be written or borrowed mutably.
2071 /// Returns the root place if the place passed in is a projection.
2074 place: PlaceRef<'tcx>,
2075 is_local_mutation_allowed: LocalMutationIsAllowed,
2076 ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2077 debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2078 match place.last_projection() {
2080 let local = &self.body.local_decls[place.local];
2081 match local.mutability {
2082 Mutability::Not => match is_local_mutation_allowed {
2083 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2084 place_local: place.local,
2085 place_projection: place.projection,
2086 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2088 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2089 place_local: place.local,
2090 place_projection: place.projection,
2091 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2093 LocalMutationIsAllowed::No => Err(place),
2095 Mutability::Mut => Ok(RootPlace {
2096 place_local: place.local,
2097 place_projection: place.projection,
2098 is_local_mutation_allowed,
2102 Some((place_base, elem)) => {
2104 ProjectionElem::Deref => {
2105 let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2107 // Check the kind of deref to decide
2108 match base_ty.kind() {
2109 ty::Ref(_, _, mutbl) => {
2111 // Shared borrowed data is never mutable
2112 hir::Mutability::Not => Err(place),
2113 // Mutably borrowed data is mutable, but only if we have a
2114 // unique path to the `&mut`
2115 hir::Mutability::Mut => {
2116 let mode = match self.is_upvar_field_projection(place) {
2117 Some(field) if self.upvars[field.index()].by_ref => {
2118 is_local_mutation_allowed
2120 _ => LocalMutationIsAllowed::Yes,
2123 self.is_mutable(place_base, mode)
2127 ty::RawPtr(tnm) => {
2129 // `*const` raw pointers are not mutable
2130 hir::Mutability::Not => Err(place),
2131 // `*mut` raw pointers are always mutable, regardless of
2132 // context. The users have to check by themselves.
2133 hir::Mutability::Mut => Ok(RootPlace {
2134 place_local: place.local,
2135 place_projection: place.projection,
2136 is_local_mutation_allowed,
2140 // `Box<T>` owns its content, so mutable if its location is mutable
2141 _ if base_ty.is_box() => {
2142 self.is_mutable(place_base, is_local_mutation_allowed)
2144 // Deref should only be for reference, pointers or boxes
2145 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2148 // All other projections are owned by their base path, so mutable if
2149 // base path is mutable
2150 ProjectionElem::Field(..)
2151 | ProjectionElem::Index(..)
2152 | ProjectionElem::ConstantIndex { .. }
2153 | ProjectionElem::Subslice { .. }
2154 | ProjectionElem::OpaqueCast { .. }
2155 | ProjectionElem::Downcast(..) => {
2156 let upvar_field_projection = self.is_upvar_field_projection(place);
2157 if let Some(field) = upvar_field_projection {
2158 let upvar = &self.upvars[field.index()];
2160 "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2161 place={:?}, place_base={:?}",
2162 upvar, is_local_mutation_allowed, place, place_base
2164 match (upvar.place.mutability, is_local_mutation_allowed) {
2167 LocalMutationIsAllowed::No
2168 | LocalMutationIsAllowed::ExceptUpvars,
2170 (Mutability::Not, LocalMutationIsAllowed::Yes)
2171 | (Mutability::Mut, _) => {
2172 // Subtle: this is an upvar
2173 // reference, so it looks like
2174 // `self.foo` -- we want to double
2175 // check that the location `*self`
2176 // is mutable (i.e., this is not a
2177 // `Fn` closure). But if that
2178 // check succeeds, we want to
2179 // *blame* the mutability on
2180 // `place` (that is,
2181 // `self.foo`). This is used to
2182 // propagate the info about
2183 // whether mutability declarations
2184 // are used outwards, so that we register
2185 // the outer variable as mutable. Otherwise a
2186 // test like this fails to record the `mut`
2190 // fn foo<F: FnOnce()>(_f: F) { }
2192 // let var = Vec::new();
2199 self.is_mutable(place_base, is_local_mutation_allowed)?;
2201 place_local: place.local,
2202 place_projection: place.projection,
2203 is_local_mutation_allowed,
2208 self.is_mutable(place_base, is_local_mutation_allowed)
2216 /// If `place` is a field projection, and the field is being projected from a closure type,
2217 /// then returns the index of the field being projected. Note that this closure will always
2218 /// be `self` in the current MIR, because that is the only time we directly access the fields
2219 /// of a closure type.
2220 fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> {
2221 path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2224 fn dominators(&self) -> &Dominators<BasicBlock> {
2225 self.dominators.get_or_init(|| self.body.basic_blocks.dominators())
2230 use rustc_errors::ErrorGuaranteed;
2234 pub struct BorrowckErrors<'tcx> {
2236 /// This field keeps track of move errors that are to be reported for given move indices.
2238 /// There are situations where many errors can be reported for a single move out (see #53807)
2239 /// and we want only the best of those errors.
2241 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
2242 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
2243 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
2244 /// all move errors have been reported, any diagnostics in this map are added to the buffer
2247 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
2248 /// when errors in the map are being re-added to the error buffer so that errors with the
2249 /// same primary span come out in a consistent order.
2250 buffered_move_errors:
2251 BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorGuaranteed>)>,
2252 buffered_mut_errors: FxHashMap<Span, (DiagnosticBuilder<'tcx, ErrorGuaranteed>, usize)>,
2253 /// Diagnostics to be reported buffer.
2254 buffered: Vec<Diagnostic>,
2255 /// Set to Some if we emit an error during borrowck
2256 tainted_by_errors: Option<ErrorGuaranteed>,
2259 impl<'tcx> BorrowckErrors<'tcx> {
2260 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
2263 buffered_move_errors: BTreeMap::new(),
2264 buffered_mut_errors: Default::default(),
2265 buffered: Default::default(),
2266 tainted_by_errors: None,
2270 pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorGuaranteed>) {
2271 if let None = self.tainted_by_errors {
2272 self.tainted_by_errors = Some(
2275 .delay_span_bug(t.span.clone(), "diagnostic buffered but not emitted"),
2278 t.buffer(&mut self.buffered);
2281 pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) {
2282 t.buffer(&mut self.buffered);
2285 pub fn set_tainted_by_errors(&mut self, e: ErrorGuaranteed) {
2286 self.tainted_by_errors = Some(e);
2290 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
2291 pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorGuaranteed>) {
2292 self.errors.buffer_error(t);
2295 pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) {
2296 self.errors.buffer_non_error_diag(t);
2299 pub fn buffer_move_error(
2301 move_out_indices: Vec<MoveOutIndex>,
2302 place_and_err: (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorGuaranteed>),
2304 if let Some((_, diag)) =
2305 self.errors.buffered_move_errors.insert(move_out_indices, place_and_err)
2307 // Cancel the old diagnostic so we don't ICE
2315 pub fn get_buffered_mut_error(
2318 ) -> Option<(DiagnosticBuilder<'tcx, ErrorGuaranteed>, usize)> {
2319 self.errors.buffered_mut_errors.remove(&span)
2322 pub fn buffer_mut_error(
2325 t: DiagnosticBuilder<'tcx, ErrorGuaranteed>,
2328 self.errors.buffered_mut_errors.insert(span, (t, count));
2331 pub fn emit_errors(&mut self) -> Option<ErrorGuaranteed> {
2332 // Buffer any move errors that we collected and de-duplicated.
2333 for (_, (_, diag)) in std::mem::take(&mut self.errors.buffered_move_errors) {
2334 // We have already set tainted for this error, so just buffer it.
2335 diag.buffer(&mut self.errors.buffered);
2337 for (_, (mut diag, count)) in std::mem::take(&mut self.errors.buffered_mut_errors) {
2339 diag.note(&format!("...and {} other attempted mutable borrows", count - 10));
2341 diag.buffer(&mut self.errors.buffered);
2344 if !self.errors.buffered.is_empty() {
2345 self.errors.buffered.sort_by_key(|diag| diag.sort_span);
2347 for mut diag in self.errors.buffered.drain(..) {
2348 self.infcx.tcx.sess.diagnostic().emit_diagnostic(&mut diag);
2352 self.errors.tainted_by_errors
2355 pub fn has_buffered_errors(&self) -> bool {
2356 self.errors.buffered.is_empty()
2359 pub fn has_move_error(
2361 move_out_indices: &[MoveOutIndex],
2362 ) -> Option<&(PlaceRef<'tcx>, DiagnosticBuilder<'cx, ErrorGuaranteed>)> {
2363 self.errors.buffered_move_errors.get(move_out_indices)
2368 /// The degree of overlap between 2 places for borrow-checking.
2370 /// The places might partially overlap - in this case, we give
2371 /// up and say that they might conflict. This occurs when
2372 /// different fields of a union are borrowed. For example,
2373 /// if `u` is a union, we have no way of telling how disjoint
2374 /// `u.a.x` and `a.b.y` are.
2376 /// The places have the same type, and are either completely disjoint
2377 /// or equal - i.e., they can't "partially" overlap as can occur with
2378 /// unions. This is the "base case" on which we recur for extensions
2381 /// The places are disjoint, so we know all extensions of them
2382 /// will also be disjoint.