|
| 1 | +use crate::util::MapWithMut; |
| 2 | +use phf::phf_set; |
| 3 | +use swc_ecma_ast::*; |
| 4 | +use swc_ecma_utils::{prepend_stmts, StmtLike}; |
| 5 | +use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}; |
| 6 | + |
| 7 | +static HOIST_METHODS: phf::Set<&str> = phf_set![ |
| 8 | + "mock", |
| 9 | + "unmock", |
| 10 | + "enableAutomock", |
| 11 | + "disableAutomock", |
| 12 | + "deepUnmock" |
| 13 | +]; |
| 14 | + |
| 15 | +pub fn jest() -> impl Fold { |
| 16 | + as_folder(Jest) |
| 17 | +} |
| 18 | + |
| 19 | +struct Jest; |
| 20 | + |
| 21 | +impl Jest { |
| 22 | + fn visit_mut_stmt_like<T>(&mut self, orig: &mut Vec<T>) |
| 23 | + where |
| 24 | + T: StmtLike + VisitMutWith<Self>, |
| 25 | + { |
| 26 | + for item in &mut *orig { |
| 27 | + item.visit_mut_with(self); |
| 28 | + } |
| 29 | + |
| 30 | + let items = orig.take(); |
| 31 | + |
| 32 | + let mut new = Vec::with_capacity(items.len()); |
| 33 | + let mut hoisted = Vec::with_capacity(8); |
| 34 | + items.into_iter().for_each(|item| { |
| 35 | + match item.try_into_stmt() { |
| 36 | + Ok(stmt) => match &stmt { |
| 37 | + Stmt::Expr(ExprStmt { expr, .. }) => match &**expr { |
| 38 | + Expr::Call(CallExpr { |
| 39 | + callee: ExprOrSuper::Expr(callee), |
| 40 | + .. |
| 41 | + }) => match &**callee { |
| 42 | + Expr::Member( |
| 43 | + callee |
| 44 | + @ |
| 45 | + MemberExpr { |
| 46 | + computed: false, .. |
| 47 | + }, |
| 48 | + ) => match &callee.obj { |
| 49 | + ExprOrSuper::Super(_) => {} |
| 50 | + ExprOrSuper::Expr(callee_obj) => match &**callee_obj { |
| 51 | + Expr::Ident(i) if i.sym == *"jest" => match &*callee.prop { |
| 52 | + Expr::Ident(prop) if HOIST_METHODS.contains(&*prop.sym) => { |
| 53 | + hoisted.push(T::from_stmt(stmt)); |
| 54 | + return; |
| 55 | + } |
| 56 | + _ => new.push(T::from_stmt(stmt)), |
| 57 | + }, |
| 58 | + _ => new.push(T::from_stmt(stmt)), |
| 59 | + }, |
| 60 | + }, |
| 61 | + _ => new.push(T::from_stmt(stmt)), |
| 62 | + }, |
| 63 | + _ => new.push(T::from_stmt(stmt)), |
| 64 | + }, |
| 65 | + |
| 66 | + _ => new.push(T::from_stmt(stmt)), |
| 67 | + }, |
| 68 | + Err(node) => new.push(node), |
| 69 | + }; |
| 70 | + }); |
| 71 | + |
| 72 | + prepend_stmts(&mut new, hoisted.into_iter()); |
| 73 | + |
| 74 | + *orig = new; |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +impl VisitMut for Jest { |
| 79 | + noop_visit_mut_type!(); |
| 80 | + |
| 81 | + fn visit_mut_stmts(&mut self, stmts: &mut Vec<Stmt>) { |
| 82 | + self.visit_mut_stmt_like(stmts) |
| 83 | + } |
| 84 | + |
| 85 | + fn visit_mut_module_items(&mut self, items: &mut Vec<ModuleItem>) { |
| 86 | + self.visit_mut_stmt_like(items) |
| 87 | + } |
| 88 | +} |
0 commit comments