/
typeof_replacer.rs
52 lines (47 loc) 路 1.55 KB
/
typeof_replacer.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use std::collections::HashSet;
use swc_atoms::JsWord;
use swc_ecmascript::ast::{Expr, Lit, Str, StrKind, UnaryOp};
use swc_ecmascript::visit::{Fold, FoldWith};
use crate::id;
use crate::utils::IdentId;
pub struct TypeOfReplacer<'a> {
pub decls: &'a HashSet<IdentId>,
}
impl<'a> Fold for TypeOfReplacer<'a> {
fn fold_expr(&mut self, node: Expr) -> Expr {
if let Expr::Unary(ref unary) = node {
// typeof require -> "function"
// typeof module -> "object"
if unary.op == UnaryOp::TypeOf {
if let Expr::Ident(ident) = &*unary.arg {
if ident.sym == js_word!("require") && !self.decls.contains(&id!(ident)) {
return Expr::Lit(Lit::Str(Str {
kind: StrKind::Synthesized,
has_escape: false,
span: unary.span,
value: js_word!("function"),
}));
}
let exports: JsWord = "exports".into();
if ident.sym == exports && !self.decls.contains(&id!(ident)) {
return Expr::Lit(Lit::Str(Str {
kind: StrKind::Synthesized,
has_escape: false,
span: unary.span,
value: js_word!("object"),
}));
}
if ident.sym == js_word!("module") && !self.decls.contains(&id!(ident)) {
return Expr::Lit(Lit::Str(Str {
kind: StrKind::Synthesized,
has_escape: false,
span: unary.span,
value: js_word!("object"),
}));
}
}
}
}
node.fold_children_with(self)
}
}