Skip to main content

fallow_extract/
nesting.rs

1//! Nesting-depth guard that runs before the Oxc parser sees a source.
2//!
3//! The Oxc parser and the AST visitors recurse once per nesting level and
4//! have no depth limit (oxc-project/oxc#21953, oxc-project/oxc#24375). A
5//! file with a few thousand nested brackets overflows the stack, and because
6//! a stack overflow aborts the process, one such file kills the whole run.
7//! Extraction therefore measures the bracket nesting first and does not parse
8//! a file past [`MAX_NESTING_DEPTH`].
9//!
10//! The scan is a lexer approximation. Brackets in strings, comments and
11//! template text do not count. A string or regex literal that does not end on
12//! its line is not a literal, so the scan reads it again as code: a stray
13//! quote in JSX text or a division read as a regex cannot hide brackets. A
14//! regex body keeps its unclosed openers open, so a division that looks like
15//! a regex cannot hide brackets either. It does not need to be
16//! exact, because real code stays far below the cap. Nesting without brackets
17//! (TypeScript generics, JSX elements, long member or call chains) is not
18//! capped. [`parse_bounded`] runs such a parse on a stack that is large
19//! enough for it.
20//!
21//! The same scan also counts the `<` tokens that the TypeScript parser can
22//! try as nested type-argument lists, because each such level multiplies the
23//! parse time. [`MAX_TYPE_ARGUMENT_NESTING`] caps that count.
24
25use std::path::Path;
26
27use fallow_types::discover::FileId;
28use fallow_types::extract::ModuleInfo;
29
30use crate::visitor::ModuleInfoExtractor;
31
32/// Nesting depth of possible type-argument lists past which a file is not
33/// parsed.
34///
35/// In TypeScript, the parser reads `a<` in an expression first as the start
36/// of a type-argument list, and reads it again as a comparison when that
37/// fails. A type can hold an expression (a computed key in `{ [key]: T }`),
38/// so each `<` nested in such a list multiplies the work, and a few hundred
39/// bytes such as `t<{[t<{[t<{[...` keep the parser busy for minutes. The scan
40/// counts a `<` that is still open where the next one opens behind a deeper
41/// `(` or `[`. One level can cost up to four times the level inside it, so
42/// the cap keeps the worst case near a million steps. Real code, minified
43/// bundles and generated declaration files included, stays below this cap.
44const MAX_TYPE_ARGUMENT_NESTING: u32 = 10;
45
46/// Bracket nesting depth past which a file is not parsed.
47///
48/// A release build on a 16 MiB worker stack overflows at about 6000 levels for
49/// the most expensive shape (nested object literals), and at about half that
50/// on the 8 MiB main thread that parses small projects. Real code stays far
51/// below this cap.
52pub const MAX_NESTING_DEPTH: u32 = 1024;
53
54/// Nesting depth of CSS color functions past which lightningcss does not parse
55/// a stylesheet.
56///
57/// When the content of `light-dark(`, `rgb(` or `hsl(` is not a valid color,
58/// lightningcss parses it a second time as a plain function. Each level of
59/// such nesting doubles the parse time. Real stylesheets nest a few color
60/// functions at most, for example `color-mix(in srgb, light-dark(rgb(...)))`.
61pub const MAX_COLOR_FUNCTION_DEPTH: usize = 8;
62
63/// The CSS functions that lightningcss tries to parse as a color first.
64const COLOR_FUNCTIONS: &[&[u8]] = &[
65    b"rgb",
66    b"rgba",
67    b"hsl",
68    b"hsla",
69    b"hwb",
70    b"lab",
71    b"lch",
72    b"oklab",
73    b"oklch",
74    b"color",
75    b"color-mix",
76    b"light-dark",
77    b"alpha",
78];
79
80/// The module of a file whose bracket nesting exceeds [`MAX_NESTING_DEPTH`].
81/// The module is a failed parse with no facts, so the file shows up as
82/// degraded instead of aborting the run.
83pub fn too_deep_module(file_id: FileId, source: &str, content_hash: u64) -> ModuleInfo {
84    let mut info = ModuleInfoExtractor::new().into_module_info(
85        file_id,
86        content_hash,
87        crate::suppress::ParsedSuppressions::default(),
88    );
89    info.parse_error_count = 1;
90    info.parse_panicked = true;
91    info.parse_nesting_too_deep = true;
92    info.line_offsets = fallow_types::extract::compute_line_offsets(source);
93    info
94}
95
96/// Returns `true` when the bracket nesting of `source` exceeds
97/// [`MAX_NESTING_DEPTH`] or its type-argument nesting exceeds
98/// [`MAX_TYPE_ARGUMENT_NESTING`].
99#[cfg(test)]
100#[must_use]
101fn exceeds_nesting_limit(source: &str) -> bool {
102    scan_nesting(source, Dialect::Script).exceeds_limits()
103}
104
105/// The lexical rules of the scanned source.
106#[derive(Clone, Copy, PartialEq, Eq)]
107enum Dialect {
108    /// JavaScript, TypeScript and the component formats that embed them.
109    Script,
110    /// CSS, Sass and Less. A stylesheet has no regex or template literals, and
111    /// `//` is not a comment in `url(//host/a.png)`, so only strings and
112    /// `/* */` comments are skipped. A Sass `//` comment is scanned as code,
113    /// which can only over-count.
114    Style,
115}
116
117/// Run `parse`, which parses `source` with Oxc and walks the result, without
118/// a stack overflow. Returns `None` when the bracket nesting of `source`
119/// exceeds [`MAX_NESTING_DEPTH`], its type-argument nesting exceeds
120/// `MAX_TYPE_ARGUMENT_NESTING` (10), or the stack it needs exceeds the cap in
121/// `stack.rs`, so the caller treats the file as a failed parse.
122///
123/// Every parse of user source goes through this function. It sizes the stack
124/// from the source length and the bracket depth, and it moves the work to a
125/// thread with that stack when the current thread has too little left. A
126/// parse of a fragment inside `parse` runs on the same stack and needs no
127/// second call.
128pub fn parse_bounded<R: Send>(source: &str, parse: impl FnOnce() -> R + Send) -> Option<R> {
129    parse_bounded_as(source, Dialect::Script, parse)
130}
131
132/// [`parse_bounded`] for a lightningcss parse of stylesheet source. The
133/// nesting scan uses stylesheet rules. Returns `None` also when the token
134/// walk in `crate::style_tokens` finds the stylesheet unsafe to parse, see
135/// `style_parse_is_safe`.
136pub fn parse_style_bounded<R: Send>(source: &str, parse: impl FnOnce() -> R + Send) -> Option<R> {
137    let scan = scan_depth(source, MAX_NESTING_DEPTH, Dialect::Style);
138    if scan.max_colors > MAX_COLOR_FUNCTION_DEPTH {
139        return None;
140    }
141    run_bounded(source, scan.max_depth, || {
142        crate::style_tokens::style_parse_is_safe(source).then(parse)
143    })
144    .flatten()
145}
146
147/// [`parse_bounded`] for the file at `path`. A CSS, Sass or Less file is
148/// scanned with stylesheet rules.
149pub fn parse_file_bounded<R: Send>(
150    path: &Path,
151    source: &str,
152    parse: impl FnOnce() -> R + Send,
153) -> Option<R> {
154    let dialect = if crate::css::is_css_file(path) {
155        Dialect::Style
156    } else {
157        Dialect::Script
158    };
159    parse_bounded_as(source, dialect, parse)
160}
161
162fn parse_bounded_as<R: Send>(
163    source: &str,
164    dialect: Dialect,
165    parse: impl FnOnce() -> R + Send,
166) -> Option<R> {
167    let nesting = scan_nesting(source, dialect);
168    if nesting.exceeds_limits() {
169        return None;
170    }
171    run_bounded(source, nesting.brackets, parse)
172}
173
174fn run_bounded<R: Send>(source: &str, depth: u32, parse: impl FnOnce() -> R + Send) -> Option<R> {
175    if depth > MAX_NESTING_DEPTH {
176        return None;
177    }
178    let need = crate::stack::stack_need(source.len(), depth as usize)?;
179    Some(crate::stack::run_with_stack(need, parse))
180}
181
182/// Parse `source` with Oxc and call `walk` with the result, through
183/// [`parse_bounded`]. Returns `T::default()` when the bracket nesting exceeds
184/// [`MAX_NESTING_DEPTH`].
185pub fn parse_bounded_or_default<T: Send + Default>(
186    source: &str,
187    source_type: oxc_span::SourceType,
188    walk: impl FnOnce(&oxc_parser::ParserReturn<'_>) -> T + Send,
189) -> T {
190    parse_bounded(source, || {
191        let allocator = oxc_allocator::Allocator::default();
192        let parsed = oxc_parser::Parser::new(&allocator, source, source_type).parse();
193        walk(&parsed)
194    })
195    .unwrap_or_default()
196}
197
198/// The nesting that the parse of a source has to handle.
199struct Nesting {
200    /// Maximum bracket nesting depth.
201    brackets: u32,
202    /// Maximum nesting of `<` that can open a type-argument list.
203    type_arguments: u32,
204}
205
206impl Nesting {
207    const fn exceeds_limits(&self) -> bool {
208        self.brackets > MAX_NESTING_DEPTH || self.type_arguments > MAX_TYPE_ARGUMENT_NESTING
209    }
210}
211
212/// Measures the nesting of `source`. The scan stops as soon as a value passes
213/// its limit, so each value is at most its limit + 1.
214fn scan_nesting(source: &str, dialect: Dialect) -> Nesting {
215    let mut scanner = Scanner::new(source, MAX_NESTING_DEPTH, dialect);
216    scanner.scan();
217    Nesting {
218        brackets: scanner.max_depth,
219        type_arguments: scanner.max_type_arguments,
220    }
221}
222
223/// Maximum bracket nesting depth of `source`. The scan stops as soon as the
224/// depth passes `limit`, so the result is at most `limit + 1`.
225#[cfg(test)]
226fn max_depth(source: &str, limit: u32, dialect: Dialect) -> u32 {
227    scan_depth(source, limit, dialect).max_depth
228}
229
230fn scan_depth(source: &str, limit: u32, dialect: Dialect) -> Scanner<'_> {
231    let mut scanner = Scanner::new(source, limit, dialect);
232    scanner.scan();
233    scanner
234}
235
236struct Scanner<'a> {
237    bytes: &'a [u8],
238    pos: usize,
239    depth: u32,
240    max_depth: u32,
241    limit: u32,
242    dialect: Dialect,
243    /// Depth of each open `${` substitution, innermost last. The `}` that
244    /// brings the depth back to this value resumes the template text.
245    templates: Vec<u32>,
246    /// Whether a `/` at this point starts a regex literal instead of a
247    /// division, judged from the previous significant byte.
248    regex_allowed: bool,
249    /// Each open `<` that can start a type-argument list, outermost first.
250    /// Each entry is deeper than the one before it.
251    type_arguments: Vec<TypeArguments>,
252    max_type_arguments: u32,
253    /// Depth of each open `(` and `[`, innermost last. Only these brackets
254    /// can hold an expression inside a type.
255    expression_brackets: Vec<u32>,
256    /// Whether this scanner reads the body of a guessed regex as code, see
257    /// [`Scanner::count_regex_type_arguments`].
258    regex_body: bool,
259    /// Depth of each open stylesheet color function, innermost last.
260    colors: Vec<u32>,
261    /// Maximum number of color functions open at one time.
262    max_colors: usize,
263    /// The closing byte of each open stylesheet block, innermost last. In CSS
264    /// only the matching byte ends a block, so a `}` inside an open `(` is a
265    /// plain token.
266    style_closers: Vec<u8>,
267}
268
269/// An open `<` that can start a type-argument list.
270#[derive(Clone, Copy)]
271struct TypeArguments {
272    /// Bracket depth of the `<`.
273    depth: u32,
274    /// How many open lists, this one included, nest behind a `(` or `[`.
275    level: u32,
276}
277
278impl<'a> Scanner<'a> {
279    fn new(source: &'a str, limit: u32, dialect: Dialect) -> Self {
280        Scanner {
281            bytes: source.as_bytes(),
282            pos: 0,
283            depth: 0,
284            max_depth: 0,
285            limit,
286            dialect,
287            templates: Vec::new(),
288            regex_allowed: true,
289            type_arguments: Vec::new(),
290            max_type_arguments: 0,
291            expression_brackets: Vec::new(),
292            regex_body: false,
293            colors: Vec::new(),
294            max_colors: 0,
295            style_closers: Vec::new(),
296        }
297    }
298}
299
300impl Scanner<'_> {
301    fn scan(&mut self) {
302        while let Some(&byte) = self.bytes.get(self.pos) {
303            if self.passed_limit() {
304                return;
305            }
306            self.pos += 1;
307            match byte {
308                b'\\' | b'(' | b'/'
309                    if self.dialect == Dialect::Style && self.scan_style_byte(byte) => {}
310                b'(' | b'[' | b'{' => self.open_bracket(byte),
311                b')' | b']' | b'}'
312                    if self.dialect == Dialect::Style && !self.close_style_block(byte) => {}
313                b'}' if self.templates.last() == Some(&self.depth) => {
314                    self.templates.pop();
315                    self.depth -= 1;
316                    self.close_type_arguments_above_depth();
317                    self.skip_template_text();
318                }
319                b')' | b']' | b'}' => {
320                    self.depth = self.depth.saturating_sub(1);
321                    self.close_type_arguments_above_depth();
322                    self.regex_allowed = byte == b'}';
323                    self.close_color_functions();
324                }
325                b'<' | b'>' | b';' | b'=' | b'&' | b'|' | b'?' | b'`'
326                    if self.dialect == Dialect::Script =>
327                {
328                    self.scan_script_byte(byte);
329                }
330                b'\'' | b'"' => {
331                    self.skip_string(byte);
332                    self.regex_allowed = false;
333                }
334                b'/' => self.skip_slash(),
335                b' ' | b'\t' | b'\n' | b'\r' => {}
336                _ => self.regex_allowed = starts_expression(byte),
337            }
338        }
339    }
340
341    fn open(&mut self) {
342        self.depth += 1;
343        self.max_depth = self.max_depth.max(self.depth);
344    }
345
346    /// Whether a nesting value passed its limit, so the scan can stop.
347    const fn passed_limit(&self) -> bool {
348        self.max_depth > self.limit || self.max_type_arguments > MAX_TYPE_ARGUMENT_NESTING
349    }
350
351    /// Opens a bracket. A `(` or `[` can hold an expression inside a type.
352    fn open_bracket(&mut self, byte: u8) {
353        self.open();
354        if byte != b'{' {
355            self.expression_brackets.push(self.depth);
356        }
357        if self.dialect == Dialect::Style {
358            self.style_closers.push(match byte {
359                b'(' => b')',
360                b'[' => b']',
361                _ => b'}',
362            });
363        }
364        self.regex_allowed = true;
365    }
366
367    /// Ends the innermost stylesheet block when `closer` matches it. Returns
368    /// false for a closing byte that CSS reads as a plain token.
369    fn close_style_block(&mut self, closer: u8) -> bool {
370        if self.style_closers.last() != Some(&closer) {
371            return false;
372        }
373        self.style_closers.pop();
374        true
375    }
376
377    /// Handles the script tokens that stylesheets do not have: a template
378    /// literal and the tokens that open or end a type-argument list.
379    fn scan_script_byte(&mut self, byte: u8) {
380        match byte {
381            b'`' => self.skip_template_text(),
382            b'<' => {
383                self.open_type_arguments();
384                self.regex_allowed = true;
385            }
386            _ => {
387                self.end_type_arguments(byte);
388                self.regex_allowed = true;
389            }
390        }
391    }
392
393    /// Records the `<` at `pos - 1` as a possible type-argument list. A `<`
394    /// at the depth of the last open one replaces it. A `<` in a deeper
395    /// bracket nests one level deeper only behind a `(` or `[` opened after
396    /// the enclosing `<`: a type such as `A<{ b: C<D> }>` holds no
397    /// expression, so the parser does not retry it. `<=` and `<<=` cannot
398    /// open a list.
399    fn open_type_arguments(&mut self) {
400        if self.bytes.get(self.pos) == Some(&b'<') {
401            self.pos += 1;
402        }
403        if self.bytes.get(self.pos) == Some(&b'=') {
404            return;
405        }
406        // A sibling `<` at the same depth keeps the level of the list that it
407        // replaces. The levels match for code, and a list carried out of a
408        // regex body keeps its nesting.
409        let replaced = if self
410            .type_arguments
411            .last()
412            .is_some_and(|open| open.depth == self.depth)
413        {
414            self.type_arguments.pop().map_or(0, |open| open.level)
415        } else {
416            0
417        };
418        let level = self
419            .type_arguments
420            .last()
421            .map_or(1, |outer| {
422                let behind_expression = self
423                    .expression_brackets
424                    .last()
425                    .is_some_and(|&bracket| bracket > outer.depth);
426                outer.level + u32::from(behind_expression)
427            })
428            .max(replaced);
429        self.type_arguments.push(TypeArguments {
430            depth: self.depth,
431            level,
432        });
433        self.max_type_arguments = self.max_type_arguments.max(level);
434    }
435
436    /// Ends the open `<` at the current depth when the `byte` at `pos - 1`
437    /// closes a type-argument list (`>`) or cannot appear in one (`;`, `=`,
438    /// `&&`, `||`, `??`). The parser stops its attempt at such a token, so a
439    /// later `<` is not nested in it. The arrow `=>` is valid in a type and
440    /// ends nothing, and a single `&`, `|` or `?` is valid in a type too.
441    fn end_type_arguments(&mut self, byte: u8) {
442        let next = self.bytes.get(self.pos).copied();
443        let ends = match byte {
444            b'>' => self.pos < 2 || self.bytes[self.pos - 2] != b'=',
445            b'=' => next != Some(b'>'),
446            b'&' | b'|' | b'?' => next == Some(byte),
447            _ => true,
448        };
449        if matches!(byte, b'&' | b'|' | b'?') && ends {
450            self.pos += 1;
451        }
452        if ends
453            && self
454                .type_arguments
455                .last()
456                .is_some_and(|open| open.depth == self.depth)
457        {
458            self.type_arguments.pop();
459        }
460    }
461
462    /// A closing bracket ends every `<` and every bracket opened inside it.
463    fn close_type_arguments_above_depth(&mut self) {
464        while self
465            .type_arguments
466            .last()
467            .is_some_and(|open| open.depth > self.depth)
468        {
469            self.type_arguments.pop();
470        }
471        while self
472            .expression_brackets
473            .last()
474            .is_some_and(|&bracket| bracket > self.depth)
475        {
476            self.expression_brackets.pop();
477        }
478    }
479
480    /// Handles the stylesheet tokens that differ from script: an escape, a
481    /// `/* */` comment, an unquoted `url(` body and a color function. Returns
482    /// false for a `(` that opens a plain bracket.
483    fn scan_style_byte(&mut self, byte: u8) -> bool {
484        match byte {
485            b'\\' => self.skip_escape(),
486            b'/' => self.skip_block_comment(),
487            _ if self.at_unquoted_url() => self.skip_unquoted_url(),
488            _ if self.at_color_function() => {
489                self.open();
490                self.style_closers.push(b')');
491                self.colors.push(self.depth);
492                self.max_colors = self.max_colors.max(self.colors.len());
493            }
494            _ => return false,
495        }
496        true
497    }
498
499    /// Ends the color functions that a closing bracket closed.
500    fn close_color_functions(&mut self) {
501        while self.colors.last().is_some_and(|open| *open > self.depth) {
502            self.colors.pop();
503        }
504    }
505
506    /// Skips a comment, a regex literal, or a division operator.
507    fn skip_slash(&mut self) {
508        match self.bytes.get(self.pos) {
509            Some(b'/') => {
510                while self.pos < self.bytes.len() && !self.at_line_terminator() {
511                    self.pos += 1;
512                }
513            }
514            Some(b'*') => self.skip_block_comment(),
515            _ if self.may_start_regex() && self.skip_regex() => {
516                self.regex_allowed = false;
517            }
518            _ => self.regex_allowed = true,
519        }
520    }
521
522    /// Whether the `(` at `pos - 1` opens an unquoted CSS `url(`, whose body is
523    /// raw text: quotes, `/*` and brackets in it are not tokens.
524    fn at_unquoted_url(&self) -> bool {
525        let open = self.pos - 1;
526        let Some(name) = open.checked_sub(3).map(|start| &self.bytes[start..open]) else {
527            return false;
528        };
529        // A name byte or an escape before `url` makes a longer name, such as
530        // `a\url(` or `\61 url(`, which is a plain function.
531        let starts_word = open.checked_sub(4).is_none_or(|before| {
532            let byte = self.bytes[before];
533            !is_css_name_byte(byte) && byte != b'\\' && self.escape_whitespace_len(before) == 0
534        });
535        let body = self.bytes[self.pos..].trim_ascii_start();
536        name.eq_ignore_ascii_case(b"url")
537            && starts_word
538            && !matches!(body.first(), Some(b'\'' | b'"'))
539    }
540
541    /// Whether the `(` at `pos - 1` opens one of the [`COLOR_FUNCTIONS`]. A
542    /// name with a CSS escape such as `r\67 b(` can spell any function, so it
543    /// counts as a color function.
544    fn at_color_function(&self) -> bool {
545        let open = self.pos - 1;
546        let mut start = open;
547        loop {
548            while start > 0 && is_css_name_byte_or_escape(self.bytes[start - 1]) {
549                start -= 1;
550            }
551            // The whitespace after a hex escape belongs to the name.
552            match start
553                .checked_sub(1)
554                .map(|before| self.escape_whitespace_len(before))
555            {
556                Some(len) if len > 0 => start -= len,
557                _ => break,
558            }
559        }
560        let name = &self.bytes[start..open];
561        name.contains(&b'\\')
562            || COLOR_FUNCTIONS
563                .iter()
564                .any(|color| name.eq_ignore_ascii_case(color))
565    }
566
567    /// The length of the whitespace that ends at `last` when it ends a hex
568    /// escape such as `\67 `, else 0. CSS reads `\r\n` as one whitespace, so
569    /// it has length 2.
570    fn escape_whitespace_len(&self, last: usize) -> usize {
571        match self.bytes[last] {
572            b'\n'
573                if last > 0 && self.bytes[last - 1] == b'\r' && self.ends_hex_escape(last - 1) =>
574            {
575                2
576            }
577            b' ' | b'\t' | b'\n' | b'\r' | 0x0C if self.ends_hex_escape(last) => 1,
578            _ => 0,
579        }
580    }
581
582    /// Whether a hex escape such as `\67` ends right before `end`.
583    fn ends_hex_escape(&self, end: usize) -> bool {
584        let digits = self.bytes[..end]
585            .iter()
586            .rev()
587            .take(MAX_HEX_ESCAPE_DIGITS + 1)
588            .take_while(|byte| byte.is_ascii_hexdigit())
589            .count();
590        (1..=MAX_HEX_ESCAPE_DIGITS).contains(&digits)
591            && end
592                .checked_sub(digits + 1)
593                .is_some_and(|slash| self.bytes[slash] == b'\\')
594    }
595
596    /// Skips an unquoted `url(` body up to its `)`. Quotes and `/*` in it are
597    /// raw text. Its brackets still count, as in a regex body: a `(` that only
598    /// looks like `url(` must not hide nesting. A CSS escape skips the next
599    /// character.
600    fn skip_unquoted_url(&mut self) {
601        self.open();
602        let mut local = 0_u32;
603        let mut peak = 0_u32;
604        while let Some(&byte) = self.bytes.get(self.pos) {
605            self.pos += 1;
606            match byte {
607                b'\\' => self.skip_escape(),
608                b'(' | b'[' | b'{' => {
609                    local += 1;
610                    peak = peak.max(local);
611                }
612                b')' if local == 0 => break,
613                b')' | b']' | b'}' => local = local.saturating_sub(1),
614                _ => {}
615            }
616        }
617        self.max_depth = self.max_depth.max(self.depth + peak);
618        self.depth = self.depth - 1 + local;
619        // A body that reaches the end of the source leaves its brackets open.
620        self.style_closers
621            .extend(std::iter::repeat_n(b')', local as usize));
622    }
623
624    /// Skips a `/* */` comment when one starts at the `/` at `pos - 1`.
625    fn skip_block_comment(&mut self) {
626        if self.bytes.get(self.pos) != Some(&b'*') {
627            return;
628        }
629        self.pos += 1;
630        while self.pos < self.bytes.len() && !self.bytes[self.pos..].starts_with(b"*/") {
631            self.pos += 1;
632        }
633        self.pos = (self.pos + 2).min(self.bytes.len());
634    }
635
636    /// Skips a string body. In script, a quote without a closing quote on its
637    /// line is not a string, so the scan goes on after the quote as code. In
638    /// a stylesheet such a quote starts a bad string, which ends before the
639    /// newline, as in the CSS tokenizer.
640    fn skip_string(&mut self, quote: u8) {
641        let start = self.pos;
642        while let Some(&byte) = self.bytes.get(self.pos) {
643            self.pos += 1;
644            match byte {
645                b'\\' if self.dialect == Dialect::Style => self.skip_style_escape(),
646                b'\\' => self.skip_escape(),
647                // A string may hold U+2028 and U+2029 since ES2019. A form
648                // feed is a newline in CSS.
649                b'\n' | b'\r' | 0x0C if self.dialect == Dialect::Style => {
650                    self.pos -= 1;
651                    return;
652                }
653                b'\n' | b'\r' => break,
654                _ if byte == quote => return,
655                _ => {}
656            }
657        }
658        if self.dialect == Dialect::Script {
659            self.pos = start;
660        }
661    }
662
663    /// Skips a regex body. A real regex balances its own groups, so its
664    /// brackets leave the running depth as it was. A division that only looks
665    /// like a regex must not hide brackets, so the body raises the peak depth
666    /// and its unclosed openers stay open. A body without a closing `/` on its
667    /// line is a division.
668    fn skip_regex(&mut self) -> bool {
669        let start = self.pos;
670        // Depth before the open character class. A class closes at its first
671        // `]` and its brackets are literal, so the close restores this depth.
672        let mut class_base = None;
673        let mut local = 0_u32;
674        let mut peak = 0_u32;
675        while let Some(&byte) = self.bytes.get(self.pos) {
676            if self.at_line_terminator() {
677                break;
678            }
679            self.pos += 1;
680            match byte {
681                // A regex cannot continue on the next line.
682                b'\\' if self.at_line_terminator() => break,
683                b'\\' => self.pos += 1,
684                b']' if class_base.is_some() => local = class_base.take().unwrap_or(0),
685                b'(' | b'[' | b'{' => {
686                    if byte == b'[' && class_base.is_none() {
687                        class_base = Some(local);
688                    }
689                    local += 1;
690                    peak = peak.max(local);
691                }
692                b')' | b']' | b'}' => local = local.saturating_sub(1),
693                b'/' if class_base.is_none() => {
694                    self.max_depth = self.max_depth.max(self.depth + peak);
695                    let base = self.depth;
696                    self.depth += local;
697                    self.count_regex_type_arguments(start, self.pos - 1, base);
698                    return true;
699                }
700                _ => {}
701            }
702        }
703        self.pos = start;
704        false
705    }
706
707    /// Counts the `<` of the regex body `start..end` as type arguments. The
708    /// parser can read the `/` as a division, so the body can be code whose
709    /// type arguments nest. The body is scanned as code from bracket depth
710    /// `base`, its nesting adds to the level that is open here, and the lists
711    /// that stay open at its end stay open after the `/`. Inside such a scan,
712    /// a further regex body counts each of its `<` as one more open level, so
713    /// the work stays linear.
714    fn count_regex_type_arguments(&mut self, start: usize, end: usize, base: u32) {
715        let body = &self.bytes[start..end];
716        if !body.contains(&b'<') {
717            return;
718        }
719        let open = self.type_arguments.last().map_or(0, |outer| outer.level);
720        if self.regex_body {
721            let count = body.iter().fold(0_u32, |count, &byte| {
722                count.saturating_add(u32::from(byte == b'<'))
723            });
724            self.carry_type_arguments(self.depth, open.saturating_add(count));
725            return;
726        }
727        // The body starts and ends next to an ASCII `/`, so it is UTF-8.
728        let Ok(text) = std::str::from_utf8(body) else {
729            return;
730        };
731        let mut scanner = Scanner::new(text, u32::MAX, Dialect::Script);
732        scanner.regex_body = true;
733        scanner.scan();
734        for list in &scanner.type_arguments {
735            self.carry_type_arguments(base + list.depth, open.saturating_add(list.level));
736        }
737        for &bracket in &scanner.expression_brackets {
738            let depth = (base + bracket).min(self.depth);
739            if self
740                .expression_brackets
741                .last()
742                .is_none_or(|&last| last < depth)
743            {
744                self.expression_brackets.push(depth);
745            }
746        }
747        self.max_type_arguments = self
748            .max_type_arguments
749            .max(open.saturating_add(scanner.max_type_arguments));
750    }
751
752    /// Keeps a type-argument list of a regex body open at `depth` with
753    /// `level`. The depth is at most the running depth, so a later closing
754    /// bracket ends it. A list at the same depth or deeper is merged into it
755    /// and keeps the higher level.
756    fn carry_type_arguments(&mut self, depth: u32, level: u32) {
757        let depth = depth.min(self.depth);
758        let mut level = level;
759        while let Some(last) = self.type_arguments.last().copied()
760            && last.depth >= depth
761        {
762            level = level.max(last.level);
763            self.type_arguments.pop();
764        }
765        self.type_arguments.push(TypeArguments { depth, level });
766        self.max_type_arguments = self.max_type_arguments.max(level);
767    }
768
769    /// Skips template text up to the closing backtick or the next `${`,
770    /// which opens one nesting level.
771    fn skip_template_text(&mut self) {
772        while let Some(&byte) = self.bytes.get(self.pos) {
773            self.pos += 1;
774            match byte {
775                b'\\' => self.skip_escape(),
776                b'`' => {
777                    self.regex_allowed = false;
778                    return;
779                }
780                b'$' if self.bytes.get(self.pos) == Some(&b'{') => {
781                    self.pos += 1;
782                    self.open();
783                    self.templates.push(self.depth);
784                    self.regex_allowed = true;
785                    return;
786                }
787                _ => {}
788            }
789        }
790    }
791}
792
793/// Whether `byte` can be part of a CSS identifier, so `myurl(` is not `url(`.
794const fn is_css_name_byte(byte: u8) -> bool {
795    byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_') || byte >= 0x80
796}
797
798/// Maximum number of hex digits in a CSS escape such as `\67`.
799const MAX_HEX_ESCAPE_DIGITS: usize = 6;
800
801const fn is_css_name_byte_or_escape(byte: u8) -> bool {
802    is_css_name_byte(byte) || byte == b'\\'
803}
804
805/// Keywords after which a `/` starts a regex literal.
806const REGEX_KEYWORDS: &[&[u8]] = &[
807    b"await",
808    b"case",
809    b"delete",
810    b"do",
811    b"else",
812    b"in",
813    b"instanceof",
814    b"new",
815    b"of",
816    b"return",
817    b"throw",
818    b"typeof",
819    b"void",
820    b"yield",
821];
822
823impl Scanner<'_> {
824    /// Whether the `/` at `pos - 1` can start a regex literal. In `</` and
825    /// `/>` it is part of a JSX tag.
826    fn may_start_regex(&self) -> bool {
827        let jsx_tag = self.pos >= 2 && self.bytes[self.pos - 2] == b'<'
828            || self.bytes.get(self.pos) == Some(&b'>');
829        !jsx_tag && (self.regex_allowed || self.after_keyword())
830    }
831
832    /// Whether an ECMAScript line terminator starts at `pos`: LF, CR, U+2028
833    /// or U+2029. Oxc ends a comment or a regex at each of them.
834    fn at_line_terminator(&self) -> bool {
835        self.line_terminator_len() > 0
836    }
837
838    /// Byte length of the line terminator at `pos`, or 0. CR LF is one
839    /// terminator.
840    fn line_terminator_len(&self) -> usize {
841        match self.bytes.get(self.pos..) {
842            Some([b'\r', b'\n', ..]) => 2,
843            Some([b'\n' | b'\r', ..]) => 1,
844            Some([0xE2, 0x80, 0xA8 | 0xA9, ..]) => 3,
845            _ => 0,
846        }
847    }
848
849    /// Steps over the character after a backslash at `pos - 1`. A backslash
850    /// before a line terminator continues a string or template on the next
851    /// line, so the whole terminator is skipped.
852    fn skip_escape(&mut self) {
853        self.pos += self.line_terminator_len().max(1);
854    }
855
856    /// Skips a CSS escape after the `\` at `pos - 1`. A hex escape such as
857    /// `\a` takes up to six hex digits and one whitespace after them, so a
858    /// newline there does not end a string.
859    fn skip_style_escape(&mut self) {
860        let digits = self.bytes[self.pos..]
861            .iter()
862            .take(MAX_HEX_ESCAPE_DIGITS)
863            .take_while(|byte| byte.is_ascii_hexdigit())
864            .count();
865        if digits == 0 {
866            self.skip_escape();
867            return;
868        }
869        self.pos += digits;
870        self.pos += match self.bytes.get(self.pos..) {
871            Some([b'\r', b'\n', ..]) => 2,
872            Some([b' ' | b'\t' | b'\n' | b'\r' | 0x0C, ..]) => 1,
873            _ => 0,
874        };
875    }
876
877    /// Whether the word before the `/` at `pos - 1` is a keyword that a regex
878    /// literal can follow.
879    fn after_keyword(&self) -> bool {
880        let before = &self.bytes[..self.pos - 1];
881        let before = before.trim_ascii_end();
882        let start = before
883            .iter()
884            .rposition(|byte| !(byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$')))
885            .map_or(0, |index| index + 1);
886        REGEX_KEYWORDS.contains(&&before[start..])
887    }
888}
889
890/// Whether a `/` after `byte` starts a regex literal. After an identifier,
891/// a number or a closing bracket it is a division.
892const fn starts_expression(byte: u8) -> bool {
893    !(byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$' | b'.' | b')' | b']'))
894}
895
896#[cfg(test)]
897mod tests {
898    use super::*;
899
900    fn depth_of(source: &str) -> u32 {
901        max_depth(source, u32::MAX, Dialect::Script)
902    }
903
904    fn style_depth_of(source: &str) -> u32 {
905        max_depth(source, u32::MAX, Dialect::Style)
906    }
907
908    #[test]
909    fn style_sources_skip_strings_and_block_comments_only() {
910        assert_eq!(style_depth_of(".a{content:\"(((\"}/* [[[ */"), 1);
911        assert_eq!(
912            style_depth_of(".b{background:url(//cdn.example.com/a.png)}.c{a:b(c(d))}"),
913            3
914        );
915        assert_eq!(style_depth_of(".d{width:calc(100%/3)}"), 2);
916        assert_eq!(
917            style_depth_of(".e::before{content:'it\\'s'}.f{g:h((i))}"),
918            3
919        );
920        // A CSS escape is not a quote, and an unquoted url() body is raw text.
921        assert_eq!(style_depth_of(".g\\\"{a:b((c))}"), 3);
922        assert_eq!(style_depth_of(".h{a:url(/*x.png)}.i{a:b((c))}"), 3);
923        assert_eq!(style_depth_of(".j{a:url(it's.png)}.k{a:b((c))}"), 3);
924        assert_eq!(style_depth_of(".l{a:URL( \"(((\" )}"), 2);
925        assert_eq!(style_depth_of(".m{a:myurl(((b)))}"), 4);
926        // A url() body still counts its brackets, so a misread url( hides
927        // nothing.
928        assert_eq!(style_depth_of("#url({{{{"), 5);
929        assert_eq!(style_depth_of(".n{a:\"x\u{c}((((1"), 5);
930    }
931
932    fn color_depth_of(source: &str) -> usize {
933        scan_depth(source, u32::MAX, Dialect::Style).max_colors
934    }
935
936    #[test]
937    fn counts_nested_color_functions() {
938        assert_eq!(color_depth_of(".a{color:red}"), 0);
939        assert_eq!(
940            color_depth_of(".a{color:color-mix(in srgb, LIGHT-DARK(rgb(0 0 0), red), red)}"),
941            3
942        );
943        // Sibling functions and plain brackets do not add depth.
944        assert_eq!(color_depth_of(".a{x:rgb(1 2 3) hsl(1 2% 3%) calc((1))}"), 1);
945        assert_eq!(color_depth_of(".a{x:rgb(var(--a, hsl(1 2% 3%)))}"), 2);
946        // A longer name, a string and a comment are not color functions.
947        assert_eq!(color_depth_of(".a{x:myrgb(no-hsl(1))}"), 0);
948        assert_eq!(color_depth_of(".a{content:\"rgb(rgb(\"}/* hsl(hsl( */"), 0);
949        // An unclosed color function stays open.
950        assert_eq!(color_depth_of(".a{x:light-dark(((light-dark(}"), 2);
951    }
952
953    #[test]
954    fn an_escaped_function_name_counts_as_a_color_function() {
955        assert_eq!(color_depth_of(".a{x:r\\67 b(r\\gb(\\72\tgb(1)))}"), 3);
956        assert_eq!(color_depth_of(".a{x:f\\(1)}"), 0);
957        // CSS reads `\r\n` after a hex escape as one whitespace.
958        assert_eq!(color_depth_of(".a{x:r\\67\r\nb(r\\67\r\nb(1))}"), 2);
959    }
960
961    /// An escape before `url` makes a longer name such as `aurl`, a plain
962    /// function whose body lightningcss parses. Its color functions count.
963    #[test]
964    fn an_escaped_name_that_ends_in_url_is_not_a_url() {
965        let nested = "rgb(".repeat(3);
966        for prefix in ["a\\", "\\61 ", "\\61\r\n", "\\61\t"] {
967            let source = format!(".a{{x:{prefix}url({nested}");
968            // The escaped name itself can also spell a color function.
969            assert!(color_depth_of(&source) >= 3, "{prefix:?}");
970        }
971        assert_eq!(color_depth_of(".a{x:url(rgb(rgb(}"), 0);
972    }
973
974    #[test]
975    fn color_function_depth_at_the_cap_is_allowed() {
976        let at_limit = format!(".a{{x:{}", "rgb(".repeat(MAX_COLOR_FUNCTION_DEPTH));
977        assert!(parse_style_bounded(&at_limit, || ()).is_some());
978        assert!(parse_style_bounded(&format!("{at_limit}hsl("), || ()).is_none());
979    }
980
981    #[test]
982    fn counts_code_brackets_only() {
983        assert_eq!(depth_of("f(a[b{c}])"), 3);
984        assert_eq!(
985            depth_of("'((('; \"[[[\"; `{{{`; /\\(\\(/; // (((\n/* ((( */"),
986            0
987        );
988        assert_eq!(depth_of("`a${b(`c${d}`)}`"), 3);
989        assert_eq!(depth_of("a / (b) / c"), 1);
990        assert_eq!(depth_of("x = /[/(]/ + (1)"), 2);
991        assert_eq!(depth_of("return /[(]/.test(a)"), 2);
992    }
993
994    #[test]
995    fn misread_literals_do_not_hide_brackets() {
996        assert_eq!(depth_of("x = i++ / (((1"), 3);
997        assert_eq!(depth_of("x = i++ / (((1 / 2)))"), 3);
998        assert_eq!(depth_of("<p>it's {{{a}}}</p>"), 3);
999        let lines = "x = i++ / ((1 / 2\n".repeat(500);
1000        assert_eq!(depth_of(&lines), 1000);
1001        for terminator in ["\r", "\u{2028}", "\u{2029}"] {
1002            assert_eq!(depth_of(&format!("// a{terminator}(((1")), 3);
1003            assert_eq!(depth_of(&format!("x = i++ / a{terminator}(((1")), 3);
1004        }
1005        assert_eq!(depth_of("'a\rb' + (((1"), 3);
1006        assert_eq!(depth_of("((('a\\\r\n)))' + (((1"), 6);
1007        assert_eq!(depth_of("((('a\\\u{2028})))' + (((1"), 6);
1008        assert_eq!(depth_of("x = i++ /a\\\n(((1 /"), 3);
1009    }
1010
1011    #[test]
1012    fn regex_character_classes_do_not_accumulate() {
1013        let regex = format!("x = /{}/;\n", "[a-z(][^)]".repeat(2000));
1014        assert_eq!(depth_of(&regex), 2);
1015    }
1016
1017    #[test]
1018    fn compact_jsx_closers_keep_the_depth_balanced() {
1019        let line = "<ul>{xs.map(i => (<li>{i}</li>))}</ul>\n{xs.map(i => <Item {...i} />)}\n";
1020        assert_eq!(depth_of(line), 4);
1021        assert_eq!(depth_of(&line.repeat(2000)), 4);
1022    }
1023
1024    fn type_argument_nesting_of(source: &str) -> u32 {
1025        scan_nesting(source, Dialect::Script).type_arguments
1026    }
1027
1028    #[test]
1029    fn type_argument_nesting_counts_open_lists_behind_expression_brackets() {
1030        assert_eq!(type_argument_nesting_of(&"t<{[".repeat(5)), 5);
1031        assert_eq!(type_argument_nesting_of(&"t<({[".repeat(5)), 5);
1032        // A `<` at the same depth replaces the open one.
1033        assert_eq!(type_argument_nesting_of("f(a<b, c<d, e<(g<h))"), 2);
1034        // `&&`, `||`, `??` and `=` cannot appear in a type, so they end the
1035        // open list.
1036        assert_eq!(
1037            type_argument_nesting_of("a < b && f(c < d || g(e < f ?? h(i = j < k)))"),
1038            1
1039        );
1040        // An object type holds no expression, so it adds no level.
1041        assert_eq!(
1042            type_argument_nesting_of(
1043                "useQuery<{ data: Array<{ id: string; tags: Map<string, Set<number>> }> }>()"
1044            ),
1045            1
1046        );
1047        assert_eq!(
1048            type_argument_nesting_of(&format!("{}x{}", "Z<{ a: ".repeat(40), " }>".repeat(40))),
1049            1
1050        );
1051        // `>`, `;` and closing brackets end a list. `=>`, `<=` and `<<=` do
1052        // not open or end one.
1053        assert_eq!(
1054            type_argument_nesting_of(
1055                "for (let i = 0; i < n; i++) { if (x[i] <= y) { f(() => a <<= b) } }"
1056            ),
1057            1
1058        );
1059        assert_eq!(
1060            type_argument_nesting_of("<ul>{xs.map(i => <li key={i}>{i < 2}</li>)}</ul>"),
1061            1
1062        );
1063        // Stylesheets have no type arguments.
1064        assert_eq!(
1065            scan_nesting(&"a>{[".repeat(40), Dialect::Style).type_arguments,
1066            0
1067        );
1068    }
1069
1070    #[test]
1071    fn type_argument_nesting_at_the_cap_is_allowed() {
1072        let at_limit = "t<{[".repeat(MAX_TYPE_ARGUMENT_NESTING as usize);
1073        assert!(!exceeds_nesting_limit(&at_limit));
1074        assert!(exceeds_nesting_limit(&format!("{at_limit}t<")));
1075    }
1076
1077    /// After `{}` the scanner reads `/` as the start of a regex, but the
1078    /// parser can read it as a division. The `<` in such a body must still
1079    /// count.
1080    #[test]
1081    fn type_arguments_in_a_guessed_regex_body_count() {
1082        let nested = "t<{[".repeat(MAX_TYPE_ARGUMENT_NESTING as usize + 2);
1083        let close = "]".repeat(MAX_TYPE_ARGUMENT_NESTING as usize + 2);
1084        assert!(exceeds_nesting_limit(&format!(
1085            "x = {{}} / {nested}{close}/ 1"
1086        )));
1087        assert!(!exceeds_nesting_limit("const re = /<a<b<c>/; f(re)"));
1088    }
1089
1090    /// The type-argument lists that stay open at the end of a guessed regex
1091    /// body stay open after its `/`, as in the parse of a division.
1092    #[test]
1093    fn open_type_arguments_of_a_guessed_regex_body_stay_open() {
1094        let half = MAX_TYPE_ARGUMENT_NESTING as usize / 2 + 1;
1095        let body = format!("{}]", "t<{[".repeat(half));
1096        let after = "t<{[".repeat(half);
1097        assert!(exceeds_nesting_limit(&format!(
1098            "x = {{}} / {body}/ {after}"
1099        )));
1100        // A regex class can hold a further guessed regex after an escaped
1101        // `\]`, which ends the class bracket only in code. That regex body
1102        // carries its open lists too.
1103        let inner = format!("[\\] {{}} / {}/ ]", "t<".repeat(half));
1104        assert!(exceeds_nesting_limit(&format!(
1105            "x = {{}} / {inner}/ {after}"
1106        )));
1107    }
1108
1109    #[test]
1110    fn depth_at_the_cap_is_allowed() {
1111        let at_limit = "[".repeat(MAX_NESTING_DEPTH as usize);
1112        assert!(!exceeds_nesting_limit(&at_limit));
1113        assert!(exceeds_nesting_limit(&format!("{at_limit}[")));
1114    }
1115}