Don't mark for loop head span with desugaring

This commit is contained in:
Cameron Steffen 2021-10-14 16:19:39 -05:00
parent 313e71a253
commit bd1a1e4f0d
5 changed files with 48 additions and 53 deletions

View File

@ -1331,15 +1331,10 @@ impl<'hir> LoweringContext<'_, 'hir> {
body: &Block, body: &Block,
opt_label: Option<Label>, opt_label: Option<Label>,
) -> hir::Expr<'hir> { ) -> hir::Expr<'hir> {
let orig_head_span = head.span;
// expand <head> // expand <head>
let mut head = self.lower_expr_mut(head); let head = self.lower_expr_mut(head);
let desugared_span = self.mark_span_with_reason( let desugared_span =
DesugaringKind::ForLoop(ForLoopLoc::Head), self.mark_span_with_reason(DesugaringKind::ForLoop(ForLoopLoc::Head), head.span, None);
orig_head_span,
None,
);
head.span = self.lower_span(desugared_span);
let iter = Ident::with_dummy_span(sym::iter); let iter = Ident::with_dummy_span(sym::iter);
@ -1428,7 +1423,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
loop_block, loop_block,
self.lower_label(opt_label), self.lower_label(opt_label),
hir::LoopSource::ForLoop, hir::LoopSource::ForLoop,
self.lower_span(e.span.with_hi(orig_head_span.hi())), self.lower_span(e.span.with_hi(head.span.hi())),
); );
let loop_expr = self.arena.alloc(hir::Expr { let loop_expr = self.arena.alloc(hir::Expr {
hir_id: self.lower_node_id(e.id), hir_id: self.lower_node_id(e.id),
@ -1441,7 +1436,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let into_iter_span = self.mark_span_with_reason( let into_iter_span = self.mark_span_with_reason(
DesugaringKind::ForLoop(ForLoopLoc::IntoIter), DesugaringKind::ForLoop(ForLoopLoc::IntoIter),
orig_head_span, head.span,
None, None,
); );

View File

@ -11,7 +11,6 @@ use rustc_middle::mir::{
}; };
use rustc_middle::ty::{self, suggest_constraining_type_param, Ty}; use rustc_middle::ty::{self, suggest_constraining_type_param, Ty};
use rustc_mir_dataflow::move_paths::{InitKind, MoveOutIndex, MovePathIndex}; use rustc_mir_dataflow::move_paths::{InitKind, MoveOutIndex, MovePathIndex};
use rustc_span::source_map::DesugaringKind;
use rustc_span::symbol::sym; use rustc_span::symbol::sym;
use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP}; use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::infer::InferCtxtExt;
@ -247,6 +246,36 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
place_name, partially_str, loop_message place_name, partially_str, loop_message
), ),
); );
let sess = self.infcx.tcx.sess;
let ty = used_place.ty(self.body, self.infcx.tcx).ty;
// If we have a `&mut` ref, we need to reborrow.
if let ty::Ref(_, _, hir::Mutability::Mut) = ty.kind() {
// If we are in a loop this will be suggested later.
if !is_loop_move {
err.span_suggestion_verbose(
move_span.shrink_to_lo(),
&format!(
"consider creating a fresh reborrow of {} here",
self.describe_place(moved_place.as_ref())
.map(|n| format!("`{}`", n))
.unwrap_or_else(
|| "the mutable reference".to_string()
),
),
"&mut *".to_string(),
Applicability::MachineApplicable,
);
}
} else if let Ok(snippet) =
sess.source_map().span_to_snippet(move_span)
{
err.span_suggestion(
move_span,
"consider borrowing to avoid moving into the for loop",
format!("&{}", snippet),
Applicability::MaybeIncorrect,
);
}
} else { } else {
err.span_label( err.span_label(
fn_call_span, fn_call_span,
@ -315,35 +344,6 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
in_pattern = true; in_pattern = true;
} }
} }
if let Some(DesugaringKind::ForLoop(_)) = move_span.desugaring_kind() {
let sess = self.infcx.tcx.sess;
let ty = used_place.ty(self.body, self.infcx.tcx).ty;
// If we have a `&mut` ref, we need to reborrow.
if let ty::Ref(_, _, hir::Mutability::Mut) = ty.kind() {
// If we are in a loop this will be suggested later.
if !is_loop_move {
err.span_suggestion_verbose(
move_span.shrink_to_lo(),
&format!(
"consider creating a fresh reborrow of {} here",
self.describe_place(moved_place.as_ref())
.map(|n| format!("`{}`", n))
.unwrap_or_else(|| "the mutable reference".to_string()),
),
"&mut *".to_string(),
Applicability::MachineApplicable,
);
}
} else if let Ok(snippet) = sess.source_map().span_to_snippet(move_span) {
err.span_suggestion(
move_span,
"consider borrowing to avoid moving into the for loop",
format!("&{}", snippet),
Applicability::MaybeIncorrect,
);
}
}
} }
use_spans.var_span_label_path_only( use_spans.var_span_label_path_only(

View File

@ -5,11 +5,10 @@ use rustc_middle::ty;
use rustc_mir_dataflow::move_paths::{ use rustc_mir_dataflow::move_paths::{
IllegalMoveOrigin, IllegalMoveOriginKind, LookupResult, MoveError, MovePathIndex, IllegalMoveOrigin, IllegalMoveOriginKind, LookupResult, MoveError, MovePathIndex,
}; };
use rustc_span::source_map::DesugaringKind;
use rustc_span::{sym, Span, DUMMY_SP}; use rustc_span::{sym, Span, DUMMY_SP};
use rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions; use rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions;
use crate::diagnostics::UseSpans; use crate::diagnostics::{FnSelfUseKind, UseSpans};
use crate::prefixes::PrefixSet; use crate::prefixes::PrefixSet;
use crate::MirBorrowckCtxt; use crate::MirBorrowckCtxt;
@ -400,19 +399,21 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
| ty::Opaque(def_id, _) => def_id, | ty::Opaque(def_id, _) => def_id,
_ => return err, _ => return err,
}; };
let is_option = self.infcx.tcx.is_diagnostic_item(sym::Option, def_id); let diag_name = self.infcx.tcx.get_diagnostic_name(def_id);
let is_result = self.infcx.tcx.is_diagnostic_item(sym::Result, def_id); if matches!(diag_name, Some(sym::Option | sym::Result))
if (is_option || is_result) && use_spans.map_or(true, |v| !v.for_closure()) { && use_spans.map_or(true, |v| !v.for_closure())
{
err.span_suggestion_verbose( err.span_suggestion_verbose(
span.shrink_to_hi(), span.shrink_to_hi(),
&format!( &format!("consider borrowing the `{}`'s content", diag_name.unwrap()),
"consider borrowing the `{}`'s content",
if is_option { "Option" } else { "Result" }
),
".as_ref()".to_string(), ".as_ref()".to_string(),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
} else if matches!(span.desugaring_kind(), Some(DesugaringKind::ForLoop(_))) { } else if let Some(UseSpans::FnSelfUse {
kind: FnSelfUseKind::Normal { implicit_into_iter: true, .. },
..
}) = use_spans
{
let suggest = match self.infcx.tcx.get_diagnostic_item(sym::IntoIterator) { let suggest = match self.infcx.tcx.get_diagnostic_item(sym::IntoIterator) {
Some(def_id) => self.infcx.tcx.infer_ctxt().enter(|infcx| { Some(def_id) => self.infcx.tcx.infer_ctxt().enter(|infcx| {
type_known_to_meet_bound_modulo_regions( type_known_to_meet_bound_modulo_regions(

View File

@ -134,9 +134,8 @@ impl<'tcx> LateLintPass<'tcx> for ArrayIntoIter {
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
if self.for_expr_span == expr.span { if self.for_expr_span == expr.span {
let expr_span = expr.span.ctxt().outer_expn_data().call_site;
diag.span_suggestion( diag.span_suggestion(
receiver_arg.span.shrink_to_hi().to(expr_span.shrink_to_hi()), receiver_arg.span.shrink_to_hi().to(expr.span.shrink_to_hi()),
"or remove `.into_iter()` to iterate by value", "or remove `.into_iter()` to iterate by value",
String::new(), String::new(),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,

View File

@ -83,7 +83,7 @@ pub fn change_iteration_variable_pattern() {
#[cfg(not(any(cfail1,cfail4)))] #[cfg(not(any(cfail1,cfail4)))]
#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, optimized_mir, typeck")] #[rustc_clean(cfg="cfail2", except="hir_owner_nodes, optimized_mir, typeck")]
#[rustc_clean(cfg="cfail3")] #[rustc_clean(cfg="cfail3")]
#[rustc_clean(cfg="cfail5", except="hir_owner_nodes, optimized_mir, typeck, promoted_mir")] #[rustc_clean(cfg="cfail5", except="hir_owner_nodes, optimized_mir, typeck")]
#[rustc_clean(cfg="cfail6")] #[rustc_clean(cfg="cfail6")]
pub fn change_iteration_variable_pattern() { pub fn change_iteration_variable_pattern() {
let mut _x = 0; let mut _x = 0;