Unverified Commit db03f83f authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: batch EsmBinding codegen (#99722)

**View diff without whitespace**

Call these just once (per module), not once per referenced import
- `unused_references()`
- `reference.get_referenced_asset()`
- `imported_module.get_ident(export)`
parent a10d278e
......@@ -29,7 +29,7 @@ use crate::{
dynamic_expression::DynamicExpression,
emit_collect::CollectReferenceCodeGen,
esm::{
EsmBinding, EsmModuleItem, ImportMetaBinding, ImportMetaRef,
EsmBindings, EsmModuleItem, ImportMetaBinding, ImportMetaRef,
dynamic::EsmAsyncAssetReferenceCodeGen, module_id::EsmModuleIdAssetReferenceCodeGen,
url::UrlAssetReferenceCodeGen,
},
......@@ -187,7 +187,7 @@ pub enum CodeGen {
ConstantConditionCodeGen(ConstantConditionCodeGen),
ConstantValueCodeGen(ConstantValueCodeGen),
DynamicExpression(DynamicExpression),
EsmBinding(EsmBinding),
EsmBindings(EsmBindings),
EsmModuleItem(EsmModuleItem),
ExportsInfoBinding(ExportsInfoBinding),
ExportsInfoRef(ExportsInfoRef),
......@@ -225,7 +225,7 @@ impl CodeGen {
Self::CollectReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::ConstantValueCodeGen(v) => v.code_generation(trie, ctx).await,
Self::DynamicExpression(v) => v.code_generation(trie, ctx).await,
Self::EsmBinding(v) => v.code_generation(trie, ctx, scope_hoisting_context).await,
Self::EsmBindings(v) => v.code_generation(trie, ctx, scope_hoisting_context).await,
Self::EsmModuleItem(v) => v.code_generation(trie, ctx).await,
Self::ExportsInfoBinding(v) => v.code_generation(trie, ctx, module, exports).await,
Self::ExportsInfoRef(v) => v.code_generation(trie, ctx).await,
......
......@@ -1139,7 +1139,7 @@ impl EcmascriptModuleContentOptions {
export_registration_mode
.unwrap_or_else(|| eval_context.imports.export_registration_mode()),
export_registration_mode
.map(|_| (&part_references[..], &esm_references_ref[..])),
.map(|_| (part_references.as_ref(), esm_references_ref.as_ref())),
async_module_info.is_some(),
)
.await?;
......
......@@ -73,7 +73,7 @@ pub enum ReferencedAsset {
Unresolvable,
}
#[derive(Debug)]
#[derive(Clone, Debug)]
pub enum ReferencedAssetIdent {
/// The given export (or namespace) is a local binding in the current scope hoisting group.
LocalBinding {
......@@ -100,7 +100,7 @@ pub enum ReferencedAssetIdent {
}
/// The source to import when initializing a `ReferencedAssetIdent::Module` variable.
#[derive(Debug)]
#[derive(Clone, Debug)]
pub enum ImportSource {
/// Import an in-graph module.
Module {
......
use anyhow::Result;
use bincode::{Decode, Encode};
use rustc_hash::FxHashMap;
use swc_core::ecma::{
ast::{Expr, KeyValueProp, Prop, PropName, SimpleAssignTarget},
visit::fields::{CalleeField, PropField},
};
use turbo_rcstr::RcStr;
use turbo_tasks::{NonLocalValue, ResolvedVc, Vc};
use turbo_tasks::{FxIndexMap, NonLocalValue, ResolvedVc, Vc};
use turbopack_core::chunk::ChunkingContext;
use crate::{
ScopeHoistingContext,
ast_path_trie::{AstPathId, AstPathTrie},
code_gen::{CodeGen, CodeGeneration},
code_gen::CodeGeneration,
create_visitor,
references::esm::{
EsmAssetReference,
......@@ -19,216 +20,258 @@ use crate::{
},
};
#[derive(Hash, Clone, Debug, PartialEq, Eq, NonLocalValue, Encode, Decode)]
pub struct EsmBinding {
reference: ResolvedVc<EsmAssetReference>,
#[derive(Clone, Debug, PartialEq, Eq, NonLocalValue, Encode, Decode, Hash)]
struct EsmBinding {
export: Option<RcStr>,
ast_path: AstPathId,
keep_this: bool,
}
impl EsmBinding {
pub fn new(
#[derive(Default, Clone, Debug)]
pub struct EsmBindingsBuilder {
bindings: FxIndexMap<ResolvedVc<EsmAssetReference>, Vec<EsmBinding>>,
}
#[derive(Default, Clone, Debug, PartialEq, Eq, NonLocalValue, Encode, Decode, Hash)]
pub struct EsmBindings {
#[allow(clippy::type_complexity)]
bindings: Box<[(ResolvedVc<EsmAssetReference>, Box<[EsmBinding]>)]>,
}
impl EsmBindingsBuilder {
pub fn add(
&mut self,
reference: ResolvedVc<EsmAssetReference>,
export: Option<RcStr>,
ast_path: AstPathId,
) -> Self {
EsmBinding {
reference,
export,
ast_path,
keep_this: false,
}
) {
self.bindings
.entry(reference)
.or_default()
.push(EsmBinding {
export,
ast_path,
keep_this: false,
});
}
/// Where possible, bind the namespace to `this` when the named import is called.
pub fn new_keep_this(
pub fn add_keep_this(
&mut self,
reference: ResolvedVc<EsmAssetReference>,
export: Option<RcStr>,
ast_path: AstPathId,
) -> Self {
EsmBinding {
reference,
export,
ast_path,
keep_this: true,
) {
self.bindings
.entry(reference)
.or_default()
.push(EsmBinding {
export,
ast_path,
keep_this: true,
});
}
pub fn build(self) -> Option<EsmBindings> {
if self.bindings.is_empty() {
return None;
}
Some(EsmBindings {
bindings: self
.bindings
.into_iter()
.map(|(k, v)| (k, v.into_boxed_slice()))
.collect(),
})
}
}
impl EsmBindings {
pub async fn code_generation(
&self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>,
scope_hoisting_context: ScopeHoistingContext<'_>,
) -> Result<CodeGeneration> {
if chunking_context
.unused_references()
.contains_key(&ResolvedVc::upcast(self.reference))
.await?
{
return Ok(CodeGeneration::empty());
}
let mut visitors = vec![];
let export = self.export.clone();
let imported_module = self.reference.get_referenced_asset().await?;
let unused_references = chunking_context.unused_references();
enum ImportedIdent {
Module(ReferencedAssetIdent),
None,
/// Empty module (alias set to `false`): namespace imports resolve to `{}`.
Empty,
Unresolvable,
}
for (reference, bindings) in &self.bindings {
if unused_references
.contains_key(&ResolvedVc::upcast(*reference))
.await?
{
continue;
}
let imported_module = reference.get_referenced_asset().await?;
let imported_ident = match &imported_module {
ReferencedAsset::None => ImportedIdent::None,
ReferencedAsset::Empty => {
if export.is_some() {
// Named/default binding from an empty module → `undefined`
ImportedIdent::None
} else {
// Namespace import from an empty module → `{}`
ImportedIdent::Empty
}
let mut exports_cache: FxHashMap<Option<RcStr>, _> = FxHashMap::default();
#[derive(Clone)]
enum ImportedIdent {
Module(ReferencedAssetIdent),
None,
/// Empty module (alias set to `false`): namespace imports resolve to `{}`.
Empty,
Unresolvable,
}
imported_module => imported_module
.get_ident(chunking_context, export, scope_hoisting_context)
.await?
.map_or(ImportedIdent::Unresolvable, ImportedIdent::Module),
};
// Walk up from the binding towards the root, stopping at the innermost node kind we
// know how to rewrite.
let mut ast_path = self.ast_path;
loop {
match trie.get(ast_path) {
// Shorthand properties get special treatment because we need to rewrite them to
// normal key-value pairs.
Some(swc_core::ecma::visit::AstParentKind::Prop(PropField::Shorthand)) => {
ast_path = trie.parent_or_root(ast_path);
visitors.push(create_visitor!(
exact,
trie,
ast_path,
visit_mut_prop,
|prop: &mut Prop| {
if let Prop::Shorthand(ident) = prop {
match &imported_ident {
ImportedIdent::Module(imported_ident) => {
*prop = Prop::KeyValue(KeyValueProp {
key: PropName::Ident(ident.clone().into()),
value: Box::new(
imported_ident.as_expr(ident.span, false),
),
});
}
ImportedIdent::None => {
*prop = Prop::KeyValue(KeyValueProp {
key: PropName::Ident(ident.clone().into()),
value: Expr::undefined(ident.span),
});
}
ImportedIdent::Empty => {
use swc_core::quote;
*prop = Prop::KeyValue(KeyValueProp {
key: PropName::Ident(ident.clone().into()),
value: Box::new(quote!("{}" as Expr)),
});
}
ImportedIdent::Unresolvable => {
// Do nothing, the reference will insert a throw
for EsmBinding {
export,
ast_path,
keep_this,
} in bindings
{
let imported_ident = match &imported_module {
ReferencedAsset::None => ImportedIdent::None,
ReferencedAsset::Empty => {
if export.is_some() {
// Named/default binding from an empty module → `undefined`
ImportedIdent::None
} else {
// Namespace import from an empty module → `{}`
ImportedIdent::Empty
}
}
imported_module => match exports_cache.entry(export.clone()) {
std::collections::hash_map::Entry::Vacant(entry) => {
let ident: ImportedIdent = imported_module
.get_ident(chunking_context, export.clone(), scope_hoisting_context)
.await?
.map_or(ImportedIdent::Unresolvable, ImportedIdent::Module);
entry.insert(ident.clone());
ident
}
std::collections::hash_map::Entry::Occupied(entry) => entry.get().clone(),
},
};
// Walk up from the binding towards the root, stopping at the innermost node kind we
// know how to rewrite.
let mut ast_path = *ast_path;
loop {
match trie.get(ast_path) {
// Shorthand properties get special treatment because we need to rewrite
// them to normal key-value pairs.
Some(swc_core::ecma::visit::AstParentKind::Prop(PropField::Shorthand)) => {
ast_path = trie.parent_or_root(ast_path);
visitors.push(create_visitor!(
exact,
trie,
ast_path,
visit_mut_prop,
|prop: &mut Prop| {
if let Prop::Shorthand(ident) = prop {
match &imported_ident {
ImportedIdent::Module(imported_ident) => {
*prop = Prop::KeyValue(KeyValueProp {
key: PropName::Ident(ident.clone().into()),
value: Box::new(
imported_ident.as_expr(ident.span, false),
),
});
}
ImportedIdent::None => {
*prop = Prop::KeyValue(KeyValueProp {
key: PropName::Ident(ident.clone().into()),
value: Expr::undefined(ident.span),
});
}
ImportedIdent::Empty => {
use swc_core::quote;
*prop = Prop::KeyValue(KeyValueProp {
key: PropName::Ident(ident.clone().into()),
value: Box::new(quote!("{}" as Expr)),
});
}
ImportedIdent::Unresolvable => {
// Do nothing, the reference will insert a throw
}
}
}
}
}
));
break;
}
));
break;
}
// Any other expression can be replaced with the import accessor.
Some(swc_core::ecma::visit::AstParentKind::Expr(_)) => {
ast_path = trie.parent_or_root(ast_path);
let in_call = !self.keep_this
&& matches!(
trie.get(ast_path),
Some(swc_core::ecma::visit::AstParentKind::Callee(
CalleeField::Expr
))
);
visitors.push(create_visitor!(
exact,
trie,
ast_path,
visit_mut_expr,
|expr: &mut Expr| {
use swc_core::common::Spanned;
match &imported_ident {
ImportedIdent::Module(imported_ident) => {
*expr = imported_ident.as_expr(expr.span(), in_call);
}
ImportedIdent::None => {
*expr = *Expr::undefined(expr.span());
}
ImportedIdent::Empty => {
use swc_core::quote;
*expr = quote!("{}" as Expr);
}
ImportedIdent::Unresolvable => {
// Do nothing, the reference will insert a throw
// Any other expression can be replaced with the import accessor.
Some(swc_core::ecma::visit::AstParentKind::Expr(_)) => {
ast_path = trie.parent_or_root(ast_path);
let in_call = !keep_this
&& matches!(
trie.get(ast_path),
Some(swc_core::ecma::visit::AstParentKind::Callee(
CalleeField::Expr
))
);
visitors.push(create_visitor!(
exact,
trie,
ast_path,
visit_mut_expr,
|expr: &mut Expr| {
use swc_core::common::Spanned;
match &imported_ident {
ImportedIdent::Module(imported_ident) => {
*expr = imported_ident.as_expr(expr.span(), in_call);
}
ImportedIdent::None => {
*expr = *Expr::undefined(expr.span());
}
ImportedIdent::Empty => {
use swc_core::quote;
*expr = quote!("{}" as Expr);
}
ImportedIdent::Unresolvable => {
// Do nothing, the reference will insert a throw
}
}
}
}
));
break;
}
));
break;
}
// We need to handle LHS because of code like
// (function (RouteKind1){})(RouteKind || RouteKind = {})
Some(swc_core::ecma::visit::AstParentKind::SimpleAssignTarget(_)) => {
ast_path = trie.parent_or_root(ast_path);
visitors.push(create_visitor!(
exact,
trie,
ast_path,
visit_mut_simple_assign_target,
|l: &mut SimpleAssignTarget| {
use swc_core::common::Spanned;
match &imported_ident {
ImportedIdent::Module(imported_ident) => {
*l = imported_ident
.as_expr_individual(l.span())
.map_either(
|i| SimpleAssignTarget::Ident(i.into()),
SimpleAssignTarget::Member,
)
.into_inner();
}
ImportedIdent::None | ImportedIdent::Empty => {
// Do nothing, cannot assign to `undefined` or `{}`
}
ImportedIdent::Unresolvable => {
// Do nothing, the reference will insert a throw
// We need to handle LHS because of code like
// (function (RouteKind1){})(RouteKind || RouteKind = {})
Some(swc_core::ecma::visit::AstParentKind::SimpleAssignTarget(_)) => {
ast_path = trie.parent_or_root(ast_path);
visitors.push(create_visitor!(
exact,
trie,
ast_path,
visit_mut_simple_assign_target,
|l: &mut SimpleAssignTarget| {
use swc_core::common::Spanned;
match &imported_ident {
ImportedIdent::Module(imported_ident) => {
*l = imported_ident
.as_expr_individual(l.span())
.map_either(
|i| SimpleAssignTarget::Ident(i.into()),
SimpleAssignTarget::Member,
)
.into_inner();
}
ImportedIdent::None | ImportedIdent::Empty => {
// Do nothing, cannot assign to `undefined` or `{}`
}
ImportedIdent::Unresolvable => {
// Do nothing, the reference will insert a throw
}
}
}
}
));
break;
}
));
break;
}
Some(_) => {
ast_path = trie.parent_or_root(ast_path);
Some(_) => {
ast_path = trie.parent_or_root(ast_path);
}
None => break,
}
}
None => break,
}
}
Ok(CodeGeneration::visitors(visitors))
}
}
impl From<EsmBinding> for CodeGen {
fn from(val: EsmBinding) -> Self {
CodeGen::EsmBinding(val)
}
}
......@@ -10,7 +10,7 @@ pub(crate) mod url;
pub use self::{
base::{EsmAssetReference, EsmAssetReferenceOptions},
binding::EsmBinding,
binding::EsmBindings,
dynamic::EsmAsyncAssetReference,
export::{EsmExport, EsmExports, FoundExportType, Liveness},
mangle::generated_export_key,
......
......@@ -131,9 +131,9 @@ use crate::{
dynamic_expression::DynamicExpression,
emit_collect::{CollectReference, EmitReference},
esm::{
EsmAssetReference, EsmAssetReferenceOptions, EsmAsyncAssetReference, EsmBinding,
ImportMetaBinding, ImportMetaRef, UrlAssetReference, UrlRewriteBehavior,
base::EsmAssetReferences, module_id::EsmModuleIdAssetReference,
EsmAssetReference, EsmAssetReferenceOptions, EsmAsyncAssetReference, ImportMetaBinding,
ImportMetaRef, UrlAssetReference, UrlRewriteBehavior, base::EsmAssetReferences,
binding::EsmBindingsBuilder, module_id::EsmModuleIdAssetReference,
},
exports::{EcmascriptExportsAnalysis, compute_ecmascript_module_exports},
exports_info::{ExportsInfoBinding, ExportsInfoRef},
......@@ -226,6 +226,8 @@ struct AnalyzeEcmascriptModuleResultBuilder {
// This caches repeated access because EsmAssetReference::new is not a turbo task function.
esm_references_rewritten: FxHashMap<usize, FxIndexMap<RcStr, ResolvedVc<EsmAssetReference>>>,
esm_bindings: EsmBindingsBuilder,
code_gens: CodeGenCollection,
/// Interns the AST paths referenced by `code_gens`, so overlapping paths share storage.
/// Handed to the resulting [`CodeGens`] once analysis finishes.
......@@ -253,6 +255,7 @@ impl AnalyzeEcmascriptModuleResultBuilder {
esm_reexport_references: Default::default(),
esm_references_rewritten: Default::default(),
esm_references_free_var: Default::default(),
esm_bindings: Default::default(),
code_gens: Default::default(),
ast_paths: Default::default(),
async_module: ResolvedVc::cell(None),
......@@ -459,6 +462,10 @@ impl AnalyzeEcmascriptModuleResultBuilder {
}
}
if let Some(esm_bindings) = std::mem::take(&mut self.esm_bindings).build() {
self.add_code_gen(CodeGen::EsmBindings(esm_bindings));
}
let references: Vec<_> = self.references.into_iter().collect();
if !self.analyze_mode.is_codegen {
......@@ -1473,11 +1480,11 @@ async fn analyze_ecmascript_module_internal(
.resolved_cell()
},
);
analysis.add_code_gen(EsmBinding::new_keep_this(
analysis.esm_bindings.add_keep_this(
named_reference,
Some(export),
analysis.intern_path(&ast_path),
));
);
continue;
}
......@@ -1500,21 +1507,19 @@ async fn analyze_ecmascript_module_internal(
.resolved_cell()
},
);
analysis.add_code_gen(EsmBinding::new(
analysis.esm_bindings.add(
narrowed_reference,
export,
analysis.intern_path(&ast_path),
));
);
continue;
}
}
analysis.add_esm_reference(esm_reference_index);
analysis.add_code_gen(EsmBinding::new(
*r,
export,
analysis.intern_path(&ast_path),
));
analysis
.esm_bindings
.add(*r, export, analysis.intern_path(&ast_path));
}
}
Effect::TypeOf {
......@@ -3868,11 +3873,11 @@ async fn handle_free_var_reference(
})
.await?;
analysis.add_code_gen(EsmBinding::new(
analysis.esm_bindings.add(
esm_reference,
export.clone(),
analysis.intern_path(ast_path),
));
);
}
FreeVarReference::InputRelative(kind) => {
let source_path = (*state.source).ident().await?.path.clone();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment