1use alloc::boxed::Box;
8use alloc::rc::Rc;
9use core::cell::{Cell, RefCell};
10use alloc::string::String;
11use alloc::vec::Vec;
12
13#[derive(Debug, Clone, PartialEq)]
14pub enum BinaryOp {
15 Add,
16 Sub,
17 Mul,
18 Div,
19 Mod,
20 Pow,
21 Eq,
22 NotEq,
23 StrictEq,
24 StrictNotEq,
25 Lt,
26 Gt,
27 LtEq,
28 GtEq,
29 BitAnd,
30 BitOr,
31 BitXor,
32 Shl,
33 Shr,
34 UShr,
35 InstanceOf,
36 In,
37}
38
39#[derive(Debug, Clone, PartialEq)]
40pub enum LogicalOp {
41 And, Or, Nullish, }
45
46#[derive(Debug, Clone, PartialEq)]
47pub enum UnaryOp {
48 Neg, Pos, Not, BitNot, TypeOf, Void, Delete, }
56
57#[derive(Debug, Clone, PartialEq)]
59pub struct Property {
60 pub key: Rc<str>,
61 pub value: Expression,
62 pub computed: Option<Expression>,
64 pub accessor: Option<bool>,
67}
68
69pub const OBJECT_SPREAD_KEY: &str = "\u{0}spread";
71
72#[derive(Debug, Clone, PartialEq)]
73pub enum Expression {
74 Number(f64),
75 BigIntLit(String),
77 Str(String),
78 Bool(bool),
79 Null,
80 Undefined,
81 Identifier(Rc<str>),
82 This,
83 TemplateLiteral {
84 quasis: Box<Vec<String>>,
87 exprs: Box<Vec<Expression>>,
88 },
89 TaggedTemplate {
93 tag: Box<Expression>,
94 quasis: Box<Vec<String>>,
95 raw: Box<Vec<String>>,
96 exprs: Box<Vec<Expression>>,
97 },
98 Elision,
100 Array(Vec<Expression>),
101 Object(Vec<Property>),
102 Function {
106 name: Option<Rc<str>>,
109 params: Rc<Vec<Param>>,
110 body: Rc<FnBody>,
111 is_arrow: bool,
112 is_async: bool,
113 is_generator: bool,
114 },
115 Await(Box<Expression>),
117 Yield {
119 argument: Option<Box<Expression>>,
120 delegate: bool,
121 },
122 Unary {
123 op: UnaryOp,
124 expr: Box<Expression>,
125 },
126 Update {
127 op: &'static str, prefix: bool,
129 target: Box<Expression>,
130 },
131 Binary {
132 op: BinaryOp,
133 left: Box<Expression>,
134 right: Box<Expression>,
135 },
136 Logical {
137 op: LogicalOp,
138 left: Box<Expression>,
139 right: Box<Expression>,
140 },
141 Assign {
142 op: &'static str, target: Box<Expression>,
144 value: Box<Expression>,
145 },
146 Conditional {
147 test: Box<Expression>,
148 consequent: Box<Expression>,
149 alternate: Box<Expression>,
150 },
151 Member {
152 object: Box<Expression>,
153 property: Rc<str>,
154 optional: bool, },
156 Index {
157 object: Box<Expression>,
158 index: Box<Expression>,
159 optional: bool, },
161 Call {
162 callee: Box<Expression>,
163 arguments: Vec<Expression>,
164 optional: bool, },
166 New {
167 callee: Box<Expression>,
168 arguments: Vec<Expression>,
169 },
170 Spread(Box<Expression>),
172 Class {
174 name: Option<String>,
175 superclass: Option<Box<Expression>>,
176 members: Box<Vec<ClassMember>>,
177 },
178 Super,
180 Sequence(Vec<Expression>),
183 NewTarget,
186 Regex(Box<(String, String)>),
188}
189
190#[derive(Debug, Clone, PartialEq)]
192pub enum MethodKind {
193 Method,
194 Constructor,
195 Field,
198 Getter,
200 Setter,
202 StaticBlock,
205 ClassSource,
207}
208
209#[derive(Debug, Clone, PartialEq)]
211pub struct ClassMember {
212 pub key: Rc<str>,
213 pub computed_key: Option<Expression>,
216 pub kind: MethodKind,
217 pub params: Rc<Vec<Param>>,
218 pub body: Rc<FnBody>,
219 pub is_static: bool,
220 pub field_init: Option<Expression>,
222 pub is_async: bool,
224 pub is_generator: bool,
226}
227
228#[derive(Debug, Clone, PartialEq)]
229pub enum VarKind {
230 Var,
231 Let,
232 Const,
233 Using,
236 AwaitUsing,
238}
239
240#[derive(Debug, Clone, PartialEq)]
242pub enum Pattern {
243 Identifier(Rc<str>),
244 Object(Vec<ObjPatProp>),
246 Array(Vec<ArrPatElem>),
248 Expr(Box<Expression>),
251}
252
253#[derive(Debug, Clone, PartialEq)]
255pub struct ObjPatProp {
256 pub key: Rc<str>,
259 pub computed_key: Option<Expression>,
261 pub value: Pattern,
263 pub default: Option<Expression>,
264 pub is_rest: bool,
265}
266
267#[derive(Debug, Clone, PartialEq)]
269pub struct ArrPatElem {
270 pub pattern: Option<Pattern>,
272 pub default: Option<Expression>,
273 pub is_rest: bool,
274}
275
276#[derive(Debug, Clone, PartialEq)]
278pub struct Param {
279 pub pattern: Pattern,
280 pub default: Option<Box<Expression>>,
281 pub is_rest: bool,
282}
283
284#[derive(Debug, Clone, PartialEq)]
285pub enum Statement {
286 Expression(Expression),
287 VarDeclaration {
288 kind: VarKind,
289 decls: Vec<(Pattern, Option<Expression>)>,
291 },
292 Block(Vec<Statement>),
293 If {
294 test: Box<Expression>,
295 consequent: Box<Statement>,
296 alternate: Option<Box<Statement>>,
297 },
298 While {
299 test: Expression,
300 body: Box<Statement>,
301 },
302 DoWhile {
303 body: Box<Statement>,
304 test: Expression,
305 },
306 For {
307 init: Option<Box<Statement>>,
308 test: Option<Box<Expression>>,
309 update: Option<Box<Expression>>,
310 body: Box<Statement>,
311 },
312 ForIn {
313 decl_kind: Option<VarKind>,
314 pattern: Pattern,
315 object: Box<Expression>,
316 body: Box<Statement>,
317 of: bool, is_await: bool,
321 },
322 FunctionDeclaration {
323 name: Rc<str>,
324 params: Rc<Vec<Param>>,
325 body: Rc<FnBody>,
326 is_async: bool,
327 is_generator: bool,
328 },
329 Return(Option<Expression>),
330 Break(Option<Rc<str>>),
332 Continue(Option<Rc<str>>),
334 Labeled(Rc<str>, Box<Statement>),
337 Throw(Expression),
338 Switch {
339 discriminant: Box<Expression>,
340 cases: Vec<SwitchCase>,
341 },
342 Try(Box<TryStmt>),
345 Import(Box<ImportDecl>),
349 ExportNamed {
351 specifiers: Vec<(String, String)>,
353 source: Option<String>,
355 },
356 ExportDefault(Expression),
358 ExportDecl {
361 declaration: Box<Statement>,
362 names: Vec<String>,
363 },
364 ExportAll {
366 source: String,
367 },
368 InitPrivateBrand(u64),
370 InitPrivateField {
372 brand: u64,
373 name: Rc<str>,
374 init: Option<Box<Expression>>,
375 },
376 InitPublicField {
378 key: Rc<str>,
379 init: Option<Box<Expression>>,
380 },
381 ClassFieldInit {
383 stmts: Vec<Statement>,
384 priv_names: Vec<Rc<str>>,
385 },
386 With {
388 object: Box<Expression>,
389 body: Box<Statement>,
390 },
391 Empty,
392}
393
394#[derive(Debug, Clone, PartialEq)]
397pub struct TryStmt {
398 pub block: Vec<Statement>,
399 pub catch_param: Option<Box<Pattern>>,
401 pub catch_block: Option<Vec<Statement>>,
402 pub finally_block: Option<Vec<Statement>>,
403}
404
405#[derive(Debug, Clone, PartialEq)]
406pub struct ImportDecl {
407 pub source: String,
409 pub default: Option<String>,
411 pub namespace: Option<String>,
413 pub named: Vec<(String, String)>,
415 pub side_effect_only: bool,
417}
418
419#[derive(Debug, Clone, PartialEq)]
420pub struct SwitchCase {
421 pub test: Option<Expression>,
422 pub body: Vec<Statement>,
423}
424
425#[derive(Debug, Clone, PartialEq)]
426pub struct Program {
427 pub body: Vec<Statement>,
428}
429
430pub(crate) const CODE_AFTER_CALLS: u32 = 2;
434
435#[derive(Debug, Clone, Default, PartialEq, Eq)]
436pub struct EvalSyntaxCtx {
437 pub in_function: bool,
438 pub allow_super_call: bool,
439 pub allow_super_prop: bool,
440 pub in_field_init: bool,
441 pub in_static_block: bool,
442 pub private_names: Vec<Rc<str>>,
443}
444
445pub struct FnBody {
450 state: RefCell<FnBodyState>,
451 pub strict: bool,
454 uses_args: core::cell::Cell<u8>,
456 has_func_decl: core::cell::Cell<u8>,
458 var_names: RefCell<Option<Rc<Vec<Rc<str>>>>>,
462 code: RefCell<Option<BodyCode>>,
465 code_calls: Cell<u32>,
467 shared_info: RefCell<Option<alloc::rc::Weak<super::value::SharedFnInfo>>>,
469 source_text: RefCell<Option<(Rc<str>, u32, u32)>>,
473 eval_ctx: RefCell<Option<EvalSyntaxCtx>>,
474 is_method: Cell<bool>,
476}
477
478enum BodyCode {
480 Func(Option<Rc<super::interp::bytecode::Code>>),
481 Gen(Option<Rc<super::interp::gen_vm::GenCode>>),
482}
483
484pub static LAZY_KIND: [core::sync::atomic::AtomicU64; 3] = [const { core::sync::atomic::AtomicU64::new(0) }; 3];
486
487enum FnBodyState {
488 Parsed(Rc<Vec<Statement>>),
489 Source {
490 src: Rc<str>,
491 start: u32,
492 end: u32,
493 calls: u8,
494 atoms: Option<super::lexer::SharedAtoms>,
496 },
497}
498
499impl FnBody {
500 pub fn parsed(stmts: Vec<Statement>) -> Rc<Self> {
501 Self::parsed_with(stmts, false)
502 }
503
504 pub fn parsed_with(stmts: Vec<Statement>, strict: bool) -> Rc<Self> {
505 Rc::new(Self {
506 state: RefCell::new(FnBodyState::Parsed(Rc::new(stmts))),
507 strict,
508 uses_args: core::cell::Cell::new(0),
509 has_func_decl: core::cell::Cell::new(0),
510 var_names: RefCell::new(None),
511 code: RefCell::new(None),
512 code_calls: Cell::new(0),
513 shared_info: RefCell::new(None),
514 source_text: RefCell::new(None),
515 eval_ctx: RefCell::new(None),
516 is_method: Cell::new(false),
517 })
518 }
519
520 pub fn from_rc(stmts: Rc<Vec<Statement>>) -> Rc<Self> {
521 Rc::new(Self {
522 state: RefCell::new(FnBodyState::Parsed(stmts)),
523 strict: false,
524 uses_args: core::cell::Cell::new(0),
525 has_func_decl: core::cell::Cell::new(0),
526 var_names: RefCell::new(None),
527 code: RefCell::new(None),
528 code_calls: Cell::new(0),
529 shared_info: RefCell::new(None),
530 source_text: RefCell::new(None),
531 eval_ctx: RefCell::new(None),
532 is_method: Cell::new(false),
533 })
534 }
535
536 pub fn lazy(source: String, strict: bool) -> Rc<Self> {
537 let len = source.len() as u32;
538 Self::lazy_range(Rc::from(source.into_boxed_str()), 0, len, strict, None)
539 }
540
541 pub fn lazy_range(src: Rc<str>, start: u32, end: u32, strict: bool, atoms: Option<super::lexer::SharedAtoms>) -> Rc<Self> {
542 Rc::new(Self {
543 state: RefCell::new(FnBodyState::Source {
544 src,
545 start,
546 end,
547 calls: 0,
548 atoms,
549 }),
550 strict,
551 uses_args: core::cell::Cell::new(0),
552 has_func_decl: core::cell::Cell::new(0),
553 var_names: RefCell::new(None),
554 code: RefCell::new(None),
555 code_calls: Cell::new(0),
556 shared_info: RefCell::new(None),
557 source_text: RefCell::new(None),
558 eval_ctx: RefCell::new(None),
559 is_method: Cell::new(false),
560 })
561 }
562 pub fn set_eval_ctx(&self, ctx: EvalSyntaxCtx) {
563 *self.eval_ctx.borrow_mut() = Some(ctx);
564 }
565 pub fn eval_ctx(&self) -> Option<EvalSyntaxCtx> {
566 self.eval_ctx.borrow().clone()
567 }
568 pub fn mark_method(&self) {
570 self.is_method.set(true);
571 }
572 pub fn is_method(&self) -> bool {
573 self.is_method.get()
574 }
575 pub fn set_source_text(&self, src: Rc<str>, start: u32, end: u32) {
577 *self.source_text.borrow_mut() = Some((src, start, end));
578 }
579
580 pub fn copy_source_from(&self, other: &FnBody) {
582 let v = other.source_text.borrow().clone();
583 *self.source_text.borrow_mut() = v;
584 }
585
586 pub fn source_text(&self) -> Option<String> {
588 let b = self.source_text.borrow();
589 let (src, s, e) = b.as_ref()?;
590 src.get(*s as usize..*e as usize).map(String::from)
591 }
592
593 pub fn source_head(&self, n: usize) -> Option<String> {
598 let b = self.source_text.borrow();
599 let (src, s, e) = b.as_ref()?;
600 src.get(*s as usize..*e as usize).map(|t| t.chars().take(n).collect())
601 }
602
603 pub fn get_or_create_shared_info(
605 self: &Rc<Self>,
606 name: &str,
607 params: &Rc<Vec<Param>>,
608 flags: u8,
609 ) -> Rc<super::value::SharedFnInfo> {
610 if let Some(existing) = self.shared_info.borrow().as_ref().and_then(|w| w.upgrade()) {
611 return existing;
612 }
613 let mut full_flags = flags & !super::value::FN_FLAG_SIMPLE_PARAMS;
614 if compute_simple_unique_params(params) {
615 full_flags |= super::value::FN_FLAG_SIMPLE_PARAMS;
616 }
617 let shared = Rc::new(super::value::SharedFnInfo {
618 name: name.into(),
619 params: params.clone(),
620 body: self.clone(),
621 flags: full_flags,
622 });
623 *self.shared_info.borrow_mut() = Some(Rc::downgrade(&shared));
624 shared
625 }
626
627
628 pub fn cached_var_names(&self) -> Option<Rc<Vec<Rc<str>>>> {
630 self.var_names.borrow().clone()
631 }
632
633 pub fn store_var_names(&self, stmts: &Rc<Vec<Statement>>, names: Rc<Vec<Rc<str>>>) {
636 let cached = matches!(&*self.state.borrow(), FnBodyState::Parsed(s) if Rc::ptr_eq(s, stmts));
637 if cached {
638 *self.var_names.borrow_mut() = Some(names);
639 }
640 }
641
642 pub(crate) fn code(&self, stmts: &Rc<Vec<Statement>>) -> Option<Rc<super::interp::bytecode::Code>> {
645 if let Some(BodyCode::Func(c)) = &*self.code.borrow() {
646 return c.clone();
647 }
648 if !matches!(&*self.state.borrow(), FnBodyState::Parsed(s) if Rc::ptr_eq(s, stmts)) {
649 return None;
650 }
651 let calls = self.code_calls.get() + 1;
652 self.code_calls.set(calls);
653 if calls < CODE_AFTER_CALLS && !stmts_has_loop(stmts) {
654 return None;
655 }
656 let c = super::interp::bytecode::compile(stmts).map(Rc::new);
657 *self.code.borrow_mut() = Some(BodyCode::Func(c.clone()));
658 c
659 }
660
661 pub(crate) fn gen_code(&self, stmts: &Rc<Vec<Statement>>) -> Option<Rc<super::interp::gen_vm::GenCode>> {
664 if let Some(BodyCode::Gen(c)) = &*self.code.borrow() {
665 return c.clone();
666 }
667 let c = super::interp::gen_vm::compile_gen(stmts).map(Rc::new);
668 if matches!(&*self.state.borrow(), FnBodyState::Parsed(s) if Rc::ptr_eq(s, stmts)) {
669 *self.code.borrow_mut() = Some(BodyCode::Gen(c.clone()));
670 }
671 c
672 }
673
674 pub fn is_lazy(&self) -> bool {
676 matches!(&*self.state.borrow(), FnBodyState::Source { .. })
677 }
678
679 pub fn stmts(&self) -> Rc<Vec<Statement>> {
690 enum Action {
691 Cached(Rc<Vec<Statement>>),
692 ParseOnce(Rc<str>, u32, u32),
693 ParseAndDrop(Rc<str>, u32, u32),
694 ParseAndCache(Rc<str>, u32, u32),
695 }
696 let mut atoms_for_parse: Option<super::lexer::SharedAtoms> = None;
697 let action = {
698 let mut b = self.state.borrow_mut();
699 if let FnBodyState::Source { atoms, .. } = &*b {
700 atoms_for_parse = atoms.clone();
701 }
702 match &mut *b {
703 FnBodyState::Parsed(s) => Action::Cached(s.clone()),
704 FnBodyState::Source {
705 src,
706 start,
707 end,
708 calls,
709 ..
710 } => {
711 let s = src.clone();
712 let st = *start;
713 let en = *end;
714 if en.saturating_sub(st) >= 65_536 && *calls == 0 {
715 *calls = 1;
721 Action::ParseAndDrop(s, st, en)
722 } else if *calls == 0 {
723 *calls = 1;
724 Action::ParseOnce(s, st, en)
725 } else {
726 *b = FnBodyState::Parsed(Rc::new(Vec::new()));
727 Action::ParseAndCache(s, st, en)
728 }
729 }
730 }
731 };
732 match &action {
734 Action::ParseOnce(_, a, b) => LAZY_KIND.first().map(|x| x.fetch_add((*b - *a) as u64, core::sync::atomic::Ordering::Relaxed)),
735 Action::ParseAndCache(_, a, b) => LAZY_KIND.get(1).map(|x| x.fetch_add((*b - *a) as u64, core::sync::atomic::Ordering::Relaxed)),
736 Action::ParseAndDrop(_, a, b) => LAZY_KIND.get(2).map(|x| x.fetch_add((*b - *a) as u64, core::sync::atomic::Ordering::Relaxed)),
737 Action::Cached(_) => None,
738 };
739 match action {
740 Action::Cached(s) => s,
741 Action::ParseOnce(src, start, end) => {
742 let parsed = Rc::new(super::parser::parse_function_body_range(
743 src,
744 start as usize,
745 end as usize,
746 self.strict,
747 atoms_for_parse.clone(),
748 ));
749 if end.saturating_sub(start) < 16_384 && stmts_has_loop(&parsed) {
750 *self.state.borrow_mut() = FnBodyState::Parsed(parsed.clone());
751 }
752 parsed
753 }
754 Action::ParseAndDrop(src, start, end) => {
755 Rc::new(super::parser::parse_function_body_range(
756 src,
757 start as usize,
758 end as usize,
759 self.strict,
760 atoms_for_parse.clone(),
761 ))
762 }
763 Action::ParseAndCache(src, start, end) => {
764 let parsed = Rc::new(super::parser::parse_function_body_range(
765 src,
766 start as usize,
767 end as usize,
768 self.strict,
769 atoms_for_parse.clone(),
770 ));
771 *self.state.borrow_mut() = FnBodyState::Parsed(parsed.clone());
772 parsed
773 }
774 }
775 }
776
777 pub fn uses_arguments(&self, stmts: &[Statement]) -> bool {
779 match self.uses_args.get() {
780 1 => false,
781 2 => true,
782 _ => {
783 let u = stmts_use_arguments(stmts);
784 self.uses_args.set(if u { 2 } else { 1 });
785 u
786 }
787 }
788 }
789
790 #[inline]
792 pub fn has_function_decls(&self, stmts: &[Statement]) -> bool {
793 match self.has_func_decl.get() {
794 1 => false,
795 2 => true,
796 _ => {
797 let has = stmts.iter().any(|s| match s {
798 Statement::FunctionDeclaration { .. } => true,
799 Statement::ExportDecl { declaration, .. } => {
800 matches!(**declaration, Statement::FunctionDeclaration { .. })
801 }
802 _ => false,
803 });
804 self.has_func_decl.set(if has { 2 } else { 1 });
805 has
806 }
807 }
808 }
809
810 fn raw_might_use_arguments(&self) -> bool {
811 match self.uses_args.get() {
812 1 => false,
813 2 => true,
814 _ => match &*self.state.borrow() {
815 FnBodyState::Source {
816 src, start, end, ..
817 } => {
818 let slice = src.get(*start as usize..*end as usize).unwrap_or("");
819 slice.contains("arguments") || slice.contains("eval")
820 }
821 FnBodyState::Parsed(s) => {
822 let u = stmts_use_arguments(s);
823 self.uses_args.set(if u { 2 } else { 1 });
824 u
825 }
826 },
827 }
828 }
829}
830
831fn compute_simple_unique_params(params: &[Param]) -> bool {
832 if params.len() > 16 {
833 return false;
834 }
835 for (i, p) in params.iter().enumerate() {
836 if p.is_rest || p.default.is_some() {
837 return false;
838 }
839 let Pattern::Identifier(name) = &p.pattern else {
840 return false;
841 };
842 for prev in ¶ms[..i] {
843 if let Pattern::Identifier(pn) = &prev.pattern {
844 if Rc::ptr_eq(name, pn) || **name == **pn {
845 return false;
846 }
847 }
848 }
849 }
850 true
851}
852
853fn stmts_use_arguments(stmts: &[Statement]) -> bool {
854 stmts.iter().any(stmt_uses_arguments)
855}
856
857fn stmt_uses_arguments(stmt: &Statement) -> bool {
858 match stmt {
859 Statement::Expression(e)
860 | Statement::Return(Some(e))
861 | Statement::Throw(e)
862 | Statement::ExportDefault(e) => expr_uses_arguments(e),
863 Statement::VarDeclaration { decls, .. } => decls
864 .iter()
865 .any(|(p, init)| pat_uses_arguments(p) || init.as_ref().is_some_and(expr_uses_arguments)),
866 Statement::Block(b) => stmts_use_arguments(b),
867 Statement::If {
868 test,
869 consequent,
870 alternate,
871 } => {
872 expr_uses_arguments(test)
873 || stmt_uses_arguments(consequent)
874 || alternate.as_deref().is_some_and(stmt_uses_arguments)
875 }
876 Statement::While { test, body } | Statement::DoWhile { body, test } => {
877 expr_uses_arguments(test) || stmt_uses_arguments(body)
878 }
879 Statement::For {
880 init,
881 test,
882 update,
883 body,
884 } => {
885 init.as_deref().is_some_and(stmt_uses_arguments)
886 || test.as_deref().is_some_and(expr_uses_arguments)
887 || update.as_deref().is_some_and(expr_uses_arguments)
888 || stmt_uses_arguments(body)
889 }
890 Statement::ForIn {
891 pattern,
892 object,
893 body,
894 ..
895 } => {
896 pat_uses_arguments(pattern)
897 || expr_uses_arguments(object)
898 || stmt_uses_arguments(body)
899 }
900 Statement::Labeled(_, s) | Statement::ExportDecl { declaration: s, .. } => {
901 stmt_uses_arguments(s)
902 }
903 Statement::ClassFieldInit { stmts, .. } => stmts_use_arguments(stmts),
904 Statement::With { object, body } => {
905 expr_uses_arguments(object) || stmt_uses_arguments(body)
906 }
907 Statement::Switch {
908 discriminant,
909 cases,
910 } => {
911 expr_uses_arguments(discriminant)
912 || cases.iter().any(|c| {
913 c.test.as_ref().is_some_and(expr_uses_arguments)
914 || stmts_use_arguments(&c.body)
915 })
916 }
917 Statement::Try(t) => {
918 let TryStmt {
919 block,
920 catch_param,
921 catch_block,
922 finally_block,
923 } = &**t;
924 stmts_use_arguments(block)
925 || catch_param.as_deref().is_some_and(pat_uses_arguments)
926 || catch_block.as_deref().is_some_and(stmts_use_arguments)
927 || finally_block.as_deref().is_some_and(stmts_use_arguments)
928 }
929 Statement::InitPrivateField { init: Some(e), .. } | Statement::InitPublicField { init: Some(e), .. } => {
931 expr_uses_arguments(e)
932 }
933 Statement::InitPrivateBrand(_)
934 | Statement::InitPrivateField { init: None, .. }
935 | Statement::InitPublicField { init: None, .. }
936 | Statement::FunctionDeclaration { .. }
937 | Statement::Return(None)
938 | Statement::Break(_)
939 | Statement::Continue(_)
940 | Statement::Import(_)
941 | Statement::ExportNamed { .. }
942 | Statement::ExportAll { .. }
943 | Statement::Empty => false,
944 }
945}
946
947fn pat_uses_arguments(pat: &Pattern) -> bool {
948 match pat {
949 Pattern::Identifier(n) => &**n == "arguments" || &**n == "eval",
950 Pattern::Object(props) => props.iter().any(|p| {
951 p.computed_key.as_ref().is_some_and(expr_uses_arguments)
952 || pat_uses_arguments(&p.value)
953 || p.default.as_ref().is_some_and(expr_uses_arguments)
954 }),
955 Pattern::Array(elems) => elems.iter().any(|e| {
956 e.pattern.as_ref().is_some_and(pat_uses_arguments)
957 || e.default.as_ref().is_some_and(expr_uses_arguments)
958 }),
959 Pattern::Expr(e) => expr_uses_arguments(e),
960 }
961}
962
963fn expr_uses_arguments(expr: &Expression) -> bool {
964 match expr {
965 Expression::Identifier(n) => &**n == "arguments" || &**n == "eval",
966 Expression::TemplateLiteral { exprs, .. } => exprs.iter().any(expr_uses_arguments),
967 Expression::Array(exprs) | Expression::Sequence(exprs) => {
968 exprs.iter().any(expr_uses_arguments)
969 }
970 Expression::TaggedTemplate { tag, exprs, .. } => {
971 expr_uses_arguments(tag) || exprs.iter().any(expr_uses_arguments)
972 }
973 Expression::Object(props) => props.iter().any(|p| {
974 p.computed.as_ref().is_some_and(expr_uses_arguments) || expr_uses_arguments(&p.value)
975 }),
976 Expression::Function {
977 params,
978 body,
979 is_arrow,
980 ..
981 } => {
982 if !*is_arrow {
983 false
984 } else {
985 params.iter().any(|p| {
986 pat_uses_arguments(&p.pattern)
987 || p.default.as_deref().is_some_and(expr_uses_arguments)
988 }) || body.raw_might_use_arguments()
989 }
990 }
991 Expression::Await(e)
992 | Expression::Unary { expr: e, .. }
993 | Expression::Update { target: e, .. }
994 | Expression::Spread(e)
995 | Expression::Member { object: e, .. } => expr_uses_arguments(e),
996 Expression::Yield { argument, .. } => argument.as_deref().is_some_and(expr_uses_arguments),
997 Expression::Binary { left, right, .. }
998 | Expression::Logical { left, right, .. }
999 | Expression::Assign {
1000 target: left,
1001 value: right,
1002 ..
1003 }
1004 | Expression::Index {
1005 object: left,
1006 index: right,
1007 ..
1008 } => expr_uses_arguments(left) || expr_uses_arguments(right),
1009 Expression::Conditional {
1010 test,
1011 consequent,
1012 alternate,
1013 } => {
1014 expr_uses_arguments(test)
1015 || expr_uses_arguments(consequent)
1016 || expr_uses_arguments(alternate)
1017 }
1018 Expression::Call {
1019 callee, arguments, ..
1020 }
1021 | Expression::New { callee, arguments } => {
1022 expr_uses_arguments(callee) || arguments.iter().any(expr_uses_arguments)
1023 }
1024 Expression::Class {
1025 superclass,
1026 members,
1027 ..
1028 } => {
1029 superclass.as_deref().is_some_and(expr_uses_arguments)
1030 || members.iter().any(|m| {
1031 m.computed_key.as_ref().is_some_and(expr_uses_arguments)
1032 || m.field_init.as_ref().is_some_and(expr_uses_arguments)
1033 })
1034 }
1035 Expression::Number(_)
1036 | Expression::BigIntLit(_)
1037 | Expression::Str(_)
1038 | Expression::Bool(_)
1039 | Expression::Null
1040 | Expression::Undefined
1041 | Expression::Elision
1042 | Expression::This
1043 | Expression::Super
1044 | Expression::NewTarget
1045 | Expression::Regex(_) => false,
1046 }
1047}
1048
1049impl core::fmt::Debug for FnBody {
1050 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1051 match &*self.state.borrow() {
1052 FnBodyState::Parsed(s) => write!(f, "FnBody({} stmts)", s.len()),
1053 FnBodyState::Source { start, end, .. } => {
1054 write!(f, "FnBody(lazy {} chars)", end.saturating_sub(*start))
1055 }
1056 }
1057 }
1058}
1059
1060impl PartialEq for FnBody {
1062 fn eq(&self, other: &Self) -> bool {
1063 core::ptr::eq(self, other)
1064 }
1065}
1066
1067fn stmt_has_loop(s: &Statement) -> bool {
1068 match s {
1069 Statement::While { .. }
1070 | Statement::DoWhile { .. }
1071 | Statement::For { .. }
1072 | Statement::ForIn { .. } => true,
1073 Statement::Block(body) => stmts_has_loop(body),
1074 Statement::If { consequent, alternate, .. } => {
1075 stmt_has_loop(consequent) || alternate.as_deref().is_some_and(stmt_has_loop)
1076 }
1077 Statement::Labeled(_, inner) | Statement::With { body: inner, .. } => stmt_has_loop(inner),
1078 Statement::ClassFieldInit { stmts, .. } => stmts_has_loop(stmts),
1079 Statement::Try(t) => {
1080 stmts_has_loop(&t.block)
1081 || t.catch_block.as_ref().is_some_and(|cb| stmts_has_loop(cb))
1082 || t.finally_block.as_ref().is_some_and(|fb| stmts_has_loop(fb))
1083 }
1084 Statement::Switch { cases, .. } => cases.iter().any(|c| stmts_has_loop(&c.body)),
1085 _ => false,
1086 }
1087}
1088
1089pub(crate) fn stmts_has_loop(stmts: &[Statement]) -> bool {
1090 stmts.iter().any(stmt_has_loop)
1091}