Unverified Commit 67ec3ad9 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: expose used export info in tests (#86037)

This will allow us to reuse more Webpack tests soon
```js
module.exports = [
"[project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/code-gen/exports-info/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";

// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/code-gen/exports-info/input/module.js [test] (ecmascript)
;
const __TURBOPACK__$5f$_webpack_exports_info_$5f$__ = {
    "bar": {
        used: false
    },
    "foo": {
        used: true
    },
    "usage": {
        used: true
    }
};
const foo = 'foo';
const bar = 'bar';
const usage = __TURBOPACK__$5f$_webpack_exports_info_$5f$__;
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/code-gen/exports-info/input/index.js [test] (ecmascript)
;
;
it('should expose __webpack_exports_info__ in tests', ()=>{
    expect(foo).toBe('foo');
    expect(usage.foo.used).toBe(true);
    expect(usage.bar.used).toBe(false);
    expect(usage.usage.used).toBe(true);
});
__turbopack_context__.s([], "[project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/code-gen/exports-info/input/index.js [test] (ecmascript)");
}),
];
```
parent 291aefd9
...@@ -16,6 +16,7 @@ use turbopack_core::{chunk::ChunkingContext, reference::ModuleReference}; ...@@ -16,6 +16,7 @@ use turbopack_core::{chunk::ChunkingContext, reference::ModuleReference};
use crate::{ use crate::{
ScopeHoistingContext, ScopeHoistingContext,
chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
references::{ references::{
AstPath, AstPath,
amd::AmdDefineWithDependenciesCodeGen, amd::AmdDefineWithDependenciesCodeGen,
...@@ -31,6 +32,7 @@ use crate::{ ...@@ -31,6 +32,7 @@ use crate::{
dynamic::EsmAsyncAssetReferenceCodeGen, module_id::EsmModuleIdAssetReferenceCodeGen, dynamic::EsmAsyncAssetReferenceCodeGen, module_id::EsmModuleIdAssetReferenceCodeGen,
url::UrlAssetReferenceCodeGen, url::UrlAssetReferenceCodeGen,
}, },
exports_info::{ExportsInfoBinding, ExportsInfoRef},
ident::IdentReplacement, ident::IdentReplacement,
member::MemberReplacement, member::MemberReplacement,
require_context::RequireContextAssetReferenceCodeGen, require_context::RequireContextAssetReferenceCodeGen,
...@@ -181,6 +183,8 @@ pub enum CodeGen { ...@@ -181,6 +183,8 @@ pub enum CodeGen {
DynamicExpression(DynamicExpression), DynamicExpression(DynamicExpression),
EsmBinding(EsmBinding), EsmBinding(EsmBinding),
EsmModuleItem(EsmModuleItem), EsmModuleItem(EsmModuleItem),
ExportsInfoBinding(ExportsInfoBinding),
ExportsInfoRef(ExportsInfoRef),
IdentReplacement(IdentReplacement), IdentReplacement(IdentReplacement),
ImportMetaBinding(ImportMetaBinding), ImportMetaBinding(ImportMetaBinding),
ImportMetaRef(ImportMetaRef), ImportMetaRef(ImportMetaRef),
...@@ -200,6 +204,8 @@ impl CodeGen { ...@@ -200,6 +204,8 @@ impl CodeGen {
&self, &self,
ctx: Vc<Box<dyn ChunkingContext>>, ctx: Vc<Box<dyn ChunkingContext>>,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
exports: ResolvedVc<EcmascriptExports>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
match self { match self {
Self::AmdDefineWithDependenciesCodeGen(v) => v.code_generation(ctx).await, Self::AmdDefineWithDependenciesCodeGen(v) => v.code_generation(ctx).await,
...@@ -209,6 +215,8 @@ impl CodeGen { ...@@ -209,6 +215,8 @@ impl CodeGen {
Self::DynamicExpression(v) => v.code_generation(ctx).await, Self::DynamicExpression(v) => v.code_generation(ctx).await,
Self::EsmBinding(v) => v.code_generation(ctx, scope_hoisting_context).await, Self::EsmBinding(v) => v.code_generation(ctx, scope_hoisting_context).await,
Self::EsmModuleItem(v) => v.code_generation(ctx).await, Self::EsmModuleItem(v) => v.code_generation(ctx).await,
Self::ExportsInfoBinding(v) => v.code_generation(ctx, module, exports).await,
Self::ExportsInfoRef(v) => v.code_generation(ctx).await,
Self::IdentReplacement(v) => v.code_generation(ctx).await, Self::IdentReplacement(v) => v.code_generation(ctx).await,
Self::ImportMetaBinding(v) => v.code_generation(ctx).await, Self::ImportMetaBinding(v) => v.code_generation(ctx).await,
Self::ImportMetaRef(v) => v.code_generation(ctx).await, Self::ImportMetaRef(v) => v.code_generation(ctx).await,
......
...@@ -270,6 +270,8 @@ pub struct EcmascriptOptions { ...@@ -270,6 +270,8 @@ pub struct EcmascriptOptions {
// node_modules. // node_modules.
/// Whether to replace `typeof window` with some constant value. /// Whether to replace `typeof window` with some constant value.
pub enable_typeof_window_inlining: Option<TypeofWindow>, pub enable_typeof_window_inlining: Option<TypeofWindow>,
/// Whether to allow accessing exports info via `__webpack_exports_info__`.
pub enable_exports_info_inlining: bool,
pub inline_helpers: bool, pub inline_helpers: bool,
} }
...@@ -1025,7 +1027,14 @@ impl EcmascriptModuleContentOptions { ...@@ -1025,7 +1027,14 @@ impl EcmascriptModuleContentOptions {
let code_gens = code_generation let code_gens = code_generation
.await? .await?
.iter() .iter()
.map(|c| c.code_generation(**chunking_context, scope_hoisting_context)) .map(|c| {
c.code_generation(
**chunking_context,
scope_hoisting_context,
*module,
*exports,
)
})
.try_join() .try_join()
.await?; .await?;
......
use anyhow::Result;
use serde::{Deserialize, Serialize};
use swc_core::{
common::DUMMY_SP,
ecma::ast::{Expr, Ident, KeyValueProp, ObjectLit, PropName, PropOrSpread},
quote,
};
use turbo_rcstr::rcstr;
use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, debug::ValueDebugFormat, trace::TraceRawVcs};
use turbopack_core::chunk::ChunkingContext;
use crate::{
chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
code_gen::{CodeGen, CodeGeneration},
create_visitor, magic_identifier,
references::AstPath,
};
/// Responsible for initializing the `ExportsInfoBinding` object binding, so that it may be
/// referenced in the the file.
///
/// There can be many references, and they appear at any nesting in the file. But we must only
/// initialize the binding a single time.
///
/// This singleton behavior must be enforced by the caller!
#[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
pub struct ExportsInfoBinding {}
impl ExportsInfoBinding {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
ExportsInfoBinding {}
}
pub async fn code_generation(
&self,
chunking_context: Vc<Box<dyn ChunkingContext>>,
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
exports: ResolvedVc<EcmascriptExports>,
) -> Result<CodeGeneration> {
let export_usage_info = chunking_context
.module_export_usage(*ResolvedVc::upcast(module))
.await?;
let export_usage_info = export_usage_info.export_usage.await?;
let props = if let EcmascriptExports::EsmExports(exports) = &*exports.await? {
exports
.await?
.exports
.keys()
.map(|e| {
let used: Expr = export_usage_info.is_export_used(e).into();
PropOrSpread::Prop(Box::new(swc_core::ecma::ast::Prop::KeyValue(
KeyValueProp {
key: PropName::Str(e.as_str().into()),
value: quote!("{ used: $v }" as Box<Expr>, v: Expr = used),
},
)))
})
.collect()
} else {
vec![]
};
let data = Expr::Object(ObjectLit {
props,
span: DUMMY_SP,
});
Ok(CodeGeneration::hoisted_stmt(
rcstr!("__webpack_exports_info__"),
quote!(
"const $name = $data;" as Stmt,
name = exports_ident(),
data: Expr = data
),
))
}
}
impl From<ExportsInfoBinding> for CodeGen {
fn from(val: ExportsInfoBinding) -> Self {
CodeGen::ExportsInfoBinding(val)
}
}
/// Handles rewriting `__webpack_exports_info__` references into the injected binding created by
/// ExportsInfoBinding.
///
/// There can be many references, and they appear at any nesting in the file. But all references
/// refer to the same mutable object.
#[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
pub struct ExportsInfoRef {
ast_path: AstPath,
}
impl ExportsInfoRef {
pub fn new(ast_path: AstPath) -> Self {
ExportsInfoRef { ast_path }
}
pub async fn code_generation(
&self,
_chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> {
let visitor = create_visitor!(self.ast_path, visit_mut_expr, |expr: &mut Expr| {
*expr = Expr::Ident(exports_ident());
});
Ok(CodeGeneration::visitors(vec![visitor]))
}
}
impl From<ExportsInfoRef> for CodeGen {
fn from(val: ExportsInfoRef) -> Self {
CodeGen::ExportsInfoRef(val)
}
}
fn exports_ident() -> Ident {
Ident::new(
magic_identifier::mangle("__webpack_exports_info__").into(),
DUMMY_SP,
Default::default(),
)
}
...@@ -5,6 +5,7 @@ pub mod constant_condition; ...@@ -5,6 +5,7 @@ pub mod constant_condition;
pub mod constant_value; pub mod constant_value;
pub mod dynamic_expression; pub mod dynamic_expression;
pub mod esm; pub mod esm;
pub mod exports_info;
pub mod external_module; pub mod external_module;
pub mod ident; pub mod ident;
pub mod member; pub mod member;
...@@ -149,6 +150,7 @@ use crate::{ ...@@ -149,6 +150,7 @@ use crate::{
EsmBinding, UrlRewriteBehavior, base::EsmAssetReferences, EsmBinding, UrlRewriteBehavior, base::EsmAssetReferences,
module_id::EsmModuleIdAssetReference, module_id::EsmModuleIdAssetReference,
}, },
exports_info::{ExportsInfoBinding, ExportsInfoRef},
ident::IdentReplacement, ident::IdentReplacement,
member::MemberReplacement, member::MemberReplacement,
node::{FilePathModuleReference, PackageJsonReference}, node::{FilePathModuleReference, PackageJsonReference},
...@@ -441,6 +443,9 @@ struct AnalysisState<'a> { ...@@ -441,6 +443,9 @@ struct AnalysisState<'a> {
// There can be many references to import.meta, but only the first should hoist // There can be many references to import.meta, but only the first should hoist
// the object allocation. // the object allocation.
first_import_meta: bool, first_import_meta: bool,
// There can be many references to __webpack_exports_info__, but only the first should hoist
// the object allocation.
first_webpack_exports_info: bool,
tree_shaking_mode: Option<TreeShakingMode>, tree_shaking_mode: Option<TreeShakingMode>,
import_externals: bool, import_externals: bool,
ignore_dynamic_requests: bool, ignore_dynamic_requests: bool,
...@@ -978,6 +983,7 @@ async fn analyze_ecmascript_module_internal( ...@@ -978,6 +983,7 @@ async fn analyze_ecmascript_module_internal(
fun_args_values: Default::default(), fun_args_values: Default::default(),
var_cache: Default::default(), var_cache: Default::default(),
first_import_meta: true, first_import_meta: true,
first_webpack_exports_info: true,
tree_shaking_mode: options.tree_shaking_mode, tree_shaking_mode: options.tree_shaking_mode,
import_externals: options.import_externals, import_externals: options.import_externals,
ignore_dynamic_requests: options.ignore_dynamic_requests, ignore_dynamic_requests: options.ignore_dynamic_requests,
...@@ -1305,6 +1311,15 @@ async fn analyze_ecmascript_module_internal( ...@@ -1305,6 +1311,15 @@ async fn analyze_ecmascript_module_internal(
"unexpected Effect::FreeVar in tracing mode" "unexpected Effect::FreeVar in tracing mode"
); );
if options.enable_exports_info_inlining && var == "__webpack_exports_info__" {
if analysis_state.first_webpack_exports_info {
analysis_state.first_webpack_exports_info = false;
analysis.add_code_gen(ExportsInfoBinding::new());
}
analysis.add_code_gen(ExportsInfoRef::new(ast_path.into()));
continue;
}
// FreeVar("require") might be turbopackIgnore-d // FreeVar("require") might be turbopackIgnore-d
if !analysis_state if !analysis_state
.link_value( .link_value(
......
...@@ -403,6 +403,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V ...@@ -403,6 +403,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
TypescriptTransformOptions::default().resolved_cell(), TypescriptTransformOptions::default().resolved_cell(),
), ),
import_externals: true, import_externals: true,
enable_exports_info_inlining: true,
..Default::default() ..Default::default()
}, },
environment: Some(env), environment: Some(env),
......
import { foo, usage } from './module.js'
it('should expose __webpack_exports_info__ in tests', () => {
expect(foo).toBe('foo')
expect(usage.foo.used).toBe(true)
expect(usage.bar.used).toBe(false)
expect(usage.usage.used).toBe(true)
})
export const foo = 'foo'
export const bar = 'bar'
export const usage = __webpack_exports_info__
...@@ -355,6 +355,7 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> { ...@@ -355,6 +355,7 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
..Default::default() ..Default::default()
})), })),
ignore_dynamic_requests: true, ignore_dynamic_requests: true,
enable_exports_info_inlining: true,
..Default::default() ..Default::default()
}, },
environment: Some(env), environment: Some(env),
......
...@@ -208,6 +208,7 @@ impl ModuleOptions { ...@@ -208,6 +208,7 @@ impl ModuleOptions {
import_externals, import_externals,
esm_url_rewrite_behavior, esm_url_rewrite_behavior,
enable_typeof_window_inlining, enable_typeof_window_inlining,
enable_exports_info_inlining,
source_maps: ecmascript_source_maps, source_maps: ecmascript_source_maps,
inline_helpers, inline_helpers,
.. ..
...@@ -283,6 +284,7 @@ impl ModuleOptions { ...@@ -283,6 +284,7 @@ impl ModuleOptions {
keep_last_successful_parse, keep_last_successful_parse,
analyze_mode, analyze_mode,
enable_typeof_window_inlining, enable_typeof_window_inlining,
enable_exports_info_inlining,
inline_helpers, inline_helpers,
..Default::default() ..Default::default()
}; };
......
...@@ -239,6 +239,9 @@ pub struct EcmascriptOptionsContext { ...@@ -239,6 +239,9 @@ pub struct EcmascriptOptionsContext {
/// Specifies how Source Maps are handled. /// Specifies how Source Maps are handled.
pub source_maps: SourceMapsType, pub source_maps: SourceMapsType,
/// Whether to allow accessing exports info via `__webpack_exports_info__`.
pub enable_exports_info_inlining: bool,
// TODO should this be a part of Environment instead? // TODO should this be a part of Environment instead?
pub inline_helpers: bool, pub inline_helpers: bool,
......
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