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