Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(es/utils): Refine some APIs #9049

Merged
merged 12 commits into from
Jun 14, 2024
4 changes: 2 additions & 2 deletions crates/swc_bundler/src/bundler/chunk/cjs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{collections::HashMap, sync::atomic::Ordering};
use anyhow::Error;
use swc_common::{collections::AHashMap, Span, SyntaxContext, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::{quote_ident, undefined, ExprFactory};
use swc_ecma_utils::{quote_ident, ExprFactory};
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};

use crate::{
Expand Down Expand Up @@ -168,7 +168,7 @@ fn wrap_module(
)
.make_member(Ident::new("bind".into(), DUMMY_SP))
.as_callee(),
args: vec![undefined(DUMMY_SP).as_arg(), module_fn.as_arg()],
args: vec![Expr::undefined(DUMMY_SP).as_arg(), module_fn.as_arg()],
type_args: None,
}))),
definite: false,
Expand Down
20 changes: 18 additions & 2 deletions crates/swc_ecma_ast/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ use crate::{
TsAsExpr, TsConstAssertion, TsInstantiation, TsNonNullExpr, TsSatisfiesExpr, TsTypeAnn,
TsTypeAssertion, TsTypeParamDecl, TsTypeParamInstantiation,
},
ArrayPat, BindingIdent, ComputedPropName, Id, ImportPhase, Invalid, KeyValueProp, ObjectPat,
PropName, Str,
ArrayPat, BindingIdent, ComputedPropName, Id, ImportPhase, Invalid, KeyValueProp, Number,
ObjectPat, PropName, Str,
};

#[ast_node(no_clone)]
Expand Down Expand Up @@ -171,6 +171,22 @@ bridge_from!(Box<Expr>, Box<JSXElement>, JSXElement);
// assert_eq_size!(Expr, [u8; 80]);

impl Expr {
/// Creates `void 0`.
#[inline]
pub fn undefined(span: Span) -> Box<Expr> {
UnaryExpr {
span,
op: op!("void"),
arg: Lit::Num(Number {
span,
value: 0.0,
raw: None,
})
.into(),
}
.into()
}

pub fn leftmost(&self) -> Option<&Ident> {
match self {
Expr::Ident(i) => Some(i),
Expand Down
25 changes: 19 additions & 6 deletions crates/swc_ecma_ast/src/ident.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use phf::phf_set;
use scoped_tls::scoped_thread_local;
use swc_atoms::{js_word, Atom};
use swc_common::{
ast_node, util::take::Take, BytePos, EqIgnoreSpan, Span, Spanned, SyntaxContext, DUMMY_SP,
ast_node, util::take::Take, BytePos, EqIgnoreSpan, Mark, Span, Spanned, SyntaxContext, DUMMY_SP,
};

use crate::{typescript::TsTypeAnn, Expr};
Expand Down Expand Up @@ -307,6 +307,19 @@ impl Ident {
Err(buf)
}

/// Create a new identifier with the given prefix.
pub fn with_prefix(&self, prefix: &str) -> Ident {
Ident::new(format!("{}{}", prefix, self.sym).into(), self.span)
}

/// Create a private identifier that is unique in the file, but with the
/// same symbol.
pub fn into_private(self) -> Ident {
let span = self.span.apply_mark(Mark::new());

Self::new(self.sym, span)
}

#[inline]
pub fn is_dummy(&self) -> bool {
self.sym == js_word!("") && self.span.is_dummy()
Expand Down Expand Up @@ -446,7 +459,7 @@ static RESERVED_IN_ES3: phf::Set<&str> = phf_set!(
"volatile",
);

pub trait IdentExt: AsRef<str> {
pub trait EsReserved: AsRef<str> {
fn is_reserved(&self) -> bool {
RESERVED.contains(self.as_ref())
}
Expand Down Expand Up @@ -474,7 +487,7 @@ pub trait IdentExt: AsRef<str> {
}
}

impl IdentExt for Atom {}
impl IdentExt for Ident {}
impl IdentExt for &'_ str {}
impl IdentExt for String {}
impl EsReserved for Atom {}
impl EsReserved for Ident {}
impl EsReserved for &'_ str {}
impl EsReserved for String {}
2 changes: 1 addition & 1 deletion crates/swc_ecma_ast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub use self::{
decl::{ClassDecl, Decl, FnDecl, UsingDecl, VarDecl, VarDeclKind, VarDeclarator},
expr::*,
function::{Function, Param, ParamOrTsParamProp},
ident::{BindingIdent, Id, Ident, IdentExt, PrivateName},
ident::{BindingIdent, EsReserved, Id, Ident, PrivateName},
jsx::{
JSXAttr, JSXAttrName, JSXAttrOrSpread, JSXAttrValue, JSXClosingElement, JSXClosingFragment,
JSXElement, JSXElementChild, JSXElementName, JSXEmptyExpr, JSXExpr, JSXExprContainer,
Expand Down
10 changes: 5 additions & 5 deletions crates/swc_ecma_compat_es2015/src/block_scoping/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use swc_ecma_ast::*;
use swc_ecma_transforms_base::helper;
use swc_ecma_utils::{
find_pat_ids, function::FnEnvHoister, prepend_stmt, private_ident, quote_ident, quote_str,
undefined, ExprFactory, StmtLike,
ExprFactory, StmtLike,
};
use swc_ecma_visit::{
as_folder, noop_visit_mut_type, noop_visit_type, visit_mut_obj_and_computed, Fold, Visit,
Expand Down Expand Up @@ -596,7 +596,7 @@ impl VisitMut for BlockScoping {
if self.var_decl_kind == VarDeclKind::Var {
var.init = None
} else {
var.init = Some(undefined(var.span()))
var.init = Some(Expr::undefined(var.span()))
}
}
}
Expand Down Expand Up @@ -819,7 +819,7 @@ impl VisitMut for FlowHelper<'_> {
Box::new(Expr::Unary(UnaryExpr {
span: DUMMY_SP,
op: op!("void"),
arg: undefined(DUMMY_SP),
arg: Expr::undefined(DUMMY_SP),
}))
}),
})))],
Expand Down Expand Up @@ -869,7 +869,7 @@ struct MutationHandler<'a> {
impl MutationHandler<'_> {
fn make_reassignment(&self, orig: Option<Box<Expr>>) -> Expr {
if self.map.is_empty() {
return *orig.unwrap_or_else(|| undefined(DUMMY_SP));
return *orig.unwrap_or_else(|| Expr::undefined(DUMMY_SP));
}

let mut exprs = Vec::with_capacity(self.map.len() + 1);
Expand All @@ -885,7 +885,7 @@ impl MutationHandler<'_> {
))),
})));
}
exprs.push(orig.unwrap_or_else(|| undefined(DUMMY_SP)));
exprs.push(orig.unwrap_or_else(|| Expr::undefined(DUMMY_SP)));

