diff options
Diffstat (limited to 'compiler/rustc_errors/src')
| -rw-r--r-- | compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs | 10 | ||||
| -rw-r--r-- | compiler/rustc_errors/src/diagnostic.rs | 289 | ||||
| -rw-r--r-- | compiler/rustc_errors/src/diagnostic_impls.rs | 159 | ||||
| -rw-r--r-- | compiler/rustc_errors/src/emitter.rs | 40 | ||||
| -rw-r--r-- | compiler/rustc_errors/src/json.rs | 16 | ||||
| -rw-r--r-- | compiler/rustc_errors/src/lib.rs | 226 | ||||
| -rw-r--r-- | compiler/rustc_errors/src/translation.rs | 6 |
7 files changed, 368 insertions, 378 deletions
diff --git a/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs b/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs index 52b5a7eff48..e6668769b95 100644 --- a/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs +++ b/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs @@ -9,8 +9,8 @@ use crate::emitter::FileWithAnnotatedLines; use crate::snippet::Line; use crate::translation::{to_fluent_args, Translate}; use crate::{ - CodeSuggestion, Diagnostic, DiagnosticMessage, Emitter, ErrCode, FluentBundle, - LazyFallbackBundle, Level, MultiSpan, Style, SubDiagnostic, + CodeSuggestion, DiagInner, DiagnosticMessage, Emitter, ErrCode, FluentBundle, + LazyFallbackBundle, Level, MultiSpan, Style, Subdiag, }; use annotate_snippets::{Annotation, AnnotationType, Renderer, Slice, Snippet, SourceAnnotation}; use rustc_data_structures::sync::Lrc; @@ -44,7 +44,7 @@ impl Translate for AnnotateSnippetEmitter { impl Emitter for AnnotateSnippetEmitter { /// The entry point for the diagnostics generation - fn emit_diagnostic(&mut self, mut diag: Diagnostic) { + fn emit_diagnostic(&mut self, mut diag: DiagInner) { let fluent_args = to_fluent_args(diag.args.iter()); let mut suggestions = diag.suggestions.unwrap_or(vec![]); @@ -82,7 +82,7 @@ fn source_string(file: Lrc<SourceFile>, line: &Line) -> String { file.get_line(line.line_index - 1).map(|a| a.to_string()).unwrap_or_default() } -/// Maps `Diagnostic::Level` to `snippet::AnnotationType` +/// Maps `diagnostic::Level` to `snippet::AnnotationType` fn annotation_type_for_level(level: Level) -> AnnotationType { match level { Level::Bug | Level::Fatal | Level::Error | Level::DelayedBug => AnnotationType::Error, @@ -129,7 +129,7 @@ impl AnnotateSnippetEmitter { args: &FluentArgs<'_>, code: &Option<ErrCode>, msp: &MultiSpan, - _children: &[SubDiagnostic], + _children: &[Subdiag], _suggestions: &[CodeSuggestion], ) { let message = self.translate_messages(messages, args); diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index 65c49a6085c..0cf519d2029 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -18,23 +18,23 @@ use std::ops::{Deref, DerefMut}; use std::panic; use std::thread::panicking; -/// Error type for `Diagnostic`'s `suggestions` field, indicating that -/// `.disable_suggestions()` was called on the `Diagnostic`. +/// Error type for `DiagInner`'s `suggestions` field, indicating that +/// `.disable_suggestions()` was called on the `DiagInner`. #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)] pub struct SuggestionsDisabled; /// Simplified version of `FluentArg` that can implement `Encodable` and `Decodable`. Collection of -/// `DiagnosticArg` are converted to `FluentArgs` (consuming the collection) at the start of -/// diagnostic emission. -pub type DiagnosticArg<'iter> = (&'iter DiagnosticArgName, &'iter DiagnosticArgValue); +/// `DiagArg` are converted to `FluentArgs` (consuming the collection) at the start of diagnostic +/// emission. +pub type DiagArg<'iter> = (&'iter DiagArgName, &'iter DiagArgValue); /// Name of a diagnostic argument. -pub type DiagnosticArgName = Cow<'static, str>; +pub type DiagArgName = Cow<'static, str>; /// Simplified version of `FluentValue` that can implement `Encodable` and `Decodable`. Converted /// to a `FluentValue` by the emitter to be used in diagnostic translation. #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)] -pub enum DiagnosticArgValue { +pub enum DiagArgValue { Str(Cow<'static, str>), // This gets converted to a `FluentNumber`, which is an `f64`. An `i32` // safely fits in an `f64`. Any integers bigger than that will be converted @@ -43,31 +43,31 @@ pub enum DiagnosticArgValue { StrListSepByAnd(Vec<Cow<'static, str>>), } -pub type DiagnosticArgMap = FxIndexMap<DiagnosticArgName, DiagnosticArgValue>; +pub type DiagArgMap = FxIndexMap<DiagArgName, DiagArgValue>; -/// Trait for types that `DiagnosticBuilder::emit` can return as a "guarantee" -/// (or "proof") token that the emission happened. +/// Trait for types that `Diag::emit` can return as a "guarantee" (or "proof") +/// token that the emission happened. pub trait EmissionGuarantee: Sized { /// This exists so that bugs and fatal errors can both result in `!` (an /// abort) when emitted, but have different aborting behaviour. type EmitResult = Self; - /// Implementation of `DiagnosticBuilder::emit`, fully controlled by each - /// `impl` of `EmissionGuarantee`, to make it impossible to create a value - /// of `Self::EmitResult` without actually performing the emission. + /// Implementation of `Diag::emit`, fully controlled by each `impl` of + /// `EmissionGuarantee`, to make it impossible to create a value of + /// `Self::EmitResult` without actually performing the emission. #[track_caller] - fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult; + fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult; } impl EmissionGuarantee for ErrorGuaranteed { - fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult { - db.emit_producing_error_guaranteed() + fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult { + diag.emit_producing_error_guaranteed() } } impl EmissionGuarantee for () { - fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult { - db.emit_producing_nothing(); + fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult { + diag.emit_producing_nothing(); } } @@ -79,8 +79,8 @@ pub struct BugAbort; impl EmissionGuarantee for BugAbort { type EmitResult = !; - fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult { - db.emit_producing_nothing(); + fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult { + diag.emit_producing_nothing(); panic::panic_any(ExplicitBug); } } @@ -93,26 +93,45 @@ pub struct FatalAbort; impl EmissionGuarantee for FatalAbort { type EmitResult = !; - fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult { - db.emit_producing_nothing(); + fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult { + diag.emit_producing_nothing(); crate::FatalError.raise() } } impl EmissionGuarantee for rustc_span::fatal_error::FatalError { - fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult { - db.emit_producing_nothing(); + fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult { + diag.emit_producing_nothing(); rustc_span::fatal_error::FatalError } } /// Trait implemented by error types. This is rarely implemented manually. Instead, use /// `#[derive(Diagnostic)]` -- see [rustc_macros::Diagnostic]. +/// +/// When implemented manually, it should be generic over the emission +/// guarantee, i.e.: +/// ```ignore (fragment) +/// impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for Foo { ... } +/// ``` +/// rather than being specific: +/// ```ignore (fragment) +/// impl<'a> IntoDiagnostic<'a> for Bar { ... } // the default type param is `ErrorGuaranteed` +/// impl<'a> IntoDiagnostic<'a, ()> for Baz { ... } +/// ``` +/// There are two reasons for this. +/// - A diagnostic like `Foo` *could* be emitted at any level -- `level` is +/// passed in to `into_diagnostic` from outside. Even if in practice it is +/// always emitted at a single level, we let the diagnostic creation/emission +/// site determine the level (by using `create_err`, `emit_warn`, etc.) +/// rather than the `IntoDiagnostic` impl. +/// - Derived impls are always generic, and it's good for the hand-written +/// impls to be consistent with them. #[rustc_diagnostic_item = "IntoDiagnostic"] pub trait IntoDiagnostic<'a, G: EmissionGuarantee = ErrorGuaranteed> { /// Write out as a diagnostic out of `DiagCtxt`. #[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> @@ -120,31 +139,31 @@ where T: IntoDiagnostic<'a, G>, 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) } } -/// Converts a value of a type into a `DiagnosticArg` (typically a field of an `IntoDiagnostic` -/// struct). Implemented as a custom trait rather than `From` so that it is implemented on the type -/// being converted rather than on `DiagnosticArgValue`, which enables types from other `rustc_*` -/// crates to implement this. +/// Converts a value of a type into a `DiagArg` (typically a field of an `IntoDiagnostic` struct). +/// Implemented as a custom trait rather than `From` so that it is implemented on the type being +/// converted rather than on `DiagArgValue`, which enables types from other `rustc_*` crates to +/// implement this. pub trait IntoDiagnosticArg { - fn into_diagnostic_arg(self) -> DiagnosticArgValue; + fn into_diagnostic_arg(self) -> DiagArgValue; } -impl IntoDiagnosticArg for DiagnosticArgValue { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { +impl IntoDiagnosticArg for DiagArgValue { + fn into_diagnostic_arg(self) -> DiagArgValue { self } } -impl Into<FluentValue<'static>> for DiagnosticArgValue { +impl Into<FluentValue<'static>> for DiagArgValue { fn into(self) -> FluentValue<'static> { match self { - DiagnosticArgValue::Str(s) => From::from(s), - DiagnosticArgValue::Number(n) => From::from(n), - DiagnosticArgValue::StrListSepByAnd(l) => fluent_value_from_str_list_sep_by_and(l), + DiagArgValue::Str(s) => From::from(s), + DiagArgValue::Number(n) => From::from(n), + DiagArgValue::StrListSepByAnd(l) => fluent_value_from_str_list_sep_by_and(l), } } } @@ -157,7 +176,7 @@ where Self: Sized, { /// 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); } @@ -165,40 +184,40 @@ where /// (to optionally perform eager translation). fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( self, - diag: &mut DiagnosticBuilder<'_, G>, + diag: &mut Diag<'_, G>, f: F, ); } 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 /// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic]. #[rustc_diagnostic_item = "DecorateLint"] pub trait DecorateLint<'a, G: EmissionGuarantee> { /// 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; } #[derive(Clone, Debug, Encodable, Decodable)] -pub struct DiagnosticLocation { +pub struct DiagLocation { file: Cow<'static, str>, line: u32, col: u32, } -impl DiagnosticLocation { +impl DiagLocation { #[track_caller] fn caller() -> Self { let loc = panic::Location::caller(); - DiagnosticLocation { file: loc.file().into(), line: loc.line(), col: loc.column() } + DiagLocation { file: loc.file().into(), line: loc.line(), col: loc.column() } } } -impl fmt::Display for DiagnosticLocation { +impl fmt::Display for DiagLocation { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}:{}:{}", self.file, self.line, self.col) } @@ -213,11 +232,11 @@ pub struct IsLint { } #[derive(Debug, PartialEq, Eq)] -pub struct DiagnosticStyledString(pub Vec<StringPart>); +pub struct DiagStyledString(pub Vec<StringPart>); -impl DiagnosticStyledString { - pub fn new() -> DiagnosticStyledString { - DiagnosticStyledString(vec![]) +impl DiagStyledString { + pub fn new() -> DiagStyledString { + DiagStyledString(vec![]) } pub fn push_normal<S: Into<String>>(&mut self, t: S) { self.0.push(StringPart::normal(t)); @@ -232,12 +251,12 @@ impl DiagnosticStyledString { self.push_normal(t); } } - pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString { - DiagnosticStyledString(vec![StringPart::normal(t)]) + pub fn normal<S: Into<String>>(t: S) -> DiagStyledString { + DiagStyledString(vec![StringPart::normal(t)]) } - pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString { - DiagnosticStyledString(vec![StringPart::highlighted(t)]) + pub fn highlighted<S: Into<String>>(t: S) -> DiagStyledString { + DiagStyledString(vec![StringPart::highlighted(t)]) } pub fn content(&self) -> String { @@ -261,13 +280,13 @@ impl StringPart { } } -/// The main part of a diagnostic. Note that `DiagnosticBuilder`, which wraps -/// this type, is used for most operations, and should be used instead whenever -/// possible. This type should only be used when `DiagnosticBuilder`'s lifetime -/// causes difficulties, e.g. when storing diagnostics within `DiagCtxt`. +/// The main part of a diagnostic. Note that `Diag`, which wraps this type, is +/// used for most operations, and should be used instead whenever possible. +/// This type should only be used when `Diag`'s lifetime causes difficulties, +/// e.g. when storing diagnostics within `DiagCtxt`. #[must_use] #[derive(Clone, Debug, Encodable, Decodable)] -pub struct Diagnostic { +pub struct DiagInner { // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes, // outside of what methods in this crate themselves allow. pub(crate) level: Level, @@ -275,9 +294,9 @@ pub struct Diagnostic { pub messages: Vec<(DiagnosticMessage, Style)>, pub code: Option<ErrCode>, pub span: MultiSpan, - pub children: Vec<SubDiagnostic>, + pub children: Vec<Subdiag>, pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>, - pub args: DiagnosticArgMap, + pub args: DiagArgMap, /// This is not used for highlighting or rendering any error message. Rather, it can be used /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of @@ -288,18 +307,18 @@ pub struct Diagnostic { /// With `-Ztrack_diagnostics` enabled, /// we print where in rustc this error was emitted. - pub(crate) emitted_at: DiagnosticLocation, + pub(crate) emitted_at: DiagLocation, } -impl Diagnostic { +impl DiagInner { #[track_caller] pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self { - Diagnostic::new_with_messages(level, vec![(message.into(), Style::NoStyle)]) + DiagInner::new_with_messages(level, vec![(message.into(), Style::NoStyle)]) } #[track_caller] pub fn new_with_messages(level: Level, messages: Vec<(DiagnosticMessage, Style)>) -> Self { - Diagnostic { + DiagInner { level, messages, code: None, @@ -309,7 +328,7 @@ impl Diagnostic { args: Default::default(), sort_span: DUMMY_SP, is_lint: None, - emitted_at: DiagnosticLocation::caller(), + emitted_at: DiagLocation::caller(), } } @@ -374,7 +393,7 @@ impl Diagnostic { } } - // 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( &self, attr: impl Into<SubdiagnosticMessage>, @@ -390,7 +409,7 @@ impl Diagnostic { message: impl Into<SubdiagnosticMessage>, span: MultiSpan, ) { - let sub = SubDiagnostic { + let sub = Subdiag { level, messages: vec![( self.subdiagnostic_message_to_diagnostic_message(message), @@ -401,7 +420,7 @@ impl Diagnostic { self.children.push(sub); } - pub(crate) fn arg(&mut self, name: impl Into<DiagnosticArgName>, arg: impl IntoDiagnosticArg) { + pub(crate) fn arg(&mut self, name: impl Into<DiagArgName>, arg: impl IntoDiagnosticArg) { self.args.insert(name.into(), arg.into_diagnostic_arg()); } @@ -413,9 +432,9 @@ impl Diagnostic { &[(DiagnosticMessage, Style)], &Option<ErrCode>, &MultiSpan, - &[SubDiagnostic], + &[Subdiag], &Result<Vec<CodeSuggestion>, SuggestionsDisabled>, - Vec<(&DiagnosticArgName, &DiagnosticArgValue)>, + Vec<(&DiagArgName, &DiagArgValue)>, &Option<IsLint>, ) { ( @@ -433,7 +452,7 @@ impl Diagnostic { } } -impl Hash for Diagnostic { +impl Hash for DiagInner { fn hash<H>(&self, state: &mut H) where H: Hasher, @@ -442,7 +461,7 @@ impl Hash for Diagnostic { } } -impl PartialEq for Diagnostic { +impl PartialEq for DiagInner { fn eq(&self, other: &Self) -> bool { self.keys() == other.keys() } @@ -451,75 +470,70 @@ impl PartialEq for Diagnostic { /// A "sub"-diagnostic attached to a parent diagnostic. /// For example, a note attached to an error. #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)] -pub struct SubDiagnostic { +pub struct Subdiag { pub level: Level, pub messages: Vec<(DiagnosticMessage, Style)>, pub span: MultiSpan, } /// Used for emitting structured error messages and other diagnostic information. -/// Wraps a `Diagnostic`, adding some useful things. +/// Wraps a `DiagInner`, adding some useful things. /// - The `dcx` field, allowing it to (a) emit itself, and (b) do a drop check /// that it has been emitted or cancelled. /// - The `EmissionGuarantee`, which determines the type returned from `emit`. /// -/// Each constructed `DiagnosticBuilder` must be consumed by a function such as -/// `emit`, `cancel`, `delay_as_bug`, or `into_diagnostic`. A panic occurrs if a -/// `DiagnosticBuilder` is dropped without being consumed by one of these -/// functions. +/// Each constructed `Diag` must be consumed by a function such as `emit`, +/// `cancel`, `delay_as_bug`, or `into_diagnostic`. A panic occurrs if a `Diag` +/// is dropped without being consumed by one of these functions. /// -/// If there is some state in a downstream crate you would like to -/// access in the methods of `DiagnosticBuilder` here, consider -/// extending `DiagCtxtFlags`. +/// If there is some state in a downstream crate you would like to access in +/// the methods of `Diag` here, consider extending `DiagCtxtFlags`. #[must_use] -pub struct DiagnosticBuilder<'a, G: EmissionGuarantee = ErrorGuaranteed> { +pub struct Diag<'a, G: EmissionGuarantee = ErrorGuaranteed> { pub dcx: &'a DiagCtxt, - /// Why the `Option`? It is always `Some` until the `DiagnosticBuilder` is - /// consumed via `emit`, `cancel`, etc. At that point it is consumed and - /// replaced with `None`. Then `drop` checks that it is `None`; if not, it - /// panics because a diagnostic was built but not used. + /// Why the `Option`? It is always `Some` until the `Diag` is consumed via + /// `emit`, `cancel`, etc. At that point it is consumed and replaced with + /// `None`. Then `drop` checks that it is `None`; if not, it panics because + /// a diagnostic was built but not used. /// - /// Why the Box? `Diagnostic` is a large type, and `DiagnosticBuilder` is - /// often used as a return value, especially within the frequently-used - /// `PResult` type. In theory, return value optimization (RVO) should avoid - /// unnecessary copying. In practice, it does not (at the time of writing). - diag: Option<Box<Diagnostic>>, + /// Why the Box? `DiagInner` is a large type, and `Diag` is often used as a + /// return value, especially within the frequently-used `PResult` type. In + /// theory, return value optimization (RVO) should avoid unnecessary + /// copying. In practice, it does not (at the time of writing). + diag: Option<Box<DiagInner>>, _marker: PhantomData<G>, } -// Cloning a `DiagnosticBuilder` is a recipe for a diagnostic being emitted -// twice, which would be bad. -impl<G> !Clone for DiagnosticBuilder<'_, G> {} +// Cloning a `Diag` is a recipe for a diagnostic being emitted twice, which +// would be bad. +impl<G> !Clone for Diag<'_, G> {} -rustc_data_structures::static_assert_size!( - DiagnosticBuilder<'_, ()>, - 2 * std::mem::size_of::<usize>() -); +rustc_data_structures::static_assert_size!(Diag<'_, ()>, 2 * std::mem::size_of::<usize>()); -impl<G: EmissionGuarantee> Deref for DiagnosticBuilder<'_, G> { - type Target = Diagnostic; +impl<G: EmissionGuarantee> Deref for Diag<'_, G> { + type Target = DiagInner; - fn deref(&self) -> &Diagnostic { + fn deref(&self) -> &DiagInner { self.diag.as_ref().unwrap() } } -impl<G: EmissionGuarantee> DerefMut for DiagnosticBuilder<'_, G> { - fn deref_mut(&mut self) -> &mut Diagnostic { +impl<G: EmissionGuarantee> DerefMut for Diag<'_, G> { + fn deref_mut(&mut self) -> &mut DiagInner { 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 { self.diag.fmt(f) } } -/// `DiagnosticBuilder` impls many `&mut self -> &mut Self` methods. Each one -/// modifies an existing diagnostic, either in a standalone fashion, e.g. +/// `Diag` impls many `&mut self -> &mut Self` methods. Each one modifies an +/// existing diagnostic, either in a standalone fashion, e.g. /// `err.code(code);`, or in a chained fashion to make multiple modifications, /// e.g. `err.code(code).span(span);`. /// @@ -546,14 +560,14 @@ macro_rules! with_fn { } => { // The original function. $(#[$attrs])* - #[doc = concat!("See [`DiagnosticBuilder::", stringify!($f), "()`].")] + #[doc = concat!("See [`Diag::", stringify!($f), "()`].")] pub fn $f(&mut $self, $($name: $ty),*) -> &mut Self { $($body)* } // The `with_*` variant. $(#[$attrs])* - #[doc = concat!("See [`DiagnosticBuilder::", stringify!($f), "()`].")] + #[doc = concat!("See [`Diag::", stringify!($f), "()`].")] pub fn $with_f(mut $self, $($name: $ty),*) -> Self { $self.$f($($name),*); $self @@ -561,17 +575,16 @@ macro_rules! with_fn { }; } -impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { +impl<'a, G: EmissionGuarantee> Diag<'a, G> { #[rustc_lint_diagnostics] #[track_caller] pub fn new<M: Into<DiagnosticMessage>>(dcx: &'a DiagCtxt, level: Level, message: M) -> Self { - Self::new_diagnostic(dcx, Diagnostic::new(level, message)) + Self::new_diagnostic(dcx, DiagInner::new(level, message)) } - /// Creates a new `DiagnosticBuilder` with an already constructed - /// diagnostic. + /// Creates a new `Diag` with an already constructed diagnostic. #[track_caller] - pub(crate) fn new_diagnostic(dcx: &'a DiagCtxt, diag: Diagnostic) -> Self { + pub(crate) fn new_diagnostic(dcx: &'a DiagCtxt, diag: DiagInner) -> Self { debug!("Created new diagnostic"); Self { dcx, diag: Some(Box::new(diag)), _marker: PhantomData } } @@ -644,9 +657,9 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { pub fn note_expected_found( &mut self, expected_label: &dyn fmt::Display, - expected: DiagnosticStyledString, + expected: DiagStyledString, found_label: &dyn fmt::Display, - found: DiagnosticStyledString, + found: DiagStyledString, ) -> &mut Self { self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"") } @@ -654,9 +667,9 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { pub fn note_expected_found_extra( &mut self, expected_label: &dyn fmt::Display, - expected: DiagnosticStyledString, + expected: DiagStyledString, found_label: &dyn fmt::Display, - found: DiagnosticStyledString, + found: DiagStyledString, expected_extra: &dyn fmt::Display, found_extra: &dyn fmt::Display, ) -> &mut Self { @@ -715,7 +728,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { 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 { self.sub(Level::OnceNote, msg, MultiSpan::new()); self @@ -723,7 +736,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { with_fn! { with_span_note, /// 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] pub fn span_note( &mut self, @@ -735,7 +748,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { } } /// 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>>( &mut self, sp: S, @@ -754,7 +767,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { } } /// 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] pub fn span_warn<S: Into<MultiSpan>>( &mut self, @@ -773,7 +786,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { 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 { self.sub(Level::OnceHelp, msg, MultiSpan::new()); self @@ -786,7 +799,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { } /// 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] pub fn span_help<S: Into<MultiSpan>>( &mut self, @@ -856,7 +869,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( &mut self, msg: impl Into<SubdiagnosticMessage>, @@ -948,7 +961,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { 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( &mut self, sp: Span, @@ -993,7 +1006,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { with_fn! { with_span_suggestions, /// 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( &mut self, sp: Span, @@ -1039,7 +1052,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { /// Prints out a message with multiple suggested edits of the code, where each edit consists of /// multiple parts. - /// See also [`DiagnosticBuilder::multipart_suggestion()`]. + /// See also [`Diag::multipart_suggestion()`]. pub fn multipart_suggestions( &mut self, msg: impl Into<SubdiagnosticMessage>, @@ -1199,7 +1212,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { /// Add an argument. pub fn arg( &mut self, - name: impl Into<DiagnosticArgName>, + name: impl Into<DiagArgName>, arg: impl IntoDiagnosticArg, ) -> &mut Self { self.deref_mut().arg(name, arg); @@ -1231,14 +1244,14 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { .into_iter() .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.content), m.style)) .collect(); - let sub = SubDiagnostic { level, messages, span }; + let sub = Subdiag { level, messages, span }; self.children.push(sub); } - /// Takes the diagnostic. For use by methods that consume the - /// DiagnosticBuilder: `emit`, `cancel`, etc. Afterwards, `drop` is the - /// only code that will be run on `self`. - fn take_diag(&mut self) -> Diagnostic { + /// Takes the diagnostic. For use by methods that consume the Diag: `emit`, + /// `cancel`, etc. Afterwards, `drop` is the only code that will be run on + /// `self`. + fn take_diag(&mut self) -> DiagInner { Box::into_inner(self.diag.take().unwrap()) } @@ -1257,7 +1270,7 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { // because delayed bugs have their level changed to `Bug` when they are // actually printed, so they produce an ICE. // - // (Also, even though `level` isn't `pub`, the whole `Diagnostic` could + // (Also, even though `level` isn't `pub`, the whole `DiagInner` could // be overwritten with a new one thanks to `DerefMut`. So this assert // protects against that, too.) assert!( @@ -1319,13 +1332,13 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { } } -/// Destructor bomb: every `DiagnosticBuilder` must be consumed (emitted, -/// cancelled, etc.) or we emit a bug. -impl<G: EmissionGuarantee> Drop for DiagnosticBuilder<'_, G> { +/// Destructor bomb: every `Diag` must be consumed (emitted, cancelled, etc.) +/// or we emit a bug. +impl<G: EmissionGuarantee> Drop for Diag<'_, G> { fn drop(&mut self) { match self.diag.take() { Some(diag) if !panicking() => { - self.dcx.emit_diagnostic(Diagnostic::new( + self.dcx.emit_diagnostic(DiagInner::new( Level::Bug, DiagnosticMessage::from("the following error was constructed but not emitted"), )); diff --git a/compiler/rustc_errors/src/diagnostic_impls.rs b/compiler/rustc_errors/src/diagnostic_impls.rs index bc1e81642ff..70c8d971868 100644 --- a/compiler/rustc_errors/src/diagnostic_impls.rs +++ b/compiler/rustc_errors/src/diagnostic_impls.rs @@ -1,8 +1,8 @@ -use crate::diagnostic::DiagnosticLocation; +use crate::diagnostic::DiagLocation; use crate::{fluent_generated as fluent, AddToDiagnostic}; use crate::{ - DiagCtxt, DiagnosticArgValue, DiagnosticBuilder, EmissionGuarantee, ErrCode, IntoDiagnostic, - IntoDiagnosticArg, Level, SubdiagnosticMessageOp, + Diag, DiagArgValue, DiagCtxt, EmissionGuarantee, ErrCode, IntoDiagnostic, IntoDiagnosticArg, + Level, SubdiagnosticMessageOp, }; use rustc_ast as ast; use rustc_ast_pretty::pprust; @@ -20,28 +20,28 @@ use std::num::ParseIntError; use std::path::{Path, PathBuf}; use std::process::ExitStatus; -pub struct DiagnosticArgFromDisplay<'a>(pub &'a dyn fmt::Display); +pub struct DiagArgFromDisplay<'a>(pub &'a dyn fmt::Display); -impl IntoDiagnosticArg for DiagnosticArgFromDisplay<'_> { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { +impl IntoDiagnosticArg for DiagArgFromDisplay<'_> { + fn into_diagnostic_arg(self) -> DiagArgValue { self.0.to_string().into_diagnostic_arg() } } -impl<'a> From<&'a dyn fmt::Display> for DiagnosticArgFromDisplay<'a> { +impl<'a> From<&'a dyn fmt::Display> for DiagArgFromDisplay<'a> { fn from(t: &'a dyn fmt::Display) -> Self { - DiagnosticArgFromDisplay(t) + DiagArgFromDisplay(t) } } -impl<'a, T: fmt::Display> From<&'a T> for DiagnosticArgFromDisplay<'a> { +impl<'a, T: fmt::Display> From<&'a T> for DiagArgFromDisplay<'a> { fn from(t: &'a T) -> Self { - DiagnosticArgFromDisplay(t) + DiagArgFromDisplay(t) } } impl<'a, T: Clone + IntoDiagnosticArg> IntoDiagnosticArg for &'a T { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { + fn into_diagnostic_arg(self) -> DiagArgValue { self.clone().into_diagnostic_arg() } } @@ -50,7 +50,7 @@ macro_rules! into_diagnostic_arg_using_display { ($( $ty:ty ),+ $(,)?) => { $( impl IntoDiagnosticArg for $ty { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { + fn into_diagnostic_arg(self) -> DiagArgValue { self.to_string().into_diagnostic_arg() } } @@ -62,10 +62,10 @@ macro_rules! into_diagnostic_arg_for_number { ($( $ty:ty ),+ $(,)?) => { $( impl IntoDiagnosticArg for $ty { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { + fn into_diagnostic_arg(self) -> DiagArgValue { // Convert to a string if it won't fit into `Number`. if let Ok(n) = TryInto::<i32>::try_into(self) { - DiagnosticArgValue::Number(n) + DiagArgValue::Number(n) } else { self.to_string().into_diagnostic_arg() } @@ -95,74 +95,74 @@ into_diagnostic_arg_using_display!( into_diagnostic_arg_for_number!(i8, u8, i16, u16, i32, u32, i64, u64, i128, u128, isize, usize); impl IntoDiagnosticArg for bool { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { + fn into_diagnostic_arg(self) -> DiagArgValue { if self { - DiagnosticArgValue::Str(Cow::Borrowed("true")) + DiagArgValue::Str(Cow::Borrowed("true")) } else { - DiagnosticArgValue::Str(Cow::Borrowed("false")) + DiagArgValue::Str(Cow::Borrowed("false")) } } } impl IntoDiagnosticArg for char { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::Owned(format!("{self:?}"))) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::Owned(format!("{self:?}"))) } } impl IntoDiagnosticArg for Vec<char> { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::StrListSepByAnd( + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::StrListSepByAnd( self.into_iter().map(|c| Cow::Owned(format!("{c:?}"))).collect(), ) } } impl IntoDiagnosticArg for Symbol { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { + fn into_diagnostic_arg(self) -> DiagArgValue { self.to_ident_string().into_diagnostic_arg() } } impl<'a> IntoDiagnosticArg for &'a str { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { + fn into_diagnostic_arg(self) -> DiagArgValue { self.to_string().into_diagnostic_arg() } } impl IntoDiagnosticArg for String { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::Owned(self)) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::Owned(self)) } } impl<'a> IntoDiagnosticArg for Cow<'a, str> { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::Owned(self.into_owned())) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::Owned(self.into_owned())) } } impl<'a> IntoDiagnosticArg for &'a Path { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::Owned(self.display().to_string())) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::Owned(self.display().to_string())) } } impl IntoDiagnosticArg for PathBuf { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::Owned(self.display().to_string())) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::Owned(self.display().to_string())) } } impl IntoDiagnosticArg for PanicStrategy { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::Owned(self.desc().to_string())) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::Owned(self.desc().to_string())) } } impl IntoDiagnosticArg for hir::ConstContext { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::Borrowed(match self { + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::Borrowed(match self { hir::ConstContext::ConstFn => "const_fn", hir::ConstContext::Static(_) => "static", hir::ConstContext::Const { .. } => "const", @@ -171,123 +171,122 @@ impl IntoDiagnosticArg for hir::ConstContext { } impl IntoDiagnosticArg for ast::Expr { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::Owned(pprust::expr_to_string(&self))) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::Owned(pprust::expr_to_string(&self))) } } impl IntoDiagnosticArg for ast::Path { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::Owned(pprust::path_to_string(&self))) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::Owned(pprust::path_to_string(&self))) } } impl IntoDiagnosticArg for ast::token::Token { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(pprust::token_to_string(&self)) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(pprust::token_to_string(&self)) } } impl IntoDiagnosticArg for ast::token::TokenKind { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(pprust::token_kind_to_string(&self)) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(pprust::token_kind_to_string(&self)) } } impl IntoDiagnosticArg for type_ir::FloatTy { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::Borrowed(self.name_str())) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::Borrowed(self.name_str())) } } impl IntoDiagnosticArg for std::ffi::CString { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::Owned(self.to_string_lossy().into_owned())) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::Owned(self.to_string_lossy().into_owned())) } } impl IntoDiagnosticArg for rustc_data_structures::small_c_str::SmallCStr { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::Owned(self.to_string_lossy().into_owned())) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::Owned(self.to_string_lossy().into_owned())) } } impl IntoDiagnosticArg for ast::Visibility { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { + fn into_diagnostic_arg(self) -> DiagArgValue { let s = pprust::vis_to_string(&self); let s = s.trim_end().to_string(); - DiagnosticArgValue::Str(Cow::Owned(s)) + DiagArgValue::Str(Cow::Owned(s)) } } impl IntoDiagnosticArg for rustc_lint_defs::Level { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::Borrowed(self.to_cmd_flag())) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::Borrowed(self.to_cmd_flag())) } } #[derive(Clone)] -pub struct DiagnosticSymbolList(Vec<Symbol>); +pub struct DiagSymbolList(Vec<Symbol>); -impl From<Vec<Symbol>> for DiagnosticSymbolList { +impl From<Vec<Symbol>> for DiagSymbolList { fn from(v: Vec<Symbol>) -> Self { - DiagnosticSymbolList(v) + DiagSymbolList(v) } } -impl IntoDiagnosticArg for DiagnosticSymbolList { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::StrListSepByAnd( +impl IntoDiagnosticArg for DiagSymbolList { + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::StrListSepByAnd( self.0.into_iter().map(|sym| Cow::Owned(format!("`{sym}`"))).collect(), ) } } impl<Id> IntoDiagnosticArg for hir::def::Res<Id> { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::Borrowed(self.descr())) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::Borrowed(self.descr())) } } 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 { 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("cause", cause) .with_arg("err", 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("bit", bit) .with_arg("cause", cause) .with_arg("err", err) } 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) } 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("err_kind", err.diag_ident()) .with_arg("align", err.align()) } 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("target", 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("target", target) } TargetDataLayoutErrors::InvalidBitsSize { err } => { - DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_bits_size) - .with_arg("err", err) + Diag::new(dcx, level, fluent::errors_target_invalid_bits_size).with_arg("err", err) } } } @@ -301,7 +300,7 @@ pub struct SingleLabelManySpans { impl AddToDiagnostic for SingleLabelManySpans { fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>( self, - diag: &mut DiagnosticBuilder<'_, G>, + diag: &mut Diag<'_, G>, _: F, ) { diag.span_labels(self.spans, self.label); @@ -316,21 +315,21 @@ pub struct ExpectedLifetimeParameter { pub count: usize, } -impl IntoDiagnosticArg for DiagnosticLocation { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::from(self.to_string())) +impl IntoDiagnosticArg for DiagLocation { + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::from(self.to_string())) } } impl IntoDiagnosticArg for Backtrace { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::from(self.to_string())) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::from(self.to_string())) } } impl IntoDiagnosticArg for Level { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(Cow::from(self.to_string())) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(Cow::from(self.to_string())) } } @@ -344,7 +343,7 @@ pub struct IndicateAnonymousLifetime { } impl IntoDiagnosticArg for type_ir::ClosureKind { - fn into_diagnostic_arg(self) -> DiagnosticArgValue { - DiagnosticArgValue::Str(self.as_str().into()) + fn into_diagnostic_arg(self) -> DiagArgValue { + DiagArgValue::Str(self.as_str().into()) } } diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index c4b2c28fc23..304922018eb 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -1,6 +1,6 @@ //! 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 //! JSON and human readable output. @@ -17,9 +17,9 @@ use crate::snippet::{ use crate::styled_buffer::StyledBuffer; use crate::translation::{to_fluent_args, Translate}; use crate::{ - diagnostic::DiagnosticLocation, CodeSuggestion, DiagCtxt, Diagnostic, DiagnosticMessage, - ErrCode, FluentBundle, LazyFallbackBundle, Level, MultiSpan, SubDiagnostic, - SubstitutionHighlight, SuggestionStyle, TerminalUrl, + diagnostic::DiagLocation, CodeSuggestion, DiagCtxt, DiagInner, DiagnosticMessage, ErrCode, + FluentBundle, LazyFallbackBundle, Level, MultiSpan, Subdiag, SubstitutionHighlight, + SuggestionStyle, TerminalUrl, }; use rustc_lint_defs::pluralize; @@ -194,7 +194,7 @@ pub type DynEmitter = dyn Emitter + DynSend; /// Emitter trait for emitting errors. pub trait Emitter: Translate { /// Emit a structured diagnostic. - fn emit_diagnostic(&mut self, diag: Diagnostic); + fn emit_diagnostic(&mut self, diag: DiagInner); /// Emit a notification that an artifact has been output. /// Currently only supported for the JSON format. @@ -202,7 +202,7 @@ pub trait Emitter: Translate { /// Emit a report about future breakage. /// Currently only supported for the JSON format. - fn emit_future_breakage_report(&mut self, _diags: Vec<Diagnostic>) {} + fn emit_future_breakage_report(&mut self, _diags: Vec<DiagInner>) {} /// Emit list of unused externs. /// Currently only supported for the JSON format. @@ -229,12 +229,12 @@ pub trait Emitter: Translate { /// /// There are a lot of conditions to this method, but in short: /// - /// * If the current `Diagnostic` has only one visible `CodeSuggestion`, + /// * If the current `DiagInner` has only one visible `CodeSuggestion`, /// we format the `help` suggestion depending on the content of the /// substitutions. In that case, we modify the span and clear the /// suggestions. /// - /// * If the current `Diagnostic` has multiple suggestions, + /// * If the current `DiagInner` has multiple suggestions, /// we leave `primary_span` and the suggestions untouched. fn primary_span_formatted( &mut self, @@ -303,7 +303,7 @@ pub trait Emitter: Translate { fn fix_multispans_in_extern_macros_and_render_macro_backtrace( &self, span: &mut MultiSpan, - children: &mut Vec<SubDiagnostic>, + children: &mut Vec<Subdiag>, level: &Level, backtrace: bool, ) { @@ -350,7 +350,7 @@ pub trait Emitter: Translate { (in Nightly builds, run with -Z macro-backtrace for more info)", ); - children.push(SubDiagnostic { + children.push(Subdiag { level: Level::Note, messages: vec![(DiagnosticMessage::from(msg), Style::NoStyle)], span: MultiSpan::new(), @@ -362,7 +362,7 @@ pub trait Emitter: Translate { fn render_multispans_macro_backtrace( &self, span: &mut MultiSpan, - children: &mut Vec<SubDiagnostic>, + children: &mut Vec<Subdiag>, backtrace: bool, ) { for span in iter::once(span).chain(children.iter_mut().map(|child| &mut child.span)) { @@ -461,11 +461,7 @@ pub trait Emitter: Translate { // This does a small "fix" for multispans by looking to see if it can find any that // point directly at external macros. Since these are often difficult to read, // this will change the span to point at the use site. - fn fix_multispans_in_extern_macros( - &self, - span: &mut MultiSpan, - children: &mut Vec<SubDiagnostic>, - ) { + fn fix_multispans_in_extern_macros(&self, span: &mut MultiSpan, children: &mut Vec<Subdiag>) { debug!("fix_multispans_in_extern_macros: before: span={:?} children={:?}", span, children); self.fix_multispan_in_extern_macros(span); for child in children.iter_mut() { @@ -518,7 +514,7 @@ impl Emitter for HumanEmitter { self.sm.as_ref() } - fn emit_diagnostic(&mut self, mut diag: Diagnostic) { + fn emit_diagnostic(&mut self, mut diag: DiagInner) { let fluent_args = to_fluent_args(diag.args.iter()); let mut suggestions = diag.suggestions.unwrap_or(vec![]); @@ -597,7 +593,7 @@ impl Emitter for SilentEmitter { None } - fn emit_diagnostic(&mut self, mut diag: Diagnostic) { + fn emit_diagnostic(&mut self, mut diag: DiagInner) { if diag.level == Level::Fatal { diag.sub(Level::Note, self.fatal_note.clone(), MultiSpan::new()); self.fatal_dcx.emit_diagnostic(diag); @@ -1235,7 +1231,7 @@ impl HumanEmitter { max } - fn get_max_line_num(&mut self, span: &MultiSpan, children: &[SubDiagnostic]) -> usize { + fn get_max_line_num(&mut self, span: &MultiSpan, children: &[Subdiag]) -> usize { let primary = self.get_multispan_max_line_num(span); children .iter() @@ -1331,7 +1327,7 @@ impl HumanEmitter { level: &Level, max_line_num_len: usize, is_secondary: bool, - emitted_at: Option<&DiagnosticLocation>, + emitted_at: Option<&DiagLocation>, ) -> io::Result<()> { let mut buffer = StyledBuffer::new(); @@ -2098,9 +2094,9 @@ impl HumanEmitter { args: &FluentArgs<'_>, code: &Option<ErrCode>, span: &MultiSpan, - children: &[SubDiagnostic], + children: &[Subdiag], suggestions: &[CodeSuggestion], - emitted_at: Option<&DiagnosticLocation>, + emitted_at: Option<&DiagLocation>, ) { let max_line_num_len = if self.ui_testing { ANONYMIZED_LINE_NUM.len() diff --git a/compiler/rustc_errors/src/json.rs b/compiler/rustc_errors/src/json.rs index e57b414c52d..88a83c8bf78 100644 --- a/compiler/rustc_errors/src/json.rs +++ b/compiler/rustc_errors/src/json.rs @@ -17,7 +17,7 @@ use crate::registry::Registry; use crate::translation::{to_fluent_args, Translate}; use crate::{ diagnostic::IsLint, CodeSuggestion, FluentBundle, LazyFallbackBundle, MultiSpan, SpanLabel, - SubDiagnostic, TerminalUrl, + Subdiag, TerminalUrl, }; use rustc_lint_defs::Applicability; @@ -176,7 +176,7 @@ impl Translate for JsonEmitter { } impl Emitter for JsonEmitter { - fn emit_diagnostic(&mut self, diag: crate::Diagnostic) { + fn emit_diagnostic(&mut self, diag: crate::DiagInner) { let data = Diagnostic::from_errors_diagnostic(diag, self); let result = self.emit(EmitTyped::Diagnostic(data)); if let Err(e) = result { @@ -192,7 +192,7 @@ impl Emitter for JsonEmitter { } } - fn emit_future_breakage_report(&mut self, diags: Vec<crate::Diagnostic>) { + fn emit_future_breakage_report(&mut self, diags: Vec<crate::DiagInner>) { let data: Vec<FutureBreakageItem<'_>> = diags .into_iter() .map(|mut diag| { @@ -340,7 +340,7 @@ struct UnusedExterns<'a, 'b, 'c> { } impl Diagnostic { - fn from_errors_diagnostic(diag: crate::Diagnostic, je: &JsonEmitter) -> Diagnostic { + fn from_errors_diagnostic(diag: crate::DiagInner, je: &JsonEmitter) -> Diagnostic { let args = to_fluent_args(diag.args.iter()); let sugg = diag.suggestions.iter().flatten().map(|sugg| { let translated_message = @@ -431,16 +431,16 @@ impl Diagnostic { } fn from_sub_diagnostic( - diag: &SubDiagnostic, + subdiag: &Subdiag, args: &FluentArgs<'_>, je: &JsonEmitter, ) -> Diagnostic { - let translated_message = je.translate_messages(&diag.messages, args); + let translated_message = je.translate_messages(&subdiag.messages, args); Diagnostic { message: translated_message.to_string(), code: None, - level: diag.level.to_str(), - spans: DiagnosticSpan::from_multispan(&diag.span, args, je), + level: subdiag.level.to_str(), + spans: DiagnosticSpan::from_multispan(&subdiag.span, args, je), children: vec![], rendered: None, } diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 3f667e264e8..2652feff62a 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -37,14 +37,13 @@ extern crate self as rustc_errors; pub use codes::*; pub use diagnostic::{ - AddToDiagnostic, BugAbort, DecorateLint, Diagnostic, DiagnosticArg, DiagnosticArgMap, - DiagnosticArgName, DiagnosticArgValue, DiagnosticBuilder, DiagnosticStyledString, - EmissionGuarantee, FatalAbort, IntoDiagnostic, IntoDiagnosticArg, StringPart, SubDiagnostic, - SubdiagnosticMessageOp, + AddToDiagnostic, BugAbort, DecorateLint, Diag, DiagArg, DiagArgMap, DiagArgName, DiagArgValue, + DiagInner, DiagStyledString, EmissionGuarantee, FatalAbort, IntoDiagnostic, IntoDiagnosticArg, + StringPart, Subdiag, SubdiagnosticMessageOp, }; pub use diagnostic_impls::{ - DiagnosticArgFromDisplay, DiagnosticSymbolList, ExpectedLifetimeParameter, - IndicateAnonymousLifetime, SingleLabelManySpans, + DiagArgFromDisplay, DiagSymbolList, ExpectedLifetimeParameter, IndicateAnonymousLifetime, + SingleLabelManySpans, }; pub use emitter::ColorConfig; pub use rustc_error_messages::{ @@ -98,7 +97,7 @@ mod styled_buffer; mod tests; pub mod translation; -pub type PErr<'a> = DiagnosticBuilder<'a>; +pub type PErr<'a> = Diag<'a>; pub type PResult<'a, T> = Result<T, PErr<'a>>; rustc_fluent_macro::fluent_messages! { "../messages.ftl" } @@ -433,7 +432,7 @@ struct DiagCtxtInner { /// lint error count. lint_err_guars: Vec<ErrorGuaranteed>, /// The delayed bugs and their error guarantees. - delayed_bugs: Vec<(DelayedDiagnostic, ErrorGuaranteed)>, + delayed_bugs: Vec<(DelayedDiagInner, ErrorGuaranteed)>, /// The number of stashed errors. Unlike the other counts, this can go up /// and down, so it doesn't guarantee anything. @@ -476,9 +475,9 @@ struct DiagCtxtInner { /// add more information). All stashed diagnostics must be emitted with /// `emit_stashed_diagnostics` by the time the `DiagCtxtInner` is dropped, /// otherwise an assertion failure will occur. - stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>, + stashed_diagnostics: FxIndexMap<(Span, StashKey), DiagInner>, - future_breakage_diagnostics: Vec<Diagnostic>, + future_breakage_diagnostics: Vec<DiagInner>, /// The [`Self::unstable_expect_diagnostics`] should be empty when this struct is /// dropped. However, it can have values if the compilation is stopped early @@ -487,13 +486,13 @@ struct DiagCtxtInner { /// have been converted. check_unstable_expect_diagnostics: bool, - /// Expected [`Diagnostic`][struct@diagnostic::Diagnostic]s store a [`LintExpectationId`] as part of + /// Expected [`DiagInner`][struct@diagnostic::DiagInner]s store a [`LintExpectationId`] as part of /// the lint level. [`LintExpectationId`]s created early during the compilation /// (before `HirId`s have been defined) are not stable and can therefore not be /// stored on disk. This buffer stores these diagnostics until the ID has been - /// replaced by a stable [`LintExpectationId`]. The [`Diagnostic`][struct@diagnostic::Diagnostic]s are the - /// submitted for storage and added to the list of fulfilled expectations. - unstable_expect_diagnostics: Vec<Diagnostic>, + /// replaced by a stable [`LintExpectationId`]. The [`DiagInner`][struct@diagnostic::DiagInner]s + /// are submitted for storage and added to the list of fulfilled expectations. + unstable_expect_diagnostics: Vec<DiagInner>, /// expected diagnostic will have the level `Expect` which additionally /// carries the [`LintExpectationId`] of the expectation that can be @@ -531,11 +530,11 @@ pub enum StashKey { UndeterminedMacroResolution, } -fn default_track_diagnostic(diag: Diagnostic, f: &mut dyn FnMut(Diagnostic)) { +fn default_track_diagnostic(diag: DiagInner, f: &mut dyn FnMut(DiagInner)) { (*f)(diag) } -pub static TRACK_DIAGNOSTIC: AtomicRef<fn(Diagnostic, &mut dyn FnMut(Diagnostic))> = +pub static TRACK_DIAGNOSTIC: AtomicRef<fn(DiagInner, &mut dyn FnMut(DiagInner))> = AtomicRef::new(&(default_track_diagnostic as _)); #[derive(Copy, Clone, Default)] @@ -640,7 +639,7 @@ impl DiagCtxt { pub fn eagerly_translate<'a>( &self, message: DiagnosticMessage, - args: impl Iterator<Item = DiagnosticArg<'a>>, + args: impl Iterator<Item = DiagArg<'a>>, ) -> SubdiagnosticMessage { let inner = self.inner.borrow(); inner.eagerly_translate(message, args) @@ -650,7 +649,7 @@ impl DiagCtxt { pub fn eagerly_translate_to_string<'a>( &self, message: DiagnosticMessage, - args: impl Iterator<Item = DiagnosticArg<'a>>, + args: impl Iterator<Item = DiagArg<'a>>, ) -> String { let inner = self.inner.borrow(); inner.eagerly_translate_to_string(message, args) @@ -718,7 +717,7 @@ impl DiagCtxt { /// Stash a given diagnostic with the given `Span` and [`StashKey`] as the key. /// Retrieve a stashed diagnostic with `steal_diagnostic`. - pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) { + pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: DiagInner) { let mut inner = self.inner.borrow_mut(); let key = (span.with_parent(None), key); @@ -736,7 +735,7 @@ impl DiagCtxt { } /// 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 key = (span.with_parent(None), key); // FIXME(#120456) - is `swap_remove` correct? @@ -746,7 +745,7 @@ impl DiagCtxt { 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 { @@ -824,16 +823,16 @@ impl DiagCtxt { (0, _) => { // Use `ForceWarning` rather than `Warning` to guarantee emission, e.g. with a // configuration like `--cap-lints allow --force-warn bare_trait_objects`. - inner.emit_diagnostic(Diagnostic::new( + inner.emit_diagnostic(DiagInner::new( ForceWarning(None), DiagnosticMessage::Str(warnings), )); } (_, 0) => { - inner.emit_diagnostic(Diagnostic::new(Error, errors)); + inner.emit_diagnostic(DiagInner::new(Error, errors)); } (_, _) => { - inner.emit_diagnostic(Diagnostic::new(Error, format!("{errors}; {warnings}"))); + inner.emit_diagnostic(DiagInner::new(Error, format!("{errors}; {warnings}"))); } } @@ -864,14 +863,14 @@ impl DiagCtxt { "For more information about an error, try `rustc --explain {}`.", &error_codes[0] ); - inner.emit_diagnostic(Diagnostic::new(FailureNote, msg1)); - inner.emit_diagnostic(Diagnostic::new(FailureNote, msg2)); + inner.emit_diagnostic(DiagInner::new(FailureNote, msg1)); + inner.emit_diagnostic(DiagInner::new(FailureNote, msg2)); } else { let msg = format!( "For more information about this error, try `rustc --explain {}`.", &error_codes[0] ); - inner.emit_diagnostic(Diagnostic::new(FailureNote, msg)); + inner.emit_diagnostic(DiagInner::new(FailureNote, msg)); } } } @@ -896,7 +895,7 @@ impl DiagCtxt { self.inner.borrow_mut().taught_diagnostics.insert(code) } - pub fn emit_diagnostic(&self, diagnostic: Diagnostic) -> Option<ErrorGuaranteed> { + pub fn emit_diagnostic(&self, diagnostic: DiagInner) -> Option<ErrorGuaranteed> { self.inner.borrow_mut().emit_diagnostic(diagnostic) } @@ -1000,8 +999,8 @@ impl DiagCtxt { impl DiagCtxt { // No `#[rustc_lint_diagnostics]` because bug messages aren't user-facing. #[track_caller] - pub fn struct_bug(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, BugAbort> { - DiagnosticBuilder::new(self, Bug, msg) + pub fn struct_bug(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_, BugAbort> { + Diag::new(self, Bug, msg) } // No `#[rustc_lint_diagnostics]` because bug messages aren't user-facing. @@ -1016,7 +1015,7 @@ impl DiagCtxt { &self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>, - ) -> DiagnosticBuilder<'_, BugAbort> { + ) -> Diag<'_, BugAbort> { self.struct_bug(msg).with_span(span) } @@ -1027,10 +1026,7 @@ impl DiagCtxt { } #[track_caller] - pub fn create_bug<'a>( - &'a self, - bug: impl IntoDiagnostic<'a, BugAbort>, - ) -> DiagnosticBuilder<'a, BugAbort> { + pub fn create_bug<'a>(&'a self, bug: impl IntoDiagnostic<'a, BugAbort>) -> Diag<'a, BugAbort> { bug.into_diagnostic(self, Bug) } @@ -1041,11 +1037,8 @@ impl DiagCtxt { #[rustc_lint_diagnostics] #[track_caller] - pub fn struct_fatal( - &self, - msg: impl Into<DiagnosticMessage>, - ) -> DiagnosticBuilder<'_, FatalAbort> { - DiagnosticBuilder::new(self, Fatal, msg) + pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_, FatalAbort> { + Diag::new(self, Fatal, msg) } #[rustc_lint_diagnostics] @@ -1060,7 +1053,7 @@ impl DiagCtxt { &self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>, - ) -> DiagnosticBuilder<'_, FatalAbort> { + ) -> Diag<'_, FatalAbort> { self.struct_fatal(msg).with_span(span) } @@ -1074,7 +1067,7 @@ impl DiagCtxt { pub fn create_fatal<'a>( &'a self, fatal: impl IntoDiagnostic<'a, FatalAbort>, - ) -> DiagnosticBuilder<'a, FatalAbort> { + ) -> Diag<'a, FatalAbort> { fatal.into_diagnostic(self, Fatal) } @@ -1087,7 +1080,7 @@ impl DiagCtxt { pub fn create_almost_fatal<'a>( &'a self, fatal: impl IntoDiagnostic<'a, FatalError>, - ) -> DiagnosticBuilder<'a, FatalError> { + ) -> Diag<'a, FatalError> { 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). #[rustc_lint_diagnostics] #[track_caller] - pub fn struct_err(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_> { - DiagnosticBuilder::new(self, Error, msg) + pub fn struct_err(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_> { + Diag::new(self, Error, msg) } #[rustc_lint_diagnostics] @@ -1118,7 +1111,7 @@ impl DiagCtxt { &self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>, - ) -> DiagnosticBuilder<'_> { + ) -> Diag<'_> { self.struct_err(msg).with_span(span) } @@ -1133,7 +1126,7 @@ impl DiagCtxt { } #[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) } @@ -1146,7 +1139,7 @@ impl DiagCtxt { // No `#[rustc_lint_diagnostics]` because bug messages aren't user-facing. #[track_caller] 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`. @@ -1160,13 +1153,13 @@ impl DiagCtxt { sp: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>, ) -> ErrorGuaranteed { - DiagnosticBuilder::<ErrorGuaranteed>::new(self, DelayedBug, msg).with_span(sp).emit() + Diag::<ErrorGuaranteed>::new(self, DelayedBug, msg).with_span(sp).emit() } #[rustc_lint_diagnostics] #[track_caller] - pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> { - DiagnosticBuilder::new(self, Warning, msg) + pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_, ()> { + Diag::new(self, Warning, msg) } #[rustc_lint_diagnostics] @@ -1181,7 +1174,7 @@ impl DiagCtxt { &self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>, - ) -> DiagnosticBuilder<'_, ()> { + ) -> Diag<'_, ()> { self.struct_warn(msg).with_span(span) } @@ -1192,10 +1185,7 @@ impl DiagCtxt { } #[track_caller] - pub fn create_warn<'a>( - &'a self, - warning: impl IntoDiagnostic<'a, ()>, - ) -> DiagnosticBuilder<'a, ()> { + pub fn create_warn<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) -> Diag<'a, ()> { warning.into_diagnostic(self, Warning) } @@ -1206,8 +1196,8 @@ impl DiagCtxt { #[rustc_lint_diagnostics] #[track_caller] - pub fn struct_note(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> { - DiagnosticBuilder::new(self, Note, msg) + pub fn struct_note(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_, ()> { + Diag::new(self, Note, msg) } #[rustc_lint_diagnostics] @@ -1222,7 +1212,7 @@ impl DiagCtxt { &self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>, - ) -> DiagnosticBuilder<'_, ()> { + ) -> Diag<'_, ()> { self.struct_note(msg).with_span(span) } @@ -1233,10 +1223,7 @@ impl DiagCtxt { } #[track_caller] - pub fn create_note<'a>( - &'a self, - note: impl IntoDiagnostic<'a, ()>, - ) -> DiagnosticBuilder<'a, ()> { + pub fn create_note<'a>(&'a self, note: impl IntoDiagnostic<'a, ()>) -> Diag<'a, ()> { note.into_diagnostic(self, Note) } @@ -1247,23 +1234,20 @@ impl DiagCtxt { #[rustc_lint_diagnostics] #[track_caller] - pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> { - DiagnosticBuilder::new(self, Help, msg) + pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_, ()> { + Diag::new(self, Help, msg) } #[rustc_lint_diagnostics] #[track_caller] - pub fn struct_failure_note( - &self, - msg: impl Into<DiagnosticMessage>, - ) -> DiagnosticBuilder<'_, ()> { - DiagnosticBuilder::new(self, FailureNote, msg) + pub fn struct_failure_note(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_, ()> { + Diag::new(self, FailureNote, msg) } #[rustc_lint_diagnostics] #[track_caller] - pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> { - DiagnosticBuilder::new(self, Allow, msg) + pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> Diag<'_, ()> { + Diag::new(self, Allow, msg) } #[rustc_lint_diagnostics] @@ -1272,8 +1256,8 @@ impl DiagCtxt { &self, msg: impl Into<DiagnosticMessage>, id: LintExpectationId, - ) -> DiagnosticBuilder<'_, ()> { - DiagnosticBuilder::new(self, Expect(id), msg) + ) -> Diag<'_, ()> { + Diag::new(self, Expect(id), msg) } } @@ -1305,7 +1289,7 @@ impl DiagCtxtInner { } // Return value is only `Some` if the level is `Error` or `DelayedBug`. - fn emit_diagnostic(&mut self, mut diagnostic: Diagnostic) -> Option<ErrorGuaranteed> { + fn emit_diagnostic(&mut self, mut diagnostic: DiagInner) -> Option<ErrorGuaranteed> { assert!(diagnostic.level.can_be_top_or_sub().0); if let Some(expectation_id) = diagnostic.level.get_expectation_id() { @@ -1354,7 +1338,7 @@ impl DiagCtxtInner { #[allow(deprecated)] let guar = ErrorGuaranteed::unchecked_error_guaranteed(); self.delayed_bugs - .push((DelayedDiagnostic::with_backtrace(diagnostic, backtrace), guar)); + .push((DelayedDiagInner::with_backtrace(diagnostic, backtrace), guar)); Some(guar) }; } @@ -1393,7 +1377,7 @@ impl DiagCtxtInner { debug!(?diagnostic); debug!(?self.emitted_diagnostics); - let already_emitted_sub = |sub: &mut SubDiagnostic| { + let already_emitted_sub = |sub: &mut Subdiag| { debug!(?sub); if sub.level != OnceNote && sub.level != OnceHelp { return false; @@ -1477,7 +1461,7 @@ impl DiagCtxtInner { pub fn eagerly_translate<'a>( &self, message: DiagnosticMessage, - args: impl Iterator<Item = DiagnosticArg<'a>>, + args: impl Iterator<Item = DiagArg<'a>>, ) -> SubdiagnosticMessage { SubdiagnosticMessage::Translated(Cow::from(self.eagerly_translate_to_string(message, args))) } @@ -1486,7 +1470,7 @@ impl DiagCtxtInner { pub fn eagerly_translate_to_string<'a>( &self, message: DiagnosticMessage, - args: impl Iterator<Item = DiagnosticArg<'a>>, + args: impl Iterator<Item = DiagArg<'a>>, ) -> String { let args = crate::translation::to_fluent_args(args); self.emitter.translate_message(&message, &args).map_err(Report::new).unwrap().to_string() @@ -1494,7 +1478,7 @@ impl DiagCtxtInner { fn eagerly_translate_for_subdiag( &self, - diag: &Diagnostic, + diag: &DiagInner, msg: impl Into<SubdiagnosticMessage>, ) -> SubdiagnosticMessage { let msg = diag.subdiagnostic_message_to_diagnostic_message(msg); @@ -1514,14 +1498,26 @@ impl DiagCtxtInner { let bugs: Vec<_> = std::mem::take(&mut self.delayed_bugs).into_iter().map(|(b, _)| b).collect(); - // If backtraces are enabled, also print the query stack let backtrace = std::env::var_os("RUST_BACKTRACE").map_or(true, |x| &x != "0"); - for (i, bug) in bugs.into_iter().enumerate() { - if let Some(file) = self.ice_file.as_ref() - && let Ok(mut out) = std::fs::File::options().create(true).append(true).open(file) - { - let _ = write!( - &mut out, + let decorate = backtrace || self.ice_file.is_none(); + let mut out = self + .ice_file + .as_ref() + .and_then(|file| std::fs::File::options().create(true).append(true).open(file).ok()); + + // Put the overall explanation before the `DelayedBug`s, to frame them + // better (e.g. separate warnings from them). Also, use notes, which + // don't count as errors, to avoid possibly triggering + // `-Ztreat-err-as-bug`, which we don't want. + let note1 = "no errors encountered even though delayed bugs were created"; + let note2 = "those delayed bugs will now be shown as internal compiler errors"; + self.emit_diagnostic(DiagInner::new(Note, note1)); + self.emit_diagnostic(DiagInner::new(Note, note2)); + + for bug in bugs { + if let Some(out) = &mut out { + _ = write!( + out, "delayed bug: {}\n{}\n", bug.inner .messages @@ -1532,28 +1528,16 @@ impl DiagCtxtInner { ); } - if i == 0 { - // Put the overall explanation before the `DelayedBug`s, to - // frame them better (e.g. separate warnings from them). Also, - // make it a note so it doesn't count as an error, because that - // could trigger `-Ztreat-err-as-bug`, which we don't want. - let note1 = "no errors encountered even though delayed bugs were created"; - let note2 = "those delayed bugs will now be shown as internal compiler errors"; - self.emit_diagnostic(Diagnostic::new(Note, note1)); - self.emit_diagnostic(Diagnostic::new(Note, note2)); - } - - let mut bug = - if backtrace || self.ice_file.is_none() { bug.decorate(self) } else { bug.inner }; + let mut bug = if decorate { bug.decorate(self) } else { bug.inner }; - // "Undelay" the delayed bugs (into plain `Bug`s). + // "Undelay" the delayed bugs into plain bugs. if bug.level != DelayedBug { // NOTE(eddyb) not panicking here because we're already producing // an ICE, and the more information the merrier. // - // We are at the `Diagnostic`/`DiagCtxtInner` level rather than - // the usual `DiagnosticBuilder`/`DiagCtxt` level, so we must - // augment `bug` in a lower-level fashion. + // We are at the `DiagInner`/`DiagCtxtInner` level rather than + // the usual `Diag`/`DiagCtxt` level, so we must augment `bug` + // in a lower-level fashion. bug.arg("level", bug.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 @@ -1581,20 +1565,20 @@ impl DiagCtxtInner { } } -struct DelayedDiagnostic { - inner: Diagnostic, +struct DelayedDiagInner { + inner: DiagInner, note: Backtrace, } -impl DelayedDiagnostic { - fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self { - DelayedDiagnostic { inner: diagnostic, note: backtrace } +impl DelayedDiagInner { + fn with_backtrace(diagnostic: DiagInner, backtrace: Backtrace) -> Self { + DelayedDiagInner { inner: diagnostic, note: backtrace } } - fn decorate(self, dcx: &DiagCtxtInner) -> Diagnostic { - // We are at the `Diagnostic`/`DiagCtxtInner` level rather than the - // usual `DiagnosticBuilder`/`DiagCtxt` level, so we must construct - // `diag` in a lower-level fashion. + fn decorate(self, dcx: &DiagCtxtInner) -> DiagInner { + // We are at the `DiagInner`/`DiagCtxtInner` level rather than the + // usual `Diag`/`DiagCtxt` level, so we must construct `diag` in a + // lower-level fashion. let mut diag = self.inner; let msg = match self.note.status() { 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. pub fn add_elided_lifetime_in_path_suggestion<G: EmissionGuarantee>( source_map: &SourceMap, - diag: &mut DiagnosticBuilder<'_, G>, + diag: &mut Diag<'_, G>, n: usize, path_span: Span, 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>( - db: &mut DiagnosticBuilder<'a, G>, + diag: &mut Diag<'a, G>, ambiguity: rustc_lint_defs::AmbiguityErrorDiag, ) { - db.span_label(ambiguity.label_span, ambiguity.label_msg); - db.note(ambiguity.note_msg); - db.span_note(ambiguity.b1_span, ambiguity.b1_note_msg); + diag.span_label(ambiguity.label_span, ambiguity.label_msg); + diag.note(ambiguity.note_msg); + diag.span_note(ambiguity.b1_span, ambiguity.b1_note_msg); 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 { - db.help(help_msg); + diag.help(help_msg); } } diff --git a/compiler/rustc_errors/src/translation.rs b/compiler/rustc_errors/src/translation.rs index 5f074dbbbad..1f98ba4c3b9 100644 --- a/compiler/rustc_errors/src/translation.rs +++ b/compiler/rustc_errors/src/translation.rs @@ -1,6 +1,6 @@ use crate::error::{TranslateError, TranslateErrorKind}; use crate::snippet::Style; -use crate::{DiagnosticArg, DiagnosticMessage, FluentBundle}; +use crate::{DiagArg, DiagnosticMessage, FluentBundle}; use rustc_data_structures::sync::Lrc; pub use rustc_error_messages::FluentArgs; use std::borrow::Cow; @@ -12,9 +12,7 @@ use std::error::Report; /// /// Typically performed once for each diagnostic at the start of `emit_diagnostic` and then /// passed around as a reference thereafter. -pub fn to_fluent_args<'iter>( - iter: impl Iterator<Item = DiagnosticArg<'iter>>, -) -> FluentArgs<'static> { +pub fn to_fluent_args<'iter>(iter: impl Iterator<Item = DiagArg<'iter>>) -> FluentArgs<'static> { let mut args = if let Some(size) = iter.size_hint().1 { FluentArgs::with_capacity(size) } else { |
