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