1use std::borrow::Cow;
2use std::fmt::{self, Debug};
3use std::hash::{Hash, Hasher};
4use std::marker::PhantomData;
5use std::ops::{Deref, DerefMut};
6use std::panic;
7use std::path::PathBuf;
8use std::thread::panicking;
9
10use rustc_data_structures::sync::{DynSend, DynSync};
11use rustc_error_messages::{DiagArgMap, DiagArgName, DiagArgValue, IntoDiagArg};
12use rustc_lint_defs::{Applicability, LintExpectationId};
13use rustc_macros::{Decodable, Encodable};
14use rustc_span::{DUMMY_SP, Span, Spanned, Symbol};
15use tracing::debug;
16
17use crate::{
18 CodeSuggestion, DiagCtxtHandle, DiagMessage, ErrCode, ErrorGuaranteed, ExplicitBug, Level,
19 MultiSpan, StashKey, Style, Substitution, SubstitutionPart, SuggestionStyle, Suggestions,
20};
21
22pub trait EmissionGuarantee: Sized {
25 type EmitResult = Self;
28
29 #[track_caller]
33 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult;
34}
35
36impl EmissionGuarantee for ErrorGuaranteed {
37 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
38 diag.emit_producing_error_guaranteed()
39 }
40}
41
42impl EmissionGuarantee for () {
43 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
44 diag.emit_producing_nothing();
45 }
46}
47
48#[derive(#[automatically_derived]
impl ::core::marker::Copy for BugAbort { }Copy, #[automatically_derived]
impl ::core::clone::Clone for BugAbort {
#[inline]
fn clone(&self) -> BugAbort { *self }
}Clone)]
51pub struct BugAbort;
52
53impl EmissionGuarantee for BugAbort {
54 type EmitResult = !;
55
56 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
57 diag.emit_producing_nothing();
58 panic::panic_any(ExplicitBug);
59 }
60}
61
62#[derive(#[automatically_derived]
impl ::core::marker::Copy for FatalAbort { }Copy, #[automatically_derived]
impl ::core::clone::Clone for FatalAbort {
#[inline]
fn clone(&self) -> FatalAbort { *self }
}Clone)]
65pub struct FatalAbort;
66
67impl EmissionGuarantee for FatalAbort {
68 type EmitResult = !;
69
70 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
71 diag.emit_producing_nothing();
72 crate::FatalError.raise()
73 }
74}
75
76impl EmissionGuarantee for rustc_span::fatal_error::FatalError {
77 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
78 diag.emit_producing_nothing();
79 rustc_span::fatal_error::FatalError
80 }
81}
82
83#[rustc_diagnostic_item = "Diagnostic"]
105pub trait Diagnostic<'a, G: EmissionGuarantee = ErrorGuaranteed> {
106 #[must_use]
108 #[track_caller]
109 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G>;
110}
111
112impl<'a, T, G> Diagnostic<'a, G> for Spanned<T>
113where
114 T: Diagnostic<'a, G>,
115 G: EmissionGuarantee,
116{
117 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
118 self.node.into_diag(dcx, level).with_span(self.span)
119 }
120}
121
122impl<'a> Diagnostic<'a, ()>
123 for Box<
124 dyn for<'b> FnOnce(DiagCtxtHandle<'b>, Level) -> Diag<'b, ()> + DynSync + DynSend + 'static,
125 >
126{
127 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
128 self(dcx, level)
129 }
130}
131
132pub struct DiagDecorator<F: FnOnce(&mut Diag<'_, ()>)>(pub F);
134
135impl<'a, F: FnOnce(&mut Diag<'_, ()>)> Diagnostic<'a, ()> for DiagDecorator<F> {
136 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
137 let mut diag = Diag::new(dcx, level, "");
138 (self.0)(&mut diag);
139 diag
140 }
141}
142
143#[rustc_diagnostic_item = "Subdiagnostic"]
146pub trait Subdiagnostic
147where
148 Self: Sized,
149{
150 fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>);
152}
153
154#[derive(#[automatically_derived]
impl ::core::clone::Clone for DiagLocation {
#[inline]
fn clone(&self) -> DiagLocation {
DiagLocation {
file: ::core::clone::Clone::clone(&self.file),
line: ::core::clone::Clone::clone(&self.line),
col: ::core::clone::Clone::clone(&self.col),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for DiagLocation {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "DiagLocation",
"file", &self.file, "line", &self.line, "col", &&self.col)
}
}Debug, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for DiagLocation {
fn encode(&self, __encoder: &mut __E) {
match *self {
DiagLocation {
file: ref __binding_0,
line: ref __binding_1,
col: ref __binding_2 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for DiagLocation {
fn decode(__decoder: &mut __D) -> Self {
DiagLocation {
file: ::rustc_serialize::Decodable::decode(__decoder),
line: ::rustc_serialize::Decodable::decode(__decoder),
col: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
155pub struct DiagLocation {
156 file: Cow<'static, str>,
157 line: u32,
158 col: u32,
159}
160
161impl DiagLocation {
162 #[track_caller]
163 pub fn caller() -> Self {
164 let loc = panic::Location::caller();
165 DiagLocation { file: loc.file().into(), line: loc.line(), col: loc.column() }
166 }
167}
168
169impl fmt::Display for DiagLocation {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 f.write_fmt(format_args!("{0}:{1}:{2}", self.file, self.line, self.col))write!(f, "{}:{}:{}", self.file, self.line, self.col)
172 }
173}
174
175#[derive(#[automatically_derived]
impl ::core::clone::Clone for IsLint {
#[inline]
fn clone(&self) -> IsLint {
IsLint {
name: ::core::clone::Clone::clone(&self.name),
has_future_breakage: ::core::clone::Clone::clone(&self.has_future_breakage),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for IsLint {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "IsLint",
"name", &self.name, "has_future_breakage",
&&self.has_future_breakage)
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for IsLint {
#[inline]
fn eq(&self, other: &IsLint) -> bool {
self.has_future_breakage == other.has_future_breakage &&
self.name == other.name
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for IsLint {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<String>;
let _: ::core::cmp::AssertParamIsEq<bool>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for IsLint {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.name, state);
::core::hash::Hash::hash(&self.has_future_breakage, state)
}
}Hash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for IsLint {
fn encode(&self, __encoder: &mut __E) {
match *self {
IsLint {
name: ref __binding_0, has_future_breakage: ref __binding_1
} => {
::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 IsLint {
fn decode(__decoder: &mut __D) -> Self {
IsLint {
name: ::rustc_serialize::Decodable::decode(__decoder),
has_future_breakage: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
176pub struct IsLint {
177 pub(crate) name: String,
179 has_future_breakage: bool,
181}
182
183#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DiagStyledString {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DiagStyledString", &&self.0)
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for DiagStyledString {
#[inline]
fn eq(&self, other: &DiagStyledString) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for DiagStyledString {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Vec<StringPart>>;
}
}Eq)]
184pub struct DiagStyledString(pub Vec<StringPart>);
185
186impl DiagStyledString {
187 pub fn new() -> DiagStyledString {
188 DiagStyledString(::alloc::vec::Vec::new()vec![])
189 }
190 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
191 self.0.push(StringPart::normal(t));
192 }
193 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
194 self.0.push(StringPart::highlighted(t));
195 }
196 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
197 if highlight {
198 self.push_highlighted(t);
199 } else {
200 self.push_normal(t);
201 }
202 }
203 pub fn normal<S: Into<String>>(t: S) -> DiagStyledString {
204 DiagStyledString(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[StringPart::normal(t)]))vec![StringPart::normal(t)])
205 }
206
207 pub fn highlighted<S: Into<String>>(t: S) -> DiagStyledString {
208 DiagStyledString(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[StringPart::highlighted(t)]))vec![StringPart::highlighted(t)])
209 }
210
211 pub fn content(&self) -> String {
212 self.0.iter().map(|x| x.content.as_str()).collect::<String>()
213 }
214}
215
216#[derive(#[automatically_derived]
impl ::core::fmt::Debug for StringPart {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "StringPart",
"content", &self.content, "style", &&self.style)
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for StringPart {
#[inline]
fn eq(&self, other: &StringPart) -> bool {
self.content == other.content && self.style == other.style
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for StringPart {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<String>;
let _: ::core::cmp::AssertParamIsEq<Style>;
}
}Eq)]
217pub struct StringPart {
218 content: String,
219 style: Style,
220}
221
222impl StringPart {
223 pub fn normal<S: Into<String>>(content: S) -> StringPart {
224 StringPart { content: content.into(), style: Style::NoStyle }
225 }
226
227 pub fn highlighted<S: Into<String>>(content: S) -> StringPart {
228 StringPart { content: content.into(), style: Style::Highlight }
229 }
230}
231
232#[must_use]
237#[derive(#[automatically_derived]
impl ::core::clone::Clone for DiagInner {
#[inline]
fn clone(&self) -> DiagInner {
DiagInner {
level: ::core::clone::Clone::clone(&self.level),
messages: ::core::clone::Clone::clone(&self.messages),
code: ::core::clone::Clone::clone(&self.code),
lint_id: ::core::clone::Clone::clone(&self.lint_id),
span: ::core::clone::Clone::clone(&self.span),
children: ::core::clone::Clone::clone(&self.children),
suggestions: ::core::clone::Clone::clone(&self.suggestions),
args: ::core::clone::Clone::clone(&self.args),
sort_span: ::core::clone::Clone::clone(&self.sort_span),
is_lint: ::core::clone::Clone::clone(&self.is_lint),
long_ty_path: ::core::clone::Clone::clone(&self.long_ty_path),
emitted_at: ::core::clone::Clone::clone(&self.emitted_at),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for DiagInner {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["level", "messages", "code", "lint_id", "span", "children",
"suggestions", "args", "sort_span", "is_lint",
"long_ty_path", "emitted_at"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.level, &self.messages, &self.code, &self.lint_id,
&self.span, &self.children, &self.suggestions, &self.args,
&self.sort_span, &self.is_lint, &self.long_ty_path,
&&self.emitted_at];
::core::fmt::Formatter::debug_struct_fields_finish(f, "DiagInner",
names, values)
}
}Debug, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for DiagInner {
fn encode(&self, __encoder: &mut __E) {
match *self {
DiagInner {
level: ref __binding_0,
messages: ref __binding_1,
code: ref __binding_2,
lint_id: ref __binding_3,
span: ref __binding_4,
children: ref __binding_5,
suggestions: ref __binding_6,
args: ref __binding_7,
sort_span: ref __binding_8,
is_lint: ref __binding_9,
long_ty_path: ref __binding_10,
emitted_at: ref __binding_11 } => {
::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);
::rustc_serialize::Encodable::<__E>::encode(__binding_4,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_5,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_6,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_7,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_8,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_9,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_10,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_11,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for DiagInner {
fn decode(__decoder: &mut __D) -> Self {
DiagInner {
level: ::rustc_serialize::Decodable::decode(__decoder),
messages: ::rustc_serialize::Decodable::decode(__decoder),
code: ::rustc_serialize::Decodable::decode(__decoder),
lint_id: ::rustc_serialize::Decodable::decode(__decoder),
span: ::rustc_serialize::Decodable::decode(__decoder),
children: ::rustc_serialize::Decodable::decode(__decoder),
suggestions: ::rustc_serialize::Decodable::decode(__decoder),
args: ::rustc_serialize::Decodable::decode(__decoder),
sort_span: ::rustc_serialize::Decodable::decode(__decoder),
is_lint: ::rustc_serialize::Decodable::decode(__decoder),
long_ty_path: ::rustc_serialize::Decodable::decode(__decoder),
emitted_at: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
238pub struct DiagInner {
239 pub(crate) level: Level,
242
243 pub messages: Vec<(DiagMessage, Style)>,
244 pub code: Option<ErrCode>,
245 pub lint_id: Option<LintExpectationId>,
246 pub span: MultiSpan,
247 pub children: Vec<Subdiag>,
248 pub suggestions: Suggestions,
249 pub args: DiagArgMap,
250
251 pub sort_span: Span,
255
256 pub is_lint: Option<IsLint>,
257
258 pub long_ty_path: Option<PathBuf>,
259 pub emitted_at: DiagLocation,
262}
263
264impl DiagInner {
265 #[track_caller]
266 pub fn new<M: Into<DiagMessage>>(level: Level, message: M) -> Self {
267 DiagInner::new_with_messages(level, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(message.into(), Style::NoStyle)]))vec![(message.into(), Style::NoStyle)])
268 }
269
270 #[track_caller]
271 pub fn new_with_messages(level: Level, messages: Vec<(DiagMessage, Style)>) -> Self {
272 DiagInner {
273 level,
274 lint_id: None,
275 messages,
276 code: None,
277 span: MultiSpan::new(),
278 children: ::alloc::vec::Vec::new()vec![],
279 suggestions: Suggestions::Enabled(::alloc::vec::Vec::new()vec![]),
280 args: Default::default(),
281 sort_span: DUMMY_SP,
282 is_lint: None,
283 long_ty_path: None,
284 emitted_at: DiagLocation::caller(),
285 }
286 }
287
288 #[inline(always)]
289 pub fn level(&self) -> Level {
290 self.level
291 }
292
293 pub fn is_error(&self) -> bool {
294 match self.level {
295 Level::Bug | Level::Fatal | Level::Error | Level::DelayedBug => true,
296
297 Level::ForceWarning
298 | Level::Warning
299 | Level::Note
300 | Level::OnceNote
301 | Level::Help
302 | Level::OnceHelp
303 | Level::FailureNote
304 | Level::Allow
305 | Level::Expect => false,
306 }
307 }
308
309 pub(crate) fn has_future_breakage(&self) -> bool {
311 #[allow(non_exhaustive_omitted_patterns)] match self.is_lint {
Some(IsLint { has_future_breakage: true, .. }) => true,
_ => false,
}matches!(self.is_lint, Some(IsLint { has_future_breakage: true, .. }))
312 }
313
314 pub(crate) fn is_force_warn(&self) -> bool {
315 match self.level {
316 Level::ForceWarning => {
317 if !self.is_lint.is_some() {
::core::panicking::panic("assertion failed: self.is_lint.is_some()")
};assert!(self.is_lint.is_some());
318 true
319 }
320 _ => false,
321 }
322 }
323
324 pub(crate) fn sub(&mut self, level: Level, message: impl Into<DiagMessage>, span: MultiSpan) {
325 let sub = Subdiag { level, messages: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(message.into(), Style::NoStyle)]))vec![(message.into(), Style::NoStyle)], span };
326 self.children.push(sub);
327 }
328
329 pub(crate) fn arg(&mut self, name: impl Into<DiagArgName>, arg: impl IntoDiagArg) {
330 let name = name.into();
331 let value = arg.into_diag_arg(&mut self.long_ty_path);
332 if true {
if !(!self.args.contains_key(&name) ||
self.args.get(&name) == Some(&value)) {
{
::core::panicking::panic_fmt(format_args!("arg {0} already exists",
name));
}
};
};debug_assert!(
334 !self.args.contains_key(&name) || self.args.get(&name) == Some(&value),
335 "arg {} already exists",
336 name
337 );
338 self.args.insert(name, value);
339 }
340
341 pub fn remove_arg(&mut self, name: &str) {
342 self.args.swap_remove(name);
343 }
344
345 pub fn emitted_at_sub_diag(&self) -> Subdiag {
346 let track = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-Ztrack-diagnostics: created at {0}",
self.emitted_at))
})format!("-Ztrack-diagnostics: created at {}", self.emitted_at);
347 Subdiag {
348 level: crate::Level::Note,
349 messages: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(DiagMessage::Str(Cow::Owned(track)), Style::NoStyle)]))vec![(DiagMessage::Str(Cow::Owned(track)), Style::NoStyle)],
350 span: MultiSpan::new(),
351 }
352 }
353
354 fn keys(
356 &self,
357 ) -> (
358 &Level,
359 &[(DiagMessage, Style)],
360 &Option<ErrCode>,
361 &MultiSpan,
362 &[Subdiag],
363 &Suggestions,
364 Vec<(&DiagArgName, &DiagArgValue)>,
365 &Option<IsLint>,
366 ) {
367 (
368 &self.level,
369 &self.messages,
370 &self.code,
371 &self.span,
372 &self.children,
373 &self.suggestions,
374 self.args.iter().collect(),
375 &self.is_lint,
377 )
379 }
380}
381
382impl Hash for DiagInner {
383 fn hash<H>(&self, state: &mut H)
384 where
385 H: Hasher,
386 {
387 self.keys().hash(state);
388 }
389}
390
391impl PartialEq for DiagInner {
392 fn eq(&self, other: &Self) -> bool {
393 self.keys() == other.keys()
394 }
395}
396
397#[derive(#[automatically_derived]
impl ::core::clone::Clone for Subdiag {
#[inline]
fn clone(&self) -> Subdiag {
Subdiag {
level: ::core::clone::Clone::clone(&self.level),
messages: ::core::clone::Clone::clone(&self.messages),
span: ::core::clone::Clone::clone(&self.span),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Subdiag {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "Subdiag",
"level", &self.level, "messages", &self.messages, "span",
&&self.span)
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for Subdiag {
#[inline]
fn eq(&self, other: &Subdiag) -> bool {
self.level == other.level && self.messages == other.messages &&
self.span == other.span
}
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for Subdiag {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.level, state);
::core::hash::Hash::hash(&self.messages, state);
::core::hash::Hash::hash(&self.span, state)
}
}Hash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for Subdiag {
fn encode(&self, __encoder: &mut __E) {
match *self {
Subdiag {
level: ref __binding_0,
messages: ref __binding_1,
span: ref __binding_2 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for Subdiag {
fn decode(__decoder: &mut __D) -> Self {
Subdiag {
level: ::rustc_serialize::Decodable::decode(__decoder),
messages: ::rustc_serialize::Decodable::decode(__decoder),
span: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
400pub struct Subdiag {
401 pub level: Level,
402 pub messages: Vec<(DiagMessage, Style)>,
403 pub span: MultiSpan,
404}
405
406#[must_use]
419pub struct Diag<'a, G: EmissionGuarantee = ErrorGuaranteed> {
420 pub dcx: DiagCtxtHandle<'a>,
421
422 diag: Option<Box<DiagInner>>,
432
433 _marker: PhantomData<G>,
434}
435
436impl<G> !Clone for Diag<'_, G> {}
439
440const _: [(); 3 * size_of::<usize>()] =
[(); ::std::mem::size_of::<Diag<'_, ()>>()];rustc_data_structures::static_assert_size!(Diag<'_, ()>, 3 * size_of::<usize>());
441
442impl<G: EmissionGuarantee> Deref for Diag<'_, G> {
443 type Target = DiagInner;
444
445 fn deref(&self) -> &DiagInner {
446 self.diag.as_ref().unwrap()
447 }
448}
449
450impl<G: EmissionGuarantee> DerefMut for Diag<'_, G> {
451 fn deref_mut(&mut self) -> &mut DiagInner {
452 self.diag.as_mut().unwrap()
453 }
454}
455
456impl<G: EmissionGuarantee> Debug for Diag<'_, G> {
457 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
458 self.diag.fmt(f)
459 }
460}
461
462macro_rules! with_fn {
481 {
482 $with_f:ident,
483 $(#[$attrs:meta])*
484 pub fn $f:ident(&mut $self:ident, $($name:ident: $ty:ty),* $(,)?) -> &mut Self {
485 $($body:tt)*
486 }
487 } => {
488 $(#[$attrs])*
490 #[doc = concat!("See [`Diag::", stringify!($f), "()`].")]
491 pub fn $f(&mut $self, $($name: $ty),*) -> &mut Self {
492 $($body)*
493 }
494
495 $(#[$attrs])*
497 #[doc = concat!("See [`Diag::", stringify!($f), "()`].")]
498 pub fn $with_f(mut $self, $($name: $ty),*) -> Self {
499 $self.$f($($name),*);
500 $self
501 }
502 };
503}
504
505impl<'a, G: EmissionGuarantee> Diag<'a, G> {
506 #[track_caller]
507 pub fn new(dcx: DiagCtxtHandle<'a>, level: Level, message: impl Into<DiagMessage>) -> Self {
508 Self::new_diagnostic(dcx, DiagInner::new(level, message))
509 }
510
511 pub fn with_dcx(mut self, dcx: DiagCtxtHandle<'_>) -> Diag<'_, G> {
513 Diag { dcx, diag: self.diag.take(), _marker: PhantomData }
514 }
515
516 #[track_caller]
518 pub(crate) fn new_diagnostic(dcx: DiagCtxtHandle<'a>, diag: DiagInner) -> Self {
519 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_errors/src/diagnostic.rs:519",
"rustc_errors::diagnostic", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_errors/src/diagnostic.rs"),
::tracing_core::__macro_support::Option::Some(519u32),
::tracing_core::__macro_support::Option::Some("rustc_errors::diagnostic"),
::tracing_core::field::FieldSet::new(&["message"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Created new diagnostic")
as &dyn Value))])
});
} else { ; }
};debug!("Created new diagnostic");
520 Self { dcx, diag: Some(Box::new(diag)), _marker: PhantomData }
521 }
522
523 #[track_caller]
534 pub fn downgrade_to_delayed_bug(&mut self) {
535 if !#[allow(non_exhaustive_omitted_patterns)] match self.level {
Level::Error | Level::DelayedBug => true,
_ => false,
} {
{
::core::panicking::panic_fmt(format_args!("downgrade_to_delayed_bug: cannot downgrade {0:?} to DelayedBug: not an error",
self.level));
}
};assert!(
536 matches!(self.level, Level::Error | Level::DelayedBug),
537 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
538 self.level
539 );
540 self.level = Level::DelayedBug;
541 }
542
543 #[track_caller]
551 pub fn upgrade_to_fatal(mut self) -> Diag<'a, FatalAbort> {
552 if !#[allow(non_exhaustive_omitted_patterns)] match self.level {
Level::Error => true,
_ => false,
} {
{
::core::panicking::panic_fmt(format_args!("upgrade_to_fatal: cannot upgrade {0:?} to Fatal: not an error",
self.level));
}
};assert!(
553 matches!(self.level, Level::Error),
554 "upgrade_to_fatal: cannot upgrade {:?} to Fatal: not an error",
555 self.level
556 );
557 self.level = Level::Fatal;
558
559 let diag = self.diag.take();
562 Diag { dcx: self.dcx, diag, _marker: PhantomData }
563 }
564
565 "See [`Diag::span_label()`]."
&mut Self
self
span
label
&mut Self
"See [`Diag::span_label()`]."
mut self
span
label
Self
self.span_label(span, label);
self;with_fn! { with_span_label,
566 pub fn span_label(&mut self, span: Span, label: impl Into<DiagMessage>) -> &mut Self {
579 self.span.push_span_label(span, label.into());
580 self
581 } }
582
583 "See [`Diag::span_labels()`]."
&mut Self
self
spans
label
&mut Self
"See [`Diag::span_labels()`]."
mut self
spans
label
Self
self.span_labels(spans, label);
self;with_fn! { with_span_labels,
584 pub fn span_labels(&mut self, spans: impl IntoIterator<Item = Span>, label: &str) -> &mut Self {
587 for span in spans {
588 self.span_label(span, label.to_string());
589 }
590 self
591 } }
592
593 pub fn replace_span_with(&mut self, after: Span, keep_label: bool) -> &mut Self {
594 let before = self.span.clone();
595 self.span(after);
596 for span_label in before.span_labels() {
597 if let Some(label) = span_label.label {
598 if span_label.is_primary && keep_label {
599 self.span.push_span_label(after, label);
600 } else {
601 self.span.push_span_label(span_label.span, label);
602 }
603 }
604 }
605 self
606 }
607
608 pub fn note_expected_found(
609 &mut self,
610 expected_label: &str,
611 expected: DiagStyledString,
612 found_label: &str,
613 found: DiagStyledString,
614 ) -> &mut Self {
615 self.note_expected_found_extra(
616 expected_label,
617 expected,
618 found_label,
619 found,
620 DiagStyledString::normal(""),
621 DiagStyledString::normal(""),
622 )
623 }
624
625 pub fn note_expected_found_extra(
626 &mut self,
627 expected_label: &str,
628 expected: DiagStyledString,
629 found_label: &str,
630 found: DiagStyledString,
631 expected_extra: DiagStyledString,
632 found_extra: DiagStyledString,
633 ) -> &mut Self {
634 let expected_label = expected_label.to_string();
635 let expected_label = if expected_label.is_empty() {
636 "expected".to_string()
637 } else {
638 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}", expected_label))
})format!("expected {expected_label}")
639 };
640 let found_label = found_label.to_string();
641 let found_label = if found_label.is_empty() {
642 "found".to_string()
643 } else {
644 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("found {0}", found_label))
})format!("found {found_label}")
645 };
646 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
647 (expected_label.len() - found_label.len(), 0)
648 } else {
649 (0, found_label.len() - expected_label.len())
650 };
651 let mut msg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[StringPart::normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1} `",
" ".repeat(expected_padding), expected_label))
}))]))vec![StringPart::normal(format!(
652 "{}{} `",
653 " ".repeat(expected_padding),
654 expected_label
655 ))];
656 msg.extend(expected.0);
657 msg.push(StringPart::normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("`")) })format!("`")));
658 msg.extend(expected_extra.0);
659 msg.push(StringPart::normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("\n")) })format!("\n")));
660 msg.push(StringPart::normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1} `",
" ".repeat(found_padding), found_label))
})format!("{}{} `", " ".repeat(found_padding), found_label)));
661 msg.extend(found.0);
662 msg.push(StringPart::normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("`")) })format!("`")));
663 msg.extend(found_extra.0);
664
665 self.highlighted_note(msg);
667 self
668 }
669
670 pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
671 self.highlighted_note(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[StringPart::normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` from trait: `",
name))
})), StringPart::highlighted(signature),
StringPart::normal("`")]))vec![
672 StringPart::normal(format!("`{name}` from trait: `")),
673 StringPart::highlighted(signature),
674 StringPart::normal("`"),
675 ]);
676 self
677 }
678
679 "See [`Diag::note()`]."
&mut Self
self
msg
&mut Self
"See [`Diag::note()`]."
mut self
msg
Self
self.note(msg);
self;with_fn! { with_note,
680 pub fn note(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
682 self.sub(Level::Note, msg, MultiSpan::new());
683 self
684 } }
685
686 pub fn highlighted_note(&mut self, msg: Vec<StringPart>) -> &mut Self {
687 self.sub_with_highlights(Level::Note, msg, MultiSpan::new());
688 self
689 }
690
691 pub fn highlighted_span_note(
692 &mut self,
693 span: impl Into<MultiSpan>,
694 msg: Vec<StringPart>,
695 ) -> &mut Self {
696 self.sub_with_highlights(Level::Note, msg, span.into());
697 self
698 }
699
700 pub fn note_once(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
702 self.sub(Level::OnceNote, msg, MultiSpan::new());
703 self
704 }
705
706 "See [`Diag::span_note()`]."
&mut Self
self
sp
msg
&mut Self
"See [`Diag::span_note()`]."
mut self
sp
msg
Self
self.span_note(sp, msg);
self;with_fn! { with_span_note,
707 pub fn span_note(
710 &mut self,
711 sp: impl Into<MultiSpan>,
712 msg: impl Into<DiagMessage>,
713 ) -> &mut Self {
714 self.sub(Level::Note, msg, sp.into());
715 self
716 } }
717
718 pub fn span_note_once<S: Into<MultiSpan>>(
721 &mut self,
722 sp: S,
723 msg: impl Into<DiagMessage>,
724 ) -> &mut Self {
725 self.sub(Level::OnceNote, msg, sp.into());
726 self
727 }
728
729 "See [`Diag::warn()`]."
&mut Self
self
msg
&mut Self
"See [`Diag::warn()`]."
mut self
msg
Self
self.warn(msg);
self;with_fn! { with_warn,
730 pub fn warn(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
732 self.sub(Level::Warning, msg, MultiSpan::new());
733 self
734 } }
735
736 pub fn span_warn<S: Into<MultiSpan>>(
739 &mut self,
740 sp: S,
741 msg: impl Into<DiagMessage>,
742 ) -> &mut Self {
743 self.sub(Level::Warning, msg, sp.into());
744 self
745 }
746
747 "See [`Diag::help()`]."
&mut Self
self
msg
&mut Self
"See [`Diag::help()`]."
mut self
msg
Self
self.help(msg);
self;with_fn! { with_help,
748 pub fn help(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
750 self.sub(Level::Help, msg, MultiSpan::new());
751 self
752 } }
753
754 pub fn help_once(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
756 self.sub(Level::OnceHelp, msg, MultiSpan::new());
757 self
758 }
759
760 pub fn highlighted_help(&mut self, msg: Vec<StringPart>) -> &mut Self {
762 self.sub_with_highlights(Level::Help, msg, MultiSpan::new());
763 self
764 }
765
766 pub fn highlighted_span_help(
768 &mut self,
769 span: impl Into<MultiSpan>,
770 msg: Vec<StringPart>,
771 ) -> &mut Self {
772 self.sub_with_highlights(Level::Help, msg, span.into());
773 self
774 }
775
776 "See [`Diag::span_help()`]."
&mut Self
self
sp
msg
&mut Self
"See [`Diag::span_help()`]."
mut self
sp
msg
Self
self.span_help(sp, msg);
self;with_fn! { with_span_help,
777 pub fn span_help(
780 &mut self,
781 sp: impl Into<MultiSpan>,
782 msg: impl Into<DiagMessage>,
783 ) -> &mut Self {
784 self.sub(Level::Help, msg, sp.into());
785 self
786 } }
787
788 pub fn disable_suggestions(&mut self) -> &mut Self {
792 self.suggestions = Suggestions::Disabled;
793 self
794 }
795
796 pub fn seal_suggestions(&mut self) -> &mut Self {
801 if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
802 let suggestions_slice = std::mem::take(suggestions).into_boxed_slice();
803 self.suggestions = Suggestions::Sealed(suggestions_slice);
804 }
805 self
806 }
807
808 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
813 for subst in &suggestion.substitutions {
814 for part in &subst.parts {
815 let span = part.span;
816 let call_site = span.ctxt().outer_expn_data().call_site;
817 if span.in_derive_expansion() && span.overlaps_or_adjacent(call_site) {
818 return;
820 }
821 }
822 }
823
824 if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
825 suggestions.push(suggestion);
826 }
827 }
828
829 "See [`Diag::multipart_suggestion()`]."
&mut Self
self
msg
suggestion
applicability
&mut Self
"See [`Diag::multipart_suggestion()`]."
mut self
msg
suggestion
applicability
Self
self.multipart_suggestion(msg, suggestion, applicability);
self;with_fn! { with_multipart_suggestion,
830 pub fn multipart_suggestion(
833 &mut self,
834 msg: impl Into<DiagMessage>,
835 suggestion: Vec<(Span, String)>,
836 applicability: Applicability,
837 ) -> &mut Self {
838 self.multipart_suggestion_with_style(
839 msg,
840 suggestion,
841 applicability,
842 SuggestionStyle::ShowAlways,
843 )
844 } }
845
846 pub fn multipart_suggestion_with_style(
848 &mut self,
849 msg: impl Into<DiagMessage>,
850 mut suggestion: Vec<(Span, String)>,
851 applicability: Applicability,
852 style: SuggestionStyle,
853 ) -> &mut Self {
854 let mut seen = crate::FxHashSet::default();
855 suggestion.retain(|(span, msg)| seen.insert((span.lo(), span.hi(), msg.clone())));
856
857 let parts = suggestion
858 .into_iter()
859 .map(|(span, snippet)| SubstitutionPart { snippet, span })
860 .collect::<Vec<_>>();
861
862 if !!parts.is_empty() {
::core::panicking::panic("assertion failed: !parts.is_empty()")
};assert!(!parts.is_empty());
863 if true {
match (&parts.iter().find(|part|
part.span.is_empty() && part.snippet.is_empty()), &None) {
(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::Some(format_args!("Span must not be empty and have no suggestion")));
}
}
};
};debug_assert_eq!(
864 parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()),
865 None,
866 "Span must not be empty and have no suggestion",
867 );
868 if true {
match (&parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
&None) {
(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::Some(format_args!("suggestion must not have overlapping parts")));
}
}
};
};debug_assert_eq!(
869 parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
870 None,
871 "suggestion must not have overlapping parts",
872 );
873
874 self.push_suggestion(CodeSuggestion {
875 substitutions: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Substitution { parts }]))vec![Substitution { parts }],
876 msg: msg.into(),
877 style,
878 applicability,
879 });
880 self
881 }
882
883 pub fn tool_only_multipart_suggestion(
890 &mut self,
891 msg: impl Into<DiagMessage>,
892 suggestion: Vec<(Span, String)>,
893 applicability: Applicability,
894 ) -> &mut Self {
895 self.multipart_suggestion_with_style(
896 msg,
897 suggestion,
898 applicability,
899 SuggestionStyle::CompletelyHidden,
900 )
901 }
902
903 "See [`Diag::span_suggestion()`]."
&mut Self
self
sp
msg
suggestion
applicability
&mut Self
"See [`Diag::span_suggestion()`]."
mut self
sp
msg
suggestion
applicability
Self
self.span_suggestion(sp, msg, suggestion, applicability);
self;with_fn! { with_span_suggestion,
904 pub fn span_suggestion(
922 &mut self,
923 sp: Span,
924 msg: impl Into<DiagMessage>,
925 suggestion: impl ToString,
926 applicability: Applicability,
927 ) -> &mut Self {
928 self.span_suggestion_with_style(
929 sp,
930 msg,
931 suggestion,
932 applicability,
933 SuggestionStyle::ShowCode,
934 );
935 self
936 } }
937
938 "See [`Diag::span_suggestion_with_style()`]."
&mut Self
self
sp
msg
suggestion
applicability
style
&mut Self
if true {
if !!(sp.is_empty() && suggestion.to_string().is_empty()) {
{
::core::panicking::panic_fmt(format_args!("Span must not be empty and have no suggestion"));
}
};
};
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Substitution {
parts: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[SubstitutionPart {
snippet: suggestion.to_string(),
span: sp,
}])),
}]))
"See [`Diag::span_suggestion_with_style()`]."
mut self
sp
msg
suggestion
applicability
style
Self
self.span_suggestion_with_style(sp, msg, suggestion, applicability, style);
self;with_fn! { with_span_suggestion_with_style,
939 pub fn span_suggestion_with_style(
941 &mut self,
942 sp: Span,
943 msg: impl Into<DiagMessage>,
944 suggestion: impl ToString,
945 applicability: Applicability,
946 style: SuggestionStyle,
947 ) -> &mut Self {
948 debug_assert!(
949 !(sp.is_empty() && suggestion.to_string().is_empty()),
950 "Span must not be empty and have no suggestion"
951 );
952 self.push_suggestion(CodeSuggestion {
953 substitutions: vec![Substitution {
954 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
955 }],
956 msg: msg.into(),
957 style,
958 applicability,
959 });
960 self
961 } }
962
963 "See [`Diag::span_suggestion_verbose()`]."
&mut Self
self
sp
msg
suggestion
applicability
&mut Self
"See [`Diag::span_suggestion_verbose()`]."
mut self
sp
msg
suggestion
applicability
Self
self.span_suggestion_verbose(sp, msg, suggestion, applicability);
self;with_fn! { with_span_suggestion_verbose,
964 pub fn span_suggestion_verbose(
966 &mut self,
967 sp: Span,
968 msg: impl Into<DiagMessage>,
969 suggestion: impl ToString,
970 applicability: Applicability,
971 ) -> &mut Self {
972 self.span_suggestion_with_style(
973 sp,
974 msg,
975 suggestion,
976 applicability,
977 SuggestionStyle::ShowAlways,
978 );
979 self
980 } }
981
982 "See [`Diag::span_suggestions()`]."
&mut Self
self
sp
msg
suggestions
applicability
&mut Self
"See [`Diag::span_suggestions()`]."
mut self
sp
msg
suggestions
applicability
Self
self.span_suggestions(sp, msg, suggestions, applicability);
self;with_fn! { with_span_suggestions,
983 pub fn span_suggestions(
986 &mut self,
987 sp: Span,
988 msg: impl Into<DiagMessage>,
989 suggestions: impl IntoIterator<Item = String>,
990 applicability: Applicability,
991 ) -> &mut Self {
992 self.span_suggestions_with_style(
993 sp,
994 msg,
995 suggestions,
996 applicability,
997 SuggestionStyle::ShowCode,
998 )
999 } }
1000
1001 pub fn span_suggestions_with_style(
1002 &mut self,
1003 sp: Span,
1004 msg: impl Into<DiagMessage>,
1005 suggestions: impl IntoIterator<Item = String>,
1006 applicability: Applicability,
1007 style: SuggestionStyle,
1008 ) -> &mut Self {
1009 let substitutions = suggestions
1010 .into_iter()
1011 .map(|snippet| {
1012 if true {
if !!(sp.is_empty() && snippet.is_empty()) {
{
::core::panicking::panic_fmt(format_args!("Span `{0:?}` must not be empty and have no suggestion",
sp));
}
};
};debug_assert!(
1013 !(sp.is_empty() && snippet.is_empty()),
1014 "Span `{sp:?}` must not be empty and have no suggestion"
1015 );
1016 Substitution { parts: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[SubstitutionPart { snippet, span: sp }]))vec![SubstitutionPart { snippet, span: sp }] }
1017 })
1018 .collect();
1019 self.push_suggestion(CodeSuggestion {
1020 substitutions,
1021 msg: msg.into(),
1022 style,
1023 applicability,
1024 });
1025 self
1026 }
1027
1028 pub fn multipart_suggestions(
1032 &mut self,
1033 msg: impl Into<DiagMessage>,
1034 suggestions: impl IntoIterator<Item = Vec<(Span, String)>>,
1035 applicability: Applicability,
1036 ) -> &mut Self {
1037 let substitutions = suggestions
1038 .into_iter()
1039 .map(|sugg| {
1040 let mut parts = sugg
1041 .into_iter()
1042 .map(|(span, snippet)| SubstitutionPart { snippet, span })
1043 .collect::<Vec<_>>();
1044
1045 parts.sort_unstable_by_key(|part| part.span);
1046
1047 if !!parts.is_empty() {
::core::panicking::panic("assertion failed: !parts.is_empty()")
};assert!(!parts.is_empty());
1048 if true {
match (&parts.iter().find(|part|
part.span.is_empty() && part.snippet.is_empty()), &None) {
(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::Some(format_args!("Span must not be empty and have no suggestion")));
}
}
};
};debug_assert_eq!(
1049 parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()),
1050 None,
1051 "Span must not be empty and have no suggestion",
1052 );
1053 if true {
match (&parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
&None) {
(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::Some(format_args!("suggestion must not have overlapping parts")));
}
}
};
};debug_assert_eq!(
1054 parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
1055 None,
1056 "suggestion must not have overlapping parts",
1057 );
1058
1059 Substitution { parts }
1060 })
1061 .collect();
1062
1063 self.push_suggestion(CodeSuggestion {
1064 substitutions,
1065 msg: msg.into(),
1066 style: SuggestionStyle::ShowAlways,
1067 applicability,
1068 });
1069 self
1070 }
1071
1072 "See [`Diag::span_suggestion_short()`]."
&mut Self
self
sp
msg
suggestion
applicability
&mut Self
"See [`Diag::span_suggestion_short()`]."
mut self
sp
msg
suggestion
applicability
Self
self.span_suggestion_short(sp, msg, suggestion, applicability);
self;with_fn! { with_span_suggestion_short,
1073 pub fn span_suggestion_short(
1078 &mut self,
1079 sp: Span,
1080 msg: impl Into<DiagMessage>,
1081 suggestion: impl ToString,
1082 applicability: Applicability,
1083 ) -> &mut Self {
1084 self.span_suggestion_with_style(
1085 sp,
1086 msg,
1087 suggestion,
1088 applicability,
1089 SuggestionStyle::HideCodeInline,
1090 );
1091 self
1092 } }
1093
1094 pub fn span_suggestion_hidden(
1101 &mut self,
1102 sp: Span,
1103 msg: impl Into<DiagMessage>,
1104 suggestion: impl ToString,
1105 applicability: Applicability,
1106 ) -> &mut Self {
1107 self.span_suggestion_with_style(
1108 sp,
1109 msg,
1110 suggestion,
1111 applicability,
1112 SuggestionStyle::HideCodeAlways,
1113 );
1114 self
1115 }
1116
1117 "See [`Diag::tool_only_span_suggestion()`]."
&mut Self
self
sp
msg
suggestion
applicability
&mut Self
"See [`Diag::tool_only_span_suggestion()`]."
mut self
sp
msg
suggestion
applicability
Self
self.tool_only_span_suggestion(sp, msg, suggestion, applicability);
self;with_fn! { with_tool_only_span_suggestion,
1118 pub fn tool_only_span_suggestion(
1123 &mut self,
1124 sp: Span,
1125 msg: impl Into<DiagMessage>,
1126 suggestion: impl ToString,
1127 applicability: Applicability,
1128 ) -> &mut Self {
1129 self.span_suggestion_with_style(
1130 sp,
1131 msg,
1132 suggestion,
1133 applicability,
1134 SuggestionStyle::CompletelyHidden,
1135 );
1136 self
1137 } }
1138
1139 pub fn subdiagnostic(&mut self, subdiagnostic: impl Subdiagnostic) -> &mut Self {
1144 subdiagnostic.add_to_diag(self);
1145 self
1146 }
1147
1148 "See [`Diag::span()`]."
&mut Self
self
sp
&mut Self
"See [`Diag::span()`]."
mut self
sp
Self
self.span(sp);
self;with_fn! { with_span,
1149 pub fn span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self {
1151 self.span = sp.into();
1152 if let Some(span) = self.span.primary_span() {
1153 self.sort_span = span;
1154 }
1155 self
1156 } }
1157
1158 pub fn is_lint(&mut self, name: String, has_future_breakage: bool) -> &mut Self {
1159 self.is_lint = Some(IsLint { name, has_future_breakage });
1160 self
1161 }
1162
1163 "See [`Diag::code()`]."
&mut Self
self
code
&mut Self
"See [`Diag::code()`]."
mut self
code
Self
self.code(code);
self;with_fn! { with_code,
1164 pub fn code(&mut self, code: ErrCode) -> &mut Self {
1166 self.code = Some(code);
1167 self
1168 } }
1169
1170 "See [`Diag::lint_id()`]."
&mut Self
self
id
&mut Self
"See [`Diag::lint_id()`]."
mut self
id
Self
self.lint_id(id);
self;with_fn! { with_lint_id,
1171 pub fn lint_id(
1173 &mut self,
1174 id: LintExpectationId,
1175 ) -> &mut Self {
1176 self.lint_id = Some(id);
1177 self
1178 } }
1179
1180 "See [`Diag::primary_message()`]."
&mut Self
self
msg
&mut Self
"See [`Diag::primary_message()`]."
mut self
msg
Self
self.primary_message(msg);
self;with_fn! { with_primary_message,
1181 pub fn primary_message(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
1183 self.messages[0] = (msg.into(), Style::NoStyle);
1184 self
1185 } }
1186
1187 "See [`Diag::arg()`]."
&mut Self
self
name
arg
&mut Self
"See [`Diag::arg()`]."
mut self
name
arg
Self
self.arg(name, arg);
self;with_fn! { with_arg,
1188 pub fn arg(
1190 &mut self,
1191 name: impl Into<DiagArgName>,
1192 arg: impl IntoDiagArg,
1193 ) -> &mut Self {
1194 self.deref_mut().arg(name, arg);
1195 self
1196 } }
1197
1198 pub fn sub(&mut self, level: Level, message: impl Into<DiagMessage>, span: MultiSpan) {
1203 self.deref_mut().sub(level, message, span);
1204 }
1205
1206 fn sub_with_highlights(&mut self, level: Level, messages: Vec<StringPart>, span: MultiSpan) {
1209 let messages = messages.into_iter().map(|m| (m.content.into(), m.style)).collect();
1210 let sub = Subdiag { level, messages, span };
1211 self.children.push(sub);
1212 }
1213
1214 fn take_diag(&mut self) -> DiagInner {
1218 if let Some(path) = &self.long_ty_path {
1219 self.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the full name for the type has been written to \'{0}\'",
path.display()))
})format!(
1220 "the full name for the type has been written to '{}'",
1221 path.display()
1222 ));
1223 self.note("consider using `--verbose` to print the full type name to the console");
1224 }
1225 *self.diag.take().unwrap()
1226 }
1227
1228 pub fn long_ty_path(&mut self) -> &mut Option<PathBuf> {
1246 &mut self.long_ty_path
1247 }
1248
1249 pub fn with_long_ty_path(mut self, long_ty_path: Option<PathBuf>) -> Self {
1250 self.long_ty_path = long_ty_path;
1251 self
1252 }
1253
1254 fn emit_producing_nothing(mut self) {
1256 let diag = self.take_diag();
1257 self.dcx.emit_diagnostic(diag);
1258 }
1259
1260 fn emit_producing_error_guaranteed(mut self) -> ErrorGuaranteed {
1262 let diag = self.take_diag();
1263
1264 if !#[allow(non_exhaustive_omitted_patterns)] match diag.level {
Level::Error | Level::DelayedBug => true,
_ => false,
} {
{
::core::panicking::panic_fmt(format_args!("invalid diagnostic level ({0:?})",
diag.level));
}
};assert!(
1273 matches!(diag.level, Level::Error | Level::DelayedBug),
1274 "invalid diagnostic level ({:?})",
1275 diag.level,
1276 );
1277
1278 let guar = self.dcx.emit_diagnostic(diag);
1279 guar.unwrap()
1280 }
1281
1282 #[track_caller]
1284 pub fn emit(self) -> G::EmitResult {
1285 G::emit_producing_guarantee(self)
1286 }
1287
1288 #[track_caller]
1293 pub fn emit_unless_delay(mut self, delay: bool) -> G::EmitResult {
1294 if delay {
1295 self.downgrade_to_delayed_bug();
1296 }
1297 self.emit()
1298 }
1299
1300 pub fn cancel(mut self) {
1303 self.diag = None;
1304 drop(self);
1305 }
1306
1307 pub fn cancel_into_message(self) -> Option<String> {
1309 let s = self.diag.as_ref()?.messages.get(0)?.0.as_str().map(ToString::to_string);
1310 self.cancel();
1311 s
1312 }
1313
1314 pub fn stash(mut self, span: Span, key: StashKey) -> Option<ErrorGuaranteed> {
1316 let diag = self.take_diag();
1317 self.dcx.stash_diagnostic(span, key, diag)
1318 }
1319
1320 #[track_caller]
1331 pub fn delay_as_bug(mut self) -> G::EmitResult {
1332 self.downgrade_to_delayed_bug();
1333 self.emit()
1334 }
1335}
1336
1337impl<G: EmissionGuarantee> Drop for Diag<'_, G> {
1340 fn drop(&mut self) {
1341 match self.diag.take() {
1342 Some(diag) if !panicking() => {
1343 self.dcx.emit_diagnostic(DiagInner::new(
1344 Level::Bug,
1345 DiagMessage::from("the following error was constructed but not emitted"),
1346 ));
1347 self.dcx.emit_diagnostic(*diag);
1348 {
::core::panicking::panic_fmt(format_args!("error was constructed but not emitted"));
};panic!("error was constructed but not emitted");
1349 }
1350 _ => {}
1351 }
1352 }
1353}
1354
1355#[macro_export]
1356macro_rules! struct_span_code_err {
1357 ($dcx:expr, $span:expr, $code:expr, $($message:tt)*) => ({
1358 $dcx.struct_span_err($span, format!($($message)*)).with_code($code)
1359 })
1360}