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;
49
50pub const MAX_NESTING_DEPTH: u32 = 1024;
57
58pub const MAX_COLOR_FUNCTION_DEPTH: usize = 8;
66
67const MAX_COLOR_PARSE_COST: usize = 1 << 20;
76
77const 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
94pub 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#[cfg(test)]
114#[must_use]
115fn exceeds_nesting_limit(source: &str) -> bool {
116 scan_nesting(source, Dialect::Script).exceeds_limits()
117}
118
119#[derive(Clone, Copy, PartialEq, Eq)]
121enum Dialect {
122 Script,
124 Style,
129}
130
131pub fn parse_bounded<R: Send>(source: &str, parse: impl FnOnce() -> R + Send) -> Option<R> {
143 parse_bounded_as(source, Dialect::Script, parse)
144}
145
146pub 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
161pub 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
196pub 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
212struct Nesting {
214 brackets: u32,
216 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
226fn 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#[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 templates: Vec<u32>,
261 regex_allowed: bool,
264 type_arguments: Vec<TypeArguments>,
267 max_type_arguments: u32,
268 expression_brackets: Vec<u32>,
271 parameter_lists: Vec<u32>,
274 regex_body: bool,
277 colors: Vec<(u32, usize)>,
280 max_colors: usize,
282 color_cost: usize,
287 open_color_cost: usize,
289 style_closers: Vec<u8>,
293}
294
295#[derive(Clone, Copy)]
297struct TypeArguments {
298 depth: u32,
300 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 const fn passed_limit(&self) -> bool {
377 self.max_depth > self.limit || self.max_type_arguments > MAX_TYPE_ARGUMENT_NESTING
378 }
379
380 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 self.style_closers
703 .extend(std::iter::repeat_n(b')', local as usize));
704 }
705
706 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 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 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 fn skip_regex(&mut self) -> bool {
751 let start = self.pos;
752 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 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 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 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 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 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
877fn 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
889const fn is_css_name_byte(byte: u8) -> bool {
891 byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_') || byte >= 0x80
892}
893
894const 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
901const 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 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 fn at_line_terminator(&self) -> bool {
931 self.line_terminator_len() > 0
932 }
933
934 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 fn skip_escape(&mut self) {
949 self.pos += self.line_terminator_len().max(1);
950 }
951
952 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 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
986const 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 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 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 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 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 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 assert_eq!(color_cost_of(".a{x:rgb(1)}"), 0);
1058 assert_eq!(color_cost_of(".a{x:rgb(rgb(1))}"), 6);
1060 assert_eq!(color_cost_of(".a{x:rgb(rgb(rgb(1)))}"), 2 * 8 + 4 * 3);
1062 assert_eq!(color_cost_of(".a{x:rgb(rgb(1)) rgb(rgb(1))}"), 6);
1064 assert_eq!(color_cost_of("rgb(rgb(1"), 2 * 2);
1066 }
1067
1068 #[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 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 assert_eq!(color_depth_of(".a{x:r\\67\r\nb(r\\67\r\nb(1))}"), 2);
1087 }
1088
1089 #[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 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(®ex), 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 assert_eq!(type_argument_nesting_of("f(a<b, c<d, e<(g<h))"), 2);
1161 assert_eq!(
1164 type_argument_nesting_of("a < b && f(c < d || g(e < f ?? h(i = j < k)))"),
1165 1
1166 );
1167 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 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 assert_eq!(
1192 scan_nesting(&"a>{[".repeat(40), Dialect::Style).type_arguments,
1193 0
1194 );
1195 }
1196
1197 #[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 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 #[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 #[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 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}