Unverified Commit 4e110ef3 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[turbopack] Eliminate many calls to `into` and from and cell involving RcStr (#80076)

Adopt the `rcstr!` macro in turbopack

Instead of `"foo".into()` call `rcstr!("foo")` while being slightly more annoying to type the macro approach is more readabie and faster as it can leverage constant folding for small strings and amortize construction of larger strings.  In general these performance improvement are very small but consistent.

At the same time, eliminate uses of turbo-tasks where they were amortizing construction of RcStr instances since the `rcstr!` macro can do the same thing.  Generally speaking we should prefer `RcStr` over `ResolvedVc<RcStr>` as a task input since it has much more reasonable equality semantics and observationally many of these values were constructed via `Vc::cell("foo".into())`.

## Why?

Generally this should be a small consistent memory and performance improvement.  My understanding is that many uses of `ResolvedVc<RcStr>` actually predate `RcStr` when we were using `String` directly.  In that world, turbotasks are fulfilling a vital function, but now that we can rely on RcStr this is much less needed.

## How?

Mostly this was a bunch of regex replacements and manual fixups.  An AstGrep rule would have been ideal but beyond matching `RcStr::from("...")` this doesn't work since it was mostly calls to `into()` which rely on type inference.  Still by seeding the codebase with the pattern we can probably prevent regressions.

## Performance

From measuring vercel-site this is a latency progression of a few percent.  codspeed agrees!

![image.png](https://graphite-user-uploaded-assets-prod.s3.amazonaws.com/AwJ29EfoPcPdLSwCZxAz/c08ffcaa-2856-4742-a049-1306491d69ba.png)
parent b981ac58
......@@ -10180,6 +10180,7 @@ dependencies = [
"rustc-hash 2.1.1",
"serde",
"serde_with",
"turbo-rcstr",
"turbo-tasks",
"turbo-tasks-build",
"turbo-tasks-fs",
......
......@@ -28,7 +28,7 @@ use serde::{Deserialize, Serialize};
use tokio::{io::AsyncWriteExt, time::Instant};
use tracing::Instrument;
use tracing_subscriber::{Registry, layer::SubscriberExt, util::SubscriberInitExt};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
Completion, Effects, FxIndexSet, NonLocalValue, OperationValue, OperationVc, ReadRef,
ResolvedVc, TaskInput, TransientInstance, TryJoinIterExt, UpdateInfo, Vc, get_effects,
......@@ -426,7 +426,7 @@ pub async fn project_new(
let options: ProjectOptions = options.into();
let container = turbo_tasks
.run_once(async move {
let project = ProjectContainer::new("next.js".into(), options.dev);
let project = ProjectContainer::new(rcstr!("next.js"), options.dev);
let project = project.to_resolved().await?;
project.initialize(options).await?;
Ok(project)
......
This diff is collapsed.
......@@ -6,7 +6,7 @@ use next_core::{
next_server::{ServerContextType, get_server_runtime_entries},
};
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Completion, ResolvedVc, Value, Vc};
use turbo_tasks_fs::{File, FileContent, FileSystemPath};
use turbopack_core::{
......@@ -44,7 +44,7 @@ pub struct InstrumentationEndpoint {
is_edge: bool,
app_dir: Option<ResolvedVc<FileSystemPath>>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>,
ecmascript_client_reference_transition_name: Option<RcStr>,
}
#[turbo_tasks::value_impl]
......@@ -56,7 +56,7 @@ impl InstrumentationEndpoint {
source: ResolvedVc<Box<dyn Source>>,
is_edge: bool,
app_dir: Option<ResolvedVc<FileSystemPath>>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>,
ecmascript_client_reference_transition_name: Option<RcStr>,
) -> Vc<Self> {
Self {
project,
......@@ -85,7 +85,7 @@ impl InstrumentationEndpoint {
*self.asset_context,
self.project.project_path(),
*userland_module,
"instrumentation".into(),
rcstr!("instrumentation"),
)
.to_resolved()
.await?;
......@@ -108,7 +108,8 @@ impl InstrumentationEndpoint {
Value::new(ServerContextType::Instrumentation {
app_dir: this.app_dir,
ecmascript_client_reference_transition_name: this
.ecmascript_client_reference_transition_name,
.ecmascript_client_reference_transition_name
.clone(),
}),
this.project.next_mode(),
)
......@@ -147,12 +148,13 @@ impl InstrumentationEndpoint {
.entry_chunk_group(
this.project
.node_root()
.join("server/instrumentation.js".into()),
.join(rcstr!("server/instrumentation.js")),
get_server_runtime_entries(
Value::new(ServerContextType::Instrumentation {
app_dir: this.app_dir,
ecmascript_client_reference_transition_name: this
.ecmascript_client_reference_transition_name,
.ecmascript_client_reference_transition_name
.clone(),
}),
this.project.next_mode(),
)
......@@ -188,7 +190,7 @@ impl InstrumentationEndpoint {
let instrumentation_definition = InstrumentationDefinition {
files: file_paths_from_root,
wasm: wasm_paths_to_bindings(wasm_paths_from_root).await?,
name: "instrumentation".into(),
name: rcstr!("instrumentation"),
..Default::default()
};
let middleware_manifest_v2 = MiddlewaresManifestV2 {
......@@ -196,7 +198,7 @@ impl InstrumentationEndpoint {
..Default::default()
};
let middleware_manifest_v2 = VirtualOutputAsset::new(
node_root.join("server/instrumentation/middleware-manifest.json".into()),
node_root.join(rcstr!("server/instrumentation/middleware-manifest.json")),
AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty(
&middleware_manifest_v2,
......
......@@ -10,7 +10,7 @@ use next_core::{
util::{MiddlewareMatcherKind, NextRuntime, parse_config_from_source},
};
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Completion, ResolvedVc, Value, Vc};
use turbo_tasks_fs::{self, File, FileContent, FileSystemPath};
use turbopack_core::{
......@@ -47,7 +47,7 @@ pub struct MiddlewareEndpoint {
asset_context: ResolvedVc<Box<dyn AssetContext>>,
source: ResolvedVc<Box<dyn Source>>,
app_dir: Option<ResolvedVc<FileSystemPath>>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>,
ecmascript_client_reference_transition_name: Option<RcStr>,
}
#[turbo_tasks::value_impl]
......@@ -58,7 +58,7 @@ impl MiddlewareEndpoint {
asset_context: ResolvedVc<Box<dyn AssetContext>>,
source: ResolvedVc<Box<dyn Source>>,
app_dir: Option<ResolvedVc<FileSystemPath>>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>,
ecmascript_client_reference_transition_name: Option<RcStr>,
) -> Vc<Self> {
Self {
project,
......@@ -95,7 +95,7 @@ impl MiddlewareEndpoint {
*self.asset_context,
self.project.project_path(),
module,
"middleware".into(),
rcstr!("middleware"),
))
}
......@@ -110,7 +110,8 @@ impl MiddlewareEndpoint {
Value::new(ServerContextType::Middleware {
app_dir: this.app_dir,
ecmascript_client_reference_transition_name: this
.ecmascript_client_reference_transition_name,
.ecmascript_client_reference_transition_name
.clone(),
}),
this.project.next_mode(),
)
......@@ -146,12 +147,15 @@ impl MiddlewareEndpoint {
let EntryChunkGroupResult { asset: chunk, .. } = *chunking_context
.entry_chunk_group(
this.project.node_root().join("server/middleware.js".into()),
this.project
.node_root()
.join(rcstr!("server/middleware.js")),
get_server_runtime_entries(
Value::new(ServerContextType::Middleware {
app_dir: this.app_dir,
ecmascript_client_reference_transition_name: this
.ecmascript_client_reference_transition_name,
.ecmascript_client_reference_transition_name
.clone(),
}),
this.project.next_mode(),
)
......@@ -233,8 +237,8 @@ impl MiddlewareEndpoint {
.collect()
} else {
vec![MiddlewareMatcher {
regexp: Some("^/.*$".into()),
original_source: "/:path*".into(),
regexp: Some(rcstr!("^/.*$")),
original_source: rcstr!("/:path*"),
..Default::default()
}]
};
......@@ -256,7 +260,7 @@ impl MiddlewareEndpoint {
let middleware_manifest_v2 = VirtualOutputAsset::new(
this.project
.node_root()
.join("server/middleware/middleware-manifest.json".into()),
.join(rcstr!("server/middleware/middleware-manifest.json")),
AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty(
&middleware_manifest_v2,
......@@ -303,20 +307,20 @@ impl MiddlewareEndpoint {
files: file_paths_from_root,
wasm: wasm_paths_to_bindings(wasm_paths_from_root).await?,
assets: paths_to_bindings(all_assets),
name: "middleware".into(),
page: "/".into(),
name: rcstr!("middleware"),
page: rcstr!("/"),
regions,
matchers: matchers.clone(),
env: this.project.edge_env().owned().await?,
};
let middleware_manifest_v2 = MiddlewaresManifestV2 {
middleware: [("/".into(), edge_function_definition)]
middleware: [(rcstr!("/"), edge_function_definition)]
.into_iter()
.collect(),
..Default::default()
};
let middleware_manifest_v2 = VirtualOutputAsset::new(
node_root.join("server/middleware/middleware-manifest.json".into()),
node_root.join(rcstr!("server/middleware/middleware-manifest.json")),
AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty(
&middleware_manifest_v2,
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -119,7 +119,7 @@ impl HmrEntryModuleReference {
impl ValueToString for HmrEntryModuleReference {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
Vc::cell("entry".into())
Vc::cell(rcstr!("entry"))
}
}
......
use std::iter::once;
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, OptionVcExt, ResolvedVc, Value, Vc};
use turbo_tasks_env::EnvMap;
use turbo_tasks_fs::FileSystemPath;
......@@ -102,14 +102,14 @@ async fn next_client_free_vars(define_env: Vc<EnvMap>) -> Result<Vc<FreeVarRefer
Ok(free_var_references!(
..defines(&*define_env.await?).into_iter(),
Buffer = FreeVarReference::EcmaScriptModule {
request: "node:buffer".into(),
request: rcstr!("node:buffer"),
lookup_path: None,
export: Some("Buffer".into()),
export: Some(rcstr!("Buffer")),
},
process = FreeVarReference::EcmaScriptModule {
request: "node:process".into(),
request: rcstr!("node:process"),
lookup_path: None,
export: Some("default".into()),
export: Some(rcstr!("default")),
}
)
.cell())
......@@ -265,7 +265,7 @@ pub async fn get_client_module_options_context(
// foreign_code_context_condition. This allows to import codes from
// node_modules that requires webpack loaders, which next-dev implicitly
// does by default.
let conditions = vec!["browser".into(), mode.await?.condition().into()];
let conditions = vec![rcstr!("browser"), mode.await?.condition().into()];
let foreign_enable_webpack_loaders = webpack_loader_options(
project_path,
next_config,
......@@ -273,7 +273,7 @@ pub async fn get_client_module_options_context(
conditions
.iter()
.cloned()
.chain(once("foreign".into()))
.chain(once(rcstr!("foreign")))
.collect(),
)
.await?;
......@@ -425,9 +425,9 @@ pub async fn get_client_module_options_context(
pub async fn get_client_chunking_context(
root_path: ResolvedVc<FileSystemPath>,
client_root: ResolvedVc<FileSystemPath>,
client_root_to_root_path: ResolvedVc<RcStr>,
asset_prefix: ResolvedVc<Option<RcStr>>,
chunk_suffix_path: ResolvedVc<Option<RcStr>>,
client_root_to_root_path: RcStr,
asset_prefix: Option<RcStr>,
chunk_suffix_path: Option<RcStr>,
environment: ResolvedVc<Environment>,
mode: Vc<NextMode>,
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
......@@ -442,14 +442,14 @@ pub async fn get_client_chunking_context(
client_root_to_root_path,
client_root,
client_root
.join("static/chunks".into())
.join(rcstr!("static/chunks"))
.to_resolved()
.await?,
get_client_assets_path(*client_root).to_resolved().await?,
environment,
next_mode.runtime_type(),
)
.chunk_base_path(asset_prefix)
.chunk_base_path(asset_prefix.clone())
.chunk_suffix_path(chunk_suffix_path)
.minify_type(if *minify.await? {
MinifyType::Minify {
......@@ -494,7 +494,7 @@ pub async fn get_client_chunking_context(
#[turbo_tasks::function]
pub fn get_client_assets_path(client_root: Vc<FileSystemPath>) -> Vc<FileSystemPath> {
client_root.join("static/media".into())
client_root.join(rcstr!("static/media"))
}
#[turbo_tasks::function]
......@@ -522,7 +522,7 @@ pub async fn get_client_runtime_entries(
runtime_entries.push(
RuntimeEntry::Request(
request.to_resolved().await?,
project_root.join("_".into()).to_resolved().await?,
project_root.join(rcstr!("_")).to_resolved().await?,
)
.resolved_cell(),
)
......@@ -532,12 +532,12 @@ pub async fn get_client_runtime_entries(
if matches!(*ty, ClientContextType::App { .. },) {
runtime_entries.push(
RuntimeEntry::Request(
Request::parse(Value::new(Pattern::Constant(
"next/dist/client/app-next-turbopack.js".into(),
)))
Request::parse(Value::new(Pattern::Constant(rcstr!(
"next/dist/client/app-next-turbopack.js"
))))
.to_resolved()
.await?,
project_root.join("_".into()).to_resolved().await?,
project_root.join(rcstr!("_")).to_resolved().await?,
)
.resolved_cell(),
);
......
......@@ -80,7 +80,7 @@ impl ChunkableModuleReference for CssClientReference {
fn chunking_type(&self) -> Vc<ChunkingTypeOption> {
Vc::cell(Some(ChunkingType::Isolated {
_ty: ChunkGroupType::Evaluated,
merge_tag: Some("client".into()),
merge_tag: Some(rcstr!("client")),
}))
}
}
......@@ -97,6 +97,6 @@ impl ModuleReference for CssClientReference {
impl ValueToString for CssClientReference {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
Vc::cell("css client reference to client".into())
Vc::cell(rcstr!("css client reference to client"))
}
}
......@@ -176,16 +176,6 @@ impl EcmascriptClientReferenceModule {
}
}
#[turbo_tasks::function]
fn ecmascript_client_reference_client_ref_modifier() -> Vc<RcStr> {
Vc::cell("ecmascript client reference to client".into())
}
#[turbo_tasks::function]
fn ecmascript_client_reference_ssr_ref_modifier() -> Vc<RcStr> {
Vc::cell("ecmascript client reference to ssr".into())
}
pub fn ecmascript_client_reference_merge_tag() -> RcStr {
rcstr!("client")
}
......@@ -222,7 +212,7 @@ impl Module for EcmascriptClientReferenceModule {
*ResolvedVc::upcast(*client_module),
ChunkGroupType::Evaluated,
Some(ecmascript_client_reference_merge_tag()),
ecmascript_client_reference_client_ref_modifier(),
rcstr!("ecmascript client reference to client"),
)
.to_resolved()
.await?,
......@@ -232,7 +222,7 @@ impl Module for EcmascriptClientReferenceModule {
*ResolvedVc::upcast(*ssr_module),
ChunkGroupType::Entry,
Some(ecmascript_client_reference_merge_tag_ssr()),
ecmascript_client_reference_ssr_ref_modifier(),
rcstr!("ecmascript client reference to ssr"),
)
.to_resolved()
.await?,
......@@ -298,11 +288,6 @@ struct EcmascriptClientReferenceProxyChunkItem {
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
}
#[turbo_tasks::function]
fn client_reference_description() -> Vc<RcStr> {
Vc::cell("client references".into())
}
#[turbo_tasks::value_impl]
impl ChunkItem for EcmascriptClientReferenceProxyChunkItem {
#[turbo_tasks::function]
......@@ -348,7 +333,7 @@ pub(crate) struct EcmascriptClientReference {
module: ResolvedVc<Box<dyn Module>>,
ty: ChunkGroupType,
merge_tag: Option<RcStr>,
description: ResolvedVc<RcStr>,
description: RcStr,
}
#[turbo_tasks::value_impl]
......@@ -358,7 +343,7 @@ impl EcmascriptClientReference {
module: ResolvedVc<Box<dyn Module>>,
ty: ChunkGroupType,
merge_tag: Option<RcStr>,
description: ResolvedVc<RcStr>,
description: RcStr,
) -> Vc<Self> {
Self::cell(EcmascriptClientReference {
module,
......@@ -392,6 +377,6 @@ impl ModuleReference for EcmascriptClientReference {
impl ValueToString for EcmascriptClientReference {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
*self.description
Vc::cell(self.description.clone())
}
}
......@@ -3,7 +3,7 @@ use rustc_hash::FxHashSet;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value as JsonValue;
use turbo_esregex::EsRegex;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
FxIndexMap, NonLocalValue, OperationValue, ResolvedVc, TaskInput, Vc, debug::ValueDebugFormat,
trace::TraceRawVcs,
......@@ -1655,7 +1655,7 @@ impl Issue for OutdatedConfigIssue {
fn title(&self) -> Vc<StyledString> {
StyledString::Line(vec![
StyledString::Code(self.old_name.clone()),
StyledString::Text(" has been replaced by ".into()),
StyledString::Text(rcstr!(" has been replaced by ")),
StyledString::Code(self.new_name.clone()),
])
.cell()
......
......@@ -37,9 +37,8 @@ impl NextDynamicEntryModule {
}
}
#[turbo_tasks::function]
fn dynamic_ref_description() -> Vc<RcStr> {
Vc::cell("next/dynamic reference".into())
fn dynamic_ref_description() -> RcStr {
rcstr!("next/dynamic reference")
}
#[turbo_tasks::value_impl]
......@@ -105,9 +104,10 @@ impl EcmascriptChunkPlaceable for NextDynamicEntryModule {
);
let mut exports = BTreeMap::new();
let default = rcstr!("default");
exports.insert(
"default".into(),
EsmExport::ImportedBinding(module_reference, "default".into(), false),
default.clone(),
EsmExport::ImportedBinding(module_reference, default, false),
);
Ok(EcmascriptExports::EsmExports(
......
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, OptionVcExt, ResolvedVc, Value, Vc};
use turbo_tasks_env::EnvMap;
use turbo_tasks_fs::FileSystemPath;
......@@ -71,9 +71,9 @@ async fn next_edge_free_vars(
Ok(free_var_references!(
..defines(&*define_env.await?).into_iter(),
Buffer = FreeVarReference::EcmaScriptModule {
request: "buffer".into(),
request: rcstr!("buffer"),
lookup_path: Some(project_path),
export: Some("Buffer".into()),
export: Some(rcstr!("Buffer")),
},
)
.cell())
......@@ -109,10 +109,15 @@ pub async fn get_edge_resolve_options_context(
next_config: Vc<NextConfig>,
execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ResolveOptionsContext>> {
let next_edge_import_map =
get_next_edge_import_map(*project_path, ty, next_config, mode, execution_context)
.to_resolved()
.await?;
let next_edge_import_map = get_next_edge_import_map(
*project_path,
ty.clone(),
next_config,
mode,
execution_context,
)
.to_resolved()
.await?;
let ty: ServerContextType = ty.into_value();
......@@ -171,7 +176,7 @@ pub async fn get_edge_resolve_options_context(
);
if ty.supports_react_server() {
custom_conditions.push("react-server".into());
custom_conditions.push(rcstr!("react-server"));
};
let resolve_options_context = ResolveOptionsContext {
......@@ -214,25 +219,25 @@ pub async fn get_edge_chunking_context_with_client_assets(
mode: Vc<NextMode>,
root_path: ResolvedVc<FileSystemPath>,
node_root: ResolvedVc<FileSystemPath>,
output_root_to_root_path: ResolvedVc<RcStr>,
output_root_to_root_path: RcStr,
client_root: ResolvedVc<FileSystemPath>,
asset_prefix: ResolvedVc<Option<RcStr>>,
asset_prefix: Option<RcStr>,
environment: ResolvedVc<Environment>,
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
turbo_minify: Vc<bool>,
turbo_source_maps: Vc<bool>,
no_mangling: Vc<bool>,
) -> Result<Vc<Box<dyn ChunkingContext>>> {
let output_root = node_root.join("server/edge".into()).to_resolved().await?;
let output_root = node_root.join(rcstr!("server/edge")).to_resolved().await?;
let next_mode = mode.await?;
let mut builder = BrowserChunkingContext::builder(
root_path,
output_root,
output_root_to_root_path,
client_root,
output_root.join("chunks/ssr".into()).to_resolved().await?,
output_root.join(rcstr!("chunks/ssr")).to_resolved().await?,
client_root
.join("static/media".into())
.join(rcstr!("static/media"))
.to_resolved()
.await?,
environment,
......@@ -279,22 +284,22 @@ pub async fn get_edge_chunking_context(
mode: Vc<NextMode>,
root_path: ResolvedVc<FileSystemPath>,
node_root: ResolvedVc<FileSystemPath>,
node_root_to_root_path: ResolvedVc<RcStr>,
node_root_to_root_path: RcStr,
environment: ResolvedVc<Environment>,
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
turbo_minify: Vc<bool>,
turbo_source_maps: Vc<bool>,
no_mangling: Vc<bool>,
) -> Result<Vc<Box<dyn ChunkingContext>>> {
let output_root = node_root.join("server/edge".into()).to_resolved().await?;
let output_root = node_root.join(rcstr!("server/edge")).to_resolved().await?;
let next_mode = mode.await?;
let mut builder = BrowserChunkingContext::builder(
root_path,
output_root,
node_root_to_root_path,
output_root,
output_root.join("chunks".into()).to_resolved().await?,
output_root.join("assets".into()).to_resolved().await?,
output_root.join(rcstr!("chunks")).to_resolved().await?,
output_root.join(rcstr!("assets")).to_resolved().await?,
environment,
next_mode.runtime_type(),
)
......@@ -302,7 +307,7 @@ pub async fn get_edge_chunking_context(
// instead. This special blob url is handled by the custom fetch
// implementation in the edge sandbox. It will respond with the
// asset from the output directory.
.asset_base_path(ResolvedVc::cell(Some("blob:server/edge/".into())))
.asset_base_path(Some(rcstr!("blob:server/edge/")))
.minify_type(if *turbo_minify.await? {
MinifyType::Minify {
mangle: (!*no_mangling.await?).then_some(MangleType::OptimalSize),
......
use anyhow::Result;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, trace::TraceRawVcs};
pub(crate) struct DefaultFallbackFont {
......@@ -14,16 +14,16 @@ pub(crate) struct DefaultFallbackFont {
// From https://github.com/vercel/next.js/blob/a3893bf69c83fb08e88c87bf8a21d987a0448c8e/packages/font/src/utils.ts#L4
pub(crate) static DEFAULT_SANS_SERIF_FONT: Lazy<DefaultFallbackFont> =
Lazy::new(|| DefaultFallbackFont {
name: "Arial".into(),
capsize_key: "arial".into(),
name: rcstr!("Arial"),
capsize_key: rcstr!("arial"),
az_avg_width: 934.5116279069767,
units_per_em: 2048,
});
pub(crate) static DEFAULT_SERIF_FONT: Lazy<DefaultFallbackFont> =
Lazy::new(|| DefaultFallbackFont {
name: "Times New Roman".into(),
capsize_key: "timesNewRoman".into(),
name: rcstr!("Times New Roman"),
capsize_key: rcstr!("timesNewRoman"),
az_avg_width: 854.3953488372093,
units_per_em: 2048,
});
......@@ -32,9 +32,9 @@ pub(crate) static DEFAULT_SERIF_FONT: Lazy<DefaultFallbackFont> =
#[turbo_tasks::value(shared)]
pub(crate) struct AutomaticFontFallback {
/// e.g. `__Roboto_Fallback_c123b8`
pub scoped_font_family: ResolvedVc<RcStr>,
pub scoped_font_family: RcStr,
/// The name of font locally, used in `src: local("{}")`
pub local_font_family: ResolvedVc<RcStr>,
pub local_font_family: RcStr,
pub adjustment: Option<FontAdjustment>,
}
......
......@@ -3,7 +3,7 @@ use once_cell::sync::Lazy;
use regex::Regex;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, trace::TraceRawVcs};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::issue::{IssueExt, IssueSeverity, StyledString};
......@@ -53,7 +53,7 @@ pub(super) async fn get_font_fallback(
None => {
let metrics_json = load_next_js_templateon(
lookup_path,
"dist/server/capsize-font-metrics.json".into(),
rcstr!("dist/server/capsize-font-metrics.json"),
)
.await?;
let fallback = lookup_fallback(
......@@ -65,12 +65,10 @@ pub(super) async fn get_font_fallback(
match fallback {
Ok(fallback) => FontFallback::Automatic(AutomaticFontFallback {
scoped_font_family: get_scoped_font_family(
FontFamilyType::Fallback.cell(),
options_vc.font_family(),
)
.to_resolved()
.await?,
local_font_family: ResolvedVc::cell(fallback.font_family),
FontFamilyType::Fallback,
options_vc.font_family().await?,
),
local_font_family: fallback.font_family,
adjustment: fallback.adjustment,
})
.cell(),
......@@ -85,9 +83,9 @@ pub(super) async fn get_font_fallback(
.into(),
)
.resolved_cell(),
description: StyledString::Text(
"Skipping generating a fallback font.".into(),
)
description: StyledString::Text(rcstr!(
"Skipping generating a fallback font."
))
.resolved_cell(),
severity: IssueSeverity::Warning.resolved_cell(),
}
......@@ -172,6 +170,7 @@ fn lookup_fallback(
#[cfg(test)]
mod tests {
use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks_fs::json::parse_json_with_source_context;
use super::{FontAdjustment, FontMetricsMap};
......@@ -211,7 +210,7 @@ mod tests {
assert_eq!(
lookup_fallback("Inter", font_metrics, true)?,
Fallback {
font_family: "Arial".into(),
font_family: rcstr!("Arial"),
adjustment: Some(FontAdjustment {
ascent: 0.901_989_700_374_532,
descent: -0.224_836_142_322_097_4,
......@@ -257,7 +256,7 @@ mod tests {
assert_eq!(
lookup_fallback("Roboto Slab", font_metrics, true)?,
Fallback {
font_family: "Times New Roman".into(),
font_family: rcstr!("Times New Roman"),
adjustment: Some(FontAdjustment {
ascent: 0.885_645_438_273_993_8,
descent: -0.229_046_234_036_377_7,
......
......@@ -5,7 +5,7 @@ use futures::FutureExt;
use indoc::formatdoc;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Completion, FxIndexMap, ResolvedVc, Value, Vc};
use turbo_tasks_bytes::stream::SingleValue;
use turbo_tasks_env::{CommandLineProcessEnv, ProcessEnv};
......@@ -96,8 +96,8 @@ impl NextFontGoogleReplacer {
let fallback = get_font_fallback(*self.project_path, options);
let properties = get_font_css_properties(options, fallback).await?;
let js_asset = VirtualSource::new(
next_js_file_path("internal/font/google".into())
.join(format!("{}.js", get_request_id(options.font_family(), request_hash).await?).into()),
next_js_file_path(rcstr!("internal/font/google"))
.join(format!("{}.js", get_request_id(options.font_family().await?, request_hash)).into()),
AssetContent::file(FileContent::Content(
formatdoc!(
r#"
......@@ -203,28 +203,28 @@ impl NextFontGoogleCssModuleReplacer {
let request_hash = get_request_hash(&query);
let font_data = load_font_data(*self.project_path);
let options = font_options_from_query_map(query, font_data);
let stylesheet_url = get_stylesheet_url_from_options(options, font_data);
let stylesheet_url = get_stylesheet_url_from_options(options, font_data)
.owned()
.await?;
let font_family = options.font_family().await?;
let scoped_font_family =
get_scoped_font_family(FontFamilyType::WebFont.cell(), options.font_family());
let css_virtual_path = next_js_file_path("internal/font/google".into()).join(
format!(
"/{}.module.css",
get_request_id(options.font_family(), request_hash).await?
)
.into(),
);
get_scoped_font_family(FontFamilyType::WebFont, font_family.clone());
let css_virtual_path = next_js_file_path(rcstr!("internal/font/google"))
.join(format!("/{}.module.css", get_request_id(font_family, request_hash)).into());
// When running Next.js integration tests, use the mock data available in
// process.env.NEXT_FONT_GOOGLE_MOCKED_RESPONSES instead of making real
// requests to Google Fonts.
let env = Vc::upcast::<Box<dyn ProcessEnv>>(CommandLineProcessEnv::new());
let mocked_responses_path = &*env.read("NEXT_FONT_GOOGLE_MOCKED_RESPONSES".into()).await?;
let mocked_responses_path = &*env
.read(rcstr!("NEXT_FONT_GOOGLE_MOCKED_RESPONSES"))
.await?;
let stylesheet_str = mocked_responses_path
.as_ref()
.map_or_else(
|| fetch_real_stylesheet(stylesheet_url, css_virtual_path).boxed(),
|p| get_mock_stylesheet(stylesheet_url, p, *self.execution_context).boxed(),
|| fetch_real_stylesheet(stylesheet_url.clone(), css_virtual_path).boxed(),
|p| get_mock_stylesheet(stylesheet_url.clone(), p, *self.execution_context).boxed(),
)
.await?;
......@@ -416,12 +416,11 @@ impl ImportMappingReplacement for NextFontGoogleFontFileReplacer {
}
let font_virtual_path =
next_js_file_path("internal/font/google".into()).join(format!("/{name}.{ext}").into());
next_js_file_path(rcstr!("internal/font/google")).join(format!("/{name}.{ext}").into());
// doesn't seem ideal to download the font into a string, but probably doesn't
// really matter either.
let Some(font) = fetch_from_google_fonts(Vc::cell(url.into()), font_virtual_path).await?
else {
let Some(font) = fetch_from_google_fonts(url.into(), font_virtual_path).await? else {
return Ok(ImportMapResult::Result(ResolveResult::unresolvable()).cell());
};
......@@ -440,7 +439,7 @@ impl ImportMappingReplacement for NextFontGoogleFontFileReplacer {
async fn load_font_data(project_root: ResolvedVc<FileSystemPath>) -> Result<Vc<FontData>> {
let data: FontData = load_next_js_templateon(
project_root,
"dist/compiled/@next/font/dist/google/font-data.json".into(),
rcstr!("dist/compiled/@next/font/dist/google/font-data.json"),
)
.await?;
......@@ -453,7 +452,7 @@ async fn load_font_data(project_root: ResolvedVc<FileSystemPath>) -> Result<Vc<F
async fn update_google_stylesheet(
stylesheet: Vc<RcStr>,
options: Vc<NextFontGoogleOptions>,
scoped_font_family: Vc<RcStr>,
scoped_font_family: RcStr,
has_size_adjust: Vc<bool>,
) -> Result<Vc<RcStr>> {
let options = &*options.await?;
......@@ -462,7 +461,7 @@ async fn update_google_stylesheet(
// TODO: Do this more resiliently, e.g. transforming an swc ast
let mut stylesheet = stylesheet.await?.replace(
&format!("font-family: '{}';", &options.font_family),
&format!("font-family: '{}';", &*scoped_font_family.await?),
&format!("font-family: '{scoped_font_family}';"),
);
let font_files = find_font_files_in_css(
......@@ -541,7 +540,7 @@ async fn get_stylesheet_url_from_options(
use turbo_tasks_env::{CommandLineProcessEnv, ProcessEnv};
let env = CommandLineProcessEnv::new();
if let Some(url) = &*env.read("TURBOPACK_TEST_ONLY_MOCK_SERVER".into()).await? {
if let Some(url) = &*env.read(rcstr!("TURBOPACK_TEST_ONLY_MOCK_SERVER")).await? {
css_url = Some(format!("{url}/css2"));
}
}
......@@ -571,7 +570,7 @@ async fn get_font_css_properties(
) -> Result<Vc<FontCssProperties>> {
let options = &*options_vc.await?;
let scoped_font_family =
&*get_scoped_font_family(FontFamilyType::WebFont.cell(), options_vc.font_family()).await?;
get_scoped_font_family(FontFamilyType::WebFont, options_vc.font_family().await?);
let mut font_families = vec![format!("'{}'", scoped_font_family.clone()).into()];
let font_fallback = &*font_fallback.await?;
......@@ -580,7 +579,7 @@ async fn get_font_css_properties(
font_families.extend_from_slice(fonts);
}
FontFallback::Automatic(fallback) => {
font_families.push(format!("'{}'", *fallback.scoped_font_family.await?).into());
font_families.push(format!("'{}'", fallback.scoped_font_family).into());
}
FontFallback::Error => {}
}
......@@ -642,7 +641,7 @@ fn font_file_options_from_query_map(query: &RcStr) -> Result<NextFontGoogleFontF
}
async fn fetch_real_stylesheet(
stylesheet_url: Vc<RcStr>,
stylesheet_url: RcStr,
css_virtual_path: Vc<FileSystemPath>,
) -> Result<Option<Vc<RcStr>>> {
let body = fetch_from_google_fonts(stylesheet_url, css_virtual_path).await?;
......@@ -651,12 +650,12 @@ async fn fetch_real_stylesheet(
}
async fn fetch_from_google_fonts(
url: Vc<RcStr>,
url: RcStr,
virtual_path: Vc<FileSystemPath>,
) -> Result<Option<Vc<HttpResponseBody>>> {
let result = fetch(
url,
Vc::cell(Some(USER_AGENT_FOR_GOOGLE_FONTS.into())),
Some(rcstr!(USER_AGENT_FOR_GOOGLE_FONTS)),
Vc::cell(None),
)
.await?;
......@@ -675,13 +674,13 @@ async fn fetch_from_google_fonts(
}
async fn get_mock_stylesheet(
stylesheet_url: Vc<RcStr>,
stylesheet_url: RcStr,
mocked_responses_path: &str,
execution_context: Vc<ExecutionContext>,
) -> Result<Option<Vc<RcStr>>> {
let response_path = Path::new(&mocked_responses_path);
let mock_fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(
"mock".into(),
rcstr!("mock"),
response_path
.parent()
.context("Must be valid path")?
......@@ -697,8 +696,8 @@ async fn get_mock_stylesheet(
chunking_context,
} = *execution_context.await?;
let asset_context =
node_evaluate_asset_context(execution_context, None, None, "next_font".into(), false);
let loader_path = mock_fs.root().join("loader.js".into());
node_evaluate_asset_context(execution_context, None, None, rcstr!("next_font"), false);
let loader_path = mock_fs.root().join(rcstr!("loader.js"));
let mocked_response_asset = asset_context
.process(
Vc::upcast(VirtualSource::new(
......@@ -741,7 +740,7 @@ async fn get_mock_stylesheet(
let val: FxHashMap<RcStr, Option<RcStr>> =
parse_json_with_source_context(val.to_str()?)?;
Ok(val
.get(&*stylesheet_url.await?)
.get(&stylesheet_url)
.context("url not found")?
.clone()
.map(Vc::cell))
......
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
FxIndexMap, FxIndexSet, NonLocalValue, Value, Vc, fxindexset, trace::TraceRawVcs,
};
......@@ -29,17 +29,18 @@ pub(super) struct NextFontGoogleOptions {
pub subsets: Option<Vec<RcStr>>,
}
impl NextFontGoogleOptions {
pub async fn font_family(self: Vc<Self>) -> Result<RcStr> {
Ok(self.await?.font_family.clone())
}
}
#[turbo_tasks::value_impl]
impl NextFontGoogleOptions {
#[turbo_tasks::function]
pub fn new(options: Value<NextFontGoogleOptions>) -> Vc<NextFontGoogleOptions> {
Self::cell(options.into_value())
}
#[turbo_tasks::function]
pub fn font_family(&self) -> Vc<RcStr> {
Vc::cell((*self.font_family).into())
}
}
#[derive(
......@@ -155,7 +156,7 @@ pub(super) fn options_from_request(
if font_data.styles.len() == 1 {
styles.push(font_data.styles[0].clone());
} else {
styles.push("normal".into());
styles.push(rcstr!("normal"));
}
}
......@@ -170,7 +171,7 @@ pub(super) fn options_from_request(
}
}
let display = argument.display.unwrap_or_else(|| "swap".into());
let display = argument.display.unwrap_or_else(|| rcstr!("swap"));
if !ALLOWED_DISPLAY_VALUES.contains(&display.as_str()) {
anyhow::bail!(
......@@ -213,7 +214,7 @@ pub(super) fn options_from_request(
#[cfg(test)]
mod tests {
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::FxIndexMap;
use turbo_tasks_fs::json::parse_json_with_source_context;
......@@ -280,10 +281,10 @@ mod tests {
assert_eq!(
options_from_request(&request, &data)?,
NextFontGoogleOptions {
font_family: "ABeeZee".into(),
font_family: rcstr!("ABeeZee"),
weights: FontWeights::Variable,
styles: vec!["normal".into()],
display: "swap".into(),
styles: vec![rcstr!("normal")],
display: rcstr!("swap"),
preload: true,
selected_variable_axes: None,
fallback: None,
......@@ -436,7 +437,7 @@ mod tests {
)?;
let options = options_from_request(&request, &data)?;
assert_eq!(options.styles, vec![RcStr::from("italic")]);
assert_eq!(options.styles, vec![rcstr!("italic")]);
Ok(())
}
......@@ -468,7 +469,7 @@ mod tests {
)?;
let options = options_from_request(&request, &data)?;
assert_eq!(options.styles, vec![RcStr::from("normal")]);
assert_eq!(options.styles, vec![rcstr!("normal")]);
Ok(())
}
......
......@@ -2,7 +2,7 @@ use anyhow::{Context, Result, bail};
use font_fallback::FontFallbackResult;
use indoc::formatdoc;
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Value, Vc};
use turbo_tasks_fs::{
FileContent, FileSystemPath, glob::Glob, json::parse_json_with_source_context,
......@@ -68,9 +68,9 @@ impl NextFontLocalResolvePlugin {
impl BeforeResolvePlugin for NextFontLocalResolvePlugin {
#[turbo_tasks::function]
fn before_resolve_condition(&self) -> Vc<BeforeResolvePluginCondition> {
BeforeResolvePluginCondition::from_request_glob(Glob::new(
"{next,@vercel/turbopack-next/internal}/font/local/*".into(),
))
BeforeResolvePluginCondition::from_request_glob(Glob::new(rcstr!(
"{next,@vercel/turbopack-next/internal}/font/local/*"
)))
}
#[turbo_tasks::function]
......@@ -163,7 +163,7 @@ impl BeforeResolvePlugin for NextFontLocalResolvePlugin {
lookup_path.join(
format!(
"{}.js",
get_request_id(options_vc.font_family(), request_hash).await?
get_request_id(options_vc.font_family().await?, request_hash)
)
.into(),
),
......@@ -182,7 +182,7 @@ impl BeforeResolvePlugin for NextFontLocalResolvePlugin {
let css_virtual_path = lookup_path.join(
format!(
"/{}.module.css",
get_request_id(options.font_family(), request_hash).await?
get_request_id(options.font_family().await?, request_hash)
)
.into(),
);
......@@ -348,9 +348,9 @@ impl Issue for FontResolvingIssue {
async fn title(self: Vc<Self>) -> Result<Vc<StyledString>> {
let this = self.await?;
Ok(StyledString::Line(vec![
StyledString::Text("Font file not found: Can't resolve '".into()),
StyledString::Text(rcstr!("Font file not found: Can't resolve '")),
StyledString::Code(this.font_path.owned().await?),
StyledString::Text("'".into()),
StyledString::Text(rcstr!("'")),
])
.cell())
}
......
......@@ -34,17 +34,18 @@ pub(super) struct NextFontLocalOptions {
pub variable_name: RcStr,
}
impl NextFontLocalOptions {
pub async fn font_family(self: Vc<Self>) -> Result<RcStr> {
Ok(self.await?.variable_name.clone())
}
}
#[turbo_tasks::value_impl]
impl NextFontLocalOptions {
#[turbo_tasks::function]
pub fn new(options: Value<NextFontLocalOptions>) -> Vc<NextFontLocalOptions> {
Self::cell(options.into_value())
}
#[turbo_tasks::function]
pub fn font_family(&self) -> Vc<RcStr> {
Vc::cell(self.variable_name.clone())
}
}
/// Describes an individual font file's path, weight, style, etc. Derived from
......@@ -204,6 +205,7 @@ pub(super) fn options_from_request(request: &NextFontLocalRequest) -> Result<Nex
#[cfg(test)]
mod tests {
use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks_fs::json::parse_json_with_source_context;
use super::{NextFontLocalOptions, options_from_request};
......@@ -231,19 +233,19 @@ mod tests {
options_from_request(&request)?,
NextFontLocalOptions {
fonts: FontDescriptors::One(FontDescriptor {
path: "./Roboto-Regular.ttf".into(),
path: rcstr!("./Roboto-Regular.ttf"),
weight: None,
style: None,
ext: "ttf".into(),
ext: rcstr!("ttf"),
}),
default_style: None,
default_weight: None,
display: "swap".into(),
display: rcstr!("swap"),
preload: true,
fallback: None,
adjust_font_fallback: AdjustFontFallback::Arial,
variable: None,
variable_name: "myFont".into()
variable_name: rcstr!("myFont")
},
);
......@@ -279,26 +281,26 @@ mod tests {
NextFontLocalOptions {
fonts: FontDescriptors::Many(vec![
FontDescriptor {
path: "./Roboto-Regular.ttf".into(),
weight: Some(FontWeight::Fixed("400".into())),
style: Some("normal".into()),
ext: "ttf".into(),
path: rcstr!("./Roboto-Regular.ttf"),
weight: Some(FontWeight::Fixed(rcstr!("400"))),
style: Some(rcstr!("normal")),
ext: rcstr!("ttf"),
},
FontDescriptor {
path: "./Roboto-Italic.ttf".into(),
weight: Some(FontWeight::Fixed("400".into())),
path: rcstr!("./Roboto-Italic.ttf"),
weight: Some(FontWeight::Fixed(rcstr!("400"))),
style: None,
ext: "ttf".into(),
ext: rcstr!("ttf"),
}
]),
default_weight: Some(FontWeight::Fixed("300".into())),
default_style: Some("italic".into()),
display: "swap".into(),
default_weight: Some(FontWeight::Fixed(rcstr!("300"))),
default_style: Some(rcstr!("italic")),
display: rcstr!("swap"),
preload: true,
fallback: None,
adjust_font_fallback: AdjustFontFallback::Arial,
variable: None,
variable_name: "myFont".into()
variable_name: rcstr!("myFont")
},
);
......@@ -360,19 +362,19 @@ mod tests {
options_from_request(&request)?,
NextFontLocalOptions {
fonts: FontDescriptors::One(FontDescriptor {
path: "./Roboto-Regular.woff".into(),
weight: Some(FontWeight::Fixed("500".into())),
style: Some("italic".into()),
ext: "woff".into(),
path: rcstr!("./Roboto-Regular.woff"),
weight: Some(FontWeight::Fixed(rcstr!("500"))),
style: Some(rcstr!("italic")),
ext: rcstr!("woff"),
}),
default_style: Some("italic".into()),
default_weight: Some(FontWeight::Fixed("500".into())),
display: "optional".into(),
default_style: Some(rcstr!("italic")),
default_weight: Some(FontWeight::Fixed(rcstr!("500"))),
display: rcstr!("optional"),
preload: false,
fallback: Some(vec!["Fallback".into()]),
fallback: Some(vec![rcstr!("Fallback")]),
adjust_font_fallback: AdjustFontFallback::TimesNewRoman,
variable: Some("myvar".into()),
variable_name: "myFont".into()
variable: Some(rcstr!("myvar")),
variable_name: rcstr!("myFont")
},
);
......
......@@ -18,7 +18,7 @@ pub(super) async fn build_stylesheet(
css_properties: Vc<FontCssProperties>,
) -> Result<Vc<RcStr>> {
let scoped_font_family =
get_scoped_font_family(FontFamilyType::WebFont.cell(), options.font_family());
get_scoped_font_family(FontFamilyType::WebFont, options.font_family().await?);
Ok(Vc::cell(
formatdoc!(
......@@ -39,7 +39,7 @@ pub(super) async fn build_stylesheet(
/// Builds a string of `@font-face` definitions for each local font file
#[turbo_tasks::function]
pub(super) async fn build_font_face_definitions(
scoped_font_family: Vc<RcStr>,
scoped_font_family: RcStr,
options: Vc<NextFontLocalOptions>,
has_size_adjust: Vc<bool>,
) -> Result<Vc<RcStr>> {
......@@ -70,7 +70,7 @@ pub(super) async fn build_font_face_definitions(
{}{}
}}
"#,
*scoped_font_family.await?,
scoped_font_family,
query_str,
ext_to_format(&font.ext)?,
options.display,
......
......@@ -17,7 +17,7 @@ pub(super) async fn build_font_family_string(
let mut font_families = vec![
format!(
"'{}'",
*get_scoped_font_family(FontFamilyType::WebFont.cell(), options.font_family(),).await?
get_scoped_font_family(FontFamilyType::WebFont, options.font_family().await?)
)
.into(),
];
......@@ -25,7 +25,7 @@ pub(super) async fn build_font_family_string(
for font_fallback in &*font_fallbacks.await? {
match &*font_fallback.await? {
FontFallback::Automatic(fallback) => {
font_families.push(format!("'{}'", *fallback.scoped_font_family.await?).into());
font_families.push(format!("'{}'", fallback.scoped_font_family).into());
}
FontFallback::Manual(fallbacks) => {
font_families.extend_from_slice(fallbacks);
......
......@@ -38,8 +38,8 @@ pub(crate) async fn build_fallback_definition(fallbacks: Vc<FontFallbacks>) -> R
{}
}}
"#,
fallback.scoped_font_family.await?,
fallback.local_font_family.await?,
fallback.scoped_font_family,
fallback.local_font_family,
override_properties
));
}
......
use anyhow::{Context, Result};
use serde::Deserialize;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{FileSystemPath, json::parse_json_with_source_context};
use turbo_tasks_hash::hash_xxh3_hash64;
......@@ -46,31 +46,21 @@ pub(crate) enum FontFamilyType {
/// e.g. `__Roboto_Fallback_c123b8`
/// * `font_family_name` - The font name to scope, e.g. `Roboto`
/// * `request_hash` - The hash value of the font request
#[turbo_tasks::function]
pub(crate) async fn get_scoped_font_family(
ty: Vc<FontFamilyType>,
font_family_name: Vc<RcStr>,
) -> Result<Vc<RcStr>> {
let font_family_base = font_family_name.await?.to_string();
let font_family_name = match &*ty.await? {
FontFamilyType::WebFont => font_family_base,
FontFamilyType::Fallback => format!("{font_family_base} Fallback"),
};
Ok(Vc::cell(font_family_name.into()))
pub(crate) fn get_scoped_font_family(ty: FontFamilyType, font_family_name: RcStr) -> RcStr {
match ty {
FontFamilyType::WebFont => font_family_name,
FontFamilyType::Fallback => format!("{font_family_name} Fallback").into(),
}
}
/// Returns a [Vc] for [String] uniquely identifying the request for the font.
#[turbo_tasks::function]
pub async fn get_request_id(font_family: Vc<RcStr>, request_hash: u32) -> Result<Vc<RcStr>> {
Ok(Vc::cell(
format!(
"{}_{:x?}",
font_family.await?.to_lowercase().replace(' ', "_"),
request_hash
)
.into(),
))
/// Returns a [RcStr] for [String] uniquely identifying the request for the font.
pub fn get_request_id(font_family: RcStr, request_hash: u32) -> RcStr {
format!(
"{}_{:x?}",
font_family.to_lowercase().replace(' ', "_"),
request_hash
)
.into()
}
#[derive(Debug, Deserialize)]
......@@ -98,12 +88,12 @@ pub(crate) async fn can_use_next_font(
NextFontIssue {
path: path.to_resolved().await?,
title: StyledString::Line(vec![
StyledString::Code("next/font:".into()),
StyledString::Text(" error:".into()),
StyledString::Code(rcstr!("next/font:")),
StyledString::Text(rcstr!(" error:")),
])
.resolved_cell(),
description: StyledString::Line(vec![
StyledString::Text("Cannot be used within ".into()),
StyledString::Text(rcstr!("Cannot be used within ")),
StyledString::Code(request.path),
])
.resolved_cell(),
......
......@@ -2,7 +2,7 @@ use std::collections::BTreeMap;
use anyhow::{Context, Result};
use rustc_hash::FxHashMap;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, ResolvedVc, Value, Vc, fxindexmap};
use turbo_tasks_fs::{FileSystem, FileSystemPath};
use turbopack_core::{
......@@ -333,7 +333,7 @@ pub async fn get_next_server_import_map(
import_map.insert_exact_alias(
"styled-jsx/style",
ImportMapping::External(
Some("styled-jsx/style.js".into()),
Some(rcstr!("styled-jsx/style.js")),
ExternalType::CommonJs,
ExternalTraced::Traced,
)
......@@ -456,7 +456,7 @@ pub async fn get_next_edge_import_map(
.await?;
let ty = ty.into_value();
match ty {
match &ty {
ServerContextType::Pages { .. }
| ServerContextType::PagesData { .. }
| ServerContextType::PagesApi { .. }
......@@ -486,7 +486,7 @@ pub async fn get_next_edge_import_map(
insert_next_server_special_aliases(
&mut import_map,
project_path,
ty,
ty.clone(),
NextRuntime::Edge,
next_config,
)
......@@ -607,14 +607,14 @@ async fn insert_next_server_special_aliases(
.resolved_cell(),
);
match ty {
match &ty {
ServerContextType::Pages { .. } | ServerContextType::PagesApi { .. } => {}
ServerContextType::PagesData { .. } => {}
// the logic closely follows the one in createRSCAliases in webpack-config.ts
ServerContextType::AppSSR { app_dir }
| ServerContextType::AppRSC { app_dir, .. }
| ServerContextType::AppRoute { app_dir, .. } => {
let next_package = get_next_package(*app_dir).to_resolved().await?;
let next_package = get_next_package(**app_dir).to_resolved().await?;
import_map.insert_exact_alias(
"styled-jsx",
request_to_import_mapping(next_package, "styled-jsx"),
......@@ -624,10 +624,10 @@ async fn insert_next_server_special_aliases(
request_to_import_mapping(next_package, "styled-jsx/*"),
);
rsc_aliases(import_map, project_path, ty, runtime, next_config).await?;
rsc_aliases(import_map, project_path, ty.clone(), runtime, next_config).await?;
}
ServerContextType::Middleware { .. } | ServerContextType::Instrumentation { .. } => {
rsc_aliases(import_map, project_path, ty, runtime, next_config).await?;
rsc_aliases(import_map, project_path, ty.clone(), runtime, next_config).await?;
}
}
......@@ -636,7 +636,7 @@ async fn insert_next_server_special_aliases(
// context, it'll resolve to the noop where it's allowed, or aliased into
// the error which throws a runtime error. This works with in combination of
// build-time error as well, refer https://github.com/vercel/next.js/blob/0060de1c4905593ea875fa7250d4b5d5ce10897d/packages/next-swc/crates/next-core/src/next_server/context.rs#L103
match ty {
match &ty {
ServerContextType::Pages { .. } => {
insert_exact_alias_map(
import_map,
......@@ -1014,7 +1014,7 @@ pub async fn get_next_package(context_directory: Vc<FileSystemPath>) -> Result<V
let result = resolve(
context_directory,
Value::new(ReferenceType::CommonJs(CommonJsReferenceSubType::Undefined)),
Request::parse(Value::new(Pattern::Constant("next/package.json".into()))),
Request::parse(Value::new(Pattern::Constant(rcstr!("next/package.json")))),
node_cjs_resolve_options(context_directory.root()),
);
let source = result
......@@ -1113,7 +1113,7 @@ fn insert_package_alias(
) {
import_map.insert_wildcard_alias(
prefix,
ImportMapping::PrimaryAlternative("./*".into(), Some(package_root)).resolved_cell(),
ImportMapping::PrimaryAlternative(rcstr!("./*"), Some(package_root)).resolved_cell(),
);
}
......
......@@ -2,7 +2,7 @@ use std::io::Write;
use anyhow::{Result, bail};
use serde::Serialize;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, ResolvedVc, Value, Vc, fxindexmap};
use turbo_tasks_fs::{File, FileSystemPath, rope::RopeBuilder};
use turbopack_core::{
......@@ -32,18 +32,18 @@ pub struct PageSsrEntryModule {
#[turbo_tasks::function]
pub async fn create_page_ssr_entry_module(
pathname: Vc<RcStr>,
pathname: RcStr,
reference_type: Value<ReferenceType>,
project_root: Vc<FileSystemPath>,
ssr_module_context: Vc<Box<dyn AssetContext>>,
source: Vc<Box<dyn Source>>,
next_original_name: Vc<RcStr>,
next_original_name: RcStr,
pages_structure: Vc<PagesStructure>,
runtime: NextRuntime,
next_config: Vc<NextConfig>,
) -> Result<Vc<PageSsrEntryModule>> {
let definition_page = &*next_original_name.await?;
let definition_pathname = &*pathname.await?;
let definition_page = next_original_name;
let definition_pathname = pathname;
let ssr_module = ssr_module_context
.process(source, reference_type.clone())
......@@ -69,20 +69,20 @@ pub async fn create_page_ssr_entry_module(
_ => bail!("Invalid path type"),
};
const INNER: &str = "INNER_PAGE";
let inner = rcstr!("INNER_PAGE");
const INNER_DOCUMENT: &str = "INNER_DOCUMENT";
const INNER_APP: &str = "INNER_APP";
let inner_document = rcstr!("INNER_DOCUMENT");
let inner_app = rcstr!("INNER_APP");
let mut replacements = fxindexmap! {
"VAR_DEFINITION_PAGE" => definition_page.clone(),
"VAR_DEFINITION_PATHNAME" => definition_pathname.clone(),
"VAR_USERLAND" => INNER.into(),
"VAR_USERLAND" => inner.clone(),
};
if reference_type == ReferenceType::Entry(EntryReferenceSubType::Page) {
replacements.insert("VAR_MODULE_DOCUMENT", INNER_DOCUMENT.into());
replacements.insert("VAR_MODULE_APP", INNER_APP.into());
replacements.insert("VAR_MODULE_DOCUMENT", inner_document.clone());
replacements.insert("VAR_MODULE_APP", inner_app.clone());
}
// Load the file from the next.js codebase.
......@@ -99,7 +99,7 @@ pub async fn create_page_ssr_entry_module(
// instrumentation file conflicts with a page also labeled
// /instrumentation) hoist the `register` method.
if reference_type == ReferenceType::Entry(EntryReferenceSubType::Page)
&& (*definition_page == "/instrumentation" || *definition_page == "/src/instrumentation")
&& (definition_page == "/instrumentation" || definition_page == "/src/instrumentation")
{
let file = &*file_content_rope(source.content().file_content()).await?;
......@@ -120,7 +120,7 @@ pub async fn create_page_ssr_entry_module(
}
let mut inner_assets = fxindexmap! {
INNER.into() => ssr_module,
inner => ssr_module,
};
let pages_structure_ref = pages_structure.await?;
......@@ -141,8 +141,8 @@ pub async fn create_page_ssr_entry_module(
)
.to_resolved()
.await?;
inner_assets.insert(INNER_DOCUMENT.into(), document_module);
inner_assets.insert(INNER_APP.into(), app_module);
inner_assets.insert(inner_document, document_module);
inner_assets.insert(inner_app, app_module);
(Some(app_module), Some(document_module))
} else {
(None, None)
......@@ -244,8 +244,8 @@ async fn wrap_edge_page(
"nextConfig" => serde_json::to_string(next_config_val)?.into(),
"dev" => serde_json::Value::Bool(dev).to_string().into(),
"pageRouteModuleOptions" => serde_json::to_string(&get_route_module_options(page.clone(), pathname.clone()))?.into(),
"errorRouteModuleOptions" => serde_json::to_string(&get_route_module_options("/_error".into(), "/_error".into()))?.into(),
"user500RouteModuleOptions" => serde_json::to_string(&get_route_module_options("/500".into(), "/500".into()))?.into(),
"errorRouteModuleOptions" => serde_json::to_string(&get_route_module_options(rcstr!("/_error"), rcstr!("/_error")))?.into(),
"user500RouteModuleOptions" => serde_json::to_string(&get_route_module_options(rcstr!("/500"), rcstr!("/500")))?.into(),
},
fxindexmap! {
// TODO
......@@ -322,12 +322,12 @@ struct RouteDefinition {
fn get_route_module_options(page: RcStr, pathname: RcStr) -> PartialRouteModuleOptions {
PartialRouteModuleOptions {
definition: RouteDefinition {
kind: "PAGES".into(),
kind: rcstr!("PAGES"),
page,
pathname,
// The following aren't used in production.
bundle_path: "".into(),
filename: "".into(),
bundle_path: rcstr!(""),
filename: rcstr!(""),
},
}
}
use std::iter::once;
use anyhow::{Result, bail};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, OptionVcExt, ResolvedVc, Value, Vc};
use turbo_tasks_env::{EnvMap, ProcessEnv};
use turbo_tasks_fs::FileSystemPath;
......@@ -79,7 +79,7 @@ use crate::{
};
#[turbo_tasks::value(shared, serialization = "auto_for_input")]
#[derive(Debug, Copy, Clone, Hash)]
#[derive(Debug, Clone, Hash)]
pub enum ServerContextType {
Pages {
pages_dir: ResolvedVc<FileSystemPath>,
......@@ -95,20 +95,20 @@ pub enum ServerContextType {
},
AppRSC {
app_dir: ResolvedVc<FileSystemPath>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>,
ecmascript_client_reference_transition_name: Option<RcStr>,
client_transition: Option<ResolvedVc<Box<dyn Transition>>>,
},
AppRoute {
app_dir: ResolvedVc<FileSystemPath>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>,
ecmascript_client_reference_transition_name: Option<RcStr>,
},
Middleware {
app_dir: Option<ResolvedVc<FileSystemPath>>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>,
ecmascript_client_reference_transition_name: Option<RcStr>,
},
Instrumentation {
app_dir: Option<ResolvedVc<FileSystemPath>>,
ecmascript_client_reference_transition_name: Option<ResolvedVc<RcStr>>,
ecmascript_client_reference_transition_name: Option<RcStr>,
},
}
......@@ -133,10 +133,15 @@ pub async fn get_server_resolve_options_context(
next_config: Vc<NextConfig>,
execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ResolveOptionsContext>> {
let next_server_import_map =
get_next_server_import_map(*project_path, ty, next_config, mode, execution_context)
.to_resolved()
.await?;
let next_server_import_map = get_next_server_import_map(
*project_path,
ty.clone(),
next_config,
mode,
execution_context,
)
.to_resolved()
.await?;
let foreign_code_context_condition =
foreign_code_context_condition(next_config, project_path).await?;
let root_dir = project_path.root().to_resolved().await?;
......@@ -154,7 +159,7 @@ pub async fn get_server_resolve_options_context(
// Always load these predefined packages as external.
let mut external_packages: Vec<RcStr> = load_next_js_templateon(
project_path,
"dist/lib/server-external-packages.json".into(),
rcstr!("dist/lib/server-external-packages.json"),
)
.await?;
......@@ -209,7 +214,7 @@ pub async fn get_server_resolve_options_context(
);
if ty.supports_react_server() {
custom_conditions.push("react-server".into());
custom_conditions.push(rcstr!("react-server"));
};
let external_cjs_modules_plugin = if *next_config.bundle_pages_router_dependencies().await? {
......@@ -229,11 +234,11 @@ pub async fn get_server_resolve_options_context(
.to_resolved()
.await?;
let next_node_shared_runtime_plugin =
NextNodeSharedRuntimeResolvePlugin::new(*project_path, Value::new(ty))
NextNodeSharedRuntimeResolvePlugin::new(*project_path, Value::new(ty.clone()))
.to_resolved()
.await?;
let mut before_resolve_plugins = match ty {
let mut before_resolve_plugins = match &ty {
ServerContextType::Pages { .. }
| ServerContextType::AppSSR { .. }
| ServerContextType::AppRSC { .. } => {
......@@ -415,7 +420,7 @@ pub async fn get_server_module_options_context(
let next_mode = mode.await?;
let mut next_server_rules = get_next_server_transforms_rules(
next_config,
ty.into_value(),
ty.clone().into_value(),
mode,
false,
next_runtime,
......@@ -424,7 +429,7 @@ pub async fn get_server_module_options_context(
.await?;
let mut foreign_next_server_rules = get_next_server_transforms_rules(
next_config,
ty.into_value(),
ty.clone().into_value(),
mode,
true,
next_runtime,
......@@ -432,7 +437,7 @@ pub async fn get_server_module_options_context(
)
.await?;
let mut internal_custom_rules = get_next_server_internal_transforms_rules(
ty.into_value(),
ty.clone().into_value(),
next_config.mdx_rs().await?.is_some(),
)
.await?;
......@@ -478,7 +483,7 @@ pub async fn get_server_module_options_context(
conditions
.iter()
.cloned()
.chain(once("foreign".into()))
.chain(once(rcstr!("foreign")))
.collect(),
)
.await?;
......@@ -983,9 +988,9 @@ pub async fn get_server_chunking_context_with_client_assets(
mode: Vc<NextMode>,
root_path: ResolvedVc<FileSystemPath>,
node_root: ResolvedVc<FileSystemPath>,
node_root_to_root_path: ResolvedVc<RcStr>,
node_root_to_root_path: RcStr,
client_root: ResolvedVc<FileSystemPath>,
asset_prefix: ResolvedVc<Option<RcStr>>,
asset_prefix: Option<RcStr>,
environment: ResolvedVc<Environment>,
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
turbo_minify: Vc<bool>,
......@@ -1002,11 +1007,11 @@ pub async fn get_server_chunking_context_with_client_assets(
node_root_to_root_path,
client_root,
node_root
.join("server/chunks/ssr".into())
.join(rcstr!("server/chunks/ssr"))
.to_resolved()
.await?,
client_root
.join("static/media".into())
.join(rcstr!("static/media"))
.to_resolved()
.await?,
environment,
......@@ -1058,7 +1063,7 @@ pub async fn get_server_chunking_context(
mode: Vc<NextMode>,
root_path: ResolvedVc<FileSystemPath>,
node_root: ResolvedVc<FileSystemPath>,
node_root_to_root_path: ResolvedVc<RcStr>,
node_root_to_root_path: RcStr,
environment: ResolvedVc<Environment>,
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
turbo_minify: Vc<bool>,
......@@ -1074,8 +1079,14 @@ pub async fn get_server_chunking_context(
node_root,
node_root_to_root_path,
node_root,
node_root.join("server/chunks".into()).to_resolved().await?,
node_root.join("server/assets".into()).to_resolved().await?,
node_root
.join(rcstr!("server/chunks"))
.to_resolved()
.await?,
node_root
.join(rcstr!("server/assets"))
.to_resolved()
.await?,
environment,
next_mode.runtime_type(),
)
......
......@@ -86,7 +86,7 @@ pub async fn get_next_server_transforms_rules(
if !foreign_code {
rules.push(get_next_page_static_info_assert_rule(
mdx_rs,
Some(context_ty),
Some(context_ty.clone()),
None,
));
}
......@@ -95,7 +95,7 @@ pub async fn get_next_server_transforms_rules(
let cache_kinds = next_config.cache_kinds().to_resolved().await?;
let mut is_app_dir = false;
let is_server_components = match context_ty {
let is_server_components = match &context_ty {
ServerContextType::Pages { pages_dir } | ServerContextType::PagesApi { pages_dir } => {
if !foreign_code {
rules.push(get_next_disallow_export_all_in_page_rule(
......@@ -109,7 +109,7 @@ pub async fn get_next_server_transforms_rules(
if !foreign_code {
rules.push(
get_next_pages_transforms_rule(
*pages_dir,
**pages_dir,
ExportFilter::StripDefaultExport,
mdx_rs,
)
......
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Vc, fxindexmap};
use turbopack_core::diagnostics::{Diagnostic, DiagnosticPayload};
......@@ -17,7 +17,7 @@ pub struct NextFeatureTelemetry {
impl NextFeatureTelemetry {
pub fn new(feature_name: RcStr, enabled: bool) -> Self {
NextFeatureTelemetry {
event_name: "EVENT_BUILD_FEATURE_USAGE".into(),
event_name: rcstr!("EVENT_BUILD_FEATURE_USAGE"),
feature_name,
enabled,
}
......@@ -28,7 +28,7 @@ impl NextFeatureTelemetry {
impl Diagnostic for NextFeatureTelemetry {
#[turbo_tasks::function]
fn category(&self) -> Vc<RcStr> {
Vc::cell("NextFeatureTelemetry_category_tbd".into())
Vc::cell(rcstr!("NextFeatureTelemetry_category_tbd"))
}
#[turbo_tasks::function]
......@@ -57,7 +57,7 @@ pub struct ModuleFeatureTelemetry {
impl ModuleFeatureTelemetry {
pub fn new(feature_name: RcStr, invocation_count: usize) -> Self {
ModuleFeatureTelemetry {
event_name: "EVENT_BUILD_FEATURE_USAGE".into(),
event_name: rcstr!("EVENT_BUILD_FEATURE_USAGE"),
feature_name,
invocation_count,
}
......@@ -68,7 +68,7 @@ impl ModuleFeatureTelemetry {
impl Diagnostic for ModuleFeatureTelemetry {
#[turbo_tasks::function]
fn category(&self) -> Vc<RcStr> {
Vc::cell("ModuleFeatureTelemetry_category_tbd".into())
Vc::cell(rcstr!("ModuleFeatureTelemetry_category_tbd"))
}
#[turbo_tasks::function]
......
use std::io::Write;
use anyhow::{Result, bail};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, Value, Vc, fxindexmap};
use turbo_tasks_fs::{
self, File, FileContent, FileSystemPath, FileSystemPathOption, rope::RopeBuilder,
......@@ -25,16 +25,12 @@ use crate::{embed_js::next_js_file_path, util::get_asset_path_from_pathname};
pub async fn create_page_loader_entry_module(
client_context: Vc<Box<dyn AssetContext>>,
entry_asset: Vc<Box<dyn Source>>,
pathname: Vc<RcStr>,
pathname: RcStr,
) -> Result<Vc<Box<dyn Module>>> {
let mut result = RopeBuilder::default();
writeln!(
result,
"const PAGE_PATH = {};\n",
StringifyJs(&*pathname.await?)
)?;
writeln!(result, "const PAGE_PATH = {};\n", StringifyJs(&pathname))?;
let page_loader_path = next_js_file_path("entry/page-loader.ts".into());
let page_loader_path = next_js_file_path(rcstr!("entry/page-loader.ts"));
let base_code = page_loader_path.read();
if let FileContent::Content(base_file) = &*base_code.await? {
result += base_file.content()
......@@ -62,7 +58,7 @@ pub async fn create_page_loader_entry_module(
.process(
virtual_source,
Value::new(ReferenceType::Internal(ResolvedVc::cell(fxindexmap! {
"PAGE".into() => module,
rcstr!("PAGE") => module,
}))),
)
.module();
......@@ -72,7 +68,7 @@ pub async fn create_page_loader_entry_module(
#[turbo_tasks::value(shared)]
pub struct PageLoaderAsset {
pub server_root: ResolvedVc<FileSystemPath>,
pub pathname: ResolvedVc<RcStr>,
pub pathname: RcStr,
pub rebase_prefix_path: ResolvedVc<FileSystemPathOption>,
pub page_chunks: ResolvedVc<OutputAssets>,
}
......@@ -82,7 +78,7 @@ impl PageLoaderAsset {
#[turbo_tasks::function]
pub fn new(
server_root: ResolvedVc<FileSystemPath>,
pathname: ResolvedVc<RcStr>,
pathname: RcStr,
rebase_prefix_path: ResolvedVc<FileSystemPathOption>,
page_chunks: ResolvedVc<OutputAssets>,
) -> Vc<Self> {
......@@ -125,11 +121,6 @@ impl PageLoaderAsset {
}
}
#[turbo_tasks::function]
fn page_loader_chunk_reference_description() -> Vc<RcStr> {
Vc::cell("page loader chunk".into())
}
#[turbo_tasks::value_impl]
impl OutputAsset for PageLoaderAsset {
#[turbo_tasks::function]
......@@ -141,7 +132,7 @@ impl OutputAsset for PageLoaderAsset {
Ok(root.join(
format!(
"static/chunks/pages{}",
get_asset_path_from_pathname(&self.pathname.await?, ".js")
get_asset_path_from_pathname(&self.pathname, ".js")
)
.into(),
))
......@@ -181,7 +172,7 @@ impl Asset for PageLoaderAsset {
let content = format!(
"__turbopack_load_page_chunks__({}, {:#})\n",
StringifyJs(&this.pathname.await?),
StringifyJs(&this.pathname),
StringifyJs(&chunks_data)
);
......
......@@ -32,7 +32,7 @@ use swc_core::{
},
quote,
};
use turbo_rcstr::RcStr;
use turbo_rcstr::{rcstr, RcStr};
use crate::FxIndexMap;
......@@ -2778,7 +2778,7 @@ impl DirectiveVisitor<'_> {
if value == "use cache" {
self.directive = Some(Directive::UseCache {
cache_kind: RcStr::from("default"),
cache_kind: rcstr!("default"),
});
self.increment_cache_usage_counter("default");
} else {
......
......@@ -37,8 +37,8 @@ mod tagged_value;
///
/// ## Conversion
///
/// Converting a `String` or `&str` to an `RcStr` can be perfomed using `.into()` or
/// `RcStr::from(...)`:
/// Converting a `String` or `&str` to an `RcStr` can be perfomed using `.into()`,
/// `RcStr::from(...)`, or the `rcstr!` macro.
///
/// ```
/// # use turbo_rcstr::RcStr;
......@@ -46,9 +46,15 @@ mod tagged_value;
/// let s = "foo";
/// let rc_s1: RcStr = s.into();
/// let rc_s2 = RcStr::from(s);
/// let rc_s3 = rcstr!("foo");
/// assert_eq!(rc_s1, rc_s2);
/// ```
///
/// Generally speaking you should
/// * use `rcstr!` when converting a `const`-compatible `str`
/// * use `RcStr::from` for readability
/// * use `.into()` when context makes it clear.
///
/// Converting from an [`RcStr`] to a `&str` should be done with [`RcStr::as_str`]. Converting to a
/// `String` should be done with [`RcStr::into_owned`].
///
......
......@@ -3,7 +3,7 @@
#![feature(arbitrary_self_types_pointers)]
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc, duration_span, mark_session_dependent};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::issue::{Issue, IssueSeverity, IssueStage, OptionStyledString, StyledString};
......@@ -50,12 +50,10 @@ pub struct OptionProxyConfig(Option<ProxyConfig>);
#[turbo_tasks::function(network)]
pub async fn fetch(
url: Vc<RcStr>,
user_agent: Vc<Option<RcStr>>,
url: RcStr,
user_agent: Option<RcStr>,
proxy_option: Vc<OptionProxyConfig>,
) -> Result<Vc<FetchResult>> {
let url = &*url.await?;
let user_agent = &*user_agent.await?;
let proxy_option = &*proxy_option.await?;
let client_builder = reqwest::Client::builder();
......@@ -96,7 +94,7 @@ pub async fn fetch(
Err(err) => {
mark_session_dependent();
Ok(Vc::cell(Err(
FetchError::from_reqwest_error(&err, url).resolved_cell()
FetchError::from_reqwest_error(&err, &url).resolved_cell()
)))
}
}
......@@ -181,7 +179,7 @@ impl Issue for FetchIssue {
#[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> {
StyledString::Text("Error while requesting resource".into()).cell()
StyledString::Text(rcstr!("Error while requesting resource")).cell()
}
#[turbo_tasks::function]
......
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
#![cfg(test)]
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::Vc;
use turbo_tasks_fetch::{FetchErrorKind, fetch};
use turbo_tasks_fs::{DiskFileSystem, FileSystem, FileSystemPath};
......@@ -18,13 +19,9 @@ async fn basic_get() {
then.status(200).body("responsebody");
});
let result = &*fetch(
Vc::cell(server.url("/foo.woff").into()),
Vc::cell(None),
Vc::cell(None),
)
.await
.unwrap();
let result = &*fetch(server.url("/foo.woff").into(), None, Vc::cell(None))
.await
.unwrap();
resource_mock.assert();
match result {
......@@ -51,8 +48,8 @@ async fn sends_user_agent() {
});
let result = &*fetch(
Vc::cell(server.url("/foo.woff").into()),
Vc::cell(Some("foo".into())),
server.url("/foo.woff").into(),
Some(rcstr!("foo")),
Vc::cell(None),
)
.await
......@@ -81,10 +78,10 @@ async fn invalidation_does_not_invalidate() {
then.status(200).body("responsebody");
});
let url = Vc::cell(server.url("/foo.woff").into());
let user_agent = Vc::cell(Some("foo".into()));
let url: RcStr = server.url("/foo.woff").into();
let user_agent = Some(rcstr!("foo"));
let proxy = Vc::cell(None);
let result = &*fetch(url, user_agent, proxy).await?;
let result = &*fetch(url.clone(), user_agent.clone(), proxy).await?;
resource_mock.assert();
let Ok(response_vc) = result else { panic!() };
......@@ -111,8 +108,8 @@ async fn invalidation_does_not_invalidate() {
#[tokio::test]
async fn errors_on_failed_connection() {
run(&REGISTRATION, || async {
let url = "https://doesnotexist/foo.woff";
let result = &*fetch(Vc::cell(url.into()), Vc::cell(None), Vc::cell(None)).await?;
let url = rcstr!("https://doesnotexist/foo.woff");
let result = &*fetch(url.clone(), None, Vc::cell(None)).await?;
let Err(err_vc) = result else {
panic!()
};
......@@ -122,7 +119,7 @@ async fn errors_on_failed_connection() {
let issue = err_vc.to_issue(IssueSeverity::Error.into(), get_issue_context());
assert_eq!(*issue.severity().await?, IssueSeverity::Error);
assert_eq!(*issue.description().await?.unwrap().await?, StyledString::Text("There was an issue establishing a connection while requesting https://doesnotexist/foo.woff.".into()));
assert_eq!(*issue.description().await?.unwrap().await?, StyledString::Text(rcstr!("There was an issue establishing a connection while requesting https://doesnotexist/foo.woff.")));
anyhow::Ok(())
})
.await.unwrap()
......@@ -132,14 +129,10 @@ async fn errors_on_failed_connection() {
async fn errors_on_404() {
run(&REGISTRATION, || async {
let server = httpmock::MockServer::start();
let resource_url = server.url("/");
let result = &*fetch(
Vc::cell(resource_url.clone().into()),
Vc::cell(None),
Vc::cell(None),
)
.await
.unwrap();
let resource_url: RcStr = server.url("/").into();
let result = &*fetch(resource_url.clone(), None, Vc::cell(None))
.await
.unwrap();
let Err(err_vc) = result else { panic!() };
let err = &*err_vc.await?;
assert!(matches!(*err.kind.await?, FetchErrorKind::Status(404)));
......@@ -164,5 +157,5 @@ async fn errors_on_404() {
}
fn get_issue_context() -> Vc<FileSystemPath> {
DiskFileSystem::new("root".into(), "/".into(), vec![]).root()
DiskFileSystem::new(rcstr!("root"), rcstr!("/"), vec![]).root()
}
......@@ -23,7 +23,6 @@ pub mod source_context;
pub mod util;
pub(crate) mod virtual_fs;
mod watcher;
use std::{
borrow::Cow,
cmp::{Ordering, min},
......@@ -57,7 +56,7 @@ use tokio::{
sync::{RwLock, RwLockReadGuard},
};
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
ApplyEffectsContext, Completion, InvalidationReason, Invalidator, NonLocalValue, ReadRef,
ResolvedVc, ValueToString, Vc, debug::ValueDebugFormat, effect, mark_session_dependent,
......@@ -1286,7 +1285,7 @@ impl FileSystemPath {
#[turbo_tasks::function]
pub fn extension(&self) -> Vc<RcStr> {
Vc::cell(self.extension_ref().unwrap_or("").into())
Vc::cell(self.extension_ref().map(RcStr::from).unwrap_or_default())
}
#[turbo_tasks::function]
......@@ -2404,7 +2403,7 @@ impl FileSystem for NullFileSystem {
impl ValueToString for NullFileSystem {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
Vc::cell(RcStr::from("null"))
Vc::cell(rcstr!("null"))
}
}
......@@ -2431,6 +2430,8 @@ pub fn register() {
#[cfg(test)]
mod tests {
use turbo_rcstr::rcstr;
use super::*;
#[test]
......@@ -2456,26 +2457,26 @@ mod tests {
turbo_tasks_testing::VcStorage::with(async {
let fs = Vc::upcast(VirtualFileSystem::new());
let path_txt = FileSystemPath::new_normalized(fs, "foo/bar.txt".into());
let path_txt = FileSystemPath::new_normalized(fs, rcstr!("foo/bar.txt"));
let path_json = path_txt.with_extension("json".into());
let path_json = path_txt.with_extension(rcstr!("json"));
assert_eq!(&*path_json.await.unwrap().path, "foo/bar.json");
let path_no_ext = path_txt.with_extension("".into());
let path_no_ext = path_txt.with_extension(rcstr!(""));
assert_eq!(&*path_no_ext.await.unwrap().path, "foo/bar");
let path_new_ext = path_no_ext.with_extension("json".into());
let path_new_ext = path_no_ext.with_extension(rcstr!("json"));
assert_eq!(&*path_new_ext.await.unwrap().path, "foo/bar.json");
let path_no_slash_txt = FileSystemPath::new_normalized(fs, "bar.txt".into());
let path_no_slash_txt = FileSystemPath::new_normalized(fs, rcstr!("bar.txt"));
let path_no_slash_json = path_no_slash_txt.with_extension("json".into());
let path_no_slash_json = path_no_slash_txt.with_extension(rcstr!("json"));
assert_eq!(path_no_slash_json.await.unwrap().path.as_str(), "bar.json");
let path_no_slash_no_ext = path_no_slash_txt.with_extension("".into());
let path_no_slash_no_ext = path_no_slash_txt.with_extension(rcstr!(""));
assert_eq!(path_no_slash_no_ext.await.unwrap().path.as_str(), "bar");
let path_no_slash_new_ext = path_no_slash_no_ext.with_extension("json".into());
let path_no_slash_new_ext = path_no_slash_no_ext.with_extension(rcstr!("json"));
assert_eq!(
path_no_slash_new_ext.await.unwrap().path.as_str(),
"bar.json"
......@@ -2494,19 +2495,19 @@ mod tests {
turbo_tasks_testing::VcStorage::with(async {
let fs = Vc::upcast::<Box<dyn FileSystem>>(VirtualFileSystem::new());
let path = FileSystemPath::new_normalized(fs, "".into());
let path = FileSystemPath::new_normalized(fs, rcstr!(""));
assert_eq!(path.file_stem().await.unwrap().as_deref(), None);
let path = FileSystemPath::new_normalized(fs, "foo/bar.txt".into());
let path = FileSystemPath::new_normalized(fs, rcstr!("foo/bar.txt"));
assert_eq!(path.file_stem().await.unwrap().as_deref(), Some("bar"));
let path = FileSystemPath::new_normalized(fs, "bar.txt".into());
let path = FileSystemPath::new_normalized(fs, rcstr!("bar.txt"));
assert_eq!(path.file_stem().await.unwrap().as_deref(), Some("bar"));
let path = FileSystemPath::new_normalized(fs, "foo/bar".into());
let path = FileSystemPath::new_normalized(fs, rcstr!("foo/bar"));
assert_eq!(path.file_stem().await.unwrap().as_deref(), Some("bar"));
let path = FileSystemPath::new_normalized(fs, "foo/.bar".into());
let path = FileSystemPath::new_normalized(fs, rcstr!("foo/.bar"));
assert_eq!(path.file_stem().await.unwrap().as_deref(), Some(".bar"));
anyhow::Ok(())
......
......@@ -11,7 +11,7 @@ use clap::{Args, Parser, Subcommand};
use rand::{Rng, RngCore, SeedableRng};
use rustc_hash::FxHashSet;
use tokio::time::sleep;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, ResolvedVc, TransientInstance, Vc, trace::TraceRawVcs};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{DiskFileSystem, FileSystem, FileSystemPath};
......@@ -142,7 +142,7 @@ async fn fuzz_fs_watcher(args: FsWatcher) -> anyhow::Result<()> {
#[turbo_tasks::function(operation)]
fn disk_file_system_operation(fs_root: RcStr) -> Vc<DiskFileSystem> {
DiskFileSystem::new("project".into(), fs_root, Vec::new())
DiskFileSystem::new(rcstr!("project"), fs_root, Vec::new())
}
#[turbo_tasks::function(operation)]
......
......@@ -3,7 +3,7 @@
#![feature(arbitrary_self_types_pointers)]
use anyhow::{Result, bail};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Value, ValueToString, Vc};
use turbo_tasks_testing::{Registration, register, run};
......@@ -93,7 +93,7 @@ impl ValueToString for MyEnumValue {
fn to_string(&self) -> Vc<RcStr> {
match self {
MyEnumValue::Yeah(value) => Vc::cell(value.to_string().into()),
MyEnumValue::Nah => Vc::cell("nah".into()),
MyEnumValue::Nah => Vc::cell(rcstr!("nah")),
MyEnumValue::More(more) => more.to_string(),
}
}
......
......@@ -8,7 +8,7 @@ use anyhow::Result;
use auto_hash_map::AutoSet;
use rustc_hash::FxHashSet;
use tokio::time::sleep;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{CollectiblesSource, ResolvedVc, ValueToString, Vc, emit};
use turbo_tasks_testing::{Registration, register, run};
......@@ -17,7 +17,7 @@ static REGISTRATION: Registration = register!();
#[tokio::test]
async fn transitive_emitting() {
run(&REGISTRATION, || async {
let result_op = my_transitive_emitting_function("".into(), "".into());
let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!(""));
let result_val = result_op.connect().strongly_consistent().await?;
let list = result_op.peek_collectibles::<Box<dyn ValueToString>>();
assert_eq!(list.len(), 2);
......@@ -35,8 +35,8 @@ async fn transitive_emitting() {
#[tokio::test]
async fn transitive_emitting_indirect() {
run(&REGISTRATION, || async {
let result_op = my_transitive_emitting_function("".into(), "".into());
let collectibles_op = my_transitive_emitting_function_collectibles("".into(), "".into());
let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!(""));
let collectibles_op = my_transitive_emitting_function_collectibles(rcstr!(""), rcstr!(""));
let list = collectibles_op.connect().strongly_consistent().await?;
assert_eq!(list.len(), 2);
let mut expected = ["123", "42"].into_iter().collect::<FxHashSet<_>>();
......@@ -103,34 +103,34 @@ async fn taking_collectibles_extra_layer() {
#[tokio::test]
async fn taking_collectibles_parallel() {
run(&REGISTRATION, || async {
let result_op = my_transitive_emitting_function("".into(), "a".into());
let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!("a"));
let result_val = result_op.connect().strongly_consistent().await?;
let list = result_op.take_collectibles::<Box<dyn ValueToString>>();
assert_eq!(list.len(), 2);
assert_eq!(result_val.0, 0);
let result_op = my_transitive_emitting_function("".into(), "b".into());
let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!("b"));
let result_val = result_op.connect().strongly_consistent().await?;
let list = result_op.take_collectibles::<Box<dyn ValueToString>>();
assert_eq!(list.len(), 2);
assert_eq!(result_val.0, 0);
let result_op =
my_transitive_emitting_function_with_child_scope("".into(), "b".into(), "1".into());
my_transitive_emitting_function_with_child_scope(rcstr!(""), rcstr!("b"), rcstr!("1"));
let result_val = result_op.connect().strongly_consistent().await?;
let list = result_op.take_collectibles::<Box<dyn ValueToString>>();
assert_eq!(list.len(), 2);
assert_eq!(result_val.0, 0);
let result_op =
my_transitive_emitting_function_with_child_scope("".into(), "b".into(), "2".into());
my_transitive_emitting_function_with_child_scope(rcstr!(""), rcstr!("b"), rcstr!("2"));
let result_val = result_op.connect().strongly_consistent().await?;
let list = result_op.take_collectibles::<Box<dyn ValueToString>>();
assert_eq!(list.len(), 2);
assert_eq!(result_val.0, 0);
let result_op =
my_transitive_emitting_function_with_child_scope("".into(), "c".into(), "3".into());
my_transitive_emitting_function_with_child_scope(rcstr!(""), rcstr!("c"), rcstr!("3"));
let result_val = result_op.connect().strongly_consistent().await?;
let list = result_op.take_collectibles::<Box<dyn ValueToString>>();
assert_eq!(list.len(), 2);
......@@ -145,7 +145,7 @@ async fn taking_collectibles_parallel() {
#[tokio::test]
async fn taking_collectibles_with_resolve() {
run(&REGISTRATION, || async {
let result_op = my_transitive_emitting_function_with_resolve("resolve".into());
let result_op = my_transitive_emitting_function_with_resolve(rcstr!("resolve"));
result_op.connect().strongly_consistent().await?;
let list = result_op.take_collectibles::<Box<dyn ValueToString>>();
assert_eq!(list.len(), 2);
......@@ -161,7 +161,7 @@ struct Collectibles(AutoSet<ResolvedVc<Box<dyn ValueToString>>>);
#[turbo_tasks::function(operation)]
async fn my_collecting_function() -> Result<Vc<Thing>> {
let result_op = my_transitive_emitting_function("".into(), "".into());
let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!(""));
let result_vc = result_op.connect();
result_vc.await?;
result_op.take_collectibles::<Box<dyn ValueToString>>();
......@@ -182,13 +182,13 @@ async fn my_collecting_function_indirect() -> Result<Vc<Thing>> {
#[turbo_tasks::function(operation)]
async fn my_multi_emitting_function() -> Result<Vc<Thing>> {
my_transitive_emitting_function("".into(), "a".into())
my_transitive_emitting_function(rcstr!(""), rcstr!("a"))
.connect()
.await?;
my_transitive_emitting_function("".into(), "b".into())
my_transitive_emitting_function(rcstr!(""), rcstr!("b"))
.connect()
.await?;
my_emitting_function("".into()).await?;
my_emitting_function(rcstr!("")).await?;
Ok(Thing::cell(Thing(0)))
}
......
......@@ -322,6 +322,7 @@ tuple_impls! { A B C D E F G H I J K L }
#[cfg(test)]
mod tests {
use turbo_rcstr::rcstr;
use turbo_tasks_macros::TaskInput;
use super::*;
......@@ -364,7 +365,7 @@ mod tests {
)]
struct MultipleUnnamedFields(u32, RcStr);
assert_task_input(MultipleUnnamedFields(42, "42".into()));
assert_task_input(MultipleUnnamedFields(42, rcstr!("42")));
Ok(())
}
......@@ -393,7 +394,7 @@ mod tests {
assert_task_input(MultipleNamedFields {
named: 42,
other: "42".into(),
other: rcstr!("42"),
});
Ok(())
}
......@@ -406,7 +407,7 @@ mod tests {
struct GenericField<T>(T);
assert_task_input(GenericField(42));
assert_task_input(GenericField(RcStr::from("42")));
assert_task_input(GenericField(rcstr!("42")));
Ok(())
}
......@@ -448,7 +449,7 @@ mod tests {
fn test_multiple_variants_and_heterogeneous_fields() -> Result<()> {
assert_task_input(MultipleVariantsAndHeterogeneousFields::Variant5 {
named: 42,
other: "42".into(),
other: rcstr!("42"),
});
Ok(())
}
......@@ -468,12 +469,12 @@ mod tests {
assert_task_input(NestedVariants::Variant5 {
named: OneVariant::Variant,
other: "42".into(),
other: rcstr!("42"),
});
assert_task_input(NestedVariants::Variant2(
MultipleVariantsAndHeterogeneousFields::Variant5 {
named: 42,
other: "42".into(),
other: rcstr!("42"),
},
));
Ok(())
......
......@@ -97,17 +97,17 @@ impl BrowserChunkingContextBuilder {
self
}
pub fn asset_base_path(mut self, asset_base_path: ResolvedVc<Option<RcStr>>) -> Self {
pub fn asset_base_path(mut self, asset_base_path: Option<RcStr>) -> Self {
self.chunking_context.asset_base_path = asset_base_path;
self
}
pub fn chunk_base_path(mut self, chunk_base_path: ResolvedVc<Option<RcStr>>) -> Self {
pub fn chunk_base_path(mut self, chunk_base_path: Option<RcStr>) -> Self {
self.chunking_context.chunk_base_path = chunk_base_path;
self
}
pub fn chunk_suffix_path(mut self, chunk_suffix_path: ResolvedVc<Option<RcStr>>) -> Self {
pub fn chunk_suffix_path(mut self, chunk_suffix_path: Option<RcStr>) -> Self {
self.chunking_context.chunk_suffix_path = chunk_suffix_path;
self
}
......@@ -182,7 +182,7 @@ pub struct BrowserChunkingContext {
/// This path is used to compute the url to request chunks from
output_root: ResolvedVc<FileSystemPath>,
/// The relative path from the output_root to the root_path.
output_root_to_root_path: ResolvedVc<RcStr>,
output_root_to_root_path: RcStr,
/// This path is used to compute the url to request assets from
client_root: ResolvedVc<FileSystemPath>,
/// Chunks are placed at this path
......@@ -191,13 +191,13 @@ pub struct BrowserChunkingContext {
asset_root_path: ResolvedVc<FileSystemPath>,
/// Base path that will be prepended to all chunk URLs when loading them.
/// This path will not appear in chunk paths or chunk data.
chunk_base_path: ResolvedVc<Option<RcStr>>,
chunk_base_path: Option<RcStr>,
/// Suffix path that will be appended to all chunk URLs when loading them.
/// This path will not appear in chunk paths or chunk data.
chunk_suffix_path: ResolvedVc<Option<RcStr>>,
chunk_suffix_path: Option<RcStr>,
/// URL prefix that will be prepended to all static asset URLs when loading
/// them.
asset_base_path: ResolvedVc<Option<RcStr>>,
asset_base_path: Option<RcStr>,
/// Enable HMR for this chunking
enable_hot_module_replacement: bool,
/// Enable tracing for this chunking
......@@ -226,7 +226,7 @@ impl BrowserChunkingContext {
pub fn builder(
root_path: ResolvedVc<FileSystemPath>,
output_root: ResolvedVc<FileSystemPath>,
output_root_to_root_path: ResolvedVc<RcStr>,
output_root_to_root_path: RcStr,
client_root: ResolvedVc<FileSystemPath>,
chunk_root_path: ResolvedVc<FileSystemPath>,
asset_root_path: ResolvedVc<FileSystemPath>,
......@@ -243,9 +243,9 @@ impl BrowserChunkingContext {
chunk_root_path,
should_use_file_source_map_uris: false,
asset_root_path,
chunk_base_path: ResolvedVc::cell(None),
chunk_suffix_path: ResolvedVc::cell(None),
asset_base_path: ResolvedVc::cell(None),
chunk_base_path: None,
chunk_suffix_path: None,
asset_base_path: None,
enable_hot_module_replacement: false,
enable_tracing: false,
environment,
......@@ -272,13 +272,13 @@ impl BrowserChunkingContext {
}
/// Returns the asset base path.
pub fn chunk_base_path(&self) -> Vc<Option<RcStr>> {
*self.chunk_base_path
pub fn chunk_base_path(&self) -> Option<RcStr> {
self.chunk_base_path.clone()
}
/// Returns the asset suffix path.
pub fn chunk_suffix_path(&self) -> Vc<Option<RcStr>> {
*self.chunk_suffix_path
pub fn chunk_suffix_path(&self) -> Option<RcStr> {
self.chunk_suffix_path.clone()
}
/// Returns the source map type.
......@@ -367,7 +367,7 @@ impl ChunkingContext for BrowserChunkingContext {
if let Some(name) = &self.name {
Vc::cell(name.clone())
} else {
Vc::cell("unknown".into())
Vc::cell(rcstr!("unknown"))
}
}
......@@ -383,7 +383,7 @@ impl ChunkingContext for BrowserChunkingContext {
#[turbo_tasks::function]
fn output_root_to_root_path(&self) -> Vc<RcStr> {
*self.output_root_to_root_path
Vc::cell(self.output_root_to_root_path.clone())
}
#[turbo_tasks::function]
......@@ -446,7 +446,6 @@ impl ChunkingContext for BrowserChunkingContext {
format!(
"{}{}",
self.asset_base_path
.await?
.as_ref()
.map(|s| s.as_str())
.unwrap_or("/"),
......
......@@ -60,7 +60,7 @@ impl EcmascriptBrowserChunk {
impl ValueToString for EcmascriptBrowserChunk {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
Vc::cell("Ecmascript Dev Chunk".into())
Vc::cell(rcstr!("Ecmascript Dev Chunk"))
}
}
......@@ -103,7 +103,7 @@ impl OutputAsset for EcmascriptBrowserChunk {
let ident = this.ident_for_path();
Ok(this
.chunking_context
.chunk_path(Some(Vc::upcast(self)), ident, ".js".into()))
.chunk_path(Some(Vc::upcast(self)), ident, rcstr!(".js")))
}
#[turbo_tasks::function]
......@@ -158,21 +158,11 @@ impl GenerateSourceMap for EcmascriptBrowserChunk {
}
}
#[turbo_tasks::function]
fn introspectable_type() -> Vc<RcStr> {
Vc::cell("dev ecmascript chunk".into())
}
#[turbo_tasks::function]
fn introspectable_details() -> Vc<RcStr> {
Vc::cell("generates a development ecmascript chunk".into())
}
#[turbo_tasks::value_impl]
impl Introspectable for EcmascriptBrowserChunk {
#[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> {
introspectable_type()
Vc::cell(rcstr!("dev ecmascript chunk"))
}
#[turbo_tasks::function]
......@@ -182,14 +172,14 @@ impl Introspectable for EcmascriptBrowserChunk {
#[turbo_tasks::function]
fn details(&self) -> Vc<RcStr> {
introspectable_details()
Vc::cell(rcstr!("generates a development ecmascript chunk"))
}
#[turbo_tasks::function]
async fn children(&self) -> Result<Vc<IntrospectableChildren>> {
let mut children = FxIndexSet::default();
let chunk = ResolvedVc::upcast::<Box<dyn Introspectable>>(self.chunk);
children.insert((ResolvedVc::cell("chunk".into()), chunk));
children.insert((rcstr!("chunk"), chunk));
Ok(Vc::cell(children))
}
}
......@@ -78,7 +78,11 @@ impl EcmascriptBrowserEvaluateChunk {
let chunking_context = this.chunking_context.await?;
let environment = this.chunking_context.environment();
let output_root_to_root_path = this.chunking_context.output_root_to_root_path();
let output_root_to_root_path = this
.chunking_context
.output_root_to_root_path()
.owned()
.await?;
let source_maps = *this
.chunking_context
.reference_chunk_source_maps(Vc::upcast(self))
......@@ -242,7 +246,7 @@ impl EcmascriptBrowserEvaluateChunk {
impl ValueToString for EcmascriptBrowserEvaluateChunk {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
Vc::cell("Ecmascript Browser Evaluate Chunk".into())
Vc::cell(rcstr!("Ecmascript Browser Evaluate Chunk"))
}
}
......@@ -254,7 +258,7 @@ impl OutputAsset for EcmascriptBrowserEvaluateChunk {
let ident = self.ident_for_path();
Ok(this
.chunking_context
.chunk_path(Some(Vc::upcast(self)), ident, ".js".into()))
.chunk_path(Some(Vc::upcast(self)), ident, rcstr!(".js")))
}
#[turbo_tasks::function]
......
......@@ -64,7 +64,7 @@ impl EcmascriptDevChunkList {
impl ValueToString for EcmascriptDevChunkList {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
Vc::cell("Ecmascript Dev Chunk List".into())
Vc::cell(rcstr!("Ecmascript Dev Chunk List"))
}
}
......@@ -90,7 +90,7 @@ impl OutputAsset for EcmascriptDevChunkList {
let ident = AssetIdent::new(Value::new(ident));
Ok(this
.chunking_context
.chunk_path(Some(Vc::upcast(self)), ident, ".js".into()))
.chunk_path(Some(Vc::upcast(self)), ident, rcstr!(".js")))
}
#[turbo_tasks::function]
......
use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Value, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
......@@ -12,12 +13,14 @@ use turbopack_resolve::{
#[turbo_tasks::function]
fn react_refresh_request() -> Vc<Request> {
Request::parse_string("@next/react-refresh-utils/dist/runtime".into())
Request::parse_string(rcstr!("@next/react-refresh-utils/dist/runtime"))
}
#[turbo_tasks::function]
fn react_refresh_request_in_next() -> Vc<Request> {
Request::parse_string("next/dist/compiled/@next/react-refresh-utils/dist/runtime".into())
Request::parse_string(rcstr!(
"next/dist/compiled/@next/react-refresh-utils/dist/runtime"
))
}
#[turbo_tasks::value]
......@@ -84,7 +87,7 @@ impl Issue for ReactRefreshResolvingIssue {
#[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> {
StyledString::Text("Could not resolve React Refresh runtime".into()).cell()
StyledString::Text(rcstr!("Could not resolve React Refresh runtime")).cell()
}
#[turbo_tasks::function]
......@@ -101,13 +104,13 @@ impl Issue for ReactRefreshResolvingIssue {
fn description(&self) -> Vc<OptionStyledString> {
Vc::cell(Some(
StyledString::Line(vec![
StyledString::Text(
"React Refresh will be disabled.\nTo enable React Refresh, install the ".into(),
),
StyledString::Code("react-refresh".into()),
StyledString::Text(" and ".into()),
StyledString::Code("@next/react-refresh-utils".into()),
StyledString::Text(" modules.".into()),
StyledString::Text(rcstr!(
"React Refresh will be disabled.\nTo enable React Refresh, install the "
)),
StyledString::Code(rcstr!("react-refresh")),
StyledString::Text(rcstr!(" and ")),
StyledString::Code(rcstr!("@next/react-refresh-utils")),
StyledString::Text(rcstr!(" modules.")),
])
.resolved_cell(),
))
......
......@@ -8,7 +8,7 @@ use std::{
use anyhow::{Context, Result, bail};
use rustc_hash::FxHashSet;
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
ReadConsistency, ResolvedVc, TransientInstance, TryJoinIterExt, TurboTasks, Value, Vc,
apply_effects,
......@@ -208,12 +208,12 @@ async fn build_internal(
.into();
let root_path = project_fs.root().to_resolved().await?;
let project_path = root_path.join(project_relative).to_resolved().await?;
let build_output_root = output_fs.root().join("dist".into()).to_resolved().await?;
let build_output_root = output_fs.root().join(rcstr!("dist")).to_resolved().await?;
let node_env = NodeEnv::Production.cell();
let build_output_root_to_root_path = project_path
.join("dist".into())
.join(rcstr!("dist"))
.await?
.get_relative_path_to(&*root_path.await?)
.context("Project path is in root path")?;
......@@ -230,7 +230,7 @@ async fn build_internal(
NodeJsChunkingContext::builder(
project_path,
build_output_root,
ResolvedVc::cell(build_output_root_to_root_path.clone()),
build_output_root_to_root_path.clone(),
build_output_root,
build_output_root,
build_output_root,
......@@ -276,7 +276,7 @@ async fn build_internal(
.await?)
.to_vec();
let origin = PlainResolveOrigin::new(asset_context, project_fs.root().join("_".into()));
let origin = PlainResolveOrigin::new(asset_context, project_fs.root().join(rcstr!("_")));
let project_dir = &project_dir;
let entries = async move {
entry_requests
......@@ -318,7 +318,7 @@ async fn build_internal(
let mut builder = BrowserChunkingContext::builder(
project_path,
build_output_root,
ResolvedVc::cell(build_output_root_to_root_path),
build_output_root_to_root_path,
build_output_root,
build_output_root,
build_output_root,
......@@ -369,7 +369,7 @@ async fn build_internal(
let mut builder = NodeJsChunkingContext::builder(
project_path,
build_output_root,
ResolvedVc::cell(build_output_root_to_root_path),
build_output_root_to_root_path,
build_output_root,
build_output_root,
build_output_root,
......@@ -433,7 +433,7 @@ async fn build_internal(
.unwrap()
.into(),
)
.with_extension("entry.js".into()),
.with_extension(rcstr!("entry.js")),
),
ChunkGroup::Entry(
[ResolvedVc::upcast(ecmascript)].into_iter().collect(),
......@@ -458,7 +458,7 @@ async fn build_internal(
.unwrap()
.into(),
)
.with_extension("entry.js".into()),
.with_extension(rcstr!("entry.js")),
EvaluatableAssets::one(*ResolvedVc::upcast(ecmascript)),
module_graph,
OutputAssets::empty(),
......
......@@ -11,7 +11,7 @@ use std::{
use anyhow::{Context, Result};
use owo_colors::OwoColorize;
use rustc_hash::FxHashSet;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
NonLocalValue, OperationVc, ResolvedVc, TransientInstance, TurboTasks, UpdateInfo, Value, Vc,
trace::TraceRawVcs,
......@@ -271,16 +271,16 @@ async fn source(
let env = load_env(*root_path);
let build_output_root = output_fs
.root()
.join(".turbopack/build".into())
.join(rcstr!(".turbopack/build"))
.to_resolved()
.await?;
let build_output_root_to_root_path = project_path
.join(".turbopack/build".into())
.join(rcstr!(".turbopack/build"))
.await?
.get_relative_path_to(&*root_path.await?)
.context("Project path is in root path")?;
let build_output_root_to_root_path = ResolvedVc::cell(build_output_root_to_root_path);
let build_output_root_to_root_path = build_output_root_to_root_path;
let build_chunking_context = NodeJsChunkingContext::builder(
root_path,
......@@ -288,11 +288,11 @@ async fn source(
build_output_root_to_root_path,
build_output_root,
build_output_root
.join("chunks".into())
.join(rcstr!("chunks"))
.to_resolved()
.await?,
build_output_root
.join("assets".into())
.join(rcstr!("assets"))
.to_resolved()
.await?,
node_build_environment().to_resolved().await?,
......@@ -328,7 +328,7 @@ async fn source(
execution_context,
entry_requests,
server_root,
Vc::cell("/ROOT".into()),
rcstr!("/ROOT"),
env,
eager_compile,
NodeEnv::Development.cell(),
......@@ -338,7 +338,7 @@ async fn source(
.to_resolved()
.await?;
let static_source = ResolvedVc::upcast(
StaticAssetsContentSource::new(Default::default(), project_path.join("public".into()))
StaticAssetsContentSource::new(Default::default(), project_path.join(rcstr!("public")))
.to_resolved()
.await?,
);
......@@ -354,7 +354,7 @@ async fn source(
let main_source = ResolvedVc::upcast(main_source);
Ok(Vc::upcast(PrefixedRouterContentSource::new(
Default::default(),
vec![("__turbopack__".into(), introspect)],
vec![(rcstr!("__turbopack__"), introspect)],
*main_source,
)))
}
......
use anyhow::{Result, anyhow};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Value, Vc};
use turbo_tasks_env::ProcessEnv;
use turbo_tasks_fs::FileSystemPath;
......@@ -36,7 +36,7 @@ use crate::{
pub async fn get_client_chunking_context(
root_path: ResolvedVc<FileSystemPath>,
server_root: ResolvedVc<FileSystemPath>,
server_root_to_root_path: ResolvedVc<RcStr>,
server_root_to_root_path: RcStr,
environment: ResolvedVc<Environment>,
) -> Result<Vc<Box<dyn ChunkingContext>>> {
Ok(Vc::upcast(
......@@ -45,8 +45,8 @@ pub async fn get_client_chunking_context(
server_root,
server_root_to_root_path,
server_root,
server_root.join("/_chunks".into()).to_resolved().await?,
server_root.join("/_assets".into()).to_resolved().await?,
server_root.join(rcstr!("/_chunks")).to_resolved().await?,
server_root.join(rcstr!("/_assets")).to_resolved().await?,
environment,
RuntimeType::Development,
)
......@@ -76,7 +76,7 @@ pub async fn get_client_runtime_entries(
runtime_entries.push(
RuntimeEntry::Request(
request.to_resolved().await?,
project_path.join("_".into()).to_resolved().await?,
project_path.join(rcstr!("_")).to_resolved().await?,
)
.resolved_cell(),
)
......@@ -84,7 +84,7 @@ pub async fn get_client_runtime_entries(
runtime_entries.push(
RuntimeEntry::Source(ResolvedVc::upcast(
FileSource::new(embed_file_path("entry/bootstrap.ts".into()))
FileSource::new(embed_file_path(rcstr!("entry/bootstrap.ts")))
.to_resolved()
.await?,
))
......@@ -100,7 +100,7 @@ pub async fn create_web_entry_source(
execution_context: Vc<ExecutionContext>,
entry_requests: Vec<Vc<Request>>,
server_root: Vc<FileSystemPath>,
server_root_to_root_path: ResolvedVc<RcStr>,
server_root_to_root_path: RcStr,
_env: Vc<Box<dyn ProcessEnv>>,
eager_compile: bool,
node_env: Vc<NodeEnv>,
......@@ -118,7 +118,7 @@ pub async fn create_web_entry_source(
let chunking_context = get_client_chunking_context(
root_path,
server_root,
*server_root_to_root_path,
server_root_to_root_path,
compile_time_info.environment(),
)
.to_resolved()
......@@ -127,7 +127,7 @@ pub async fn create_web_entry_source(
let runtime_entries = entries.resolve_entries(asset_context);
let origin = PlainResolveOrigin::new(asset_context, root_path.join("_".into()));
let origin = PlainResolveOrigin::new(asset_context, root_path.join(rcstr!("_")));
let entries = entry_requests
.into_iter()
.map(|request| async move {
......@@ -196,7 +196,7 @@ pub async fn create_web_entry_source(
.await?;
let entry_asset = Vc::upcast(DevHtmlAsset::new(
server_root.join("index.html".into()).to_resolved().await?,
server_root.join(rcstr!("index.html")).to_resolved().await?,
entries,
));
......
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_tasks::{ReadRef, ResolvedVc, TryJoinIterExt, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_hash::Xxh3Hash64Hasher;
......@@ -40,11 +39,6 @@ impl ChunksData {
}
}
#[turbo_tasks::function]
fn module_chunk_reference_description() -> Vc<RcStr> {
Vc::cell("module chunk".into())
}
#[turbo_tasks::value_impl]
impl ChunkData {
#[turbo_tasks::function]
......
......@@ -5,7 +5,7 @@ use std::{
use anyhow::{Context, Result, anyhow};
use swc_core::ecma::preset_env::{Version, Versions};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TaskInput, Value, Vc};
use turbo_tasks_env::ProcessEnv;
......@@ -146,7 +146,7 @@ impl Environment {
let env = self;
match env.execution {
ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => {
Vc::cell(vec![".js".into(), ".node".into(), ".json".into()])
Vc::cell(vec![rcstr!(".js"), rcstr!(".node"), rcstr!(".json")])
}
ExecutionEnvironment::EdgeWorker(_) | ExecutionEnvironment::Browser(_) => {
Vc::<Vec<RcStr>>::default()
......@@ -174,11 +174,11 @@ impl Environment {
let env = self;
match env.execution {
ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => {
Vc::cell(vec!["node".into()])
Vc::cell(vec![rcstr!("node")])
}
ExecutionEnvironment::Browser(_) => Vc::<Vec<RcStr>>::default(),
ExecutionEnvironment::EdgeWorker(_) => {
Vc::cell(vec!["edge-light".into(), "worker".into()])
Vc::cell(vec![rcstr!("edge-light"), rcstr!("worker")])
}
ExecutionEnvironment::Custom(_) => todo!(),
}
......@@ -302,7 +302,7 @@ pub struct RuntimeVersions(#[turbo_tasks(trace_ignore)] pub Versions);
#[turbo_tasks::function]
pub async fn get_current_nodejs_version(env: Vc<Box<dyn ProcessEnv>>) -> Result<Vc<RcStr>> {
let path_read = env.read("PATH".into()).await?;
let path_read = env.read(rcstr!("PATH")).await?;
let path = path_read.as_ref().context("env must have PATH")?;
let mut cmd = Command::new("node");
cmd.arg("--version");
......
......@@ -9,7 +9,7 @@ use turbo_tasks::{FxIndexSet, ResolvedVc, Vc};
type VcDynIntrospectable = ResolvedVc<Box<dyn Introspectable>>;
#[turbo_tasks::value(transparent)]
pub struct IntrospectableChildren(FxIndexSet<(ResolvedVc<RcStr>, VcDynIntrospectable)>);
pub struct IntrospectableChildren(FxIndexSet<(RcStr, VcDynIntrospectable)>);
#[turbo_tasks::value_trait]
pub trait Introspectable {
......
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use super::{
......@@ -20,16 +20,11 @@ impl IntrospectableModule {
}
}
#[turbo_tasks::function]
fn ty() -> Vc<RcStr> {
Vc::cell("asset".into())
}
#[turbo_tasks::value_impl]
impl Introspectable for IntrospectableModule {
#[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> {
ty()
Vc::cell(rcstr!("asset"))
}
#[turbo_tasks::function]
......
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use super::{
......@@ -25,16 +25,11 @@ impl IntrospectableOutputAsset {
}
}
#[turbo_tasks::function]
fn ty() -> Vc<RcStr> {
Vc::cell("output asset".into())
}
#[turbo_tasks::value_impl]
impl Introspectable for IntrospectableOutputAsset {
#[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> {
ty()
Vc::cell(rcstr!("output asset"))
}
#[turbo_tasks::function]
......
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use super::{Introspectable, utils::content_to_details};
......@@ -17,16 +17,11 @@ impl IntrospectableSource {
}
}
#[turbo_tasks::function]
fn ty() -> Vc<RcStr> {
Vc::cell("source".into())
}
#[turbo_tasks::value_impl]
impl Introspectable for IntrospectableSource {
#[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> {
ty()
Vc::cell(rcstr!("source"))
}
#[turbo_tasks::function]
......
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexSet, ResolvedVc, Vc};
use turbo_tasks_fs::FileContent;
......@@ -13,39 +13,32 @@ use crate::{
reference::{ModuleReference, ModuleReferences},
};
#[turbo_tasks::function]
fn reference_ty() -> Vc<RcStr> {
Vc::cell("reference".into())
fn reference_ty() -> RcStr {
rcstr!("reference")
}
#[turbo_tasks::function]
fn parallel_reference_ty() -> Vc<RcStr> {
Vc::cell("parallel reference".into())
fn parallel_reference_ty() -> RcStr {
rcstr!("parallel reference")
}
#[turbo_tasks::function]
fn parallel_inherit_async_reference_ty() -> Vc<RcStr> {
Vc::cell("parallel reference (inherit async module)".into())
fn parallel_inherit_async_reference_ty() -> RcStr {
rcstr!("parallel reference (inherit async module)")
}
#[turbo_tasks::function]
fn async_reference_ty() -> Vc<RcStr> {
Vc::cell("async reference".into())
fn async_reference_ty() -> RcStr {
rcstr!("async reference")
}
#[turbo_tasks::function]
fn isolated_reference_ty() -> Vc<RcStr> {
Vc::cell("isolated reference".into())
fn isolated_reference_ty() -> RcStr {
rcstr!("isolated reference")
}
#[turbo_tasks::function]
fn shared_reference_ty() -> Vc<RcStr> {
Vc::cell("shared reference".into())
fn shared_reference_ty() -> RcStr {
rcstr!("shared reference")
}
#[turbo_tasks::function]
fn traced_reference_ty() -> Vc<RcStr> {
Vc::cell("traced reference".into())
fn traced_reference_ty() -> RcStr {
rcstr!("traced reference")
}
#[turbo_tasks::function]
......@@ -59,7 +52,7 @@ pub async fn content_to_details(content: Vc<AssetContent>) -> Result<Vc<RcStr>>
Err(_) => Vc::cell(format!("{} binary bytes", content.len()).into()),
}
}
FileContent::NotFound => Vc::cell("not found".into()),
FileContent::NotFound => Vc::cell(rcstr!("not found")),
},
AssetContent::Redirect { target, link_type } => {
Vc::cell(format!("redirect to {target} with type {link_type:?}").into())
......@@ -75,21 +68,27 @@ pub async fn children_from_module_references(
let mut children = FxIndexSet::default();
let references = references.await?;
for &reference in &*references {
let mut key = key;
if let Some(chunkable) =
let key = if let Some(chunkable) =
ResolvedVc::try_downcast::<Box<dyn ChunkableModuleReference>>(reference)
{
match &*chunkable.chunking_type().await? {
None => {}
Some(ChunkingType::Parallel { .. }) => key = parallel_reference_ty(),
Some(ChunkingType::Async) => key = async_reference_ty(),
Some(ChunkingType::Isolated { .. }) => key = isolated_reference_ty(),
Some(ChunkingType::Shared { .. }) => key = shared_reference_ty(),
Some(ChunkingType::Traced) => key = traced_reference_ty(),
None => key.clone(),
Some(ChunkingType::Parallel { inherit_async, .. }) => {
if *inherit_async {
parallel_inherit_async_reference_ty()
} else {
parallel_reference_ty()
}
}
Some(ChunkingType::Async) => async_reference_ty(),
Some(ChunkingType::Isolated { .. }) => isolated_reference_ty(),
Some(ChunkingType::Shared { .. }) => shared_reference_ty(),
Some(ChunkingType::Traced) => traced_reference_ty(),
}
}
} else {
key.clone()
};
let key = key.to_resolved().await?;
for &module in reference
.resolve_reference()
.resolve()
......@@ -98,7 +97,10 @@ pub async fn children_from_module_references(
.await?
.iter()
{
children.insert((key, IntrospectableModule::new(*module).to_resolved().await?));
children.insert((
key.clone(),
IntrospectableModule::new(*module).to_resolved().await?,
));
}
for &output_asset in reference
.resolve_reference()
......@@ -107,7 +109,7 @@ pub async fn children_from_module_references(
.iter()
{
children.insert((
key,
key.clone(),
IntrospectableOutputAsset::new(*output_asset)
.to_resolved()
.await?,
......@@ -121,12 +123,12 @@ pub async fn children_from_module_references(
pub async fn children_from_output_assets(
references: Vc<OutputAssets>,
) -> Result<Vc<IntrospectableChildren>> {
let key = reference_ty().to_resolved().await?;
let key = reference_ty();
let mut children = FxIndexSet::default();
let references = references.await?;
for &reference in &*references {
children.insert((
key,
key.clone(),
IntrospectableOutputAsset::new(*ResolvedVc::upcast(reference))
.to_resolved()
.await?,
......
......@@ -49,7 +49,7 @@ impl ModuleReferences {
#[turbo_tasks::value]
pub struct SingleModuleReference {
asset: ResolvedVc<Box<dyn Module>>,
description: ResolvedVc<RcStr>,
description: RcStr,
}
#[turbo_tasks::value_impl]
......@@ -64,7 +64,7 @@ impl ModuleReference for SingleModuleReference {
impl ValueToString for SingleModuleReference {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
*self.description
Vc::cell(self.description.clone())
}
}
......@@ -73,7 +73,7 @@ impl SingleModuleReference {
/// Create a new [Vc<SingleModuleReference>] that resolves to the given
/// asset.
#[turbo_tasks::function]
pub fn new(asset: ResolvedVc<Box<dyn Module>>, description: ResolvedVc<RcStr>) -> Vc<Self> {
pub fn new(asset: ResolvedVc<Box<dyn Module>>, description: RcStr) -> Vc<Self> {
Self::cell(SingleModuleReference { asset, description })
}
......@@ -87,13 +87,13 @@ impl SingleModuleReference {
#[turbo_tasks::value]
pub struct SingleChunkableModuleReference {
asset: ResolvedVc<Box<dyn Module>>,
description: ResolvedVc<RcStr>,
description: RcStr,
}
#[turbo_tasks::value_impl]
impl SingleChunkableModuleReference {
#[turbo_tasks::function]
pub fn new(asset: ResolvedVc<Box<dyn Module>>, description: ResolvedVc<RcStr>) -> Vc<Self> {
pub fn new(asset: ResolvedVc<Box<dyn Module>>, description: RcStr) -> Vc<Self> {
Self::cell(SingleChunkableModuleReference { asset, description })
}
}
......@@ -121,7 +121,7 @@ impl ModuleReference for SingleChunkableModuleReference {
impl ValueToString for SingleChunkableModuleReference {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
*self.description
Vc::cell(self.description.clone())
}
}
......@@ -129,7 +129,7 @@ impl ValueToString for SingleChunkableModuleReference {
#[turbo_tasks::value]
pub struct SingleOutputAssetReference {
asset: ResolvedVc<Box<dyn OutputAsset>>,
description: ResolvedVc<RcStr>,
description: RcStr,
}
#[turbo_tasks::value_impl]
......@@ -144,7 +144,7 @@ impl ModuleReference for SingleOutputAssetReference {
impl ValueToString for SingleOutputAssetReference {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
*self.description
Vc::cell(self.description.clone())
}
}
......@@ -153,10 +153,7 @@ impl SingleOutputAssetReference {
/// Create a new [Vc<SingleOutputAssetReference>] that resolves to the given
/// asset.
#[turbo_tasks::function]
pub fn new(
asset: ResolvedVc<Box<dyn OutputAsset>>,
description: ResolvedVc<RcStr>,
) -> Vc<Self> {
pub fn new(asset: ResolvedVc<Box<dyn OutputAsset>>, description: RcStr) -> Vc<Self> {
Self::cell(SingleOutputAssetReference { asset, description })
}
......
......@@ -10,7 +10,7 @@ use anyhow::{Result, bail};
use rustc_hash::{FxHashMap, FxHashSet};
use serde::{Deserialize, Serialize};
use tracing::{Instrument, Level};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
FxIndexMap, FxIndexSet, NonLocalValue, ReadRef, ResolvedVc, SliceMap, TaskInput,
TryJoinIterExt, Value, ValueToString, Vc, trace::TraceRawVcs,
......@@ -1270,7 +1270,7 @@ async fn imports_field(lookup_path: Vc<FileSystemPath>) -> Result<Vc<ImportsFiel
#[turbo_tasks::function]
pub fn package_json() -> Vc<Vec<RcStr>> {
Vc::cell(vec!["package.json".into()])
Vc::cell(vec![rcstr!("package.json")])
}
#[turbo_tasks::value(shared)]
......@@ -1326,7 +1326,7 @@ pub async fn find_context_file_or_package_key(
package_key: Value<RcStr>,
) -> Result<Vc<FindContextFileResult>> {
let mut refs = Vec::new();
let package_json_path = lookup_path.join("package.json".into());
let package_json_path = lookup_path.join(rcstr!("package.json"));
if let Some(package_json_path) = exists(package_json_path, &mut refs).await? {
if let Some(json) = &*read_package_json(*package_json_path).await? {
if json.get(&**package_key).is_some() {
......@@ -1519,7 +1519,7 @@ pub async fn resolve_raw(
.and_then(|pat| pat.filter_could_not_match("/ROOT/fsd8nz8og54z"))
{
let path = Pattern::new(pat);
let matches = read_matches(lookup_dir.root(), "/ROOT/".into(), true, path).await?;
let matches = read_matches(lookup_dir.root(), rcstr!("/ROOT/"), true, path).await?;
if matches.len() > 10000 {
let path_str = path.to_string().await?;
println!(
......@@ -1538,7 +1538,7 @@ pub async fn resolve_raw(
}
{
let matches = read_matches(lookup_dir, "".into(), force_in_lookup_dir, path).await?;
let matches = read_matches(lookup_dir, rcstr!(""), force_in_lookup_dir, path).await?;
if matches.len() > 10000 {
println!(
"WARN: resolving pattern {} in {} leads to {} results",
......@@ -1834,7 +1834,7 @@ async fn resolve_internal_inline(
let mut results = Vec::new();
let matches = read_matches(
lookup_path,
"".into(),
rcstr!(""),
*force_in_lookup_dir,
Pattern::new(path.clone()).resolve().await?,
)
......@@ -1927,7 +1927,7 @@ async fn resolve_internal_inline(
fragment,
} => {
let mut new_pat = path.clone();
new_pat.push_front(RcStr::from(".").into());
new_pat.push_front(rcstr!(".").into());
let relative =
Request::relative(Value::new(new_pat), query.clone(), fragment.clone(), true);
......@@ -2101,7 +2101,7 @@ async fn resolve_into_folder(
package_path: ResolvedVc<FileSystemPath>,
options: Vc<ResolveOptions>,
) -> Result<Vc<ResolveResult>> {
let package_json_path = package_path.join("package.json".into());
let package_json_path = package_path.join(rcstr!("package.json"));
let options_value = options.await?;
for resolve_into_package in options_value.into_package.iter() {
......@@ -2133,7 +2133,7 @@ async fn resolve_into_folder(
// we continue to try other alternatives
if !result.is_unresolvable_ref() {
let mut result: ResolveResultBuilder =
result.with_request_ref(".".into()).into();
result.with_request_ref(rcstr!(".")).into();
result.affecting_sources.push(ResolvedVc::upcast(
FileSource::new(package_json_path).to_resolved().await?,
));
......@@ -2166,7 +2166,7 @@ async fn resolve_into_folder(
Ok(resolve_internal_inline(*package_path, request, options)
.await?
.with_request(".".into()))
.with_request(rcstr!(".")))
}
#[tracing::instrument(level = Level::TRACE, skip_all)]
......@@ -2231,23 +2231,23 @@ async fn resolve_relative_request(
Some((base, "js")) => (
base,
vec![
Pattern::Constant(".ts".into()),
Pattern::Constant(".tsx".into()),
Pattern::Constant(".js".into()),
Pattern::Constant(rcstr!(".ts")),
Pattern::Constant(rcstr!(".tsx")),
Pattern::Constant(rcstr!(".js")),
],
),
Some((base, "mjs")) => (
base,
vec![
Pattern::Constant(".mts".into()),
Pattern::Constant(".mjs".into()),
Pattern::Constant(rcstr!(".mts")),
Pattern::Constant(rcstr!(".mjs")),
],
),
Some((base, "cjs")) => (
base,
vec![
Pattern::Constant(".cts".into()),
Pattern::Constant(".cjs".into()),
Pattern::Constant(rcstr!(".cts")),
Pattern::Constant(rcstr!(".cjs")),
],
),
_ => {
......@@ -2269,7 +2269,7 @@ async fn resolve_relative_request(
let mut results = Vec::new();
let matches = read_matches(
lookup_path,
"".into(),
rcstr!(""),
force_in_lookup_dir,
Pattern::new(new_path).resolve().await?,
)
......@@ -2588,7 +2588,7 @@ async fn resolve_module_request(
FindPackageItem::PackageFile(package_path) => {
if path.is_match("") {
let resolved = resolved(
RequestKey::new(".".into()),
RequestKey::new(rcstr!(".")),
*package_path,
lookup_path,
request,
......@@ -2606,13 +2606,13 @@ async fn resolve_module_request(
let module_result =
merge_results_with_affecting_sources(results, result.affecting_sources.clone())
.with_replaced_request_key(".".into(), Value::new(RequestKey::new(module.into())));
.with_replaced_request_key(rcstr!("."), Value::new(RequestKey::new(module.into())));
if options_value.prefer_relative {
let module_prefix: RcStr = format!("./{module}").into();
let pattern = Pattern::concat([
module_prefix.clone().into(),
RcStr::from("/").into(),
rcstr!("/").into(),
path.clone(),
]);
let relative = Request::relative(Value::new(pattern), query, fragment, true)
......@@ -2652,7 +2652,7 @@ async fn resolve_into_package(
conditions,
unspecified_conditions,
} => {
let package_json_path = package_path.join("package.json".into());
let package_json_path = package_path.join(rcstr!("package.json"));
let ExportsFieldResult::Some(exports_field) =
&*exports_field(package_json_path).await?
else {
......@@ -2700,7 +2700,7 @@ async fn resolve_into_package(
if could_match_others {
let mut new_pat = path.clone();
new_pat.push_front(RcStr::from(".").into());
new_pat.push_front(rcstr!(".").into());
let relative = Request::relative(Value::new(new_pat), query, fragment, true)
.to_resolved()
......@@ -2911,7 +2911,7 @@ async fn handle_exports_imports_field(
for (result_path, conditions) in results {
if let Some(result_path) = result_path.with_normalized_path() {
let request = Request::parse(Value::new(Pattern::Concatenation(vec![
Pattern::Constant("./".into()),
Pattern::Constant(rcstr!("./")),
result_path,
])))
.to_resolved()
......
......@@ -2,7 +2,7 @@ use std::{collections::BTreeMap, future::Future, pin::Pin};
use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
FxIndexSet, NonLocalValue, ResolvedVc, TryJoinIterExt, Value, ValueToString, Vc,
debug::ValueDebugFormat, trace::TraceRawVcs,
......@@ -463,9 +463,9 @@ impl ValueToString for ImportMapResult {
#[turbo_tasks::function]
async fn to_string(&self) -> Result<Vc<RcStr>> {
match self {
ImportMapResult::Result(_) => Ok(Vc::cell("Resolved by import map".into())),
ImportMapResult::External(_, _, _) => Ok(Vc::cell("TODO external".into())),
ImportMapResult::AliasExternal { .. } => Ok(Vc::cell("TODO external".into())),
ImportMapResult::Result(_) => Ok(Vc::cell(rcstr!("Resolved by import map"))),
ImportMapResult::External(_, _, _) => Ok(Vc::cell(rcstr!("TODO external"))),
ImportMapResult::AliasExternal { .. } => Ok(Vc::cell(rcstr!("TODO external"))),
ImportMapResult::Alias(request, context) => {
let s = if let Some(path) = context {
let path = path.to_string().await?;
......@@ -491,7 +491,7 @@ impl ValueToString for ImportMapResult {
.collect::<Vec<_>>();
Ok(Vc::cell(strings.join(" | ").into()))
}
ImportMapResult::NoEntry => Ok(Vc::cell("No import map entry".into())),
ImportMapResult::NoEntry => Ok(Vc::cell(rcstr!("No import map entry"))),
}
}
}
......
use anyhow::{Ok, Result};
use lazy_static::lazy_static;
use regex::Regex;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, Value, ValueToString, Vc};
use super::pattern::Pattern;
......@@ -124,7 +124,7 @@ impl Request {
path: Pattern::Constant(path),
..
} => path.clone(),
Request::Empty => "".into(),
Request::Empty => rcstr!(""),
Request::PackageInternal {
path: Pattern::Constant(path),
..
......@@ -158,7 +158,7 @@ impl Request {
if let Some(remainder) = r.strip_prefix("//") {
return Ok(Request::Uri {
protocol: "//".into(),
protocol: rcstr!("//"),
remainder: remainder.into(),
query: RcStr::default(),
fragment: RcStr::default(),
......@@ -380,12 +380,12 @@ impl Request {
Self::parse(Value::new(pat))
}
Request::PackageInternal { path } => {
let mut pat = Pattern::Constant("./".into());
let mut pat = Pattern::Constant(rcstr!("./"));
pat.push(path.clone());
Self::parse(Value::new(pat))
}
Request::Unknown { path } => {
let mut pat = Pattern::Constant("./".into());
let mut pat = Pattern::Constant(rcstr!("./"));
pat.push(path.clone());
Self::parse(Value::new(pat))
}
......@@ -717,7 +717,7 @@ impl Request {
}
Request::ServerRelative { path, .. } => path.clone(),
Request::Windows { path, .. } => path.clone(),
Request::Empty => Pattern::Constant("".into()),
Request::Empty => Pattern::Constant(rcstr!("")),
Request::PackageInternal { path } => path.clone(),
Request::DataUri {
media_type,
......@@ -785,7 +785,7 @@ impl ValueToString for Request {
}
Request::ServerRelative { path, .. } => format!("server relative {path}").into(),
Request::Windows { path, .. } => format!("windows {path}").into(),
Request::Empty => "empty".into(),
Request::Empty => rcstr!("empty"),
Request::PackageInternal { path } => format!("package internal {path}").into(),
Request::DataUri {
media_type,
......@@ -802,7 +802,7 @@ impl ValueToString for Request {
..
} => format!("uri \"{protocol}\" \"{remainder}\"").into(),
Request::Unknown { path } => format!("unknown {path}").into(),
Request::Dynamic => "dynamic".into(),
Request::Dynamic => rcstr!("dynamic"),
Request::Alternatives { requests } => {
let vec = requests.iter().map(|i| i.to_string()).try_join().await?;
vec.iter()
......@@ -835,7 +835,7 @@ mod tests {
fn test_split_query_fragment() {
assert_eq!(
(
Pattern::Constant("foo".into()),
Pattern::Constant(rcstr!("foo")),
RcStr::default(),
RcStr::default()
),
......@@ -845,42 +845,42 @@ mod tests {
// from `import './foo'`, ditto for fragments.
assert_eq!(
(
Pattern::Constant("foo".into()),
RcStr::from("?"),
Pattern::Constant(rcstr!("foo")),
rcstr!("?"),
RcStr::default()
),
split_off_query_fragment("foo?")
);
assert_eq!(
(
Pattern::Constant("foo".into()),
Pattern::Constant(rcstr!("foo")),
RcStr::default(),
RcStr::from("#")
rcstr!("#")
),
split_off_query_fragment("foo#")
);
assert_eq!(
(
Pattern::Constant("foo".into()),
RcStr::from("?bar=baz"),
Pattern::Constant(rcstr!("foo")),
rcstr!("?bar=baz"),
RcStr::default()
),
split_off_query_fragment("foo?bar=baz")
);
assert_eq!(
(
Pattern::Constant("foo".into()),
Pattern::Constant(rcstr!("foo")),
RcStr::default(),
RcStr::from("#stuff?bar=baz")
rcstr!("#stuff?bar=baz")
),
split_off_query_fragment("foo#stuff?bar=baz")
);
assert_eq!(
(
Pattern::Constant("foo".into()),
RcStr::from("?bar=baz"),
RcStr::from("#stuff")
Pattern::Constant(rcstr!("foo")),
rcstr!("?bar=baz"),
rcstr!("#stuff")
),
split_off_query_fragment("foo?bar=baz#stuff")
);
......
use anyhow::{Result, bail};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ValueToString, Vc};
use turbo_tasks_fs::{
FileContent, FileMeta, FileSystem, FileSystemPath, LinkContent, RawDirectoryContent,
......@@ -53,6 +53,6 @@ impl FileSystem for ServerFileSystem {
impl ValueToString for ServerFileSystem {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
Vc::cell("root-of-the-server".into())
Vc::cell(rcstr!("root-of-the-server"))
}
}
use anyhow::Result;
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
FxIndexSet, NonLocalValue, ResolvedVc, ValueToString, Vc, debug::ValueDebugFormat,
trace::TraceRawVcs,
......@@ -77,9 +77,9 @@ impl OutputAsset for SourceMapAsset {
chunking_context,
ident_for_path,
} => chunking_context
.chunk_path(Some(Vc::upcast(self)), *ident_for_path, ".js".into())
.append(".map".into()),
PathType::Fixed { path } => path.append(".map".into()),
.chunk_path(Some(Vc::upcast(self)), *ident_for_path, rcstr!(".js"))
.append(rcstr!(".map")),
PathType::Fixed { path } => path.append(rcstr!(".map")),
})
}
}
......@@ -98,21 +98,11 @@ impl Asset for SourceMapAsset {
}
}
#[turbo_tasks::function]
fn introspectable_type() -> Vc<RcStr> {
Vc::cell("source map".into())
}
#[turbo_tasks::function]
fn introspectable_details() -> Vc<RcStr> {
Vc::cell("source map of an asset".into())
}
#[turbo_tasks::value_impl]
impl Introspectable for SourceMapAsset {
#[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> {
introspectable_type()
Vc::cell(rcstr!("source map"))
}
#[turbo_tasks::function]
......@@ -122,7 +112,7 @@ impl Introspectable for SourceMapAsset {
#[turbo_tasks::function]
fn details(&self) -> Vc<RcStr> {
introspectable_details()
Vc::cell(rcstr!("source map of an asset"))
}
#[turbo_tasks::function]
......@@ -131,7 +121,7 @@ impl Introspectable for SourceMapAsset {
if let Some(asset) =
ResolvedVc::try_sidecast::<Box<dyn Introspectable>>(self.generate_source_map)
{
children.insert((ResolvedVc::cell("asset".into()), asset));
children.insert((rcstr!("asset"), asset));
}
Ok(Vc::cell(children))
}
......
......@@ -411,21 +411,11 @@ pub trait CssChunkItem: ChunkItem {
fn content(self: Vc<Self>) -> Vc<CssChunkItemContent>;
}
#[turbo_tasks::function]
fn introspectable_type() -> Vc<RcStr> {
Vc::cell("css chunk".into())
}
#[turbo_tasks::function]
fn entry_module_key() -> Vc<RcStr> {
Vc::cell("entry module".into())
}
#[turbo_tasks::value_impl]
impl Introspectable for CssChunk {
#[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> {
introspectable_type()
Vc::cell(rcstr!("css chunk"))
}
#[turbo_tasks::function]
......@@ -461,7 +451,7 @@ impl Introspectable for CssChunk {
.iter()
.map(|chunk_item| async move {
Ok((
entry_module_key().to_resolved().await?,
rcstr!("entry module"),
IntrospectableModule::new(chunk_item.module())
.to_resolved()
.await?,
......@@ -482,7 +472,7 @@ pub struct CssChunkType {}
impl ValueToString for CssChunkType {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
Vc::cell("css".into())
Vc::cell(rcstr!("css"))
}
}
......
......@@ -100,7 +100,7 @@ impl OutputAsset for SingleItemCssChunk {
Ok(self.await?.chunking_context.chunk_path(
Some(Vc::upcast(self)),
self.ident_for_path(),
".single.css".into(),
rcstr!(".single.css"),
))
}
......@@ -156,21 +156,11 @@ impl GenerateSourceMap for SingleItemCssChunk {
}
}
#[turbo_tasks::function]
fn introspectable_type() -> Vc<RcStr> {
Vc::cell("single asset css chunk".into())
}
#[turbo_tasks::function]
fn entry_module_key() -> Vc<RcStr> {
Vc::cell("entry module".into())
}
#[turbo_tasks::value_impl]
impl Introspectable for SingleItemCssChunk {
#[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> {
introspectable_type()
Vc::cell(rcstr!("single asset css chunk"))
}
#[turbo_tasks::function]
......
......@@ -13,7 +13,7 @@ use rustc_hash::FxHashMap;
use smallvec::smallvec;
use swc_core::base::sourcemap::SourceMapBuilder;
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::{FileContent, FileSystemPath, rope::Rope};
use turbopack_core::{
......@@ -434,7 +434,7 @@ async fn process_content(
ParsingIssue {
file: fs_path_vc,
msg: ResolvedVc::cell(err.to_string().into()),
msg: err.to_string().into(),
source,
}
.resolved_cell()
......@@ -471,7 +471,7 @@ async fn process_content(
};
ParsingIssue {
file: fs_path_vc,
msg: ResolvedVc::cell(e.to_string().into()),
msg: e.to_string().into(),
source,
}
.resolved_cell()
......@@ -520,9 +520,8 @@ impl CssError {
CssError::CssSelectorInModuleNotPure { selector } => {
ParsingIssue {
file,
msg: ResolvedVc::cell(
format!("{CSS_MODULE_ERROR}, (lightningcss, {selector})").into(),
),
msg: format!("{CSS_MODULE_ERROR}, (lightningcss, {selector})").into(),
source: None,
}
.resolved_cell()
......@@ -617,7 +616,7 @@ fn generate_css_source_map(source_map: &parcel_sourcemap::SourceMap) -> Result<R
#[turbo_tasks::value]
struct ParsingIssue {
msg: ResolvedVc<RcStr>,
msg: RcStr,
file: ResolvedVc<FileSystemPath>,
source: Option<IssueSource>,
}
......@@ -636,7 +635,7 @@ impl Issue for ParsingIssue {
#[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> {
StyledString::Text("Parsing css source code failed".into()).cell()
StyledString::Text(rcstr!("Parsing css source code failed")).cell()
}
#[turbo_tasks::function]
......@@ -650,7 +649,7 @@ impl Issue for ParsingIssue {
#[turbo_tasks::function]
async fn description(&self) -> Result<Vc<OptionStyledString>> {
Ok(Vc::cell(Some(
StyledString::Text(self.msg.await?.as_str().into()).resolved_cell(),
StyledString::Text(self.msg.clone()).resolved_cell(),
)))
}
}
......
......@@ -40,11 +40,6 @@ pub struct DevHtmlAsset {
body: Option<RcStr>,
}
#[turbo_tasks::function]
fn dev_html_chunk_reference_description() -> Vc<RcStr> {
Vc::cell("dev html chunk".into())
}
#[turbo_tasks::value_impl]
impl OutputAsset for DevHtmlAsset {
#[turbo_tasks::function]
......
......@@ -2,7 +2,7 @@ use std::{borrow::Cow, fmt::Display};
use anyhow::Result;
use rustc_hash::FxHashSet;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ReadRef, ResolvedVc, TryJoinIterExt, Vc};
use turbo_tasks_fs::{File, json::parse_json_with_source_context};
use turbopack_core::{
......@@ -22,22 +22,30 @@ pub struct IntrospectionSource {
pub roots: FxHashSet<ResolvedVc<Box<dyn Introspectable>>>,
}
fn introspection_source() -> RcStr {
rcstr!("introspection-source")
}
#[turbo_tasks::value_impl]
impl Introspectable for IntrospectionSource {
#[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> {
Vc::cell("introspection-source".into())
Vc::cell(introspection_source())
}
#[turbo_tasks::function]
fn title(&self) -> Vc<RcStr> {
Vc::cell("introspection-source".into())
Vc::cell(introspection_source())
}
#[turbo_tasks::function]
fn children(&self) -> Vc<IntrospectableChildren> {
let name = ResolvedVc::cell("root".into());
Vc::cell(self.roots.iter().map(|root| (name, *root)).collect())
Vc::cell(
self.roots
.iter()
.map(|root| (rcstr!("root"), *root))
.collect(),
)
}
}
......@@ -127,9 +135,7 @@ impl GetContentSourceContent for IntrospectionSource {
let has_children = !children.is_empty();
let children = children
.iter()
.map(|&(name, child)| async move {
let name = name.await;
let name = str_or_err(&name);
.map(|(name, child)| async move {
let ty = child.ty().await;
let ty = str_or_err(&ty);
let title = child.title().await;
......
......@@ -2,7 +2,7 @@ use std::{collections::VecDeque, iter::once};
use anyhow::Result;
use rustc_hash::FxHashSet;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
Completion, FxIndexMap, FxIndexSet, ResolvedVc, State, TryJoinIterExt, Value, ValueToString,
Vc, fxindexset,
......@@ -177,7 +177,7 @@ async fn expand(
}
for (sub_path, asset) in assets {
if &*sub_path == "index.html" {
map.insert("".into(), asset);
map.insert(rcstr!(""), asset);
} else if let Some(p) = sub_path.strip_suffix("/index.html") {
map.insert(p.into(), asset);
map.insert(format!("{p}/").into(), asset);
......@@ -192,7 +192,7 @@ async fn expand(
fn get_sub_paths(sub_path: &str) -> ([RcStr; 3], usize) {
let sub_paths_buffer: [RcStr; 3];
let n = if sub_path == "index.html" {
sub_paths_buffer = ["".into(), sub_path.into(), Default::default()];
sub_paths_buffer = [rcstr!(""), sub_path.into(), Default::default()];
2
} else if let Some(p) = sub_path.strip_suffix("/index.html") {
sub_paths_buffer = [p.into(), format!("{p}/").into(), sub_path.into()];
......@@ -293,16 +293,11 @@ impl ContentSourceSideEffect for AssetGraphGetContentSourceContent {
}
}
#[turbo_tasks::function]
fn introspectable_type() -> Vc<RcStr> {
Vc::cell("asset graph content source".into())
}
#[turbo_tasks::value_impl]
impl Introspectable for AssetGraphContentSource {
#[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> {
introspectable_type()
Vc::cell(rcstr!("asset graph content source"))
}
#[turbo_tasks::function]
......@@ -315,23 +310,20 @@ impl Introspectable for AssetGraphContentSource {
Vc::cell(if let Some(expanded) = &self.expanded {
format!("{} assets expanded", expanded.get().len()).into()
} else {
"eager".into()
rcstr!("eager")
})
}
#[turbo_tasks::function]
async fn children(self: Vc<Self>) -> Result<Vc<IntrospectableChildren>> {
let this = self.await?;
let key = ResolvedVc::cell("root".into());
let inner_key = ResolvedVc::cell("inner".into());
let expanded_key = ResolvedVc::cell("expanded".into());
let root_assets = this.root_assets.await?;
let root_asset_children = root_assets
.iter()
.map(|&asset| async move {
Ok((
key,
rcstr!("root"),
IntrospectableOutputAsset::new(*ResolvedVc::upcast(asset))
.to_resolved()
.await?,
......@@ -346,7 +338,7 @@ impl Introspectable for AssetGraphContentSource {
.filter(|&a| !root_assets.contains(a))
.map(|&asset| async move {
Ok((
inner_key,
rcstr!("inner"),
IntrospectableOutputAsset::new(*ResolvedVc::upcast(asset))
.to_resolved()
.await?,
......@@ -360,7 +352,7 @@ impl Introspectable for AssetGraphContentSource {
.into_iter()
.chain(expanded_asset_children)
.chain(once((
expanded_key,
rcstr!("expanded"),
ResolvedVc::upcast(FullyExpanded(self.to_resolved().await?).resolved_cell()),
)))
.collect(),
......@@ -368,11 +360,6 @@ impl Introspectable for AssetGraphContentSource {
}
}
#[turbo_tasks::function]
fn fully_expanded_introspectable_type() -> Vc<RcStr> {
Vc::cell("fully expanded asset graph content source".into())
}
#[turbo_tasks::value]
struct FullyExpanded(ResolvedVc<AssetGraphContentSource>);
......@@ -380,7 +367,7 @@ struct FullyExpanded(ResolvedVc<AssetGraphContentSource>);
impl Introspectable for FullyExpanded {
#[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> {
fully_expanded_introspectable_type()
Vc::cell(rcstr!("fully expanded asset graph content source"))
}
#[turbo_tasks::function]
......@@ -391,14 +378,16 @@ impl Introspectable for FullyExpanded {
#[turbo_tasks::function]
async fn children(&self) -> Result<Vc<IntrospectableChildren>> {
let source = self.0.await?;
let key = ResolvedVc::cell("asset".into());
let expanded_assets =
expand(&*source.root_assets.await?, &*source.root_path.await?, None).await?;
let children = expanded_assets
.iter()
.map(|(_k, &v)| async move {
Ok((key, IntrospectableOutputAsset::new(*v).to_resolved().await?))
Ok((
rcstr!("asset"),
IntrospectableOutputAsset::new(*v).to_resolved().await?,
))
})
.try_join()
.await?
......
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc};
use turbopack_core::introspect::{Introspectable, IntrospectableChildren};
......@@ -47,7 +47,7 @@ impl ContentSource for CombinedContentSource {
impl Introspectable for CombinedContentSource {
#[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> {
Vc::cell("combined content source".into())
Vc::cell(rcstr!("combined content source"))
}
#[turbo_tasks::function]
......@@ -85,7 +85,6 @@ impl Introspectable for CombinedContentSource {
#[turbo_tasks::function]
async fn children(&self) -> Result<Vc<IntrospectableChildren>> {
let source = ResolvedVc::cell("source".into());
Ok(Vc::cell(
self.sources
.iter()
......@@ -95,7 +94,7 @@ impl Introspectable for CombinedContentSource {
.await?
.into_iter()
.flatten()
.map(|i| (source, i))
.map(|i| (rcstr!("source"), i))
.collect(),
))
}
......
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Value, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
......@@ -156,7 +156,7 @@ impl Introspectable for IssueFilePathContentSource {
if let Some(source) = ResolvedVc::try_sidecast::<Box<dyn Introspectable>>(self.source) {
source.ty()
} else {
Vc::cell("IssueContextContentSource".into())
Vc::cell(rcstr!("IssueContextContentSource"))
},
)
}
......
use std::iter::once;
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, Value, Vc};
use turbopack_core::introspect::{Introspectable, IntrospectableChildren};
......@@ -63,14 +63,9 @@ async fn get_introspection_children(
.iter()
.cloned()
.chain(std::iter::once((RcStr::default(), *fallback)))
.map(|(path, source)| async move {
Ok(ResolvedVc::try_sidecast::<Box<dyn Introspectable>>(source)
.map(|i| (ResolvedVc::cell(path), i)))
.filter_map(|(path, source)| {
ResolvedVc::try_sidecast::<Box<dyn Introspectable>>(source).map(|i| (path, i))
})
.try_join()
.await?
.into_iter()
.flatten()
.collect(),
))
}
......@@ -169,7 +164,7 @@ impl GetContentSourceContent for PrefixedRouterGetContentSourceContent {
let prefix = self.mapper.await?.prefix.await?;
if let Some(path) = path.strip_prefix(&**prefix) {
if path.is_empty() {
return Ok(self.get_content.get("".into(), data));
return Ok(self.get_content.get(RcStr::default(), data));
} else if prefix.is_empty() {
return Ok(self.get_content.get(path.into(), data));
} else if let Some(path) = path.strip_prefix('/') {
......@@ -184,7 +179,7 @@ impl GetContentSourceContent for PrefixedRouterGetContentSourceContent {
impl Introspectable for PrefixedRouterContentSource {
#[turbo_tasks::function]
fn ty(&self) -> Vc<RcStr> {
Vc::cell("prefixed router content source".into())
Vc::cell(rcstr!("prefixed router content source"))
}
#[turbo_tasks::function]
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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