]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_errors/src/diagnostic_builder.rs
Auto merge of #107843 - bjorn3:sync_cg_clif-2023-02-09, r=bjorn3
[rust.git] / compiler / rustc_errors / src / diagnostic_builder.rs
1 use crate::diagnostic::IntoDiagnosticArg;
2 use crate::{
3     Diagnostic, DiagnosticId, DiagnosticMessage, DiagnosticStyledString, ErrorGuaranteed,
4     ExplicitBug, SubdiagnosticMessage,
5 };
6 use crate::{Handler, Level, MultiSpan, StashKey};
7 use rustc_lint_defs::Applicability;
8 use rustc_span::source_map::Spanned;
9
10 use rustc_span::Span;
11 use std::borrow::Cow;
12 use std::fmt::{self, Debug};
13 use std::marker::PhantomData;
14 use std::ops::{Deref, DerefMut};
15 use std::panic;
16 use std::thread::panicking;
17
18 /// Trait implemented by error types. This should not be implemented manually. Instead, use
19 /// `#[derive(Diagnostic)]` -- see [rustc_macros::Diagnostic].
20 #[rustc_diagnostic_item = "IntoDiagnostic"]
21 pub trait IntoDiagnostic<'a, T: EmissionGuarantee = ErrorGuaranteed> {
22     /// Write out as a diagnostic out of `Handler`.
23     #[must_use]
24     fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, T>;
25 }
26
27 impl<'a, T, E> IntoDiagnostic<'a, E> for Spanned<T>
28 where
29     T: IntoDiagnostic<'a, E>,
30     E: EmissionGuarantee,
31 {
32     fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, E> {
33         let mut diag = self.node.into_diagnostic(handler);
34         diag.set_span(self.span);
35         diag
36     }
37 }
38
39 /// Used for emitting structured error messages and other diagnostic information.
40 ///
41 /// If there is some state in a downstream crate you would like to
42 /// access in the methods of `DiagnosticBuilder` here, consider
43 /// extending `HandlerFlags`, accessed via `self.handler.flags`.
44 #[must_use]
45 #[derive(Clone)]
46 pub struct DiagnosticBuilder<'a, G: EmissionGuarantee> {
47     inner: DiagnosticBuilderInner<'a>,
48     _marker: PhantomData<G>,
49 }
50
51 /// This type exists only for `DiagnosticBuilder::forget_guarantee`, because it:
52 /// 1. lacks the `G` parameter and therefore `DiagnosticBuilder<G1>` can be
53 ///    converted into `DiagnosticBuilder<G2>` while reusing the `inner` field
54 /// 2. can implement the `Drop` "bomb" instead of `DiagnosticBuilder`, as it
55 ///    contains all of the data (`state` + `diagnostic`) of `DiagnosticBuilder`
56 ///
57 /// The `diagnostic` field is not `Copy` and can't be moved out of whichever
58 /// type implements the `Drop` "bomb", but because of the above two facts, that
59 /// never needs to happen - instead, the whole `inner: DiagnosticBuilderInner`
60 /// can be moved out of a `DiagnosticBuilder` and into another.
61 #[must_use]
62 #[derive(Clone)]
63 struct DiagnosticBuilderInner<'a> {
64     state: DiagnosticBuilderState<'a>,
65
66     /// `Diagnostic` is a large type, and `DiagnosticBuilder` is often used as a
67     /// return value, especially within the frequently-used `PResult` type.
68     /// In theory, return value optimization (RVO) should avoid unnecessary
69     /// copying. In practice, it does not (at the time of writing).
70     diagnostic: Box<Diagnostic>,
71 }
72
73 #[derive(Clone)]
74 enum DiagnosticBuilderState<'a> {
75     /// Initial state of a `DiagnosticBuilder`, before `.emit()` or `.cancel()`.
76     ///
77     /// The `Diagnostic` will be emitted through this `Handler`.
78     Emittable(&'a Handler),
79
80     /// State of a `DiagnosticBuilder`, after `.emit()` or *during* `.cancel()`.
81     ///
82     /// The `Diagnostic` will be ignored when calling `.emit()`, and it can be
83     /// assumed that `.emit()` was previously called, to end up in this state.
84     ///
85     /// While this is also used by `.cancel()`, this state is only observed by
86     /// the `Drop` `impl` of `DiagnosticBuilderInner`, as `.cancel()` takes
87     /// `self` by-value specifically to prevent any attempts to `.emit()`.
88     ///
89     // FIXME(eddyb) currently this doesn't prevent extending the `Diagnostic`,
90     // despite that being potentially lossy, if important information is added
91     // *after* the original `.emit()` call.
92     AlreadyEmittedOrDuringCancellation,
93 }
94
95 // `DiagnosticBuilderState` should be pointer-sized.
96 rustc_data_structures::static_assert_size!(
97     DiagnosticBuilderState<'_>,
98     std::mem::size_of::<&Handler>()
99 );
100
101 /// Trait for types that `DiagnosticBuilder::emit` can return as a "guarantee"
102 /// (or "proof") token that the emission happened.
103 pub trait EmissionGuarantee: Sized {
104     /// Implementation of `DiagnosticBuilder::emit`, fully controlled by each
105     /// `impl` of `EmissionGuarantee`, to make it impossible to create a value
106     /// of `Self` without actually performing the emission.
107     #[track_caller]
108     fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self;
109
110     /// Creates a new `DiagnosticBuilder` that will return this type of guarantee.
111     #[track_caller]
112     fn make_diagnostic_builder(
113         handler: &Handler,
114         msg: impl Into<DiagnosticMessage>,
115     ) -> DiagnosticBuilder<'_, Self>;
116 }
117
118 /// Private module for sealing the `IsError` helper trait.
119 mod sealed_level_is_error {
120     use crate::Level;
121
122     /// Sealed helper trait for statically checking that a `Level` is an error.
123     pub(crate) trait IsError<const L: Level> {}
124
125     impl IsError<{ Level::Bug }> for () {}
126     impl IsError<{ Level::DelayedBug }> for () {}
127     impl IsError<{ Level::Fatal }> for () {}
128     // NOTE(eddyb) `Level::Error { lint: true }` is also an error, but lints
129     // don't need error guarantees, as their levels are always dynamic.
130     impl IsError<{ Level::Error { lint: false } }> for () {}
131 }
132
133 impl<'a> DiagnosticBuilder<'a, ErrorGuaranteed> {
134     /// Convenience function for internal use, clients should use one of the
135     /// `struct_*` methods on [`Handler`].
136     #[track_caller]
137     pub(crate) fn new_guaranteeing_error<M: Into<DiagnosticMessage>, const L: Level>(
138         handler: &'a Handler,
139         message: M,
140     ) -> Self
141     where
142         (): sealed_level_is_error::IsError<L>,
143     {
144         Self {
145             inner: DiagnosticBuilderInner {
146                 state: DiagnosticBuilderState::Emittable(handler),
147                 diagnostic: Box::new(Diagnostic::new_with_code(L, None, message)),
148             },
149             _marker: PhantomData,
150         }
151     }
152
153     /// Discard the guarantee `.emit()` would return, in favor of having the
154     /// type `DiagnosticBuilder<'a, ()>`. This may be necessary whenever there
155     /// is a common codepath handling both errors and warnings.
156     pub fn forget_guarantee(self) -> DiagnosticBuilder<'a, ()> {
157         DiagnosticBuilder { inner: self.inner, _marker: PhantomData }
158     }
159 }
160
161 // FIXME(eddyb) make `ErrorGuaranteed` impossible to create outside `.emit()`.
162 impl EmissionGuarantee for ErrorGuaranteed {
163     fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
164         match db.inner.state {
165             // First `.emit()` call, the `&Handler` is still available.
166             DiagnosticBuilderState::Emittable(handler) => {
167                 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
168
169                 let guar = handler.emit_diagnostic(&mut db.inner.diagnostic);
170
171                 // Only allow a guarantee if the `level` wasn't switched to a
172                 // non-error - the field isn't `pub`, but the whole `Diagnostic`
173                 // can be overwritten with a new one, thanks to `DerefMut`.
174                 assert!(
175                     db.inner.diagnostic.is_error(),
176                     "emitted non-error ({:?}) diagnostic \
177                      from `DiagnosticBuilder<ErrorGuaranteed>`",
178                     db.inner.diagnostic.level,
179                 );
180                 guar.unwrap()
181             }
182             // `.emit()` was previously called, disallowed from repeating it,
183             // but can take advantage of the previous `.emit()`'s guarantee
184             // still being applicable (i.e. as a form of idempotency).
185             DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {
186                 // Only allow a guarantee if the `level` wasn't switched to a
187                 // non-error - the field isn't `pub`, but the whole `Diagnostic`
188                 // can be overwritten with a new one, thanks to `DerefMut`.
189                 assert!(
190                     db.inner.diagnostic.is_error(),
191                     "`DiagnosticBuilder<ErrorGuaranteed>`'s diagnostic \
192                      became non-error ({:?}), after original `.emit()`",
193                     db.inner.diagnostic.level,
194                 );
195                 ErrorGuaranteed::unchecked_claim_error_was_emitted()
196             }
197         }
198     }
199
200     #[track_caller]
201     fn make_diagnostic_builder(
202         handler: &Handler,
203         msg: impl Into<DiagnosticMessage>,
204     ) -> DiagnosticBuilder<'_, Self> {
205         DiagnosticBuilder::new_guaranteeing_error::<_, { Level::Error { lint: false } }>(
206             handler, msg,
207         )
208     }
209 }
210
211 impl<'a> DiagnosticBuilder<'a, ()> {
212     /// Convenience function for internal use, clients should use one of the
213     /// `struct_*` methods on [`Handler`].
214     #[track_caller]
215     pub(crate) fn new<M: Into<DiagnosticMessage>>(
216         handler: &'a Handler,
217         level: Level,
218         message: M,
219     ) -> Self {
220         let diagnostic = Diagnostic::new_with_code(level, None, message);
221         Self::new_diagnostic(handler, diagnostic)
222     }
223
224     /// Creates a new `DiagnosticBuilder` with an already constructed
225     /// diagnostic.
226     #[track_caller]
227     pub(crate) fn new_diagnostic(handler: &'a Handler, diagnostic: Diagnostic) -> Self {
228         debug!("Created new diagnostic");
229         Self {
230             inner: DiagnosticBuilderInner {
231                 state: DiagnosticBuilderState::Emittable(handler),
232                 diagnostic: Box::new(diagnostic),
233             },
234             _marker: PhantomData,
235         }
236     }
237 }
238
239 // FIXME(eddyb) should there be a `Option<ErrorGuaranteed>` impl as well?
240 impl EmissionGuarantee for () {
241     fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
242         match db.inner.state {
243             // First `.emit()` call, the `&Handler` is still available.
244             DiagnosticBuilderState::Emittable(handler) => {
245                 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
246
247                 handler.emit_diagnostic(&mut db.inner.diagnostic);
248             }
249             // `.emit()` was previously called, disallowed from repeating it.
250             DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
251         }
252     }
253
254     fn make_diagnostic_builder(
255         handler: &Handler,
256         msg: impl Into<DiagnosticMessage>,
257     ) -> DiagnosticBuilder<'_, Self> {
258         DiagnosticBuilder::new(handler, Level::Warning(None), msg)
259     }
260 }
261
262 /// Marker type which enables implementation of `create_note` and `emit_note` functions for
263 /// note-without-error struct diagnostics.
264 #[derive(Copy, Clone)]
265 pub struct Noted;
266
267 impl<'a> DiagnosticBuilder<'a, Noted> {
268     /// Convenience function for internal use, clients should use one of the
269     /// `struct_*` methods on [`Handler`].
270     pub(crate) fn new_note(handler: &'a Handler, message: impl Into<DiagnosticMessage>) -> Self {
271         let diagnostic = Diagnostic::new_with_code(Level::Note, None, message);
272         Self::new_diagnostic_note(handler, diagnostic)
273     }
274
275     /// Creates a new `DiagnosticBuilder` with an already constructed
276     /// diagnostic.
277     pub(crate) fn new_diagnostic_note(handler: &'a Handler, diagnostic: Diagnostic) -> Self {
278         debug!("Created new diagnostic");
279         Self {
280             inner: DiagnosticBuilderInner {
281                 state: DiagnosticBuilderState::Emittable(handler),
282                 diagnostic: Box::new(diagnostic),
283             },
284             _marker: PhantomData,
285         }
286     }
287 }
288
289 impl EmissionGuarantee for Noted {
290     fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
291         match db.inner.state {
292             // First `.emit()` call, the `&Handler` is still available.
293             DiagnosticBuilderState::Emittable(handler) => {
294                 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
295                 handler.emit_diagnostic(&mut db.inner.diagnostic);
296             }
297             // `.emit()` was previously called, disallowed from repeating it.
298             DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
299         }
300
301         Noted
302     }
303
304     fn make_diagnostic_builder(
305         handler: &Handler,
306         msg: impl Into<DiagnosticMessage>,
307     ) -> DiagnosticBuilder<'_, Self> {
308         DiagnosticBuilder::new_note(handler, msg)
309     }
310 }
311
312 /// Marker type which enables implementation of `create_bug` and `emit_bug` functions for
313 /// bug struct diagnostics.
314 #[derive(Copy, Clone)]
315 pub struct Bug;
316
317 impl<'a> DiagnosticBuilder<'a, Bug> {
318     /// Convenience function for internal use, clients should use one of the
319     /// `struct_*` methods on [`Handler`].
320     #[track_caller]
321     pub(crate) fn new_bug(handler: &'a Handler, message: impl Into<DiagnosticMessage>) -> Self {
322         let diagnostic = Diagnostic::new_with_code(Level::Bug, None, message);
323         Self::new_diagnostic_bug(handler, diagnostic)
324     }
325
326     /// Creates a new `DiagnosticBuilder` with an already constructed
327     /// diagnostic.
328     pub(crate) fn new_diagnostic_bug(handler: &'a Handler, diagnostic: Diagnostic) -> Self {
329         debug!("Created new diagnostic bug");
330         Self {
331             inner: DiagnosticBuilderInner {
332                 state: DiagnosticBuilderState::Emittable(handler),
333                 diagnostic: Box::new(diagnostic),
334             },
335             _marker: PhantomData,
336         }
337     }
338 }
339
340 impl EmissionGuarantee for Bug {
341     fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
342         match db.inner.state {
343             // First `.emit()` call, the `&Handler` is still available.
344             DiagnosticBuilderState::Emittable(handler) => {
345                 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
346
347                 handler.emit_diagnostic(&mut db.inner.diagnostic);
348             }
349             // `.emit()` was previously called, disallowed from repeating it.
350             DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
351         }
352         // Then panic. No need to return the marker type.
353         panic::panic_any(ExplicitBug);
354     }
355
356     fn make_diagnostic_builder(
357         handler: &Handler,
358         msg: impl Into<DiagnosticMessage>,
359     ) -> DiagnosticBuilder<'_, Self> {
360         DiagnosticBuilder::new_bug(handler, msg)
361     }
362 }
363
364 impl<'a> DiagnosticBuilder<'a, !> {
365     /// Convenience function for internal use, clients should use one of the
366     /// `struct_*` methods on [`Handler`].
367     #[track_caller]
368     pub(crate) fn new_fatal(handler: &'a Handler, message: impl Into<DiagnosticMessage>) -> Self {
369         let diagnostic = Diagnostic::new_with_code(Level::Fatal, None, message);
370         Self::new_diagnostic_fatal(handler, diagnostic)
371     }
372
373     /// Creates a new `DiagnosticBuilder` with an already constructed
374     /// diagnostic.
375     pub(crate) fn new_diagnostic_fatal(handler: &'a Handler, diagnostic: Diagnostic) -> Self {
376         debug!("Created new diagnostic");
377         Self {
378             inner: DiagnosticBuilderInner {
379                 state: DiagnosticBuilderState::Emittable(handler),
380                 diagnostic: Box::new(diagnostic),
381             },
382             _marker: PhantomData,
383         }
384     }
385 }
386
387 impl EmissionGuarantee for ! {
388     fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
389         match db.inner.state {
390             // First `.emit()` call, the `&Handler` is still available.
391             DiagnosticBuilderState::Emittable(handler) => {
392                 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
393
394                 handler.emit_diagnostic(&mut db.inner.diagnostic);
395             }
396             // `.emit()` was previously called, disallowed from repeating it.
397             DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
398         }
399         // Then fatally error, returning `!`
400         crate::FatalError.raise()
401     }
402
403     fn make_diagnostic_builder(
404         handler: &Handler,
405         msg: impl Into<DiagnosticMessage>,
406     ) -> DiagnosticBuilder<'_, Self> {
407         DiagnosticBuilder::new_fatal(handler, msg)
408     }
409 }
410
411 impl<'a> DiagnosticBuilder<'a, rustc_span::fatal_error::FatalError> {
412     /// Convenience function for internal use, clients should use one of the
413     /// `struct_*` methods on [`Handler`].
414     #[track_caller]
415     pub(crate) fn new_almost_fatal(
416         handler: &'a Handler,
417         message: impl Into<DiagnosticMessage>,
418     ) -> Self {
419         let diagnostic = Diagnostic::new_with_code(Level::Fatal, None, message);
420         Self::new_diagnostic_almost_fatal(handler, diagnostic)
421     }
422
423     /// Creates a new `DiagnosticBuilder` with an already constructed
424     /// diagnostic.
425     pub(crate) fn new_diagnostic_almost_fatal(
426         handler: &'a Handler,
427         diagnostic: Diagnostic,
428     ) -> Self {
429         debug!("Created new diagnostic");
430         Self {
431             inner: DiagnosticBuilderInner {
432                 state: DiagnosticBuilderState::Emittable(handler),
433                 diagnostic: Box::new(diagnostic),
434             },
435             _marker: PhantomData,
436         }
437     }
438 }
439
440 impl EmissionGuarantee for rustc_span::fatal_error::FatalError {
441     fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
442         match db.inner.state {
443             // First `.emit()` call, the `&Handler` is still available.
444             DiagnosticBuilderState::Emittable(handler) => {
445                 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
446
447                 handler.emit_diagnostic(&mut db.inner.diagnostic);
448             }
449             // `.emit()` was previously called, disallowed from repeating it.
450             DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
451         }
452         // Then fatally error..
453         rustc_span::fatal_error::FatalError
454     }
455
456     fn make_diagnostic_builder(
457         handler: &Handler,
458         msg: impl Into<DiagnosticMessage>,
459     ) -> DiagnosticBuilder<'_, Self> {
460         DiagnosticBuilder::new_almost_fatal(handler, msg)
461     }
462 }
463
464 /// In general, the `DiagnosticBuilder` uses deref to allow access to
465 /// the fields and methods of the embedded `diagnostic` in a
466 /// transparent way. *However,* many of the methods are intended to
467 /// be used in a chained way, and hence ought to return `self`. In
468 /// that case, we can't just naively forward to the method on the
469 /// `diagnostic`, because the return type would be a `&Diagnostic`
470 /// instead of a `&DiagnosticBuilder<'a>`. This `forward!` macro makes
471 /// it easy to declare such methods on the builder.
472 macro_rules! forward {
473     // Forward pattern for &mut self -> &mut Self
474     (
475         $(#[$attrs:meta])*
476         pub fn $n:ident(&mut self, $($name:ident: $ty:ty),* $(,)?) -> &mut Self
477     ) => {
478         $(#[$attrs])*
479         #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
480         pub fn $n(&mut self, $($name: $ty),*) -> &mut Self {
481             self.inner.diagnostic.$n($($name),*);
482             self
483         }
484     };
485 }
486
487 impl<G: EmissionGuarantee> Deref for DiagnosticBuilder<'_, G> {
488     type Target = Diagnostic;
489
490     fn deref(&self) -> &Diagnostic {
491         &self.inner.diagnostic
492     }
493 }
494
495 impl<G: EmissionGuarantee> DerefMut for DiagnosticBuilder<'_, G> {
496     fn deref_mut(&mut self) -> &mut Diagnostic {
497         &mut self.inner.diagnostic
498     }
499 }
500
501 impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
502     /// Emit the diagnostic.
503     #[track_caller]
504     pub fn emit(&mut self) -> G {
505         G::diagnostic_builder_emit_producing_guarantee(self)
506     }
507
508     /// Emit the diagnostic unless `delay` is true,
509     /// in which case the emission will be delayed as a bug.
510     ///
511     /// See `emit` and `delay_as_bug` for details.
512     #[track_caller]
513     pub fn emit_unless(&mut self, delay: bool) -> G {
514         if delay {
515             self.downgrade_to_delayed_bug();
516         }
517         self.emit()
518     }
519
520     /// Cancel the diagnostic (a structured diagnostic must either be emitted or
521     /// cancelled or it will panic when dropped).
522     ///
523     /// This method takes `self` by-value to disallow calling `.emit()` on it,
524     /// which may be expected to *guarantee* the emission of an error, either
525     /// at the time of the call, or through a prior `.emit()` call.
526     pub fn cancel(mut self) {
527         self.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
528         drop(self);
529     }
530
531     /// Stashes diagnostic for possible later improvement in a different,
532     /// later stage of the compiler. The diagnostic can be accessed with
533     /// the provided `span` and `key` through [`Handler::steal_diagnostic()`].
534     ///
535     /// As with `buffer`, this is unless the handler has disabled such buffering.
536     pub fn stash(self, span: Span, key: StashKey) {
537         if let Some((diag, handler)) = self.into_diagnostic() {
538             handler.stash_diagnostic(span, key, diag);
539         }
540     }
541
542     /// Converts the builder to a `Diagnostic` for later emission,
543     /// unless handler has disabled such buffering, or `.emit()` was called.
544     pub fn into_diagnostic(mut self) -> Option<(Diagnostic, &'a Handler)> {
545         let handler = match self.inner.state {
546             // No `.emit()` calls, the `&Handler` is still available.
547             DiagnosticBuilderState::Emittable(handler) => handler,
548             // `.emit()` was previously called, nothing we can do.
549             DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {
550                 return None;
551             }
552         };
553
554         if handler.flags.dont_buffer_diagnostics || handler.flags.treat_err_as_bug.is_some() {
555             self.emit();
556             return None;
557         }
558
559         // Take the `Diagnostic` by replacing it with a dummy.
560         let dummy = Diagnostic::new(Level::Allow, DiagnosticMessage::Str("".to_string()));
561         let diagnostic = std::mem::replace(&mut *self.inner.diagnostic, dummy);
562
563         // Disable the ICE on `Drop`.
564         self.cancel();
565
566         // Logging here is useful to help track down where in logs an error was
567         // actually emitted.
568         debug!("buffer: diagnostic={:?}", diagnostic);
569
570         Some((diagnostic, handler))
571     }
572
573     /// Buffers the diagnostic for later emission,
574     /// unless handler has disabled such buffering.
575     pub fn buffer(self, buffered_diagnostics: &mut Vec<Diagnostic>) {
576         buffered_diagnostics.extend(self.into_diagnostic().map(|(diag, _)| diag));
577     }
578
579     /// Delay emission of this diagnostic as a bug.
580     ///
581     /// This can be useful in contexts where an error indicates a bug but
582     /// typically this only happens when other compilation errors have already
583     /// happened. In those cases this can be used to defer emission of this
584     /// diagnostic as a bug in the compiler only if no other errors have been
585     /// emitted.
586     ///
587     /// In the meantime, though, callsites are required to deal with the "bug"
588     /// locally in whichever way makes the most sense.
589     #[track_caller]
590     pub fn delay_as_bug(&mut self) -> G {
591         self.downgrade_to_delayed_bug();
592         self.emit()
593     }
594
595     forward!(
596         #[track_caller]
597         pub fn downgrade_to_delayed_bug(&mut self,) -> &mut Self
598     );
599
600     forward!(
601     /// Appends a labeled span to the diagnostic.
602     ///
603     /// Labels are used to convey additional context for the diagnostic's primary span. They will
604     /// be shown together with the original diagnostic's span, *not* with spans added by
605     /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
606     /// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
607     /// either.
608     ///
609     /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
610     /// the diagnostic was constructed. However, the label span is *not* considered a
611     /// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
612     /// primary.
613     pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self);
614
615     forward!(
616     /// Labels all the given spans with the provided label.
617     /// See [`Diagnostic::span_label()`] for more information.
618     pub fn span_labels(
619         &mut self,
620         spans: impl IntoIterator<Item = Span>,
621         label: impl AsRef<str>,
622     ) -> &mut Self);
623
624     forward!(pub fn note_expected_found(
625         &mut self,
626         expected_label: &dyn fmt::Display,
627         expected: DiagnosticStyledString,
628         found_label: &dyn fmt::Display,
629         found: DiagnosticStyledString,
630     ) -> &mut Self);
631
632     forward!(pub fn note_expected_found_extra(
633         &mut self,
634         expected_label: &dyn fmt::Display,
635         expected: DiagnosticStyledString,
636         found_label: &dyn fmt::Display,
637         found: DiagnosticStyledString,
638         expected_extra: &dyn fmt::Display,
639         found_extra: &dyn fmt::Display,
640     ) -> &mut Self);
641
642     forward!(pub fn note_unsuccessful_coercion(
643         &mut self,
644         expected: DiagnosticStyledString,
645         found: DiagnosticStyledString,
646     ) -> &mut Self);
647
648     forward!(pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
649     forward!(pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
650     forward!(pub fn span_note(
651         &mut self,
652         sp: impl Into<MultiSpan>,
653         msg: impl Into<SubdiagnosticMessage>,
654     ) -> &mut Self);
655     forward!(pub fn span_note_once(
656         &mut self,
657         sp: impl Into<MultiSpan>,
658         msg: impl Into<SubdiagnosticMessage>,
659     ) -> &mut Self);
660     forward!(pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
661     forward!(pub fn span_warn(
662         &mut self,
663         sp: impl Into<MultiSpan>,
664         msg: impl Into<SubdiagnosticMessage>,
665     ) -> &mut Self);
666     forward!(pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
667     forward!(pub fn span_help(
668         &mut self,
669         sp: impl Into<MultiSpan>,
670         msg: impl Into<SubdiagnosticMessage>,
671     ) -> &mut Self);
672     forward!(pub fn set_is_lint(&mut self,) -> &mut Self);
673
674     forward!(pub fn disable_suggestions(&mut self,) -> &mut Self);
675     forward!(pub fn clear_suggestions(&mut self,) -> &mut Self);
676
677     forward!(pub fn multipart_suggestion(
678         &mut self,
679         msg: impl Into<SubdiagnosticMessage>,
680         suggestion: Vec<(Span, String)>,
681         applicability: Applicability,
682     ) -> &mut Self);
683     forward!(pub fn multipart_suggestion_verbose(
684         &mut self,
685         msg: impl Into<SubdiagnosticMessage>,
686         suggestion: Vec<(Span, String)>,
687         applicability: Applicability,
688     ) -> &mut Self);
689     forward!(pub fn tool_only_multipart_suggestion(
690         &mut self,
691         msg: impl Into<SubdiagnosticMessage>,
692         suggestion: Vec<(Span, String)>,
693         applicability: Applicability,
694     ) -> &mut Self);
695     forward!(pub fn span_suggestion(
696         &mut self,
697         sp: Span,
698         msg: impl Into<SubdiagnosticMessage>,
699         suggestion: impl ToString,
700         applicability: Applicability,
701     ) -> &mut Self);
702     forward!(pub fn span_suggestions(
703         &mut self,
704         sp: Span,
705         msg: impl Into<SubdiagnosticMessage>,
706         suggestions: impl IntoIterator<Item = String>,
707         applicability: Applicability,
708     ) -> &mut Self);
709     forward!(pub fn multipart_suggestions(
710         &mut self,
711         msg: impl Into<SubdiagnosticMessage>,
712         suggestions: impl IntoIterator<Item = Vec<(Span, String)>>,
713         applicability: Applicability,
714     ) -> &mut Self);
715     forward!(pub fn span_suggestion_short(
716         &mut self,
717         sp: Span,
718         msg: impl Into<SubdiagnosticMessage>,
719         suggestion: impl ToString,
720         applicability: Applicability,
721     ) -> &mut Self);
722     forward!(pub fn span_suggestion_verbose(
723         &mut self,
724         sp: Span,
725         msg: impl Into<SubdiagnosticMessage>,
726         suggestion: impl ToString,
727         applicability: Applicability,
728     ) -> &mut Self);
729     forward!(pub fn span_suggestion_hidden(
730         &mut self,
731         sp: Span,
732         msg: impl Into<SubdiagnosticMessage>,
733         suggestion: impl ToString,
734         applicability: Applicability,
735     ) -> &mut Self);
736     forward!(pub fn tool_only_span_suggestion(
737         &mut self,
738         sp: Span,
739         msg: impl Into<SubdiagnosticMessage>,
740         suggestion: impl ToString,
741         applicability: Applicability,
742     ) -> &mut Self);
743
744     forward!(pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self);
745     forward!(pub fn set_span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self);
746     forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self);
747     forward!(pub fn set_arg(
748         &mut self,
749         name: impl Into<Cow<'static, str>>,
750         arg: impl IntoDiagnosticArg,
751     ) -> &mut Self);
752
753     forward!(pub fn subdiagnostic(
754         &mut self,
755         subdiagnostic: impl crate::AddToDiagnostic
756     ) -> &mut Self);
757 }
758
759 impl<G: EmissionGuarantee> Debug for DiagnosticBuilder<'_, G> {
760     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
761         self.inner.diagnostic.fmt(f)
762     }
763 }
764
765 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or cancelled
766 /// or we emit a bug.
767 impl Drop for DiagnosticBuilderInner<'_> {
768     fn drop(&mut self) {
769         match self.state {
770             // No `.emit()` or `.cancel()` calls.
771             DiagnosticBuilderState::Emittable(handler) => {
772                 if !panicking() {
773                     handler.emit_diagnostic(&mut Diagnostic::new(
774                         Level::Bug,
775                         DiagnosticMessage::Str(
776                             "the following error was constructed but not emitted".to_string(),
777                         ),
778                     ));
779                     handler.emit_diagnostic(&mut self.diagnostic);
780                     panic!("error was constructed but not emitted");
781                 }
782             }
783             // `.emit()` was previously called, or maybe we're during `.cancel()`.
784             DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
785         }
786     }
787 }
788
789 #[macro_export]
790 macro_rules! struct_span_err {
791     ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
792         $session.struct_span_err_with_code(
793             $span,
794             &format!($($message)*),
795             $crate::error_code!($code),
796         )
797     })
798 }
799
800 #[macro_export]
801 macro_rules! error_code {
802     ($code:ident) => {{ $crate::DiagnosticId::Error(stringify!($code).to_owned()) }};
803 }