1#![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)]
16use 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
100pub mod consumers;
102
103rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
104
105struct 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
116fn mir_borrowck(
120 tcx: TyCtxt<'_>,
121 def: LocalDefId,
122) -> Result<&DefinitionSiteHiddenTypes<'_>, 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 = DefinitionSiteHiddenTypes(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#[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#[derive(Clone, Debug)]
195pub struct ClosureRegionRequirements<'tcx> {
196 pub num_external_vids: usize,
202
203 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
206}
207
208#[derive(Copy, Clone, Debug)]
211pub struct ClosureOutlivesRequirement<'tcx> {
212 pub subject: ClosureOutlivesSubject<'tcx>,
214
215 pub outlived_free_region: ty::RegionVid,
217
218 pub blame_span: Span,
220
221 pub category: ConstraintCategory<'tcx>,
223}
224
225#[cfg(target_pointer_width = "64")]
227rustc_data_structures::static_assert_size!(ConstraintCategory<'_>, 16);
228
229#[derive(Copy, Clone, Debug)]
232pub enum ClosureOutlivesSubject<'tcx> {
233 Ty(ClosureOutlivesSubjectTy<'tcx>),
237
238 Region(ty::RegionVid),
241}
242
243#[derive(Copy, Clone, Debug)]
249pub struct ClosureOutlivesSubjectTy<'tcx> {
250 inner: Ty<'tcx>,
251}
252impl<'tcx, I> !TypeVisitable<I> for ClosureOutlivesSubjectTy<'tcx> {}
255impl<'tcx, I> !TypeFoldable<I> for ClosureOutlivesSubjectTy<'tcx> {}
256
257impl<'tcx> ClosureOutlivesSubjectTy<'tcx> {
258 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(ty::BoundVarIndexKind::Bound(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
308fn 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 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; 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 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
388fn 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 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 nll::dump_nll_mir(&infcx, body, ®ioncx, &opt_closure_req, &borrow_set);
443 polonius::dump_polonius_mir(
444 &infcx,
445 body,
446 ®ioncx,
447 &opt_closure_req,
448 &borrow_set,
449 polonius_diagnostics.as_ref(),
450 );
451
452 nll::dump_annotation(&infcx, body, ®ioncx, &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 for promoted_body in &promoted {
463 use rustc_middle::mir::visit::Visitor;
464 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 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: ®ioncx,
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: ®ioncx,
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 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, ®ioncx);
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 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 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 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 location_table: &'a PoloniusLocationTable,
727
728 movable_coroutine: bool,
729 access_place_error_reported: FxIndexSet<(Place<'tcx>, Span)>,
735 reservation_error_reported: FxIndexSet<Place<'tcx>>,
743 fn_self_span_reported: FxIndexSet<Span>,
747 uninitialized_error_reported: FxIndexSet<Local>,
750 used_mut: FxIndexSet<Local>,
753 used_mut_upvars: SmallVec<[FieldIdx; 8]>,
756 regioncx: &'a RegionInferenceContext<'tcx>,
759
760 borrow_set: &'a BorrowSet<'tcx>,
762
763 upvars: &'tcx [&'tcx ty::CapturedPlace<'tcx>],
765
766 local_names: OnceCell<IndexVec<Local, Option<Symbol>>>,
768
769 region_names: RefCell<FxIndexMap<RegionVid, RegionName>>,
772
773 next_region_name: RefCell<usize>,
775
776 diags_buffer: &'a mut BorrowckDiagnosticsBuffer<'infcx, 'tcx>,
777 move_errors: Vec<MoveError<'tcx>>,
778
779 polonius_output: Option<&'a PoloniusOutput>,
781 polonius_diagnostics: Option<&'a PoloniusDiagnosticsContext>,
783}
784
785impl<'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 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 StatementKind::AscribeUserType(..)
838 | StatementKind::PlaceMention(..)
840 | StatementKind::Coverage(..)
842 | StatementKind::ConstEvalCounter
844 | StatementKind::StorageLive(..) => {}
845 StatementKind::BackwardIncompatibleDropHint { place, reason: BackwardIncompatibleDropReason::Edition2024 } => {
847 self.check_backward_incompatible_drop(location, **place, state);
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::SetDiscriminant { .. } => {
861 bug!("Statement not allowed in this MIR phase")
862 }
863 }
864 }
865
866 fn visit_after_early_terminator_effect(
867 &mut self,
868 _analysis: &mut Borrowck<'a, 'tcx>,
869 state: &BorrowckDomain,
870 term: &Terminator<'tcx>,
871 loc: Location,
872 ) {
873 debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, state);
874 let span = term.source_info.span;
875
876 self.check_activations(loc, span, state);
877
878 match &term.kind {
879 TerminatorKind::SwitchInt { discr, targets: _ } => {
880 self.consume_operand(loc, (discr, span), state);
881 }
882 TerminatorKind::Drop {
883 place,
884 target: _,
885 unwind: _,
886 replace,
887 drop: _,
888 async_fut: _,
889 } => {
890 debug!(
891 "visit_terminator_drop \
892 loc: {:?} term: {:?} place: {:?} span: {:?}",
893 loc, term, place, span
894 );
895
896 let write_kind =
897 if *replace { WriteKind::Replace } else { WriteKind::StorageDeadOrDrop };
898 self.access_place(
899 loc,
900 (*place, span),
901 (AccessDepth::Drop, Write(write_kind)),
902 LocalMutationIsAllowed::Yes,
903 state,
904 );
905 }
906 TerminatorKind::Call {
907 func,
908 args,
909 destination,
910 target: _,
911 unwind: _,
912 call_source: _,
913 fn_span: _,
914 } => {
915 self.consume_operand(loc, (func, span), state);
916 for arg in args {
917 self.consume_operand(loc, (&arg.node, arg.span), state);
918 }
919 self.mutate_place(loc, (*destination, span), Deep, state);
920 }
921 TerminatorKind::TailCall { func, args, fn_span: _ } => {
922 self.consume_operand(loc, (func, span), state);
923 for arg in args {
924 self.consume_operand(loc, (&arg.node, arg.span), state);
925 }
926 }
927 TerminatorKind::Assert { cond, expected: _, msg, target: _, unwind: _ } => {
928 self.consume_operand(loc, (cond, span), state);
929 if let AssertKind::BoundsCheck { len, index } = &**msg {
930 self.consume_operand(loc, (len, span), state);
931 self.consume_operand(loc, (index, span), state);
932 }
933 }
934
935 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
936 self.consume_operand(loc, (value, span), state);
937 self.mutate_place(loc, (*resume_arg, span), Deep, state);
938 }
939
940 TerminatorKind::InlineAsm {
941 asm_macro: _,
942 template: _,
943 operands,
944 options: _,
945 line_spans: _,
946 targets: _,
947 unwind: _,
948 } => {
949 for op in operands {
950 match op {
951 InlineAsmOperand::In { reg: _, value } => {
952 self.consume_operand(loc, (value, span), state);
953 }
954 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
955 if let Some(place) = place {
956 self.mutate_place(loc, (*place, span), Shallow(None), state);
957 }
958 }
959 InlineAsmOperand::InOut { reg: _, late: _, in_value, out_place } => {
960 self.consume_operand(loc, (in_value, span), state);
961 if let &Some(out_place) = out_place {
962 self.mutate_place(loc, (out_place, span), Shallow(None), state);
963 }
964 }
965 InlineAsmOperand::Const { value: _ }
966 | InlineAsmOperand::SymFn { value: _ }
967 | InlineAsmOperand::SymStatic { def_id: _ }
968 | InlineAsmOperand::Label { target_index: _ } => {}
969 }
970 }
971 }
972
973 TerminatorKind::Goto { target: _ }
974 | TerminatorKind::UnwindTerminate(_)
975 | TerminatorKind::Unreachable
976 | TerminatorKind::UnwindResume
977 | TerminatorKind::Return
978 | TerminatorKind::CoroutineDrop
979 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
980 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
981 }
983 }
984 }
985
986 fn visit_after_primary_terminator_effect(
987 &mut self,
988 _analysis: &mut Borrowck<'a, 'tcx>,
989 state: &BorrowckDomain,
990 term: &Terminator<'tcx>,
991 loc: Location,
992 ) {
993 let span = term.source_info.span;
994
995 match term.kind {
996 TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
997 if self.movable_coroutine {
998 for i in state.borrows.iter() {
1000 let borrow = &self.borrow_set[i];
1001 self.check_for_local_borrow(borrow, span);
1002 }
1003 }
1004 }
1005
1006 TerminatorKind::UnwindResume
1007 | TerminatorKind::Return
1008 | TerminatorKind::TailCall { .. }
1009 | TerminatorKind::CoroutineDrop => {
1010 match self.borrow_set.locals_state_at_exit() {
1011 LocalsStateAtExit::AllAreInvalidated => {
1012 for i in state.borrows.iter() {
1017 let borrow = &self.borrow_set[i];
1018 self.check_for_invalidation_at_exit(loc, borrow, span);
1019 }
1020 }
1021 LocalsStateAtExit::SomeAreInvalidated { has_storage_dead_or_moved: _ } => {}
1024 }
1025 }
1026
1027 TerminatorKind::UnwindTerminate(_)
1028 | TerminatorKind::Assert { .. }
1029 | TerminatorKind::Call { .. }
1030 | TerminatorKind::Drop { .. }
1031 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
1032 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
1033 | TerminatorKind::Goto { .. }
1034 | TerminatorKind::SwitchInt { .. }
1035 | TerminatorKind::Unreachable
1036 | TerminatorKind::InlineAsm { .. } => {}
1037 }
1038 }
1039}
1040
1041use self::AccessDepth::{Deep, Shallow};
1042use self::ReadOrWrite::{Activation, Read, Reservation, Write};
1043
1044#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1045enum ArtificialField {
1046 ArrayLength,
1047 FakeBorrow,
1048}
1049
1050#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1051enum AccessDepth {
1052 Shallow(Option<ArtificialField>),
1058
1059 Deep,
1063
1064 Drop,
1067}
1068
1069#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1072enum ReadOrWrite {
1073 Read(ReadKind),
1076
1077 Write(WriteKind),
1081
1082 Reservation(WriteKind),
1086 Activation(WriteKind, BorrowIndex),
1087}
1088
1089#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1092enum ReadKind {
1093 Borrow(BorrowKind),
1094 Copy,
1095}
1096
1097#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1100enum WriteKind {
1101 StorageDeadOrDrop,
1102 Replace,
1103 MutableBorrow(BorrowKind),
1104 Mutate,
1105 Move,
1106}
1107
1108#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1116enum LocalMutationIsAllowed {
1117 Yes,
1118 ExceptUpvars,
1121 No,
1122}
1123
1124#[derive(Copy, Clone, Debug)]
1125enum InitializationRequiringAction {
1126 Borrow,
1127 MatchOn,
1128 Use,
1129 Assignment,
1130 PartialAssignment,
1131}
1132
1133#[derive(Debug)]
1134struct RootPlace<'tcx> {
1135 place_local: Local,
1136 place_projection: &'tcx [PlaceElem<'tcx>],
1137 is_local_mutation_allowed: LocalMutationIsAllowed,
1138}
1139
1140impl InitializationRequiringAction {
1141 fn as_noun(self) -> &'static str {
1142 match self {
1143 InitializationRequiringAction::Borrow => "borrow",
1144 InitializationRequiringAction::MatchOn => "use", InitializationRequiringAction::Use => "use",
1146 InitializationRequiringAction::Assignment => "assign",
1147 InitializationRequiringAction::PartialAssignment => "assign to part",
1148 }
1149 }
1150
1151 fn as_verb_in_past_tense(self) -> &'static str {
1152 match self {
1153 InitializationRequiringAction::Borrow => "borrowed",
1154 InitializationRequiringAction::MatchOn => "matched on",
1155 InitializationRequiringAction::Use => "used",
1156 InitializationRequiringAction::Assignment => "assigned",
1157 InitializationRequiringAction::PartialAssignment => "partially assigned",
1158 }
1159 }
1160
1161 fn as_general_verb_in_past_tense(self) -> &'static str {
1162 match self {
1163 InitializationRequiringAction::Borrow
1164 | InitializationRequiringAction::MatchOn
1165 | InitializationRequiringAction::Use => "used",
1166 InitializationRequiringAction::Assignment => "assigned",
1167 InitializationRequiringAction::PartialAssignment => "partially assigned",
1168 }
1169 }
1170}
1171
1172impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
1173 fn body(&self) -> &'a Body<'tcx> {
1174 self.body
1175 }
1176
1177 fn access_place(
1184 &mut self,
1185 location: Location,
1186 place_span: (Place<'tcx>, Span),
1187 kind: (AccessDepth, ReadOrWrite),
1188 is_local_mutation_allowed: LocalMutationIsAllowed,
1189 state: &BorrowckDomain,
1190 ) {
1191 let (sd, rw) = kind;
1192
1193 if let Activation(_, borrow_index) = rw {
1194 if self.reservation_error_reported.contains(&place_span.0) {
1195 debug!(
1196 "skipping access_place for activation of invalid reservation \
1197 place: {:?} borrow_index: {:?}",
1198 place_span.0, borrow_index
1199 );
1200 return;
1201 }
1202 }
1203
1204 if !self.access_place_error_reported.is_empty()
1207 && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
1208 {
1209 debug!(
1210 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
1211 place_span, kind
1212 );
1213 return;
1214 }
1215
1216 let mutability_error = self.check_access_permissions(
1217 place_span,
1218 rw,
1219 is_local_mutation_allowed,
1220 state,
1221 location,
1222 );
1223 let conflict_error = self.check_access_for_conflict(location, place_span, sd, rw, state);
1224
1225 if conflict_error || mutability_error {
1226 debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
1227 self.access_place_error_reported.insert((place_span.0, place_span.1));
1228 }
1229 }
1230
1231 fn borrows_in_scope<'s>(
1232 &self,
1233 location: Location,
1234 state: &'s BorrowckDomain,
1235 ) -> Cow<'s, MixedBitSet<BorrowIndex>> {
1236 if let Some(polonius) = &self.polonius_output {
1237 let location = self.location_table.start_index(location);
1239 let mut polonius_output = MixedBitSet::new_empty(self.borrow_set.len());
1240 for &idx in polonius.errors_at(location) {
1241 polonius_output.insert(idx);
1242 }
1243 Cow::Owned(polonius_output)
1244 } else {
1245 Cow::Borrowed(&state.borrows)
1246 }
1247 }
1248
1249 #[instrument(level = "debug", skip(self, state))]
1250 fn check_access_for_conflict(
1251 &mut self,
1252 location: Location,
1253 place_span: (Place<'tcx>, Span),
1254 sd: AccessDepth,
1255 rw: ReadOrWrite,
1256 state: &BorrowckDomain,
1257 ) -> bool {
1258 let mut error_reported = false;
1259
1260 let borrows_in_scope = self.borrows_in_scope(location, state);
1261
1262 each_borrow_involving_path(
1263 self,
1264 self.infcx.tcx,
1265 self.body,
1266 (sd, place_span.0),
1267 self.borrow_set,
1268 |borrow_index| borrows_in_scope.contains(borrow_index),
1269 |this, borrow_index, borrow| match (rw, borrow.kind) {
1270 (Activation(_, activating), _) if activating == borrow_index => {
1277 debug!(
1278 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1279 skipping {:?} b/c activation of same borrow_index",
1280 place_span,
1281 sd,
1282 rw,
1283 (borrow_index, borrow),
1284 );
1285 ControlFlow::Continue(())
1286 }
1287
1288 (Read(_), BorrowKind::Shared | BorrowKind::Fake(_))
1289 | (
1290 Read(ReadKind::Borrow(BorrowKind::Fake(FakeBorrowKind::Shallow))),
1291 BorrowKind::Mut { .. },
1292 ) => ControlFlow::Continue(()),
1293
1294 (Reservation(_), BorrowKind::Fake(_) | BorrowKind::Shared) => {
1295 ControlFlow::Continue(())
1298 }
1299
1300 (Write(WriteKind::Move), BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
1301 ControlFlow::Continue(())
1303 }
1304
1305 (Read(kind), BorrowKind::Mut { .. }) => {
1306 if !is_active(this.dominators(), borrow, location) {
1308 assert!(borrow.kind.allows_two_phase_borrow());
1309 return ControlFlow::Continue(());
1310 }
1311
1312 error_reported = true;
1313 match kind {
1314 ReadKind::Copy => {
1315 let err = this
1316 .report_use_while_mutably_borrowed(location, place_span, borrow);
1317 this.buffer_error(err);
1318 }
1319 ReadKind::Borrow(bk) => {
1320 let err =
1321 this.report_conflicting_borrow(location, place_span, bk, borrow);
1322 this.buffer_error(err);
1323 }
1324 }
1325 ControlFlow::Break(())
1326 }
1327
1328 (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1329 match rw {
1330 Reservation(..) => {
1331 debug!(
1332 "recording invalid reservation of \
1333 place: {:?}",
1334 place_span.0
1335 );
1336 this.reservation_error_reported.insert(place_span.0);
1337 }
1338 Activation(_, activating) => {
1339 debug!(
1340 "observing check_place for activation of \
1341 borrow_index: {:?}",
1342 activating
1343 );
1344 }
1345 Read(..) | Write(..) => {}
1346 }
1347
1348 error_reported = true;
1349 match kind {
1350 WriteKind::MutableBorrow(bk) => {
1351 let err =
1352 this.report_conflicting_borrow(location, place_span, bk, borrow);
1353 this.buffer_error(err);
1354 }
1355 WriteKind::StorageDeadOrDrop => this
1356 .report_borrowed_value_does_not_live_long_enough(
1357 location,
1358 borrow,
1359 place_span,
1360 Some(WriteKind::StorageDeadOrDrop),
1361 ),
1362 WriteKind::Mutate => {
1363 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1364 }
1365 WriteKind::Move => {
1366 this.report_move_out_while_borrowed(location, place_span, borrow)
1367 }
1368 WriteKind::Replace => {
1369 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1370 }
1371 }
1372 ControlFlow::Break(())
1373 }
1374 },
1375 );
1376
1377 error_reported
1378 }
1379
1380 #[instrument(level = "debug", skip(self, state))]
1383 fn check_backward_incompatible_drop(
1384 &mut self,
1385 location: Location,
1386 place: Place<'tcx>,
1387 state: &BorrowckDomain,
1388 ) {
1389 let tcx = self.infcx.tcx;
1390 let sd = if place.ty(self.body, tcx).ty.needs_drop(tcx, self.body.typing_env(tcx)) {
1394 AccessDepth::Drop
1395 } else {
1396 AccessDepth::Shallow(None)
1397 };
1398
1399 let borrows_in_scope = self.borrows_in_scope(location, state);
1400
1401 each_borrow_involving_path(
1404 self,
1405 self.infcx.tcx,
1406 self.body,
1407 (sd, place),
1408 self.borrow_set,
1409 |borrow_index| borrows_in_scope.contains(borrow_index),
1410 |this, _borrow_index, borrow| {
1411 if matches!(borrow.kind, BorrowKind::Fake(_)) {
1412 return ControlFlow::Continue(());
1413 }
1414 let borrowed = this.retrieve_borrow_spans(borrow).var_or_use_path_span();
1415 let explain = this.explain_why_borrow_contains_point(
1416 location,
1417 borrow,
1418 Some((WriteKind::StorageDeadOrDrop, place)),
1419 );
1420 this.infcx.tcx.node_span_lint(
1421 TAIL_EXPR_DROP_ORDER,
1422 CRATE_HIR_ID,
1423 borrowed,
1424 |diag| {
1425 session_diagnostics::TailExprDropOrder { borrowed }.decorate_lint(diag);
1426 explain.add_explanation_to_diagnostic(&this, diag, "", None, None);
1427 },
1428 );
1429 ControlFlow::Break(())
1431 },
1432 );
1433 }
1434
1435 fn mutate_place(
1436 &mut self,
1437 location: Location,
1438 place_span: (Place<'tcx>, Span),
1439 kind: AccessDepth,
1440 state: &BorrowckDomain,
1441 ) {
1442 self.check_if_assigned_path_is_moved(location, place_span, state);
1444
1445 self.access_place(
1446 location,
1447 place_span,
1448 (kind, Write(WriteKind::Mutate)),
1449 LocalMutationIsAllowed::No,
1450 state,
1451 );
1452 }
1453
1454 fn consume_rvalue(
1455 &mut self,
1456 location: Location,
1457 (rvalue, span): (&Rvalue<'tcx>, Span),
1458 state: &BorrowckDomain,
1459 ) {
1460 match rvalue {
1461 &Rvalue::Ref(_ , bk, place) => {
1462 let access_kind = match bk {
1463 BorrowKind::Fake(FakeBorrowKind::Shallow) => {
1464 (Shallow(Some(ArtificialField::FakeBorrow)), Read(ReadKind::Borrow(bk)))
1465 }
1466 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep) => {
1467 (Deep, Read(ReadKind::Borrow(bk)))
1468 }
1469 BorrowKind::Mut { .. } => {
1470 let wk = WriteKind::MutableBorrow(bk);
1471 if bk.allows_two_phase_borrow() {
1472 (Deep, Reservation(wk))
1473 } else {
1474 (Deep, Write(wk))
1475 }
1476 }
1477 };
1478
1479 self.access_place(
1480 location,
1481 (place, span),
1482 access_kind,
1483 LocalMutationIsAllowed::No,
1484 state,
1485 );
1486
1487 let action = if bk == BorrowKind::Fake(FakeBorrowKind::Shallow) {
1488 InitializationRequiringAction::MatchOn
1489 } else {
1490 InitializationRequiringAction::Borrow
1491 };
1492
1493 self.check_if_path_or_subpath_is_moved(
1494 location,
1495 action,
1496 (place.as_ref(), span),
1497 state,
1498 );
1499 }
1500
1501 &Rvalue::RawPtr(kind, place) => {
1502 let access_kind = match kind {
1503 RawPtrKind::Mut => (
1504 Deep,
1505 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1506 kind: MutBorrowKind::Default,
1507 })),
1508 ),
1509 RawPtrKind::Const => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1510 RawPtrKind::FakeForPtrMetadata => {
1511 (Shallow(Some(ArtificialField::ArrayLength)), Read(ReadKind::Copy))
1512 }
1513 };
1514
1515 self.access_place(
1516 location,
1517 (place, span),
1518 access_kind,
1519 LocalMutationIsAllowed::No,
1520 state,
1521 );
1522
1523 self.check_if_path_or_subpath_is_moved(
1524 location,
1525 InitializationRequiringAction::Borrow,
1526 (place.as_ref(), span),
1527 state,
1528 );
1529 }
1530
1531 Rvalue::ThreadLocalRef(_) => {}
1532
1533 Rvalue::Use(operand)
1534 | Rvalue::Repeat(operand, _)
1535 | Rvalue::UnaryOp(_ , operand)
1536 | Rvalue::Cast(_ , operand, _ )
1537 | Rvalue::ShallowInitBox(operand, _ ) => {
1538 self.consume_operand(location, (operand, span), state)
1539 }
1540
1541 &Rvalue::Discriminant(place) => {
1542 let af = match *rvalue {
1543 Rvalue::Discriminant(..) => None,
1544 _ => unreachable!(),
1545 };
1546 self.access_place(
1547 location,
1548 (place, span),
1549 (Shallow(af), Read(ReadKind::Copy)),
1550 LocalMutationIsAllowed::No,
1551 state,
1552 );
1553 self.check_if_path_or_subpath_is_moved(
1554 location,
1555 InitializationRequiringAction::Use,
1556 (place.as_ref(), span),
1557 state,
1558 );
1559 }
1560
1561 Rvalue::BinaryOp(_bin_op, box (operand1, operand2)) => {
1562 self.consume_operand(location, (operand1, span), state);
1563 self.consume_operand(location, (operand2, span), state);
1564 }
1565
1566 Rvalue::NullaryOp(_op, _ty) => {
1567 }
1569
1570 Rvalue::Aggregate(aggregate_kind, operands) => {
1571 match **aggregate_kind {
1575 AggregateKind::Closure(def_id, _)
1576 | AggregateKind::CoroutineClosure(def_id, _)
1577 | AggregateKind::Coroutine(def_id, _) => {
1578 let def_id = def_id.expect_local();
1579 let used_mut_upvars = self.root_cx.used_mut_upvars(def_id);
1580 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1581 for field in used_mut_upvars.clone() {
1585 self.propagate_closure_used_mut_upvar(&operands[field]);
1586 }
1587 }
1588 AggregateKind::Adt(..)
1589 | AggregateKind::Array(..)
1590 | AggregateKind::Tuple { .. }
1591 | AggregateKind::RawPtr(..) => (),
1592 }
1593
1594 for operand in operands {
1595 self.consume_operand(location, (operand, span), state);
1596 }
1597 }
1598
1599 Rvalue::WrapUnsafeBinder(op, _) => {
1600 self.consume_operand(location, (op, span), state);
1601 }
1602
1603 Rvalue::CopyForDeref(_) => bug!("`CopyForDeref` in borrowck"),
1604 }
1605 }
1606
1607 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1608 let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1609 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1617 this.used_mut_upvars.push(field);
1618 return;
1619 }
1620
1621 for (place_ref, proj) in place.iter_projections().rev() {
1622 if proj == ProjectionElem::Deref {
1624 match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1625 ty::Ref(_, _, hir::Mutability::Mut) => return,
1627
1628 _ => {}
1629 }
1630 }
1631
1632 if let Some(field) = this.is_upvar_field_projection(place_ref) {
1634 this.used_mut_upvars.push(field);
1635 return;
1636 }
1637 }
1638
1639 this.used_mut.insert(place.local);
1641 };
1642
1643 match *operand {
1647 Operand::Move(place) | Operand::Copy(place) => {
1648 match place.as_local() {
1649 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1650 if self.body.local_decls[local].ty.is_mutable_ptr() {
1651 return;
1653 }
1654 let Some(temp_mpi) = self.move_data.rev_lookup.find_local(local) else {
1670 bug!("temporary should be tracked");
1671 };
1672 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1673 &self.move_data.inits[init_index]
1674 } else {
1675 bug!("temporary should be initialized exactly once")
1676 };
1677
1678 let InitLocation::Statement(loc) = init.location else {
1679 bug!("temporary initialized in arguments")
1680 };
1681
1682 let body = self.body;
1683 let bbd = &body[loc.block];
1684 let stmt = &bbd.statements[loc.statement_index];
1685 debug!("temporary assigned in: stmt={:?}", stmt);
1686
1687 match stmt.kind {
1688 StatementKind::Assign(box (
1689 _,
1690 Rvalue::Ref(_, _, source)
1691 | Rvalue::Use(Operand::Copy(source) | Operand::Move(source)),
1692 )) => {
1693 propagate_closure_used_mut_place(self, source);
1694 }
1695 _ => {
1696 bug!(
1697 "closures should only capture user variables \
1698 or references to user variables"
1699 );
1700 }
1701 }
1702 }
1703 _ => propagate_closure_used_mut_place(self, place),
1704 }
1705 }
1706 Operand::Constant(..) => {}
1707 }
1708 }
1709
1710 fn consume_operand(
1711 &mut self,
1712 location: Location,
1713 (operand, span): (&Operand<'tcx>, Span),
1714 state: &BorrowckDomain,
1715 ) {
1716 match *operand {
1717 Operand::Copy(place) => {
1718 self.access_place(
1721 location,
1722 (place, span),
1723 (Deep, Read(ReadKind::Copy)),
1724 LocalMutationIsAllowed::No,
1725 state,
1726 );
1727
1728 self.check_if_path_or_subpath_is_moved(
1730 location,
1731 InitializationRequiringAction::Use,
1732 (place.as_ref(), span),
1733 state,
1734 );
1735 }
1736 Operand::Move(place) => {
1737 self.check_movable_place(location, place);
1739
1740 self.access_place(
1742 location,
1743 (place, span),
1744 (Deep, Write(WriteKind::Move)),
1745 LocalMutationIsAllowed::Yes,
1746 state,
1747 );
1748
1749 self.check_if_path_or_subpath_is_moved(
1751 location,
1752 InitializationRequiringAction::Use,
1753 (place.as_ref(), span),
1754 state,
1755 );
1756 }
1757 Operand::Constant(_) => {}
1758 }
1759 }
1760
1761 #[instrument(level = "debug", skip(self))]
1764 fn check_for_invalidation_at_exit(
1765 &mut self,
1766 location: Location,
1767 borrow: &BorrowData<'tcx>,
1768 span: Span,
1769 ) {
1770 let place = borrow.borrowed_place;
1771 let mut root_place = PlaceRef { local: place.local, projection: &[] };
1772
1773 let might_be_alive = if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1779 root_place.projection = TyCtxtConsts::DEREF_PROJECTION;
1783 true
1784 } else {
1785 false
1786 };
1787
1788 let sd = if might_be_alive { Deep } else { Shallow(None) };
1789
1790 if places_conflict::borrow_conflicts_with_place(
1791 self.infcx.tcx,
1792 self.body,
1793 place,
1794 borrow.kind,
1795 root_place,
1796 sd,
1797 places_conflict::PlaceConflictBias::Overlap,
1798 ) {
1799 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1800 let span = self.infcx.tcx.sess.source_map().end_point(span);
1803 self.report_borrowed_value_does_not_live_long_enough(
1804 location,
1805 borrow,
1806 (place, span),
1807 None,
1808 )
1809 }
1810 }
1811
1812 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1815 debug!("check_for_local_borrow({:?})", borrow);
1816
1817 if borrow_of_local_data(borrow.borrowed_place) {
1818 let err = self.cannot_borrow_across_coroutine_yield(
1819 self.retrieve_borrow_spans(borrow).var_or_use(),
1820 yield_span,
1821 );
1822
1823 self.buffer_error(err);
1824 }
1825 }
1826
1827 fn check_activations(&mut self, location: Location, span: Span, state: &BorrowckDomain) {
1828 for &borrow_index in self.borrow_set.activations_at_location(location) {
1832 let borrow = &self.borrow_set[borrow_index];
1833
1834 assert!(match borrow.kind {
1836 BorrowKind::Shared | BorrowKind::Fake(_) => false,
1837 BorrowKind::Mut { .. } => true,
1838 });
1839
1840 self.access_place(
1841 location,
1842 (borrow.borrowed_place, span),
1843 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1844 LocalMutationIsAllowed::No,
1845 state,
1846 );
1847 }
1851 }
1852
1853 fn check_movable_place(&mut self, location: Location, place: Place<'tcx>) {
1854 use IllegalMoveOriginKind::*;
1855
1856 let body = self.body;
1857 let tcx = self.infcx.tcx;
1858 let mut place_ty = PlaceTy::from_ty(body.local_decls[place.local].ty);
1859 for (place_ref, elem) in place.iter_projections() {
1860 match elem {
1861 ProjectionElem::Deref => match place_ty.ty.kind() {
1862 ty::Ref(..) | ty::RawPtr(..) => {
1863 self.move_errors.push(MoveError::new(
1864 place,
1865 location,
1866 BorrowedContent {
1867 target_place: place_ref.project_deeper(&[elem], tcx),
1868 },
1869 ));
1870 return;
1871 }
1872 ty::Adt(adt, _) => {
1873 if !adt.is_box() {
1874 bug!("Adt should be a box type when Place is deref");
1875 }
1876 }
1877 ty::Bool
1878 | ty::Char
1879 | ty::Int(_)
1880 | ty::Uint(_)
1881 | ty::Float(_)
1882 | ty::Foreign(_)
1883 | ty::Str
1884 | ty::Array(_, _)
1885 | ty::Pat(_, _)
1886 | ty::Slice(_)
1887 | ty::FnDef(_, _)
1888 | ty::FnPtr(..)
1889 | ty::Dynamic(_, _)
1890 | ty::Closure(_, _)
1891 | ty::CoroutineClosure(_, _)
1892 | ty::Coroutine(_, _)
1893 | ty::CoroutineWitness(..)
1894 | ty::Never
1895 | ty::Tuple(_)
1896 | ty::UnsafeBinder(_)
1897 | ty::Alias(_, _)
1898 | ty::Param(_)
1899 | ty::Bound(_, _)
1900 | ty::Infer(_)
1901 | ty::Error(_)
1902 | ty::Placeholder(_) => {
1903 bug!("When Place is Deref it's type shouldn't be {place_ty:#?}")
1904 }
1905 },
1906 ProjectionElem::Field(_, _) => match place_ty.ty.kind() {
1907 ty::Adt(adt, _) => {
1908 if adt.has_dtor(tcx) {
1909 self.move_errors.push(MoveError::new(
1910 place,
1911 location,
1912 InteriorOfTypeWithDestructor { container_ty: place_ty.ty },
1913 ));
1914 return;
1915 }
1916 }
1917 ty::Closure(..)
1918 | ty::CoroutineClosure(..)
1919 | ty::Coroutine(_, _)
1920 | ty::Tuple(_) => (),
1921 ty::Bool
1922 | ty::Char
1923 | ty::Int(_)
1924 | ty::Uint(_)
1925 | ty::Float(_)
1926 | ty::Foreign(_)
1927 | ty::Str
1928 | ty::Array(_, _)
1929 | ty::Pat(_, _)
1930 | ty::Slice(_)
1931 | ty::RawPtr(_, _)
1932 | ty::Ref(_, _, _)
1933 | ty::FnDef(_, _)
1934 | ty::FnPtr(..)
1935 | ty::Dynamic(_, _)
1936 | ty::CoroutineWitness(..)
1937 | ty::Never
1938 | ty::UnsafeBinder(_)
1939 | ty::Alias(_, _)
1940 | ty::Param(_)
1941 | ty::Bound(_, _)
1942 | ty::Infer(_)
1943 | ty::Error(_)
1944 | ty::Placeholder(_) => bug!(
1945 "When Place contains ProjectionElem::Field it's type shouldn't be {place_ty:#?}"
1946 ),
1947 },
1948 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
1949 match place_ty.ty.kind() {
1950 ty::Slice(_) => {
1951 self.move_errors.push(MoveError::new(
1952 place,
1953 location,
1954 InteriorOfSliceOrArray { ty: place_ty.ty, is_index: false },
1955 ));
1956 return;
1957 }
1958 ty::Array(_, _) => (),
1959 _ => bug!("Unexpected type {:#?}", place_ty.ty),
1960 }
1961 }
1962 ProjectionElem::Index(_) => match place_ty.ty.kind() {
1963 ty::Array(..) | ty::Slice(..) => {
1964 self.move_errors.push(MoveError::new(
1965 place,
1966 location,
1967 InteriorOfSliceOrArray { ty: place_ty.ty, is_index: true },
1968 ));
1969 return;
1970 }
1971 _ => bug!("Unexpected type {place_ty:#?}"),
1972 },
1973 ProjectionElem::OpaqueCast(_)
1977 | ProjectionElem::Downcast(_, _)
1978 | ProjectionElem::UnwrapUnsafeBinder(_) => (),
1979 }
1980
1981 place_ty = place_ty.projection_ty(tcx, elem);
1982 }
1983 }
1984
1985 fn check_if_full_path_is_moved(
1986 &mut self,
1987 location: Location,
1988 desired_action: InitializationRequiringAction,
1989 place_span: (PlaceRef<'tcx>, Span),
1990 state: &BorrowckDomain,
1991 ) {
1992 let maybe_uninits = &state.uninits;
1993
1994 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
2030 let (prefix, mpi) = self.move_path_closest_to(place_span.0);
2031 if maybe_uninits.contains(mpi) {
2032 self.report_use_of_moved_or_uninitialized(
2033 location,
2034 desired_action,
2035 (prefix, place_span.0, place_span.1),
2036 mpi,
2037 );
2038 } }
2045
2046 fn check_if_subslice_element_is_moved(
2052 &mut self,
2053 location: Location,
2054 desired_action: InitializationRequiringAction,
2055 place_span: (PlaceRef<'tcx>, Span),
2056 maybe_uninits: &MixedBitSet<MovePathIndex>,
2057 from: u64,
2058 to: u64,
2059 ) {
2060 if let Some(mpi) = self.move_path_for_place(place_span.0) {
2061 let move_paths = &self.move_data.move_paths;
2062
2063 let root_path = &move_paths[mpi];
2064 for (child_mpi, child_move_path) in root_path.children(move_paths) {
2065 let last_proj = child_move_path.place.projection.last().unwrap();
2066 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
2067 debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
2068
2069 if (from..to).contains(offset) {
2070 let uninit_child =
2071 self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
2072 maybe_uninits.contains(mpi)
2073 });
2074
2075 if let Some(uninit_child) = uninit_child {
2076 self.report_use_of_moved_or_uninitialized(
2077 location,
2078 desired_action,
2079 (place_span.0, place_span.0, place_span.1),
2080 uninit_child,
2081 );
2082 return; }
2084 }
2085 }
2086 }
2087 }
2088 }
2089
2090 fn check_if_path_or_subpath_is_moved(
2091 &mut self,
2092 location: Location,
2093 desired_action: InitializationRequiringAction,
2094 place_span: (PlaceRef<'tcx>, Span),
2095 state: &BorrowckDomain,
2096 ) {
2097 let maybe_uninits = &state.uninits;
2098
2099 self.check_if_full_path_is_moved(location, desired_action, place_span, state);
2115
2116 if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
2117 place_span.0.last_projection()
2118 {
2119 let place_ty = place_base.ty(self.body(), self.infcx.tcx);
2120 if let ty::Array(..) = place_ty.ty.kind() {
2121 self.check_if_subslice_element_is_moved(
2122 location,
2123 desired_action,
2124 (place_base, place_span.1),
2125 maybe_uninits,
2126 from,
2127 to,
2128 );
2129 return;
2130 }
2131 }
2132
2133 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
2143 if let Some(mpi) = self.move_path_for_place(place_span.0) {
2144 let uninit_mpi = self
2145 .move_data
2146 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
2147
2148 if let Some(uninit_mpi) = uninit_mpi {
2149 self.report_use_of_moved_or_uninitialized(
2150 location,
2151 desired_action,
2152 (place_span.0, place_span.0, place_span.1),
2153 uninit_mpi,
2154 );
2155 return; }
2157 }
2158 }
2159
2160 fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
2171 match self.move_data.rev_lookup.find(place) {
2172 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
2173 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
2174 }
2175 LookupResult::Parent(None) => panic!("should have move path for every Local"),
2176 }
2177 }
2178
2179 fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
2180 match self.move_data.rev_lookup.find(place) {
2185 LookupResult::Parent(_) => None,
2186 LookupResult::Exact(mpi) => Some(mpi),
2187 }
2188 }
2189
2190 fn check_if_assigned_path_is_moved(
2191 &mut self,
2192 location: Location,
2193 (place, span): (Place<'tcx>, Span),
2194 state: &BorrowckDomain,
2195 ) {
2196 debug!("check_if_assigned_path_is_moved place: {:?}", place);
2197
2198 for (place_base, elem) in place.iter_projections().rev() {
2200 match elem {
2201 ProjectionElem::Index(_) |
2202 ProjectionElem::OpaqueCast(_) |
2203 ProjectionElem::ConstantIndex { .. } |
2204 ProjectionElem::Downcast(_, _) =>
2206 { }
2210
2211 ProjectionElem::UnwrapUnsafeBinder(_) => {
2212 check_parent_of_field(self, location, place_base, span, state);
2213 }
2214
2215 ProjectionElem::Deref => {
2217 self.check_if_full_path_is_moved(
2218 location, InitializationRequiringAction::Use,
2219 (place_base, span), state);
2220 break;
2223 }
2224
2225 ProjectionElem::Subslice { .. } => {
2226 panic!("we don't allow assignments to subslices, location: {location:?}");
2227 }
2228
2229 ProjectionElem::Field(..) => {
2230 let tcx = self.infcx.tcx;
2234 let base_ty = place_base.ty(self.body(), tcx).ty;
2235 match base_ty.kind() {
2236 ty::Adt(def, _) if def.has_dtor(tcx) => {
2237 self.check_if_path_or_subpath_is_moved(
2238 location, InitializationRequiringAction::Assignment,
2239 (place_base, span), state);
2240
2241 break;
2244 }
2245
2246 ty::Adt(..) | ty::Tuple(..) => {
2249 check_parent_of_field(self, location, place_base, span, state);
2250 }
2251
2252 _ => {}
2253 }
2254 }
2255 }
2256 }
2257
2258 fn check_parent_of_field<'a, 'tcx>(
2259 this: &mut MirBorrowckCtxt<'a, '_, 'tcx>,
2260 location: Location,
2261 base: PlaceRef<'tcx>,
2262 span: Span,
2263 state: &BorrowckDomain,
2264 ) {
2265 let maybe_uninits = &state.uninits;
2297
2298 let mut shortest_uninit_seen = None;
2301 for prefix in this.prefixes(base, PrefixSet::Shallow) {
2302 let Some(mpi) = this.move_path_for_place(prefix) else { continue };
2303
2304 if maybe_uninits.contains(mpi) {
2305 debug!(
2306 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
2307 shortest_uninit_seen,
2308 Some((prefix, mpi))
2309 );
2310 shortest_uninit_seen = Some((prefix, mpi));
2311 } else {
2312 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
2313 }
2314 }
2315
2316 if let Some((prefix, mpi)) = shortest_uninit_seen {
2317 let tcx = this.infcx.tcx;
2323 if base.ty(this.body(), tcx).ty.is_union()
2324 && this.move_data.path_map[mpi].iter().any(|moi| {
2325 this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
2326 })
2327 {
2328 return;
2329 }
2330
2331 this.report_use_of_moved_or_uninitialized(
2332 location,
2333 InitializationRequiringAction::PartialAssignment,
2334 (prefix, base, span),
2335 mpi,
2336 );
2337
2338 this.used_mut.insert(base.local);
2342 }
2343 }
2344 }
2345
2346 fn check_access_permissions(
2350 &mut self,
2351 (place, span): (Place<'tcx>, Span),
2352 kind: ReadOrWrite,
2353 is_local_mutation_allowed: LocalMutationIsAllowed,
2354 state: &BorrowckDomain,
2355 location: Location,
2356 ) -> bool {
2357 debug!(
2358 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
2359 place, kind, is_local_mutation_allowed
2360 );
2361
2362 let error_access;
2363 let the_place_err;
2364
2365 match kind {
2366 Reservation(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind }))
2367 | Write(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind })) => {
2368 let is_local_mutation_allowed = match mut_borrow_kind {
2369 MutBorrowKind::ClosureCapture => LocalMutationIsAllowed::Yes,
2373 MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow => {
2374 is_local_mutation_allowed
2375 }
2376 };
2377 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2378 Ok(root_place) => {
2379 self.add_used_mut(root_place, state);
2380 return false;
2381 }
2382 Err(place_err) => {
2383 error_access = AccessKind::MutableBorrow;
2384 the_place_err = place_err;
2385 }
2386 }
2387 }
2388 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
2389 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2390 Ok(root_place) => {
2391 self.add_used_mut(root_place, state);
2392 return false;
2393 }
2394 Err(place_err) => {
2395 error_access = AccessKind::Mutate;
2396 the_place_err = place_err;
2397 }
2398 }
2399 }
2400
2401 Reservation(
2402 WriteKind::Move
2403 | WriteKind::Replace
2404 | WriteKind::StorageDeadOrDrop
2405 | WriteKind::MutableBorrow(BorrowKind::Shared)
2406 | WriteKind::MutableBorrow(BorrowKind::Fake(_)),
2407 )
2408 | Write(
2409 WriteKind::Move
2410 | WriteKind::Replace
2411 | WriteKind::StorageDeadOrDrop
2412 | WriteKind::MutableBorrow(BorrowKind::Shared)
2413 | WriteKind::MutableBorrow(BorrowKind::Fake(_)),
2414 ) => {
2415 if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err()
2416 && !self.has_buffered_diags()
2417 {
2418 self.dcx().span_delayed_bug(
2424 span,
2425 format!(
2426 "Accessing `{place:?}` with the kind `{kind:?}` shouldn't be possible",
2427 ),
2428 );
2429 }
2430 return false;
2431 }
2432 Activation(..) => {
2433 return false;
2435 }
2436 Read(
2437 ReadKind::Borrow(BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_))
2438 | ReadKind::Copy,
2439 ) => {
2440 return false;
2442 }
2443 }
2444
2445 let previously_initialized = self.is_local_ever_initialized(place.local, state);
2450
2451 if let Some(init_index) = previously_initialized {
2453 if let (AccessKind::Mutate, Some(_)) = (error_access, place.as_local()) {
2454 let init = &self.move_data.inits[init_index];
2457 let assigned_span = init.span(self.body);
2458 self.report_illegal_reassignment((place, span), assigned_span, place);
2459 } else {
2460 self.report_mutability_error(place, span, the_place_err, error_access, location)
2461 }
2462 true
2463 } else {
2464 false
2465 }
2466 }
2467
2468 fn is_local_ever_initialized(&self, local: Local, state: &BorrowckDomain) -> Option<InitIndex> {
2469 let mpi = self.move_data.rev_lookup.find_local(local)?;
2470 let ii = &self.move_data.init_path_map[mpi];
2471 ii.into_iter().find(|&&index| state.ever_inits.contains(index)).copied()
2472 }
2473
2474 fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, state: &BorrowckDomain) {
2476 match root_place {
2477 RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2478 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2482 && self.is_local_ever_initialized(local, state).is_some()
2483 {
2484 self.used_mut.insert(local);
2485 }
2486 }
2487 RootPlace {
2488 place_local: _,
2489 place_projection: _,
2490 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2491 } => {}
2492 RootPlace {
2493 place_local,
2494 place_projection: place_projection @ [.., _],
2495 is_local_mutation_allowed: _,
2496 } => {
2497 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2498 local: place_local,
2499 projection: place_projection,
2500 }) {
2501 self.used_mut_upvars.push(field);
2502 }
2503 }
2504 }
2505 }
2506
2507 fn is_mutable(
2510 &self,
2511 place: PlaceRef<'tcx>,
2512 is_local_mutation_allowed: LocalMutationIsAllowed,
2513 ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2514 debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2515 match place.last_projection() {
2516 None => {
2517 let local = &self.body.local_decls[place.local];
2518 match local.mutability {
2519 Mutability::Not => match is_local_mutation_allowed {
2520 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2521 place_local: place.local,
2522 place_projection: place.projection,
2523 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2524 }),
2525 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2526 place_local: place.local,
2527 place_projection: place.projection,
2528 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2529 }),
2530 LocalMutationIsAllowed::No => Err(place),
2531 },
2532 Mutability::Mut => Ok(RootPlace {
2533 place_local: place.local,
2534 place_projection: place.projection,
2535 is_local_mutation_allowed,
2536 }),
2537 }
2538 }
2539 Some((place_base, elem)) => {
2540 match elem {
2541 ProjectionElem::Deref => {
2542 let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2543
2544 match base_ty.kind() {
2546 ty::Ref(_, _, mutbl) => {
2547 match mutbl {
2548 hir::Mutability::Not => Err(place),
2550 hir::Mutability::Mut => {
2553 let mode = match self.is_upvar_field_projection(place) {
2554 Some(field)
2555 if self.upvars[field.index()].is_by_ref() =>
2556 {
2557 is_local_mutation_allowed
2558 }
2559 _ => LocalMutationIsAllowed::Yes,
2560 };
2561
2562 self.is_mutable(place_base, mode)
2563 }
2564 }
2565 }
2566 ty::RawPtr(_, mutbl) => {
2567 match mutbl {
2568 hir::Mutability::Not => Err(place),
2570 hir::Mutability::Mut => Ok(RootPlace {
2573 place_local: place.local,
2574 place_projection: place.projection,
2575 is_local_mutation_allowed,
2576 }),
2577 }
2578 }
2579 _ if base_ty.is_box() => {
2581 self.is_mutable(place_base, is_local_mutation_allowed)
2582 }
2583 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2585 }
2586 }
2587 ProjectionElem::Field(..)
2590 | ProjectionElem::Index(..)
2591 | ProjectionElem::ConstantIndex { .. }
2592 | ProjectionElem::Subslice { .. }
2593 | ProjectionElem::OpaqueCast { .. }
2594 | ProjectionElem::Downcast(..)
2595 | ProjectionElem::UnwrapUnsafeBinder(_) => {
2596 let upvar_field_projection = self.is_upvar_field_projection(place);
2597 if let Some(field) = upvar_field_projection {
2598 let upvar = &self.upvars[field.index()];
2599 debug!(
2600 "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2601 place={:?}, place_base={:?}",
2602 upvar, is_local_mutation_allowed, place, place_base
2603 );
2604 match (upvar.mutability, is_local_mutation_allowed) {
2605 (
2606 Mutability::Not,
2607 LocalMutationIsAllowed::No
2608 | LocalMutationIsAllowed::ExceptUpvars,
2609 ) => Err(place),
2610 (Mutability::Not, LocalMutationIsAllowed::Yes)
2611 | (Mutability::Mut, _) => {
2612 let _ =
2631 self.is_mutable(place_base, is_local_mutation_allowed)?;
2632 Ok(RootPlace {
2633 place_local: place.local,
2634 place_projection: place.projection,
2635 is_local_mutation_allowed,
2636 })
2637 }
2638 }
2639 } else {
2640 self.is_mutable(place_base, is_local_mutation_allowed)
2641 }
2642 }
2643 }
2644 }
2645 }
2646 }
2647
2648 fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<FieldIdx> {
2653 path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2654 }
2655
2656 fn dominators(&self) -> &Dominators<BasicBlock> {
2657 self.body.basic_blocks.dominators()
2659 }
2660
2661 fn lint_unused_mut(&self) {
2662 let tcx = self.infcx.tcx;
2663 let body = self.body;
2664 for local in body.mut_vars_and_args_iter().filter(|local| !self.used_mut.contains(local)) {
2665 let local_decl = &body.local_decls[local];
2666 let ClearCrossCrate::Set(SourceScopeLocalData { lint_root, .. }) =
2667 body.source_scopes[local_decl.source_info.scope].local_data
2668 else {
2669 continue;
2670 };
2671
2672 if self.local_excluded_from_unused_mut_lint(local) {
2674 continue;
2675 }
2676
2677 let span = local_decl.source_info.span;
2678 if span.desugaring_kind().is_some() {
2679 continue;
2681 }
2682
2683 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
2684
2685 tcx.emit_node_span_lint(UNUSED_MUT, lint_root, span, VarNeedNotMut { span: mut_span })
2686 }
2687 }
2688}
2689
2690enum Overlap {
2692 Arbitrary,
2698 EqualOrDisjoint,
2703 Disjoint,
2706}