forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
top_level_binding_collector.rs
93 lines (81 loc) · 2.55 KB
/
top_level_binding_collector.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use swc_common::collections::AHashSet;
use swc_ecmascript::{
ast::{
ArrowExpr, ClassDecl, FnDecl, Function, Id, ImportDefaultSpecifier, ImportNamedSpecifier,
ImportStarAsSpecifier, ObjectPatProp, Pat, VarDeclarator,
},
visit::{noop_visit_type, Visit, VisitWith},
};
// Modified from swc_ecma_utils/src/lib.rs:BindingCollector.
pub struct TopLevelBindingCollector {
bindings: AHashSet<Id>,
in_pat_decl: bool,
}
impl TopLevelBindingCollector {
fn add(&mut self, i: &Id) {
self.bindings.insert(i.clone());
}
}
impl Visit for TopLevelBindingCollector {
noop_visit_type!();
fn visit_class_decl(&mut self, node: &ClassDecl) {
self.add(&node.ident.to_id());
}
fn visit_fn_decl(&mut self, node: &FnDecl) {
self.add(&node.ident.to_id());
}
fn visit_pat(&mut self, node: &Pat) {
if !self.in_pat_decl {
return;
}
match node {
Pat::Ident(i) => self.add(&i.id.to_id()),
Pat::Object(o) => {
for prop in o.props.iter() {
match prop {
ObjectPatProp::Assign(a) => self.add(&a.key.to_id()),
ObjectPatProp::KeyValue(k) => k.value.visit_with(self),
ObjectPatProp::Rest(_) => {}
}
}
}
Pat::Array(a) => {
for elem in a.elems.iter() {
elem.visit_with(self);
}
}
Pat::Assign(a) => {
a.left.visit_with(self);
}
_ => {}
}
}
fn visit_arrow_expr(&mut self, _: &ArrowExpr) {}
fn visit_function(&mut self, _: &Function) {}
fn visit_import_default_specifier(&mut self, node: &ImportDefaultSpecifier) {
self.add(&node.local.to_id());
}
fn visit_import_named_specifier(&mut self, node: &ImportNamedSpecifier) {
self.add(&node.local.to_id());
}
fn visit_import_star_as_specifier(&mut self, node: &ImportStarAsSpecifier) {
self.add(&node.local.to_id());
}
fn visit_var_declarator(&mut self, node: &VarDeclarator) {
let old = self.in_pat_decl;
self.in_pat_decl = true;
node.name.visit_with(self);
self.in_pat_decl = old;
}
}
pub fn collect_top_level_decls<N>(n: &N) -> AHashSet<Id>
where
N: VisitWith<TopLevelBindingCollector>,
{
let mut v = TopLevelBindingCollector {
bindings: Default::default(),
in_pat_decl: false,
};
n.visit_with(&mut v);
v.bindings
}