Commit a86d64d1 authored by Luke Sandberg's avatar Luke Sandberg

Optimize re-export bindings

Fix an expr
parent ceff818b
......@@ -105,6 +105,7 @@ impl EcmascriptChunkPlaceable for NextDynamicEntryModule {
.to_resolved()
.await?,
);
let mut exports = BTreeMap::new();
let default = rcstr!("default");
exports.insert(
......
......@@ -105,9 +105,12 @@ function createModuleObject(id: ModuleId): Module {
}
}
type BindingTag = 0
type BindingTag = 0 | 1 | 2 | 3 | 4
const BindingTag_Value = 0 as BindingTag
const BindingTag_ReExport = 1 as BindingTag
const BindingTag_RenamedReexport = 2 as BindingTag
const BindingTag_Mutable_ReExport = 3 as BindingTag
const BindingTag_Mutable_RenamedReexport = 4 as BindingTag
// an arbitrary sequence of bindings as
// - a prop name
// - BindingTag_Value, a value to be bound directly, or
......@@ -127,15 +130,49 @@ function esm(exports: Exports, bindings: EsmBindings) {
const propName = bindings[i++] as string
const tagOrFunction = bindings[i++]
if (typeof tagOrFunction === 'number') {
if (tagOrFunction === BindingTag_Value) {
defineProp(exports, propName, {
value: bindings[i++],
enumerable: true,
writable: false,
})
} else {
throw new Error(`unexpected tag: ${tagOrFunction}`)
let descriptor: PropertyDescriptor
switch (tagOrFunction) {
case BindingTag_Value:
descriptor = {
value: bindings[i++],
enumerable: true,
writable: false,
}
break
case BindingTag_ReExport:
case BindingTag_Mutable_ReExport:
{
const namespace = bindings[i++] as Record<string, any>
// Note: in the common case we can just copy the descriptor this removes some indirection when
// accesing reexports however the propery may not exist if there is a cycle between a CJS file
// and an ESM module, in that case we just bind a getter and optional setter.
descriptor =
Object.getOwnPropertyDescriptor(namespace, propName) ??
makeReexportDescriptor(
namespace,
propName,
tagOrFunction === BindingTag_Mutable_ReExport
)
}
break
case BindingTag_RenamedReexport:
case BindingTag_Mutable_RenamedReexport:
{
const sourceName = bindings[i++] as string
const namespace = bindings[i++] as Record<string, any>
descriptor =
Object.getOwnPropertyDescriptor(namespace, sourceName) ??
makeReexportDescriptor(
namespace,
sourceName,
tagOrFunction === BindingTag_Mutable_RenamedReexport
)
}
break
default:
throw new Error(`unexpected tag: ${tagOrFunction}`)
}
defineProp(exports, propName, descriptor)
} else {
const getterFn = tagOrFunction as () => unknown
if (typeof bindings[i] === 'function') {
......@@ -156,6 +193,21 @@ function esm(exports: Exports, bindings: EsmBindings) {
Object.seal(exports)
}
function makeReexportDescriptor(
namespace: Record<string, any>,
propName: string,
mutable: boolean
): PropertyDescriptor {
const descriptor: PropertyDescriptor = {
enumerable: true,
get: createGetter(namespace, propName),
}
if (mutable) {
descriptor.set = createSetter(namespace, propName)
}
return descriptor
}
/**
* Makes the module an ESM with exports
*/
......@@ -275,7 +327,11 @@ contextPrototype.n = exportNamespace
function createGetter(obj: Record<string | symbol, any>, key: string | symbol) {
return () => obj[key]
}
function createSetter(obj: Record<string | symbol, any>, key: string | symbol) {
return (v) => {
obj[key] = v
}
}
/**
* @returns prototype of the object
*/
......
......@@ -41,6 +41,7 @@ use crate::{
analyzer::imports::ImportAnnotations,
chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
code_gen::{CodeGeneration, CodeGenerationHoistedStmt},
export::Liveness,
magic_identifier,
references::{
esm::EsmExport,
......@@ -62,7 +63,11 @@ pub enum ReferencedAsset {
#[derive(Debug)]
pub enum ReferencedAssetIdent {
/// The given export (or namespace) is a local binding in the current scope hoisting group.
LocalBinding { ident: RcStr, ctxt: SyntaxContext },
LocalBinding {
ident: RcStr,
ctxt: SyntaxContext,
liveness: Liveness,
},
/// The given export (or namespace) should be imported and will be assigned to a new variable.
Module {
namespace_ident: String,
......@@ -82,16 +87,33 @@ impl ReferencedAssetIdent {
ReferencedAssetIdent::LocalBinding { .. } => None,
}
}
pub fn as_module_namespace_expr(&self, span: Span) -> Option<Expr> {
match self {
ReferencedAssetIdent::Module {
namespace_ident,
ctxt,
..
} => Some(Expr::Ident(Ident::new(
namespace_ident.as_str().into(),
span,
ctxt.unwrap_or_default(),
))),
ReferencedAssetIdent::LocalBinding { .. } => None,
}
}
pub fn as_expr_individual(&self, span: Span) -> Either<Ident, MemberExpr> {
match self {
ReferencedAssetIdent::LocalBinding { ident, ctxt } => {
Either::Left(Ident::new(ident.as_str().into(), span, *ctxt))
}
ReferencedAssetIdent::LocalBinding {
ident,
ctxt,
liveness: _,
} => Either::Left(Ident::new(ident.as_str().into(), span, *ctxt)),
ReferencedAssetIdent::Module {
namespace_ident,
ctxt,
export,
..
} => {
if let Some(export) = export {
Either::Right(MemberExpr {
......@@ -172,13 +194,14 @@ impl ReferencedAsset {
let exports = exports.expand_exports(ModuleExportUsageInfo::all()).await?;
let esm_export = exports.exports.get(export);
match esm_export {
Some(EsmExport::LocalBinding(_, _)) => {
Some(EsmExport::LocalBinding(_, liveness)) => {
// A local binding in a module that is merged in the same group. Use the
// export name as identifier, it will be replaced with the actual
// variable name during AST merging.
return Ok(Some(ReferencedAssetIdent::LocalBinding {
ident: export.clone(),
ctxt,
liveness: *liveness,
}));
}
Some(b @ EsmExport::ImportedBinding(esm_ref, _, _))
......
......@@ -649,6 +649,8 @@ impl EsmExports {
Getter(Expr),
GetterSetter(Expr, Expr),
Value(Expr),
// The namespace expression and the export name
ReExport(Expr, bool, RcStr),
None,
}
......@@ -686,9 +688,7 @@ impl EsmExports {
let local = Ident::new(local.into(), DUMMY_SP, ctxt);
match (liveness, export_usage_info.is_circuit_breaker) {
(Liveness::Constant, false) => {
ExportBinding::Value(quote!("$local" as Expr, local = local))
}
(Liveness::Constant, false) => ExportBinding::Value(Expr::Ident(local)),
// If the value might change or we are a circuit breaker we must bind a
// getter to avoid capturing the value at the wrong time.
(Liveness::Live, _) | (Liveness::Constant, true) => {
......@@ -713,31 +713,67 @@ impl EsmExports {
.map(|ident| {
let expr = ident.as_expr_individual(DUMMY_SP);
let read_expr = expr.map_either(Expr::from, Expr::from).into_inner();
// For imported bindings we could simply export the 'import' and have the runtime hook the bindings together.
// This would be cute, slightly smaller codegen but efficiency is an open question. In fact we could even
// perform the 'liveness' check at runtime by querying the property descriptor.
let getter = quote!(
"() => $expr" as Expr,
expr: Expr = read_expr,
);
if *mutable {
ExportBinding::GetterSetter(
getter,
quote!(
"($new) => $lhs = $new" as Expr,
lhs: AssignTarget = AssignTarget::Simple(
ident.as_expr_individual(DUMMY_SP).map_either(|i| SimpleAssignTarget::Ident(i.into()), SimpleAssignTarget::Member).into_inner()),
new = Ident::new(
format!("new_{name}").into(),
DUMMY_SP,
Default::default()
),
)
)
} else {
ExportBinding::Getter(getter)
}
}).unwrap_or(ExportBinding::None)
use crate::references::esm::base::ReferencedAssetIdent;
match &ident {
ReferencedAssetIdent::LocalBinding {ctxt, liveness,.. } => {
debug_assert!(*mutable == (*liveness == Liveness::Mutable), "If the re-export is mutable, the merged local must be too");
// If we are re-exporting something but got merged with it we can treat it like a local export
match (liveness, export_usage_info.is_circuit_breaker) {
(Liveness::Constant, false) => {
ExportBinding::Value(read_expr)
}
// If the value might change or we are a circuit breaker we must bind a
// getter to avoid capturing the value at the wrong time.
(Liveness::Live, _) | (Liveness::Constant, true) => {
ExportBinding::Getter(quote!("() => $local" as Expr, local: Expr = read_expr))
}
(Liveness::Mutable, _) => ExportBinding::GetterSetter(
quote!("() => $local" as Expr, local: Expr= read_expr.clone()),
quote!(
"($new) => $lhs = $new" as Expr,
lhs: AssignTarget = AssignTarget::Simple(
ident.as_expr_individual(DUMMY_SP).map_either(|i| SimpleAssignTarget::Ident(i.into()), SimpleAssignTarget::Member).into_inner()),
new = Ident::new(format!("new_{name}").into(), DUMMY_SP, *ctxt),
),
),
}
},
ReferencedAssetIdent::Module { namespace_ident:_, ctxt:_, export } => {
if export_usage_info.is_circuit_breaker {
// Instead of a function we could pass a module-id up and have the runtime bind a getter that retrieves it from the modulecache
let getter = quote!(
"() => $expr" as Expr,
expr: Expr = read_expr,
);
if *mutable {
ExportBinding::GetterSetter(
getter,
quote!(
"($new) => $lhs = $new" as Expr,
lhs: AssignTarget = AssignTarget::Simple(
ident.as_expr_individual(DUMMY_SP).map_either(|i| SimpleAssignTarget::Ident(i.into()), SimpleAssignTarget::Member).into_inner()),
new = Ident::new(
format!("new_{name}").into(),
DUMMY_SP,
Default::default()
),
))
} else {
ExportBinding::Getter(getter)
}
} else {
let namespace_expr = ident.as_module_namespace_expr(DUMMY_SP).unwrap();
if let Some(export) = export {
ExportBinding::ReExport(namespace_expr, *mutable, export.clone())
} else {
ExportBinding::Value(namespace_expr)
}
}
}
}})
.unwrap_or(ExportBinding::None)
}
EsmExport::ImportedNamespace(esm_ref) => {
let referenced_asset =
......@@ -748,6 +784,10 @@ impl EsmExports {
.map(|ident| {
let imported = ident.as_expr(DUMMY_SP, false);
if export_usage_info.is_circuit_breaker {
// In theory we could just pass the target module id up and the
// runtime could do the import when binding the export.
// This would almost work but could change evaluation order unless
// we create some way to look-up a module without loading it.
ExportBinding::Getter(quote!(
"(() => $imported)" as Expr,
imported: Expr = imported
......@@ -783,6 +823,25 @@ impl EsmExports {
getters.push(Some(value.into()));
}
ExportBinding::None => {}
ExportBinding::ReExport(namespace, mutable, export) => {
let offset = if mutable { 2 } else { 0 };
if &export == exported {
getters
.push(Some(Expr::Lit(Lit::Num(Number::from(1 + offset))).into()));
} else {
getters
.push(Some(Expr::Lit(Lit::Num(Number::from(2 + offset))).into()));
getters.push(Some(
Expr::Lit(Lit::Str(Str {
span: DUMMY_SP,
value: export.as_str().into(),
raw: None,
}))
.into(),
))
}
getters.push(Some(namespace.into()));
}
};
}
}
......
......@@ -24,7 +24,9 @@ __turbopack_context__.s([
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$rename$2d$side$2d$effect$2d$free$2d$facade$2f$input$2f$node_modules$2f$lib$2f$a$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/rename-side-effect-free-facade/input/node_modules/lib/a.js [test] (ecmascript)");
__turbopack_context__.s([
"a0",
()=>__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$rename$2d$side$2d$effect$2d$free$2d$facade$2f$input$2f$node_modules$2f$lib$2f$a$2e$js__$5b$test$5d$__$28$ecmascript$29$__["a"]
2,
"a",
__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$rename$2d$side$2d$effect$2d$free$2d$facade$2f$input$2f$node_modules$2f$lib$2f$a$2e$js__$5b$test$5d$__$28$ecmascript$29$__
]);
}),
]);
......
......@@ -48,6 +48,10 @@ function getOverwrittenModule(moduleCache, id) {
};
}
const BindingTag_Value = 0;
const BindingTag_ReExport = 1;
const BindingTag_RenamedReexport = 2;
const BindingTag_Mutable_ReExport = 3;
const BindingTag_Mutable_RenamedReexport = 4;
/**
* Adds the getters to the exports object.
*/ function esm(exports, bindings) {
......@@ -62,15 +66,37 @@ const BindingTag_Value = 0;
const propName = bindings[i++];
const tagOrFunction = bindings[i++];
if (typeof tagOrFunction === 'number') {
if (tagOrFunction === BindingTag_Value) {
defineProp(exports, propName, {
value: bindings[i++],
enumerable: true,
writable: false
});
} else {
throw new Error(`unexpected tag: ${tagOrFunction}`);
let descriptor;
switch(tagOrFunction){
case BindingTag_Value:
descriptor = {
value: bindings[i++],
enumerable: true,
writable: false
};
break;
case BindingTag_ReExport:
case BindingTag_Mutable_ReExport:
{
const namespace = bindings[i++];
// Note: in the common case we can just copy the descriptor this removes some indirection when
// accesing reexports however the propery may not exist if there is a cycle between a CJS file
// and an ESM module, in that case we just bind a getter and optional setter.
descriptor = Object.getOwnPropertyDescriptor(namespace, propName) ?? makeReexportDescriptor(namespace, propName, tagOrFunction === BindingTag_Mutable_ReExport);
}
break;
case BindingTag_RenamedReexport:
case BindingTag_Mutable_RenamedReexport:
{
const sourceName = bindings[i++];
const namespace = bindings[i++];
descriptor = Object.getOwnPropertyDescriptor(namespace, sourceName) ?? makeReexportDescriptor(namespace, sourceName, tagOrFunction === BindingTag_Mutable_RenamedReexport);
}
break;
default:
throw new Error(`unexpected tag: ${tagOrFunction}`);
}
defineProp(exports, propName, descriptor);
} else {
const getterFn = tagOrFunction;
if (typeof bindings[i] === 'function') {
......@@ -90,6 +116,16 @@ const BindingTag_Value = 0;
}
Object.seal(exports);
}
function makeReexportDescriptor(namespace, propName, mutable) {
const descriptor = {
enumerable: true,
get: createGetter(namespace, propName)
};
if (mutable) {
descriptor.set = createSetter(namespace, propName);
}
return descriptor;
}
/**
* Makes the module an ESM with exports
*/ function esmExport(bindings, id) {
......@@ -175,6 +211,11 @@ contextPrototype.n = exportNamespace;
function createGetter(obj, key) {
return ()=>obj[key];
}
function createSetter(obj, key) {
return (v)=>{
obj[key] = v;
};
}
/**
* @returns prototype of the object
*/ const getProto = Object.getPrototypeOf ? (obj)=>Object.getPrototypeOf(obj) : (obj)=>obj.__proto__;
......
......@@ -58,6 +58,10 @@ function getOverwrittenModule(moduleCache, id) {
};
}
const BindingTag_Value = 0;
const BindingTag_ReExport = 1;
const BindingTag_RenamedReexport = 2;
const BindingTag_Mutable_ReExport = 3;
const BindingTag_Mutable_RenamedReexport = 4;
/**
* Adds the getters to the exports object.
*/ function esm(exports, bindings) {
......@@ -72,15 +76,37 @@ const BindingTag_Value = 0;
const propName = bindings[i++];
const tagOrFunction = bindings[i++];
if (typeof tagOrFunction === 'number') {
if (tagOrFunction === BindingTag_Value) {
defineProp(exports, propName, {
value: bindings[i++],
enumerable: true,
writable: false
});
} else {
throw new Error(`unexpected tag: ${tagOrFunction}`);
let descriptor;
switch(tagOrFunction){
case BindingTag_Value:
descriptor = {
value: bindings[i++],
enumerable: true,
writable: false
};
break;
case BindingTag_ReExport:
case BindingTag_Mutable_ReExport:
{
const namespace = bindings[i++];
// Note: in the common case we can just copy the descriptor this removes some indirection when
// accesing reexports however the propery may not exist if there is a cycle between a CJS file
// and an ESM module, in that case we just bind a getter and optional setter.
descriptor = Object.getOwnPropertyDescriptor(namespace, propName) ?? makeReexportDescriptor(namespace, propName, tagOrFunction === BindingTag_Mutable_ReExport);
}
break;
case BindingTag_RenamedReexport:
case BindingTag_Mutable_RenamedReexport:
{
const sourceName = bindings[i++];
const namespace = bindings[i++];
descriptor = Object.getOwnPropertyDescriptor(namespace, sourceName) ?? makeReexportDescriptor(namespace, sourceName, tagOrFunction === BindingTag_Mutable_RenamedReexport);
}
break;
default:
throw new Error(`unexpected tag: ${tagOrFunction}`);
}
defineProp(exports, propName, descriptor);
} else {
const getterFn = tagOrFunction;
if (typeof bindings[i] === 'function') {
......@@ -100,6 +126,16 @@ const BindingTag_Value = 0;
}
Object.seal(exports);
}
function makeReexportDescriptor(namespace, propName, mutable) {
const descriptor = {
enumerable: true,
get: createGetter(namespace, propName)
};
if (mutable) {
descriptor.set = createSetter(namespace, propName);
}
return descriptor;
}
/**
* Makes the module an ESM with exports
*/ function esmExport(bindings, id) {
......@@ -185,6 +221,11 @@ contextPrototype.n = exportNamespace;
function createGetter(obj, key) {
return ()=>obj[key];
}
function createSetter(obj, key) {
return (v)=>{
obj[key] = v;
};
}
/**
* @returns prototype of the object
*/ const getProto = Object.getPrototypeOf ? (obj)=>Object.getPrototypeOf(obj) : (obj)=>obj.__proto__;
......
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