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_serialize::Encodable;
16use rustc_span::{Span, Spanned, Symbol};
17use tracing::debug;
1819use crate::dedup_hash::DedupHashEncoder;
20use crate::{
21CodeSuggestion, DiagCtxtHandle, DiagMessage, ErrCode, ErrorGuaranteed, ExplicitBug, Level,
22MultiSpan, StashKey, Style, Sublevel, Substitution, SubstitutionPart, SuggestionStyle,
23Suggestions,
24};
2526/// Trait implemented by error types. This is rarely implemented manually. Instead, use
27/// `#[derive(Diagnostic)]` -- see [rustc_macros::Diagnostic].
28pub trait Diagnostic<'a> {
29/// Write out as a diagnostic out of `DiagCtxt`.
30#[must_use]
31 #[track_caller]
32fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a>;
33}
3435impl<'a, T> Diagnostic<'a> for Spanned<T>
36where
37T: Diagnostic<'a>,
38{
39fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
40self.node.into_diag(dcx, level).with_span(self.span)
41 }
42}
4344/// Type used to emit diagnostic through a closure instead of implementing the `Diagnostic` trait.
45pub struct DiagDecorator<F: FnOnce(&mut Diag<'_>)>(pub F);
4647impl<'a, F: FnOnce(&mut Diag<'_>)> Diagnostic<'a> for DiagDecorator<F> {
48fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
49let mut diag = Diag::new(dcx, level, "");
50 (self.0)(&mut diag);
51diag52 }
53}
5455/// Trait implemented by error types. This should not be implemented manually. Instead, use
56/// `#[derive(Subdiagnostic)]` -- see [rustc_macros::Subdiagnostic].
57pub trait Subdiagnostic {
58/// Add a subdiagnostic to an existing diagnostic.
59fn add_to_diag(self, diag: &mut Diag<'_>);
60}
6162#[derive(#[automatically_derived]impl ::core::clone::Clone for DiagLocation {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"DiagLocation file line col", &self.file, &self.line, &&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)]
63pub struct DiagLocation {
64 file: Cow<'static, str>,
65 line: u32,
66 col: u32,
67}
6869impl DiagLocation {
70pub fn from_location(loc: &'static panic::Location<'static>) -> Self {
71DiagLocation { file: loc.file().into(), line: loc.line(), col: loc.column() }
72 }
7374#[track_caller]
75pub fn caller() -> Self {
76Self::from_location(panic::Location::caller())
77 }
78}
7980impl fmt::Displayfor DiagLocation {
81fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82f.write_fmt(format_args!("{0}:{1}:{2}", self.file, self.line, self.col))write!(f, "{}:{}:{}", self.file, self.line, self.col)83 }
84}
8586#[derive(#[automatically_derived]impl ::core::clone::Clone for IsLint {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"IsLint name has_future_breakage rust_version", &self.name,
&self.has_future_breakage, &&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)]
87pub struct IsLint {
88/// The lint name.
89pub(crate) name: String,
90/// Indicates whether this lint should show up in cargo's future breakage report.
91has_future_breakage: bool,
92/// Indicates the minimum rust version this lint applies to
93rust_version: Option<RustcVersion>,
94}
9596#[derive(#[automatically_derived]impl ::core::fmt::Debug for DiagStyledString {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_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)]
97pub struct DiagStyledString(pub Vec<StringPart>);
9899impl DiagStyledString {
100pub fn new() -> DiagStyledString {
101DiagStyledString(::alloc::vec::Vec::new()vec![])
102 }
103pub fn push_normal<S: Into<String>>(&mut self, t: S) {
104self.0.push(StringPart::normal(t));
105 }
106pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
107self.0.push(StringPart::highlighted(t));
108 }
109pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
110if highlight {
111self.push_highlighted(t);
112 } else {
113self.push_normal(t);
114 }
115 }
116pub fn normal<S: Into<String>>(t: S) -> DiagStyledString {
117DiagStyledString(::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)])
118 }
119120pub fn highlighted<S: Into<String>>(t: S) -> DiagStyledString {
121DiagStyledString(::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)])
122 }
123124pub fn content(&self) -> String {
125self.0.iter().map(|x| x.content.as_str()).collect::<String>()
126 }
127128/// Merge segments of the same style.
129pub fn compact(&mut self) {
130let segments = std::mem::take(&mut self.0);
131let mut iter = segments.into_iter();
132let Some(mut prev) = iter.next() else { return };
133while let Some(segment) = iter.next() {
134if prev.style == segment.style {
135 prev.content.push_str(&segment.content);
136 } else {
137self.0.push(prev);
138 prev = segment;
139 }
140 }
141self.0.push(prev);
142 }
143144/// Remove the middle of all long segments for shorter rendering.
145pub fn shorten(&mut self) {
146self.compact();
147/// The marker for removed text.
148const ELLIPSIS: &str = "...";
149/// How many chars at the start and end will remain.
150const PADDING: usize = 6;
151/// The distance after which it is not worth it to reduce the text.
152const DELTA: usize = 3;
153154for segment in self.0.iter_mut() {
155let char_len = segment.content.chars().count();
156if char_len > PADDING * 2 + ELLIPSIS.chars().count() + DELTA
157 && let Some((left, _)) = segment.content.char_indices().nth(PADDING)
158 && let Some((right, _)) = segment.content.char_indices().nth(char_len - PADDING)
159 {
160 segment.content.replace_range(left..right, ELLIPSIS);
161 }
162 }
163 }
164}
165166#[derive(#[automatically_derived]impl ::core::fmt::Debug for StringPart {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"StringPart content style", &self.content, &&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)]
167pub struct StringPart {
168 content: String,
169 style: Style,
170}
171172impl StringPart {
173pub fn normal<S: Into<String>>(content: S) -> StringPart {
174StringPart { content: content.into(), style: Style::NoStyle }
175 }
176177pub fn highlighted<S: Into<String>>(content: S) -> StringPart {
178StringPart { content: content.into(), style: Style::Highlight }
179 }
180}
181182/// The main part of a diagnostic. Note that `Diag`, which wraps this type, is
183/// used for most operations, and should be used instead whenever possible.
184/// This type should only be used when `Diag`'s lifetime causes difficulties,
185/// e.g. when storing diagnostics within `DiagCtxt`.
186#[must_use]
187#[derive(#[automatically_derived]impl ::core::clone::Clone for DiagInner {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
"DiagInner 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, 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)]
188pub struct DiagInner {
189// NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
190 // outside of what methods in this crate themselves allow.
191pub(crate) level: Level,
192193pub messages: Vec<(DiagMessage, Style)>,
194pub code: Option<ErrCode>,
195pub span: MultiSpan,
196pub children: Vec<Subdiag>,
197pub suggestions: Suggestions,
198pub args: DiagArgMap,
199pub is_lint: Option<IsLint>,
200pub long_ty_path: Option<PathBuf>,
201/// With `-Ztrack_diagnostics` enabled,
202 /// we print where in rustc this error was emitted.
203pub emitted_at: DiagLocation,
204}
205206impl DiagInner {
207#[track_caller]
208pub fn new<M: Into<DiagMessage>>(level: Level, message: M) -> Self {
209DiagInner::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)])
210 }
211212#[track_caller]
213pub fn new_with_messages(level: Level, messages: Vec<(DiagMessage, Style)>) -> Self {
214DiagInner {
215level,
216messages,
217 code: None,
218 span: MultiSpan::new(),
219 children: ::alloc::vec::Vec::new()vec![],
220 suggestions: Suggestions::Enabled(::alloc::vec::Vec::new()vec![]),
221 args: Default::default(),
222 is_lint: None,
223 long_ty_path: None,
224 emitted_at: DiagLocation::caller(),
225 }
226 }
227228#[inline(always)]
229pub fn level(&self) -> Level {
230self.level
231 }
232233pub fn is_error(&self) -> bool {
234match self.level {
235 Level::Bug | Level::Fatal | Level::Error | Level::DelayedBug => true,
236237 Level::Warning(_) | Level::Note | Level::Help | Level::FailureNote => false,
238 }
239 }
240241/// Indicates whether this diagnostic should show up in cargo's future breakage report.
242pub(crate) fn has_future_breakage(&self) -> bool {
243#[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, .. }))244 }
245246/// Indicates the minimum rust version this lint applies to.
247pub(crate) fn rust_version(&self) -> Option<RustcVersion> {
248self.is_lint.as_ref().and_then(|is| is.rust_version)
249 }
250251pub(crate) fn sub(
252&mut self,
253 level: Sublevel,
254 message: impl Into<DiagMessage>,
255 span: MultiSpan,
256 ) {
257let 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 };
258self.children.push(sub);
259 }
260261pub(crate) fn arg(&mut self, name: impl Into<DiagArgName>, arg: impl IntoDiagArg) {
262let name = name.into();
263let value = arg.into_diag_arg(&mut self.long_ty_path);
264// This assertion is to avoid subdiagnostics overwriting an existing diagnostic arg.
265if 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!(
266 !self.args.contains_key(&name) || self.args.get(&name) == Some(&value),
267"arg {} already exists",
268 name
269 );
270self.args.insert(name, value);
271 }
272273pub fn remove_arg(&mut self, name: &str) {
274self.args.swap_remove(name);
275 }
276277pub fn emitted_at_sub_diag(&self) -> Subdiag {
278let 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);
279Subdiag {
280 level: crate::Sublevel::Note,
281 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)],
282 span: MultiSpan::new(),
283 }
284 }
285286/// Hash used to determine if two diagnostics are the same. Used by
287 /// `DiagCtxtInner::emitted_diagnostics`. Some fields are ignored for the hash.
288pub(crate) fn dedup_hash(&self) -> Hash128 {
289// Deconstruct to ensure all fields are considered.
290let DiagInner {
291 level,
292 messages,
293 code,
294 span,
295 children,
296 suggestions,
297 args,
298 is_lint,
299 long_ty_path: _, // ignore
300emitted_at: _, // ignore
301} = self;
302303let mut e = DedupHashEncoder(StableHasher::new());
304305// We use `discriminant` because we want to ignore the field within `Warning`.
306 // `Encoder`/`SpanEncoder` can't traverse a `Discriminant<T>` so we hash it directly.
307std::mem::discriminant(level).hash(&mut e.0);
308309// All the other fields are hashed via `encode`.
310messages.encode(&mut e);
311code.encode(&mut e);
312span.encode(&mut e);
313children.encode(&mut e);
314suggestions.encode(&mut e);
315args.encode(&mut e);
316is_lint.encode(&mut e);
317318e.0.finish()
319 }
320}
321322/// A "sub"-diagnostic attached to a parent diagnostic.
323/// For example, a note attached to an error.
324#[derive(#[automatically_derived]impl ::core::clone::Clone for Subdiag {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"Subdiag level messages span", &self.level, &self.messages,
&&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)]
325pub struct Subdiag {
326pub level: Sublevel,
327pub messages: Vec<(DiagMessage, Style)>,
328pub span: MultiSpan,
329}
330331impl Subdiag {
332/// Hash used to determine if two subdiagnostics are the same. Used by
333 /// `DiagCtxtInner::emitted_diagnostics`.
334pub(crate) fn dedup_hash(&self) -> Hash128 {
335let mut e = DedupHashEncoder(StableHasher::new());
336self.encode(&mut e);
337e.0.finish()
338 }
339}
340341/// Used for emitting structured error messages and other diagnostic information.
342/// Wraps a `DiagInner`, adding some useful things.
343/// - The `dcx` field, allowing it to (a) emit itself, and (b) do a drop check
344/// that it has been emitted or cancelled.
345///
346/// Each constructed `Diag` must be consumed by a function such as
347/// `emit_bug`/`emit_fatal`/`emit_err`/`emit`, `cancel`, or `delay_as_bug`. A
348/// panic occurs if a `Diag` is dropped without being consumed by one of these
349/// functions.
350///
351/// If there is some state in a downstream crate you would like to access in
352/// the methods of `Diag` here, consider extending `DiagCtxtFlags`.
353#[must_use]
354pub struct Diag<'a> {
355pub dcx: DiagCtxtHandle<'a>,
356357/// Why the `Option`? It is always `Some` until the `Diag` is consumed via
358 /// `emit`, `cancel`, etc. At that point it is consumed and replaced with
359 /// `None`. Then `drop` checks that it is `None`; if not, it panics because
360 /// a diagnostic was built but not used.
361 ///
362 /// Why the Box? `DiagInner` is a large type, and `Diag` is often used as a
363 /// return value, especially within the frequently-used `PResult` type. In
364 /// theory, return value optimization (RVO) should avoid unnecessary
365 /// copying. In practice, it does not (at the time of writing).
366diag: Option<Box<DiagInner>>,
367}
368369// Cloning a `Diag` is a recipe for a diagnostic being emitted twice, which
370// would be bad.
371impl !Clonefor Diag<'_> {}
372373const _: [(); 3 * size_of::<usize>()] =
[(); ::std::mem::size_of::<Diag<'_>>()];rustc_data_structures::static_assert_size!(Diag<'_>, 3 * size_of::<usize>());
374375impl Dereffor Diag<'_> {
376type Target = DiagInner;
377378fn deref(&self) -> &DiagInner {
379self.diag.as_ref().unwrap()
380 }
381}
382383impl DerefMutfor Diag<'_> {
384fn deref_mut(&mut self) -> &mut DiagInner {
385self.diag.as_mut().unwrap()
386 }
387}
388389impl Debugfor Diag<'_> {
390fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391self.diag.fmt(f)
392 }
393}
394395/// `Diag` impls many `&mut self -> &mut Self` methods. Each one modifies an
396/// existing diagnostic, either in a standalone fashion, e.g.
397/// `err.code(code);`, or in a chained fashion to make multiple modifications,
398/// e.g. `err.code(code).span(span);`.
399///
400/// This macro creates an equivalent `self -> Self` method, with a `with_`
401/// prefix. This can be used in a chained fashion when making a new diagnostic,
402/// e.g. `let err = struct_err(msg).with_code(code);`, or emitting a new
403/// diagnostic, e.g. `struct_err(msg).with_code(code).emit();`.
404///
405/// Although the latter method can be used to modify an existing diagnostic,
406/// e.g. `err = err.with_code(code);`, this should be avoided because the former
407/// method gives shorter code, e.g. `err.code(code);`.
408///
409/// Note: the `with_` methods are added only when needed. If you want to use
410/// one and it's not defined, feel free to add it.
411///
412/// Note: any doc comments must be within the `with_fn!` call.
413macro_rules!with_fn {
414 {
415$with_f:ident,
416 $(#[$attrs:meta])*
417pub fn $f:ident(&mut $self:ident, $($name:ident: $ty:ty),* $(,)?) -> &mut Self {
418 $($body:tt)*
419 }
420 } => {
421// The original function.
422$(#[$attrs])*
423pub fn $f(&mut $self, $($name: $ty),*) -> &mut Self {
424 $($body)*
425 }
426427// The `with_*` variant.
428$(#[$attrs])*
429#[doc = concat!("See [`Diag::", stringify!($f), "()`].")]
430pub fn $with_f(mut $self, $($name: $ty),*) -> Self {
431$self.$f($($name),*);
432$self
433}
434 };
435}
436437impl<'a> Diag<'a> {
438#[track_caller]
439pub fn new(dcx: DiagCtxtHandle<'a>, level: Level, message: impl Into<DiagMessage>) -> Self {
440Self::new_diagnostic(dcx, DiagInner::new(level, message))
441 }
442443/// Allow moving diagnostics between different error tainting contexts
444pub fn with_dcx(mut self, dcx: DiagCtxtHandle<'_>) -> Diag<'_> {
445Diag { dcx, diag: self.diag.take() }
446 }
447448/// Creates a new `Diag` with an already constructed diagnostic.
449#[track_caller]
450pub(crate) fn new_diagnostic(dcx: DiagCtxtHandle<'a>, diag: DiagInner) -> Self {
451{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_errors/src/diagnostic.rs:451",
"rustc_errors::diagnostic", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_errors/src/diagnostic.rs"),
::tracing_core::__macro_support::Option::Some(451u32),
::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");
452Self { dcx, diag: Some(Box::new(diag)) }
453 }
454455/// Delay emission of this diagnostic as a bug.
456 ///
457 /// This can be useful in contexts where an error indicates a bug but
458 /// typically this only happens when other compilation errors have already
459 /// happened. In those cases this can be used to defer emission of this
460 /// diagnostic as a bug in the compiler only if no other errors have been
461 /// emitted.
462 ///
463 /// In the meantime, though, callsites are required to deal with the "bug"
464 /// locally in whichever way makes the most sense.
465#[track_caller]
466pub fn downgrade_to_delayed_bug(&mut self) {
467if !#[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!(
468matches!(self.level, Level::Error | Level::DelayedBug),
469"downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
470self.level
471 );
472self.level = Level::DelayedBug;
473 }
474475/// Make emitting this diagnostic fatal.
476#[track_caller]
477pub fn upgrade_to_fatal(mut self) -> Diag<'a> {
478if !#[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!(
479matches!(self.level, Level::Error),
480"upgrade_to_fatal: cannot upgrade {:?} to Fatal: not an error",
481self.level
482 );
483self.level = Level::Fatal;
484485// Take is okay since we immediately rewrap it in another diagnostic.
486 // i.e. we do emit it despite defusing the original diagnostic's drop bomb.
487let diag = self.diag.take();
488Diag { dcx: self.dcx, diag }
489 }
490491#[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."]
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,
492/// Appends a labeled span to the diagnostic.
493 ///
494 /// Labels are used to convey additional context for the diagnostic's primary span. They will
495 /// be shown together with the original diagnostic's span, *not* with spans added by
496 /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
497 /// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
498 /// either.
499 ///
500 /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
501 /// the diagnostic was constructed. However, the label span is *not* considered a
502 /// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
503 /// primary.
504pub fn span_label(&mut self, span: Span, label: impl Into<DiagMessage>) -> &mut Self {
505self.span.push_span_label(span, label.into());
506self
507} }508509pub 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,
510pub fn span_context(&mut self, span: Span) -> &mut Self {
511self.span.push_span_context(span);
512self
513} }514515#[doc = r" Labels all the given spans with the provided label."]
#[doc = r" See [`Self::span_label()`] for more information."]
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,
516/// Labels all the given spans with the provided label.
517 /// See [`Self::span_label()`] for more information.
518pub fn span_labels(&mut self, spans: impl IntoIterator<Item = Span>, label: &str) -> &mut Self {
519for span in spans {
520self.span_label(span, label.to_string());
521 }
522self
523} }524525pub fn replace_span_with(&mut self, after: Span, keep_label: bool) -> &mut Self {
526let before = self.span.clone();
527self.span(after);
528for span_label in before.span_labels() {
529if let Some(label) = span_label.label {
530if span_label.is_primary && keep_label {
531self.span.push_span_label(after, label);
532 } else {
533self.span.push_span_label(span_label.span, label);
534 }
535 }
536 }
537self538 }
539540pub fn note_expected_found(
541&mut self,
542 expected_label: &str,
543 expected: DiagStyledString,
544 found_label: &str,
545 found: DiagStyledString,
546 ) -> &mut Self {
547self.note_expected_found_extra(
548expected_label,
549expected,
550found_label,
551found,
552DiagStyledString::normal(""),
553DiagStyledString::normal(""),
554 )
555 }
556557pub fn note_expected_found_extra(
558&mut self,
559 expected_label: &str,
560 expected: DiagStyledString,
561 found_label: &str,
562 found: DiagStyledString,
563 expected_extra: DiagStyledString,
564 found_extra: DiagStyledString,
565 ) -> &mut Self {
566let expected_label = expected_label.to_string();
567let expected_label = if expected_label.is_empty() {
568"expected".to_string()
569 } else {
570::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}", expected_label))
})format!("expected {expected_label}")571 };
572let found_label = found_label.to_string();
573let found_label = if found_label.is_empty() {
574"found".to_string()
575 } else {
576::alloc::__export::must_use({
::alloc::fmt::format(format_args!("found {0}", found_label))
})format!("found {found_label}")577 };
578let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
579 (expected_label.len() - found_label.len(), 0)
580 } else {
581 (0, found_label.len() - expected_label.len())
582 };
583let 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!(
584"{}{} `",
585" ".repeat(expected_padding),
586 expected_label
587 ))];
588msg.extend(expected.0);
589msg.push(StringPart::normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("`")) })format!("`")));
590msg.extend(expected_extra.0);
591msg.push(StringPart::normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("\n")) })format!("\n")));
592msg.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)));
593msg.extend(found.0);
594msg.push(StringPart::normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("`")) })format!("`")));
595msg.extend(found_extra.0);
596597// For now, just attach these as notes.
598self.highlighted_note(msg);
599self600 }
601602pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
603self.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![
604 StringPart::normal(format!("`{name}` from trait: `")),
605 StringPart::highlighted(signature),
606 StringPart::normal("`"),
607 ]);
608self609 }
610611#[doc = r" Add a note attached to this diagnostic."]
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,
612/// Add a note attached to this diagnostic.
613pub fn note(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
614self.sub(Sublevel::Note, msg, MultiSpan::new());
615self
616} }617618pub fn highlighted_note(&mut self, msg: Vec<StringPart>) -> &mut Self {
619self.sub_with_highlights(Sublevel::Note, msg, MultiSpan::new());
620self621 }
622623pub fn highlighted_span_note(
624&mut self,
625 span: impl Into<MultiSpan>,
626 msg: Vec<StringPart>,
627 ) -> &mut Self {
628self.sub_with_highlights(Sublevel::Note, msg, span.into());
629self630 }
631632/// This is like [`Diag::note()`], but it's only printed once.
633pub fn note_once(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
634self.sub(Sublevel::OnceNote, msg, MultiSpan::new());
635self636 }
637638#[doc = r" Prints the span with a note above it."]
#[doc = r" This is like [`Diag::note()`], but it gets its own span."]
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,
639/// Prints the span with a note above it.
640 /// This is like [`Diag::note()`], but it gets its own span.
641pub fn span_note(
642&mut self,
643 sp: impl Into<MultiSpan>,
644 msg: impl Into<DiagMessage>,
645 ) -> &mut Self {
646self.sub(Sublevel::Note, msg, sp.into());
647self
648} }649650/// Prints the span with a note above it.
651 /// This is like [`Diag::note_once()`], but it gets its own span.
652pub fn span_note_once<S: Into<MultiSpan>>(
653&mut self,
654 sp: S,
655 msg: impl Into<DiagMessage>,
656 ) -> &mut Self {
657self.sub(Sublevel::OnceNote, msg, sp.into());
658self659 }
660661#[doc = r" Add a warning attached to this diagnostic."]
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,
662/// Add a warning attached to this diagnostic.
663pub fn warn(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
664self.sub(Sublevel::Warning, msg, MultiSpan::new());
665self
666} }667668/// Prints the span with a warning above it.
669 /// This is like [`Diag::warn()`], but it gets its own span.
670pub fn span_warn<S: Into<MultiSpan>>(
671&mut self,
672 sp: S,
673 msg: impl Into<DiagMessage>,
674 ) -> &mut Self {
675self.sub(Sublevel::Warning, msg, sp.into());
676self677 }
678679#[doc = r" Add a help message attached to this diagnostic."]
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,
680/// Add a help message attached to this diagnostic.
681pub fn help(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
682self.sub(Sublevel::Help, msg, MultiSpan::new());
683self
684} }685686/// This is like [`Diag::help()`], but it's only printed once.
687pub fn help_once(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
688self.sub(Sublevel::OnceHelp, msg, MultiSpan::new());
689self690 }
691692/// Add a help message attached to this diagnostic with a customizable highlighted message.
693pub fn highlighted_help(&mut self, msg: Vec<StringPart>) -> &mut Self {
694self.sub_with_highlights(Sublevel::Help, msg, MultiSpan::new());
695self696 }
697698/// Add a help message attached to this diagnostic with a customizable highlighted message.
699pub fn highlighted_span_help(
700&mut self,
701 span: impl Into<MultiSpan>,
702 msg: Vec<StringPart>,
703 ) -> &mut Self {
704self.sub_with_highlights(Sublevel::Help, msg, span.into());
705self706 }
707708#[doc = r" Prints the span with some help above it."]
#[doc = r" This is like [`Diag::help()`], but it gets its own span."]
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,
709/// Prints the span with some help above it.
710 /// This is like [`Diag::help()`], but it gets its own span.
711pub fn span_help(
712&mut self,
713 sp: impl Into<MultiSpan>,
714 msg: impl Into<DiagMessage>,
715 ) -> &mut Self {
716self.sub(Sublevel::Help, msg, sp.into());
717self
718} }719720/// Disallow attaching suggestions to this diagnostic.
721 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
722 /// (before and after the call to `disable_suggestions`) will be ignored.
723pub fn disable_suggestions(&mut self) -> &mut Self {
724self.suggestions = Suggestions::Disabled;
725self726 }
727728/// Prevent new suggestions from being added to this diagnostic.
729 ///
730 /// Suggestions added before the call to `.seal_suggestions()` will be preserved
731 /// and new suggestions will be ignored.
732pub fn seal_suggestions(&mut self) -> &mut Self {
733if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
734let suggestions_slice = std::mem::take(suggestions).into_boxed_slice();
735self.suggestions = Suggestions::Sealed(suggestions_slice);
736 }
737self738 }
739740/// Helper for pushing to `self.suggestions`.
741 ///
742 /// A new suggestion is added if suggestions are enabled for this diagnostic.
743 /// Otherwise, they are ignored.
744fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
745for subst in &suggestion.substitutions {
746for part in &subst.parts {
747let span = part.span;
748let call_site = span.ctxt().outer_expn_data().call_site;
749if span.in_derive_expansion() && span.overlaps_or_adjacent(call_site) {
750// Ignore if spans is from derive macro.
751return;
752 }
753 }
754 }
755756if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
757suggestions.push(suggestion);
758 }
759 }
760761#[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."]
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,
762/// Show a suggestion that has multiple parts to it, always as its own subdiagnostic.
763 /// In other words, multiple changes need to be applied as part of this suggestion.
764pub fn multipart_suggestion(
765&mut self,
766 msg: impl Into<DiagMessage>,
767 suggestion: Vec<(Span, String)>,
768 applicability: Applicability,
769 ) -> &mut Self {
770self.multipart_suggestion_with_style(
771 msg,
772 suggestion,
773 applicability,
774 SuggestionStyle::ShowAlways,
775 )
776 } }777778/// [`Diag::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
779pub fn multipart_suggestion_with_style(
780&mut self,
781 msg: impl Into<DiagMessage>,
782mut suggestion: Vec<(Span, String)>,
783 applicability: Applicability,
784 style: SuggestionStyle,
785 ) -> &mut Self {
786let mut seen = crate::FxHashSet::default();
787suggestion.retain(|(span, msg)| seen.insert((span.lo(), span.hi(), msg.clone())));
788789let parts = suggestion790 .into_iter()
791 .map(|(span, snippet)| SubstitutionPart { snippet, span })
792 .collect::<Vec<_>>();
793794if !!parts.is_empty() {
::core::panicking::panic("assertion failed: !parts.is_empty()")
};assert!(!parts.is_empty());
795if 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!(
796 parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()),
797None,
798"Span must not be empty and have no suggestion",
799 );
800if 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!(
801 parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
802None,
803"suggestion must not have overlapping parts",
804 );
805806self.push_suggestion(CodeSuggestion {
807 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 }],
808 msg: msg.into(),
809style,
810applicability,
811 });
812self813 }
814815/// Prints out a message with for a multipart suggestion without showing the suggested code.
816 ///
817 /// This is intended to be used for suggestions that are obvious in what the changes need to
818 /// be from the message, showing the span label inline would be visually unpleasant
819 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
820 /// improve understandability.
821pub fn tool_only_multipart_suggestion(
822&mut self,
823 msg: impl Into<DiagMessage>,
824 suggestion: Vec<(Span, String)>,
825 applicability: Applicability,
826 ) -> &mut Self {
827self.multipart_suggestion_with_style(
828msg,
829suggestion,
830applicability,
831 SuggestionStyle::CompletelyHidden,
832 )
833 }
834835#[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."]
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,
836/// Prints out a message with a suggested edit of the code.
837 ///
838 /// In case of short messages and a simple suggestion, rustc displays it as a label:
839 ///
840 /// ```text
841 /// try adding parentheses: `(tup.0).1`
842 /// ```
843 ///
844 /// The message
845 ///
846 /// * should not end in any punctuation (a `:` is added automatically)
847 /// * should not be a question (avoid language like "did you mean")
848 /// * should not contain any phrases like "the following", "as shown", etc.
849 /// * may look like "to do xyz, use" or "to do xyz, use abc"
850 /// * may contain a name of a function, variable, or type, but not whole expressions
851 ///
852 /// See [`CodeSuggestion`] for more information.
853pub fn span_suggestion(
854&mut self,
855 sp: Span,
856 msg: impl Into<DiagMessage>,
857 suggestion: impl ToString,
858 applicability: Applicability,
859 ) -> &mut Self {
860self.span_suggestion_with_style(
861 sp,
862 msg,
863 suggestion,
864 applicability,
865 SuggestionStyle::ShowCode,
866 );
867self
868} }869870#[doc =
r" [`Diag::span_suggestion()`] but you can set the [`SuggestionStyle`]."]
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,
871/// [`Diag::span_suggestion()`] but you can set the [`SuggestionStyle`].
872pub fn span_suggestion_with_style(
873&mut self,
874 sp: Span,
875 msg: impl Into<DiagMessage>,
876 suggestion: impl ToString,
877 applicability: Applicability,
878 style: SuggestionStyle,
879 ) -> &mut Self {
880debug_assert!(
881 !(sp.is_empty() && suggestion.to_string().is_empty()),
882"Span must not be empty and have no suggestion"
883);
884self.push_suggestion(CodeSuggestion {
885 substitutions: vec![Substitution {
886 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
887 }],
888 msg: msg.into(),
889 style,
890 applicability,
891 });
892self
893} }894895#[doc = r" Always show the suggested change."]
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,
896/// Always show the suggested change.
897pub fn span_suggestion_verbose(
898&mut self,
899 sp: Span,
900 msg: impl Into<DiagMessage>,
901 suggestion: impl ToString,
902 applicability: Applicability,
903 ) -> &mut Self {
904self.span_suggestion_with_style(
905 sp,
906 msg,
907 suggestion,
908 applicability,
909 SuggestionStyle::ShowAlways,
910 );
911self
912} }913914#[doc = r" Prints out a message with multiple suggested edits of the code."]
#[doc = r" See also [`Diag::span_suggestion()`]."]
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,
915/// Prints out a message with multiple suggested edits of the code.
916 /// See also [`Diag::span_suggestion()`].
917pub fn span_suggestions(
918&mut self,
919 sp: Span,
920 msg: impl Into<DiagMessage>,
921 suggestions: impl IntoIterator<Item = String>,
922 applicability: Applicability,
923 ) -> &mut Self {
924self.span_suggestions_with_style(
925 sp,
926 msg,
927 suggestions,
928 applicability,
929 SuggestionStyle::ShowAlways,
930 )
931 } }932933pub fn span_suggestions_with_style(
934&mut self,
935 sp: Span,
936 msg: impl Into<DiagMessage>,
937 suggestions: impl IntoIterator<Item = String>,
938 applicability: Applicability,
939 style: SuggestionStyle,
940 ) -> &mut Self {
941let substitutions = suggestions942 .into_iter()
943 .map(|snippet| {
944if 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!(
945 !(sp.is_empty() && snippet.is_empty()),
946"Span `{sp:?}` must not be empty and have no suggestion"
947);
948Substitution { 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 }] }
949 })
950 .collect();
951self.push_suggestion(CodeSuggestion {
952substitutions,
953 msg: msg.into(),
954style,
955applicability,
956 });
957self958 }
959960/// Prints out a message with multiple suggested edits of the code, where each edit consists of
961 /// multiple parts.
962 /// See also [`Diag::multipart_suggestion()`].
963pub fn multipart_suggestions(
964&mut self,
965 msg: impl Into<DiagMessage>,
966 suggestions: impl IntoIterator<Item = Vec<(Span, String)>>,
967 applicability: Applicability,
968 ) -> &mut Self {
969let substitutions = suggestions970 .into_iter()
971 .map(|sugg| {
972let mut parts = sugg973 .into_iter()
974 .map(|(span, snippet)| SubstitutionPart { snippet, span })
975 .collect::<Vec<_>>();
976977parts.sort_unstable_by_key(|part| part.span.lo_hi());
978979if !!parts.is_empty() {
::core::panicking::panic("assertion failed: !parts.is_empty()")
};assert!(!parts.is_empty());
980if 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!(
981 parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()),
982None,
983"Span must not be empty and have no suggestion",
984 );
985if 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!(
986 parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
987None,
988"suggestion must not have overlapping parts",
989 );
990991Substitution { parts }
992 })
993 .collect();
994995self.push_suggestion(CodeSuggestion {
996substitutions,
997 msg: msg.into(),
998 style: SuggestionStyle::ShowAlways,
999applicability,
1000 });
1001self1002 }
10031004#[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."]
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,
1005/// Prints out a message with a suggested edit of the code. If the suggestion is presented
1006 /// inline, it will only show the message and not the suggestion.
1007 ///
1008 /// See [`CodeSuggestion`] for more information.
1009pub fn span_suggestion_short(
1010&mut self,
1011 sp: Span,
1012 msg: impl Into<DiagMessage>,
1013 suggestion: impl ToString,
1014 applicability: Applicability,
1015 ) -> &mut Self {
1016self.span_suggestion_with_style(
1017 sp,
1018 msg,
1019 suggestion,
1020 applicability,
1021 SuggestionStyle::HideCodeInline,
1022 );
1023self
1024} }10251026/// Prints out a message for a suggestion without showing the suggested code.
1027 ///
1028 /// This is intended to be used for suggestions that are obvious in what the changes need to
1029 /// be from the message, showing the span label inline would be visually unpleasant
1030 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
1031 /// improve understandability.
1032pub fn span_suggestion_hidden(
1033&mut self,
1034 sp: Span,
1035 msg: impl Into<DiagMessage>,
1036 suggestion: impl ToString,
1037 applicability: Applicability,
1038 ) -> &mut Self {
1039self.span_suggestion_with_style(
1040sp,
1041msg,
1042suggestion,
1043applicability,
1044 SuggestionStyle::HideCodeAlways,
1045 );
1046self1047 }
10481049#[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."]
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,
1050/// Adds a suggestion to the JSON output that will not be shown in the CLI.
1051 ///
1052 /// This is intended to be used for suggestions that are *very* obvious in what the changes
1053 /// need to be from the message, but we still want other tools to be able to apply them.
1054pub fn tool_only_span_suggestion(
1055&mut self,
1056 sp: Span,
1057 msg: impl Into<DiagMessage>,
1058 suggestion: impl ToString,
1059 applicability: Applicability,
1060 ) -> &mut Self {
1061self.span_suggestion_with_style(
1062 sp,
1063 msg,
1064 suggestion,
1065 applicability,
1066 SuggestionStyle::CompletelyHidden,
1067 );
1068self
1069} }10701071/// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
1072 /// [rustc_macros::Subdiagnostic]). Performs eager formatting of any messages
1073 /// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of
1074 /// interpolated variables).
1075pub fn subdiagnostic(&mut self, subdiagnostic: impl Subdiagnostic) -> &mut Self {
1076subdiagnostic.add_to_diag(self);
1077self1078 }
10791080#[doc = r" Add a 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,
1081/// Add a span.
1082pub fn span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self {
1083self.span = sp.into();
1084self
1085} }10861087pub fn is_lint(
1088&mut self,
1089 name: String,
1090 has_future_breakage: bool,
1091 rust_version: Option<RustcVersion>,
1092 ) -> &mut Self {
1093self.is_lint = Some(IsLint { name, has_future_breakage, rust_version });
1094self1095 }
10961097#[doc = r" Add an error 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,
1098/// Add an error code.
1099pub fn code(&mut self, code: ErrCode) -> &mut Self {
1100self.code = Some(code);
1101self
1102} }11031104#[doc = r" Add a 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,
1105/// Add a primary message.
1106pub fn primary_message(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
1107self.messages[0] = (msg.into(), Style::NoStyle);
1108self
1109} }11101111#[doc = r" Add an argument."]
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,
1112/// Add an argument.
1113pub fn arg(
1114&mut self,
1115 name: impl Into<DiagArgName>,
1116 arg: impl IntoDiagArg,
1117 ) -> &mut Self {
1118self.deref_mut().arg(name, arg);
1119self
1120} }11211122/// Convenience function for internal use, clients should use one of the
1123 /// public methods above.
1124 ///
1125 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
1126pub fn sub(&mut self, level: Sublevel, message: impl Into<DiagMessage>, span: MultiSpan) {
1127self.deref_mut().sub(level, message, span);
1128 }
11291130/// Convenience function for internal use, clients should use one of the
1131 /// public methods above.
1132fn sub_with_highlights(&mut self, level: Sublevel, messages: Vec<StringPart>, span: MultiSpan) {
1133let messages = messages.into_iter().map(|m| (m.content.into(), m.style)).collect();
1134let sub = Subdiag { level, messages, span };
1135self.children.push(sub);
1136 }
11371138/// Takes the diagnostic. For use by methods that consume the Diag: `emit`,
1139 /// `cancel`, etc. Afterwards, `drop` is the only code that will be run on
1140 /// `self`.
1141fn take_diag(&mut self) -> DiagInner {
1142if let Some(path) = &self.long_ty_path {
1143self.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the full name for the type has been written to \'{0}\'",
path.display()))
})format!(
1144"the full name for the type has been written to '{}'",
1145 path.display()
1146 ));
1147self.note("consider using `--verbose` to print the full type name to the console");
1148 }
1149*self.diag.take().unwrap()
1150 }
11511152/// This method allows us to access the path of the file where "long types" are written to.
1153 ///
1154 /// When calling `Diag::emit`, as part of that we will check if a `long_ty_path` has been set,
1155 /// and if it has been then we add a note mentioning the file where the "long types" were
1156 /// written to.
1157 ///
1158 /// When calling `tcx.short_string()` after a `Diag` is constructed, the preferred way of doing
1159 /// so is `tcx.short_string(ty, diag.long_ty_path())`. The diagnostic itself is the one that
1160 /// keeps the existence of a "long type" anywhere in the diagnostic, so the note telling the
1161 /// user where we wrote the file to is only printed once at most, *and* it makes it much harder
1162 /// to forget to set it.
1163 ///
1164 /// If the diagnostic hasn't been created before a "short ty string" is created, then you should
1165 /// ensure that this method is called to set it `*diag.long_ty_path() = path`.
1166 ///
1167 /// As a rule of thumb, if you see or add at least one `tcx.short_string()` call anywhere, in a
1168 /// scope, `diag.long_ty_path()` should be called once somewhere close by.
1169pub fn long_ty_path(&mut self) -> &mut Option<PathBuf> {
1170&mut self.long_ty_path
1171 }
11721173pub fn with_long_ty_path(mut self, long_ty_path: Option<PathBuf>) -> Self {
1174self.long_ty_path = long_ty_path;
1175self1176 }
11771178/// Emit the diagnostic. Will also abort appropriately if the level is `Bug` or `Fatal`.
1179#[track_caller]
1180pub fn emit(mut self) {
1181let level = self.level; // get level before taking the inner diag
1182let diag = self.take_diag();
1183self.dcx.emit_diagnostic(diag);
11841185match level {
1186 Level::Bug => panic::panic_any(ExplicitBug),
1187 Level::Fatal => crate::FatalError.raise(),
1188_ => {}
1189 }
1190 }
11911192/// Use this on a `Bug` diagnostic if you need the `!` return type. Otherwise `emit` suffices.
1193 /// Aborts if used on a non-`Bug` diagnostic.
1194#[track_caller]
1195pub fn emit_bug(self) -> ! {
1196{
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);
1197self.emit();
1198::core::panicking::unreachable_default_msg();unreachable!(); // `emit` will have aborted
1199}
12001201/// Use this on a `Fatal` diagnostic if you need the `!` return type. Otherwise `emit`
1202 /// suffices. Aborts if used on a non-`Fatal` diagnostic.
1203#[track_caller]
1204pub fn emit_fatal(self) -> ! {
1205{
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);
1206self.emit();
1207::core::panicking::unreachable_default_msg();unreachable!(); // `emit` will have aborted
1208}
12091210/// Use this on an `Error`/`DelayedBug` diagnostic if you need the `ErrorGuaranteed` return
1211 /// type. Otherwise `emit` suffices. Aborts if used on a non-`Error`/`DelayedBug` diagnostic.
1212#[track_caller]
1213pub fn emit_err(mut self) -> ErrorGuaranteed {
1214let diag = self.take_diag();
12151216// The only error levels that should reach here are `Error` and `DelayedBug`.
1217 // (Also, even though `level` isn't `pub`, the whole `DiagInner` could
1218 // be overwritten with a new one thanks to `DerefMut`. So this assert
1219 // protects against that, too.)
1220if !#[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!(
1221matches!(diag.level, Level::Error | Level::DelayedBug),
1222"invalid diagnostic level ({:?})",
1223 diag.level,
1224 );
12251226let guar = self.dcx.emit_diagnostic(diag);
1227guar.unwrap()
1228 }
12291230/// Emit the diagnostic unless `delay` is true,
1231 /// in which case the emission will be delayed as a bug.
1232 ///
1233 /// See `emit` and `delay_as_bug` for details.
1234#[track_caller]
1235pub fn emit_err_unless_delay(mut self, delay: bool) -> ErrorGuaranteed {
1236if delay {
1237self.downgrade_to_delayed_bug();
1238 }
1239self.emit_err()
1240 }
12411242/// Cancel and consume the diagnostic. (A diagnostic must either be emitted or
1243 /// cancelled or it will panic when dropped).
1244pub fn cancel(mut self) {
1245self.diag = None;
1246drop(self);
1247 }
12481249/// Cancels this diagnostic and returns its first message, if it exists.
1250pub fn cancel_into_message(self) -> Option<String> {
1251let s = self.diag.as_ref()?.messages.get(0)?.0.as_str().map(ToString::to_string);
1252self.cancel();
1253s1254 }
12551256/// See `DiagCtxtHandle::stash_diagnostic` for details.
1257pub fn stash(mut self, span: Span, key: StashKey) -> Option<ErrorGuaranteed> {
1258let diag = self.take_diag();
1259self.dcx.stash_diagnostic(span, key, diag)
1260 }
12611262/// Delay emission of this diagnostic as a bug.
1263 ///
1264 /// This can be useful in contexts where an error indicates a bug but
1265 /// typically this only happens when other compilation errors have already
1266 /// happened. In those cases this can be used to defer emission of this
1267 /// diagnostic as a bug in the compiler only if no other errors have been
1268 /// emitted.
1269 ///
1270 /// In the meantime, though, callsites are required to deal with the "bug"
1271 /// locally in whichever way makes the most sense.
1272#[track_caller]
1273pub fn delay_as_bug(mut self) -> ErrorGuaranteed {
1274self.downgrade_to_delayed_bug();
1275self.emit_err()
1276 }
1277}
12781279/// Destructor bomb: every `Diag` must be consumed (emitted, cancelled, etc.)
1280/// or we emit a bug.
1281impl Dropfor Diag<'_> {
1282fn drop(&mut self) {
1283match self.diag.take() {
1284Some(diag) if !panicking() => {
1285self.dcx.emit_diagnostic(DiagInner::new(
1286 Level::Bug,
1287DiagMessage::from("the following error was constructed but not emitted"),
1288 ));
1289self.dcx.emit_diagnostic(*diag);
1290{
::core::panicking::panic_fmt(format_args!("error was constructed but not emitted"));
};panic!("error was constructed but not emitted");
1291 }
1292_ => {}
1293 }
1294 }
1295}
12961297#[macro_export]
1298macro_rules!struct_span_code_err {
1299 ($dcx:expr, $span:expr, $code:expr, $($message:tt)*) => ({
1300$dcx.struct_span_err($span, format!($($message)*)).with_code($code)
1301 })
1302}