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