file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
crates/swc_ecma_transforms_base/src/quote.rs | Rust | /// Not a public api.
#[doc(hidden)]
#[macro_export]
macro_rules! helper_expr {
(ts, $field_name:ident) => {{
$crate::helper_expr!(ts, ::swc_common::DUMMY_SP, $field_name)
}};
(ts, $span:expr, $field_name:ident) => {{
use swc_ecma_utils::{quote_ident, ExprFactory};
let mark = $crate::enable_helper!($field_name);
let ctxt = swc_common::SyntaxContext::empty().apply_mark(mark);
Expr::from(swc_ecma_utils::quote_ident!(
ctxt,
$span,
concat!("_", stringify!($field_name))
))
}};
($field_name:ident) => {{
$crate::helper_expr!(::swc_common::DUMMY_SP, $field_name)
}};
($span:expr, $field_name:ident) => {{
use swc_ecma_utils::{quote_ident, ExprFactory};
let mark = $crate::enable_helper!($field_name);
let ctxt = swc_common::SyntaxContext::empty().apply_mark(mark);
Expr::from(swc_ecma_utils::quote_ident!(
ctxt,
$span,
concat!("_", stringify!($field_name))
))
}};
}
/// Not a public api.
#[doc(hidden)]
#[macro_export]
macro_rules! helper {
($($t:tt)*) => {{
use swc_ecma_utils::ExprFactory;
$crate::helper_expr!($($t)*).as_callee()
}};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/src/rename/analyzer/mod.rs | Rust | use swc_common::Mark;
use swc_ecma_ast::*;
use swc_ecma_utils::stack_size::maybe_grow_default;
use swc_ecma_visit::{noop_visit_type, Visit, VisitWith};
use self::scope::{Scope, ScopeKind};
mod reverse_map;
pub(super) mod scope;
#[derive(Debug, Default)]
pub(super) struct Analyzer {
/// If `eval` exists for the current scope, we only rename synthesized
/// identifiers.
pub has_eval: bool,
/// The [Mark] which is parent of user-specified identifiers.
pub top_level_mark: Mark,
pub is_pat_decl: bool,
pub var_belong_to_fn_scope: bool,
pub in_catch_params: bool,
pub scope: Scope,
/// If we try add variables declared by `var` to the block scope,
/// variables will be added to `hoisted_vars` and merged to latest
/// function scope in the end.
pub hoisted_vars: Vec<Id>,
}
impl Analyzer {
fn add_decl(&mut self, id: Id, belong_to_fn_scope: bool) {
if belong_to_fn_scope {
match self.scope.kind {
ScopeKind::Fn => {
self.scope.add_decl(&id, self.has_eval, self.top_level_mark);
}
ScopeKind::Block => self.hoisted_vars.push(id),
}
} else {
self.scope.add_decl(&id, self.has_eval, self.top_level_mark);
}
}
fn reserve_decl(&mut self, len: usize, belong_to_fn_scope: bool) {
if belong_to_fn_scope {
match self.scope.kind {
ScopeKind::Fn => {
self.scope.reserve_decl(len);
}
ScopeKind::Block => {
self.hoisted_vars.reserve(len);
}
}
} else {
self.scope.reserve_decl(len);
}
}
fn add_usage(&mut self, id: Id) {
self.scope.add_usage(id);
}
fn reserve_usage(&mut self, len: usize) {
self.scope.reserve_usage(len);
}
fn with_scope<F>(&mut self, kind: ScopeKind, op: F)
where
F: FnOnce(&mut Analyzer),
{
{
let mut v = Analyzer {
has_eval: self.has_eval,
top_level_mark: self.top_level_mark,
is_pat_decl: self.is_pat_decl,
var_belong_to_fn_scope: false,
in_catch_params: false,
scope: Scope {
kind,
..Default::default()
},
hoisted_vars: Default::default(),
};
op(&mut v);
if !v.hoisted_vars.is_empty() {
debug_assert!(matches!(v.scope.kind, ScopeKind::Block));
self.reserve_usage(v.hoisted_vars.len());
v.hoisted_vars.clone().into_iter().for_each(|id| {
// For variables declared in block scope using `var` and `function`,
// We should create a fake usage in the block to prevent conflicted
// renaming.
v.add_usage(id);
});
match self.scope.kind {
ScopeKind::Fn => {
self.reserve_decl(v.hoisted_vars.len(), true);
v.hoisted_vars
.into_iter()
.for_each(|id| self.add_decl(id, true));
}
ScopeKind::Block => {
self.hoisted_vars.extend(v.hoisted_vars);
}
}
}
self.scope.children.push(v.scope);
}
}
fn with_fn_scope<F>(&mut self, op: F)
where
F: FnOnce(&mut Analyzer),
{
self.with_scope(ScopeKind::Fn, op)
}
fn visit_fn_body_within_same_scope(&mut self, body: &Option<BlockStmt>) {
if let Some(body) = &body {
body.visit_children_with(self);
}
}
fn visit_for_body_within_same_scope(&mut self, body: &Stmt) {
match body {
Stmt::Block(s) => s.visit_children_with(self),
_ => body.visit_with(self),
}
}
}
impl Visit for Analyzer {
noop_visit_type!();
fn visit_arrow_expr(&mut self, e: &ArrowExpr) {
self.with_fn_scope(|v| {
let old = v.is_pat_decl;
v.is_pat_decl = true;
e.params.visit_with(v);
v.is_pat_decl = false;
e.body.visit_with(v);
v.is_pat_decl = old;
});
}
fn visit_assign_target(&mut self, n: &AssignTarget) {
let old = self.is_pat_decl;
self.is_pat_decl = false;
n.visit_children_with(self);
self.is_pat_decl = old;
}
fn visit_binding_ident(&mut self, i: &BindingIdent) {
if self.is_pat_decl {
self.add_decl(i.to_id(), self.var_belong_to_fn_scope)
} else {
self.add_usage(i.to_id())
}
}
fn visit_block_stmt(&mut self, n: &BlockStmt) {
self.with_scope(ScopeKind::Block, |v| n.visit_children_with(v))
}
fn visit_block_stmt_or_expr(&mut self, n: &BlockStmtOrExpr) {
match n {
// This avoid crating extra block scope for arrow function
BlockStmtOrExpr::BlockStmt(n) => n.visit_children_with(self),
BlockStmtOrExpr::Expr(n) => n.visit_with(self),
}
}
fn visit_catch_clause(&mut self, n: &CatchClause) {
self.with_scope(ScopeKind::Block, |v| {
let old = v.is_pat_decl;
let old_in_catch_params = v.in_catch_params;
v.is_pat_decl = false;
n.body.visit_children_with(v);
v.is_pat_decl = true;
v.in_catch_params = true;
n.param.visit_with(v);
v.is_pat_decl = old;
v.in_catch_params = old_in_catch_params;
})
}
fn visit_class_decl(&mut self, c: &ClassDecl) {
self.add_decl(c.ident.to_id(), false);
c.class.visit_with(self);
}
fn visit_class_expr(&mut self, c: &ClassExpr) {
self.with_fn_scope(|v| {
if let Some(id) = &c.ident {
v.add_decl(id.to_id(), false);
}
c.class.visit_with(v);
})
}
fn visit_class_method(&mut self, f: &ClassMethod) {
f.key.visit_with(self);
self.with_fn_scope(|v| {
f.function.decorators.visit_with(v);
f.function.params.visit_with(v);
v.visit_fn_body_within_same_scope(&f.function.body);
})
}
fn visit_constructor(&mut self, f: &Constructor) {
self.with_fn_scope(|v| {
f.key.visit_with(v);
f.params.visit_with(v);
v.visit_fn_body_within_same_scope(&f.body);
})
}
fn visit_default_decl(&mut self, d: &DefaultDecl) {
match d {
DefaultDecl::Class(c) => {
if let Some(id) = &c.ident {
self.add_decl(id.to_id(), false);
}
self.with_fn_scope(|v| {
c.class.visit_with(v);
})
}
DefaultDecl::Fn(f) => {
if let Some(id) = &f.ident {
self.add_decl(id.to_id(), true);
}
f.visit_with(self);
}
DefaultDecl::TsInterfaceDecl(_) => {}
}
}
fn visit_export_named_specifier(&mut self, n: &ExportNamedSpecifier) {
match &n.orig {
ModuleExportName::Ident(orig) => {
self.add_usage(orig.to_id());
}
ModuleExportName::Str(..) => {}
};
}
fn visit_expr(&mut self, e: &Expr) {
let old_is_pat_decl = self.is_pat_decl;
self.is_pat_decl = false;
maybe_grow_default(|| e.visit_children_with(self));
if let Expr::Ident(i) = e {
self.add_usage(i.to_id());
}
self.is_pat_decl = old_is_pat_decl;
}
fn visit_fn_decl(&mut self, f: &FnDecl) {
self.add_decl(f.ident.to_id(), true);
// https://github.com/swc-project/swc/issues/6819
//
// We need to check for assign pattern because safari has a bug.
// https://github.com/swc-project/swc/issues/9015
let has_rest = f
.function
.params
.iter()
.any(|p| p.pat.is_rest() || p.pat.is_assign());
if has_rest {
self.add_usage(f.ident.to_id());
}
self.with_fn_scope(|v| {
if has_rest {
v.add_usage(f.ident.to_id());
}
f.function.decorators.visit_with(v);
f.function.params.visit_with(v);
// WARN: Option<BlockStmt>::visit_mut_children_wth
// is not same with BlockStmt::visit_mut_children_wth
v.visit_fn_body_within_same_scope(&f.function.body);
})
}
fn visit_fn_expr(&mut self, f: &FnExpr) {
if let Some(id) = &f.ident {
self.with_fn_scope(|v| {
v.add_decl(id.to_id(), true);
v.with_fn_scope(|v| {
// https://github.com/swc-project/swc/issues/6819
//
// We need to check for assign pattern because safari has a bug.
// https://github.com/swc-project/swc/issues/9015
if f.function
.params
.iter()
.any(|p| p.pat.is_rest() || p.pat.is_assign())
{
v.add_usage(id.to_id());
}
f.function.decorators.visit_with(v);
f.function.params.visit_with(v);
v.visit_fn_body_within_same_scope(&f.function.body);
});
})
} else {
f.function.visit_with(self)
}
}
fn visit_for_in_stmt(&mut self, n: &ForInStmt) {
self.with_scope(ScopeKind::Block, |v| {
n.left.visit_with(v);
n.right.visit_with(v);
v.with_scope(ScopeKind::Block, |v| {
v.visit_for_body_within_same_scope(&n.body);
})
});
}
fn visit_for_of_stmt(&mut self, n: &ForOfStmt) {
self.with_scope(ScopeKind::Block, |v| {
n.left.visit_with(v);
n.right.visit_with(v);
v.with_scope(ScopeKind::Block, |v| {
v.visit_for_body_within_same_scope(&n.body);
})
});
}
fn visit_for_stmt(&mut self, n: &ForStmt) {
self.with_scope(ScopeKind::Block, |v| {
n.init.visit_with(v);
n.test.visit_with(v);
n.update.visit_with(v);
v.with_scope(ScopeKind::Block, |v| {
v.visit_for_body_within_same_scope(&n.body);
})
});
}
// ensure param and function body always in same scope
fn visit_function(&mut self, f: &Function) {
self.with_fn_scope(|v| {
f.decorators.visit_with(v);
f.params.visit_with(v);
v.visit_fn_body_within_same_scope(&f.body);
})
}
fn visit_import_default_specifier(&mut self, n: &ImportDefaultSpecifier) {
self.add_decl(n.local.to_id(), true);
}
fn visit_import_named_specifier(&mut self, n: &ImportNamedSpecifier) {
self.add_decl(n.local.to_id(), true);
}
fn visit_import_star_as_specifier(&mut self, n: &ImportStarAsSpecifier) {
self.add_decl(n.local.to_id(), true);
}
fn visit_member_expr(&mut self, e: &MemberExpr) {
e.obj.visit_with(self);
if let MemberProp::Computed(c) = &e.prop {
c.visit_with(self);
}
}
fn visit_method_prop(&mut self, f: &MethodProp) {
f.key.visit_with(self);
f.function.visit_with(self)
}
fn visit_named_export(&mut self, n: &NamedExport) {
if n.src.is_some() {
return;
}
n.visit_children_with(self);
}
fn visit_param(&mut self, e: &Param) {
let old = self.is_pat_decl;
let old_need_hoisted = self.var_belong_to_fn_scope;
// Params belong to function scope.
// Params in catch clause belong to block scope
self.var_belong_to_fn_scope = !self.in_catch_params;
self.is_pat_decl = false;
e.decorators.visit_with(self);
self.is_pat_decl = true;
e.pat.visit_with(self);
self.is_pat_decl = old;
self.var_belong_to_fn_scope = old_need_hoisted
}
fn visit_prop(&mut self, p: &Prop) {
p.visit_children_with(self);
if let Prop::Shorthand(i) = p {
self.add_usage(i.to_id())
}
}
fn visit_static_block(&mut self, n: &StaticBlock) {
self.with_fn_scope(|v| n.body.visit_children_with(v))
}
fn visit_super_prop_expr(&mut self, e: &SuperPropExpr) {
if let SuperProp::Computed(c) = &e.prop {
c.visit_with(self);
}
}
fn visit_var_decl(&mut self, n: &VarDecl) {
let old_need_hoisted = self.var_belong_to_fn_scope;
self.var_belong_to_fn_scope = n.kind == VarDeclKind::Var;
n.visit_children_with(self);
self.var_belong_to_fn_scope = old_need_hoisted;
}
fn visit_var_declarator(&mut self, v: &VarDeclarator) {
let old = self.is_pat_decl;
self.is_pat_decl = true;
v.name.visit_with(self);
self.is_pat_decl = false;
v.init.visit_with(self);
self.is_pat_decl = old;
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/src/rename/analyzer/reverse_map.rs | Rust | use rustc_hash::FxHashMap;
use swc_atoms::Atom;
use swc_ecma_ast::Id;
#[derive(Debug, Default)]
pub(crate) struct ReverseMap<'a> {
prev: Option<&'a ReverseMap<'a>>,
inner: FxHashMap<Atom, Vec<Id>>,
}
impl ReverseMap<'_> {
pub fn push_entry(&mut self, key: Atom, id: Id) {
self.inner.entry(key).or_default().push(id);
}
fn iter(&self) -> Iter {
Iter { cur: Some(self) }
}
pub fn get<'a>(&'a self, key: &'a Atom) -> impl Iterator<Item = &'a Id> + 'a {
self.iter()
.filter_map(|v| v.inner.get(key))
.flat_map(|v| v.iter())
}
pub fn next(&self) -> ReverseMap {
ReverseMap {
prev: Some(self),
..Default::default()
}
}
}
pub(crate) struct Iter<'a> {
cur: Option<&'a ReverseMap<'a>>,
}
impl<'a> Iterator for Iter<'a> {
type Item = &'a ReverseMap<'a>;
fn next(&mut self) -> Option<Self::Item> {
let cur = self.cur.take()?;
self.cur = cur.prev;
Some(cur)
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/src/rename/analyzer/scope.rs | Rust | #![allow(clippy::too_many_arguments)]
use std::{
fmt::{Display, Formatter},
hash::BuildHasherDefault,
mem::{take, transmute_copy, ManuallyDrop},
};
use indexmap::IndexSet;
#[cfg(feature = "concurrent-renamer")]
use rayon::prelude::*;
use rustc_hash::{FxHashSet, FxHasher};
use swc_atoms::{atom, Atom};
use swc_common::{util::take::Take, Mark, SyntaxContext};
use swc_ecma_ast::*;
use tracing::debug;
use super::reverse_map::ReverseMap;
use crate::rename::{RenameMap, Renamer};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ScopeKind {
Fn,
Block,
}
impl Default for ScopeKind {
fn default() -> Self {
Self::Fn
}
}
#[derive(Debug, Default)]
pub(crate) struct Scope {
pub(super) kind: ScopeKind,
pub(super) data: ScopeData,
pub(super) children: Vec<Scope>,
}
pub(super) type FxIndexSet<T> = IndexSet<T, BuildHasherDefault<FxHasher>>;
#[derive(Debug, Default)]
pub(super) struct ScopeData {
/// All identifiers used by this scope or children.
///
/// This is add-only.
///
/// If the add-only contraint is violated, it is very likely to be a bug,
/// because we merge every items in children to current scope.
all: FxHashSet<Id>,
queue: FxIndexSet<Id>,
}
impl Scope {
pub(super) fn add_decl(&mut self, id: &Id, has_eval: bool, top_level_mark: Mark) {
if id.0 == atom!("arguments") {
return;
}
self.data.all.insert(id.clone());
if !self.data.queue.contains(id) {
if has_eval && id.1.outer().is_descendant_of(top_level_mark) {
return;
}
self.data.queue.insert(id.clone());
}
}
pub(crate) fn reserve_decl(&mut self, len: usize) {
self.data.all.reserve(len);
self.data.queue.reserve(len);
}
pub(super) fn add_usage(&mut self, id: Id) {
if id.0 == atom!("arguments") {
return;
}
self.data.all.insert(id);
}
pub(crate) fn reserve_usage(&mut self, len: usize) {
self.data.all.reserve(len);
}
/// Copy `children.data.all` to `self.data.all`.
pub(crate) fn prepare_renaming(&mut self) {
self.children.iter_mut().for_each(|child| {
child.prepare_renaming();
self.data.all.extend(child.data.all.iter().cloned());
});
}
pub(crate) fn rename_in_normal_mode<R>(
&mut self,
renamer: &R,
to: &mut RenameMap,
previous: &RenameMap,
reverse: &mut ReverseMap,
preserved: &FxHashSet<Id>,
preserved_symbols: &FxHashSet<Atom>,
) where
R: Renamer,
{
let queue = take(&mut self.data.queue);
// let mut cloned_reverse = reverse.clone();
self.rename_one_scope_in_normal_mode(
renamer,
to,
previous,
reverse,
queue,
preserved,
preserved_symbols,
);
for child in &mut self.children {
child.rename_in_normal_mode(
renamer,
to,
&Default::default(),
reverse,
preserved,
preserved_symbols,
);
}
}
fn rename_one_scope_in_normal_mode<R>(
&self,
renamer: &R,
to: &mut RenameMap,
previous: &RenameMap,
reverse: &mut ReverseMap,
queue: FxIndexSet<Id>,
preserved: &FxHashSet<Id>,
preserved_symbols: &FxHashSet<Atom>,
) where
R: Renamer,
{
let mut n = 0;
for id in queue {
if preserved.contains(&id)
|| to.get(&id).is_some()
|| previous.get(&id).is_some()
|| id.0 == "eval"
{
continue;
}
if R::RESET_N {
n = 0;
}
loop {
let sym = renamer.new_name_for(&id, &mut n);
if preserved_symbols.contains(&sym) {
continue;
}
if self.can_rename(&id, &sym, reverse) {
if cfg!(debug_assertions) {
debug!("Renaming `{}{:?}` to `{}`", id.0, id.1, sym);
}
reverse.push_entry(sym.clone(), id.clone());
to.insert(id, sym);
break;
}
}
}
}
fn can_rename(&self, id: &Id, symbol: &Atom, reverse: &ReverseMap) -> bool {
// We can optimize this
// We only need to check the current scope and parents (ignoring `a` generated
// for unrelated scopes)
for left in reverse.get(symbol) {
if left.1 == id.1 && *left.0 == id.0 {
continue;
}
if self.data.all.contains(left) {
return false;
}
}
true
}
#[cfg_attr(
not(feature = "concurrent-renamer"),
allow(unused, clippy::only_used_in_recursion)
)]
pub(crate) fn rename_in_mangle_mode<R>(
&mut self,
renamer: &R,
to: &mut RenameMap,
previous: &RenameMap,
reverse: &ReverseMap,
preserved: &FxHashSet<Id>,
preserved_symbols: &FxHashSet<Atom>,
parallel: bool,
) where
R: Renamer,
{
let queue = take(&mut self.data.queue);
let mut cloned_reverse = reverse.next();
self.rename_one_scope_in_mangle_mode(
renamer,
to,
previous,
&mut cloned_reverse,
queue,
preserved,
preserved_symbols,
);
#[cfg(feature = "concurrent-renamer")]
if parallel {
#[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
let iter = self.children.par_iter_mut();
#[cfg(target_arch = "wasm32")]
let iter = self.children.iter_mut();
let iter = iter
.map(|child| {
use std::collections::HashMap;
let mut new_map = HashMap::default();
child.rename_in_mangle_mode(
renamer,
&mut new_map,
to,
&cloned_reverse,
preserved,
preserved_symbols,
parallel,
);
new_map
})
.collect::<Vec<_>>();
for (k, v) in iter.into_iter().flatten() {
to.entry(k).or_insert(v);
}
return;
}
for child in &mut self.children {
child.rename_in_mangle_mode(
renamer,
to,
&Default::default(),
&cloned_reverse,
preserved,
preserved_symbols,
parallel,
);
}
}
fn rename_one_scope_in_mangle_mode<R>(
&self,
renamer: &R,
to: &mut RenameMap,
previous: &RenameMap,
reverse: &mut ReverseMap,
queue: FxIndexSet<Id>,
preserved: &FxHashSet<Id>,
preserved_symbols: &FxHashSet<Atom>,
) where
R: Renamer,
{
let mut n = 0;
for id in queue {
if preserved.contains(&id)
|| to.get(&id).is_some()
|| previous.get(&id).is_some()
|| id.0 == "eval"
{
continue;
}
loop {
let sym = renamer.new_name_for(&id, &mut n);
// TODO: Use base54::decode
if preserved_symbols.contains(&sym) {
continue;
}
if self.can_rename(&id, &sym, reverse) {
#[cfg(debug_assertions)]
{
debug!("mangle: `{}{:?}` -> {}", id.0, id.1, sym);
}
reverse.push_entry(sym.clone(), id.clone());
to.insert(id.clone(), sym);
// self.data.decls.remove(&id);
// self.data.usages.remove(&id);
break;
}
}
}
}
pub fn rename_cost(&self) -> usize {
let children = &self.children;
self.data.queue.len() + children.iter().map(|v| v.rename_cost()).sum::<usize>()
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/src/rename/collector.rs | Rust | use std::hash::Hash;
use rustc_hash::FxHashSet;
use swc_common::{Mark, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_utils::{ident::IdentLike, stack_size::maybe_grow_default};
use swc_ecma_visit::{noop_visit_type, visit_obj_and_computed, Visit, VisitWith};
pub(super) struct IdCollector {
pub ids: FxHashSet<Id>,
}
impl Visit for IdCollector {
noop_visit_type!();
visit_obj_and_computed!();
fn visit_export_default_specifier(&mut self, _: &ExportDefaultSpecifier) {}
fn visit_export_named_specifier(&mut self, _: &ExportNamedSpecifier) {}
fn visit_export_namespace_specifier(&mut self, _: &ExportNamespaceSpecifier) {}
fn visit_bin_expr(&mut self, n: &BinExpr) {
maybe_grow_default(|| n.visit_children_with(self));
}
fn visit_ident(&mut self, id: &Ident) {
if id.ctxt != SyntaxContext::empty() {
self.ids.insert(id.to_id());
}
}
fn visit_named_export(&mut self, e: &NamedExport) {
if e.src.is_some() {
return;
}
e.visit_children_with(self);
}
fn visit_prop_name(&mut self, p: &PropName) {
if let PropName::Computed(n) = p {
n.visit_with(self);
}
}
}
pub(super) struct CustomBindingCollector<I>
where
I: IdentLike + Eq + Hash + Send + Sync,
{
bindings: FxHashSet<I>,
preserved: FxHashSet<I>,
is_pat_decl: bool,
/// [None] if there's no `eval`.
pub top_level_for_eval: Option<SyntaxContext>,
}
impl<I> CustomBindingCollector<I>
where
I: IdentLike + Eq + Hash + Send + Sync,
{
fn add(&mut self, i: &Ident) {
if let Some(top_level_ctxt) = self.top_level_for_eval {
if i.ctxt == top_level_ctxt {
self.preserved.insert(I::from_ident(i));
return;
}
}
self.bindings.insert(I::from_ident(i));
}
}
impl<I> Visit for CustomBindingCollector<I>
where
I: IdentLike + Eq + Hash + Send + Sync,
{
noop_visit_type!();
fn visit_arrow_expr(&mut self, n: &ArrowExpr) {
let old = self.is_pat_decl;
for p in &n.params {
self.is_pat_decl = true;
p.visit_with(self);
}
n.body.visit_with(self);
self.is_pat_decl = old;
}
fn visit_assign_pat_prop(&mut self, node: &AssignPatProp) {
node.value.visit_with(self);
if self.is_pat_decl {
self.add(&Ident::from(&node.key));
}
}
fn visit_binding_ident(&mut self, n: &BindingIdent) {
n.visit_children_with(self);
if self.is_pat_decl {
self.add(&Ident::from(n))
}
}
fn visit_catch_clause(&mut self, node: &CatchClause) {
let old = self.is_pat_decl;
self.is_pat_decl = true;
node.param.visit_with(self);
self.is_pat_decl = false;
node.body.visit_with(self);
self.is_pat_decl = old;
}
fn visit_class_decl(&mut self, node: &ClassDecl) {
node.visit_children_with(self);
self.add(&node.ident);
}
fn visit_class_expr(&mut self, node: &ClassExpr) {
node.visit_children_with(self);
if let Some(id) = &node.ident {
self.add(id);
}
}
fn visit_expr(&mut self, node: &Expr) {
let old = self.is_pat_decl;
self.is_pat_decl = false;
node.visit_children_with(self);
self.is_pat_decl = old;
}
fn visit_bin_expr(&mut self, node: &BinExpr) {
maybe_grow_default(|| node.visit_children_with(self));
}
fn visit_fn_decl(&mut self, node: &FnDecl) {
node.visit_children_with(self);
self.add(&node.ident);
}
fn visit_fn_expr(&mut self, node: &FnExpr) {
node.visit_children_with(self);
if let Some(id) = &node.ident {
self.add(id);
}
}
fn visit_import_default_specifier(&mut self, node: &ImportDefaultSpecifier) {
self.add(&node.local);
}
fn visit_import_named_specifier(&mut self, node: &ImportNamedSpecifier) {
self.add(&node.local);
}
fn visit_import_star_as_specifier(&mut self, node: &ImportStarAsSpecifier) {
self.add(&node.local);
}
fn visit_param(&mut self, node: &Param) {
let old = self.is_pat_decl;
self.is_pat_decl = true;
node.visit_children_with(self);
self.is_pat_decl = old;
}
fn visit_ts_param_prop(&mut self, p: &TsParamProp) {
let old = self.is_pat_decl;
self.is_pat_decl = true;
p.visit_children_with(self);
self.is_pat_decl = old;
}
fn visit_var_declarator(&mut self, node: &VarDeclarator) {
let old = self.is_pat_decl;
self.is_pat_decl = true;
node.name.visit_with(self);
self.is_pat_decl = false;
node.init.visit_with(self);
self.is_pat_decl = old;
}
}
/// Returns `(bindings, preserved)`.
pub(super) fn collect_decls<I, N>(
n: &N,
top_level_mark_for_eval: Option<Mark>,
) -> (FxHashSet<I>, FxHashSet<I>)
where
I: IdentLike + Eq + Hash + Send + Sync,
N: VisitWith<CustomBindingCollector<I>>,
{
let mut v = CustomBindingCollector {
bindings: Default::default(),
preserved: Default::default(),
is_pat_decl: false,
top_level_for_eval: top_level_mark_for_eval.map(|m| SyntaxContext::empty().apply_mark(m)),
};
n.visit_with(&mut v);
(v.bindings, v.preserved)
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/src/rename/eval.rs | Rust | use swc_ecma_ast::*;
use swc_ecma_utils::stack_size::maybe_grow_default;
use swc_ecma_visit::{noop_visit_type, visit_obj_and_computed, Visit, VisitWith};
pub(crate) fn contains_eval<N>(node: &N, include_with: bool) -> bool
where
N: VisitWith<EvalFinder>,
{
let mut v = EvalFinder {
found: false,
include_with,
};
node.visit_with(&mut v);
v.found
}
pub(crate) struct EvalFinder {
found: bool,
include_with: bool,
}
impl Visit for EvalFinder {
noop_visit_type!();
visit_obj_and_computed!();
fn visit_callee(&mut self, c: &Callee) {
c.visit_children_with(self);
if let Callee::Expr(e) = c {
if e.is_ident_ref_to("eval") {
self.found = true
}
}
}
fn visit_export_default_specifier(&mut self, _: &ExportDefaultSpecifier) {}
fn visit_export_named_specifier(&mut self, _: &ExportNamedSpecifier) {}
fn visit_export_namespace_specifier(&mut self, _: &ExportNamespaceSpecifier) {}
fn visit_expr(&mut self, n: &Expr) {
maybe_grow_default(|| n.visit_children_with(self));
}
fn visit_named_export(&mut self, e: &NamedExport) {
if e.src.is_some() {
return;
}
e.visit_children_with(self);
}
fn visit_prop_name(&mut self, p: &PropName) {
if let PropName::Computed(n) = p {
n.visit_with(self);
}
}
fn visit_with_stmt(&mut self, s: &WithStmt) {
if self.include_with {
self.found = true;
} else {
s.visit_children_with(self);
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/src/rename/mod.rs | Rust | #![allow(unused_imports)]
use std::{borrow::Cow, collections::hash_map::Entry};
use rustc_hash::{FxHashMap, FxHashSet};
use swc_atoms::Atom;
use swc_ecma_ast::*;
use swc_ecma_utils::stack_size::maybe_grow_default;
use swc_ecma_visit::{
noop_visit_mut_type, visit_mut_pass, Fold, VisitMut, VisitMutWith, VisitWith,
};
#[cfg(feature = "concurrent-renamer")]
use self::renamer_concurrent::{Send, Sync};
#[cfg(not(feature = "concurrent-renamer"))]
use self::renamer_single::{Send, Sync};
use self::{
analyzer::Analyzer,
collector::{collect_decls, CustomBindingCollector, IdCollector},
eval::contains_eval,
ops::Operator,
};
use crate::hygiene::Config;
mod analyzer;
mod collector;
mod eval;
mod ops;
pub trait Renamer: Send + Sync {
/// Should reset `n` to 0 for each identifier?
const RESET_N: bool;
/// It should be true if you expect lots of collisions
const MANGLE: bool;
fn preserved_ids_for_module(&mut self, _: &Module) -> FxHashSet<Id> {
Default::default()
}
fn preserved_ids_for_script(&mut self, _: &Script) -> FxHashSet<Id> {
Default::default()
}
fn get_cached(&self) -> Option<Cow<RenameMap>> {
None
}
fn store_cache(&mut self, _update: &RenameMap) {}
/// Should increment `n`.
fn new_name_for(&self, orig: &Id, n: &mut usize) -> Atom;
}
pub type RenameMap = FxHashMap<Id, Atom>;
pub fn rename(map: &RenameMap) -> impl '_ + Pass + VisitMut {
rename_with_config(map, Default::default())
}
pub fn rename_with_config(map: &RenameMap, config: Config) -> impl '_ + Pass + VisitMut {
visit_mut_pass(Operator {
rename: map,
config,
extra: Default::default(),
})
}
pub fn remap(map: &FxHashMap<Id, Id>, config: Config) -> impl '_ + Pass + VisitMut {
visit_mut_pass(Operator {
rename: map,
config,
extra: Default::default(),
})
}
pub fn renamer<R>(config: Config, renamer: R) -> impl Pass + VisitMut
where
R: Renamer,
{
visit_mut_pass(RenamePass {
config,
renamer,
preserved: Default::default(),
unresolved: Default::default(),
previous_cache: Default::default(),
total_map: None,
})
}
#[derive(Debug, Default)]
struct RenamePass<R>
where
R: Renamer,
{
config: Config,
renamer: R,
preserved: FxHashSet<Id>,
unresolved: FxHashSet<Atom>,
previous_cache: RenameMap,
/// Used to store cache.
///
/// [Some] if the [`Renamer::get_cached`] returns [Some].
total_map: Option<RenameMap>,
}
impl<R> RenamePass<R>
where
R: Renamer,
{
fn get_unresolved<N>(&self, n: &N, has_eval: bool) -> FxHashSet<Atom>
where
N: VisitWith<IdCollector> + VisitWith<CustomBindingCollector<Id>>,
{
let usages = {
let mut v = IdCollector {
ids: Default::default(),
};
n.visit_with(&mut v);
v.ids
};
let (decls, preserved) = collect_decls(
n,
if has_eval {
Some(self.config.top_level_mark)
} else {
None
},
);
usages
.into_iter()
.filter(|used_id| !decls.contains(used_id))
.map(|v| v.0)
.chain(preserved.into_iter().map(|v| v.0))
.collect()
}
fn get_map<N>(&mut self, node: &N, skip_one: bool, top_level: bool, has_eval: bool) -> RenameMap
where
N: VisitWith<IdCollector> + VisitWith<CustomBindingCollector<Id>>,
N: VisitWith<Analyzer>,
{
let mut scope = {
let mut v = Analyzer {
has_eval,
top_level_mark: self.config.top_level_mark,
..Default::default()
};
if skip_one {
node.visit_children_with(&mut v);
} else {
node.visit_with(&mut v);
}
v.scope
};
scope.prepare_renaming();
let mut map = RenameMap::default();
let mut unresolved = if !top_level {
let mut unresolved = self.unresolved.clone();
unresolved.extend(self.get_unresolved(node, has_eval));
Cow::Owned(unresolved)
} else {
Cow::Borrowed(&self.unresolved)
};
if !self.preserved.is_empty() {
unresolved
.to_mut()
.extend(self.preserved.iter().map(|v| v.0.clone()));
}
if !self.config.preserved_symbols.is_empty() {
unresolved
.to_mut()
.extend(self.config.preserved_symbols.iter().cloned());
}
if R::MANGLE {
let cost = scope.rename_cost();
scope.rename_in_mangle_mode(
&self.renamer,
&mut map,
&self.previous_cache,
&Default::default(),
&self.preserved,
&unresolved,
cost > 1024,
);
} else {
scope.rename_in_normal_mode(
&self.renamer,
&mut map,
&self.previous_cache,
&mut Default::default(),
&self.preserved,
&unresolved,
);
}
if let Some(total_map) = &mut self.total_map {
total_map.reserve(map.len());
for (k, v) in &map {
match total_map.entry(k.clone()) {
Entry::Occupied(old) => {
unreachable!(
"{} is already renamed to {}, but it's renamed as {}",
k.0,
old.get(),
v
);
}
Entry::Vacant(e) => {
e.insert(v.clone());
}
}
}
}
map
}
fn load_cache(&mut self) {
if let Some(cache) = self.renamer.get_cached() {
self.previous_cache = cache.into_owned();
self.total_map = Some(Default::default());
}
}
}
/// Mark a node as a unit of minification.
///
/// This is
macro_rules! unit {
($name:ident, $T:ty) => {
/// Only called if `eval` exists
fn $name(&mut self, n: &mut $T) {
if !self.config.ignore_eval && contains_eval(n, true) {
n.visit_mut_children_with(self);
} else {
let map = self.get_map(n, false, false, false);
if !map.is_empty() {
n.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
}
}
}
};
($name:ident, $T:ty, true) => {
/// Only called if `eval` exists
fn $name(&mut self, n: &mut $T) {
if !self.config.ignore_eval && contains_eval(n, true) {
n.visit_mut_children_with(self);
} else {
let map = self.get_map(n, true, false, false);
if !map.is_empty() {
n.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
}
}
}
};
}
impl<R> VisitMut for RenamePass<R>
where
R: Renamer,
{
noop_visit_mut_type!();
unit!(visit_mut_arrow_expr, ArrowExpr);
unit!(visit_mut_setter_prop, SetterProp);
unit!(visit_mut_getter_prop, GetterProp);
unit!(visit_mut_constructor, Constructor);
unit!(visit_mut_fn_expr, FnExpr);
unit!(visit_mut_method_prop, MethodProp);
unit!(visit_mut_class_method, ClassMethod);
unit!(visit_mut_private_method, PrivateMethod);
fn visit_mut_fn_decl(&mut self, n: &mut FnDecl) {
if !self.config.ignore_eval && contains_eval(n, true) {
n.visit_mut_children_with(self);
} else {
let id = n.ident.to_id();
let inserted = self.preserved.insert(id.clone());
let map = self.get_map(n, true, false, false);
if inserted {
self.preserved.remove(&id);
}
if !map.is_empty() {
n.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
}
}
}
fn visit_mut_class_decl(&mut self, n: &mut ClassDecl) {
if !self.config.ignore_eval && contains_eval(n, true) {
n.visit_mut_children_with(self);
} else {
let id = n.ident.to_id();
let inserted = self.preserved.insert(id.clone());
let map = self.get_map(n, true, false, false);
if inserted {
self.preserved.remove(&id);
}
if !map.is_empty() {
n.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
}
}
}
fn visit_mut_default_decl(&mut self, n: &mut DefaultDecl) {
match n {
DefaultDecl::Class(n) => {
n.visit_mut_children_with(self);
}
DefaultDecl::Fn(n) => {
n.visit_mut_children_with(self);
}
DefaultDecl::TsInterfaceDecl(n) => {
n.visit_mut_children_with(self);
}
}
}
fn visit_mut_expr(&mut self, n: &mut Expr) {
maybe_grow_default(|| n.visit_mut_children_with(self));
}
fn visit_mut_module(&mut self, m: &mut Module) {
self.load_cache();
self.preserved = self.renamer.preserved_ids_for_module(m);
let has_eval = !self.config.ignore_eval && contains_eval(m, true);
self.unresolved = self.get_unresolved(m, has_eval);
let map = self.get_map(m, false, true, has_eval);
// If we have eval, we cannot rename a whole program at once.
//
// Still, we can, and should rename some identifiers, if the containing scope
// (function-like nodes) does not have eval. This `eval` check includes
// `eval` in children.
//
// We calculate the top level map first, rename children, and then rename the
// top level.
//
//
// Order:
//
// 1. Top level map calculation
// 2. Per-unit map calculation
// 3. Per-unit renaming
// 4. Top level renaming
//
// This is because the top level map may contain a mapping which conflicts
// with a map from one of the children.
//
// See https://github.com/swc-project/swc/pull/7615
if has_eval {
m.visit_mut_children_with(self);
}
if !map.is_empty() {
m.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
}
if let Some(total_map) = &self.total_map {
self.renamer.store_cache(total_map);
}
}
fn visit_mut_script(&mut self, m: &mut Script) {
self.load_cache();
self.preserved = self.renamer.preserved_ids_for_script(m);
let has_eval = !self.config.ignore_eval && contains_eval(m, true);
self.unresolved = self.get_unresolved(m, has_eval);
let map = self.get_map(m, false, true, has_eval);
if has_eval {
m.visit_mut_children_with(self);
}
if !map.is_empty() {
m.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
}
if let Some(total_map) = &self.total_map {
self.renamer.store_cache(total_map);
}
}
}
#[cfg(feature = "concurrent-renamer")]
mod renamer_concurrent {
pub use std::marker::{Send, Sync};
}
#[cfg(not(feature = "concurrent-renamer"))]
mod renamer_single {
/// Dummy trait because swc_common is in single thread mode.
pub trait Send {}
/// Dummy trait because swc_common is in single thread mode.
pub trait Sync {}
impl<T> Send for T where T: ?Sized {}
impl<T> Sync for T where T: ?Sized {}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/src/rename/ops.rs | Rust | use rustc_hash::FxHashMap;
use swc_common::{
util::{move_map::MoveMap, take::Take},
Spanned, SyntaxContext, DUMMY_SP,
};
use swc_ecma_ast::*;
use swc_ecma_utils::{ident::IdentLike, stack_size::maybe_grow_default};
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use super::RenameMap;
use crate::{
hygiene::Config,
perf::{cpu_count, ParExplode, Parallel, ParallelExt},
};
pub(super) struct Operator<'a, I>
where
I: IdentLike,
{
pub rename: &'a FxHashMap<Id, I>,
pub config: Config,
pub extra: Vec<ModuleItem>,
}
impl<I> Operator<'_, I>
where
I: IdentLike,
{
fn keep_class_name(&mut self, ident: &mut Ident, class: &mut Class) -> Option<ClassExpr> {
if !self.config.keep_class_names {
return None;
}
let mut orig_name = ident.clone();
orig_name.ctxt = SyntaxContext::empty();
{
// Remove span hygiene of the class.
let mut rename = RenameMap::default();
rename.insert(ident.to_id(), orig_name.sym.clone());
let mut operator = Operator {
rename: &rename,
config: self.config.clone(),
extra: Default::default(),
};
class.visit_mut_with(&mut operator);
}
let _ = self.rename_ident(ident);
class.visit_mut_with(self);
let class_expr = ClassExpr {
ident: Some(orig_name),
class: Box::new(class.take()),
};
Some(class_expr)
}
}
impl<I> Parallel for Operator<'_, I>
where
I: IdentLike,
{
fn create(&self) -> Self {
Self {
rename: self.rename,
config: self.config.clone(),
extra: Default::default(),
}
}
fn merge(&mut self, other: Self) {
self.extra.extend(other.extra);
}
fn after_module_items(&mut self, stmts: &mut Vec<ModuleItem>) {
stmts.append(&mut self.extra);
}
}
impl<I> ParExplode for Operator<'_, I>
where
I: IdentLike,
{
fn after_one_stmt(&mut self, _: &mut Vec<Stmt>) {}
fn after_one_module_item(&mut self, stmts: &mut Vec<ModuleItem>) {
stmts.append(&mut self.extra);
}
}
impl<I> VisitMut for Operator<'_, I>
where
I: IdentLike,
{
noop_visit_mut_type!();
/// Preserve key of properties.
fn visit_mut_assign_pat_prop(&mut self, p: &mut AssignPatProp) {
if let Some(value) = &mut p.value {
value.visit_mut_children_with(self);
}
}
fn visit_mut_class_expr(&mut self, n: &mut ClassExpr) {
if let Some(ident) = &mut n.ident {
if let Some(expr) = self.keep_class_name(ident, &mut n.class) {
*n = expr;
return;
}
}
n.ident.visit_mut_with(self);
n.class.visit_mut_with(self);
}
fn visit_mut_decl(&mut self, decl: &mut Decl) {
match decl {
Decl::Class(cls) if self.config.keep_class_names => {
let span = cls.class.span;
let expr = self.keep_class_name(&mut cls.ident, &mut cls.class);
if let Some(expr) = expr {
let var = VarDeclarator {
span,
name: cls.ident.clone().into(),
init: Some(expr.into()),
definite: false,
};
*decl = VarDecl {
span,
kind: VarDeclKind::Let,
decls: vec![var],
..Default::default()
}
.into();
return;
}
return;
}
_ => {}
}
decl.visit_mut_children_with(self);
}
fn visit_mut_export_named_specifier(&mut self, s: &mut ExportNamedSpecifier) {
if s.exported.is_some() {
s.orig.visit_mut_with(self);
return;
}
let exported = s.orig.clone();
if let ModuleExportName::Ident(orig) = &mut s.orig {
if self.rename_ident(orig).is_ok() {
match &exported {
ModuleExportName::Ident(exported) => {
if orig.sym == exported.sym {
return;
}
}
ModuleExportName::Str(_) => {}
}
s.exported = Some(exported);
}
}
}
fn visit_mut_expr(&mut self, n: &mut Expr) {
maybe_grow_default(|| n.visit_mut_children_with(self))
}
fn visit_mut_expr_or_spreads(&mut self, n: &mut Vec<ExprOrSpread>) {
self.maybe_par(cpu_count() * 100, n, |v, n| {
n.visit_mut_with(v);
})
}
fn visit_mut_exprs(&mut self, n: &mut Vec<Box<Expr>>) {
self.maybe_par(cpu_count() * 100, n, |v, n| {
n.visit_mut_with(v);
})
}
fn visit_mut_ident(&mut self, ident: &mut Ident) {
match self.rename_ident(ident) {
Ok(i) | Err(i) => i,
}
}
fn visit_mut_import_named_specifier(&mut self, s: &mut ImportNamedSpecifier) {
if s.imported.is_some() {
s.local.visit_mut_with(self);
return;
}
let imported = s.local.clone();
let local = self.rename_ident(&mut s.local);
if local.is_ok() {
if s.local.sym == imported.sym {
return;
}
s.imported = Some(ModuleExportName::Ident(imported));
}
}
/// Preserve key of properties.
fn visit_mut_key_value_pat_prop(&mut self, p: &mut KeyValuePatProp) {
p.key.visit_mut_with(self);
p.value.visit_mut_with(self);
}
fn visit_mut_key_value_prop(&mut self, p: &mut KeyValueProp) {
p.key.visit_mut_with(self);
p.value.visit_mut_with(self);
}
fn visit_mut_member_expr(&mut self, expr: &mut MemberExpr) {
expr.span.visit_mut_with(self);
expr.obj.visit_mut_with(self);
if let MemberProp::Computed(c) = &mut expr.prop {
c.visit_mut_with(self)
}
}
fn visit_mut_module_item(&mut self, item: &mut ModuleItem) {
let span = item.span();
macro_rules! export {
($orig:expr, $ident:expr) => {
self.extra
.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(
NamedExport {
span,
specifiers: vec![ExportSpecifier::Named(ExportNamedSpecifier {
span: DUMMY_SP,
orig: $ident,
exported: Some($orig),
is_type_only: false,
})],
src: None,
type_only: false,
with: None,
},
)));
};
}
match item {
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
span,
decl:
Decl::Class(ClassDecl {
ident,
class,
declare,
}),
})) => {
let mut ident = ident.take();
let mut class = class.take();
class.visit_mut_with(self);
let orig_ident = ident.clone();
match self.rename_ident(&mut ident) {
Ok(..) => {
*item = ClassDecl {
ident: ident.clone(),
class: class.take(),
declare: *declare,
}
.into();
export!(
ModuleExportName::Ident(orig_ident),
ModuleExportName::Ident(ident.take())
);
}
Err(..) => {
*item = ExportDecl {
span: *span,
decl: ClassDecl {
ident: ident.take(),
class: class.take(),
declare: *declare,
}
.into(),
}
.into()
}
}
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
span,
decl:
Decl::Fn(FnDecl {
ident,
function,
declare,
}),
})) => {
let mut ident = ident.take();
let mut function = function.take();
function.visit_mut_with(self);
let orig_ident = ident.clone();
match self.rename_ident(&mut ident) {
Ok(..) => {
*item = FnDecl {
ident: ident.clone(),
function,
declare: *declare,
}
.into();
export!(
ModuleExportName::Ident(orig_ident),
ModuleExportName::Ident(ident)
);
}
Err(..) => {
*item = ExportDecl {
span: *span,
decl: FnDecl {
ident,
function,
declare: *declare,
}
.into(),
}
.into()
}
}
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
decl: Decl::Var(var),
..
})) => {
let decls = var.decls.take();
let mut renamed: Vec<ExportSpecifier> = Vec::new();
let decls = decls.move_map(|mut decl| {
decl.name.visit_mut_with(&mut VarFolder {
orig: self,
renamed: &mut renamed,
});
decl.init.visit_mut_with(self);
decl
});
if renamed.is_empty() {
*item = ExportDecl {
span,
decl: VarDecl {
decls,
..*var.take()
}
.into(),
}
.into();
return;
}
*item = VarDecl {
decls,
..*var.take()
}
.into();
self.extra.push(
NamedExport {
span,
specifiers: renamed,
src: None,
type_only: false,
with: None,
}
.into(),
);
}
_ => {
item.visit_mut_children_with(self);
}
}
}
fn visit_mut_module_items(&mut self, nodes: &mut Vec<ModuleItem>) {
use std::mem::take;
#[cfg(feature = "concurrent")]
if nodes.len() >= 8 * cpu_count() {
::swc_common::GLOBALS.with(|globals| {
use rayon::prelude::*;
let (visitor, new_nodes) = take(nodes)
.into_par_iter()
.map(|mut node| {
::swc_common::GLOBALS.set(globals, || {
let mut visitor = Parallel::create(&*self);
node.visit_mut_with(&mut visitor);
let mut nodes = Vec::with_capacity(4);
ParExplode::after_one_module_item(&mut visitor, &mut nodes);
nodes.push(node);
(visitor, nodes)
})
})
.reduce(
|| (Parallel::create(&*self), Vec::new()),
|mut a, b| {
Parallel::merge(&mut a.0, b.0);
a.1.extend(b.1);
a
},
);
Parallel::merge(self, visitor);
{
self.after_module_items(nodes);
}
*nodes = new_nodes;
});
return;
}
let mut buf = Vec::with_capacity(nodes.len());
for mut node in take(nodes) {
let mut visitor = Parallel::create(&*self);
node.visit_mut_with(&mut visitor);
buf.push(node);
visitor.after_one_module_item(&mut buf);
}
self.after_module_items(&mut buf);
*nodes = buf;
}
fn visit_mut_named_export(&mut self, e: &mut NamedExport) {
if e.src.is_some() {
return;
}
e.visit_mut_children_with(self);
}
fn visit_mut_object_pat_prop(&mut self, n: &mut ObjectPatProp) {
n.visit_mut_children_with(self);
if let ObjectPatProp::Assign(p) = n {
let mut renamed = Ident::from(&p.key);
if self.rename_ident(&mut renamed).is_ok() {
if renamed.sym == p.key.sym {
return;
}
*n = KeyValuePatProp {
key: PropName::Ident(p.key.take().into()),
value: match p.value.take() {
Some(default_expr) => AssignPat {
span: p.span,
left: renamed.into(),
right: default_expr,
}
.into(),
None => renamed.into(),
},
}
.into();
}
}
}
fn visit_mut_opt_vec_expr_or_spreads(&mut self, n: &mut Vec<Option<ExprOrSpread>>) {
self.maybe_par(cpu_count() * 100, n, |v, n| {
n.visit_mut_with(v);
})
}
fn visit_mut_prop(&mut self, prop: &mut Prop) {
match prop {
Prop::Shorthand(i) => {
let mut renamed = i.clone();
if self.rename_ident(&mut renamed).is_ok() {
if renamed.sym == i.sym {
return;
}
*prop = Prop::KeyValue(KeyValueProp {
key: PropName::Ident(IdentName {
// clear mark
span: i.span,
sym: i.sym.clone(),
}),
value: renamed.into(),
})
}
}
_ => prop.visit_mut_children_with(self),
}
}
fn visit_mut_prop_name(&mut self, n: &mut PropName) {
if let PropName::Computed(c) = n {
c.visit_mut_with(self)
}
}
fn visit_mut_class_members(&mut self, members: &mut Vec<ClassMember>) {
self.maybe_par(cpu_count(), members, |v, member| {
member.visit_mut_with(v);
});
}
fn visit_mut_prop_or_spreads(&mut self, n: &mut Vec<PropOrSpread>) {
self.maybe_par(cpu_count() * 100, n, |v, n| {
n.visit_mut_with(v);
})
}
fn visit_mut_stmts(&mut self, nodes: &mut Vec<Stmt>) {
use std::mem::take;
#[cfg(feature = "concurrent")]
if nodes.len() >= 100 * cpu_count() {
::swc_common::GLOBALS.with(|globals| {
use rayon::prelude::*;
let (visitor, new_nodes) = take(nodes)
.into_par_iter()
.map(|mut node| {
::swc_common::GLOBALS.set(globals, || {
let mut visitor = Parallel::create(&*self);
node.visit_mut_with(&mut visitor);
let mut nodes = Vec::with_capacity(4);
ParExplode::after_one_stmt(&mut visitor, &mut nodes);
nodes.push(node);
(visitor, nodes)
})
})
.reduce(
|| (Parallel::create(&*self), Vec::new()),
|mut a, b| {
Parallel::merge(&mut a.0, b.0);
a.1.extend(b.1);
a
},
);
Parallel::merge(self, visitor);
{
self.after_stmts(nodes);
}
*nodes = new_nodes;
});
return;
}
let mut buf = Vec::with_capacity(nodes.len());
for mut node in take(nodes) {
let mut visitor = Parallel::create(&*self);
node.visit_mut_with(&mut visitor);
buf.push(node);
visitor.after_one_stmt(&mut buf);
}
self.after_stmts(&mut buf);
*nodes = buf;
}
fn visit_mut_super_prop_expr(&mut self, expr: &mut SuperPropExpr) {
expr.span.visit_mut_with(self);
if let SuperProp::Computed(c) = &mut expr.prop {
c.visit_mut_with(self);
}
}
fn visit_mut_var_declarators(&mut self, n: &mut Vec<VarDeclarator>) {
self.maybe_par(cpu_count() * 100, n, |v, n| {
n.visit_mut_with(v);
})
}
}
struct VarFolder<'a, 'b, I>
where
I: IdentLike,
{
orig: &'a mut Operator<'b, I>,
renamed: &'a mut Vec<ExportSpecifier>,
}
impl<I> VisitMut for VarFolder<'_, '_, I>
where
I: IdentLike,
{
noop_visit_mut_type!();
#[inline]
fn visit_mut_expr(&mut self, _: &mut Expr) {}
#[inline]
fn visit_mut_simple_assign_target(&mut self, _: &mut SimpleAssignTarget) {}
fn visit_mut_ident(&mut self, i: &mut Ident) {
let orig = i.clone();
if self.orig.rename_ident(i).is_ok() {
self.renamed
.push(ExportSpecifier::Named(ExportNamedSpecifier {
span: i.span,
exported: Some(ModuleExportName::Ident(orig)),
orig: ModuleExportName::Ident(i.clone()),
is_type_only: false,
}));
}
}
}
impl<I> Operator<'_, I>
where
I: IdentLike,
{
/// Returns `Ok(renamed_ident)` if ident should be renamed.
fn rename_ident(&mut self, ident: &mut Ident) -> Result<(), ()> {
if let Some(new_id) = self.rename.get(&ident.to_id()) {
let (new_sym, new_ctxt) = new_id.to_id();
if new_sym == ident.sym {
return Err(());
}
ident.ctxt = new_ctxt;
ident.sym = new_sym;
return Ok(());
}
Err(())
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/src/resolver/mod.rs | Rust | use rustc_hash::{FxHashMap, FxHashSet};
use swc_atoms::Atom;
use swc_common::{Mark, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_utils::{find_pat_ids, stack_size::maybe_grow_default};
use swc_ecma_visit::{
noop_visit_mut_type, visit_mut_obj_and_computed, visit_mut_pass, VisitMut, VisitMutWith,
};
use tracing::{debug, span, Level};
use crate::scope::{DeclKind, IdentType, ScopeKind};
#[cfg(test)]
mod tests;
const LOG: bool = false && cfg!(debug_assertions);
/// See [Ident] for know how does swc manages identifiers.
///
/// # When to run
///
/// The resolver expects 'clean' ast. You can get clean ast by parsing, or by
/// removing all syntax context in ast nodes.
///
/// # What does it do
///
/// Firstly all scopes (fn, block) has it's own SyntaxContext.
/// Resolver visits all identifiers in module, and look for binding identifies
/// in the scope. Those identifiers now have the SyntaxContext of scope (fn,
/// block). While doing so, resolver tries to resolve normal identifiers (no
/// hygiene info) as a reference to identifier of scope. If the resolver find
/// suitable variable, the identifier reference will have same context as the
/// variable.
///
///
/// # Panics
///
/// `top_level_mark` should not be root.
///
/// # Example
///
/// ```js
/// let a = 1;
/// {
/// let a = 2;
/// use(a);
/// }
/// use(a)
/// ```
///
/// resolver does
///
/// 1. Define `a` with top level context.
///
/// 2. Found a block, so visit block with a new syntax context.
///
/// 3. Defined `a` with syntax context of the block statement.
///
/// 4. Found usage of `a`, and determines that it's reference to `a` in the
/// block. So the reference to `a` will have same syntax context as `a` in
/// the block.
///
/// 5. Found usage of `a` (last line), and determines that it's a reference to
/// top-level `a`, and change syntax context of `a` on last line to top-level
/// syntax context.
///
///
/// # Parameters
///
/// ## `unresolved_mark`
///
/// [Mark] applied to unresolved references.
///
/// A pass should accept this [Mark] if it's going to generate a refernce to
/// globals like `require`.
///
/// e.g. `common_js` pass generates calls to `require`, and this should not
/// be shadowed by a declaration named `require` in the same file.
/// So it uses this value.
///
/// ## `top_level_mark`
///
/// [Mark] applied to top-level bindings.
///
/// **NOTE**: This is **not** globals. This is for top level items declared by
/// users.
///
/// A pass should accept this [Mark] if it requires user-defined top-level
/// items.
///
/// e.g. `jsx` pass requires to call `React` imported by the user.
///
/// ```js
/// import React from 'react';
/// ```
///
/// In the code above, `React` has this [Mark]. `jsx` passes need to
/// reference this [Mark], so it accpets this.
///
/// This [Mark] should be used for referencing top-level bindings written by
/// user. If you are going to create a binding, use `private_ident`
/// instead.
///
/// In other words, **this [Mark] should not be used for determining if a
/// variable is top-level.** This is simply a configuration of the `resolver`
/// pass.
///
///
/// ## `typescript`
///
/// Enable this only if you are going to strip types or apply type-aware
/// passes like decorators pass.
///
///
/// # FAQ
///
/// ## Does a pair `(Atom, SyntaxContext)` always uniquely identifiers a
/// variable binding?
///
/// Yes, but multiple variables can have the exactly same name.
///
/// In the code below,
///
/// ```js
/// var a = 1, a = 2;
/// ```
///
/// both of them have the same name, so the `(Atom, SyntaxContext)` pair will
/// be also identical.
pub fn resolver(
unresolved_mark: Mark,
top_level_mark: Mark,
typescript: bool,
) -> impl 'static + Pass + VisitMut {
assert_ne!(
unresolved_mark,
Mark::root(),
"Marker provided to resolver should not be the root mark"
);
let _ = SyntaxContext::empty().apply_mark(unresolved_mark);
let _ = SyntaxContext::empty().apply_mark(top_level_mark);
visit_mut_pass(Resolver {
current: Scope::new(ScopeKind::Fn, top_level_mark, None),
ident_type: IdentType::Ref,
in_type: false,
is_module: false,
in_ts_module: false,
decl_kind: DeclKind::Lexical,
strict_mode: false,
config: InnerConfig {
handle_types: typescript,
unresolved_mark,
top_level_mark,
},
})
}
#[derive(Debug, Clone)]
struct Scope<'a> {
/// Parent scope of the scope
parent: Option<&'a Scope<'a>>,
/// Kind of the scope.
kind: ScopeKind,
/// [Mark] of the current scope.
mark: Mark,
/// All declarations in the scope
declared_symbols: FxHashMap<Atom, DeclKind>,
/// All types declared in the scope
declared_types: FxHashSet<Atom>,
}
impl<'a> Scope<'a> {
pub fn new(kind: ScopeKind, mark: Mark, parent: Option<&'a Scope<'a>>) -> Self {
Scope {
parent,
kind,
mark,
declared_symbols: Default::default(),
declared_types: Default::default(),
}
}
fn is_declared(&self, symbol: &Atom) -> Option<&DeclKind> {
self.declared_symbols
.get(symbol)
.or_else(|| self.parent?.is_declared(symbol))
}
}
/// # Phases
///
/// ## Hoisting phase
///
/// ## Resolving phase
struct Resolver<'a> {
current: Scope<'a>,
ident_type: IdentType,
in_type: bool,
is_module: bool,
in_ts_module: bool,
decl_kind: DeclKind,
strict_mode: bool,
config: InnerConfig,
}
#[derive(Debug, Clone, Copy)]
struct InnerConfig {
handle_types: bool,
unresolved_mark: Mark,
top_level_mark: Mark,
}
#[allow(clippy::needless_lifetimes)]
impl<'a> Resolver<'a> {
#[cfg(test)]
fn new(current: Scope<'a>, config: InnerConfig) -> Self {
Resolver {
current,
ident_type: IdentType::Ref,
in_type: false,
is_module: false,
in_ts_module: false,
config,
decl_kind: DeclKind::Lexical,
strict_mode: false,
}
}
fn with_child<F>(&self, kind: ScopeKind, op: F)
where
F: for<'aa> FnOnce(&mut Resolver<'aa>),
{
let mut child = Resolver {
current: Scope::new(
kind,
Mark::fresh(self.config.top_level_mark),
Some(&self.current),
),
ident_type: IdentType::Ref,
config: self.config,
in_type: self.in_type,
is_module: self.is_module,
in_ts_module: self.in_ts_module,
decl_kind: self.decl_kind,
strict_mode: self.strict_mode,
};
op(&mut child);
}
fn visit_mut_stmt_within_child_scope(&mut self, s: &mut Stmt) {
self.with_child(ScopeKind::Block, |child| match s {
Stmt::Block(s) => {
child.mark_block(&mut s.ctxt);
s.visit_mut_children_with(child);
}
_ => s.visit_mut_with(child),
});
}
/// Returns a [Mark] for an identifier reference.
fn mark_for_ref(&self, sym: &Atom) -> Option<Mark> {
self.mark_for_ref_inner(sym, false)
}
fn mark_for_ref_inner(&self, sym: &Atom, stop_an_fn_scope: bool) -> Option<Mark> {
if self.config.handle_types && self.in_type {
let mut mark = self.current.mark;
let mut scope = Some(&self.current);
while let Some(cur) = scope {
// if cur.declared_types.contains(sym) ||
// cur.hoisted_symbols.borrow().contains(sym) {
if cur.declared_types.contains(sym) {
if mark == Mark::root() {
break;
}
return Some(mark);
}
if cur.kind == ScopeKind::Fn && stop_an_fn_scope {
return None;
}
if let Some(parent) = &cur.parent {
mark = parent.mark;
}
scope = cur.parent;
}
}
let mut mark = self.current.mark;
let mut scope = Some(&self.current);
while let Some(cur) = scope {
if cur.declared_symbols.contains_key(sym) {
if mark == Mark::root() {
return None;
}
return match &**sym {
// https://tc39.es/ecma262/multipage/global-object.html#sec-value-properties-of-the-global-object-infinity
// non configurable global value
"undefined" | "NaN" | "Infinity"
if mark == self.config.top_level_mark && !self.is_module =>
{
Some(self.config.unresolved_mark)
}
_ => Some(mark),
};
}
if cur.kind == ScopeKind::Fn && stop_an_fn_scope {
return None;
}
if let Some(parent) = &cur.parent {
mark = parent.mark;
}
scope = cur.parent;
}
None
}
/// Modifies a binding identifier.
fn modify(&mut self, id: &mut Ident, kind: DeclKind) {
if cfg!(debug_assertions) && LOG {
debug!(
"Binding (type = {}) {}{:?} {:?}",
self.in_type, id.sym, id.ctxt, kind
);
}
if id.ctxt != SyntaxContext::empty() {
return;
}
if self.in_type {
self.current.declared_types.insert(id.sym.clone());
} else {
self.current.declared_symbols.insert(id.sym.clone(), kind);
}
let mark = self.current.mark;
if mark != Mark::root() {
id.ctxt = id.ctxt.apply_mark(mark);
}
}
fn mark_block(&mut self, ctxt: &mut SyntaxContext) {
if *ctxt != SyntaxContext::empty() {
return;
}
let mark = self.current.mark;
if mark != Mark::root() {
*ctxt = ctxt.apply_mark(mark)
}
}
fn try_resolving_as_type(&mut self, i: &mut Ident) {
if i.ctxt.outer() == self.config.unresolved_mark {
i.ctxt = SyntaxContext::empty()
}
self.in_type = true;
i.visit_mut_with(self);
self.in_type = false;
}
}
macro_rules! typed {
($name:ident, $T:ty) => {
fn $name(&mut self, node: &mut $T) {
if self.config.handle_types {
node.visit_mut_children_with(self)
}
}
};
}
macro_rules! typed_ref {
($name:ident, $T:ty) => {
fn $name(&mut self, node: &mut $T) {
if self.config.handle_types {
let in_type = self.in_type;
let ident_type = self.ident_type;
self.in_type = true;
node.visit_mut_children_with(self);
self.ident_type = ident_type;
self.in_type = in_type;
}
}
};
}
macro_rules! typed_ref_init {
($name:ident, $T:ty) => {
fn $name(&mut self, node: &mut $T) {
if self.config.handle_types {
let in_type = self.in_type;
let ident_type = self.ident_type;
self.ident_type = IdentType::Ref;
self.in_type = true;
node.visit_mut_children_with(self);
self.ident_type = ident_type;
self.in_type = in_type;
}
}
};
}
macro_rules! typed_decl {
($name:ident, $T:ty) => {
fn $name(&mut self, node: &mut $T) {
if self.config.handle_types {
let in_type = self.in_type;
self.ident_type = IdentType::Binding;
self.in_type = true;
node.visit_mut_children_with(self);
self.in_type = in_type;
}
}
};
}
macro_rules! noop {
($name:ident, $T:ty) => {
#[inline]
fn $name(&mut self, _: &mut $T) {}
};
}
impl VisitMut for Resolver<'_> {
noop!(visit_mut_accessibility, Accessibility);
noop!(visit_mut_true_plus_minus, TruePlusMinus);
noop!(visit_mut_ts_keyword_type, TsKeywordType);
noop!(visit_mut_ts_keyword_type_kind, TsKeywordTypeKind);
noop!(visit_mut_ts_type_operator_op, TsTypeOperatorOp);
noop!(visit_mut_ts_enum_member_id, TsEnumMemberId);
noop!(visit_mut_ts_external_module_ref, TsExternalModuleRef);
noop!(visit_mut_ts_module_name, TsModuleName);
noop!(visit_mut_ts_this_type, TsThisType);
typed_ref!(visit_mut_ts_array_type, TsArrayType);
typed_ref!(visit_mut_ts_conditional_type, TsConditionalType);
typed_ref_init!(
visit_mut_ts_type_param_instantiation,
TsTypeParamInstantiation
);
typed_ref!(visit_mut_ts_type_query, TsTypeQuery);
typed_ref!(visit_mut_ts_type_query_expr, TsTypeQueryExpr);
typed_ref!(visit_mut_ts_type_operator, TsTypeOperator);
typed_ref_init!(visit_mut_ts_type, TsType);
typed_ref_init!(visit_mut_ts_type_ann, TsTypeAnn);
typed!(
visit_mut_ts_union_or_intersection_type,
TsUnionOrIntersectionType
);
typed!(visit_mut_ts_fn_or_constructor_type, TsFnOrConstructorType);
typed_ref!(visit_mut_ts_union_type, TsUnionType);
typed_ref!(visit_mut_ts_infer_type, TsInferType);
typed_ref!(visit_mut_ts_tuple_type, TsTupleType);
typed_ref!(visit_mut_ts_intersection_type, TsIntersectionType);
typed_ref!(visit_mut_ts_type_ref, TsTypeRef);
typed_decl!(visit_mut_ts_type_param_decl, TsTypeParamDecl);
typed!(visit_mut_ts_fn_param, TsFnParam);
typed!(visit_mut_ts_indexed_access_type, TsIndexedAccessType);
typed!(visit_mut_ts_index_signature, TsIndexSignature);
typed!(visit_mut_ts_interface_body, TsInterfaceBody);
typed!(visit_mut_ts_parenthesized_type, TsParenthesizedType);
typed!(visit_mut_ts_type_lit, TsTypeLit);
typed!(visit_mut_ts_type_element, TsTypeElement);
typed!(visit_mut_ts_optional_type, TsOptionalType);
typed!(visit_mut_ts_rest_type, TsRestType);
typed!(visit_mut_ts_type_predicate, TsTypePredicate);
typed_ref!(visit_mut_ts_this_type_or_ident, TsThisTypeOrIdent);
visit_mut_obj_and_computed!();
// TODO: How should I handle this?
typed!(visit_mut_ts_namespace_export_decl, TsNamespaceExportDecl);
fn visit_mut_arrow_expr(&mut self, e: &mut ArrowExpr) {
self.with_child(ScopeKind::Fn, |child| {
e.type_params.visit_mut_with(child);
let old = child.ident_type;
child.ident_type = IdentType::Binding;
{
let params = e
.params
.iter()
.filter(|p| !p.is_rest())
.flat_map(find_pat_ids::<_, Id>);
for id in params {
child.current.declared_symbols.insert(id.0, DeclKind::Param);
}
}
e.params.visit_mut_with(child);
child.ident_type = old;
match &mut *e.body {
BlockStmtOrExpr::BlockStmt(s) => {
child.mark_block(&mut s.ctxt);
let old_strict_mode = child.strict_mode;
if !child.strict_mode {
child.strict_mode = s
.stmts
.first()
.map(|stmt| stmt.is_use_strict())
.unwrap_or(false);
}
// Prevent creating new scope.
s.stmts.visit_mut_with(child);
child.strict_mode = old_strict_mode;
}
BlockStmtOrExpr::Expr(e) => e.visit_mut_with(child),
}
e.return_type.visit_mut_with(child);
});
}
fn visit_mut_assign_pat(&mut self, node: &mut AssignPat) {
// visit the type first so that it doesn't resolve any
// identifiers from the others
node.left.visit_mut_with(self);
node.right.visit_mut_with(self);
}
fn visit_mut_binding_ident(&mut self, i: &mut BindingIdent) {
let ident_type = self.ident_type;
let in_type = self.in_type;
self.ident_type = IdentType::Ref;
i.type_ann.visit_mut_with(self);
self.ident_type = ident_type;
i.id.visit_mut_with(self);
self.in_type = in_type;
self.ident_type = ident_type;
}
fn visit_mut_block_stmt(&mut self, block: &mut BlockStmt) {
self.with_child(ScopeKind::Block, |child| {
child.mark_block(&mut block.ctxt);
block.visit_mut_children_with(child);
})
}
fn visit_mut_break_stmt(&mut self, s: &mut BreakStmt) {
let old = self.ident_type;
self.ident_type = IdentType::Label;
s.label.visit_mut_with(self);
self.ident_type = old;
}
fn visit_mut_catch_clause(&mut self, c: &mut CatchClause) {
// Child folder
self.with_child(ScopeKind::Fn, |child| {
child.ident_type = IdentType::Binding;
c.param.visit_mut_with(child);
child.ident_type = IdentType::Ref;
child.mark_block(&mut c.body.ctxt);
c.body.visit_mut_children_with(child);
});
}
fn visit_mut_class(&mut self, c: &mut Class) {
let old_strict_mode = self.strict_mode;
self.strict_mode = true;
let old = self.ident_type;
self.ident_type = IdentType::Ref;
c.decorators.visit_mut_with(self);
self.ident_type = IdentType::Ref;
c.super_class.visit_mut_with(self);
self.ident_type = IdentType::Binding;
c.type_params.visit_mut_with(self);
self.ident_type = IdentType::Ref;
c.super_type_params.visit_mut_with(self);
self.ident_type = IdentType::Ref;
c.implements.visit_mut_with(self);
self.ident_type = old;
c.body.visit_mut_with(self);
self.strict_mode = old_strict_mode;
}
fn visit_mut_class_decl(&mut self, n: &mut ClassDecl) {
if n.declare && !self.config.handle_types {
return;
}
self.modify(&mut n.ident, DeclKind::Lexical);
n.class.decorators.visit_mut_with(self);
// Create a child scope. The class name is only accessible within the class.
self.with_child(ScopeKind::Fn, |child| {
child.ident_type = IdentType::Ref;
n.class.visit_mut_with(child);
});
}
fn visit_mut_class_expr(&mut self, n: &mut ClassExpr) {
// Create a child scope. The class name is only accessible within the class.
n.class.super_class.visit_mut_with(self);
self.with_child(ScopeKind::Fn, |child| {
child.ident_type = IdentType::Binding;
n.ident.visit_mut_with(child);
child.ident_type = IdentType::Ref;
n.class.visit_mut_with(child);
});
}
fn visit_mut_class_method(&mut self, m: &mut ClassMethod) {
m.key.visit_mut_with(self);
for p in m.function.params.iter_mut() {
p.decorators.visit_mut_with(self);
}
self.with_child(ScopeKind::Fn, |child| m.function.visit_mut_with(child));
}
fn visit_mut_class_prop(&mut self, p: &mut ClassProp) {
p.decorators.visit_mut_with(self);
if let PropName::Computed(key) = &mut p.key {
let old = self.ident_type;
self.ident_type = IdentType::Binding;
key.expr.visit_mut_with(self);
self.ident_type = old;
}
let old = self.ident_type;
self.ident_type = IdentType::Ref;
p.value.visit_mut_with(self);
self.ident_type = old;
p.type_ann.visit_mut_with(self);
}
fn visit_mut_constructor(&mut self, c: &mut Constructor) {
for p in c.params.iter_mut() {
match p {
ParamOrTsParamProp::TsParamProp(p) => {
p.decorators.visit_mut_with(self);
}
ParamOrTsParamProp::Param(p) => {
p.decorators.visit_mut_with(self);
}
}
}
self.with_child(ScopeKind::Fn, |child| {
let old = child.ident_type;
child.ident_type = IdentType::Binding;
{
let params = c
.params
.iter()
.filter(|p| match p {
ParamOrTsParamProp::TsParamProp(_) => false,
ParamOrTsParamProp::Param(p) => !p.pat.is_rest(),
})
.flat_map(find_pat_ids::<_, Id>);
for id in params {
child.current.declared_symbols.insert(id.0, DeclKind::Param);
}
}
c.params.visit_mut_with(child);
child.ident_type = old;
if let Some(body) = &mut c.body {
child.mark_block(&mut body.ctxt);
body.visit_mut_children_with(child);
}
});
}
fn visit_mut_continue_stmt(&mut self, s: &mut ContinueStmt) {
let old = self.ident_type;
self.ident_type = IdentType::Label;
s.label.visit_mut_with(self);
self.ident_type = old;
}
fn visit_mut_export_default_decl(&mut self, e: &mut ExportDefaultDecl) {
// Treat default exported functions and classes as declarations
// even though they are parsed as expressions.
match &mut e.decl {
DefaultDecl::Fn(f) => {
if f.ident.is_some() {
self.with_child(ScopeKind::Fn, |child| {
f.function.visit_mut_with(child);
});
} else {
f.visit_mut_with(self)
}
}
DefaultDecl::Class(c) => {
// Skip class expression visitor to treat as a declaration.
c.class.visit_mut_with(self)
}
_ => e.visit_mut_children_with(self),
}
}
fn visit_mut_export_default_expr(&mut self, node: &mut ExportDefaultExpr) {
node.expr.visit_mut_with(self);
if self.config.handle_types {
if let Expr::Ident(i) = &mut *node.expr {
self.try_resolving_as_type(i);
}
}
}
fn visit_mut_export_named_specifier(&mut self, e: &mut ExportNamedSpecifier) {
e.visit_mut_children_with(self);
if self.config.handle_types {
match &mut e.orig {
ModuleExportName::Ident(orig) => {
self.try_resolving_as_type(orig);
}
ModuleExportName::Str(_) => {}
}
}
}
fn visit_mut_export_specifier(&mut self, s: &mut ExportSpecifier) {
let old = self.ident_type;
self.ident_type = IdentType::Ref;
s.visit_mut_children_with(self);
self.ident_type = old;
}
fn visit_mut_expr(&mut self, expr: &mut Expr) {
let _span = if LOG {
Some(span!(Level::ERROR, "visit_mut_expr").entered())
} else {
None
};
let old = self.ident_type;
self.ident_type = IdentType::Ref;
maybe_grow_default(|| expr.visit_mut_children_with(self));
self.ident_type = old;
}
fn visit_mut_fn_decl(&mut self, node: &mut FnDecl) {
if node.declare && !self.config.handle_types {
return;
}
// We don't fold ident as Hoister handles this.
node.function.decorators.visit_mut_with(self);
self.with_child(ScopeKind::Fn, |child| node.function.visit_mut_with(child));
}
fn visit_mut_fn_expr(&mut self, e: &mut FnExpr) {
e.function.decorators.visit_mut_with(self);
if let Some(ident) = &mut e.ident {
self.with_child(ScopeKind::Fn, |child| {
child.modify(ident, DeclKind::Function);
child.with_child(ScopeKind::Fn, |child| {
e.function.visit_mut_with(child);
});
});
} else {
self.with_child(ScopeKind::Fn, |child| {
e.function.visit_mut_with(child);
});
}
}
fn visit_mut_for_in_stmt(&mut self, n: &mut ForInStmt) {
self.with_child(ScopeKind::Block, |child| {
n.left.visit_mut_with(child);
n.right.visit_mut_with(child);
child.visit_mut_stmt_within_child_scope(&mut n.body);
});
}
fn visit_mut_for_of_stmt(&mut self, n: &mut ForOfStmt) {
self.with_child(ScopeKind::Block, |child| {
n.left.visit_mut_with(child);
n.right.visit_mut_with(child);
child.visit_mut_stmt_within_child_scope(&mut n.body);
});
}
fn visit_mut_for_stmt(&mut self, n: &mut ForStmt) {
self.with_child(ScopeKind::Block, |child| {
child.ident_type = IdentType::Binding;
n.init.visit_mut_with(child);
child.ident_type = IdentType::Ref;
n.test.visit_mut_with(child);
child.ident_type = IdentType::Ref;
n.update.visit_mut_with(child);
child.visit_mut_stmt_within_child_scope(&mut n.body);
});
}
fn visit_mut_function(&mut self, f: &mut Function) {
self.mark_block(&mut f.ctxt);
f.type_params.visit_mut_with(self);
self.ident_type = IdentType::Ref;
f.decorators.visit_mut_with(self);
{
let params = f
.params
.iter()
.filter(|p| !p.pat.is_rest())
.flat_map(find_pat_ids::<_, Id>);
for id in params {
self.current.declared_symbols.insert(id.0, DeclKind::Param);
}
}
self.ident_type = IdentType::Binding;
f.params.visit_mut_with(self);
f.return_type.visit_mut_with(self);
self.ident_type = IdentType::Ref;
if let Some(body) = &mut f.body {
self.mark_block(&mut body.ctxt);
let old_strict_mode = self.strict_mode;
if !self.strict_mode {
self.strict_mode = body
.stmts
.first()
.map(|stmt| stmt.is_use_strict())
.unwrap_or(false);
}
// Prevent creating new scope.
body.visit_mut_children_with(self);
self.strict_mode = old_strict_mode;
}
}
fn visit_mut_getter_prop(&mut self, f: &mut GetterProp) {
let old = self.ident_type;
self.ident_type = IdentType::Ref;
f.key.visit_mut_with(self);
self.ident_type = old;
f.type_ann.visit_mut_with(self);
f.body.visit_mut_with(self);
}
fn visit_mut_jsx_element_name(&mut self, node: &mut JSXElementName) {
if let JSXElementName::Ident(i) = node {
if i.as_ref().starts_with(|c: char| c.is_ascii_lowercase()) {
if cfg!(debug_assertions) && LOG {
debug!("\t -> JSXElementName");
}
let ctxt = i.ctxt.apply_mark(self.config.unresolved_mark);
if cfg!(debug_assertions) && LOG {
debug!("\t -> {:?}", ctxt);
}
i.ctxt = ctxt;
return;
}
}
node.visit_mut_children_with(self);
}
fn visit_mut_ident(&mut self, i: &mut Ident) {
if i.ctxt != SyntaxContext::empty() {
return;
}
match self.ident_type {
IdentType::Binding => self.modify(i, self.decl_kind),
IdentType::Ref => {
let Ident { sym, ctxt, .. } = i;
if cfg!(debug_assertions) && LOG {
debug!("IdentRef (type = {}) {}{:?}", self.in_type, sym, ctxt);
}
if *ctxt != SyntaxContext::empty() {
return;
}
if let Some(mark) = self.mark_for_ref(sym) {
let ctxt = ctxt.apply_mark(mark);
if cfg!(debug_assertions) && LOG {
debug!("\t -> {:?}", ctxt);
}
i.ctxt = ctxt;
} else {
if cfg!(debug_assertions) && LOG {
debug!("\t -> Unresolved");
}
let ctxt = ctxt.apply_mark(self.config.unresolved_mark);
if cfg!(debug_assertions) && LOG {
debug!("\t -> {:?}", ctxt);
}
i.ctxt = ctxt;
// Support hoisting
self.modify(i, self.decl_kind)
}
}
// We currently does not touch labels
IdentType::Label => {}
}
}
fn visit_mut_import_decl(&mut self, n: &mut ImportDecl) {
// Always resolve the import declaration identifiers even if it's type only.
// We need to analyze these identifiers for type stripping purposes.
self.ident_type = IdentType::Binding;
let old_in_type = self.in_type;
self.in_type = n.type_only;
n.visit_mut_children_with(self);
self.in_type = old_in_type;
}
fn visit_mut_import_named_specifier(&mut self, s: &mut ImportNamedSpecifier) {
let old = self.ident_type;
self.ident_type = IdentType::Binding;
s.local.visit_mut_with(self);
if self.config.handle_types {
self.current.declared_types.insert(s.local.sym.clone());
}
self.ident_type = old;
}
fn visit_mut_import_specifier(&mut self, s: &mut ImportSpecifier) {
let old = self.ident_type;
self.ident_type = IdentType::Binding;
match s {
ImportSpecifier::Named(ImportNamedSpecifier { imported: None, .. })
| ImportSpecifier::Namespace(..)
| ImportSpecifier::Default(..) => s.visit_mut_children_with(self),
ImportSpecifier::Named(s) => s.local.visit_mut_with(self),
}
self.ident_type = old;
}
/// Ignore.
///
/// See https://github.com/swc-project/swc/issues/2854
fn visit_mut_jsx_attr_name(&mut self, _: &mut JSXAttrName) {}
fn visit_mut_key_value_pat_prop(&mut self, n: &mut KeyValuePatProp) {
n.key.visit_mut_with(self);
n.value.visit_mut_with(self);
}
fn visit_mut_labeled_stmt(&mut self, s: &mut LabeledStmt) {
let old = self.ident_type;
self.ident_type = IdentType::Label;
s.label.visit_mut_with(self);
self.ident_type = old;
s.body.visit_mut_with(self);
}
fn visit_mut_method_prop(&mut self, m: &mut MethodProp) {
m.key.visit_mut_with(self);
// Child folder
self.with_child(ScopeKind::Fn, |child| m.function.visit_mut_with(child));
}
fn visit_mut_module(&mut self, module: &mut Module) {
self.strict_mode = true;
self.is_module = true;
module.visit_mut_children_with(self)
}
fn visit_mut_module_items(&mut self, stmts: &mut Vec<ModuleItem>) {
if !self.in_ts_module && self.current.kind != ScopeKind::Fn {
return stmts.visit_mut_children_with(self);
}
// Phase 1: Handle hoisting
{
let mut hoister = Hoister {
kind: self.decl_kind,
resolver: self,
in_block: false,
in_catch_body: false,
catch_param_decls: Default::default(),
excluded_from_catch: Default::default(),
};
stmts.visit_mut_with(&mut hoister)
}
// Phase 2.
stmts.visit_mut_children_with(self)
}
fn visit_mut_named_export(&mut self, e: &mut NamedExport) {
if e.src.is_some() {
return;
}
e.visit_mut_children_with(self);
}
fn visit_mut_object_lit(&mut self, o: &mut ObjectLit) {
self.with_child(ScopeKind::Block, |child| {
o.visit_mut_children_with(child);
});
}
fn visit_mut_param(&mut self, param: &mut Param) {
self.ident_type = IdentType::Binding;
param.visit_mut_children_with(self);
}
fn visit_mut_pat(&mut self, p: &mut Pat) {
p.visit_mut_children_with(self);
}
fn visit_mut_private_method(&mut self, m: &mut PrivateMethod) {
m.key.visit_mut_with(self);
{
// Child folder
self.with_child(ScopeKind::Fn, |child| m.function.visit_mut_with(child));
}
}
fn visit_mut_private_name(&mut self, _: &mut PrivateName) {}
fn visit_mut_prop_name(&mut self, n: &mut PropName) {
if let PropName::Computed(c) = n {
c.visit_mut_with(self);
}
}
fn visit_mut_rest_pat(&mut self, node: &mut RestPat) {
node.arg.visit_mut_with(self);
node.type_ann.visit_mut_with(self);
}
fn visit_mut_script(&mut self, script: &mut Script) {
self.strict_mode = script
.body
.first()
.map(|stmt| stmt.is_use_strict())
.unwrap_or(false);
script.visit_mut_children_with(self)
}
fn visit_mut_setter_prop(&mut self, n: &mut SetterProp) {
n.key.visit_mut_with(self);
{
self.with_child(ScopeKind::Fn, |child| {
child.ident_type = IdentType::Binding;
n.this_param.visit_mut_with(child);
n.param.visit_mut_with(child);
n.body.visit_mut_with(child);
});
};
}
fn visit_mut_stmts(&mut self, stmts: &mut Vec<Stmt>) {
let _span = if LOG {
Some(span!(Level::ERROR, "visit_mut_stmts").entered())
} else {
None
};
// Phase 1: Handle hoisting
{
let _span = if LOG {
Some(span!(Level::ERROR, "hoist").entered())
} else {
None
};
let mut hoister = Hoister {
kind: self.decl_kind,
resolver: self,
in_block: false,
in_catch_body: false,
catch_param_decls: Default::default(),
excluded_from_catch: Default::default(),
};
stmts.visit_mut_with(&mut hoister)
}
// Phase 2.
stmts.visit_mut_children_with(self)
}
fn visit_mut_switch_case(&mut self, n: &mut SwitchCase) {
n.cons.visit_mut_with(self);
n.test.visit_mut_with(self);
}
fn visit_mut_switch_stmt(&mut self, s: &mut SwitchStmt) {
s.discriminant.visit_mut_with(self);
self.with_child(ScopeKind::Block, |child| {
s.cases.visit_mut_with(child);
});
}
fn visit_mut_ts_as_expr(&mut self, n: &mut TsAsExpr) {
if self.config.handle_types {
n.type_ann.visit_mut_with(self);
}
n.expr.visit_mut_with(self);
}
fn visit_mut_ts_call_signature_decl(&mut self, n: &mut TsCallSignatureDecl) {
if !self.config.handle_types {
return;
}
self.with_child(ScopeKind::Fn, |child| {
child.in_type = true;
n.type_params.visit_mut_with(child);
n.params.visit_mut_with(child);
n.type_ann.visit_mut_with(child);
});
}
fn visit_mut_ts_construct_signature_decl(&mut self, decl: &mut TsConstructSignatureDecl) {
if !self.config.handle_types {
return;
}
// Child folder
self.with_child(ScopeKind::Fn, |child| {
child.in_type = true;
// order is important
decl.type_params.visit_mut_with(child);
decl.params.visit_mut_with(child);
decl.type_ann.visit_mut_with(child);
});
}
fn visit_mut_ts_constructor_type(&mut self, ty: &mut TsConstructorType) {
if !self.config.handle_types {
return;
}
self.with_child(ScopeKind::Fn, |child| {
child.in_type = true;
ty.type_params.visit_mut_with(child);
ty.params.visit_mut_with(child);
ty.type_ann.visit_mut_with(child);
});
}
fn visit_mut_ts_enum_decl(&mut self, decl: &mut TsEnumDecl) {
if decl.declare && !self.config.handle_types {
return;
}
self.modify(&mut decl.id, DeclKind::Lexical);
self.with_child(ScopeKind::Block, |child| {
// add the enum member names as declared symbols for this scope
// Ex. `enum Foo { a, b = a }`
let member_names = decl.members.iter().filter_map(|m| match &m.id {
TsEnumMemberId::Ident(id) => Some((id.sym.clone(), DeclKind::Lexical)),
TsEnumMemberId::Str(_) => None,
});
child.current.declared_symbols.extend(member_names);
decl.members.visit_mut_with(child);
});
}
fn visit_mut_ts_export_assignment(&mut self, node: &mut TsExportAssignment) {
node.expr.visit_mut_with(self);
if self.config.handle_types {
if let Some(i) = leftmost(&mut node.expr) {
self.try_resolving_as_type(i);
}
}
}
fn visit_mut_ts_expr_with_type_args(&mut self, n: &mut TsExprWithTypeArgs) {
if self.config.handle_types {
let old = self.in_type;
self.in_type = true;
n.visit_mut_children_with(self);
self.in_type = old;
}
}
fn visit_mut_ts_fn_type(&mut self, ty: &mut TsFnType) {
if !self.config.handle_types {
return;
}
self.with_child(ScopeKind::Fn, |child| {
child.in_type = true;
ty.type_params.visit_mut_with(child);
ty.params.visit_mut_with(child);
ty.type_ann.visit_mut_with(child);
});
}
fn visit_mut_ts_getter_signature(&mut self, n: &mut TsGetterSignature) {
if n.computed {
n.key.visit_mut_with(self);
}
n.type_ann.visit_mut_with(self);
}
fn visit_mut_ts_import_equals_decl(&mut self, n: &mut TsImportEqualsDecl) {
self.modify(&mut n.id, DeclKind::Lexical);
n.module_ref.visit_mut_with(self);
}
fn visit_mut_ts_import_type(&mut self, n: &mut TsImportType) {
if !self.config.handle_types {
return;
}
n.type_args.visit_mut_with(self);
}
fn visit_mut_ts_interface_decl(&mut self, n: &mut TsInterfaceDecl) {
// always resolve the identifier for type stripping purposes
let old_in_type = self.in_type;
let old_ident_type = self.ident_type;
self.in_type = true;
self.ident_type = IdentType::Ref;
self.modify(&mut n.id, DeclKind::Type);
if !self.config.handle_types {
self.in_type = old_in_type;
self.ident_type = old_ident_type;
return;
}
self.with_child(ScopeKind::Fn, |child| {
child.in_type = true;
n.type_params.visit_mut_with(child);
n.extends.visit_mut_with(child);
n.body.visit_mut_with(child);
});
self.in_type = old_in_type;
self.ident_type = old_ident_type;
}
fn visit_mut_ts_mapped_type(&mut self, n: &mut TsMappedType) {
if !self.config.handle_types {
return;
}
self.ident_type = IdentType::Binding;
n.type_param.visit_mut_with(self);
self.ident_type = IdentType::Ref;
n.name_type.visit_mut_with(self);
self.ident_type = IdentType::Ref;
n.type_ann.visit_mut_with(self);
}
fn visit_mut_ts_method_signature(&mut self, n: &mut TsMethodSignature) {
if !self.config.handle_types {
return;
}
self.with_child(ScopeKind::Fn, |child| {
child.in_type = true;
n.type_params.visit_mut_with(child);
if n.computed {
n.key.visit_mut_with(child);
}
n.params.visit_mut_with(child);
n.type_ann.visit_mut_with(child);
});
}
fn visit_mut_ts_module_decl(&mut self, decl: &mut TsModuleDecl) {
if decl.declare && !self.config.handle_types {
return;
}
match &mut decl.id {
TsModuleName::Ident(i) => {
self.modify(i, DeclKind::Lexical);
}
TsModuleName::Str(_) => {}
}
self.with_child(ScopeKind::Block, |child| {
child.in_ts_module = true;
decl.body.visit_mut_children_with(child);
});
}
fn visit_mut_ts_namespace_decl(&mut self, n: &mut TsNamespaceDecl) {
if n.declare && !self.config.handle_types {
return;
}
self.modify(&mut n.id, DeclKind::Lexical);
n.body.visit_mut_with(self);
}
fn visit_mut_ts_param_prop_param(&mut self, n: &mut TsParamPropParam) {
self.ident_type = IdentType::Binding;
n.visit_mut_children_with(self)
}
fn visit_mut_ts_property_signature(&mut self, n: &mut TsPropertySignature) {
if !self.config.handle_types {
return;
}
if n.computed {
n.key.visit_mut_with(self);
}
self.with_child(ScopeKind::Fn, |child| {
child.in_type = true;
n.type_ann.visit_mut_with(child);
});
}
fn visit_mut_ts_qualified_name(&mut self, n: &mut TsQualifiedName) {
self.ident_type = IdentType::Ref;
n.left.visit_mut_with(self)
}
fn visit_mut_ts_satisfies_expr(&mut self, n: &mut TsSatisfiesExpr) {
if self.config.handle_types {
n.type_ann.visit_mut_with(self);
}
n.expr.visit_mut_with(self);
}
fn visit_mut_ts_setter_signature(&mut self, n: &mut TsSetterSignature) {
if n.computed {
n.key.visit_mut_with(self);
}
n.param.visit_mut_with(self);
}
fn visit_mut_ts_tuple_element(&mut self, e: &mut TsTupleElement) {
if !self.config.handle_types {
return;
}
self.ident_type = IdentType::Ref;
e.ty.visit_mut_with(self);
}
fn visit_mut_ts_type_alias_decl(&mut self, n: &mut TsTypeAliasDecl) {
// always resolve the identifier for type stripping purposes
let old_in_type = self.in_type;
self.in_type = true;
self.modify(&mut n.id, DeclKind::Type);
if !self.config.handle_types {
self.in_type = old_in_type;
return;
}
self.with_child(ScopeKind::Fn, |child| {
child.in_type = true;
n.type_params.visit_mut_with(child);
n.type_ann.visit_mut_with(child);
});
self.in_type = old_in_type;
}
fn visit_mut_ts_type_assertion(&mut self, n: &mut TsTypeAssertion) {
if self.config.handle_types {
n.type_ann.visit_mut_with(self);
}
n.expr.visit_mut_with(self);
}
fn visit_mut_ts_type_param(&mut self, param: &mut TsTypeParam) {
if !self.config.handle_types {
return;
}
param.name.visit_mut_with(self);
let ident_type = self.ident_type;
param.default.visit_mut_with(self);
param.constraint.visit_mut_with(self);
self.ident_type = ident_type;
}
fn visit_mut_ts_type_params(&mut self, params: &mut Vec<TsTypeParam>) {
for param in params.iter_mut() {
param.name.visit_mut_with(self);
}
params.visit_mut_children_with(self);
}
fn visit_mut_using_decl(&mut self, decl: &mut UsingDecl) {
let old_kind = self.decl_kind;
self.decl_kind = DeclKind::Lexical;
decl.decls.visit_mut_with(self);
self.decl_kind = old_kind;
}
fn visit_mut_var_decl(&mut self, decl: &mut VarDecl) {
if decl.declare && !self.config.handle_types {
return;
}
let old_kind = self.decl_kind;
self.decl_kind = decl.kind.into();
decl.decls.visit_mut_with(self);
self.decl_kind = old_kind;
}
fn visit_mut_var_declarator(&mut self, decl: &mut VarDeclarator) {
// order is important
let old_type = self.ident_type;
self.ident_type = IdentType::Binding;
decl.name.visit_mut_with(self);
self.ident_type = old_type;
decl.init.visit_mut_children_with(self);
}
}
fn leftmost(expr: &mut Expr) -> Option<&mut Ident> {
match expr {
Expr::Ident(i) => Some(i),
Expr::Member(MemberExpr { obj, .. }) => leftmost(obj),
Expr::Paren(ParenExpr { expr, .. }) => leftmost(expr),
_ => None,
}
}
/// The folder which handles var / function hoisting.
struct Hoister<'a, 'b> {
resolver: &'a mut Resolver<'b>,
kind: DeclKind,
/// Hoister should not touch let / const in the block.
in_block: bool,
in_catch_body: bool,
excluded_from_catch: FxHashSet<Atom>,
catch_param_decls: FxHashSet<Atom>,
}
impl Hoister<'_, '_> {
fn add_pat_id(&mut self, id: &mut BindingIdent) {
if self.in_catch_body {
// If we have a binding, it's different variable.
if self.resolver.mark_for_ref_inner(&id.sym, true).is_some()
&& self.catch_param_decls.contains(&id.sym)
{
return;
}
self.excluded_from_catch.insert(id.sym.clone());
} else {
// Behavior is different
if self.catch_param_decls.contains(&id.sym)
&& !self.excluded_from_catch.contains(&id.sym)
{
return;
}
}
self.resolver.modify(id, self.kind)
}
}
impl VisitMut for Hoister<'_, '_> {
noop_visit_mut_type!();
#[inline]
fn visit_mut_arrow_expr(&mut self, _: &mut ArrowExpr) {}
fn visit_mut_assign_pat_prop(&mut self, node: &mut AssignPatProp) {
node.visit_mut_children_with(self);
self.add_pat_id(&mut node.key);
}
fn visit_mut_block_stmt(&mut self, n: &mut BlockStmt) {
let old_in_block = self.in_block;
self.in_block = true;
n.visit_mut_children_with(self);
self.in_block = old_in_block;
}
/// The code below prints "PASS"
///
/// ```js
///
/// var a = "PASS";
/// try {
/// throw "FAIL1";
/// } catch (a) {
/// var a = "FAIL2";
/// }
/// console.log(a);
/// ```
///
/// While the code below does not throw **ReferenceError** for `b`
///
/// ```js
///
/// b()
/// try {
/// } catch (b) {
/// var b;
/// }
/// ```
///
/// while the code below throws **ReferenceError**
///
/// ```js
///
/// b()
/// try {
/// } catch (b) {
/// }
/// ```
#[inline]
fn visit_mut_catch_clause(&mut self, c: &mut CatchClause) {
let old_exclude = self.excluded_from_catch.clone();
self.excluded_from_catch = Default::default();
let old_in_catch_body = self.in_catch_body;
let params: Vec<Id> = find_pat_ids(&c.param);
let orig = self.catch_param_decls.clone();
self.catch_param_decls
.extend(params.into_iter().map(|v| v.0));
self.in_catch_body = true;
c.body.visit_mut_with(self);
// let mut excluded = find_ids::<_, Id>(&c.body);
// excluded.retain(|id| {
// // If we already have a declartion named a, `var a` in the catch body is
// // different var.
// self.resolver.mark_for_ref(&id.0).is_none()
// });
self.in_catch_body = false;
c.param.visit_mut_with(self);
self.catch_param_decls = orig;
self.in_catch_body = old_in_catch_body;
self.excluded_from_catch = old_exclude;
}
fn visit_mut_class_decl(&mut self, node: &mut ClassDecl) {
if node.declare && !self.resolver.config.handle_types {
return;
}
if self.in_block {
return;
}
self.resolver.modify(&mut node.ident, DeclKind::Lexical);
if self.resolver.config.handle_types {
self.resolver
.current
.declared_types
.insert(node.ident.sym.clone());
}
}
#[inline]
fn visit_mut_constructor(&mut self, _: &mut Constructor) {}
#[inline]
fn visit_mut_decl(&mut self, decl: &mut Decl) {
decl.visit_mut_children_with(self);
if self.resolver.config.handle_types {
match decl {
Decl::TsInterface(i) => {
if self.in_block {
return;
}
let old_in_type = self.resolver.in_type;
self.resolver.in_type = true;
self.resolver.modify(&mut i.id, DeclKind::Type);
self.resolver.in_type = old_in_type;
}
Decl::TsTypeAlias(a) => {
let old_in_type = self.resolver.in_type;
self.resolver.in_type = true;
self.resolver.modify(&mut a.id, DeclKind::Type);
self.resolver.in_type = old_in_type;
}
Decl::TsEnum(e) => {
if !self.in_block {
let old_in_type = self.resolver.in_type;
self.resolver.in_type = false;
self.resolver.modify(&mut e.id, DeclKind::Lexical);
self.resolver.in_type = old_in_type;
}
}
Decl::TsModule(v)
if matches!(
&**v,
TsModuleDecl {
global: false,
id: TsModuleName::Ident(_),
..
},
) =>
{
if !self.in_block {
let old_in_type = self.resolver.in_type;
self.resolver.in_type = false;
let id = v.id.as_mut_ident().unwrap();
self.resolver.modify(id, DeclKind::Lexical);
self.resolver.in_type = old_in_type;
}
}
_ => {}
}
}
}
fn visit_mut_export_default_decl(&mut self, node: &mut ExportDefaultDecl) {
// Treat default exported functions and classes as declarations
// even though they are parsed as expressions.
match &mut node.decl {
DefaultDecl::Fn(f) => {
if let Some(id) = &mut f.ident {
self.resolver.modify(id, DeclKind::Var);
}
f.visit_mut_with(self)
}
DefaultDecl::Class(c) => {
if let Some(id) = &mut c.ident {
self.resolver.modify(id, DeclKind::Lexical);
}
c.visit_mut_with(self)
}
_ => {
node.visit_mut_children_with(self);
}
}
}
#[inline]
fn visit_mut_expr(&mut self, _: &mut Expr) {}
fn visit_mut_fn_decl(&mut self, node: &mut FnDecl) {
if node.declare && !self.resolver.config.handle_types {
return;
}
if self.catch_param_decls.contains(&node.ident.sym) {
return;
}
if self.in_block {
// function declaration is block scoped in strict mode
if self.resolver.strict_mode {
return;
}
// If we are in nested block, and variable named `foo` is lexically declared or
// a parameter, we should ignore function foo while handling upper scopes.
if let Some(DeclKind::Lexical | DeclKind::Param) =
self.resolver.current.is_declared(&node.ident.sym)
{
return;
}
}
self.resolver.modify(&mut node.ident, DeclKind::Function);
}
#[inline]
fn visit_mut_function(&mut self, _: &mut Function) {}
fn visit_mut_import_default_specifier(&mut self, n: &mut ImportDefaultSpecifier) {
n.visit_mut_children_with(self);
self.resolver.modify(&mut n.local, DeclKind::Lexical);
if self.resolver.config.handle_types {
self.resolver
.current
.declared_types
.insert(n.local.sym.clone());
}
}
fn visit_mut_import_named_specifier(&mut self, n: &mut ImportNamedSpecifier) {
n.visit_mut_children_with(self);
self.resolver.modify(&mut n.local, DeclKind::Lexical);
if self.resolver.config.handle_types {
self.resolver
.current
.declared_types
.insert(n.local.sym.clone());
}
}
fn visit_mut_import_star_as_specifier(&mut self, n: &mut ImportStarAsSpecifier) {
n.visit_mut_children_with(self);
self.resolver.modify(&mut n.local, DeclKind::Lexical);
if self.resolver.config.handle_types {
self.resolver
.current
.declared_types
.insert(n.local.sym.clone());
}
}
#[inline]
fn visit_mut_param(&mut self, _: &mut Param) {}
fn visit_mut_pat(&mut self, node: &mut Pat) {
match node {
Pat::Ident(i) => {
self.add_pat_id(i);
}
_ => node.visit_mut_children_with(self),
}
}
#[inline]
fn visit_mut_assign_target(&mut self, _: &mut AssignTarget) {}
#[inline]
fn visit_mut_setter_prop(&mut self, _: &mut SetterProp) {}
fn visit_mut_switch_stmt(&mut self, s: &mut SwitchStmt) {
s.discriminant.visit_mut_with(self);
let old_in_block = self.in_block;
self.in_block = true;
s.cases.visit_mut_with(self);
self.in_block = old_in_block;
}
#[inline]
fn visit_mut_tagged_tpl(&mut self, _: &mut TaggedTpl) {}
#[inline]
fn visit_mut_tpl(&mut self, _: &mut Tpl) {}
#[inline]
fn visit_mut_ts_module_block(&mut self, _: &mut TsModuleBlock) {}
#[inline]
fn visit_mut_using_decl(&mut self, _: &mut UsingDecl) {}
fn visit_mut_var_decl(&mut self, node: &mut VarDecl) {
if node.declare && !self.resolver.config.handle_types {
return;
}
if self.in_block {
match node.kind {
VarDeclKind::Const | VarDeclKind::Let => return,
_ => {}
}
}
let old_kind = self.kind;
self.kind = node.kind.into();
node.visit_mut_children_with(self);
self.kind = old_kind;
}
fn visit_mut_var_decl_or_expr(&mut self, n: &mut VarDeclOrExpr) {
match n {
VarDeclOrExpr::VarDecl(v)
if matches!(
&**v,
VarDecl {
kind: VarDeclKind::Let | VarDeclKind::Const,
..
}
) => {}
_ => {
n.visit_mut_children_with(self);
}
}
}
fn visit_mut_for_head(&mut self, n: &mut ForHead) {
match n {
ForHead::VarDecl(v)
if matches!(
&**v,
VarDecl {
kind: VarDeclKind::Let | VarDeclKind::Const,
..
}
) => {}
// Hoister should not handle lhs of for in statement below
//
// const b = [];
// {
// let a;
// for (a in b) {
// console.log(a);
// }
// }
ForHead::Pat(..) => {}
_ => {
n.visit_mut_children_with(self);
}
}
}
#[inline]
fn visit_mut_var_declarator(&mut self, node: &mut VarDeclarator) {
node.name.visit_mut_with(self);
}
/// should visit var decls first, cause var decl may appear behind the
/// usage. this can deal with code below:
/// ```js
/// try {} catch (Ic) {
/// throw Ic;
/// }
/// var Ic;
/// ```
/// the `Ic` defined by catch param and the `Ic` defined by `var Ic` are
/// different variables.
/// If we deal with the `var Ic` first, we can know
/// that there is already an global declaration of Ic when deal with the try
/// block.
fn visit_mut_module_items(&mut self, items: &mut Vec<ModuleItem>) {
items.iter_mut().for_each(|item| match item {
ModuleItem::Stmt(Stmt::Decl(Decl::Var(v)))
| ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
decl: Decl::Var(v),
..
})) if matches!(
&**v,
VarDecl {
kind: VarDeclKind::Var,
..
}
) =>
{
item.visit_mut_with(self);
}
ModuleItem::Stmt(Stmt::Decl(Decl::Fn(..)))
| ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
decl: Decl::Fn(..),
..
})) => {
item.visit_mut_with(self);
}
_ => item.visit_mut_with(self),
});
}
/// see docs for `self.visit_mut_module_items`
fn visit_mut_stmts(&mut self, stmts: &mut Vec<Stmt>) {
let others = stmts
.iter_mut()
.filter_map(|item| match item {
Stmt::Decl(Decl::Var(..)) => {
item.visit_mut_with(self);
None
}
Stmt::Decl(Decl::Fn(..)) => {
item.visit_mut_with(self);
None
}
_ => Some(item),
})
.collect::<Vec<_>>();
for other_stmt in others {
other_stmt.visit_mut_with(self);
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/src/resolver/tests.rs | Rust | use swc_ecma_parser::Syntax;
use super::*;
use crate::hygiene::Config;
// struct TsHygiene {
// top_level_mark: Mark,
// }
// impl VisitMut for TsHygiene {
// fn visit_mut_ident(&mut self, i: &mut Ident) {
// if SyntaxContext::empty().apply_mark(self.top_level_mark) ==
// i.ctxt { println!("ts_hygiene: {} is top-level", i.sym);
// return;
// }
// let ctxt = format!("{:?}", i.ctxt).replace("#", "");
// i.sym = format!("{}__{}", i.sym, ctxt).into();
// i.span = i.span.with_ctxt(SyntaxContext::empty());
// }
// fn visit_mut_member_expr(&mut self, n: &mut MemberExpr) {
// n.obj.visit_mut_with(self);
// if n.computed {
// n.prop.visit_mut_with(self);
// }
// }
// fn visit_mut_prop_name(&mut self, n: &mut PropName) {
// match n {
// PropName::Computed(n) => {
// n.visit_mut_with(self);
// }
// _ => {}
// }
// }
// fn visit_mut_ts_qualified_name(&mut self, q: &mut TsQualifiedName) {
// q.left.visit_mut_with(self);
// }
// }
fn run_test_with_config<F, V>(
syntax: Syntax,
tr: F,
src: &str,
to: &str,
config: impl FnOnce() -> crate::hygiene::Config,
) where
F: FnOnce() -> V,
V: Pass,
{
crate::tests::test_transform(syntax, |_| tr(), src, to, true, config);
}
#[test]
fn test_mark_for() {
::testing::run_test(false, |_, _| {
let mark1 = Mark::fresh(Mark::root());
let mark2 = Mark::fresh(mark1);
let mark3 = Mark::fresh(mark2);
let mark4 = Mark::fresh(mark3);
let folder1 = Resolver::new(
Scope::new(ScopeKind::Block, mark1, None),
InnerConfig {
handle_types: true,
unresolved_mark: Mark::fresh(Mark::root()),
top_level_mark: mark1,
},
);
let mut folder2 = Resolver::new(
Scope::new(ScopeKind::Block, mark2, Some(&folder1.current)),
InnerConfig {
handle_types: true,
unresolved_mark: Mark::fresh(Mark::root()),
top_level_mark: mark2,
},
);
folder2
.current
.declared_symbols
.insert("foo".into(), DeclKind::Var);
let mut folder3 = Resolver::new(
Scope::new(ScopeKind::Block, mark3, Some(&folder2.current)),
InnerConfig {
handle_types: true,
unresolved_mark: Mark::fresh(Mark::root()),
top_level_mark: mark3,
},
);
folder3
.current
.declared_symbols
.insert("bar".into(), DeclKind::Var);
assert_eq!(folder3.mark_for_ref(&"bar".into()), Some(mark3));
let mut folder4 = Resolver::new(
Scope::new(ScopeKind::Block, mark4, Some(&folder3.current)),
InnerConfig {
handle_types: true,
unresolved_mark: Mark::fresh(Mark::root()),
top_level_mark: mark4,
},
);
folder4
.current
.declared_symbols
.insert("foo".into(), DeclKind::Var);
assert_eq!(folder4.mark_for_ref(&"foo".into()), Some(mark4));
assert_eq!(folder4.mark_for_ref(&"bar".into()), Some(mark3));
Ok(())
})
.unwrap();
}
#[test]
fn issue_1279_1() {
run_test_with_config(
Default::default(),
|| resolver(Mark::new(), Mark::new(), false),
"class Foo {
static f = 1;
static g = Foo.f;
}",
"
let Foo = class Foo {
static f = 1;
static g = Foo.f;
};
",
|| Config {
keep_class_names: true,
..Default::default()
},
);
}
#[test]
fn issue_1279_2() {
run_test_with_config(
Default::default(),
|| resolver(Mark::new(), Mark::new(), false),
"class Foo {
static f = 1;
static g = Foo.f;
method() {
class Foo {
static nested = 1;
static nested2 = Foo.nested;
}
}
}",
"
let Foo = class Foo {
static f = 1;
static g = Foo.f;
method() {
let Foo = class Foo {
static nested = 1;
static nested2 = Foo.nested;
};
}
};
",
|| Config {
keep_class_names: true,
..Default::default()
},
);
}
#[test]
fn issue_2516() {
run_test_with_config(
Default::default(),
|| resolver(Mark::new(), Mark::new(), false),
"class A {
static A = class {}
}",
"
let A = class A {
static A = class {}
};
",
|| Config {
keep_class_names: true,
..Default::default()
},
);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/src/scope.rs | Rust | use swc_ecma_ast::VarDeclKind;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ScopeKind {
Block,
#[default]
Fn,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IdentType {
Binding,
Ref,
Label,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeclKind {
Lexical,
Param,
Var,
Function,
/// don't actually get stored
Type,
}
impl From<VarDeclKind> for DeclKind {
fn from(kind: VarDeclKind) -> Self {
match kind {
VarDeclKind::Const | VarDeclKind::Let => Self::Lexical,
VarDeclKind::Var => Self::Var,
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/src/tests.rs | Rust | use swc_common::{
comments::SingleThreadedComments,
errors::{Handler, HANDLER},
sync::Lrc,
FileName, SourceMap,
};
use swc_ecma_ast::*;
use swc_ecma_codegen::Emitter;
use swc_ecma_parser::{error::Error, lexer::Lexer, Parser, StringInput, Syntax};
use swc_ecma_utils::DropSpan;
use swc_ecma_visit::{Fold, FoldWith};
use crate::{fixer::fixer, helpers::HELPERS, hygiene::hygiene_with_config};
pub struct Tester<'a> {
pub cm: Lrc<SourceMap>,
pub handler: &'a Handler,
pub comments: Lrc<SingleThreadedComments>,
}
impl Tester<'_> {
pub fn run<F>(op: F)
where
F: FnOnce(&mut Tester<'_>) -> Result<(), ()>,
{
let out = ::testing::run_test(false, |cm, handler| {
HANDLER.set(handler, || {
HELPERS.set(&Default::default(), || {
op(&mut Tester {
cm,
handler,
comments: Default::default(),
})
})
})
});
match out {
Ok(()) => {}
Err(stderr) => panic!("Stderr:\n{}", stderr),
}
}
pub fn with_parser<F, T>(
&mut self,
file_name: &str,
syntax: Syntax,
src: &str,
op: F,
) -> Result<T, ()>
where
F: FnOnce(&mut Parser<Lexer>) -> Result<T, Error>,
{
let fm = self
.cm
.new_source_file(FileName::Real(file_name.into()).into(), src.into());
let mut p = Parser::new(syntax, StringInput::from(&*fm), Some(&self.comments));
let res = op(&mut p).map_err(|e| e.into_diagnostic(self.handler).emit());
for e in p.take_errors() {
e.into_diagnostic(self.handler).emit()
}
res
}
pub fn parse_module(&mut self, file_name: &str, src: &str) -> Result<Module, ()> {
self.with_parser(file_name, Syntax::default(), src, |p| p.parse_module())
}
pub fn parse_stmts(&mut self, file_name: &str, src: &str) -> Result<Vec<Stmt>, ()> {
let stmts = self.with_parser(file_name, Syntax::default(), src, |p| {
p.parse_script().map(|script| script.body)
})?;
Ok(stmts)
}
pub fn parse_stmt(&mut self, file_name: &str, src: &str) -> Result<Stmt, ()> {
let mut stmts = self.parse_stmts(file_name, src)?;
assert!(stmts.len() == 1);
Ok(stmts.pop().unwrap())
}
pub fn apply_transform<T: Pass>(
&mut self,
tr: T,
name: &str,
syntax: Syntax,
src: &str,
) -> Result<Program, ()> {
let fm = self
.cm
.new_source_file(FileName::Real(name.into()).into(), src.into());
let module = {
let mut p = Parser::new(syntax, StringInput::from(&*fm), Some(&self.comments));
let res = p
.parse_module()
.map_err(|e| e.into_diagnostic(self.handler).emit());
for e in p.take_errors() {
e.into_diagnostic(self.handler).emit()
}
res?
};
let module = Program::Module(module).apply(tr).apply(DropSpan);
Ok(module)
}
pub fn print(&mut self, program: &Program) -> String {
let mut buf = Vec::new();
{
let mut emitter = Emitter {
cfg: Default::default(),
cm: self.cm.clone(),
wr: Box::new(swc_ecma_codegen::text_writer::JsWriter::new(
self.cm.clone(),
"\n",
&mut buf,
None,
)),
comments: None,
};
// println!("Emitting: {:?}", module);
emitter.emit_program(program).unwrap();
}
let s = String::from_utf8_lossy(&buf);
s.to_string()
}
}
pub(crate) struct HygieneVisualizer;
impl Fold for HygieneVisualizer {
fn fold_ident(&mut self, ident: Ident) -> Ident {
Ident {
sym: format!("{}{:?}", ident.sym, ident.ctxt).into(),
..ident
}
}
}
pub(crate) fn test_transform<F, P>(
syntax: Syntax,
tr: F,
input: &str,
expected: &str,
ok_if_code_eq: bool,
hygiene_config: impl FnOnce() -> crate::hygiene::Config,
) where
F: FnOnce(&mut Tester) -> P,
P: Pass,
{
crate::tests::Tester::run(|tester| {
let expected = tester.apply_transform(DropSpan, "output.js", syntax, expected)?;
println!("----- Actual -----");
let tr = tr(tester);
let actual = tester.apply_transform(tr, "input.js", syntax, input)?;
match ::std::env::var("PRINT_HYGIENE") {
Ok(ref s) if s == "1" => {
let hygiene_src = tester.print(&actual.clone().fold_with(&mut HygieneVisualizer));
println!("----- Hygiene -----\n{}", hygiene_src);
}
_ => {}
}
let actual = actual
.apply(hygiene_with_config(hygiene_config()))
.apply(fixer(None))
.apply(DropSpan);
if actual == expected {
return Ok(());
}
let (actual_src, expected_src) = (tester.print(&actual), tester.print(&expected));
if actual_src == expected_src {
if ok_if_code_eq {
return Ok(());
}
// Diff it
println!(">>>>> Code <<<<<\n{}", actual_src);
assert_eq!(actual, expected, "different ast was detected");
return Err(());
}
println!(">>>>> Orig <<<<<\n{}", input);
println!(">>>>> Code <<<<<\n{}", actual_src);
if actual_src != expected_src {
panic!(
r#"assertion failed: `(left == right)`
{}"#,
::testing::diff(&actual_src, &expected_src),
);
}
Err(())
});
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/fixer_test262.rs | Rust | #![feature(test)]
extern crate test;
use std::{
env,
fs::{read_dir, File},
io::{self, Read, Write},
path::Path,
sync::{Arc, RwLock},
};
use swc_ecma_ast::*;
use swc_ecma_codegen::Emitter;
use swc_ecma_parser::{lexer::Lexer, Parser, Syntax};
use swc_ecma_transforms_base::fixer::fixer;
use swc_ecma_utils::DropSpan;
use swc_ecma_visit::{Fold, FoldWith, VisitMutWith};
use test::{
test_main, DynTestFn, Options, ShouldPanic::No, TestDesc, TestDescAndFn, TestName, TestType,
};
const IGNORED_PASS_TESTS: &[&str] = &[
// TODO: unignore
"5654d4106d7025c2.js",
"431ecef8c85d4d24.js",
// Stack size (Stupid parens)
"6b5e7e125097d439.js",
"714be6d28082eaa7.js",
"882910de7dd1aef9.js",
"dd3c63403db5c06e.js",
// Generated code is better than it from `pass`
"0da4b57d03d33129.js",
"aec65a9745669870.js",
"1c055d256ec34f17.js",
"d57a361bc638f38c.js",
"95520bedf0fdd4c9.js",
"5f1e0eff7ac775ee.js",
"90ad0135b905a622.js",
"7da12349ac9f51f2.js",
"46173461e93df4c2.js",
"446ffc8afda7e47f.js",
"3b5d1fb0e093dab8.js",
"0140c25a4177e5f7.module.js",
"e877f5e6753dc7e4.js",
"aac70baa56299267.js",
// Wrong tests (normalized expected.js is wrong)
"50c6ab935ccb020a.module.js",
"9949a2e1a6844836.module.js",
"1efde9ddd9d6e6ce.module.js",
// Wrong tests (variable name or value is different)
"8386fbff927a9e0e.js",
"0339fa95c78c11bd.js",
"0426f15dac46e92d.js",
"0b4d61559ccce0f9.js",
"0f88c334715d2489.js",
"1093d98f5fc0758d.js",
"15d9592709b947a0.js",
"2179895ec5cc6276.js",
"247a3a57e8176ebd.js",
"441a92357939904a.js",
"47f974d6fc52e3e4.js",
"4e1a0da46ca45afe.js",
"5829d742ab805866.js",
"589dc8ad3b9aa28f.js",
"598a5cedba92154d.js",
"72d79750e81ef03d.js",
"7788d3c1e1247da9.js",
"7b72d7b43bedc895.js",
"7dab6e55461806c9.js",
"82c827ccaecbe22b.js",
"87a9b0d1d80812cc.js",
"8c80f7ee04352eba.js",
"96f5d93be9a54573.js",
"988e362ed9ddcac5.js",
"9bcae7c7f00b4e3c.js",
"a8a03a88237c4e8f.js",
"ad06370e34811a6a.js",
"b0fdc038ee292aba.js",
"b62c6dd890bef675.js",
"cb211fadccb029c7.js",
"ce968fcdf3a1987c.js",
"db3c01738aaf0b92.js",
"e1387fe892984e2b.js",
"e71c1d5f0b6b833c.js",
"e8ea384458526db0.js",
// We don't implement Annex B fully.
"1c1e2a43fe5515b6.js",
"3dabeca76119d501.js",
"52aeec7b8da212a2.js",
"59ae0289778b80cd.js",
"a4d62a651f69d815.js",
"c06df922631aeabc.js",
// Unicode 14 vs 15
"046a0bb70d03d0cc.js",
"08a39e4289b0c3f3.js",
"300a638d978d0f2c.js",
"44f31660bd715f05.js",
];
fn add_test<F: FnOnce() -> Result<(), String> + Send + 'static>(
tests: &mut Vec<TestDescAndFn>,
name: String,
ignore: bool,
f: F,
) {
tests.push(TestDescAndFn {
desc: TestDesc {
test_type: TestType::UnitTest,
name: TestName::DynTestName(name),
ignore,
should_panic: No,
compile_fail: false,
no_run: false,
ignore_message: Default::default(),
source_file: Default::default(),
start_line: 0,
start_col: 0,
end_line: 0,
end_col: 0,
},
testfn: DynTestFn(Box::new(f)),
});
}
fn identity_tests(tests: &mut Vec<TestDescAndFn>) -> Result<(), io::Error> {
let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.join("swc_ecma_parser")
.join("tests")
.join("test262-parser");
eprintln!("Loading tests from {}", dir.display());
let normal = dir.join("pass");
let explicit = dir.join("pass-explicit");
for entry in read_dir(&explicit).expect("failed to read directory") {
let entry = entry?;
let file_name = entry
.path()
.strip_prefix(&explicit)
.expect("failed to strip prefix")
.to_str()
.expect("to_str() failed")
.to_string();
let input = {
let mut buf = String::new();
File::open(entry.path())?.read_to_string(&mut buf)?;
buf
};
let ignore = IGNORED_PASS_TESTS.contains(&&*file_name);
let module = file_name.contains("module");
let name = format!("fixer::{}", file_name);
add_test(tests, name, ignore, {
let normal = normal.clone();
move || {
eprintln!(
"\n\n========== Running fixer test {}\nSource:\n{}\n",
file_name, input
);
::testing::run_test(false, |cm, handler| {
let src = cm.load_file(&entry.path()).expect("failed to load file");
let expected = cm
.load_file(&normal.join(file_name))
.expect("failed to load reference file");
let mut wr = Buf(Arc::new(RwLock::new(Vec::new())));
let mut wr2 = Buf(Arc::new(RwLock::new(Vec::new())));
let mut parser: Parser<Lexer> =
Parser::new(Syntax::default(), (&*src).into(), None);
{
let mut emitter = Emitter {
cfg: swc_ecma_codegen::Config::default(),
cm: cm.clone(),
wr: Box::new(swc_ecma_codegen::text_writer::JsWriter::new(
cm.clone(),
"\n",
&mut wr,
None,
)),
comments: None,
};
let mut expected_emitter = Emitter {
cfg: swc_ecma_codegen::Config::default(),
cm: cm.clone(),
wr: Box::new(swc_ecma_codegen::text_writer::JsWriter::new(
cm, "\n", &mut wr2, None,
)),
comments: None,
};
// Parse source
let mut e_parser: Parser<Lexer> =
Parser::new(Syntax::default(), (&*expected).into(), None);
if module {
let module = parser
.parse_module()
.map(normalize)
.map(Program::Module)
.map(|p| p.apply(fixer(None)))
.map_err(|e| {
e.into_diagnostic(handler).emit();
})?;
let module2 = e_parser
.parse_module()
.map(normalize)
.map(Program::Module)
.map_err(|e| {
e.into_diagnostic(handler).emit();
})
.expect("failed to parse reference file");
if module == module2 {
return Ok(());
}
emitter.emit_program(&module).unwrap();
expected_emitter.emit_program(&module2).unwrap();
} else {
let script = parser
.parse_script()
.map(normalize)
.map(Program::Script)
.map(|p| p.apply(fixer(None)))
.map_err(|e| {
e.into_diagnostic(handler).emit();
})?;
let script2 = e_parser
.parse_script()
.map(normalize)
.map(Program::Script)
.map(|p| p.apply(fixer(None)))
.map_err(|e| {
e.into_diagnostic(handler).emit();
})?;
if script == script2 {
return Ok(());
}
emitter.emit_program(&script).unwrap();
expected_emitter.emit_program(&script2).unwrap();
}
}
for e in parser.take_errors() {
e.into_diagnostic(handler).emit();
}
let output = String::from_utf8_lossy(&wr.0.read().unwrap()).to_string();
let expected = String::from_utf8_lossy(&wr2.0.read().unwrap()).to_string();
if output == expected {
return Ok(());
}
eprintln!("Wrong output:\n{}\n-----\n{}", output, expected);
Err(())
})
.expect("failed to run test");
Ok(())
}
});
}
Ok(())
}
#[test]
fn identity() {
let args: Vec<_> = env::args().collect();
let mut tests = Vec::new();
identity_tests(&mut tests).expect("failed to load tests");
test_main(&args, tests, Some(Options::new()));
}
#[derive(Debug, Clone)]
struct Buf(Arc<RwLock<Vec<u8>>>);
impl Write for Buf {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
self.0.write().unwrap().write(data)
}
fn flush(&mut self) -> io::Result<()> {
self.0.write().unwrap().flush()
}
}
struct Normalizer;
impl Fold for Normalizer {
fn fold_new_expr(&mut self, expr: NewExpr) -> NewExpr {
let mut expr = expr.fold_children_with(self);
expr.args = match expr.args {
Some(..) => expr.args,
None => Some(Vec::new()),
};
expr
}
fn fold_number(&mut self, n: Number) -> Number {
Number {
span: n.span,
value: n.value,
raw: None,
}
}
fn fold_prop_name(&mut self, name: PropName) -> PropName {
let name = name.fold_children_with(self);
match name {
PropName::Ident(i) => PropName::Str(Str {
raw: None,
value: i.sym,
span: i.span,
}),
PropName::Num(n) => {
let s = if n.value.is_infinite() {
if n.value.is_sign_positive() {
"Infinity".into()
} else {
"-Infinity".into()
}
} else {
format!("{}", n.value)
};
PropName::Str(Str {
raw: None,
value: s.into(),
span: n.span,
})
}
_ => name,
}
}
fn fold_simple_assign_target(&mut self, n: SimpleAssignTarget) -> SimpleAssignTarget {
let n = n.fold_children_with(self);
match n {
SimpleAssignTarget::Paren(ParenExpr { mut expr, .. }) => {
while let Expr::Paren(ParenExpr { expr: e, .. }) = *expr {
expr = e;
}
SimpleAssignTarget::try_from(expr).unwrap()
}
_ => n,
}
}
fn fold_stmt(&mut self, stmt: Stmt) -> Stmt {
let stmt = stmt.fold_children_with(self);
match stmt {
Stmt::Expr(ExprStmt { span, expr }) => match *expr {
Expr::Paren(ParenExpr { expr, .. }) => ExprStmt { span, expr }.into(),
_ => ExprStmt { span, expr }.into(),
},
_ => stmt,
}
}
fn fold_str(&mut self, s: Str) -> Str {
Str {
span: s.span,
value: s.value,
raw: None,
}
}
}
fn normalize<T>(node: T) -> T
where
T: FoldWith<Normalizer> + VisitMutWith<DropSpan>,
{
let mut node = node.fold_with(&mut Normalizer);
node.visit_mut_with(&mut DropSpan);
node
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/fixture.rs | Rust | use std::path::{Path, PathBuf};
use swc_common::{sync::Lrc, Mark, SourceMap, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_codegen::Emitter;
use swc_ecma_parser::{lexer::Lexer, EsSyntax, Parser, StringInput, Syntax, TsSyntax};
use swc_ecma_transforms_base::{fixer::fixer, resolver};
use swc_ecma_visit::{visit_mut_obj_and_computed, visit_mut_pass, VisitMut, VisitMutWith};
use testing::{fixture, run_test2, NormalizedOutput};
pub fn print(cm: Lrc<SourceMap>, program: &Program) -> String {
let mut buf = Vec::new();
{
let mut emitter = Emitter {
cfg: Default::default(),
cm: cm.clone(),
wr: Box::new(swc_ecma_codegen::text_writer::JsWriter::new(
cm, "\n", &mut buf, None,
)),
comments: None,
};
// println!("Emitting: {:?}", module);
emitter.emit_program(program).unwrap();
}
let s = String::from_utf8_lossy(&buf);
s.to_string()
}
fn run<F, P>(syntax: Syntax, input: &Path, op: F)
where
F: FnOnce() -> P,
P: Pass,
{
let dir = input.parent().unwrap();
let output = dir.join(format!(
"output.{}",
input.extension().unwrap().to_string_lossy(),
));
run_test2(false, |cm, handler| {
let fm = cm.load_file(input).unwrap();
let lexer = Lexer::new(syntax, EsVersion::latest(), StringInput::from(&*fm), None);
let mut parser = Parser::new_from(lexer);
let program = parser
.parse_program()
.map_err(|err| err.into_diagnostic(&handler).emit())?;
let mut folder = op();
let program = program.apply(&mut folder);
let actual = print(cm, &program);
let actual = NormalizedOutput::from(actual);
actual.compare_to_file(&output).unwrap();
Ok(())
})
.unwrap();
}
#[fixture("tests/resolver/**/input.js")]
fn test_resolver(input: PathBuf) {
run(
Syntax::Es(EsSyntax {
jsx: true,
..Default::default()
}),
&input,
|| {
let unresolved_mark = Mark::fresh(Mark::root());
(
resolver(unresolved_mark, Mark::new(), false),
visit_mut_pass(TsHygiene { unresolved_mark }),
fixer(None),
)
},
);
}
#[fixture("tests/ts-resolver/**/input.ts")]
#[fixture("tests/ts-resolver/**/input.tsx")]
fn test_ts_resolver(input: PathBuf) {
run(
Syntax::Typescript(TsSyntax {
decorators: true,
tsx: input.extension().filter(|ext| *ext == "tsx").is_some(),
..Default::default()
}),
&input,
|| {
let unresolved_mark = Mark::fresh(Mark::root());
(
resolver(unresolved_mark, Mark::new(), true),
visit_mut_pass(TsHygiene { unresolved_mark }),
fixer(None),
)
},
);
}
struct TsHygiene {
unresolved_mark: Mark,
}
impl VisitMut for TsHygiene {
visit_mut_obj_and_computed!();
fn visit_mut_ident(&mut self, i: &mut Ident) {
if SyntaxContext::empty().apply_mark(self.unresolved_mark) == i.ctxt {
println!("ts_hygiene: {} is unresolved", i.sym);
return;
}
let ctxt = format!("{:?}", i.ctxt).replace('#', "");
i.sym = format!("{}__{}", i.sym, ctxt).into();
i.ctxt = SyntaxContext::empty();
}
fn visit_mut_prop_name(&mut self, n: &mut PropName) {
if let PropName::Computed(n) = n {
n.visit_mut_with(self);
}
}
fn visit_mut_ts_qualified_name(&mut self, q: &mut TsQualifiedName) {
q.left.visit_mut_with(self);
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/par.rs | Rust | use swc_ecma_ast::*;
use swc_ecma_transforms_base::perf::Parallel;
use swc_ecma_transforms_macros::parallel;
use swc_ecma_visit::{Fold, VisitMut};
#[derive(Default, Clone, Copy)]
struct ExampleVisitMut;
impl Parallel for ExampleVisitMut {
fn merge(&mut self, _: Self) {}
fn create(&self) -> Self {
Self
}
}
#[parallel]
impl VisitMut for ExampleVisitMut {}
#[derive(Default, Clone, Copy)]
struct ExampleFold;
impl Parallel for ExampleFold {
fn merge(&mut self, _: Self) {}
fn create(&self) -> Self {
Self
}
}
#[parallel]
impl Fold for ExampleFold {}
#[test]
fn test() {
let _ = ExampleFold;
let _ = ExampleVisitMut;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/par_explode.rs | Rust | use swc_ecma_ast::*;
use swc_ecma_transforms_base::perf::{ParExplode, Parallel};
use swc_ecma_transforms_macros::parallel;
use swc_ecma_visit::{Fold, VisitMut};
#[derive(Default, Clone, Copy)]
struct ExampleVisitMut;
impl Parallel for ExampleVisitMut {
fn merge(&mut self, _: Self) {}
fn create(&self) -> Self {
Self
}
}
impl ParExplode for ExampleVisitMut {
fn after_one_stmt(&mut self, _: &mut Vec<Stmt>) {}
fn after_one_module_item(&mut self, _: &mut Vec<ModuleItem>) {}
}
#[parallel(explode)]
impl VisitMut for ExampleVisitMut {}
#[derive(Default, Clone, Copy)]
struct ExampleFold;
impl Parallel for ExampleFold {
fn merge(&mut self, _: Self) {}
fn create(&self) -> Self {
Self
}
}
impl ParExplode for ExampleFold {
fn after_one_stmt(&mut self, _: &mut Vec<swc_ecma_ast::Stmt>) {}
fn after_one_module_item(&mut self, _: &mut Vec<ModuleItem>) {}
}
#[parallel(explode)]
impl Fold for ExampleFold {}
#[test]
fn test_1() {
let _ = ExampleFold;
let _ = ExampleVisitMut;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/babel/issue/.1051/input.js | JavaScript | foo.func1 = function () {
if (cond1) {
for (;;) {
if (cond2) {
function func2() {}
function func3() {}
func4(function () {
func2();
});
break;
}
}
}
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/babel/issue/.2174/input.js | JavaScript | if (true) {
function foo() {}
function bar() {
return foo;
}
for (var x in {}) {
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/babel/issue/.4363/input.js | JavaScript | function WithoutCurlyBraces() {
if (true)
for (let k in kv) {
function foo() {
return this;
}
function bar() {
return foo.call(this);
}
console.log(this, k); // => undefined
}
}
function WithCurlyBraces() {
if (true) {
for (let k in kv) {
function foo() {
return this;
}
function bar() {
return foo.call(this);
}
console.log(this, k); // => 777
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/babel/issue/.4946/input.js | JavaScript | (function foo() {
let foo = true;
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/babel/issue/973/input.js | JavaScript | let arr = [];
for (let i = 0; i < 10; i++) {
for (let i = 0; i < 10; i++) {
arr.push(() => i);
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/babel/issue/973/output.js | JavaScript | let arr__2 = [];
for(let i__3 = 0; i__3 < 10; i__3++){
for(let i__5 = 0; i__5 < 10; i__5++){
arr__2.push(()=>i__5);
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/basic/1/input.js | JavaScript | {
var foo = 1;
{
let foo = 2;
use(foo);
}
use(foo);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/basic/1/output.js | JavaScript | {
var foo__2 = 1;
{
let foo__4 = 2;
use(foo__4);
}
use(foo__2);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/basic/no-usage/input.js | JavaScript | let foo;
{
let foo;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/basic/no-usage/output.js | JavaScript | let foo__2;
{
let foo__3;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/block/scope/class/input.js | JavaScript | const g = 20;
function baz() {
{
class g {}
console.log(g);
}
return g;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/block/scope/class/output.js | JavaScript | const g__2 = 20;
function baz__2() {
{
class g__4 {
}
console.log(g__4);
}
return g__2;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/block/1/input.js | JavaScript | var Foo = (function (_Bar) {
_inherits(Foo, _Bar);
function Foo() {}
return Foo;
})(Bar);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/block/1/output.js | JavaScript | var Foo__2 = function(_Bar__3) {
_inherits(Foo__3, _Bar__3);
function Foo__3() {}
return Foo__3;
}(Bar);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/block/2/input.js | JavaScript | var Foo = (function (_Bar) {
_inherits(Foo, _Bar);
function Foo() {}
return Foo;
})(Bar);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/block/2/output.js | JavaScript | var Foo__2 = function(_Bar__3) {
_inherits(Foo__3, _Bar__3);
function Foo__3() {}
return Foo__3;
}(Bar);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/expr/scope/input.js | JavaScript | let Test = 2;
test(
class Test {
hi() {
console.log(Test);
}
}
);
Test = 4;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/expr/scope/output.js | JavaScript | let Test__2 = 2;
test(class Test__3 {
hi() {
console.log(Test__3);
}
});
Test__2 = 4;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/nested/input.js | JavaScript | var Outer = (function (_Hello) {
_inherits(Outer, _Hello);
function Outer() {
_classCallCheck(this, Outer);
var _this = _possibleConstructorReturn(
this,
_getPrototypeOf(Outer).call(this)
);
var Inner = (function () {
function Inner() {
_classCallCheck(this, Inner);
}
_createClass(Inner, [
{
key: _get(
_getPrototypeOf(Outer.prototype),
"toString",
_assertThisInitialized(_this)
).call(_this),
value: function () {
return "hello";
},
},
]);
return Inner;
})();
return _possibleConstructorReturn(_this, new Inner());
}
return Outer;
})(Hello);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/nested/output.js | JavaScript | var Outer__2 = function(_Hello__3) {
_inherits(Outer__3, _Hello__3);
function Outer__3() {
_classCallCheck(this, Outer__3);
var _this__4 = _possibleConstructorReturn(this, _getPrototypeOf(Outer__3).call(this));
var Inner__4 = function() {
function Inner__5() {
_classCallCheck(this, Inner__5);
}
_createClass(Inner__5, [
{
key: _get(_getPrototypeOf(Outer__3.prototype), "toString", _assertThisInitialized(_this__4)).call(_this__4),
value: function() {
return "hello";
}
}
]);
return Inner__5;
}();
return _possibleConstructorReturn(_this__4, new Inner__4());
}
return Outer__3;
}(Hello);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/nested/var/input.js | JavaScript | var ConstructorScoping = function ConstructorScoping() {
_classCallCheck(this, ConstructorScoping);
var bar;
{
let bar;
use(bar);
}
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/nested/var/output.js | JavaScript | var ConstructorScoping__2 = function ConstructorScoping__3() {
_classCallCheck(this, ConstructorScoping__3);
var bar__4;
{
let bar__5;
use(bar__5);
}
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/singleton/input.js | JavaScript | var singleton;
var Sub = (function (_Foo) {
_inherits(Sub, _Foo);
function Sub() {
var _this;
_classCallCheck(this, Sub);
if (singleton) {
return _possibleConstructorReturn(_this, singleton);
}
singleton = _this = _possibleConstructorReturn(
this,
_getPrototypeOf(Sub).call(this)
);
return _possibleConstructorReturn(_this);
}
return Sub;
})(Foo);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/singleton/output.js | JavaScript | var singleton__2;
var Sub__2 = function(_Foo__3) {
_inherits(Sub__3, _Foo__3);
function Sub__3() {
var _this__4;
_classCallCheck(this, Sub__3);
if (singleton__2) {
return _possibleConstructorReturn(_this__4, singleton__2);
}
singleton__2 = _this__4 = _possibleConstructorReturn(this, _getPrototypeOf(Sub__3).call(this));
return _possibleConstructorReturn(_this__4);
}
return Sub__3;
}(Foo);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/super/input.js | JavaScript | function foo() {
const sym = "dasdas";
return class Bar extends Foo {
[sym]() {
return super[sym]() + super.sym();
}
};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/super/output.js | JavaScript | function foo__2() {
const sym__3 = "dasdas";
return class Bar__4 extends Foo {
[sym__3]() {
return super[sym__3]() + super.sym();
}
};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/var/1/input.js | JavaScript | var Foo = (function (_Bar) {
_inherits(Foo, _Bar);
function Foo() {
var _this;
_classCallCheck(this, Foo);
Foo[_assertThisInitialized(_this)];
return _possibleConstructorReturn(_this);
}
return Foo;
})(Bar);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/var/1/output.js | JavaScript | var Foo__2 = function(_Bar__3) {
_inherits(Foo__3, _Bar__3);
function Foo__3() {
var _this__4;
_classCallCheck(this, Foo__3);
Foo__3[_assertThisInitialized(_this__4)];
return _possibleConstructorReturn(_this__4);
}
return Foo__3;
}(Bar);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/var/constructor-only/input.js | JavaScript | var Foo = function Foo() {};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/class/var/constructor-only/output.js | JavaScript | var Foo__2 = function Foo__3() {};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/deno/8620/1/input.js | JavaScript | const b = 1;
const b1 = 2;
{
const b = 3;
const b1 = 4;
const b2 = 5;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/deno/8620/1/output.js | JavaScript | const b__2 = 1;
const b1__2 = 2;
{
const b__3 = 3;
const b1__3 = 4;
const b2__3 = 5;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/deno/9121/1/input.js | JavaScript | var _ = 1;
function wt(e, n, t, r) {
var l = e.updateQueue;
if (u !== null) {
if (y !== null) {
var _ = y.lastBaseUpdate;
}
}
if (i !== null) {
(_ = l.baseState), (o = 0), (y = d = s = null);
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/deno/9121/1/output.js | JavaScript | var ___2 = 1;
function wt__2(e__3, n__3, t__3, r__3) {
var l__3 = e__3.updateQueue;
if (u !== null) {
if (y !== null) {
var ___3 = y.lastBaseUpdate;
}
}
if (i !== null) {
___3 = l__3.baseState, o = 0, y = d = s = null;
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/deno/9121/2/input.js | JavaScript | var _ = 1;
function wt() {
if (u !== null) {
if (y !== null) {
var _ = 2;
}
}
if (i !== null) {
_ = 3;
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/deno/9121/2/output.js | JavaScript | var ___2 = 1;
function wt__2() {
if (u !== null) {
if (y !== null) {
var ___3 = 2;
}
}
if (i !== null) {
___3 = 3;
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/export/default/class/decl/scope/input.js | JavaScript | export default class Test {
hi() {
let Test = 2;
console.log(Test);
}
}
Test = 2;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/export/default/class/decl/scope/output.js | JavaScript | export default class Test__2 {
hi() {
let Test__3 = 2;
console.log(Test__3);
}
}
Test__2 = 2;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/export/default/fn_decl/scope/input.js | JavaScript | export default function foo() {
foo = function foo(x) {
return x === 0 ? 1 : 1 + foo(x - 1);
};
return foo(10);
}
foo = 2;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/export/default/fn_decl/scope/output.js | JavaScript | export default function foo__2() {
foo__2 = function foo__4(x__5) {
return x__5 === 0 ? 1 : 1 + foo__4(x__5 - 1);
};
return foo__2(10);
}
foo__2 = 2;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/fn_expr/scope/input.js | JavaScript | test(function foo() {
foo = function foo(x) {
return x === 0 ? 1 : 1 + foo(x - 1);
};
return foo(10);
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/fn_expr/scope/output.js | JavaScript | test(function foo__3() {
foo__3 = function foo__5(x__6) {
return x__6 === 0 ? 1 : 1 + foo__5(x__6 - 1);
};
return foo__3(10);
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/for_of_hoisting/input.js | JavaScript | var k, v;
var map = new Map([["", true]]);
for ([k, ...[v]] of map) {
k;
v;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/for_of_hoisting/output.js | JavaScript | var k__2, v__2;
var map__2 = new Map([
[
"",
true
]
]);
for ([k__2, ...[v__2]] of map__2){
k__2;
v__2;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/function/block/input.js | JavaScript | export function k() {
function x() {
console.log("hi");
}
{
function x() {
console.log("merong");
}
}
return x;
}
k();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/function/block/output.js | JavaScript | export function k__2() {
function x__3() {
console.log("hi");
}
{
function x__5() {
console.log("merong");
}
}
return x__3;
}
k__2();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/function/body/input.js | JavaScript | let a = "foo";
function foo() {
let a = "bar";
use(a);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/function/body/output.js | JavaScript | let a__2 = "foo";
function foo__2() {
let a__3 = "bar";
use(a__3);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/function/hoist/input.js | JavaScript | function foo() {
const r = () => 1;
if (true) {
function r() {
return 2;
}
}
console.log(r());
}
function bar() {
var r = () => 1;
if (true) {
function r() {
return 2;
}
}
console.log(r());
}
function baz() {
function r() {
return 1;
}
if (true) {
function r() {
return 2;
}
}
console.log(r());
}
function quz(r = () => 1) {
if (true) {
function r() {
return 2;
}
}
console.log(r());
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/function/hoist/output.js | JavaScript | function foo__2() {
const r__3 = ()=>1;
if (true) {
function r__4() {
return 2;
}
}
console.log(r__3());
}
function bar__2() {
var r__6 = ()=>1;
if (true) {
function r__6() {
return 2;
}
}
console.log(r__6());
}
function baz__2() {
function r__9() {
return 1;
}
if (true) {
function r__9() {
return 2;
}
}
console.log(r__9());
}
function quz__2(r__13 = ()=>1) {
if (true) {
function r__14() {
return 2;
}
}
console.log(r__13());
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/function/param/input.js | JavaScript | let a = "foo";
function foo(a) {
use(a);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/function/param/output.js | JavaScript | let a__2 = "foo";
function foo__2(a__3) {
use(a__3);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/general/assignment/patterns/input.js | JavaScript | const foo = "foo";
function foobar() {
for (let item of [1, 2, 3]) {
let foo = "bar";
[bar, foo] = [1, 2];
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/general/assignment/patterns/output.js | JavaScript | const foo__2 = "foo";
function foobar__2() {
for (let item__4 of [
1,
2,
3
]){
let foo__5 = "bar";
[bar, foo__5] = [
1,
2
];
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/general/function/input.js | JavaScript | function test() {
let foo = "bar";
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/general/function/output.js | JavaScript | function test__2() {
let foo__3 = "bar";
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/global/globalThis/input.js | JavaScript | var globalThis = {};
console.log(globalThis);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/global/globalThis/output.js | JavaScript | var globalThis__2 = {};
console.log(globalThis__2);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/global/object/input.js | JavaScript | function foo(Object) {
Object.defineProperty();
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/global/object/output.js | JavaScript | function foo__2(Object__3) {
Object__3.defineProperty();
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/hoisting/input.js | JavaScript | function foo() {
return XXX;
}
var XXX = 1;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/hoisting/output.js | JavaScript | function foo__2() {
return XXX__2;
}
var XXX__2 = 1;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/in_constructor/input.js | JavaScript | class C {}
class A extends C {
constructor() {
super();
class B extends C {
constructor() {
super();
}
}
new B();
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/in_constructor/output.js | JavaScript | class C__2 {
}
class A__2 extends C__2 {
constructor(){
super();
class B__3 extends C__2 {
constructor(){
super();
}
}
new B__3();
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issue-4953/input.js | JavaScript | export default function (module, exports) {
"use strict";
!function (t, e) {
e(exports)
}(void 0, function (t) {
"use strict";
function vr(e, r, o) {
try {
} catch (t) {
}
function t() {
return '123';
}
return t;
}
t.vr = vr;
});
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issue-4953/output.js | JavaScript | export default function(module__3, exports__3) {
"use strict";
!function(t__4, e__4) {
e__4(exports__3);
}(void 0, function(t__5) {
"use strict";
function vr__5(e__6, r__6, o__6) {
try {} catch (t__8) {}
function t__6() {
return '123';
}
return t__6;
}
t__5.vr = vr__5;
});
}
;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issue-7248/input.js | JavaScript | const messages = [{ message: "hello" }];
const logs = messages.map(
({ log = () => console.log(message), message }) => log
);
logs[0]();
class A {
constructor({ log = () => console.log(message), message }) {}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issue-7248/output.js | JavaScript | const messages__2 = [
{
message: "hello"
}
];
const logs__2 = messages__2.map(({ log__3 = ()=>console.log(message__3), message__3 })=>log__3);
logs__2[0]();
class A__2 {
constructor({ log__4 = ()=>console.log(message__4), message__4 }){}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issue-7546/input.js | JavaScript | import { ClassName } from './some-file';
export default {
field: class ClassName extends ClassName {
constructor() {
super();
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issue-7546/output.js | JavaScript | import { ClassName__2 } from './some-file';
export default {
field: class ClassName__3 extends ClassName__2 {
constructor(){
super();
}
}
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issue-8528/input.js | JavaScript | let A;
B.A;
<C.A />;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issue-8528/output.js | JavaScript | let A__2;
B.A;
<C.A/>;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issues/1086/input.js | JavaScript | const b = [];
{
let a;
for (a in b) {
console.log(a);
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issues/1086/output.js | JavaScript | const b__2 = [];
{
let a__3;
for(a__3 in b__2){
console.log(a__3);
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issues/1140/input.js | JavaScript | const categories = [{ key: "apple" }, { key: "banana" }, { key: "strawberry" }];
const item = "some item";
const catNames = categories.reduce((a, item) => {
return { ...a, [item.key.toString()]: item };
}, {});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issues/1140/output.js | JavaScript | const categories__2 = [
{
key: "apple"
},
{
key: "banana"
},
{
key: "strawberry"
}
];
const item__2 = "some item";
const catNames__2 = categories__2.reduce((a__3, item__3)=>{
return {
...a__3,
[item__3.key.toString()]: item__3
};
}, {});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issues/1402/input.js | JavaScript | var e = 1;
try {
throw 2;
} catch (e) {
console.log(e);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issues/1402/output.js | JavaScript | var e__2 = 1;
try {
throw 2;
} catch (e__4) {
console.log(e__4);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issues/2021/1/input.js | JavaScript | class Item extends Component {
constructor(props) {
super(props);
}
input = this.props.item;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issues/2021/1/output.js | JavaScript | class Item__2 extends Component {
constructor(props__3){
super(props__3);
}
input = this.props.item;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issues/2550/input.js | JavaScript | let isNewPrefsActive = true;
() =>
({
isNewPrefsActive,
} && {
a: 1,
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issues/2550/output.js | JavaScript | let isNewPrefsActive__2 = true;
()=>({
isNewPrefsActive__2
}) && {
a: 1
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issues/271/input.js | JavaScript | function foo(scope) {
var startOperation = function startOperation1(operation) {
scope.agentOperation = operation;
};
scope.startOperation = startOperation;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_base/tests/resolver/issues/271/output.js | JavaScript | function foo__2(scope__3) {
var startOperation__3 = function startOperation1__4(operation__5) {
scope__3.agentOperation = operation__5;
};
scope__3.startOperation = startOperation__3;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.