Rollup merge of #118933 - nnethercote:cleanup-errors-even-more, r=compiler-errors

Cleanup errors handlers even more

A sequel to #118587.

r? `@compiler-errors`
This commit is contained in:
Jubilee 2023-12-14 16:07:48 -08:00 committed by GitHub
commit 9e872b7cd8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 117 additions and 113 deletions

View File

@ -2502,8 +2502,8 @@ mod error {
if !self.errors.buffered.is_empty() { if !self.errors.buffered.is_empty() {
self.errors.buffered.sort_by_key(|diag| diag.sort_span); self.errors.buffered.sort_by_key(|diag| diag.sort_span);
for mut diag in self.errors.buffered.drain(..) { for diag in self.errors.buffered.drain(..) {
self.infcx.tcx.sess.diagnostic().emit_diagnostic(&mut diag); self.infcx.tcx.sess.diagnostic().emit_diagnostic(diag);
} }
} }

View File

@ -453,7 +453,7 @@ impl<'a> IntoDiagnostic<'a> for EnvNotDefinedWithUserMessage {
rustc::untranslatable_diagnostic, rustc::untranslatable_diagnostic,
reason = "cannot translate user-provided messages" reason = "cannot translate user-provided messages"
)] )]
let mut diag = handler.struct_diagnostic(self.msg_from_user.to_string()); let mut diag = handler.struct_err(self.msg_from_user.to_string());
diag.set_span(self.span); diag.set_span(self.span);
diag diag
} }
@ -804,7 +804,7 @@ pub(crate) struct AsmClobberNoReg {
impl<'a> IntoDiagnostic<'a> for AsmClobberNoReg { impl<'a> IntoDiagnostic<'a> for AsmClobberNoReg {
fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> { fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
let mut diag = let mut diag =
handler.struct_diagnostic(crate::fluent_generated::builtin_macros_asm_clobber_no_reg); handler.struct_err(crate::fluent_generated::builtin_macros_asm_clobber_no_reg);
diag.set_span(self.spans.clone()); diag.set_span(self.spans.clone());
// eager translation as `span_labels` takes `AsRef<str>` // eager translation as `span_labels` takes `AsRef<str>`
let lbl1 = handler.eagerly_translate_to_string( let lbl1 = handler.eagerly_translate_to_string(

View File

@ -107,7 +107,8 @@ impl IntoDiagnostic<'_, FatalError> for ParseTargetMachineConfig<'_> {
let (message, _) = diag.styled_message().first().expect("`LlvmError` with no message"); let (message, _) = diag.styled_message().first().expect("`LlvmError` with no message");
let message = handler.eagerly_translate_to_string(message.clone(), diag.args()); let message = handler.eagerly_translate_to_string(message.clone(), diag.args());
let mut diag = handler.struct_diagnostic(fluent::codegen_llvm_parse_target_machine_config); let mut diag =
handler.struct_almost_fatal(fluent::codegen_llvm_parse_target_machine_config);
diag.set_arg("error", message); diag.set_arg("error", message);
diag diag
} }

View File

@ -1848,7 +1848,7 @@ impl SharedEmitterMain {
d.code(code); d.code(code);
} }
d.replace_args(diag.args); d.replace_args(diag.args);
handler.emit_diagnostic(&mut d); handler.emit_diagnostic(d);
} }
Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => { Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
let msg = msg.strip_prefix("error: ").unwrap_or(&msg).to_string(); let msg = msg.strip_prefix("error: ").unwrap_or(&msg).to_string();

View File

@ -277,8 +277,8 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> {
// "secondary" errors if they occurred. // "secondary" errors if they occurred.
let secondary_errors = mem::take(&mut self.secondary_errors); let secondary_errors = mem::take(&mut self.secondary_errors);
if self.error_emitted.is_none() { if self.error_emitted.is_none() {
for mut error in secondary_errors { for error in secondary_errors {
self.tcx.sess.diagnostic().emit_diagnostic(&mut error); self.tcx.sess.diagnostic().emit_diagnostic(error);
} }
} else { } else {
assert!(self.tcx.sess.has_errors().is_some()); assert!(self.tcx.sess.has_errors().is_some());

View File

@ -132,7 +132,7 @@ impl EmissionGuarantee for ErrorGuaranteed {
DiagnosticBuilderState::Emittable(handler) => { DiagnosticBuilderState::Emittable(handler) => {
db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation; db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
let guar = handler.emit_diagnostic(&mut db.inner.diagnostic); let guar = handler.emit_diagnostic_without_consuming(&mut db.inner.diagnostic);
// Only allow a guarantee if the `level` wasn't switched to a // Only allow a guarantee if the `level` wasn't switched to a
// non-error - the field isn't `pub`, but the whole `Diagnostic` // non-error - the field isn't `pub`, but the whole `Diagnostic`
@ -181,7 +181,7 @@ impl EmissionGuarantee for () {
DiagnosticBuilderState::Emittable(handler) => { DiagnosticBuilderState::Emittable(handler) => {
db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation; db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
handler.emit_diagnostic(&mut db.inner.diagnostic); handler.emit_diagnostic_without_consuming(&mut db.inner.diagnostic);
} }
// `.emit()` was previously called, disallowed from repeating it. // `.emit()` was previously called, disallowed from repeating it.
DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {} DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
@ -207,7 +207,7 @@ impl EmissionGuarantee for Noted {
// First `.emit()` call, the `&Handler` is still available. // First `.emit()` call, the `&Handler` is still available.
DiagnosticBuilderState::Emittable(handler) => { DiagnosticBuilderState::Emittable(handler) => {
db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation; db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
handler.emit_diagnostic(&mut db.inner.diagnostic); handler.emit_diagnostic_without_consuming(&mut db.inner.diagnostic);
} }
// `.emit()` was previously called, disallowed from repeating it. // `.emit()` was previously called, disallowed from repeating it.
DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {} DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
@ -236,7 +236,7 @@ impl EmissionGuarantee for Bug {
DiagnosticBuilderState::Emittable(handler) => { DiagnosticBuilderState::Emittable(handler) => {
db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation; db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
handler.emit_diagnostic(&mut db.inner.diagnostic); handler.emit_diagnostic_without_consuming(&mut db.inner.diagnostic);
} }
// `.emit()` was previously called, disallowed from repeating it. // `.emit()` was previously called, disallowed from repeating it.
DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {} DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
@ -260,7 +260,7 @@ impl EmissionGuarantee for ! {
DiagnosticBuilderState::Emittable(handler) => { DiagnosticBuilderState::Emittable(handler) => {
db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation; db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
handler.emit_diagnostic(&mut db.inner.diagnostic); handler.emit_diagnostic_without_consuming(&mut db.inner.diagnostic);
} }
// `.emit()` was previously called, disallowed from repeating it. // `.emit()` was previously called, disallowed from repeating it.
DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {} DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
@ -284,7 +284,7 @@ impl EmissionGuarantee for rustc_span::fatal_error::FatalError {
DiagnosticBuilderState::Emittable(handler) => { DiagnosticBuilderState::Emittable(handler) => {
db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation; db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
handler.emit_diagnostic(&mut db.inner.diagnostic); handler.emit_diagnostic_without_consuming(&mut db.inner.diagnostic);
} }
// `.emit()` was previously called, disallowed from repeating it. // `.emit()` was previously called, disallowed from repeating it.
DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {} DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
@ -365,7 +365,9 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
} }
} }
/// Emit the diagnostic. /// Emit the diagnostic. Does not consume `self`, which may be surprising,
/// but there are various places that rely on continuing to use `self`
/// after calling `emit`.
#[track_caller] #[track_caller]
pub fn emit(&mut self) -> G { pub fn emit(&mut self) -> G {
G::diagnostic_builder_emit_producing_guarantee(self) G::diagnostic_builder_emit_producing_guarantee(self)
@ -640,13 +642,13 @@ impl Drop for DiagnosticBuilderInner<'_> {
// No `.emit()` or `.cancel()` calls. // No `.emit()` or `.cancel()` calls.
DiagnosticBuilderState::Emittable(handler) => { DiagnosticBuilderState::Emittable(handler) => {
if !panicking() { if !panicking() {
handler.emit_diagnostic(&mut Diagnostic::new( handler.emit_diagnostic(Diagnostic::new(
Level::Bug, Level::Bug,
DiagnosticMessage::from( DiagnosticMessage::from(
"the following error was constructed but not emitted", "the following error was constructed but not emitted",
), ),
)); ));
handler.emit_diagnostic(&mut self.diagnostic); handler.emit_diagnostic_without_consuming(&mut self.diagnostic);
panic!("error was constructed but not emitted"); panic!("error was constructed but not emitted");
} }
} }

View File

@ -581,7 +581,7 @@ impl Emitter for SilentEmitter {
if let Some(ref note) = self.fatal_note { if let Some(ref note) = self.fatal_note {
d.note(note.clone()); d.note(note.clone());
} }
self.fatal_handler.emit_diagnostic(&mut d); self.fatal_handler.emit_diagnostic(d);
} }
} }
} }

View File

@ -585,11 +585,6 @@ impl Handler {
self self
} }
pub fn treat_err_as_bug(mut self, treat_err_as_bug: NonZeroUsize) -> Self {
self.inner.get_mut().flags.treat_err_as_bug = Some(treat_err_as_bug);
self
}
pub fn with_flags(mut self, flags: HandlerFlags) -> Self { pub fn with_flags(mut self, flags: HandlerFlags) -> Self {
self.inner.get_mut().flags = flags; self.inner.get_mut().flags = flags;
self self
@ -727,7 +722,12 @@ impl Handler {
self.inner.borrow_mut().emit_stashed_diagnostics() self.inner.borrow_mut().emit_stashed_diagnostics()
} }
/// Construct a builder with the `msg` at the level appropriate for the specific `EmissionGuarantee`. /// Construct a builder with the `msg` at the level appropriate for the
/// specific `EmissionGuarantee`.
///
/// Note: this is necessary for `derive(Diagnostic)`, but shouldn't be used
/// outside of that. Instead use `struct_err`, `struct_warn`, etc., which
/// make the diagnostic kind clearer.
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn struct_diagnostic<G: EmissionGuarantee>( pub fn struct_diagnostic<G: EmissionGuarantee>(
@ -942,13 +942,23 @@ impl Handler {
result result
} }
/// Construct a builder at the `Error` level with the `msg`. /// Construct a builder at the `Fatal` level with the `msg`.
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> { pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
DiagnosticBuilder::new(self, Level::Fatal, msg) DiagnosticBuilder::new(self, Level::Fatal, msg)
} }
/// Construct a builder at the `Fatal` level with the `msg`, that doesn't abort.
#[rustc_lint_diagnostics]
#[track_caller]
pub fn struct_almost_fatal(
&self,
msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, FatalError> {
DiagnosticBuilder::new(self, Level::Fatal, msg)
}
/// Construct a builder at the `Help` level with the `msg`. /// Construct a builder at the `Help` level with the `msg`.
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> { pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
@ -965,8 +975,7 @@ impl Handler {
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! { pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span); self.struct_span_fatal(span, msg).emit()
FatalError.raise()
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
@ -977,8 +986,7 @@ impl Handler {
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
code: DiagnosticId, code: DiagnosticId,
) -> ! { ) -> ! {
self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span); self.struct_span_fatal_with_code(span, msg, code).emit()
FatalError.raise()
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
@ -988,7 +996,7 @@ impl Handler {
span: impl Into<MultiSpan>, span: impl Into<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> ErrorGuaranteed { ) -> ErrorGuaranteed {
self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span).unwrap() self.struct_span_err(span, msg).emit()
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
@ -999,17 +1007,13 @@ impl Handler {
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
code: DiagnosticId, code: DiagnosticId,
) -> ErrorGuaranteed { ) -> ErrorGuaranteed {
self.emit_diag_at_span( self.struct_span_err_with_code(span, msg, code).emit()
Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
span,
)
.unwrap()
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) { pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
self.emit_diag_at_span(Diagnostic::new(Warning(None), msg), span); self.struct_span_warn(span, msg).emit()
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
@ -1020,10 +1024,10 @@ impl Handler {
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
code: DiagnosticId, code: DiagnosticId,
) { ) {
self.emit_diag_at_span(Diagnostic::new_with_code(Warning(None), Some(code), msg), span); self.struct_span_warn_with_code(span, msg, code).emit()
} }
pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: impl Into<String>) -> ! { pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
self.inner.borrow_mut().span_bug(span, msg) self.inner.borrow_mut().span_bug(span, msg)
} }
@ -1035,7 +1039,7 @@ impl Handler {
pub fn span_delayed_bug( pub fn span_delayed_bug(
&self, &self,
sp: impl Into<MultiSpan>, sp: impl Into<MultiSpan>,
msg: impl Into<String>, msg: impl Into<DiagnosticMessage>,
) -> ErrorGuaranteed { ) -> ErrorGuaranteed {
let mut inner = self.inner.borrow_mut(); let mut inner = self.inner.borrow_mut();
@ -1046,11 +1050,11 @@ impl Handler {
inner.err_count + inner.lint_err_count + inner.delayed_bug_count() + 1 >= c.get() inner.err_count + inner.lint_err_count + inner.delayed_bug_count() + 1 >= c.get()
}) { }) {
// FIXME: don't abort here if report_delayed_bugs is off // FIXME: don't abort here if report_delayed_bugs is off
inner.span_bug(sp, msg.into()); inner.span_bug(sp, msg);
} }
let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg.into()); let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
diagnostic.set_span(sp.into()); diagnostic.set_span(sp);
inner.emit_diagnostic(&mut diagnostic).unwrap() inner.emit_diagnostic(diagnostic).unwrap()
} }
// FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
@ -1060,7 +1064,7 @@ impl Handler {
let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg); let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
if inner.flags.report_delayed_bugs { if inner.flags.report_delayed_bugs {
inner.emit_diagnostic(&mut diagnostic); inner.emit_diagnostic_without_consuming(&mut diagnostic);
} }
let backtrace = std::backtrace::Backtrace::capture(); let backtrace = std::backtrace::Backtrace::capture();
inner.good_path_delayed_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace)); inner.good_path_delayed_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
@ -1068,20 +1072,22 @@ impl Handler {
#[track_caller] #[track_caller]
pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) { pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
self.emit_diag_at_span(Diagnostic::new(Bug, msg), span); let mut diag = Diagnostic::new(Bug, msg);
diag.set_span(span);
self.emit_diagnostic(diag);
} }
#[track_caller] #[track_caller]
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
pub fn span_note(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) { pub fn span_note(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
self.emit_diag_at_span(Diagnostic::new(Note, msg), span); self.struct_span_note(span, msg).emit()
} }
#[track_caller] #[track_caller]
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
pub fn struct_span_note( pub fn struct_span_note(
&self, &self,
span: Span, span: impl Into<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, ()> { ) -> DiagnosticBuilder<'_, ()> {
let mut db = DiagnosticBuilder::new(self, Note, msg); let mut db = DiagnosticBuilder::new(self, Note, msg);
@ -1091,22 +1097,22 @@ impl Handler {
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> ! { pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> ! {
DiagnosticBuilder::<FatalError>::new(self, Fatal, msg).emit().raise() self.struct_fatal(msg).emit()
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed { pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
DiagnosticBuilder::<ErrorGuaranteed>::new(self, Error { lint: false }, msg).emit() self.struct_err(msg).emit()
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
pub fn warn(&self, msg: impl Into<DiagnosticMessage>) { pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
DiagnosticBuilder::<()>::new(self, Warning(None), msg).emit(); self.struct_warn(msg).emit()
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
pub fn note(&self, msg: impl Into<DiagnosticMessage>) { pub fn note(&self, msg: impl Into<DiagnosticMessage>) {
DiagnosticBuilder::<()>::new(self, Note, msg).emit(); self.struct_note(msg).emit()
} }
pub fn bug(&self, msg: impl Into<DiagnosticMessage>) -> ! { pub fn bug(&self, msg: impl Into<DiagnosticMessage>) -> ! {
@ -1181,10 +1187,10 @@ impl Handler {
DiagnosticMessage::Str(warnings), DiagnosticMessage::Str(warnings),
)), )),
(_, 0) => { (_, 0) => {
inner.emit_diagnostic(&mut Diagnostic::new(Fatal, errors)); inner.emit_diagnostic(Diagnostic::new(Fatal, errors));
} }
(_, _) => { (_, _) => {
inner.emit_diagnostic(&mut Diagnostic::new(Fatal, format!("{errors}; {warnings}"))); inner.emit_diagnostic(Diagnostic::new(Fatal, format!("{errors}; {warnings}")));
} }
} }
@ -1251,8 +1257,17 @@ impl Handler {
self.inner.borrow_mut().emitter.emit_diagnostic(&db); self.inner.borrow_mut().emitter.emit_diagnostic(&db);
} }
pub fn emit_diagnostic(&self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> { pub fn emit_diagnostic(&self, mut diagnostic: Diagnostic) -> Option<ErrorGuaranteed> {
self.inner.borrow_mut().emit_diagnostic(diagnostic) self.emit_diagnostic_without_consuming(&mut diagnostic)
}
// It's unfortunate this exists. `emit_diagnostic` is preferred, because it
// consumes the diagnostic, thus ensuring it is emitted just once.
pub(crate) fn emit_diagnostic_without_consuming(
&self,
diagnostic: &mut Diagnostic,
) -> Option<ErrorGuaranteed> {
self.inner.borrow_mut().emit_diagnostic_without_consuming(diagnostic)
} }
pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed { pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
@ -1327,14 +1342,6 @@ impl Handler {
note.into_diagnostic(self) note.into_diagnostic(self)
} }
fn emit_diag_at_span(
&self,
mut diag: Diagnostic,
sp: impl Into<MultiSpan>,
) -> Option<ErrorGuaranteed> {
self.emit_diagnostic(diag.set_span(sp))
}
pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) { pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
self.inner.borrow_mut().emitter.emit_artifact_notification(path, artifact_type); self.inner.borrow_mut().emitter.emit_artifact_notification(path, artifact_type);
} }
@ -1374,7 +1381,7 @@ impl Handler {
// Here the diagnostic is given back to `emit_diagnostic` where it was first // Here the diagnostic is given back to `emit_diagnostic` where it was first
// intercepted. Now it should be processed as usual, since the unstable expectation // intercepted. Now it should be processed as usual, since the unstable expectation
// id is now stable. // id is now stable.
inner.emit_diagnostic(&mut diag); inner.emit_diagnostic(diag);
} }
} }
@ -1416,7 +1423,7 @@ impl HandlerInner {
let has_errors = self.has_errors(); let has_errors = self.has_errors();
let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>(); let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
let mut reported = None; let mut reported = None;
for mut diag in diags { for diag in diags {
// Decrement the count tracking the stash; emitting will increment it. // Decrement the count tracking the stash; emitting will increment it.
if diag.is_error() { if diag.is_error() {
if matches!(diag.level, Level::Error { lint: true }) { if matches!(diag.level, Level::Error { lint: true }) {
@ -1436,14 +1443,20 @@ impl HandlerInner {
} }
} }
} }
let reported_this = self.emit_diagnostic(&mut diag); let reported_this = self.emit_diagnostic(diag);
reported = reported.or(reported_this); reported = reported.or(reported_this);
} }
reported reported
} }
// FIXME(eddyb) this should ideally take `diagnostic` by value. fn emit_diagnostic(&mut self, mut diagnostic: Diagnostic) -> Option<ErrorGuaranteed> {
fn emit_diagnostic(&mut self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> { self.emit_diagnostic_without_consuming(&mut diagnostic)
}
fn emit_diagnostic_without_consuming(
&mut self,
diagnostic: &mut Diagnostic,
) -> Option<ErrorGuaranteed> {
if matches!(diagnostic.level, Level::Error { .. } | Level::Fatal) && self.treat_err_as_bug() if matches!(diagnostic.level, Level::Error { .. } | Level::Fatal) && self.treat_err_as_bug()
{ {
diagnostic.level = Level::Bug; diagnostic.level = Level::Bug;
@ -1579,17 +1592,15 @@ impl HandlerInner {
} }
#[track_caller] #[track_caller]
fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: impl Into<String>) -> ! { fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
self.emit_diag_at_span(Diagnostic::new(Bug, msg.into()), sp); let mut diag = Diagnostic::new(Bug, msg);
diag.set_span(sp);
self.emit_diagnostic(diag);
panic::panic_any(ExplicitBug); panic::panic_any(ExplicitBug);
} }
fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
self.emit_diagnostic(diag.set_span(sp));
}
fn failure_note(&mut self, msg: impl Into<DiagnosticMessage>) { fn failure_note(&mut self, msg: impl Into<DiagnosticMessage>) {
self.emit_diagnostic(&mut Diagnostic::new(FailureNote, msg)); self.emit_diagnostic(Diagnostic::new(FailureNote, msg));
} }
fn flush_delayed( fn flush_delayed(
@ -1621,7 +1632,7 @@ impl HandlerInner {
if no_bugs { if no_bugs {
// Put the overall explanation before the `DelayedBug`s, to // Put the overall explanation before the `DelayedBug`s, to
// frame them better (e.g. separate warnings from them). // frame them better (e.g. separate warnings from them).
self.emit_diagnostic(&mut Diagnostic::new(Bug, explanation)); self.emit_diagnostic(Diagnostic::new(Bug, explanation));
no_bugs = false; no_bugs = false;
} }
@ -1636,7 +1647,7 @@ impl HandlerInner {
} }
bug.level = Level::Bug; bug.level = Level::Bug;
self.emit_diagnostic(&mut bug); self.emit_diagnostic(bug);
} }
// Panic with `DelayedBugPanic` to avoid "unexpected panic" messages. // Panic with `DelayedBugPanic` to avoid "unexpected panic" messages.

