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