Unverified Commit c5f0da7b authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[turbopack] Remove turbotask functions from `trait ResolveOrigin` (#94324)

### What?

Removes the `#[turbo_tasks::function]` annotations from the
`ResolveOrigin` trait methods (`origin_path`, `asset_context`,
`resolve_options`), turning them into plain synchronous trait methods.
Callers obtain the value once via `Vc::into_trait_ref().await?` and then
call the methods directly on the resulting `TraitRef`.

This mirrors the earlier de-functionification of the `Issue` trait
(#92623).

### Why?

The `ResolveOrigin` implementations are all trivial — they return a
stored field or delegate a single call.

| Task (misses, before → after) | Misses removed |
| --- | --- |
| `ResolveOrigin::resolve_options` (dyn) | 92,608 → 0 |
| `EcmascriptModuleAsset::origin_path` | 64,779 → 0 |
| `ResolveOriginWithTransition::asset_context` | 52,292 → 0 |
| `ResolveOriginWithTransition::origin_path` | 52,292 → 0 |
| `EcmascriptModuleAsset::asset_context` | 41,164 → 0 |
| `PlainResolveOrigin::{origin_path, asset_context}` | 105 + 105 → 0 |
| `EcmascriptCssModule::{origin_path, asset_context}` | 32 + 32 → 0 |
| `CssModule::{origin_path, asset_context}` | 19 + 19 → 0 |

Net effect in that run: **~303k fewer cache misses** (total misses
6,197,068 → 5,893,545) — The ~1.35M eliminated cached-task *hits*
additionally remove the per-call task lookup/scheduling overhead.

The caching that genuinely matters is preserved one layer down —
`AssetContext::resolve_options` (which `ResolveOrigin::resolve_options`
delegated to) is still a cached task; its miss count is unchanged
(39,668) since those distinct results were always computed, and it
simply absorbs the call volume directly now (hit rate 57% → 92%).

## Build Performance: `ResolveOrigin` optimization

Benchmark across 10 runs per branch.

| Metric | Base | This branch | Δ |
|---|---|---|---|
| **Wall time** | 43.302 s | 42.692 s | **−0.61 s (−1.4%)** |
| **User time** | 314.249 s | 310.919 s | **−3.33 s (−1.1%)** |
| **Sys time** | 84.225 s | 84.618 s | +0.39 s (+0.5%) |
| **MaxRSS** | 14106.1 MB | 13883.4 MB | **−222.8 MB (−1.6%)** |

### Notes on significance

- **User time** is the cleanest signal: −1.1% with very tight variance
(base σ 0.4%, branch σ 0.3%). The drop (~3.3 s) is well outside the
noise — a real reduction in CPU work.
- **MaxRSS** is down a solid 1.6% (~223 MB) with tight variance on both
sides (σ ≈ 0.5–0.6%) — a clear, reproducible memory win.
- **Wall time** improves 1.4%, but variance is large (base σ 6.6%,
branch σ 4.5%, with one 50 s outlier in the base set), so treat this as
directional. It tracks the user-time improvement.
- **Sys time** is essentially flat (+0.5%, within its ~10% run-to-run
noise) — no meaningful change, as expected for a CPU/allocation
optimization.

### Invalidation tradeoff

The main behavioral risk is invalidation granularity. Removing the
per-method tasks removes their invalidation boundary: a consumer that
previously depended only on the `origin_path()` (or `asset_context()`)
task output now reads the value off the origin directly, so it is tied
to the origin cell rather than to that one method's cached output.

In practice this is narrow, because every `ResolveOrigin` implementor is
an immutable, content-addressed `#[turbo_tasks::value]` (only
`ResolvedVc`/owned fields) — a different field value means a different
cell, so "reading the whole value vs. one field" does not by itself
widen invalidation.

<!-- NEXT_JS_LLM_PR -->
parent 74bb0d9a
# yaml-language-server: $schema=https://raw.githubusercontent.com/ast-grep/ast-grep/main/schemas/rule.json
id: resolved-vc-in-return-type
message: Returning a `ResolvedVc` in a turbo task is not recommended. Consider replacing `$TYPE` in `$FN_NAME` with `$RESOLVED_VC` instead.
message: Returning a `ResolvedVc` in a turbo task is not recommended. Consider replacing `ResolvedVc<$A>` in `$FN_NAME` with `Vc<$A>` instead.
severity: warning # error, warning, info, hint
language: Rust
rule:
any:
# turbo tasks function
- all:
- pattern:
context: 'let x: ResolvedVc<$A> = 1;'
selector: generic_type
- pattern: $TYPE
inside:
kind: function_item
field: return_type
stopBy: end
follows:
pattern: '#[turbo_tasks::function]'
has:
kind: identifier
pattern: $FN_NAME
# turbo tasks value trait
- all:
- pattern:
context: 'let x: ResolvedVc<$A> = 1;'
selector: generic_type
- pattern: $TYPE
inside:
kind: function_signature_item
field: return_type
stopBy: end
inside:
inside:
kind: trait_item
follows:
pattern: '#[turbo_tasks::value_trait]'
has:
kind: identifier
pattern: $FN_NAME
rewriters:
- id: rewrite-vc
rule:
pattern: $TYPE
fix: Vc<$A>
transform:
RESOLVED_VC:
rewrite:
rewriters: [rewrite-vc]
source: $TYPE
fix: $RESOLVED_VC
# The `ResolvedVc<$A>` generic type itself, captured as $TYPE.
pattern:
context: 'let x: ResolvedVc<$A> = 1;'
selector: generic_type
# ...appearing in the return type of a `#[turbo_tasks::function]`.
inside:
kind: function_item
field: return_type
stopBy: end
follows:
pattern: '#[turbo_tasks::function]'
stopBy: end
has:
kind: identifier
pattern: $FN_NAME
fix: Vc<$A>
......@@ -5,7 +5,6 @@ use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc, trace::TraceRawVcs};
use turbo_tasks_fs::FileSystemPath;
use turbopack::module_options::ModuleRule;
use turbopack_core::{context::AssetContext, resolve::origin::ResolveOrigin};
use turbopack_ecmascript::{CustomTransformer, TransformPlugin};
use crate::next_config::NextConfig;
......@@ -46,33 +45,6 @@ pub async fn get_swc_ecma_transform_plugin_rule(
}
}
/// A resolve origin without any asset_context, intended for handle_resolve_error
#[turbo_tasks::value]
pub struct DummyResolveOrigin {
origin_path: FileSystemPath,
}
#[turbo_tasks::value_impl]
impl DummyResolveOrigin {
#[turbo_tasks::function]
pub fn new(origin_path: FileSystemPath) -> Vc<Self> {
DummyResolveOrigin { origin_path }.cell()
}
}
#[turbo_tasks::value_impl]
impl ResolveOrigin for DummyResolveOrigin {
#[turbo_tasks::function]
fn origin_path(&self) -> Vc<FileSystemPath> {
self.origin_path.clone().cell()
}
#[turbo_tasks::function]
fn asset_context(&self) -> Result<Vc<Box<dyn AssetContext>>> {
anyhow::bail!("DummyResolveOrigin has no asset context");
}
}
pub async fn get_swc_ecma_transform_rule_impl(
project_path: FileSystemPath,
plugin_configs: &[(RcStr, serde_json::Value)],
......@@ -126,7 +98,7 @@ pub async fn get_swc_ecma_transform_rule_impl(
.as_raw_module_result(),
ReferenceType::CommonJs(CommonJsReferenceSubType::Undefined),
// TODO proper error location
Vc::upcast(DummyResolveOrigin::new(project_path.clone())),
project_path.clone(),
request,
resolve_options,
ResolveErrorMode::Error,
......
......@@ -28,6 +28,7 @@ use turbopack_core::{
ChunkingConfig, ChunkingContext, ChunkingContextExt, ContentHashing, EvaluatableAsset,
MangleType, MinifyType, SourceMapsType, availability_info::AvailabilityInfo,
},
context::AssetContext,
environment::{BrowserEnvironment, Environment, ExecutionEnvironment, NodeJsEnvironment},
ident::AssetIdent,
issue::{IssueReporter, IssueSeverity, handle_issues},
......@@ -40,7 +41,7 @@ use turbopack_core::{
output::{OutputAsset, OutputAssets, OutputAssetsWithReferenced},
reference_type::{EntryReferenceSubType, ReferenceType},
resolve::{
origin::{PlainResolveOrigin, ResolveOrigin, ResolveOriginExt},
origin::{PlainResolveOrigin, ResolveOrigin},
parse::Request,
},
};
......@@ -283,27 +284,33 @@ async fn build_internal(
.await?)
.to_vec();
let origin = PlainResolveOrigin::new(asset_context, project_fs.root().await?.join("_")?);
let origin =
PlainResolveOrigin::new(asset_context, project_fs.root().await?.join("_")?).await?;
let resolve_options = origin.resolve_options();
let asset_context = origin.asset_context();
let origin_path = origin.origin_path();
let project_dir = &project_dir;
let entries = async move {
entry_requests
.into_iter()
.map(|request_vc| async move {
let ty = ReferenceType::Entry(EntryReferenceSubType::Undefined);
let request = request_vc.await?;
origin
.resolve_asset(request_vc, origin.resolve_options(), ty)
.await?
.await?
.first_module()
.await?
.with_context(|| {
format!(
"Unable to resolve entry {} from directory {}.",
request.request().unwrap(),
project_dir
)
})
.map(|request_vc| {
let origin_path = origin_path.clone();
async move {
let ty = ReferenceType::Entry(EntryReferenceSubType::Undefined);
let request = request_vc.await?;
asset_context
.resolve_asset(origin_path, request_vc, resolve_options, ty)
.await?
.first_module()
.await?
.with_context(|| {
format!(
"Unable to resolve entry {} from directory {}.",
request.request().unwrap(),
project_dir
)
})
}
})
.try_join()
.await
......
......@@ -9,6 +9,7 @@ use turbopack_core::{
chunk::{
ChunkableModule, ChunkingContext, EvaluatableAsset, SourceMapSourceType, SourceMapsType,
},
context::AssetContext,
environment::Environment,
file_source::FileSource,
module::Module,
......@@ -17,7 +18,7 @@ use turbopack_core::{
},
reference_type::{EntryReferenceSubType, ReferenceType},
resolve::{
origin::{PlainResolveOrigin, ResolveOrigin, ResolveOriginExt},
origin::{PlainResolveOrigin, ResolveOrigin},
parse::Request,
},
};
......@@ -135,17 +136,22 @@ pub async fn create_web_entry_source(
let runtime_entries = entries.resolve_entries(asset_context);
let origin = PlainResolveOrigin::new(asset_context, root_path.join("_")?);
let origin = PlainResolveOrigin::new(asset_context, root_path.join("_")?).await?;
let resolve_options = origin.resolve_options();
let asset_context = origin.asset_context();
let origin_path = origin.origin_path();
let entries = entry_requests
.into_iter()
.map(|request| async move {
let ty = ReferenceType::Entry(EntryReferenceSubType::Web);
origin
.resolve_asset(request, origin.resolve_options(), ty)
.await?
.await?
.first_module()
.await
.map(|request| {
let origin_path = origin_path.clone();
async move {
let ty = ReferenceType::Entry(EntryReferenceSubType::Web);
asset_context
.resolve_asset(origin_path, request, resolve_options, ty)
.await?
.first_module()
.await
}
})
.try_flat_join()
.await?;
......
......@@ -12,14 +12,14 @@ use crate::{
reference_type::ReferenceType,
resolve::{
ModuleResolveResult, ResolveErrorMode, ResolveResult, options::ResolveOptions,
origin::ResolveOrigin, parse::Request,
parse::Request,
},
};
pub async fn handle_resolve_error(
result: Vc<ModuleResolveResult>,
reference_type: ReferenceType,
origin: Vc<Box<dyn ResolveOrigin>>,
origin_path: FileSystemPath,
request: Vc<Request>,
resolve_options: Vc<ResolveOptions>,
error_mode: ResolveErrorMode,
......@@ -31,7 +31,7 @@ pub async fn handle_resolve_error(
if result_ref.is_unresolvable() {
emit_unresolvable_issue(
error_mode,
origin,
&origin_path,
reference_type,
request,
resolve_options,
......@@ -40,14 +40,14 @@ pub async fn handle_resolve_error(
.await?;
}
handle_item_issues(result_ref.errors(), origin, source).await?;
handle_item_issues(result_ref.errors(), &origin_path, source).await?;
result
}
Err(err) => {
emit_resolve_error_issue(
error_mode,
origin,
&origin_path,
reference_type,
request,
resolve_options,
......@@ -63,7 +63,7 @@ pub async fn handle_resolve_error(
pub async fn handle_resolve_source_error(
result: Vc<ResolveResult>,
reference_type: ReferenceType,
origin: Vc<Box<dyn ResolveOrigin>>,
origin_path: FileSystemPath,
request: Vc<Request>,
resolve_options: Vc<ResolveOptions>,
error_mode: ResolveErrorMode,
......@@ -74,7 +74,7 @@ pub async fn handle_resolve_source_error(
if result_ref.is_unresolvable() {
emit_unresolvable_issue(
error_mode,
origin,
&origin_path,
reference_type,
request,
resolve_options,
......@@ -83,14 +83,14 @@ pub async fn handle_resolve_source_error(
.await?;
}
handle_item_issues(result_ref.errors(), origin, source).await?;
handle_item_issues(result_ref.errors(), &origin_path, source).await?;
result
}
Err(err) => {
emit_resolve_error_issue(
error_mode,
origin,
&origin_path,
reference_type,
request,
resolve_options,
......@@ -105,12 +105,11 @@ pub async fn handle_resolve_source_error(
async fn handle_item_issues(
items: impl Iterator<Item = ResolvedVc<Box<dyn Issue>>>,
origin: Vc<Box<dyn ResolveOrigin>>,
origin_path: &FileSystemPath,
source: Option<IssueSource>,
) -> Result<()> {
let mut items = items.peekable();
if items.peek().is_some() {
let file_path = origin.origin_path().owned().await?;
for item in items {
let trait_ref = item.into_trait_ref().await?;
ResolvingIssueWithLocation {
......@@ -118,7 +117,7 @@ async fn handle_item_issues(
severity: trait_ref.severity(),
stage: trait_ref.stage(),
documentation_link: trait_ref.documentation_link(),
file_path: file_path.clone(),
file_path: origin_path.clone(),
source,
}
.resolved_cell()
......@@ -130,7 +129,7 @@ async fn handle_item_issues(
async fn emit_resolve_error_issue(
error_mode: ResolveErrorMode,
origin: Vc<Box<dyn ResolveOrigin>>,
origin_path: &FileSystemPath,
reference_type: ReferenceType,
request: Vc<Request>,
resolve_options: Vc<ResolveOptions>,
......@@ -147,7 +146,7 @@ async fn emit_resolve_error_issue(
};
ResolvingIssue {
severity,
file_path: origin.origin_path().owned().await?,
file_path: origin_path.clone(),
request_type: format!("{reference_type} request"),
request: request.to_resolved().await?,
resolve_options: resolve_options.to_resolved().await?,
......@@ -161,8 +160,7 @@ async fn emit_resolve_error_issue(
async fn emit_unresolvable_issue(
error_mode: ResolveErrorMode,
origin: Vc<Box<dyn ResolveOrigin>>,
origin_path: &FileSystemPath,
reference_type: ReferenceType,
request: Vc<Request>,
resolve_options: Vc<ResolveOptions>,
......@@ -178,7 +176,7 @@ async fn emit_unresolvable_issue(
};
ResolvingIssue {
severity,
file_path: origin.origin_path().owned().await?,
file_path: origin_path.clone(),
request_type: format!("{reference_type} request"),
request: request.to_resolved().await?,
resolve_options: resolve_options.to_resolved().await?,
......
......@@ -1666,9 +1666,11 @@ pub async fn url_resolve(
issue_source: Option<IssueSource>,
error_mode: ResolveErrorMode,
) -> Result<Vc<ModuleResolveResult>> {
let resolve_options = origin.resolve_options();
let origin_ref = origin.into_trait_ref().await?;
let resolve_options = origin_ref.resolve_options();
let rel_request = request.as_relative();
let origin_path_parent = origin.origin_path().await?.parent();
let origin_path = origin_ref.origin_path();
let origin_path_parent = origin_path.parent();
let rel_result = resolve(
origin_path_parent.clone(),
reference_type.clone(),
......@@ -1697,13 +1699,13 @@ pub async fn url_resolve(
} else {
rel_result
};
let result = origin
let result = origin_ref
.asset_context()
.process_resolve_result(result, reference_type.clone());
handle_resolve_error(
result,
reference_type,
origin,
origin_path,
*request,
resolve_options,
error_mode,
......
......@@ -16,20 +16,15 @@ pub trait ResolveOrigin {
/// since that might be needed to infer custom resolving options for that
/// specific file. But usually only the directory is relevant for the real
/// resolving.
#[turbo_tasks::function]
fn origin_path(self: Vc<Self>) -> Vc<FileSystemPath>;
fn origin_path(&self) -> FileSystemPath;
/// The AssetContext that carries the configuration for building that
/// subgraph.
#[turbo_tasks::function]
fn asset_context(self: Vc<Self>) -> Vc<Box<dyn AssetContext>>;
fn asset_context(&self) -> ResolvedVc<Box<dyn AssetContext>>;
/// Get the resolve options that apply for this origin.
#[turbo_tasks::function]
async fn resolve_options(self: Vc<Self>) -> Result<Vc<ResolveOptions>> {
Ok(self
.asset_context()
.resolve_options(self.origin_path().owned().await?))
fn resolve_options(&self) -> Vc<ResolveOptions> {
self.asset_context().resolve_options(self.origin_path())
}
}
......@@ -47,7 +42,10 @@ pub trait ResolveOriginExt: Send {
) -> impl Future<Output = Result<Vc<ModuleResolveResult>>> + Send;
/// Adds a transition that is used for resolved assets.
fn with_transition(self: ResolvedVc<Self>, transition: RcStr) -> Vc<Box<dyn ResolveOrigin>>;
fn with_transition(
self: ResolvedVc<Self>,
transition: RcStr,
) -> impl Future<Output = Result<Vc<Box<dyn ResolveOrigin>>>> + Send;
}
impl<T> ResolveOriginExt for T
......@@ -60,22 +58,35 @@ where
options: Vc<ResolveOptions>,
reference_type: ReferenceType,
) -> Result<Vc<ModuleResolveResult>> {
Ok(self.asset_context().to_resolved().await?.resolve_asset(
self.origin_path().owned().await?,
let origin = Vc::upcast_non_strict::<Box<dyn ResolveOrigin>>(self)
.into_trait_ref()
.await?;
Ok(origin.asset_context().resolve_asset(
origin.origin_path(),
*request.to_resolved().await?,
*options.to_resolved().await?,
reference_type,
))
}
fn with_transition(self: ResolvedVc<Self>, transition: RcStr) -> Vc<Box<dyn ResolveOrigin>> {
Vc::upcast(
async fn with_transition(
self: ResolvedVc<Self>,
transition: RcStr,
) -> Result<Vc<Box<dyn ResolveOrigin>>> {
let origin = Vc::upcast_non_strict::<Box<dyn ResolveOrigin>>(*self)
.into_trait_ref()
.await?;
Ok(Vc::upcast(
ResolveOriginWithTransition {
previous: ResolvedVc::upcast_non_strict(self),
transition,
origin_path: origin.origin_path(),
asset_context: origin
.asset_context()
.with_transition(transition)
.to_resolved()
.await?,
}
.cell(),
)
))
}
}
......@@ -103,35 +114,33 @@ impl PlainResolveOrigin {
#[turbo_tasks::value_impl]
impl ResolveOrigin for PlainResolveOrigin {
#[turbo_tasks::function]
fn origin_path(&self) -> Vc<FileSystemPath> {
self.origin_path.clone().cell()
fn origin_path(&self) -> FileSystemPath {
self.origin_path.clone()
}
#[turbo_tasks::function]
fn asset_context(&self) -> Vc<Box<dyn AssetContext>> {
*self.asset_context
fn asset_context(&self) -> ResolvedVc<Box<dyn AssetContext>> {
self.asset_context
}
}
/// Wraps a ResolveOrigin to add a transition.
///
/// The transition is applied to the wrapped origin's [`AssetContext`] eagerly at
/// construction (see [`ResolveOriginExt::with_transition`]) so that the trait
/// methods can be synchronous.
#[turbo_tasks::value]
struct ResolveOriginWithTransition {
previous: ResolvedVc<Box<dyn ResolveOrigin>>,
transition: RcStr,
origin_path: FileSystemPath,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
}
#[turbo_tasks::value_impl]
impl ResolveOrigin for ResolveOriginWithTransition {
#[turbo_tasks::function]
fn origin_path(&self) -> Vc<FileSystemPath> {
self.previous.origin_path()
fn origin_path(&self) -> FileSystemPath {
self.origin_path.clone()
}
#[turbo_tasks::function]
fn asset_context(&self) -> Vc<Box<dyn AssetContext>> {
self.previous
.asset_context()
.with_transition(self.transition.clone())
fn asset_context(&self) -> ResolvedVc<Box<dyn AssetContext>> {
self.asset_context
}
}
......@@ -43,28 +43,31 @@ pub struct CssModule {
ty: CssModuleType,
environment: Option<ResolvedVc<Environment>>,
lightningcss_features: LightningCssFeatureFlags,
/// The path of `source`, precomputed so that `ResolveOrigin::origin_path` is synchronous.
origin_path: FileSystemPath,
}
#[turbo_tasks::value_impl]
impl CssModule {
/// Creates a new CSS asset.
#[turbo_tasks::function]
pub fn new(
pub async fn new(
source: ResolvedVc<Box<dyn Source>>,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
ty: CssModuleType,
import_context: Option<ResolvedVc<ImportContext>>,
environment: Option<ResolvedVc<Environment>>,
lightningcss_features: LightningCssFeatureFlags,
) -> Vc<Self> {
Self::cell(CssModule {
) -> Result<Vc<Self>> {
Ok(Self::cell(CssModule {
origin_path: source.ident().await?.path.clone(),
source,
asset_context,
import_context,
ty,
environment,
lightningcss_features,
})
}))
}
/// Returns the asset ident of the source without the "css" modifier
......@@ -202,14 +205,12 @@ impl CssChunkPlaceable for CssModule {}
#[turbo_tasks::value_impl]
impl ResolveOrigin for CssModule {
#[turbo_tasks::function]
async fn origin_path(&self) -> Result<Vc<FileSystemPath>> {
Ok(self.source.ident().await?.path.clone().cell())
fn origin_path(&self) -> FileSystemPath {
self.origin_path.clone()
}
#[turbo_tasks::function]
fn asset_context(&self) -> Vc<Box<dyn AssetContext>> {
*self.asset_context
fn asset_context(&self) -> ResolvedVc<Box<dyn AssetContext>> {
self.asset_context
}
}
......
......@@ -41,19 +41,22 @@ use crate::{
pub struct EcmascriptCssModule {
pub source: ResolvedVc<Box<dyn Source>>,
pub asset_context: ResolvedVc<Box<dyn AssetContext>>,
/// The path of `source`, precomputed so that `ResolveOrigin::origin_path` is synchronous.
origin_path: FileSystemPath,
}
#[turbo_tasks::value_impl]
impl EcmascriptCssModule {
#[turbo_tasks::function]
pub fn new(
pub async fn new(
source: ResolvedVc<Box<dyn Source>>,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
) -> Vc<Self> {
Self::cell(EcmascriptCssModule {
) -> Result<Vc<Self>> {
Ok(Self::cell(EcmascriptCssModule {
origin_path: source.ident().await?.path.clone(),
source,
asset_context,
})
}))
}
}
......@@ -357,14 +360,12 @@ impl EcmascriptChunkPlaceable for EcmascriptCssModule {
#[turbo_tasks::value_impl]
impl ResolveOrigin for EcmascriptCssModule {
#[turbo_tasks::function]
async fn origin_path(&self) -> Result<Vc<FileSystemPath>> {
Ok(self.source.ident().await?.path.clone().cell())
fn origin_path(&self) -> FileSystemPath {
self.origin_path.clone()
}
#[turbo_tasks::function]
fn asset_context(&self) -> Vc<Box<dyn AssetContext>> {
*self.asset_context
fn asset_context(&self) -> ResolvedVc<Box<dyn AssetContext>> {
self.asset_context
}
}
......
......@@ -47,7 +47,7 @@ impl ModuleReference for CssModuleComposeReference {
);
let resolved = result.await?.first_module().await?;
let file_path = self.origin.origin_path().to_resolved().await?;
let file_path = self.origin.into_trait_ref().await?.origin_path();
if let Some(module) = resolved {
if ResolvedVc::try_downcast_type::<EcmascriptCssModule>(module).is_none() {
CssModuleComposesIssue {
......@@ -92,7 +92,7 @@ impl ModuleReference for CssModuleComposeReference {
#[turbo_tasks::value(shared)]
struct CssModuleComposesIssue {
severity: IssueSeverity,
file_path: ResolvedVc<FileSystemPath>,
file_path: FileSystemPath,
message: RcStr,
}
......@@ -114,7 +114,7 @@ impl Issue for CssModuleComposesIssue {
}
async fn file_path(&self) -> Result<FileSystemPath> {
self.file_path.owned().await
Ok(self.file_path.clone())
}
async fn description(&self) -> Result<Option<StyledString>> {
......
......@@ -426,6 +426,8 @@ pub struct EcmascriptModuleAsset {
pub compile_time_info: ResolvedVc<CompileTimeInfo>,
pub side_effect_free_packages: Option<ResolvedVc<Glob>>,
pub inner_assets: Option<ResolvedVc<InnerAssets>>,
/// The path of `source`, precomputed so that `ResolveOrigin::origin_path` is synchronous.
origin_path: FileSystemPath,
}
#[turbo_tasks::value_trait]
......@@ -704,7 +706,7 @@ async fn determine_module_type_for_directory(
#[turbo_tasks::value_impl]
impl EcmascriptModuleAsset {
#[turbo_tasks::function]
fn new(
async fn new(
source: ResolvedVc<Box<dyn Source>>,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
ty: EcmascriptModuleAssetType,
......@@ -712,8 +714,9 @@ impl EcmascriptModuleAsset {
options: ResolvedVc<EcmascriptOptions>,
compile_time_info: ResolvedVc<CompileTimeInfo>,
side_effect_free_packages: Option<ResolvedVc<Glob>>,
) -> Vc<Self> {
Self::cell(EcmascriptModuleAsset {
) -> Result<Vc<Self>> {
Ok(Self::cell(EcmascriptModuleAsset {
origin_path: source.ident().await?.path.clone(),
source,
asset_context,
ty,
......@@ -722,7 +725,7 @@ impl EcmascriptModuleAsset {
compile_time_info,
side_effect_free_packages,
inner_assets: None,
})
}))
}
#[turbo_tasks::function]
......@@ -748,6 +751,7 @@ impl EcmascriptModuleAsset {
))
} else {
Ok(Self::cell(EcmascriptModuleAsset {
origin_path: source.ident().await?.path.clone(),
source,
asset_context,
ty,
......@@ -810,7 +814,7 @@ impl EcmascriptModuleAsset {
SpecifiedModuleType::Automatic => {}
}
determine_module_type_for_directory(self.origin_path().await?.parent()).await
determine_module_type_for_directory(this.origin_path.parent()).await
}
}
......@@ -953,14 +957,12 @@ impl EvaluatableAsset for EcmascriptModuleAsset {}
#[turbo_tasks::value_impl]
impl ResolveOrigin for EcmascriptModuleAsset {
#[turbo_tasks::function]
async fn origin_path(&self) -> Result<Vc<FileSystemPath>> {
Ok(self.source.ident().await?.path.clone().cell())
fn origin_path(&self) -> FileSystemPath {
self.origin_path.clone()
}
#[turbo_tasks::function]
fn asset_context(&self) -> Vc<Box<dyn AssetContext>> {
*self.asset_context
fn asset_context(&self) -> ResolvedVc<Box<dyn AssetContext>> {
self.asset_context
}
}
......
use anyhow::{Result, bail};
use async_trait::async_trait;
use bincode::{Decode, Encode};
use either::Either;
use strsim::jaro;
use swc_core::{
......@@ -11,12 +12,15 @@ use swc_core::{
quote,
};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, ValueToString, Vc, turbobail};
use turbo_tasks::{
NonLocalValue, ResolvedVc, ValueToString, Vc, debug::ValueDebugFormat, trace::TraceRawVcs,
turbobail,
};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
chunk::{ChunkingContext, ChunkingType, ModuleChunkItemIdExt},
issue::{Issue, IssueExt, IssueSeverity, IssueSource, IssueStage, StyledString},
loader::ResolvedWebpackLoaderItem,
loader::{ResolvedWebpackLoaderItem, WebpackLoaderItem},
module::{Module, ModuleSideEffects},
module_graph::binding_usage_info::ModuleExportUsageInfo,
reference::ModuleReference,
......@@ -372,31 +376,77 @@ impl EsmAssetReferences {
#[value_to_string("import {request}")]
pub struct EsmAssetReference {
pub module: ResolvedVc<EcmascriptModuleAsset>,
/// The resolve origin, with any annotation-driven transition already applied at construction.
pub origin: ResolvedVc<Box<dyn ResolveOrigin>>,
// Request is a string to avoid eagerly parsing into a `Request` VC
pub request: RcStr,
pub annotations: Option<ImportAnnotations>,
pub issue_source: IssueSource,
pub export_name: Option<ModulePart>,
pub import_usage: ImportUsage,
pub import_externals: bool,
pub tree_shaking_mode: Option<TreeShakingMode>,
pub is_pure_import: bool,
pub resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
/// Rarely-present, slightly-large fields (import-annotation overrides and a resolve override),
/// boxed off the common path so the typical reference stays small. `None` whenever every field
/// would be empty.
extras: Option<Box<EsmReferenceExtras>>,
}
impl EsmAssetReference {
fn get_origin(&self) -> Vc<Box<dyn ResolveOrigin>> {
if let Some(transition) = self.annotations.as_ref().and_then(|a| a.transition()) {
self.origin.with_transition(transition.into())
} else {
*self.origin
}
/// Optional extra state for an [`EsmAssetReference`] that is rarely present: the few values
/// extracted from `ImportAnnotations` (the full `ImportAnnotations` — a `BTreeMap` plus several
/// `Option`s — is not retained) plus a `resolve_override` from matched inner assets.
#[derive(
Clone,
Default,
PartialEq,
Eq,
Hash,
Debug,
TraceRawVcs,
ValueDebugFormat,
NonLocalValue,
Encode,
Decode,
)]
struct EsmReferenceExtras {
/// `turbopackLoader` configuration (drives `ImportWithTurbopackUse`).
turbopack_loader: Option<WebpackLoaderItem>,
/// `turbopackAs` rename configuration.
turbopack_rename_as: Option<RcStr>,
/// `turbopackModuleType` override (distinct from the `with { type: ... }` attribute).
turbopack_module_type: Option<RcStr>,
/// The `with { type: ... }` attribute (drives `ImportWithType`).
module_type: Option<RcStr>,
/// The chunking-type annotation (drives `chunking_type`).
chunking_type: Option<SpecifiedChunkingType>,
/// A module to resolve to directly, bypassing resolution (from a matched inner asset).
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
}
impl EsmReferenceExtras {
/// Builds the extras from import annotations and a resolve override, returning `None` (rather
/// than an all-empty box) when nothing relevant is present — the common case.
fn new(
annotations: Option<&ImportAnnotations>,
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
) -> Option<Box<Self>> {
let extras = EsmReferenceExtras {
turbopack_loader: annotations.and_then(|a| a.turbopack_loader().cloned()),
turbopack_rename_as: annotations.and_then(|a| a.turbopack_rename_as().cloned()),
turbopack_module_type: annotations.and_then(|a| a.turbopack_module_type().cloned()),
module_type: annotations
.and_then(|a| a.module_type())
.map(|m| RcStr::from(&*m.to_string_lossy())),
chunking_type: annotations.and_then(|a| a.chunking_type()),
resolve_override,
};
(extras != EsmReferenceExtras::default()).then(|| Box::new(extras))
}
}
impl EsmAssetReference {
pub fn new(
#[allow(clippy::too_many_arguments)]
async fn new_inner(
module: ResolvedVc<EcmascriptModuleAsset>,
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
request: RcStr,
......@@ -407,8 +457,47 @@ impl EsmAssetReference {
import_externals: bool,
tree_shaking_mode: Option<TreeShakingMode>,
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
) -> Self {
EsmAssetReference {
is_pure_import: bool,
) -> Result<Self> {
// Apply any annotation-driven transition eagerly so the stored origin is final and the
// `annotations` don't need to be retained on the reference.
let origin = if let Some(transition) = annotations.as_ref().and_then(|a| a.transition()) {
origin
.with_transition(transition.into())
.await?
.to_resolved()
.await?
} else {
origin
};
Ok(EsmAssetReference {
module,
origin,
request,
issue_source,
export_name,
import_usage,
import_externals,
tree_shaking_mode,
is_pure_import,
extras: EsmReferenceExtras::new(annotations.as_ref(), resolve_override),
})
}
#[allow(clippy::too_many_arguments)]
pub async fn new(
module: ResolvedVc<EcmascriptModuleAsset>,
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
request: RcStr,
issue_source: IssueSource,
annotations: Option<ImportAnnotations>,
export_name: Option<ModulePart>,
import_usage: ImportUsage,
import_externals: bool,
tree_shaking_mode: Option<TreeShakingMode>,
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
) -> Result<Self> {
Self::new_inner(
module,
origin,
request,
......@@ -418,12 +507,14 @@ impl EsmAssetReference {
import_usage,
import_externals,
tree_shaking_mode,
is_pure_import: false,
resolve_override,
}
/* is_pure_import */ false,
)
.await
}
pub fn new_pure(
#[allow(clippy::too_many_arguments)]
pub async fn new_pure(
module: ResolvedVc<EcmascriptModuleAsset>,
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
request: RcStr,
......@@ -434,8 +525,8 @@ impl EsmAssetReference {
import_externals: bool,
tree_shaking_mode: Option<TreeShakingMode>,
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
) -> Self {
EsmAssetReference {
) -> Result<Self> {
Self::new_inner(
module,
origin,
request,
......@@ -445,10 +536,36 @@ impl EsmAssetReference {
import_usage,
import_externals,
tree_shaking_mode,
is_pure_import: true,
resolve_override,
/* is_pure_import */ true,
)
.await
}
/// Builds a copy of this reference for a single resolved namespace export
/// (`import * as ns from 'foo'; ns.bar` → behave like `import { bar } from 'foo'`).
///
/// Reuses the already-transitioned `origin` and the `extras` (annotation values + resolve
/// override), overriding only the `export_name`. Stays synchronous (no transition / annotation
/// re-extraction) so it can be called from the synchronous namespace-rewrite path.
pub fn rewrite_for_export(&self, export_name: ModulePart) -> Self {
EsmAssetReference {
module: self.module,
origin: self.origin,
request: self.request.clone(),
issue_source: self.issue_source,
export_name: Some(export_name),
// TODO this is correct, but an overapproximation. We should have individual
// import_usage data for each export. This would be fixed by moving this
// logic earlier.
import_usage: self.import_usage.clone(),
import_externals: self.import_externals,
tree_shaking_mode: self.tree_shaking_mode,
is_pure_import: self.is_pure_import,
extras: self.extras.clone(),
}
}
pub(crate) fn get_referenced_asset(
self: Vc<Self>,
) -> impl Future<Output = Result<ReferencedAsset>> {
......@@ -460,20 +577,20 @@ impl EsmAssetReference {
impl ModuleReference for EsmAssetReference {
#[turbo_tasks::function]
async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
if let Some(resolved) = &self.resolve_override {
return Ok(*ModuleResolveResult::module(*resolved));
let extras = self.extras.as_deref();
if let Some(resolved) = extras.and_then(|e| e.resolve_override) {
return Ok(*ModuleResolveResult::module(resolved));
}
let ty = if let Some(loader) = self.annotations.as_ref().and_then(|a| a.turbopack_loader())
{
let ty = if let Some(loader) = extras.and_then(|e| e.turbopack_loader.as_ref()) {
// Resolve the loader path relative to the importing file
let origin = self.get_origin();
let origin_path = origin.origin_path().await?;
let origin_ref = self.origin.into_trait_ref().await?;
let origin_path = origin_ref.origin_path();
let loader_request = Request::parse(loader.loader.clone().into());
let resolved = resolve(
origin_path.parent(),
ReferenceType::Loader,
loader_request,
origin.resolve_options(),
origin_ref.resolve_options(),
);
let loader_fs_path = if let Some(source) = resolved.await?.first_source() {
source.ident().await?.path.clone()
......@@ -486,21 +603,11 @@ impl ModuleReference for EsmAssetReference {
loader: loader_fs_path,
options: loader.options.clone(),
},
rename_as: self
.annotations
.as_ref()
.and_then(|a| a.turbopack_rename_as())
.cloned(),
module_type: self
.annotations
.as_ref()
.and_then(|a| a.turbopack_module_type())
.cloned(),
rename_as: extras.and_then(|e| e.turbopack_rename_as.clone()),
module_type: extras.and_then(|e| e.turbopack_module_type.clone()),
}
} else if let Some(module_type) = self.annotations.as_ref().and_then(|a| a.module_type()) {
EcmaScriptModulesReferenceSubType::ImportWithType(RcStr::from(
&*module_type.to_string_lossy(),
))
} else if let Some(module_type) = extras.and_then(|e| e.module_type.as_ref()) {
EcmaScriptModulesReferenceSubType::ImportWithType(module_type.clone())
} else if let Some(part) = &self.export_name {
EcmaScriptModulesReferenceSubType::ImportPart(part.clone())
} else {
......@@ -535,7 +642,7 @@ impl ModuleReference for EsmAssetReference {
}
let result = esm_resolve(
self.get_origin(),
*self.origin,
request,
ty,
ResolveErrorMode::Error,
......@@ -563,9 +670,9 @@ impl ModuleReference for EsmAssetReference {
}
fn chunking_type(&self) -> Option<ChunkingType> {
self.annotations
.as_ref()
.and_then(|a| a.chunking_type())
self.extras
.as_deref()
.and_then(|e| e.chunking_type)
.map_or_else(
|| {
Some(ChunkingType::Parallel {
......@@ -611,9 +718,9 @@ impl EsmAssetReference {
// only chunked references can be imported
if this
.annotations
.as_ref()
.and_then(|a| a.chunking_type())
.extras
.as_deref()
.and_then(|e| e.chunking_type)
.is_none_or(|v| v != SpecifiedChunkingType::None)
{
let import_externals = this.import_externals;
......
......@@ -39,7 +39,6 @@ use crate::{
pub struct EsmAsyncAssetReference {
pub origin: ResolvedVc<Box<dyn ResolveOrigin>>,
pub request: ResolvedVc<Request>,
pub annotations: ImportAnnotations,
pub issue_source: IssueSource,
pub error_mode: ResolveErrorMode,
pub import_externals: bool,
......@@ -51,17 +50,8 @@ pub struct EsmAsyncAssetReference {
}
impl EsmAsyncAssetReference {
fn get_origin(&self) -> Vc<Box<dyn ResolveOrigin>> {
if let Some(transition) = self.annotations.transition() {
self.origin.with_transition(transition.into())
} else {
*self.origin
}
}
}
impl EsmAsyncAssetReference {
pub fn new(
#[allow(clippy::too_many_arguments)]
pub async fn new(
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
request: ResolvedVc<Request>,
issue_source: IssueSource,
......@@ -70,17 +60,27 @@ impl EsmAsyncAssetReference {
import_externals: bool,
export_usage: ExportUsage,
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
) -> Self {
EsmAsyncAssetReference {
) -> Result<Self> {
// Apply any annotation-driven transition eagerly so the stored origin is final and the
// `annotations` don't need to be retained on the reference.
let origin = if let Some(transition) = annotations.transition() {
origin
.with_transition(transition.into())
.await?
.to_resolved()
.await?
} else {
origin
};
Ok(EsmAsyncAssetReference {
origin,
request,
issue_source,
annotations,
error_mode,
import_externals,
export_usage,
resolve_override,
}
})
}
}
......@@ -93,7 +93,7 @@ impl ModuleReference for EsmAsyncAssetReference {
}
esm_resolve(
*self.get_origin().to_resolved().await?,
*self.origin,
*self.request,
EcmaScriptModulesReferenceSubType::DynamicImport,
self.error_mode,
......
......@@ -142,6 +142,7 @@ pub async fn compute_ecmascript_module_exports(
options.tree_shaking_mode,
resolve_override,
)
.await?
.resolved_cell();
import_references.push(reference);
......
......@@ -307,10 +307,11 @@ impl Module for CachedExternalModule {
.await?
}
CachedExternalType::Global | CachedExternalType::Script => {
let resolve_options = origin.into_trait_ref().await?.resolve_options();
origin
.resolve_asset(
Request::parse_string(self.request.clone()),
origin.resolve_options(),
resolve_options,
ReferenceType::Undefined,
)
.await?
......
......@@ -413,7 +413,7 @@ impl ImportMetaGlobMap {
issue_source: Option<IssueSource>,
error_mode: ResolveErrorMode,
) -> Result<Vc<Self>> {
let origin_path = origin.origin_path().await?.parent();
let origin_path = origin.into_trait_ref().await?.origin_path().parent();
// Use read_glob for efficient directory-pruning file discovery.
let glob_result = base_dir.read_glob(positive_glob).await?;
......@@ -594,7 +594,7 @@ impl ImportMetaGlobAsset {
#[turbo_tasks::function]
pub async fn map(&self) -> Result<Vc<ImportMetaGlobMap>> {
let origin = *self.origin;
let origin_dir = origin.origin_path().await?.parent();
let origin_dir = origin.into_trait_ref().await?.origin_path().parent();
// Compute the base directory for glob scanning.
// With `base`, patterns are resolved relative to origin + base.
......@@ -662,7 +662,7 @@ impl ImportMetaGlobAsset {
impl Module for ImportMetaGlobAsset {
#[turbo_tasks::function]
async fn ident(&self) -> Result<Vc<AssetIdent>> {
let origin_path = self.origin.origin_path().owned().await?;
let origin_path = self.origin.into_trait_ref().await?.origin_path();
Ok(AssetIdent::from_path(origin_path)
.with_modifier(modifier(
&self.patterns,
......
......@@ -67,7 +67,6 @@ use turbo_tasks::{
};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
chunk::ChunkingType,
compile_time_info::{
CompileTimeDefineValue, CompileTimeDefines, CompileTimeInfo, DefinableNameSegment,
DefinableNameSegmentRef, FreeVarReference, FreeVarReferences, FreeVarReferencesMembers,
......@@ -435,6 +434,7 @@ struct AnalysisState<'a> {
module: ResolvedVc<EcmascriptModuleAsset>,
source: ResolvedVc<Box<dyn Source>>,
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
origin_path: FileSystemPath,
compile_time_info: ResolvedVc<CompileTimeInfo>,
free_var_references_members: ResolvedVc<FreeVarReferencesMembers>,
compile_time_info_ref: ReadRef<CompileTimeInfo>,
......@@ -483,6 +483,7 @@ impl AnalysisState<'_> {
&|value| {
value_visitor(
*self.origin,
&self.origin_path,
value,
*self.compile_time_info,
&self.compile_time_info_ref,
......@@ -542,7 +543,9 @@ async fn analyze_ecmascript_module_internal(
let analyze_mode = options.analyze_mode;
let origin = ResolvedVc::upcast::<Box<dyn ResolveOrigin>>(module);
let path = &*origin.origin_path().await?;
let origin_ref = origin.into_trait_ref().await?;
let origin_path = origin_ref.origin_path();
let path = &origin_path;
let mut analysis = AnalyzeEcmascriptModuleResultBuilder::new(analyze_mode);
#[cfg(debug_assertions)]
{
......@@ -737,12 +740,9 @@ async fn analyze_ecmascript_module_internal(
if options.extract_source_map {
let span = tracing::trace_span!("source map reference");
async {
if let Some((source_map, reference)) = parse_source_map_comment(
source,
source_mapping_url.as_deref(),
&*origin.origin_path().await?,
)
.await?
if let Some((source_map, reference)) =
parse_source_map_comment(source, source_mapping_url.as_deref(), &origin_path)
.await?
{
analysis.set_source_map(source_map);
if let Some(reference) = reference {
......@@ -815,6 +815,7 @@ async fn analyze_ecmascript_module_internal(
module,
source,
origin,
origin_path: origin_path.clone(),
compile_time_info,
free_var_references_members: compile_time_info_ref
.free_var_references
......@@ -1243,20 +1244,7 @@ async fn analyze_ecmascript_module_internal(
};
if let Some("__turbopack_module_id__") = export.as_deref() {
let chunking_type = r
.await?
.annotations
.as_ref()
.and_then(|a| a.chunking_type())
.map_or_else(
|| {
Some(ChunkingType::Parallel {
inherit_async: true,
hoisted: true,
})
},
|c| c.as_chunking_type(true, true),
);
let chunking_type = r.await?.chunking_type();
analysis.add_reference_code_gen(
EsmModuleIdAssetReference::new(*r, chunking_type),
ast_path.into(),
......@@ -1280,23 +1268,11 @@ async fn analyze_ecmascript_module_internal(
esm_reference_index,
export.clone(),
|| {
EsmAssetReference::new(
original_reference.module,
original_reference.origin,
original_reference.request.clone(),
original_reference.issue_source,
original_reference.annotations.clone(),
Some(ModulePart::export(export.clone())),
// TODO this is correct, but an overapproximation.
// We should have individual import_usage data for
// each export. This would be fixed by moving this
// logic earlier (see TODO above)
original_reference.import_usage.clone(),
original_reference.import_externals,
original_reference.tree_shaking_mode,
original_reference.resolve_override,
)
.resolved_cell()
original_reference
.rewrite_for_export(ModulePart::export(
export.clone(),
))
.resolved_cell()
},
);
analysis.add_code_gen(EsmBinding::new_keep_this(
......@@ -1746,7 +1722,8 @@ async fn handle_dynamic_import_with_linked_args(
import_externals,
export_usage,
resolve_override,
),
)
.await?,
ast_path.to_vec().into(),
);
return Ok(());
......@@ -1995,7 +1972,7 @@ where
args.first(),
Some(JsValue::Url(_, JsValueUrlKind::Relative))
) {
origin.origin_path().await?.parent()
origin.into_trait_ref().await?.origin_path().parent()
} else {
get_traced_project_dir().await?
};
......@@ -2121,12 +2098,12 @@ where
return Ok(());
}
}
let origin_ref = origin.into_trait_ref().await?;
let origin = ResolvedVc::upcast(
PlainResolveOrigin::new(
origin.asset_context(),
origin
*origin_ref.asset_context(),
origin_ref
.origin_path()
.await?
.parent()
.join(rel.as_str())?
.join("_")?,
......@@ -2358,7 +2335,7 @@ where
)
}
WellKnownFunctionKind::PathResolve(..) if analysis.analyze_mode.is_tracing_assets() => {
let parent_path = origin.origin_path().owned().await?.parent();
let parent_path = origin.into_trait_ref().await?.origin_path().parent();
let args = linked_args().await?;
let linked_func_call = state
......@@ -2592,7 +2569,7 @@ where
}
analysis.add_reference(
NodePreGypConfigReference::new(
origin.origin_path().await?.parent(),
origin.into_trait_ref().await?.origin_path().parent(),
Pattern::new(pat),
compile_time_info.environment().compile_target(),
collect_affecting_sources,
......@@ -2625,8 +2602,9 @@ where
if let Some(s) = first_arg.as_str() {
// TODO this resolving should happen within Vc<NodeGypBuildReference>
let current_context = origin
.origin_path()
.into_trait_ref()
.await?
.origin_path()
.root()
.await?
.join(s.trim_start_matches("/ROOT/"))?;
......@@ -2664,7 +2642,7 @@ where
if let Some(s) = first_arg.as_str() {
analysis.add_reference(
NodeBindingsReference::new(
origin.origin_path().owned().await?,
origin.into_trait_ref().await?.origin_path(),
s.into(),
collect_affecting_sources,
)
......@@ -3131,7 +3109,7 @@ async fn handle_free_var_reference(
if let Some(lookup_path) = lookup_path {
ResolvedVc::upcast(
PlainResolveOrigin::new(
state.origin.asset_context(),
*state.origin.into_trait_ref().await?.asset_context(),
lookup_path.clone(),
)
.to_resolved()
......@@ -3155,6 +3133,7 @@ async fn handle_free_var_reference(
state.tree_shaking_mode,
None,
)
.await?
.resolved_cell())
})
.await?;
......@@ -3423,6 +3402,7 @@ async fn early_value_visitor(mut v: JsValue) -> Result<(JsValue, bool)> {
async fn value_visitor(
origin: Vc<Box<dyn ResolveOrigin>>,
origin_path: &FileSystemPath,
v: JsValue,
compile_time_info: Vc<CompileTimeInfo>,
compile_time_info_ref: &CompileTimeInfo,
......@@ -3432,6 +3412,7 @@ async fn value_visitor(
) -> Result<(JsValue, bool)> {
let (mut v, modified) = value_visitor_inner(
origin,
origin_path,
v,
compile_time_info,
compile_time_info_ref,
......@@ -3446,6 +3427,7 @@ async fn value_visitor(
async fn value_visitor_inner(
origin: Vc<Box<dyn ResolveOrigin>>,
origin_path: &FileSystemPath,
v: JsValue,
compile_time_info: Vc<CompileTimeInfo>,
compile_time_info_ref: &CompileTimeInfo,
......@@ -3486,7 +3468,7 @@ async fn value_visitor_inner(
) =>
{
let (_, args) = call.into_parts();
require_context_visitor(origin, args).await?
require_context_visitor(origin, origin_path, args).await?
}
JsValue::Call(_, ref call)
if matches!(
......@@ -3573,8 +3555,8 @@ async fn value_visitor_inner(
}
}
JsValue::FreeVar(ref kind) => match &**kind {
"__dirname" => as_abs_path(origin.origin_path().owned().await?.parent()).into(),
"__filename" => as_abs_path(origin.origin_path().owned().await?).into(),
"__dirname" => as_abs_path(origin_path.parent()).into(),
"__filename" => as_abs_path(origin_path.clone()).into(),
"require" => JsValue::unknown_if(
ignore,
......@@ -3684,6 +3666,7 @@ async fn require_resolve_visitor(
async fn require_context_visitor(
origin: Vc<Box<dyn ResolveOrigin>>,
origin_path: &FileSystemPath,
args: Vec<JsValue>,
) -> Result<JsValue> {
let options = match parse_require_context(&args) {
......@@ -3700,12 +3683,7 @@ async fn require_context_visitor(
}
};
let dir = origin
.origin_path()
.owned()
.await?
.parent()
.join(options.dir.as_str())?;
let dir = origin_path.parent().join(options.dir.as_str())?;
let map = RequireContextMap::generate(
origin,
......
......@@ -354,7 +354,7 @@ async fn to_single_pattern_mapping(
.into(),
)
.resolved_cell(),
path: origin.origin_path().owned().await?,
path: origin.into_trait_ref().await?.origin_path(),
source: None,
}
.resolved_cell()
......@@ -386,7 +386,7 @@ async fn to_single_pattern_mapping(
"asset is not placeable in ESM chunks, so it doesn't have a module id"
))
.resolved_cell(),
path: origin.origin_path().owned().await?,
path: origin.into_trait_ref().await?.origin_path(),
source: None,
}
.resolved_cell()
......
......@@ -186,7 +186,7 @@ impl RequireContextMap {
issue_source: Option<IssueSource>,
error_mode: ResolveErrorMode,
) -> Result<Vc<Self>> {
let origin_path = origin.origin_path().await?.parent();
let origin_path = origin.into_trait_ref().await?.origin_path().parent();
let list = &*FlatDirList::read(dir, recursive, filter).await?;
......@@ -260,7 +260,12 @@ impl RequireContextAssetReference {
) -> Result<Self> {
let map = RequireContextMap::generate(
*origin,
origin.origin_path().await?.parent().join(&dir)?,
origin
.into_trait_ref()
.await?
.origin_path()
.parent()
.join(&dir)?,
include_subdirs,
filter,
issue_source,
......
......@@ -71,16 +71,10 @@ impl TsReferencePathAssetReference {
impl ModuleReference for TsReferencePathAssetReference {
#[turbo_tasks::function]
async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
let origin = self.origin.into_trait_ref().await?;
Ok(
if let Some(path) = self
.origin
.origin_path()
.await?
.parent()
.try_join(&self.path)
{
let module = self
.origin
if let Some(path) = origin.origin_path().parent().try_join(&self.path) {
let module = origin
.asset_context()
.process(
Vc::upcast(FileSource::new(path.clone())),
......
......@@ -116,7 +116,8 @@ impl WorkerAssetReference {
impl ModuleReference for WorkerAssetReference {
#[turbo_tasks::function]
async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
let asset_context = self.origin.asset_context().to_resolved().await?;
let origin = self.origin.into_trait_ref().await?;
let asset_context = origin.asset_context();
let result = match (&self.worker_type, &self.request) {
(WorkerType::WebWorker | WorkerType::SharedWebWorker, WorkerRequest::Url(request)) => {
......@@ -151,9 +152,9 @@ impl ModuleReference for WorkerAssetReference {
handle_resolve_error(
result,
reference_type.clone(),
*self.origin,
origin.origin_path(),
Request::parse(path.owned().await?),
self.origin.resolve_options(),
origin.resolve_options(),
self.error_mode,
Some(self.issue_source),
)
......@@ -195,7 +196,7 @@ impl ModuleReference for WorkerAssetReference {
.await?,
)
.resolved_cell(),
path: self.origin.origin_path().owned().await?,
path: origin.origin_path(),
source: Some(self.issue_source),
}
.resolved_cell()
......@@ -224,7 +225,7 @@ impl ModuleReference for WorkerAssetReference {
.await?,
)
.resolved_cell(),
path: self.origin.origin_path().owned().await?,
path: origin.origin_path(),
source: Some(self.issue_source),
}
.resolved_cell()
......@@ -273,7 +274,13 @@ impl WorkerAssetReference {
async fn get_module_type_issue_severity(&self) -> Result<IssueSeverity> {
Ok(
if self.error_mode != ResolveErrorMode::Error
|| self.origin.resolve_options().await?.loose_errors
|| self
.origin
.into_trait_ref()
.await?
.resolve_options()
.await?
.loose_errors
{
IssueSeverity::Warning
} else {
......
......@@ -56,7 +56,7 @@ impl Module for TsConfigModuleAsset {
let configs = read_tsconfigs(
self.source.content().file_content(),
self.source,
apply_cjs_specific_options(self.origin.resolve_options()),
apply_cjs_specific_options(self.origin.into_trait_ref().await?.resolve_options()),
)
.await?;
references.extend(
......
......@@ -193,12 +193,13 @@ pub struct WebpackRuntimeAssetReference {
impl ModuleReference for WebpackRuntimeAssetReference {
#[turbo_tasks::function]
async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
let options = self.origin.resolve_options();
let origin = self.origin.into_trait_ref().await?;
let options = origin.resolve_options();
let options = apply_cjs_specific_options(options);
let resolved = resolve(
self.origin.origin_path().await?.parent(),
origin.origin_path().parent(),
ReferenceType::CommonJs(CommonJsReferenceSubType::Undefined),
*self.request,
options,
......
use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks::{ResolvedVc, TraitRef, Vc};
use turbopack_core::{
context::AssetContext,
issue::IssueSource,
reference_type::{CommonJsReferenceSubType, EcmaScriptModulesReferenceSubType, ReferenceType},
resolve::{
......@@ -11,7 +12,7 @@ use turbopack_core::{
ConditionValue, ResolutionConditions, ResolveInPackage, ResolveIntoPackage,
ResolveOptions,
},
origin::{ResolveOrigin, ResolveOriginExt},
origin::ResolveOrigin,
parse::Request,
resolve,
},
......@@ -101,10 +102,11 @@ pub async fn esm_resolve(
issue_source: Option<IssueSource>,
) -> Result<Vc<ModuleResolveResult>> {
let ty = ReferenceType::EcmaScriptModules(ty);
let options = *apply_esm_specific_options(origin.resolve_options(), &ty)
let origin_ref = origin.into_trait_ref().await?;
let options = *apply_esm_specific_options(origin_ref.resolve_options(), &ty)
.to_resolved()
.await?;
specific_resolve(origin, request, options, ty, error_mode, issue_source).await
specific_resolve(origin_ref, request, options, ty, error_mode, issue_source).await
}
#[turbo_tasks::function]
......@@ -116,10 +118,11 @@ pub async fn cjs_resolve(
error_mode: ResolveErrorMode,
) -> Result<Vc<ModuleResolveResult>> {
let ty = ReferenceType::CommonJs(ty);
let options = *apply_cjs_specific_options(origin.resolve_options())
let origin_ref = origin.into_trait_ref().await?;
let options = *apply_cjs_specific_options(origin_ref.resolve_options())
.to_resolved()
.await?;
specific_resolve(origin, request, options, ty, error_mode, issue_source).await
specific_resolve(origin_ref, request, options, ty, error_mode, issue_source).await
}
#[turbo_tasks::function]
......@@ -131,20 +134,17 @@ pub async fn cjs_resolve_source(
error_mode: ResolveErrorMode,
) -> Result<Vc<ResolveResult>> {
let ty = ReferenceType::CommonJs(ty);
let options = *apply_cjs_specific_options(origin.resolve_options())
let origin_ref = origin.into_trait_ref().await?;
let options = *apply_cjs_specific_options(origin_ref.resolve_options())
.to_resolved()
.await?;
let result = resolve(
origin.origin_path().await?.parent(),
ty.clone(),
*request,
options,
);
let origin_path = origin_ref.origin_path();
let result = resolve(origin_path.parent(), ty.clone(), *request, options);
handle_resolve_source_error(
result,
ty,
*origin,
origin_path,
*request,
options,
error_mode,
......@@ -154,21 +154,24 @@ pub async fn cjs_resolve_source(
}
async fn specific_resolve(
origin: Vc<Box<dyn ResolveOrigin>>,
origin: TraitRef<Box<dyn ResolveOrigin>>,
request: Vc<Request>,
options: Vc<ResolveOptions>,
reference_type: ReferenceType,
error_mode: ResolveErrorMode,
issue_source: Option<IssueSource>,
) -> Result<Vc<ModuleResolveResult>> {
let result = origin
.resolve_asset(request, options, reference_type.clone())
.await?;
let result = origin.asset_context().resolve_asset(
origin.origin_path(),
request,
options,
reference_type.clone(),
);
handle_resolve_error(
result,
reference_type,
origin,
origin.origin_path(),
request,
options,
error_mode,
......
......@@ -394,8 +394,9 @@ pub async fn type_resolve(
request: Vc<Request>,
) -> Result<Vc<ModuleResolveResult>> {
let ty = ReferenceType::TypeScript(TypeScriptReferenceSubType::Undefined);
let context_path = origin.origin_path().await?.parent();
let options = origin.resolve_options();
let origin_ref = origin.into_trait_ref().await?;
let context_path = origin_ref.origin_path().parent();
let options = origin_ref.resolve_options();
let options = apply_typescript_types_options(options);
let types_request = if let Request::Module {
module: m,
......@@ -446,14 +447,14 @@ pub async fn type_resolve(
)
};
let result = as_typings_result(
origin
origin_ref
.asset_context()
.process_resolve_result(result, ty.clone()),
);
handle_resolve_error(
result,
ty,
origin,
origin_ref.origin_path(),
request,
options,
ResolveErrorMode::Error,
......
......@@ -36,19 +36,22 @@ use crate::{
pub struct WebAssemblyModuleAsset {
source: ResolvedVc<WebAssemblySource>,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
/// The path of `source`, precomputed so that `ResolveOrigin::origin_path` is synchronous.
origin_path: FileSystemPath,
}
#[turbo_tasks::value_impl]
impl WebAssemblyModuleAsset {
#[turbo_tasks::function]
pub fn new(
pub async fn new(
source: ResolvedVc<WebAssemblySource>,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
) -> Vc<Self> {
Self::cell(WebAssemblyModuleAsset {
) -> Result<Vc<Self>> {
Ok(Self::cell(WebAssemblyModuleAsset {
origin_path: source.ident().await?.path.clone(),
source,
asset_context,
})
}))
}
#[turbo_tasks::function]
......@@ -209,13 +212,11 @@ impl EcmascriptChunkPlaceable for WebAssemblyModuleAsset {
#[turbo_tasks::value_impl]
impl ResolveOrigin for WebAssemblyModuleAsset {
#[turbo_tasks::function]
async fn origin_path(&self) -> Result<Vc<FileSystemPath>> {
Ok(self.source.ident().await?.path.clone().cell())
fn origin_path(&self) -> FileSystemPath {
self.origin_path.clone()
}
#[turbo_tasks::function]
fn asset_context(&self) -> Vc<Box<dyn AssetContext>> {
*self.asset_context
fn asset_context(&self) -> ResolvedVc<Box<dyn AssetContext>> {
self.asset_context
}
}
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