View File

@ -1145,7 +1145,7 @@ impl<'a> ExtCtxt<'a> {
pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) { pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) {
self.sess.diagnostic().span_err(sp, msg); self.sess.diagnostic().span_err(sp, msg);
} }
pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<String>) -> ! { pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) -> ! {
self.sess.diagnostic().span_bug(sp, msg); self.sess.diagnostic().span_bug(sp, msg);
} }
pub fn trace_macros_diag(&mut self) { pub fn trace_macros_diag(&mut self) {

View File

@ -502,7 +502,7 @@ impl server::FreeFunctions for Rustc<'_, '_> {
None, None,
); );
} }
self.sess().span_diagnostic.emit_diagnostic(&mut diag); self.sess().span_diagnostic.emit_diagnostic(diag);
} }
} }

View File

@ -504,8 +504,8 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
if !errors_buffer.is_empty() { if !errors_buffer.is_empty() {
errors_buffer.sort_by_key(|diag| diag.span.primary_span()); errors_buffer.sort_by_key(|diag| diag.span.primary_span());
for mut diag in errors_buffer { for diag in errors_buffer {
self.tcx().sess.diagnostic().emit_diagnostic(&mut diag); self.tcx().sess.diagnostic().emit_diagnostic(diag);
} }
} }
} }

