Skip to main content

runic_diagnostics/
lib.rs

1#![no_std]
2#![deny(unsafe_code)]
3
4extern crate alloc;
5
6#[cfg(any(test, feature = "std"))]
7extern crate std;
8
9#[cfg(feature = "derive")]
10pub use runic_diagnostics_macros::{Diagnostic, Spanned};
11
12mod adhoc;
13#[cfg(feature = "std")]
14mod application;
15mod collection;
16mod descriptor;
17mod diagnostic;
18mod emit;
19mod owned;
20mod panic_support;
21mod registry;
22mod render;
23mod shims;
24mod snapshot;
25mod source;
26#[cfg(feature = "std")]
27mod terminal;
28
29#[doc(hidden)]
30pub use adhoc::AdHocDiagnostic;
31#[cfg(feature = "std")]
32pub use application::ExitWithOutcome;
33pub use collection::{
34    DefaultFailurePolicy, DiagnosticCollector, DiagnosticEntry, DiagnosticInstanceId,
35    DiagnosticLimits, DiagnosticSet, DiagnosticSink, FailurePolicy, MergeSummary, Outcome,
36    PushResult, SeverityCounts, WarningsAsErrors,
37};
38pub use descriptor::{
39    DescriptorOrigin, DiagnosticCode, DiagnosticCodeRef, DiagnosticDescriptor, DiagnosticMetadata,
40    DiagnosticTag, Explanation, Severity,
41};
42pub use diagnostic::{
43    Applicability, Diagnostic, Label, LabelStyle, Note, NoteKind, Suggestion, TextEdit,
44    VisitDiagnostic, VisitTextEdit, VisitTextEdits,
45};
46pub use emit::{EmissionFailure, EmissionStatus, EmissionSummary, Emitter, FmtEmitter};
47#[cfg(feature = "std")]
48pub use emit::{IoEmissionError, IoEmitter};
49pub use owned::{ContextFrame, DiagnosticDisplay, DiagnosticRenderError, OwnedDiagnostic, Report};
50#[cfg(feature = "std")]
51pub use panic_support::{InstallHookError, PanicHookOptions, install_panic_hook};
52pub use registry::{LookupError, RegistryError, StaticRegistry};
53#[cfg(feature = "linked-registry")]
54pub use registry::{RegistryIndex, linked_registry};
55pub use render::{AnnotateRenderer, RenderConfig, RenderError};
56pub use shims::{IntoDiagnostic, WrapErr};
57pub use snapshot::{
58    DiagnosticCodeOwned, DiagnosticRelation, DiagnosticSnapshot, OwnedCause, OwnedLabel, OwnedNote,
59    OwnedSuggestion, OwnedTextEdit, PreparationItemKind, PreparationLimits, PrepareError,
60    PreparedDiagnostic, PreparedSet, prepare_ref, prepare_ref_with_limits,
61};
62pub use source::{
63    ColumnIndex, ColumnNumber, LayeredSourceProvider, LineColumn, LineIndex, LineNumber,
64    ResolvedSource, SharedSourceProvider, Source, SourceId, SourceKey, SourceMap, SourceMapError,
65    SourceNamespace, SourceProvider, SourceRevision, SourceSpan, Span, Spanned, TextRange,
66    TextRangeError,
67};
68#[cfg(feature = "std")]
69pub use terminal::{StderrEmitter, StdoutEmitter, TerminalChoice, TerminalPolicy, TerminalWidth};
70
71pub type Result<T, E = Report> = core::result::Result<T, E>;
72
73#[doc(hidden)]
74pub mod __private {
75    pub use alloc::vec::Vec;
76
77    #[cfg(feature = "linked-registry")]
78    pub use inventory;
79
80    #[cfg(feature = "linked-registry")]
81    pub use crate::registry::RegistryEntry;
82    pub use crate::{
83        AdHocDiagnostic, OwnedTextEdit,
84        adhoc::{format_arguments, validate_canonical_code},
85        panic_support::panic_report,
86    };
87}
88
89#[macro_export]
90macro_rules! panic_report {
91    ($report:expr $(,)?) => {{ $crate::__private::panic_report($report) }};
92}
93
94#[cfg(feature = "embed-explanations")]
95#[doc(hidden)]
96#[macro_export]
97macro_rules! __include_explanation {
98    ($explanation:expr) => {
99        $crate::Explanation::Embedded($explanation)
100    };
101}
102
103#[cfg(not(feature = "embed-explanations"))]
104#[doc(hidden)]
105#[macro_export]
106macro_rules! __include_explanation {
107    ($($discarded:tt)*) => {
108        $crate::Explanation::NotEmbedded
109    };
110}
111
112#[cfg(feature = "linked-registry")]
113#[doc(hidden)]
114#[macro_export]
115macro_rules! __register_descriptor {
116    ($descriptor:expr) => {
117        $crate::__private::inventory::submit! {
118            $crate::__private::RegistryEntry::new($descriptor)
119        }
120    };
121}
122
123#[cfg(not(feature = "linked-registry"))]
124#[doc(hidden)]
125#[macro_export]
126macro_rules! __register_descriptor {
127    ($($discarded:tt)*) => {
128        const _: () = ();
129    };
130}
131
132#[doc(hidden)]
133#[macro_export]
134macro_rules! __diagnostic_severity {
135    (Error) => {
136        $crate::Severity::Error
137    };
138    (Warning) => {
139        $crate::Severity::Warning
140    };
141    (Info) => {
142        $crate::Severity::Info
143    };
144    (Hint) => {
145        $crate::Severity::Hint
146    };
147    ($other:ident) => {
148        compile_error!(concat!("unsupported diagnostic severity `", stringify!($other), "`"))
149    };
150}
151
152#[doc(hidden)]
153#[macro_export]
154macro_rules! __diagnostic_tag {
155    (Unnecessary) => {
156        $crate::DiagnosticTag::Unnecessary
157    };
158    (Deprecated) => {
159        $crate::DiagnosticTag::Deprecated
160    };
161    ($other:ident) => {
162        compile_error!(concat!("unsupported diagnostic tag `", stringify!($other), "`"))
163    };
164}
165
166#[doc(hidden)]
167#[macro_export]
168macro_rules! __diagnostic_applicability {
169    (MachineApplicable) => {
170        $crate::Applicability::MachineApplicable
171    };
172    (MaybeIncorrect) => {
173        $crate::Applicability::MaybeIncorrect
174    };
175    (HasPlaceholders) => {
176        $crate::Applicability::HasPlaceholders
177    };
178    (Unspecified) => {
179        $crate::Applicability::Unspecified
180    };
181    ($other:ident) => {
182        compile_error!(concat!("unsupported diagnostic applicability `", stringify!($other), "`"))
183    };
184}
185
186#[doc(hidden)]
187#[macro_export]
188macro_rules! __diagnostic_explanation {
189    () => {
190        $crate::Explanation::NotProvided
191    };
192    ($explanation:expr) => {
193        $crate::__include_explanation!($explanation)
194    };
195}
196
197#[doc(hidden)]
198#[macro_export]
199macro_rules! __diagnostic_url {
200    () => {
201        None
202    };
203    ($url:literal) => {
204        Some($url)
205    };
206}
207
208#[macro_export]
209macro_rules! diagnostic_codes {
210    (
211        namespace = $namespace:literal;
212        catalog = $catalog:ident;
213        $(
214            $visibility:vis $name:ident {
215                summary: $summary:literal,
216                severity: $severity:ident,
217                $(explanation: $explanation:expr,)?
218                $(documentation_url: $documentation_url:literal,)?
219                $(tags: [$($tag:ident),* $(,)?],)?
220            }
221        )*
222    ) => {
223        $(
224            const _: () = $crate::__private::validate_canonical_code(
225                concat!($namespace, "/", stringify!($name)),
226            );
227            $visibility static $name: $crate::DiagnosticDescriptor =
228                $crate::DiagnosticDescriptor {
229                    code: $crate::DiagnosticCode {
230                        namespace: $namespace,
231                        code: stringify!($name),
232                    },
233                    summary: $summary,
234                    default_severity: $crate::__diagnostic_severity!($severity),
235                    explanation:
236                        $crate::__diagnostic_explanation!($($explanation)?),
237                    documentation_url:
238                        $crate::__diagnostic_url!($($documentation_url)?),
239                    tags: &[$($($crate::__diagnostic_tag!($tag)),*)?],
240                    origin: $crate::DescriptorOrigin {
241                        module_path: module_path!(),
242                        file: file!(),
243                        line: line!(),
244                    },
245                };
246            $crate::__register_descriptor!(&$name);
247        )*
248
249        pub static $catalog: &[&'static $crate::DiagnosticDescriptor] =
250            &[$(&$name),*];
251    };
252}
253
254#[doc(hidden)]
255#[macro_export]
256macro_rules! __diagnostic_format_args {
257    ($message:literal) => {
258        format_args!($message)
259    };
260    ($message:expr) => {
261        format_args!("{}", $message)
262    };
263}
264
265#[doc(hidden)]
266#[macro_export]
267macro_rules! __diagnostic_push_label {
268    ($diagnostic:ident, primary, $span:expr) => {
269        $diagnostic.push_label($span, $crate::LabelStyle::Primary, None)
270    };
271    ($diagnostic:ident, primary, $span:expr, $message:tt) => {
272        $diagnostic.push_label(
273            $span,
274            $crate::LabelStyle::Primary,
275            Some($crate::__diagnostic_format_args!($message)),
276        )
277    };
278    ($diagnostic:ident, context, $span:expr) => {
279        $diagnostic.push_label($span, $crate::LabelStyle::Context, None)
280    };
281    ($diagnostic:ident, context, $span:expr, $message:tt) => {
282        $diagnostic.push_label(
283            $span,
284            $crate::LabelStyle::Context,
285            Some($crate::__diagnostic_format_args!($message)),
286        )
287    };
288    ($diagnostic:ident, $other:ident, $($rest:tt)*) => {
289        compile_error!(concat!("unsupported diagnostic label `", stringify!($other), "`"))
290    };
291}
292
293#[doc(hidden)]
294#[macro_export]
295macro_rules! __diagnostic_push_note {
296    ($diagnostic:ident, note, $message:tt) => {
297        $diagnostic.push_note($crate::NoteKind::Note, $crate::__diagnostic_format_args!($message))
298    };
299    ($diagnostic:ident, help, $message:tt) => {
300        $diagnostic.push_note($crate::NoteKind::Help, $crate::__diagnostic_format_args!($message))
301    };
302    ($diagnostic:ident, $other:ident, $($rest:tt)*) => {
303        compile_error!(concat!("unsupported diagnostic note `", stringify!($other), "`"))
304    };
305}
306
307#[doc(hidden)]
308#[macro_export]
309macro_rules! __diagnostic_push_suggestions {
310    ($diagnostic:ident;) => {};
311    (
312        $diagnostic:ident;
313        suggestion(
314            $message:tt,
315            applicability: $applicability:ident,
316            edits: [
317                $(edit($span:expr, $replacement:tt)),+ $(,)?
318            ]
319        )
320        $(, $(
321            suggestion(
322                $rest_message:tt,
323                applicability: $rest_applicability:ident,
324                edits: [
325                    $(edit($rest_span:expr, $rest_replacement:tt)),+ $(,)?
326                ]
327            )
328        ),* $(,)?)?
329    ) => {
330        {
331            let mut __runic_diagnostic_edits = $crate::__private::Vec::new();
332            $(
333                __runic_diagnostic_edits.push($crate::OwnedTextEdit {
334                    span: $span,
335                    replacement: $crate::__private::format_arguments(
336                        $crate::__diagnostic_format_args!($replacement),
337                    ),
338                });
339            )+
340            $diagnostic.push_suggestion(
341                $crate::__diagnostic_format_args!($message),
342                $crate::__diagnostic_applicability!($applicability),
343                __runic_diagnostic_edits,
344            );
345        }
346        $(
347            $(
348                {
349                    let mut __runic_diagnostic_edits = $crate::__private::Vec::new();
350                    $(
351                        __runic_diagnostic_edits.push($crate::OwnedTextEdit {
352                            span: $rest_span,
353                            replacement: $crate::__private::format_arguments(
354                                $crate::__diagnostic_format_args!($rest_replacement),
355                            ),
356                        });
357                    )+
358                    $diagnostic.push_suggestion(
359                        $crate::__diagnostic_format_args!($rest_message),
360                        $crate::__diagnostic_applicability!($rest_applicability),
361                        __runic_diagnostic_edits,
362                    );
363                }
364            )*
365        )?
366    };
367    ($diagnostic:ident; $($invalid:tt)+) => {
368        compile_error!("invalid suggestion syntax; expected `suggestion(message, applicability: Applicability, edits: [edit(span, replacement), ...])`")
369    };
370}
371
372#[doc(hidden)]
373#[macro_export]
374macro_rules! __diagnostic_build {
375    (
376        $root:expr;
377        $(labels: [
378            $($label_kind:ident($label_span:expr $(, $label_message:expr)?)),* $(,)?
379        ],)?
380        $(notes: [
381            $($note_kind:ident($note_message:expr)),* $(,)?
382        ],)?
383        $(suggestions: [
384            $($suggestion:tt)*
385        ],)?
386        $(cause: $cause:expr,)?
387        $(diagnostic_source: $diagnostic_source:expr,)?
388        $(related: [$($related:expr),* $(,)?],)?
389    ) => {
390        {
391            let mut __runic_diagnostic = $root;
392            $(
393                $(
394                    $crate::__diagnostic_push_label!(
395                        __runic_diagnostic,
396                        $label_kind,
397                        $label_span
398                        $(, $label_message)?
399                    );
400                )*
401            )?
402            $(
403                $(
404                    $crate::__diagnostic_push_note!(
405                        __runic_diagnostic,
406                        $note_kind,
407                        $note_message
408                    );
409                )*
410            )?
411            $(
412                $crate::__diagnostic_push_suggestions!(
413                    __runic_diagnostic;
414                    $($suggestion)*
415                );
416            )?
417            $(
418                __runic_diagnostic.set_cause($cause);
419            )?
420            $(
421                __runic_diagnostic.set_diagnostic_source($diagnostic_source);
422            )?
423            $(
424                $(
425                    __runic_diagnostic.push_related($related);
426                )*
427            )?
428            __runic_diagnostic
429        }
430    };
431}
432
433#[macro_export]
434macro_rules! diagnostic {
435    (
436        descriptor: $descriptor:expr,
437        severity: $severity:ident,
438        message: $message:tt
439        $(, $($fields:tt)*)?
440    ) => {
441        $crate::__diagnostic_build!(
442            $crate::__private::AdHocDiagnostic::new(
443                $crate::__diagnostic_format_args!($message),
444            )
445            .with_descriptor($descriptor)
446            .with_severity($crate::__diagnostic_severity!($severity));
447            $($($fields)*)?
448        )
449    };
450    (
451        descriptor: $descriptor:expr,
452        message: $message:tt
453        $(, $($fields:tt)*)?
454    ) => {
455        $crate::__diagnostic_build!(
456            $crate::__private::AdHocDiagnostic::new(
457                $crate::__diagnostic_format_args!($message),
458            )
459            .with_descriptor($descriptor);
460            $($($fields)*)?
461        )
462    };
463    (
464        severity: $severity:ident,
465        code: $code:literal,
466        message: $message:tt
467        $(, $($fields:tt)*)?
468    ) => {
469        {
470            const _: () = $crate::__private::validate_canonical_code($code);
471            $crate::__diagnostic_build!(
472                $crate::__private::AdHocDiagnostic::new(
473                    $crate::__diagnostic_format_args!($message),
474                )
475                .with_canonical_code($code)
476                .with_severity($crate::__diagnostic_severity!($severity));
477                $($($fields)*)?
478            )
479        }
480    };
481    (
482        severity: $severity:ident,
483        message: $message:tt
484        $(, $($fields:tt)*)?
485    ) => {
486        $crate::__diagnostic_build!(
487            $crate::__private::AdHocDiagnostic::new(
488                $crate::__diagnostic_format_args!($message),
489            )
490            .with_severity($crate::__diagnostic_severity!($severity));
491            $($($fields)*)?
492        )
493    };
494    (
495        code: $code:literal,
496        message: $message:tt
497        $(, $($fields:tt)*)?
498    ) => {
499        $crate::diagnostic!(
500            severity: Error,
501            code: $code,
502            message: $message
503            $(, $($fields)*)?
504        )
505    };
506    (
507        message: $message:tt
508        $(, $($fields:tt)*)?
509    ) => {
510        $crate::diagnostic!(
511            severity: Error,
512            message: $message
513            $(, $($fields)*)?
514        )
515    };
516}
517
518#[macro_export]
519macro_rules! report {
520    (severity: Warning, $($rest:tt)*) => {
521        compile_error!("report! cannot construct a literal Warning diagnostic; use diagnostic!")
522    };
523    (severity: Info, $($rest:tt)*) => {
524        compile_error!("report! cannot construct a literal Info diagnostic; use diagnostic!")
525    };
526    (severity: Hint, $($rest:tt)*) => {
527        compile_error!("report! cannot construct a literal Hint diagnostic; use diagnostic!")
528    };
529    (descriptor: $descriptor:expr, severity: Warning, $($rest:tt)*) => {
530        compile_error!("report! cannot construct a literal Warning diagnostic; use diagnostic!")
531    };
532    (descriptor: $descriptor:expr, severity: Info, $($rest:tt)*) => {
533        compile_error!("report! cannot construct a literal Info diagnostic; use diagnostic!")
534    };
535    (descriptor: $descriptor:expr, severity: Hint, $($rest:tt)*) => {
536        compile_error!("report! cannot construct a literal Hint diagnostic; use diagnostic!")
537    };
538    (severity: Error, $($rest:tt)*) => {
539        $crate::Report::new($crate::diagnostic!(severity: Error, $($rest)*))
540    };
541    (descriptor: $descriptor:expr, severity: Error, $($rest:tt)*) => {
542        $crate::Report::new($crate::diagnostic!(
543            descriptor: $descriptor,
544            severity: Error,
545            $($rest)*
546        ))
547    };
548    (descriptor: $descriptor:expr, $($rest:tt)*) => {
549        $crate::Report::new($crate::diagnostic!(
550            descriptor: $descriptor,
551            $($rest)*
552        ))
553    };
554    (code: $code:literal, $($rest:tt)*) => {
555        $crate::Report::new($crate::diagnostic!(
556            severity: Error,
557            code: $code,
558            $($rest)*
559        ))
560    };
561    (message: $message:tt $(, $($rest:tt)*)?) => {
562        $crate::Report::new($crate::diagnostic!(
563            severity: Error,
564            message: $message
565            $(, $($rest)*)?
566        ))
567    };
568    ($diagnostic:expr $(,)?) => {
569        $crate::Report::new($diagnostic)
570    };
571}