Remove redundant argument from subdiagnostic method

This commit is contained in:
Oli Scherer 2024-06-18 11:10:18 +00:00
parent 7ba82d61eb
commit 3f34196839
38 changed files with 361 additions and 542 deletions

View File

@ -228,7 +228,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
seen_spans.insert(move_span); seen_spans.insert(move_span);
} }
use_spans.var_path_only_subdiag(self.dcx(), &mut err, desired_action); use_spans.var_path_only_subdiag(&mut err, desired_action);
if !is_loop_move { if !is_loop_move {
err.span_label( err.span_label(
@ -303,24 +303,18 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
if needs_note { if needs_note {
if let Some(local) = place.as_local() { if let Some(local) = place.as_local() {
let span = self.body.local_decls[local].source_info.span; let span = self.body.local_decls[local].source_info.span;
err.subdiagnostic( err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label {
self.dcx(), is_partial_move,
crate::session_diagnostics::TypeNoCopy::Label { ty,
is_partial_move, place: &note_msg,
ty, span,
place: &note_msg, });
span,
},
);
} else { } else {
err.subdiagnostic( err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Note {
self.dcx(), is_partial_move,
crate::session_diagnostics::TypeNoCopy::Note { ty,
is_partial_move, place: &note_msg,
ty, });
place: &note_msg,
},
);
}; };
} }
@ -597,7 +591,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
E0381, E0381,
"{used} binding {desc}{isnt_initialized}" "{used} binding {desc}{isnt_initialized}"
); );
use_spans.var_path_only_subdiag(self.dcx(), &mut err, desired_action); use_spans.var_path_only_subdiag(&mut err, desired_action);
if let InitializationRequiringAction::PartialAssignment if let InitializationRequiringAction::PartialAssignment
| InitializationRequiringAction::Assignment = desired_action | InitializationRequiringAction::Assignment = desired_action
@ -1410,13 +1404,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
&value_msg, &value_msg,
); );
borrow_spans.var_path_only_subdiag( borrow_spans.var_path_only_subdiag(&mut err, crate::InitializationRequiringAction::Borrow);
self.dcx(),
&mut err,
crate::InitializationRequiringAction::Borrow,
);
move_spans.var_subdiag(self.dcx(), &mut err, None, |kind, var_span| { move_spans.var_subdiag(&mut err, None, |kind, var_span| {
use crate::session_diagnostics::CaptureVarCause::*; use crate::session_diagnostics::CaptureVarCause::*;
match kind { match kind {
hir::ClosureKind::Coroutine(_) => MoveUseInCoroutine { var_span }, hir::ClosureKind::Coroutine(_) => MoveUseInCoroutine { var_span },
@ -1468,7 +1458,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
borrow_span, borrow_span,
&self.describe_any_place(borrow.borrowed_place.as_ref()), &self.describe_any_place(borrow.borrowed_place.as_ref()),
); );
borrow_spans.var_subdiag(self.dcx(), &mut err, Some(borrow.kind), |kind, var_span| { borrow_spans.var_subdiag(&mut err, Some(borrow.kind), |kind, var_span| {
use crate::session_diagnostics::CaptureVarCause::*; use crate::session_diagnostics::CaptureVarCause::*;
let place = &borrow.borrowed_place; let place = &borrow.borrowed_place;
let desc_place = self.describe_any_place(place.as_ref()); let desc_place = self.describe_any_place(place.as_ref());
@ -1633,7 +1623,6 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
"mutably borrow", "mutably borrow",
); );
borrow_spans.var_subdiag( borrow_spans.var_subdiag(
self.dcx(),
&mut err, &mut err,
Some(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }), Some(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }),
|kind, var_span| { |kind, var_span| {
@ -1730,64 +1719,45 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
}; };
if issued_spans == borrow_spans { if issued_spans == borrow_spans {
borrow_spans.var_subdiag( borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
self.dcx(), use crate::session_diagnostics::CaptureVarCause::*;
&mut err, match kind {
Some(gen_borrow_kind), hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
|kind, var_span| { place: desc_place,
use crate::session_diagnostics::CaptureVarCause::*; var_span,
match kind { is_single_var: false,
hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine { },
place: desc_place, hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
var_span, BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: false }
is_single_var: false,
},
hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
BorrowUsePlaceClosure {
place: desc_place,
var_span,
is_single_var: false,
}
}
} }
}, }
); });
} else { } else {
issued_spans.var_subdiag( issued_spans.var_subdiag(&mut err, Some(issued_borrow.kind), |kind, var_span| {
self.dcx(), use crate::session_diagnostics::CaptureVarCause::*;
&mut err, let borrow_place = &issued_borrow.borrowed_place;
Some(issued_borrow.kind), let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
|kind, var_span| { match kind {
use crate::session_diagnostics::CaptureVarCause::*; hir::ClosureKind::Coroutine(_) => {
let borrow_place = &issued_borrow.borrowed_place; FirstBorrowUsePlaceCoroutine { place: borrow_place_desc, var_span }
let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
match kind {
hir::ClosureKind::Coroutine(_) => {
FirstBorrowUsePlaceCoroutine { place: borrow_place_desc, var_span }
}
hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
FirstBorrowUsePlaceClosure { place: borrow_place_desc, var_span }
}
} }
}, hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
); FirstBorrowUsePlaceClosure { place: borrow_place_desc, var_span }
}
}
});
borrow_spans.var_subdiag( borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
self.dcx(), use crate::session_diagnostics::CaptureVarCause::*;
&mut err, match kind {
Some(gen_borrow_kind), hir::ClosureKind::Coroutine(_) => {
|kind, var_span| { SecondBorrowUsePlaceCoroutine { place: desc_place, var_span }
use crate::session_diagnostics::CaptureVarCause::*;
match kind {
hir::ClosureKind::Coroutine(_) => {
SecondBorrowUsePlaceCoroutine { place: desc_place, var_span }
}
hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
SecondBorrowUsePlaceClosure { place: desc_place, var_span }
}
} }
}, hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
); SecondBorrowUsePlaceClosure { place: desc_place, var_span }
}
}
});
} }
if union_type_name != "" { if union_type_name != "" {
@ -2961,7 +2931,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
err.span_label(borrow_span, "borrowed value does not live long enough"); err.span_label(borrow_span, "borrowed value does not live long enough");
err.span_label(drop_span, format!("`{name}` dropped here while still borrowed")); err.span_label(drop_span, format!("`{name}` dropped here while still borrowed"));
borrow_spans.args_subdiag(self.dcx(), &mut err, |args_span| { borrow_spans.args_subdiag(&mut err, |args_span| {
crate::session_diagnostics::CaptureArgLabel::Capture { crate::session_diagnostics::CaptureArgLabel::Capture {
is_within: borrow_spans.for_coroutine(), is_within: borrow_spans.for_coroutine(),
args_span, args_span,
@ -3219,7 +3189,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
None, None,
); );
borrow_spans.args_subdiag(self.dcx(), &mut err, |args_span| { borrow_spans.args_subdiag(&mut err, |args_span| {
crate::session_diagnostics::CaptureArgLabel::Capture { crate::session_diagnostics::CaptureArgLabel::Capture {
is_within: borrow_spans.for_coroutine(), is_within: borrow_spans.for_coroutine(),
args_span, args_span,
@ -3680,7 +3650,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
"assign", "assign",
); );
loan_spans.var_subdiag(self.dcx(), &mut err, Some(loan.kind), |kind, var_span| { loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
use crate::session_diagnostics::CaptureVarCause::*; use crate::session_diagnostics::CaptureVarCause::*;
match kind { match kind {
hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span }, hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
@ -3698,7 +3668,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place); let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place);
loan_spans.var_subdiag(self.dcx(), &mut err, Some(loan.kind), |kind, var_span| { loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
use crate::session_diagnostics::CaptureVarCause::*; use crate::session_diagnostics::CaptureVarCause::*;
match kind { match kind {
hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span }, hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },

View File

@ -5,7 +5,7 @@ use crate::session_diagnostics::{
CaptureVarKind, CaptureVarPathUseCause, OnClosureNote, CaptureVarKind, CaptureVarPathUseCause, OnClosureNote,
}; };
use rustc_errors::MultiSpan; use rustc_errors::MultiSpan;
use rustc_errors::{Applicability, Diag, DiagCtxtHandle}; use rustc_errors::{Applicability, Diag};
use rustc_hir::def::{CtorKind, Namespace}; use rustc_hir::def::{CtorKind, Namespace};
use rustc_hir::CoroutineKind; use rustc_hir::CoroutineKind;
use rustc_hir::{self as hir, LangItem}; use rustc_hir::{self as hir, LangItem};
@ -130,16 +130,13 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() { if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() {
let did = did.expect_local(); let did = did.expect_local();
if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) { if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) {
diag.subdiagnostic( diag.subdiagnostic(OnClosureNote::InvokedTwice {
self.dcx(), place_name: &ty::place_to_string_for_capture(
OnClosureNote::InvokedTwice { self.infcx.tcx,
place_name: &ty::place_to_string_for_capture( hir_place,
self.infcx.tcx, ),
hir_place, span: *span,
), });
span: *span,
},
);
return true; return true;
} }
} }
@ -152,13 +149,10 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
if let ty::Closure(did, _) = self.body.local_decls[target].ty.kind() { if let ty::Closure(did, _) = self.body.local_decls[target].ty.kind() {
let did = did.expect_local(); let did = did.expect_local();
if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) { if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) {
diag.subdiagnostic( diag.subdiagnostic(OnClosureNote::MovedTwice {
self.dcx(), place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place),
OnClosureNote::MovedTwice { span: *span,
place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place), });
span: *span,
},
);
return true; return true;
} }
} }
@ -591,14 +585,9 @@ impl UseSpans<'_> {
/// Add a span label to the arguments of the closure, if it exists. /// Add a span label to the arguments of the closure, if it exists.
#[allow(rustc::diagnostic_outside_of_impl)] #[allow(rustc::diagnostic_outside_of_impl)]
pub(super) fn args_subdiag( pub(super) fn args_subdiag(self, err: &mut Diag<'_>, f: impl FnOnce(Span) -> CaptureArgLabel) {
self,
dcx: DiagCtxtHandle<'_>,
err: &mut Diag<'_>,
f: impl FnOnce(Span) -> CaptureArgLabel,
) {
if let UseSpans::ClosureUse { args_span, .. } = self { if let UseSpans::ClosureUse { args_span, .. } = self {
err.subdiagnostic(dcx, f(args_span)); err.subdiagnostic(f(args_span));
} }
} }
@ -607,7 +596,6 @@ impl UseSpans<'_> {
#[allow(rustc::diagnostic_outside_of_impl)] #[allow(rustc::diagnostic_outside_of_impl)]
pub(super) fn var_path_only_subdiag( pub(super) fn var_path_only_subdiag(
self, self,
dcx: DiagCtxtHandle<'_>,
err: &mut Diag<'_>, err: &mut Diag<'_>,
action: crate::InitializationRequiringAction, action: crate::InitializationRequiringAction,
) { ) {
@ -616,26 +604,20 @@ impl UseSpans<'_> {
if let UseSpans::ClosureUse { closure_kind, path_span, .. } = self { if let UseSpans::ClosureUse { closure_kind, path_span, .. } = self {
match closure_kind { match closure_kind {
hir::ClosureKind::Coroutine(_) => { hir::ClosureKind::Coroutine(_) => {
err.subdiagnostic( err.subdiagnostic(match action {
dcx, Borrow => BorrowInCoroutine { path_span },
match action { MatchOn | Use => UseInCoroutine { path_span },
Borrow => BorrowInCoroutine { path_span }, Assignment => AssignInCoroutine { path_span },
MatchOn | Use => UseInCoroutine { path_span }, PartialAssignment => AssignPartInCoroutine { path_span },
Assignment => AssignInCoroutine { path_span }, });
PartialAssignment => AssignPartInCoroutine { path_span },
},
);
} }
hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => { hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
err.subdiagnostic( err.subdiagnostic(match action {
dcx, Borrow => BorrowInClosure { path_span },
match action { MatchOn | Use => UseInClosure { path_span },
Borrow => BorrowInClosure { path_span }, Assignment => AssignInClosure { path_span },
MatchOn | Use => UseInClosure { path_span }, PartialAssignment => AssignPartInClosure { path_span },
Assignment => AssignInClosure { path_span }, });
PartialAssignment => AssignPartInClosure { path_span },
},
);
} }
} }
} }
@ -645,32 +627,28 @@ impl UseSpans<'_> {
#[allow(rustc::diagnostic_outside_of_impl)] #[allow(rustc::diagnostic_outside_of_impl)]
pub(super) fn var_subdiag( pub(super) fn var_subdiag(
self, self,
dcx: DiagCtxtHandle<'_>,
err: &mut Diag<'_>, err: &mut Diag<'_>,
kind: Option<rustc_middle::mir::BorrowKind>, kind: Option<rustc_middle::mir::BorrowKind>,
f: impl FnOnce(hir::ClosureKind, Span) -> CaptureVarCause, f: impl FnOnce(hir::ClosureKind, Span) -> CaptureVarCause,
) { ) {
if let UseSpans::ClosureUse { closure_kind, capture_kind_span, path_span, .. } = self { if let UseSpans::ClosureUse { closure_kind, capture_kind_span, path_span, .. } = self {
if capture_kind_span != path_span { if capture_kind_span != path_span {
err.subdiagnostic( err.subdiagnostic(match kind {
dcx, Some(kd) => match kd {
match kind { rustc_middle::mir::BorrowKind::Shared
Some(kd) => match kd { | rustc_middle::mir::BorrowKind::Fake(_) => {
rustc_middle::mir::BorrowKind::Shared CaptureVarKind::Immut { kind_span: capture_kind_span }
| rustc_middle::mir::BorrowKind::Fake(_) => { }
CaptureVarKind::Immut { kind_span: capture_kind_span }
}
rustc_middle::mir::BorrowKind::Mut { .. } => { rustc_middle::mir::BorrowKind::Mut { .. } => {
CaptureVarKind::Mut { kind_span: capture_kind_span } CaptureVarKind::Mut { kind_span: capture_kind_span }
} }
},
None => CaptureVarKind::Move { kind_span: capture_kind_span },
}, },
); None => CaptureVarKind::Move { kind_span: capture_kind_span },
});
}; };
let diag = f(closure_kind, path_span); let diag = f(closure_kind, path_span);
err.subdiagnostic(dcx, diag); err.subdiagnostic(diag);
} }
} }
@ -1042,15 +1020,12 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
CallKind::FnCall { fn_trait_id, self_ty } CallKind::FnCall { fn_trait_id, self_ty }
if self.infcx.tcx.is_lang_item(fn_trait_id, LangItem::FnOnce) => if self.infcx.tcx.is_lang_item(fn_trait_id, LangItem::FnOnce) =>
{ {
err.subdiagnostic( err.subdiagnostic(CaptureReasonLabel::Call {
self.dcx(), fn_call_span,
CaptureReasonLabel::Call { place_name: &place_name,
fn_call_span, is_partial,
place_name: &place_name, is_loop_message,
is_partial, });
is_loop_message,
},
);
// Check if the move occurs on a value because of a call on a closure that comes // Check if the move occurs on a value because of a call on a closure that comes
// from a type parameter `F: FnOnce()`. If so, we provide a targeted `note`: // from a type parameter `F: FnOnce()`. If so, we provide a targeted `note`:
// ``` // ```
@ -1119,27 +1094,20 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
); );
err.span_note(span, fluent::borrowck_moved_a_fn_once_in_call_call); err.span_note(span, fluent::borrowck_moved_a_fn_once_in_call_call);
} else { } else {
err.subdiagnostic( err.subdiagnostic(CaptureReasonNote::FnOnceMoveInCall { var_span });
self.dcx(),
CaptureReasonNote::FnOnceMoveInCall { var_span },
);
} }
} }
CallKind::Operator { self_arg, trait_id, .. } => { CallKind::Operator { self_arg, trait_id, .. } => {
let self_arg = self_arg.unwrap(); let self_arg = self_arg.unwrap();
err.subdiagnostic( err.subdiagnostic(CaptureReasonLabel::OperatorUse {
self.dcx(), fn_call_span,
CaptureReasonLabel::OperatorUse { place_name: &place_name,
fn_call_span, is_partial,
place_name: &place_name, is_loop_message,
is_partial, });
is_loop_message,
},
);
if self.fn_self_span_reported.insert(fn_span) { if self.fn_self_span_reported.insert(fn_span) {
let lang = self.infcx.tcx.lang_items(); let lang = self.infcx.tcx.lang_items();
err.subdiagnostic( err.subdiagnostic(
self.dcx(),
if [lang.not_trait(), lang.deref_trait(), lang.neg_trait()] if [lang.not_trait(), lang.deref_trait(), lang.neg_trait()]
.contains(&Some(trait_id)) .contains(&Some(trait_id))
{ {
@ -1164,14 +1132,11 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
); );
let func = tcx.def_path_str(method_did); let func = tcx.def_path_str(method_did);
err.subdiagnostic( err.subdiagnostic(CaptureReasonNote::FuncTakeSelf {
self.dcx(), func,
CaptureReasonNote::FuncTakeSelf { place_name: place_name.clone(),
func, span: self_arg.span,
place_name: place_name.clone(), });
span: self_arg.span,
},
);
} }
let parent_did = tcx.parent(method_did); let parent_did = tcx.parent(method_did);
let parent_self_ty = let parent_self_ty =
@ -1185,10 +1150,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result)) matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result))
}); });
if is_option_or_result && maybe_reinitialized_locations_is_empty { if is_option_or_result && maybe_reinitialized_locations_is_empty {
err.subdiagnostic( err.subdiagnostic(CaptureReasonLabel::BorrowContent { var_span });
self.dcx(),
CaptureReasonLabel::BorrowContent { var_span },
);
} }
if let Some((CallDesugaringKind::ForLoopIntoIter, _)) = desugaring { if let Some((CallDesugaringKind::ForLoopIntoIter, _)) = desugaring {
let ty = moved_place.ty(self.body, tcx).ty; let ty = moved_place.ty(self.body, tcx).ty;
@ -1202,24 +1164,18 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
_ => false, _ => false,
}; };
if suggest { if suggest {
err.subdiagnostic( err.subdiagnostic(CaptureReasonSuggest::IterateSlice {
self.dcx(), ty,
CaptureReasonSuggest::IterateSlice { span: move_span.shrink_to_lo(),
ty, });
span: move_span.shrink_to_lo(),
},
);
} }
err.subdiagnostic( err.subdiagnostic(CaptureReasonLabel::ImplicitCall {
self.dcx(), fn_call_span,
CaptureReasonLabel::ImplicitCall { place_name: &place_name,
fn_call_span, is_partial,
place_name: &place_name, is_loop_message,
is_partial, });
is_loop_message,
},
);
// If the moved place was a `&mut` ref, then we can // If the moved place was a `&mut` ref, then we can
// suggest to reborrow it where it was moved, so it // suggest to reborrow it where it was moved, so it
// will still be valid by the time we get to the usage. // will still be valid by the time we get to the usage.
@ -1243,25 +1199,19 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
} }
} else { } else {
if let Some((CallDesugaringKind::Await, _)) = desugaring { if let Some((CallDesugaringKind::Await, _)) = desugaring {
err.subdiagnostic( err.subdiagnostic(CaptureReasonLabel::Await {
self.dcx(), fn_call_span,
CaptureReasonLabel::Await { place_name: &place_name,
fn_call_span, is_partial,
place_name: &place_name, is_loop_message,
is_partial, });
is_loop_message,
},
);
} else { } else {
err.subdiagnostic( err.subdiagnostic(CaptureReasonLabel::MethodCall {
self.dcx(), fn_call_span,
CaptureReasonLabel::MethodCall { place_name: &place_name,
fn_call_span, is_partial,
place_name: &place_name, is_loop_message,
is_partial, });
is_loop_message,
},
);
} }
// Erase and shadow everything that could be passed to the new infcx. // Erase and shadow everything that could be passed to the new infcx.
let ty = moved_place.ty(self.body, tcx).ty; let ty = moved_place.ty(self.body, tcx).ty;
@ -1276,12 +1226,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
) )
&& self.infcx.can_eq(self.param_env, ty, self_ty) && self.infcx.can_eq(self.param_env, ty, self_ty)
{ {
err.subdiagnostic( err.subdiagnostic(CaptureReasonSuggest::FreshReborrow {
self.dcx(), span: move_span.shrink_to_hi(),
CaptureReasonSuggest::FreshReborrow { });
span: move_span.shrink_to_hi(),
},
);
has_sugg = true; has_sugg = true;
} }
if let Some(clone_trait) = tcx.lang_items().clone_trait() { if let Some(clone_trait) = tcx.lang_items().clone_trait() {
@ -1368,20 +1315,17 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
} }
} else { } else {
if move_span != span || is_loop_message { if move_span != span || is_loop_message {
err.subdiagnostic( err.subdiagnostic(CaptureReasonLabel::MovedHere {
self.dcx(), move_span,
CaptureReasonLabel::MovedHere { is_partial,
move_span, is_move_msg,
is_partial, is_loop_message,
is_move_msg, });
is_loop_message,
},
);
} }
// If the move error occurs due to a loop, don't show // If the move error occurs due to a loop, don't show
// another message for the same span // another message for the same span
if !is_loop_message { if !is_loop_message {
move_spans.var_subdiag(self.dcx(), err, None, |kind, var_span| match kind { move_spans.var_subdiag(err, None, |kind, var_span| match kind {
hir::ClosureKind::Coroutine(_) => { hir::ClosureKind::Coroutine(_) => {
CaptureVarCause::PartialMoveUseInCoroutine { var_span, is_partial } CaptureVarCause::PartialMoveUseInCoroutine { var_span, is_partial }
} }

View File

@ -579,15 +579,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
self.suggest_cloning(err, place_ty, expr, self.find_expr(other_span), None); self.suggest_cloning(err, place_ty, expr, self.find_expr(other_span), None);
} }
err.subdiagnostic( err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label {
self.dcx(), is_partial_move: false,
crate::session_diagnostics::TypeNoCopy::Label { ty: place_ty,
is_partial_move: false, place: &place_desc,
ty: place_ty, span,
place: &place_desc, });
span,
},
);
} else { } else {
binds_to.sort(); binds_to.sort();
binds_to.dedup(); binds_to.dedup();
@ -620,17 +617,14 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
); );
} }
err.subdiagnostic( err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label {
self.dcx(), is_partial_move: false,
crate::session_diagnostics::TypeNoCopy::Label { ty: place_ty,
is_partial_move: false, place: &place_desc,
ty: place_ty, span: use_span,
place: &place_desc, });
span: use_span,
},
);
use_spans.args_subdiag(self.dcx(), err, |args_span| { use_spans.args_subdiag(err, |args_span| {
crate::session_diagnostics::CaptureArgLabel::MoveOutPlace { crate::session_diagnostics::CaptureArgLabel::MoveOutPlace {
place: place_desc, place: place_desc,
args_span, args_span,
@ -733,15 +727,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
self.suggest_cloning(err, bind_to.ty, expr, None, None); self.suggest_cloning(err, bind_to.ty, expr, None, None);
} }
err.subdiagnostic( err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label {
self.dcx(), is_partial_move: false,
crate::session_diagnostics::TypeNoCopy::Label { ty: bind_to.ty,
is_partial_move: false, place: place_desc,
ty: bind_to.ty, span: binding_span,
place: place_desc, });
span: binding_span,
},
);
} }
} }

