1
Fork 0

Rename DiagnosticBuilder as Diag.

Much better!

Note that this involves renaming (and updating the value of)
`DIAGNOSTIC_BUILDER` in clippy.
This commit is contained in:
Nicholas Nethercote 2024-02-23 10:20:45 +11:00
parent 4e1f9bd528
commit 899cb40809
153 changed files with 1136 additions and 1367 deletions

View file

@ -1,5 +1,5 @@
use rustc_errors::{ use rustc_errors::{
codes::*, AddToDiagnostic, DiagnosticArgFromDisplay, DiagnosticBuilder, EmissionGuarantee, codes::*, AddToDiagnostic, Diag, DiagnosticArgFromDisplay, EmissionGuarantee,
SubdiagnosticMessageOp, SubdiagnosticMessageOp,
}; };
use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_macros::{Diagnostic, Subdiagnostic};
@ -44,7 +44,7 @@ pub struct InvalidAbiReason(pub &'static str);
impl AddToDiagnostic for InvalidAbiReason { impl AddToDiagnostic for InvalidAbiReason {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_: F, _: F,
) { ) {
#[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::untranslatable_diagnostic)]

View file

@ -2,8 +2,7 @@
use rustc_ast::ParamKindOrd; use rustc_ast::ParamKindOrd;
use rustc_errors::{ use rustc_errors::{
codes::*, AddToDiagnostic, Applicability, DiagnosticBuilder, EmissionGuarantee, codes::*, AddToDiagnostic, Applicability, Diag, EmissionGuarantee, SubdiagnosticMessageOp,
SubdiagnosticMessageOp,
}; };
use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_span::{symbol::Ident, Span, Symbol}; use rustc_span::{symbol::Ident, Span, Symbol};
@ -377,7 +376,7 @@ pub struct EmptyLabelManySpans(pub Vec<Span>);
impl AddToDiagnostic for EmptyLabelManySpans { impl AddToDiagnostic for EmptyLabelManySpans {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_: F, _: F,
) { ) {
diag.span_labels(self.0, ""); diag.span_labels(self.0, "");
@ -738,7 +737,7 @@ pub struct StableFeature {
impl AddToDiagnostic for StableFeature { impl AddToDiagnostic for StableFeature {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_: F, _: F,
) { ) {
diag.arg("name", self.name); diag.arg("name", self.name);

View file

@ -2,7 +2,7 @@ use std::num::IntErrorKind;
use rustc_ast as ast; use rustc_ast as ast;
use rustc_errors::{ use rustc_errors::{
codes::*, Applicability, DiagCtxt, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic, Level, codes::*, Applicability, Diag, DiagCtxt, EmissionGuarantee, IntoDiagnostic, Level,
}; };
use rustc_macros::Diagnostic; use rustc_macros::Diagnostic;
use rustc_span::{Span, Symbol}; use rustc_span::{Span, Symbol};
@ -51,9 +51,9 @@ pub(crate) struct UnknownMetaItem<'a> {
// Manual implementation to be able to format `expected` items correctly. // Manual implementation to be able to format `expected` items correctly.
impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for UnknownMetaItem<'_> { impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for UnknownMetaItem<'_> {
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
let expected = self.expected.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>(); let expected = self.expected.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>();
DiagnosticBuilder::new(dcx, level, fluent::attr_unknown_meta_item) Diag::new(dcx, level, fluent::attr_unknown_meta_item)
.with_span(self.span) .with_span(self.span)
.with_code(E0541) .with_code(E0541)
.with_arg("item", self.item) .with_arg("item", self.item)
@ -198,8 +198,8 @@ pub(crate) struct UnsupportedLiteral {
} }
impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for UnsupportedLiteral { impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for UnsupportedLiteral {
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
let mut diag = DiagnosticBuilder::new( let mut diag = Diag::new(
dcx, dcx,
level, level,
match self.reason { match self.reason {

View file

@ -1,7 +1,7 @@
#![allow(rustc::diagnostic_outside_of_impl)] #![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)] #![allow(rustc::untranslatable_diagnostic)]
use rustc_errors::{codes::*, struct_span_code_err, DiagCtxt, DiagnosticBuilder}; use rustc_errors::{codes::*, struct_span_code_err, Diag, DiagCtxt};
use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::Span; use rustc_span::Span;
@ -17,7 +17,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
place: &str, place: &str,
borrow_place: &str, borrow_place: &str,
value_place: &str, value_place: &str,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
self.dcx().create_err(crate::session_diagnostics::MoveBorrow { self.dcx().create_err(crate::session_diagnostics::MoveBorrow {
place, place,
span, span,
@ -33,7 +33,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
desc: &str, desc: &str,
borrow_span: Span, borrow_span: Span,
borrow_desc: &str, borrow_desc: &str,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
struct_span_code_err!( struct_span_code_err!(
self.dcx(), self.dcx(),
span, span,
@ -53,7 +53,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
old_loan_span: Span, old_loan_span: Span,
old_opt_via: &str, old_opt_via: &str,
old_load_end_span: Option<Span>, old_load_end_span: Option<Span>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") }; let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") };
let mut err = struct_span_code_err!( let mut err = struct_span_code_err!(
self.dcx(), self.dcx(),
@ -100,7 +100,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
desc: &str, desc: &str,
old_loan_span: Span, old_loan_span: Span,
old_load_end_span: Option<Span>, old_load_end_span: Option<Span>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let mut err = struct_span_code_err!( let mut err = struct_span_code_err!(
self.dcx(), self.dcx(),
new_loan_span, new_loan_span,
@ -133,7 +133,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
noun_old: &str, noun_old: &str,
old_opt_via: &str, old_opt_via: &str,
previous_end_span: Option<Span>, previous_end_span: Option<Span>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let mut err = struct_span_code_err!( let mut err = struct_span_code_err!(
self.dcx(), self.dcx(),
new_loan_span, new_loan_span,
@ -165,7 +165,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
old_opt_via: &str, old_opt_via: &str,
previous_end_span: Option<Span>, previous_end_span: Option<Span>,
second_borrow_desc: &str, second_borrow_desc: &str,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let mut err = struct_span_code_err!( let mut err = struct_span_code_err!(
self.dcx(), self.dcx(),
new_loan_span, new_loan_span,
@ -197,7 +197,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
kind_old: &str, kind_old: &str,
msg_old: &str, msg_old: &str,
old_load_end_span: Option<Span>, old_load_end_span: Option<Span>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") }; let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") };
let mut err = struct_span_code_err!( let mut err = struct_span_code_err!(
self.dcx(), self.dcx(),
@ -238,7 +238,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
span: Span, span: Span,
borrow_span: Span, borrow_span: Span,
desc: &str, desc: &str,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
struct_span_code_err!( struct_span_code_err!(
self.dcx(), self.dcx(),
span, span,
@ -255,12 +255,12 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
span: Span, span: Span,
desc: &str, desc: &str,
is_arg: bool, is_arg: bool,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let msg = if is_arg { "to immutable argument" } else { "twice to immutable variable" }; let msg = if is_arg { "to immutable argument" } else { "twice to immutable variable" };
struct_span_code_err!(self.dcx(), span, E0384, "cannot assign {} {}", msg, desc) struct_span_code_err!(self.dcx(), span, E0384, "cannot assign {} {}", msg, desc)
} }
pub(crate) fn cannot_assign(&self, span: Span, desc: &str) -> DiagnosticBuilder<'tcx> { pub(crate) fn cannot_assign(&self, span: Span, desc: &str) -> Diag<'tcx> {
struct_span_code_err!(self.dcx(), span, E0594, "cannot assign to {}", desc) struct_span_code_err!(self.dcx(), span, E0594, "cannot assign to {}", desc)
} }
@ -268,7 +268,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
&self, &self,
move_from_span: Span, move_from_span: Span,
move_from_desc: &str, move_from_desc: &str,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
struct_span_code_err!( struct_span_code_err!(
self.dcx(), self.dcx(),
move_from_span, move_from_span,
@ -286,7 +286,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
move_from_span: Span, move_from_span: Span,
ty: Ty<'_>, ty: Ty<'_>,
is_index: Option<bool>, is_index: Option<bool>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let type_name = match (&ty.kind(), is_index) { let type_name = match (&ty.kind(), is_index) {
(&ty::Array(_, _), Some(true)) | (&ty::Array(_, _), None) => "array", (&ty::Array(_, _), Some(true)) | (&ty::Array(_, _), None) => "array",
(&ty::Slice(_), _) => "slice", (&ty::Slice(_), _) => "slice",
@ -307,7 +307,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
&self, &self,
move_from_span: Span, move_from_span: Span,
container_ty: Ty<'_>, container_ty: Ty<'_>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
struct_span_code_err!( struct_span_code_err!(
self.dcx(), self.dcx(),
move_from_span, move_from_span,
@ -324,7 +324,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
verb: &str, verb: &str,
optional_adverb_for_moved: &str, optional_adverb_for_moved: &str,
moved_path: Option<String>, moved_path: Option<String>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let moved_path = moved_path.map(|mp| format!(": `{mp}`")).unwrap_or_default(); let moved_path = moved_path.map(|mp| format!(": `{mp}`")).unwrap_or_default();
struct_span_code_err!( struct_span_code_err!(
@ -343,7 +343,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
span: Span, span: Span,
path: &str, path: &str,
reason: &str, reason: &str,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
struct_span_code_err!( struct_span_code_err!(
self.dcx(), self.dcx(),
span, span,
@ -361,7 +361,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
immutable_place: &str, immutable_place: &str,
immutable_section: &str, immutable_section: &str,
action: &str, action: &str,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
struct_span_code_err!( struct_span_code_err!(
self.dcx(), self.dcx(),
mutate_span, mutate_span,
@ -379,7 +379,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
&self, &self,
span: Span, span: Span,
yield_span: Span, yield_span: Span,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let coroutine_kind = self.body.coroutine.as_ref().unwrap().coroutine_kind; let coroutine_kind = self.body.coroutine.as_ref().unwrap().coroutine_kind;
struct_span_code_err!( struct_span_code_err!(
self.dcx(), self.dcx(),
@ -390,10 +390,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
.with_span_label(yield_span, "possible yield occurs here") .with_span_label(yield_span, "possible yield occurs here")
} }
pub(crate) fn cannot_borrow_across_destructor( pub(crate) fn cannot_borrow_across_destructor(&self, borrow_span: Span) -> Diag<'tcx> {
&self,
borrow_span: Span,
) -> DiagnosticBuilder<'tcx> {
struct_span_code_err!( struct_span_code_err!(
self.dcx(), self.dcx(),
borrow_span, borrow_span,
@ -402,11 +399,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
) )
} }
pub(crate) fn path_does_not_live_long_enough( pub(crate) fn path_does_not_live_long_enough(&self, span: Span, path: &str) -> Diag<'tcx> {
&self,
span: Span,
path: &str,
) -> DiagnosticBuilder<'tcx> {
struct_span_code_err!(self.dcx(), span, E0597, "{} does not live long enough", path,) struct_span_code_err!(self.dcx(), span, E0597, "{} does not live long enough", path,)
} }
@ -416,7 +409,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
return_kind: &str, return_kind: &str,
reference_desc: &str, reference_desc: &str,
path_desc: &str, path_desc: &str,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
struct_span_code_err!( struct_span_code_err!(
self.dcx(), self.dcx(),
span, span,
@ -439,7 +432,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
borrowed_path: &str, borrowed_path: &str,
capture_span: Span, capture_span: Span,
scope: &str, scope: &str,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
struct_span_code_err!( struct_span_code_err!(
self.dcx(), self.dcx(),
closure_span, closure_span,
@ -451,10 +444,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
.with_span_label(closure_span, format!("may outlive borrowed value {borrowed_path}")) .with_span_label(closure_span, format!("may outlive borrowed value {borrowed_path}"))
} }
pub(crate) fn thread_local_value_does_not_live_long_enough( pub(crate) fn thread_local_value_does_not_live_long_enough(&self, span: Span) -> Diag<'tcx> {
&self,
span: Span,
) -> DiagnosticBuilder<'tcx> {
struct_span_code_err!( struct_span_code_err!(
self.dcx(), self.dcx(),
span, span,
@ -463,10 +453,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
) )
} }
pub(crate) fn temporary_value_borrowed_for_too_long( pub(crate) fn temporary_value_borrowed_for_too_long(&self, span: Span) -> Diag<'tcx> {
&self,
span: Span,
) -> DiagnosticBuilder<'tcx> {
struct_span_code_err!(self.dcx(), span, E0716, "temporary value dropped while borrowed",) struct_span_code_err!(self.dcx(), span, E0716, "temporary value dropped while borrowed",)
} }
} }
@ -475,7 +462,7 @@ pub(crate) fn borrowed_data_escapes_closure<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
escape_span: Span, escape_span: Span,
escapes_from: &str, escapes_from: &str,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
struct_span_code_err!( struct_span_code_err!(
tcx.dcx(), tcx.dcx(),
escape_span, escape_span,

View file

@ -1,4 +1,4 @@
use rustc_errors::DiagnosticBuilder; use rustc_errors::Diag;
use rustc_infer::infer::canonical::Canonical; use rustc_infer::infer::canonical::Canonical;
use rustc_infer::infer::error_reporting::nice_region_error::NiceRegionError; use rustc_infer::infer::error_reporting::nice_region_error::NiceRegionError;
use rustc_infer::infer::region_constraints::Constraint; use rustc_infer::infer::region_constraints::Constraint;
@ -144,7 +144,7 @@ impl<'tcx> ToUniverseInfo<'tcx> for ! {
trait TypeOpInfo<'tcx> { trait TypeOpInfo<'tcx> {
/// Returns an error to be reported if rerunning the type op fails to /// Returns an error to be reported if rerunning the type op fails to
/// recover the error's cause. /// recover the error's cause.
fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> DiagnosticBuilder<'tcx>; fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> Diag<'tcx>;
fn base_universe(&self) -> ty::UniverseIndex; fn base_universe(&self) -> ty::UniverseIndex;
@ -154,7 +154,7 @@ trait TypeOpInfo<'tcx> {
cause: ObligationCause<'tcx>, cause: ObligationCause<'tcx>,
placeholder_region: ty::Region<'tcx>, placeholder_region: ty::Region<'tcx>,
error_region: Option<ty::Region<'tcx>>, error_region: Option<ty::Region<'tcx>>,
) -> Option<DiagnosticBuilder<'tcx>>; ) -> Option<Diag<'tcx>>;
#[instrument(level = "debug", skip(self, mbcx))] #[instrument(level = "debug", skip(self, mbcx))]
fn report_error( fn report_error(
@ -217,7 +217,7 @@ struct PredicateQuery<'tcx> {
} }
impl<'tcx> TypeOpInfo<'tcx> for PredicateQuery<'tcx> { impl<'tcx> TypeOpInfo<'tcx> for PredicateQuery<'tcx> {
fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> Diag<'tcx> {
tcx.dcx().create_err(HigherRankedLifetimeError { tcx.dcx().create_err(HigherRankedLifetimeError {
cause: Some(HigherRankedErrorCause::CouldNotProve { cause: Some(HigherRankedErrorCause::CouldNotProve {
predicate: self.canonical_query.value.value.predicate.to_string(), predicate: self.canonical_query.value.value.predicate.to_string(),
@ -236,7 +236,7 @@ impl<'tcx> TypeOpInfo<'tcx> for PredicateQuery<'tcx> {
cause: ObligationCause<'tcx>, cause: ObligationCause<'tcx>,
placeholder_region: ty::Region<'tcx>, placeholder_region: ty::Region<'tcx>,
error_region: Option<ty::Region<'tcx>>, error_region: Option<ty::Region<'tcx>>,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<Diag<'tcx>> {
let (infcx, key, _) = let (infcx, key, _) =
mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query); mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query);
let ocx = ObligationCtxt::new(&infcx); let ocx = ObligationCtxt::new(&infcx);
@ -254,7 +254,7 @@ impl<'tcx, T> TypeOpInfo<'tcx> for NormalizeQuery<'tcx, T>
where where
T: Copy + fmt::Display + TypeFoldable<TyCtxt<'tcx>> + 'tcx, T: Copy + fmt::Display + TypeFoldable<TyCtxt<'tcx>> + 'tcx,
{ {
fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> Diag<'tcx> {
tcx.dcx().create_err(HigherRankedLifetimeError { tcx.dcx().create_err(HigherRankedLifetimeError {
cause: Some(HigherRankedErrorCause::CouldNotNormalize { cause: Some(HigherRankedErrorCause::CouldNotNormalize {
value: self.canonical_query.value.value.value.to_string(), value: self.canonical_query.value.value.value.to_string(),
@ -273,7 +273,7 @@ where
cause: ObligationCause<'tcx>, cause: ObligationCause<'tcx>,
placeholder_region: ty::Region<'tcx>, placeholder_region: ty::Region<'tcx>,
error_region: Option<ty::Region<'tcx>>, error_region: Option<ty::Region<'tcx>>,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<Diag<'tcx>> {
let (infcx, key, _) = let (infcx, key, _) =
mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query); mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query);
let ocx = ObligationCtxt::new(&infcx); let ocx = ObligationCtxt::new(&infcx);
@ -297,7 +297,7 @@ struct AscribeUserTypeQuery<'tcx> {
} }
impl<'tcx> TypeOpInfo<'tcx> for AscribeUserTypeQuery<'tcx> { impl<'tcx> TypeOpInfo<'tcx> for AscribeUserTypeQuery<'tcx> {
fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> Diag<'tcx> {
// FIXME: This error message isn't great, but it doesn't show up in the existing UI tests, // FIXME: This error message isn't great, but it doesn't show up in the existing UI tests,
// and is only the fallback when the nice error fails. Consider improving this some more. // and is only the fallback when the nice error fails. Consider improving this some more.
tcx.dcx().create_err(HigherRankedLifetimeError { cause: None, span }) tcx.dcx().create_err(HigherRankedLifetimeError { cause: None, span })
@ -313,7 +313,7 @@ impl<'tcx> TypeOpInfo<'tcx> for AscribeUserTypeQuery<'tcx> {
cause: ObligationCause<'tcx>, cause: ObligationCause<'tcx>,
placeholder_region: ty::Region<'tcx>, placeholder_region: ty::Region<'tcx>,
error_region: Option<ty::Region<'tcx>>, error_region: Option<ty::Region<'tcx>>,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<Diag<'tcx>> {
let (infcx, key, _) = let (infcx, key, _) =
mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query); mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query);
let ocx = ObligationCtxt::new(&infcx); let ocx = ObligationCtxt::new(&infcx);
@ -323,7 +323,7 @@ impl<'tcx> TypeOpInfo<'tcx> for AscribeUserTypeQuery<'tcx> {
} }
impl<'tcx> TypeOpInfo<'tcx> for crate::type_check::InstantiateOpaqueType<'tcx> { impl<'tcx> TypeOpInfo<'tcx> for crate::type_check::InstantiateOpaqueType<'tcx> {
fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> Diag<'tcx> {
// FIXME: This error message isn't great, but it doesn't show up in the existing UI tests, // FIXME: This error message isn't great, but it doesn't show up in the existing UI tests,
// and is only the fallback when the nice error fails. Consider improving this some more. // and is only the fallback when the nice error fails. Consider improving this some more.
tcx.dcx().create_err(HigherRankedLifetimeError { cause: None, span }) tcx.dcx().create_err(HigherRankedLifetimeError { cause: None, span })
@ -339,7 +339,7 @@ impl<'tcx> TypeOpInfo<'tcx> for crate::type_check::InstantiateOpaqueType<'tcx> {
_cause: ObligationCause<'tcx>, _cause: ObligationCause<'tcx>,
placeholder_region: ty::Region<'tcx>, placeholder_region: ty::Region<'tcx>,
error_region: Option<ty::Region<'tcx>>, error_region: Option<ty::Region<'tcx>>,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<Diag<'tcx>> {
try_extract_error_from_region_constraints( try_extract_error_from_region_constraints(
mbcx.infcx, mbcx.infcx,
placeholder_region, placeholder_region,
@ -360,7 +360,7 @@ fn try_extract_error_from_fulfill_cx<'tcx>(
ocx: &ObligationCtxt<'_, 'tcx>, ocx: &ObligationCtxt<'_, 'tcx>,
placeholder_region: ty::Region<'tcx>, placeholder_region: ty::Region<'tcx>,
error_region: Option<ty::Region<'tcx>>, error_region: Option<ty::Region<'tcx>>,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<Diag<'tcx>> {
// We generally shouldn't have errors here because the query was // We generally shouldn't have errors here because the query was
// already run, but there's no point using `span_delayed_bug` // already run, but there's no point using `span_delayed_bug`
// when we're going to emit an error here anyway. // when we're going to emit an error here anyway.
@ -384,7 +384,7 @@ fn try_extract_error_from_region_constraints<'tcx>(
region_constraints: &RegionConstraintData<'tcx>, region_constraints: &RegionConstraintData<'tcx>,
mut region_var_origin: impl FnMut(RegionVid) -> RegionVariableOrigin, mut region_var_origin: impl FnMut(RegionVid) -> RegionVariableOrigin,
mut universe_of_region: impl FnMut(RegionVid) -> UniverseIndex, mut universe_of_region: impl FnMut(RegionVid) -> UniverseIndex,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<Diag<'tcx>> {
let placeholder_universe = match placeholder_region.kind() { let placeholder_universe = match placeholder_region.kind() {
ty::RePlaceholder(p) => p.universe, ty::RePlaceholder(p) => p.universe,
ty::ReVar(vid) => universe_of_region(vid), ty::ReVar(vid) => universe_of_region(vid),

View file

@ -6,7 +6,7 @@
use either::Either; use either::Either;
use rustc_data_structures::captures::Captures; use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::{codes::*, struct_span_code_err, Applicability, DiagnosticBuilder, MultiSpan}; use rustc_errors::{codes::*, struct_span_code_err, Applicability, Diag, MultiSpan};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res}; use rustc_hir::def::{DefKind, Res};
use rustc_hir::intravisit::{walk_block, walk_expr, Visitor}; use rustc_hir::intravisit::{walk_block, walk_expr, Visitor};
@ -334,7 +334,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
&mut self, &mut self,
mpi: MovePathIndex, mpi: MovePathIndex,
move_span: Span, move_span: Span,
err: &mut DiagnosticBuilder<'tcx>, err: &mut Diag<'tcx>,
in_pattern: &mut bool, in_pattern: &mut bool,
move_spans: UseSpans<'_>, move_spans: UseSpans<'_>,
) { ) {
@ -486,7 +486,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
desired_action: InitializationRequiringAction, desired_action: InitializationRequiringAction,
span: Span, span: Span,
use_spans: UseSpans<'tcx>, use_spans: UseSpans<'tcx>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
// We need all statements in the body where the binding was assigned to later find all // We need all statements in the body where the binding was assigned to later find all
// the branching code paths where the binding *wasn't* assigned to. // the branching code paths where the binding *wasn't* assigned to.
let inits = &self.move_data.init_path_map[mpi]; let inits = &self.move_data.init_path_map[mpi];
@ -633,7 +633,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
fn suggest_assign_value( fn suggest_assign_value(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
moved_place: PlaceRef<'tcx>, moved_place: PlaceRef<'tcx>,
sugg_span: Span, sugg_span: Span,
) { ) {
@ -672,7 +672,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
fn suggest_borrow_fn_like( fn suggest_borrow_fn_like(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
ty: Ty<'tcx>, ty: Ty<'tcx>,
move_sites: &[MoveSite], move_sites: &[MoveSite],
value_name: &str, value_name: &str,
@ -738,13 +738,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
true true
} }
fn suggest_cloning( fn suggest_cloning(&self, err: &mut Diag<'_>, ty: Ty<'tcx>, expr: &hir::Expr<'_>, span: Span) {
&self,
err: &mut DiagnosticBuilder<'_>,
ty: Ty<'tcx>,
expr: &hir::Expr<'_>,
span: Span,
) {
let tcx = self.infcx.tcx; let tcx = self.infcx.tcx;
// Try to find predicates on *generic params* that would allow copying `ty` // Try to find predicates on *generic params* that would allow copying `ty`
let suggestion = let suggestion =
@ -776,12 +770,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
} }
} }
fn suggest_adding_copy_bounds( fn suggest_adding_copy_bounds(&self, err: &mut Diag<'_>, ty: Ty<'tcx>, span: Span) {
&self,
err: &mut DiagnosticBuilder<'_>,
ty: Ty<'tcx>,
span: Span,
) {
let tcx = self.infcx.tcx; let tcx = self.infcx.tcx;
let generics = tcx.generics_of(self.mir_def_id()); let generics = tcx.generics_of(self.mir_def_id());
@ -891,7 +880,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
location: Location, location: Location,
(place, _span): (Place<'tcx>, Span), (place, _span): (Place<'tcx>, Span),
borrow: &BorrowData<'tcx>, borrow: &BorrowData<'tcx>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let borrow_spans = self.retrieve_borrow_spans(borrow); let borrow_spans = self.retrieve_borrow_spans(borrow);
let borrow_span = borrow_spans.args_or_use(); let borrow_span = borrow_spans.args_or_use();
@ -941,7 +930,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
(place, span): (Place<'tcx>, Span), (place, span): (Place<'tcx>, Span),
gen_borrow_kind: BorrowKind, gen_borrow_kind: BorrowKind,
issued_borrow: &BorrowData<'tcx>, issued_borrow: &BorrowData<'tcx>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let issued_spans = self.retrieve_borrow_spans(issued_borrow); let issued_spans = self.retrieve_borrow_spans(issued_borrow);
let issued_span = issued_spans.args_or_use(); let issued_span = issued_spans.args_or_use();
@ -1228,7 +1217,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
#[instrument(level = "debug", skip(self, err))] #[instrument(level = "debug", skip(self, err))]
fn suggest_using_local_if_applicable( fn suggest_using_local_if_applicable(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
location: Location, location: Location,
issued_borrow: &BorrowData<'tcx>, issued_borrow: &BorrowData<'tcx>,
explanation: BorrowExplanation<'tcx>, explanation: BorrowExplanation<'tcx>,
@ -1324,7 +1313,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
fn suggest_slice_method_if_applicable( fn suggest_slice_method_if_applicable(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
place: Place<'tcx>, place: Place<'tcx>,
borrowed_place: Place<'tcx>, borrowed_place: Place<'tcx>,
) { ) {
@ -1433,7 +1422,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
/// ``` /// ```
pub(crate) fn explain_iterator_advancement_in_for_loop_if_applicable( pub(crate) fn explain_iterator_advancement_in_for_loop_if_applicable(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
span: Span, span: Span,
issued_spans: &UseSpans<'tcx>, issued_spans: &UseSpans<'tcx>,
) { ) {
@ -1620,7 +1609,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
/// ``` /// ```
fn suggest_using_closure_argument_instead_of_capture( fn suggest_using_closure_argument_instead_of_capture(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
borrowed_place: Place<'tcx>, borrowed_place: Place<'tcx>,
issued_spans: &UseSpans<'tcx>, issued_spans: &UseSpans<'tcx>,
) { ) {
@ -1754,7 +1743,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
fn suggest_binding_for_closure_capture_self( fn suggest_binding_for_closure_capture_self(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
issued_spans: &UseSpans<'tcx>, issued_spans: &UseSpans<'tcx>,
) { ) {
let UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return }; let UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
@ -2149,7 +2138,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
drop_span: Span, drop_span: Span,
borrow_spans: UseSpans<'tcx>, borrow_spans: UseSpans<'tcx>,
explanation: BorrowExplanation<'tcx>, explanation: BorrowExplanation<'tcx>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
debug!( debug!(
"report_local_value_does_not_live_long_enough(\ "report_local_value_does_not_live_long_enough(\
{:?}, {:?}, {:?}, {:?}, {:?}\ {:?}, {:?}, {:?}, {:?}, {:?}\
@ -2324,7 +2313,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
&mut self, &mut self,
drop_span: Span, drop_span: Span,
borrow_span: Span, borrow_span: Span,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
debug!( debug!(
"report_thread_local_value_does_not_live_long_enough(\ "report_thread_local_value_does_not_live_long_enough(\
{:?}, {:?}\ {:?}, {:?}\
@ -2349,7 +2338,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
borrow_spans: UseSpans<'tcx>, borrow_spans: UseSpans<'tcx>,
proper_span: Span, proper_span: Span,
explanation: BorrowExplanation<'tcx>, explanation: BorrowExplanation<'tcx>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
if let BorrowExplanation::MustBeValidFor { category, span, from_closure: false, .. } = if let BorrowExplanation::MustBeValidFor { category, span, from_closure: false, .. } =
explanation explanation
{ {
@ -2515,7 +2504,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
return_span: Span, return_span: Span,
category: ConstraintCategory<'tcx>, category: ConstraintCategory<'tcx>,
opt_place_desc: Option<&String>, opt_place_desc: Option<&String>,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<Diag<'tcx>> {
let return_kind = match category { let return_kind = match category {
ConstraintCategory::Return(_) => "return", ConstraintCategory::Return(_) => "return",
ConstraintCategory::Yield => "yield", ConstraintCategory::Yield => "yield",
@ -2610,7 +2599,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
constraint_span: Span, constraint_span: Span,
captured_var: &str, captured_var: &str,
scope: &str, scope: &str,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let tcx = self.infcx.tcx; let tcx = self.infcx.tcx;
let args_span = use_span.args_or_use(); let args_span = use_span.args_or_use();
@ -2718,7 +2707,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
upvar_span: Span, upvar_span: Span,
upvar_name: Symbol, upvar_name: Symbol,
escape_span: Span, escape_span: Span,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let tcx = self.infcx.tcx; let tcx = self.infcx.tcx;
let escapes_from = tcx.def_descr(self.mir_def_id().to_def_id()); let escapes_from = tcx.def_descr(self.mir_def_id().to_def_id());
@ -3000,7 +2989,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
self.buffer_error(err); self.buffer_error(err);
} }
fn explain_deref_coercion(&mut self, loan: &BorrowData<'tcx>, err: &mut DiagnosticBuilder<'_>) { fn explain_deref_coercion(&mut self, loan: &BorrowData<'tcx>, err: &mut Diag<'_>) {
let tcx = self.infcx.tcx; let tcx = self.infcx.tcx;
if let ( if let (
Some(Terminator { Some(Terminator {
@ -3535,11 +3524,7 @@ enum AnnotatedBorrowFnSignature<'tcx> {
impl<'tcx> AnnotatedBorrowFnSignature<'tcx> { impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
/// Annotate the provided diagnostic with information about borrow from the fn signature that /// Annotate the provided diagnostic with information about borrow from the fn signature that
/// helps explain. /// helps explain.
pub(crate) fn emit( pub(crate) fn emit(&self, cx: &mut MirBorrowckCtxt<'_, 'tcx>, diag: &mut Diag<'_>) -> String {
&self,
cx: &mut MirBorrowckCtxt<'_, 'tcx>,
diag: &mut DiagnosticBuilder<'_>,
) -> String {
match self { match self {
&AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => { &AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
diag.span_label( diag.span_label(

View file

@ -3,7 +3,7 @@
#![allow(rustc::diagnostic_outside_of_impl)] #![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)] #![allow(rustc::untranslatable_diagnostic)]
use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_errors::{Applicability, Diag};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::intravisit::Visitor; use rustc_hir::intravisit::Visitor;
use rustc_index::IndexSlice; use rustc_index::IndexSlice;
@ -65,7 +65,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
body: &Body<'tcx>, body: &Body<'tcx>,
local_names: &IndexSlice<Local, Option<Symbol>>, local_names: &IndexSlice<Local, Option<Symbol>>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
borrow_desc: &str, borrow_desc: &str,
borrow_span: Option<Span>, borrow_span: Option<Span>,
multiple_borrow_span: Option<(Span, Span)>, multiple_borrow_span: Option<(Span, Span)>,
@ -306,7 +306,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
fn add_object_lifetime_default_note( fn add_object_lifetime_default_note(
&self, &self,
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
unsize_ty: Ty<'tcx>, unsize_ty: Ty<'tcx>,
) { ) {
if let ty::Adt(def, args) = unsize_ty.kind() { if let ty::Adt(def, args) = unsize_ty.kind() {
@ -359,7 +359,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
fn add_lifetime_bound_suggestion_to_diagnostic( fn add_lifetime_bound_suggestion_to_diagnostic(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
category: &ConstraintCategory<'tcx>, category: &ConstraintCategory<'tcx>,
span: Span, span: Span,
region_name: &RegionName, region_name: &RegionName,

View file

@ -5,7 +5,7 @@ use crate::session_diagnostics::{
CaptureVarKind, CaptureVarPathUseCause, OnClosureNote, CaptureVarKind, CaptureVarPathUseCause, OnClosureNote,
}; };
use itertools::Itertools; use itertools::Itertools;
use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_errors::{Applicability, Diag};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{CtorKind, Namespace}; use rustc_hir::def::{CtorKind, Namespace};
use rustc_hir::CoroutineKind; use rustc_hir::CoroutineKind;
@ -80,7 +80,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
&self, &self,
location: Location, location: Location,
place: PlaceRef<'tcx>, place: PlaceRef<'tcx>,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
) -> bool { ) -> bool {
debug!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location, place); debug!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location, place);
let mut target = place.local_or_deref_local(); let mut target = place.local_or_deref_local();
@ -588,7 +588,7 @@ impl UseSpans<'_> {
pub(super) fn args_subdiag( pub(super) fn args_subdiag(
self, self,
dcx: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
f: impl FnOnce(Span) -> CaptureArgLabel, f: impl FnOnce(Span) -> CaptureArgLabel,
) { ) {
if let UseSpans::ClosureUse { args_span, .. } = self { if let UseSpans::ClosureUse { args_span, .. } = self {
@ -601,7 +601,7 @@ impl UseSpans<'_> {
pub(super) fn var_path_only_subdiag( pub(super) fn var_path_only_subdiag(
self, self,
dcx: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
action: crate::InitializationRequiringAction, action: crate::InitializationRequiringAction,
) { ) {
use crate::InitializationRequiringAction::*; use crate::InitializationRequiringAction::*;
@ -638,7 +638,7 @@ impl UseSpans<'_> {
pub(super) fn var_subdiag( pub(super) fn var_subdiag(
self, self,
dcx: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
err: &mut DiagnosticBuilder<'_>, 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,
) { ) {
@ -1010,7 +1010,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
fn explain_captures( fn explain_captures(
&mut self, &mut self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
span: Span, span: Span,
move_span: Span, move_span: Span,
move_spans: UseSpans<'tcx>, move_spans: UseSpans<'tcx>,

View file

@ -1,7 +1,7 @@
#![allow(rustc::diagnostic_outside_of_impl)] #![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)] #![allow(rustc::untranslatable_diagnostic)]
use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_errors::{Applicability, Diag};
use rustc_middle::mir::*; use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty}; use rustc_middle::ty::{self, Ty};
use rustc_mir_dataflow::move_paths::{LookupResult, MovePathIndex}; use rustc_mir_dataflow::move_paths::{LookupResult, MovePathIndex};
@ -287,11 +287,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
self.buffer_error(err); self.buffer_error(err);
} }
fn report_cannot_move_from_static( fn report_cannot_move_from_static(&mut self, place: Place<'tcx>, span: Span) -> Diag<'tcx> {
&mut self,
place: Place<'tcx>,
span: Span,
) -> DiagnosticBuilder<'tcx> {
let description = if place.projection.len() == 1 { let description = if place.projection.len() == 1 {
format!("static item {}", self.describe_any_place(place.as_ref())) format!("static item {}", self.describe_any_place(place.as_ref()))
} else { } else {
@ -313,7 +309,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
deref_target_place: Place<'tcx>, deref_target_place: Place<'tcx>,
span: Span, span: Span,
use_spans: Option<UseSpans<'tcx>>, use_spans: Option<UseSpans<'tcx>>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
// Inspect the type of the content behind the // Inspect the type of the content behind the
// borrow to provide feedback about why this // borrow to provide feedback about why this
// was a move rather than a copy. // was a move rather than a copy.
@ -437,12 +433,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
err err
} }
fn add_move_hints( fn add_move_hints(&self, error: GroupedMoveError<'tcx>, err: &mut Diag<'_>, span: Span) {
&self,
error: GroupedMoveError<'tcx>,
err: &mut DiagnosticBuilder<'_>,
span: Span,
) {
match error { match error {
GroupedMoveError::MovesFromPlace { mut binds_to, move_from, .. } => { GroupedMoveError::MovesFromPlace { mut binds_to, move_from, .. } => {
self.add_borrow_suggestions(err, span); self.add_borrow_suggestions(err, span);
@ -505,7 +496,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
} }
} }
fn add_borrow_suggestions(&self, err: &mut DiagnosticBuilder<'_>, span: Span) { fn add_borrow_suggestions(&self, err: &mut Diag<'_>, span: Span) {
match self.infcx.tcx.sess.source_map().span_to_snippet(span) { match self.infcx.tcx.sess.source_map().span_to_snippet(span) {
Ok(snippet) if snippet.starts_with('*') => { Ok(snippet) if snippet.starts_with('*') => {
err.span_suggestion_verbose( err.span_suggestion_verbose(
@ -526,7 +517,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
} }
} }
fn add_move_error_suggestions(&self, err: &mut DiagnosticBuilder<'_>, binds_to: &[Local]) { fn add_move_error_suggestions(&self, err: &mut Diag<'_>, binds_to: &[Local]) {
let mut suggestions: Vec<(Span, String, String)> = Vec::new(); let mut suggestions: Vec<(Span, String, String)> = Vec::new();
for local in binds_to { for local in binds_to {
let bind_to = &self.body.local_decls[*local]; let bind_to = &self.body.local_decls[*local];
@ -578,7 +569,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
} }
} }
fn add_move_error_details(&self, err: &mut DiagnosticBuilder<'_>, binds_to: &[Local]) { fn add_move_error_details(&self, err: &mut Diag<'_>, binds_to: &[Local]) {
for (j, local) in binds_to.iter().enumerate() { for (j, local) in binds_to.iter().enumerate() {
let bind_to = &self.body.local_decls[*local]; let bind_to = &self.body.local_decls[*local];
let binding_span = bind_to.source_info.span; let binding_span = bind_to.source_info.span;
@ -615,7 +606,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
/// expansion of a packed struct. /// expansion of a packed struct.
/// Such errors happen because derive macro expansions shy away from taking /// Such errors happen because derive macro expansions shy away from taking
/// references to the struct's fields since doing so would be undefined behaviour /// references to the struct's fields since doing so would be undefined behaviour
fn add_note_for_packed_struct_derive(&self, err: &mut DiagnosticBuilder<'_>, local: Local) { fn add_note_for_packed_struct_derive(&self, err: &mut Diag<'_>, local: Local) {
let local_place: PlaceRef<'tcx> = local.into(); let local_place: PlaceRef<'tcx> = local.into();
let local_ty = local_place.ty(self.body.local_decls(), self.infcx.tcx).ty.peel_refs(); let local_ty = local_place.ty(self.body.local_decls(), self.infcx.tcx).ty.peel_refs();

View file

@ -2,7 +2,7 @@
#![allow(rustc::untranslatable_diagnostic)] #![allow(rustc::untranslatable_diagnostic)]
use hir::ExprKind; use hir::ExprKind;
use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_errors::{Applicability, Diag};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::intravisit::Visitor; use rustc_hir::intravisit::Visitor;
use rustc_hir::Node; use rustc_hir::Node;
@ -540,12 +540,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
} }
} }
fn suggest_map_index_mut_alternatives( fn suggest_map_index_mut_alternatives(&self, ty: Ty<'tcx>, err: &mut Diag<'tcx>, span: Span) {
&self,
ty: Ty<'tcx>,
err: &mut DiagnosticBuilder<'tcx>,
span: Span,
) {
let Some(adt) = ty.ty_adt_def() else { return }; let Some(adt) = ty.ty_adt_def() else { return };
let did = adt.did(); let did = adt.did();
if self.infcx.tcx.is_diagnostic_item(sym::HashMap, did) if self.infcx.tcx.is_diagnostic_item(sym::HashMap, did)
@ -553,7 +548,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
{ {
struct V<'a, 'tcx> { struct V<'a, 'tcx> {
assign_span: Span, assign_span: Span,
err: &'a mut DiagnosticBuilder<'tcx>, err: &'a mut Diag<'tcx>,
ty: Ty<'tcx>, ty: Ty<'tcx>,
suggested: bool, suggested: bool,
} }
@ -717,7 +712,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
fn construct_mut_suggestion_for_local_binding_patterns( fn construct_mut_suggestion_for_local_binding_patterns(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
local: Local, local: Local,
) { ) {
let local_decl = &self.body.local_decls[local]; let local_decl = &self.body.local_decls[local];
@ -795,7 +790,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
tcx: TyCtxt<'_>, tcx: TyCtxt<'_>,
closure_local_def_id: hir::def_id::LocalDefId, closure_local_def_id: hir::def_id::LocalDefId,
the_place_err: PlaceRef<'tcx>, the_place_err: PlaceRef<'tcx>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
) { ) {
let tables = tcx.typeck(closure_local_def_id); let tables = tcx.typeck(closure_local_def_id);
if let Some((span, closure_kind_origin)) = tcx.closure_kind_origin(closure_local_def_id) { if let Some((span, closure_kind_origin)) = tcx.closure_kind_origin(closure_local_def_id) {
@ -857,7 +852,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
// Attempt to search similar mutable associated items for suggestion. // Attempt to search similar mutable associated items for suggestion.
// In the future, attempt in all path but initially for RHS of for_loop // In the future, attempt in all path but initially for RHS of for_loop
fn suggest_similar_mut_method_for_for_loop(&self, err: &mut DiagnosticBuilder<'_>, span: Span) { fn suggest_similar_mut_method_for_for_loop(&self, err: &mut Diag<'_>, span: Span) {
use hir::{ use hir::{
BorrowKind, Expr, BorrowKind, Expr,
ExprKind::{AddrOf, Block, Call, MethodCall}, ExprKind::{AddrOf, Block, Call, MethodCall},
@ -941,7 +936,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
} }
/// Targeted error when encountering an `FnMut` closure where an `Fn` closure was expected. /// Targeted error when encountering an `FnMut` closure where an `Fn` closure was expected.
fn expected_fn_found_fn_mut_call(&self, err: &mut DiagnosticBuilder<'_>, sp: Span, act: &str) { fn expected_fn_found_fn_mut_call(&self, err: &mut Diag<'_>, sp: Span, act: &str) {
err.span_label(sp, format!("cannot {act}")); err.span_label(sp, format!("cannot {act}"));
let hir = self.infcx.tcx.hir(); let hir = self.infcx.tcx.hir();
@ -1031,7 +1026,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
} }
} }
fn suggest_using_iter_mut(&self, err: &mut DiagnosticBuilder<'_>) { fn suggest_using_iter_mut(&self, err: &mut Diag<'_>) {
let source = self.body.source; let source = self.body.source;
let hir = self.infcx.tcx.hir(); let hir = self.infcx.tcx.hir();
if let InstanceDef::Item(def_id) = source.instance if let InstanceDef::Item(def_id) = source.instance
@ -1072,7 +1067,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
} }
} }
fn suggest_make_local_mut(&self, err: &mut DiagnosticBuilder<'_>, local: Local, name: Symbol) { fn suggest_make_local_mut(&self, err: &mut Diag<'_>, local: Local, name: Symbol) {
let local_decl = &self.body.local_decls[local]; let local_decl = &self.body.local_decls[local];
let (pointer_sigil, pointer_desc) = let (pointer_sigil, pointer_desc) =

View file

@ -5,7 +5,7 @@
#![allow(rustc::untranslatable_diagnostic)] #![allow(rustc::untranslatable_diagnostic)]
use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::DiagnosticBuilder; use rustc_errors::Diag;
use rustc_middle::ty::RegionVid; use rustc_middle::ty::RegionVid;
use smallvec::SmallVec; use smallvec::SmallVec;
use std::collections::BTreeMap; use std::collections::BTreeMap;
@ -157,13 +157,12 @@ impl OutlivesSuggestionBuilder {
self.constraints_to_add.entry(fr).or_default().push(outlived_fr); self.constraints_to_add.entry(fr).or_default().push(outlived_fr);
} }
/// Emit an intermediate note on the given `DiagnosticBuilder` if the involved regions are /// Emit an intermediate note on the given `Diag` if the involved regions are suggestable.
/// suggestable.
pub(crate) fn intermediate_suggestion( pub(crate) fn intermediate_suggestion(
&mut self, &mut self,
mbcx: &MirBorrowckCtxt<'_, '_>, mbcx: &MirBorrowckCtxt<'_, '_>,
errci: &ErrorConstraintInfo<'_>, errci: &ErrorConstraintInfo<'_>,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
) { ) {
// Emit an intermediate note. // Emit an intermediate note.
let fr_name = self.region_vid_to_name(mbcx, errci.fr); let fr_name = self.region_vid_to_name(mbcx, errci.fr);

View file

@ -1,7 +1,7 @@
//! Error reporting machinery for lifetime errors. //! Error reporting machinery for lifetime errors.
use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, MultiSpan}; use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::Res::Def; use rustc_hir::def::Res::Def;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
@ -203,7 +203,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
// and the span which bounded to the trait for adding 'static lifetime suggestion // and the span which bounded to the trait for adding 'static lifetime suggestion
fn suggest_static_lifetime_for_gat_from_hrtb( fn suggest_static_lifetime_for_gat_from_hrtb(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
lower_bound: RegionVid, lower_bound: RegionVid,
) { ) {
let mut suggestions = vec![]; let mut suggestions = vec![];
@ -584,7 +584,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
&self, &self,
errci: &ErrorConstraintInfo<'tcx>, errci: &ErrorConstraintInfo<'tcx>,
kind: ReturnConstraint, kind: ReturnConstraint,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let ErrorConstraintInfo { outlived_fr, span, .. } = errci; let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty; let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
@ -653,10 +653,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
/// | ^^^^^^^^^^ `x` escapes the function body here /// | ^^^^^^^^^^ `x` escapes the function body here
/// ``` /// ```
#[instrument(level = "debug", skip(self))] #[instrument(level = "debug", skip(self))]
fn report_escaping_data_error( fn report_escaping_data_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'tcx> {
&self,
errci: &ErrorConstraintInfo<'tcx>,
) -> DiagnosticBuilder<'tcx> {
let ErrorConstraintInfo { span, category, .. } = errci; let ErrorConstraintInfo { span, category, .. } = errci;
let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region( let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
@ -764,7 +761,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
/// | ^^^^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it /// | ^^^^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it
/// | is returning data with lifetime `'b` /// | is returning data with lifetime `'b`
/// ``` /// ```
fn report_general_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> DiagnosticBuilder<'tcx> { fn report_general_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'tcx> {
let ErrorConstraintInfo { let ErrorConstraintInfo {
fr, fr,
fr_is_local, fr_is_local,
@ -827,7 +824,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
/// ``` /// ```
fn add_static_impl_trait_suggestion( fn add_static_impl_trait_suggestion(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
fr: RegionVid, fr: RegionVid,
// We need to pass `fr_name` - computing it again will label it twice. // We need to pass `fr_name` - computing it again will label it twice.
fr_name: RegionName, fr_name: RegionName,
@ -916,7 +913,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
fn maybe_suggest_constrain_dyn_trait_impl( fn maybe_suggest_constrain_dyn_trait_impl(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
f: Region<'tcx>, f: Region<'tcx>,
o: Region<'tcx>, o: Region<'tcx>,
category: &ConstraintCategory<'tcx>, category: &ConstraintCategory<'tcx>,
@ -978,7 +975,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
#[instrument(skip(self, err), level = "debug")] #[instrument(skip(self, err), level = "debug")]
fn suggest_constrain_dyn_trait_in_impl( fn suggest_constrain_dyn_trait_in_impl(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
found_dids: &FxIndexSet<DefId>, found_dids: &FxIndexSet<DefId>,
ident: Ident, ident: Ident,
self_ty: &hir::Ty<'_>, self_ty: &hir::Ty<'_>,
@ -1011,12 +1008,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
suggested suggested
} }
fn suggest_adding_lifetime_params( fn suggest_adding_lifetime_params(&self, diag: &mut Diag<'_>, sub: RegionVid, sup: RegionVid) {
&self,
diag: &mut DiagnosticBuilder<'_>,
sub: RegionVid,
sup: RegionVid,
) {
let (Some(sub), Some(sup)) = (self.to_error_region(sub), self.to_error_region(sup)) else { let (Some(sub), Some(sup)) = (self.to_error_region(sub), self.to_error_region(sup)) else {
return; return;
}; };
@ -1042,7 +1034,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
suggest_adding_lifetime_params(self.infcx.tcx, sub, ty_sup, ty_sub, diag); suggest_adding_lifetime_params(self.infcx.tcx, sub, ty_sup, ty_sub, diag);
} }
fn suggest_move_on_borrowing_closure(&self, diag: &mut DiagnosticBuilder<'_>) { fn suggest_move_on_borrowing_closure(&self, diag: &mut Diag<'_>) {
let map = self.infcx.tcx.hir(); let map = self.infcx.tcx.hir();
let body_id = map.body_owned_by(self.mir_def_id()); let body_id = map.body_owned_by(self.mir_def_id());
let expr = &map.body(body_id).value.peel_blocks(); let expr = &map.body(body_id).value.peel_blocks();

View file

@ -5,7 +5,7 @@ use std::fmt::{self, Display};
use std::iter; use std::iter;
use rustc_data_structures::fx::IndexEntry; use rustc_data_structures::fx::IndexEntry;
use rustc_errors::DiagnosticBuilder; use rustc_errors::Diag;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res}; use rustc_hir::def::{DefKind, Res};
use rustc_middle::ty::print::RegionHighlightMode; use rustc_middle::ty::print::RegionHighlightMode;
@ -106,7 +106,7 @@ impl RegionName {
} }
} }
pub(crate) fn highlight_region_name(&self, diag: &mut DiagnosticBuilder<'_>) { pub(crate) fn highlight_region_name(&self, diag: &mut Diag<'_>) {
match &self.source { match &self.source {
RegionNameSource::NamedLateParamRegion(span) RegionNameSource::NamedLateParamRegion(span)
| RegionNameSource::NamedEarlyParamRegion(span) => { | RegionNameSource::NamedEarlyParamRegion(span) => {

View file

@ -20,7 +20,7 @@ extern crate tracing;
use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
use rustc_data_structures::graph::dominators::Dominators; use rustc_data_structures::graph::dominators::Dominators;
use rustc_errors::DiagnosticBuilder; use rustc_errors::Diag;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::LocalDefId; use rustc_hir::def_id::LocalDefId;
use rustc_index::bit_set::{BitSet, ChunkedBitSet}; use rustc_index::bit_set::{BitSet, ChunkedBitSet};
@ -2395,8 +2395,8 @@ mod diags {
use super::*; use super::*;
enum BufferedDiag<'tcx> { enum BufferedDiag<'tcx> {
Error(DiagnosticBuilder<'tcx>), Error(Diag<'tcx>),
NonError(DiagnosticBuilder<'tcx, ()>), NonError(Diag<'tcx, ()>),
} }
impl<'tcx> BufferedDiag<'tcx> { impl<'tcx> BufferedDiag<'tcx> {
@ -2423,10 +2423,9 @@ mod diags {
/// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
/// when errors in the map are being re-added to the error buffer so that errors with the /// when errors in the map are being re-added to the error buffer so that errors with the
/// same primary span come out in a consistent order. /// same primary span come out in a consistent order.
buffered_move_errors: buffered_move_errors: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, Diag<'tcx>)>,
BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'tcx>)>,
buffered_mut_errors: FxIndexMap<Span, (DiagnosticBuilder<'tcx>, usize)>, buffered_mut_errors: FxIndexMap<Span, (Diag<'tcx>, usize)>,
/// Buffer of diagnostics to be reported. A mixture of error and non-error diagnostics. /// Buffer of diagnostics to be reported. A mixture of error and non-error diagnostics.
buffered_diags: Vec<BufferedDiag<'tcx>>, buffered_diags: Vec<BufferedDiag<'tcx>>,
@ -2441,28 +2440,28 @@ mod diags {
} }
} }
pub fn buffer_error(&mut self, t: DiagnosticBuilder<'tcx>) { pub fn buffer_error(&mut self, diag: Diag<'tcx>) {
self.buffered_diags.push(BufferedDiag::Error(t)); self.buffered_diags.push(BufferedDiag::Error(diag));
} }
pub fn buffer_non_error(&mut self, t: DiagnosticBuilder<'tcx, ()>) { pub fn buffer_non_error(&mut self, diag: Diag<'tcx, ()>) {
self.buffered_diags.push(BufferedDiag::NonError(t)); self.buffered_diags.push(BufferedDiag::NonError(diag));
} }
} }
impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
pub fn buffer_error(&mut self, t: DiagnosticBuilder<'tcx>) { pub fn buffer_error(&mut self, diag: Diag<'tcx>) {
self.diags.buffer_error(t); self.diags.buffer_error(diag);
} }
pub fn buffer_non_error(&mut self, t: DiagnosticBuilder<'tcx, ()>) { pub fn buffer_non_error(&mut self, diag: Diag<'tcx, ()>) {
self.diags.buffer_non_error(t); self.diags.buffer_non_error(diag);
} }
pub fn buffer_move_error( pub fn buffer_move_error(
&mut self, &mut self,
move_out_indices: Vec<MoveOutIndex>, move_out_indices: Vec<MoveOutIndex>,
place_and_err: (PlaceRef<'tcx>, DiagnosticBuilder<'tcx>), place_and_err: (PlaceRef<'tcx>, Diag<'tcx>),
) -> bool { ) -> bool {
if let Some((_, diag)) = if let Some((_, diag)) =
self.diags.buffered_move_errors.insert(move_out_indices, place_and_err) self.diags.buffered_move_errors.insert(move_out_indices, place_and_err)
@ -2475,16 +2474,13 @@ mod diags {
} }
} }
pub fn get_buffered_mut_error( pub fn get_buffered_mut_error(&mut self, span: Span) -> Option<(Diag<'tcx>, usize)> {
&mut self,
span: Span,
) -> Option<(DiagnosticBuilder<'tcx>, usize)> {
// FIXME(#120456) - is `swap_remove` correct? // FIXME(#120456) - is `swap_remove` correct?
self.diags.buffered_mut_errors.swap_remove(&span) self.diags.buffered_mut_errors.swap_remove(&span)
} }
pub fn buffer_mut_error(&mut self, span: Span, t: DiagnosticBuilder<'tcx>, count: usize) { pub fn buffer_mut_error(&mut self, span: Span, diag: Diag<'tcx>, count: usize) {
self.diags.buffered_mut_errors.insert(span, (t, count)); self.diags.buffered_mut_errors.insert(span, (diag, count));
} }
pub fn emit_errors(&mut self) -> Option<ErrorGuaranteed> { pub fn emit_errors(&mut self) -> Option<ErrorGuaranteed> {
@ -2524,7 +2520,7 @@ mod diags {
pub fn has_move_error( pub fn has_move_error(
&self, &self,
move_out_indices: &[MoveOutIndex], move_out_indices: &[MoveOutIndex],
) -> Option<&(PlaceRef<'tcx>, DiagnosticBuilder<'tcx>)> { ) -> Option<&(PlaceRef<'tcx>, Diag<'tcx>)> {
self.diags.buffered_move_errors.get(move_out_indices) self.diags.buffered_move_errors.get(move_out_indices)
} }
} }

View file

@ -5,7 +5,7 @@ use rustc_data_structures::binary_search_util;
use rustc_data_structures::frozen::Frozen; use rustc_data_structures::frozen::Frozen;
use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
use rustc_data_structures::graph::scc::Sccs; use rustc_data_structures::graph::scc::Sccs;
use rustc_errors::DiagnosticBuilder; use rustc_errors::Diag;
use rustc_hir::def_id::CRATE_DEF_ID; use rustc_hir::def_id::CRATE_DEF_ID;
use rustc_index::{IndexSlice, IndexVec}; use rustc_index::{IndexSlice, IndexVec};
use rustc_infer::infer::outlives::test_type_match; use rustc_infer::infer::outlives::test_type_match;
@ -592,7 +592,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
} }
/// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`. /// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.
pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut DiagnosticBuilder<'_, ()>) { pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diag<'_, ()>) {
self.universal_regions.annotate(tcx, err) self.universal_regions.annotate(tcx, err)
} }

View file

@ -16,7 +16,7 @@
#![allow(rustc::untranslatable_diagnostic)] #![allow(rustc::untranslatable_diagnostic)]
use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::fx::FxIndexMap;
use rustc_errors::DiagnosticBuilder; use rustc_errors::Diag;
use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::lang_items::LangItem; use rustc_hir::lang_items::LangItem;
use rustc_hir::BodyOwnerKind; use rustc_hir::BodyOwnerKind;
@ -343,7 +343,7 @@ impl<'tcx> UniversalRegions<'tcx> {
/// that this region imposes on others. The methods in this file /// that this region imposes on others. The methods in this file
/// handle the part about dumping the inference context internal /// handle the part about dumping the inference context internal
/// state. /// state.
pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut DiagnosticBuilder<'_, ()>) { pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diag<'_, ()>) {
match self.defining_ty { match self.defining_ty {
DefiningTy::Closure(def_id, args) => { DefiningTy::Closure(def_id, args) => {
let v = with_no_trimmed_paths!( let v = with_no_trimmed_paths!(

View file

@ -1,6 +1,6 @@
use rustc_errors::{ use rustc_errors::{
codes::*, AddToDiagnostic, DiagCtxt, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic, codes::*, AddToDiagnostic, Diag, DiagCtxt, EmissionGuarantee, IntoDiagnostic, Level, MultiSpan,
Level, MultiSpan, SingleLabelManySpans, SubdiagnosticMessageOp, SingleLabelManySpans, SubdiagnosticMessageOp,
}; };
use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_span::{symbol::Ident, Span, Symbol}; use rustc_span::{symbol::Ident, Span, Symbol};
@ -448,12 +448,12 @@ pub(crate) struct EnvNotDefinedWithUserMessage {
// Hand-written implementation to support custom user messages. // Hand-written implementation to support custom user messages.
impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for EnvNotDefinedWithUserMessage { impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for EnvNotDefinedWithUserMessage {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
#[expect( #[expect(
rustc::untranslatable_diagnostic, rustc::untranslatable_diagnostic,
reason = "cannot translate user-provided messages" reason = "cannot translate user-provided messages"
)] )]
let mut diag = DiagnosticBuilder::new(dcx, level, self.msg_from_user.to_string()); let mut diag = Diag::new(dcx, level, self.msg_from_user.to_string());
diag.span(self.span); diag.span(self.span);
diag diag
} }
@ -613,7 +613,7 @@ pub(crate) struct FormatUnusedArg {
impl AddToDiagnostic for FormatUnusedArg { impl AddToDiagnostic for FormatUnusedArg {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
f: F, f: F,
) { ) {
diag.arg("named", self.named); diag.arg("named", self.named);
@ -800,7 +800,7 @@ pub(crate) struct AsmClobberNoReg {
} }
impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for AsmClobberNoReg { impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for AsmClobberNoReg {
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
// eager translation as `span_labels` takes `AsRef<str>` // eager translation as `span_labels` takes `AsRef<str>`
let lbl1 = dcx.eagerly_translate_to_string( let lbl1 = dcx.eagerly_translate_to_string(
crate::fluent_generated::builtin_macros_asm_clobber_abi, crate::fluent_generated::builtin_macros_asm_clobber_abi,
@ -810,11 +810,7 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for AsmClobberNoReg {
crate::fluent_generated::builtin_macros_asm_clobber_outputs, crate::fluent_generated::builtin_macros_asm_clobber_outputs,
[].into_iter(), [].into_iter(),
); );
DiagnosticBuilder::new( Diag::new(dcx, level, crate::fluent_generated::builtin_macros_asm_clobber_no_reg)
dcx,
level,
crate::fluent_generated::builtin_macros_asm_clobber_no_reg,
)
.with_span(self.spans.clone()) .with_span(self.spans.clone())
.with_span_labels(self.clobbers, &lbl1) .with_span_labels(self.clobbers, &lbl1)
.with_span_labels(self.spans, &lbl2) .with_span_labels(self.spans, &lbl2)

View file

@ -8,7 +8,7 @@ use rustc_ast::{
FormatDebugHex, FormatOptions, FormatPlaceholder, FormatSign, FormatTrait, FormatDebugHex, FormatOptions, FormatPlaceholder, FormatSign, FormatTrait,
}; };
use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{Applicability, DiagnosticBuilder, MultiSpan, PResult, SingleLabelManySpans}; use rustc_errors::{Applicability, Diag, MultiSpan, PResult, SingleLabelManySpans};
use rustc_expand::base::{self, *}; use rustc_expand::base::{self, *};
use rustc_parse::parser::Recovered; use rustc_parse::parser::Recovered;
use rustc_parse_format as parse; use rustc_parse_format as parse;
@ -730,7 +730,7 @@ fn report_redundant_format_arguments<'a>(
args: &FormatArguments, args: &FormatArguments,
used: &[bool], used: &[bool],
placeholders: Vec<(Span, &str)>, placeholders: Vec<(Span, &str)>,
) -> Option<DiagnosticBuilder<'a>> { ) -> Option<Diag<'a>> {
let mut fmt_arg_indices = vec![]; let mut fmt_arg_indices = vec![];
let mut args_spans = vec![]; let mut args_spans = vec![];
let mut fmt_spans = vec![]; let mut fmt_spans = vec![];

View file

@ -5,7 +5,7 @@ use crate::util::{check_builtin_macro_attribute, warn_on_duplicate_attribute};
use rustc_ast::ptr::P; use rustc_ast::ptr::P;
use rustc_ast::{self as ast, attr, GenericParamKind}; use rustc_ast::{self as ast, attr, GenericParamKind};
use rustc_ast_pretty::pprust; use rustc_ast_pretty::pprust;
use rustc_errors::{Applicability, DiagnosticBuilder, Level}; use rustc_errors::{Applicability, Diag, Level};
use rustc_expand::base::*; use rustc_expand::base::*;
use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::symbol::{sym, Ident, Symbol};
use rustc_span::{ErrorGuaranteed, FileNameDisplayPreference, Span}; use rustc_span::{ErrorGuaranteed, FileNameDisplayPreference, Span};
@ -410,7 +410,7 @@ fn not_testable_error(cx: &ExtCtxt<'_>, attr_sp: Span, item: Option<&ast::Item>)
Some(ast::ItemKind::MacCall(_)) => Level::Warning, Some(ast::ItemKind::MacCall(_)) => Level::Warning,
_ => Level::Error, _ => Level::Error,
}; };
let mut err = DiagnosticBuilder::<()>::new(dcx, level, msg); let mut err = Diag::<()>::new(dcx, level, msg);
err.span(attr_sp); err.span(attr_sp);
if let Some(item) = item { if let Some(item) = item {
err.span_label( err.span_label(

View file

@ -1,6 +1,5 @@
use rustc_errors::{ use rustc_errors::{
DiagCtxt, DiagnosticArgValue, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic, DiagCtxt, DiagnosticArgValue, Diag, EmissionGuarantee, IntoDiagnostic, IntoDiagnosticArg, Level,
IntoDiagnosticArg, Level,
}; };
use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_span::Span; use rustc_span::Span;
@ -112,12 +111,8 @@ pub(crate) struct TargetFeatureDisableOrEnable<'a> {
pub(crate) struct MissingFeatures; pub(crate) struct MissingFeatures;
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetFeatureDisableOrEnable<'_> { impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetFeatureDisableOrEnable<'_> {
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
let mut diag = DiagnosticBuilder::new( let mut diag = Diag::new(dcx, level, fluent::codegen_gcc_target_feature_disable_or_enable);
dcx,
level,
fluent::codegen_gcc_target_feature_disable_or_enable
);
if let Some(span) = self.span { if let Some(span) = self.span {
diag.span(span); diag.span(span);
}; };

View file

@ -4,7 +4,7 @@ use std::path::Path;
use crate::fluent_generated as fluent; use crate::fluent_generated as fluent;
use rustc_data_structures::small_c_str::SmallCStr; use rustc_data_structures::small_c_str::SmallCStr;
use rustc_errors::{DiagCtxt, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic, Level}; use rustc_errors::{Diag, DiagCtxt, EmissionGuarantee, IntoDiagnostic, Level};
use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_span::Span; use rustc_span::Span;
@ -100,11 +100,11 @@ pub(crate) struct DynamicLinkingWithLTO;
pub(crate) struct ParseTargetMachineConfig<'a>(pub LlvmError<'a>); pub(crate) struct ParseTargetMachineConfig<'a>(pub LlvmError<'a>);
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ParseTargetMachineConfig<'_> { impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ParseTargetMachineConfig<'_> {
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
let diag: DiagnosticBuilder<'_, G> = self.0.into_diagnostic(dcx, level); let diag: Diag<'_, G> = self.0.into_diagnostic(dcx, level);
let (message, _) = diag.messages.first().expect("`LlvmError` with no message"); let (message, _) = diag.messages.first().expect("`LlvmError` with no message");
let message = dcx.eagerly_translate_to_string(message.clone(), diag.args.iter()); let message = dcx.eagerly_translate_to_string(message.clone(), diag.args.iter());
DiagnosticBuilder::new(dcx, level, fluent::codegen_llvm_parse_target_machine_config) Diag::new(dcx, level, fluent::codegen_llvm_parse_target_machine_config)
.with_arg("error", message) .with_arg("error", message)
} }
} }
@ -120,12 +120,8 @@ pub(crate) struct TargetFeatureDisableOrEnable<'a> {
pub(crate) struct MissingFeatures; pub(crate) struct MissingFeatures;
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetFeatureDisableOrEnable<'_> { impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetFeatureDisableOrEnable<'_> {
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
let mut diag = DiagnosticBuilder::new( let mut diag = Diag::new(dcx, level, fluent::codegen_llvm_target_feature_disable_or_enable);
dcx,
level,
fluent::codegen_llvm_target_feature_disable_or_enable,
);
if let Some(span) = self.span { if let Some(span) = self.span {
diag.span(span); diag.span(span);
}; };
@ -184,7 +180,7 @@ pub enum LlvmError<'a> {
pub(crate) struct WithLlvmError<'a>(pub LlvmError<'a>, pub String); pub(crate) struct WithLlvmError<'a>(pub LlvmError<'a>, pub String);
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for WithLlvmError<'_> { impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for WithLlvmError<'_> {
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
use LlvmError::*; use LlvmError::*;
let msg_with_llvm_err = match &self.0 { let msg_with_llvm_err = match &self.0 {
WriteOutput { .. } => fluent::codegen_llvm_write_output_with_llvm_err, WriteOutput { .. } => fluent::codegen_llvm_write_output_with_llvm_err,

View file

@ -16,8 +16,8 @@ use rustc_data_structures::sync::Lrc;
use rustc_errors::emitter::Emitter; use rustc_errors::emitter::Emitter;
use rustc_errors::translation::Translate; use rustc_errors::translation::Translate;
use rustc_errors::{ use rustc_errors::{
DiagCtxt, DiagnosticArgMap, DiagnosticBuilder, DiagnosticMessage, ErrCode, FatalError, Diag, DiagCtxt, DiagnosticArgMap, DiagnosticMessage, ErrCode, FatalError, FluentBundle, Level,
FluentBundle, Level, MultiSpan, Style, MultiSpan, Style,
}; };
use rustc_fs_util::link_or_copy; use rustc_fs_util::link_or_copy;
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE}; use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
@ -1898,7 +1898,7 @@ impl SharedEmitterMain {
Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => { Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
assert!(matches!(level, Level::Error | Level::Warning | Level::Note)); assert!(matches!(level, Level::Error | Level::Warning | Level::Note));
let msg = msg.strip_prefix("error: ").unwrap_or(&msg).to_string(); let msg = msg.strip_prefix("error: ").unwrap_or(&msg).to_string();
let mut err = DiagnosticBuilder::<()>::new(sess.dcx(), level, msg); let mut err = Diag::<()>::new(sess.dcx(), level, msg);
// If the cookie is 0 then we don't have span information. // If the cookie is 0 then we don't have span information.
if cookie != 0 { if cookie != 0 {

View file

@ -4,7 +4,7 @@ use crate::assert_module_sources::CguReuse;
use crate::back::command::Command; use crate::back::command::Command;
use crate::fluent_generated as fluent; use crate::fluent_generated as fluent;
use rustc_errors::{ use rustc_errors::{
codes::*, DiagCtxt, DiagnosticArgValue, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic, codes::*, Diag, DiagCtxt, DiagnosticArgValue, EmissionGuarantee, IntoDiagnostic,
IntoDiagnosticArg, Level, IntoDiagnosticArg, Level,
}; };
use rustc_macros::Diagnostic; use rustc_macros::Diagnostic;
@ -216,8 +216,8 @@ pub enum LinkRlibError {
pub struct ThorinErrorWrapper(pub thorin::Error); pub struct ThorinErrorWrapper(pub thorin::Error);
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ThorinErrorWrapper { impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ThorinErrorWrapper {
fn into_diagnostic(self, dcx: &DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &DiagCtxt, level: Level) -> Diag<'_, G> {
let build = |msg| DiagnosticBuilder::new(dcx, level, msg); let build = |msg| Diag::new(dcx, level, msg);
match self.0 { match self.0 {
thorin::Error::ReadInput(_) => build(fluent::codegen_ssa_thorin_read_input_failure), thorin::Error::ReadInput(_) => build(fluent::codegen_ssa_thorin_read_input_failure),
thorin::Error::ParseFileKind(_) => { thorin::Error::ParseFileKind(_) => {
@ -349,8 +349,8 @@ pub struct LinkingFailed<'a> {
} }
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for LinkingFailed<'_> { impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for LinkingFailed<'_> {
fn into_diagnostic(self, dcx: &DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &DiagCtxt, level: Level) -> Diag<'_, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::codegen_ssa_linking_failed); let mut diag = Diag::new(dcx, level, fluent::codegen_ssa_linking_failed);
diag.arg("linker_path", format!("{}", self.linker_path.display())); diag.arg("linker_path", format!("{}", self.linker_path.display()));
diag.arg("exit_status", format!("{}", self.exit_status)); diag.arg("exit_status", format!("{}", self.exit_status));

View file

@ -1,8 +1,8 @@
use std::borrow::Cow; use std::borrow::Cow;
use rustc_errors::{ use rustc_errors::{
codes::*, DiagCtxt, DiagnosticArgValue, DiagnosticBuilder, DiagnosticMessage, codes::*, Diag, DiagCtxt, DiagnosticArgValue, DiagnosticMessage, EmissionGuarantee,
EmissionGuarantee, IntoDiagnostic, Level, IntoDiagnostic, Level,
}; };
use rustc_hir::ConstContext; use rustc_hir::ConstContext;
use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
@ -426,7 +426,7 @@ pub struct UndefinedBehavior {
pub trait ReportErrorExt { pub trait ReportErrorExt {
/// Returns the diagnostic message for this error. /// Returns the diagnostic message for this error.
fn diagnostic_message(&self) -> DiagnosticMessage; fn diagnostic_message(&self) -> DiagnosticMessage;
fn add_args<G: EmissionGuarantee>(self, diag: &mut DiagnosticBuilder<'_, G>); fn add_args<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>);
fn debug(self) -> String fn debug(self) -> String
where where
@ -505,7 +505,7 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> {
} }
} }
fn add_args<G: EmissionGuarantee>(self, diag: &mut DiagnosticBuilder<'_, G>) { fn add_args<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
use UndefinedBehaviorInfo::*; use UndefinedBehaviorInfo::*;
let dcx = diag.dcx; let dcx = diag.dcx;
match self { match self {
@ -671,7 +671,7 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> {
} }
} }
fn add_args<G: EmissionGuarantee>(self, err: &mut DiagnosticBuilder<'_, G>) { fn add_args<G: EmissionGuarantee>(self, err: &mut Diag<'_, G>) {
use crate::fluent_generated as fluent; use crate::fluent_generated as fluent;
use rustc_middle::mir::interpret::ValidationErrorKind::*; use rustc_middle::mir::interpret::ValidationErrorKind::*;
@ -697,7 +697,7 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> {
fn add_range_arg<G: EmissionGuarantee>( fn add_range_arg<G: EmissionGuarantee>(
r: WrappingRange, r: WrappingRange,
max_hi: u128, max_hi: u128,
err: &mut DiagnosticBuilder<'_, G>, err: &mut Diag<'_, G>,
) { ) {
let WrappingRange { start: lo, end: hi } = r; let WrappingRange { start: lo, end: hi } = r;
assert!(hi <= max_hi); assert!(hi <= max_hi);
@ -798,7 +798,7 @@ impl ReportErrorExt for UnsupportedOpInfo {
UnsupportedOpInfo::ExternStatic(_) => const_eval_extern_static, UnsupportedOpInfo::ExternStatic(_) => const_eval_extern_static,
} }
} }
fn add_args<G: EmissionGuarantee>(self, diag: &mut DiagnosticBuilder<'_, G>) { fn add_args<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
use crate::fluent_generated::*; use crate::fluent_generated::*;
use UnsupportedOpInfo::*; use UnsupportedOpInfo::*;
@ -831,7 +831,7 @@ impl<'tcx> ReportErrorExt for InterpError<'tcx> {
InterpError::MachineStop(e) => e.diagnostic_message(), InterpError::MachineStop(e) => e.diagnostic_message(),
} }
} }
fn add_args<G: EmissionGuarantee>(self, diag: &mut DiagnosticBuilder<'_, G>) { fn add_args<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
match self { match self {
InterpError::UndefinedBehavior(ub) => ub.add_args(diag), InterpError::UndefinedBehavior(ub) => ub.add_args(diag),
InterpError::Unsupported(e) => e.add_args(diag), InterpError::Unsupported(e) => e.add_args(diag),
@ -856,13 +856,13 @@ impl<'tcx> ReportErrorExt for InvalidProgramInfo<'tcx> {
} }
} }
} }
fn add_args<G: EmissionGuarantee>(self, diag: &mut DiagnosticBuilder<'_, G>) { fn add_args<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
match self { match self {
InvalidProgramInfo::TooGeneric | InvalidProgramInfo::AlreadyReported(_) => {} InvalidProgramInfo::TooGeneric | InvalidProgramInfo::AlreadyReported(_) => {}
InvalidProgramInfo::Layout(e) => { InvalidProgramInfo::Layout(e) => {
// The level doesn't matter, `dummy_diag` is consumed without it being used. // The level doesn't matter, `dummy_diag` is consumed without it being used.
let dummy_level = Level::Bug; let dummy_level = Level::Bug;
let dummy_diag: DiagnosticBuilder<'_, ()> = let dummy_diag: Diag<'_, ()> =
e.into_diagnostic().into_diagnostic(diag.dcx, dummy_level); e.into_diagnostic().into_diagnostic(diag.dcx, dummy_level);
for (name, val) in dummy_diag.args.iter() { for (name, val) in dummy_diag.args.iter() {
diag.arg(name.clone(), val.clone()); diag.arg(name.clone(), val.clone());
@ -888,7 +888,7 @@ impl ReportErrorExt for ResourceExhaustionInfo {
ResourceExhaustionInfo::AddressSpaceFull => const_eval_address_space_full, ResourceExhaustionInfo::AddressSpaceFull => const_eval_address_space_full,
} }
} }
fn add_args<G: EmissionGuarantee>(self, _: &mut DiagnosticBuilder<'_, G>) {} fn add_args<G: EmissionGuarantee>(self, _: &mut Diag<'_, G>) {}
} }
impl rustc_errors::IntoDiagnosticArg for InternKind { impl rustc_errors::IntoDiagnosticArg for InternKind {

View file

@ -1,6 +1,6 @@
//! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations. //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed}; use rustc_errors::{Diag, ErrorGuaranteed};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_index::bit_set::BitSet; use rustc_index::bit_set::BitSet;
@ -187,7 +187,7 @@ pub struct Checker<'mir, 'tcx> {
local_has_storage_dead: Option<BitSet<Local>>, local_has_storage_dead: Option<BitSet<Local>>,
error_emitted: Option<ErrorGuaranteed>, error_emitted: Option<ErrorGuaranteed>,
secondary_errors: Vec<DiagnosticBuilder<'tcx>>, secondary_errors: Vec<Diag<'tcx>>,
} }
impl<'mir, 'tcx> Deref for Checker<'mir, 'tcx> { impl<'mir, 'tcx> Deref for Checker<'mir, 'tcx> {

View file

@ -2,7 +2,7 @@
use hir::def_id::LocalDefId; use hir::def_id::LocalDefId;
use hir::{ConstContext, LangItem}; use hir::{ConstContext, LangItem};
use rustc_errors::{codes::*, DiagnosticBuilder}; use rustc_errors::{codes::*, Diag};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::infer::TyCtxtInferExt;
@ -48,7 +48,7 @@ pub trait NonConstOp<'tcx>: std::fmt::Debug {
DiagnosticImportance::Primary DiagnosticImportance::Primary
} }
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx>; fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx>;
} }
#[derive(Debug)] #[derive(Debug)]
@ -62,7 +62,7 @@ impl<'tcx> NonConstOp<'tcx> for FloatingPointOp {
} }
} }
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
feature_err( feature_err(
&ccx.tcx.sess, &ccx.tcx.sess,
sym::const_fn_floating_point_arithmetic, sym::const_fn_floating_point_arithmetic,
@ -76,7 +76,7 @@ impl<'tcx> NonConstOp<'tcx> for FloatingPointOp {
#[derive(Debug)] #[derive(Debug)]
pub struct FnCallIndirect; pub struct FnCallIndirect;
impl<'tcx> NonConstOp<'tcx> for FnCallIndirect { impl<'tcx> NonConstOp<'tcx> for FnCallIndirect {
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
ccx.dcx().create_err(errors::UnallowedFnPointerCall { span, kind: ccx.const_kind() }) ccx.dcx().create_err(errors::UnallowedFnPointerCall { span, kind: ccx.const_kind() })
} }
} }
@ -96,7 +96,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> {
// FIXME: make this translatable // FIXME: make this translatable
#[allow(rustc::diagnostic_outside_of_impl)] #[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::untranslatable_diagnostic)]
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, _: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, _: Span) -> Diag<'tcx> {
let FnCallNonConst { caller, callee, args, span, call_source, feature } = *self; let FnCallNonConst { caller, callee, args, span, call_source, feature } = *self;
let ConstCx { tcx, param_env, .. } = *ccx; let ConstCx { tcx, param_env, .. } = *ccx;
@ -317,7 +317,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> {
pub struct FnCallUnstable(pub DefId, pub Option<Symbol>); pub struct FnCallUnstable(pub DefId, pub Option<Symbol>);
impl<'tcx> NonConstOp<'tcx> for FnCallUnstable { impl<'tcx> NonConstOp<'tcx> for FnCallUnstable {
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
let FnCallUnstable(def_id, feature) = *self; let FnCallUnstable(def_id, feature) = *self;
let mut err = ccx let mut err = ccx
@ -353,7 +353,7 @@ impl<'tcx> NonConstOp<'tcx> for Coroutine {
} }
} }
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
let msg = format!("{:#}s are not allowed in {}s", self.0, ccx.const_kind()); let msg = format!("{:#}s are not allowed in {}s", self.0, ccx.const_kind());
if let hir::CoroutineKind::Desugared( if let hir::CoroutineKind::Desugared(
hir::CoroutineDesugaring::Async, hir::CoroutineDesugaring::Async,
@ -373,7 +373,7 @@ impl<'tcx> NonConstOp<'tcx> for Coroutine {
#[derive(Debug)] #[derive(Debug)]
pub struct HeapAllocation; pub struct HeapAllocation;
impl<'tcx> NonConstOp<'tcx> for HeapAllocation { impl<'tcx> NonConstOp<'tcx> for HeapAllocation {
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
ccx.dcx().create_err(errors::UnallowedHeapAllocations { ccx.dcx().create_err(errors::UnallowedHeapAllocations {
span, span,
kind: ccx.const_kind(), kind: ccx.const_kind(),
@ -385,7 +385,7 @@ impl<'tcx> NonConstOp<'tcx> for HeapAllocation {
#[derive(Debug)] #[derive(Debug)]
pub struct InlineAsm; pub struct InlineAsm;
impl<'tcx> NonConstOp<'tcx> for InlineAsm { impl<'tcx> NonConstOp<'tcx> for InlineAsm {
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
ccx.dcx().create_err(errors::UnallowedInlineAsm { span, kind: ccx.const_kind() }) ccx.dcx().create_err(errors::UnallowedInlineAsm { span, kind: ccx.const_kind() })
} }
} }
@ -396,7 +396,7 @@ pub struct LiveDrop<'tcx> {
pub dropped_ty: Ty<'tcx>, pub dropped_ty: Ty<'tcx>,
} }
impl<'tcx> NonConstOp<'tcx> for LiveDrop<'tcx> { impl<'tcx> NonConstOp<'tcx> for LiveDrop<'tcx> {
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
ccx.dcx().create_err(errors::LiveDrop { ccx.dcx().create_err(errors::LiveDrop {
span, span,
dropped_ty: self.dropped_ty, dropped_ty: self.dropped_ty,
@ -414,7 +414,7 @@ impl<'tcx> NonConstOp<'tcx> for TransientCellBorrow {
fn status_in_item(&self, _: &ConstCx<'_, 'tcx>) -> Status { fn status_in_item(&self, _: &ConstCx<'_, 'tcx>) -> Status {
Status::Unstable(sym::const_refs_to_cell) Status::Unstable(sym::const_refs_to_cell)
} }
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
ccx.tcx ccx.tcx
.sess .sess
.create_feature_err(errors::InteriorMutabilityBorrow { span }, sym::const_refs_to_cell) .create_feature_err(errors::InteriorMutabilityBorrow { span }, sym::const_refs_to_cell)
@ -432,7 +432,7 @@ impl<'tcx> NonConstOp<'tcx> for CellBorrow {
// triggers its own errors. Only show this one if that does not happen. // triggers its own errors. Only show this one if that does not happen.
DiagnosticImportance::Secondary DiagnosticImportance::Secondary
} }
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
// FIXME: Maybe a more elegant solution to this if else case // FIXME: Maybe a more elegant solution to this if else case
if let hir::ConstContext::Static(_) = ccx.const_kind() { if let hir::ConstContext::Static(_) = ccx.const_kind() {
ccx.dcx().create_err(errors::InteriorMutableDataRefer { ccx.dcx().create_err(errors::InteriorMutableDataRefer {
@ -469,7 +469,7 @@ impl<'tcx> NonConstOp<'tcx> for MutBorrow {
DiagnosticImportance::Secondary DiagnosticImportance::Secondary
} }
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
match self.0 { match self.0 {
hir::BorrowKind::Raw => ccx.tcx.dcx().create_err(errors::UnallowedMutableRaw { hir::BorrowKind::Raw => ccx.tcx.dcx().create_err(errors::UnallowedMutableRaw {
span, span,
@ -493,7 +493,7 @@ impl<'tcx> NonConstOp<'tcx> for TransientMutBorrow {
Status::Unstable(sym::const_mut_refs) Status::Unstable(sym::const_mut_refs)
} }
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
let kind = ccx.const_kind(); let kind = ccx.const_kind();
match self.0 { match self.0 {
hir::BorrowKind::Raw => ccx hir::BorrowKind::Raw => ccx
@ -520,7 +520,7 @@ impl<'tcx> NonConstOp<'tcx> for MutDeref {
DiagnosticImportance::Secondary DiagnosticImportance::Secondary
} }
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
ccx.tcx.sess.create_feature_err( ccx.tcx.sess.create_feature_err(
errors::MutDerefErr { span, kind: ccx.const_kind() }, errors::MutDerefErr { span, kind: ccx.const_kind() },
sym::const_mut_refs, sym::const_mut_refs,
@ -532,7 +532,7 @@ impl<'tcx> NonConstOp<'tcx> for MutDeref {
#[derive(Debug)] #[derive(Debug)]
pub struct PanicNonStr; pub struct PanicNonStr;
impl<'tcx> NonConstOp<'tcx> for PanicNonStr { impl<'tcx> NonConstOp<'tcx> for PanicNonStr {
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
ccx.dcx().create_err(errors::PanicNonStrErr { span }) ccx.dcx().create_err(errors::PanicNonStrErr { span })
} }
} }
@ -543,7 +543,7 @@ impl<'tcx> NonConstOp<'tcx> for PanicNonStr {
#[derive(Debug)] #[derive(Debug)]
pub struct RawPtrComparison; pub struct RawPtrComparison;
impl<'tcx> NonConstOp<'tcx> for RawPtrComparison { impl<'tcx> NonConstOp<'tcx> for RawPtrComparison {
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
// FIXME(const_trait_impl): revert to span_bug? // FIXME(const_trait_impl): revert to span_bug?
ccx.dcx().create_err(errors::RawPtrComparisonErr { span }) ccx.dcx().create_err(errors::RawPtrComparisonErr { span })
} }
@ -556,7 +556,7 @@ impl<'tcx> NonConstOp<'tcx> for RawMutPtrDeref {
Status::Unstable(sym::const_mut_refs) Status::Unstable(sym::const_mut_refs)
} }
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
feature_err( feature_err(
&ccx.tcx.sess, &ccx.tcx.sess,
sym::const_mut_refs, sym::const_mut_refs,
@ -572,7 +572,7 @@ impl<'tcx> NonConstOp<'tcx> for RawMutPtrDeref {
#[derive(Debug)] #[derive(Debug)]
pub struct RawPtrToIntCast; pub struct RawPtrToIntCast;
impl<'tcx> NonConstOp<'tcx> for RawPtrToIntCast { impl<'tcx> NonConstOp<'tcx> for RawPtrToIntCast {
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
ccx.dcx().create_err(errors::RawPtrToIntErr { span }) ccx.dcx().create_err(errors::RawPtrToIntErr { span })
} }
} }
@ -589,7 +589,7 @@ impl<'tcx> NonConstOp<'tcx> for StaticAccess {
} }
} }
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
let mut err = feature_err( let mut err = feature_err(
&ccx.tcx.sess, &ccx.tcx.sess,
sym::const_refs_to_static, sym::const_refs_to_static,
@ -609,7 +609,7 @@ impl<'tcx> NonConstOp<'tcx> for StaticAccess {
#[derive(Debug)] #[derive(Debug)]
pub struct ThreadLocalAccess; pub struct ThreadLocalAccess;
impl<'tcx> NonConstOp<'tcx> for ThreadLocalAccess { impl<'tcx> NonConstOp<'tcx> for ThreadLocalAccess {
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
ccx.dcx().create_err(errors::ThreadLocalAccessErr { span }) ccx.dcx().create_err(errors::ThreadLocalAccessErr { span })
} }
} }
@ -634,7 +634,7 @@ pub mod ty {
} }
} }
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
feature_err( feature_err(
&ccx.tcx.sess, &ccx.tcx.sess,
sym::const_mut_refs, sym::const_mut_refs,

View file

@ -45,29 +45,29 @@ pub enum DiagnosticArgValue {
pub type DiagnosticArgMap = FxIndexMap<DiagnosticArgName, DiagnosticArgValue>; pub type DiagnosticArgMap = FxIndexMap<DiagnosticArgName, DiagnosticArgValue>;
/// Trait for types that `DiagnosticBuilder::emit` can return as a "guarantee" /// Trait for types that `Diag::emit` can return as a "guarantee" (or "proof")
/// (or "proof") token that the emission happened. /// token that the emission happened.
pub trait EmissionGuarantee: Sized { pub trait EmissionGuarantee: Sized {
/// This exists so that bugs and fatal errors can both result in `!` (an /// This exists so that bugs and fatal errors can both result in `!` (an
/// abort) when emitted, but have different aborting behaviour. /// abort) when emitted, but have different aborting behaviour.
type EmitResult = Self; type EmitResult = Self;
/// Implementation of `DiagnosticBuilder::emit`, fully controlled by each /// Implementation of `Diag::emit`, fully controlled by each `impl` of
/// `impl` of `EmissionGuarantee`, to make it impossible to create a value /// `EmissionGuarantee`, to make it impossible to create a value of
/// of `Self::EmitResult` without actually performing the emission. /// `Self::EmitResult` without actually performing the emission.
#[track_caller] #[track_caller]
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult; fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult;
} }
impl EmissionGuarantee for ErrorGuaranteed { impl EmissionGuarantee for ErrorGuaranteed {
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult { fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
db.emit_producing_error_guaranteed() diag.emit_producing_error_guaranteed()
} }
} }
impl EmissionGuarantee for () { impl EmissionGuarantee for () {
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult { fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
db.emit_producing_nothing(); diag.emit_producing_nothing();
} }
} }
@ -79,8 +79,8 @@ pub struct BugAbort;
impl EmissionGuarantee for BugAbort { impl EmissionGuarantee for BugAbort {
type EmitResult = !; type EmitResult = !;
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult { fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
db.emit_producing_nothing(); diag.emit_producing_nothing();
panic::panic_any(ExplicitBug); panic::panic_any(ExplicitBug);
} }
} }
@ -93,15 +93,15 @@ pub struct FatalAbort;
impl EmissionGuarantee for FatalAbort { impl EmissionGuarantee for FatalAbort {
type EmitResult = !; type EmitResult = !;
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult { fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
db.emit_producing_nothing(); diag.emit_producing_nothing();
crate::FatalError.raise() crate::FatalError.raise()
} }
} }
impl EmissionGuarantee for rustc_span::fatal_error::FatalError { impl EmissionGuarantee for rustc_span::fatal_error::FatalError {
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult { fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
db.emit_producing_nothing(); diag.emit_producing_nothing();
rustc_span::fatal_error::FatalError rustc_span::fatal_error::FatalError
} }
} }
@ -112,7 +112,7 @@ impl EmissionGuarantee for rustc_span::fatal_error::FatalError {
pub trait IntoDiagnostic<'a, G: EmissionGuarantee = ErrorGuaranteed> { pub trait IntoDiagnostic<'a, G: EmissionGuarantee = ErrorGuaranteed> {
/// Write out as a diagnostic out of `DiagCtxt`. /// Write out as a diagnostic out of `DiagCtxt`.
#[must_use] #[must_use]
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G>; fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G>;
} }
impl<'a, T, G> IntoDiagnostic<'a, G> for Spanned<T> impl<'a, T, G> IntoDiagnostic<'a, G> for Spanned<T>
@ -120,7 +120,7 @@ where
T: IntoDiagnostic<'a, G>, T: IntoDiagnostic<'a, G>,
G: EmissionGuarantee, G: EmissionGuarantee,
{ {
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
self.node.into_diagnostic(dcx, level).with_span(self.span) self.node.into_diagnostic(dcx, level).with_span(self.span)
} }
} }
@ -157,7 +157,7 @@ where
Self: Sized, Self: Sized,
{ {
/// Add a subdiagnostic to an existing diagnostic. /// Add a subdiagnostic to an existing diagnostic.
fn add_to_diagnostic<G: EmissionGuarantee>(self, diag: &mut DiagnosticBuilder<'_, G>) { fn add_to_diagnostic<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
self.add_to_diagnostic_with(diag, |_, m| m); self.add_to_diagnostic_with(diag, |_, m| m);
} }
@ -165,20 +165,20 @@ where
/// (to optionally perform eager translation). /// (to optionally perform eager translation).
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
f: F, f: F,
); );
} }
pub trait SubdiagnosticMessageOp<G> = pub trait SubdiagnosticMessageOp<G> =
Fn(&mut DiagnosticBuilder<'_, G>, SubdiagnosticMessage) -> SubdiagnosticMessage; Fn(&mut Diag<'_, G>, SubdiagnosticMessage) -> SubdiagnosticMessage;
/// Trait implemented by lint types. This should not be implemented manually. Instead, use /// Trait implemented by lint types. This should not be implemented manually. Instead, use
/// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic]. /// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic].
#[rustc_diagnostic_item = "DecorateLint"] #[rustc_diagnostic_item = "DecorateLint"]
pub trait DecorateLint<'a, G: EmissionGuarantee> { pub trait DecorateLint<'a, G: EmissionGuarantee> {
/// Decorate and emit a lint. /// Decorate and emit a lint.
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, G>); fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, G>);
fn msg(&self) -> DiagnosticMessage; fn msg(&self) -> DiagnosticMessage;
} }
@ -261,10 +261,10 @@ impl StringPart {
} }
} }
/// The main part of a diagnostic. Note that `DiagnosticBuilder`, which wraps /// The main part of a diagnostic. Note that `Diag`, which wraps this type, is
/// this type, is used for most operations, and should be used instead whenever /// used for most operations, and should be used instead whenever possible.
/// possible. This type should only be used when `DiagnosticBuilder`'s lifetime /// This type should only be used when `Diag`'s lifetime causes difficulties,
/// causes difficulties, e.g. when storing diagnostics within `DiagCtxt`. /// e.g. when storing diagnostics within `DiagCtxt`.
#[must_use] #[must_use]
#[derive(Clone, Debug, Encodable, Decodable)] #[derive(Clone, Debug, Encodable, Decodable)]
pub struct DiagInner { pub struct DiagInner {
@ -374,7 +374,7 @@ impl DiagInner {
} }
} }
// See comment on `DiagnosticBuilder::subdiagnostic_message_to_diagnostic_message`. // See comment on `Diag::subdiagnostic_message_to_diagnostic_message`.
pub(crate) fn subdiagnostic_message_to_diagnostic_message( pub(crate) fn subdiagnostic_message_to_diagnostic_message(
&self, &self,
attr: impl Into<SubdiagnosticMessage>, attr: impl Into<SubdiagnosticMessage>,
@ -463,42 +463,37 @@ pub struct Subdiag {
/// that it has been emitted or cancelled. /// that it has been emitted or cancelled.
/// - The `EmissionGuarantee`, which determines the type returned from `emit`. /// - The `EmissionGuarantee`, which determines the type returned from `emit`.
/// ///
/// Each constructed `DiagnosticBuilder` must be consumed by a function such as /// Each constructed `Diag` must be consumed by a function such as `emit`,
/// `emit`, `cancel`, `delay_as_bug`, or `into_diagnostic`. A panic occurrs if a /// `cancel`, `delay_as_bug`, or `into_diagnostic`. A panic occurrs if a `Diag`
/// `DiagnosticBuilder` is dropped without being consumed by one of these /// is dropped without being consumed by one of these functions.
/// functions.
/// ///
/// If there is some state in a downstream crate you would like to /// If there is some state in a downstream crate you would like to access in
/// access in the methods of `DiagnosticBuilder` here, consider /// the methods of `Diag` here, consider extending `DiagCtxtFlags`.
/// extending `DiagCtxtFlags`.
#[must_use] #[must_use]
pub struct DiagnosticBuilder<'a, G: EmissionGuarantee = ErrorGuaranteed> { pub struct Diag<'a, G: EmissionGuarantee = ErrorGuaranteed> {
pub dcx: &'a DiagCtxt, pub dcx: &'a DiagCtxt,
/// Why the `Option`? It is always `Some` until the `DiagnosticBuilder` is /// Why the `Option`? It is always `Some` until the `Diag` is consumed via
/// consumed via `emit`, `cancel`, etc. At that point it is consumed and /// `emit`, `cancel`, etc. At that point it is consumed and replaced with
/// replaced with `None`. Then `drop` checks that it is `None`; if not, it /// `None`. Then `drop` checks that it is `None`; if not, it panics because
/// panics because a diagnostic was built but not used. /// a diagnostic was built but not used.
/// ///
/// Why the Box? `DiagInner` is a large type, and `DiagnosticBuilder` is /// Why the Box? `DiagInner` is a large type, and `Diag` is often used as a
/// often used as a return value, especially within the frequently-used /// return value, especially within the frequently-used `PResult` type. In
/// `PResult` type. In theory, return value optimization (RVO) should avoid /// theory, return value optimization (RVO) should avoid unnecessary
/// unnecessary copying. In practice, it does not (at the time of writing). /// copying. In practice, it does not (at the time of writing).
diag: Option<Box<DiagInner>>, diag: Option<Box<DiagInner>>,
_marker: PhantomData<G>, _marker: PhantomData<G>,
} }
// Cloning a `DiagnosticBuilder` is a recipe for a diagnostic being emitted // Cloning a `Diag` is a recipe for a diagnostic being emitted twice, which
// twice, which would be bad. // would be bad.
impl<G> !Clone for DiagnosticBuilder<'_, G> {} impl<G> !Clone for Diag<'_, G> {}
rustc_data_structures::static_assert_size!( rustc_data_structures::static_assert_size!(Diag<'_, ()>, 2 * std::mem::size_of::<usize>());
DiagnosticBuilder<'_, ()>,
2 * std::mem::size_of::<usize>()
);
impl<G: EmissionGuarantee> Deref for DiagnosticBuilder<'_, G> { impl<G: EmissionGuarantee> Deref for Diag<'_, G> {
type Target = DiagInner; type Target = DiagInner;
fn deref(&self) -> &DiagInner { fn deref(&self) -> &DiagInner {
@ -506,20 +501,20 @@ impl<G: EmissionGuarantee> Deref for DiagnosticBuilder<'_, G> {
} }
} }
impl<G: EmissionGuarantee> DerefMut for DiagnosticBuilder<'_, G> { impl<G: EmissionGuarantee> DerefMut for Diag<'_, G> {
fn deref_mut(&mut self) -> &mut DiagInner { fn deref_mut(&mut self) -> &mut DiagInner {
self.diag.as_mut().unwrap() self.diag.as_mut().unwrap()
} }
} }
impl<G: EmissionGuarantee> Debug for DiagnosticBuilder<'_, G> { impl<G: EmissionGuarantee> Debug for Diag<'_, G> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.diag.fmt(f) self.diag.fmt(f)
} }
} }
/// `DiagnosticBuilder` impls many `&mut self -> &mut Self` methods. Each one /// `Diag` impls many `&mut self -> &mut Self` methods. Each one modifies an
/// modifies an existing diagnostic, either in a standalone fashion, e.g. /// existing diagnostic, either in a standalone fashion, e.g.
/// `err.code(code);`, or in a chained fashion to make multiple modifications, /// `err.code(code);`, or in a chained fashion to make multiple modifications,
/// e.g. `err.code(code).span(span);`. /// e.g. `err.code(code).span(span);`.
/// ///
@ -546,14 +541,14 @@ macro_rules! with_fn {
} => { } => {
// The original function. // The original function.
$(#[$attrs])* $(#[$attrs])*
#[doc = concat!("See [`DiagnosticBuilder::", stringify!($f), "()`].")] #[doc = concat!("See [`Diag::", stringify!($f), "()`].")]
pub fn $f(&mut $self, $($name: $ty),*) -> &mut Self { pub fn $f(&mut $self, $($name: $ty),*) -> &mut Self {
$($body)* $($body)*
} }
// The `with_*` variant. // The `with_*` variant.
$(#[$attrs])* $(#[$attrs])*
#[doc = concat!("See [`DiagnosticBuilder::", stringify!($f), "()`].")] #[doc = concat!("See [`Diag::", stringify!($f), "()`].")]
pub fn $with_f(mut $self, $($name: $ty),*) -> Self { pub fn $with_f(mut $self, $($name: $ty),*) -> Self {
$self.$f($($name),*); $self.$f($($name),*);
$self $self
@ -561,15 +556,14 @@ macro_rules! with_fn {
}; };
} }
impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { impl<'a, G: EmissionGuarantee> Diag<'a, G> {
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn new<M: Into<DiagnosticMessage>>(dcx: &'a DiagCtxt, level: Level, message: M) -> Self { pub fn new<M: Into<DiagnosticMessage>>(dcx: &'a DiagCtxt, level: Level, message: M) -> Self {
Self::new_diagnostic(dcx, DiagInner::new(level, message)) Self::new_diagnostic(dcx, DiagInner::new(level, message))
} }
/// Creates a new `DiagnosticBuilder` with an already constructed /// Creates a new `Diag` with an already constructed diagnostic.
/// diagnostic.
#[track_caller] #[track_caller]
pub(crate) fn new_diagnostic(dcx: &'a DiagCtxt, diag: DiagInner) -> Self { pub(crate) fn new_diagnostic(dcx: &'a DiagCtxt, diag: DiagInner) -> Self {
debug!("Created new diagnostic"); debug!("Created new diagnostic");
@ -715,7 +709,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
self self
} }
/// This is like [`DiagnosticBuilder::note()`], but it's only printed once. /// This is like [`Diag::note()`], but it's only printed once.
pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self { pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
self.sub(Level::OnceNote, msg, MultiSpan::new()); self.sub(Level::OnceNote, msg, MultiSpan::new());
self self
@ -723,7 +717,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
with_fn! { with_span_note, with_fn! { with_span_note,
/// Prints the span with a note above it. /// Prints the span with a note above it.
/// This is like [`DiagnosticBuilder::note()`], but it gets its own span. /// This is like [`Diag::note()`], but it gets its own span.
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
pub fn span_note( pub fn span_note(
&mut self, &mut self,
@ -735,7 +729,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
} } } }
/// Prints the span with a note above it. /// Prints the span with a note above it.
/// This is like [`DiagnosticBuilder::note_once()`], but it gets its own span. /// This is like [`Diag::note_once()`], but it gets its own span.
pub fn span_note_once<S: Into<MultiSpan>>( pub fn span_note_once<S: Into<MultiSpan>>(
&mut self, &mut self,
sp: S, sp: S,
@ -754,7 +748,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
} } } }
/// Prints the span with a warning above it. /// Prints the span with a warning above it.
/// This is like [`DiagnosticBuilder::warn()`], but it gets its own span. /// This is like [`Diag::warn()`], but it gets its own span.
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
pub fn span_warn<S: Into<MultiSpan>>( pub fn span_warn<S: Into<MultiSpan>>(
&mut self, &mut self,
@ -773,7 +767,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
self self
} } } }
/// This is like [`DiagnosticBuilder::help()`], but it's only printed once. /// This is like [`Diag::help()`], but it's only printed once.
pub fn help_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self { pub fn help_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
self.sub(Level::OnceHelp, msg, MultiSpan::new()); self.sub(Level::OnceHelp, msg, MultiSpan::new());
self self
@ -786,7 +780,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
} }
/// Prints the span with some help above it. /// Prints the span with some help above it.
/// This is like [`DiagnosticBuilder::help()`], but it gets its own span. /// This is like [`Diag::help()`], but it gets its own span.
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
pub fn span_help<S: Into<MultiSpan>>( pub fn span_help<S: Into<MultiSpan>>(
&mut self, &mut self,
@ -856,7 +850,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
) )
} }
/// [`DiagnosticBuilder::multipart_suggestion()`] but you can set the [`SuggestionStyle`]. /// [`Diag::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
pub fn multipart_suggestion_with_style( pub fn multipart_suggestion_with_style(
&mut self, &mut self,
msg: impl Into<SubdiagnosticMessage>, msg: impl Into<SubdiagnosticMessage>,
@ -948,7 +942,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
self self
} } } }
/// [`DiagnosticBuilder::span_suggestion()`] but you can set the [`SuggestionStyle`]. /// [`Diag::span_suggestion()`] but you can set the [`SuggestionStyle`].
pub fn span_suggestion_with_style( pub fn span_suggestion_with_style(
&mut self, &mut self,
sp: Span, sp: Span,
@ -993,7 +987,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
with_fn! { with_span_suggestions, with_fn! { with_span_suggestions,
/// Prints out a message with multiple suggested edits of the code. /// Prints out a message with multiple suggested edits of the code.
/// See also [`DiagnosticBuilder::span_suggestion()`]. /// See also [`Diag::span_suggestion()`].
pub fn span_suggestions( pub fn span_suggestions(
&mut self, &mut self,
sp: Span, sp: Span,
@ -1039,7 +1033,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
/// Prints out a message with multiple suggested edits of the code, where each edit consists of /// Prints out a message with multiple suggested edits of the code, where each edit consists of
/// multiple parts. /// multiple parts.
/// See also [`DiagnosticBuilder::multipart_suggestion()`]. /// See also [`Diag::multipart_suggestion()`].
pub fn multipart_suggestions( pub fn multipart_suggestions(
&mut self, &mut self,
msg: impl Into<SubdiagnosticMessage>, msg: impl Into<SubdiagnosticMessage>,
@ -1235,9 +1229,9 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
self.children.push(sub); self.children.push(sub);
} }
/// Takes the diagnostic. For use by methods that consume the /// Takes the diagnostic. For use by methods that consume the Diag: `emit`,
/// DiagnosticBuilder: `emit`, `cancel`, etc. Afterwards, `drop` is the /// `cancel`, etc. Afterwards, `drop` is the only code that will be run on
/// only code that will be run on `self`. /// `self`.
fn take_diag(&mut self) -> DiagInner { fn take_diag(&mut self) -> DiagInner {
Box::into_inner(self.diag.take().unwrap()) Box::into_inner(self.diag.take().unwrap())
} }
@ -1319,9 +1313,9 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
} }
} }
/// Destructor bomb: every `DiagnosticBuilder` must be consumed (emitted, /// Destructor bomb: every `Diag` must be consumed (emitted, cancelled, etc.)
/// cancelled, etc.) or we emit a bug. /// or we emit a bug.
impl<G: EmissionGuarantee> Drop for DiagnosticBuilder<'_, G> { impl<G: EmissionGuarantee> Drop for Diag<'_, G> {
fn drop(&mut self) { fn drop(&mut self) {
match self.diag.take() { match self.diag.take() {
Some(diag) if !panicking() => { Some(diag) if !panicking() => {

View file

@ -1,7 +1,7 @@
use crate::diagnostic::DiagnosticLocation; use crate::diagnostic::DiagnosticLocation;
use crate::{fluent_generated as fluent, AddToDiagnostic}; use crate::{fluent_generated as fluent, AddToDiagnostic};
use crate::{ use crate::{
DiagCtxt, DiagnosticArgValue, DiagnosticBuilder, EmissionGuarantee, ErrCode, IntoDiagnostic, Diag, DiagCtxt, DiagnosticArgValue, EmissionGuarantee, ErrCode, IntoDiagnostic,
IntoDiagnosticArg, Level, SubdiagnosticMessageOp, IntoDiagnosticArg, Level, SubdiagnosticMessageOp,
}; };
use rustc_ast as ast; use rustc_ast as ast;
@ -250,44 +250,43 @@ impl<Id> IntoDiagnosticArg for hir::def::Res<Id> {
} }
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetDataLayoutErrors<'_> { impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetDataLayoutErrors<'_> {
fn into_diagnostic(self, dcx: &DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &DiagCtxt, level: Level) -> Diag<'_, G> {
match self { match self {
TargetDataLayoutErrors::InvalidAddressSpace { addr_space, err, cause } => { TargetDataLayoutErrors::InvalidAddressSpace { addr_space, err, cause } => {
DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_address_space) Diag::new(dcx, level, fluent::errors_target_invalid_address_space)
.with_arg("addr_space", addr_space) .with_arg("addr_space", addr_space)
.with_arg("cause", cause) .with_arg("cause", cause)
.with_arg("err", err) .with_arg("err", err)
} }
TargetDataLayoutErrors::InvalidBits { kind, bit, cause, err } => { TargetDataLayoutErrors::InvalidBits { kind, bit, cause, err } => {
DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_bits) Diag::new(dcx, level, fluent::errors_target_invalid_bits)
.with_arg("kind", kind) .with_arg("kind", kind)
.with_arg("bit", bit) .with_arg("bit", bit)
.with_arg("cause", cause) .with_arg("cause", cause)
.with_arg("err", err) .with_arg("err", err)
} }
TargetDataLayoutErrors::MissingAlignment { cause } => { TargetDataLayoutErrors::MissingAlignment { cause } => {
DiagnosticBuilder::new(dcx, level, fluent::errors_target_missing_alignment) Diag::new(dcx, level, fluent::errors_target_missing_alignment)
.with_arg("cause", cause) .with_arg("cause", cause)
} }
TargetDataLayoutErrors::InvalidAlignment { cause, err } => { TargetDataLayoutErrors::InvalidAlignment { cause, err } => {
DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_alignment) Diag::new(dcx, level, fluent::errors_target_invalid_alignment)
.with_arg("cause", cause) .with_arg("cause", cause)
.with_arg("err_kind", err.diag_ident()) .with_arg("err_kind", err.diag_ident())
.with_arg("align", err.align()) .with_arg("align", err.align())
} }
TargetDataLayoutErrors::InconsistentTargetArchitecture { dl, target } => { TargetDataLayoutErrors::InconsistentTargetArchitecture { dl, target } => {
DiagnosticBuilder::new(dcx, level, fluent::errors_target_inconsistent_architecture) Diag::new(dcx, level, fluent::errors_target_inconsistent_architecture)
.with_arg("dl", dl) .with_arg("dl", dl)
.with_arg("target", target) .with_arg("target", target)
} }
TargetDataLayoutErrors::InconsistentTargetPointerWidth { pointer_size, target } => { TargetDataLayoutErrors::InconsistentTargetPointerWidth { pointer_size, target } => {
DiagnosticBuilder::new(dcx, level, fluent::errors_target_inconsistent_pointer_width) Diag::new(dcx, level, fluent::errors_target_inconsistent_pointer_width)
.with_arg("pointer_size", pointer_size) .with_arg("pointer_size", pointer_size)
.with_arg("target", target) .with_arg("target", target)
} }
TargetDataLayoutErrors::InvalidBitsSize { err } => { TargetDataLayoutErrors::InvalidBitsSize { err } => {
DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_bits_size) Diag::new(dcx, level, fluent::errors_target_invalid_bits_size).with_arg("err", err)
.with_arg("err", err)
} }
} }
} }
@ -301,7 +300,7 @@ pub struct SingleLabelManySpans {
impl AddToDiagnostic for SingleLabelManySpans { impl AddToDiagnostic for SingleLabelManySpans {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_: F, _: F,
) { ) {
diag.span_labels(self.spans, self.label); diag.span_labels(self.spans, self.label);

View file

@ -1,6 +1,6 @@
//! The current rustc diagnostics emitter. //! The current rustc diagnostics emitter.
//! //!
//! An `Emitter` takes care of generating the output from a `DiagnosticBuilder` struct. //! An `Emitter` takes care of generating the output from a `Diag` struct.
//! //!
//! There are various `Emitter` implementations that generate different output formats such as //! There are various `Emitter` implementations that generate different output formats such as
//! JSON and human readable output. //! JSON and human readable output.

View file

@ -37,10 +37,9 @@ extern crate self as rustc_errors;
pub use codes::*; pub use codes::*;
pub use diagnostic::{ pub use diagnostic::{
AddToDiagnostic, BugAbort, DecorateLint, DiagInner, DiagnosticArg, DiagnosticArgMap, AddToDiagnostic, BugAbort, DecorateLint, Diag, DiagInner, DiagnosticArg, DiagnosticArgMap,
DiagnosticArgName, DiagnosticArgValue, DiagnosticBuilder, DiagnosticStyledString, DiagnosticArgName, DiagnosticArgValue, DiagnosticStyledString, EmissionGuarantee, FatalAbort,
EmissionGuarantee, FatalAbort, IntoDiagnostic, IntoDiagnosticArg, StringPart, Subdiag, IntoDiagnostic, IntoDiagnosticArg, StringPart, Subdiag, SubdiagnosticMessageOp,
SubdiagnosticMessageOp,
}; };
pub use diagnostic_impls::{ pub use diagnostic_impls::{
DiagnosticArgFromDisplay, DiagnosticSymbolList, ExpectedLifetimeParameter, DiagnosticArgFromDisplay, DiagnosticSymbolList, ExpectedLifetimeParameter,
@ -98,7 +97,7 @@ mod styled_buffer;
mod tests; mod tests;
pub mod translation; pub mod translation;
pub type PErr<'a> = DiagnosticBuilder<'a>; pub type PErr<'a> = Diag<'a>;
pub type PResult<'a, T> = Result<T, PErr<'a>>; pub type PResult<'a, T> = Result<T, PErr<'a>>;
rustc_fluent_macro::fluent_messages! { "../messages.ftl" } rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
@ -736,7 +735,7 @@ impl DiagCtxt {
} }
/// Steal a previously stashed diagnostic with the given `Span` and [`StashKey`] as the key. /// Steal a previously stashed diagnostic with the given `Span` and [`StashKey`] as the key.
pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_, ()>> { pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<Diag<'_, ()>> {
let mut inner = self.inner.borrow_mut(); let mut inner = self.inner.borrow_mut();
let key = (span.with_parent(None), key); let key = (span.with_parent(None), key);
// FIXME(#120456) - is `swap_remove` correct? // FIXME(#120456) - is `swap_remove` correct?
@ -746,7 +745,7 @@ impl DiagCtxt {
inner.stashed_err_count -= 1; inner.stashed_err_count -= 1;
} }
} }
Some(DiagnosticBuilder::new_diagnostic(self, diag)) Some(Diag::new_diagnostic(self, diag))
} }
pub fn has_stashed_diagnostic(&self, span: Span, key: StashKey) -> bool { pub fn has_stashed_diagnostic(&self, span: Span, key: StashKey) -> bool {
@ -1000,8 +999,8 @@ impl DiagCtxt {
impl DiagCtxt { impl DiagCtxt {
// No `#[rustc_lint_diagnostics]` because bug messages aren't user-facing. // No `#[rustc_lint_diagnostics]` because bug messages aren't user-facing.
#[track_caller] #[track_caller]
pub fn struct_bug(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, BugAbort> { pub fn struct_bug(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_, BugAbort> {
DiagnosticBuilder::new(self, Bug, msg) Diag::new(self, Bug, msg)
} }
// No `#[rustc_lint_diagnostics]` because bug messages aren't user-facing. // No `#[rustc_lint_diagnostics]` because bug messages aren't user-facing.
@ -1016,7 +1015,7 @@ impl DiagCtxt {
&self, &self,
span: impl Into<MultiSpan>, span: impl Into<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, BugAbort> { ) -> Diag<'_, BugAbort> {
self.struct_bug(msg).with_span(span) self.struct_bug(msg).with_span(span)
} }
@ -1027,10 +1026,7 @@ impl DiagCtxt {
} }
#[track_caller] #[track_caller]
pub fn create_bug<'a>( pub fn create_bug<'a>(&'a self, bug: impl IntoDiagnostic<'a, BugAbort>) -> Diag<'a, BugAbort> {
&'a self,
bug: impl IntoDiagnostic<'a, BugAbort>,
) -> DiagnosticBuilder<'a, BugAbort> {
bug.into_diagnostic(self, Bug) bug.into_diagnostic(self, Bug)
} }
@ -1041,11 +1037,8 @@ impl DiagCtxt {
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn struct_fatal( pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_, FatalAbort> {
&self, Diag::new(self, Fatal, msg)
msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, FatalAbort> {
DiagnosticBuilder::new(self, Fatal, msg)
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
@ -1060,7 +1053,7 @@ impl DiagCtxt {
&self, &self,
span: impl Into<MultiSpan>, span: impl Into<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, FatalAbort> { ) -> Diag<'_, FatalAbort> {
self.struct_fatal(msg).with_span(span) self.struct_fatal(msg).with_span(span)
} }
@ -1074,7 +1067,7 @@ impl DiagCtxt {
pub fn create_fatal<'a>( pub fn create_fatal<'a>(
&'a self, &'a self,
fatal: impl IntoDiagnostic<'a, FatalAbort>, fatal: impl IntoDiagnostic<'a, FatalAbort>,
) -> DiagnosticBuilder<'a, FatalAbort> { ) -> Diag<'a, FatalAbort> {
fatal.into_diagnostic(self, Fatal) fatal.into_diagnostic(self, Fatal)
} }
@ -1087,7 +1080,7 @@ impl DiagCtxt {
pub fn create_almost_fatal<'a>( pub fn create_almost_fatal<'a>(
&'a self, &'a self,
fatal: impl IntoDiagnostic<'a, FatalError>, fatal: impl IntoDiagnostic<'a, FatalError>,
) -> DiagnosticBuilder<'a, FatalError> { ) -> Diag<'a, FatalError> {
fatal.into_diagnostic(self, Fatal) fatal.into_diagnostic(self, Fatal)
} }
@ -1102,8 +1095,8 @@ impl DiagCtxt {
// FIXME: This method should be removed (every error should have an associated error code). // FIXME: This method should be removed (every error should have an associated error code).
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn struct_err(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_> { pub fn struct_err(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_> {
DiagnosticBuilder::new(self, Error, msg) Diag::new(self, Error, msg)
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
@ -1118,7 +1111,7 @@ impl DiagCtxt {
&self, &self,
span: impl Into<MultiSpan>, span: impl Into<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_> { ) -> Diag<'_> {
self.struct_err(msg).with_span(span) self.struct_err(msg).with_span(span)
} }
@ -1133,7 +1126,7 @@ impl DiagCtxt {
} }
#[track_caller] #[track_caller]
pub fn create_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> DiagnosticBuilder<'a> { pub fn create_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> Diag<'a> {
err.into_diagnostic(self, Error) err.into_diagnostic(self, Error)
} }
@ -1146,7 +1139,7 @@ impl DiagCtxt {
// No `#[rustc_lint_diagnostics]` because bug messages aren't user-facing. // No `#[rustc_lint_diagnostics]` because bug messages aren't user-facing.
#[track_caller] #[track_caller]
pub fn delayed_bug(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed { pub fn delayed_bug(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
DiagnosticBuilder::<ErrorGuaranteed>::new(self, DelayedBug, msg).emit() Diag::<ErrorGuaranteed>::new(self, DelayedBug, msg).emit()
} }
/// Ensures that an error is printed. See `Level::DelayedBug`. /// Ensures that an error is printed. See `Level::DelayedBug`.
@ -1160,13 +1153,13 @@ impl DiagCtxt {
sp: impl Into<MultiSpan>, sp: impl Into<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> ErrorGuaranteed { ) -> ErrorGuaranteed {
DiagnosticBuilder::<ErrorGuaranteed>::new(self, DelayedBug, msg).with_span(sp).emit() Diag::<ErrorGuaranteed>::new(self, DelayedBug, msg).with_span(sp).emit()
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> { pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_, ()> {
DiagnosticBuilder::new(self, Warning, msg) Diag::new(self, Warning, msg)
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
@ -1181,7 +1174,7 @@ impl DiagCtxt {
&self, &self,
span: impl Into<MultiSpan>, span: impl Into<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, ()> { ) -> Diag<'_, ()> {
self.struct_warn(msg).with_span(span) self.struct_warn(msg).with_span(span)
} }
@ -1192,10 +1185,7 @@ impl DiagCtxt {
} }
#[track_caller] #[track_caller]
pub fn create_warn<'a>( pub fn create_warn<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) -> Diag<'a, ()> {
&'a self,
warning: impl IntoDiagnostic<'a, ()>,
) -> DiagnosticBuilder<'a, ()> {
warning.into_diagnostic(self, Warning) warning.into_diagnostic(self, Warning)
} }
@ -1206,8 +1196,8 @@ impl DiagCtxt {
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn struct_note(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> { pub fn struct_note(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_, ()> {
DiagnosticBuilder::new(self, Note, msg) Diag::new(self, Note, msg)
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
@ -1222,7 +1212,7 @@ impl DiagCtxt {
&self, &self,
span: impl Into<MultiSpan>, span: impl Into<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, ()> { ) -> Diag<'_, ()> {
self.struct_note(msg).with_span(span) self.struct_note(msg).with_span(span)
} }
@ -1233,10 +1223,7 @@ impl DiagCtxt {
} }
#[track_caller] #[track_caller]
pub fn create_note<'a>( pub fn create_note<'a>(&'a self, note: impl IntoDiagnostic<'a, ()>) -> Diag<'a, ()> {
&'a self,
note: impl IntoDiagnostic<'a, ()>,
) -> DiagnosticBuilder<'a, ()> {
note.into_diagnostic(self, Note) note.into_diagnostic(self, Note)
} }
@ -1247,23 +1234,20 @@ impl DiagCtxt {
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> { pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_, ()> {
DiagnosticBuilder::new(self, Help, msg) Diag::new(self, Help, msg)
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn struct_failure_note( pub fn struct_failure_note(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_, ()> {
&self, Diag::new(self, FailureNote, msg)
msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, ()> {
DiagnosticBuilder::new(self, FailureNote, msg)
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> { pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_, ()> {
DiagnosticBuilder::new(self, Allow, msg) Diag::new(self, Allow, msg)
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
@ -1272,8 +1256,8 @@ impl DiagCtxt {
&self, &self,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
id: LintExpectationId, id: LintExpectationId,
) -> DiagnosticBuilder<'_, ()> { ) -> Diag<'_, ()> {
DiagnosticBuilder::new(self, Expect(id), msg) Diag::new(self, Expect(id), msg)
} }
} }
@ -1552,8 +1536,8 @@ impl DiagCtxtInner {
// an ICE, and the more information the merrier. // an ICE, and the more information the merrier.
// //
// We are at the `DiagInner`/`DiagCtxtInner` level rather than // We are at the `DiagInner`/`DiagCtxtInner` level rather than
// the usual `DiagnosticBuilder`/`DiagCtxt` level, so we must // the usual `Diag`/`DiagCtxt` level, so we must augment `bug`
// augment `bug` in a lower-level fashion. // in a lower-level fashion.
bug.arg("level", bug.level); bug.arg("level", bug.level);
let msg = crate::fluent_generated::errors_invalid_flushed_delayed_diagnostic_level; let msg = crate::fluent_generated::errors_invalid_flushed_delayed_diagnostic_level;
let msg = self.eagerly_translate_for_subdiag(&bug, msg); // after the `arg` call let msg = self.eagerly_translate_for_subdiag(&bug, msg); // after the `arg` call
@ -1593,8 +1577,8 @@ impl DelayedDiagInner {
fn decorate(self, dcx: &DiagCtxtInner) -> DiagInner { fn decorate(self, dcx: &DiagCtxtInner) -> DiagInner {
// We are at the `DiagInner`/`DiagCtxtInner` level rather than the // We are at the `DiagInner`/`DiagCtxtInner` level rather than the
// usual `DiagnosticBuilder`/`DiagCtxt` level, so we must construct // usual `Diag`/`DiagCtxt` level, so we must construct `diag` in a
// `diag` in a lower-level fashion. // lower-level fashion.
let mut diag = self.inner; let mut diag = self.inner;
let msg = match self.note.status() { let msg = match self.note.status() {
BacktraceStatus::Captured => crate::fluent_generated::errors_delayed_at_with_newline, BacktraceStatus::Captured => crate::fluent_generated::errors_delayed_at_with_newline,
@ -1750,7 +1734,7 @@ impl Level {
// FIXME(eddyb) this doesn't belong here AFAICT, should be moved to callsite. // FIXME(eddyb) this doesn't belong here AFAICT, should be moved to callsite.
pub fn add_elided_lifetime_in_path_suggestion<G: EmissionGuarantee>( pub fn add_elided_lifetime_in_path_suggestion<G: EmissionGuarantee>(
source_map: &SourceMap, source_map: &SourceMap,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
n: usize, n: usize,
path_span: Span, path_span: Span,
incl_angl_brckt: bool, incl_angl_brckt: bool,
@ -1772,18 +1756,18 @@ pub fn add_elided_lifetime_in_path_suggestion<G: EmissionGuarantee>(
} }
pub fn report_ambiguity_error<'a, G: EmissionGuarantee>( pub fn report_ambiguity_error<'a, G: EmissionGuarantee>(
db: &mut DiagnosticBuilder<'a, G>, diag: &mut Diag<'a, G>,
ambiguity: rustc_lint_defs::AmbiguityErrorDiag, ambiguity: rustc_lint_defs::AmbiguityErrorDiag,
) { ) {
db.span_label(ambiguity.label_span, ambiguity.label_msg); diag.span_label(ambiguity.label_span, ambiguity.label_msg);
db.note(ambiguity.note_msg); diag.note(ambiguity.note_msg);
db.span_note(ambiguity.b1_span, ambiguity.b1_note_msg); diag.span_note(ambiguity.b1_span, ambiguity.b1_note_msg);
for help_msg in ambiguity.b1_help_msgs { for help_msg in ambiguity.b1_help_msgs {
db.help(help_msg); diag.help(help_msg);
} }
db.span_note(ambiguity.b2_span, ambiguity.b2_note_msg); diag.span_note(ambiguity.b2_span, ambiguity.b2_note_msg);
for help_msg in ambiguity.b2_help_msgs { for help_msg in ambiguity.b2_help_msgs {
db.help(help_msg); diag.help(help_msg);
} }
} }

View file

@ -13,7 +13,7 @@ use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind
use rustc_attr::{self as attr, Deprecation, Stability}; use rustc_attr::{self as attr, Deprecation, Stability};
use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::sync::{self, Lrc}; use rustc_data_structures::sync::{self, Lrc};
use rustc_errors::{Applicability, DiagCtxt, DiagnosticBuilder, ErrorGuaranteed, PResult}; use rustc_errors::{Applicability, Diag, DiagCtxt, ErrorGuaranteed, PResult};
use rustc_feature::Features; use rustc_feature::Features;
use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT; use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, RegisteredTools}; use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, RegisteredTools};
@ -1260,7 +1260,7 @@ pub fn expr_to_spanned_string<'a>(
err_msg: &'static str, err_msg: &'static str,
) -> Result< ) -> Result<
(Symbol, ast::StrStyle, Span), (Symbol, ast::StrStyle, Span),
Result<(DiagnosticBuilder<'a>, bool /* has_suggestions */), ErrorGuaranteed>, Result<(Diag<'a>, bool /* has_suggestions */), ErrorGuaranteed>,
> { > {
// Perform eager expansion on the expression. // Perform eager expansion on the expression.
// We want to be able to handle e.g., `concat!("foo", "bar")`. // We want to be able to handle e.g., `concat!("foo", "bar")`.

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, DiagCtxt, DiagnosticBuilder, DiagnosticMessage}; use rustc_errors::{Applicability, Diag, DiagCtxt, DiagnosticMessage};
use rustc_parse::parser::{Parser, Recovery}; use rustc_parse::parser::{Parser, Recovery};
use rustc_span::source_map::SourceMap; use rustc_span::source_map::SourceMap;
use rustc_span::symbol::Ident; use rustc_span::symbol::Ident;
@ -218,7 +218,7 @@ impl<'matcher> Tracker<'matcher> for FailureForwarder {
} }
pub(super) fn emit_frag_parse_err( pub(super) fn emit_frag_parse_err(
mut e: DiagnosticBuilder<'_>, mut e: Diag<'_>,
parser: &Parser<'_>, parser: &Parser<'_>,
orig_parser: &mut Parser<'_>, orig_parser: &mut Parser<'_>,
site_span: Span, site_span: Span,
@ -285,11 +285,7 @@ pub(super) fn emit_frag_parse_err(
e.emit() e.emit()
} }
pub(crate) fn annotate_err_with_kind( pub(crate) fn annotate_err_with_kind(err: &mut Diag<'_>, kind: AstFragmentKind, span: Span) {
err: &mut DiagnosticBuilder<'_>,
kind: AstFragmentKind,
span: Span,
) {
match kind { match kind {
AstFragmentKind::Ty => { AstFragmentKind::Ty => {
err.span_label(span, "this macro call doesn't expand to a type"); err.span_label(span, "this macro call doesn't expand to a type");
@ -315,12 +311,7 @@ enum ExplainDocComment {
}, },
} }
pub(super) fn annotate_doc_comment( pub(super) fn annotate_doc_comment(dcx: &DiagCtxt, err: &mut Diag<'_>, sm: &SourceMap, span: Span) {
dcx: &DiagCtxt,
err: &mut DiagnosticBuilder<'_>,
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(dcx, ExplainDocComment::Outer { span });

View file

@ -9,7 +9,7 @@ use rustc_ast::mut_visit::{self, MutVisitor};
use rustc_ast::token::{self, Delimiter, Token, TokenKind}; use rustc_ast::token::{self, Delimiter, Token, TokenKind};
use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree};
use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::fx::FxHashMap;
use rustc_errors::DiagnosticBuilder; use rustc_errors::Diag;
use rustc_errors::{pluralize, PResult}; use rustc_errors::{pluralize, PResult};
use rustc_span::hygiene::{LocalExpnId, Transparency}; use rustc_span::hygiene::{LocalExpnId, Transparency};
use rustc_span::symbol::{sym, Ident, MacroRulesNormalizedIdent}; use rustc_span::symbol::{sym, Ident, MacroRulesNormalizedIdent};
@ -622,12 +622,7 @@ where
/// Used by meta-variable expressions when an user input is out of the actual declared bounds. For /// Used by meta-variable expressions when an user input is out of the actual declared bounds. For
/// example, index(999999) in an repetition of only three elements. /// example, index(999999) in an repetition of only three elements.
fn out_of_bounds_err<'a>( fn out_of_bounds_err<'a>(cx: &ExtCtxt<'a>, max: usize, span: Span, ty: &str) -> Diag<'a> {
cx: &ExtCtxt<'a>,
max: usize,
span: Span,
ty: &str,
) -> DiagnosticBuilder<'a> {
let msg = if max == 0 { let msg = if max == 0 {
format!( format!(
"meta-variable expression `{ty}` with depth parameter \ "meta-variable expression `{ty}` with depth parameter \

View file

@ -4,7 +4,7 @@ use crate::errors::{
}; };
use rustc_ast::ptr::P; use rustc_ast::ptr::P;
use rustc_ast::{token, AttrVec, Attribute, Inline, Item, ModSpans}; use rustc_ast::{token, AttrVec, Attribute, Inline, Item, ModSpans};
use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed}; use rustc_errors::{Diag, ErrorGuaranteed};
use rustc_parse::new_parser_from_file; use rustc_parse::new_parser_from_file;
use rustc_parse::validate_attr; use rustc_parse::validate_attr;
use rustc_session::parse::ParseSess; use rustc_session::parse::ParseSess;
@ -43,7 +43,7 @@ pub enum ModError<'a> {
ModInBlock(Option<Ident>), ModInBlock(Option<Ident>),
FileNotFound(Ident, PathBuf, PathBuf), FileNotFound(Ident, PathBuf, PathBuf),
MultipleCandidates(Ident, PathBuf, PathBuf), MultipleCandidates(Ident, PathBuf, PathBuf),
ParserError(DiagnosticBuilder<'a>), ParserError(Diag<'a>),
} }
pub(crate) fn parse_external_mod( pub(crate) fn parse_external_mod(

View file

@ -11,7 +11,7 @@ use rustc_ast::util::literal::escape_byte_str_symbol;
use rustc_ast_pretty::pprust; use rustc_ast_pretty::pprust;
use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::Lrc; use rustc_data_structures::sync::Lrc;
use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed, MultiSpan, PResult}; use rustc_errors::{Diag, ErrorGuaranteed, MultiSpan, PResult};
use rustc_parse::lexer::nfc_normalize; use rustc_parse::lexer::nfc_normalize;
use rustc_parse::parse_stream_from_source_str; use rustc_parse::parse_stream_from_source_str;
use rustc_session::parse::ParseSess; use rustc_session::parse::ParseSess;
@ -513,8 +513,8 @@ impl server::FreeFunctions for Rustc<'_, '_> {
fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) { fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) {
let message = rustc_errors::DiagnosticMessage::from(diagnostic.message); let message = rustc_errors::DiagnosticMessage::from(diagnostic.message);
let mut diag: DiagnosticBuilder<'_, ()> = let mut diag: Diag<'_, ()> =
DiagnosticBuilder::new(&self.sess().dcx, diagnostic.level.to_internal(), message); Diag::new(&self.sess().dcx, diagnostic.level.to_internal(), message);
diag.span(MultiSpan::from_spans(diagnostic.spans)); diag.span(MultiSpan::from_spans(diagnostic.spans));
for child in diagnostic.children { for child in diagnostic.children {
diag.sub(child.level.to_internal(), child.message, MultiSpan::from_spans(child.spans)); diag.sub(child.level.to_internal(), child.message, MultiSpan::from_spans(child.spans));

View file

@ -9,7 +9,7 @@ use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::sorted_map::SortedMap;
use rustc_data_structures::unord::UnordMap; use rustc_data_structures::unord::UnordMap;
use rustc_errors::{ use rustc_errors::{
codes::*, pluralize, struct_span_code_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, codes::*, pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed,
}; };
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::def_id::{DefId, LocalDefId};
@ -371,7 +371,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
// FIXME(fmease): Heavily adapted from `rustc_hir_typeck::method::suggest`. Deduplicate. // FIXME(fmease): Heavily adapted from `rustc_hir_typeck::method::suggest`. Deduplicate.
fn note_ambiguous_inherent_assoc_type( fn note_ambiguous_inherent_assoc_type(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
candidates: Vec<DefId>, candidates: Vec<DefId>,
span: Span, span: Span,
) { ) {
@ -429,7 +429,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let tcx = self.tcx(); let tcx = self.tcx();
let adt_did = self_ty.ty_adt_def().map(|def| def.did()); let adt_did = self_ty.ty_adt_def().map(|def| def.did());
let add_def_label = |err: &mut DiagnosticBuilder<'_>| { let add_def_label = |err: &mut Diag<'_>| {
if let Some(did) = adt_did { if let Some(did) = adt_did {
err.span_label( err.span_label(
tcx.def_span(did), tcx.def_span(did),

View file

@ -6,7 +6,7 @@ use crate::astconv::{
use crate::structured_errors::{GenericArgsInfo, StructuredDiagnostic, WrongNumberOfGenericArgs}; use crate::structured_errors::{GenericArgsInfo, StructuredDiagnostic, WrongNumberOfGenericArgs};
use rustc_ast::ast::ParamKindOrd; use rustc_ast::ast::ParamKindOrd;
use rustc_errors::{ use rustc_errors::{
codes::*, struct_span_code_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, codes::*, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan,
}; };
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res}; use rustc_hir::def::{DefKind, Res};
@ -47,7 +47,7 @@ fn generic_arg_mismatch_err(
} }
} }
let add_braces_suggestion = |arg: &GenericArg<'_>, err: &mut DiagnosticBuilder<'_>| { let add_braces_suggestion = |arg: &GenericArg<'_>, err: &mut Diag<'_>| {
let suggestions = vec![ let suggestions = vec![
(arg.span().shrink_to_lo(), String::from("{ ")), (arg.span().shrink_to_lo(), String::from("{ ")),
(arg.span().shrink_to_hi(), String::from(" }")), (arg.span().shrink_to_hi(), String::from(" }")),

View file

@ -1,5 +1,5 @@
use rustc_ast::TraitObjectSyntax; use rustc_ast::TraitObjectSyntax;
use rustc_errors::{codes::*, DiagnosticBuilder, EmissionGuarantee, StashKey}; use rustc_errors::{codes::*, Diag, EmissionGuarantee, StashKey};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res}; use rustc_hir::def::{DefKind, Res};
use rustc_lint_defs::{builtin::BARE_TRAIT_OBJECTS, Applicability}; use rustc_lint_defs::{builtin::BARE_TRAIT_OBJECTS, Applicability};
@ -13,7 +13,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
pub(super) fn maybe_lint_blanket_trait_impl<G: EmissionGuarantee>( pub(super) fn maybe_lint_blanket_trait_impl<G: EmissionGuarantee>(
&self, &self,
self_ty: &hir::Ty<'_>, self_ty: &hir::Ty<'_>,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
) { ) {
let tcx = self.tcx(); let tcx = self.tcx();
let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id; let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
@ -75,11 +75,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
} }
/// Make sure that we are in the condition to suggest `impl Trait`. /// Make sure that we are in the condition to suggest `impl Trait`.
fn maybe_lint_impl_trait( fn maybe_lint_impl_trait(&self, self_ty: &hir::Ty<'_>, diag: &mut Diag<'_>) -> bool {
&self,
self_ty: &hir::Ty<'_>,
diag: &mut DiagnosticBuilder<'_>,
) -> bool {
let tcx = self.tcx(); let tcx = self.tcx();
let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id; let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
let (sig, generics, owner) = match tcx.hir_node_by_def_id(parent_id) { let (sig, generics, owner) = match tcx.hir_node_by_def_id(parent_id) {

View file

@ -18,8 +18,7 @@ use crate::require_c_abi_if_c_variadic;
use rustc_ast::TraitObjectSyntax; use rustc_ast::TraitObjectSyntax;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_errors::{ use rustc_errors::{
codes::*, struct_span_code_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, FatalError, codes::*, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, FatalError, MultiSpan,
MultiSpan,
}; };
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{CtorOf, DefKind, Namespace, Res}; use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
@ -1723,7 +1722,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
pub fn prohibit_generics<'a>( pub fn prohibit_generics<'a>(
&self, &self,
segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone, segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
extend: impl Fn(&mut DiagnosticBuilder<'_>), extend: impl Fn(&mut Diag<'_>),
) -> bool { ) -> bool {
let args = segments.clone().flat_map(|segment| segment.args().args); let args = segments.clone().flat_map(|segment| segment.args().args);
@ -2739,7 +2738,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
&self, &self,
constrained_regions: FxHashSet<ty::BoundRegionKind>, constrained_regions: FxHashSet<ty::BoundRegionKind>,
referenced_regions: FxHashSet<ty::BoundRegionKind>, referenced_regions: FxHashSet<ty::BoundRegionKind>,
generate_err: impl Fn(&str) -> DiagnosticBuilder<'tcx>, generate_err: impl Fn(&str) -> Diag<'tcx>,
) { ) {
for br in referenced_regions.difference(&constrained_regions) { for br in referenced_regions.difference(&constrained_regions) {
let br_name = match *br { let br_name = match *br {

View file

@ -1236,7 +1236,7 @@ fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) { fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
// Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate. // Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate.
// Here `idx` refers to the order of which the discriminant appears, and its index in `vs` // Here `idx` refers to the order of which the discriminant appears, and its index in `vs`
let report = |dis: Discr<'tcx>, idx, err: &mut DiagnosticBuilder<'_>| { let report = |dis: Discr<'tcx>, idx, err: &mut Diag<'_>| {
let var = adt.variant(idx); // HIR for the duplicate discriminant let var = adt.variant(idx); // HIR for the duplicate discriminant
let (span, display_discr) = match var.discr { let (span, display_discr) = match var.discr {
ty::VariantDiscr::Explicit(discr_def_id) => { ty::VariantDiscr::Explicit(discr_def_id) => {
@ -1296,7 +1296,7 @@ fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
let mut i = 0; let mut i = 0;
while i < discrs.len() { while i < discrs.len() {
let var_i_idx = discrs[i].0; let var_i_idx = discrs[i].0;
let mut error: Option<DiagnosticBuilder<'_, _>> = None; let mut error: Option<Diag<'_, _>> = None;
let mut o = i + 1; let mut o = i + 1;
while o < discrs.len() { while o < discrs.len() {

View file

@ -78,7 +78,7 @@ use std::num::NonZero;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_errors::ErrorGuaranteed; use rustc_errors::ErrorGuaranteed;
use rustc_errors::{pluralize, struct_span_code_err, DiagnosticBuilder}; use rustc_errors::{pluralize, struct_span_code_err, Diag};
use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::intravisit::Visitor; use rustc_hir::intravisit::Visitor;
use rustc_index::bit_set::BitSet; use rustc_index::bit_set::BitSet;

View file

@ -17,7 +17,7 @@
use rustc_data_structures::captures::Captures; use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_data_structures::unord::UnordMap; use rustc_data_structures::unord::UnordMap;
use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, StashKey}; use rustc_errors::{Applicability, Diag, ErrorGuaranteed, StashKey};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::DefKind; use rustc_hir::def::DefKind;
use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
@ -186,7 +186,7 @@ pub(crate) fn placeholder_type_error_diag<'tcx>(
suggest: bool, suggest: bool,
hir_ty: Option<&hir::Ty<'_>>, hir_ty: Option<&hir::Ty<'_>>,
kind: &'static str, kind: &'static str,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
if placeholder_types.is_empty() { if placeholder_types.is_empty() {
return bad_placeholder(tcx, additional_spans, kind); return bad_placeholder(tcx, additional_spans, kind);
} }
@ -335,7 +335,7 @@ fn bad_placeholder<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
mut spans: Vec<Span>, mut spans: Vec<Span>,
kind: &'static str, kind: &'static str,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let kind = if kind.ends_with('s') { format!("{kind}es") } else { format!("{kind}s") }; let kind = if kind.ends_with('s') { format!("{kind}es") } else { format!("{kind}s") };
spans.sort(); spans.sort();

View file

@ -1181,8 +1181,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
&& !self.tcx.asyncness(lifetime_ref.hir_id.owner.def_id).is_async() && !self.tcx.asyncness(lifetime_ref.hir_id.owner.def_id).is_async()
&& !self.tcx.features().anonymous_lifetime_in_impl_trait && !self.tcx.features().anonymous_lifetime_in_impl_trait
{ {
let mut diag: rustc_errors::DiagnosticBuilder<'_> = let mut diag: rustc_errors::Diag<'_> = rustc_session::parse::feature_err(
rustc_session::parse::feature_err(
&self.tcx.sess, &self.tcx.sess,
sym::anonymous_lifetime_in_impl_trait, sym::anonymous_lifetime_in_impl_trait,
lifetime_ref.ident.span, lifetime_ref.ident.span,

View file

@ -2,8 +2,7 @@
use crate::fluent_generated as fluent; use crate::fluent_generated as fluent;
use rustc_errors::{ use rustc_errors::{
codes::*, Applicability, DiagCtxt, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic, Level, codes::*, Applicability, Diag, DiagCtxt, EmissionGuarantee, IntoDiagnostic, Level, MultiSpan,
MultiSpan,
}; };
use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
use rustc_middle::ty::Ty; use rustc_middle::ty::Ty;
@ -359,8 +358,8 @@ pub struct MissingTypeParams {
// Manual implementation of `IntoDiagnostic` to be able to call `span_to_snippet`. // Manual implementation of `IntoDiagnostic` to be able to call `span_to_snippet`.
impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for MissingTypeParams { impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for MissingTypeParams {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
let mut err = DiagnosticBuilder::new(dcx, level, fluent::hir_analysis_missing_type_params); let mut err = Diag::new(dcx, level, fluent::hir_analysis_missing_type_params);
err.span(self.span); err.span(self.span);
err.code(E0393); err.code(E0393);
err.arg("parameterCount", self.missing_type_params.len()); err.arg("parameterCount", self.missing_type_params.len());

View file

@ -6,7 +6,7 @@ pub use self::{
missing_cast_for_variadic_arg::*, sized_unsized_cast::*, wrong_number_of_generic_args::*, missing_cast_for_variadic_arg::*, sized_unsized_cast::*, wrong_number_of_generic_args::*,
}; };
use rustc_errors::{DiagnosticBuilder, ErrCode}; use rustc_errors::{Diag, ErrCode};
use rustc_session::Session; use rustc_session::Session;
pub trait StructuredDiagnostic<'tcx> { pub trait StructuredDiagnostic<'tcx> {
@ -14,7 +14,7 @@ pub trait StructuredDiagnostic<'tcx> {
fn code(&self) -> ErrCode; fn code(&self) -> ErrCode;
fn diagnostic(&self) -> DiagnosticBuilder<'tcx> { fn diagnostic(&self) -> Diag<'tcx> {
let err = self.diagnostic_common(); let err = self.diagnostic_common();
if self.session().teach(self.code()) { if self.session().teach(self.code()) {
@ -24,13 +24,13 @@ pub trait StructuredDiagnostic<'tcx> {
} }
} }
fn diagnostic_common(&self) -> DiagnosticBuilder<'tcx>; fn diagnostic_common(&self) -> Diag<'tcx>;
fn diagnostic_regular(&self, err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> { fn diagnostic_regular(&self, err: Diag<'tcx>) -> Diag<'tcx> {
err err
} }
fn diagnostic_extended(&self, err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> { fn diagnostic_extended(&self, err: Diag<'tcx>) -> Diag<'tcx> {
err err
} }
} }

View file

@ -1,5 +1,5 @@
use crate::{errors, structured_errors::StructuredDiagnostic}; use crate::{errors, structured_errors::StructuredDiagnostic};
use rustc_errors::{codes::*, DiagnosticBuilder}; use rustc_errors::{codes::*, Diag};
use rustc_middle::ty::{Ty, TypeVisitableExt}; use rustc_middle::ty::{Ty, TypeVisitableExt};
use rustc_session::Session; use rustc_session::Session;
use rustc_span::Span; use rustc_span::Span;
@ -20,7 +20,7 @@ impl<'tcx> StructuredDiagnostic<'tcx> for MissingCastForVariadicArg<'tcx, '_> {
E0617 E0617
} }
fn diagnostic_common(&self) -> DiagnosticBuilder<'tcx> { fn diagnostic_common(&self) -> Diag<'tcx> {
let (sugg_span, replace, help) = let (sugg_span, replace, help) =
if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.span) { if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.span) {
(Some(self.span), format!("{} as {}", snippet, self.cast_ty), None) (Some(self.span), format!("{} as {}", snippet, self.cast_ty), None)
@ -44,7 +44,7 @@ impl<'tcx> StructuredDiagnostic<'tcx> for MissingCastForVariadicArg<'tcx, '_> {
err err
} }
fn diagnostic_extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> { fn diagnostic_extended(&self, mut err: Diag<'tcx>) -> Diag<'tcx> {
err.note(format!( err.note(format!(
"certain types, like `{}`, must be casted before passing them to a \ "certain types, like `{}`, must be casted before passing them to a \
variadic function, because of arcane ABI rules dictated by the C \ variadic function, because of arcane ABI rules dictated by the C \

View file

@ -1,5 +1,5 @@
use crate::{errors, structured_errors::StructuredDiagnostic}; use crate::{errors, structured_errors::StructuredDiagnostic};
use rustc_errors::{codes::*, DiagnosticBuilder}; use rustc_errors::{codes::*, Diag};
use rustc_middle::ty::{Ty, TypeVisitableExt}; use rustc_middle::ty::{Ty, TypeVisitableExt};
use rustc_session::Session; use rustc_session::Session;
use rustc_span::Span; use rustc_span::Span;
@ -20,7 +20,7 @@ impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCast<'tcx> {
E0607 E0607
} }
fn diagnostic_common(&self) -> DiagnosticBuilder<'tcx> { fn diagnostic_common(&self) -> Diag<'tcx> {
let mut err = self.sess.dcx().create_err(errors::CastThinPointerToFatPointer { let mut err = self.sess.dcx().create_err(errors::CastThinPointerToFatPointer {
span: self.span, span: self.span,
expr_ty: self.expr_ty, expr_ty: self.expr_ty,
@ -34,7 +34,7 @@ impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCast<'tcx> {
err err
} }
fn diagnostic_extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> { fn diagnostic_extended(&self, mut err: Diag<'tcx>) -> Diag<'tcx> {
err.help( err.help(
"Thin pointers are \"simple\" pointers: they are purely a reference to a "Thin pointers are \"simple\" pointers: they are purely a reference to a
memory address. memory address.

View file

@ -1,5 +1,5 @@
use crate::structured_errors::StructuredDiagnostic; use crate::structured_errors::StructuredDiagnostic;
use rustc_errors::{codes::*, pluralize, Applicability, DiagnosticBuilder, MultiSpan}; use rustc_errors::{codes::*, pluralize, Applicability, Diag, MultiSpan};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_middle::ty::{self as ty, AssocItems, AssocKind, TyCtxt}; use rustc_middle::ty::{self as ty, AssocItems, AssocKind, TyCtxt};
use rustc_session::Session; use rustc_session::Session;
@ -518,14 +518,14 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
} }
} }
fn start_diagnostics(&self) -> DiagnosticBuilder<'tcx> { fn start_diagnostics(&self) -> Diag<'tcx> {
let span = self.path_segment.ident.span; let span = self.path_segment.ident.span;
let msg = self.create_error_message(); let msg = self.create_error_message();
self.tcx.dcx().struct_span_err(span, msg).with_code(self.code()) self.tcx.dcx().struct_span_err(span, msg).with_code(self.code())
} }
/// Builds the `expected 1 type argument / supplied 2 type arguments` message. /// Builds the `expected 1 type argument / supplied 2 type arguments` message.
fn notify(&self, err: &mut DiagnosticBuilder<'_>) { fn notify(&self, err: &mut Diag<'_>) {
let (quantifier, bound) = self.get_quantifier_and_bound(); let (quantifier, bound) = self.get_quantifier_and_bound();
let provided_args = self.num_provided_args(); let provided_args = self.num_provided_args();
@ -577,7 +577,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
} }
} }
fn suggest(&self, err: &mut DiagnosticBuilder<'_>) { fn suggest(&self, err: &mut Diag<'_>) {
debug!( debug!(
"suggest(self.provided {:?}, self.gen_args.span(): {:?})", "suggest(self.provided {:?}, self.gen_args.span(): {:?})",
self.num_provided_args(), self.num_provided_args(),
@ -605,7 +605,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
/// ```text /// ```text
/// type Map = HashMap<String>; /// type Map = HashMap<String>;
/// ``` /// ```
fn suggest_adding_args(&self, err: &mut DiagnosticBuilder<'_>) { fn suggest_adding_args(&self, err: &mut Diag<'_>) {
if self.gen_args.parenthesized != hir::GenericArgsParentheses::No { if self.gen_args.parenthesized != hir::GenericArgsParentheses::No {
return; return;
} }
@ -624,7 +624,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
} }
} }
fn suggest_adding_lifetime_args(&self, err: &mut DiagnosticBuilder<'_>) { fn suggest_adding_lifetime_args(&self, err: &mut Diag<'_>) {
debug!("suggest_adding_lifetime_args(path_segment: {:?})", self.path_segment); debug!("suggest_adding_lifetime_args(path_segment: {:?})", self.path_segment);
let num_missing_args = self.num_missing_lifetime_args(); let num_missing_args = self.num_missing_lifetime_args();
let num_params_to_take = num_missing_args; let num_params_to_take = num_missing_args;
@ -678,7 +678,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
} }
} }
fn suggest_adding_type_and_const_args(&self, err: &mut DiagnosticBuilder<'_>) { fn suggest_adding_type_and_const_args(&self, err: &mut Diag<'_>) {
let num_missing_args = self.num_missing_type_or_const_args(); let num_missing_args = self.num_missing_type_or_const_args();
let msg = format!("add missing {} argument{}", self.kind(), pluralize!(num_missing_args)); let msg = format!("add missing {} argument{}", self.kind(), pluralize!(num_missing_args));
@ -738,7 +738,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
/// ```compile_fail /// ```compile_fail
/// Into::into::<Option<_>>(42) // suggests considering `Into::<Option<_>>::into(42)` /// Into::into::<Option<_>>(42) // suggests considering `Into::<Option<_>>::into(42)`
/// ``` /// ```
fn suggest_moving_args_from_assoc_fn_to_trait(&self, err: &mut DiagnosticBuilder<'_>) { fn suggest_moving_args_from_assoc_fn_to_trait(&self, err: &mut Diag<'_>) {
let trait_ = match self.tcx.trait_of_item(self.def_id) { let trait_ = match self.tcx.trait_of_item(self.def_id) {
Some(def_id) => def_id, Some(def_id) => def_id,
None => return, None => return,
@ -794,7 +794,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
fn suggest_moving_args_from_assoc_fn_to_trait_for_qualified_path( fn suggest_moving_args_from_assoc_fn_to_trait_for_qualified_path(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
qpath: &'tcx hir::QPath<'tcx>, qpath: &'tcx hir::QPath<'tcx>,
msg: String, msg: String,
num_assoc_fn_excess_args: usize, num_assoc_fn_excess_args: usize,
@ -827,7 +827,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
fn suggest_moving_args_from_assoc_fn_to_trait_for_method_call( fn suggest_moving_args_from_assoc_fn_to_trait_for_method_call(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
trait_def_id: DefId, trait_def_id: DefId,
expr: &'tcx hir::Expr<'tcx>, expr: &'tcx hir::Expr<'tcx>,
msg: String, msg: String,
@ -881,7 +881,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
/// ```text /// ```text
/// type Map = HashMap<String, String, String, String>; /// type Map = HashMap<String, String, String, String>;
/// ``` /// ```
fn suggest_removing_args_or_generics(&self, err: &mut DiagnosticBuilder<'_>) { fn suggest_removing_args_or_generics(&self, err: &mut Diag<'_>) {
let num_provided_lt_args = self.num_provided_lifetime_args(); let num_provided_lt_args = self.num_provided_lifetime_args();
let num_provided_type_const_args = self.num_provided_type_or_const_args(); let num_provided_type_const_args = self.num_provided_type_or_const_args();
let unbound_types = self.get_unbound_associated_types(); let unbound_types = self.get_unbound_associated_types();
@ -899,7 +899,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
let provided_args_matches_unbound_traits = let provided_args_matches_unbound_traits =
unbound_types.len() == num_redundant_type_or_const_args; unbound_types.len() == num_redundant_type_or_const_args;
let remove_lifetime_args = |err: &mut DiagnosticBuilder<'_>| { let remove_lifetime_args = |err: &mut Diag<'_>| {
let mut lt_arg_spans = Vec::new(); let mut lt_arg_spans = Vec::new();
let mut found_redundant = false; let mut found_redundant = false;
for arg in self.gen_args.args { for arg in self.gen_args.args {
@ -940,7 +940,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
); );
}; };
let remove_type_or_const_args = |err: &mut DiagnosticBuilder<'_>| { let remove_type_or_const_args = |err: &mut Diag<'_>| {
let mut gen_arg_spans = Vec::new(); let mut gen_arg_spans = Vec::new();
let mut found_redundant = false; let mut found_redundant = false;
for arg in self.gen_args.args { for arg in self.gen_args.args {
@ -1037,7 +1037,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
} }
/// Builds the `type defined here` message. /// Builds the `type defined here` message.
fn show_definition(&self, err: &mut DiagnosticBuilder<'_>) { fn show_definition(&self, err: &mut Diag<'_>) {
let mut spans: MultiSpan = if let Some(def_span) = self.tcx.def_ident_span(self.def_id) { let mut spans: MultiSpan = if let Some(def_span) = self.tcx.def_ident_span(self.def_id) {
if self.tcx.sess.source_map().is_span_accessible(def_span) { if self.tcx.sess.source_map().is_span_accessible(def_span) {
def_span.into() def_span.into()
@ -1088,7 +1088,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
} }
/// Add note if `impl Trait` is explicitly specified. /// Add note if `impl Trait` is explicitly specified.
fn note_synth_provided(&self, err: &mut DiagnosticBuilder<'_>) { fn note_synth_provided(&self, err: &mut Diag<'_>) {
if !self.is_synth_provided() { if !self.is_synth_provided() {
return; return;
} }
@ -1106,7 +1106,7 @@ impl<'tcx> StructuredDiagnostic<'tcx> for WrongNumberOfGenericArgs<'_, 'tcx> {
E0107 E0107
} }
fn diagnostic_common(&self) -> DiagnosticBuilder<'tcx> { fn diagnostic_common(&self) -> Diag<'tcx> {
let mut err = self.start_diagnostics(); let mut err = self.start_diagnostics();
self.notify(&mut err); self.notify(&mut err);

View file

@ -1,6 +1,6 @@
use crate::coercion::{AsCoercionSite, CoerceMany}; use crate::coercion::{AsCoercionSite, CoerceMany};
use crate::{Diverges, Expectation, FnCtxt, Needs}; use crate::{Diverges, Expectation, FnCtxt, Needs};
use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_errors::{Applicability, Diag};
use rustc_hir::{ use rustc_hir::{
self as hir, self as hir,
def::{CtorOf, DefKind, Res}, def::{CtorOf, DefKind, Res},
@ -177,7 +177,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn explain_never_type_coerced_to_unit( fn explain_never_type_coerced_to_unit(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
arm: &hir::Arm<'tcx>, arm: &hir::Arm<'tcx>,
arm_ty: Ty<'tcx>, arm_ty: Ty<'tcx>,
prior_arm: Option<(Option<hir::HirId>, Ty<'tcx>, Span)>, prior_arm: Option<(Option<hir::HirId>, Ty<'tcx>, Span)>,
@ -209,7 +209,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_removing_semicolon_for_coerce( fn suggest_removing_semicolon_for_coerce(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
expr: &hir::Expr<'tcx>, expr: &hir::Expr<'tcx>,
arm_ty: Ty<'tcx>, arm_ty: Ty<'tcx>,
prior_arm: Option<(Option<hir::HirId>, Ty<'tcx>, Span)>, prior_arm: Option<(Option<hir::HirId>, Ty<'tcx>, Span)>,
@ -303,7 +303,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// `if let PAT = EXPR {}` expressions that could be turned into `let PAT = EXPR;`. /// `if let PAT = EXPR {}` expressions that could be turned into `let PAT = EXPR;`.
fn explain_if_expr( fn explain_if_expr(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
ret_reason: Option<(Span, String)>, ret_reason: Option<(Span, String)>,
if_span: Span, if_span: Span,
cond_expr: &'tcx hir::Expr<'tcx>, cond_expr: &'tcx hir::Expr<'tcx>,

View file

@ -4,7 +4,7 @@ use super::{Expectation, FnCtxt, TupleArgumentsFlag};
use crate::errors; use crate::errors;
use rustc_ast::util::parser::PREC_POSTFIX; use rustc_ast::util::parser::PREC_POSTFIX;
use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, StashKey}; use rustc_errors::{Applicability, Diag, ErrorGuaranteed, StashKey};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{self, CtorKind, Namespace, Res}; use rustc_hir::def::{self, CtorKind, Namespace, Res};
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
@ -347,7 +347,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// likely intention is to call the closure, suggest `(||{})()`. (#55851) /// likely intention is to call the closure, suggest `(||{})()`. (#55851)
fn identify_bad_closure_def_and_call( fn identify_bad_closure_def_and_call(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
hir_id: hir::HirId, hir_id: hir::HirId,
callee_node: &hir::ExprKind<'_>, callee_node: &hir::ExprKind<'_>,
callee_span: Span, callee_span: Span,
@ -410,7 +410,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// likely intention is to create an array containing tuples. /// likely intention is to create an array containing tuples.
fn maybe_suggest_bad_array_definition( fn maybe_suggest_bad_array_definition(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
call_expr: &'tcx hir::Expr<'tcx>, call_expr: &'tcx hir::Expr<'tcx>,
callee_expr: &'tcx hir::Expr<'tcx>, callee_expr: &'tcx hir::Expr<'tcx>,
) -> bool { ) -> bool {
@ -601,7 +601,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// and suggesting the fix if the method probe is successful. /// and suggesting the fix if the method probe is successful.
fn suggest_call_as_method( fn suggest_call_as_method(
&self, &self,
diag: &mut DiagnosticBuilder<'_, ()>, diag: &mut Diag<'_, ()>,
segment: &'tcx hir::PathSegment<'tcx>, segment: &'tcx hir::PathSegment<'tcx>,
arg_exprs: &'tcx [hir::Expr<'tcx>], arg_exprs: &'tcx [hir::Expr<'tcx>],
call_expr: &'tcx hir::Expr<'tcx>, call_expr: &'tcx hir::Expr<'tcx>,

View file

@ -33,7 +33,7 @@ use super::FnCtxt;
use crate::errors; use crate::errors;
use crate::type_error_struct; use crate::type_error_struct;
use hir::ExprKind; use hir::ExprKind;
use rustc_errors::{codes::*, Applicability, DiagnosticBuilder, ErrorGuaranteed}; use rustc_errors::{codes::*, Applicability, Diag, ErrorGuaranteed};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_macros::{TypeFoldable, TypeVisitable}; use rustc_macros::{TypeFoldable, TypeVisitable};
use rustc_middle::mir::Mutability; use rustc_middle::mir::Mutability;
@ -182,7 +182,7 @@ fn make_invalid_casting_error<'a, 'tcx>(
expr_ty: Ty<'tcx>, expr_ty: Ty<'tcx>,
cast_ty: Ty<'tcx>, cast_ty: Ty<'tcx>,
fcx: &FnCtxt<'a, 'tcx>, fcx: &FnCtxt<'a, 'tcx>,
) -> DiagnosticBuilder<'a> { ) -> Diag<'a> {
type_error_struct!( type_error_struct!(
fcx.dcx(), fcx.dcx(),
span, span,
@ -980,11 +980,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
/// Attempt to suggest using `.is_empty` when trying to cast from a /// Attempt to suggest using `.is_empty` when trying to cast from a
/// collection type to a boolean. /// collection type to a boolean.
fn try_suggest_collection_to_bool( fn try_suggest_collection_to_bool(&self, fcx: &FnCtxt<'a, 'tcx>, err: &mut Diag<'_>) {
&self,
fcx: &FnCtxt<'a, 'tcx>,
err: &mut DiagnosticBuilder<'_>,
) {
if self.cast_ty.is_bool() { if self.cast_ty.is_bool() {
let derefed = fcx let derefed = fcx
.autoderef(self.expr_span, self.expr_ty) .autoderef(self.expr_span, self.expr_ty)

View file

@ -36,7 +36,7 @@
//! ``` //! ```
use crate::FnCtxt; use crate::FnCtxt;
use rustc_errors::{codes::*, struct_span_code_err, Applicability, DiagnosticBuilder, MultiSpan}; use rustc_errors::{codes::*, struct_span_code_err, Applicability, Diag, MultiSpan};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::intravisit::{self, Visitor};
@ -1437,7 +1437,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
&mut self, &mut self,
fcx: &FnCtxt<'a, 'tcx>, fcx: &FnCtxt<'a, 'tcx>,
cause: &ObligationCause<'tcx>, cause: &ObligationCause<'tcx>,
augment_error: impl FnOnce(&mut DiagnosticBuilder<'_>), augment_error: impl FnOnce(&mut Diag<'_>),
label_unit_as_expected: bool, label_unit_as_expected: bool,
) { ) {
self.coerce_inner( self.coerce_inner(
@ -1460,7 +1460,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
cause: &ObligationCause<'tcx>, cause: &ObligationCause<'tcx>,
expression: Option<&'tcx hir::Expr<'tcx>>, expression: Option<&'tcx hir::Expr<'tcx>>,
mut expression_ty: Ty<'tcx>, mut expression_ty: Ty<'tcx>,
augment_error: impl FnOnce(&mut DiagnosticBuilder<'_>), augment_error: impl FnOnce(&mut Diag<'_>),
label_expression_as_expected: bool, label_expression_as_expected: bool,
) { ) {
// Incorporate whatever type inference information we have // Incorporate whatever type inference information we have
@ -1671,7 +1671,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
fn note_unreachable_loop_return( fn note_unreachable_loop_return(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
expr: &hir::Expr<'tcx>, expr: &hir::Expr<'tcx>,
ret_exprs: &Vec<&'tcx hir::Expr<'tcx>>, ret_exprs: &Vec<&'tcx hir::Expr<'tcx>>,
@ -1783,7 +1783,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
id: hir::HirId, id: hir::HirId,
expression: Option<&'tcx hir::Expr<'tcx>>, expression: Option<&'tcx hir::Expr<'tcx>>,
blk_id: Option<hir::HirId>, blk_id: Option<hir::HirId>,
) -> DiagnosticBuilder<'a> { ) -> Diag<'a> {
let mut err = fcx.err_ctxt().report_mismatched_types(cause, expected, found, ty_err); let mut err = fcx.err_ctxt().report_mismatched_types(cause, expected, found, ty_err);
let parent_id = fcx.tcx.parent_hir_id(id); let parent_id = fcx.tcx.parent_hir_id(id);

View file

@ -1,6 +1,6 @@
use crate::FnCtxt; use crate::FnCtxt;
use rustc_errors::MultiSpan; use rustc_errors::MultiSpan;
use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_errors::{Applicability, Diag};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::Res; use rustc_hir::def::Res;
use rustc_hir::intravisit::Visitor; use rustc_hir::intravisit::Visitor;
@ -19,7 +19,7 @@ use super::method::probe;
impl<'a, 'tcx> FnCtxt<'a, 'tcx> { impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub fn emit_type_mismatch_suggestions( pub fn emit_type_mismatch_suggestions(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'tcx>, expr: &hir::Expr<'tcx>,
expr_ty: Ty<'tcx>, expr_ty: Ty<'tcx>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
@ -70,7 +70,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub fn emit_coerce_suggestions( pub fn emit_coerce_suggestions(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'tcx>, expr: &hir::Expr<'tcx>,
expr_ty: Ty<'tcx>, expr_ty: Ty<'tcx>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
@ -174,7 +174,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
sp: Span, sp: Span,
expected: Ty<'tcx>, expected: Ty<'tcx>,
actual: Ty<'tcx>, actual: Ty<'tcx>,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<Diag<'tcx>> {
self.demand_suptype_with_origin(&self.misc(sp), expected, actual) self.demand_suptype_with_origin(&self.misc(sp), expected, actual)
} }
@ -184,7 +184,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
cause: &ObligationCause<'tcx>, cause: &ObligationCause<'tcx>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
actual: Ty<'tcx>, actual: Ty<'tcx>,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<Diag<'tcx>> {
match self.at(cause, self.param_env).sup(DefineOpaqueTypes::Yes, expected, actual) { match self.at(cause, self.param_env).sup(DefineOpaqueTypes::Yes, expected, actual) {
Ok(InferOk { obligations, value: () }) => { Ok(InferOk { obligations, value: () }) => {
self.register_predicates(obligations); self.register_predicates(obligations);
@ -205,7 +205,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
sp: Span, sp: Span,
expected: Ty<'tcx>, expected: Ty<'tcx>,
actual: Ty<'tcx>, actual: Ty<'tcx>,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<Diag<'tcx>> {
self.demand_eqtype_with_origin(&self.misc(sp), expected, actual) self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
} }
@ -214,7 +214,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
cause: &ObligationCause<'tcx>, cause: &ObligationCause<'tcx>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
actual: Ty<'tcx>, actual: Ty<'tcx>,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<Diag<'tcx>> {
match self.at(cause, self.param_env).eq(DefineOpaqueTypes::Yes, expected, actual) { match self.at(cause, self.param_env).eq(DefineOpaqueTypes::Yes, expected, actual) {
Ok(InferOk { obligations, value: () }) => { Ok(InferOk { obligations, value: () }) => {
self.register_predicates(obligations); self.register_predicates(obligations);
@ -252,7 +252,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
expected: Ty<'tcx>, expected: Ty<'tcx>,
mut expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>, mut expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
allow_two_phase: AllowTwoPhase, allow_two_phase: AllowTwoPhase,
) -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx>>) { ) -> (Ty<'tcx>, Option<Diag<'tcx>>) {
let expected = self.resolve_vars_with_obligations(expected); let expected = self.resolve_vars_with_obligations(expected);
let e = match self.coerce(expr, checked_ty, expected, allow_two_phase, None) { let e = match self.coerce(expr, checked_ty, expected, allow_two_phase, None) {
@ -280,7 +280,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// with some expectation given by `source`. /// with some expectation given by `source`.
pub fn note_source_of_type_mismatch_constraint( pub fn note_source_of_type_mismatch_constraint(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
source: TypeMismatchSource<'tcx>, source: TypeMismatchSource<'tcx>,
) -> bool { ) -> bool {
@ -550,7 +550,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// expected type. // expected type.
pub fn annotate_loop_expected_due_to_inference( pub fn annotate_loop_expected_due_to_inference(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
error: Option<TypeError<'tcx>>, error: Option<TypeError<'tcx>>,
) { ) {
@ -673,7 +673,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn annotate_expected_due_to_let_ty( fn annotate_expected_due_to_let_ty(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
error: Option<TypeError<'tcx>>, error: Option<TypeError<'tcx>>,
) { ) {
@ -782,7 +782,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn annotate_alternative_method_deref( fn annotate_alternative_method_deref(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
error: Option<TypeError<'tcx>>, error: Option<TypeError<'tcx>>,
) { ) {
@ -1029,7 +1029,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn explain_self_literal( fn explain_self_literal(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'tcx>, expr: &hir::Expr<'tcx>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
found: Ty<'tcx>, found: Ty<'tcx>,
@ -1082,7 +1082,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn note_wrong_return_ty_due_to_generic_arg( fn note_wrong_return_ty_due_to_generic_arg(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
checked_ty: Ty<'tcx>, checked_ty: Ty<'tcx>,
) { ) {

View file

@ -3,8 +3,8 @@ use std::borrow::Cow;
use crate::fluent_generated as fluent; use crate::fluent_generated as fluent;
use rustc_errors::{ use rustc_errors::{
codes::*, AddToDiagnostic, Applicability, DiagnosticArgValue, DiagnosticBuilder, codes::*, AddToDiagnostic, Applicability, Diag, DiagnosticArgValue, EmissionGuarantee,
EmissionGuarantee, IntoDiagnosticArg, MultiSpan, SubdiagnosticMessageOp, IntoDiagnosticArg, MultiSpan, SubdiagnosticMessageOp,
}; };
use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
use rustc_middle::ty::Ty; use rustc_middle::ty::Ty;
@ -197,7 +197,7 @@ pub struct TypeMismatchFruTypo {
impl AddToDiagnostic for TypeMismatchFruTypo { impl AddToDiagnostic for TypeMismatchFruTypo {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
diag.arg("expr", self.expr.as_deref().unwrap_or("NONE")); diag.arg("expr", self.expr.as_deref().unwrap_or("NONE"));
@ -376,7 +376,7 @@ pub struct RemoveSemiForCoerce {
impl AddToDiagnostic for RemoveSemiForCoerce { impl AddToDiagnostic for RemoveSemiForCoerce {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
let mut multispan: MultiSpan = self.semi.into(); let mut multispan: MultiSpan = self.semi.into();
@ -552,7 +552,7 @@ pub enum CastUnknownPointerSub {
impl rustc_errors::AddToDiagnostic for CastUnknownPointerSub { impl rustc_errors::AddToDiagnostic for CastUnknownPointerSub {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
f: F, f: F,
) { ) {
match self { match self {

View file

@ -26,7 +26,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_data_structures::unord::UnordMap; use rustc_data_structures::unord::UnordMap;
use rustc_errors::{ use rustc_errors::{
codes::*, pluralize, struct_span_code_err, AddToDiagnostic, Applicability, DiagnosticBuilder, codes::*, pluralize, struct_span_code_err, AddToDiagnostic, Applicability, Diag,
ErrorGuaranteed, StashKey, ErrorGuaranteed, StashKey,
}; };
use rustc_hir as hir; use rustc_hir as hir;
@ -69,7 +69,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&self, &self,
expr: &'tcx hir::Expr<'tcx>, expr: &'tcx hir::Expr<'tcx>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
extend_err: impl FnOnce(&mut DiagnosticBuilder<'_>), extend_err: impl FnOnce(&mut Diag<'_>),
) -> Ty<'tcx> { ) -> Ty<'tcx> {
let mut ty = self.check_expr_with_expectation(expr, ExpectHasType(expected_ty)); let mut ty = self.check_expr_with_expectation(expr, ExpectHasType(expected_ty));
@ -954,7 +954,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
lhs: &'tcx hir::Expr<'tcx>, lhs: &'tcx hir::Expr<'tcx>,
code: ErrCode, code: ErrCode,
op_span: Span, op_span: Span,
adjust_err: impl FnOnce(&mut DiagnosticBuilder<'_>), adjust_err: impl FnOnce(&mut Diag<'_>),
) { ) {
if lhs.is_syntactic_place_expr() { if lhs.is_syntactic_place_expr() {
return; return;
@ -980,11 +980,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
/// Check if the expression that could not be assigned to was a typoed expression that /// Check if the expression that could not be assigned to was a typoed expression that
pub fn check_for_missing_semi( pub fn check_for_missing_semi(&self, expr: &'tcx hir::Expr<'tcx>, err: &mut Diag<'_>) -> bool {
&self,
expr: &'tcx hir::Expr<'tcx>,
err: &mut DiagnosticBuilder<'_>,
) -> bool {
if let hir::ExprKind::Binary(binop, lhs, rhs) = expr.kind if let hir::ExprKind::Binary(binop, lhs, rhs) = expr.kind
&& let hir::BinOpKind::Mul = binop.node && let hir::BinOpKind::Mul = binop.node
&& self.tcx.sess.source_map().is_multiline(lhs.span.between(rhs.span)) && self.tcx.sess.source_map().is_multiline(lhs.span.between(rhs.span))
@ -1219,7 +1215,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let lhs_ty = self.check_expr_with_needs(lhs, Needs::MutPlace); let lhs_ty = self.check_expr_with_needs(lhs, Needs::MutPlace);
let suggest_deref_binop = |err: &mut DiagnosticBuilder<'_>, rhs_ty: Ty<'tcx>| { let suggest_deref_binop = |err: &mut Diag<'_>, rhs_ty: Ty<'tcx>| {
if let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty) { if let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty) {
// Can only assign if the type is sized, so if `DerefMut` yields a type that is // Can only assign if the type is sized, so if `DerefMut` yields a type that is
// unsized, do not suggest dereferencing it. // unsized, do not suggest dereferencing it.
@ -2003,7 +1999,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
last_expr_field: &hir::ExprField<'tcx>, last_expr_field: &hir::ExprField<'tcx>,
variant: &ty::VariantDef, variant: &ty::VariantDef,
args: GenericArgsRef<'tcx>, args: GenericArgsRef<'tcx>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
) { ) {
// I don't use 'is_range_literal' because only double-sided, half-open ranges count. // I don't use 'is_range_literal' because only double-sided, half-open ranges count.
if let ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), [range_start, range_end], _) = if let ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), [range_start, range_end], _) =
@ -2519,7 +2515,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_await_on_field_access( fn suggest_await_on_field_access(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
field_ident: Ident, field_ident: Ident,
base: &'tcx hir::Expr<'tcx>, base: &'tcx hir::Expr<'tcx>,
ty: Ty<'tcx>, ty: Ty<'tcx>,
@ -2718,7 +2714,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.emit() err.emit()
} }
fn point_at_param_definition(&self, err: &mut DiagnosticBuilder<'_>, param: ty::ParamTy) { fn point_at_param_definition(&self, err: &mut Diag<'_>, param: ty::ParamTy) {
let generics = self.tcx.generics_of(self.body_id); let generics = self.tcx.generics_of(self.body_id);
let generic_param = generics.type_param(&param, self.tcx); let generic_param = generics.type_param(&param, self.tcx);
if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind { if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind {
@ -2737,7 +2733,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn maybe_suggest_array_indexing( fn maybe_suggest_array_indexing(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
base: &hir::Expr<'_>, base: &hir::Expr<'_>,
field: Ident, field: Ident,
@ -2761,7 +2757,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_first_deref_field( fn suggest_first_deref_field(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
base: &hir::Expr<'_>, base: &hir::Expr<'_>,
field: Ident, field: Ident,
@ -2774,12 +2770,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
} }
fn no_such_field_err( fn no_such_field_err(&self, field: Ident, expr_t: Ty<'tcx>, id: HirId) -> Diag<'_> {
&self,
field: Ident,
expr_t: Ty<'tcx>,
id: HirId,
) -> DiagnosticBuilder<'_> {
let span = field.span; let span = field.span;
debug!("no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})", span, field, expr_t); debug!("no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})", span, field, expr_t);
@ -2862,7 +2853,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err err
} }
fn private_field_err(&self, field: Ident, base_did: DefId) -> DiagnosticBuilder<'_> { fn private_field_err(&self, field: Ident, base_did: DefId) -> Diag<'_> {
let struct_path = self.tcx().def_path_str(base_did); let struct_path = self.tcx().def_path_str(base_did);
let kind_name = self.tcx().def_descr(base_did); let kind_name = self.tcx().def_descr(base_did);
struct_span_code_err!( struct_span_code_err!(

View file

@ -5,7 +5,7 @@ use crate::rvalue_scopes;
use crate::{BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy}; use crate::{BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy};
use rustc_data_structures::captures::Captures; use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, StashKey}; use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def::{CtorOf, DefKind, Res};
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
@ -1020,7 +1020,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(in super::super) fn note_internal_mutation_in_method( pub(in super::super) fn note_internal_mutation_in_method(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
expected: Option<Ty<'tcx>>, expected: Option<Ty<'tcx>>,
found: Ty<'tcx>, found: Ty<'tcx>,

View file

@ -17,7 +17,7 @@ use itertools::Itertools;
use rustc_ast as ast; use rustc_ast as ast;
use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::{ use rustc_errors::{
codes::*, pluralize, Applicability, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, StashKey, codes::*, pluralize, Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey,
}; };
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def::{CtorOf, DefKind, Res};
@ -561,7 +561,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
None None
}; };
let suggest_confusable = |err: &mut DiagnosticBuilder<'_>| { let suggest_confusable = |err: &mut Diag<'_>| {
let Some(call_name) = call_ident else { let Some(call_name) = call_ident else {
return; return;
}; };
@ -1369,7 +1369,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
provided_ty: Ty<'tcx>, provided_ty: Ty<'tcx>,
arg: &hir::Expr<'tcx>, arg: &hir::Expr<'tcx>,
err: &mut rustc_errors::DiagnosticBuilder<'tcx>, err: &mut Diag<'tcx>,
) { ) {
if let ty::RawPtr(ty::TypeAndMut { mutbl: hir::Mutability::Mut, .. }) = expected_ty.kind() if let ty::RawPtr(ty::TypeAndMut { mutbl: hir::Mutability::Mut, .. }) = expected_ty.kind()
&& let ty::RawPtr(ty::TypeAndMut { mutbl: hir::Mutability::Not, .. }) = && let ty::RawPtr(ty::TypeAndMut { mutbl: hir::Mutability::Not, .. }) =
@ -2047,7 +2047,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn label_fn_like( fn label_fn_like(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
callable_def_id: Option<DefId>, callable_def_id: Option<DefId>,
callee_ty: Option<Ty<'tcx>>, callee_ty: Option<Ty<'tcx>>,
call_expr: &'tcx hir::Expr<'tcx>, call_expr: &'tcx hir::Expr<'tcx>,

View file

@ -12,7 +12,7 @@ use core::cmp::min;
use core::iter; use core::iter;
use rustc_ast::util::parser::{ExprPrecedence, PREC_POSTFIX}; use rustc_ast::util::parser::{ExprPrecedence, PREC_POSTFIX};
use rustc_data_structures::packed::Pu128; use rustc_data_structures::packed::Pu128;
use rustc_errors::{Applicability, DiagnosticBuilder, MultiSpan}; use rustc_errors::{Applicability, Diag, MultiSpan};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::Res; use rustc_hir::def::Res;
use rustc_hir::def::{CtorKind, CtorOf, DefKind}; use rustc_hir::def::{CtorKind, CtorOf, DefKind};
@ -48,11 +48,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.copied() .copied()
} }
pub(in super::super) fn suggest_semicolon_at_end( pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diag<'_>) {
&self,
span: Span,
err: &mut DiagnosticBuilder<'_>,
) {
// This suggestion is incorrect for // This suggestion is incorrect for
// fn foo() -> bool { match () { () => true } || match () { () => true } } // fn foo() -> bool { match () { () => true } || match () { () => true } }
err.span_suggestion_short( err.span_suggestion_short(
@ -70,7 +66,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// - Possible missing return type if the return type is the default, and not `fn main()`. /// - Possible missing return type if the return type is the default, and not `fn main()`.
pub fn suggest_mismatched_types_on_tail( pub fn suggest_mismatched_types_on_tail(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &'tcx hir::Expr<'tcx>, expr: &'tcx hir::Expr<'tcx>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
found: Ty<'tcx>, found: Ty<'tcx>,
@ -101,7 +97,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// ``` /// ```
pub(crate) fn suggest_fn_call( pub(crate) fn suggest_fn_call(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
found: Ty<'tcx>, found: Ty<'tcx>,
can_satisfy: impl FnOnce(Ty<'tcx>) -> bool, can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
@ -183,7 +179,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub fn suggest_two_fn_call( pub fn suggest_two_fn_call(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
lhs_expr: &'tcx hir::Expr<'tcx>, lhs_expr: &'tcx hir::Expr<'tcx>,
lhs_ty: Ty<'tcx>, lhs_ty: Ty<'tcx>,
rhs_expr: &'tcx hir::Expr<'tcx>, rhs_expr: &'tcx hir::Expr<'tcx>,
@ -257,7 +253,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub fn suggest_remove_last_method_call( pub fn suggest_remove_last_method_call(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'tcx>, expr: &hir::Expr<'tcx>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
) -> bool { ) -> bool {
@ -286,7 +282,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub fn suggest_deref_ref_or_into( pub fn suggest_deref_ref_or_into(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'tcx>, expr: &hir::Expr<'tcx>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
found: Ty<'tcx>, found: Ty<'tcx>,
@ -544,7 +540,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// in the heap by calling `Box::new()`. /// in the heap by calling `Box::new()`.
pub(in super::super) fn suggest_boxing_when_appropriate( pub(in super::super) fn suggest_boxing_when_appropriate(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
span: Span, span: Span,
hir_id: HirId, hir_id: HirId,
expected: Ty<'tcx>, expected: Ty<'tcx>,
@ -587,7 +583,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// suggest a non-capturing closure /// suggest a non-capturing closure
pub(in super::super) fn suggest_no_capture_closure( pub(in super::super) fn suggest_no_capture_closure(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
found: Ty<'tcx>, found: Ty<'tcx>,
) -> bool { ) -> bool {
@ -624,7 +620,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
#[instrument(skip(self, err))] #[instrument(skip(self, err))]
pub(in super::super) fn suggest_calling_boxed_future_when_appropriate( pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
found: Ty<'tcx>, found: Ty<'tcx>,
@ -736,7 +732,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`. /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
pub fn suggest_missing_semicolon( pub fn suggest_missing_semicolon(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expression: &'tcx hir::Expr<'tcx>, expression: &'tcx hir::Expr<'tcx>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
needs_block: bool, needs_block: bool,
@ -795,7 +791,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
#[instrument(level = "trace", skip(self, err))] #[instrument(level = "trace", skip(self, err))]
pub(in super::super) fn suggest_missing_return_type( pub(in super::super) fn suggest_missing_return_type(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
fn_decl: &hir::FnDecl<'tcx>, fn_decl: &hir::FnDecl<'tcx>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
found: Ty<'tcx>, found: Ty<'tcx>,
@ -913,7 +909,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// ``` /// ```
fn try_suggest_return_impl_trait( fn try_suggest_return_impl_trait(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
found: Ty<'tcx>, found: Ty<'tcx>,
fn_id: hir::HirId, fn_id: hir::HirId,
@ -1018,7 +1014,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(in super::super) fn suggest_missing_break_or_return_expr( pub(in super::super) fn suggest_missing_break_or_return_expr(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &'tcx hir::Expr<'tcx>, expr: &'tcx hir::Expr<'tcx>,
fn_decl: &hir::FnDecl<'tcx>, fn_decl: &hir::FnDecl<'tcx>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
@ -1117,7 +1113,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(in super::super) fn suggest_missing_parentheses( pub(in super::super) fn suggest_missing_parentheses(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
) -> bool { ) -> bool {
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);
@ -1135,7 +1131,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// if it was possibly mistaken array syntax. /// if it was possibly mistaken array syntax.
pub(crate) fn suggest_block_to_brackets_peeling_refs( pub(crate) fn suggest_block_to_brackets_peeling_refs(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
mut expr: &hir::Expr<'_>, mut expr: &hir::Expr<'_>,
mut expr_ty: Ty<'tcx>, mut expr_ty: Ty<'tcx>,
mut expected_ty: Ty<'tcx>, mut expected_ty: Ty<'tcx>,
@ -1162,7 +1158,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_clone_for_ref( pub(crate) fn suggest_clone_for_ref(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
expr_ty: Ty<'tcx>, expr_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
@ -1197,7 +1193,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_copied_cloned_or_as_ref( pub(crate) fn suggest_copied_cloned_or_as_ref(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
expr_ty: Ty<'tcx>, expr_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
@ -1247,7 +1243,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_into( pub(crate) fn suggest_into(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
expr_ty: Ty<'tcx>, expr_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
@ -1310,7 +1306,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()` /// When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()`
pub(crate) fn suggest_option_to_bool( pub(crate) fn suggest_option_to_bool(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
expr_ty: Ty<'tcx>, expr_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
@ -1367,7 +1363,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`. /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
pub(crate) fn suggest_block_to_brackets( pub(crate) fn suggest_block_to_brackets(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
blk: &hir::Block<'_>, blk: &hir::Block<'_>,
blk_ty: Ty<'tcx>, blk_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
@ -1407,7 +1403,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
#[instrument(skip(self, err))] #[instrument(skip(self, err))]
pub(crate) fn suggest_floating_point_literal( pub(crate) fn suggest_floating_point_literal(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
) -> bool { ) -> bool {
@ -1478,7 +1474,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
#[instrument(skip(self, err))] #[instrument(skip(self, err))]
pub(crate) fn suggest_null_ptr_for_literal_zero_given_to_ptr_arg( pub(crate) fn suggest_null_ptr_for_literal_zero_given_to_ptr_arg(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
) -> bool { ) -> bool {
@ -1516,7 +1512,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_associated_const( pub(crate) fn suggest_associated_const(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'tcx>, expr: &hir::Expr<'tcx>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
) -> bool { ) -> bool {
@ -1610,7 +1606,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// which is a side-effect of autoref. /// which is a side-effect of autoref.
pub(crate) fn note_type_is_not_clone( pub(crate) fn note_type_is_not_clone(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
found_ty: Ty<'tcx>, found_ty: Ty<'tcx>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
@ -1810,7 +1806,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&self, &self,
blk: &'tcx hir::Block<'tcx>, blk: &'tcx hir::Block<'tcx>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
) -> bool { ) -> bool {
if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) { if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) {
if let StatementAsExpression::NeedsBoxing = boxed { if let StatementAsExpression::NeedsBoxing = boxed {
@ -1855,7 +1851,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_missing_unwrap_expect( pub(crate) fn suggest_missing_unwrap_expect(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'tcx>, expr: &hir::Expr<'tcx>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
found: Ty<'tcx>, found: Ty<'tcx>,
@ -1938,7 +1934,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_coercing_result_via_try_operator( pub(crate) fn suggest_coercing_result_via_try_operator(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'tcx>, expr: &hir::Expr<'tcx>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
found: Ty<'tcx>, found: Ty<'tcx>,
@ -1985,7 +1981,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// sole field is of the found type, suggest such variants. (Issue #42764) /// sole field is of the found type, suggest such variants. (Issue #42764)
pub(crate) fn suggest_compatible_variants( pub(crate) fn suggest_compatible_variants(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
expr_ty: Ty<'tcx>, expr_ty: Ty<'tcx>,
@ -2174,7 +2170,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_non_zero_new_unwrap( pub(crate) fn suggest_non_zero_new_unwrap(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
expr_ty: Ty<'tcx>, expr_ty: Ty<'tcx>,
@ -2718,7 +2714,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_cast( pub(crate) fn suggest_cast(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
checked_ty: Ty<'tcx>, checked_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
@ -2846,7 +2842,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let in_const_context = self.tcx.hir().is_inside_const_context(expr.hir_id); let in_const_context = self.tcx.hir().is_inside_const_context(expr.hir_id);
let suggest_fallible_into_or_lhs_from = let suggest_fallible_into_or_lhs_from =
|err: &mut DiagnosticBuilder<'_>, exp_to_found_is_fallible: bool| { |err: &mut Diag<'_>, exp_to_found_is_fallible: bool| {
// If we know the expression the expected type is derived from, we might be able // If we know the expression the expected type is derived from, we might be able
// to suggest a widening conversion rather than a narrowing one (which may // to suggest a widening conversion rather than a narrowing one (which may
// panic). For example, given x: u8 and y: u32, if we know the span of "x", // panic). For example, given x: u8 and y: u32, if we know the span of "x",
@ -2886,9 +2882,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}; };
let suggest_to_change_suffix_or_into = let suggest_to_change_suffix_or_into =
|err: &mut DiagnosticBuilder<'_>, |err: &mut Diag<'_>, found_to_exp_is_fallible: bool, exp_to_found_is_fallible: bool| {
found_to_exp_is_fallible: bool,
exp_to_found_is_fallible: bool| {
let exp_is_lhs = expected_ty_expr.is_some_and(|e| self.tcx.hir().is_lhs(e.hir_id)); let exp_is_lhs = expected_ty_expr.is_some_and(|e| self.tcx.hir().is_lhs(e.hir_id));
if exp_is_lhs { if exp_is_lhs {
@ -3084,7 +3078,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// Identify when the user has written `foo..bar()` instead of `foo.bar()`. /// Identify when the user has written `foo..bar()` instead of `foo.bar()`.
pub(crate) fn suggest_method_call_on_range_literal( pub(crate) fn suggest_method_call_on_range_literal(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'tcx>, expr: &hir::Expr<'tcx>,
checked_ty: Ty<'tcx>, checked_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
@ -3162,7 +3156,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// block without a tail expression. /// block without a tail expression.
pub(crate) fn suggest_return_binding_for_missing_tail_expr( pub(crate) fn suggest_return_binding_for_missing_tail_expr(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
checked_ty: Ty<'tcx>, checked_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,

View file

@ -11,7 +11,7 @@ pub use self::suggest::SelfSource;
pub use self::MethodError::*; pub use self::MethodError::*;
use crate::FnCtxt; use crate::FnCtxt;
use rustc_errors::{Applicability, DiagnosticBuilder, SubdiagnosticMessage}; use rustc_errors::{Applicability, Diag, SubdiagnosticMessage};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{CtorOf, DefKind, Namespace}; use rustc_hir::def::{CtorOf, DefKind, Namespace};
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
@ -126,7 +126,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
#[instrument(level = "debug", skip(self, err, call_expr))] #[instrument(level = "debug", skip(self, err, call_expr))]
pub(crate) fn suggest_method_call( pub(crate) fn suggest_method_call(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
msg: impl Into<SubdiagnosticMessage> + std::fmt::Debug, msg: impl Into<SubdiagnosticMessage> + std::fmt::Debug,
method_name: Ident, method_name: Ident,
self_ty: Ty<'tcx>, self_ty: Ty<'tcx>,

View file

@ -12,8 +12,7 @@ use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::sorted_map::SortedMap;
use rustc_data_structures::unord::UnordSet; use rustc_data_structures::unord::UnordSet;
use rustc_errors::{ use rustc_errors::{
codes::*, pluralize, struct_span_code_err, Applicability, DiagnosticBuilder, MultiSpan, codes::*, pluralize, struct_span_code_err, Applicability, Diag, MultiSpan, StashKey,
StashKey,
}; };
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::DefKind; use rustc_hir::def::DefKind;
@ -208,7 +207,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
args: Option<&'tcx [hir::Expr<'tcx>]>, args: Option<&'tcx [hir::Expr<'tcx>]>,
expected: Expectation<'tcx>, expected: Expectation<'tcx>,
trait_missing_method: bool, trait_missing_method: bool,
) -> Option<DiagnosticBuilder<'_>> { ) -> Option<Diag<'_>> {
// Avoid suggestions when we don't know what's going on. // Avoid suggestions when we don't know what's going on.
if rcvr_ty.references_error() { if rcvr_ty.references_error() {
return None; return None;
@ -344,11 +343,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
None None
} }
fn suggest_missing_writer( fn suggest_missing_writer(&self, rcvr_ty: Ty<'tcx>, rcvr_expr: &hir::Expr<'tcx>) -> Diag<'_> {
&self,
rcvr_ty: Ty<'tcx>,
rcvr_expr: &hir::Expr<'tcx>,
) -> DiagnosticBuilder<'_> {
let mut file = None; let mut file = None;
let ty_str = self.tcx.short_ty_string(rcvr_ty, &mut file); let ty_str = self.tcx.short_ty_string(rcvr_ty, &mut file);
let mut err = struct_span_code_err!( let mut err = struct_span_code_err!(
@ -387,7 +382,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
no_match_data: &mut NoMatchData<'tcx>, no_match_data: &mut NoMatchData<'tcx>,
expected: Expectation<'tcx>, expected: Expectation<'tcx>,
trait_missing_method: bool, trait_missing_method: bool,
) -> Option<DiagnosticBuilder<'_>> { ) -> Option<Diag<'_>> {
let mode = no_match_data.mode; let mode = no_match_data.mode;
let tcx = self.tcx; let tcx = self.tcx;
let rcvr_ty = self.resolve_vars_if_possible(rcvr_ty); let rcvr_ty = self.resolve_vars_if_possible(rcvr_ty);
@ -1130,7 +1125,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
} }
let label_span_not_found = |err: &mut DiagnosticBuilder<'_>| { let label_span_not_found = |err: &mut Diag<'_>| {
if unsatisfied_predicates.is_empty() { if unsatisfied_predicates.is_empty() {
err.span_label(span, format!("{item_kind} not found in `{ty_str}`")); err.span_label(span, format!("{item_kind} not found in `{ty_str}`"));
let is_string_or_ref_str = match rcvr_ty.kind() { let is_string_or_ref_str = match rcvr_ty.kind() {
@ -1414,7 +1409,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn find_likely_intended_associated_item( fn find_likely_intended_associated_item(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
similar_candidate: ty::AssocItem, similar_candidate: ty::AssocItem,
span: Span, span: Span,
args: Option<&'tcx [hir::Expr<'tcx>]>, args: Option<&'tcx [hir::Expr<'tcx>]>,
@ -1492,7 +1487,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn confusable_method_name( pub(crate) fn confusable_method_name(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
rcvr_ty: Ty<'tcx>, rcvr_ty: Ty<'tcx>,
item_name: Ident, item_name: Ident,
call_args: Option<Vec<Ty<'tcx>>>, call_args: Option<Vec<Ty<'tcx>>>,
@ -1559,7 +1554,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self_source: SelfSource<'tcx>, self_source: SelfSource<'tcx>,
args: Option<&'tcx [hir::Expr<'tcx>]>, args: Option<&'tcx [hir::Expr<'tcx>]>,
span: Span, span: Span,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
sources: &mut Vec<CandidateSource>, sources: &mut Vec<CandidateSource>,
sugg_span: Option<Span>, sugg_span: Option<Span>,
) { ) {
@ -1705,7 +1700,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// Look at all the associated functions without receivers in the type's inherent impls /// Look at all the associated functions without receivers in the type's inherent impls
/// to look for builders that return `Self`, `Option<Self>` or `Result<Self, _>`. /// to look for builders that return `Self`, `Option<Self>` or `Result<Self, _>`.
fn find_builder_fn(&self, err: &mut DiagnosticBuilder<'_>, rcvr_ty: Ty<'tcx>) { fn find_builder_fn(&self, err: &mut Diag<'_>, rcvr_ty: Ty<'tcx>) {
let ty::Adt(adt_def, _) = rcvr_ty.kind() else { let ty::Adt(adt_def, _) = rcvr_ty.kind() else {
return; return;
}; };
@ -1790,7 +1785,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// doesn't take a `self` receiver. /// doesn't take a `self` receiver.
fn suggest_associated_call_syntax( fn suggest_associated_call_syntax(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
static_candidates: &Vec<CandidateSource>, static_candidates: &Vec<CandidateSource>,
rcvr_ty: Ty<'tcx>, rcvr_ty: Ty<'tcx>,
source: SelfSource<'tcx>, source: SelfSource<'tcx>,
@ -1934,7 +1929,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
rcvr_ty: Ty<'tcx>, rcvr_ty: Ty<'tcx>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
item_name: Ident, item_name: Ident,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
) -> bool { ) -> bool {
let tcx = self.tcx; let tcx = self.tcx;
let field_receiver = self.autoderef(span, rcvr_ty).find_map(|(ty, _)| match ty.kind() { let field_receiver = self.autoderef(span, rcvr_ty).find_map(|(ty, _)| match ty.kind() {
@ -2257,7 +2252,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// Suggest calling a method on a field i.e. `a.field.bar()` instead of `a.bar()` /// Suggest calling a method on a field i.e. `a.field.bar()` instead of `a.bar()`
fn suggest_calling_method_on_field( fn suggest_calling_method_on_field(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
source: SelfSource<'tcx>, source: SelfSource<'tcx>,
span: Span, span: Span,
actual: Ty<'tcx>, actual: Ty<'tcx>,
@ -2337,7 +2332,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_unwrapping_inner_self( fn suggest_unwrapping_inner_self(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
source: SelfSource<'tcx>, source: SelfSource<'tcx>,
actual: Ty<'tcx>, actual: Ty<'tcx>,
item_name: Ident, item_name: Ident,
@ -2526,7 +2521,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn note_unmet_impls_on_type( pub(crate) fn note_unmet_impls_on_type(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
errors: Vec<FulfillmentError<'tcx>>, errors: Vec<FulfillmentError<'tcx>>,
suggest_derive: bool, suggest_derive: bool,
) { ) {
@ -2609,7 +2604,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn note_predicate_source_and_get_derives( fn note_predicate_source_and_get_derives(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
unsatisfied_predicates: &[( unsatisfied_predicates: &[(
ty::Predicate<'tcx>, ty::Predicate<'tcx>,
Option<ty::Predicate<'tcx>>, Option<ty::Predicate<'tcx>>,
@ -2691,7 +2686,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_derive( pub(crate) fn suggest_derive(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
unsatisfied_predicates: &[( unsatisfied_predicates: &[(
ty::Predicate<'tcx>, ty::Predicate<'tcx>,
Option<ty::Predicate<'tcx>>, Option<ty::Predicate<'tcx>>,
@ -2727,7 +2722,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn note_derefed_ty_has_method( fn note_derefed_ty_has_method(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
self_source: SelfSource<'tcx>, self_source: SelfSource<'tcx>,
rcvr_ty: Ty<'tcx>, rcvr_ty: Ty<'tcx>,
item_name: Ident, item_name: Ident,
@ -2807,7 +2802,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_await_before_method( fn suggest_await_before_method(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
item_name: Ident, item_name: Ident,
ty: Ty<'tcx>, ty: Ty<'tcx>,
call: &hir::Expr<'_>, call: &hir::Expr<'_>,
@ -2830,12 +2825,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
} }
fn suggest_use_candidates( fn suggest_use_candidates(&self, err: &mut Diag<'_>, msg: String, candidates: Vec<DefId>) {
&self,
err: &mut DiagnosticBuilder<'_>,
msg: String,
candidates: Vec<DefId>,
) {
let parent_map = self.tcx.visible_parent_map(()); let parent_map = self.tcx.visible_parent_map(());
// Separate out candidates that must be imported with a glob, because they are named `_` // Separate out candidates that must be imported with a glob, because they are named `_`
@ -2882,7 +2872,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_valid_traits( fn suggest_valid_traits(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
item_name: Ident, item_name: Ident,
valid_out_of_scope_traits: Vec<DefId>, valid_out_of_scope_traits: Vec<DefId>,
explain: bool, explain: bool,
@ -2931,7 +2921,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_traits_to_import( fn suggest_traits_to_import(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
span: Span, span: Span,
rcvr_ty: Ty<'tcx>, rcvr_ty: Ty<'tcx>,
item_name: Ident, item_name: Ident,
@ -3475,7 +3465,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// FIXME: currently not working for suggesting `map_or_else`, see #102408 /// FIXME: currently not working for suggesting `map_or_else`, see #102408
pub(crate) fn suggest_else_fn_with_closure( pub(crate) fn suggest_else_fn_with_closure(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
found: Ty<'tcx>, found: Ty<'tcx>,
expected: Ty<'tcx>, expected: Ty<'tcx>,
@ -3601,7 +3591,7 @@ pub fn all_traits(tcx: TyCtxt<'_>) -> Vec<TraitInfo> {
fn print_disambiguation_help<'tcx>( fn print_disambiguation_help<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
source: SelfSource<'tcx>, source: SelfSource<'tcx>,
args: Option<&'tcx [hir::Expr<'tcx>]>, args: Option<&'tcx [hir::Expr<'tcx>]>,
trait_ref: ty::TraitRef<'tcx>, trait_ref: ty::TraitRef<'tcx>,

View file

@ -5,7 +5,7 @@ use super::FnCtxt;
use crate::Expectation; use crate::Expectation;
use rustc_ast as ast; use rustc_ast as ast;
use rustc_data_structures::packed::Pu128; use rustc_data_structures::packed::Pu128;
use rustc_errors::{codes::*, struct_span_code_err, Applicability, DiagnosticBuilder}; use rustc_errors::{codes::*, struct_span_code_err, Applicability, Diag};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use rustc_infer::traits::ObligationCauseCode; use rustc_infer::traits::ObligationCauseCode;
@ -390,8 +390,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.downgrade_to_delayed_bug(); err.downgrade_to_delayed_bug();
} }
let suggest_deref_binop = let suggest_deref_binop = |err: &mut Diag<'_, _>, lhs_deref_ty: Ty<'tcx>| {
|err: &mut DiagnosticBuilder<'_, _>, lhs_deref_ty: Ty<'tcx>| {
if self if self
.lookup_op_method( .lookup_op_method(
(lhs_expr, lhs_deref_ty), (lhs_expr, lhs_deref_ty),
@ -420,7 +419,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}; };
let suggest_different_borrow = let suggest_different_borrow =
|err: &mut DiagnosticBuilder<'_, _>, |err: &mut Diag<'_, _>,
lhs_adjusted_ty, lhs_adjusted_ty,
lhs_new_mutbl: Option<ast::Mutability>, lhs_new_mutbl: Option<ast::Mutability>,
rhs_adjusted_ty, rhs_adjusted_ty,
@ -695,7 +694,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
rhs_expr: &'tcx hir::Expr<'tcx>, rhs_expr: &'tcx hir::Expr<'tcx>,
lhs_ty: Ty<'tcx>, lhs_ty: Ty<'tcx>,
rhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
is_assign: IsAssign, is_assign: IsAssign,
op: hir::BinOp, op: hir::BinOp,
) -> bool { ) -> bool {

View file

@ -3,8 +3,7 @@ use crate::{errors, FnCtxt, LoweredTy};
use rustc_ast as ast; use rustc_ast as ast;
use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::fx::FxHashMap;
use rustc_errors::{ use rustc_errors::{
codes::*, pluralize, struct_span_code_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, codes::*, pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan,
MultiSpan,
}; };
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def::{CtorKind, DefKind, Res};
@ -99,7 +98,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
expected: Ty<'tcx>, expected: Ty<'tcx>,
actual: Ty<'tcx>, actual: Ty<'tcx>,
ti: TopInfo<'tcx>, ti: TopInfo<'tcx>,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<Diag<'tcx>> {
let mut diag = let mut diag =
self.demand_eqtype_with_origin(&self.pattern_cause(ti, cause_span), expected, actual)?; self.demand_eqtype_with_origin(&self.pattern_cause(ti, cause_span), expected, actual)?;
if let Some(expr) = ti.origin_expr { if let Some(expr) = ti.origin_expr {
@ -529,7 +528,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
ty ty
} }
fn endpoint_has_type(&self, err: &mut DiagnosticBuilder<'_>, span: Span, ty: Ty<'_>) { fn endpoint_has_type(&self, err: &mut Diag<'_>, span: Span, ty: Ty<'_>) {
if !ty.references_error() { if !ty.references_error() {
err.span_label(span, format!("this is of type `{ty}`")); err.span_label(span, format!("this is of type `{ty}`"));
} }
@ -683,7 +682,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_adding_missing_ref_or_removing_ref( fn suggest_adding_missing_ref_or_removing_ref(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
span: Span, span: Span,
expected: Ty<'tcx>, expected: Ty<'tcx>,
actual: Ty<'tcx>, actual: Ty<'tcx>,
@ -715,7 +714,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
// Precondition: pat is a Ref(_) pattern // Precondition: pat is a Ref(_) pattern
fn borrow_pat_suggestion(&self, err: &mut DiagnosticBuilder<'_>, pat: &Pat<'_>) { fn borrow_pat_suggestion(&self, err: &mut Diag<'_>, pat: &Pat<'_>) {
let tcx = self.tcx; let tcx = self.tcx;
if let PatKind::Ref(inner, mutbl) = pat.kind if let PatKind::Ref(inner, mutbl) = pat.kind
&& let PatKind::Binding(_, _, binding, ..) = inner.kind && let PatKind::Binding(_, _, binding, ..) = inner.kind
@ -933,7 +932,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn maybe_suggest_range_literal( fn maybe_suggest_range_literal(
&self, &self,
e: &mut DiagnosticBuilder<'_>, e: &mut Diag<'_>,
opt_def_id: Option<hir::def_id::DefId>, opt_def_id: Option<hir::def_id::DefId>,
ident: Ident, ident: Ident,
) -> bool { ) -> bool {
@ -968,7 +967,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn emit_bad_pat_path( fn emit_bad_pat_path(
&self, &self,
mut e: DiagnosticBuilder<'_>, mut e: Diag<'_>,
pat: &hir::Pat<'tcx>, pat: &hir::Pat<'tcx>,
res: Res, res: Res,
pat_res: Res, pat_res: Res,
@ -1505,7 +1504,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
variant: &VariantDef, variant: &VariantDef,
pat: &'_ Pat<'_>, pat: &'_ Pat<'_>,
fields: &[hir::PatField<'_>], fields: &[hir::PatField<'_>],
) -> Option<DiagnosticBuilder<'_>> { ) -> Option<Diag<'_>> {
// if this is a tuple struct, then all field names will be numbers // if this is a tuple struct, then all field names will be numbers
// so if any fields in a struct pattern use shorthand syntax, they will // so if any fields in a struct pattern use shorthand syntax, they will
// be invalid identifiers (for example, Foo { 0, 1 }). // be invalid identifiers (for example, Foo { 0, 1 }).
@ -1581,7 +1580,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pat: &'tcx Pat<'tcx>, pat: &'tcx Pat<'tcx>,
variant: &ty::VariantDef, variant: &ty::VariantDef,
args: &'tcx ty::List<ty::GenericArg<'tcx>>, args: &'tcx ty::List<ty::GenericArg<'tcx>>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let tcx = self.tcx; let tcx = self.tcx;
let (field_names, t, plural) = if let [field] = inexistent_fields { let (field_names, t, plural) = if let [field] = inexistent_fields {
(format!("a field named `{}`", field.ident), "this", "") (format!("a field named `{}`", field.ident), "this", "")
@ -1686,7 +1685,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pat: &Pat<'_>, pat: &Pat<'_>,
fields: &'tcx [hir::PatField<'tcx>], fields: &'tcx [hir::PatField<'tcx>],
variant: &ty::VariantDef, variant: &ty::VariantDef,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<Diag<'tcx>> {
if let (Some(CtorKind::Fn), PatKind::Struct(qpath, pattern_fields, ..)) = if let (Some(CtorKind::Fn), PatKind::Struct(qpath, pattern_fields, ..)) =
(variant.ctor_kind(), &pat.kind) (variant.ctor_kind(), &pat.kind)
{ {
@ -1772,7 +1771,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&self, &self,
pat: &Pat<'_>, pat: &Pat<'_>,
fields: &'tcx [hir::PatField<'tcx>], fields: &'tcx [hir::PatField<'tcx>],
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let mut err = self let mut err = self
.dcx() .dcx()
.struct_span_err(pat.span, "pattern requires `..` due to inaccessible fields"); .struct_span_err(pat.span, "pattern requires `..` due to inaccessible fields");
@ -1863,7 +1862,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
unmentioned_fields: &[(&ty::FieldDef, Ident)], unmentioned_fields: &[(&ty::FieldDef, Ident)],
have_inaccessible_fields: bool, have_inaccessible_fields: bool,
fields: &'tcx [hir::PatField<'tcx>], fields: &'tcx [hir::PatField<'tcx>],
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let inaccessible = if have_inaccessible_fields { " and inaccessible fields" } else { "" }; let inaccessible = if have_inaccessible_fields { " and inaccessible fields" } else { "" };
let field_names = if let [(_, field)] = unmentioned_fields { let field_names = if let [(_, field)] = unmentioned_fields {
format!("field `{field}`{inaccessible}") format!("field `{field}`{inaccessible}")

View file

@ -1,8 +1,7 @@
use hir::GenericParamKind; use hir::GenericParamKind;
use rustc_errors::{ use rustc_errors::{
codes::*, AddToDiagnostic, Applicability, DiagnosticBuilder, DiagnosticMessage, codes::*, AddToDiagnostic, Applicability, Diag, DiagnosticMessage, DiagnosticStyledString,
DiagnosticStyledString, EmissionGuarantee, IntoDiagnosticArg, MultiSpan, EmissionGuarantee, IntoDiagnosticArg, MultiSpan, SubdiagnosticMessageOp,
SubdiagnosticMessageOp,
}; };
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::FnRetTy; use rustc_hir::FnRetTy;
@ -228,7 +227,7 @@ pub enum RegionOriginNote<'a> {
impl AddToDiagnostic for RegionOriginNote<'_> { impl AddToDiagnostic for RegionOriginNote<'_> {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
let mut label_or_note = |span, msg: DiagnosticMessage| { let mut label_or_note = |span, msg: DiagnosticMessage| {
@ -293,7 +292,7 @@ pub enum LifetimeMismatchLabels {
impl AddToDiagnostic for LifetimeMismatchLabels { impl AddToDiagnostic for LifetimeMismatchLabels {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
match self { match self {
@ -341,7 +340,7 @@ pub struct AddLifetimeParamsSuggestion<'a> {
impl AddToDiagnostic for AddLifetimeParamsSuggestion<'_> { impl AddToDiagnostic for AddLifetimeParamsSuggestion<'_> {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
let mut mk_suggestion = || { let mut mk_suggestion = || {
@ -443,7 +442,7 @@ pub struct IntroducesStaticBecauseUnmetLifetimeReq {
impl AddToDiagnostic for IntroducesStaticBecauseUnmetLifetimeReq { impl AddToDiagnostic for IntroducesStaticBecauseUnmetLifetimeReq {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
mut self, mut self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
self.unmet_requirements self.unmet_requirements
@ -762,7 +761,7 @@ pub struct ConsiderBorrowingParamHelp {
impl AddToDiagnostic for ConsiderBorrowingParamHelp { impl AddToDiagnostic for ConsiderBorrowingParamHelp {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
f: F, f: F,
) { ) {
let mut type_param_span: MultiSpan = self.spans.clone().into(); let mut type_param_span: MultiSpan = self.spans.clone().into();
@ -807,7 +806,7 @@ pub struct DynTraitConstraintSuggestion {
impl AddToDiagnostic for DynTraitConstraintSuggestion { impl AddToDiagnostic for DynTraitConstraintSuggestion {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
f: F, f: F,
) { ) {
let mut multi_span: MultiSpan = vec![self.span].into(); let mut multi_span: MultiSpan = vec![self.span].into();
@ -854,7 +853,7 @@ pub struct ReqIntroducedLocations {
impl AddToDiagnostic for ReqIntroducedLocations { impl AddToDiagnostic for ReqIntroducedLocations {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
mut self, mut self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
f: F, f: F,
) { ) {
for sp in self.spans { for sp in self.spans {
@ -877,7 +876,7 @@ pub struct MoreTargeted {
impl AddToDiagnostic for MoreTargeted { impl AddToDiagnostic for MoreTargeted {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
diag.code(E0772); diag.code(E0772);
@ -1300,7 +1299,7 @@ pub struct SuggestTuplePatternMany {
impl AddToDiagnostic for SuggestTuplePatternMany { impl AddToDiagnostic for SuggestTuplePatternMany {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
f: F, f: F,
) { ) {
diag.arg("path", self.path); diag.arg("path", self.path);

View file

@ -1,8 +1,7 @@
use crate::fluent_generated as fluent; use crate::fluent_generated as fluent;
use crate::infer::error_reporting::nice_region_error::find_anon_type; use crate::infer::error_reporting::nice_region_error::find_anon_type;
use rustc_errors::{ use rustc_errors::{
AddToDiagnostic, DiagnosticBuilder, EmissionGuarantee, IntoDiagnosticArg, AddToDiagnostic, Diag, EmissionGuarantee, IntoDiagnosticArg, SubdiagnosticMessageOp,
SubdiagnosticMessageOp,
}; };
use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::ty::{self, TyCtxt};
use rustc_span::{symbol::kw, Span}; use rustc_span::{symbol::kw, Span};
@ -165,7 +164,7 @@ impl RegionExplanation<'_> {
impl AddToDiagnostic for RegionExplanation<'_> { impl AddToDiagnostic for RegionExplanation<'_> {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
f: F, f: F,
) { ) {
diag.arg("pref_kind", self.prefix); diag.arg("pref_kind", self.prefix);

View file

@ -60,7 +60,7 @@ use crate::traits::{
use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
use rustc_errors::{ use rustc_errors::{
codes::*, pluralize, struct_span_code_err, Applicability, DiagCtxt, DiagnosticBuilder, codes::*, pluralize, struct_span_code_err, Applicability, Diag, DiagCtxt,
DiagnosticStyledString, ErrorGuaranteed, IntoDiagnosticArg, DiagnosticStyledString, ErrorGuaranteed, IntoDiagnosticArg,
}; };
use rustc_hir as hir; use rustc_hir as hir;
@ -158,7 +158,7 @@ impl<'tcx> Deref for TypeErrCtxt<'_, 'tcx> {
pub(super) fn note_and_explain_region<'tcx>( pub(super) fn note_and_explain_region<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
prefix: &str, prefix: &str,
region: ty::Region<'tcx>, region: ty::Region<'tcx>,
suffix: &str, suffix: &str,
@ -183,7 +183,7 @@ pub(super) fn note_and_explain_region<'tcx>(
fn explain_free_region<'tcx>( fn explain_free_region<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
prefix: &str, prefix: &str,
region: ty::Region<'tcx>, region: ty::Region<'tcx>,
suffix: &str, suffix: &str,
@ -265,7 +265,7 @@ fn msg_span_from_named_region<'tcx>(
} }
fn emit_msg_span( fn emit_msg_span(
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
prefix: &str, prefix: &str,
description: String, description: String,
span: Option<Span>, span: Option<Span>,
@ -281,7 +281,7 @@ fn emit_msg_span(
} }
fn label_msg_span( fn label_msg_span(
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
prefix: &str, prefix: &str,
description: String, description: String,
span: Option<Span>, span: Option<Span>,
@ -303,7 +303,7 @@ pub fn unexpected_hidden_region_diagnostic<'tcx>(
hidden_ty: Ty<'tcx>, hidden_ty: Ty<'tcx>,
hidden_region: ty::Region<'tcx>, hidden_region: ty::Region<'tcx>,
opaque_ty_key: ty::OpaqueTypeKey<'tcx>, opaque_ty_key: ty::OpaqueTypeKey<'tcx>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let mut err = tcx.dcx().create_err(errors::OpaqueCapturesLifetime { let mut err = tcx.dcx().create_err(errors::OpaqueCapturesLifetime {
span, span,
opaque_ty: Ty::new_opaque(tcx, opaque_ty_key.def_id.to_def_id(), opaque_ty_key.args), opaque_ty: Ty::new_opaque(tcx, opaque_ty_key.def_id.to_def_id(), opaque_ty_key.args),
@ -582,11 +582,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
} }
/// Adds a note if the types come from similarly named crates /// Adds a note if the types come from similarly named crates
fn check_and_note_conflicting_crates( fn check_and_note_conflicting_crates(&self, err: &mut Diag<'_>, terr: TypeError<'tcx>) {
&self,
err: &mut DiagnosticBuilder<'_>,
terr: TypeError<'tcx>,
) {
use hir::def_id::CrateNum; use hir::def_id::CrateNum;
use rustc_hir::definitions::DisambiguatedDefPathData; use rustc_hir::definitions::DisambiguatedDefPathData;
use ty::print::Printer; use ty::print::Printer;
@ -660,7 +656,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
} }
} }
let report_path_match = |err: &mut DiagnosticBuilder<'_>, did1: DefId, did2: DefId| { let report_path_match = |err: &mut Diag<'_>, did1: DefId, did2: DefId| {
// Only report definitions from different crates. If both definitions // Only report definitions from different crates. If both definitions
// are from a local module we could have false positives, e.g. // are from a local module we could have false positives, e.g.
// let _ = [{struct Foo; Foo}, {struct Foo; Foo}]; // let _ = [{struct Foo; Foo}, {struct Foo; Foo}];
@ -710,7 +706,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
fn note_error_origin( fn note_error_origin(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
cause: &ObligationCause<'tcx>, cause: &ObligationCause<'tcx>,
exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>, exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
terr: TypeError<'tcx>, terr: TypeError<'tcx>,
@ -1544,7 +1540,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
)] )]
pub fn note_type_err( pub fn note_type_err(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
cause: &ObligationCause<'tcx>, cause: &ObligationCause<'tcx>,
secondary_span: Option<(Span, Cow<'static, str>)>, secondary_span: Option<(Span, Cow<'static, str>)>,
mut values: Option<ValuePairs<'tcx>>, mut values: Option<ValuePairs<'tcx>>,
@ -1591,14 +1587,14 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
types_visitor types_visitor
} }
fn report(&self, err: &mut DiagnosticBuilder<'_>) { fn report(&self, err: &mut Diag<'_>) {
self.add_labels_for_types(err, "expected", &self.expected); self.add_labels_for_types(err, "expected", &self.expected);
self.add_labels_for_types(err, "found", &self.found); self.add_labels_for_types(err, "found", &self.found);
} }
fn add_labels_for_types( fn add_labels_for_types(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
target: &str, target: &str,
types: &FxIndexMap<TyCategory, FxIndexSet<Span>>, types: &FxIndexMap<TyCategory, FxIndexSet<Span>>,
) { ) {
@ -1809,16 +1805,12 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
// If two types mismatch but have similar names, mention that specifically. // If two types mismatch but have similar names, mention that specifically.
TypeError::Sorts(values) if let Some(s) = similarity(values) => { TypeError::Sorts(values) if let Some(s) = similarity(values) => {
let diagnose_primitive = let diagnose_primitive =
|prim: Ty<'tcx>, |prim: Ty<'tcx>, shadow: Ty<'tcx>, defid: DefId, diag: &mut Diag<'_>| {
shadow: Ty<'tcx>,
defid: DefId,
diagnostic: &mut DiagnosticBuilder<'_>| {
let name = shadow.sort_string(self.tcx); let name = shadow.sort_string(self.tcx);
diagnostic.note(format!( diag.note(format!(
"{prim} and {name} have similar names, but are actually distinct types" "{prim} and {name} have similar names, but are actually distinct types"
)); ));
diagnostic diag.note(format!("{prim} is a primitive defined by the language"));
.note(format!("{prim} is a primitive defined by the language"));
let def_span = self.tcx.def_span(defid); let def_span = self.tcx.def_span(defid);
let msg = if defid.is_local() { let msg = if defid.is_local() {
format!("{name} is defined in the current crate") format!("{name} is defined in the current crate")
@ -1826,20 +1818,20 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
let crate_name = self.tcx.crate_name(defid.krate); let crate_name = self.tcx.crate_name(defid.krate);
format!("{name} is defined in crate `{crate_name}`") format!("{name} is defined in crate `{crate_name}`")
}; };
diagnostic.span_note(def_span, msg); diag.span_note(def_span, msg);
}; };
let diagnose_adts = let diagnose_adts =
|expected_adt: ty::AdtDef<'tcx>, |expected_adt: ty::AdtDef<'tcx>,
found_adt: ty::AdtDef<'tcx>, found_adt: ty::AdtDef<'tcx>,
diagnostic: &mut DiagnosticBuilder<'_>| { diag: &mut Diag<'_>| {
let found_name = values.found.sort_string(self.tcx); let found_name = values.found.sort_string(self.tcx);
let expected_name = values.expected.sort_string(self.tcx); let expected_name = values.expected.sort_string(self.tcx);
let found_defid = found_adt.did(); let found_defid = found_adt.did();
let expected_defid = expected_adt.did(); let expected_defid = expected_adt.did();
diagnostic.note(format!("{found_name} and {expected_name} have similar names, but are actually distinct types")); diag.note(format!("{found_name} and {expected_name} have similar names, but are actually distinct types"));
for (defid, name) in for (defid, name) in
[(found_defid, found_name), (expected_defid, expected_name)] [(found_defid, found_name), (expected_defid, expected_name)]
{ {
@ -1861,7 +1853,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
let crate_name = self.tcx.crate_name(defid.krate); let crate_name = self.tcx.crate_name(defid.krate);
format!("{name} is defined in crate `{crate_name}`") format!("{name} is defined in crate `{crate_name}`")
}; };
diagnostic.span_note(def_span, msg); diag.span_note(def_span, msg);
} }
}; };
@ -2180,7 +2172,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
&self, &self,
trace: TypeTrace<'tcx>, trace: TypeTrace<'tcx>,
terr: TypeError<'tcx>, terr: TypeError<'tcx>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr); debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
let span = trace.cause.span(); let span = trace.cause.span();
@ -2328,7 +2320,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
origin: Option<SubregionOrigin<'tcx>>, origin: Option<SubregionOrigin<'tcx>>,
bound_kind: GenericKind<'tcx>, bound_kind: GenericKind<'tcx>,
sub: Region<'tcx>, sub: Region<'tcx>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
if let Some(SubregionOrigin::CompareImplItemObligation { if let Some(SubregionOrigin::CompareImplItemObligation {
span, span,
impl_item_def_id, impl_item_def_id,
@ -2741,10 +2733,7 @@ impl<'tcx> TypeRelation<'tcx> for SameTypeModuloInfer<'_, 'tcx> {
} }
impl<'tcx> InferCtxt<'tcx> { impl<'tcx> InferCtxt<'tcx> {
fn report_inference_failure( fn report_inference_failure(&self, var_origin: RegionVariableOrigin) -> Diag<'tcx> {
&self,
var_origin: RegionVariableOrigin,
) -> DiagnosticBuilder<'tcx> {
let br_string = |br: ty::BoundRegionKind| { let br_string = |br: ty::BoundRegionKind| {
let mut s = match br { let mut s = match br {
ty::BrNamed(_, name) => name.to_string(), ty::BrNamed(_, name) => name.to_string(),

View file

@ -5,7 +5,7 @@ use crate::errors::{
use crate::infer::error_reporting::TypeErrCtxt; use crate::infer::error_reporting::TypeErrCtxt;
use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use crate::infer::InferCtxt; use crate::infer::InferCtxt;
use rustc_errors::{codes::*, DiagnosticBuilder, IntoDiagnosticArg}; use rustc_errors::{codes::*, Diag, IntoDiagnosticArg};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::Res; use rustc_hir::def::Res;
use rustc_hir::def::{CtorOf, DefKind, Namespace}; use rustc_hir::def::{CtorOf, DefKind, Namespace};
@ -371,7 +371,7 @@ impl<'tcx> InferCtxt<'tcx> {
span: Span, span: Span,
arg_data: InferenceDiagnosticsData, arg_data: InferenceDiagnosticsData,
error_code: TypeAnnotationNeeded, error_code: TypeAnnotationNeeded,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let source_kind = "other"; let source_kind = "other";
let source_name = ""; let source_name = "";
let failure_span = None; let failure_span = None;
@ -419,7 +419,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
arg: GenericArg<'tcx>, arg: GenericArg<'tcx>,
error_code: TypeAnnotationNeeded, error_code: TypeAnnotationNeeded,
should_label_span: bool, should_label_span: bool,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let arg = self.resolve_vars_if_possible(arg); let arg = self.resolve_vars_if_possible(arg);
let arg_data = self.extract_inference_diagnostics_data(arg, None); let arg_data = self.extract_inference_diagnostics_data(arg, None);

View file

@ -12,7 +12,7 @@ use crate::infer::SubregionOrigin;
use crate::infer::TyCtxt; use crate::infer::TyCtxt;
use rustc_errors::AddToDiagnostic; use rustc_errors::AddToDiagnostic;
use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed}; use rustc_errors::{Diag, ErrorGuaranteed};
use rustc_hir::Ty; use rustc_hir::Ty;
use rustc_middle::ty::Region; use rustc_middle::ty::Region;
@ -142,7 +142,7 @@ pub fn suggest_adding_lifetime_params<'tcx>(
sub: Region<'tcx>, sub: Region<'tcx>,
ty_sup: &'tcx Ty<'_>, ty_sup: &'tcx Ty<'_>,
ty_sub: &'tcx Ty<'_>, ty_sub: &'tcx Ty<'_>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
) { ) {
let suggestion = AddLifetimeParamsSuggestion { tcx, sub, ty_sup, ty_sub, add_note: false }; let suggestion = AddLifetimeParamsSuggestion { tcx, sub, ty_sup, ty_sub, add_note: false };
suggestion.add_to_diagnostic(err); suggestion.add_to_diagnostic(err);

View file

@ -1,7 +1,7 @@
use crate::infer::error_reporting::TypeErrCtxt; use crate::infer::error_reporting::TypeErrCtxt;
use crate::infer::lexical_region_resolve::RegionResolutionError; use crate::infer::lexical_region_resolve::RegionResolutionError;
use crate::infer::lexical_region_resolve::RegionResolutionError::*; use crate::infer::lexical_region_resolve::RegionResolutionError::*;
use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed}; use rustc_errors::{Diag, ErrorGuaranteed};
use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::ty::{self, TyCtxt};
use rustc_span::Span; use rustc_span::Span;
@ -53,7 +53,7 @@ impl<'cx, 'tcx> NiceRegionError<'cx, 'tcx> {
self.cx.tcx self.cx.tcx
} }
pub fn try_report_from_nll(&self) -> Option<DiagnosticBuilder<'tcx>> { pub fn try_report_from_nll(&self) -> Option<Diag<'tcx>> {
// Due to the improved diagnostics returned by the MIR borrow checker, only a subset of // Due to the improved diagnostics returned by the MIR borrow checker, only a subset of
// the nice region errors are required when running under the MIR borrow checker. // the nice region errors are required when running under the MIR borrow checker.
self.try_report_named_anon_conflict() self.try_report_named_anon_conflict()

View file

@ -5,14 +5,14 @@ use crate::{
errors::ExplicitLifetimeRequired, errors::ExplicitLifetimeRequired,
infer::error_reporting::nice_region_error::find_anon_type::find_anon_type, infer::error_reporting::nice_region_error::find_anon_type::find_anon_type,
}; };
use rustc_errors::DiagnosticBuilder; use rustc_errors::Diag;
use rustc_middle::ty; use rustc_middle::ty;
use rustc_span::symbol::kw; use rustc_span::symbol::kw;
impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
/// When given a `ConcreteFailure` for a function with parameters containing a named region and /// When given a `ConcreteFailure` for a function with parameters containing a named region and
/// an anonymous region, emit an descriptive diagnostic error. /// an anonymous region, emit an descriptive diagnostic error.
pub(super) fn try_report_named_anon_conflict(&self) -> Option<DiagnosticBuilder<'tcx>> { pub(super) fn try_report_named_anon_conflict(&self) -> Option<Diag<'tcx>> {
let (span, sub, sup) = self.regions()?; let (span, sub, sup) = self.regions()?;
debug!( debug!(

View file

@ -8,7 +8,7 @@ use crate::infer::ValuePairs;
use crate::infer::{SubregionOrigin, TypeTrace}; use crate::infer::{SubregionOrigin, TypeTrace};
use crate::traits::{ObligationCause, ObligationCauseCode}; use crate::traits::{ObligationCause, ObligationCauseCode};
use rustc_data_structures::intern::Interned; use rustc_data_structures::intern::Interned;
use rustc_errors::{DiagnosticBuilder, IntoDiagnosticArg}; use rustc_errors::{Diag, IntoDiagnosticArg};
use rustc_hir::def::Namespace; use rustc_hir::def::Namespace;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_middle::ty::error::ExpectedFound; use rustc_middle::ty::error::ExpectedFound;
@ -57,7 +57,7 @@ where
impl<'tcx> NiceRegionError<'_, 'tcx> { impl<'tcx> NiceRegionError<'_, 'tcx> {
/// When given a `ConcreteFailure` for a function with arguments containing a named region and /// When given a `ConcreteFailure` for a function with arguments containing a named region and
/// an anonymous region, emit a descriptive diagnostic error. /// an anonymous region, emit a descriptive diagnostic error.
pub(super) fn try_report_placeholder_conflict(&self) -> Option<DiagnosticBuilder<'tcx>> { pub(super) fn try_report_placeholder_conflict(&self) -> Option<Diag<'tcx>> {
match &self.error { match &self.error {
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
// NB. The ordering of cases in this match is very // NB. The ordering of cases in this match is very
@ -193,7 +193,7 @@ impl<'tcx> NiceRegionError<'_, 'tcx> {
sub_placeholder: Option<Region<'tcx>>, sub_placeholder: Option<Region<'tcx>>,
sup_placeholder: Option<Region<'tcx>>, sup_placeholder: Option<Region<'tcx>>,
value_pairs: &ValuePairs<'tcx>, value_pairs: &ValuePairs<'tcx>,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<Diag<'tcx>> {
let (expected_args, found_args, trait_def_id) = match value_pairs { let (expected_args, found_args, trait_def_id) = match value_pairs {
ValuePairs::PolyTraitRefs(ExpectedFound { expected, found }) ValuePairs::PolyTraitRefs(ExpectedFound { expected, found })
if expected.def_id() == found.def_id() => if expected.def_id() == found.def_id() =>
@ -236,7 +236,7 @@ impl<'tcx> NiceRegionError<'_, 'tcx> {
trait_def_id: DefId, trait_def_id: DefId,
expected_args: GenericArgsRef<'tcx>, expected_args: GenericArgsRef<'tcx>,
actual_args: GenericArgsRef<'tcx>, actual_args: GenericArgsRef<'tcx>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let span = cause.span(); let span = cause.span();
let (leading_ellipsis, satisfy_span, where_span, dup_span, def_id) = let (leading_ellipsis, satisfy_span, where_span, dup_span, def_id) =

View file

@ -5,12 +5,12 @@ use crate::{
}, },
}; };
use rustc_data_structures::intern::Interned; use rustc_data_structures::intern::Interned;
use rustc_errors::DiagnosticBuilder; use rustc_errors::Diag;
use rustc_middle::ty::{self, RePlaceholder, Region}; use rustc_middle::ty::{self, RePlaceholder, Region};
impl<'tcx> NiceRegionError<'_, 'tcx> { impl<'tcx> NiceRegionError<'_, 'tcx> {
/// Emitted wwhen given a `ConcreteFailure` when relating two placeholders. /// Emitted wwhen given a `ConcreteFailure` when relating two placeholders.
pub(super) fn try_report_placeholder_relation(&self) -> Option<DiagnosticBuilder<'tcx>> { pub(super) fn try_report_placeholder_relation(&self) -> Option<Diag<'tcx>> {
match &self.error { match &self.error {
Some(RegionResolutionError::ConcreteFailure( Some(RegionResolutionError::ConcreteFailure(
SubregionOrigin::RelateRegionParamBound(span), SubregionOrigin::RelateRegionParamBound(span),

View file

@ -9,7 +9,7 @@ use crate::infer::lexical_region_resolve::RegionResolutionError;
use crate::infer::{SubregionOrigin, TypeTrace}; use crate::infer::{SubregionOrigin, TypeTrace};
use crate::traits::{ObligationCauseCode, UnifyReceiverContext}; use crate::traits::{ObligationCauseCode, UnifyReceiverContext};
use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::{AddToDiagnostic, Applicability, DiagnosticBuilder, ErrorGuaranteed, MultiSpan}; use rustc_errors::{AddToDiagnostic, Applicability, Diag, ErrorGuaranteed, MultiSpan};
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_hir::intravisit::{walk_ty, Visitor}; use rustc_hir::intravisit::{walk_ty, Visitor};
use rustc_hir::{ use rustc_hir::{
@ -261,7 +261,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
pub fn suggest_new_region_bound( pub fn suggest_new_region_bound(
tcx: TyCtxt<'_>, tcx: TyCtxt<'_>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
fn_returns: Vec<&rustc_hir::Ty<'_>>, fn_returns: Vec<&rustc_hir::Ty<'_>>,
lifetime_name: String, lifetime_name: String,
arg: Option<String>, arg: Option<String>,
@ -488,7 +488,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
/// `'static` obligation. Suggest relaxing that implicit bound. /// `'static` obligation. Suggest relaxing that implicit bound.
fn find_impl_on_dyn_trait( fn find_impl_on_dyn_trait(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
ty: Ty<'_>, ty: Ty<'_>,
ctxt: &UnifyReceiverContext<'tcx>, ctxt: &UnifyReceiverContext<'tcx>,
) -> bool { ) -> bool {
@ -521,7 +521,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
fn suggest_constrain_dyn_trait_in_impl( fn suggest_constrain_dyn_trait_in_impl(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
found_dids: &FxIndexSet<DefId>, found_dids: &FxIndexSet<DefId>,
ident: Ident, ident: Ident,
self_ty: &hir::Ty<'_>, self_ty: &hir::Ty<'_>,

View file

@ -5,7 +5,7 @@ use crate::errors::{
use crate::fluent_generated as fluent; use crate::fluent_generated as fluent;
use crate::infer::error_reporting::{note_and_explain_region, TypeErrCtxt}; use crate::infer::error_reporting::{note_and_explain_region, TypeErrCtxt};
use crate::infer::{self, SubregionOrigin}; use crate::infer::{self, SubregionOrigin};
use rustc_errors::{AddToDiagnostic, DiagnosticBuilder}; use rustc_errors::{AddToDiagnostic, Diag};
use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_middle::traits::ObligationCauseCode; use rustc_middle::traits::ObligationCauseCode;
use rustc_middle::ty::error::TypeError; use rustc_middle::ty::error::TypeError;
@ -15,11 +15,7 @@ use rustc_span::symbol::kw;
use super::ObligationCauseAsDiagArg; use super::ObligationCauseAsDiagArg;
impl<'tcx> TypeErrCtxt<'_, 'tcx> { impl<'tcx> TypeErrCtxt<'_, 'tcx> {
pub(super) fn note_region_origin( pub(super) fn note_region_origin(&self, err: &mut Diag<'_>, origin: &SubregionOrigin<'tcx>) {
&self,
err: &mut DiagnosticBuilder<'_>,
origin: &SubregionOrigin<'tcx>,
) {
match *origin { match *origin {
infer::Subtype(ref trace) => RegionOriginNote::WithRequirement { infer::Subtype(ref trace) => RegionOriginNote::WithRequirement {
span: trace.cause.span, span: trace.cause.span,
@ -82,7 +78,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
origin: SubregionOrigin<'tcx>, origin: SubregionOrigin<'tcx>,
sub: Region<'tcx>, sub: Region<'tcx>,
sup: Region<'tcx>, sup: Region<'tcx>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let mut err = match origin { let mut err = match origin {
infer::Subtype(box trace) => { infer::Subtype(box trace) => {
let terr = TypeError::RegionsDoesNotOutlive(sup, sub); let terr = TypeError::RegionsDoesNotOutlive(sup, sub);
@ -294,7 +290,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
&self, &self,
trait_item_def_id: DefId, trait_item_def_id: DefId,
impl_item_def_id: LocalDefId, impl_item_def_id: LocalDefId,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
) { ) {
// FIXME(compiler-errors): Right now this is only being used for region // FIXME(compiler-errors): Right now this is only being used for region
// predicate mismatches. Ideally, we'd use it for *all* predicate mismatches, // predicate mismatches. Ideally, we'd use it for *all* predicate mismatches,
@ -354,7 +350,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
placeholder_origin: SubregionOrigin<'tcx>, placeholder_origin: SubregionOrigin<'tcx>,
sub: Region<'tcx>, sub: Region<'tcx>,
sup: Region<'tcx>, sup: Region<'tcx>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
// I can't think how to do better than this right now. -nikomatsakis // I can't think how to do better than this right now. -nikomatsakis
debug!(?placeholder_origin, ?sub, ?sup, "report_placeholder_failure"); debug!(?placeholder_origin, ?sub, ?sup, "report_placeholder_failure");
match placeholder_origin { match placeholder_origin {

View file

@ -1,6 +1,6 @@
use super::TypeErrCtxt; use super::TypeErrCtxt;
use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect}; use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect};
use rustc_errors::{pluralize, DiagnosticBuilder, MultiSpan}; use rustc_errors::{pluralize, Diag, MultiSpan};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::DefKind; use rustc_hir::def::DefKind;
use rustc_middle::traits::ObligationCauseCode; use rustc_middle::traits::ObligationCauseCode;
@ -15,7 +15,7 @@ use rustc_span::{def_id::DefId, sym, BytePos, Span, Symbol};
impl<'tcx> TypeErrCtxt<'_, 'tcx> { impl<'tcx> TypeErrCtxt<'_, 'tcx> {
pub fn note_and_explain_type_err( pub fn note_and_explain_type_err(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
err: TypeError<'tcx>, err: TypeError<'tcx>,
cause: &ObligationCause<'tcx>, cause: &ObligationCause<'tcx>,
sp: Span, sp: Span,
@ -522,7 +522,7 @@ impl<T> Trait<T> for X {
fn suggest_constraint( fn suggest_constraint(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
msg: impl Fn() -> String, msg: impl Fn() -> String,
body_owner_def_id: DefId, body_owner_def_id: DefId,
proj_ty: &ty::AliasTy<'tcx>, proj_ty: &ty::AliasTy<'tcx>,
@ -595,7 +595,7 @@ impl<T> Trait<T> for X {
/// fn that returns the type. /// fn that returns the type.
fn expected_projection( fn expected_projection(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
proj_ty: &ty::AliasTy<'tcx>, proj_ty: &ty::AliasTy<'tcx>,
values: ExpectedFound<Ty<'tcx>>, values: ExpectedFound<Ty<'tcx>>,
body_owner_def_id: DefId, body_owner_def_id: DefId,
@ -705,7 +705,7 @@ fn foo(&self) -> Self::T { String::new() }
/// a return type. This can occur when dealing with `TryStream` (#71035). /// a return type. This can occur when dealing with `TryStream` (#71035).
fn suggest_constraining_opaque_associated_type( fn suggest_constraining_opaque_associated_type(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
msg: impl Fn() -> String, msg: impl Fn() -> String,
proj_ty: &ty::AliasTy<'tcx>, proj_ty: &ty::AliasTy<'tcx>,
ty: Ty<'tcx>, ty: Ty<'tcx>,
@ -740,7 +740,7 @@ fn foo(&self) -> Self::T { String::new() }
fn point_at_methods_that_satisfy_associated_type( fn point_at_methods_that_satisfy_associated_type(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
assoc_container_id: DefId, assoc_container_id: DefId,
current_method_ident: Option<Symbol>, current_method_ident: Option<Symbol>,
proj_ty_item_def_id: DefId, proj_ty_item_def_id: DefId,
@ -798,7 +798,7 @@ fn foo(&self) -> Self::T { String::new() }
fn point_at_associated_type( fn point_at_associated_type(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
body_owner_def_id: DefId, body_owner_def_id: DefId,
found: Ty<'tcx>, found: Ty<'tcx>,
) -> bool { ) -> bool {
@ -879,7 +879,7 @@ fn foo(&self) -> Self::T { String::new() }
/// type is defined on a supertrait of the one present in the bounds. /// type is defined on a supertrait of the one present in the bounds.
fn constrain_generic_bound_associated_type_structured_suggestion( fn constrain_generic_bound_associated_type_structured_suggestion(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
trait_ref: &ty::TraitRef<'tcx>, trait_ref: &ty::TraitRef<'tcx>,
bounds: hir::GenericBounds<'_>, bounds: hir::GenericBounds<'_>,
assoc: ty::AssocItem, assoc: ty::AssocItem,
@ -916,7 +916,7 @@ fn foo(&self) -> Self::T { String::new() }
/// associated type to a given type `ty`. /// associated type to a given type `ty`.
fn constrain_associated_type_structured_suggestion( fn constrain_associated_type_structured_suggestion(
&self, &self,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
span: Span, span: Span,
assoc: ty::AssocItem, assoc: ty::AssocItem,
assoc_args: &[ty::GenericArg<'tcx>], assoc_args: &[ty::GenericArg<'tcx>],

View file

@ -1,7 +1,7 @@
use hir::def::CtorKind; use hir::def::CtorKind;
use hir::intravisit::{walk_expr, walk_stmt, Visitor}; use hir::intravisit::{walk_expr, walk_stmt, Visitor};
use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_errors::{Applicability, Diag};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_middle::traits::{ use rustc_middle::traits::{
IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode, IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
@ -76,7 +76,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
pub(super) fn suggest_boxing_for_return_impl_trait( pub(super) fn suggest_boxing_for_return_impl_trait(
&self, &self,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
return_sp: Span, return_sp: Span,
arm_spans: impl Iterator<Item = Span>, arm_spans: impl Iterator<Item = Span>,
) { ) {
@ -100,7 +100,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
&self, &self,
cause: &ObligationCause<'tcx>, cause: &ObligationCause<'tcx>,
exp_found: &ty::error::ExpectedFound<Ty<'tcx>>, exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
) { ) {
// Heavily inspired by `FnCtxt::suggest_compatible_variants`, with // Heavily inspired by `FnCtxt::suggest_compatible_variants`, with
// some modifications due to that being in typeck and this being in infer. // some modifications due to that being in typeck and this being in infer.
@ -177,7 +177,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
cause: &ObligationCause<'tcx>, cause: &ObligationCause<'tcx>,
exp_span: Span, exp_span: Span,
exp_found: &ty::error::ExpectedFound<Ty<'tcx>>, exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
) { ) {
debug!( debug!(
"suggest_await_on_expect_found: exp_span={:?}, expected_ty={:?}, found_ty={:?}", "suggest_await_on_expect_found: exp_span={:?}, expected_ty={:?}, found_ty={:?}",
@ -258,7 +258,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
&self, &self,
cause: &ObligationCause<'tcx>, cause: &ObligationCause<'tcx>,
exp_found: &ty::error::ExpectedFound<Ty<'tcx>>, exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
) { ) {
debug!( debug!(
"suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})", "suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})",
@ -298,7 +298,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
cause: &ObligationCause<'tcx>, cause: &ObligationCause<'tcx>,
span: Span, span: Span,
exp_found: &ty::error::ExpectedFound<Ty<'tcx>>, exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
) { ) {
debug!("suggest_function_pointers(cause={:?}, exp_found={:?})", cause, exp_found); debug!("suggest_function_pointers(cause={:?}, exp_found={:?})", cause, exp_found);
let ty::error::ExpectedFound { expected, found } = exp_found; let ty::error::ExpectedFound { expected, found } = exp_found;
@ -532,7 +532,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
span: Span, span: Span,
hir: hir::Node<'_>, hir: hir::Node<'_>,
exp_found: &ty::error::ExpectedFound<ty::PolyTraitRef<'tcx>>, exp_found: &ty::error::ExpectedFound<ty::PolyTraitRef<'tcx>>,
diag: &mut DiagnosticBuilder<'_>, diag: &mut Diag<'_>,
) { ) {
// 0. Extract fn_decl from hir // 0. Extract fn_decl from hir
let hir::Node::Expr(hir::Expr { let hir::Node::Expr(hir::Expr {
@ -818,7 +818,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
&self, &self,
blk: &'tcx hir::Block<'tcx>, blk: &'tcx hir::Block<'tcx>,
expected_ty: Ty<'tcx>, expected_ty: Ty<'tcx>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
) -> bool { ) -> bool {
let diag = self.consider_returning_binding_diag(blk, expected_ty); let diag = self.consider_returning_binding_diag(blk, expected_ty);
match diag { match diag {

View file

@ -23,7 +23,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::sync::Lrc; use rustc_data_structures::sync::Lrc;
use rustc_data_structures::undo_log::Rollback; use rustc_data_structures::undo_log::Rollback;
use rustc_data_structures::unify as ut; use rustc_data_structures::unify as ut;
use rustc_errors::{DiagCtxt, DiagnosticBuilder, ErrorGuaranteed}; use rustc_errors::{Diag, DiagCtxt, ErrorGuaranteed};
use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues}; use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
use rustc_middle::infer::unify_key::ConstVariableValue; use rustc_middle::infer::unify_key::ConstVariableValue;
@ -1767,9 +1767,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
sp: Span, sp: Span,
mk_diag: M, mk_diag: M,
actual_ty: Ty<'tcx>, actual_ty: Ty<'tcx>,
) -> DiagnosticBuilder<'tcx> ) -> Diag<'tcx>
where where
M: FnOnce(String) -> DiagnosticBuilder<'tcx>, M: FnOnce(String) -> Diag<'tcx>,
{ {
let actual_ty = self.resolve_vars_if_possible(actual_ty); let actual_ty = self.resolve_vars_if_possible(actual_ty);
debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty); debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
@ -1790,7 +1790,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
expected: Ty<'tcx>, expected: Ty<'tcx>,
actual: Ty<'tcx>, actual: Ty<'tcx>,
err: TypeError<'tcx>, err: TypeError<'tcx>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
self.report_and_explain_type_error(TypeTrace::types(cause, true, expected, actual), err) self.report_and_explain_type_error(TypeTrace::types(cause, true, expected, actual), err)
} }
@ -1800,7 +1800,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
expected: ty::Const<'tcx>, expected: ty::Const<'tcx>,
actual: ty::Const<'tcx>, actual: ty::Const<'tcx>,
err: TypeError<'tcx>, err: TypeError<'tcx>,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
self.report_and_explain_type_error(TypeTrace::consts(cause, true, expected, actual), err) self.report_and_explain_type_error(TypeTrace::consts(cause, true, expected, actual), err)
} }
} }

View file

@ -2,7 +2,7 @@ use super::ObjectSafetyViolation;
use crate::infer::InferCtxt; use crate::infer::InferCtxt;
use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::{codes::*, struct_span_code_err, Applicability, DiagnosticBuilder, MultiSpan}; use rustc_errors::{codes::*, struct_span_code_err, Applicability, Diag, MultiSpan};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::print::with_no_trimmed_paths;
@ -18,7 +18,7 @@ impl<'tcx> InferCtxt<'tcx> {
impl_item_def_id: LocalDefId, impl_item_def_id: LocalDefId,
trait_item_def_id: DefId, trait_item_def_id: DefId,
requirement: &dyn fmt::Display, requirement: &dyn fmt::Display,
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let mut err = struct_span_code_err!( let mut err = struct_span_code_err!(
self.tcx.dcx(), self.tcx.dcx(),
error_span, error_span,
@ -45,7 +45,7 @@ pub fn report_object_safety_error<'tcx>(
hir_id: Option<hir::HirId>, hir_id: Option<hir::HirId>,
trait_def_id: DefId, trait_def_id: DefId,
violations: &[ObjectSafetyViolation], violations: &[ObjectSafetyViolation],
) -> DiagnosticBuilder<'tcx> { ) -> Diag<'tcx> {
let trait_str = tcx.def_path_str(trait_def_id); let trait_str = tcx.def_path_str(trait_def_id);
let trait_span = tcx.hir().get_if_local(trait_def_id).and_then(|node| match node { let trait_span = tcx.hir().get_if_local(trait_def_id).and_then(|node| match node {
hir::Node::Item(item) => Some(item.ident.span), hir::Node::Item(item) => Some(item.ident.span),

View file

@ -21,7 +21,7 @@ use crate::passes::{EarlyLintPassObject, LateLintPassObject};
use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::sync; use rustc_data_structures::sync;
use rustc_data_structures::unord::UnordMap; use rustc_data_structures::unord::UnordMap;
use rustc_errors::{DecorateLint, DiagnosticBuilder, DiagnosticMessage, MultiSpan}; use rustc_errors::{DecorateLint, Diag, DiagnosticMessage, MultiSpan};
use rustc_feature::Features; use rustc_feature::Features;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::Res; use rustc_hir::def::Res;
@ -338,7 +338,7 @@ impl LintStore {
} }
/// Checks the name of a lint for its existence, and whether it was /// Checks the name of a lint for its existence, and whether it was
/// renamed or removed. Generates a DiagnosticBuilder containing a /// renamed or removed. Generates a `Diag` containing a
/// warning for renamed and removed lints. This is over both lint /// warning for renamed and removed lints. This is over both lint
/// names from attributes and those passed on the command line. Since /// names from attributes and those passed on the command line. Since
/// it emits non-fatal warnings and there are *two* lint passes that /// it emits non-fatal warnings and there are *two* lint passes that
@ -537,7 +537,7 @@ pub trait LintContext {
lint: &'static Lint, lint: &'static Lint,
span: Option<impl Into<MultiSpan>>, span: Option<impl Into<MultiSpan>>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>), decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
diagnostic: BuiltinLintDiagnostics, diagnostic: BuiltinLintDiagnostics,
) { ) {
// We first generate a blank diagnostic. // We first generate a blank diagnostic.
@ -560,7 +560,7 @@ pub trait LintContext {
lint: &'static Lint, lint: &'static Lint,
span: Option<S>, span: Option<S>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>), decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
); );
/// Emit a lint at `span` from a lint struct (some type that implements `DecorateLint`, /// Emit a lint at `span` from a lint struct (some type that implements `DecorateLint`,
@ -585,7 +585,7 @@ pub trait LintContext {
lint: &'static Lint, lint: &'static Lint,
span: S, span: S,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>), decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
) { ) {
self.opt_span_lint(lint, Some(span), msg, decorate); self.opt_span_lint(lint, Some(span), msg, decorate);
} }
@ -606,7 +606,7 @@ pub trait LintContext {
&self, &self,
lint: &'static Lint, lint: &'static Lint,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>), decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
) { ) {
self.opt_span_lint(lint, None as Option<Span>, msg, decorate); self.opt_span_lint(lint, None as Option<Span>, msg, decorate);
} }
@ -671,7 +671,7 @@ impl<'tcx> LintContext for LateContext<'tcx> {
lint: &'static Lint, lint: &'static Lint,
span: Option<S>, span: Option<S>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>), decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
) { ) {
let hir_id = self.last_node_with_lint_attrs; let hir_id = self.last_node_with_lint_attrs;
@ -698,7 +698,7 @@ impl LintContext for EarlyContext<'_> {
lint: &'static Lint, lint: &'static Lint,
span: Option<S>, span: Option<S>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>), decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
) { ) {
self.builder.opt_span_lint(lint, span.map(|s| s.into()), msg, decorate) self.builder.opt_span_lint(lint, span.map(|s| s.into()), msg, decorate)
} }

View file

@ -2,7 +2,7 @@
#![allow(rustc::untranslatable_diagnostic)] #![allow(rustc::untranslatable_diagnostic)]
use rustc_ast::util::unicode::TEXT_FLOW_CONTROL_CHARS; use rustc_ast::util::unicode::TEXT_FLOW_CONTROL_CHARS;
use rustc_errors::{add_elided_lifetime_in_path_suggestion, DiagnosticBuilder}; use rustc_errors::{add_elided_lifetime_in_path_suggestion, Diag};
use rustc_errors::{Applicability, SuggestionStyle}; use rustc_errors::{Applicability, SuggestionStyle};
use rustc_middle::middle::stability; use rustc_middle::middle::stability;
use rustc_session::config::ExpectedValues; use rustc_session::config::ExpectedValues;
@ -12,11 +12,7 @@ use rustc_span::edit_distance::find_best_match_for_name;
use rustc_span::symbol::{sym, Symbol}; use rustc_span::symbol::{sym, Symbol};
use rustc_span::BytePos; use rustc_span::BytePos;
pub(super) fn builtin( pub(super) fn builtin(sess: &Session, diagnostic: BuiltinLintDiagnostics, diag: &mut Diag<'_, ()>) {
sess: &Session,
diagnostic: BuiltinLintDiagnostics,
db: &mut DiagnosticBuilder<'_, ()>,
) {
match diagnostic { match diagnostic {
BuiltinLintDiagnostics::UnicodeTextFlow(span, content) => { BuiltinLintDiagnostics::UnicodeTextFlow(span, content) => {
let spans: Vec<_> = content let spans: Vec<_> = content
@ -32,22 +28,22 @@ pub(super) fn builtin(
1 => ("an ", ""), 1 => ("an ", ""),
_ => ("", "s"), _ => ("", "s"),
}; };
db.span_label( diag.span_label(
span, span,
format!( format!(
"this comment contains {an}invisible unicode text flow control codepoint{s}", "this comment contains {an}invisible unicode text flow control codepoint{s}",
), ),
); );
for (c, span) in &spans { for (c, span) in &spans {
db.span_label(*span, format!("{c:?}")); diag.span_label(*span, format!("{c:?}"));
} }
db.note( diag.note(
"these kind of unicode codepoints change the way text flows on \ "these kind of unicode codepoints change the way text flows on \
applications that support them, but can cause confusion because they \ applications that support them, but can cause confusion because they \
change the order of characters on the screen", change the order of characters on the screen",
); );
if !spans.is_empty() { if !spans.is_empty() {
db.multipart_suggestion_with_style( diag.multipart_suggestion_with_style(
"if their presence wasn't intentional, you can remove them", "if their presence wasn't intentional, you can remove them",
spans.into_iter().map(|(_, span)| (span, "".to_string())).collect(), spans.into_iter().map(|(_, span)| (span, "".to_string())).collect(),
Applicability::MachineApplicable, Applicability::MachineApplicable,
@ -67,16 +63,16 @@ pub(super) fn builtin(
} }
Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders), Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
}; };
db.span_suggestion(span, "use `crate`", sugg, app); diag.span_suggestion(span, "use `crate`", sugg, app);
} }
BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => { BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
db.span_label( diag.span_label(
span, span,
"names from parent modules are not accessible without an explicit import", "names from parent modules are not accessible without an explicit import",
); );
} }
BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def) => { BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def) => {
db.span_note(span_def, "the macro is defined here"); diag.span_note(span_def, "the macro is defined here");
} }
BuiltinLintDiagnostics::ElidedLifetimesInPaths( BuiltinLintDiagnostics::ElidedLifetimesInPaths(
n, n,
@ -86,7 +82,7 @@ pub(super) fn builtin(
) => { ) => {
add_elided_lifetime_in_path_suggestion( add_elided_lifetime_in_path_suggestion(
sess.source_map(), sess.source_map(),
db, diag,
n, n,
path_span, path_span,
incl_angl_brckt, incl_angl_brckt,
@ -94,11 +90,11 @@ pub(super) fn builtin(
); );
} }
BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => { BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
db.span_suggestion(span, note, sugg, Applicability::MaybeIncorrect); diag.span_suggestion(span, note, sugg, Applicability::MaybeIncorrect);
} }
BuiltinLintDiagnostics::UnusedImports(message, replaces, in_test_module) => { BuiltinLintDiagnostics::UnusedImports(message, replaces, in_test_module) => {
if !replaces.is_empty() { if !replaces.is_empty() {
db.tool_only_multipart_suggestion( diag.tool_only_multipart_suggestion(
message, message,
replaces, replaces,
Applicability::MachineApplicable, Applicability::MachineApplicable,
@ -106,7 +102,7 @@ pub(super) fn builtin(
} }
if let Some(span) = in_test_module { if let Some(span) = in_test_module {
db.span_help( diag.span_help(
sess.source_map().guess_head_span(span), sess.source_map().guess_head_span(span),
"consider adding a `#[cfg(test)]` to the containing module", "consider adding a `#[cfg(test)]` to the containing module",
); );
@ -115,19 +111,19 @@ pub(super) fn builtin(
BuiltinLintDiagnostics::RedundantImport(spans, ident) => { BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
for (span, is_imported) in spans { for (span, is_imported) in spans {
let introduced = if is_imported { "imported" } else { "defined" }; let introduced = if is_imported { "imported" } else { "defined" };
db.span_label(span, format!("the item `{ident}` is already {introduced} here")); diag.span_label(span, format!("the item `{ident}` is already {introduced} here"));
} }
} }
BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => { BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
stability::deprecation_suggestion(db, "macro", suggestion, span) stability::deprecation_suggestion(diag, "macro", suggestion, span)
} }
BuiltinLintDiagnostics::UnusedDocComment(span) => { BuiltinLintDiagnostics::UnusedDocComment(span) => {
db.span_label(span, "rustdoc does not generate documentation for macro invocations"); diag.span_label(span, "rustdoc does not generate documentation for macro invocations");
db.help("to document an item produced by a macro, \ diag.help("to document an item produced by a macro, \
the macro must produce the documentation as part of its expansion"); the macro must produce the documentation as part of its expansion");
} }
BuiltinLintDiagnostics::PatternsInFnsWithoutBody(span, ident) => { BuiltinLintDiagnostics::PatternsInFnsWithoutBody(span, ident) => {
db.span_suggestion( diag.span_suggestion(
span, span,
"remove `mut` from the parameter", "remove `mut` from the parameter",
ident, ident,
@ -135,17 +131,17 @@ pub(super) fn builtin(
); );
} }
BuiltinLintDiagnostics::MissingAbi(span, default_abi) => { BuiltinLintDiagnostics::MissingAbi(span, default_abi) => {
db.span_label(span, "ABI should be specified here"); diag.span_label(span, "ABI should be specified here");
db.help(format!("the default ABI is {}", default_abi.name())); diag.help(format!("the default ABI is {}", default_abi.name()));
} }
BuiltinLintDiagnostics::LegacyDeriveHelpers(span) => { BuiltinLintDiagnostics::LegacyDeriveHelpers(span) => {
db.span_label(span, "the attribute is introduced here"); diag.span_label(span, "the attribute is introduced here");
} }
BuiltinLintDiagnostics::ProcMacroBackCompat(note) => { BuiltinLintDiagnostics::ProcMacroBackCompat(note) => {
db.note(note); diag.note(note);
} }
BuiltinLintDiagnostics::OrPatternsBackCompat(span, suggestion) => { BuiltinLintDiagnostics::OrPatternsBackCompat(span, suggestion) => {
db.span_suggestion( diag.span_suggestion(
span, span,
"use pat_param to preserve semantics", "use pat_param to preserve semantics",
suggestion, suggestion,
@ -153,8 +149,8 @@ pub(super) fn builtin(
); );
} }
BuiltinLintDiagnostics::ReservedPrefix(span) => { BuiltinLintDiagnostics::ReservedPrefix(span) => {
db.span_label(span, "unknown prefix"); diag.span_label(span, "unknown prefix");
db.span_suggestion_verbose( diag.span_suggestion_verbose(
span.shrink_to_hi(), span.shrink_to_hi(),
"insert whitespace here to avoid this being parsed as a prefix in Rust 2021", "insert whitespace here to avoid this being parsed as a prefix in Rust 2021",
" ", " ",
@ -162,19 +158,19 @@ pub(super) fn builtin(
); );
} }
BuiltinLintDiagnostics::UnusedBuiltinAttribute { attr_name, macro_name, invoc_span } => { BuiltinLintDiagnostics::UnusedBuiltinAttribute { attr_name, macro_name, invoc_span } => {
db.span_note( diag.span_note(
invoc_span, invoc_span,
format!("the built-in attribute `{attr_name}` will be ignored, since it's applied to the macro invocation `{macro_name}`") format!("the built-in attribute `{attr_name}` will be ignored, since it's applied to the macro invocation `{macro_name}`")
); );
} }
BuiltinLintDiagnostics::TrailingMacro(is_trailing, name) => { BuiltinLintDiagnostics::TrailingMacro(is_trailing, name) => {
if is_trailing { if is_trailing {
db.note("macro invocations at the end of a block are treated as expressions"); diag.note("macro invocations at the end of a block are treated as expressions");
db.note(format!("to ignore the value produced by the macro, add a semicolon after the invocation of `{name}`")); diag.note(format!("to ignore the value produced by the macro, add a semicolon after the invocation of `{name}`"));
} }
} }
BuiltinLintDiagnostics::BreakWithLabelAndLoop(span) => { BuiltinLintDiagnostics::BreakWithLabelAndLoop(span) => {
db.multipart_suggestion( diag.multipart_suggestion(
"wrap this expression in parentheses", "wrap this expression in parentheses",
vec![ vec![
(span.shrink_to_lo(), "(".to_string()), (span.shrink_to_lo(), "(".to_string()),
@ -184,8 +180,8 @@ pub(super) fn builtin(
); );
} }
BuiltinLintDiagnostics::NamedAsmLabel(help) => { BuiltinLintDiagnostics::NamedAsmLabel(help) => {
db.help(help); diag.help(help);
db.note("see the asm section of Rust By Example <https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels> for more information"); diag.note("see the asm section of Rust By Example <https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels> for more information");
} }
BuiltinLintDiagnostics::UnexpectedCfgName((name, name_span), value) => { BuiltinLintDiagnostics::UnexpectedCfgName((name, name_span), value) => {
#[allow(rustc::potential_query_instability)] #[allow(rustc::potential_query_instability)]
@ -212,7 +208,7 @@ pub(super) fn builtin(
let mut is_feature_cfg = name == sym::feature; let mut is_feature_cfg = name == sym::feature;
if is_feature_cfg && is_from_cargo { if is_feature_cfg && is_from_cargo {
db.help("consider defining some features in `Cargo.toml`"); diag.help("consider defining some features in `Cargo.toml`");
// Suggest the most probable if we found one // Suggest the most probable if we found one
} else if let Some(best_match) = find_best_match_for_name(&possibilities, name, None) { } else if let Some(best_match) = find_best_match_for_name(&possibilities, name, None) {
if let Some(ExpectedValues::Some(best_match_values)) = if let Some(ExpectedValues::Some(best_match_values)) =
@ -227,7 +223,7 @@ pub(super) fn builtin(
let mut should_print_possibilities = true; let mut should_print_possibilities = true;
if let Some((value, value_span)) = value { if let Some((value, value_span)) = value {
if best_match_values.contains(&Some(value)) { if best_match_values.contains(&Some(value)) {
db.span_suggestion( diag.span_suggestion(
name_span, name_span,
"there is a config with a similar name and value", "there is a config with a similar name and value",
best_match, best_match,
@ -235,7 +231,7 @@ pub(super) fn builtin(
); );
should_print_possibilities = false; should_print_possibilities = false;
} else if best_match_values.contains(&None) { } else if best_match_values.contains(&None) {
db.span_suggestion( diag.span_suggestion(
name_span.to(value_span), name_span.to(value_span),
"there is a config with a similar name and no value", "there is a config with a similar name and no value",
best_match, best_match,
@ -243,14 +239,14 @@ pub(super) fn builtin(
); );
should_print_possibilities = false; should_print_possibilities = false;
} else if let Some(first_value) = possibilities.first() { } else if let Some(first_value) = possibilities.first() {
db.span_suggestion( diag.span_suggestion(
name_span.to(value_span), name_span.to(value_span),
"there is a config with a similar name and different values", "there is a config with a similar name and different values",
format!("{best_match} = \"{first_value}\""), format!("{best_match} = \"{first_value}\""),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
} else { } else {
db.span_suggestion( diag.span_suggestion(
name_span.to(value_span), name_span.to(value_span),
"there is a config with a similar name and different values", "there is a config with a similar name and different values",
best_match, best_match,
@ -258,7 +254,7 @@ pub(super) fn builtin(
); );
}; };
} else { } else {
db.span_suggestion( diag.span_suggestion(
name_span, name_span,
"there is a config with a similar name", "there is a config with a similar name",
best_match, best_match,
@ -268,12 +264,12 @@ pub(super) fn builtin(
if !possibilities.is_empty() && should_print_possibilities { if !possibilities.is_empty() && should_print_possibilities {
let possibilities = possibilities.join("`, `"); let possibilities = possibilities.join("`, `");
db.help(format!( diag.help(format!(
"expected values for `{best_match}` are: `{possibilities}`" "expected values for `{best_match}` are: `{possibilities}`"
)); ));
} }
} else { } else {
db.span_suggestion( diag.span_suggestion(
name_span, name_span,
"there is a config with a similar name", "there is a config with a similar name",
best_match, best_match,
@ -286,7 +282,7 @@ pub(super) fn builtin(
if !names_possibilities.is_empty() && names_possibilities.len() <= 3 { if !names_possibilities.is_empty() && names_possibilities.len() <= 3 {
names_possibilities.sort(); names_possibilities.sort();
for cfg_name in names_possibilities.iter() { for cfg_name in names_possibilities.iter() {
db.span_suggestion( diag.span_suggestion(
name_span, name_span,
"found config with similar value", "found config with similar value",
format!("{cfg_name} = \"{name}\""), format!("{cfg_name} = \"{name}\""),
@ -304,7 +300,7 @@ pub(super) fn builtin(
// so the diagnostic produced can take a lot of space. To avoid // so the diagnostic produced can take a lot of space. To avoid
// cloging the user output we only want to print that diagnostic // cloging the user output we only want to print that diagnostic
// once. // once.
db.help_once(format!("expected names are: `{possibilities}`")); diag.help_once(format!("expected names are: `{possibilities}`"));
} }
} }
@ -317,12 +313,12 @@ pub(super) fn builtin(
if is_from_cargo { if is_from_cargo {
if !is_feature_cfg { if !is_feature_cfg {
db.help(format!("consider using a Cargo feature instead or adding `println!(\"cargo:rustc-check-cfg={inst}\");` to the top of a `build.rs`")); diag.help(format!("consider using a Cargo feature instead or adding `println!(\"cargo:rustc-check-cfg={inst}\");` to the top of a `build.rs`"));
} }
db.note("see <https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#check-cfg> for more information about checking conditional configuration"); diag.note("see <https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#check-cfg> for more information about checking conditional configuration");
} else { } else {
db.help(format!("to expect this configuration use `--check-cfg={inst}`")); diag.help(format!("to expect this configuration use `--check-cfg={inst}`"));
db.note("see <https://doc.rust-lang.org/nightly/unstable-book/compiler-flags/check-cfg.html> for more information about checking conditional configuration"); diag.note("see <https://doc.rust-lang.org/nightly/unstable-book/compiler-flags/check-cfg.html> for more information about checking conditional configuration");
} }
} }
BuiltinLintDiagnostics::UnexpectedCfgValue((name, name_span), value) => { BuiltinLintDiagnostics::UnexpectedCfgValue((name, name_span), value) => {
@ -356,14 +352,14 @@ pub(super) fn builtin(
let possibilities = possibilities.join("`, `"); let possibilities = possibilities.join("`, `");
let none = if have_none_possibility { "(none), " } else { "" }; let none = if have_none_possibility { "(none), " } else { "" };
db.note(format!("expected values for `{name}` are: {none}`{possibilities}`")); diag.note(format!("expected values for `{name}` are: {none}`{possibilities}`"));
} }
if let Some((value, value_span)) = value { if let Some((value, value_span)) = value {
// Suggest the most probable if we found one // Suggest the most probable if we found one
if let Some(best_match) = find_best_match_for_name(&possibilities, value, None) if let Some(best_match) = find_best_match_for_name(&possibilities, value, None)
{ {
db.span_suggestion( diag.span_suggestion(
value_span, value_span,
"there is a expected value with a similar name", "there is a expected value with a similar name",
format!("\"{best_match}\""), format!("\"{best_match}\""),
@ -371,7 +367,7 @@ pub(super) fn builtin(
); );
} }
} else if let &[first_possibility] = &possibilities[..] { } else if let &[first_possibility] = &possibilities[..] {
db.span_suggestion( diag.span_suggestion(
name_span.shrink_to_hi(), name_span.shrink_to_hi(),
"specify a config value", "specify a config value",
format!(" = \"{first_possibility}\""), format!(" = \"{first_possibility}\""),
@ -379,9 +375,9 @@ pub(super) fn builtin(
); );
} }
} else if have_none_possibility { } else if have_none_possibility {
db.note(format!("no expected value for `{name}`")); diag.note(format!("no expected value for `{name}`"));
if let Some((_value, value_span)) = value { if let Some((_value, value_span)) = value {
db.span_suggestion( diag.span_suggestion(
name_span.shrink_to_hi().to(value_span), name_span.shrink_to_hi().to(value_span),
"remove the value", "remove the value",
"", "",
@ -389,14 +385,14 @@ pub(super) fn builtin(
); );
} }
} else { } else {
db.note(format!("no expected values for `{name}`")); diag.note(format!("no expected values for `{name}`"));
let sp = if let Some((_value, value_span)) = value { let sp = if let Some((_value, value_span)) = value {
name_span.to(value_span) name_span.to(value_span)
} else { } else {
name_span name_span
}; };
db.span_suggestion(sp, "remove the condition", "", Applicability::MaybeIncorrect); diag.span_suggestion(sp, "remove the condition", "", Applicability::MaybeIncorrect);
} }
// We don't want to suggest adding values to well known names // We don't want to suggest adding values to well known names
@ -415,28 +411,30 @@ pub(super) fn builtin(
if is_from_cargo { if is_from_cargo {
if name == sym::feature { if name == sym::feature {
if let Some((value, _value_span)) = value { if let Some((value, _value_span)) = value {
db.help(format!("consider adding `{value}` as a feature in `Cargo.toml`")); diag.help(format!(
"consider adding `{value}` as a feature in `Cargo.toml`"
));
} else { } else {
db.help("consider defining some features in `Cargo.toml`"); diag.help("consider defining some features in `Cargo.toml`");
} }
} else if !is_cfg_a_well_know_name { } else if !is_cfg_a_well_know_name {
db.help(format!("consider using a Cargo feature instead or adding `println!(\"cargo:rustc-check-cfg={inst}\");` to the top of a `build.rs`")); diag.help(format!("consider using a Cargo feature instead or adding `println!(\"cargo:rustc-check-cfg={inst}\");` to the top of a `build.rs`"));
} }
db.note("see <https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#check-cfg> for more information about checking conditional configuration"); diag.note("see <https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#check-cfg> for more information about checking conditional configuration");
} else { } else {
if !is_cfg_a_well_know_name { if !is_cfg_a_well_know_name {
db.help(format!("to expect this configuration use `--check-cfg={inst}`")); diag.help(format!("to expect this configuration use `--check-cfg={inst}`"));
} }
db.note("see <https://doc.rust-lang.org/nightly/unstable-book/compiler-flags/check-cfg.html> for more information about checking conditional configuration"); diag.note("see <https://doc.rust-lang.org/nightly/unstable-book/compiler-flags/check-cfg.html> for more information about checking conditional configuration");
} }
} }
BuiltinLintDiagnostics::DeprecatedWhereclauseLocation(new_span, suggestion) => { BuiltinLintDiagnostics::DeprecatedWhereclauseLocation(new_span, suggestion) => {
db.multipart_suggestion( diag.multipart_suggestion(
"move it to the end of the type declaration", "move it to the end of the type declaration",
vec![(db.span.primary_span().unwrap(), "".to_string()), (new_span, suggestion)], vec![(diag.span.primary_span().unwrap(), "".to_string()), (new_span, suggestion)],
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
db.note( diag.note(
"see issue #89122 <https://github.com/rust-lang/rust/issues/89122> for more information", "see issue #89122 <https://github.com/rust-lang/rust/issues/89122> for more information",
); );
} }
@ -446,8 +444,8 @@ pub(super) fn builtin(
deletion_span, deletion_span,
} => { } => {
debug!(?param_span, ?use_span, ?deletion_span); debug!(?param_span, ?use_span, ?deletion_span);
db.span_label(param_span, "this lifetime..."); diag.span_label(param_span, "this lifetime...");
db.span_label(use_span, "...is used only here"); diag.span_label(use_span, "...is used only here");
if let Some(deletion_span) = deletion_span { if let Some(deletion_span) = deletion_span {
let msg = "elide the single-use lifetime"; let msg = "elide the single-use lifetime";
let (use_span, replace_lt) = if elide { let (use_span, replace_lt) = if elide {
@ -468,7 +466,7 @@ pub(super) fn builtin(
} else { } else {
vec![(deletion_span, String::new()), (use_span, replace_lt)] vec![(deletion_span, String::new()), (use_span, replace_lt)]
}; };
db.multipart_suggestion(msg, suggestions, Applicability::MachineApplicable); diag.multipart_suggestion(msg, suggestions, Applicability::MachineApplicable);
} }
} }
BuiltinLintDiagnostics::SingleUseLifetime { BuiltinLintDiagnostics::SingleUseLifetime {
@ -478,7 +476,7 @@ pub(super) fn builtin(
} => { } => {
debug!(?deletion_span); debug!(?deletion_span);
if let Some(deletion_span) = deletion_span { if let Some(deletion_span) = deletion_span {
db.span_suggestion( diag.span_suggestion(
deletion_span, deletion_span,
"elide the unused lifetime", "elide the unused lifetime",
"", "",
@ -493,7 +491,7 @@ pub(super) fn builtin(
named_arg_name, named_arg_name,
is_formatting_arg, is_formatting_arg,
} => { } => {
db.span_label( diag.span_label(
named_arg_sp, named_arg_sp,
"this named argument is referred to by position in formatting string", "this named argument is referred to by position in formatting string",
); );
@ -501,7 +499,7 @@ pub(super) fn builtin(
let msg = format!( let msg = format!(
"this formatting argument uses named argument `{named_arg_name}` by position" "this formatting argument uses named argument `{named_arg_name}` by position"
); );
db.span_label(positional_arg_for_msg, msg); diag.span_label(positional_arg_for_msg, msg);
} }
if let Some(positional_arg_to_replace) = position_sp_to_replace { if let Some(positional_arg_to_replace) = position_sp_to_replace {
@ -514,7 +512,7 @@ pub(super) fn builtin(
} else { } else {
positional_arg_to_replace positional_arg_to_replace
}; };
db.span_suggestion_verbose( diag.span_suggestion_verbose(
span_to_replace, span_to_replace,
"use the named argument by name to avoid ambiguity", "use the named argument by name to avoid ambiguity",
name, name,
@ -523,22 +521,22 @@ pub(super) fn builtin(
} }
} }
BuiltinLintDiagnostics::ByteSliceInPackedStructWithDerive => { BuiltinLintDiagnostics::ByteSliceInPackedStructWithDerive => {
db.help("consider implementing the trait by hand, or remove the `packed` attribute"); diag.help("consider implementing the trait by hand, or remove the `packed` attribute");
} }
BuiltinLintDiagnostics::UnusedExternCrate { removal_span } => { BuiltinLintDiagnostics::UnusedExternCrate { removal_span } => {
db.span_suggestion(removal_span, "remove it", "", Applicability::MachineApplicable); diag.span_suggestion(removal_span, "remove it", "", Applicability::MachineApplicable);
} }
BuiltinLintDiagnostics::ExternCrateNotIdiomatic { vis_span, ident_span } => { BuiltinLintDiagnostics::ExternCrateNotIdiomatic { vis_span, ident_span } => {
let suggestion_span = vis_span.between(ident_span); let suggestion_span = vis_span.between(ident_span);
db.span_suggestion_verbose( diag.span_suggestion_verbose(
suggestion_span, suggestion_span,
"convert it to a `use`", "convert it to a `use`",
if vis_span.is_empty() { "use " } else { " use " }, if vis_span.is_empty() { "use " } else { " use " },
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
} }
BuiltinLintDiagnostics::AmbiguousGlobImports { diag } => { BuiltinLintDiagnostics::AmbiguousGlobImports { diag: ambiguity } => {
rustc_errors::report_ambiguity_error(db, diag); rustc_errors::report_ambiguity_error(diag, ambiguity);
} }
BuiltinLintDiagnostics::AmbiguousGlobReexports { BuiltinLintDiagnostics::AmbiguousGlobReexports {
name, name,
@ -546,11 +544,11 @@ pub(super) fn builtin(
first_reexport_span, first_reexport_span,
duplicate_reexport_span, duplicate_reexport_span,
} => { } => {
db.span_label( diag.span_label(
first_reexport_span, first_reexport_span,
format!("the name `{name}` in the {namespace} namespace is first re-exported here"), format!("the name `{name}` in the {namespace} namespace is first re-exported here"),
); );
db.span_label( diag.span_label(
duplicate_reexport_span, duplicate_reexport_span,
format!( format!(
"but the name `{name}` in the {namespace} namespace is also re-exported here" "but the name `{name}` in the {namespace} namespace is also re-exported here"
@ -563,11 +561,11 @@ pub(super) fn builtin(
glob_reexport_span, glob_reexport_span,
private_item_span, private_item_span,
} => { } => {
db.span_note(glob_reexport_span, format!("the name `{name}` in the {namespace} namespace is supposed to be publicly re-exported here")); diag.span_note(glob_reexport_span, format!("the name `{name}` in the {namespace} namespace is supposed to be publicly re-exported here"));
db.span_note(private_item_span, "but the private item here shadows it".to_owned()); diag.span_note(private_item_span, "but the private item here shadows it".to_owned());
} }
BuiltinLintDiagnostics::UnusedQualifications { removal_span } => { BuiltinLintDiagnostics::UnusedQualifications { removal_span } => {
db.span_suggestion_verbose( diag.span_suggestion_verbose(
removal_span, removal_span,
"remove the unnecessary path segments", "remove the unnecessary path segments",
"", "",
@ -575,7 +573,7 @@ pub(super) fn builtin(
); );
} }
BuiltinLintDiagnostics::AssociatedConstElidedLifetime { elided, span } => { BuiltinLintDiagnostics::AssociatedConstElidedLifetime { elided, span } => {
db.span_suggestion_verbose( diag.span_suggestion_verbose(
if elided { span.shrink_to_hi() } else { span }, if elided { span.shrink_to_hi() } else { span },
"use the `'static` lifetime", "use the `'static` lifetime",
if elided { "'static " } else { "'static" }, if elided { "'static " } else { "'static" },
@ -583,8 +581,10 @@ pub(super) fn builtin(
); );
} }
BuiltinLintDiagnostics::RedundantImportVisibility { max_vis, span } => { BuiltinLintDiagnostics::RedundantImportVisibility { max_vis, span } => {
db.span_note(span, format!("the most public imported item is `{max_vis}`")); diag.span_note(span, format!("the most public imported item is `{max_vis}`"));
db.help("reduce the glob import's visibility or increase visibility of imported items"); diag.help(
"reduce the glob import's visibility or increase visibility of imported items",
);
} }
} }
} }

View file

@ -1,7 +1,5 @@
use crate::fluent_generated as fluent; use crate::fluent_generated as fluent;
use rustc_errors::{ use rustc_errors::{codes::*, AddToDiagnostic, Diag, EmissionGuarantee, SubdiagnosticMessageOp};
codes::*, AddToDiagnostic, DiagnosticBuilder, EmissionGuarantee, SubdiagnosticMessageOp,
};
use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_session::lint::Level; use rustc_session::lint::Level;
use rustc_span::{Span, Symbol}; use rustc_span::{Span, Symbol};
@ -28,7 +26,7 @@ pub enum OverruledAttributeSub {
impl AddToDiagnostic for OverruledAttributeSub { impl AddToDiagnostic for OverruledAttributeSub {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
match self { match self {

View file

@ -16,7 +16,7 @@ use crate::{
use rustc_ast as ast; use rustc_ast as ast;
use rustc_ast_pretty::pprust; use rustc_ast_pretty::pprust;
use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::fx::FxIndexMap;
use rustc_errors::{DecorateLint, DiagnosticBuilder, DiagnosticMessage, MultiSpan}; use rustc_errors::{DecorateLint, Diag, DiagnosticMessage, MultiSpan};
use rustc_feature::{Features, GateIssue}; use rustc_feature::{Features, GateIssue};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::intravisit::{self, Visitor};
@ -1107,7 +1107,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> {
lint: &'static Lint, lint: &'static Lint,
span: Option<MultiSpan>, span: Option<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>), decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
) { ) {
let (level, src) = self.lint_level(lint); let (level, src) = self.lint_level(lint);
lint_level(self.sess, lint, level, src, span, msg, decorate) lint_level(self.sess, lint, level, src, span, msg, decorate)

View file

@ -5,7 +5,7 @@ use std::num::NonZero;
use crate::errors::RequestedLevel; use crate::errors::RequestedLevel;
use crate::fluent_generated as fluent; use crate::fluent_generated as fluent;
use rustc_errors::{ use rustc_errors::{
codes::*, AddToDiagnostic, Applicability, DecorateLint, DiagnosticBuilder, DiagnosticMessage, codes::*, AddToDiagnostic, Applicability, DecorateLint, Diag, DiagnosticMessage,
DiagnosticStyledString, EmissionGuarantee, SubdiagnosticMessageOp, SuggestionStyle, DiagnosticStyledString, EmissionGuarantee, SubdiagnosticMessageOp, SuggestionStyle,
}; };
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
@ -137,7 +137,7 @@ pub struct BuiltinMissingDebugImpl<'a> {
// Needed for def_path_str // Needed for def_path_str
impl<'a> DecorateLint<'a, ()> for BuiltinMissingDebugImpl<'_> { impl<'a> DecorateLint<'a, ()> for BuiltinMissingDebugImpl<'_> {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::Diag<'a, ()>) {
diag.arg("debug", self.tcx.def_path_str(self.def_id)); diag.arg("debug", self.tcx.def_path_str(self.def_id));
} }
@ -242,7 +242,7 @@ pub struct BuiltinUngatedAsyncFnTrackCaller<'a> {
} }
impl<'a> DecorateLint<'a, ()> for BuiltinUngatedAsyncFnTrackCaller<'_> { impl<'a> DecorateLint<'a, ()> for BuiltinUngatedAsyncFnTrackCaller<'_> {
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, ()>) {
diag.span_label(self.label, fluent::lint_label); diag.span_label(self.label, fluent::lint_label);
rustc_session::parse::add_feature_diagnostics( rustc_session::parse::add_feature_diagnostics(
diag, diag,
@ -273,7 +273,7 @@ pub struct SuggestChangingAssocTypes<'a, 'b> {
impl<'a, 'b> AddToDiagnostic for SuggestChangingAssocTypes<'a, 'b> { impl<'a, 'b> AddToDiagnostic for SuggestChangingAssocTypes<'a, 'b> {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
// Access to associates types should use `<T as Bound>::Assoc`, which does not need a // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
@ -282,7 +282,7 @@ impl<'a, 'b> AddToDiagnostic for SuggestChangingAssocTypes<'a, 'b> {
// We use a HIR visitor to walk the type. // We use a HIR visitor to walk the type.
use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::intravisit::{self, Visitor};
struct WalkAssocTypes<'a, 'b, G: EmissionGuarantee> { struct WalkAssocTypes<'a, 'b, G: EmissionGuarantee> {
err: &'a mut DiagnosticBuilder<'b, G>, err: &'a mut Diag<'b, G>,
} }
impl<'a, 'b, G: EmissionGuarantee> Visitor<'_> for WalkAssocTypes<'a, 'b, G> { impl<'a, 'b, G: EmissionGuarantee> Visitor<'_> for WalkAssocTypes<'a, 'b, G> {
fn visit_qpath( fn visit_qpath(
@ -329,7 +329,7 @@ pub struct BuiltinTypeAliasGenericBoundsSuggestion {
impl AddToDiagnostic for BuiltinTypeAliasGenericBoundsSuggestion { impl AddToDiagnostic for BuiltinTypeAliasGenericBoundsSuggestion {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
diag.multipart_suggestion( diag.multipart_suggestion(
@ -424,7 +424,7 @@ pub struct BuiltinUnpermittedTypeInit<'a> {
} }
impl<'a> DecorateLint<'a, ()> for BuiltinUnpermittedTypeInit<'_> { impl<'a> DecorateLint<'a, ()> for BuiltinUnpermittedTypeInit<'_> {
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, ()>) {
diag.arg("ty", self.ty); diag.arg("ty", self.ty);
diag.span_label(self.label, fluent::lint_builtin_unpermitted_type_init_label); diag.span_label(self.label, fluent::lint_builtin_unpermitted_type_init_label);
if let InhabitedPredicate::True = self.ty.inhabited_predicate(self.tcx) { if let InhabitedPredicate::True = self.ty.inhabited_predicate(self.tcx) {
@ -450,7 +450,7 @@ pub struct BuiltinUnpermittedTypeInitSub {
impl AddToDiagnostic for BuiltinUnpermittedTypeInitSub { impl AddToDiagnostic for BuiltinUnpermittedTypeInitSub {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
let mut err = self.err; let mut err = self.err;
@ -505,7 +505,7 @@ pub struct BuiltinClashingExternSub<'a> {
impl AddToDiagnostic for BuiltinClashingExternSub<'_> { impl AddToDiagnostic for BuiltinClashingExternSub<'_> {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
let mut expected_str = DiagnosticStyledString::new(); let mut expected_str = DiagnosticStyledString::new();
@ -787,7 +787,7 @@ pub struct HiddenUnicodeCodepointsDiagLabels {
impl AddToDiagnostic for HiddenUnicodeCodepointsDiagLabels { impl AddToDiagnostic for HiddenUnicodeCodepointsDiagLabels {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
for (c, span) in self.spans { for (c, span) in self.spans {
@ -805,7 +805,7 @@ pub enum HiddenUnicodeCodepointsDiagSub {
impl AddToDiagnostic for HiddenUnicodeCodepointsDiagSub { impl AddToDiagnostic for HiddenUnicodeCodepointsDiagSub {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
match self { match self {
@ -957,7 +957,7 @@ pub struct NonBindingLetSub {
impl AddToDiagnostic for NonBindingLetSub { impl AddToDiagnostic for NonBindingLetSub {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
let can_suggest_binding = self.drop_fn_start_end.is_some() || !self.is_assign_desugar; let can_suggest_binding = self.drop_fn_start_end.is_some() || !self.is_assign_desugar;
@ -1164,7 +1164,7 @@ pub struct NonFmtPanicUnused {
// Used because of two suggestions based on one Option<Span> // Used because of two suggestions based on one Option<Span>
impl<'a> DecorateLint<'a, ()> for NonFmtPanicUnused { impl<'a> DecorateLint<'a, ()> for NonFmtPanicUnused {
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, ()>) {
diag.arg("count", self.count); diag.arg("count", self.count);
diag.note(fluent::lint_note); diag.note(fluent::lint_note);
if let Some(span) = self.suggestion { if let Some(span) = self.suggestion {
@ -1243,7 +1243,7 @@ pub enum NonSnakeCaseDiagSub {
impl AddToDiagnostic for NonSnakeCaseDiagSub { impl AddToDiagnostic for NonSnakeCaseDiagSub {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
match self { match self {
@ -1402,7 +1402,7 @@ pub struct DropTraitConstraintsDiag<'a> {
// Needed for def_path_str // Needed for def_path_str
impl<'a> DecorateLint<'a, ()> for DropTraitConstraintsDiag<'_> { impl<'a> DecorateLint<'a, ()> for DropTraitConstraintsDiag<'_> {
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, ()>) {
diag.arg("predicate", self.predicate); diag.arg("predicate", self.predicate);
diag.arg("needs_drop", self.tcx.def_path_str(self.def_id)); diag.arg("needs_drop", self.tcx.def_path_str(self.def_id));
} }
@ -1419,7 +1419,7 @@ pub struct DropGlue<'a> {
// Needed for def_path_str // Needed for def_path_str
impl<'a> DecorateLint<'a, ()> for DropGlue<'_> { impl<'a> DecorateLint<'a, ()> for DropGlue<'_> {
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, ()>) {
diag.arg("needs_drop", self.tcx.def_path_str(self.def_id)); diag.arg("needs_drop", self.tcx.def_path_str(self.def_id));
} }
@ -1485,7 +1485,7 @@ pub enum OverflowingBinHexSign {
impl AddToDiagnostic for OverflowingBinHexSign { impl AddToDiagnostic for OverflowingBinHexSign {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
match self { match self {
@ -1694,7 +1694,7 @@ pub struct ImproperCTypes<'a> {
// Used because of the complexity of Option<DiagnosticMessage>, DiagnosticMessage, and Option<Span> // Used because of the complexity of Option<DiagnosticMessage>, DiagnosticMessage, and Option<Span>
impl<'a> DecorateLint<'a, ()> for ImproperCTypes<'_> { impl<'a> DecorateLint<'a, ()> for ImproperCTypes<'_> {
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, ()>) {
diag.arg("ty", self.ty); diag.arg("ty", self.ty);
diag.arg("desc", self.desc); diag.arg("desc", self.desc);
diag.span_label(self.label, fluent::lint_label); diag.span_label(self.label, fluent::lint_label);
@ -1837,7 +1837,7 @@ pub enum UnusedDefSuggestion {
// Needed because of def_path_str // Needed because of def_path_str
impl<'a> DecorateLint<'a, ()> for UnusedDef<'_, '_> { impl<'a> DecorateLint<'a, ()> for UnusedDef<'_, '_> {
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, ()>) {
diag.arg("pre", self.pre); diag.arg("pre", self.pre);
diag.arg("post", self.post); diag.arg("post", self.post);
diag.arg("def", self.cx.tcx.def_path_str(self.def_id)); diag.arg("def", self.cx.tcx.def_path_str(self.def_id));
@ -1920,7 +1920,7 @@ pub struct AsyncFnInTraitDiag {
} }
impl<'a> DecorateLint<'a, ()> for AsyncFnInTraitDiag { impl<'a> DecorateLint<'a, ()> for AsyncFnInTraitDiag {
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, ()>) {
diag.note(fluent::lint_note); diag.note(fluent::lint_note);
if let Some(sugg) = self.sugg { if let Some(sugg) = self.sugg {
diag.multipart_suggestion(fluent::lint_suggestion, sugg, Applicability::MaybeIncorrect); diag.multipart_suggestion(fluent::lint_suggestion, sugg, Applicability::MaybeIncorrect);

View file

@ -683,7 +683,7 @@ pub struct BufferedEarlyLint {
/// `rustc_lint::early::EarlyContextAndPass::check_id`. /// `rustc_lint::early::EarlyContextAndPass::check_id`.
pub lint_id: LintId, pub lint_id: LintId,
/// Customization of the `DiagnosticBuilder<'_>` for the lint. /// Customization of the `Diag<'_>` for the lint.
pub diagnostic: BuiltinLintDiagnostics, pub diagnostic: BuiltinLintDiagnostics,
} }

View file

@ -51,7 +51,7 @@ impl<'a> DiagnosticDerive<'a> {
Some(slug) => { Some(slug) => {
slugs.borrow_mut().push(slug.clone()); slugs.borrow_mut().push(slug.clone());
quote! { quote! {
let mut diag = rustc_errors::DiagnosticBuilder::new( let mut diag = rustc_errors::Diag::new(
dcx, dcx,
level, level,
crate::fluent_generated::#slug crate::fluent_generated::#slug
@ -83,7 +83,7 @@ impl<'a> DiagnosticDerive<'a> {
self, self,
dcx: &'_sess rustc_errors::DiagCtxt, dcx: &'_sess rustc_errors::DiagCtxt,
level: rustc_errors::Level level: rustc_errors::Level
) -> rustc_errors::DiagnosticBuilder<'_sess, G> { ) -> rustc_errors::Diag<'_sess, G> {
#implementation #implementation
} }
} }
@ -160,7 +160,7 @@ impl<'a> LintDiagnosticDerive<'a> {
#[track_caller] #[track_caller]
fn decorate_lint<'__b>( fn decorate_lint<'__b>(
self, self,
diag: &'__b mut rustc_errors::DiagnosticBuilder<'__a, ()> diag: &'__b mut rustc_errors::Diag<'__a, ()>
) { ) {
#implementation; #implementation;
} }

View file

@ -14,7 +14,7 @@ impl DiagnosticDeriveError {
match self { match self {
DiagnosticDeriveError::SynError(e) => e.to_compile_error(), DiagnosticDeriveError::SynError(e) => e.to_compile_error(),
DiagnosticDeriveError::ErrorHandled => { DiagnosticDeriveError::ErrorHandled => {
// Return ! to avoid having to create a blank DiagnosticBuilder to return when an // Return ! to avoid having to create a blank Diag to return when an
// error has already been emitted to the compiler. // error has already been emitted to the compiler.
quote! { quote! {
{ unreachable!(); } { unreachable!(); }

View file

@ -89,7 +89,7 @@ impl SubdiagnosticDeriveBuilder {
gen impl rustc_errors::AddToDiagnostic for @Self { gen impl rustc_errors::AddToDiagnostic for @Self {
fn add_to_diagnostic_with<__G, __F>( fn add_to_diagnostic_with<__G, __F>(
self, self,
#diag: &mut rustc_errors::DiagnosticBuilder<'_, __G>, #diag: &mut rustc_errors::Diag<'_, __G>,
#f: __F #f: __F
) where ) where
__G: rustc_errors::EmissionGuarantee, __G: rustc_errors::EmissionGuarantee,
@ -108,7 +108,7 @@ impl SubdiagnosticDeriveBuilder {
/// only to be able to destructure and split `self.builder` and the `self.structure` up to avoid a /// only to be able to destructure and split `self.builder` and the `self.structure` up to avoid a
/// double mut borrow later on. /// double mut borrow later on.
struct SubdiagnosticDeriveVariantBuilder<'parent, 'a> { struct SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
/// The identifier to use for the generated `DiagnosticBuilder` instance. /// The identifier to use for the generated `Diag` instance.
parent: &'parent SubdiagnosticDeriveBuilder, parent: &'parent SubdiagnosticDeriveBuilder,
/// Info for the current variant (or the type if not an enum). /// Info for the current variant (or the type if not an enum).

View file

@ -3,9 +3,7 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use rustc_errors::{ use rustc_errors::{codes::*, Diag, DiagCtxt, EmissionGuarantee, IntoDiagnostic, Level};
codes::*, DiagCtxt, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic, Level,
};
use rustc_macros::Diagnostic; use rustc_macros::Diagnostic;
use rustc_session::config; use rustc_session::config;
use rustc_span::{sym, Span, Symbol}; use rustc_span::{sym, Span, Symbol};
@ -498,8 +496,8 @@ pub(crate) struct MultipleCandidates {
} }
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for MultipleCandidates { impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for MultipleCandidates {
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::metadata_multiple_candidates); let mut diag = Diag::new(dcx, level, fluent::metadata_multiple_candidates);
diag.arg("crate_name", self.crate_name); diag.arg("crate_name", self.crate_name);
diag.arg("flavor", self.flavor); diag.arg("flavor", self.flavor);
diag.code(E0464); diag.code(E0464);
@ -597,8 +595,8 @@ pub struct InvalidMetadataFiles {
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for InvalidMetadataFiles { impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for InvalidMetadataFiles {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::metadata_invalid_meta_files); let mut diag = Diag::new(dcx, level, fluent::metadata_invalid_meta_files);
diag.arg("crate_name", self.crate_name); diag.arg("crate_name", self.crate_name);
diag.arg("add_info", self.add_info); diag.arg("add_info", self.add_info);
diag.code(E0786); diag.code(E0786);
@ -626,8 +624,8 @@ pub struct CannotFindCrate {
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for CannotFindCrate { impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for CannotFindCrate {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::metadata_cannot_find_crate); let mut diag = Diag::new(dcx, level, fluent::metadata_cannot_find_crate);
diag.arg("crate_name", self.crate_name); diag.arg("crate_name", self.crate_name);
diag.arg("current_crate", self.current_crate); diag.arg("current_crate", self.current_crate);
diag.arg("add_info", self.add_info); diag.arg("add_info", self.add_info);

View file

@ -2,7 +2,7 @@ use std::cmp;
use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::sorted_map::SortedMap;
use rustc_errors::{DiagnosticBuilder, DiagnosticMessage, MultiSpan}; use rustc_errors::{Diag, DiagnosticMessage, MultiSpan};
use rustc_hir::{HirId, ItemLocalId}; use rustc_hir::{HirId, ItemLocalId};
use rustc_session::lint::{ use rustc_session::lint::{
builtin::{self, FORBIDDEN_LINT_GROUPS}, builtin::{self, FORBIDDEN_LINT_GROUPS},
@ -204,7 +204,7 @@ pub fn explain_lint_level_source(
lint: &'static Lint, lint: &'static Lint,
level: Level, level: Level,
src: LintLevelSource, src: LintLevelSource,
err: &mut DiagnosticBuilder<'_, ()>, err: &mut Diag<'_, ()>,
) { ) {
let name = lint.name_lower(); let name = lint.name_lower();
if let Level::Allow = level { if let Level::Allow = level {
@ -260,8 +260,7 @@ pub fn explain_lint_level_source(
/// ///
/// ## `decorate` /// ## `decorate`
/// ///
/// It is not intended to call `emit`/`cancel` on the `DiagnosticBuilder` passed /// It is not intended to call `emit`/`cancel` on the `Diag` passed in the `decorate` callback.
/// in the `decorate` callback.
#[track_caller] #[track_caller]
pub fn lint_level( pub fn lint_level(
sess: &Session, sess: &Session,
@ -270,7 +269,7 @@ pub fn lint_level(
src: LintLevelSource, src: LintLevelSource,
span: Option<MultiSpan>, span: Option<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>), decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
) { ) {
// Avoid codegen bloat from monomorphization by immediately doing dyn dispatch of `decorate` to // Avoid codegen bloat from monomorphization by immediately doing dyn dispatch of `decorate` to
// the "real" work. // the "real" work.
@ -282,7 +281,7 @@ pub fn lint_level(
src: LintLevelSource, src: LintLevelSource,
span: Option<MultiSpan>, span: Option<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: Box<dyn '_ + for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>)>, decorate: Box<dyn '_ + for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>)>,
) { ) {
// Check for future incompatibility lints and issue a stronger warning. // Check for future incompatibility lints and issue a stronger warning.
let future_incompatible = lint.future_incompatible; let future_incompatible = lint.future_incompatible;
@ -314,7 +313,7 @@ pub fn lint_level(
// //
// We can also not mark the lint expectation as fulfilled here right away, as it // We can also not mark the lint expectation as fulfilled here right away, as it
// can still be cancelled in the decorate function. All of this means that we simply // can still be cancelled in the decorate function. All of this means that we simply
// create a `DiagnosticBuilder` and continue as we would for warnings. // create a `Diag` and continue as we would for warnings.
rustc_errors::Level::Expect(expect_id) rustc_errors::Level::Expect(expect_id)
} }
Level::ForceWarn(Some(expect_id)) => rustc_errors::Level::ForceWarning(Some(expect_id)), Level::ForceWarn(Some(expect_id)) => rustc_errors::Level::ForceWarning(Some(expect_id)),
@ -322,7 +321,7 @@ pub fn lint_level(
Level::Warn => rustc_errors::Level::Warning, Level::Warn => rustc_errors::Level::Warning,
Level::Deny | Level::Forbid => rustc_errors::Level::Error, Level::Deny | Level::Forbid => rustc_errors::Level::Error,
}; };
let mut err = DiagnosticBuilder::new(sess.dcx(), err_level, ""); let mut err = Diag::new(sess.dcx(), err_level, "");
if let Some(span) = span { if let Some(span) = span {
err.span(span); err.span(span);
} }

View file

@ -9,7 +9,7 @@ use rustc_attr::{
self as attr, ConstStability, DefaultBodyStability, DeprecatedSince, Deprecation, Stability, self as attr, ConstStability, DefaultBodyStability, DeprecatedSince, Deprecation, Stability,
}; };
use rustc_data_structures::unord::UnordMap; use rustc_data_structures::unord::UnordMap;
use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_errors::{Applicability, Diag};
use rustc_feature::GateIssue; use rustc_feature::GateIssue;
use rustc_hir::def::DefKind; use rustc_hir::def::DefKind;
use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdMap}; use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdMap};
@ -125,7 +125,7 @@ pub fn report_unstable(
} }
pub fn deprecation_suggestion( pub fn deprecation_suggestion(
diag: &mut DiagnosticBuilder<'_, ()>, diag: &mut Diag<'_, ()>,
kind: &str, kind: &str,
suggestion: Option<Symbol>, suggestion: Option<Symbol>,
span: Span, span: Span,

View file

@ -16,7 +16,7 @@ use crate::ty::GenericArgsRef;
use crate::ty::{self, AdtKind, Ty}; use crate::ty::{self, AdtKind, Ty};
use rustc_data_structures::sync::Lrc; use rustc_data_structures::sync::Lrc;
use rustc_errors::{Applicability, DiagnosticBuilder, EmissionGuarantee}; use rustc_errors::{Applicability, Diag, EmissionGuarantee};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_span::def_id::{LocalDefId, CRATE_DEF_ID}; use rustc_span::def_id::{LocalDefId, CRATE_DEF_ID};
@ -908,7 +908,7 @@ pub enum ObjectSafetyViolationSolution {
} }
impl ObjectSafetyViolationSolution { impl ObjectSafetyViolationSolution {
pub fn add_to<G: EmissionGuarantee>(self, err: &mut DiagnosticBuilder<'_, G>) { pub fn add_to<G: EmissionGuarantee>(self, err: &mut Diag<'_, G>) {
match self { match self {
ObjectSafetyViolationSolution::None => {} ObjectSafetyViolationSolution::None => {}
ObjectSafetyViolationSolution::AddSelfOrMakeSized { ObjectSafetyViolationSolution::AddSelfOrMakeSized {

View file

@ -43,9 +43,7 @@ use rustc_data_structures::sync::{self, FreezeReadGuard, Lock, WorkerLocal};
#[cfg(parallel_compiler)] #[cfg(parallel_compiler)]
use rustc_data_structures::sync::{DynSend, DynSync}; use rustc_data_structures::sync::{DynSend, DynSync};
use rustc_data_structures::unord::UnordSet; use rustc_data_structures::unord::UnordSet;
use rustc_errors::{ use rustc_errors::{DecorateLint, Diag, DiagCtxt, DiagnosticMessage, ErrorGuaranteed, MultiSpan};
DecorateLint, DiagCtxt, DiagnosticBuilder, DiagnosticMessage, ErrorGuaranteed, MultiSpan,
};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::DefKind; use rustc_hir::def::DefKind;
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
@ -2117,7 +2115,7 @@ impl<'tcx> TyCtxt<'tcx> {
hir_id: HirId, hir_id: HirId,
span: impl Into<MultiSpan>, span: impl Into<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>), decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
) { ) {
let (level, src) = self.lint_level_at_node(lint, hir_id); let (level, src) = self.lint_level_at_node(lint, hir_id);
lint_level(self.sess, lint, level, src, Some(span.into()), msg, decorate); lint_level(self.sess, lint, level, src, Some(span.into()), msg, decorate);
@ -2147,7 +2145,7 @@ impl<'tcx> TyCtxt<'tcx> {
lint: &'static Lint, lint: &'static Lint,
id: HirId, id: HirId,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>), decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
) { ) {
let (level, src) = self.lint_level_at_node(lint, id); let (level, src) = self.lint_level_at_node(lint, id);
lint_level(self.sess, lint, level, src, None, msg, decorate); lint_level(self.sess, lint, level, src, None, msg, decorate);

View file

@ -11,7 +11,7 @@ use crate::ty::{
}; };
use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::fx::FxHashMap;
use rustc_errors::{Applicability, DiagnosticArgValue, DiagnosticBuilder, IntoDiagnosticArg}; use rustc_errors::{Applicability, Diag, DiagnosticArgValue, IntoDiagnosticArg};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::DefKind; use rustc_hir::def::DefKind;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
@ -111,7 +111,7 @@ where
pub fn suggest_arbitrary_trait_bound<'tcx>( pub fn suggest_arbitrary_trait_bound<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
generics: &hir::Generics<'_>, generics: &hir::Generics<'_>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
trait_pred: PolyTraitPredicate<'tcx>, trait_pred: PolyTraitPredicate<'tcx>,
associated_ty: Option<(&'static str, Ty<'tcx>)>, associated_ty: Option<(&'static str, Ty<'tcx>)>,
) -> bool { ) -> bool {
@ -216,7 +216,7 @@ fn suggest_changing_unsized_bound(
pub fn suggest_constraining_type_param( pub fn suggest_constraining_type_param(
tcx: TyCtxt<'_>, tcx: TyCtxt<'_>,
generics: &hir::Generics<'_>, generics: &hir::Generics<'_>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
param_name: &str, param_name: &str,
constraint: &str, constraint: &str,
def_id: Option<DefId>, def_id: Option<DefId>,
@ -235,7 +235,7 @@ pub fn suggest_constraining_type_param(
pub fn suggest_constraining_type_params<'a>( pub fn suggest_constraining_type_params<'a>(
tcx: TyCtxt<'_>, tcx: TyCtxt<'_>,
generics: &hir::Generics<'_>, generics: &hir::Generics<'_>,
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
param_names_and_constraints: impl Iterator<Item = (&'a str, &'a str, Option<DefId>)>, param_names_and_constraints: impl Iterator<Item = (&'a str, &'a str, Option<DefId>)>,
span_to_replace: Option<Span>, span_to_replace: Option<Span>,
) -> bool { ) -> bool {

View file

@ -5,8 +5,7 @@ use crate::ty::normalize_erasing_regions::NormalizationError;
use crate::ty::{self, ConstKind, Ty, TyCtxt, TypeVisitableExt}; use crate::ty::{self, ConstKind, Ty, TyCtxt, TypeVisitableExt};
use rustc_error_messages::DiagnosticMessage; use rustc_error_messages::DiagnosticMessage;
use rustc_errors::{ use rustc_errors::{
DiagCtxt, DiagnosticArgValue, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic, Diag, DiagCtxt, DiagnosticArgValue, EmissionGuarantee, IntoDiagnostic, IntoDiagnosticArg, Level,
IntoDiagnosticArg, Level,
}; };
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
@ -1262,7 +1261,7 @@ pub enum FnAbiError<'tcx> {
} }
impl<'a, 'b, G: EmissionGuarantee> IntoDiagnostic<'a, G> for FnAbiError<'b> { impl<'a, 'b, G: EmissionGuarantee> IntoDiagnostic<'a, G> for FnAbiError<'b> {
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
match self { match self {
Self::Layout(e) => e.into_diagnostic().into_diagnostic(dcx, level), Self::Layout(e) => e.into_diagnostic().into_diagnostic(dcx, level),
Self::AdjustForForeignAbi(call::AdjustForForeignAbiError::Unsupported { Self::AdjustForForeignAbi(call::AdjustForForeignAbiError::Unsupported {

View file

@ -39,7 +39,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::steal::Steal; use rustc_data_structures::steal::Steal;
use rustc_data_structures::tagged_ptr::CopyTaggedPtr; use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
use rustc_data_structures::unord::UnordMap; use rustc_data_structures::unord::UnordMap;
use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed, StashKey}; use rustc_errors::{Diag, ErrorGuaranteed, StashKey};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res}; use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap, LocalDefIdSet}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap, LocalDefIdSet};
@ -845,7 +845,7 @@ impl<'tcx> OpaqueHiddenType<'tcx> {
other: &Self, other: &Self,
opaque_def_id: LocalDefId, opaque_def_id: LocalDefId,
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
) -> Result<DiagnosticBuilder<'tcx>, ErrorGuaranteed> { ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
if let Some(diag) = tcx if let Some(diag) = tcx
.sess .sess
.dcx() .dcx()

View file

@ -1,8 +1,8 @@
use crate::fluent_generated as fluent; use crate::fluent_generated as fluent;
use rustc_errors::DiagnosticArgValue; use rustc_errors::DiagnosticArgValue;
use rustc_errors::{ use rustc_errors::{
codes::*, AddToDiagnostic, Applicability, DiagCtxt, DiagnosticBuilder, EmissionGuarantee, codes::*, AddToDiagnostic, Applicability, Diag, DiagCtxt, EmissionGuarantee, IntoDiagnostic,
IntoDiagnostic, Level, MultiSpan, SubdiagnosticMessageOp, Level, MultiSpan, SubdiagnosticMessageOp,
}; };
use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
use rustc_middle::ty::{self, Ty}; use rustc_middle::ty::{self, Ty};
@ -422,7 +422,7 @@ pub struct UnsafeNotInheritedLintNote {
impl AddToDiagnostic for UnsafeNotInheritedLintNote { impl AddToDiagnostic for UnsafeNotInheritedLintNote {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
diag.span_note(self.signature_span, fluent::mir_build_unsafe_fn_safe_body); diag.span_note(self.signature_span, fluent::mir_build_unsafe_fn_safe_body);
@ -464,12 +464,9 @@ pub(crate) struct NonExhaustivePatternsTypeNotEmpty<'p, 'tcx, 'm> {
impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G>
for NonExhaustivePatternsTypeNotEmpty<'_, '_, '_> for NonExhaustivePatternsTypeNotEmpty<'_, '_, '_>
{ {
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'_, G> {
let mut diag = DiagnosticBuilder::new( let mut diag =
dcx, Diag::new(dcx, level, fluent::mir_build_non_exhaustive_patterns_type_not_empty);
level,
fluent::mir_build_non_exhaustive_patterns_type_not_empty,
);
diag.span(self.span); diag.span(self.span);
diag.code(E0004); diag.code(E0004);
let peeled_ty = self.ty.peel_refs(); let peeled_ty = self.ty.peel_refs();
@ -873,7 +870,7 @@ pub struct Variant {
impl<'tcx> AddToDiagnostic for AdtDefinedHere<'tcx> { impl<'tcx> AddToDiagnostic for AdtDefinedHere<'tcx> {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_f: F, _f: F,
) { ) {
diag.arg("ty", self.ty); diag.arg("ty", self.ty);

View file

@ -11,7 +11,7 @@ use rustc_ast::Mutability;
use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::fx::FxIndexSet;
use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_errors::{ use rustc_errors::{
codes::*, struct_span_code_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, codes::*, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan,
}; };
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::*; use rustc_hir::def::*;
@ -64,7 +64,7 @@ pub(crate) fn check_match(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), Err
visitor.error visitor.error
} }
fn create_e0004(sess: &Session, sp: Span, error_message: String) -> DiagnosticBuilder<'_> { fn create_e0004(sess: &Session, sp: Span, error_message: String) -> Diag<'_> {
struct_span_code_err!(sess.dcx(), sp, E0004, "{}", &error_message) struct_span_code_err!(sess.dcx(), sp, E0004, "{}", &error_message)
} }

View file

@ -1,8 +1,8 @@
use std::borrow::Cow; use std::borrow::Cow;
use rustc_errors::{ use rustc_errors::{
codes::*, Applicability, DecorateLint, DiagCtxt, DiagnosticArgValue, DiagnosticBuilder, codes::*, Applicability, DecorateLint, Diag, DiagCtxt, DiagnosticArgValue, DiagnosticMessage,
DiagnosticMessage, EmissionGuarantee, IntoDiagnostic, Level, EmissionGuarantee, IntoDiagnostic, Level,
}; };
use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
use rustc_middle::mir::{AssertKind, UnsafetyViolationDetails}; use rustc_middle::mir::{AssertKind, UnsafetyViolationDetails};
@ -64,8 +64,8 @@ pub(crate) struct RequiresUnsafe {
// but this would result in a lot of duplication. // but this would result in a lot of duplication.
impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for RequiresUnsafe { impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for RequiresUnsafe {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::mir_transform_requires_unsafe); let mut diag = Diag::new(dcx, level, fluent::mir_transform_requires_unsafe);
diag.code(E0133); diag.code(E0133);
diag.span(self.span); diag.span(self.span);
diag.span_label(self.span, self.details.label()); diag.span_label(self.span, self.details.label());
@ -90,7 +90,7 @@ impl RequiresUnsafeDetail {
// FIXME: make this translatable // FIXME: make this translatable
#[allow(rustc::diagnostic_outside_of_impl)] #[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::untranslatable_diagnostic)]
fn add_subdiagnostics<G: EmissionGuarantee>(&self, diag: &mut DiagnosticBuilder<'_, G>) { fn add_subdiagnostics<G: EmissionGuarantee>(&self, diag: &mut Diag<'_, G>) {
use UnsafetyViolationDetails::*; use UnsafetyViolationDetails::*;
match self.violation { match self.violation {
CallToUnsafeFunction => { CallToUnsafeFunction => {
@ -183,7 +183,7 @@ pub(crate) struct UnsafeOpInUnsafeFn {
impl<'a> DecorateLint<'a, ()> for UnsafeOpInUnsafeFn { impl<'a> DecorateLint<'a, ()> for UnsafeOpInUnsafeFn {
#[track_caller] #[track_caller]
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, ()>) {
let desc = diag.dcx.eagerly_translate_to_string(self.details.label(), [].into_iter()); let desc = diag.dcx.eagerly_translate_to_string(self.details.label(), [].into_iter());
diag.arg("details", desc); diag.arg("details", desc);
diag.span_label(self.details.span, self.details.label()); diag.span_label(self.details.span, self.details.label());
@ -216,7 +216,7 @@ pub(crate) enum AssertLintKind {
} }
impl<'a, P: std::fmt::Debug> DecorateLint<'a, ()> for AssertLint<P> { impl<'a, P: std::fmt::Debug> DecorateLint<'a, ()> for AssertLint<P> {
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, ()>) {
let message = self.assert_kind.diagnostic_message(); let message = self.assert_kind.diagnostic_message();
self.assert_kind.add_args(&mut |name, value| { self.assert_kind.add_args(&mut |name, value| {
diag.arg(name, value); diag.arg(name, value);
@ -270,7 +270,7 @@ pub(crate) struct MustNotSupend<'tcx, 'a> {
// Needed for def_path_str // Needed for def_path_str
impl<'a> DecorateLint<'a, ()> for MustNotSupend<'_, '_> { impl<'a> DecorateLint<'a, ()> for MustNotSupend<'_, '_> {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::Diag<'a, ()>) {
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(diag.dcx, reason);

View file

@ -1,7 +1,7 @@
use std::path::PathBuf; use std::path::PathBuf;
use crate::fluent_generated as fluent; use crate::fluent_generated as fluent;
use rustc_errors::{DiagCtxt, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic, Level}; use rustc_errors::{Diag, DiagCtxt, EmissionGuarantee, IntoDiagnostic, Level};
use rustc_macros::{Diagnostic, LintDiagnostic}; use rustc_macros::{Diagnostic, LintDiagnostic};
use rustc_span::{Span, Symbol}; use rustc_span::{Span, Symbol};
@ -48,9 +48,8 @@ pub struct UnusedGenericParamsHint {
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for UnusedGenericParamsHint { impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for UnusedGenericParamsHint {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
let mut diag = let mut diag = Diag::new(dcx, level, fluent::monomorphize_unused_generic_params);
DiagnosticBuilder::new(dcx, level, fluent::monomorphize_unused_generic_params);
diag.span(self.span); diag.span(self.span);
for (span, name) in self.param_spans.into_iter().zip(self.param_names) { for (span, name) in self.param_spans.into_iter().zip(self.param_names) {
// FIXME: I can figure out how to do a label with a fluent string with a fixed message, // FIXME: I can figure out how to do a label with a fluent string with a fixed message,

View file

@ -3,8 +3,8 @@ use std::borrow::Cow;
use rustc_ast::token::Token; use rustc_ast::token::Token;
use rustc_ast::{Path, Visibility}; use rustc_ast::{Path, Visibility};
use rustc_errors::{ use rustc_errors::{
codes::*, AddToDiagnostic, Applicability, DiagCtxt, DiagnosticBuilder, EmissionGuarantee, codes::*, AddToDiagnostic, Applicability, Diag, DiagCtxt, EmissionGuarantee, IntoDiagnostic,
IntoDiagnostic, Level, SubdiagnosticMessageOp, Level, SubdiagnosticMessageOp,
}; };
use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_session::errors::ExprParenthesesNeeded; use rustc_session::errors::ExprParenthesesNeeded;
@ -1075,10 +1075,10 @@ pub(crate) struct ExpectedIdentifier {
impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for ExpectedIdentifier { impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for ExpectedIdentifier {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
let token_descr = TokenDescription::from_token(&self.token); let token_descr = TokenDescription::from_token(&self.token);
let mut diag = DiagnosticBuilder::new( let mut diag = Diag::new(
dcx, dcx,
level, level,
match token_descr { match token_descr {
@ -1135,10 +1135,10 @@ pub(crate) struct ExpectedSemi {
impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for ExpectedSemi { impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for ExpectedSemi {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
let token_descr = TokenDescription::from_token(&self.token); let token_descr = TokenDescription::from_token(&self.token);
let mut diag = DiagnosticBuilder::new( let mut diag = Diag::new(
dcx, dcx,
level, level,
match token_descr { match token_descr {
@ -1477,7 +1477,7 @@ pub(crate) struct FnTraitMissingParen {
impl AddToDiagnostic for FnTraitMissingParen { impl AddToDiagnostic for FnTraitMissingParen {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self, self,
diag: &mut DiagnosticBuilder<'_, G>, diag: &mut Diag<'_, G>,
_: F, _: F,
) { ) {
diag.span_label(self.span, crate::fluent_generated::parse_fn_trait_missing_paren); diag.span_label(self.span, crate::fluent_generated::parse_fn_trait_missing_paren);

View file

@ -1,6 +1,6 @@
use super::UnmatchedDelim; use super::UnmatchedDelim;
use rustc_ast::token::Delimiter; use rustc_ast::token::Delimiter;
use rustc_errors::DiagnosticBuilder; use rustc_errors::Diag;
use rustc_span::source_map::SourceMap; use rustc_span::source_map::SourceMap;
use rustc_span::Span; use rustc_span::Span;
@ -30,10 +30,7 @@ pub fn same_indentation_level(sm: &SourceMap, open_sp: Span, close_sp: Span) ->
// When we get a `)` or `]` for `{`, we should emit help message here // When we get a `)` or `]` for `{`, we should emit help message here
// it's more friendly compared to report `unmatched error` in later phase // it's more friendly compared to report `unmatched error` in later phase
pub fn report_missing_open_delim( pub fn report_missing_open_delim(err: &mut Diag<'_>, unmatched_delims: &[UnmatchedDelim]) -> bool {
err: &mut DiagnosticBuilder<'_>,
unmatched_delims: &[UnmatchedDelim],
) -> bool {
let mut reported_missing_open = false; let mut reported_missing_open = false;
for unmatch_brace in unmatched_delims.iter() { for unmatch_brace in unmatched_delims.iter() {
if let Some(delim) = unmatch_brace.found_delim if let Some(delim) = unmatch_brace.found_delim
@ -55,7 +52,7 @@ pub fn report_missing_open_delim(
} }
pub fn report_suspicious_mismatch_block( pub fn report_suspicious_mismatch_block(
err: &mut DiagnosticBuilder<'_>, err: &mut Diag<'_>,
diag_info: &TokenTreeDiagInfo, diag_info: &TokenTreeDiagInfo,
sm: &SourceMap, sm: &SourceMap,
delim: Delimiter, delim: Delimiter,

Some files were not shown because too many files have changed in this diff Show more