swc_bundler/bundler/export.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
use indexmap::IndexMap;
use swc_atoms::JsWord;
use swc_common::{collections::ARandomState, FileName, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_utils::find_pat_ids;
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use super::{
load::{Source, Specifier},
Bundler,
};
use crate::{id::Id, load::Load, resolve::Resolve, util::ExportMetadata};
impl<L, R> Bundler<'_, L, R>
where
L: Load,
R: Resolve,
{
/// TODO: Support pattern like
/// export const [a, b] = [1, 2]
pub(super) fn extract_export_info(
&self,
file_name: &FileName,
module: &mut Module,
export_ctxt: SyntaxContext,
) -> RawExports {
self.run(|| {
let mut v = ExportFinder {
info: Default::default(),
file_name,
bundler: self,
export_ctxt,
};
module.visit_mut_with(&mut v);
v.info
})
}
}
#[derive(Debug, Default)]
pub(super) struct RawExports {
/// Key is None if it's exported from the module itself.
pub items: IndexMap<Option<Str>, Vec<Specifier>, ARandomState>,
}
#[derive(Debug, Default)]
pub(crate) struct Exports {
pub items: Vec<Specifier>,
pub reexports: Vec<(Source, Vec<Specifier>)>,
}
struct ExportFinder<'a, 'b, L, R>
where
L: Load,
R: Resolve,
{
info: RawExports,
file_name: &'a FileName,
bundler: &'a Bundler<'b, L, R>,
export_ctxt: SyntaxContext,
}
impl<L, R> ExportFinder<'_, '_, L, R>
where
L: Load,
R: Resolve,
{
/// Returns `(local, export)`.
fn ctxt_for(&self, src: &JsWord) -> Option<(SyntaxContext, SyntaxContext)> {
// Don't apply mark if it's a core module.
if self
.bundler
.config
.external_modules
.iter()
.any(|v| v == src)
{
return None;
}
let path = self.bundler.resolve(self.file_name, src).ok()?;
let (_, local_mark, export_mark) = self.bundler.scope.module_id_gen.gen(&path);
Some((
SyntaxContext::empty().apply_mark(local_mark),
SyntaxContext::empty().apply_mark(export_mark),
))
}
fn mark_as_wrapping_required(&self, src: &JsWord) {
// Don't apply mark if it's a core module.
if self
.bundler
.config
.external_modules
.iter()
.any(|v| v == src)
{
return;
}
let path = self.bundler.resolve(self.file_name, src);
let path = match path {
Ok(v) => v,
_ => return,
};
let (id, _, _) = self.bundler.scope.module_id_gen.gen(&path);
self.bundler.scope.mark_as_wrapping_required(id);
}
}
impl<L, R> VisitMut for ExportFinder<'_, '_, L, R>
where
L: Load,
R: Resolve,
{
noop_visit_mut_type!(fail);
fn visit_mut_module_item(&mut self, item: &mut ModuleItem) {
match item {
// TODO: Optimize pure constants
// ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
// decl: Decl::Var(v),
// ..
// })) if v.kind == VarDeclKind::Const
// && v.decls.iter().all(|v| {
// (match v.name {
// Pat::Ident(..) => true,
// _ => false,
// }) && (match v.init {
// Some(box Expr::Lit(..)) => true,
// _ => false,
// })
// }) =>
// {
// self.info
// .pure_constants
// .extend(v.decls.into_iter().map(|decl| {
// let id = match decl.name {
// Pat::Ident(i) => i.into(),
// _ => unreachable!(),
// };
// let lit = match decl.init {
// Some(box Expr::Lit(l)) => l,
// _ => unreachable!(),
// };
// (id, lit)
// }));
// return ModuleItem::Stmt(Stmt::Empty(EmptyStmt { span: DUMMY_SP }));
// }
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(decl)) => {
let v = self.info.items.entry(None).or_default();
v.push({
let i = match decl.decl {
Decl::Class(ref c) => &c.ident,
Decl::Fn(ref f) => &f.ident,
Decl::Var(ref var) => {
let ids: Vec<Id> = find_pat_ids(&var.decls);
for id in ids {
v.push(Specifier::Specific {
local: id,
alias: None,
});
}
return;
}
Decl::TsEnum(ref e) => &e.id,
Decl::TsInterface(ref i) => &i.id,
Decl::TsTypeAlias(ref a) => &a.id,
_ => unreachable!("Decl in ExportDecl: {:?}", decl.decl),
};
Specifier::Specific {
local: i.into(),
alias: None,
}
});
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(_decl)) => {
self.info
.items
.entry(None)
.or_default()
.push(Specifier::Specific {
local: Id::new("default".into(), SyntaxContext::empty()),
alias: None,
});
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(_expr)) => {
self.info
.items
.entry(None)
.or_default()
.push(Specifier::Specific {
local: Id::new("default".into(), SyntaxContext::empty()),
alias: None,
});
}
ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(named)) => {
let ctxt = named
.src
.as_ref()
.map(|s| &s.value)
.and_then(|src| self.ctxt_for(src));
let mut need_wrapping = false;
let v = self
.info
.items
.entry(named.src.clone().map(|v| *v))
.or_default();
for s in &mut named.specifiers {
match s {
ExportSpecifier::Namespace(n) => {
match &mut n.name {
ModuleExportName::Ident(name) => {
name.ctxt = self.export_ctxt;
need_wrapping = true;
v.push(Specifier::Namespace {
local: name.clone().into(),
all: true,
})
}
ModuleExportName::Str(..) => {
unimplemented!("module string names unimplemented")
}
};
}
ExportSpecifier::Default(d) => {
v.push(Specifier::Specific {
local: d.exported.clone().into(),
alias: Some(Id::new("default".into(), SyntaxContext::empty())),
});
}
ExportSpecifier::Named(n) => {
let orig = match &mut n.orig {
ModuleExportName::Ident(ident) => ident,
ModuleExportName::Str(..) => {
unimplemented!("module string names unimplemented")
}
};
if let Some((_, export_ctxt)) = ctxt {
orig.ctxt = export_ctxt;
}
match &mut n.exported {
Some(ModuleExportName::Ident(exported)) => {
exported.ctxt = self.export_ctxt;
}
Some(ModuleExportName::Str(..)) => {
unimplemented!("module string names unimplemented")
}
None => {
let mut exported: Ident = orig.clone();
exported.ctxt = self.export_ctxt;
n.exported = Some(ModuleExportName::Ident(exported));
}
}
match &n.exported {
Some(ModuleExportName::Ident(exported)) => {
v.push(Specifier::Specific {
local: exported.clone().into(),
alias: Some(orig.clone().into()),
});
}
Some(ModuleExportName::Str(..)) => {
unimplemented!("module string names unimplemented")
}
_ => {
v.push(Specifier::Specific {
local: orig.clone().into(),
alias: None,
});
}
}
}
}
}
if need_wrapping {
self.mark_as_wrapping_required(&named.src.as_ref().unwrap().value);
}
}
ModuleItem::ModuleDecl(ModuleDecl::ExportAll(all)) => {
let ctxt = self.ctxt_for(&all.src.value);
if let Some((_, export_ctxt)) = ctxt {
ExportMetadata {
export_ctxt: Some(export_ctxt),
..Default::default()
}
.encode(&mut all.with);
}
self.info.items.entry(Some(*all.src.clone())).or_default();
}
_ => {}
}
}
}