View File

@ -230,7 +230,6 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
} }
if suggest { if suggest {
borrow_spans.var_subdiag( borrow_spans.var_subdiag(
self.dcx(),
&mut err, &mut err,
Some(mir::BorrowKind::Mut { kind: mir::MutBorrowKind::Default }), Some(mir::BorrowKind::Mut { kind: mir::MutBorrowKind::Default }),
|_kind, var_span| { |_kind, var_span| {

View File

@ -631,13 +631,13 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap(); let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
let upvar_def_span = self.infcx.tcx.hir().span(def_hir); let upvar_def_span = self.infcx.tcx.hir().span(def_hir);
let upvar_span = upvars_map.get(&def_hir).unwrap().span; let upvar_span = upvars_map.get(&def_hir).unwrap().span;
diag.subdiagnostic(self.dcx(), VarHereDenote::Defined { span: upvar_def_span }); diag.subdiagnostic(VarHereDenote::Defined { span: upvar_def_span });
diag.subdiagnostic(self.dcx(), VarHereDenote::Captured { span: upvar_span }); diag.subdiagnostic(VarHereDenote::Captured { span: upvar_span });
} }
} }
if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() { if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
diag.subdiagnostic(self.dcx(), VarHereDenote::FnMutInferred { span: fr_span }); diag.subdiagnostic(VarHereDenote::FnMutInferred { span: fr_span });
} }
self.suggest_move_on_borrowing_closure(&mut diag); self.suggest_move_on_borrowing_closure(&mut diag);
@ -810,7 +810,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
}, },
}; };
diag.subdiagnostic(self.dcx(), err_category); diag.subdiagnostic(err_category);
self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr); self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
self.suggest_adding_lifetime_params(&mut diag, *fr, *outlived_fr); self.suggest_adding_lifetime_params(&mut diag, *fr, *outlived_fr);
@ -1008,7 +1008,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
ident.span, ident.span,
"calling this method introduces the `impl`'s `'static` requirement", "calling this method introduces the `impl`'s `'static` requirement",
); );
err.subdiagnostic(self.dcx(), RequireStaticErr::UsedImpl { multi_span }); err.subdiagnostic(RequireStaticErr::UsedImpl { multi_span });
err.span_suggestion_verbose( err.span_suggestion_verbose(
span.shrink_to_hi(), span.shrink_to_hi(),
"consider relaxing the implicit `'static` requirement", "consider relaxing the implicit `'static` requirement",

View File

@ -96,7 +96,7 @@ impl<G: EmissionGuarantee> Diagnostic<'_, G> for TargetFeatureDisableOrEnable<'_
diag.span(span); diag.span(span);
}; };
if let Some(missing_features) = self.missing_features { if let Some(missing_features) = self.missing_features {
diag.subdiagnostic(dcx, missing_features); diag.subdiagnostic(missing_features);
} }
diag.arg("features", self.features.join(", ")); diag.arg("features", self.features.join(", "));
diag diag

View File

@ -126,7 +126,7 @@ impl<G: EmissionGuarantee> Diagnostic<'_, G> for TargetFeatureDisableOrEnable<'_
diag.span(span); diag.span(span);
}; };
if let Some(missing_features) = self.missing_features { if let Some(missing_features) = self.missing_features {
diag.subdiagnostic(dcx, missing_features); diag.subdiagnostic(missing_features);
} }
diag.arg("features", self.features.join(", ")); diag.arg("features", self.features.join(", "));
diag diag

View File

@ -138,7 +138,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> {
// FIXME(effects) revisit this // FIXME(effects) revisit this
if !tcx.is_const_trait_impl_raw(data.impl_def_id) { if !tcx.is_const_trait_impl_raw(data.impl_def_id) {
let span = tcx.def_span(data.impl_def_id); let span = tcx.def_span(data.impl_def_id);
err.subdiagnostic(tcx.dcx(), errors::NonConstImplNote { span }); err.subdiagnostic(errors::NonConstImplNote { span });
} }
} }
} }

View File

@ -1192,11 +1192,8 @@ impl<'a, G: EmissionGuarantee> Diag<'a, G> {
/// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of /// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of
/// interpolated variables). /// interpolated variables).
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
pub fn subdiagnostic( pub fn subdiagnostic(&mut self, subdiagnostic: impl Subdiagnostic) -> &mut Self {
&mut self, let dcx = self.dcx;
dcx: DiagCtxtHandle<'_>,
subdiagnostic: impl Subdiagnostic,
) -> &mut Self {
subdiagnostic.add_to_diag_with(self, &|diag, msg| { subdiagnostic.add_to_diag_with(self, &|diag, msg| {
let args = diag.args.iter(); let args = diag.args.iter();
let msg = diag.subdiagnostic_message_to_diagnostic_message(msg); let msg = diag.subdiagnostic_message_to_diagnostic_message(msg);

View File

@ -7,7 +7,7 @@ use crate::mbe::{
use rustc_ast::token::{self, Token, TokenKind}; use rustc_ast::token::{self, Token, TokenKind};
use rustc_ast::tokenstream::TokenStream; use rustc_ast::tokenstream::TokenStream;
use rustc_ast_pretty::pprust; use rustc_ast_pretty::pprust;
use rustc_errors::{Applicability, Diag, DiagCtxtHandle, DiagMessage}; use rustc_errors::{Applicability, Diag, DiagMessage};
use rustc_macros::Subdiagnostic; use rustc_macros::Subdiagnostic;
use rustc_parse::parser::{Parser, Recovery}; use rustc_parse::parser::{Parser, Recovery};
use rustc_span::source_map::SourceMap; use rustc_span::source_map::SourceMap;
@ -61,7 +61,7 @@ pub(super) fn failed_to_match_macro<'cx>(
err.span_label(cx.source_map().guess_head_span(def_span), "when calling this macro"); err.span_label(cx.source_map().guess_head_span(def_span), "when calling this macro");
} }
annotate_doc_comment(cx.sess.dcx(), &mut err, psess.source_map(), span); annotate_doc_comment(&mut err, psess.source_map(), span);
if let Some(span) = remaining_matcher.span() { if let Some(span) = remaining_matcher.span() {
err.span_note(span, format!("while trying to match {remaining_matcher}")); err.span_note(span, format!("while trying to match {remaining_matcher}"));
@ -324,17 +324,12 @@ enum ExplainDocComment {
}, },
} }
pub(super) fn annotate_doc_comment( pub(super) fn annotate_doc_comment(err: &mut Diag<'_>, sm: &SourceMap, span: Span) {
dcx: DiagCtxtHandle<'_>,
err: &mut Diag<'_>,
sm: &SourceMap,
span: Span,
) {
if let Ok(src) = sm.span_to_snippet(span) { if let Ok(src) = sm.span_to_snippet(span) {
if src.starts_with("///") || src.starts_with("/**") { if src.starts_with("///") || src.starts_with("/**") {
err.subdiagnostic(dcx, ExplainDocComment::Outer { span }); err.subdiagnostic(ExplainDocComment::Outer { span });
} else if src.starts_with("//!") || src.starts_with("/*!") { } else if src.starts_with("//!") || src.starts_with("/*!") {
err.subdiagnostic(dcx, ExplainDocComment::Inner { span }); err.subdiagnostic(ExplainDocComment::Inner { span });
} }
} }
} }

View File

@ -463,7 +463,7 @@ pub fn compile_declarative_macro(
let sp = token.span.substitute_dummy(def.span); let sp = token.span.substitute_dummy(def.span);
let mut err = sess.dcx().struct_span_err(sp, s); let mut err = sess.dcx().struct_span_err(sp, s);
err.span_label(sp, msg); err.span_label(sp, msg);
annotate_doc_comment(sess.dcx(), &mut err, sess.source_map(), sp); annotate_doc_comment(&mut err, sess.source_map(), sp);
let guar = err.emit(); let guar = err.emit();
return dummy_syn_ext(guar); return dummy_syn_ext(guar);
} }

View File

@ -403,74 +403,56 @@ fn emit_orphan_check_error<'tcx>(
match *ty.kind() { match *ty.kind() {
ty::Slice(_) => { ty::Slice(_) => {
if is_foreign { if is_foreign {
diag.subdiagnostic( diag.subdiagnostic(errors::OnlyCurrentTraitsForeign { span });
tcx.dcx(),
errors::OnlyCurrentTraitsForeign { span },
);
} else { } else {
diag.subdiagnostic( diag.subdiagnostic(errors::OnlyCurrentTraitsName {
tcx.dcx(), span,
errors::OnlyCurrentTraitsName { span, name: "slices" }, name: "slices",
); });
} }
} }
ty::Array(..) => { ty::Array(..) => {
if is_foreign { if is_foreign {
diag.subdiagnostic( diag.subdiagnostic(errors::OnlyCurrentTraitsForeign { span });
tcx.dcx(),
errors::OnlyCurrentTraitsForeign { span },
);
} else { } else {
diag.subdiagnostic( diag.subdiagnostic(errors::OnlyCurrentTraitsName {
tcx.dcx(), span,
errors::OnlyCurrentTraitsName { span, name: "arrays" }, name: "arrays",
); });
} }
} }
ty::Tuple(..) => { ty::Tuple(..) => {
if is_foreign { if is_foreign {
diag.subdiagnostic( diag.subdiagnostic(errors::OnlyCurrentTraitsForeign { span });
tcx.dcx(),
errors::OnlyCurrentTraitsForeign { span },
);
} else { } else {
diag.subdiagnostic( diag.subdiagnostic(errors::OnlyCurrentTraitsName {
tcx.dcx(), span,
errors::OnlyCurrentTraitsName { span, name: "tuples" }, name: "tuples",
); });
} }
} }
ty::Alias(ty::Opaque, ..) => { ty::Alias(ty::Opaque, ..) => {
diag.subdiagnostic(tcx.dcx(), errors::OnlyCurrentTraitsOpaque { span }); diag.subdiagnostic(errors::OnlyCurrentTraitsOpaque { span });
} }
ty::RawPtr(ptr_ty, mutbl) => { ty::RawPtr(ptr_ty, mutbl) => {
if !trait_ref.self_ty().has_param() { if !trait_ref.self_ty().has_param() {
diag.subdiagnostic( diag.subdiagnostic(errors::OnlyCurrentTraitsPointerSugg {
tcx.dcx(), wrapper_span: impl_.self_ty.span,
errors::OnlyCurrentTraitsPointerSugg { struct_span: item.span.shrink_to_lo(),
wrapper_span: impl_.self_ty.span, mut_key: mutbl.prefix_str(),
struct_span: item.span.shrink_to_lo(), ptr_ty,
mut_key: mutbl.prefix_str(), });
ptr_ty,
},
);
} }
diag.subdiagnostic( diag.subdiagnostic(errors::OnlyCurrentTraitsPointer { span, pointer: ty });
tcx.dcx(),
errors::OnlyCurrentTraitsPointer { span, pointer: ty },
);
} }
ty::Adt(adt_def, _) => { ty::Adt(adt_def, _) => {
diag.subdiagnostic( diag.subdiagnostic(errors::OnlyCurrentTraitsAdt {
tcx.dcx(), span,
errors::OnlyCurrentTraitsAdt { name: tcx.def_path_str(adt_def.did()),
span, });
name: tcx.def_path_str(adt_def.did()),
},
);
} }
_ => { _ => {
diag.subdiagnostic(tcx.dcx(), errors::OnlyCurrentTraitsTy { span, ty }); diag.subdiagnostic(errors::OnlyCurrentTraitsTy { span, ty });
} }
} }
} }

View File

@ -246,7 +246,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let semi = expr.span.shrink_to_hi().with_hi(semi_span.hi()); let semi = expr.span.shrink_to_hi().with_hi(semi_span.hi());
let sugg = crate::errors::RemoveSemiForCoerce { expr: expr.span, ret, semi }; let sugg = crate::errors::RemoveSemiForCoerce { expr: expr.span, ret, semi };
diag.subdiagnostic(self.dcx(), sugg); diag.subdiagnostic(sugg);
} }
/// When the previously checked expression (the scrutinee) diverges, /// When the previously checked expression (the scrutinee) diverges,

