Skip to content

Commit bc0d618

Browse files
authored
Rollup merge of #120575 - nnethercote:simplify-codegen-diag-handling, r=estebank
Simplify codegen diagnostic handling Some nice improvements. Details in the individual commit logs. r? ``@estebank``
2 parents 749af61 + f4dce1e commit bc0d618

File tree

8 files changed

+90
-116
lines changed

8 files changed

+90
-116
lines changed

compiler/rustc_codegen_ssa/src/back/write.rs

+5-40
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,7 @@ use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
1515
use rustc_data_structures::sync::Lrc;
1616
use rustc_errors::emitter::Emitter;
1717
use rustc_errors::translation::Translate;
18-
use rustc_errors::{
19-
DiagCtxt, DiagnosticArgName, DiagnosticArgValue, DiagnosticBuilder, DiagnosticMessage, ErrCode,
20-
FatalError, FluentBundle, Level, Style,
21-
};
18+
use rustc_errors::{DiagCtxt, Diagnostic, DiagnosticBuilder, FatalError, FluentBundle, Level};
2219
use rustc_fs_util::link_or_copy;
2320
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
2421
use rustc_incremental::{
@@ -997,13 +994,6 @@ pub(crate) enum Message<B: WriteBackendMethods> {
997994
/// process another codegen unit.
998995
pub struct CguMessage;
999996

1000-
struct Diagnostic {
1001-
msgs: Vec<(DiagnosticMessage, Style)>,
1002-
args: FxHashMap<DiagnosticArgName, DiagnosticArgValue>,
1003-
code: Option<ErrCode>,
1004-
lvl: Level,
1005-
}
1006-
1007997
#[derive(PartialEq, Clone, Copy, Debug)]
1008998
enum MainThreadState {
1009999
/// Doing nothing.
@@ -1764,7 +1754,6 @@ fn spawn_work<'a, B: ExtraBackendMethods>(
17641754
enum SharedEmitterMessage {
17651755
Diagnostic(Diagnostic),
17661756
InlineAsmError(u32, String, Level, Option<(String, Vec<InnerSpan>)>),
1767-
AbortIfErrors,
17681757
Fatal(String),
17691758
}
17701759

@@ -1810,24 +1799,8 @@ impl Translate for SharedEmitter {
18101799
}
18111800

18121801
impl Emitter for SharedEmitter {
1813-
fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) {
1814-
let args: FxHashMap<DiagnosticArgName, DiagnosticArgValue> =
1815-
diag.args().map(|(name, arg)| (name.clone(), arg.clone())).collect();
1816-
drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1817-
msgs: diag.messages.clone(),
1818-
args: args.clone(),
1819-
code: diag.code,
1820-
lvl: diag.level(),
1821-
})));
1822-
for child in &diag.children {
1823-
drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1824-
msgs: child.messages.clone(),
1825-
args: args.clone(),
1826-
code: None,
1827-
lvl: child.level,
1828-
})));
1829-
}
1830-
drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1802+
fn emit_diagnostic(&mut self, diag: rustc_errors::Diagnostic) {
1803+
drop(self.sender.send(SharedEmitterMessage::Diagnostic(diag)));
18311804
}
18321805

