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

[turbopack] Adopt rcstr! more consistently (#80552)

Replace construction of `RcStr` instances on constant strings with the `rcstr!` macro which can shift construction costs to compile time and eliminate reference counting.

Performance impacts from all the dropped ref counts are minor but do exist

![image.png](https://graphite-user-uploaded-assets-prod.s3.amazonaws.com/AwJ29EfoPcPdLSwCZxAz/e82b0e64-5803-4883-a89f-3090f1e937ce.png)

There is also a small progression in max heap which makes sense, laying out the static rcstrs should be a somewhat easier job compared to mimalloc.
parent f6431004
...@@ -17,7 +17,7 @@ use next_api::{ ...@@ -17,7 +17,7 @@ use next_api::{
use serde_json::json; use serde_json::json;
use tempfile::TempDir; use tempfile::TempDir;
use tokio::runtime::Runtime; use tokio::runtime::Runtime;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
TransientInstance, TurboTasks, TurboTasksApi, Vc, backend::Backend, trace::TraceRawVcs, TransientInstance, TurboTasks, TurboTasksApi, Vc, backend::Backend, trace::TraceRawVcs,
}; };
...@@ -182,7 +182,7 @@ impl HmrBenchmark { ...@@ -182,7 +182,7 @@ impl HmrBenchmark {
let test_app = create_test_app(module_count)?; let test_app = create_test_app(module_count)?;
let project_container = { let project_container = {
let container = ProjectContainer::new(RcStr::from("hmr-benchmark"), true) let container = ProjectContainer::new(rcstr!("hmr-benchmark"), true)
.to_resolved() .to_resolved()
.await?; .await?;
...@@ -193,7 +193,7 @@ impl HmrBenchmark { ...@@ -193,7 +193,7 @@ impl HmrBenchmark {
root_path: RcStr::from(root_path), root_path: RcStr::from(root_path),
project_path: RcStr::from(project_path.clone()), project_path: RcStr::from(project_path.clone()),
next_config: load_next_config(), next_config: load_next_config(),
js_config: RcStr::from("{}"), js_config: rcstr!("{}"),
env: vec![], env: vec![],
define_env: DefineEnv { define_env: DefineEnv {
client: vec![], client: vec![],
...@@ -205,14 +205,14 @@ impl HmrBenchmark { ...@@ -205,14 +205,14 @@ impl HmrBenchmark {
poll_interval: None, poll_interval: None,
}, },
dev: true, dev: true,
encryption_key: RcStr::from("test-key"), encryption_key: rcstr!("test-key"),
build_id: RcStr::from("development"), build_id: rcstr!("development"),
preview_props: DraftModeOptions { preview_props: DraftModeOptions {
preview_mode_id: RcStr::from("development"), preview_mode_id: rcstr!("development"),
preview_mode_encryption_key: RcStr::from("test-key"), preview_mode_encryption_key: rcstr!("test-key"),
preview_mode_signing_key: RcStr::from("test-key"), preview_mode_signing_key: rcstr!("test-key"),
}, },
browserslist_query: RcStr::from("last 2 versions"), browserslist_query: rcstr!("last 2 versions"),
no_mangling: false, no_mangling: false,
current_node_js_version: RcStr::from("18.0.0"), current_node_js_version: RcStr::from("18.0.0"),
}; };
......
...@@ -12,7 +12,7 @@ use next_core::{ ...@@ -12,7 +12,7 @@ use next_core::{
}; };
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
CollectiblesSource, FxIndexMap, ReadRef, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, CollectiblesSource, FxIndexMap, ReadRef, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt,
ValueToString, Vc, ValueToString, Vc,
...@@ -440,15 +440,16 @@ impl Issue for CssGlobalImportIssue { ...@@ -440,15 +440,16 @@ impl Issue for CssGlobalImportIssue {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn title(&self) -> Vc<StyledString> { async fn title(&self) -> Vc<StyledString> {
StyledString::Stack(vec![ StyledString::Stack(vec![
StyledString::Text("Failed to compile".into()), StyledString::Text(rcstr!("Failed to compile")),
StyledString::Text( StyledString::Text(rcstr!(
"Global CSS cannot be imported from files other than your Custom <App>. Due to \ "Global CSS cannot be imported from files other than your Custom <App>. Due to \
the Global nature of stylesheets, and to avoid conflicts, Please move all \ the Global nature of stylesheets, and to avoid conflicts, Please move all \
first-party global CSS imports to pages/_app.js. Or convert the import to \ first-party global CSS imports to pages/_app.js. Or convert the import to \
Component-Level CSS (CSS Modules)." Component-Level CSS (CSS Modules)."
.into(), )),
), StyledString::Text(rcstr!(
StyledString::Text("Read more: https://nextjs.org/docs/messages/css-global".into()), "Read more: https://nextjs.org/docs/messages/css-global"
)),
]) ])
.cell() .cell()
} }
......
...@@ -8,7 +8,7 @@ use next_core::{ ...@@ -8,7 +8,7 @@ use next_core::{
util::NextRuntime, util::NextRuntime,
}; };
use swc_core::{ use swc_core::{
atoms::Atom, atoms::{Atom, atom},
common::comments::Comments, common::comments::Comments,
ecma::{ ecma::{
ast::{ ast::{
...@@ -321,7 +321,7 @@ fn all_export_names(program: &Program) -> Vec<Atom> { ...@@ -321,7 +321,7 @@ fn all_export_names(program: &Program) -> Vec<Atom> {
ModuleItem::ModuleDecl( ModuleItem::ModuleDecl(
ModuleDecl::ExportDefaultExpr(..) | ModuleDecl::ExportDefaultDecl(..), ModuleDecl::ExportDefaultExpr(..) | ModuleDecl::ExportDefaultDecl(..),
) => { ) => {
exports.push("default".into()); exports.push(atom!("default"));
} }
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(decl)) => match &decl.decl { ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(decl)) => match &decl.decl {
Decl::Class(c) => { Decl::Class(c) => {
...@@ -354,7 +354,7 @@ fn all_export_names(program: &Program) -> Vec<Atom> { ...@@ -354,7 +354,7 @@ fn all_export_names(program: &Program) -> Vec<Atom> {
); );
} }
ExportSpecifier::Default(_) => { ExportSpecifier::Default(_) => {
exports.push("default".into()); exports.push(atom!("default"));
} }
ExportSpecifier::Namespace(e) => { ExportSpecifier::Namespace(e) => {
exports.push(e.name.atom().clone()); exports.push(e.name.atom().clone());
......
...@@ -2,7 +2,7 @@ use anyhow::Result; ...@@ -2,7 +2,7 @@ use anyhow::Result;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use serde::Serialize; use serde::Serialize;
use tracing::{Level, instrument}; use tracing::{Level, instrument};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
FxIndexMap, FxIndexSet, ResolvedVc, TryJoinIterExt, ValueToString, Vc, fxindexmap, FxIndexMap, FxIndexSet, ResolvedVc, TryJoinIterExt, ValueToString, Vc, fxindexmap,
}; };
...@@ -94,7 +94,7 @@ where ...@@ -94,7 +94,7 @@ where
}; };
for asset in entry_assets { for asset in entry_assets {
let path = RcStr::from(normalize_client_path(&asset.path().await?.path)); let path = normalize_client_path(&asset.path().await?.path);
let Some(asset_len) = *asset.size_bytes().await? else { let Some(asset_len) = *asset.size_bytes().await? else {
continue; continue;
...@@ -108,7 +108,7 @@ where ...@@ -108,7 +108,7 @@ where
parents: if let Some(parents) = asset_parents.get(&asset) { parents: if let Some(parents) = asset_parents.get(&asset) {
parents parents
.iter() .iter()
.map(async |c| Ok(normalize_client_path(&c.path().await?.path).into())) .map(async |c| Ok(normalize_client_path(&c.path().await?.path)))
.try_join() .try_join()
.await? .await?
} else { } else {
...@@ -117,7 +117,7 @@ where ...@@ -117,7 +117,7 @@ where
children: if let Some(children) = asset_children.get(&asset) { children: if let Some(children) = asset_children.get(&asset) {
children children
.iter() .iter()
.map(async |c| Ok(normalize_client_path(&c.path().await?.path).into())) .map(async |c| Ok(normalize_client_path(&c.path().await?.path)))
.try_join() .try_join()
.await? .await?
} else { } else {
...@@ -132,7 +132,7 @@ where ...@@ -132,7 +132,7 @@ where
} }
assets.push(WebpackStatsAsset { assets.push(WebpackStatsAsset {
ty: "asset".into(), ty: rcstr!("asset"),
name: path.clone(), name: path.clone(),
chunk_names: vec![path], chunk_names: vec![path],
size: asset_len, size: asset_len,
...@@ -191,7 +191,7 @@ where ...@@ -191,7 +191,7 @@ where
}) })
} }
fn normalize_client_path(path: &str) -> String { fn normalize_client_path(path: &str) -> RcStr {
let next_re = regex::Regex::new(r"^_next/").unwrap(); let next_re = regex::Regex::new(r"^_next/").unwrap();
next_re.replace(path, ".next/").into() next_re.replace(path, ".next/").into()
} }
......
...@@ -11,7 +11,7 @@ use next_api::{ ...@@ -11,7 +11,7 @@ use next_api::{
project::{ProjectContainer, ProjectOptions}, project::{ProjectContainer, ProjectOptions},
route::{Endpoint, EndpointOutputPaths, Route, endpoint_write_to_disk}, route::{Endpoint, EndpointOutputPaths, Route, endpoint_write_to_disk},
}; };
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ReadConsistency, ResolvedVc, TransientInstance, TurboTasks, Vc, get_effects}; use turbo_tasks::{ReadConsistency, ResolvedVc, TransientInstance, TurboTasks, Vc, get_effects};
use turbo_tasks_backend::{NoopBackingStorage, TurboTasksBackend}; use turbo_tasks_backend::{NoopBackingStorage, TurboTasksBackend};
use turbo_tasks_malloc::TurboMalloc; use turbo_tasks_malloc::TurboMalloc;
...@@ -41,7 +41,7 @@ pub async fn main_inner( ...@@ -41,7 +41,7 @@ pub async fn main_inner(
let project = tt let project = tt
.run_once(async { .run_once(async {
let project = ProjectContainer::new("next-build-test".into(), options.dev); let project = ProjectContainer::new(rcstr!("next-build-test"), options.dev);
let project = project.to_resolved().await?; let project = project.to_resolved().await?;
project.initialize(options).await?; project.initialize(options).await?;
Ok(project) Ok(project)
......
...@@ -12,6 +12,7 @@ use next_core::tracing_presets::{ ...@@ -12,6 +12,7 @@ use next_core::tracing_presets::{
TRACING_NEXT_TURBOPACK_TARGETS, TRACING_NEXT_TURBOPACK_TARGETS,
}; };
use tracing_subscriber::{Registry, layer::SubscriberExt, util::SubscriberInitExt}; use tracing_subscriber::{Registry, layer::SubscriberExt, util::SubscriberInitExt};
use turbo_rcstr::rcstr;
use turbo_tasks::TurboTasks; use turbo_tasks::TurboTasks;
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage}; use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_malloc::TurboMalloc; use turbo_tasks_malloc::TurboMalloc;
...@@ -159,30 +160,30 @@ fn main() { ...@@ -159,30 +160,30 @@ fn main() {
let canonical_path = std::fs::canonicalize(absolute_dir).unwrap(); let canonical_path = std::fs::canonicalize(absolute_dir).unwrap();
let options = ProjectOptions { let options = ProjectOptions {
build_id: "test".into(), build_id: rcstr!("test"),
define_env: DefineEnv { define_env: DefineEnv {
client: vec![], client: vec![],
edge: vec![], edge: vec![],
nodejs: vec![], nodejs: vec![],
}, },
dev: true, dev: true,
encryption_key: "deadbeef".into(), encryption_key: rcstr!("deadbeef"),
env: vec![], env: vec![],
js_config: include_str!("../jsConfig.json").into(), js_config: include_str!("../jsConfig.json").into(),
next_config: include_str!("../nextConfig.json").into(), next_config: include_str!("../nextConfig.json").into(),
preview_props: next_api::project::DraftModeOptions { preview_props: next_api::project::DraftModeOptions {
preview_mode_encryption_key: "deadbeef".into(), preview_mode_encryption_key: rcstr!("deadbeef"),
preview_mode_id: "test".into(), preview_mode_id: rcstr!("test"),
preview_mode_signing_key: "deadbeef".into(), preview_mode_signing_key: rcstr!("deadbeef"),
}, },
project_path: canonical_path.to_string_lossy().into(), project_path: canonical_path.to_string_lossy().into(),
root_path: "/".into(), root_path: rcstr!("/"),
watch: Default::default(), watch: Default::default(),
browserslist_query: "last 1 Chrome versions, last 1 Firefox versions, last 1 \ browserslist_query: "last 1 Chrome versions, last 1 Firefox versions, last 1 \
Safari versions, last 1 Edge versions" Safari versions, last 1 Edge versions"
.into(), .into(),
no_mangling: false, no_mangling: false,
current_node_js_version: "18.0.0".into(), current_node_js_version: rcstr!("18.0.0"),
}; };
let json = serde_json::to_string_pretty(&options).unwrap(); let json = serde_json::to_string_pretty(&options).unwrap();
......
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use turbo_rcstr::rcstr;
use turbo_tasks::{FxIndexMap, ResolvedVc, ValueToString, Vc}; use turbo_tasks::{FxIndexMap, ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::{File, FileSystemPath}; use turbo_tasks_fs::{File, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
...@@ -92,8 +93,8 @@ pub async fn bootstrap( ...@@ -92,8 +93,8 @@ pub async fn bootstrap(
.await?; .await?;
let mut inner_assets = inner_assets.owned().await?; let mut inner_assets = inner_assets.owned().await?;
inner_assets.insert("ENTRY".into(), asset); inner_assets.insert(rcstr!("ENTRY"), asset);
inner_assets.insert("BOOTSTRAP_CONFIG".into(), config_asset); inner_assets.insert(rcstr!("BOOTSTRAP_CONFIG"), config_asset);
let asset = asset_context let asset = asset_context
.process( .process(
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, ResolvedVc, Vc, fxindexmap}; use turbo_tasks::{FxIndexMap, ResolvedVc, Vc, fxindexmap};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{context::AssetContext, module::Module, reference_type::ReferenceType}; use turbopack_core::{context::AssetContext, module::Module, reference_type::ReferenceType};
...@@ -27,15 +27,15 @@ pub async fn get_middleware_module( ...@@ -27,15 +27,15 @@ pub async fn get_middleware_module(
project_root: FileSystemPath, project_root: FileSystemPath,
userland_module: ResolvedVc<Box<dyn Module>>, userland_module: ResolvedVc<Box<dyn Module>>,
) -> Result<Vc<Box<dyn Module>>> { ) -> Result<Vc<Box<dyn Module>>> {
const INNER: &str = "INNER_MIDDLEWARE_MODULE"; let inner = rcstr!("INNER_MIDDLEWARE_MODULE");
// Load the file from the next.js codebase. // Load the file from the next.js codebase.
let source = load_next_js_template( let source = load_next_js_template(
"middleware.js", "middleware.js",
project_root, project_root,
fxindexmap! { fxindexmap! {
"VAR_USERLAND" => INNER.into(), "VAR_USERLAND" => inner.clone(),
"VAR_DEFINITION_PAGE" => "/middleware".into(), "VAR_DEFINITION_PAGE" => rcstr!("/middleware"),
}, },
FxIndexMap::default(), FxIndexMap::default(),
FxIndexMap::default(), FxIndexMap::default(),
...@@ -43,7 +43,7 @@ pub async fn get_middleware_module( ...@@ -43,7 +43,7 @@ pub async fn get_middleware_module(
.await?; .await?;
let inner_assets = fxindexmap! { let inner_assets = fxindexmap! {
INNER.into() => userland_module inner => userland_module
}; };
let module = asset_context let module = asset_context
......
use std::io::Write; use std::io::Write;
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc, fxindexmap}; use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc, fxindexmap};
use turbo_tasks_fs::{self, File, FileSystemPath, rope::RopeBuilder}; use turbo_tasks_fs::{self, File, FileSystemPath, rope::RopeBuilder};
use turbopack::ModuleAssetContext; use turbopack::ModuleAssetContext;
...@@ -92,7 +92,7 @@ pub async fn get_app_page_entry( ...@@ -92,7 +92,7 @@ pub async fn get_app_page_entry(
"VAR_MODULE_GLOBAL_ERROR" => if inner_assets.contains_key(GLOBAL_ERROR) { "VAR_MODULE_GLOBAL_ERROR" => if inner_assets.contains_key(GLOBAL_ERROR) {
GLOBAL_ERROR.into() GLOBAL_ERROR.into()
} else { } else {
"next/dist/client/components/builtin/global-error".into() rcstr!("next/dist/client/components/builtin/global-error")
}, },
}, },
fxindexmap! { fxindexmap! {
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc, fxindexmap}; use turbo_tasks::{ResolvedVc, Vc, fxindexmap};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack::ModuleAssetContext; use turbopack::ModuleAssetContext;
...@@ -57,18 +57,17 @@ pub async fn get_app_route_entry( ...@@ -57,18 +57,17 @@ pub async fn get_app_route_entry(
let path = source.ident().path().owned().await?; let path = source.ident().path().owned().await?;
const INNER: &str = "INNER_APP_ROUTE"; let inner = rcstr!("INNER_APP_ROUTE");
let output_type: RcStr = next_config let output_type: RcStr = next_config
.await? .await?
.output .output
.as_ref() .as_ref()
.map(|o| match o { .map(|o| match o {
OutputType::Standalone => "\"standalone\"".to_string(), OutputType::Standalone => rcstr!("\"standalone\""),
OutputType::Export => "\"export\"".to_string(), OutputType::Export => rcstr!("\"export\""),
}) })
.map(RcStr::from) .unwrap_or(rcstr!("\"\""));
.unwrap_or_else(|| "\"\"".into());
// Load the file from the next.js codebase. // Load the file from the next.js codebase.
let virtual_source = load_next_js_template( let virtual_source = load_next_js_template(
...@@ -81,7 +80,7 @@ pub async fn get_app_route_entry( ...@@ -81,7 +80,7 @@ pub async fn get_app_route_entry(
// TODO(alexkirsz) Is this necessary? // TODO(alexkirsz) Is this necessary?
"VAR_DEFINITION_BUNDLE_PATH" => "".to_string().into(), "VAR_DEFINITION_BUNDLE_PATH" => "".to_string().into(),
"VAR_RESOLVED_PAGE_PATH" => path.value_to_string().owned().await?, "VAR_RESOLVED_PAGE_PATH" => path.value_to_string().owned().await?,
"VAR_USERLAND" => INNER.into(), "VAR_USERLAND" => inner.clone(),
}, },
fxindexmap! { fxindexmap! {
"nextConfigOutput" => output_type "nextConfigOutput" => output_type
...@@ -100,7 +99,7 @@ pub async fn get_app_route_entry( ...@@ -100,7 +99,7 @@ pub async fn get_app_route_entry(
.await?; .await?;
let inner_assets = fxindexmap! { let inner_assets = fxindexmap! {
INNER.into() => userland_module inner => userland_module
}; };
let mut rsc_entry = module_asset_context let mut rsc_entry = module_asset_context
...@@ -137,7 +136,7 @@ async fn wrap_edge_route( ...@@ -137,7 +136,7 @@ async fn wrap_edge_route(
page: AppPage, page: AppPage,
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
) -> Result<Vc<Box<dyn Module>>> { ) -> Result<Vc<Box<dyn Module>>> {
const INNER: &str = "INNER_ROUTE_ENTRY"; let inner = rcstr!("INNER_ROUTE_ENTRY");
let next_config = &*next_config.await?; let next_config = &*next_config.await?;
...@@ -145,7 +144,7 @@ async fn wrap_edge_route( ...@@ -145,7 +144,7 @@ async fn wrap_edge_route(
"edge-app-route.js", "edge-app-route.js",
project_root.clone(), project_root.clone(),
fxindexmap! { fxindexmap! {
"VAR_USERLAND" => INNER.into(), "VAR_USERLAND" => inner.clone(),
"VAR_PAGE" => page.to_string().into(), "VAR_PAGE" => page.to_string().into(),
}, },
fxindexmap! { fxindexmap! {
...@@ -156,7 +155,7 @@ async fn wrap_edge_route( ...@@ -156,7 +155,7 @@ async fn wrap_edge_route(
.await?; .await?;
let inner_assets = fxindexmap! { let inner_assets = fxindexmap! {
INNER.into() => entry inner => entry
}; };
let wrapped = asset_context let wrapped = asset_context
......
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
use anyhow::{Ok, Result, bail}; use anyhow::{Ok, Result, bail};
use base64::{display::Base64Display, engine::general_purpose::STANDARD}; use base64::{display::Base64Display, engine::general_purpose::STANDARD};
use indoc::{formatdoc, indoc}; use indoc::{formatdoc, indoc};
use turbo_rcstr::rcstr;
use turbo_tasks::Vc; use turbo_tasks::Vc;
use turbo_tasks_fs::{self, File, FileContent, FileSystemPath}; use turbo_tasks_fs::{self, File, FileContent, FileSystemPath};
use turbopack::ModuleAssetContext; use turbopack::ModuleAssetContext;
...@@ -83,12 +84,12 @@ pub async fn get_app_metadata_route_entry( ...@@ -83,12 +84,12 @@ pub async fn get_app_metadata_route_entry(
page.0.pop(); page.0.pop();
if is_multi_dynamic { if is_multi_dynamic {
page.push(PageSegment::Dynamic("__metadata_id__".into()))?; page.push(PageSegment::Dynamic(rcstr!("__metadata_id__")))?;
} else { } else {
// if page last segment is sitemap, change to sitemap.xml // if page last segment is sitemap, change to sitemap.xml
if page.last() == Some(&PageSegment::Static("sitemap".into())) { if page.last() == Some(&PageSegment::Static(rcstr!("sitemap"))) {
page.0.pop(); page.0.pop();
page.push(PageSegment::Static("sitemap.xml".into()))? page.push(PageSegment::Static(rcstr!("sitemap.xml")))?
} }
}; };
// Push /route back // Push /route back
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::Vc; use turbo_tasks::Vc;
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::resolve::{ExternalTraced, ExternalType, options::ImportMapping}; use turbopack_core::resolve::{ExternalTraced, ExternalType, options::ImportMapping};
...@@ -12,10 +12,10 @@ pub async fn get_postcss_package_mapping( ...@@ -12,10 +12,10 @@ pub async fn get_postcss_package_mapping(
) -> Result<Vc<ImportMapping>> { ) -> Result<Vc<ImportMapping>> {
Ok(ImportMapping::Alternatives(vec![ Ok(ImportMapping::Alternatives(vec![
// Prefer the local installed version over the next.js version // Prefer the local installed version over the next.js version
ImportMapping::PrimaryAlternative("postcss".into(), Some(project_path.clone())) ImportMapping::PrimaryAlternative(rcstr!("postcss"), Some(project_path.clone()))
.resolved_cell(), .resolved_cell(),
ImportMapping::PrimaryAlternative( ImportMapping::PrimaryAlternative(
"postcss".into(), rcstr!("postcss"),
Some(get_next_package(project_path.clone()).owned().await?), Some(get_next_package(project_path.clone()).owned().await?),
) )
.resolved_cell(), .resolved_cell(),
......
...@@ -1170,10 +1170,10 @@ impl Issue for InvalidLoaderRuleError { ...@@ -1170,10 +1170,10 @@ impl Issue for InvalidLoaderRuleError {
.into(), .into(),
), ),
StyledString::Text( StyledString::Text(
"Check out the documentation here for more information:".into(), rcstr!("Check out the documentation here for more information:"),
), ),
StyledString::Text( StyledString::Text(
"https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#configuring-webpack-loaders".into(), rcstr!("https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#configuring-webpack-loaders"),
), ),
]).resolved_cell()))) ]).resolved_cell())))
} }
......
use anyhow::Result; use anyhow::Result;
use indoc::formatdoc; use indoc::formatdoc;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc, fxindexmap}; use turbo_tasks::{ResolvedVc, Vc, fxindexmap};
use turbo_tasks_fs::{File, FileSystemPath}; use turbo_tasks_fs::{File, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
...@@ -51,7 +51,7 @@ pub fn wrap_edge_entry( ...@@ -51,7 +51,7 @@ pub fn wrap_edge_entry(
); );
let inner_assets = fxindexmap! { let inner_assets = fxindexmap! {
"MODULE".into() => entry rcstr!("MODULE") => entry
}; };
Ok(asset_context Ok(asset_context
......
use std::{cmp::Ordering, collections::BTreeSet}; use std::{cmp::Ordering, collections::BTreeSet};
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::FxIndexSet; use turbo_tasks::FxIndexSet;
use super::options::{FontData, FontWeights}; use super::options::{FontData, FontWeights};
...@@ -47,8 +47,8 @@ pub(super) fn get_font_axes( ...@@ -47,8 +47,8 @@ pub(super) fn get_font_axes(
.axes; .axes;
let ital = { let ital = {
let has_italic = styles.contains(&"italic".into()); let has_italic = styles.contains(&rcstr!("italic"));
let has_normal = styles.contains(&"normal".into()); let has_normal = styles.contains(&rcstr!("normal"));
let mut set = FxIndexSet::default(); let mut set = FxIndexSet::default();
if has_normal { if has_normal {
set.insert(FontStyle::Normal); set.insert(FontStyle::Normal);
...@@ -291,6 +291,7 @@ mod tests { ...@@ -291,6 +291,7 @@ mod tests {
use std::collections::BTreeSet; use std::collections::BTreeSet;
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::fxindexset; use turbo_tasks::fxindexset;
use turbo_tasks_fs::json::parse_json_with_source_context; use turbo_tasks_fs::json::parse_json_with_source_context;
...@@ -381,12 +382,12 @@ mod tests { ...@@ -381,12 +382,12 @@ mod tests {
"Inter", "Inter",
&FontWeights::Variable, &FontWeights::Variable,
&[], &[],
&Some(vec!["slnt".into()]), &Some(vec![rcstr!("slnt")]),
)?, )?,
FontAxes { FontAxes {
wght: FontAxesWeights::Variable(Some("100..900".into())), wght: FontAxesWeights::Variable(Some(rcstr!("100..900"))),
ital: fxindexset! {}, ital: fxindexset! {},
variable_axes: Some(vec![("slnt".into(), "-10..0".into())]) variable_axes: Some(vec![(rcstr!("slnt"), rcstr!("-10..0"))])
} }
); );
Ok(()) Ok(())
...@@ -422,10 +423,10 @@ mod tests { ...@@ -422,10 +423,10 @@ mod tests {
"Inter", "Inter",
&FontWeights::Variable, &FontWeights::Variable,
&[], &[],
&Some(vec!["slnt".into()]), &Some(vec![rcstr!("slnt")]),
)?, )?,
FontAxes { FontAxes {
variable_axes: Some(vec![("slnt".into(), "-10..0".into())]), variable_axes: Some(vec![(rcstr!("slnt"), rcstr!("-10..0"))]),
wght: FontAxesWeights::Variable(None), wght: FontAxesWeights::Variable(None),
..Default::default() ..Default::default()
} }
...@@ -493,9 +494,9 @@ mod tests { ...@@ -493,9 +494,9 @@ mod tests {
wght: FontAxesWeights::Fixed(BTreeSet::from([500])), wght: FontAxesWeights::Fixed(BTreeSet::from([500])),
ital: fxindexset! {FontStyle::Normal}, ital: fxindexset! {FontStyle::Normal},
variable_axes: Some(vec![ variable_axes: Some(vec![
("GRAD".into(), "-50..100".into()), (rcstr!("GRAD"), rcstr!("-50..100")),
("opsz".into(), "8..144".into()), (rcstr!("opsz"), rcstr!("8..144")),
("wdth".into(), "50..150".into()), (rcstr!("wdth"), rcstr!("50..150")),
]) ])
}, },
"optional" "optional"
...@@ -535,9 +536,9 @@ mod tests { ...@@ -535,9 +536,9 @@ mod tests {
wght: FontAxesWeights::Fixed(BTreeSet::from([500, 300])), wght: FontAxesWeights::Fixed(BTreeSet::from([500, 300])),
ital: fxindexset! {FontStyle::Normal, FontStyle::Italic}, ital: fxindexset! {FontStyle::Normal, FontStyle::Italic},
variable_axes: Some(vec![ variable_axes: Some(vec![
("GRAD".into(), "-50..100".into()), (rcstr!("GRAD"), rcstr!("-50..100")),
("opsz".into(), "8..144".into()), (rcstr!("opsz"), rcstr!("8..144")),
("wdth".into(), "50..150".into()), (rcstr!("wdth"), rcstr!("50..150")),
]) ])
}, },
"optional" "optional"
...@@ -557,8 +558,8 @@ mod tests { ...@@ -557,8 +558,8 @@ mod tests {
"Nabla", "Nabla",
&FontAxes { &FontAxes {
variable_axes: Some(vec![ variable_axes: Some(vec![
("EDPT".into(), "0..200".into()), (rcstr!("EDPT"), rcstr!("0..200")),
("EHLT".into(), "0..24".into()), (rcstr!("EHLT"), rcstr!("0..24")),
]), ]),
..Default::default() ..Default::default()
}, },
......
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, TaskInput, trace::TraceRawVcs}; use turbo_tasks::{NonLocalValue, TaskInput, trace::TraceRawVcs};
/// The top-most structure encoded into the query param in requests to /// The top-most structure encoded into the query param in requests to
...@@ -112,7 +112,7 @@ fn default_preload() -> bool { ...@@ -112,7 +112,7 @@ fn default_preload() -> bool {
} }
fn default_display() -> RcStr { fn default_display() -> RcStr {
"swap".into() rcstr!("swap")
} }
#[cfg(test)] #[cfg(test)]
......
...@@ -38,7 +38,7 @@ impl Source for StructuredImageFileSource { ...@@ -38,7 +38,7 @@ impl Source for StructuredImageFileSource {
self.image self.image
.ident() .ident()
.with_modifier(rcstr!("structured image object")) .with_modifier(rcstr!("structured image object"))
.rename_as("*.mjs".into()) .rename_as(rcstr!("*.mjs"))
} }
} }
......
This diff is collapsed.
...@@ -5,7 +5,7 @@ use itertools::Itertools; ...@@ -5,7 +5,7 @@ use itertools::Itertools;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
FxIndexSet, ResolvedVc, TaskInput, TryFlatJoinIterExt, TryJoinIterExt, ValueToString, Vc, FxIndexSet, ResolvedVc, TaskInput, TryFlatJoinIterExt, TryJoinIterExt, ValueToString, Vc,
trace::TraceRawVcs, trace::TraceRawVcs,
...@@ -71,17 +71,13 @@ impl ClientReferenceManifest { ...@@ -71,17 +71,13 @@ impl ClientReferenceManifest {
async move { async move {
let mut entry_manifest: ClientReferenceManifest = Default::default(); let mut entry_manifest: ClientReferenceManifest = Default::default();
let mut references = FxIndexSet::default(); let mut references = FxIndexSet::default();
let chunk_suffix_path = next_config.chunk_suffix_path().await?; let chunk_suffix_path = next_config.chunk_suffix_path().owned().await?;
let prefix_path = next_config let prefix_path = next_config
.computed_asset_prefix() .computed_asset_prefix()
.owned()
.await? .await?
.as_ref()
.map(|p| p.clone())
.unwrap_or_default(); .unwrap_or_default();
let suffix_path = chunk_suffix_path let suffix_path = chunk_suffix_path.unwrap_or_default();
.as_ref()
.map(|p| p.to_string())
.unwrap_or("".into());
// TODO: Add `suffix` to the manifest for React to use. // TODO: Add `suffix` to the manifest for React to use.
// entry_manifest.module_loading.prefix = prefix_path; // entry_manifest.module_loading.prefix = prefix_path;
...@@ -267,7 +263,7 @@ impl ClientReferenceManifest { ...@@ -267,7 +263,7 @@ impl ClientReferenceManifest {
entry_manifest.client_modules.module_exports.insert( entry_manifest.client_modules.module_exports.insert(
get_client_reference_module_key(&server_path, "*"), get_client_reference_module_key(&server_path, "*"),
ManifestNodeEntry { ManifestNodeEntry {
name: "*".into(), name: rcstr!("*"),
id: (&*client_chunk_item_id).into(), id: (&*client_chunk_item_id).into(),
chunks: client_chunks_paths, chunks: client_chunks_paths,
// This should of course be client_is_async, but SSR can become // This should of course be client_is_async, but SSR can become
...@@ -280,9 +276,9 @@ impl ClientReferenceManifest { ...@@ -280,9 +276,9 @@ impl ClientReferenceManifest {
let mut ssr_manifest_node = ManifestNode::default(); let mut ssr_manifest_node = ManifestNode::default();
ssr_manifest_node.module_exports.insert( ssr_manifest_node.module_exports.insert(
"*".into(), rcstr!("*"),
ManifestNodeEntry { ManifestNodeEntry {
name: "*".into(), name: rcstr!("*"),
id: (&*ssr_chunk_item_id).into(), id: (&*ssr_chunk_item_id).into(),
chunks: ssr_chunks_paths, chunks: ssr_chunks_paths,
// See above // See above
...@@ -292,9 +288,9 @@ impl ClientReferenceManifest { ...@@ -292,9 +288,9 @@ impl ClientReferenceManifest {
let mut rsc_manifest_node = ManifestNode::default(); let mut rsc_manifest_node = ManifestNode::default();
rsc_manifest_node.module_exports.insert( rsc_manifest_node.module_exports.insert(
"*".into(), rcstr!("*"),
ManifestNodeEntry { ManifestNodeEntry {
name: "*".into(), name: rcstr!("*"),
id: (&*rsc_chunk_item_id).into(), id: (&*rsc_chunk_item_id).into(),
chunks: vec![], chunks: vec![],
r#async: rsc_is_async, r#async: rsc_is_async,
......
...@@ -519,6 +519,8 @@ pub struct ClientBuildManifest<'a> { ...@@ -519,6 +519,8 @@ pub struct ClientBuildManifest<'a> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use turbo_rcstr::rcstr;
use super::*; use super::*;
#[test] #[test]
...@@ -529,20 +531,20 @@ mod tests { ...@@ -529,20 +531,20 @@ mod tests {
locale: false, locale: false,
has: None, has: None,
missing: None, missing: None,
original_source: "".into(), original_source: rcstr!(""),
}, },
MiddlewareMatcher { MiddlewareMatcher {
regexp: Some(".*".into()), regexp: Some(rcstr!(".*")),
locale: true, locale: true,
has: Some(vec![RouteHas::Query { has: Some(vec![RouteHas::Query {
key: "foo".into(), key: rcstr!("foo"),
value: None, value: None,
}]), }]),
missing: Some(vec![RouteHas::Query { missing: Some(vec![RouteHas::Query {
key: "bar".into(), key: rcstr!("bar"),
value: Some("value".into()), value: Some(rcstr!("value")),
}]), }]),
original_source: "source".into(), original_source: rcstr!("source"),
}, },
]; ];
......
...@@ -238,7 +238,7 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin { ...@@ -238,7 +238,7 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
// have an extension in the request we try to append ".js" // have an extension in the request we try to append ".js"
// automatically // automatically
request_str.push_str(".js"); request_str.push_str(".js");
request = request.append_path(".js".into()).resolve().await?; request = request.append_path(rcstr!(".js")).resolve().await?;
continue; continue;
} }
// this can't resolve with node.js from the original location, so bundle it // this can't resolve with node.js from the original location, so bundle it
...@@ -271,7 +271,7 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin { ...@@ -271,7 +271,7 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
.into(), .into(),
), ),
StyledString::Code(format!("npm install {package}").into()), StyledString::Code(format!("npm install {package}").into()),
StyledString::Text(" from the project directory.".into()), StyledString::Text(rcstr!(" from the project directory.")),
]); ]);
}; };
...@@ -293,9 +293,9 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin { ...@@ -293,9 +293,9 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
let FindContextFileResult::Found(package_json_from_original_location, _) = let FindContextFileResult::Found(package_json_from_original_location, _) =
&*package_json_from_original_location.await? &*package_json_from_original_location.await?
else { else {
return unable_to_externalize(vec![StyledString::Text( return unable_to_externalize(vec![StyledString::Text(rcstr!(
"The package.json of the package can't be found.".into(), "The package.json of the package can't be found."
)]); ))]);
}; };
let FileJsonContent::Content(package_json_file) = let FileJsonContent::Content(package_json_file) =
&*package_json_file.read_json().await? &*package_json_file.read_json().await?
...@@ -309,17 +309,17 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin { ...@@ -309,17 +309,17 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
let FileJsonContent::Content(package_json_from_original_location) = let FileJsonContent::Content(package_json_from_original_location) =
&*package_json_from_original_location.read_json().await? &*package_json_from_original_location.read_json().await?
else { else {
return unable_to_externalize(vec![StyledString::Text( return unable_to_externalize(vec![StyledString::Text(rcstr!(
"The package.json of the package can't be parsed.".into(), "The package.json of the package can't be parsed."
)]); ))]);
}; };
let (Some(name), Some(version)) = ( let (Some(name), Some(version)) = (
package_json_file.get("name").and_then(|v| v.as_str()), package_json_file.get("name").and_then(|v| v.as_str()),
package_json_file.get("version").and_then(|v| v.as_str()), package_json_file.get("version").and_then(|v| v.as_str()),
) else { ) else {
return unable_to_externalize(vec![StyledString::Text( return unable_to_externalize(vec![StyledString::Text(rcstr!(
"The package.json of the package has no name or version.".into(), "The package.json of the package has no name or version."
)]); ))]);
}; };
let (Some(name2), Some(version2)) = ( let (Some(name2), Some(version2)) = (
package_json_from_original_location package_json_from_original_location
...@@ -354,15 +354,15 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin { ...@@ -354,15 +354,15 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
let external_type = match (file_type, is_esm) { let external_type = match (file_type, is_esm) {
(FileType::UnsupportedExtension, _) => { (FileType::UnsupportedExtension, _) => {
// unsupported file type, bundle it // unsupported file type, bundle it
return unable_to_externalize(vec![StyledString::Text( return unable_to_externalize(vec![StyledString::Text(rcstr!(
"Only .mjs, .cjs, .js, .json, or .node can be handled by Node.js.".into(), "Only .mjs, .cjs, .js, .json, or .node can be handled by Node.js."
)]); ))]);
} }
(FileType::InvalidPackageJson, _) => { (FileType::InvalidPackageJson, _) => {
// invalid package.json, bundle it // invalid package.json, bundle it
return unable_to_externalize(vec![StyledString::Text( return unable_to_externalize(vec![StyledString::Text(rcstr!(
"The package.json can't be found or parsed.".into(), "The package.json can't be found or parsed."
)]); ))]);
} }
// commonjs without esm is always external // commonjs without esm is always external
(FileType::CommonJs, false) => ExternalType::CommonJs, (FileType::CommonJs, false) => ExternalType::CommonJs,
......
...@@ -101,8 +101,8 @@ impl EcmascriptChunkPlaceable for NextServerComponentModule { ...@@ -101,8 +101,8 @@ impl EcmascriptChunkPlaceable for NextServerComponentModule {
let mut exports = BTreeMap::new(); let mut exports = BTreeMap::new();
exports.insert( exports.insert(
"default".into(), rcstr!("default"),
EsmExport::ImportedBinding(module_reference, "default".into(), false), EsmExport::ImportedBinding(module_reference, rcstr!("default"), false),
); );
Ok(EcmascriptExports::EsmExports( Ok(EcmascriptExports::EsmExports(
......
...@@ -101,8 +101,8 @@ impl EcmascriptChunkPlaceable for NextServerUtilityModule { ...@@ -101,8 +101,8 @@ impl EcmascriptChunkPlaceable for NextServerUtilityModule {
let mut exports = BTreeMap::new(); let mut exports = BTreeMap::new();
exports.insert( exports.insert(
"default".into(), rcstr!("default"),
EsmExport::ImportedBinding(module_reference, "default".into(), false), EsmExport::ImportedBinding(module_reference, rcstr!("default"), false),
); );
Ok(EcmascriptExports::EsmExports( Ok(EcmascriptExports::EsmExports(
......
use anyhow::Result; use anyhow::Result;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, ValueToString, Vc}; use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use turbopack_core::{ use turbopack_core::{
chunk::{ChunkableModuleReference, ChunkingType, ChunkingTypeOption}, chunk::{ChunkableModuleReference, ChunkingType, ChunkingTypeOption},
...@@ -44,7 +44,7 @@ impl ModuleReference for NextServerUtilityModuleReference { ...@@ -44,7 +44,7 @@ impl ModuleReference for NextServerUtilityModuleReference {
} }
} }
pub static NEXT_SERVER_UTILITY_MERGE_TAG: Lazy<RcStr> = Lazy::new(|| "next-server-utility".into()); pub static NEXT_SERVER_UTILITY_MERGE_TAG: Lazy<RcStr> = Lazy::new(|| rcstr!("next-server-utility"));
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ChunkableModuleReference for NextServerUtilityModuleReference { impl ChunkableModuleReference for NextServerUtilityModuleReference {
......
...@@ -158,7 +158,7 @@ pub(crate) fn get_invalid_client_only_resolve_plugin( ...@@ -158,7 +158,7 @@ pub(crate) fn get_invalid_client_only_resolve_plugin(
) -> Vc<InvalidImportResolvePlugin> { ) -> Vc<InvalidImportResolvePlugin> {
InvalidImportResolvePlugin::new( InvalidImportResolvePlugin::new(
root, root,
"client-only".into(), rcstr!("client-only"),
vec![ vec![
"'client-only' cannot be imported from a Server Component module. It should only be \ "'client-only' cannot be imported from a Server Component module. It should only be \
used from a Client Component." used from a Client Component."
...@@ -175,7 +175,7 @@ pub(crate) fn get_invalid_server_only_resolve_plugin( ...@@ -175,7 +175,7 @@ pub(crate) fn get_invalid_server_only_resolve_plugin(
) -> Vc<InvalidImportResolvePlugin> { ) -> Vc<InvalidImportResolvePlugin> {
InvalidImportResolvePlugin::new( InvalidImportResolvePlugin::new(
root, root,
"server-only".into(), rcstr!("server-only"),
vec![ vec![
"'server-only' cannot be imported from a Client Component module. It should only be \ "'server-only' cannot be imported from a Client Component module. It should only be \
used from a Server Component." used from a Server Component."
...@@ -190,7 +190,7 @@ pub(crate) fn get_invalid_styled_jsx_resolve_plugin( ...@@ -190,7 +190,7 @@ pub(crate) fn get_invalid_styled_jsx_resolve_plugin(
) -> Vc<InvalidImportResolvePlugin> { ) -> Vc<InvalidImportResolvePlugin> {
InvalidImportResolvePlugin::new( InvalidImportResolvePlugin::new(
root, root,
"styled-jsx".into(), rcstr!("styled-jsx"),
vec![ vec![
"'client-only' cannot be imported from a Server Component module. It should only be \ "'client-only' cannot be imported from a Server Component module. It should only be \
used from a Client Component." used from a Client Component."
...@@ -222,7 +222,9 @@ impl AfterResolvePlugin for NextExternalResolvePlugin { ...@@ -222,7 +222,9 @@ impl AfterResolvePlugin for NextExternalResolvePlugin {
async fn after_resolve_condition(&self) -> Result<Vc<AfterResolvePluginCondition>> { async fn after_resolve_condition(&self) -> Result<Vc<AfterResolvePluginCondition>> {
Ok(AfterResolvePluginCondition::new( Ok(AfterResolvePluginCondition::new(
self.project_path.root().owned().await?, self.project_path.root().owned().await?,
Glob::new("**/next/dist/**/*.{external,runtime.dev,runtime.prod}.js".into()), Glob::new(rcstr!(
"**/next/dist/**/*.{external,runtime.dev,runtime.prod}.js"
)),
)) ))
} }
...@@ -276,7 +278,7 @@ impl AfterResolvePlugin for NextNodeSharedRuntimeResolvePlugin { ...@@ -276,7 +278,7 @@ impl AfterResolvePlugin for NextNodeSharedRuntimeResolvePlugin {
async fn after_resolve_condition(&self) -> Result<Vc<AfterResolvePluginCondition>> { async fn after_resolve_condition(&self) -> Result<Vc<AfterResolvePluginCondition>> {
Ok(AfterResolvePluginCondition::new( Ok(AfterResolvePluginCondition::new(
self.root.root().owned().await?, self.root.root().owned().await?,
Glob::new("**/next/dist/**/*.shared-runtime.js".into()), Glob::new(rcstr!("**/next/dist/**/*.shared-runtime.js")),
)) ))
} }
...@@ -401,7 +403,7 @@ impl AfterResolvePlugin for NextSharedRuntimeResolvePlugin { ...@@ -401,7 +403,7 @@ impl AfterResolvePlugin for NextSharedRuntimeResolvePlugin {
async fn after_resolve_condition(&self) -> Result<Vc<AfterResolvePluginCondition>> { async fn after_resolve_condition(&self) -> Result<Vc<AfterResolvePluginCondition>> {
Ok(AfterResolvePluginCondition::new( Ok(AfterResolvePluginCondition::new(
self.root.root().owned().await?, self.root.root().owned().await?,
Glob::new("**/next/dist/esm/**/*.shared-runtime.js".into()), Glob::new(rcstr!("**/next/dist/esm/**/*.shared-runtime.js")),
)) ))
} }
......
use anyhow::Result; use anyhow::Result;
use async_trait::async_trait; use async_trait::async_trait;
use next_custom_transforms::transforms::fonts::*; use next_custom_transforms::transforms::fonts::*;
use swc_core::ecma::{ast::Program, atoms::Atom, visit::VisitMutWith}; use swc_core::{
atoms::atom,
ecma::{ast::Program, atoms::Atom, visit::VisitMutWith},
};
use turbo_tasks::ResolvedVc; use turbo_tasks::ResolvedVc;
use turbopack::module_options::{ModuleRule, ModuleRuleEffect}; use turbopack::module_options::{ModuleRule, ModuleRuleEffect};
use turbopack_ecmascript::{CustomTransformer, EcmascriptInputTransform, TransformContext}; use turbopack_ecmascript::{CustomTransformer, EcmascriptInputTransform, TransformContext};
...@@ -11,10 +14,10 @@ use super::module_rule_match_js_no_url; ...@@ -11,10 +14,10 @@ use super::module_rule_match_js_no_url;
/// Returns a rule which applies the Next.js font transform. /// Returns a rule which applies the Next.js font transform.
pub fn get_next_font_transform_rule(enable_mdx_rs: bool) -> ModuleRule { pub fn get_next_font_transform_rule(enable_mdx_rs: bool) -> ModuleRule {
let font_loaders = vec![ let font_loaders = vec![
"next/font/google".into(), atom!("next/font/google"),
"@next/font/google".into(), atom!("@next/font/google"),
"next/font/local".into(), atom!("next/font/local"),
"@next/font/local".into(), atom!("@next/font/local"),
]; ];
let transformer = let transformer =
......
...@@ -116,7 +116,7 @@ pub async fn is_babel_loader_available(project_path: FileSystemPath) -> Result<V ...@@ -116,7 +116,7 @@ pub async fn is_babel_loader_available(project_path: FileSystemPath) -> Result<V
let result = resolve( let result = resolve(
project_path.clone(), project_path.clone(),
ReferenceType::CommonJs(CommonJsReferenceSubType::Undefined), ReferenceType::CommonJs(CommonJsReferenceSubType::Undefined),
Request::parse(Pattern::Constant("babel-loader/package.json".into())), Request::parse(Pattern::Constant(rcstr!("babel-loader/package.json"))),
node_cjs_resolve_options(project_path), node_cjs_resolve_options(project_path),
); );
let assets = result.primary_sources().await?; let assets = result.primary_sources().await?;
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack::module_options::WebpackLoadersOptions; use turbopack::module_options::WebpackLoadersOptions;
...@@ -46,7 +46,7 @@ pub async fn webpack_loader_options( ...@@ -46,7 +46,7 @@ pub async fn webpack_loader_options(
fn loader_runner_package_mapping() -> Result<Vc<ImportMapping>> { fn loader_runner_package_mapping() -> Result<Vc<ImportMapping>> {
Ok(ImportMapping::Alternatives(vec![ Ok(ImportMapping::Alternatives(vec![
ImportMapping::External( ImportMapping::External(
Some("next/dist/compiled/loader-runner".into()), Some(rcstr!("next/dist/compiled/loader-runner")),
ExternalType::CommonJs, ExternalType::CommonJs,
ExternalTraced::Untraced, ExternalTraced::Untraced,
) )
......
...@@ -2,6 +2,7 @@ use std::mem::take; ...@@ -2,6 +2,7 @@ use std::mem::take;
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use serde_json::Value as JsonValue; use serde_json::Value as JsonValue;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbopack::module_options::{LoaderRuleItem, OptionWebpackRules, WebpackRules}; use turbopack::module_options::{LoaderRuleItem, OptionWebpackRules, WebpackRules};
use turbopack_node::transforms::webpack::WebpackLoaderItem; use turbopack_node::transforms::webpack::WebpackLoaderItem;
...@@ -41,7 +42,7 @@ pub async fn maybe_add_sass_loader( ...@@ -41,7 +42,7 @@ pub async fn maybe_add_sass_loader(
.or(sass_options.get("additionalData")); .or(sass_options.get("additionalData"));
let rule = rules.get_mut(pattern); let rule = rules.get_mut(pattern);
let sass_loader = WebpackLoaderItem { let sass_loader = WebpackLoaderItem {
loader: "next/dist/compiled/sass-loader".into(), loader: rcstr!("next/dist/compiled/sass-loader"),
options: take( options: take(
serde_json::json!({ serde_json::json!({
"implementation": sass_options.get("implementation"), "implementation": sass_options.get("implementation"),
...@@ -54,7 +55,7 @@ pub async fn maybe_add_sass_loader( ...@@ -54,7 +55,7 @@ pub async fn maybe_add_sass_loader(
), ),
}; };
let resolve_url_loader = WebpackLoaderItem { let resolve_url_loader = WebpackLoaderItem {
loader: "next/dist/build/webpack/loaders/resolve-url-loader/index".into(), loader: rcstr!("next/dist/build/webpack/loaders/resolve-url-loader/index"),
options: take( options: take(
serde_json::json!({ serde_json::json!({
//https://github.com/vercel/turbo/blob/d527eb54be384a4658243304cecd547d09c05c6b/crates/turbopack-node/src/transforms/webpack.rs#L191 //https://github.com/vercel/turbo/blob/d527eb54be384a4658243304cecd547d09c05c6b/crates/turbopack-node/src/transforms/webpack.rs#L191
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{self, FileJsonContent, FileSystemPath}; use turbo_tasks_fs::{self, FileJsonContent, FileSystemPath};
use turbopack::{ use turbopack::{
...@@ -161,11 +162,11 @@ pub async fn get_jsx_transform_options( ...@@ -161,11 +162,11 @@ pub async fn get_jsx_transform_options(
// https://github.com/vercel/next.js/blob/3dc2c1c7f8441cdee31da9f7e0986d654c7fd2e7/packages/next/src/build/swc/options.ts#L112 // https://github.com/vercel/next.js/blob/3dc2c1c7f8441cdee31da9f7e0986d654c7fd2e7/packages/next/src/build/swc/options.ts#L112
// This'll be ignored if ts|jsconfig explicitly specifies importSource // This'll be ignored if ts|jsconfig explicitly specifies importSource
import_source: if is_emotion_enabled && !is_rsc_context { import_source: if is_emotion_enabled && !is_rsc_context {
Some("@emotion/react".into()) Some(rcstr!("@emotion/react"))
} else { } else {
None None
}, },
runtime: Some("automatic".into()), runtime: Some(rcstr!("automatic")),
react_refresh: enable_react_refresh, react_refresh: enable_react_refresh,
}; };
......
...@@ -105,7 +105,7 @@ pub async fn pathname_for_path( ...@@ -105,7 +105,7 @@ pub async fn pathname_for_path(
}; };
let path = match (path_ty, path) { let path = match (path_ty, path) {
// "/" is special-cased to "/index" for data routes. // "/" is special-cased to "/index" for data routes.
(PathType::Data, "") => "/index".into(), (PathType::Data, "") => rcstr!("/index"),
// `get_path_to` always strips the leading `/` from the path, so we need to add // `get_path_to` always strips the leading `/` from the path, so we need to add
// it back here. // it back here.
(_, path) => format!("/{path}").into(), (_, path) => format!("/{path}").into(),
...@@ -141,7 +141,7 @@ pub async fn get_transpiled_packages( ...@@ -141,7 +141,7 @@ pub async fn get_transpiled_packages(
let default_transpiled_packages: Vec<RcStr> = load_next_js_templateon( let default_transpiled_packages: Vec<RcStr> = load_next_js_templateon(
project_path, project_path,
"dist/lib/default-transpiled-packages.json".into(), rcstr!("dist/lib/default-transpiled-packages.json"),
) )
.await?; .await?;
...@@ -280,8 +280,10 @@ impl Issue for NextSourceConfigParsingIssue { ...@@ -280,8 +280,10 @@ impl Issue for NextSourceConfigParsingIssue {
#[turbo_tasks::function] #[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> { fn title(&self) -> Vc<StyledString> {
StyledString::Text("Next.js can't recognize the exported `config` field in route".into()) StyledString::Text(rcstr!(
.cell() "Next.js can't recognize the exported `config` field in route"
))
.cell()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -553,7 +555,7 @@ pub async fn parse_config_from_source( ...@@ -553,7 +555,7 @@ pub async fn parse_config_from_source(
if let Expr::Lit(Lit::Str(str_value)) = &**init { if let Expr::Lit(Lit::Str(str_value)) = &**init {
let mut config = NextSourceConfig::default(); let mut config = NextSourceConfig::default();
let runtime = str_value.value.to_string(); let runtime = &str_value.value;
match runtime.as_str() { match runtime.as_str() {
"edge" | "experimental-edge" => { "edge" | "experimental-edge" => {
config.runtime = NextRuntime::Edge; config.runtime = NextRuntime::Edge;
......
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use serde::Deserialize; use serde::Deserialize;
use swc_core::{ use swc_core::{
atoms::atom,
common::{util::take::Take, SyntaxContext, DUMMY_SP}, common::{util::take::Take, SyntaxContext, DUMMY_SP},
ecma::{ ecma::{
ast::{ ast::{
...@@ -113,7 +114,7 @@ impl VisitMut for CjsOptimizer { ...@@ -113,7 +114,7 @@ impl VisitMut for CjsOptimizer {
obj: Box::new(Expr::Call(CallExpr { obj: Box::new(Expr::Call(CallExpr {
span: DUMMY_SP, span: DUMMY_SP,
callee: Ident::new( callee: Ident::new(
"require".into(), atom!("require"),
DUMMY_SP, DUMMY_SP,
self.unresolved_ctxt, self.unresolved_ctxt,
) )
......
...@@ -5,7 +5,7 @@ use std::{ ...@@ -5,7 +5,7 @@ use std::{
use pathdiff::diff_paths; use pathdiff::diff_paths;
use swc_core::{ use swc_core::{
atoms::Atom, atoms::{atom, Atom},
common::{errors::HANDLER, FileName, Span, DUMMY_SP}, common::{errors::HANDLER, FileName, Span, DUMMY_SP},
ecma::{ ecma::{
ast::{ ast::{
...@@ -264,7 +264,7 @@ impl Fold for NextDynamicPatcher { ...@@ -264,7 +264,7 @@ impl Fold for NextDynamicPatcher {
let mut props = let mut props =
vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident(IdentName::new( key: PropName::Ident(IdentName::new(
"loadableGenerated".into(), atom!("loadableGenerated"),
DUMMY_SP, DUMMY_SP,
)), )),
value: generated, value: generated,
...@@ -432,7 +432,7 @@ impl VisitMut for DynamicImportTransitionAdder<'_> { ...@@ -432,7 +432,7 @@ impl VisitMut for DynamicImportTransitionAdder<'_> {
ObjectLit { ObjectLit {
span: DUMMY_SP, span: DUMMY_SP,
props: vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { props: vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident(IdentName::new("with".into(), DUMMY_SP)), key: PropName::Ident(IdentName::new(atom!("with"), DUMMY_SP)),
value: with_transition(self.transition_name).into(), value: with_transition(self.transition_name).into(),
})))], })))],
} }
...@@ -453,7 +453,7 @@ impl VisitMut for DynamicImportTransitionAdder<'_> { ...@@ -453,7 +453,7 @@ impl VisitMut for DynamicImportTransitionAdder<'_> {
fn module_id_options(module_id: Expr) -> Vec<PropOrSpread> { fn module_id_options(module_id: Expr) -> Vec<PropOrSpread> {
vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident(IdentName::new("modules".into(), DUMMY_SP)), key: PropName::Ident(IdentName::new(atom!("modules"), DUMMY_SP)),
value: Box::new(Expr::Array(ArrayLit { value: Box::new(Expr::Array(ArrayLit {
elems: vec![Some(ExprOrSpread { elems: vec![Some(ExprOrSpread {
expr: Box::new(module_id), expr: Box::new(module_id),
...@@ -466,7 +466,7 @@ fn module_id_options(module_id: Expr) -> Vec<PropOrSpread> { ...@@ -466,7 +466,7 @@ fn module_id_options(module_id: Expr) -> Vec<PropOrSpread> {
fn webpack_options(module_id: Expr) -> Vec<PropOrSpread> { fn webpack_options(module_id: Expr) -> Vec<PropOrSpread> {
vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident(IdentName::new("webpack".into(), DUMMY_SP)), key: PropName::Ident(IdentName::new(atom!("webpack"), DUMMY_SP)),
value: Box::new(Expr::Arrow(ArrowExpr { value: Box::new(Expr::Arrow(ArrowExpr {
params: vec![], params: vec![],
body: Box::new(BlockStmtOrExpr::Expr(Box::new(Expr::Array(ArrayLit { body: Box::new(BlockStmtOrExpr::Expr(Box::new(Expr::Array(ArrayLit {
...@@ -512,7 +512,7 @@ impl NextDynamicPatcher { ...@@ -512,7 +512,7 @@ impl NextDynamicPatcher {
local: id_ident, local: id_ident,
imported: Some( imported: Some(
Ident::new( Ident::new(
"__turbopack_module_id__".into(), atom!("__turbopack_module_id__"),
DUMMY_SP, DUMMY_SP,
Default::default(), Default::default(),
) )
...@@ -541,7 +541,7 @@ impl NextDynamicPatcher { ...@@ -541,7 +541,7 @@ impl NextDynamicPatcher {
fn exec_expr_when_resolve_weak_available(expr: &Expr) -> Expr { fn exec_expr_when_resolve_weak_available(expr: &Expr) -> Expr {
let undefined_str_literal = Expr::Lit(Lit::Str(Str { let undefined_str_literal = Expr::Lit(Lit::Str(Str {
span: DUMMY_SP, span: DUMMY_SP,
value: "undefined".into(), value: atom!("undefined"),
raw: None, raw: None,
})); }));
......
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use swc_core::{ use swc_core::{
atoms::Atom, atoms::{atom, Atom},
ecma::{ ecma::{
ast::{ ast::{
Expr, Id, ImportDecl, ImportNamedSpecifier, ImportSpecifier, MemberExpr, MemberProp, Expr, Id, ImportDecl, ImportNamedSpecifier, ImportSpecifier, MemberExpr, MemberProp,
...@@ -80,7 +80,7 @@ impl Visit for Analyzer<'_> { ...@@ -80,7 +80,7 @@ impl Visit for Analyzer<'_> {
Some(imported) => (local.to_id(), orig_name(imported)), Some(imported) => (local.to_id(), orig_name(imported)),
_ => (local.to_id(), local.sym.clone()), _ => (local.to_id(), local.sym.clone()),
}, },
ImportSpecifier::Default(s) => (s.local.to_id(), "default".into()), ImportSpecifier::Default(s) => (s.local.to_id(), atom!("default")),
ImportSpecifier::Namespace(s) => { ImportSpecifier::Namespace(s) => {
self.data self.data
.namespace_imports .namespace_imports
......
...@@ -3,7 +3,7 @@ use std::{cell::RefCell, mem::take, rc::Rc}; ...@@ -3,7 +3,7 @@ use std::{cell::RefCell, mem::take, rc::Rc};
use easy_error::{bail, Error}; use easy_error::{bail, Error};
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use swc_core::{ use swc_core::{
atoms::Atom, atoms::{atom, Atom},
common::{ common::{
errors::HANDLER, errors::HANDLER,
pass::{Repeat, Repeated}, pass::{Repeat, Repeated},
...@@ -443,7 +443,7 @@ impl Fold for NextSsg { ...@@ -443,7 +443,7 @@ impl Fold for NextSsg {
match &i { match &i {
ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(e)) if e.specifiers.is_empty() => { ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(e)) if e.specifiers.is_empty() => {
return ModuleItem::Stmt(Stmt::Empty(EmptyStmt { span: DUMMY_SP })) return ModuleItem::Stmt(Stmt::Empty(EmptyStmt { span: DUMMY_SP }));
} }
_ => {} _ => {}
} }
...@@ -469,9 +469,9 @@ impl Fold for NextSsg { ...@@ -469,9 +469,9 @@ impl Fold for NextSsg {
name: Pat::Ident( name: Pat::Ident(
IdentName::new( IdentName::new(
if self.state.is_prerenderer { if self.state.is_prerenderer {
"__N_SSG".into() atom!("__N_SSG")
} else { } else {
"__N_SSP".into() atom!("__N_SSP")
}, },
DUMMY_SP, DUMMY_SP,
) )
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
use serde::Deserialize; use serde::Deserialize;
use swc_core::{ use swc_core::{
atoms::atom,
common::DUMMY_SP, common::DUMMY_SP,
ecma::{ ecma::{
ast::*, ast::*,
...@@ -71,18 +72,18 @@ fn wrap_expr_with_env_prod_condition(call: CallExpr) -> Expr { ...@@ -71,18 +72,18 @@ fn wrap_expr_with_env_prod_condition(call: CallExpr) -> Expr {
left: Box::new(Expr::Member(MemberExpr { left: Box::new(Expr::Member(MemberExpr {
obj: (Box::new(Expr::Member(MemberExpr { obj: (Box::new(Expr::Member(MemberExpr {
obj: (Box::new(Expr::Ident(Ident { obj: (Box::new(Expr::Ident(Ident {
sym: "process".into(), sym: atom!("process"),
span: DUMMY_SP, span: DUMMY_SP,
..Default::default() ..Default::default()
}))), }))),
prop: MemberProp::Ident(IdentName { prop: MemberProp::Ident(IdentName {
sym: "env".into(), sym: atom!("env"),
span: DUMMY_SP, span: DUMMY_SP,
}), }),
span: DUMMY_SP, span: DUMMY_SP,
}))), }))),
prop: (MemberProp::Ident(IdentName { prop: (MemberProp::Ident(IdentName {
sym: "__NEXT_PRIVATE_MINIMIZE_MACRO_FALSE".into(), sym: atom!("__NEXT_PRIVATE_MINIMIZE_MACRO_FALSE"),
span: DUMMY_SP, span: DUMMY_SP,
})), })),
span: DUMMY_SP, span: DUMMY_SP,
......
...@@ -445,7 +445,7 @@ impl<C: Comments> ServerActions<C> { ...@@ -445,7 +445,7 @@ impl<C: Comments> ServerActions<C> {
new_params.push(Param { new_params.push(Param {
span: DUMMY_SP, span: DUMMY_SP,
decorators: vec![], decorators: vec![],
pat: Pat::Ident(IdentName::new("$$ACTION_CLOSURE_BOUND".into(), DUMMY_SP).into()), pat: Pat::Ident(IdentName::new(atom!("$$ACTION_CLOSURE_BOUND"), DUMMY_SP).into()),
}); });
} }
...@@ -597,7 +597,7 @@ impl<C: Comments> ServerActions<C> { ...@@ -597,7 +597,7 @@ impl<C: Comments> ServerActions<C> {
new_params.push(Param { new_params.push(Param {
span: DUMMY_SP, span: DUMMY_SP,
decorators: vec![], decorators: vec![],
pat: Pat::Ident(IdentName::new("$$ACTION_CLOSURE_BOUND".into(), DUMMY_SP).into()), pat: Pat::Ident(IdentName::new(atom!("$$ACTION_CLOSURE_BOUND"), DUMMY_SP).into()),
}); });
} }
...@@ -1620,7 +1620,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -1620,7 +1620,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
// export default function foo() {} // export default function foo() {}
self.exported_idents.push(( self.exported_idents.push((
ident.clone(), ident.clone(),
"default".into(), atom!("default"),
ref_id, ref_id,
)); ));
} else { } else {
...@@ -1638,7 +1638,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -1638,7 +1638,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
self.exported_idents.push(( self.exported_idents.push((
new_ident.clone(), new_ident.clone(),
"default".into(), atom!("default"),
ref_id, ref_id,
)); ));
...@@ -1694,7 +1694,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -1694,7 +1694,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
self.exported_idents.push(( self.exported_idents.push((
new_ident.clone(), new_ident.clone(),
"default".into(), atom!("default"),
self.generate_server_reference_id( self.generate_server_reference_id(
"default", "default",
is_cache, is_cache,
...@@ -1723,7 +1723,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -1723,7 +1723,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
// export default foo // export default foo
self.exported_idents.push(( self.exported_idents.push((
ident.clone(), ident.clone(),
"default".into(), atom!("default"),
self.generate_server_reference_id( self.generate_server_reference_id(
"default", "default",
in_cache_file, in_cache_file,
...@@ -1741,7 +1741,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -1741,7 +1741,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
self.exported_idents.push(( self.exported_idents.push((
new_ident.clone(), new_ident.clone(),
"default".into(), atom!("default"),
self.generate_server_reference_id( self.generate_server_reference_id(
"default", "default",
in_cache_file, in_cache_file,
...@@ -1858,7 +1858,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -1858,7 +1858,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
], ],
src: Box::new(Str { src: Box::new(Str {
span: DUMMY_SP, span: DUMMY_SP,
value: "private-next-rsc-action-client-wrapper".into(), value: atom!("private-next-rsc-action-client-wrapper"),
raw: None, raw: None,
}), }),
type_only: false, type_only: false,
...@@ -1990,7 +1990,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -1990,7 +1990,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
})], })],
src: Box::new(Str { src: Box::new(Str {
span: DUMMY_SP, span: DUMMY_SP,
value: "private-next-rsc-action-validate".into(), value: atom!("private-next-rsc-action-validate"),
raw: None, raw: None,
}), }),
type_only: false, type_only: false,
...@@ -2040,7 +2040,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -2040,7 +2040,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
})], })],
src: Box::new(Str { src: Box::new(Str {
span: DUMMY_SP, span: DUMMY_SP,
value: "private-next-rsc-cache-wrapper".into(), value: atom!("private-next-rsc-cache-wrapper"),
raw: None, raw: None,
}), }),
type_only: false, type_only: false,
...@@ -2065,7 +2065,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -2065,7 +2065,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
})], })],
src: Box::new(Str { src: Box::new(Str {
span: DUMMY_SP, span: DUMMY_SP,
value: "private-next-rsc-server-reference".into(), value: atom!("private-next-rsc-server-reference"),
raw: None, raw: None,
}), }),
type_only: false, type_only: false,
...@@ -2094,7 +2094,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -2094,7 +2094,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
], ],
src: Box::new(Str { src: Box::new(Str {
span: DUMMY_SP, span: DUMMY_SP,
value: "private-next-rsc-action-encryption".into(), value: atom!("private-next-rsc-action-encryption"),
raw: None, raw: None,
}), }),
type_only: false, type_only: false,
...@@ -2142,7 +2142,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -2142,7 +2142,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
ServerActionsMode::Turbopack => { ServerActionsMode::Turbopack => {
new.push(ModuleItem::Stmt(Stmt::Expr(ExprStmt { new.push(ModuleItem::Stmt(Stmt::Expr(ExprStmt {
expr: Box::new(Expr::Lit(Lit::Str( expr: Box::new(Expr::Lit(Lit::Str(
"use turbopack no side effects".into(), atom!("use turbopack no side effects").into(),
))), ))),
span: DUMMY_SP, span: DUMMY_SP,
}))); })));
...@@ -2165,7 +2165,8 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -2165,7 +2165,8 @@ impl<C: Comments> VisitMut for ServerActions<C> {
vec![ vec![
ModuleItem::Stmt(Stmt::Expr(ExprStmt { ModuleItem::Stmt(Stmt::Expr(ExprStmt {
expr: Box::new(Expr::Lit(Lit::Str( expr: Box::new(Expr::Lit(Lit::Str(
"use turbopack no side effects".into(), atom!("use turbopack no side effects")
.into(),
))), ))),
span: DUMMY_SP, span: DUMMY_SP,
})), })),
......
...@@ -11,6 +11,7 @@ use next_custom_transforms::transforms::{ ...@@ -11,6 +11,7 @@ use next_custom_transforms::transforms::{
}; };
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use swc_core::{ use swc_core::{
atoms::atom,
common::{FileName, Mark}, common::{FileName, Mark},
ecma::{ ecma::{
parser::{EsSyntax, Syntax}, parser::{EsSyntax, Syntax},
...@@ -21,6 +22,7 @@ use swc_core::{ ...@@ -21,6 +22,7 @@ use swc_core::{
}, },
}; };
use testing::fixture; use testing::fixture;
use turbo_rcstr::rcstr;
fn syntax() -> Syntax { fn syntax() -> Syntax {
Syntax::Es(EsSyntax { Syntax::Es(EsSyntax {
...@@ -125,8 +127,8 @@ fn next_font_loaders_errors(input: PathBuf) { ...@@ -125,8 +127,8 @@ fn next_font_loaders_errors(input: PathBuf) {
syntax(), syntax(),
&|_tr| { &|_tr| {
next_font_loaders(FontLoaderConfig { next_font_loaders(FontLoaderConfig {
relative_file_path_from_root: "pages/test.tsx".into(), relative_file_path_from_root: atom!("pages/test.tsx"),
font_loaders: vec!["@next/font/google".into(), "cool-fonts".into()], font_loaders: vec![atom!("@next/font/google"), atom!("cool-fonts")],
}) })
}, },
&input, &input,
...@@ -231,7 +233,7 @@ fn use_cache_not_allowed(input: PathBuf) { ...@@ -231,7 +233,7 @@ fn use_cache_not_allowed(input: PathBuf) {
is_development: true, is_development: true,
use_cache_enabled: false, use_cache_enabled: false,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: FxHashSet::from_iter(["x".into()]), cache_kinds: FxHashSet::from_iter([rcstr!("x")]),
}, },
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
tr.cm.clone(), tr.cm.clone(),
......
...@@ -184,11 +184,11 @@ impl VisitMut for TransformVisitor { ...@@ -184,11 +184,11 @@ impl VisitMut for TransformVisitor {
callee: Callee::Expr(Box::new(Expr::Member(MemberExpr { callee: Callee::Expr(Box::new(Expr::Member(MemberExpr {
span: new_error_expr.span, span: new_error_expr.span,
obj: Box::new(Expr::Ident(Ident::new( obj: Box::new(Expr::Ident(Ident::new(
"Object".into(), rcstr!("Object"),
new_error_expr.span, new_error_expr.span,
Default::default(), Default::default(),
))), ))),
prop: MemberProp::Ident("defineProperty".into()), prop: MemberProp::Ident(rcstr!("defineProperty")),
}))), // Object.defineProperty( }))), // Object.defineProperty(
args: vec![ args: vec![
ExprOrSpread { ExprOrSpread {
...@@ -199,7 +199,7 @@ impl VisitMut for TransformVisitor { ...@@ -199,7 +199,7 @@ impl VisitMut for TransformVisitor {
spread: None, spread: None,
expr: Box::new(Expr::Lit(Lit::Str(Str { expr: Box::new(Expr::Lit(Lit::Str(Str {
span: new_error_expr.span, span: new_error_expr.span,
value: "__NEXT_ERROR_CODE".into(), value: rcstr!("__NEXT_ERROR_CODE"),
raw: None, raw: None,
}))), // "__NEXT_ERROR_CODE" }))), // "__NEXT_ERROR_CODE"
}, },
...@@ -209,7 +209,7 @@ impl VisitMut for TransformVisitor { ...@@ -209,7 +209,7 @@ impl VisitMut for TransformVisitor {
span: new_error_expr.span, span: new_error_expr.span,
props: vec![ props: vec![
PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident("value".into()), key: PropName::Ident(rcstr!("value")),
value: Box::new(Expr::Lit(Lit::Str(Str { value: Box::new(Expr::Lit(Lit::Str(Str {
span: new_error_expr.span, span: new_error_expr.span,
value: code.into(), value: code.into(),
...@@ -217,14 +217,14 @@ impl VisitMut for TransformVisitor { ...@@ -217,14 +217,14 @@ impl VisitMut for TransformVisitor {
}))), }))),
}))), }))),
PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident("enumerable".into()), key: PropName::Ident(rcstr!("enumerable")),
value: Box::new(Expr::Lit(Lit::Bool(Bool { value: Box::new(Expr::Lit(Lit::Bool(Bool {
span: new_error_expr.span, span: new_error_expr.span,
value: false, value: false,
}))), }))),
}))), }))),
PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident("configurable".into()), key: PropName::Ident(rcstr!("configurable")),
value: Box::new(Expr::Lit(Lit::Bool(Bool { value: Box::new(Expr::Lit(Lit::Bool(Bool {
span: new_error_expr.span, span: new_error_expr.span,
value: true, value: true,
......
...@@ -10,7 +10,7 @@ use std::{ ...@@ -10,7 +10,7 @@ use std::{
use anyhow::Result; use anyhow::Result;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ReadConsistency, TurboTasks, UpdateInfo, Vc, util::FormatDuration}; use turbo_tasks::{ReadConsistency, TurboTasks, UpdateInfo, Vc, util::FormatDuration};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage}; use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{ use turbo_tasks_fs::{
...@@ -35,7 +35,7 @@ async fn main() -> Result<()> { ...@@ -35,7 +35,7 @@ async fn main() -> Result<()> {
let task = tt.spawn_root_task(|| { let task = tt.spawn_root_task(|| {
Box::pin(async { Box::pin(async {
let root = current_dir().unwrap().to_str().unwrap().into(); let root = current_dir().unwrap().to_str().unwrap().into();
let disk_fs = DiskFileSystem::new("project".into(), root); let disk_fs = DiskFileSystem::new(rcstr!("project"), root);
disk_fs.await?.start_watching(None).await?; disk_fs.await?.start_watching(None).await?;
// Smart Pointer cast // Smart Pointer cast
......
...@@ -10,7 +10,7 @@ use std::{ ...@@ -10,7 +10,7 @@ use std::{
use anyhow::Result; use anyhow::Result;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ReadConsistency, TurboTasks, UpdateInfo, Vc, util::FormatDuration}; use turbo_tasks::{ReadConsistency, TurboTasks, UpdateInfo, Vc, util::FormatDuration};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage}; use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{ use turbo_tasks_fs::{
...@@ -32,13 +32,13 @@ async fn main() -> Result<()> { ...@@ -32,13 +32,13 @@ async fn main() -> Result<()> {
let task = tt.spawn_root_task(|| { let task = tt.spawn_root_task(|| {
Box::pin(async { Box::pin(async {
let root = current_dir().unwrap().to_str().unwrap().into(); let root = current_dir().unwrap().to_str().unwrap().into();
let disk_fs = DiskFileSystem::new("project".into(), root); let disk_fs = DiskFileSystem::new(rcstr!("project"), root);
disk_fs.await?.start_watching(None).await?; disk_fs.await?.start_watching(None).await?;
// Smart Pointer cast // Smart Pointer cast
let fs: Vc<Box<dyn FileSystem>> = Vc::upcast(disk_fs); let fs: Vc<Box<dyn FileSystem>> = Vc::upcast(disk_fs);
let input = fs.root().await?.join("crates")?; let input = fs.root().await?.join("crates")?;
let glob = Glob::new("**/*.rs".into()); let glob = Glob::new(rcstr!("**/*.rs"));
let glob_result = input.read_glob(glob); let glob_result = input.read_glob(glob);
let dir_hash = hash_glob_result(glob_result); let dir_hash = hash_glob_result(glob_result);
print_hash(dir_hash).await?; print_hash(dir_hash).await?;
......
use anyhow::Result; use anyhow::Result;
use regex::bytes::{Regex, RegexBuilder}; use regex::bytes::{Regex, RegexBuilder};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::Vc; use turbo_tasks::Vc;
use crate::globset::parse; use crate::globset::parse;
...@@ -100,7 +100,7 @@ impl Glob { ...@@ -100,7 +100,7 @@ impl Glob {
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn alternatives(globs: Vec<Vc<Glob>>) -> Result<Vc<Self>> { pub async fn alternatives(globs: Vec<Vc<Glob>>) -> Result<Vc<Self>> {
match globs.len() { match globs.len() {
0 => Ok(Glob::new("".into())), 0 => Ok(Glob::new(rcstr!(""))),
1 => Ok(globs.into_iter().next().unwrap()), 1 => Ok(globs.into_iter().next().unwrap()),
_ => { _ => {
let mut new_glob = String::new(); let mut new_glob = String::new();
......
...@@ -193,7 +193,7 @@ pub mod tests { ...@@ -193,7 +193,7 @@ pub mod tests {
io::prelude::*, io::prelude::*,
}; };
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Completion, ReadRef, Vc, apply_effects}; use turbo_tasks::{Completion, ReadRef, Vc, apply_effects};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage}; use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
...@@ -224,11 +224,11 @@ pub mod tests { ...@@ -224,11 +224,11 @@ pub mod tests {
)); ));
let path: RcStr = scratch.path().to_str().unwrap().into(); let path: RcStr = scratch.path().to_str().unwrap().into();
tt.run_once(async { tt.run_once(async {
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new("temp".into(), path)); let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), path));
let read_dir = fs let read_dir = fs
.root() .root()
.await? .await?
.read_glob(Glob::new("**".into())) .read_glob(Glob::new(rcstr!("**")))
.await .await
.unwrap(); .unwrap();
assert_eq!(read_dir.results.len(), 2); assert_eq!(read_dir.results.len(), 2);
...@@ -253,7 +253,7 @@ pub mod tests { ...@@ -253,7 +253,7 @@ pub mod tests {
let read_dir = fs let read_dir = fs
.root() .root()
.await? .await?
.read_glob(Glob::new("**/bar".into())) .read_glob(Glob::new(rcstr!("**/bar")))
.await .await
.unwrap(); .unwrap();
assert_eq!(read_dir.results.len(), 0); assert_eq!(read_dir.results.len(), 0);
...@@ -294,11 +294,11 @@ pub mod tests { ...@@ -294,11 +294,11 @@ pub mod tests {
)); ));
let path: RcStr = scratch.path().to_str().unwrap().into(); let path: RcStr = scratch.path().to_str().unwrap().into();
tt.run_once(async { tt.run_once(async {
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new("temp".into(), path)); let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), path));
let read_dir = fs let read_dir = fs
.root() .root()
.await? .await?
.read_glob(Glob::new("*.js".into())) .read_glob(Glob::new(rcstr!("*.js")))
.await .await
.unwrap(); .unwrap();
assert_eq!(read_dir.results.len(), 1); assert_eq!(read_dir.results.len(), 1);
...@@ -331,7 +331,7 @@ pub mod tests { ...@@ -331,7 +331,7 @@ pub mod tests {
#[turbo_tasks::function(operation)] #[turbo_tasks::function(operation)]
pub fn track_star_star_glob(path: FileSystemPath) -> Vc<Completion> { pub fn track_star_star_glob(path: FileSystemPath) -> Vc<Completion> {
path.track_glob(Glob::new("**".into()), false) path.track_glob(Glob::new(rcstr!("**")), false)
} }
#[cfg(unix)] #[cfg(unix)]
...@@ -375,7 +375,7 @@ pub mod tests { ...@@ -375,7 +375,7 @@ pub mod tests {
)); ));
let path: RcStr = scratch.path().to_str().unwrap().into(); let path: RcStr = scratch.path().to_str().unwrap().into();
tt.run_once(async { tt.run_once(async {
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new("temp".into(), path)); let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), path));
let dir = fs.root().await?.join("dir")?; let dir = fs.root().await?.join("dir")?;
let read_dir = track_star_star_glob(dir.clone()) let read_dir = track_star_star_glob(dir.clone())
.read_strongly_consistent() .read_strongly_consistent()
...@@ -405,7 +405,7 @@ pub mod tests { ...@@ -405,7 +405,7 @@ pub mod tests {
// Modify a symlink target file // Modify a symlink target file
let write_result = write( let write_result = write(
fs.root().await?.join("link_target.js")?, fs.root().await?.join("link_target.js")?,
"new_contents".into(), rcstr!("new_contents"),
); );
write_result.read_strongly_consistent().await?; write_result.read_strongly_consistent().await?;
apply_effects(write_result).await?; apply_effects(write_result).await?;
...@@ -445,11 +445,13 @@ pub mod tests { ...@@ -445,11 +445,13 @@ pub mod tests {
)); ));
let path: RcStr = scratch.path().to_str().unwrap().into(); let path: RcStr = scratch.path().to_str().unwrap().into();
tt.run_once(async { tt.run_once(async {
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new("temp".into(), path)); use turbo_rcstr::rcstr;
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), path));
let err = fs let err = fs
.root() .root()
.await? .await?
.track_glob(Glob::new("**".into()), false) .track_glob(Glob::new(rcstr!("**")), false)
.await .await
.expect_err("Should have detected an infinite loop"); .expect_err("Should have detected an infinite loop");
...@@ -462,7 +464,7 @@ pub mod tests { ...@@ -462,7 +464,7 @@ pub mod tests {
let err = fs let err = fs
.root() .root()
.await? .await?
.track_glob(Glob::new("**".into()), false) .track_glob(Glob::new(rcstr!("**")), false)
.await .await
.expect_err("Should have detected an infinite loop"); .expect_err("Should have detected an infinite loop");
...@@ -501,11 +503,11 @@ pub mod tests { ...@@ -501,11 +503,11 @@ pub mod tests {
)); ));
let path: RcStr = scratch.path().to_str().unwrap().into(); let path: RcStr = scratch.path().to_str().unwrap().into();
tt.run_once(async { tt.run_once(async {
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new("temp".into(), path)); let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), path));
let err = fs let err = fs
.root() .root()
.await? .await?
.read_glob(Glob::new("**".into())) .read_glob(Glob::new(rcstr!("**")))
.await .await
.expect_err("Should have detected an infinite loop"); .expect_err("Should have detected an infinite loop");
...@@ -518,7 +520,7 @@ pub mod tests { ...@@ -518,7 +520,7 @@ pub mod tests {
let err = fs let err = fs
.root() .root()
.await? .await?
.track_glob(Glob::new("**".into()), false) .track_glob(Glob::new(rcstr!("**")), false)
.await .await
.expect_err("Should have detected an infinite loop"); .expect_err("Should have detected an infinite loop");
......
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ValueDefault, ValueToString, Vc}; use turbo_tasks::{ValueDefault, ValueToString, Vc};
use super::{FileContent, FileMeta, FileSystem, FileSystemPath, LinkContent}; use super::{FileContent, FileMeta, FileSystem, FileSystemPath, LinkContent};
...@@ -21,7 +21,7 @@ impl VirtualFileSystem { ...@@ -21,7 +21,7 @@ impl VirtualFileSystem {
/// [`Vc<VirtualFileSystem>`]. /// [`Vc<VirtualFileSystem>`].
pub fn new() -> Vc<Self> { pub fn new() -> Vc<Self> {
Self::cell(VirtualFileSystem { Self::cell(VirtualFileSystem {
name: "virtual file system".into(), name: rcstr!("virtual file system"),
}) })
} }
......
...@@ -44,23 +44,23 @@ impl fmt::Display for NodeEnv { ...@@ -44,23 +44,23 @@ impl fmt::Display for NodeEnv {
} }
} }
async fn foreign_code_context_condition() -> Result<ContextCondition> { fn foreign_code_context_condition() -> ContextCondition {
Ok(ContextCondition::InDirectory("node_modules".to_string())) ContextCondition::InDirectory("node_modules".to_string())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn get_client_import_map(project_path: FileSystemPath) -> Result<Vc<ImportMap>> { pub async fn get_client_import_map(project_path: FileSystemPath) -> Result<Vc<ImportMap>> {
let mut import_map = ImportMap::empty(); let mut import_map = ImportMap::empty();
import_map.insert_singleton_alias("@swc/helpers", project_path.clone()); import_map.insert_singleton_alias(rcstr!("@swc/helpers"), project_path.clone());
import_map.insert_singleton_alias("styled-jsx", project_path.clone()); import_map.insert_singleton_alias(rcstr!("styled-jsx"), project_path.clone());
import_map.insert_singleton_alias("react", project_path.clone()); import_map.insert_singleton_alias(rcstr!("react"), project_path.clone());
import_map.insert_singleton_alias("react-dom", project_path.clone()); import_map.insert_singleton_alias(rcstr!("react-dom"), project_path.clone());
import_map.insert_wildcard_alias( import_map.insert_wildcard_alias(
"@vercel/turbopack-ecmascript-runtime/", rcstr!("@vercel/turbopack-ecmascript-runtime/"),
ImportMapping::PrimaryAlternative( ImportMapping::PrimaryAlternative(
"./*".into(), rcstr!("./*"),
Some( Some(
turbopack_ecmascript_runtime::embed_fs() turbopack_ecmascript_runtime::embed_fs()
.root() .root()
...@@ -84,7 +84,7 @@ pub async fn get_client_resolve_options_context( ...@@ -84,7 +84,7 @@ pub async fn get_client_resolve_options_context(
.await?; .await?;
let module_options_context = ResolveOptionsContext { let module_options_context = ResolveOptionsContext {
enable_node_modules: Some(project_path.root().owned().await?), enable_node_modules: Some(project_path.root().owned().await?),
custom_conditions: vec![node_env.await?.to_string().into(), "browser".into()], custom_conditions: vec![node_env.await?.to_string().into(), rcstr!("browser")],
import_map: Some(next_client_import_map), import_map: Some(next_client_import_map),
browser: true, browser: true,
module: true, module: true,
...@@ -94,7 +94,7 @@ pub async fn get_client_resolve_options_context( ...@@ -94,7 +94,7 @@ pub async fn get_client_resolve_options_context(
enable_typescript: true, enable_typescript: true,
enable_react: true, enable_react: true,
rules: vec![( rules: vec![(
foreign_code_context_condition().await?, foreign_code_context_condition(),
module_options_context.clone().resolved_cell(), module_options_context.clone().resolved_cell(),
)], )],
..module_options_context ..module_options_context
...@@ -161,7 +161,7 @@ async fn get_client_module_options_context( ...@@ -161,7 +161,7 @@ async fn get_client_module_options_context(
}, },
enable_postcss_transform: Some(PostCssTransformOptions::default().resolved_cell()), enable_postcss_transform: Some(PostCssTransformOptions::default().resolved_cell()),
rules: vec![( rules: vec![(
foreign_code_context_condition().await?, foreign_code_context_condition(),
module_options_context.clone().resolved_cell(), module_options_context.clone().resolved_cell(),
)], )],
module_rules: vec![module_rules], module_rules: vec![module_rules],
......
...@@ -3,7 +3,7 @@ use std::{env::current_dir, path::PathBuf}; ...@@ -3,7 +3,7 @@ use std::{env::current_dir, path::PathBuf};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use dunce::canonicalize; use dunce::canonicalize;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, TaskInput, Vc, trace::TraceRawVcs}; use turbo_tasks::{NonLocalValue, TaskInput, Vc, trace::TraceRawVcs};
use turbo_tasks_fs::{DiskFileSystem, FileSystem}; use turbo_tasks_fs::{DiskFileSystem, FileSystem};
...@@ -56,12 +56,12 @@ pub fn normalize_entries(entries: &Option<Vec<String>>) -> Vec<RcStr> { ...@@ -56,12 +56,12 @@ pub fn normalize_entries(entries: &Option<Vec<String>>) -> Vec<RcStr> {
entries entries
.as_ref() .as_ref()
.map(|v| v.iter().map(|v| RcStr::from(&**v)).collect()) .map(|v| v.iter().map(|v| RcStr::from(&**v)).collect())
.unwrap_or_else(|| vec!["src/entry".into()]) .unwrap_or_else(|| vec![rcstr!("src/entry")])
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn project_fs(project_dir: RcStr, watch: bool) -> Result<Vc<Box<dyn FileSystem>>> { pub async fn project_fs(project_dir: RcStr, watch: bool) -> Result<Vc<Box<dyn FileSystem>>> {
let disk_fs = DiskFileSystem::new("project".into(), project_dir); let disk_fs = DiskFileSystem::new(rcstr!("project"), project_dir);
if watch { if watch {
disk_fs.await?.start_watching(None).await?; disk_fs.await?.start_watching(None).await?;
} }
...@@ -70,6 +70,6 @@ pub async fn project_fs(project_dir: RcStr, watch: bool) -> Result<Vc<Box<dyn Fi ...@@ -70,6 +70,6 @@ pub async fn project_fs(project_dir: RcStr, watch: bool) -> Result<Vc<Box<dyn Fi
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn output_fs(project_dir: RcStr) -> Result<Vc<Box<dyn FileSystem>>> { pub fn output_fs(project_dir: RcStr) -> Result<Vc<Box<dyn FileSystem>>> {
let disk_fs = DiskFileSystem::new("output".into(), project_dir); let disk_fs = DiskFileSystem::new(rcstr!("output"), project_dir);
Ok(Vc::upcast(disk_fs)) Ok(Vc::upcast(disk_fs))
} }
...@@ -3,6 +3,7 @@ use std::{collections::HashSet, sync::atomic::AtomicBool}; ...@@ -3,6 +3,7 @@ use std::{collections::HashSet, sync::atomic::AtomicBool};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use smallvec::{SmallVec, smallvec}; use smallvec::{SmallVec, smallvec};
use turbo_rcstr::rcstr;
use turbo_tasks::{FxIndexSet, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Vc}; use turbo_tasks::{FxIndexSet, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Vc};
use super::{ use super::{
...@@ -150,7 +151,7 @@ pub async fn make_chunk_group( ...@@ -150,7 +151,7 @@ pub async fn make_chunk_group(
chunking_context, chunking_context,
chunk_items, chunk_items,
chunk_item_batch_groups, chunk_item_batch_groups,
"".into(), rcstr!(""),
ResolvedVc::cell(referenced_output_assets), ResolvedVc::cell(referenced_output_assets),
) )
.await?; .await?;
......
use anyhow::Result; use anyhow::Result;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use crate::{ use crate::{
...@@ -49,7 +50,7 @@ pub async fn make_style_production_chunks( ...@@ -49,7 +50,7 @@ pub async fn make_style_production_chunks(
vec![&ChunkItemOrBatchWithInfo::ChunkItem { vec![&ChunkItemOrBatchWithInfo::ChunkItem {
chunk_item: chunk_item.clone(), chunk_item: chunk_item.clone(),
size: 0, size: 0,
asset_ident: "".into(), asset_ident: rcstr!(""),
}], }],
vec![], vec![],
&mut String::new(), &mut String::new(),
......
...@@ -236,6 +236,11 @@ impl From<String> for FreeVarReference { ...@@ -236,6 +236,11 @@ impl From<String> for FreeVarReference {
Self::Value(value.into()) Self::Value(value.into())
} }
} }
impl From<RcStr> for FreeVarReference {
fn from(value: RcStr) -> Self {
Self::Value(value.into())
}
}
impl From<&str> for FreeVarReference { impl From<&str> for FreeVarReference {
fn from(value: &str) -> Self { fn from(value: &str) -> Self {
...@@ -366,6 +371,7 @@ impl CompileTimeInfoBuilder { ...@@ -366,6 +371,7 @@ impl CompileTimeInfoBuilder {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use turbo_rcstr::rcstr;
use turbo_tasks::FxIndexMap; use turbo_tasks::FxIndexMap;
use crate::compile_time_info::{DefinableNameSegment, FreeVarReference, FreeVarReferences}; use crate::compile_time_info::{DefinableNameSegment, FreeVarReference, FreeVarReferences};
...@@ -377,20 +383,26 @@ mod test { ...@@ -377,20 +383,26 @@ mod test {
FOO = "bar", FOO = "bar",
FOO = false, FOO = false,
Buffer = FreeVarReference::EcmaScriptModule { Buffer = FreeVarReference::EcmaScriptModule {
request: "node:buffer".into(), request: rcstr!("node:buffer"),
lookup_path: None, lookup_path: None,
export: Some("Buffer".into()), export: Some(rcstr!("Buffer")),
}, },
), ),
FreeVarReferences(FxIndexMap::from_iter(vec![ FreeVarReferences(FxIndexMap::from_iter(vec![
(vec!["FOO".into()], FreeVarReference::Value("bar".into())),
(vec!["FOO".into()], FreeVarReference::Value(false.into())),
( (
vec!["Buffer".into()], vec![rcstr!("FOO").into()],
FreeVarReference::Value(rcstr!("bar").into())
),
(
vec![rcstr!("FOO").into()],
FreeVarReference::Value(false.into())
),
(
vec![rcstr!("Buffer").into()],
FreeVarReference::EcmaScriptModule { FreeVarReference::EcmaScriptModule {
request: "node:buffer".into(), request: rcstr!("node:buffer"),
lookup_path: None, lookup_path: None,
export: Some("Buffer".into()), export: Some(rcstr!("Buffer")),
} }
), ),
])) ]))
...@@ -407,21 +419,34 @@ mod test { ...@@ -407,21 +419,34 @@ mod test {
), ),
FreeVarReferences(FxIndexMap::from_iter(vec![ FreeVarReferences(FxIndexMap::from_iter(vec![
( (
vec!["x".into(), DefinableNameSegment::TypeOf], vec![rcstr!("x").into(), DefinableNameSegment::TypeOf],
FreeVarReference::Value("a".into()) FreeVarReference::Value(rcstr!("a").into())
), ),
( (
vec!["x".into(), "y".into(), DefinableNameSegment::TypeOf], vec![
FreeVarReference::Value("b".into()) rcstr!("x").into(),
rcstr!("y").into(),
DefinableNameSegment::TypeOf
],
FreeVarReference::Value(rcstr!("b").into())
),
(
vec![
rcstr!("x").into(),
rcstr!("y").into(),
rcstr!("z").into(),
DefinableNameSegment::TypeOf
],
FreeVarReference::Value(rcstr!("b").into())
), ),
( (
vec![ vec![
"x".into(), rcstr!("x").into(),
"y".into(), rcstr!("y").into(),
"z".into(), rcstr!("z").into(),
DefinableNameSegment::TypeOf DefinableNameSegment::TypeOf
], ],
FreeVarReference::Value("c".into()) FreeVarReference::Value(rcstr!("c").into())
) )
])) ]))
); );
......
...@@ -112,7 +112,7 @@ impl Environment { ...@@ -112,7 +112,7 @@ impl Environment {
// browserslist correctly because CSS Modules in client components is double-processed, // browserslist correctly because CSS Modules in client components is double-processed,
// once for server once for browser. // once for server once for browser.
{ {
Vc::cell("".into()) Vc::cell(rcstr!(""))
} }
ExecutionEnvironment::Browser(browser_env) => { ExecutionEnvironment::Browser(browser_env) => {
Vc::cell(browser_env.await?.browserslist_query.clone()) Vc::cell(browser_env.await?.browserslist_query.clone())
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
...@@ -47,15 +47,15 @@ impl Issue for AnalyzeIssue { ...@@ -47,15 +47,15 @@ impl Issue for AnalyzeIssue {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn title(&self) -> Result<Vc<StyledString>> { async fn title(&self) -> Result<Vc<StyledString>> {
let title = &**self.title.await?; let title = &*self.title.await?;
Ok(if let Some(code) = self.code.as_ref() { Ok(if let Some(code) = self.code.as_ref() {
StyledString::Line(vec![ StyledString::Line(vec![
StyledString::Strong(code.clone()), StyledString::Strong(code.clone()),
StyledString::Text(" ".into()), StyledString::Text(rcstr!(" ")),
StyledString::Text(title.into()), StyledString::Text(title.clone()),
]) ])
} else { } else {
StyledString::Text(title.into()) StyledString::Text(title.clone())
} }
.cell()) .cell())
} }
......
...@@ -785,7 +785,7 @@ pub enum IssueStage { ...@@ -785,7 +785,7 @@ pub enum IssueStage {
CodeGen, CodeGen,
Unsupported, Unsupported,
Misc, Misc,
Other(String), Other(RcStr),
} }
impl Display for IssueStage { impl Display for IssueStage {
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
...@@ -50,7 +51,7 @@ impl Issue for ModuleIssue { ...@@ -50,7 +51,7 @@ impl Issue for ModuleIssue {
pub async fn emit_unknown_module_type_error(source: Vc<Box<dyn Source>>) -> Result<()> { pub async fn emit_unknown_module_type_error(source: Vc<Box<dyn Source>>) -> Result<()> {
ModuleIssue { ModuleIssue {
ident: source.ident().to_resolved().await?, ident: source.ident().to_resolved().await?,
title: StyledString::Text("Unknown module type".into()).resolved_cell(), title: StyledString::Text(rcstr!("Unknown module type")).resolved_cell(),
description: StyledString::Text( description: StyledString::Text(
r"This module doesn't have an associated type. Use a known file extension, or register a loader for it. r"This module doesn't have an associated type. Use a known file extension, or register a loader for it.
......
use std::fmt::Write; use std::fmt::Write;
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ReadRef, ResolvedVc, ValueToString, Vc}; use turbo_tasks::{ReadRef, ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
...@@ -36,8 +36,8 @@ impl Issue for ResolvingIssue { ...@@ -36,8 +36,8 @@ impl Issue for ResolvingIssue {
async fn title(&self) -> Result<Vc<StyledString>> { async fn title(&self) -> Result<Vc<StyledString>> {
let request = self.request.request_pattern().to_string().owned().await?; let request = self.request.request_pattern().to_string().owned().await?;
Ok(StyledString::Line(vec![ Ok(StyledString::Line(vec![
StyledString::Strong("Module not found".into()), StyledString::Strong(rcstr!("Module not found")),
StyledString::Text(": Can't resolve ".into()), StyledString::Text(rcstr!(": Can't resolve ")),
StyledString::Code(request), StyledString::Code(request),
]) ])
.cell()) .cell())
......
...@@ -702,6 +702,8 @@ pub trait AliasTemplate { ...@@ -702,6 +702,8 @@ pub trait AliasTemplate {
mod test { mod test {
use std::assert_matches::assert_matches; use std::assert_matches::assert_matches;
use turbo_rcstr::rcstr;
use super::{AliasMap, AliasPattern, AliasTemplate}; use super::{AliasMap, AliasPattern, AliasTemplate};
use crate::resolve::pattern::Pattern; use crate::resolve::pattern::Pattern;
...@@ -916,37 +918,37 @@ mod test { ...@@ -916,37 +918,37 @@ mod test {
assert_eq!( assert_eq!(
map.lookup(&Pattern::Concatenation(vec![ map.lookup(&Pattern::Concatenation(vec![
Pattern::Constant("card/".into()), Pattern::Constant(rcstr!("card/")),
Pattern::Dynamic Pattern::Dynamic
])) ]))
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
vec![super::AliasMatch::Replaced(Pattern::Concatenation(vec![ vec![super::AliasMatch::Replaced(Pattern::Concatenation(vec![
Pattern::Constant("src/cards/".into()), Pattern::Constant(rcstr!("src/cards/")),
Pattern::Dynamic Pattern::Dynamic
]))] ]))]
); );
assert_eq!( assert_eq!(
map.lookup(&Pattern::Concatenation(vec![ map.lookup(&Pattern::Concatenation(vec![
Pattern::Constant("comp/".into()), Pattern::Constant(rcstr!("comp/")),
Pattern::Dynamic, Pattern::Dynamic,
Pattern::Constant("/x".into()), Pattern::Constant(rcstr!("/x")),
])) ]))
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
vec![super::AliasMatch::Replaced(Pattern::Concatenation(vec![ vec![super::AliasMatch::Replaced(Pattern::Concatenation(vec![
Pattern::Constant("src/comps/".into()), Pattern::Constant(rcstr!("src/comps/")),
Pattern::Dynamic, Pattern::Dynamic,
Pattern::Constant("/x".into()), Pattern::Constant(rcstr!("/x")),
]))] ]))]
); );
assert_eq!( assert_eq!(
map.lookup(&Pattern::Concatenation(vec![ map.lookup(&Pattern::Concatenation(vec![
Pattern::Constant("head/".into()), Pattern::Constant(rcstr!("head/")),
Pattern::Dynamic, Pattern::Dynamic,
Pattern::Constant("/x".into()), Pattern::Constant(rcstr!("/x")),
])) ]))
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
vec![super::AliasMatch::Replaced(Pattern::Concatenation(vec![ vec![super::AliasMatch::Replaced(Pattern::Concatenation(vec![
Pattern::Constant("src/heads/".into()), Pattern::Constant(rcstr!("src/heads/")),
Pattern::Dynamic, Pattern::Dynamic,
]))] ]))]
); );
......
use turbo_rcstr::rcstr;
use turbo_tasks::Vc; use turbo_tasks::Vc;
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
...@@ -9,28 +10,28 @@ use super::options::{ ...@@ -9,28 +10,28 @@ use super::options::{
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn node_cjs_resolve_options(root: FileSystemPath) -> Vc<ResolveOptions> { pub fn node_cjs_resolve_options(root: FileSystemPath) -> Vc<ResolveOptions> {
let conditions: ResolutionConditions = [ let conditions: ResolutionConditions = [
("node".into(), ConditionValue::Set), (rcstr!("node"), ConditionValue::Set),
("require".into(), ConditionValue::Set), (rcstr!("require"), ConditionValue::Set),
] ]
.into(); .into();
let extensions = vec![".js".into(), ".json".into(), ".node".into()]; let extensions = vec![rcstr!(".js"), rcstr!(".json"), rcstr!(".node")];
ResolveOptions { ResolveOptions {
extensions, extensions,
modules: vec![ResolveModules::Nested(root, vec!["node_modules".into()])], modules: vec![ResolveModules::Nested(root, vec![rcstr!("node_modules")])],
into_package: vec![ into_package: vec![
ResolveIntoPackage::ExportsField { ResolveIntoPackage::ExportsField {
conditions: conditions.clone(), conditions: conditions.clone(),
unspecified_conditions: ConditionValue::Unset, unspecified_conditions: ConditionValue::Unset,
}, },
ResolveIntoPackage::MainField { ResolveIntoPackage::MainField {
field: "main".into(), field: rcstr!("main"),
}, },
], ],
in_package: vec![ResolveInPackage::ImportsField { in_package: vec![ResolveInPackage::ImportsField {
conditions, conditions,
unspecified_conditions: ConditionValue::Unset, unspecified_conditions: ConditionValue::Unset,
}], }],
default_files: vec!["index".into()], default_files: vec![rcstr!("index")],
..Default::default() ..Default::default()
} }
.cell() .cell()
...@@ -39,29 +40,29 @@ pub fn node_cjs_resolve_options(root: FileSystemPath) -> Vc<ResolveOptions> { ...@@ -39,29 +40,29 @@ pub fn node_cjs_resolve_options(root: FileSystemPath) -> Vc<ResolveOptions> {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn node_esm_resolve_options(root: FileSystemPath) -> Vc<ResolveOptions> { pub fn node_esm_resolve_options(root: FileSystemPath) -> Vc<ResolveOptions> {
let conditions: ResolutionConditions = [ let conditions: ResolutionConditions = [
("node".into(), ConditionValue::Set), (rcstr!("node"), ConditionValue::Set),
("import".into(), ConditionValue::Set), (rcstr!("import"), ConditionValue::Set),
] ]
.into(); .into();
let extensions = vec![".js".into(), ".json".into(), ".node".into()]; let extensions = vec![rcstr!(".js"), rcstr!(".json"), rcstr!(".node")];
ResolveOptions { ResolveOptions {
fully_specified: true, fully_specified: true,
extensions, extensions,
modules: vec![ResolveModules::Nested(root, vec!["node_modules".into()])], modules: vec![ResolveModules::Nested(root, vec![rcstr!("node_modules")])],
into_package: vec![ into_package: vec![
ResolveIntoPackage::ExportsField { ResolveIntoPackage::ExportsField {
conditions: conditions.clone(), conditions: conditions.clone(),
unspecified_conditions: ConditionValue::Unset, unspecified_conditions: ConditionValue::Unset,
}, },
ResolveIntoPackage::MainField { ResolveIntoPackage::MainField {
field: "main".into(), field: rcstr!("main"),
}, },
], ],
in_package: vec![ResolveInPackage::ImportsField { in_package: vec![ResolveInPackage::ImportsField {
conditions, conditions,
unspecified_conditions: ConditionValue::Unset, unspecified_conditions: ConditionValue::Unset,
}], }],
default_files: vec!["index".into()], default_files: vec![rcstr!("index")],
..Default::default() ..Default::default()
} }
.cell() .cell()
......
...@@ -335,7 +335,8 @@ impl ImportMap { ...@@ -335,7 +335,8 @@ impl ImportMap {
prefix: impl Into<RcStr> + 'a, prefix: impl Into<RcStr> + 'a,
mapping: ResolvedVc<ImportMapping>, mapping: ResolvedVc<ImportMapping>,
) { ) {
self.map.insert(AliasPattern::wildcard(prefix, ""), mapping); self.map
.insert(AliasPattern::wildcard(prefix, rcstr!("")), mapping);
} }
/// Inserts a wildcard alias with suffix into the import map. /// Inserts a wildcard alias with suffix into the import map.
......
...@@ -487,7 +487,7 @@ fn is_folder_shorthand(key: &str) -> bool { ...@@ -487,7 +487,7 @@ fn is_folder_shorthand(key: &str) -> bool {
/// we do the expansion here. /// we do the expansion here.
fn expand_folder_shorthand(key: &str, value: &mut SubpathValue) -> Result<AliasPattern> { fn expand_folder_shorthand(key: &str, value: &mut SubpathValue) -> Result<AliasPattern> {
// Transform folder patterns into wildcard patterns. // Transform folder patterns into wildcard patterns.
let pattern = AliasPattern::wildcard(key, ""); let pattern = AliasPattern::wildcard(key, rcstr!(""));
// Transform templates into wildcard patterns as well. // Transform templates into wildcard patterns as well.
for result in value.results_mut() { for result in value.results_mut() {
......
...@@ -7,7 +7,7 @@ use ref_cast::RefCast; ...@@ -7,7 +7,7 @@ use ref_cast::RefCast;
use regex::Regex; use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::{Deserialize, Deserializer, Serialize, Serializer};
use swc_sourcemap::{DecodedMap, SourceMap as RegularMap, SourceMapBuilder, SourceMapIndex}; use swc_sourcemap::{DecodedMap, SourceMap as RegularMap, SourceMapBuilder, SourceMapIndex};
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc}; use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc};
use turbo_tasks_fs::{ use turbo_tasks_fs::{
File, FileContent, FileSystem, FileSystemPath, VirtualFileSystem, File, FileContent, FileSystem, FileSystemPath, VirtualFileSystem,
...@@ -548,7 +548,7 @@ impl SourceMap { ...@@ -548,7 +548,7 @@ impl SourceMap {
#[turbo_tasks::function] #[turbo_tasks::function]
fn sourcemap_content_fs_root() -> Vc<FileSystemPath> { fn sourcemap_content_fs_root() -> Vc<FileSystemPath> {
VirtualFileSystem::new_with_name("sourcemap-content".into()).root() VirtualFileSystem::new_with_name(rcstr!("sourcemap-content")).root()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{File, FileSystemPath}; use turbo_tasks_fs::{File, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
...@@ -37,7 +38,7 @@ impl OutputAsset for SingleItemCssChunkSourceMapAsset { ...@@ -37,7 +38,7 @@ impl OutputAsset for SingleItemCssChunkSourceMapAsset {
Some(Vc::upcast(self)), Some(Vc::upcast(self)),
this.chunk.ident_for_path(), this.chunk.ident_for_path(),
None, None,
".single.css".into(), rcstr!(".single.css"),
) )
.await? .await?
.append(".map")? .append(".map")?
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{File, FileSystemPath}; use turbo_tasks_fs::{File, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
...@@ -34,7 +35,7 @@ impl OutputAsset for CssChunkSourceMapAsset { ...@@ -34,7 +35,7 @@ impl OutputAsset for CssChunkSourceMapAsset {
.chunk .chunk
.await? .await?
.chunking_context .chunking_context
.chunk_path(Some(Vc::upcast(self)), ident, None, ".css".into()) .chunk_path(Some(Vc::upcast(self)), ident, None, rcstr!(".css"))
.await? .await?
.append(".map")? .append(".map")?
.cell()) .cell())
......
...@@ -385,7 +385,7 @@ impl Issue for FatalStreamIssue { ...@@ -385,7 +385,7 @@ impl Issue for FatalStreamIssue {
#[turbo_tasks::function] #[turbo_tasks::function]
fn stage(&self) -> Vc<IssueStage> { fn stage(&self) -> Vc<IssueStage> {
IssueStage::Other("websocket".into()).cell() IssueStage::Other(rcstr!("websocket")).cell()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbopack_core::{ use turbopack_core::{
code_builder::{Code, CodeBuilder}, code_builder::{Code, CodeBuilder},
...@@ -17,27 +18,27 @@ pub async fn get_nodejs_runtime_code( ...@@ -17,27 +18,27 @@ pub async fn get_nodejs_runtime_code(
let shared_runtime_utils_code = embed_static_code( let shared_runtime_utils_code = embed_static_code(
asset_context, asset_context,
"shared/runtime-utils.ts".into(), rcstr!("shared/runtime-utils.ts"),
generate_source_map, generate_source_map,
); );
let shared_base_external_utils_code = embed_static_code( let shared_base_external_utils_code = embed_static_code(
asset_context, asset_context,
"shared-node/base-externals-utils.ts".into(), rcstr!("shared-node/base-externals-utils.ts"),
generate_source_map, generate_source_map,
); );
let shared_node_external_utils_code = embed_static_code( let shared_node_external_utils_code = embed_static_code(
asset_context, asset_context,
"shared-node/node-externals-utils.ts".into(), rcstr!("shared-node/node-externals-utils.ts"),
generate_source_map, generate_source_map,
); );
let shared_node_wasm_utils_code = embed_static_code( let shared_node_wasm_utils_code = embed_static_code(
asset_context, asset_context,
"shared-node/node-wasm-utils.ts".into(), rcstr!("shared-node/node-wasm-utils.ts"),
generate_source_map, generate_source_map,
); );
let runtime_code = embed_static_code( let runtime_code = embed_static_code(
asset_context, asset_context,
"nodejs/runtime.ts".into(), rcstr!("nodejs/runtime.ts"),
generate_source_map, generate_source_map,
); );
......
...@@ -40,7 +40,7 @@ static ANNOTATION_CHUNKING_TYPE: Lazy<Atom> = ...@@ -40,7 +40,7 @@ static ANNOTATION_CHUNKING_TYPE: Lazy<Atom> =
Lazy::new(|| crate::annotations::ANNOTATION_CHUNKING_TYPE.into()); Lazy::new(|| crate::annotations::ANNOTATION_CHUNKING_TYPE.into());
/// Changes the type of the resolved module (only "json" is supported currently) /// Changes the type of the resolved module (only "json" is supported currently)
static ATTRIBUTE_MODULE_TYPE: Lazy<Atom> = Lazy::new(|| "type".into()); static ATTRIBUTE_MODULE_TYPE: Lazy<Atom> = Lazy::new(|| atom!("type"));
impl ImportAnnotations { impl ImportAnnotations {
pub fn parse(with: Option<&ObjectLit>) -> ImportAnnotations { pub fn parse(with: Option<&ObjectLit>) -> ImportAnnotations {
...@@ -497,7 +497,7 @@ impl Visit for Analyzer<'_> { ...@@ -497,7 +497,7 @@ impl Visit for Analyzer<'_> {
Some(imported) => (local.to_id(), orig_name(imported)), Some(imported) => (local.to_id(), orig_name(imported)),
_ => (local.to_id(), local.sym.clone()), _ => (local.to_id(), local.sym.clone()),
}, },
ImportSpecifier::Default(s) => (s.local.to_id(), "default".into()), ImportSpecifier::Default(s) => (s.local.to_id(), atom!("default")),
ImportSpecifier::Namespace(s) => { ImportSpecifier::Namespace(s) => {
self.data.namespace_imports.insert(s.local.to_id(), i); self.data.namespace_imports.insert(s.local.to_id(), i);
continue; continue;
......
...@@ -3960,8 +3960,8 @@ pub mod test_utils { ...@@ -3960,8 +3960,8 @@ pub mod test_utils {
} }
} }
JsValue::FreeVar(ref var) => match &**var { JsValue::FreeVar(ref var) => match &**var {
"__dirname" => "__dirname".into(), "__dirname" => rcstr!("__dirname").into(),
"__filename" => "__filename".into(), "__filename" => rcstr!("__filename").into(),
"require" => JsValue::unknown_if( "require" => JsValue::unknown_if(
ignore, ignore,
......
use std::mem::take; use std::mem::take;
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::rcstr;
use turbo_tasks::Vc; use turbo_tasks::Vc;
use turbopack_core::compile_time_info::CompileTimeInfo; use turbopack_core::compile_time_info::CompileTimeInfo;
use url::Url; use url::Url;
...@@ -162,7 +163,7 @@ pub fn object_assign(args: Vec<JsValue>) -> JsValue { ...@@ -162,7 +163,7 @@ pub fn object_assign(args: Vec<JsValue>) -> JsValue {
pub fn path_join(args: Vec<JsValue>) -> JsValue { pub fn path_join(args: Vec<JsValue>) -> JsValue {
if args.is_empty() { if args.is_empty() {
return ".".into(); return rcstr!(".").into();
} }
let mut parts = Vec::new(); let mut parts = Vec::new();
for item in args { for item in args {
...@@ -203,9 +204,12 @@ pub fn path_join(args: Vec<JsValue>) -> JsValue { ...@@ -203,9 +204,12 @@ pub fn path_join(args: Vec<JsValue>) -> JsValue {
for part in iter { for part in iter {
let is_str = part.as_str().is_some(); let is_str = part.as_str().is_some();
if last_is_str && is_str { if last_is_str && is_str {
results.push("/".into()); results.push(rcstr!("/").into());
} else { } else {
results.push(JsValue::alternatives(vec!["/".into(), "".into()])); results.push(JsValue::alternatives(vec![
rcstr!("/").into(),
rcstr!("").into(),
]));
} }
results.push(part); results.push(part);
last_is_str = is_str; last_is_str = is_str;
...@@ -246,7 +250,7 @@ pub fn path_resolve(cwd: JsValue, mut args: Vec<JsValue>) -> JsValue { ...@@ -246,7 +250,7 @@ pub fn path_resolve(cwd: JsValue, mut args: Vec<JsValue>) -> JsValue {
} }
".." => { ".." => {
if results.pop().is_none() { if results.pop().is_none() {
results_final.push("..".into()); results_final.push(rcstr!("..").into());
} }
} }
_ => results.push(str.into()), _ => results.push(str.into()),
...@@ -274,9 +278,12 @@ pub fn path_resolve(cwd: JsValue, mut args: Vec<JsValue>) -> JsValue { ...@@ -274,9 +278,12 @@ pub fn path_resolve(cwd: JsValue, mut args: Vec<JsValue>) -> JsValue {
for part in iter { for part in iter {
let is_str = part.as_str().is_some(); let is_str = part.as_str().is_some();
if last_was_str && is_str { if last_was_str && is_str {
results.push("/".into()); results.push(rcstr!("/").into());
} else { } else {
results.push(JsValue::alternatives(vec!["/".into(), "".into()])); results.push(JsValue::alternatives(vec![
rcstr!("/").into(),
rcstr!("").into(),
]));
} }
results.push(part); results.push(part);
last_was_str = is_str; last_was_str = is_str;
...@@ -291,7 +298,7 @@ pub fn path_dirname(mut args: Vec<JsValue>) -> JsValue { ...@@ -291,7 +298,7 @@ pub fn path_dirname(mut args: Vec<JsValue>) -> JsValue {
if let Some(i) = str.rfind('/') { if let Some(i) = str.rfind('/') {
return JsValue::Constant(ConstantValue::Str(str[..i].to_string().into())); return JsValue::Constant(ConstantValue::Str(str[..i].to_string().into()));
} else { } else {
return JsValue::Constant(ConstantValue::Str("".into())); return JsValue::Constant(ConstantValue::Str(rcstr!("").into()));
} }
} else if let JsValue::Concat(_, items) = arg } else if let JsValue::Concat(_, items) = arg
&& let Some(last) = items.last_mut() && let Some(last) = items.last_mut()
......
...@@ -3,6 +3,7 @@ use std::sync::Arc; ...@@ -3,6 +3,7 @@ use std::sync::Arc;
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use bytes_str::BytesStr; use bytes_str::BytesStr;
use swc_core::{ use swc_core::{
atoms::atom,
base::try_with_handler, base::try_with_handler,
common::{ common::{
BytePos, FileName, FilePathMapping, GLOBALS, LineCol, Mark, SourceMap as SwcSourceMap, BytePos, FileName, FilePathMapping, GLOBALS, LineCol, Mark, SourceMap as SwcSourceMap,
...@@ -89,7 +90,7 @@ pub fn minify(code: Code, source_maps: bool, mangle: Option<MangleType>) -> Resu ...@@ -89,7 +90,7 @@ pub fn minify(code: Code, source_maps: bool, mangle: Option<MangleType>) -> Resu
..Default::default() ..Default::default()
}), }),
mangle: mangle.map(|mangle| { mangle: mangle.map(|mangle| {
let reserved = vec!["AbortSignal".into()]; let reserved = vec![atom!("AbortSignal")];
match mangle { match mangle {
MangleType::OptimalSize => MangleOptions { MangleType::OptimalSize => MangleOptions {
reserved, reserved,
......
...@@ -310,14 +310,14 @@ async fn parse_file_content( ...@@ -310,14 +310,14 @@ async fn parse_file_content(
let (emitter, collector) = IssueEmitter::new( let (emitter, collector) = IssueEmitter::new(
source, source,
source_map.clone(), source_map.clone(),
Some("Ecmascript file had an error".into()), Some(rcstr!("Ecmascript file had an error")),
); );
let handler = Handler::with_emitter(true, false, Box::new(emitter)); let handler = Handler::with_emitter(true, false, Box::new(emitter));
let (emitter, collector_parse) = IssueEmitter::new( let (emitter, collector_parse) = IssueEmitter::new(
source, source,
source_map.clone(), source_map.clone(),
Some("Parsing ecmascript source code failed".into()), Some(rcstr!("Parsing ecmascript source code failed")),
); );
let parser_handler = Handler::with_emitter(true, false, Box::new(emitter)); let parser_handler = Handler::with_emitter(true, false, Box::new(emitter));
let globals = Arc::new(Globals::new()); let globals = Arc::new(Globals::new());
......
...@@ -866,9 +866,9 @@ impl Issue for CircularReExport { ...@@ -866,9 +866,9 @@ impl Issue for CircularReExport {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn title(&self) -> Result<Vc<StyledString>> { async fn title(&self) -> Result<Vc<StyledString>> {
Ok(StyledString::Line(vec![ Ok(StyledString::Line(vec![
StyledString::Text("Export ".into()), StyledString::Text(rcstr!("Export ")),
StyledString::Code(self.export.clone()), StyledString::Code(self.export.clone()),
StyledString::Text(" is a circular re-export".into()), StyledString::Text(rcstr!(" is a circular re-export")),
]) ])
.cell()) .cell())
} }
...@@ -887,20 +887,20 @@ impl Issue for CircularReExport { ...@@ -887,20 +887,20 @@ impl Issue for CircularReExport {
async fn description(&self) -> Result<Vc<OptionStyledString>> { async fn description(&self) -> Result<Vc<OptionStyledString>> {
Ok(Vc::cell(Some( Ok(Vc::cell(Some(
StyledString::Stack(vec![ StyledString::Stack(vec![
StyledString::Line(vec![StyledString::Text("The export".into())]), StyledString::Line(vec![StyledString::Text(rcstr!("The export"))]),
StyledString::Line(vec![ StyledString::Line(vec![
StyledString::Code(self.export.clone()), StyledString::Code(self.export.clone()),
StyledString::Text(" of module ".into()), StyledString::Text(rcstr!(" of module ")),
StyledString::Strong(self.module.ident().to_string().owned().await?), StyledString::Strong(self.module.ident().to_string().owned().await?),
]), ]),
StyledString::Line(vec![StyledString::Text( StyledString::Line(vec![StyledString::Text(rcstr!(
"is a re-export of the export".into(), "is a re-export of the export"
)]), ))]),
StyledString::Line(vec![ StyledString::Line(vec![
StyledString::Code(self.import.clone().unwrap_or_else(|| "*".into())), StyledString::Code(self.import.clone().unwrap_or_else(|| rcstr!("*"))),
StyledString::Text(" of module ".into()), StyledString::Text(rcstr!(" of module ")),
StyledString::Strong(self.module_cycle.ident().to_string().owned().await?), StyledString::Strong(self.module_cycle.ident().to_string().owned().await?),
StyledString::Text(".".into()), StyledString::Text(rcstr!(".")),
]), ]),
]) ])
.resolved_cell(), .resolved_cell(),
......
...@@ -39,7 +39,7 @@ use regex::Regex; ...@@ -39,7 +39,7 @@ use regex::Regex;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
atoms::Atom, atoms::{Atom, atom},
common::{ common::{
GLOBALS, Globals, Span, Spanned, GLOBALS, Globals, Span, Spanned,
comments::{CommentKind, Comments}, comments::{CommentKind, Comments},
...@@ -1469,7 +1469,7 @@ async fn compile_time_info_for_module_type( ...@@ -1469,7 +1469,7 @@ async fn compile_time_info_for_module_type(
DefinableNameSegment::Name(rcstr!("meta")), DefinableNameSegment::Name(rcstr!("meta")),
DefinableNameSegment::TypeOf, DefinableNameSegment::TypeOf,
]) ])
.or_insert("object".into()); .or_insert(rcstr!("object").into());
free_var_references free_var_references
.entry(vec![ .entry(vec![
DefinableNameSegment::Name(rcstr!("exports")), DefinableNameSegment::Name(rcstr!("exports")),
...@@ -1487,31 +1487,31 @@ async fn compile_time_info_for_module_type( ...@@ -1487,31 +1487,31 @@ async fn compile_time_info_for_module_type(
DefinableNameSegment::Name(rcstr!("require")), DefinableNameSegment::Name(rcstr!("require")),
DefinableNameSegment::TypeOf, DefinableNameSegment::TypeOf,
]) ])
.or_insert("function".into()); .or_insert(rcstr!("function").into());
free_var_references free_var_references
.entry(vec![DefinableNameSegment::Name(rcstr!("require"))]) .entry(vec![DefinableNameSegment::Name(rcstr!("require"))])
.or_insert(require.into()); .or_insert(require.into());
let dir_name: RcStr = rcstr!("__dirname"); let dir_name = rcstr!("__dirname");
free_var_references free_var_references
.entry(vec![ .entry(vec![
DefinableNameSegment::Name(dir_name.clone()), DefinableNameSegment::Name(dir_name.clone()),
DefinableNameSegment::TypeOf, DefinableNameSegment::TypeOf,
]) ])
.or_insert("string".into()); .or_insert(rcstr!("string").into());
free_var_references free_var_references
.entry(vec![DefinableNameSegment::Name(dir_name)]) .entry(vec![DefinableNameSegment::Name(dir_name)])
.or_insert(FreeVarReference::InputRelative( .or_insert(FreeVarReference::InputRelative(
InputRelativeConstant::DirName, InputRelativeConstant::DirName,
)); ));
let file_name: RcStr = rcstr!("__filename"); let file_name = rcstr!("__filename");
free_var_references free_var_references
.entry(vec![ .entry(vec![
DefinableNameSegment::Name(file_name.clone()), DefinableNameSegment::Name(file_name.clone()),
DefinableNameSegment::TypeOf, DefinableNameSegment::TypeOf,
]) ])
.or_insert("string".into()); .or_insert(rcstr!("string").into());
free_var_references free_var_references
.entry(vec![DefinableNameSegment::Name(file_name)]) .entry(vec![DefinableNameSegment::Name(file_name)])
.or_insert(FreeVarReference::InputRelative( .or_insert(FreeVarReference::InputRelative(
...@@ -1519,16 +1519,16 @@ async fn compile_time_info_for_module_type( ...@@ -1519,16 +1519,16 @@ async fn compile_time_info_for_module_type(
)); ));
// Compiletime rewrite the nodejs `global` to `globalThis` // Compiletime rewrite the nodejs `global` to `globalThis`
let global: RcStr = rcstr!("global"); let global = rcstr!("global");
free_var_references free_var_references
.entry(vec![ .entry(vec![
DefinableNameSegment::Name(global.clone()), DefinableNameSegment::Name(global.clone()),
DefinableNameSegment::TypeOf, DefinableNameSegment::TypeOf,
]) ])
.or_insert("object".into()); .or_insert(rcstr!("object").into());
free_var_references free_var_references
.entry(vec![DefinableNameSegment::Name(global)]) .entry(vec![DefinableNameSegment::Name(global)])
.or_insert(FreeVarReference::Ident("globalThis".into())); .or_insert(FreeVarReference::Ident(rcstr!("globalThis")));
free_var_references.extend(TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS.into_iter().map( free_var_references.extend(TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS.into_iter().map(
|(name, shortcut)| { |(name, shortcut)| {
...@@ -1558,9 +1558,9 @@ async fn compile_time_info_for_module_type( ...@@ -1558,9 +1558,9 @@ async fn compile_time_info_for_module_type(
DefinableNameSegment::TypeOf, DefinableNameSegment::TypeOf,
]) ])
.or_insert(if is_esm { .or_insert(if is_esm {
"undefined".into() rcstr!("undefined").into()
} else { } else {
"object".into() rcstr!("object").into()
}); });
Ok(CompileTimeInfo { Ok(CompileTimeInfo {
environment: compile_time_info.environment, environment: compile_time_info.environment,
...@@ -2268,7 +2268,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( ...@@ -2268,7 +2268,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
WellKnownFunctionKind::PathJoin, WellKnownFunctionKind::PathJoin,
)), )),
vec![ vec![
JsValue::FreeVar("__dirname".into()), JsValue::FreeVar(atom!("__dirname")),
pkg_or_dir.clone(), pkg_or_dir.clone(),
], ],
), ),
...@@ -2328,9 +2328,9 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( ...@@ -2328,9 +2328,9 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
WellKnownFunctionKind::PathJoin, WellKnownFunctionKind::PathJoin,
)), )),
vec![ vec![
JsValue::FreeVar("__dirname".into()), JsValue::FreeVar(atom!("__dirname")),
p.into(), p.into(),
"intl".into(), atom!("intl").into(),
], ],
), ),
ImportAttributes::empty_ref(), ImportAttributes::empty_ref(),
...@@ -3567,7 +3567,7 @@ impl From<Vec<AstParentKind>> for AstPath { ...@@ -3567,7 +3567,7 @@ impl From<Vec<AstParentKind>> for AstPath {
} }
} }
pub static TURBOPACK_HELPER: Lazy<Atom> = Lazy::new(|| "__turbopack-helper__".into()); pub static TURBOPACK_HELPER: Lazy<Atom> = Lazy::new(|| atom!("__turbopack-helper__"));
pub fn is_turbopack_helper_import(import: &ImportDecl) -> bool { pub fn is_turbopack_helper_import(import: &ImportDecl) -> bool {
let annotations = ImportAnnotations::parse(import.with.as_deref()); let annotations = ImportAnnotations::parse(import.with.as_deref());
......
...@@ -10,7 +10,7 @@ use swc_core::{ ...@@ -10,7 +10,7 @@ use swc_core::{
}, },
quote, quote_expr, quote, quote_expr,
}; };
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
FxIndexMap, NonLocalValue, ResolvedVc, TaskInput, TryJoinIterExt, Vc, debug::ValueDebugFormat, FxIndexMap, NonLocalValue, ResolvedVc, TaskInput, TryJoinIterExt, Vc, debug::ValueDebugFormat,
trace::TraceRawVcs, trace::TraceRawVcs,
...@@ -341,9 +341,9 @@ async fn to_single_pattern_mapping( ...@@ -341,9 +341,9 @@ async fn to_single_pattern_mapping(
// TODO implement mapping // TODO implement mapping
CodeGenerationIssue { CodeGenerationIssue {
severity: IssueSeverity::Bug, severity: IssueSeverity::Bug,
title: StyledString::Text( title: StyledString::Text(rcstr!(
"pattern mapping is not implemented for this result".into(), "pattern mapping is not implemented for this result"
) ))
.resolved_cell(), .resolved_cell(),
message: StyledString::Text( message: StyledString::Text(
format!( format!(
...@@ -374,10 +374,10 @@ async fn to_single_pattern_mapping( ...@@ -374,10 +374,10 @@ async fn to_single_pattern_mapping(
} }
CodeGenerationIssue { CodeGenerationIssue {
severity: IssueSeverity::Bug, severity: IssueSeverity::Bug,
title: StyledString::Text("non-ecmascript placeable asset".into()).resolved_cell(), title: StyledString::Text(rcstr!("non-ecmascript placeable asset")).resolved_cell(),
message: StyledString::Text( message: StyledString::Text(rcstr!(
"asset is not placeable in ESM chunks, so it doesn't have a module id".into(), "asset is not placeable in ESM chunks, so it doesn't have a module id"
) ))
.resolved_cell(), .resolved_cell(),
path: origin.origin_path().owned().await?, path: origin.origin_path().owned().await?,
} }
......
...@@ -3,7 +3,7 @@ use std::mem::take; ...@@ -3,7 +3,7 @@ use std::mem::take;
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
atoms::atom, atoms::{Atom, atom},
base::SwcComments, base::SwcComments,
common::{ common::{
DUMMY_SP, Span, Spanned, DUMMY_SP, Span, Spanned,
...@@ -37,6 +37,9 @@ pub struct Unreachable { ...@@ -37,6 +37,9 @@ pub struct Unreachable {
range: AstPathRange, range: AstPathRange,
} }
fn unreachable_atom() -> Atom {
atom!("TURBOPACK unreachable")
}
struct UnreachableModifier { struct UnreachableModifier {
comments: SwcComments, comments: SwcComments,
} }
...@@ -49,7 +52,7 @@ impl AstModifier for UnreachableModifier { ...@@ -49,7 +52,7 @@ impl AstModifier for UnreachableModifier {
*node = Expr::Lit(Lit::Str(Str { *node = Expr::Lit(Lit::Str(Str {
span, span,
value: atom!("TURBOPACK unreachable"), value: unreachable_atom(),
raw: None, raw: None,
})); }));
} }
...@@ -64,7 +67,7 @@ impl AstModifier for UnreachableModifier { ...@@ -64,7 +67,7 @@ impl AstModifier for UnreachableModifier {
Comment { Comment {
kind: CommentKind::Line, kind: CommentKind::Line,
span: DUMMY_SP, span: DUMMY_SP,
text: atom!("TURBOPACK unreachable"), text: unreachable_atom(),
}, },
); );
...@@ -111,7 +114,7 @@ impl UnreachableRangeModifier { ...@@ -111,7 +114,7 @@ impl UnreachableRangeModifier {
Comment { Comment {
kind: CommentKind::Line, kind: CommentKind::Line,
span: DUMMY_SP, span: DUMMY_SP,
text: atom!("TURBOPACK unreachable"), text: unreachable_atom(),
}, },
); );
......
use std::fmt::{Display, Formatter}; use std::fmt::{Display, Formatter};
use swc_core::ecma::ast::{Expr, MemberExpr, MemberProp}; use swc_core::{
atoms::atom,
ecma::ast::{Expr, MemberExpr, MemberProp},
};
use turbo_rcstr::rcstr;
use turbopack_core::compile_time_info::FreeVarReference; use turbopack_core::compile_time_info::FreeVarReference;
pub struct TurbopackRuntimeFunctionShortcut { pub struct TurbopackRuntimeFunctionShortcut {
...@@ -29,14 +33,14 @@ impl Display for TurbopackRuntimeFunctionShortcut { ...@@ -29,14 +33,14 @@ impl Display for TurbopackRuntimeFunctionShortcut {
impl From<&TurbopackRuntimeFunctionShortcut> for FreeVarReference { impl From<&TurbopackRuntimeFunctionShortcut> for FreeVarReference {
fn from(val: &TurbopackRuntimeFunctionShortcut) -> Self { fn from(val: &TurbopackRuntimeFunctionShortcut) -> Self {
FreeVarReference::Member("__turbopack_context__".into(), val.shortcut.into()) FreeVarReference::Member(rcstr!("__turbopack_context__"), val.shortcut.into())
} }
} }
impl From<&TurbopackRuntimeFunctionShortcut> for Expr { impl From<&TurbopackRuntimeFunctionShortcut> for Expr {
fn from(val: &TurbopackRuntimeFunctionShortcut) -> Self { fn from(val: &TurbopackRuntimeFunctionShortcut) -> Self {
Expr::Member(MemberExpr { Expr::Member(MemberExpr {
obj: Box::new(Expr::Ident("__turbopack_context__".into())), obj: Box::new(Expr::Ident(atom!("__turbopack_context__").into())),
prop: MemberProp::Ident(val.shortcut.into()), prop: MemberProp::Ident(val.shortcut.into()),
..Default::default() ..Default::default()
}) })
......
...@@ -45,7 +45,7 @@ pub enum EcmascriptInputTransform { ...@@ -45,7 +45,7 @@ pub enum EcmascriptInputTransform {
runtime: ResolvedVc<Option<RcStr>>, runtime: ResolvedVc<Option<RcStr>>,
}, },
GlobalTypeofs { GlobalTypeofs {
window_value: String, window_value: RcStr,
}, },
// These options are subset of swc_core::ecma::transforms::typescript::Config, but // These options are subset of swc_core::ecma::transforms::typescript::Config, but
// it doesn't derive `Copy` so repeating values in here // it doesn't derive `Copy` so repeating values in here
......
...@@ -10,6 +10,7 @@ use petgraph::{ ...@@ -10,6 +10,7 @@ use petgraph::{
}; };
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use swc_core::{ use swc_core::{
atoms::atom,
common::{BytePos, DUMMY_SP, Spanned, SyntaxContext, comments::Comments, util::take::Take}, common::{BytePos, DUMMY_SP, Spanned, SyntaxContext, comments::Comments, util::take::Take},
ecma::{ ecma::{
ast::{ ast::{
...@@ -695,7 +696,7 @@ impl DepGraph { ...@@ -695,7 +696,7 @@ impl DepGraph {
is_type_only: false, is_type_only: false,
})], })],
src: if cfg!(test) { src: if cfg!(test) {
Some(Box::new("__TURBOPACK_VAR__".into())) Some(Box::new(atom!("__TURBOPACK_VAR__").into()))
} else { } else {
None None
}, },
...@@ -929,7 +930,7 @@ impl DepGraph { ...@@ -929,7 +930,7 @@ impl DepGraph {
), ),
ExportSpecifier::Default(s) => ( ExportSpecifier::Default(s) => (
Some(ModuleExportName::Ident(Ident::new( Some(ModuleExportName::Ident(Ident::new(
"default".into(), atom!("default"),
DUMMY_SP, DUMMY_SP,
Default::default(), Default::default(),
))), ))),
...@@ -1076,7 +1077,7 @@ impl DepGraph { ...@@ -1076,7 +1077,7 @@ impl DepGraph {
items.insert(id, data); items.insert(id, data);
} }
exports.push((default_var.to_id(), "default".into())); exports.push((default_var.to_id(), atom!("default")));
} }
ModuleDecl::ExportDefaultExpr(export) => { ModuleDecl::ExportDefaultExpr(export) => {
// Mirror what `EsmModuleItem::code_generation` does, these are live // Mirror what `EsmModuleItem::code_generation` does, these are live
...@@ -1140,7 +1141,7 @@ impl DepGraph { ...@@ -1140,7 +1141,7 @@ impl DepGraph {
{ {
// For export default __TURBOPACK__default__export__ // For export default __TURBOPACK__default__export__
exports.push((default_var.to_id(), "default".into())); exports.push((default_var.to_id(), atom!("default")));
} }
} }
......
...@@ -3,10 +3,10 @@ use std::{collections::BTreeMap, fmt::Write, hash::Hash, path::PathBuf, sync::Ar ...@@ -3,10 +3,10 @@ use std::{collections::BTreeMap, fmt::Write, hash::Hash, path::PathBuf, sync::Ar
use anyhow::Error; use anyhow::Error;
use serde::Deserialize; use serde::Deserialize;
use swc_core::{ use swc_core::{
atoms::atom,
common::{Mark, SourceMap, SyntaxContext, comments::SingleThreadedComments, util::take::Take}, common::{Mark, SourceMap, SyntaxContext, comments::SingleThreadedComments, util::take::Take},
ecma::{ ecma::{
ast::{EsVersion, Id, Module}, ast::{EsVersion, Id, Module},
atoms::Atom,
codegen::text_writer::JsWriter, codegen::text_writer::JsWriter,
parser::{EsSyntax, parse_file_as_module}, parser::{EsSyntax, parse_file_as_module},
visit::VisitMutWith, visit::VisitMutWith,
...@@ -175,7 +175,7 @@ fn run(input: PathBuf) { ...@@ -175,7 +175,7 @@ fn run(input: PathBuf) {
) )
.unwrap(); .unwrap();
let uri_of_module: Atom = "entry.js".into(); let uri_of_module = atom!("entry.js");
let mut describe = let mut describe =
|is_debug: bool, title: &str, entries: Vec<ItemIdGroupKind>, skip_parts: bool| { |is_debug: bool, title: &str, entries: Vec<ItemIdGroupKind>, skip_parts: bool| {
......
...@@ -265,7 +265,11 @@ mod tests { ...@@ -265,7 +265,11 @@ mod tests {
Pattern::Constant(rcstr!("hello/world")), Pattern::Constant(rcstr!("hello/world")),
js_value_to_pattern(&JsValue::Concat( js_value_to_pattern(&JsValue::Concat(
1, 1,
vec!["hello".into(), "\\".into(), "world".into()] vec![
rcstr!("hello").into(),
rcstr!("\\").into(),
rcstr!("world").into()
]
)) ))
); );
} }
......
...@@ -12,25 +12,25 @@ use crate::TryDotenvProcessEnv; ...@@ -12,25 +12,25 @@ use crate::TryDotenvProcessEnv;
pub async fn load_env(project_path: FileSystemPath) -> Result<Vc<Box<dyn ProcessEnv>>> { pub async fn load_env(project_path: FileSystemPath) -> Result<Vc<Box<dyn ProcessEnv>>> {
let env: Vc<Box<dyn ProcessEnv>> = Vc::upcast(CommandLineProcessEnv::new()); let env: Vc<Box<dyn ProcessEnv>> = Vc::upcast(CommandLineProcessEnv::new());
let node_env = env.read(rcstr!("NODE_ENV")).await?; let node_env = env.read(rcstr!("NODE_ENV")).owned().await?;
let node_env = node_env.as_deref().unwrap_or("development"); let node_env = node_env.unwrap_or(rcstr!("development"));
let env = Vc::upcast(CustomProcessEnv::new( let env = Vc::upcast(CustomProcessEnv::new(
env, env,
Vc::cell(fxindexmap! { Vc::cell(fxindexmap! {
rcstr!("NODE_ENV") => node_env.into(), rcstr!("NODE_ENV") => node_env.clone(),
}), }),
)); ));
let mut files = [ let mut files = [
Some(format!(".env.{node_env}.local")), Some(format!(".env.{node_env}.local").into()),
if node_env == "test" { if node_env == "test" {
None None
} else { } else {
Some(".env.local".into()) Some(rcstr!(".env.local"))
}, },
Some(format!(".env.{node_env}")), Some(format!(".env.{node_env}").into()),
Some(".env".into()), Some(rcstr!(".env")),
] ]
.into_iter() .into_iter()
.flatten(); .flatten();
......
...@@ -321,7 +321,7 @@ pub async fn tsconfig_resolve_options( ...@@ -321,7 +321,7 @@ pub async fn tsconfig_resolve_options(
}) })
.collect(); .collect();
all_paths.insert( all_paths.insert(
key.to_string(), RcStr::from(key.as_str()),
ImportMapping::primary_alternatives(entries, Some(context_dir.clone())), ImportMapping::primary_alternatives(entries, Some(context_dir.clone())),
); );
} else { } else {
......
...@@ -141,7 +141,7 @@ fn get_messages(js_results: JsResult) -> Vec<String> { ...@@ -141,7 +141,7 @@ fn get_messages(js_results: JsResult) -> Vec<String> {
let mut messages = vec![]; let mut messages = vec![];
if js_results.jest_result.test_results.is_empty() { if js_results.jest_result.test_results.is_empty() {
messages.push("No tests were run.".into()); messages.push("No tests were run.".to_string());
} }
for test_result in js_results.jest_result.test_results { for test_result in js_results.jest_result.test_results {
...@@ -191,7 +191,7 @@ async fn run(resource: PathBuf, snapshot_mode: IssueSnapshotMode) -> Result<JsRe ...@@ -191,7 +191,7 @@ async fn run(resource: PathBuf, snapshot_mode: IssueSnapshotMode) -> Result<JsRe
// Set up a `tracing_subscriber` for debugging -- We can only do this when using nextest, as // Set up a `tracing_subscriber` for debugging -- We can only do this when using nextest, as
// `cargo test` runs all execution test cases in the same process. // `cargo test` runs all execution test cases in the same process.
// //
// Configuring `tracing_subscriber` requires proces-global side-effects. We can't use a // Configuring `tracing_subscriber` requires process-global side-effects. We can't use a
// thread-local subscriber because we're not fully single-threaded, even with the // thread-local subscriber because we're not fully single-threaded, even with the
// `current_thread` tokio executor. // `current_thread` tokio executor.
// //
...@@ -359,7 +359,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V ...@@ -359,7 +359,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
let mut import_map = ImportMap::empty(); let mut import_map = ImportMap::empty();
import_map.insert_wildcard_alias( import_map.insert_wildcard_alias(
"esm-external/", rcstr!("esm-external/"),
ImportMapping::External( ImportMapping::External(
Some(rcstr!("*")), Some(rcstr!("*")),
ExternalType::EcmaScriptModule, ExternalType::EcmaScriptModule,
...@@ -368,7 +368,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V ...@@ -368,7 +368,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
.resolved_cell(), .resolved_cell(),
); );
import_map.insert_exact_alias( import_map.insert_exact_alias(
"jest-circus", rcstr!("jest-circus"),
ImportMapping::External(None, ExternalType::CommonJs, ExternalTraced::Untraced) ImportMapping::External(None, ExternalType::CommonJs, ExternalTraced::Untraced)
.resolved_cell(), .resolved_cell(),
); );
......
...@@ -79,7 +79,7 @@ fn bench_emit(b: &mut Bencher, bench_input: &BenchInput) { ...@@ -79,7 +79,7 @@ fn bench_emit(b: &mut Bencher, bench_input: &BenchInput) {
let input: RcStr = bench_input.input.clone().into(); let input: RcStr = bench_input.input.clone().into();
async move { async move {
let task = tt.spawn_once_task(async move { let task = tt.spawn_once_task(async move {
let input_fs = DiskFileSystem::new("tests".into(), tests_root.clone()); let input_fs = DiskFileSystem::new(rcstr!("tests"), tests_root.clone());
let input = input_fs.root().await?.join(&input)?; let input = input_fs.root().await?.join(&input)?;
let input_dir = input.parent().parent(); let input_dir = input.parent().parent();
......
...@@ -43,7 +43,7 @@ pub async fn node_evaluate_asset_context( ...@@ -43,7 +43,7 @@ pub async fn node_evaluate_asset_context(
ImportMap::empty() ImportMap::empty()
}; };
import_map.insert_wildcard_alias( import_map.insert_wildcard_alias(
"@vercel/turbopack-node/", rcstr!("@vercel/turbopack-node/"),
ImportMapping::PrimaryAlternative( ImportMapping::PrimaryAlternative(
rcstr!("./*"), rcstr!("./*"),
Some(turbopack_node::embed_js::embed_fs().root().owned().await?), Some(turbopack_node::embed_js::embed_fs().root().owned().await?),
......
...@@ -654,8 +654,8 @@ async fn externals_tracing_module_context(ty: ExternalType) -> Result<Vc<ModuleA ...@@ -654,8 +654,8 @@ async fn externals_tracing_module_context(ty: ExternalType) -> Result<Vc<ModuleA
emulate_environment: Some(env), emulate_environment: Some(env),
loose_errors: true, loose_errors: true,
custom_conditions: match ty { custom_conditions: match ty {
ExternalType::CommonJs => vec!["require".into()], ExternalType::CommonJs => vec![rcstr!("require")],
ExternalType::EcmaScriptModule => vec!["import".into()], ExternalType::EcmaScriptModule => vec![rcstr!("import")],
ExternalType::Url | ExternalType::Global | ExternalType::Script => vec![], ExternalType::Url | ExternalType::Global | ExternalType::Script => vec![],
}, },
..Default::default() ..Default::default()
......
...@@ -37,7 +37,10 @@ fn package_import_map_from_import_mapping( ...@@ -37,7 +37,10 @@ fn package_import_map_from_import_mapping(
package_mapping: ResolvedVc<ImportMapping>, package_mapping: ResolvedVc<ImportMapping>,
) -> Vc<ImportMap> { ) -> Vc<ImportMap> {
let mut import_map = ImportMap::default(); let mut import_map = ImportMap::default();
import_map.insert_exact_alias(format!("@vercel/turbopack/{package_name}"), package_mapping); import_map.insert_exact_alias(
RcStr::from(format!("@vercel/turbopack/{package_name}")),
package_mapping,
);
import_map.cell() import_map.cell()
} }
...@@ -48,7 +51,7 @@ fn package_import_map_from_context( ...@@ -48,7 +51,7 @@ fn package_import_map_from_context(
) -> Vc<ImportMap> { ) -> Vc<ImportMap> {
let mut import_map = ImportMap::default(); let mut import_map = ImportMap::default();
import_map.insert_exact_alias( import_map.insert_exact_alias(
format!("@vercel/turbopack/{package_name}"), RcStr::from(format!("@vercel/turbopack/{package_name}")),
ImportMapping::PrimaryAlternative(package_name, Some(context_path)).resolved_cell(), ImportMapping::PrimaryAlternative(package_name, Some(context_path)).resolved_cell(),
); );
import_map.cell() import_map.cell()
...@@ -181,8 +184,8 @@ impl ModuleOptions { ...@@ -181,8 +184,8 @@ impl ModuleOptions {
if let Some(enable_typeof_window_inlining) = enable_typeof_window_inlining { if let Some(enable_typeof_window_inlining) = enable_typeof_window_inlining {
transforms.push(EcmascriptInputTransform::GlobalTypeofs { transforms.push(EcmascriptInputTransform::GlobalTypeofs {
window_value: match enable_typeof_window_inlining { window_value: match enable_typeof_window_inlining {
TypeofWindow::Object => "object".to_string(), TypeofWindow::Object => rcstr!("object"),
TypeofWindow::Undefined => "undefined".to_string(), TypeofWindow::Undefined => rcstr!("undefined"),
}, },
}); });
} }
...@@ -461,7 +464,7 @@ impl ModuleOptions { ...@@ -461,7 +464,7 @@ impl ModuleOptions {
.context("execution_context is required for the postcss_transform")?; .context("execution_context is required for the postcss_transform")?;
let import_map = if let Some(postcss_package) = options.postcss_package { let import_map = if let Some(postcss_package) = options.postcss_package {
package_import_map_from_import_mapping("postcss".into(), *postcss_package) package_import_map_from_import_mapping(rcstr!("postcss"), *postcss_package)
} else { } else {
package_import_map_from_context( package_import_map_from_context(
rcstr!("postcss"), rcstr!("postcss"),
...@@ -618,12 +621,12 @@ impl ModuleOptions { ...@@ -618,12 +621,12 @@ impl ModuleOptions {
webpack_loaders_options.loader_runner_package webpack_loaders_options.loader_runner_package
{ {
package_import_map_from_import_mapping( package_import_map_from_import_mapping(
"loader-runner".into(), rcstr!("loader-runner"),
*loader_runner_package, *loader_runner_package,
) )
} else { } else {
package_import_map_from_context( package_import_map_from_context(
"loader-runner".into(), rcstr!("loader-runner"),
path.context("need_path in ModuleOptions::new is incorrect")?, path.context("need_path in ModuleOptions::new is incorrect")?,
) )
}; };
......
...@@ -141,7 +141,7 @@ impl RuleCondition { ...@@ -141,7 +141,7 @@ impl RuleCondition {
let content_type = &source.ident().await?.content_type; let content_type = &source.ident().await?.content_type;
return Ok(content_type return Ok(content_type
.as_ref() .as_ref()
.is_some_and(|ct| ct.starts_with(start))); .is_some_and(|ct| ct.starts_with(start.as_str())));
} }
RuleCondition::ContentTypeEmpty => { RuleCondition::ContentTypeEmpty => {
return Ok(source.ident().await?.content_type.is_none()); return Ok(source.ident().await?.content_type.is_none());
......
...@@ -34,7 +34,7 @@ impl AfterResolvePlugin for UnsupportedSassResolvePlugin { ...@@ -34,7 +34,7 @@ impl AfterResolvePlugin for UnsupportedSassResolvePlugin {
async fn after_resolve_condition(&self) -> Result<Vc<AfterResolvePluginCondition>> { async fn after_resolve_condition(&self) -> Result<Vc<AfterResolvePluginCondition>> {
Ok(AfterResolvePluginCondition::new( Ok(AfterResolvePluginCondition::new(
self.root.root().owned().await?, self.root.root().owned().await?,
Glob::new("**/*.{sass,scss}".into()), Glob::new(rcstr!("**/*.{sass,scss}")),
)) ))
} }
......
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