View File

@ -1005,25 +1005,19 @@ impl<'a, 'tcx> CastCheck<'tcx> {
if let Some((deref_ty, _)) = derefed { if let Some((deref_ty, _)) = derefed {
// Give a note about what the expr derefs to. // Give a note about what the expr derefs to.
if deref_ty != self.expr_ty.peel_refs() { if deref_ty != self.expr_ty.peel_refs() {
err.subdiagnostic( err.subdiagnostic(errors::DerefImplsIsEmpty {
fcx.dcx(), span: self.expr_span,
errors::DerefImplsIsEmpty { deref_ty: fcx.ty_to_string(deref_ty),
span: self.expr_span, });
deref_ty: fcx.ty_to_string(deref_ty),
},
);
} }
// Create a multipart suggestion: add `!` and `.is_empty()` in // Create a multipart suggestion: add `!` and `.is_empty()` in
// place of the cast. // place of the cast.
err.subdiagnostic( err.subdiagnostic(errors::UseIsEmpty {
fcx.dcx(), lo: self.expr_span.shrink_to_lo(),
errors::UseIsEmpty { hi: self.span.with_lo(self.expr_span.hi()),
lo: self.expr_span.shrink_to_lo(), expr_ty: fcx.ty_to_string(self.expr_ty),
hi: self.span.with_lo(self.expr_span.hi()), });
expr_ty: fcx.ty_to_string(self.expr_ty),
},
);
} }
} }
} }

View File