View File

@ -15,7 +15,9 @@ use hir::def::DefKind;
use polonius_engine::Atom; use polonius_engine::Atom;
use rustc_data_structures::captures::Captures; use rustc_data_structures::captures::Captures;
use rustc_data_structures::intern::Interned; use rustc_data_structures::intern::Interned;
use rustc_errors::{DiagnosticArgValue, ErrorGuaranteed, IntoDiagnosticArg, MultiSpan}; use rustc_errors::{
DiagnosticArgValue, DiagnosticMessage, ErrorGuaranteed, IntoDiagnosticArg, MultiSpan,
};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_hir::LangItem; use rustc_hir::LangItem;
@ -2005,7 +2007,7 @@ impl<'tcx> Ty<'tcx> {
pub fn new_error_with_message<S: Into<MultiSpan>>( pub fn new_error_with_message<S: Into<MultiSpan>>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
span: S, span: S,
msg: impl Into<String>, msg: impl Into<DiagnosticMessage>,
) -> Ty<'tcx> { ) -> Ty<'tcx> {
let reported = tcx.sess.span_delayed_bug(span, msg); let reported = tcx.sess.span_delayed_bug(span, msg);
Ty::new(tcx, Error(reported)) Ty::new(tcx, Error(reported))

View File

@ -65,7 +65,7 @@ pub(crate) struct RequiresUnsafe {
impl<'sess> IntoDiagnostic<'sess> for RequiresUnsafe { impl<'sess> IntoDiagnostic<'sess> for RequiresUnsafe {
#[track_caller] #[track_caller]
fn into_diagnostic(self, handler: &'sess Handler) -> DiagnosticBuilder<'sess, ErrorGuaranteed> { fn into_diagnostic(self, handler: &'sess Handler) -> DiagnosticBuilder<'sess, ErrorGuaranteed> {
let mut diag = handler.struct_diagnostic(fluent::mir_transform_requires_unsafe); let mut diag = handler.struct_err(fluent::mir_transform_requires_unsafe);
diag.code(rustc_errors::DiagnosticId::Error("E0133".to_string())); diag.code(rustc_errors::DiagnosticId::Error("E0133".to_string()));
diag.set_span(self.span); diag.set_span(self.span);
diag.span_label(self.span, self.details.label()); diag.span_label(self.span, self.details.label());

View File

@ -1046,7 +1046,7 @@ impl<'a> IntoDiagnostic<'a> for ExpectedIdentifier {
) -> rustc_errors::DiagnosticBuilder<'a, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'a, ErrorGuaranteed> {
let token_descr = TokenDescription::from_token(&self.token); let token_descr = TokenDescription::from_token(&self.token);
let mut diag = handler.struct_diagnostic(match token_descr { let mut diag = handler.struct_err(match token_descr {
Some(TokenDescription::ReservedIdentifier) => { Some(TokenDescription::ReservedIdentifier) => {
fluent::parse_expected_identifier_found_reserved_identifier_str fluent::parse_expected_identifier_found_reserved_identifier_str
} }
@ -1103,7 +1103,7 @@ impl<'a> IntoDiagnostic<'a> for ExpectedSemi {
) -> rustc_errors::DiagnosticBuilder<'a, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'a, ErrorGuaranteed> {
let token_descr = TokenDescription::from_token(&self.token); let token_descr = TokenDescription::from_token(&self.token);
let mut diag = handler.struct_diagnostic(match token_descr { let mut diag = handler.struct_err(match token_descr {
Some(TokenDescription::ReservedIdentifier) => { Some(TokenDescription::ReservedIdentifier) => {
fluent::parse_expected_semi_found_reserved_identifier_str fluent::parse_expected_semi_found_reserved_identifier_str
} }

View File

@ -350,8 +350,7 @@ pub(super) fn check_for_substitution(
let Some((_, ascii_name, token)) = ASCII_ARRAY.iter().find(|&&(s, _, _)| s == ascii_str) else { let Some((_, ascii_name, token)) = ASCII_ARRAY.iter().find(|&&(s, _, _)| s == ascii_str) else {
let msg = format!("substitution character not found for '{ch}'"); let msg = format!("substitution character not found for '{ch}'");
reader.sess.span_diagnostic.span_bug_no_panic(span, msg); reader.sess.span_diagnostic.span_bug(span, msg);
return (None, None);
}; };
// special help suggestion for "directed" double quotes // special help suggestion for "directed" double quotes

View File

@ -51,8 +51,8 @@ macro_rules! panictry_buffer {
match $e { match $e {
Ok(e) => e, Ok(e) => e,
Err(errs) => { Err(errs) => {
for mut e in errs { for e in errs {
$handler.emit_diagnostic(&mut e); $handler.emit_diagnostic(e);
} }
FatalError.raise() FatalError.raise()
} }
@ -165,8 +165,8 @@ fn try_file_to_source_file(
fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) -> Lrc<SourceFile> { fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) -> Lrc<SourceFile> {
match try_file_to_source_file(sess, path, spanopt) { match try_file_to_source_file(sess, path, spanopt) {
Ok(source_file) => source_file, Ok(source_file) => source_file,
Err(mut d) => { Err(d) => {
sess.span_diagnostic.emit_diagnostic(&mut d); sess.span_diagnostic.emit_diagnostic(d);
FatalError.raise(); FatalError.raise();
} }
} }

View File

@ -249,8 +249,8 @@ impl<'a> Parser<'a> {
self.diagnostic().struct_span_err(sp, m) self.diagnostic().struct_span_err(sp, m)
} }
pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: impl Into<String>) -> ! { pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) -> ! {
self.diagnostic().span_bug(sp, m) self.diagnostic().span_bug(sp, msg)
} }
pub(super) fn diagnostic(&self) -> &'a Handler { pub(super) fn diagnostic(&self) -> &'a Handler {

View File

@ -926,8 +926,8 @@ impl<D: Deps> DepGraphData<D> {
let handle = qcx.dep_context().sess().diagnostic(); let handle = qcx.dep_context().sess().diagnostic();
for mut diagnostic in side_effects.diagnostics { for diagnostic in side_effects.diagnostics {
handle.emit_diagnostic(&mut diagnostic); handle.emit_diagnostic(diagnostic);
} }
} }
} }

View File

@ -19,7 +19,7 @@ impl<'a> IntoDiagnostic<'a> for FeatureGateError {
self, self,
handler: &'a rustc_errors::Handler, handler: &'a rustc_errors::Handler,
) -> rustc_errors::DiagnosticBuilder<'a, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'a, ErrorGuaranteed> {
let mut diag = handler.struct_diagnostic(self.explain); let mut diag = handler.struct_err(self.explain);
diag.set_span(self.span); diag.set_span(self.span);
diag.code(error_code!(E0658)); diag.code(error_code!(E0658));
diag diag

View File

@ -14,7 +14,7 @@ use rustc_data_structures::sync::{AppendOnlyVec, Lock, Lrc};
use rustc_errors::{emitter::SilentEmitter, Handler}; use rustc_errors::{emitter::SilentEmitter, Handler};
use rustc_errors::{ use rustc_errors::{
fallback_fluent_bundle, Diagnostic, DiagnosticBuilder, DiagnosticId, DiagnosticMessage, fallback_fluent_bundle, Diagnostic, DiagnosticBuilder, DiagnosticId, DiagnosticMessage,
EmissionGuarantee, ErrorGuaranteed, IntoDiagnostic, MultiSpan, Noted, StashKey, ErrorGuaranteed, IntoDiagnostic, MultiSpan, Noted, StashKey,
}; };
use rustc_feature::{find_feature_issue, GateIssue, UnstableFeatures}; use rustc_feature::{find_feature_issue, GateIssue, UnstableFeatures};
use rustc_span::edition::Edition; use rustc_span::edition::Edition;
@ -390,13 +390,4 @@ impl ParseSess {
pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> { pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
self.span_diagnostic.struct_fatal(msg) self.span_diagnostic.struct_fatal(msg)
} }
#[rustc_lint_diagnostics]
#[track_caller]
pub fn struct_diagnostic<G: EmissionGuarantee>(
&self,
msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, G> {
self.span_diagnostic.struct_diagnostic(msg)
}
} }

View File

@ -632,7 +632,7 @@ impl Session {
pub fn span_delayed_bug<S: Into<MultiSpan>>( pub fn span_delayed_bug<S: Into<MultiSpan>>(
&self, &self,
sp: S, sp: S,
msg: impl Into<String>, msg: impl Into<DiagnosticMessage>,
) -> ErrorGuaranteed { ) -> ErrorGuaranteed {
self.diagnostic().span_delayed_bug(sp, msg) self.diagnostic().span_delayed_bug(sp, msg)
} }

View File

@ -512,7 +512,7 @@ pub fn report_msg<'tcx>(
} }
} }
handler.emit_diagnostic(&mut err); handler.emit_diagnostic(err);
} }
impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> { impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {

View File

@ -284,10 +284,8 @@ impl ParseSess {
// Methods that should be restricted within the parse module. // Methods that should be restricted within the parse module.
impl ParseSess { impl ParseSess {
pub(super) fn emit_diagnostics(&self, diagnostics: Vec<Diagnostic>) { pub(super) fn emit_diagnostics(&self, diagnostics: Vec<Diagnostic>) {
for mut diagnostic in diagnostics { for diagnostic in diagnostics {
self.parse_sess self.parse_sess.span_diagnostic.emit_diagnostic(diagnostic);
.span_diagnostic
.emit_diagnostic(&mut diagnostic);
} }
} }