swc_bundler/bundler/import/mod.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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
use anyhow::{Context, Error};
use swc_atoms::JsWord;
use swc_common::{
collections::{AHashMap, AHashSet},
sync::Lrc,
FileName, Mark, Spanned, SyntaxContext, DUMMY_SP,
};
use swc_ecma_ast::*;
use swc_ecma_utils::find_pat_ids;
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use super::Bundler;
use crate::{load::Load, resolve::Resolve, util::ExportMetadata};
#[cfg(test)]
mod tests;
impl<L, R> Bundler<'_, L, R>
where
L: Load,
R: Resolve,
{
/// This method de-globs imports if possible and colorizes imported values.
pub(super) fn extract_import_info(
&self,
path: &FileName,
module: &mut Module,
module_local_mark: Mark,
) -> RawImports {
self.run(|| {
let mut v = ImportHandler {
module_ctxt: SyntaxContext::empty().apply_mark(module_local_mark),
path,
bundler: self,
top_level: false,
info: Default::default(),
usages: Default::default(),
imported_idents: Default::default(),
deglob_phase: false,
idents_to_deglob: Default::default(),
in_obj_of_member: false,
};
module.body.visit_mut_with(&mut v);
v.deglob_phase = true;
module.body.visit_mut_with(&mut v);
v.info
})
}
pub(super) fn resolve(
&self,
base: &FileName,
module_specifier: &str,
) -> Result<Lrc<FileName>, Error> {
self.run(|| {
let path = self
.resolver
.resolve(base, module_specifier)
.map(|v| v.filename)
.with_context(|| format!("failed to resolve {} from {}", module_specifier, base))?;
let path = Lrc::new(path);
Ok(path)
})
}
}
#[derive(Debug, Default)]
pub(super) struct RawImports {
/// Unconditional imports. This includes require on top level.
pub imports: Vec<ImportDecl>,
/// Non-top-level imports.
///
/// # Example
///
/// ```js
/// try{
/// const { watch } = require('watcher');
/// } catch (e) {
/// }
/// ```
pub lazy_imports: Vec<ImportDecl>,
pub dynamic_imports: Vec<Str>,
/// Contains namespace imports accessed with computed key.
///
///
/// e.g.
///
///```js
/// import * as foo from './foo';
/// function bar() {}
/// foo[bar()]
/// ```
pub forced_ns: AHashSet<JsWord>,
}
/// This type implements two operation (analysis, deglobbing) to reduce binary
/// size.
struct ImportHandler<'a, 'b, L, R>
where
L: Load,
R: Resolve,
{
/// The [SyntaxContext] for the top level module items.
//// The top level module items includes imported bindings.
module_ctxt: SyntaxContext,
path: &'a FileName,
bundler: &'a Bundler<'b, L, R>,
top_level: bool,
info: RawImports,
/// HashMap from the local identifier of a namespace import to used
/// properties.
usages: AHashMap<Id, Vec<Id>>,
/// While deglobbing, we also marks imported identifiers.
imported_idents: AHashMap<Id, SyntaxContext>,
deglob_phase: bool,
idents_to_deglob: AHashSet<Id>,
/// `true` while folding objects of a member expression.
///
/// This is used to distinguish usage of `a` in `console.log(a)` and
/// `a.join()`.
in_obj_of_member: bool,
}
impl RawImports {
fn insert(&mut self, import: &ImportDecl) {
for prev in self.imports.iter_mut() {
if prev.src.value == import.src.value {
prev.specifiers.extend(import.specifiers.clone());
return;
}
}
self.imports.push(import.clone());
}
}
impl<L, R> ImportHandler<'_, '_, 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.is_external(src) {
return None;
}
let path = self.bundler.resolve(self.path, 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.is_external(src) {
return;
}
let path = self.bundler.resolve(self.path, src);
let path = match path {
Ok(v) => v,
Err(_) => return,
};
let (id, _, _) = self.bundler.scope.module_id_gen.gen(&path);
self.bundler.scope.mark_as_wrapping_required(id);
}
fn mark_as_cjs(&self, src: &JsWord) {
let path = self.bundler.resolve(self.path, src);
let path = match path {
Ok(v) => v,
Err(_) => return,
};
let (id, _, _) = self.bundler.scope.module_id_gen.gen(&path);
self.bundler.scope.mark_as_cjs(id);
}
fn add_forced_ns_for(&mut self, id: Id) {
self.idents_to_deglob.remove(&id);
self.imported_idents.remove(&id);
self.usages.remove(&id);
if let Some(src) = self
.info
.imports
.iter()
.find(|import| {
import.specifiers.iter().any(|specifier| match specifier {
ImportSpecifier::Namespace(ns) => ns.local.sym == id.0 && ns.local.ctxt == id.1,
_ => false,
})
})
.map(|import| import.src.value.clone())
{
self.info.forced_ns.insert(src);
}
}
fn find_require(&mut self, e: &mut Expr) {
match e {
Expr::Call(e) if e.args.len() == 1 => {
let src = match e.args.first().unwrap() {
ExprOrSpread { spread: None, expr } => match &**expr {
Expr::Lit(Lit::Str(s)) => s,
_ => return,
},
_ => return,
};
match &mut e.callee {
Callee::Expr(callee)
if self.bundler.config.require && callee.is_ident_ref_to("require") =>
{
if self.bundler.is_external(&src.value) {
return;
}
if let Expr::Ident(i) = &mut **callee {
self.mark_as_cjs(&src.value);
if let Some((_, export_ctxt)) = self.ctxt_for(&src.value) {
i.ctxt = export_ctxt;
}
}
let span = callee.span();
let decl = ImportDecl {
span,
specifiers: Vec::new(),
src: Box::new(src.clone()),
type_only: false,
with: None,
phase: Default::default(),
};
if self.top_level {
self.info.insert(&decl);
return;
}
self.info.lazy_imports.push(decl);
}
// TODO: Uncomment this after implementing an option to make swc_bundler
// includes dynamic imports
//
//
// ExprOrSuper::Expr(ref e) => match &**e {
// Expr::Ident(Ident {
// sym: "import",
// ..
// }) => {
// self.info.dynamic_imports.push(src.clone());
// }
// _ => {}
// },
_ => {}
}
}
_ => {}
}
}
fn analyze_usage(&mut self, e: &mut Expr) {
if let Expr::Member(e) = e {
if let Expr::Ident(obj) = &*e.obj {
if !self.imported_idents.contains_key(&obj.to_id()) {
// If it's not imported, just abort the usage analysis.
return;
}
if e.prop.is_computed() {
// If a module is accessed with unknown key, we should import
// everything from it.
self.add_forced_ns_for(obj.to_id());
return;
}
// Store usages of obj
let import = self.info.imports.iter().find(|import| {
for s in &import.specifiers {
if let ImportSpecifier::Namespace(n) = s {
return obj.sym == n.local.sym
&& (obj.ctxt == self.module_ctxt || obj.ctxt == n.local.ctxt);
}
}
false
});
let import = match import {
Some(v) => v,
None => return,
};
let mark = self.ctxt_for(&import.src.value);
let exported_ctxt = match mark {
None => return,
Some(ctxts) => ctxts.1,
};
let prop = match &e.prop {
MemberProp::Ident(i) => {
let mut i = Ident::from(i.clone());
i.ctxt = exported_ctxt;
i
}
_ => unreachable!(
"Non-computed member expression with property other than ident is invalid"
),
};
self.usages
.entry(obj.to_id())
.or_default()
.push(prop.to_id());
}
}
}
fn try_deglob(&mut self, e: &mut Expr) {
let me = match e {
Expr::Member(e) => e,
_ => return,
};
if me.prop.is_computed() {
return;
}
let obj = match &*me.obj {
Expr::Ident(obj) => obj,
_ => return,
};
let usages = self.usages.get(&obj.to_id());
match usages {
Some(..) => {}
_ => return,
};
let mut prop = match &me.prop {
MemberProp::Ident(v) => Ident::from(v.clone()),
_ => return,
};
prop.ctxt = self.imported_idents.get(&obj.to_id()).copied().unwrap();
*e = prop.into();
}
}
impl<L, R> VisitMut for ImportHandler<'_, '_, L, R>
where
L: Load,
R: Resolve,
{
noop_visit_mut_type!(fail);
fn visit_mut_export_named_specifier(&mut self, s: &mut ExportNamedSpecifier) {
let orig = match &s.orig {
ModuleExportName::Ident(ident) => ident,
ModuleExportName::Str(..) => unimplemented!("module string names unimplemented"),
};
self.add_forced_ns_for(orig.to_id());
match &mut s.exported {
Some(ModuleExportName::Ident(exported)) => {
// PR 3139 (https://github.com/swc-project/swc/pull/3139) removes the syntax context from any named exports from other sources.
exported.ctxt = self.module_ctxt;
}
Some(ModuleExportName::Str(..)) => unimplemented!("module string names unimplemented"),
None => {
let exported = Ident::new(orig.sym.clone(), orig.span, self.module_ctxt);
s.exported = Some(ModuleExportName::Ident(exported));
}
}
}
fn visit_mut_expr(&mut self, e: &mut Expr) {
e.visit_mut_children_with(self);
if !self.deglob_phase {
// Firstly, we check for usages of imported namespaces.
// Code like below are handled by this check.
//
// import * as log from './log';
// console.log(log)
// console.log(log.getLogger())
if !self.in_obj_of_member {
if let Expr::Ident(i) = &e {
if !self.in_obj_of_member {
self.add_forced_ns_for(i.to_id());
return;
}
}
}
self.analyze_usage(e);
self.find_require(e);
} else {
self.try_deglob(e);
}
}
fn visit_mut_import_decl(&mut self, import: &mut ImportDecl) {
// Ignore if it's a core module.
if self.bundler.is_external(&import.src.value) {
return;
}
if !self.deglob_phase {
if let Some((_, export_ctxt)) = self.ctxt_for(&import.src.value) {
// Firstly we attach proper syntax contexts.
ExportMetadata {
export_ctxt: Some(export_ctxt),
..Default::default()
}
.encode(&mut import.with);
// Then we store list of imported identifiers.
for specifier in &mut import.specifiers {
match specifier {
ImportSpecifier::Named(n) => {
self.imported_idents.insert(n.local.to_id(), export_ctxt);
match &mut n.imported {
Some(ModuleExportName::Ident(imported)) => {
imported.ctxt = export_ctxt;
}
Some(ModuleExportName::Str(..)) => {
unimplemented!("module string names unimplemented")
}
None => {
let mut imported: Ident = n.local.clone();
imported.ctxt = export_ctxt;
n.imported = Some(ModuleExportName::Ident(imported));
}
}
}
ImportSpecifier::Default(n) => {
self.imported_idents.insert(n.local.to_id(), n.local.ctxt);
}
ImportSpecifier::Namespace(n) => {
self.imported_idents.insert(n.local.to_id(), export_ctxt);
}
}
}
}
self.info.insert(import);
return;
}
// Now we are in deglobbing phase.
// We cannot deglob this.
if self.info.forced_ns.contains(&import.src.value) {
return;
}
// deglob namespace imports
if import.specifiers.len() == 1 {
if let ImportSpecifier::Namespace(ns) = &import.specifiers[0] {
//
let specifiers = self
.usages
.get(&ns.local.to_id())
.cloned()
.map(|ids| {
//
let specifiers: Vec<_> = ids
.into_iter()
.map(|id| {
self.idents_to_deglob.insert(id.clone());
ImportSpecifier::Named(ImportNamedSpecifier {
span: DUMMY_SP,
local: Ident::new(id.0, DUMMY_SP, id.1),
imported: None,
is_type_only: false,
})
})
.collect();
for import_info in &mut self.info.imports {
if import_info.src != import.src {
continue;
}
import_info.specifiers.extend(specifiers.clone());
}
specifiers
})
.unwrap_or_else(Vec::new);
if !specifiers.is_empty() {
import.specifiers = specifiers;
return;
}
// We failed to found property usage.
self.info.forced_ns.insert(import.src.value.clone());
}
}
}
fn visit_mut_member_expr(&mut self, e: &mut MemberExpr) {
let old = self.in_obj_of_member;
self.in_obj_of_member = true;
e.obj.visit_mut_with(self);
if let MemberProp::Computed(c) = &mut e.prop {
self.in_obj_of_member = false;
c.visit_mut_with(self);
}
self.in_obj_of_member = old;
}
fn visit_mut_module_items(&mut self, items: &mut Vec<ModuleItem>) {
self.top_level = true;
items.visit_mut_children_with(self);
items.retain_mut(|item| match item {
ModuleItem::Stmt(Stmt::Empty(..)) => false,
ModuleItem::Stmt(Stmt::Decl(Decl::Var(var))) => {
var.decls.retain(|d| !matches!(d.name, Pat::Invalid(..)));
!var.decls.is_empty()
}
_ => true,
});
if self.deglob_phase {
let mut wrapping_required = Vec::new();
for import in self.info.imports.iter_mut() {
let use_ns = self.info.forced_ns.contains(&import.src.value)
|| self
.bundler
.config
.external_modules
.contains(&import.src.value);
if use_ns {
wrapping_required.push(import.src.value.clone());
} else {
// De-glob namespace imports
import
.specifiers
.retain(|s| !matches!(s, ImportSpecifier::Namespace(_)));
}
}
for id in wrapping_required {
self.mark_as_wrapping_required(&id);
}
}
}
fn visit_mut_stmts(&mut self, items: &mut Vec<Stmt>) {
self.top_level = false;
items.visit_mut_children_with(self)
}
fn visit_mut_super_prop_expr(&mut self, e: &mut SuperPropExpr) {
let old = self.in_obj_of_member;
if let SuperProp::Computed(c) = &mut e.prop {
self.in_obj_of_member = false;
c.visit_mut_with(self);
}
self.in_obj_of_member = old;
}
/// ```js
/// const { readFile } = required('fs');
/// ```
///
/// is treated as
///
/// ```js
/// import { readFile } from 'fs';
/// ```
fn visit_mut_var_declarator(&mut self, node: &mut VarDeclarator) {
node.visit_mut_children_with(self);
if let Some(init) = &mut node.init {
match &mut **init {
Expr::Call(CallExpr {
span,
callee: Callee::Expr(ref mut callee),
ref args,
..
}) if self.bundler.config.require
&& callee.is_ident_ref_to("require")
&& args.len() == 1 =>
{
let span = *span;
let src = match args.first().unwrap() {
ExprOrSpread { spread: None, expr } => match &**expr {
Expr::Lit(Lit::Str(s)) => s.clone(),
_ => return,
},
_ => return,
};
// Ignore core modules.
if self.bundler.config.external_modules.contains(&src.value) {
return;
}
self.mark_as_cjs(&src.value);
if let Expr::Ident(i) = &mut **callee {
if let Some((_, export_ctxt)) = self.ctxt_for(&src.value) {
i.ctxt = export_ctxt;
}
}
let ids: Vec<Ident> = find_pat_ids(&node.name);
let decl = ImportDecl {
span,
specifiers: ids
.into_iter()
.map(|ident| {
ImportSpecifier::Named(ImportNamedSpecifier {
span,
local: ident,
imported: None,
is_type_only: false,
})
})
.collect(),
src: Box::new(src),
type_only: false,
with: None,
phase: Default::default(),
};
// if self.top_level {
// self.info.imports.push(decl);
// node.init = None;
// node.name = Pat::Invalid(Invalid { span: DUMMY_SP });
// return node;
// }
self.info.lazy_imports.push(decl);
}
_ => {}
}
}
}
}