]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_errors/src/diagnostic_builder.rs
Rollup merge of #102623 - davidtwco:translation-eager, r=compiler-errors
[rust.git] / compiler / rustc_errors / src / diagnostic_builder.rs
1 use crate::diagnostic::IntoDiagnosticArg;
2 use crate::{
3     Diagnostic, DiagnosticId, DiagnosticMessage, DiagnosticStyledString, ErrorGuaranteed,
4     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::thread::panicking;
16
17 /// Trait implemented by error types. This should not be implemented manually. Instead, use
18 /// `#[derive(Diagnostic)]` -- see [rustc_macros::Diagnostic].
19 #[cfg_attr(bootstrap, rustc_diagnostic_item = "SessionDiagnostic")]
20 #[cfg_attr(not(bootstrap), 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     pub(crate) fn new_guaranteeing_error<M: Into<DiagnosticMessage>, const L: Level>(
137         handler: &'a Handler,
138         message: M,
139     ) -> Self
140     where
141         (): sealed_level_is_error::IsError<L>,
142     {
143         Self {
144             inner: DiagnosticBuilderInner {
145                 state: DiagnosticBuilderState::Emittable(handler),
146                 diagnostic: Box::new(Diagnostic::new_with_code(L, None, message)),
147             },
148             _marker: PhantomData,
149         }
150     }
151
152     /// Discard the guarantee `.emit()` would return, in favor of having the
153     /// type `DiagnosticBuilder<'a, ()>`. This may be necessary whenever there
154     /// is a common codepath handling both errors and warnings.
155     pub fn forget_guarantee(self) -> DiagnosticBuilder<'a, ()> {
156         DiagnosticBuilder { inner: self.inner, _marker: PhantomData }
157     }
158 }
159
160 // FIXME(eddyb) make `ErrorGuaranteed` impossible to create outside `.emit()`.
161 impl EmissionGuarantee for ErrorGuaranteed {
162     fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
163         match db.inner.state {
164             // First `.emit()` call, the `&Handler` is still available.
165             DiagnosticBuilderState::Emittable(handler) => {
166                 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
167
168                 let guar = handler.emit_diagnostic(&mut db.inner.diagnostic);
169
170                 // Only allow a guarantee if the `level` wasn't switched to a
171                 // non-error - the field isn't `pub`, but the whole `Diagnostic`
172                 // can be overwritten with a new one, thanks to `DerefMut`.
173                 assert!(
174                     db.inner.diagnostic.is_error(),
175                     "emitted non-error ({:?}) diagnostic \
176                      from `DiagnosticBuilder<ErrorGuaranteed>`",
177                     db.inner.diagnostic.level,
178                 );
179                 guar.unwrap()
180             }
181             // `.emit()` was previously called, disallowed from repeating it,
182             // but can take advantage of the previous `.emit()`'s guarantee
183             // still being applicable (i.e. as a form of idempotency).
184             DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {
185                 // Only allow a guarantee if the `level` wasn't switched to a
186                 // non-error - the field isn't `pub`, but the whole `Diagnostic`
187                 // can be overwritten with a new one, thanks to `DerefMut`.
188                 assert!(
189                     db.inner.diagnostic.is_error(),
190                     "`DiagnosticBuilder<ErrorGuaranteed>`'s diagnostic \
191                      became non-error ({:?}), after original `.emit()`",
192                     db.inner.diagnostic.level,
193                 );
194                 ErrorGuaranteed::unchecked_claim_error_was_emitted()
195             }
196         }
197     }
198
199     fn make_diagnostic_builder(
200         handler: &Handler,
201         msg: impl Into<DiagnosticMessage>,
202     ) -> DiagnosticBuilder<'_, Self> {
203         DiagnosticBuilder::new_guaranteeing_error::<_, { Level::Error { lint: false } }>(
204             handler, msg,
205         )
206     }
207 }
208
209 impl<'a> DiagnosticBuilder<'a, ()> {
210     /// Convenience function for internal use, clients should use one of the
211     /// `struct_*` methods on [`Handler`].
212     pub(crate) fn new<M: Into<DiagnosticMessage>>(
213         handler: &'a Handler,
214         level: Level,
215         message: M,
216     ) -> Self {
217         let diagnostic = Diagnostic::new_with_code(level, None, message);
218         Self::new_diagnostic(handler, diagnostic)
219     }
220
221     /// Creates a new `DiagnosticBuilder` with an already constructed
222     /// diagnostic.
223     pub(crate) fn new_diagnostic(handler: &'a Handler, diagnostic: Diagnostic) -> Self {
224         debug!("Created new diagnostic");
225         Self {
226             inner: DiagnosticBuilderInner {
227                 state: DiagnosticBuilderState::Emittable(handler),
228                 diagnostic: Box::new(diagnostic),
229             },
230             _marker: PhantomData,
231         }
232     }
233 }
234
235 // FIXME(eddyb) should there be a `Option<ErrorGuaranteed>` impl as well?
236 impl EmissionGuarantee for () {
237     fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
238         match db.inner.state {
239             // First `.emit()` call, the `&Handler` is still available.
240             DiagnosticBuilderState::Emittable(handler) => {
241                 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
242
243                 handler.emit_diagnostic(&mut db.inner.diagnostic);
244             }
245             // `.emit()` was previously called, disallowed from repeating it.
246             DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
247         }
248     }
249
250     fn make_diagnostic_builder(
251         handler: &Handler,
252         msg: impl Into<DiagnosticMessage>,
253     ) -> DiagnosticBuilder<'_, Self> {
254         DiagnosticBuilder::new(handler, Level::Warning(None), msg)
255     }
256 }
257
258 /// Marker type which enables implementation of `create_note` and `emit_note` functions for
259 /// note-without-error struct diagnostics.
260 #[derive(Copy, Clone)]
261 pub struct Noted;
262
263 impl<'a> DiagnosticBuilder<'a, Noted> {
264     /// Convenience function for internal use, clients should use one of the
265     /// `struct_*` methods on [`Handler`].
266     pub(crate) fn new_note(handler: &'a Handler, message: impl Into<DiagnosticMessage>) -> Self {
267         let diagnostic = Diagnostic::new_with_code(Level::Note, None, message);
268         Self::new_diagnostic_note(handler, diagnostic)
269     }
270
271     /// Creates a new `DiagnosticBuilder` with an already constructed
272     /// diagnostic.
273     pub(crate) fn new_diagnostic_note(handler: &'a Handler, diagnostic: Diagnostic) -> Self {
274         debug!("Created new diagnostic");
275         Self {
276             inner: DiagnosticBuilderInner {
277                 state: DiagnosticBuilderState::Emittable(handler),
278                 diagnostic: Box::new(diagnostic),
279             },
280             _marker: PhantomData,
281         }
282     }
283 }
284
285 impl EmissionGuarantee for Noted {
286     fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
287         match db.inner.state {
288             // First `.emit()` call, the `&Handler` is still available.
289             DiagnosticBuilderState::Emittable(handler) => {
290                 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
291                 handler.emit_diagnostic(&mut db.inner.diagnostic);
292             }
293             // `.emit()` was previously called, disallowed from repeating it.
294             DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
295         }
296
297         Noted
298     }
299
300     fn make_diagnostic_builder(
301         handler: &Handler,
302         msg: impl Into<DiagnosticMessage>,
303     ) -> DiagnosticBuilder<'_, Self> {
304         DiagnosticBuilder::new_note(handler, msg)
305     }
306 }
307
308 impl<'a> DiagnosticBuilder<'a, !> {
309     /// Convenience function for internal use, clients should use one of the
310     /// `struct_*` methods on [`Handler`].
311     pub(crate) fn new_fatal(handler: &'a Handler, message: impl Into<DiagnosticMessage>) -> Self {
312         let diagnostic = Diagnostic::new_with_code(Level::Fatal, None, message);
313         Self::new_diagnostic_fatal(handler, diagnostic)
314     }
315
316     /// Creates a new `DiagnosticBuilder` with an already constructed
317     /// diagnostic.
318     pub(crate) fn new_diagnostic_fatal(handler: &'a Handler, diagnostic: Diagnostic) -> Self {
319         debug!("Created new diagnostic");
320         Self {
321             inner: DiagnosticBuilderInner {
322                 state: DiagnosticBuilderState::Emittable(handler),
323                 diagnostic: Box::new(diagnostic),
324             },
325             _marker: PhantomData,
326         }
327     }
328 }
329
330 impl EmissionGuarantee for ! {
331     fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
332         match db.inner.state {
333             // First `.emit()` call, the `&Handler` is still available.
334             DiagnosticBuilderState::Emittable(handler) => {
335                 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
336
337                 handler.emit_diagnostic(&mut db.inner.diagnostic);
338             }
339             // `.emit()` was previously called, disallowed from repeating it.
340             DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
341         }
342         // Then fatally error, returning `!`
343         crate::FatalError.raise()
344     }
345
346     fn make_diagnostic_builder(
347         handler: &Handler,
348         msg: impl Into<DiagnosticMessage>,
349     ) -> DiagnosticBuilder<'_, Self> {
350         DiagnosticBuilder::new_fatal(handler, msg)
351     }
352 }
353
354 /// In general, the `DiagnosticBuilder` uses deref to allow access to
355 /// the fields and methods of the embedded `diagnostic` in a
356 /// transparent way. *However,* many of the methods are intended to
357 /// be used in a chained way, and hence ought to return `self`. In
358 /// that case, we can't just naively forward to the method on the
359 /// `diagnostic`, because the return type would be a `&Diagnostic`
360 /// instead of a `&DiagnosticBuilder<'a>`. This `forward!` macro makes
361 /// it easy to declare such methods on the builder.
362 macro_rules! forward {
363     // Forward pattern for &mut self -> &mut Self
364     (
365         $(#[$attrs:meta])*
366         pub fn $n:ident(&mut self, $($name:ident: $ty:ty),* $(,)?) -> &mut Self
367     ) => {
368         $(#[$attrs])*
369         #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
370         pub fn $n(&mut self, $($name: $ty),*) -> &mut Self {
371             self.inner.diagnostic.$n($($name),*);
372             self
373         }
374     };
375 }
376
377 impl<G: EmissionGuarantee> Deref for DiagnosticBuilder<'_, G> {
378     type Target = Diagnostic;
379
380     fn deref(&self) -> &Diagnostic {
381         &self.inner.diagnostic
382     }
383 }
384
385 impl<G: EmissionGuarantee> DerefMut for DiagnosticBuilder<'_, G> {
386     fn deref_mut(&mut self) -> &mut Diagnostic {
387         &mut self.inner.diagnostic
388     }
389 }
390
391 impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
392     /// Emit the diagnostic.
393     #[track_caller]
394     pub fn emit(&mut self) -> G {
395         G::diagnostic_builder_emit_producing_guarantee(self)
396     }
397
398     /// Emit the diagnostic unless `delay` is true,
399     /// in which case the emission will be delayed as a bug.
400     ///
401     /// See `emit` and `delay_as_bug` for details.
402     #[track_caller]
403     pub fn emit_unless(&mut self, delay: bool) -> G {
404         if delay {
405             self.downgrade_to_delayed_bug();
406         }
407         self.emit()
408     }
409
410     /// Cancel the diagnostic (a structured diagnostic must either be emitted or
411     /// cancelled or it will panic when dropped).
412     ///
413     /// This method takes `self` by-value to disallow calling `.emit()` on it,
414     /// which may be expected to *guarantee* the emission of an error, either
415     /// at the time of the call, or through a prior `.emit()` call.
416     pub fn cancel(mut self) {
417         self.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
418         drop(self);
419     }
420
421     /// Stashes diagnostic for possible later improvement in a different,
422     /// later stage of the compiler. The diagnostic can be accessed with
423     /// the provided `span` and `key` through [`Handler::steal_diagnostic()`].
424     ///
425     /// As with `buffer`, this is unless the handler has disabled such buffering.
426     pub fn stash(self, span: Span, key: StashKey) {
427         if let Some((diag, handler)) = self.into_diagnostic() {
428             handler.stash_diagnostic(span, key, diag);
429         }
430     }
431
432     /// Converts the builder to a `Diagnostic` for later emission,
433     /// unless handler has disabled such buffering, or `.emit()` was called.
434     pub fn into_diagnostic(mut self) -> Option<(Diagnostic, &'a Handler)> {
435         let handler = match self.inner.state {
436             // No `.emit()` calls, the `&Handler` is still available.
437             DiagnosticBuilderState::Emittable(handler) => handler,
438             // `.emit()` was previously called, nothing we can do.
439             DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {
440                 return None;
441             }
442         };
443
444         if handler.flags.dont_buffer_diagnostics || handler.flags.treat_err_as_bug.is_some() {
445             self.emit();
446             return None;
447         }
448
449         // Take the `Diagnostic` by replacing it with a dummy.
450         let dummy = Diagnostic::new(Level::Allow, DiagnosticMessage::Str("".to_string()));
451         let diagnostic = std::mem::replace(&mut *self.inner.diagnostic, dummy);
452
453         // Disable the ICE on `Drop`.
454         self.cancel();
455
456         // Logging here is useful to help track down where in logs an error was
457         // actually emitted.
458         debug!("buffer: diagnostic={:?}", diagnostic);
459
460         Some((diagnostic, handler))
461     }
462
463     /// Buffers the diagnostic for later emission,
464     /// unless handler has disabled such buffering.
465     pub fn buffer(self, buffered_diagnostics: &mut Vec<Diagnostic>) {
466         buffered_diagnostics.extend(self.into_diagnostic().map(|(diag, _)| diag));
467     }
468
469     /// Delay emission of this diagnostic as a bug.
470     ///
471     /// This can be useful in contexts where an error indicates a bug but
472     /// typically this only happens when other compilation errors have already
473     /// happened. In those cases this can be used to defer emission of this
474     /// diagnostic as a bug in the compiler only if no other errors have been
475     /// emitted.
476     ///
477     /// In the meantime, though, callsites are required to deal with the "bug"
478     /// locally in whichever way makes the most sense.
479     #[track_caller]
480     pub fn delay_as_bug(&mut self) {
481         self.downgrade_to_delayed_bug();
482         self.emit();
483     }
484
485     forward!(
486         #[track_caller]
487         pub fn downgrade_to_delayed_bug(&mut self,) -> &mut Self
488     );
489
490     forward!(
491     /// Appends a labeled span to the diagnostic.
492     ///
493     /// Labels are used to convey additional context for the diagnostic's primary span. They will
494     /// be shown together with the original diagnostic's span, *not* with spans added by
495     /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
496     /// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
497     /// either.
498     ///
499     /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
500     /// the diagnostic was constructed. However, the label span is *not* considered a
501     /// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
502     /// primary.
503     pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self);
504
505     forward!(
506     /// Labels all the given spans with the provided label.
507     /// See [`Diagnostic::span_label()`] for more information.
508     pub fn span_labels(
509         &mut self,
510         spans: impl IntoIterator<Item = Span>,
511         label: impl AsRef<str>,
512     ) -> &mut Self);
513
514     forward!(pub fn note_expected_found(
515         &mut self,
516         expected_label: &dyn fmt::Display,
517         expected: DiagnosticStyledString,
518         found_label: &dyn fmt::Display,
519         found: DiagnosticStyledString,
520     ) -> &mut Self);
521
522     forward!(pub fn note_expected_found_extra(
523         &mut self,
524         expected_label: &dyn fmt::Display,
525         expected: DiagnosticStyledString,
526         found_label: &dyn fmt::Display,
527         found: DiagnosticStyledString,
528         expected_extra: &dyn fmt::Display,
529         found_extra: &dyn fmt::Display,
530     ) -> &mut Self);
531
532     forward!(pub fn note_unsuccessful_coercion(
533         &mut self,
534         expected: DiagnosticStyledString,
535         found: DiagnosticStyledString,
536     ) -> &mut Self);
537
538     forward!(pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
539     forward!(pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
540     forward!(pub fn span_note(
541         &mut self,
542         sp: impl Into<MultiSpan>,
543         msg: impl Into<SubdiagnosticMessage>,
544     ) -> &mut Self);
545     forward!(pub fn span_note_once(
546         &mut self,
547         sp: impl Into<MultiSpan>,
548         msg: impl Into<SubdiagnosticMessage>,
549     ) -> &mut Self);
550     forward!(pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
551     forward!(pub fn span_warn(
552         &mut self,
553         sp: impl Into<MultiSpan>,
554         msg: impl Into<SubdiagnosticMessage>,
555     ) -> &mut Self);
556     forward!(pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
557     forward!(pub fn span_help(
558         &mut self,
559         sp: impl Into<MultiSpan>,
560         msg: impl Into<SubdiagnosticMessage>,
561     ) -> &mut Self);
562     forward!(pub fn help_use_latest_edition(&mut self,) -> &mut Self);
563     forward!(pub fn set_is_lint(&mut self,) -> &mut Self);
564
565     forward!(pub fn disable_suggestions(&mut self,) -> &mut Self);
566     forward!(pub fn clear_suggestions(&mut self,) -> &mut Self);
567
568     forward!(pub fn multipart_suggestion(
569         &mut self,
570         msg: impl Into<SubdiagnosticMessage>,
571         suggestion: Vec<(Span, String)>,
572         applicability: Applicability,
573     ) -> &mut Self);
574     forward!(pub fn multipart_suggestion_verbose(
575         &mut self,
576         msg: impl Into<SubdiagnosticMessage>,
577         suggestion: Vec<(Span, String)>,
578         applicability: Applicability,
579     ) -> &mut Self);
580     forward!(pub fn tool_only_multipart_suggestion(
581         &mut self,
582         msg: impl Into<SubdiagnosticMessage>,
583         suggestion: Vec<(Span, String)>,
584         applicability: Applicability,
585     ) -> &mut Self);
586     forward!(pub fn span_suggestion(
587         &mut self,
588         sp: Span,
589         msg: impl Into<SubdiagnosticMessage>,
590         suggestion: impl ToString,
591         applicability: Applicability,
592     ) -> &mut Self);
593     forward!(pub fn span_suggestions(
594         &mut self,
595         sp: Span,
596         msg: impl Into<SubdiagnosticMessage>,
597         suggestions: impl Iterator<Item = String>,
598         applicability: Applicability,
599     ) -> &mut Self);
600     forward!(pub fn multipart_suggestions(
601         &mut self,
602         msg: impl Into<SubdiagnosticMessage>,
603         suggestions: impl Iterator<Item = Vec<(Span, String)>>,
604         applicability: Applicability,
605     ) -> &mut Self);
606     forward!(pub fn span_suggestion_short(
607         &mut self,
608         sp: Span,
609         msg: impl Into<SubdiagnosticMessage>,
610         suggestion: impl ToString,
611         applicability: Applicability,
612     ) -> &mut Self);
613     forward!(pub fn span_suggestion_verbose(
614         &mut self,
615         sp: Span,
616         msg: impl Into<SubdiagnosticMessage>,
617         suggestion: impl ToString,
618         applicability: Applicability,
619     ) -> &mut Self);
620     forward!(pub fn span_suggestion_hidden(
621         &mut self,
622         sp: Span,
623         msg: impl Into<SubdiagnosticMessage>,
624         suggestion: impl ToString,
625         applicability: Applicability,
626     ) -> &mut Self);
627     forward!(pub fn tool_only_span_suggestion(
628         &mut self,
629         sp: Span,
630         msg: impl Into<SubdiagnosticMessage>,
631         suggestion: impl ToString,
632         applicability: Applicability,
633     ) -> &mut Self);
634
635     forward!(pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self);
636     forward!(pub fn set_span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self);
637     forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self);
638     forward!(pub fn set_arg(
639         &mut self,
640         name: impl Into<Cow<'static, str>>,
641         arg: impl IntoDiagnosticArg,
642     ) -> &mut Self);
643
644     forward!(pub fn subdiagnostic(
645         &mut self,
646         subdiagnostic: impl crate::AddToDiagnostic
647     ) -> &mut Self);
648 }
649
650 impl<G: EmissionGuarantee> Debug for DiagnosticBuilder<'_, G> {
651     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
652         self.inner.diagnostic.fmt(f)
653     }
654 }
655
656 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or cancelled
657 /// or we emit a bug.
658 impl Drop for DiagnosticBuilderInner<'_> {
659     fn drop(&mut self) {
660         match self.state {
661             // No `.emit()` or `.cancel()` calls.
662             DiagnosticBuilderState::Emittable(handler) => {
663                 if !panicking() {
664                     handler.emit_diagnostic(&mut Diagnostic::new(
665                         Level::Bug,
666                         DiagnosticMessage::Str(
667                             "the following error was constructed but not emitted".to_string(),
668                         ),
669                     ));
670                     handler.emit_diagnostic(&mut self.diagnostic);
671                     panic!("error was constructed but not emitted");
672                 }
673             }
674             // `.emit()` was previously called, or maybe we're during `.cancel()`.
675             DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
676         }
677     }
678 }
679
680 #[macro_export]
681 macro_rules! struct_span_err {
682     ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
683         $session.struct_span_err_with_code(
684             $span,
685             &format!($($message)*),
686             $crate::error_code!($code),
687         )
688     })
689 }
690
691 #[macro_export]
692 macro_rules! error_code {
693     ($code:ident) => {{ $crate::DiagnosticId::Error(stringify!($code).to_owned()) }};
694 }