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