]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_errors/src/diagnostic_builder.rs
New upstream version 1.60.0+dfsg1
[rustc.git] / compiler / rustc_errors / src / diagnostic_builder.rs
1 use crate::{Diagnostic, DiagnosticId, DiagnosticStyledString};
2 use crate::{Handler, Level, StashKey};
3 use rustc_lint_defs::Applicability;
4
5 use rustc_span::{MultiSpan, Span};
6 use std::fmt::{self, Debug};
7 use std::ops::{Deref, DerefMut};
8 use std::thread::panicking;
9 use tracing::debug;
10
11 /// Used for emitting structured error messages and other diagnostic information.
12 ///
13 /// If there is some state in a downstream crate you would like to
14 /// access in the methods of `DiagnosticBuilder` here, consider
15 /// extending `HandlerFlags`, accessed via `self.handler.flags`.
16 #[must_use]
17 #[derive(Clone)]
18 pub struct DiagnosticBuilder<'a> {
19 handler: &'a Handler,
20
21 /// `Diagnostic` is a large type, and `DiagnosticBuilder` is often used as a
22 /// return value, especially within the frequently-used `PResult` type.
23 /// In theory, return value optimization (RVO) should avoid unnecessary
24 /// copying. In practice, it does not (at the time of writing).
25 diagnostic: Box<Diagnostic>,
26 }
27
28 /// In general, the `DiagnosticBuilder` uses deref to allow access to
29 /// the fields and methods of the embedded `diagnostic` in a
30 /// transparent way. *However,* many of the methods are intended to
31 /// be used in a chained way, and hence ought to return `self`. In
32 /// that case, we can't just naively forward to the method on the
33 /// `diagnostic`, because the return type would be a `&Diagnostic`
34 /// instead of a `&DiagnosticBuilder<'a>`. This `forward!` macro makes
35 /// it easy to declare such methods on the builder.
36 macro_rules! forward {
37 // Forward pattern for &self -> &Self
38 (
39 $(#[$attrs:meta])*
40 pub fn $n:ident(&self, $($name:ident: $ty:ty),* $(,)?) -> &Self
41 ) => {
42 $(#[$attrs])*
43 #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
44 pub fn $n(&self, $($name: $ty),*) -> &Self {
45 self.diagnostic.$n($($name),*);
46 self
47 }
48 };
49
50 // Forward pattern for &mut self -> &mut Self
51 (
52 $(#[$attrs:meta])*
53 pub fn $n:ident(&mut self, $($name:ident: $ty:ty),* $(,)?) -> &mut Self
54 ) => {
55 $(#[$attrs])*
56 #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
57 pub fn $n(&mut self, $($name: $ty),*) -> &mut Self {
58 self.diagnostic.$n($($name),*);
59 self
60 }
61 };
62
63 // Forward pattern for &mut self -> &mut Self, with generic parameters.
64 (
65 $(#[$attrs:meta])*
66 pub fn $n:ident<$($generic:ident: $bound:path),*>(
67 &mut self,
68 $($name:ident: $ty:ty),*
69 $(,)?
70 ) -> &mut Self
71 ) => {
72 $(#[$attrs])*
73 #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
74 pub fn $n<$($generic: $bound),*>(&mut self, $($name: $ty),*) -> &mut Self {
75 self.diagnostic.$n($($name),*);
76 self
77 }
78 };
79 }
80
81 impl<'a> Deref for DiagnosticBuilder<'a> {
82 type Target = Diagnostic;
83
84 fn deref(&self) -> &Diagnostic {
85 &self.diagnostic
86 }
87 }
88
89 impl<'a> DerefMut for DiagnosticBuilder<'a> {
90 fn deref_mut(&mut self) -> &mut Diagnostic {
91 &mut self.diagnostic
92 }
93 }
94
95 impl<'a> DiagnosticBuilder<'a> {
96 /// Emit the diagnostic.
97 pub fn emit(&mut self) {
98 self.handler.emit_diagnostic(&self);
99 self.cancel();
100 }
101
102 /// Emit the diagnostic unless `delay` is true,
103 /// in which case the emission will be delayed as a bug.
104 ///
105 /// See `emit` and `delay_as_bug` for details.
106 pub fn emit_unless(&mut self, delay: bool) {
107 if delay {
108 self.delay_as_bug();
109 } else {
110 self.emit();
111 }
112 }
113
114 /// Stashes diagnostic for possible later improvement in a different,
115 /// later stage of the compiler. The diagnostic can be accessed with
116 /// the provided `span` and `key` through [`Handler::steal_diagnostic()`].
117 ///
118 /// As with `buffer`, this is unless the handler has disabled such buffering.
119 pub fn stash(self, span: Span, key: StashKey) {
120 if let Some((diag, handler)) = self.into_diagnostic() {
121 handler.stash_diagnostic(span, key, diag);
122 }
123 }
124
125 /// Converts the builder to a `Diagnostic` for later emission,
126 /// unless handler has disabled such buffering.
127 pub fn into_diagnostic(mut self) -> Option<(Diagnostic, &'a Handler)> {
128 if self.handler.flags.dont_buffer_diagnostics
129 || self.handler.flags.treat_err_as_bug.is_some()
130 {
131 self.emit();
132 return None;
133 }
134
135 let handler = self.handler;
136
137 // We must use `Level::Cancelled` for `dummy` to avoid an ICE about an
138 // unused diagnostic.
139 let dummy = Diagnostic::new(Level::Cancelled, "");
140 let diagnostic = std::mem::replace(&mut *self.diagnostic, dummy);
141
142 // Logging here is useful to help track down where in logs an error was
143 // actually emitted.
144 debug!("buffer: diagnostic={:?}", diagnostic);
145
146 Some((diagnostic, handler))
147 }
148
149 /// Buffers the diagnostic for later emission,
150 /// unless handler has disabled such buffering.
151 pub fn buffer(self, buffered_diagnostics: &mut Vec<Diagnostic>) {
152 buffered_diagnostics.extend(self.into_diagnostic().map(|(diag, _)| diag));
153 }
154
155 /// Delay emission of this diagnostic as a bug.
156 ///
157 /// This can be useful in contexts where an error indicates a bug but
158 /// typically this only happens when other compilation errors have already
159 /// happened. In those cases this can be used to defer emission of this
160 /// diagnostic as a bug in the compiler only if no other errors have been
161 /// emitted.
162 ///
163 /// In the meantime, though, callsites are required to deal with the "bug"
164 /// locally in whichever way makes the most sense.
165 pub fn delay_as_bug(&mut self) {
166 self.level = Level::Bug;
167 self.handler.delay_as_bug((*self.diagnostic).clone());
168 self.cancel();
169 }
170
171 /// Appends a labeled span to the diagnostic.
172 ///
173 /// Labels are used to convey additional context for the diagnostic's primary span. They will
174 /// be shown together with the original diagnostic's span, *not* with spans added by
175 /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
176 /// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
177 /// either.
178 ///
179 /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
180 /// the diagnostic was constructed. However, the label span is *not* considered a
181 /// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
182 /// primary.
183 pub fn span_label(&mut self, span: Span, label: impl Into<String>) -> &mut Self {
184 self.diagnostic.span_label(span, label);
185 self
186 }
187
188 /// Labels all the given spans with the provided label.
189 /// See [`Diagnostic::span_label()`] for more information.
190 pub fn span_labels(
191 &mut self,
192 spans: impl IntoIterator<Item = Span>,
193 label: impl AsRef<str>,
194 ) -> &mut Self {
195 let label = label.as_ref();
196 for span in spans {
197 self.diagnostic.span_label(span, label);
198 }
199 self
200 }
201
202 forward!(pub fn note_expected_found(
203 &mut self,
204 expected_label: &dyn fmt::Display,
205 expected: DiagnosticStyledString,
206 found_label: &dyn fmt::Display,
207 found: DiagnosticStyledString,
208 ) -> &mut Self);
209
210 forward!(pub fn note_expected_found_extra(
211 &mut self,
212 expected_label: &dyn fmt::Display,
213 expected: DiagnosticStyledString,
214 found_label: &dyn fmt::Display,
215 found: DiagnosticStyledString,
216 expected_extra: &dyn fmt::Display,
217 found_extra: &dyn fmt::Display,
218 ) -> &mut Self);
219
220 forward!(pub fn note_unsuccessful_coercion(
221 &mut self,
222 expected: DiagnosticStyledString,
223 found: DiagnosticStyledString,
224 ) -> &mut Self);
225
226 forward!(pub fn note(&mut self, msg: &str) -> &mut Self);
227 forward!(pub fn span_note<S: Into<MultiSpan>>(
228 &mut self,
229 sp: S,
230 msg: &str,
231 ) -> &mut Self);
232 forward!(pub fn warn(&mut self, msg: &str) -> &mut Self);
233 forward!(pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self);
234 forward!(pub fn help(&mut self, msg: &str) -> &mut Self);
235 forward!(pub fn span_help<S: Into<MultiSpan>>(
236 &mut self,
237 sp: S,
238 msg: &str,
239 ) -> &mut Self);
240 forward!(pub fn set_is_lint(&mut self,) -> &mut Self);
241
242 forward!(pub fn disable_suggestions(&mut self,) -> &mut Self);
243
244 forward!(pub fn multipart_suggestion(
245 &mut self,
246 msg: &str,
247 suggestion: Vec<(Span, String)>,
248 applicability: Applicability,
249 ) -> &mut Self);
250 forward!(pub fn multipart_suggestion_verbose(
251 &mut self,
252 msg: &str,
253 suggestion: Vec<(Span, String)>,
254 applicability: Applicability,
255 ) -> &mut Self);
256 forward!(pub fn tool_only_multipart_suggestion(
257 &mut self,
258 msg: &str,
259 suggestion: Vec<(Span, String)>,
260 applicability: Applicability,
261 ) -> &mut Self);
262 forward!(pub fn span_suggestion(
263 &mut self,
264 sp: Span,
265 msg: &str,
266 suggestion: String,
267 applicability: Applicability,
268 ) -> &mut Self);
269 forward!(pub fn span_suggestions(
270 &mut self,
271 sp: Span,
272 msg: &str,
273 suggestions: impl Iterator<Item = String>,
274 applicability: Applicability,
275 ) -> &mut Self);
276 forward!(pub fn multipart_suggestions(
277 &mut self,
278 msg: &str,
279 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
280 applicability: Applicability,
281 ) -> &mut Self);
282 forward!(pub fn span_suggestion_short(
283 &mut self,
284 sp: Span,
285 msg: &str,
286 suggestion: String,
287 applicability: Applicability,
288 ) -> &mut Self);
289 forward!(pub fn span_suggestion_verbose(
290 &mut self,
291 sp: Span,
292 msg: &str,
293 suggestion: String,
294 applicability: Applicability,
295 ) -> &mut Self);
296 forward!(pub fn span_suggestion_hidden(
297 &mut self,
298 sp: Span,
299 msg: &str,
300 suggestion: String,
301 applicability: Applicability,
302 ) -> &mut Self);
303 forward!(pub fn tool_only_span_suggestion(
304 &mut self,
305 sp: Span,
306 msg: &str,
307 suggestion: String,
308 applicability: Applicability,
309 ) -> &mut Self);
310
311 forward!(pub fn set_primary_message<M: Into<String>>(&mut self, msg: M) -> &mut Self);
312 forward!(pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self);
313 forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self);
314
315 /// Convenience function for internal use, clients should use one of the
316 /// `struct_*` methods on [`Handler`].
317 crate fn new(handler: &'a Handler, level: Level, message: &str) -> DiagnosticBuilder<'a> {
318 DiagnosticBuilder::new_with_code(handler, level, None, message)
319 }
320
321 /// Convenience function for internal use, clients should use one of the
322 /// `struct_*` methods on [`Handler`].
323 crate fn new_with_code(
324 handler: &'a Handler,
325 level: Level,
326 code: Option<DiagnosticId>,
327 message: &str,
328 ) -> DiagnosticBuilder<'a> {
329 let diagnostic = Diagnostic::new_with_code(level, code, message);
330 DiagnosticBuilder::new_diagnostic(handler, diagnostic)
331 }
332
333 /// Creates a new `DiagnosticBuilder` with an already constructed
334 /// diagnostic.
335 crate fn new_diagnostic(handler: &'a Handler, diagnostic: Diagnostic) -> DiagnosticBuilder<'a> {
336 debug!("Created new diagnostic");
337 DiagnosticBuilder { handler, diagnostic: Box::new(diagnostic) }
338 }
339 }
340
341 impl<'a> Debug for DiagnosticBuilder<'a> {
342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343 self.diagnostic.fmt(f)
344 }
345 }
346
347 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or canceled
348 /// or we emit a bug.
349 impl<'a> Drop for DiagnosticBuilder<'a> {
350 fn drop(&mut self) {
351 if !panicking() && !self.cancelled() {
352 let mut db = DiagnosticBuilder::new(
353 self.handler,
354 Level::Bug,
355 "the following error was constructed but not emitted",
356 );
357 db.emit();
358 self.emit();
359 panic!();
360 }
361 }
362 }
363
364 #[macro_export]
365 macro_rules! struct_span_err {
366 ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
367 $session.struct_span_err_with_code(
368 $span,
369 &format!($($message)*),
370 $crate::error_code!($code),
371 )
372 })
373 }
374
375 #[macro_export]
376 macro_rules! error_code {
377 ($code:ident) => {{ $crate::DiagnosticId::Error(stringify!($code).to_owned()) }};
378 }