]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_errors/src/lib.rs
New upstream version 1.57.0+dfsg1
[rustc.git] / compiler / rustc_errors / src / lib.rs
CommitLineData
dc9dc135
XL
1//! Diagnostics creation and emission for `rustc`.
2//!
3//! This module contains the code for creating and emitting diagnostics.
4
1b1a35ee 5#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
dc9dc135 6#![feature(crate_visibility_modifier)]
1b1a35ee 7#![feature(backtrace)]
94222f64 8#![feature(if_let_guard)]
17df50a5 9#![feature(format_args_capture)]
cdc7bbd5 10#![feature(iter_zip)]
0bf4aa26 11#![feature(nll)]
3dfed10e
XL
12
13#[macro_use]
14extern crate rustc_macros;
3157f602 15
c295e0f8
XL
16#[macro_use]
17extern crate tracing;
18
3157f602 19pub use emitter::ColorConfig;
9cc50fc6 20
9fa01778 21use Level::*;
9cc50fc6 22
60c5eb7d 23use emitter::{is_case_difference, Emitter, EmitterWriter};
48663c56 24use registry::Registry;
e74abb32 25use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
abe05a73 26use rustc_data_structures::stable_hasher::StableHasher;
60c5eb7d 27use rustc_data_structures::sync::{self, Lock, Lrc};
dfeec247 28use rustc_data_structures::AtomicRef;
29967ef6 29pub use rustc_lint_defs::{pluralize, Applicability};
6a06907d
XL
30use rustc_serialize::json::Json;
31use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
dfeec247
XL
32use rustc_span::source_map::SourceMap;
33use rustc_span::{Loc, MultiSpan, Span};
abe05a73 34
041b39d2 35use std::borrow::Cow;
6a06907d
XL
36use std::hash::{Hash, Hasher};
37use std::num::NonZeroUsize;
2c00a5a8 38use std::panic;
48663c56 39use std::path::Path;
60c5eb7d 40use std::{error, fmt};
9cc50fc6 41
60c5eb7d 42use termcolor::{Color, ColorSpec};
0531ce1d 43
60c5eb7d 44pub mod annotate_snippet_emitter_writer;
3b2f2976
XL
45mod diagnostic;
46mod diagnostic_builder;
9cc50fc6 47pub mod emitter;
60c5eb7d
XL
48pub mod json;
49mod lock;
3157f602 50pub mod registry;
60c5eb7d 51mod snippet;
041b39d2 52mod styled_buffer;
60c5eb7d
XL
53pub use snippet::Style;
54
55pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
3157f602 56
60c5eb7d
XL
57// `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
58// (See also the comment on `DiagnosticBuilderInner`.)
6a06907d 59#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
60c5eb7d 60rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
9cc50fc6 61
3dfed10e 62#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
9fa01778
XL
63pub enum SuggestionStyle {
64 /// Hide the suggested code when displaying this suggestion inline.
65 HideCodeInline,
66 /// Always hide the suggested code but display the message.
67 HideCodeAlways,
68 /// Do not display this suggestion in the cli output, it is only meant for tools.
69 CompletelyHidden,
70 /// Always show the suggested code.
71 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
72 /// empty.
73 ShowCode,
e74abb32
XL
74 /// Always show the suggested code independently.
75 ShowAlways,
9fa01778
XL
76}
77
78impl SuggestionStyle {
79 fn hide_inline(&self) -> bool {
29967ef6 80 !matches!(*self, SuggestionStyle::ShowCode)
9fa01778 81 }
83c7162d
XL
82}
83
6a06907d
XL
84#[derive(Clone, Debug, PartialEq, Default)]
85pub struct ToolMetadata(pub Option<Json>);
86
87impl ToolMetadata {
88 fn new(json: Json) -> Self {
89 ToolMetadata(Some(json))
90 }
91
92 fn is_set(&self) -> bool {
93 self.0.is_some()
94 }
95}
96
97impl Hash for ToolMetadata {
98 fn hash<H: Hasher>(&self, _state: &mut H) {}
99}
100
101// Doesn't really need to round-trip
102impl<D: Decoder> Decodable<D> for ToolMetadata {
103 fn decode(_d: &mut D) -> Result<Self, D::Error> {
104 Ok(ToolMetadata(None))
105 }
106}
107
108impl<S: Encoder> Encodable<S> for ToolMetadata {
109 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
110 match &self.0 {
111 None => e.emit_unit(),
112 Some(json) => json.encode(e),
113 }
114 }
115}
116
3dfed10e 117#[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
7453a54e 118pub struct CodeSuggestion {
7cac9316
XL
119 /// Each substitute can have multiple variants due to multiple
120 /// applicable suggestions
121 ///
122 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
123 /// `foo` and `bar` on their own:
124 ///
125 /// ```
126 /// vec![
abe05a73
XL
127 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
128 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
7cac9316
XL
129 /// ]
130 /// ```
131 ///
132 /// or by replacing the entire span:
133 ///
134 /// ```
abe05a73
XL
135 /// vec![
136 /// Substitution { parts: vec![(0..7, "a.b")] },
137 /// Substitution { parts: vec![(0..7, "x.y")] },
138 /// ]
7cac9316 139 /// ```
abe05a73 140 pub substitutions: Vec<Substitution>,
7cac9316 141 pub msg: String,
9fa01778
XL
142 /// Visual representation of this suggestion.
143 pub style: SuggestionStyle,
2c00a5a8
XL
144 /// Whether or not the suggestion is approximate
145 ///
146 /// Sometimes we may show suggestions with placeholders,
147 /// which are useful for users but not useful for
148 /// tools like rustfix
83c7162d 149 pub applicability: Applicability,
6a06907d
XL
150 /// Tool-specific metadata
151 pub tool_metadata: ToolMetadata,
7cac9316
XL
152}
153
3dfed10e 154#[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
7cac9316
XL
155/// See the docs on `CodeSuggestion::substitutions`
156pub struct Substitution {
abe05a73
XL
157 pub parts: Vec<SubstitutionPart>,
158}
159
3dfed10e 160#[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
abe05a73 161pub struct SubstitutionPart {
7cac9316 162 pub span: Span,
abe05a73 163 pub snippet: String,
3157f602
XL
164}
165
94222f64
XL
166/// Used to translate between `Span`s and byte positions within a single output line in highlighted
167/// code of structured suggestions.
168#[derive(Debug, Clone, Copy)]
169pub struct SubstitutionHighlight {
170 start: usize,
171 end: usize,
172}
173
174impl SubstitutionPart {
175 pub fn is_addition(&self, sm: &SourceMap) -> bool {
176 !self.snippet.is_empty()
177 && sm
178 .span_to_snippet(self.span)
179 .map_or(self.span.is_empty(), |snippet| snippet.trim().is_empty())
180 }
181
182 pub fn is_deletion(&self) -> bool {
183 self.snippet.trim().is_empty()
184 }
185
186 pub fn is_replacement(&self, sm: &SourceMap) -> bool {
187 !self.snippet.is_empty()
188 && sm
189 .span_to_snippet(self.span)
190 .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
191 }
192}
193
7453a54e 194impl CodeSuggestion {
e74abb32
XL
195 /// Returns the assembled code suggestions, whether they should be shown with an underline
196 /// and whether the substitution only differs in capitalization.
94222f64
XL
197 pub fn splice_lines(
198 &self,
199 sm: &SourceMap,
200 ) -> Vec<(String, Vec<SubstitutionPart>, Vec<Vec<SubstitutionHighlight>>, bool)> {
201 // For the `Vec<Vec<SubstitutionHighlight>>` value, the first level of the vector
202 // corresponds to the output snippet's lines, while the second level corresponds to the
203 // substrings within that line that should be highlighted.
204
dfeec247 205 use rustc_span::{CharPos, Pos};
7453a54e 206
94222f64
XL
207 /// Append to a buffer the remainder of the line of existing source code, and return the
208 /// count of lines that have been added for accurate highlighting.
60c5eb7d
XL
209 fn push_trailing(
210 buf: &mut String,
211 line_opt: Option<&Cow<'_, str>>,
212 lo: &Loc,
213 hi_opt: Option<&Loc>,
94222f64
XL
214 ) -> usize {
215 let mut line_count = 0;
c30ab7b3 216 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
7453a54e 217 if let Some(line) = line_opt {
8bb4bdeb
XL
218 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
219 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
9fa01778 220 match hi_opt {
94222f64
XL
221 Some(hi) if hi > lo => {
222 line_count = line[lo..hi].matches('\n').count();
223 buf.push_str(&line[lo..hi])
224 }
9fa01778 225 Some(_) => (),
94222f64
XL
226 None => {
227 line_count = line[lo..].matches('\n').count();
228 buf.push_str(&line[lo..])
229 }
9fa01778 230 }
7453a54e 231 }
74b04a01 232 if hi_opt.is_none() {
7453a54e
SL
233 buf.push('\n');
234 }
235 }
94222f64 236 line_count
9cc50fc6 237 }
7453a54e 238
abe05a73
XL
239 assert!(!self.substitutions.is_empty());
240
60c5eb7d
XL
241 self.substitutions
242 .iter()
243 .filter(|subst| {
244 // Suggestions coming from macros can have malformed spans. This is a heavy
245 // handed approach to avoid ICEs by ignoring the suggestion outright.
74b04a01 246 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
60c5eb7d
XL
247 if invalid {
248 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
249 }
250 !invalid
251 })
252 .cloned()
dfeec247 253 .filter_map(|mut substitution| {
60c5eb7d
XL
254 // Assumption: all spans are in the same file, and all spans
255 // are disjoint. Sort in ascending order.
256 substitution.parts.sort_by_key(|part| part.span.lo());
257
258 // Find the bounding span.
dfeec247
XL
259 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
260 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
60c5eb7d 261 let bounding_span = Span::with_root_ctxt(lo, hi);
dfeec247 262 // The different spans might belong to different contexts, if so ignore suggestion.
74b04a01 263 let lines = sm.span_to_lines(bounding_span).ok()?;
ba9703b0
XL
264 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
265
266 // We can't splice anything if the source is unavailable.
267 if !sm.ensure_source_file_source_present(lines.file.clone()) {
268 return None;
269 }
60c5eb7d 270
94222f64 271 let mut highlights = vec![];
60c5eb7d
XL
272 // To build up the result, we do this for each span:
273 // - push the line segment trailing the previous span
274 // (at the beginning a "phantom" span pointing at the start of the line)
275 // - push lines between the previous and current span (if any)
276 // - if the previous and current span are not on the same line
277 // push the line segment leading up to the current span
278 // - splice in the span substitution
279 //
280 // Finally push the trailing line segment of the last span
74b04a01
XL
281 let sf = &lines.file;
282 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
60c5eb7d 283 prev_hi.col = CharPos::from_usize(0);
ba9703b0
XL
284 let mut prev_line =
285 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
60c5eb7d
XL
286 let mut buf = String::new();
287
94222f64
XL
288 let mut line_highlight = vec![];
289 // We need to keep track of the difference between the existing code and the added
290 // or deleted code in order to point at the correct column *after* substitution.
291 let mut acc = 0;
60c5eb7d 292 for part in &substitution.parts {
74b04a01 293 let cur_lo = sm.lookup_char_pos(part.span.lo());
60c5eb7d 294 if prev_hi.line == cur_lo.line {
94222f64
XL
295 let mut count =
296 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
297 while count > 0 {
298 highlights.push(std::mem::take(&mut line_highlight));
299 acc = 0;
300 count -= 1;
301 }
60c5eb7d 302 } else {
94222f64
XL
303 acc = 0;
304 highlights.push(std::mem::take(&mut line_highlight));
305 let mut count = push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
306 while count > 0 {
307 highlights.push(std::mem::take(&mut line_highlight));
308 count -= 1;
309 }
60c5eb7d
XL
310 // push lines between the previous and current span (if any)
311 for idx in prev_hi.line..(cur_lo.line - 1) {
74b04a01 312 if let Some(line) = sf.get_line(idx) {
60c5eb7d
XL
313 buf.push_str(line.as_ref());
314 buf.push('\n');
94222f64 315 highlights.push(std::mem::take(&mut line_highlight));
60c5eb7d
XL
316 }
317 }
74b04a01 318 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
ba9703b0
XL
319 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
320 Some((i, _)) => i,
321 None => cur_line.len(),
322 };
60c5eb7d 323 buf.push_str(&cur_line[..end]);
7cac9316
XL
324 }
325 }
94222f64
XL
326 // Add a whole line highlight per line in the snippet.
327 let len: isize = part
328 .snippet
329 .split('\n')
330 .next()
331 .unwrap_or(&part.snippet)
332 .chars()
333 .map(|c| match c {
334 '\t' => 4,
335 _ => 1,
336 })
337 .sum();
338 line_highlight.push(SubstitutionHighlight {
339 start: (cur_lo.col.0 as isize + acc) as usize,
340 end: (cur_lo.col.0 as isize + acc + len) as usize,
341 });
60c5eb7d 342 buf.push_str(&part.snippet);
94222f64 343 let cur_hi = sm.lookup_char_pos(part.span.hi());
c295e0f8 344 if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line {
94222f64
XL
345 // Account for the difference between the width of the current code and the
346 // snippet being suggested, so that the *later* suggestions are correctly
347 // aligned on the screen.
348 acc += len as isize - (cur_hi.col.0 - cur_lo.col.0) as isize;
349 }
350 prev_hi = cur_hi;
74b04a01 351 prev_line = sf.get_line(prev_hi.line - 1);
94222f64
XL
352 for line in part.snippet.split('\n').skip(1) {
353 acc = 0;
354 highlights.push(std::mem::take(&mut line_highlight));
355 let end: usize = line
356 .chars()
357 .map(|c| match c {
358 '\t' => 4,
359 _ => 1,
360 })
361 .sum();
362 line_highlight.push(SubstitutionHighlight { start: 0, end });
363 }
7453a54e 364 }
94222f64 365 highlights.push(std::mem::take(&mut line_highlight));
74b04a01 366 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
60c5eb7d
XL
367 // if the replacement already ends with a newline, don't print the next line
368 if !buf.ends_with('\n') {
369 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
370 }
371 // remove trailing newlines
372 while buf.ends_with('\n') {
373 buf.pop();
374 }
94222f64 375 Some((buf, substitution.parts, highlights, only_capitalization))
60c5eb7d
XL
376 })
377 .collect()
9cc50fc6
SL
378 }
379}
380
dfeec247 381pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
9cc50fc6
SL
382
383/// Signifies that the compiler died with an explicit call to `.bug`
384/// or `.span_bug` rather than a failed assertion, etc.
385#[derive(Copy, Clone, Debug)]
386pub struct ExplicitBug;
387
388impl fmt::Display for ExplicitBug {
9fa01778 389 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9cc50fc6
SL
390 write!(f, "parser internal bug")
391 }
392}
393
dfeec247 394impl error::Error for ExplicitBug {}
9cc50fc6 395
60c5eb7d 396pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
c30ab7b3 397pub use diagnostic_builder::DiagnosticBuilder;
17df50a5 398use std::backtrace::Backtrace;
9cc50fc6 399
48663c56
XL
400/// A handler deals with errors and other compiler output.
401/// Certain errors (fatal, bug, unimpl) may cause immediate exit,
9cc50fc6
SL
402/// others log errors for later reporting.
403pub struct Handler {
e1599b0c
XL
404 flags: HandlerFlags,
405 inner: Lock<HandlerInner>,
406}
ff7c6d11 407
e74abb32
XL
408/// This inner struct exists to keep it all behind a single lock;
409/// this is done to prevent possible deadlocks in a multi-threaded compiler,
410/// as well as inconsistent state observation.
e1599b0c
XL
411struct HandlerInner {
412 flags: HandlerFlags,
dc9dc135
XL
413 /// The number of errors that have been emitted, including duplicates.
414 ///
415 /// This is not necessarily the count that's reported to the user once
416 /// compilation ends.
e1599b0c 417 err_count: usize,
1b1a35ee 418 warn_count: usize,
e1599b0c
XL
419 deduplicated_err_count: usize,
420 emitter: Box<dyn Emitter + sync::Send>,
e1599b0c 421 delayed_span_bugs: Vec<Diagnostic>,
17df50a5 422 delayed_good_path_bugs: Vec<DelayedDiagnostic>,
abe05a73 423
48663c56
XL
424 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
425 /// emitting the same diagnostic with extended help (`--teach`) twice, which
cdc7bbd5 426 /// would be unnecessary repetition.
e1599b0c 427 taught_diagnostics: FxHashSet<DiagnosticId>,
83c7162d
XL
428
429 /// Used to suggest rustc --explain <error code>
e1599b0c 430 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
2c00a5a8 431
48663c56
XL
432 /// This set contains a hash of every diagnostic that has been emitted by
433 /// this handler. These hashes is used to avoid emitting the same error
434 /// twice.
e1599b0c 435 emitted_diagnostics: FxHashSet<u128>,
e74abb32
XL
436
437 /// Stashed diagnostics emitted in one stage of the compiler that may be
438 /// stolen by other stages (e.g. to improve them and add more information).
439 /// The stashed diagnostics count towards the total error count.
440 /// When `.abort_if_errors()` is called, these are also emitted.
441 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
ba9703b0
XL
442
443 /// The warning count, used for a recap upon finishing
444 deduplicated_warn_count: usize,
29967ef6
XL
445
446 future_breakage_diagnostics: Vec<Diagnostic>,
94222f64
XL
447
448 /// If set to `true`, no warning or error will be emitted.
449 quiet: bool,
e74abb32
XL
450}
451
452/// A key denoting where from a diagnostic was stashed.
453#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
454pub enum StashKey {
455 ItemNoType,
9cc50fc6
SL
456}
457
83c7162d
XL
458fn default_track_diagnostic(_: &Diagnostic) {}
459
dfeec247
XL
460pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
461 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
83c7162d 462
e1599b0c 463#[derive(Copy, Clone, Default)]
ff7c6d11 464pub struct HandlerFlags {
0bf4aa26
XL
465 /// If false, warning-level lints are suppressed.
466 /// (rustc: see `--allow warnings` and `--cap-lints`)
ff7c6d11 467 pub can_emit_warnings: bool,
0bf4aa26
XL
468 /// If true, error-level diagnostics are upgraded to bug-level.
469 /// (rustc: see `-Z treat-err-as-bug`)
6a06907d 470 pub treat_err_as_bug: Option<NonZeroUsize>,
0bf4aa26
XL
471 /// If true, immediately emit diagnostics that would otherwise be buffered.
472 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
473 pub dont_buffer_diagnostics: bool,
474 /// If true, immediately print bugs registered with `delay_span_bug`.
475 /// (rustc: see `-Z report-delayed-bugs`)
8faf50e0 476 pub report_delayed_bugs: bool,
74b04a01
XL
477 /// Show macro backtraces.
478 /// (rustc: see `-Z macro-backtrace`)
479 pub macro_backtrace: bool,
dfeec247
XL
480 /// If true, identical diagnostics are reported only once.
481 pub deduplicate_diagnostics: bool,
ff7c6d11
XL
482}
483
e1599b0c 484impl Drop for HandlerInner {
8faf50e0 485 fn drop(&mut self) {
e74abb32
XL
486 self.emit_stashed_diagnostics();
487
488 if !self.has_errors() {
e1599b0c 489 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
1b1a35ee
XL
490 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
491 }
492
493 if !self.has_any_message() {
494 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
495 self.flush_delayed(
17df50a5 496 bugs.into_iter().map(DelayedDiagnostic::decorate).collect(),
1b1a35ee
XL
497 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
498 );
8faf50e0
XL
499 }
500 }
501}
502
9cc50fc6 503impl Handler {
e74abb32
XL
504 pub fn with_tty_emitter(
505 color_config: ColorConfig,
506 can_emit_warnings: bool,
6a06907d 507 treat_err_as_bug: Option<NonZeroUsize>,
74b04a01 508 sm: Option<Lrc<SourceMap>>,
e74abb32
XL
509 ) -> Self {
510 Self::with_tty_emitter_and_flags(
ff7c6d11 511 color_config,
74b04a01 512 sm,
60c5eb7d 513 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
e74abb32 514 )
ff7c6d11
XL
515 }
516
e74abb32
XL
517 pub fn with_tty_emitter_and_flags(
518 color_config: ColorConfig,
74b04a01 519 sm: Option<Lrc<SourceMap>>,
e74abb32
XL
520 flags: HandlerFlags,
521 ) -> Self {
e1599b0c 522 let emitter = Box::new(EmitterWriter::stderr(
e74abb32 523 color_config,
74b04a01 524 sm,
e74abb32
XL
525 false,
526 false,
527 None,
74b04a01 528 flags.macro_backtrace,
e74abb32
XL
529 ));
530 Self::with_emitter_and_flags(emitter, flags)
531 }
532
533 pub fn with_emitter(
534 can_emit_warnings: bool,
6a06907d 535 treat_err_as_bug: Option<NonZeroUsize>,
e74abb32
XL
536 emitter: Box<dyn Emitter + sync::Send>,
537 ) -> Self {
ff7c6d11 538 Handler::with_emitter_and_flags(
e74abb32 539 emitter,
60c5eb7d 540 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
e74abb32 541 )
ff7c6d11
XL
542 }
543
e74abb32
XL
544 pub fn with_emitter_and_flags(
545 emitter: Box<dyn Emitter + sync::Send>,
60c5eb7d 546 flags: HandlerFlags,
e74abb32
XL
547 ) -> Self {
548 Self {
ff7c6d11 549 flags,
e1599b0c
XL
550 inner: Lock::new(HandlerInner {
551 flags,
552 err_count: 0,
1b1a35ee 553 warn_count: 0,
e1599b0c 554 deduplicated_err_count: 0,
ba9703b0 555 deduplicated_warn_count: 0,
e74abb32 556 emitter,
e1599b0c 557 delayed_span_bugs: Vec::new(),
1b1a35ee 558 delayed_good_path_bugs: Vec::new(),
e1599b0c
XL
559 taught_diagnostics: Default::default(),
560 emitted_diagnostic_codes: Default::default(),
561 emitted_diagnostics: Default::default(),
e74abb32 562 stashed_diagnostics: Default::default(),
29967ef6 563 future_breakage_diagnostics: Vec::new(),
94222f64 564 quiet: false,
e1599b0c 565 }),
9cc50fc6
SL
566 }
567 }
568
94222f64
XL
569 pub fn with_disabled_diagnostic<T, F: FnOnce() -> T>(&self, f: F) -> T {
570 let prev = self.inner.borrow_mut().quiet;
571 self.inner.borrow_mut().quiet = true;
572 let ret = f();
573 self.inner.borrow_mut().quiet = prev;
574 ret
575 }
576
e1599b0c 577 // This is here to not allow mutation of flags;
ba9703b0 578 // as of this writing it's only used in tests in librustc_middle.
e1599b0c
XL
579 pub fn can_emit_warnings(&self) -> bool {
580 self.flags.can_emit_warnings
7453a54e
SL
581 }
582
2c00a5a8
XL
583 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
584 ///
9fa01778 585 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
2c00a5a8
XL
586 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
587 /// the overall count of emitted error diagnostics.
ea8adc8c 588 pub fn reset_err_count(&self) {
e1599b0c 589 let mut inner = self.inner.borrow_mut();
e1599b0c 590 inner.err_count = 0;
1b1a35ee 591 inner.warn_count = 0;
e74abb32 592 inner.deduplicated_err_count = 0;
ba9703b0 593 inner.deduplicated_warn_count = 0;
e74abb32
XL
594
595 // actually free the underlying memory (which `clear` would not do)
596 inner.delayed_span_bugs = Default::default();
1b1a35ee 597 inner.delayed_good_path_bugs = Default::default();
e74abb32
XL
598 inner.taught_diagnostics = Default::default();
599 inner.emitted_diagnostic_codes = Default::default();
600 inner.emitted_diagnostics = Default::default();
601 inner.stashed_diagnostics = Default::default();
602 }
603
604 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
e74abb32
XL
605 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
606 let mut inner = self.inner.borrow_mut();
dfeec247
XL
607 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
608 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
609 // See the PR for a discussion.
610 inner.stashed_diagnostics.insert((span, key), diag);
e74abb32
XL
611 }
612
613 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
614 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
615 self.inner
616 .borrow_mut()
617 .stashed_diagnostics
618 .remove(&(span, key))
619 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
ea8adc8c
XL
620 }
621
e74abb32
XL
622 /// Emit all stashed diagnostics.
623 pub fn emit_stashed_diagnostics(&self) {
624 self.inner.borrow_mut().emit_stashed_diagnostics();
625 }
626
627 /// Construct a dummy builder with `Level::Cancelled`.
628 ///
629 /// Using this will neither report anything to the user (e.g. a warning),
630 /// nor will compilation cancel as a result.
416331ca 631 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
a7813a04 632 DiagnosticBuilder::new(self, Level::Cancelled, "")
9cc50fc6
SL
633 }
634
e74abb32 635 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
136023e0
XL
636 ///
637 /// The builder will be canceled if warnings cannot be emitted.
e74abb32
XL
638 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
639 let mut result = self.struct_warn(msg);
640 result.set_span(span);
9cc50fc6
SL
641 result
642 }
e74abb32 643
136023e0
XL
644 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
645 ///
646 /// This will "force" the warning meaning it will not be canceled even
647 /// if warnings cannot be emitted.
648 pub fn struct_span_force_warn(
649 &self,
650 span: impl Into<MultiSpan>,
651 msg: &str,
652 ) -> DiagnosticBuilder<'_> {
653 let mut result = self.struct_force_warn(msg);
654 result.set_span(span);
655 result
656 }
657
29967ef6
XL
658 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
659 pub fn struct_span_allow(
660 &self,
661 span: impl Into<MultiSpan>,
662 msg: &str,
663 ) -> DiagnosticBuilder<'_> {
664 let mut result = self.struct_allow(msg);
665 result.set_span(span);
666 result
667 }
668
e74abb32
XL
669 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
670 /// Also include a code.
671 pub fn struct_span_warn_with_code(
672 &self,
673 span: impl Into<MultiSpan>,
674 msg: &str,
675 code: DiagnosticId,
676 ) -> DiagnosticBuilder<'_> {
677 let mut result = self.struct_span_warn(span, msg);
abe05a73 678 result.code(code);
9cc50fc6
SL
679 result
680 }
e74abb32
XL
681
682 /// Construct a builder at the `Warning` level with the `msg`.
136023e0
XL
683 ///
684 /// The builder will be canceled if warnings cannot be emitted.
416331ca 685 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
a7813a04 686 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
ff7c6d11 687 if !self.flags.can_emit_warnings {
9cc50fc6
SL
688 result.cancel();
689 }
690 result
691 }
e74abb32 692
136023e0
XL
693 /// Construct a builder at the `Warning` level with the `msg`.
694 ///
695 /// This will "force" a warning meaning it will not be canceled even
696 /// if warnings cannot be emitted.
697 pub fn struct_force_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
698 DiagnosticBuilder::new(self, Level::Warning, msg)
699 }
700
29967ef6
XL
701 /// Construct a builder at the `Allow` level with the `msg`.
702 pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_> {
703 DiagnosticBuilder::new(self, Level::Allow, msg)
704 }
705
e74abb32
XL
706 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
707 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
708 let mut result = self.struct_err(msg);
709 result.set_span(span);
9cc50fc6
SL
710 result
711 }
e74abb32
XL
712
713 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
714 pub fn struct_span_err_with_code(
715 &self,
716 span: impl Into<MultiSpan>,
717 msg: &str,
718 code: DiagnosticId,
719 ) -> DiagnosticBuilder<'_> {
720 let mut result = self.struct_span_err(span, msg);
abe05a73 721 result.code(code);
9cc50fc6
SL
722 result
723 }
e74abb32
XL
724
725 /// Construct a builder at the `Error` level with the `msg`.
7cac9316 726 // FIXME: This method should be removed (every error should have an associated error code).
416331ca 727 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
a7813a04 728 DiagnosticBuilder::new(self, Level::Error, msg)
9cc50fc6 729 }
e74abb32
XL
730
731 /// Construct a builder at the `Error` level with the `msg` and the `code`.
732 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
733 let mut result = self.struct_err(msg);
abe05a73 734 result.code(code);
7cac9316
XL
735 result
736 }
e74abb32
XL
737
738 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
739 pub fn struct_span_fatal(
740 &self,
741 span: impl Into<MultiSpan>,
742 msg: &str,
743 ) -> DiagnosticBuilder<'_> {
744 let mut result = self.struct_fatal(msg);
745 result.set_span(span);
9cc50fc6
SL
746 result
747 }
e74abb32
XL
748
749 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
750 pub fn struct_span_fatal_with_code(
751 &self,
752 span: impl Into<MultiSpan>,
753 msg: &str,
754 code: DiagnosticId,
755 ) -> DiagnosticBuilder<'_> {
756 let mut result = self.struct_span_fatal(span, msg);
abe05a73 757 result.code(code);
9cc50fc6
SL
758 result
759 }
e74abb32
XL
760
761 /// Construct a builder at the `Error` level with the `msg`.
416331ca 762 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
a7813a04 763 DiagnosticBuilder::new(self, Level::Fatal, msg)
9cc50fc6
SL
764 }
765
60c5eb7d
XL
766 /// Construct a builder at the `Help` level with the `msg`.
767 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
768 DiagnosticBuilder::new(self, Level::Help, msg)
769 }
770
f035d41b
XL
771 /// Construct a builder at the `Note` level with the `msg`.
772 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
773 DiagnosticBuilder::new(self, Level::Note, msg)
774 }
775
17df50a5 776 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
e74abb32 777 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
17df50a5 778 FatalError.raise()
9cc50fc6 779 }
e74abb32
XL
780
781 pub fn span_fatal_with_code(
782 &self,
783 span: impl Into<MultiSpan>,
784 msg: &str,
785 code: DiagnosticId,
17df50a5 786 ) -> ! {
e74abb32 787 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
17df50a5 788 FatalError.raise()
9cc50fc6 789 }
e74abb32
XL
790
791 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
792 self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
9e0c209e 793 }
e74abb32
XL
794
795 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
796 self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
9cc50fc6 797 }
e74abb32
XL
798
799 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
800 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
9cc50fc6 801 }
e74abb32
XL
802
803 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
804 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
9cc50fc6 805 }
e74abb32
XL
806
807 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
808 self.inner.borrow_mut().span_bug(span, msg)
9cc50fc6 809 }
e74abb32 810
f035d41b 811 #[track_caller]
e74abb32
XL
812 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
813 self.inner.borrow_mut().delay_span_bug(span, msg)
9cc50fc6 814 }
e74abb32 815
1b1a35ee
XL
816 pub fn delay_good_path_bug(&self, msg: &str) {
817 self.inner.borrow_mut().delay_good_path_bug(msg)
818 }
819
e74abb32
XL
820 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
821 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
9cc50fc6 822 }
e74abb32
XL
823
824 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
825 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
9cc50fc6 826 }
e74abb32
XL
827
828 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
7cac9316 829 let mut db = DiagnosticBuilder::new(self, Note, msg);
e74abb32 830 db.set_span(span);
7cac9316
XL
831 db
832 }
e74abb32 833
17df50a5 834 // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
9cc50fc6 835 pub fn fatal(&self, msg: &str) -> FatalError {
e1599b0c 836 self.inner.borrow_mut().fatal(msg)
9cc50fc6 837 }
e74abb32 838
9cc50fc6 839 pub fn err(&self, msg: &str) {
e1599b0c 840 self.inner.borrow_mut().err(msg);
9cc50fc6 841 }
e74abb32 842
9cc50fc6 843 pub fn warn(&self, msg: &str) {
c30ab7b3 844 let mut db = DiagnosticBuilder::new(self, Warning, msg);
5bcae85e 845 db.emit();
9cc50fc6 846 }
e74abb32 847
9cc50fc6 848 pub fn note_without_error(&self, msg: &str) {
e74abb32 849 DiagnosticBuilder::new(self, Note, msg).emit();
9cc50fc6 850 }
e74abb32 851
9cc50fc6 852 pub fn bug(&self, msg: &str) -> ! {
e1599b0c 853 self.inner.borrow_mut().bug(msg)
9cc50fc6
SL
854 }
855
17df50a5 856 #[inline]
9cc50fc6 857 pub fn err_count(&self) -> usize {
e74abb32 858 self.inner.borrow().err_count()
9cc50fc6
SL
859 }
860
861 pub fn has_errors(&self) -> bool {
e74abb32
XL
862 self.inner.borrow().has_errors()
863 }
864 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
865 self.inner.borrow().has_errors_or_delayed_span_bugs()
9cc50fc6 866 }
0531ce1d 867
48663c56 868 pub fn print_error_count(&self, registry: &Registry) {
e1599b0c
XL
869 self.inner.borrow_mut().print_error_count(registry)
870 }
871
29967ef6
XL
872 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
873 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
874 }
875
e1599b0c 876 pub fn abort_if_errors(&self) {
e74abb32 877 self.inner.borrow_mut().abort_if_errors()
e1599b0c
XL
878 }
879
e74abb32
XL
880 /// `true` if we haven't taught a diagnostic with this code already.
881 /// The caller must then teach the user about such a diagnostic.
882 ///
883 /// Used to suppress emitting the same error multiple times with extended explanation when
884 /// calling `-Zteach`.
e1599b0c
XL
885 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
886 self.inner.borrow_mut().must_teach(code)
887 }
888
889 pub fn force_print_diagnostic(&self, db: Diagnostic) {
890 self.inner.borrow_mut().force_print_diagnostic(db)
891 }
892
893 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
894 self.inner.borrow_mut().emit_diagnostic(diagnostic)
895 }
896
e74abb32
XL
897 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
898 let mut inner = self.inner.borrow_mut();
899 inner.emit_diagnostic(diag.set_span(sp));
e74abb32
XL
900 }
901
e1599b0c
XL
902 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
903 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
904 }
905
136023e0 906 pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
29967ef6
XL
907 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
908 }
909
cdc7bbd5
XL
910 pub fn emit_unused_externs(&self, lint_level: &str, unused_externs: &[&str]) {
911 self.inner.borrow_mut().emit_unused_externs(lint_level, unused_externs)
912 }
913
e1599b0c
XL
914 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
915 self.inner.borrow_mut().delay_as_bug(diagnostic)
916 }
917}
918
919impl HandlerInner {
e1599b0c
XL
920 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
921 self.taught_diagnostics.insert(code.clone())
922 }
923
924 fn force_print_diagnostic(&mut self, db: Diagnostic) {
925 self.emitter.emit_diagnostic(&db);
926 }
927
e74abb32
XL
928 /// Emit all stashed diagnostics.
929 fn emit_stashed_diagnostics(&mut self) {
930 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
931 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
932 }
933
e1599b0c 934 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
94222f64 935 if diagnostic.cancelled() || self.quiet {
e1599b0c
XL
936 return;
937 }
938
29967ef6
XL
939 if diagnostic.has_future_breakage() {
940 self.future_breakage_diagnostics.push(diagnostic.clone());
941 }
942
136023e0
XL
943 if diagnostic.level == Warning
944 && !self.flags.can_emit_warnings
945 && !diagnostic.is_force_warn()
946 {
29967ef6
XL
947 if diagnostic.has_future_breakage() {
948 (*TRACK_DIAGNOSTICS)(diagnostic);
949 }
e1599b0c
XL
950 return;
951 }
952
dfeec247 953 (*TRACK_DIAGNOSTICS)(diagnostic);
e1599b0c 954
29967ef6
XL
955 if diagnostic.level == Allow {
956 return;
957 }
958
e1599b0c
XL
959 if let Some(ref code) = diagnostic.code {
960 self.emitted_diagnostic_codes.insert(code.clone());
961 }
962
dfeec247 963 let already_emitted = |this: &mut Self| {
e1599b0c
XL
964 let mut hasher = StableHasher::new();
965 diagnostic.hash(&mut hasher);
dfeec247
XL
966 let diagnostic_hash = hasher.finish();
967 !this.emitted_diagnostics.insert(diagnostic_hash)
e1599b0c
XL
968 };
969
dfeec247
XL
970 // Only emit the diagnostic if we've been asked to deduplicate and
971 // haven't already emitted an equivalent diagnostic.
972 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
e1599b0c
XL
973 self.emitter.emit_diagnostic(diagnostic);
974 if diagnostic.is_error() {
975 self.deduplicated_err_count += 1;
ba9703b0
XL
976 } else if diagnostic.level == Warning {
977 self.deduplicated_warn_count += 1;
e1599b0c
XL
978 }
979 }
980 if diagnostic.is_error() {
981 self.bump_err_count();
1b1a35ee
XL
982 } else {
983 self.bump_warn_count();
e1599b0c
XL
984 }
985 }
986
987 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
988 self.emitter.emit_artifact_notification(path, artifact_type);
cdc7bbd5
XL
989 }
990
991 fn emit_unused_externs(&mut self, lint_level: &str, unused_externs: &[&str]) {
992 self.emitter.emit_unused_externs(lint_level, unused_externs);
e1599b0c
XL
993 }
994
995 fn treat_err_as_bug(&self) -> bool {
6a06907d 996 self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() >= c.get())
e1599b0c
XL
997 }
998
999 fn print_error_count(&mut self, registry: &Registry) {
e74abb32
XL
1000 self.emit_stashed_diagnostics();
1001
ba9703b0
XL
1002 let warnings = match self.deduplicated_warn_count {
1003 0 => String::new(),
1004 1 => "1 warning emitted".to_string(),
1005 count => format!("{} warnings emitted", count),
1006 };
1007 let errors = match self.deduplicated_err_count {
1008 0 => String::new(),
0531ce1d 1009 1 => "aborting due to previous error".to_string(),
60c5eb7d 1010 count => format!("aborting due to {} previous errors", count),
0531ce1d 1011 };
532ac7d7
XL
1012 if self.treat_err_as_bug() {
1013 return;
1014 }
0531ce1d 1015
ba9703b0
XL
1016 match (errors.len(), warnings.len()) {
1017 (0, 0) => return,
136023e0 1018 (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(Level::Warning, &warnings)),
ba9703b0
XL
1019 (_, 0) => {
1020 let _ = self.fatal(&errors);
1021 }
1022 (_, _) => {
1023 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1024 }
1025 }
0531ce1d 1026
e1599b0c
XL
1027 let can_show_explain = self.emitter.should_show_explain();
1028 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
0531ce1d 1029 if can_show_explain && are_there_diagnostics {
48663c56
XL
1030 let mut error_codes = self
1031 .emitted_diagnostic_codes
48663c56 1032 .iter()
c295e0f8 1033 .filter_map(|x| match &x {
94222f64 1034 DiagnosticId::Error(s)
c295e0f8 1035 if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
94222f64
XL
1036 {
1037 Some(s.clone())
48663c56
XL
1038 }
1039 _ => None,
1040 })
1041 .collect::<Vec<_>>();
0531ce1d
XL
1042 if !error_codes.is_empty() {
1043 error_codes.sort();
1044 if error_codes.len() > 1 {
1045 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
60c5eb7d
XL
1046 self.failure(&format!(
1047 "Some errors have detailed explanations: {}{}",
1048 error_codes[..limit].join(", "),
1049 if error_codes.len() > 9 { "..." } else { "." }
1050 ));
1051 self.failure(&format!(
1052 "For more information about an error, try \
ba9703b0 1053 `rustc --explain {}`.",
60c5eb7d
XL
1054 &error_codes[0]
1055 ));
0531ce1d 1056 } else {
60c5eb7d
XL
1057 self.failure(&format!(
1058 "For more information about this error, try \
ba9703b0 1059 `rustc --explain {}`.",
60c5eb7d
XL
1060 &error_codes[0]
1061 ));
9cc50fc6 1062 }
041b39d2 1063 }
9cc50fc6 1064 }
0531ce1d 1065 }
9cc50fc6 1066
17df50a5 1067 #[inline]
e74abb32
XL
1068 fn err_count(&self) -> usize {
1069 self.err_count + self.stashed_diagnostics.len()
1070 }
1071
1072 fn has_errors(&self) -> bool {
1073 self.err_count() > 0
1074 }
1075 fn has_errors_or_delayed_span_bugs(&self) -> bool {
1076 self.has_errors() || !self.delayed_span_bugs.is_empty()
1077 }
1b1a35ee
XL
1078 fn has_any_message(&self) -> bool {
1079 self.err_count() > 0 || self.warn_count > 0
1080 }
e74abb32 1081
e74abb32
XL
1082 fn abort_if_errors(&mut self) {
1083 self.emit_stashed_diagnostics();
1084
1085 if self.has_errors() {
e1599b0c 1086 FatalError.raise();
c30ab7b3 1087 }
9cc50fc6 1088 }
3b2f2976 1089
e74abb32
XL
1090 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
1091 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
5869c6ff 1092 panic::panic_any(ExplicitBug);
83c7162d
XL
1093 }
1094
e74abb32
XL
1095 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1096 self.emit_diagnostic(diag.set_span(sp));
e74abb32
XL
1097 }
1098
f035d41b 1099 #[track_caller]
e74abb32 1100 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
f9f354fc
XL
1101 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1102 // incrementing `err_count` by one, so we need to +1 the comparing.
1103 // FIXME: Would be nice to increment err_count in a more coherent way.
6a06907d 1104 if self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() + 1 >= c.get()) {
e1599b0c
XL
1105 // FIXME: don't abort here if report_delayed_bugs is off
1106 self.span_bug(sp, msg);
1107 }
1108 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
1109 diagnostic.set_span(sp.into());
f035d41b 1110 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
e1599b0c 1111 self.delay_as_bug(diagnostic)
2c00a5a8
XL
1112 }
1113
1b1a35ee 1114 fn delay_good_path_bug(&mut self, msg: &str) {
17df50a5 1115 let diagnostic = Diagnostic::new(Level::Bug, msg);
1b1a35ee
XL
1116 if self.flags.report_delayed_bugs {
1117 self.emit_diagnostic(&diagnostic);
1118 }
17df50a5
XL
1119 let backtrace = std::backtrace::Backtrace::force_capture();
1120 self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1b1a35ee
XL
1121 }
1122
e1599b0c
XL
1123 fn failure(&mut self, msg: &str) {
1124 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
1125 }
abe05a73 1126
e1599b0c 1127 fn fatal(&mut self, msg: &str) -> FatalError {
e74abb32 1128 self.emit_error(Fatal, msg);
e1599b0c
XL
1129 FatalError
1130 }
abe05a73 1131
e1599b0c 1132 fn err(&mut self, msg: &str) {
e74abb32
XL
1133 self.emit_error(Error, msg);
1134 }
1135
1136 /// Emit an error; level should be `Error` or `Fatal`.
60c5eb7d 1137 fn emit_error(&mut self, level: Level, msg: &str) {
e1599b0c
XL
1138 if self.treat_err_as_bug() {
1139 self.bug(msg);
2c00a5a8 1140 }
e74abb32 1141 self.emit_diagnostic(&Diagnostic::new(level, msg));
e1599b0c 1142 }
2c00a5a8 1143
e1599b0c
XL
1144 fn bug(&mut self, msg: &str) -> ! {
1145 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
5869c6ff 1146 panic::panic_any(ExplicitBug);
e1599b0c 1147 }
abe05a73 1148
e1599b0c 1149 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
94222f64
XL
1150 if self.quiet {
1151 return;
1152 }
e1599b0c
XL
1153 if self.flags.report_delayed_bugs {
1154 self.emit_diagnostic(&diagnostic);
dc9dc135 1155 }
e1599b0c 1156 self.delayed_span_bugs.push(diagnostic);
3b2f2976 1157 }
9cc50fc6 1158
1b1a35ee
XL
1159 fn flush_delayed(&mut self, bugs: Vec<Diagnostic>, explanation: &str) {
1160 let has_bugs = !bugs.is_empty();
1161 for bug in bugs {
1162 self.emit_diagnostic(&bug);
1163 }
1164 if has_bugs {
1165 panic!("{}", explanation);
1166 }
1167 }
1168
e1599b0c
XL
1169 fn bump_err_count(&mut self) {
1170 self.err_count += 1;
1171 self.panic_if_treat_err_as_bug();
1172 }
1173
1b1a35ee
XL
1174 fn bump_warn_count(&mut self) {
1175 self.warn_count += 1;
1176 }
1177
e1599b0c
XL
1178 fn panic_if_treat_err_as_bug(&self) {
1179 if self.treat_err_as_bug() {
6a06907d 1180 match (self.err_count(), self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0)) {
1b1a35ee
XL
1181 (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1182 (0, _) | (1, _) => {}
1183 (count, as_bug) => panic!(
60c5eb7d
XL
1184 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1185 count, as_bug,
1186 ),
1b1a35ee 1187 }
e1599b0c 1188 }
48663c56
XL
1189 }
1190}
9cc50fc6 1191
17df50a5
XL
1192struct DelayedDiagnostic {
1193 inner: Diagnostic,
1194 note: Backtrace,
1195}
1196
1197impl DelayedDiagnostic {
1198 fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1199 DelayedDiagnostic { inner: diagnostic, note: backtrace }
1200 }
1201
1202 fn decorate(mut self) -> Diagnostic {
1203 self.inner.note(&format!("delayed at {}", self.note));
1204 self.inner
1205 }
1206}
1207
3dfed10e 1208#[derive(Copy, PartialEq, Clone, Hash, Debug, Encodable, Decodable)]
9cc50fc6
SL
1209pub enum Level {
1210 Bug,
1211 Fatal,
1212 Error,
1213 Warning,
1214 Note,
1215 Help,
1216 Cancelled,
0531ce1d 1217 FailureNote,
29967ef6 1218 Allow,
9cc50fc6
SL
1219}
1220
1221impl fmt::Display for Level {
9fa01778 1222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9cc50fc6
SL
1223 self.to_str().fmt(f)
1224 }
1225}
1226
1227impl Level {
0531ce1d
XL
1228 fn color(self) -> ColorSpec {
1229 let mut spec = ColorSpec::new();
9cc50fc6 1230 match self {
e1599b0c 1231 Bug | Fatal | Error => {
60c5eb7d 1232 spec.set_fg(Some(Color::Red)).set_intense(true);
0531ce1d 1233 }
9e0c209e 1234 Warning => {
60c5eb7d 1235 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
c30ab7b3 1236 }
0531ce1d 1237 Note => {
60c5eb7d 1238 spec.set_fg(Some(Color::Green)).set_intense(true);
0531ce1d
XL
1239 }
1240 Help => {
60c5eb7d 1241 spec.set_fg(Some(Color::Cyan)).set_intense(true);
0531ce1d
XL
1242 }
1243 FailureNote => {}
29967ef6 1244 Allow | Cancelled => unreachable!(),
9cc50fc6 1245 }
0531ce1d 1246 spec
9cc50fc6
SL
1247 }
1248
3157f602 1249 pub fn to_str(self) -> &'static str {
9cc50fc6
SL
1250 match self {
1251 Bug => "error: internal compiler error",
e1599b0c 1252 Fatal | Error => "error",
9cc50fc6
SL
1253 Warning => "warning",
1254 Note => "note",
1255 Help => "help",
e1599b0c 1256 FailureNote => "failure-note",
9cc50fc6 1257 Cancelled => panic!("Shouldn't call on cancelled error"),
29967ef6 1258 Allow => panic!("Shouldn't call on allowed error"),
9cc50fc6
SL
1259 }
1260 }
0531ce1d
XL
1261
1262 pub fn is_failure_note(&self) -> bool {
29967ef6 1263 matches!(*self, FailureNote)
0531ce1d 1264 }
9cc50fc6 1265}
e1599b0c 1266
29967ef6
XL
1267pub fn add_elided_lifetime_in_path_suggestion(
1268 source_map: &SourceMap,
1269 db: &mut DiagnosticBuilder<'_>,
1270 n: usize,
1271 path_span: Span,
1272 incl_angl_brckt: bool,
1273 insertion_span: Span,
1274 anon_lts: String,
1275) {
1276 let (replace_span, suggestion) = if incl_angl_brckt {
1277 (insertion_span, anon_lts)
1278 } else {
1279 // When possible, prefer a suggestion that replaces the whole
1280 // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
1281 // at a point (which makes for an ugly/confusing label)
1282 if let Ok(snippet) = source_map.span_to_snippet(path_span) {
1283 // But our spans can get out of whack due to macros; if the place we think
1284 // we want to insert `'_` isn't even within the path expression's span, we
1285 // should bail out of making any suggestion rather than panicking on a
1286 // subtract-with-overflow or string-slice-out-out-bounds (!)
1287 // FIXME: can we do better?
1288 if insertion_span.lo().0 < path_span.lo().0 {
1289 return;
1290 }
1291 let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
1292 if insertion_index > snippet.len() {
1293 return;
1294 }
1295 let (before, after) = snippet.split_at(insertion_index);
1296 (path_span, format!("{}{}{}", before, anon_lts, after))
1297 } else {
1298 (insertion_span, anon_lts)
1299 }
e1599b0c 1300 };
29967ef6
XL
1301 db.span_suggestion(
1302 replace_span,
1303 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1304 suggestion,
1305 Applicability::MachineApplicable,
1306 );
e1599b0c 1307}
60c5eb7d
XL
1308
1309// Useful type to use with `Result<>` indicate that an error has already
1310// been reported to the user, so no need to continue checking.
3dfed10e 1311#[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq)]
60c5eb7d
XL
1312pub struct ErrorReported;
1313
1314rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);