Commit 4af1ad7c authored by Luke Sandberg's avatar Luke Sandberg

Optimize re-export bindings

Fix an expr
parent 0cc87425
...@@ -105,9 +105,12 @@ function createModuleObject(id: ModuleId): Module { ...@@ -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_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 // an arbitrary sequence of bindings as
// - a prop name // - a prop name
// - BindingTag_Value, a value to be bound directly, or // - BindingTag_Value, a value to be bound directly, or
...@@ -127,15 +130,49 @@ function esm(exports: Exports, bindings: EsmBindings) { ...@@ -127,15 +130,49 @@ function esm(exports: Exports, bindings: EsmBindings) {
const propName = bindings[i++] as string const propName = bindings[i++] as string
const tagOrFunction = bindings[i++] const tagOrFunction = bindings[i++]
if (typeof tagOrFunction === 'number') { if (typeof tagOrFunction === 'number') {
if (tagOrFunction === BindingTag_Value) { let descriptor: PropertyDescriptor
defineProp(exports, propName, { switch (tagOrFunction) {
case BindingTag_Value:
descriptor = {
value: bindings[i++], value: bindings[i++],
enumerable: true, enumerable: true,
writable: false, writable: false,
}) }
} else { 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}`) throw new Error(`unexpected tag: ${tagOrFunction}`)
} }
defineProp(exports, propName, descriptor)
} else { } else {
const getterFn = tagOrFunction as () => unknown const getterFn = tagOrFunction as () => unknown
if (typeof bindings[i] === 'function') { if (typeof bindings[i] === 'function') {
...@@ -156,6 +193,21 @@ function esm(exports: Exports, bindings: EsmBindings) { ...@@ -156,6 +193,21 @@ function esm(exports: Exports, bindings: EsmBindings) {
Object.seal(exports) 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 * Makes the module an ESM with exports
*/ */
...@@ -275,7 +327,11 @@ contextPrototype.n = exportNamespace ...@@ -275,7 +327,11 @@ contextPrototype.n = exportNamespace
function createGetter(obj: Record<string | symbol, any>, key: string | symbol) { function createGetter(obj: Record<string | symbol, any>, key: string | symbol) {
return () => obj[key] return () => obj[key]
} }
function createSetter(obj: Record<string | symbol, any>, key: string | symbol) {
return (v) => {
obj[key] = v
}
}
/** /**
* @returns prototype of the object * @returns prototype of the object
*/ */
......
...@@ -87,6 +87,20 @@ impl ReferencedAssetIdent { ...@@ -87,6 +87,20 @@ impl ReferencedAssetIdent {
ReferencedAssetIdent::LocalBinding { .. } => None, 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> { pub fn as_expr_individual(&self, span: Span) -> Either<Ident, MemberExpr> {
match self { match self {
...@@ -99,6 +113,7 @@ impl ReferencedAssetIdent { ...@@ -99,6 +113,7 @@ impl ReferencedAssetIdent {
namespace_ident, namespace_ident,
ctxt, ctxt,
export, export,
..
} => { } => {
if let Some(export) = export { if let Some(export) = export {
Either::Right(MemberExpr { Either::Right(MemberExpr {
......
...@@ -630,6 +630,8 @@ impl EsmExports { ...@@ -630,6 +630,8 @@ impl EsmExports {
Getter(Expr), Getter(Expr),
GetterSetter(Expr, Expr), GetterSetter(Expr, Expr),
Value(Expr), Value(Expr),
// The namespace expression and the export name
ReExport(Expr, bool, RcStr),
None, None,
} }
...@@ -718,11 +720,12 @@ impl EsmExports { ...@@ -718,11 +720,12 @@ impl EsmExports {
), ),
), ),
} }
}, },
ReferencedAssetIdent::Module { namespace_ident:_, ctxt:_, export:_ } => { ReferencedAssetIdent::Module { namespace_ident:_, ctxt:_, export } => {
// Otherwise we need to bind as a getter to preserve the 'liveness' of the other modules bindings.
// TODO: If this becomes important it might be faster to use the runtime to copy PropertyDescriptors across modules if export_usage_info.is_circuit_breaker {
// since that would reduce allocations and optimize access. We could do this by passing the module-id up. // 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!( let getter = quote!(
"() => $expr" as Expr, "() => $expr" as Expr,
expr: Expr = read_expr, expr: Expr = read_expr,
...@@ -743,9 +746,17 @@ impl EsmExports { ...@@ -743,9 +746,17 @@ impl EsmExports {
} else { } else {
ExportBinding::Getter(getter) 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) }
}})
.unwrap_or(ExportBinding::None)
} }
EsmExport::ImportedNamespace(esm_ref) => { EsmExport::ImportedNamespace(esm_ref) => {
let referenced_asset = let referenced_asset =
...@@ -756,6 +767,10 @@ impl EsmExports { ...@@ -756,6 +767,10 @@ impl EsmExports {
.map(|ident| { .map(|ident| {
let imported = ident.as_expr(DUMMY_SP, false); let imported = ident.as_expr(DUMMY_SP, false);
if export_usage_info.is_circuit_breaker { 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!( ExportBinding::Getter(quote!(
"(() => $imported)" as Expr, "(() => $imported)" as Expr,
imported: Expr = imported imported: Expr = imported
...@@ -791,6 +806,25 @@ impl EsmExports { ...@@ -791,6 +806,25 @@ impl EsmExports {
getters.push(Some(value.into())); getters.push(Some(value.into()));
} }
ExportBinding::None => {} 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([ ...@@ -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)"); 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([ __turbopack_context__.s([
"a0", "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) { ...@@ -48,6 +48,10 @@ function getOverwrittenModule(moduleCache, id) {
}; };
} }
const BindingTag_Value = 0; 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. * Adds the getters to the exports object.
*/ function esm(exports, bindings) { */ function esm(exports, bindings) {
...@@ -62,15 +66,37 @@ const BindingTag_Value = 0; ...@@ -62,15 +66,37 @@ const BindingTag_Value = 0;
const propName = bindings[i++]; const propName = bindings[i++];
const tagOrFunction = bindings[i++]; const tagOrFunction = bindings[i++];
if (typeof tagOrFunction === 'number') { if (typeof tagOrFunction === 'number') {
if (tagOrFunction === BindingTag_Value) { let descriptor;
defineProp(exports, propName, { switch(tagOrFunction){
case BindingTag_Value:
descriptor = {
value: bindings[i++], value: bindings[i++],
enumerable: true, enumerable: true,
writable: false writable: false
}); };
} else { 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}`); throw new Error(`unexpected tag: ${tagOrFunction}`);
} }
defineProp(exports, propName, descriptor);
} else { } else {
const getterFn = tagOrFunction; const getterFn = tagOrFunction;
if (typeof bindings[i] === 'function') { if (typeof bindings[i] === 'function') {
...@@ -90,6 +116,16 @@ const BindingTag_Value = 0; ...@@ -90,6 +116,16 @@ const BindingTag_Value = 0;
} }
Object.seal(exports); 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 * Makes the module an ESM with exports
*/ function esmExport(bindings, id) { */ function esmExport(bindings, id) {
...@@ -175,6 +211,11 @@ contextPrototype.n = exportNamespace; ...@@ -175,6 +211,11 @@ contextPrototype.n = exportNamespace;
function createGetter(obj, key) { function createGetter(obj, key) {
return ()=>obj[key]; return ()=>obj[key];
} }
function createSetter(obj, key) {
return (v)=>{
obj[key] = v;
};
}
/** /**
* @returns prototype of the object * @returns prototype of the object
*/ const getProto = Object.getPrototypeOf ? (obj)=>Object.getPrototypeOf(obj) : (obj)=>obj.__proto__; */ const getProto = Object.getPrototypeOf ? (obj)=>Object.getPrototypeOf(obj) : (obj)=>obj.__proto__;
......
...@@ -58,6 +58,10 @@ function getOverwrittenModule(moduleCache, id) { ...@@ -58,6 +58,10 @@ function getOverwrittenModule(moduleCache, id) {
}; };
} }
const BindingTag_Value = 0; 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. * Adds the getters to the exports object.
*/ function esm(exports, bindings) { */ function esm(exports, bindings) {
...@@ -72,15 +76,37 @@ const BindingTag_Value = 0; ...@@ -72,15 +76,37 @@ const BindingTag_Value = 0;
const propName = bindings[i++]; const propName = bindings[i++];
const tagOrFunction = bindings[i++]; const tagOrFunction = bindings[i++];
if (typeof tagOrFunction === 'number') { if (typeof tagOrFunction === 'number') {
if (tagOrFunction === BindingTag_Value) { let descriptor;
defineProp(exports, propName, { switch(tagOrFunction){
case BindingTag_Value:
descriptor = {
value: bindings[i++], value: bindings[i++],
enumerable: true, enumerable: true,
writable: false writable: false
}); };
} else { 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}`); throw new Error(`unexpected tag: ${tagOrFunction}`);
} }
defineProp(exports, propName, descriptor);
} else { } else {
const getterFn = tagOrFunction; const getterFn = tagOrFunction;
if (typeof bindings[i] === 'function') { if (typeof bindings[i] === 'function') {
...@@ -100,6 +126,16 @@ const BindingTag_Value = 0; ...@@ -100,6 +126,16 @@ const BindingTag_Value = 0;
} }
Object.seal(exports); 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 * Makes the module an ESM with exports
*/ function esmExport(bindings, id) { */ function esmExport(bindings, id) {
...@@ -185,6 +221,11 @@ contextPrototype.n = exportNamespace; ...@@ -185,6 +221,11 @@ contextPrototype.n = exportNamespace;
function createGetter(obj, key) { function createGetter(obj, key) {
return ()=>obj[key]; return ()=>obj[key];
} }
function createSetter(obj, key) {
return (v)=>{
obj[key] = v;
};
}
/** /**
* @returns prototype of the object * @returns prototype of the object
*/ const getProto = Object.getPrototypeOf ? (obj)=>Object.getPrototypeOf(obj) : (obj)=>obj.__proto__; */ 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