18331806
fn source_map(&self) -> Option<&Lrc<SourceMap>> {
@@ -1852,13 +1825,8 @@ impl SharedEmitterMain {
18521825

18531826
match message {
18541827
Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1855-
let dcx = sess.dcx();
1856-
let mut d = rustc_errors::Diagnostic::new_with_messages(diag.lvl, diag.msgs);
1857-
if let Some(code) = diag.code {
1858-
d.code(code);
1859-
}
1860-
d.replace_args(diag.args);
1861-
dcx.emit_diagnostic(d);
1828+
sess.dcx().emit_diagnostic(diag);
1829+
sess.dcx().abort_if_errors();
18621830
}
18631831
Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
18641832
assert!(matches!(level, Level::Error | Level::Warning | Level::Note));
@@ -1891,9 +1859,6 @@ impl SharedEmitterMain {
18911859

18921860
err.emit();
18931861
}
1894-
Ok(SharedEmitterMessage::AbortIfErrors) => {
1895-
sess.dcx().abort_if_errors();
1896-
}
18971862
Ok(SharedEmitterMessage::Fatal(msg)) => {
18981863
sess.dcx().fatal(msg);
18991864
}

compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs

+8-8
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,15 @@ impl Translate for AnnotateSnippetEmitter {
4444

4545
impl Emitter for AnnotateSnippetEmitter {
4646
/// The entry point for the diagnostics generation
47-
fn emit_diagnostic(&mut self, diag: &Diagnostic) {
47+
fn emit_diagnostic(&mut self, mut diag: Diagnostic) {
4848
let fluent_args = to_fluent_args(diag.args());
4949

50-
let mut children = diag.children.clone();
51-
let (mut primary_span, suggestions) = self.primary_span_formatted(diag, &fluent_args);
50+
let mut suggestions = diag.suggestions.unwrap_or(vec![]);
51+
self.primary_span_formatted(&mut diag.span, &mut suggestions, &fluent_args);
5252

5353
self.fix_multispans_in_extern_macros_and_render_macro_backtrace(
54-
&mut primary_span,
55-
&mut children,
54+
&mut diag.span,
55+
&mut diag.children,
5656
&diag.level,
5757
self.macro_backtrace,
5858
);
@@ -62,9 +62,9 @@ impl Emitter for AnnotateSnippetEmitter {
6262
&diag.messages,
6363
&fluent_args,
6464
&diag.code,
65-
&primary_span,
66-
&children,
67-
suggestions,
65+
&diag.span,
66+
&diag.children,
67+
&suggestions,
6868
);
6969
}
7070

compiler/rustc_errors/src/emitter.rs

+19-22
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ pub type DynEmitter = dyn Emitter + DynSend;
193193
/// Emitter trait for emitting errors.
194194
pub trait Emitter: Translate {
195195
/// Emit a structured diagnostic.
196-
fn emit_diagnostic(&mut self, diag: &Diagnostic);
196+
fn emit_diagnostic(&mut self, diag: Diagnostic);
197197

198198
/// Emit a notification that an artifact has been output.
199199
/// Currently only supported for the JSON format.
@@ -230,17 +230,17 @@ pub trait Emitter: Translate {
230230
///
231231
/// * If the current `Diagnostic` has only one visible `CodeSuggestion`,
232232
/// we format the `help` suggestion depending on the content of the
233-
/// substitutions. In that case, we return the modified span only.
233+
/// substitutions. In that case, we modify the span and clear the
234+
/// suggestions.
234235
///
235236
/// * If the current `Diagnostic` has multiple suggestions,
236-
/// we return the original `primary_span` and the original suggestions.
237-
fn primary_span_formatted<'a>(
237+
/// we leave `primary_span` and the suggestions untouched.
238+
fn primary_span_formatted(
238239
&mut self,
239-
diag: &'a Diagnostic,
240+
primary_span: &mut MultiSpan,
241+
suggestions: &mut Vec<CodeSuggestion>,
240242
fluent_args: &FluentArgs<'_>,
241-
) -> (MultiSpan, &'a [CodeSuggestion]) {
242-
let mut primary_span = diag.span.clone();
243-
let suggestions = diag.suggestions.as_deref().unwrap_or(&[]);
243+
) {
244244
if let Some((sugg, rest)) = suggestions.split_first() {
245245
let msg = self.translate_message(&sugg.msg, fluent_args).map_err(Report::new).unwrap();
246246
if rest.is_empty() &&
@@ -287,16 +287,15 @@ pub trait Emitter: Translate {
287287
primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
288288

289289
// We return only the modified primary_span
290-
(primary_span, &[])
290+
suggestions.clear();
291291
} else {
292292
// if there are multiple suggestions, print them all in full
293293
// to be consistent. We could try to figure out if we can
294294
// make one (or the first one) inline, but that would give
295295
// undue importance to a semi-random suggestion
296-
(primary_span, suggestions)
297296
}
298297
} else {
299-
(primary_span, suggestions)
298+
// do nothing
300299
}
301300
}
302301

@@ -518,16 +517,15 @@ impl Emitter for HumanEmitter {
518517
self.sm.as_ref()
519518
}
520519

521-
fn emit_diagnostic(&mut self, diag: &Diagnostic) {
520+
fn emit_diagnostic(&mut self, mut diag: Diagnostic) {
522521
let fluent_args = to_fluent_args(diag.args());
523522

524-
let mut children = diag.children.clone();
525-
let (mut primary_span, suggestions) = self.primary_span_formatted(diag, &fluent_args);
526-
debug!("emit_diagnostic: suggestions={:?}", suggestions);
523+
let mut suggestions = diag.suggestions.unwrap_or(vec![]);
524+
self.primary_span_formatted(&mut diag.span, &mut suggestions, &fluent_args);
527525

528526
self.fix_multispans_in_extern_macros_and_render_macro_backtrace(
529-
&mut primary_span,
530-
&mut children,
527+
&mut diag.span,
528+
&mut diag.children,
531529
&diag.level,
532530
self.macro_backtrace,
533531
);
@@ -537,9 +535,9 @@ impl Emitter for HumanEmitter {
537535
&diag.messages,
538536
&fluent_args,
539537
&diag.code,
540-
&primary_span,
541-
&children,
542-
suggestions,
538+
&diag.span,
539+
&diag.children,
540+
&suggestions,
543541
self.track_diagnostics.then_some(&diag.emitted_at),
544542
);
545543
}
@@ -576,9 +574,8 @@ impl Emitter for SilentEmitter {
576574
None
577575
}
578576

579-
fn emit_diagnostic(&mut self, diag: &Diagnostic) {
577+
fn emit_diagnostic(&mut self, mut diag: Diagnostic) {
580578
if diag.level == Level::Fatal {
581-
let mut diag = diag.clone();
582579
diag.note(self.fatal_note.clone());
583580
self.fatal_dcx.emit_diagnostic(diag);
584581
}

compiler/rustc_errors/src/json.rs

+28-24
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ impl Translate for JsonEmitter {
176176
}
177177

178178
impl Emitter for JsonEmitter {
179-
fn emit_diagnostic(&mut self, diag: &crate::Diagnostic) {
179+
fn emit_diagnostic(&mut self, diag: crate::Diagnostic) {
180180
let data = Diagnostic::from_errors_diagnostic(diag, self);
181181
let result = self.emit(EmitTyped::Diagnostic(data));
182182
if let Err(e) = result {
@@ -201,7 +201,7 @@ impl Emitter for JsonEmitter {
201201
}
202202
FutureBreakageItem {
203203
diagnostic: EmitTyped::Diagnostic(Diagnostic::from_errors_diagnostic(
204-
&diag, self,
204+
diag, self,
205205
)),
206206
}
207207
})
@@ -340,7 +340,7 @@ struct UnusedExterns<'a, 'b, 'c> {
340340
}
341341

342342
impl Diagnostic {
343-
fn from_errors_diagnostic(diag: &crate::Diagnostic, je: &JsonEmitter) -> Diagnostic {
343+
fn from_errors_diagnostic(diag: crate::Diagnostic, je: &JsonEmitter) -> Diagnostic {
344344
let args = to_fluent_args(diag.args());
345345
let sugg = diag.suggestions.iter().flatten().map(|sugg| {
346346
let translated_message =
@@ -382,6 +382,28 @@ impl Diagnostic {
382382
Ok(())
383383
}
384384
}
385+
386+
let translated_message = je.translate_messages(&diag.messages, &args);
387+
388+
let code = if let Some(code) = diag.code {
389+
Some(DiagnosticCode {
390+
code: code.to_string(),
391+
explanation: je.registry.as_ref().unwrap().try_find_description(code).ok(),
392+
})
393+
} else if let Some(IsLint { name, .. }) = &diag.is_lint {
394+
Some(DiagnosticCode { code: name.to_string(), explanation: None })
395+
} else {
396+
None
397+
};
398+
let level = diag.level.to_str();
399+
let spans = DiagnosticSpan::from_multispan(&diag.span, &args, je);
400+
let children = diag
401+
.children
402+
.iter()
403+
.map(|c| Diagnostic::from_sub_diagnostic(c, &args, je))
404+
.chain(sugg)
405+
.collect();
406+
385407
let buf = BufWriter::default();
386408
let output = buf.clone();
387409
je.json_rendered
@@ -398,30 +420,12 @@ impl Diagnostic {
398420
let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
399421
let output = String::from_utf8(output).unwrap();
400422

401-
let translated_message = je.translate_messages(&diag.messages, &args);
402-
403-
let code = if let Some(code) = diag.code {
404-
Some(DiagnosticCode {
405-
code: code.to_string(),
406-
explanation: je.registry.as_ref().unwrap().try_find_description(code).ok(),
407-
})
408-
} else if let Some(IsLint { name, .. }) = &diag.is_lint {
409-
Some(DiagnosticCode { code: name.to_string(), explanation: None })
410-
} else {
411-
None
412-
};
413-
414423
Diagnostic {
415424
message: translated_message.to_string(),
416425
code,
417-
level: diag.level.to_str(),
418-
spans: DiagnosticSpan::from_multispan(&diag.span, &args, je),
419-
children: diag
420-
.children
421-
.iter()
422-
.map(|c| Diagnostic::from_sub_diagnostic(c, &args, je))
423-
.chain(sugg)
424-
.collect(),
426+
level,
427+
spans,
428+
children,
425429
rendered: Some(output),
426430
}
427431
}

compiler/rustc_errors/src/lib.rs

+17-9
Original file line numberDiff line numberDiff line change
@@ -991,9 +991,13 @@ impl DiagCtxt {
991991

992992
match (errors.len(), warnings.len()) {
993993
(0, 0) => return,
994-
(0, _) => inner
995-
.emitter
996-
.emit_diagnostic(&Diagnostic::new(Warning, DiagnosticMessage::Str(warnings))),
994+
(0, _) => {
995+
// Use `inner.emitter` directly, otherwise the warning might not be emitted, e.g.
996+
// with a configuration like `--cap-lints allow --force-warn bare_trait_objects`.
997+
inner
998+
.emitter
999+
.emit_diagnostic(Diagnostic::new(Warning, DiagnosticMessage::Str(warnings)));
1000+
}
9971001
(_, 0) => {
9981002
inner.emit_diagnostic(Diagnostic::new(Fatal, errors));
9991003
}
@@ -1057,7 +1061,7 @@ impl DiagCtxt {
10571061
}
10581062

10591063
pub fn force_print_diagnostic(&self, db: Diagnostic) {
1060-
self.inner.borrow_mut().emitter.emit_diagnostic(&db);
1064+
self.inner.borrow_mut().emitter.emit_diagnostic(db);
10611065
}
10621066

10631067
pub fn emit_diagnostic(&self, diagnostic: Diagnostic) -> Option<ErrorGuaranteed> {
@@ -1325,11 +1329,15 @@ impl DiagCtxtInner {
13251329
!self.emitted_diagnostics.insert(diagnostic_hash)
13261330
};
13271331

1332+
let is_error = diagnostic.is_error();
1333+
let is_lint = diagnostic.is_lint.is_some();
1334+
13281335
// Only emit the diagnostic if we've been asked to deduplicate or
13291336
// haven't already emitted an equivalent diagnostic.
13301337
if !(self.flags.deduplicate_diagnostics && already_emitted) {
13311338
debug!(?diagnostic);
13321339
debug!(?self.emitted_diagnostics);
1340+
13331341
let already_emitted_sub = |sub: &mut SubDiagnostic| {
13341342
debug!(?sub);
13351343
if sub.level != OnceNote && sub.level != OnceHelp {
@@ -1341,24 +1349,24 @@ impl DiagCtxtInner {
13411349
debug!(?diagnostic_hash);
13421350
!self.emitted_diagnostics.insert(diagnostic_hash)
13431351
};
1344-
13451352
diagnostic.children.extract_if(already_emitted_sub).for_each(|_| {});
13461353
if already_emitted {
13471354
diagnostic.note(
13481355
"duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`",
13491356
);
13501357
}
13511358

1352-
self.emitter.emit_diagnostic(&diagnostic);
1353-
if diagnostic.is_error() {
1359+
if is_error {
13541360
self.deduplicated_err_count += 1;
13551361
} else if matches!(diagnostic.level, ForceWarning(_) | Warning) {
13561362
self.deduplicated_warn_count += 1;
13571363
}
13581364
self.has_printed = true;
1365+
1366+
self.emitter.emit_diagnostic(diagnostic);
13591367
}
1360-
if diagnostic.is_error() {
1361-
if diagnostic.is_lint.is_some() {
1368+
if is_error {
1369+
if is_lint {
13621370
self.lint_err_count += 1;
13631371
} else {
13641372
self.err_count += 1;

src/librustdoc/passes/lint/check_code_block_syntax.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ impl Translate for BufferEmitter {
156156
}
157157

158158
impl Emitter for BufferEmitter {
159-
fn emit_diagnostic(&mut self, diag: &Diagnostic) {
159+
fn emit_diagnostic(&mut self, diag: Diagnostic) {
160160
let mut buffer = self.buffer.borrow_mut();
161161

162162
let fluent_args = to_fluent_args(diag.args());

0 commit comments

Comments
 (0)