Warning: Direct indexing (e.g., `vec[i]`, `slice[i]`) panics on out-of-bounds access. Prefer using `.get(index)` or `.get_mut(index)` which return Option<&T>/Option<&mut T>.
if let Some(prev_name) = local_names[local]
1//! Borrow checker diagnostics.23use std::collections::BTreeMap;45use rustc_abi::{FieldIdx, VariantIdx};6use rustc_data_structures::fx::FxIndexMap;7use rustc_errors::formatting::DiagMessageAddArg;8use rustc_errors::{Applicability, Diag, DiagMessage, EmissionGuarantee, MultiSpan, listify, msg};9use rustc_hir::def::{CtorKind, Namespace};10use rustc_hir::{11 self as hir, CoroutineKind, GenericBound, LangItem, WhereBoundPredicate, WherePredicateKind,12};13use rustc_index::{IndexSlice, IndexVec};14use rustc_infer::infer::{BoundRegionConversionTime, NllRegionVariableOrigin};15use rustc_infer::traits::SelectionError;16use rustc_middle::mir::{17 AggregateKind, CallSource, ConstOperand, ConstraintCategory, FakeReadCause, Local, LocalInfo,18 LocalKind, Location, Operand, Place, PlaceRef, PlaceTy, ProjectionElem, Rvalue, Statement,19 StatementKind, Terminator, TerminatorKind, VarDebugInfoContents, find_self_call,20};21use rustc_middle::ty::print::Print;22use rustc_middle::ty::{self, Ty, TyCtxt};23use rustc_middle::{bug, span_bug};24use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveOutIndex};25use rustc_span::def_id::LocalDefId;26use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Spanned, Symbol, sym};27use rustc_trait_selection::error_reporting::InferCtxtErrorExt;28use rustc_trait_selection::error_reporting::traits::call_kind::{CallDesugaringKind, call_kind};29use rustc_trait_selection::infer::InferCtxtExt;30use rustc_trait_selection::traits::{31 FulfillmentError, FulfillmentErrorCode, type_known_to_meet_bound_modulo_regions,32};33use tracing::debug;3435use super::MirBorrowckCtxt;36use super::borrow_set::BorrowData;37use crate::LocalMutationIsAllowed;38use crate::constraints::OutlivesConstraint;39use crate::nll::ConstraintDescription;40use crate::session_diagnostics::{41 CaptureArgLabel, CaptureReasonLabel, CaptureReasonNote, CaptureReasonSuggest, CaptureVarCause,42 CaptureVarKind, CaptureVarPathUseCause, OnClosureNote,43};4445mod find_all_local_uses;46mod find_use;47mod outlives_suggestion;48mod region_name;49mod var_name;5051mod bound_region_errors;52mod conflict_errors;53mod explain_borrow;54mod move_errors;55mod mutability_errors;56mod opaque_types;57mod region_errors;5859pub(crate) use bound_region_errors::{ToUniverseInfo, UniverseInfo};60pub(crate) use move_errors::{IllegalMoveOriginKind, MoveError};61pub(crate) use mutability_errors::AccessKind;62pub(crate) use outlives_suggestion::OutlivesSuggestionBuilder;63pub(crate) use region_errors::{ErrorConstraintInfo, RegionErrorKind, RegionErrors};64pub(crate) use region_name::{RegionName, RegionNameSource};65pub(crate) use rustc_trait_selection::error_reporting::traits::call_kind::CallKind;6667pub(super) struct DescribePlaceOpt {68 including_downcast: bool,6970 /// Enable/Disable tuple fields.71 /// For example `x` tuple. if it's `true` `x.0`. Otherwise `x`72 including_tuple_field: bool,73}7475pub(super) struct IncludingTupleField(pub(super) bool);7677enum BufferedDiag<'infcx> {78 Error(Diag<'infcx>),79 NonError(Diag<'infcx, ()>),80}8182impl<'infcx> BufferedDiag<'infcx> {83 fn sort_span(&self) -> Span {84 match self {85 BufferedDiag::Error(diag) => diag.sort_span,86 BufferedDiag::NonError(diag) => diag.sort_span,87 }88 }89}9091#[derive(Default)]92pub(crate) struct BorrowckDiagnosticsBuffer<'infcx, 'tcx> {93 /// This field keeps track of move errors that are to be reported for given move indices.94 ///95 /// There are situations where many errors can be reported for a single move out (see96 /// #53807) and we want only the best of those errors.97 ///98 /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the99 /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of100 /// the `Place` of the previous most diagnostic. This happens instead of buffering the101 /// error. Once all move errors have been reported, any diagnostics in this map are added102 /// to the buffer to be emitted.103 ///104 /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary105 /// when errors in the map are being re-added to the error buffer so that errors with the106 /// same primary span come out in a consistent order.107 buffered_move_errors: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, Diag<'infcx>)>,108109 buffered_mut_errors: FxIndexMap<Span, (Diag<'infcx>, usize)>,110111 /// Buffer of diagnostics to be reported. A mixture of error and non-error diagnostics.112 buffered_diags: Vec<BufferedDiag<'infcx>>,113}114115impl<'infcx, 'tcx> BorrowckDiagnosticsBuffer<'infcx, 'tcx> {116 pub(crate) fn buffer_non_error(&mut self, diag: Diag<'infcx, ()>) {117 self.buffered_diags.push(BufferedDiag::NonError(diag));118 }119}120121impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {122 pub(crate) fn buffer_error(&mut self, diag: Diag<'infcx>) {123 self.diags_buffer.buffered_diags.push(BufferedDiag::Error(diag));124 }125126 pub(crate) fn buffer_non_error(&mut self, diag: Diag<'infcx, ()>) {127 self.diags_buffer.buffer_non_error(diag);128 }129130 pub(crate) fn buffer_move_error(131 &mut self,132 move_out_indices: Vec<MoveOutIndex>,133 place_and_err: (PlaceRef<'tcx>, Diag<'infcx>),134 ) -> bool {135 if let Some((_, diag)) =136 self.diags_buffer.buffered_move_errors.insert(move_out_indices, place_and_err)137 {138 // Cancel the old diagnostic so we don't ICE139 diag.cancel();140 false141 } else {142 true143 }144 }145146 pub(crate) fn get_buffered_mut_error(&mut self, span: Span) -> Option<(Diag<'infcx>, usize)> {147 // FIXME(#120456) - is `swap_remove` correct?148 self.diags_buffer.buffered_mut_errors.swap_remove(&span)149 }150151 pub(crate) fn buffer_mut_error(&mut self, span: Span, diag: Diag<'infcx>, count: usize) {152 self.diags_buffer.buffered_mut_errors.insert(span, (diag, count));153 }154155 pub(crate) fn emit_errors(&mut self) -> Option<ErrorGuaranteed> {156 let mut res = self.infcx.tainted_by_errors();157158 // Buffer any move errors that we collected and de-duplicated.159 for (_, (_, diag)) in std::mem::take(&mut self.diags_buffer.buffered_move_errors) {160 // We have already set tainted for this error, so just buffer it.161 self.buffer_error(diag);162 }163 for (_, (mut diag, count)) in std::mem::take(&mut self.diags_buffer.buffered_mut_errors) {164 if count > 10 {165 diag.note(format!("...and {} other attempted mutable borrows", count - 10));166 }167 self.buffer_error(diag);168 }169170 if !self.diags_buffer.buffered_diags.is_empty() {171 self.diags_buffer.buffered_diags.sort_by_key(|buffered_diag| buffered_diag.sort_span());172 for buffered_diag in self.diags_buffer.buffered_diags.drain(..) {173 match buffered_diag {174 BufferedDiag::Error(diag) => res = Some(diag.emit()),175 BufferedDiag::NonError(diag) => diag.emit(),176 }177 }178 }179180 res181 }182183 pub(crate) fn has_buffered_diags(&self) -> bool {184 self.diags_buffer.buffered_diags.is_empty()185 }186187 pub(crate) fn has_move_error(188 &self,189 move_out_indices: &[MoveOutIndex],190 ) -> Option<&(PlaceRef<'tcx>, Diag<'infcx>)> {191 self.diags_buffer.buffered_move_errors.get(move_out_indices)192 }193194 /// Uses `body.var_debug_info` to find the symbol195 fn local_name(&self, index: Local) -> Option<Symbol> {196 *self.local_names().get(index)?197 }198199 fn local_names(&self) -> &IndexSlice<Local, Option<Symbol>> {200 self.local_names.get_or_init(|| {201 let mut local_names = IndexVec::from_elem(None, &self.body.local_decls);202 for var_debug_info in &self.body.var_debug_info {203 if let VarDebugInfoContents::Place(place) = var_debug_info.value {204 if let Some(local) = place.as_local() {205 if let Some(prev_name) = local_names[local]206 && var_debug_info.name != prev_name207 {208 span_bug!(209 var_debug_info.source_info.span,210 "local {:?} has many names (`{}` vs `{}`)",211 local,212 prev_name,213 var_debug_info.name214 );215 }216 local_names[local] = Some(var_debug_info.name);217 }218 }219 }220 local_names221 })222 }223}224225impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {226 /// Adds a suggestion when a closure is invoked twice with a moved variable or when a closure227 /// is moved after being invoked.228 ///229 /// ```text230 /// note: closure cannot be invoked more than once because it moves the variable `dict` out of231 /// its environment232 /// --> $DIR/issue-42065.rs:16:29233 /// |234 /// LL | for (key, value) in dict {235 /// | ^^^^236 /// ```237 pub(super) fn add_moved_or_invoked_closure_note(238 &self,239 location: Location,240 place: PlaceRef<'tcx>,241 diag: &mut Diag<'infcx>,242 ) -> bool {243 debug!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location, place);244 let mut target = place.local_or_deref_local();245 for stmt in &self.body[location.block].statements[location.statement_index..] {246 debug!("add_moved_or_invoked_closure_note: stmt={:?} target={:?}", stmt, target);247 if let StatementKind::Assign((into, Rvalue::Use(from, _))) = &stmt.kind {248 debug!("add_fnonce_closure_note: into={:?} from={:?}", into, from);249 match from {250 Operand::Copy(place) | Operand::Move(place)251 if target == place.local_or_deref_local() =>252 {253 target = into.local_or_deref_local()254 }255 _ => {}256 }257 }258 }259260 // Check if we are attempting to call a closure after it has been invoked.261 let terminator = self.body[location.block].terminator();262 debug!("add_moved_or_invoked_closure_note: terminator={:?}", terminator);263 if let TerminatorKind::Call {264 func: Operand::Constant(ConstOperand { const_, .. }),265 args,266 ..267 } = &terminator.kind268 && let ty::FnDef(id, _) = *const_.ty().kind()269 {270 debug!("add_moved_or_invoked_closure_note: id={:?}", id);271 if self.infcx.tcx.is_lang_item(self.infcx.tcx.parent(id), LangItem::FnOnce) {272 let closure = match args.first() {273 Some(Spanned { node: Operand::Copy(place) | Operand::Move(place), .. })274 if target == place.local_or_deref_local() =>275 {276 place.local_or_deref_local().unwrap()277 }278 _ => return false,279 };280281 debug!("add_moved_or_invoked_closure_note: closure={:?}", closure);282 if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() {283 let did = did.expect_local();284 if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) {285 diag.subdiagnostic(OnClosureNote::InvokedTwice {286 place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place),287 span: *span,288 });289 return true;290 }291 }292 }293 }294295 // Check if we are just moving a closure after it has been invoked.296 if let Some(target) = target297 && let ty::Closure(did, _) = self.body.local_decls[target].ty.kind()298 {299 let did = did.expect_local();300 if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) {301 diag.subdiagnostic(OnClosureNote::MovedTwice {302 place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place),303 span: *span,304 });305 return true;306 }307 }308 false309 }310311 /// End-user visible description of `place` if one can be found.312 /// If the place is a temporary for instance, `"value"` will be returned.313 pub(super) fn describe_any_place(&self, place_ref: PlaceRef<'tcx>) -> String {314 match self.describe_place(place_ref) {315 Some(mut descr) => {316 // Surround descr with `backticks`.317 descr.reserve(2);318 descr.insert(0, '`');319 descr.push('`');320 descr321 }322 None => "value".to_string(),323 }324 }325326 /// End-user visible description of `place` if one can be found.327 /// If the place is a temporary for instance, `None` will be returned.328 pub(super) fn describe_place(&self, place_ref: PlaceRef<'tcx>) -> Option<String> {329 self.describe_place_with_options(330 place_ref,331 DescribePlaceOpt { including_downcast: false, including_tuple_field: true },332 )333 }334335 /// End-user visible description of `place` if one can be found. If the place is a temporary336 /// for instance, `None` will be returned.337 /// `IncludingDowncast` parameter makes the function return `None` if `ProjectionElem` is338 /// `Downcast` and `IncludingDowncast` is true339 pub(super) fn describe_place_with_options(340 &self,341 place: PlaceRef<'tcx>,342 opt: DescribePlaceOpt,343 ) -> Option<String> {344 let local = place.local;345 if self.body.local_decls[local]346 .source_info347 .span348 .in_external_macro(self.infcx.tcx.sess.source_map())349 {350 return None;351 }352353 let mut autoderef_index = None;354 let mut buf = String::new();355 let mut ok = self.append_local_to_string(local, &mut buf);356357 for (index, elem) in place.projection.into_iter().enumerate() {358 match elem {359 ProjectionElem::Deref => {360 if index == 0 {361 if self.body.local_decls[local].is_ref_for_guard() {362 continue;363 }364 if let LocalInfo::StaticRef { def_id, .. } =365 *self.body.local_decls[local].local_info()366 {367 buf.push_str(self.infcx.tcx.item_name(def_id).as_str());368 ok = Ok(());369 continue;370 }371 }372 if let Some(field) = self.is_upvar_field_projection(PlaceRef {373 local,374 projection: place.projection.split_at(index + 1).0,375 }) {376 let var_index = field.index();377 buf = self.upvars[var_index].to_string(self.infcx.tcx);378 ok = Ok(());379 if !self.upvars[var_index].is_by_ref() {380 buf.insert(0, '*');381 }382 } else {383 if autoderef_index.is_none() {384 autoderef_index = match place.projection.iter().rposition(|elem| {385 !matches!(386 elem,387 ProjectionElem::Deref | ProjectionElem::Downcast(..)388 )389 }) {390 Some(index) => Some(index + 1),391 None => Some(0),392 };393 }394 if index >= autoderef_index.unwrap() {395 buf.insert(0, '*');396 }397 }398 }399 ProjectionElem::Downcast(..) if opt.including_downcast => return None,400 ProjectionElem::Downcast(..) => (),401 ProjectionElem::OpaqueCast(..) => (),402 ProjectionElem::UnwrapUnsafeBinder(_) => (),403 ProjectionElem::Field(field, _ty) => {404 // FIXME(project-rfc_2229#36): print capture precisely here.405 if let Some(field) = self.is_upvar_field_projection(PlaceRef {406 local,407 projection: place.projection.split_at(index + 1).0,408 }) {409 buf = self.upvars[field.index()].to_string(self.infcx.tcx);410 ok = Ok(());411 } else {412 let field_name = self.describe_field(413 PlaceRef { local, projection: place.projection.split_at(index).0 },414 *field,415 IncludingTupleField(opt.including_tuple_field),416 );417 if let Some(field_name_str) = field_name {418 buf.push('.');419 buf.push_str(&field_name_str);420 }421 }422 }423 ProjectionElem::Index(index) => {424 buf.push('[');425 if self.append_local_to_string(*index, &mut buf).is_err() {426 buf.push('_');427 }428 buf.push(']');429 }430 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {431 // Since it isn't possible to borrow an element on a particular index and432 // then use another while the borrow is held, don't output indices details433 // to avoid confusing the end-user434 buf.push_str("[..]");435 }436 }437 }438 ok.ok().map(|_| buf)439 }440441 fn describe_name(&self, place: PlaceRef<'tcx>) -> Option<Symbol> {442 for elem in place.projection.into_iter() {443 match elem {444 ProjectionElem::Downcast(Some(name), _) => {445 return Some(*name);446 }447 _ => {}448 }449 }450 None451 }452453 /// Appends end-user visible description of the `local` place to `buf`. If `local` doesn't have454 /// a name, or its name was generated by the compiler, then `Err` is returned455 fn append_local_to_string(&self, local: Local, buf: &mut String) -> Result<(), ()> {456 let decl = &self.body.local_decls[local];457 match self.local_name(local) {458 Some(name) if !decl.from_compiler_desugaring() => {459 buf.push_str(name.as_str());460 Ok(())461 }462 _ => Err(()),463 }464 }465466 /// End-user visible description of the `field`nth field of `base`467 fn describe_field(468 &self,469 place: PlaceRef<'tcx>,470 field: FieldIdx,471 including_tuple_field: IncludingTupleField,472 ) -> Option<String> {473 let place_ty = match place {474 PlaceRef { local, projection: [] } => PlaceTy::from_ty(self.body.local_decls[local].ty),475 PlaceRef { local, projection: [proj_base @ .., elem] } => match elem {476 ProjectionElem::Deref477 | ProjectionElem::Index(..)478 | ProjectionElem::ConstantIndex { .. }479 | ProjectionElem::Subslice { .. } => {480 PlaceRef { local, projection: proj_base }.ty(self.body, self.infcx.tcx)481 }482 ProjectionElem::Downcast(..) => place.ty(self.body, self.infcx.tcx),483 ProjectionElem::OpaqueCast(ty) | ProjectionElem::UnwrapUnsafeBinder(ty) => {484 PlaceTy::from_ty(*ty)485 }486 ProjectionElem::Field(_, field_type) => PlaceTy::from_ty(*field_type),487 },488 };489 self.describe_field_from_ty(490 place_ty.ty,491 field,492 place_ty.variant_index,493 including_tuple_field,494 )495 }496497 /// End-user visible description of the `field_index`nth field of `ty`498 fn describe_field_from_ty(499 &self,500 ty: Ty<'_>,501 field: FieldIdx,502 variant_index: Option<VariantIdx>,503 including_tuple_field: IncludingTupleField,504 ) -> Option<String> {505 if let Some(boxed_ty) = ty.boxed_ty() {506 // If the type is a box, the field is described from the boxed type507 self.describe_field_from_ty(boxed_ty, field, variant_index, including_tuple_field)508 } else {509 match *ty.kind() {510 ty::Adt(def, _) => {511 let variant = if let Some(idx) = variant_index {512 assert!(def.is_enum());513 def.variant(idx)514 } else {515 def.non_enum_variant()516 };517 if !including_tuple_field.0 && variant.ctor_kind() == Some(CtorKind::Fn) {518 return None;519 }520 Some(variant.fields[field].name.to_string())521 }522 ty::Tuple(_) => Some(field.index().to_string()),523 ty::Ref(_, ty, _) | ty::RawPtr(ty, _) => {524 self.describe_field_from_ty(ty, field, variant_index, including_tuple_field)525 }526 ty::Array(ty, _) | ty::Slice(ty) => {527 self.describe_field_from_ty(ty, field, variant_index, including_tuple_field)528 }529 ty::Closure(def_id, _) | ty::Coroutine(def_id, _) => {530 // We won't be borrowck'ing here if the closure came from another crate,531 // so it's safe to call `expect_local`.532 //533 // We know the field exists so it's safe to call operator[] and `unwrap` here.534 let def_id = def_id.expect_local();535 let var_id =536 self.infcx.tcx.closure_captures(def_id)[field.index()].get_root_variable();537538 Some(self.infcx.tcx.hir_name(var_id).to_string())539 }540 _ => {541 // This can happen for field accesses on `Box<T>`: the field is542 // described from the boxed type, which may have no named fields543 Some(field.index().to_string())544 }545 }546 }547 }548549 pub(super) fn borrowed_content_source(550 &self,551 deref_base: PlaceRef<'tcx>,552 ) -> BorrowedContentSource<'tcx> {553 let tcx = self.infcx.tcx;554555 // Look up the provided place and work out the move path index for it,556 // we'll use this to check whether it was originally from an overloaded557 // operator.558 match self.move_data.rev_lookup.find(deref_base) {559 LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => {560 debug!("borrowed_content_source: mpi={:?}", mpi);561562 for i in &self.move_data.init_path_map[mpi] {563 let init = &self.move_data.inits[*i];564 debug!("borrowed_content_source: init={:?}", init);565 // We're only interested in statements that initialized a value, not the566 // initializations from arguments.567 let InitLocation::Statement(loc) = init.location else { continue };568569 let bbd = &self.body[loc.block];570 let is_terminator = bbd.statements.len() == loc.statement_index;571 debug!(572 "borrowed_content_source: loc={:?} is_terminator={:?}",573 loc, is_terminator,574 );575 if !is_terminator {576 continue;577 } else if let Some(Terminator {578 kind:579 TerminatorKind::Call {580 func,581 call_source: CallSource::OverloadedOperator,582 ..583 },584 ..585 }) = &bbd.terminator586 {587 if let Some(source) =588 BorrowedContentSource::from_call(func.ty(self.body, tcx), tcx)589 {590 return source;591 }592 }593 }594 }595 // Base is a `static` so won't be from an overloaded operator596 _ => (),597 };598599 // If we didn't find an overloaded deref or index, then assume it's a600 // built in deref and check the type of the base.601 let base_ty = deref_base.ty(self.body, tcx).ty;602 if base_ty.is_raw_ptr() {603 BorrowedContentSource::DerefRawPointer604 } else if base_ty.is_mutable_ptr() {605 BorrowedContentSource::DerefMutableRef606 } else if base_ty.is_ref() {607 BorrowedContentSource::DerefSharedRef608 } else {609 // Custom type implementing `Deref` (e.g. `MyBox<T>`, `Rc<T>`, `Arc<T>`)610 // that wasn't detected via the MIR init trace above. This can happen611 // when the deref base is initialized by a regular statement rather than612 // a `TerminatorKind::Call` with `CallSource::OverloadedOperator`.613 BorrowedContentSource::OverloadedDeref(base_ty)614 }615 }616617 /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime618 /// name where required.619 pub(super) fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {620 let mut p = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);621622 // We need to add synthesized lifetimes where appropriate. We do623 // this by hooking into the pretty printer and telling it to label the624 // lifetimes without names with the value `'0`.625 if let ty::Ref(region, ..) = ty.kind() {626 match region.kind() {627 ty::ReBound(_, ty::BoundRegion { kind: br, .. })628 | ty::RePlaceholder(ty::PlaceholderRegion {629 bound: ty::BoundRegion { kind: br, .. },630 ..631 }) => p.region_highlight_mode.highlighting_bound_region(br, counter),632 _ => {}633 }634 }635636 ty.print(&mut p).unwrap();637 p.into_buffer()638 }639640 /// Returns the name of the provided `Ty` (that must be a reference)'s region with a641 /// synthesized lifetime name where required.642 pub(super) fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {643 let mut p = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);644645 let region = if let ty::Ref(region, ..) = ty.kind() {646 match region.kind() {647 ty::ReBound(_, ty::BoundRegion { kind: br, .. })648 | ty::RePlaceholder(ty::PlaceholderRegion {649 bound: ty::BoundRegion { kind: br, .. },650 ..651 }) => p.region_highlight_mode.highlighting_bound_region(br, counter),652 _ => {}653 }654 region655 } else {656 bug!("ty for annotation of borrow region is not a reference");657 };658659 region.print(&mut p).unwrap();660 p.into_buffer()661 }662663 /// Add a note to region errors and borrow explanations when higher-ranked regions in predicates664 /// implicitly introduce an "outlives `'static`" constraint.665 ///666 /// This is very similar to `fn suggest_static_lifetime_for_gat_from_hrtb` which handles this667 /// note for failed type tests instead of outlives errors.668 fn add_placeholder_from_predicate_note<G: EmissionGuarantee>(669 &self,670 diag: &mut Diag<'_, G>,671 path: &[OutlivesConstraint<'tcx>],672 ) {673 let tcx = self.infcx.tcx;674 let Some((gat_hir_id, generics)) = path.iter().find_map(|constraint| {675 let outlived = constraint.sub;676 if let Some(origin) = self.regioncx.definitions.get(outlived)677 && let NllRegionVariableOrigin::Placeholder(placeholder) = origin.origin678 && let Some(id) = placeholder.bound.kind.get_id()679 && let Some(placeholder_id) = id.as_local()680 && let gat_hir_id = tcx.local_def_id_to_hir_id(placeholder_id)681 && let Some(generics_impl) =682 tcx.parent_hir_node(tcx.parent_hir_id(gat_hir_id)).generics()683 {684 Some((gat_hir_id, generics_impl))685 } else {686 None687 }688 }) else {689 return;690 };691692 // Look for the where-bound which introduces the placeholder.693 // As we're using the HIR, we need to handle both `for<'a> T: Trait<'a>`694 // and `T: for<'a> Trait`<'a>.695 for pred in generics.predicates {696 let WherePredicateKind::BoundPredicate(WhereBoundPredicate {697 bound_generic_params,698 bounds,699 ..700 }) = pred.kind701 else {702 continue;703 };704 if bound_generic_params705 .iter()706 .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)707 .is_some()708 {709 diag.span_note(pred.span, LIMITATION_NOTE);710 return;711 }712 for bound in bounds.iter() {713 if let GenericBound::Trait(bound) = bound {714 if bound715 .bound_generic_params716 .iter()717 .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)718 .is_some()719 {720 diag.span_note(bound.span, LIMITATION_NOTE);721 return;722 }723 }724 }725 }726 }727728 /// Add a label to region errors and borrow explanations when outlives constraints arise from729 /// proving a type implements `Sized` or `Copy`.730 fn add_sized_or_copy_bound_info<G: EmissionGuarantee>(731 &self,732 err: &mut Diag<'_, G>,733 blamed_category: ConstraintCategory<'tcx>,734 path: &[OutlivesConstraint<'tcx>],735 ) {736 for sought_category in [ConstraintCategory::SizedBound, ConstraintCategory::CopyBound] {737 if sought_category != blamed_category738 && let Some(sought_constraint) = path.iter().find(|c| c.category == sought_category)739 {740 let label = format!(741 "requirement occurs due to {}",742 sought_category.description().trim_end()743 );744 err.span_label(sought_constraint.span, label);745 }746 }747 }748}749750/// The span(s) associated to a use of a place.751#[derive(Copy, Clone, PartialEq, Eq, Debug)]752pub(super) enum UseSpans<'tcx> {753 /// The access is caused by capturing a variable for a closure.754 ClosureUse {755 /// This is true if the captured variable was from a coroutine.756 closure_kind: hir::ClosureKind,757 /// The span of the args of the closure, including the `move` keyword if758 /// it's present.759 args_span: Span,760 /// The span of the use resulting in capture kind761 /// Check `ty::CaptureInfo` for more details762 capture_kind_span: Span,763 /// The span of the use resulting in the captured path764 /// Check `ty::CaptureInfo` for more details765 path_span: Span,766 },767 /// The access is caused by using a variable as the receiver of a method768 /// that takes 'self'769 FnSelfUse {770 /// The span of the variable being moved771 var_span: Span,772 /// The span of the method call on the variable773 fn_call_span: Span,774 /// The definition span of the method being called775 fn_span: Span,776 kind: CallKind<'tcx>,777 },778 /// This access is caused by a `match` or `if let` pattern.779 PatUse(Span),780 /// This access has a single span associated to it: common case.781 OtherUse(Span),782}783784impl UseSpans<'_> {785 pub(super) fn args_or_use(self) -> Span {786 match self {787 UseSpans::ClosureUse { args_span: span, .. }788 | UseSpans::PatUse(span)789 | UseSpans::OtherUse(span) => span,790 UseSpans::FnSelfUse { var_span, .. } => var_span,791 }792 }793794 /// Returns the span of `self`, in the case of a `ClosureUse` returns the `path_span`795 pub(super) fn var_or_use_path_span(self) -> Span {796 match self {797 UseSpans::ClosureUse { path_span: span, .. }798 | UseSpans::PatUse(span)799 | UseSpans::OtherUse(span) => span,800 UseSpans::FnSelfUse { var_span, .. } => var_span,801 }802 }803804 /// Returns the span of `self`, in the case of a `ClosureUse` returns the `capture_kind_span`805 pub(super) fn var_or_use(self) -> Span {806 match self {807 UseSpans::ClosureUse { capture_kind_span: span, .. }808 | UseSpans::PatUse(span)809 | UseSpans::OtherUse(span) => span,810 UseSpans::FnSelfUse { var_span, .. } => var_span,811 }812 }813814 // FIXME(coroutines): Make this just return the `ClosureKind` directly?815 pub(super) fn coroutine_kind(self) -> Option<CoroutineKind> {816 match self {817 UseSpans::ClosureUse {818 closure_kind: hir::ClosureKind::Coroutine(coroutine_kind),819 ..820 } => Some(coroutine_kind),821 _ => None,822 }823 }824825 /// Add a span label to the arguments of the closure, if it exists.826 pub(super) fn args_subdiag(self, err: &mut Diag<'_>, f: impl FnOnce(Span) -> CaptureArgLabel) {827 if let UseSpans::ClosureUse { args_span, .. } = self {828 err.subdiagnostic(f(args_span));829 }830 }831832 /// Add a span label to the use of the captured variable, if it exists.833 /// only adds label to the `path_span`834 pub(super) fn var_path_only_subdiag(835 self,836 err: &mut Diag<'_>,837 action: crate::InitializationRequiringAction,838 ) {839 use CaptureVarPathUseCause::*;840841 use crate::InitializationRequiringAction::*;842 if let UseSpans::ClosureUse { closure_kind, path_span, .. } = self {843 match closure_kind {844 hir::ClosureKind::Coroutine(_) => {845 err.subdiagnostic(match action {846 Borrow => BorrowInCoroutine { path_span },847 MatchOn | Use => UseInCoroutine { path_span },848 Assignment => AssignInCoroutine { path_span },849 PartialAssignment => AssignPartInCoroutine { path_span },850 });851 }852 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {853 err.subdiagnostic(match action {854 Borrow => BorrowInClosure { path_span },855 MatchOn | Use => UseInClosure { path_span },856 Assignment => AssignInClosure { path_span },857 PartialAssignment => AssignPartInClosure { path_span },858 });859 }860 }861 }862 }863864 /// Add a subdiagnostic to the use of the captured variable, if it exists.865 pub(super) fn var_subdiag(866 self,867 err: &mut Diag<'_>,868 kind: Option<rustc_middle::mir::BorrowKind>,869 f: impl FnOnce(hir::ClosureKind, Span) -> CaptureVarCause,870 ) {871 if let UseSpans::ClosureUse { closure_kind, capture_kind_span, path_span, .. } = self {872 if capture_kind_span != path_span {873 err.subdiagnostic(match kind {874 Some(kd) => match kd {875 rustc_middle::mir::BorrowKind::Shared876 | rustc_middle::mir::BorrowKind::Fake(_) => {877 CaptureVarKind::Immut { kind_span: capture_kind_span }878 }879880 rustc_middle::mir::BorrowKind::Mut { .. } => {881 CaptureVarKind::Mut { kind_span: capture_kind_span }882 }883 },884 None => CaptureVarKind::Move { kind_span: capture_kind_span },885 });886 };887 let diag = f(closure_kind, path_span);888 err.subdiagnostic(diag);889 }890 }891892 /// Returns `false` if this place is not used in a closure.893 pub(super) fn for_closure(&self) -> bool {894 match *self {895 UseSpans::ClosureUse { closure_kind, .. } => {896 matches!(closure_kind, hir::ClosureKind::Closure)897 }898 _ => false,899 }900 }901902 /// Returns `false` if this place is not used in a coroutine.903 pub(super) fn for_coroutine(&self) -> bool {904 match *self {905 // FIXME(coroutines): Do we want this to apply to synthetic coroutines?906 UseSpans::ClosureUse { closure_kind, .. } => {907 matches!(closure_kind, hir::ClosureKind::Coroutine(..))908 }909 _ => false,910 }911 }912913 pub(super) fn or_else<F>(self, if_other: F) -> Self914 where915 F: FnOnce() -> Self,916 {917 match self {918 closure @ UseSpans::ClosureUse { .. } => closure,919 UseSpans::PatUse(_) | UseSpans::OtherUse(_) => if_other(),920 fn_self @ UseSpans::FnSelfUse { .. } => fn_self,921 }922 }923}924925pub(super) enum BorrowedContentSource<'tcx> {926 DerefRawPointer,927 DerefMutableRef,928 DerefSharedRef,929 OverloadedDeref(Ty<'tcx>),930 OverloadedIndex(Ty<'tcx>),931}932933impl<'tcx> BorrowedContentSource<'tcx> {934 pub(super) fn describe_for_unnamed_place(&self, tcx: TyCtxt<'_>) -> String {935 match *self {936 BorrowedContentSource::DerefRawPointer => "a raw pointer".to_string(),937 BorrowedContentSource::DerefSharedRef => "a shared reference".to_string(),938 BorrowedContentSource::DerefMutableRef => "a mutable reference".to_string(),939 BorrowedContentSource::OverloadedDeref(ty) => ty940 .ty_adt_def()941 .and_then(|adt| match tcx.get_diagnostic_name(adt.did())? {942 name @ (sym::Rc | sym::Arc) => Some(format!("an `{name}`")),943 _ => None,944 })945 .unwrap_or_else(|| format!("dereference of `{ty}`")),946 BorrowedContentSource::OverloadedIndex(ty) => format!("index of `{ty}`"),947 }948 }949950 pub(super) fn describe_for_named_place(&self) -> Option<&'static str> {951 match *self {952 BorrowedContentSource::DerefRawPointer => Some("raw pointer"),953 BorrowedContentSource::DerefSharedRef => Some("shared reference"),954 BorrowedContentSource::DerefMutableRef => Some("mutable reference"),955 // Overloaded deref and index operators should be evaluated into a956 // temporary. So we don't need a description here.957 BorrowedContentSource::OverloadedDeref(_)958 | BorrowedContentSource::OverloadedIndex(_) => None,959 }960 }961962 pub(super) fn describe_for_immutable_place(&self, tcx: TyCtxt<'_>) -> String {963 match *self {964 BorrowedContentSource::DerefRawPointer => "a `*const` pointer".to_string(),965 BorrowedContentSource::DerefSharedRef => "a `&` reference".to_string(),966 BorrowedContentSource::DerefMutableRef => {967 bug!("describe_for_immutable_place: DerefMutableRef isn't immutable")968 }969 BorrowedContentSource::OverloadedDeref(ty) => ty970 .ty_adt_def()971 .and_then(|adt| match tcx.get_diagnostic_name(adt.did())? {972 name @ (sym::Rc | sym::Arc) => Some(format!("an `{name}`")),973 _ => None,974 })975 .unwrap_or_else(|| format!("dereference of `{ty}`")),976 BorrowedContentSource::OverloadedIndex(ty) => format!("an index of `{ty}`"),977 }978 }979980 fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Self> {981 match *func.kind() {982 ty::FnDef(def_id, args) => {983 let trait_id = tcx.trait_of_assoc(def_id)?;984985 if tcx.is_lang_item(trait_id, LangItem::Deref)986 || tcx.is_lang_item(trait_id, LangItem::DerefMut)987 {988 Some(BorrowedContentSource::OverloadedDeref(args.type_at(0)))989 } else if tcx.is_lang_item(trait_id, LangItem::Index)990 || tcx.is_lang_item(trait_id, LangItem::IndexMut)991 {992 Some(BorrowedContentSource::OverloadedIndex(args.type_at(0)))993 } else {994 None995 }996 }997 _ => None,998 }999 }1000}10011002/// Helper struct for `explain_captures`.1003struct CapturedMessageOpt {1004 is_partial_move: bool,1005 is_loop_message: bool,1006 is_move_msg: bool,1007 is_loop_move: bool,1008 has_suggest_reborrow: bool,1009 maybe_reinitialized_locations_is_empty: bool,1010}10111012/// Tracks whether [`MirBorrowckCtxt::explain_captures`] emitted a clone1013/// suggestion, so callers can avoid emitting redundant suggestions downstream.1014#[derive(Copy, Clone, PartialEq, Eq)]1015pub(super) enum CloneSuggestion {1016 Emitted,1017 NotEmitted,1018}10191020impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {1021 /// Finds the spans associated to a move or copy of move_place at location.1022 pub(super) fn move_spans(1023 &self,1024 moved_place: PlaceRef<'tcx>, // Could also be an upvar.1025 location: Location,1026 ) -> UseSpans<'tcx> {1027 use self::UseSpans::*;10281029 let Some(stmt) = self.body[location.block].statements.get(location.statement_index) else {1030 return OtherUse(self.body.source_info(location).span);1031 };10321033 debug!("move_spans: moved_place={:?} location={:?} stmt={:?}", moved_place, location, stmt);1034 if let StatementKind::Assign((_, Rvalue::Aggregate(kind, places))) = &stmt.kind1035 && let AggregateKind::Closure(def_id, _) | AggregateKind::Coroutine(def_id, _) = **kind1036 {1037 debug!("move_spans: def_id={:?} places={:?}", def_id, places);1038 let def_id = def_id.expect_local();1039 if let Some((args_span, closure_kind, capture_kind_span, path_span)) =1040 self.closure_span(def_id, moved_place, places)1041 {1042 return ClosureUse { closure_kind, args_span, capture_kind_span, path_span };1043 }1044 }10451046 // StatementKind::FakeRead only contains a def_id if they are introduced as a result1047 // of pattern matching within a closure.1048 if let StatementKind::FakeRead((cause, place)) = stmt.kind {1049 match cause {1050 FakeReadCause::ForMatchedPlace(Some(closure_def_id))1051 | FakeReadCause::ForLet(Some(closure_def_id)) => {1052 debug!("move_spans: def_id={:?} place={:?}", closure_def_id, place);1053 let places = &[Operand::Move(place)];1054 if let Some((args_span, closure_kind, capture_kind_span, path_span)) =1055 self.closure_span(closure_def_id, moved_place, IndexSlice::from_raw(places))1056 {1057 return ClosureUse {1058 closure_kind,1059 args_span,1060 capture_kind_span,1061 path_span,1062 };1063 }1064 }1065 _ => {}1066 }1067 }10681069 let normal_ret =1070 if moved_place.projection.iter().any(|p| matches!(p, ProjectionElem::Downcast(..))) {1071 PatUse(stmt.source_info.span)1072 } else {1073 OtherUse(stmt.source_info.span)1074 };10751076 // We are trying to find MIR of the form:1077 // ```1078 // _temp = _moved_val;1079 // ...1080 // FnSelfCall(_temp, ...)1081 // ```1082 //1083 // where `_moved_val` is the place we generated the move error for,1084 // `_temp` is some other local, and `FnSelfCall` is a function1085 // that has a `self` parameter.10861087 let target_temp = match stmt.kind {1088 StatementKind::Assign((temp, _)) if temp.as_local().is_some() => {1089 temp.as_local().unwrap()1090 }1091 _ => return normal_ret,1092 };10931094 debug!("move_spans: target_temp = {:?}", target_temp);10951096 if let Some(Terminator {1097 kind: TerminatorKind::Call { fn_span, call_source, .. }, ..1098 }) = &self.body[location.block].terminator1099 {1100 let Some((method_did, method_args)) =1101 find_self_call(self.infcx.tcx, self.body, target_temp, location.block)1102 else {1103 return normal_ret;1104 };11051106 let kind = call_kind(1107 self.infcx.tcx,1108 self.infcx.typing_env(self.infcx.param_env),1109 method_did,1110 method_args,1111 *fn_span,1112 call_source.from_hir_call(),1113 self.infcx.tcx.fn_arg_idents(method_did)[0],1114 );11151116 return FnSelfUse {1117 var_span: stmt.source_info.span,1118 fn_call_span: *fn_span,1119 fn_span: self.infcx.tcx.def_span(method_did),1120 kind,1121 };1122 }11231124 normal_ret1125 }11261127 /// Finds the span of arguments of a closure (within `maybe_closure_span`)1128 /// and its usage of the local assigned at `location`.1129 /// This is done by searching in statements succeeding `location`1130 /// and originating from `maybe_closure_span`.1131 pub(super) fn borrow_spans(&self, use_span: Span, location: Location) -> UseSpans<'tcx> {1132 use self::UseSpans::*;1133 debug!("borrow_spans: use_span={:?} location={:?}", use_span, location);11341135 let Some(Statement { kind: StatementKind::Assign((place, _)), .. }) =1136 self.body[location.block].statements.get(location.statement_index)1137 else {1138 return OtherUse(use_span);1139 };1140 let Some(target) = place.as_local() else { return OtherUse(use_span) };11411142 if self.body.local_kind(target) != LocalKind::Temp {1143 // operands are always temporaries.1144 return OtherUse(use_span);1145 }11461147 // drop and replace might have moved the assignment to the next block1148 let maybe_additional_statement =1149 if let TerminatorKind::Drop { target: drop_target, .. } =1150 self.body[location.block].terminator().kind1151 {1152 self.body[drop_target].statements.first()1153 } else {1154 None1155 };11561157 let statements =1158 self.body[location.block].statements[location.statement_index + 1..].iter();11591160 for stmt in statements.chain(maybe_additional_statement) {1161 if let StatementKind::Assign((_, Rvalue::Aggregate(kind, places))) = &stmt.kind {1162 let (&def_id, is_coroutine) = match kind {1163 AggregateKind::Closure(def_id, _) => (def_id, false),1164 AggregateKind::Coroutine(def_id, _) => (def_id, true),1165 _ => continue,1166 };1167 let def_id = def_id.expect_local();11681169 debug!(1170 "borrow_spans: def_id={:?} is_coroutine={:?} places={:?}",1171 def_id, is_coroutine, places1172 );1173 if let Some((args_span, closure_kind, capture_kind_span, path_span)) =1174 self.closure_span(def_id, Place::from(target).as_ref(), places)1175 {1176 return ClosureUse { closure_kind, args_span, capture_kind_span, path_span };1177 } else {1178 return OtherUse(use_span);1179 }1180 }11811182 if use_span != stmt.source_info.span {1183 break;1184 }1185 }11861187 OtherUse(use_span)1188 }11891190 /// Finds the spans of a captured place within a closure or coroutine.1191 /// The first span is the location of the use resulting in the capture kind of the capture1192 /// The second span is the location the use resulting in the captured path of the capture1193 fn closure_span(1194 &self,1195 def_id: LocalDefId,1196 target_place: PlaceRef<'tcx>,1197 places: &IndexSlice<FieldIdx, Operand<'tcx>>,1198 ) -> Option<(Span, hir::ClosureKind, Span, Span)> {1199 debug!(1200 "closure_span: def_id={:?} target_place={:?} places={:?}",1201 def_id, target_place, places1202 );1203 let hir_id = self.infcx.tcx.local_def_id_to_hir_id(def_id);1204 let expr = &self.infcx.tcx.hir_expect_expr(hir_id).kind;1205 debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);1206 if let &hir::ExprKind::Closure(&hir::Closure { kind, fn_decl_span, .. }) = expr {1207 for (captured_place, place) in1208 self.infcx.tcx.closure_captures(def_id).iter().zip(places)1209 {1210 match place {1211 Operand::Copy(place) | Operand::Move(place)1212 if target_place == place.as_ref() =>1213 {1214 debug!("closure_span: found captured local {:?}", place);1215 return Some((1216 fn_decl_span,1217 kind,1218 captured_place.get_capture_kind_span(self.infcx.tcx),1219 captured_place.get_path_span(self.infcx.tcx),1220 ));1221 }1222 _ => {}1223 }1224 }1225 }1226 None1227 }12281229 /// Helper to retrieve span(s) of given borrow from the current MIR1230 /// representation1231 pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans<'tcx> {1232 let span = self.body.source_info(borrow.reserve_location).span;1233 self.borrow_spans(span, borrow.reserve_location)1234 }12351236 fn explain_captures(1237 &mut self,1238 err: &mut Diag<'infcx>,1239 span: Span,1240 move_span: Span,1241 move_spans: UseSpans<'tcx>,1242 moved_place: Place<'tcx>,1243 msg_opt: CapturedMessageOpt,1244 ) -> CloneSuggestion {1245 let CapturedMessageOpt {1246 is_partial_move: is_partial,1247 is_loop_message,1248 is_move_msg,1249 is_loop_move,1250 has_suggest_reborrow,1251 maybe_reinitialized_locations_is_empty,1252 } = msg_opt;1253 let mut suggested_cloning = false;1254 if let UseSpans::FnSelfUse { var_span, fn_call_span, fn_span, kind } = move_spans {1255 let place_name = self1256 .describe_place(moved_place.as_ref())1257 .map(|n| format!("`{n}`"))1258 .unwrap_or_else(|| "value".to_owned());1259 match kind {1260 CallKind::FnCall { fn_trait_id, self_ty }1261 if self.infcx.tcx.is_lang_item(fn_trait_id, LangItem::FnOnce) =>1262 {1263 err.subdiagnostic(CaptureReasonLabel::Call {1264 fn_call_span,1265 place_name: &place_name,1266 is_partial,1267 is_loop_message,1268 });1269 // Check if the move occurs on a value because of a call on a closure that comes1270 // from a type parameter `F: FnOnce()`. If so, we provide a targeted `note`:1271 // ```1272 // error[E0382]: use of moved value: `blk`1273 // --> $DIR/once-cant-call-twice-on-heap.rs:8:51274 // |1275 // LL | fn foo<F:FnOnce()>(blk: F) {1276 // | --- move occurs because `blk` has type `F`, which does not implement the `Copy` trait1277 // LL | blk();1278 // | ----- `blk` moved due to this call1279 // LL | blk();1280 // | ^^^ value used here after move1281 // |1282 // note: `FnOnce` closures can only be called once1283 // --> $DIR/once-cant-call-twice-on-heap.rs:6:101284 // |1285 // LL | fn foo<F:FnOnce()>(blk: F) {1286 // | ^^^^^^^^ `F` is made to be an `FnOnce` closure here1287 // LL | blk();1288 // | ----- this value implements `FnOnce`, which causes it to be moved when called1289 // ```1290 if let ty::Param(param_ty) = *self_ty.kind()1291 && let generics = self.infcx.tcx.generics_of(self.mir_def_id())1292 && let param = generics.type_param(param_ty, self.infcx.tcx)1293 && let Some(hir_generics) = self.infcx.tcx.hir_get_generics(1294 self.infcx.tcx.typeck_root_def_id_local(self.mir_def_id()),1295 )1296 && let spans = hir_generics1297 .predicates1298 .iter()1299 .filter_map(|pred| match pred.kind {1300 hir::WherePredicateKind::BoundPredicate(pred) => Some(pred),1301 _ => None,1302 })1303 .filter(|pred| {1304 if let Some((id, _)) = pred.bounded_ty.as_generic_param() {1305 id == param.def_id1306 } else {1307 false1308 }1309 })1310 .flat_map(|pred| pred.bounds)1311 .filter_map(|bound| {1312 if let Some(trait_ref) = bound.trait_ref()1313 && let Some(trait_def_id) = trait_ref.trait_def_id()1314 && trait_def_id == fn_trait_id1315 {1316 Some(bound.span())1317 } else {1318 None1319 }1320 })1321 .collect::<Vec<Span>>()1322 && !spans.is_empty()1323 {1324 let mut span: MultiSpan = spans.clone().into();1325 let msg = msg!("`{$ty}` is made to be an `FnOnce` closure here")1326 .arg("ty", param_ty.to_string())1327 .format();1328 for sp in spans {1329 span.push_span_label(sp, msg.clone());1330 }1331 span.push_span_label(1332 fn_call_span,1333 msg!("this value implements `FnOnce`, which causes it to be moved when called"),1334 );1335 err.span_note(span, msg!("`FnOnce` closures can only be called once"));1336 } else {1337 err.subdiagnostic(CaptureReasonNote::FnOnceMoveInCall { var_span });1338 }1339 }1340 CallKind::Operator { self_arg, trait_id, .. } => {1341 let self_arg = self_arg.unwrap();1342 err.subdiagnostic(CaptureReasonLabel::OperatorUse {1343 fn_call_span,1344 place_name: &place_name,1345 is_partial,1346 is_loop_message,1347 });1348 if self.fn_self_span_reported.insert(fn_span) {1349 let lang = self.infcx.tcx.lang_items();1350 err.subdiagnostic(1351 if [lang.not_trait(), lang.deref_trait(), lang.neg_trait()]1352 .contains(&Some(trait_id))1353 {1354 CaptureReasonNote::UnOpMoveByOperator { span: self_arg.span }1355 } else {1356 CaptureReasonNote::LhsMoveByOperator { span: self_arg.span }1357 },1358 );1359 }1360 }1361 CallKind::Normal { self_arg, desugaring, method_did, method_args } => {1362 let self_arg = self_arg.unwrap();1363 let mut has_sugg = false;1364 let tcx = self.infcx.tcx;1365 // Avoid pointing to the same function in multiple different1366 // error messages.1367 if span != DUMMY_SP && self.fn_self_span_reported.insert(self_arg.span) {1368 self.explain_iterator_advancement_in_for_loop_if_applicable(1369 err,1370 span,1371 &move_spans,1372 );13731374 let func = tcx.def_path_str(method_did);1375 err.subdiagnostic(CaptureReasonNote::FuncTakeSelf {1376 func,1377 place_name: place_name.clone(),1378 span: self_arg.span,1379 });1380 }1381 let parent_did = tcx.parent(method_did);1382 let parent_self_ty =1383 matches!(tcx.def_kind(parent_did), rustc_hir::def::DefKind::Impl { .. })1384 .then_some(parent_did)1385 .and_then(|did| {1386 match tcx.type_of(did).instantiate_identity().skip_norm_wip().kind()1387 {1388 ty::Adt(def, ..) => Some(def.did()),1389 _ => None,1390 }1391 });1392 let is_option_or_result = parent_self_ty.is_some_and(|def_id| {1393 matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result))1394 });1395 if is_option_or_result && maybe_reinitialized_locations_is_empty {1396 err.subdiagnostic(CaptureReasonLabel::BorrowContent {1397 var_span: var_span.shrink_to_hi(),1398 });1399 }1400 if let Some((CallDesugaringKind::ForLoopIntoIter, _)) = desugaring {1401 let ty = moved_place.ty(self.body, tcx).ty;1402 let suggest = match tcx.get_diagnostic_item(sym::IntoIterator) {1403 Some(def_id) => type_known_to_meet_bound_modulo_regions(1404 self.infcx,1405 self.infcx.param_env,1406 Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty),1407 def_id,1408 ),1409 _ => false,1410 };1411 if suggest {1412 err.subdiagnostic(CaptureReasonSuggest::IterateSlice {1413 ty,1414 span: move_span.shrink_to_lo(),1415 });1416 }14171418 err.subdiagnostic(CaptureReasonLabel::ImplicitCall {1419 fn_call_span,1420 place_name: &place_name,1421 is_partial,1422 is_loop_message,1423 });1424 // If the moved place was a `&mut` ref, then we can1425 // suggest to reborrow it where it was moved, so it1426 // will still be valid by the time we get to the usage.1427 if let ty::Ref(_, _, hir::Mutability::Mut) =1428 moved_place.ty(self.body, self.infcx.tcx).ty.kind()1429 {1430 // The `&mut *place` reborrow suggestion is `MachineApplicable`, so1431 // only offer it where `*place` can be borrowed mutably: a value1432 // captured by an `Fn` closure (held via `&self`) cannot, and the1433 // suggestion would otherwise fail to compile with E0596.1434 let reborrow_place = self.infcx.tcx.mk_place_deref(moved_place);1435 let reborrow_is_valid = self1436 .is_mutable(reborrow_place.as_ref(), LocalMutationIsAllowed::No)1437 .is_ok();1438 // Suggest `reborrow` in other place for following situations:1439 // 1. If we are in a loop this will be suggested later.1440 // 2. If the moved value is a mut reference, it is used in a1441 // generic function and the corresponding arg's type is generic param.1442 if !is_loop_move && !has_suggest_reborrow && reborrow_is_valid {1443 self.suggest_reborrow(1444 err,1445 move_span.shrink_to_lo(),1446 moved_place.as_ref(),1447 );1448 }1449 }1450 } else {1451 if let Some((CallDesugaringKind::Await, _)) = desugaring {1452 err.subdiagnostic(CaptureReasonLabel::Await {1453 fn_call_span,1454 place_name: &place_name,1455 is_partial,1456 is_loop_message,1457 });1458 } else {1459 err.subdiagnostic(CaptureReasonLabel::MethodCall {1460 fn_call_span,1461 place_name: &place_name,1462 is_partial,1463 is_loop_message,1464 });1465 }1466 // Erase and shadow everything that could be passed to the new infcx.1467 let ty = moved_place.ty(self.body, tcx).ty;14681469 if let ty::Adt(def, args) = ty.peel_refs().kind()1470 && tcx.is_lang_item(def.did(), LangItem::Pin)1471 && let ty::Ref(_, _, hir::Mutability::Mut) = args.type_at(0).kind()1472 && let self_ty = self.infcx.instantiate_binder_with_fresh_vars(1473 fn_call_span,1474 BoundRegionConversionTime::FnCall,1475 tcx.fn_sig(method_did)1476 .instantiate(tcx, method_args)1477 .skip_norm_wip()1478 .input(0),1479 )1480 && self.infcx.can_eq(self.infcx.param_env, ty, self_ty)1481 {1482 err.subdiagnostic(CaptureReasonSuggest::FreshReborrow {1483 span: move_span.shrink_to_hi(),1484 });1485 has_sugg = true;1486 }1487 if let Some(clone_trait) = tcx.lang_items().clone_trait() {1488 // Check whether the deref is from a custom Deref impl1489 // (e.g. Rc, Box) or a built-in reference deref.1490 // For built-in derefs with Clone fully satisfied, we skip1491 // the UFCS suggestion here and let `suggest_cloning`1492 // downstream emit a simpler `.clone()` suggestion instead.1493 let has_overloaded_deref =1494 moved_place.iter_projections().any(|(place, elem)| {1495 matches!(elem, ProjectionElem::Deref)1496 && matches!(1497 self.borrowed_content_source(place),1498 BorrowedContentSource::OverloadedDeref(_)1499 | BorrowedContentSource::OverloadedIndex(_)1500 )1501 });15021503 let has_deref = moved_place1504 .iter_projections()1505 .any(|(_, elem)| matches!(elem, ProjectionElem::Deref));15061507 let sugg = if has_deref {1508 let (start, end) = if let Some(expr) = self.find_expr(move_span)1509 && let Some(_) = self.clone_on_reference(expr)1510 && let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind1511 {1512 (move_span.shrink_to_lo(), move_span.with_lo(rcvr.span.hi()))1513 } else {1514 (move_span.shrink_to_lo(), move_span.shrink_to_hi())1515 };1516 vec![1517 // We use the fully-qualified path because `.clone()` can1518 // sometimes choose `<&T as Clone>` instead of `<T as Clone>`1519 // when going through auto-deref, so this ensures that doesn't1520 // happen, causing suggestions for `.clone().clone()`.1521 (start, format!("<{ty} as Clone>::clone(&")),1522 (end, ")".to_string()),1523 ]1524 } else {1525 vec![(move_span.shrink_to_hi(), ".clone()".to_string())]1526 };1527 if let Some(errors) = self.infcx.type_implements_trait_shallow(1528 clone_trait,1529 ty,1530 self.infcx.param_env,1531 ) && !has_sugg1532 {1533 let skip_for_simple_clone =1534 has_deref && !has_overloaded_deref && errors.is_empty();1535 if !skip_for_simple_clone {1536 let msg = match &errors[..] {1537 [] => "you can `clone` the value and consume it, but \1538 this might not be your desired behavior"1539 .to_string(),1540 [error] => {1541 format!(1542 "you could `clone` the value and consume it, if \1543 the `{}` trait bound could be satisfied",1544 error.obligation.predicate,1545 )1546 }1547 _ => {1548 format!(1549 "you could `clone` the value and consume it, if \1550 the following trait bounds could be satisfied: \1551 {}",1552 listify(1553 &errors,1554 |e: &FulfillmentError<'tcx>| format!(1555 "`{}`",1556 e.obligation.predicate1557 )1558 )1559 .unwrap(),1560 )1561 }1562 };1563 err.multipart_suggestion(1564 msg,1565 sugg,1566 Applicability::MaybeIncorrect,1567 );15681569 suggested_cloning = errors.is_empty();15701571 for error in errors {1572 if let FulfillmentErrorCode::Select(1573 SelectionError::Unimplemented,1574 ) = error.code1575 && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(1576 pred,1577 )) = error.obligation.predicate.kind().skip_binder()1578 {1579 self.infcx.err_ctxt().suggest_derive(1580 &error.obligation,1581 err,1582 error.obligation.predicate.kind().rebind(pred),1583 );1584 }1585 }1586 }1587 }1588 }1589 }1590 }1591 // Other desugarings takes &self, which cannot cause a move1592 _ => {}1593 }1594 } else {1595 if move_span != span || is_loop_message {1596 err.subdiagnostic(CaptureReasonLabel::MovedHere {1597 move_span,1598 is_partial,1599 is_move_msg,1600 is_loop_message,1601 });1602 }1603 // If the move error occurs due to a loop, don't show1604 // another message for the same span1605 if !is_loop_message {1606 move_spans.var_subdiag(err, None, |kind, var_span| match kind {1607 hir::ClosureKind::Coroutine(_) => {1608 CaptureVarCause::PartialMoveUseInCoroutine { var_span, is_partial }1609 }1610 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {1611 CaptureVarCause::PartialMoveUseInClosure { var_span, is_partial }1612 }1613 })1614 }1615 }1616 if suggested_cloning { CloneSuggestion::Emitted } else { CloneSuggestion::NotEmitted }1617 }16181619 /// Skip over locals that begin with an underscore or have no name1620 pub(crate) fn local_excluded_from_unused_mut_lint(&self, index: Local) -> bool {1621 self.local_name(index).is_none_or(|name| name.as_str().starts_with('_'))1622 }1623}16241625const LIMITATION_NOTE: DiagMessage =1626 msg!("due to a current limitation of the type system, this implies a `'static` lifetime");
Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.