Expr::Seq(SeqExpr {
span: DUMMY_SP,
Expand Down
12 changes: 6 additions & 6 deletions crates/swc_ecma_compat_es2015/src/classes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use swc_ecma_transforms_macros::fast_path;
use swc_ecma_utils::{
alias_if_required, contains_this_expr, default_constructor, is_valid_ident,
is_valid_prop_ident, prepend_stmt, private_ident, prop_name_to_expr, quote_expr, quote_ident,
quote_str, replace_ident, ExprFactory, IdentExt, ModuleItemLike, StmtLike,
quote_str, replace_ident, ExprFactory, ModuleItemLike, StmtLike,
};
use swc_ecma_visit::{
as_folder, noop_visit_mut_type, noop_visit_type, Fold, Visit, VisitMut, VisitMutWith, VisitWith,
Expand Down Expand Up @@ -264,7 +264,7 @@ where
} = d
{
if let Expr::Class(c @ ClassExpr { ident: None, .. }) = &mut **init {
c.ident = Some(i.id.clone().private())
c.ident = Some(i.id.clone().into_private())
}
}

Expand All @@ -275,7 +275,7 @@ where
fn visit_mut_assign_pat_prop(&mut self, n: &mut AssignPatProp) {
if let Some(value) = &mut n.value {
if let Expr::Class(c @ ClassExpr { ident: None, .. }) = &mut **value {
c.ident = Some((*n.key).clone().private());
c.ident = Some((*n.key).clone().into_private());
}
}

Expand All @@ -290,7 +290,7 @@ where
Expr::Class(c @ ClassExpr { ident: None, .. }),
) = (&*n.left, &mut *n.right)
{
c.ident = Some(id.clone().private())
c.ident = Some(id.clone().into_private())
}

n.visit_mut_children_with(self);
Expand All @@ -305,7 +305,7 @@ where
if let Expr::Class(c @ ClassExpr { ident: None, .. }) = &mut *n.value {
match &n.key {
PropName::Ident(ident) => {
c.ident = Some(ident.clone().private());
c.ident = Some(ident.clone().into_private());
}
PropName::Str(Str { value, span, .. }) => {
if is_valid_prop_ident(value) {
Expand Down Expand Up @@ -336,7 +336,7 @@ where
{
if let Expr::Class(c @ ClassExpr { ident: None, .. }) = &mut **right {
if let AssignTarget::Simple(SimpleAssignTarget::Ident(ident)) = left {
c.ident = Some((**ident).clone().private())
c.ident = Some((**ident).clone().into_private())
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions crates/swc_ecma_compat_es2015/src/destructuring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use swc_ecma_transforms_base::{helper, helper_expr, perf::Check};
use swc_ecma_transforms_macros::fast_path;
use swc_ecma_utils::{
alias_ident_for, alias_if_required, has_rest_pat, is_literal, member_expr, private_ident,
prop_name_to_expr, quote_ident, undefined, ExprFactory, StmtLike,
prop_name_to_expr, quote_ident, ExprFactory, StmtLike,
};
use swc_ecma_visit::{
as_folder, noop_visit_mut_type, noop_visit_type, Fold, Visit, VisitMut, VisitMutWith, VisitWith,
Expand Down Expand Up @@ -682,7 +682,7 @@ impl VisitMut for AssignFolder {
debug_assert_eq!(e.spread, None);
e.expr
})
.unwrap_or_else(|| undefined(p.span()));
.unwrap_or_else(|| Expr::undefined(p.span()));

let p = p.take();
let mut expr = if let Pat::Assign(pat) = p {
Expand Down Expand Up @@ -1002,7 +1002,7 @@ impl VisitMut for AssignFolder {
if var_decl.kind == VarDeclKind::Const {
var_decl.decls.iter_mut().for_each(|v| {
if v.init.is_none() {
v.init = Some(undefined(DUMMY_SP));
v.init = Some(Expr::undefined(DUMMY_SP));
}
})
}
Expand Down
9 changes: 4 additions & 5 deletions crates/swc_ecma_compat_es2015/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ use swc_common::{
use swc_ecma_ast::*;
use swc_ecma_transforms_base::helper;
use swc_ecma_utils::{
function::FnEnvHoister, private_ident, prop_name_to_expr_value, quote_ident, undefined,
ExprFactory,
function::FnEnvHoister, private_ident, prop_name_to_expr_value, quote_ident, ExprFactory,
};
use swc_ecma_visit::{
as_folder, noop_visit_mut_type, noop_visit_type, Fold, Visit, VisitMut, VisitMutWith, VisitWith,
Expand Down Expand Up @@ -812,7 +811,7 @@ impl VisitMut for Generator {
&mut args,
Some(ExprOrSpread {
spread: None,
expr: undefined(DUMMY_SP),
expr: Expr::undefined(DUMMY_SP),
}),
None,
))
Expand Down Expand Up @@ -3463,7 +3462,7 @@ impl Generator {
if is_new_call {
callee
} else {
undefined(DUMMY_SP)
Expr::undefined(DUMMY_SP)
},
),

Expand All @@ -3481,7 +3480,7 @@ impl Generator {

_ => {
if !is_new_call {
(callee, undefined(DUMMY_SP))
(callee, Expr::undefined(DUMMY_SP))
} else {
let this_arg = self.create_temp_variable();
let target = callee.make_assign_to(op!("="), this_arg.clone().into());
Expand Down
6 changes: 3 additions & 3 deletions crates/swc_ecma_compat_es2015/src/new_target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{borrow::Cow, mem};
use swc_common::{pass::CompilerPass, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::perf::{should_work, Check};
use swc_ecma_utils::{private_ident, quote_ident, undefined, ExprFactory};
use swc_ecma_utils::{private_ident, quote_ident, ExprFactory};
use swc_ecma_visit::{
as_folder, noop_visit_mut_type, noop_visit_type, Fold, Visit, VisitMut, VisitMutWith,
};
Expand Down Expand Up @@ -68,7 +68,7 @@ impl VisitMut for NewTarget {
};
match &self.ctx {
Ctx::Constructor => *e = this_ctor(*span),
Ctx::Method => *e = *undefined(DUMMY_SP),
Ctx::Method => *e = *Expr::undefined(DUMMY_SP),
Ctx::Function(i) => {
*e = Expr::Cond(CondExpr {
span: *span,
Expand All @@ -81,7 +81,7 @@ impl VisitMut for NewTarget {
})),
cons: Box::new(this_ctor(DUMMY_SP)),
// void 0
alt: undefined(DUMMY_SP),
alt: Expr::undefined(DUMMY_SP),
})
}
}
Expand Down
5 changes: 2 additions & 3 deletions crates/swc_ecma_compat_es2015/src/object_super.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use swc_ecma_ast::*;
use swc_ecma_transforms_base::helper;
use swc_ecma_utils::{
alias_ident_for, is_rest_arguments, prepend_stmt, private_ident, quote_ident, ExprFactory,
IdentExt,
};
use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith};
use swc_trace_macro::swc_trace;
Expand Down Expand Up @@ -397,7 +396,7 @@ impl SuperReplacer {
self.get_proto(),
super_token,
if computed {
let ref_ident = alias_ident_for(&rhs, "_ref").private();
let ref_ident = alias_ident_for(&rhs, "_ref").into_private();
self.vars.push(ref_ident.clone());
*prop = Expr::Assign(AssignExpr {
span: DUMMY_SP,
Expand Down Expand Up @@ -427,7 +426,7 @@ impl SuperReplacer {
.as_arg(),
)
} else {
let update_ident = alias_ident_for(&rhs, "_super").private();
let update_ident = alias_ident_for(&rhs, "_super").into_private();
self.vars.push(update_ident.clone());
Expr::Seq(SeqExpr {
span: DUMMY_SP,
Expand Down
10 changes: 5 additions & 5 deletions crates/swc_ecma_compat_es2015/src/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use swc_ecma_ast::*;
// use swc_ecma_transforms_macros::parallel;
use swc_ecma_utils::{
function::{init_this, FnEnvHoister},
member_expr, prepend_stmt, prepend_stmts, private_ident, quote_ident, undefined, ExprFactory,
member_expr, prepend_stmt, prepend_stmts, private_ident, quote_ident, ExprFactory,
};
use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith};
use swc_trace_macro::swc_trace;
Expand Down Expand Up @@ -148,7 +148,7 @@ impl Params {
right: Box::new(Expr::Bin(BinExpr {
left: make_arg_nth(i).into(),
op: op!("!=="),
right: undefined(DUMMY_SP),
right: Expr::undefined(DUMMY_SP),
span: DUMMY_SP,
})),
span,
Expand All @@ -170,7 +170,7 @@ impl Params {
span: DUMMY_SP,
left: Box::new(Expr::Ident(ident.id.clone())),
op: op!("==="),
right: undefined(DUMMY_SP),
right: Expr::undefined(DUMMY_SP),
})),
cons: Box::new(Stmt::Expr(ExprStmt {
span,
Expand Down Expand Up @@ -203,7 +203,7 @@ impl Params {
span: DUMMY_SP,
left: Box::new(Expr::Ident(binding.clone())),
op: op!("==="),
right: undefined(DUMMY_SP),
right: Expr::undefined(DUMMY_SP),
})),
cons: right,
alt: Box::new(Expr::Ident(binding)),
Expand Down Expand Up @@ -786,7 +786,7 @@ fn check_arg_len_or_undef(n: usize) -> Expr {
Expr::Cond(CondExpr {
test: Box::new(check_arg_len(n)),
cons: make_arg_nth(n).into(),
alt: undefined(DUMMY_SP),
alt: Expr::undefined(DUMMY_SP),
span: DUMMY_SP,
})
}
4 changes: 2 additions & 2 deletions crates/swc_ecma_compat_es2015/src/spread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use swc_ecma_ast::*;
use swc_ecma_transforms_base::{ext::ExprRefExt, helper, perf::Check};
use swc_ecma_transforms_macros::fast_path;
use swc_ecma_utils::{
alias_ident_for, member_expr, prepend_stmt, quote_ident, undefined, ExprFactory, StmtLike,
alias_ident_for, member_expr, prepend_stmt, quote_ident, ExprFactory, StmtLike,
};
use swc_ecma_visit::{
as_folder, noop_visit_mut_type, noop_visit_type, Fold, Visit, VisitMut, VisitMutWith, VisitWith,
Expand Down Expand Up @@ -95,7 +95,7 @@ impl VisitMut for Spread {
(Box::new(Expr::Ident(obj.as_ident().unwrap().clone())), None)
}

Expr::Ident(Ident { span, .. }) => (undefined(*span), None),
Expr::Ident(Ident { span, .. }) => (Expr::undefined(*span), None),

Expr::Member(MemberExpr { span, obj, prop }) => {
let ident = alias_ident_for(obj, "_instance");
Expand Down
Loading
Loading