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_macros/src/fast.rs
Rust
use proc_macro2::TokenStream; use quote::quote; use swc_macros_common::call_site; use syn::{parse_quote, FnArg, Ident, ImplItem, ImplItemFn, ItemImpl, Pat, Path}; use crate::common::Mode; pub fn expand(attr: TokenStream, item: ItemImpl) -> ItemImpl { let expander = Expander { handler: syn::parse2(attr).expect("Usage should be like #[fast_path(ArrowVisitor)]"), mode: detect_mode(&item), }; let items = expander.inject_default_methods(item.items); ItemImpl { items: items .into_iter() .map(|item| match item { ImplItem::Fn(m) => ImplItem::Fn(expander.patch_method(m)), _ => item, }) .collect(), ..item } } fn detect_mode(i: &ItemImpl) -> Mode { if i.items.iter().any(|item| match item { ImplItem::Fn(m) => m.sig.ident.to_string().starts_with("fold"), _ => false, }) { return Mode::Fold; } Mode::VisitMut } struct Expander { mode: Mode, handler: Path, } impl Expander { fn inject_default_methods(&self, mut items: Vec<ImplItem>) -> Vec<ImplItem> { let list = &[ ("stmt", quote!(swc_ecma_ast::Stmt)), ("stmts", quote!(Vec<swc_ecma_ast::Stmt>)), ("module_decl", quote!(swc_ecma_ast::ModuleDecl)), ("module_item", quote!(swc_ecma_ast::ModuleItem)), ("module_items", quote!(Vec<swc_ecma_ast::ModuleItem>)), ("expr", quote!(swc_ecma_ast::Expr)), ("exprs", quote!(Vec<Box<swc_ecma_ast::Expr>>)), ("decl", quote!(swc_ecma_ast::Decl)), ("pat", quote!(swc_ecma_ast::Pat)), ]; for (name, ty) in list { let has = items.iter().any(|item| match item { ImplItem::Fn(i) => i.sig.ident.to_string().ends_with(name), _ => false, }); if has { continue; } let name = Ident::new(&format!("{}_{}", self.mode.prefix(), name), call_site()); let method = match self.mode { Mode::Fold => parse_quote!( fn #name(&mut self, node: #ty) -> #ty { node.fold_children_with(self) } ), Mode::VisitMut => parse_quote!( fn #name(&mut self, node: &mut #ty) { node.visit_mut_children_with(self) } ), }; items.push(method); } items } /// Add fast path to a method fn patch_method(&self, mut m: ImplItemFn) -> ImplItemFn { let ty_arg = m .sig .inputs .last() .expect("method of Fold / VisitMut must accept two parameters"); let ty_arg = match ty_arg { FnArg::Receiver(_) => unreachable!(), FnArg::Typed(ty) => ty, }; if m.sig.ident == "visit_mut_ident" || m.sig.ident == "fold_ident" { return m; } if m.block.stmts.is_empty() { return m; } let arg = match &*ty_arg.pat { Pat::Ident(i) => &i.ident, _ => unimplemented!( "Fast-path injection for Fold / VisitMut where pattern is not an ident" ), }; let checker = &self.handler; let fast_path = match self.mode { Mode::Fold => parse_quote!( if !swc_ecma_transforms_base::perf::should_work::<#checker, _>(&#arg) { return #arg; } ), Mode::VisitMut => parse_quote!( if !swc_ecma_transforms_base::perf::should_work::<#checker, _>(&*#arg) { return; } ), }; let mut stmts = vec![fast_path]; stmts.extend(m.block.stmts); m.block.stmts = stmts; m } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_macros/src/lib.rs
Rust
#![deny(clippy::all)] #![recursion_limit = "2048"] use proc_macro::TokenStream; use quote::ToTokens; use swc_macros_common::print; mod common; mod fast; mod parallel; /// This macro adds fast-path to the `swc_ecma_visit::Fold` and /// `swc_ecma_visit::Visit`. /// /// Currently this macro modifies handler of `Expr`, `Stmt`, `ModuleItem`, /// `Decl`, `Pat` and some vector types. /// /// /// /// /// # Usage /// /// `#[fast_path(ArrowVisitor)]` /// /// where `ShouldWork` implements `swc_ecma_transforms::perf::Check` #[proc_macro_attribute] pub fn fast_path(attr: TokenStream, item: TokenStream) -> TokenStream { let item = syn::parse(item).expect("failed to parse input as an item"); let expanded = fast::expand(attr.into(), item); print("fast_path", expanded.into_token_stream()) } /// /// # Input /// /// Basically, input for each types are wrapped in the suffix of the visitor /// method for the type. /// /// ## `#[threashold]` /// /// ```ignore, /// #[parallel(module_items(threshold = "4"))] /// impl VisitMut for Pass {} /// ``` #[proc_macro_attribute] pub fn parallel(attr: TokenStream, item: TokenStream) -> TokenStream { let item = syn::parse(item).expect("failed to parse input as an item"); let expanded = parallel::expand(attr.into(), item); print("parallel", expanded.into_token_stream()) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_macros/src/parallel.rs
Rust
#![allow(non_snake_case)] use proc_macro2::{Span, TokenStream}; use syn::{parse_quote, Expr, Ident, ImplItem, ImplItemFn, ItemImpl, Meta, Type}; use crate::common::Mode; pub fn expand(attr: TokenStream, mut item: ItemImpl) -> ItemImpl { let mode = { let p = &item.trait_.as_ref().unwrap().1; if p.is_ident("Fold") { Mode::Fold } else if p.is_ident("VisitMut") { Mode::VisitMut } else { unimplemented!("Unknown visitor type: {:?}", p) } }; let meta = if attr.is_empty() { None } else { Some(syn::parse2::<Meta>(attr).expect("failed to parse meta")) }; let explode = meta .as_ref() .map(|v| v.path().is_ident("explode")) .unwrap_or(false); item.items.push(ImplItem::Fn(make_par_visit_method( mode, "module_items", explode, ))); item.items .push(ImplItem::Fn(make_par_visit_method(mode, "stmts", explode))); item } fn node_type(suffix: &str) -> Type { match suffix { "module_items" => parse_quote!(ModuleItem), "stmts" => parse_quote!(Stmt), _ => { unimplemented!("Unknown suffix `{}`", suffix) } } } fn post_visit_hook(mode: Mode, suffix: &str) -> Option<Expr> { match suffix { "module_items" => Some(match mode { Mode::Fold => parse_quote!( swc_ecma_transforms_base::perf::Parallel::after_module_items(self, &mut nodes) ), Mode::VisitMut => parse_quote!( swc_ecma_transforms_base::perf::Parallel::after_module_items(self, nodes) ), }), "stmts" => Some(match mode { Mode::Fold => parse_quote!(swc_ecma_transforms_base::perf::Parallel::after_stmts( self, &mut nodes )), Mode::VisitMut => parse_quote!(swc_ecma_transforms_base::perf::Parallel::after_stmts( self, nodes )), }), _ => None, } } fn explode_hook_method_name(explode: bool, suffix: &str) -> Option<Ident> { if !explode { return None; } match suffix { "module_items" => Some(Ident::new("after_one_module_item", Span::call_site())), "stmts" => Some(Ident::new("after_one_stmt", Span::call_site())), _ => None, } } fn make_par_visit_method(mode: Mode, suffix: &str, explode: bool) -> ImplItemFn { let method_name = Ident::new(&format!("{}_{}", mode.prefix(), suffix), Span::call_site()); let hook = post_visit_hook(mode, suffix); let explode_method_name = explode_hook_method_name(explode, suffix); let node_type = node_type(suffix); match (mode, explode_method_name) { (Mode::Fold, Some(explode_method_name)) => parse_quote!( fn #method_name(&mut self, mut nodes: Vec<#node_type>) -> Vec<#node_type> { use swc_common::errors::HANDLER; use swc_ecma_transforms_base::perf::{ParExplode, Parallel}; use swc_ecma_visit::FoldWith; let mut buf = Vec::with_capacity(nodes.len()); for node in nodes { let mut visitor = Parallel::create(&*self); let node = node.fold_with(&mut visitor); ParExplode::#explode_method_name(&mut visitor, &mut buf); buf.push(node); } let mut nodes = buf; { #hook; } nodes } ), (Mode::Fold, None) => parse_quote!( fn #method_name(&mut self, nodes: Vec<#node_type>) -> Vec<#node_type> { use swc_common::errors::HANDLER; use swc_ecma_transforms_base::perf::Parallel; use swc_ecma_visit::FoldWith; let mut nodes = nodes.fold_children_with(self); { #hook; } nodes } ), (Mode::VisitMut, Some(explode_method_name)) => parse_quote!( fn #method_name(&mut self, nodes: &mut Vec<#node_type>) { use std::mem::take; use swc_common::errors::HANDLER; use swc_ecma_transforms_base::perf::{ParExplode, Parallel}; use swc_ecma_visit::VisitMutWith; 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); ParExplode::#explode_method_name(&mut visitor, &mut buf); buf.push(node); } *nodes = buf; { #hook; } } ), (Mode::VisitMut, None) => parse_quote!( fn #method_name(&mut self, nodes: &mut Vec<#node_type>) { use swc_common::errors::HANDLER; use swc_ecma_transforms_base::perf::Parallel; use swc_ecma_visit::VisitMutWith; nodes.visit_mut_children_with(self); { #hook; } } ), } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/src/amd.rs
Rust
use anyhow::Context; use regex::Regex; use serde::{Deserialize, Serialize}; use swc_atoms::Atom; use swc_common::{ comments::{CommentKind, Comments}, source_map::PURE_SP, util::take::Take, Mark, Span, SyntaxContext, DUMMY_SP, }; use swc_ecma_ast::*; use swc_ecma_transforms_base::{feature::FeatureFlag, helper_expr}; use swc_ecma_utils::{ member_expr, private_ident, quote_ident, quote_str, ExprFactory, FunctionFactory, IsDirective, }; use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith}; pub use super::util::Config as InnerConfig; use crate::{ module_decl_strip::{Export, Link, LinkFlag, LinkItem, LinkSpecifierReducer, ModuleDeclStrip}, module_ref_rewriter::{rewrite_import_bindings, ImportMap}, path::Resolver, top_level_this::top_level_this, util::{ define_es_module, emit_export_stmts, local_name_for_src, use_strict, ImportInterop, VecStmtLike, }, SpanCtx, }; #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct Config { #[serde(default)] pub module_id: Option<String>, #[serde(flatten, default)] pub config: InnerConfig, } pub fn amd<C>( resolver: Resolver, unresolved_mark: Mark, config: Config, available_features: FeatureFlag, comments: Option<C>, ) -> impl Pass where C: Comments, { let Config { module_id, config } = config; visit_mut_pass(Amd { module_id, config, unresolved_mark, resolver, comments, support_arrow: caniuse!(available_features.ArrowFunctions), const_var_kind: if caniuse!(available_features.BlockScoping) { VarDeclKind::Const } else { VarDeclKind::Var }, dep_list: Default::default(), require: quote_ident!( SyntaxContext::empty().apply_mark(unresolved_mark), "require" ), exports: None, module: None, found_import_meta: false, }) } pub struct Amd<C> where C: Comments, { module_id: Option<String>, config: InnerConfig, unresolved_mark: Mark, resolver: Resolver, comments: Option<C>, support_arrow: bool, const_var_kind: VarDeclKind, dep_list: Vec<(Ident, Atom, SpanCtx)>, require: Ident, exports: Option<Ident>, module: Option<Ident>, found_import_meta: bool, } impl<C> VisitMut for Amd<C> where C: Comments, { noop_visit_mut_type!(fail); fn visit_mut_module(&mut self, n: &mut Module) { if self.module_id.is_none() { self.module_id = self.get_amd_module_id_from_comments(n.span); } let mut stmts: Vec<Stmt> = Vec::with_capacity(n.body.len() + 4); // Collect directives stmts.extend( &mut n .body .iter_mut() .take_while(|i| i.directive_continue()) .map(|i| i.take()) .map(ModuleItem::expect_stmt), ); // "use strict"; if self.config.strict_mode && !stmts.has_use_strict() { stmts.push(use_strict()); } if !self.config.allow_top_level_this { top_level_this(&mut n.body, *Expr::undefined(DUMMY_SP)); } let import_interop = self.config.import_interop(); let mut strip = ModuleDeclStrip::new(self.const_var_kind); n.body.visit_mut_with(&mut strip); let ModuleDeclStrip { link, export, export_assign, has_module_decl, .. } = strip; let is_export_assign = export_assign.is_some(); if has_module_decl && !import_interop.is_none() && !is_export_assign { stmts.push(define_es_module(self.exports())) } let mut import_map = Default::default(); stmts.extend( self.handle_import_export(&mut import_map, link, export, is_export_assign) .map(From::from), ); stmts.extend(n.body.take().into_iter().filter_map(|item| match item { ModuleItem::Stmt(stmt) if !stmt.is_empty() => Some(stmt), _ => None, })); if let Some(export_assign) = export_assign { let return_stmt = ReturnStmt { span: DUMMY_SP, arg: Some(export_assign), }; stmts.push(return_stmt.into()) } if !self.config.ignore_dynamic || !self.config.preserve_import_meta { stmts.visit_mut_children_with(self); } rewrite_import_bindings(&mut stmts, import_map, Default::default()); // ==================== // Emit // ==================== let mut elems = vec![Some(quote_str!("require").as_arg())]; let mut params = vec![self.require.clone().into()]; if let Some(exports) = self.exports.take() { elems.push(Some(quote_str!("exports").as_arg())); params.push(exports.into()) } if let Some(module) = self.module.clone() { elems.push(Some(quote_str!("module").as_arg())); params.push(module.into()) } self.dep_list .take() .into_iter() .for_each(|(ident, src_path, src_span)| { let src_path = match &self.resolver { Resolver::Real { resolver, base } => resolver .resolve_import(base, &src_path) .with_context(|| format!("failed to resolve `{}`", src_path)) .unwrap(), Resolver::Default => src_path, }; elems.push(Some(quote_str!(src_span.0, src_path).as_arg())); params.push(ident.into()); }); let mut amd_call_args = Vec::with_capacity(3); if let Some(module_id) = self.module_id.clone() { amd_call_args.push(quote_str!(module_id).as_arg()); } amd_call_args.push( ArrayLit { span: DUMMY_SP, elems, } .as_arg(), ); amd_call_args.push( Function { params, decorators: Default::default(), span: DUMMY_SP, body: Some(BlockStmt { stmts, ..Default::default() }), is_generator: false, is_async: false, ..Default::default() } .into_fn_expr(None) .as_arg(), ); n.body = vec![quote_ident!( SyntaxContext::empty().apply_mark(self.unresolved_mark), "define" ) .as_call(DUMMY_SP, amd_call_args) .into_stmt() .into()]; } fn visit_mut_script(&mut self, _: &mut Script) { // skip script } fn visit_mut_expr(&mut self, n: &mut Expr) { match n { Expr::Call(CallExpr { span, callee: Callee::Import(Import { span: import_span, phase: ImportPhase::Evaluation, }), args, .. }) if !self.config.ignore_dynamic => { args.visit_mut_with(self); args.get_mut(0).into_iter().for_each(|x| { if let ExprOrSpread { spread: None, expr } = x { if let Expr::Lit(Lit::Str(Str { value, raw, .. })) = &mut **expr { *value = self.resolver.resolve(value.clone()); *raw = None; } } }); let mut require = self.require.clone(); require.span = *import_span; *n = amd_dynamic_import( *span, args.take(), require, self.config.import_interop(), self.support_arrow, ); } Expr::Member(MemberExpr { span, obj, prop }) if prop.is_ident_with("url") && !self.config.preserve_import_meta && obj .as_meta_prop() .map(|p| p.kind == MetaPropKind::ImportMeta) .unwrap_or_default() => { obj.visit_mut_with(self); *n = amd_import_meta_url(*span, self.module()); self.found_import_meta = true; } _ => n.visit_mut_children_with(self), } } } impl<C> Amd<C> where C: Comments, { fn handle_import_export( &mut self, import_map: &mut ImportMap, link: Link, export: Export, is_export_assign: bool, ) -> impl Iterator<Item = Stmt> { let import_interop = self.config.import_interop(); let mut stmts = Vec::with_capacity(link.len()); let mut export_obj_prop_list = export.into_iter().collect(); link.into_iter().for_each( |(src, LinkItem(src_span, link_specifier_set, mut link_flag))| { let is_node_default = !link_flag.has_named() && import_interop.is_node(); if import_interop.is_none() { link_flag -= LinkFlag::NAMESPACE; } let need_re_export = link_flag.export_star(); let need_interop = link_flag.interop(); let need_new_var = link_flag.need_raw_import(); let mod_ident = private_ident!(local_name_for_src(&src)); let new_var_ident = if need_new_var { private_ident!(local_name_for_src(&src)) } else { mod_ident.clone() }; self.dep_list.push((mod_ident.clone(), src, src_span)); link_specifier_set.reduce( import_map, &mut export_obj_prop_list, &new_var_ident, &Some(mod_ident.clone()), &mut false, is_node_default, ); // _export_star(mod, exports); let mut import_expr: Expr = if need_re_export { helper_expr!(export_star).as_call( DUMMY_SP, vec![mod_ident.clone().as_arg(), self.exports().as_arg()], ) } else { mod_ident.clone().into() }; // _introp(mod); if need_interop { import_expr = match import_interop { ImportInterop::Swc if link_flag.interop() => if link_flag.namespace() { helper_expr!(interop_require_wildcard) } else { helper_expr!(interop_require_default) } .as_call(PURE_SP, vec![import_expr.as_arg()]), ImportInterop::Node if link_flag.namespace() => { helper_expr!(interop_require_wildcard) .as_call(PURE_SP, vec![import_expr.as_arg(), true.as_arg()]) } _ => import_expr, } }; // mod = _introp(mod); // var mod1 = _introp(mod); if need_new_var { let stmt: Stmt = import_expr .into_var_decl(self.const_var_kind, new_var_ident.into()) .into(); stmts.push(stmt) } else if need_interop { let stmt = import_expr .make_assign_to(op!("="), mod_ident.into()) .into_stmt(); stmts.push(stmt); } else if need_re_export { stmts.push(import_expr.into_stmt()); }; }, ); let mut export_stmts = Default::default(); if !export_obj_prop_list.is_empty() && !is_export_assign { export_obj_prop_list.sort_by_cached_key(|(key, ..)| key.clone()); let exports = self.exports(); export_stmts = emit_export_stmts(exports, export_obj_prop_list); } export_stmts.into_iter().chain(stmts) } fn module(&mut self) -> Ident { self.module .get_or_insert_with(|| private_ident!("module")) .clone() } fn exports(&mut self) -> Ident { self.exports .get_or_insert_with(|| private_ident!("exports")) .clone() } fn get_amd_module_id_from_comments(&self, span: Span) -> Option<String> { // https://github.com/microsoft/TypeScript/blob/1b9c8a15adc3c9a30e017a7048f98ef5acc0cada/src/compiler/parser.ts#L9648-L9658 let amd_module_re = Regex::new(r#"(?i)^/\s*<amd-module.*?name\s*=\s*(?:(?:'([^']*)')|(?:"([^"]*)")).*?/>"#) .unwrap(); self.comments.as_ref().and_then(|comments| { comments .get_leading(span.lo) .iter() .flatten() .rev() .find_map(|cmt| { if cmt.kind != CommentKind::Line { return None; } amd_module_re .captures(&cmt.text) .and_then(|cap| cap.get(1).or_else(|| cap.get(2))) }) .map(|m| m.as_str().to_string()) }) } } /// new Promise((resolve, reject) => require([arg], m => resolve(m), reject)) pub(crate) fn amd_dynamic_import( span: Span, args: Vec<ExprOrSpread>, require: Ident, import_interop: ImportInterop, support_arrow: bool, ) -> Expr { let resolve = private_ident!("resolve"); let reject = private_ident!("reject"); let arg = args[..1].iter().cloned().map(Option::Some).collect(); let module = private_ident!("m"); let resolved_module: Expr = match import_interop { ImportInterop::None => module.clone().into(), ImportInterop::Swc => { helper_expr!(interop_require_wildcard).as_call(PURE_SP, vec![module.clone().as_arg()]) } ImportInterop::Node => helper_expr!(interop_require_wildcard) .as_call(PURE_SP, vec![module.clone().as_arg(), true.as_arg()]), }; let resolve_callback = resolve .clone() .as_call(DUMMY_SP, vec![resolved_module.as_arg()]) .into_lazy_auto(vec![module.into()], support_arrow); let require_call = require.as_call( DUMMY_SP, vec![ ArrayLit { span: DUMMY_SP, elems: arg, } .as_arg(), resolve_callback.as_arg(), reject.clone().as_arg(), ], ); let promise_executer = require_call.into_lazy_auto(vec![resolve.into(), reject.into()], support_arrow); NewExpr { span, callee: Box::new(quote_ident!("Promise").into()), args: Some(vec![promise_executer.as_arg()]), ..Default::default() } .into() } /// new URL(module.uri, document.baseURI).href fn amd_import_meta_url(span: Span, module: Ident) -> Expr { MemberExpr { span, obj: quote_ident!("URL") .into_new_expr( DUMMY_SP, Some(vec![ module.make_member(quote_ident!("uri")).as_arg(), member_expr!(Default::default(), DUMMY_SP, document.baseURI).as_arg(), ]), ) .into(), prop: MemberProp::Ident("href".into()), } .into() }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/src/common_js.rs
Rust
use rustc_hash::FxHashSet; use swc_common::{source_map::PURE_SP, util::take::Take, Mark, Span, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_transforms_base::{feature::FeatureFlag, helper_expr}; use swc_ecma_utils::{ member_expr, private_ident, quote_expr, quote_ident, ExprFactory, FunctionFactory, IsDirective, }; use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith}; pub use super::util::Config; use crate::{ module_decl_strip::{ Export, ExportKV, Link, LinkFlag, LinkItem, LinkSpecifierReducer, ModuleDeclStrip, }, module_ref_rewriter::{rewrite_import_bindings, ImportMap}, path::Resolver, top_level_this::top_level_this, util::{ define_es_module, emit_export_stmts, local_name_for_src, prop_name, use_strict, ImportInterop, VecStmtLike, }, }; pub fn common_js( resolver: Resolver, unresolved_mark: Mark, config: Config, available_features: FeatureFlag, ) -> impl Pass { visit_mut_pass(Cjs { config, resolver, unresolved_mark, available_features, support_arrow: caniuse!(available_features.ArrowFunctions), const_var_kind: if caniuse!(available_features.BlockScoping) { VarDeclKind::Const } else { VarDeclKind::Var }, }) } pub struct Cjs { config: Config, resolver: Resolver, unresolved_mark: Mark, available_features: FeatureFlag, support_arrow: bool, const_var_kind: VarDeclKind, } impl VisitMut for Cjs { noop_visit_mut_type!(fail); fn visit_mut_module(&mut self, n: &mut Module) { let mut stmts: Vec<ModuleItem> = Vec::with_capacity(n.body.len() + 6); // Collect directives stmts.extend( &mut n .body .iter_mut() .take_while(|i| i.directive_continue()) .map(|i| i.take()), ); // "use strict"; if self.config.strict_mode && !stmts.has_use_strict() { stmts.push(use_strict().into()); } if !self.config.allow_top_level_this { top_level_this(&mut n.body, *Expr::undefined(DUMMY_SP)); } let import_interop = self.config.import_interop(); let mut module_map = Default::default(); let mut has_ts_import_equals = false; // handle `import foo = require("mod")` n.body.iter_mut().for_each(|item| { if let ModuleItem::ModuleDecl(module_decl) = item { *item = self.handle_ts_import_equals( module_decl.take(), &mut module_map, &mut has_ts_import_equals, ); } }); let mut strip = ModuleDeclStrip::new(self.const_var_kind); n.body.visit_mut_with(&mut strip); let ModuleDeclStrip { link, export, export_assign, has_module_decl, .. } = strip; let has_module_decl = has_module_decl || has_ts_import_equals; let is_export_assign = export_assign.is_some(); if has_module_decl && !import_interop.is_none() && !is_export_assign { stmts.push(define_es_module(self.exports()).into()) } let mut lazy_record = Default::default(); // `import` -> `require` // `export` -> `_export(exports, {});` stmts.extend( self.handle_import_export( &mut module_map, &mut lazy_record, link, export, is_export_assign, ) .map(From::from), ); stmts.extend(n.body.take().into_iter().filter(|item| match item { ModuleItem::Stmt(stmt) => !stmt.is_empty(), _ => false, })); // `export = expr;` -> `module.exports = expr;` if let Some(export_assign) = export_assign { stmts.push( export_assign .make_assign_to( op!("="), member_expr!( SyntaxContext::empty().apply_mark(self.unresolved_mark), Default::default(), module.exports ) .into(), ) .into_stmt() .into(), ) } if !self.config.ignore_dynamic || !self.config.preserve_import_meta { stmts.visit_mut_children_with(self); } rewrite_import_bindings(&mut stmts, module_map, lazy_record); n.body = stmts; } fn visit_mut_script(&mut self, _: &mut Script) { // skip script } fn visit_mut_expr(&mut self, n: &mut Expr) { match n { Expr::Call(CallExpr { span, callee: Callee::Import(Import { span: import_span, phase: ImportPhase::Evaluation, }), args, .. }) if !self.config.ignore_dynamic => { args.visit_mut_with(self); let mut is_lit_path = false; args.get_mut(0).into_iter().for_each(|x| { if let ExprOrSpread { spread: None, expr } = x { if let Expr::Lit(Lit::Str(Str { value, raw, .. })) = &mut **expr { is_lit_path = true; *value = self.resolver.resolve(value.clone()); *raw = None; } } }); let unresolved_ctxt = SyntaxContext::empty().apply_mark(self.unresolved_mark); *n = cjs_dynamic_import( *span, args.take(), quote_ident!(unresolved_ctxt, *import_span, "require"), self.config.import_interop(), self.support_arrow, is_lit_path, ); } Expr::Member(MemberExpr { span, obj, prop }) if prop.is_ident_with("url") && !self.config.preserve_import_meta && obj .as_meta_prop() .map(|p| p.kind == MetaPropKind::ImportMeta) .unwrap_or_default() => { obj.visit_mut_with(self); let require = quote_ident!( SyntaxContext::empty().apply_mark(self.unresolved_mark), "require" ); *n = cjs_import_meta_url(*span, require, self.unresolved_mark); } _ => n.visit_mut_children_with(self), } } } impl Cjs { fn handle_import_export( &mut self, import_map: &mut ImportMap, lazy_record: &mut FxHashSet<Id>, link: Link, export: Export, is_export_assign: bool, ) -> impl Iterator<Item = Stmt> { let import_interop = self.config.import_interop(); let export_interop_annotation = self.config.export_interop_annotation(); let is_node = import_interop.is_node(); let mut stmts = Vec::with_capacity(link.len()); let mut export_obj_prop_list = export.into_iter().collect(); let lexer_reexport = if export_interop_annotation { self.emit_lexer_reexport(&link) } else { None }; link.into_iter().for_each( |(src, LinkItem(src_span, link_specifier_set, mut link_flag))| { let is_node_default = !link_flag.has_named() && is_node; if import_interop.is_none() { link_flag -= LinkFlag::NAMESPACE; } let mod_ident = private_ident!(local_name_for_src(&src)); let mut decl_mod_ident = false; link_specifier_set.reduce( import_map, &mut export_obj_prop_list, &mod_ident, &None, &mut decl_mod_ident, is_node_default, ); let is_lazy = decl_mod_ident && !link_flag.export_star() && self.config.lazy.is_lazy(&src); if is_lazy { lazy_record.insert(mod_ident.to_id()); } // require("mod"); let import_expr = self.resolver .make_require_call(self.unresolved_mark, src, src_span.0); // _export_star(require("mod"), exports); let import_expr = if link_flag.export_star() { helper_expr!(export_star).as_call( DUMMY_SP, vec![import_expr.as_arg(), self.exports().as_arg()], ) } else { import_expr }; // _introp(require("mod")); let import_expr = { match import_interop { ImportInterop::Swc if link_flag.interop() => if link_flag.namespace() { helper_expr!(interop_require_wildcard) } else { helper_expr!(interop_require_default) } .as_call(PURE_SP, vec![import_expr.as_arg()]), ImportInterop::Node if link_flag.namespace() => { helper_expr!(interop_require_wildcard) .as_call(PURE_SP, vec![import_expr.as_arg(), true.as_arg()]) } _ => import_expr, } }; if decl_mod_ident { let stmt = if is_lazy { lazy_require(import_expr, mod_ident, self.const_var_kind).into() } else { import_expr .into_var_decl(self.const_var_kind, mod_ident.into()) .into() }; stmts.push(stmt); } else { stmts.push(import_expr.into_stmt()); } }, ); let mut export_stmts: Vec<Stmt> = Default::default(); if !export_obj_prop_list.is_empty() && !is_export_assign { export_obj_prop_list.sort_by_cached_key(|(key, ..)| key.clone()); let mut features = self.available_features; let exports = self.exports(); if export_interop_annotation { if export_obj_prop_list.len() > 1 { export_stmts.extend(self.emit_lexer_exports_init(&export_obj_prop_list)); } else { // `cjs-module-lexer` does not support `get: ()=> foo` // see https://github.com/nodejs/cjs-module-lexer/pull/74 features -= FeatureFlag::ArrowFunctions; } } export_stmts.extend(emit_export_stmts(exports, export_obj_prop_list)); } export_stmts.extend(lexer_reexport); export_stmts.into_iter().chain(stmts) } fn handle_ts_import_equals( &self, module_decl: ModuleDecl, module_map: &mut ImportMap, has_ts_import_equals: &mut bool, ) -> ModuleItem { match module_decl { ModuleDecl::TsImportEquals(v) if matches!( &*v, TsImportEqualsDecl { is_type_only: false, module_ref: TsModuleRef::TsExternalModuleRef(TsExternalModuleRef { .. }), .. } ) => { let TsImportEqualsDecl { span, is_export, id, module_ref, .. } = *v; let Str { span: src_span, value: src, .. } = module_ref.expect_ts_external_module_ref().expr; *has_ts_import_equals = true; let require = self .resolver .make_require_call(self.unresolved_mark, src, src_span); if is_export { // exports.foo = require("mod") module_map.insert(id.to_id(), (self.exports(), Some(id.sym.clone()))); let assign_expr = AssignExpr { span, op: op!("="), left: self.exports().make_member(id.into()).into(), right: Box::new(require), }; assign_expr.into_stmt() } else { // const foo = require("mod") let mut var_decl = require.into_var_decl(self.const_var_kind, id.into()); var_decl.span = span; var_decl.into() } .into() } _ => module_decl.into(), } } fn exports(&self) -> Ident { quote_ident!( SyntaxContext::empty().apply_mark(self.unresolved_mark), "exports" ) } /// emit [cjs-module-lexer](https://github.com/nodejs/cjs-module-lexer) friendly exports list /// ```javascript /// 0 && (exports.foo = 0); /// 0 && (module.exports = { foo: _, bar: _ }); /// ``` fn emit_lexer_exports_init(&mut self, export_id_list: &[ExportKV]) -> Option<Stmt> { match export_id_list.len() { 0 => None, 1 => { let expr: Expr = 0.into(); let (key, export_item) = &export_id_list[0]; let prop = prop_name(key, Default::default()).into(); let export_binding = MemberExpr { obj: Box::new(self.exports().into()), span: export_item.export_name_span().0, prop, }; let expr = expr.make_assign_to(op!("="), export_binding.into()); let expr = BinExpr { span: DUMMY_SP, op: op!("&&"), left: 0.into(), right: Box::new(expr), }; Some(expr.into_stmt()) } _ => { let props = export_id_list .iter() .map(|(key, ..)| prop_name(key, Default::default())) .map(|key| KeyValueProp { key: key.into(), // `cjs-module-lexer` only support identifier as value // `null` is treated as identifier in `cjs-module-lexer` value: quote_expr!(DUMMY_SP, null).into(), }) .map(Prop::KeyValue) .map(Box::new) .map(PropOrSpread::Prop) .collect(); let module_exports_assign = ObjectLit { span: DUMMY_SP, props, } .make_assign_to( op!("="), member_expr!( SyntaxContext::empty().apply_mark(self.unresolved_mark), Default::default(), module.exports ) .into(), ); let expr = BinExpr { span: DUMMY_SP, op: op!("&&"), left: 0.into(), right: Box::new(module_exports_assign), }; Some(expr.into_stmt()) } } } /// emit [cjs-module-lexer](https://github.com/nodejs/cjs-module-lexer) friendly exports list /// ```javascript /// 0 && __export(require("foo")) && __export(require("bar")); /// ``` fn emit_lexer_reexport(&self, link: &Link) -> Option<Stmt> { link.iter() .filter(|(.., LinkItem(.., link_flag))| link_flag.export_star()) .map(|(src, ..)| { let import_expr = self.resolver .make_require_call(self.unresolved_mark, src.clone(), DUMMY_SP); quote_ident!("__export").as_call(DUMMY_SP, vec![import_expr.as_arg()]) }) .reduce(|left, right| { BinExpr { span: DUMMY_SP, op: op!("&&"), left: left.into(), right: right.into(), } .into() }) .map(|expr| { BinExpr { span: DUMMY_SP, op: op!("&&"), left: 0.into(), right: expr.into(), } .into_stmt() }) } } /// ```javascript /// Promise.resolve(args).then(p => require(p)) /// // for literial dynamic import: /// Promise.resolve().then(() => require(args)) /// ``` pub(crate) fn cjs_dynamic_import( span: Span, args: Vec<ExprOrSpread>, require: Ident, import_interop: ImportInterop, support_arrow: bool, is_lit_path: bool, ) -> Expr { let p = private_ident!("p"); let (resolve_args, callback_params, require_args) = if is_lit_path { (Vec::new(), Vec::new(), args) } else { (args, vec![p.clone().into()], vec![p.as_arg()]) }; let then = member_expr!(Default::default(), Default::default(), Promise.resolve) // TODO: handle import assert .as_call(DUMMY_SP, resolve_args) .make_member(quote_ident!("then")); let import_expr = { let require = require.as_call(DUMMY_SP, require_args); match import_interop { ImportInterop::None => require, ImportInterop::Swc => { helper_expr!(interop_require_wildcard).as_call(PURE_SP, vec![require.as_arg()]) } ImportInterop::Node => helper_expr!(interop_require_wildcard) .as_call(PURE_SP, vec![require.as_arg(), true.as_arg()]), } }; then.as_call( span, vec![import_expr .into_lazy_auto(callback_params, support_arrow) .as_arg()], ) } /// require('url').pathToFileURL(__filename).toString() fn cjs_import_meta_url(span: Span, require: Ident, unresolved_mark: Mark) -> Expr { require .as_call(DUMMY_SP, vec!["url".as_arg()]) .make_member(quote_ident!("pathToFileURL")) .as_call( DUMMY_SP, vec![quote_ident!( SyntaxContext::empty().apply_mark(unresolved_mark), "__filename" ) .as_arg()], ) .make_member(quote_ident!("toString")) .as_call(span, Default::default()) } /// ```javascript /// function foo() { /// const data = expr; /// /// foo = () => data; /// /// return data; /// } /// ``` pub fn lazy_require(expr: Expr, mod_ident: Ident, var_kind: VarDeclKind) -> FnDecl { let data = private_ident!("data"); let data_decl = expr.into_var_decl(var_kind, data.clone().into()); let data_stmt = data_decl.into(); let overwrite_stmt = data .clone() .into_lazy_fn(Default::default()) .into_fn_expr(None) .make_assign_to(op!("="), mod_ident.clone().into()) .into_stmt(); let return_stmt = data.into_return_stmt().into(); FnDecl { ident: mod_ident, declare: false, function: Function { params: Default::default(), decorators: Default::default(), span: DUMMY_SP, body: Some(BlockStmt { span: DUMMY_SP, stmts: vec![data_stmt, overwrite_stmt, return_stmt], ..Default::default() }), is_generator: false, is_async: false, ..Default::default() } .into(), } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/src/import_analysis.rs
Rust
use rustc_hash::FxHashMap; use swc_atoms::Atom; use swc_ecma_ast::*; use swc_ecma_transforms_base::enable_helper; use swc_ecma_visit::{ noop_visit_mut_type, noop_visit_type, visit_mut_pass, Visit, VisitMut, VisitWith, }; use crate::{module_decl_strip::LinkFlag, util::ImportInterop}; pub fn import_analyzer(import_interop: ImportInterop, ignore_dynamic: bool) -> impl Pass { visit_mut_pass(ImportAnalyzer { import_interop, ignore_dynamic, flag_record: Default::default(), dynamic_import_found: false, }) } pub struct ImportAnalyzer { import_interop: ImportInterop, ignore_dynamic: bool, flag_record: FxHashMap<Atom, LinkFlag>, dynamic_import_found: bool, } /// Inject required helpers methods **for** module transform passes. impl VisitMut for ImportAnalyzer { noop_visit_mut_type!(fail); fn visit_mut_module(&mut self, module: &mut Module) { self.visit_module(&*module); } } impl Visit for ImportAnalyzer { noop_visit_type!(fail); fn visit_module_items(&mut self, n: &[ModuleItem]) { for item in n.iter() { if item.is_module_decl() { item.visit_with(self); } } let flag_record = &self.flag_record; if flag_record.values().any(|flag| flag.export_star()) { enable_helper!(export_star); } if self.import_interop.is_none() { return; } if self.import_interop.is_swc() && flag_record .values() .any(|flag| flag.interop() && !flag.has_named()) { enable_helper!(interop_require_default); } if flag_record.values().any(|flag| flag.namespace()) { enable_helper!(interop_require_wildcard); } else if !self.ignore_dynamic { // `import/export * as foo from "foo"` not found // but it may be used with dynamic import for item in n.iter() { if item.is_stmt() { item.visit_with(self); } if self.dynamic_import_found { enable_helper!(interop_require_wildcard); break; } } } } fn visit_import_decl(&mut self, n: &ImportDecl) { let flag = self.flag_record.entry(n.src.value.clone()).or_default(); for s in &n.specifiers { *flag |= s.into(); } } fn visit_named_export(&mut self, n: &NamedExport) { if let Some(src) = n.src.clone() { let flag = self.flag_record.entry(src.value).or_default(); for s in &n.specifiers { *flag |= s.into(); } } } fn visit_export_all(&mut self, n: &ExportAll) { *self.flag_record.entry(n.src.value.clone()).or_default() |= LinkFlag::EXPORT_STAR; } fn visit_import(&mut self, _: &Import) { self.dynamic_import_found = true; } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/src/lib.rs
Rust
#![deny(clippy::all)] #![allow(clippy::needless_lifetimes)] #![allow(clippy::vec_box)] #![allow(clippy::mutable_key_type)] use serde::{Deserialize, Serialize}; use swc_common::{Span, SyntaxContext}; use util::Config; pub use self::{amd::amd, common_js::common_js, system_js::system_js, umd::umd}; #[macro_use] pub mod util; pub mod amd; pub mod common_js; pub mod import_analysis; pub(crate) mod module_decl_strip; pub(crate) mod module_ref_rewriter; pub mod path; pub mod rewriter; pub mod system_js; mod top_level_this; pub mod umd; #[derive(Debug, Default, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct EsModuleConfig { #[serde(flatten, default)] pub config: Config, } type SpanCtx = (Span, SyntaxContext);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/src/module_decl_strip.rs
Rust
use indexmap::IndexMap; use rustc_hash::{FxHashMap, FxHashSet}; use swc_atoms::Atom; use swc_common::{util::take::Take, Mark, Span, SyntaxContext}; use swc_ecma_ast::*; use swc_ecma_utils::{find_pat_ids, private_ident, quote_ident, ExprFactory}; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; use crate::{module_ref_rewriter::ImportMap, SpanCtx}; /// key: module path pub type Link = IndexMap<Atom, LinkItem>; /// key: export binding name pub type Export = FxHashMap<Atom, ExportItem>; #[derive(Debug)] pub struct ModuleDeclStrip { /// all imports/exports collected by path in source text order pub link: Link, /// local exported binding /// /// `export { foo as "1", bar }` /// -> Map("1" => foo, bar => bar) pub export: Export, /// `export = ` detected pub export_assign: Option<Box<Expr>>, pub has_module_decl: bool, /// `export default expr` export_default: Option<Stmt>, const_var_kind: VarDeclKind, } impl ModuleDeclStrip { pub fn new(const_var_kind: VarDeclKind) -> Self { Self { link: Default::default(), export: Default::default(), export_assign: Default::default(), has_module_decl: Default::default(), export_default: Default::default(), const_var_kind, } } } impl VisitMut for ModuleDeclStrip { noop_visit_mut_type!(fail); fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) { let mut list = Vec::with_capacity(n.len()); for item in n.drain(..) { match item { ModuleItem::Stmt(stmt) => list.push(stmt.into()), ModuleItem::ModuleDecl(mut module_decl) => { // collect link meta module_decl.visit_mut_with(self); self.has_module_decl = true; // emit stmt match module_decl { ModuleDecl::Import(..) => continue, ModuleDecl::ExportDecl(ExportDecl { decl, .. }) => { list.push(decl.into()); } ModuleDecl::ExportNamed(..) => continue, ModuleDecl::ExportDefaultDecl(ExportDefaultDecl { decl, .. }) => match decl { DefaultDecl::Class(class_expr) => { list.extend(class_expr.as_class_decl().map(From::from)) } DefaultDecl::Fn(fn_expr) => { list.extend(fn_expr.as_fn_decl().map(From::from)) } DefaultDecl::TsInterfaceDecl(_) => continue, }, ModuleDecl::ExportDefaultExpr(..) => { list.extend(self.export_default.take().map(From::from)) } ModuleDecl::ExportAll(..) => continue, ModuleDecl::TsImportEquals(..) => continue, ModuleDecl::TsExportAssignment(..) => continue, ModuleDecl::TsNamespaceExport(..) => continue, }; } }; } *n = list; } // collect all static import fn visit_mut_import_decl(&mut self, n: &mut ImportDecl) { if n.type_only { return; } let ImportDecl { specifiers, src, .. } = n.take(); self.link .entry(src.value) .or_default() .mut_dummy_span(src.span) .extend(specifiers.into_iter().map(From::from)); } /// ```javascript /// export const foo = 1, bar = 2, { baz } = { baz: 3 }; /// export let a = 1, [b] = [2]; /// export function x() {} /// export class y {} /// ``` /// -> /// ```javascript /// const foo = 1, bar = 2, { baz } = { baz: 3 }; /// let a = 1, [b] = [2]; /// function x() {} /// class y {} /// ``` fn visit_mut_export_decl(&mut self, n: &mut ExportDecl) { match &n.decl { Decl::Class(ClassDecl { ident, .. }) | Decl::Fn(FnDecl { ident, .. }) => { self.export.insert( ident.sym.clone(), ExportItem::new((ident.span, ident.ctxt), ident.clone()), ); } Decl::Var(v) => { self.export.extend( find_pat_ids::<_, Ident>(&v.decls) .into_iter() .map(|id| (id.sym.clone(), ExportItem::new((id.span, id.ctxt), id))), ); } _ => {} }; } /// ```javascript /// export { foo, foo as bar, foo as "baz" }; /// export { "foo", foo as bar, "foo" as "baz" } from "mod"; /// export * as foo from "mod"; /// export * as "bar" from "mod"; /// ``` fn visit_mut_named_export(&mut self, n: &mut NamedExport) { if n.type_only { return; } let NamedExport { specifiers, src, .. } = n.take(); if let Some(src) = src { self.link .entry(src.value) .or_default() .mut_dummy_span(src.span) .extend(specifiers.into_iter().map(From::from)); } else { self.export.extend(specifiers.into_iter().map(|e| match e { ExportSpecifier::Namespace(..) => { unreachable!("`export *` without src is invalid") } ExportSpecifier::Default(..) => { unreachable!("`export foo` without src is invalid") } ExportSpecifier::Named(ExportNamedSpecifier { orig, exported, .. }) => { let orig = match orig { ModuleExportName::Ident(id) => id, ModuleExportName::Str(_) => { unreachable!(r#"`export {{ "foo" }}` without src is invalid"#) } }; if let Some(exported) = exported { let (export_name, export_name_span) = match exported { ModuleExportName::Ident(Ident { ctxt, span, sym, .. }) => (sym, (span, ctxt)), ModuleExportName::Str(Str { span, value, .. }) => { (value, (span, Default::default())) } }; (export_name, ExportItem::new(export_name_span, orig)) } else { ( orig.sym.clone(), ExportItem::new((orig.span, orig.ctxt), orig), ) } } })) } } /// ```javascript /// export default class foo {}; /// export default class {}; /// export default function bar () {}; /// export default function () {}; /// ``` /// -> /// ```javascript /// class foo {}; /// class _default {}; /// function bar () {}; /// function _default () {}; /// ``` fn visit_mut_export_default_decl(&mut self, n: &mut ExportDefaultDecl) { match &mut n.decl { DefaultDecl::Class(class_expr) => { let ident = class_expr .ident .get_or_insert_with(|| private_ident!(n.span, "_default")) .clone(); self.export.insert( "default".into(), ExportItem::new((n.span, Default::default()), ident), ); } DefaultDecl::Fn(fn_expr) => { let ident = fn_expr .ident .get_or_insert_with(|| private_ident!(n.span, "_default")) .clone(); self.export.insert( "default".into(), ExportItem::new((n.span, Default::default()), ident), ); } DefaultDecl::TsInterfaceDecl(_) => {} } } /// ```javascript /// export default foo; /// export default 1 /// ``` /// -> /// ```javascript /// var _default = foo; /// var _default = 1; /// ``` fn visit_mut_export_default_expr(&mut self, n: &mut ExportDefaultExpr) { let ident = private_ident!(n.span, "_default"); self.export.insert( "default".into(), ExportItem::new((n.span, Default::default()), ident.clone()), ); self.export_default = Some( n.expr .take() .into_var_decl(self.const_var_kind, ident.into()) .into(), ); } /// ```javascript /// export * from "mod"; /// ``` fn visit_mut_export_all(&mut self, n: &mut ExportAll) { let Str { value: src_key, span: src_span, .. } = *n.take().src; self.link .entry(src_key) .or_default() .mut_dummy_span(src_span) .insert(LinkSpecifier::ExportStar); } /// ```javascript /// import foo = require("mod"); /// export import foo = require("mod"); /// ``` fn visit_mut_ts_import_equals_decl(&mut self, n: &mut TsImportEqualsDecl) { if n.is_type_only { return; } let TsImportEqualsDecl { id, module_ref, is_export, .. } = n; if let TsModuleRef::TsExternalModuleRef(TsExternalModuleRef { expr: Str { span, value: src_key, .. }, .. }) = module_ref { if *is_export { self.export.insert( id.sym.clone(), ExportItem::new((id.span, id.ctxt), id.clone()), ); } self.link .entry(src_key.clone()) .or_default() .mut_dummy_span(*span) .insert(LinkSpecifier::ImportEqual(id.to_id())); } } /// ```javascript /// export = expr; /// ``` fn visit_mut_ts_export_assignment(&mut self, n: &mut TsExportAssignment) { self.export_assign.get_or_insert(n.expr.take()); } } #[derive(Debug, PartialEq, Eq, Hash)] pub enum LinkSpecifier { ///```javascript /// import "mod"; /// import {} from "mod", /// import { type foo } from "mod"; /// export {} from "mod"; /// export { type foo } from "mod"; /// ``` Empty, /// ```javascript /// import { imported as local, local } from "mod"; /// import { "imported" as local } from "mod"; /// ``` /// Note: imported will never be `default` ImportNamed { imported: Option<Atom>, local: Id }, /// ```javascript /// import foo from "mod"; /// ``` ImportDefault(Id), /// ```javascript /// import * as foo from "mod"; /// ``` ImportStarAs(Id), /// ```javascript /// export { orig, orig as exported } from "mod"; /// export { "orig", "orig" as "exported" } from "mod"; /// ``` /// Note: orig will never be `default` ExportNamed { orig: (Atom, SpanCtx), exported: Option<(Atom, SpanCtx)>, }, /// ```javascript /// export { default } from "foo"; /// export { "default" } from "foo"; /// export { default as foo } from "mod"; /// ``` /// (default_span, local_sym, local_span) ExportDefaultAs(SpanCtx, Atom, SpanCtx), /// ```javascript /// export * as foo from "mod"; /// export * as "bar" from "mod"; /// ``` ExportStarAs(Atom, SpanCtx), /// ```javascript /// export * from "mod"; /// ``` ExportStar, /// ```javascript /// import foo = require("foo"); /// ``` ImportEqual(Id), } impl From<ImportSpecifier> for LinkSpecifier { fn from(i: ImportSpecifier) -> Self { match i { ImportSpecifier::Namespace(ImportStarAsSpecifier { local, .. }) => { Self::ImportStarAs(local.to_id()) } ImportSpecifier::Default(ImportDefaultSpecifier { local, .. }) => { Self::ImportDefault(local.to_id()) } ImportSpecifier::Named(ImportNamedSpecifier { is_type_only: false, local, imported: Some(ModuleExportName::Ident(Ident { sym: s, .. })) | Some(ModuleExportName::Str(Str { value: s, .. })), .. }) if &*s == "default" => Self::ImportDefault(local.to_id()), ImportSpecifier::Named(ImportNamedSpecifier { is_type_only: false, local, imported, .. }) => { let imported = imported.map(|e| match e { ModuleExportName::Ident(Ident { sym, .. }) => sym, ModuleExportName::Str(Str { value, .. }) => value, }); Self::ImportNamed { local: local.to_id(), imported, } } _ => Self::Empty, } } } impl From<ExportSpecifier> for LinkSpecifier { fn from(e: ExportSpecifier) -> Self { match e { ExportSpecifier::Namespace(ExportNamespaceSpecifier { name: ModuleExportName::Ident(Ident { span, sym, .. }) | ModuleExportName::Str(Str { span, value: sym, .. }), .. }) => Self::ExportStarAs(sym, (span, SyntaxContext::empty())), ExportSpecifier::Default(ExportDefaultSpecifier { exported }) => { // https://github.com/tc39/proposal-export-default-from Self::ExportDefaultAs( (exported.span, exported.ctxt), exported.sym, (exported.span, exported.ctxt), ) } ExportSpecifier::Named(ExportNamedSpecifier { is_type_only: false, orig, exported, .. }) => { let orig = match orig { ModuleExportName::Ident(Ident { span, sym, .. }) | ModuleExportName::Str(Str { span, value: sym, .. }) => (sym, (span, SyntaxContext::empty().apply_mark(Mark::new()))), }; let exported = exported.map(|exported| match exported { ModuleExportName::Ident(Ident { span, sym, .. }) | ModuleExportName::Str(Str { span, value: sym, .. }) => (sym, (span, SyntaxContext::empty().apply_mark(Mark::new()))), }); match (&*orig.0, orig.1) { ("default", default_span) => { let (sym, span) = exported.unwrap_or(orig); Self::ExportDefaultAs(default_span, sym, span) } _ => Self::ExportNamed { orig, exported }, } } _ => Self::Empty, } } } #[derive(Debug, Default)] pub struct LinkItem(pub SpanCtx, pub FxHashSet<LinkSpecifier>, pub LinkFlag); use bitflags::bitflags; bitflags! { #[derive(Default, Debug)] pub struct LinkFlag: u8 { const NAMED = 1 << 0; const DEFAULT = 1 << 1; const NAMESPACE = Self::NAMED.bits() | Self::DEFAULT.bits(); const EXPORT_STAR = 1 << 2; const IMPORT_EQUAL = 1 << 3; } } impl LinkFlag { pub fn interop(&self) -> bool { self.intersects(Self::DEFAULT) } pub fn has_named(&self) -> bool { self.intersects(Self::NAMED) } pub fn namespace(&self) -> bool { self.contains(Self::NAMESPACE) } pub fn need_raw_import(&self) -> bool { self.interop() && self.intersects(Self::IMPORT_EQUAL) } pub fn export_star(&self) -> bool { self.intersects(Self::EXPORT_STAR) } } impl From<&LinkSpecifier> for LinkFlag { fn from(s: &LinkSpecifier) -> Self { match s { LinkSpecifier::Empty => Self::empty(), LinkSpecifier::ImportStarAs(..) => Self::NAMESPACE, LinkSpecifier::ImportDefault(..) => Self::DEFAULT, LinkSpecifier::ImportNamed { .. } => Self::NAMED, LinkSpecifier::ExportStarAs(..) => Self::NAMESPACE, LinkSpecifier::ExportDefaultAs(..) => Self::DEFAULT, LinkSpecifier::ExportNamed { .. } => Self::NAMED, LinkSpecifier::ImportEqual(..) => Self::IMPORT_EQUAL, LinkSpecifier::ExportStar => Self::EXPORT_STAR, } } } impl From<&ImportSpecifier> for LinkFlag { fn from(i: &ImportSpecifier) -> Self { match i { ImportSpecifier::Namespace(..) => Self::NAMESPACE, ImportSpecifier::Default(ImportDefaultSpecifier { .. }) => Self::DEFAULT, ImportSpecifier::Named(ImportNamedSpecifier { is_type_only: false, imported: Some(ModuleExportName::Ident(Ident { sym: default, .. })) | Some(ModuleExportName::Str(Str { value: default, .. })), .. }) if &**default == "default" => Self::DEFAULT, ImportSpecifier::Named(ImportNamedSpecifier { is_type_only: false, .. }) => Self::NAMED, _ => Self::empty(), } } } impl From<&ExportSpecifier> for LinkFlag { fn from(e: &ExportSpecifier) -> Self { match e { ExportSpecifier::Namespace(..) => Self::NAMESPACE, // https://github.com/tc39/proposal-export-default-from ExportSpecifier::Default(..) => Self::DEFAULT, ExportSpecifier::Named(ExportNamedSpecifier { is_type_only: false, orig: ModuleExportName::Ident(Ident { sym: s, .. }) | ModuleExportName::Str(Str { value: s, .. }), .. }) if &**s == "default" => Self::DEFAULT, ExportSpecifier::Named(ExportNamedSpecifier { is_type_only: false, .. }) => Self::NAMED, _ => Self::empty(), } } } impl Extend<LinkSpecifier> for LinkItem { fn extend<T: IntoIterator<Item = LinkSpecifier>>(&mut self, iter: T) { iter.into_iter().for_each(|link| { self.insert(link); }); } } impl LinkItem { fn mut_dummy_span(&mut self, span: Span) -> &mut Self { if self.0 .0.is_dummy() { self.0 .0 = span; } self } fn insert(&mut self, link: LinkSpecifier) -> bool { self.2 |= (&link).into(); self.1.insert(link) } } pub(crate) type ExportObjPropList = Vec<ExportKV>; /// Reduce self to generate ImportMap and ExportObjPropList pub(crate) trait LinkSpecifierReducer { fn reduce( self, import_map: &mut ImportMap, export_obj_prop_list: &mut ExportObjPropList, mod_ident: &Ident, raw_mod_ident: &Option<Ident>, ref_to_mod_ident: &mut bool, // do not emit `mod.default`, emit `mod` instead default_nowrap: bool, ); } impl LinkSpecifierReducer for FxHashSet<LinkSpecifier> { fn reduce( self, import_map: &mut ImportMap, export_obj_prop_list: &mut ExportObjPropList, mod_ident: &Ident, raw_mod_ident: &Option<Ident>, ref_to_mod_ident: &mut bool, default_nowrap: bool, ) { self.into_iter().for_each(|s| match s { LinkSpecifier::ImportNamed { imported, local } => { *ref_to_mod_ident = true; import_map.insert( local.clone(), (mod_ident.clone(), imported.or(Some(local.0))), ); } LinkSpecifier::ImportDefault(id) => { *ref_to_mod_ident = true; import_map.insert( id, ( mod_ident.clone(), (!default_nowrap).then(|| "default".into()), ), ); } LinkSpecifier::ImportStarAs(id) => { *ref_to_mod_ident = true; import_map.insert(id, (mod_ident.clone(), None)); } LinkSpecifier::ExportNamed { orig, exported } => { *ref_to_mod_ident = true; // ```javascript // export { foo as bar } from "mod"; // // import { foo } from "mod"; // export { foo as bar }; // ``` // foo -> mod.foo import_map.insert( (orig.0.clone(), orig.1 .1), (mod_ident.clone(), Some(orig.0.clone())), ); let (export_name, export_name_span) = exported.unwrap_or_else(|| orig.clone()); // bar -> foo export_obj_prop_list.push(( export_name, ExportItem::new(export_name_span, quote_ident!(orig.1 .1, orig.1 .0, orig.0)), )) } LinkSpecifier::ExportDefaultAs(_, key, span) => { *ref_to_mod_ident = true; // ```javascript // export { default as foo } from "mod"; // // import { default as foo } from "mod"; // export { foo }; // ``` // foo -> mod.default import_map.insert( (key.clone(), span.1), (mod_ident.clone(), Some("default".into())), ); export_obj_prop_list.push(( key.clone(), ExportItem::new(span, quote_ident!(span.1, span.0, key)), )); } LinkSpecifier::ExportStarAs(key, span) => { *ref_to_mod_ident = true; export_obj_prop_list.push((key, ExportItem::new(span, mod_ident.clone()))); } LinkSpecifier::ExportStar => {} LinkSpecifier::ImportEqual(id) => { *ref_to_mod_ident = true; import_map.insert( id, ( raw_mod_ident.clone().unwrap_or_else(|| mod_ident.clone()), None, ), ); } LinkSpecifier::Empty => {} }) } } #[derive(Debug)] pub struct ExportItem(SpanCtx, Ident); impl ExportItem { pub fn new(export_name_span: SpanCtx, local_ident: Ident) -> Self { Self(export_name_span, local_ident) } pub fn export_name_span(&self) -> SpanCtx { self.0 } pub fn into_local_ident(self) -> Ident { self.1 } } pub type ExportKV = (Atom, ExportItem);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/src/module_ref_rewriter.rs
Rust
use rustc_hash::{FxHashMap, FxHashSet}; use swc_atoms::Atom; use swc_common::SyntaxContext; use swc_ecma_ast::*; use swc_ecma_transforms_base::helpers::HELPERS; use swc_ecma_utils::{ExprFactory, QueryRef, RefRewriter}; use swc_ecma_visit::VisitMutWith; use crate::util::prop_name; pub type ImportMap = FxHashMap<Id, (Ident, Option<Atom>)>; pub(crate) struct ImportQuery { /// ```javascript /// import foo, { a as b, c } from "mod"; /// import * as x from "x"; /// foo, b, c; /// x; /// ``` /// -> /// ```javascript /// _mod.default, _mod.a, _mod.c; /// _x; /// /// Map( /// foo => (_mod, Some("default")), /// b => (_mod, Some("a")), /// c => (_mod, Some("c")), /// x => (_x, None), /// ) /// ``` import_map: ImportMap, lazy_record: FxHashSet<Id>, helper_ctxt: Option<SyntaxContext>, } impl QueryRef for ImportQuery { fn query_ref(&self, ident: &Ident) -> Option<Box<Expr>> { self.import_map .get(&ident.to_id()) .map(|(mod_ident, mod_prop)| -> Box<Expr> { let mut mod_ident = mod_ident.clone(); let span = ident.span; mod_ident.span = span; let mod_expr = if self.lazy_record.contains(&mod_ident.to_id()) { mod_ident.as_call(span, Default::default()) } else { mod_ident.into() }; if let Some(imported_name) = mod_prop { let prop = prop_name(imported_name, Default::default()).into(); MemberExpr { obj: Box::new(mod_expr), span, prop, } .into() } else { mod_expr.into() } }) } fn query_lhs(&self, _: &Ident) -> Option<Box<Expr>> { // import binding cannot be used as lhs None } fn query_jsx(&self, _: &Ident) -> Option<JSXElementName> { // We do not need to handle JSX since there is no jsx preserve option in swc None } fn should_fix_this(&self, ident: &Ident) -> bool { if self.helper_ctxt.iter().any(|ctxt| ctxt == &ident.ctxt) { return false; } self.import_map .get(&ident.to_id()) .map(|(_, prop)| prop.is_some()) .unwrap_or_default() } } pub(crate) fn rewrite_import_bindings<V>( node: &mut V, import_map: ImportMap, lazy_record: FxHashSet<Id>, ) where V: VisitMutWith<RefRewriter<ImportQuery>>, { let mut v = RefRewriter { query: ImportQuery { import_map, lazy_record, helper_ctxt: { HELPERS .is_set() .then(|| HELPERS.with(|helper| helper.mark())) .map(|mark| SyntaxContext::empty().apply_mark(mark)) }, }, }; node.visit_mut_with(&mut v); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/src/path.rs
Rust
use std::{ borrow::Cow, env::current_dir, fs::canonicalize, io, path::{Component, Path, PathBuf}, sync::Arc, }; use anyhow::{anyhow, Context, Error}; use path_clean::PathClean; use pathdiff::diff_paths; use swc_atoms::Atom; use swc_common::{FileName, Mark, Span, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_loader::resolve::{Resolution, Resolve}; use swc_ecma_utils::{quote_ident, ExprFactory}; use tracing::{debug, info, warn, Level}; #[derive(Default)] pub enum Resolver { Real { base: FileName, resolver: Arc<dyn ImportResolver>, }, #[default] Default, } impl Resolver { pub(crate) fn resolve(&self, src: Atom) -> Atom { match self { Self::Real { resolver, base } => resolver .resolve_import(base, &src) .with_context(|| format!("failed to resolve import `{}`", src)) .unwrap(), Self::Default => src, } } pub(crate) fn make_require_call( &self, unresolved_mark: Mark, src: Atom, src_span: Span, ) -> Expr { let src = self.resolve(src); CallExpr { span: DUMMY_SP, callee: quote_ident!( SyntaxContext::empty().apply_mark(unresolved_mark), "require" ) .as_callee(), args: vec![Lit::Str(Str { span: src_span, raw: None, value: src, }) .as_arg()], ..Default::default() } .into() } } pub trait ImportResolver { /// Resolves `target` as a string usable by the modules pass. /// /// The returned string will be used as a module specifier. fn resolve_import(&self, base: &FileName, module_specifier: &str) -> Result<Atom, Error>; } /// [ImportResolver] implementation which just uses original source. #[derive(Debug, Clone, Copy, Default)] pub struct NoopImportResolver; impl ImportResolver for NoopImportResolver { fn resolve_import(&self, _: &FileName, module_specifier: &str) -> Result<Atom, Error> { Ok(module_specifier.into()) } } /// [ImportResolver] implementation for node.js /// /// Supports [FileName::Real] and [FileName::Anon] for `base`, [FileName::Real] /// and [FileName::Custom] for `target`. ([FileName::Custom] is used for core /// modules) #[derive(Debug, Clone, Default)] pub struct NodeImportResolver<R> where R: Resolve, { resolver: R, config: Config, } #[derive(Debug, Clone)] pub struct Config { pub base_dir: Option<PathBuf>, pub resolve_fully: bool, pub file_extension: String, } impl Default for Config { fn default() -> Config { Config { file_extension: crate::util::Config::default_js_ext(), resolve_fully: bool::default(), base_dir: Option::default(), } } } impl<R> NodeImportResolver<R> where R: Resolve, { pub fn with_config(resolver: R, config: Config) -> Self { #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))] if let Some(base_dir) = &config.base_dir { assert!( base_dir.is_absolute(), "base_dir(`{}`) must be absolute. Please ensure that `jsc.baseUrl` is specified \ correctly. This cannot be deduced by SWC itself because SWC is a transpiler and \ it does not try to resolve project details. In other words, SWC does not know \ which directory should be used as a base directory. It can be deduced if \ `.swcrc` is used, but if not, there are many candidates. e.g. the directory \ containing `package.json`, or the current working directory. Because of that, \ the caller (typically the developer of the JavaScript package) should specify \ it. If you see this error, please report an issue to the package author.", base_dir.display() ); } Self { resolver, config } } } impl<R> NodeImportResolver<R> where R: Resolve, { fn to_specifier(&self, mut target_path: PathBuf, orig_filename: Option<&str>) -> Atom { debug!( "Creating a specifier for `{}` with original filename `{:?}`", target_path.display(), orig_filename ); if let Some(orig_filename) = orig_filename { let is_resolved_as_index = if let Some(stem) = target_path.file_stem() { stem == "index" } else { false }; let is_resolved_as_non_js = if let Some(ext) = target_path.extension() { ext.to_string_lossy() != self.config.file_extension } else { false }; let is_resolved_as_js = if let Some(ext) = target_path.extension() { ext.to_string_lossy() == self.config.file_extension } else { false }; let is_exact = if let Some(filename) = target_path.file_name() { filename == orig_filename } else { false }; let file_stem_matches = if let Some(stem) = target_path.file_stem() { stem == orig_filename } else { false }; if self.config.resolve_fully && is_resolved_as_js { } else if orig_filename == "index" { // Import: `./foo/index` // Resolved: `./foo/index.js` if self.config.resolve_fully { target_path.set_file_name(format!("index.{}", self.config.file_extension)); } else { target_path.set_file_name("index"); } } else if is_resolved_as_index && is_resolved_as_js && orig_filename != format!("index.{}", self.config.file_extension) { // Import: `./foo` // Resolved: `./foo/index.js` target_path.pop(); } else if is_resolved_as_non_js && self.config.resolve_fully && file_stem_matches { target_path.set_extension(self.config.file_extension.clone()); } else if !is_resolved_as_js && !is_resolved_as_index && !is_exact { target_path.set_file_name(orig_filename); } else if is_resolved_as_non_js && is_exact { if let Some(ext) = Path::new(orig_filename).extension() { target_path.set_extension(ext); } else { target_path.set_extension(self.config.file_extension.clone()); } } else if self.config.resolve_fully && is_resolved_as_non_js { target_path.set_extension(self.config.file_extension.clone()); } else if is_resolved_as_non_js && is_resolved_as_index { if orig_filename == "index" { target_path.set_extension(""); } else { target_path.pop(); } } } else { target_path.set_extension(""); } if cfg!(target_os = "windows") { target_path.display().to_string().replace('\\', "/").into() } else { target_path.display().to_string().into() } } fn try_resolve_import(&self, base: &FileName, module_specifier: &str) -> Result<Atom, Error> { let _tracing = if cfg!(debug_assertions) { Some( tracing::span!( Level::ERROR, "resolve_import", base = tracing::field::display(base), module_specifier = tracing::field::display(module_specifier), ) .entered(), ) } else { None }; let orig_slug = module_specifier.split('/').last(); let target = self.resolver.resolve(base, module_specifier); let mut target = match target { Ok(v) => v, Err(err) => { warn!("import rewriter: failed to resolve: {}", err); return Ok(module_specifier.into()); } }; // Bazel uses symlink // // https://github.com/swc-project/swc/issues/8265 if let FileName::Real(resolved) = &target.filename { if let Ok(orig) = canonicalize(resolved) { target.filename = FileName::Real(orig); } } let Resolution { filename: target, slug, } = target; let slug = slug.as_deref().or(orig_slug); info!("Resolved as {target:?} with slug = {slug:?}"); let mut target = match target { FileName::Real(v) => v, FileName::Custom(s) => return Ok(self.to_specifier(s.into(), slug)), _ => { unreachable!( "Node path provider does not support using `{:?}` as a target file name", target ) } }; let mut base = match base { FileName::Real(v) => Cow::Borrowed( v.parent() .ok_or_else(|| anyhow!("failed to get parent of {:?}", v))?, ), FileName::Anon => match &self.config.base_dir { Some(v) => Cow::Borrowed(&**v), None => { if cfg!(target_arch = "wasm32") { panic!("Please specify `filename`") } else { Cow::Owned(current_dir().expect("failed to get current directory")) } } }, _ => { unreachable!( "Node path provider does not support using `{:?}` as a base file name", base ) } }; if base.is_absolute() != target.is_absolute() { base = Cow::Owned(absolute_path(self.config.base_dir.as_deref(), &base)?); target = absolute_path(self.config.base_dir.as_deref(), &target)?; } debug!( "Comparing values (after normalizing absoluteness)\nbase={}\ntarget={}", base.display(), target.display() ); let rel_path = diff_paths(&target, &*base); let rel_path = match rel_path { Some(v) => v, None => return Ok(self.to_specifier(target, slug)), }; debug!("Relative path: {}", rel_path.display()); { // Check for `node_modules`. for component in rel_path.components() { match component { Component::Prefix(_) => {} Component::RootDir => {} Component::CurDir => {} Component::ParentDir => {} Component::Normal(c) => { if c == "node_modules" { return Ok(module_specifier.into()); } } } } } let s = rel_path.to_string_lossy(); let s = if s.starts_with('.') || s.starts_with('/') || rel_path.is_absolute() { s } else { Cow::Owned(format!("./{}", s)) }; Ok(self.to_specifier(s.into_owned().into(), slug)) } } impl<R> ImportResolver for NodeImportResolver<R> where R: Resolve, { fn resolve_import(&self, base: &FileName, module_specifier: &str) -> Result<Atom, Error> { self.try_resolve_import(base, module_specifier) .or_else(|err| { warn!("Failed to resolve import: {}", err); Ok(module_specifier.into()) }) } } macro_rules! impl_ref { ($P:ident, $T:ty) => { impl<$P> ImportResolver for $T where $P: ImportResolver, { fn resolve_import(&self, base: &FileName, target: &str) -> Result<Atom, Error> { (**self).resolve_import(base, target) } } }; } impl_ref!(P, &'_ P); impl_ref!(P, Box<P>); impl_ref!(P, Arc<P>); fn absolute_path(base_dir: Option<&Path>, path: &Path) -> io::Result<PathBuf> { let absolute_path = if path.is_absolute() { path.to_path_buf() } else { match base_dir { Some(base_dir) => base_dir.join(path), None => current_dir()?.join(path), } } .clean(); Ok(absolute_path) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/src/rewriter.rs
Rust
use std::sync::Arc; use anyhow::Context; use swc_common::FileName; use swc_ecma_ast::*; use swc_ecma_visit::{visit_mut_pass, VisitMut, VisitMutWith}; use crate::path::ImportResolver; /// Import rewriter, which rewrites imports as es modules. pub fn import_rewriter(base: FileName, resolver: Arc<dyn ImportResolver>) -> impl Pass { visit_mut_pass(Rewriter { base, resolver }) } struct Rewriter { base: FileName, resolver: Arc<dyn ImportResolver>, } impl VisitMut for Rewriter { fn visit_mut_call_expr(&mut self, e: &mut CallExpr) { e.visit_mut_children_with(self); if let Callee::Import(_) = &e.callee { if let Some(ExprOrSpread { spread: None, expr }) = &mut e.args.get_mut(0) { if let Expr::Lit(Lit::Str(s)) = &mut **expr { let src = self .resolver .resolve_import(&self.base, &s.value) .with_context(|| format!("failed to resolve import `{}`", s.value)) .unwrap(); s.raw = None; s.value = src; } } } } fn visit_mut_import_decl(&mut self, i: &mut ImportDecl) { let src = self .resolver .resolve_import(&self.base, &i.src.value) .with_context(|| format!("failed to resolve import `{}`", i.src.value)) .unwrap(); i.src.raw = None; i.src.value = src; } fn visit_mut_named_export(&mut self, e: &mut NamedExport) { if let Some(src) = &mut e.src { let new = self .resolver .resolve_import(&self.base, &src.value) .with_context(|| format!("failed to resolve import `{}`", src.value)) .unwrap(); src.raw = None; src.value = new; } } fn visit_mut_export_all(&mut self, n: &mut ExportAll) { let src = &mut n.src; let new = self .resolver .resolve_import(&self.base, &src.value) .with_context(|| format!("failed to resolve import `{}`", src.value)) .unwrap(); src.raw = None; src.value = new; } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/src/system_js.rs
Rust
use anyhow::Context; use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; use swc_atoms::Atom; use swc_common::{Mark, Span, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::{ member_expr, private_ident, quote_ident, quote_str, var::VarCollector, ExprFactory, }; use swc_ecma_visit::{fold_pass, standard_only_fold, Fold, FoldWith, VisitWith}; pub use super::util::Config as InnerConfig; use crate::{ path::Resolver, top_level_this::top_level_this, util::{local_name_for_src, use_strict}, }; #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct Config { #[serde(default)] pub allow_top_level_this: bool, #[serde(flatten, default)] pub config: InnerConfig, } struct SystemJs { unresolved_mark: Mark, resolver: Resolver, config: Config, declare_var_idents: Vec<Ident>, export_map: FxHashMap<Id, Vec<Atom>>, export_names: Vec<Atom>, export_values: Vec<Box<Expr>>, tla: bool, enter_async_fn: u32, root_fn_decl_idents: Vec<Ident>, module_item_meta_list: Vec<ModuleItemMeta>, import_idents: Vec<Id>, export_ident: Ident, context_ident: Ident, } pub fn system_js(resolver: Resolver, unresolved_mark: Mark, config: Config) -> impl Pass { fold_pass(SystemJs { unresolved_mark, resolver, config, declare_var_idents: Vec::new(), export_map: Default::default(), export_names: Vec::new(), export_values: Vec::new(), tla: false, enter_async_fn: 0, root_fn_decl_idents: Vec::new(), module_item_meta_list: Vec::new(), import_idents: Vec::new(), export_ident: private_ident!("_export"), context_ident: private_ident!("_context"), }) } struct ModuleItemMeta { export_names: Vec<Atom>, export_values: Vec<Box<Expr>>, has_export_all: bool, src: Atom, setter_fn_stmts: Vec<Stmt>, } impl SystemJs { fn export_call(&self, name: Atom, span: Span, expr: Expr) -> CallExpr { CallExpr { span, callee: self.export_ident.clone().as_callee(), args: vec![quote_str!(name).as_arg(), expr.as_arg()], ..Default::default() } } fn fold_module_name_ident(&mut self, ident: Ident) -> Expr { if &*ident.sym == "__moduleName" && ident.ctxt.outer() == self.unresolved_mark { return self .context_ident .clone() .make_member(quote_ident!("id")) .into(); } ident.into() } fn replace_assign_expr(&mut self, assign_expr: AssignExpr) -> Expr { match &assign_expr.left { AssignTarget::Simple(pat_or_expr) => match pat_or_expr { SimpleAssignTarget::Ident(ident) => { for (k, v) in self.export_map.iter() { if ident.to_id() == *k { let mut expr = assign_expr.into(); for value in v.iter() { expr = self.export_call(value.clone(), DUMMY_SP, expr).into(); } return expr; } } assign_expr.into() } _ => assign_expr.into(), }, AssignTarget::Pat(pat) => { let mut to: Vec<Id> = Vec::new(); pat.visit_with(&mut VarCollector { to: &mut to }); match pat { AssignTargetPat::Object(..) | AssignTargetPat::Array(..) => { let mut exprs = vec![Box::new(Expr::Assign(assign_expr))]; for to in to { for (k, v) in self.export_map.iter() { if to == *k { for _ in v.iter() { exprs.push( self.export_call( to.0.clone(), DUMMY_SP, Ident::new(to.0.clone(), DUMMY_SP, to.1).into(), ) .into(), ); } break; } } } SeqExpr { span: DUMMY_SP, exprs, } .into() } _ => assign_expr.into(), } } } } fn replace_update_expr(&mut self, update_expr: UpdateExpr) -> Expr { if !update_expr.prefix { match &*update_expr.arg { Expr::Ident(ident) => { for (k, v) in self.export_map.iter() { if ident.to_id() == *k { let mut expr = BinExpr { span: DUMMY_SP, op: op!(bin, "+"), left: UnaryExpr { span: DUMMY_SP, op: op!(unary, "+"), arg: Box::new(Expr::Ident(ident.clone())), } .into(), right: 1.0.into(), } .into(); for value in v.iter() { expr = self.export_call(value.clone(), DUMMY_SP, expr).into(); } return SeqExpr { span: DUMMY_SP, exprs: vec![Box::new(expr), Box::new(Expr::Update(update_expr))], } .into(); } } update_expr.into() } _ => update_expr.into(), } } else { update_expr.into() } } fn add_export_name(&mut self, key: Id, value: Atom) { let mut find = false; for (k, v) in self.export_map.iter_mut() { if key == *k { v.push(value.clone()); find = true; break; } } if !find { self.export_map.insert(key, vec![value]); } } fn add_declare_var_idents(&mut self, ident: &Ident) { self.declare_var_idents.push(ident.clone()); } fn build_export_call( &mut self, export_names: &mut Vec<Atom>, export_values: &mut Vec<Box<Expr>>, ) -> Vec<Stmt> { match export_names.len() { 0 => Vec::new(), 1 => vec![self .export_call(export_names.remove(0), DUMMY_SP, *export_values.remove(0)) .into_stmt()], _ => { let mut props = Vec::new(); for (sym, value) in export_names.drain(..).zip(export_values.drain(..)) { props.push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: match Ident::verify_symbol(&sym) { Ok(..) => PropName::Ident(quote_ident!(sym)), Err(..) => PropName::Str(quote_str!(sym)), }, value, })))); } vec![CallExpr { span: DUMMY_SP, callee: self.export_ident.clone().as_callee(), args: vec![ObjectLit { span: DUMMY_SP, props, } .as_arg()], ..Default::default() } .into_stmt()] } } } fn build_module_item_export_all(&mut self, mut meta: ModuleItemMeta) -> Vec<Stmt> { if !meta.has_export_all { meta.setter_fn_stmts.append( &mut self.build_export_call(&mut meta.export_names, &mut meta.export_values), ); } else { let export_obj = quote_ident!("exportObj"); let key_ident = quote_ident!("key"); let target = quote_ident!(local_name_for_src(&meta.src)); meta.setter_fn_stmts.push( VarDecl { kind: VarDeclKind::Var, decls: vec![VarDeclarator { span: DUMMY_SP, name: export_obj.clone().into(), init: Some(Box::new(Expr::Object(ObjectLit { span: DUMMY_SP, props: Vec::new(), }))), definite: false, }], ..Default::default() } .into(), ); meta.setter_fn_stmts.push( ForInStmt { span: DUMMY_SP, left: VarDecl { kind: VarDeclKind::Var, decls: vec![VarDeclarator { span: DUMMY_SP, name: key_ident.clone().into(), init: None, definite: false, }], ..Default::default() } .into(), right: target.clone().into(), body: Box::new(Stmt::Block(BlockStmt { span: DUMMY_SP, stmts: vec![Stmt::If(IfStmt { span: DUMMY_SP, test: Box::new(Expr::Bin(BinExpr { span: DUMMY_SP, op: op!("&&"), left: Box::new( key_ident .clone() .make_bin(op!("!=="), quote_str!("default")), ), right: Box::new( key_ident .clone() .make_bin(op!("!=="), quote_str!("__esModule")), ), })), cons: Box::new(Stmt::Block(BlockStmt { stmts: vec![AssignExpr { span: DUMMY_SP, op: op!("="), left: export_obj .clone() .computed_member(key_ident.clone()) .into(), right: target.computed_member(key_ident).into(), } .into_stmt()], ..Default::default() })), alt: None, })], ..Default::default() })), } .into(), ); for (sym, value) in meta .export_names .drain(..) .zip(meta.export_values.drain(..)) { meta.setter_fn_stmts.push( AssignExpr { span: DUMMY_SP, op: op!("="), left: export_obj.clone().make_member(quote_ident!(sym)).into(), right: value, } .into_stmt(), ); } meta.setter_fn_stmts.push( CallExpr { span: DUMMY_SP, callee: self.export_ident.clone().as_callee(), args: vec![export_obj.as_arg()], ..Default::default() } .into_stmt(), ); } meta.setter_fn_stmts } fn add_module_item_meta(&mut self, mut m: ModuleItemMeta) { match self .module_item_meta_list .iter() .position(|i| m.src.eq(&i.src)) { Some(index) => { let mut meta = self.module_item_meta_list.remove(index); meta.setter_fn_stmts.append(&mut m.setter_fn_stmts); meta.export_names.append(&mut m.export_names); meta.export_values.append(&mut m.export_values); if m.has_export_all { meta.has_export_all = m.has_export_all; } self.module_item_meta_list.insert(index, meta); } None => { self.module_item_meta_list.push(m); } } } #[allow(clippy::boxed_local)] fn hoist_var_decl(&mut self, var_decl: Box<VarDecl>) -> Option<Expr> { let mut exprs = Vec::new(); for var_declarator in var_decl.decls { let mut tos: Vec<Id> = Vec::new(); var_declarator.visit_with(&mut VarCollector { to: &mut tos }); for (sym, ctxt) in tos { if var_declarator.init.is_none() { for (k, v) in self.export_map.iter_mut() { if (sym.clone(), ctxt) == *k { for value in v.iter() { self.export_names.push(value.clone()); self.export_values.push(Expr::undefined(DUMMY_SP)); } break; } } } self.declare_var_idents .push(Ident::new(sym, DUMMY_SP, ctxt)); } if let Some(init) = var_declarator.init { exprs.push( AssignExpr { span: DUMMY_SP, op: op!("="), left: var_declarator.name.try_into().unwrap(), right: init, } .into(), ); } } match exprs.len() { 0 => None, _ => Some( SeqExpr { span: DUMMY_SP, exprs, } .into(), ), } } fn hoist_for_var_decl(&mut self, var_decl_or_pat: ForHead) -> ForHead { if let ForHead::VarDecl(mut var_decl) = var_decl_or_pat { if var_decl.kind == VarDeclKind::Var { let var_declarator = var_decl.decls.remove(0); let mut tos: Vec<Id> = Vec::new(); var_declarator.visit_with(&mut VarCollector { to: &mut tos }); for to in tos { if var_declarator.init.is_none() { for (k, v) in self.export_map.iter_mut() { if to == *k { for value in v.iter() { self.export_names.push(value.clone()); self.export_values.push(Expr::undefined(DUMMY_SP)); } break; } } } self.declare_var_idents .push(Ident::new(to.0, DUMMY_SP, to.1)); } ForHead::Pat(var_declarator.name.into()) } else { ForHead::VarDecl(var_decl) } } else { var_decl_or_pat } } fn hoist_variables(&mut self, stmt: Stmt) -> Stmt { match stmt { Stmt::Decl(decl) => { if let Decl::Var(var_decl) = decl { // if var_decl.kind == VarDeclKind::Var { if let Some(expr) = self.hoist_var_decl(var_decl) { expr.into_stmt() } else { EmptyStmt { span: DUMMY_SP }.into() } // } else { // return Stmt::Decl(Decl::Var(var_decl)); // } } else { decl.into() } } Stmt::For(for_stmt) => { if let Some(init) = for_stmt.init { if let VarDeclOrExpr::VarDecl(var_decl) = init { if var_decl.kind == VarDeclKind::Var { ForStmt { init: self .hoist_var_decl(var_decl) .map(|expr| VarDeclOrExpr::Expr(Box::new(expr))), ..for_stmt } .into() } else { ForStmt { init: Some(VarDeclOrExpr::VarDecl(var_decl)), ..for_stmt } .into() } } else { ForStmt { init: Some(init), ..for_stmt } .into() } } else { for_stmt.into() } } Stmt::ForIn(for_in_stmt) => ForInStmt { left: self.hoist_for_var_decl(for_in_stmt.left), ..for_in_stmt } .into(), Stmt::ForOf(for_of_stmt) => ForOfStmt { left: self.hoist_for_var_decl(for_of_stmt.left), ..for_of_stmt } .into(), _ => stmt, } } } impl Fold for SystemJs { standard_only_fold!(); fn fold_call_expr(&mut self, expr: CallExpr) -> CallExpr { let expr = expr.fold_children_with(self); match expr.callee { Callee::Import(_) => CallExpr { callee: self .context_ident .clone() .make_member(quote_ident!("import")) .as_callee(), ..expr }, _ => expr, } } fn fold_expr(&mut self, expr: Expr) -> Expr { let expr = expr.fold_children_with(self); match expr { Expr::Ident(ident) => self.fold_module_name_ident(ident), Expr::Assign(assign) => { let assign_expr = AssignExpr { right: match *assign.right { Expr::Ident(ident) => Box::new(self.fold_module_name_ident(ident)), Expr::Assign(AssignExpr { op: AssignOp::Assign, .. }) => { return self.replace_assign_expr(AssignExpr { right: assign.right, ..assign }); } _ => assign.right, }, ..assign } .fold_with(self); self.replace_assign_expr(assign_expr) } Expr::Update(update) => self.replace_update_expr(update), Expr::Call(call) => match call.callee { Callee::Import(_) => CallExpr { args: call.args.fold_with(self), callee: self .context_ident .clone() .make_member(quote_ident!("import")) .as_callee(), ..call } .into(), _ => call.into(), }, Expr::MetaProp(meta_prop_expr) => match meta_prop_expr.kind { MetaPropKind::ImportMeta => self .context_ident .clone() .make_member(quote_ident!("meta")) .into(), _ => meta_prop_expr.into(), }, Expr::Await(await_expr) => { if self.enter_async_fn == 0 { self.tla = true; } await_expr.into() } _ => expr, } } fn fold_fn_decl(&mut self, fn_decl: FnDecl) -> FnDecl { let is_async = fn_decl.function.is_async; if is_async { self.enter_async_fn += 1; } let fold_fn_expr = fn_decl.fold_children_with(self); if is_async { self.enter_async_fn -= 1; } fold_fn_expr } fn fold_prop(&mut self, prop: Prop) -> Prop { let prop = prop.fold_children_with(self); match prop { Prop::Shorthand(shorthand) => Prop::KeyValue(KeyValueProp { key: PropName::Ident(shorthand.clone().into()), value: Box::new(self.fold_module_name_ident(shorthand)), }), Prop::KeyValue(key_value_prop) => Prop::KeyValue(KeyValueProp { key: key_value_prop.key, value: match *key_value_prop.value { Expr::Ident(ident) => Box::new(self.fold_module_name_ident(ident)), _ => key_value_prop.value, }, }), _ => prop, } } fn fold_module(&mut self, module: Module) -> Module { let module = { let mut module = module; if !self.config.allow_top_level_this { top_level_this(&mut module, *Expr::undefined(DUMMY_SP)); } module }; let mut before_body_stmts: Vec<Stmt> = Vec::new(); let mut execute_stmts = Vec::new(); // collect top level fn decl for item in &module.body { if let ModuleItem::Stmt(Stmt::Decl(Decl::Fn(fn_decl))) = item { self.root_fn_decl_idents.push(fn_decl.ident.clone()); } } for item in module.body { match item { ModuleItem::ModuleDecl(decl) => match decl { ModuleDecl::Import(import) => { let src = match &self.resolver { Resolver::Real { resolver, base } => resolver .resolve_import(base, &import.src.value) .with_context(|| { format!("failed to resolve import `{}`", import.src.value) }) .unwrap(), Resolver::Default => import.src.value, }; let source_alias = local_name_for_src(&src); let mut setter_fn_stmts = Vec::new(); for specifier in import.specifiers { match specifier { ImportSpecifier::Default(specifier) => { self.import_idents.push(specifier.local.to_id()); self.add_declare_var_idents(&specifier.local); setter_fn_stmts.push( AssignExpr { span: specifier.span, op: op!("="), left: specifier.local.into(), right: quote_ident!(source_alias.clone()) .make_member(quote_ident!("default")) .into(), } .into_stmt(), ); } ImportSpecifier::Named(specifier) => { self.add_declare_var_idents(&specifier.local); setter_fn_stmts.push( AssignExpr { span: specifier.span, op: op!("="), left: specifier.local.clone().into(), right: MemberExpr { span: DUMMY_SP, obj: Box::new( quote_ident!(source_alias.clone()).into(), ), prop: match specifier.imported { Some(m) => get_module_export_member_prop(&m), None => { MemberProp::Ident(specifier.local.into()) } }, } .into(), } .into_stmt(), ); } ImportSpecifier::Namespace(specifier) => { self.import_idents.push(specifier.local.to_id()); self.add_declare_var_idents(&specifier.local); setter_fn_stmts.push( AssignExpr { span: specifier.span, op: op!("="), left: specifier.local.into(), right: quote_ident!(source_alias.clone()).into(), } .into_stmt(), ); } } } self.add_module_item_meta(ModuleItemMeta { export_names: Vec::new(), export_values: Vec::new(), has_export_all: false, src: src.clone(), setter_fn_stmts, }); } ModuleDecl::ExportNamed(decl) => match decl.src { Some(s) => { let src = match &self.resolver { Resolver::Real { resolver, base } => resolver .resolve_import(base, &s.value) .with_context(|| { format!("failed to resolve import `{}`", s.value) }) .unwrap(), Resolver::Default => s.value, }; for specifier in decl.specifiers { let source_alias = local_name_for_src(&src); let mut export_names = Vec::new(); let mut export_values = Vec::new(); match specifier { ExportSpecifier::Named(specifier) => { export_names.push(match &specifier.exported { Some(m) => get_module_export_name(m).0, None => get_module_export_name(&specifier.orig).0, }); export_values.push( MemberExpr { span: DUMMY_SP, obj: Box::new( quote_ident!(source_alias.clone()).into(), ), prop: get_module_export_member_prop( &specifier.orig, ), } .into(), ); } ExportSpecifier::Default(specifier) => { export_names.push(specifier.exported.sym.clone()); export_values.push( quote_ident!(source_alias.clone()) .make_member(quote_ident!("default")) .into(), ); } ExportSpecifier::Namespace(specifier) => { export_names .push(get_module_export_name(&specifier.name).0); export_values .push(quote_ident!(source_alias.clone()).into()); } } self.add_module_item_meta(ModuleItemMeta { export_names, export_values, has_export_all: false, src: src.clone(), setter_fn_stmts: Vec::new(), }); } } None => { for specifier in decl.specifiers { if let ExportSpecifier::Named(specifier) = specifier { let id = get_module_export_name(&specifier.orig); if self.root_fn_decl_idents.iter().any(|i| i.sym == id.0) { // hoisted function export self.export_names.push(match &specifier.exported { Some(m) => get_module_export_name(m).0, None => id.0.clone(), }); self.export_values.push(Box::new(get_module_export_expr( &specifier.orig, ))); } if self.import_idents.iter().any(|i| id == *i) { execute_stmts.push( self.export_call( id.0.clone(), DUMMY_SP, match &specifier.exported { Some(m) => get_module_export_expr(m), None => get_module_export_expr(&specifier.orig), }, ) .into_stmt(), ); } self.add_export_name( id, match specifier.exported { Some(m) => get_module_export_name(&m).0, None => get_module_export_name(&specifier.orig).0, }, ); } } } }, ModuleDecl::ExportDecl(decl) => { match decl.decl { Decl::Class(class_decl) => { let ident = class_decl.ident; self.export_names.push(ident.sym.clone()); self.export_values.push(Expr::undefined(DUMMY_SP)); self.add_declare_var_idents(&ident); self.add_export_name(ident.to_id(), ident.sym.clone()); execute_stmts.push( AssignExpr { span: DUMMY_SP, op: op!("="), left: ident.clone().into(), right: ClassExpr { ident: Some(ident.clone()), class: class_decl.class, } .into(), } .into_stmt(), ); } Decl::Fn(fn_decl) => { self.export_names.push(fn_decl.ident.sym.clone()); self.export_values.push(fn_decl.ident.clone().into()); self.add_export_name( fn_decl.ident.to_id(), fn_decl.ident.sym.clone(), ); before_body_stmts.push(fn_decl.into()); } Decl::Var(var_decl) => { let mut decl = VarDecl { decls: Vec::new(), ..*var_decl }; for var_declarator in var_decl.decls { let mut tos: Vec<Id> = Vec::new(); var_declarator.visit_with(&mut VarCollector { to: &mut tos }); for to in tos { let ident = Ident::new(to.0.clone(), DUMMY_SP, to.1); self.add_export_name(to, ident.sym.clone()); } decl.decls.push(var_declarator); } execute_stmts.push(decl.into()); } _ => {} }; } ModuleDecl::ExportDefaultDecl(decl) => { match decl.decl { DefaultDecl::Class(class_expr) => { if let Some(ident) = &class_expr.ident { self.export_names.push("default".into()); self.export_values.push(Expr::undefined(DUMMY_SP)); self.add_declare_var_idents(ident); self.add_export_name(ident.to_id(), "default".into()); execute_stmts.push( AssignExpr { span: DUMMY_SP, op: op!("="), left: ident.clone().into(), right: class_expr.into(), } .into_stmt(), ); } else { self.export_names.push("default".into()); self.export_values.push(class_expr.into()); } } DefaultDecl::Fn(fn_expr) => { if let Some(ident) = &fn_expr.ident { self.export_names.push("default".into()); self.export_values.push(ident.clone().into()); self.add_export_name(ident.to_id(), "default".into()); before_body_stmts.push( FnDecl { ident: ident.clone(), declare: false, function: fn_expr.function, } .into(), ); } else { self.export_names.push("default".into()); self.export_values.push(fn_expr.into()); } } _ => {} }; } ModuleDecl::ExportDefaultExpr(expr) => { execute_stmts.push( self.export_call("default".into(), expr.span, *expr.expr) .into_stmt(), ); } ModuleDecl::ExportAll(decl) => { self.add_module_item_meta(ModuleItemMeta { export_names: Vec::new(), export_values: Vec::new(), has_export_all: true, src: decl.src.value, setter_fn_stmts: Vec::new(), }); } _ => {} }, ModuleItem::Stmt(stmt) => match stmt { Stmt::Decl(decl) => match decl { Decl::Class(class_decl) => { self.add_declare_var_idents(&class_decl.ident); execute_stmts.push( AssignExpr { span: DUMMY_SP, op: op!("="), left: class_decl.ident.clone().into(), right: ClassExpr { ident: Some(class_decl.ident.clone()), class: class_decl.class, } .into(), } .into_stmt(), ); } Decl::Fn(fn_decl) => { before_body_stmts.push(fn_decl.into()); } _ => execute_stmts.push(decl.into()), }, _ => execute_stmts.push(stmt), }, } } // ==================== // fold_with function, here export_map is collected finished. // ==================== before_body_stmts = before_body_stmts .into_iter() .map(|s| s.fold_with(self)) .collect(); execute_stmts = execute_stmts .into_iter() .map(|s| self.hoist_variables(s).fold_with(self)) .filter(|s| !matches!(s, Stmt::Empty(_))) .collect(); // ==================== // generate export call, here export_names is collected finished. // ==================== if !self.export_names.is_empty() { let mut export_names = self.export_names.drain(..).collect(); let mut export_values = self.export_values.drain(..).collect(); before_body_stmts .append(&mut self.build_export_call(&mut export_names, &mut export_values)); } let mut setters = ArrayLit { span: DUMMY_SP, elems: Vec::new(), }; let mut dep_module_names = ArrayLit { span: DUMMY_SP, elems: Vec::new(), }; let module_item_meta_list: Vec<ModuleItemMeta> = self.module_item_meta_list.drain(..).collect(); for meta in module_item_meta_list { dep_module_names .elems .push(Some(quote_str!(meta.src.clone()).as_arg())); setters.elems.push(Some( Function { params: vec![Param { span: DUMMY_SP, decorators: Default::default(), pat: quote_ident!(local_name_for_src(&meta.src)).into(), }], span: DUMMY_SP, body: Some(BlockStmt { span: DUMMY_SP, stmts: self.build_module_item_export_all(meta), ..Default::default() }), is_generator: false, is_async: false, ..Default::default() } .as_arg(), )); } let execute = Box::new(Function { params: Vec::new(), decorators: Default::default(), span: DUMMY_SP, body: Some(BlockStmt { stmts: execute_stmts, ..Default::default() }), is_generator: false, is_async: self.tla, ..Default::default() }); let return_stmt = ReturnStmt { span: DUMMY_SP, arg: Some( ObjectLit { span: DUMMY_SP, props: vec![ PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: quote_ident!("setters").into(), value: Box::new(Expr::Array(setters)), }))), PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: quote_ident!("execute").into(), value: Box::new(Expr::Fn(FnExpr { ident: None, function: execute, })), }))), ], } .into(), ), }; let mut function_stmts = vec![use_strict()]; if !self.declare_var_idents.is_empty() { function_stmts.push( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, declare: false, decls: self .declare_var_idents .iter() .map(|i| VarDeclarator { span: i.span, name: i.clone().into(), init: None, definite: false, }) .collect(), ..Default::default() } .into(), ); } function_stmts.append(&mut before_body_stmts); function_stmts.push(return_stmt.into()); let function = Box::new(Function { params: vec![ Param { span: DUMMY_SP, decorators: Default::default(), pat: self.export_ident.clone().into(), }, Param { span: DUMMY_SP, decorators: Default::default(), pat: self.context_ident.clone().into(), }, ], decorators: Default::default(), span: DUMMY_SP, body: Some(BlockStmt { span: DUMMY_SP, stmts: function_stmts, ..Default::default() }), is_generator: false, is_async: false, ..Default::default() }); Module { body: vec![CallExpr { span: DUMMY_SP, callee: member_expr!(Default::default(), Default::default(), System.register) .as_callee(), args: vec![ dep_module_names.as_arg(), FnExpr { ident: None, function, } .as_arg(), ], ..Default::default() } .into_stmt() .into()], ..module } } } #[inline] fn get_module_export_name(module_export_name: &ModuleExportName) -> Id { match &module_export_name { ModuleExportName::Ident(ident) => ident.to_id(), ModuleExportName::Str(s) => (s.value.clone(), SyntaxContext::empty()), } } #[inline] fn get_module_export_expr(module_export_name: &ModuleExportName) -> Expr { match &module_export_name { ModuleExportName::Ident(ident) => ident.clone().into(), ModuleExportName::Str(s) => Lit::Str(quote_str!(s.value.clone())).into(), } } #[inline] fn get_module_export_member_prop(module_export_name: &ModuleExportName) -> MemberProp { match &module_export_name { ModuleExportName::Ident(ident) => MemberProp::Ident(ident.clone().into()), ModuleExportName::Str(s) => MemberProp::Computed(ComputedPropName { span: s.span, expr: Lit::Str(quote_str!(s.value.clone())).into(), }), } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/src/top_level_this.rs
Rust
use swc_ecma_ast::*; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; pub struct TopLevelThis { found: bool, this: Expr, } pub(crate) fn top_level_this<V>(node: &mut V, replace_with: Expr) -> bool where V: VisitMutWith<TopLevelThis>, { let mut v = TopLevelThis { this: replace_with, found: false, }; node.visit_mut_with(&mut v); v.found } impl VisitMut for TopLevelThis { noop_visit_mut_type!(fail); noop_visit_mut_type!(visit_mut_function, Function); fn visit_mut_class_member(&mut self, n: &mut ClassMember) { match n { ClassMember::Method(ClassMethod { key: PropName::Computed(computed), .. }) | ClassMember::ClassProp(ClassProp { key: PropName::Computed(computed), .. }) => { computed.visit_mut_with(self); } _ => {} } } fn visit_mut_prop(&mut self, n: &mut Prop) { match n { Prop::KeyValue(..) => { n.visit_mut_children_with(self); } Prop::Getter(GetterProp { key: PropName::Computed(computed), .. }) | Prop::Setter(SetterProp { key: PropName::Computed(computed), .. }) | Prop::Method(MethodProp { key: PropName::Computed(computed), .. }) => computed.visit_mut_children_with(self), _ => {} } } fn visit_mut_expr(&mut self, n: &mut Expr) { if let Expr::This(ThisExpr { span }) = n { self.found = true; let mut this = self.this.clone(); match &mut this { // for void 0 Expr::Unary(unary_expr) => unary_expr.span = *span, Expr::Ident(ident) => ident.span = *span, Expr::Member(member) => member.span = *span, _ => { unimplemented!(); } } *n = this; } else { n.visit_mut_children_with(self); } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/src/umd.rs
Rust
use anyhow::Context; use swc_atoms::Atom; use swc_common::{ source_map::PURE_SP, sync::Lrc, util::take::Take, Mark, SourceMap, Span, SyntaxContext, DUMMY_SP, }; use swc_ecma_ast::*; use swc_ecma_transforms_base::{feature::FeatureFlag, helper_expr}; use swc_ecma_utils::{ is_valid_prop_ident, private_ident, quote_ident, quote_str, ExprFactory, IsDirective, }; use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith}; use self::config::BuiltConfig; pub use self::config::Config; use crate::{ module_decl_strip::{Export, Link, LinkFlag, LinkItem, LinkSpecifierReducer, ModuleDeclStrip}, module_ref_rewriter::{rewrite_import_bindings, ImportMap}, path::Resolver, top_level_this::top_level_this, util::{ define_es_module, emit_export_stmts, local_name_for_src, use_strict, ImportInterop, VecStmtLike, }, SpanCtx, }; mod config; pub fn umd( cm: Lrc<SourceMap>, resolver: Resolver, unresolved_mark: Mark, config: Config, available_features: FeatureFlag, ) -> impl Pass { visit_mut_pass(Umd { config: config.build(cm.clone()), unresolved_mark, cm, resolver, const_var_kind: if caniuse!(available_features.BlockScoping) { VarDeclKind::Const } else { VarDeclKind::Var }, dep_list: Default::default(), exports: None, }) } pub struct Umd { cm: Lrc<SourceMap>, unresolved_mark: Mark, config: BuiltConfig, resolver: Resolver, const_var_kind: VarDeclKind, dep_list: Vec<(Ident, Atom, SpanCtx)>, exports: Option<Ident>, } impl VisitMut for Umd { noop_visit_mut_type!(fail); fn visit_mut_module(&mut self, module: &mut Module) { let module_items = &mut module.body; let mut stmts: Vec<Stmt> = Vec::with_capacity(module_items.len() + 4); // Collect directives stmts.extend( module_items .iter_mut() .take_while(|i| i.directive_continue()) .map(|i| i.take()) .map(ModuleItem::expect_stmt), ); // "use strict"; if self.config.config.strict_mode && !stmts.has_use_strict() { stmts.push(use_strict()); } if !self.config.config.allow_top_level_this { top_level_this(module_items, *Expr::undefined(DUMMY_SP)); } let import_interop = self.config.config.import_interop(); let mut strip = ModuleDeclStrip::new(self.const_var_kind); module_items.visit_mut_with(&mut strip); let ModuleDeclStrip { link, export, export_assign, has_module_decl, .. } = strip; let is_export_assign = export_assign.is_some(); if has_module_decl && !import_interop.is_none() && !is_export_assign { stmts.push(define_es_module(self.exports())) } let mut import_map = Default::default(); stmts.extend( self.handle_import_export(&mut import_map, link, export, is_export_assign) .map(From::from), ); stmts.extend(module_items.take().into_iter().filter_map(|i| match i { ModuleItem::Stmt(stmt) if !stmt.is_empty() => Some(stmt), _ => None, })); if let Some(export_assign) = export_assign { let return_stmt = ReturnStmt { span: DUMMY_SP, arg: Some(export_assign), }; stmts.push(return_stmt.into()) } rewrite_import_bindings(&mut stmts, import_map, Default::default()); // ==================== // Emit // ==================== let (adapter_fn_expr, factory_params) = self.adapter(module.span, is_export_assign); let factory_fn_expr: Expr = Function { params: factory_params, decorators: Default::default(), span: DUMMY_SP, body: Some(BlockStmt { stmts, ..Default::default() }), is_generator: false, is_async: false, ..Default::default() } .into(); *module_items = vec![adapter_fn_expr .as_call( DUMMY_SP, vec![ ThisExpr { span: DUMMY_SP }.as_arg(), factory_fn_expr.as_arg(), ], ) .into_stmt() .into()] } } impl Umd { fn handle_import_export( &mut self, import_map: &mut ImportMap, link: Link, export: Export, is_export_assign: bool, ) -> impl Iterator<Item = Stmt> { let import_interop = self.config.config.import_interop(); let mut stmts = Vec::with_capacity(link.len()); let mut export_obj_prop_list = export.into_iter().collect(); link.into_iter().for_each( |(src, LinkItem(src_span, link_specifier_set, mut link_flag))| { let is_node_default = !link_flag.has_named() && import_interop.is_node(); if import_interop.is_none() { link_flag -= LinkFlag::NAMESPACE; } let need_re_export = link_flag.export_star(); let need_interop = link_flag.interop(); let need_new_var = link_flag.need_raw_import(); let mod_ident = private_ident!(local_name_for_src(&src)); let new_var_ident = if need_new_var { private_ident!(local_name_for_src(&src)) } else { mod_ident.clone() }; self.dep_list.push((mod_ident.clone(), src, src_span)); link_specifier_set.reduce( import_map, &mut export_obj_prop_list, &new_var_ident, &Some(mod_ident.clone()), &mut false, is_node_default, ); // _export_star(mod, exports); let mut import_expr: Expr = if need_re_export { helper_expr!(export_star).as_call( DUMMY_SP, vec![mod_ident.clone().as_arg(), self.exports().as_arg()], ) } else { mod_ident.clone().into() }; // _introp(mod); if need_interop { import_expr = match import_interop { ImportInterop::Swc if link_flag.interop() => if link_flag.namespace() { helper_expr!(interop_require_wildcard) } else { helper_expr!(interop_require_default) } .as_call(PURE_SP, vec![import_expr.as_arg()]), ImportInterop::Node if link_flag.namespace() => { helper_expr!(interop_require_wildcard) .as_call(PURE_SP, vec![import_expr.as_arg(), true.as_arg()]) } _ => import_expr, } }; // mod = _introp(mod); // var mod1 = _introp(mod); if need_new_var { let stmt: Stmt = import_expr .into_var_decl(self.const_var_kind, new_var_ident.into()) .into(); stmts.push(stmt) } else if need_interop { let stmt = import_expr .make_assign_to(op!("="), mod_ident.into()) .into_stmt(); stmts.push(stmt); } else if need_re_export { stmts.push(import_expr.into_stmt()); } }, ); let mut export_stmts = Default::default(); if !export_obj_prop_list.is_empty() && !is_export_assign { export_obj_prop_list.sort_by_cached_key(|(key, ..)| key.clone()); let exports = self.exports(); export_stmts = emit_export_stmts(exports, export_obj_prop_list); } export_stmts.into_iter().chain(stmts) } fn exports(&mut self) -> Ident { self.exports .get_or_insert_with(|| private_ident!("exports")) .clone() } /// - Without `export =` /// ```javascript /// (function (global, factory) { /// if (typeof module === "object" && typeof module.exports === "object") { /// factory(exports, require("mod")); /// } else if (typeof define === "function" && define.amd) { /// define(["exports", "mod"], factory); /// } else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) { /// factory((global.lib = {}), global.mod); /// } /// })(this, function (exports, mod) { /// ... /// }); /// ``` /// - With `export =` /// ```javascript /// (function (global, factory) { /// if (typeof module === "object" && typeof module.exports === "object") { /// module.exports = factory(require("mod")); /// } else if (typeof define === "function" && define.amd) { /// define(["mod"], factory); /// } else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) { /// global.lib = factory(global.mod); /// } /// })(this, function (mod) { /// ... /// }); /// ``` /// Return: adapter expr and factory params fn adapter(&mut self, module_span: Span, is_export_assign: bool) -> (FnExpr, Vec<Param>) { macro_rules! js_typeof { ($test:expr =>! $type:expr) => { Expr::Unary(UnaryExpr { span: DUMMY_SP, op: op!("typeof"), arg: Box::new(Expr::from($test)), }) .make_bin(op!("!=="), quote_str!($type)) }; ($test:expr => $type:expr) => { Expr::Unary(UnaryExpr { span: DUMMY_SP, op: op!("typeof"), arg: Box::new(Expr::from($test)), }) .make_bin(op!("==="), quote_str!($type)) }; } // define unresolved ref let module = quote_ident!( SyntaxContext::empty().apply_mark(self.unresolved_mark), "module" ); let require = quote_ident!( SyntaxContext::empty().apply_mark(self.unresolved_mark), "require" ); let define = quote_ident!( SyntaxContext::empty().apply_mark(self.unresolved_mark), "define" ); let global_this = quote_ident!( SyntaxContext::empty().apply_mark(self.unresolved_mark), "globalThis" ); let js_self = quote_ident!( SyntaxContext::empty().apply_mark(self.unresolved_mark), "self" ); // adapter arguments let global = private_ident!("global"); let factory = private_ident!("factory"); let module_exports = module.clone().make_member(quote_ident!("exports")); let define_amd = define.clone().make_member(quote_ident!("amd")); let mut cjs_args = Vec::new(); let mut amd_dep_list = Vec::new(); let mut browser_args = Vec::new(); let mut factory_params = Vec::new(); if !is_export_assign && self.exports.is_some() { let filename = self.cm.span_to_filename(module_span); let exported_name = self.config.determine_export_name(filename); let global_lib = global.clone().make_member(exported_name.into()); cjs_args.push(quote_ident!("exports").as_arg()); amd_dep_list.push(Some(quote_str!("exports").as_arg())); browser_args.push( ObjectLit { span: DUMMY_SP, props: Default::default(), } .make_assign_to(op!("="), global_lib.into()) .as_arg(), ); factory_params.push(self.exports().into()); } self.dep_list .take() .into_iter() .for_each(|(ident, src_path, src_span)| { let src_path = match &self.resolver { Resolver::Real { resolver, base } => resolver .resolve_import(base, &src_path) .with_context(|| format!("failed to resolve `{}`", src_path)) .unwrap(), Resolver::Default => src_path, }; cjs_args.push( require .clone() .as_call( DUMMY_SP, vec![quote_str!(src_span.0, src_path.clone()).as_arg()], ) .as_arg(), ); amd_dep_list.push(Some(quote_str!(src_span.0, src_path.clone()).as_arg())); let global_dep = { let dep_name = self.config.global_name(&src_path); let global = global.clone(); if is_valid_prop_ident(&dep_name) { global.make_member(quote_ident!(dep_name)) } else { global.computed_member(quote_str!(dep_name)) } }; browser_args.push(global_dep.as_arg()); factory_params.push(ident.into()); }); let cjs_if_test = js_typeof!(module => "object") .make_bin(op!("&&"), js_typeof!(module_exports.clone() => "object")); let mut cjs_if_body = factory.clone().as_call(DUMMY_SP, cjs_args); if is_export_assign { cjs_if_body = cjs_if_body.make_assign_to(op!("="), module_exports.clone().into()); } let amd_if_test = js_typeof!(define.clone() => "function").make_bin(op!("&&"), define_amd); let amd_if_body = define.as_call( DUMMY_SP, vec![ ArrayLit { span: DUMMY_SP, elems: amd_dep_list, } .as_arg(), factory.clone().as_arg(), ], ); let browser_if_test = CondExpr { span: DUMMY_SP, test: Box::new(js_typeof!(global_this.clone() =>! "undefined")), cons: Box::new(global_this.into()), alt: Box::new(global.clone().make_bin(op!("||"), js_self)), } .make_assign_to(op!("="), global.clone().into()); let mut browser_if_body = factory.clone().as_call(DUMMY_SP, browser_args); if is_export_assign { browser_if_body = browser_if_body.make_assign_to(op!("="), module_exports.into()); } let adapter_body = BlockStmt { span: DUMMY_SP, stmts: vec![IfStmt { span: DUMMY_SP, test: Box::new(cjs_if_test), cons: Box::new(cjs_if_body.into_stmt()), alt: Some(Box::new( IfStmt { span: DUMMY_SP, test: Box::new(amd_if_test), cons: Box::new(amd_if_body.into_stmt()), alt: Some(Box::new( IfStmt { span: DUMMY_SP, test: Box::new(browser_if_test), cons: Box::new(browser_if_body.into_stmt()), alt: None, } .into(), )), } .into(), )), } .into()], ..Default::default() }; let adapter_fn_expr = Function { params: vec![global.into(), factory.into()], span: DUMMY_SP, body: Some(adapter_body), is_generator: false, is_async: false, ..Default::default() } .into(); (adapter_fn_expr, factory_params) } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/src/umd/config.rs
Rust
use std::collections::HashMap; use inflector::Inflector; use serde::{Deserialize, Serialize}; use swc_atoms::Atom; use swc_common::{errors::HANDLER, sync::Lrc, FileName, SourceMap}; use swc_ecma_ast::{Expr, Ident}; use swc_ecma_parser::{parse_file_as_expr, Syntax}; use swc_ecma_utils::quote_ident; use super::super::util; #[derive(Debug, Default, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct Config { #[serde(default)] pub globals: HashMap<String, String>, #[serde(flatten, default)] pub config: util::Config, } impl Config { pub(super) fn build(self, cm: Lrc<SourceMap>) -> BuiltConfig { BuiltConfig { config: self.config, globals: self .globals .into_iter() .map(|(k, v)| { let parse = |s| { let fm = cm.new_source_file( FileName::Internal(format!("<umd-config-{}.js>", s)).into(), s, ); parse_file_as_expr( &fm, Syntax::default(), Default::default(), None, &mut Vec::new(), ) .map_err(|e| { if HANDLER.is_set() { HANDLER.with(|h| e.into_diagnostic(h).emit()) } }) .unwrap() }; (k, parse(v)) }) .collect(), } } } #[derive(Clone)] pub(super) struct BuiltConfig { #[allow(dead_code)] pub globals: HashMap<String, Box<Expr>>, pub config: util::Config, } impl BuiltConfig { pub fn global_name(&self, src: &str) -> Atom { if !src.contains('/') { return src.to_camel_case().into(); } src.split('/').last().unwrap().to_camel_case().into() } pub fn determine_export_name(&self, filename: Lrc<FileName>) -> Ident { match &*filename { FileName::Real(ref path) => { let s = match path.file_stem() { Some(stem) => self.global_name(&stem.to_string_lossy()), None => self.global_name(&path.display().to_string()), }; quote_ident!(s).into() } FileName::Custom(s) => { let s = self.global_name(s); quote_ident!(s).into() } _ => unimplemented!("determine_export_name({:?})", filename), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/src/util.rs
Rust
use is_macro::Is; use serde::{Deserialize, Serialize}; use swc_atoms::Atom; use swc_cached::regex::CachedRegex; use swc_common::DUMMY_SP; use swc_ecma_ast::*; use swc_ecma_utils::{ is_valid_prop_ident, member_expr, private_ident, quote_ident, quote_str, ExprFactory, FunctionFactory, IsDirective, }; use crate::{ module_decl_strip::{ExportItem, ExportKV}, SpanCtx, }; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct Config { #[serde(default)] pub allow_top_level_this: bool, #[serde(default)] pub strict: bool, #[serde(default = "default_strict_mode")] pub strict_mode: bool, #[serde(default)] pub lazy: Lazy, #[serde(default)] pub import_interop: Option<ImportInterop>, /// Emits `cjs-module-lexer` annotation /// `cjs-module-lexer` is used in Node.js core for detecting the named /// exports available when importing a CJS module into ESM. /// swc will emit `cjs-module-lexer` detectable annotation with this option /// enabled. /// /// Defaults to `true` if import_interop is Node, else `false` #[serde(default)] pub export_interop_annotation: Option<bool>, #[serde(default)] /// Note: deprecated pub no_interop: bool, #[serde(default)] pub ignore_dynamic: bool, #[serde(default)] pub preserve_import_meta: bool, #[serde(default)] pub resolve_fully: bool, #[serde(default = "Config::default_js_ext")] pub out_file_extension: String, } impl Config { pub fn default_js_ext() -> String { "js".to_string() } } impl Default for Config { fn default() -> Self { Config { allow_top_level_this: false, strict: false, strict_mode: default_strict_mode(), lazy: Lazy::default(), import_interop: None, export_interop_annotation: None, no_interop: false, ignore_dynamic: false, preserve_import_meta: false, resolve_fully: false, out_file_extension: "js".to_string(), } } } const fn default_strict_mode() -> bool { true } #[derive(Debug, Clone, Copy, PartialEq, Eq, Is, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum ImportInterop { #[serde(alias = "babel")] Swc, Node, None, } impl From<bool> for ImportInterop { fn from(no_interop: bool) -> Self { if no_interop { ImportInterop::None } else { ImportInterop::Swc } } } impl Config { #[inline(always)] pub fn import_interop(&self) -> ImportInterop { self.import_interop .unwrap_or_else(|| self.no_interop.into()) } #[inline(always)] pub fn export_interop_annotation(&self) -> bool { self.export_interop_annotation .unwrap_or_else(|| self.import_interop == Some(ImportInterop::Node)) } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct LazyObjectConfig { pub patterns: Vec<CachedRegex>, } impl LazyObjectConfig { pub fn is_lazy(&self, src: &Atom) -> bool { self.patterns.iter().any(|pat| pat.is_match(src)) } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged, deny_unknown_fields, rename_all = "camelCase")] pub enum Lazy { Bool(bool), List(Vec<Atom>), Object(LazyObjectConfig), } impl Lazy { pub fn is_lazy(&self, src: &Atom) -> bool { match *self { Lazy::Bool(false) => false, Lazy::Bool(true) => !src.starts_with('.'), Lazy::List(ref srcs) => srcs.contains(src), Lazy::Object(ref object) => object.is_lazy(src), } } } impl Default for Lazy { fn default() -> Self { Lazy::Bool(false) } } pub(super) fn local_name_for_src(src: &Atom) -> Atom { let src = src.split('/').last().unwrap(); let src = src .strip_suffix(".js") .or_else(|| src.strip_suffix(".mjs")) .unwrap_or(src); let id = match Ident::verify_symbol(src) { Ok(_) => src.into(), Err(err) => err, }; if !id.starts_with('_') { format!("_{}", id).into() } else { id.into() } } /// Creates /// ///```js /// /// Object.defineProperty(target, prop_name, { /// ...props /// }); /// ``` pub(super) fn object_define_property( target: ExprOrSpread, prop_name: ExprOrSpread, descriptor: ExprOrSpread, ) -> Expr { member_expr!(Default::default(), DUMMY_SP, Object.defineProperty) .as_call(DUMMY_SP, vec![target, prop_name, descriptor]) } /// Creates /// ///```js /// /// Object.defineProperty(exports, '__esModule', { /// value: true /// }); /// ``` pub(super) fn define_es_module(exports: Ident) -> Stmt { object_define_property( exports.as_arg(), quote_str!("__esModule").as_arg(), ObjectLit { span: DUMMY_SP, props: vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: PropName::Ident(quote_ident!("value")), value: true.into(), })))], } .as_arg(), ) .into_stmt() } pub(super) trait VecStmtLike { type StmtLike: IsDirective; fn as_ref(&self) -> &[Self::StmtLike]; fn has_use_strict(&self) -> bool { self.as_ref() .iter() .take_while(|s| s.directive_continue()) .any(IsDirective::is_use_strict) } } impl VecStmtLike for [ModuleItem] { type StmtLike = ModuleItem; fn as_ref(&self) -> &[Self::StmtLike] { self } } impl VecStmtLike for [Stmt] { type StmtLike = Stmt; fn as_ref(&self) -> &[Self::StmtLike] { self } } pub(super) fn use_strict() -> Stmt { Lit::Str(quote_str!("use strict")).into_stmt() } pub(crate) fn object_define_enumerable( target: ExprOrSpread, prop_name: ExprOrSpread, prop: PropOrSpread, ) -> Expr { object_define_property( target, prop_name, ObjectLit { span: DUMMY_SP, props: vec![ PropOrSpread::Prop(Box::new( KeyValueProp { key: quote_ident!("enumerable").into(), value: Box::new(true.into()), } .into(), )), prop, ], } .as_arg(), ) } #[macro_export] macro_rules! caniuse { ($feature_set:ident . $feature:ident) => { $feature_set.intersects(swc_ecma_transforms_base::feature::FeatureFlag::$feature) }; } /// ```javascript /// function _esmExport(target, all) { /// for (var name in all)Object.defineProperty(target, name, { get: all[name], enumerable: true }); /// } /// ``` pub(crate) fn esm_export() -> Function { let target = private_ident!("target"); let all = private_ident!("all"); let name = private_ident!("name"); let getter = KeyValueProp { key: quote_ident!("get").into(), value: all.clone().computed_member(name.clone()).into(), }; let body = object_define_enumerable( target.clone().as_arg(), name.clone().as_arg(), PropOrSpread::Prop(Box::new(Prop::KeyValue(getter))), ) .into_stmt(); let for_in_stmt: Stmt = ForInStmt { span: DUMMY_SP, left: VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, declare: false, decls: vec![VarDeclarator { span: DUMMY_SP, name: name.into(), init: None, definite: false, }], ..Default::default() } .into(), right: Box::new(all.clone().into()), body: Box::new(body), } .into(); Function { params: vec![target.into(), all.into()], decorators: Default::default(), span: DUMMY_SP, body: Some(BlockStmt { stmts: vec![for_in_stmt], ..Default::default() }), is_generator: false, is_async: false, ..Default::default() } } pub(crate) fn emit_export_stmts(exports: Ident, mut prop_list: Vec<ExportKV>) -> Vec<Stmt> { match prop_list.len() { 0 | 1 => prop_list .pop() .map(|(export_name, export_item)| { object_define_enumerable( exports.as_arg(), quote_str!(export_item.export_name_span().0, export_name).as_arg(), prop_function(( "get".into(), ExportItem::new(Default::default(), export_item.into_local_ident()), )) .into(), ) .into_stmt() }) .into_iter() .collect(), _ => { let props = prop_list .into_iter() .map(prop_function) .map(From::from) .collect(); let obj_lit = ObjectLit { span: DUMMY_SP, props, }; let esm_export_ident = private_ident!("_export"); vec![ Stmt::Decl(Decl::Fn( esm_export().into_fn_decl(esm_export_ident.clone()), )), esm_export_ident .as_call(DUMMY_SP, vec![exports.as_arg(), obj_lit.as_arg()]) .into_stmt(), ] } } } pub(crate) fn prop_name(key: &str, (span, _): SpanCtx) -> IdentOrStr { if is_valid_prop_ident(key) { IdentOrStr::Ident(IdentName::new(key.into(), span)) } else { IdentOrStr::Str(quote_str!(span, key)) } } pub(crate) enum IdentOrStr { Ident(IdentName), Str(Str), } impl From<IdentOrStr> for PropName { fn from(val: IdentOrStr) -> Self { match val { IdentOrStr::Ident(i) => Self::Ident(i), IdentOrStr::Str(s) => Self::Str(s), } } } impl From<IdentOrStr> for MemberProp { fn from(val: IdentOrStr) -> Self { match val { IdentOrStr::Ident(i) => Self::Ident(i), IdentOrStr::Str(s) => Self::Computed(ComputedPropName { span: DUMMY_SP, expr: s.into(), }), } } } /// ```javascript /// { /// key: function() { /// return expr; /// }, /// } /// ``` pub(crate) fn prop_function((key, export_item): ExportKV) -> Prop { let key = prop_name(&key, export_item.export_name_span()).into(); KeyValueProp { key, value: Box::new( export_item .into_local_ident() .into_lazy_fn(Default::default()) .into_fn_expr(None) .into(), ), } .into() }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/__swc_snapshots__/tests/amd.rs/for_of_as_array_for_of_import_amd.js
JavaScript
define([ "require", "exports", "foo" ], function(require, exports, _foo) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); for(let _i = 0; _i < _foo.array.length; _i++){ const elm = _foo.array[_i]; console.log(elm); } });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/__swc_snapshots__/tests/common_js.rs/for_of_as_array_for_of_import_commonjs.js
JavaScript
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const _foo = require("foo"); for(let _i = 0; _i < _foo.array.length; _i++){ const elm = _foo.array[_i]; console.log(elm); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/__swc_snapshots__/tests/system_js.rs/allow_continuous_assignment.js
JavaScript
System.register([], function(_export, _context) { "use strict"; var e; return { setters: [], execute: function() { e = {}; e.a = e.b = e.c = e.d = e.e = e.f = e.g = e.h = e.i = e.j = e.k = e.l = e.m = e.n = e.o = e.p = e.q = e.r = e.s = e.t = e.u = e.v = e.w = e.x = e.y = e.z = e.A = e.B = e.C = e.D = e.E = e.F = e.G = e.H = e.I = e.J = e.K = e.L = e.M = e.N = e.O = e.P = e.Q = e.R = e.S = void 0; } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/__swc_snapshots__/tests/system_js.rs/allow_top_level_this_false.js
JavaScript
System.register([], function(_export, _context) { "use strict"; var v; function a() { function d() {} var b = this; } return { setters: [], execute: function() { _export("v", v = void 0); } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/__swc_snapshots__/tests/system_js.rs/allow_top_level_this_true.js
JavaScript
System.register([], function(_export, _context) { "use strict"; var v; return { setters: [], execute: function() { _export("v", v = this); } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/__swc_snapshots__/tests/system_js.rs/iife.js
JavaScript
System.register([], function(_export, _context) { "use strict"; return { setters: [], execute: function() { (function(a) { this.foo = a; })(void 0); } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/__swc_snapshots__/tests/system_js.rs/imports.js
JavaScript
System.register([], function(_export, _context) { "use strict"; return { setters: [], execute: async function() { _context.meta.url; _context.meta.fn(); await _context.import('./test2'); } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/__swc_snapshots__/tests/system_js.rs/top_level_this_false_class.js
JavaScript
System.register([], function(_export, _context) { "use strict"; var A, a; return { setters: [], execute: function() { a = void 0; A = class A { constructor(){ this.a = 1; } test() { this.a = 2; } }; } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/amd.rs
Rust
use std::{fs::File, path::PathBuf, rc::Rc}; use swc_common::{comments::SingleThreadedComments, Mark}; use swc_ecma_ast::Pass; use swc_ecma_parser::{Syntax, TsSyntax}; use swc_ecma_transforms_base::{feature::FeatureFlag, resolver}; use swc_ecma_transforms_compat::es2015::for_of; use swc_ecma_transforms_module::amd::{self, amd}; use swc_ecma_transforms_testing::{test, test_fixture, FixtureTestConfig}; use swc_ecma_transforms_typescript::typescript; fn syntax() -> Syntax { Default::default() } fn ts_syntax() -> Syntax { Syntax::Typescript(TsSyntax::default()) } fn tr(config: amd::Config, is_ts: bool, comments: Rc<SingleThreadedComments>) -> impl Pass { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); let avalible_set = FeatureFlag::all(); ( resolver(unresolved_mark, top_level_mark, is_ts), typescript::typescript(Default::default(), unresolved_mark, top_level_mark), amd( Default::default(), unresolved_mark, config, avalible_set, Some(comments), ), ) } #[testing::fixture("tests/fixture/common/**/input.js")] #[testing::fixture("tests/fixture/common/**/input.ts")] #[testing::fixture("tests/fixture/common/**/input.cts")] fn esm_to_amd(input: PathBuf) { let is_ts = input .file_name() .map(|x| x.to_string_lossy()) .map(|x| x.ends_with(".ts") || x.ends_with(".mts") || x.ends_with(".cts")) .unwrap_or_default(); let dir = input.parent().unwrap().to_path_buf(); let output = dir .join("output.amd.js") .with_extension(if is_ts { "ts" } else { "js" }); let amd_config_path = dir.join("module.amd.json"); let config_path = dir.join("module.json"); let config: amd::Config = match File::open(amd_config_path).or_else(|_| File::open(config_path)) { Ok(file) => serde_json::from_reader(file).unwrap(), Err(..) => Default::default(), }; test_fixture( if is_ts { ts_syntax() } else { syntax() }, &|t| tr(config.clone(), is_ts, t.comments.clone()), &input, &output, FixtureTestConfig { module: Some(true), ..Default::default() }, ); } test!( module, syntax(), |t| ( for_of(for_of::Config { assume_array: true, ..Default::default() }), tr(Default::default(), false, t.comments.clone()) ), for_of_as_array_for_of_import_amd, r#" import { array } from "foo"; for (const elm of array) { console.log(elm); } "# );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/common_js.rs
Rust
use std::{fs::File, path::PathBuf}; use swc_common::Mark; use swc_ecma_ast::Pass; use swc_ecma_parser::{Syntax, TsSyntax}; use swc_ecma_transforms_base::{feature::FeatureFlag, resolver}; use swc_ecma_transforms_compat::es2015::for_of; use swc_ecma_transforms_module::common_js::{self, common_js}; use swc_ecma_transforms_testing::{test, test_fixture, FixtureTestConfig}; use swc_ecma_transforms_typescript::typescript; fn syntax() -> Syntax { Default::default() } fn ts_syntax() -> Syntax { Syntax::Typescript(TsSyntax::default()) } fn tr(config: common_js::Config, is_ts: bool) -> impl Pass { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); let available_set = FeatureFlag::all(); ( resolver(unresolved_mark, top_level_mark, is_ts), typescript::typescript(Default::default(), unresolved_mark, top_level_mark), common_js(Default::default(), unresolved_mark, config, available_set), ) } #[testing::fixture("tests/fixture/common/**/input.js")] #[testing::fixture("tests/fixture/common/**/input.ts")] #[testing::fixture("tests/fixture/common/**/input.cts")] fn esm_to_cjs(input: PathBuf) { let is_ts = input .file_name() .map(|x| x.to_string_lossy()) .map(|x| x.ends_with(".ts") || x.ends_with(".mts") || x.ends_with(".cts")) .unwrap_or_default(); let dir = input.parent().unwrap().to_path_buf(); let output = dir .join("output.js") .with_extension(if is_ts { "cts" } else { "cjs" }); let config_path = dir.join("module.json"); let config: common_js::Config = match File::open(config_path) { Ok(file) => serde_json::from_reader(file).unwrap(), Err(..) => Default::default(), }; test_fixture( if is_ts { ts_syntax() } else { syntax() }, &|_| tr(config.clone(), is_ts), &input, &output, FixtureTestConfig { sourcemap: false, module: Some(true), ..Default::default() }, ); } test!( module, syntax(), |_| ( for_of(for_of::Config { assume_array: true, ..Default::default() }), tr(Default::default(), false) ), for_of_as_array_for_of_import_commonjs, r#" import { array } from "foo"; for (const elm of array) { console.log(elm); } "# );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture-manual/issue-4730/input/src/index.js
JavaScript
import { displayB } from "@print/b"; async function display() { const displayA = await import("@print/a").then((c) => c.displayA); console.log(displayA()); console.log(displayB()); } display();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture-manual/issue-4730/output/index.js
JavaScript
import { displayB } from "../packages/b/src/index.js"; async function display() { const displayA = await import("../packages/a/src/index.js").then((c)=>c.displayA); console.log(displayA()); console.log(displayB()); } display();
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/allow-top-level-this/false/input.js
JavaScript
export var v = this;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/allow-top-level-this/false/output.amd.js
JavaScript
define([ "require", "exports" ], function(require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "v", { enumerable: true, get: function() { return v; } }); var v = void 0; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/allow-top-level-this/false/output.cjs
JavaScript
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "v", { enumerable: true, get: function() { return v; } }); var v = void 0;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/allow-top-level-this/false/output.umd.js
JavaScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(exports); else if (typeof define === "function" && define.amd) define([ "exports" ], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(global.input = {}); })(this, function(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "v", { enumerable: true, get: function() { return v; } }); var v = void 0; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/allow-top-level-this/true/input.js
JavaScript
export var v = this;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/allow-top-level-this/true/output.amd.js
JavaScript
define([ "require", "exports" ], function(require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "v", { enumerable: true, get: function() { return v; } }); var v = this; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/allow-top-level-this/true/output.cjs
JavaScript
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "v", { enumerable: true, get: function() { return v; } }); var v = this;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/allow-top-level-this/true/output.umd.js
JavaScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(exports); else if (typeof define === "function" && define.amd) define([ "exports" ], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(global.input = {}); })(this, function(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "v", { enumerable: true, get: function() { return v; } }); var v = this; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/amd-triple-slash-directive/1/input.ts
TypeScript
///<amd-module name='NamedModule'/> class Foo { x: number; constructor() { this.x = 5; } } export = Foo;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/amd-triple-slash-directive/1/output.amd.ts
TypeScript
///<amd-module name='NamedModule'/> define("NamedModule", [ "require" ], function(require) { "use strict"; class Foo { x; constructor(){ this.x = 5; } } module.exports = Foo; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/amd-triple-slash-directive/1/output.umd.ts
TypeScript
///<amd-module name='NamedModule'/> (function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(); else if (typeof define === "function" && define.amd) define([], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(); })(this, function() { "use strict"; class Foo { x; constructor(){ this.x = 5; } } module.exports = Foo; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/amd-triple-slash-directive/2/input.ts
TypeScript
///<amd-module name='FirstModuleName'/> ///<amd-module name='SecondModuleName'/> class Foo { x: number; constructor() { this.x = 5; } } export = Foo;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/amd-triple-slash-directive/2/output.amd.ts
TypeScript
///<amd-module name='FirstModuleName'/> ///<amd-module name='SecondModuleName'/> define("SecondModuleName", [ "require" ], function(require) { "use strict"; class Foo { x; constructor(){ this.x = 5; } } module.exports = Foo; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/amd-triple-slash-directive/2/output.umd.ts
TypeScript
///<amd-module name='FirstModuleName'/> ///<amd-module name='SecondModuleName'/> (function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(); else if (typeof define === "function" && define.amd) define([], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(); })(this, function() { "use strict"; class Foo { x; constructor(){ this.x = 5; } } module.exports = Foo; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/amd-triple-slash-directive/3/input.ts
TypeScript
///<AmD-moDulE nAme='NamedModule'/> class Foo { x: number; constructor() { this.x = 5; } } export = Foo;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/amd-triple-slash-directive/3/output.amd.ts
TypeScript
///<AmD-moDulE nAme='NamedModule'/> define("NamedModule", [ "require" ], function(require) { "use strict"; class Foo { x; constructor(){ this.x = 5; } } module.exports = Foo; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/amd-triple-slash-directive/3/output.umd.ts
TypeScript
///<AmD-moDulE nAme='NamedModule'/> (function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(); else if (typeof define === "function" && define.amd) define([], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(); })(this, function() { "use strict"; class Foo { x; constructor(){ this.x = 5; } } module.exports = Foo; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/amd-triple-slash-directive/4/input.ts
TypeScript
/*/<amd-module name='should-ignore'/> */ class Foo { x: number; constructor() { this.x = 5; } } export = Foo;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/amd-triple-slash-directive/4/output.amd.ts
TypeScript
/*/<amd-module name='should-ignore'/> */ define([ "require" ], function(require) { "use strict"; class Foo { x; constructor(){ this.x = 5; } } module.exports = Foo; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/amd-triple-slash-directive/4/output.umd.ts
TypeScript
/*/<amd-module name='should-ignore'/> */ (function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(); else if (typeof define === "function" && define.amd) define([], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(); })(this, function() { "use strict"; class Foo { x; constructor(){ this.x = 5; } } module.exports = Foo; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/live-rewrite/input.js
JavaScript
import { test1, test2, test3, test4, test5, test6, test7, test8, test9, } from "anywhere"; class Example { #test1 = test1; test2 = test2; #test3() { return test3; } test4() { return test4; } get #test5() { return test5; } get test6() { return test6; } #test7 = this.#test1; #test8() { return this.#test3(); } get #test9() { return this.#test5(); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/live-rewrite/output.amd.js
JavaScript
define([ "require", "exports", "anywhere" ], function(require, exports, _anywhere) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class Example { #test1 = _anywhere.test1; test2 = _anywhere.test2; #test3() { return _anywhere.test3; } test4() { return _anywhere.test4; } get #test5() { return _anywhere.test5; } get test6() { return _anywhere.test6; } #test7 = this.#test1; #test8() { return this.#test3(); } get #test9() { return this.#test5(); } } });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/live-rewrite/output.cjs
JavaScript
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const _anywhere = require("anywhere"); class Example { #test1 = _anywhere.test1; test2 = _anywhere.test2; #test3() { return _anywhere.test3; } test4() { return _anywhere.test4; } get #test5() { return _anywhere.test5; } get test6() { return _anywhere.test6; } #test7 = this.#test1; #test8() { return this.#test3(); } get #test9() { return this.#test5(); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/live-rewrite/output.umd.js
JavaScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(exports, require("anywhere")); else if (typeof define === "function" && define.amd) define([ "exports", "anywhere" ], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(global.input = {}, global.anywhere); })(this, function(exports, _anywhere) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class Example { #test1 = _anywhere.test1; test2 = _anywhere.test2; #test3() { return _anywhere.test3; } test4() { return _anywhere.test4; } get #test5() { return _anywhere.test5; } get test6() { return _anywhere.test6; } #test7 = this.#test1; #test8() { return this.#test3(); } get #test9() { return this.#test5(); } } });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/private-method/input.js
JavaScript
class Example { #method() { console.log(this); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/private-method/output.amd.js
JavaScript
define([ "require" ], function(require) { "use strict"; class Example { #method() { console.log(this); } } });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/private-method/output.cjs
JavaScript
"use strict"; class Example { #method() { console.log(this); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/private-method/output.umd.js
JavaScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(); else if (typeof define === "function" && define.amd) define([], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(); })(this, function() { "use strict"; class Example { #method() { console.log(this); } } });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/private/input.js
JavaScript
class Example { #property = this; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/private/output.amd.js
JavaScript
define([ "require" ], function(require) { "use strict"; class Example { #property = this; } });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/private/output.cjs
JavaScript
"use strict"; class Example { #property = this; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/private/output.umd.js
JavaScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(); else if (typeof define === "function" && define.amd) define([], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(); })(this, function() { "use strict"; class Example { #property = this; } });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/public/input.js
JavaScript
class Example { property = this; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/public/output.amd.js
JavaScript
define([ "require" ], function(require) { "use strict"; class Example { property = this; } });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/public/output.cjs
JavaScript
"use strict"; class Example { property = this; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-properties/public/output.umd.js
JavaScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(); else if (typeof define === "function" && define.amd) define([], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(); })(this, function() { "use strict"; class Example { property = this; } });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-property/input.js
JavaScript
import { a } from "./files_with_swcrc/simple"; export class Foo { static prop = a; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-property/output.amd.js
JavaScript
define([ "require", "exports", "./files_with_swcrc/simple" ], function(require, exports, _simple) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "Foo", { enumerable: true, get: function() { return Foo; } }); class Foo { static prop = _simple.a; } });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-property/output.cjs
JavaScript
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "Foo", { enumerable: true, get: function() { return Foo; } }); const _simple = require("./files_with_swcrc/simple"); class Foo { static prop = _simple.a; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/class-property/output.umd.js
JavaScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(exports, require("./files_with_swcrc/simple")); else if (typeof define === "function" && define.amd) define([ "exports", "./files_with_swcrc/simple" ], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(global.input = {}, global.simple); })(this, function(exports, _simple) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "Foo", { enumerable: true, get: function() { return Foo; } }); class Foo { static prop = _simple.a; } });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/cts-import-export/export-assign/output.amd.ts
TypeScript
define([ "require" ], function(require) { "use strict"; const foo = require("foo"); module.exports = foo; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/cts-import-export/export-assign/output.umd.ts
TypeScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(); else if (typeof define === "function" && define.amd) define([], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(); })(this, function() { "use strict"; const foo = require("foo"); module.exports = foo; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/cts-import-export/export-import/output.amd.ts
TypeScript
define([ "require" ], function(require) { "use strict"; const foo = exports.foo = require("foo"); });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/cts-import-export/export-import/output.umd.ts
TypeScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(); else if (typeof define === "function" && define.amd) define([], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(); })(this, function() { "use strict"; const foo = exports.foo = require("foo"); });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/cts-import-export/mixed/output.amd.ts
TypeScript
define([ "require", "exports", "foo" ], function(require, exports, _foo) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); _foo = /*#__PURE__*/ _interop_require_default(_foo); const bar = require("foo"); (0, _foo.default)(); bar(); });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/cts-import-export/mixed/output.umd.ts
TypeScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(exports, require("foo")); else if (typeof define === "function" && define.amd) define([ "exports", "foo" ], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(global.input = {}, global.foo); })(this, function(exports, _foo) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); _foo = /*#__PURE__*/ _interop_require_default(_foo); const bar = require("foo"); (0, _foo.default)(); bar(); });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/01/input.js
JavaScript
var foo = 1; export var foo = 2; foo = 3;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/01/output.amd.js
JavaScript
define([ "require", "exports" ], function(require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "foo", { enumerable: true, get: function() { return foo; } }); var foo = 1; var foo = 2; foo = 3; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/01/output.cjs
JavaScript
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "foo", { enumerable: true, get: function() { return foo; } }); var foo = 1; var foo = 2; foo = 3;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/01/output.umd.js
JavaScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(exports); else if (typeof define === "function" && define.amd) define([ "exports" ], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(global.input = {}); })(this, function(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "foo", { enumerable: true, get: function() { return foo; } }); var foo = 1; var foo = 2; foo = 3; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/02/input.js
JavaScript
export const good = { a(bad1) { ((...bad2) => {}); }, };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/02/output.amd.js
JavaScript
define([ "require", "exports" ], function(require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "good", { enumerable: true, get: function() { return good; } }); const good = { a (bad1) { (...bad2)=>{}; } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/02/output.cjs
JavaScript
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "good", { enumerable: true, get: function() { return good; } }); const good = { a (bad1) { (...bad2)=>{}; } };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/02/output.umd.js
JavaScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(exports); else if (typeof define === "function" && define.amd) define([ "exports" ], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(global.input = {}); })(this, function(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "good", { enumerable: true, get: function() { return good; } }); const good = { a (bad1) { (...bad2)=>{}; } }; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/named-define/input.js
JavaScript
import { foo } from "src"; export { foo };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/named-define/output.amd.js
JavaScript
define("moduleId", [ "require", "exports", "src" ], function(require, exports, _src) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "foo", { enumerable: true, get: function() { return _src.foo; } }); });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/named-define/output.cjs
JavaScript
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "foo", { enumerable: true, get: function() { return _src.foo; } }); const _src = require("src");
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/named-define/output.umd.js
JavaScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(exports, require("src")); else if (typeof define === "function" && define.amd) define([ "exports", "src" ], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(global.input = {}, global.src); })(this, function(exports, _src) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "foo", { enumerable: true, get: function() { return _src.foo; } }); });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/non-strict-mode/input.js
JavaScript
export function foo() {}
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/non-strict-mode/output.amd.js
JavaScript
define([ "require", "exports" ], function(require, exports) { Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "foo", { enumerable: true, get: function() { return foo; } }); function foo() {} });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/non-strict-mode/output.cjs
JavaScript
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "foo", { enumerable: true, get: function() { return foo; } }); function foo() {}
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/non-strict-mode/output.umd.js
JavaScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(exports); else if (typeof define === "function" && define.amd) define([ "exports" ], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(global.input = {}); })(this, function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "foo", { enumerable: true, get: function() { return foo; } }); function foo() {} });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/usage/input.js
JavaScript
import React from "react"; window.React = React;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/usage/output.amd.js
JavaScript
define([ "require", "exports", "react" ], function(require, exports, _react) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); _react = /*#__PURE__*/ _interop_require_default(_react); window.React = _react.default; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/usage/output.cjs
JavaScript
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const _react = /*#__PURE__*/ _interop_require_default(require("react")); window.React = _react.default;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/custom/usage/output.umd.js
JavaScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(exports, require("react")); else if (typeof define === "function" && define.amd) define([ "exports", "react" ], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(global.input = {}, global.react); })(this, function(exports, _react) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); _react = /*#__PURE__*/ _interop_require_default(_react); window.React = _react.default; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/disable-strict-mode-strict-mode-false/input.js
JavaScript
import "foo"; import "foo-bar"; import "./directory/foo-bar";
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/disable-strict-mode-strict-mode-false/output.amd.js
JavaScript
define([ "require", "exports", "foo", "foo-bar", "./directory/foo-bar" ], function(require, exports, _foo, _foobar, _foobar1) { Object.defineProperty(exports, "__esModule", { value: true }); });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/disable-strict-mode-strict-mode-false/output.cjs
JavaScript
Object.defineProperty(exports, "__esModule", { value: true }); require("foo"); require("foo-bar"); require("./directory/foo-bar");
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/disable-strict-mode-strict-mode-false/output.umd.js
JavaScript
(function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") factory(exports, require("foo"), require("foo-bar"), require("./directory/foo-bar")); else if (typeof define === "function" && define.amd) define([ "exports", "foo", "foo-bar", "./directory/foo-bar" ], factory); else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(global.input = {}, global.foo, global.fooBar, global.fooBar); })(this, function(exports, _foo, _foobar, _foobar1) { Object.defineProperty(exports, "__esModule", { value: true }); });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/export-interop-annotation/input.js
JavaScript
export function useRouter() {} export default useRouter;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_module/tests/fixture/common/export-interop-annotation/output.amd.js
JavaScript
define([ "require", "exports" ], function(require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _export(target, all) { for(var name in all)Object.defineProperty(target, name, { enumerable: true, get: all[name] }); } _export(exports, { default: function() { return _default; }, useRouter: function() { return useRouter; } }); function useRouter() {} const _default = useRouter; });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University