fix(es/utils): Fix extract_var_ids (#2798)

swc_ecma_utils:
 - `extract_var_ids`: Handle assignment object pattern property.
This commit is contained in:
David Sherret 2021-11-18 13:02:08 -05:00 committed by GitHub
parent ca55539938
commit 02ffe8a289
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 60 additions and 0 deletions

1
Cargo.lock generated
View File

@ -3093,6 +3093,7 @@ dependencies = [
"swc_atoms 0.2.9",
"swc_common",
"swc_ecma_ast",
"swc_ecma_parser",
"swc_ecma_visit",
"testing",
"unicode-xid",

View File

@ -26,3 +26,4 @@ unicode-xid = "0.2"
[dev-dependencies]
testing = {version = "0.15.0", path = "../testing"}
swc_ecma_parser = {version = "0.78.4", path = "../swc_ecma_parser"}

View File

@ -411,6 +411,12 @@ pub struct Hoister {
impl Visit for Hoister {
noop_visit_type!();
fn visit_assign_pat_prop(&mut self, node: &AssignPatProp, _: &dyn Node) {
node.value.visit_with(node, self);
self.vars.push(node.key.clone());
}
fn visit_assign_expr(&mut self, node: &AssignExpr, _: &dyn Node) {
node.right.visit_children_with(self);
}
@ -2326,3 +2332,55 @@ where
n.visit_with(&Invalid { span: DUMMY_SP }, &mut v);
v.bindings
}
#[cfg(test)]
mod test {
use swc_common::{input::StringInput, BytePos};
use swc_ecma_parser::{Parser, Syntax};
use super::*;
#[test]
fn test_collect_decls() {
run_collect_decls(
"const { a, b = 1, inner: { c }, ...d } = {};",
&["a", "b", "c", "d"],
);
run_collect_decls("const [ a, b = 1, [c], ...d ] = [];", &["a", "b", "c", "d"]);
}
fn run_collect_decls(text: &str, expected_names: &[&str]) {
let module = parse_module(text);
let decls: AHashSet<Id> = collect_decls(&module);
let mut names = decls.iter().map(|d| d.0.to_string()).collect::<Vec<_>>();
names.sort();
assert_eq!(names, expected_names);
}
#[test]
fn test_extract_var_ids() {
run_extract_var_ids(
"var { a, b = 1, inner: { c }, ...d } = {};",
&["a", "b", "c", "d"],
);
run_extract_var_ids("var [ a, b = 1, [c], ...d ] = [];", &["a", "b", "c", "d"]);
}
fn run_extract_var_ids(text: &str, expected_names: &[&str]) {
let module = parse_module(text);
let decls = extract_var_ids(&module);
let mut names = decls.iter().map(|d| d.sym.to_string()).collect::<Vec<_>>();
names.sort();
assert_eq!(names, expected_names);
}
fn parse_module(text: &str) -> Module {
let syntax = Syntax::Es(Default::default());
let mut p = Parser::new(
syntax,
StringInput::new(text, BytePos(0), BytePos(text.len() as u32)),
None,
);
p.parse_module().unwrap()
}
}