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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
//! Error types.

use crate::properties::custom::Token;
use crate::rules::Location;
use crate::values::string::CowArcStr;
use cssparser::{BasicParseErrorKind, ParseError, ParseErrorKind};
use parcel_selectors::parser::SelectorParseErrorKind;
use serde::Serialize;
use std::fmt;

/// An error with a source location.
#[derive(Debug, PartialEq, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Error<T> {
  /// The type of error that occurred.
  pub kind: T,
  /// The location where the error occurred.
  pub loc: Option<ErrorLocation>,
}

impl<T: fmt::Display> fmt::Display for Error<T> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    self.kind.fmt(f)?;
    if let Some(loc) = &self.loc {
      write!(f, " at {}", loc)?;
    }
    Ok(())
  }
}

impl<T: fmt::Display + fmt::Debug> std::error::Error for Error<T> {}

/// A line and column location within a source file.
#[derive(Debug, PartialEq, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ErrorLocation {
  /// The filename in which the error occurred.
  pub filename: String,
  /// The line number, starting from 0.
  pub line: u32,
  /// The column number, starting from 1.
  pub column: u32,
}

impl ErrorLocation {
  /// Create a new error location from a source location and filename.
  pub fn new(loc: Location, filename: String) -> Self {
    ErrorLocation {
      filename,
      line: loc.line,
      column: loc.column,
    }
  }
}

impl fmt::Display for ErrorLocation {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "{}:{}:{}", self.filename, self.line, self.column)
  }
}