@ -1782,20 +1782,14 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
} }
let rpid_def_span = fcx.tcx.def_span(rpit_def_id); let rpid_def_span = fcx.tcx.def_span(rpit_def_id);
err.subdiagnostic( err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
fcx.tcx.dcx(), start_sp: rpid_def_span.with_hi(rpid_def_span.lo() + BytePos(4)),
SuggestBoxingForReturnImplTrait::ChangeReturnType { end_sp: rpid_def_span.shrink_to_hi(),
start_sp: rpid_def_span.with_hi(rpid_def_span.lo() + BytePos(4)), });
end_sp: rpid_def_span.shrink_to_hi(),
},
);
let (starts, ends) = let (starts, ends) =
arm_spans.map(|span| (span.shrink_to_lo(), span.shrink_to_hi())).unzip(); arm_spans.map(|span| (span.shrink_to_lo(), span.shrink_to_hi())).unzip();
err.subdiagnostic( err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr { starts, ends });
fcx.tcx.dcx(),
SuggestBoxingForReturnImplTrait::BoxReturnExpr { starts, ends },
);
} }
fn report_return_mismatched_types<'a>( fn report_return_mismatched_types<'a>(

View File

@ -384,7 +384,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if let Some(sp) = if let Some(sp) =
tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp) tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp)
{ {
err.subdiagnostic(self.dcx(), ExprParenthesesNeeded::surrounding(*sp)); err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
} }
oprnd_t = Ty::new_error(tcx, err.emit()); oprnd_t = Ty::new_error(tcx, err.emit());
} }
@ -2018,10 +2018,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.shrink_to_hi() .shrink_to_hi()
.to(range_end.span); .to(range_end.span);
err.subdiagnostic( err.subdiagnostic(TypeMismatchFruTypo { expr_span: range_start.span, fru_span, expr });
self.dcx(),
TypeMismatchFruTypo { expr_span: range_start.span, fru_span, expr },
);
// Suppress any range expr type mismatches // Suppress any range expr type mismatches
self.dcx().try_steal_replace_and_emit_err( self.dcx().try_steal_replace_and_emit_err(

View File

@ -1435,7 +1435,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
{ {
// The user provided `ptr::null()`, but the function expects // The user provided `ptr::null()`, but the function expects
// `ptr::null_mut()`. // `ptr::null_mut()`.
err.subdiagnostic(self.dcx(), SuggestPtrNullMut { span: arg.span }); err.subdiagnostic(SuggestPtrNullMut { span: arg.span });
} }
} }

View File

@ -460,16 +460,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// but those checks need to be a bit more delicate and the benefit is diminishing. // but those checks need to be a bit more delicate and the benefit is diminishing.
if self.can_eq(self.param_env, found_ty_inner, peeled) && error_tys_equate_as_ref { if self.can_eq(self.param_env, found_ty_inner, peeled) && error_tys_equate_as_ref {
let sugg = prefix_wrap(".as_ref()"); let sugg = prefix_wrap(".as_ref()");
err.subdiagnostic( err.subdiagnostic(errors::SuggestConvertViaMethod {
self.dcx(), span: expr.span.shrink_to_hi(),
errors::SuggestConvertViaMethod { sugg,
span: expr.span.shrink_to_hi(), expected,
sugg, found,
expected, borrow_removal_span,
found, });
borrow_removal_span,
},
);
return true; return true;
} else if let Some((deref_ty, _)) = } else if let Some((deref_ty, _)) =
self.autoderef(expr.span, found_ty_inner).silence_errors().nth(1) self.autoderef(expr.span, found_ty_inner).silence_errors().nth(1)
@ -477,16 +474,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&& error_tys_equate_as_ref && error_tys_equate_as_ref
{ {
let sugg = prefix_wrap(".as_deref()"); let sugg = prefix_wrap(".as_deref()");
err.subdiagnostic( err.subdiagnostic(errors::SuggestConvertViaMethod {
self.dcx(), span: expr.span.shrink_to_hi(),
errors::SuggestConvertViaMethod { sugg,
span: expr.span.shrink_to_hi(), expected,
sugg, found,
expected, borrow_removal_span,
found, });
borrow_removal_span,
},
);
return true; return true;
} else if let ty::Adt(adt, _) = found_ty_inner.peel_refs().kind() } else if let ty::Adt(adt, _) = found_ty_inner.peel_refs().kind()
&& self.tcx.is_lang_item(adt.did(), LangItem::String) && self.tcx.is_lang_item(adt.did(), LangItem::String)
@ -573,7 +567,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
end: span.shrink_to_hi(), end: span.shrink_to_hi(),
}, },
}; };
err.subdiagnostic(self.dcx(), suggest_boxing); err.subdiagnostic(suggest_boxing);
true true
} else { } else {
@ -814,28 +808,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
match &fn_decl.output { match &fn_decl.output {
&hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => { &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => {
// `fn main()` must return `()`, do not suggest changing return type // `fn main()` must return `()`, do not suggest changing return type
err.subdiagnostic(self.dcx(), errors::ExpectedReturnTypeLabel::Unit { span }); err.subdiagnostic(errors::ExpectedReturnTypeLabel::Unit { span });
return true; return true;
} }
&hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => { &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
if let Some(found) = found.make_suggestable(self.tcx, false, None) { if let Some(found) = found.make_suggestable(self.tcx, false, None) {
err.subdiagnostic( err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
self.dcx(), span,
errors::AddReturnTypeSuggestion::Add { span, found: found.to_string() }, found: found.to_string(),
); });
return true; return true;
} else if let Some(sugg) = suggest_impl_trait(self, self.param_env, found) { } else if let Some(sugg) = suggest_impl_trait(self, self.param_env, found) {
err.subdiagnostic( err.subdiagnostic(errors::AddReturnTypeSuggestion::Add { span, found: sugg });
self.dcx(),
errors::AddReturnTypeSuggestion::Add { span, found: sugg },
);
return true; return true;
} else { } else {
// FIXME: if `found` could be `impl Iterator` we should suggest that. // FIXME: if `found` could be `impl Iterator` we should suggest that.
err.subdiagnostic( err.subdiagnostic(errors::AddReturnTypeSuggestion::MissingHere { span });
self.dcx(),
errors::AddReturnTypeSuggestion::MissingHere { span },
);
return true; return true;
} }
} }
@ -856,19 +844,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
debug!(?found); debug!(?found);
if found.is_suggestable(self.tcx, false) { if found.is_suggestable(self.tcx, false) {
if ty.span.is_empty() { if ty.span.is_empty() {
err.subdiagnostic( err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
self.dcx(), span: ty.span,
errors::AddReturnTypeSuggestion::Add { found: found.to_string(),
span: ty.span, });
found: found.to_string(),
},
);
return true; return true;
} else { } else {
err.subdiagnostic( err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
self.dcx(), span: ty.span,
errors::ExpectedReturnTypeLabel::Other { span: ty.span, expected }, expected,
); });
} }
} }
} else { } else {
@ -883,10 +868,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let ty = self.normalize(hir_ty.span, ty); let ty = self.normalize(hir_ty.span, ty);
let ty = self.tcx.instantiate_bound_regions_with_erased(ty); let ty = self.tcx.instantiate_bound_regions_with_erased(ty);
if self.can_coerce(expected, ty) { if self.can_coerce(expected, ty) {
err.subdiagnostic( err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
self.dcx(), span: hir_ty.span,
errors::ExpectedReturnTypeLabel::Other { span: hir_ty.span, expected }, expected,
); });
self.try_suggest_return_impl_trait(err, expected, found, fn_id); self.try_suggest_return_impl_trait(err, expected, found, fn_id);
self.note_caller_chooses_ty_for_ty_param(err, expected, found); self.note_caller_chooses_ty_for_ty_param(err, expected, found);
return true; return true;
@ -905,13 +890,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
found: Ty<'tcx>, found: Ty<'tcx>,
) { ) {
if let ty::Param(expected_ty_as_param) = expected.kind() { if let ty::Param(expected_ty_as_param) = expected.kind() {
diag.subdiagnostic( diag.subdiagnostic(errors::NoteCallerChoosesTyForTyParam {
self.dcx(), ty_param_name: expected_ty_as_param.name,
errors::NoteCallerChoosesTyForTyParam { found_ty: found,
ty_param_name: expected_ty_as_param.name, });
found_ty: found,
},
);
} }
} }
@ -1136,7 +1118,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let sp = self.tcx.sess.source_map().start_point(expr.span).with_parent(None); let sp = self.tcx.sess.source_map().start_point(expr.span).with_parent(None);
if let Some(sp) = self.tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp) { if let Some(sp) = self.tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
// `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }` // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
err.subdiagnostic(self.dcx(), ExprParenthesesNeeded::surrounding(*sp)); err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
true true
} else { } else {
false false
@ -1250,7 +1232,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else { } else {
return false; return false;
}; };
diag.subdiagnostic(self.dcx(), subdiag); diag.subdiagnostic(subdiag);
return true; return true;
} }
} }

View File

