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