1#![allow(internal_features)]
5#![deny(clippy::manual_let_else)]
6#![feature(assert_matches)]
7#![feature(box_patterns)]
8#![feature(file_buffered)]
9#![feature(if_let_guard)]
10#![feature(negative_impls)]
11#![feature(never_type)]
12#![feature(rustc_attrs)]
13#![feature(stmt_expr_attributes)]
14#![feature(try_blocks)]
15use std::borrow::Cow;
18use std::cell::{OnceCell, RefCell};
19use std::marker::PhantomData;
20use std::ops::{ControlFlow, Deref};
21use std::rc::Rc;
22
23use borrow_set::LocalsStateAtExit;
24use polonius_engine::AllFacts;
25use root_cx::BorrowCheckRootCtxt;
26use rustc_abi::FieldIdx;
27use rustc_data_structures::frozen::Frozen;
28use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
29use rustc_data_structures::graph::dominators::Dominators;
30use rustc_errors::LintDiagnostic;
31use rustc_hir as hir;
32use rustc_hir::CRATE_HIR_ID;
33use rustc_hir::def_id::LocalDefId;
34use rustc_index::bit_set::MixedBitSet;
35use rustc_index::{IndexSlice, IndexVec};
36use rustc_infer::infer::outlives::env::RegionBoundPairs;
37use rustc_infer::infer::{
38 InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin, TyCtxtInferExt,
39};
40use rustc_middle::mir::*;
41use rustc_middle::query::Providers;
42use rustc_middle::ty::{
43 self, ParamEnv, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitable, TypingMode, fold_regions,
44};
45use rustc_middle::{bug, span_bug};
46use rustc_mir_dataflow::impls::{EverInitializedPlaces, MaybeUninitializedPlaces};
47use rustc_mir_dataflow::move_paths::{
48 InitIndex, InitLocation, LookupResult, MoveData, MovePathIndex,
49};
50use rustc_mir_dataflow::points::DenseLocationMap;
51use rustc_mir_dataflow::{Analysis, EntryStates, Results, ResultsVisitor, visit_results};
52use rustc_session::lint::builtin::{TAIL_EXPR_DROP_ORDER, UNUSED_MUT};
53use rustc_span::{ErrorGuaranteed, Span, Symbol};
54use smallvec::SmallVec;
55use tracing::{debug, instrument};
56
57use crate::borrow_set::{BorrowData, BorrowSet};
58use crate::consumers::{BodyWithBorrowckFacts, RustcFacts};
59use crate::dataflow::{BorrowIndex, Borrowck, BorrowckDomain, Borrows};
60use crate::diagnostics::{
61 AccessKind, BorrowckDiagnosticsBuffer, IllegalMoveOriginKind, MoveError, RegionName,
62};
63use crate::path_utils::*;
64use crate::place_ext::PlaceExt;
65use crate::places_conflict::{PlaceConflictBias, places_conflict};
66use crate::polonius::legacy::{
67 PoloniusFacts, PoloniusFactsExt, PoloniusLocationTable, PoloniusOutput,
68};
69use crate::polonius::{PoloniusContext, PoloniusDiagnosticsContext};
70use crate::prefixes::PrefixSet;
71use crate::region_infer::RegionInferenceContext;
72use crate::region_infer::opaque_types::DeferredOpaqueTypeError;
73use crate::renumber::RegionCtxt;
74use crate::session_diagnostics::VarNeedNotMut;
75use crate::type_check::free_region_relations::UniversalRegionRelations;
76use crate::type_check::{Locations, MirTypeckRegionConstraints, MirTypeckResults};
77
78mod borrow_set;
79mod borrowck_errors;
80mod constraints;
81mod dataflow;
82mod def_use;
83mod diagnostics;
84mod handle_placeholders;
85mod nll;
86mod path_utils;
87mod place_ext;
88mod places_conflict;
89mod polonius;
90mod prefixes;
91mod region_infer;
92mod renumber;
93mod root_cx;
94mod session_diagnostics;
95mod type_check;
96mod universal_regions;
97mod used_muts;
98
99pub mod consumers;
101
102rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
103
104struct TyCtxtConsts<'tcx>(PhantomData<&'tcx ()>);
106
107impl<'tcx> TyCtxtConsts<'tcx> {
108 const DEREF_PROJECTION: &'tcx [PlaceElem<'tcx>; 1] = &[ProjectionElem::Deref];
109}
110
111pub fn provide(providers: &mut Providers) {
112 *providers = Providers { mir_borrowck, ..*providers };
113}
114
115fn mir_borrowck(
119 tcx: TyCtxt<'_>,
120 def: LocalDefId,
121) -> Result<&FxIndexMap<LocalDefId, ty::DefinitionSiteHiddenType<'_>>, ErrorGuaranteed> {
122 assert!(!tcx.is_typeck_child(def.to_def_id()));
123 let (input_body, _) = tcx.mir_promoted(def);
124 debug!("run query mir_borrowck: {}", tcx.def_path_str(def));
125
126 let input_body: &Body<'_> = &input_body.borrow();
127 if let Some(guar) = input_body.tainted_by_errors {
128 debug!("Skipping borrowck because of tainted body");
129 Err(guar)
130 } else if input_body.should_skip() {
131 debug!("Skipping borrowck because of injected body");
132 let opaque_types = Default::default();
133 Ok(tcx.arena.alloc(opaque_types))
134 } else {
135 let mut root_cx = BorrowCheckRootCtxt::new(tcx, def, None);
136 root_cx.do_mir_borrowck();
137 root_cx.finalize()
138 }
139}
140
141#[derive(Debug)]
144struct PropagatedBorrowCheckResults<'tcx> {
145 closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
146 used_mut_upvars: SmallVec<[FieldIdx; 8]>,
147}
148
149type DeferredClosureRequirements<'tcx> = Vec<(LocalDefId, ty::GenericArgsRef<'tcx>, Locations)>;
150
151#[derive(Clone, Debug)]
194pub struct ClosureRegionRequirements<'tcx> {
195 pub num_external_vids: usize,
201
202 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
205}
206
207#[derive(Copy, Clone, Debug)]
210pub struct ClosureOutlivesRequirement<'tcx> {
211 pub subject: ClosureOutlivesSubject<'tcx>,
213
214 pub outlived_free_region: ty::RegionVid,
216
217 pub blame_span: Span,
219
220 pub category: ConstraintCategory<'tcx>,
222}
223
224#[cfg(target_pointer_width = "64")]
226rustc_data_structures::static_assert_size!(ConstraintCategory<'_>, 16);
227
228#[derive(Copy, Clone, Debug)]
231pub enum ClosureOutlivesSubject<'tcx> {
232 Ty(ClosureOutlivesSubjectTy<'tcx>),
236
237 Region(ty::RegionVid),
240}
241
242#[derive(Copy, Clone, Debug)]
248pub struct ClosureOutlivesSubjectTy<'tcx> {
249 inner: Ty<'tcx>,
250}
251impl<'tcx, I> !TypeVisitable<I> for ClosureOutlivesSubjectTy<'tcx> {}
254impl<'tcx, I> !TypeFoldable<I> for ClosureOutlivesSubjectTy<'tcx> {}
255
256impl<'tcx> ClosureOutlivesSubjectTy<'tcx> {
257 pub fn bind(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Self {
260 let inner = fold_regions(tcx, ty, |r, depth| match r.kind() {
261 ty::ReVar(vid) => {
262 let br = ty::BoundRegion {
263 var: ty::BoundVar::from_usize(vid.index()),
264 kind: ty::BoundRegionKind::Anon,
265 };
266 ty::Region::new_bound(tcx, depth, br)
267 }
268 _ => bug!("unexpected region in ClosureOutlivesSubjectTy: {r:?}"),
269 });
270
271 Self { inner }
272 }
273
274 pub fn instantiate(
275 self,
276 tcx: TyCtxt<'tcx>,
277 mut map: impl FnMut(ty::RegionVid) -> ty::Region<'tcx>,
278 ) -> Ty<'tcx> {
279 fold_regions(tcx, self.inner, |r, depth| match r.kind() {
280 ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn), br) => {
281 debug_assert_eq!(debruijn, depth);
282 map(ty::RegionVid::from_usize(br.var.index()))
283 }
284 _ => bug!("unexpected region {r:?}"),
285 })
286 }
287}
288
289struct CollectRegionConstraintsResult<'tcx> {
290 infcx: BorrowckInferCtxt<'tcx>,
291 body_owned: Body<'tcx>,
292 promoted: IndexVec<Promoted, Body<'tcx>>,
293 move_data: MoveData<'tcx>,
294 borrow_set: BorrowSet<'tcx>,
295 location_table: PoloniusLocationTable,
296 location_map: Rc<DenseLocationMap>,
297 universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
298 region_bound_pairs: Frozen<RegionBoundPairs<'tcx>>,
299 known_type_outlives_obligations: Frozen<Vec<ty::PolyTypeOutlivesPredicate<'tcx>>>,
300 constraints: MirTypeckRegionConstraints<'tcx>,
301 deferred_closure_requirements: DeferredClosureRequirements<'tcx>,
302 deferred_opaque_type_errors: Vec<DeferredOpaqueTypeError<'tcx>>,
303 polonius_facts: Option<AllFacts<RustcFacts>>,
304 polonius_context: Option<PoloniusContext>,
305}
306
307fn borrowck_collect_region_constraints<'tcx>(
311 root_cx: &mut BorrowCheckRootCtxt<'tcx>,
312 def: LocalDefId,
313) -> CollectRegionConstraintsResult<'tcx> {
314 let tcx = root_cx.tcx;
315 let infcx = BorrowckInferCtxt::new(tcx, def, root_cx.root_def_id());
316 let (input_body, promoted) = tcx.mir_promoted(def);
317 let input_body: &Body<'_> = &input_body.borrow();
318 let input_promoted: &IndexSlice<_, _> = &promoted.borrow();
319 if let Some(e) = input_body.tainted_by_errors {
320 infcx.set_tainted_by_errors(e);
321 root_cx.set_tainted_by_errors(e);
322 }
323
324 let mut body_owned = input_body.clone();
329 let mut promoted = input_promoted.to_owned();
330 let universal_regions = nll::replace_regions_in_mir(&infcx, &mut body_owned, &mut promoted);
331 let body = &body_owned; let location_table = PoloniusLocationTable::new(body);
334
335 let move_data = MoveData::gather_moves(body, tcx, |_| true);
336
337 let locals_are_invalidated_at_exit = tcx.hir_body_owner_kind(def).is_fn_or_closure();
338 let borrow_set = BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &move_data);
339
340 let location_map = Rc::new(DenseLocationMap::new(body));
341
342 let polonius_input = root_cx.consumer.as_ref().map_or(false, |c| c.polonius_input())
343 || infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled();
344 let mut polonius_facts =
345 (polonius_input || PoloniusFacts::enabled(infcx.tcx)).then_some(PoloniusFacts::default());
346
347 let MirTypeckResults {
349 constraints,
350 universal_region_relations,
351 region_bound_pairs,
352 known_type_outlives_obligations,
353 deferred_closure_requirements,
354 polonius_context,
355 } = type_check::type_check(
356 root_cx,
357 &infcx,
358 body,
359 &promoted,
360 universal_regions,
361 &location_table,
362 &borrow_set,
363 &mut polonius_facts,
364 &move_data,
365 Rc::clone(&location_map),
366 );
367
368 CollectRegionConstraintsResult {
369 infcx,
370 body_owned,
371 promoted,
372 move_data,
373 borrow_set,
374 location_table,
375 location_map,
376 universal_region_relations,
377 region_bound_pairs,
378 known_type_outlives_obligations,
379 constraints,
380 deferred_closure_requirements,
381 deferred_opaque_type_errors: Default::default(),
382 polonius_facts,
383 polonius_context,
384 }
385}
386
387fn borrowck_check_region_constraints<'tcx>(
391 root_cx: &mut BorrowCheckRootCtxt<'tcx>,
392 CollectRegionConstraintsResult {
393 infcx,
394 body_owned,
395 promoted,
396 move_data,
397 borrow_set,
398 location_table,
399 location_map,
400 universal_region_relations,
401 region_bound_pairs: _,
402 known_type_outlives_obligations: _,
403 constraints,
404 deferred_closure_requirements,
405 deferred_opaque_type_errors,
406 polonius_facts,
407 polonius_context,
408 }: CollectRegionConstraintsResult<'tcx>,
409) -> PropagatedBorrowCheckResults<'tcx> {
410 assert!(!infcx.has_opaque_types_in_storage());
411 assert!(deferred_closure_requirements.is_empty());
412 let tcx = root_cx.tcx;
413 let body = &body_owned;
414 let def = body.source.def_id().expect_local();
415
416 let nll::NllOutput {
419 regioncx,
420 polonius_input,
421 polonius_output,
422 opt_closure_req,
423 nll_errors,
424 polonius_diagnostics,
425 } = nll::compute_regions(
426 root_cx,
427 &infcx,
428 body,
429 &location_table,
430 &move_data,
431 &borrow_set,
432 location_map,
433 universal_region_relations,
434 constraints,
435 polonius_facts,
436 polonius_context,
437 );
438
439 nll::dump_nll_mir(&infcx, body, ®ioncx, &opt_closure_req, &borrow_set);
442 polonius::dump_polonius_mir(
443 &infcx,
444 body,
445 ®ioncx,
446 &opt_closure_req,
447 &borrow_set,
448 polonius_diagnostics.as_ref(),
449 );
450
451 nll::dump_annotation(&infcx, body, ®ioncx, &opt_closure_req);
454
455 let movable_coroutine = body.coroutine.is_some()
456 && tcx.coroutine_movability(def.to_def_id()) == hir::Movability::Movable;
457
458 let diags_buffer = &mut BorrowckDiagnosticsBuffer::default();
459 for promoted_body in &promoted {
462 use rustc_middle::mir::visit::Visitor;
463 let move_data = MoveData::gather_moves(promoted_body, tcx, |_| true);
467 let mut promoted_mbcx = MirBorrowckCtxt {
468 root_cx,
469 infcx: &infcx,
470 body: promoted_body,
471 move_data: &move_data,
472 location_table: &location_table,
474 movable_coroutine,
475 fn_self_span_reported: Default::default(),
476 access_place_error_reported: Default::default(),
477 reservation_error_reported: Default::default(),
478 uninitialized_error_reported: Default::default(),
479 regioncx: ®ioncx,
480 used_mut: Default::default(),
481 used_mut_upvars: SmallVec::new(),
482 borrow_set: &borrow_set,
483 upvars: &[],
484 local_names: OnceCell::from(IndexVec::from_elem(None, &promoted_body.local_decls)),
485 region_names: RefCell::default(),
486 next_region_name: RefCell::new(1),
487 polonius_output: None,
488 move_errors: Vec::new(),
489 diags_buffer,
490 polonius_diagnostics: polonius_diagnostics.as_ref(),
491 };
492 struct MoveVisitor<'a, 'b, 'infcx, 'tcx> {
493 ctxt: &'a mut MirBorrowckCtxt<'b, 'infcx, 'tcx>,
494 }
495
496 impl<'tcx> Visitor<'tcx> for MoveVisitor<'_, '_, '_, 'tcx> {
497 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
498 if let Operand::Move(place) = operand {
499 self.ctxt.check_movable_place(location, *place);
500 }
501 }
502 }
503 MoveVisitor { ctxt: &mut promoted_mbcx }.visit_body(promoted_body);
504 promoted_mbcx.report_move_errors();
505 }
506
507 let mut mbcx = MirBorrowckCtxt {
508 root_cx,
509 infcx: &infcx,
510 body,
511 move_data: &move_data,
512 location_table: &location_table,
513 movable_coroutine,
514 fn_self_span_reported: Default::default(),
515 access_place_error_reported: Default::default(),
516 reservation_error_reported: Default::default(),
517 uninitialized_error_reported: Default::default(),
518 regioncx: ®ioncx,
519 used_mut: Default::default(),
520 used_mut_upvars: SmallVec::new(),
521 borrow_set: &borrow_set,
522 upvars: tcx.closure_captures(def),
523 local_names: OnceCell::new(),
524 region_names: RefCell::default(),
525 next_region_name: RefCell::new(1),
526 move_errors: Vec::new(),
527 diags_buffer,
528 polonius_output: polonius_output.as_deref(),
529 polonius_diagnostics: polonius_diagnostics.as_ref(),
530 };
531
532 if nll_errors.is_empty() {
534 mbcx.report_opaque_type_errors(deferred_opaque_type_errors);
535 } else {
536 mbcx.report_region_errors(nll_errors);
537 }
538
539 let flow_results = get_flow_results(tcx, body, &move_data, &borrow_set, ®ioncx);
540 visit_results(
541 body,
542 traversal::reverse_postorder(body).map(|(bb, _)| bb),
543 &flow_results,
544 &mut mbcx,
545 );
546
547 mbcx.report_move_errors();
548
549 let temporary_used_locals: FxIndexSet<Local> = mbcx
555 .used_mut
556 .iter()
557 .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
558 .cloned()
559 .collect();
560 let unused_mut_locals =
564 mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
565 mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
566
567 debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
568 mbcx.lint_unused_mut();
569 if let Some(guar) = mbcx.emit_errors() {
570 mbcx.root_cx.set_tainted_by_errors(guar);
571 }
572
573 let result = PropagatedBorrowCheckResults {
574 closure_requirements: opt_closure_req,
575 used_mut_upvars: mbcx.used_mut_upvars,
576 };
577
578 if let Some(consumer) = &mut root_cx.consumer {
579 consumer.insert_body(
580 def,
581 BodyWithBorrowckFacts {
582 body: body_owned,
583 promoted,
584 borrow_set,
585 region_inference_context: regioncx,
586 location_table: polonius_input.as_ref().map(|_| location_table),
587 input_facts: polonius_input,
588 output_facts: polonius_output,
589 },
590 );
591 }
592
593 debug!("do_mir_borrowck: result = {:#?}", result);
594
595 result
596}
597
598fn get_flow_results<'a, 'tcx>(
599 tcx: TyCtxt<'tcx>,
600 body: &'a Body<'tcx>,
601 move_data: &'a MoveData<'tcx>,
602 borrow_set: &'a BorrowSet<'tcx>,
603 regioncx: &RegionInferenceContext<'tcx>,
604) -> Results<'tcx, Borrowck<'a, 'tcx>> {
605 let borrows = Borrows::new(tcx, body, regioncx, borrow_set).iterate_to_fixpoint(
608 tcx,
609 body,
610 Some("borrowck"),
611 );
612 let uninits = MaybeUninitializedPlaces::new(tcx, body, move_data).iterate_to_fixpoint(
613 tcx,
614 body,
615 Some("borrowck"),
616 );
617 let ever_inits = EverInitializedPlaces::new(body, move_data).iterate_to_fixpoint(
618 tcx,
619 body,
620 Some("borrowck"),
621 );
622
623 let analysis = Borrowck {
624 borrows: borrows.analysis,
625 uninits: uninits.analysis,
626 ever_inits: ever_inits.analysis,
627 };
628
629 assert_eq!(borrows.entry_states.len(), uninits.entry_states.len());
630 assert_eq!(borrows.entry_states.len(), ever_inits.entry_states.len());
631 let entry_states: EntryStates<_> =
632 itertools::izip!(borrows.entry_states, uninits.entry_states, ever_inits.entry_states)
633 .map(|(borrows, uninits, ever_inits)| BorrowckDomain { borrows, uninits, ever_inits })
634 .collect();
635
636 Results { analysis, entry_states }
637}
638
639pub(crate) struct BorrowckInferCtxt<'tcx> {
640 pub(crate) infcx: InferCtxt<'tcx>,
641 pub(crate) root_def_id: LocalDefId,
642 pub(crate) param_env: ParamEnv<'tcx>,
643 pub(crate) reg_var_to_origin: RefCell<FxIndexMap<ty::RegionVid, RegionCtxt>>,
644}
645
646impl<'tcx> BorrowckInferCtxt<'tcx> {
647 pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId, root_def_id: LocalDefId) -> Self {
648 let typing_mode = if tcx.use_typing_mode_borrowck() {
649 TypingMode::borrowck(tcx, def_id)
650 } else {
651 TypingMode::analysis_in_body(tcx, def_id)
652 };
653 let infcx = tcx.infer_ctxt().build(typing_mode);
654 let param_env = tcx.param_env(def_id);
655 BorrowckInferCtxt {
656 infcx,
657 root_def_id,
658 reg_var_to_origin: RefCell::new(Default::default()),
659 param_env,
660 }
661 }
662
663 pub(crate) fn next_region_var<F>(
664 &self,
665 origin: RegionVariableOrigin<'tcx>,
666 get_ctxt_fn: F,
667 ) -> ty::Region<'tcx>
668 where
669 F: Fn() -> RegionCtxt,
670 {
671 let next_region = self.infcx.next_region_var(origin);
672 let vid = next_region.as_var();
673
674 if cfg!(debug_assertions) {
675 debug!("inserting vid {:?} with origin {:?} into var_to_origin", vid, origin);
676 let ctxt = get_ctxt_fn();
677 let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
678 assert_eq!(var_to_origin.insert(vid, ctxt), None);
679 }
680
681 next_region
682 }
683
684 #[instrument(skip(self, get_ctxt_fn), level = "debug")]
685 pub(crate) fn next_nll_region_var<F>(
686 &self,
687 origin: NllRegionVariableOrigin<'tcx>,
688 get_ctxt_fn: F,
689 ) -> ty::Region<'tcx>
690 where
691 F: Fn() -> RegionCtxt,
692 {
693 let next_region = self.infcx.next_nll_region_var(origin);
694 let vid = next_region.as_var();
695
696 if cfg!(debug_assertions) {
697 debug!("inserting vid {:?} with origin {:?} into var_to_origin", vid, origin);
698 let ctxt = get_ctxt_fn();
699 let mut var_to_origin = self.reg_var_to_origin.borrow_mut();
700 assert_eq!(var_to_origin.insert(vid, ctxt), None);
701 }
702
703 next_region
704 }
705}
706
707impl<'tcx> Deref for BorrowckInferCtxt<'tcx> {
708 type Target = InferCtxt<'tcx>;
709
710 fn deref(&self) -> &Self::Target {
711 &self.infcx
712 }
713}
714
715struct MirBorrowckCtxt<'a, 'infcx, 'tcx> {
716 root_cx: &'a mut BorrowCheckRootCtxt<'tcx>,
717 infcx: &'infcx BorrowckInferCtxt<'tcx>,
718 body: &'a Body<'tcx>,
719 move_data: &'a MoveData<'tcx>,
720
721 location_table: &'a PoloniusLocationTable,
724
725 movable_coroutine: bool,
726 access_place_error_reported: FxIndexSet<(Place<'tcx>, Span)>,
732 reservation_error_reported: FxIndexSet<Place<'tcx>>,
740 fn_self_span_reported: FxIndexSet<Span>,
744 uninitialized_error_reported: FxIndexSet<Local>,
747 used_mut: FxIndexSet<Local>,
750 used_mut_upvars: SmallVec<[FieldIdx; 8]>,
753 regioncx: &'a RegionInferenceContext<'tcx>,
756
757 borrow_set: &'a BorrowSet<'tcx>,
759
760 upvars: &'tcx [&'tcx ty::CapturedPlace<'tcx>],
762
763 local_names: OnceCell<IndexVec<Local, Option<Symbol>>>,
765
766 region_names: RefCell<FxIndexMap<RegionVid, RegionName>>,
769
770 next_region_name: RefCell<usize>,
772
773 diags_buffer: &'a mut BorrowckDiagnosticsBuffer<'infcx, 'tcx>,
774 move_errors: Vec<MoveError<'tcx>>,
775
776 polonius_output: Option<&'a PoloniusOutput>,
778 polonius_diagnostics: Option<&'a PoloniusDiagnosticsContext>,
780}
781
782impl<'a, 'tcx> ResultsVisitor<'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<'a, '_, 'tcx> {
788 fn visit_after_early_statement_effect(
789 &mut self,
790 _analysis: &Borrowck<'a, 'tcx>,
791 state: &BorrowckDomain,
792 stmt: &Statement<'tcx>,
793 location: Location,
794 ) {
795 debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, state);
796 let span = stmt.source_info.span;
797
798 self.check_activations(location, span, state);
799
800 match &stmt.kind {
801 StatementKind::Assign(box (lhs, rhs)) => {
802 self.consume_rvalue(location, (rhs, span), state);
803
804 self.mutate_place(location, (*lhs, span), Shallow(None), state);
805 }
806 StatementKind::FakeRead(box (_, place)) => {
807 self.check_if_path_or_subpath_is_moved(
818 location,
819 InitializationRequiringAction::Use,
820 (place.as_ref(), span),
821 state,
822 );
823 }
824 StatementKind::Intrinsic(box kind) => match kind {
825 NonDivergingIntrinsic::Assume(op) => {
826 self.consume_operand(location, (op, span), state);
827 }
828 NonDivergingIntrinsic::CopyNonOverlapping(..) => span_bug!(
829 span,
830 "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
831 )
832 }
833 StatementKind::AscribeUserType(..)
835 | StatementKind::PlaceMention(..)
837 | StatementKind::Coverage(..)
839 | StatementKind::ConstEvalCounter
841 | StatementKind::StorageLive(..) => {}
842 StatementKind::BackwardIncompatibleDropHint { place, reason: BackwardIncompatibleDropReason::Edition2024 } => {
844 self.check_backward_incompatible_drop(location, **place, state);
845 }
846 StatementKind::StorageDead(local) => {
847 self.access_place(
848 location,
849 (Place::from(*local), span),
850 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
851 LocalMutationIsAllowed::Yes,
852 state,
853 );
854 }
855 StatementKind::Nop
856 | StatementKind::Retag { .. }
857 | StatementKind::SetDiscriminant { .. } => {
858 bug!("Statement not allowed in this MIR phase")
859 }
860 }
861 }
862
863 fn visit_after_early_terminator_effect(
864 &mut self,
865 _analysis: &Borrowck<'a, 'tcx>,
866 state: &BorrowckDomain,
867 term: &Terminator<'tcx>,
868 loc: Location,
869 ) {
870 debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, state);
871 let span = term.source_info.span;
872
873 self.check_activations(loc, span, state);
874
875 match &term.kind {
876 TerminatorKind::SwitchInt { discr, targets: _ } => {
877 self.consume_operand(loc, (discr, span), state);
878 }
879 TerminatorKind::Drop {
880 place,
881 target: _,
882 unwind: _,
883 replace,
884 drop: _,
885 async_fut: _,
886 } => {
887 debug!(
888 "visit_terminator_drop \
889 loc: {:?} term: {:?} place: {:?} span: {:?}",
890 loc, term, place, span
891 );
892
893 let write_kind =
894 if *replace { WriteKind::Replace } else { WriteKind::StorageDeadOrDrop };
895 self.access_place(
896 loc,
897 (*place, span),
898 (AccessDepth::Drop, Write(write_kind)),
899 LocalMutationIsAllowed::Yes,
900 state,
901 );
902 }
903 TerminatorKind::Call {
904 func,
905 args,
906 destination,
907 target: _,
908 unwind: _,
909 call_source: _,
910 fn_span: _,
911 } => {
912 self.consume_operand(loc, (func, span), state);
913 for arg in args {
914 self.consume_operand(loc, (&arg.node, arg.span), state);
915 }
916 self.mutate_place(loc, (*destination, span), Deep, state);
917 }
918 TerminatorKind::TailCall { func, args, fn_span: _ } => {
919 self.consume_operand(loc, (func, span), state);
920 for arg in args {
921 self.consume_operand(loc, (&arg.node, arg.span), state);
922 }
923 }
924 TerminatorKind::Assert { cond, expected: _, msg, target: _, unwind: _ } => {
925 self.consume_operand(loc, (cond, span), state);
926 if let AssertKind::BoundsCheck { len, index } = &**msg {
927 self.consume_operand(loc, (len, span), state);
928 self.consume_operand(loc, (index, span), state);
929 }
930 }
931
932 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
933 self.consume_operand(loc, (value, span), state);
934 self.mutate_place(loc, (*resume_arg, span), Deep, state);
935 }
936
937 TerminatorKind::InlineAsm {
938 asm_macro: _,
939 template: _,
940 operands,
941 options: _,
942 line_spans: _,
943 targets: _,
944 unwind: _,
945 } => {
946 for op in operands {
947 match op {
948 InlineAsmOperand::In { reg: _, value } => {
949 self.consume_operand(loc, (value, span), state);
950 }
951 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
952 if let Some(place) = place {
953 self.mutate_place(loc, (*place, span), Shallow(None), state);
954 }
955 }
956 InlineAsmOperand::InOut { reg: _, late: _, in_value, out_place } => {
957 self.consume_operand(loc, (in_value, span), state);
958 if let &Some(out_place) = out_place {
959 self.mutate_place(loc, (out_place, span), Shallow(None), state);
960 }
961 }
962 InlineAsmOperand::Const { value: _ }
963 | InlineAsmOperand::SymFn { value: _ }
964 | InlineAsmOperand::SymStatic { def_id: _ }
965 | InlineAsmOperand::Label { target_index: _ } => {}
966 }
967 }
968 }
969
970 TerminatorKind::Goto { target: _ }
971 | TerminatorKind::UnwindTerminate(_)
972 | TerminatorKind::Unreachable
973 | TerminatorKind::UnwindResume
974 | TerminatorKind::Return
975 | TerminatorKind::CoroutineDrop
976 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
977 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
978 }
980 }
981 }
982
983 fn visit_after_primary_terminator_effect(
984 &mut self,
985 _analysis: &Borrowck<'a, 'tcx>,
986 state: &BorrowckDomain,
987 term: &Terminator<'tcx>,
988 loc: Location,
989 ) {
990 let span = term.source_info.span;
991
992 match term.kind {
993 TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
994 if self.movable_coroutine {
995 for i in state.borrows.iter() {
997 let borrow = &self.borrow_set[i];
998 self.check_for_local_borrow(borrow, span);
999 }
1000 }
1001 }
1002
1003 TerminatorKind::UnwindResume
1004 | TerminatorKind::Return
1005 | TerminatorKind::TailCall { .. }
1006 | TerminatorKind::CoroutineDrop => {
1007 match self.borrow_set.locals_state_at_exit() {
1008 LocalsStateAtExit::AllAreInvalidated => {
1009 for i in state.borrows.iter() {
1014 let borrow = &self.borrow_set[i];
1015 self.check_for_invalidation_at_exit(loc, borrow, span);
1016 }
1017 }
1018 LocalsStateAtExit::SomeAreInvalidated { has_storage_dead_or_moved: _ } => {}
1021 }
1022 }
1023
1024 TerminatorKind::UnwindTerminate(_)
1025 | TerminatorKind::Assert { .. }
1026 | TerminatorKind::Call { .. }
1027 | TerminatorKind::Drop { .. }
1028 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
1029 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
1030 | TerminatorKind::Goto { .. }
1031 | TerminatorKind::SwitchInt { .. }
1032 | TerminatorKind::Unreachable
1033 | TerminatorKind::InlineAsm { .. } => {}
1034 }
1035 }
1036}
1037
1038use self::AccessDepth::{Deep, Shallow};
1039use self::ReadOrWrite::{Activation, Read, Reservation, Write};
1040
1041#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1042enum ArtificialField {
1043 ArrayLength,
1044 FakeBorrow,
1045}
1046
1047#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1048enum AccessDepth {
1049 Shallow(Option<ArtificialField>),
1055
1056 Deep,
1060
1061 Drop,
1064}
1065
1066#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1069enum ReadOrWrite {
1070 Read(ReadKind),
1073
1074 Write(WriteKind),
1078
1079 Reservation(WriteKind),
1083 Activation(WriteKind, BorrowIndex),
1084}
1085
1086#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1089enum ReadKind {
1090 Borrow(BorrowKind),
1091 Copy,
1092}
1093
1094#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1097enum WriteKind {
1098 StorageDeadOrDrop,
1099 Replace,
1100 MutableBorrow(BorrowKind),
1101 Mutate,
1102 Move,
1103}
1104
1105#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1113enum LocalMutationIsAllowed {
1114 Yes,
1115 ExceptUpvars,
1118 No,
1119}
1120
1121#[derive(Copy, Clone, Debug)]
1122enum InitializationRequiringAction {
1123 Borrow,
1124 MatchOn,
1125 Use,
1126 Assignment,
1127 PartialAssignment,
1128}
1129
1130#[derive(Debug)]
1131struct RootPlace<'tcx> {
1132 place_local: Local,
1133 place_projection: &'tcx [PlaceElem<'tcx>],
1134 is_local_mutation_allowed: LocalMutationIsAllowed,
1135}
1136
1137impl InitializationRequiringAction {
1138 fn as_noun(self) -> &'static str {
1139 match self {
1140 InitializationRequiringAction::Borrow => "borrow",
1141 InitializationRequiringAction::MatchOn => "use", InitializationRequiringAction::Use => "use",
1143 InitializationRequiringAction::Assignment => "assign",
1144 InitializationRequiringAction::PartialAssignment => "assign to part",
1145 }
1146 }
1147
1148 fn as_verb_in_past_tense(self) -> &'static str {
1149 match self {
1150 InitializationRequiringAction::Borrow => "borrowed",
1151 InitializationRequiringAction::MatchOn => "matched on",
1152 InitializationRequiringAction::Use => "used",
1153 InitializationRequiringAction::Assignment => "assigned",
1154 InitializationRequiringAction::PartialAssignment => "partially assigned",
1155 }
1156 }
1157
1158 fn as_general_verb_in_past_tense(self) -> &'static str {
1159 match self {
1160 InitializationRequiringAction::Borrow
1161 | InitializationRequiringAction::MatchOn
1162 | InitializationRequiringAction::Use => "used",
1163 InitializationRequiringAction::Assignment => "assigned",
1164 InitializationRequiringAction::PartialAssignment => "partially assigned",
1165 }
1166 }
1167}
1168
1169impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
1170 fn body(&self) -> &'a Body<'tcx> {
1171 self.body
1172 }
1173
1174 fn access_place(
1181 &mut self,
1182 location: Location,
1183 place_span: (Place<'tcx>, Span),
1184 kind: (AccessDepth, ReadOrWrite),
1185 is_local_mutation_allowed: LocalMutationIsAllowed,
1186 state: &BorrowckDomain,
1187 ) {
1188 let (sd, rw) = kind;
1189
1190 if let Activation(_, borrow_index) = rw {
1191 if self.reservation_error_reported.contains(&place_span.0) {
1192 debug!(
1193 "skipping access_place for activation of invalid reservation \
1194 place: {:?} borrow_index: {:?}",
1195 place_span.0, borrow_index
1196 );
1197 return;
1198 }
1199 }
1200
1201 if !self.access_place_error_reported.is_empty()
1204 && self.access_place_error_reported.contains(&(place_span.0, place_span.1))
1205 {
1206 debug!(
1207 "access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
1208 place_span, kind
1209 );
1210 return;
1211 }
1212
1213 let mutability_error = self.check_access_permissions(
1214 place_span,
1215 rw,
1216 is_local_mutation_allowed,
1217 state,
1218 location,
1219 );
1220 let conflict_error = self.check_access_for_conflict(location, place_span, sd, rw, state);
1221
1222 if conflict_error || mutability_error {
1223 debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
1224 self.access_place_error_reported.insert((place_span.0, place_span.1));
1225 }
1226 }
1227
1228 fn borrows_in_scope<'s>(
1229 &self,
1230 location: Location,
1231 state: &'s BorrowckDomain,
1232 ) -> Cow<'s, MixedBitSet<BorrowIndex>> {
1233 if let Some(polonius) = &self.polonius_output {
1234 let location = self.location_table.start_index(location);
1236 let mut polonius_output = MixedBitSet::new_empty(self.borrow_set.len());
1237 for &idx in polonius.errors_at(location) {
1238 polonius_output.insert(idx);
1239 }
1240 Cow::Owned(polonius_output)
1241 } else {
1242 Cow::Borrowed(&state.borrows)
1243 }
1244 }
1245
1246 #[instrument(level = "debug", skip(self, state))]
1247 fn check_access_for_conflict(
1248 &mut self,
1249 location: Location,
1250 place_span: (Place<'tcx>, Span),
1251 sd: AccessDepth,
1252 rw: ReadOrWrite,
1253 state: &BorrowckDomain,
1254 ) -> bool {
1255 let mut error_reported = false;
1256
1257 let borrows_in_scope = self.borrows_in_scope(location, state);
1258
1259 each_borrow_involving_path(
1260 self,
1261 self.infcx.tcx,
1262 self.body,
1263 (sd, place_span.0),
1264 self.borrow_set,
1265 |borrow_index| borrows_in_scope.contains(borrow_index),
1266 |this, borrow_index, borrow| match (rw, borrow.kind) {
1267 (Activation(_, activating), _) if activating == borrow_index => {
1274 debug!(
1275 "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
1276 skipping {:?} b/c activation of same borrow_index",
1277 place_span,
1278 sd,
1279 rw,
1280 (borrow_index, borrow),
1281 );
1282 ControlFlow::Continue(())
1283 }
1284
1285 (Read(_), BorrowKind::Shared | BorrowKind::Fake(_))
1286 | (
1287 Read(ReadKind::Borrow(BorrowKind::Fake(FakeBorrowKind::Shallow))),
1288 BorrowKind::Mut { .. },
1289 ) => ControlFlow::Continue(()),
1290
1291 (Reservation(_), BorrowKind::Fake(_) | BorrowKind::Shared) => {
1292 ControlFlow::Continue(())
1295 }
1296
1297 (Write(WriteKind::Move), BorrowKind::Fake(FakeBorrowKind::Shallow)) => {
1298 ControlFlow::Continue(())
1300 }
1301
1302 (Read(kind), BorrowKind::Mut { .. }) => {
1303 if !is_active(this.dominators(), borrow, location) {
1305 assert!(borrow.kind.allows_two_phase_borrow());
1306 return ControlFlow::Continue(());
1307 }
1308
1309 error_reported = true;
1310 match kind {
1311 ReadKind::Copy => {
1312 let err = this
1313 .report_use_while_mutably_borrowed(location, place_span, borrow);
1314 this.buffer_error(err);
1315 }
1316 ReadKind::Borrow(bk) => {
1317 let err =
1318 this.report_conflicting_borrow(location, place_span, bk, borrow);
1319 this.buffer_error(err);
1320 }
1321 }
1322 ControlFlow::Break(())
1323 }
1324
1325 (Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
1326 match rw {
1327 Reservation(..) => {
1328 debug!(
1329 "recording invalid reservation of \
1330 place: {:?}",
1331 place_span.0
1332 );
1333 this.reservation_error_reported.insert(place_span.0);
1334 }
1335 Activation(_, activating) => {
1336 debug!(
1337 "observing check_place for activation of \
1338 borrow_index: {:?}",
1339 activating
1340 );
1341 }
1342 Read(..) | Write(..) => {}
1343 }
1344
1345 error_reported = true;
1346 match kind {
1347 WriteKind::MutableBorrow(bk) => {
1348 let err =
1349 this.report_conflicting_borrow(location, place_span, bk, borrow);
1350 this.buffer_error(err);
1351 }
1352 WriteKind::StorageDeadOrDrop => this
1353 .report_borrowed_value_does_not_live_long_enough(
1354 location,
1355 borrow,
1356 place_span,
1357 Some(WriteKind::StorageDeadOrDrop),
1358 ),
1359 WriteKind::Mutate => {
1360 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1361 }
1362 WriteKind::Move => {
1363 this.report_move_out_while_borrowed(location, place_span, borrow)
1364 }
1365 WriteKind::Replace => {
1366 this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
1367 }
1368 }
1369 ControlFlow::Break(())
1370 }
1371 },
1372 );
1373
1374 error_reported
1375 }
1376
1377 #[instrument(level = "debug", skip(self, state))]
1380 fn check_backward_incompatible_drop(
1381 &mut self,
1382 location: Location,
1383 place: Place<'tcx>,
1384 state: &BorrowckDomain,
1385 ) {
1386 let tcx = self.infcx.tcx;
1387 let sd = if place.ty(self.body, tcx).ty.needs_drop(tcx, self.body.typing_env(tcx)) {
1391 AccessDepth::Drop
1392 } else {
1393 AccessDepth::Shallow(None)
1394 };
1395
1396 let borrows_in_scope = self.borrows_in_scope(location, state);
1397
1398 each_borrow_involving_path(
1401 self,
1402 self.infcx.tcx,
1403 self.body,
1404 (sd, place),
1405 self.borrow_set,
1406 |borrow_index| borrows_in_scope.contains(borrow_index),
1407 |this, _borrow_index, borrow| {
1408 if matches!(borrow.kind, BorrowKind::Fake(_)) {
1409 return ControlFlow::Continue(());
1410 }
1411 let borrowed = this.retrieve_borrow_spans(borrow).var_or_use_path_span();
1412 let explain = this.explain_why_borrow_contains_point(
1413 location,
1414 borrow,
1415 Some((WriteKind::StorageDeadOrDrop, place)),
1416 );
1417 this.infcx.tcx.node_span_lint(
1418 TAIL_EXPR_DROP_ORDER,
1419 CRATE_HIR_ID,
1420 borrowed,
1421 |diag| {
1422 session_diagnostics::TailExprDropOrder { borrowed }.decorate_lint(diag);
1423 explain.add_explanation_to_diagnostic(&this, diag, "", None, None);
1424 },
1425 );
1426 ControlFlow::Break(())
1428 },
1429 );
1430 }
1431
1432 fn mutate_place(
1433 &mut self,
1434 location: Location,
1435 place_span: (Place<'tcx>, Span),
1436 kind: AccessDepth,
1437 state: &BorrowckDomain,
1438 ) {
1439 self.check_if_assigned_path_is_moved(location, place_span, state);
1441
1442 self.access_place(
1443 location,
1444 place_span,
1445 (kind, Write(WriteKind::Mutate)),
1446 LocalMutationIsAllowed::No,
1447 state,
1448 );
1449 }
1450
1451 fn consume_rvalue(
1452 &mut self,
1453 location: Location,
1454 (rvalue, span): (&Rvalue<'tcx>, Span),
1455 state: &BorrowckDomain,
1456 ) {
1457 match rvalue {
1458 &Rvalue::Ref(_ , bk, place) => {
1459 let access_kind = match bk {
1460 BorrowKind::Fake(FakeBorrowKind::Shallow) => {
1461 (Shallow(Some(ArtificialField::FakeBorrow)), Read(ReadKind::Borrow(bk)))
1462 }
1463 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep) => {
1464 (Deep, Read(ReadKind::Borrow(bk)))
1465 }
1466 BorrowKind::Mut { .. } => {
1467 let wk = WriteKind::MutableBorrow(bk);
1468 if bk.allows_two_phase_borrow() {
1469 (Deep, Reservation(wk))
1470 } else {
1471 (Deep, Write(wk))
1472 }
1473 }
1474 };
1475
1476 self.access_place(
1477 location,
1478 (place, span),
1479 access_kind,
1480 LocalMutationIsAllowed::No,
1481 state,
1482 );
1483
1484 let action = if bk == BorrowKind::Fake(FakeBorrowKind::Shallow) {
1485 InitializationRequiringAction::MatchOn
1486 } else {
1487 InitializationRequiringAction::Borrow
1488 };
1489
1490 self.check_if_path_or_subpath_is_moved(
1491 location,
1492 action,
1493 (place.as_ref(), span),
1494 state,
1495 );
1496 }
1497
1498 &Rvalue::RawPtr(kind, place) => {
1499 let access_kind = match kind {
1500 RawPtrKind::Mut => (
1501 Deep,
1502 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
1503 kind: MutBorrowKind::Default,
1504 })),
1505 ),
1506 RawPtrKind::Const => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
1507 RawPtrKind::FakeForPtrMetadata => {
1508 (Shallow(Some(ArtificialField::ArrayLength)), Read(ReadKind::Copy))
1509 }
1510 };
1511
1512 self.access_place(
1513 location,
1514 (place, span),
1515 access_kind,
1516 LocalMutationIsAllowed::No,
1517 state,
1518 );
1519
1520 self.check_if_path_or_subpath_is_moved(
1521 location,
1522 InitializationRequiringAction::Borrow,
1523 (place.as_ref(), span),
1524 state,
1525 );
1526 }
1527
1528 Rvalue::ThreadLocalRef(_) => {}
1529
1530 Rvalue::Use(operand)
1531 | Rvalue::Repeat(operand, _)
1532 | Rvalue::UnaryOp(_ , operand)
1533 | Rvalue::Cast(_ , operand, _ )
1534 | Rvalue::ShallowInitBox(operand, _ ) => {
1535 self.consume_operand(location, (operand, span), state)
1536 }
1537
1538 &Rvalue::Discriminant(place) => {
1539 let af = match *rvalue {
1540 Rvalue::Discriminant(..) => None,
1541 _ => unreachable!(),
1542 };
1543 self.access_place(
1544 location,
1545 (place, span),
1546 (Shallow(af), Read(ReadKind::Copy)),
1547 LocalMutationIsAllowed::No,
1548 state,
1549 );
1550 self.check_if_path_or_subpath_is_moved(
1551 location,
1552 InitializationRequiringAction::Use,
1553 (place.as_ref(), span),
1554 state,
1555 );
1556 }
1557
1558 Rvalue::BinaryOp(_bin_op, box (operand1, operand2)) => {
1559 self.consume_operand(location, (operand1, span), state);
1560 self.consume_operand(location, (operand2, span), state);
1561 }
1562
1563 Rvalue::NullaryOp(_op) => {
1564 }
1566
1567 Rvalue::Aggregate(aggregate_kind, operands) => {
1568 match **aggregate_kind {
1572 AggregateKind::Closure(def_id, _)
1573 | AggregateKind::CoroutineClosure(def_id, _)
1574 | AggregateKind::Coroutine(def_id, _) => {
1575 let def_id = def_id.expect_local();
1576 let used_mut_upvars = self.root_cx.used_mut_upvars(def_id);
1577 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
1578 for field in used_mut_upvars.clone() {
1582 self.propagate_closure_used_mut_upvar(&operands[field]);
1583 }
1584 }
1585 AggregateKind::Adt(..)
1586 | AggregateKind::Array(..)
1587 | AggregateKind::Tuple { .. }
1588 | AggregateKind::RawPtr(..) => (),
1589 }
1590
1591 for operand in operands {
1592 self.consume_operand(location, (operand, span), state);
1593 }
1594 }
1595
1596 Rvalue::WrapUnsafeBinder(op, _) => {
1597 self.consume_operand(location, (op, span), state);
1598 }
1599
1600 Rvalue::CopyForDeref(_) => bug!("`CopyForDeref` in borrowck"),
1601 }
1602 }
1603
1604 fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
1605 let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
1606 if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
1614 this.used_mut_upvars.push(field);
1615 return;
1616 }
1617
1618 for (place_ref, proj) in place.iter_projections().rev() {
1619 if proj == ProjectionElem::Deref {
1621 match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
1622 ty::Ref(_, _, hir::Mutability::Mut) => return,
1624
1625 _ => {}
1626 }
1627 }
1628
1629 if let Some(field) = this.is_upvar_field_projection(place_ref) {
1631 this.used_mut_upvars.push(field);
1632 return;
1633 }
1634 }
1635
1636 this.used_mut.insert(place.local);
1638 };
1639
1640 match *operand {
1644 Operand::Move(place) | Operand::Copy(place) => {
1645 match place.as_local() {
1646 Some(local) if !self.body.local_decls[local].is_user_variable() => {
1647 if self.body.local_decls[local].ty.is_mutable_ptr() {
1648 return;
1650 }
1651 let Some(temp_mpi) = self.move_data.rev_lookup.find_local(local) else {
1667 bug!("temporary should be tracked");
1668 };
1669 let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
1670 &self.move_data.inits[init_index]
1671 } else {
1672 bug!("temporary should be initialized exactly once")
1673 };
1674
1675 let InitLocation::Statement(loc) = init.location else {
1676 bug!("temporary initialized in arguments")
1677 };
1678
1679 let body = self.body;
1680 let bbd = &body[loc.block];
1681 let stmt = &bbd.statements[loc.statement_index];
1682 debug!("temporary assigned in: stmt={:?}", stmt);
1683
1684 match stmt.kind {
1685 StatementKind::Assign(box (
1686 _,
1687 Rvalue::Ref(_, _, source)
1688 | Rvalue::Use(Operand::Copy(source) | Operand::Move(source)),
1689 )) => {
1690 propagate_closure_used_mut_place(self, source);
1691 }
1692 _ => {
1693 bug!(
1694 "closures should only capture user variables \
1695 or references to user variables"
1696 );
1697 }
1698 }
1699 }
1700 _ => propagate_closure_used_mut_place(self, place),
1701 }
1702 }
1703 Operand::Constant(..) => {}
1704 }
1705 }
1706
1707 fn consume_operand(
1708 &mut self,
1709 location: Location,
1710 (operand, span): (&Operand<'tcx>, Span),
1711 state: &BorrowckDomain,
1712 ) {
1713 match *operand {
1714 Operand::Copy(place) => {
1715 self.access_place(
1718 location,
1719 (place, span),
1720 (Deep, Read(ReadKind::Copy)),
1721 LocalMutationIsAllowed::No,
1722 state,
1723 );
1724
1725 self.check_if_path_or_subpath_is_moved(
1727 location,
1728 InitializationRequiringAction::Use,
1729 (place.as_ref(), span),
1730 state,
1731 );
1732 }
1733 Operand::Move(place) => {
1734 self.check_movable_place(location, place);
1736
1737 self.access_place(
1739 location,
1740 (place, span),
1741 (Deep, Write(WriteKind::Move)),
1742 LocalMutationIsAllowed::Yes,
1743 state,
1744 );
1745
1746 self.check_if_path_or_subpath_is_moved(
1748 location,
1749 InitializationRequiringAction::Use,
1750 (place.as_ref(), span),
1751 state,
1752 );
1753 }
1754 Operand::Constant(_) => {}
1755 }
1756 }
1757
1758 #[instrument(level = "debug", skip(self))]
1761 fn check_for_invalidation_at_exit(
1762 &mut self,
1763 location: Location,
1764 borrow: &BorrowData<'tcx>,
1765 span: Span,
1766 ) {
1767 let place = borrow.borrowed_place;
1768 let mut root_place = PlaceRef { local: place.local, projection: &[] };
1769
1770 let might_be_alive = if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
1776 root_place.projection = TyCtxtConsts::DEREF_PROJECTION;
1780 true
1781 } else {
1782 false
1783 };
1784
1785 let sd = if might_be_alive { Deep } else { Shallow(None) };
1786
1787 if places_conflict::borrow_conflicts_with_place(
1788 self.infcx.tcx,
1789 self.body,
1790 place,
1791 borrow.kind,
1792 root_place,
1793 sd,
1794 places_conflict::PlaceConflictBias::Overlap,
1795 ) {
1796 debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
1797 let span = self.infcx.tcx.sess.source_map().end_point(span);
1800 self.report_borrowed_value_does_not_live_long_enough(
1801 location,
1802 borrow,
1803 (place, span),
1804 None,
1805 )
1806 }
1807 }
1808
1809 fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
1812 debug!("check_for_local_borrow({:?})", borrow);
1813
1814 if borrow_of_local_data(borrow.borrowed_place) {
1815 let err = self.cannot_borrow_across_coroutine_yield(
1816 self.retrieve_borrow_spans(borrow).var_or_use(),
1817 yield_span,
1818 );
1819
1820 self.buffer_error(err);
1821 }
1822 }
1823
1824 fn check_activations(&mut self, location: Location, span: Span, state: &BorrowckDomain) {
1825 for &borrow_index in self.borrow_set.activations_at_location(location) {
1829 let borrow = &self.borrow_set[borrow_index];
1830
1831 assert!(match borrow.kind {
1833 BorrowKind::Shared | BorrowKind::Fake(_) => false,
1834 BorrowKind::Mut { .. } => true,
1835 });
1836
1837 self.access_place(
1838 location,
1839 (borrow.borrowed_place, span),
1840 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
1841 LocalMutationIsAllowed::No,
1842 state,
1843 );
1844 }
1848 }
1849
1850 fn check_movable_place(&mut self, location: Location, place: Place<'tcx>) {
1851 use IllegalMoveOriginKind::*;
1852
1853 let body = self.body;
1854 let tcx = self.infcx.tcx;
1855 let mut place_ty = PlaceTy::from_ty(body.local_decls[place.local].ty);
1856 for (place_ref, elem) in place.iter_projections() {
1857 match elem {
1858 ProjectionElem::Deref => match place_ty.ty.kind() {
1859 ty::Ref(..) | ty::RawPtr(..) => {
1860 self.move_errors.push(MoveError::new(
1861 place,
1862 location,
1863 BorrowedContent {
1864 target_place: place_ref.project_deeper(&[elem], tcx),
1865 },
1866 ));
1867 return;
1868 }
1869 ty::Adt(adt, _) => {
1870 if !adt.is_box() {
1871 bug!("Adt should be a box type when Place is deref");
1872 }
1873 }
1874 ty::Bool
1875 | ty::Char
1876 | ty::Int(_)
1877 | ty::Uint(_)
1878 | ty::Float(_)
1879 | ty::Foreign(_)
1880 | ty::Str
1881 | ty::Array(_, _)
1882 | ty::Pat(_, _)
1883 | ty::Slice(_)
1884 | ty::FnDef(_, _)
1885 | ty::FnPtr(..)
1886 | ty::Dynamic(_, _)
1887 | ty::Closure(_, _)
1888 | ty::CoroutineClosure(_, _)
1889 | ty::Coroutine(_, _)
1890 | ty::CoroutineWitness(..)
1891 | ty::Never
1892 | ty::Tuple(_)
1893 | ty::UnsafeBinder(_)
1894 | ty::Alias(_, _)
1895 | ty::Param(_)
1896 | ty::Bound(_, _)
1897 | ty::Infer(_)
1898 | ty::Error(_)
1899 | ty::Placeholder(_) => {
1900 bug!("When Place is Deref it's type shouldn't be {place_ty:#?}")
1901 }
1902 },
1903 ProjectionElem::Field(_, _) => match place_ty.ty.kind() {
1904 ty::Adt(adt, _) => {
1905 if adt.has_dtor(tcx) {
1906 self.move_errors.push(MoveError::new(
1907 place,
1908 location,
1909 InteriorOfTypeWithDestructor { container_ty: place_ty.ty },
1910 ));
1911 return;
1912 }
1913 }
1914 ty::Closure(..)
1915 | ty::CoroutineClosure(..)
1916 | ty::Coroutine(_, _)
1917 | ty::Tuple(_) => (),
1918 ty::Bool
1919 | ty::Char
1920 | ty::Int(_)
1921 | ty::Uint(_)
1922 | ty::Float(_)
1923 | ty::Foreign(_)
1924 | ty::Str
1925 | ty::Array(_, _)
1926 | ty::Pat(_, _)
1927 | ty::Slice(_)
1928 | ty::RawPtr(_, _)
1929 | ty::Ref(_, _, _)
1930 | ty::FnDef(_, _)
1931 | ty::FnPtr(..)
1932 | ty::Dynamic(_, _)
1933 | ty::CoroutineWitness(..)
1934 | ty::Never
1935 | ty::UnsafeBinder(_)
1936 | ty::Alias(_, _)
1937 | ty::Param(_)
1938 | ty::Bound(_, _)
1939 | ty::Infer(_)
1940 | ty::Error(_)
1941 | ty::Placeholder(_) => bug!(
1942 "When Place contains ProjectionElem::Field it's type shouldn't be {place_ty:#?}"
1943 ),
1944 },
1945 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
1946 match place_ty.ty.kind() {
1947 ty::Slice(_) => {
1948 self.move_errors.push(MoveError::new(
1949 place,
1950 location,
1951 InteriorOfSliceOrArray { ty: place_ty.ty, is_index: false },
1952 ));
1953 return;
1954 }
1955 ty::Array(_, _) => (),
1956 _ => bug!("Unexpected type {:#?}", place_ty.ty),
1957 }
1958 }
1959 ProjectionElem::Index(_) => match place_ty.ty.kind() {
1960 ty::Array(..) | ty::Slice(..) => {
1961 self.move_errors.push(MoveError::new(
1962 place,
1963 location,
1964 InteriorOfSliceOrArray { ty: place_ty.ty, is_index: true },
1965 ));
1966 return;
1967 }
1968 _ => bug!("Unexpected type {place_ty:#?}"),
1969 },
1970 ProjectionElem::OpaqueCast(_)
1974 | ProjectionElem::Downcast(_, _)
1975 | ProjectionElem::UnwrapUnsafeBinder(_) => (),
1976 }
1977
1978 place_ty = place_ty.projection_ty(tcx, elem);
1979 }
1980 }
1981
1982 fn check_if_full_path_is_moved(
1983 &mut self,
1984 location: Location,
1985 desired_action: InitializationRequiringAction,
1986 place_span: (PlaceRef<'tcx>, Span),
1987 state: &BorrowckDomain,
1988 ) {
1989 let maybe_uninits = &state.uninits;
1990
1991 debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
2027 let (prefix, mpi) = self.move_path_closest_to(place_span.0);
2028 if maybe_uninits.contains(mpi) {
2029 self.report_use_of_moved_or_uninitialized(
2030 location,
2031 desired_action,
2032 (prefix, place_span.0, place_span.1),
2033 mpi,
2034 );
2035 } }
2042
2043 fn check_if_subslice_element_is_moved(
2049 &mut self,
2050 location: Location,
2051 desired_action: InitializationRequiringAction,
2052 place_span: (PlaceRef<'tcx>, Span),
2053 maybe_uninits: &MixedBitSet<MovePathIndex>,
2054 from: u64,
2055 to: u64,
2056 ) {
2057 if let Some(mpi) = self.move_path_for_place(place_span.0) {
2058 let move_paths = &self.move_data.move_paths;
2059
2060 let root_path = &move_paths[mpi];
2061 for (child_mpi, child_move_path) in root_path.children(move_paths) {
2062 let last_proj = child_move_path.place.projection.last().unwrap();
2063 if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
2064 debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
2065
2066 if (from..to).contains(offset) {
2067 let uninit_child =
2068 self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
2069 maybe_uninits.contains(mpi)
2070 });
2071
2072 if let Some(uninit_child) = uninit_child {
2073 self.report_use_of_moved_or_uninitialized(
2074 location,
2075 desired_action,
2076 (place_span.0, place_span.0, place_span.1),
2077 uninit_child,
2078 );
2079 return; }
2081 }
2082 }
2083 }
2084 }
2085 }
2086
2087 fn check_if_path_or_subpath_is_moved(
2088 &mut self,
2089 location: Location,
2090 desired_action: InitializationRequiringAction,
2091 place_span: (PlaceRef<'tcx>, Span),
2092 state: &BorrowckDomain,
2093 ) {
2094 let maybe_uninits = &state.uninits;
2095
2096 self.check_if_full_path_is_moved(location, desired_action, place_span, state);
2112
2113 if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
2114 place_span.0.last_projection()
2115 {
2116 let place_ty = place_base.ty(self.body(), self.infcx.tcx);
2117 if let ty::Array(..) = place_ty.ty.kind() {
2118 self.check_if_subslice_element_is_moved(
2119 location,
2120 desired_action,
2121 (place_base, place_span.1),
2122 maybe_uninits,
2123 from,
2124 to,
2125 );
2126 return;
2127 }
2128 }
2129
2130 debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
2140 if let Some(mpi) = self.move_path_for_place(place_span.0) {
2141 let uninit_mpi = self
2142 .move_data
2143 .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
2144
2145 if let Some(uninit_mpi) = uninit_mpi {
2146 self.report_use_of_moved_or_uninitialized(
2147 location,
2148 desired_action,
2149 (place_span.0, place_span.0, place_span.1),
2150 uninit_mpi,
2151 );
2152 return; }
2154 }
2155 }
2156
2157 fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
2168 match self.move_data.rev_lookup.find(place) {
2169 LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
2170 (self.move_data.move_paths[mpi].place.as_ref(), mpi)
2171 }
2172 LookupResult::Parent(None) => panic!("should have move path for every Local"),
2173 }
2174 }
2175
2176 fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
2177 match self.move_data.rev_lookup.find(place) {
2182 LookupResult::Parent(_) => None,
2183 LookupResult::Exact(mpi) => Some(mpi),
2184 }
2185 }
2186
2187 fn check_if_assigned_path_is_moved(
2188 &mut self,
2189 location: Location,
2190 (place, span): (Place<'tcx>, Span),
2191 state: &BorrowckDomain,
2192 ) {
2193 debug!("check_if_assigned_path_is_moved place: {:?}", place);
2194
2195 for (place_base, elem) in place.iter_projections().rev() {
2197 match elem {
2198 ProjectionElem::Index(_) |
2199 ProjectionElem::OpaqueCast(_) |
2200 ProjectionElem::ConstantIndex { .. } |
2201 ProjectionElem::Downcast(_, _) =>
2203 { }
2207
2208 ProjectionElem::UnwrapUnsafeBinder(_) => {
2209 check_parent_of_field(self, location, place_base, span, state);
2210 }
2211
2212 ProjectionElem::Deref => {
2214 self.check_if_full_path_is_moved(
2215 location, InitializationRequiringAction::Use,
2216 (place_base, span), state);
2217 break;
2220 }
2221
2222 ProjectionElem::Subslice { .. } => {
2223 panic!("we don't allow assignments to subslices, location: {location:?}");
2224 }
2225
2226 ProjectionElem::Field(..) => {
2227 let tcx = self.infcx.tcx;
2231 let base_ty = place_base.ty(self.body(), tcx).ty;
2232 match base_ty.kind() {
2233 ty::Adt(def, _) if def.has_dtor(tcx) => {
2234 self.check_if_path_or_subpath_is_moved(
2235 location, InitializationRequiringAction::Assignment,
2236 (place_base, span), state);
2237
2238 break;
2241 }
2242
2243 ty::Adt(..) | ty::Tuple(..) => {
2246 check_parent_of_field(self, location, place_base, span, state);
2247 }
2248
2249 _ => {}
2250 }
2251 }
2252 }
2253 }
2254
2255 fn check_parent_of_field<'a, 'tcx>(
2256 this: &mut MirBorrowckCtxt<'a, '_, 'tcx>,
2257 location: Location,
2258 base: PlaceRef<'tcx>,
2259 span: Span,
2260 state: &BorrowckDomain,
2261 ) {
2262 let maybe_uninits = &state.uninits;
2294
2295 let mut shortest_uninit_seen = None;
2298 for prefix in this.prefixes(base, PrefixSet::Shallow) {
2299 let Some(mpi) = this.move_path_for_place(prefix) else { continue };
2300
2301 if maybe_uninits.contains(mpi) {
2302 debug!(
2303 "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
2304 shortest_uninit_seen,
2305 Some((prefix, mpi))
2306 );
2307 shortest_uninit_seen = Some((prefix, mpi));
2308 } else {
2309 debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
2310 }
2311 }
2312
2313 if let Some((prefix, mpi)) = shortest_uninit_seen {
2314 let tcx = this.infcx.tcx;
2320 if base.ty(this.body(), tcx).ty.is_union()
2321 && this.move_data.path_map[mpi].iter().any(|moi| {
2322 this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
2323 })
2324 {
2325 return;
2326 }
2327
2328 this.report_use_of_moved_or_uninitialized(
2329 location,
2330 InitializationRequiringAction::PartialAssignment,
2331 (prefix, base, span),
2332 mpi,
2333 );
2334
2335 this.used_mut.insert(base.local);
2339 }
2340 }
2341 }
2342
2343 fn check_access_permissions(
2347 &mut self,
2348 (place, span): (Place<'tcx>, Span),
2349 kind: ReadOrWrite,
2350 is_local_mutation_allowed: LocalMutationIsAllowed,
2351 state: &BorrowckDomain,
2352 location: Location,
2353 ) -> bool {
2354 debug!(
2355 "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
2356 place, kind, is_local_mutation_allowed
2357 );
2358
2359 let error_access;
2360 let the_place_err;
2361
2362 match kind {
2363 Reservation(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind }))
2364 | Write(WriteKind::MutableBorrow(BorrowKind::Mut { kind: mut_borrow_kind })) => {
2365 let is_local_mutation_allowed = match mut_borrow_kind {
2366 MutBorrowKind::ClosureCapture => LocalMutationIsAllowed::Yes,
2370 MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow => {
2371 is_local_mutation_allowed
2372 }
2373 };
2374 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2375 Ok(root_place) => {
2376 self.add_used_mut(root_place, state);
2377 return false;
2378 }
2379 Err(place_err) => {
2380 error_access = AccessKind::MutableBorrow;
2381 the_place_err = place_err;
2382 }
2383 }
2384 }
2385 Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
2386 match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
2387 Ok(root_place) => {
2388 self.add_used_mut(root_place, state);
2389 return false;
2390 }
2391 Err(place_err) => {
2392 error_access = AccessKind::Mutate;
2393 the_place_err = place_err;
2394 }
2395 }
2396 }
2397
2398 Reservation(
2399 WriteKind::Move
2400 | WriteKind::Replace
2401 | WriteKind::StorageDeadOrDrop
2402 | WriteKind::MutableBorrow(BorrowKind::Shared)
2403 | WriteKind::MutableBorrow(BorrowKind::Fake(_)),
2404 )
2405 | Write(
2406 WriteKind::Move
2407 | WriteKind::Replace
2408 | WriteKind::StorageDeadOrDrop
2409 | WriteKind::MutableBorrow(BorrowKind::Shared)
2410 | WriteKind::MutableBorrow(BorrowKind::Fake(_)),
2411 ) => {
2412 if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err()
2413 && !self.has_buffered_diags()
2414 {
2415 self.dcx().span_delayed_bug(
2421 span,
2422 format!(
2423 "Accessing `{place:?}` with the kind `{kind:?}` shouldn't be possible",
2424 ),
2425 );
2426 }
2427 return false;
2428 }
2429 Activation(..) => {
2430 return false;
2432 }
2433 Read(
2434 ReadKind::Borrow(BorrowKind::Mut { .. } | BorrowKind::Shared | BorrowKind::Fake(_))
2435 | ReadKind::Copy,
2436 ) => {
2437 return false;
2439 }
2440 }
2441
2442 let previously_initialized = self.is_local_ever_initialized(place.local, state);
2447
2448 if let Some(init_index) = previously_initialized {
2450 if let (AccessKind::Mutate, Some(_)) = (error_access, place.as_local()) {
2451 let init = &self.move_data.inits[init_index];
2454 let assigned_span = init.span(self.body);
2455 self.report_illegal_reassignment((place, span), assigned_span, place);
2456 } else {
2457 self.report_mutability_error(place, span, the_place_err, error_access, location)
2458 }
2459 true
2460 } else {
2461 false
2462 }
2463 }
2464
2465 fn is_local_ever_initialized(&self, local: Local, state: &BorrowckDomain) -> Option<InitIndex> {
2466 let mpi = self.move_data.rev_lookup.find_local(local)?;
2467 let ii = &self.move_data.init_path_map[mpi];
2468 ii.into_iter().find(|&&index| state.ever_inits.contains(index)).copied()
2469 }
2470
2471 fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, state: &BorrowckDomain) {
2473 match root_place {
2474 RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
2475 if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2479 && self.is_local_ever_initialized(local, state).is_some()
2480 {
2481 self.used_mut.insert(local);
2482 }
2483 }
2484 RootPlace {
2485 place_local: _,
2486 place_projection: _,
2487 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2488 } => {}
2489 RootPlace {
2490 place_local,
2491 place_projection: place_projection @ [.., _],
2492 is_local_mutation_allowed: _,
2493 } => {
2494 if let Some(field) = self.is_upvar_field_projection(PlaceRef {
2495 local: place_local,
2496 projection: place_projection,
2497 }) {
2498 self.used_mut_upvars.push(field);
2499 }
2500 }
2501 }
2502 }
2503
2504 fn is_mutable(
2507 &self,
2508 place: PlaceRef<'tcx>,
2509 is_local_mutation_allowed: LocalMutationIsAllowed,
2510 ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2511 debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
2512 match place.last_projection() {
2513 None => {
2514 let local = &self.body.local_decls[place.local];
2515 match local.mutability {
2516 Mutability::Not => match is_local_mutation_allowed {
2517 LocalMutationIsAllowed::Yes => Ok(RootPlace {
2518 place_local: place.local,
2519 place_projection: place.projection,
2520 is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
2521 }),
2522 LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
2523 place_local: place.local,
2524 place_projection: place.projection,
2525 is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
2526 }),
2527 LocalMutationIsAllowed::No => Err(place),
2528 },
2529 Mutability::Mut => Ok(RootPlace {
2530 place_local: place.local,
2531 place_projection: place.projection,
2532 is_local_mutation_allowed,
2533 }),
2534 }
2535 }
2536 Some((place_base, elem)) => {
2537 match elem {
2538 ProjectionElem::Deref => {
2539 let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
2540
2541 match base_ty.kind() {
2543 ty::Ref(_, _, mutbl) => {
2544 match mutbl {
2545 hir::Mutability::Not => Err(place),
2547 hir::Mutability::Mut => {
2550 let mode = match self.is_upvar_field_projection(place) {
2551 Some(field)
2552 if self.upvars[field.index()].is_by_ref() =>
2553 {
2554 is_local_mutation_allowed
2555 }
2556 _ => LocalMutationIsAllowed::Yes,
2557 };
2558
2559 self.is_mutable(place_base, mode)
2560 }
2561 }
2562 }
2563 ty::RawPtr(_, mutbl) => {
2564 match mutbl {
2565 hir::Mutability::Not => Err(place),
2567 hir::Mutability::Mut => Ok(RootPlace {
2570 place_local: place.local,
2571 place_projection: place.projection,
2572 is_local_mutation_allowed,
2573 }),
2574 }
2575 }
2576 _ if base_ty.is_box() => {
2578 self.is_mutable(place_base, is_local_mutation_allowed)
2579 }
2580 _ => bug!("Deref of unexpected type: {:?}", base_ty),
2582 }
2583 }
2584 ProjectionElem::Field(FieldIdx::ZERO, _)
2587 if let Some(adt) =
2588 place_base.ty(self.body(), self.infcx.tcx).ty.ty_adt_def()
2589 && adt.is_pin()
2590 && self.infcx.tcx.features().pin_ergonomics() =>
2591 {
2592 self.is_mutable(place_base, is_local_mutation_allowed)
2593 }
2594 ProjectionElem::Field(..)
2597 | ProjectionElem::Index(..)
2598 | ProjectionElem::ConstantIndex { .. }
2599 | ProjectionElem::Subslice { .. }
2600 | ProjectionElem::OpaqueCast { .. }
2601 | ProjectionElem::Downcast(..)
2602 | ProjectionElem::UnwrapUnsafeBinder(_) => {
2603 let upvar_field_projection = self.is_upvar_field_projection(place);
2604 if let Some(field) = upvar_field_projection {
2605 let upvar = &self.upvars[field.index()];
2606 debug!(
2607 "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
2608 place={:?}, place_base={:?}",
2609 upvar, is_local_mutation_allowed, place, place_base
2610 );
2611 match (upvar.mutability, is_local_mutation_allowed) {
2612 (
2613 Mutability::Not,
2614 LocalMutationIsAllowed::No
2615 | LocalMutationIsAllowed::ExceptUpvars,
2616 ) => Err(place),
2617 (Mutability::Not, LocalMutationIsAllowed::Yes)
2618 | (Mutability::Mut, _) => {
2619 let _ =
2638 self.is_mutable(place_base, is_local_mutation_allowed)?;
2639 Ok(RootPlace {
2640 place_local: place.local,
2641 place_projection: place.projection,
2642 is_local_mutation_allowed,
2643 })
2644 }
2645 }
2646 } else {
2647 self.is_mutable(place_base, is_local_mutation_allowed)
2648 }
2649 }
2650 }
2651 }
2652 }
2653 }
2654
2655 fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<FieldIdx> {
2660 path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
2661 }
2662
2663 fn dominators(&self) -> &Dominators<BasicBlock> {
2664 self.body.basic_blocks.dominators()
2666 }
2667
2668 fn lint_unused_mut(&self) {
2669 let tcx = self.infcx.tcx;
2670 let body = self.body;
2671 for local in body.mut_vars_and_args_iter().filter(|local| !self.used_mut.contains(local)) {
2672 let local_decl = &body.local_decls[local];
2673 let ClearCrossCrate::Set(SourceScopeLocalData { lint_root, .. }) =
2674 body.source_scopes[local_decl.source_info.scope].local_data
2675 else {
2676 continue;
2677 };
2678
2679 if self.local_excluded_from_unused_mut_lint(local) {
2681 continue;
2682 }
2683
2684 let span = local_decl.source_info.span;
2685 if span.desugaring_kind().is_some() {
2686 continue;
2688 }
2689
2690 let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
2691
2692 tcx.emit_node_span_lint(UNUSED_MUT, lint_root, span, VarNeedNotMut { span: mut_span })
2693 }
2694 }
2695}
2696
2697enum Overlap {
2699 Arbitrary,
2705 EqualOrDisjoint,
2710 Disjoint,
2713}