1use std::path::Path;
26
27use fallow_types::discover::FileId;
28use fallow_types::extract::ModuleInfo;
29
30use crate::visitor::ModuleInfoExtractor;
31
32const MAX_TYPE_ARGUMENT_NESTING: u32 = 10;
45
46pub const MAX_NESTING_DEPTH: u32 = 1024;
53
54pub const MAX_COLOR_FUNCTION_DEPTH: usize = 8;
62
63const 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
80pub 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#[cfg(test)]
100#[must_use]
101fn exceeds_nesting_limit(source: &str) -> bool {
102 scan_nesting(source, Dialect::Script).exceeds_limits()
103}
104
105#[derive(Clone, Copy, PartialEq, Eq)]
107enum Dialect {
108 Script,
110 Style,
115}
116
117pub fn parse_bounded<R: Send>(source: &str, parse: impl FnOnce() -> R + Send) -> Option<R> {
129 parse_bounded_as(source, Dialect::Script, parse)
130}
131
132pub 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
147pub 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
182pub 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
198struct Nesting {
200 brackets: u32,
202 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
212fn 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#[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 templates: Vec<u32>,
246 regex_allowed: bool,
249 type_arguments: Vec<TypeArguments>,
252 max_type_arguments: u32,
253 expression_brackets: Vec<u32>,
256 regex_body: bool,
259 colors: Vec<u32>,
261 max_colors: usize,
263 style_closers: Vec<u8>,
267}
268
269#[derive(Clone, Copy)]
271struct TypeArguments {
272 depth: u32,
274 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 const fn passed_limit(&self) -> bool {
348 self.max_depth > self.limit || self.max_type_arguments > MAX_TYPE_ARGUMENT_NESTING
349 }
350
351 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 self.style_closers
621 .extend(std::iter::repeat_n(b')', local as usize));
622 }
623
624 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 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 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 fn skip_regex(&mut self) -> bool {
669 let start = self.pos;
670 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 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 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 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 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 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
793const fn is_css_name_byte(byte: u8) -> bool {
795 byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_') || byte >= 0x80
796}
797
798const 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
805const 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 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 fn at_line_terminator(&self) -> bool {
835 self.line_terminator_len() > 0
836 }
837
838 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 fn skip_escape(&mut self) {
853 self.pos += self.line_terminator_len().max(1);
854 }
855
856 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 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
890const 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 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 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 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 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 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 assert_eq!(color_depth_of(".a{x:r\\67\r\nb(r\\67\r\nb(1))}"), 2);
959 }
960
961 #[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 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(®ex), 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 assert_eq!(type_argument_nesting_of("f(a<b, c<d, e<(g<h))"), 2);
1034 assert_eq!(
1037 type_argument_nesting_of("a < b && f(c < d || g(e < f ?? h(i = j < k)))"),
1038 1
1039 );
1040 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 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 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 #[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 #[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 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}