Skip to main content

jessie_css/
lib.rs

1use peekmore::{PeekMore, PeekMoreIterator};
2use std::{borrow::Cow, str::Chars};
3mod tests;
4
5pub struct Tokenizer<'a> {
6    process: PutBackPeekMore<'a>,
7    parse_error: bool,
8}
9
10impl<'a> Tokenizer<'a> {
11    pub fn new(input: &'a str) -> Self {
12        Self {
13            process: PutBackPeekMore::new(input),
14            parse_error: false,
15        }
16    }
17
18    pub fn consume_token(&mut self) -> CSSToken {
19        // https://www.w3.org/TR/css-syntax-3/#consume-token
20
21        // This section describes how to consume a token from a stream of code points. It will return a single token of any type.
22
23        // Consume comments.
24        self.consume_comments();
25
26        // Consume the next input code point.
27        match self.process.next() {
28            Some(v) => {
29                // whitespace
30                if Self::is_whitespace(v) {
31                    // Consume as much whitespace as possible. Return a <whitespace-token>.
32                    self.consume_whitespace();
33                    return CSSToken::WhitespaceToken;
34                }
35                // U+0022 QUOTATION MARK (")
36                if v == '\u{0022}' {
37                    // Consume a string token and return it.
38                    return self.consume_string_token(v);
39                }
40                // U+0023 NUMBER SIGN (#)
41                if v == '\u{0023}' {
42                    let (first, second) = self.peek_twin();
43
44                    // If the next input code point is an ident code point or the next two input code points are a valid escape, then:
45                    if Self::is_ident_code_point(first) || Self::is_valid_escape(first, second) {
46                        // Create a <hash-token>.  NOTE: we cant really lol
47                        let mut flag = HashTokenFlag::Unrestricted;
48                        //  If the next 3 input code points would start an ident sequence, set the <hash-token>’s type flag to "id".
49                        if self.would_start_ident_sequence() {
50                            flag = HashTokenFlag::Id;
51                        }
52                        // Consume an ident sequence, and set the <hash-token>’s value to the returned string.
53                        let value = self.consume_ident_sequence();
54                        // Return the <hash-token>.
55                        return CSSToken::HashToken { flag, value };
56                    }
57                    // Otherwise, return a <delim-token> with its value set to the current input code point.
58                    return CSSToken::DelimToken { value: v };
59                }
60                // U+0027 APOSTROPHE (')
61                if v == '\u{0027}' {
62                    // Consume a string token and return it.
63                    return self.consume_string_token(v);
64                }
65                // U+0028 LEFT PARENTHESIS (()
66                if v == '\u{0028}' {
67                    // Return a <(-token>.
68                    return CSSToken::LeftParenthesisToken;
69                }
70                // U+0029 RIGHT PARENTHESIS ())
71                if v == '\u{0029}' {
72                    // Return a <)-token>.
73                    return CSSToken::RightParenthesisToken;
74                }
75                // U+002B PLUS SIGN (+)
76                if v == '\u{002b}' {
77                    // If the input stream starts with a number, reconsume the current input code point, consume a numeric token, and return it.
78                    if self.would_start_number() {
79                        self.process.put_back(v);
80                        return self.consume_numeric_token();
81                    }
82                    // Otherwise, return a <delim-token> with its value set to the current input code point.
83                    return CSSToken::DelimToken { value: v };
84                }
85                // U+002C COMMA (,)
86                if v == '\u{002c}' {
87                    // Return a <comma-token>.
88                    return CSSToken::CommaToken;
89                }
90                // U+002D HYPHEN-MINUS (-)
91                if v == '\u{002d}' {
92                    // If the input stream starts with a number, reconsume the current input code point, consume a numeric token, and return it.
93                    if self.would_start_number() {
94                        self.process.put_back(v);
95                        return self.consume_numeric_token();
96                    }
97                    // Otherwise, if the next 2 input code points are U+002D HYPHEN-MINUS U+003E GREATER-THAN SIGN (->), consume them and return a <CDC-token>.
98                    if self.peek_twin() == (Some('\u{002d}'), Some('\u{003e}')) {
99                        self.process.next();
100                        self.process.next();
101                        return CSSToken::CDCToken;
102                    }
103                    // Otherwise, if the input stream starts with an ident sequence, reconsume the current input code point, consume an ident-like token, and return it.
104                    if self.would_start_ident_sequence() {
105                        self.process.put_back(v);
106                        return self.consume_ident_like_token();
107                    }
108                    // Otherwise, return a <delim-token> with its value set to the current input code point.
109                    return CSSToken::DelimToken { value: v };
110                }
111                // U+002E FULL STOP (.)
112                if v == '\u{002e}' {
113                    // If the input stream starts with a number, reconsume the current input code point, consume a numeric token, and return it.
114                    if self.would_start_number() {
115                        self.process.put_back(v);
116                        return self.consume_numeric_token();
117                    }
118                    // Otherwise, return a <delim-token> with its value set to the current input code point.
119                    return CSSToken::DelimToken { value: v };
120                }
121                // U+003A COLON (:)
122                if v == '\u{003a}' {
123                    // Return a <colon-token>.
124                    return CSSToken::ColonToken;
125                }
126                // U+003B SEMICOLON (;)
127                if v == '\u{003b}' {
128                    // Return a <semicolon-token>.
129                    return CSSToken::SemicolonToken;
130                }
131                // U+003C LESS-THAN SIGN (<)
132                if v == '\u{003c}' {
133                    // If the next 3 input code points are U+0021 EXCLAMATION MARK U+002D HYPHEN-MINUS U+002D HYPHEN-MINUS (!--), consume them and return a <CDO-token>.
134                    if self.process.peek_amount(3)
135                        == [Some('\u{0021}'), Some('\u{002d}'), Some('\u{002d}')]
136                    {
137                        self.process.next();
138                        self.process.next();
139                        self.process.next();
140                        return CSSToken::CDOToken;
141                    }
142                    // Otherwise, return a <delim-token> with its value set to the current input code point.
143                    return CSSToken::DelimToken { value: v };
144                }
145                // U+0040 COMMERCIAL AT (@)
146                if v == '\u{0040}' {
147                    // If the next 3 input code points would start an ident sequence, consume an ident sequence, create an <at-keyword-token> with its value set to the returned value, and return it.
148                    if self.would_start_ident_sequence() {
149                        return CSSToken::AtKeywordToken {
150                            value: self.consume_ident_sequence(),
151                        };
152                    }
153                    // Otherwise, return a <delim-token> with its value set to the current input code point.
154                    return CSSToken::DelimToken { value: v };
155                }
156                // U+005B LEFT SQUARE BRACKET ([)
157                if v == '\u{005b}' {
158                    // Return a <[-token>.
159                    return CSSToken::LeftSquareBracketToken;
160                }
161                // U+005C REVERSE SOLIDUS (\)
162                if v == '\u{005c}' {
163                    // If the input stream starts with a valid escape, reconsume the current input code point, consume an ident-like token, and return it.
164                    if let Some(&second) = self.process.peek()
165                        && Self::is_valid_escape(Some(v), Some(second))
166                    {
167                        self.process.put_back(v);
168                        return self.consume_ident_like_token();
169                    }
170                    // Otherwise, this is a parse error. Return a <delim-token> with its value set to the current input code point.
171                    self.parse_error();
172                    return CSSToken::DelimToken { value: v };
173                }
174                // U+005D RIGHT SQUARE BRACKET (])
175                if v == '\u{005d}' {
176                    // Return a <]-token>.
177                    return CSSToken::RightSquareBracketToken;
178                }
179                // U+007B LEFT CURLY BRACKET ({)
180                if v == '\u{007b}' {
181                    // Return a <{-token>.
182                    return CSSToken::LeftCurlyBracketToken;
183                }
184                // U+007D RIGHT CURLY BRACKET (})
185                if v == '\u{007d}' {
186                    // Return a <}-token>.
187                    return CSSToken::RightCurlyBracketToken;
188                }
189                // digit
190                if Self::is_digit(v) {
191                    // Reconsume the current input code point, consume a numeric token, and return it.
192                    self.process.put_back(v);
193                    return self.consume_numeric_token();
194                }
195                // ident-start code point
196                if Self::is_ident_start_code_point(v) {
197                    // Reconsume the current input code point, consume an ident-like token, and return it.
198                    self.process.put_back(v);
199                    return self.consume_ident_like_token();
200                }
201                // anything else
202                // Return a <delim-token> with its value set to the current input code point.
203                CSSToken::DelimToken { value: v }
204            }
205            // EOF
206            // Return an <EOF-token>.
207            None => CSSToken::EOFToken,
208        }
209    }
210
211    pub fn is_parse_error(&mut self) -> bool {
212        self.parse_error
213    }
214
215    pub fn consume_ident_like_token(&mut self) -> CSSToken {
216        // https://www.w3.org/TR/css-syntax-3/#consume-ident-like-token
217        // This section describes how to consume an ident-like token from a stream of code points. It returns an <ident-token>, <function-token>, <url-token>, or <bad-url-token>.
218
219        // Consume an ident sequence, and let string be the result.
220        let string = self.consume_ident_sequence();
221
222        // If string’s value is an ASCII case-insensitive match for "url", and the next input code point is U+0028 LEFT PARENTHESIS ((),
223        if &string.to_lowercase() == "url" && self.process.peek() == Some(&'\u{0028}') {
224            //  consume it.
225            self.process.next();
226
227            // 	While the next two input code points are whitespace, consume the next input code point.
228            while let (Some(first), Some(second)) = self.peek_twin() {
229                if !(Self::is_whitespace(first) && Self::is_whitespace(second)) {
230                    break;
231                }
232                self.process.next();
233            }
234
235            // If the next one or two input code points are U+0022 QUOTATION MARK ("), U+0027 APOSTROPHE ('), or whitespace followed by U+0022 QUOTATION MARK (") or U+0027 APOSTROPHE ('),
236            if let (Some(first), Some(second)) = self.peek_twin() {
237                if (first == '\u{0022}' || first == '\u{0027}')
238                    || (Self::is_whitespace(first)
239                        && (second == '\u{0022}' || second == '\u{0027}'))
240                {
241                    // then create a <function-token> with its value set to string and return it.
242                    return CSSToken::FunctionToken { value: string };
243                }
244                // 	Otherwise, consume a url token, and return it.
245                return self.consume_url_token();
246            }
247        }
248        // Otherwise, if the next input code point is U+0028 LEFT PARENTHESIS ((), consume it.
249        if self.process.peek() == Some(&'\u{0028}') {
250            self.process.next();
251            // Create a <function-token> with its value set to string and return it.
252            return CSSToken::FunctionToken { value: string };
253        }
254        // Otherwise, create an <ident-token> with its value set to string and return it.
255        CSSToken::IdentToken { value: string }
256    }
257
258    pub fn consume_url_token(&mut self) -> CSSToken {
259        // https://www.w3.org/TR/css-syntax-3/#consume-url-token
260        // This section describes how to consume a url token from a stream of code points. It returns either a <url-token> or a <bad-url-token>.
261
262        // Initially create a <url-token> with its value set to the empty string.
263        let mut url_token_val = String::new();
264
265        //  Consume as much whitespace as possible.
266        self.consume_whitespace();
267
268        // Repeatedly consume the next input code point from the stream:
269        loop {
270            let next = self.process.next();
271
272            // U+0029 RIGHT PARENTHESIS ())
273            if next == Some('\u{0029}') {
274                // Return the <url-token>.
275                return CSSToken::URLToken {
276                    value: url_token_val,
277                };
278            }
279
280            // EOF
281            if next.is_none() {
282                // This is a parse error. Return the <url-token>.
283                self.parse_error();
284                return CSSToken::URLToken {
285                    value: url_token_val,
286                };
287            }
288
289            // whitespace
290            if Self::is_whitespace(next.unwrap()) {
291                // Consume as much whitespace as possible.
292                self.consume_whitespace();
293
294                // 	If the next input code point is U+0029 RIGHT PARENTHESIS ()) or EOF,
295                let peek = self.process.peek();
296                if matches!(peek, None | Some(&'\u{0029}')) {
297                    // 	consume it and return the <url-token>  (if EOF was encountered, this is a parse error);
298                    if peek.is_none() {
299                        self.parse_error();
300                    }
301                    self.process.next();
302                    return CSSToken::URLToken {
303                        value: url_token_val,
304                    };
305                }
306
307                // otherwise, consume the remnants of a bad url, create a <bad-url-token>, and return it.
308                self.consume_remnants_of_bad_url();
309                return CSSToken::BadURLToken;
310            }
311
312            // U+0022 QUOTATION MARK (")
313            // U+0027 APOSTROPHE (')
314            // U+0028 LEFT PARENTHESIS (()
315            // non-printable code point
316            if let Some(v) = next
317                && ((v == '\u{0022}')
318                    || (v == '\u{0027}')
319                    || (v == '\u{0028}')
320                    || Self::is_none_printable_code_point(v))
321            {
322                // This is a parse error. Consume the remnants of a bad url, create a <bad-url-token>, and return it.
323                self.parse_error();
324                self.consume_remnants_of_bad_url();
325                return CSSToken::BadURLToken;
326            }
327
328            // U+005C REVERSE SOLIDUS (\)
329            if next == Some('\u{005c}') {
330                // If the stream starts with a valid escape, consume an escaped code point and append the returned code point to the <url-token>’s value.
331                if let Some(&v) = self.process.peek()
332                    && Self::is_valid_escape(next, Some(v))
333                {
334                    url_token_val.push(self.consume_escaped_code_point());
335                }
336
337                // Otherwise, this is a parse error. Consume the remnants of a bad url, create a <bad-url-token>, and return it.
338                self.parse_error();
339                self.consume_remnants_of_bad_url();
340                return CSSToken::BadURLToken;
341            }
342
343            // anything else
344            if let Some(v) = next {
345                // Append the current input code point to the <url-token>’s value.
346                url_token_val.push(v);
347            }
348        }
349    }
350
351    pub fn is_none_printable_code_point(input: char) -> bool {
352        // https://www.w3.org/TR/css-syntax-3/#tokenizer-definitions
353        // A code point between U+0000 NULL and U+0008 BACKSPACE inclusive, or U+000B LINE TABULATION, or a code point between U+000E SHIFT OUT and U+001F INFORMATION SEPARATOR ONE inclusive, or U+007F DELETE.
354        (('\u{0000}'..='\u{0008}').contains(&input))
355            || (input == '\u{000b}')
356            || (('\u{000e}'..='\u{001f}').contains(&input))
357            || (input == '\u{007f}')
358    }
359
360    pub fn consume_remnants_of_bad_url(&mut self) {
361        // https://www.w3.org/TR/css-syntax-3/#consume-remnants-of-bad-url
362        loop {
363            // Repeatedly consume the next input code point from the stream:
364            let next = self.process.next();
365
366            // U+0029 RIGHT PARENTHESIS ())
367            // EOF
368            if next == Some('\u{0029}') || next.is_none() {
369                return;
370            }
371
372            // the input stream starts with a valid escape
373            if let Some(&peek) = self.process.peek()
374                && Self::is_valid_escape(next, Some(peek))
375            {
376                // Consume an escaped code point. This allows an escaped right parenthesis ("\)") to be encountered without ending the <bad-url-token>. This is otherwise identical to the "anything else" clause.
377                self.consume_escaped_code_point();
378            }
379
380            // anything else
381            // Do nothing.
382        }
383    }
384
385    pub fn consume_numeric_token(&mut self) -> CSSToken {
386        // https://www.w3.org/TR/css-syntax-3/#consume-numeric-token
387
388        // This section describes how to consume a numeric token from a stream of code points. It returns either a <number-token>, <percentage-token>, or <dimension-token>.
389
390        // Consume a number and let number be the result.
391        let number = self.consume_number();
392
393        // If the next 3 input code points would start an ident sequence, then:
394        if self.would_start_ident_sequence() {
395            // Create a <dimension-token> with the same value and type flag as number, and a unit set initially to the empty string.
396            // Consume an ident sequence. Set the <dimension-token>’s unit to the returned value.
397            // Return the <dimension-token>.
398            return CSSToken::DimensionToken {
399                flag: number.r#type,
400                value: number.value,
401                unit: self.consume_ident_sequence(),
402            };
403        }
404
405        // Otherwise, if the next input code point is U+0025 PERCENTAGE SIGN (%), consume it.
406        if self.process.peek() == Some(&'\u{0025}') {
407            self.process.next();
408
409            // 	Create a <percentage-token> with the same value as number, and return it.
410            return CSSToken::PercentageToken {
411                flag: number.r#type,
412                value: number.value,
413            };
414        }
415
416        // Otherwise, create a <number-token> with the same value and type flag as number, and return it.
417        CSSToken::NumberToken {
418            flag: number.r#type,
419            value: number.value,
420        }
421    }
422
423    pub fn consume_number(&mut self) -> Number {
424        // https://www.w3.org/TR/css-syntax-3/#consume-number
425        // This section describes how to consume a number from a stream of code points. It returns a numeric value, and a type which is either "integer" or "number".
426
427        //  Initially set type to "integer". Let repr be the empty string.
428        let mut r#type = NumberType::Integer;
429        let mut repr = String::new();
430
431        // If the next input code point is U+002B PLUS SIGN (+) or U+002D HYPHEN-MINUS (-), consume it and append it to repr.
432        if let Some(&v) = self.process.peek()
433            && (v == '\u{002b}' || v == '\u{002d}')
434        {
435            self.process.next();
436            repr.push(v);
437        }
438
439        // While the next input code point is a digit, consume it and append it to repr.
440        while let Some(&v) = self.process.peek() {
441            if !Self::is_digit(v) {
442                break;
443            }
444            self.process.next();
445            repr.push(v);
446        }
447
448        // If the next 2 input code points are U+002E FULL STOP (.) followed by a digit, then:
449        if let (Some(first), Some(second)) = self.peek_twin()
450            && (first == '\u{002e}' && Self::is_digit(second))
451        {
452            // Consume them.
453            self.process.next();
454            self.process.next();
455            // Append them to repr.
456            repr.push(first);
457            repr.push(second);
458            // Set type to "number".
459            r#type = NumberType::Number;
460
461            // While the next input code point is a digit, consume it and append it to repr.
462            while let Some(&v) = self.process.peek() {
463                if !Self::is_digit(v) {
464                    break;
465                }
466                self.process.next();
467                repr.push(v);
468            }
469        }
470
471        // If the next 2 or 3 input code points are U+0045 LATIN CAPITAL LETTER E (E) or U+0065 LATIN SMALL LETTER E (e), optionally followed by U+002D HYPHEN-MINUS (-) or U+002B PLUS SIGN (+), followed by a digit, then:
472        if let &[Some(first), Some(second), Some(third)] = self.process.peek_amount(3).as_slice()
473            && ((Self::is_e(first) && Self::is_digit(second))
474                || (Self::is_e(first) && Self::is_plus_or_minus(second) && Self::is_digit(third)))
475        {
476            // Consume them.
477            // Append them to repr
478            self.process.next();
479            self.process.next();
480            repr.push(first);
481            repr.push(second);
482            if Self::is_e(first) && Self::is_plus_or_minus(second) && Self::is_digit(third) {
483                self.process.next();
484                repr.push(third);
485            }
486
487            // Set type to "number".
488            r#type = NumberType::Number;
489
490            // While the next input code point is a digit, consume it and append it to repr.
491            while let Some(&v) = self.process.peek() {
492                if !Self::is_digit(v) {
493                    break;
494                }
495                self.process.next();
496                repr.push(v);
497            }
498        }
499
500        // Convert repr to a number, and set the value to the returned value.
501        // Return value and type.
502        Number {
503            value: Self::string_to_number(repr),
504            r#type,
505        }
506    }
507
508    pub fn string_to_number(input: String) -> f64 {
509        // https://www.w3.org/TR/css-syntax-3/#convert-string-to-number
510        // This section describes how to convert a string to a number. It returns a number.
511        let mut iter = input.chars().peekable();
512        let mut _sign: Option<char> = None;
513
514        // Divide the string into seven components, in order from left to right:
515        // A sign: a single U+002B PLUS SIGN (+) or U+002D HYPHEN-MINUS (-), or the empty string.
516        if let Some(&v) = iter.peek()
517            && (v == '\u{002b}' || v == '\u{002d}')
518        {
519            iter.next();
520            _sign = Some(v);
521        }
522        // 	Let s be the number -1 if the sign is U+002D HYPHEN-MINUS (-); otherwise, let s be the number 1.
523        let s: f64 = {
524            match _sign {
525                Some('\u{002d}') => -1.,
526                _ => 1.,
527            }
528        };
529
530        // An integer part: zero or more digits.
531        let mut integer_part = String::new();
532        while let Some(&v) = iter.peek() {
533            if !Self::is_digit(v) {
534                break;
535            }
536            integer_part.push(v);
537            iter.next();
538        }
539
540        // If there is at least one digit, let i be the number formed by interpreting the digits as a base-10 integer; otherwise, let i be the number 0.
541        let i = integer_part.parse::<f64>().unwrap_or(0.);
542
543        // A decimal point: a single U+002E FULL STOP (.), or the empty string.
544        let mut _decimal_point = None;
545        if let Some(&v) = iter.peek()
546            && (v == '\u{002e}')
547        {
548            iter.next();
549            _decimal_point = Some(v);
550        }
551
552        // A fractional part: zero or more digits.
553        let mut fractional_part = String::new();
554        while let Some(&v) = iter.peek() {
555            if !Self::is_digit(v) {
556                break;
557            }
558            fractional_part.push(v);
559            iter.next();
560        }
561
562        // If there is at least one digit, let f be the number formed by interpreting the digits as a base-10 integer and d be the number of digits; otherwise, let f and d be the number 0.
563        let f = fractional_part.parse::<f64>().unwrap_or(0.);
564        let d = fractional_part.len() as f64;
565
566        // An exponent indicator: a single U+0045 LATIN CAPITAL LETTER E (E) or U+0065 LATIN SMALL LETTER E (e), or the empty string.
567        let mut _exponent_indicator = None;
568        if let Some(&v) = iter.peek()
569            && (v == '\u{0045}' || v == '\u{0065}')
570        {
571            iter.next();
572            _exponent_indicator = Some(v);
573        }
574
575        // An exponent sign: a single U+002B PLUS SIGN (+) or U+002D HYPHEN-MINUS (-), or the empty string.
576        let mut _exponent_sign = None;
577
578        if let Some(&v) = iter.peek()
579            && (v == '\u{002b}' || v == '\u{002d}')
580        {
581            iter.next();
582            _exponent_sign = Some(v);
583        }
584
585        // Let t be the number -1 if the sign is U+002D HYPHEN-MINUS (-); otherwise, let t be the number 1.
586        let t = {
587            match _exponent_sign {
588                Some('\u{002d}') => -1.,
589                _ => 1.,
590            }
591        };
592
593        // An exponent: zero or more digits.
594        let mut exponent = String::new();
595        while let Some(&v) = iter.peek() {
596            if !Self::is_digit(v) {
597                break;
598            }
599            exponent.push(v);
600            iter.next();
601        }
602
603        // If there is at least one digit, let e be the number formed by interpreting the digits as a base-10 integer; otherwise, let e be the number 0.
604        let e = exponent.parse::<f64>().unwrap_or(0.);
605
606        // Return the number s·(i + f·10-d)·10te.
607        s * (i + (f * 10.0_f64.powf(-d))) * 10.0_f64.powf(t * e)
608    }
609
610    pub fn is_plus_or_minus(input: char) -> bool {
611        input == '\u{002d}' || input == '\u{002b}'
612    }
613
614    pub fn is_e(input: char) -> bool {
615        input == '\u{0045}' || input == '\u{0065}'
616    }
617
618    pub fn would_start_number(&mut self) -> bool {
619        // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
620        let peek = self.process.peek_amount(3);
621
622        // Look at the first code point:
623        let first = peek[0];
624
625        // U+002B PLUS SIGN (+)
626        // U+002D HYPHEN-MINUS (-)
627        if first == Some('\u{002b}') || first == Some('\u{002d}') {
628            if let Some(second_val) = peek[1]
629                && Self::is_digit(second_val)
630            {
631                // If the second code point is a digit, return true.
632                return true;
633            }
634
635            // Otherwise, if the second code point is a U+002E FULL STOP (.) and the third code point is a digit, return true.
636            if peek[1] == Some('\u{002e}')
637                && let Some(third_val) = peek[2]
638                && Self::is_digit(third_val)
639            {
640                return true;
641            }
642
643            // Otherwise, return false.
644            return false;
645        }
646
647        // U+002E FULL STOP (.)
648        if first == Some('\u{002e}') {
649            // If the second code point is a digit, return true. Otherwise, return false.
650            if let Some(second) = peek[1]
651                && Self::is_digit(second)
652            {
653                return true;
654            }
655
656            return false;
657        }
658
659        // digit
660        if let Some(v) = first
661            && Self::is_digit(v)
662        {
663            // Return true.
664            return true;
665        }
666
667        // anything else
668        // Return false.
669        false
670    }
671
672    pub fn consume_ident_sequence(&mut self) -> String {
673        // https://www.w3.org/TR/css-syntax-3/#consume-name
674
675        // Let result initially be an empty string.
676        let mut result = String::new();
677
678        // Repeatedly consume the next input code point from the stream:
679        loop {
680            let next = self.process.next();
681
682            // ident code point
683            if let Some(v) = next
684                && Self::is_ident_code_point(Some(v))
685            {
686                // Append the code point to result.
687                result.push(v);
688            }
689            // the stream starts with a valid escape
690            else if let Some(&v) = self.process.peek()
691                && Self::is_valid_escape(next, Some(v))
692            {
693                // Consume an escaped code point. Append the returned code point to result.
694                result.push(self.consume_escaped_code_point());
695            }
696            // anything else
697            else {
698                // Reconsume the current input code point. Return result.
699                self.process.put_back_option(next);
700                return result;
701            }
702        }
703    }
704
705    pub fn would_start_ident_sequence(&mut self) -> bool {
706        // https://www.w3.org/TR/css-syntax-3/#would-start-an-identifier
707        let peek = self.process.peek_amount(3);
708        let first = peek[0];
709        let second = peek[1];
710        let third = peek[2];
711
712        // Look at the first code point:
713
714        // U+002D HYPHEN-MINUS
715        if first == Some('\u{002d}') {
716            // If the second code point is an ident-start code point or a U+002D HYPHEN-MINUS, or the second and third code points are a valid escape, return true
717            if let Some(v) = second
718                && (Self::is_ident_start_code_point(v) || v == '\u{002d}')
719            {
720                return true;
721            }
722
723            if Self::is_valid_escape(second, third) {
724                return true;
725            }
726
727            // Otherwise, return false.
728            return false;
729        }
730
731        // ident-start code point
732        if let Some(v) = first
733            && Self::is_ident_start_code_point(v)
734        {
735            return true;
736        }
737
738        // U+005C REVERSE SOLIDUS (\)
739        if first == Some('\u{005c}') {
740            // If the first and second code points are a valid escape, return true. Otherwise, return false.
741            return Self::is_valid_escape(first, second);
742        }
743        // anything else
744        // Return false.
745        false
746    }
747
748    pub fn is_ident_code_point(input: Option<char>) -> bool {
749        // https://www.w3.org/TR/css-syntax-3/#tokenizer-definitions
750        // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
751        if let Some(v) = input {
752            return Self::is_ident_start_code_point(v) || Self::is_digit(v) || v == '\u{002d}';
753        }
754        false
755    }
756
757    pub fn is_ident_start_code_point(input: char) -> bool {
758        // https://www.w3.org/TR/css-syntax-3/#tokenizer-definitions
759        // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
760        Self::is_letter(input) || Self::is_none_ascii(input) || input == '\u{0080}'
761    }
762
763    pub fn is_letter(input: char) -> bool {
764        // https://www.w3.org/TR/css-syntax-3/#tokenizer-definitions
765        // An uppercase letter or a lowercase letter.
766        Self::is_uppercase_letter(input) || Self::is_lowercase_letter(input)
767    }
768
769    pub fn is_uppercase_letter(input: char) -> bool {
770        // https://www.w3.org/TR/css-syntax-3/#tokenizer-definitions
771        // A code point between U+0041 LATIN CAPITAL LETTER A (A) and U+005A LATIN CAPITAL LETTER Z (Z) inclusive.
772        ('\u{0041}'..='\u{005a}').contains(&input)
773    }
774
775    pub fn is_lowercase_letter(input: char) -> bool {
776        // https://www.w3.org/TR/css-syntax-3/#tokenizer-definitions
777        // A code point between U+0061 LATIN SMALL LETTER A (a) and U+007A LATIN SMALL LETTER Z (z) inclusive.
778        ('\u{0061}'..='\u{007a}').contains(&input)
779    }
780
781    pub fn is_none_ascii(input: char) -> bool {
782        // https://www.w3.org/TR/css-syntax-3/#tokenizer-definitions
783        // A code point with a value equal to or greater than U+0080 <control>.
784        input >= '\u{0080}'
785    }
786
787    pub fn consume_string_token(&mut self, code_point: char) -> CSSToken {
788        // https://www.w3.org/TR/css-syntax-3/#consume-string-token
789        // This section describes how to consume a string token from a stream of code points. It returns either a <string-token> or <bad-string-token>.
790
791        //This algorithm may be called with an ending code point, which denotes the code point that ends the string. If an ending code point is not specified, the current input code point is used.
792
793        //Initially create a <string-token> with its value set to the empty string.
794        let mut out = String::new();
795
796        // Repeatedly consume the next input code point from the stream:
797        loop {
798            let next = self.process.next();
799            // ending code point
800            if next == Some(code_point) {
801                // Return the <string-token>.
802                return CSSToken::StringToken { string: out };
803            }
804
805            //EOF
806            if next.is_none() {
807                // This is a parse error. Return the <string-token>.
808                self.parse_error();
809                return CSSToken::StringToken { string: out };
810            }
811            // newline
812            if next == Some('\u{000a}') {
813                // This is a parse error. Reconsume the current input code point, create a <bad-string-token>, and return it.
814                self.parse_error();
815                self.process.put_back('\u{000a}');
816                return CSSToken::BadStringToken;
817            }
818            // U+005C REVERSE SOLIDUS (\)
819            if next == Some('\u{005c}') {
820                // If the next input code point is EOF, do nothing.
821                if self.process.peek().is_none() {
822                    continue;
823                }
824                // Otherwise, if the next input code point is a newline, consume it.
825                else if let Some(&v) = self.process.peek()
826                    && Self::is_newline(v)
827                {
828                    self.process.next();
829                    continue;
830                }
831                // Otherwise, (the stream starts with a valid escape) consume an escaped code point and append the returned code point to the <string-token>’s value.
832                else if let Some(&v) = self.process.peek()
833                    && Self::is_valid_escape(Some('\u{005c}'), Some(v))
834                {
835                    out.push(self.consume_escaped_code_point());
836                    continue;
837                }
838            }
839
840            // anything else
841            // Append the current input code point to the <string-token>’s value.
842            if let Some(v) = next {
843                out.push(v);
844            }
845        }
846    }
847
848    pub fn is_newline(input: char) -> bool {
849        // https://www.w3.org/TR/css-syntax-3/#tokenizer-definitions
850        // U+000A LINE FEED.
851        input == '\u{000a}'
852    }
853
854    pub fn peek_twin(&mut self) -> (Option<char>, Option<char>) {
855        let peek = self.process.peek_amount(2);
856        let first = peek[0];
857        let second = peek[1];
858        (first, second)
859    }
860
861    pub fn consume_escaped_code_point(&mut self) -> char {
862        // https://www.w3.org/TR/css-syntax-3/#consume-escaped-code-point
863
864        // Consume the next input code point.
865        let next = self.process.next();
866
867        // hex digit
868        if let Some(v) = next
869            && Self::is_hex_digit(v)
870        {
871            // Consume as many hex digits as possible, but no more than 5.
872            let mut digits = String::new();
873            digits.push(v);
874
875            while let Some(&peek) = self.process.peek()
876                && Self::is_hex_digit(peek)
877                && digits.len() <= 6
878            {
879                digits.push(peek);
880                self.process.next();
881            }
882
883            // If the next input code point is whitespace, consume it as well.
884            if let Some(&peek) = self.process.peek()
885                && Self::is_whitespace(peek)
886            {
887                self.process.next();
888            }
889
890            // Interpret the hex digits as a hexadecimal number.
891            let parsed = u32::from_str_radix(&digits, 16).unwrap();
892
893            // If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point,
894            if parsed == 0 || Self::is_surrogate(parsed) || parsed > Self::max_allowed_code_point()
895            {
896                // return U+FFFD REPLACEMENT CHARACTER (�).
897                return '\u{fffd}';
898            }
899
900            // 	Otherwise, return the code point with that value.
901            return char::from_u32(parsed).unwrap();
902        }
903
904        // EOF
905        if next.is_none() {
906            // This is a parse error. Return U+FFFD REPLACEMENT CHARACTER (�).
907            self.parse_error();
908            return '\u{fffd}';
909        }
910
911        // anything else
912        // Return the current input code point.
913        next.unwrap()
914    }
915
916    pub fn max_allowed_code_point() -> u32 {
917        // https://www.w3.org/TR/css-syntax-3/#tokenizer-definitions
918        // The greatest code point defined by Unicode: U+10FFFF.
919        0x10ffff
920    }
921
922    pub fn is_surrogate(input: u32) -> bool {
923        // https://infra.spec.whatwg.org/#surrogate
924        // A surrogate is a leading surrogate or a trailing surrogate.
925        Self::is_leading_surrogate(input) || Self::is_trailing_surrogate(input)
926    }
927
928    pub fn is_leading_surrogate(input: u32) -> bool {
929        // https://infra.spec.whatwg.org/#surrogate
930        // A leading surrogate is a code point that is in the range U+D800 to U+DBFF, inclusive.
931        (0xd800..=0xdbff).contains(&input)
932    }
933
934    pub fn is_trailing_surrogate(input: u32) -> bool {
935        // https://infra.spec.whatwg.org/#surrogate
936        // A trailing surrogate is a code point that is in the range U+DC00 to U+DFFF, inclusive.
937        (0xdc00..=0xdfff).contains(&input)
938    }
939
940    pub fn code_point_to_char(input: &str) -> char {
941        char::from_u32(u32::from_str_radix(input, 16).unwrap()).unwrap()
942    }
943
944    pub fn is_digit(input: char) -> bool {
945        // https://www.w3.org/TR/css-syntax-3/#tokenizer-definitions
946        // A code point between U+0030 DIGIT ZERO (0) and U+0039 DIGIT NINE (9) inclusive.
947        ('\u{0030}'..='\u{0039}').contains(&input)
948    }
949
950    pub fn is_hex_digit(input: char) -> bool {
951        // https://www.w3.org/TR/css-syntax-3/#tokenizer-definitions
952        // A digit, or a code point between U+0041 LATIN CAPITAL LETTER A (A) and U+0046 LATIN CAPITAL LETTER F (F) inclusive, or a code point between U+0061 LATIN SMALL LETTER A (a) and U+0066 LATIN SMALL LETTER F (f) inclusive.
953        Self::is_digit(input)
954            || ('\u{0041}'..='\u{0046}').contains(&input)
955            || ('\u{0061}'..='\u{0066}').contains(&input)
956    }
957
958    pub fn is_valid_escape(first: Option<char>, second: Option<char>) -> bool {
959        // https://www.w3.org/TR/css-syntax-3/#starts-with-a-valid-escape
960
961        // If the first code point is not U+005C REVERSE SOLIDUS (\), return false.
962        if first != Some('\u{005c}') {
963            return false;
964        }
965
966        //Otherwise, if the second code point is a newline, return false.
967        if second == Some('\u{000a}') {
968            return false;
969        }
970
971        //Otherwise, return true.
972        true
973    }
974
975    pub fn consume_whitespace(&mut self) {
976        while let Some(&v) = self.process.peek() {
977            if !Self::is_whitespace(v) {
978                break;
979            }
980            println!("consuming {v}");
981            self.process.next();
982        }
983    }
984
985    pub fn is_whitespace(input: char) -> bool {
986        // https://www.w3.org/TR/css-syntax-3/#tokenizer-definitions
987        // A newline, U+0009 CHARACTER TABULATION, or U+0020 SPACE.
988        input == '\u{000a}' || input == '\u{0009}' || input == '\u{0020}'
989    }
990
991    pub fn consume_comments(&mut self) {
992        // https://www.w3.org/TR/css-syntax-3/#consume-comment
993        // This section describes how to consume comments from a stream of code points. It returns nothing.
994        // If the next two input code point are U+002F SOLIDUS (/) followed by a U+002A ASTERISK (*), consume them and all following code points up to and including the first U+002A ASTERISK (*) followed by a U+002F SOLIDUS (/), or up to an EOF code point. Return to the start of this step.
995        let (mut first, mut second) = self.peek_twin();
996        if !(first == Some('\u{002f}') && second == Some('\u{002a}')) {
997            return;
998        }
999
1000        self.process.next();
1001        self.process.next();
1002
1003        loop {
1004            (first, second) = self.peek_twin();
1005
1006            if first.is_none() || second.is_none() {
1007                // If the preceding paragraph ended by consuming an EOF code point, this is a parse error.
1008                self.parse_error();
1009                return;
1010            }
1011
1012            if first == Some('\u{002a}') && second == Some('\u{002f}') {
1013                println!("i was true");
1014                self.process.next();
1015                self.process.next();
1016                self.consume_comments();
1017                // Return nothing.
1018                return;
1019            }
1020
1021            self.process.next();
1022        }
1023    }
1024
1025    pub fn parse_error(&mut self) {
1026        self.parse_error = true;
1027    }
1028
1029    pub fn tokenize(&mut self) -> Vec<CSSToken> {
1030        let mut out = vec![];
1031        loop {
1032            let tok = self.consume_token();
1033            if tok == CSSToken::EOFToken {
1034                out.push(CSSToken::EOFToken);
1035                break;
1036            }
1037            out.push(tok);
1038        }
1039        out
1040    }
1041}
1042
1043#[derive(Debug, PartialEq)]
1044pub enum CSSToken {
1045    EOFToken,
1046    WhitespaceToken,
1047    StringToken {
1048        string: String,
1049    },
1050    BadStringToken,
1051    HashToken {
1052        flag: HashTokenFlag,
1053        value: String,
1054    },
1055    DelimToken {
1056        value: char,
1057    },
1058    LeftParenthesisToken,
1059    RightParenthesisToken,
1060    NumberToken {
1061        flag: NumberType,
1062        value: f64,
1063    },
1064    PercentageToken {
1065        flag: NumberType,
1066        value: f64,
1067    },
1068    DimensionToken {
1069        flag: NumberType,
1070        value: f64,
1071        unit: String,
1072    },
1073    CommaToken,
1074    CDCToken,
1075    FunctionToken {
1076        value: String,
1077    },
1078    URLToken {
1079        value: String,
1080    },
1081    BadURLToken,
1082    IdentToken {
1083        value: String,
1084    },
1085    ColonToken,
1086    SemicolonToken,
1087    CDOToken,
1088    AtKeywordToken {
1089        value: String,
1090    },
1091    LeftSquareBracketToken,
1092    RightSquareBracketToken,
1093    LeftCurlyBracketToken,
1094    RightCurlyBracketToken,
1095}
1096
1097#[derive(Debug, PartialEq, Eq)]
1098pub enum HashTokenFlag {
1099    Id,
1100    Unrestricted,
1101}
1102
1103#[derive(Debug, PartialEq)]
1104pub struct Number {
1105    value: f64,
1106    r#type: NumberType,
1107}
1108
1109#[derive(Debug, PartialEq, Eq)]
1110pub enum NumberType {
1111    Integer,
1112    Number,
1113}
1114
1115pub struct PutBackPeekMore<'a> {
1116    pub peek_more: PeekMoreIterator<Chars<'a>>,
1117    pub put_back: Option<char>,
1118}
1119
1120impl<'a> Iterator for PutBackPeekMore<'a> {
1121    type Item = char;
1122    fn next(&mut self) -> Option<Self::Item> {
1123        if let Some(v) = self.put_back {
1124            let returned = v;
1125            self.put_back = None;
1126            return Some(v);
1127        }
1128        self.peek_more.next()
1129    }
1130}
1131
1132impl<'a> PutBackPeekMore<'a> {
1133    pub fn new(input: &'a str) -> Self {
1134        Self {
1135            put_back: None,
1136            peek_more: input.chars().peekmore(),
1137        }
1138    }
1139
1140    pub fn put_back(&mut self, input: char) {
1141        self.put_back = Some(input);
1142    }
1143
1144    pub fn put_back_option(&mut self, input: Option<char>) {
1145        self.put_back = input;
1146    }
1147
1148    pub fn peek(&mut self) -> Option<&char> {
1149        if self.put_back.is_some() {
1150            return self.put_back.as_ref();
1151        }
1152        self.peek_more.peek()
1153    }
1154
1155    pub fn peek_amount(&mut self, amount: usize) -> Vec<Option<char>> {
1156        if self.put_back.is_some() {
1157            let mut out = vec![self.put_back];
1158            out.extend_from_slice(self.peek_more.peek_amount(amount - 1));
1159            return out;
1160        }
1161        self.peek_more.peek_amount(amount).to_vec()
1162    }
1163
1164    pub fn peek_nth(&mut self, amount: usize) -> Option<&char> {
1165        if self.put_back.is_some() {
1166            return self.peek_more.peek_nth(amount - 1);
1167        }
1168        self.peek_more.peek_nth(amount)
1169    }
1170}