1use std::borrow::Cow;
2use std::fmt::{self, Debug};
3use std::hash::Hash;
4use std::ops::{Deref, DerefMut};
5use std::panic;
6use std::path::PathBuf;
7use std::thread::panicking;
89use rustc_ast::attr::version::RustcVersion;
10use rustc_data_structures::stable_hash::StableHasher;
11use rustc_error_messages::{DiagArgMap, DiagArgName, IntoDiagArg};
12use rustc_hashes::Hash128;
13use rustc_lint_defs::Applicability;
14use rustc_macros::{Decodable, Encodable};
15use rustc_span::{Span, Spanned, Symbol};
16use tracing::debug;
1718use crate::{
19CodeSuggestion, DiagCtxtHandle, DiagMessage, ErrCode, ErrorGuaranteed, ExplicitBug, Level,
20MultiSpan, StashKey, Style, Sublevel, Substitution, SubstitutionPart, SuggestionStyle,
21Suggestions,
22};
2324/// Trait implemented by error types. This is rarely implemented manually. Instead, use
25/// `#[derive(Diagnostic)]` -- see [rustc_macros::Diagnostic].
26pub trait Diagnostic<'a> {
27/// Write out as a diagnostic out of `DiagCtxt`.
28#[must_use]
29 #[track_caller]
30fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a>;
31}
3233impl<'a, T> Diagnostic<'a> for Spanned<T>
34where
35T: Diagnostic<'a>,
36{
37fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
38self.node.into_diag(dcx, level).with_span(self.span)
39 }
40}
4142/// Type used to emit diagnostic through a closure instead of implementing the `Diagnostic` trait.
43pub struct DiagDecorator<F: FnOnce(&mut Diag<'_>)>(pub F);
4445impl<'a, F: FnOnce(&mut Diag<'_>)> Diagnostic<'a> for DiagDecorator<F> {
46fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
47let mut diag = Diag::new(dcx, level, "");
48 (self.0)(&mut diag);
49diag50 }
51}
5253/// Trait implemented by error types. This should not be implemented manually. Instead, use
54/// `#[derive(Subdiagnostic)]` -- see [rustc_macros::Subdiagnostic].
55pub trait Subdiagnostic {
56/// Add a subdiagnostic to an existing diagnostic.
57fn add_to_diag(self, diag: &mut Diag<'_>);
58}
5960#[derive(#[automatically_derived]
impl ::core::clone::Clone for DiagLocation {
#[inline]
fn clone(&self) -> Self {
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) {
let DiagLocation {
file: ref __binding_0,
line: ref __binding_1,
col: ref __binding_2 } = *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);
}
}
};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)]
61pub struct DiagLocation {
62 file: Cow<'static, str>,
63 line: u32,
64 col: u32,
65}
6667impl DiagLocation {
68pub fn from_location(loc: &'static panic::Location<'static>) -> Self {
69DiagLocation { file: loc.file().into(), line: loc.line(), col: loc.column() }
70 }
7172#[track_caller]
73pub fn caller() -> Self {
74Self::from_location(panic::Location::caller())
75 }
76}
7778impl fmt::Displayfor DiagLocation {
79fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80f.write_fmt(format_args!("{0}:{1}:{2}", self.file, self.line, self.col))write!(f, "{}:{}:{}", self.file, self.line, self.col)81 }
82}
8384#[derive(#[automatically_derived]
impl ::core::clone::Clone for IsLint {
#[inline]
fn clone(&self) -> Self {
IsLint {
name: ::core::clone::Clone::clone(&self.name),
has_future_breakage: ::core::clone::Clone::clone(&self.has_future_breakage),
rust_version: ::core::clone::Clone::clone(&self.rust_version),
}
}
}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_field3_finish(f, "IsLint",
"name", &self.name, "has_future_breakage",
&self.has_future_breakage, "rust_version", &&self.rust_version)
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for IsLint { }
#[automatically_derived]
impl ::core::cmp::PartialEq for IsLint {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.has_future_breakage == other.has_future_breakage &&
self.name == other.name &&
self.rust_version == other.rust_version
}
}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>;
let _: ::core::cmp::AssertParamIsEq<Option<RustcVersion>>;
}
}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);
::core::hash::Hash::hash(&self.rust_version, state)
}
}Hash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for IsLint {
fn encode(&self, __encoder: &mut __E) {
let IsLint {
name: ref __binding_0,
has_future_breakage: ref __binding_1,
rust_version: ref __binding_2 } = *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);
}
}
};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),
rust_version: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
85pub struct IsLint {
86/// The lint name.
87pub(crate) name: String,
88/// Indicates whether this lint should show up in cargo's future breakage report.
89has_future_breakage: bool,
90/// Indicates the minimum rust version this lint applies to
91rust_version: Option<RustcVersion>,
92}
9394#[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::marker::StructuralPartialEq for DiagStyledString { }
#[automatically_derived]
impl ::core::cmp::PartialEq for DiagStyledString {
#[inline]
fn eq(&self, other: &Self) -> 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)]
95pub struct DiagStyledString(pub Vec<StringPart>);
9697impl DiagStyledString {
98pub fn new() -> DiagStyledString {
99DiagStyledString(::alloc::vec::Vec::new()vec![])
100 }
101pub fn push_normal<S: Into<String>>(&mut self, t: S) {
102self.0.push(StringPart::normal(t));
103 }
104pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
105self.0.push(StringPart::highlighted(t));
106 }
107pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
108if highlight {
109self.push_highlighted(t);
110 } else {
111self.push_normal(t);
112 }
113 }
114pub fn normal<S: Into<String>>(t: S) -> DiagStyledString {
115DiagStyledString(::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)])
116 }
117118pub fn highlighted<S: Into<String>>(t: S) -> DiagStyledString {
119DiagStyledString(::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)])
120 }
121122pub fn content(&self) -> String {
123self.0.iter().map(|x| x.content.as_str()).collect::<String>()
124 }
125126/// Merge segments of the same style.
127pub fn compact(&mut self) {
128let segments = std::mem::take(&mut self.0);
129let mut iter = segments.into_iter();
130let Some(mut prev) = iter.next() else { return };
131while let Some(segment) = iter.next() {
132if prev.style == segment.style {
133 prev.content.push_str(&segment.content);
134 } else {
135self.0.push(prev);
136 prev = segment;
137 }
138 }
139self.0.push(prev);
140 }
141142/// Remove the middle of all long segments for shorter rendering.
143pub fn shorten(&mut self) {
144self.compact();
145/// The marker for removed text.
146const ELLIPSIS: &str = "...";
147/// How many chars at the start and end will remain.
148const PADDING: usize = 6;
149/// The distance after which it is not worth it to reduce the text.
150const DELTA: usize = 3;
151152for segment in self.0.iter_mut() {
153let char_len = segment.content.chars().count();
154if char_len > PADDING * 2 + ELLIPSIS.chars().count() + DELTA
155 && let Some((left, _)) = segment.content.char_indices().nth(PADDING)
156 && let Some((right, _)) = segment.content.char_indices().nth(char_len - PADDING)
157 {
158 segment.content.replace_range(left..right, ELLIPSIS);
159 }
160 }
161 }
162}
163164#[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::marker::StructuralPartialEq for StringPart { }
#[automatically_derived]
impl ::core::cmp::PartialEq for StringPart {
#[inline]
fn eq(&self, other: &Self) -> 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)]
165pub struct StringPart {
166 content: String,
167 style: Style,
168}
169170impl StringPart {
171pub fn normal<S: Into<String>>(content: S) -> StringPart {
172StringPart { content: content.into(), style: Style::NoStyle }
173 }
174175pub fn highlighted<S: Into<String>>(content: S) -> StringPart {
176StringPart { content: content.into(), style: Style::Highlight }
177 }
178}
179180/// The main part of a diagnostic. Note that `Diag`, which wraps this type, is
181/// used for most operations, and should be used instead whenever possible.
182/// This type should only be used when `Diag`'s lifetime causes difficulties,
183/// e.g. when storing diagnostics within `DiagCtxt`.
184#[must_use]
185#[derive(#[automatically_derived]
impl ::core::clone::Clone for DiagInner {
#[inline]
fn clone(&self) -> Self {
DiagInner {
level: ::core::clone::Clone::clone(&self.level),
messages: ::core::clone::Clone::clone(&self.messages),
code: ::core::clone::Clone::clone(&self.code),
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),
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", "span", "children", "suggestions",
"args", "is_lint", "long_ty_path", "emitted_at"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.level, &self.messages, &self.code, &self.span,
&self.children, &self.suggestions, &self.args,
&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) {
let DiagInner {
level: ref __binding_0,
messages: ref __binding_1,
code: ref __binding_2,
span: ref __binding_3,
children: ref __binding_4,
suggestions: ref __binding_5,
args: ref __binding_6,
is_lint: ref __binding_7,
long_ty_path: ref __binding_8,
emitted_at: ref __binding_9 } = *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);
::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);
}
}
};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),
span: ::rustc_serialize::Decodable::decode(__decoder),
children: ::rustc_serialize::Decodable::decode(__decoder),
suggestions: ::rustc_serialize::Decodable::decode(__decoder),
args: ::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)]
186pub struct DiagInner {
187// NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
188 // outside of what methods in this crate themselves allow.
189pub(crate) level: Level,
190191pub messages: Vec<(DiagMessage, Style)>,
192pub code: Option<ErrCode>,
193pub span: MultiSpan,
194pub children: Vec<Subdiag>,
195pub suggestions: Suggestions,
196pub args: DiagArgMap,
197pub is_lint: Option<IsLint>,
198pub long_ty_path: Option<PathBuf>,
199/// With `-Ztrack_diagnostics` enabled,
200 /// we print where in rustc this error was emitted.
201pub emitted_at: DiagLocation,
202}
203204impl DiagInner {
205#[track_caller]
206pub fn new<M: Into<DiagMessage>>(level: Level, message: M) -> Self {
207DiagInner::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)])
208 }
209210#[track_caller]
211pub fn new_with_messages(level: Level, messages: Vec<(DiagMessage, Style)>) -> Self {
212DiagInner {
213level,
214messages,
215 code: None,
216 span: MultiSpan::new(),
217 children: ::alloc::vec::Vec::new()vec![],
218 suggestions: Suggestions::Enabled(::alloc::vec::Vec::new()vec![]),
219 args: Default::default(),
220 is_lint: None,
221 long_ty_path: None,
222 emitted_at: DiagLocation::caller(),
223 }
224 }
225226#[inline(always)]
227pub fn level(&self) -> Level {
228self.level
229 }
230231pub fn is_error(&self) -> bool {
232match self.level {
233 Level::Bug | Level::Fatal | Level::Error | Level::DelayedBug => true,
234235 Level::Warning(_) | Level::Note | Level::Help | Level::FailureNote => false,
236 }
237 }
238239/// Indicates whether this diagnostic should show up in cargo's future breakage report.
240pub(crate) fn has_future_breakage(&self) -> bool {
241#[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, .. }))242 }
243244/// Indicates the minimum rust version this lint applies to.
245pub(crate) fn rust_version(&self) -> Option<RustcVersion> {
246self.is_lint.as_ref().and_then(|is| is.rust_version)
247 }
248249pub(crate) fn sub(
250&mut self,
251 level: Sublevel,
252 message: impl Into<DiagMessage>,
253 span: MultiSpan,
254 ) {
255let 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 };
256self.children.push(sub);
257 }
258259pub(crate) fn arg(&mut self, name: impl Into<DiagArgName>, arg: impl IntoDiagArg) {
260let name = name.into();
261let value = arg.into_diag_arg(&mut self.long_ty_path);
262// This assertion is to avoid subdiagnostics overwriting an existing diagnostic arg.
263if 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!(
264 !self.args.contains_key(&name) || self.args.get(&name) == Some(&value),
265"arg {} already exists",
266 name
267 );
268self.args.insert(name, value);
269 }
270271pub fn remove_arg(&mut self, name: &str) {
272self.args.swap_remove(name);
273 }
274275pub fn emitted_at_sub_diag(&self) -> Subdiag {
276let 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);
277Subdiag {
278 level: crate::Sublevel::Note,
279 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)],
280 span: MultiSpan::new(),
281 }
282 }
283284/// Hash used to determine if two diagnostics are the same. Used by
285 /// `DiagCtxtInner::emitted_diagnostics`. Some fields are ignored for the hash.
286pub(crate) fn dedup_hash(&self) -> Hash128 {
287// Deconstruct to ensure all fields are considered.
288let DiagInner {
289 level,
290 messages,
291 code,
292 span,
293 children,
294 suggestions,
295 args,
296 is_lint,
297 long_ty_path: _, // ignore
298emitted_at: _, // ignore
299} = self;
300301let hashed_parts = (
302 std::mem::discriminant(level), // ignore the field within `Warning`
303messages,
304code,
305span,
306children,
307suggestions,
308args.as_slice(),
309is_lint,
310 );
311312let mut hasher = StableHasher::new();
313hashed_parts.hash(&mut hasher);
314hasher.finish()
315 }
316}
317318/// A "sub"-diagnostic attached to a parent diagnostic.
319/// For example, a note attached to an error.
320#[derive(#[automatically_derived]
impl ::core::clone::Clone for Subdiag {
#[inline]
fn clone(&self) -> Self {
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::marker::StructuralPartialEq for Subdiag { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Subdiag {
#[inline]
fn eq(&self, other: &Self) -> 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) {
let Subdiag {
level: ref __binding_0,
messages: ref __binding_1,
span: ref __binding_2 } = *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);
}
}
};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)]
321pub struct Subdiag {
322pub level: Sublevel,
323pub messages: Vec<(DiagMessage, Style)>,
324pub span: MultiSpan,
325}
326327/// Used for emitting structured error messages and other diagnostic information.
328/// Wraps a `DiagInner`, adding some useful things.
329/// - The `dcx` field, allowing it to (a) emit itself, and (b) do a drop check
330/// that it has been emitted or cancelled.
331///
332/// Each constructed `Diag` must be consumed by a function such as
333/// `emit_bug`/`emit_fatal`/`emit_err`/`emit`, `cancel`, or `delay_as_bug`. A
334/// panic occurs if a `Diag` is dropped without being consumed by one of these
335/// functions.
336///
337/// If there is some state in a downstream crate you would like to access in
338/// the methods of `Diag` here, consider extending `DiagCtxtFlags`.
339#[must_use]
340pub struct Diag<'a> {
341pub dcx: DiagCtxtHandle<'a>,
342343/// Why the `Option`? It is always `Some` until the `Diag` is consumed via
344 /// `emit`, `cancel`, etc. At that point it is consumed and replaced with
345 /// `None`. Then `drop` checks that it is `None`; if not, it panics because
346 /// a diagnostic was built but not used.
347 ///
348 /// Why the Box? `DiagInner` is a large type, and `Diag` is often used as a
349 /// return value, especially within the frequently-used `PResult` type. In
350 /// theory, return value optimization (RVO) should avoid unnecessary
351 /// copying. In practice, it does not (at the time of writing).
352diag: Option<Box<DiagInner>>,
353}
354355// Cloning a `Diag` is a recipe for a diagnostic being emitted twice, which
356// would be bad.
357impl !Clonefor Diag<'_> {}
358359const _: [(); 3 * size_of::<usize>()] =
[(); ::std::mem::size_of::<Diag<'_>>()];rustc_data_structures::static_assert_size!(Diag<'_>, 3 * size_of::<usize>());
360361impl Dereffor Diag<'_> {
362type Target = DiagInner;
363364fn deref(&self) -> &DiagInner {
365self.diag.as_ref().unwrap()
366 }
367}
368369impl DerefMutfor Diag<'_> {
370fn deref_mut(&mut self) -> &mut DiagInner {
371self.diag.as_mut().unwrap()
372 }
373}
374375impl Debugfor Diag<'_> {
376fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377self.diag.fmt(f)
378 }
379}
380381/// `Diag` impls many `&mut self -> &mut Self` methods. Each one modifies an
382/// existing diagnostic, either in a standalone fashion, e.g.
383/// `err.code(code);`, or in a chained fashion to make multiple modifications,
384/// e.g. `err.code(code).span(span);`.
385///
386/// This macro creates an equivalent `self -> Self` method, with a `with_`
387/// prefix. This can be used in a chained fashion when making a new diagnostic,
388/// e.g. `let err = struct_err(msg).with_code(code);`, or emitting a new
389/// diagnostic, e.g. `struct_err(msg).with_code(code).emit();`.
390///
391/// Although the latter method can be used to modify an existing diagnostic,
392/// e.g. `err = err.with_code(code);`, this should be avoided because the former
393/// method gives shorter code, e.g. `err.code(code);`.
394///
395/// Note: the `with_` methods are added only when needed. If you want to use
396/// one and it's not defined, feel free to add it.
397///
398/// Note: any doc comments must be within the `with_fn!` call.
399macro_rules!with_fn {
400 {
401$with_f:ident,
402 $(#[$attrs:meta])*
403pub fn $f:ident(&mut $self:ident, $($name:ident: $ty:ty),* $(,)?) -> &mut Self {
404 $($body:tt)*
405 }
406 } => {
407// The original function.
408$(#[$attrs])*
409#[doc = concat!("See [`Diag::", stringify!($f), "()`].")]
410pub fn $f(&mut $self, $($name: $ty),*) -> &mut Self {
411 $($body)*
412 }
413414// The `with_*` variant.
415$(#[$attrs])*
416#[doc = concat!("See [`Diag::", stringify!($f), "()`].")]
417pub fn $with_f(mut $self, $($name: $ty),*) -> Self {
418$self.$f($($name),*);
419$self
420}
421 };
422}
423424impl<'a> Diag<'a> {
425#[track_caller]
426pub fn new(dcx: DiagCtxtHandle<'a>, level: Level, message: impl Into<DiagMessage>) -> Self {
427Self::new_diagnostic(dcx, DiagInner::new(level, message))
428 }
429430/// Allow moving diagnostics between different error tainting contexts
431pub fn with_dcx(mut self, dcx: DiagCtxtHandle<'_>) -> Diag<'_> {
432Diag { dcx, diag: self.diag.take() }
433 }
434435/// Creates a new `Diag` with an already constructed diagnostic.
436#[track_caller]
437pub(crate) fn new_diagnostic(dcx: DiagCtxtHandle<'a>, diag: DiagInner) -> Self {
438{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/fd8e211ae301c84a86d13cf52a6d3ce08c589e2e/compiler/rustc_errors/src/diagnostic.rs:438",
"rustc_errors::diagnostic", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/fd8e211ae301c84a86d13cf52a6d3ce08c589e2e/compiler/rustc_errors/src/diagnostic.rs"),
::tracing_core::__macro_support::Option::Some(438u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Created new diagnostic")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("Created new diagnostic");
439Self { dcx, diag: Some(Box::new(diag)) }
440 }
441442/// Delay emission of this diagnostic as a bug.
443 ///
444 /// This can be useful in contexts where an error indicates a bug but
445 /// typically this only happens when other compilation errors have already
446 /// happened. In those cases this can be used to defer emission of this
447 /// diagnostic as a bug in the compiler only if no other errors have been
448 /// emitted.
449 ///
450 /// In the meantime, though, callsites are required to deal with the "bug"
451 /// locally in whichever way makes the most sense.
452#[track_caller]
453pub fn downgrade_to_delayed_bug(&mut self) {
454if !#[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!(
455matches!(self.level, Level::Error | Level::DelayedBug),
456"downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
457self.level
458 );
459self.level = Level::DelayedBug;
460 }
461462/// Make emitting this diagnostic fatal.
463#[track_caller]
464pub fn upgrade_to_fatal(mut self) -> Diag<'a> {
465if !#[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!(
466matches!(self.level, Level::Error),
467"upgrade_to_fatal: cannot upgrade {:?} to Fatal: not an error",
468self.level
469 );
470self.level = Level::Fatal;
471472// Take is okay since we immediately rewrap it in another diagnostic.
473 // i.e. we do emit it despite defusing the original diagnostic's drop bomb.
474let diag = self.diag.take();
475Diag { dcx: self.dcx, diag }
476 }
477478#[doc = r" Appends a labeled span to the diagnostic."]
#[doc = r""]
#[doc =
r" Labels are used to convey additional context for the diagnostic's primary span. They will"]
#[doc =
r" be shown together with the original diagnostic's span, *not* with spans added by"]
#[doc =
r" `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because"]
#[doc =
r" the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed"]
#[doc = r" either."]
#[doc = r""]
#[doc =
r" Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when"]
#[doc =
r" the diagnostic was constructed. However, the label span is *not* considered a"]
#[doc =
r#" ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is"#]
#[doc = r" primary."]
#[doc = "See [`Diag::span_label()`]."]
pub fn span_label(&mut self, span: Span, label: impl Into<DiagMessage>)
-> &mut Self {
self.span.push_span_label(span, label.into());
self
}
#[doc = r" Appends a labeled span to the diagnostic."]
#[doc = r""]
#[doc =
r" Labels are used to convey additional context for the diagnostic's primary span. They will"]
#[doc =
r" be shown together with the original diagnostic's span, *not* with spans added by"]
#[doc =
r" `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because"]
#[doc =
r" the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed"]
#[doc = r" either."]
#[doc = r""]
#[doc =
r" Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when"]
#[doc =
r" the diagnostic was constructed. However, the label span is *not* considered a"]
#[doc =
r#" ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is"#]
#[doc = r" primary."]
#[doc = "See [`Diag::span_label()`]."]
pub fn with_span_label(mut self, span: Span, label: impl Into<DiagMessage>)
-> Self {
self.span_label(span, label);
self
}with_fn! { with_span_label,
479/// Appends a labeled span to the diagnostic.
480 ///
481 /// Labels are used to convey additional context for the diagnostic's primary span. They will
482 /// be shown together with the original diagnostic's span, *not* with spans added by
483 /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
484 /// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
485 /// either.
486 ///
487 /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
488 /// the diagnostic was constructed. However, the label span is *not* considered a
489 /// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
490 /// primary.
491pub fn span_label(&mut self, span: Span, label: impl Into<DiagMessage>) -> &mut Self {
492self.span.push_span_label(span, label.into());
493self
494} }495496#[doc = "See [`Diag::span_context()`]."]
pub fn span_context(&mut self, span: Span) -> &mut Self {
self.span.push_span_context(span);
self
}
#[doc = "See [`Diag::span_context()`]."]
pub fn with_span_context(mut self, span: Span) -> Self {
self.span_context(span);
self
}with_fn! { with_span_context,
497pub fn span_context(&mut self, span: Span) -> &mut Self {
498self.span.push_span_context(span);
499self
500} }501502#[doc = r" Labels all the given spans with the provided label."]
#[doc = r" See [`Self::span_label()`] for more information."]
#[doc = "See [`Diag::span_labels()`]."]
pub fn span_labels(&mut self, spans: impl IntoIterator<Item = Span>,
label: &str) -> &mut Self {
for span in spans { self.span_label(span, label.to_string()); }
self
}
#[doc = r" Labels all the given spans with the provided label."]
#[doc = r" See [`Self::span_label()`] for more information."]
#[doc = "See [`Diag::span_labels()`]."]
pub fn with_span_labels(mut self, spans: impl IntoIterator<Item = Span>,
label: &str) -> Self {
self.span_labels(spans, label);
self
}with_fn! { with_span_labels,
503/// Labels all the given spans with the provided label.
504 /// See [`Self::span_label()`] for more information.
505pub fn span_labels(&mut self, spans: impl IntoIterator<Item = Span>, label: &str) -> &mut Self {
506for span in spans {
507self.span_label(span, label.to_string());
508 }
509self
510} }511512pub fn replace_span_with(&mut self, after: Span, keep_label: bool) -> &mut Self {
513let before = self.span.clone();
514self.span(after);
515for span_label in before.span_labels() {
516if let Some(label) = span_label.label {
517if span_label.is_primary && keep_label {
518self.span.push_span_label(after, label);
519 } else {
520self.span.push_span_label(span_label.span, label);
521 }
522 }
523 }
524self525 }
526527pub fn note_expected_found(
528&mut self,
529 expected_label: &str,
530 expected: DiagStyledString,
531 found_label: &str,
532 found: DiagStyledString,
533 ) -> &mut Self {
534self.note_expected_found_extra(
535expected_label,
536expected,
537found_label,
538found,
539DiagStyledString::normal(""),
540DiagStyledString::normal(""),
541 )
542 }
543544pub fn note_expected_found_extra(
545&mut self,
546 expected_label: &str,
547 expected: DiagStyledString,
548 found_label: &str,
549 found: DiagStyledString,
550 expected_extra: DiagStyledString,
551 found_extra: DiagStyledString,
552 ) -> &mut Self {
553let expected_label = expected_label.to_string();
554let expected_label = if expected_label.is_empty() {
555"expected".to_string()
556 } else {
557::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}", expected_label))
})format!("expected {expected_label}")558 };
559let found_label = found_label.to_string();
560let found_label = if found_label.is_empty() {
561"found".to_string()
562 } else {
563::alloc::__export::must_use({
::alloc::fmt::format(format_args!("found {0}", found_label))
})format!("found {found_label}")564 };
565let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
566 (expected_label.len() - found_label.len(), 0)
567 } else {
568 (0, found_label.len() - expected_label.len())
569 };
570let 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!(
571"{}{} `",
572" ".repeat(expected_padding),
573 expected_label
574 ))];
575msg.extend(expected.0);
576msg.push(StringPart::normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("`")) })format!("`")));
577msg.extend(expected_extra.0);
578msg.push(StringPart::normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("\n")) })format!("\n")));
579msg.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)));
580msg.extend(found.0);
581msg.push(StringPart::normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("`")) })format!("`")));
582msg.extend(found_extra.0);
583584// For now, just attach these as notes.
585self.highlighted_note(msg);
586self587 }
588589pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
590self.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![
591 StringPart::normal(format!("`{name}` from trait: `")),
592 StringPart::highlighted(signature),
593 StringPart::normal("`"),
594 ]);
595self596 }
597598#[doc = r" Add a note attached to this diagnostic."]
#[doc = "See [`Diag::note()`]."]
pub fn note(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
self.sub(Sublevel::Note, msg, MultiSpan::new());
self
}
#[doc = r" Add a note attached to this diagnostic."]
#[doc = "See [`Diag::note()`]."]
pub fn with_note(mut self, msg: impl Into<DiagMessage>) -> Self {
self.note(msg);
self
}with_fn! { with_note,
599/// Add a note attached to this diagnostic.
600pub fn note(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
601self.sub(Sublevel::Note, msg, MultiSpan::new());
602self
603} }604605pub fn highlighted_note(&mut self, msg: Vec<StringPart>) -> &mut Self {
606self.sub_with_highlights(Sublevel::Note, msg, MultiSpan::new());
607self608 }
609610pub fn highlighted_span_note(
611&mut self,
612 span: impl Into<MultiSpan>,
613 msg: Vec<StringPart>,
614 ) -> &mut Self {
615self.sub_with_highlights(Sublevel::Note, msg, span.into());
616self617 }
618619/// This is like [`Diag::note()`], but it's only printed once.
620pub fn note_once(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
621self.sub(Sublevel::OnceNote, msg, MultiSpan::new());
622self623 }
624625#[doc = r" Prints the span with a note above it."]
#[doc = r" This is like [`Diag::note()`], but it gets its own span."]
#[doc = "See [`Diag::span_note()`]."]
pub fn span_note(&mut self, sp: impl Into<MultiSpan>,
msg: impl Into<DiagMessage>) -> &mut Self {
self.sub(Sublevel::Note, msg, sp.into());
self
}
#[doc = r" Prints the span with a note above it."]
#[doc = r" This is like [`Diag::note()`], but it gets its own span."]
#[doc = "See [`Diag::span_note()`]."]
pub fn with_span_note(mut self, sp: impl Into<MultiSpan>,
msg: impl Into<DiagMessage>) -> Self {
self.span_note(sp, msg);
self
}with_fn! { with_span_note,
626/// Prints the span with a note above it.
627 /// This is like [`Diag::note()`], but it gets its own span.
628pub fn span_note(
629&mut self,
630 sp: impl Into<MultiSpan>,
631 msg: impl Into<DiagMessage>,
632 ) -> &mut Self {
633self.sub(Sublevel::Note, msg, sp.into());
634self
635} }636637/// Prints the span with a note above it.
638 /// This is like [`Diag::note_once()`], but it gets its own span.
639pub fn span_note_once<S: Into<MultiSpan>>(
640&mut self,
641 sp: S,
642 msg: impl Into<DiagMessage>,
643 ) -> &mut Self {
644self.sub(Sublevel::OnceNote, msg, sp.into());
645self646 }
647648#[doc = r" Add a warning attached to this diagnostic."]
#[doc = "See [`Diag::warn()`]."]
pub fn warn(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
self.sub(Sublevel::Warning, msg, MultiSpan::new());
self
}
#[doc = r" Add a warning attached to this diagnostic."]
#[doc = "See [`Diag::warn()`]."]
pub fn with_warn(mut self, msg: impl Into<DiagMessage>) -> Self {
self.warn(msg);
self
}with_fn! { with_warn,
649/// Add a warning attached to this diagnostic.
650pub fn warn(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
651self.sub(Sublevel::Warning, msg, MultiSpan::new());
652self
653} }654655/// Prints the span with a warning above it.
656 /// This is like [`Diag::warn()`], but it gets its own span.
657pub fn span_warn<S: Into<MultiSpan>>(
658&mut self,
659 sp: S,
660 msg: impl Into<DiagMessage>,
661 ) -> &mut Self {
662self.sub(Sublevel::Warning, msg, sp.into());
663self664 }
665666#[doc = r" Add a help message attached to this diagnostic."]
#[doc = "See [`Diag::help()`]."]
pub fn help(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
self.sub(Sublevel::Help, msg, MultiSpan::new());
self
}
#[doc = r" Add a help message attached to this diagnostic."]
#[doc = "See [`Diag::help()`]."]
pub fn with_help(mut self, msg: impl Into<DiagMessage>) -> Self {
self.help(msg);
self
}with_fn! { with_help,
667/// Add a help message attached to this diagnostic.
668pub fn help(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
669self.sub(Sublevel::Help, msg, MultiSpan::new());
670self
671} }672673/// This is like [`Diag::help()`], but it's only printed once.
674pub fn help_once(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
675self.sub(Sublevel::OnceHelp, msg, MultiSpan::new());
676self677 }
678679/// Add a help message attached to this diagnostic with a customizable highlighted message.
680pub fn highlighted_help(&mut self, msg: Vec<StringPart>) -> &mut Self {
681self.sub_with_highlights(Sublevel::Help, msg, MultiSpan::new());
682self683 }
684685/// Add a help message attached to this diagnostic with a customizable highlighted message.
686pub fn highlighted_span_help(
687&mut self,
688 span: impl Into<MultiSpan>,
689 msg: Vec<StringPart>,
690 ) -> &mut Self {
691self.sub_with_highlights(Sublevel::Help, msg, span.into());
692self693 }
694695#[doc = r" Prints the span with some help above it."]
#[doc = r" This is like [`Diag::help()`], but it gets its own span."]
#[doc = "See [`Diag::span_help()`]."]
pub fn span_help(&mut self, sp: impl Into<MultiSpan>,
msg: impl Into<DiagMessage>) -> &mut Self {
self.sub(Sublevel::Help, msg, sp.into());
self
}
#[doc = r" Prints the span with some help above it."]
#[doc = r" This is like [`Diag::help()`], but it gets its own span."]
#[doc = "See [`Diag::span_help()`]."]
pub fn with_span_help(mut self, sp: impl Into<MultiSpan>,
msg: impl Into<DiagMessage>) -> Self {
self.span_help(sp, msg);
self
}with_fn! { with_span_help,
696/// Prints the span with some help above it.
697 /// This is like [`Diag::help()`], but it gets its own span.
698pub fn span_help(
699&mut self,
700 sp: impl Into<MultiSpan>,
701 msg: impl Into<DiagMessage>,
702 ) -> &mut Self {
703self.sub(Sublevel::Help, msg, sp.into());
704self
705} }706707/// Disallow attaching suggestions to this diagnostic.
708 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
709 /// (before and after the call to `disable_suggestions`) will be ignored.
710pub fn disable_suggestions(&mut self) -> &mut Self {
711self.suggestions = Suggestions::Disabled;
712self713 }
714715/// Prevent new suggestions from being added to this diagnostic.
716 ///
717 /// Suggestions added before the call to `.seal_suggestions()` will be preserved
718 /// and new suggestions will be ignored.
719pub fn seal_suggestions(&mut self) -> &mut Self {
720if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
721let suggestions_slice = std::mem::take(suggestions).into_boxed_slice();
722self.suggestions = Suggestions::Sealed(suggestions_slice);
723 }
724self725 }
726727/// Helper for pushing to `self.suggestions`.
728 ///
729 /// A new suggestion is added if suggestions are enabled for this diagnostic.
730 /// Otherwise, they are ignored.
731fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
732for subst in &suggestion.substitutions {
733for part in &subst.parts {
734let span = part.span;
735let call_site = span.ctxt().outer_expn_data().call_site;
736if span.in_derive_expansion() && span.overlaps_or_adjacent(call_site) {
737// Ignore if spans is from derive macro.
738return;
739 }
740 }
741 }
742743if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
744suggestions.push(suggestion);
745 }
746 }
747748#[doc =
r" Show a suggestion that has multiple parts to it, always as its own subdiagnostic."]
#[doc =
r" In other words, multiple changes need to be applied as part of this suggestion."]
#[doc = "See [`Diag::multipart_suggestion()`]."]
pub fn multipart_suggestion(&mut self, msg: impl Into<DiagMessage>,
suggestion: Vec<(Span, String)>, applicability: Applicability)
-> &mut Self {
self.multipart_suggestion_with_style(msg, suggestion, applicability,
SuggestionStyle::ShowAlways)
}
#[doc =
r" Show a suggestion that has multiple parts to it, always as its own subdiagnostic."]
#[doc =
r" In other words, multiple changes need to be applied as part of this suggestion."]
#[doc = "See [`Diag::multipart_suggestion()`]."]
pub fn with_multipart_suggestion(mut self, msg: impl Into<DiagMessage>,
suggestion: Vec<(Span, String)>, applicability: Applicability) -> Self {
self.multipart_suggestion(msg, suggestion, applicability);
self
}with_fn! { with_multipart_suggestion,
749/// Show a suggestion that has multiple parts to it, always as its own subdiagnostic.
750 /// In other words, multiple changes need to be applied as part of this suggestion.
751pub fn multipart_suggestion(
752&mut self,
753 msg: impl Into<DiagMessage>,
754 suggestion: Vec<(Span, String)>,
755 applicability: Applicability,
756 ) -> &mut Self {
757self.multipart_suggestion_with_style(
758 msg,
759 suggestion,
760 applicability,
761 SuggestionStyle::ShowAlways,
762 )
763 } }764765/// [`Diag::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
766pub fn multipart_suggestion_with_style(
767&mut self,
768 msg: impl Into<DiagMessage>,
769mut suggestion: Vec<(Span, String)>,
770 applicability: Applicability,
771 style: SuggestionStyle,
772 ) -> &mut Self {
773let mut seen = crate::FxHashSet::default();
774suggestion.retain(|(span, msg)| seen.insert((span.lo(), span.hi(), msg.clone())));
775776let parts = suggestion777 .into_iter()
778 .map(|(span, snippet)| SubstitutionPart { snippet, span })
779 .collect::<Vec<_>>();
780781if !!parts.is_empty() {
::core::panicking::panic("assertion failed: !parts.is_empty()")
};assert!(!parts.is_empty());
782if 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!(
783 parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()),
784None,
785"Span must not be empty and have no suggestion",
786 );
787if 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!(
788 parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
789None,
790"suggestion must not have overlapping parts",
791 );
792793self.push_suggestion(CodeSuggestion {
794 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 }],
795 msg: msg.into(),
796style,
797applicability,
798 });
799self800 }
801802/// Prints out a message with for a multipart suggestion without showing the suggested code.
803 ///
804 /// This is intended to be used for suggestions that are obvious in what the changes need to
805 /// be from the message, showing the span label inline would be visually unpleasant
806 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
807 /// improve understandability.
808pub fn tool_only_multipart_suggestion(
809&mut self,
810 msg: impl Into<DiagMessage>,
811 suggestion: Vec<(Span, String)>,
812 applicability: Applicability,
813 ) -> &mut Self {
814self.multipart_suggestion_with_style(
815msg,
816suggestion,
817applicability,
818 SuggestionStyle::CompletelyHidden,
819 )
820 }
821822#[doc = r" Prints out a message with a suggested edit of the code."]
#[doc = r""]
#[doc =
r" In case of short messages and a simple suggestion, rustc displays it as a label:"]
#[doc = r""]
#[doc = r" ```text"]
#[doc = r" try adding parentheses: `(tup.0).1`"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" The message"]
#[doc = r""]
#[doc =
r" * should not end in any punctuation (a `:` is added automatically)"]
#[doc = r#" * should not be a question (avoid language like "did you mean")"#]
#[doc =
r#" * should not contain any phrases like "the following", "as shown", etc."#]
#[doc = r#" * may look like "to do xyz, use" or "to do xyz, use abc""#]
#[doc =
r" * may contain a name of a function, variable, or type, but not whole expressions"]
#[doc = r""]
#[doc = r" See [`CodeSuggestion`] for more information."]
#[doc = "See [`Diag::span_suggestion()`]."]
pub fn span_suggestion(&mut self, sp: Span, msg: impl Into<DiagMessage>,
suggestion: impl ToString, applicability: Applicability) -> &mut Self {
self.span_suggestion_with_style(sp, msg, suggestion, applicability,
SuggestionStyle::ShowCode);
self
}
#[doc = r" Prints out a message with a suggested edit of the code."]
#[doc = r""]
#[doc =
r" In case of short messages and a simple suggestion, rustc displays it as a label:"]
#[doc = r""]
#[doc = r" ```text"]
#[doc = r" try adding parentheses: `(tup.0).1`"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" The message"]
#[doc = r""]
#[doc =
r" * should not end in any punctuation (a `:` is added automatically)"]
#[doc = r#" * should not be a question (avoid language like "did you mean")"#]
#[doc =
r#" * should not contain any phrases like "the following", "as shown", etc."#]
#[doc = r#" * may look like "to do xyz, use" or "to do xyz, use abc""#]
#[doc =
r" * may contain a name of a function, variable, or type, but not whole expressions"]
#[doc = r""]
#[doc = r" See [`CodeSuggestion`] for more information."]
#[doc = "See [`Diag::span_suggestion()`]."]
pub fn with_span_suggestion(mut self, sp: Span, msg: impl Into<DiagMessage>,
suggestion: impl ToString, applicability: Applicability) -> Self {
self.span_suggestion(sp, msg, suggestion, applicability);
self
}with_fn! { with_span_suggestion,
823/// Prints out a message with a suggested edit of the code.
824 ///
825 /// In case of short messages and a simple suggestion, rustc displays it as a label:
826 ///
827 /// ```text
828 /// try adding parentheses: `(tup.0).1`
829 /// ```
830 ///
831 /// The message
832 ///
833 /// * should not end in any punctuation (a `:` is added automatically)
834 /// * should not be a question (avoid language like "did you mean")
835 /// * should not contain any phrases like "the following", "as shown", etc.
836 /// * may look like "to do xyz, use" or "to do xyz, use abc"
837 /// * may contain a name of a function, variable, or type, but not whole expressions
838 ///
839 /// See [`CodeSuggestion`] for more information.
840pub fn span_suggestion(
841&mut self,
842 sp: Span,
843 msg: impl Into<DiagMessage>,
844 suggestion: impl ToString,
845 applicability: Applicability,
846 ) -> &mut Self {
847self.span_suggestion_with_style(
848 sp,
849 msg,
850 suggestion,
851 applicability,
852 SuggestionStyle::ShowCode,
853 );
854self
855} }856857#[doc =
r" [`Diag::span_suggestion()`] but you can set the [`SuggestionStyle`]."]
#[doc = "See [`Diag::span_suggestion_with_style()`]."]
pub fn span_suggestion_with_style(&mut self, sp: Span,
msg: impl Into<DiagMessage>, suggestion: impl ToString,
applicability: Applicability, style: SuggestionStyle) -> &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"));
}
};
};
self.push_suggestion(CodeSuggestion {
substitutions: ::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,
}])),
}])),
msg: msg.into(),
style,
applicability,
});
self
}
#[doc =
r" [`Diag::span_suggestion()`] but you can set the [`SuggestionStyle`]."]
#[doc = "See [`Diag::span_suggestion_with_style()`]."]
pub fn with_span_suggestion_with_style(mut self, sp: Span,
msg: impl Into<DiagMessage>, suggestion: impl ToString,
applicability: Applicability, style: SuggestionStyle) -> Self {
self.span_suggestion_with_style(sp, msg, suggestion, applicability,
style);
self
}with_fn! { with_span_suggestion_with_style,
858/// [`Diag::span_suggestion()`] but you can set the [`SuggestionStyle`].
859pub fn span_suggestion_with_style(
860&mut self,
861 sp: Span,
862 msg: impl Into<DiagMessage>,
863 suggestion: impl ToString,
864 applicability: Applicability,
865 style: SuggestionStyle,
866 ) -> &mut Self {
867debug_assert!(
868 !(sp.is_empty() && suggestion.to_string().is_empty()),
869"Span must not be empty and have no suggestion"
870);
871self.push_suggestion(CodeSuggestion {
872 substitutions: vec![Substitution {
873 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
874 }],
875 msg: msg.into(),
876 style,
877 applicability,
878 });
879self
880} }881882#[doc = r" Always show the suggested change."]
#[doc = "See [`Diag::span_suggestion_verbose()`]."]
pub fn span_suggestion_verbose(&mut self, sp: Span,
msg: impl Into<DiagMessage>, suggestion: impl ToString,
applicability: Applicability) -> &mut Self {
self.span_suggestion_with_style(sp, msg, suggestion, applicability,
SuggestionStyle::ShowAlways);
self
}
#[doc = r" Always show the suggested change."]
#[doc = "See [`Diag::span_suggestion_verbose()`]."]
pub fn with_span_suggestion_verbose(mut self, sp: Span,
msg: impl Into<DiagMessage>, suggestion: impl ToString,
applicability: Applicability) -> Self {
self.span_suggestion_verbose(sp, msg, suggestion, applicability);
self
}with_fn! { with_span_suggestion_verbose,
883/// Always show the suggested change.
884pub fn span_suggestion_verbose(
885&mut self,
886 sp: Span,
887 msg: impl Into<DiagMessage>,
888 suggestion: impl ToString,
889 applicability: Applicability,
890 ) -> &mut Self {
891self.span_suggestion_with_style(
892 sp,
893 msg,
894 suggestion,
895 applicability,
896 SuggestionStyle::ShowAlways,
897 );
898self
899} }900901#[doc = r" Prints out a message with multiple suggested edits of the code."]
#[doc = r" See also [`Diag::span_suggestion()`]."]
#[doc = "See [`Diag::span_suggestions()`]."]
pub fn span_suggestions(&mut self, sp: Span, msg: impl Into<DiagMessage>,
suggestions: impl IntoIterator<Item = String>,
applicability: Applicability) -> &mut Self {
self.span_suggestions_with_style(sp, msg, suggestions, applicability,
SuggestionStyle::ShowAlways)
}
#[doc = r" Prints out a message with multiple suggested edits of the code."]
#[doc = r" See also [`Diag::span_suggestion()`]."]
#[doc = "See [`Diag::span_suggestions()`]."]
pub fn with_span_suggestions(mut self, sp: Span, msg: impl Into<DiagMessage>,
suggestions: impl IntoIterator<Item = String>,
applicability: Applicability) -> Self {
self.span_suggestions(sp, msg, suggestions, applicability);
self
}with_fn! { with_span_suggestions,
902/// Prints out a message with multiple suggested edits of the code.
903 /// See also [`Diag::span_suggestion()`].
904pub fn span_suggestions(
905&mut self,
906 sp: Span,
907 msg: impl Into<DiagMessage>,
908 suggestions: impl IntoIterator<Item = String>,
909 applicability: Applicability,
910 ) -> &mut Self {
911self.span_suggestions_with_style(
912 sp,
913 msg,
914 suggestions,
915 applicability,
916 SuggestionStyle::ShowAlways,
917 )
918 } }919920pub fn span_suggestions_with_style(
921&mut self,
922 sp: Span,
923 msg: impl Into<DiagMessage>,
924 suggestions: impl IntoIterator<Item = String>,
925 applicability: Applicability,
926 style: SuggestionStyle,
927 ) -> &mut Self {
928let substitutions = suggestions929 .into_iter()
930 .map(|snippet| {
931if 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!(
932 !(sp.is_empty() && snippet.is_empty()),
933"Span `{sp:?}` must not be empty and have no suggestion"
934);
935Substitution { 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 }] }
936 })
937 .collect();
938self.push_suggestion(CodeSuggestion {
939substitutions,
940 msg: msg.into(),
941style,
942applicability,
943 });
944self945 }
946947/// Prints out a message with multiple suggested edits of the code, where each edit consists of
948 /// multiple parts.
949 /// See also [`Diag::multipart_suggestion()`].
950pub fn multipart_suggestions(
951&mut self,
952 msg: impl Into<DiagMessage>,
953 suggestions: impl IntoIterator<Item = Vec<(Span, String)>>,
954 applicability: Applicability,
955 ) -> &mut Self {
956let substitutions = suggestions957 .into_iter()
958 .map(|sugg| {
959let mut parts = sugg960 .into_iter()
961 .map(|(span, snippet)| SubstitutionPart { snippet, span })
962 .collect::<Vec<_>>();
963964parts.sort_unstable_by_key(|part| part.span);
965966if !!parts.is_empty() {
::core::panicking::panic("assertion failed: !parts.is_empty()")
};assert!(!parts.is_empty());
967if 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!(
968 parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()),
969None,
970"Span must not be empty and have no suggestion",
971 );
972if 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!(
973 parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
974None,
975"suggestion must not have overlapping parts",
976 );
977978Substitution { parts }
979 })
980 .collect();
981982self.push_suggestion(CodeSuggestion {
983substitutions,
984 msg: msg.into(),
985 style: SuggestionStyle::ShowAlways,
986applicability,
987 });
988self989 }
990991#[doc =
r" Prints out a message with a suggested edit of the code. If the suggestion is presented"]
#[doc = r" inline, it will only show the message and not the suggestion."]
#[doc = r""]
#[doc = r" See [`CodeSuggestion`] for more information."]
#[doc = "See [`Diag::span_suggestion_short()`]."]
pub fn span_suggestion_short(&mut self, sp: Span, msg: impl Into<DiagMessage>,
suggestion: impl ToString, applicability: Applicability) -> &mut Self {
self.span_suggestion_with_style(sp, msg, suggestion, applicability,
SuggestionStyle::HideCodeInline);
self
}
#[doc =
r" Prints out a message with a suggested edit of the code. If the suggestion is presented"]
#[doc = r" inline, it will only show the message and not the suggestion."]
#[doc = r""]
#[doc = r" See [`CodeSuggestion`] for more information."]
#[doc = "See [`Diag::span_suggestion_short()`]."]
pub fn with_span_suggestion_short(mut self, sp: Span,
msg: impl Into<DiagMessage>, suggestion: impl ToString,
applicability: Applicability) -> Self {
self.span_suggestion_short(sp, msg, suggestion, applicability);
self
}with_fn! { with_span_suggestion_short,
992/// Prints out a message with a suggested edit of the code. If the suggestion is presented
993 /// inline, it will only show the message and not the suggestion.
994 ///
995 /// See [`CodeSuggestion`] for more information.
996pub fn span_suggestion_short(
997&mut self,
998 sp: Span,
999 msg: impl Into<DiagMessage>,
1000 suggestion: impl ToString,
1001 applicability: Applicability,
1002 ) -> &mut Self {
1003self.span_suggestion_with_style(
1004 sp,
1005 msg,
1006 suggestion,
1007 applicability,
1008 SuggestionStyle::HideCodeInline,
1009 );
1010self
1011} }10121013/// Prints out a message for a suggestion without showing the suggested code.
1014 ///
1015 /// This is intended to be used for suggestions that are obvious in what the changes need to
1016 /// be from the message, showing the span label inline would be visually unpleasant
1017 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
1018 /// improve understandability.
1019pub fn span_suggestion_hidden(
1020&mut self,
1021 sp: Span,
1022 msg: impl Into<DiagMessage>,
1023 suggestion: impl ToString,
1024 applicability: Applicability,
1025 ) -> &mut Self {
1026self.span_suggestion_with_style(
1027sp,
1028msg,
1029suggestion,
1030applicability,
1031 SuggestionStyle::HideCodeAlways,
1032 );
1033self1034 }
10351036#[doc =
r" Adds a suggestion to the JSON output that will not be shown in the CLI."]
#[doc = r""]
#[doc =
r" This is intended to be used for suggestions that are *very* obvious in what the changes"]
#[doc =
r" need to be from the message, but we still want other tools to be able to apply them."]
#[doc = "See [`Diag::tool_only_span_suggestion()`]."]
pub fn tool_only_span_suggestion(&mut self, sp: Span,
msg: impl Into<DiagMessage>, suggestion: impl ToString,
applicability: Applicability) -> &mut Self {
self.span_suggestion_with_style(sp, msg, suggestion, applicability,
SuggestionStyle::CompletelyHidden);
self
}
#[doc =
r" Adds a suggestion to the JSON output that will not be shown in the CLI."]
#[doc = r""]
#[doc =
r" This is intended to be used for suggestions that are *very* obvious in what the changes"]
#[doc =
r" need to be from the message, but we still want other tools to be able to apply them."]
#[doc = "See [`Diag::tool_only_span_suggestion()`]."]
pub fn with_tool_only_span_suggestion(mut self, sp: Span,
msg: impl Into<DiagMessage>, suggestion: impl ToString,
applicability: Applicability) -> Self {
self.tool_only_span_suggestion(sp, msg, suggestion, applicability);
self
}with_fn! { with_tool_only_span_suggestion,
1037/// Adds a suggestion to the JSON output that will not be shown in the CLI.
1038 ///
1039 /// This is intended to be used for suggestions that are *very* obvious in what the changes
1040 /// need to be from the message, but we still want other tools to be able to apply them.
1041pub fn tool_only_span_suggestion(
1042&mut self,
1043 sp: Span,
1044 msg: impl Into<DiagMessage>,
1045 suggestion: impl ToString,
1046 applicability: Applicability,
1047 ) -> &mut Self {
1048self.span_suggestion_with_style(
1049 sp,
1050 msg,
1051 suggestion,
1052 applicability,
1053 SuggestionStyle::CompletelyHidden,
1054 );
1055self
1056} }10571058/// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
1059 /// [rustc_macros::Subdiagnostic]). Performs eager formatting of any messages
1060 /// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of
1061 /// interpolated variables).
1062pub fn subdiagnostic(&mut self, subdiagnostic: impl Subdiagnostic) -> &mut Self {
1063subdiagnostic.add_to_diag(self);
1064self1065 }
10661067#[doc = r" Add a span."]
#[doc = "See [`Diag::span()`]."]
pub fn span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self {
self.span = sp.into();
self
}
#[doc = r" Add a span."]
#[doc = "See [`Diag::span()`]."]
pub fn with_span(mut self, sp: impl Into<MultiSpan>) -> Self {
self.span(sp);
self
}with_fn! { with_span,
1068/// Add a span.
1069pub fn span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self {
1070self.span = sp.into();
1071self
1072} }10731074pub fn is_lint(
1075&mut self,
1076 name: String,
1077 has_future_breakage: bool,
1078 rust_version: Option<RustcVersion>,
1079 ) -> &mut Self {
1080self.is_lint = Some(IsLint { name, has_future_breakage, rust_version });
1081self1082 }
10831084#[doc = r" Add an error code."]
#[doc = "See [`Diag::code()`]."]
pub fn code(&mut self, code: ErrCode) -> &mut Self {
self.code = Some(code);
self
}
#[doc = r" Add an error code."]
#[doc = "See [`Diag::code()`]."]
pub fn with_code(mut self, code: ErrCode) -> Self { self.code(code); self }with_fn! { with_code,
1085/// Add an error code.
1086pub fn code(&mut self, code: ErrCode) -> &mut Self {
1087self.code = Some(code);
1088self
1089} }10901091#[doc = r" Add a primary message."]
#[doc = "See [`Diag::primary_message()`]."]
pub fn primary_message(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
self.messages[0] = (msg.into(), Style::NoStyle);
self
}
#[doc = r" Add a primary message."]
#[doc = "See [`Diag::primary_message()`]."]
pub fn with_primary_message(mut self, msg: impl Into<DiagMessage>) -> Self {
self.primary_message(msg);
self
}with_fn! { with_primary_message,
1092/// Add a primary message.
1093pub fn primary_message(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
1094self.messages[0] = (msg.into(), Style::NoStyle);
1095self
1096} }10971098#[doc = r" Add an argument."]
#[doc = "See [`Diag::arg()`]."]
pub fn arg(&mut self, name: impl Into<DiagArgName>, arg: impl IntoDiagArg)
-> &mut Self {
self.deref_mut().arg(name, arg);
self
}
#[doc = r" Add an argument."]
#[doc = "See [`Diag::arg()`]."]
pub fn with_arg(mut self, name: impl Into<DiagArgName>, arg: impl IntoDiagArg)
-> Self {
self.arg(name, arg);
self
}with_fn! { with_arg,
1099/// Add an argument.
1100pub fn arg(
1101&mut self,
1102 name: impl Into<DiagArgName>,
1103 arg: impl IntoDiagArg,
1104 ) -> &mut Self {
1105self.deref_mut().arg(name, arg);
1106self
1107} }11081109/// Convenience function for internal use, clients should use one of the
1110 /// public methods above.
1111 ///
1112 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
1113pub fn sub(&mut self, level: Sublevel, message: impl Into<DiagMessage>, span: MultiSpan) {
1114self.deref_mut().sub(level, message, span);
1115 }
11161117/// Convenience function for internal use, clients should use one of the
1118 /// public methods above.
1119fn sub_with_highlights(&mut self, level: Sublevel, messages: Vec<StringPart>, span: MultiSpan) {
1120let messages = messages.into_iter().map(|m| (m.content.into(), m.style)).collect();
1121let sub = Subdiag { level, messages, span };
1122self.children.push(sub);
1123 }
11241125/// Takes the diagnostic. For use by methods that consume the Diag: `emit`,
1126 /// `cancel`, etc. Afterwards, `drop` is the only code that will be run on
1127 /// `self`.
1128fn take_diag(&mut self) -> DiagInner {
1129if let Some(path) = &self.long_ty_path {
1130self.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the full name for the type has been written to \'{0}\'",
path.display()))
})format!(
1131"the full name for the type has been written to '{}'",
1132 path.display()
1133 ));
1134self.note("consider using `--verbose` to print the full type name to the console");
1135 }
1136*self.diag.take().unwrap()
1137 }
11381139/// This method allows us to access the path of the file where "long types" are written to.
1140 ///
1141 /// When calling `Diag::emit`, as part of that we will check if a `long_ty_path` has been set,
1142 /// and if it has been then we add a note mentioning the file where the "long types" were
1143 /// written to.
1144 ///
1145 /// When calling `tcx.short_string()` after a `Diag` is constructed, the preferred way of doing
1146 /// so is `tcx.short_string(ty, diag.long_ty_path())`. The diagnostic itself is the one that
1147 /// keeps the existence of a "long type" anywhere in the diagnostic, so the note telling the
1148 /// user where we wrote the file to is only printed once at most, *and* it makes it much harder
1149 /// to forget to set it.
1150 ///
1151 /// If the diagnostic hasn't been created before a "short ty string" is created, then you should
1152 /// ensure that this method is called to set it `*diag.long_ty_path() = path`.
1153 ///
1154 /// As a rule of thumb, if you see or add at least one `tcx.short_string()` call anywhere, in a
1155 /// scope, `diag.long_ty_path()` should be called once somewhere close by.
1156pub fn long_ty_path(&mut self) -> &mut Option<PathBuf> {
1157&mut self.long_ty_path
1158 }
11591160pub fn with_long_ty_path(mut self, long_ty_path: Option<PathBuf>) -> Self {
1161self.long_ty_path = long_ty_path;
1162self1163 }
11641165/// Emit the diagnostic. Will also abort appropriately if the level is `Bug` or `Fatal`.
1166#[track_caller]
1167pub fn emit(mut self) {
1168let level = self.level; // get level before taking the inner diag
1169let diag = self.take_diag();
1170self.dcx.emit_diagnostic(diag);
11711172match level {
1173 Level::Bug => panic::panic_any(ExplicitBug),
1174 Level::Fatal => crate::FatalError.raise(),
1175_ => {}
1176 }
1177 }
11781179/// Use this on a `Bug` diagnostic if you need the `!` return type. Otherwise `emit` suffices.
1180 /// Aborts if used on a non-`Bug` diagnostic.
1181#[track_caller]
1182pub fn emit_bug(self) -> ! {
1183{
match (&self.level, &Level::Bug) {
(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.level, Level::Bug);
1184self.emit();
1185::core::panicking::panic("internal error: entered unreachable code");unreachable!(); // `emit` will have aborted
1186}
11871188/// Use this on a `Fatal` diagnostic if you need the `!` return type. Otherwise `emit`
1189 /// suffices. Aborts if used on a non-`Fatal` diagnostic.
1190#[track_caller]
1191pub fn emit_fatal(self) -> ! {
1192{
match (&self.level, &Level::Fatal) {
(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.level, Level::Fatal);
1193self.emit();
1194::core::panicking::panic("internal error: entered unreachable code");unreachable!(); // `emit` will have aborted
1195}
11961197/// Use this on an `Error`/`DelayedBug` diagnostic if you need the `ErrorGuaranteed` return
1198 /// type. Otherwise `emit` suffices. Aborts if used on a non-`Error`/`DelayedBug` diagnostic.
1199#[track_caller]
1200pub fn emit_err(mut self) -> ErrorGuaranteed {
1201let diag = self.take_diag();
12021203// The only error levels that should reach here are `Error` and `DelayedBug`.
1204 // (Also, even though `level` isn't `pub`, the whole `DiagInner` could
1205 // be overwritten with a new one thanks to `DerefMut`. So this assert
1206 // protects against that, too.)
1207if !#[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!(
1208matches!(diag.level, Level::Error | Level::DelayedBug),
1209"invalid diagnostic level ({:?})",
1210 diag.level,
1211 );
12121213let guar = self.dcx.emit_diagnostic(diag);
1214guar.unwrap()
1215 }
12161217/// Emit the diagnostic unless `delay` is true,
1218 /// in which case the emission will be delayed as a bug.
1219 ///
1220 /// See `emit` and `delay_as_bug` for details.
1221#[track_caller]
1222pub fn emit_err_unless_delay(mut self, delay: bool) -> ErrorGuaranteed {
1223if delay {
1224self.downgrade_to_delayed_bug();
1225 }
1226self.emit_err()
1227 }
12281229/// Cancel and consume the diagnostic. (A diagnostic must either be emitted or
1230 /// cancelled or it will panic when dropped).
1231pub fn cancel(mut self) {
1232self.diag = None;
1233drop(self);
1234 }
12351236/// Cancels this diagnostic and returns its first message, if it exists.
1237pub fn cancel_into_message(self) -> Option<String> {
1238let s = self.diag.as_ref()?.messages.get(0)?.0.as_str().map(ToString::to_string);
1239self.cancel();
1240s1241 }
12421243/// See `DiagCtxtHandle::stash_diagnostic` for details.
1244pub fn stash(mut self, span: Span, key: StashKey) -> Option<ErrorGuaranteed> {
1245let diag = self.take_diag();
1246self.dcx.stash_diagnostic(span, key, diag)
1247 }
12481249/// Delay emission of this diagnostic as a bug.
1250 ///
1251 /// This can be useful in contexts where an error indicates a bug but
1252 /// typically this only happens when other compilation errors have already
1253 /// happened. In those cases this can be used to defer emission of this
1254 /// diagnostic as a bug in the compiler only if no other errors have been
1255 /// emitted.
1256 ///
1257 /// In the meantime, though, callsites are required to deal with the "bug"
1258 /// locally in whichever way makes the most sense.
1259#[track_caller]
1260pub fn delay_as_bug(mut self) -> ErrorGuaranteed {
1261self.downgrade_to_delayed_bug();
1262self.emit_err()
1263 }
1264}
12651266/// Destructor bomb: every `Diag` must be consumed (emitted, cancelled, etc.)
1267/// or we emit a bug.
1268impl Dropfor Diag<'_> {
1269fn drop(&mut self) {
1270match self.diag.take() {
1271Some(diag) if !panicking() => {
1272self.dcx.emit_diagnostic(DiagInner::new(
1273 Level::Bug,
1274DiagMessage::from("the following error was constructed but not emitted"),
1275 ));
1276self.dcx.emit_diagnostic(*diag);
1277{
::core::panicking::panic_fmt(format_args!("error was constructed but not emitted"));
};panic!("error was constructed but not emitted");
1278 }
1279_ => {}
1280 }
1281 }
1282}
12831284#[macro_export]
1285macro_rules!struct_span_code_err {
1286 ($dcx:expr, $span:expr, $code:expr, $($message:tt)*) => ({
1287$dcx.struct_span_err($span, format!($($message)*)).with_code($code)
1288 })
1289}