diff options
| author | bors <bors@rust-lang.org> | 2024-02-29 11:25:45 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2024-02-29 11:25:45 +0000 |
| commit | 5717e52d173f2cc9919900d0013e0e3eeb4afa2c (patch) | |
| tree | 18ad46d4d5135068609a49a284100effdd5d6724 /compiler/rustc_errors/src | |
| parent | d79a5ed90459b2ad382c974f5cdadb5ab586c75d (diff) | |
| parent | 1b41d791f94c7f4b478a317667405ba7e17aa501 (diff) | |
| download | rust-5717e52d173f2cc9919900d0013e0e3eeb4afa2c.tar.gz rust-5717e52d173f2cc9919900d0013e0e3eeb4afa2c.zip | |
Auto merge of #3335 - rust-lang:rustup-2024-02-29, r=saethlin
Automatic Rustup
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 | 270 | ||||
| -rw-r--r-- | compiler/rustc_errors/src/diagnostic_impls.rs | 159 | ||||
| -rw-r--r-- | compiler/rustc_errors/src/emitter.rs | 101 | ||||
| -rw-r--r-- | compiler/rustc_errors/src/error.rs | 3 | ||||
| -rw-r--r-- | compiler/rustc_errors/src/json.rs | 147 | ||||
| -rw-r--r-- | compiler/rustc_errors/src/json/tests.rs | 12 | ||||
| -rw-r--r-- | compiler/rustc_errors/src/lib.rs | 211 | ||||
| -rw-r--r-- | compiler/rustc_errors/src/translation.rs | 6 |
9 files changed, 398 insertions, 521 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..01f36ad6a78 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,15 +93,15 @@ 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 } } @@ -112,7 +112,7 @@ impl EmissionGuarantee for rustc_span::fatal_error::FatalError { 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 +120,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 +157,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 +165,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 +213,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 +232,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 +261,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 +275,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 +288,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 +309,7 @@ impl Diagnostic { args: Default::default(), sort_span: DUMMY_SP, is_lint: None, - emitted_at: DiagnosticLocation::caller(), + emitted_at: DiagLocation::caller(), } } @@ -374,7 +374,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 +390,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 +401,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 +413,9 @@ impl Diagnostic { &[(DiagnosticMessage, Style)], &Option<ErrCode>, &MultiSpan, - &[SubDiagnostic], + &[Subdiag], &Result<Vec<CodeSuggestion>, SuggestionsDisabled>, - Vec<(&DiagnosticArgName, &DiagnosticArgValue)>, + Vec<(&DiagArgName, &DiagArgValue)>, &Option<IsLint>, ) { ( @@ -433,7 +433,7 @@ impl Diagnostic { } } -impl Hash for Diagnostic { +impl Hash for DiagInner { fn hash<H>(&self, state: &mut H) where H: Hasher, @@ -442,7 +442,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 +451,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 +541,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 +556,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 +638,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 +648,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 +709,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 +717,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 +729,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 +748,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 +767,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 +780,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 +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( &mut self, msg: impl Into<SubdiagnosticMessage>, @@ -948,7 +942,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 +987,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 +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 /// multiple parts. - /// See also [`DiagnosticBuilder::multipart_suggestion()`]. + /// See also [`Diag::multipart_suggestion()`]. pub fn multipart_suggestions( &mut self, msg: impl Into<SubdiagnosticMessage>, @@ -1199,7 +1193,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 +1225,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 +1251,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 +1313,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..5637c05d04c 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,16 +17,15 @@ 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; - use derive_setters::Setters; use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet}; use rustc_data_structures::sync::{DynSend, IntoDynSyncSend, Lrc}; use rustc_error_messages::{FluentArgs, SpanLabel}; +use rustc_lint_defs::pluralize; use rustc_span::hygiene::{ExpnKind, MacroKind}; use std::borrow::Cow; use std::cmp::{max, min, Reverse}; @@ -35,7 +34,7 @@ use std::io::prelude::*; use std::io::{self, IsTerminal}; use std::iter; use std::path::Path; -use termcolor::{Ansi, Buffer, BufferWriter, ColorChoice, ColorSpec, StandardStream}; +use termcolor::{Buffer, BufferWriter, ColorChoice, ColorSpec, StandardStream}; use termcolor::{Color, WriteColor}; /// Default column width, used in tests and when terminal dimensions cannot be determined. @@ -58,18 +57,6 @@ impl HumanReadableErrorType { HumanReadableErrorType::AnnotateSnippet(cc) => (false, cc), } } - pub fn new_emitter( - self, - mut dst: Box<dyn WriteColor + Send>, - fallback_bundle: LazyFallbackBundle, - ) -> HumanEmitter { - let (short, color_config) = self.unzip(); - let color = color_config.suggests_using_colors(); - if !dst.supports_color() && color { - dst = Box::new(Ansi::new(dst)); - } - HumanEmitter::new(dst, fallback_bundle).short_message(short) - } } #[derive(Clone, Copy, Debug)] @@ -130,8 +117,8 @@ impl Margin { fn was_cut_right(&self, line_len: usize) -> bool { let right = if self.computed_right == self.span_right || self.computed_right == self.label_right { - // Account for the "..." padding given above. Otherwise we end up with code lines that - // do fit but end in "..." as if they were trimmed. + // Account for the "..." padding given above. Otherwise we end up with code lines + // that do fit but end in "..." as if they were trimmed. self.computed_right - 6 } else { self.computed_right @@ -194,7 +181,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 +189,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 +216,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 +290,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 +337,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 +349,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 +448,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 +501,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 +580,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); @@ -632,12 +615,6 @@ impl ColorConfig { ColorConfig::Auto => ColorChoice::Never, } } - fn suggests_using_colors(self) -> bool { - match self { - ColorConfig::Always | ColorConfig::Auto => true, - ColorConfig::Never => false, - } - } } /// Handles the writing of `HumanReadableErrorType::Default` and `HumanReadableErrorType::Short` @@ -661,19 +638,14 @@ pub struct HumanEmitter { } #[derive(Debug)] -pub struct FileWithAnnotatedLines { - pub file: Lrc<SourceFile>, - pub lines: Vec<Line>, +pub(crate) struct FileWithAnnotatedLines { + pub(crate) file: Lrc<SourceFile>, + pub(crate) lines: Vec<Line>, multiline_depth: usize, } impl HumanEmitter { - pub fn stderr(color_config: ColorConfig, fallback_bundle: LazyFallbackBundle) -> HumanEmitter { - let dst = from_stderr(color_config); - Self::create(dst, fallback_bundle) - } - - fn create(dst: Destination, fallback_bundle: LazyFallbackBundle) -> HumanEmitter { + pub fn new(dst: Destination, fallback_bundle: LazyFallbackBundle) -> HumanEmitter { HumanEmitter { dst: IntoDynSyncSend(dst), sm: None, @@ -690,13 +662,6 @@ impl HumanEmitter { } } - pub fn new( - dst: Box<dyn WriteColor + Send>, - fallback_bundle: LazyFallbackBundle, - ) -> HumanEmitter { - Self::create(dst, fallback_bundle) - } - fn maybe_anonymized(&self, line_num: usize) -> Cow<'static, str> { if self.ui_testing { Cow::Borrowed(ANONYMIZED_LINE_NUM) @@ -728,8 +693,9 @@ impl HumanEmitter { .skip(left) .take_while(|ch| { // Make sure that the trimming on the right will fall within the terminal width. - // FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` is. - // For now, just accept that sometimes the code line will be longer than desired. + // FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` + // is. For now, just accept that sometimes the code line will be longer than + // desired. let next = unicode_width::UnicodeWidthChar::width(*ch).unwrap_or(1); if taken + next > right - left { return false; @@ -1235,7 +1201,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 +1297,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 +2064,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() @@ -2232,8 +2198,8 @@ impl HumanEmitter { buffer.puts(*row_num - 1, max_line_num_len + 3, &line, Style::NoStyle); *row_num += 1; } - // If the last line is exactly equal to the line we need to add, we can skip both of them. - // This allows us to avoid output like the following: + // If the last line is exactly equal to the line we need to add, we can skip both of + // them. This allows us to avoid output like the following: // 2 - & // 2 + if true { true } else { false } // 3 - if true { true } else { false } @@ -2590,6 +2556,7 @@ fn num_overlap( let extra = if inclusive { 1 } else { 0 }; (b_start..b_end + extra).contains(&a_start) || (a_start..a_end + extra).contains(&b_start) } + fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool { num_overlap( a1.start_col.display, @@ -2636,7 +2603,7 @@ fn emit_to_destination( Ok(()) } -pub type Destination = Box<(dyn WriteColor + Send)>; +pub type Destination = Box<dyn WriteColor + Send>; struct Buffy { buffer_writer: BufferWriter, @@ -2678,7 +2645,7 @@ impl WriteColor for Buffy { } } -fn from_stderr(color: ColorConfig) -> Destination { +pub fn stderr_destination(color: ColorConfig) -> Destination { let choice = color.to_color_choice(); // On Windows we'll be performing global synchronization on the entire // system for emitting rustc errors, so there's no need to buffer diff --git a/compiler/rustc_errors/src/error.rs b/compiler/rustc_errors/src/error.rs index ec0a2fe8cd8..ca818a4d832 100644 --- a/compiler/rustc_errors/src/error.rs +++ b/compiler/rustc_errors/src/error.rs @@ -23,9 +23,11 @@ impl<'args> TranslateError<'args> { pub fn message(id: &'args Cow<'args, str>, args: &'args FluentArgs<'args>) -> Self { Self::One { id, args, kind: TranslateErrorKind::MessageMissing } } + pub fn primary(id: &'args Cow<'args, str>, args: &'args FluentArgs<'args>) -> Self { Self::One { id, args, kind: TranslateErrorKind::PrimaryBundleMissing } } + pub fn attribute( id: &'args Cow<'args, str>, args: &'args FluentArgs<'args>, @@ -33,6 +35,7 @@ impl<'args> TranslateError<'args> { ) -> Self { Self::One { id, args, kind: TranslateErrorKind::AttributeMissing { attr } } } + pub fn value(id: &'args Cow<'args, str>, args: &'args FluentArgs<'args>) -> Self { Self::One { id, args, kind: TranslateErrorKind::ValueMissing } } diff --git a/compiler/rustc_errors/src/json.rs b/compiler/rustc_errors/src/json.rs index e57b414c52d..bc1822f83fc 100644 --- a/compiler/rustc_errors/src/json.rs +++ b/compiler/rustc_errors/src/json.rs @@ -9,42 +9,49 @@ // FIXME: spec the JSON output properly. -use rustc_span::source_map::{FilePathMapping, SourceMap}; -use termcolor::{ColorSpec, WriteColor}; - -use crate::emitter::{should_show_source_code, Emitter, HumanReadableErrorType}; +use crate::emitter::{ + should_show_source_code, ColorConfig, Destination, Emitter, HumanEmitter, + HumanReadableErrorType, +}; 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; - +use derive_setters::Setters; use rustc_data_structures::sync::{IntoDynSyncSend, Lrc}; use rustc_error_messages::FluentArgs; +use rustc_lint_defs::Applicability; use rustc_span::hygiene::ExpnData; +use rustc_span::source_map::SourceMap; use rustc_span::Span; +use serde::Serialize; use std::error::Report; use std::io::{self, Write}; use std::path::Path; use std::sync::{Arc, Mutex}; use std::vec; - -use serde::Serialize; +use termcolor::{ColorSpec, WriteColor}; #[cfg(test)] mod tests; +#[derive(Setters)] pub struct JsonEmitter { + #[setters(skip)] dst: IntoDynSyncSend<Box<dyn Write + Send>>, registry: Option<Registry>, + #[setters(skip)] sm: Lrc<SourceMap>, fluent_bundle: Option<Lrc<FluentBundle>>, + #[setters(skip)] fallback_bundle: LazyFallbackBundle, + #[setters(skip)] pretty: bool, ui_testing: bool, ignored_directories_in_source_blocks: Vec<String>, + #[setters(skip)] json_rendered: HumanReadableErrorType, diagnostic_width: Option<usize>, macro_backtrace: bool, @@ -53,98 +60,30 @@ pub struct JsonEmitter { } impl JsonEmitter { - pub fn stderr( - registry: Option<Registry>, - source_map: Lrc<SourceMap>, - fluent_bundle: Option<Lrc<FluentBundle>>, - fallback_bundle: LazyFallbackBundle, - pretty: bool, - json_rendered: HumanReadableErrorType, - diagnostic_width: Option<usize>, - macro_backtrace: bool, - track_diagnostics: bool, - terminal_url: TerminalUrl, - ) -> JsonEmitter { - JsonEmitter { - dst: IntoDynSyncSend(Box::new(io::BufWriter::new(io::stderr()))), - registry, - sm: source_map, - fluent_bundle, - fallback_bundle, - pretty, - ui_testing: false, - ignored_directories_in_source_blocks: Vec::new(), - json_rendered, - diagnostic_width, - macro_backtrace, - track_diagnostics, - terminal_url, - } - } - - pub fn basic( - pretty: bool, - json_rendered: HumanReadableErrorType, - fluent_bundle: Option<Lrc<FluentBundle>>, - fallback_bundle: LazyFallbackBundle, - diagnostic_width: Option<usize>, - macro_backtrace: bool, - track_diagnostics: bool, - terminal_url: TerminalUrl, - ) -> JsonEmitter { - let file_path_mapping = FilePathMapping::empty(); - JsonEmitter::stderr( - None, - Lrc::new(SourceMap::new(file_path_mapping)), - fluent_bundle, - fallback_bundle, - pretty, - json_rendered, - diagnostic_width, - macro_backtrace, - track_diagnostics, - terminal_url, - ) - } - pub fn new( dst: Box<dyn Write + Send>, - registry: Option<Registry>, - source_map: Lrc<SourceMap>, - fluent_bundle: Option<Lrc<FluentBundle>>, + sm: Lrc<SourceMap>, fallback_bundle: LazyFallbackBundle, pretty: bool, json_rendered: HumanReadableErrorType, - diagnostic_width: Option<usize>, - macro_backtrace: bool, - track_diagnostics: bool, - terminal_url: TerminalUrl, ) -> JsonEmitter { JsonEmitter { dst: IntoDynSyncSend(dst), - registry, - sm: source_map, - fluent_bundle, + registry: None, + sm, + fluent_bundle: None, fallback_bundle, pretty, ui_testing: false, ignored_directories_in_source_blocks: Vec::new(), json_rendered, - diagnostic_width, - macro_backtrace, - track_diagnostics, - terminal_url, + diagnostic_width: None, + macro_backtrace: false, + track_diagnostics: false, + terminal_url: TerminalUrl::No, } } - pub fn ui_testing(self, ui_testing: bool) -> Self { - Self { ui_testing, ..self } - } - - pub fn ignored_directories_in_source_blocks(self, value: Vec<String>) -> Self { - Self { ignored_directories_in_source_blocks: value, ..self } - } - fn emit(&mut self, val: EmitTyped<'_>) -> io::Result<()> { if self.pretty { serde_json::to_writer_pretty(&mut *self.dst, &val)? @@ -162,7 +101,7 @@ enum EmitTyped<'a> { Diagnostic(Diagnostic), Artifact(ArtifactNotification<'a>), FutureIncompat(FutureIncompatReport<'a>), - UnusedExtern(UnusedExterns<'a, 'a, 'a>), + UnusedExtern(UnusedExterns<'a>), } impl Translate for JsonEmitter { @@ -176,7 +115,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 +131,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| { @@ -332,15 +271,16 @@ struct FutureIncompatReport<'a> { // We could unify this struct the one in rustdoc but they have different // ownership semantics, so doing so would create wasteful allocations. #[derive(Serialize)] -struct UnusedExterns<'a, 'b, 'c> { +struct UnusedExterns<'a> { /// The severity level of the unused dependencies lint lint_level: &'a str, /// List of unused externs by their names. - unused_extern_names: &'b [&'c str], + unused_extern_names: &'a [&'a str], } impl Diagnostic { - fn from_errors_diagnostic(diag: crate::Diagnostic, je: &JsonEmitter) -> Diagnostic { + /// Converts from `rustc_errors::DiagInner` to `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 = @@ -405,9 +345,14 @@ impl Diagnostic { .collect(); let buf = BufWriter::default(); - let output = buf.clone(); - je.json_rendered - .new_emitter(Box::new(buf), je.fallback_bundle.clone()) + let mut dst: Destination = Box::new(buf.clone()); + let (short, color_config) = je.json_rendered.unzip(); + match color_config { + ColorConfig::Always | ColorConfig::Auto => dst = Box::new(termcolor::Ansi::new(dst)), + ColorConfig::Never => {} + } + HumanEmitter::new(dst, je.fallback_bundle.clone()) + .short_message(short) .sm(Some(je.sm.clone())) .fluent_bundle(je.fluent_bundle.clone()) .diagnostic_width(je.diagnostic_width) @@ -417,8 +362,8 @@ impl Diagnostic { .ui_testing(je.ui_testing) .ignored_directories_in_source_blocks(je.ignored_directories_in_source_blocks.clone()) .emit_diagnostic(diag); - let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap(); - let output = String::from_utf8(output).unwrap(); + let buf = Arc::try_unwrap(buf.0).unwrap().into_inner().unwrap(); + let buf = String::from_utf8(buf).unwrap(); Diagnostic { message: translated_message.to_string(), @@ -426,21 +371,21 @@ impl Diagnostic { level, spans, children, - rendered: Some(output), + rendered: Some(buf), } } 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/json/tests.rs b/compiler/rustc_errors/src/json/tests.rs index 303de0a93f6..80b4d2bf75c 100644 --- a/compiler/rustc_errors/src/json/tests.rs +++ b/compiler/rustc_errors/src/json/tests.rs @@ -1,7 +1,7 @@ use super::*; -use crate::emitter::ColorConfig; use crate::DiagCtxt; +use rustc_span::source_map::FilePathMapping; use rustc_span::BytePos; use std::str; @@ -48,20 +48,14 @@ fn test_positions(code: &str, span: (u32, u32), expected_output: SpanTestData) { let output = Arc::new(Mutex::new(Vec::new())); let je = JsonEmitter::new( Box::new(Shared { data: output.clone() }), - None, sm, - None, fallback_bundle, - true, + true, // pretty HumanReadableErrorType::Short(ColorConfig::Never), - None, - false, - false, - TerminalUrl::No, ); let span = Span::with_root_ctxt(BytePos(span.0), BytePos(span.1)); - let dcx = DiagCtxt::with_emitter(Box::new(je)); + let dcx = DiagCtxt::new(Box::new(je)); dcx.span_err(span, "foo"); let bytes = output.lock().unwrap(); diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 3f667e264e8..a5e6aed13eb 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::{ @@ -60,11 +59,11 @@ pub use snippet::Style; // See https://github.com/rust-lang/rust/pull/115393. pub use termcolor::{Color, ColorSpec, WriteColor}; -use emitter::{is_case_difference, DynEmitter, Emitter, HumanEmitter}; +use emitter::{is_case_difference, DynEmitter, Emitter}; use registry::Registry; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::stable_hasher::{Hash128, StableHasher}; -use rustc_data_structures::sync::{Lock, Lrc}; +use rustc_data_structures::sync::Lock; use rustc_data_structures::AtomicRef; use rustc_lint_defs::LintExpectationId; use rustc_span::source_map::SourceMap; @@ -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" } @@ -218,10 +217,10 @@ impl CodeSuggestion { use rustc_span::{CharPos, Pos}; - /// Extracts a substring from the provided `line_opt` based on the specified low and high indices, - /// appends it to the given buffer `buf`, and returns the count of newline characters in the substring - /// for accurate highlighting. - /// If `line_opt` is `None`, a newline character is appended to the buffer, and 0 is returned. + /// Extracts a substring from the provided `line_opt` based on the specified low and high + /// indices, appends it to the given buffer `buf`, and returns the count of newline + /// characters in the substring for accurate highlighting. If `line_opt` is `None`, a + /// newline character is appended to the buffer, and 0 is returned. /// /// ## Returns /// @@ -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 - /// the lint level. [`LintExpectationId`]s created early during the compilation + /// 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)] @@ -587,13 +586,6 @@ impl Drop for DiagCtxtInner { } impl DiagCtxt { - pub fn with_tty_emitter( - sm: Option<Lrc<SourceMap>>, - fallback_bundle: LazyFallbackBundle, - ) -> Self { - let emitter = Box::new(HumanEmitter::stderr(ColorConfig::Auto, fallback_bundle).sm(sm)); - Self::with_emitter(emitter) - } pub fn disable_warnings(mut self) -> Self { self.inner.get_mut().flags.can_emit_warnings = false; self @@ -609,7 +601,7 @@ impl DiagCtxt { self } - pub fn with_emitter(emitter: Box<DynEmitter>) -> Self { + pub fn new(emitter: Box<DynEmitter>) -> Self { Self { inner: Lock::new(DiagCtxtInner { flags: DiagCtxtFlags { can_emit_warnings: true, ..Default::default() }, @@ -640,7 +632,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 +642,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 +710,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 +728,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 +738,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 +816,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 +856,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 +888,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 +992,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 +1008,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 +1019,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 +1030,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 +1046,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 +1060,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 +1073,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 +1088,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 +1104,7 @@ impl DiagCtxt { &self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>, - ) -> DiagnosticBuilder<'_> { + ) -> Diag<'_> { self.struct_err(msg).with_span(span) } @@ -1133,7 +1119,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 +1132,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 +1146,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 +1167,7 @@ impl DiagCtxt { &self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>, - ) -> DiagnosticBuilder<'_, ()> { + ) -> Diag<'_, ()> { self.struct_warn(msg).with_span(span) } @@ -1192,10 +1178,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 +1189,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 +1205,7 @@ impl DiagCtxt { &self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>, - ) -> DiagnosticBuilder<'_, ()> { + ) -> Diag<'_, ()> { self.struct_note(msg).with_span(span) } @@ -1233,10 +1216,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 +1227,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 +1249,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 +1282,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 +1331,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 +1370,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 +1454,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 +1463,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 +1471,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); @@ -1539,8 +1516,8 @@ impl DiagCtxtInner { // 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)); + self.emit_diagnostic(DiagInner::new(Note, note1)); + self.emit_diagnostic(DiagInner::new(Note, note2)); } let mut bug = @@ -1551,9 +1528,9 @@ impl DiagCtxtInner { // 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 +1558,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 +1727,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 +1749,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 { |
