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