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