Unverified Commit 477eaf0e authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: don't cell CodeGen-s (#75513)

No need to cell them, they are module-specific anyway.

```
testing against 0293c96cf32

canary dd676ccb:
14,7 GB
TURBO_ENGINE_READ_ONLY=1 NEXT_TURBOPACK_TRACING= TURBOPACK=1 TURBOPACK_BUILD=  533.84s user 84.44s system 834% cpu 1:14.10 total
TURBO_ENGINE_READ_ONLY=1 NEXT_TURBOPACK_TRACING= TURBOPACK=1 TURBOPACK_BUILD=  526.68s user 86.15s system 834% cpu 1:13.48 total

plus fewer cells b5ce9afeb5:
14,3 GB
TURBO_ENGINE_READ_ONLY=1 NEXT_TURBOPACK_TRACING= TURBOPACK=1 TURBOPACK_BUILD=  517.74s user 85.77s system 831% cpu 1:12.54 total
TURBO_ENGINE_READ_ONLY=1 NEXT_TURBOPACK_TRACING= TURBOPACK=1 TURBOPACK_BUILD=  516.06s user 85.35s system 836% cpu 1:11.89 total

plus no self reads b3370a59ca:
13,8 GB
TURBO_ENGINE_READ_ONLY=1 NEXT_TURBOPACK_TRACING= TURBOPACK=1 TURBOPACK_BUILD=  516.65s user 84.11s system 834% cpu 1:12.01 total
TURBO_ENGINE_READ_ONLY=1 NEXT_TURBOPACK_TRACING= TURBOPACK=1 TURBOPACK_BUILD=  518.01s user 87.55s system 839% cpu 1:12.15 total
```

<details>
<summary>Old</summary>

```
canary 82026906:
15,3gb
492.59s user 103.43s system 736% cpu 1:20.90 total
495.16s user 96.50s system 739% cpu 1:20.01 total

code-gen bd58ad63a7:
14,95gb
489.30s user 102.66s system 745% cpu 1:19.36 total
501.91s user 105.99s system 743% cpu 1:21.80 total
```

