pomsky_syntax/
warning.rs

1//! Provides warnings that are shown to the user (in addition to the output)
2
3use std::fmt;
4
5use crate::span::Span;
6
7/// A warning.
8#[derive(Clone)]
9pub struct ParseWarning {
10    /// The kind of warning
11    pub kind: ParseWarningKind,
12    /// The span pointing to the source of the warning
13    pub span: Span,
14}
15
16/// A warning without a span pointing to the source of the warning
17#[derive(Debug, Clone)]
18pub enum ParseWarningKind {
19    /// A deprecation warning
20    Deprecation(DeprecationWarning),
21}
22
23impl ParseWarningKind {
24    pub(crate) fn at(self, span: Span) -> ParseWarning {
25        ParseWarning { kind: self, span }
26    }
27}
28
29impl fmt::Display for ParseWarning {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        let ParseWarningKind::Deprecation(warning) = &self.kind;
32        if let Some(std::ops::Range { start, end }) = self.span.range() {
33            write!(f, "{warning}\n  at {start}..{end}")
34        } else {
35            write!(f, "{warning}")
36        }
37    }
38}
39
40impl fmt::Display for ParseWarningKind {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        let ParseWarningKind::Deprecation(c) = self;
43        c.fmt(f)
44    }
45}
46
47/// A deprecation warning: Indicates that something shouldn't be used anymore
48#[derive(Debug, Clone)]
49pub enum DeprecationWarning {
50    /// U+147A, U147A
51    Unicode(String),
52    /// A shorthand character in a range, e.g. `[a-f]`
53    ShorthandInRange(char),
54}
55
56impl fmt::Display for DeprecationWarning {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        match self {
59            DeprecationWarning::Unicode(u) => {
60                let rest = u.trim_start_matches(['U', '+']);
61                write!(f, "This syntax is deprecated. Use `U+{rest}` instead.")
62            }
63            &DeprecationWarning::ShorthandInRange(c) => {
64                write!(
65                    f,
66                    "Shorthands in character ranges are deprecated. Use U+{:02X} instead",
67                    c as u8
68                )
69            }
70        }
71    }
72}