1#![feature(default_field_values)]
7#![feature(macro_metavar_expr_concat)]
8#![feature(negative_impls)]
9extern crate self as rustc_errors;
12
13use std::backtrace::{Backtrace, BacktraceStatus};
14use std::borrow::Cow;
15use std::cell::Cell;
16use std::ffi::OsStr;
17use std::hash::Hash;
18use std::io::Write;
19use std::num::NonZero;
20use std::ops::DerefMut;
21use std::path::{Path, PathBuf};
22use std::thread::ThreadId;
23use std::{assert_matches, fmt, mem, panic};
24
25use Level::*;
26pub use anstream::{AutoStream, ColorChoice};
29pub use anstyle::{
30 Ansi256Color, AnsiColor, Color, EffectIter, Effects, Reset, RgbColor, Style as Anstyle,
31};
32pub use codes::*;
33pub use decorate_diag::{BufferedEarlyLint, DecorateDiagCompat, LintBuffer};
34pub use diagnostic::{
35 Diag, DiagDecorator, DiagInner, DiagLocation, DiagStyledString, Diagnostic, StringPart,
36 Subdiag, Subdiagnostic,
37};
38pub use diagnostic_impls::{
39 DiagSymbolList, ElidedLifetimeInPathSubdiag, ExpectedLifetimeParameter,
40 IndicateAnonymousLifetime, SingleLabelManySpans,
41};
42pub use emitter::ColorConfig;
43use emitter::{DynEmitter, Emitter};
44use rustc_ast::attr::version::RustcVersion;
45use rustc_data_structures::AtomicRef;
46use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
47use rustc_data_structures::sync::{DynSend, Lock};
48pub use rustc_error_messages::{
49 DiagArg, DiagArgFromDisplay, DiagArgMap, DiagArgName, DiagArgValue, DiagMessage, IntoDiagArg,
50 LanguageIdentifier, MultiSpan, SpanLabel, fluent_bundle, into_diag_arg_using_display,
51};
52use rustc_hashes::Hash128;
53use rustc_lint_defs::LintExpectationId;
54pub use rustc_lint_defs::{Applicability, listify, pluralize};
55pub use rustc_macros::msg;
56use rustc_macros::{Decodable, Encodable};
57pub use rustc_span::ErrorGuaranteed;
58pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker, catch_fatal_errors};
59pub use rustc_span::macros::ExplicitBug;
60use rustc_span::source_map::SourceMap;
61use rustc_span::{DUMMY_SP, Span};
62use tracing::debug;
63
64use crate::emitter::TimingEvent;
65use crate::formatting::DiagMessageAddArg;
66pub use crate::formatting::format_diag_message;
67use crate::timings::TimingRecord;
68
69pub mod annotate_snippet_emitter_writer;
70pub mod codes;
71mod decorate_diag;
72mod dedup_hash;
73mod diagnostic;
74mod diagnostic_impls;
75pub mod emitter;
76pub mod formatting;
77pub mod json;
78mod lock;
79pub mod markdown;
80pub mod timings;
81
82pub type PResult<'a, T> = Result<T, Diag<'a>>;
83
84#[cfg(target_pointer_width = "64")]
86const _: [(); 24] = [(); ::std::mem::size_of::<PResult<'_, ()>>()];rustc_data_structures::static_assert_size!(PResult<'_, ()>, 24);
87#[cfg(target_pointer_width = "64")]
88const _: [(); 24] = [(); ::std::mem::size_of::<PResult<'_, bool>>()];rustc_data_structures::static_assert_size!(PResult<'_, bool>, 24);
89
90#[derive(#[automatically_derived]impl ::core::fmt::Debug for SuggestionStyle {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_c_like_enum_write_str(f,
"HideCodeInline HideCodeAlways CompletelyHidden ShowCode ShowAlways",
match self {
SuggestionStyle::HideCodeInline => 0usize,
SuggestionStyle::HideCodeAlways => 15usize,
SuggestionStyle::CompletelyHidden => 30usize,
SuggestionStyle::ShowCode => 47usize,
SuggestionStyle::ShowAlways => 56usize,
})
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
SuggestionStyle {
}
#[automatically_derived]impl ::core::cmp::PartialEq for SuggestionStyle {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for SuggestionStyle { }Eq, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for SuggestionStyle {
}
#[automatically_derived]impl ::core::clone::Clone for SuggestionStyle {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for SuggestionStyle { }Copy, #[automatically_derived]impl ::core::hash::Hash for SuggestionStyle {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state)
}
}Hash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for SuggestionStyle {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
SuggestionStyle::HideCodeInline => { 0usize }
SuggestionStyle::HideCodeAlways => { 1usize }
SuggestionStyle::CompletelyHidden => { 2usize }
SuggestionStyle::ShowCode => { 3usize }
SuggestionStyle::ShowAlways => { 4usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for SuggestionStyle {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { SuggestionStyle::HideCodeInline }
1usize => { SuggestionStyle::HideCodeAlways }
2usize => { SuggestionStyle::CompletelyHidden }
3usize => { SuggestionStyle::ShowCode }
4usize => { SuggestionStyle::ShowAlways }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `SuggestionStyle`, expected 0..5, actual {0}",
n));
}
}
}
}
};Decodable)]
91pub enum SuggestionStyle {
92 HideCodeInline,
94 HideCodeAlways,
96 CompletelyHidden,
98 ShowCode,
102 ShowAlways,
104}
105
106impl SuggestionStyle {
107 fn hide_inline(&self) -> bool {
108 !#[allow(non_exhaustive_omitted_patterns)] match *self {
SuggestionStyle::ShowCode => true,
_ => false,
}matches!(*self, SuggestionStyle::ShowCode)
109 }
110}
111
112#[derive(#[automatically_derived]impl ::core::clone::Clone for Suggestions {
#[inline]
fn clone(&self) -> Self {
match self {
Self::Enabled(__self_0) =>
Suggestions::Enabled(::core::clone::Clone::clone(__self_0)),
Self::Sealed(__self_0) =>
Suggestions::Sealed(::core::clone::Clone::clone(__self_0)),
Self::Disabled => Suggestions::Disabled,
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Suggestions {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Enabled(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Enabled", &__self_0),
Self::Sealed(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Sealed", &__self_0),
Self::Disabled =>
::core::fmt::Formatter::write_str(f, "Disabled"),
}
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
Suggestions {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Suggestions {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Enabled(__self_0), Self::Enabled(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Sealed(__self_0), Self::Sealed(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]impl ::core::hash::Hash for Suggestions {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state);
match self {
Self::Enabled(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Self::Sealed(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
_ => {}
}
}
}Hash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for Suggestions {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
Suggestions::Enabled(ref __binding_0) => { 0usize }
Suggestions::Sealed(ref __binding_0) => { 1usize }
Suggestions::Disabled => { 2usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
Suggestions::Enabled(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
Suggestions::Sealed(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
Suggestions::Disabled => {}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for Suggestions {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => {
Suggestions::Enabled(::rustc_serialize::Decodable::decode(__decoder))
}
1usize => {
Suggestions::Sealed(::rustc_serialize::Decodable::decode(__decoder))
}
2usize => { Suggestions::Disabled }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Suggestions`, expected 0..3, actual {0}",
n));
}
}
}
}
};Decodable)]
114pub enum Suggestions {
115 Enabled(Vec<CodeSuggestion>),
120 Sealed(Box<[CodeSuggestion]>),
124 Disabled,
128}
129
130impl Suggestions {
131 pub fn unwrap_tag(self) -> Vec<CodeSuggestion> {
133 match self {
134 Suggestions::Enabled(suggestions) => suggestions,
135 Suggestions::Sealed(suggestions) => suggestions.into_vec(),
136 Suggestions::Disabled => Vec::new(),
137 }
138 }
139
140 pub fn len(&self) -> usize {
141 match self {
142 Suggestions::Enabled(suggestions) => suggestions.len(),
143 Suggestions::Sealed(suggestions) => suggestions.len(),
144 Suggestions::Disabled => 0,
145 }
146 }
147}
148
149impl Default for Suggestions {
150 fn default() -> Self {
151 Self::Enabled(::alloc::vec::Vec::new()vec![])
152 }
153}
154
155#[derive(#[automatically_derived]impl ::core::clone::Clone for CodeSuggestion {
#[inline]
fn clone(&self) -> Self {
CodeSuggestion {
substitutions: ::core::clone::Clone::clone(&self.substitutions),
msg: ::core::clone::Clone::clone(&self.msg),
style: ::core::clone::Clone::clone(&self.style),
applicability: ::core::clone::Clone::clone(&self.applicability),
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for CodeSuggestion {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"CodeSuggestion substitutions msg style applicability",
&self.substitutions, &self.msg, &self.style, &&self.applicability)
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
CodeSuggestion {
}
#[automatically_derived]impl ::core::cmp::PartialEq for CodeSuggestion {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.substitutions == other.substitutions && self.msg == other.msg &&
self.style == other.style &&
self.applicability == other.applicability
}
}PartialEq, #[automatically_derived]impl ::core::hash::Hash for CodeSuggestion {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.substitutions, state);
::core::hash::Hash::hash(&self.msg, state);
::core::hash::Hash::hash(&self.style, state);
::core::hash::Hash::hash(&self.applicability, state)
}
}Hash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for CodeSuggestion {
fn encode(&self, __encoder: &mut __E) {
let CodeSuggestion {
substitutions: ref __binding_0,
msg: ref __binding_1,
style: ref __binding_2,
applicability: ref __binding_3 } = *self;
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for CodeSuggestion {
fn decode(__decoder: &mut __D) -> Self {
CodeSuggestion {
substitutions: ::rustc_serialize::Decodable::decode(__decoder),
msg: ::rustc_serialize::Decodable::decode(__decoder),
style: ::rustc_serialize::Decodable::decode(__decoder),
applicability: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
156pub struct CodeSuggestion {
157 pub substitutions: Vec<Substitution>,
179 pub msg: DiagMessage,
180 pub style: SuggestionStyle,
182 pub applicability: Applicability,
188}
189
190#[derive(#[automatically_derived]impl ::core::clone::Clone for Substitution {
#[inline]
fn clone(&self) -> Self {
Substitution { parts: ::core::clone::Clone::clone(&self.parts) }
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Substitution {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Substitution parts", &&self.parts)
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
Substitution {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Substitution {
#[inline]
fn eq(&self, other: &Self) -> bool { self.parts == other.parts }
}PartialEq, #[automatically_derived]impl ::core::hash::Hash for Substitution {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.parts, state)
}
}Hash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for Substitution {
fn encode(&self, __encoder: &mut __E) {
let Substitution { parts: ref __binding_0 } = *self;
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for Substitution {
fn decode(__decoder: &mut __D) -> Self {
Substitution {
parts: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
191pub struct Substitution {
193 pub parts: Vec<SubstitutionPart>,
194}
195
196#[derive(#[automatically_derived]impl ::core::clone::Clone for SubstitutionPart {
#[inline]
fn clone(&self) -> Self {
SubstitutionPart {
span: ::core::clone::Clone::clone(&self.span),
snippet: ::core::clone::Clone::clone(&self.snippet),
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for SubstitutionPart {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"SubstitutionPart span snippet", &self.span, &&self.snippet)
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
SubstitutionPart {
}
#[automatically_derived]impl ::core::cmp::PartialEq for SubstitutionPart {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.span == other.span && self.snippet == other.snippet
}
}PartialEq, #[automatically_derived]impl ::core::hash::Hash for SubstitutionPart {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.span, state);
::core::hash::Hash::hash(&self.snippet, state)
}
}Hash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for SubstitutionPart {
fn encode(&self, __encoder: &mut __E) {
let SubstitutionPart {
span: ref __binding_0, snippet: ref __binding_1 } = *self;
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for SubstitutionPart {
fn decode(__decoder: &mut __D) -> Self {
SubstitutionPart {
span: ::rustc_serialize::Decodable::decode(__decoder),
snippet: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
197pub struct SubstitutionPart {
198 pub span: Span,
199 pub snippet: String,
200}
201
202pub struct DelayedBugPanic;
205
206pub struct DiagCtxt {
213 inner: Lock<DiagCtxtInner>,
214}
215
216#[derive(#[automatically_derived]impl<'a> ::core::marker::Copy for DiagCtxtHandle<'a> {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'a>
::core::clone::TrivialClone for DiagCtxtHandle<'a> {
}
#[automatically_derived]impl<'a> ::core::clone::Clone for DiagCtxtHandle<'a> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<&'a DiagCtxt>;
let _:
::core::clone::AssertParamIsClone<Option<&'a Cell<Option<ErrorGuaranteed>>>>;
*self
}
}Clone)]
217pub struct DiagCtxtHandle<'a> {
218 dcx: &'a DiagCtxt,
219 tainted_with_errors: Option<&'a Cell<Option<ErrorGuaranteed>>>,
222}
223
224struct DiagCtxtInner {
231 flags: DiagCtxtFlags,
232
233 err_guars: Vec<(ErrorGuaranteed, ThreadId)>,
236 lint_err_guars: Vec<(ErrorGuaranteed, ThreadId)>,
239 delayed_bugs: Vec<(DelayedDiagInner, ErrorGuaranteed)>,
241
242 deduplicated_err_count: usize,
244 deduplicated_warn_count: usize,
246
247 emitter: Box<DynEmitter>,
248
249 must_produce_diag: Option<Backtrace>,
252
253 has_printed: bool,
256
257 suppressed_expected_diag: bool,
260
261 taught_diagnostics: FxHashSet<ErrCode>,
265
266 emitted_diagnostic_codes: FxIndexSet<ErrCode>,
268
269 emitted_diagnostics: FxHashSet<Hash128>,
275
276 emitted_recursion_depth_exceeding_limit: bool,
284
285 stashed_diagnostics:
291 FxIndexMap<StashKey, FxIndexMap<Span, (DiagInner, Option<ErrorGuaranteed>, ThreadId)>>,
292
293 future_breakage_diagnostics: Vec<DiagInner>,
294
295 fulfilled_expectations: FxIndexSet<LintExpectationId>,
306
307 ice_file: Option<PathBuf>,
310
311 msrv: Option<RustcVersion>,
313}
314
315#[derive(#[automatically_derived]impl ::core::marker::Copy for StashKey { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for StashKey {
}
#[automatically_derived]impl ::core::clone::Clone for StashKey {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for StashKey
{
}
#[automatically_derived]impl ::core::cmp::PartialEq for StashKey {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for StashKey { }Eq, #[automatically_derived]impl ::core::hash::Hash for StashKey {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state)
}
}Hash, #[automatically_derived]impl ::core::fmt::Debug for StashKey {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_c_like_enum_write_str(f,
"ItemNoType EarlySyntaxWarning CallIntoMethod LifetimeIsChar MaybeFruTypo CallAssocMethod UndeterminedMacroResolution ExprInPat GenericInFieldExpr ReturnTypeNotation",
match self {
StashKey::ItemNoType => 0usize,
StashKey::EarlySyntaxWarning => 11usize,
StashKey::CallIntoMethod => 30usize,
StashKey::LifetimeIsChar => 45usize,
StashKey::MaybeFruTypo => 60usize,
StashKey::CallAssocMethod => 73usize,
StashKey::UndeterminedMacroResolution => 89usize,
StashKey::ExprInPat => 117usize,
StashKey::GenericInFieldExpr => 127usize,
StashKey::ReturnTypeNotation => 146usize,
})
}
}Debug)]
317pub enum StashKey {
318 ItemNoType,
319 EarlySyntaxWarning,
320 CallIntoMethod,
321 LifetimeIsChar,
324 MaybeFruTypo,
327 CallAssocMethod,
328 UndeterminedMacroResolution,
329 ExprInPat,
331 GenericInFieldExpr,
335 ReturnTypeNotation,
336}
337
338fn default_track_diagnostic<R>(diag: DiagInner, f: &mut dyn FnMut(DiagInner) -> R) -> R {
339 (*f)(diag)
340}
341
342pub static TRACK_DIAGNOSTIC: AtomicRef<
345 fn(DiagInner, &mut dyn FnMut(DiagInner) -> Option<ErrorGuaranteed>) -> Option<ErrorGuaranteed>,
346> = AtomicRef::new(&(default_track_diagnostic as _));
347
348#[derive(#[automatically_derived]impl ::core::marker::Copy for DiagCtxtFlags { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for DiagCtxtFlags {
}
#[automatically_derived]impl ::core::clone::Clone for DiagCtxtFlags {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<Option<NonZero<usize>>>;
*self
}
}Clone, #[automatically_derived]impl ::core::default::Default for DiagCtxtFlags {
#[inline]
fn default() -> Self {
DiagCtxtFlags {
can_emit_warnings: ::core::default::Default::default(),
treat_err_as_bug: ::core::default::Default::default(),
eagerly_emit_delayed_bugs: ::core::default::Default::default(),
macro_backtrace: ::core::default::Default::default(),
deduplicate_diagnostics: ::core::default::Default::default(),
track_diagnostics: ::core::default::Default::default(),
}
}
}Default)]
349pub struct DiagCtxtFlags {
350 pub can_emit_warnings: bool,
353 pub treat_err_as_bug: Option<NonZero<usize>>,
356 pub eagerly_emit_delayed_bugs: bool,
359 pub macro_backtrace: bool,
362 pub deduplicate_diagnostics: bool,
364 pub track_diagnostics: bool,
366}
367
368impl Drop for DiagCtxtInner {
369 fn drop(&mut self) {
370 self.emit_stashed_diagnostics();
378
379 self.flush_delayed();
383
384 if !self.has_printed && !self.suppressed_expected_diag && !std::thread::panicking() {
388 if let Some(backtrace) = &self.must_produce_diag {
389 let suggestion = match backtrace.status() {
390 BacktraceStatus::Disabled => String::from(
391 "Backtraces are currently disabled: set `RUST_BACKTRACE=1` and re-run \
392 to see where it happened.",
393 ),
394 BacktraceStatus::Captured => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("This happened in the following `must_produce_diag` call\'s backtrace:\n{0}",
backtrace))
})format!(
395 "This happened in the following `must_produce_diag` call's backtrace:\n\
396 {backtrace}",
397 ),
398 _ => String::from("(impossible to capture backtrace where this happened)"),
399 };
400 {
::core::panicking::panic_fmt(format_args!("`trimmed_def_paths` called, diagnostics were expected but none were emitted. Use `with_no_trimmed_paths` for debugging. {0}",
suggestion));
};panic!(
401 "`trimmed_def_paths` called, diagnostics were expected but none were emitted. \
402 Use `with_no_trimmed_paths` for debugging. {suggestion}"
403 );
404 }
405 }
406 }
407}
408
409impl DiagCtxt {
410 pub fn disable_warnings(mut self) -> Self {
411 self.inner.get_mut().flags.can_emit_warnings = false;
412 self
413 }
414
415 pub fn with_flags(mut self, flags: DiagCtxtFlags) -> Self {
416 self.inner.get_mut().flags = flags;
417 self
418 }
419
420 pub fn with_ice_file(mut self, ice_file: PathBuf) -> Self {
421 self.inner.get_mut().ice_file = Some(ice_file);
422 self
423 }
424
425 pub fn with_msrv(mut self, msrv: RustcVersion) -> Self {
426 self.inner.get_mut().msrv = Some(msrv);
427 self
428 }
429
430 pub fn new(emitter: Box<DynEmitter>) -> Self {
431 Self { inner: Lock::new(DiagCtxtInner::new(emitter)) }
432 }
433
434 pub fn handle<'a>(&'a self) -> DiagCtxtHandle<'a> {
435 DiagCtxtHandle { dcx: self, tainted_with_errors: None }
436 }
437}
438
439impl<'a> DiagCtxtHandle<'a> {
440 pub fn make_silent(&self) {
441 let mut inner = self.dcx.inner.borrow_mut();
442 inner.emitter = Box::new(emitter::SilentEmitter {});
443 }
444
445 pub fn set_emitter(&self, emitter: Box<dyn Emitter + DynSend>) {
446 self.dcx.inner.borrow_mut().emitter = emitter;
447 }
448
449 pub fn can_emit_warnings(&self) -> bool {
452 self.dcx.inner.borrow().flags.can_emit_warnings
453 }
454
455 pub fn reset_err_count(&self) {
461 let mut inner = self.dcx.inner.borrow_mut();
464 let DiagCtxtInner {
465 flags: _,
466 err_guars,
467 lint_err_guars,
468 delayed_bugs,
469 deduplicated_err_count,
470 deduplicated_warn_count,
471 emitter: _,
472 must_produce_diag,
473 has_printed,
474 suppressed_expected_diag,
475 taught_diagnostics,
476 emitted_diagnostic_codes,
477 emitted_diagnostics,
478 emitted_recursion_depth_exceeding_limit,
479 stashed_diagnostics,
480 future_breakage_diagnostics,
481 fulfilled_expectations,
482 ice_file: _,
483 msrv: _,
484 } = inner.deref_mut();
485
486 *err_guars = Default::default();
489 *lint_err_guars = Default::default();
490 *delayed_bugs = Default::default();
491 *deduplicated_err_count = 0;
492 *deduplicated_warn_count = 0;
493 *must_produce_diag = None;
494 *has_printed = false;
495 *suppressed_expected_diag = false;
496 *taught_diagnostics = Default::default();
497 *emitted_diagnostic_codes = Default::default();
498 *emitted_diagnostics = Default::default();
499 *emitted_recursion_depth_exceeding_limit = false;
500 *stashed_diagnostics = Default::default();
501 *future_breakage_diagnostics = Default::default();
502 *fulfilled_expectations = Default::default();
503 }
504
505 pub fn into_taintable(
509 self,
510 tainted_with_errors: &'a Cell<Option<ErrorGuaranteed>>,
511 ) -> DiagCtxtHandle<'a> {
512 DiagCtxtHandle { dcx: self.dcx, tainted_with_errors: Some(tainted_with_errors) }
513 }
514
515 pub fn stash_diagnostic(
537 &self,
538 span: Span,
539 key: StashKey,
540 diag: DiagInner,
541 ) -> Option<ErrorGuaranteed> {
542 let guar = match diag.level {
543 Bug | Fatal => {
544 self.span_bug(
545 span,
546 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid level in `stash_diagnostic`: {0:?}",
diag.level))
})format!("invalid level in `stash_diagnostic`: {:?}", diag.level),
547 );
548 }
549 Error => Some(self.span_delayed_bug(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("stashing {0:?}", key))
})format!("stashing {key:?}"))),
553 DelayedBug => {
554 return self.dcx.inner.borrow_mut().emit_diagnostic(diag, self.tainted_with_errors);
555 }
556 Warning(_) | Note | Help | FailureNote => None,
557 };
558
559 self.dcx
563 .inner
564 .borrow_mut()
565 .stashed_diagnostics
566 .entry(key)
567 .or_default()
568 .insert(span.with_parent(None), (diag, guar, std::thread::current().id()));
569
570 guar
571 }
572
573 pub fn steal_non_err(self, span: Span, key: StashKey) -> Option<Diag<'a>> {
577 let (diag, guar, _) =
579 self.dcx.inner.borrow_mut().stashed_diagnostics.get_mut(&key).and_then(
580 |stashed_diagnostics| stashed_diagnostics.swap_remove(&span.with_parent(None)),
581 )?;
582 if !!diag.is_error() {
::core::panicking::panic("assertion failed: !diag.is_error()")
};assert!(!diag.is_error());
583 if !guar.is_none() {
::core::panicking::panic("assertion failed: guar.is_none()")
};assert!(guar.is_none());
584 Some(Diag::new_diagnostic(self, diag))
585 }
586
587 pub fn try_steal_modify_and_emit_err<F>(
592 self,
593 span: Span,
594 key: StashKey,
595 mut modify_err: F,
596 ) -> Option<ErrorGuaranteed>
597 where
598 F: FnMut(&mut Diag<'_>),
599 {
600 let err = self.dcx.inner.borrow_mut().stashed_diagnostics.get_mut(&key).and_then(
602 |stashed_diagnostics| stashed_diagnostics.swap_remove(&span.with_parent(None)),
603 );
604 err.map(|(err, guar, _)| {
605 {
match (&err.level, &Error) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(err.level, Error);
606 if !guar.is_some() {
::core::panicking::panic("assertion failed: guar.is_some()")
};assert!(guar.is_some());
607 let mut err = Diag::new_diagnostic(self, err);
608 modify_err(&mut err);
609 {
match (&err.level, &Error) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(err.level, Error);
610 err.emit_err()
611 })
612 }
613
614 pub fn try_steal_replace_and_emit_err(
618 self,
619 span: Span,
620 key: StashKey,
621 new_err: Diag<'_>,
622 ) -> ErrorGuaranteed {
623 let old_err = self.dcx.inner.borrow_mut().stashed_diagnostics.get_mut(&key).and_then(
625 |stashed_diagnostics| stashed_diagnostics.swap_remove(&span.with_parent(None)),
626 );
627 match old_err {
628 Some((old_err, guar, _)) => {
629 {
match (&old_err.level, &Error) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(old_err.level, Error);
630 if !guar.is_some() {
::core::panicking::panic("assertion failed: guar.is_some()")
};assert!(guar.is_some());
631 Diag::new_diagnostic(self, old_err).cancel();
634 }
635 None => {}
636 };
637 new_err.emit_err()
638 }
639
640 pub fn has_stashed_diagnostic(&self, span: Span, key: StashKey) -> bool {
641 let inner = self.dcx.inner.borrow();
642 if let Some(stashed_diagnostics) = inner.stashed_diagnostics.get(&key)
643 && !stashed_diagnostics.is_empty()
644 {
645 stashed_diagnostics.contains_key(&span.with_parent(None))
646 } else {
647 false
648 }
649 }
650
651 pub fn emit_stashed_diagnostics(&self) -> Option<ErrorGuaranteed> {
653 self.dcx.inner.borrow_mut().emit_stashed_diagnostics()
654 }
655
656 #[inline]
658 pub fn err_count(&self) -> usize {
659 let inner = self.dcx.inner.borrow();
660 inner.err_guars.len()
661 + inner.lint_err_guars.len()
662 + inner
663 .stashed_diagnostics
664 .values()
665 .map(|a| a.values().filter(|(_, guar, _)| guar.is_some()).count())
666 .sum::<usize>()
667 }
668
669 pub fn err_count_on_current_thread(&self) -> usize {
674 let inner = self.dcx.inner.borrow();
675 let current = std::thread::current().id();
676 inner.err_guars.iter().filter(|(_, thread)| *thread == current).count()
677 + inner.lint_err_guars.iter().filter(|(_, thread)| *thread == current).count()
678 + inner
679 .stashed_diagnostics
680 .values()
681 .map(|a| {
682 a.values()
683 .filter(|(_, guar, thread)| guar.is_some() && *thread == current)
684 .count()
685 })
686 .sum::<usize>()
687 }
688
689 pub fn has_errors_excluding_lint_errors(&self) -> Option<ErrorGuaranteed> {
692 self.dcx.inner.borrow().has_errors_excluding_lint_errors()
693 }
694
695 pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
697 self.dcx.inner.borrow().has_errors()
698 }
699
700 pub fn has_errors_or_delayed_bugs(&self) -> Option<ErrorGuaranteed> {
703 self.dcx.inner.borrow().has_errors_or_delayed_bugs()
704 }
705
706 pub fn print_error_count(&self) {
707 let mut inner = self.dcx.inner.borrow_mut();
708
709 if !inner.stashed_diagnostics.is_empty() {
::core::panicking::panic("assertion failed: inner.stashed_diagnostics.is_empty()")
};assert!(inner.stashed_diagnostics.is_empty());
712
713 if inner.treat_err_as_bug() {
714 return;
715 }
716
717 let warnings = match inner.deduplicated_warn_count {
718 0 => Cow::from(""),
719 1 => Cow::from("1 warning emitted"),
720 count => Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} warnings emitted", count))
})format!("{count} warnings emitted")),
721 };
722 let errors = match inner.deduplicated_err_count {
723 0 => Cow::from(""),
724 1 => Cow::from("aborting due to 1 previous error"),
725 count => Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("aborting due to {0} previous errors",
count))
})format!("aborting due to {count} previous errors")),
726 };
727
728 match (errors.len(), warnings.len()) {
729 (0, 0) => return,
730 (0, _) => {
731 let diag = DiagInner::new(
733 Warning(Some(EmissionOverride::Forced { lint_id: None })),
734 DiagMessage::Str(warnings),
735 );
736 inner.emit_diagnostic(diag, None);
737 }
738 (_, 0) => {
739 inner.emit_diagnostic(DiagInner::new(Error, errors), self.tainted_with_errors);
740 }
741 (_, _) => {
742 inner.emit_diagnostic(
743 DiagInner::new(Error, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}; {1}", errors, warnings))
})format!("{errors}; {warnings}")),
744 self.tainted_with_errors,
745 );
746 }
747 }
748
749 let can_show_explain = inner.emitter.should_show_explain();
750 let are_there_diagnostics = !inner.emitted_diagnostic_codes.is_empty();
751 if can_show_explain && are_there_diagnostics {
752 let mut error_codes = inner
753 .emitted_diagnostic_codes
754 .iter()
755 .filter_map(|&code| {
756 if crate::codes::try_find_description(code).is_ok() {
757 Some(code.to_string())
758 } else {
759 None
760 }
761 })
762 .collect::<Vec<_>>();
763 if !error_codes.is_empty() {
764 error_codes.sort();
765 if error_codes.len() > 1 {
766 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
767 let msg1 = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Some errors have detailed explanations: {0}{1}",
error_codes[..limit].join(", "),
if error_codes.len() > 9 { "..." } else { "." }))
})format!(
768 "Some errors have detailed explanations: {}{}",
769 error_codes[..limit].join(", "),
770 if error_codes.len() > 9 { "..." } else { "." }
771 );
772 let msg2 = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("For more information about an error, try `rustc --explain {0}`.",
&error_codes[0]))
})format!(
773 "For more information about an error, try `rustc --explain {}`.",
774 &error_codes[0]
775 );
776 inner.emit_diagnostic(DiagInner::new(FailureNote, msg1), None);
777 inner.emit_diagnostic(DiagInner::new(FailureNote, msg2), None);
778 } else {
779 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("For more information about this error, try `rustc --explain {0}`.",
&error_codes[0]))
})format!(
780 "For more information about this error, try `rustc --explain {}`.",
781 &error_codes[0]
782 );
783 inner.emit_diagnostic(DiagInner::new(FailureNote, msg), None);
784 }
785 }
786 }
787 }
788
789 pub fn abort_if_errors(&self) {
794 if let Some(guar) = self.has_errors() {
795 guar.raise_fatal();
796 }
797 }
798
799 pub fn must_teach(&self, code: ErrCode) -> bool {
805 self.dcx.inner.borrow_mut().taught_diagnostics.insert(code)
806 }
807
808 pub fn emit_diagnostic(&self, diagnostic: DiagInner) -> Option<ErrorGuaranteed> {
809 self.dcx.inner.borrow_mut().emit_diagnostic(diagnostic, self.tainted_with_errors)
810 }
811
812 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
813 self.dcx.inner.borrow_mut().emitter.emit_artifact_notification(path, artifact_type);
814 }
815
816 pub fn emit_timing_section_start(&self, record: TimingRecord) {
817 self.dcx.inner.borrow_mut().emitter.emit_timing_section(record, TimingEvent::Start);
818 }
819
820 pub fn emit_timing_section_end(&self, record: TimingRecord) {
821 self.dcx.inner.borrow_mut().emitter.emit_timing_section(record, TimingEvent::End);
822 }
823
824 pub fn emit_future_breakage_report(&self) {
825 let inner = &mut *self.dcx.inner.borrow_mut();
826 let diags = mem::take(&mut inner.future_breakage_diagnostics);
827 if !diags.is_empty() {
828 inner.emitter.emit_future_breakage_report(diags);
829 }
830 }
831
832 pub fn emit_unused_externs(
833 &self,
834 lint_level: rustc_lint_defs::Level,
835 loud: bool,
836 unused_externs: &[&str],
837 ) {
838 let mut inner = self.dcx.inner.borrow_mut();
839
840 if loud && lint_level.is_error() {
851 #[allow(deprecated)]
854 let guar = ErrorGuaranteed::unchecked_error_guaranteed();
855 inner.lint_err_guars.push((guar, std::thread::current().id()));
856 inner.panic_if_treat_err_as_bug();
857 }
858
859 inner.emitter.emit_unused_externs(lint_level, unused_externs)
860 }
861
862 #[track_caller]
867 pub fn fulfill_expectation(self, expectation: impl Into<LintExpectationId>) {
868 let emission_override = Some(EmissionOverride::Expected { lint_id: expectation.into() });
869 let msg = "this is a dummy diagnostic, to submit and store an expectation";
870 Diag::new(self, Warning(emission_override), msg).emit()
871 }
872
873 #[must_use]
876 pub fn steal_fulfilled_expectation_ids(&self) -> FxIndexSet<LintExpectationId> {
877 mem::take(&mut self.dcx.inner.borrow_mut().fulfilled_expectations)
878 }
879
880 pub fn flush_delayed(&self) {
885 self.dcx.inner.borrow_mut().flush_delayed();
886 }
887
888 #[track_caller]
891 pub fn set_must_produce_diag(&self) {
892 if !self.dcx.inner.borrow().must_produce_diag.is_none() {
{
::core::panicking::panic_fmt(format_args!("should only need to collect a backtrace once"));
}
};assert!(
893 self.dcx.inner.borrow().must_produce_diag.is_none(),
894 "should only need to collect a backtrace once"
895 );
896 self.dcx.inner.borrow_mut().must_produce_diag = Some(Backtrace::capture());
897 }
898}
899
900impl<'a> DiagCtxtHandle<'a> {
905 #[track_caller]
906 pub fn struct_bug(self, msg: impl Into<Cow<'static, str>>) -> Diag<'a> {
907 Diag::new(self, Bug, msg.into())
908 }
909
910 #[track_caller]
911 pub fn bug(self, msg: impl Into<Cow<'static, str>>) -> ! {
912 self.struct_bug(msg).emit_bug()
913 }
914
915 #[track_caller]
916 pub fn struct_span_bug(
917 self,
918 span: impl Into<MultiSpan>,
919 msg: impl Into<Cow<'static, str>>,
920 ) -> Diag<'a> {
921 self.struct_bug(msg).with_span(span)
922 }
923
924 #[track_caller]
925 pub fn span_bug(self, span: impl Into<MultiSpan>, msg: impl Into<Cow<'static, str>>) -> ! {
926 self.struct_span_bug(span, msg.into()).emit_bug()
927 }
928
929 #[track_caller]
930 pub fn create_bug(self, bug: impl Diagnostic<'a>) -> Diag<'a> {
931 bug.into_diag(self, Bug)
932 }
933
934 #[track_caller]
935 pub fn emit_bug(self, bug: impl Diagnostic<'a>) -> ! {
936 self.create_bug(bug).emit_bug()
937 }
938
939 #[track_caller]
940 pub fn struct_fatal(self, msg: impl Into<DiagMessage>) -> Diag<'a> {
941 Diag::new(self, Fatal, msg)
942 }
943
944 #[track_caller]
945 pub fn fatal(self, msg: impl Into<DiagMessage>) -> ! {
946 self.struct_fatal(msg).emit_fatal()
947 }
948
949 #[track_caller]
950 pub fn struct_span_fatal(
951 self,
952 span: impl Into<MultiSpan>,
953 msg: impl Into<DiagMessage>,
954 ) -> Diag<'a> {
955 self.struct_fatal(msg).with_span(span)
956 }
957
958 #[track_caller]
959 pub fn span_fatal(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) -> ! {
960 self.struct_span_fatal(span, msg).emit_fatal()
961 }
962
963 #[track_caller]
964 pub fn create_fatal(self, fatal: impl Diagnostic<'a>) -> Diag<'a> {
965 fatal.into_diag(self, Fatal)
966 }
967
968 #[track_caller]
969 pub fn emit_fatal(self, fatal: impl Diagnostic<'a>) -> ! {
970 self.create_fatal(fatal).emit_fatal()
971 }
972
973 #[track_caller]
974 pub fn struct_err(self, msg: impl Into<DiagMessage>) -> Diag<'a> {
975 Diag::new(self, Error, msg)
976 }
977
978 #[track_caller]
979 pub fn err(self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
980 self.struct_err(msg).emit_err()
981 }
982
983 #[track_caller]
984 pub fn struct_span_err(
985 self,
986 span: impl Into<MultiSpan>,
987 msg: impl Into<DiagMessage>,
988 ) -> Diag<'a> {
989 self.struct_err(msg).with_span(span)
990 }
991
992 #[track_caller]
993 pub fn span_err(
994 self,
995 span: impl Into<MultiSpan>,
996 msg: impl Into<DiagMessage>,
997 ) -> ErrorGuaranteed {
998 self.struct_span_err(span, msg).emit_err()
999 }
1000
1001 #[track_caller]
1002 pub fn create_err(self, err: impl Diagnostic<'a>) -> Diag<'a> {
1003 err.into_diag(self, Error)
1004 }
1005
1006 #[track_caller]
1007 pub fn emit_err(self, err: impl Diagnostic<'a>) -> ErrorGuaranteed {
1008 self.create_err(err).emit_err()
1009 }
1010
1011 #[track_caller]
1013 pub fn delayed_bug(self, msg: impl Into<Cow<'static, str>>) -> ErrorGuaranteed {
1014 Diag::new(self, DelayedBug, msg.into()).emit_err()
1015 }
1016
1017 #[track_caller]
1022 pub fn span_delayed_bug(
1023 self,
1024 sp: impl Into<MultiSpan>,
1025 msg: impl Into<Cow<'static, str>>,
1026 ) -> ErrorGuaranteed {
1027 Diag::new(self, DelayedBug, msg.into()).with_span(sp).emit_err()
1028 }
1029
1030 #[track_caller]
1031 pub fn struct_warn(self, msg: impl Into<DiagMessage>) -> Diag<'a> {
1032 Diag::new(self, Warning(None), msg)
1033 }
1034
1035 #[track_caller]
1036 pub fn warn(self, msg: impl Into<DiagMessage>) {
1037 self.struct_warn(msg).emit()
1038 }
1039
1040 #[track_caller]
1041 pub fn struct_span_warn(
1042 self,
1043 span: impl Into<MultiSpan>,
1044 msg: impl Into<DiagMessage>,
1045 ) -> Diag<'a> {
1046 self.struct_warn(msg).with_span(span)
1047 }
1048
1049 #[track_caller]
1050 pub fn span_warn(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) {
1051 self.struct_span_warn(span, msg).emit()
1052 }
1053
1054 #[track_caller]
1055 pub fn create_warn(self, warning: impl Diagnostic<'a>) -> Diag<'a> {
1056 warning.into_diag(self, Warning(None))
1057 }
1058
1059 #[track_caller]
1060 pub fn emit_warn(self, warning: impl Diagnostic<'a>) {
1061 self.create_warn(warning).emit()
1062 }
1063
1064 #[track_caller]
1065 pub fn struct_note(self, msg: impl Into<DiagMessage>) -> Diag<'a> {
1066 Diag::new(self, Note, msg)
1067 }
1068
1069 #[track_caller]
1070 pub fn note(&self, msg: impl Into<DiagMessage>) {
1071 self.struct_note(msg).emit()
1072 }
1073
1074 #[track_caller]
1075 pub fn struct_span_note(
1076 self,
1077 span: impl Into<MultiSpan>,
1078 msg: impl Into<DiagMessage>,
1079 ) -> Diag<'a> {
1080 self.struct_note(msg).with_span(span)
1081 }
1082
1083 #[track_caller]
1084 pub fn span_note(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) {
1085 self.struct_span_note(span, msg).emit()
1086 }
1087
1088 #[track_caller]
1089 pub fn create_note(self, note: impl Diagnostic<'a>) -> Diag<'a> {
1090 note.into_diag(self, Note)
1091 }
1092
1093 #[track_caller]
1094 pub fn emit_note(self, note: impl Diagnostic<'a>) {
1095 self.create_note(note).emit()
1096 }
1097}
1098
1099impl DiagCtxtInner {
1100 fn new(emitter: Box<DynEmitter>) -> Self {
1101 Self {
1102 flags: DiagCtxtFlags { can_emit_warnings: true, ..Default::default() },
1103 err_guars: Vec::new(),
1104 lint_err_guars: Vec::new(),
1105 delayed_bugs: Vec::new(),
1106 deduplicated_err_count: 0,
1107 deduplicated_warn_count: 0,
1108 emitter,
1109 must_produce_diag: None,
1110 has_printed: false,
1111 suppressed_expected_diag: false,
1112 taught_diagnostics: Default::default(),
1113 emitted_diagnostic_codes: Default::default(),
1114 emitted_diagnostics: Default::default(),
1115 emitted_recursion_depth_exceeding_limit: false,
1116 stashed_diagnostics: Default::default(),
1117 future_breakage_diagnostics: Vec::new(),
1118 fulfilled_expectations: Default::default(),
1119 ice_file: None,
1120 msrv: None,
1121 }
1122 }
1123
1124 fn emit_stashed_diagnostics(&mut self) -> Option<ErrorGuaranteed> {
1126 let mut guar = None;
1127 let has_errors = !self.err_guars.is_empty();
1128 for (_, stashed_diagnostics) in mem::take(&mut self.stashed_diagnostics).into_iter() {
1129 for (_, (diag, _guar, _thread)) in stashed_diagnostics {
1130 if has_errors
1133 && let Warning(emission_override) = diag.level
1134 && !#[allow(non_exhaustive_omitted_patterns)] match emission_override {
Some(EmissionOverride::Forced { .. }) => true,
_ => false,
}matches!(emission_override, Some(EmissionOverride::Forced { .. }))
1135 {
1136 continue;
1137 }
1138 guar = guar.or(self.emit_diagnostic(diag, None));
1139 }
1140 }
1141 guar
1142 }
1143
1144 fn emit_diagnostic(
1146 &mut self,
1147 mut diagnostic: DiagInner,
1148 taint: Option<&Cell<Option<ErrorGuaranteed>>>,
1149 ) -> Option<ErrorGuaranteed> {
1150 if diagnostic.has_future_breakage() {
1151 {
match diagnostic.level {
Error | Warning(_) => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"Error | Warning(_)", ::core::option::Option::None);
}
}
};assert_matches!(diagnostic.level, Error | Warning(_));
1155 self.future_breakage_diagnostics.push(diagnostic.clone());
1156 }
1157
1158 match diagnostic.level {
1162 Bug => {}
1163 Fatal | Error => {
1164 if self.treat_next_err_as_bug() {
1165 diagnostic.level = Bug;
1167 }
1168 }
1169 DelayedBug => {
1170 if self.flags.eagerly_emit_delayed_bugs {
1175 if self.treat_next_err_as_bug() {
1177 diagnostic.level = Bug;
1178 } else {
1179 diagnostic.level = Error;
1180 }
1181 } else {
1182 return if let Some(guar) = self.has_errors() {
1185 Some(guar)
1186 } else {
1187 let backtrace = std::backtrace::Backtrace::capture();
1191 #[allow(deprecated)]
1195 let guar = ErrorGuaranteed::unchecked_error_guaranteed();
1196 self.delayed_bugs
1197 .push((DelayedDiagInner::with_backtrace(diagnostic, backtrace), guar));
1198 Some(guar)
1199 };
1200 }
1201 }
1202 Warning(emission_override) => {
1203 match emission_override {
1204 None => {
1205 if !self.flags.can_emit_warnings {
1206 if diagnostic.has_future_breakage() {
1208 TRACK_DIAGNOSTIC(diagnostic, &mut |_| None);
1210 }
1211 return None;
1212 }
1213 }
1214 Some(EmissionOverride::Forced { lint_id: None }) => {}
1215 Some(EmissionOverride::Forced { lint_id: Some(lint_id) }) => {
1216 self.fulfilled_expectations.insert(lint_id);
1217 }
1218 Some(EmissionOverride::Allowed) => {
1219 if !diagnostic.has_future_breakage() {
::core::panicking::panic("assertion failed: diagnostic.has_future_breakage()")
};assert!(diagnostic.has_future_breakage());
1220 TRACK_DIAGNOSTIC(diagnostic, &mut |_| None);
1221 self.suppressed_expected_diag = true;
1222 return None;
1223 }
1224 Some(EmissionOverride::Expected { lint_id }) => {
1225 self.fulfilled_expectations.insert(lint_id);
1226 TRACK_DIAGNOSTIC(diagnostic, &mut |_| None);
1227 self.suppressed_expected_diag = true;
1228 return None;
1229 }
1230 }
1231 }
1232 Note | Help | FailureNote => {}
1233 }
1234
1235 if let (Some(msrv), Some(diag_msrv)) = (self.msrv, diagnostic.rust_version())
1236 && diag_msrv > msrv
1237 {
1238 return None;
1239 }
1240
1241 TRACK_DIAGNOSTIC(diagnostic, &mut |mut diagnostic| {
1242 if let Some(code) = diagnostic.code {
1243 self.emitted_diagnostic_codes.insert(code);
1244 }
1245
1246 let already_emitted = !self.emitted_diagnostics.insert(diagnostic.dedup_hash());
1247
1248 let is_error = diagnostic.is_error();
1249 let is_lint = diagnostic.is_lint.is_some();
1250 let silence_recursion_depth_exceeded_limit =
1252 diagnostic.is_lint.as_ref().is_some_and(|lint| {
1253 lint.name.eq_ignore_ascii_case(
1254 rustc_lint_defs::builtin::RECURSION_DEPTH_EXCEEDING_LIMIT.name,
1255 ) && mem::replace(&mut self.emitted_recursion_depth_exceeding_limit, true)
1256 });
1257
1258 if !silence_recursion_depth_exceeded_limit
1261 && !(self.flags.deduplicate_diagnostics && already_emitted)
1262 {
1263 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_errors/src/lib.rs:1263",
"rustc_errors", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_errors/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1263u32),
::tracing_core::__macro_support::Option::Some("rustc_errors"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("diagnostic")
}> =
::tracing::__macro_support::FieldName::new("diagnostic");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diagnostic)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?diagnostic);
1264 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_errors/src/lib.rs:1264",
"rustc_errors", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_errors/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1264u32),
::tracing_core::__macro_support::Option::Some("rustc_errors"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self.emitted_diagnostics")
}> =
::tracing::__macro_support::FieldName::new("self.emitted_diagnostics");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.emitted_diagnostics)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?self.emitted_diagnostics);
1265
1266 let show_sub = |sub: &Subdiag| {
1267 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_errors/src/lib.rs:1267",
"rustc_errors", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_errors/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1267u32),
::tracing_core::__macro_support::Option::Some("rustc_errors"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("sub")
}> =
::tracing::__macro_support::FieldName::new("sub");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sub)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?sub);
1268 match sub.level {
1269 Sublevel::Error | Sublevel::Warning | Sublevel::Note | Sublevel::Help => {
1270 true
1271 }
1272 Sublevel::OnceNote | Sublevel::OnceHelp => {
1273 self.emitted_diagnostics.insert(sub.dedup_hash())
1274 }
1275 }
1276 };
1277 diagnostic.children.retain(show_sub);
1278 if already_emitted {
1279 let msg = "duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`";
1280 diagnostic.sub(Sublevel::Note, msg, MultiSpan::new());
1281 }
1282
1283 if is_error {
1284 self.deduplicated_err_count += 1;
1285 } else if #[allow(non_exhaustive_omitted_patterns)] match diagnostic.level {
Warning(_) => true,
_ => false,
}matches!(diagnostic.level, Warning(_)) {
1286 self.deduplicated_warn_count += 1;
1287 }
1288 self.has_printed = true;
1289
1290 self.emitter.emit_diagnostic(diagnostic);
1291 }
1292
1293 if is_error {
1294 if !self.delayed_bugs.is_empty() {
1299 {
match (&(self.lint_err_guars.len() + self.err_guars.len()), &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.lint_err_guars.len() + self.err_guars.len(), 0);
1300 self.delayed_bugs.clear();
1301 self.delayed_bugs.shrink_to_fit();
1302 }
1303
1304 #[allow(deprecated)]
1307 let guar = ErrorGuaranteed::unchecked_error_guaranteed();
1308 let thread = std::thread::current().id();
1309 if is_lint {
1310 self.lint_err_guars.push((guar, thread));
1311 } else {
1312 if let Some(taint) = taint {
1313 taint.set(Some(guar));
1314 }
1315 self.err_guars.push((guar, thread));
1316 }
1317 self.panic_if_treat_err_as_bug();
1318 Some(guar)
1319 } else {
1320 None
1321 }
1322 })
1323 }
1324
1325 fn treat_err_as_bug(&self) -> bool {
1326 self.flags
1327 .treat_err_as_bug
1328 .is_some_and(|c| self.err_guars.len() + self.lint_err_guars.len() >= c.get())
1329 }
1330
1331 fn treat_next_err_as_bug(&self) -> bool {
1333 self.flags
1334 .treat_err_as_bug
1335 .is_some_and(|c| self.err_guars.len() + self.lint_err_guars.len() + 1 >= c.get())
1336 }
1337
1338 fn has_errors_excluding_lint_errors(&self) -> Option<ErrorGuaranteed> {
1339 self.err_guars.get(0).map(|(guar, _)| *guar).or_else(|| {
1340 if let Some((_diag, guar, _)) = self
1341 .stashed_diagnostics
1342 .values()
1343 .flat_map(|stashed_diagnostics| stashed_diagnostics.values())
1344 .find(|(diag, guar, _)| guar.is_some() && diag.is_lint.is_none())
1345 {
1346 *guar
1347 } else {
1348 None
1349 }
1350 })
1351 }
1352
1353 fn has_errors(&self) -> Option<ErrorGuaranteed> {
1354 self.err_guars
1355 .get(0)
1356 .map(|(guar, _)| *guar)
1357 .or_else(|| self.lint_err_guars.get(0).map(|(guar, _)| *guar))
1358 .or_else(|| {
1359 self.stashed_diagnostics.values().find_map(|stashed_diagnostics| {
1360 stashed_diagnostics.values().find_map(|(_, guar, _)| *guar)
1361 })
1362 })
1363 }
1364
1365 fn has_errors_or_delayed_bugs(&self) -> Option<ErrorGuaranteed> {
1366 self.has_errors().or_else(|| self.delayed_bugs.get(0).map(|(_, guar)| guar).copied())
1367 }
1368
1369 fn flush_delayed(&mut self) {
1370 if !self.stashed_diagnostics.is_empty() {
::core::panicking::panic("assertion failed: self.stashed_diagnostics.is_empty()")
};assert!(self.stashed_diagnostics.is_empty());
1374
1375 if !self.err_guars.is_empty() {
1376 return;
1378 }
1379
1380 if self.delayed_bugs.is_empty() {
1381 return;
1383 }
1384
1385 let bugs: Vec<_> = mem::take(&mut self.delayed_bugs).into_iter().map(|(b, _)| b).collect();
1386
1387 let backtrace = std::env::var_os("RUST_BACKTRACE").as_deref() != Some(OsStr::new("0"));
1388 let decorate = backtrace || self.ice_file.is_none();
1389 let mut out = self
1390 .ice_file
1391 .as_ref()
1392 .and_then(|file| std::fs::File::options().create(true).append(true).open(file).ok());
1393
1394 let note1 = "no errors encountered even though delayed bugs were created";
1399 let note2 = "those delayed bugs will now be shown as internal compiler errors";
1400 self.emit_diagnostic(DiagInner::new(Note, note1), None);
1401 self.emit_diagnostic(DiagInner::new(Note, note2), None);
1402
1403 for bug in bugs {
1404 if let Some(out) = &mut out {
1405 _ = out.write_fmt(format_args!("delayed bug: {0}\n{1}\n",
bug.inner.messages.iter().filter_map(|(msg, _)|
msg.as_str()).collect::<String>(), &bug.note))write!(
1406 out,
1407 "delayed bug: {}\n{}\n",
1408 bug.inner
1409 .messages
1410 .iter()
1411 .filter_map(|(msg, _)| msg.as_str())
1412 .collect::<String>(),
1413 &bug.note
1414 );
1415 }
1416
1417 let mut bug = if decorate { bug.decorate() } else { bug.inner };
1418
1419 if bug.level != DelayedBug {
1421 let msg = rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`flushed_delayed` got diagnostic with level {$level}, instead of the expected `DelayedBug`"))msg!(
1428 "`flushed_delayed` got diagnostic with level {$level}, instead of the expected `DelayedBug`"
1429 ).arg("level", bug.level).format();
1430 bug.sub(Sublevel::Note, msg, bug.span.primary_span().unwrap().into());
1431 }
1432 bug.level = Bug;
1433
1434 self.emit_diagnostic(bug, None);
1435 }
1436
1437 panic::panic_any(DelayedBugPanic);
1439 }
1440
1441 fn panic_if_treat_err_as_bug(&self) {
1442 if self.treat_err_as_bug() {
1443 let n = self.flags.treat_err_as_bug.map(|c| c.get()).unwrap();
1444 {
match (&n, &(self.err_guars.len() + self.lint_err_guars.len())) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(n, self.err_guars.len() + self.lint_err_guars.len());
1445 if n == 1 {
1446 {
::core::panicking::panic_fmt(format_args!("aborting due to `-Z treat-err-as-bug=1`"));
};panic!("aborting due to `-Z treat-err-as-bug=1`");
1447 } else {
1448 {
::core::panicking::panic_fmt(format_args!("aborting after {0} errors due to `-Z treat-err-as-bug={0}`",
n));
};panic!("aborting after {n} errors due to `-Z treat-err-as-bug={n}`");
1449 }
1450 }
1451 }
1452}
1453
1454struct DelayedDiagInner {
1455 inner: DiagInner,
1456 note: Backtrace,
1457}
1458
1459impl DelayedDiagInner {
1460 fn with_backtrace(diagnostic: DiagInner, backtrace: Backtrace) -> Self {
1461 DelayedDiagInner { inner: diagnostic, note: backtrace }
1462 }
1463
1464 fn decorate(self) -> DiagInner {
1465 let mut diag = self.inner;
1469 let msg = match self.note.status() {
1470 BacktraceStatus::Captured => rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("delayed at {$emitted_at}\n {$note}"))msg!(
1471 "delayed at {$emitted_at}
1472 {$note}"
1473 ),
1474 _ => rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("delayed at {$emitted_at} - {$note}"))msg!("delayed at {$emitted_at} - {$note}"),
1477 }
1478 .arg("emitted_at", diag.emitted_at.clone())
1479 .arg("note", self.note)
1480 .format();
1481 diag.sub(Sublevel::Note, msg, diag.span.primary_span().unwrap_or(DUMMY_SP).into());
1482 diag
1483 }
1484}
1485
1486#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for EmissionOverride {
}
#[automatically_derived]impl ::core::clone::Clone for EmissionOverride {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Option<LintExpectationId>>;
let _: ::core::clone::AssertParamIsClone<LintExpectationId>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for EmissionOverride { }Copy, #[automatically_derived]impl ::core::fmt::Debug for EmissionOverride {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Forced { lint_id: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Forced lint_id", &__self_0),
Self::Allowed => ::core::fmt::Formatter::write_str(f, "Allowed"),
Self::Expected { lint_id: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Expected lint_id", &__self_0),
}
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
EmissionOverride {
}
#[automatically_derived]impl ::core::cmp::PartialEq for EmissionOverride {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Forced { lint_id: __self_0 }, Self::Forced {
lint_id: __arg1_0 }) => __self_0 == __arg1_0,
(Self::Expected { lint_id: __self_0 }, Self::Expected {
lint_id: __arg1_0 }) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for EmissionOverride {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Option<LintExpectationId>>;
let _: ::core::cmp::AssertParamIsEq<LintExpectationId>;
}
}Eq, #[automatically_derived]impl ::core::hash::Hash for EmissionOverride {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state);
match self {
Self::Forced { lint_id: __self_0 } =>
::core::hash::Hash::hash(__self_0, state),
Self::Expected { lint_id: __self_0 } =>
::core::hash::Hash::hash(__self_0, state),
_ => {}
}
}
}Hash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for EmissionOverride {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
EmissionOverride::Forced { lint_id: ref __binding_0 } => {
0usize
}
EmissionOverride::Allowed => { 1usize }
EmissionOverride::Expected { lint_id: ref __binding_0 } => {
2usize
}
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
EmissionOverride::Forced { lint_id: ref __binding_0 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
EmissionOverride::Allowed => {}
EmissionOverride::Expected { lint_id: ref __binding_0 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for EmissionOverride {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => {
EmissionOverride::Forced {
lint_id: ::rustc_serialize::Decodable::decode(__decoder),
}
}
1usize => { EmissionOverride::Allowed }
2usize => {
EmissionOverride::Expected {
lint_id: ::rustc_serialize::Decodable::decode(__decoder),
}
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `EmissionOverride`, expected 0..3, actual {0}",
n));
}
}
}
}
};Decodable)]
1503pub enum EmissionOverride {
1504 Forced { lint_id: Option<LintExpectationId> },
1506
1507 Allowed,
1510
1511 Expected { lint_id: LintExpectationId },
1513}
1514
1515#[derive(#[automatically_derived]impl ::core::marker::Copy for Level { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Level { }
#[automatically_derived]impl ::core::cmp::PartialEq for Level {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Warning(__self_0), Self::Warning(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Level {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Option<EmissionOverride>>;
}
}Eq, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Level {
}
#[automatically_derived]impl ::core::clone::Clone for Level {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Option<EmissionOverride>>;
*self
}
}Clone, #[automatically_derived]impl ::core::hash::Hash for Level {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state);
match self {
Self::Warning(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
_ => {}
}
}
}Hash, #[automatically_derived]impl ::core::fmt::Debug for Level {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Bug => ::core::fmt::Formatter::write_str(f, "Bug"),
Self::Fatal => ::core::fmt::Formatter::write_str(f, "Fatal"),
Self::Error => ::core::fmt::Formatter::write_str(f, "Error"),
Self::DelayedBug =>
::core::fmt::Formatter::write_str(f, "DelayedBug"),
Self::Warning(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Warning", &__self_0),
Self::Note => ::core::fmt::Formatter::write_str(f, "Note"),
Self::Help => ::core::fmt::Formatter::write_str(f, "Help"),
Self::FailureNote =>
::core::fmt::Formatter::write_str(f, "FailureNote"),
}
}
}Debug, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for Level {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
Level::Bug => { 0usize }
Level::Fatal => { 1usize }
Level::Error => { 2usize }
Level::DelayedBug => { 3usize }
Level::Warning(ref __binding_0) => { 4usize }
Level::Note => { 5usize }
Level::Help => { 6usize }
Level::FailureNote => { 7usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
Level::Bug => {}
Level::Fatal => {}
Level::Error => {}
Level::DelayedBug => {}
Level::Warning(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
Level::Note => {}
Level::Help => {}
Level::FailureNote => {}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for Level {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { Level::Bug }
1usize => { Level::Fatal }
2usize => { Level::Error }
3usize => { Level::DelayedBug }
4usize => {
Level::Warning(::rustc_serialize::Decodable::decode(__decoder))
}
5usize => { Level::Note }
6usize => { Level::Help }
7usize => { Level::FailureNote }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Level`, expected 0..8, actual {0}",
n));
}
}
}
}
};Decodable)]
1527pub enum Level {
1528 Bug,
1530
1531 Fatal,
1534
1535 Error,
1538
1539 DelayedBug,
1544
1545 Warning(Option<EmissionOverride>),
1548
1549 Note,
1551
1552 Help,
1558
1559 FailureNote,
1562}
1563
1564impl fmt::Display for Level {
1565 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1566 self.to_str().fmt(f)
1567 }
1568}
1569
1570impl Level {
1571 pub fn to_str(self) -> &'static str {
1572 match self {
1573 Bug | DelayedBug => "error: internal compiler error",
1574 Fatal | Error => "error",
1575 Warning(_) => "warning",
1576 Note => "note",
1577 Help => "help",
1578 FailureNote => "failure-note",
1579 }
1580 }
1581
1582 pub fn is_failure_note(self) -> bool {
1583 #[allow(non_exhaustive_omitted_patterns)] match self {
FailureNote => true,
_ => false,
}matches!(self, FailureNote)
1584 }
1585}
1586
1587impl IntoDiagArg for Level {
1588 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
1589 DiagArgValue::Str(Cow::from(self.to_string()))
1590 }
1591}
1592
1593#[derive(#[automatically_derived]impl ::core::marker::Copy for Sublevel { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Sublevel
{
}
#[automatically_derived]impl ::core::cmp::PartialEq for Sublevel {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Sublevel { }Eq, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Sublevel {
}
#[automatically_derived]impl ::core::clone::Clone for Sublevel {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::hash::Hash for Sublevel {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state)
}
}Hash, #[automatically_derived]impl ::core::fmt::Debug for Sublevel {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_c_like_enum_write_str(f,
"Error Warning Note OnceNote Help OnceHelp",
match self {
Sublevel::Error => 0usize,
Sublevel::Warning => 6usize,
Sublevel::Note => 14usize,
Sublevel::OnceNote => 19usize,
Sublevel::Help => 28usize,
Sublevel::OnceHelp => 33usize,
})
}
}Debug, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for Sublevel {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
Sublevel::Error => { 0usize }
Sublevel::Warning => { 1usize }
Sublevel::Note => { 2usize }
Sublevel::OnceNote => { 3usize }
Sublevel::Help => { 4usize }
Sublevel::OnceHelp => { 5usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for Sublevel {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { Sublevel::Error }
1usize => { Sublevel::Warning }
2usize => { Sublevel::Note }
3usize => { Sublevel::OnceNote }
4usize => { Sublevel::Help }
5usize => { Sublevel::OnceHelp }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Sublevel`, expected 0..6, actual {0}",
n));
}
}
}
}
};Decodable)]
1595pub enum Sublevel {
1596 Error,
1601
1602 Warning,
1604
1605 Note,
1607
1608 OnceNote,
1610
1611 Help,
1613
1614 OnceHelp,
1616}
1617
1618impl Sublevel {
1619 pub fn to_str(self) -> &'static str {
1620 match self {
1621 Sublevel::Error => "error",
1622 Sublevel::Warning => "warning",
1623 Sublevel::Note | Sublevel::OnceNote => "note",
1624 Sublevel::Help | Sublevel::OnceHelp => "help",
1625 }
1626 }
1627}
1628
1629#[derive(#[automatically_derived]impl ::core::marker::Copy for Style { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Style {
}
#[automatically_derived]impl ::core::clone::Clone for Style {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Style {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Style::NoStyle => "NoStyle",
Style::Highlight => "Highlight",
})
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Style { }
#[automatically_derived]impl ::core::cmp::PartialEq for Style {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Style { }Eq, #[automatically_derived]impl ::core::hash::Hash for Style {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state)
}
}Hash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for Style {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
Style::NoStyle => { 0usize }
Style::Highlight => { 1usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for Style {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { Style::NoStyle }
1usize => { Style::Highlight }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Style`, expected 0..2, actual {0}",
n));
}
}
}
}
};Decodable)]
1630pub enum Style {
1631 NoStyle,
1632 Highlight,
1633}
1634
1635pub fn elided_lifetime_in_path_suggestion(
1637 source_map: &SourceMap,
1638 n: usize,
1639 path_span: Span,
1640 incl_angl_brckt: bool,
1641 insertion_span: Span,
1642) -> ElidedLifetimeInPathSubdiag {
1643 let expected = ExpectedLifetimeParameter { span: path_span, count: n };
1644 let indicate = source_map.is_span_accessible(insertion_span).then(|| {
1646 let anon_lts = ::alloc::vec::from_elem_global("'_", n)vec!["'_"; n].join(", ");
1647 let suggestion =
1648 if incl_angl_brckt { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", anon_lts))
})format!("<{anon_lts}>") } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ", anon_lts))
})format!("{anon_lts}, ") };
1649
1650 IndicateAnonymousLifetime { span: insertion_span.shrink_to_hi(), count: n, suggestion }
1651 });
1652
1653 ElidedLifetimeInPathSubdiag { expected, indicate }
1654}
1655
1656pub fn a_or_an(s: &str) -> &'static str {
1660 let mut chars = s.chars();
1661 let Some(mut first_alpha_char) = chars.next() else {
1662 return "a";
1663 };
1664 if first_alpha_char == '`' {
1665 let Some(next) = chars.next() else {
1666 return "a";
1667 };
1668 first_alpha_char = next;
1669 }
1670 if ["a", "e", "i", "o", "u", "&"].contains(&&first_alpha_char.to_lowercase().to_string()[..]) {
1671 "an"
1672 } else {
1673 "a"
1674 }
1675}
1676
1677#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for TerminalUrl {
}
#[automatically_derived]impl ::core::clone::Clone for TerminalUrl {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for TerminalUrl { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
TerminalUrl {
}
#[automatically_derived]impl ::core::cmp::PartialEq for TerminalUrl {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::hash::Hash for TerminalUrl {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state)
}
}Hash, #[automatically_derived]impl ::core::fmt::Debug for TerminalUrl {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
TerminalUrl::No => "No",
TerminalUrl::Yes => "Yes",
TerminalUrl::Auto => "Auto",
})
}
}Debug)]
1678pub enum TerminalUrl {
1679 No,
1680 Yes,
1681 Auto,
1682}