rustc_borrowck/
lib.rs

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