@ -3729,22 +3729,19 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if impls_trait(trait_info.def_id) { if impls_trait(trait_info.def_id) {
self.suggest_valid_traits(err, item_name, vec![trait_info.def_id], false); self.suggest_valid_traits(err, item_name, vec![trait_info.def_id], false);
} else { } else {
err.subdiagnostic( err.subdiagnostic(CandidateTraitNote {
self.dcx(), span: self.tcx.def_span(trait_info.def_id),
CandidateTraitNote { trait_name: self.tcx.def_path_str(trait_info.def_id),
span: self.tcx.def_span(trait_info.def_id), item_name,
trait_name: self.tcx.def_path_str(trait_info.def_id), action_or_ty: if trait_missing_method {
item_name, "NONE".to_string()
action_or_ty: if trait_missing_method { } else {
"NONE".to_string() param_type.map_or_else(
} else { || "implement".to_string(), // FIXME: it might only need to be imported into scope, not implemented.
param_type.map_or_else( |p| p.to_string(),
|| "implement".to_string(), // FIXME: it might only need to be imported into scope, not implemented. )
|p| p.to_string(),
)
},
}, },
); });
} }
} }
trait_infos => { trait_infos => {

View File

@ -820,7 +820,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// If the previous expression was a block expression, suggest parentheses // If the previous expression was a block expression, suggest parentheses
// (turning this into a binary subtraction operation instead.) // (turning this into a binary subtraction operation instead.)
// for example, `{2} - 2` -> `({2}) - 2` (see src\test\ui\parser\expr-as-stmt.rs) // for example, `{2} - 2` -> `({2}) - 2` (see src\test\ui\parser\expr-as-stmt.rs)
err.subdiagnostic(self.dcx(), ExprParenthesesNeeded::surrounding(*sp)); err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
} else { } else {
match actual.kind() { match actual.kind() {
Uint(_) if op == hir::UnOp::Neg => { Uint(_) if op == hir::UnOp::Neg => {

View File

@ -892,7 +892,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
arm_ty, arm_ty,
arm_span, arm_span,
) { ) {
err.subdiagnostic(self.dcx(), subdiag); err.subdiagnostic(subdiag);
} }
} }
}, },
@ -918,7 +918,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
else_ty, else_ty,
else_span, else_span,
) { ) {
err.subdiagnostic(self.dcx(), subdiag); err.subdiagnostic(subdiag);
} }
} }
ObligationCauseCode::LetElse => { ObligationCauseCode::LetElse => {

View File

@ -369,7 +369,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
trait_predicates: trait_predicates.join(", "), trait_predicates: trait_predicates.join(", "),
} }
}; };
err.subdiagnostic(self.dcx(), suggestion); err.subdiagnostic(suggestion);
} }
pub(super) fn report_placeholder_failure( pub(super) fn report_placeholder_failure(

View File

@ -121,7 +121,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
span_low: cause.span.shrink_to_lo(), span_low: cause.span.shrink_to_lo(),
span_high: cause.span.shrink_to_hi(), span_high: cause.span.shrink_to_hi(),
}; };
diag.subdiagnostic(self.dcx(), sugg); diag.subdiagnostic(sugg);
} }
_ => { _ => {
// More than one matching variant. // More than one matching variant.
@ -130,7 +130,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
cause_span: cause.span, cause_span: cause.span,
compatible_variants, compatible_variants,
}; };
diag.subdiagnostic(self.dcx(), sugg); diag.subdiagnostic(sugg);
} }
} }
} }
@ -202,10 +202,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
}, },
(_, Some(ty)) if self.same_type_modulo_infer(exp_found.expected, ty) => { (_, Some(ty)) if self.same_type_modulo_infer(exp_found.expected, ty) => {
// FIXME: Seems like we can't have a suggestion and a note with different spans in a single subdiagnostic // FIXME: Seems like we can't have a suggestion and a note with different spans in a single subdiagnostic
diag.subdiagnostic( diag.subdiagnostic(ConsiderAddingAwait::FutureSugg {
self.dcx(), span: exp_span.shrink_to_hi(),
ConsiderAddingAwait::FutureSugg { span: exp_span.shrink_to_hi() }, });
);
Some(ConsiderAddingAwait::FutureSuggNote { span: exp_span }) Some(ConsiderAddingAwait::FutureSuggNote { span: exp_span })
} }
(Some(ty), _) if self.same_type_modulo_infer(ty, exp_found.found) => match cause.code() (Some(ty), _) if self.same_type_modulo_infer(ty, exp_found.found) => match cause.code()
@ -233,7 +232,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
_ => None, _ => None,
}; };
if let Some(subdiag) = subdiag { if let Some(subdiag) = subdiag {
diag.subdiagnostic(self.dcx(), subdiag); diag.subdiagnostic(subdiag);
} }
} }
@ -269,7 +268,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
} else { } else {
return; return;
}; };
diag.subdiagnostic(self.dcx(), suggestion); diag.subdiagnostic(suggestion);
} }
} }
} }
@ -401,15 +400,15 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
(true, false) => FunctionPointerSuggestion::UseRef { span, fn_name }, (true, false) => FunctionPointerSuggestion::UseRef { span, fn_name },
(false, true) => FunctionPointerSuggestion::RemoveRef { span, fn_name }, (false, true) => FunctionPointerSuggestion::RemoveRef { span, fn_name },
(true, true) => { (true, true) => {
diag.subdiagnostic(self.dcx(), FnItemsAreDistinct); diag.subdiagnostic(FnItemsAreDistinct);
FunctionPointerSuggestion::CastRef { span, fn_name, sig: *sig } FunctionPointerSuggestion::CastRef { span, fn_name, sig: *sig }
} }
(false, false) => { (false, false) => {
diag.subdiagnostic(self.dcx(), FnItemsAreDistinct); diag.subdiagnostic(FnItemsAreDistinct);
FunctionPointerSuggestion::Cast { span, fn_name, sig: *sig } FunctionPointerSuggestion::Cast { span, fn_name, sig: *sig }
} }
}; };
diag.subdiagnostic(self.dcx(), sugg); diag.subdiagnostic(sugg);
} }
(ty::FnDef(did1, args1), ty::FnDef(did2, args2)) => { (ty::FnDef(did1, args1), ty::FnDef(did2, args2)) => {
let expected_sig = let expected_sig =
@ -418,7 +417,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
&(self.normalize_fn_sig)(self.tcx.fn_sig(*did2).instantiate(self.tcx, args2)); &(self.normalize_fn_sig)(self.tcx.fn_sig(*did2).instantiate(self.tcx, args2));
if self.same_type_modulo_infer(*expected_sig, *found_sig) { if self.same_type_modulo_infer(*expected_sig, *found_sig) {
diag.subdiagnostic(self.dcx(), FnUniqTypes); diag.subdiagnostic(FnUniqTypes);
} }
if !self.same_type_modulo_infer(*found_sig, *expected_sig) if !self.same_type_modulo_infer(*found_sig, *expected_sig)
@ -447,7 +446,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
} }
}; };
diag.subdiagnostic(self.dcx(), sug); diag.subdiagnostic(sug);
} }
(ty::FnDef(did, args), ty::FnPtr(sig)) => { (ty::FnDef(did, args), ty::FnPtr(sig)) => {
let expected_sig = let expected_sig =
@ -466,7 +465,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
format!("{fn_name} as {found_sig}") format!("{fn_name} as {found_sig}")
}; };
diag.subdiagnostic(self.dcx(), FnConsiderCasting { casting }); diag.subdiagnostic(FnConsiderCasting { casting });
} }
_ => { _ => {
return; return;
@ -889,7 +888,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
let diag = self.consider_returning_binding_diag(blk, expected_ty); let diag = self.consider_returning_binding_diag(blk, expected_ty);
match diag { match diag {
Some(diag) => { Some(diag) => {
err.subdiagnostic(self.dcx(), diag); err.subdiagnostic(diag);
true true
} }
None => false, None => false,

View File

@ -1405,7 +1405,7 @@ impl<'a> LintDiagnostic<'a, ()> for NonLocalDefinitionsDiag {
diag.note(fluent::lint_macro_to_change); diag.note(fluent::lint_macro_to_change);
} }
if let Some(cargo_update) = cargo_update { if let Some(cargo_update) = cargo_update {
diag.subdiagnostic(diag.dcx, cargo_update); diag.subdiagnostic(cargo_update);
} }
if has_trait { if has_trait {
@ -1471,7 +1471,7 @@ impl<'a> LintDiagnostic<'a, ()> for NonLocalDefinitionsDiag {
diag.note(fluent::lint_non_local_definitions_deprecation); diag.note(fluent::lint_non_local_definitions_deprecation);
if let Some(cargo_update) = cargo_update { if let Some(cargo_update) = cargo_update {
diag.subdiagnostic(diag.dcx, cargo_update); diag.subdiagnostic(cargo_update);
} }
} }
} }
@ -1957,7 +1957,7 @@ impl<'a> LintDiagnostic<'a, ()> for UnusedDef<'_, '_> {
diag.note(note.to_string()); diag.note(note.to_string());
} }
if let Some(sugg) = self.suggestion { if let Some(sugg) = self.suggestion {
diag.subdiagnostic(diag.dcx, sugg); diag.subdiagnostic(sugg);
} }
} }
} }

View File

@ -335,7 +335,7 @@ impl DiagnosticDeriveVariantBuilder {
} }
} }
(Meta::Path(_), "subdiagnostic") => { (Meta::Path(_), "subdiagnostic") => {
return Ok(quote! { diag.subdiagnostic(diag.dcx, #binding); }); return Ok(quote! { diag.subdiagnostic(#binding); });
} }
_ => (), _ => (),
} }

View File

@ -176,7 +176,7 @@ impl<'a, G: EmissionGuarantee> rustc_errors::LintDiagnostic<'a, G> for Deprecate
diag.arg("has_note", false); diag.arg("has_note", false);
} }
if let Some(sub) = self.sub { if let Some(sub) = self.sub {
diag.subdiagnostic(diag.dcx, sub); diag.subdiagnostic(sub);
} }
} }
} }

View File

