Unverified Commit 74e159fb authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

Store code generation AST paths in a shared trie (#98581)

### What?

Store the AST paths that code generation uses to locate nodes in a
per-module trie, referenced by a 4-byte id, instead of a
`Vec<AstParentKind>` per path.

### Why?

Ast paths can share long prefixes leading to quadratic behavior (in
pathological cases), even in non pathological cases there can be
redundancy.

Peak memory on a repro of 180 files, each with a 1200-term chain:

| | peak | compile |
|---|---|---|
| before | 24.0 GB | 19.1 / 17.4 / 16.5s |
| after | 4.0 GB | 13.7 / 14.2 / 14.8s |

And on an ordinary app (`vercel-site`, 5,669 files; 5 cold runs +
warmup):

| | baseline | this branch |
|---|---|---|
| user time | 321.00 s ±0.8% | 321.30 s ±0.8% |
| MaxRSS | 14,984 MB ±0.4% | 14,755 MB ±0.4% |

### How?

The trie is built lazily, interning only the paths code generation asks
for, so it stays sparse. A builder holds the child index during analysis
and is frozen into an immutable trie stored beside the code gens.

`ApplyVisitors` previously sorted the full paths and binary searched
them at every level; it now descends the trie alongside the AST walk.
Consumers that manipulated paths structurally walk it instead —
`EsmBinding` steps to a parent rather than popping, and `removal.rs` and
`code_gen::path_to` trim from the end without allocating.

Interning was profiled separately. Sorting paths first, embedding the
child map in each node, resuming interning from the previous path, and
moving `Effect`'s paths into a second trie were all measured and
rejected: each was slower, needed more memory, or was inside the noise.
Interning is not a hot path.

Ideally we would also intern the paths stored in the temporary `Effect`
enum, but this is a pure time/memory tradeoff. We can massively reduce
pressure on the arena in exchange for a 10% perf regression. Not worth
it.


<!-- NEXT_JS_LLM -->

---------
Co-authored-by: 's avatarClaude Opus 5 (1M context) <noreply@anthropic.com>
parent 02f3bebc
...@@ -15,6 +15,7 @@ pub use crate::analyzer::graph::{ ...@@ -15,6 +15,7 @@ pub use crate::analyzer::graph::{
use crate::{ use crate::{
AnalyzeMode, SpecifiedModuleType, AnalyzeMode, SpecifiedModuleType,
analyzer::{Bump, JsValue, graph::visitor::Analyzer}, analyzer::{Bump, JsValue, graph::visitor::Analyzer},
ast_path_trie::AstPathTrieBuilder,
chunk::CjsStaticExports, chunk::CjsStaticExports,
code_gen::CodeGen, code_gen::CodeGen,
}; };
...@@ -36,6 +37,9 @@ pub struct VarGraph<'a> { ...@@ -36,6 +37,9 @@ pub struct VarGraph<'a> {
pub effects: Vec<Effect<'a>>, pub effects: Vec<Effect<'a>>,
// Some unconditional codegens, usually for ESM items. // Some unconditional codegens, usually for ESM items.
pub code_gens: Vec<CodeGen>, pub code_gens: Vec<CodeGen>,
/// Interns the AST paths used by `code_gens`. Effect processing keeps interning into
/// this same trie, so every path for the module ends up sharing one arena.
pub ast_paths: AstPathTrieBuilder,
/// [`ExportUsage`] per `require("…")` call, keyed by call position; absent /// [`ExportUsage`] per `require("…")` call, keyed by call position; absent
/// calls fall back to `ExportUsage::All`. /// calls fall back to `ExportUsage::All`.
...@@ -75,6 +79,7 @@ pub fn create_graph<'a>( ...@@ -75,6 +79,7 @@ pub fn create_graph<'a>(
free_var_ids: Default::default(), free_var_ids: Default::default(),
effects: Default::default(), effects: Default::default(),
code_gens: Default::default(), code_gens: Default::default(),
ast_paths: Default::default(),
require_usage: Default::default(), require_usage: Default::default(),
cjs_static_exports: Default::default(), cjs_static_exports: Default::default(),
}, },
...@@ -83,6 +88,7 @@ pub fn create_graph<'a>( ...@@ -83,6 +88,7 @@ pub fn create_graph<'a>(
effects: Default::default(), effects: Default::default(),
hoisted_effects: Default::default(), hoisted_effects: Default::default(),
code_gens: Default::default(), code_gens: Default::default(),
ast_paths: Default::default(),
supports_block_scoping, supports_block_scoping,
}; };
......
...@@ -29,10 +29,10 @@ use crate::{ ...@@ -29,10 +29,10 @@ use crate::{
graph::{ConditionalKind, Effect, EffectArg, EffectsBlock, EvalContext, VarGraph}, graph::{ConditionalKind, Effect, EffectArg, EffectsBlock, EvalContext, VarGraph},
is_unresolved_id, is_unresolved_id,
}, },
ast_path_trie::{AstPathId, AstPathTrieBuilder},
chunk::CjsStaticExports, chunk::CjsStaticExports,
code_gen::CodeGen, code_gen::CodeGen,
references::{ references::{
AstPath,
cjs::{CjsExportsDropCodeGen, DroppableCjsExportAssignment}, cjs::{CjsExportsDropCodeGen, DroppableCjsExportAssignment},
esm::EsmModuleItem, esm::EsmModuleItem,
}, },
...@@ -88,6 +88,8 @@ pub(super) struct Analyzer<'arena, 'eval> { ...@@ -88,6 +88,8 @@ pub(super) struct Analyzer<'arena, 'eval> {
// Some unconditional codegens, usually for ESM items. // Some unconditional codegens, usually for ESM items.
pub(super) code_gens: Vec<CodeGen>, pub(super) code_gens: Vec<CodeGen>,
/// Interns the AST paths used by `code_gens`; handed to the [`VarGraph`] at the end.
pub(super) ast_paths: AstPathTrieBuilder,
/// Whether we may codegen `let` and `const` or if we should fallback to var (at the cost of /// Whether we may codegen `let` and `const` or if we should fallback to var (at the cost of
/// slightly less correct circular import errors) for EsmModuleItem /// slightly less correct circular import errors) for EsmModuleItem
...@@ -502,7 +504,9 @@ mod analyzer_state { ...@@ -502,7 +504,9 @@ mod analyzer_state {
} => { } => {
let block = EffectsBlock { let block = EffectsBlock {
effects: take(&mut self.effects).into_boxed_slice(), effects: take(&mut self.effects).into_boxed_slice(),
range: AstPathRange::StartAfter(start_ast_path.to_vec()), range: AstPathRange::StartAfter(
self.ast_paths.intern(start_ast_path.iter().copied()),
),
}; };
self.effects = prev_effects; self.effects = prev_effects;
let kind = match (then, r#else, early_return_condition_value) { let kind = match (then, r#else, early_return_condition_value) {
...@@ -705,11 +709,11 @@ mod analyzer_state { ...@@ -705,11 +709,11 @@ mod analyzer_state {
} }
} }
pub(super) fn record_cjs_export(&mut self, name: RcStr, path: AstPath) { pub(super) fn record_cjs_export(&mut self, name: RcStr, path: AstPathId) {
self.push_cjs_export(DroppableCjsExportAssignment::Write { name, path }); self.push_cjs_export(DroppableCjsExportAssignment::Write { name, path });
} }
pub(super) fn record_dead_cjs_write(&mut self, name: RcStr, path: AstPath) { pub(super) fn record_dead_cjs_write(&mut self, name: RcStr, path: AstPathId) {
if let Some(c) = &mut self.state.cjs_exports { if let Some(c) = &mut self.state.cjs_exports {
c.dead_writes c.dead_writes
.push(DroppableCjsExportAssignment::Write { name, path }); .push(DroppableCjsExportAssignment::Write { name, path });
...@@ -721,7 +725,7 @@ mod analyzer_state { ...@@ -721,7 +725,7 @@ mod analyzer_state {
pub(super) fn record_cjs_object_literal_exports( pub(super) fn record_cjs_object_literal_exports(
&mut self, &mut self,
names: Vec<RcStr>, names: Vec<RcStr>,
path: AstPath, path: AstPathId,
) { ) {
self.push_cjs_export(DroppableCjsExportAssignment::ObjectLiteral { names, path }); self.push_cjs_export(DroppableCjsExportAssignment::ObjectLiteral { names, path });
} }
...@@ -986,17 +990,6 @@ fn extract_names_from_then_callback(call: &CallExpr) -> Option<SmallVec<[RcStr; ...@@ -986,17 +990,6 @@ fn extract_names_from_then_callback(call: &CallExpr) -> Option<SmallVec<[RcStr;
} }
} }
pub fn as_parent_path_with(
ast_path: &AstNodePath<AstParentNodeRef<'_>>,
additional: AstParentKind,
) -> Vec<AstParentKind> {
let kinds = ast_path.kinds();
let mut path = Vec::with_capacity(kinds.len() + 1);
path.extend_from_slice(kinds);
path.push(additional);
path
}
enum CallOrNewExpr<'ast> { enum CallOrNewExpr<'ast> {
Call(&'ast CallExpr), Call(&'ast CallExpr),
New(&'ast NewExpr), New(&'ast NewExpr),
...@@ -1346,7 +1339,9 @@ impl<'a> Analyzer<'a, '_> { ...@@ -1346,7 +1339,9 @@ impl<'a> Analyzer<'a, '_> {
BumpBox::new_in( BumpBox::new_in(
EffectsBlock { EffectsBlock {
effects: effects.into_boxed_slice(), effects: effects.into_boxed_slice(),
range: AstPathRange::Exact(path), range: AstPathRange::Exact(
self.ast_paths.intern(path.iter().copied()),
),
}, },
self.arena, self.arena,
), ),
...@@ -1450,10 +1445,9 @@ impl<'a> Analyzer<'a, '_> { ...@@ -1450,10 +1445,9 @@ impl<'a> Analyzer<'a, '_> {
fn add_esm_module_item(&mut self, ast_path: &AstNodePath<AstParentNodeRef<'_>>) { fn add_esm_module_item(&mut self, ast_path: &AstNodePath<AstParentNodeRef<'_>>) {
if self.analyze_mode.is_code_gen() { if self.analyze_mode.is_code_gen() {
self.code_gens.push( let path = self.ast_paths.intern(ast_path.kinds().iter().copied());
EsmModuleItem::new(as_parent_path(ast_path).into(), self.supports_block_scoping) self.code_gens
.into(), .push(EsmModuleItem::new(path, self.supports_block_scoping).into());
);
} }
} }
...@@ -1495,7 +1489,7 @@ impl<'a> Analyzer<'a, '_> { ...@@ -1495,7 +1489,7 @@ impl<'a> Analyzer<'a, '_> {
// The RHS isn't inspected; the code-gen keeps it as `<value>`. // The RHS isn't inspected; the code-gen keeps it as `<value>`.
let name = RcStr::from(name.sym.as_str()); let name = RcStr::from(name.sym.as_str());
let path = as_parent_path(ast_path).into(); let path = self.ast_paths.intern(ast_path.kinds().iter().copied());
if dead { if dead {
self.record_dead_cjs_write(name, path); self.record_dead_cjs_write(name, path);
} else { } else {
...@@ -1531,7 +1525,8 @@ impl<'a> Analyzer<'a, '_> { ...@@ -1531,7 +1525,8 @@ impl<'a> Analyzer<'a, '_> {
} }
return; return;
} }
let (name, path) = (RcStr::from(name), as_parent_path(ast_path).into()); let path = self.ast_paths.intern(ast_path.kinds().iter().copied());
let name = RcStr::from(name);
if dead { if dead {
self.record_dead_cjs_write(name, path); self.record_dead_cjs_write(name, path);
} else { } else {
...@@ -1604,7 +1599,8 @@ impl<'a> Analyzer<'a, '_> { ...@@ -1604,7 +1599,8 @@ impl<'a> Analyzer<'a, '_> {
names.push(name); names.push(name);
} }
if !names.is_empty() { if !names.is_empty() {
self.record_cjs_object_literal_exports(names, as_parent_path(ast_path).into()); let path = self.ast_paths.intern(ast_path.kinds().iter().copied());
self.record_cjs_object_literal_exports(names, path);
} }
} }
} }
...@@ -2587,6 +2583,7 @@ impl VisitAstPath for Analyzer<'_, '_> { ...@@ -2587,6 +2583,7 @@ impl VisitAstPath for Analyzer<'_, '_> {
self.data.cjs_static_exports = cjs_static_exports; self.data.cjs_static_exports = cjs_static_exports;
self.data.code_gens = take(&mut self.code_gens); self.data.code_gens = take(&mut self.code_gens);
self.data.ast_paths = take(&mut self.ast_paths);
} }
fn visit_cond_expr<'ast: 'r, 'r>( fn visit_cond_expr<'ast: 'r, 'r>(
...@@ -2607,7 +2604,7 @@ impl VisitAstPath for Analyzer<'_, '_> { ...@@ -2607,7 +2604,7 @@ impl VisitAstPath for Analyzer<'_, '_> {
expr.cons.visit_with_ast_path(self, &mut ast_path); expr.cons.visit_with_ast_path(self, &mut ast_path);
EffectsBlock { EffectsBlock {
effects: take(&mut self.effects).into_boxed_slice(), effects: take(&mut self.effects).into_boxed_slice(),
range: AstPathRange::Exact(as_parent_path(&ast_path)), range: AstPathRange::Exact(self.ast_paths.intern(ast_path.kinds().iter().copied())),
} }
}; };
let r#else = { let r#else = {
...@@ -2616,7 +2613,7 @@ impl VisitAstPath for Analyzer<'_, '_> { ...@@ -2616,7 +2613,7 @@ impl VisitAstPath for Analyzer<'_, '_> {
expr.alt.visit_with_ast_path(self, &mut ast_path); expr.alt.visit_with_ast_path(self, &mut ast_path);
EffectsBlock { EffectsBlock {
effects: take(&mut self.effects).into_boxed_slice(), effects: take(&mut self.effects).into_boxed_slice(),
range: AstPathRange::Exact(as_parent_path(&ast_path)), range: AstPathRange::Exact(self.ast_paths.intern(ast_path.kinds().iter().copied())),
} }
}; };
self.effects = prev_effects; self.effects = prev_effects;
...@@ -2653,7 +2650,7 @@ impl VisitAstPath for Analyzer<'_, '_> { ...@@ -2653,7 +2650,7 @@ impl VisitAstPath for Analyzer<'_, '_> {
EffectsBlock { EffectsBlock {
effects: take(&mut self.effects).into_boxed_slice(), effects: take(&mut self.effects).into_boxed_slice(),
range: AstPathRange::Exact(as_parent_path(&ast_path)), range: AstPathRange::Exact(self.ast_paths.intern(ast_path.kinds().iter().copied())),
} }
}; };
let mut else_returning = false; let mut else_returning = false;
...@@ -2668,7 +2665,7 @@ impl VisitAstPath for Analyzer<'_, '_> { ...@@ -2668,7 +2665,7 @@ impl VisitAstPath for Analyzer<'_, '_> {
EffectsBlock { EffectsBlock {
effects: take(&mut self.effects).into_boxed_slice(), effects: take(&mut self.effects).into_boxed_slice(),
range: AstPathRange::Exact(as_parent_path(&ast_path)), range: AstPathRange::Exact(self.ast_paths.intern(ast_path.kinds().iter().copied())),
} }
}); });
self.effects = prev_effects; self.effects = prev_effects;
...@@ -2828,6 +2825,11 @@ impl VisitAstPath for Analyzer<'_, '_> { ...@@ -2828,6 +2825,11 @@ impl VisitAstPath for Analyzer<'_, '_> {
}); });
let effects = take(&mut self.effects); let effects = take(&mut self.effects);
let labeled_body_path = self
.ast_paths
.intern(ast_path.kinds().iter().copied().chain(iter::once(
AstParentKind::LabeledStmt(LabeledStmtField::Body),
)));
prev_effects.push( prev_effects.push(
self.arena, self.arena,
...@@ -2840,10 +2842,7 @@ impl VisitAstPath for Analyzer<'_, '_> { ...@@ -2840,10 +2842,7 @@ impl VisitAstPath for Analyzer<'_, '_> {
ConditionalKind::Labeled { ConditionalKind::Labeled {
body: EffectsBlock { body: EffectsBlock {
effects: effects.into_boxed_slice(), effects: effects.into_boxed_slice(),
range: AstPathRange::Exact(as_parent_path_with( range: AstPathRange::Exact(labeled_body_path),
ast_path,
AstParentKind::LabeledStmt(LabeledStmtField::Body),
)),
}, },
}, },
self.arena, self.arena,
......
This diff is collapsed.
...@@ -16,9 +16,9 @@ use turbopack_core::{chunk::ChunkingContext, reference::ModuleReference}; ...@@ -16,9 +16,9 @@ use turbopack_core::{chunk::ChunkingContext, reference::ModuleReference};
use crate::{ use crate::{
ScopeHoistingContext, ScopeHoistingContext,
ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder},
chunk::{EcmascriptChunkPlaceable, EcmascriptExports}, chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
references::{ references::{
AstPath,
amd::AmdDefineWithDependenciesCodeGen, amd::AmdDefineWithDependenciesCodeGen,
cjs::{ cjs::{
CjsExportsDropCodeGen, CjsRequireAssetReferenceCodeGen, CjsRequireCacheAccess, CjsExportsDropCodeGen, CjsRequireAssetReferenceCodeGen, CjsRequireCacheAccess,
...@@ -48,7 +48,7 @@ use crate::{ ...@@ -48,7 +48,7 @@ use crate::{
#[derive(Default)] #[derive(Default)]
pub struct CodeGeneration { pub struct CodeGeneration {
/// ast nodes matching the span will be visitor by the visitor /// ast nodes matching the span will be visitor by the visitor
pub visitors: Vec<(Vec<AstParentKind>, Box<dyn AstModifier>)>, pub visitors: Vec<(AstPathId, Box<dyn AstModifier>)>,
pub hoisted_stmts: Vec<CodeGenerationHoistedStmt>, pub hoisted_stmts: Vec<CodeGenerationHoistedStmt>,
pub early_hoisted_stmts: Vec<CodeGenerationHoistedStmt>, pub early_hoisted_stmts: Vec<CodeGenerationHoistedStmt>,
pub late_stmts: Vec<CodeGenerationHoistedStmt>, pub late_stmts: Vec<CodeGenerationHoistedStmt>,
...@@ -64,7 +64,7 @@ impl CodeGeneration { ...@@ -64,7 +64,7 @@ impl CodeGeneration {
} }
pub fn new( pub fn new(
visitors: Vec<(Vec<AstParentKind>, Box<dyn AstModifier>)>, visitors: Vec<(AstPathId, Box<dyn AstModifier>)>,
hoisted_stmts: Vec<CodeGenerationHoistedStmt>, hoisted_stmts: Vec<CodeGenerationHoistedStmt>,
early_hoisted_stmts: Vec<CodeGenerationHoistedStmt>, early_hoisted_stmts: Vec<CodeGenerationHoistedStmt>,
late_stmts: Vec<CodeGenerationHoistedStmt>, late_stmts: Vec<CodeGenerationHoistedStmt>,
...@@ -81,7 +81,7 @@ impl CodeGeneration { ...@@ -81,7 +81,7 @@ impl CodeGeneration {
} }
pub fn visitors_with_comments( pub fn visitors_with_comments(
visitors: Vec<(Vec<AstParentKind>, Box<dyn AstModifier>)>, visitors: Vec<(AstPathId, Box<dyn AstModifier>)>,
comments: SwcComments, comments: SwcComments,
) -> Self { ) -> Self {
CodeGeneration { CodeGeneration {
...@@ -91,7 +91,7 @@ impl CodeGeneration { ...@@ -91,7 +91,7 @@ impl CodeGeneration {
} }
} }
pub fn visitors(visitors: Vec<(Vec<AstParentKind>, Box<dyn AstModifier>)>) -> Self { pub fn visitors(visitors: Vec<(AstPathId, Box<dyn AstModifier>)>) -> Self {
CodeGeneration { CodeGeneration {
visitors, visitors,
..Default::default() ..Default::default()
...@@ -216,53 +216,65 @@ pub enum CodeGen { ...@@ -216,53 +216,65 @@ pub enum CodeGen {
impl CodeGen { impl CodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
ctx: Vc<Box<dyn ChunkingContext>>, ctx: Vc<Box<dyn ChunkingContext>>,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
exports: ResolvedVc<EcmascriptExports>, exports: ResolvedVc<EcmascriptExports>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
match self { match self {
Self::AmdDefineWithDependenciesCodeGen(v) => v.code_generation(ctx).await, Self::AmdDefineWithDependenciesCodeGen(v) => v.code_generation(trie, ctx).await,
Self::CjsRequireCacheAccess(v) => v.code_generation(ctx).await, Self::CjsRequireCacheAccess(v) => v.code_generation(trie, ctx).await,
Self::ConstantConditionCodeGen(v) => v.code_generation(ctx).await, Self::ConstantConditionCodeGen(v) => v.code_generation(trie, ctx).await,
Self::CollectReferenceCodeGen(v) => v.code_generation(ctx).await, Self::CollectReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::ConstantValueCodeGen(v) => v.code_generation(ctx).await, Self::ConstantValueCodeGen(v) => v.code_generation(trie, ctx).await,
Self::DynamicExpression(v) => v.code_generation(ctx).await, Self::DynamicExpression(v) => v.code_generation(trie, ctx).await,
Self::EsmBinding(v) => v.code_generation(ctx, scope_hoisting_context).await, Self::EsmBinding(v) => v.code_generation(trie, ctx, scope_hoisting_context).await,
Self::EsmModuleItem(v) => v.code_generation(ctx).await, Self::EsmModuleItem(v) => v.code_generation(trie, ctx).await,
Self::ExportsInfoBinding(v) => v.code_generation(ctx, module, exports).await, Self::ExportsInfoBinding(v) => v.code_generation(trie, ctx, module, exports).await,
Self::ExportsInfoRef(v) => v.code_generation(ctx).await, Self::ExportsInfoRef(v) => v.code_generation(trie, ctx).await,
Self::CjsExportsDropCodeGen(v) => v.code_generation(ctx, module, exports).await, Self::CjsExportsDropCodeGen(v) => v.code_generation(trie, ctx, module, exports).await,
Self::IdentReplacement(v) => v.code_generation(ctx).await, Self::IdentReplacement(v) => v.code_generation(trie, ctx).await,
Self::ImportMetaBinding(v) => v.code_generation(ctx).await, Self::ImportMetaBinding(v) => v.code_generation(trie, ctx).await,
Self::ImportMetaRef(v) => v.code_generation(ctx).await, Self::ImportMetaRef(v) => v.code_generation(trie, ctx).await,
Self::MemberReplacement(v) => v.code_generation(ctx).await, Self::MemberReplacement(v) => v.code_generation(trie, ctx).await,
Self::RemovalCodeGen(v) => v.code_generation(ctx).await, Self::RemovalCodeGen(v) => v.code_generation(trie, ctx).await,
Self::CjsRequireAssetReferenceCodeGen(v) => v.code_generation(ctx).await, Self::CjsRequireAssetReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::CjsRequireResolveAssetReferenceCodeGen(v) => v.code_generation(ctx).await, Self::CjsRequireResolveAssetReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::EsmAsyncAssetReferenceCodeGen(v) => v.code_generation(ctx).await, Self::EsmAsyncAssetReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::EsmModuleIdAssetReferenceCodeGen(v) => v.code_generation(ctx).await, Self::EsmModuleIdAssetReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::ImportMetaGlobAssetReferenceCodeGen(v) => v.code_generation(ctx).await, Self::ImportMetaGlobAssetReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::RequireContextAssetReferenceCodeGen(v) => v.code_generation(ctx).await, Self::RequireContextAssetReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::UrlAssetReferenceCodeGen(v) => v.code_generation(ctx).await, Self::UrlAssetReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::WorkerAssetReferenceCodeGen(v) => v.code_generation(ctx).await, Self::WorkerAssetReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::ServiceWorkerAssetReferenceCodeGen(v) => v.code_generation(ctx).await, Self::ServiceWorkerAssetReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::ModuleHotReferenceCodeGen(v) => { Self::ModuleHotReferenceCodeGen(v) => {
v.code_generation(ctx, scope_hoisting_context).await v.code_generation(trie, ctx, scope_hoisting_context).await
} }
Self::WorkerGlobalsReplacementCodeGen(v) => v.code_generation(ctx).await, Self::WorkerGlobalsReplacementCodeGen(v) => v.code_generation(trie, ctx).await,
} }
} }
} }
#[turbo_tasks::value(transparent)] /// The code generations for a module, together with the trie their [`AstPathId`]s index into.
pub struct CodeGens(Vec<CodeGen>); ///
/// The trie is shared by every code generation here, so it is stored once alongside them
/// rather than being cloned into each one.
#[turbo_tasks::value(shared)]
pub struct CodeGens {
pub code_gens: Vec<CodeGen>,
pub ast_paths: AstPathTrie,
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl CodeGens { impl CodeGens {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn empty() -> Vc<Self> { pub fn empty() -> Vc<Self> {
Vc::cell(Vec::new()) CodeGens {
code_gens: Vec::new(),
ast_paths: AstPathTrie::default(),
}
.cell()
} }
} }
...@@ -270,20 +282,23 @@ pub trait IntoCodeGenReference { ...@@ -270,20 +282,23 @@ pub trait IntoCodeGenReference {
fn into_reference(self) -> ResolvedVc<Box<dyn ModuleReference>>; fn into_reference(self) -> ResolvedVc<Box<dyn ModuleReference>>;
fn into_code_gen_reference( fn into_code_gen_reference(
self, self,
path: AstPath, trie: &AstPathTrieBuilder,
path: AstPathId,
) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen); ) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen);
} }
/// The prefix of `path` up to (excluding) its innermost element matching `f`.
///
/// Returns the whole path when nothing matches.
pub fn path_to( pub fn path_to(
path: &[AstParentKind], trie: &AstPathTrie,
path: AstPathId,
f: impl FnMut(&AstParentKind) -> bool, f: impl FnMut(&AstParentKind) -> bool,
) -> Vec<AstParentKind> { ) -> AstPathId {
if let Some(pos) = path.iter().rev().position(f) { // Everything from the innermost match down is dropped; with no match the path is used
let index = path.len() - pos - 1; // as-is.
path[..index].to_vec() trie.find_last(path, f)
} else { .map_or(path, |found| trie.parent_or_root(found))
path.to_vec()
}
} }
/// Creates a single-method visitor that will visit the AST nodes matching the /// Creates a single-method visitor that will visit the AST nodes matching the
...@@ -297,11 +312,13 @@ pub fn path_to( ...@@ -297,11 +312,13 @@ pub fn path_to(
/// possible visit methods. /// possible visit methods.
#[macro_export] #[macro_export]
macro_rules! create_visitor { macro_rules! create_visitor {
(exact, $ast_path:expr, $name:ident, |$arg:ident: &mut $ty:ident| $b:block) => { // `exact` means the path already points at the node to modify, so unlike the arm below
$crate::create_visitor!(__ $ast_path.to_vec(), $name, |$arg: &mut $ty| $b) // it needs no trie to find an enclosing node.
(exact, $trie:expr, $ast_path:expr, $name:ident, |$arg:ident: &mut $ty:ident| $b:block) => {
$crate::create_visitor!(__ $ast_path, $name, |$arg: &mut $ty| $b)
}; };
($ast_path:expr, $name:ident, |$arg:ident: &mut $ty:ident| $b:block) => { ($trie:expr, $ast_path:expr, $name:ident, |$arg:ident: &mut $ty:ident| $b:block) => {
$crate::create_visitor!(__ $crate::code_gen::path_to(&$ast_path, |n| { $crate::create_visitor!(__ $crate::code_gen::path_to($trie, $ast_path, |n| {
matches!(n, swc_core::ecma::visit::AstParentKind::$ty(_)) matches!(n, swc_core::ecma::visit::AstParentKind::$ty(_))
}), $name, |$arg: &mut $ty| $b) }), $name, |$arg: &mut $ty| $b)
}; };
...@@ -320,7 +337,7 @@ macro_rules! create_visitor { ...@@ -320,7 +337,7 @@ macro_rules! create_visitor {
{ {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
if $ast_path.is_empty() { if $ast_path.is_root() {
unreachable!("if the path is empty, the visitor should be a root visitor"); unreachable!("if the path is empty, the visitor should be a root visitor");
} }
......
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
pub mod analyzer; pub mod analyzer;
pub mod annotations; pub mod annotations;
pub mod ast_path_trie;
pub mod async_chunk; pub mod async_chunk;
pub mod bytes_source_transform; pub mod bytes_source_transform;
pub mod chunk; pub mod chunk;
...@@ -108,6 +109,7 @@ use turbopack_core::{ ...@@ -108,6 +109,7 @@ use turbopack_core::{
use crate::{ use crate::{
analyzer::{graph::EvalContext, side_effects::compute_module_evaluation_side_effects}, analyzer::{graph::EvalContext, side_effects::compute_module_evaluation_side_effects},
ast_path_trie::AstPathTrie,
chunk::{ chunk::{
EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports, EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports,
ecmascript_chunk_item, ecmascript_chunk_item,
...@@ -117,7 +119,7 @@ use crate::{ ...@@ -117,7 +119,7 @@ use crate::{
directive::parse_module_turbopack_directives, directive::parse_module_turbopack_directives,
merged_module::MergedEcmascriptModule, merged_module::MergedEcmascriptModule,
parse::{IdentCollector, ParseResult, generate_js_source_map, parse}, parse::{IdentCollector, ParseResult, generate_js_source_map, parse},
path_visitor::ApplyVisitors, path_visitor::{ApplyVisitors, Visitors},
references::{ references::{
analyze_ecmascript_module, analyze_ecmascript_module,
async_module::OptionAsyncModule, async_module::OptionAsyncModule,
...@@ -1060,7 +1062,7 @@ impl EcmascriptModuleContentOptions { ...@@ -1060,7 +1062,7 @@ impl EcmascriptModuleContentOptions {
&self, &self,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
eval_context: &EvalContext, eval_context: &EvalContext,
) -> Result<Vec<CodeGeneration>> { ) -> Result<(Vec<CodeGeneration>, ReadRef<CodeGens>)> {
// Don't read `parsed` here again, it will cause a recomputation as `process_parse_result` // Don't read `parsed` here again, it will cause a recomputation as `process_parse_result`
// has consumed the cell already. // has consumed the cell already.
let EcmascriptModuleContentOptions { let EcmascriptModuleContentOptions {
...@@ -1120,11 +1122,13 @@ impl EcmascriptModuleContentOptions { ...@@ -1120,11 +1122,13 @@ impl EcmascriptModuleContentOptions {
.try_join() .try_join()
.await?; .await?;
let code_generation = code_generation.await?;
let code_gens = code_generation let code_gens = code_generation
.await? .code_gens
.iter() .iter()
.map(|c| { .map(|c| {
c.code_generation( c.code_generation(
&code_generation.ast_paths,
**chunking_context, **chunking_context,
scope_hoisting_context, scope_hoisting_context,
*module, *module,
...@@ -1134,14 +1138,15 @@ impl EcmascriptModuleContentOptions { ...@@ -1134,14 +1138,15 @@ impl EcmascriptModuleContentOptions {
.try_join() .try_join()
.await?; .await?;
anyhow::Ok( anyhow::Ok((
part_code_gens part_code_gens
.into_iter() .into_iter()
.chain(esm_code_gens) .chain(esm_code_gens)
.chain(additional_code_gens.into_iter().flatten()) .chain(additional_code_gens.into_iter().flatten())
.chain(code_gens) .chain(code_gens)
.collect(), .collect(),
) code_generation,
))
} }
.instrument(tracing::info_span!("precompute code generation")) .instrument(tracing::info_span!("precompute code generation"))
.await .await
...@@ -1918,7 +1923,7 @@ async fn process_parse_result( ...@@ -1918,7 +1923,7 @@ async fn process_parse_result(
) )
.into_inner(); .into_inner();
let (mut code_gens, retain_syntax_context, prepend_ident_comment) = let (mut code_gens, ast_paths, retain_syntax_context, prepend_ident_comment) =
if let Some(scope_hoisting_options) = scope_hoisting_options { if let Some(scope_hoisting_options) = scope_hoisting_options {
let is_import_mark = GLOBALS.set(globals, || Mark::new()); let is_import_mark = GLOBALS.set(globals, || Mark::new());
...@@ -1930,7 +1935,7 @@ async fn process_parse_result( ...@@ -1930,7 +1935,7 @@ async fn process_parse_result(
is_import_mark, is_import_mark,
globals, globals,
}; };
let code_gens = options let (code_gens, ast_paths) = options
.unwrap() .unwrap()
.merged_code_gens( .merged_code_gens(
ctx, ctx,
...@@ -1977,6 +1982,7 @@ async fn process_parse_result( ...@@ -1977,6 +1982,7 @@ async fn process_parse_result(
( (
code_gens, code_gens,
Some(ast_paths),
Some(( Some((
is_import_mark, is_import_mark,
module_syntax_contexts_cache, module_syntax_contexts_cache,
...@@ -1986,21 +1992,18 @@ async fn process_parse_result( ...@@ -1986,21 +1992,18 @@ async fn process_parse_result(
prepend_ident_comment, prepend_ident_comment,
) )
} else if let Some(options) = options { } else if let Some(options) = options {
( let (code_gens, ast_paths) = options
options .merged_code_gens(
.merged_code_gens( ScopeHoistingContext::None,
ScopeHoistingContext::None, match &eval_context {
match &eval_context { Either::Left(e) => e,
Either::Left(e) => e, Either::Right(e) => e,
Either::Right(e) => e, },
}, )
) .await?;
.await?, (code_gens, Some(ast_paths), None, None)
None,
None,
)
} else { } else {
(vec![], None, None) (vec![], None, None, None)
}; };
let extra_comments = SwcComments { let extra_comments = SwcComments {
...@@ -2008,8 +2011,12 @@ async fn process_parse_result( ...@@ -2008,8 +2011,12 @@ async fn process_parse_result(
trailing: Default::default(), trailing: Default::default(),
}; };
let early_hoisted_count = let early_hoisted_count = process_content_with_code_gens(
process_content_with_code_gens(&mut program, globals, &mut code_gens); &mut program,
globals,
ast_paths.as_deref().map(|p| &p.ast_paths),
&mut code_gens,
);
for comments in code_gens.iter_mut().flat_map(|cg| cg.comments.as_mut()) { for comments in code_gens.iter_mut().flat_map(|cg| cg.comments.as_mut()) {
let leading = Arc::unwrap_or_clone(take(&mut comments.leading)); let leading = Arc::unwrap_or_clone(take(&mut comments.leading));
...@@ -2373,6 +2380,7 @@ async fn emit_content( ...@@ -2373,6 +2380,7 @@ async fn emit_content(
fn process_content_with_code_gens( fn process_content_with_code_gens(
program: &mut Program, program: &mut Program,
globals: &Globals, globals: &Globals,
trie: Option<&AstPathTrie>,
code_gens: &mut Vec<CodeGeneration>, code_gens: &mut Vec<CodeGeneration>,
) -> usize { ) -> usize {
let mut visitors = Vec::new(); let mut visitors = Vec::new();
...@@ -2395,20 +2403,24 @@ fn process_content_with_code_gens( ...@@ -2395,20 +2403,24 @@ fn process_content_with_code_gens(
early_late_stmts.insert(key.clone(), stmt); early_late_stmts.insert(key.clone(), stmt);
} }
for (path, visitor) in &code_gen.visitors { for (path, visitor) in &code_gen.visitors {
if path.is_empty() { if path.is_root() {
root_visitors.push(&**visitor); root_visitors.push(&**visitor);
} else { } else {
visitors.push((path, &**visitor)); visitors.push((*path, &**visitor));
} }
} }
} }
GLOBALS.set(globals, || { GLOBALS.set(globals, || {
if !visitors.is_empty() { if !visitors.is_empty() {
program.visit_mut_with_ast_path( let trie = trie.expect("code gens with visitors always come with their trie");
&mut ApplyVisitors::new(visitors), let visitors = Visitors::new(trie, visitors);
&mut Default::default(), if !visitors.is_empty() {
); program.visit_mut_with_ast_path(
&mut ApplyVisitors::new(&visitors),
&mut Default::default(),
);
}
} }
for pass in root_visitors { for pass in root_visitors {
program.modify(pass); program.modify(pass);
......
...@@ -24,12 +24,10 @@ use turbopack_core::{ ...@@ -24,12 +24,10 @@ use turbopack_core::{
use turbopack_resolve::ecmascript::cjs_resolve; use turbopack_resolve::ecmascript::cjs_resolve;
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie},
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
references::{ references::pattern_mapping::{PatternMapping, ResolveType},
AstPath,
pattern_mapping::{PatternMapping, ResolveType},
},
runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_REQUIRE}, runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_REQUIRE},
}; };
...@@ -124,7 +122,7 @@ pub enum AmdDefineFactoryType { ...@@ -124,7 +122,7 @@ pub enum AmdDefineFactoryType {
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: AstPath, path: AstPathId,
factory_type: AmdDefineFactoryType, factory_type: AmdDefineFactoryType,
issue_source: IssueSource, issue_source: IssueSource,
error_mode: ResolveErrorMode, error_mode: ResolveErrorMode,
...@@ -134,7 +132,7 @@ impl AmdDefineWithDependenciesCodeGen { ...@@ -134,7 +132,7 @@ 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: AstPath, path: AstPathId,
factory_type: AmdDefineFactoryType, factory_type: AmdDefineFactoryType,
issue_source: IssueSource, issue_source: IssueSource,
error_mode: ResolveErrorMode, error_mode: ResolveErrorMode,
...@@ -151,6 +149,7 @@ impl AmdDefineWithDependenciesCodeGen { ...@@ -151,6 +149,7 @@ impl AmdDefineWithDependenciesCodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
_trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let mut visitors = Vec::new(); let mut visitors = Vec::new();
...@@ -199,6 +198,7 @@ impl AmdDefineWithDependenciesCodeGen { ...@@ -199,6 +198,7 @@ impl AmdDefineWithDependenciesCodeGen {
visitors.push(create_visitor!( visitors.push(create_visitor!(
exact, exact,
trie,
self.path, self.path,
visit_mut_call_expr, visit_mut_call_expr,
|call_expr: &mut CallExpr| { |call_expr: &mut CallExpr| {
......
...@@ -29,11 +29,11 @@ use turbopack_core::{ ...@@ -29,11 +29,11 @@ use turbopack_core::{
use turbopack_resolve::ecmascript::cjs_resolve; use turbopack_resolve::ecmascript::cjs_resolve;
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder},
chunk::{EcmascriptChunkPlaceable, EcmascriptExports}, chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference}, code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference},
create_visitor, create_visitor,
references::{ references::{
AstPath,
pattern_mapping::{PatternMapping, ResolveType}, pattern_mapping::{PatternMapping, ResolveType},
util::SpecifiedChunkingType, util::SpecifiedChunkingType,
}, },
...@@ -180,7 +180,8 @@ impl IntoCodeGenReference for CjsRequireAssetReference { ...@@ -180,7 +180,8 @@ impl IntoCodeGenReference for CjsRequireAssetReference {
fn into_code_gen_reference( fn into_code_gen_reference(
self, self,
path: AstPath, _trie: &AstPathTrieBuilder,
path: AstPathId,
) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) { ) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) {
let reference = self.resolved_cell(); let reference = self.resolved_cell();
( (
...@@ -198,12 +199,13 @@ impl IntoCodeGenReference for CjsRequireAssetReference { ...@@ -198,12 +199,13 @@ impl IntoCodeGenReference for CjsRequireAssetReference {
)] )]
pub struct CjsRequireAssetReferenceCodeGen { pub struct CjsRequireAssetReferenceCodeGen {
reference: ResolvedVc<CjsRequireAssetReference>, reference: ResolvedVc<CjsRequireAssetReference>,
path: AstPath, path: AstPathId,
} }
impl CjsRequireAssetReferenceCodeGen { impl CjsRequireAssetReferenceCodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let reference = self.reference.await?; let reference = self.reference.await?;
...@@ -220,6 +222,7 @@ impl CjsRequireAssetReferenceCodeGen { ...@@ -220,6 +222,7 @@ impl CjsRequireAssetReferenceCodeGen {
let mut visitors = Vec::new(); let mut visitors = Vec::new();
visitors.push(create_visitor!( visitors.push(create_visitor!(
trie,
self.path, self.path,
visit_mut_expr, visit_mut_expr,
|expr: &mut Expr| { |expr: &mut Expr| {
...@@ -326,7 +329,8 @@ impl IntoCodeGenReference for CjsRequireResolveAssetReference { ...@@ -326,7 +329,8 @@ impl IntoCodeGenReference for CjsRequireResolveAssetReference {
fn into_code_gen_reference( fn into_code_gen_reference(
self, self,
path: AstPath, _trie: &AstPathTrieBuilder,
path: AstPathId,
) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) { ) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) {
let reference = self.resolved_cell(); let reference = self.resolved_cell();
( (
...@@ -343,12 +347,13 @@ impl IntoCodeGenReference for CjsRequireResolveAssetReference { ...@@ -343,12 +347,13 @@ impl IntoCodeGenReference for CjsRequireResolveAssetReference {
)] )]
pub struct CjsRequireResolveAssetReferenceCodeGen { pub struct CjsRequireResolveAssetReferenceCodeGen {
reference: ResolvedVc<CjsRequireResolveAssetReference>, reference: ResolvedVc<CjsRequireResolveAssetReference>,
path: AstPath, path: AstPathId,
} }
impl CjsRequireResolveAssetReferenceCodeGen { impl CjsRequireResolveAssetReferenceCodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let reference = self.reference.await?; let reference = self.reference.await?;
...@@ -366,6 +371,7 @@ impl CjsRequireResolveAssetReferenceCodeGen { ...@@ -366,6 +371,7 @@ impl CjsRequireResolveAssetReferenceCodeGen {
// Inline the result of the `require.resolve` call as a literal. // Inline the result of the `require.resolve` call as a literal.
visitors.push(create_visitor!( visitors.push(create_visitor!(
trie,
self.path, self.path,
visit_mut_expr, visit_mut_expr,
|expr: &mut Expr| { |expr: &mut Expr| {
...@@ -405,20 +411,22 @@ impl CjsRequireResolveAssetReferenceCodeGen { ...@@ -405,20 +411,22 @@ impl CjsRequireResolveAssetReferenceCodeGen {
PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Debug, Hash, Encode, Decode, PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Debug, Hash, Encode, Decode,
)] )]
pub struct CjsRequireCacheAccess { pub struct CjsRequireCacheAccess {
pub path: AstPath, pub path: AstPathId,
} }
impl CjsRequireCacheAccess { impl CjsRequireCacheAccess {
pub fn new(path: AstPath) -> Self { pub fn new(path: AstPathId) -> Self {
CjsRequireCacheAccess { path } CjsRequireCacheAccess { path }
} }
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let mut visitors = Vec::new(); let mut visitors = Vec::new();
visitors.push(create_visitor!( visitors.push(create_visitor!(
trie,
self.path, self.path,
visit_mut_expr, visit_mut_expr,
|expr: &mut Expr| { |expr: &mut Expr| {
...@@ -462,10 +470,10 @@ pub struct CjsExportsDropCodeGen { ...@@ -462,10 +470,10 @@ pub struct CjsExportsDropCodeGen {
pub enum DroppableCjsExportAssignment { pub enum DroppableCjsExportAssignment {
/// A standalone `exports.NAME = …` write or `Object.defineProperty(exports, …)` /// A standalone `exports.NAME = …` write or `Object.defineProperty(exports, …)`
/// call (the assignment is replaced by its value; the define call is removed). /// call (the assignment is replaced by its value; the define call is removed).
Write { name: RcStr, path: AstPath }, Write { name: RcStr, path: AstPathId },
/// A `module.exports = { … }` object literal. Every recognized property name /// A `module.exports = { … }` object literal. Every recognized property name
/// shares `path` (the assignment), so the literal is rewritten in one pass. /// shares `path` (the assignment), so the literal is rewritten in one pass.
ObjectLiteral { names: Vec<RcStr>, path: AstPath }, ObjectLiteral { names: Vec<RcStr>, path: AstPathId },
} }
impl CjsExportsDropCodeGen { impl CjsExportsDropCodeGen {
...@@ -483,6 +491,7 @@ impl CjsExportsDropCodeGen { ...@@ -483,6 +491,7 @@ impl CjsExportsDropCodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
_exports: ResolvedVc<EcmascriptExports>, _exports: ResolvedVc<EcmascriptExports>,
...@@ -513,24 +522,29 @@ impl CjsExportsDropCodeGen { ...@@ -513,24 +522,29 @@ impl CjsExportsDropCodeGen {
if !dead && export_usage_info.is_export_used(name) { if !dead && export_usage_info.is_export_used(name) {
continue; continue;
} }
visitors.push(create_visitor!(path, visit_mut_expr, |expr: &mut Expr| { visitors.push(create_visitor!(
match expr { trie,
// `exports.NAME = <value>` → `<value>` (keep side effects). *path,
Expr::Assign(assign) => { visit_mut_expr,
let value = assign.right.take(); |expr: &mut Expr| {
*expr = *value; match expr {
} // `exports.NAME = <value>` → `<value>` (keep side effects).
// `Object.defineProperty(exports, …)`: keep an eager Expr::Assign(assign) => {
// `value`'s side effects; a getter is lazy, drop the call. let value = assign.right.take();
Expr::Call(call) => { *expr = *value;
*expr = match take_define_property_value(call) { }
Some(value) => *value, // `Object.defineProperty(exports, …)`: keep an eager
None => quote!("0" as Expr), // `value`'s side effects; a getter is lazy, drop the call.
}; Expr::Call(call) => {
*expr = match take_define_property_value(call) {
Some(value) => *value,
None => quote!("0" as Expr),
};
}
_ => {}
} }
_ => {}
} }
})); ));
} }
DroppableCjsExportAssignment::ObjectLiteral { names, path } => { DroppableCjsExportAssignment::ObjectLiteral { names, path } => {
let unused = names let unused = names
...@@ -543,13 +557,18 @@ impl CjsExportsDropCodeGen { ...@@ -543,13 +557,18 @@ impl CjsExportsDropCodeGen {
} }
// `module.exports = { …, NAME: v, … }` → drop each unused `NAME`, // `module.exports = { …, NAME: v, … }` → drop each unused `NAME`,
// keeping a data value's side effects in place via `...(void v)`. // keeping a data value's side effects in place via `...(void v)`.
visitors.push(create_visitor!(path, visit_mut_expr, |expr: &mut Expr| { visitors.push(create_visitor!(
if let Expr::Assign(assign) = expr trie,
&& let Expr::Object(obj) = &mut *assign.right *path,
{ visit_mut_expr,
drop_object_literal_exports(obj, &unused); |expr: &mut Expr| {
if let Expr::Assign(assign) = expr
&& let Expr::Object(obj) = &mut *assign.right
{
drop_object_literal_exports(obj, &unused);
}
} }
})); ));
} }
} }
} }
......
...@@ -5,9 +5,9 @@ use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs ...@@ -5,9 +5,9 @@ use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs
use turbopack_core::chunk::ChunkingContext; use turbopack_core::chunk::ChunkingContext;
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie},
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
references::AstPath,
}; };
#[derive(Copy, Clone, Hash, PartialEq, Eq, Debug, TraceRawVcs, NonLocalValue, Encode, Decode)] #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug, TraceRawVcs, NonLocalValue, Encode, Decode)]
...@@ -22,21 +22,23 @@ pub enum ConstantConditionValue { ...@@ -22,21 +22,23 @@ pub enum ConstantConditionValue {
)] )]
pub struct ConstantConditionCodeGen { pub struct ConstantConditionCodeGen {
value: ConstantConditionValue, value: ConstantConditionValue,
path: AstPath, path: AstPathId,
} }
impl ConstantConditionCodeGen { impl ConstantConditionCodeGen {
pub fn new(value: ConstantConditionValue, path: AstPath) -> Self { pub fn new(value: ConstantConditionValue, path: AstPathId) -> Self {
ConstantConditionCodeGen { value, path } ConstantConditionCodeGen { value, path }
} }
pub async fn code_generation( pub async fn code_generation(
&self, &self,
_trie: &AstPathTrie,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let value = self.value; let value = self.value;
let visitors = [create_visitor!( let visitors = [create_visitor!(
exact, exact,
trie,
self.path, self.path,
visit_mut_expr, visit_mut_expr,
|expr: &mut Expr| { |expr: &mut Expr| {
......
...@@ -16,9 +16,9 @@ use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs ...@@ -16,9 +16,9 @@ use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs
use turbopack_core::{chunk::ChunkingContext, compile_time_info::CompileTimeDefineValue}; use turbopack_core::{chunk::ChunkingContext, compile_time_info::CompileTimeDefineValue};
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie},
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
references::AstPath,
}; };
#[derive( #[derive(
...@@ -26,30 +26,31 @@ use crate::{ ...@@ -26,30 +26,31 @@ use crate::{
)] )]
pub struct ConstantValueCodeGen { pub struct ConstantValueCodeGen {
value: CompileTimeDefineValue, value: CompileTimeDefineValue,
path: AstPath, path: AstPathId,
} }
impl ConstantValueCodeGen { impl ConstantValueCodeGen {
pub fn new(value: CompileTimeDefineValue, path: AstPath) -> Self { pub fn new(value: CompileTimeDefineValue, path: AstPathId) -> Self {
ConstantValueCodeGen { value, path } ConstantValueCodeGen { value, path }
} }
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let value = self.value.clone(); let value = self.value.clone();
let mut visitors = Vec::new(); let mut visitors = Vec::new();
let mut ast_path = self.path.0.clone();
if matches!( if matches!(
ast_path.last(), trie.get(self.path),
Some(swc_core::ecma::visit::AstParentKind::Prop( Some(swc_core::ecma::visit::AstParentKind::Prop(
PropField::Shorthand PropField::Shorthand
)) ))
) { ) {
ast_path.pop(); let ast_path = trie.parent_or_root(self.path);
visitors.push(create_visitor!( visitors.push(create_visitor!(
exact, exact,
trie,
ast_path, ast_path,
visit_mut_prop, visit_mut_prop,
|prop: &mut Prop| { |prop: &mut Prop| {
...@@ -63,6 +64,7 @@ impl ConstantValueCodeGen { ...@@ -63,6 +64,7 @@ impl ConstantValueCodeGen {
)); ));
} else { } else {
visitors.push(create_visitor!( visitors.push(create_visitor!(
trie,
self.path, self.path,
visit_mut_expr, visit_mut_expr,
|expr: &mut Expr| { |expr: &mut Expr| {
......
...@@ -5,9 +5,9 @@ use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs ...@@ -5,9 +5,9 @@ use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs
use turbopack_core::chunk::ChunkingContext; use turbopack_core::chunk::ChunkingContext;
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie},
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
references::AstPath,
}; };
#[derive( #[derive(
...@@ -22,19 +22,19 @@ enum DynamicExpressionType { ...@@ -22,19 +22,19 @@ enum DynamicExpressionType {
PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Debug, Hash, Encode, Decode, PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Debug, Hash, Encode, Decode,
)] )]
pub struct DynamicExpression { pub struct DynamicExpression {
path: AstPath, path: AstPathId,
ty: DynamicExpressionType, ty: DynamicExpressionType,
} }
impl DynamicExpression { impl DynamicExpression {
pub fn new(path: AstPath) -> Self { pub fn new(path: AstPathId) -> Self {
DynamicExpression { DynamicExpression {
path, path,
ty: DynamicExpressionType::Normal, ty: DynamicExpressionType::Normal,
} }
} }
pub fn new_promise(path: AstPath) -> Self { pub fn new_promise(path: AstPathId) -> Self {
DynamicExpression { DynamicExpression {
path, path,
ty: DynamicExpressionType::Promise, ty: DynamicExpressionType::Promise,
...@@ -43,11 +43,12 @@ impl DynamicExpression { ...@@ -43,11 +43,12 @@ impl DynamicExpression {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let visitor = match self.ty { let visitor = match self.ty {
DynamicExpressionType::Normal => { DynamicExpressionType::Normal => {
create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| { create_visitor!(trie, self.path, visit_mut_expr, |expr: &mut Expr| {
*expr = quote!( *expr = quote!(
"(() => { const e = new Error(\"Cannot find module as expression is too \ "(() => { const e = new Error(\"Cannot find module as expression is too \
dynamic\"); e.code = 'MODULE_NOT_FOUND'; throw e; })()" dynamic\"); e.code = 'MODULE_NOT_FOUND'; throw e; })()"
...@@ -56,7 +57,7 @@ impl DynamicExpression { ...@@ -56,7 +57,7 @@ impl DynamicExpression {
}) })
} }
DynamicExpressionType::Promise => { DynamicExpressionType::Promise => {
create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| { create_visitor!(trie, self.path, visit_mut_expr, |expr: &mut Expr| {
*expr = quote!( *expr = quote!(
"Promise.resolve().then(() => { const e = new Error(\"Cannot find module \ "Promise.resolve().then(() => { const e = new Error(\"Cannot find module \
as expression is too dynamic\"); e.code = 'MODULE_NOT_FOUND'; throw e; })" as expression is too dynamic\"); e.code = 'MODULE_NOT_FOUND'; throw e; })"
......
...@@ -27,11 +27,11 @@ use turbopack_resolve::ecmascript::esm_resolve; ...@@ -27,11 +27,11 @@ use turbopack_resolve::ecmascript::esm_resolve;
use crate::{ use crate::{
analyzer::imports::ImportAnnotations, analyzer::imports::ImportAnnotations,
ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder},
code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference}, code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference},
collect_module::{COLLECT_LIST_EXPORT, EcmascriptCollectModule}, collect_module::{COLLECT_LIST_EXPORT, EcmascriptCollectModule},
create_visitor, create_visitor,
references::{ references::{
AstPath,
esm::{base::ReferencedAsset, mangle::generated_export_key}, esm::{base::ReferencedAsset, mangle::generated_export_key},
pattern_mapping::{PatternMapping, ResolveType}, pattern_mapping::{PatternMapping, ResolveType},
removal::RemovalCodeGen, removal::RemovalCodeGen,
...@@ -148,15 +148,17 @@ impl IntoCodeGenReference for EmitReference { ...@@ -148,15 +148,17 @@ impl IntoCodeGenReference for EmitReference {
fn into_code_gen_reference( fn into_code_gen_reference(
self, self,
mut path: AstPath, trie: &AstPathTrieBuilder,
path: AstPathId,
) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) { ) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) {
let reference = self.resolved_cell(); let reference = self.resolved_cell();
path.0.pop(); // The reference is on the import specifier; the statement to remove is its parent.
let path = trie.parent_or_root(path);
( (
ResolvedVc::upcast(reference), ResolvedVc::upcast(reference),
CodeGen::RemovalCodeGen(RemovalCodeGen::new( CodeGen::RemovalCodeGen(RemovalCodeGen::new(
rcstr!("TURBOPACK collect"), rcstr!("TURBOPACK collect"),
AstPathRange::Exact(path.0), AstPathRange::Exact(path),
)), )),
) )
} }
...@@ -225,10 +227,11 @@ impl IntoCodeGenReference for CollectReference { ...@@ -225,10 +227,11 @@ impl IntoCodeGenReference for CollectReference {
fn into_code_gen_reference( fn into_code_gen_reference(
self, self,
mut path: AstPath, trie: &AstPathTrieBuilder,
path: AstPathId,
) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) { ) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) {
let reference = self.resolved_cell(); let reference = self.resolved_cell();
path.0.pop(); let path = trie.parent_or_root(path);
( (
ResolvedVc::upcast(reference), ResolvedVc::upcast(reference),
CodeGen::CollectReferenceCodeGen(CollectReferenceCodeGen { reference, path }), CodeGen::CollectReferenceCodeGen(CollectReferenceCodeGen { reference, path }),
...@@ -241,12 +244,13 @@ impl IntoCodeGenReference for CollectReference { ...@@ -241,12 +244,13 @@ impl IntoCodeGenReference for CollectReference {
)] )]
pub struct CollectReferenceCodeGen { pub struct CollectReferenceCodeGen {
reference: ResolvedVc<CollectReference>, reference: ResolvedVc<CollectReference>,
path: AstPath, path: AstPathId,
} }
impl CollectReferenceCodeGen { impl CollectReferenceCodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let reference = self.reference.await?; let reference = self.reference.await?;
...@@ -275,6 +279,7 @@ impl CollectReferenceCodeGen { ...@@ -275,6 +279,7 @@ impl CollectReferenceCodeGen {
}; };
visitors.push(create_visitor!( visitors.push(create_visitor!(
trie,
self.path, self.path,
visit_mut_expr, visit_mut_expr,
|expr: &mut Expr| { |expr: &mut Expr| {
......
...@@ -10,14 +10,12 @@ use turbopack_core::chunk::ChunkingContext; ...@@ -10,14 +10,12 @@ use turbopack_core::chunk::ChunkingContext;
use crate::{ use crate::{
ScopeHoistingContext, ScopeHoistingContext,
ast_path_trie::{AstPathId, AstPathTrie},
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
references::{ references::esm::{
AstPath, EsmAssetReference,
esm::{ base::{ReferencedAsset, ReferencedAssetIdent},
EsmAssetReference,
base::{ReferencedAsset, ReferencedAssetIdent},
},
}, },
}; };
...@@ -25,7 +23,7 @@ use crate::{ ...@@ -25,7 +23,7 @@ use crate::{
pub struct EsmBinding { pub struct EsmBinding {
reference: ResolvedVc<EsmAssetReference>, reference: ResolvedVc<EsmAssetReference>,
export: Option<RcStr>, export: Option<RcStr>,
ast_path: AstPath, ast_path: AstPathId,
keep_this: bool, keep_this: bool,
} }
...@@ -33,7 +31,7 @@ impl EsmBinding { ...@@ -33,7 +31,7 @@ impl EsmBinding {
pub fn new( pub fn new(
reference: ResolvedVc<EsmAssetReference>, reference: ResolvedVc<EsmAssetReference>,
export: Option<RcStr>, export: Option<RcStr>,
ast_path: AstPath, ast_path: AstPathId,
) -> Self { ) -> Self {
EsmBinding { EsmBinding {
reference, reference,
...@@ -47,7 +45,7 @@ impl EsmBinding { ...@@ -47,7 +45,7 @@ impl EsmBinding {
pub fn new_keep_this( pub fn new_keep_this(
reference: ResolvedVc<EsmAssetReference>, reference: ResolvedVc<EsmAssetReference>,
export: Option<RcStr>, export: Option<RcStr>,
ast_path: AstPath, ast_path: AstPathId,
) -> Self { ) -> Self {
EsmBinding { EsmBinding {
reference, reference,
...@@ -59,6 +57,7 @@ impl EsmBinding { ...@@ -59,6 +57,7 @@ impl EsmBinding {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
...@@ -89,15 +88,18 @@ impl EsmBinding { ...@@ -89,15 +88,18 @@ impl EsmBinding {
.map_or(ImportedIdent::Unresolvable, ImportedIdent::Module), .map_or(ImportedIdent::Unresolvable, ImportedIdent::Module),
}; };
let mut ast_path = self.ast_path.0.clone(); // Walk up from the binding towards the root, stopping at the innermost node kind we
// know how to rewrite.
let mut ast_path = self.ast_path;
loop { loop {
match ast_path.last() { match trie.get(ast_path) {
// Shorthand properties get special treatment because we need to rewrite them to // Shorthand properties get special treatment because we need to rewrite them to
// normal key-value pairs. // normal key-value pairs.
Some(swc_core::ecma::visit::AstParentKind::Prop(PropField::Shorthand)) => { Some(swc_core::ecma::visit::AstParentKind::Prop(PropField::Shorthand)) => {
ast_path.pop(); ast_path = trie.parent_or_root(ast_path);
visitors.push(create_visitor!( visitors.push(create_visitor!(
exact, exact,
trie,
ast_path, ast_path,
visit_mut_prop, visit_mut_prop,
|prop: &mut Prop| { |prop: &mut Prop| {
...@@ -128,10 +130,10 @@ impl EsmBinding { ...@@ -128,10 +130,10 @@ impl EsmBinding {
} }
// Any other expression can be replaced with the import accessor. // Any other expression can be replaced with the import accessor.
Some(swc_core::ecma::visit::AstParentKind::Expr(_)) => { Some(swc_core::ecma::visit::AstParentKind::Expr(_)) => {
ast_path.pop(); ast_path = trie.parent_or_root(ast_path);
let in_call = !self.keep_this let in_call = !self.keep_this
&& matches!( && matches!(
ast_path.last(), trie.get(ast_path),
Some(swc_core::ecma::visit::AstParentKind::Callee( Some(swc_core::ecma::visit::AstParentKind::Callee(
CalleeField::Expr CalleeField::Expr
)) ))
...@@ -139,6 +141,7 @@ impl EsmBinding { ...@@ -139,6 +141,7 @@ impl EsmBinding {
visitors.push(create_visitor!( visitors.push(create_visitor!(
exact, exact,
trie,
ast_path, ast_path,
visit_mut_expr, visit_mut_expr,
|expr: &mut Expr| { |expr: &mut Expr| {
...@@ -161,10 +164,11 @@ impl EsmBinding { ...@@ -161,10 +164,11 @@ impl EsmBinding {
// We need to handle LHS because of code like // We need to handle LHS because of code like
// (function (RouteKind1){})(RouteKind || RouteKind = {}) // (function (RouteKind1){})(RouteKind || RouteKind = {})
Some(swc_core::ecma::visit::AstParentKind::SimpleAssignTarget(_)) => { Some(swc_core::ecma::visit::AstParentKind::SimpleAssignTarget(_)) => {
ast_path.pop(); ast_path = trie.parent_or_root(ast_path);
visitors.push(create_visitor!( visitors.push(create_visitor!(
exact, exact,
trie,
ast_path, ast_path,
visit_mut_simple_assign_target, visit_mut_simple_assign_target,
|l: &mut SimpleAssignTarget| { |l: &mut SimpleAssignTarget| {
...@@ -191,7 +195,7 @@ impl EsmBinding { ...@@ -191,7 +195,7 @@ impl EsmBinding {
break; break;
} }
Some(_) => { Some(_) => {
ast_path.pop(); ast_path = trie.parent_or_root(ast_path);
} }
None => break, None => break,
} }
......
...@@ -24,14 +24,12 @@ use turbopack_resolve::ecmascript::esm_resolve; ...@@ -24,14 +24,12 @@ use turbopack_resolve::ecmascript::esm_resolve;
use crate::{ use crate::{
analyzer::imports::ImportAnnotations, analyzer::imports::ImportAnnotations,
ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder},
async_chunk::proxy::LazyCompilationProxyModule, async_chunk::proxy::LazyCompilationProxyModule,
chunk::EcmascriptChunkPlaceable, chunk::EcmascriptChunkPlaceable,
code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference}, code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference},
create_visitor, create_visitor,
references::{ references::pattern_mapping::{PatternMapping, ResolveType},
AstPath,
pattern_mapping::{PatternMapping, ResolveType},
},
}; };
#[turbo_tasks::value] #[turbo_tasks::value]
...@@ -143,7 +141,8 @@ impl IntoCodeGenReference for EsmAsyncAssetReference { ...@@ -143,7 +141,8 @@ impl IntoCodeGenReference for EsmAsyncAssetReference {
fn into_code_gen_reference( fn into_code_gen_reference(
self, self,
path: AstPath, _trie: &AstPathTrieBuilder,
path: AstPathId,
) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) { ) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) {
let reference = self.resolved_cell(); let reference = self.resolved_cell();
( (
...@@ -160,13 +159,14 @@ impl IntoCodeGenReference for EsmAsyncAssetReference { ...@@ -160,13 +159,14 @@ impl IntoCodeGenReference for EsmAsyncAssetReference {
PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode, PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode,
)] )]
pub struct EsmAsyncAssetReferenceCodeGen { pub struct EsmAsyncAssetReferenceCodeGen {
path: AstPath, path: AstPathId,
reference: ResolvedVc<EsmAsyncAssetReference>, reference: ResolvedVc<EsmAsyncAssetReference>,
} }
impl EsmAsyncAssetReferenceCodeGen { impl EsmAsyncAssetReferenceCodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let reference = self.reference.await?; let reference = self.reference.await?;
...@@ -187,7 +187,7 @@ impl EsmAsyncAssetReferenceCodeGen { ...@@ -187,7 +187,7 @@ impl EsmAsyncAssetReferenceCodeGen {
let import_externals = reference.import_externals; let import_externals = reference.import_externals;
let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| { let visitor = create_visitor!(trie, self.path, visit_mut_expr, |expr: &mut Expr| {
let old_expr = expr.take(); let old_expr = expr.take();
let message = if let Expr::Call(CallExpr { args, .. }) = old_expr { let message = if let Expr::Call(CallExpr { args, .. }) = old_expr {
match args.into_iter().next() { match args.into_iter().next() {
......
...@@ -13,9 +13,9 @@ use turbo_tasks_fs::FileSystemPath; ...@@ -13,9 +13,9 @@ use turbo_tasks_fs::FileSystemPath;
use turbopack_core::chunk::ChunkingContext; use turbopack_core::chunk::ChunkingContext;
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie},
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, magic_identifier, create_visitor, magic_identifier,
references::AstPath,
runtime_functions::{TURBOPACK_MODULE, TURBOPACK_RESOLVE_FILE_URL}, runtime_functions::{TURBOPACK_MODULE, TURBOPACK_RESOLVE_FILE_URL},
}; };
...@@ -56,6 +56,7 @@ impl ImportMetaBinding { ...@@ -56,6 +56,7 @@ impl ImportMetaBinding {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
_trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let rel_path = chunking_context let rel_path = chunking_context
...@@ -140,19 +141,20 @@ impl From<ImportMetaBinding> for CodeGen { ...@@ -140,19 +141,20 @@ impl From<ImportMetaBinding> for CodeGen {
PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode, PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode,
)] )]
pub struct ImportMetaRef { pub struct ImportMetaRef {
ast_path: AstPath, ast_path: AstPathId,
} }
impl ImportMetaRef { impl ImportMetaRef {
pub fn new(ast_path: AstPath) -> Self { pub fn new(ast_path: AstPathId) -> Self {
ImportMetaRef { ast_path } ImportMetaRef { ast_path }
} }
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let visitor = create_visitor!(self.ast_path, visit_mut_expr, |expr: &mut Expr| { let visitor = create_visitor!(trie, self.ast_path, visit_mut_expr, |expr: &mut Expr| {
*expr = Expr::Ident(meta_ident()); *expr = Expr::Ident(meta_ident());
}); });
......
...@@ -11,12 +11,10 @@ use turbopack_core::{ ...@@ -11,12 +11,10 @@ use turbopack_core::{
}; };
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder},
code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference}, code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference},
create_visitor, create_visitor,
references::{ references::esm::{EsmAssetReference, base::ReferencedAsset},
AstPath,
esm::{EsmAssetReference, base::ReferencedAsset},
},
utils::module_id_to_lit, utils::module_id_to_lit,
}; };
...@@ -56,7 +54,8 @@ impl IntoCodeGenReference for EsmModuleIdAssetReference { ...@@ -56,7 +54,8 @@ impl IntoCodeGenReference for EsmModuleIdAssetReference {
fn into_code_gen_reference( fn into_code_gen_reference(
self, self,
path: AstPath, _trie: &AstPathTrieBuilder,
path: AstPathId,
) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) { ) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) {
let reference = self.resolved_cell(); let reference = self.resolved_cell();
( (
...@@ -73,13 +72,14 @@ impl IntoCodeGenReference for EsmModuleIdAssetReference { ...@@ -73,13 +72,14 @@ impl IntoCodeGenReference for EsmModuleIdAssetReference {
PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode, PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode,
)] )]
pub struct EsmModuleIdAssetReferenceCodeGen { pub struct EsmModuleIdAssetReferenceCodeGen {
path: AstPath, path: AstPathId,
reference: ResolvedVc<EsmModuleIdAssetReference>, reference: ResolvedVc<EsmModuleIdAssetReference>,
} }
impl EsmModuleIdAssetReferenceCodeGen { impl EsmModuleIdAssetReferenceCodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let mut visitors = Vec::new(); let mut visitors = Vec::new();
...@@ -90,6 +90,7 @@ impl EsmModuleIdAssetReferenceCodeGen { ...@@ -90,6 +90,7 @@ impl EsmModuleIdAssetReferenceCodeGen {
let id = asset.chunk_item_id(chunking_context).await?; let id = asset.chunk_item_id(chunking_context).await?;
let id = module_id_to_lit(&id); let id = module_id_to_lit(&id);
visitors.push(create_visitor!( visitors.push(create_visitor!(
trie,
self.path, self.path,
visit_mut_expr, visit_mut_expr,
|expr: &mut Expr| { |expr: &mut Expr| {
...@@ -101,6 +102,7 @@ impl EsmModuleIdAssetReferenceCodeGen { ...@@ -101,6 +102,7 @@ impl EsmModuleIdAssetReferenceCodeGen {
// This can happen if the referenced asset is an external, or doesn't resolve // This can happen if the referenced asset is an external, or doesn't resolve
// to anything. // to anything.
visitors.push(create_visitor!( visitors.push(create_visitor!(
trie,
self.path, self.path,
visit_mut_expr, visit_mut_expr,
|expr: &mut Expr| { |expr: &mut Expr| {
......
...@@ -14,10 +14,10 @@ use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs ...@@ -14,10 +14,10 @@ use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs
use turbopack_core::chunk::ChunkingContext; use turbopack_core::chunk::ChunkingContext;
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie},
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
magic_identifier::MAGIC_IDENTIFIER_DEFAULT_EXPORT_ATOM, magic_identifier::MAGIC_IDENTIFIER_DEFAULT_EXPORT_ATOM,
references::AstPath,
}; };
/// Makes code changes to remove export/import declarations and places the /// Makes code changes to remove export/import declarations and places the
...@@ -27,12 +27,12 @@ use crate::{ ...@@ -27,12 +27,12 @@ use crate::{
PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Debug, Hash, Encode, Decode, PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Debug, Hash, Encode, Decode,
)] )]
pub struct EsmModuleItem { pub struct EsmModuleItem {
pub path: AstPath, pub path: AstPathId,
pub supports_block_scoping: bool, pub supports_block_scoping: bool,
} }
impl EsmModuleItem { impl EsmModuleItem {
pub fn new(path: AstPath, supports_block_scoping: bool) -> Self { pub fn new(path: AstPathId, supports_block_scoping: bool) -> Self {
EsmModuleItem { EsmModuleItem {
path, path,
supports_block_scoping, supports_block_scoping,
...@@ -41,12 +41,14 @@ impl EsmModuleItem { ...@@ -41,12 +41,14 @@ impl EsmModuleItem {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let mut visitors = Vec::new(); let mut visitors = Vec::new();
let supports_block_scoping = self.supports_block_scoping; let supports_block_scoping = self.supports_block_scoping;
visitors.push(create_visitor!( visitors.push(create_visitor!(
trie,
self.path, self.path,
visit_mut_module_item, visit_mut_module_item,
|module_item: &mut ModuleItem| { |module_item: &mut ModuleItem| {
......
...@@ -20,9 +20,10 @@ use turbopack_core::{ ...@@ -20,9 +20,10 @@ use turbopack_core::{
}; };
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder},
code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference}, code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference},
create_visitor, create_visitor,
references::{AstPath, esm::base::ReferencedAsset}, references::esm::base::ReferencedAsset,
runtime_functions::{ runtime_functions::{
TURBOPACK_RELATIVE_URL, TURBOPACK_REQUIRE, TURBOPACK_RESOLVE_MODULE_ID_PATH, TURBOPACK_RELATIVE_URL, TURBOPACK_REQUIRE, TURBOPACK_RESOLVE_MODULE_ID_PATH,
}, },
...@@ -118,7 +119,8 @@ impl IntoCodeGenReference for UrlAssetReference { ...@@ -118,7 +119,8 @@ impl IntoCodeGenReference for UrlAssetReference {
fn into_code_gen_reference( fn into_code_gen_reference(
self, self,
path: AstPath, _trie: &AstPathTrieBuilder,
path: AstPathId,
) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) { ) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) {
let reference = self.resolved_cell(); let reference = self.resolved_cell();
( (
...@@ -133,7 +135,7 @@ impl IntoCodeGenReference for UrlAssetReference { ...@@ -133,7 +135,7 @@ impl IntoCodeGenReference for UrlAssetReference {
)] )]
pub struct UrlAssetReferenceCodeGen { pub struct UrlAssetReferenceCodeGen {
reference: ResolvedVc<UrlAssetReference>, reference: ResolvedVc<UrlAssetReference>,
path: AstPath, path: AstPathId,
} }
impl UrlAssetReferenceCodeGen { impl UrlAssetReferenceCodeGen {
...@@ -156,6 +158,7 @@ impl UrlAssetReferenceCodeGen { ...@@ -156,6 +158,7 @@ impl UrlAssetReferenceCodeGen {
*/ */
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let mut visitors = vec![]; let mut visitors = vec![];
...@@ -178,7 +181,7 @@ impl UrlAssetReferenceCodeGen { ...@@ -178,7 +181,7 @@ impl UrlAssetReferenceCodeGen {
// item, which exports the static asset path to the linked file. // item, which exports the static asset path to the linked file.
let id = asset.chunk_item_id(chunking_context).await?; let id = asset.chunk_item_id(chunking_context).await?;
visitors.push(create_visitor!(self.path, visit_mut_expr, |new_expr: &mut Expr| { visitors.push(create_visitor!(trie, self.path, visit_mut_expr, |new_expr: &mut Expr| {
let should_rewrite_to_relative = if let Expr::New(NewExpr { args: Some(args), .. }) = new_expr { let should_rewrite_to_relative = if let Expr::New(NewExpr { args: Some(args), .. }) = new_expr {
matches!(args.first(), Some(ExprOrSpread { .. })) matches!(args.first(), Some(ExprOrSpread { .. }))
} else { } else {
...@@ -197,7 +200,7 @@ impl UrlAssetReferenceCodeGen { ...@@ -197,7 +200,7 @@ impl UrlAssetReferenceCodeGen {
} }
ReferencedAsset::External(request, ExternalType::Url) => { ReferencedAsset::External(request, ExternalType::Url) => {
let request = request.to_string(); let request = request.to_string();
visitors.push(create_visitor!(self.path, visit_mut_expr, |new_expr: &mut Expr| { visitors.push(create_visitor!(trie, self.path, visit_mut_expr, |new_expr: &mut Expr| {
let should_rewrite_to_relative = if let Expr::New(NewExpr { args: Some(args), .. }) = new_expr { let should_rewrite_to_relative = if let Expr::New(NewExpr { args: Some(args), .. }) = new_expr {
matches!(args.first(), Some(ExprOrSpread { .. })) matches!(args.first(), Some(ExprOrSpread { .. }))
} else { } else {
...@@ -268,6 +271,7 @@ impl UrlAssetReferenceCodeGen { ...@@ -268,6 +271,7 @@ impl UrlAssetReferenceCodeGen {
}; };
visitors.push(create_visitor!( visitors.push(create_visitor!(
trie,
self.path, self.path,
visit_mut_expr, visit_mut_expr,
|new_expr: &mut Expr| { |new_expr: &mut Expr| {
...@@ -301,6 +305,7 @@ impl UrlAssetReferenceCodeGen { ...@@ -301,6 +305,7 @@ impl UrlAssetReferenceCodeGen {
ReferencedAsset::External(request, ExternalType::Url) => { ReferencedAsset::External(request, ExternalType::Url) => {
let request = request.to_string(); let request = request.to_string();
visitors.push(create_visitor!( visitors.push(create_visitor!(
trie,
self.path, self.path,
visit_mut_expr, visit_mut_expr,
|new_expr: &mut Expr| { |new_expr: &mut Expr| {
......
...@@ -10,10 +10,11 @@ use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, debug::ValueDebugFormat, trace: ...@@ -10,10 +10,11 @@ use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, debug::ValueDebugFormat, trace:
use turbopack_core::chunk::ChunkingContext; use turbopack_core::chunk::ChunkingContext;
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie},
chunk::{EcmascriptChunkPlaceable, EcmascriptExports}, chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, magic_identifier, create_visitor, magic_identifier,
references::{AstPath, esm::mangle::mangled_export_names}, references::esm::mangle::mangled_export_names,
}; };
/// Responsible for initializing the `ExportsInfoBinding` object binding, so that it may be /// Responsible for initializing the `ExportsInfoBinding` object binding, so that it may be
...@@ -36,6 +37,7 @@ impl ExportsInfoBinding { ...@@ -36,6 +37,7 @@ impl ExportsInfoBinding {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
_trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
exports: ResolvedVc<EcmascriptExports>, exports: ResolvedVc<EcmascriptExports>,
...@@ -125,19 +127,20 @@ impl From<ExportsInfoBinding> for CodeGen { ...@@ -125,19 +127,20 @@ impl From<ExportsInfoBinding> for CodeGen {
PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode, PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode,
)] )]
pub struct ExportsInfoRef { pub struct ExportsInfoRef {
ast_path: AstPath, ast_path: AstPathId,
} }
impl ExportsInfoRef { impl ExportsInfoRef {
pub fn new(ast_path: AstPath) -> Self { pub fn new(ast_path: AstPathId) -> Self {
ExportsInfoRef { ast_path } ExportsInfoRef { ast_path }
} }
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let visitor = create_visitor!(self.ast_path, visit_mut_expr, |expr: &mut Expr| { let visitor = create_visitor!(trie, self.ast_path, visit_mut_expr, |expr: &mut Expr| {
*expr = Expr::Ident(exports_ident()); *expr = Expr::Ident(exports_ident());
}); });
......
...@@ -25,10 +25,10 @@ use turbopack_resolve::ecmascript::{cjs_resolve, esm_resolve}; ...@@ -25,10 +25,10 @@ use turbopack_resolve::ecmascript::{cjs_resolve, esm_resolve};
use crate::{ use crate::{
ScopeHoistingContext, ScopeHoistingContext,
ast_path_trie::{AstPathId, AstPathTrie},
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
references::{ references::{
AstPath,
esm::{EsmAssetReference, base::ReferencedAsset}, esm::{EsmAssetReference, base::ReferencedAsset},
pattern_mapping::{PatternMapping, ResolveType}, pattern_mapping::{PatternMapping, ResolveType},
}, },
...@@ -111,14 +111,14 @@ pub struct ModuleHotReferenceCodeGen { ...@@ -111,14 +111,14 @@ pub struct ModuleHotReferenceCodeGen {
/// This is used to generate code that re-assigns the ESM namespace variable /// This is used to generate code that re-assigns the ESM namespace variable
/// after an HMR update so that imported bindings reflect the updated module. /// after an HMR update so that imported bindings reflect the updated module.
esm_references: Vec<Option<ResolvedVc<EsmAssetReference>>>, esm_references: Vec<Option<ResolvedVc<EsmAssetReference>>>,
path: AstPath, path: AstPathId,
} }
impl ModuleHotReferenceCodeGen { impl ModuleHotReferenceCodeGen {
pub fn new( pub fn new(
references: Vec<ResolvedVc<ModuleHotReferenceAssetReference>>, references: Vec<ResolvedVc<ModuleHotReferenceAssetReference>>,
esm_references: Vec<Option<ResolvedVc<EsmAssetReference>>>, esm_references: Vec<Option<ResolvedVc<EsmAssetReference>>>,
path: AstPath, path: AstPathId,
) -> Self { ) -> Self {
ModuleHotReferenceCodeGen { ModuleHotReferenceCodeGen {
references, references,
...@@ -129,6 +129,7 @@ impl ModuleHotReferenceCodeGen { ...@@ -129,6 +129,7 @@ impl ModuleHotReferenceCodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
...@@ -203,6 +204,7 @@ impl ModuleHotReferenceCodeGen { ...@@ -203,6 +204,7 @@ impl ModuleHotReferenceCodeGen {
let mut visitors = Vec::new(); let mut visitors = Vec::new();
visitors.push(create_visitor!( visitors.push(create_visitor!(
trie,
self.path, self.path,
visit_mut_expr, visit_mut_expr,
|expr: &mut Expr| { |expr: &mut Expr| {
......
...@@ -6,9 +6,9 @@ use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs ...@@ -6,9 +6,9 @@ use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs
use turbopack_core::chunk::ChunkingContext; use turbopack_core::chunk::ChunkingContext;
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie},
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
references::AstPath,
}; };
#[derive( #[derive(
...@@ -16,21 +16,22 @@ use crate::{ ...@@ -16,21 +16,22 @@ use crate::{
)] )]
pub struct IdentReplacement { pub struct IdentReplacement {
value: RcStr, value: RcStr,
path: AstPath, path: AstPathId,
} }
impl IdentReplacement { impl IdentReplacement {
pub fn new(value: RcStr, path: AstPath) -> Self { pub fn new(value: RcStr, path: AstPathId) -> Self {
IdentReplacement { value, path } IdentReplacement { value, path }
} }
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let value = self.value.clone(); let value = self.value.clone();
let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| { let visitor = create_visitor!(trie, 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,13 +46,11 @@ use turbopack_resolve::ecmascript::esm_resolve; ...@@ -46,13 +46,11 @@ use turbopack_resolve::ecmascript::esm_resolve;
use crate::{ use crate::{
EcmascriptChunkPlaceable, EcmascriptChunkPlaceable,
analyzer::JsValue, analyzer::JsValue,
ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder},
chunk::{EcmascriptChunkItemContent, EcmascriptExports, ecmascript_chunk_item}, chunk::{EcmascriptChunkItemContent, EcmascriptExports, ecmascript_chunk_item},
code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference}, code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference},
create_visitor, create_visitor,
references::{ references::pattern_mapping::{PatternMapping, ResolveType},
AstPath,
pattern_mapping::{PatternMapping, ResolveType},
},
runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_REQUIRE}, runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_REQUIRE},
utils::module_id_to_lit, utils::module_id_to_lit,
}; };
...@@ -1269,7 +1267,8 @@ impl IntoCodeGenReference for ImportMetaGlobAssetReference { ...@@ -1269,7 +1267,8 @@ impl IntoCodeGenReference for ImportMetaGlobAssetReference {
fn into_code_gen_reference( fn into_code_gen_reference(
self, self,
path: AstPath, _trie: &AstPathTrieBuilder,
path: AstPathId,
) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) { ) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) {
let reference = self.resolved_cell(); let reference = self.resolved_cell();
( (
...@@ -1290,13 +1289,14 @@ impl IntoCodeGenReference for ImportMetaGlobAssetReference { ...@@ -1290,13 +1289,14 @@ impl IntoCodeGenReference for ImportMetaGlobAssetReference {
PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode, PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode,
)] )]
pub struct ImportMetaGlobAssetReferenceCodeGen { pub struct ImportMetaGlobAssetReferenceCodeGen {
path: AstPath, path: AstPathId,
reference: ResolvedVc<ImportMetaGlobAssetReference>, reference: ResolvedVc<ImportMetaGlobAssetReference>,
} }
impl ImportMetaGlobAssetReferenceCodeGen { impl ImportMetaGlobAssetReferenceCodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let module_id = self let module_id = self
...@@ -1308,6 +1308,7 @@ impl ImportMetaGlobAssetReferenceCodeGen { ...@@ -1308,6 +1308,7 @@ impl ImportMetaGlobAssetReferenceCodeGen {
let mut visitors = Vec::new(); let mut visitors = Vec::new();
visitors.push(create_visitor!( visitors.push(create_visitor!(
trie,
self.path, self.path,
visit_mut_expr, visit_mut_expr,
|expr: &mut Expr| { |expr: &mut Expr| {
......
...@@ -15,9 +15,9 @@ use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs ...@@ -15,9 +15,9 @@ use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs
use turbopack_core::chunk::ChunkingContext; use turbopack_core::chunk::ChunkingContext;
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie},
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
references::AstPath,
}; };
#[derive( #[derive(
...@@ -26,16 +26,17 @@ use crate::{ ...@@ -26,16 +26,17 @@ use crate::{
pub struct MemberReplacement { pub struct MemberReplacement {
key: RcStr, key: RcStr,
value: RcStr, value: RcStr,
path: AstPath, path: AstPathId,
} }
impl MemberReplacement { impl MemberReplacement {
pub fn new(key: RcStr, value: RcStr, path: AstPath) -> Self { pub fn new(key: RcStr, value: RcStr, path: AstPathId) -> Self {
MemberReplacement { key, value, path } MemberReplacement { key, value, path }
} }
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let comments = SwcComments::default(); let comments = SwcComments::default();
...@@ -44,7 +45,7 @@ impl MemberReplacement { ...@@ -44,7 +45,7 @@ impl MemberReplacement {
let value = self.value.clone(); let value = self.value.clone();
let comments_clone = comments.clone(); let comments_clone = comments.clone();
let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| { let visitor = create_visitor!(trie, self.path, visit_mut_expr, |expr: &mut Expr| {
let span = Span::dummy_with_cmt(); let span = Span::dummy_with_cmt();
comments_clone.add_leading( comments_clone.add_leading(
......
...@@ -29,6 +29,7 @@ use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs ...@@ -29,6 +29,7 @@ use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs
use turbopack_core::chunk::ChunkingContext; use turbopack_core::chunk::ChunkingContext;
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie},
code_gen::{AstModifier, CodeGen, CodeGeneration}, code_gen::{AstModifier, CodeGen, CodeGeneration},
utils::AstPathRange, utils::AstPathRange,
}; };
...@@ -151,6 +152,7 @@ impl RemovalCodeGen { ...@@ -151,6 +152,7 @@ impl RemovalCodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let comments = SwcComments::default(); let comments = SwcComments::default();
...@@ -159,63 +161,43 @@ impl RemovalCodeGen { ...@@ -159,63 +161,43 @@ impl RemovalCodeGen {
let visitors = match &self.range { let visitors = match &self.range {
AstPathRange::Exact(path) => vec![( AstPathRange::Exact(path) => vec![(
path.clone(), *path,
Box::new(UnreachableModifier { Box::new(UnreachableModifier {
comment_replacement: comment_replacement.clone(), comment_replacement: comment_replacement.clone(),
comments: comments.clone(), comments: comments.clone(),
}) as Box<dyn AstModifier>, }) as Box<dyn AstModifier>,
)], )],
AstPathRange::StartAfter(path) => { AstPathRange::StartAfter(path) => {
let mut parent = &path[..]; // Walk up to the enclosing statement, then past the element naming the slot
while !parent.is_empty() // it occupies, leaving the node that owns the statement list plus the index
&& !matches!(parent.last().unwrap(), AstParentKind::Stmt(_)) // to start removing from. Every ancestor of an interned path is itself a
{ // node, so this only walks the trie.
parent = &parent[0..parent.len() - 1]; let Some(stmt) = trie.find_last(*path, |k| matches!(k, AstParentKind::Stmt(_)))
} else {
if !parent.is_empty() { return Ok(CodeGeneration::visitors_with_comments(vec![], comments));
parent = &parent[0..parent.len() - 1]; };
// `slot` names which statement of its parent this is, e.g. `Stmts(3)`.
let (parent, [last]) = parent.split_at(parent.len() - 1) else { let Some(slot) = trie.get_parent(stmt) else {
unreachable!(); return Ok(CodeGeneration::visitors_with_comments(vec![], comments));
}; };
if let &AstParentKind::BlockStmt(BlockStmtField::Stmts(start_index)) = last { let start_index = match trie.get(slot) {
vec![( Some(AstParentKind::BlockStmt(BlockStmtField::Stmts(i)))
parent.to_vec(), | Some(AstParentKind::FunctionBody(FunctionBodyField::Stmts(i)))
Box::new(UnreachableRangeModifier { | Some(AstParentKind::SwitchCase(SwitchCaseField::Cons(i))) => i,
comment_replacement: comment_replacement.clone(), // Not a statement list we know how to truncate.
comments: comments.clone(), _ => {
start_index, return Ok(CodeGeneration::visitors_with_comments(vec![], comments));
}) as Box<dyn AstModifier>,
)]
} else if let &AstParentKind::FunctionBody(FunctionBodyField::Stmts(
start_index,
)) = last
{
vec![(
parent.to_vec(),
Box::new(UnreachableRangeModifier {
comment_replacement: comment_replacement.clone(),
comments: comments.clone(),
start_index,
}) as Box<dyn AstModifier>,
)]
} else if let &AstParentKind::SwitchCase(SwitchCaseField::Cons(start_index)) =
last
{
vec![(
parent.to_vec(),
Box::new(UnreachableRangeModifier {
comment_replacement: comment_replacement.clone(),
comments: comments.clone(),
start_index,
}) as Box<dyn AstModifier>,
)]
} else {
Vec::new()
} }
} else { };
Vec::new() let owner = trie.get_parent(slot).unwrap_or(AstPathId::ROOT);
} vec![(
owner,
Box::new(UnreachableRangeModifier {
comment_replacement: comment_replacement.clone(),
comments: comments.clone(),
start_index,
}) as Box<dyn AstModifier>,
)]
} }
}; };
......
...@@ -38,13 +38,11 @@ use turbopack_resolve::ecmascript::cjs_resolve; ...@@ -38,13 +38,11 @@ use turbopack_resolve::ecmascript::cjs_resolve;
use crate::{ use crate::{
EcmascriptChunkPlaceable, EcmascriptChunkPlaceable,
ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder},
chunk::{EcmascriptChunkItemContent, EcmascriptExports, ecmascript_chunk_item}, chunk::{EcmascriptChunkItemContent, EcmascriptExports, ecmascript_chunk_item},
code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference}, code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference},
create_visitor, create_visitor,
references::{ references::pattern_mapping::{PatternMapping, ResolveType},
AstPath,
pattern_mapping::{PatternMapping, ResolveType},
},
runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_MODULE_CONTEXT, TURBOPACK_REQUIRE}, runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_MODULE_CONTEXT, TURBOPACK_REQUIRE},
utils::module_id_to_lit, utils::module_id_to_lit,
}; };
...@@ -320,7 +318,8 @@ impl IntoCodeGenReference for RequireContextAssetReference { ...@@ -320,7 +318,8 @@ impl IntoCodeGenReference for RequireContextAssetReference {
fn into_code_gen_reference( fn into_code_gen_reference(
self, self,
path: AstPath, _trie: &AstPathTrieBuilder,
path: AstPathId,
) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) { ) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) {
let reference = self.resolved_cell(); let reference = self.resolved_cell();
( (
...@@ -337,13 +336,14 @@ impl IntoCodeGenReference for RequireContextAssetReference { ...@@ -337,13 +336,14 @@ impl IntoCodeGenReference for RequireContextAssetReference {
PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode, PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode,
)] )]
pub struct RequireContextAssetReferenceCodeGen { pub struct RequireContextAssetReferenceCodeGen {
path: AstPath, path: AstPathId,
reference: ResolvedVc<RequireContextAssetReference>, reference: ResolvedVc<RequireContextAssetReference>,
} }
impl RequireContextAssetReferenceCodeGen { impl RequireContextAssetReferenceCodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let module_id = self let module_id = self
...@@ -356,6 +356,7 @@ impl RequireContextAssetReferenceCodeGen { ...@@ -356,6 +356,7 @@ impl RequireContextAssetReferenceCodeGen {
let mut visitors = Vec::new(); let mut visitors = Vec::new();
visitors.push(create_visitor!( visitors.push(create_visitor!(
trie,
self.path, self.path,
visit_mut_expr, visit_mut_expr,
|expr: &mut Expr| { |expr: &mut Expr| {
......
...@@ -26,13 +26,13 @@ use turbopack_core::{ ...@@ -26,13 +26,13 @@ use turbopack_core::{
}; };
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder},
chunk::{ chunk::{
EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports, EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports,
ecmascript_chunk_item, ecmascript_chunk_item,
}, },
code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference}, code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference},
create_visitor, create_visitor,
references::AstPath,
}; };
/// The root-served file name for a service worker registered at `scope`. One worker is supported /// The root-served file name for a service worker registered at `scope`. One worker is supported
...@@ -226,7 +226,8 @@ impl IntoCodeGenReference for ServiceWorkerAssetReference { ...@@ -226,7 +226,8 @@ impl IntoCodeGenReference for ServiceWorkerAssetReference {
fn into_code_gen_reference( fn into_code_gen_reference(
self, self,
path: AstPath, _trie: &AstPathTrieBuilder,
path: AstPathId,
) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) { ) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) {
let scope = self.scope.clone(); let scope = self.scope.clone();
let reference = self.resolved_cell(); let reference = self.resolved_cell();
...@@ -245,12 +246,13 @@ impl IntoCodeGenReference for ServiceWorkerAssetReference { ...@@ -245,12 +246,13 @@ impl IntoCodeGenReference for ServiceWorkerAssetReference {
)] )]
pub struct ServiceWorkerAssetReferenceCodeGen { pub struct ServiceWorkerAssetReferenceCodeGen {
scope: RcStr, scope: RcStr,
path: AstPath, path: AstPathId,
} }
impl ServiceWorkerAssetReferenceCodeGen { impl ServiceWorkerAssetReferenceCodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
// Rewrite `register(...)`'s script argument to the served URL and pin the `{ scope }` the // Rewrite `register(...)`'s script argument to the served URL and pin the `{ scope }` the
...@@ -274,7 +276,7 @@ impl ServiceWorkerAssetReferenceCodeGen { ...@@ -274,7 +276,7 @@ impl ServiceWorkerAssetReferenceCodeGen {
s => format!("{base_path}{s}"), s => format!("{base_path}{s}"),
}; };
let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| { let visitor = create_visitor!(trie, self.path, visit_mut_expr, |expr: &mut Expr| {
let message = if let Expr::Call(call_expr) = expr { let message = if let Expr::Call(call_expr) = expr {
match call_expr.args.first() { match call_expr.args.first() {
Some(ExprOrSpread { spread: None, .. }) => { Some(ExprOrSpread { spread: None, .. }) => {
......
...@@ -26,12 +26,10 @@ use turbopack_core::{ ...@@ -26,12 +26,10 @@ use turbopack_core::{
}; };
use crate::{ use crate::{
ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder},
code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference}, code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference},
create_visitor, create_visitor,
references::{ references::pattern_mapping::{PatternMapping, ResolveType},
AstPath,
pattern_mapping::{PatternMapping, ResolveType},
},
worker_chunk::{WorkerType, module::WorkerLoaderModule}, worker_chunk::{WorkerType, module::WorkerLoaderModule},
}; };
...@@ -314,7 +312,8 @@ impl IntoCodeGenReference for WorkerAssetReference { ...@@ -314,7 +312,8 @@ impl IntoCodeGenReference for WorkerAssetReference {
fn into_code_gen_reference( fn into_code_gen_reference(
self, self,
path: AstPath, _trie: &AstPathTrieBuilder,
path: AstPathId,
) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) { ) -> (ResolvedVc<Box<dyn ModuleReference>>, CodeGen) {
let reference = self.resolved_cell(); let reference = self.resolved_cell();
( (
...@@ -329,12 +328,13 @@ impl IntoCodeGenReference for WorkerAssetReference { ...@@ -329,12 +328,13 @@ impl IntoCodeGenReference for WorkerAssetReference {
)] )]
pub struct WorkerAssetReferenceCodeGen { pub struct WorkerAssetReferenceCodeGen {
reference: ResolvedVc<WorkerAssetReference>, reference: ResolvedVc<WorkerAssetReference>,
path: AstPath, path: AstPathId,
} }
impl WorkerAssetReferenceCodeGen { impl WorkerAssetReferenceCodeGen {
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let reference = self.reference.await?; let reference = self.reference.await?;
...@@ -359,7 +359,7 @@ impl WorkerAssetReferenceCodeGen { ...@@ -359,7 +359,7 @@ impl WorkerAssetReferenceCodeGen {
// Transform `new Worker(url, opts)` into `require(id)(Worker, opts)` // Transform `new Worker(url, opts)` into `require(id)(Worker, opts)`
// The loader module exports a function that creates the worker with all necessary // The loader module exports a function that creates the worker with all necessary
// configuration (entrypoint, chunks, forwarded globals, etc.) // configuration (entrypoint, chunks, forwarded globals, etc.)
let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| { let visitor = create_visitor!(trie, self.path, visit_mut_expr, |expr: &mut Expr| {
let message = if let Expr::New(new_expr) = expr { let message = if let Expr::New(new_expr) = expr {
if let Some(args) = &mut new_expr.args { if let Some(args) = &mut new_expr.args {
match args.first_mut() { match args.first_mut() {
...@@ -435,16 +435,17 @@ pub enum WorkerGlobalPlaceholder { ...@@ -435,16 +435,17 @@ pub enum WorkerGlobalPlaceholder {
pub struct WorkerGlobalsReplacementCodeGen { pub struct WorkerGlobalsReplacementCodeGen {
/// Which placeholder this codegen replaces (determines the injected value). /// Which placeholder this codegen replaces (determines the injected value).
placeholder: WorkerGlobalPlaceholder, placeholder: WorkerGlobalPlaceholder,
path: AstPath, path: AstPathId,
} }
impl WorkerGlobalsReplacementCodeGen { impl WorkerGlobalsReplacementCodeGen {
pub fn new(placeholder: WorkerGlobalPlaceholder, path: AstPath) -> Self { pub fn new(placeholder: WorkerGlobalPlaceholder, path: AstPathId) -> Self {
WorkerGlobalsReplacementCodeGen { placeholder, path } WorkerGlobalsReplacementCodeGen { placeholder, path }
} }
pub async fn code_generation( pub async fn code_generation(
&self, &self,
trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let options = chunking_context.worker_configuration_options().await?; let options = chunking_context.worker_configuration_options().await?;
...@@ -463,7 +464,7 @@ impl WorkerGlobalsReplacementCodeGen { ...@@ -463,7 +464,7 @@ impl WorkerGlobalsReplacementCodeGen {
}, },
}; };
let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| { let visitor = create_visitor!(trie, self.path, visit_mut_expr, |expr: &mut Expr| {
*expr = value.clone(); *expr = value.clone();
}); });
......
...@@ -5,18 +5,18 @@ use serde::Serialize; ...@@ -5,18 +5,18 @@ use serde::Serialize;
use smallvec::SmallVec; use smallvec::SmallVec;
use swc_core::{ use swc_core::{
common::{DUMMY_SP, SyntaxContext}, common::{DUMMY_SP, SyntaxContext},
ecma::{ ecma::ast::{ComputedPropName, Expr, Lit, MemberProp, ObjectPatProp, Pat, PropName, Str},
ast::{ComputedPropName, Expr, Lit, MemberProp, ObjectPatProp, Pat, PropName, Str},
visit::AstParentKind,
},
}; };
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, TaskInput, trace::TraceRawVcs}; use turbo_tasks::{NonLocalValue, TaskInput, trace::TraceRawVcs};
use turbopack_core::{chunk::ModuleId, resolve::pattern::Pattern}; use turbopack_core::{chunk::ModuleId, resolve::pattern::Pattern};
use crate::analyzer::{ use crate::{
ConstantNumber, ConstantValue, JsValue, JsValueUrlKind, ModuleValue, WellKnownFunctionKind, analyzer::{
WellKnownObjectKind, ConstantNumber, ConstantValue, JsValue, JsValueUrlKind, ModuleValue, WellKnownFunctionKind,
WellKnownObjectKind,
},
ast_path_trie::AstPathId,
}; };
pub fn unparen(expr: &Expr) -> &Expr { pub fn unparen(expr: &Expr) -> &Expr {
...@@ -216,21 +216,13 @@ format_iter!(std::fmt::Pointer); ...@@ -216,21 +216,13 @@ 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);
#[derive(Clone, PartialEq, Eq, TraceRawVcs, Debug, NonLocalValue, Hash, Encode, Decode)] #[derive(Clone, Copy, PartialEq, Eq, TraceRawVcs, Debug, NonLocalValue, Hash, Encode, Decode)]
pub enum AstPathRange { pub enum AstPathRange {
/// The ast path to the block or expression. /// The ast path to the block or expression.
Exact( Exact(AstPathId),
#[bincode(with_serde)]
#[turbo_tasks(trace_ignore)]
Vec<AstParentKind>,
),
/// The ast path to a expression just before the range in the parent of the /// The ast path to a expression just before the range in the parent of the
/// specific ast path. /// specific ast path.
StartAfter( StartAfter(AstPathId),
#[bincode(with_serde)]
#[turbo_tasks(trace_ignore)]
Vec<AstParentKind>,
),
} }
/// Converts a module value (ie an import) to a well known object, /// Converts a module value (ie an import) to a well known object,
......
...@@ -160,50 +160,9 @@ ...@@ -160,50 +160,9 @@
}, },
], ],
range: Exact( range: Exact(
[ AstPathId(
Program( 12,
Script, ),
),
Script(
Body(
1,
),
),
Stmt(
Decl,
),
Decl(
Var,
),
VarDecl(
Decls(
0,
),
),
VarDeclarator(
Init,
),
Expr(
Call,
),
CallExpr(
Args(
0,
),
),
ExprOrSpread(
Expr,
),
Expr(
Fn,
),
FnExpr(
Function,
),
Function(
Body,
),
],
), ),
}, },
), ),
...@@ -400,50 +359,9 @@ ...@@ -400,50 +359,9 @@
}, },
], ],
range: Exact( range: Exact(
[ AstPathId(
Program( 23,
Script, ),
),
Script(
Body(
2,
),
),
Stmt(
Decl,
),
Decl(
Var,
),
VarDecl(
Decls(
0,
),
),
VarDeclarator(
Init,
),
Expr(
Call,
),
CallExpr(
Args(
0,
),
),
ExprOrSpread(
Expr,
),
Expr(
Fn,
),
FnExpr(
Function,
),
Function(
Body,
),
],
), ),
}, },
), ),
...@@ -881,50 +799,9 @@ ...@@ -881,50 +799,9 @@
}, },
], ],
range: Exact( range: Exact(
[ AstPathId(
Program( 34,
Script, ),
),
Script(
Body(
3,
),
),
Stmt(
Decl,
),
Decl(
Var,
),
VarDecl(
Decls(
0,
),
),
VarDeclarator(
Init,
),
Expr(
Call,
),
CallExpr(
Args(
0,
),
),
ExprOrSpread(
Expr,
),
Expr(
Fn,
),
FnExpr(
Function,
),
Function(
Body,
),
],
), ),
}, },
), ),
......
...@@ -123,45 +123,9 @@ ...@@ -123,45 +123,9 @@
}, },
], ],
range: Exact( range: Exact(
[ AstPathId(
Program( 11,
Module, ),
),
Module(
Body(
2,
),
),
ModuleItem(
ModuleDecl,
),
ModuleDecl(
ExportDecl,
),
ExportDecl(
Decl,
),
Decl(
Fn,
),
FnDecl(
Function,
),
Function(
Body,
),
FunctionBody(
Stmts(
0,
),
),
Stmt(
If,
),
IfStmt(
Cons,
),
],
), ),
}, },
}, },
...@@ -518,45 +482,9 @@ ...@@ -518,45 +482,9 @@
}, },
], ],
range: Exact( range: Exact(
[ AstPathId(
Program( 21,
Module, ),
),
Module(
Body(
5,
),
),
ModuleItem(
ModuleDecl,
),
ModuleDecl(
ExportDecl,
),
ExportDecl(
Decl,
),
Decl(
Fn,
),
FnDecl(
Function,
),
Function(
Body,
),
FunctionBody(
Stmts(
0,
),
),
Stmt(
If,
),
IfStmt(
Cons,
),
],
), ),
}, },
}, },
......
...@@ -285,54 +285,9 @@ ...@@ -285,54 +285,9 @@
}, },
], ],
range: Exact( range: Exact(
[ AstPathId(
Program( 35,
Module, ),
),
Module(
Body(
7,
),
),
ModuleItem(
ModuleDecl,
),
ModuleDecl(
ExportDecl,
),
ExportDecl(
Decl,
),
Decl(
Var,
),
VarDecl(
Decls(
0,
),
),
VarDeclarator(
Init,
),
Expr(
Await,
),
AwaitExpr(
Arg,
),
Expr(
Paren,
),
ParenExpr(
Expr,
),
Expr(
Cond,
),
CondExpr(
Cons,
),
],
), ),
}, },
else: EffectsBlock { else: EffectsBlock {
...@@ -402,54 +357,9 @@ ...@@ -402,54 +357,9 @@
}, },
], ],
range: Exact( range: Exact(
[ AstPathId(
Program( 36,
Module, ),
),
Module(
Body(
7,
),
),
ModuleItem(
ModuleDecl,
),
ModuleDecl(
ExportDecl,
),
ExportDecl(
Decl,
),
Decl(
Var,
),
VarDecl(
Decls(
0,
),
),
VarDeclarator(
Init,
),
Expr(
Await,
),
AwaitExpr(
Arg,
),
Expr(
Paren,
),
ParenExpr(
Expr,
),
Expr(
Cond,
),
CondExpr(
Alt,
),
],
), ),
}, },
}, },
...@@ -606,42 +516,9 @@ ...@@ -606,42 +516,9 @@
}, },
], ],
range: Exact( range: Exact(
[ AstPathId(
Program( 45,
Module, ),
),
Module(
Body(
8,
),
),
ModuleItem(
ModuleDecl,
),
ModuleDecl(
ExportDecl,
),
ExportDecl(
Decl,
),
Decl(
Var,
),
VarDecl(
Decls(
0,
),
),
VarDeclarator(
Init,
),
Expr(
Cond,
),
CondExpr(
Cons,
),
],
), ),
}, },
else: EffectsBlock { else: EffectsBlock {
...@@ -699,42 +576,9 @@ ...@@ -699,42 +576,9 @@
}, },
], ],
range: Exact( range: Exact(
[ AstPathId(
Program( 46,
Module, ),
),
Module(
Body(
8,
),
),
ModuleItem(
ModuleDecl,
),
ModuleDecl(
ExportDecl,
),
ExportDecl(
Decl,
),
Decl(
Var,
),
VarDecl(
Decls(
0,
),
),
VarDeclarator(
Init,
),
Expr(
Cond,
),
CondExpr(
Alt,
),
],
), ),
}, },
}, },
...@@ -1097,48 +941,9 @@ ...@@ -1097,48 +941,9 @@
}, },
], ],
range: Exact( range: Exact(
[ AstPathId(
Program( 12,
Module, ),
),
Module(
Body(
3,
),
),
ModuleItem(
Stmt,
),
Stmt(
Decl,
),
Decl(
Fn,
),
FnDecl(
Function,
),
Function(
Body,
),
FunctionBody(
Stmts(
0,
),
),
Stmt(
Return,
),
ReturnStmt(
Arg,
),
Expr(
Cond,
),
CondExpr(
Cons,
),
],
), ),
}, },
else: EffectsBlock { else: EffectsBlock {
...@@ -1202,48 +1007,9 @@ ...@@ -1202,48 +1007,9 @@
}, },
], ],
range: Exact( range: Exact(
[ AstPathId(
Program( 13,
Module, ),
),
Module(
Body(
3,
),
),
ModuleItem(
Stmt,
),
Stmt(
Decl,
),
Decl(
Fn,
),
FnDecl(
Function,
),
Function(
Body,
),
FunctionBody(
Stmts(
0,
),
),
Stmt(
Return,
),
ReturnStmt(
Arg,
),
Expr(
Cond,
),
CondExpr(
Alt,
),
],
), ),
}, },
}, },
......
...@@ -223,70 +223,9 @@ ...@@ -223,70 +223,9 @@
}, },
], ],
range: Exact( range: Exact(
[ AstPathId(
Program( 21,
Module, ),
),
Module(
Body(
2,
),
),
ModuleItem(
Stmt,
),
Stmt(
Decl,
),
Decl(
Class,
),
ClassDecl(
Class,
),
Class(
Body(
0,
),
),
ClassMember(
Constructor,
),
Constructor(
Body,
),
FunctionBody(
Stmts(
0,
),
),
Stmt(
Expr,
),
ExprStmt(
Expr,
),
Expr(
Call,
),
CallExpr(
Args(
0,
),
),
ExprOrSpread(
Expr,
),
Expr(
Arrow,
),
ArrowExpr(
Body,
),
ArrowFunctionBody(
FunctionBody,
),
],
), ),
}, },
), ),
......
...@@ -129,57 +129,9 @@ ...@@ -129,57 +129,9 @@
}, },
], ],
range: Exact( range: Exact(
[ AstPathId(
Program( 15,
Script, ),
),
Script(
Body(
3,
),
),
Stmt(
Expr,
),
ExprStmt(
Expr,
),
Expr(
Call,
),
CallExpr(
Callee,
),
Callee(
Expr,
),
Expr(
Paren,
),
ParenExpr(
Expr,
),
Expr(
Arrow,
),
ArrowExpr(
Body,
),
ArrowFunctionBody(
FunctionBody,
),
FunctionBody(
Stmts(
1,
),
),
Stmt(
If,
),
IfStmt(
Cons,
),
],
), ),
}, },
}, },
......
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