use std::path::Path;
use fallow_types::discover::FileId;
use fallow_types::extract::ModuleInfo;
use crate::visitor::ModuleInfoExtractor;
const MAX_TYPE_ARGUMENT_NESTING: u32 = 10;
pub const MAX_NESTING_DEPTH: u32 = 1024;
const MAX_COLOR_FUNCTION_DEPTH: usize = 8;
const COLOR_FUNCTIONS: &[&[u8]] = &[
b"rgb",
b"rgba",
b"hsl",
b"hsla",
b"hwb",
b"lab",
b"lch",
b"oklab",
b"oklch",
b"color",
b"color-mix",
b"light-dark",
b"alpha",
];
pub fn too_deep_module(file_id: FileId, source: &str, content_hash: u64) -> ModuleInfo {
let mut info = ModuleInfoExtractor::new().into_module_info(
file_id,
content_hash,
crate::suppress::ParsedSuppressions::default(),
);
info.parse_error_count = 1;
info.parse_panicked = true;
info.parse_nesting_too_deep = true;
info.line_offsets = fallow_types::extract::compute_line_offsets(source);
info
}
#[cfg(test)]
#[must_use]
fn exceeds_nesting_limit(source: &str) -> bool {
scan_nesting(source, Dialect::Script).exceeds_limits()
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Dialect {
Script,
Style,
}
pub fn parse_bounded<R: Send>(source: &str, parse: impl FnOnce() -> R + Send) -> Option<R> {
parse_bounded_as(source, Dialect::Script, parse)
}
pub fn parse_style_bounded<R: Send>(source: &str, parse: impl FnOnce() -> R + Send) -> Option<R> {
let scan = scan_depth(source, MAX_NESTING_DEPTH, Dialect::Style);
if scan.max_colors > MAX_COLOR_FUNCTION_DEPTH {
return None;
}
run_bounded(source, scan.max_depth, parse)
}
pub fn parse_file_bounded<R: Send>(
path: &Path,
source: &str,
parse: impl FnOnce() -> R + Send,
) -> Option<R> {
let dialect = if crate::css::is_css_file(path) {
Dialect::Style
} else {
Dialect::Script
};
parse_bounded_as(source, dialect, parse)
}
fn parse_bounded_as<R: Send>(
source: &str,
dialect: Dialect,
parse: impl FnOnce() -> R + Send,
) -> Option<R> {
let nesting = scan_nesting(source, dialect);
if nesting.exceeds_limits() {
return None;
}
run_bounded(source, nesting.brackets, parse)
}
fn run_bounded<R: Send>(source: &str, depth: u32, parse: impl FnOnce() -> R + Send) -> Option<R> {
if depth > MAX_NESTING_DEPTH {
return None;
}
let need = crate::stack::stack_need(source.len(), depth as usize)?;
Some(crate::stack::run_with_stack(need, parse))
}
pub fn parse_bounded_or_default<T: Send + Default>(
source: &str,
source_type: oxc_span::SourceType,
walk: impl FnOnce(&oxc_parser::ParserReturn<'_>) -> T + Send,
) -> T {
parse_bounded(source, || {
let allocator = oxc_allocator::Allocator::default();
let parsed = oxc_parser::Parser::new(&allocator, source, source_type).parse();
walk(&parsed)
})
.unwrap_or_default()
}
struct Nesting {
brackets: u32,
type_arguments: u32,
}
impl Nesting {
const fn exceeds_limits(&self) -> bool {
self.brackets > MAX_NESTING_DEPTH || self.type_arguments > MAX_TYPE_ARGUMENT_NESTING
}
}
fn scan_nesting(source: &str, dialect: Dialect) -> Nesting {
let mut scanner = Scanner::new(source, MAX_NESTING_DEPTH, dialect);
scanner.scan();
Nesting {
brackets: scanner.max_depth,
type_arguments: scanner.max_type_arguments,
}
}
#[cfg(test)]
fn max_depth(source: &str, limit: u32, dialect: Dialect) -> u32 {
scan_depth(source, limit, dialect).max_depth
}
fn scan_depth(source: &str, limit: u32, dialect: Dialect) -> Scanner<'_> {
let mut scanner = Scanner::new(source, limit, dialect);
scanner.scan();
scanner
}
struct Scanner<'a> {
bytes: &'a [u8],
pos: usize,
depth: u32,
max_depth: u32,
limit: u32,
dialect: Dialect,
templates: Vec<u32>,
regex_allowed: bool,
type_arguments: Vec<TypeArguments>,
max_type_arguments: u32,
expression_brackets: Vec<u32>,
regex_body: bool,
colors: Vec<u32>,
max_colors: usize,
}
#[derive(Clone, Copy)]
struct TypeArguments {
depth: u32,
level: u32,
}
impl<'a> Scanner<'a> {
fn new(source: &'a str, limit: u32, dialect: Dialect) -> Self {
Scanner {
bytes: source.as_bytes(),
pos: 0,
depth: 0,
max_depth: 0,
limit,
dialect,
templates: Vec::new(),
regex_allowed: true,
type_arguments: Vec::new(),
max_type_arguments: 0,
expression_brackets: Vec::new(),
regex_body: false,
colors: Vec::new(),
max_colors: 0,
}
}
}
impl Scanner<'_> {
fn scan(&mut self) {
while let Some(&byte) = self.bytes.get(self.pos) {
if self.passed_limit() {
return;
}
self.pos += 1;
match byte {
b'\\' | b'(' | b'/'
if self.dialect == Dialect::Style && self.scan_style_byte(byte) => {}
b'(' | b'[' | b'{' => self.open_bracket(byte),
b'}' if self.templates.last() == Some(&self.depth) => {
self.templates.pop();
self.depth -= 1;
self.close_type_arguments_above_depth();
self.skip_template_text();
}
b')' | b']' | b'}' => {
self.depth = self.depth.saturating_sub(1);
self.close_type_arguments_above_depth();
self.regex_allowed = byte == b'}';
self.close_color_functions();
}
b'<' | b'>' | b';' | b'=' | b'&' | b'|' | b'?' | b'`'
if self.dialect == Dialect::Script =>
{
self.scan_script_byte(byte);
}
b'\'' | b'"' => {
self.skip_string(byte);
self.regex_allowed = false;
}
b'/' => self.skip_slash(),
b' ' | b'\t' | b'\n' | b'\r' => {}
_ => self.regex_allowed = starts_expression(byte),
}
}
}
fn open(&mut self) {
self.depth += 1;
self.max_depth = self.max_depth.max(self.depth);
}
const fn passed_limit(&self) -> bool {
self.max_depth > self.limit || self.max_type_arguments > MAX_TYPE_ARGUMENT_NESTING
}
fn open_bracket(&mut self, byte: u8) {
self.open();
if byte != b'{' {
self.expression_brackets.push(self.depth);
}
self.regex_allowed = true;
}
fn scan_script_byte(&mut self, byte: u8) {
match byte {
b'`' => self.skip_template_text(),
b'<' => {
self.open_type_arguments();
self.regex_allowed = true;
}
_ => {
self.end_type_arguments(byte);
self.regex_allowed = true;
}
}
}
fn open_type_arguments(&mut self) {
if self.bytes.get(self.pos) == Some(&b'<') {
self.pos += 1;
}
if self.bytes.get(self.pos) == Some(&b'=') {
return;
}
let replaced = if self
.type_arguments
.last()
.is_some_and(|open| open.depth == self.depth)
{
self.type_arguments.pop().map_or(0, |open| open.level)
} else {
0
};
let level = self
.type_arguments
.last()
.map_or(1, |outer| {
let behind_expression = self
.expression_brackets
.last()
.is_some_and(|&bracket| bracket > outer.depth);
outer.level + u32::from(behind_expression)
})
.max(replaced);
self.type_arguments.push(TypeArguments {
depth: self.depth,
level,
});
self.max_type_arguments = self.max_type_arguments.max(level);
}
fn end_type_arguments(&mut self, byte: u8) {
let next = self.bytes.get(self.pos).copied();
let ends = match byte {
b'>' => self.pos < 2 || self.bytes[self.pos - 2] != b'=',
b'=' => next != Some(b'>'),
b'&' | b'|' | b'?' => next == Some(byte),
_ => true,
};
if matches!(byte, b'&' | b'|' | b'?') && ends {
self.pos += 1;
}
if ends
&& self
.type_arguments
.last()
.is_some_and(|open| open.depth == self.depth)
{
self.type_arguments.pop();
}
}
fn close_type_arguments_above_depth(&mut self) {
while self
.type_arguments
.last()
.is_some_and(|open| open.depth > self.depth)
{
self.type_arguments.pop();
}
while self
.expression_brackets
.last()
.is_some_and(|&bracket| bracket > self.depth)
{
self.expression_brackets.pop();
}
}
fn scan_style_byte(&mut self, byte: u8) -> bool {
match byte {
b'\\' => self.skip_escape(),
b'/' => self.skip_block_comment(),
_ if self.at_unquoted_url() => self.skip_unquoted_url(),
_ if self.at_color_function() => {
self.open();
self.colors.push(self.depth);
self.max_colors = self.max_colors.max(self.colors.len());
}
_ => return false,
}
true
}
fn close_color_functions(&mut self) {
while self.colors.last().is_some_and(|open| *open > self.depth) {
self.colors.pop();
}
}
fn skip_slash(&mut self) {
match self.bytes.get(self.pos) {
Some(b'/') => {
while self.pos < self.bytes.len() && !self.at_line_terminator() {
self.pos += 1;
}
}
Some(b'*') => self.skip_block_comment(),
_ if self.may_start_regex() && self.skip_regex() => {
self.regex_allowed = false;
}
_ => self.regex_allowed = true,
}
}
fn at_unquoted_url(&self) -> bool {
let open = self.pos - 1;
let Some(name) = open.checked_sub(3).map(|start| &self.bytes[start..open]) else {
return false;
};
let starts_word = open.checked_sub(4).is_none_or(|before| {
let byte = self.bytes[before];
!is_css_name_byte(byte) && byte != b'\\' && self.escape_whitespace_len(before) == 0
});
let body = self.bytes[self.pos..].trim_ascii_start();
name.eq_ignore_ascii_case(b"url")
&& starts_word
&& !matches!(body.first(), Some(b'\'' | b'"'))
}
fn at_color_function(&self) -> bool {
let open = self.pos - 1;
let mut start = open;
loop {
while start > 0 && is_css_name_byte_or_escape(self.bytes[start - 1]) {
start -= 1;
}
match start
.checked_sub(1)
.map(|before| self.escape_whitespace_len(before))
{
Some(len) if len > 0 => start -= len,
_ => break,
}
}
let name = &self.bytes[start..open];
name.contains(&b'\\')
|| COLOR_FUNCTIONS
.iter()
.any(|color| name.eq_ignore_ascii_case(color))
}
fn escape_whitespace_len(&self, last: usize) -> usize {
match self.bytes[last] {
b'\n'
if last > 0 && self.bytes[last - 1] == b'\r' && self.ends_hex_escape(last - 1) =>
{
2
}
b' ' | b'\t' | b'\n' | b'\r' | 0x0C if self.ends_hex_escape(last) => 1,
_ => 0,
}
}
fn ends_hex_escape(&self, end: usize) -> bool {
let digits = self.bytes[..end]
.iter()
.rev()
.take(MAX_HEX_ESCAPE_DIGITS + 1)
.take_while(|byte| byte.is_ascii_hexdigit())
.count();
(1..=MAX_HEX_ESCAPE_DIGITS).contains(&digits)
&& end
.checked_sub(digits + 1)
.is_some_and(|slash| self.bytes[slash] == b'\\')
}
fn skip_unquoted_url(&mut self) {
self.open();
let mut local = 0_u32;
let mut peak = 0_u32;
while let Some(&byte) = self.bytes.get(self.pos) {
self.pos += 1;
match byte {
b'\\' => self.skip_escape(),
b'(' | b'[' | b'{' => {
local += 1;
peak = peak.max(local);
}
b')' if local == 0 => break,
b')' | b']' | b'}' => local = local.saturating_sub(1),
_ => {}
}
}
self.max_depth = self.max_depth.max(self.depth + peak);
self.depth = self.depth - 1 + local;
}
fn skip_block_comment(&mut self) {
if self.bytes.get(self.pos) != Some(&b'*') {
return;
}
self.pos += 1;
while self.pos < self.bytes.len() && !self.bytes[self.pos..].starts_with(b"*/") {
self.pos += 1;
}
self.pos = (self.pos + 2).min(self.bytes.len());
}
fn skip_string(&mut self, quote: u8) {
let start = self.pos;
while let Some(&byte) = self.bytes.get(self.pos) {
self.pos += 1;
match byte {
b'\\' => self.skip_escape(),
b'\n' | b'\r' => break,
0x0C if self.dialect == Dialect::Style => break,
_ if byte == quote => return,
_ => {}
}
}
self.pos = start;
}
fn skip_regex(&mut self) -> bool {
let start = self.pos;
let mut class_base = None;
let mut local = 0_u32;
let mut peak = 0_u32;
while let Some(&byte) = self.bytes.get(self.pos) {
if self.at_line_terminator() {
break;
}
self.pos += 1;
match byte {
b'\\' if self.at_line_terminator() => break,
b'\\' => self.pos += 1,
b']' if class_base.is_some() => local = class_base.take().unwrap_or(0),
b'(' | b'[' | b'{' => {
if byte == b'[' && class_base.is_none() {
class_base = Some(local);
}
local += 1;
peak = peak.max(local);
}
b')' | b']' | b'}' => local = local.saturating_sub(1),
b'/' if class_base.is_none() => {
self.max_depth = self.max_depth.max(self.depth + peak);
let base = self.depth;
self.depth += local;
self.count_regex_type_arguments(start, self.pos - 1, base);
return true;
}
_ => {}
}
}
self.pos = start;
false
}
fn count_regex_type_arguments(&mut self, start: usize, end: usize, base: u32) {
let body = &self.bytes[start..end];
if !body.contains(&b'<') {
return;
}
let open = self.type_arguments.last().map_or(0, |outer| outer.level);
if self.regex_body {
let count = body.iter().fold(0_u32, |count, &byte| {
count.saturating_add(u32::from(byte == b'<'))
});
self.carry_type_arguments(self.depth, open.saturating_add(count));
return;
}
let Ok(text) = std::str::from_utf8(body) else {
return;
};
let mut scanner = Scanner::new(text, u32::MAX, Dialect::Script);
scanner.regex_body = true;
scanner.scan();
for list in &scanner.type_arguments {
self.carry_type_arguments(base + list.depth, open.saturating_add(list.level));
}
for &bracket in &scanner.expression_brackets {
let depth = (base + bracket).min(self.depth);
if self
.expression_brackets
.last()
.is_none_or(|&last| last < depth)
{
self.expression_brackets.push(depth);
}
}
self.max_type_arguments = self
.max_type_arguments
.max(open.saturating_add(scanner.max_type_arguments));
}
fn carry_type_arguments(&mut self, depth: u32, level: u32) {
let depth = depth.min(self.depth);
let mut level = level;
while let Some(last) = self.type_arguments.last().copied()
&& last.depth >= depth
{
level = level.max(last.level);
self.type_arguments.pop();
}
self.type_arguments.push(TypeArguments { depth, level });
self.max_type_arguments = self.max_type_arguments.max(level);
}
fn skip_template_text(&mut self) {
while let Some(&byte) = self.bytes.get(self.pos) {
self.pos += 1;
match byte {
b'\\' => self.skip_escape(),
b'`' => {
self.regex_allowed = false;
return;
}
b'$' if self.bytes.get(self.pos) == Some(&b'{') => {
self.pos += 1;
self.open();
self.templates.push(self.depth);
self.regex_allowed = true;
return;
}
_ => {}
}
}
}
}
const fn is_css_name_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_') || byte >= 0x80
}
const MAX_HEX_ESCAPE_DIGITS: usize = 6;
const fn is_css_name_byte_or_escape(byte: u8) -> bool {
is_css_name_byte(byte) || byte == b'\\'
}
const REGEX_KEYWORDS: &[&[u8]] = &[
b"await",
b"case",
b"delete",
b"do",
b"else",
b"in",
b"instanceof",
b"new",
b"of",
b"return",
b"throw",
b"typeof",
b"void",
b"yield",
];
impl Scanner<'_> {
fn may_start_regex(&self) -> bool {
let jsx_tag = self.pos >= 2 && self.bytes[self.pos - 2] == b'<'
|| self.bytes.get(self.pos) == Some(&b'>');
!jsx_tag && (self.regex_allowed || self.after_keyword())
}
fn at_line_terminator(&self) -> bool {
self.line_terminator_len() > 0
}
fn line_terminator_len(&self) -> usize {
match self.bytes.get(self.pos..) {
Some([b'\r', b'\n', ..]) => 2,
Some([b'\n' | b'\r', ..]) => 1,
Some([0xE2, 0x80, 0xA8 | 0xA9, ..]) => 3,
_ => 0,
}
}
fn skip_escape(&mut self) {
self.pos += self.line_terminator_len().max(1);
}
fn after_keyword(&self) -> bool {
let before = &self.bytes[..self.pos - 1];
let before = before.trim_ascii_end();
let start = before
.iter()
.rposition(|byte| !(byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$')))
.map_or(0, |index| index + 1);
REGEX_KEYWORDS.contains(&&before[start..])
}
}
const fn starts_expression(byte: u8) -> bool {
!(byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$' | b'.' | b')' | b']'))
}
#[cfg(test)]
mod tests {
use super::*;
fn depth_of(source: &str) -> u32 {
max_depth(source, u32::MAX, Dialect::Script)
}
fn style_depth_of(source: &str) -> u32 {
max_depth(source, u32::MAX, Dialect::Style)
}
#[test]
fn style_sources_skip_strings_and_block_comments_only() {
assert_eq!(style_depth_of(".a{content:\"(((\"}/* [[[ */"), 1);
assert_eq!(
style_depth_of(".b{background:url(//cdn.example.com/a.png)}.c{a:b(c(d))}"),
3
);
assert_eq!(style_depth_of(".d{width:calc(100%/3)}"), 2);
assert_eq!(
style_depth_of(".e::before{content:'it\\'s'}.f{g:h((i))}"),
3
);
assert_eq!(style_depth_of(".g\\\"{a:b((c))}"), 3);
assert_eq!(style_depth_of(".h{a:url(/*x.png)}.i{a:b((c))}"), 3);
assert_eq!(style_depth_of(".j{a:url(it's.png)}.k{a:b((c))}"), 3);
assert_eq!(style_depth_of(".l{a:URL( \"(((\" )}"), 2);
assert_eq!(style_depth_of(".m{a:myurl(((b)))}"), 4);
assert_eq!(style_depth_of("#url({{{{"), 5);
assert_eq!(style_depth_of(".n{a:\"x\u{c}((((1"), 5);
}
fn color_depth_of(source: &str) -> usize {
scan_depth(source, u32::MAX, Dialect::Style).max_colors
}
#[test]
fn counts_nested_color_functions() {
assert_eq!(color_depth_of(".a{color:red}"), 0);
assert_eq!(
color_depth_of(".a{color:color-mix(in srgb, LIGHT-DARK(rgb(0 0 0), red), red)}"),
3
);
assert_eq!(color_depth_of(".a{x:rgb(1 2 3) hsl(1 2% 3%) calc((1))}"), 1);
assert_eq!(color_depth_of(".a{x:rgb(var(--a, hsl(1 2% 3%)))}"), 2);
assert_eq!(color_depth_of(".a{x:myrgb(no-hsl(1))}"), 0);
assert_eq!(color_depth_of(".a{content:\"rgb(rgb(\"}/* hsl(hsl( */"), 0);
assert_eq!(color_depth_of(".a{x:light-dark(((light-dark(}"), 2);
}
#[test]
fn an_escaped_function_name_counts_as_a_color_function() {
assert_eq!(color_depth_of(".a{x:r\\67 b(r\\gb(\\72\tgb(1)))}"), 3);
assert_eq!(color_depth_of(".a{x:f\\(1)}"), 0);
assert_eq!(color_depth_of(".a{x:r\\67\r\nb(r\\67\r\nb(1))}"), 2);
}
#[test]
fn an_escaped_name_that_ends_in_url_is_not_a_url() {
let nested = "rgb(".repeat(3);
for prefix in ["a\\", "\\61 ", "\\61\r\n", "\\61\t"] {
let source = format!(".a{{x:{prefix}url({nested}");
assert!(color_depth_of(&source) >= 3, "{prefix:?}");
}
assert_eq!(color_depth_of(".a{x:url(rgb(rgb(}"), 0);
}
#[test]
fn color_function_depth_at_the_cap_is_allowed() {
let at_limit = format!(".a{{x:{}", "rgb(".repeat(MAX_COLOR_FUNCTION_DEPTH));
assert!(parse_style_bounded(&at_limit, || ()).is_some());
assert!(parse_style_bounded(&format!("{at_limit}hsl("), || ()).is_none());
}
#[test]
fn counts_code_brackets_only() {
assert_eq!(depth_of("f(a[b{c}])"), 3);
assert_eq!(
depth_of("'((('; \"[[[\"; `{{{`; /\\(\\(/; // (((\n/* ((( */"),
0
);
assert_eq!(depth_of("`a${b(`c${d}`)}`"), 3);
assert_eq!(depth_of("a / (b) / c"), 1);
assert_eq!(depth_of("x = /[/(]/ + (1)"), 2);
assert_eq!(depth_of("return /[(]/.test(a)"), 2);
}
#[test]
fn misread_literals_do_not_hide_brackets() {
assert_eq!(depth_of("x = i++ / (((1"), 3);
assert_eq!(depth_of("x = i++ / (((1 / 2)))"), 3);
assert_eq!(depth_of("<p>it's {{{a}}}</p>"), 3);
let lines = "x = i++ / ((1 / 2\n".repeat(500);
assert_eq!(depth_of(&lines), 1000);
for terminator in ["\r", "\u{2028}", "\u{2029}"] {
assert_eq!(depth_of(&format!("// a{terminator}(((1")), 3);
assert_eq!(depth_of(&format!("x = i++ / a{terminator}(((1")), 3);
}
assert_eq!(depth_of("'a\rb' + (((1"), 3);
assert_eq!(depth_of("((('a\\\r\n)))' + (((1"), 6);
assert_eq!(depth_of("((('a\\\u{2028})))' + (((1"), 6);
assert_eq!(depth_of("x = i++ /a\\\n(((1 /"), 3);
}
#[test]
fn regex_character_classes_do_not_accumulate() {
let regex = format!("x = /{}/;\n", "[a-z(][^)]".repeat(2000));
assert_eq!(depth_of(®ex), 2);
}
#[test]
fn compact_jsx_closers_keep_the_depth_balanced() {
let line = "<ul>{xs.map(i => (<li>{i}</li>))}</ul>\n{xs.map(i => <Item {...i} />)}\n";
assert_eq!(depth_of(line), 4);
assert_eq!(depth_of(&line.repeat(2000)), 4);
}
fn type_argument_nesting_of(source: &str) -> u32 {
scan_nesting(source, Dialect::Script).type_arguments
}
#[test]
fn type_argument_nesting_counts_open_lists_behind_expression_brackets() {
assert_eq!(type_argument_nesting_of(&"t<{[".repeat(5)), 5);
assert_eq!(type_argument_nesting_of(&"t<({[".repeat(5)), 5);
assert_eq!(type_argument_nesting_of("f(a<b, c<d, e<(g<h))"), 2);
assert_eq!(
type_argument_nesting_of("a < b && f(c < d || g(e < f ?? h(i = j < k)))"),
1
);
assert_eq!(
type_argument_nesting_of(
"useQuery<{ data: Array<{ id: string; tags: Map<string, Set<number>> }> }>()"
),
1
);
assert_eq!(
type_argument_nesting_of(&format!("{}x{}", "Z<{ a: ".repeat(40), " }>".repeat(40))),
1
);
assert_eq!(
type_argument_nesting_of(
"for (let i = 0; i < n; i++) { if (x[i] <= y) { f(() => a <<= b) } }"
),
1
);
assert_eq!(
type_argument_nesting_of("<ul>{xs.map(i => <li key={i}>{i < 2}</li>)}</ul>"),
1
);
assert_eq!(
scan_nesting(&"a>{[".repeat(40), Dialect::Style).type_arguments,
0
);
}
#[test]
fn type_argument_nesting_at_the_cap_is_allowed() {
let at_limit = "t<{[".repeat(MAX_TYPE_ARGUMENT_NESTING as usize);
assert!(!exceeds_nesting_limit(&at_limit));
assert!(exceeds_nesting_limit(&format!("{at_limit}t<")));
}
#[test]
fn type_arguments_in_a_guessed_regex_body_count() {
let nested = "t<{[".repeat(MAX_TYPE_ARGUMENT_NESTING as usize + 2);
let close = "]".repeat(MAX_TYPE_ARGUMENT_NESTING as usize + 2);
assert!(exceeds_nesting_limit(&format!(
"x = {{}} / {nested}{close}/ 1"
)));
assert!(!exceeds_nesting_limit("const re = /<a<b<c>/; f(re)"));
}
#[test]
fn open_type_arguments_of_a_guessed_regex_body_stay_open() {
let half = MAX_TYPE_ARGUMENT_NESTING as usize / 2 + 1;
let body = format!("{}]", "t<{[".repeat(half));
let after = "t<{[".repeat(half);
assert!(exceeds_nesting_limit(&format!(
"x = {{}} / {body}/ {after}"
)));
let inner = format!("[\\] {{}} / {}/ ]", "t<".repeat(half));
assert!(exceeds_nesting_limit(&format!(
"x = {{}} / {inner}/ {after}"
)));
}
#[test]
fn depth_at_the_cap_is_allowed() {
let at_limit = "[".repeat(MAX_NESTING_DEPTH as usize);
assert!(!exceeds_nesting_limit(&at_limit));
assert!(exceeds_nesting_limit(&format!("{at_limit}[")));
}
}