@ -1137,7 +1137,7 @@ fn report_non_exhaustive_match<'p, 'tcx>(
let all_arms_have_guards = arms.iter().all(|arm_id| thir[*arm_id].guard.is_some()); let all_arms_have_guards = arms.iter().all(|arm_id| thir[*arm_id].guard.is_some());
if !is_empty_match && all_arms_have_guards { if !is_empty_match && all_arms_have_guards {
err.subdiagnostic(cx.tcx.dcx(), NonExhaustiveMatchAllArmsGuarded); err.subdiagnostic(NonExhaustiveMatchAllArmsGuarded);
} }
if let Some((span, sugg)) = suggestion { if let Some((span, sugg)) = suggestion {
err.span_suggestion_verbose(span, msg, sugg, Applicability::HasPlaceholders); err.span_suggestion_verbose(span, msg, sugg, Applicability::HasPlaceholders);

View File

@ -104,7 +104,7 @@ impl<'a> LintDiagnostic<'a, ()> for MustNotSupend<'_, '_> {
diag.primary_message(fluent::mir_transform_must_not_suspend); diag.primary_message(fluent::mir_transform_must_not_suspend);
diag.span_label(self.yield_sp, fluent::_subdiag::label); diag.span_label(self.yield_sp, fluent::_subdiag::label);
if let Some(reason) = self.reason { if let Some(reason) = self.reason {
diag.subdiagnostic(diag.dcx, reason); diag.subdiagnostic(reason);
} }
diag.span_help(self.src_sp, fluent::_subdiag::help); diag.span_help(self.src_sp, fluent::_subdiag::help);
diag.arg("pre", self.pre); diag.arg("pre", self.pre);

View File

@ -666,7 +666,7 @@ impl<'a> Parser<'a> {
{ {
err.note("you may be trying to write a c-string literal"); err.note("you may be trying to write a c-string literal");
err.note("c-string literals require Rust 2021 or later"); err.note("c-string literals require Rust 2021 or later");
err.subdiagnostic(self.dcx(), HelpUseLatestEdition::new()); err.subdiagnostic(HelpUseLatestEdition::new());
} }
// `pub` may be used for an item or `pub(crate)` // `pub` may be used for an item or `pub(crate)`
@ -2357,7 +2357,7 @@ impl<'a> Parser<'a> {
let mut err = self.dcx().struct_span_err(span, msg); let mut err = self.dcx().struct_span_err(span, msg);
let sp = self.psess.source_map().start_point(self.token.span); let sp = self.psess.source_map().start_point(self.token.span);
if let Some(sp) = self.psess.ambiguous_block_expr_parse.borrow().get(&sp) { if let Some(sp) = self.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
err.subdiagnostic(self.dcx(), ExprParenthesesNeeded::surrounding(*sp)); err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
} }
err.span_label(span, "expected expression"); err.span_label(span, "expected expression");

View File

@ -1461,7 +1461,7 @@ impl<'a> Parser<'a> {
// If the input is something like `if a { 1 } else { 2 } | if a { 3 } else { 4 }` // If the input is something like `if a { 1 } else { 2 } | if a { 3 } else { 4 }`
// then suggest parens around the lhs. // then suggest parens around the lhs.
if let Some(sp) = this.psess.ambiguous_block_expr_parse.borrow().get(&lo) { if let Some(sp) = this.psess.ambiguous_block_expr_parse.borrow().get(&lo) {
err.subdiagnostic(this.dcx(), ExprParenthesesNeeded::surrounding(*sp)); err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
} }
err err
}) })

View File

@ -1966,7 +1966,7 @@ impl<'a> Parser<'a> {
if self.token.kind == token::Not { if self.token.kind == token::Not {
if let Err(mut err) = self.unexpected() { if let Err(mut err) = self.unexpected() {
// Encounter the macro invocation // Encounter the macro invocation
err.subdiagnostic(self.dcx(), MacroExpandsToAdtField { adt_ty }); err.subdiagnostic(MacroExpandsToAdtField { adt_ty });
return Err(err); return Err(err);
} }
} }
@ -2382,13 +2382,10 @@ impl<'a> Parser<'a> {
.into_iter() .into_iter()
.any(|s| self.prev_token.is_ident_named(s)); .any(|s| self.prev_token.is_ident_named(s));
err.subdiagnostic( err.subdiagnostic(errors::FnTraitMissingParen {
self.dcx(), span: self.prev_token.span,
errors::FnTraitMissingParen { machine_applicable,
span: self.prev_token.span, });
machine_applicable,
},
);
} }
return Err(err); return Err(err);
} }

View File

@ -851,7 +851,7 @@ impl<'a> Parser<'a> {
let sp = self.psess.source_map().start_point(self.token.span); let sp = self.psess.source_map().start_point(self.token.span);
if let Some(sp) = self.psess.ambiguous_block_expr_parse.borrow().get(&sp) { if let Some(sp) = self.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
err.subdiagnostic(self.dcx(), ExprParenthesesNeeded::surrounding(*sp)); err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
} }
Err(err) Err(err)

View File

@ -334,12 +334,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
Some((import, _, true)) if should_remove_import && !import.is_glob() => { Some((import, _, true)) if should_remove_import && !import.is_glob() => {
// Simple case - remove the entire import. Due to the above match arm, this can // Simple case - remove the entire import. Due to the above match arm, this can
// only be a single use so just remove it entirely. // only be a single use so just remove it entirely.
err.subdiagnostic( err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport {
self.tcx.dcx(), span: import.use_span_with_attributes,
errors::ToolOnlyRemoveUnnecessaryImport { });
span: import.use_span_with_attributes,
},
);
} }
Some((import, span, _)) => { Some((import, span, _)) => {
self.add_suggestion_for_rename_of_use(&mut err, name, import, span); self.add_suggestion_for_rename_of_use(&mut err, name, import, span);
@ -405,12 +402,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
} }
if let Some(suggestion) = suggestion { if let Some(suggestion) = suggestion {
err.subdiagnostic( err.subdiagnostic(ChangeImportBindingSuggestion { span: binding_span, suggestion });
self.dcx(),
ChangeImportBindingSuggestion { span: binding_span, suggestion },
);
} else { } else {
err.subdiagnostic(self.dcx(), ChangeImportBinding { span: binding_span }); err.subdiagnostic(ChangeImportBinding { span: binding_span });
} }
} }
@ -458,20 +452,19 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
// previous imports. // previous imports.
if found_closing_brace { if found_closing_brace {
if let Some(span) = extend_span_to_previous_binding(self.tcx.sess, span) { if let Some(span) = extend_span_to_previous_binding(self.tcx.sess, span) {
err.subdiagnostic(self.dcx(), errors::ToolOnlyRemoveUnnecessaryImport { span }); err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport { span });
} else { } else {
// Remove the entire line if we cannot extend the span back, this indicates an // Remove the entire line if we cannot extend the span back, this indicates an
// `issue_52891::{self}` case. // `issue_52891::{self}` case.
err.subdiagnostic( err.subdiagnostic(errors::RemoveUnnecessaryImport {
self.dcx(), span: import.use_span_with_attributes,
errors::RemoveUnnecessaryImport { span: import.use_span_with_attributes }, });
);
} }
return; return;
} }
err.subdiagnostic(self.dcx(), errors::RemoveUnnecessaryImport { span }); err.subdiagnostic(errors::RemoveUnnecessaryImport { span });
} }
pub(crate) fn lint_if_path_starts_with_module( pub(crate) fn lint_if_path_starts_with_module(
@ -682,10 +675,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
.dcx() .dcx()
.create_err(errors::VariableIsNotBoundInAllPatterns { multispan: msp, name }); .create_err(errors::VariableIsNotBoundInAllPatterns { multispan: msp, name });
for sp in target_sp { for sp in target_sp {
err.subdiagnostic(self.dcx(), errors::PatternDoesntBindName { span: sp, name }); err.subdiagnostic(errors::PatternDoesntBindName { span: sp, name });
} }
for sp in origin_sp { for sp in origin_sp {
err.subdiagnostic(self.dcx(), errors::VariableNotInAllPatterns { span: sp }); err.subdiagnostic(errors::VariableNotInAllPatterns { span: sp });
} }
if could_be_path { if could_be_path {
let import_suggestions = self.lookup_import_candidates( let import_suggestions = self.lookup_import_candidates(
@ -1446,12 +1439,12 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
); );
if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules { if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules {
err.subdiagnostic(self.dcx(), MaybeMissingMacroRulesName { span: ident.span }); err.subdiagnostic(MaybeMissingMacroRulesName { span: ident.span });
return; return;
} }
if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) { if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
err.subdiagnostic(self.dcx(), ExplicitUnsafeTraits { span: ident.span, ident }); err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
return; return;
} }
@ -1467,14 +1460,14 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
let scope = self.local_macro_def_scopes[&def_id]; let scope = self.local_macro_def_scopes[&def_id];
let parent_nearest = parent_scope.module.nearest_parent_mod(); let parent_nearest = parent_scope.module.nearest_parent_mod();
if Some(parent_nearest) == scope.opt_def_id() { if Some(parent_nearest) == scope.opt_def_id() {
err.subdiagnostic(self.dcx(), MacroDefinedLater { span: unused_ident.span }); err.subdiagnostic(MacroDefinedLater { span: unused_ident.span });
err.subdiagnostic(self.dcx(), MacroSuggMovePosition { span: ident.span, ident }); err.subdiagnostic(MacroSuggMovePosition { span: ident.span, ident });
return; return;
} }
} }
if self.macro_names.contains(&ident.normalize_to_macros_2_0()) { if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
err.subdiagnostic(self.dcx(), AddedMacroUse); err.subdiagnostic(AddedMacroUse);
return; return;
} }
@ -1484,13 +1477,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
let span = self.def_span(def_id); let span = self.def_span(def_id);
let source_map = self.tcx.sess.source_map(); let source_map = self.tcx.sess.source_map();
let head_span = source_map.guess_head_span(span); let head_span = source_map.guess_head_span(span);
err.subdiagnostic( err.subdiagnostic(ConsiderAddingADerive {
self.dcx(), span: head_span.shrink_to_lo(),
ConsiderAddingADerive { suggestion: "#[derive(Default)]\n".to_string(),
span: head_span.shrink_to_lo(), });
suggestion: "#[derive(Default)]\n".to_string(),
},
);
} }
for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] { for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
if let Ok(binding) = self.early_resolve_ident_in_lexical_scope( if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
@ -1533,7 +1523,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
imported_ident: ident, imported_ident: ident,
imported_ident_desc: &desc, imported_ident_desc: &desc,
}; };
err.subdiagnostic(self.tcx.dcx(), note); err.subdiagnostic(note);
// Silence the 'unused import' warning we might get, // Silence the 'unused import' warning we might get,
// since this diagnostic already covers that import. // since this diagnostic already covers that import.
self.record_use(ident, binding, Used::Other); self.record_use(ident, binding, Used::Other);
@ -1544,7 +1534,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
imported_ident: ident, imported_ident: ident,
imported_ident_desc: &desc, imported_ident_desc: &desc,
}; };
err.subdiagnostic(self.tcx.dcx(), note); err.subdiagnostic(note);
return; return;
} }
} }
@ -1599,7 +1589,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
} }
}; };
did_label_def_span = true; did_label_def_span = true;
err.subdiagnostic(self.tcx.dcx(), label); err.subdiagnostic(label);
} }
let (span, msg, sugg) = if let SuggestionTarget::SimilarlyNamed = suggestion.target let (span, msg, sugg) = if let SuggestionTarget::SimilarlyNamed = suggestion.target
@ -1790,7 +1780,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
outer_ident_descr: this_res.descr(), outer_ident_descr: this_res.descr(),
outer_ident, outer_ident,
}; };
err.subdiagnostic(self.tcx.dcx(), label); err.subdiagnostic(label);
} }
} }
@ -1805,14 +1795,14 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
non_exhaustive = Some(attr.span); non_exhaustive = Some(attr.span);
} else if let Some(span) = ctor_fields_span { } else if let Some(span) = ctor_fields_span {
let label = errors::ConstructorPrivateIfAnyFieldPrivate { span }; let label = errors::ConstructorPrivateIfAnyFieldPrivate { span };
err.subdiagnostic(self.tcx.dcx(), label); err.subdiagnostic(label);
if let Res::Def(_, d) = res if let Res::Def(_, d) = res
&& let Some(fields) = self.field_visibility_spans.get(&d) && let Some(fields) = self.field_visibility_spans.get(&d)
{ {
let spans = fields.iter().map(|span| *span).collect(); let spans = fields.iter().map(|span| *span).collect();
let sugg = let sugg =
errors::ConsiderMakingTheFieldPublic { spans, number_of_fields: fields.len() }; errors::ConsiderMakingTheFieldPublic { spans, number_of_fields: fields.len() };
err.subdiagnostic(self.tcx.dcx(), sugg); err.subdiagnostic(sugg);
} }
} }
@ -1921,7 +1911,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
first, first,
dots: next_binding.is_some(), dots: next_binding.is_some(),
}; };
err.subdiagnostic(self.tcx.dcx(), note); err.subdiagnostic(note);
} }
// We prioritize shorter paths, non-core imports and direct imports over the alternatives. // We prioritize shorter paths, non-core imports and direct imports over the alternatives.
sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0] == "core", *reexport)); sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0] == "core", *reexport));
@ -1940,7 +1930,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
} else { } else {
errors::ImportIdent::Directly { span: dedup_span, ident, path } errors::ImportIdent::Directly { span: dedup_span, ident, path }
}; };
err.subdiagnostic(self.tcx.dcx(), sugg); err.subdiagnostic(sugg);
break; break;
} }
@ -2521,14 +2511,14 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
} }
let note = errors::FoundItemConfigureOut { span: name.span }; let note = errors::FoundItemConfigureOut { span: name.span };
err.subdiagnostic(self.tcx.dcx(), note); err.subdiagnostic(note);
if let MetaItemKind::List(nested) = &cfg.kind if let MetaItemKind::List(nested) = &cfg.kind
&& let NestedMetaItem::MetaItem(meta_item) = &nested[0] && let NestedMetaItem::MetaItem(meta_item) = &nested[0]
&& let MetaItemKind::NameValue(feature_name) = &meta_item.kind && let MetaItemKind::NameValue(feature_name) = &meta_item.kind
{ {
let note = errors::ItemWasBehindFeature { feature: feature_name.symbol }; let note = errors::ItemWasBehindFeature { feature: feature_name.symbol };
err.subdiagnostic(self.tcx.dcx(), note); err.subdiagnostic(note);
} }
} }
} }

