Skip to main content

rust_css_parser/parser/
tokenize.rs

1//! Port of `src/parser/tokenize.ts`.
2//!
3//! The tokenizer reads the code units of the css source (ascii bytes or utf-16 code units, see
4//! [`crate::parser::input`]): the values of the tokens are ranges of the code units, no string is created.
5
6use crate::ast::arena::AstArena;
7use crate::ast::strings::StringSource;
8use crate::ast::types::{ColorType, EnumToken};
9use crate::parser::input::{to_code_units, CssInput};
10use crate::parser::source::SourceFile;
11use crate::parser::utils::canonical::{canonical_end, canonical_start, register_canonical};
12use crate::parser::utils::codes::{lower_ascii, CodeUnits};
13use crate::syntax::constants::{
14    validation_units, COLORS_FUNC, CONTAINER_FUNC, GRID_TEMPLATE_FUNC, IMAGE_FUNC, MATH_FUNCS, PSEUDO_ELEMENTS, SUPPORT_FUNC,
15    TIMELINE_FUNC, TIMING_FUNC, TRANSFORM_FUNCTIONS, URL_FUNC, WHEN_ELSE_FUNC, WILD_CARD_FUNCS,
16};
17use crate::syntax::syntax::{
18    is_digit, is_ident_codepoint, is_ident_start, is_letter, is_new_line, is_non_printable, is_white_space, ANGLE_UNITS,
19    DIMENSION_UNITS, FLEX_UNITS, FREQUENCY_UNITS, RESOLUTION_UNITS, TIME_UNITS,
20};
21use crate::utils::fx::HashMap;
22use std::rc::Rc;
23use std::sync::OnceLock;
24
25/// end of the stream (`undefined` in typescript)
26const EOF: u32 = u32::MAX;
27
28/// decode the escape sequences of a range of code units: a backslash followed by a new line, or by 1 to 6
29/// hexadecimal digits, and an optional space
30pub fn decode_escapes(codes: &CodeUnits, start: usize, end: usize, output: &mut Vec<u16>) {
31    output.clear();
32    let mut i = start;
33    while i < end {
34        let code = codes.at(i);
35        if code != 0x5c || i + 1 >= end {
36            output.push(code as u16);
37            i += 1;
38            continue;
39        }
40        let mut next = codes.at(i + 1);
41        if matches!(next, 0xa | 0xb | 0xc | 0xd | 0x2028 | 0x2029) {
42            i += 2;
43        } else if is_hex_digit(next) {
44            let mut codepoint: u32 = 0;
45            let mut k = i + 1;
46            while k < end && k < i + 7 && is_hex_digit({
47                next = codes.at(k);
48                next
49            }) {
50                codepoint = codepoint * 16 + if next <= 0x39 { next - 0x30 } else { (next | 0x20) - 0x57 };
51                k += 1;
52            }
53            i = k;
54            if codepoint == 0 || (0xd800..=0xdfff).contains(&codepoint) || codepoint > 0x10ffff {
55                output.push(0xfffd);
56            } else if codepoint > 0xffff {
57                let c = codepoint - 0x10000;
58                output.push((0xd800 + (c >> 10)) as u16);
59                output.push((0xdc00 + (c & 0x3ff)) as u16);
60            } else {
61                output.push(codepoint as u16);
62            }
63        } else {
64            // not an escape sequence: the backslash is kept, the next character is read again
65            output.push(code as u16);
66            i += 1;
67            continue;
68        }
69        // an optional space ends the escape sequence
70        if i < end && codes.at(i) == 0x20 {
71            i += 1;
72        }
73    }
74}
75
76/// table of ascii keys, looked up by a range of code units ignoring the case. no string is created: the range is
77/// lowercased into a stack buffer
78struct HashTable<T> {
79    map: HashMap<Box<[u8]>, T>,
80}
81
82impl<T> HashTable<T> {
83    fn new() -> Self {
84        Self { map: HashMap::default() }
85    }
86
87    fn get(&self, codes: &CodeUnits, start: usize, end: usize) -> Option<&T> {
88        let mut buffer = [0u8; 64];
89        let length = end.checked_sub(start)?;
90        if length > buffer.len() {
91            return None;
92        }
93        for (k, slot) in buffer[..length].iter_mut().enumerate() {
94            let code = lower_ascii(codes.at(start + k));
95            if code < 0 {
96                return None;
97            }
98            *slot = code as u8;
99        }
100        self.map.get(&buffer[..length])
101    }
102
103    fn get_key(&self, key: &str) -> Option<&T> {
104        self.map.get(key.to_ascii_lowercase().as_bytes())
105    }
106
107    fn get_key_mut(&mut self, key: &str) -> Option<&mut T> {
108        self.map.get_mut(key.to_ascii_lowercase().as_bytes())
109    }
110
111    fn set(&mut self, key: &str, value: T) {
112        self.map.insert(key.to_ascii_lowercase().into_bytes().into_boxed_slice(), value);
113    }
114}
115
116/// symbols, units and function names: their token type. units and function names: their canonical spelling by
117/// token type
118struct Tables {
119    symbols: HashTable<u8>,
120    items: HashTable<Vec<(u8, u32)>>,
121}
122
123fn tables() -> &'static Tables {
124    // the canonical strings are thread local: the tables are built once per thread
125    thread_local! {
126        static TABLES: &'static Tables = Box::leak(Box::new(build_tables()));
127    }
128    TABLES.with(|t| *t)
129}
130
131fn build_tables() -> Tables {
132    // insertion ordered definitions: a later definition of the same key replaces the value, like a `Map`
133    let mut definitions: Vec<(String, u8)> = Vec::new();
134    let define = |key: String, typ: u8, defs: &mut Vec<(String, u8)>| {
135        if let Some(entry) = defs.iter_mut().find(|(k, _)| *k == key) {
136            entry.1 = typ;
137        } else {
138            defs.push((key, typ));
139        }
140    };
141    let mut items: HashTable<Vec<(u8, u32)>> = HashTable::new();
142    for (key, typ) in [
143        ("+", EnumToken::Plus),
144        ("=", EnumToken::DelimTokenType),
145        ("|", EnumToken::PipeTokenType),
146        ("||", EnumToken::ColumnCombinatorTokenType),
147        ("|=", EnumToken::DashMatchTokenType),
148        ("&", EnumToken::NestingSelectorTokenType),
149        ("*", EnumToken::Star),
150        ("*=", EnumToken::ContainMatchTokenType),
151        ("~", EnumToken::Tilda),
152        ("~=", EnumToken::IncludeMatchTokenType),
153        ("^=", EnumToken::StartMatchTokenType),
154        ("$=", EnumToken::EndMatchTokenType),
155        (",", EnumToken::Comma),
156        (":", EnumToken::ColonTokenType),
157        ("::", EnumToken::DoubleColonTokenType),
158        (";", EnumToken::SemiColonTokenType),
159        ("(", EnumToken::StartParensTokenType),
160        (")", EnumToken::EndParensTokenType),
161        ("[", EnumToken::AttrStartTokenType),
162        ("]", EnumToken::AttrEndTokenType),
163        ("{", EnumToken::BlockStartTokenType),
164        ("}", EnumToken::BlockEndTokenType),
165        ("<=", EnumToken::LteTokenType),
166        (">", EnumToken::GtTokenType),
167        (">=", EnumToken::GteTokenType),
168        (" ", EnumToken::Whitespace),
169        ("\t", EnumToken::Whitespace),
170        ("\r", EnumToken::Whitespace),
171        ("\n", EnumToken::Whitespace),
172        ("\x0c", EnumToken::Whitespace),
173    ] {
174        define(key.to_string(), typ, &mut definitions);
175    }
176    let assign = |entries: &[&str], typ: u8, suffix: &str, lowercase: bool, defs: &mut Vec<(String, u8)>, items: &mut HashTable<Vec<(u8, u32)>>| {
177        for &entry in entries {
178            let key = format!("{}{}", if lowercase { entry.to_lowercase() } else { entry.to_string() }, suffix);
179            define(key, typ, defs);
180            if items.get_key(entry).is_none() {
181                items.set(entry, Vec::new());
182            }
183            let list = items.get_key_mut(entry).unwrap();
184            // the first item wins
185            if !list.iter().any(|(t, _)| *t == typ) {
186                list.push((typ, register_canonical(entry)));
187            }
188        }
189    };
190    assign(&FLEX_UNITS, EnumToken::FlexTokenType, "", false, &mut definitions, &mut items);
191    assign(&DIMENSION_UNITS, EnumToken::LengthTokenType, "", false, &mut definitions, &mut items);
192    assign(&RESOLUTION_UNITS, EnumToken::ResolutionTokenType, "", false, &mut definitions, &mut items);
193    assign(&ANGLE_UNITS, EnumToken::AngleTokenType, "", false, &mut definitions, &mut items);
194    assign(&TIME_UNITS, EnumToken::TimeTokenType, "", false, &mut definitions, &mut items);
195    assign(&FREQUENCY_UNITS, EnumToken::FrequencyTokenType, "", false, &mut definitions, &mut items);
196    // the units of the other dimensions are rendered in their canonical spelling: `6DB` is rendered `6dB`
197    for unit in validation_units() {
198        if items.get_key(unit).is_none() {
199            items.set(unit, Vec::new());
200        }
201        let list = items.get_key_mut(unit).unwrap();
202        if !list.iter().any(|(t, _)| *t == EnumToken::DimensionTokenType) {
203            list.push((EnumToken::DimensionTokenType, register_canonical(unit)));
204        }
205    }
206    assign(&PSEUDO_ELEMENTS, EnumToken::PseudoElementTokenType, "", false, &mut definitions, &mut items);
207    assign(&CONTAINER_FUNC, EnumToken::ContainerFunctionTokenDefType, "(", false, &mut definitions, &mut items);
208    assign(&URL_FUNC, EnumToken::UrlFunctionTokenDefType, "(", false, &mut definitions, &mut items);
209    assign(&GRID_TEMPLATE_FUNC, EnumToken::GridTemplateFuncTokenDefType, "(", false, &mut definitions, &mut items);
210    assign(&IMAGE_FUNC, EnumToken::ImageFunctionTokenDefType, "(", false, &mut definitions, &mut items);
211    assign(&TIMELINE_FUNC, EnumToken::TimelineFunctionTokenDefType, "(", false, &mut definitions, &mut items);
212    assign(&SUPPORT_FUNC, EnumToken::SupportsFunctionTokenDefType, "(", false, &mut definitions, &mut items);
213    assign(&TIMING_FUNC, EnumToken::TimingFunctionTokenDefType, "(", false, &mut definitions, &mut items);
214    assign(&COLORS_FUNC, EnumToken::ColorFunctionTokenDefType, "(", false, &mut definitions, &mut items);
215    assign(&MATH_FUNCS, EnumToken::MathFunctionTokenDefType, "(", false, &mut definitions, &mut items);
216    assign(&TRANSFORM_FUNCTIONS, EnumToken::TransformFunctionTokenDefType, "(", true, &mut definitions, &mut items);
217    assign(&WHEN_ELSE_FUNC, EnumToken::WhenElseFunctionTokenDefType, "(", false, &mut definitions, &mut items);
218    assign(&WILD_CARD_FUNCS, EnumToken::WildCardFunctionTokenDefType, "(", false, &mut definitions, &mut items);
219    let mut symbols = HashTable::new();
220    for (key, typ) in definitions {
221        symbols.set(&key, typ);
222    }
223    Tables { symbols, items }
224}
225
226/// do not capture the value (`hintsEnum`)
227pub fn is_hint(typ: u8) -> bool {
228    matches!(
229        typ,
230        EnumToken::CommaTokenType
231            | EnumToken::ImportantTokenType
232            | EnumToken::SemiColonTokenType
233            | EnumToken::BlockStartTokenType
234            | EnumToken::BlockEndTokenType
235            | EnumToken::StartParensTokenType
236            | EnumToken::EndParensTokenType
237            | EnumToken::ColonTokenType
238            | EnumToken::EOFTokenType
239    )
240}
241
242/// field of the token the value of a token is stored in
243#[derive(Clone, Copy, Debug, PartialEq, Eq)]
244pub enum TokenValueField {
245    None = 0,
246    Number = 1,
247    Name = 2,
248    Value = 3,
249    Unit = 4,
250}
251
252/// where the string value of a token is read from
253#[derive(Clone, Copy, Debug, PartialEq, Eq)]
254pub enum TokenValueKind {
255    Source = 0,
256    Canonical = 1,
257    Escaped = 2,
258}
259
260#[allow(non_snake_case, dead_code)]
261mod TokenMap {
262    pub const EXCLAMATION: u32 = 33;
263    pub const QUESTION: u32 = 63;
264    pub const SLASH: u32 = 47;
265    pub const LOWERTHAN: u32 = 60;
266    pub const HASH: u32 = 35;
267    pub const REVERSE_SOLIDUS: u32 = 92;
268    pub const DOUBLE_QUOTE: u32 = 34;
269    pub const SINGLE_QUOTE: u32 = 39;
270    pub const DOT: u32 = 46;
271    pub const AT: u32 = 64;
272    pub const PIPE: u32 = 124;
273    pub const EQUALS: u32 = 61;
274    pub const AMPERSAND: u32 = 38;
275    pub const STAR: u32 = 42;
276    pub const TILDA: u32 = 126;
277    pub const CARET: u32 = 94;
278    pub const DOLLAR: u32 = 36;
279    pub const COMMA: u32 = 44;
280    pub const COLON: u32 = 58;
281    pub const SEMICOLON: u32 = 59;
282    pub const LEFT_PARENTHESIS: u32 = 40;
283    pub const RIGHT_PARENTHESIS: u32 = 41;
284    pub const LEFT_BRACKETS: u32 = 91;
285    pub const RIGHT_BRACKETS: u32 = 93;
286    pub const LEFT_BRACE: u32 = 123;
287    pub const RIGHT_BRACE: u32 = 125;
288    pub const PLUS: u32 = 43;
289    pub const MINUS: u32 = 45;
290    pub const GREATERTHAN: u32 = 62;
291    pub const PERCENTAGE: u32 = 37;
292}
293
294use TokenMap::*;
295
296/// value of a number: the longest prefix of the range that is a number, like `parseFloat()`. the prefix is copied to a
297/// stack buffer and parsed by the correctly rounded rust parser (same result as `parseFloat()`)
298pub fn parse_number(codes: &CodeUnits, start: usize, end: usize) -> f64 {
299    parse_short_number(codes, start, end).unwrap_or_else(|| parse_long_number(codes, start, end))
300}
301
302/// powers of ten represented exactly by a f64
303const POWERS_OF_TEN: [f64; 16] = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15];
304
305/// a number of 15 digits or less, without exponent: the digits are an integer represented exactly by a f64, divided by
306/// a power of ten represented exactly. the division is correctly rounded: the result is the result of `parseFloat`.
307/// `None` for the other numbers
308fn parse_short_number(codes: &CodeUnits, start: usize, end: usize) -> Option<f64> {
309    let mut i = start;
310    let mut code = codes.at(i);
311    let negative = code == 0x2d;
312    if negative || code == 0x2b {
313        i += 1;
314        code = codes.at(i);
315    }
316    let mut mantissa: u64 = 0;
317    let mut digits = 0usize;
318    let mut decimals = 0usize;
319    let mut dot = false;
320    while i < end {
321        if (0x30..=0x39).contains(&code) {
322            mantissa = mantissa * 10 + (code - 0x30) as u64;
323            digits += 1;
324            if dot {
325                decimals += 1;
326            }
327        } else if code == 0x2e && !dot {
328            dot = true;
329        } else {
330            break;
331        }
332        i += 1;
333        code = codes.at(i);
334    }
335    if digits == 0 || digits > 15 || (i < end && (code == 0x65 || code == 0x45)) {
336        return None;
337    }
338    let value = mantissa as f64 / POWERS_OF_TEN[decimals];
339    Some(if negative { -value } else { value })
340}
341
342/// see [`parse_number`]: the numbers that are not read by [`parse_short_number`]
343fn parse_long_number(codes: &CodeUnits, start: usize, end: usize) -> f64 {
344    let mut buffer = [0u8; 128];
345    let mut heap: Vec<u8> = Vec::new();
346    let mut len = 0usize;
347    let push = |b: u8, buffer: &mut [u8; 128], heap: &mut Vec<u8>, len: &mut usize| {
348        if *len < 128 {
349            buffer[*len] = b;
350        } else {
351            if heap.is_empty() {
352                heap.extend_from_slice(&buffer[..]);
353            }
354            heap.push(b);
355        }
356        *len += 1;
357    };
358    let mut i = start;
359    let mut code = codes.at(i);
360    if code == 0x2d || code == 0x2b {
361        push(code as u8, &mut buffer, &mut heap, &mut len);
362        i += 1;
363        code = codes.at(i);
364    }
365    let mut count = 0;
366    let mut dot = false;
367    while i < end {
368        if (0x30..=0x39).contains(&code) {
369            push(code as u8, &mut buffer, &mut heap, &mut len);
370            count += 1;
371        } else if code == 0x2e && !dot {
372            dot = true;
373            push(b'.', &mut buffer, &mut heap, &mut len);
374        } else {
375            break;
376        }
377        i += 1;
378        code = codes.at(i);
379    }
380    if count == 0 {
381        return f64::NAN;
382    }
383    if i < end && (code == 0x65 || code == 0x45) {
384        let mut k = i + 1;
385        let mut exponent: Vec<u8> = vec![b'e'];
386        if k < end && (codes.at(k) == 0x2d || codes.at(k) == 0x2b) {
387            exponent.push(codes.at(k) as u8);
388            k += 1;
389        }
390        if k < end && is_digit(codes.at(k)) {
391            let mut digits = 0;
392            while k < end && is_digit(codes.at(k)) {
393                // larger exponents are Infinity or 0
394                if digits < 7 {
395                    exponent.push(codes.at(k) as u8);
396                }
397                digits += 1;
398                k += 1;
399            }
400            for b in exponent {
401                push(b, &mut buffer, &mut heap, &mut len);
402            }
403        }
404    }
405    let text = if heap.is_empty() { &buffer[..len] } else { &heap[..] };
406    // ascii digits: valid utf-8. rust rejects a trailing dot ("1.") but parseFloat accepts it
407    let mut s = unsafe { std::str::from_utf8_unchecked(text) };
408    let trimmed;
409    if s.contains(".e") || s.contains(".E") || s.ends_with('.') {
410        trimmed = s.replacen(".e", "e", 1).replacen(".E", "E", 1).trim_end_matches('.').to_string();
411        s = &trimmed;
412    }
413    s.parse::<f64>().unwrap_or(f64::NAN)
414}
415
416#[inline]
417fn is_hex_digit(codepoint: u32) -> bool {
418    (0x30..=0x39).contains(&codepoint) || (0x41..=0x46).contains(&codepoint) || (0x61..=0x66).contains(&codepoint)
419}
420
421/// true if the character may follow a numeric token
422#[inline]
423fn is_numeric_token_end(codepoint: u32, is_dimension: bool) -> bool {
424    codepoint == EOF
425        || is_white_space(codepoint)
426        || codepoint == LEFT_BRACE
427        || codepoint == RIGHT_PARENTHESIS
428        || codepoint == SEMICOLON
429        || codepoint == EXCLAMATION
430        || codepoint == RIGHT_BRACE
431        || codepoint == SLASH
432        || codepoint == STAR
433        || codepoint == COMMA
434        || (is_dimension && codepoint == PLUS)
435}
436
437/// the css being tokenized (`ParseInfo`)
438#[derive(Debug)]
439pub struct ParseInfo {
440    pub codes: CodeUnits,
441    pub length: usize,
442    pub source: Rc<SourceFile>,
443    pub offset: usize,
444    pub time: f64,
445    pub position: usize,
446    pub current_position: usize,
447}
448
449impl ParseInfo {
450    #[inline(always)]
451    fn at(&self, index: usize) -> u32 {
452        if index < self.length {
453            self.codes.at(index)
454        } else {
455            EOF
456        }
457    }
458
459    #[inline(always)]
460    fn cur(&self) -> u32 {
461        self.at(self.current_position - self.offset)
462    }
463
464    fn push_line_start(&self, position: usize) {
465        self.source.line_starts.borrow_mut().line_starts.push(position as u32);
466    }
467}
468
469/// the parse info of a css input
470pub fn create_parse_info(input: Option<&CssInput>, source: Rc<SourceFile>) -> ParseInfo {
471    let mut parse_info = ParseInfo {
472        codes: CodeUnits::Bytes(Rc::from(&[][..])),
473        length: 0,
474        source,
475        offset: 0,
476        time: 0.0,
477        position: 0,
478        current_position: 0,
479    };
480    Tokenizer::load(&mut parse_info, input);
481    parse_info
482}
483
484/// a chunk of a stream
485pub enum StreamChunk {
486    Bytes(Rc<[u8]>),
487    Text(Rc<str>),
488}
489
490/// decode the longest prefix of complete utf-8 characters: the invalid sequences are replaced with U+FFFD, like
491/// `TextDecoder`. returns the length of the decoded prefix: the bytes that follow start a character that is not
492/// complete
493fn decode_utf8_prefix(bytes: &[u8], out: &mut String) -> usize {
494    let mut i = 0;
495    while i < bytes.len() {
496        match std::str::from_utf8(&bytes[i..]) {
497            Ok(text) => {
498                out.push_str(text);
499                return bytes.len();
500            }
501            Err(error) => {
502                let valid = error.valid_up_to();
503                // SAFETY: the prefix is valid utf-8
504                out.push_str(unsafe { std::str::from_utf8_unchecked(&bytes[i..i + valid]) });
505                match error.error_len() {
506                    // a character that continues in the next chunk
507                    None => return i + valid,
508                    Some(length) => {
509                        out.push('\u{fffd}');
510                        i += valid + length;
511                    }
512                }
513            }
514        }
515    }
516    i
517}
518
519/// a buffer of at least `required` units that starts with `units`: the capacity doubles
520fn grow<T: Copy>(units: &[T], required: usize, zero: T) -> Rc<[T]> {
521    let mut capacity = units.len().max(1 << 16);
522    while capacity < required {
523        capacity *= 2;
524    }
525    let mut buffer = Vec::with_capacity(capacity);
526    buffer.extend_from_slice(units);
527    buffer.resize(capacity, zero);
528    Rc::from(buffer)
529}
530
531/// write the utf-16 code units of a text at an offset
532fn write_utf16(buffer: &mut [u16], offset: usize, text: &str) {
533    for (i, unit) in text.encode_utf16().enumerate() {
534        buffer[offset + i] = unit;
535    }
536}
537
538/// tokenizer
539pub struct Tokenizer {
540    pub typ: Option<u8>,
541    pub kin: Option<u8>,
542    pub num: f64,
543    pub field: TokenValueField,
544    pub value_kind: TokenValueKind,
545    pub value_start: usize,
546    pub value_end: usize,
547    pub src_id: Option<u32>,
548    pub sta: Option<usize>,
549    pub end: Option<usize>,
550    pub bytes_in: Option<usize>,
551    pub slice: Option<usize>,
552    ident_non_ascii: bool,
553    hint: Option<u8>,
554    state: Option<u8>,
555    pub parse_info: ParseInfo,
556    decoded: Vec<u16>,
557    /// the input is a stream that is not read to its end, see [`Tokenizer::next`] and [`Tokenizer::append`]
558    stream: Option<StreamState>,
559    /// the last call of [`Tokenizer::next`] reached the end of the code units read from the stream: the token may
560    /// continue in the next chunk. no token is returned, a chunk must be appended before `next()` is called again
561    pub waiting: bool,
562    /// the size of the css of a stream, in bytes, when it is known, see [`Tokenizer::streaming`]
563    expected_length: usize,
564}
565
566/// the state of a stream read by the tokenizer
567struct StreamState {
568    /// the bytes of a character split between two chunks
569    pending: Vec<u8>,
570    /// no chunk has been decoded yet: a leading byte order mark is removed
571    first: bool,
572}
573
574/// number of code units the tokenizer may read after the end of a token (escape sequences, unicode ranges, `<!--`,
575/// ...): a token read from a stream is complete when the stream has more code units after it
576const STREAM_LOOKAHEAD: usize = 32;
577
578impl Tokenizer {
579    pub fn new(parse_info: ParseInfo) -> Self {
580        Self {
581            typ: None,
582            kin: None,
583            num: 0.0,
584            field: TokenValueField::None,
585            value_kind: TokenValueKind::Source,
586            value_start: 0,
587            value_end: 0,
588            src_id: None,
589            sta: None,
590            end: None,
591            bytes_in: None,
592            slice: None,
593            ident_non_ascii: false,
594            hint: None,
595            state: None,
596            parse_info,
597            decoded: Vec::new(),
598            stream: None,
599            waiting: false,
600            expected_length: 0,
601        }
602    }
603
604    /// tokenizer of a stream: the chunks are appended with [`Tokenizer::append`] when the tokenizer is waiting.
605    /// `size`: the size of the css in bytes when it is known, 0 otherwise. the code units are allocated once: the size
606    /// in bytes is not less than the number of utf-16 code units
607    pub fn streaming(parse_info: ParseInfo, size: usize) -> Self {
608        let mut tokenizer = Self::new(parse_info);
609        tokenizer.parse_info.codes = CodeUnits::Bytes(if size > 0 { Rc::from(vec![0u8; size]) } else { Rc::from(&[][..]) });
610        tokenizer.parse_info.length = 0;
611        tokenizer.stream = Some(StreamState { pending: Vec::new(), first: true });
612        tokenizer.expected_length = size;
613        tokenizer
614    }
615
616    /// the size of the css of a stream, in bytes, when it is known. 0: not known, or not a stream
617    pub fn expected_length(&self) -> usize {
618        self.expected_length
619    }
620
621    /// true while the input is a stream that is not read to its end
622    pub fn is_streaming(&self) -> bool {
623        self.stream.is_some()
624    }
625
626    /// append a chunk of the stream: utf-8 bytes or text. `None` ends the stream. the code units stay bytes while the
627    /// css is ascii, they are utf-16 code units otherwise. the buffer of the code units doubles when it is full: the
628    /// code units read so far are not copied for each chunk. the buffer is written in place when the tokenizer holds
629    /// the only reference to it: the caller drops its other references first (the source text of the arena)
630    pub fn append(&mut self, chunk: Option<StreamChunk>) {
631        self.waiting = false;
632        let Some(state) = self.stream.as_mut() else {
633            return;
634        };
635        let mut text = String::new();
636        match chunk {
637            Some(StreamChunk::Text(t)) => text.push_str(&t),
638            Some(StreamChunk::Bytes(bytes)) => {
639                state.pending.extend_from_slice(&bytes);
640                let pending = std::mem::take(&mut state.pending);
641                let rest = decode_utf8_prefix(&pending, &mut text);
642                state.pending = pending[rest..].to_vec();
643                // TextDecoder removes the byte order mark
644                if state.first && !text.is_empty() {
645                    if let Some(stripped) = text.strip_prefix('\u{feff}') {
646                        text = stripped.to_string();
647                    }
648                }
649                if !text.is_empty() {
650                    state.first = false;
651                }
652            }
653            None => {
654                // a character that is not complete at the end of the stream
655                if !state.pending.is_empty() {
656                    text.push('\u{fffd}');
657                }
658                self.stream = None;
659            }
660        }
661        if !text.is_empty() {
662            self.append_text(&text);
663        }
664        if self.stream.is_none() {
665            self.finish_stream();
666        }
667    }
668
669    /// append the code units of a text to the code units of the stream
670    fn append_text(&mut self, text: &str) {
671        // the size of the stream when it is known: the buffer of utf-16 code units is allocated once
672        let expected = self.expected_length;
673        let pi = &mut self.parse_info;
674        let length = pi.length;
675        let ascii = text.is_ascii() && matches!(pi.codes, CodeUnits::Bytes(_));
676        let required = length + if ascii { text.len() } else { text.encode_utf16().count() };
677        let codes = std::mem::replace(&mut pi.codes, CodeUnits::Bytes(Rc::from(&[][..])));
678        pi.codes = match codes {
679            CodeUnits::Bytes(mut bytes) if ascii => {
680                if required > bytes.len() || Rc::get_mut(&mut bytes).is_none() {
681                    bytes = grow(&bytes[..length], required, 0u8);
682                }
683                Rc::get_mut(&mut bytes).expect("unique buffer")[length..required].copy_from_slice(text.as_bytes());
684                CodeUnits::Bytes(bytes)
685            }
686            CodeUnits::Bytes(bytes) => {
687                // the css is not ascii: the code units are utf-16 code units from now on
688                let widened: Vec<u16> = bytes[..length].iter().map(|&b| b as u16).collect();
689                let mut units = grow(&widened, required.max(expected), 0u16);
690                write_utf16(Rc::get_mut(&mut units).expect("unique buffer"), length, text);
691                CodeUnits::Utf16(units)
692            }
693            CodeUnits::Utf16(mut units) => {
694                if required > units.len() || Rc::get_mut(&mut units).is_none() {
695                    units = grow(&units[..length], required, 0u16);
696                }
697                write_utf16(Rc::get_mut(&mut units).expect("unique buffer"), length, text);
698                CodeUnits::Utf16(units)
699            }
700        };
701        pi.length = required;
702    }
703
704    /// the end of the stream: the code units are trimmed to their length, the text of the source file is set
705    fn finish_stream(&mut self) {
706        let pi = &mut self.parse_info;
707        let length = pi.length;
708        let (codes, text): (CodeUnits, Rc<str>) = match &pi.codes {
709            CodeUnits::Bytes(b) => {
710                let bytes: Rc<[u8]> = Rc::from(&b[..length]);
711                // ascii: the bytes are the text
712                let text: Rc<str> = Rc::from(std::str::from_utf8(&bytes).expect("ascii"));
713                (CodeUnits::Bytes(bytes), text)
714            }
715            CodeUnits::Utf16(u) => (CodeUnits::Utf16(Rc::from(&u[..length])), Rc::from(String::from_utf16_lossy(&u[..length]))),
716        };
717        pi.codes = codes;
718        *pi.source.content.borrow_mut() = text;
719    }
720
721    /// tokenizer of a css input with a new anonymous source
722    pub fn from_input(input: &CssInput) -> Self {
723        let source = SourceFile::new(Rc::from(""), Vec::new(), Some(Rc::from("")));
724        Self::new(create_parse_info(Some(input), source))
725    }
726
727    /// set the css read by the tokenizer. the text of the css is the content of the source file
728    pub fn load(parse_info: &mut ParseInfo, input: Option<&CssInput>) {
729        let units = to_code_units(input);
730        parse_info.length = units.codes.len();
731        parse_info.codes = units.codes;
732        *parse_info.source.content.borrow_mut() = units.text;
733    }
734
735    /// id of the source file being tokenized
736    pub fn source_id(&self) -> u32 {
737        self.parse_info.source.id
738    }
739
740    /// length of the css input, in code units
741    pub fn stream_length(&self) -> usize {
742        self.parse_info.length
743    }
744
745    /// the source file
746    pub fn source(&self) -> Rc<SourceFile> {
747        self.parse_info.source.clone()
748    }
749
750    fn consume_string(&mut self) -> &mut Self {
751        let quote = self.advance_code();
752        let mut decode_segments = false;
753        loop {
754            let pi = &self.parse_info;
755            let mut char_code = pi.cur();
756            if char_code == EOF {
757                break;
758            }
759            if char_code == REVERSE_SOLIDUS {
760                let p = pi.current_position - pi.offset;
761                if char_code == pi.at(p + 1) {
762                    self.advance(2);
763                    continue;
764                }
765                char_code = pi.at(p + 1);
766                if matches!(char_code, 0xa | 0xb | 0xc | 0xd | 0x2028 | 0x2029) {
767                    self.advance(2);
768                    decode_segments = true;
769                    continue;
770                }
771                let escape_length = self.escape_sequence_length();
772                if escape_length > 0 {
773                    let pi = &self.parse_info;
774                    let length = escape_length + 1 + if is_white_space(pi.cur()) { 1 } else { 0 };
775                    decode_segments = true;
776                    self.advance(length);
777                    continue;
778                }
779                self.advance(2);
780                continue;
781            }
782            if char_code == quote {
783                self.advance_code();
784                return self.make_token(Some(EnumToken::StringTokenType), None, decode_segments);
785            }
786            if is_new_line(char_code) {
787                self.advance_code();
788                return self.make_token(Some(EnumToken::BadStringTokenType), None, false);
789            }
790            self.advance_code();
791        }
792        self.make_token(Some(EnumToken::StringTokenType), None, decode_segments)
793    }
794
795    fn consume_string_as_url_token(&mut self) -> &mut Self {
796        let quote = self.advance_code();
797        let mut decode_segments = false;
798        loop {
799            let pi = &self.parse_info;
800            let mut char_code = pi.cur();
801            if char_code == EOF {
802                break;
803            }
804            if char_code == REVERSE_SOLIDUS {
805                let p = pi.current_position - pi.offset;
806                if char_code == pi.at(p + 1) {
807                    self.advance(2);
808                    continue;
809                }
810                let escape_length = self.escape_sequence_length();
811                if escape_length > 0 {
812                    let length = escape_length + 1 + if is_white_space(self.parse_info.cur()) { 1 } else { 0 };
813                    decode_segments = true;
814                    self.advance(length);
815                    continue;
816                }
817                self.advance(2);
818                continue;
819            }
820            if char_code == quote {
821                self.advance_code();
822                let pi = &self.parse_info;
823                let k = 1;
824                let end = pi.length - pi.offset;
825                let position = pi.current_position - pi.offset;
826                let mut k = k;
827                while position + k < end {
828                    char_code = pi.at(position);
829                    if char_code == EOF {
830                        self.advance(k);
831                        return self.make_token(Some(EnumToken::BadUrlTokenType), None, false);
832                    }
833                    if is_white_space(char_code) {
834                        k += 1;
835                        continue;
836                    }
837                    if char_code != RIGHT_PARENTHESIS {
838                        self.advance(k);
839                        return self.make_token(Some(EnumToken::BadUrlTokenType), None, false);
840                    }
841                    break;
842                }
843                return self.make_token(Some(EnumToken::StringTokenType), None, decode_segments);
844            }
845            if is_new_line(char_code) {
846                self.advance_code();
847                loop {
848                    let c = self.parse_info.cur();
849                    if c == EOF {
850                        break;
851                    }
852                    if c == REVERSE_SOLIDUS {
853                        self.advance(2);
854                        continue;
855                    }
856                    if c == RIGHT_PARENTHESIS {
857                        return self.make_token(Some(EnumToken::BadUrlTokenType), None, false);
858                    }
859                    self.advance_code();
860                }
861                return self.make_token(Some(EnumToken::BadStringTokenType), None, false);
862            }
863            self.advance_code();
864        }
865        self.make_token(Some(EnumToken::BadUrlTokenType), None, false)
866    }
867
868    /// consume a unicode range: `U+0025-00FF`, `U+4??`
869    fn consume_unicode_range_token(&self) -> usize {
870        let pi = &self.parse_info;
871        let start = pi.current_position - pi.offset;
872        let mut position = start + 2;
873        let mut count = 0;
874        let mut wildcards = 0;
875        if pi.at(start + 1) != PLUS {
876            return 0;
877        }
878        while count < 6 {
879            let codepoint = pi.at(position);
880            if wildcards == 0 && is_hex_digit(codepoint) {
881                count += 1;
882                position += 1;
883            } else if codepoint == QUESTION {
884                wildcards += 1;
885                count += 1;
886                position += 1;
887            } else {
888                break;
889            }
890        }
891        if count == 0 {
892            return 0;
893        }
894        if wildcards == 0 && pi.at(position) == MINUS && is_hex_digit(pi.at(position + 1)) {
895            position += 1;
896            count = 0;
897            while count < 6 && is_hex_digit(pi.at(position)) {
898                count += 1;
899                position += 1;
900            }
901        }
902        let codepoint = pi.at(position);
903        if codepoint == EOF
904            || is_white_space(codepoint)
905            || codepoint == COMMA
906            || codepoint == SEMICOLON
907            || codepoint == RIGHT_BRACE
908            || codepoint == RIGHT_PARENTHESIS
909            || codepoint == EXCLAMATION
910        {
911            return position - start;
912        }
913        0
914    }
915
916    /// consume a number, a dimension or a percentage
917    fn consume_numeric_token(&mut self) -> usize {
918        self.slice = None;
919        self.hint = None;
920        let pi = &self.parse_info;
921        let offset = pi.current_position - pi.offset;
922        let mut position = offset;
923        let mut has_digits = false;
924        let mut codepoint = pi.at(position);
925        if codepoint == PLUS || codepoint == MINUS {
926            position += 1;
927        }
928        while is_digit(pi.at(position)) {
929            position += 1;
930            has_digits = true;
931        }
932        if pi.at(position) == DOT && is_digit(pi.at(position + 1)) {
933            position += 1;
934            while is_digit(pi.at(position)) {
935                position += 1;
936            }
937            has_digits = true;
938        }
939        if !has_digits {
940            return 0;
941        }
942        codepoint = pi.at(position);
943        if codepoint == 0x45 || codepoint == 0x65 {
944            let mut k = position + 1;
945            if pi.at(k) == PLUS || pi.at(k) == MINUS {
946                k += 1;
947            }
948            if is_digit(pi.at(k)) {
949                position = k;
950                while is_digit(pi.at(position)) {
951                    position += 1;
952                }
953            }
954        }
955        codepoint = pi.at(position);
956        if codepoint == PERCENTAGE {
957            let slice = position;
958            position += 1;
959            if !is_numeric_token_end(pi.at(position), false) {
960                return 0;
961            }
962            self.slice = Some(slice);
963            self.hint = Some(EnumToken::PercentageTokenType);
964            return position - offset;
965        }
966        if is_letter(codepoint) || (codepoint == MINUS && pi.at(position + 1) == MINUS) {
967            let slice = position;
968            while position < pi.length {
969                position += 1;
970                codepoint = pi.at(position);
971                if !is_letter(codepoint) && codepoint != MINUS {
972                    break;
973                }
974            }
975            if !is_numeric_token_end(pi.at(position), true) {
976                return 0;
977            }
978            let hint = get_symbol_hint(pi, slice, position).unwrap_or(EnumToken::DimensionTokenType);
979            self.slice = Some(slice);
980            self.hint = Some(hint);
981            return position - offset;
982        }
983        if is_numeric_token_end(codepoint, false) {
984            position - offset
985        } else {
986            0
987        }
988    }
989
990    fn consume_ident_token(&mut self) -> usize {
991        let pi = &self.parse_info;
992        let mut position = pi.current_position - pi.offset;
993        let offset = position;
994        self.ident_non_ascii = false;
995        let mut codepoint = pi.at(position);
996        if !is_ident_start(codepoint) && codepoint != MINUS {
997            return 0;
998        }
999        if codepoint == MINUS {
1000            position += 1;
1001            codepoint = pi.at(position);
1002            if !is_ident_start(codepoint) && codepoint != MINUS {
1003                return 0;
1004            }
1005        }
1006        loop {
1007            codepoint = pi.at(position);
1008            if codepoint == EOF {
1009                break;
1010            }
1011            if codepoint == REVERSE_SOLIDUS {
1012                codepoint = pi.at(position + 1);
1013                if codepoint == EOF {
1014                    return 0;
1015                }
1016                if matches!(codepoint, 0xa | 0xb | 0xc | 0xd | 0x2028 | 0x2029) {
1017                    return 0;
1018                }
1019                position += 2;
1020                continue;
1021            }
1022            if codepoint == 0x2d || is_ident_codepoint(codepoint) {
1023                if codepoint > 0x7f {
1024                    self.ident_non_ascii = true;
1025                }
1026                position += 1;
1027            } else {
1028                match codepoint {
1029                    COLON | LEFT_BRACE | RIGHT_BRACE | LEFT_PARENTHESIS | RIGHT_PARENTHESIS | LEFT_BRACKETS | RIGHT_BRACKETS
1030                    | SEMICOLON | EXCLAMATION | SLASH | HASH | STAR | EQUALS | TILDA | PIPE | CARET | DOLLAR | COMMA
1031                    | GREATERTHAN | DOT | PLUS => return position - offset,
1032                    _ => {}
1033                }
1034                if is_white_space(codepoint) {
1035                    return position - offset;
1036                }
1037                return 0;
1038            }
1039        }
1040        position - offset
1041    }
1042
1043    fn consume_color(&self) -> usize {
1044        let pi = &self.parse_info;
1045        let mut position = pi.current_position - pi.offset;
1046        let offset = position;
1047        if pi.at(position) != HASH {
1048            return 0;
1049        }
1050        position += 1;
1051        let mut count = 0;
1052        while is_hex_digit(pi.at(position)) {
1053            position += 1;
1054            count += 1;
1055        }
1056        if count != 3 && count != 4 && count != 6 && count != 8 {
1057            return 0;
1058        }
1059        let codepoint = pi.at(position);
1060        if codepoint == EOF
1061            || is_white_space(codepoint)
1062            || codepoint == RIGHT_PARENTHESIS
1063            || codepoint == SEMICOLON
1064            || codepoint == RIGHT_BRACE
1065            || codepoint == COMMA
1066        {
1067            return position - offset;
1068        }
1069        0
1070    }
1071
1072    fn consume_url_token(&mut self, end_position: usize) -> &mut Self {
1073        while is_white_space(self.parse_info.cur()) {
1074            self.advance_code();
1075        }
1076        let mut char_code = self.parse_info.cur();
1077        if char_code == DOUBLE_QUOTE || char_code == SINGLE_QUOTE {
1078            return self.consume_string_as_url_token();
1079        }
1080        loop {
1081            self.advance_code();
1082            char_code = self.parse_info.cur();
1083            if !(char_code != RIGHT_PARENTHESIS && !is_white_space(char_code) && self.parse_info.current_position < end_position) {
1084                break;
1085            }
1086        }
1087        if char_code != RIGHT_PARENTHESIS {
1088            let mut k = 1;
1089            let pi = &self.parse_info;
1090            while k < end_position {
1091                char_code = pi.at(pi.current_position - pi.offset + k);
1092                if is_white_space(char_code) {
1093                    k += 1;
1094                    continue;
1095                }
1096                break;
1097            }
1098            if char_code == EOF || (char_code != RIGHT_PARENTHESIS && !is_ident_start(char_code)) {
1099                self.advance(k);
1100                return self.make_token(Some(EnumToken::BadUrlTokenType), None, false);
1101            }
1102        }
1103        let typ = if self.parse_info.cur() == EOF || !self.is_url_token() {
1104            EnumToken::BadUrlTokenType
1105        } else {
1106            EnumToken::UrlTokenTokenType
1107        };
1108        self.make_token(Some(typ), None, false)
1109    }
1110
1111    /// set the current token: its type, its numeric value and the range of its string value. no string is created
1112    pub fn make_token(&mut self, hint: Option<u8>, slice: Option<usize>, decode_segments: bool) -> &mut Self {
1113        let pi = &self.parse_info;
1114        let start = pi.position - pi.offset;
1115        let end = pi.current_position - pi.offset;
1116        let mut canonical: i64 = -1;
1117        let mut value_start = start;
1118        let mut has_value = false;
1119        self.typ = None;
1120        self.kin = None;
1121        self.num = 0.0;
1122        self.field = TokenValueField::None;
1123        self.slice = None;
1124        self.hint = None;
1125        // `if (slice)`: 0 is falsy
1126        if let Some(s) = slice.filter(|&s| s != 0) {
1127            self.slice = Some(s);
1128        }
1129        if let Some(hint) = hint {
1130            let mut is_list = false;
1131            let mut has_unit = false;
1132            match hint {
1133                EnumToken::TransformFunctionTokenDefType
1134                | EnumToken::ColorFunctionTokenDefType
1135                | EnumToken::ContainerFunctionTokenDefType
1136                | EnumToken::UrlFunctionTokenDefType
1137                | EnumToken::GridTemplateFuncTokenDefType
1138                | EnumToken::ImageFunctionTokenDefType
1139                | EnumToken::TimelineFunctionTokenDefType
1140                | EnumToken::SupportsFunctionTokenDefType
1141                | EnumToken::TimingFunctionTokenDefType
1142                | EnumToken::MathFunctionTokenDefType
1143                | EnumToken::WhenElseFunctionTokenDefType
1144                | EnumToken::WildCardFunctionTokenDefType => is_list = true,
1145                EnumToken::FrequencyTokenType
1146                | EnumToken::ResolutionTokenType
1147                | EnumToken::LengthTokenType
1148                | EnumToken::FlexTokenType
1149                | EnumToken::AngleTokenType
1150                | EnumToken::TimeTokenType => {
1151                    is_list = true;
1152                    has_unit = true;
1153                }
1154                EnumToken::DimensionTokenType => has_unit = true,
1155                _ => {}
1156            }
1157            let hinted = is_hint(hint);
1158            if is_list {
1159                value_start = if has_unit { slice.unwrap_or(0) } else { start };
1160                canonical = find_item(hint, pi, value_start, end);
1161                has_value = canonical != -1;
1162            } else if hint == EnumToken::NumberTokenType || hint == EnumToken::WhitespaceTokenType {
1163                // the number is read below. the whitespace is rendered as a single space
1164            } else if !hinted {
1165                value_start = slice.unwrap_or(start);
1166                canonical = if hint == EnumToken::DimensionTokenType {
1167                    find_item(EnumToken::DimensionTokenType, pi, value_start, end)
1168                } else {
1169                    -1
1170                };
1171                has_value = true;
1172            }
1173            self.typ = Some(hint);
1174            if !hinted {
1175                if has_unit || hint == EnumToken::PercentageTokenType || hint == EnumToken::DimensionTokenType {
1176                    self.num = parse_number(&pi.codes, start, slice.unwrap_or(start));
1177                    if hint != EnumToken::PercentageTokenType {
1178                        self.field = if has_value { TokenValueField::Unit } else { TokenValueField::Number };
1179                        if canonical == -1 && pi.at(value_start) == 0x2d && pi.at(value_start + 1) == 0x2d {
1180                            self.typ = Some(EnumToken::UserDefinedDimensionTokenType);
1181                        }
1182                    } else {
1183                        self.field = TokenValueField::Number;
1184                    }
1185                } else if hint == EnumToken::NumberTokenType {
1186                    self.num = parse_number(&pi.codes, slice.unwrap_or(start), end);
1187                    self.field = TokenValueField::Number;
1188                } else if hint == EnumToken::AtRuleTokenType {
1189                    self.field = if has_value { TokenValueField::Name } else { TokenValueField::None };
1190                } else {
1191                    self.field = if has_value { TokenValueField::Value } else { TokenValueField::None };
1192                    if hint == EnumToken::ColorTokenType {
1193                        self.kin = Some(ColorType::HEX);
1194                    }
1195                }
1196            }
1197        } else if self.equals_ignore_case("!important") {
1198            self.typ = Some(EnumToken::ImportantTokenType);
1199        }
1200        if self.typ.is_none() {
1201            value_start = start;
1202            has_value = true;
1203            self.typ = Some(EnumToken::LiteralTokenType);
1204            self.field = TokenValueField::Value;
1205        }
1206        if has_value {
1207            if canonical != -1 {
1208                self.value_kind = TokenValueKind::Canonical;
1209                self.value_start = canonical_start(canonical as u32) as usize;
1210                self.value_end = canonical_end(canonical as u32) as usize;
1211            } else {
1212                self.value_kind = if decode_segments { TokenValueKind::Escaped } else { TokenValueKind::Source };
1213                self.value_start = value_start;
1214                self.value_end = end;
1215            }
1216        }
1217        let pi = &mut self.parse_info;
1218        self.src_id = Some(pi.source.id);
1219        self.sta = Some(pi.position);
1220        self.end = Some(pi.current_position);
1221        self.bytes_in = Some(pi.current_position);
1222        pi.position = pi.current_position;
1223        self
1224    }
1225
1226    /// id of the string value of the current token in the arena. no string is created
1227    pub fn intern_value(&mut self, arena: &AstArena, source_index: i32) -> u32 {
1228        match self.value_kind {
1229            TokenValueKind::Canonical => arena.intern_canonical(self.value_start as u32, self.value_end as u32),
1230            TokenValueKind::Escaped => {
1231                let mut decoded = std::mem::take(&mut self.decoded);
1232                decode_escapes(&self.parse_info.codes, self.value_start, self.value_end, &mut decoded);
1233                let id = arena.intern_units(&decoded);
1234                self.decoded = decoded;
1235                id
1236            }
1237            TokenValueKind::Source => arena.intern_range(
1238                &self.parse_info.codes,
1239                self.value_start,
1240                self.value_end,
1241                if source_index < 0 { StringSource::Pool } else { source_index },
1242            ),
1243        }
1244    }
1245
1246    /// the string value of the current token (decoded)
1247    pub fn value_string(&mut self) -> String {
1248        match self.value_kind {
1249            TokenValueKind::Canonical => crate::parser::utils::canonical::canonical_slice(self.value_start as u32, self.value_end as u32),
1250            TokenValueKind::Escaped => {
1251                let mut decoded = std::mem::take(&mut self.decoded);
1252                decode_escapes(&self.parse_info.codes, self.value_start, self.value_end, &mut decoded);
1253                let s = String::from_utf16_lossy(&decoded);
1254                self.decoded = decoded;
1255                s
1256            }
1257            TokenValueKind::Source => self.parse_info.codes.slice(self.value_start, self.value_end).into_owned(),
1258        }
1259    }
1260
1261    /// content of the source being tokenized
1262    pub fn content(&self) -> Rc<str> {
1263        self.parse_info.source.content.borrow().clone()
1264    }
1265
1266    /// code units of the source being tokenized
1267    pub fn codes(&self) -> &CodeUnits {
1268        &self.parse_info.codes
1269    }
1270
1271    /// true if the text of the token being read equals the input, ignoring the case
1272    fn equals_ignore_case(&self, input: &str) -> bool {
1273        let pi = &self.parse_info;
1274        let position = pi.position - pi.offset;
1275        if pi.current_position - pi.position != input.len() {
1276            return false;
1277        }
1278        input.bytes().enumerate().all(|(i, b)| {
1279            let mut ca = pi.at(position + i);
1280            let mut cb = b as u32;
1281            if (65..=90).contains(&ca) {
1282                ca += 32;
1283            }
1284            if (65..=90).contains(&cb) {
1285                cb += 32;
1286            }
1287            ca == cb
1288        })
1289    }
1290
1291    fn matches(&self, input: &str) -> bool {
1292        let pi = &self.parse_info;
1293        let position = pi.current_position - pi.offset;
1294        input.bytes().enumerate().all(|(i, b)| pi.at(position + i) == b as u32)
1295    }
1296
1297    /// length of the escape sequence that follows the backslash at the current position
1298    fn escape_sequence_length(&self) -> usize {
1299        let pi = &self.parse_info;
1300        let position = pi.current_position - pi.offset;
1301        let limit = if pi.length.saturating_sub(position) < 7 { pi.length.saturating_sub(position) } else { 7 };
1302        let mut digits = 0;
1303        let mut length = 0;
1304        for i in 1..limit {
1305            let codepoint = pi.at(position + i);
1306            if codepoint == 0x20 {
1307                length += 1;
1308                break;
1309            }
1310            if !is_hex_digit(codepoint) {
1311                break;
1312            }
1313            digits += 1;
1314            length += 1;
1315        }
1316        if digits > 0 {
1317            length
1318        } else {
1319            0
1320        }
1321    }
1322
1323    /// move forward by count characters and record the new lines
1324    fn advance(&mut self, count: usize) {
1325        let pi = &self.parse_info;
1326        let position = pi.current_position - pi.offset;
1327        let remaining = pi.length.saturating_sub(position);
1328        let length = count.min(remaining);
1329        for i in 0..length {
1330            let codepoint = pi.at(position + i);
1331            if matches!(codepoint, 0xa | 0xb | 0xc | 0xd | 0x2028 | 0x2029) && (codepoint != 0xd || pi.at(position + i + 1) != 0xa) {
1332                pi.push_line_start(position + pi.offset + i);
1333            }
1334        }
1335        self.parse_info.current_position += length;
1336    }
1337
1338    /// move forward over characters that are not new lines
1339    #[inline]
1340    fn skip(&mut self, count: usize) {
1341        let pi = &mut self.parse_info;
1342        let remaining = pi.length.saturating_sub(pi.current_position - pi.offset);
1343        pi.current_position += count.min(remaining);
1344    }
1345
1346    fn skip_ident(&mut self, count: usize) {
1347        if self.ident_non_ascii {
1348            self.advance(count);
1349        } else {
1350            self.skip(count);
1351        }
1352    }
1353
1354    /// move forward by one character and return its code (EOF at the end of the stream)
1355    fn advance_code(&mut self) -> u32 {
1356        let pi = &self.parse_info;
1357        let position = pi.current_position - pi.offset;
1358        let codepoint = pi.at(position);
1359        if codepoint == EOF {
1360            return EOF;
1361        }
1362        if codepoint == 0xa
1363            || codepoint == 0xb
1364            || codepoint == 0xc
1365            || (codepoint == 0xd && pi.at(position + 1) != 0xa)
1366            || codepoint == 0x2028
1367            || codepoint == 0x2029
1368        {
1369            pi.push_line_start(position + pi.offset);
1370        }
1371        self.parse_info.current_position += 1;
1372        codepoint
1373    }
1374
1375    fn is_ident_token(&self) -> bool {
1376        let pi = &self.parse_info;
1377        let mut j = (pi.current_position - pi.offset) as isize;
1378        let mut i = (pi.position - pi.offset) as isize;
1379        j -= 1;
1380        let at = |i: isize| pi.at(i as usize);
1381        let mut codepoint = at(i);
1382        if codepoint == 0x2d {
1383            let next = at(i + 1);
1384            if next == EOF {
1385                return false;
1386            }
1387            if !is_ident_start(next) && next != 0x2d {
1388                return false;
1389            }
1390            codepoint = next;
1391            i += 1;
1392        }
1393        if codepoint != 0x2d && !is_ident_start(codepoint) {
1394            return false;
1395        }
1396        if codepoint == REVERSE_SOLIDUS {
1397            i += 1;
1398        }
1399        while i < j {
1400            i += 1;
1401            codepoint = at(i);
1402            if codepoint == REVERSE_SOLIDUS {
1403                i += 2;
1404                continue;
1405            }
1406            if codepoint != 0x2d && !is_ident_codepoint(codepoint) {
1407                return false;
1408            }
1409        }
1410        true
1411    }
1412
1413    fn starts_with(&self, input: &str) -> bool {
1414        let pi = &self.parse_info;
1415        input.bytes().enumerate().all(|(i, b)| pi.at(pi.position - pi.offset + i) == b as u32)
1416    }
1417
1418    fn is_url_token(&self) -> bool {
1419        let pi = &self.parse_info;
1420        let mut i = pi.position - pi.offset;
1421        loop {
1422            i += 1;
1423            if i >= pi.current_position {
1424                break;
1425            }
1426            let mut c = pi.at(i);
1427            if is_non_printable(c) || c == 0x27 || c == 0x22 || c == 0x28 || c == 0x29 {
1428                return false;
1429            }
1430            if c == REVERSE_SOLIDUS {
1431                i += 1;
1432                if i >= pi.current_position {
1433                    return false;
1434                }
1435                c = pi.at(i);
1436                if c == 0x6e || c == 0x72 || c == 0x66 {
1437                    return false;
1438                }
1439                continue;
1440            }
1441            if c == 0x20 || c == 0x09 {
1442                break;
1443            }
1444        }
1445        i == pi.current_position
1446    }
1447
1448    pub fn done(&self) -> bool {
1449        self.typ == Some(EnumToken::EOF)
1450    }
1451
1452    /// read the next token
1453    #[allow(clippy::should_implement_trait)]
1454    /// read the next token. when the input is a stream that is not read to its end, a token that ends near the end of
1455    /// the code units read so far may continue in the next chunk (an identifier, a number, a string, a comment, ...):
1456    /// the token is not returned, [`Tokenizer::waiting`] is true and a chunk must be appended before the next call
1457    pub fn next(&mut self) -> &mut Self {
1458        if self.stream.is_none() {
1459            return self.next_token();
1460        }
1461        let position = self.parse_info.position;
1462        let current_position = self.parse_info.current_position;
1463        let state = self.state;
1464        let line_count = self.parse_info.source.line_starts.borrow().line_starts.len();
1465        self.next_token();
1466        // the tokenizer reads at most a few code units after the end of a token: the token is complete when the
1467        // stream has more code units after it
1468        if self.parse_info.current_position + STREAM_LOOKAHEAD > self.parse_info.length {
1469            self.parse_info.position = position;
1470            self.parse_info.current_position = current_position;
1471            self.state = state;
1472            self.parse_info.source.line_starts.borrow_mut().line_starts.truncate(line_count);
1473            self.typ = None;
1474            self.waiting = true;
1475        }
1476        self
1477    }
1478
1479    /// read the next token from the code units of the input
1480    fn next_token(&mut self) -> &mut Self {
1481        let end_position = self.parse_info.length.saturating_sub(1);
1482        loop {
1483            let mut char_code = self.parse_info.cur();
1484            if char_code == EOF {
1485                break;
1486            }
1487            if self.state == Some(EnumToken::UrlFunctionTokenDefType) {
1488                self.state = None;
1489                return self.consume_url_token(end_position);
1490            }
1491            if self.parse_info.position == self.parse_info.current_position {
1492                if char_code == 0x55 || char_code == 0x75 {
1493                    let count = self.consume_unicode_range_token();
1494                    if count > 0 {
1495                        self.skip(count);
1496                        return self.make_token(Some(EnumToken::UniCodeRange), None, false);
1497                    }
1498                }
1499                if char_code == MINUS || char_code == PLUS || char_code == DOT || is_digit(char_code) {
1500                    let count = self.consume_numeric_token();
1501                    if count > 0 {
1502                        self.advance(count);
1503                        let hint = self.hint.unwrap_or(EnumToken::NumberTokenType);
1504                        let slice = self.slice;
1505                        return self.make_token(Some(hint), slice, false);
1506                    }
1507                }
1508                if is_ident_start(char_code) || char_code == MINUS {
1509                    let count = self.consume_ident_token();
1510                    if count > 0 {
1511                        self.skip_ident(count);
1512                        char_code = self.parse_info.cur();
1513                        if char_code != LEFT_PARENTHESIS {
1514                            let typ = if self.starts_with("--") { EnumToken::DashedIdenTokenType } else { EnumToken::IdenTokenType };
1515                            return self.make_token(Some(typ), None, false);
1516                        }
1517                    }
1518                }
1519                if char_code == AT {
1520                    self.skip(1);
1521                    char_code = self.parse_info.cur();
1522                    if char_code == MINUS || is_ident_start(self.parse_info.cur()) {
1523                        self.parse_info.position = self.parse_info.current_position;
1524                        let count = self.consume_ident_token();
1525                        if count > 0 {
1526                            self.skip_ident(count);
1527                            return self.make_token(Some(EnumToken::AtRuleTokenType), None, false);
1528                        }
1529                    }
1530                }
1531                if char_code == HASH {
1532                    let count = self.consume_color();
1533                    if count > 0 {
1534                        self.skip(count);
1535                        return self.make_token(Some(EnumToken::ColorTokenType), None, false);
1536                    }
1537                    self.skip(1);
1538                    let count = self.consume_ident_token();
1539                    if count > 0 {
1540                        self.skip_ident(count);
1541                        return self.make_token(Some(EnumToken::HashTokenType), None, false);
1542                    }
1543                }
1544            }
1545            let pending = self.parse_info.position < self.parse_info.current_position;
1546            match char_code {
1547                EQUALS => {
1548                    self.skip(1);
1549                    return self.make_token(Some(EnumToken::DelimTokenType), None, false);
1550                }
1551                PLUS => {
1552                    self.skip(1);
1553                    return self.make_token(Some(EnumToken::Plus), None, false);
1554                }
1555                MINUS => {
1556                    if self.parse_info.position == self.parse_info.current_position {
1557                        let pi = &self.parse_info;
1558                        let next = pi.at(pi.current_position - pi.offset + 1);
1559                        if is_white_space(next) {
1560                            self.skip(1);
1561                            return self.make_token(Some(EnumToken::Sub), None, false);
1562                        }
1563                    }
1564                    self.skip(1);
1565                }
1566                LEFT_BRACE => {
1567                    if pending {
1568                        return self.make_token(None, None, false);
1569                    }
1570                    self.skip(1);
1571                    return self.make_token(Some(EnumToken::BlockStartTokenType), None, false);
1572                }
1573                RIGHT_BRACE => {
1574                    if pending {
1575                        return self.make_token(None, None, false);
1576                    }
1577                    self.skip(1);
1578                    return self.make_token(Some(EnumToken::BlockEndTokenType), None, false);
1579                }
1580                LEFT_PARENTHESIS => {
1581                    if pending && self.is_ident_token() {
1582                        let pi = &self.parse_info;
1583                        let hint = if self.starts_with("--") {
1584                            EnumToken::CustomFunctionTokenDefType
1585                        } else {
1586                            get_symbol_hint(pi, pi.position - pi.offset, pi.current_position - pi.offset + 1)
1587                                .unwrap_or(EnumToken::FunctionTokenDefType)
1588                        };
1589                        self.make_token(Some(hint), None, false);
1590                        self.skip(1);
1591                        self.parse_info.position = self.parse_info.current_position;
1592                        if hint == EnumToken::UrlFunctionTokenDefType {
1593                            self.state = Some(hint);
1594                        }
1595                        return self;
1596                    }
1597                    self.skip(1);
1598                    return self.make_token(Some(EnumToken::StartParensTokenType), None, false);
1599                }
1600                RIGHT_PARENTHESIS => {
1601                    if pending {
1602                        return self.make_token(None, None, false);
1603                    }
1604                    self.skip(1);
1605                    return self.make_token(Some(EnumToken::EndParensTokenType), None, false);
1606                }
1607                LEFT_BRACKETS => {
1608                    self.skip(1);
1609                    return self.make_token(Some(EnumToken::AttrStartTokenType), None, false);
1610                }
1611                RIGHT_BRACKETS => {
1612                    self.skip(1);
1613                    return self.make_token(Some(EnumToken::AttrEndTokenType), None, false);
1614                }
1615                SEMICOLON => {
1616                    self.skip(1);
1617                    return self.make_token(Some(EnumToken::SemiColonTokenType), None, false);
1618                }
1619                COLON => {
1620                    self.skip(1);
1621                    if self.parse_info.cur() == COLON {
1622                        self.skip(1);
1623                        return self.make_token(Some(EnumToken::DoubleColonTokenType), None, false);
1624                    }
1625                    return self.make_token(Some(EnumToken::ColonTokenType), None, false);
1626                }
1627                0x9 | 0x20 | 0xa | 0xb | 0xc | 0xd | 0x2028 | 0x2029 => {
1628                    if pending {
1629                        return self.make_token(None, None, false);
1630                    }
1631                    self.advance_code();
1632                    let mut next = self.parse_info.cur();
1633                    while next == 0x20 || (0x9..=0xd).contains(&next) || next == 0x2028 || next == 0x2029 {
1634                        self.advance_code();
1635                        next = self.parse_info.cur();
1636                    }
1637                    return self.make_token(Some(EnumToken::WhitespaceTokenType), None, false);
1638                }
1639                COMMA => {
1640                    self.skip(1);
1641                    return self.make_token(Some(EnumToken::CommaTokenType), None, false);
1642                }
1643                DOLLAR => {
1644                    if self.matches("$=") {
1645                        self.skip(2);
1646                        return self.make_token(Some(EnumToken::EndMatchTokenType), None, false);
1647                    }
1648                    self.skip(1);
1649                }
1650                TILDA => {
1651                    if self.matches("~=") {
1652                        self.skip(2);
1653                        return self.make_token(Some(EnumToken::IncludeMatchTokenType), None, false);
1654                    }
1655                    self.skip(1);
1656                    return self.make_token(Some(EnumToken::Tilda), None, false);
1657                }
1658                CARET => {
1659                    if self.matches("^=") {
1660                        self.skip(2);
1661                        return self.make_token(Some(EnumToken::StartMatchTokenType), None, false);
1662                    }
1663                    self.skip(1);
1664                }
1665                STAR => {
1666                    if self.matches("*=") {
1667                        self.skip(2);
1668                        return self.make_token(Some(EnumToken::ContainMatchTokenType), None, false);
1669                    }
1670                    self.skip(1);
1671                    return self.make_token(Some(EnumToken::Star), None, false);
1672                }
1673                AMPERSAND => {
1674                    if pending {
1675                        return self.make_token(None, None, false);
1676                    }
1677                    self.skip(1);
1678                    return self.make_token(Some(EnumToken::NestingSelectorTokenType), None, false);
1679                }
1680                PIPE => {
1681                    if self.matches("||") {
1682                        self.skip(2);
1683                        return self.make_token(Some(EnumToken::ColumnCombinatorTokenType), None, false);
1684                    } else if self.matches("|=") {
1685                        self.skip(2);
1686                        return self.make_token(Some(EnumToken::DashMatchTokenType), None, false);
1687                    }
1688                    self.skip(1);
1689                    return self.make_token(Some(EnumToken::PipeTokenType), None, false);
1690                }
1691                EXCLAMATION => {
1692                    if pending {
1693                        return self.make_token(None, None, false);
1694                    }
1695                    if self.matches("!important") {
1696                        self.skip(10);
1697                        return self.make_token(Some(EnumToken::ImportantTokenType), None, false);
1698                    }
1699                    self.skip(1);
1700                }
1701                SLASH => {
1702                    if !self.matches("/*") {
1703                        self.skip(1);
1704                        let pi = &self.parse_info;
1705                        let hint = get_symbol_hint(pi, pi.position - pi.offset, pi.current_position - pi.offset);
1706                        return self.make_token(hint, None, false);
1707                    }
1708                    self.skip(2);
1709                    loop {
1710                        let c = self.advance_code();
1711                        if c == EOF {
1712                            break;
1713                        }
1714                        if c == STAR && self.matches("/") {
1715                            self.skip(1);
1716                            return self.make_token(Some(EnumToken::CommentTokenType), None, false);
1717                        }
1718                    }
1719                    if self.parse_info.position < self.parse_info.current_position {
1720                        return self.make_token(Some(EnumToken::BadCommentTokenType), None, false);
1721                    }
1722                }
1723                GREATERTHAN => {
1724                    if self.matches(">=") {
1725                        self.skip(2);
1726                        return self.make_token(Some(EnumToken::GteTokenType), None, false);
1727                    }
1728                    self.skip(1);
1729                    return self.make_token(Some(EnumToken::GtTokenType), None, false);
1730                }
1731                LOWERTHAN => {
1732                    if pending {
1733                        return self.make_token(None, None, false);
1734                    }
1735                    if self.matches("<=") {
1736                        self.skip(2);
1737                        return self.make_token(Some(EnumToken::LteTokenType), None, false);
1738                    }
1739                    self.skip(1);
1740                    if self.matches("!--") {
1741                        self.skip(3);
1742                        loop {
1743                            let c = self.advance_code();
1744                            if c == EOF {
1745                                break;
1746                            }
1747                            if c == MINUS && self.matches("->") {
1748                                break;
1749                            }
1750                        }
1751                        if self.parse_info.current_position >= end_position {
1752                            return self.make_token(Some(EnumToken::BadCdoTokenType), None, false);
1753                        }
1754                        self.skip(2);
1755                        return self.make_token(Some(EnumToken::CDOCOMMTokenType), None, false);
1756                    }
1757                    let pi = &self.parse_info;
1758                    let start_position = pi.position - pi.offset;
1759                    let mut offset = 1;
1760                    let mut c = pi.at(start_position + offset);
1761                    if is_letter(c) {
1762                        offset += 1;
1763                        c = pi.at(offset + start_position);
1764                        while offset < end_position && (c == MINUS || is_letter(c)) {
1765                            offset += 1;
1766                            c = pi.at(offset + start_position);
1767                        }
1768                        if offset > 1 && c == GREATERTHAN {
1769                            self.skip(offset);
1770                            return self.make_token(Some(EnumToken::CssTypeTokenType), None, false);
1771                        }
1772                    }
1773                }
1774                HASH => {
1775                    if pending {
1776                        return self.make_token(None, None, false);
1777                    }
1778                    self.skip(1);
1779                }
1780                REVERSE_SOLIDUS => {
1781                    self.advance(1);
1782                    if self.parse_info.cur() == EOF && self.parse_info.position < self.parse_info.current_position {
1783                        return self.make_token(None, None, false);
1784                    }
1785                    self.advance(1);
1786                }
1787                SINGLE_QUOTE | DOUBLE_QUOTE => {
1788                    if pending {
1789                        return self.make_token(None, None, false);
1790                    }
1791                    return self.consume_string();
1792                }
1793                DOT => {
1794                    let pi = &self.parse_info;
1795                    let codepoint = pi.at(pi.current_position - pi.offset + 1);
1796                    if is_ident_start(codepoint) || codepoint == MINUS {
1797                        self.skip(1);
1798                        let count = self.consume_ident_token();
1799                        if count > 0 {
1800                            self.skip_ident(count);
1801                            return self.make_token(Some(EnumToken::ClassSelectorTokenType), None, false);
1802                        }
1803                    }
1804                    self.advance_code();
1805                }
1806                _ => self.skip(1),
1807            }
1808        }
1809        if self.parse_info.position < self.parse_info.current_position {
1810            return self.make_token(None, None, false);
1811        }
1812        self.make_token(Some(EnumToken::EOFTokenType), None, false)
1813    }
1814}
1815
1816/// token type of a symbol, unit or function name
1817fn get_symbol_hint(parse_info: &ParseInfo, start: usize, end: usize) -> Option<u8> {
1818    let end = end.min(parse_info.length);
1819    if end <= start {
1820        return None;
1821    }
1822    tables().symbols.get(&parse_info.codes, start, end).copied()
1823}
1824
1825/// canonical spelling of a unit or a function name of the given token type, -1 when the name is not known
1826fn find_item(typ: u8, parse_info: &ParseInfo, start: usize, end: usize) -> i64 {
1827    if end <= start {
1828        return -1;
1829    }
1830    tables()
1831        .items
1832        .get(&parse_info.codes, start, end)
1833        .and_then(|items| items.iter().find(|(t, _)| *t == typ))
1834        .map_or(-1, |(_, c)| *c as i64)
1835}
1836
1837#[allow(dead_code)]
1838static _UNUSED: OnceLock<()> = OnceLock::new();
1839
1840#[cfg(test)]
1841mod tests {
1842    use super::*;
1843
1844    /// the numbers read by `parse_short_number` have the value read by `parse_long_number`
1845    #[test]
1846    fn short_numbers() {
1847        let mut inputs: Vec<String> = [
1848            "0", "-0", "+0", "1", "-1", "+1", "1.", "-1.", ".5", "-.5", "+.5", "0.1", "0.2", "0.3", "1.5", "12.345",
1849            "123456789012345", "12345678901234.5", "0.000000000000001", "9.99999999999999", "33.333333333333",
1850            "1e3", "1.e3", "1.5e-3", "1em", "10px", "1.2.3", ".", "-", "+-1", "007", "0.30000000000000004",
1851        ]
1852        .iter()
1853        .map(|s| s.to_string())
1854        .collect();
1855        // pseudo random numbers
1856        let mut seed: u64 = 0x2545f4914f6cdd1d;
1857        for _ in 0..20000 {
1858            seed ^= seed << 13;
1859            seed ^= seed >> 7;
1860            seed ^= seed << 17;
1861            let digits = (seed % 15 + 1) as usize;
1862            let mantissa = format!("{:015}", seed % 1_000_000_000_000_000);
1863            let mantissa = &mantissa[15 - digits..];
1864            let dot = (seed >> 20) as usize % (digits + 1);
1865            let sign = ["", "-", "+"][(seed >> 40) as usize % 3];
1866            inputs.push(format!("{}{}.{}", sign, &mantissa[..dot], &mantissa[dot..]));
1867            inputs.push(format!("{}{}", sign, mantissa));
1868        }
1869        for input in inputs {
1870            let codes = CodeUnits::Bytes(Rc::from(input.as_bytes()));
1871            let long = parse_long_number(&codes, 0, input.len());
1872            if let Some(short) = parse_short_number(&codes, 0, input.len()) {
1873                assert!(short.to_bits() == long.to_bits(), "{}: {} != {}", input, short, long);
1874            }
1875        }
1876    }
1877}