/// A parser error.
#[derive(Debug, PartialEq, Serialize)]
#[serde(tag = "type", content = "value")]
pub enum ParserError<'i> {
  /// An at rule body was invalid.
  AtRuleBodyInvalid,
  /// An unknown or unsupported at rule was encountered.
  AtRuleInvalid(CowArcStr<'i>),
  /// Unexpectedly encountered the end of input data.
  EndOfInput,
  /// A declaration was invalid.
  InvalidDeclaration,
  /// A media query was invalid.
  InvalidMediaQuery,
  /// Invalid CSS nesting.
  InvalidNesting,
  /// An invalid selector in an `@page` rule.
  InvalidPageSelector,
  /// An invalid value was encountered.
  InvalidValue,
  /// Invalid qualified rule.
  QualifiedRuleInvalid,
  /// A selector was invalid.
  SelectorError(SelectorError<'i>),
  /// An `@import` rule was encountered after any rule besides `@charset` or `@layer`.
  UnexpectedImportRule,
  /// A `@namespace` rule was encountered after any rules besides `@charset`, `@import`, or `@layer`.
  UnexpectedNamespaceRule,
  /// An unexpected token was encountered.
  UnexpectedToken(#[serde(skip)] Token<'i>),
}

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

impl<'i> Error<ParserError<'i>> {
  /// Creates an error from a cssparser error.
  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> {
  #[deprecated(note = "use `ParserError::to_string()` or `fmt::Display` instead")]
  #[allow(missing_docs)]
  pub fn reason(&self) -> String {
    self.to_string()
  }
}

/// A selector parsing error.
#[derive(Debug, PartialEq, Serialize)]
#[serde(tag = "type", content = "value")]
pub enum SelectorError<'i> {
  /// An unexpected token was found in an attribute selector.
  BadValueInAttr(#[serde(skip)] Token<'i>),
  /// An unexpected token was found in a class selector.
  ClassNeedsIdent(#[serde(skip)] Token<'i>),
  /// A dangling combinator was found.
  DanglingCombinator,
  /// An empty selector.
  EmptySelector,
  /// A `|` was expected in an attribute selector.
  ExpectedBarInAttr(#[serde(skip)] Token<'i>),
  /// A namespace was expected.
  ExpectedNamespace(CowArcStr<'i>),
  /// An unexpected token was encountered in a namespace.
  ExplicitNamespaceUnexpectedToken(#[serde(skip)] Token<'i>),
  /// An invalid pseudo class was encountered after a pseudo element.
  InvalidPseudoClassAfterPseudoElement,
  /// An invalid pseudo class was encountered after a `-webkit-scrollbar` pseudo element.
  InvalidPseudoClassAfterWebKitScrollbar,
  /// A `-webkit-scrollbar` state was encountered before a `-webkit-scrollbar` pseudo element.
  InvalidPseudoClassBeforeWebKitScrollbar,
  /// Invalid qualified name in attribute selector.
  InvalidQualNameInAttr(#[serde(skip)] Token<'i>),
  /// The current token is not allowed in this state.
  InvalidState,
  /// The selector is required to have the `&` nesting selector at the start.
  MissingNestingPrefix,
  /// The selector is missing a `&` nesting selector.
  MissingNestingSelector,
  /// No qualified name in attribute selector.
  NoQualifiedNameInAttributeSelector(#[serde(skip)] Token<'i>),
  /// An Invalid token was encountered in a pseudo element.
  PseudoElementExpectedIdent(#[serde(skip)] Token<'i>),
  /// An unexpected identifier was encountered.
  UnexpectedIdent(CowArcStr<'i>),
  /// An unexpected token was encountered inside an attribute selector.
  UnexpectedTokenInAttributeSelector(#[serde(skip)] Token<'i>),
  /// An unsupported pseudo class or pseudo element was encountered.
  UnsupportedPseudoClassOrElement(CowArcStr<'i>),
}

impl<'i> fmt::Display for SelectorError<'i> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    use SelectorError::*;
    match self {
      InvalidState => write!(f, "Invalid state"),
      BadValueInAttr(token) => write!(f, "Invalid value in attribute selector: {:?}", token),
      ClassNeedsIdent(token) => write!(f, "Expected identifier in class selector, got {:?}", token),
      DanglingCombinator => write!(f, "Invalid dangling combinator in selector"),
      EmptySelector => write!(f, "Invalid empty selector"),
      ExpectedBarInAttr(name) => write!(f, "Expected | in attribute, got {:?}", name),
      ExpectedNamespace(name) => write!(f, "Expected namespace: {}", name),
      ExplicitNamespaceUnexpectedToken(token) => write!(f, "Unexpected token in namespace selector: {:?}", token),
      InvalidPseudoClassAfterPseudoElement => write!(f, "Invalid pseudo class after pseudo element, only user action pseudo classes (e.g. :hover, :active) are allowed"),
      InvalidPseudoClassAfterWebKitScrollbar => write!(f, "Invalid pseudo class after ::-webkit-scrollbar pseudo element"),
      InvalidPseudoClassBeforeWebKitScrollbar => write!(f, "Pseudo class must be prefixed by a ::-webkit-scrollbar pseudo element"),
      InvalidQualNameInAttr(token) => write!(f, "Invalid qualified name in attribute selector: {:?}", token),
      MissingNestingPrefix => write!(f, "A nesting selector (&) is required as a prefix of each selector in a nested style rule"),
      MissingNestingSelector => write!(f, "A nesting selector (&) is required in each selector of a @nest rule"),
      NoQualifiedNameInAttributeSelector(token) => write!(f, "No qualified name in attribute selector: {:?}.", token),
      PseudoElementExpectedIdent(token) => write!(f, "Invalid token in pseudo element: {:?}", token),
      UnexpectedIdent(name) => write!(f, "Unexpected identifier: {}", name),
      UnexpectedTokenInAttributeSelector(token) => write!(f, "Unexpected token in attribute selector: {:?}", token),
      UnsupportedPseudoClassOrElement(name) => write!(f, "Unsupported pseudo class or element: {}", name),
    }
  }
}

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::InvalidPseudoClassBeforeWebKitScrollbar => {
        SelectorError::InvalidPseudoClassBeforeWebKitScrollbar
      }
      SelectorParseErrorKind::InvalidPseudoClassAfterWebKitScrollbar => {
        SelectorError::InvalidPseudoClassAfterWebKitScrollbar
      }
      SelectorParseErrorKind::InvalidPseudoClassAfterPseudoElement => {
        SelectorError::InvalidPseudoClassAfterPseudoElement
      }
      SelectorParseErrorKind::InvalidState => SelectorError::InvalidState,
      SelectorParseErrorKind::MissingNestingSelector => SelectorError::MissingNestingSelector,
      SelectorParseErrorKind::MissingNestingPrefix => SelectorError::MissingNestingPrefix,
      SelectorParseErrorKind::UnexpectedTokenInAttributeSelector(t) => {
        SelectorError::UnexpectedTokenInAttributeSelector(t.into())
      }
      SelectorParseErrorKind::PseudoElementExpectedIdent(t) => SelectorError::PseudoElementExpectedIdent(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()),
    }
  }
}

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

impl<T: fmt::Display> fmt::Display for ErrorWithLocation<T> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    self.kind.fmt(f)
  }
}

impl<T: fmt::Display + fmt::Debug> std::error::Error for ErrorWithLocation<T> {}

pub(crate) type MinifyError = ErrorWithLocation<MinifyErrorKind>;

/// A transformation error.
#[derive(Debug, PartialEq, Serialize)]
#[serde(tag = "type")]
pub enum MinifyErrorKind {
  /// A circular `@custom-media` rule was detected.
  CircularCustomMedia {
    /// The name of the `@custom-media` rule that was referenced circularly.
    name: String,
  },
  /// Attempted to reference a custom media rule that doesn't exist.
  CustomMediaNotDefined {
    /// The name of the `@custom-media` rule that was not defined.
    name: String,
  },
  /// Boolean logic with media types in @custom-media rules is not supported.
  UnsupportedCustomMediaBooleanLogic {
    /// The source location of the `@custom-media` rule with unsupported boolean logic.
    custom_media_loc: Location,
  },
}

impl fmt::Display for MinifyErrorKind {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    use MinifyErrorKind::*;
    match self {
      CircularCustomMedia { name } => write!(f, "Circular custom media query {} detected", name),
      CustomMediaNotDefined { name } => write!(f, "Custom media query {} is not defined", name),
      UnsupportedCustomMediaBooleanLogic { .. } => write!(
        f,
        "Boolean logic with media types in @custom-media rules is not supported by Parcel CSS"
      ),
    }
  }
}

impl MinifyErrorKind {
  #[deprecated(note = "use `MinifyErrorKind::to_string()` or `fmt::Display` instead")]
  #[allow(missing_docs)]
  pub fn reason(&self) -> String {
    self.to_string()
  }
}

/// A printer error.
pub type PrinterError = Error<PrinterErrorKind>;

/// A printer error type.
#[derive(Debug, PartialEq, Serialize)]
#[serde(tag = "type")]
pub enum PrinterErrorKind {
  /// An ambiguous relative `url()` was encountered in a custom property declaration.
  AmbiguousUrlInCustomProperty {
    /// The ambiguous URL.
    url: String,
  },
  /// A [std::fmt::Error](std::fmt::Error) was encountered in the underlying destination.
  FmtError,
  /// The CSS modules `composes` property cannot be used within nested rules.
  InvalidComposesNesting,
  /// The CSS modules `composes` property cannot be used with a simple class selector.
  InvalidComposesSelector,
}

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

impl fmt::Display for PrinterErrorKind {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    use PrinterErrorKind::*;
    match self {
      AmbiguousUrlInCustomProperty { url } => write!(f, "Ambiguous url('{}') in custom property. Relative paths are resolved from the location the var() is used, not where the custom property is defined. Use an absolute URL instead", url),
      FmtError => write!(f, "Printer error"),
      InvalidComposesNesting => write!(f, "The `composes` property cannot be used within nested rules"),
      InvalidComposesSelector => write!(f, "The `composes` property cannot be used with a simple class selector"),
    }
  }
}

impl PrinterErrorKind {
  #[deprecated(note = "use `PrinterErrorKind::to_string()` or `fmt::Display` instead")]
  #[allow(missing_docs)]
  pub fn reason(&self) -> String {
    self.to_string()
  }
}