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