Skip to main content

css_tokenize/
lib.rs

1//! A CSS tokenizer, implementing [CSS Syntax Module Level 3][spec] §3
2//! (Tokenizing and Parsing CSS) and §4 (Tokenization), written in 100% safe
3//! Rust and without dependencies.
4//!
5//! This crate only turns a `&str` into a stream of tokens. It knows nothing
6//! about grammars built on top of CSS tokens (media queries, selectors,
7//! stylesheets).
8//!
9//! ```
10//! use css_tokenize::{Token, tokenize};
11//!
12//! let tokens = tokenize("a:hover");
13//! assert!(matches!(tokens[0], Token::Ident(_)));
14//! ```
15//!
16//! [spec]: https://www.w3.org/TR/css-syntax-3/
17
18#![forbid(unsafe_code)]
19#![warn(missing_docs)]
20
21/// Numeric type flag, as used by [`Token::Number`] and
22/// [`Token::Dimension`] (spec §4.3.12, "Consume a number").
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24#[non_exhaustive]
25pub enum NumericType {
26    /// The number had no fractional part or exponent.
27    Integer,
28    /// The number had a fractional part and/or an exponent.
29    Number,
30}
31
32/// Type flag of a [`Token::Hash`] (spec §4.3.1, the `#` branch).
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34#[non_exhaustive]
35pub enum HashType {
36    /// The hash's value would be a valid ID selector (starts with an
37    /// ident sequence).
38    Id,
39    /// The hash's value does not qualify as an ID selector.
40    Unrestricted,
41}
42
43/// A single CSS token, per spec §4.3.1 ("Consume a token") and the
44/// token types defined at the start of §4.3.
45#[derive(Debug, Clone, PartialEq)]
46#[non_exhaustive]
47pub enum Token {
48    /// An identifier, e.g. `screen`.
49    Ident(String),
50    /// An identifier immediately followed by `(`, e.g. `calc(`. The
51    /// `(` itself is consumed but not part of the stored string.
52    Function(String),
53    /// `@` followed by an ident sequence, e.g. `@media`.
54    AtKeyword(String),
55    /// `#` followed by an ident-code-point/escape sequence, e.g. `#foo`.
56    Hash {
57        /// The value after `#`.
58        value: String,
59        /// Whether the value would itself be a valid ID selector.
60        type_flag: HashType,
61    },
62    /// A quoted string, e.g. `"screen"`.
63    String(String),
64    /// A string that was not terminated correctly (e.g. an unescaped
65    /// newline before the closing quote).
66    BadString,
67    /// A `url(...)` token with an unquoted value.
68    Url(String),
69    /// A `url(...)` construct that could not be tokenized as a valid
70    /// URL token (e.g. an unescaped space in the unquoted value).
71    BadUrl,
72    /// A single code point that didn't start any other token, e.g. `^`.
73    Delim(char),
74    /// A numeric literal with no unit or `%` suffix, e.g. `42`.
75    Number {
76        /// The parsed numeric value.
77        value: f64,
78        /// Whether the literal had a fractional part/exponent.
79        type_flag: NumericType,
80    },
81    /// A numeric literal followed by `%`, e.g. `50%`.
82    Percentage {
83        /// The parsed numeric value (before the `%`).
84        value: f64,
85    },
86    /// A numeric literal followed by a unit, e.g. `10px`.
87    Dimension {
88        /// The parsed numeric value (before the unit).
89        value: f64,
90        /// Whether the literal had a fractional part/exponent.
91        type_flag: NumericType,
92        /// The unit identifier, e.g. `px`.
93        unit: String,
94    },
95    /// One or more consecutive whitespace code points.
96    Whitespace,
97    /// `<!--`
98    Cdo,
99    /// `-->`
100    Cdc,
101    /// `:`
102    Colon,
103    /// `;`
104    Semicolon,
105    /// `,`
106    Comma,
107    /// `[`
108    OpenSquare,
109    /// `]`
110    CloseSquare,
111    /// `(`
112    OpenParen,
113    /// `)`
114    CloseParen,
115    /// `{`
116    OpenCurly,
117    /// `}`
118    CloseCurly,
119    /// The end of the input stream. Always the last token produced by
120    /// [`Tokenizer`], never followed by another token.
121    Eof,
122}
123
124/// Preprocesses the input stream per spec §3.3 ("Preprocessing the
125/// input stream"):
126///
127/// - CR, FF, and CRLF are normalized to a single LF.
128/// - U+0000 NULL is replaced with U+FFFD REPLACEMENT CHARACTER.
129///
130/// The spec also requires replacing lone surrogates with U+FFFD, but
131/// that step is a no-op here: `input` is a Rust `&str`, which is
132/// guaranteed to be valid UTF-8, and surrogate code points cannot
133/// occur in valid UTF-8. There is no surrogate case to handle.
134fn preprocess(input: &str) -> String {
135    let mut out = String::with_capacity(input.len());
136    let mut chars = input.chars().peekable();
137    while let Some(c) = chars.next() {
138        match c {
139            '\r' => {
140                if chars.peek() == Some(&'\n') {
141                    chars.next();
142                }
143                out.push('\n');
144            }
145            '\u{000C}' => out.push('\n'),
146            '\u{0000}' => out.push('\u{FFFD}'),
147            other => out.push(other),
148        }
149    }
150    out
151}
152
153/// Spec §4.2: "letter" is an uppercase or lowercase ASCII letter.
154fn is_letter(c: char) -> bool {
155    c.is_ascii_alphabetic()
156}
157
158/// Spec §4.2: "non-ASCII code point" is any code point >= U+0080.
159fn is_non_ascii(c: char) -> bool {
160    !c.is_ascii()
161}
162
163/// Spec §4.2: "ident-start code point".
164fn is_ident_start(c: char) -> bool {
165    is_letter(c) || is_non_ascii(c) || c == '_'
166}
167
168/// Spec §4.2: "ident code point".
169fn is_ident_code_point(c: char) -> bool {
170    is_ident_start(c) || c.is_ascii_digit() || c == '-'
171}
172
173/// Spec §4.2: "non-printable code point".
174fn is_non_printable(c: char) -> bool {
175    matches!(c, '\u{0000}'..='\u{0008}' | '\u{000B}' | '\u{000E}'..='\u{001F}' | '\u{007F}')
176}
177
178/// Spec §4.2: "whitespace" (newline, tab, or space; CR/FF have already
179/// been normalized away by [`preprocess`]).
180fn is_whitespace(c: char) -> bool {
181    matches!(c, '\n' | '\t' | ' ')
182}
183
184fn is_surrogate(value: u32) -> bool {
185    (0xD800..=0xDFFF).contains(&value)
186}
187
188/// A tokenizer over a preprocessed input stream, per spec §4.3.
189///
190/// Implements [`Iterator`], yielding tokens in order and ending with a
191/// single [`Token::Eof`], after which it yields `None`.
192pub struct Tokenizer {
193    input: Vec<char>,
194    pos: usize,
195    done: bool,
196}
197
198impl Tokenizer {
199    /// Creates a tokenizer over `input`, applying the spec §3.3
200    /// preprocessing step (newline normalization, NULL replacement) up
201    /// front.
202    pub fn new(input: &str) -> Self {
203        Self {
204            input: preprocess(input).chars().collect(),
205            pos: 0,
206            done: false,
207        }
208    }
209
210    fn peek_n(&self, n: usize) -> Option<char> {
211        self.input.get(self.pos + n).copied()
212    }
213
214    fn peek(&self) -> Option<char> {
215        self.peek_n(0)
216    }
217
218    /// Consumes as much whitespace as possible. Shared substep of several
219    /// spec algorithms (not itself a named spec algorithm).
220    fn skip_whitespace(&mut self) {
221        while matches!(self.peek(), Some(w) if is_whitespace(w)) {
222            self.pos += 1;
223        }
224    }
225
226    /// Spec §4.3.8: "Check if two code points are a valid escape",
227    /// applied to the two code points starting at `offset`.
228    fn is_valid_escape_at(&self, offset: usize) -> bool {
229        match self.peek_n(offset) {
230            Some('\\') => !matches!(self.peek_n(offset + 1), Some('\n')),
231            _ => false,
232        }
233    }
234
235    /// Spec §4.3.9: "Check if three code points would start an ident
236    /// sequence", applied starting at `offset`.
237    fn starts_ident_sequence(&self, offset: usize) -> bool {
238        match self.peek_n(offset) {
239            Some('-') => match self.peek_n(offset + 1) {
240                Some(c) if is_ident_start(c) || c == '-' => true,
241                _ => self.is_valid_escape_at(offset + 1),
242            },
243            Some(c) if is_ident_start(c) => true,
244            Some('\\') => self.is_valid_escape_at(offset),
245            _ => false,
246        }
247    }
248
249    /// Spec §4.3.10: "Check if three code points would start a
250    /// number", applied starting at `offset`.
251    fn starts_number(&self, offset: usize) -> bool {
252        match self.peek_n(offset) {
253            Some('+') | Some('-') => match self.peek_n(offset + 1) {
254                Some(c) if c.is_ascii_digit() => true,
255                Some('.') => matches!(self.peek_n(offset + 2), Some(c) if c.is_ascii_digit()),
256                _ => false,
257            },
258            Some('.') => matches!(self.peek_n(offset + 1), Some(c) if c.is_ascii_digit()),
259            Some(c) if c.is_ascii_digit() => true,
260            _ => false,
261        }
262    }
263
264    /// Spec §4.3.2: "Consume comments". Comments produce no token.
265    fn consume_comments(&mut self) {
266        while self.peek() == Some('/') && self.peek_n(1) == Some('*') {
267            self.pos += 2;
268            loop {
269                match self.peek() {
270                    None => return, // parse error: EOF inside comment
271                    Some('*') if self.peek_n(1) == Some('/') => {
272                        self.pos += 2;
273                        break;
274                    }
275                    _ => self.pos += 1,
276                }
277            }
278        }
279    }
280
281    /// Spec §4.3.7: "Consume an escaped code point". Assumes the
282    /// leading backslash has already been consumed.
283    fn consume_escaped_code_point(&mut self) -> char {
284        match self.peek() {
285            Some(c) if c.is_ascii_hexdigit() => {
286                let mut hex = String::new();
287                hex.push(c);
288                self.pos += 1;
289                for _ in 0..5 {
290                    match self.peek() {
291                        Some(h) if h.is_ascii_hexdigit() => {
292                            hex.push(h);
293                            self.pos += 1;
294                        }
295                        _ => break,
296                    }
297                }
298                if matches!(self.peek(), Some(w) if is_whitespace(w)) {
299                    self.pos += 1;
300                }
301                let value = u32::from_str_radix(&hex, 16).unwrap_or(0);
302                if value == 0 || is_surrogate(value) || value > 0x10FFFF {
303                    '\u{FFFD}'
304                } else {
305                    char::from_u32(value).unwrap_or('\u{FFFD}')
306                }
307            }
308            Some(c) => {
309                self.pos += 1;
310                c
311            }
312            None => '\u{FFFD}', // parse error: EOF
313        }
314    }
315
316    /// Spec §4.3.11: "Consume an ident sequence".
317    fn consume_ident_sequence(&mut self) -> String {
318        let mut result = String::new();
319        loop {
320            match self.peek() {
321                Some(c) if is_ident_code_point(c) => {
322                    result.push(c);
323                    self.pos += 1;
324                }
325                Some('\\') if self.is_valid_escape_at(0) => {
326                    self.pos += 1;
327                    let ch = self.consume_escaped_code_point();
328                    result.push(ch);
329                }
330                _ => break,
331            }
332        }
333        result
334    }
335
336    /// Spec §4.3.12: "Consume a number". Returns the (grammar-exact)
337    /// representation string together with its type flag.
338    ///
339    /// The representation is parsed with `str::parse::<f64>`, which
340    /// implements the same sign/integer/fraction/exponent semantics
341    /// as spec §4.3.13 ("Convert a string to a number") for any
342    /// string this algorithm can produce.
343    fn consume_number(&mut self) -> (f64, NumericType) {
344        let mut repr = String::new();
345        let mut type_flag = NumericType::Integer;
346
347        if matches!(self.peek(), Some('+') | Some('-')) {
348            repr.push(self.peek().unwrap());
349            self.pos += 1;
350        }
351        while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
352            repr.push(self.peek().unwrap());
353            self.pos += 1;
354        }
355        if self.peek() == Some('.') && matches!(self.peek_n(1), Some(c) if c.is_ascii_digit()) {
356            repr.push('.');
357            self.pos += 1;
358            type_flag = NumericType::Number;
359            while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
360                repr.push(self.peek().unwrap());
361                self.pos += 1;
362            }
363        }
364        if matches!(self.peek(), Some('e') | Some('E')) {
365            let has_sign = matches!(self.peek_n(1), Some('+') | Some('-'));
366            let digit_offset = if has_sign { 2 } else { 1 };
367            if matches!(self.peek_n(digit_offset), Some(c) if c.is_ascii_digit()) {
368                repr.push(self.peek().unwrap());
369                self.pos += 1;
370                if has_sign {
371                    repr.push(self.peek().unwrap());
372                    self.pos += 1;
373                }
374                type_flag = NumericType::Number;
375                while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
376                    repr.push(self.peek().unwrap());
377                    self.pos += 1;
378                }
379            }
380        }
381
382        // `repr` is only reached via `starts_number`, which guarantees
383        // a syntactically valid CSS number literal, so this always
384        // parses.
385        let value = repr
386            .parse::<f64>()
387            .expect("consume_number produced a valid number literal");
388        (value, type_flag)
389    }
390
391    /// Spec §4.3.3: "Consume a numeric token".
392    fn consume_numeric_token(&mut self) -> Token {
393        let (value, type_flag) = self.consume_number();
394        if self.starts_ident_sequence(0) {
395            let unit = self.consume_ident_sequence();
396            Token::Dimension {
397                value,
398                type_flag,
399                unit,
400            }
401        } else if self.peek() == Some('%') {
402            self.pos += 1;
403            Token::Percentage { value }
404        } else {
405            Token::Number { value, type_flag }
406        }
407    }
408
409    /// Spec §4.3.14: "Consume the remnants of a bad url", used for
410    /// error recovery after a bad-url-token.
411    fn consume_bad_url_remnants(&mut self) {
412        loop {
413            match self.peek() {
414                Some(')') => {
415                    self.pos += 1;
416                    return;
417                }
418                None => return,
419                _ if self.is_valid_escape_at(0) => {
420                    self.pos += 1;
421                    self.consume_escaped_code_point();
422                }
423                _ => self.pos += 1,
424            }
425        }
426    }
427
428    /// Spec §4.3.6: "Consume a url token". Assumes the leading `url(`
429    /// has already been consumed.
430    fn consume_url_token(&mut self) -> Token {
431        let mut value = String::new();
432        self.skip_whitespace();
433        loop {
434            match self.peek() {
435                None => return Token::Url(value), // parse error: EOF
436                Some(')') => {
437                    self.pos += 1;
438                    return Token::Url(value);
439                }
440                Some(c) if is_whitespace(c) => {
441                    self.skip_whitespace();
442                    match self.peek() {
443                        Some(')') => {
444                            self.pos += 1;
445                            return Token::Url(value);
446                        }
447                        None => return Token::Url(value), // parse error: EOF
448                        _ => {
449                            self.consume_bad_url_remnants();
450                            return Token::BadUrl;
451                        }
452                    }
453                }
454                Some('"') | Some('\'') | Some('(') => {
455                    self.pos += 1; // parse error
456                    self.consume_bad_url_remnants();
457                    return Token::BadUrl;
458                }
459                Some(c) if is_non_printable(c) => {
460                    self.pos += 1; // parse error
461                    self.consume_bad_url_remnants();
462                    return Token::BadUrl;
463                }
464                Some('\\') => {
465                    if self.is_valid_escape_at(0) {
466                        self.pos += 1;
467                        let ch = self.consume_escaped_code_point();
468                        value.push(ch);
469                    } else {
470                        self.pos += 1; // parse error
471                        self.consume_bad_url_remnants();
472                        return Token::BadUrl;
473                    }
474                }
475                Some(c) => {
476                    value.push(c);
477                    self.pos += 1;
478                }
479            }
480        }
481    }
482
483    /// Spec §4.3.4: "Consume an ident-like token".
484    fn consume_ident_like_token(&mut self) -> Token {
485        let s = self.consume_ident_sequence();
486        if s.eq_ignore_ascii_case("url") && self.peek() == Some('(') {
487            self.pos += 1;
488            while matches!(self.peek(), Some(a) if is_whitespace(a))
489                && matches!(self.peek_n(1), Some(b) if is_whitespace(b))
490            {
491                self.pos += 1;
492            }
493            let starts_quoted = matches!(self.peek(), Some('"') | Some('\''))
494                || (matches!(self.peek(), Some(a) if is_whitespace(a))
495                    && matches!(self.peek_n(1), Some('"') | Some('\'')));
496            if starts_quoted {
497                Token::Function(s)
498            } else {
499                self.consume_url_token()
500            }
501        } else if self.peek() == Some('(') {
502            self.pos += 1;
503            Token::Function(s)
504        } else {
505            Token::Ident(s)
506        }
507    }
508
509    /// Spec §4.3.5: "Consume a string token", with `ending` as the
510    /// ending code point.
511    fn consume_string_token(&mut self, ending: char) -> Token {
512        let mut value = String::new();
513        loop {
514            match self.peek() {
515                Some(c) if c == ending => {
516                    self.pos += 1;
517                    return Token::String(value);
518                }
519                None => return Token::String(value), // parse error: EOF
520                Some('\n') => return Token::BadString, // parse error; reconsume the newline
521                Some('\\') => {
522                    self.pos += 1;
523                    match self.peek() {
524                        None => {}
525                        Some('\n') => self.pos += 1,
526                        Some(_) => {
527                            let ch = self.consume_escaped_code_point();
528                            value.push(ch);
529                        }
530                    }
531                }
532                Some(c) => {
533                    value.push(c);
534                    self.pos += 1;
535                }
536            }
537        }
538    }
539
540    /// Spec §4.3.1: "Consume a token".
541    fn consume_token(&mut self) -> Token {
542        self.consume_comments();
543        match self.peek() {
544            None => Token::Eof,
545            Some(c) if is_whitespace(c) => {
546                self.skip_whitespace();
547                Token::Whitespace
548            }
549            Some('"') => {
550                self.pos += 1;
551                self.consume_string_token('"')
552            }
553            Some('#') => {
554                self.pos += 1;
555                if matches!(self.peek(), Some(c) if is_ident_code_point(c))
556                    || self.is_valid_escape_at(0)
557                {
558                    let type_flag = if self.starts_ident_sequence(0) {
559                        HashType::Id
560                    } else {
561                        HashType::Unrestricted
562                    };
563                    let value = self.consume_ident_sequence();
564                    Token::Hash { value, type_flag }
565                } else {
566                    Token::Delim('#')
567                }
568            }
569            Some('\'') => {
570                self.pos += 1;
571                self.consume_string_token('\'')
572            }
573            Some('(') => {
574                self.pos += 1;
575                Token::OpenParen
576            }
577            Some(')') => {
578                self.pos += 1;
579                Token::CloseParen
580            }
581            Some('+') => {
582                if self.starts_number(0) {
583                    self.consume_numeric_token()
584                } else {
585                    self.pos += 1;
586                    Token::Delim('+')
587                }
588            }
589            Some(',') => {
590                self.pos += 1;
591                Token::Comma
592            }
593            Some('-') => {
594                if self.starts_number(0) {
595                    self.consume_numeric_token()
596                } else if self.peek_n(1) == Some('-') && self.peek_n(2) == Some('>') {
597                    self.pos += 3;
598                    Token::Cdc
599                } else if self.starts_ident_sequence(0) {
600                    self.consume_ident_like_token()
601                } else {
602                    self.pos += 1;
603                    Token::Delim('-')
604                }
605            }
606            Some('.') => {
607                if self.starts_number(0) {
608                    self.consume_numeric_token()
609                } else {
610                    self.pos += 1;
611                    Token::Delim('.')
612                }
613            }
614            Some(':') => {
615                self.pos += 1;
616                Token::Colon
617            }
618            Some(';') => {
619                self.pos += 1;
620                Token::Semicolon
621            }
622            Some('<') => {
623                if self.peek_n(1) == Some('!')
624                    && self.peek_n(2) == Some('-')
625                    && self.peek_n(3) == Some('-')
626                {
627                    self.pos += 4;
628                    Token::Cdo
629                } else {
630                    self.pos += 1;
631                    Token::Delim('<')
632                }
633            }
634            Some('@') => {
635                self.pos += 1;
636                if self.starts_ident_sequence(0) {
637                    let value = self.consume_ident_sequence();
638                    Token::AtKeyword(value)
639                } else {
640                    Token::Delim('@')
641                }
642            }
643            Some('[') => {
644                self.pos += 1;
645                Token::OpenSquare
646            }
647            Some('\\') => {
648                if self.is_valid_escape_at(0) {
649                    self.consume_ident_like_token()
650                } else {
651                    self.pos += 1; // parse error
652                    Token::Delim('\\')
653                }
654            }
655            Some(']') => {
656                self.pos += 1;
657                Token::CloseSquare
658            }
659            Some('{') => {
660                self.pos += 1;
661                Token::OpenCurly
662            }
663            Some('}') => {
664                self.pos += 1;
665                Token::CloseCurly
666            }
667            Some(c) if c.is_ascii_digit() => self.consume_numeric_token(),
668            Some(c) if is_ident_start(c) => self.consume_ident_like_token(),
669            Some(c) => {
670                self.pos += 1;
671                Token::Delim(c)
672            }
673        }
674    }
675}
676
677impl Iterator for Tokenizer {
678    type Item = Token;
679
680    fn next(&mut self) -> Option<Token> {
681        if self.done {
682            return None;
683        }
684        let token = self.consume_token();
685        if token == Token::Eof {
686            self.done = true;
687        }
688        Some(token)
689    }
690}
691
692/// Tokenizes `input` into a `Vec<Token>`, ending with a single
693/// [`Token::Eof`]. Convenience wrapper around [`Tokenizer`] for
694/// callers that don't need streaming/lazy tokenization.
695pub fn tokenize(input: &str) -> Vec<Token> {
696    Tokenizer::new(input).collect()
697}
698
699#[cfg(test)]
700mod tests {
701    use super::*;
702
703    fn tokens(input: &str) -> Vec<Token> {
704        tokenize(input)
705    }
706
707    #[test]
708    fn ident_token() {
709        assert_eq!(tokens("foo"), vec![Token::Ident("foo".into()), Token::Eof]);
710    }
711
712    #[test]
713    fn ident_token_with_escape() {
714        assert_eq!(
715            tokens(r"\41 bc"),
716            vec![Token::Ident("Abc".into()), Token::Eof]
717        );
718    }
719
720    #[test]
721    fn function_token() {
722        assert_eq!(
723            tokens("foo("),
724            vec![Token::Function("foo".into()), Token::Eof]
725        );
726    }
727
728    #[test]
729    fn at_keyword_token() {
730        assert_eq!(
731            tokens("@media"),
732            vec![Token::AtKeyword("media".into()), Token::Eof]
733        );
734    }
735
736    #[test]
737    fn hash_token_id() {
738        assert_eq!(
739            tokens("#foo"),
740            vec![
741                Token::Hash {
742                    value: "foo".into(),
743                    type_flag: HashType::Id
744                },
745                Token::Eof
746            ]
747        );
748    }
749
750    #[test]
751    fn hash_token_unrestricted() {
752        assert_eq!(
753            tokens("#1"),
754            vec![
755                Token::Hash {
756                    value: "1".into(),
757                    type_flag: HashType::Unrestricted
758                },
759                Token::Eof
760            ]
761        );
762    }
763
764    #[test]
765    fn string_token() {
766        assert_eq!(
767            tokens("\"hello\""),
768            vec![Token::String("hello".into()), Token::Eof]
769        );
770        assert_eq!(
771            tokens("'hello'"),
772            vec![Token::String("hello".into()), Token::Eof]
773        );
774    }
775
776    #[test]
777    fn bad_string_token_on_unterminated_newline() {
778        assert_eq!(
779            tokens("\"abc\ndef\""),
780            vec![
781                Token::BadString,
782                Token::Whitespace,
783                Token::Ident("def".into()),
784                Token::String("".into()),
785                Token::Eof,
786            ]
787        );
788    }
789
790    #[test]
791    fn url_token() {
792        assert_eq!(
793            tokens("url(foo.png)"),
794            vec![Token::Url("foo.png".into()), Token::Eof]
795        );
796    }
797
798    #[test]
799    fn url_token_quoted_is_a_function() {
800        assert_eq!(
801            tokens("url(\"foo.png\")"),
802            vec![
803                Token::Function("url".into()),
804                Token::String("foo.png".into()),
805                Token::CloseParen,
806                Token::Eof
807            ]
808        );
809    }
810
811    #[test]
812    fn bad_url_token_on_unescaped_space() {
813        assert_eq!(tokens("url(foo bar)"), vec![Token::BadUrl, Token::Eof]);
814    }
815
816    #[test]
817    fn delim_token() {
818        assert_eq!(tokens("^"), vec![Token::Delim('^'), Token::Eof]);
819    }
820
821    #[test]
822    fn number_token_integer() {
823        assert_eq!(
824            tokens("42"),
825            vec![
826                Token::Number {
827                    value: 42.0,
828                    type_flag: NumericType::Integer
829                },
830                Token::Eof
831            ]
832        );
833    }
834
835    #[test]
836    fn number_token_fractional() {
837        assert_eq!(
838            tokens("4.2"),
839            vec![
840                Token::Number {
841                    value: 4.2,
842                    type_flag: NumericType::Number
843                },
844                Token::Eof
845            ]
846        );
847    }
848
849    #[test]
850    fn percentage_token() {
851        assert_eq!(
852            tokens("50%"),
853            vec![Token::Percentage { value: 50.0 }, Token::Eof]
854        );
855    }
856
857    #[test]
858    fn dimension_token() {
859        assert_eq!(
860            tokens("10px"),
861            vec![
862                Token::Dimension {
863                    value: 10.0,
864                    type_flag: NumericType::Integer,
865                    unit: "px".into()
866                },
867                Token::Eof
868            ]
869        );
870    }
871
872    #[test]
873    fn whitespace_token() {
874        assert_eq!(tokens("  \t\n"), vec![Token::Whitespace, Token::Eof]);
875    }
876
877    #[test]
878    fn cdo_token() {
879        assert_eq!(tokens("<!--"), vec![Token::Cdo, Token::Eof]);
880    }
881
882    #[test]
883    fn cdc_token() {
884        assert_eq!(tokens("-->"), vec![Token::Cdc, Token::Eof]);
885    }
886
887    #[test]
888    fn colon_semicolon_comma_tokens() {
889        assert_eq!(
890            tokens(":;,"),
891            vec![Token::Colon, Token::Semicolon, Token::Comma, Token::Eof]
892        );
893    }
894
895    #[test]
896    fn bracket_tokens() {
897        assert_eq!(
898            tokens("[](){}"),
899            vec![
900                Token::OpenSquare,
901                Token::CloseSquare,
902                Token::OpenParen,
903                Token::CloseParen,
904                Token::OpenCurly,
905                Token::CloseCurly,
906                Token::Eof,
907            ]
908        );
909    }
910
911    #[test]
912    fn eof_token_on_empty_input() {
913        assert_eq!(tokens(""), vec![Token::Eof]);
914    }
915
916    #[test]
917    fn comments_are_transparent() {
918        assert_eq!(
919            tokens("/* comment */foo"),
920            vec![Token::Ident("foo".into()), Token::Eof]
921        );
922    }
923
924    #[test]
925    fn preprocessing_normalizes_newlines() {
926        assert_eq!(tokens("a\r\nb"), tokens("a\nb"));
927        assert_eq!(tokens("a\rb"), tokens("a\nb"));
928        assert_eq!(tokens("a\u{000C}b"), tokens("a\nb"));
929    }
930
931    #[test]
932    fn preprocessing_replaces_null_with_replacement_character() {
933        assert_eq!(
934            tokens("\u{0000}"),
935            vec![Token::Ident("\u{FFFD}".into()), Token::Eof]
936        );
937    }
938}