1#![feature(default_field_values)]
7#![feature(macro_metavar_expr_concat)]
8#![feature(negative_impls)]
9#![feature(register_tool)]
10#![register_tool(lint)]
11extern crate self as rustc_errors;
14
15use std::backtrace::{Backtrace, BacktraceStatus};
16use std::borrow::Cow;
17use std::cell::Cell;
18use std::ffi::OsStr;
19use std::hash::Hash;
20use std::io::Write;
21use std::num::NonZero;
22use std::ops::DerefMut;
23use std::path::{Path, PathBuf};
24use std::thread::ThreadId;
25use std::{assert_matches, fmt, mem, panic};
26
27use Level::*;
28pub use anstream::{AutoStream, ColorChoice};
31pub use anstyle::{
32 Ansi256Color, AnsiColor, Color, EffectIter, Effects, Reset, RgbColor, Style as Anstyle,
33};
34pub use codes::*;
35pub use decorate_diag::{BufferedEarlyLint, DecorateDiagCompat, LintBuffer};
36pub use diagnostic::{
37 Diag, DiagDecorator, DiagInner, DiagLocation, DiagStyledString, Diagnostic, StringPart,
38 Subdiag, Subdiagnostic,
39};
40pub use diagnostic_impls::{
41 DiagSymbolList, ElidedLifetimeInPathSubdiag, ExpectedLifetimeParameter,
42 IndicateAnonymousLifetime, SingleLabelManySpans,
43};
44pub use emitter::ColorConfig;
45use emitter::{DynEmitter, Emitter};
46use rustc_ast::attr::version::RustcVersion;
47use rustc_data_structures::AtomicRef;
48use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
49use rustc_data_structures::sync::{DynSend, Lock};
50pub use rustc_error_messages::{
51 DiagArg, DiagArgFromDisplay, DiagArgMap, DiagArgName, DiagArgValue, DiagMessage, IntoDiagArg,
52 LanguageIdentifier, MultiSpan, SpanLabel, fluent_bundle, into_diag_arg_using_display,
53};
54use rustc_hashes::Hash128;
55use rustc_lint_defs::LintExpectationId;
56pub use rustc_lint_defs::{Applicability, listify, pluralize};
57pub use rustc_macros::msg;
58use rustc_macros::{Decodable, Encodable};
59pub use rustc_span::ErrorGuaranteed;
60pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker, catch_fatal_errors};
61pub use rustc_span::macros::ExplicitBug;
62use rustc_span::source_map::SourceMap;
63use rustc_span::{DUMMY_SP, Span};
64use tracing::debug;
65
66use crate::emitter::TimingEvent;
67use crate::formatting::DiagMessageAddArg;
68pub use crate::formatting::format_diag_message;
69use crate::timings::TimingRecord;
70
71pub mod annotate_snippet_emitter_writer;
72pub mod codes;
73mod decorate_diag;
74mod dedup_hash;
75mod diagnostic;
76mod diagnostic_impls;
77pub mod emitter;
78pub mod formatting;
79pub mod json;
80mod lock;
81pub mod markdown;
82pub mod timings;
83
84pub type PResult<'a, T> = Result<T, Diag<'a>>;
85
86#[cfg(target_pointer_width = "64")]
88const _: [(); 24] = [(); ::std::mem::size_of::<PResult<'_, ()>>()];rustc_data_structures::static_assert_size!(PResult<'_, ()>, 24);
89#[cfg(target_pointer_width = "64")]
90const _: [(); 24] = [(); ::std::mem::size_of::<PResult<'_, bool>>()];rustc_data_structures::static_assert_size!(PResult<'_, bool>, 24);
91
92#[derive(#[automatically_derived]impl ::core::fmt::Debug for SuggestionStyle {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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)]
93pub enum SuggestionStyle {
94 HideCodeInline,
96 HideCodeAlways,
98 CompletelyHidden,
100 ShowCode,
104 ShowAlways,
106}
107
108impl SuggestionStyle {
109 fn hide_inline(&self) -> bool {
110 !#[allow(non_exhaustive_omitted_patterns)] match *self {
SuggestionStyle::ShowCode => true,
_ => false,
}matches!(*self, SuggestionStyle::ShowCode)
111 }
112}
113
114#[derive(#[automatically_derived]impl ::core::clone::Clone for Suggestions {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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)]
116pub enum Suggestions {
117 Enabled(Vec<CodeSuggestion>),
122 Sealed(Box<[CodeSuggestion]>),
126 Disabled,
130}
131
132impl Suggestions {
133 pub fn unwrap_tag(self) -> Vec<CodeSuggestion> {
135 match self {
136 Suggestions::Enabled(suggestions) => suggestions,
137 Suggestions::Sealed(suggestions) => suggestions.into_vec(),
138 Suggestions::Disabled => Vec::new(),
139 }
140 }
141
142 pub fn len(&self) -> usize {
143 match self {
144 Suggestions::Enabled(suggestions) => suggestions.len(),
145 Suggestions::Sealed(suggestions) => suggestions.len(),
146 Suggestions::Disabled => 0,
147 }
148 }
149}
150
151impl Default for Suggestions {
152 fn default() -> Self {
153 Self::Enabled(::alloc::vec::Vec::new()vec![])
154 }
155}
156
157#[derive(#[automatically_derived]impl ::core::clone::Clone for CodeSuggestion {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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)]
158pub struct CodeSuggestion {
159 pub substitutions: Vec<Substitution>,
181 pub msg: DiagMessage,
182 pub style: SuggestionStyle,
184 pub applicability: Applicability,
190}
191
192#[derive(#[automatically_derived]impl ::core::clone::Clone for Substitution {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
Substitution { parts: ::core::clone::Clone::clone(&self.parts) }
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Substitution {
#[inline]
#[rustc_trivial_field_reads]
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)]
193pub struct Substitution {
195 pub parts: Vec<SubstitutionPart>,
196}
197
198#[derive(#[automatically_derived]impl ::core::clone::Clone for SubstitutionPart {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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)]
199pub struct SubstitutionPart {
200 pub span: Span,
201 pub snippet: String,
202}
203
204pub struct DelayedBugPanic;
207
208pub struct DiagCtxt {
215 inner: Lock<DiagCtxtInner>,
216}
217
218#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<&'a DiagCtxt>;
let _:
::core::clone::AssertParamIsClone<Option<&'a Cell<Option<ErrorGuaranteed>>>>;
*self
}
}Clone)]
219pub struct DiagCtxtHandle<'a> {
220 dcx: &'a DiagCtxt,
221 tainted_with_errors: Option<&'a Cell<Option<ErrorGuaranteed>>>,
224}
225
226struct DiagCtxtInner {
233 flags: DiagCtxtFlags,
234
235 err_guars: Vec<(ErrorGuaranteed, ThreadId)>,
238 lint_err_guars: Vec<(ErrorGuaranteed, ThreadId)>,
241 delayed_bugs: Vec<(DelayedDiagInner, ErrorGuaranteed)>,
243
244 deduplicated_err_count: usize,
246 deduplicated_warn_count: usize,
248
249 emitter: Box<DynEmitter>,
250
251 must_produce_diag: Option<Backtrace>,
254
255 has_printed: bool,
258
259 suppressed_expected_diag: bool,
262
263 taught_diagnostics: FxHashSet<ErrCode>,
267
268 emitted_diagnostic_codes: FxIndexSet<ErrCode>,
270
271 emitted_diagnostics: FxHashSet<Hash128>,
277
278 emitted_recursion_depth_exceeding_limit: bool,
286
287 stashed_diagnostics:
293 FxIndexMap<StashKey, FxIndexMap<Span, (DiagInner, Option<ErrorGuaranteed>, ThreadId)>>,
294
295 future_breakage_diagnostics: Vec<DiagInner>,
296
297 fulfilled_expectations: FxIndexSet<LintExpectationId>,
308
309 ice_file: Option<PathBuf>,
312
313 msrv: Option<RustcVersion>,
315}
316
317#[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]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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 ParenAroundGuardedPatInMatchArm",
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,
StashKey::ParenAroundGuardedPatInMatchArm => 165usize,
})
}
}Debug)]
319pub enum StashKey {
320 ItemNoType,
321 EarlySyntaxWarning,
322 CallIntoMethod,
323 LifetimeIsChar,
326 MaybeFruTypo,
329 CallAssocMethod,
330 UndeterminedMacroResolution,
331 ExprInPat,
333 GenericInFieldExpr,
337 ReturnTypeNotation,
338 ParenAroundGuardedPatInMatchArm,
339}
340
341fn default_track_diagnostic<R>(diag: DiagInner, f: &mut dyn FnMut(DiagInner) -> R) -> R {
342 (*f)(diag)
343}
344
345pub static TRACK_DIAGNOSTIC: AtomicRef<
348 fn(DiagInner, &mut dyn FnMut(DiagInner) -> Option<ErrorGuaranteed>) -> Option<ErrorGuaranteed>,
349> = AtomicRef::new(&(default_track_diagnostic as _));
350
351#[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]
#[rustc_trivial_field_reads]
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)]
352pub struct DiagCtxtFlags {
353 pub can_emit_warnings: bool,
356 pub treat_err_as_bug: Option<NonZero<usize>>,
359 pub eagerly_emit_delayed_bugs: bool,
362 pub macro_backtrace: bool,
365 pub deduplicate_diagnostics: bool,
367 pub track_diagnostics: bool,
369}
370
371impl Drop for DiagCtxtInner {
372 fn drop(&mut self) {
373 self.emit_stashed_diagnostics();
381
382 self.flush_delayed();
386
387 if !self.has_printed && !self.suppressed_expected_diag && !std::thread::panicking() {
391 if let Some(backtrace) = &self.must_produce_diag {
392 let suggestion = match backtrace.status() {
393 BacktraceStatus::Disabled => String::from(
394 "Backtraces are currently disabled: set `RUST_BACKTRACE=1` and re-run \
395 to see where it happened.",
396 ),
397 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!(
398 "This happened in the following `must_produce_diag` call's backtrace:\n\
399 {backtrace}",
400 ),
401 _ => String::from("(impossible to capture backtrace where this happened)"),
402 };
403 {
::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!(
404 "`trimmed_def_paths` called, diagnostics were expected but none were emitted. \
405 Use `with_no_trimmed_paths` for debugging. {suggestion}"
406 );
407 }
408 }
409 }
410}
411
412impl DiagCtxt {
413 pub fn disable_warnings(mut self) -> Self {
414 self.inner.get_mut().flags.can_emit_warnings = false;
415 self
416 }
417
418 pub fn with_flags(mut self, flags: DiagCtxtFlags) -> Self {
419 self.inner.get_mut().flags = flags;
420 self
421 }
422
423 pub fn with_ice_file(mut self, ice_file: PathBuf) -> Self {
424 self.inner.get_mut().ice_file = Some(ice_file);
425 self
426 }
427
428 pub fn with_msrv(mut self, msrv: RustcVersion) -> Self {
429 self.inner.get_mut().msrv = Some(msrv);
430 self
431 }
432
433 pub fn new(emitter: Box<DynEmitter>) -> Self {
434 Self { inner: Lock::new(DiagCtxtInner::new(emitter)) }
435 }
436
437 pub fn handle<'a>(&'a self) -> DiagCtxtHandle<'a> {
438 DiagCtxtHandle { dcx: self, tainted_with_errors: None }
439 }
440}
441
442impl<'a> DiagCtxtHandle<'a> {
443 pub fn make_silent(&self) {
444 let mut inner = self.dcx.inner.borrow_mut();
445 inner.emitter = Box::new(emitter::SilentEmitter {});
446 }
447
448 pub fn set_emitter(&self, emitter: Box<dyn Emitter + DynSend>) {
449 self.dcx.inner.borrow_mut().emitter = emitter;
450 }
451
452 pub fn can_emit_warnings(&self) -> bool {
455 self.dcx.inner.borrow().flags.can_emit_warnings
456 }
457
458 pub fn reset_err_count(&self) {
464 let mut inner = self.dcx.inner.borrow_mut();
467 let DiagCtxtInner {
468 flags: _,
469 err_guars,
470 lint_err_guars,
471 delayed_bugs,
472 deduplicated_err_count,
473 deduplicated_warn_count,
474 emitter: _,
475 must_produce_diag,
476 has_printed,
477 suppressed_expected_diag,
478 taught_diagnostics,
479 emitted_diagnostic_codes,
480 emitted_diagnostics,
481 emitted_recursion_depth_exceeding_limit,
482 stashed_diagnostics,
483 future_breakage_diagnostics,
484 fulfilled_expectations,
485 ice_file: _,
486 msrv: _,
487 } = inner.deref_mut();
488
489 *err_guars = Default::default();
492 *lint_err_guars = Default::default();
493 *delayed_bugs = Default::default();
494 *deduplicated_err_count = 0;
495 *deduplicated_warn_count = 0;
496 *must_produce_diag = None;
497 *has_printed = false;
498 *suppressed_expected_diag = false;
499 *taught_diagnostics = Default::default();
500 *emitted_diagnostic_codes = Default::default();
501 *emitted_diagnostics = Default::default();
502 *emitted_recursion_depth_exceeding_limit = false;
503 *stashed_diagnostics = Default::default();
504 *future_breakage_diagnostics = Default::default();
505 *fulfilled_expectations = Default::default();
506 }
507
508 pub fn into_taintable(
512 self,
513 tainted_with_errors: &'a Cell<Option<ErrorGuaranteed>>,
514 ) -> DiagCtxtHandle<'a> {
515 DiagCtxtHandle { dcx: self.dcx, tainted_with_errors: Some(tainted_with_errors) }
516 }
517
518 pub fn stash_diagnostic(
540 &self,
541 span: Span,
542 key: StashKey,
543 diag: DiagInner,
544 ) -> Option<ErrorGuaranteed> {
545 let guar = match diag.level {
546 Bug | Fatal => {
547 self.span_bug(
548 span,
549 ::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),
550 );
551 }
552 Error => Some(self.span_delayed_bug(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("stashing {0:?}", key))
})format!("stashing {key:?}"))),
556 DelayedBug => {
557 return self.dcx.inner.borrow_mut().emit_diagnostic(diag, self.tainted_with_errors);
558 }
559 Warning(_) | Note | Help | FailureNote => None,
560 };
561
562 self.dcx
566 .inner
567 .borrow_mut()
568 .stashed_diagnostics
569 .entry(key)
570 .or_default()
571 .insert(span.with_parent(None), (diag, guar, std::thread::current().id()));
572
573 guar
574 }
575
576 pub fn steal_non_err(self, span: Span, key: StashKey) -> Option<Diag<'a>> {
580 let (diag, guar, _) =
582 self.dcx.inner.borrow_mut().stashed_diagnostics.get_mut(&key).and_then(
583 |stashed_diagnostics| stashed_diagnostics.swap_remove(&span.with_parent(None)),
584 )?;
585 if !!diag.is_error() {
::core::panicking::panic("assertion failed: !diag.is_error()")
};assert!(!diag.is_error());
586 if !guar.is_none() {
::core::panicking::panic("assertion failed: guar.is_none()")
};assert!(guar.is_none());
587 Some(Diag::new_diagnostic(self, diag))
588 }
589
590 pub fn try_steal_modify_and_emit_err<F>(
595 self,
596 span: Span,
597 key: StashKey,
598 mut modify_err: F,
599 ) -> Option<ErrorGuaranteed>
600 where
601 F: FnMut(&mut Diag<'_>),
602 {
603 let err = self.dcx.inner.borrow_mut().stashed_diagnostics.get_mut(&key).and_then(
605 |stashed_diagnostics| stashed_diagnostics.swap_remove(&span.with_parent(None)),
606 );
607 err.map(|(err, guar, _)| {
608 {
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);
609 if !guar.is_some() {
::core::panicking::panic("assertion failed: guar.is_some()")
};assert!(guar.is_some());
610 let mut err = Diag::new_diagnostic(self, err);
611 modify_err(&mut err);
612 {
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);
613 err.emit_err()
614 })
615 }
616
617 pub fn try_steal_replace_and_emit_err(
621 self,
622 span: Span,
623 key: StashKey,
624 new_err: Diag<'_>,
625 ) -> ErrorGuaranteed {
626 let old_err = self.dcx.inner.borrow_mut().stashed_diagnostics.get_mut(&key).and_then(
628 |stashed_diagnostics| stashed_diagnostics.swap_remove(&span.with_parent(None)),
629 );
630 match old_err {
631 Some((old_err, guar, _)) => {
632 {
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);
633 if !guar.is_some() {
::core::panicking::panic("assertion failed: guar.is_some()")
};assert!(guar.is_some());
634 Diag::new_diagnostic(self, old_err).cancel();
637 }
638 None => {}
639 };
640 new_err.emit_err()
641 }
642
643 pub fn has_stashed_diagnostic(&self, span: Span, key: StashKey) -> bool {
644 let inner = self.dcx.inner.borrow();
645 if let Some(stashed_diagnostics) = inner.stashed_diagnostics.get(&key)
646 && !stashed_diagnostics.is_empty()
647 {
648 stashed_diagnostics.contains_key(&span.with_parent(None))
649 } else {
650 false
651 }
652 }
653
654 pub fn emit_stashed_diagnostics(&self) -> Option<ErrorGuaranteed> {
656 self.dcx.inner.borrow_mut().emit_stashed_diagnostics()
657 }
658
659 #[inline]
661 pub fn err_count(&self) -> usize {
662 let inner = self.dcx.inner.borrow();
663 inner.err_guars.len()
664 + inner.lint_err_guars.len()
665 + inner
666 .stashed_diagnostics
667 .values()
668 .map(|a| a.values().filter(|(_, guar, _)| guar.is_some()).count())
669 .sum::<usize>()
670 }
671
672 pub fn err_count_on_current_thread(&self) -> usize {
677 let inner = self.dcx.inner.borrow();
678 let current = std::thread::current().id();
679 inner.err_guars.iter().filter(|(_, thread)| *thread == current).count()
680 + inner.lint_err_guars.iter().filter(|(_, thread)| *thread == current).count()
681 + inner
682 .stashed_diagnostics
683 .values()
684 .map(|a| {
685 a.values()
686 .filter(|(_, guar, thread)| guar.is_some() && *thread == current)
687 .count()
688 })
689 .sum::<usize>()
690 }
691
692 pub fn has_errors_excluding_lint_errors(&self) -> Option<ErrorGuaranteed> {
695 self.dcx.inner.borrow().has_errors_excluding_lint_errors()
696 }
697
698 pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
700 self.dcx.inner.borrow().has_errors()
701 }
702
703 pub fn has_errors_or_delayed_bugs(&self) -> Option<ErrorGuaranteed> {
706 self.dcx.inner.borrow().has_errors_or_delayed_bugs()
707 }
708
709 pub fn print_error_count(&self) {
710 let mut inner = self.dcx.inner.borrow_mut();
711
712 if !inner.stashed_diagnostics.is_empty() {
::core::panicking::panic("assertion failed: inner.stashed_diagnostics.is_empty()")
};assert!(inner.stashed_diagnostics.is_empty());
715
716 if inner.treat_err_as_bug() {
717 return;
718 }
719
720 let warnings = match inner.deduplicated_warn_count {
721 0 => Cow::from(""),
722 1 => Cow::from("1 warning emitted"),
723 count => Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} warnings emitted", count))
})format!("{count} warnings emitted")),
724 };
725 let errors = match inner.deduplicated_err_count {
726 0 => Cow::from(""),
727 1 => Cow::from("aborting due to 1 previous error"),
728 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")),
729 };
730
731 match (errors.len(), warnings.len()) {
732 (0, 0) => return,
733 (0, _) => {
734 let diag = DiagInner::new(
736 Warning(Some(EmissionOverride::Forced { lint_id: None })),
737 DiagMessage::Str(warnings),
738 );
739 inner.emit_diagnostic(diag, None);
740 }
741 (_, 0) => {
742 inner.emit_diagnostic(DiagInner::new(Error, errors), self.tainted_with_errors);
743 }
744 (_, _) => {
745 inner.emit_diagnostic(
746 DiagInner::new(Error, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}; {1}", errors, warnings))
})format!("{errors}; {warnings}")),
747 self.tainted_with_errors,
748 );
749 }
750 }
751
752 let can_show_explain = inner.emitter.should_show_explain();
753 let are_there_diagnostics = !inner.emitted_diagnostic_codes.is_empty();
754 if can_show_explain && are_there_diagnostics {
755 let mut error_codes = inner
756 .emitted_diagnostic_codes
757 .iter()
758 .filter_map(|&code| {
759 if crate::codes::try_find_description(code).is_ok() {
760 Some(code.to_string())
761 } else {
762 None
763 }
764 })
765 .collect::<Vec<_>>();
766 if !error_codes.is_empty() {
767 error_codes.sort();
768 if error_codes.len() > 1 {
769 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
770 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!(
771 "Some errors have detailed explanations: {}{}",
772 error_codes[..limit].join(", "),
773 if error_codes.len() > 9 { "..." } else { "." }
774 );
775 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!(
776 "For more information about an error, try `rustc --explain {}`.",
777 &error_codes[0]
778 );
779 inner.emit_diagnostic(DiagInner::new(FailureNote, msg1), None);
780 inner.emit_diagnostic(DiagInner::new(FailureNote, msg2), None);
781 } else {
782 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!(
783 "For more information about this error, try `rustc --explain {}`.",
784 &error_codes[0]
785 );
786 inner.emit_diagnostic(DiagInner::new(FailureNote, msg), None);
787 }
788 }
789 }
790 }
791
792 pub fn abort_if_errors(&self) {
797 if let Some(guar) = self.has_errors() {
798 guar.raise_fatal();
799 }
800 }
801
802 pub fn must_teach(&self, code: ErrCode) -> bool {
808 self.dcx.inner.borrow_mut().taught_diagnostics.insert(code)
809 }
810
811 pub fn emit_diagnostic(&self, diagnostic: DiagInner) -> Option<ErrorGuaranteed> {
812 self.dcx.inner.borrow_mut().emit_diagnostic(diagnostic, self.tainted_with_errors)
813 }
814
815 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
816 self.dcx.inner.borrow_mut().emitter.emit_artifact_notification(path, artifact_type);
817 }
818
819 pub fn emit_timing_section_start(&self, record: TimingRecord) {
820 self.dcx.inner.borrow_mut().emitter.emit_timing_section(record, TimingEvent::Start);
821 }
822
823 pub fn emit_timing_section_end(&self, record: TimingRecord) {
824 self.dcx.inner.borrow_mut().emitter.emit_timing_section(record, TimingEvent::End);
825 }
826
827 pub fn emit_future_breakage_report(&self) {
828 let inner = &mut *self.dcx.inner.borrow_mut();
829 let diags = mem::take(&mut inner.future_breakage_diagnostics);
830 if !diags.is_empty() {
831 inner.emitter.emit_future_breakage_report(diags);
832 }
833 }
834
835 pub fn emit_unused_externs(
836 &self,
837 lint_level: rustc_lint_defs::Level,
838 loud: bool,
839 unused_externs: &[&str],
840 ) {
841 let mut inner = self.dcx.inner.borrow_mut();
842
843 if loud && lint_level.is_error() {
854 #[allow(deprecated)]
857 let guar = ErrorGuaranteed::unchecked_error_guaranteed();
858 inner.lint_err_guars.push((guar, std::thread::current().id()));
859 inner.panic_if_treat_err_as_bug();
860 }
861
862 inner.emitter.emit_unused_externs(lint_level, unused_externs)
863 }
864
865 #[track_caller]
870 pub fn fulfill_expectation(self, expectation: impl Into<LintExpectationId>) {
871 let emission_override = Some(EmissionOverride::Expected { lint_id: expectation.into() });
872 let msg = "this is a dummy diagnostic, to submit and store an expectation";
873 Diag::new(self, Warning(emission_override), msg).emit()
874 }
875
876 #[must_use]
879 pub fn steal_fulfilled_expectation_ids(&self) -> FxIndexSet<LintExpectationId> {
880 mem::take(&mut self.dcx.inner.borrow_mut().fulfilled_expectations)
881 }
882
883 pub fn flush_delayed(&self) {
888 self.dcx.inner.borrow_mut().flush_delayed();
889 }
890
891 #[track_caller]
894 pub fn set_must_produce_diag(&self) {
895 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!(
896 self.dcx.inner.borrow().must_produce_diag.is_none(),
897 "should only need to collect a backtrace once"
898 );
899 self.dcx.inner.borrow_mut().must_produce_diag = Some(Backtrace::capture());
900 }
901}
902
903impl<'a> DiagCtxtHandle<'a> {
908 #[track_caller]
909 pub fn struct_bug(self, msg: impl Into<Cow<'static, str>>) -> Diag<'a> {
910 Diag::new(self, Bug, msg.into())
911 }
912
913 #[track_caller]
914 pub fn bug(self, msg: impl Into<Cow<'static, str>>) -> ! {
915 self.struct_bug(msg).emit_bug()
916 }
917
918 #[track_caller]
919 pub fn struct_span_bug(
920 self,
921 span: impl Into<MultiSpan>,
922 msg: impl Into<Cow<'static, str>>,
923 ) -> Diag<'a> {
924 self.struct_bug(msg).with_span(span)
925 }
926
927 #[track_caller]
928 pub fn span_bug(self, span: impl Into<MultiSpan>, msg: impl Into<Cow<'static, str>>) -> ! {
929 self.struct_span_bug(span, msg.into()).emit_bug()
930 }
931
932 #[track_caller]
933 pub fn create_bug(self, bug: impl Diagnostic<'a>) -> Diag<'a> {
934 bug.into_diag(self, Bug)
935 }
936
937 #[track_caller]
938 pub fn emit_bug(self, bug: impl Diagnostic<'a>) -> ! {
939 self.create_bug(bug).emit_bug()
940 }
941
942 #[track_caller]
943 pub fn struct_fatal(self, msg: impl Into<DiagMessage>) -> Diag<'a> {
944 Diag::new(self, Fatal, msg)
945 }
946
947 #[track_caller]
948 pub fn fatal(self, msg: impl Into<DiagMessage>) -> ! {
949 self.struct_fatal(msg).emit_fatal()
950 }
951
952 #[track_caller]
953 pub fn struct_span_fatal(
954 self,
955 span: impl Into<MultiSpan>,
956 msg: impl Into<DiagMessage>,
957 ) -> Diag<'a> {
958 self.struct_fatal(msg).with_span(span)
959 }
960
961 #[track_caller]
962 pub fn span_fatal(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) -> ! {
963 self.struct_span_fatal(span, msg).emit_fatal()
964 }
965
966 #[track_caller]
967 pub fn create_fatal(self, fatal: impl Diagnostic<'a>) -> Diag<'a> {
968 fatal.into_diag(self, Fatal)
969 }
970
971 #[track_caller]
972 pub fn emit_fatal(self, fatal: impl Diagnostic<'a>) -> ! {
973 self.create_fatal(fatal).emit_fatal()
974 }
975
976 #[track_caller]
977 pub fn struct_err(self, msg: impl Into<DiagMessage>) -> Diag<'a> {
978 Diag::new(self, Error, msg)
979 }
980
981 #[track_caller]
982 pub fn err(self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
983 self.struct_err(msg).emit_err()
984 }
985
986 #[track_caller]
987 pub fn struct_span_err(
988 self,
989 span: impl Into<MultiSpan>,
990 msg: impl Into<DiagMessage>,
991 ) -> Diag<'a> {
992 self.struct_err(msg).with_span(span)
993 }
994
995 #[track_caller]
996 pub fn span_err(
997 self,
998 span: impl Into<MultiSpan>,
999 msg: impl Into<DiagMessage>,
1000 ) -> ErrorGuaranteed {
1001 self.struct_span_err(span, msg).emit_err()
1002 }
1003
1004 #[track_caller]
1005 pub fn create_err(self, err: impl Diagnostic<'a>) -> Diag<'a> {
1006 err.into_diag(self, Error)
1007 }
1008
1009 #[track_caller]
1010 pub fn emit_err(self, err: impl Diagnostic<'a>) -> ErrorGuaranteed {
1011 self.create_err(err).emit_err()
1012 }
1013
1014 #[track_caller]
1016 pub fn delayed_bug(self, msg: impl Into<Cow<'static, str>>) -> ErrorGuaranteed {
1017 Diag::new(self, DelayedBug, msg.into()).emit_err()
1018 }
1019
1020 #[track_caller]
1025 pub fn span_delayed_bug(
1026 self,
1027 sp: impl Into<MultiSpan>,
1028 msg: impl Into<Cow<'static, str>>,
1029 ) -> ErrorGuaranteed {
1030 Diag::new(self, DelayedBug, msg.into()).with_span(sp).emit_err()
1031 }
1032
1033 #[track_caller]
1034 pub fn struct_warn(self, msg: impl Into<DiagMessage>) -> Diag<'a> {
1035 Diag::new(self, Warning(None), msg)
1036 }
1037
1038 #[track_caller]
1039 pub fn warn(self, msg: impl Into<DiagMessage>) {
1040 self.struct_warn(msg).emit()
1041 }
1042
1043 #[track_caller]
1044 pub fn struct_span_warn(
1045 self,
1046 span: impl Into<MultiSpan>,
1047 msg: impl Into<DiagMessage>,
1048 ) -> Diag<'a> {
1049 self.struct_warn(msg).with_span(span)
1050 }
1051
1052 #[track_caller]
1053 pub fn span_warn(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) {
1054 self.struct_span_warn(span, msg).emit()
1055 }
1056
1057 #[track_caller]
1058 pub fn create_warn(self, warning: impl Diagnostic<'a>) -> Diag<'a> {
1059 warning.into_diag(self, Warning(None))
1060 }
1061
1062 #[track_caller]
1063 pub fn emit_warn(self, warning: impl Diagnostic<'a>) {
1064 self.create_warn(warning).emit()
1065 }
1066
1067 #[track_caller]
1068 pub fn struct_note(self, msg: impl Into<DiagMessage>) -> Diag<'a> {
1069 Diag::new(self, Note, msg)
1070 }
1071
1072 #[track_caller]
1073 pub fn note(&self, msg: impl Into<DiagMessage>) {
1074 self.struct_note(msg).emit()
1075 }
1076
1077 #[track_caller]
1078 pub fn struct_span_note(
1079 self,
1080 span: impl Into<MultiSpan>,
1081 msg: impl Into<DiagMessage>,
1082 ) -> Diag<'a> {
1083 self.struct_note(msg).with_span(span)
1084 }
1085
1086 #[track_caller]
1087 pub fn span_note(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) {
1088 self.struct_span_note(span, msg).emit()
1089 }
1090
1091 #[track_caller]
1092 pub fn create_note(self, note: impl Diagnostic<'a>) -> Diag<'a> {
1093 note.into_diag(self, Note)
1094 }
1095
1096 #[track_caller]
1097 pub fn emit_note(self, note: impl Diagnostic<'a>) {
1098 self.create_note(note).emit()
1099 }
1100}
1101
1102impl DiagCtxtInner {
1103 fn new(emitter: Box<DynEmitter>) -> Self {
1104 Self {
1105 flags: DiagCtxtFlags { can_emit_warnings: true, ..Default::default() },
1106 err_guars: Vec::new(),
1107 lint_err_guars: Vec::new(),
1108 delayed_bugs: Vec::new(),
1109 deduplicated_err_count: 0,
1110 deduplicated_warn_count: 0,
1111 emitter,
1112 must_produce_diag: None,
1113 has_printed: false,
1114 suppressed_expected_diag: false,
1115 taught_diagnostics: Default::default(),
1116 emitted_diagnostic_codes: Default::default(),
1117 emitted_diagnostics: Default::default(),
1118 emitted_recursion_depth_exceeding_limit: false,
1119 stashed_diagnostics: Default::default(),
1120 future_breakage_diagnostics: Vec::new(),
1121 fulfilled_expectations: Default::default(),
1122 ice_file: None,
1123 msrv: None,
1124 }
1125 }
1126
1127 fn emit_stashed_diagnostics(&mut self) -> Option<ErrorGuaranteed> {
1129 let mut guar = None;
1130 let has_errors = !self.err_guars.is_empty();
1131 for (_, stashed_diagnostics) in mem::take(&mut self.stashed_diagnostics).into_iter() {
1132 for (_, (diag, _guar, _thread)) in stashed_diagnostics {
1133 if has_errors
1136 && let Warning(emission_override) = diag.level
1137 && !#[allow(non_exhaustive_omitted_patterns)] match emission_override {
Some(EmissionOverride::Forced { .. }) => true,
_ => false,
}matches!(emission_override, Some(EmissionOverride::Forced { .. }))
1138 {
1139 continue;
1140 }
1141 guar = guar.or(self.emit_diagnostic(diag, None));
1142 }
1143 }
1144 guar
1145 }
1146
1147 fn emit_diagnostic(
1149 &mut self,
1150 mut diagnostic: DiagInner,
1151 taint: Option<&Cell<Option<ErrorGuaranteed>>>,
1152 ) -> Option<ErrorGuaranteed> {
1153 if diagnostic.has_future_breakage() {
1154 {
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(_));
1158 self.future_breakage_diagnostics.push(diagnostic.clone());
1159 }
1160
1161 match diagnostic.level {
1165 Bug => {}
1166 Fatal | Error => {
1167 if self.treat_next_err_as_bug() {
1168 diagnostic.level = Bug;
1170 }
1171 }
1172 DelayedBug => {
1173 if self.flags.eagerly_emit_delayed_bugs {
1178 if self.treat_next_err_as_bug() {
1180 diagnostic.level = Bug;
1181 } else {
1182 diagnostic.level = Error;
1183 }
1184 } else {
1185 return if let Some(guar) = self.has_errors() {
1188 Some(guar)
1189 } else {
1190 let backtrace = std::backtrace::Backtrace::capture();
1194 #[allow(deprecated)]
1198 let guar = ErrorGuaranteed::unchecked_error_guaranteed();
1199 self.delayed_bugs
1200 .push((DelayedDiagInner::with_backtrace(diagnostic, backtrace), guar));
1201 Some(guar)
1202 };
1203 }
1204 }
1205 Warning(emission_override) => {
1206 match emission_override {
1207 None => {
1208 if !self.flags.can_emit_warnings {
1209 if diagnostic.has_future_breakage() {
1211 TRACK_DIAGNOSTIC(diagnostic, &mut |_| None);
1213 }
1214 return None;
1215 }
1216 }
1217 Some(EmissionOverride::Forced { lint_id: None }) => {}
1218 Some(EmissionOverride::Forced { lint_id: Some(lint_id) }) => {
1219 self.fulfilled_expectations.insert(lint_id);
1220 }
1221 Some(EmissionOverride::Allowed) => {
1222 if !diagnostic.has_future_breakage() {
::core::panicking::panic("assertion failed: diagnostic.has_future_breakage()")
};assert!(diagnostic.has_future_breakage());
1223 TRACK_DIAGNOSTIC(diagnostic, &mut |_| None);
1224 self.suppressed_expected_diag = true;
1225 return None;
1226 }
1227 Some(EmissionOverride::Expected { lint_id }) => {
1228 self.fulfilled_expectations.insert(lint_id);
1229 TRACK_DIAGNOSTIC(diagnostic, &mut |_| None);
1230 self.suppressed_expected_diag = true;
1231 return None;
1232 }
1233 }
1234 }
1235 Note | Help | FailureNote => {}
1236 }
1237
1238 if let (Some(msrv), Some(diag_msrv)) = (self.msrv, diagnostic.rust_version())
1239 && diag_msrv > msrv
1240 {
1241 return None;
1242 }
1243
1244 TRACK_DIAGNOSTIC(diagnostic, &mut |mut diagnostic| {
1245 if let Some(code) = diagnostic.code {
1246 self.emitted_diagnostic_codes.insert(code);
1247 }
1248
1249 let already_emitted = !self.emitted_diagnostics.insert(diagnostic.dedup_hash());
1250
1251 let is_error = diagnostic.is_error();
1252 let is_lint = diagnostic.is_lint.is_some();
1253 let silence_recursion_depth_exceeded_limit =
1255 diagnostic.is_lint.as_ref().is_some_and(|lint| {
1256 lint.name.eq_ignore_ascii_case(
1257 rustc_lint_defs::builtin::RECURSION_DEPTH_EXCEEDING_LIMIT.name,
1258 ) && mem::replace(&mut self.emitted_recursion_depth_exceeding_limit, true)
1259 });
1260
1261 if !silence_recursion_depth_exceeded_limit
1264 && !(self.flags.deduplicate_diagnostics && already_emitted)
1265 {
1266 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_errors/src/lib.rs:1266",
"rustc_errors", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_errors/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1266u32),
::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);
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/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_errors/src/lib.rs:1267",
"rustc_errors", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/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("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);
1268
1269 let show_sub = |sub: &Subdiag| {
1270 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_errors/src/lib.rs:1270",
"rustc_errors", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_errors/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1270u32),
::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);
1271 match sub.level {
1272 Sublevel::Error | Sublevel::Warning | Sublevel::Note | Sublevel::Help => {
1273 true
1274 }
1275 Sublevel::OnceNote | Sublevel::OnceHelp => {
1276 self.emitted_diagnostics.insert(sub.dedup_hash())
1277 }
1278 }
1279 };
1280 diagnostic.children.retain(show_sub);
1281 if already_emitted {
1282 let msg = "duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`";
1283 diagnostic.sub(Sublevel::Note, msg, MultiSpan::new());
1284 }
1285
1286 if is_error {
1287 self.deduplicated_err_count += 1;
1288 } else if #[allow(non_exhaustive_omitted_patterns)] match diagnostic.level {
Warning(_) => true,
_ => false,
}matches!(diagnostic.level, Warning(_)) {
1289 self.deduplicated_warn_count += 1;
1290 }
1291 self.has_printed = true;
1292
1293 self.emitter.emit_diagnostic(diagnostic);
1294 }
1295
1296 if is_error {
1297 if !self.delayed_bugs.is_empty() {
1302 {
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);
1303 self.delayed_bugs.clear();
1304 self.delayed_bugs.shrink_to_fit();
1305 }
1306
1307 #[allow(deprecated)]
1310 let guar = ErrorGuaranteed::unchecked_error_guaranteed();
1311 let thread = std::thread::current().id();
1312 if is_lint {
1313 self.lint_err_guars.push((guar, thread));
1314 } else {
1315 if let Some(taint) = taint {
1316 taint.set(Some(guar));
1317 }
1318 self.err_guars.push((guar, thread));
1319 }
1320 self.panic_if_treat_err_as_bug();
1321 Some(guar)
1322 } else {
1323 None
1324 }
1325 })
1326 }
1327
1328 fn treat_err_as_bug(&self) -> bool {
1329 self.flags
1330 .treat_err_as_bug
1331 .is_some_and(|c| self.err_guars.len() + self.lint_err_guars.len() >= c.get())
1332 }
1333
1334 fn treat_next_err_as_bug(&self) -> bool {
1336 self.flags
1337 .treat_err_as_bug
1338 .is_some_and(|c| self.err_guars.len() + self.lint_err_guars.len() + 1 >= c.get())
1339 }
1340
1341 fn has_errors_excluding_lint_errors(&self) -> Option<ErrorGuaranteed> {
1342 self.err_guars.get(0).map(|(guar, _)| *guar).or_else(|| {
1343 if let Some((_diag, guar, _)) = self
1344 .stashed_diagnostics
1345 .values()
1346 .flat_map(|stashed_diagnostics| stashed_diagnostics.values())
1347 .find(|(diag, guar, _)| guar.is_some() && diag.is_lint.is_none())
1348 {
1349 *guar
1350 } else {
1351 None
1352 }
1353 })
1354 }
1355
1356 fn has_errors(&self) -> Option<ErrorGuaranteed> {
1357 self.err_guars
1358 .get(0)
1359 .map(|(guar, _)| *guar)
1360 .or_else(|| self.lint_err_guars.get(0).map(|(guar, _)| *guar))
1361 .or_else(|| {
1362 self.stashed_diagnostics.values().find_map(|stashed_diagnostics| {
1363 stashed_diagnostics.values().find_map(|(_, guar, _)| *guar)
1364 })
1365 })
1366 }
1367
1368 fn has_errors_or_delayed_bugs(&self) -> Option<ErrorGuaranteed> {
1369 self.has_errors().or_else(|| self.delayed_bugs.get(0).map(|(_, guar)| guar).copied())
1370 }
1371
1372 fn flush_delayed(&mut self) {
1373 if !self.stashed_diagnostics.is_empty() {
::core::panicking::panic("assertion failed: self.stashed_diagnostics.is_empty()")
};assert!(self.stashed_diagnostics.is_empty());
1377
1378 if !self.err_guars.is_empty() {
1379 return;
1381 }
1382
1383 if self.delayed_bugs.is_empty() {
1384 return;
1386 }
1387
1388 let bugs: Vec<_> = mem::take(&mut self.delayed_bugs).into_iter().map(|(b, _)| b).collect();
1389
1390 let backtrace = std::env::var_os("RUST_BACKTRACE").as_deref() != Some(OsStr::new("0"));
1391 let decorate = backtrace || self.ice_file.is_none();
1392 let mut out = self
1393 .ice_file
1394 .as_ref()
1395 .and_then(|file| std::fs::File::options().create(true).append(true).open(file).ok());
1396
1397 let note1 = "no errors encountered even though delayed bugs were created";
1402 let note2 = "those delayed bugs will now be shown as internal compiler errors";
1403 self.emit_diagnostic(DiagInner::new(Note, note1), None);
1404 self.emit_diagnostic(DiagInner::new(Note, note2), None);
1405
1406 for bug in bugs {
1407 if let Some(out) = &mut out {
1408 _ = 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!(
1409 out,
1410 "delayed bug: {}\n{}\n",
1411 bug.inner
1412 .messages
1413 .iter()
1414 .filter_map(|(msg, _)| msg.as_str())
1415 .collect::<String>(),
1416 &bug.note
1417 );
1418 }
1419
1420 let mut bug = if decorate { bug.decorate() } else { bug.inner };
1421
1422 if bug.level != DelayedBug {
1424 let msg = rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`flushed_delayed` got diagnostic with level {$level}, instead of the expected `DelayedBug`"))msg!(
1431 "`flushed_delayed` got diagnostic with level {$level}, instead of the expected `DelayedBug`"
1432 ).arg("level", bug.level).format();
1433 bug.sub(Sublevel::Note, msg, bug.span.primary_span().unwrap().into());
1434 }
1435 bug.level = Bug;
1436
1437 self.emit_diagnostic(bug, None);
1438 }
1439
1440 panic::panic_any(DelayedBugPanic);
1442 }
1443
1444 fn panic_if_treat_err_as_bug(&self) {
1445 if self.treat_err_as_bug() {
1446 let n = self.flags.treat_err_as_bug.map(|c| c.get()).unwrap();
1447 {
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());
1448 if n == 1 {
1449 {
::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`");
1450 } else {
1451 {
::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}`");
1452 }
1453 }
1454 }
1455}
1456
1457struct DelayedDiagInner {
1458 inner: DiagInner,
1459 note: Backtrace,
1460}
1461
1462impl DelayedDiagInner {
1463 fn with_backtrace(diagnostic: DiagInner, backtrace: Backtrace) -> Self {
1464 DelayedDiagInner { inner: diagnostic, note: backtrace }
1465 }
1466
1467 fn decorate(self) -> DiagInner {
1468 let mut diag = self.inner;
1472 let msg = match self.note.status() {
1473 BacktraceStatus::Captured => rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("delayed at {$emitted_at}\n {$note}"))msg!(
1474 "delayed at {$emitted_at}
1475 {$note}"
1476 ),
1477 _ => rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("delayed at {$emitted_at} - {$note}"))msg!("delayed at {$emitted_at} - {$note}"),
1480 }
1481 .arg("emitted_at", diag.emitted_at.clone())
1482 .arg("note", self.note)
1483 .format();
1484 diag.sub(Sublevel::Note, msg, diag.span.primary_span().unwrap_or(DUMMY_SP).into());
1485 diag
1486 }
1487}
1488
1489#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for EmissionOverride {
}
#[automatically_derived]impl ::core::clone::Clone for EmissionOverride {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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)]
1506pub enum EmissionOverride {
1507 Forced { lint_id: Option<LintExpectationId> },
1509
1510 Allowed,
1513
1514 Expected { lint_id: LintExpectationId },
1516}
1517
1518#[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]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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)]
1530pub enum Level {
1531 Bug,
1533
1534 Fatal,
1537
1538 Error,
1541
1542 DelayedBug,
1547
1548 Warning(Option<EmissionOverride>),
1551
1552 Note,
1554
1555 Help,
1561
1562 FailureNote,
1565}
1566
1567impl fmt::Display for Level {
1568 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1569 self.to_str().fmt(f)
1570 }
1571}
1572
1573impl Level {
1574 pub fn to_str(self) -> &'static str {
1575 match self {
1576 Bug | DelayedBug => "error: internal compiler error",
1577 Fatal | Error => "error",
1578 Warning(_) => "warning",
1579 Note => "note",
1580 Help => "help",
1581 FailureNote => "failure-note",
1582 }
1583 }
1584
1585 pub fn is_failure_note(self) -> bool {
1586 #[allow(non_exhaustive_omitted_patterns)] match self {
FailureNote => true,
_ => false,
}matches!(self, FailureNote)
1587 }
1588}
1589
1590impl IntoDiagArg for Level {
1591 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
1592 DiagArgValue::Str(Cow::from(self.to_string()))
1593 }
1594}
1595
1596#[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]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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)]
1598pub enum Sublevel {
1599 Error,
1604
1605 Warning,
1607
1608 Note,
1610
1611 OnceNote,
1613
1614 Help,
1616
1617 OnceHelp,
1619}
1620
1621impl Sublevel {
1622 pub fn to_str(self) -> &'static str {
1623 match self {
1624 Sublevel::Error => "error",
1625 Sublevel::Warning => "warning",
1626 Sublevel::Note | Sublevel::OnceNote => "note",
1627 Sublevel::Help | Sublevel::OnceHelp => "help",
1628 }
1629 }
1630}
1631
1632#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Style {
#[inline]
#[rustc_trivial_field_reads]
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)]
1633pub enum Style {
1634 NoStyle,
1635 Highlight,
1636}
1637
1638pub fn elided_lifetime_in_path_suggestion(
1640 source_map: &SourceMap,
1641 n: usize,
1642 path_span: Span,
1643 incl_angl_brckt: bool,
1644 insertion_span: Span,
1645) -> ElidedLifetimeInPathSubdiag {
1646 let expected = ExpectedLifetimeParameter { span: path_span, count: n };
1647 let indicate = source_map.is_span_accessible(insertion_span).then(|| {
1649 let anon_lts = ::alloc::vec::from_elem_global("'_", n)vec!["'_"; n].join(", ");
1650 let suggestion =
1651 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}, ") };
1652
1653 IndicateAnonymousLifetime { span: insertion_span.shrink_to_hi(), count: n, suggestion }
1654 });
1655
1656 ElidedLifetimeInPathSubdiag { expected, indicate }
1657}
1658
1659pub fn a_or_an(s: &str) -> &'static str {
1663 let mut chars = s.chars();
1664 let Some(mut first_alpha_char) = chars.next() else {
1665 return "a";
1666 };
1667 if first_alpha_char == '`' {
1668 let Some(next) = chars.next() else {
1669 return "a";
1670 };
1671 first_alpha_char = next;
1672 }
1673 if ["a", "e", "i", "o", "u", "&"].contains(&&first_alpha_char.to_lowercase().to_string()[..]) {
1674 "an"
1675 } else {
1676 "a"
1677 }
1678}
1679
1680#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for TerminalUrl {
}
#[automatically_derived]impl ::core::clone::Clone for TerminalUrl {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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)]
1681pub enum TerminalUrl {
1682 No,
1683 Yes,
1684 Auto,
1685}