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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use parcel_selectors::parser::SelectorParseErrorKind;
use cssparser::{ParseError, ParseErrorKind, BasicParseErrorKind};
use crate::rules::Location;
use crate::properties::custom::Token;
use crate::values::string::CowArcStr;

#[derive(Debug, PartialEq, Clone)]
pub struct Error<T> {
  pub kind: T,
  pub loc: Option<ErrorLocation>
}

#[derive(Debug, PartialEq, Clone)]
pub struct ErrorLocation {
  pub filename: String,
  pub line: u32,
  pub column: u32
}

impl ErrorLocation {
  pub fn from(loc: Location, filename: String) -> Self {
    ErrorLocation {
      filename,
      line: loc.line,
      column: loc.column
    }
  }
}

#[derive(Debug, PartialEq)]
pub enum ParserError<'i> {
  /// An unexpected token was encountered.
  UnexpectedToken(Token<'i>),
  /// The end of the input was encountered unexpectedly.
  EndOfInput,
  /// An `@` rule was encountered that was invalid.
  AtRuleInvalid(CowArcStr<'i>),
  /// The body of an '@' rule was invalid.
  AtRuleBodyInvalid,
  /// A qualified rule was encountered that was invalid.
  QualifiedRuleInvalid,
  SelectorError(SelectorError<'i>),
  InvalidDeclaration,
  InvalidPageSelector,
  InvalidValue,
  InvalidMediaQuery,
  InvalidNesting,
  UnexpectedImportRule,
  UnexpectedNamespaceRule
}

impl<'i> Error<ParserError<'i>> {
  pub fn from(err: ParseError<'i, ParserError<'i>>, filename: String) -> Error<ParserError<'i>> {
    let kind = match err.kind {
      ParseErrorKind::Basic(b) => {
        match &b {
          BasicParseErrorKind::
          UnexpectedToken(t) => ParserError::UnexpectedToken(t.into()),
          BasicParseErrorKind::EndOfInput => ParserError::EndOfInput,
          BasicParseErrorKind::AtRuleInvalid(a) => ParserError::AtRuleInvalid(a.into()),
          BasicParseErrorKind::AtRuleBodyInvalid => ParserError::AtRuleBodyInvalid,
          BasicParseErrorKind::QualifiedRuleInvalid => ParserError::QualifiedRuleInvalid,
        }
      }
      ParseErrorKind::Custom(c) => c
    };

    Error {
      kind,
      loc: Some(ErrorLocation {
        filename,
        line: err.location.line,
        column: err.location.column
      })
    }
  }
}

impl<'i> From<SelectorParseErrorKind<'i>> for ParserError<'i> {
  fn from(err: SelectorParseErrorKind<'i>) -> ParserError<'i> {
    ParserError::SelectorError(err.into())
  }
}

impl<'i> ParserError<'i> {
  pub fn reason(&self) -> String {
    match self {
      ParserError::AtRuleBodyInvalid => "Invalid at rule body".into(),
      ParserError::EndOfInput => "Unexpected end of input".into(),
      ParserError::AtRuleInvalid(name) => format!("Unknown at rule: @{}", name),
      ParserError::QualifiedRuleInvalid => "Invalid qualified rule".into(),
      ParserError::UnexpectedToken(token) => format!("Unexpected token {:?}", token),
      ParserError::InvalidDeclaration => "Invalid declaration".into(),
      ParserError::InvalidMediaQuery => "Invalid media query".into(),
      ParserError::InvalidNesting => "Invalid nesting".into(),
      ParserError::InvalidPageSelector => "Invalid page selector".into(),
      ParserError::InvalidValue => "Invalid value".into(),
      ParserError::UnexpectedImportRule => "@import rules must precede all rules aside from @charset and @layer statements".into(),
      ParserError::UnexpectedNamespaceRule => "@namespaces rules must precede all rules aside from @charset, @import, and @layer statements".into(),
      ParserError::SelectorError(s) => s.reason()
    }
  }
}

#[derive(Debug, PartialEq)]
pub enum SelectorError<'i> {
  NoQualifiedNameInAttributeSelector(Token<'i>),
  EmptySelector,
  DanglingCombinator,
  NonCompoundSelector,
  NonPseudoElementAfterSlotted,
  InvalidPseudoElementAfterSlotted,
  InvalidPseudoElementInsideWhere,
  InvalidState,
  MissingNestingSelector,
  MissingNestingPrefix,
  UnexpectedTokenInAttributeSelector(Token<'i>),
  PseudoElementExpectedColon(Token<'i>),
  PseudoElementExpectedIdent(Token<'i>),
  NoIdentForPseudo(Token<'i>),
  UnsupportedPseudoClassOrElement(CowArcStr<'i>),
  UnexpectedIdent(CowArcStr<'i>),
  ExpectedNamespace(CowArcStr<'i>),
  ExpectedBarInAttr(Token<'i>),
  BadValueInAttr(Token<'i>),
  InvalidQualNameInAttr(Token<'i>),
  ExplicitNamespaceUnexpectedToken(Token<'i>),
  ClassNeedsIdent(Token<'i>),
}

impl<'i> From<SelectorParseErrorKind<'i>> for SelectorError<'i> {
  fn from(err: SelectorParseErrorKind<'i>) -> Self {
    match &err {
      SelectorParseErrorKind::NoQualifiedNameInAttributeSelector(t) => SelectorError::NoQualifiedNameInAttributeSelector(t.into()),
      SelectorParseErrorKind::EmptySelector => SelectorError::EmptySelector,
      SelectorParseErrorKind::DanglingCombinator => SelectorError::DanglingCombinator,
      SelectorParseErrorKind::NonCompoundSelector => SelectorError::NonCompoundSelector,
      SelectorParseErrorKind::NonPseudoElementAfterSlotted => SelectorError::NonPseudoElementAfterSlotted,
      SelectorParseErrorKind::InvalidPseudoElementAfterSlotted => SelectorError::InvalidPseudoElementAfterSlotted,
      SelectorParseErrorKind::InvalidPseudoElementInsideWhere => SelectorError::InvalidPseudoElementInsideWhere,
      SelectorParseErrorKind::InvalidState => SelectorError::InvalidState,
      SelectorParseErrorKind::MissingNestingSelector => SelectorError::MissingNestingSelector,
      SelectorParseErrorKind::MissingNestingPrefix => SelectorError::MissingNestingPrefix,
      SelectorParseErrorKind::UnexpectedTokenInAttributeSelector(t) => SelectorError::UnexpectedTokenInAttributeSelector(t.into()),
      SelectorParseErrorKind::PseudoElementExpectedColon(t) => SelectorError::PseudoElementExpectedColon(t.into()),
      SelectorParseErrorKind::PseudoElementExpectedIdent(t) => SelectorError::PseudoElementExpectedIdent(t.into()),
      SelectorParseErrorKind::NoIdentForPseudo(t) => SelectorError::NoIdentForPseudo(t.into()),
      SelectorParseErrorKind::UnsupportedPseudoClassOrElement(t) => SelectorError::UnsupportedPseudoClassOrElement(t.into()),
      SelectorParseErrorKind::UnexpectedIdent(t) => SelectorError::UnexpectedIdent(t.into()),
      SelectorParseErrorKind::ExpectedNamespace(t) => SelectorError::ExpectedNamespace(t.into()),
      SelectorParseErrorKind::ExpectedBarInAttr(t) => SelectorError::ExpectedBarInAttr(t.into()),
      SelectorParseErrorKind::BadValueInAttr(t) => SelectorError::BadValueInAttr(t.into()),
      SelectorParseErrorKind::InvalidQualNameInAttr(t) => SelectorError::InvalidQualNameInAttr(t.into()),
      SelectorParseErrorKind::ExplicitNamespaceUnexpectedToken(t) => SelectorError::ExplicitNamespaceUnexpectedToken(t.into()),
      SelectorParseErrorKind::ClassNeedsIdent(t) => SelectorError::ClassNeedsIdent(t.into()),
    }
  }
}

impl<'i> SelectorError<'i> {
  fn reason(&self) -> String {
    use SelectorError::*;
    match self {
      NoQualifiedNameInAttributeSelector(token) => format!("No qualified name in attribute selector: {:?}.", token),
      EmptySelector => "Invalid empty selector.".into(),
      DanglingCombinator => "Invalid dangling combinator in selector.".into(),
      MissingNestingSelector => "A nesting selector (&) is required in each selector of a @nest rule.".into(),
      MissingNestingPrefix => "A nesting selector (&) is required as a prefix of each selector in a nested style rule.".into(),
      UnexpectedTokenInAttributeSelector(token) => format!("Unexpected token in attribute selector: {:?}", token),
      PseudoElementExpectedIdent(token) => format!("Invalid token in pseudo element: {:?}", token),
      UnsupportedPseudoClassOrElement(name) => format!("Unsupported pseudo class or element: {}", name),
      UnexpectedIdent(name) => format!("Unexpected identifier: {}", name),
      ExpectedNamespace(name) => format!("Expected namespace: {}", name),
      ExpectedBarInAttr(name) => format!("Expected | in attribute, got {:?}", name),
      BadValueInAttr(token) => format!("Invalid value in attribute selector: {:?}", token),
      InvalidQualNameInAttr(token) => format!("Invalid qualified name in attribute selector: {:?}", token),
      ExplicitNamespaceUnexpectedToken(token) => format!("Unexpected token in namespace selector: {:?}", token),
      ClassNeedsIdent(token) => format!("Expected identifier in class selector, got {:?}", token),
      err => format!("Error parsing selector: {:?}", err)
    }
  }
}

#[derive(Debug, PartialEq)]
pub struct ErrorWithLocation<T> {
  pub kind: T,
  pub loc: Location
}

pub type MinifyError = ErrorWithLocation<MinifyErrorKind>;

#[derive(Debug, PartialEq)]
pub enum MinifyErrorKind {
  UnsupportedCustomMediaBooleanLogic { custom_media_loc: Location },
  CustomMediaNotDefined { name: String },
  CircularCustomMedia { name: String }
}

impl MinifyErrorKind {
  pub fn reason(&self) -> String {
    match self {
      MinifyErrorKind::UnsupportedCustomMediaBooleanLogic {..} => "Boolean logic with media types in @custom-media rules is not supported by Parcel CSS.".into(),
      MinifyErrorKind::CustomMediaNotDefined { name, .. } => format!("Custom media query {} is not defined.", name),
      MinifyErrorKind::CircularCustomMedia { name, .. } => format!("Circular custom media query {} detected.", name)
    }
  }
}

pub type PrinterError = Error<PrinterErrorKind>;

#[derive(Debug)]
pub enum PrinterErrorKind {
  FmtError,
  InvalidComposesSelector,
  InvalidComposesNesting
}

impl From<std::fmt::Error> for PrinterError {
  fn from(_: std::fmt::Error) -> PrinterError {
    PrinterError {
      kind: PrinterErrorKind::FmtError,
      loc: None
    }
  }
}

impl PrinterErrorKind {
  pub fn reason(&self) -> String {
    match self {
      PrinterErrorKind::InvalidComposesSelector => "The `composes` property can only be used within a simple class selector.".into(),
      PrinterErrorKind::InvalidComposesNesting => "The `composes` property cannot be used within nested rules.".into(),
      PrinterErrorKind::FmtError => "Printer error".into()
    }
  }
}