View File

@ -1294,12 +1294,12 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
// exclude decl_macro // exclude decl_macro
if self.get_macro_by_def_id(def_id).macro_rules => if self.get_macro_by_def_id(def_id).macro_rules =>
{ {
err.subdiagnostic(self.dcx(), ConsiderAddingMacroExport { err.subdiagnostic( ConsiderAddingMacroExport {
span: binding.span, span: binding.span,
}); });
} }
_ => { _ => {
err.subdiagnostic(self.dcx(), ConsiderMarkingAsPub { err.subdiagnostic( ConsiderMarkingAsPub {
span: import.span, span: import.span,
ident, ident,
}); });

View File

@ -1109,14 +1109,11 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
Side::Start => (segment.ident.span.between(range.span), " @ ".into()), Side::Start => (segment.ident.span.between(range.span), " @ ".into()),
Side::End => (range.span.to(segment.ident.span), format!("{} @ ..", segment.ident)), Side::End => (range.span.to(segment.ident.span), format!("{} @ ..", segment.ident)),
}; };
err.subdiagnostic( err.subdiagnostic(errors::UnexpectedResUseAtOpInSlicePatWithRangeSugg {
self.r.dcx(), span,
errors::UnexpectedResUseAtOpInSlicePatWithRangeSugg { ident: segment.ident,
span, snippet,
ident: segment.ident, });
snippet,
},
);
} }
enum Side { enum Side {
@ -1208,13 +1205,10 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
}); });
if let Some(param) = param { if let Some(param) = param {
err.subdiagnostic( err.subdiagnostic(errors::UnexpectedResChangeTyToConstParamSugg {
self.r.dcx(), span: param.shrink_to_lo(),
errors::UnexpectedResChangeTyToConstParamSugg { applicability,
span: param.shrink_to_lo(), });
applicability,
},
);
} }
} }

View File

@ -178,23 +178,23 @@ pub fn add_feature_diagnostics_for_issue<G: EmissionGuarantee>(
inject_span: Option<Span>, inject_span: Option<Span>,
) { ) {
if let Some(n) = find_feature_issue(feature, issue) { if let Some(n) = find_feature_issue(feature, issue) {
err.subdiagnostic(sess.dcx(), FeatureDiagnosticForIssue { n }); err.subdiagnostic(FeatureDiagnosticForIssue { n });
} }
// #23973: do not suggest `#![feature(...)]` if we are in beta/stable // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
if sess.psess.unstable_features.is_nightly_build() { if sess.psess.unstable_features.is_nightly_build() {
if feature_from_cli { if feature_from_cli {
err.subdiagnostic(sess.dcx(), CliFeatureDiagnosticHelp { feature }); err.subdiagnostic(CliFeatureDiagnosticHelp { feature });
} else if let Some(span) = inject_span { } else if let Some(span) = inject_span {
err.subdiagnostic(sess.dcx(), FeatureDiagnosticSuggestion { feature, span }); err.subdiagnostic(FeatureDiagnosticSuggestion { feature, span });
} else { } else {
err.subdiagnostic(sess.dcx(), FeatureDiagnosticHelp { feature }); err.subdiagnostic(FeatureDiagnosticHelp { feature });
} }
if sess.opts.unstable_opts.ui_testing { if sess.opts.unstable_opts.ui_testing {
err.subdiagnostic(sess.dcx(), SuggestUpgradeCompiler::ui_testing()); err.subdiagnostic(SuggestUpgradeCompiler::ui_testing());
} else if let Some(suggestion) = SuggestUpgradeCompiler::new() { } else if let Some(suggestion) = SuggestUpgradeCompiler::new() {
err.subdiagnostic(sess.dcx(), suggestion); err.subdiagnostic(suggestion);
} }
} }
} }

View File

@ -4705,14 +4705,11 @@ fn hint_missing_borrow<'tcx>(
} }
if !to_borrow.is_empty() { if !to_borrow.is_empty() {
err.subdiagnostic(infcx.dcx(), errors::AdjustSignatureBorrow::Borrow { to_borrow }); err.subdiagnostic(errors::AdjustSignatureBorrow::Borrow { to_borrow });
} }
if !remove_borrow.is_empty() { if !remove_borrow.is_empty() {
err.subdiagnostic( err.subdiagnostic(errors::AdjustSignatureBorrow::RemoveBorrow { remove_borrow });
infcx.dcx(),
errors::AdjustSignatureBorrow::RemoveBorrow { remove_borrow },
);
} }
} }

View File

@ -566,7 +566,7 @@ pub fn report_msg<'tcx>(
let is_local = machine.is_local(frame_info); let is_local = machine.is_local(frame_info);
// No span for non-local frames and the first frame (which is the error site). // No span for non-local frames and the first frame (which is the error site).
if is_local && idx > 0 { if is_local && idx > 0 {
err.subdiagnostic(err.dcx, frame_info.as_note(machine.tcx)); err.subdiagnostic(frame_info.as_note(machine.tcx));
} else { } else {
let sm = sess.source_map(); let sm = sess.source_map();
let span = sm.span_to_embeddable_string(frame_info.span); let span = sm.span_to_embeddable_string(frame_info.span);