1 //! This query borrow-checks the MIR to (further) ensure it is not broken.
3 #![feature(bool_to_option)]
4 #![feature(box_patterns)]
5 #![feature(crate_visibility_modifier)]
7 #![feature(min_specialization)]
8 #![feature(stmt_expr_attributes)]
9 #![feature(trusted_step)]
10 #![feature(try_blocks)]
11 #![recursion_limit = "256"]
12 #![cfg_attr(not(bootstrap), allow(rustc::potential_query_instability))]
15 extern crate rustc_middle;
19 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
20 use rustc_data_structures::graph::dominators::Dominators;
21 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorReported};
23 use rustc_hir::def_id::LocalDefId;
25 use rustc_index::bit_set::ChunkedBitSet;
26 use rustc_index::vec::IndexVec;
27 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
28 use rustc_middle::mir::{
29 traversal, Body, ClearCrossCrate, Local, Location, Mutability, Operand, Place, PlaceElem,
30 PlaceRef, VarDebugInfoContents,
32 use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
33 use rustc_middle::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
34 use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind};
35 use rustc_middle::ty::query::Providers;
36 use rustc_middle::ty::{self, CapturedPlace, ParamEnv, RegionVid, TyCtxt};
37 use rustc_session::lint::builtin::{MUTABLE_BORROW_RESERVATION_CONFLICT, UNUSED_MUT};
38 use rustc_span::{Span, Symbol, DUMMY_SP};
41 use smallvec::SmallVec;
42 use std::cell::RefCell;
43 use std::collections::BTreeMap;
47 use rustc_mir_dataflow::impls::{
48 EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces,
50 use rustc_mir_dataflow::move_paths::{InitIndex, MoveOutIndex, MovePathIndex};
51 use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveData, MoveError};
52 use rustc_mir_dataflow::Analysis;
53 use rustc_mir_dataflow::MoveDataParamEnv;
55 use self::diagnostics::{AccessKind, RegionName};
56 use self::location::LocationTable;
57 use self::prefixes::PrefixSet;
60 use self::path_utils::*;
64 mod constraint_generation;
72 mod member_constraints;
81 mod universal_regions;
84 // A public API provided for the Rust compiler consumers.
87 use borrow_set::{BorrowData, BorrowSet};
88 use dataflow::{BorrowIndex, BorrowckFlowState as Flows, BorrowckResults, Borrows};
89 use nll::{PoloniusOutput, ToRegionVid};
90 use place_ext::PlaceExt;
91 use places_conflict::{places_conflict, PlaceConflictBias};
92 use region_infer::RegionInferenceContext;
94 // FIXME(eddyb) perhaps move this somewhere more centrally.
97 place: CapturedPlace<'tcx>,
99 /// If true, the capture is behind a reference.
103 const DEREF_PROJECTION: &[PlaceElem<'_>; 1] = &[ProjectionElem::Deref];
105 pub fn provide(providers: &mut Providers) {
106 *providers = Providers {
107 mir_borrowck: |tcx, did| {
108 if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
109 tcx.mir_borrowck_const_arg(def)
111 mir_borrowck(tcx, ty::WithOptConstParam::unknown(did))
114 mir_borrowck_const_arg: |tcx, (did, param_did)| {
115 mir_borrowck(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
121 fn mir_borrowck<'tcx>(
123 def: ty::WithOptConstParam<LocalDefId>,
124 ) -> &'tcx BorrowCheckResult<'tcx> {
125 let (input_body, promoted) = tcx.mir_promoted(def);
126 debug!("run query mir_borrowck: {}", tcx.def_path_str(def.did.to_def_id()));
128 let opt_closure_req = tcx.infer_ctxt().with_opaque_type_inference(def.did).enter(|infcx| {
129 let input_body: &Body<'_> = &input_body.borrow();
130 let promoted: &IndexVec<_, _> = &promoted.borrow();
131 do_mir_borrowck(&infcx, input_body, promoted, false).0
133 debug!("mir_borrowck done");
135 tcx.arena.alloc(opt_closure_req)
138 /// Perform the actual borrow checking.
140 /// If `return_body_with_facts` is true, then return the body with non-erased
141 /// region ids on which the borrow checking was performed together with Polonius
143 #[instrument(skip(infcx, input_body, input_promoted), level = "debug")]
144 fn do_mir_borrowck<'a, 'tcx>(
145 infcx: &InferCtxt<'a, 'tcx>,
146 input_body: &Body<'tcx>,
147 input_promoted: &IndexVec<Promoted, Body<'tcx>>,
148 return_body_with_facts: bool,
149 ) -> (BorrowCheckResult<'tcx>, Option<Box<BodyWithBorrowckFacts<'tcx>>>) {
150 let def = input_body.source.with_opt_param().as_local().unwrap();
155 let param_env = tcx.param_env(def.did);
156 let id = tcx.hir().local_def_id_to_hir_id(def.did);
158 let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
159 for var_debug_info in &input_body.var_debug_info {
160 if let VarDebugInfoContents::Place(place) = var_debug_info.value {
161 if let Some(local) = place.as_local() {
162 if let Some(prev_name) = local_names[local] {
163 if var_debug_info.name != prev_name {
165 var_debug_info.source_info.span,
166 "local {:?} has many names (`{}` vs `{}`)",
173 local_names[local] = Some(var_debug_info.name);
178 let mut errors = error::BorrowckErrors::new();
180 // Gather the upvars of a closure, if any.
181 let tables = tcx.typeck_opt_const_arg(def);
182 if let Some(ErrorReported) = tables.tainted_by_errors {
183 infcx.set_tainted_by_errors();
184 errors.set_tainted_by_errors();
186 let upvars: Vec<_> = tables
187 .closure_min_captures_flattened(def.did.to_def_id())
188 .map(|captured_place| {
189 let capture = captured_place.info.capture_kind;
190 let by_ref = match capture {
191 ty::UpvarCapture::ByValue => false,
192 ty::UpvarCapture::ByRef(..) => true,
194 Upvar { place: captured_place.clone(), by_ref }
198 // Replace all regions with fresh inference variables. This
199 // requires first making our own copy of the MIR. This copy will
200 // be modified (in place) to contain non-lexical lifetimes. It
201 // will have a lifetime tied to the inference context.
202 let mut body_owned = input_body.clone();
203 let mut promoted = input_promoted.clone();
205 nll::replace_regions_in_mir(infcx, param_env, &mut body_owned, &mut promoted);
206 let body = &body_owned; // no further changes
208 let location_table_owned = LocationTable::new(body);
209 let location_table = &location_table_owned;
211 let (move_data, move_errors): (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>) =
212 match MoveData::gather_moves(&body, tcx, param_env) {
213 Ok(move_data) => (move_data, Vec::new()),
214 Err((move_data, move_errors)) => (move_data, move_errors),
216 let promoted_errors = promoted
218 .map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env)));
220 let mdpe = MoveDataParamEnv { move_data, param_env };
222 let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe)
223 .into_engine(tcx, &body)
224 .pass_name("borrowck")
225 .iterate_to_fixpoint()
226 .into_results_cursor(&body);
228 let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
230 Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
232 let use_polonius = return_body_with_facts || infcx.tcx.sess.opts.debugging_opts.polonius;
234 // Compute non-lexical lifetimes.
242 } = nll::compute_regions(
256 // Dump MIR results into a file, if that is enabled. This let us
257 // write unit-tests, as well as helping with debugging.
258 nll::dump_mir_results(infcx, &body, ®ioncx, &opt_closure_req);
260 // We also have a `#[rustc_regions]` annotation that causes us to dump
262 nll::dump_annotation(
271 // The various `flow_*` structures can be large. We drop `flow_inits` here
272 // so it doesn't overlap with the others below. This reduces peak memory
273 // usage significantly on some benchmarks.
276 let regioncx = Rc::new(regioncx);
278 let flow_borrows = Borrows::new(tcx, body, ®ioncx, &borrow_set)
279 .into_engine(tcx, body)
280 .pass_name("borrowck")
281 .iterate_to_fixpoint();
282 let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &mdpe)
283 .into_engine(tcx, body)
284 .pass_name("borrowck")
285 .iterate_to_fixpoint();
286 let flow_ever_inits = EverInitializedPlaces::new(tcx, body, &mdpe)
287 .into_engine(tcx, body)
288 .pass_name("borrowck")
289 .iterate_to_fixpoint();
291 let movable_generator = !matches!(
293 Node::Expr(&hir::Expr {
294 kind: hir::ExprKind::Closure(.., Some(hir::Movability::Static)),
299 for (idx, move_data_results) in promoted_errors {
300 let promoted_body = &promoted[idx];
302 if let Err((move_data, move_errors)) = move_data_results {
303 let mut promoted_mbcx = MirBorrowckCtxt {
307 move_data: &move_data,
308 location_table, // no need to create a real one for the promoted, it is not used
310 fn_self_span_reported: Default::default(),
311 locals_are_invalidated_at_exit,
312 access_place_error_reported: Default::default(),
313 reservation_error_reported: Default::default(),
314 reservation_warnings: Default::default(),
315 uninitialized_error_reported: Default::default(),
316 regioncx: regioncx.clone(),
317 used_mut: Default::default(),
318 used_mut_upvars: SmallVec::new(),
319 borrow_set: Rc::clone(&borrow_set),
320 dominators: Dominators::dummy(), // not used
322 local_names: IndexVec::from_elem(None, &promoted_body.local_decls),
323 region_names: RefCell::default(),
324 next_region_name: RefCell::new(1),
325 polonius_output: None,
328 promoted_mbcx.report_move_errors(move_errors);
329 errors = promoted_mbcx.errors;
333 let dominators = body.dominators();
335 let mut mbcx = MirBorrowckCtxt {
339 move_data: &mdpe.move_data,
342 locals_are_invalidated_at_exit,
343 fn_self_span_reported: Default::default(),
344 access_place_error_reported: Default::default(),
345 reservation_error_reported: Default::default(),
346 reservation_warnings: Default::default(),
347 uninitialized_error_reported: Default::default(),
348 regioncx: Rc::clone(®ioncx),
349 used_mut: Default::default(),
350 used_mut_upvars: SmallVec::new(),
351 borrow_set: Rc::clone(&borrow_set),
355 region_names: RefCell::default(),
356 next_region_name: RefCell::new(1),
361 // Compute and report region errors, if any.
362 mbcx.report_region_errors(nll_errors);
364 let results = BorrowckResults {
365 ever_inits: flow_ever_inits,
366 uninits: flow_uninits,
367 borrows: flow_borrows,
370 mbcx.report_move_errors(move_errors);
372 rustc_mir_dataflow::visit_results(
374 traversal::reverse_postorder(body).map(|(bb, _)| bb),
379 // Convert any reservation warnings into lints.
380 let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
381 for (_, (place, span, location, bk, borrow)) in reservation_warnings {
382 let initial_diag = mbcx.report_conflicting_borrow(location, (place, span), bk, &borrow);
384 let scope = mbcx.body.source_info(location).scope;
385 let lint_root = match &mbcx.body.source_scopes[scope].local_data {
386 ClearCrossCrate::Set(data) => data.lint_root,
390 // Span and message don't matter; we overwrite them below anyway
391 mbcx.infcx.tcx.struct_span_lint_hir(
392 MUTABLE_BORROW_RESERVATION_CONFLICT,
396 let mut diag = lint.build("");
398 diag.message = initial_diag.styled_message().clone();
399 diag.span = initial_diag.span.clone();
401 mbcx.buffer_non_error_diag(diag);
404 initial_diag.cancel();
407 // For each non-user used mutable variable, check if it's been assigned from
408 // a user-declared local. If so, then put that local into the used_mut set.
409 // Note that this set is expected to be small - only upvars from closures
410 // would have a chance of erroneously adding non-user-defined mutable vars
412 let temporary_used_locals: FxHashSet<Local> = mbcx
415 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
418 // For the remaining unused locals that are marked as mutable, we avoid linting any that
419 // were never initialized. These locals may have been removed as unreachable code; or will be
420 // linted as unused variables.
421 let unused_mut_locals =
422 mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
423 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
425 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
426 let used_mut = std::mem::take(&mut mbcx.used_mut);
427 for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
428 let local_decl = &mbcx.body.local_decls[local];
429 let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data {
430 ClearCrossCrate::Set(data) => data.lint_root,
434 // Skip over locals that begin with an underscore or have no name
435 match mbcx.local_names[local] {
437 if name.as_str().starts_with('_') {
444 let span = local_decl.source_info.span;
445 if span.desugaring_kind().is_some() {
446 // If the `mut` arises as part of a desugaring, we should ignore it.
450 tcx.struct_span_lint_hir(UNUSED_MUT, lint_root, span, |lint| {
451 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
452 lint.build("variable does not need to be mutable")
453 .span_suggestion_short(
457 Applicability::MachineApplicable,
463 let tainted_by_errors = mbcx.emit_errors();
465 let result = BorrowCheckResult {
466 concrete_opaque_types: opaque_type_values,
467 closure_requirements: opt_closure_req,
468 used_mut_upvars: mbcx.used_mut_upvars,
472 let body_with_facts = if return_body_with_facts {
473 let output_facts = mbcx.polonius_output.expect("Polonius output was not computed");
474 Some(Box::new(BodyWithBorrowckFacts {
476 input_facts: *polonius_input.expect("Polonius input facts were not generated"),
478 location_table: location_table_owned,
484 debug!("do_mir_borrowck: result = {:#?}", result);
486 (result, body_with_facts)
489 /// A `Body` with information computed by the borrow checker. This struct is
490 /// intended to be consumed by compiler consumers.
492 /// We need to include the MIR body here because the region identifiers must
493 /// match the ones in the Polonius facts.
494 pub struct BodyWithBorrowckFacts<'tcx> {
495 /// A mir body that contains region identifiers.
496 pub body: Body<'tcx>,
497 /// Polonius input facts.
498 pub input_facts: AllFacts,
499 /// Polonius output facts.
500 pub output_facts: Rc<self::nll::PoloniusOutput>,
501 /// The table that maps Polonius points to locations in the table.
502 pub location_table: LocationTable,
505 struct MirBorrowckCtxt<'cx, 'tcx> {
506 infcx: &'cx InferCtxt<'cx, 'tcx>,
507 param_env: ParamEnv<'tcx>,
508 body: &'cx Body<'tcx>,
509 move_data: &'cx MoveData<'tcx>,
511 /// Map from MIR `Location` to `LocationIndex`; created
512 /// when MIR borrowck begins.
513 location_table: &'cx LocationTable,
515 movable_generator: bool,
516 /// This keeps track of whether local variables are free-ed when the function
517 /// exits even without a `StorageDead`, which appears to be the case for
520 /// I'm not sure this is the right approach - @eddyb could you try and
522 locals_are_invalidated_at_exit: bool,
523 /// This field keeps track of when borrow errors are reported in the access_place function
524 /// so that there is no duplicate reporting. This field cannot also be used for the conflicting
525 /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
526 /// of the `Span` type (while required to mute some errors) stops the muting of the reservation
528 access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
529 /// This field keeps track of when borrow conflict errors are reported
530 /// for reservations, so that we don't report seemingly duplicate
531 /// errors for corresponding activations.
533 // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
534 // but it is currently inconvenient to track down the `BorrowIndex`
535 // at the time we detect and report a reservation error.
536 reservation_error_reported: FxHashSet<Place<'tcx>>,
537 /// This fields keeps track of the `Span`s that we have
538 /// used to report extra information for `FnSelfUse`, to avoid
539 /// unnecessarily verbose errors.
540 fn_self_span_reported: FxHashSet<Span>,
541 /// Migration warnings to be reported for #56254. We delay reporting these
542 /// so that we can suppress the warning if there's a corresponding error
543 /// for the activation of the borrow.
544 reservation_warnings:
545 FxHashMap<BorrowIndex, (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)>,
546 /// This field keeps track of errors reported in the checking of uninitialized variables,
547 /// so that we don't report seemingly duplicate errors.
548 uninitialized_error_reported: FxHashSet<PlaceRef<'tcx>>,
549 /// This field keeps track of all the local variables that are declared mut and are mutated.
550 /// Used for the warning issued by an unused mutable local variable.
551 used_mut: FxHashSet<Local>,
552 /// If the function we're checking is a closure, then we'll need to report back the list of
553 /// mutable upvars that have been used. This field keeps track of them.
554 used_mut_upvars: SmallVec<[Field; 8]>,
555 /// Region inference context. This contains the results from region inference and lets us e.g.
556 /// find out which CFG points are contained in each borrow region.
557 regioncx: Rc<RegionInferenceContext<'tcx>>,
559 /// The set of borrows extracted from the MIR
560 borrow_set: Rc<BorrowSet<'tcx>>,
562 /// Dominators for MIR
563 dominators: Dominators<BasicBlock>,
565 /// Information about upvars not necessarily preserved in types or MIR
566 upvars: Vec<Upvar<'tcx>>,
568 /// Names of local (user) variables (extracted from `var_debug_info`).
569 local_names: IndexVec<Local, Option<Symbol>>,
571 /// Record the region names generated for each region in the given
572 /// MIR def so that we can reuse them later in help/error messages.
573 region_names: RefCell<FxHashMap<RegionVid, RegionName>>,
575 /// The counter for generating new region names.
576 next_region_name: RefCell<usize>,
578 /// Results of Polonius analysis.
579 polonius_output: Option<Rc<PoloniusOutput>>,
581 errors: error::BorrowckErrors<'tcx>,
585 // 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
586 // 2. loans made in overlapping scopes do not conflict
587 // 3. assignments do not affect things loaned out as immutable
588 // 4. moves do not affect things loaned out in any way
589 impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
590 type FlowState = Flows<'cx, 'tcx>;
592 fn visit_statement_before_primary_effect(
594 flow_state: &Flows<'cx, 'tcx>,
595 stmt: &'cx Statement<'tcx>,
598 debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state);
599 let span = stmt.source_info.span;
601 self.check_activations(location, span, flow_state);
604 StatementKind::Assign(box (lhs, ref rhs)) => {
605 self.consume_rvalue(location, (rhs, span), flow_state);
607 self.mutate_place(location, (*lhs, span), Shallow(None), flow_state);
609 StatementKind::FakeRead(box (_, ref place)) => {
610 // Read for match doesn't access any memory and is used to
611 // assert that a place is safe and live. So we don't have to
612 // do any checks here.
614 // FIXME: Remove check that the place is initialized. This is
615 // needed for now because matches don't have never patterns yet.
616 // So this is the only place we prevent
620 self.check_if_path_or_subpath_is_moved(
622 InitializationRequiringAction::Use,
623 (place.as_ref(), span),
627 StatementKind::SetDiscriminant { place, variant_index: _ } => {
628 self.mutate_place(location, (**place, span), Shallow(None), flow_state);
630 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
635 "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
639 | StatementKind::Coverage(..)
640 | StatementKind::AscribeUserType(..)
641 | StatementKind::Retag { .. }
642 | StatementKind::StorageLive(..) => {
643 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
646 StatementKind::StorageDead(local) => {
649 (Place::from(*local), span),
650 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
651 LocalMutationIsAllowed::Yes,
658 fn visit_terminator_before_primary_effect(
660 flow_state: &Flows<'cx, 'tcx>,
661 term: &'cx Terminator<'tcx>,
664 debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
665 let span = term.source_info.span;
667 self.check_activations(loc, span, flow_state);
670 TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => {
671 self.consume_operand(loc, (discr, span), flow_state);
673 TerminatorKind::Drop { place, target: _, unwind: _ } => {
675 "visit_terminator_drop \
676 loc: {:?} term: {:?} place: {:?} span: {:?}",
677 loc, term, place, span
683 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
684 LocalMutationIsAllowed::Yes,
688 TerminatorKind::DropAndReplace {
690 value: ref new_value,
694 self.mutate_place(loc, (drop_place, span), Deep, flow_state);
695 self.consume_operand(loc, (new_value, span), flow_state);
697 TerminatorKind::Call {
705 self.consume_operand(loc, (func, span), flow_state);
707 self.consume_operand(loc, (arg, span), flow_state);
709 if let Some((dest, _ /*bb*/)) = *destination {
710 self.mutate_place(loc, (dest, span), Deep, flow_state);
713 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
714 self.consume_operand(loc, (cond, span), flow_state);
715 use rustc_middle::mir::AssertKind;
716 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
717 self.consume_operand(loc, (len, span), flow_state);
718 self.consume_operand(loc, (index, span), flow_state);
722 TerminatorKind::Yield { ref value, resume: _, resume_arg, drop: _ } => {
723 self.consume_operand(loc, (value, span), flow_state);
724 self.mutate_place(loc, (resume_arg, span), Deep, flow_state);
727 TerminatorKind::InlineAsm {
737 InlineAsmOperand::In { reg: _, ref value } => {
738 self.consume_operand(loc, (value, span), flow_state);
740 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
741 if let Some(place) = place {
742 self.mutate_place(loc, (place, span), Shallow(None), flow_state);
745 InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
746 self.consume_operand(loc, (in_value, span), flow_state);
747 if let Some(out_place) = out_place {
756 InlineAsmOperand::Const { value: _ }
757 | InlineAsmOperand::SymFn { value: _ }
758 | InlineAsmOperand::SymStatic { def_id: _ } => {}
763 TerminatorKind::Goto { target: _ }
764 | TerminatorKind::Abort
765 | TerminatorKind::Unreachable
766 | TerminatorKind::Resume
767 | TerminatorKind::Return
768 | TerminatorKind::GeneratorDrop
769 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
770 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
771 // no data used, thus irrelevant to borrowck
776 fn visit_terminator_after_primary_effect(
778 flow_state: &Flows<'cx, 'tcx>,
779 term: &'cx Terminator<'tcx>,
782 let span = term.source_info.span;
785 TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
786 if self.movable_generator {
787 // Look for any active borrows to locals
788 let borrow_set = self.borrow_set.clone();
789 for i in flow_state.borrows.iter() {
790 let borrow = &borrow_set[i];
791 self.check_for_local_borrow(borrow, span);
796 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
797 // Returning from the function implicitly kills storage for all locals and statics.
798 // Often, the storage will already have been killed by an explicit
799 // StorageDead, but we don't always emit those (notably on unwind paths),
800 // so this "extra check" serves as a kind of backup.
801 let borrow_set = self.borrow_set.clone();
802 for i in flow_state.borrows.iter() {
803 let borrow = &borrow_set[i];
804 self.check_for_invalidation_at_exit(loc, borrow, span);
808 TerminatorKind::Abort
809 | TerminatorKind::Assert { .. }
810 | TerminatorKind::Call { .. }
811 | TerminatorKind::Drop { .. }
812 | TerminatorKind::DropAndReplace { .. }
813 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
814 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
815 | TerminatorKind::Goto { .. }
816 | TerminatorKind::SwitchInt { .. }
817 | TerminatorKind::Unreachable
818 | TerminatorKind::InlineAsm { .. } => {}
823 use self::AccessDepth::{Deep, Shallow};
824 use self::ReadOrWrite::{Activation, Read, Reservation, Write};
826 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
827 enum ArtificialField {
832 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
834 /// From the RFC: "A *shallow* access means that the immediate
835 /// fields reached at P are accessed, but references or pointers
836 /// found within are not dereferenced. Right now, the only access
837 /// that is shallow is an assignment like `x = ...;`, which would
838 /// be a *shallow write* of `x`."
839 Shallow(Option<ArtificialField>),
841 /// From the RFC: "A *deep* access means that all data reachable
842 /// through the given place may be invalidated or accesses by
846 /// Access is Deep only when there is a Drop implementation that
847 /// can reach the data behind the reference.
851 /// Kind of access to a value: read or write
852 /// (For informational purposes only)
853 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
855 /// From the RFC: "A *read* means that the existing data may be
856 /// read, but will not be changed."
859 /// From the RFC: "A *write* means that the data may be mutated to
860 /// new values or otherwise invalidated (for example, it could be
861 /// de-initialized, as in a move operation).
864 /// For two-phase borrows, we distinguish a reservation (which is treated
865 /// like a Read) from an activation (which is treated like a write), and
866 /// each of those is furthermore distinguished from Reads/Writes above.
867 Reservation(WriteKind),
868 Activation(WriteKind, BorrowIndex),
871 /// Kind of read access to a value
872 /// (For informational purposes only)
873 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
879 /// Kind of write access to a value
880 /// (For informational purposes only)
881 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
884 MutableBorrow(BorrowKind),
889 /// When checking permissions for a place access, this flag is used to indicate that an immutable
890 /// local place can be mutated.
892 // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
893 // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
894 // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
895 // `is_declared_mutable()`.
896 // - Take flow state into consideration in `is_assignable()` for local variables.
897 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
898 enum LocalMutationIsAllowed {
900 /// We want use of immutable upvars to cause a "write to immutable upvar"
901 /// error, not an "reassignment" error.
906 #[derive(Copy, Clone, Debug)]
907 enum InitializationRequiringAction {
915 struct RootPlace<'tcx> {
917 place_projection: &'tcx [PlaceElem<'tcx>],
918 is_local_mutation_allowed: LocalMutationIsAllowed,
921 impl InitializationRequiringAction {
922 fn as_noun(self) -> &'static str {
924 InitializationRequiringAction::Borrow => "borrow",
925 InitializationRequiringAction::MatchOn => "use", // no good noun
926 InitializationRequiringAction::Use => "use",
927 InitializationRequiringAction::Assignment => "assign",
928 InitializationRequiringAction::PartialAssignment => "assign to part",
932 fn as_verb_in_past_tense(self) -> &'static str {
934 InitializationRequiringAction::Borrow => "borrowed",
935 InitializationRequiringAction::MatchOn => "matched on",
936 InitializationRequiringAction::Use => "used",
937 InitializationRequiringAction::Assignment => "assigned",
938 InitializationRequiringAction::PartialAssignment => "partially assigned",
943 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
944 fn body(&self) -> &'cx Body<'tcx> {
948 /// Checks an access to the given place to see if it is allowed. Examines the set of borrows
949 /// that are in scope, as well as which paths have been initialized, to ensure that (a) the
950 /// place is initialized and (b) it is not borrowed in some way that would prevent this
953 /// Returns `true` if an error is reported.
957 place_span: (Place<'tcx>, Span),
958 kind: (AccessDepth, ReadOrWrite),
959 is_local_mutation_allowed: LocalMutationIsAllowed,
960 flow_state: &Flows<'cx, 'tcx>,
964 if let Activation(_, borrow_index) = rw {
965 if self.reservation_error_reported.contains(&place_span.0) {
967 "skipping access_place for activation of invalid reservation \
968 place: {:?} borrow_index: {:?}",
969 place_span.0, borrow_index
975 // Check is_empty() first because it's the common case, and doing that
976 // way we avoid the clone() call.
977 if !self.access_place_error_reported.is_empty()
978 && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
981 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
987 let mutability_error = self.check_access_permissions(
990 is_local_mutation_allowed,
995 self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
997 if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
998 // Suppress this warning when there's an error being emitted for the
999 // same borrow: fixing the error is likely to fix the warning.
1000 self.reservation_warnings.remove(&borrow_idx);
1003 if conflict_error || mutability_error {
1004 debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
1005 self.access_place_error_reported.insert((place_span.0, place_span.1));
1009 fn check_access_for_conflict(
1012 place_span: (Place<'tcx>, Span),
1015 flow_state: &Flows<'cx, 'tcx>,
1018 "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
1019 location, place_span, sd, rw,
1022 let mut error_reported = false;
1023 let tcx = self.infcx.tcx;
1024 let body = self.body;
1025 let borrow_set = self.borrow_set.clone();
1027 // Use polonius output if it has been enabled.
1028 let polonius_output = self.polonius_output.clone();
1029 let borrows_in_scope = if let Some(polonius) = &polonius_output {
1030 let location = self.location_table.start_index(location);
1031 Either::Left(polonius.errors_at(location).iter().copied())
1033 Either::Right(flow_state.borrows.iter())
1036 each_borrow_involving_path(
1044 |this, borrow_index, borrow| match (rw, borrow.kind) {
1045 // Obviously an activation is compatible with its own
1046 // reservation (or even prior activating uses of same
1047 // borrow); so don't check if they interfere.
1049 // NOTE: *reservations* do conflict with themselves;
1050 // thus aren't injecting unsoundenss w/ this check.)
1051 (Activation(_, activating), _) if activating == borrow_index => {
1053 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1054 skipping {:?} b/c activation of same borrow_index",
1058 (borrow_index, borrow),
1063 (Read(_), BorrowKind::Shared | BorrowKind::Shallow)
1065 Read(ReadKind::Borrow(BorrowKind::Shallow)),
1066 BorrowKind::Unique | BorrowKind::Mut { .. },
1067 ) => Control::Continue,
1069 (Write(WriteKind::Move), BorrowKind::Shallow) => {
1070 // Handled by initialization checks.
1074 (Read(kind), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
1075 // Reading from mere reservations of mutable-borrows is OK.
1076 if !is_active(&this.dominators, borrow, location) {
1077 assert!(allow_two_phase_borrow(borrow.kind));
1078 return Control::Continue;
1081 error_reported = true;
1085 .report_use_while_mutably_borrowed(location, place_span, borrow);
1086 this.buffer_error(err);
1088 ReadKind::Borrow(bk) => {
1090 this.report_conflicting_borrow(location, place_span, bk, borrow);
1091 this.buffer_error(err);
1098 Reservation(WriteKind::MutableBorrow(bk)),
1099 BorrowKind::Shallow | BorrowKind::Shared,
1100 ) if { tcx.migrate_borrowck() && this.borrow_set.contains(&location) } => {
1101 let bi = this.borrow_set.get_index_of(&location).unwrap();
1103 "recording invalid reservation of place: {:?} with \
1104 borrow index {:?} as warning",
1107 // rust-lang/rust#56254 - This was previously permitted on
1108 // the 2018 edition so we emit it as a warning. We buffer
1109 // these sepately so that we only emit a warning if borrow
1110 // checking was otherwise successful.
1111 this.reservation_warnings
1112 .insert(bi, (place_span.0, place_span.1, location, bk, borrow.clone()));
1114 // Don't suppress actual errors.
1118 (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1120 Reservation(..) => {
1122 "recording invalid reservation of \
1126 this.reservation_error_reported.insert(place_span.0);
1128 Activation(_, activating) => {
1130 "observing check_place for activation of \
1131 borrow_index: {:?}",
1135 Read(..) | Write(..) => {}
1138 error_reported = true;
1140 WriteKind::MutableBorrow(bk) => {
1142 this.report_conflicting_borrow(location, place_span, bk, borrow);
1143 this.buffer_error(err);
1145 WriteKind::StorageDeadOrDrop => this
1146 .report_borrowed_value_does_not_live_long_enough(
1152 WriteKind::Mutate => {
1153 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1155 WriteKind::Move => {
1156 this.report_move_out_while_borrowed(location, place_span, borrow)
1170 place_span: (Place<'tcx>, Span),
1172 flow_state: &Flows<'cx, 'tcx>,
1174 // Write of P[i] or *P requires P init'd.
1175 self.check_if_assigned_path_is_moved(location, place_span, flow_state);
1177 // Special case: you can assign an immutable local variable
1178 // (e.g., `x = ...`) so long as it has never been initialized
1179 // before (at this point in the flow).
1180 if let Some(local) = place_span.0.as_local() {
1181 if let Mutability::Not = self.body.local_decls[local].mutability {
1182 // check for reassignments to immutable local variables
1183 self.check_if_reassignment_to_immutable_state(
1184 location, local, place_span, flow_state,
1190 // Otherwise, use the normal access permission rules.
1194 (kind, Write(WriteKind::Mutate)),
1195 LocalMutationIsAllowed::No,
1203 (rvalue, span): (&'cx Rvalue<'tcx>, Span),
1204 flow_state: &Flows<'cx, 'tcx>,
1207 Rvalue::Ref(_ /*rgn*/, bk, place) => {
1208 let access_kind = match bk {
1209 BorrowKind::Shallow => {
1210 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
1212 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
1213 BorrowKind::Unique | BorrowKind::Mut { .. } => {
1214 let wk = WriteKind::MutableBorrow(bk);
1215 if allow_two_phase_borrow(bk) {
1216 (Deep, Reservation(wk))
1227 LocalMutationIsAllowed::No,
1231 let action = if bk == BorrowKind::Shallow {
1232 InitializationRequiringAction::MatchOn
1234 InitializationRequiringAction::Borrow
1237 self.check_if_path_or_subpath_is_moved(
1240 (place.as_ref(), span),
1245 Rvalue::AddressOf(mutability, place) => {
1246 let access_kind = match mutability {
1247 Mutability::Mut => (
1249 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1250 allow_two_phase_borrow: false,
1253 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1260 LocalMutationIsAllowed::No,
1264 self.check_if_path_or_subpath_is_moved(
1266 InitializationRequiringAction::Borrow,
1267 (place.as_ref(), span),
1272 Rvalue::ThreadLocalRef(_) => {}
1274 Rvalue::Use(ref operand)
1275 | Rvalue::Repeat(ref operand, _)
1276 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
1277 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/)
1278 | Rvalue::ShallowInitBox(ref operand, _ /*ty*/) => {
1279 self.consume_operand(location, (operand, span), flow_state)
1282 Rvalue::Len(place) | Rvalue::Discriminant(place) => {
1283 let af = match *rvalue {
1284 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
1285 Rvalue::Discriminant(..) => None,
1286 _ => unreachable!(),
1291 (Shallow(af), Read(ReadKind::Copy)),
1292 LocalMutationIsAllowed::No,
1295 self.check_if_path_or_subpath_is_moved(
1297 InitializationRequiringAction::Use,
1298 (place.as_ref(), span),
1303 Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2))
1304 | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => {
1305 self.consume_operand(location, (operand1, span), flow_state);
1306 self.consume_operand(location, (operand2, span), flow_state);
1309 Rvalue::NullaryOp(_op, _ty) => {
1310 // nullary ops take no dynamic input; no borrowck effect.
1313 Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
1314 // We need to report back the list of mutable upvars that were
1315 // moved into the closure and subsequently used by the closure,
1316 // in order to populate our used_mut set.
1317 match **aggregate_kind {
1318 AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
1319 let BorrowCheckResult { used_mut_upvars, .. } =
1320 self.infcx.tcx.mir_borrowck(def_id.expect_local());
1321 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1322 for field in used_mut_upvars {
1323 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1326 AggregateKind::Adt(..)
1327 | AggregateKind::Array(..)
1328 | AggregateKind::Tuple { .. } => (),
1331 for operand in operands {
1332 self.consume_operand(location, (operand, span), flow_state);
1338 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1339 let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1340 // We have three possibilities here:
1341 // a. We are modifying something through a mut-ref
1342 // b. We are modifying something that is local to our parent
1343 // c. Current body is a nested closure, and we are modifying path starting from
1344 // a Place captured by our parent closure.
1346 // Handle (c), the path being modified is exactly the path captured by our parent
1347 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1348 this.used_mut_upvars.push(field);
1352 for (place_ref, proj) in place.iter_projections().rev() {
1354 if proj == ProjectionElem::Deref {
1355 match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1356 // We aren't modifying a variable directly
1357 ty::Ref(_, _, hir::Mutability::Mut) => return,
1364 if let Some(field) = this.is_upvar_field_projection(place_ref) {
1365 this.used_mut_upvars.push(field);
1371 this.used_mut.insert(place.local);
1374 // This relies on the current way that by-value
1375 // captures of a closure are copied/moved directly
1376 // when generating MIR.
1378 Operand::Move(place) | Operand::Copy(place) => {
1379 match place.as_local() {
1380 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1381 if self.body.local_decls[local].ty.is_mutable_ptr() {
1382 // The variable will be marked as mutable by the borrow.
1385 // This is an edge case where we have a `move` closure
1386 // inside a non-move closure, and the inner closure
1387 // contains a mutation:
1390 // || { move || { i += 1; }; };
1392 // In this case our usual strategy of assuming that the
1393 // variable will be captured by mutable reference is
1394 // wrong, since `i` can be copied into the inner
1395 // closure from a shared reference.
1397 // As such we have to search for the local that this
1398 // capture comes from and mark it as being used as mut.
1400 let temp_mpi = self.move_data.rev_lookup.find_local(local);
1401 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1402 &self.move_data.inits[init_index]
1404 bug!("temporary should be initialized exactly once")
1407 let InitLocation::Statement(loc) = init.location else {
1408 bug!("temporary initialized in arguments")
1411 let body = self.body;
1412 let bbd = &body[loc.block];
1413 let stmt = &bbd.statements[loc.statement_index];
1414 debug!("temporary assigned in: stmt={:?}", stmt);
1416 if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, source))) = stmt.kind
1418 propagate_closure_used_mut_place(self, source);
1421 "closures should only capture user variables \
1422 or references to user variables"
1426 _ => propagate_closure_used_mut_place(self, place),
1429 Operand::Constant(..) => {}
1436 (operand, span): (&'cx Operand<'tcx>, Span),
1437 flow_state: &Flows<'cx, 'tcx>,
1440 Operand::Copy(place) => {
1441 // copy of place: check if this is "copy of frozen path"
1442 // (FIXME: see check_loans.rs)
1446 (Deep, Read(ReadKind::Copy)),
1447 LocalMutationIsAllowed::No,
1451 // Finally, check if path was already moved.
1452 self.check_if_path_or_subpath_is_moved(
1454 InitializationRequiringAction::Use,
1455 (place.as_ref(), span),
1459 Operand::Move(place) => {
1460 // move of place: check if this is move of already borrowed path
1464 (Deep, Write(WriteKind::Move)),
1465 LocalMutationIsAllowed::Yes,
1469 // Finally, check if path was already moved.
1470 self.check_if_path_or_subpath_is_moved(
1472 InitializationRequiringAction::Use,
1473 (place.as_ref(), span),
1477 Operand::Constant(_) => {}
1481 /// Checks whether a borrow of this place is invalidated when the function
1483 fn check_for_invalidation_at_exit(
1486 borrow: &BorrowData<'tcx>,
1489 debug!("check_for_invalidation_at_exit({:?})", borrow);
1490 let place = borrow.borrowed_place;
1491 let mut root_place = PlaceRef { local: place.local, projection: &[] };
1493 // FIXME(nll-rfc#40): do more precise destructor tracking here. For now
1494 // we just know that all locals are dropped at function exit (otherwise
1495 // we'll have a memory leak) and assume that all statics have a destructor.
1497 // FIXME: allow thread-locals to borrow other thread locals?
1499 let (might_be_alive, will_be_dropped) =
1500 if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1501 // Thread-locals might be dropped after the function exits
1502 // We have to dereference the outer reference because
1503 // borrows don't conflict behind shared references.
1504 root_place.projection = DEREF_PROJECTION;
1507 (false, self.locals_are_invalidated_at_exit)
1510 if !will_be_dropped {
1511 debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
1515 let sd = if might_be_alive { Deep } else { Shallow(None) };
1517 if places_conflict::borrow_conflicts_with_place(
1524 places_conflict::PlaceConflictBias::Overlap,
1526 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1527 // FIXME: should be talking about the region lifetime instead
1528 // of just a span here.
1529 let span = self.infcx.tcx.sess.source_map().end_point(span);
1530 self.report_borrowed_value_does_not_live_long_enough(
1539 /// Reports an error if this is a borrow of local data.
1540 /// This is called for all Yield expressions on movable generators
1541 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1542 debug!("check_for_local_borrow({:?})", borrow);
1544 if borrow_of_local_data(borrow.borrowed_place) {
1545 let err = self.cannot_borrow_across_generator_yield(
1546 self.retrieve_borrow_spans(borrow).var_or_use(),
1550 self.buffer_error(err);
1554 fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
1555 // Two-phase borrow support: For each activation that is newly
1556 // generated at this statement, check if it interferes with
1558 let borrow_set = self.borrow_set.clone();
1559 for &borrow_index in borrow_set.activations_at_location(location) {
1560 let borrow = &borrow_set[borrow_index];
1562 // only mutable borrows should be 2-phase
1563 assert!(match borrow.kind {
1564 BorrowKind::Shared | BorrowKind::Shallow => false,
1565 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
1570 (borrow.borrowed_place, span),
1571 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1572 LocalMutationIsAllowed::No,
1575 // We do not need to call `check_if_path_or_subpath_is_moved`
1576 // again, as we already called it when we made the
1577 // initial reservation.
1581 fn check_if_reassignment_to_immutable_state(
1585 place_span: (Place<'tcx>, Span),
1586 flow_state: &Flows<'cx, 'tcx>,
1588 debug!("check_if_reassignment_to_immutable_state({:?})", local);
1590 // Check if any of the initializiations of `local` have happened yet:
1591 if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
1592 // And, if so, report an error.
1593 let init = &self.move_data.inits[init_index];
1594 let span = init.span(&self.body);
1595 self.report_illegal_reassignment(location, place_span, span, place_span.0);
1599 fn check_if_full_path_is_moved(
1602 desired_action: InitializationRequiringAction,
1603 place_span: (PlaceRef<'tcx>, Span),
1604 flow_state: &Flows<'cx, 'tcx>,
1606 let maybe_uninits = &flow_state.uninits;
1610 // 1. Move of `a.b.c`, use of `a.b.c`
1611 // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
1612 // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
1613 // partial initialization support, one might have `a.x`
1614 // initialized but not `a.b`.
1618 // 4. Move of `a.b.c`, use of `a.b.d`
1619 // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1620 // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1621 // must have been initialized for the use to be sound.
1622 // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1624 // The dataflow tracks shallow prefixes distinctly (that is,
1625 // field-accesses on P distinctly from P itself), in order to
1626 // track substructure initialization separately from the whole
1629 // E.g., when looking at (*a.b.c).d, if the closest prefix for
1630 // which we have a MovePath is `a.b`, then that means that the
1631 // initialization state of `a.b` is all we need to inspect to
1632 // know if `a.b.c` is valid (and from that we infer that the
1633 // dereference and `.d` access is also valid, since we assume
1634 // `a.b.c` is assigned a reference to an initialized and
1635 // well-formed record structure.)
1637 // Therefore, if we seek out the *closest* prefix for which we
1638 // have a MovePath, that should capture the initialization
1639 // state for the place scenario.
1641 // This code covers scenarios 1, 2, and 3.
1643 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
1644 let (prefix, mpi) = self.move_path_closest_to(place_span.0);
1645 if maybe_uninits.contains(mpi) {
1646 self.report_use_of_moved_or_uninitialized(
1649 (prefix, place_span.0, place_span.1),
1652 } // Only query longest prefix with a MovePath, not further
1653 // ancestors; dataflow recurs on children when parents
1654 // move (to support partial (re)inits).
1656 // (I.e., querying parents breaks scenario 7; but may want
1657 // to do such a query based on partial-init feature-gate.)
1660 /// Subslices correspond to multiple move paths, so we iterate through the
1661 /// elements of the base array. For each element we check
1663 /// * Does this element overlap with our slice.
1664 /// * Is any part of it uninitialized.
1665 fn check_if_subslice_element_is_moved(
1668 desired_action: InitializationRequiringAction,
1669 place_span: (PlaceRef<'tcx>, Span),
1670 maybe_uninits: &ChunkedBitSet<MovePathIndex>,
1674 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1675 let move_paths = &self.move_data.move_paths;
1677 let root_path = &move_paths[mpi];
1678 for (child_mpi, child_move_path) in root_path.children(move_paths) {
1679 let last_proj = child_move_path.place.projection.last().unwrap();
1680 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
1681 debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
1683 if (from..to).contains(offset) {
1685 self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
1686 maybe_uninits.contains(mpi)
1689 if let Some(uninit_child) = uninit_child {
1690 self.report_use_of_moved_or_uninitialized(
1693 (place_span.0, place_span.0, place_span.1),
1696 return; // don't bother finding other problems.
1704 fn check_if_path_or_subpath_is_moved(
1707 desired_action: InitializationRequiringAction,
1708 place_span: (PlaceRef<'tcx>, Span),
1709 flow_state: &Flows<'cx, 'tcx>,
1711 let maybe_uninits = &flow_state.uninits;
1715 // 1. Move of `a.b.c`, use of `a` or `a.b`
1716 // partial initialization support, one might have `a.x`
1717 // initialized but not `a.b`.
1718 // 2. All bad scenarios from `check_if_full_path_is_moved`
1722 // 3. Move of `a.b.c`, use of `a.b.d`
1723 // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
1724 // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
1725 // must have been initialized for the use to be sound.
1726 // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
1728 self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
1730 if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
1731 place_span.0.last_projection()
1733 let place_ty = place_base.ty(self.body(), self.infcx.tcx);
1734 if let ty::Array(..) = place_ty.ty.kind() {
1735 self.check_if_subslice_element_is_moved(
1738 (place_base, place_span.1),
1747 // A move of any shallow suffix of `place` also interferes
1748 // with an attempt to use `place`. This is scenario 3 above.
1750 // (Distinct from handling of scenarios 1+2+4 above because
1751 // `place` does not interfere with suffixes of its prefixes,
1752 // e.g., `a.b.c` does not interfere with `a.b.d`)
1754 // This code covers scenario 1.
1756 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
1757 if let Some(mpi) = self.move_path_for_place(place_span.0) {
1758 let uninit_mpi = self
1760 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
1762 if let Some(uninit_mpi) = uninit_mpi {
1763 self.report_use_of_moved_or_uninitialized(
1766 (place_span.0, place_span.0, place_span.1),
1769 return; // don't bother finding other problems.
1774 /// Currently MoveData does not store entries for all places in
1775 /// the input MIR. For example it will currently filter out
1776 /// places that are Copy; thus we do not track places of shared
1777 /// reference type. This routine will walk up a place along its
1778 /// prefixes, searching for a foundational place that *is*
1779 /// tracked in the MoveData.
1781 /// An Err result includes a tag indicated why the search failed.
1782 /// Currently this can only occur if the place is built off of a
1783 /// static variable, as we do not track those in the MoveData.
1784 fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
1785 match self.move_data.rev_lookup.find(place) {
1786 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
1787 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
1789 LookupResult::Parent(None) => panic!("should have move path for every Local"),
1793 fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
1794 // If returns None, then there is no move path corresponding
1795 // to a direct owner of `place` (which means there is nothing
1796 // that borrowck tracks for its analysis).
1798 match self.move_data.rev_lookup.find(place) {
1799 LookupResult::Parent(_) => None,
1800 LookupResult::Exact(mpi) => Some(mpi),
1804 fn check_if_assigned_path_is_moved(
1807 (place, span): (Place<'tcx>, Span),
1808 flow_state: &Flows<'cx, 'tcx>,
1810 debug!("check_if_assigned_path_is_moved place: {:?}", place);
1812 // None case => assigning to `x` does not require `x` be initialized.
1813 for (place_base, elem) in place.iter_projections().rev() {
1815 ProjectionElem::Index(_/*operand*/) |
1816 ProjectionElem::ConstantIndex { .. } |
1817 // assigning to P[i] requires P to be valid.
1818 ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
1819 // assigning to (P->variant) is okay if assigning to `P` is okay
1821 // FIXME: is this true even if P is an adt with a dtor?
1824 // assigning to (*P) requires P to be initialized
1825 ProjectionElem::Deref => {
1826 self.check_if_full_path_is_moved(
1827 location, InitializationRequiringAction::Use,
1828 (place_base, span), flow_state);
1829 // (base initialized; no need to
1834 ProjectionElem::Subslice { .. } => {
1835 panic!("we don't allow assignments to subslices, location: {:?}",
1839 ProjectionElem::Field(..) => {
1840 // if type of `P` has a dtor, then
1841 // assigning to `P.f` requires `P` itself
1842 // be already initialized
1843 let tcx = self.infcx.tcx;
1844 let base_ty = place_base.ty(self.body(), tcx).ty;
1845 match base_ty.kind() {
1846 ty::Adt(def, _) if def.has_dtor(tcx) => {
1847 self.check_if_path_or_subpath_is_moved(
1848 location, InitializationRequiringAction::Assignment,
1849 (place_base, span), flow_state);
1851 // (base initialized; no need to
1856 // Once `let s; s.x = V; read(s.x);`,
1857 // is allowed, remove this match arm.
1858 ty::Adt(..) | ty::Tuple(..) => {
1859 check_parent_of_field(self, location, place_base, span, flow_state);
1861 // rust-lang/rust#21232, #54499, #54986: during period where we reject
1862 // partial initialization, do not complain about unnecessary `mut` on
1863 // an attempt to do a partial initialization.
1864 self.used_mut.insert(place.local);
1873 fn check_parent_of_field<'cx, 'tcx>(
1874 this: &mut MirBorrowckCtxt<'cx, 'tcx>,
1876 base: PlaceRef<'tcx>,
1878 flow_state: &Flows<'cx, 'tcx>,
1880 // rust-lang/rust#21232: Until Rust allows reads from the
1881 // initialized parts of partially initialized structs, we
1882 // will, starting with the 2018 edition, reject attempts
1883 // to write to structs that are not fully initialized.
1885 // In other words, *until* we allow this:
1887 // 1. `let mut s; s.x = Val; read(s.x);`
1889 // we will for now disallow this:
1891 // 2. `let mut s; s.x = Val;`
1895 // 3. `let mut s = ...; drop(s); s.x=Val;`
1897 // This does not use check_if_path_or_subpath_is_moved,
1898 // because we want to *allow* reinitializations of fields:
1899 // e.g., want to allow
1901 // `let mut s = ...; drop(s.x); s.x=Val;`
1903 // This does not use check_if_full_path_is_moved on
1904 // `base`, because that would report an error about the
1905 // `base` as a whole, but in this scenario we *really*
1906 // want to report an error about the actual thing that was
1907 // moved, which may be some prefix of `base`.
1909 // Shallow so that we'll stop at any dereference; we'll
1910 // report errors about issues with such bases elsewhere.
1911 let maybe_uninits = &flow_state.uninits;
1913 // Find the shortest uninitialized prefix you can reach
1914 // without going over a Deref.
1915 let mut shortest_uninit_seen = None;
1916 for prefix in this.prefixes(base, PrefixSet::Shallow) {
1917 let Some(mpi) = this.move_path_for_place(prefix) else { continue };
1919 if maybe_uninits.contains(mpi) {
1921 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
1922 shortest_uninit_seen,
1925 shortest_uninit_seen = Some((prefix, mpi));
1927 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
1931 if let Some((prefix, mpi)) = shortest_uninit_seen {
1932 // Check for a reassignment into an uninitialized field of a union (for example,
1933 // after a move out). In this case, do not report an error here. There is an
1934 // exception, if this is the first assignment into the union (that is, there is
1935 // no move out from an earlier location) then this is an attempt at initialization
1936 // of the union - we should error in that case.
1937 let tcx = this.infcx.tcx;
1938 if base.ty(this.body(), tcx).ty.is_union() {
1939 if this.move_data.path_map[mpi].iter().any(|moi| {
1940 this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
1946 this.report_use_of_moved_or_uninitialized(
1948 InitializationRequiringAction::PartialAssignment,
1949 (prefix, base, span),
1956 /// Checks the permissions for the given place and read or write kind
1958 /// Returns `true` if an error is reported.
1959 fn check_access_permissions(
1961 (place, span): (Place<'tcx>, Span),
1963 is_local_mutation_allowed: LocalMutationIsAllowed,
1964 flow_state: &Flows<'cx, 'tcx>,
1968 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
1969 place, kind, is_local_mutation_allowed
1976 Reservation(WriteKind::MutableBorrow(
1977 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
1979 | Write(WriteKind::MutableBorrow(
1980 borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
1982 let is_local_mutation_allowed = match borrow_kind {
1983 BorrowKind::Unique => LocalMutationIsAllowed::Yes,
1984 BorrowKind::Mut { .. } => is_local_mutation_allowed,
1985 BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
1987 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
1989 self.add_used_mut(root_place, flow_state);
1993 error_access = AccessKind::MutableBorrow;
1994 the_place_err = place_err;
1998 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
1999 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2001 self.add_used_mut(root_place, flow_state);
2005 error_access = AccessKind::Mutate;
2006 the_place_err = place_err;
2013 | WriteKind::StorageDeadOrDrop
2014 | WriteKind::MutableBorrow(BorrowKind::Shared)
2015 | WriteKind::MutableBorrow(BorrowKind::Shallow),
2019 | WriteKind::StorageDeadOrDrop
2020 | WriteKind::MutableBorrow(BorrowKind::Shared)
2021 | WriteKind::MutableBorrow(BorrowKind::Shallow),
2023 if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err()
2024 && !self.has_buffered_errors()
2026 // rust-lang/rust#46908: In pure NLL mode this code path should be
2027 // unreachable, but we use `delay_span_bug` because we can hit this when
2028 // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
2029 // enabled. We don't want to ICE for that case, as other errors will have
2030 // been emitted (#52262).
2031 self.infcx.tcx.sess.delay_span_bug(
2034 "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
2042 // permission checks are done at Reservation point.
2048 | BorrowKind::Mut { .. }
2049 | BorrowKind::Shared
2050 | BorrowKind::Shallow,
2054 // Access authorized
2059 // rust-lang/rust#21232, #54986: during period where we reject
2060 // partial initialization, do not complain about mutability
2061 // errors except for actual mutation (as opposed to an attempt
2062 // to do a partial initialization).
2063 let previously_initialized =
2064 self.is_local_ever_initialized(place.local, flow_state).is_some();
2066 // at this point, we have set up the error reporting state.
2067 if previously_initialized {
2068 self.report_mutability_error(place, span, the_place_err, error_access, location);
2075 fn is_local_ever_initialized(
2078 flow_state: &Flows<'cx, 'tcx>,
2079 ) -> Option<InitIndex> {
2080 let mpi = self.move_data.rev_lookup.find_local(local);
2081 let ii = &self.move_data.init_path_map[mpi];
2083 if flow_state.ever_inits.contains(index) {
2090 /// Adds the place into the used mutable variables set
2091 fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) {
2093 RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2094 // If the local may have been initialized, and it is now currently being
2095 // mutated, then it is justified to be annotated with the `mut`
2096 // keyword, since the mutation may be a possible reassignment.
2097 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2098 && self.is_local_ever_initialized(local, flow_state).is_some()
2100 self.used_mut.insert(local);
2105 place_projection: _,
2106 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2110 place_projection: place_projection @ [.., _],
2111 is_local_mutation_allowed: _,
2113 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2115 projection: place_projection,
2117 self.used_mut_upvars.push(field);
2123 /// Whether this value can be written or borrowed mutably.
2124 /// Returns the root place if the place passed in is a projection.
2127 place: PlaceRef<'tcx>,
2128 is_local_mutation_allowed: LocalMutationIsAllowed,
2129 ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2130 debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2131 match place.last_projection() {
2133 let local = &self.body.local_decls[place.local];
2134 match local.mutability {
2135 Mutability::Not => match is_local_mutation_allowed {
2136 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2137 place_local: place.local,
2138 place_projection: place.projection,
2139 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2141 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2142 place_local: place.local,
2143 place_projection: place.projection,
2144 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2146 LocalMutationIsAllowed::No => Err(place),
2148 Mutability::Mut => Ok(RootPlace {
2149 place_local: place.local,
2150 place_projection: place.projection,
2151 is_local_mutation_allowed,
2155 Some((place_base, elem)) => {
2157 ProjectionElem::Deref => {
2158 let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2160 // Check the kind of deref to decide
2161 match base_ty.kind() {
2162 ty::Ref(_, _, mutbl) => {
2164 // Shared borrowed data is never mutable
2165 hir::Mutability::Not => Err(place),
2166 // Mutably borrowed data is mutable, but only if we have a
2167 // unique path to the `&mut`
2168 hir::Mutability::Mut => {
2169 let mode = match self.is_upvar_field_projection(place) {
2170 Some(field) if self.upvars[field.index()].by_ref => {
2171 is_local_mutation_allowed
2173 _ => LocalMutationIsAllowed::Yes,
2176 self.is_mutable(place_base, mode)
2180 ty::RawPtr(tnm) => {
2182 // `*const` raw pointers are not mutable
2183 hir::Mutability::Not => Err(place),
2184 // `*mut` raw pointers are always mutable, regardless of
2185 // context. The users have to check by themselves.
2186 hir::Mutability::Mut => Ok(RootPlace {
2187 place_local: place.local,
2188 place_projection: place.projection,
2189 is_local_mutation_allowed,
2193 // `Box<T>` owns its content, so mutable if its location is mutable
2194 _ if base_ty.is_box() => {
2195 self.is_mutable(place_base, is_local_mutation_allowed)
2197 // Deref should only be for reference, pointers or boxes
2198 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2201 // All other projections are owned by their base path, so mutable if
2202 // base path is mutable
2203 ProjectionElem::Field(..)
2204 | ProjectionElem::Index(..)
2205 | ProjectionElem::ConstantIndex { .. }
2206 | ProjectionElem::Subslice { .. }
2207 | ProjectionElem::Downcast(..) => {
2208 let upvar_field_projection = self.is_upvar_field_projection(place);
2209 if let Some(field) = upvar_field_projection {
2210 let upvar = &self.upvars[field.index()];
2212 "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2213 place={:?}, place_base={:?}",
2214 upvar, is_local_mutation_allowed, place, place_base
2216 match (upvar.place.mutability, is_local_mutation_allowed) {
2219 LocalMutationIsAllowed::No
2220 | LocalMutationIsAllowed::ExceptUpvars,
2222 (Mutability::Not, LocalMutationIsAllowed::Yes)
2223 | (Mutability::Mut, _) => {
2224 // Subtle: this is an upvar
2225 // reference, so it looks like
2226 // `self.foo` -- we want to double
2227 // check that the location `*self`
2228 // is mutable (i.e., this is not a
2229 // `Fn` closure). But if that
2230 // check succeeds, we want to
2231 // *blame* the mutability on
2232 // `place` (that is,
2233 // `self.foo`). This is used to
2234 // propagate the info about
2235 // whether mutability declarations
2236 // are used outwards, so that we register
2237 // the outer variable as mutable. Otherwise a
2238 // test like this fails to record the `mut`
2242 // fn foo<F: FnOnce()>(_f: F) { }
2244 // let var = Vec::new();
2251 self.is_mutable(place_base, is_local_mutation_allowed)?;
2253 place_local: place.local,
2254 place_projection: place.projection,
2255 is_local_mutation_allowed,
2260 self.is_mutable(place_base, is_local_mutation_allowed)
2268 /// If `place` is a field projection, and the field is being projected from a closure type,
2269 /// then returns the index of the field being projected. Note that this closure will always
2270 /// be `self` in the current MIR, because that is the only time we directly access the fields
2271 /// of a closure type.
2272 fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> {
2273 path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2280 pub struct BorrowckErrors<'tcx> {
2281 /// This field keeps track of move errors that are to be reported for given move indices.
2283 /// There are situations where many errors can be reported for a single move out (see #53807)
2284 /// and we want only the best of those errors.
2286 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
2287 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
2288 /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
2289 /// all move errors have been reported, any diagnostics in this map are added to the buffer
2292 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
2293 /// when errors in the map are being re-added to the error buffer so that errors with the
2294 /// same primary span come out in a consistent order.
2295 buffered_move_errors:
2296 BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorReported>)>,
2297 /// Diagnostics to be reported buffer.
2298 buffered: Vec<Diagnostic>,
2299 /// Set to Some if we emit an error during borrowck
2300 tainted_by_errors: Option<ErrorReported>,
2303 impl BorrowckErrors<'_> {
2304 pub fn new() -> Self {
2306 buffered_move_errors: BTreeMap::new(),
2307 buffered: Default::default(),
2308 tainted_by_errors: None,
2312 // FIXME(eddyb) this is a suboptimal API because `tainted_by_errors` is
2313 // set before any emission actually happens (weakening the guarantee).
2314 pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorReported>) {
2315 self.tainted_by_errors = Some(ErrorReported {});
2316 t.buffer(&mut self.buffered);
2319 pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) {
2320 t.buffer(&mut self.buffered);
2323 pub fn set_tainted_by_errors(&mut self) {
2324 self.tainted_by_errors = Some(ErrorReported {});
2328 impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
2329 pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorReported>) {
2330 self.errors.buffer_error(t);
2333 pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) {
2334 self.errors.buffer_non_error_diag(t);
2337 pub fn buffer_move_error(
2339 move_out_indices: Vec<MoveOutIndex>,
2340 place_and_err: (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorReported>),
2342 if let Some((_, diag)) =
2343 self.errors.buffered_move_errors.insert(move_out_indices, place_and_err)
2345 // Cancel the old diagnostic so we don't ICE
2353 pub fn emit_errors(&mut self) -> Option<ErrorReported> {
2354 // Buffer any move errors that we collected and de-duplicated.
2355 for (_, (_, diag)) in std::mem::take(&mut self.errors.buffered_move_errors) {
2356 // We have already set tainted for this error, so just buffer it.
2357 diag.buffer(&mut self.errors.buffered);
2360 if !self.errors.buffered.is_empty() {
2361 self.errors.buffered.sort_by_key(|diag| diag.sort_span);
2363 for diag in self.errors.buffered.drain(..) {
2364 self.infcx.tcx.sess.diagnostic().emit_diagnostic(&diag);
2368 self.errors.tainted_by_errors
2371 pub fn has_buffered_errors(&self) -> bool {
2372 self.errors.buffered.is_empty()
2375 pub fn has_move_error(
2377 move_out_indices: &[MoveOutIndex],
2378 ) -> Option<&(PlaceRef<'tcx>, DiagnosticBuilder<'cx, ErrorReported>)> {
2379 self.errors.buffered_move_errors.get(move_out_indices)
2384 /// The degree of overlap between 2 places for borrow-checking.
2386 /// The places might partially overlap - in this case, we give
2387 /// up and say that they might conflict. This occurs when
2388 /// different fields of a union are borrowed. For example,
2389 /// if `u` is a union, we have no way of telling how disjoint
2390 /// `u.a.x` and `a.b.y` are.
2392 /// The places have the same type, and are either completely disjoint
2393 /// or equal - i.e., they can't "partially" overlap as can occur with
2394 /// unions. This is the "base case" on which we recur for extensions
2397 /// The places are disjoint, so we know all extensions of them
2398 /// will also be disjoint.