1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
//! Error management.

use crate::pos::Span;
#[cfg(feature = "serialize")]
use serde::Serialize;
use std::fmt::Display;

#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "camelCase"))]
pub struct Error {
    pub kind: ErrorKind,
    pub span: Span,
}

#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
pub enum ErrorKind {
    Unexpected(
        /* expected */ &'static str,
        /* actual */ &'static str,
    ),
    ExpectOneOf(
        /* expected */ Vec<&'static str>,
        /* actual */ &'static str,
    ),

    UnknownToken,
    InvalidNumber,
    InvalidEscape,
    InvalidHash,
    ExpectRightBraceForLessVar,
    UnexpectedLinebreak,
    UnexpectedEof,
    UnterminatedString,

    ExpectRule,
    UnexpectedWhitespace,
    UnexpectedWhitespaceOrComments,
    ExpectSimpleSelector,
    ExpectTypeSelector,
    ExpectIdSelector,
    ExpectWqName,
    ExpectAttributeSelectorMatcher,
    ExpectAttributeSelectorValue,
    ExpectComponentValue,
    ExpectSassExpression,
    ExpectDedentOrEof,
    ExpectString,
    ExpectUrl,
    InvalidUrl,
    UnexpectedTemplateInCss,
    ExpectMediaFeatureComparison,
    ExpectMediaAnd,
    ExpectMediaOr,
    ExpectMediaNot,
    ExpectContainerConditionAnd,
    ExpectContainerConditionOr,
    ExpectContainerConditionNot,
    ExpectStyleConditionAnd,
    ExpectStyleConditionOr,
    ExpectStyleConditionNot,
    ExpectStyleQuery,
    ExpectSassKeyword(&'static str),
    InvalidAnPlusB,
    ExpectInteger,
    ExpectUnsignedInteger,
    ExpectImportantAnnotation,
    ExpectSassUseNamespace,
    InvalidUnicodeRange,
    UnexpectedSassElseAtRule,
    ExpectSassAtRootWithOrWithout,
    ExpectNthOf,
    ExpectKeyframeBlock,
    MixedDelimiterKindInLessMixin,
    ExpectLessKeyword(&'static str),
    ExpectLessExtendRule,
    ExpectScopeTo,

    TryParseError,
    CSSWideKeywordDisallowed,
    MediaTypeKeywordDisallowed(String),
    UnknownKeyframeSelectorIdent,
    InvalidRatioDenominator,
    ExpectMediaFeatureName,
    ExpectDashedIdent,
    InvalidIdSelectorName,
    ReturnOutsideFunction,
    MaxCodePointExceeded,
    UnicodeRangeStartGreaterThanEnd,
    UnexpectedNthMatcher,
    InvalidSassFlagName(String),
    UnexpectedSassFlag(&'static str),
    DuplicatedSassFlag(&'static str),
    LessGuardOnMultipleComplexSelectors,
    UnexpectedLessMixinCall,
    UnexpectedSemicolonInSass,
}

impl Display for ErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Unexpected(expected, actual) => {
                write!(f, "expect token `{expected}`, but found `{actual}`")
            }
            Self::ExpectOneOf(expected, actual) => {
                if let [init @ .., last] = &expected[..] {
                    let joined = init
                        .iter()
                        .map(|token| format!("`{token}`"))
                        .collect::<Vec<_>>()
                        .join(", ");
                    write!(
                        f,
                        "expect one of {} or `{last}`, but found `{actual}`",
                        joined
                    )
                } else {
                    panic!("the number of expected tokens must be at least 2")
                }
            }

            Self::UnknownToken => write!(f, "unknown token"),
            Self::InvalidNumber => write!(f, "invalid number"),
            Self::InvalidEscape => write!(f, "invalid escape"),
            Self::InvalidHash => write!(f, "invalid hash token"),
            Self::ExpectRightBraceForLessVar => write!(f, "`}}` for Less variable is expected"),
            Self::UnexpectedLinebreak => write!(f, "unexpected linebreak"),
            Self::UnexpectedEof => write!(f, "unexpected end of file"),
            Self::UnterminatedString => write!(f, "unterminated string"),

            Self::ExpectRule => write!(f, "CSS rule is expected"),
            Self::UnexpectedWhitespace => write!(f, "unexpected whitespace"),
            Self::UnexpectedWhitespaceOrComments => write!(f, "unexpected whitespace or comments"),
            Self::ExpectSimpleSelector => write!(f, "simple selector is expected"),
            Self::ExpectTypeSelector => write!(f, "type selector is expected"),
            Self::ExpectIdSelector => write!(f, "ID selector is expected"),
            Self::ExpectWqName => write!(f, "WqName is expected"),
            Self::ExpectAttributeSelectorMatcher => {
                write!(f, "attribute selector matcher is expected")
            }
            Self::ExpectAttributeSelectorValue => write!(f, "attribute selector value is expected"),
            Self::ExpectComponentValue => write!(f, "component value is expected"),
            Self::ExpectSassExpression => write!(f, "Sass expression is expected"),
            Self::ExpectDedentOrEof => write!(f, "dedentation or end of file is expected"),
            Self::ExpectString => write!(f, "string is expected"),
            Self::ExpectUrl => write!(f, "URL is expected"),
            Self::InvalidUrl => write!(f, "invalid URL"),
            Self::UnexpectedTemplateInCss => write!(f, "template isn't allowed in CSS"),
            Self::ExpectMediaFeatureComparison => write!(f, "media feature comparison is expected"),
            Self::ExpectMediaAnd => write!(f, "media query `and` is expected"),
            Self::ExpectMediaOr => write!(f, "media query `or` is expected"),
            Self::ExpectMediaNot => write!(f, "media query `not` is expected"),
            Self::ExpectContainerConditionAnd => write!(f, "container condition `and` is expected"),
            Self::ExpectContainerConditionOr => write!(f, "container condition `or` is expected"),
            Self::ExpectContainerConditionNot => write!(f, "container condition `not` is expected"),
            Self::ExpectStyleConditionAnd => write!(f, "style condition `and` is expected"),
            Self::ExpectStyleConditionOr => write!(f, "style condition `or` is expected"),
            Self::ExpectStyleConditionNot => write!(f, "style condition `not` is expected"),
            Self::ExpectStyleQuery => write!(f, "style query is expected"),
            Self::ExpectSassKeyword(keyword) => write!(f, "Sass keyword `{keyword}` is expected"),
            Self::InvalidAnPlusB => write!(f, "invalid An+B syntax"),
            Self::ExpectInteger => write!(f, "an integer is expected"),
            Self::ExpectUnsignedInteger => write!(f, "unsigned integer is expected"),
            Self::ExpectImportantAnnotation => write!(f, "`!important` is expected"),
            Self::ExpectSassUseNamespace => {
                write!(f, "`*` or ident for Sass namespace is expected")
            }
            Self::InvalidUnicodeRange => write!(f, "invalid unicode range"),
            Self::UnexpectedSassElseAtRule => write!(f, "Sass `@else` at-rule is disallowed here"),
            Self::ExpectSassAtRootWithOrWithout => {
                write!(f, "Sass identifier `with` or `without` is expected")
            }
            Self::ExpectNthOf => write!(f, "`of` is expected"),
            Self::ExpectKeyframeBlock => write!(f, "keyframe block is expected"),
            Self::MixedDelimiterKindInLessMixin => write!(
                f,
                "using both `;` and `,` as delimiters in the same Less mixin is disallowed"
            ),
            Self::ExpectLessKeyword(keyword) => write!(f, "Less keyword `{keyword}` is expected"),
            Self::ExpectLessExtendRule => write!(f, "Less extend rule is expected"),
            Self::ExpectScopeTo => write!(f, "keyword `to` of `@scope` at-rule is expected"),

            Self::TryParseError => unreachable!(),
            Self::CSSWideKeywordDisallowed => {
                write!(f, "using CSS wide keyword as identifier is disallowed")
            }
            Self::MediaTypeKeywordDisallowed(keyword) => {
                write!(f, "keyword `{keyword}` as media type is disallowed")
            }
            Self::UnknownKeyframeSelectorIdent => write!(f, "unknown keyframe selector"),
            Self::InvalidRatioDenominator => write!(f, "ratio denominator is invalid"),
            Self::ExpectMediaFeatureName => write!(f, "media feature name is expected"),
            Self::ExpectDashedIdent => write!(f, "dashed identifier is expected"),
            Self::InvalidIdSelectorName => write!(f, "invalid ID selector name"),
            Self::ReturnOutsideFunction => write!(f, "`@return` is disallowed outside function"),
            Self::MaxCodePointExceeded => {
                write!(f, "unicode range end value exceeds max allowed code point")
            }
            Self::UnicodeRangeStartGreaterThanEnd => {
                write!(f, "unicode range start value can't greater than end value")
            }
            Self::UnexpectedNthMatcher => write!(
                f,
                "elements matcher is allowed in `:nth-child` and `:nth-last-child` only"
            ),
            Self::InvalidSassFlagName(flag) => write!(f, "invalid Sass flag name `{flag}`"),
            Self::UnexpectedSassFlag(flag) => write!(f, "Sass flag `!{flag}` is disallowed"),
            Self::DuplicatedSassFlag(flag) => write!(f, "duplicated Sass flag `!{flag}`"),
            Self::LessGuardOnMultipleComplexSelectors => write!(
                f,
                "Less guards are only allowed on a single complex selector"
            ),
            Self::UnexpectedLessMixinCall => write!(f, "Less mixin call is disallowed"),
            Self::UnexpectedSemicolonInSass => write!(f, "semicolon in Sass is disallowed"),
        }
    }
}

pub type PResult<T> = Result<T, Error>;