</details>
parent 0cff3757
...@@ -9653,6 +9653,7 @@ dependencies = [ ...@@ -9653,6 +9653,7 @@ dependencies = [
"sourcemap", "sourcemap",
"strsim 0.11.1", "strsim 0.11.1",
"swc_core", "swc_core",
"swc_ecma_visit",
"tokio", "tokio",
"tracing", "tracing",
"turbo-rcstr", "turbo-rcstr",
......
...@@ -67,6 +67,7 @@ swc_core = { workspace = true, features = [ ...@@ -67,6 +67,7 @@ swc_core = { workspace = true, features = [
"testing", "testing",
"base", "base",
] } ] }
swc_ecma_visit = { version = "5.0.0", features = ["serde-impl"] }
[dev-dependencies] [dev-dependencies]
criterion = { workspace = true, features = ["async_tokio"] } criterion = { workspace = true, features = ["async_tokio"] }
......
...@@ -5,10 +5,19 @@ use swc_core::ecma::{ ...@@ -5,10 +5,19 @@ use swc_core::ecma::{
visit::{AstParentKind, VisitMut}, visit::{AstParentKind, VisitMut},
}; };
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, ResolvedVc, Vc}; use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, Vc};
use turbopack_core::{ use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph};
chunk::{AsyncModuleInfo, ChunkingContext},
module_graph::ModuleGraph, use crate::references::{
amd::AmdDefineWithDependenciesCodeGen,
cjs::CjsRequireCacheAccess,
constant_condition::ConstantConditionCodeGen,
constant_value::ConstantValueCodeGen,
dynamic_expression::DynamicExpression,
esm::{EsmBinding, EsmModuleItem, ImportMetaBinding, ImportMetaRef},
ident::IdentReplacement,
member::MemberReplacement,
unreachable::Unreachable,
}; };
/// impl of code generation inferred from a ModuleReference. /// impl of code generation inferred from a ModuleReference.
...@@ -41,37 +50,33 @@ impl CodeGeneration { ...@@ -41,37 +50,33 @@ impl CodeGeneration {
visitors: Vec<(Vec<AstParentKind>, Box<dyn VisitorFactory>)>, visitors: Vec<(Vec<AstParentKind>, Box<dyn VisitorFactory>)>,
hoisted_stmts: Vec<CodeGenerationHoistedStmt>, hoisted_stmts: Vec<CodeGenerationHoistedStmt>,
early_hoisted_stmts: Vec<CodeGenerationHoistedStmt>, early_hoisted_stmts: Vec<CodeGenerationHoistedStmt>,
) -> Vc<Self> { ) -> Self {
CodeGeneration { CodeGeneration {
visitors, visitors,
hoisted_stmts, hoisted_stmts,
early_hoisted_stmts, early_hoisted_stmts,
} }
.cell()
} }
pub fn visitors(visitors: Vec<(Vec<AstParentKind>, Box<dyn VisitorFactory>)>) -> Vc<Self> { pub fn visitors(visitors: Vec<(Vec<AstParentKind>, Box<dyn VisitorFactory>)>) -> Self {
CodeGeneration { CodeGeneration {
visitors, visitors,
..Default::default() ..Default::default()
} }
.cell()
} }
pub fn hoisted_stmt(key: RcStr, stmt: Stmt) -> Vc<Self> { pub fn hoisted_stmt(key: RcStr, stmt: Stmt) -> Self {
CodeGeneration { CodeGeneration {
hoisted_stmts: vec![CodeGenerationHoistedStmt::new(key, stmt)], hoisted_stmts: vec![CodeGenerationHoistedStmt::new(key, stmt)],
..Default::default() ..Default::default()
} }
.cell()
} }
pub fn hoisted_stmts(hoisted_stmts: Vec<CodeGenerationHoistedStmt>) -> Vc<Self> { pub fn hoisted_stmts(hoisted_stmts: Vec<CodeGenerationHoistedStmt>) -> Self {
CodeGeneration { CodeGeneration {
hoisted_stmts, hoisted_stmts,
..Default::default() ..Default::default()
} }
.cell()
} }
} }
...@@ -102,42 +107,47 @@ pub trait CodeGenerateable { ...@@ -102,42 +107,47 @@ pub trait CodeGenerateable {
) -> Vc<CodeGeneration>; ) -> Vc<CodeGeneration>;
} }
#[turbo_tasks::value_trait] #[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
pub trait CodeGenerateableWithAsyncModuleInfo { pub enum CodeGen {
fn code_generation( AmdDefineWithDependenciesCodeGen(AmdDefineWithDependenciesCodeGen),
self: Vc<Self>, CjsRequireCacheAccess(CjsRequireCacheAccess),
module_graph: Vc<ModuleGraph>, ConstantConditionCodeGen(ConstantConditionCodeGen),
chunking_context: Vc<Box<dyn ChunkingContext>>, ConstantValueCodeGen(ConstantValueCodeGen),
async_module_info: Option<Vc<AsyncModuleInfo>>, DynamicExpression(DynamicExpression),
) -> Vc<CodeGeneration>; EsmBinding(EsmBinding),
} EsmModuleItem(EsmModuleItem),
IdentReplacement(IdentReplacement),
pub enum UnresolvedCodeGen { ImportMetaBinding(ImportMetaBinding),
CodeGenerateable(Vc<Box<dyn CodeGenerateable>>), ImportMetaRef(ImportMetaRef),
CodeGenerateableWithAsyncModuleInfo(Vc<Box<dyn CodeGenerateableWithAsyncModuleInfo>>), MemberReplacement(MemberReplacement),
Unreachable(Unreachable),
} }
impl UnresolvedCodeGen { impl CodeGen {
pub async fn to_resolved(&self) -> Result<CodeGen> { pub async fn code_generation(
Ok(match self { &self,
Self::CodeGenerateable(vc) => CodeGen::CodeGenerateable(vc.to_resolved().await?), g: Vc<ModuleGraph>,
Self::CodeGenerateableWithAsyncModuleInfo(vc) => { ctx: Vc<Box<dyn ChunkingContext>>,
CodeGen::CodeGenerateableWithAsyncModuleInfo(vc.to_resolved().await?) ) -> Result<CodeGeneration> {
} match self {
}) Self::AmdDefineWithDependenciesCodeGen(v) => v.code_generation(g, ctx).await,
Self::CjsRequireCacheAccess(v) => v.code_generation(g, ctx).await,
Self::ConstantConditionCodeGen(v) => v.code_generation(g, ctx).await,
Self::ConstantValueCodeGen(v) => v.code_generation(g, ctx).await,
Self::DynamicExpression(v) => v.code_generation(g, ctx).await,
Self::EsmBinding(v) => v.code_generation(g, ctx).await,
Self::EsmModuleItem(v) => v.code_generation(g, ctx).await,
Self::IdentReplacement(v) => v.code_generation(g, ctx).await,
Self::ImportMetaBinding(v) => v.code_generation(g, ctx).await,
Self::ImportMetaRef(v) => v.code_generation(g, ctx).await,
Self::MemberReplacement(v) => v.code_generation(g, ctx).await,
Self::Unreachable(v) => v.code_generation(g, ctx).await,
}
} }
} }
#[derive(
Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue,
)]
pub enum CodeGen {
CodeGenerateable(ResolvedVc<Box<dyn CodeGenerateable>>),
CodeGenerateableWithAsyncModuleInfo(ResolvedVc<Box<dyn CodeGenerateableWithAsyncModuleInfo>>),
}
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct CodeGenerateables(Vec<CodeGen>); pub struct CodeGens(Vec<CodeGen>);
pub fn path_to( pub fn path_to(
path: &[AstParentKind], path: &[AstParentKind],
......
...@@ -87,12 +87,10 @@ use turbopack_core::{ ...@@ -87,12 +87,10 @@ use turbopack_core::{
// TODO remove this // TODO remove this
pub use turbopack_resolve::ecmascript as resolve; pub use turbopack_resolve::ecmascript as resolve;
use self::{ use self::chunk::{EcmascriptChunkItemContent, EcmascriptChunkType, EcmascriptExports};
chunk::{EcmascriptChunkItemContent, EcmascriptChunkType, EcmascriptExports},
code_gen::{CodeGen, CodeGenerateableWithAsyncModuleInfo, CodeGenerateables},
};
use crate::{ use crate::{
chunk::EcmascriptChunkPlaceable, chunk::EcmascriptChunkPlaceable,
code_gen::CodeGens,
references::{analyse_ecmascript_module, async_module::OptionAsyncModule}, references::{analyse_ecmascript_module, async_module::OptionAsyncModule},
transform::remove_shebang, transform::remove_shebang,
}; };
...@@ -757,64 +755,45 @@ impl EcmascriptModuleContent { ...@@ -757,64 +755,45 @@ impl EcmascriptModuleContent {
module_graph: Vc<ModuleGraph>, module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
references: Vc<ModuleReferences>, references: Vc<ModuleReferences>,
code_generation: Vc<CodeGenerateables>, code_generation: Vc<CodeGens>,
async_module: Vc<OptionAsyncModule>, async_module: Vc<OptionAsyncModule>,
generate_source_map: Vc<bool>, generate_source_map: Vc<bool>,
original_source_map: ResolvedVc<OptionSourceMap>, original_source_map: ResolvedVc<OptionSourceMap>,
exports: Vc<EcmascriptExports>, exports: Vc<EcmascriptExports>,
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
) -> Result<Vc<Self>> { ) -> Result<Vc<Self>> {
let mut code_gens = Vec::new(); let mut code_gen_cells = Vec::new();
for r in references.await?.iter() { for r in references.await?.iter() {
let r = r.resolve().await?; if let Some(code_gen) = ResolvedVc::try_sidecast::<Box<dyn CodeGenerateable>>(*r) {
if let Some(code_gen) = code_gen_cells.push(code_gen.code_generation(module_graph, chunking_context));
ResolvedVc::try_sidecast::<Box<dyn CodeGenerateableWithAsyncModuleInfo>>(r)
{
code_gens.push(code_gen.code_generation(
module_graph,
chunking_context,
async_module_info,
));
} else if let Some(code_gen) = ResolvedVc::try_sidecast::<Box<dyn CodeGenerateable>>(r)
{
code_gens.push(code_gen.code_generation(module_graph, chunking_context));
} }
} }
if let Some(async_module) = *async_module.await? { if let Some(async_module) = *async_module.await? {
code_gens.push(async_module.code_generation( code_gen_cells.push(async_module.code_generation(
async_module_info, async_module_info,
references, references,
module_graph, module_graph,
chunking_context, chunking_context,
)); ));
} }
for c in code_generation.await?.iter() {
match c {
CodeGen::CodeGenerateable(c) => {
code_gens.push(c.code_generation(module_graph, chunking_context));
}
CodeGen::CodeGenerateableWithAsyncModuleInfo(c) => {
code_gens.push(c.code_generation(
module_graph,
chunking_context,
async_module_info,
));
}
}
}
if let EcmascriptExports::EsmExports(exports) = *exports.await? { if let EcmascriptExports::EsmExports(exports) = *exports.await? {
code_gens.push(exports.code_generation(module_graph, chunking_context)); code_gen_cells.push(exports.code_generation(module_graph, chunking_context));
} }
// need to keep that around to allow references into that let code_gens = code_generation
let code_gens = code_gens.into_iter().try_join().await?; .await?
let code_gens = code_gens.iter().map(|cg| &**cg).collect::<Vec<_>>(); .iter()
.map(|c| c.code_generation(module_graph, chunking_context))
.try_join()
.await?;
let code_gen_cells = code_gen_cells.into_iter().try_join().await?;
let code_gens = code_gen_cells.iter().map(|c| &**c).chain(code_gens.iter());
gen_content_with_code_gens( gen_content_with_code_gens(
parsed, parsed,
ident, ident,
specified_module_type, specified_module_type,
&code_gens, code_gens,
generate_source_map, generate_source_map,
original_source_map, original_source_map,
) )
...@@ -845,7 +824,7 @@ async fn gen_content_with_code_gens( ...@@ -845,7 +824,7 @@ async fn gen_content_with_code_gens(
parsed: ResolvedVc<ParseResult>, parsed: ResolvedVc<ParseResult>,
ident: ResolvedVc<AssetIdent>, ident: ResolvedVc<AssetIdent>,
specified_module_type: SpecifiedModuleType, specified_module_type: SpecifiedModuleType,
code_gens: &[&CodeGeneration], code_gens: impl IntoIterator<Item = &CodeGeneration>,
generate_source_map: Vc<bool>, generate_source_map: Vc<bool>,
original_source_map: ResolvedVc<OptionSourceMap>, original_source_map: ResolvedVc<OptionSourceMap>,
) -> Result<Vc<EcmascriptModuleContent>> { ) -> Result<Vc<EcmascriptModuleContent>> {
...@@ -938,11 +917,11 @@ async fn gen_content_with_code_gens( ...@@ -938,11 +917,11 @@ async fn gen_content_with_code_gens(
} }
} }
fn process_content_with_code_gens( fn process_content_with_code_gens<'a>(
program: &mut Program, program: &mut Program,
globals: &Globals, globals: &Globals,
top_level_mark: Option<Mark>, top_level_mark: Option<Mark>,
code_gens: &[&CodeGeneration], code_gens: impl IntoIterator<Item = &'a CodeGeneration>,
) { ) {
let mut visitors = Vec::new(); let mut visitors = Vec::new();
let mut root_visitors = Vec::new(); let mut root_visitors = Vec::new();
......
...@@ -13,7 +13,7 @@ use swc_core::{ ...@@ -13,7 +13,7 @@ use swc_core::{
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ use turbo_tasks::{
debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, ReadRef, ResolvedVc, debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, ReadRef, ResolvedVc,
TryJoinIterExt, Value, ValueToString, Vc, TryJoinIterExt, ValueToString, Vc,
}; };
use turbopack_core::{ use turbopack_core::{
chunk::{ChunkableModuleReference, ChunkingContext}, chunk::{ChunkableModuleReference, ChunkingContext},
...@@ -24,11 +24,13 @@ use turbopack_core::{ ...@@ -24,11 +24,13 @@ use turbopack_core::{
}; };
use turbopack_resolve::ecmascript::cjs_resolve; use turbopack_resolve::ecmascript::cjs_resolve;
use super::pattern_mapping::{PatternMapping, ResolveType::ChunkItem};
use crate::{ use crate::{
code_gen::{CodeGenerateable, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
references::AstPath, references::{
pattern_mapping::{PatternMapping, ResolveType},
AstPath,
},
runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_REQUIRE}, runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_REQUIRE},
}; };
...@@ -124,12 +126,11 @@ pub enum AmdDefineFactoryType { ...@@ -124,12 +126,11 @@ pub enum AmdDefineFactoryType {
Value, Value,
} }
#[turbo_tasks::value(shared)] #[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
#[derive(Debug)]
pub struct AmdDefineWithDependenciesCodeGen { pub struct AmdDefineWithDependenciesCodeGen {
dependencies_requests: Vec<AmdDefineDependencyElement>, dependencies_requests: Vec<AmdDefineDependencyElement>,
origin: ResolvedVc<Box<dyn ResolveOrigin>>, origin: ResolvedVc<Box<dyn ResolveOrigin>>,
path: ResolvedVc<AstPath>, path: AstPath,
factory_type: AmdDefineFactoryType, factory_type: AmdDefineFactoryType,
issue_source: ResolvedVc<IssueSource>, issue_source: ResolvedVc<IssueSource>,
in_try: bool, in_try: bool,
...@@ -139,30 +140,26 @@ impl AmdDefineWithDependenciesCodeGen { ...@@ -139,30 +140,26 @@ impl AmdDefineWithDependenciesCodeGen {
pub fn new( pub fn new(
dependencies_requests: Vec<AmdDefineDependencyElement>, dependencies_requests: Vec<AmdDefineDependencyElement>,
origin: ResolvedVc<Box<dyn ResolveOrigin>>, origin: ResolvedVc<Box<dyn ResolveOrigin>>,
path: ResolvedVc<AstPath>, path: AstPath,
factory_type: AmdDefineFactoryType, factory_type: AmdDefineFactoryType,
issue_source: ResolvedVc<IssueSource>, issue_source: ResolvedVc<IssueSource>,
in_try: bool, in_try: bool,
) -> Vc<Self> { ) -> Self {
Self::cell(AmdDefineWithDependenciesCodeGen { AmdDefineWithDependenciesCodeGen {
dependencies_requests, dependencies_requests,
origin, origin,
path, path,
factory_type, factory_type,
issue_source, issue_source,
in_try, in_try,
}) }
} }
}
#[turbo_tasks::value_impl] pub async fn code_generation(
impl CodeGenerateable for AmdDefineWithDependenciesCodeGen {
#[turbo_tasks::function]
async fn code_generation(
&self, &self,
module_graph: Vc<ModuleGraph>, module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> { ) -> Result<CodeGeneration> {
let mut visitors = Vec::new(); let mut visitors = Vec::new();
let resolved_elements = self let resolved_elements = self
...@@ -185,7 +182,7 @@ impl CodeGenerateable for AmdDefineWithDependenciesCodeGen { ...@@ -185,7 +182,7 @@ impl CodeGenerateable for AmdDefineWithDependenciesCodeGen {
Some(*self.issue_source), Some(*self.issue_source),
self.in_try, self.in_try,
), ),
Value::new(ChunkItem), ResolveType::ChunkItem,
) )
.await?, .await?,
request_str: request_str.to_string(), request_str: request_str.to_string(),
...@@ -206,9 +203,8 @@ impl CodeGenerateable for AmdDefineWithDependenciesCodeGen { ...@@ -206,9 +203,8 @@ impl CodeGenerateable for AmdDefineWithDependenciesCodeGen {
let factory_type = self.factory_type; let factory_type = self.factory_type;
let path = self.path.await?;
visitors.push( visitors.push(
create_visitor!(exact path, visit_mut_call_expr(call_expr: &mut CallExpr) { create_visitor!(exact self.path, visit_mut_call_expr(call_expr: &mut CallExpr) {
transform_amd_factory(call_expr, &resolved_elements, factory_type) transform_amd_factory(call_expr, &resolved_elements, factory_type)
}), }),
); );
...@@ -217,6 +213,12 @@ impl CodeGenerateable for AmdDefineWithDependenciesCodeGen { ...@@ -217,6 +213,12 @@ impl CodeGenerateable for AmdDefineWithDependenciesCodeGen {
} }
} }
impl From<AmdDefineWithDependenciesCodeGen> for CodeGen {
fn from(val: AmdDefineWithDependenciesCodeGen) -> Self {
CodeGen::AmdDefineWithDependenciesCodeGen(val)
}
}
enum ResolvedElement { enum ResolvedElement {
PatternMapping { PatternMapping {
pattern_mapping: ReadRef<PatternMapping>, pattern_mapping: ReadRef<PatternMapping>,
......
...@@ -245,7 +245,7 @@ impl AsyncModule { ...@@ -245,7 +245,7 @@ impl AsyncModule {
type_ann: None, type_ann: None,
}.into(), }.into(),
)), )),
].to_vec())); ].to_vec()).cell());
} }
} }
......
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
common::util::take::Take, common::util::take::Take,
ecma::ast::{CallExpr, Expr, ExprOrSpread, Lit}, ecma::ast::{CallExpr, Expr, ExprOrSpread, Lit},
quote, quote,
}; };
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Value, ValueToString, Vc}; use turbo_tasks::{
debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, ResolvedVc, ValueToString, Vc,
};
use turbopack_core::{ use turbopack_core::{
chunk::{ChunkableModuleReference, ChunkingContext}, chunk::{ChunkableModuleReference, ChunkingContext},
issue::IssueSource, issue::IssueSource,
...@@ -15,11 +18,13 @@ use turbopack_core::{ ...@@ -15,11 +18,13 @@ use turbopack_core::{
}; };
use turbopack_resolve::ecmascript::cjs_resolve; use turbopack_resolve::ecmascript::cjs_resolve;
use super::pattern_mapping::{PatternMapping, ResolveType::ChunkItem};
use crate::{ use crate::{
code_gen::{CodeGenerateable, CodeGeneration}, code_gen::{CodeGen, CodeGenerateable, CodeGeneration},
create_visitor, create_visitor,
references::AstPath, references::{
pattern_mapping::{PatternMapping, ResolveType},
AstPath,
},
runtime_functions::TURBOPACK_CACHE, runtime_functions::TURBOPACK_CACHE,
}; };
...@@ -151,7 +156,7 @@ impl CodeGenerateable for CjsRequireAssetReference { ...@@ -151,7 +156,7 @@ impl CodeGenerateable for CjsRequireAssetReference {
Some(*self.issue_source), Some(*self.issue_source),
self.in_try, self.in_try,
), ),
Value::new(ChunkItem), ResolveType::ChunkItem,
) )
.await?; .await?;
let mut visitors = Vec::new(); let mut visitors = Vec::new();
...@@ -181,7 +186,7 @@ impl CodeGenerateable for CjsRequireAssetReference { ...@@ -181,7 +186,7 @@ impl CodeGenerateable for CjsRequireAssetReference {
); );
})); }));
Ok(CodeGeneration::visitors(visitors)) Ok(CodeGeneration::visitors(visitors).cell())
} }
} }
...@@ -260,7 +265,7 @@ impl CodeGenerateable for CjsRequireResolveAssetReference { ...@@ -260,7 +265,7 @@ impl CodeGenerateable for CjsRequireResolveAssetReference {
Some(*self.issue_source), Some(*self.issue_source),
self.in_try, self.in_try,
), ),
Value::new(ChunkItem), ResolveType::ChunkItem,
) )
.await?; .await?;
let mut visitors = Vec::new(); let mut visitors = Vec::new();
...@@ -294,28 +299,27 @@ impl CodeGenerateable for CjsRequireResolveAssetReference { ...@@ -294,28 +299,27 @@ impl CodeGenerateable for CjsRequireResolveAssetReference {
// but we can ignore that as it will be recomputed anyway. // but we can ignore that as it will be recomputed anyway.
})); }));
Ok(CodeGeneration::visitors(visitors)) Ok(CodeGeneration::visitors(visitors).cell())
} }
} }
#[turbo_tasks::value(shared)] #[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
#[derive(Hash, Debug)]
pub struct CjsRequireCacheAccess { pub struct CjsRequireCacheAccess {
pub path: ResolvedVc<AstPath>, pub path: AstPath,
} }
impl CjsRequireCacheAccess {
pub fn new(path: AstPath) -> Self {
CjsRequireCacheAccess { path }
}
#[turbo_tasks::value_impl] pub async fn code_generation(
impl CodeGenerateable for CjsRequireCacheAccess {
#[turbo_tasks::function]
async fn code_generation(
&self, &self,
_module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> { ) -> Result<CodeGeneration> {
let mut visitors = Vec::new(); let mut visitors = Vec::new();
let path = &self.path.await?; visitors.push(create_visitor!(self.path, visit_mut_expr(expr: &mut Expr) {
visitors.push(create_visitor!(path, visit_mut_expr(expr: &mut Expr) {
if let Expr::Member(_) = expr { if let Expr::Member(_) = expr {
*expr = TURBOPACK_CACHE.into(); *expr = TURBOPACK_CACHE.into();
} else { } else {
...@@ -326,3 +330,9 @@ impl CodeGenerateable for CjsRequireCacheAccess { ...@@ -326,3 +330,9 @@ impl CodeGenerateable for CjsRequireCacheAccess {
Ok(CodeGeneration::visitors(visitors)) Ok(CodeGeneration::visitors(visitors))
} }
} }
impl From<CjsRequireCacheAccess> for CodeGen {
fn from(val: CjsRequireCacheAccess) -> Self {
CodeGen::CjsRequireCacheAccess(val)
}
}
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize};
use swc_core::quote; use swc_core::quote;
use turbo_tasks::{ResolvedVc, Value, Vc}; use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, Vc};
use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph}; use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph};
use super::AstPath; use super::AstPath;
use crate::{ use crate::{
code_gen::{CodeGenerateable, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
}; };
#[turbo_tasks::value(serialization = "auto_for_input")] #[derive(
#[derive(Debug, Clone, Copy, Hash)] Copy, Clone, Hash, PartialEq, Eq, Debug, Serialize, Deserialize, TraceRawVcs, NonLocalValue,
)]
pub enum ConstantConditionValue { pub enum ConstantConditionValue {
Truthy, Truthy,
Falsy, Falsy,
Nullish, Nullish,
} }
#[turbo_tasks::value] #[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
pub struct ConstantCondition { pub struct ConstantConditionCodeGen {
value: ConstantConditionValue, value: ConstantConditionValue,
path: ResolvedVc<AstPath>, path: AstPath,
} }
#[turbo_tasks::value_impl] impl ConstantConditionCodeGen {
impl ConstantCondition { pub fn new(value: ConstantConditionValue, path: AstPath) -> Self {
#[turbo_tasks::function] ConstantConditionCodeGen { value, path }
pub fn new(value: Value<ConstantConditionValue>, path: ResolvedVc<AstPath>) -> Vc<Self> {
Self::cell(ConstantCondition {
value: value.into_value(),
path,
})
} }
}
#[turbo_tasks::value_impl] pub async fn code_generation(
impl CodeGenerateable for ConstantCondition {
#[turbo_tasks::function]
async fn code_generation(
&self, &self,
_module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> { ) -> Result<CodeGeneration> {
let value = self.value; let value = self.value;
let visitors = [ let visitors = [
create_visitor!(exact &self.path.await?, visit_mut_expr(expr: &mut Expr) { create_visitor!(exact self.path, visit_mut_expr(expr: &mut Expr) {
*expr = match value { *expr = match value {
ConstantConditionValue::Truthy => quote!("(\"TURBOPACK compile-time truthy\", 1)" as Expr), ConstantConditionValue::Truthy => quote!("(\"TURBOPACK compile-time truthy\", 1)" as Expr),
ConstantConditionValue::Falsy => quote!("(\"TURBOPACK compile-time falsy\", 0)" as Expr), ConstantConditionValue::Falsy => quote!("(\"TURBOPACK compile-time falsy\", 0)" as Expr),
...@@ -57,3 +50,9 @@ impl CodeGenerateable for ConstantCondition { ...@@ -57,3 +50,9 @@ impl CodeGenerateable for ConstantCondition {
Ok(CodeGeneration::visitors(visitors)) Ok(CodeGeneration::visitors(visitors))
} }
} }
impl From<ConstantConditionCodeGen> for CodeGen {
fn from(val: ConstantConditionCodeGen) -> Self {
CodeGen::ConstantConditionCodeGen(val)
}
}
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize};
use swc_core::quote; use swc_core::quote;
use turbo_tasks::{ResolvedVc, Value, Vc}; use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, Value, Vc};
use turbopack_core::{ use turbopack_core::{
chunk::ChunkingContext, compile_time_info::CompileTimeDefineValue, module_graph::ModuleGraph, chunk::ChunkingContext, compile_time_info::CompileTimeDefineValue, module_graph::ModuleGraph,
}; };
use super::AstPath; use super::AstPath;
use crate::{ use crate::{
code_gen::{CodeGenerateable, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
}; };
#[turbo_tasks::value] #[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
pub struct ConstantValue { pub struct ConstantValueCodeGen {
value: CompileTimeDefineValue, value: CompileTimeDefineValue,
path: ResolvedVc<AstPath>, path: AstPath,
} }
#[turbo_tasks::value_impl] impl ConstantValueCodeGen {
impl ConstantValue { pub fn new(value: Value<CompileTimeDefineValue>, path: AstPath) -> Self {
#[turbo_tasks::function] ConstantValueCodeGen {
pub fn new(value: Value<CompileTimeDefineValue>, path: ResolvedVc<AstPath>) -> Vc<Self> {
Self::cell(ConstantValue {
value: value.into_value(), value: value.into_value(),
path, path,
}) }
} }
} pub async fn code_generation(
#[turbo_tasks::value_impl]
impl CodeGenerateable for ConstantValue {
#[turbo_tasks::function]
async fn code_generation(
&self, &self,
_module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> { ) -> Result<CodeGeneration> {
let value = self.value.clone(); let value = self.value.clone();
let path = &self.path.await?;
let visitor = create_visitor!(path, visit_mut_expr(expr: &mut Expr) { let visitor = create_visitor!(self.path, visit_mut_expr(expr: &mut Expr) {
*expr = match value { *expr = match value {
CompileTimeDefineValue::Bool(true) => quote!("(\"TURBOPACK compile-time value\", true)" as Expr), CompileTimeDefineValue::Bool(true) => quote!("(\"TURBOPACK compile-time value\", true)" as Expr),
CompileTimeDefineValue::Bool(false) => quote!("(\"TURBOPACK compile-time value\", false)" as Expr), CompileTimeDefineValue::Bool(false) => quote!("(\"TURBOPACK compile-time value\", false)" as Expr),
...@@ -51,3 +44,9 @@ impl CodeGenerateable for ConstantValue { ...@@ -51,3 +44,9 @@ impl CodeGenerateable for ConstantValue {
Ok(CodeGeneration::visitors(vec![visitor])) Ok(CodeGeneration::visitors(vec![visitor]))
} }
} }
impl From<ConstantValueCodeGen> for CodeGen {
fn from(val: ConstantValueCodeGen) -> Self {
CodeGen::ConstantValueCodeGen(val)
}
}
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc_core::quote; use swc_core::quote;
use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, ResolvedVc, Vc}; use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, Vc};
use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph}; use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph};
use super::AstPath; use super::AstPath;
use crate::{ use crate::{
code_gen::{CodeGenerateable, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
}; };
...@@ -16,49 +16,40 @@ enum DynamicExpressionType { ...@@ -16,49 +16,40 @@ enum DynamicExpressionType {
Normal, Normal,
} }
#[turbo_tasks::value] #[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
pub struct DynamicExpression { pub struct DynamicExpression {
path: ResolvedVc<AstPath>, path: AstPath,
ty: DynamicExpressionType, ty: DynamicExpressionType,
} }
#[turbo_tasks::value_impl]
impl DynamicExpression { impl DynamicExpression {
#[turbo_tasks::function] pub fn new(path: AstPath) -> Self {
pub fn new(path: ResolvedVc<AstPath>) -> Vc<Self> { DynamicExpression {
Self::cell(DynamicExpression {
path, path,
ty: DynamicExpressionType::Normal, ty: DynamicExpressionType::Normal,
}) }
} }
#[turbo_tasks::function] pub fn new_promise(path: AstPath) -> Self {
pub fn new_promise(path: ResolvedVc<AstPath>) -> Vc<Self> { DynamicExpression {
Self::cell(DynamicExpression {
path, path,
ty: DynamicExpressionType::Promise, ty: DynamicExpressionType::Promise,
}) }
} }
}
#[turbo_tasks::value_impl] pub async fn code_generation(
impl CodeGenerateable for DynamicExpression {
#[turbo_tasks::function]
async fn code_generation(
&self, &self,
_module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> { ) -> Result<CodeGeneration> {
let path = &self.path.await?;
let visitor = match self.ty { let visitor = match self.ty {
DynamicExpressionType::Normal => { DynamicExpressionType::Normal => {
create_visitor!(path, visit_mut_expr(expr: &mut Expr) { create_visitor!(self.path, visit_mut_expr(expr: &mut Expr) {
*expr = quote!("(() => { const e = new Error(\"Cannot find module as expression is too dynamic\"); e.code = 'MODULE_NOT_FOUND'; throw e; })()" as Expr); *expr = quote!("(() => { const e = new Error(\"Cannot find module as expression is too dynamic\"); e.code = 'MODULE_NOT_FOUND'; throw e; })()" as Expr);
}) })
} }
DynamicExpressionType::Promise => { DynamicExpressionType::Promise => {
create_visitor!(path, visit_mut_expr(expr: &mut Expr) { create_visitor!(self.path, visit_mut_expr(expr: &mut Expr) {
*expr = quote!("Promise.resolve().then(() => { const e = new Error(\"Cannot find module as expression is too dynamic\"); e.code = 'MODULE_NOT_FOUND'; throw e; })" as Expr); *expr = quote!("Promise.resolve().then(() => { const e = new Error(\"Cannot find module as expression is too dynamic\"); e.code = 'MODULE_NOT_FOUND'; throw e; })" as Expr);
}) })
} }
...@@ -67,3 +58,9 @@ impl CodeGenerateable for DynamicExpression { ...@@ -67,3 +58,9 @@ impl CodeGenerateable for DynamicExpression {
Ok(CodeGeneration::visitors(vec![visitor])) Ok(CodeGeneration::visitors(vec![visitor]))
} }
} }
impl From<DynamicExpression> for CodeGen {
fn from(val: DynamicExpression) -> Self {
CodeGen::DynamicExpression(val)
}
}
...@@ -397,7 +397,7 @@ impl CodeGenerateable for EsmAssetReference { ...@@ -397,7 +397,7 @@ impl CodeGenerateable for EsmAssetReference {
}; };
if let Some((key, stmt)) = result { if let Some((key, stmt)) = result {
Ok(CodeGeneration::hoisted_stmt(key, stmt)) Ok(CodeGeneration::hoisted_stmt(key, stmt).cell())
} else { } else {
Ok(CodeGeneration::empty()) Ok(CodeGeneration::empty())
} }
......
...@@ -7,49 +7,32 @@ use swc_core::{ ...@@ -7,49 +7,32 @@ use swc_core::{
ComputedPropName, Expr, Ident, KeyValueProp, Lit, MemberExpr, MemberProp, Number, Prop, ComputedPropName, Expr, Ident, KeyValueProp, Lit, MemberExpr, MemberProp, Number, Prop,
PropName, SeqExpr, SimpleAssignTarget, Str, PropName, SeqExpr, SimpleAssignTarget, Str,
}, },
visit::{ visit::fields::{CalleeField, PropField},
fields::{CalleeField, PropField},
AstParentKind,
},
}, },
}; };
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{trace::TraceRawVcs, NonLocalValue, ResolvedVc, TaskInput, Vc}; use turbo_tasks::{trace::TraceRawVcs, NonLocalValue, ResolvedVc, Vc};
use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph}; use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph};
use super::EsmAssetReference; use super::EsmAssetReference;
use crate::{ use crate::{
code_gen::{CodeGenerateable, CodeGeneration, VisitorFactory}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
references::AstPath, references::AstPath,
}; };
#[turbo_tasks::value(shared)] #[derive(Hash, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, TraceRawVcs, NonLocalValue)]
#[derive(Hash, Debug)]
pub struct EsmBindings {
pub bindings: Vec<EsmBinding>,
}
impl EsmBindings {
pub fn new(bindings: Vec<EsmBinding>) -> Vc<Self> {
EsmBindings { bindings }.cell()
}
}
#[derive(
Hash, Clone, Debug, TaskInput, Serialize, Deserialize, PartialEq, Eq, TraceRawVcs, NonLocalValue,
)]
pub struct EsmBinding { pub struct EsmBinding {
pub reference: ResolvedVc<EsmAssetReference>, pub reference: ResolvedVc<EsmAssetReference>,
pub export: Option<RcStr>, pub export: Option<RcStr>,
pub ast_path: ResolvedVc<AstPath>, pub ast_path: AstPath,
} }
impl EsmBinding { impl EsmBinding {
pub fn new( pub fn new(
reference: ResolvedVc<EsmAssetReference>, reference: ResolvedVc<EsmAssetReference>,
export: Option<RcStr>, export: Option<RcStr>,
ast_path: ResolvedVc<AstPath>, ast_path: AstPath,
) -> Self { ) -> Self {
EsmBinding { EsmBinding {
reference, reference,
...@@ -58,21 +41,21 @@ impl EsmBinding { ...@@ -58,21 +41,21 @@ impl EsmBinding {
} }
} }
async fn to_visitors( pub async fn code_generation(
&self, &self,
visitors: &mut Vec<(Vec<AstParentKind>, Box<dyn VisitorFactory>)>,
module_graph: Vc<ModuleGraph>, module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<()> { ) -> Result<CodeGeneration> {
let item = self.clone(); let mut visitors = vec![];
let imported_module = self.reference.get_referenced_asset();
let mut ast_path = item.ast_path.await?.clone_value(); let export = self.export.clone();
let imported_module = self.reference.get_referenced_asset();
let imported_module = imported_module let imported_module = imported_module
.await? .await?
.get_ident(module_graph, chunking_context) .get_ident(module_graph, chunking_context)
.await?; .await?;
let mut ast_path = self.ast_path.0.clone();
loop { loop {
match ast_path.last() { match ast_path.last() {
// Shorthand properties get special treatment because we need to rewrite them to // Shorthand properties get special treatment because we need to rewrite them to
...@@ -86,7 +69,7 @@ impl EsmBinding { ...@@ -86,7 +69,7 @@ impl EsmBinding {
if let Some(imported_ident) = imported_module.as_deref() { if let Some(imported_ident) = imported_module.as_deref() {
*prop = Prop::KeyValue(KeyValueProp { *prop = Prop::KeyValue(KeyValueProp {
key: PropName::Ident(ident.clone().into()), key: PropName::Ident(ident.clone().into()),
value: Box::new(make_expr(imported_ident, item.export.as_deref(), ident.span, false)) value: Box::new(make_expr(imported_ident, export.as_deref(), ident.span, false))
}); });
} }
} }
...@@ -104,15 +87,16 @@ impl EsmBinding { ...@@ -104,15 +87,16 @@ impl EsmBinding {
); );
visitors.push( visitors.push(
create_visitor!(exact ast_path, visit_mut_expr(expr: &mut Expr) { create_visitor!(exact ast_path, visit_mut_expr(expr: &mut Expr) {
if let Some(ident) = imported_module.as_deref() { if let Some(ident) = imported_module.as_deref() {
use swc_core::common::Spanned; use swc_core::common::Spanned;
*expr = make_expr(ident, item.export.as_deref(), expr.span(), in_call); *expr = make_expr(ident, export.as_deref(), expr.span(), in_call);
} }
// If there's no identifier for the imported module, // If there's no identifier for the imported module,
// resolution failed and will insert code that throws // resolution failed and will insert code that throws
// before this expression is reached. Leave behind the original identifier. // before this expression is reached. Leave behind the original identifier.
})); }),
);
break; break;
} }
Some(swc_core::ecma::visit::AstParentKind::BindingIdent( Some(swc_core::ecma::visit::AstParentKind::BindingIdent(
...@@ -132,7 +116,7 @@ impl EsmBinding { ...@@ -132,7 +116,7 @@ impl EsmBinding {
create_visitor!(exact ast_path, visit_mut_simple_assign_target(l: &mut SimpleAssignTarget) { create_visitor!(exact ast_path, visit_mut_simple_assign_target(l: &mut SimpleAssignTarget) {
if let Some(ident) = imported_module.as_deref() { if let Some(ident) = imported_module.as_deref() {
use swc_core::common::Spanned; use swc_core::common::Spanned;
*l = match make_expr(ident, item.export.as_deref(), l.span(), false) { *l = match make_expr(ident, export.as_deref(), l.span(), false) {
Expr::Ident(ident) => SimpleAssignTarget::Ident(ident.into()), Expr::Ident(ident) => SimpleAssignTarget::Ident(ident.into()),
Expr::Member(member) => SimpleAssignTarget::Member(member), Expr::Member(member) => SimpleAssignTarget::Member(member),
_ => unreachable!(), _ => unreachable!(),
...@@ -149,27 +133,13 @@ impl EsmBinding { ...@@ -149,27 +133,13 @@ impl EsmBinding {
} }
} }
Ok(()) Ok(CodeGeneration::visitors(visitors))
} }
} }
#[turbo_tasks::value_impl] impl From<EsmBinding> for CodeGen {
impl CodeGenerateable for EsmBindings { fn from(val: EsmBinding) -> Self {
#[turbo_tasks::function] CodeGen::EsmBinding(val)
async fn code_generation(
&self,
module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> {
let mut visitors = Vec::new();
let bindings = self.bindings.clone();
for item in bindings.into_iter() {
item.to_visitors(&mut visitors, module_graph, chunking_context)
.await?;
}
Ok(CodeGeneration::visitors(visitors))
} }
} }
......
...@@ -133,9 +133,9 @@ impl CodeGenerateable for EsmAsyncAssetReference { ...@@ -133,9 +133,9 @@ impl CodeGenerateable for EsmAsyncAssetReference {
*chunking_context.environment().chunk_loading().await?, *chunking_context.environment().chunk_loading().await?,
ChunkLoading::Edge ChunkLoading::Edge
) { ) {
Value::new(ResolveType::ChunkItem) ResolveType::ChunkItem
} else { } else {
Value::new(ResolveType::AsyncChunkLoader) ResolveType::AsyncChunkLoader
}, },
) )
.await?; .await?;
...@@ -177,6 +177,6 @@ impl CodeGenerateable for EsmAsyncAssetReference { ...@@ -177,6 +177,6 @@ impl CodeGenerateable for EsmAsyncAssetReference {
}); });
}); });
Ok(CodeGeneration::visitors(vec![visitor])) Ok(CodeGeneration::visitors(vec![visitor]).cell())
} }
} }
...@@ -639,6 +639,7 @@ impl CodeGenerateable for EsmExports { ...@@ -639,6 +639,7 @@ impl CodeGenerateable for EsmExports {
getters: Expr = getters.clone() getters: Expr = getters.clone()
), ),
)], )],
)) )
.cell())
} }
} }
use std::borrow::Cow; use std::borrow::Cow;
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
common::DUMMY_SP, common::DUMMY_SP,
ecma::ast::{Expr, Ident}, ecma::ast::{Expr, Ident},
quote, quote,
}; };
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph}; use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph};
use crate::{ use crate::{
code_gen::{CodeGenerateable, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, magic_identifier, create_visitor, magic_identifier,
references::AstPath, references::AstPath,
runtime_functions::TURBOPACK_RESOLVE_ABSOLUTE_PATH, runtime_functions::TURBOPACK_RESOLVE_ABSOLUTE_PATH,
...@@ -22,28 +23,23 @@ use crate::{ ...@@ -22,28 +23,23 @@ use crate::{
/// ///
/// There can be many references to import.meta, and they appear at any nesting /// There can be many references to import.meta, and they appear at any nesting
/// in the file. But we must only initialize the binding a single time. /// in the file. But we must only initialize the binding a single time.
#[turbo_tasks::value(shared)] ///
#[derive(Hash, Debug)] /// This singleton behavior must be enforced by the caller!
#[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
pub struct ImportMetaBinding { pub struct ImportMetaBinding {
path: ResolvedVc<FileSystemPath>, path: ResolvedVc<FileSystemPath>,
} }
#[turbo_tasks::value_impl]
impl ImportMetaBinding { impl ImportMetaBinding {
#[turbo_tasks::function] pub fn new(path: ResolvedVc<FileSystemPath>) -> Self {
pub fn new(path: ResolvedVc<FileSystemPath>) -> Vc<Self> { ImportMetaBinding { path }
ImportMetaBinding { path }.cell()
} }
}
#[turbo_tasks::value_impl] pub async fn code_generation(
impl CodeGenerateable for ImportMetaBinding {
#[turbo_tasks::function]
async fn code_generation(
&self, &self,
_module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> { ) -> Result<CodeGeneration> {
let rel_path = chunking_context let rel_path = chunking_context
.root_path() .root_path()
.await? .await?
...@@ -78,35 +74,33 @@ impl CodeGenerateable for ImportMetaBinding { ...@@ -78,35 +74,33 @@ impl CodeGenerateable for ImportMetaBinding {
} }
} }
impl From<ImportMetaBinding> for CodeGen {
fn from(val: ImportMetaBinding) -> Self {
CodeGen::ImportMetaBinding(val)
}
}
/// Handles rewriting `import.meta` references into the injected binding created /// Handles rewriting `import.meta` references into the injected binding created
/// by ImportMetaBindi ImportMetaBinding. /// by ImportMetaBinding.
/// ///
/// There can be many references to import.meta, and they appear at any nesting /// There can be many references to import.meta, and they appear at any nesting
/// in the file. But all references refer to the same mutable object. /// in the file. But all references refer to the same mutable object.
#[turbo_tasks::value(shared)] #[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
#[derive(Hash, Debug)]
pub struct ImportMetaRef { pub struct ImportMetaRef {
ast_path: ResolvedVc<AstPath>, ast_path: AstPath,
} }
#[turbo_tasks::value_impl]
impl ImportMetaRef { impl ImportMetaRef {
#[turbo_tasks::function] pub fn new(ast_path: AstPath) -> Self {
pub fn new(ast_path: ResolvedVc<AstPath>) -> Vc<Self> { ImportMetaRef { ast_path }
ImportMetaRef { ast_path }.cell()
} }
}
#[turbo_tasks::value_impl] pub async fn code_generation(
impl CodeGenerateable for ImportMetaRef {
#[turbo_tasks::function]
async fn code_generation(
&self, &self,
_module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> { ) -> Result<CodeGeneration> {
let ast_path = &self.ast_path.await?; let visitor = create_visitor!(self.ast_path, visit_mut_expr(expr: &mut Expr) {
let visitor = create_visitor!(ast_path, visit_mut_expr(expr: &mut Expr) {
*expr = Expr::Ident(meta_ident()); *expr = Expr::Ident(meta_ident());
}); });
...@@ -114,6 +108,12 @@ impl CodeGenerateable for ImportMetaRef { ...@@ -114,6 +108,12 @@ impl CodeGenerateable for ImportMetaRef {
} }
} }
impl From<ImportMetaRef> for CodeGen {
fn from(val: ImportMetaRef) -> Self {
CodeGen::ImportMetaRef(val)
}
}
/// URL encodes special chars that would appear in the "pathname" portion. /// URL encodes special chars that would appear in the "pathname" portion.
/// https://github.com/nodejs/node/blob/3bed5f11e039153eff5cbfd9513b8f55fd53fc43/lib/internal/url.js#L1513-L1526 /// https://github.com/nodejs/node/blob/3bed5f11e039153eff5cbfd9513b8f55fd53fc43/lib/internal/url.js#L1513-L1526
fn encode_path(path: &'_ str) -> Cow<'_, str> { fn encode_path(path: &'_ str) -> Cow<'_, str> {
......
...@@ -93,6 +93,6 @@ impl CodeGenerateable for EsmModuleIdAssetReference { ...@@ -93,6 +93,6 @@ impl CodeGenerateable for EsmModuleIdAssetReference {
); );
} }
Ok(CodeGeneration::visitors(visitors)) Ok(CodeGeneration::visitors(visitors).cell())
} }
} }
use std::mem::replace; use std::mem::replace;
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
common::DUMMY_SP, common::DUMMY_SP,
ecma::ast::{ ecma::ast::{
...@@ -9,11 +10,11 @@ use swc_core::{ ...@@ -9,11 +10,11 @@ use swc_core::{
}, },
quote, quote,
}; };
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, Vc};
use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph}; use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph};
use crate::{ use crate::{
code_gen::{CodeGenerateable, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, magic_identifier, create_visitor, magic_identifier,
references::AstPath, references::AstPath,
}; };
...@@ -21,31 +22,25 @@ use crate::{ ...@@ -21,31 +22,25 @@ use crate::{
/// Makes code changes to remove export/import declarations and places the /// Makes code changes to remove export/import declarations and places the
/// expr/decl in a normal statement. Unnamed expr/decl will be named with the /// expr/decl in a normal statement. Unnamed expr/decl will be named with the
/// magic identifier "export default" /// magic identifier "export default"
#[turbo_tasks::value] #[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
#[derive(Hash, Debug)]
pub struct EsmModuleItem { pub struct EsmModuleItem {
pub path: ResolvedVc<AstPath>, pub path: AstPath,
} }
impl EsmModuleItem { impl EsmModuleItem {
pub fn new(path: ResolvedVc<AstPath>) -> Vc<Self> { pub fn new(path: AstPath) -> Self {
Self::cell(EsmModuleItem { path }) EsmModuleItem { path }
} }
}
#[turbo_tasks::value_impl] pub async fn code_generation(
impl CodeGenerateable for EsmModuleItem {
#[turbo_tasks::function]
async fn code_generation(
&self, &self,
_module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> { ) -> Result<CodeGeneration> {
let mut visitors = Vec::new(); let mut visitors = Vec::new();
let path = &self.path.await?;
visitors.push( visitors.push(
create_visitor!(path, visit_mut_module_item(module_item: &mut ModuleItem) { create_visitor!(self.path, visit_mut_module_item(module_item: &mut ModuleItem) {
let item = replace(module_item, ModuleItem::Stmt(quote!(";" as Stmt))); let item = replace(module_item, ModuleItem::Stmt(quote!(";" as Stmt)));
if let ModuleItem::ModuleDecl(module_decl) = item { if let ModuleItem::ModuleDecl(module_decl) = item {
match module_decl { match module_decl {
...@@ -105,3 +100,9 @@ impl CodeGenerateable for EsmModuleItem { ...@@ -105,3 +100,9 @@ impl CodeGenerateable for EsmModuleItem {
Ok(CodeGeneration::visitors(visitors)) Ok(CodeGeneration::visitors(visitors))
} }
} }
impl From<EsmModuleItem> for CodeGen {
fn from(val: EsmModuleItem) -> Self {
CodeGen::EsmModuleItem(val)
}
}
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
ecma::ast::{Expr, ExprOrSpread, NewExpr}, ecma::ast::{Expr, ExprOrSpread, NewExpr},
quote, quote,
}; };
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Value, ValueToString, Vc}; use turbo_tasks::{
trace::TraceRawVcs, NonLocalValue, ResolvedVc, TaskInput, Value, ValueToString, Vc,
};
use turbopack_core::{ use turbopack_core::{
chunk::{ chunk::{
ChunkItemExt, ChunkableModule, ChunkableModuleReference, ChunkingContext, ChunkingType, ChunkItemExt, ChunkableModule, ChunkableModuleReference, ChunkingContext, ChunkingType,
...@@ -34,8 +37,19 @@ use crate::{ ...@@ -34,8 +37,19 @@ use crate::{
/// Determines how to treat `new URL(...)` rewrites. /// Determines how to treat `new URL(...)` rewrites.
/// This allows to construct url depends on the different building context, /// This allows to construct url depends on the different building context,
/// e.g. SSR, CSR, or Node.js. /// e.g. SSR, CSR, or Node.js.
#[turbo_tasks::value(shared)] #[derive(
#[derive(Debug, Copy, Clone, Hash)] Copy,
Clone,
Debug,
Eq,
PartialEq,
Hash,
Serialize,
Deserialize,
TraceRawVcs,
TaskInput,
NonLocalValue,
)]
pub enum UrlRewriteBehavior { pub enum UrlRewriteBehavior {
/// Omits base, resulting in a relative URL. /// Omits base, resulting in a relative URL.
Relative, Relative,
...@@ -58,7 +72,7 @@ pub struct UrlAssetReference { ...@@ -58,7 +72,7 @@ pub struct UrlAssetReference {
ast_path: ResolvedVc<AstPath>, ast_path: ResolvedVc<AstPath>,
issue_source: ResolvedVc<IssueSource>, issue_source: ResolvedVc<IssueSource>,
in_try: bool, in_try: bool,
url_rewrite_behavior: ResolvedVc<UrlRewriteBehavior>, url_rewrite_behavior: UrlRewriteBehavior,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -71,7 +85,7 @@ impl UrlAssetReference { ...@@ -71,7 +85,7 @@ impl UrlAssetReference {
ast_path: ResolvedVc<AstPath>, ast_path: ResolvedVc<AstPath>,
issue_source: ResolvedVc<IssueSource>, issue_source: ResolvedVc<IssueSource>,
in_try: bool, in_try: bool,
url_rewrite_behavior: ResolvedVc<UrlRewriteBehavior>, url_rewrite_behavior: UrlRewriteBehavior,
) -> Vc<Self> { ) -> Vc<Self> {
UrlAssetReference { UrlAssetReference {
origin, origin,
...@@ -150,9 +164,8 @@ impl CodeGenerateable for UrlAssetReference { ...@@ -150,9 +164,8 @@ impl CodeGenerateable for UrlAssetReference {
) -> Result<Vc<CodeGeneration>> { ) -> Result<Vc<CodeGeneration>> {
let this = self.await?; let this = self.await?;
let mut visitors = vec![]; let mut visitors = vec![];
let rewrite_behavior = &*this.url_rewrite_behavior.await?;
match rewrite_behavior { match this.url_rewrite_behavior {
UrlRewriteBehavior::Relative => { UrlRewriteBehavior::Relative => {
let referenced_asset = self.get_referenced_asset().await?; let referenced_asset = self.get_referenced_asset().await?;
let ast_path = this.ast_path.await?; let ast_path = this.ast_path.await?;
...@@ -312,6 +325,6 @@ impl CodeGenerateable for UrlAssetReference { ...@@ -312,6 +325,6 @@ impl CodeGenerateable for UrlAssetReference {
} }
}; };
Ok(CodeGeneration::visitors(visitors)) Ok(CodeGeneration::visitors(visitors).cell())
} }
} }
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize};
use swc_core::{ecma::ast::Expr, quote}; use swc_core::{ecma::ast::Expr, quote};
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, Vc};
use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph}; use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph};
use super::AstPath; use super::AstPath;
use crate::{ use crate::{
code_gen::{CodeGenerateable, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
}; };
#[turbo_tasks::value] #[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
pub struct IdentReplacement { pub struct IdentReplacement {
value: RcStr, value: RcStr,
path: ResolvedVc<AstPath>, path: AstPath,
} }
#[turbo_tasks::value_impl]
impl IdentReplacement { impl IdentReplacement {
#[turbo_tasks::function] pub fn new(value: RcStr, path: AstPath) -> Self {
pub async fn new(value: RcStr, path: Vc<AstPath>) -> Result<Vc<Self>> { IdentReplacement { value, path }
Ok(Self::cell(IdentReplacement {
value,
path: path.to_resolved().await?,
}))
} }
}
#[turbo_tasks::value_impl] pub async fn code_generation(
impl CodeGenerateable for IdentReplacement {
#[turbo_tasks::function]
async fn code_generation(
&self, &self,
_module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> { ) -> Result<CodeGeneration> {
let value = self.value.clone(); let value = self.value.clone();
let path = &self.path.await?;
let visitor = create_visitor!(path, visit_mut_expr(expr: &mut Expr) { let visitor = create_visitor!(self.path, visit_mut_expr(expr: &mut Expr) {
let id = Expr::Ident((&*value).into()); let id = Expr::Ident((&*value).into());
*expr = quote!("(\"TURBOPACK ident replacement\", $e)" as Expr, e: Expr = id); *expr = quote!("(\"TURBOPACK ident replacement\", $e)" as Expr, e: Expr = id);
}); });
...@@ -46,3 +37,9 @@ impl CodeGenerateable for IdentReplacement { ...@@ -46,3 +37,9 @@ impl CodeGenerateable for IdentReplacement {
Ok(CodeGeneration::visitors(vec![visitor])) Ok(CodeGeneration::visitors(vec![visitor]))
} }
} }
impl From<IdentReplacement> for CodeGen {
fn from(val: IdentReplacement) -> Self {
CodeGen::IdentReplacement(val)
}
}
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
common::DUMMY_SP, common::DUMMY_SP,
ecma::ast::{Expr, MemberExpr, MemberProp}, ecma::ast::{Expr, MemberExpr, MemberProp},
quote, quote,
}; };
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, Vc};
use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph}; use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph};
use super::AstPath; use super::AstPath;
use crate::{ use crate::{
code_gen::{CodeGenerateable, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
}; };
#[turbo_tasks::value] #[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
pub struct MemberReplacement { pub struct MemberReplacement {
key: RcStr, key: RcStr,
value: RcStr, value: RcStr,
path: ResolvedVc<AstPath>, path: AstPath,
} }
#[turbo_tasks::value_impl]
impl MemberReplacement { impl MemberReplacement {
#[turbo_tasks::function] pub fn new(key: RcStr, value: RcStr, path: AstPath) -> Self {
pub async fn new(key: RcStr, value: RcStr, path: Vc<AstPath>) -> Result<Vc<Self>> { MemberReplacement { key, value, path }
Ok(Self::cell(MemberReplacement {
key,
value,
path: path.to_resolved().await?,
}))
} }
}
#[turbo_tasks::value_impl] pub async fn code_generation(
impl CodeGenerateable for MemberReplacement {
#[turbo_tasks::function]
async fn code_generation(
&self, &self,
_module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> { ) -> Result<CodeGeneration> {
let key = self.key.clone(); let key = self.key.clone();
let value = self.value.clone(); let value = self.value.clone();
let path = &self.path.await?;
let visitor = create_visitor!(path, visit_mut_expr(expr: &mut Expr) { let visitor = create_visitor!(self.path, visit_mut_expr(expr: &mut Expr) {
let member = Expr::Member(MemberExpr { let member = Expr::Member(MemberExpr {
span: DUMMY_SP, span: DUMMY_SP,
obj: Box::new(Expr::Ident((&*key).into())), obj: Box::new(Expr::Ident((&*key).into())),
...@@ -57,3 +47,9 @@ impl CodeGenerateable for MemberReplacement { ...@@ -57,3 +47,9 @@ impl CodeGenerateable for MemberReplacement {
Ok(CodeGeneration::visitors(vec![visitor])) Ok(CodeGeneration::visitors(vec![visitor]))
} }
} }
impl From<MemberReplacement> for CodeGen {
fn from(val: MemberReplacement) -> Self {
CodeGen::MemberReplacement(val)
}
}
...@@ -12,8 +12,8 @@ use swc_core::{ ...@@ -12,8 +12,8 @@ use swc_core::{
}; };
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ use turbo_tasks::{
debug::ValueDebugFormat, trace::TraceRawVcs, FxIndexMap, NonLocalValue, ResolvedVc, debug::ValueDebugFormat, trace::TraceRawVcs, FxIndexMap, NonLocalValue, ResolvedVc, TaskInput,
TryJoinIterExt, Value, Vc, TryJoinIterExt, Vc,
}; };
use turbopack_core::{ use turbopack_core::{
chunk::{ChunkItemExt, ChunkableModule, ChunkingContext, ModuleId}, chunk::{ChunkItemExt, ChunkableModule, ChunkingContext, ModuleId},
...@@ -87,8 +87,19 @@ pub(crate) enum PatternMapping { ...@@ -87,8 +87,19 @@ pub(crate) enum PatternMapping {
Map(FxIndexMap<String, SinglePatternMapping>), Map(FxIndexMap<String, SinglePatternMapping>),
} }
#[derive(Hash, Debug, Copy, Clone)] #[derive(
#[turbo_tasks::value(serialization = "auto_for_input")] Copy,
Clone,
Debug,
Eq,
PartialEq,
Hash,
Serialize,
Deserialize,
TraceRawVcs,
TaskInput,
NonLocalValue,
)]
pub(crate) enum ResolveType { pub(crate) enum ResolveType {
AsyncChunkLoader, AsyncChunkLoader,
ChunkItem, ChunkItem,
...@@ -398,9 +409,8 @@ impl PatternMapping { ...@@ -398,9 +409,8 @@ impl PatternMapping {
module_graph: Vc<ModuleGraph>, module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
resolve_result: Vc<ModuleResolveResult>, resolve_result: Vc<ModuleResolveResult>,
resolve_type: Value<ResolveType>, resolve_type: ResolveType,
) -> Result<Vc<PatternMapping>> { ) -> Result<Vc<PatternMapping>> {
let resolve_type = resolve_type.into_value();
let result = resolve_result.await?; let result = resolve_result.await?;
match result.primary.len() { match result.primary.len() {
0 => Ok(PatternMapping::Single(SinglePatternMapping::Unresolvable( 0 => Ok(PatternMapping::Single(SinglePatternMapping::Unresolvable(
......
...@@ -314,7 +314,7 @@ impl CodeGenerateable for RequireContextAssetReference { ...@@ -314,7 +314,7 @@ impl CodeGenerateable for RequireContextAssetReference {
} }
})); }));
Ok(CodeGeneration::visitors(visitors)) Ok(CodeGeneration::visitors(visitors).cell())
} }
} }
...@@ -458,7 +458,7 @@ impl EcmascriptChunkItem for RequireContextChunkItem { ...@@ -458,7 +458,7 @@ impl EcmascriptChunkItem for RequireContextChunkItem {
*self.module_graph, *self.module_graph,
*ResolvedVc::upcast(self.chunking_context), *ResolvedVc::upcast(self.chunking_context),
*entry.result, *entry.result,
Value::new(ResolveType::ChunkItem), ResolveType::ChunkItem,
) )
.await?; .await?;
......
use std::mem::take; use std::mem::take;
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
common::{util::take::Take, Spanned}, common::{util::take::Take, Spanned},
ecma::{ ecma::{
...@@ -16,36 +17,32 @@ use swc_core::{ ...@@ -16,36 +17,32 @@ use swc_core::{
}, },
quote, quote,
}; };
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, NonLocalValue, Vc};
use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph}; use turbopack_core::{chunk::ChunkingContext, module_graph::ModuleGraph};
use crate::{ use crate::{
code_gen::{CodeGenerateable, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
utils::AstPathRange, utils::AstPathRange,
}; };
#[turbo_tasks::value] #[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
pub struct Unreachable { pub struct Unreachable {
range: ResolvedVc<AstPathRange>, range: AstPathRange,
} }
impl Unreachable { impl Unreachable {
pub fn new(range: ResolvedVc<AstPathRange>) -> Vc<Self> { pub fn new(range: AstPathRange) -> Self {
Self::cell(Unreachable { range }) Unreachable { range }
} }
}
#[turbo_tasks::value_impl] pub async fn code_generation(
impl CodeGenerateable for Unreachable {
#[turbo_tasks::function]
async fn code_generation(
&self, &self,
_module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> { ) -> Result<CodeGeneration> {
let range = self.range.await?; let visitors = match &self.range {
let visitors = match &*range {
AstPathRange::Exact(path) => { AstPathRange::Exact(path) => {
[ [
// Unreachable might be used on Stmt or Expr // Unreachable might be used on Stmt or Expr
...@@ -127,6 +124,12 @@ impl CodeGenerateable for Unreachable { ...@@ -127,6 +124,12 @@ impl CodeGenerateable for Unreachable {
} }
} }
impl From<Unreachable> for CodeGen {
fn from(val: Unreachable) -> Self {
CodeGen::Unreachable(val)
}
}
struct ExtractDeclarations<'a> { struct ExtractDeclarations<'a> {
stmts: &'a mut Vec<Stmt>, stmts: &'a mut Vec<Stmt>,
in_nested_block_scope: bool, in_nested_block_scope: bool,
......
...@@ -176,6 +176,6 @@ impl CodeGenerateable for WorkerAssetReference { ...@@ -176,6 +176,6 @@ impl CodeGenerateable for WorkerAssetReference {
); );
}); });
Ok(CodeGeneration::visitors(vec![visitor])) Ok(CodeGeneration::visitors(vec![visitor]).cell())
} }
} }
...@@ -23,7 +23,7 @@ use crate::{ ...@@ -23,7 +23,7 @@ use crate::{
EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkItemOptions, EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkItemOptions,
EcmascriptChunkPlaceable, EcmascriptChunkType, EcmascriptExports, EcmascriptChunkPlaceable, EcmascriptChunkType, EcmascriptExports,
}, },
code_gen::{CodeGenerateable, CodeGenerateableWithAsyncModuleInfo}, code_gen::CodeGenerateable,
process_content_with_code_gens, process_content_with_code_gens,
}; };
...@@ -71,16 +71,7 @@ impl EcmascriptChunkItem for EcmascriptModuleFacadeChunkItem { ...@@ -71,16 +71,7 @@ impl EcmascriptChunkItem for EcmascriptModuleFacadeChunkItem {
let references_ref = references.await?; let references_ref = references.await?;
let mut code_gens = Vec::with_capacity(references_ref.len() + 2); let mut code_gens = Vec::with_capacity(references_ref.len() + 2);
for r in &references_ref { for r in &references_ref {
if let Some(code_gen) = if let Some(code_gen) = ResolvedVc::try_sidecast::<Box<dyn CodeGenerateable>>(*r) {
ResolvedVc::try_sidecast::<Box<dyn CodeGenerateableWithAsyncModuleInfo>>(*r)
{
code_gens.push(code_gen.code_generation(
*self.module_graph,
*chunking_context,
async_module_info,
));
} else if let Some(code_gen) = ResolvedVc::try_sidecast::<Box<dyn CodeGenerateable>>(*r)
{
code_gens.push(code_gen.code_generation(*self.module_graph, *chunking_context)); code_gens.push(code_gen.code_generation(*self.module_graph, *chunking_context));
} }
} }
...@@ -92,10 +83,10 @@ impl EcmascriptChunkItem for EcmascriptModuleFacadeChunkItem { ...@@ -92,10 +83,10 @@ impl EcmascriptChunkItem for EcmascriptModuleFacadeChunkItem {
)); ));
code_gens.push(exports.code_generation(*self.module_graph, *chunking_context)); code_gens.push(exports.code_generation(*self.module_graph, *chunking_context));
let code_gens = code_gens.into_iter().try_join().await?; let code_gens = code_gens.into_iter().try_join().await?;
let code_gens = code_gens.iter().map(|cg| &**cg).collect::<Vec<_>>(); let code_gens = code_gens.iter().map(|cg| &**cg);
let mut program = Program::Module(swc_core::ecma::ast::Module::dummy()); let mut program = Program::Module(swc_core::ecma::ast::Module::dummy());
process_content_with_code_gens(&mut program, &Globals::new(), None, &code_gens); process_content_with_code_gens(&mut program, &Globals::new(), None, code_gens);
let mut bytes: Vec<u8> = vec![]; let mut bytes: Vec<u8> = vec![];
......
...@@ -140,6 +140,7 @@ impl CodeGenerateable for EcmascriptModulePartReference { ...@@ -140,6 +140,7 @@ impl CodeGenerateable for EcmascriptModulePartReference {
turbopack_import: Expr = TURBOPACK_IMPORT.into(), turbopack_import: Expr = TURBOPACK_IMPORT.into(),
id: Expr = module_id_to_lit(&id), id: Expr = module_id_to_lit(&id),
), ),
)) )
.cell())
} }
} }
use serde::Serialize; use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
common::DUMMY_SP, common::DUMMY_SP,
ecma::{ ecma::{
...@@ -6,6 +6,7 @@ use swc_core::{ ...@@ -6,6 +6,7 @@ use swc_core::{
visit::AstParentKind, visit::AstParentKind,
}, },
}; };
use turbo_tasks::{trace::TraceRawVcs, NonLocalValue};
use turbopack_core::{chunk::ModuleId, resolve::pattern::Pattern}; use turbopack_core::{chunk::ModuleId, resolve::pattern::Pattern};
use crate::analyzer::{ use crate::analyzer::{
...@@ -163,8 +164,7 @@ format_iter!(std::fmt::Pointer); ...@@ -163,8 +164,7 @@ format_iter!(std::fmt::Pointer);
format_iter!(std::fmt::UpperExp); format_iter!(std::fmt::UpperExp);
format_iter!(std::fmt::UpperHex); format_iter!(std::fmt::UpperHex);
#[turbo_tasks::value(shared, serialization = "none")] #[derive(Clone, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, Debug, NonLocalValue)]
#[derive(Debug, Clone)]
pub enum AstPathRange { pub enum AstPathRange {
/// The ast path to the block or expression. /// The ast path to the block or expression.
Exact(#[turbo_tasks(trace_ignore)] Vec<AstParentKind>), Exact(#[turbo_tasks(trace_ignore)] Vec<AstParentKind>),
......
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