From 09cfe11c5f431e5296a6b18ef96fbdc1919d9ec7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Donny/=EA=B0=95=EB=8F=99=EC=9C=A4?= Date: Wed, 5 Jun 2024 14:08:52 +0900 Subject: [PATCH] perf: Introduce `RcStr` (vercel/turbo#8221) ### Description If we accept `: String` from a function, invoking the function needs one owned `String` and it means allocation even if the value isn't changed. But with this PR, functions now accept `RcStr`, which is shared, so invoking the same function with the same value does not involve allocation for `String` . --- I tried using `Arc` in https://github.com/vercel/turbo/pull/7772, but a team member suggested creating a new type so we can replace underlying implementation easily in the future. I used `ast-grep` with ```yml id: convert-expr-into language: rust rule: kind: function_item all: - has: kind: parameters pattern: $PARAMS - any: - has: kind: visibility_modifier pattern: $VIS - not: has: kind: visibility_modifier - any: - has: kind: function_modifiers pattern: $MOD - not: has: kind: function_modifiers - has: field: return_type pattern: $RET - has: field: body pattern: $BODY - has: kind: identifier pattern: $NAME - follows: kind: attribute_item pattern: '#[turbo_tasks::function]' transform: NEW_PARAMS: replace: replace: 'String' by: 'RcStr' source: $PARAMS fix: $VIS $MOD fn $NAME $NEW_PARAMS -> $RET $BODY ``` ### Performance difference: #### `main`: ``` Benchmarking bench_startup/Next.js canary Turbo SSR/1000 modules: Warming up for 3.0000 s Warning: Unable to complete 10 samples in 60.0s. You may wish to increase target time to 65.6s. bench_startup/Next.js canary Turbo SSR/1000 modules time: [4.1476 s 4.1625 s 4.1752 s] Benchmarking bench_startup/Next.js canary Turbo RSC/1000 modules: Warming up for 3.0000 s Warning: Unable to complete 10 samples in 60.0s. You may wish to increase target time to 63.5s. bench_startup/Next.js canary Turbo RSC/1000 modules time: [4.0396 s 4.0673 s 4.0956 s] Benchmarking bench_startup/Next.js canary Turbo RCC/1000 modules: Warming up for 3.0000 s Warning: Unable to complete 10 samples in 60.0s. You may wish to increase target time to 69.7s. bench_startup/Next.js canary Turbo RCC/1000 modules time: [4.7222 s 4.7508 s 4.7790 s] ``` #### `pr`: ``` Benchmarking bench_startup/Next.js canary Turbo SSR/1000 modules: Warming up for 3.0000 s Warning: Unable to complete 10 samples in 60.0s. You may wish to increase target time to 66.2s. bench_startup/Next.js canary Turbo SSR/1000 modules time: [4.1175 s 4.1310 s 4.1496 s] Found 1 outliers among 10 measurements (10.00%) 1 (10.00%) high severe Benchmarking bench_startup/Next.js canary Turbo RSC/1000 modules: Warming up for 3.0000 s Warning: Unable to complete 10 samples in 60.0s. You may wish to increase target time to 63.7s. bench_startup/Next.js canary Turbo RSC/1000 modules time: [4.0401 s 4.0714 s 4.1105 s] Found 1 outliers among 10 measurements (10.00%) 1 (10.00%) high mild Benchmarking bench_startup/Next.js canary Turbo RCC/1000 modules: Warming up for 3.0000 s Warning: Unable to complete 10 samples in 60.0s. You may wish to increase target time to 70.2s. bench_startup/Next.js canary Turbo RCC/1000 modules time: [4.6696 s 4.6900 s 4.7107 s] Benchmarking bench_startup/Next.js 14 Turbo SSR/1000 modules: Warming up for 3.0000 s Warning: Unable to complete 10 samples in 60.0s. You may wish to increase target time to 63.9s. ``` --------- Co-authored-by: Benjamin Woodruff --- crates/node-file-trace/src/lib.rs | 44 ++-- crates/node-file-trace/src/nft_json.rs | 4 +- crates/turbo-tasks-env/src/command_line.rs | 4 +- crates/turbo-tasks-env/src/custom.rs | 4 +- crates/turbo-tasks-env/src/dotenv.rs | 8 +- crates/turbo-tasks-env/src/filter.rs | 17 +- crates/turbo-tasks-env/src/lib.rs | 20 +- crates/turbo-tasks-fetch/src/lib.rs | 42 ++-- crates/turbo-tasks-fetch/tests/fetch.rs | 18 +- .../turbo-tasks-fs/examples/hash_directory.rs | 22 +- crates/turbo-tasks-fs/examples/hash_glob.rs | 28 +-- crates/turbo-tasks-fs/src/attach.rs | 12 +- crates/turbo-tasks-fs/src/embed/dir.rs | 10 +- crates/turbo-tasks-fs/src/embed/file.rs | 16 +- crates/turbo-tasks-fs/src/embed/fs.rs | 19 +- crates/turbo-tasks-fs/src/glob.rs | 4 +- crates/turbo-tasks-fs/src/invalidation.rs | 4 +- crates/turbo-tasks-fs/src/lib.rs | 154 ++++++------ crates/turbo-tasks-fs/src/read_glob.rs | 6 +- crates/turbo-tasks-fs/src/virtual_fs.rs | 10 +- crates/turbo-tasks-fs/src/watcher.rs | 14 +- crates/turbo-tasks-macros/src/lib.rs | 2 +- crates/turbo-tasks-memory/tests/all_in_one.rs | 24 +- .../turbo-tasks-memory/tests/collectibles.rs | 45 ++-- crates/turbo-tasks/src/debug/mod.rs | 2 +- crates/turbo-tasks/src/display.rs | 4 +- crates/turbo-tasks/src/lib.rs | 3 + crates/turbo-tasks/src/primitives.rs | 20 +- crates/turbo-tasks/src/rcstr.rs | 154 ++++++++++++ .../src/task/concrete_task_input.rs | 4 +- crates/turbo-tasks/src/task/function.rs | 11 +- crates/turbo-tasks/src/task/task_input.rs | 18 +- crates/turbo-tasks/src/trace.rs | 4 +- .../turbopack-browser/src/chunking_context.rs | 62 ++--- .../turbopack-browser/src/ecmascript/chunk.rs | 30 +-- .../src/ecmascript/content.rs | 4 +- .../src/ecmascript/content_entry.rs | 4 +- .../src/ecmascript/evaluate/chunk.rs | 16 +- .../src/ecmascript/list/asset.rs | 26 +- .../src/ecmascript/list/version.rs | 6 +- .../src/ecmascript/merged/version.rs | 6 +- .../src/ecmascript/runtime.rs | 8 +- .../src/ecmascript/version.rs | 6 +- crates/turbopack-browser/src/react_refresh.rs | 17 +- crates/turbopack-cli/src/build/mod.rs | 37 +-- crates/turbopack-cli/src/contexts.rs | 10 +- crates/turbopack-cli/src/dev/mod.rs | 49 ++-- .../turbopack-cli/src/dev/web_entry_source.rs | 17 +- crates/turbopack-cli/src/embed_js.rs | 6 +- crates/turbopack-cli/src/util.rs | 30 +-- crates/turbopack-core/src/asset.rs | 4 +- .../turbopack-core/src/chunk/chunk_group.rs | 4 +- crates/turbopack-core/src/chunk/chunking.rs | 8 +- .../src/chunk/chunking_context.rs | 10 +- crates/turbopack-core/src/chunk/data.rs | 6 +- crates/turbopack-core/src/chunk/mod.rs | 12 +- .../turbopack-core/src/compile_time_info.rs | 40 ++-- crates/turbopack-core/src/context.rs | 6 +- crates/turbopack-core/src/diagnostics/mod.rs | 14 +- crates/turbopack-core/src/environment.rs | 36 ++- crates/turbopack-core/src/file_source.rs | 8 +- crates/turbopack-core/src/ident.rs | 44 ++-- crates/turbopack-core/src/introspect/mod.rs | 14 +- .../turbopack-core/src/introspect/module.rs | 12 +- .../src/introspect/output_asset.rs | 12 +- .../turbopack-core/src/introspect/source.rs | 12 +- crates/turbopack-core/src/introspect/utils.rs | 32 +-- crates/turbopack-core/src/issue/analyze.rs | 16 +- crates/turbopack-core/src/issue/mod.rs | 42 ++-- crates/turbopack-core/src/issue/resolve.rs | 16 +- .../src/issue/unsupported_module.rs | 16 +- crates/turbopack-core/src/package_json.rs | 8 +- crates/turbopack-core/src/reference/mod.rs | 14 +- .../src/reference/source_map.rs | 15 +- crates/turbopack-core/src/reference_type.rs | 34 +-- .../turbopack-core/src/resolve/alias_map.rs | 39 +-- crates/turbopack-core/src/resolve/mod.rs | 222 +++++++++--------- crates/turbopack-core/src/resolve/node.rs | 30 +-- crates/turbopack-core/src/resolve/options.rs | 70 +++--- crates/turbopack-core/src/resolve/origin.rs | 8 +- crates/turbopack-core/src/resolve/parse.rs | 147 ++++++------ crates/turbopack-core/src/resolve/pattern.rs | 211 +++++++++-------- crates/turbopack-core/src/resolve/remap.rs | 35 +-- crates/turbopack-core/src/server_fs.rs | 6 +- crates/turbopack-core/src/source_map/mod.rs | 12 +- .../src/source_map/source_map_asset.rs | 20 +- crates/turbopack-core/src/version.rs | 16 +- crates/turbopack-css/src/asset.rs | 8 +- crates/turbopack-css/src/chunk/mod.rs | 32 +-- .../src/chunk/single_item_chunk/chunk.rs | 24 +- .../src/chunk/single_item_chunk/source_map.rs | 2 +- crates/turbopack-css/src/chunk/source_map.rs | 2 +- crates/turbopack-css/src/module_asset.rs | 18 +- crates/turbopack-css/src/process.rs | 24 +- .../turbopack-css/src/references/compose.rs | 11 +- crates/turbopack-css/src/references/import.rs | 32 +-- .../turbopack-css/src/references/internal.rs | 11 +- crates/turbopack-css/src/references/mod.rs | 10 +- crates/turbopack-css/src/references/url.rs | 18 +- crates/turbopack-dev-server/src/html.rs | 29 +-- crates/turbopack-dev-server/src/http.rs | 6 +- .../src/introspect/mod.rs | 39 +-- .../src/source/asset_graph.rs | 70 +++--- .../src/source/combined.rs | 12 +- .../src/source/conditional.rs | 26 +- .../src/source/issue_context.rs | 28 +-- .../src/source/lazy_instantiated.rs | 12 +- crates/turbopack-dev-server/src/source/mod.rs | 43 ++-- .../src/source/resolve.rs | 28 ++- .../src/source/route_tree.rs | 18 +- .../turbopack-dev-server/src/source/router.rs | 38 +-- .../src/source/static_assets.rs | 16 +- .../src/source/wrapping_source.rs | 4 +- .../turbopack-dev-server/src/update/server.rs | 2 +- .../turbopack-dev-server/src/update/stream.rs | 17 +- .../src/transform/directives/client.rs | 6 +- .../src/transform/directives/server.rs | 6 +- .../transform/swc_ecma_transform_plugins.rs | 4 +- .../src/asset_context.rs | 2 +- .../src/build_runtime.rs | 18 +- .../src/dev_runtime.rs | 37 ++- .../src/embed_js.rs | 8 +- .../src/analyzer/graph.rs | 4 +- .../src/analyzer/imports.rs | 8 +- .../turbopack-ecmascript/src/analyzer/mod.rs | 30 ++- .../src/async_chunk/chunk_item.rs | 10 +- .../src/async_chunk/module.rs | 10 +- .../src/chunk/chunk_type.rs | 6 +- crates/turbopack-ecmascript/src/chunk/item.rs | 4 +- crates/turbopack-ecmascript/src/chunk/mod.rs | 37 ++- .../src/chunk/placeable.rs | 41 ++-- .../src/chunk_group_files_asset.rs | 30 +-- crates/turbopack-ecmascript/src/lib.rs | 12 +- .../src/manifest/chunk_asset.rs | 13 +- .../src/manifest/chunk_item.rs | 2 +- .../src/manifest/loader_item.rs | 14 +- crates/turbopack-ecmascript/src/parse.rs | 38 +-- .../src/references/amd.rs | 12 +- .../src/references/cjs.rs | 29 +-- .../src/references/esm/base.rs | 29 ++- .../src/references/esm/binding.rs | 6 +- .../src/references/esm/dynamic.rs | 11 +- .../src/references/esm/export.rs | 47 ++-- .../src/references/esm/module_id.rs | 13 +- .../src/references/esm/url.rs | 11 +- .../src/references/mod.rs | 102 ++++---- .../src/references/node.rs | 28 +-- .../src/references/pattern_mapping.rs | 23 +- .../src/references/raw.rs | 11 +- .../src/references/require_context.rs | 50 ++-- .../src/references/type_issue.rs | 12 +- .../src/references/typescript.rs | 43 ++-- .../src/references/util.rs | 4 +- .../side_effect_optimization/facade/module.rs | 4 +- .../src/side_effect_optimization/reference.rs | 8 +- crates/turbopack-ecmascript/src/text/mod.rs | 10 +- .../turbopack-ecmascript/src/transform/mod.rs | 8 +- .../src/tree_shake/asset.rs | 8 +- .../src/tree_shake/graph.rs | 5 +- .../src/tree_shake/mod.rs | 10 +- .../src/tree_shake/tests.rs | 2 +- .../src/typescript/mod.rs | 67 +++--- crates/turbopack-ecmascript/src/utils.rs | 16 +- .../turbopack-ecmascript/src/webpack/mod.rs | 25 +- .../src/webpack/references.rs | 2 +- .../analyzer/graph/concat/graph.snapshot | 4 +- .../graph/esbuild/graph-effects.snapshot | 2 +- .../analyzer/graph/esbuild/graph.snapshot | 2 +- crates/turbopack-env/src/asset.rs | 2 +- crates/turbopack-env/src/dotenv.rs | 6 +- crates/turbopack-env/src/embeddable.rs | 11 +- crates/turbopack-env/src/issue.rs | 2 +- crates/turbopack-env/src/try_env.rs | 2 +- crates/turbopack-image/src/process/mod.rs | 14 +- crates/turbopack-json/src/lib.rs | 6 +- crates/turbopack-mdx/src/lib.rs | 21 +- crates/turbopack-node/src/bootstrap.rs | 6 +- crates/turbopack-node/src/embed_js.rs | 6 +- crates/turbopack-node/src/evaluate.rs | 19 +- crates/turbopack-node/src/lib.rs | 8 +- crates/turbopack-node/src/pool.rs | 8 +- .../turbopack-node/src/render/error_page.rs | 20 +- crates/turbopack-node/src/render/issue.rs | 6 +- crates/turbopack-node/src/render/mod.rs | 22 +- .../src/render/node_api_source.rs | 37 +-- .../turbopack-node/src/render/render_proxy.rs | 16 +- .../src/render/render_static.rs | 6 +- .../src/render/rendered_source.rs | 37 +-- crates/turbopack-node/src/route_matcher.rs | 12 +- crates/turbopack-node/src/source_map/mod.rs | 4 +- crates/turbopack-node/src/source_map/trace.rs | 13 +- .../turbopack-node/src/transforms/postcss.rs | 32 ++- crates/turbopack-node/src/transforms/util.rs | 6 +- .../turbopack-node/src/transforms/webpack.rs | 88 ++++--- .../turbopack-nodejs/src/chunking_context.rs | 46 ++-- .../src/ecmascript/node/chunk.rs | 28 +-- .../src/ecmascript/node/content.rs | 2 +- .../src/ecmascript/node/entry/chunk.rs | 14 +- .../src/ecmascript/node/entry/runtime.rs | 10 +- .../src/ecmascript/node/version.rs | 6 +- crates/turbopack-resolve/src/ecmascript.rs | 8 +- .../src/node_native_binding.rs | 100 ++++---- crates/turbopack-resolve/src/resolve.rs | 53 ++--- .../src/resolve_options_context.rs | 6 +- crates/turbopack-resolve/src/typescript.rs | 63 +++-- crates/turbopack-static/src/lib.rs | 17 +- crates/turbopack-static/src/output_asset.rs | 2 +- crates/turbopack-swc-utils/src/emitter.rs | 14 +- crates/turbopack-test-utils/src/snapshot.rs | 11 +- crates/turbopack-tests/tests/execution.rs | 47 ++-- crates/turbopack-tests/tests/snapshot.rs | 50 ++-- crates/turbopack-tests/tests/util.rs | 9 +- crates/turbopack-wasm/src/loader.rs | 13 +- crates/turbopack-wasm/src/module_asset.rs | 8 +- crates/turbopack-wasm/src/output_asset.rs | 8 +- crates/turbopack-wasm/src/raw.rs | 11 +- crates/turbopack-wasm/src/source.rs | 2 +- crates/turbopack/benches/node_file_trace.rs | 10 +- crates/turbopack/examples/turbopack.rs | 16 +- crates/turbopack/src/evaluate_context.rs | 18 +- crates/turbopack/src/lib.rs | 30 ++- crates/turbopack/src/module_options/mod.rs | 18 +- .../module_options/module_options_context.rs | 12 +- .../src/transition/context_transition.rs | 8 +- crates/turbopack/src/transition/mod.rs | 6 +- crates/turbopack/src/unsupported_sass.rs | 24 +- crates/turbopack/tests/node-file-trace.rs | 30 +-- 227 files changed, 2606 insertions(+), 2364 deletions(-) create mode 100644 crates/turbo-tasks/src/rcstr.rs diff --git a/crates/node-file-trace/src/lib.rs b/crates/node-file-trace/src/lib.rs index 34e21c08c5702..8a7e3377c2fda 100644 --- a/crates/node-file-trace/src/lib.rs +++ b/crates/node-file-trace/src/lib.rs @@ -22,8 +22,8 @@ use serde::Deserialize; use serde::Serialize; use tokio::sync::mpsc::channel; use turbo_tasks::{ - backend::Backend, util::FormatDuration, TaskId, TransientInstance, TransientValue, TurboTasks, - UpdateInfo, Value, Vc, + backend::Backend, util::FormatDuration, RcStr, TaskId, TransientInstance, TransientValue, + TurboTasks, UpdateInfo, Value, Vc, }; use turbo_tasks_fs::{ glob::Glob, DirectoryEntry, DiskFileSystem, FileSystem, FileSystemPath, ReadGlobResult, @@ -188,7 +188,7 @@ impl Args { } async fn create_fs(name: &str, root: &str, watch: bool) -> Result>> { - let fs = DiskFileSystem::new(name.to_string(), root.to_string(), vec![]); + let fs = DiskFileSystem::new(name.into(), root.into(), vec![]); if watch { fs.await?.start_watching()?; } else { @@ -232,17 +232,17 @@ async fn add_glob_results( #[turbo_tasks::function] async fn input_to_modules( fs: Vc>, - input: Vec, + input: Vec, exact: bool, - process_cwd: Option, - context_directory: String, + process_cwd: Option, + context_directory: RcStr, module_options: TransientInstance, resolve_options: TransientInstance, ) -> Result> { let root = fs.root(); let process_cwd = process_cwd .clone() - .map(|p| format!("/ROOT{}", p.trim_start_matches(&context_directory))); + .map(|p| format!("/ROOT{}", p.trim_start_matches(&*context_directory)).into()); let asset_context: Vc> = Vc::upcast(create_module_asset( root, @@ -283,7 +283,7 @@ fn process_context(dir: &Path, context_directory: Option<&String>) -> Result Result { +fn make_relative_path(dir: &Path, context_directory: &str, input: &str) -> Result { let mut input = PathBuf::from(input); if !input.is_absolute() { input = dir.join(input); @@ -299,10 +299,11 @@ fn make_relative_path(dir: &Path, context_directory: &str, input: &str) -> Resul Ok(input .to_str() .ok_or_else(|| anyhow!("input contains invalid characters"))? - .replace('\\', "/")) + .replace('\\', "/") + .into()) } -fn process_input(dir: &Path, context_directory: &str, input: &[String]) -> Result> { +fn process_input(dir: &Path, context_directory: &str, input: &[String]) -> Result> { input .iter() .map(|input| make_relative_path(dir, context_directory, input)) @@ -314,7 +315,7 @@ pub async fn start( turbo_tasks: Option<&Arc>>, module_options: Option, resolve_options: Option, -) -> Result> { +) -> Result> { register(); let &CommonArgs { memory_limit, @@ -394,7 +395,7 @@ async fn run>( final_finish: impl FnOnce(Arc>, TaskId, Duration) -> F, module_options: Option, resolve_options: Option, -) -> Result> { +) -> Result> { let &CommonArgs { watch, show_all, @@ -494,7 +495,7 @@ async fn run>( if has_return_value { let output_read_ref = output.await?; let output_iter = output_read_ref.iter().cloned(); - sender.send(output_iter.collect::>()).await?; + sender.send(output_iter.collect::>()).await?; drop(sender); } Ok::, _>(Default::default()) @@ -515,7 +516,7 @@ async fn main_operation( args: TransientInstance, module_options: TransientInstance, resolve_options: TransientInstance, -) -> Result>> { +) -> Result>> { let dir = current_dir.into_value(); let args = &*args; let &CommonArgs { @@ -526,8 +527,11 @@ async fn main_operation( ref process_cwd, .. } = args.common(); - let context_directory = process_context(&dir, context_directory.as_ref()).unwrap(); + let context_directory: RcStr = process_context(&dir, context_directory.as_ref()) + .unwrap() + .into(); let fs = create_fs("context directory", &context_directory, watch).await?; + let process_cwd = process_cwd.clone().map(RcStr::from); match *args { Args::Print { common: _ } => { @@ -549,7 +553,7 @@ async fn main_operation( .await?; for asset in set.await?.iter() { let path = asset.ident().path().await?; - result.insert(path.path.to_string()); + result.insert(RcStr::from(&*path.path)); } } @@ -620,7 +624,7 @@ async fn main_operation( #[turbo_tasks::function] async fn create_module_asset( root: Vc, - process_cwd: Option, + process_cwd: Option, module_options: TransientInstance, resolve_options: TransientInstance, ) -> Result> { @@ -635,12 +639,12 @@ async fn create_module_asset( let glob_mappings = vec![ ( root, - Glob::new("**/*/next/dist/server/next.js".to_string()), + Glob::new("**/*/next/dist/server/next.js".into()), ImportMapping::Ignore.into(), ), ( root, - Glob::new("**/*/next/dist/bin/next".to_string()), + Glob::new("**/*/next/dist/bin/next".into()), ImportMapping::Ignore.into(), ), ]; @@ -662,7 +666,7 @@ async fn create_module_asset( compile_time_info, ModuleOptionsContext::clone(&*module_options).cell(), resolve_options.cell(), - Vc::cell("node_file_trace".to_string()), + Vc::cell("node_file_trace".into()), )) } diff --git a/crates/node-file-trace/src/nft_json.rs b/crates/node-file-trace/src/nft_json.rs index 0d800b417a427..1e57d80a5d5f2 100644 --- a/crates/node-file-trace/src/nft_json.rs +++ b/crates/node-file-trace/src/nft_json.rs @@ -29,7 +29,9 @@ impl OutputAsset for NftJsonAsset { async fn ident(&self) -> Result> { let path = self.entry.ident().path().await?; Ok(AssetIdent::from_path( - path.fs.root().join(format!("{}.nft.json", path.path)), + path.fs + .root() + .join(format!("{}.nft.json", path.path).into()), )) } } diff --git a/crates/turbo-tasks-env/src/command_line.rs b/crates/turbo-tasks-env/src/command_line.rs index 51b763183ddc2..e3ffa7e70765c 100644 --- a/crates/turbo-tasks-env/src/command_line.rs +++ b/crates/turbo-tasks-env/src/command_line.rs @@ -1,5 +1,5 @@ use indexmap::IndexMap; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use crate::{sorted_env_vars, EnvMap, ProcessEnv, GLOBAL_ENV_LOCK}; @@ -16,7 +16,7 @@ impl CommandLineProcessEnv { } /// Clones the current env vars into a IndexMap. -fn env_snapshot() -> IndexMap { +fn env_snapshot() -> IndexMap { let _lock = GLOBAL_ENV_LOCK.lock().unwrap(); sorted_env_vars() } diff --git a/crates/turbo-tasks-env/src/custom.rs b/crates/turbo-tasks-env/src/custom.rs index f24f63e499fad..2f3eec2c770dd 100644 --- a/crates/turbo-tasks-env/src/custom.rs +++ b/crates/turbo-tasks-env/src/custom.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use crate::{case_insensitive_read, EnvMap, ProcessEnv}; @@ -32,7 +32,7 @@ impl ProcessEnv for CustomProcessEnv { } #[turbo_tasks::function] - async fn read(&self, name: String) -> Result>> { + async fn read(&self, name: RcStr) -> Result>> { let custom = case_insensitive_read(self.custom, name.clone()); match &*custom.await? { Some(_) => Ok(custom), diff --git a/crates/turbo-tasks-env/src/dotenv.rs b/crates/turbo-tasks-env/src/dotenv.rs index d32cde2af6004..9f65765cf7001 100644 --- a/crates/turbo-tasks-env/src/dotenv.rs +++ b/crates/turbo-tasks-env/src/dotenv.rs @@ -2,7 +2,7 @@ use std::{env, sync::MutexGuard}; use anyhow::{anyhow, Context, Result}; use indexmap::IndexMap; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbo_tasks_fs::{FileContent, FileSystemPath}; use crate::{sorted_env_vars, EnvMap, ProcessEnv, GLOBAL_ENV_LOCK}; @@ -84,11 +84,7 @@ impl ProcessEnv for DotenvProcessEnv { } /// Restores the global env variables to mirror `to`. -fn restore_env( - from: &IndexMap, - to: &IndexMap, - _lock: &MutexGuard<()>, -) { +fn restore_env(from: &IndexMap, to: &IndexMap, _lock: &MutexGuard<()>) { for key in from.keys() { if !to.contains_key(key) { env::remove_var(key); diff --git a/crates/turbo-tasks-env/src/filter.rs b/crates/turbo-tasks-env/src/filter.rs index bd8fb1f86abe8..5b5da3639e3ee 100644 --- a/crates/turbo-tasks-env/src/filter.rs +++ b/crates/turbo-tasks-env/src/filter.rs @@ -1,6 +1,6 @@ use anyhow::Result; use indexmap::IndexMap; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use crate::{EnvMap, ProcessEnv}; @@ -9,16 +9,19 @@ use crate::{EnvMap, ProcessEnv}; #[turbo_tasks::value] pub struct FilterProcessEnv { prior: Vc>, - filters: Vec, + filters: Vec, } #[turbo_tasks::value_impl] impl FilterProcessEnv { #[turbo_tasks::function] - pub fn new(prior: Vc>, filters: Vec) -> Vc { + pub fn new(prior: Vc>, filters: Vec) -> Vc { FilterProcessEnv { prior, - filters: filters.into_iter().map(|f| f.to_uppercase()).collect(), + filters: filters + .into_iter() + .map(|f| f.to_uppercase().into()) + .collect(), } .cell() } @@ -33,7 +36,7 @@ impl ProcessEnv for FilterProcessEnv { for (key, value) in &*prior { let uppercase = key.to_uppercase(); for filter in &self.filters { - if uppercase.starts_with(filter) { + if uppercase.starts_with(&**filter) { filtered.insert(key.clone(), value.clone()); break; } @@ -43,9 +46,9 @@ impl ProcessEnv for FilterProcessEnv { } #[turbo_tasks::function] - fn read(&self, name: String) -> Vc> { + fn read(&self, name: RcStr) -> Vc> { for filter in &self.filters { - if name.to_uppercase().starts_with(filter) { + if name.to_uppercase().starts_with(&**filter) { return self.prior.read(name); } } diff --git a/crates/turbo-tasks-env/src/lib.rs b/crates/turbo-tasks-env/src/lib.rs index db35acfd2d90b..6d4880ff6fbaf 100644 --- a/crates/turbo-tasks-env/src/lib.rs +++ b/crates/turbo-tasks-env/src/lib.rs @@ -9,7 +9,7 @@ use std::{env, sync::Mutex}; use anyhow::Result; use indexmap::IndexMap; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; pub use self::{ command_line::CommandLineProcessEnv, custom::CustomProcessEnv, dotenv::DotenvProcessEnv, @@ -17,7 +17,7 @@ pub use self::{ }; #[turbo_tasks::value(transparent)] -pub struct EnvMap(#[turbo_tasks(trace_ignore)] IndexMap); +pub struct EnvMap(#[turbo_tasks(trace_ignore)] IndexMap); #[turbo_tasks::value_impl] impl EnvMap { @@ -35,7 +35,7 @@ impl ProcessEnv for EnvMap { } #[turbo_tasks::function] - async fn read(self: Vc, name: String) -> Vc> { + async fn read(self: Vc, name: RcStr) -> Vc> { case_insensitive_read(self, name) } } @@ -51,23 +51,25 @@ pub trait ProcessEnv { fn read_all(self: Vc) -> Vc; /// Reads a single env variable. Ignores casing. - fn read(self: Vc, name: String) -> Vc> { + fn read(self: Vc, name: RcStr) -> Vc> { case_insensitive_read(self.read_all(), name) } } -pub fn sorted_env_vars() -> IndexMap { - let mut vars = env::vars().collect::>(); +pub fn sorted_env_vars() -> IndexMap { + let mut vars = env::vars() + .map(|(k, v)| (k.into(), v.into())) + .collect::>(); vars.sort_keys(); vars } #[turbo_tasks::function] -pub async fn case_insensitive_read(map: Vc, name: String) -> Result>> { +pub async fn case_insensitive_read(map: Vc, name: RcStr) -> Result>> { Ok(Vc::cell( to_uppercase_map(map) .await? - .get(&name.to_uppercase()) + .get(&RcStr::from(name.to_uppercase())) .cloned(), )) } @@ -77,7 +79,7 @@ async fn to_uppercase_map(map: Vc) -> Result> { let map = &*map.await?; let mut new = IndexMap::with_capacity(map.len()); for (k, v) in map { - new.insert(k.to_uppercase(), v.clone()); + new.insert(k.to_uppercase().into(), v.clone()); } Ok(Vc::cell(new)) } diff --git a/crates/turbo-tasks-fetch/src/lib.rs b/crates/turbo-tasks-fetch/src/lib.rs index 7684fab16dbea..7cb59d1039b37 100644 --- a/crates/turbo-tasks-fetch/src/lib.rs +++ b/crates/turbo-tasks-fetch/src/lib.rs @@ -2,7 +2,7 @@ #![feature(arbitrary_self_types)] use anyhow::Result; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::FileSystemPath; use turbopack_core::issue::{Issue, IssueSeverity, IssueStage, OptionStyledString, StyledString}; @@ -30,9 +30,9 @@ pub struct HttpResponseBody(pub Vec); #[turbo_tasks::value_impl] impl HttpResponseBody { #[turbo_tasks::function] - pub async fn to_string(self: Vc) -> Result> { + pub async fn to_string(self: Vc) -> Result> { let this = &*self.await?; - Ok(Vc::cell(std::str::from_utf8(&this.0)?.to_owned())) + Ok(Vc::cell(std::str::from_utf8(&this.0)?.into())) } } @@ -48,8 +48,8 @@ pub struct OptionProxyConfig(Option); #[turbo_tasks::function] pub async fn fetch( - url: Vc, - user_agent: Vc>, + url: Vc, + user_agent: Vc>, proxy_option: Vc, ) -> Result> { let url = &*url.await?; @@ -65,9 +65,9 @@ pub async fn fetch( let client = client_builder.build()?; - let mut builder = client.get(url); + let mut builder = client.get(url.as_str()); if let Some(user_agent) = user_agent { - builder = builder.header("User-Agent", user_agent); + builder = builder.header("User-Agent", user_agent.as_str()); } let response = builder.send().await.and_then(|r| r.error_for_status()); @@ -99,7 +99,7 @@ pub enum FetchErrorKind { #[turbo_tasks::value(shared)] pub struct FetchError { - pub url: Vc, + pub url: Vc, pub kind: Vc, pub detail: Vc, } @@ -117,8 +117,8 @@ impl FetchError { }; FetchError { - detail: StyledString::Text(error.to_string()).cell(), - url: Vc::cell(url.to_owned()), + detail: StyledString::Text(error.to_string().into()).cell(), + url: Vc::cell(url.into()), kind: kind.into(), } } @@ -148,7 +148,7 @@ impl FetchError { pub struct FetchIssue { pub issue_context: Vc, pub severity: Vc, - pub url: Vc, + pub url: Vc, pub kind: Vc, pub detail: Vc, } @@ -167,7 +167,7 @@ impl Issue for FetchIssue { #[turbo_tasks::function] fn title(&self) -> Vc { - StyledString::Text("Error while requesting resource".to_string()).cell() + StyledString::Text("Error while requesting resource".into()).cell() } #[turbo_tasks::function] @@ -185,15 +185,17 @@ impl Issue for FetchIssue { FetchErrorKind::Connect => format!( "There was an issue establishing a connection while requesting {}.", url - ), - FetchErrorKind::Status(status) => { - format!( - "Received response with status {} when requesting {}", - status, url - ) + ) + .into(), + FetchErrorKind::Status(status) => format!( + "Received response with status {} when requesting {}", + status, url + ) + .into(), + FetchErrorKind::Timeout => { + format!("Connection timed out when requesting {}", url).into() } - FetchErrorKind::Timeout => format!("Connection timed out when requesting {}", url), - FetchErrorKind::Other => format!("There was an issue requesting {}", url), + FetchErrorKind::Other => format!("There was an issue requesting {}", url).into(), }) .cell(), ))) diff --git a/crates/turbo-tasks-fetch/tests/fetch.rs b/crates/turbo-tasks-fetch/tests/fetch.rs index 0ccdcabce5168..531ad8f7ca354 100644 --- a/crates/turbo-tasks-fetch/tests/fetch.rs +++ b/crates/turbo-tasks-fetch/tests/fetch.rs @@ -21,7 +21,7 @@ async fn basic_get() { }); - let result = &*fetch(Vc::cell(server.url("/foo.woff")), Vc::cell(None), Vc::cell(None)).await?; + let result = &*fetch(Vc::cell(server.url("/foo.woff").into()), Vc::cell(None), Vc::cell(None)).await?; resource_mock.assert(); match result { @@ -47,7 +47,7 @@ async fn sends_user_agent() { .body("responsebody"); }); - let result = &*fetch(Vc::cell(server.url("/foo.woff")), Vc::cell(Some("foo".to_owned())), Vc::cell(None)).await?; + let result = &*fetch(Vc::cell(server.url("/foo.woff").into()), Vc::cell(Some("foo".into())), Vc::cell(None)).await?; resource_mock.assert(); let Ok(response) = result else { @@ -74,8 +74,8 @@ async fn invalidation_does_not_invalidate() { .body("responsebody"); }); - let url = Vc::cell(server.url("/foo.woff")); - let user_agent = Vc::cell(Some("foo".to_owned())); + let url = Vc::cell(server.url("/foo.woff").into()); + let user_agent = Vc::cell(Some("foo".into())); let proxy = Vc::cell(None); let result = &*fetch(url, user_agent, proxy).await?; resource_mock.assert(); @@ -105,7 +105,7 @@ async fn errors_on_failed_connection() { register(); let url = "https://doesnotexist/foo.woff"; - let result = &*fetch(Vc::cell(url.to_owned()), Vc::cell(None), Vc::cell(None)).await?; + let result = &*fetch(Vc::cell(url.into()), Vc::cell(None), Vc::cell(None)).await?; let Err(err_vc) = result else { panic!() }; @@ -115,7 +115,7 @@ async fn errors_on_failed_connection() { let issue = err_vc.to_issue(IssueSeverity::Error.into(), get_issue_context()); assert_eq!(*issue.severity().await?, IssueSeverity::Error); - assert_eq!(*issue.description().await?.unwrap().await?, StyledString::Text("There was an issue establishing a connection while requesting https://doesnotexist/foo.woff.".to_string())); + assert_eq!(*issue.description().await?.unwrap().await?, StyledString::Text("There was an issue establishing a connection while requesting https://doesnotexist/foo.woff.".into())); } } @@ -126,7 +126,7 @@ async fn errors_on_404() { let server = httpmock::MockServer::start(); let resource_url = server.url("/"); - let result = &*fetch(Vc::cell(resource_url.clone()), Vc::cell(None), Vc::cell(None)).await?; + let result = &*fetch(Vc::cell(resource_url.clone().into()), Vc::cell(None), Vc::cell(None)).await?; let Err(err_vc) = result else { panic!() }; @@ -136,10 +136,10 @@ async fn errors_on_404() { let issue = err_vc.to_issue(IssueSeverity::Error.into(), get_issue_context()); assert_eq!(*issue.severity().await?, IssueSeverity::Error); - assert_eq!(*issue.description().await?.unwrap().await?, StyledString::Text(format!("Received response with status 404 when requesting {}", &resource_url))); + assert_eq!(*issue.description().await?.unwrap().await?, StyledString::Text(format!("Received response with status 404 when requesting {}", &resource_url).into())); } } fn get_issue_context() -> Vc { - DiskFileSystem::new("root".to_owned(), "/".to_owned(), vec![]).root() + DiskFileSystem::new("root".into(), "/".into(), vec![]).root() } diff --git a/crates/turbo-tasks-fs/examples/hash_directory.rs b/crates/turbo-tasks-fs/examples/hash_directory.rs index 032e4f4ae667c..a8d3fb72502dc 100644 --- a/crates/turbo-tasks-fs/examples/hash_directory.rs +++ b/crates/turbo-tasks-fs/examples/hash_directory.rs @@ -9,7 +9,7 @@ use std::{ use anyhow::Result; use sha2::{Digest, Sha256}; -use turbo_tasks::{util::FormatDuration, TurboTasks, UpdateInfo, Vc}; +use turbo_tasks::{util::FormatDuration, RcStr, TurboTasks, UpdateInfo, Vc}; use turbo_tasks_fs::{ register, DirectoryContent, DirectoryEntry, DiskFileSystem, FileContent, FileSystem, FileSystemPath, @@ -29,13 +29,13 @@ async fn main() -> Result<()> { let task = tt.spawn_root_task(|| { Box::pin(async { - let root = current_dir().unwrap().to_str().unwrap().to_string(); - let disk_fs = DiskFileSystem::new("project".to_string(), root, vec![]); + let root = current_dir().unwrap().to_str().unwrap().into(); + let disk_fs = DiskFileSystem::new("project".into(), root, vec![]); disk_fs.await?.start_watching()?; // Smart Pointer cast let fs: Vc> = Vc::upcast(disk_fs); - let input = fs.root().join("demo".to_string()); + let input = fs.root().join("demo".into()); let dir_hash = hash_directory(input); print_hash(dir_hash).await?; Ok::, _>(Default::default()) @@ -55,7 +55,7 @@ async fn main() -> Result<()> { } #[turbo_tasks::function] -async fn print_hash(dir_hash: Vc) -> Result> { +async fn print_hash(dir_hash: Vc) -> Result> { println!("DIR HASH: {}", dir_hash.await?.as_str()); Ok(Default::default()) } @@ -65,7 +65,7 @@ async fn filename(path: Vc) -> Result { } #[turbo_tasks::function] -async fn hash_directory(directory: Vc) -> Result> { +async fn hash_directory(directory: Vc) -> Result> { let dir_path = &directory.await?.path; let content = directory.read_dir(); let mut hashes = BTreeMap::new(); @@ -92,7 +92,7 @@ async fn hash_directory(directory: Vc) -> Result> { let hash = hash_content( &mut hashes .into_values() - .collect::>() + .collect::>() .join(",") .as_bytes(), ); @@ -101,18 +101,18 @@ async fn hash_directory(directory: Vc) -> Result> { } #[turbo_tasks::function] -async fn hash_file(file_path: Vc) -> Result> { +async fn hash_file(file_path: Vc) -> Result> { let content = file_path.read().await?; Ok(match &*content { FileContent::Content(file) => hash_content(&mut file.read()), FileContent::NotFound => { // report error - Vc::cell("".to_string()) + Vc::cell(Default::default()) } }) } -fn hash_content(content: &mut R) -> Vc { +fn hash_content(content: &mut R) -> Vc { let mut hasher = Sha256::new(); let mut buf = [0; 1024]; while let Ok(size) = content.read(&mut buf) { @@ -120,5 +120,5 @@ fn hash_content(content: &mut R) -> Vc { } let result = format!("{:x}", hasher.finalize()); - Vc::cell(result) + Vc::cell(result.into()) } diff --git a/crates/turbo-tasks-fs/examples/hash_glob.rs b/crates/turbo-tasks-fs/examples/hash_glob.rs index 28e3231682d3f..50dcdad53f05e 100644 --- a/crates/turbo-tasks-fs/examples/hash_glob.rs +++ b/crates/turbo-tasks-fs/examples/hash_glob.rs @@ -9,7 +9,7 @@ use std::{ use anyhow::Result; use sha2::{Digest, Sha256}; -use turbo_tasks::{util::FormatDuration, TurboTasks, UpdateInfo, Vc}; +use turbo_tasks::{util::FormatDuration, RcStr, TurboTasks, UpdateInfo, Vc}; use turbo_tasks_fs::{ glob::Glob, register, DirectoryEntry, DiskFileSystem, FileContent, FileSystem, FileSystemPath, ReadGlobResult, @@ -26,14 +26,14 @@ async fn main() -> Result<()> { let task = tt.spawn_root_task(|| { Box::pin(async { - let root = current_dir().unwrap().to_str().unwrap().to_string(); - let disk_fs = DiskFileSystem::new("project".to_string(), root, vec![]); + let root = current_dir().unwrap().to_str().unwrap().into(); + let disk_fs = DiskFileSystem::new("project".into(), root, vec![]); disk_fs.await?.start_watching()?; // Smart Pointer cast let fs: Vc> = Vc::upcast(disk_fs); - let input = fs.root().join("crates".to_string()); - let glob = Glob::new("**/*.rs".to_string()); + let input = fs.root().join("crates".into()); + let glob = Glob::new("**/*.rs".into()); let glob_result = input.read_glob(glob, true); let dir_hash = hash_glob_result(glob_result); print_hash(dir_hash).await?; @@ -54,18 +54,18 @@ async fn main() -> Result<()> { } #[turbo_tasks::function] -pub fn empty_string() -> Vc { - Vc::cell("".to_string()) +pub fn empty_string() -> Vc { + Vc::cell(Default::default()) } #[turbo_tasks::function] -async fn print_hash(dir_hash: Vc) -> Result> { +async fn print_hash(dir_hash: Vc) -> Result> { println!("DIR HASH: {}", dir_hash.await?.as_str()); Ok(Default::default()) } #[turbo_tasks::function] -async fn hash_glob_result(result: Vc) -> Result> { +async fn hash_glob_result(result: Vc) -> Result> { let result = result.await?; let mut hashes = BTreeMap::new(); for (name, entry) in result.results.iter() { @@ -85,7 +85,7 @@ async fn hash_glob_result(result: Vc) -> Result> { let hash = hash_content( &mut hashes .into_values() - .collect::>() + .collect::>() .join(",") .as_bytes(), ); @@ -93,18 +93,18 @@ async fn hash_glob_result(result: Vc) -> Result> { } #[turbo_tasks::function] -async fn hash_file(file_path: Vc) -> Result> { +async fn hash_file(file_path: Vc) -> Result> { let content = file_path.read().await?; Ok(match &*content { FileContent::Content(file) => hash_content(&mut file.read()), FileContent::NotFound => { // report error - Vc::cell("".to_string()) + Vc::cell(Default::default()) } }) } -fn hash_content(content: &mut R) -> Vc { +fn hash_content(content: &mut R) -> Vc { let mut hasher = Sha256::new(); let mut buf = [0; 1024]; while let Ok(size) = content.read(&mut buf) { @@ -112,5 +112,5 @@ fn hash_content(content: &mut R) -> Vc { } let result = format!("{:x}", hasher.finalize()); - Vc::cell(result) + Vc::cell(result.into()) } diff --git a/crates/turbo-tasks-fs/src/attach.rs b/crates/turbo-tasks-fs/src/attach.rs index 7fc1af31ec9e1..f9b70352f660d 100644 --- a/crates/turbo-tasks-fs/src/attach.rs +++ b/crates/turbo-tasks-fs/src/attach.rs @@ -1,6 +1,6 @@ use anyhow::{bail, Result}; use auto_hash_map::AutoMap; -use turbo_tasks::{Completion, ValueToString, Vc}; +use turbo_tasks::{Completion, RcStr, ValueToString, Vc}; use crate::{ DirectoryContent, DirectoryEntry, FileContent, FileMeta, FileSystem, FileSystemPath, @@ -16,7 +16,7 @@ pub struct AttachedFileSystem { root_fs: Vc>, // we turn this into a string because creating a FileSystemPath requires the filesystem which // we are creating (circular reference) - child_path: String, + child_path: RcStr, child_fs: Vc>, } @@ -112,7 +112,7 @@ impl AttachedFileSystem { .root() .resolve() .await? - .join(inner_path.to_string()) + .join(inner_path.into()) } else { this.root_fs.root().resolve().await?.join(path.path.clone()) }) @@ -185,9 +185,11 @@ impl FileSystem for AttachedFileSystem { #[turbo_tasks::value_impl] impl ValueToString for AttachedFileSystem { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { + async fn to_string(&self) -> Result> { let root_fs_str = self.root_fs.to_string().await?; let child_fs_str = self.child_fs.to_string().await?; - Ok(Vc::cell(format!("{}-with-{}", root_fs_str, child_fs_str))) + Ok(Vc::cell( + format!("{}-with-{}", root_fs_str, child_fs_str).into(), + )) } } diff --git a/crates/turbo-tasks-fs/src/embed/dir.rs b/crates/turbo-tasks-fs/src/embed/dir.rs index 90e34fc5b86e7..93031ecf60aef 100644 --- a/crates/turbo-tasks-fs/src/embed/dir.rs +++ b/crates/turbo-tasks-fs/src/embed/dir.rs @@ -2,14 +2,14 @@ pub use ::include_dir::{ include_dir, {self}, }; use anyhow::Result; -use turbo_tasks::{TransientInstance, Vc}; +use turbo_tasks::{RcStr, TransientInstance, Vc}; use crate::{embed::EmbeddedFileSystem, DiskFileSystem, FileSystem}; #[turbo_tasks::function] pub async fn directory_from_relative_path( - name: String, - path: String, + name: RcStr, + path: RcStr, ) -> Result>> { let disk_fs = DiskFileSystem::new(name, path, vec![]); disk_fs.await?.start_watching()?; @@ -19,7 +19,7 @@ pub async fn directory_from_relative_path( #[turbo_tasks::function] pub async fn directory_from_include_dir( - name: String, + name: RcStr, dir: TransientInstance<&'static include_dir::Dir<'static>>, ) -> Result>> { Ok(Vc::upcast(EmbeddedFileSystem::new(name, dir))) @@ -72,7 +72,7 @@ macro_rules! embed_directory_internal { static dir: include_dir::Dir<'static> = turbo_tasks_fs::embed::include_dir!($path); turbo_tasks_fs::embed::directory_from_include_dir( - $name.to_string(), + $name.into(), turbo_tasks::TransientInstance::new(&dir), ) }}; diff --git a/crates/turbo-tasks-fs/src/embed/file.rs b/crates/turbo-tasks-fs/src/embed/file.rs index 6dcc925f13ae1..74646862b8ff4 100644 --- a/crates/turbo-tasks-fs/src/embed/file.rs +++ b/crates/turbo-tasks-fs/src/embed/file.rs @@ -2,14 +2,14 @@ use std::path::PathBuf; use anyhow::{Context, Result}; use dunce::canonicalize; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use crate::{DiskFileSystem, File, FileContent, FileSystem}; #[turbo_tasks::function] pub async fn content_from_relative_path( - package_path: String, - path: String, + package_path: RcStr, + path: RcStr, ) -> Result> { let package_path = PathBuf::from(package_path); let resolved_path = package_path.join(path); @@ -19,18 +19,18 @@ pub async fn content_from_relative_path( let path = resolved_path.file_name().unwrap().to_str().unwrap(); let disk_fs = DiskFileSystem::new( - root_path.to_string_lossy().to_string(), - root_path.to_string_lossy().to_string(), + root_path.to_string_lossy().into(), + root_path.to_string_lossy().into(), vec![], ); disk_fs.await?.start_watching()?; - let fs_path = disk_fs.root().join(path.to_string()); + let fs_path = disk_fs.root().join(path.into()); Ok(fs_path.read()) } #[turbo_tasks::function] -pub async fn content_from_str(string: String) -> Result> { +pub async fn content_from_str(string: RcStr) -> Result> { Ok(File::from(string).into()) } @@ -57,7 +57,7 @@ macro_rules! embed_file { macro_rules! embed_file { ($path:expr) => { turbo_tasks_fs::embed::content_from_str( - include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/", $path)).to_string(), + include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/", $path)).into(), ) }; } diff --git a/crates/turbo-tasks-fs/src/embed/fs.rs b/crates/turbo-tasks-fs/src/embed/fs.rs index 7e5862a71427b..e0f24c32e54c4 100644 --- a/crates/turbo-tasks-fs/src/embed/fs.rs +++ b/crates/turbo-tasks-fs/src/embed/fs.rs @@ -1,6 +1,6 @@ use anyhow::{bail, Result}; use include_dir::{Dir, DirEntry}; -use turbo_tasks::{Completion, TransientInstance, ValueToString, Vc}; +use turbo_tasks::{Completion, RcStr, TransientInstance, ValueToString, Vc}; use crate::{ DirectoryContent, DirectoryEntry, File, FileContent, FileMeta, FileSystem, FileSystemPath, @@ -9,7 +9,7 @@ use crate::{ #[turbo_tasks::value(serialization = "none")] pub struct EmbeddedFileSystem { - name: String, + name: RcStr, #[turbo_tasks(trace_ignore)] dir: TransientInstance<&'static Dir<'static>>, } @@ -18,7 +18,7 @@ pub struct EmbeddedFileSystem { impl EmbeddedFileSystem { #[turbo_tasks::function] pub(super) fn new( - name: String, + name: RcStr, dir: TransientInstance<&'static Dir<'static>>, ) -> Vc { EmbeddedFileSystem { name, dir }.cell() @@ -55,11 +55,16 @@ impl FileSystem for EmbeddedFileSystem { .entries() .iter() .map(|e| { - let entry_name = e.path().file_name().unwrap_or_default().to_string_lossy(); - let entry_path = path.join(entry_name.to_string()); + let entry_name: RcStr = e + .path() + .file_name() + .unwrap_or_default() + .to_string_lossy() + .into(); + let entry_path = path.join(entry_name.clone()); ( - entry_name.to_string(), + entry_name, match e { DirEntry::Dir(_) => DirectoryEntry::Directory(entry_path), DirEntry::File(_) => DirectoryEntry::File(entry_path), @@ -107,7 +112,7 @@ impl FileSystem for EmbeddedFileSystem { #[turbo_tasks::value_impl] impl ValueToString for EmbeddedFileSystem { #[turbo_tasks::function] - fn to_string(&self) -> Vc { + fn to_string(&self) -> Vc { Vc::cell(self.name.clone()) } } diff --git a/crates/turbo-tasks-fs/src/glob.rs b/crates/turbo-tasks-fs/src/glob.rs index f68be03ca9ec0..43e72853ed1f5 100644 --- a/crates/turbo-tasks-fs/src/glob.rs +++ b/crates/turbo-tasks-fs/src/glob.rs @@ -2,7 +2,7 @@ use std::mem::take; use anyhow::{anyhow, bail, Context, Result}; use serde::{Deserialize, Serialize}; -use turbo_tasks::{trace::TraceRawVcs, TryJoinIterExt, Vc}; +use turbo_tasks::{trace::TraceRawVcs, RcStr, TryJoinIterExt, Vc}; use unicode_segmentation::GraphemeCursor; #[derive(PartialEq, Eq, Debug, Clone, TraceRawVcs, Serialize, Deserialize)] @@ -395,7 +395,7 @@ impl TryFrom<&str> for Glob { #[turbo_tasks::value_impl] impl Glob { #[turbo_tasks::function] - pub fn new(glob: String) -> Result> { + pub fn new(glob: RcStr) -> Result> { Ok(Self::cell(Glob::try_from(glob.as_str())?)) } diff --git a/crates/turbo-tasks-fs/src/invalidation.rs b/crates/turbo-tasks-fs/src/invalidation.rs index cbb46ddd2659d..22976c49dc4e4 100644 --- a/crates/turbo-tasks-fs/src/invalidation.rs +++ b/crates/turbo-tasks-fs/src/invalidation.rs @@ -1,7 +1,7 @@ use std::fmt::{Display, Formatter}; use indexmap::IndexSet; -use turbo_tasks::{util::StaticOrArc, InvalidationReason, InvalidationReasonKind}; +use turbo_tasks::{util::StaticOrArc, InvalidationReason, InvalidationReasonKind, RcStr}; /// Invalidation was caused by a file change detected by the file watcher #[derive(PartialEq, Eq, Hash)] @@ -50,7 +50,7 @@ impl InvalidationReasonKind for WatchChangeKind { /// before. #[derive(PartialEq, Eq, Hash)] pub struct WatchStart { - pub name: String, + pub name: RcStr, } impl InvalidationReason for WatchStart { diff --git a/crates/turbo-tasks-fs/src/lib.rs b/crates/turbo-tasks-fs/src/lib.rs index 9a34102d25418..75409f6ee39d5 100644 --- a/crates/turbo-tasks-fs/src/lib.rs +++ b/crates/turbo-tasks-fs/src/lib.rs @@ -58,7 +58,7 @@ use tokio::{ }; use tracing::Instrument; use turbo_tasks::{ - mark_stateful, trace::TraceRawVcs, Completion, InvalidationReason, Invalidator, ReadRef, + mark_stateful, trace::TraceRawVcs, Completion, InvalidationReason, Invalidator, RcStr, ReadRef, ValueToString, Vc, }; use turbo_tasks_hash::{hash_xxh3_hash64, DeterministicHash, DeterministicHasher}; @@ -77,7 +77,7 @@ use crate::{ pub trait FileSystem: ValueToString { /// Returns the path to the root of the file system. fn root(self: Vc) -> Vc { - FileSystemPath::new_normalized(self, String::new()) + FileSystemPath::new_normalized(self, RcStr::default()) } fn read(self: Vc, fs_path: Vc) -> Vc; fn read_link(self: Vc, fs_path: Vc) -> Vc; @@ -98,8 +98,8 @@ pub trait FileSystem: ValueToString { #[turbo_tasks::value(cell = "new", eq = "manual")] pub struct DiskFileSystem { - pub name: String, - pub root: String, + pub name: RcStr, + pub root: RcStr, #[turbo_tasks(debug_ignore, trace_ignore)] #[serde(skip)] mutex_map: MutexMap, @@ -119,7 +119,7 @@ pub struct DiskFileSystem { impl DiskFileSystem { /// Returns the root as Path fn root_path(&self) -> &Path { - simplified(Path::new(&self.root)) + simplified(Path::new(&*self.root)) } /// registers the path as an invalidator for the current task, @@ -288,11 +288,7 @@ impl DiskFileSystem { /// root & project dir is different and requires to ignore specific /// subpaths from each. #[turbo_tasks::function] - pub async fn new( - name: String, - root: String, - ignored_subpaths: Vec, - ) -> Result> { + pub async fn new(name: RcStr, root: RcStr, ignored_subpaths: Vec) -> Result> { mark_stateful(); // create the directory for the filesystem on disk, if it doesn't exist fs::create_dir_all(&root).await?; @@ -383,10 +379,10 @@ impl FileSystem for DiskFileSystem { let path = e.path(); // we filter out any non unicode names and paths without the same root here - let file_name = path.file_name()?.to_str()?.to_string(); + let file_name: RcStr = path.file_name()?.to_str()?.into(); let path_to_root = sys_to_unix(path.strip_prefix(&self.root).ok()?.to_str()?); - let fs_path = FileSystemPath::new_normalized(fs_path.fs, path_to_root.to_string()); + let fs_path = FileSystemPath::new_normalized(fs_path.fs, path_to_root.into()); let entry = match e.file_type() { Ok(t) if t.is_file() => DirectoryEntry::File(fs_path), @@ -456,7 +452,7 @@ impl FileSystem for DiskFileSystem { }; let (target, file_type) = if is_link_absolute { - let target_string = relative_to_root_path.to_string_lossy().to_string(); + let target_string: RcStr = relative_to_root_path.to_string_lossy().into(); ( target_string.clone(), FileSystemPath::new_normalized(fs_path.fs(), target_string) @@ -465,14 +461,10 @@ impl FileSystem for DiskFileSystem { ) } else { let link_path_string_cow = link_path.to_string_lossy(); - let link_path_unix = sys_to_unix(&link_path_string_cow); + let link_path_unix: RcStr = sys_to_unix(&link_path_string_cow).into(); ( - link_path_unix.to_string(), - fs_path - .parent() - .join(link_path_unix.to_string()) - .get_type() - .await?, + link_path_unix.clone(), + fs_path.parent().join(link_path_unix).get_type().await?, ) }; @@ -721,7 +713,7 @@ impl FileSystem for DiskFileSystem { #[turbo_tasks::value_impl] impl ValueToString for DiskFileSystem { #[turbo_tasks::function] - fn to_string(&self) -> Vc { + fn to_string(&self) -> Vc { Vc::cell(self.name.clone()) } } @@ -730,12 +722,12 @@ impl ValueToString for DiskFileSystem { #[derive(Debug, Clone)] pub struct FileSystemPath { pub fs: Vc>, - pub path: String, + pub path: RcStr, } impl FileSystemPath { pub fn is_inside_ref(&self, other: &FileSystemPath) -> bool { - if self.fs == other.fs && self.path.starts_with(&other.path) { + if self.fs == other.fs && self.path.starts_with(&*other.path) { if other.path.is_empty() { true } else { @@ -747,7 +739,7 @@ impl FileSystemPath { } pub fn is_inside_or_equal_ref(&self, other: &FileSystemPath) -> bool { - if self.fs == other.fs && self.path.starts_with(&other.path) { + if self.fs == other.fs && self.path.starts_with(&*other.path) { if other.path.is_empty() { true } else { @@ -772,7 +764,7 @@ impl FileSystemPath { if self.fs != inner.fs { return None; } - let path = inner.path.strip_prefix(&self.path)?; + let path = inner.path.strip_prefix(&*self.path)?; if self.path.is_empty() { Some(path) } else if let Some(stripped) = path.strip_prefix('/') { @@ -782,7 +774,7 @@ impl FileSystemPath { } } - pub fn get_relative_path_to(&self, other: &FileSystemPath) -> Option { + pub fn get_relative_path_to(&self, other: &FileSystemPath) -> Option { if self.fs != other.fs { return None; } @@ -799,7 +791,7 @@ impl FileSystemPath { while self_segments.peek() == other_segments.peek() { self_segments.next(); if other_segments.next().is_none() { - return Some(".".to_string()); + return Some(".".into()); } } let mut result = Vec::new(); @@ -813,7 +805,7 @@ impl FileSystemPath { for segment in other_segments { result.push(segment); } - Some(result.join("/")) + Some(result.join("/").into()) } /// Returns the final component of the FileSystemPath, or an empty string @@ -890,7 +882,7 @@ impl FileSystemPath { /// /-separated path is expected to be already normalized (this is asserted /// in dev mode). #[turbo_tasks::function] - fn new_normalized(fs: Vc>, path: String) -> Vc { + fn new_normalized(fs: Vc>, path: RcStr) -> Vc { // On Windows, the path must be converted to a unix path before creating. But on // Unix, backslashes are a valid char in file names, and the path can be // provided by the user, so we allow it. @@ -900,7 +892,7 @@ impl FileSystemPath { path, ); debug_assert!( - normalize_path(&path).as_ref() == Some(&path), + normalize_path(&path).as_deref() == Some(&*path), "path {} must be normalized", path, ); @@ -911,10 +903,10 @@ impl FileSystemPath { /// contain ".." or "." seqments, but it must not leave the root of the /// filesystem. #[turbo_tasks::function] - pub async fn join(self: Vc, path: String) -> Result> { + pub async fn join(self: Vc, path: RcStr) -> Result> { let this = self.await?; if let Some(path) = join_path(&this.path, &path) { - Ok(Self::new_normalized(this.fs, path)) + Ok(Self::new_normalized(this.fs, path.into())) } else { bail!( "Vc(\"{}\").join(\"{}\") leaves the filesystem root", @@ -926,7 +918,7 @@ impl FileSystemPath { /// Adds a suffix to the filename. [path] must not contain `/`. #[turbo_tasks::function] - pub async fn append(self: Vc, path: String) -> Result> { + pub async fn append(self: Vc, path: RcStr) -> Result> { let this = self.await?; if path.contains('/') { bail!( @@ -937,14 +929,14 @@ impl FileSystemPath { } Ok(Self::new_normalized( this.fs, - format!("{}{}", this.path, path), + format!("{}{}", this.path, path).into(), )) } /// Adds a suffix to the basename of the filename. [appending] must not /// contain `/`. Extension will stay intact. #[turbo_tasks::function] - pub async fn append_to_stem(self: Vc, appending: String) -> Result> { + pub async fn append_to_stem(self: Vc, appending: RcStr) -> Result> { let this = self.await?; if appending.contains('/') { bail!( @@ -956,23 +948,23 @@ impl FileSystemPath { if let (path, Some(ext)) = this.split_extension() { return Ok(Self::new_normalized( this.fs, - format!("{}{}.{}", path, appending, ext), + format!("{}{}.{}", path, appending, ext).into(), )); } Ok(Self::new_normalized( this.fs, - format!("{}{}", this.path, appending), + format!("{}{}", this.path, appending).into(), )) } /// Similar to [FileSystemPath::join], but returns an Option that will be /// None when the joined path would leave the filesystem root. #[turbo_tasks::function] - pub async fn try_join(self: Vc, path: String) -> Result> { + pub async fn try_join(self: Vc, path: RcStr) -> Result> { let this = self.await?; if let Some(path) = join_path(&this.path, &path) { Ok(Vc::cell(Some( - Self::new_normalized(this.fs, path).resolve().await?, + Self::new_normalized(this.fs, path.into()).resolve().await?, ))) } else { Ok(FileSystemPathOption::none()) @@ -982,12 +974,12 @@ impl FileSystemPath { /// Similar to [FileSystemPath::join], but returns an Option that will be /// None when the joined path would leave the current path. #[turbo_tasks::function] - pub async fn try_join_inside(self: Vc, path: String) -> Result> { + pub async fn try_join_inside(self: Vc, path: RcStr) -> Result> { let this = self.await?; if let Some(path) = join_path(&this.path, &path) { - if path.starts_with(&this.path) { + if path.starts_with(&*this.path) { return Ok(Vc::cell(Some( - Self::new_normalized(this.fs, path).resolve().await?, + Self::new_normalized(this.fs, path.into()).resolve().await?, ))); } } @@ -1014,9 +1006,9 @@ impl FileSystemPath { } #[turbo_tasks::function] - pub async fn extension(self: Vc) -> Result> { + pub async fn extension(self: Vc) -> Result> { let this = self.await?; - Ok(Vc::cell(this.extension_ref().unwrap_or("").to_string())) + Ok(Vc::cell(this.extension_ref().unwrap_or("").into())) } #[turbo_tasks::function] @@ -1032,7 +1024,7 @@ impl FileSystemPath { /// Creates a new [`Vc`] like `self` but with the given /// extension. #[turbo_tasks::function] - pub async fn with_extension(self: Vc, extension: String) -> Result> { + pub async fn with_extension(self: Vc, extension: RcStr) -> Result> { let this = self.await?; let (path_without_extension, _) = this.split_extension(); Ok(Self::new_normalized( @@ -1040,8 +1032,8 @@ impl FileSystemPath { // Like `Path::with_extension` and `PathBuf::set_extension`, if the extension is empty, // we remove the extension altogether. match extension.is_empty() { - true => path_without_extension.to_string(), - false => format!("{path_without_extension}.{extension}"), + true => path_without_extension.into(), + false => format!("{path_without_extension}.{extension}").into(), }, )) } @@ -1056,13 +1048,13 @@ impl FileSystemPath { /// `.`s within; /// * Otherwise, the portion of the file name before the final `.` #[turbo_tasks::function] - pub async fn file_stem(self: Vc) -> Result>> { + pub async fn file_stem(self: Vc) -> Result>> { let this = self.await?; let (_, file_stem, _) = this.split_file_stem_extension(); if file_stem.is_empty() { return Ok(Vc::cell(None)); } - Ok(Vc::cell(Some(file_stem.to_string()))) + Ok(Vc::cell(Some(file_stem.into()))) } } @@ -1086,7 +1078,7 @@ pub async fn rebase( if new_base.path.is_empty() { new_path = fs_path.path.clone(); } else { - new_path = [new_base.path.as_str(), "/", &fs_path.path].concat(); + new_path = [new_base.path.as_str(), "/", &fs_path.path].concat().into(); } } else { let base_path = [&old_base.path, "/"].concat(); @@ -1099,9 +1091,11 @@ pub async fn rebase( ); } if new_base.path.is_empty() { - new_path = [&fs_path.path[base_path.len()..]].concat(); + new_path = [&fs_path.path[base_path.len()..]].concat().into(); } else { - new_path = [new_base.path.as_str(), &fs_path.path[old_base.path.len()..]].concat(); + new_path = [new_base.path.as_str(), &fs_path.path[old_base.path.len()..]] + .concat() + .into(); } } Ok(new_base.fs.root().join(new_path)) @@ -1171,7 +1165,7 @@ impl FileSystemPath { Some(index) => path[..index].to_string(), None => "".to_string(), }; - Ok(FileSystemPath::new_normalized(this.fs, p)) + Ok(FileSystemPath::new_normalized(this.fs, p.into())) } #[turbo_tasks::function] @@ -1222,11 +1216,7 @@ impl FileSystemPath { .rsplit_once('/') .map_or(this.path.as_str(), |(_, name)| name); let real_self = if parent_result.path != parent { - parent_result - .path - .join(basename.to_string()) - .resolve() - .await? + parent_result.path.join(basename.into()).resolve().await? } else { self }; @@ -1239,7 +1229,7 @@ impl FileSystemPath { } else { result.path } - .join(target.to_string()) + .join(target.clone()) .resolve() .await?; return Ok(result.cell()); @@ -1253,12 +1243,10 @@ impl FileSystemPath { #[turbo_tasks::value_impl] impl ValueToString for FileSystemPath { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "[{}]/{}", - self.fs.to_string().await?, - self.path - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("[{}]/{}", self.fs.to_string().await?, self.path).into(), + )) } } @@ -1429,7 +1417,7 @@ pub enum LinkContent { // normalized, which means in `fn write_link` we couldn't restore the raw value of the file // link because there is only **dist** path in `fn write_link`, and we need the raw path if // we want to restore the link value in `fn write_link` - Link { target: String, link_type: LinkType }, + Link { target: RcStr, link_type: LinkType }, Invalid, NotFound, } @@ -1499,14 +1487,20 @@ impl Debug for File { } } +impl From for File { + fn from(s: RcStr) -> Self { + s.into_owned().into() + } +} + impl From for File { fn from(s: String) -> Self { File::from_bytes(s.into_bytes()) } } -impl From> for File { - fn from(s: ReadRef) -> Self { +impl From> for File { + fn from(s: ReadRef) -> Self { File::from_bytes(s.as_bytes().to_vec()) } } @@ -1762,9 +1756,9 @@ impl ValueToString for FileJsonContent { /// This operation will only succeed if the file contents are a valid JSON /// value. #[turbo_tasks::function] - async fn to_string(&self) -> Result> { + async fn to_string(&self) -> Result> { match self { - FileJsonContent::Content(json) => Ok(Vc::cell(json.to_string())), + FileJsonContent::Content(json) => Ok(Vc::cell(json.to_string().into())), FileJsonContent::Unparseable(e) => Err(anyhow!("File is not valid JSON: {}", e)), FileJsonContent::NotFound => Err(anyhow!("File not found")), } @@ -1856,12 +1850,12 @@ impl From<&DirectoryEntry> for FileSystemEntryType { #[turbo_tasks::value] #[derive(Debug)] pub enum DirectoryContent { - Entries(AutoMap), + Entries(AutoMap), NotFound, } impl DirectoryContent { - pub fn new(entries: AutoMap) -> Vc { + pub fn new(entries: AutoMap) -> Vc { Self::cell(DirectoryContent::Entries(entries)) } @@ -1914,8 +1908,8 @@ impl FileSystem for NullFileSystem { #[turbo_tasks::value_impl] impl ValueToString for NullFileSystem { #[turbo_tasks::function] - fn to_string(&self) -> Vc { - Vc::cell(String::from("null")) + fn to_string(&self) -> Vc { + Vc::cell(RcStr::from("null")) } } @@ -1953,24 +1947,24 @@ mod tests { let path_txt = FileSystemPath::new_normalized(fs, "foo/bar.txt".into()); - let path_json = path_txt.with_extension("json".to_string()); + let path_json = path_txt.with_extension("json".into()); assert_eq!(&*path_json.await.unwrap().path, "foo/bar.json"); - let path_no_ext = path_txt.with_extension("".to_string()); + let path_no_ext = path_txt.with_extension("".into()); assert_eq!(&*path_no_ext.await.unwrap().path, "foo/bar"); - let path_new_ext = path_no_ext.with_extension("json".to_string()); + let path_new_ext = path_no_ext.with_extension("json".into()); assert_eq!(&*path_new_ext.await.unwrap().path, "foo/bar.json"); let path_no_slash_txt = FileSystemPath::new_normalized(fs, "bar.txt".into()); - let path_no_slash_json = path_no_slash_txt.with_extension("json".to_string()); + let path_no_slash_json = path_no_slash_txt.with_extension("json".into()); assert_eq!(path_no_slash_json.await.unwrap().path.as_str(), "bar.json"); - let path_no_slash_no_ext = path_no_slash_txt.with_extension("".to_string()); + let path_no_slash_no_ext = path_no_slash_txt.with_extension("".into()); assert_eq!(path_no_slash_no_ext.await.unwrap().path.as_str(), "bar"); - let path_no_slash_new_ext = path_no_slash_no_ext.with_extension("json".to_string()); + let path_no_slash_new_ext = path_no_slash_no_ext.with_extension("json".into()); assert_eq!( path_no_slash_new_ext.await.unwrap().path.as_str(), "bar.json" diff --git a/crates/turbo-tasks-fs/src/read_glob.rs b/crates/turbo-tasks-fs/src/read_glob.rs index 35bffa372dc0a..f026d23bca269 100644 --- a/crates/turbo-tasks-fs/src/read_glob.rs +++ b/crates/turbo-tasks-fs/src/read_glob.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use anyhow::Result; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use crate::{glob::Glob, DirectoryContent, DirectoryEntry, FileSystemPath}; @@ -27,7 +27,7 @@ pub async fn read_glob( #[turbo_tasks::function] async fn read_glob_inner( - prefix: String, + prefix: RcStr, directory: Vc, glob: Vc, include_dot_files: bool, @@ -50,7 +50,7 @@ async fn read_glob_internal( match item { (segment, DirectoryEntry::Directory(path)) => { let full_path = format!("{prefix}{segment}"); - let full_path_prefix = format!("{full_path}/"); + let full_path_prefix: RcStr = format!("{full_path}/").into(); if glob_value.execute(&full_path) { result .results diff --git a/crates/turbo-tasks-fs/src/virtual_fs.rs b/crates/turbo-tasks-fs/src/virtual_fs.rs index 7608c06bf5622..f578e6b037bd8 100644 --- a/crates/turbo-tasks-fs/src/virtual_fs.rs +++ b/crates/turbo-tasks-fs/src/virtual_fs.rs @@ -1,11 +1,11 @@ use anyhow::{bail, Result}; -use turbo_tasks::{Completion, ValueDefault, ValueToString, Vc}; +use turbo_tasks::{Completion, RcStr, ValueDefault, ValueToString, Vc}; use super::{DirectoryContent, FileContent, FileMeta, FileSystem, FileSystemPath, LinkContent}; #[turbo_tasks::value] pub struct VirtualFileSystem { - name: String, + name: RcStr, } impl VirtualFileSystem { @@ -19,7 +19,7 @@ impl VirtualFileSystem { /// [`Vc`]. pub fn new() -> Vc { Self::cell(VirtualFileSystem { - name: "virtual file system".to_string(), + name: "virtual file system".into(), }) } @@ -31,7 +31,7 @@ impl VirtualFileSystem { /// will never be equivalent, nor be interoperable, with a /// [`Vc`] created from another /// [`Vc`]. - pub fn new_with_name(name: String) -> Vc { + pub fn new_with_name(name: RcStr) -> Vc { Self::cell(VirtualFileSystem { name }) } } @@ -91,7 +91,7 @@ impl FileSystem for VirtualFileSystem { #[turbo_tasks::value_impl] impl ValueToString for VirtualFileSystem { #[turbo_tasks::function] - fn to_string(&self) -> Vc { + fn to_string(&self) -> Vc { Vc::cell(self.name.clone()) } } diff --git a/crates/turbo-tasks-fs/src/watcher.rs b/crates/turbo-tasks-fs/src/watcher.rs index 6af75e426bca6..371777bcbfc97 100644 --- a/crates/turbo-tasks-fs/src/watcher.rs +++ b/crates/turbo-tasks-fs/src/watcher.rs @@ -18,7 +18,7 @@ use notify_debouncer_full::{DebounceEventResult, DebouncedEvent, Debouncer, File use serde::{Deserialize, Serialize}; use tokio::sync::RwLock; use tracing::instrument; -use turbo_tasks::{spawn_thread, Invalidator}; +use turbo_tasks::{spawn_thread, Invalidator, RcStr}; use crate::{ format_absolute_fs_path, @@ -124,9 +124,9 @@ impl DiskWatcher { /// - Doesn't emit Modify events after a Create event pub(crate) fn start_watching( self: Arc, - name: String, + name: RcStr, root_path: PathBuf, - report_invalidation_reason: Option<(String, PathBuf)>, + report_invalidation_reason: Option<(RcStr, PathBuf)>, invalidation_lock: Arc>, invalidator_map: Arc, dir_invalidator_map: Arc, @@ -209,7 +209,7 @@ impl DiskWatcher { &self, rx: Receiver, root_path: PathBuf, - report_invalidation_reason: Option<(String, PathBuf)>, + report_invalidation_reason: Option<(RcStr, PathBuf)>, invalidation_lock: Arc>, invalidator_map: Arc, dir_invalidator_map: Arc, @@ -428,7 +428,7 @@ impl DiskWatcher { #[instrument(parent = None, level = "info", name = "DiskFileSystem file change", skip_all, fields(name = display(path.display())))] fn invalidate( - report_invalidation_reason: &Option<(String, PathBuf)>, + report_invalidation_reason: &Option<(RcStr, PathBuf)>, path: &Path, invalidator: Invalidator, ) { @@ -442,7 +442,7 @@ fn invalidate( } fn invalidate_path( - report_invalidation_reason: &Option<(String, PathBuf)>, + report_invalidation_reason: &Option<(RcStr, PathBuf)>, invalidator_map: &mut HashMap>, paths: impl Iterator, ) { @@ -457,7 +457,7 @@ fn invalidate_path( } fn invalidate_path_and_children_execute( - report_invalidation_reason: &Option<(String, PathBuf)>, + report_invalidation_reason: &Option<(RcStr, PathBuf)>, invalidator_map: &mut HashMap>, paths: impl Iterator, ) { diff --git a/crates/turbo-tasks-macros/src/lib.rs b/crates/turbo-tasks-macros/src/lib.rs index 0e5f3b77b49d2..f9977e5afd1c4 100644 --- a/crates/turbo-tasks-macros/src/lib.rs +++ b/crates/turbo-tasks-macros/src/lib.rs @@ -161,7 +161,7 @@ pub fn primitive(input: TokenStream) -> TokenStream { /// /// // Now you can do the following, for any `A` and `B` value types: /// -/// let vc: Vc, Vc>> = Vc::cell( +/// let vc: Vc, Vc>> = Vc::cell( /// GenericType::new( /// Vc::cell(42), /// Vc::cell("hello".to_string()) diff --git a/crates/turbo-tasks-memory/tests/all_in_one.rs b/crates/turbo-tasks-memory/tests/all_in_one.rs index d9223c442dcc8..f83d05b6ca8e9 100644 --- a/crates/turbo-tasks-memory/tests/all_in_one.rs +++ b/crates/turbo-tasks-memory/tests/all_in_one.rs @@ -2,7 +2,7 @@ use anyhow::{anyhow, Result}; use indexmap::{IndexMap, IndexSet}; -use turbo_tasks::{debug::ValueDebug, Value, ValueToString, Vc}; +use turbo_tasks::{debug::ValueDebug, RcStr, Value, ValueToString, Vc}; use turbo_tasks_testing::{register, run}; register!(); @@ -133,10 +133,10 @@ impl MyEnumValue { #[turbo_tasks::value_impl] impl ValueToString for MyEnumValue { #[turbo_tasks::function] - fn to_string(&self) -> Vc { + fn to_string(&self) -> Vc { match self { - MyEnumValue::Yeah(value) => Vc::cell(value.to_string()), - MyEnumValue::Nah => Vc::cell("nah".to_string()), + MyEnumValue::Yeah(value) => Vc::cell(value.to_string().into()), + MyEnumValue::Nah => Vc::cell("nah".into()), MyEnumValue::More(more) => more.to_string(), } } @@ -162,30 +162,30 @@ impl MyStructValue { #[turbo_tasks::value_impl] impl ValueToString for MyStructValue { #[turbo_tasks::function] - fn to_string(&self) -> Vc { - Vc::cell(self.value.to_string()) + fn to_string(&self) -> Vc { + Vc::cell(self.value.to_string().into()) } } #[turbo_tasks::value_impl] impl MyTrait for MyStructValue { #[turbo_tasks::function] - fn my_trait_function2(self: Vc) -> Vc { + fn my_trait_function2(self: Vc) -> Vc { self.to_string() } #[turbo_tasks::function] - async fn my_trait_function3(&self) -> Result> { + async fn my_trait_function3(&self) -> Result> { if let Some(next) = self.next { return Ok(next.my_trait_function3()); } - Ok(Vc::cell(self.value.to_string())) + Ok(Vc::cell(self.value.to_string().into())) } } #[turbo_tasks::value_trait] trait MyTrait: ValueToString { // TODO #[turbo_tasks::function] - async fn my_trait_function(self: Vc) -> Result> { + async fn my_trait_function(self: Vc) -> Result> { if *self.to_string().await? != "42" { return Err(anyhow!( "my_trait_function must only be called with 42 as value" @@ -195,8 +195,8 @@ trait MyTrait: ValueToString { Ok(self.to_string()) } - fn my_trait_function2(self: Vc) -> Vc; - fn my_trait_function3(self: Vc) -> Vc; + fn my_trait_function2(self: Vc) -> Vc; + fn my_trait_function3(self: Vc) -> Vc; } #[turbo_tasks::function] diff --git a/crates/turbo-tasks-memory/tests/collectibles.rs b/crates/turbo-tasks-memory/tests/collectibles.rs index 35d48f7f42fb7..779b20246c20e 100644 --- a/crates/turbo-tasks-memory/tests/collectibles.rs +++ b/crates/turbo-tasks-memory/tests/collectibles.rs @@ -5,14 +5,14 @@ use std::{collections::HashSet, time::Duration}; use anyhow::Result; use auto_hash_map::AutoSet; use tokio::time::sleep; -use turbo_tasks::{emit, CollectiblesSource, ValueToString, Vc}; +use turbo_tasks::{emit, CollectiblesSource, RcStr, ValueToString, Vc}; use turbo_tasks_testing::{register, run}; register!(); #[tokio::test] async fn transitive_emitting() { run! { - let result = my_transitive_emitting_function("".to_string(), "".to_string()); + let result = my_transitive_emitting_function("".into(), "".into()); result.strongly_consistent().await?; let list = result.peek_collectibles::>(); assert_eq!(list.len(), 2); @@ -27,8 +27,8 @@ async fn transitive_emitting() { #[tokio::test] async fn transitive_emitting_indirect() { run! { - let result = my_transitive_emitting_function("".to_string(), "".to_string()); - let collectibles = my_transitive_emitting_function_collectibles("".to_string(), "".to_string()); + let result = my_transitive_emitting_function("".into(), "".into()); + let collectibles = my_transitive_emitting_function_collectibles("".into(), "".into()); let list = collectibles.strongly_consistent().await?; assert_eq!(list.len(), 2); let mut expected = ["123", "42"].into_iter().collect::>(); @@ -82,31 +82,31 @@ async fn taking_collectibles_extra_layer() { #[tokio::test] async fn taking_collectibles_parallel() { run! { - let result = my_transitive_emitting_function("".to_string(), "a".to_string()); + let result = my_transitive_emitting_function("".into(), "a".into()); result.strongly_consistent().await?; let list = result.take_collectibles::>(); assert_eq!(list.len(), 2); assert_eq!(result.await?.0, 0); - let result = my_transitive_emitting_function("".to_string(), "b".to_string()); + let result = my_transitive_emitting_function("".into(), "b".into()); result.strongly_consistent().await?; let list = result.take_collectibles::>(); assert_eq!(list.len(), 2); assert_eq!(result.await?.0, 0); - let result = my_transitive_emitting_function_with_child_scope("".to_string(), "b".to_string(), "1".to_string()); + let result = my_transitive_emitting_function_with_child_scope("".into(), "b".into(), "1".into()); result.strongly_consistent().await?; let list = result.take_collectibles::>(); assert_eq!(list.len(), 2); assert_eq!(result.await?.0, 0); - let result = my_transitive_emitting_function_with_child_scope("".to_string(), "b".to_string(), "2".to_string()); + let result = my_transitive_emitting_function_with_child_scope("".into(), "b".into(), "2".into()); result.strongly_consistent().await?; let list = result.take_collectibles::>(); assert_eq!(list.len(), 2); assert_eq!(result.await?.0, 0); - let result = my_transitive_emitting_function_with_child_scope("".to_string(), "c".to_string(), "3".to_string()); + let result = my_transitive_emitting_function_with_child_scope("".into(), "c".into(), "3".into()); result.strongly_consistent().await?; let list = result.take_collectibles::>(); assert_eq!(list.len(), 2); @@ -119,7 +119,7 @@ struct Collectibles(AutoSet>>); #[turbo_tasks::function] async fn my_collecting_function() -> Result> { - let result = my_transitive_emitting_function("".to_string(), "".to_string()); + let result = my_transitive_emitting_function("".into(), "".into()); result.take_collectibles::>(); Ok(result) } @@ -137,32 +137,29 @@ async fn my_collecting_function_indirect() -> Result> { #[turbo_tasks::function] async fn my_multi_emitting_function() -> Result> { - my_transitive_emitting_function("".to_string(), "a".to_string()).await?; - my_transitive_emitting_function("".to_string(), "b".to_string()).await?; - my_emitting_function("".to_string()).await?; + my_transitive_emitting_function("".into(), "a".into()).await?; + my_transitive_emitting_function("".into(), "b".into()).await?; + my_emitting_function("".into()).await?; Ok(Thing::cell(Thing(0))) } #[turbo_tasks::function] -async fn my_transitive_emitting_function(key: String, _key2: String) -> Result> { +async fn my_transitive_emitting_function(key: RcStr, _key2: RcStr) -> Result> { my_emitting_function(key).await?; Ok(Thing::cell(Thing(0))) } #[turbo_tasks::function] -async fn my_transitive_emitting_function_collectibles( - key: String, - key2: String, -) -> Vc { +async fn my_transitive_emitting_function_collectibles(key: RcStr, key2: RcStr) -> Vc { let result = my_transitive_emitting_function(key, key2); Vc::cell(result.peek_collectibles::>()) } #[turbo_tasks::function] async fn my_transitive_emitting_function_with_child_scope( - key: String, - key2: String, - _key3: String, + key: RcStr, + key2: RcStr, + _key3: RcStr, ) -> Result> { let thing = my_transitive_emitting_function(key, key2); thing.strongly_consistent().await?; @@ -172,7 +169,7 @@ async fn my_transitive_emitting_function_with_child_scope( } #[turbo_tasks::function] -async fn my_emitting_function(_key: String) -> Result<()> { +async fn my_emitting_function(_key: RcStr) -> Result<()> { sleep(Duration::from_millis(100)).await; emit(Vc::upcast::>(Thing::new(123))); emit(Vc::upcast::>(Thing::new(42))); @@ -191,7 +188,7 @@ impl Thing { #[turbo_tasks::value_impl] impl ValueToString for Thing { #[turbo_tasks::function] - fn to_string(&self) -> Vc { - Vc::cell(self.0.to_string()) + fn to_string(&self) -> Vc { + Vc::cell(self.0.to_string().into()) } } diff --git a/crates/turbo-tasks/src/debug/mod.rs b/crates/turbo-tasks/src/debug/mod.rs index 57721d68b3cc1..b4e8697f52a7f 100644 --- a/crates/turbo-tasks/src/debug/mod.rs +++ b/crates/turbo-tasks/src/debug/mod.rs @@ -15,7 +15,7 @@ use internal::PassthroughDebug; /// The return type of `ValueDebug::dbg`. /// -/// We don't use `Vc` directly because we don't want the +/// We don't use `Vc` directly because we don't want the /// `Debug`/`Display` representations to be escaped. #[turbo_tasks::value] pub struct ValueDebugString(String); diff --git a/crates/turbo-tasks/src/display.rs b/crates/turbo-tasks/src/display.rs index 3e975c1527329..78a8e05cb965f 100644 --- a/crates/turbo-tasks/src/display.rs +++ b/crates/turbo-tasks/src/display.rs @@ -1,8 +1,8 @@ use turbo_tasks::Vc; -use crate::{self as turbo_tasks}; +use crate::{self as turbo_tasks, RcStr}; #[turbo_tasks::value_trait] pub trait ValueToString { - fn to_string(self: Vc) -> Vc; + fn to_string(self: Vc) -> Vc; } diff --git a/crates/turbo-tasks/src/lib.rs b/crates/turbo-tasks/src/lib.rs index 93bda5364a01f..297ffeb717138 100644 --- a/crates/turbo-tasks/src/lib.rs +++ b/crates/turbo-tasks/src/lib.rs @@ -60,6 +60,7 @@ pub mod persisted_graph; pub mod primitives; mod raw_vc; mod raw_vc_set; +mod rcstr; mod read_ref; pub mod registry; pub mod small_duration; @@ -110,6 +111,8 @@ pub use vc::{ VcDefaultRead, VcRead, VcTransparentRead, VcValueTrait, VcValueType, }; +pub use crate::rcstr::RcStr; + pub type TaskIdSet = AutoSet, 2>; pub mod test_helpers { diff --git a/crates/turbo-tasks/src/primitives.rs b/crates/turbo-tasks/src/primitives.rs index b14773ecb8edd..0d433ed7e376d 100644 --- a/crates/turbo-tasks/src/primitives.rs +++ b/crates/turbo-tasks/src/primitives.rs @@ -6,37 +6,39 @@ use futures::TryFutureExt; use turbo_tasks_macros::primitive as __turbo_tasks_internal_primitive; use crate::{ - TryJoinIterExt, Vc, {self as turbo_tasks}, + RcStr, TryJoinIterExt, Vc, {self as turbo_tasks}, }; __turbo_tasks_internal_primitive!(()); __turbo_tasks_internal_primitive!(String); +__turbo_tasks_internal_primitive!(RcStr); #[turbo_tasks::function] -fn empty_string() -> Vc { - Vc::cell(String::new()) +fn empty_string() -> Vc { + Vc::cell(RcStr::default()) } -impl Vc { +impl Vc { #[deprecated(note = "use Default::default() instead")] #[inline(always)] - pub fn empty() -> Vc { + pub fn empty() -> Vc { empty_string() } } __turbo_tasks_internal_primitive!(Option); -__turbo_tasks_internal_primitive!(Vec); +__turbo_tasks_internal_primitive!(Option); +__turbo_tasks_internal_primitive!(Vec); #[turbo_tasks::function] -fn empty_string_vec() -> Vc> { +fn empty_string_vec() -> Vc> { Vc::cell(Vec::new()) } -impl Vc> { +impl Vc> { #[deprecated(note = "use Default::default() instead")] #[inline(always)] - pub fn empty() -> Vc> { + pub fn empty() -> Vc> { empty_string_vec() } } diff --git a/crates/turbo-tasks/src/rcstr.rs b/crates/turbo-tasks/src/rcstr.rs new file mode 100644 index 0000000000000..7e2c7433eb55b --- /dev/null +++ b/crates/turbo-tasks/src/rcstr.rs @@ -0,0 +1,154 @@ +use std::{ + borrow::{Borrow, Cow}, + ffi::OsStr, + fmt::{Debug, Display}, + ops::Deref, + path::{Path, PathBuf}, + sync::Arc, +}; + +use serde::{Deserialize, Serialize}; +use turbo_tasks_hash::{DeterministicHash, DeterministicHasher}; + +use crate::debug::{ValueDebugFormat, ValueDebugFormatString}; + +/// This type exists to allow swapping out the underlying string type easily. +// +// If you want to change the underlying string type to `Arc`, please ensure that you profile +// perforamnce. The current implementation offers very cheap `String -> RcStr -> String`, meaning we +// only pay for the allocation for `Arc` when we pass `format!("").into()` to a function. +#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct RcStr(Arc); + +impl RcStr { + pub fn as_str(&self) -> &str { + self.0.as_str() + } + + /// This implementation is more efficient than `.to_string()` + pub fn into_owned(self) -> String { + match Arc::try_unwrap(self.0) { + Ok(v) => v, + Err(arc) => arc.to_string(), + } + } + + pub fn map(self, f: impl FnOnce(String) -> String) -> Self { + RcStr(Arc::new(f(self.into_owned()))) + } +} + +impl DeterministicHash for RcStr { + fn deterministic_hash(&self, state: &mut H) { + state.write_usize(self.len()); + state.write_bytes(self.as_bytes()); + } +} + +impl Deref for RcStr { + type Target = str; + + fn deref(&self) -> &Self::Target { + self.0.as_str() + } +} + +impl Borrow for RcStr { + fn borrow(&self) -> &str { + self.0.as_str() + } +} + +impl From> for RcStr { + fn from(s: Arc) -> Self { + RcStr(s) + } +} + +impl From for RcStr { + fn from(s: String) -> Self { + RcStr(Arc::new(s)) + } +} + +impl From<&'_ str> for RcStr { + fn from(s: &str) -> Self { + RcStr(Arc::new(s.to_string())) + } +} + +impl From> for RcStr { + fn from(s: Cow) -> Self { + RcStr(Arc::new(s.into_owned())) + } +} + +/// Mimic `&str` +impl AsRef for RcStr { + fn as_ref(&self) -> &Path { + (*self.0).as_ref() + } +} + +/// Mimic `&str` +impl AsRef for RcStr { + fn as_ref(&self) -> &OsStr { + (*self.0).as_ref() + } +} + +/// Mimic `&str` +impl AsRef<[u8]> for RcStr { + fn as_ref(&self) -> &[u8] { + (*self.0).as_ref() + } +} + +impl PartialEq for RcStr { + fn eq(&self, other: &str) -> bool { + self.0.as_str() == other + } +} + +impl PartialEq<&'_ str> for RcStr { + fn eq(&self, other: &&str) -> bool { + self.0.as_str() == *other + } +} + +impl PartialEq for RcStr { + fn eq(&self, other: &String) -> bool { + self.as_str() == other.as_str() + } +} + +impl Debug for RcStr { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + Debug::fmt(&self.0, f) + } +} + +impl Display for RcStr { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + Display::fmt(&self.0, f) + } +} + +impl From for String { + fn from(s: RcStr) -> Self { + s.into_owned() + } +} + +impl From for PathBuf { + fn from(s: RcStr) -> Self { + String::from(s).into() + } +} + +impl ValueDebugFormat for RcStr { + fn value_debug_format(&self, _: usize) -> ValueDebugFormatString { + ValueDebugFormatString::Sync(self.to_string()) + } +} diff --git a/crates/turbo-tasks/src/task/concrete_task_input.rs b/crates/turbo-tasks/src/task/concrete_task_input.rs index c591d652bc658..c583856e4845c 100644 --- a/crates/turbo-tasks/src/task/concrete_task_input.rs +++ b/crates/turbo-tasks/src/task/concrete_task_input.rs @@ -16,7 +16,7 @@ use crate::{ id::{FunctionId, TraitTypeId}, magic_any::MagicAny, manager::{read_task_cell, read_task_output}, - registry, turbo_tasks, CellId, RawVc, TaskId, TraitType, ValueTypeId, + registry, turbo_tasks, CellId, RawVc, RcStr, TaskId, TraitType, ValueTypeId, }; #[derive(Clone)] @@ -330,7 +330,7 @@ pub enum ConcreteTaskInput { TaskOutput(TaskId), TaskCell(TaskId, CellId), List(Vec), - String(String), + String(RcStr), Bool(bool), Usize(usize), I8(i8), diff --git a/crates/turbo-tasks/src/task/function.rs b/crates/turbo-tasks/src/task/function.rs index b5cf7f1e06ce4..58bd10fb1f225 100644 --- a/crates/turbo-tasks/src/task/function.rs +++ b/crates/turbo-tasks/src/task/function.rs @@ -345,7 +345,7 @@ fn next_arg<'a>( #[cfg(test)] mod tests { use super::*; - use crate::{VcCellNewMode, VcDefaultRead}; + use crate::{RcStr, VcCellNewMode, VcDefaultRead}; #[test] fn test_task_fn() { @@ -369,18 +369,15 @@ mod tests { todo!() } - fn with_recv_and_str(_a: &i32, _s: String) -> crate::Vc { + fn with_recv_and_str(_a: &i32, _s: RcStr) -> crate::Vc { todo!() } - async fn async_with_recv_and_str(_a: &i32, _s: String) -> crate::Vc { + async fn async_with_recv_and_str(_a: &i32, _s: RcStr) -> crate::Vc { todo!() } - async fn async_with_recv_and_str_and_result( - _a: &i32, - _s: String, - ) -> Result> { + async fn async_with_recv_and_str_and_result(_a: &i32, _s: RcStr) -> Result> { todo!() } diff --git a/crates/turbo-tasks/src/task/task_input.rs b/crates/turbo-tasks/src/task/task_input.rs index 9d1e2ffc40ea3..855a2d309acf0 100644 --- a/crates/turbo-tasks/src/task/task_input.rs +++ b/crates/turbo-tasks/src/task/task_input.rs @@ -8,7 +8,7 @@ use anyhow::{anyhow, bail, Result}; use super::concrete_task_input::TransientSharedValue; use crate::{ - magic_any::MagicAny, ConcreteTaskInput, RawVc, SharedValue, TaskId, TransientInstance, + magic_any::MagicAny, ConcreteTaskInput, RawVc, RcStr, SharedValue, TaskId, TransientInstance, TransientValue, TypedForInput, Value, ValueTypeId, Vc, VcValueType, }; @@ -31,7 +31,7 @@ impl TaskInput for ConcreteTaskInput { } } -impl TaskInput for String { +impl TaskInput for RcStr { fn try_from_concrete(input: &ConcreteTaskInput) -> Result { match input { ConcreteTaskInput::String(s) => Ok(s.clone()), @@ -406,7 +406,7 @@ mod tests { #[test] fn test_multiple_unnamed_fields() -> Result<()> { #[derive(Clone, TaskInput, Eq, PartialEq, Debug)] - struct MultipleUnnamedFields(u32, String); + struct MultipleUnnamedFields(u32, RcStr); test_conversion!(MultipleUnnamedFields(42, "42".into())); Ok(()) @@ -428,7 +428,7 @@ mod tests { #[derive(Clone, TaskInput, Eq, PartialEq, Debug)] struct MultipleNamedFields { named: u32, - other: String, + other: RcStr, } test_conversion!(MultipleNamedFields { @@ -444,7 +444,7 @@ mod tests { struct GenericField(T); test_conversion!(GenericField(42)); - test_conversion!(GenericField("42".to_string())); + test_conversion!(GenericField(RcStr::from("42"))); Ok(()) } @@ -485,8 +485,8 @@ mod tests { Variant1, Variant2(u32), Variant3 { named: u32 }, - Variant4(u32, String), - Variant5 { named: u32, other: String }, + Variant4(u32, RcStr), + Variant5 { named: u32, other: RcStr }, } #[test] @@ -505,8 +505,8 @@ mod tests { Variant1, Variant2(MultipleVariantsAndHeterogeneousFields), Variant3 { named: OneVariant }, - Variant4(OneVariant, String), - Variant5 { named: OneVariant, other: String }, + Variant4(OneVariant, RcStr), + Variant5 { named: OneVariant, other: RcStr }, } test_conversion!(NestedVariants::Variant5 { diff --git a/crates/turbo-tasks/src/trace.rs b/crates/turbo-tasks/src/trace.rs index da7000c8501cd..17fa1c185a8a1 100644 --- a/crates/turbo-tasks/src/trace.rs +++ b/crates/turbo-tasks/src/trace.rs @@ -9,7 +9,7 @@ use std::{ use auto_hash_map::{AutoMap, AutoSet}; use indexmap::{IndexMap, IndexSet}; -use crate::RawVc; +use crate::{RawVc, RcStr}; pub struct TraceRawVcsContext { list: Vec, @@ -70,7 +70,7 @@ ignore!( AtomicBool, AtomicUsize ); -ignore!((), String, Duration, anyhow::Error); +ignore!((), String, Duration, anyhow::Error, RcStr); ignore!(Path, PathBuf); ignore!(serde_json::Value); diff --git a/crates/turbopack-browser/src/chunking_context.rs b/crates/turbopack-browser/src/chunking_context.rs index 1827006f21e45..72150f93fb7fe 100644 --- a/crates/turbopack-browser/src/chunking_context.rs +++ b/crates/turbopack-browser/src/chunking_context.rs @@ -1,6 +1,6 @@ use anyhow::{bail, Context, Result}; use tracing::Instrument; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbo_tasks_fs::FileSystemPath; use turbopack_core::{ chunk::{ @@ -32,7 +32,7 @@ pub struct BrowserChunkingContextBuilder { } impl BrowserChunkingContextBuilder { - pub fn name(mut self, name: String) -> Self { + pub fn name(mut self, name: RcStr) -> Self { self.chunking_context.name = Some(name); self } @@ -42,12 +42,12 @@ impl BrowserChunkingContextBuilder { self } - pub fn asset_base_path(mut self, asset_base_path: Vc>) -> Self { + pub fn asset_base_path(mut self, asset_base_path: Vc>) -> Self { self.chunking_context.asset_base_path = asset_base_path; self } - pub fn chunk_base_path(mut self, chunk_base_path: Vc>) -> Self { + pub fn chunk_base_path(mut self, chunk_base_path: Vc>) -> Self { self.chunking_context.chunk_base_path = chunk_base_path; self } @@ -90,7 +90,7 @@ impl BrowserChunkingContextBuilder { #[turbo_tasks::value(serialization = "auto_for_input")] #[derive(Debug, Clone, Hash, PartialOrd, Ord)] pub struct BrowserChunkingContext { - name: Option, + name: Option, /// This path get stripped off of chunk paths before generating output asset /// paths. context_path: Vc, @@ -108,10 +108,10 @@ pub struct BrowserChunkingContext { asset_root_path: Vc, /// Base path that will be prepended to all chunk URLs when loading them. /// This path will not appear in chunk paths or chunk data. - chunk_base_path: Vc>, + chunk_base_path: Vc>, /// URL prefix that will be prepended to all static asset URLs when loading /// them. - asset_base_path: Vc>, + asset_base_path: Vc>, /// Enable HMR for this chunking enable_hot_module_replacement: bool, /// The environment chunks will be evaluated in. @@ -166,7 +166,7 @@ impl BrowserChunkingContext { } /// Returns the asset base path. - pub fn chunk_base_path(&self) -> Vc> { + pub fn chunk_base_path(&self) -> Vc> { self.chunk_base_path } @@ -239,11 +239,11 @@ impl BrowserChunkingContext { #[turbo_tasks::value_impl] impl ChunkingContext for BrowserChunkingContext { #[turbo_tasks::function] - fn name(&self) -> Vc { + fn name(&self) -> Vc { if let Some(name) = &self.name { Vc::cell(name.clone()) } else { - Vc::cell("unknown".to_string()) + Vc::cell("unknown".into()) } } @@ -266,7 +266,7 @@ impl ChunkingContext for BrowserChunkingContext { async fn chunk_path( &self, ident: Vc, - extension: String, + extension: RcStr, ) -> Result> { let root_path = self.chunk_root_path; let name = ident.output_name(self.context_path, extension).await?; @@ -274,22 +274,25 @@ impl ChunkingContext for BrowserChunkingContext { } #[turbo_tasks::function] - async fn asset_url(self: Vc, ident: Vc) -> Result> { + async fn asset_url(self: Vc, ident: Vc) -> Result> { let this = self.await?; let asset_path = ident.path().await?.to_string(); let asset_path = asset_path .strip_prefix(&format!("{}/", this.client_root.await?.path)) .context("expected asset_path to contain client_root")?; - Ok(Vc::cell(format!( - "{}{}", - this.asset_base_path - .await? - .as_ref() - .map(|s| s.as_str()) - .unwrap_or("/"), - asset_path - ))) + Ok(Vc::cell( + format!( + "{}{}", + this.asset_base_path + .await? + .as_ref() + .map(|s| s.as_str()) + .unwrap_or("/"), + asset_path + ) + .into(), + )) } #[turbo_tasks::function] @@ -313,7 +316,7 @@ impl ChunkingContext for BrowserChunkingContext { #[turbo_tasks::function] async fn asset_path( &self, - content_hash: String, + content_hash: RcStr, original_asset_ident: Vc, ) -> Result> { let source_path = original_asset_ident.path().await?; @@ -329,7 +332,7 @@ impl ChunkingContext for BrowserChunkingContext { content_hash = &content_hash[..8] ), }; - Ok(self.asset_root_path.join(asset_path)) + Ok(self.asset_root_path.join(asset_path.into())) } #[turbo_tasks::function] @@ -343,7 +346,10 @@ impl ChunkingContext for BrowserChunkingContext { module: Vc>, availability_info: Value, ) -> Result> { - let span = tracing::info_span!("chunking", module = *module.ident().to_string().await?); + let span = tracing::info_span!( + "chunking", + module = module.ident().to_string().await?.to_string() + ); async move { let this = self.await?; let input_availability_info = availability_info.into_value(); @@ -367,13 +373,13 @@ impl ChunkingContext for BrowserChunkingContext { match input_availability_info { AvailabilityInfo::Root => {} AvailabilityInfo::Untracked => { - ident = ident.with_modifier(Vc::cell("untracked".to_string())); + ident = ident.with_modifier(Vc::cell("untracked".into())); } AvailabilityInfo::Complete { available_chunk_items, } => { ident = ident.with_modifier(Vc::cell( - available_chunk_items.hash().await?.to_string(), + available_chunk_items.hash().await?.to_string().into(), )); } } @@ -408,8 +414,8 @@ impl ChunkingContext for BrowserChunkingContext { availability_info: Value, ) -> Result> { let span = { - let ident = ident.to_string().await?; - tracing::info_span!("chunking", chunking_type = "evaluated", ident = *ident) + let ident = ident.to_string().await?.to_string(); + tracing::info_span!("chunking", chunking_type = "evaluated", ident = ident) }; async move { let this = self.await?; diff --git a/crates/turbopack-browser/src/ecmascript/chunk.rs b/crates/turbopack-browser/src/ecmascript/chunk.rs index 7a1007d4600a4..7e6c651b8cbd7 100644 --- a/crates/turbopack-browser/src/ecmascript/chunk.rs +++ b/crates/turbopack-browser/src/ecmascript/chunk.rs @@ -1,6 +1,6 @@ use anyhow::Result; use indexmap::IndexSet; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbopack_core::{ asset::{Asset, AssetContent}, chunk::{Chunk, ChunkingContext, OutputChunk, OutputChunkRuntimeInfo}, @@ -40,8 +40,8 @@ impl EcmascriptDevChunk { #[turbo_tasks::value_impl] impl ValueToString for EcmascriptDevChunk { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell("Ecmascript Dev Chunk".to_string())) + async fn to_string(&self) -> Result> { + Ok(Vc::cell("Ecmascript Dev Chunk".into())) } } @@ -58,8 +58,8 @@ impl OutputChunk for EcmascriptDevChunk { } #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("ecmascript dev chunk".to_string()) +fn modifier() -> Vc { + Vc::cell("ecmascript dev chunk".into()) } #[turbo_tasks::value_impl] @@ -80,7 +80,7 @@ impl OutputAsset for EcmascriptDevChunk { #[turbo_tasks::function] fn ident(&self) -> Vc { let ident = self.chunk.ident().with_modifier(modifier()); - AssetIdent::from_path(self.chunking_context.chunk_path(ident, ".js".to_string())) + AssetIdent::from_path(self.chunking_context.chunk_path(ident, ".js".into())) } #[turbo_tasks::function] @@ -125,35 +125,35 @@ impl GenerateSourceMap for EcmascriptDevChunk { } #[turbo_tasks::function] - fn by_section(self: Vc, section: String) -> Vc { + fn by_section(self: Vc, section: RcStr) -> Vc { self.own_content().by_section(section) } } #[turbo_tasks::function] -fn introspectable_type() -> Vc { - Vc::cell("dev ecmascript chunk".to_string()) +fn introspectable_type() -> Vc { + Vc::cell("dev ecmascript chunk".into()) } #[turbo_tasks::function] -fn introspectable_details() -> Vc { - Vc::cell("generates a development ecmascript chunk".to_string()) +fn introspectable_details() -> Vc { + Vc::cell("generates a development ecmascript chunk".into()) } #[turbo_tasks::value_impl] impl Introspectable for EcmascriptDevChunk { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { introspectable_type() } #[turbo_tasks::function] - fn title(self: Vc) -> Vc { + fn title(self: Vc) -> Vc { self.ident().to_string() } #[turbo_tasks::function] - fn details(&self) -> Vc { + fn details(&self) -> Vc { introspectable_details() } @@ -163,7 +163,7 @@ impl Introspectable for EcmascriptDevChunk { let chunk = Vc::upcast::>(self.chunk) .resolve() .await?; - children.insert((Vc::cell("chunk".to_string()), chunk)); + children.insert((Vc::cell("chunk".into()), chunk)); Ok(Vc::cell(children)) } } diff --git a/crates/turbopack-browser/src/ecmascript/content.rs b/crates/turbopack-browser/src/ecmascript/content.rs index b3273c608a3b0..f74dad4f42fe4 100644 --- a/crates/turbopack-browser/src/ecmascript/content.rs +++ b/crates/turbopack-browser/src/ecmascript/content.rs @@ -2,7 +2,7 @@ use std::io::Write; use anyhow::{bail, Result}; use indoc::writedoc; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::File; use turbopack_core::{ asset::AssetContent, @@ -159,7 +159,7 @@ impl GenerateSourceMap for EcmascriptDevChunkContent { } #[turbo_tasks::function] - async fn by_section(&self, section: String) -> Result> { + async fn by_section(&self, section: RcStr) -> Result> { // Weirdly, the ContentSource will have already URL decoded the ModuleId, and we // can't reparse that via serde. if let Ok(id) = ModuleId::parse(§ion) { diff --git a/crates/turbopack-browser/src/ecmascript/content_entry.rs b/crates/turbopack-browser/src/ecmascript/content_entry.rs index 6221f0263c2d5..2aa8bd4ac61a1 100644 --- a/crates/turbopack-browser/src/ecmascript/content_entry.rs +++ b/crates/turbopack-browser/src/ecmascript/content_entry.rs @@ -103,9 +103,9 @@ async fn item_code( CodeGenerationIssue { severity: IssueSeverity::Error.cell(), path: item.asset_ident().path(), - title: StyledString::Text("Code generation for chunk item errored".to_string()) + title: StyledString::Text("Code generation for chunk item errored".into()) .cell(), - message: StyledString::Text(error_message).cell(), + message: StyledString::Text(error_message.into()).cell(), } .cell() .emit(); diff --git a/crates/turbopack-browser/src/ecmascript/evaluate/chunk.rs b/crates/turbopack-browser/src/ecmascript/evaluate/chunk.rs index 46372b4f8b201..57b5bc6390f8a 100644 --- a/crates/turbopack-browser/src/ecmascript/evaluate/chunk.rs +++ b/crates/turbopack-browser/src/ecmascript/evaluate/chunk.rs @@ -3,7 +3,7 @@ use std::io::Write; use anyhow::{bail, Result}; use indoc::writedoc; use serde::Serialize; -use turbo_tasks::{ReadRef, TryJoinIterExt, Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, ReadRef, TryJoinIterExt, Value, ValueToString, Vc}; use turbo_tasks_fs::File; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -147,7 +147,7 @@ impl EcmascriptDevEvaluateChunk { let runtime_code = turbopack_ecmascript_runtime::get_browser_runtime_code( environment, chunking_context.chunk_base_path(), - Vc::cell(output_root.to_string()), + Vc::cell(output_root.to_string().into()), ); code.push_code(&*runtime_code.await?); } @@ -155,7 +155,7 @@ impl EcmascriptDevEvaluateChunk { let runtime_code = turbopack_ecmascript_runtime::get_browser_runtime_code( environment, chunking_context.chunk_base_path(), - Vc::cell(output_root.to_string()), + Vc::cell(output_root.to_string().into()), ); code.push_code(&*runtime_code.await?); } @@ -190,14 +190,14 @@ impl EcmascriptDevEvaluateChunk { #[turbo_tasks::value_impl] impl ValueToString for EcmascriptDevEvaluateChunk { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell("Ecmascript Dev Evaluate Chunk".to_string())) + async fn to_string(&self) -> Result> { + Ok(Vc::cell("Ecmascript Dev Evaluate Chunk".into())) } } #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("ecmascript dev evaluate chunk".to_string()) +fn modifier() -> Vc { + Vc::cell("ecmascript dev evaluate chunk".into()) } #[turbo_tasks::value_impl] @@ -221,7 +221,7 @@ impl OutputAsset for EcmascriptDevEvaluateChunk { let ident = AssetIdent::new(Value::new(ident)); Ok(AssetIdent::from_path( - self.chunking_context.chunk_path(ident, ".js".to_string()), + self.chunking_context.chunk_path(ident, ".js".into()), )) } diff --git a/crates/turbopack-browser/src/ecmascript/list/asset.rs b/crates/turbopack-browser/src/ecmascript/list/asset.rs index cae5cb3eee07e..88deb66bf9055 100644 --- a/crates/turbopack-browser/src/ecmascript/list/asset.rs +++ b/crates/turbopack-browser/src/ecmascript/list/asset.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbopack_core::{ asset::{Asset, AssetContent}, chunk::{ChunkingContext, EvaluatableAssets}, @@ -62,29 +62,29 @@ impl EcmascriptDevChunkList { #[turbo_tasks::value_impl] impl ValueToString for EcmascriptDevChunkList { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell("Ecmascript Dev Chunk List".to_string())) + async fn to_string(&self) -> Result> { + Ok(Vc::cell("Ecmascript Dev Chunk List".into())) } } #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("ecmascript dev chunk list".to_string()) +fn modifier() -> Vc { + Vc::cell("ecmascript dev chunk list".into()) } #[turbo_tasks::function] -fn dynamic_modifier() -> Vc { - Vc::cell("dynamic".to_string()) +fn dynamic_modifier() -> Vc { + Vc::cell("dynamic".into()) } #[turbo_tasks::function] -fn chunk_list_chunk_reference_description() -> Vc { - Vc::cell("chunk list chunk".to_string()) +fn chunk_list_chunk_reference_description() -> Vc { + Vc::cell("chunk list chunk".into()) } #[turbo_tasks::function] -fn chunk_key() -> Vc { - Vc::cell("chunk".to_string()) +fn chunk_key() -> Vc { + Vc::cell("chunk".into()) } #[turbo_tasks::value_impl] @@ -93,7 +93,7 @@ impl OutputAsset for EcmascriptDevChunkList { async fn ident(&self) -> Result> { let mut ident = self.ident.await?.clone_value(); for &evaluatable_asset in self.evaluatable_assets.await?.iter() { - ident.add_asset(Vc::::default(), evaluatable_asset.ident()); + ident.add_asset(Vc::::default(), evaluatable_asset.ident()); } ident.add_modifier(modifier()); @@ -111,7 +111,7 @@ impl OutputAsset for EcmascriptDevChunkList { let ident = AssetIdent::new(Value::new(ident)); Ok(AssetIdent::from_path( - self.chunking_context.chunk_path(ident, ".js".to_string()), + self.chunking_context.chunk_path(ident, ".js".into()), )) } diff --git a/crates/turbopack-browser/src/ecmascript/list/version.rs b/crates/turbopack-browser/src/ecmascript/list/version.rs index d13458fad92a7..7dd142e36609c 100644 --- a/crates/turbopack-browser/src/ecmascript/list/version.rs +++ b/crates/turbopack-browser/src/ecmascript/list/version.rs @@ -1,6 +1,6 @@ use anyhow::Result; use indexmap::IndexMap; -use turbo_tasks::{TraitRef, TryJoinIterExt, Vc}; +use turbo_tasks::{RcStr, TraitRef, TryJoinIterExt, Vc}; use turbo_tasks_hash::{encode_hex, Xxh3Hash64Hasher}; use turbopack_core::version::{Version, VersionedContentMerger}; @@ -22,7 +22,7 @@ pub(super) struct EcmascriptDevChunkListVersion { #[turbo_tasks::value_impl] impl Version for EcmascriptDevChunkListVersion { #[turbo_tasks::function] - async fn id(&self) -> Result> { + async fn id(&self) -> Result> { let by_path = { let mut by_path = self .by_path @@ -60,6 +60,6 @@ impl Version for EcmascriptDevChunkListVersion { } let hash = hasher.finish(); let hex_hash = encode_hex(hash); - Ok(Vc::cell(hex_hash)) + Ok(Vc::cell(hex_hash.into())) } } diff --git a/crates/turbopack-browser/src/ecmascript/merged/version.rs b/crates/turbopack-browser/src/ecmascript/merged/version.rs index a20bfc27e0d3f..dd55cf5216b0f 100644 --- a/crates/turbopack-browser/src/ecmascript/merged/version.rs +++ b/crates/turbopack-browser/src/ecmascript/merged/version.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{ReadRef, TryJoinIterExt, Vc}; +use turbo_tasks::{RcStr, ReadRef, TryJoinIterExt, Vc}; use turbo_tasks_hash::{encode_hex, Xxh3Hash64Hasher}; use turbopack_core::version::Version; @@ -16,7 +16,7 @@ pub(super) struct EcmascriptDevMergedChunkVersion { #[turbo_tasks::value_impl] impl Version for EcmascriptDevMergedChunkVersion { #[turbo_tasks::function] - async fn id(&self) -> Result> { + async fn id(&self) -> Result> { let mut hasher = Xxh3Hash64Hasher::new(); hasher.write_value(self.versions.len()); let sorted_ids = { @@ -34,6 +34,6 @@ impl Version for EcmascriptDevMergedChunkVersion { } let hash = hasher.finish(); let hex_hash = encode_hex(hash); - Ok(Vc::cell(hex_hash)) + Ok(Vc::cell(hex_hash.into())) } } diff --git a/crates/turbopack-browser/src/ecmascript/runtime.rs b/crates/turbopack-browser/src/ecmascript/runtime.rs index c306b2cc043a7..68b103bed10c9 100644 --- a/crates/turbopack-browser/src/ecmascript/runtime.rs +++ b/crates/turbopack-browser/src/ecmascript/runtime.rs @@ -6,8 +6,8 @@ use turbopack_core::{ ident::AssetIdent, }; use turbopack_ecmascript::chunk::{ - EcmascriptChunk, EcmascriptChunkPlaceables, EcmascriptChunkRuntime, - EcmascriptChunkRuntimeContent, ChunkingContext, + ChunkingContext, EcmascriptChunk, EcmascriptChunkPlaceables, EcmascriptChunkRuntime, + EcmascriptChunkRuntimeContent, }; use crate::ecmascript::content::EcmascriptDevChunkContent; @@ -46,13 +46,13 @@ impl EcmascriptDevChunkRuntime { #[turbo_tasks::value_impl] impl ValueToString for EcmascriptDevChunkRuntime { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { + async fn to_string(&self) -> Result> { Ok(Vc::cell("Ecmascript Dev Runtime".to_string())) } } #[turbo_tasks::function] -fn modifier() -> Vc { +fn modifier() -> Vc { Vc::cell("ecmascript dev chunk".to_string()) } diff --git a/crates/turbopack-browser/src/ecmascript/version.rs b/crates/turbopack-browser/src/ecmascript/version.rs index f6ec41f44e6ad..a666b3f11bca4 100644 --- a/crates/turbopack-browser/src/ecmascript/version.rs +++ b/crates/turbopack-browser/src/ecmascript/version.rs @@ -1,6 +1,6 @@ use anyhow::{bail, Result}; use indexmap::IndexMap; -use turbo_tasks::{ReadRef, Vc}; +use turbo_tasks::{RcStr, ReadRef, Vc}; use turbo_tasks_fs::FileSystemPath; use turbo_tasks_hash::{encode_hex, Xxh3Hash64Hasher}; use turbopack_core::{chunk::ModuleId, version::Version}; @@ -48,7 +48,7 @@ impl EcmascriptDevChunkVersion { #[turbo_tasks::value_impl] impl Version for EcmascriptDevChunkVersion { #[turbo_tasks::function] - fn id(&self) -> Vc { + fn id(&self) -> Vc { let mut hasher = Xxh3Hash64Hasher::new(); hasher.write_ref(&self.chunk_path); let sorted_hashes = { @@ -61,6 +61,6 @@ impl Version for EcmascriptDevChunkVersion { } let hash = hasher.finish(); let hex_hash = encode_hex(hash); - Vc::cell(hex_hash) + Vc::cell(hex_hash.into()) } } diff --git a/crates/turbopack-browser/src/react_refresh.rs b/crates/turbopack-browser/src/react_refresh.rs index 54e2a64e4e9b0..359a7703fc7fe 100644 --- a/crates/turbopack-browser/src/react_refresh.rs +++ b/crates/turbopack-browser/src/react_refresh.rs @@ -12,12 +12,12 @@ use turbopack_resolve::{ #[turbo_tasks::function] fn react_refresh_request() -> Vc { - Request::parse_string("@next/react-refresh-utils/dist/runtime".to_string()) + Request::parse_string("@next/react-refresh-utils/dist/runtime".into()) } #[turbo_tasks::function] fn react_refresh_request_in_next() -> Vc { - Request::parse_string("next/dist/compiled/@next/react-refresh-utils/dist/runtime".to_string()) + Request::parse_string("next/dist/compiled/@next/react-refresh-utils/dist/runtime".into()) } #[turbo_tasks::value] @@ -84,7 +84,7 @@ impl Issue for ReactRefreshResolvingIssue { #[turbo_tasks::function] fn title(&self) -> Vc { - StyledString::Text("Could not resolve React Refresh runtime".to_string()).cell() + StyledString::Text("Could not resolve React Refresh runtime".into()).cell() } #[turbo_tasks::function] @@ -102,13 +102,12 @@ impl Issue for ReactRefreshResolvingIssue { Vc::cell(Some( StyledString::Line(vec![ StyledString::Text( - "React Refresh will be disabled.\nTo enable React Refresh, install the " - .to_string(), + "React Refresh will be disabled.\nTo enable React Refresh, install the ".into(), ), - StyledString::Code("react-refresh".to_string()), - StyledString::Text(" and ".to_string()), - StyledString::Code("@next/react-refresh-utils".to_string()), - StyledString::Text(" modules.".to_string()), + StyledString::Code("react-refresh".into()), + StyledString::Text(" and ".into()), + StyledString::Code("@next/react-refresh-utils".into()), + StyledString::Text(" modules.".into()), ]) .cell(), )) diff --git a/crates/turbopack-cli/src/build/mod.rs b/crates/turbopack-cli/src/build/mod.rs index ff5ee97fa7bd5..be5fec651583c 100644 --- a/crates/turbopack-cli/src/build/mod.rs +++ b/crates/turbopack-cli/src/build/mod.rs @@ -6,7 +6,7 @@ use std::{ }; use anyhow::{bail, Context, Result}; -use turbo_tasks::{TransientInstance, TryJoinIterExt, TurboTasks, Value, Vc}; +use turbo_tasks::{RcStr, TransientInstance, TryJoinIterExt, TurboTasks, Value, Vc}; use turbo_tasks_fs::FileSystem; use turbo_tasks_memory::MemoryBackend; use turbopack::ecmascript::EcmascriptModuleAsset; @@ -49,10 +49,10 @@ pub fn register() { pub struct TurbopackBuildBuilder { turbo_tasks: Arc>, - project_dir: String, - root_dir: String, + project_dir: RcStr, + root_dir: RcStr, entry_requests: Vec, - browserslist_query: String, + browserslist_query: RcStr, log_level: IssueSeverity, show_all: bool, log_detail: bool, @@ -62,15 +62,15 @@ pub struct TurbopackBuildBuilder { impl TurbopackBuildBuilder { pub fn new( turbo_tasks: Arc>, - project_dir: String, - root_dir: String, + project_dir: RcStr, + root_dir: RcStr, ) -> Self { TurbopackBuildBuilder { turbo_tasks, project_dir, root_dir, entry_requests: vec![], - browserslist_query: "chrome 64, edge 79, firefox 67, opera 51, safari 12".to_owned(), + browserslist_query: "chrome 64, edge 79, firefox 67, opera 51, safari 12".into(), log_level: IssueSeverity::Warning, show_all: false, log_detail: false, @@ -83,7 +83,7 @@ impl TurbopackBuildBuilder { self } - pub fn browserslist_query(mut self, browserslist_query: String) -> Self { + pub fn browserslist_query(mut self, browserslist_query: RcStr) -> Self { self.browserslist_query = browserslist_query; self } @@ -157,10 +157,10 @@ impl TurbopackBuildBuilder { #[turbo_tasks::function] async fn build_internal( - project_dir: String, - root_dir: String, + project_dir: RcStr, + root_dir: RcStr, entry_requests: Vc, - browserslist_query: String, + browserslist_query: RcStr, minify_type: MinifyType, ) -> Result> { let env = Environment::new(Value::new(ExecutionEnvironment::Browser( @@ -174,13 +174,14 @@ async fn build_internal( ))); let output_fs = output_fs(project_dir.clone()); let project_fs = project_fs(root_dir.clone()); - let project_relative = project_dir.strip_prefix(&root_dir).unwrap(); - let project_relative = project_relative + let project_relative = project_dir.strip_prefix(&*root_dir).unwrap(); + let project_relative: RcStr = project_relative .strip_prefix(MAIN_SEPARATOR) .unwrap_or(project_relative) - .replace(MAIN_SEPARATOR, "/"); + .replace(MAIN_SEPARATOR, "/") + .into(); let project_path = project_fs.root().join(project_relative); - let build_output_root = output_fs.root().join("dist".to_string()); + let build_output_root = output_fs.root().join("dist".into()); let node_env = NodeEnv::Production.cell(); @@ -231,7 +232,7 @@ async fn build_internal( .await?) .to_vec(); - let origin = PlainResolveOrigin::new(asset_context, output_fs.root().join("_".to_string())); + let origin = PlainResolveOrigin::new(asset_context, output_fs.root().join("_".into())); let project_dir = &project_dir; let entries = entry_requests .into_iter() @@ -274,9 +275,9 @@ async fn build_internal( .await? .as_deref() .unwrap() - .to_string(), + .into(), ) - .with_extension("entry.js".to_string()), + .with_extension("entry.js".into()), Vc::upcast(ecmascript), EvaluatableAssets::one(Vc::upcast(ecmascript)), Value::new(AvailabilityInfo::Root), diff --git a/crates/turbopack-cli/src/contexts.rs b/crates/turbopack-cli/src/contexts.rs index 8b20656471dbb..9b439048978e7 100644 --- a/crates/turbopack-cli/src/contexts.rs +++ b/crates/turbopack-cli/src/contexts.rs @@ -1,7 +1,7 @@ use std::{collections::HashMap, fmt}; use anyhow::Result; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::{RcStr, Value, Vc}; use turbo_tasks_fs::{FileSystem, FileSystemPath}; use turbopack::{ ecmascript::{EcmascriptInputTransform, TreeShakingMode}, @@ -61,7 +61,7 @@ pub async fn get_client_import_map(project_path: Vc) -> Result Vc { #[turbo_tasks::function] pub async fn get_client_compile_time_info( - browserslist_query: String, + browserslist_query: RcStr, node_env: Vc, ) -> Result> { Ok( diff --git a/crates/turbopack-cli/src/dev/mod.rs b/crates/turbopack-cli/src/dev/mod.rs index 17695ec11651f..73d09c0811992 100644 --- a/crates/turbopack-cli/src/dev/mod.rs +++ b/crates/turbopack-cli/src/dev/mod.rs @@ -13,7 +13,7 @@ use anyhow::{Context, Result}; use owo_colors::OwoColorize; use turbo_tasks::{ util::{FormatBytes, FormatDuration}, - TransientInstance, TurboTasks, UpdateInfo, Value, Vc, + RcStr, TransientInstance, TurboTasks, UpdateInfo, Value, Vc, }; use turbo_tasks_fs::FileSystem; use turbo_tasks_malloc::TurboMalloc; @@ -51,14 +51,14 @@ pub(crate) mod web_entry_source; pub struct TurbopackDevServerBuilder { turbo_tasks: Arc>, - project_dir: String, - root_dir: String, + project_dir: RcStr, + root_dir: RcStr, entry_requests: Vec, eager_compile: bool, hostname: Option, issue_reporter: Option>, port: Option, - browserslist_query: String, + browserslist_query: RcStr, log_level: IssueSeverity, show_all: bool, log_detail: bool, @@ -68,8 +68,8 @@ pub struct TurbopackDevServerBuilder { impl TurbopackDevServerBuilder { pub fn new( turbo_tasks: Arc>, - project_dir: String, - root_dir: String, + project_dir: RcStr, + root_dir: RcStr, ) -> TurbopackDevServerBuilder { TurbopackDevServerBuilder { turbo_tasks, @@ -82,7 +82,7 @@ impl TurbopackDevServerBuilder { port: None, browserslist_query: "last 1 Chrome versions, last 1 Firefox versions, last 1 Safari \ versions, last 1 Edge versions" - .to_owned(), + .into(), log_level: IssueSeverity::Warning, show_all: false, log_detail: false, @@ -110,7 +110,7 @@ impl TurbopackDevServerBuilder { self } - pub fn browserslist_query(mut self, browserslist_query: String) -> TurbopackDevServerBuilder { + pub fn browserslist_query(mut self, browserslist_query: RcStr) -> TurbopackDevServerBuilder { self.browserslist_query = browserslist_query; self } @@ -190,12 +190,12 @@ impl TurbopackDevServerBuilder { let server = self.find_port(host, port, 10)?; let turbo_tasks = self.turbo_tasks; - let project_dir = self.project_dir; - let root_dir = self.root_dir; + let project_dir: RcStr = self.project_dir; + let root_dir: RcStr = self.root_dir; let eager_compile = self.eager_compile; let show_all = self.show_all; - let log_detail = self.log_detail; - let browserslist_query = self.browserslist_query; + let log_detail: bool = self.log_detail; + let browserslist_query: RcStr = self.browserslist_query; let log_args = Arc::new(LogOptions { current_dir: current_dir().unwrap(), project_dir: PathBuf::from(project_dir.clone()), @@ -227,31 +227,32 @@ impl TurbopackDevServerBuilder { #[turbo_tasks::function] async fn source( - root_dir: String, - project_dir: String, + root_dir: RcStr, + project_dir: RcStr, entry_requests: TransientInstance>, eager_compile: bool, - browserslist_query: String, + browserslist_query: RcStr, ) -> Result>> { - let project_relative = project_dir.strip_prefix(&root_dir).unwrap(); - let project_relative = project_relative + let project_relative = project_dir.strip_prefix(&*root_dir).unwrap(); + let project_relative: RcStr = project_relative .strip_prefix(MAIN_SEPARATOR) .unwrap_or(project_relative) - .replace(MAIN_SEPARATOR, "/"); + .replace(MAIN_SEPARATOR, "/") + .into(); let output_fs = output_fs(project_dir); let fs = project_fs(root_dir); let project_path: Vc = fs.root().join(project_relative); let env = load_env(project_path); - let build_output_root = output_fs.root().join(".turbopack/build".to_string()); + let build_output_root = output_fs.root().join(".turbopack/build".into()); let build_chunking_context = BrowserChunkingContext::builder( project_path, build_output_root, build_output_root, - build_output_root.join("chunks".to_string()), - build_output_root.join("assets".to_string()), + build_output_root.join("chunks".into()), + build_output_root.join("assets".into()), node_build_environment(), RuntimeType::Development, ) @@ -291,8 +292,8 @@ async fn source( browserslist_query, ); let static_source = Vc::upcast(StaticAssetsContentSource::new( - String::new(), - project_path.join("public".to_string()), + Default::default(), + project_path.join("public".into()), )); let main_source = CombinedContentSource::new(vec![static_source, web_source]); let introspect = Vc::upcast( @@ -304,7 +305,7 @@ async fn source( let main_source = Vc::upcast(main_source); let source = Vc::upcast(PrefixedRouterContentSource::new( Default::default(), - vec![("__turbopack__".to_string(), introspect)], + vec![("__turbopack__".into(), introspect)], main_source, )); diff --git a/crates/turbopack-cli/src/dev/web_entry_source.rs b/crates/turbopack-cli/src/dev/web_entry_source.rs index 73a752d5cffed..7c179be3e8875 100644 --- a/crates/turbopack-cli/src/dev/web_entry_source.rs +++ b/crates/turbopack-cli/src/dev/web_entry_source.rs @@ -1,5 +1,5 @@ use anyhow::{anyhow, Result}; -use turbo_tasks::{TryJoinIterExt, Value, Vc}; +use turbo_tasks::{RcStr, TryJoinIterExt, Value, Vc}; use turbo_tasks_env::ProcessEnv; use turbo_tasks_fs::FileSystemPath; use turbopack::ecmascript::EcmascriptModuleAsset; @@ -41,8 +41,8 @@ pub fn get_client_chunking_context( project_path, server_root, server_root, - server_root.join("/_chunks".to_string()), - server_root.join("/_assets".to_string()), + server_root.join("/_chunks".into()), + server_root.join("/_assets".into()), environment, RuntimeType::Development, ) @@ -67,13 +67,12 @@ pub async fn get_client_runtime_entries( // because the bootstrap contains JSX which requires Refresh's global // functions to be available. if let Some(request) = enable_react_refresh { - runtime_entries - .push(RuntimeEntry::Request(request, project_path.join("_".to_string())).cell()) + runtime_entries.push(RuntimeEntry::Request(request, project_path.join("_".into())).cell()) }; runtime_entries.push( RuntimeEntry::Source(Vc::upcast(FileSource::new(embed_file_path( - "entry/bootstrap.ts".to_string(), + "entry/bootstrap.ts".into(), )))) .cell(), ); @@ -90,7 +89,7 @@ pub async fn create_web_entry_source( _env: Vc>, eager_compile: bool, node_env: Vc, - browserslist_query: String, + browserslist_query: RcStr, ) -> Result>> { let compile_time_info = get_client_compile_time_info(browserslist_query, node_env); let asset_context = @@ -101,7 +100,7 @@ pub async fn create_web_entry_source( let runtime_entries = entries.resolve_entries(asset_context); - let origin = PlainResolveOrigin::new(asset_context, project_path.join("_".to_string())); + let origin = PlainResolveOrigin::new(asset_context, project_path.join("_".into())); let entries = entry_requests .into_iter() .map(|request| async move { @@ -146,7 +145,7 @@ pub async fn create_web_entry_source( .await?; let entry_asset = Vc::upcast(DevHtmlAsset::new( - server_root.join("index.html".to_string()), + server_root.join("index.html".into()), entries, )); diff --git a/crates/turbopack-cli/src/embed_js.rs b/crates/turbopack-cli/src/embed_js.rs index 793fe320013ae..676341316d70b 100644 --- a/crates/turbopack-cli/src/embed_js.rs +++ b/crates/turbopack-cli/src/embed_js.rs @@ -1,4 +1,4 @@ -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::{embed_directory, FileContent, FileSystem, FileSystemPath}; #[turbo_tasks::function] @@ -7,11 +7,11 @@ fn embed_fs() -> Vc> { } #[turbo_tasks::function] -pub(crate) fn embed_file(path: String) -> Vc { +pub(crate) fn embed_file(path: RcStr) -> Vc { embed_fs().root().join(path).read() } #[turbo_tasks::function] -pub(crate) fn embed_file_path(path: String) -> Vc { +pub(crate) fn embed_file_path(path: RcStr) -> Vc { embed_fs().root().join(path) } diff --git a/crates/turbopack-cli/src/util.rs b/crates/turbopack-cli/src/util.rs index 1c230e22d5be0..7ab0ee363a795 100644 --- a/crates/turbopack-cli/src/util.rs +++ b/crates/turbopack-cli/src/util.rs @@ -2,7 +2,7 @@ use std::{env::current_dir, path::PathBuf}; use anyhow::{Context, Result}; use dunce::canonicalize; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::{DiskFileSystem, FileSystem}; #[turbo_tasks::value(transparent)] @@ -11,15 +11,15 @@ pub struct EntryRequests(pub Vec>); #[turbo_tasks::value(shared)] #[derive(Clone)] pub enum EntryRequest { - Relative(String), - Module(String, String), + Relative(RcStr), + Module(RcStr, RcStr), } pub struct NormalizedDirs { /// Normalized project directory path as an absolute path - pub project_dir: String, + pub project_dir: RcStr, /// Normalized root directory path as an absolute path - pub root_dir: String, + pub root_dir: RcStr, } /// Normalizes (canonicalizes and represents as an absolute path in a String) @@ -28,21 +28,21 @@ pub fn normalize_dirs( project_dir: &Option, root_dir: &Option, ) -> Result { - let project_dir = project_dir + let project_dir: RcStr = project_dir .as_ref() .map(canonicalize) .unwrap_or_else(current_dir) .context("project directory can't be found")? .to_str() .context("project directory contains invalid characters")? - .to_string(); + .into(); let root_dir = match root_dir.as_ref() { Some(root) => canonicalize(root) .context("root directory can't be found")? .to_str() .context("root directory contains invalid characters")? - .to_string(), + .into(), None => project_dir.clone(), }; @@ -52,23 +52,23 @@ pub fn normalize_dirs( }) } -pub fn normalize_entries(entries: &Option>) -> Vec { +pub fn normalize_entries(entries: &Option>) -> Vec { entries .as_ref() - .cloned() - .unwrap_or_else(|| vec!["src/entry".to_owned()]) + .map(|v| v.iter().map(|v| RcStr::from(&**v)).collect()) + .unwrap_or_else(|| vec!["src/entry".into()]) } #[turbo_tasks::function] -pub async fn project_fs(project_dir: String) -> Result>> { - let disk_fs = DiskFileSystem::new("project".to_string(), project_dir.to_string(), vec![]); +pub async fn project_fs(project_dir: RcStr) -> Result>> { + let disk_fs = DiskFileSystem::new("project".into(), project_dir, vec![]); disk_fs.await?.start_watching()?; Ok(Vc::upcast(disk_fs)) } #[turbo_tasks::function] -pub async fn output_fs(project_dir: String) -> Result>> { - let disk_fs = DiskFileSystem::new("output".to_string(), project_dir.to_string(), vec![]); +pub async fn output_fs(project_dir: RcStr) -> Result>> { + let disk_fs = DiskFileSystem::new("output".into(), project_dir, vec![]); disk_fs.await?.start_watching()?; Ok(Vc::upcast(disk_fs)) } diff --git a/crates/turbopack-core/src/asset.rs b/crates/turbopack-core/src/asset.rs index 9d1873b42afd6..dddcb3b674653 100644 --- a/crates/turbopack-core/src/asset.rs +++ b/crates/turbopack-core/src/asset.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{Completion, Vc}; +use turbo_tasks::{Completion, RcStr, Vc}; use turbo_tasks_fs::{ FileContent, FileJsonContent, FileLinesContent, FileSystemPath, LinkContent, LinkType, }; @@ -25,7 +25,7 @@ pub enum AssetContent { // for the relative link, the target is raw value read from the link // for the absolute link, the target is stripped of the root path while reading // See [LinkContent::Link] for more details. - Redirect { target: String, link_type: LinkType }, + Redirect { target: RcStr, link_type: LinkType }, } #[turbo_tasks::value_impl] diff --git a/crates/turbopack-core/src/chunk/chunk_group.rs b/crates/turbopack-core/src/chunk/chunk_group.rs index 6a39862e1a82d..b2b3f5dec36dc 100644 --- a/crates/turbopack-core/src/chunk/chunk_group.rs +++ b/crates/turbopack-core/src/chunk/chunk_group.rs @@ -143,7 +143,7 @@ pub async fn make_chunk_group( let mut chunks = make_chunks( chunking_context, Vc::cell(chunk_items.into_iter().collect()), - "".to_string(), + "".into(), references_to_output_assets(external_module_references).await?, ) .await? @@ -156,7 +156,7 @@ pub async fn make_chunk_group( let async_loader_chunks = make_chunks( chunking_context, Vc::cell(async_loader_chunk_items.into_iter().collect()), - "async-loader-".to_string(), + "async-loader-".into(), references_to_output_assets(async_loader_external_module_references).await?, ) .await?; diff --git a/crates/turbopack-core/src/chunk/chunking.rs b/crates/turbopack-core/src/chunk/chunking.rs index d43acf36a35c9..bfdb09e339406 100644 --- a/crates/turbopack-core/src/chunk/chunking.rs +++ b/crates/turbopack-core/src/chunk/chunking.rs @@ -10,7 +10,7 @@ use indexmap::IndexMap; use once_cell::sync::Lazy; use regex::Regex; use tracing::Level; -use turbo_tasks::{ReadRef, TryJoinIterExt, ValueToString, Vc}; +use turbo_tasks::{RcStr, ReadRef, TryJoinIterExt, ValueToString, Vc}; use super::{ AsyncModuleInfo, Chunk, ChunkItem, ChunkItemsWithAsyncModuleInfo, ChunkType, ChunkingContext, @@ -21,7 +21,7 @@ use crate::output::OutputAssets; #[turbo_tasks::value] struct ChunkItemInfo { ty: Vc>, - name: Vc, + name: Vc, size: usize, } @@ -48,7 +48,7 @@ async fn chunk_item_info( pub async fn make_chunks( chunking_context: Vc>, chunk_items: Vc, - key_prefix: String, + key_prefix: RcStr, mut referenced_output_assets: Vc, ) -> Result> { let chunk_items = chunk_items @@ -107,7 +107,7 @@ type ChunkItemWithInfo = ( Vc>, Option>, usize, - ReadRef, + ReadRef, ); struct SplitContext<'a> { diff --git a/crates/turbopack-core/src/chunk/chunking_context.rs b/crates/turbopack-core/src/chunk/chunking_context.rs index 132995a7a8a4b..760b99baddad2 100644 --- a/crates/turbopack-core/src/chunk/chunking_context.rs +++ b/crates/turbopack-core/src/chunk/chunking_context.rs @@ -1,6 +1,6 @@ use anyhow::Result; use serde::{Deserialize, Serialize}; -use turbo_tasks::{trace::TraceRawVcs, TaskInput, Upcast, Value, ValueToString, Vc}; +use turbo_tasks::{trace::TraceRawVcs, RcStr, TaskInput, Upcast, Value, ValueToString, Vc}; use turbo_tasks_fs::FileSystemPath; use turbo_tasks_hash::DeterministicHash; @@ -43,7 +43,7 @@ pub struct ChunkGroupResult { /// A context for the chunking that influences the way chunks are created #[turbo_tasks::value_trait] pub trait ChunkingContext { - fn name(self: Vc) -> Vc; + fn name(self: Vc) -> Vc; fn context_path(self: Vc) -> Vc; fn output_root(self: Vc) -> Vc; @@ -55,7 +55,7 @@ pub trait ChunkingContext { // discretion of chunking context implementors. However, we currently use this // in a couple of places in `turbopack-css`, so we need to remove that // dependency first. - fn chunk_path(self: Vc, ident: Vc, extension: String) -> Vc; + fn chunk_path(self: Vc, ident: Vc, extension: RcStr) -> Vc; // TODO(alexkirsz) Remove this from the chunking context. /// Reference Source Map Assets for chunks @@ -63,11 +63,11 @@ pub trait ChunkingContext { /// Returns a URL (relative or absolute, depending on the asset prefix) to /// the static asset based on its `ident`. - fn asset_url(self: Vc, ident: Vc) -> Result>; + fn asset_url(self: Vc, ident: Vc) -> Result>; fn asset_path( self: Vc, - content_hash: String, + content_hash: RcStr, original_asset_ident: Vc, ) -> Vc; diff --git a/crates/turbopack-core/src/chunk/data.rs b/crates/turbopack-core/src/chunk/data.rs index 9dd8de750578a..900ebd9edff5c 100644 --- a/crates/turbopack-core/src/chunk/data.rs +++ b/crates/turbopack-core/src/chunk/data.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{ReadRef, TryJoinIterExt, Vc}; +use turbo_tasks::{RcStr, ReadRef, TryJoinIterExt, Vc}; use turbo_tasks_fs::FileSystemPath; use crate::{ @@ -27,8 +27,8 @@ pub struct ChunkDataOption(Option>); pub struct ChunksData(Vec>); #[turbo_tasks::function] -fn module_chunk_reference_description() -> Vc { - Vc::cell("module chunk".to_string()) +fn module_chunk_reference_description() -> Vc { + Vc::cell("module chunk".into()) } #[turbo_tasks::value_impl] diff --git a/crates/turbopack-core/src/chunk/mod.rs b/crates/turbopack-core/src/chunk/mod.rs index 7c68e1cdd469c..e6f97891e8af9 100644 --- a/crates/turbopack-core/src/chunk/mod.rs +++ b/crates/turbopack-core/src/chunk/mod.rs @@ -24,7 +24,7 @@ use turbo_tasks::{ debug::ValueDebugFormat, graph::{AdjacencyMap, GraphTraversal, GraphTraversalResult, Visit, VisitControlFlow}, trace::TraceRawVcs, - ReadRef, TaskInput, TryFlatJoinIterExt, TryJoinIterExt, Upcast, ValueToString, Vc, + RcStr, ReadRef, TaskInput, TryFlatJoinIterExt, TryJoinIterExt, Upcast, ValueToString, Vc, }; use turbo_tasks_fs::FileSystemPath; use turbo_tasks_hash::DeterministicHash; @@ -50,7 +50,7 @@ use crate::{ #[serde(untagged)] pub enum ModuleId { Number(u32), - String(String), + String(RcStr), } impl Display for ModuleId { @@ -65,8 +65,8 @@ impl Display for ModuleId { #[turbo_tasks::value_impl] impl ValueToString for ModuleId { #[turbo_tasks::function] - fn to_string(&self) -> Vc { - Vc::cell(self.to_string()) + fn to_string(&self) -> Vc { + Vc::cell(self.to_string().into()) } } @@ -74,7 +74,7 @@ impl ModuleId { pub fn parse(id: &str) -> Result { Ok(match id.parse::() { Ok(i) => ModuleId::Number(i), - Err(_) => ModuleId::String(id.to_string()), + Err(_) => ModuleId::String(id.into()), }) } } @@ -226,7 +226,7 @@ enum ChunkContentGraphNode { // Chunk items that are placed into the current chunk group ChunkItem { item: Vc>, - ident: ReadRef, + ident: ReadRef, }, // Async module that is referenced from the chunk group AsyncModule { diff --git a/crates/turbopack-core/src/compile_time_info.rs b/crates/turbopack-core/src/compile_time_info.rs index b0375d34de00f..e33d4006b604b 100644 --- a/crates/turbopack-core/src/compile_time_info.rs +++ b/crates/turbopack-core/src/compile_time_info.rs @@ -1,6 +1,6 @@ use anyhow::Result; use indexmap::IndexMap; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::FileSystemPath; use crate::environment::Environment; @@ -37,16 +37,16 @@ macro_rules! definable_name_map_internal { $crate::definable_name_map_internal!($map, $($more)+); }; ($name:ident) => { - [stringify!($name).to_string()] + [stringify!($name).into()] }; ($name:ident . $($more:ident).+) => { - $crate::definable_name_map_internal!($($more).+, [stringify!($name).to_string()]) + $crate::definable_name_map_internal!($($more).+, [stringify!($name).into()]) }; ($name:ident, [$($array:expr),+]) => { - [$($array),+, stringify!($name).to_string()] + [$($array),+, stringify!($name).into()] }; ($name:ident . $($more:ident).+, [$($array:expr),+]) => { - $crate::definable_name_map_internal!($($more).+, [$($array),+, stringify!($name).to_string()]) + $crate::definable_name_map_internal!($($more).+, [$($array),+, stringify!($name).into()]) }; } @@ -78,8 +78,8 @@ macro_rules! free_var_references { #[derive(Debug, Clone, Hash, PartialOrd, Ord)] pub enum CompileTimeDefineValue { Bool(bool), - String(String), - JSON(String), + String(RcStr), + JSON(RcStr), } impl From for CompileTimeDefineValue { @@ -88,31 +88,37 @@ impl From for CompileTimeDefineValue { } } +impl From for CompileTimeDefineValue { + fn from(value: RcStr) -> Self { + Self::String(value) + } +} + impl From for CompileTimeDefineValue { fn from(value: String) -> Self { - Self::String(value) + Self::String(value.into()) } } impl From<&str> for CompileTimeDefineValue { fn from(value: &str) -> Self { - Self::String(value.to_string()) + Self::String(value.into()) } } impl From for CompileTimeDefineValue { fn from(value: serde_json::Value) -> Self { - Self::JSON(value.to_string()) + Self::JSON(value.to_string().into()) } } #[turbo_tasks::value(transparent)] #[derive(Debug, Clone)] -pub struct CompileTimeDefines(pub IndexMap, CompileTimeDefineValue>); +pub struct CompileTimeDefines(pub IndexMap, CompileTimeDefineValue>); impl IntoIterator for CompileTimeDefines { - type Item = (Vec, CompileTimeDefineValue); - type IntoIter = indexmap::map::IntoIter, CompileTimeDefineValue>; + type Item = (Vec, CompileTimeDefineValue); + type IntoIter = indexmap::map::IntoIter, CompileTimeDefineValue>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() @@ -131,12 +137,12 @@ impl CompileTimeDefines { #[derive(Debug, Clone)] pub enum FreeVarReference { EcmaScriptModule { - request: String, + request: RcStr, lookup_path: Option>, - export: Option, + export: Option, }, Value(CompileTimeDefineValue), - Error(String), + Error(RcStr), } impl From for FreeVarReference { @@ -165,7 +171,7 @@ impl From for FreeVarReference { #[turbo_tasks::value(transparent)] #[derive(Debug, Clone)] -pub struct FreeVarReferences(pub IndexMap, FreeVarReference>); +pub struct FreeVarReferences(pub IndexMap, FreeVarReference>); #[turbo_tasks::value_impl] impl FreeVarReferences { diff --git a/crates/turbopack-core/src/context.rs b/crates/turbopack-core/src/context.rs index 8d77c677f5d76..30f7052fa0606 100644 --- a/crates/turbopack-core/src/context.rs +++ b/crates/turbopack-core/src/context.rs @@ -1,5 +1,5 @@ use anyhow::{bail, Result}; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::{RcStr, Value, Vc}; use turbo_tasks_fs::{glob::Glob, FileSystemPath}; use crate::{ @@ -42,7 +42,7 @@ pub trait AssetContext { fn compile_time_info(self: Vc) -> Vc; /// Gets the layer of the asset context. - fn layer(self: Vc) -> Vc; + fn layer(self: Vc) -> Vc; /// Gets the resolve options for a given path. fn resolve_options( @@ -75,7 +75,7 @@ pub trait AssetContext { ) -> Vc; /// Gets a new AssetContext with the transition applied. - fn with_transition(self: Vc, transition: String) -> Vc>; + fn with_transition(self: Vc, transition: RcStr) -> Vc>; fn side_effect_free_packages(self: Vc) -> Vc; } diff --git a/crates/turbopack-core/src/diagnostics/mod.rs b/crates/turbopack-core/src/diagnostics/mod.rs index 4c2a3b247a7d6..9a7aa25bb576a 100644 --- a/crates/turbopack-core/src/diagnostics/mod.rs +++ b/crates/turbopack-core/src/diagnostics/mod.rs @@ -2,18 +2,18 @@ use std::collections::HashMap; use anyhow::Result; use async_trait::async_trait; -use turbo_tasks::{emit, CollectiblesSource, Upcast, Vc}; +use turbo_tasks::{emit, CollectiblesSource, RcStr, Upcast, Vc}; #[turbo_tasks::value(serialization = "none")] #[derive(Clone, Debug)] pub struct PlainDiagnostic { - pub category: String, - pub name: String, - pub payload: HashMap, + pub category: RcStr, + pub name: RcStr, + pub payload: HashMap, } #[turbo_tasks::value(transparent)] -pub struct DiagnosticPayload(pub HashMap); +pub struct DiagnosticPayload(pub HashMap); /// An arbitrary payload can be used to analyze, diagnose /// Turbopack's behavior. @@ -25,9 +25,9 @@ pub trait Diagnostic { /// `slow_perf_event`, or something else. This is not strongly typed /// though; since consumer or implementation may need to define own /// category. - fn category(&self) -> Vc; + fn category(&self) -> Vc; /// Name of the specific diagnostic event. - fn name(&self) -> Vc; + fn name(&self) -> Vc; /// Arbitarary payload included in the diagnostic event. fn payload(&self) -> Vc; diff --git a/crates/turbopack-core/src/environment.rs b/crates/turbopack-core/src/environment.rs index 05813151aedf0..0330c177d8922 100644 --- a/crates/turbopack-core/src/environment.rs +++ b/crates/turbopack-core/src/environment.rs @@ -5,7 +5,7 @@ use std::{ use anyhow::{anyhow, Context, Result}; use swc_core::ecma::preset_env::{Version, Versions}; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::{RcStr, Value, Vc}; use turbo_tasks_env::ProcessEnv; use crate::target::CompileTarget; @@ -149,18 +149,14 @@ impl Environment { } #[turbo_tasks::function] - pub async fn resolve_extensions(self: Vc) -> Result>> { + pub async fn resolve_extensions(self: Vc) -> Result>> { let env = self.await?; Ok(match env.execution { ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => { - Vc::cell(vec![ - ".js".to_string(), - ".node".to_string(), - ".json".to_string(), - ]) + Vc::cell(vec![".js".into(), ".node".into(), ".json".into()]) } ExecutionEnvironment::EdgeWorker(_) | ExecutionEnvironment::Browser(_) => { - Vc::>::default() + Vc::>::default() } ExecutionEnvironment::Custom(_) => todo!(), }) @@ -181,22 +177,22 @@ impl Environment { } #[turbo_tasks::function] - pub async fn resolve_conditions(self: Vc) -> Result>> { + pub async fn resolve_conditions(self: Vc) -> Result>> { let env = self.await?; Ok(match env.execution { ExecutionEnvironment::NodeJsBuildTime(..) | ExecutionEnvironment::NodeJsLambda(_) => { - Vc::cell(vec!["node".to_string()]) + Vc::cell(vec!["node".into()]) } - ExecutionEnvironment::Browser(_) => Vc::>::default(), + ExecutionEnvironment::Browser(_) => Vc::>::default(), ExecutionEnvironment::EdgeWorker(_) => { - Vc::cell(vec!["edge-light".to_string(), "worker".to_string()]) + Vc::cell(vec!["edge-light".into(), "worker".into()]) } ExecutionEnvironment::Custom(_) => todo!(), }) } #[turbo_tasks::function] - pub async fn cwd(self: Vc) -> Result>> { + pub async fn cwd(self: Vc) -> Result>> { let env = self.await?; Ok(match env.execution { ExecutionEnvironment::NodeJsBuildTime(env) @@ -241,7 +237,7 @@ pub struct NodeJsEnvironment { pub compile_target: Vc, pub node_version: Vc, // user specified process.cwd - pub cwd: Vc>, + pub cwd: Vc>, } impl Default for NodeJsEnvironment { @@ -285,12 +281,12 @@ impl NodeJsEnvironment { #[turbo_tasks::value(shared)] pub enum NodeJsVersion { Current(Vc>), - Static(Vc), + Static(Vc), } impl Default for NodeJsVersion { fn default() -> Self { - NodeJsVersion::Static(Vc::cell(DEFAULT_NODEJS_VERSION.to_owned())) + NodeJsVersion::Static(Vc::cell(DEFAULT_NODEJS_VERSION.into())) } } @@ -299,7 +295,7 @@ pub struct BrowserEnvironment { pub dom: bool, pub web_worker: bool, pub service_worker: bool, - pub browserslist_query: String, + pub browserslist_query: RcStr, } #[turbo_tasks::value(shared)] @@ -309,8 +305,8 @@ pub struct EdgeWorkerEnvironment {} pub struct RuntimeVersions(#[turbo_tasks(trace_ignore)] pub Versions); #[turbo_tasks::function] -pub async fn get_current_nodejs_version(env: Vc>) -> Result> { - let path_read = env.read("PATH".to_string()).await?; +pub async fn get_current_nodejs_version(env: Vc>) -> Result> { + let path_read = env.read("PATH".into()).await?; let path = path_read.as_ref().context("env must have PATH")?; let mut cmd = Command::new("node"); cmd.arg("--version"); @@ -325,6 +321,6 @@ pub async fn get_current_nodejs_version(env: Vc>) -> Result< .context("Version must begin with v")? .strip_suffix('\n') .context("Version must end with \\n")? - .to_owned(), + .into(), )) } diff --git a/crates/turbopack-core/src/file_source.rs b/crates/turbopack-core/src/file_source.rs index d801673862ffe..ca0f204f5630c 100644 --- a/crates/turbopack-core/src/file_source.rs +++ b/crates/turbopack-core/src/file_source.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::{FileContent, FileSystemEntryType, FileSystemPath, LinkContent}; use crate::{ @@ -13,7 +13,7 @@ use crate::{ #[turbo_tasks::value] pub struct FileSource { pub path: Vc, - pub query: Vc, + pub query: Vc, } #[turbo_tasks::value_impl] @@ -22,12 +22,12 @@ impl FileSource { pub fn new(path: Vc) -> Vc { Self::cell(FileSource { path, - query: Vc::::default(), + query: Vc::::default(), }) } #[turbo_tasks::function] - pub fn new_with_query(path: Vc, query: Vc) -> Vc { + pub fn new_with_query(path: Vc, query: Vc) -> Vc { Self::cell(FileSource { path, query }) } } diff --git a/crates/turbopack-core/src/ident.rs b/crates/turbopack-core/src/ident.rs index f835b241dca49..e63d4eb6c1c3c 100644 --- a/crates/turbopack-core/src/ident.rs +++ b/crates/turbopack-core/src/ident.rs @@ -1,7 +1,7 @@ use std::fmt::Write; use anyhow::Result; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbo_tasks_fs::FileSystemPath; use turbo_tasks_hash::{encode_hex, hash_xxh3_hash64, DeterministicHash, Xxh3Hash64Hasher}; @@ -13,25 +13,25 @@ pub struct AssetIdent { /// The primary path of the asset pub path: Vc, /// The query string of the asset (e.g. `?foo=bar`) - pub query: Vc, + pub query: Vc, /// The fragment of the asset (e.g. `#foo`) - pub fragment: Option>, + pub fragment: Option>, /// The assets that are nested in this asset - pub assets: Vec<(Vc, Vc)>, + pub assets: Vec<(Vc, Vc)>, /// The modifiers of this asset (e.g. `client chunks`) - pub modifiers: Vec>, + pub modifiers: Vec>, /// The part of the asset that is a (ECMAScript) module pub part: Option>, /// The asset layer the asset was created from. - pub layer: Option>, + pub layer: Option>, } impl AssetIdent { - pub fn add_modifier(&mut self, modifier: Vc) { + pub fn add_modifier(&mut self, modifier: Vc) { self.modifiers.push(modifier); } - pub fn add_asset(&mut self, key: Vc, asset: Vc) { + pub fn add_asset(&mut self, key: Vc, asset: Vc) { self.assets.push((key, asset)); } @@ -39,7 +39,7 @@ impl AssetIdent { let root = self.path.root(); let path = self.path.await?; self.path = root - .join(pattern.replace('*', &path.path)) + .join(pattern.replace('*', &path.path).into()) .resolve() .await?; Ok(()) @@ -49,8 +49,8 @@ impl AssetIdent { #[turbo_tasks::value_impl] impl ValueToString for AssetIdent { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - let mut s = self.path.to_string().await?.clone_value(); + async fn to_string(&self) -> Result> { + let mut s = self.path.to_string().await?.clone_value().into_owned(); let query = self.query.await?; if !query.is_empty() { @@ -99,7 +99,7 @@ impl ValueToString for AssetIdent { write!(s, " <{}>", part.to_string().await?)?; } - Ok(Vc::cell(s)) + Ok(Vc::cell(s.into())) } } @@ -115,7 +115,7 @@ impl AssetIdent { pub fn from_path(path: Vc) -> Vc { Self::new(Value::new(AssetIdent { path, - query: Vc::::default(), + query: Vc::::default(), fragment: None, assets: Vec::new(), modifiers: Vec::new(), @@ -125,14 +125,14 @@ impl AssetIdent { } #[turbo_tasks::function] - pub fn with_query(&self, query: Vc) -> Vc { + pub fn with_query(&self, query: Vc) -> Vc { let mut this = self.clone(); this.query = query; Self::new(Value::new(this)) } #[turbo_tasks::function] - pub fn with_modifier(&self, modifier: Vc) -> Vc { + pub fn with_modifier(&self, modifier: Vc) -> Vc { let mut this = self.clone(); this.add_modifier(modifier); Self::new(Value::new(this)) @@ -153,14 +153,14 @@ impl AssetIdent { } #[turbo_tasks::function] - pub fn with_layer(&self, layer: Vc) -> Vc { + pub fn with_layer(&self, layer: Vc) -> Vc { let mut this = self.clone(); this.layer = Some(layer); Self::new(Value::new(this)) } #[turbo_tasks::function] - pub async fn rename_as(&self, pattern: String) -> Result> { + pub async fn rename_as(&self, pattern: RcStr) -> Result> { let mut this = self.clone(); this.rename_as_ref(&pattern).await?; Ok(Self::new(Value::new(this))) @@ -172,7 +172,7 @@ impl AssetIdent { } #[turbo_tasks::function] - pub fn query(&self) -> Vc { + pub fn query(&self) -> Vc { self.query } @@ -184,8 +184,8 @@ impl AssetIdent { pub async fn output_name( &self, context_path: Vc, - expected_extension: String, - ) -> Result> { + expected_extension: RcStr, + ) -> Result> { // TODO(PACK-2140): restrict character set to A–Za–z0–9-_.~'() // to be compatible with all operating systems + URLs. @@ -196,7 +196,7 @@ impl AssetIdent { } else { clean_separators(&self.path.to_string().await?) }; - let removed_extension = name.ends_with(&expected_extension); + let removed_extension = name.ends_with(&*expected_extension); if removed_extension { name.truncate(name.len() - expected_extension.len()); } @@ -329,7 +329,7 @@ impl AssetIdent { name += "._"; } name += &expected_extension; - Ok(Vc::cell(name)) + Ok(Vc::cell(name.into())) } } diff --git a/crates/turbopack-core/src/introspect/mod.rs b/crates/turbopack-core/src/introspect/mod.rs index a0eede980b2e0..a05bcc9088662 100644 --- a/crates/turbopack-core/src/introspect/mod.rs +++ b/crates/turbopack-core/src/introspect/mod.rs @@ -4,21 +4,21 @@ pub mod source; pub mod utils; use indexmap::IndexSet; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; type VcDynIntrospectable = Vc>; #[turbo_tasks::value(transparent)] -pub struct IntrospectableChildren(IndexSet<(Vc, VcDynIntrospectable)>); +pub struct IntrospectableChildren(IndexSet<(Vc, VcDynIntrospectable)>); #[turbo_tasks::value_trait] pub trait Introspectable { - fn ty(self: Vc) -> Vc; - fn title(self: Vc) -> Vc { - Vc::::default() + fn ty(self: Vc) -> Vc; + fn title(self: Vc) -> Vc { + Vc::::default() } - fn details(self: Vc) -> Vc { - Vc::::default() + fn details(self: Vc) -> Vc { + Vc::::default() } fn children(self: Vc) -> Vc { Vc::cell(IndexSet::new()) diff --git a/crates/turbopack-core/src/introspect/module.rs b/crates/turbopack-core/src/introspect/module.rs index 8c40807e14468..073be94ab1aff 100644 --- a/crates/turbopack-core/src/introspect/module.rs +++ b/crates/turbopack-core/src/introspect/module.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use super::{ utils::{children_from_module_references, content_to_details}, @@ -21,24 +21,24 @@ impl IntrospectableModule { } #[turbo_tasks::function] -fn ty() -> Vc { - Vc::cell("asset".to_string()) +fn ty() -> Vc { + Vc::cell("asset".into()) } #[turbo_tasks::value_impl] impl Introspectable for IntrospectableModule { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { ty() } #[turbo_tasks::function] - fn title(&self) -> Vc { + fn title(&self) -> Vc { self.0.ident().to_string() } #[turbo_tasks::function] - fn details(&self) -> Vc { + fn details(&self) -> Vc { content_to_details(self.0.content()) } diff --git a/crates/turbopack-core/src/introspect/output_asset.rs b/crates/turbopack-core/src/introspect/output_asset.rs index 3fed6c1cee3b6..946cdd30a8dd4 100644 --- a/crates/turbopack-core/src/introspect/output_asset.rs +++ b/crates/turbopack-core/src/introspect/output_asset.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use super::{ utils::{children_from_output_assets, content_to_details}, @@ -21,24 +21,24 @@ impl IntrospectableOutputAsset { } #[turbo_tasks::function] -fn ty() -> Vc { - Vc::cell("output asset".to_string()) +fn ty() -> Vc { + Vc::cell("output asset".into()) } #[turbo_tasks::value_impl] impl Introspectable for IntrospectableOutputAsset { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { ty() } #[turbo_tasks::function] - fn title(&self) -> Vc { + fn title(&self) -> Vc { self.0.ident().to_string() } #[turbo_tasks::function] - fn details(&self) -> Vc { + fn details(&self) -> Vc { content_to_details(self.0.content()) } diff --git a/crates/turbopack-core/src/introspect/source.rs b/crates/turbopack-core/src/introspect/source.rs index ca28f44cbd17f..38c98d2678d7d 100644 --- a/crates/turbopack-core/src/introspect/source.rs +++ b/crates/turbopack-core/src/introspect/source.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use super::{utils::content_to_details, Introspectable}; use crate::{asset::Asset, source::Source}; @@ -18,24 +18,24 @@ impl IntrospectableSource { } #[turbo_tasks::function] -fn ty() -> Vc { - Vc::cell("source".to_string()) +fn ty() -> Vc { + Vc::cell("source".into()) } #[turbo_tasks::value_impl] impl Introspectable for IntrospectableSource { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { ty() } #[turbo_tasks::function] - fn title(&self) -> Vc { + fn title(&self) -> Vc { self.0.ident().to_string() } #[turbo_tasks::function] - fn details(&self) -> Vc { + fn details(&self) -> Vc { content_to_details(self.0.content()) } } diff --git a/crates/turbopack-core/src/introspect/utils.rs b/crates/turbopack-core/src/introspect/utils.rs index 0207e8f57aa25..e69db98b392ca 100644 --- a/crates/turbopack-core/src/introspect/utils.rs +++ b/crates/turbopack-core/src/introspect/utils.rs @@ -1,6 +1,6 @@ use anyhow::Result; use indexmap::IndexSet; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::FileContent; use super::{ @@ -14,45 +14,45 @@ use crate::{ }; #[turbo_tasks::function] -fn reference_ty() -> Vc { - Vc::cell("reference".to_string()) +fn reference_ty() -> Vc { + Vc::cell("reference".into()) } #[turbo_tasks::function] -fn parallel_reference_ty() -> Vc { - Vc::cell("parallel reference".to_string()) +fn parallel_reference_ty() -> Vc { + Vc::cell("parallel reference".into()) } #[turbo_tasks::function] -fn parallel_inherit_async_reference_ty() -> Vc { - Vc::cell("parallel reference (inherit async module)".to_string()) +fn parallel_inherit_async_reference_ty() -> Vc { + Vc::cell("parallel reference (inherit async module)".into()) } #[turbo_tasks::function] -fn async_reference_ty() -> Vc { - Vc::cell("async reference".to_string()) +fn async_reference_ty() -> Vc { + Vc::cell("async reference".into()) } #[turbo_tasks::function] -fn passthrough_reference_ty() -> Vc { - Vc::cell("passthrough reference".to_string()) +fn passthrough_reference_ty() -> Vc { + Vc::cell("passthrough reference".into()) } #[turbo_tasks::function] -pub async fn content_to_details(content: Vc) -> Result> { +pub async fn content_to_details(content: Vc) -> Result> { Ok(match &*content.await? { AssetContent::File(file_content) => match &*file_content.await? { FileContent::Content(file) => { let content = file.content(); match content.to_str() { - Ok(str) => Vc::cell(str.into_owned()), - Err(_) => Vc::cell(format!("{} binary bytes", content.len())), + Ok(str) => Vc::cell(str.into()), + Err(_) => Vc::cell(format!("{} binary bytes", content.len()).into()), } } - FileContent::NotFound => Vc::cell("not found".to_string()), + FileContent::NotFound => Vc::cell("not found".into()), }, AssetContent::Redirect { target, link_type } => { - Vc::cell(format!("redirect to {target} with type {link_type:?}")) + Vc::cell(format!("redirect to {target} with type {link_type:?}").into()) } }) } diff --git a/crates/turbopack-core/src/issue/analyze.rs b/crates/turbopack-core/src/issue/analyze.rs index 675e2a0218b55..435bf7325fc5d 100644 --- a/crates/turbopack-core/src/issue/analyze.rs +++ b/crates/turbopack-core/src/issue/analyze.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::FileSystemPath; use super::{ @@ -12,9 +12,9 @@ use crate::ident::AssetIdent; pub struct AnalyzeIssue { pub severity: Vc, pub source_ident: Vc, - pub title: Vc, + pub title: Vc, pub message: Vc, - pub code: Option, + pub code: Option, pub source: Option>, } @@ -27,15 +27,15 @@ impl Issue for AnalyzeIssue { #[turbo_tasks::function] async fn title(&self) -> Result> { - let title = &*self.title.await?; + let title = &**self.title.await?; Ok(if let Some(code) = self.code.as_ref() { StyledString::Line(vec![ - StyledString::Strong(code.to_string()), - StyledString::Text(" ".to_string()), - StyledString::Text(title.to_string()), + StyledString::Strong(code.clone()), + StyledString::Text(" ".into()), + StyledString::Text(title.into()), ]) } else { - StyledString::Text(title.to_string()) + StyledString::Text(title.into()) } .cell()) } diff --git a/crates/turbopack-core/src/issue/mod.rs b/crates/turbopack-core/src/issue/mod.rs index a237d647efad2..99c14a49ce5d9 100644 --- a/crates/turbopack-core/src/issue/mod.rs +++ b/crates/turbopack-core/src/issue/mod.rs @@ -14,8 +14,8 @@ use async_trait::async_trait; use auto_hash_map::AutoSet; use serde::Serialize; use turbo_tasks::{ - emit, CollectiblesSource, RawVc, ReadRef, TransientInstance, TransientValue, TryJoinIterExt, - Upcast, ValueToString, Vc, + emit, CollectiblesSource, RawVc, RcStr, ReadRef, TransientInstance, TransientValue, + TryJoinIterExt, Upcast, ValueToString, Vc, }; use turbo_tasks_fs::{FileContent, FileLine, FileLinesContent, FileSystemPath}; use turbo_tasks_hash::{DeterministicHash, Xxh3Hash64Hasher}; @@ -88,12 +88,12 @@ pub enum StyledString { /// block elements, just like the top level [StyledString]. Stack(Vec), /// Some prose text. - Text(String), + Text(RcStr), /// Code snippet. // TODO add language to support syntax hightlighting - Code(String), + Code(RcStr), /// Some important text. - Strong(String), + Strong(RcStr), } #[turbo_tasks::value_trait] @@ -134,8 +134,8 @@ pub trait Issue { /// A link to relevant documentation of the issue. Only displayed in console /// if the user explicitly asks for detailed messages. - fn documentation_link(self: Vc) -> Vc { - Vc::::default() + fn documentation_link(self: Vc) -> Vc { + Vc::::default() } /// The source location that caused the issue. Eg, for a parsing error it @@ -202,20 +202,18 @@ trait IssueProcessingPath { #[turbo_tasks::value] pub struct IssueProcessingPathItem { pub file_path: Option>, - pub description: Vc, + pub description: Vc, } #[turbo_tasks::value_impl] impl ValueToString for IssueProcessingPathItem { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { + async fn to_string(&self) -> Result> { if let Some(context) = self.file_path { let description_str = self.description.await?; - Ok(Vc::cell(format!( - "{} ({})", - context.to_string().await?, - description_str - ))) + Ok(Vc::cell( + format!("{} ({})", context.to_string().await?, description_str).into(), + )) } else { Ok(self.description) } @@ -312,7 +310,7 @@ impl IssueProcessingPath for ItemIssueProcessingPath { let (mut a, mut b) = (old.iter(), path.iter()); while let (Some(a), Some(b)) = (a.next(), b.next()) { let (a, b) = (a.to_string().await?, b.to_string().await?); - match String::cmp(&*a, &*b) { + match RcStr::cmp(&*a, &*b) { Ordering::Less => break, Ordering::Greater => { shortest = Some(path); @@ -567,14 +565,14 @@ impl Display for IssueStage { #[derive(Clone, Debug)] pub struct PlainIssue { pub severity: IssueSeverity, - pub file_path: String, + pub file_path: RcStr, pub stage: IssueStage, pub title: StyledString, pub description: Option, pub detail: Option, - pub documentation_link: String, + pub documentation_link: RcStr, pub source: Option>, pub sub_issues: Vec>, @@ -704,7 +702,7 @@ impl IssueSource { #[turbo_tasks::value(serialization = "none")] #[derive(Clone, Debug)] pub struct PlainSource { - pub ident: ReadRef, + pub ident: ReadRef, #[turbo_tasks(debug_ignore)] pub content: ReadRef, } @@ -734,8 +732,8 @@ pub struct PlainIssueProcessingPath(Option>, - pub description: ReadRef, + pub file_path: Option>, + pub description: ReadRef, } #[turbo_tasks::value_trait] @@ -811,7 +809,7 @@ where ItemIssueProcessingPath::cell(ItemIssueProcessingPath( Some(IssueProcessingPathItem::cell(IssueProcessingPathItem { file_path: file_path.into(), - description: Vc::cell(description.into()), + description: Vc::cell(RcStr::from(description.into())), })), children, )), @@ -839,7 +837,7 @@ where ItemIssueProcessingPath::cell(ItemIssueProcessingPath( Some(IssueProcessingPathItem::cell(IssueProcessingPathItem { file_path: file_path.into(), - description: Vc::cell(description.into()), + description: Vc::cell(RcStr::from(description.into())), })), children, )), diff --git a/crates/turbopack-core/src/issue/resolve.rs b/crates/turbopack-core/src/issue/resolve.rs index b56c64a46a2dc..542a5fd962b43 100644 --- a/crates/turbopack-core/src/issue/resolve.rs +++ b/crates/turbopack-core/src/issue/resolve.rs @@ -1,7 +1,7 @@ use std::fmt::Write; use anyhow::Result; -use turbo_tasks::{ReadRef, ValueToString, Vc}; +use turbo_tasks::{RcStr, ReadRef, ValueToString, Vc}; use turbo_tasks_fs::FileSystemPath; use super::{Issue, IssueSource, IssueStage, OptionIssueSource, OptionStyledString, StyledString}; @@ -34,14 +34,14 @@ impl Issue for ResolvingIssue { #[turbo_tasks::function] async fn title(&self) -> Result> { - let module_not_found = StyledString::Strong("Module not found".to_string()); + let module_not_found = StyledString::Strong("Module not found".into()); Ok(match self.request.await?.request() { Some(request) => StyledString::Line(vec![ module_not_found, - StyledString::Text(": Can't resolve '".to_string()), + StyledString::Text(": Can't resolve '".into()), StyledString::Code(request), - StyledString::Text("'".to_string()), + StyledString::Text("'".into()), ]), None => module_not_found, } @@ -77,7 +77,9 @@ impl Issue for ResolvingIssue { } } } - Ok(Vc::cell(Some(StyledString::Text(description).cell()))) + Ok(Vc::cell(Some( + StyledString::Text(description.into()).cell(), + ))) } #[turbo_tasks::function] @@ -104,7 +106,7 @@ impl Issue for ResolvingIssue { "Type of request: {request_type}", request_type = self.request_type, )?; - Ok(Vc::cell(Some(StyledString::Text(detail).cell()))) + Ok(Vc::cell(Some(StyledString::Text(detail.into()).cell()))) } #[turbo_tasks::function] @@ -120,7 +122,7 @@ async fn lookup_import_map( import_map: Vc, file_path: Vc, request: Vc, -) -> Result>> { +) -> Result>> { let result = import_map.await?.lookup(file_path, request).await?; if matches!(result, ImportMapResult::NoEntry) { diff --git a/crates/turbopack-core/src/issue/unsupported_module.rs b/crates/turbopack-core/src/issue/unsupported_module.rs index 4d2b9e9bb4815..0c870de69712b 100644 --- a/crates/turbopack-core/src/issue/unsupported_module.rs +++ b/crates/turbopack-core/src/issue/unsupported_module.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::FileSystemPath; use super::{Issue, IssueSeverity, IssueStage, OptionStyledString, StyledString}; @@ -7,8 +7,8 @@ use super::{Issue, IssueSeverity, IssueStage, OptionStyledString, StyledString}; #[turbo_tasks::value(shared)] pub struct UnsupportedModuleIssue { pub file_path: Vc, - pub package: String, - pub package_path: Option, + pub package: RcStr, + pub package_path: Option, } #[turbo_tasks::value_impl] @@ -37,19 +37,19 @@ impl Issue for UnsupportedModuleIssue { async fn description(&self) -> Result> { Ok(Vc::cell(Some( StyledString::Line(vec![ - StyledString::Text("The ".to_string()), + StyledString::Text("The ".into()), StyledString::Text( match &self.package_path { Some(_) => "module", None => "package", } - .to_string(), + .into(), ), StyledString::Code(match &self.package_path { - Some(path) => format!(" {}{}", self.package, path), - None => format!(" {}", self.package), + Some(path) => format!(" {}{}", self.package, path).into(), + None => format!(" {}", self.package).into(), }), - StyledString::Text(" is not yet supported".to_string()), + StyledString::Text(" is not yet supported".into()), ]) .cell(), ))) diff --git a/crates/turbopack-core/src/package_json.rs b/crates/turbopack-core/src/package_json.rs index 4636b496e4496..e7c1011b29eff 100644 --- a/crates/turbopack-core/src/package_json.rs +++ b/crates/turbopack-core/src/package_json.rs @@ -2,7 +2,7 @@ use std::{fmt::Write, ops::Deref}; use anyhow::Result; use serde_json::Value as JsonValue; -use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, ReadRef, Vc}; +use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, RcStr, ReadRef, Vc}; use turbo_tasks_fs::{FileContent, FileJsonContent, FileSystemPath}; use super::issue::Issue; @@ -44,7 +44,7 @@ pub async fn read_package_json(path: Vc) -> Result) -> Result, - pub error_message: String, + pub error_message: RcStr, } #[turbo_tasks::value_impl] impl Issue for PackageJsonIssue { #[turbo_tasks::function] fn title(&self) -> Vc { - StyledString::Text("Error parsing package.json file".to_string()).cell() + StyledString::Text("Error parsing package.json file".into()).cell() } #[turbo_tasks::function] diff --git a/crates/turbopack-core/src/reference/mod.rs b/crates/turbopack-core/src/reference/mod.rs index abc92ef0bef0a..634eae3d8067a 100644 --- a/crates/turbopack-core/src/reference/mod.rs +++ b/crates/turbopack-core/src/reference/mod.rs @@ -4,7 +4,7 @@ use anyhow::Result; use indexmap::IndexSet; use turbo_tasks::{ graph::{AdjacencyMap, GraphTraversal}, - TryJoinIterExt, ValueToString, Vc, + RcStr, TryJoinIterExt, ValueToString, Vc, }; use crate::{ @@ -49,7 +49,7 @@ impl ModuleReferences { #[turbo_tasks::value] pub struct SingleModuleReference { asset: Vc>, - description: Vc, + description: Vc, } impl SingleModuleReference { @@ -70,7 +70,7 @@ impl ModuleReference for SingleModuleReference { #[turbo_tasks::value_impl] impl ValueToString for SingleModuleReference { #[turbo_tasks::function] - fn to_string(&self) -> Vc { + fn to_string(&self) -> Vc { self.description } } @@ -80,7 +80,7 @@ impl SingleModuleReference { /// Create a new [Vc] that resolves to the given /// asset. #[turbo_tasks::function] - pub fn new(asset: Vc>, description: Vc) -> Vc { + pub fn new(asset: Vc>, description: Vc) -> Vc { Self::cell(SingleModuleReference { asset, description }) } @@ -95,7 +95,7 @@ impl SingleModuleReference { #[turbo_tasks::value] pub struct SingleOutputAssetReference { asset: Vc>, - description: Vc, + description: Vc, } impl SingleOutputAssetReference { @@ -116,7 +116,7 @@ impl ModuleReference for SingleOutputAssetReference { #[turbo_tasks::value_impl] impl ValueToString for SingleOutputAssetReference { #[turbo_tasks::function] - fn to_string(&self) -> Vc { + fn to_string(&self) -> Vc { self.description } } @@ -126,7 +126,7 @@ impl SingleOutputAssetReference { /// Create a new [Vc] that resolves to the given /// asset. #[turbo_tasks::function] - pub fn new(asset: Vc>, description: Vc) -> Vc { + pub fn new(asset: Vc>, description: Vc) -> Vc { Self::cell(SingleOutputAssetReference { asset, description }) } diff --git a/crates/turbopack-core/src/reference/source_map.rs b/crates/turbopack-core/src/reference/source_map.rs index 9ebe976d2a0fa..cb6ba6e26f54e 100644 --- a/crates/turbopack-core/src/reference/source_map.rs +++ b/crates/turbopack-core/src/reference/source_map.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbo_tasks_fs::{FileSystemEntryType, FileSystemPath}; use super::ModuleReference; @@ -65,10 +65,13 @@ impl GenerateSourceMap for SourceMapReference { #[turbo_tasks::value_impl] impl ValueToString for SourceMapReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "source map file is referenced by {}", - self.from.to_string().await? - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!( + "source map file is referenced by {}", + self.from.to_string().await? + ) + .into(), + )) } } diff --git a/crates/turbopack-core/src/reference_type.rs b/crates/turbopack-core/src/reference_type.rs index 57a0a6722bcd2..7db3416319b5c 100644 --- a/crates/turbopack-core/src/reference_type.rs +++ b/crates/turbopack-core/src/reference_type.rs @@ -2,7 +2,7 @@ use std::fmt::Display; use anyhow::Result; use indexmap::IndexMap; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use crate::{module::Module, resolve::ModulePart}; @@ -10,7 +10,7 @@ use crate::{module::Module, resolve::ModulePart}; /// per-module aliases of some requests to already created module assets. /// Name is usually in UPPER_CASE to make it clear that this is an inner asset. #[turbo_tasks::value(transparent)] -pub struct InnerAssets(IndexMap>>); +pub struct InnerAssets(IndexMap>>); #[turbo_tasks::value_impl] impl InnerAssets { @@ -55,9 +55,9 @@ pub enum EcmaScriptModulesReferenceSubType { #[derive(Debug)] #[turbo_tasks::value(shared)] pub struct ImportAttributes { - pub layer: Option, - pub supports: Option, - pub media: Option, + pub layer: Option, + pub supports: Option, + pub media: Option, } /// The accumulated list of conditions that should be applied to this module @@ -65,15 +65,15 @@ pub struct ImportAttributes { #[derive(Debug, Default)] #[turbo_tasks::value] pub struct ImportContext { - pub layers: Vec, - pub supports: Vec, - pub media: Vec, + pub layers: Vec, + pub supports: Vec, + pub media: Vec, } #[turbo_tasks::value_impl] impl ImportContext { #[turbo_tasks::function] - pub fn new(layers: Vec, media: Vec, supports: Vec) -> Vc { + pub fn new(layers: Vec, media: Vec, supports: Vec) -> Vc { ImportContext { layers, media, @@ -85,9 +85,9 @@ impl ImportContext { #[turbo_tasks::function] pub async fn add_attributes( self: Vc, - attr_layer: Option, - attr_media: Option, - attr_supports: Option, + attr_layer: Option, + attr_media: Option, + attr_supports: Option, ) -> Result> { let this = &*self.await?; @@ -95,7 +95,7 @@ impl ImportContext { let mut layers = this.layers.clone(); if let Some(attr_layer) = attr_layer { if !layers.contains(&attr_layer) { - layers.push(attr_layer.to_owned()); + layers.push(attr_layer); } } layers @@ -105,7 +105,7 @@ impl ImportContext { let mut media = this.media.clone(); if let Some(attr_media) = attr_media { if !media.contains(&attr_media) { - media.push(attr_media.to_owned()); + media.push(attr_media); } } media @@ -115,7 +115,7 @@ impl ImportContext { let mut supports = this.supports.clone(); if let Some(attr_supports) = attr_supports { if !supports.contains(&attr_supports) { - supports.push(attr_supports.to_owned()); + supports.push(attr_supports); } } supports @@ -125,7 +125,7 @@ impl ImportContext { } #[turbo_tasks::function] - pub fn modifier(&self) -> Result> { + pub fn modifier(&self) -> Result> { use std::fmt::Write; let mut modifier = String::new(); if !self.layers.is_empty() { @@ -158,7 +158,7 @@ impl ImportContext { write!(modifier, "supports({})", supports)? } } - Ok(Vc::cell(modifier)) + Ok(Vc::cell(modifier.into())) } } diff --git a/crates/turbopack-core/src/resolve/alias_map.rs b/crates/turbopack-core/src/resolve/alias_map.rs index 08eb248bb8f73..7577669e9a4ab 100644 --- a/crates/turbopack-core/src/resolve/alias_map.rs +++ b/crates/turbopack-core/src/resolve/alias_map.rs @@ -14,6 +14,7 @@ use serde::{ use turbo_tasks::{ debug::{internal::PassthroughDebug, ValueDebugFormat, ValueDebugFormatString}, trace::{TraceRawVcs, TraceRawVcsContext}, + RcStr, }; /// A map of [`AliasPattern`]s to the [`Template`]s they resolve to. @@ -311,14 +312,16 @@ pub struct AliasMapIntoIter { } struct AliasMapIntoIterItem { - prefix: String, + prefix: RcStr, iterator: std::collections::btree_map::IntoIter, } impl AliasMapIntoIter { fn advance_iter(&mut self) -> Option<&mut AliasMapIntoIterItem> { let (prefix, map) = self.iter.next()?; - let prefix = String::from_utf8(prefix).expect("invalid UTF-8 key in AliasMap"); + let prefix = String::from_utf8(prefix) + .expect("invalid UTF-8 key in AliasMap") + .into(); self.current_prefix_iterator = Some(AliasMapIntoIterItem { prefix, iterator: map.into_iter(), @@ -374,7 +377,7 @@ pub struct AliasMapIter<'a, T> { } struct AliasMapIterItem<'a, T> { - prefix: String, + prefix: RcStr, iterator: std::collections::btree_map::Iter<'a, AliasKey, T>, } @@ -383,7 +386,9 @@ impl<'a, T> AliasMapIter<'a, T> { let Some((prefix, map)) = self.iter.next() else { return false; }; - let prefix = String::from_utf8(prefix).expect("invalid UTF-8 key in AliasMap"); + let prefix = String::from_utf8(prefix) + .expect("invalid UTF-8 key in AliasMap") + .into(); self.current_prefix_iterator = Some(AliasMapIterItem { prefix, iterator: map.iter(), @@ -470,7 +475,7 @@ where // The suffix is longer than what remains of the request. suffix.len() > remaining.len() // Not a suffix match. - || !remaining.ends_with(suffix) + || !remaining.ends_with(&**suffix) { continue; } @@ -492,9 +497,9 @@ where #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] pub enum AliasPattern { /// Will match an exact string. - Exact(String), + Exact(RcStr), /// Will match a pattern with a single wildcard. - Wildcard { prefix: String, suffix: String }, + Wildcard { prefix: RcStr, suffix: RcStr }, } impl AliasPattern { @@ -504,25 +509,27 @@ impl AliasPattern { /// characters, including path separators. pub fn parse<'a, T>(pattern: T) -> Self where - T: Into + 'a, + T: Into + 'a, { - let mut pattern = pattern.into(); + let pattern = pattern.into(); if let Some(wildcard_index) = pattern.find('*') { - let suffix = pattern[wildcard_index + 1..].to_string(); + let mut pattern = pattern.into_owned(); + + let suffix = pattern[wildcard_index + 1..].into(); pattern.truncate(wildcard_index); AliasPattern::Wildcard { - prefix: pattern, + prefix: pattern.into(), suffix, } } else { - AliasPattern::Exact(pattern.to_string()) + AliasPattern::Exact(pattern) } } /// Creates a pattern that will only match exactly what was passed in. pub fn exact<'a, T>(pattern: T) -> Self where - T: Into + 'a, + T: Into + 'a, { AliasPattern::Exact(pattern.into()) } @@ -533,8 +540,8 @@ impl AliasPattern { /// 3. a suffix. pub fn wildcard<'p, 's, P, S>(prefix: P, suffix: S) -> Self where - P: Into + 'p, - S: Into + 's, + P: Into + 'p, + S: Into + 's, { AliasPattern::Wildcard { prefix: prefix.into(), @@ -546,7 +553,7 @@ impl AliasPattern { #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, TraceRawVcs)] enum AliasKey { Exact, - Wildcard { suffix: String }, + Wildcard { suffix: RcStr }, } /// Result of a lookup in the alias map. diff --git a/crates/turbopack-core/src/resolve/mod.rs b/crates/turbopack-core/src/resolve/mod.rs index 84c324a53a3aa..12b7329b318ed 100644 --- a/crates/turbopack-core/src/resolve/mod.rs +++ b/crates/turbopack-core/src/resolve/mod.rs @@ -11,7 +11,7 @@ use anyhow::{bail, Result}; use indexmap::{indexmap, IndexMap, IndexSet}; use serde::{Deserialize, Serialize}; use tracing::{Instrument, Level}; -use turbo_tasks::{trace::TraceRawVcs, TryJoinIterExt, Value, ValueToString, Vc}; +use turbo_tasks::{trace::TraceRawVcs, RcStr, TryJoinIterExt, Value, ValueToString, Vc}; use turbo_tasks_fs::{ util::{normalize_path, normalize_request}, FileSystemEntryType, FileSystemPath, RealPathResult, @@ -65,9 +65,9 @@ use crate::{error::PrettyPrintError, issue::IssueSeverity}; pub enum ModuleResolveResultItem { Module(Vc>), OutputAsset(Vc>), - External(String, ExternalType), + External(RcStr, ExternalType), Ignore, - Error(Vc), + Error(Vc), Empty, Custom(u8), Unresolveable, @@ -415,9 +415,9 @@ impl Display for ExternalType { #[derive(Clone, Debug)] pub enum ResolveResultItem { Source(Vc>), - External(String, ExternalType), + External(RcStr, ExternalType), Ignore, - Error(Vc), + Error(Vc), Empty, Custom(u8), Unresolveable, @@ -430,7 +430,7 @@ pub enum ResolveResultItem { #[derive(Clone, Debug, Default, Hash, Ord, PartialOrd)] #[turbo_tasks::value(serialization = "auto_for_input")] pub struct RequestKey { - pub request: Option, + pub request: Option, pub conditions: BTreeMap, } @@ -456,7 +456,7 @@ impl Display for RequestKey { } impl RequestKey { - pub fn new(request: String) -> Self { + pub fn new(request: RcStr) -> Self { RequestKey { request: Some(request), ..Default::default() @@ -480,7 +480,7 @@ impl Default for ResolveResult { #[turbo_tasks::value_impl] impl ValueToString for ResolveResult { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { + async fn to_string(&self) -> Result> { let mut result = String::new(); for (i, (request, item)) in self.primary.iter().enumerate() { if i > 0 { @@ -524,7 +524,7 @@ impl ValueToString for ResolveResult { } result.push(')'); } - Ok(Vc::cell(result)) + Ok(Vc::cell(result.into())) } } @@ -712,7 +712,7 @@ impl ResolveResult { /// Returns a new [ResolveResult] where all [RequestKey]s are set to the /// passed `request`. - pub fn with_request_ref(&self, request: String) -> Self { + pub fn with_request_ref(&self, request: RcStr) -> Self { let new_primary = self .primary .iter() @@ -896,7 +896,7 @@ impl ResolveResult { #[turbo_tasks::function] pub async fn with_replaced_request_key( self: Vc, - old_request_key: String, + old_request_key: RcStr, request_key: Value, ) -> Result> { let this = self.await?; @@ -905,13 +905,13 @@ impl ResolveResult { .primary .iter() .filter_map(|(k, v)| { - let remaining = k.request.as_ref()?.strip_prefix(&old_request_key)?; + let remaining = k.request.as_ref()?.strip_prefix(&*old_request_key)?; Some(( RequestKey { request: request_key .request .as_ref() - .map(|r| format!("{}{}", r, remaining)), + .map(|r| format!("{}{}", r, remaining).into()), conditions: request_key.conditions.clone(), }, v.clone(), @@ -928,7 +928,7 @@ impl ResolveResult { /// Returns a new [ResolveResult] where all [RequestKey]s are set to the /// passed `request`. #[turbo_tasks::function] - pub async fn with_request(self: Vc, request: String) -> Result> { + pub async fn with_request(self: Vc, request: RcStr) -> Result> { let this = self.await?; let new_primary = this .primary @@ -1044,7 +1044,7 @@ async fn exports_field(package_json_path: Vc) -> Result { PackageJsonIssue { path: package_json_path, - error_message: err.to_string(), + error_message: err.to_string().into(), } .cell() .emit(); @@ -1085,7 +1085,7 @@ async fn imports_field(lookup_path: Vc) -> Result { PackageJsonIssue { path: *package_json_path, - error_message: err.to_string(), + error_message: err.to_string().into(), } .cell() .emit(); @@ -1095,8 +1095,8 @@ async fn imports_field(lookup_path: Vc) -> Result Vc> { - Vc::cell(vec!["package.json".to_string()]) +pub fn package_json() -> Vc> { + Vc::cell(vec!["package.json".into()]) } #[turbo_tasks::value(shared)] @@ -1108,7 +1108,7 @@ pub enum FindContextFileResult { #[turbo_tasks::function] pub async fn find_context_file( lookup_path: Vc, - names: Vc>, + names: Vc>, ) -> Result> { let mut refs = Vec::new(); let context_value = lookup_path.await?; @@ -1158,7 +1158,7 @@ struct FindPackageResult { #[turbo_tasks::function] async fn find_package( lookup_path: Vc, - package_name: String, + package_name: RcStr, options: Vc, ) -> Result> { let mut packages = vec![]; @@ -1258,7 +1258,7 @@ pub async fn resolve_raw( async fn to_result(request: &str, path: Vc) -> Result> { let RealPathResult { path, symlinks } = &*path.realpath_with_links().await?; Ok(ResolveResult::source_with_affecting_sources( - RequestKey::new(request.to_string()), + RequestKey::new(request.into()), Vc::upcast(FileSource::new(*path)), symlinks .iter() @@ -1279,7 +1279,7 @@ pub async fn resolve_raw( .and_then(|pat| pat.filter_could_not_match("/ROOT/fsd8nz8og54z")) { let path = Pattern::new(pat); - let matches = read_matches(lookup_dir.root(), "/ROOT/".to_string(), true, path).await?; + let matches = read_matches(lookup_dir.root(), "/ROOT/".into(), true, path).await?; if matches.len() > 10000 { let path_str = path.to_string().await?; println!( @@ -1298,7 +1298,7 @@ pub async fn resolve_raw( } { - let matches = read_matches(lookup_dir, "".to_string(), force_in_lookup_dir, path).await?; + let matches = read_matches(lookup_dir, "".into(), force_in_lookup_dir, path).await?; if matches.len() > 10000 { println!( "WARN: resolving pattern {} in {} leads to {} results", @@ -1334,12 +1334,12 @@ pub async fn resolve_inline( options: Vc, ) -> Result> { let span = { - let lookup_path = lookup_path.to_string().await?; - let request = request.to_string().await?; + let lookup_path = lookup_path.to_string().await?.to_string(); + let request = request.to_string().await?.to_string(); tracing::info_span!( "resolving", - lookup_path = *lookup_path, - request = *request, + lookup_path = lookup_path, + request = request, reference_type = display(&reference_type), ) }; @@ -1528,12 +1528,12 @@ async fn resolve_internal_inline( options: Vc, ) -> Result> { let span = { - let lookup_path = lookup_path.to_string().await?; - let request = request.to_string().await?; + let lookup_path = lookup_path.to_string().await?.to_string(); + let request = request.to_string().await?.to_string(); tracing::info_span!( "internal resolving", - lookup_path = *lookup_path, - request = *request + lookup_path = lookup_path, + request = request ) }; async move { @@ -1592,7 +1592,7 @@ async fn resolve_internal_inline( let mut results = Vec::new(); let matches = read_matches( lookup_path, - "".to_string(), + "".into(), *force_in_lookup_dir, Pattern::new(path.clone()).resolve().await?, ) @@ -1657,7 +1657,7 @@ async fn resolve_internal_inline( path, *query, *force_in_lookup_dir, - Vc::cell(String::new()), + Vc::cell(RcStr::default()), ) .await? } @@ -1685,7 +1685,7 @@ async fn resolve_internal_inline( fragment, } => { let mut new_pat = path.clone(); - new_pat.push_front(".".to_string().into()); + new_pat.push_front(RcStr::from(".").into()); let relative = Request::relative(Value::new(new_pat), *query, *fragment, true); if !has_alias { @@ -1764,7 +1764,7 @@ async fn resolve_internal_inline( query: _, fragment: _, } => { - let uri = format!("{}{}", protocol, remainder); + let uri: RcStr = format!("{}{}", protocol, remainder).into(); ResolveResult::primary_with_key( RequestKey::new(uri.clone()), ResolveResultItem::External(uri, ExternalType::Url), @@ -1821,18 +1821,18 @@ async fn resolve_into_folder( package_path: Vc, options: Vc, ) -> Result> { - let package_json_path = package_path.join("package.json".to_string()); + let package_json_path = package_path.join("package.json".into()); let options_value = options.await?; for resolve_into_package in options_value.into_package.iter() { match resolve_into_package { ResolveIntoPackage::MainField { field: name } => { if let Some(package_json) = &*read_package_json(package_json_path).await? { - if let Some(field_value) = package_json[name].as_str() { - let normalized_request = normalize_request(field_value); + if let Some(field_value) = package_json[name.as_str()].as_str() { + let normalized_request: RcStr = normalize_request(field_value).into(); if normalized_request.is_empty() - || normalized_request == "." - || normalized_request == "./" + || &*normalized_request == "." + || &*normalized_request == "./" { continue; } @@ -1850,7 +1850,7 @@ async fn resolve_into_folder( // we are not that strict when a main field fails to resolve // we continue to try other alternatives if !result.is_unresolveable_ref() { - let mut result = result.with_request_ref(".".to_string()); + let mut result = result.with_request_ref(".".into()); result.add_affecting_source_ref(Vc::upcast(FileSource::new( package_json_path, ))); @@ -1870,11 +1870,11 @@ async fn resolve_into_folder( // fall back to dir/index.[js,ts,...] let pattern = match &options_value.default_files[..] { [] => return Ok(ResolveResult::unresolveable().into()), - [file] => Pattern::Constant(format!("./{file}")), + [file] => Pattern::Constant(format!("./{file}").into()), files => Pattern::Alternatives( files .iter() - .map(|file| Pattern::Constant(format!("./{file}"))) + .map(|file| Pattern::Constant(format!("./{file}").into())) .collect(), ), }; @@ -1884,7 +1884,7 @@ async fn resolve_into_folder( Ok( resolve_internal_inline(package_path, request.resolve().await?, options) .await? - .with_request(".".to_string()), + .with_request(".".into()), ) } @@ -1895,9 +1895,9 @@ async fn resolve_relative_request( options: Vc, options_value: &ResolveOptions, path_pattern: &Pattern, - query: Vc, + query: Vc, force_in_lookup_dir: bool, - fragment: Vc, + fragment: Vc, ) -> Result> { // Check alias field for aliases first let lookup_path_ref = &*lookup_path.await?; @@ -1909,7 +1909,7 @@ async fn resolve_relative_request( let request = path_pattern.as_string()?; let prefix_path = package_path.get_path_to(lookup_path_ref)?; let request = normalize_request(&format!("./{prefix_path}/{request}")); - Some(request) + Some(request.into()) }, query, fragment, @@ -1925,8 +1925,8 @@ async fn resolve_relative_request( if !fragment_val.is_empty() { new_path.push(Pattern::Alternatives( - once(Pattern::Constant("".to_string())) - .chain(once(Pattern::Constant(format!("#{fragment_val}")))) + once(Pattern::Constant("".into())) + .chain(once(Pattern::Constant(format!("#{fragment_val}").into()))) .collect(), )); } @@ -1935,7 +1935,7 @@ async fn resolve_relative_request( // Add the extensions as alternatives to the path // read_matches keeps the order of alternatives intact new_path.push(Pattern::Alternatives( - once(Pattern::Constant("".to_string())) + once(Pattern::Constant("".into())) .chain( options_value .extensions @@ -1951,7 +1951,7 @@ async fn resolve_relative_request( let mut results = Vec::new(); let matches = read_matches( lookup_path, - "".to_string(), + "".into(), force_in_lookup_dir, Pattern::new(new_path).resolve().await?, ) @@ -1962,7 +1962,7 @@ async fn resolve_relative_request( let mut pushed = false; if !options_value.fully_specified { for ext in options_value.extensions.iter() { - let Some(matched_pattern) = matched_pattern.strip_suffix(ext) else { + let Some(matched_pattern) = matched_pattern.strip_suffix(&**ext) else { continue; }; @@ -1975,14 +1975,14 @@ async fn resolve_relative_request( { results.push( resolved( - RequestKey::new(matched_pattern.to_string()), + RequestKey::new(matched_pattern.into()), *path, lookup_path, request, options_value, options, query, - Vc::cell(String::new()), + Vc::cell(RcStr::default()), ) .await?, ); @@ -1992,7 +1992,7 @@ async fn resolve_relative_request( if !pushed && path_pattern.is_match(matched_pattern) { results.push( resolved( - RequestKey::new(matched_pattern.to_string()), + RequestKey::new(matched_pattern.into()), *path, lookup_path, request, @@ -2015,14 +2015,14 @@ async fn resolve_relative_request( { results.push( resolved( - RequestKey::new(matched_pattern.to_string()), + RequestKey::new(matched_pattern.into()), *path, lookup_path, request, options_value, options, query, - Vc::cell(String::new()), + Vc::cell(RcStr::default()), ) .await?, ); @@ -2062,9 +2062,9 @@ async fn apply_in_package( lookup_path: Vc, options: Vc, options_value: &ResolveOptions, - get_request: impl Fn(&FileSystemPath) -> Option, - query: Vc, - fragment: Vc, + get_request: impl Fn(&FileSystemPath) -> Option, + query: Vc, + fragment: Vc, ) -> Result>> { // Check alias field for module aliases first for in_package in options_value.in_package.iter() { @@ -2086,7 +2086,7 @@ async fn apply_in_package( continue; }; - let Some(field_value) = package_json[field].as_object() else { + let Some(field_value) = package_json[field.as_str()].as_object() else { continue; }; @@ -2096,7 +2096,7 @@ async fn apply_in_package( continue; }; - let value = if let Some(value) = field_value.get(&request) { + let value = if let Some(value) = field_value.get(&*request) { value } else if let Some(request) = request.strip_prefix("./") { let Some(value) = field_value.get(request) else { @@ -2122,19 +2122,19 @@ async fn apply_in_package( } if let Some(value) = value.as_str() { - if value == request { + if value == &*request { // This would be a cycle, so we ignore it return Ok(None); } return Ok(Some( resolve_internal( package_path, - Request::parse(Value::new(Pattern::Constant(value.to_string()))) + Request::parse(Value::new(Pattern::Constant(value.into()))) .with_query(query) .with_fragment(fragment), options, ) - .with_replaced_request_key(value.to_string(), Value::new(request_key)) + .with_replaced_request_key(value.into(), Value::new(request_key)) .with_affecting_sources(refs), )); } @@ -2143,7 +2143,7 @@ async fn apply_in_package( severity: IssueSeverity::Error.cell(), file_path: *package_json_path, request_type: format!("alias field ({field})"), - request: Request::parse(Value::new(Pattern::Constant(request.to_string()))), + request: Request::parse(Value::new(Pattern::Constant(request))), resolve_options: options, error_message: Some(format!("invalid alias field value: {}", value)), source: None, @@ -2166,8 +2166,8 @@ async fn resolve_module_request( options_value: &ResolveOptions, module: &str, path: &Pattern, - query: Vc, - fragment: Vc, + query: Vc, + fragment: Vc, ) -> Result> { // Check alias field for module aliases first if let Some(result) = apply_in_package( @@ -2175,7 +2175,7 @@ async fn resolve_module_request( options, options_value, |_| { - let full_pattern = Pattern::concat([module.to_string().into(), path.clone()]); + let full_pattern = Pattern::concat([RcStr::from(module).into(), path.clone()]); full_pattern.into_string() }, query, @@ -2190,7 +2190,7 @@ async fn resolve_module_request( let result = find_package( lookup_path, - module.to_string(), + module.into(), resolve_modules_options(options).resolve().await?, ) .await?; @@ -2221,7 +2221,7 @@ async fn resolve_module_request( FindPackageItem::PackageFile(package_path) => { if path.is_match("") { let resolved = resolved( - RequestKey::new(".".to_string()), + RequestKey::new(".".into()), package_path, lookup_path, request, @@ -2239,25 +2239,20 @@ async fn resolve_module_request( let module_result = merge_results_with_affecting_sources(results, result.affecting_sources.clone()) - .with_replaced_request_key( - ".".to_string(), - Value::new(RequestKey::new(module.to_string())), - ); + .with_replaced_request_key(".".into(), Value::new(RequestKey::new(module.into()))); if options_value.prefer_relative { - let module_prefix = format!("./{module}"); + let module_prefix: RcStr = format!("./{module}").into(); let pattern = Pattern::concat([ module_prefix.clone().into(), - "/".to_string().into(), + RcStr::from("/").into(), path.clone(), ]); let relative = Request::relative(Value::new(pattern), query, fragment, true); let relative_result = resolve_internal_boxed(lookup_path, relative.resolve().await?, options).await?; - let relative_result = relative_result.with_replaced_request_key( - module_prefix, - Value::new(RequestKey::new(module.to_string())), - ); + let relative_result = relative_result + .with_replaced_request_key(module_prefix, Value::new(RequestKey::new(module.into()))); Ok(merge_results(vec![relative_result, module_result])) } else { @@ -2269,8 +2264,8 @@ async fn resolve_module_request( async fn resolve_into_package( path: Value, package_path: Vc, - query: Vc, - fragment: Vc, + query: Vc, + fragment: Vc, options: Vc, ) -> Result> { let path = path.into_value(); @@ -2288,7 +2283,7 @@ async fn resolve_into_package( conditions, unspecified_conditions, } => { - let package_json_path = package_path.join("package.json".to_string()); + let package_json_path = package_path.join("package.json".into()); let ExportsFieldResult::Some(exports_field) = &*exports_field(package_json_path).await? else { @@ -2299,7 +2294,7 @@ async fn resolve_into_package( todo!("pattern into an exports field is not implemented yet"); }; - let path = if path == "/" { + let path = if &*path == "/" { ".".to_string() } else { format!(".{path}") @@ -2333,7 +2328,7 @@ async fn resolve_into_package( if could_match_others { let mut new_pat = path.clone(); - new_pat.push_front(".".to_string().into()); + new_pat.push_front(RcStr::from(".").into()); let relative = Request::relative(Value::new(new_pat), query, fragment, true); results @@ -2350,7 +2345,7 @@ async fn resolve_import_map_result( original_lookup_path: Vc, original_request: Vc, options: Vc, - query: Vc, + query: Vc, ) -> Result>> { Ok(match result { ImportMapResult::Result(result) => Some(*result), @@ -2398,7 +2393,7 @@ fn resolve_import_map_result_boxed<'a>( original_lookup_path: Vc, original_request: Vc, options: Vc, - query: Vc, + query: Vc, ) -> Pin + Send + 'a>> { Box::pin(resolve_import_map_result( result, @@ -2418,8 +2413,8 @@ async fn resolved( original_request: Vc, options_value: &ResolveOptions, options: Vc, - query: Vc, - fragment: Vc, + query: Vc, + fragment: Vc, ) -> Result> { let RealPathResult { path, symlinks } = &*fs_path.realpath_with_links().await?; @@ -2477,9 +2472,9 @@ async fn handle_exports_imports_field( options: Vc, exports_imports_field: &AliasMap, path: &str, - conditions: &BTreeMap, + conditions: &BTreeMap, unspecified_conditions: &ConditionValue, - query: Vc, + query: Vc, ) -> Result> { let mut results = Vec::new(); let mut conditions_state = HashMap::new(); @@ -2506,12 +2501,13 @@ async fn handle_exports_imports_field( let mut resolved_results = Vec::new(); for (result_path, conditions) in results { if let Some(result_path) = normalize_path(result_path) { - let request = Request::parse(Value::new(format!("./{}", result_path).into())); + let request = + Request::parse(Value::new(RcStr::from(format!("./{}", result_path)).into())); let resolve_result = resolve_internal_boxed(package_path, request, options).await?; if conditions.is_empty() { - resolved_results.push(resolve_result.with_request(path.to_string())); + resolved_results.push(resolve_result.with_request(path.into())); } else { - let mut resolve_result = resolve_result.await?.with_request_ref(path.to_string()); + let mut resolve_result = resolve_result.await?.with_request_ref(path.into()); resolve_result.add_conditions(conditions); resolved_results.push(resolve_result.cell()); } @@ -2534,7 +2530,7 @@ async fn resolve_package_internal_with_imports_field( request: Vc, resolve_options: Vc, pattern: &Pattern, - conditions: &BTreeMap, + conditions: &BTreeMap, unspecified_conditions: &ConditionValue, ) -> Result> { let Pattern::Constant(specifier) = pattern else { @@ -2570,7 +2566,7 @@ async fn resolve_package_internal_with_imports_field( specifier, conditions, unspecified_conditions, - Vc::::default(), + Vc::::default(), ) .await } @@ -2629,14 +2625,14 @@ pub enum ModulePart { /// all exports are unused. Evaluation, /// Represents an export of a module. - Export(Vc), + Export(Vc), /// Represents a renamed export of a module. RenamedExport { - original_export: Vc, - export: Vc, + original_export: Vc, + export: Vc, }, /// Represents a namespace object of a module exported as named export. - RenamedNamespace { export: Vc }, + RenamedNamespace { export: Vc }, /// A pointer to a specific part. Internal(u32), /// The local declarations of a module. @@ -2655,11 +2651,11 @@ impl ModulePart { ModulePart::Evaluation.cell() } #[turbo_tasks::function] - pub fn export(export: String) -> Vc { + pub fn export(export: RcStr) -> Vc { ModulePart::Export(Vc::cell(export)).cell() } #[turbo_tasks::function] - pub fn renamed_export(original_export: String, export: String) -> Vc { + pub fn renamed_export(original_export: RcStr, export: RcStr) -> Vc { ModulePart::RenamedExport { original_export: Vc::cell(original_export), export: Vc::cell(export), @@ -2667,7 +2663,7 @@ impl ModulePart { .cell() } #[turbo_tasks::function] - pub fn renamed_namespace(export: String) -> Vc { + pub fn renamed_namespace(export: RcStr) -> Vc { ModulePart::RenamedNamespace { export: Vc::cell(export), } @@ -2694,25 +2690,25 @@ impl ModulePart { #[turbo_tasks::value_impl] impl ValueToString for ModulePart { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { + async fn to_string(&self) -> Result> { Ok(Vc::cell(match self { - ModulePart::Evaluation => "module evaluation".to_string(), - ModulePart::Export(export) => format!("export {}", export.await?), + ModulePart::Evaluation => "module evaluation".into(), + ModulePart::Export(export) => format!("export {}", export.await?).into(), ModulePart::RenamedExport { original_export, export, } => { let original_export = original_export.await?; let export = export.await?; - format!("export {} as {}", original_export, export) + format!("export {} as {}", original_export, export).into() } ModulePart::RenamedNamespace { export } => { - format!("export * as {}", export.await?) + format!("export * as {}", export.await?).into() } - ModulePart::Internal(id) => format!("internal part {}", id), - ModulePart::Locals => "locals".to_string(), - ModulePart::Exports => "exports".to_string(), - ModulePart::Facade => "facade".to_string(), + ModulePart::Internal(id) => format!("internal part {}", id).into(), + ModulePart::Locals => "locals".into(), + ModulePart::Exports => "exports".into(), + ModulePart::Facade => "facade".into(), })) } } diff --git a/crates/turbopack-core/src/resolve/node.rs b/crates/turbopack-core/src/resolve/node.rs index e0c07728c8e48..efcab014270c6 100644 --- a/crates/turbopack-core/src/resolve/node.rs +++ b/crates/turbopack-core/src/resolve/node.rs @@ -9,31 +9,28 @@ use super::options::{ #[turbo_tasks::function] pub fn node_cjs_resolve_options(root: Vc) -> Vc { let conditions: ResolutionConditions = [ - ("node".to_string(), ConditionValue::Set), - ("require".to_string(), ConditionValue::Set), + ("node".into(), ConditionValue::Set), + ("require".into(), ConditionValue::Set), ] .into(); - let extensions = vec![".js".to_string(), ".json".to_string(), ".node".to_string()]; + let extensions = vec![".js".into(), ".json".into(), ".node".into()]; ResolveOptions { extensions, - modules: vec![ResolveModules::Nested( - root, - vec!["node_modules".to_string()], - )], + modules: vec![ResolveModules::Nested(root, vec!["node_modules".into()])], into_package: vec![ ResolveIntoPackage::ExportsField { conditions: conditions.clone(), unspecified_conditions: ConditionValue::Unset, }, ResolveIntoPackage::MainField { - field: "main".to_string(), + field: "main".into(), }, ], in_package: vec![ResolveInPackage::ImportsField { conditions, unspecified_conditions: ConditionValue::Unset, }], - default_files: vec!["index".to_string()], + default_files: vec!["index".into()], ..Default::default() } .cell() @@ -42,32 +39,29 @@ pub fn node_cjs_resolve_options(root: Vc) -> Vc #[turbo_tasks::function] pub fn node_esm_resolve_options(root: Vc) -> Vc { let conditions: ResolutionConditions = [ - ("node".to_string(), ConditionValue::Set), - ("import".to_string(), ConditionValue::Set), + ("node".into(), ConditionValue::Set), + ("import".into(), ConditionValue::Set), ] .into(); - let extensions = vec![".js".to_string(), ".json".to_string(), ".node".to_string()]; + let extensions = vec![".js".into(), ".json".into(), ".node".into()]; ResolveOptions { fully_specified: true, extensions, - modules: vec![ResolveModules::Nested( - root, - vec!["node_modules".to_string()], - )], + modules: vec![ResolveModules::Nested(root, vec!["node_modules".into()])], into_package: vec![ ResolveIntoPackage::ExportsField { conditions: conditions.clone(), unspecified_conditions: ConditionValue::Unset, }, ResolveIntoPackage::MainField { - field: "main".to_string(), + field: "main".into(), }, ], in_package: vec![ResolveInPackage::ImportsField { conditions, unspecified_conditions: ConditionValue::Unset, }], - default_files: vec!["index".to_string()], + default_files: vec!["index".into()], ..Default::default() } .cell() diff --git a/crates/turbopack-core/src/resolve/options.rs b/crates/turbopack-core/src/resolve/options.rs index fdcd931ad335b..7472b946f9635 100644 --- a/crates/turbopack-core/src/resolve/options.rs +++ b/crates/turbopack-core/src/resolve/options.rs @@ -3,7 +3,7 @@ use std::{collections::BTreeMap, future::Future, pin::Pin}; use anyhow::{bail, Result}; use serde::{Deserialize, Serialize}; use turbo_tasks::{ - debug::ValueDebugFormat, trace::TraceRawVcs, TryJoinIterExt, Value, ValueToString, Vc, + debug::ValueDebugFormat, trace::TraceRawVcs, RcStr, TryJoinIterExt, Value, ValueToString, Vc, }; use turbo_tasks_fs::{glob::Glob, FileSystemPath}; @@ -25,7 +25,7 @@ pub struct LockedVersions {} pub enum ResolveModules { /// when inside of path, use the list of directories to /// resolve inside these - Nested(Vc, Vec), + Nested(Vc, Vec), /// look into that directory Path(Vc), /// lookup versions based on lockfile in the registry filesystem @@ -51,7 +51,7 @@ impl From for ConditionValue { } } -pub type ResolutionConditions = BTreeMap; +pub type ResolutionConditions = BTreeMap; /// The different ways to resolve a package, as described in package.json. #[derive(TraceRawVcs, Hash, PartialEq, Eq, Clone, Debug, Serialize, Deserialize)] @@ -68,14 +68,14 @@ pub enum ResolveIntoPackage { /// [main]: https://nodejs.org/api/packages.html#main /// [module]: https://esbuild.github.io/api/#main-fields /// [browser]: https://esbuild.github.io/api/#main-fields - MainField { field: String }, + MainField { field: RcStr }, } // The different ways to resolve a request withing a package #[derive(TraceRawVcs, Hash, PartialEq, Eq, Clone, Debug, Serialize, Deserialize)] pub enum ResolveInPackage { /// Using a alias field which allows to map requests - AliasField(String), + AliasField(RcStr), /// Using the [imports] field. /// /// [imports]: https://nodejs.org/api/packages.html#imports @@ -88,13 +88,13 @@ pub enum ResolveInPackage { #[turbo_tasks::value(shared)] #[derive(Clone)] pub enum ImportMapping { - External(Option, ExternalType), + External(Option, ExternalType), /// An already resolved result that will be returned directly. Direct(Vc), /// A request alias that will be resolved first, and fall back to resolving /// the original request if it fails. Useful for the tsconfig.json /// `compilerOptions.paths` option and Next aliases. - PrimaryAlternative(String, Option>), + PrimaryAlternative(RcStr, Option>), Ignore, Empty, Alternatives(Vec>), @@ -103,7 +103,7 @@ pub enum ImportMapping { impl ImportMapping { pub fn primary_alternatives( - list: Vec, + list: Vec, lookup_path: Option>, ) -> ImportMapping { if list.is_empty() { @@ -129,13 +129,19 @@ impl AliasTemplate for Vc { Ok(match this { ImportMapping::External(name, ty) => { if let Some(name) = name { - ImportMapping::External(Some(name.clone().replace('*', capture)), *ty) + ImportMapping::External( + Some(name.clone().replace('*', capture).into()), + *ty, + ) } else { ImportMapping::External(None, *ty) } } ImportMapping::PrimaryAlternative(name, context) => { - ImportMapping::PrimaryAlternative(name.clone().replace('*', capture), *context) + ImportMapping::PrimaryAlternative( + name.clone().replace('*', capture).into(), + *context, + ) } ImportMapping::Direct(_) | ImportMapping::Ignore | ImportMapping::Empty => { this.clone() @@ -148,7 +154,7 @@ impl AliasTemplate for Vc { .await?, ), ImportMapping::Dynamic(replacement) => { - (*replacement.replace(capture.to_string()).await?).clone() + (*replacement.replace(capture.into()).await?).clone() } } .cell()) @@ -187,7 +193,7 @@ impl ImportMap { /// Inserts an exact alias into the import map. pub fn insert_exact_alias<'a>( &mut self, - pattern: impl Into + 'a, + pattern: impl Into + 'a, mapping: Vc, ) { self.map.insert(AliasPattern::exact(pattern), mapping); @@ -196,7 +202,7 @@ impl ImportMap { /// Inserts a wildcard alias into the import map. pub fn insert_wildcard_alias<'a>( &mut self, - prefix: impl Into + 'a, + prefix: impl Into + 'a, mapping: Vc, ) { self.map.insert(AliasPattern::wildcard(prefix, ""), mapping); @@ -205,8 +211,8 @@ impl ImportMap { /// Inserts a wildcard alias with suffix into the import map. pub fn insert_wildcard_alias_with_suffix<'p, 's>( &mut self, - prefix: impl Into + 'p, - suffix: impl Into + 's, + prefix: impl Into + 'p, + suffix: impl Into + 's, mapping: Vc, ) { self.map @@ -217,14 +223,14 @@ impl ImportMap { /// to create a singleton. pub fn insert_singleton_alias<'a>( &mut self, - prefix: impl Into + 'a, + prefix: impl Into + 'a, context_path: Vc, ) { - let prefix = prefix.into(); - let wildcard_prefix = prefix.clone() + "/"; - let wildcard_alias: String = prefix.clone() + "/*"; + let prefix: RcStr = prefix.into(); + let wildcard_prefix: RcStr = (prefix.to_string() + "/").into(); + let wildcard_alias: RcStr = (prefix.to_string() + "/*").into(); self.insert_exact_alias( - &prefix, + prefix.clone(), ImportMapping::PrimaryAlternative(prefix.clone(), Some(context_path)).cell(), ); self.insert_wildcard_alias( @@ -269,7 +275,7 @@ async fn import_mapping_to_result( ImportMapping::Direct(result) => ImportMapResult::Result(*result), ImportMapping::External(name, ty) => ImportMapResult::Result( ResolveResult::primary(if let Some(name) = name { - ResolveResultItem::External(name.to_string(), *ty) + ResolveResultItem::External(name.clone(), *ty) } else if let Some(request) = request.await?.request() { ResolveResultItem::External(request, *ty) } else { @@ -284,7 +290,7 @@ async fn import_mapping_to_result( ImportMapResult::Result(ResolveResult::primary(ResolveResultItem::Empty).into()) } ImportMapping::PrimaryAlternative(name, context) => { - let request = Request::parse(Value::new(name.to_string().into())); + let request = Request::parse(Value::new(name.clone().into())); ImportMapResult::Alias(request, *context) } @@ -303,9 +309,9 @@ async fn import_mapping_to_result( #[turbo_tasks::value_impl] impl ValueToString for ImportMapResult { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { + async fn to_string(&self) -> Result> { match self { - ImportMapResult::Result(_) => Ok(Vc::cell("Resolved by import map".to_string())), + ImportMapResult::Result(_) => Ok(Vc::cell("Resolved by import map".into())), ImportMapResult::Alias(request, context) => { let s = if let Some(path) = context { let path = path.to_string().await?; @@ -317,7 +323,7 @@ impl ValueToString for ImportMapResult { } else { format!("aliased to {}", request.to_string().await?) }; - Ok(Vc::cell(s)) + Ok(Vc::cell(s.into())) } ImportMapResult::Alternatives(alternatives) => { let strings = alternatives @@ -329,9 +335,9 @@ impl ValueToString for ImportMapResult { .iter() .map(|string| string.as_str()) .collect::>(); - Ok(Vc::cell(strings.join(" | "))) + Ok(Vc::cell(strings.join(" | ").into())) } - ImportMapResult::NoEntry => Ok(Vc::cell("No import map entry".to_string())), + ImportMapResult::NoEntry => Ok(Vc::cell("No import map entry".into())), } } } @@ -420,7 +426,7 @@ pub struct ResolveOptions { /// request first. pub prefer_relative: bool, /// The extensions that should be added to a request when resolving. - pub extensions: Vec, + pub extensions: Vec, /// The locations where to resolve modules. pub modules: Vec, /// How to resolve packages. @@ -428,7 +434,7 @@ pub struct ResolveOptions { /// How to resolve in packages. pub in_package: Vec, /// The default files to resolve in a folder. - pub default_files: Vec, + pub default_files: Vec, /// An import map to use before resolving a request. pub import_map: Option>, /// An import map to use when a request is otherwise unresolveable. @@ -477,7 +483,7 @@ impl ResolveOptions { /// Overrides the extensions used for resolving #[turbo_tasks::function] - pub async fn with_extensions(self: Vc, extensions: Vec) -> Result> { + pub async fn with_extensions(self: Vc, extensions: Vec) -> Result> { let mut resolve_options = self.await?.clone_value(); resolve_options.extensions = extensions; Ok(resolve_options.into()) @@ -500,7 +506,7 @@ impl ResolveOptions { #[derive(Hash, Clone, Debug)] pub struct ResolveModulesOptions { pub modules: Vec, - pub extensions: Vec, + pub extensions: Vec, } #[turbo_tasks::function] @@ -517,7 +523,7 @@ pub async fn resolve_modules_options( #[turbo_tasks::value_trait] pub trait ImportMappingReplacement { - fn replace(self: Vc, capture: String) -> Vc; + fn replace(self: Vc, capture: RcStr) -> Vc; fn result( self: Vc, lookup_path: Vc, diff --git a/crates/turbopack-core/src/resolve/origin.rs b/crates/turbopack-core/src/resolve/origin.rs index 54c8bec9b0c18..ca292c03e7681 100644 --- a/crates/turbopack-core/src/resolve/origin.rs +++ b/crates/turbopack-core/src/resolve/origin.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{Upcast, Value, Vc}; +use turbo_tasks::{RcStr, Upcast, Value, Vc}; use turbo_tasks_fs::FileSystemPath; use super::{options::ResolveOptions, parse::Request, ModuleResolveResult}; @@ -44,7 +44,7 @@ pub trait ResolveOriginExt: Send { fn resolve_options(self: Vc, reference_type: Value) -> Vc; /// Adds a transition that is used for resolved assets. - fn with_transition(self: Vc, transition: String) -> Vc>; + fn with_transition(self: Vc, transition: RcStr) -> Vc>; } impl ResolveOriginExt for T @@ -65,7 +65,7 @@ where .resolve_options(self.origin_path(), reference_type) } - fn with_transition(self: Vc, transition: String) -> Vc> { + fn with_transition(self: Vc, transition: RcStr) -> Vc> { Vc::upcast( ResolveOriginWithTransition { previous: Vc::upcast(self), @@ -137,7 +137,7 @@ impl ResolveOrigin for PlainResolveOrigin { #[turbo_tasks::value] struct ResolveOriginWithTransition { previous: Vc>, - transition: String, + transition: RcStr, } #[turbo_tasks::value_impl] diff --git a/crates/turbopack-core/src/resolve/parse.rs b/crates/turbopack-core/src/resolve/parse.rs index baf6256ce752d..c97e33cee4391 100644 --- a/crates/turbopack-core/src/resolve/parse.rs +++ b/crates/turbopack-core/src/resolve/parse.rs @@ -1,7 +1,7 @@ use anyhow::Result; use lazy_static::lazy_static; use regex::Regex; -use turbo_tasks::{TryJoinIterExt, Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, TryJoinIterExt, Value, ValueToString, Vc}; use super::pattern::Pattern; @@ -10,31 +10,31 @@ use super::pattern::Pattern; pub enum Request { Raw { path: Pattern, - query: Vc, + query: Vc, force_in_lookup_dir: bool, - fragment: Vc, + fragment: Vc, }, Relative { path: Pattern, - query: Vc, + query: Vc, force_in_lookup_dir: bool, - fragment: Vc, + fragment: Vc, }, Module { - module: String, + module: RcStr, path: Pattern, - query: Vc, - fragment: Vc, + query: Vc, + fragment: Vc, }, ServerRelative { path: Pattern, - query: Vc, - fragment: Vc, + query: Vc, + fragment: Vc, }, Windows { path: Pattern, - query: Vc, - fragment: Vc, + query: Vc, + fragment: Vc, }, Empty, PackageInternal { @@ -43,8 +43,8 @@ pub enum Request { Uri { protocol: String, remainder: String, - query: Vc, - fragment: Vc, + query: Vc, + fragment: Vc, }, Unknown { path: Pattern, @@ -55,69 +55,69 @@ pub enum Request { }, } -fn split_off_query_fragment(raw: String) -> (Pattern, Vc, Vc) { +fn split_off_query_fragment(raw: RcStr) -> (Pattern, Vc, Vc) { let Some((raw, query)) = raw.split_once('?') else { if let Some((raw, fragment)) = raw.split_once('#') { return ( - Pattern::Constant(raw.to_string()), - Vc::::default(), - Vc::cell(fragment.to_string()), + Pattern::Constant(raw.into()), + Vc::::default(), + Vc::cell(fragment.into()), ); } return ( Pattern::Constant(raw), - Vc::::default(), - Vc::::default(), + Vc::::default(), + Vc::::default(), ); }; let (query, fragment) = query.split_once('#').unwrap_or((query, "")); ( - Pattern::Constant(raw.to_string()), - Vc::cell(format!("?{}", query)), - Vc::cell(format!("#{}", fragment)), + Pattern::Constant(raw.into()), + Vc::cell(format!("?{}", query).into()), + Vc::cell(format!("#{}", fragment).into()), ) } impl Request { - pub fn request(&self) -> Option { + pub fn request(&self) -> Option { Some(match self { Request::Raw { path: Pattern::Constant(path), .. - } => path.to_string(), + } => path.clone(), Request::Relative { path: Pattern::Constant(path), .. - } => path.to_string(), + } => path.clone(), Request::Module { module, path: Pattern::Constant(path), .. - } => format!("{module}{path}"), + } => format!("{module}{path}").into(), Request::ServerRelative { path: Pattern::Constant(path), .. - } => path.to_string(), + } => path.clone(), Request::Windows { path: Pattern::Constant(path), .. - } => path.to_string(), - Request::Empty => "".to_string(), + } => path.clone(), + Request::Empty => "".into(), Request::PackageInternal { path: Pattern::Constant(path), .. - } => path.to_string(), + } => path.clone(), Request::Uri { protocol, remainder, .. - } => format!("{protocol}{remainder}"), + } => format!("{protocol}{remainder}").into(), Request::Unknown { path: Pattern::Constant(path), - } => path.to_string(), + } => path.clone(), _ => return None, }) } @@ -141,7 +141,7 @@ impl Request { Request::PackageInternal { path: Pattern::Constant(r), } - } else if r.starts_with("./") || r.starts_with("../") || r == "." || r == ".." { + } else if r.starts_with("./") || r.starts_with("../") || &*r == "." || &*r == ".." { let (path, query, fragment) = split_off_query_fragment(r); Request::Relative { @@ -174,8 +174,8 @@ impl Request { return Request::Uri { protocol: protocol.as_str().to_string(), remainder: remainder.as_str().to_string(), - query: Vc::::default(), - fragment: Vc::::default(), + query: Vc::::default(), + fragment: Vc::::default(), }; } } @@ -185,10 +185,10 @@ impl Request { .and_then(|caps| caps.get(1).zip(caps.get(2))) { let (path, query, fragment) = - split_off_query_fragment(path.as_str().to_string()); + split_off_query_fragment(path.as_str().into()); return Request::Module { - module: module.as_str().to_string(), + module: module.as_str().into(), path, query, fragment, @@ -259,15 +259,15 @@ impl Request { } #[turbo_tasks::function] - pub fn parse_string(request: String) -> Vc { + pub fn parse_string(request: RcStr) -> Vc { Self::cell(Request::parse_ref(request.into())) } #[turbo_tasks::function] pub fn raw( request: Value, - query: Vc, - fragment: Vc, + query: Vc, + fragment: Vc, force_in_lookup_dir: bool, ) -> Vc { Self::cell(Request::Raw { @@ -281,8 +281,8 @@ impl Request { #[turbo_tasks::function] pub fn relative( request: Value, - query: Vc, - fragment: Vc, + query: Vc, + fragment: Vc, force_in_lookup_dir: bool, ) -> Vc { Self::cell(Request::Relative { @@ -295,10 +295,10 @@ impl Request { #[turbo_tasks::function] pub fn module( - module: String, + module: RcStr, path: Value, - query: Vc, - fragment: Vc, + query: Vc, + fragment: Vc, ) -> Vc { Self::cell(Request::Module { module, @@ -325,18 +325,18 @@ impl Request { query: _, fragment: _, } => { - let mut pat = Pattern::Constant(format!("./{module}")); + let mut pat = Pattern::Constant(format!("./{module}").into()); pat.push(path.clone()); // TODO add query Self::parse(Value::new(pat)) } Request::PackageInternal { path } => { - let mut pat = Pattern::Constant("./".to_string()); + let mut pat = Pattern::Constant("./".into()); pat.push(path.clone()); Self::parse(Value::new(pat)) } Request::Unknown { path } => { - let mut pat = Pattern::Constant("./".to_string()); + let mut pat = Pattern::Constant("./".into()); pat.push(path.clone()); Self::parse(Value::new(pat)) } @@ -348,7 +348,7 @@ impl Request { } #[turbo_tasks::function] - pub async fn with_query(self: Vc, query: Vc) -> Result> { + pub async fn with_query(self: Vc, query: Vc) -> Result> { Ok(match &*self.await? { Request::Raw { path, @@ -423,7 +423,7 @@ impl Request { } #[turbo_tasks::function] - pub async fn with_fragment(self: Vc, fragment: Vc) -> Result> { + pub async fn with_fragment(self: Vc, fragment: Vc) -> Result> { Ok(match &*self.await? { Request::Raw { path, @@ -498,7 +498,7 @@ impl Request { } #[turbo_tasks::function] - pub async fn append_path(self: Vc, suffix: String) -> Result> { + pub async fn append_path(self: Vc, suffix: RcStr) -> Result> { Ok(match &*self.await? { Request::Raw { path, @@ -596,20 +596,20 @@ impl Request { } #[turbo_tasks::function] - pub fn query(&self) -> Vc { + pub fn query(&self) -> Vc { match self { Request::Raw { query, .. } => *query, Request::Relative { query, .. } => *query, Request::Module { query, .. } => *query, Request::ServerRelative { query, .. } => *query, Request::Windows { query, .. } => *query, - Request::Empty => Vc::::default(), - Request::PackageInternal { .. } => Vc::::default(), - Request::Uri { .. } => Vc::::default(), - Request::Unknown { .. } => Vc::::default(), - Request::Dynamic => Vc::::default(), + Request::Empty => Vc::::default(), + Request::PackageInternal { .. } => Vc::::default(), + Request::Uri { .. } => Vc::::default(), + Request::Unknown { .. } => Vc::::default(), + Request::Dynamic => Vc::::default(), // TODO: is this correct, should we return the first one instead? - Request::Alternatives { .. } => Vc::::default(), + Request::Alternatives { .. } => Vc::::default(), } } } @@ -617,7 +617,7 @@ impl Request { #[turbo_tasks::value_impl] impl ValueToString for Request { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { + async fn to_string(&self) -> Result> { Ok(Vc::cell(match self { Request::Raw { path, @@ -625,9 +625,9 @@ impl ValueToString for Request { .. } => { if *force_in_lookup_dir { - format!("in-lookup-dir {path}") + format!("in-lookup-dir {path}").into() } else { - format!("{path}") + format!("{path}").into() } } Request::Relative { @@ -636,35 +636,36 @@ impl ValueToString for Request { .. } => { if *force_in_lookup_dir { - format!("relative-in-lookup-dir {path}") + format!("relative-in-lookup-dir {path}").into() } else { - format!("relative {path}") + format!("relative {path}").into() } } Request::Module { module, path, .. } => { if path.could_match_others("") { - format!("module \"{module}\" with subpath {path}") + format!("module \"{module}\" with subpath {path}").into() } else { - format!("module \"{module}\"") + format!("module \"{module}\"").into() } } - Request::ServerRelative { path, .. } => format!("server relative {path}"), - Request::Windows { path, .. } => format!("windows {path}"), - Request::Empty => "empty".to_string(), - Request::PackageInternal { path } => format!("package internal {path}"), + Request::ServerRelative { path, .. } => format!("server relative {path}").into(), + Request::Windows { path, .. } => format!("windows {path}").into(), + Request::Empty => "empty".into(), + Request::PackageInternal { path } => format!("package internal {path}").into(), Request::Uri { protocol, remainder, .. - } => format!("uri \"{protocol}\" \"{remainder}\""), - Request::Unknown { path } => format!("unknown {path}"), - Request::Dynamic => "dynamic".to_string(), + } => format!("uri \"{protocol}\" \"{remainder}\"").into(), + Request::Unknown { path } => format!("unknown {path}").into(), + Request::Dynamic => "dynamic".into(), Request::Alternatives { requests } => { let vec = requests.iter().map(|i| i.to_string()).try_join().await?; vec.iter() .map(|r| r.as_str()) .collect::>() .join(" or ") + .into() } })) } diff --git a/crates/turbopack-core/src/resolve/pattern.rs b/crates/turbopack-core/src/resolve/pattern.rs index 2cb128cb9b571..825a3c766ff2d 100644 --- a/crates/turbopack-core/src/resolve/pattern.rs +++ b/crates/turbopack-core/src/resolve/pattern.rs @@ -5,7 +5,7 @@ use lazy_static::lazy_static; use regex::Regex; use serde::{Deserialize, Serialize}; use tracing::Instrument; -use turbo_tasks::{trace::TraceRawVcs, Value, ValueToString, Vc}; +use turbo_tasks::{trace::TraceRawVcs, RcStr, Value, ValueToString, Vc}; use turbo_tasks_fs::{ DirectoryContent, DirectoryEntry, FileSystemEntryType, FileSystemPath, LinkContent, LinkType, }; @@ -13,7 +13,7 @@ use turbo_tasks_fs::{ #[turbo_tasks::value(serialization = "auto_for_input")] #[derive(PartialOrd, Ord, Hash, Clone, Debug, Default)] pub enum Pattern { - Constant(String), + Constant(RcStr), #[default] Dynamic, Alternatives(Vec), @@ -23,7 +23,9 @@ pub enum Pattern { fn concatenation_push_or_merge_item(list: &mut Vec, pat: Pattern) { if let Pattern::Constant(ref s) = pat { if let Some(Pattern::Constant(ref mut last)) = list.last_mut() { - last.push_str(s); + let mut buf = last.to_string(); + buf.push_str(s); + *last = buf.into(); return; } } @@ -31,10 +33,12 @@ fn concatenation_push_or_merge_item(list: &mut Vec, pat: Pattern) { } fn concatenation_push_front_or_merge_item(list: &mut Vec, pat: Pattern) { - if let Pattern::Constant(mut s) = pat { + if let Pattern::Constant(s) = pat { if let Some(Pattern::Constant(ref mut first)) = list.iter_mut().next() { - s.push_str(first); - *first = s; + let mut buf = s.into_owned(); + buf.push_str(first); + + *first = buf.into(); return; } list.insert(0, Pattern::Constant(s)); @@ -55,7 +59,7 @@ fn concatenation_extend_or_merge_items( impl Pattern { // TODO this should be removed in favor of pattern resolving - pub fn into_string(self) -> Option { + pub fn into_string(self) -> Option { match self { Pattern::Constant(str) => Some(str), _ => None, @@ -107,7 +111,11 @@ impl Pattern { concatenation_push_front_or_merge_item(&mut list, take(this)); *this = Pattern::Concatenation(list); } - (Pattern::Constant(str), Pattern::Constant(other)) => str.push_str(&other), + (Pattern::Constant(str), Pattern::Constant(other)) => { + let mut buf = str.to_string(); + buf.push_str(&other); + *str = buf.into(); + } (this, pat) => { *this = Pattern::Concatenation(vec![take(this), pat]); } @@ -127,9 +135,11 @@ impl Pattern { concatenation_push_or_merge_item(&mut list, take(this)); *this = Pattern::Concatenation(list); } - (Pattern::Constant(str), Pattern::Constant(mut other)) => { - other.push_str(str); - *str = other; + (Pattern::Constant(str), Pattern::Constant(other)) => { + let mut buf = other.into_owned(); + + buf.push_str(str); + *str = buf.into(); } (this, pat) => { *this = Pattern::Concatenation(vec![pat, take(this)]); @@ -252,7 +262,9 @@ impl Pattern { if !c.is_empty() { if let Some(Pattern::Constant(last)) = new_parts.last_mut() { - last.push_str(&c); + let mut buf = last.to_string(); + buf.push_str(&c); + *last = buf.into(); } else { new_parts.push(Pattern::Constant(c)); } @@ -428,7 +440,7 @@ impl Pattern { match self { Pattern::Constant(c) => { if let Some(offset) = any_offset { - if let Some(index) = value.find(c) { + if let Some(index) = value.find(&**c) { if index <= offset { MatchResult::Consumed { remaining: &value[index + c.len()..], @@ -442,7 +454,7 @@ impl Pattern { } else { MatchResult::None } - } else if value.starts_with(c) { + } else if value.starts_with(&**c) { MatchResult::Consumed { remaining: &value[c.len()..], any_offset: None, @@ -545,7 +557,7 @@ impl Pattern { match self { Pattern::Constant(c) => { if let Some(offset) = any_offset { - if let Some(index) = value.find(c) { + if let Some(index) = value.find(&**c) { if index <= offset { NextConstantUntilResult::Consumed(&value[index + c.len()..], None) } else { @@ -556,7 +568,7 @@ impl Pattern { } else { NextConstantUntilResult::NoMatch } - } else if let Some(stripped) = value.strip_prefix(c) { + } else if let Some(stripped) = value.strip_prefix(&**c) { NextConstantUntilResult::Consumed(stripped, None) } else if let Some(stripped) = c.strip_prefix(value) { NextConstantUntilResult::Partial(stripped, true) @@ -610,7 +622,7 @@ impl Pattern { pub fn or_any_nested_file(&self) -> Self { let mut new = self.clone(); - new.push(Pattern::Constant("/".to_string())); + new.push(Pattern::Constant("/".into())); new.push(Pattern::Dynamic); new.normalize(); Pattern::alternatives([self.clone(), new]) @@ -713,8 +725,8 @@ enum NextConstantUntilResult<'a, 'b> { Consumed(&'b str, Option), } -impl From for Pattern { - fn from(s: String) -> Self { +impl From for Pattern { + fn from(s: RcStr) -> Self { Pattern::Constant(s) } } @@ -747,15 +759,15 @@ impl Display for Pattern { #[turbo_tasks::value_impl] impl ValueToString for Pattern { #[turbo_tasks::function] - fn to_string(&self) -> Vc { - Vc::cell(self.to_string()) + fn to_string(&self) -> Vc { + Vc::cell(self.to_string().into()) } } #[derive(Debug, PartialEq, Eq, Clone, PartialOrd, Ord, TraceRawVcs, Serialize, Deserialize)] pub enum PatternMatch { - File(String, Vc), - Directory(String, Vc), + File(RcStr, Vc), + Directory(RcStr, Vc), } // TODO this isn't super efficient @@ -774,11 +786,11 @@ pub struct PatternMatches(Vec); #[turbo_tasks::function] pub async fn read_matches( lookup_dir: Vc, - prefix: String, + prefix: RcStr, force_in_lookup_dir: bool, pattern: Vc, ) -> Result> { - let mut prefix = prefix; + let mut prefix = prefix.to_string(); let pat = pattern.await?; let mut results = Vec::new(); let mut nested = Vec::new(); @@ -795,9 +807,9 @@ pub async fn read_matches( if until_end { if handled.insert(str) { if let Some(fs_path) = &*if force_in_lookup_dir { - lookup_dir.try_join_inside(str.to_string()).await? + lookup_dir.try_join_inside(str.into()).await? } else { - lookup_dir.try_join(str.to_string()).await? + lookup_dir.try_join(str.into()).await? } { let fs_path = fs_path.resolve().await?; // This explicit deref of `context` is necessary @@ -812,12 +824,12 @@ pub async fn read_matches( FileSystemEntryType::File => { results.push(( index, - PatternMatch::File(prefix.to_string(), fs_path), + PatternMatch::File(prefix.clone().into(), fs_path), )); } FileSystemEntryType::Directory => results.push(( index, - PatternMatch::Directory(prefix.to_string(), fs_path), + PatternMatch::Directory(prefix.clone().into(), fs_path), )), FileSystemEntryType::Symlink => { if let LinkContent::Link { link_type, .. } = @@ -827,14 +839,17 @@ pub async fn read_matches( results.push(( index, PatternMatch::Directory( - prefix.clone(), + prefix.clone().into(), fs_path, ), )); } else { results.push(( index, - PatternMatch::File(prefix.clone(), fs_path), + PatternMatch::File( + prefix.clone().into(), + fs_path, + ), )) } } @@ -849,9 +864,9 @@ pub async fn read_matches( let subpath = &str[..=str.rfind('/').unwrap()]; if handled.insert(subpath) { if let Some(fs_path) = &*if force_in_lookup_dir { - lookup_dir.try_join_inside(subpath.to_string()).await? + lookup_dir.try_join_inside(subpath.into()).await? } else { - lookup_dir.try_join(subpath.to_string()).await? + lookup_dir.try_join(subpath.into()).await? } { let fs_path = fs_path.resolve().await?; let len = prefix.len(); @@ -860,7 +875,7 @@ pub async fn read_matches( 0, read_matches( fs_path, - prefix.to_string(), + prefix.clone().into(), force_in_lookup_dir, pattern, ), @@ -888,7 +903,7 @@ pub async fn read_matches( if let Some(pos) = pat.match_position(&prefix) { results.push(( pos, - PatternMatch::Directory(prefix.clone(), lookup_dir.parent()), + PatternMatch::Directory(prefix.clone().into(), lookup_dir.parent()), )); } @@ -897,13 +912,13 @@ pub async fn read_matches( if let Some(pos) = pat.match_position(&prefix) { results.push(( pos, - PatternMatch::Directory(prefix.clone(), lookup_dir.parent()), + PatternMatch::Directory(prefix.clone().into(), lookup_dir.parent()), )); } if let Some(pos) = pat.could_match_position(&prefix) { nested.push(( pos, - read_matches(lookup_dir.parent(), prefix.clone(), false, pattern), + read_matches(lookup_dir.parent(), prefix.clone().into(), false, pattern), )); } prefix.pop(); @@ -914,19 +929,19 @@ pub async fn read_matches( prefix.push('.'); // {prefix}. if let Some(pos) = pat.match_position(&prefix) { - results.push((pos, PatternMatch::Directory(prefix.clone(), lookup_dir))); + results.push(( + pos, + PatternMatch::Directory(prefix.clone().into(), lookup_dir), + )); } prefix.pop(); } if prefix.is_empty() { if let Some(pos) = pat.match_position("./") { - results.push((pos, PatternMatch::Directory("./".to_string(), lookup_dir))); + results.push((pos, PatternMatch::Directory("./".into(), lookup_dir))); } if let Some(pos) = pat.could_match_position("./") { - nested.push(( - pos, - read_matches(lookup_dir, "./".to_string(), false, pattern), - )); + nested.push((pos, read_matches(lookup_dir, "./".into(), false, pattern))); } } else { prefix.push('/'); @@ -934,7 +949,7 @@ pub async fn read_matches( if let Some(pos) = pat.could_match_position(&prefix) { nested.push(( pos, - read_matches(lookup_dir, prefix.to_string(), false, pattern), + read_matches(lookup_dir, prefix.to_string().into(), false, pattern), )); } prefix.pop(); @@ -943,7 +958,7 @@ pub async fn read_matches( if let Some(pos) = pat.could_match_position(&prefix) { nested.push(( pos, - read_matches(lookup_dir, prefix.to_string(), false, pattern), + read_matches(lookup_dir, prefix.to_string().into(), false, pattern), )); } prefix.pop(); @@ -958,7 +973,10 @@ pub async fn read_matches( prefix.push_str(key); // {prefix}{key} if let Some(pos) = pat.match_position(&prefix) { - results.push((pos, PatternMatch::File(prefix.clone(), *path))); + results.push(( + pos, + PatternMatch::File(prefix.clone().into(), *path), + )); } prefix.truncate(len) } @@ -972,7 +990,7 @@ pub async fn read_matches( if let Some(pos) = pat.match_position(&prefix) { results.push(( pos, - PatternMatch::Directory(prefix.clone(), *path), + PatternMatch::Directory(prefix.clone().into(), *path), )); } prefix.push('/'); @@ -980,13 +998,13 @@ pub async fn read_matches( if let Some(pos) = pat.match_position(&prefix) { results.push(( pos, - PatternMatch::Directory(prefix.clone(), *path), + PatternMatch::Directory(prefix.clone().into(), *path), )); } if let Some(pos) = pat.could_match_position(&prefix) { nested.push(( pos, - read_matches(*path, prefix.clone(), true, pattern), + read_matches(*path, prefix.clone().into(), true, pattern), )); } prefix.truncate(len) @@ -1005,12 +1023,15 @@ pub async fn read_matches( if link_type.contains(LinkType::DIRECTORY) { results.push(( pos, - PatternMatch::Directory(prefix.clone(), *fs_path), + PatternMatch::Directory( + prefix.clone().into(), + *fs_path, + ), )); } else { results.push(( pos, - PatternMatch::File(prefix.clone(), *fs_path), + PatternMatch::File(prefix.clone().into(), *fs_path), )); } } @@ -1023,7 +1044,10 @@ pub async fn read_matches( if link_type.contains(LinkType::DIRECTORY) { results.push(( pos, - PatternMatch::Directory(prefix.clone(), *fs_path), + PatternMatch::Directory( + prefix.clone().into(), + *fs_path, + ), )); } } @@ -1035,7 +1059,10 @@ pub async fn read_matches( if link_type.contains(LinkType::DIRECTORY) { results.push(( pos, - PatternMatch::Directory(prefix.clone(), *fs_path), + PatternMatch::Directory( + prefix.clone().into(), + *fs_path, + ), )); } } @@ -1075,10 +1102,10 @@ mod tests { #[test] fn normalize() { - let a = Pattern::Constant("a".to_string()); - let b = Pattern::Constant("b".to_string()); - let c = Pattern::Constant("c".to_string()); - let s = Pattern::Constant("/".to_string()); + let a = Pattern::Constant("a".into()); + let b = Pattern::Constant("b".into()); + let c = Pattern::Constant("c".into()); + let s = Pattern::Constant("/".into()); let d = Pattern::Dynamic; { let mut p = Pattern::Concatenation(vec![ @@ -1090,8 +1117,8 @@ mod tests { assert_eq!( p, Pattern::Alternatives(vec![ - Pattern::Constant("a/c".to_string()), - Pattern::Constant("b/c".to_string()), + Pattern::Constant("a/c".into()), + Pattern::Constant("b/c".into()), ]) ); } @@ -1108,29 +1135,17 @@ mod tests { assert_eq!( p, Pattern::Alternatives(vec![ - Pattern::Constant("a/b".to_string()), - Pattern::Constant("b/b".to_string()), - Pattern::Concatenation(vec![ - Pattern::Dynamic, - Pattern::Constant("/b".to_string()) - ]), - Pattern::Constant("a/c".to_string()), - Pattern::Constant("b/c".to_string()), - Pattern::Concatenation(vec![ - Pattern::Dynamic, - Pattern::Constant("/c".to_string()) - ]), - Pattern::Concatenation(vec![ - Pattern::Constant("a/".to_string()), - Pattern::Dynamic - ]), - Pattern::Concatenation(vec![ - Pattern::Constant("b/".to_string()), - Pattern::Dynamic - ]), + Pattern::Constant("a/b".into()), + Pattern::Constant("b/b".into()), + Pattern::Concatenation(vec![Pattern::Dynamic, Pattern::Constant("/b".into())]), + Pattern::Constant("a/c".into()), + Pattern::Constant("b/c".into()), + Pattern::Concatenation(vec![Pattern::Dynamic, Pattern::Constant("/c".into())]), + Pattern::Concatenation(vec![Pattern::Constant("a/".into()), Pattern::Dynamic]), + Pattern::Concatenation(vec![Pattern::Constant("b/".into()), Pattern::Dynamic]), Pattern::Concatenation(vec![ Pattern::Dynamic, - Pattern::Constant("/".to_string()), + Pattern::Constant("/".into()), Pattern::Dynamic ]), ]) @@ -1141,10 +1156,10 @@ mod tests { #[test] fn is_match() { let pat = Pattern::Concatenation(vec![ - Pattern::Constant(".".to_string()), - Pattern::Constant("/".to_string()), + Pattern::Constant(".".into()), + Pattern::Constant("/".into()), Pattern::Dynamic, - Pattern::Constant(".js".to_string()), + Pattern::Constant(".js".into()), ]); assert!(pat.could_match("")); assert!(pat.could_match("./")); @@ -1169,7 +1184,7 @@ mod tests { #[rstest] #[case::dynamic(Pattern::Dynamic)] - #[case::dynamic_concat(Pattern::Concatenation(vec![Pattern::Dynamic, Pattern::Constant(".js".to_string())]))] + #[case::dynamic_concat(Pattern::Concatenation(vec![Pattern::Dynamic, Pattern::Constant(".js".into())]))] fn dynamic_match(#[case] pat: Pattern) { assert!(pat.could_match("")); assert!(pat.is_match("index.js")); @@ -1223,7 +1238,7 @@ mod tests { fn dynamic_match2() { let pat = Pattern::Concatenation(vec![ Pattern::Dynamic, - Pattern::Constant("/".to_string()), + Pattern::Constant("/".into()), Pattern::Dynamic, ]); assert!(pat.could_match("dir")); @@ -1275,16 +1290,16 @@ mod tests { #[rstest] #[case::dynamic(Pattern::Dynamic)] - #[case::dynamic_concat(Pattern::Concatenation(vec![Pattern::Dynamic, Pattern::Constant(".js".to_string())]))] + #[case::dynamic_concat(Pattern::Concatenation(vec![Pattern::Dynamic, Pattern::Constant(".js".into())]))] #[case::dynamic_concat2(Pattern::Concatenation(vec![ Pattern::Dynamic, - Pattern::Constant("/".to_string()), + Pattern::Constant("/".into()), Pattern::Dynamic, ]))] #[case::dynamic_alt_concat(Pattern::alternatives(vec![ Pattern::Concatenation(vec![ Pattern::Dynamic, - Pattern::Constant("/".to_string()), + Pattern::Constant("/".into()), Pattern::Dynamic, ]), Pattern::Dynamic, @@ -1298,28 +1313,28 @@ mod tests { #[rstest] #[case::dynamic(Pattern::Dynamic, "feijf", None)] #[case::dynamic_concat( - Pattern::Concatenation(vec![Pattern::Dynamic, Pattern::Constant(".js".to_string())]), + Pattern::Concatenation(vec![Pattern::Dynamic, Pattern::Constant(".js".into())]), "hello.", None )] - #[case::constant(Pattern::Constant("Hello World".to_string()), "Hello ", Some(vec![("World", true)]))] + #[case::constant(Pattern::Constant("Hello World".into()), "Hello ", Some(vec![("World", true)]))] #[case::alternatives( Pattern::Alternatives(vec![ - Pattern::Constant("Hello World".to_string()), - Pattern::Constant("Hello All".to_string()) + Pattern::Constant("Hello World".into()), + Pattern::Constant("Hello All".into()) ]), "Hello ", Some(vec![("World", true), ("All", true)]) )] #[case::alternatives_non_end( Pattern::Alternatives(vec![ - Pattern::Constant("Hello World".to_string()), - Pattern::Constant("Hello All".to_string()), - Pattern::Concatenation(vec![Pattern::Constant("Hello more".to_string()), Pattern::Dynamic]) + Pattern::Constant("Hello World".into()), + Pattern::Constant("Hello All".into()), + Pattern::Concatenation(vec![Pattern::Constant("Hello more".into()), Pattern::Dynamic]) ]), "Hello ", Some(vec![("World", true), ("All", true), ("more", false)]) )] #[case::request_with_extensions( Pattern::Alternatives(vec![ - Pattern::Constant("./file.js".to_string()), - Pattern::Constant("./file.ts".to_string()), - Pattern::Constant("./file.cjs".to_string()), + Pattern::Constant("./file.js".into()), + Pattern::Constant("./file.ts".into()), + Pattern::Constant("./file.cjs".into()), ]), "./", Some(vec![("file.js", true), ("file.ts", true), ("file.cjs", true)]) )] fn next_constants( diff --git a/crates/turbopack-core/src/resolve/remap.rs b/crates/turbopack-core/src/resolve/remap.rs index d156510990522..8836be855a6d6 100644 --- a/crates/turbopack-core/src/resolve/remap.rs +++ b/crates/turbopack-core/src/resolve/remap.rs @@ -8,6 +8,7 @@ use anyhow::{bail, Result}; use indexmap::IndexMap; use serde::{Deserialize, Serialize}; use serde_json::Value; +use turbo_tasks::RcStr; use super::{ alias_map::{AliasMap, AliasMapIter, AliasPattern, AliasTemplate}, @@ -47,11 +48,11 @@ pub enum SubpathValue { /// file that uses ESM syntax. /// Node defines several conditions in https://nodejs.org/api/packages.html#conditional-exports /// TODO: Should this use an enum of predefined keys? - Conditional(Vec<(String, SubpathValue)>), + Conditional(Vec<(RcStr, SubpathValue)>), /// A result subpath, defined with `"path": "other"`, remaps imports of /// `path` to `other`. - Result(String), + Result(RcStr), /// An excluded subpath, defined with `"path": null`, prevents importing /// this subpath. @@ -73,7 +74,7 @@ impl AliasTemplate for SubpathValue { .map(|(condition, value)| Ok((condition.clone(), value.replace(capture)?))) .collect::>>()?, ), - SubpathValue::Result(value) => SubpathValue::Result(value.replace('*', capture)), + SubpathValue::Result(value) => SubpathValue::Result(value.replace('*', capture).into()), SubpathValue::Excluded => SubpathValue::Excluded, }) } @@ -91,7 +92,7 @@ impl SubpathValue { /// also exposed to the consumer. pub fn add_results<'a>( &'a self, - conditions: &BTreeMap, + conditions: &BTreeMap, unspecified_condition: &ConditionValue, condition_overrides: &mut HashMap<&'a str, ConditionValue>, target: &mut Vec<(&'a str, Vec<(&'a str, bool)>)>, @@ -170,7 +171,7 @@ impl SubpathValue { fn try_new(value: &Value, ty: ExportImport) -> Result { match value { Value::Null => Ok(SubpathValue::Excluded), - Value::String(s) => Ok(SubpathValue::Result(s.to_string())), + Value::String(s) => Ok(SubpathValue::Result(s.as_str().into())), Value::Number(_) => bail!("numeric values are invalid in {ty}s field entries"), Value::Bool(_) => bail!("boolean values are invalid in {ty}s field entries"), Value::Object(object) => Ok(SubpathValue::Conditional( @@ -185,7 +186,7 @@ impl SubpathValue { ); } - Ok((key.to_string(), SubpathValue::try_new(value, ty)?)) + Ok((key.as_str().into(), SubpathValue::try_new(value, ty)?)) }) .collect::>>()?, )), @@ -204,7 +205,7 @@ struct ResultsIterMut<'a> { } impl<'a> Iterator for ResultsIterMut<'a> { - type Item = &'a mut String; + type Item = &'a mut RcStr; fn next(&mut self) -> Option { while let Some(value) = self.stack.pop() { @@ -257,7 +258,7 @@ impl TryFrom<&Value> for ExportsField { let pattern = if is_folder_shorthand(key) { expand_folder_shorthand(key, &mut value)? } else { - AliasPattern::parse(key) + AliasPattern::parse(key.as_str()) }; map.insert(pattern, value); @@ -265,13 +266,13 @@ impl TryFrom<&Value> for ExportsField { if !conditions.is_empty() { map.insert( - AliasPattern::Exact(".".to_string()), + AliasPattern::Exact(".".into()), SubpathValue::Conditional( conditions .into_iter() .map(|(key, value)| { Ok(( - key.to_string(), + key.as_str().into(), SubpathValue::try_new(value, ExportImport::Export)?, )) }) @@ -286,7 +287,7 @@ impl TryFrom<&Value> for ExportsField { let mut map = AliasMap::new(); map.insert( AliasPattern::exact("."), - SubpathValue::Result(string.to_string()), + SubpathValue::Result(string.as_str().into()), ); map } @@ -340,7 +341,7 @@ impl TryFrom<&Value> for ImportsField { bail!("imports key \"{key}\" must begin with a '#'") } let value = SubpathValue::try_new(value, ExportImport::Import)?; - map.insert(AliasPattern::parse(key), value); + map.insert(AliasPattern::parse(key.as_str()), value); } map @@ -378,7 +379,9 @@ fn expand_folder_shorthand(key: &str, value: &mut SubpathValue) -> Result Result); -impl TryFrom<&IndexMap> for ResolveAliasMap { +impl TryFrom<&IndexMap> for ResolveAliasMap { type Error = anyhow::Error; - fn try_from(object: &IndexMap) -> Result { + fn try_from(object: &IndexMap) -> Result { let mut map = AliasMap::new(); for (key, value) in object.iter() { @@ -417,7 +420,7 @@ impl TryFrom<&IndexMap> for ResolveAliasMap { let pattern = if is_folder_shorthand(key) { expand_folder_shorthand(key, &mut value)? } else { - AliasPattern::parse(key) + AliasPattern::parse(key.as_str()) }; map.insert(pattern, value); diff --git a/crates/turbopack-core/src/server_fs.rs b/crates/turbopack-core/src/server_fs.rs index b4dd139cc09b0..0c8ac7a988cc1 100644 --- a/crates/turbopack-core/src/server_fs.rs +++ b/crates/turbopack-core/src/server_fs.rs @@ -1,5 +1,5 @@ use anyhow::{bail, Result}; -use turbo_tasks::{Completion, ValueToString, Vc}; +use turbo_tasks::{Completion, RcStr, ValueToString, Vc}; use turbo_tasks_fs::{ DirectoryContent, FileContent, FileMeta, FileSystem, FileSystemPath, LinkContent, }; @@ -64,7 +64,7 @@ impl FileSystem for ServerFileSystem { #[turbo_tasks::value_impl] impl ValueToString for ServerFileSystem { #[turbo_tasks::function] - fn to_string(&self) -> Vc { - Vc::cell("root of the server".to_string()) + fn to_string(&self) -> Vc { + Vc::cell("root of the server".into()) } } diff --git a/crates/turbopack-core/src/source_map/mod.rs b/crates/turbopack-core/src/source_map/mod.rs index 86c751187aa7c..2af9fcbef4717 100644 --- a/crates/turbopack-core/src/source_map/mod.rs +++ b/crates/turbopack-core/src/source_map/mod.rs @@ -8,7 +8,7 @@ use ref_cast::RefCast; use regex::Regex; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use sourcemap::{DecodedMap, SourceMap as RegularMap, SourceMapBuilder, SourceMapIndex}; -use turbo_tasks::{TryJoinIterExt, ValueToString, Vc}; +use turbo_tasks::{RcStr, TryJoinIterExt, ValueToString, Vc}; use turbo_tasks_fs::{ rope::{Rope, RopeBuilder}, FileContent, FileSystemPath, @@ -30,7 +30,7 @@ pub trait GenerateSourceMap { fn generate_source_map(self: Vc) -> Vc; /// Returns an individual section of the larger source map, if found. - fn by_section(self: Vc, _section: String) -> Vc { + fn by_section(self: Vc, _section: RcStr) -> Vc { Vc::cell(None) } } @@ -101,7 +101,7 @@ pub struct OriginalToken { pub original_file: String, pub original_line: usize, pub original_column: usize, - pub name: Option, + pub name: Option, } impl Token { @@ -132,7 +132,7 @@ impl<'a> From> for Token { .to_string(), original_line: t.get_src_line() as usize, original_column: t.get_src_col() as usize, - name: t.get_name().map(String::from), + name: t.get_name().map(RcStr::from), }) } else { Token::Synthetic(SyntheticToken { @@ -396,7 +396,7 @@ impl SourceMap { origin: Vc, ) -> Result<(Arc, Arc)> { Ok( - if let Some(path) = *origin.parent().try_join(source_request.to_string()).await? { + if let Some(path) = *origin.parent().try_join((&*source_request).into()).await? { let path_str = path.to_string().await?; let source = format!("{SOURCE_MAP_PREFIX}{}", path_str); let source_content = if let Some(source_content) = source_content { @@ -533,7 +533,7 @@ impl GenerateSourceMap for SourceMap { } #[turbo_tasks::function] - fn by_section(&self, _section: String) -> Vc { + fn by_section(&self, _section: RcStr) -> Vc { Vc::cell(None) } } diff --git a/crates/turbopack-core/src/source_map/source_map_asset.rs b/crates/turbopack-core/src/source_map/source_map_asset.rs index ab66b6f8a93ed..a2a7a6ae61849 100644 --- a/crates/turbopack-core/src/source_map/source_map_asset.rs +++ b/crates/turbopack-core/src/source_map/source_map_asset.rs @@ -1,6 +1,6 @@ use anyhow::{bail, Result}; use indexmap::IndexSet; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbo_tasks_fs::File; use crate::{ @@ -32,7 +32,7 @@ impl OutputAsset for SourceMapAsset { // NOTE(alexkirsz) We used to include the asset's version id in the path, // but this caused `all_assets_map` to be recomputed on every change. Ok(AssetIdent::from_path( - self.asset.ident().path().append(".map".to_string()), + self.asset.ident().path().append(".map".into()), )) } } @@ -57,29 +57,29 @@ impl Asset for SourceMapAsset { } #[turbo_tasks::function] -fn introspectable_type() -> Vc { - Vc::cell("source map".to_string()) +fn introspectable_type() -> Vc { + Vc::cell("source map".into()) } #[turbo_tasks::function] -fn introspectable_details() -> Vc { - Vc::cell("source map of an asset".to_string()) +fn introspectable_details() -> Vc { + Vc::cell("source map of an asset".into()) } #[turbo_tasks::value_impl] impl Introspectable for SourceMapAsset { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { introspectable_type() } #[turbo_tasks::function] - fn title(self: Vc) -> Vc { + fn title(self: Vc) -> Vc { self.ident().to_string() } #[turbo_tasks::function] - fn details(&self) -> Vc { + fn details(&self) -> Vc { introspectable_details() } @@ -88,7 +88,7 @@ impl Introspectable for SourceMapAsset { let mut children = IndexSet::new(); if let Some(asset) = Vc::try_resolve_sidecast::>(self.asset).await? { - children.insert((Vc::cell("asset".to_string()), asset)); + children.insert((Vc::cell("asset".into()), asset)); } Ok(Vc::cell(children)) } diff --git a/crates/turbopack-core/src/version.rs b/crates/turbopack-core/src/version.rs index 8d003b067645c..08fb9f6ec3572 100644 --- a/crates/turbopack-core/src/version.rs +++ b/crates/turbopack-core/src/version.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use anyhow::{anyhow, Result}; use serde::{Deserialize, Serialize}; use turbo_tasks::{ - debug::ValueDebugFormat, trace::TraceRawVcs, IntoTraitRef, ReadRef, State, TraitRef, Vc, + debug::ValueDebugFormat, trace::TraceRawVcs, IntoTraitRef, RcStr, ReadRef, State, TraitRef, Vc, }; use turbo_tasks_fs::{FileContent, LinkType}; use turbo_tasks_hash::{encode_hex, hash_xxh3_hash64}; @@ -122,7 +122,7 @@ pub trait Version { /// Get a unique identifier of the version as a string. There is no way /// to convert an id back to its original `Version`, so the original object /// needs to be stored somewhere. - fn id(self: Vc) -> Vc; + fn id(self: Vc) -> Vc; } /// This trait allows multiple `VersionedContent` to declare which @@ -159,8 +159,8 @@ impl NotFoundVersion { #[turbo_tasks::value_impl] impl Version for NotFoundVersion { #[turbo_tasks::function] - fn id(&self) -> Vc { - Vc::cell("".to_string()) + fn id(&self) -> Vc { + Vc::cell(Default::default()) } } @@ -205,7 +205,7 @@ pub struct PartialUpdate { #[turbo_tasks::value] #[derive(Clone)] pub struct FileHashVersion { - hash: String, + hash: RcStr, } impl FileHashVersion { @@ -216,7 +216,9 @@ impl FileHashVersion { FileContent::Content(file) => { let hash = hash_xxh3_hash64(file.content()); let hex_hash = encode_hex(hash); - Ok(Self::cell(FileHashVersion { hash: hex_hash })) + Ok(Self::cell(FileHashVersion { + hash: hex_hash.into(), + })) } FileContent::NotFound => Err(anyhow!("file not found")), }, @@ -228,7 +230,7 @@ impl FileHashVersion { #[turbo_tasks::value_impl] impl Version for FileHashVersion { #[turbo_tasks::function] - async fn id(&self) -> Result> { + async fn id(&self) -> Result> { Ok(Vc::cell(self.hash.clone())) } } diff --git a/crates/turbopack-css/src/asset.rs b/crates/turbopack-css/src/asset.rs index 901f928393ea9..29cea2fec3723 100644 --- a/crates/turbopack-css/src/asset.rs +++ b/crates/turbopack-css/src/asset.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{TryJoinIterExt, ValueToString, Vc}; +use turbo_tasks::{RcStr, TryJoinIterExt, ValueToString, Vc}; use turbo_tasks_fs::FileSystemPath; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -25,11 +25,11 @@ use crate::{ }; #[turbo_tasks::function] -fn modifier(use_swc_css: bool) -> Vc { +fn modifier(use_swc_css: bool) -> Vc { if use_swc_css { - Vc::cell("swc css".to_string()) + Vc::cell("swc css".into()) } else { - Vc::cell("css".to_string()) + Vc::cell("css".into()) } } diff --git a/crates/turbopack-css/src/chunk/mod.rs b/crates/turbopack-css/src/chunk/mod.rs index ba8bd0b062f38..2f6d8c3b6d9cd 100644 --- a/crates/turbopack-css/src/chunk/mod.rs +++ b/crates/turbopack-css/src/chunk/mod.rs @@ -5,7 +5,7 @@ use std::fmt::Write; use anyhow::{bail, Result}; use indexmap::IndexSet; -use turbo_tasks::{TryJoinIterExt, Value, ValueDefault, ValueToString, Vc}; +use turbo_tasks::{RcStr, TryJoinIterExt, Value, ValueDefault, ValueToString, Vc}; use turbo_tasks_fs::{rope::Rope, File, FileSystem}; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -225,8 +225,8 @@ impl OutputChunk for CssChunk { } #[turbo_tasks::function] -fn chunk_item_key() -> Vc { - Vc::cell("chunk item".to_string()) +fn chunk_item_key() -> Vc { + Vc::cell("chunk item".into()) } #[turbo_tasks::value_impl] @@ -275,7 +275,7 @@ impl OutputAsset for CssChunk { } else { ServerFileSystem::new().root() }, - query: Vc::::default(), + query: Vc::::default(), fragment: None, assets, modifiers: Vec::new(), @@ -285,7 +285,7 @@ impl OutputAsset for CssChunk { Ok(AssetIdent::from_path(this.chunking_context.chunk_path( AssetIdent::new(Value::new(ident)), - ".css".to_string(), + ".css".into(), ))) } @@ -358,7 +358,7 @@ pub struct CssChunkPlaceables(Vec>>); #[derive(Clone, Debug)] #[turbo_tasks::value(shared)] pub enum CssImport { - External(Vc), + External(Vc), Internal(Vc, Vc>), Composes(Vc>), } @@ -382,29 +382,29 @@ pub trait CssChunkItem: ChunkItem { } #[turbo_tasks::function] -fn introspectable_type() -> Vc { - Vc::cell("css chunk".to_string()) +fn introspectable_type() -> Vc { + Vc::cell("css chunk".into()) } #[turbo_tasks::function] -fn entry_module_key() -> Vc { - Vc::cell("entry module".to_string()) +fn entry_module_key() -> Vc { + Vc::cell("entry module".into()) } #[turbo_tasks::value_impl] impl Introspectable for CssChunk { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { introspectable_type() } #[turbo_tasks::function] - fn title(self: Vc) -> Vc { + fn title(self: Vc) -> Vc { self.path().to_string() } #[turbo_tasks::function] - async fn details(self: Vc) -> Result> { + async fn details(self: Vc) -> Result> { let content = content_to_details(self.content()); let mut details = String::new(); let this = self.await?; @@ -415,7 +415,7 @@ impl Introspectable for CssChunk { } details += "\nContent:\n\n"; write!(details, "{}", content.await?)?; - Ok(Vc::cell(details)) + Ok(Vc::cell(details.into())) } #[turbo_tasks::function] @@ -440,8 +440,8 @@ pub struct CssChunkType {} #[turbo_tasks::value_impl] impl ValueToString for CssChunkType { #[turbo_tasks::function] - fn to_string(&self) -> Vc { - Vc::cell("css".to_string()) + fn to_string(&self) -> Vc { + Vc::cell("css".into()) } } diff --git a/crates/turbopack-css/src/chunk/single_item_chunk/chunk.rs b/crates/turbopack-css/src/chunk/single_item_chunk/chunk.rs index c6575fa543c41..b394b402566fa 100644 --- a/crates/turbopack-css/src/chunk/single_item_chunk/chunk.rs +++ b/crates/turbopack-css/src/chunk/single_item_chunk/chunk.rs @@ -1,7 +1,7 @@ use std::fmt::Write; use anyhow::Result; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbo_tasks_fs::File; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -93,8 +93,8 @@ impl Chunk for SingleItemCssChunk { } #[turbo_tasks::function] -fn single_item_modifier() -> Vc { - Vc::cell("single item css chunk".to_string()) +fn single_item_modifier() -> Vc { + Vc::cell("single item css chunk".into()) } #[turbo_tasks::value_impl] @@ -106,7 +106,7 @@ impl OutputAsset for SingleItemCssChunk { self.item .asset_ident() .with_modifier(single_item_modifier()), - ".css".to_string(), + ".css".into(), ), )) } @@ -146,29 +146,29 @@ impl GenerateSourceMap for SingleItemCssChunk { } #[turbo_tasks::function] -fn introspectable_type() -> Vc { - Vc::cell("single asset css chunk".to_string()) +fn introspectable_type() -> Vc { + Vc::cell("single asset css chunk".into()) } #[turbo_tasks::function] -fn entry_module_key() -> Vc { - Vc::cell("entry module".to_string()) +fn entry_module_key() -> Vc { + Vc::cell("entry module".into()) } #[turbo_tasks::value_impl] impl Introspectable for SingleItemCssChunk { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { introspectable_type() } #[turbo_tasks::function] - fn title(self: Vc) -> Vc { + fn title(self: Vc) -> Vc { self.path().to_string() } #[turbo_tasks::function] - async fn details(self: Vc) -> Result> { + async fn details(self: Vc) -> Result> { let this = self.await?; let mut details = String::new(); write!( @@ -176,6 +176,6 @@ impl Introspectable for SingleItemCssChunk { "Chunk item: {}", this.item.asset_ident().to_string().await? )?; - Ok(Vc::cell(details)) + Ok(Vc::cell(details.into())) } } diff --git a/crates/turbopack-css/src/chunk/single_item_chunk/source_map.rs b/crates/turbopack-css/src/chunk/single_item_chunk/source_map.rs index 2706cac561f90..1b0f42359dad1 100644 --- a/crates/turbopack-css/src/chunk/single_item_chunk/source_map.rs +++ b/crates/turbopack-css/src/chunk/single_item_chunk/source_map.rs @@ -30,7 +30,7 @@ impl OutputAsset for SingleItemCssChunkSourceMapAsset { #[turbo_tasks::function] async fn ident(&self) -> Result> { Ok(AssetIdent::from_path( - self.chunk.path().append(".map".to_string()), + self.chunk.path().append(".map".into()), )) } } diff --git a/crates/turbopack-css/src/chunk/source_map.rs b/crates/turbopack-css/src/chunk/source_map.rs index 854dd0c2c869a..7be9a1b14f03e 100644 --- a/crates/turbopack-css/src/chunk/source_map.rs +++ b/crates/turbopack-css/src/chunk/source_map.rs @@ -30,7 +30,7 @@ impl OutputAsset for CssChunkSourceMapAsset { #[turbo_tasks::function] async fn ident(&self) -> Result> { Ok(AssetIdent::from_path( - self.chunk.path().append(".map".to_string()), + self.chunk.path().append(".map".into()), )) } } diff --git a/crates/turbopack-css/src/module_asset.rs b/crates/turbopack-css/src/module_asset.rs index 6905f14ceb199..08c76694f2dda 100644 --- a/crates/turbopack-css/src/module_asset.rs +++ b/crates/turbopack-css/src/module_asset.rs @@ -5,7 +5,7 @@ use indexmap::IndexMap; use indoc::formatdoc; use lightningcss::css_modules::CssModuleReference; use swc_core::common::{BytePos, FileName, LineCol, SourceMap}; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbo_tasks_fs::FileSystemPath; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -35,8 +35,8 @@ use crate::{ }; #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("css module".to_string()) +fn modifier() -> Vc { + Vc::cell("css module".into()) } #[turbo_tasks::value] @@ -191,7 +191,9 @@ impl ModuleCssAsset { original: name.to_string(), from: CssModuleComposeReference::new( Vc::upcast(self), - Request::parse(Value::new(specifier.to_string().into())), + Request::parse(Value::new( + RcStr::from(specifier.clone()).into(), + )), ), } } @@ -336,7 +338,7 @@ impl EcmascriptChunkItem for ModuleChunkItem { Module {from} referenced in `composes: ... from {from};` can't be resolved. "#, from = &*from.await?.request.to_string().await? - }, + }.into(), }.cell().emit(); continue; }; @@ -353,7 +355,7 @@ impl EcmascriptChunkItem for ModuleChunkItem { Module {from} referenced in `composes: ... from {from};` is not a CSS module. "#, from = &*from.await?.request.to_string().await? - }, + }.into(), }.cell().emit(); continue; }; @@ -427,7 +429,7 @@ fn generate_minimal_source_map(filename: String, source: String) -> Vc, source: Vc, - message: String, + message: RcStr, } #[turbo_tasks::value_impl] @@ -440,7 +442,7 @@ impl Issue for CssModuleComposesIssue { #[turbo_tasks::function] async fn title(&self) -> Result> { Ok(StyledString::Text( - "An issue occurred while resolving a CSS module `composes:` rule".to_string(), + "An issue occurred while resolving a CSS module `composes:` rule".into(), ) .cell()) } diff --git a/crates/turbopack-css/src/process.rs b/crates/turbopack-css/src/process.rs index aa227d906013a..8b788080b012a 100644 --- a/crates/turbopack-css/src/process.rs +++ b/crates/turbopack-css/src/process.rs @@ -33,7 +33,7 @@ use swc_core::{ }, }; use tracing::Instrument; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbo_tasks_fs::{FileContent, FileSystemPath}; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -428,7 +428,7 @@ pub async fn finalize_css( for (src, reference) in (*url_references.await?).iter() { let resolved = resolve_url_reference(*reference, chunking_context).await?; if let Some(v) = resolved.as_ref().cloned() { - url_map.insert(src.to_string(), v); + url_map.insert(RcStr::from(src.as_str()), v); } } @@ -477,8 +477,8 @@ pub async fn parse_css( use_swc_css: bool, ) -> Result> { let span = { - let name = source.ident().to_string().await?; - tracing::info_span!("parse css", name = *name) + let name = source.ident().to_string().await?.to_string(); + tracing::info_span!("parse css", name = name) }; async move { let content = source.content(); @@ -597,7 +597,7 @@ async fn process_content( ParsingIssue { file: fs_path_vc, - msg: Vc::cell(err.to_string()), + msg: Vc::cell(err.to_string().into()), source: Vc::cell(source), } .cell() @@ -624,7 +624,7 @@ async fn process_content( ParsingIssue { file: fs_path_vc, - msg: Vc::cell(e.to_string()), + msg: Vc::cell(e.to_string().into()), source: Vc::cell(source), } .cell() @@ -642,7 +642,7 @@ async fn process_content( Box::new(IssueEmitter::new( source, cm.clone(), - Some("Parsing css source code failed".to_string()), + Some("Parsing css source code failed".into()), )), ); @@ -749,7 +749,7 @@ impl CssError { CssError::SwcSelectorInModuleNotPure { span } => { ParsingIssue { file, - msg: Vc::cell(CSS_MODULE_ERROR.to_string()), + msg: Vc::cell(CSS_MODULE_ERROR.into()), source: Vc::cell(Some(IssueSource::from_swc_offsets( source, span.lo.0 as _, @@ -762,7 +762,7 @@ impl CssError { CssError::LightningCssSelectorInModuleNotPure { selector } => { ParsingIssue { file, - msg: Vc::cell(format!("{CSS_MODULE_ERROR}, (lightningcss, {selector})")), + msg: Vc::cell(format!("{CSS_MODULE_ERROR}, (lightningcss, {selector})").into()), source: Vc::cell(None), } .cell() @@ -1083,7 +1083,7 @@ impl TransformConfig for ModuleTransformConfig { #[turbo_tasks::value] struct ParsingIssue { - msg: Vc, + msg: Vc, file: Vc, source: Vc, } @@ -1102,7 +1102,7 @@ impl Issue for ParsingIssue { #[turbo_tasks::function] fn title(&self) -> Vc { - StyledString::Text("Parsing css source code failed".to_string()).cell() + StyledString::Text("Parsing css source code failed".into()).cell() } #[turbo_tasks::function] @@ -1113,7 +1113,7 @@ impl Issue for ParsingIssue { #[turbo_tasks::function] async fn description(&self) -> Result> { Ok(Vc::cell(Some( - StyledString::Text(self.msg.await?.clone_value()).cell(), + StyledString::Text(self.msg.await?.as_str().into()).cell(), ))) } } diff --git a/crates/turbopack-css/src/references/compose.rs b/crates/turbopack-css/src/references/compose.rs index 71ce7b71eee7a..d605d1599cef0 100644 --- a/crates/turbopack-css/src/references/compose.rs +++ b/crates/turbopack-css/src/references/compose.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbopack_core::{ chunk::ChunkableModuleReference, reference::ModuleReference, @@ -45,11 +45,10 @@ impl ModuleReference for CssModuleComposeReference { #[turbo_tasks::value_impl] impl ValueToString for CssModuleComposeReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "compose(url) {}", - self.request.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("compose(url) {}", self.request.to_string().await?,).into(), + )) } } diff --git a/crates/turbopack-css/src/references/import.rs b/crates/turbopack-css/src/references/import.rs index 48607176cdc8d..8154a145af8a8 100644 --- a/crates/turbopack-css/src/references/import.rs +++ b/crates/turbopack-css/src/references/import.rs @@ -11,7 +11,7 @@ use swc_core::{ CodeGenerator, CodegenConfig, Emit, }, }; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbopack_core::{ chunk::{ChunkableModuleReference, ChunkingContext}, issue::IssueSource, @@ -150,15 +150,17 @@ impl ImportAttributes { } => turbopack_core::reference_type::ImportAttributes { layer: layer_name .as_ref() - .map(|l| l.to_css_string(Default::default()).unwrap()), + .map(|l| l.to_css_string(Default::default()).unwrap()) + .map(From::from), supports: supports .as_ref() - .map(|s| s.to_css_string(Default::default()).unwrap()), + .map(|s| s.to_css_string(Default::default()).unwrap()) + .map(From::from), media: { if media.always_matches() { None } else { - Some(media.to_css_string(Default::default()).unwrap()) + Some(media.to_css_string(Default::default()).unwrap().into()) } }, }, @@ -167,11 +169,11 @@ impl ImportAttributes { supports, media, } => turbopack_core::reference_type::ImportAttributes { - layer: layer_name.as_ref().map(gen_swc_node), - supports: supports.as_ref().map(gen_swc_node), + layer: layer_name.as_ref().map(gen_swc_node).map(From::from), + supports: supports.as_ref().map(gen_swc_node).map(From::from), media: media .as_ref() - .map(|queries| queries.iter().map(gen_swc_node).collect()), + .map(|queries| queries.iter().map(gen_swc_node).collect::().into()), }, } } @@ -244,11 +246,10 @@ impl ModuleReference for ImportAssetReference { #[turbo_tasks::value_impl] impl ValueToString for ImportAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "import(url) {}", - self.request.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("import(url) {}", self.request.to_string().await?,).into(), + )) } } @@ -267,10 +268,9 @@ impl CodeGenerateable for ImportAssetReference { .. } = &*this.request.await? { - imports.push(CssImport::External(Vc::cell(format!( - "{}{}", - protocol, remainder - )))) + imports.push(CssImport::External(Vc::cell( + format!("{}{}", protocol, remainder).into(), + ))) } Ok(CodeGeneration { imports }.into()) diff --git a/crates/turbopack-css/src/references/internal.rs b/crates/turbopack-css/src/references/internal.rs index d2f9bd560f906..cdba0d33a5067 100644 --- a/crates/turbopack-css/src/references/internal.rs +++ b/crates/turbopack-css/src/references/internal.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbopack_core::{ chunk::ChunkableModuleReference, module::Module, reference::ModuleReference, resolve::ModuleResolveResult, @@ -32,11 +32,10 @@ impl ModuleReference for InternalCssAssetReference { #[turbo_tasks::value_impl] impl ValueToString for InternalCssAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "internal css {}", - self.module.ident().to_string().await? - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("internal css {}", self.module.ident().to_string().await?).into(), + )) } } diff --git a/crates/turbopack-css/src/references/mod.rs b/crates/turbopack-css/src/references/mod.rs index 7888401256a9c..159dce8a4a487 100644 --- a/crates/turbopack-css/src/references/mod.rs +++ b/crates/turbopack-css/src/references/mod.rs @@ -11,7 +11,7 @@ use swc_core::css::{ ast::UrlValue, visit::{VisitMut, VisitMutWith}, }; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::{RcStr, Value, Vc}; use turbopack_core::{ issue::{IssueSeverity, IssueSource}, reference::ModuleReference, @@ -103,7 +103,7 @@ impl VisitMut for ModuleReferencesVisitor<'_> { self.references.push(Vc::upcast(ImportAssetReference::new( self.origin, - Request::parse(Value::new(src.to_string().into())), + Request::parse(Value::new(RcStr::from(src.as_str()).into())), ImportAttributes::new_from_swc(&i.clone()).into(), self.import_context, IssueSource::from_swc_offsets( @@ -137,7 +137,7 @@ impl VisitMut for ModuleReferencesVisitor<'_> { let vc = UrlAssetReference::new( self.origin, - Request::parse(Value::new(src.to_string().into())), + Request::parse(Value::new(RcStr::from(src.as_str()).into())), IssueSource::from_swc_offsets( Vc::upcast(self.source), issue_span.lo.0 as _, @@ -167,7 +167,7 @@ impl<'a> Visitor<'_> for ModuleReferencesVisitor<'a> { self.references.push(Vc::upcast(ImportAssetReference::new( self.origin, - Request::parse(Value::new(src.to_string().into())), + Request::parse(Value::new(RcStr::from(src).into())), ImportAttributes::new_from_lightningcss(&i.clone().into_owned()).into(), self.import_context, IssueSource::from_line_col( @@ -204,7 +204,7 @@ impl<'a> Visitor<'_> for ModuleReferencesVisitor<'a> { let vc = UrlAssetReference::new( self.origin, - Request::parse(Value::new(src.to_string().into())), + Request::parse(Value::new(RcStr::from(src).into())), IssueSource::from_line_col( Vc::upcast(self.source), SourcePos { diff --git a/crates/turbopack-css/src/references/url.rs b/crates/turbopack-css/src/references/url.rs index 889c65b28c9f2..e59e92cb66163 100644 --- a/crates/turbopack-css/src/references/url.rs +++ b/crates/turbopack-css/src/references/url.rs @@ -10,7 +10,7 @@ use swc_core::css::{ ast::UrlValue, visit::{VisitMut, VisitMutWith}, }; -use turbo_tasks::{debug::ValueDebug, Value, ValueToString, Vc}; +use turbo_tasks::{debug::ValueDebug, RcStr, Value, ValueToString, Vc}; use turbopack_core::{ chunk::{ ChunkableModule, ChunkableModuleReference, ChunkingContext, ChunkingType, @@ -107,9 +107,9 @@ impl ChunkableModuleReference for UrlAssetReference { #[turbo_tasks::value_impl] impl ValueToString for UrlAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { + async fn to_string(&self) -> Result> { Ok(Vc::cell( - format!("url {}", self.request.to_string().await?,), + format!("url {}", self.request.to_string().await?,).into(), )) } } @@ -118,13 +118,13 @@ impl ValueToString for UrlAssetReference { pub async fn resolve_url_reference( url: Vc, chunking_context: Vc>, -) -> Result>> { +) -> Result>> { let this = url.await?; // TODO(WEB-662) This is not the correct way to get the current chunk path. It // currently works as all chunks are in the same directory. let chunk_path = chunking_context.chunk_path( AssetIdent::from_path(this.origin.origin_path()), - ".css".to_string(), + ".css".into(), ); let context_path = chunk_path.parent().await?; @@ -134,7 +134,7 @@ pub async fn resolve_url_reference( let path = asset.ident().path().await?; let relative_path = context_path .get_relative_path_to(&path) - .unwrap_or_else(|| format!("/{}", path.path)); + .unwrap_or_else(|| format!("/{}", path.path).into()); return Ok(Vc::cell(Some(relative_path))); } @@ -144,7 +144,7 @@ pub async fn resolve_url_reference( pub fn replace_url_references( ss: &mut StyleSheetLike<'static, 'static>, - urls: &HashMap, + urls: &HashMap, ) { let mut replacer = AssetReferenceReplacer { urls }; match ss { @@ -158,7 +158,7 @@ pub fn replace_url_references( } struct AssetReferenceReplacer<'a> { - urls: &'a HashMap, + urls: &'a HashMap, } impl VisitMut for AssetReferenceReplacer<'_> { @@ -193,7 +193,7 @@ impl<'i> Visitor<'i> for AssetReferenceReplacer<'_> { u.visit_children(self)?; if let Some(new) = self.urls.get(&*u.url) { - u.url = new.clone().into(); + u.url = new.to_string().into(); } Ok(()) diff --git a/crates/turbopack-dev-server/src/html.rs b/crates/turbopack-dev-server/src/html.rs index ca54ad8bd9622..fdd2d2f3188d4 100644 --- a/crates/turbopack-dev-server/src/html.rs +++ b/crates/turbopack-dev-server/src/html.rs @@ -1,6 +1,6 @@ use anyhow::{anyhow, Result}; use mime_guess::mime::TEXT_HTML_UTF_8; -use turbo_tasks::{ReadRef, TryJoinIterExt, Value, Vc}; +use turbo_tasks::{RcStr, ReadRef, TryJoinIterExt, Value, Vc}; use turbo_tasks_fs::{File, FileSystemPath}; use turbo_tasks_hash::{encode_hex, Xxh3Hash64Hasher}; use turbopack_core::{ @@ -31,12 +31,12 @@ type DevHtmlEntry = ( pub struct DevHtmlAsset { path: Vc, entries: Vec, - body: Option, + body: Option, } #[turbo_tasks::function] -fn dev_html_chunk_reference_description() -> Vc { - Vc::cell("dev html chunk".to_string()) +fn dev_html_chunk_reference_description() -> Vc { + Vc::cell("dev html chunk".into()) } #[turbo_tasks::value_impl] @@ -80,7 +80,7 @@ impl DevHtmlAsset { pub fn new_with_body( path: Vc, entries: Vec, - body: String, + body: RcStr, ) -> Vc { DevHtmlAsset { path, @@ -101,7 +101,7 @@ impl DevHtmlAsset { } #[turbo_tasks::function] - pub async fn with_body(self: Vc, body: String) -> Result> { + pub async fn with_body(self: Vc, body: RcStr) -> Result> { let mut html: DevHtmlAsset = self.await?.clone_value(); html.body = Some(body); Ok(html.cell()) @@ -118,7 +118,7 @@ impl DevHtmlAsset { for chunk in &*self.chunks().await? { let chunk_path = &*chunk.ident().path().await?; if let Some(relative_path) = context_path.get_path_to(chunk_path) { - chunk_paths.push(format!("/{relative_path}")); + chunk_paths.push(format!("/{relative_path}").into()); } } @@ -167,12 +167,12 @@ impl DevHtmlAsset { #[turbo_tasks::value] struct DevHtmlAssetContent { - chunk_paths: Vec, - body: Option, + chunk_paths: Vec, + body: Option, } impl DevHtmlAssetContent { - fn new(chunk_paths: Vec, body: Option) -> Vc { + fn new(chunk_paths: Vec, body: Option) -> Vc { DevHtmlAssetContent { chunk_paths, body }.cell() } } @@ -204,12 +204,13 @@ impl DevHtmlAssetContent { None => "", }; - let html = format!( + let html: RcStr = format!( "\n\n\n{}\n\n\n{}\n{}\n\n", stylesheets.join("\n"), body, scripts.join("\n"), - ); + ) + .into(); Ok(AssetContent::file( File::from(html).with_content_type(TEXT_HTML_UTF_8).into(), @@ -244,7 +245,7 @@ struct DevHtmlAssetVersion { #[turbo_tasks::value_impl] impl Version for DevHtmlAssetVersion { #[turbo_tasks::function] - async fn id(&self) -> Result> { + async fn id(&self) -> Result> { let mut hasher = Xxh3Hash64Hasher::new(); for relative_path in &*self.content.chunk_paths { hasher.write_ref(relative_path); @@ -254,6 +255,6 @@ impl Version for DevHtmlAssetVersion { } let hash = hasher.finish(); let hex_hash = encode_hex(hash); - Ok(Vc::cell(hex_hash)) + Ok(Vc::cell(hex_hash.into())) } } diff --git a/crates/turbopack-dev-server/src/http.rs b/crates/turbopack-dev-server/src/http.rs index 739bc152a76c4..ad8d50e0b0472 100644 --- a/crates/turbopack-dev-server/src/http.rs +++ b/crates/turbopack-dev-server/src/http.rs @@ -103,15 +103,15 @@ pub async fn process_request_with_content_source( for (header_name, header_value) in headers { header_map.append( - HeaderName::try_from(header_name.clone())?, + HeaderName::try_from(header_name.as_str())?, hyper::header::HeaderValue::try_from(header_value.as_str())?, ); } for (header_name, header_value) in header_overwrites.iter() { header_map.insert( - HeaderName::try_from(header_name.clone())?, - hyper::header::HeaderValue::try_from(header_value)?, + HeaderName::try_from(header_name.as_str())?, + hyper::header::HeaderValue::try_from(header_value.as_str())?, ); } diff --git a/crates/turbopack-dev-server/src/introspect/mod.rs b/crates/turbopack-dev-server/src/introspect/mod.rs index a1f97d72defe9..49ed924a4b454 100644 --- a/crates/turbopack-dev-server/src/introspect/mod.rs +++ b/crates/turbopack-dev-server/src/introspect/mod.rs @@ -1,7 +1,7 @@ use std::{borrow::Cow, collections::HashSet, fmt::Display}; use anyhow::Result; -use turbo_tasks::{ReadRef, TryJoinIterExt, Vc}; +use turbo_tasks::{RcStr, ReadRef, TryJoinIterExt, Vc}; use turbo_tasks_fs::{json::parse_json_with_source_context, File}; use turbopack_core::{ asset::AssetContent, @@ -23,18 +23,18 @@ pub struct IntrospectionSource { #[turbo_tasks::value_impl] impl Introspectable for IntrospectionSource { #[turbo_tasks::function] - fn ty(&self) -> Vc { - Vc::cell("introspection-source".to_string()) + fn ty(&self) -> Vc { + Vc::cell("introspection-source".into()) } #[turbo_tasks::function] - fn title(&self) -> Vc { - Vc::cell("introspection-source".to_string()) + fn title(&self) -> Vc { + Vc::cell("introspection-source".into()) } #[turbo_tasks::function] fn children(&self) -> Vc { - let name = Vc::cell("root".to_string()); + let name = Vc::cell("root".into()); Vc::cell(self.roots.iter().map(|root| (name, *root)).collect()) } } @@ -89,7 +89,7 @@ impl GetContentSourceContent for IntrospectionSource { #[turbo_tasks::function] async fn get( self: Vc, - path: String, + path: RcStr, _data: turbo_tasks::Value, ) -> Result> { // get last segment @@ -105,7 +105,7 @@ impl GetContentSourceContent for IntrospectionSource { parse_json_with_source_context(path)? }; let internal_ty = Vc::debug_identifier(introspectable).await?; - fn str_or_err(s: &Result>) -> Cow<'_, str> { + fn str_or_err(s: &Result>) -> Cow<'_, str> { s.as_ref().map_or_else( |e| Cow::<'_, str>::Owned(format!("ERROR: {:?}", e)), |d| Cow::Borrowed(&**d), @@ -153,21 +153,22 @@ impl GetContentSourceContent for IntrospectionSource { details = HtmlEscaped(details) ) }; - let html = format!( + let html: RcStr = format!( " -{title} - -

{internal_ty}

-

{ty}

-

{title}

- {details} -
    {children}
- -", + {title} + +

{internal_ty}

+

{ty}

+

{title}

+ {details} +
    {children}
+ + ", title = HtmlEscaped(title), ty = HtmlEscaped(ty), children = FormatIter(|| children.iter()) - ); + ) + .into(); Ok(ContentSourceContent::static_content( AssetContent::file( File::from(html) diff --git a/crates/turbopack-dev-server/src/source/asset_graph.rs b/crates/turbopack-dev-server/src/source/asset_graph.rs index cb8d174b30f03..9d95aa7d644ca 100644 --- a/crates/turbopack-dev-server/src/source/asset_graph.rs +++ b/crates/turbopack-dev-server/src/source/asset_graph.rs @@ -5,7 +5,7 @@ use std::{ use anyhow::Result; use indexmap::{indexset, IndexMap, IndexSet}; -use turbo_tasks::{Completion, State, TryJoinIterExt, Value, ValueToString, Vc}; +use turbo_tasks::{Completion, RcStr, State, TryJoinIterExt, Value, ValueToString, Vc}; use turbo_tasks_fs::FileSystemPath; use turbopack_core::{ asset::Asset, @@ -20,9 +20,9 @@ use super::{ }; #[turbo_tasks::value(transparent)] -struct OutputAssetsMap(IndexMap>>); +struct OutputAssetsMap(IndexMap>>); -type ExpandedState = State>; +type ExpandedState = State>; #[turbo_tasks::value(serialization = "none", eq = "manual", cell = "new")] pub struct AssetGraphContentSource { @@ -105,7 +105,7 @@ async fn expand( root_assets: &IndexSet>>, root_path: &FileSystemPath, expanded: Option<&ExpandedState>, -) -> Result>>> { +) -> Result>>> { let mut map = IndexMap::new(); let mut assets = Vec::new(); let mut queue = VecDeque::with_capacity(32); @@ -177,32 +177,32 @@ async fn expand( } for (sub_path, asset) in assets { let asset = asset.resolve().await?; - if sub_path == "index.html" { - map.insert("".to_string(), asset); + if &*sub_path == "index.html" { + map.insert("".into(), asset); } else if let Some(p) = sub_path.strip_suffix("/index.html") { - map.insert(p.to_string(), asset); - map.insert(format!("{p}/"), asset); + map.insert(p.into(), asset); + map.insert(format!("{p}/").into(), asset); } else if let Some(p) = sub_path.strip_suffix(".html") { - map.insert(p.to_string(), asset); + map.insert(p.into(), asset); } map.insert(sub_path, asset); } Ok(map) } -fn get_sub_paths(sub_path: &str) -> ([String; 3], usize) { - let sub_paths_buffer: [String; 3]; +fn get_sub_paths(sub_path: &str) -> ([RcStr; 3], usize) { + let sub_paths_buffer: [RcStr; 3]; let n = if sub_path == "index.html" { - sub_paths_buffer = ["".to_string(), sub_path.to_string(), String::new()]; + sub_paths_buffer = ["".into(), sub_path.into(), Default::default()]; 2 } else if let Some(p) = sub_path.strip_suffix("/index.html") { - sub_paths_buffer = [p.to_string(), format!("{p}/"), sub_path.to_string()]; + sub_paths_buffer = [p.into(), format!("{p}/").into(), sub_path.into()]; 3 } else if let Some(p) = sub_path.strip_suffix(".html") { - sub_paths_buffer = [p.to_string(), sub_path.to_string(), String::new()]; + sub_paths_buffer = [p.into(), sub_path.into(), Default::default()]; 2 } else { - sub_paths_buffer = [sub_path.to_string(), String::new(), String::new()]; + sub_paths_buffer = [sub_path.into(), Default::default(), Default::default()]; 1 }; (sub_paths_buffer, n) @@ -223,7 +223,7 @@ impl ContentSource for AssetGraphContentSource { RouteType::Exact, Vc::upcast(AssetGraphGetContentSourceContent::new( self, - path.to_string(), + path.clone(), *asset, )), ) @@ -236,7 +236,7 @@ impl ContentSource for AssetGraphContentSource { #[turbo_tasks::value] struct AssetGraphGetContentSourceContent { source: Vc, - path: String, + path: RcStr, asset: Vc>, } @@ -245,7 +245,7 @@ impl AssetGraphGetContentSourceContent { #[turbo_tasks::function] pub fn new( source: Vc, - path: String, + path: RcStr, asset: Vc>, ) -> Vc { Self::cell(AssetGraphGetContentSourceContent { @@ -261,7 +261,7 @@ impl GetContentSourceContent for AssetGraphGetContentSourceContent { #[turbo_tasks::function] async fn get( self: Vc, - _path: String, + _path: RcStr, _data: Value, ) -> Result> { let this = self.await?; @@ -279,44 +279,44 @@ impl ContentSourceSideEffect for AssetGraphGetContentSourceContent { let source = self.source.await?; if let Some(expanded) = &source.expanded { - expanded.update_conditionally(|expanded| expanded.insert(self.path.to_string())); + expanded.update_conditionally(|expanded| expanded.insert(self.path.clone())); } Ok(Completion::new()) } } #[turbo_tasks::function] -fn introspectable_type() -> Vc { - Vc::cell("asset graph content source".to_string()) +fn introspectable_type() -> Vc { + Vc::cell("asset graph content source".into()) } #[turbo_tasks::value_impl] impl Introspectable for AssetGraphContentSource { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { introspectable_type() } #[turbo_tasks::function] - fn title(&self) -> Vc { + fn title(&self) -> Vc { self.root_path.to_string() } #[turbo_tasks::function] - fn details(&self) -> Vc { + fn details(&self) -> Vc { Vc::cell(if let Some(expanded) = &self.expanded { - format!("{} assets expanded", expanded.get().len()) + format!("{} assets expanded", expanded.get().len()).into() } else { - "eager".to_string() + "eager".into() }) } #[turbo_tasks::function] async fn children(self: Vc) -> Result> { let this = self.await?; - let key = Vc::cell("root".to_string()); - let inner_key = Vc::cell("inner".to_string()); - let expanded_key = Vc::cell("expanded".to_string()); + let key = Vc::cell("root".into()); + let inner_key = Vc::cell("inner".into()); + let expanded_key = Vc::cell("expanded".into()); let root_assets = this.root_assets.await?; let root_asset_children = root_assets @@ -344,8 +344,8 @@ impl Introspectable for AssetGraphContentSource { } #[turbo_tasks::function] -fn fully_expaned_introspectable_type() -> Vc { - Vc::cell("fully expanded asset graph content source".to_string()) +fn fully_expaned_introspectable_type() -> Vc { + Vc::cell("fully expanded asset graph content source".into()) } #[turbo_tasks::value] @@ -354,19 +354,19 @@ struct FullyExpaned(Vc); #[turbo_tasks::value_impl] impl Introspectable for FullyExpaned { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { fully_expaned_introspectable_type() } #[turbo_tasks::function] - async fn title(&self) -> Result> { + async fn title(&self) -> Result> { Ok(self.0.await?.root_path.to_string()) } #[turbo_tasks::function] async fn children(&self) -> Result> { let source = self.0.await?; - let key = Vc::cell("asset".to_string()); + let key = Vc::cell("asset".into()); let expanded_assets = expand(&*source.root_assets.await?, &*source.root_path.await?, None).await?; diff --git a/crates/turbopack-dev-server/src/source/combined.rs b/crates/turbopack-dev-server/src/source/combined.rs index 076498ce373f9..f466d898b612f 100644 --- a/crates/turbopack-dev-server/src/source/combined.rs +++ b/crates/turbopack-dev-server/src/source/combined.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{TryJoinIterExt, Vc}; +use turbo_tasks::{RcStr, TryJoinIterExt, Vc}; use turbopack_core::introspect::{Introspectable, IntrospectableChildren}; use super::{ @@ -39,12 +39,12 @@ impl ContentSource for CombinedContentSource { #[turbo_tasks::value_impl] impl Introspectable for CombinedContentSource { #[turbo_tasks::function] - fn ty(&self) -> Vc { - Vc::cell("combined content source".to_string()) + fn ty(&self) -> Vc { + Vc::cell("combined content source".into()) } #[turbo_tasks::function] - async fn title(&self) -> Result> { + async fn title(&self) -> Result> { let titles = self .sources .iter() @@ -73,12 +73,12 @@ impl Introspectable for CombinedContentSource { if titles.len() > NUMBER_OF_TITLES_TO_DISPLAY { titles[NUMBER_OF_TITLES_TO_DISPLAY] = "..."; } - Ok(Vc::cell(titles.join(", "))) + Ok(Vc::cell(titles.join(", ").into())) } #[turbo_tasks::function] async fn children(&self) -> Result> { - let source = Vc::cell("source".to_string()); + let source = Vc::cell("source".into()); Ok(Vc::cell( self.sources .iter() diff --git a/crates/turbopack-dev-server/src/source/conditional.rs b/crates/turbopack-dev-server/src/source/conditional.rs index ff6f66fd4c623..6638ef21a6235 100644 --- a/crates/turbopack-dev-server/src/source/conditional.rs +++ b/crates/turbopack-dev-server/src/source/conditional.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{Completion, State, Value, Vc}; +use turbo_tasks::{Completion, RcStr, State, Value, Vc}; use turbopack_core::introspect::{Introspectable, IntrospectableChildren}; use super::{ @@ -86,47 +86,47 @@ impl MapGetContentSourceContent for ConditionalContentSourceMapper { } #[turbo_tasks::function] -fn introspectable_type() -> Vc { - Vc::cell("conditional content source".to_string()) +fn introspectable_type() -> Vc { + Vc::cell("conditional content source".into()) } #[turbo_tasks::function] -fn activator_key() -> Vc { - Vc::cell("activator".to_string()) +fn activator_key() -> Vc { + Vc::cell("activator".into()) } #[turbo_tasks::function] -fn action_key() -> Vc { - Vc::cell("action".to_string()) +fn action_key() -> Vc { + Vc::cell("action".into()) } #[turbo_tasks::value_impl] impl Introspectable for ConditionalContentSource { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { introspectable_type() } #[turbo_tasks::function] - async fn details(&self) -> Result> { + async fn details(&self) -> Result> { Ok(Vc::cell( if *self.activated.get() { "activated" } else { "not activated" } - .to_string(), + .into(), )) } #[turbo_tasks::function] - async fn title(&self) -> Result> { + async fn title(&self) -> Result> { if let Some(activator) = Vc::try_resolve_sidecast::>(self.activator).await? { Ok(activator.title()) } else { - Ok(Vc::::default()) + Ok(Vc::::default()) } } @@ -164,7 +164,7 @@ impl GetContentSourceContent for ActivateOnGetContentSource { #[turbo_tasks::function] async fn get( self: Vc, - path: String, + path: RcStr, data: Value, ) -> Result> { turbo_tasks::emit(Vc::upcast::>(self)); diff --git a/crates/turbopack-dev-server/src/source/issue_context.rs b/crates/turbopack-dev-server/src/source/issue_context.rs index b4d71bacad438..e127955c19c73 100644 --- a/crates/turbopack-dev-server/src/source/issue_context.rs +++ b/crates/turbopack-dev-server/src/source/issue_context.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::{RcStr, Value, Vc}; use turbo_tasks_fs::FileSystemPath; use turbopack_core::{ introspect::{Introspectable, IntrospectableChildren}, @@ -15,7 +15,7 @@ use super::{ #[turbo_tasks::value] pub struct IssueFilePathContentSource { file_path: Option>, - description: String, + description: RcStr, source: Vc>, } @@ -24,7 +24,7 @@ impl IssueFilePathContentSource { #[turbo_tasks::function] pub fn new_file_path( file_path: Vc, - description: String, + description: RcStr, source: Vc>, ) -> Vc { IssueFilePathContentSource { @@ -36,7 +36,7 @@ impl IssueFilePathContentSource { } #[turbo_tasks::function] - pub fn new_description(description: String, source: Vc>) -> Vc { + pub fn new_description(description: RcStr, source: Vc>) -> Vc { IssueFilePathContentSource { file_path: None, description, @@ -54,7 +54,7 @@ impl ContentSource for IssueFilePathContentSource { let routes = this .source .get_routes() - .issue_file_path(this.file_path, &this.description) + .issue_file_path(this.file_path, &*this.description) .await?; Ok(routes.map_routes(Vc::upcast( IssueContextContentSourceMapper { source: self }.cell(), @@ -103,7 +103,7 @@ impl GetContentSourceContent for IssueContextGetContentSourceContent { let result = self .get_content .vary() - .issue_file_path(source.file_path, &source.description) + .issue_file_path(source.file_path, &*source.description) .await?; Ok(result) } @@ -111,14 +111,14 @@ impl GetContentSourceContent for IssueContextGetContentSourceContent { #[turbo_tasks::function] async fn get( &self, - path: String, + path: RcStr, data: Value, ) -> Result> { let source = self.source.await?; let result = self .get_content .get(path, data) - .issue_file_path(source.file_path, &source.description) + .issue_file_path(source.file_path, &*source.description) .await?; Ok(result) } @@ -127,26 +127,26 @@ impl GetContentSourceContent for IssueContextGetContentSourceContent { #[turbo_tasks::value_impl] impl Introspectable for IssueFilePathContentSource { #[turbo_tasks::function] - async fn ty(&self) -> Result> { + async fn ty(&self) -> Result> { Ok( if let Some(source) = Vc::try_resolve_sidecast::>(self.source).await? { source.ty() } else { - Vc::cell("IssueContextContentSource".to_string()) + Vc::cell("IssueContextContentSource".into()) }, ) } #[turbo_tasks::function] - async fn title(&self) -> Result> { + async fn title(&self) -> Result> { Ok( if let Some(source) = Vc::try_resolve_sidecast::>(self.source).await? { let title = source.title().await?; - Vc::cell(format!("{}: {}", self.description, title)) + Vc::cell(format!("{}: {}", self.description, title).into()) } else { Vc::cell(self.description.clone()) }, @@ -154,14 +154,14 @@ impl Introspectable for IssueFilePathContentSource { } #[turbo_tasks::function] - async fn details(&self) -> Result> { + async fn details(&self) -> Result> { Ok( if let Some(source) = Vc::try_resolve_sidecast::>(self.source).await? { source.details() } else { - Vc::cell(String::new()) + Vc::cell(RcStr::default()) }, ) } diff --git a/crates/turbopack-dev-server/src/source/lazy_instantiated.rs b/crates/turbopack-dev-server/src/source/lazy_instantiated.rs index 9df9c3b3fce37..4841da72aa9c8 100644 --- a/crates/turbopack-dev-server/src/source/lazy_instantiated.rs +++ b/crates/turbopack-dev-server/src/source/lazy_instantiated.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbopack_core::introspect::{Introspectable, IntrospectableChildren}; use super::{route_tree::RouteTree, ContentSource}; @@ -28,19 +28,19 @@ impl ContentSource for LazyInstantiatedContentSource { } #[turbo_tasks::function] -fn introspectable_type() -> Vc { - Vc::cell("lazy instantiated content source".to_string()) +fn introspectable_type() -> Vc { + Vc::cell("lazy instantiated content source".into()) } #[turbo_tasks::function] -fn source_key() -> Vc { - Vc::cell("source".to_string()) +fn source_key() -> Vc { + Vc::cell("source".into()) } #[turbo_tasks::value_impl] impl Introspectable for LazyInstantiatedContentSource { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { introspectable_type() } diff --git a/crates/turbopack-dev-server/src/source/mod.rs b/crates/turbopack-dev-server/src/source/mod.rs index 2b03c7dd95d50..26870a1f399c3 100644 --- a/crates/turbopack-dev-server/src/source/mod.rs +++ b/crates/turbopack-dev-server/src/source/mod.rs @@ -18,7 +18,7 @@ use anyhow::Result; use futures::{stream::Stream as StreamTrait, TryStreamExt}; use serde::{Deserialize, Serialize}; use turbo_tasks::{ - trace::TraceRawVcs, util::SharedError, Completion, Upcast, Value, ValueDefault, Vc, + trace::TraceRawVcs, util::SharedError, Completion, RcStr, Upcast, Value, ValueDefault, Vc, }; use turbo_tasks_bytes::{Bytes, Stream, StreamRead}; use turbo_tasks_fs::FileSystemPath; @@ -36,7 +36,7 @@ pub struct ProxyResult { /// The HTTP status code to return. pub status: u16, /// Headers arranged as contiguous (name, value) pairs. - pub headers: Vec<(String, String)>, + pub headers: Vec<(RcStr, RcStr)>, /// The body to return. pub body: Body, } @@ -44,7 +44,7 @@ pub struct ProxyResult { #[turbo_tasks::value_impl] impl Version for ProxyResult { #[turbo_tasks::function] - async fn id(&self) -> Result> { + async fn id(&self) -> Result> { let mut hash = Xxh3Hash64Hasher::new(); hash.write_u16(self.status); for (name, value) in &self.headers { @@ -55,7 +55,7 @@ impl Version for ProxyResult { while let Some(chunk) = read.try_next().await? { hash.write_bytes(&chunk); } - Ok(Vc::cell(hash.finish().to_string())) + Ok(Vc::cell(hash.finish().to_string().into())) } } @@ -69,11 +69,8 @@ pub trait GetContentSourceContent { } /// Get the content - fn get( - self: Vc, - path: String, - data: Value, - ) -> Vc; + fn get(self: Vc, path: RcStr, data: Value) + -> Vc; } #[turbo_tasks::value(transparent)] @@ -111,7 +108,7 @@ impl GetContentSourceContent for ContentSourceContent { #[turbo_tasks::function] fn get( self: Vc, - _path: String, + _path: RcStr, _data: Value, ) -> Vc { self @@ -158,12 +155,12 @@ impl ContentSourceContent { /// A list of headers arranged as contiguous (name, value) pairs. #[turbo_tasks::value(transparent)] -pub struct HeaderList(Vec<(String, String)>); +pub struct HeaderList(Vec<(RcStr, RcStr)>); #[turbo_tasks::value_impl] impl HeaderList { #[turbo_tasks::function] - pub fn new(headers: Vec<(String, String)>) -> Vc { + pub fn new(headers: Vec<(RcStr, RcStr)>) -> Vc { HeaderList(headers).cell() } @@ -183,22 +180,22 @@ impl HeaderList { #[derive(Clone, Debug, PartialOrd, Ord, Hash, Default)] pub struct ContentSourceData { /// HTTP method, if requested. - pub method: Option, + pub method: Option, /// The full url (including query string), if requested. - pub url: Option, + pub url: Option, /// The full url (including query string) before rewrites where applied, if /// requested. - pub original_url: Option, + pub original_url: Option, /// Query string items, if requested. pub query: Option, /// raw query string, if requested. Does not include the `?`. - pub raw_query: Option, + pub raw_query: Option, /// HTTP headers, might contain multiple headers with the same name, if /// requested. pub headers: Option, /// Raw HTTP headers, might contain multiple headers with the same name, if /// requested. - pub raw_headers: Option>, + pub raw_headers: Option>, /// Request body, if requested. pub body: Option>, /// See [ContentSourceDataVary::cache_buster]. @@ -423,7 +420,7 @@ pub trait ContentSourceExt: Send { fn issue_file_path( self: Vc, file_path: Vc, - description: String, + description: RcStr, ) -> Vc>; } @@ -434,7 +431,7 @@ where fn issue_file_path( self: Vc, file_path: Vc, - description: String, + description: RcStr, ) -> Vc> { Vc::upcast(IssueFilePathContentSource::new_file_path( file_path, @@ -480,7 +477,7 @@ pub enum RewriteType { Location { /// The new path and query used to lookup content. This _does not_ need /// to be the original path or query. - path_and_query: String, + path_and_query: RcStr, }, ContentSource { /// [Vc>]s from which to restart the lookup @@ -489,7 +486,7 @@ pub enum RewriteType { source: Vc>, /// The new path and query used to lookup content. This _does not_ need /// to be the original path or query. - path_and_query: String, + path_and_query: RcStr, }, Sources { /// [GetContentSourceContent]s from which to restart the lookup @@ -520,7 +517,7 @@ pub struct RewriteBuilder { } impl RewriteBuilder { - pub fn new(path_and_query: String) -> Self { + pub fn new(path_and_query: RcStr) -> Self { Self { rewrite: Rewrite { ty: RewriteType::Location { path_and_query }, @@ -532,7 +529,7 @@ impl RewriteBuilder { pub fn new_source_with_path_and_query( source: Vc>, - path_and_query: String, + path_and_query: RcStr, ) -> Self { Self { rewrite: Rewrite { diff --git a/crates/turbopack-dev-server/src/source/resolve.rs b/crates/turbopack-dev-server/src/source/resolve.rs index 88a4d3ab86371..8b56aa7c6c4e0 100644 --- a/crates/turbopack-dev-server/src/source/resolve.rs +++ b/crates/turbopack-dev-server/src/source/resolve.rs @@ -8,7 +8,7 @@ use hyper::{ header::{HeaderName as HyperHeaderName, HeaderValue as HyperHeaderValue}, Uri, }; -use turbo_tasks::{TransientInstance, Value, Vc}; +use turbo_tasks::{RcStr, TransientInstance, Value, Vc}; use super::{ headers::{HeaderValue, Headers}, @@ -43,7 +43,7 @@ pub async fn resolve_source_request( ) -> Result> { let original_path = request.uri.path().to_string(); // Remove leading slash. - let mut current_asset_path = urlencoding::decode(&original_path[1..])?.into_owned(); + let mut current_asset_path: RcStr = urlencoding::decode(&original_path[1..])?.into(); let mut request_overwrites = (*request).clone(); let mut response_header_overwrites = Vec::new(); let mut route_tree = source.get_routes().resolve_strongly_consistent().await?; @@ -66,30 +66,30 @@ pub async fn resolve_source_request( request_overwrites.headers.clear(); for (name, value) in &*headers.await? { request_overwrites.headers.insert( - HyperHeaderName::try_from(name)?, - HyperHeaderValue::try_from(value)?, + HyperHeaderName::try_from(name.as_str())?, + HyperHeaderValue::try_from(value.as_str())?, ); } } // do the rewrite match &rewrite.ty { RewriteType::Location { path_and_query } => { - let new_uri = Uri::try_from(path_and_query)?; + let new_uri = Uri::try_from(path_and_query.as_str())?; let new_asset_path = urlencoding::decode(&new_uri.path()[1..])?.into_owned(); request_overwrites.uri = new_uri; - current_asset_path = new_asset_path; + current_asset_path = new_asset_path.into(); continue 'routes; } RewriteType::ContentSource { source, path_and_query, } => { - let new_uri = Uri::try_from(path_and_query)?; + let new_uri = Uri::try_from(path_and_query.as_str())?; let new_asset_path = urlencoding::decode(&new_uri.path()[1..])?.into_owned(); request_overwrites.uri = new_uri; - current_asset_path = new_asset_path; + current_asset_path = new_asset_path.into(); route_tree = source.get_routes().resolve_strongly_consistent().await?; continue 'routes; @@ -134,26 +134,28 @@ async fn request_to_data( ) -> Result { let mut data = ContentSourceData::default(); if vary.method { - data.method = Some(request.method.clone()); + data.method = Some(request.method.clone().into()); } if vary.url { - data.url = Some(request.uri.to_string()); + data.url = Some(request.uri.to_string().into()); } if vary.original_url { - data.original_url = Some(original_request.uri.to_string()); + data.original_url = Some(original_request.uri.to_string().into()); } if vary.body { data.body = Some(request.body.clone().into()); } if vary.raw_query { - data.raw_query = Some(request.uri.query().unwrap_or("").to_string()); + data.raw_query = Some(request.uri.query().unwrap_or("").into()); } if vary.raw_headers { data.raw_headers = Some( request .headers .iter() - .map(|(name, value)| Ok((name.to_string(), value.to_str()?.to_string()))) + .map(|(name, value)| { + Ok((name.to_string().into(), value.to_str()?.to_string().into())) + }) .collect::>>()?, ); } diff --git a/crates/turbopack-dev-server/src/source/route_tree.rs b/crates/turbopack-dev-server/src/source/route_tree.rs index 373f62a7814ef..58f2c188a1f4d 100644 --- a/crates/turbopack-dev-server/src/source/route_tree.rs +++ b/crates/turbopack-dev-server/src/source/route_tree.rs @@ -3,7 +3,7 @@ use std::{fmt::Write, mem::replace}; use anyhow::Result; use indexmap::IndexMap; use serde::{Deserialize, Serialize}; -use turbo_tasks::{trace::TraceRawVcs, TaskInput, TryJoinIterExt, ValueToString, Vc}; +use turbo_tasks::{trace::TraceRawVcs, RcStr, TaskInput, TryJoinIterExt, ValueToString, Vc}; use super::{GetContentSourceContent, GetContentSourceContents}; @@ -20,7 +20,7 @@ pub enum RouteType { /// Some normal segment of a route. #[derive(TaskInput, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs)] pub enum BaseSegment { - Static(String), + Static(RcStr), Dynamic, } @@ -28,7 +28,7 @@ impl BaseSegment { pub fn from_static_pathname(str: &str) -> impl Iterator + '_ { str.split('/') .filter(|s| !s.is_empty()) - .map(|s| BaseSegment::Static(s.to_string())) + .map(|s| BaseSegment::Static(s.into())) } } @@ -98,7 +98,7 @@ impl RouteTrees { pub struct RouteTree { base: Vec, sources: Vec>>, - static_segments: IndexMap>, + static_segments: IndexMap>, dynamic_segments: Vec>, catch_all_sources: Vec>>, fallback_sources: Vec>>, @@ -186,7 +186,7 @@ impl RouteTree { #[turbo_tasks::value_impl] impl ValueToString for RouteTree { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { + async fn to_string(&self) -> Result> { let RouteTree { base, sources, @@ -229,7 +229,7 @@ impl ValueToString for RouteTree { result.truncate(result.len() - 2); } result.push(')'); - Ok(Vc::cell(result)) + Ok(Vc::cell(result.into())) } } @@ -255,7 +255,7 @@ impl RouteTree { // TODO(WEB-1252) It's unneccesary to compute all [`GetContentSourceContent`]s at once, we could // return some lazy iterator to make it more efficient. #[turbo_tasks::function] - pub async fn get(self: Vc, path: String) -> Result> { + pub async fn get(self: Vc, path: RcStr) -> Result> { let RouteTree { base, sources, @@ -292,10 +292,10 @@ impl RouteTree { if let Some(segment) = segments.next() { let remainder = segments.remainder().unwrap_or(""); if let Some(tree) = static_segments.get(segment) { - results.extend(tree.get(remainder.to_string()).await?.iter().copied()); + results.extend(tree.get(remainder.into()).await?.iter().copied()); } for tree in dynamic_segments.iter() { - results.extend(tree.get(remainder.to_string()).await?.iter().copied()); + results.extend(tree.get(remainder.into()).await?.iter().copied()); } } else { results.extend(sources.iter().copied()); diff --git a/crates/turbopack-dev-server/src/source/router.rs b/crates/turbopack-dev-server/src/source/router.rs index e8cf233190635..d62db2a1f891f 100644 --- a/crates/turbopack-dev-server/src/source/router.rs +++ b/crates/turbopack-dev-server/src/source/router.rs @@ -1,7 +1,7 @@ use std::iter::once; use anyhow::Result; -use turbo_tasks::{TryJoinIterExt, Value, Vc}; +use turbo_tasks::{RcStr, TryJoinIterExt, Value, Vc}; use turbopack_core::introspect::{Introspectable, IntrospectableChildren}; use super::{ @@ -17,8 +17,8 @@ use crate::source::{route_tree::MapGetContentSourceContent, ContentSources}; /// other subpaths, including if the request path does not include the prefix. #[turbo_tasks::value(shared)] pub struct PrefixedRouterContentSource { - pub prefix: Vc, - pub routes: Vec<(String, Vc>)>, + pub prefix: Vc, + pub routes: Vec<(RcStr, Vc>)>, pub fallback: Vc>, } @@ -26,8 +26,8 @@ pub struct PrefixedRouterContentSource { impl PrefixedRouterContentSource { #[turbo_tasks::function] pub async fn new( - prefix: Vc, - routes: Vec<(String, Vc>)>, + prefix: Vc, + routes: Vec<(RcStr, Vc>)>, fallback: Vc>, ) -> Result> { Ok(PrefixedRouterContentSource { @@ -40,7 +40,7 @@ impl PrefixedRouterContentSource { } fn get_children( - routes: &[(String, Vc>)], + routes: &[(RcStr, Vc>)], fallback: &Vc>, ) -> Vc { Vc::cell( @@ -53,14 +53,14 @@ fn get_children( } async fn get_introspection_children( - routes: &[(String, Vc>)], + routes: &[(RcStr, Vc>)], fallback: &Vc>, ) -> Result> { Ok(Vc::cell( routes .iter() .cloned() - .chain(std::iter::once((String::new(), *fallback))) + .chain(std::iter::once((RcStr::default(), *fallback))) .map(|(path, source)| async move { Ok(Vc::try_resolve_sidecast::>(source) .await? @@ -119,8 +119,8 @@ impl ContentSource for PrefixedRouterContentSource { #[turbo_tasks::value] struct PrefixedRouterContentSourceMapper { - prefix: Vc, - path: String, + prefix: Vc, + path: RcStr, } #[turbo_tasks::value_impl] @@ -156,17 +156,17 @@ impl GetContentSourceContent for PrefixedRouterGetContentSourceContent { #[turbo_tasks::function] async fn get( &self, - path: String, + path: RcStr, data: Value, ) -> Result> { let prefix = self.mapper.await?.prefix.await?; - if let Some(path) = path.strip_prefix(&*prefix) { + if let Some(path) = path.strip_prefix(&**prefix) { if path.is_empty() { - return Ok(self.get_content.get("".to_string(), data)); + return Ok(self.get_content.get("".into(), data)); } else if prefix.is_empty() { - return Ok(self.get_content.get(path.to_string(), data)); + return Ok(self.get_content.get(path.into(), data)); } else if let Some(path) = path.strip_prefix('/') { - return Ok(self.get_content.get(path.to_string(), data)); + return Ok(self.get_content.get(path.into(), data)); } } Ok(ContentSourceContent::not_found()) @@ -176,14 +176,14 @@ impl GetContentSourceContent for PrefixedRouterGetContentSourceContent { #[turbo_tasks::value_impl] impl Introspectable for PrefixedRouterContentSource { #[turbo_tasks::function] - fn ty(&self) -> Vc { - Vc::cell("prefixed router content source".to_string()) + fn ty(&self) -> Vc { + Vc::cell("prefixed router content source".into()) } #[turbo_tasks::function] - async fn details(&self) -> Result> { + async fn details(&self) -> Result> { let prefix = self.prefix.await?; - Ok(Vc::cell(format!("prefix: '{}'", prefix))) + Ok(Vc::cell(format!("prefix: '{}'", prefix).into())) } #[turbo_tasks::function] diff --git a/crates/turbopack-dev-server/src/source/static_assets.rs b/crates/turbopack-dev-server/src/source/static_assets.rs index 0e938d7751d23..dc8ef38e3984f 100644 --- a/crates/turbopack-dev-server/src/source/static_assets.rs +++ b/crates/turbopack-dev-server/src/source/static_assets.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::{RcStr, Value, Vc}; use turbo_tasks_fs::{DirectoryContent, DirectoryEntry, FileSystemPath}; use turbopack_core::{ asset::Asset, @@ -15,7 +15,7 @@ use super::{ #[turbo_tasks::value(shared)] pub struct StaticAssetsContentSource { - pub prefix: Vc, + pub prefix: Vc, pub dir: Vc, } @@ -23,13 +23,13 @@ pub struct StaticAssetsContentSource { impl StaticAssetsContentSource { // TODO(WEB-1151): Remove this method and migrate users to `with_prefix`. #[turbo_tasks::function] - pub fn new(prefix: String, dir: Vc) -> Vc { + pub fn new(prefix: RcStr, dir: Vc) -> Vc { StaticAssetsContentSource::with_prefix(Vc::cell(prefix), dir) } #[turbo_tasks::function] pub async fn with_prefix( - prefix: Vc, + prefix: Vc, dir: Vc, ) -> Result> { if cfg!(debug_assertions) { @@ -95,7 +95,7 @@ impl StaticAssetsContentSourceItem { #[turbo_tasks::value_impl] impl GetContentSourceContent for StaticAssetsContentSourceItem { #[turbo_tasks::function] - fn get(&self, _path: String, _data: Value) -> Vc { + fn get(&self, _path: RcStr, _data: Value) -> Vc { let content = Vc::upcast::>(FileSource::new(self.path)).content(); ContentSourceContent::static_content(content.versioned()) } @@ -104,8 +104,8 @@ impl GetContentSourceContent for StaticAssetsContentSourceItem { #[turbo_tasks::value_impl] impl Introspectable for StaticAssetsContentSource { #[turbo_tasks::function] - fn ty(&self) -> Vc { - Vc::cell("static assets directory content source".to_string()) + fn ty(&self) -> Vc { + Vc::cell("static assets directory content source".into()) } #[turbo_tasks::function] @@ -125,7 +125,7 @@ impl Introspectable for StaticAssetsContentSource { } DirectoryEntry::Directory(path) => { Vc::upcast(StaticAssetsContentSource::with_prefix( - Vc::cell(format!("{}{name}/", &*prefix)), + Vc::cell(format!("{}{name}/", &*prefix).into()), *path, )) } diff --git a/crates/turbopack-dev-server/src/source/wrapping_source.rs b/crates/turbopack-dev-server/src/source/wrapping_source.rs index 55eebeaeec162..513e1704bf602 100644 --- a/crates/turbopack-dev-server/src/source/wrapping_source.rs +++ b/crates/turbopack-dev-server/src/source/wrapping_source.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::{RcStr, Value, Vc}; use super::{ ContentSourceContent, ContentSourceData, ContentSourceDataVary, GetContentSourceContent, @@ -49,7 +49,7 @@ impl GetContentSourceContent for WrappedGetContentSourceContent { #[turbo_tasks::function] async fn get( &self, - path: String, + path: RcStr, data: Value, ) -> Result> { let res = self.inner.get(path, data); diff --git a/crates/turbopack-dev-server/src/update/server.rs b/crates/turbopack-dev-server/src/update/server.rs index dbff868f5a20a..04e41444ef0e9 100644 --- a/crates/turbopack-dev-server/src/update/server.rs +++ b/crates/turbopack-dev-server/src/update/server.rs @@ -74,7 +74,7 @@ impl UpdateServer

{ ) } }; - match UpdateStream::new(resource.to_string(), TransientInstance::new(Box::new(get_content))).await { + match UpdateStream::new(resource.to_string().into(), TransientInstance::new(Box::new(get_content))).await { Ok(stream) => { streams.insert(resource, stream); } diff --git a/crates/turbopack-dev-server/src/update/stream.rs b/crates/turbopack-dev-server/src/update/stream.rs index af23e8f1598b3..a287e7ed7c1f1 100644 --- a/crates/turbopack-dev-server/src/update/stream.rs +++ b/crates/turbopack-dev-server/src/update/stream.rs @@ -5,7 +5,7 @@ use futures::prelude::*; use tokio::sync::mpsc::Sender; use tokio_stream::wrappers::ReceiverStream; use tracing::Instrument; -use turbo_tasks::{IntoTraitRef, ReadRef, TransientInstance, Vc}; +use turbo_tasks::{IntoTraitRef, RcStr, ReadRef, TransientInstance, Vc}; use turbo_tasks_fs::{FileSystem, FileSystemPath}; use turbopack_core::{ error::PrettyPrintError, @@ -42,7 +42,7 @@ fn extend_issues(issues: &mut Vec>, new_issues: Vec, get_content: TransientInstance, ) -> Result> { @@ -55,8 +55,9 @@ async fn get_update_stream_item( Err(e) => { plain_issues.push( FatalStreamIssue { - resource: resource.to_string(), - description: StyledString::Text(format!("{}", PrettyPrintError(&e))).cell(), + resource, + description: StyledString::Text(format!("{}", PrettyPrintError(&e)).into()) + .cell(), } .cell() .into_plain(OptionIssueProcessingPathItems::none()) @@ -159,7 +160,7 @@ async fn get_update_stream_item( #[turbo_tasks::function] async fn compute_update_stream( - resource: String, + resource: RcStr, from: Vc, get_content: TransientInstance, sender: TransientInstance>>>, @@ -181,7 +182,7 @@ pub(super) struct UpdateStream( impl UpdateStream { #[tracing::instrument(skip(get_content), name = "UpdateStream::new")] pub async fn new( - resource: String, + resource: RcStr, get_content: TransientInstance, ) -> Result { let (sx, rx) = tokio::sync::mpsc::channel(32); @@ -281,7 +282,7 @@ pub enum UpdateStreamItem { #[turbo_tasks::value(serialization = "none")] struct FatalStreamIssue { description: Vc, - resource: String, + resource: RcStr, } #[turbo_tasks::value_impl] @@ -303,7 +304,7 @@ impl Issue for FatalStreamIssue { #[turbo_tasks::function] fn title(&self) -> Vc { - StyledString::Text("Fatal error while getting content to stream".to_string()).cell() + StyledString::Text("Fatal error while getting content to stream".into()).cell() } #[turbo_tasks::function] diff --git a/crates/turbopack-ecmascript-plugins/src/transform/directives/client.rs b/crates/turbopack-ecmascript-plugins/src/transform/directives/client.rs index e85eeb1f59381..58e4f7b92b368 100644 --- a/crates/turbopack-ecmascript-plugins/src/transform/directives/client.rs +++ b/crates/turbopack-ecmascript-plugins/src/transform/directives/client.rs @@ -1,18 +1,18 @@ use anyhow::Result; use async_trait::async_trait; use swc_core::ecma::{ast::Program, transforms::base::resolver, visit::VisitMutWith}; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbopack_ecmascript::{CustomTransformer, TransformContext}; use super::{is_client_module, server_to_client_proxy::create_proxy_module}; #[derive(Debug)] pub struct ClientDirectiveTransformer { - transition_name: Vc, + transition_name: Vc, } impl ClientDirectiveTransformer { - pub fn new(transition_name: Vc) -> Self { + pub fn new(transition_name: Vc) -> Self { Self { transition_name } } } diff --git a/crates/turbopack-ecmascript-plugins/src/transform/directives/server.rs b/crates/turbopack-ecmascript-plugins/src/transform/directives/server.rs index deb22705bb3b8..8d9c70bd58deb 100644 --- a/crates/turbopack-ecmascript-plugins/src/transform/directives/server.rs +++ b/crates/turbopack-ecmascript-plugins/src/transform/directives/server.rs @@ -4,7 +4,7 @@ use swc_core::{ ecma::ast::{ModuleItem, Program}, quote, }; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbopack_core::issue::IssueExt; use turbopack_ecmascript::{CustomTransformer, TransformContext, UnsupportedServerActionIssue}; @@ -15,11 +15,11 @@ pub struct ServerDirectiveTransformer { // ServerDirective is not implemented yet and always reports an issue. // We don't have to pass a valid transition name yet, but the API is prepared. #[allow(unused)] - transition_name: Vc, + transition_name: Vc, } impl ServerDirectiveTransformer { - pub fn new(transition_name: &Vc) -> Self { + pub fn new(transition_name: &Vc) -> Self { Self { transition_name: *transition_name, } diff --git a/crates/turbopack-ecmascript-plugins/src/transform/swc_ecma_transform_plugins.rs b/crates/turbopack-ecmascript-plugins/src/transform/swc_ecma_transform_plugins.rs index e75b328267dc0..04d1e4fa52c3e 100644 --- a/crates/turbopack-ecmascript-plugins/src/transform/swc_ecma_transform_plugins.rs +++ b/crates/turbopack-ecmascript-plugins/src/transform/swc_ecma_transform_plugins.rs @@ -66,7 +66,7 @@ impl Issue for UnsupportedSwcEcmaTransformPluginsIssue { #[turbo_tasks::function] async fn title(&self) -> Result> { Ok(StyledString::Text( - "Unsupported SWC EcmaScript transform plugins on this platform.".to_string(), + "Unsupported SWC EcmaScript transform plugins on this platform.".into(), ) .cell()) } @@ -82,7 +82,7 @@ impl Issue for UnsupportedSwcEcmaTransformPluginsIssue { StyledString::Text( "Turbopack does not yet support running SWC EcmaScript transform plugins on this \ platform." - .to_string(), + .into(), ) .cell(), )) diff --git a/crates/turbopack-ecmascript-runtime/src/asset_context.rs b/crates/turbopack-ecmascript-runtime/src/asset_context.rs index dd8730381049d..cef6c325e339d 100644 --- a/crates/turbopack-ecmascript-runtime/src/asset_context.rs +++ b/crates/turbopack-ecmascript-runtime/src/asset_context.rs @@ -23,7 +23,7 @@ pub fn get_runtime_asset_context(environment: Vc) -> Vc) -> Result, - chunk_base_path: Vc>, - output_root: Vc, + chunk_base_path: Vc>, + output_root: Vc, ) -> Result> { let asset_context = get_runtime_asset_context(environment); let shared_runtime_utils_code = - embed_static_code(asset_context, "shared/runtime-utils.ts".to_string()); - let runtime_base_code = embed_static_code( - asset_context, - "dev/runtime/base/runtime-base.ts".to_string(), - ); + embed_static_code(asset_context, "shared/runtime-utils.ts".into()); + let runtime_base_code = + embed_static_code(asset_context, "dev/runtime/base/runtime-base.ts".into()); let chunk_loading = &*asset_context .compile_time_info() @@ -37,9 +35,9 @@ pub async fn get_browser_runtime_code( let runtime_backend_code = embed_static_code( asset_context, match chunk_loading { - ChunkLoading::None => "dev/runtime/none/runtime-backend-none.ts".to_string(), - ChunkLoading::NodeJs => "dev/runtime/nodejs/runtime-backend-nodejs.ts".to_string(), - ChunkLoading::Dom => "dev/runtime/dom/runtime-backend-dom.ts".to_string(), + ChunkLoading::None => "dev/runtime/none/runtime-backend-none.ts".into(), + ChunkLoading::NodeJs => "dev/runtime/nodejs/runtime-backend-nodejs.ts".into(), + ChunkLoading::Dom => "dev/runtime/dom/runtime-backend-dom.ts".into(), }, ); @@ -70,26 +68,19 @@ pub async fn get_browser_runtime_code( if *environment.supports_commonjs_externals().await? { code.push_code( - &*embed_static_code( - asset_context, - "shared-node/base-externals-utils.ts".to_string(), - ) - .await?, + &*embed_static_code(asset_context, "shared-node/base-externals-utils.ts".into()) + .await?, ); } if *environment.node_externals().await? { code.push_code( - &*embed_static_code( - asset_context, - "shared-node/node-externals-utils.ts".to_string(), - ) - .await?, + &*embed_static_code(asset_context, "shared-node/node-externals-utils.ts".into()) + .await?, ); } if *environment.supports_wasm().await? { code.push_code( - &*embed_static_code(asset_context, "shared-node/node-wasm-utils.ts".to_string()) - .await?, + &*embed_static_code(asset_context, "shared-node/node-wasm-utils.ts".into()).await?, ); } diff --git a/crates/turbopack-ecmascript-runtime/src/embed_js.rs b/crates/turbopack-ecmascript-runtime/src/embed_js.rs index bd503baa98ba0..fda4e89341c62 100644 --- a/crates/turbopack-ecmascript-runtime/src/embed_js.rs +++ b/crates/turbopack-ecmascript-runtime/src/embed_js.rs @@ -1,4 +1,4 @@ -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::{embed_directory, FileContent, FileSystem, FileSystemPath}; use turbopack_core::{code_builder::Code, context::AssetContext}; use turbopack_ecmascript::StaticEcmascriptCode; @@ -9,16 +9,16 @@ pub fn embed_fs() -> Vc> { } #[turbo_tasks::function] -pub fn embed_file(path: String) -> Vc { +pub fn embed_file(path: RcStr) -> Vc { embed_fs().root().join(path).read() } #[turbo_tasks::function] -pub fn embed_file_path(path: String) -> Vc { +pub fn embed_file_path(path: RcStr) -> Vc { embed_fs().root().join(path) } #[turbo_tasks::function] -pub fn embed_static_code(asset_context: Vc>, path: String) -> Vc { +pub fn embed_static_code(asset_context: Vc>, path: RcStr) -> Vc { StaticEcmascriptCode::new(asset_context, embed_file_path(path)).code() } diff --git a/crates/turbopack-ecmascript/src/analyzer/graph.rs b/crates/turbopack-ecmascript/src/analyzer/graph.rs index 6734f06d648e6..f73894ddfa989 100644 --- a/crates/turbopack-ecmascript/src/analyzer/graph.rs +++ b/crates/turbopack-ecmascript/src/analyzer/graph.rs @@ -12,7 +12,7 @@ use swc_core::{ visit::{fields::*, *}, }, }; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbopack_core::source::Source; use super::{ConstantNumber, ConstantValue, ImportMap, JsValue, ObjectPart, WellKnownFunctionKind}; @@ -146,7 +146,7 @@ pub enum Effect { /// A reference to an imported binding. ImportedBinding { esm_reference_index: usize, - export: Option, + export: Option, ast_path: Vec, span: Span, in_try: bool, diff --git a/crates/turbopack-ecmascript/src/analyzer/imports.rs b/crates/turbopack-ecmascript/src/analyzer/imports.rs index 836eed10cf8a5..3cadd4f26087f 100644 --- a/crates/turbopack-ecmascript/src/analyzer/imports.rs +++ b/crates/turbopack-ecmascript/src/analyzer/imports.rs @@ -10,7 +10,7 @@ use swc_core::{ visit::{Visit, VisitWith}, }, }; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbopack_core::{issue::IssueSource, source::Source}; use super::{top_level_await::has_top_level_await, JsValue, ModuleValue}; @@ -183,9 +183,9 @@ impl ImportMap { } // TODO this could return &str instead of String to avoid cloning - pub fn get_binding(&self, id: &Id) -> Option<(usize, Option)> { + pub fn get_binding(&self, id: &Id) -> Option<(usize, Option)> { if let Some((i, i_sym)) = self.imports.get(id) { - return Some((*i, Some(i_sym.to_string()))); + return Some((*i, Some(i_sym.as_str().into()))); } if let Some(i) = self.namespace_imports.get(id) { return Some((*i, None)); @@ -418,7 +418,7 @@ fn parse_with(with: Option<&ObjectLit>) -> Option { find_turbopack_part_id_in_asserts(with?).map(|v| match v { PartId::Internal(index) => ImportedSymbol::Part(index), PartId::ModuleEvaluation => ImportedSymbol::ModuleEvaluation, - PartId::Export(e) => ImportedSymbol::Symbol(e.into()), + PartId::Export(e) => ImportedSymbol::Symbol(e.as_str().into()), PartId::Exports => ImportedSymbol::Exports, }) } diff --git a/crates/turbopack-ecmascript/src/analyzer/mod.rs b/crates/turbopack-ecmascript/src/analyzer/mod.rs index 4dbba8091d5bd..54f229549a26b 100644 --- a/crates/turbopack-ecmascript/src/analyzer/mod.rs +++ b/crates/turbopack-ecmascript/src/analyzer/mod.rs @@ -24,7 +24,7 @@ use swc_core::{ atoms::{Atom, JsWord}, }, }; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbopack_core::compile_time_info::CompileTimeDefineValue; use url::Url; @@ -98,6 +98,7 @@ impl Eq for ConstantNumber {} pub enum ConstantString { Word(JsWord), Atom(Atom), + RcStr(RcStr), } impl ConstantString { @@ -105,6 +106,7 @@ impl ConstantString { match self { Self::Word(s) => s, Self::Atom(s) => s, + Self::RcStr(s) => s, } } @@ -151,6 +153,12 @@ impl From for ConstantString { } } +impl From for ConstantString { + fn from(v: RcStr) -> Self { + ConstantString::RcStr(v) + } +} + #[derive(Debug, Clone, Hash, PartialEq, Eq, Default)] pub enum ConstantValue { #[default] @@ -484,9 +492,15 @@ impl From for JsValue { } } +impl From for JsValue { + fn from(v: RcStr) -> Self { + ConstantValue::Str(v.into()).into() + } +} + impl From for JsValue { fn from(v: String) -> Self { - ConstantValue::Str(v.into()).into() + RcStr::from(v).into() } } @@ -3258,7 +3272,7 @@ impl WellKnownObjectKind { #[derive(Debug, Clone)] pub struct RequireContextOptions { - pub dir: String, + pub dir: RcStr, pub include_subdirs: bool, /// this is a regex (pattern, flags) pub filter: Regex, @@ -3307,7 +3321,7 @@ pub fn parse_require_context(args: &[JsValue]) -> Result bail!("require.context() only supports 1-3 arguments (mode is not supported)"); } - let Some(dir) = args[0].as_str().map(|s| s.to_string()) else { + let Some(dir) = args[0].as_str().map(|s| s.into()) else { bail!("require.context(dir, ...) requires dir to be a constant string"); }; @@ -3347,7 +3361,7 @@ pub fn parse_require_context(args: &[JsValue]) -> Result #[turbo_tasks::value(transparent)] #[derive(Debug, Clone)] -pub struct RequireContextValue(IndexMap); +pub struct RequireContextValue(IndexMap); #[turbo_tasks::value_impl] impl RequireContextValue { @@ -3478,9 +3492,9 @@ pub mod test_utils { Ok(options) => { let mut map = IndexMap::new(); - map.insert("./a".into(), format!("[context: {}]/a", options.dir)); - map.insert("./b".into(), format!("[context: {}]/b", options.dir)); - map.insert("./c".into(), format!("[context: {}]/c", options.dir)); + map.insert("./a".into(), format!("[context: {}]/a", options.dir).into()); + map.insert("./b".into(), format!("[context: {}]/b", options.dir).into()); + map.insert("./c".into(), format!("[context: {}]/c", options.dir).into()); JsValue::WellKnownFunction(WellKnownFunctionKind::RequireContextRequire( Vc::cell(map), diff --git a/crates/turbopack-ecmascript/src/async_chunk/chunk_item.rs b/crates/turbopack-ecmascript/src/async_chunk/chunk_item.rs index 71d0a4f699361..6fd76155f6e6b 100644 --- a/crates/turbopack-ecmascript/src/async_chunk/chunk_item.rs +++ b/crates/turbopack-ecmascript/src/async_chunk/chunk_item.rs @@ -1,6 +1,6 @@ use anyhow::Result; use indoc::formatdoc; -use turbo_tasks::{TryJoinIterExt, Value, Vc}; +use turbo_tasks::{RcStr, TryJoinIterExt, Value, Vc}; use turbopack_core::{ chunk::{ ChunkData, ChunkItem, ChunkItemExt, ChunkType, ChunkableModule, ChunkingContext, @@ -153,8 +153,8 @@ impl EcmascriptChunkItem for AsyncLoaderChunkItem { } #[turbo_tasks::function] -fn chunk_reference_description() -> Vc { - Vc::cell("chunk".to_string()) +fn chunk_reference_description() -> Vc { + Vc::cell("chunk".into()) } #[turbo_tasks::value_impl] @@ -170,7 +170,9 @@ impl ChunkItem for AsyncLoaderChunkItem { if let Some(available_chunk_items) = self.module.await?.availability_info.available_chunk_items() { - ident = ident.with_modifier(Vc::cell(available_chunk_items.hash().await?.to_string())); + ident = ident.with_modifier(Vc::cell( + available_chunk_items.hash().await?.to_string().into(), + )); } Ok(ident) } diff --git a/crates/turbopack-ecmascript/src/async_chunk/module.rs b/crates/turbopack-ecmascript/src/async_chunk/module.rs index 5f2e9977a0761..460067b09c86a 100644 --- a/crates/turbopack-ecmascript/src/async_chunk/module.rs +++ b/crates/turbopack-ecmascript/src/async_chunk/module.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::{RcStr, Value, Vc}; use turbopack_core::{ asset::{Asset, AssetContent}, chunk::{availability_info::AvailabilityInfo, ChunkableModule, ChunkingContext}, @@ -11,8 +11,8 @@ use turbopack_core::{ use crate::async_chunk::chunk_item::AsyncLoaderChunkItem; #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("async loader".to_string()) +fn modifier() -> Vc { + Vc::cell("async loader".into()) } /// The AsyncLoaderModule is a module that loads another module async, by @@ -46,8 +46,8 @@ impl AsyncLoaderModule { } #[turbo_tasks::function] -fn inner_module_reference_description() -> Vc { - Vc::cell("async module".to_string()) +fn inner_module_reference_description() -> Vc { + Vc::cell("async module".into()) } #[turbo_tasks::value_impl] diff --git a/crates/turbopack-ecmascript/src/chunk/chunk_type.rs b/crates/turbopack-ecmascript/src/chunk/chunk_type.rs index 5c5f0e4056370..1561ce754563e 100644 --- a/crates/turbopack-ecmascript/src/chunk/chunk_type.rs +++ b/crates/turbopack-ecmascript/src/chunk/chunk_type.rs @@ -1,5 +1,5 @@ use anyhow::{bail, Result}; -use turbo_tasks::{TryJoinIterExt, ValueDefault, ValueToString, Vc}; +use turbo_tasks::{RcStr, TryJoinIterExt, ValueDefault, ValueToString, Vc}; use turbopack_core::{ chunk::{ AsyncModuleInfo, Chunk, ChunkItem, ChunkItemWithAsyncModuleInfo, ChunkType, ChunkingContext, @@ -16,8 +16,8 @@ pub struct EcmascriptChunkType {} #[turbo_tasks::value_impl] impl ValueToString for EcmascriptChunkType { #[turbo_tasks::function] - fn to_string(&self) -> Vc { - Vc::cell("ecmascript".to_string()) + fn to_string(&self) -> Vc { + Vc::cell("ecmascript".into()) } } diff --git a/crates/turbopack-ecmascript/src/chunk/item.rs b/crates/turbopack-ecmascript/src/chunk/item.rs index f1cad39a5524e..4b5c654454493 100644 --- a/crates/turbopack-ecmascript/src/chunk/item.rs +++ b/crates/turbopack-ecmascript/src/chunk/item.rs @@ -241,12 +241,12 @@ async fn module_factory_with_code_generation_issue( "An error occurred while generating the chunk item {}", id )); - let error_message = format!("{}", PrettyPrintError(&error)); + let error_message = format!("{}", PrettyPrintError(&error)).into(); let js_error_message = serde_json::to_string(&error_message)?; CodeGenerationIssue { severity: IssueSeverity::Error.cell(), path: chunk_item.asset_ident().path(), - title: StyledString::Text("Code generation for chunk item errored".to_string()) + title: StyledString::Text("Code generation for chunk item errored".into()) .cell(), message: StyledString::Text(error_message).cell(), } diff --git a/crates/turbopack-ecmascript/src/chunk/mod.rs b/crates/turbopack-ecmascript/src/chunk/mod.rs index ca5be5b1fda28..a45ad1374fe72 100644 --- a/crates/turbopack-ecmascript/src/chunk/mod.rs +++ b/crates/turbopack-ecmascript/src/chunk/mod.rs @@ -7,7 +7,7 @@ pub(crate) mod placeable; use std::fmt::Write; use anyhow::{bail, Result}; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbo_tasks_fs::FileSystem; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -64,13 +64,13 @@ impl EcmascriptChunk { } #[turbo_tasks::function] -fn chunk_item_key() -> Vc { - Vc::cell("chunk item".to_string()) +fn chunk_item_key() -> Vc { + Vc::cell("chunk item".into()) } #[turbo_tasks::function] -fn availability_root_key() -> Vc { - Vc::cell("current_availability_root".to_string()) +fn availability_root_key() -> Vc { + Vc::cell("current_availability_root".into()) } #[turbo_tasks::value_impl] @@ -118,7 +118,7 @@ impl Chunk for EcmascriptChunk { } else { ServerFileSystem::new().root() }, - query: Vc::::default(), + query: Vc::::default(), fragment: None, assets, modifiers: Vec::new(), @@ -145,11 +145,10 @@ impl Chunk for EcmascriptChunk { #[turbo_tasks::value_impl] impl ValueToString for EcmascriptChunk { #[turbo_tasks::function] - async fn to_string(self: Vc) -> Result> { - Ok(Vc::cell(format!( - "chunk {}", - self.ident().to_string().await? - ))) + async fn to_string(self: Vc) -> Result> { + Ok(Vc::cell( + format!("chunk {}", self.ident().to_string().await?).into(), + )) } } @@ -175,29 +174,29 @@ impl Asset for EcmascriptChunk { } #[turbo_tasks::function] -fn introspectable_type() -> Vc { - Vc::cell("ecmascript chunk".to_string()) +fn introspectable_type() -> Vc { + Vc::cell("ecmascript chunk".into()) } #[turbo_tasks::function] -fn chunk_item_module_key() -> Vc { - Vc::cell("module".to_string()) +fn chunk_item_module_key() -> Vc { + Vc::cell("module".into()) } #[turbo_tasks::value_impl] impl Introspectable for EcmascriptChunk { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { introspectable_type() } #[turbo_tasks::function] - fn title(self: Vc) -> Vc { + fn title(self: Vc) -> Vc { self.path().to_string() } #[turbo_tasks::function] - async fn details(self: Vc) -> Result> { + async fn details(self: Vc) -> Result> { let content = content_to_details(self.content()); let mut details = String::new(); let this = self.await?; @@ -208,7 +207,7 @@ impl Introspectable for EcmascriptChunk { } details += "\nContent:\n\n"; write!(details, "{}", content.await?)?; - Ok(Vc::cell(details)) + Ok(Vc::cell(details.into())) } #[turbo_tasks::function] diff --git a/crates/turbopack-ecmascript/src/chunk/placeable.rs b/crates/turbopack-ecmascript/src/chunk/placeable.rs index c63ebf097dc8a..b4c13b0d3ea36 100644 --- a/crates/turbopack-ecmascript/src/chunk/placeable.rs +++ b/crates/turbopack-ecmascript/src/chunk/placeable.rs @@ -50,19 +50,22 @@ async fn side_effects_from_package_json( .filter_map(|side_effect| { if let Some(side_effect) = side_effect.as_str() { if side_effect.contains('/') { - Some(Glob::new(side_effect.to_string())) + Some(Glob::new(side_effect.into())) } else { - Some(Glob::new(format!("**/{side_effect}"))) + Some(Glob::new(format!("**/{side_effect}").into())) } } else { SideEffectsInPackageJsonIssue { path: package_json, description: Some( - StyledString::Text(format!( - "Each element in sideEffects must be a string, but found \ - {:?}", - side_effect - )) + StyledString::Text( + format!( + "Each element in sideEffects must be a string, but \ + found {:?}", + side_effect + ) + .into(), + ) .cell(), ), } @@ -78,10 +81,13 @@ async fn side_effects_from_package_json( SideEffectsInPackageJsonIssue { path: package_json, description: Some( - StyledString::Text(format!( - "Invalid glob in sideEffects: {}", - PrettyPrintError(&err) - )) + StyledString::Text( + format!( + "Invalid glob in sideEffects: {}", + PrettyPrintError(&err) + ) + .into(), + ) .cell(), ), } @@ -100,10 +106,13 @@ async fn side_effects_from_package_json( SideEffectsInPackageJsonIssue { path: package_json, description: Some( - StyledString::Text(format!( - "sideEffects must be a boolean or an array, but found {:?}", - side_effects - )) + StyledString::Text( + format!( + "sideEffects must be a boolean or an array, but found {:?}", + side_effects + ) + .into(), + ) .cell(), ), } @@ -140,7 +149,7 @@ impl Issue for SideEffectsInPackageJsonIssue { #[turbo_tasks::function] fn title(&self) -> Vc { - StyledString::Text("Invalid value for sideEffects in package.json".to_string()).cell() + StyledString::Text("Invalid value for sideEffects in package.json".into()).cell() } #[turbo_tasks::function] diff --git a/crates/turbopack-ecmascript/src/chunk_group_files_asset.rs b/crates/turbopack-ecmascript/src/chunk_group_files_asset.rs index bc0904272529f..0c81b36c2d946 100644 --- a/crates/turbopack-ecmascript/src/chunk_group_files_asset.rs +++ b/crates/turbopack-ecmascript/src/chunk_group_files_asset.rs @@ -1,6 +1,6 @@ use anyhow::Result; use indexmap::IndexSet; -use turbo_tasks::{TryJoinIterExt, Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, TryJoinIterExt, Value, ValueToString, Vc}; use turbo_tasks_fs::{File, FileSystemPath}; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -30,8 +30,8 @@ use crate::{ }; #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("chunk group files".to_string()) +fn modifier() -> Vc { + Vc::cell("chunk group files".into()) } /// An asset that exports a list of chunk URLs by putting the [asset] into a @@ -45,13 +45,13 @@ pub struct ChunkGroupFilesAsset { } #[turbo_tasks::function] -fn module_description() -> Vc { - Vc::cell("module".to_string()) +fn module_description() -> Vc { + Vc::cell("module".into()) } #[turbo_tasks::function] -fn runtime_entry_description() -> Vc { - Vc::cell("runtime entry".to_string()) +fn runtime_entry_description() -> Vc { + Vc::cell("runtime entry".into()) } #[turbo_tasks::value_impl] @@ -84,7 +84,7 @@ impl Module for ChunkGroupFilesAsset { impl Asset for ChunkGroupFilesAsset { #[turbo_tasks::function] fn content(&self) -> Vc { - AssetContent::file(File::from("// Chunking only content".to_string()).into()) + AssetContent::file(File::from(RcStr::from("// Chunking only content")).into()) } } @@ -184,8 +184,8 @@ impl EcmascriptChunkItem for ChunkGroupFilesChunkItem { } #[turbo_tasks::function] -fn chunk_group_chunk_reference_description() -> Vc { - Vc::cell("chunk group chunk".to_string()) +fn chunk_group_chunk_reference_description() -> Vc { + Vc::cell("chunk group chunk".into()) } #[turbo_tasks::value_impl] @@ -236,17 +236,17 @@ impl ChunkItem for ChunkGroupFilesChunkItem { #[turbo_tasks::value_impl] impl Introspectable for ChunkGroupFilesAsset { #[turbo_tasks::function] - fn ty(&self) -> Vc { - Vc::cell("chunk group files asset".to_string()) + fn ty(&self) -> Vc { + Vc::cell("chunk group files asset".into()) } #[turbo_tasks::function] - fn details(self: Vc) -> Vc { + fn details(self: Vc) -> Vc { content_to_details(self.content()) } #[turbo_tasks::function] - fn title(self: Vc) -> Vc { + fn title(self: Vc) -> Vc { self.ident().to_string() } @@ -254,7 +254,7 @@ impl Introspectable for ChunkGroupFilesAsset { async fn children(self: Vc) -> Result> { let mut children = IndexSet::new(); children.insert(( - Vc::cell("inner asset".to_string()), + Vc::cell("inner asset".into()), IntrospectableModule::new(Vc::upcast(self.await?.module)), )); Ok(Vc::cell(children)) diff --git a/crates/turbopack-ecmascript/src/lib.rs b/crates/turbopack-ecmascript/src/lib.rs index 84b3e1866e8b9..114a6d2a218ec 100644 --- a/crates/turbopack-ecmascript/src/lib.rs +++ b/crates/turbopack-ecmascript/src/lib.rs @@ -55,7 +55,7 @@ pub use transform::{ TransformContext, TransformPlugin, UnsupportedServerActionIssue, }; use turbo_tasks::{ - trace::TraceRawVcs, ReadRef, TaskInput, TryJoinIterExt, Value, ValueToString, Vc, + trace::TraceRawVcs, RcStr, ReadRef, TaskInput, TryJoinIterExt, Value, ValueToString, Vc, }; use turbo_tasks_fs::{rope::Rope, FileJsonContent, FileSystemPath}; use turbopack_core::{ @@ -177,8 +177,8 @@ impl Display for EcmascriptModuleAssetType { } #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("ecmascript".to_string()) +fn modifier() -> Vc { + Vc::cell("ecmascript".into()) } #[derive(PartialEq, Eq, Clone, TraceRawVcs)] @@ -539,7 +539,7 @@ impl Module for EcmascriptModuleAsset { if let Some(inner_assets) = self.inner_assets { let mut ident = self.source.ident().await?.clone_value(); for (name, asset) in inner_assets.await?.iter() { - ident.add_asset(Vc::cell(name.clone()), asset.ident()); + ident.add_asset(Vc::cell(name.to_string().into()), asset.ident()); } ident.add_modifier(modifier()); ident.layer = Some(self.asset_context.layer()); @@ -690,7 +690,7 @@ impl EcmascriptChunkItem for ModuleChunkItem { let this = self.await?; let _span = tracing::info_span!( "code generation", - module = *self.asset_ident().to_string().await? + module = self.asset_ident().to_string().await?.to_string() ) .entered(); let async_module_options = this @@ -894,7 +894,7 @@ async fn gen_content_with_visitors( error_messages = messages .as_ref() .and_then(|m| { m.first().map(|f| format!("\n{}", f)) }) - .unwrap_or("".to_string()) + .unwrap_or("".into()) ) .into(), source_map: None, diff --git a/crates/turbopack-ecmascript/src/manifest/chunk_asset.rs b/crates/turbopack-ecmascript/src/manifest/chunk_asset.rs index 14138f4fae58b..deacb22cfa791 100644 --- a/crates/turbopack-ecmascript/src/manifest/chunk_asset.rs +++ b/crates/turbopack-ecmascript/src/manifest/chunk_asset.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::{RcStr, Value, Vc}; use turbopack_core::{ asset::{Asset, AssetContent}, chunk::{ @@ -15,8 +15,8 @@ use super::chunk_item::ManifestChunkItem; use crate::chunk::{EcmascriptChunkPlaceable, EcmascriptExports}; #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("manifest chunk".to_string()) +fn modifier() -> Vc { + Vc::cell("manifest chunk".into()) } /// The manifest module is deferred until requested by the manifest loader @@ -90,15 +90,16 @@ impl ManifestAsyncModule { pub async fn content_ident(&self) -> Result> { let mut ident = self.inner.ident(); if let Some(available_modules) = self.availability_info.available_chunk_items() { - ident = ident.with_modifier(Vc::cell(available_modules.hash().await?.to_string())); + ident = + ident.with_modifier(Vc::cell(available_modules.hash().await?.to_string().into())); } Ok(ident) } } #[turbo_tasks::function] -fn manifest_chunk_reference_description() -> Vc { - Vc::cell("manifest chunk".to_string()) +fn manifest_chunk_reference_description() -> Vc { + Vc::cell("manifest chunk".into()) } #[turbo_tasks::value_impl] diff --git a/crates/turbopack-ecmascript/src/manifest/chunk_item.rs b/crates/turbopack-ecmascript/src/manifest/chunk_item.rs index f636df1fe729a..9080b7558857c 100644 --- a/crates/turbopack-ecmascript/src/manifest/chunk_item.rs +++ b/crates/turbopack-ecmascript/src/manifest/chunk_item.rs @@ -86,7 +86,7 @@ impl ChunkItem for ManifestChunkItem { let this = self.await?; let mut references = this.manifest.references().await?.clone_value(); - let key = Vc::cell("chunk data reference".to_string()); + let key = Vc::cell("chunk data reference".into()); for chunk_data in &*self.chunks_data().await? { references.extend(chunk_data.references().await?.iter().map(|&output_asset| { diff --git a/crates/turbopack-ecmascript/src/manifest/loader_item.rs b/crates/turbopack-ecmascript/src/manifest/loader_item.rs index 4044f64485b59..5c9fc07495288 100644 --- a/crates/turbopack-ecmascript/src/manifest/loader_item.rs +++ b/crates/turbopack-ecmascript/src/manifest/loader_item.rs @@ -2,7 +2,7 @@ use std::io::Write as _; use anyhow::{anyhow, Result}; use indoc::writedoc; -use turbo_tasks::{TryJoinIterExt, Vc}; +use turbo_tasks::{RcStr, TryJoinIterExt, Vc}; use turbopack_core::{ chunk::{ ChunkData, ChunkItem, ChunkItemExt, ChunkType, ChunkableModule, ChunkingContext, ChunksData, @@ -22,8 +22,8 @@ use crate::{ }; #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("loader".to_string()) +fn modifier() -> Vc { + Vc::cell("loader".into()) } /// The manifest loader item is shipped in the same chunk that uses the dynamic @@ -74,13 +74,13 @@ impl ManifestLoaderChunkItem { } #[turbo_tasks::function] -fn manifest_loader_chunk_reference_description() -> Vc { - Vc::cell("manifest loader chunk".to_string()) +fn manifest_loader_chunk_reference_description() -> Vc { + Vc::cell("manifest loader chunk".into()) } #[turbo_tasks::function] -fn chunk_data_reference_description() -> Vc { - Vc::cell("chunk data reference".to_string()) +fn chunk_data_reference_description() -> Vc { + Vc::cell("chunk data reference".into()) } #[turbo_tasks::value_impl] diff --git a/crates/turbopack-ecmascript/src/parse.rs b/crates/turbopack-ecmascript/src/parse.rs index 258ecd3d24796..7130d2d7586db 100644 --- a/crates/turbopack-ecmascript/src/parse.rs +++ b/crates/turbopack-ecmascript/src/parse.rs @@ -21,7 +21,7 @@ use swc_core::{ }, }; use tracing::Instrument; -use turbo_tasks::{util::WrapFuture, Value, ValueToString, Vc}; +use turbo_tasks::{util::WrapFuture, RcStr, Value, ValueToString, Vc}; use turbo_tasks_fs::{FileContent, FileSystemPath}; use turbo_tasks_hash::hash_xxh3_hash64; use turbopack_core::{ @@ -58,7 +58,7 @@ pub enum ParseResult { source_map: Arc, }, Unparseable { - messages: Option>, + messages: Option>, }, NotFound, } @@ -157,8 +157,8 @@ pub async fn parse( ty: Value, transforms: Vc, ) -> Result> { - let name = source.ident().to_string().await?; - let span = tracing::info_span!("parse ecmascript", name = *name, ty = display(&*ty)); + let name = source.ident().to_string().await?.to_string(); + let span = tracing::info_span!("parse ecmascript", name = name, ty = display(&*ty)); match parse_internal(source, ty, transforms) .instrument(span) .await @@ -185,7 +185,7 @@ async fn parse_internal( let content = match content.await { Ok(content) => content, Err(error) => { - let error = PrettyPrintError(&error).to_string(); + let error: RcStr = PrettyPrintError(&error).to_string().into(); ReadSourceIssue { source, error: error.clone(), @@ -227,7 +227,7 @@ async fn parse_internal( } } Err(error) => { - let error = PrettyPrintError(&error).to_string(); + let error: RcStr = PrettyPrintError(&error).to_string().into(); ReadSourceIssue { source, error: error.clone(), @@ -262,14 +262,14 @@ async fn parse_content( Box::new(IssueEmitter::new( source, source_map.clone(), - Some("Ecmascript file had an error".to_string()), + Some("Ecmascript file had an error".into()), )), ); let emitter = Box::new(IssueEmitter::new( source, source_map.clone(), - Some("Parsing ecmascript source code failed".to_string()), + Some("Parsing ecmascript source code failed".into()), )); let parser_handler = Handler::with_emitter(true, false, emitter.clone()); let globals = Arc::new(Globals::new()); @@ -327,7 +327,7 @@ async fn parse_content( let mut has_errors = vec![]; for e in parser.take_errors() { let mut e = e.into_diagnostic(&parser_handler); - has_errors.extend(e.message.iter().map(|m| m.0.clone())); + has_errors.extend(e.message.iter().map(|m| m.0.as_str().into())); e.emit(); } @@ -341,7 +341,7 @@ async fn parse_content( Ok(parsed_program) => parsed_program, Err(e) => { let mut e = e.into_diagnostic(&parser_handler); - let messages = e.message.iter().map(|m| m.0.clone()).collect(); + let messages = e.message.iter().map(|m| m.0.as_str().into()).collect(); e.emit(); @@ -405,7 +405,7 @@ async fn parse_content( } else { None }; - let messages = Some(messages.unwrap_or_else(|| vec![string.to_string()])); + let messages = Some(messages.unwrap_or_else(|| vec![string.into()])); return Ok(ParseResult::Unparseable { messages }); } @@ -451,7 +451,7 @@ async fn parse_content( #[turbo_tasks::value] struct ReadSourceIssue { source: Vc>, - error: String, + error: RcStr, } #[turbo_tasks::value_impl] @@ -463,16 +463,20 @@ impl Issue for ReadSourceIssue { #[turbo_tasks::function] fn title(&self) -> Vc { - StyledString::Text("Reading source code for parsing failed".to_string()).cell() + StyledString::Text("Reading source code for parsing failed".into()).cell() } #[turbo_tasks::function] fn description(&self) -> Vc { Vc::cell(Some( - StyledString::Text(format!( - "An unexpected error happened while trying to read the source code to parse: {}", - self.error - )) + StyledString::Text( + format!( + "An unexpected error happened while trying to read the source code to parse: \ + {}", + self.error + ) + .into(), + ) .cell(), )) } diff --git a/crates/turbopack-ecmascript/src/references/amd.rs b/crates/turbopack-ecmascript/src/references/amd.rs index 255f60c7ae1eb..7e0e9b8ffee67 100644 --- a/crates/turbopack-ecmascript/src/references/amd.rs +++ b/crates/turbopack-ecmascript/src/references/amd.rs @@ -11,7 +11,8 @@ use swc_core::{ quote, quote_expr, }; use turbo_tasks::{ - debug::ValueDebugFormat, trace::TraceRawVcs, ReadRef, TryJoinIterExt, Value, ValueToString, Vc, + debug::ValueDebugFormat, trace::TraceRawVcs, RcStr, ReadRef, TryJoinIterExt, Value, + ValueToString, Vc, }; use turbopack_core::{ chunk::{ChunkableModuleReference, ChunkingContext}, @@ -71,11 +72,10 @@ impl ModuleReference for AmdDefineAssetReference { #[turbo_tasks::value_impl] impl ValueToString for AmdDefineAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "AMD define dependency {}", - self.request.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("AMD define dependency {}", self.request.to_string().await?,).into(), + )) } } diff --git a/crates/turbopack-ecmascript/src/references/cjs.rs b/crates/turbopack-ecmascript/src/references/cjs.rs index 3517016954d68..fe6ba26dbfbf1 100644 --- a/crates/turbopack-ecmascript/src/references/cjs.rs +++ b/crates/turbopack-ecmascript/src/references/cjs.rs @@ -4,7 +4,7 @@ use swc_core::{ ecma::ast::{CallExpr, Expr, ExprOrSpread, Ident, Lit}, quote, }; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbopack_core::{ chunk::{ChunkableModuleReference, ChunkingContext}, issue::IssueSource, @@ -63,11 +63,10 @@ impl ModuleReference for CjsAssetReference { #[turbo_tasks::value_impl] impl ValueToString for CjsAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "generic commonjs {}", - self.request.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("generic commonjs {}", self.request.to_string().await?,).into(), + )) } } @@ -120,11 +119,10 @@ impl ModuleReference for CjsRequireAssetReference { #[turbo_tasks::value_impl] impl ValueToString for CjsRequireAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "require {}", - self.request.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("require {}", self.request.to_string().await?,).into(), + )) } } @@ -228,11 +226,10 @@ impl ModuleReference for CjsRequireResolveAssetReference { #[turbo_tasks::value_impl] impl ValueToString for CjsRequireResolveAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "require.resolve {}", - self.request.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("require.resolve {}", self.request.to_string().await?,).into(), + )) } } diff --git a/crates/turbopack-ecmascript/src/references/esm/base.rs b/crates/turbopack-ecmascript/src/references/esm/base.rs index 0c279eec9daaf..d0ca04603a04c 100644 --- a/crates/turbopack-ecmascript/src/references/esm/base.rs +++ b/crates/turbopack-ecmascript/src/references/esm/base.rs @@ -5,7 +5,7 @@ use swc_core::{ ecma::ast::{self, Expr, ExprStmt, Ident, Lit, ModuleItem, Program, Script, Stmt}, quote, }; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbopack_core::{ chunk::{ ChunkItemExt, ChunkableModule, ChunkableModuleReference, ChunkingContext, ChunkingType, @@ -36,7 +36,7 @@ use crate::{ #[turbo_tasks::value] pub enum ReferencedAsset { Some(Vc>), - External(String, ExternalType), + External(RcStr, ExternalType), None, } @@ -107,7 +107,7 @@ impl EsmAssetReference { fn get_origin(&self) -> Vc> { let mut origin = self.origin; if let Some(transition) = self.annotations.transition() { - origin = origin.with_transition(transition.to_string()); + origin = origin.with_transition(transition.into()); } origin } @@ -196,12 +196,15 @@ impl ModuleReference for EsmAssetReference { #[turbo_tasks::value_impl] impl ValueToString for EsmAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "import {} with {}", - self.request.to_string().await?, - self.annotations - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!( + "import {} with {}", + self.request.to_string().await?, + self.annotations + ) + .into(), + )) } } @@ -268,7 +271,7 @@ impl CodeGenerateable for EsmAssetReference { "var $name = __turbopack_import__($id);" as Stmt, name = Ident::new(ident.clone().into(), DUMMY_SP), id: Expr = Expr::Lit(match &*id { - ModuleId::String(s) => s.clone().into(), + ModuleId::String(s) => s.clone().as_str().into(), ModuleId::Number(n) => (*n as f64).into(), }) ); @@ -297,13 +300,13 @@ impl CodeGenerateable for EsmAssetReference { quote!( "var $name = __turbopack_external_import__($id);" as Stmt, name = Ident::new(ident.clone().into(), DUMMY_SP), - id: Expr = Expr::Lit(request.clone().into()) + id: Expr = Expr::Lit(request.to_string().into()) ) } else { quote!( "var $name = __turbopack_external_require__($id, true);" as Stmt, name = Ident::new(ident.clone().into(), DUMMY_SP), - id: Expr = Expr::Lit(request.clone().into()) + id: Expr = Expr::Lit(request.to_string().into()) ) }; insert_hoisted_stmt(program, stmt); @@ -330,7 +333,7 @@ impl CodeGenerateable for EsmAssetReference { let stmt = quote!( "var $name = __turbopack_external_require__($id, true);" as Stmt, name = Ident::new(ident.clone().into(), DUMMY_SP), - id: Expr = Expr::Lit(request.clone().into()) + id: Expr = Expr::Lit(request.to_string().into()) ); insert_hoisted_stmt(program, stmt); })); diff --git a/crates/turbopack-ecmascript/src/references/esm/binding.rs b/crates/turbopack-ecmascript/src/references/esm/binding.rs index f2f4df7d86bb5..e1aac2cf3e50c 100644 --- a/crates/turbopack-ecmascript/src/references/esm/binding.rs +++ b/crates/turbopack-ecmascript/src/references/esm/binding.rs @@ -9,7 +9,7 @@ use swc_core::{ visit::fields::{CalleeField, PropField}, }, }; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbopack_core::chunk::ChunkingContext; use super::EsmAssetReference; @@ -23,7 +23,7 @@ use crate::{ #[derive(Hash, Debug)] pub struct EsmBinding { pub reference: Vc, - pub export: Option, + pub export: Option, pub ast_path: Vc, } @@ -32,7 +32,7 @@ impl EsmBinding { #[turbo_tasks::function] pub fn new( reference: Vc, - export: Option, + export: Option, ast_path: Vc, ) -> Vc { EsmBinding { diff --git a/crates/turbopack-ecmascript/src/references/esm/dynamic.rs b/crates/turbopack-ecmascript/src/references/esm/dynamic.rs index 2695d974d93c4..3c3b08bec6f4a 100644 --- a/crates/turbopack-ecmascript/src/references/esm/dynamic.rs +++ b/crates/turbopack-ecmascript/src/references/esm/dynamic.rs @@ -4,7 +4,7 @@ use swc_core::{ ecma::ast::{CallExpr, Callee, Expr, ExprOrSpread, Lit}, quote_expr, }; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbopack_core::{ chunk::{ChunkableModuleReference, ChunkingContext, ChunkingType, ChunkingTypeOption}, environment::ChunkLoading, @@ -72,11 +72,10 @@ impl ModuleReference for EsmAsyncAssetReference { #[turbo_tasks::value_impl] impl ValueToString for EsmAsyncAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "dynamic import {}", - self.request.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("dynamic import {}", self.request.to_string().await?,).into(), + )) } } diff --git a/crates/turbopack-ecmascript/src/references/esm/export.rs b/crates/turbopack-ecmascript/src/references/esm/export.rs index 8338c61aa65fc..221e0de763c22 100644 --- a/crates/turbopack-ecmascript/src/references/esm/export.rs +++ b/crates/turbopack-ecmascript/src/references/esm/export.rs @@ -14,7 +14,7 @@ use swc_core::{ }, quote, quote_expr, }; -use turbo_tasks::{trace::TraceRawVcs, TryFlatJoinIterExt, ValueToString, Vc}; +use turbo_tasks::{trace::TraceRawVcs, RcStr, TryFlatJoinIterExt, ValueToString, Vc}; use turbo_tasks_fs::glob::Glob; use turbopack_core::{ chunk::ChunkingContext, @@ -37,11 +37,11 @@ pub enum EsmExport { /// A local binding that is exported (export { a } or export const a = 1) /// /// The last bool is true if the binding is a mutable binding - LocalBinding(String, bool), + LocalBinding(RcStr, bool), /// An imported binding that is exported (export { a as b } from "...") /// /// The last bool is true if the binding is a mutable binding - ImportedBinding(Vc>, String, bool), + ImportedBinding(Vc>, RcStr, bool), /// An imported namespace that is exported (export * from "...") ImportedNamespace(Vc>), /// An error occurred while resolving the export @@ -60,14 +60,14 @@ pub enum FoundExportType { #[turbo_tasks::value] pub struct FollowExportsResult { pub module: Vc>, - pub export_name: Option, + pub export_name: Option, pub ty: FoundExportType, } #[turbo_tasks::function] pub async fn follow_reexports( module: Vc>, - export_name: String, + export_name: RcStr, side_effect_free_packages: Vc, ) -> Result> { if !*module @@ -110,7 +110,7 @@ pub async fn follow_reexports( } // Try to find the export in the star exports - if !exports_ref.star_exports.is_empty() && export_name != "default" { + if !exports_ref.star_exports.is_empty() && &*export_name != "default" { let result = get_all_export_names(module).await?; if let Some(m) = result.esm_exports.get(&export_name) { module = *m; @@ -148,10 +148,10 @@ pub async fn follow_reexports( async fn handle_declared_export( module: Vc>, - export_name: String, + export_name: RcStr, export: &EsmExport, side_effect_free_packages: Vc, -) -> Result>, String)>> { +) -> Result>, RcStr)>> { match export { EsmExport::ImportedBinding(reference, name, _) => { if let ReferencedAsset::Some(module) = @@ -163,11 +163,11 @@ async fn handle_declared_export( { return Ok(ControlFlow::Break(FollowExportsResult { module, - export_name: Some(name.to_string()), + export_name: Some(name.clone()), ty: FoundExportType::SideEffects, })); } - return Ok(ControlFlow::Continue((module, name.to_string()))); + return Ok(ControlFlow::Continue((module, name.clone()))); } } EsmExport::ImportedNamespace(reference) => { @@ -205,7 +205,7 @@ async fn handle_declared_export( #[turbo_tasks::value] struct AllExportNamesResult { - esm_exports: IndexMap>>, + esm_exports: IndexMap>>, dynamic_exporting_modules: Vec>>, } @@ -263,7 +263,7 @@ async fn get_all_export_names( #[turbo_tasks::value] pub struct ExpandStarResult { - pub star_exports: Vec, + pub star_exports: Vec, pub has_dynamic_exports: bool, } @@ -299,7 +299,8 @@ pub async fn expand_star_exports( `export type` is more efficient than `export *` as it won't emit any runtime \ code.", asset.ident().to_string().await? - ), + ) + .into(), ), EcmascriptExports::Value => emit_star_exports_issue( asset.ident(), @@ -308,7 +309,8 @@ pub async fn expand_star_exports( is not exported with export *)\nDid you want to use `export {{ default }} \ from \"...\";` instead?", asset.ident().to_string().await? - ), + ) + .into(), ), EcmascriptExports::CommonJs => { has_dynamic_exports = true; @@ -320,7 +322,8 @@ pub async fn expand_star_exports( b, c }} from \"...\") or rewrite the module to ESM, to avoid the \ additional runtime code.`", asset.ident().to_string().await? - ), + ) + .into(), ); } EcmascriptExports::DynamicNamespace => { @@ -336,14 +339,14 @@ pub async fn expand_star_exports( .cell()) } -fn emit_star_exports_issue(source_ident: Vc, message: String) { +fn emit_star_exports_issue(source_ident: Vc, message: RcStr) { AnalyzeIssue { code: None, message: StyledString::Text(message).cell(), source_ident, severity: IssueSeverity::Warning.into(), source: None, - title: Vc::cell("unexpected export *".to_string()), + title: Vc::cell("unexpected export *".into()), } .cell() .emit(); @@ -352,7 +355,7 @@ fn emit_star_exports_issue(source_ident: Vc, message: String) { #[turbo_tasks::value(shared)] #[derive(Hash, Debug)] pub struct EsmExports { - pub exports: BTreeMap, + pub exports: BTreeMap, pub star_exports: Vec>>, } @@ -364,7 +367,7 @@ pub struct EsmExports { #[turbo_tasks::value(shared)] #[derive(Hash, Debug)] pub struct ExpandedExports { - pub exports: BTreeMap, + pub exports: BTreeMap, /// Modules we couldn't analyse all exports of. pub dynamic_exports: Vec>>, } @@ -373,7 +376,7 @@ pub struct ExpandedExports { impl EsmExports { #[turbo_tasks::function] pub async fn expand_exports(&self) -> Result> { - let mut exports: BTreeMap = self.exports.clone(); + let mut exports: BTreeMap = self.exports.clone(); let mut dynamic_exports = vec![]; for esm_ref in self.star_exports.iter() { @@ -391,7 +394,7 @@ impl EsmExports { if !exports.contains_key(export) { exports.insert( export.clone(), - EsmExport::ImportedBinding(Vc::upcast(*esm_ref), export.to_string(), false), + EsmExport::ImportedBinding(Vc::upcast(*esm_ref), export.clone(), false), ); } } @@ -493,7 +496,7 @@ impl CodeGenerateable for EsmExports { props.push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: PropName::Str(Str { span: DUMMY_SP, - value: exported.clone().into(), + value: exported.as_str().into(), raw: None, }), value: Box::new(expr), diff --git a/crates/turbopack-ecmascript/src/references/esm/module_id.rs b/crates/turbopack-ecmascript/src/references/esm/module_id.rs index 835a009212bcf..e92131afcf275 100644 --- a/crates/turbopack-ecmascript/src/references/esm/module_id.rs +++ b/crates/turbopack-ecmascript/src/references/esm/module_id.rs @@ -1,6 +1,6 @@ use anyhow::Result; use swc_core::{ecma::ast::Expr, quote}; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbopack_core::{ chunk::{ ChunkItemExt, ChunkableModule, ChunkableModuleReference, ChunkingContext, @@ -43,11 +43,10 @@ impl ModuleReference for EsmModuleIdAssetReference { #[turbo_tasks::value_impl] impl ValueToString for EsmModuleIdAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "module id of {}", - self.inner.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("module id of {}", self.inner.to_string().await?,).into(), + )) } } @@ -74,7 +73,7 @@ impl CodeGenerateable for EsmModuleIdAssetReference { .id() .await?; let id = Expr::Lit(match &*id { - ModuleId::String(s) => s.clone().into(), + ModuleId::String(s) => s.as_str().into(), ModuleId::Number(n) => (*n as f64).into(), }); visitors.push( diff --git a/crates/turbopack-ecmascript/src/references/esm/url.rs b/crates/turbopack-ecmascript/src/references/esm/url.rs index 5716fe5ec04c2..ef6af603469a4 100644 --- a/crates/turbopack-ecmascript/src/references/esm/url.rs +++ b/crates/turbopack-ecmascript/src/references/esm/url.rs @@ -3,7 +3,7 @@ use swc_core::{ ecma::ast::{Expr, ExprOrSpread, NewExpr}, quote, }; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbopack_core::{ chunk::{ ChunkItemExt, ChunkableModule, ChunkableModuleReference, ChunkingContext, ChunkingType, @@ -104,11 +104,10 @@ impl ModuleReference for UrlAssetReference { #[turbo_tasks::value_impl] impl ValueToString for UrlAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "new URL({})", - self.request.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("new URL({})", self.request.to_string().await?,).into(), + )) } } diff --git a/crates/turbopack-ecmascript/src/references/mod.rs b/crates/turbopack-ecmascript/src/references/mod.rs index 15349f1deb058..6d3473871bd25 100644 --- a/crates/turbopack-ecmascript/src/references/mod.rs +++ b/crates/turbopack-ecmascript/src/references/mod.rs @@ -51,7 +51,7 @@ use swc_core::{ }, }; use tracing::Instrument; -use turbo_tasks::{TryJoinIterExt, Upcast, Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, TryJoinIterExt, Upcast, Value, ValueToString, Vc}; use turbo_tasks_fs::FileSystemPath; use turbopack_core::{ compile_time_info::{CompileTimeInfo, FreeVarReference}, @@ -372,8 +372,8 @@ pub(crate) async fn analyse_ecmascript_module( part: Option>, ) -> Result> { let span = { - let module = module.ident().to_string().await?; - tracing::info_span!("analyse ecmascript module", module = *module) + let module = module.ident().to_string().await?.to_string(); + tracing::info_span!("analyse ecmascript module", module = module) }; let result = analyse_ecmascript_module_internal(module, part) .instrument(span) @@ -474,15 +474,13 @@ pub(crate) async fn analyse_ecmascript_module_internal( let text = &comment.text; if let Some(m) = REFERENCE_PATH.captures(text) { let path = &m[1]; - analysis.add_reference(TsReferencePathAssetReference::new( - origin, - path.to_string(), - )); + analysis + .add_reference(TsReferencePathAssetReference::new(origin, path.into())); } else if let Some(m) = REFERENCE_TYPES.captures(text) { let types = &m[1]; analysis.add_reference(TsReferenceTypeAssetReference::new( origin, - types.to_string(), + types.into(), )); } } @@ -509,7 +507,7 @@ pub(crate) async fn analyse_ecmascript_module_internal( if let Some((_, path)) = paths_by_pos.into_iter().max_by_key(|&(pos, _)| pos) { let origin_path = origin.origin_path(); if path.ends_with(".map") { - let source_map_origin = origin_path.parent().join(path.to_string()); + let source_map_origin = origin_path.parent().join(path.into()); let reference = SourceMapReference::new(origin_path, source_map_origin); analysis.add_reference(reference); let source_map = reference.generate_source_map(); @@ -520,7 +518,7 @@ pub(crate) async fn analyse_ecmascript_module_internal( source_map_from_comment = true; } else if path.starts_with("data:application/json;base64,") { let source_map_origin = origin_path; - let source_map = maybe_decode_data_url(path.to_string()); + let source_map = maybe_decode_data_url(path.into()); analysis.set_source_map(convert_to_turbopack_source_map( source_map, source_map_origin, @@ -554,7 +552,7 @@ pub(crate) async fn analyse_ecmascript_module_internal( for (i, r) in eval_context.imports.references().enumerate() { let r = EsmAssetReference::new( origin, - Request::parse(Value::new(r.module_path.to_string().into())), + Request::parse(Value::new(RcStr::from(&*r.module_path).into())), r.issue_source, Value::new(r.annotations.clone()), match options.tree_shaking_mode { @@ -563,7 +561,7 @@ pub(crate) async fn analyse_ecmascript_module_internal( evaluation_references.push(i); Some(ModulePart::evaluation()) } - ImportedSymbol::Symbol(name) => Some(ModulePart::export(name.to_string())), + ImportedSymbol::Symbol(name) => Some(ModulePart::export((&**name).into())), ImportedSymbol::Part(part_id) => Some(ModulePart::internal(*part_id)), ImportedSymbol::Exports => Some(ModulePart::exports()), ImportedSymbol::Namespace => None, @@ -573,7 +571,7 @@ pub(crate) async fn analyse_ecmascript_module_internal( evaluation_references.push(i); Some(ModulePart::evaluation()) } - ImportedSymbol::Symbol(name) => Some(ModulePart::export(name.to_string())), + ImportedSymbol::Symbol(name) => Some(ModulePart::export((&**name).into())), ImportedSymbol::Part(part_id) => Some(ModulePart::internal(*part_id)), ImportedSymbol::Exports => None, ImportedSymbol::Namespace => None, @@ -613,7 +611,7 @@ pub(crate) async fn analyse_ecmascript_module_internal( } Reexport::Namespace { exported: n } => { visitor.esm_exports.insert( - n.to_string(), + n.as_str().into(), EsmExport::ImportedNamespace(Vc::upcast(import_ref)), ); } @@ -622,10 +620,10 @@ pub(crate) async fn analyse_ecmascript_module_internal( exported: e, } => { visitor.esm_exports.insert( - e.to_string(), + e.as_str().into(), EsmExport::ImportedBinding( Vc::upcast(import_ref), - i.to_string(), + i.to_string().into(), false, ), ); @@ -779,14 +777,12 @@ pub(crate) async fn analyse_ecmascript_module_internal( } else if let Some(span) = top_level_await_span { AnalyzeIssue { code: None, - message: StyledString::Text( - "top level await is only supported in ESM modules.".to_string(), - ) - .cell(), + message: StyledString::Text("top level await is only supported in ESM modules.".into()) + .cell(), source_ident: source.ident(), severity: IssueSeverity::Error.into(), source: Some(issue_source(source, span)), - title: Vc::cell("unexpected top level await".to_string()), + title: Vc::cell("unexpected top level await".into()), } .cell() .emit(); @@ -1604,7 +1600,7 @@ async fn handle_call) + Send + Sync>( let current_context = origin .origin_path() .root() - .join(s.trim_start_matches("/ROOT/").to_string()); + .join(s.trim_start_matches("/ROOT/").into()); analysis.add_reference(NodeGypBuildReference::new( current_context, compile_time_info.environment().compile_target(), @@ -1629,11 +1625,9 @@ async fn handle_call) + Send + Sync>( let args = linked_args(args).await?; if args.len() == 1 { let first_arg = state.link_value(args[0].clone(), in_try).await?; - if let Some(ref s) = first_arg.as_str() { - analysis.add_reference(NodeBindingsReference::new( - origin.origin_path(), - s.to_string(), - )); + if let Some(s) = first_arg.as_str() { + analysis + .add_reference(NodeBindingsReference::new(origin.origin_path(), s.into())); return Ok(()); } } @@ -1724,7 +1718,7 @@ async fn handle_call) + Send + Sync>( let args = linked_args(args).await?; if let Some(p) = args.first().and_then(|arg| arg.as_str()) { let abs_pattern = if p.starts_with("/ROOT/") { - Pattern::Constant(format!("{p}/intl")) + Pattern::Constant(format!("{p}/intl").into()) } else { let linked_func_call = state .link_value( @@ -1803,7 +1797,7 @@ async fn handle_call) + Send + Sync>( { analysis.add_reference(DirAssetReference::new( source, - Pattern::new(Pattern::Constant(dir)), + Pattern::new(Pattern::Constant(dir.into())), )); } return Ok(()); @@ -1848,11 +1842,11 @@ async fn handle_member( if name.len() != def_name_len + 1 { continue; } - let mut it = name.iter().map(Cow::Borrowed).rev(); + let mut it = name.iter().map(|v| Cow::Borrowed(&**v)).rev(); if it.next().unwrap() != Cow::Borrowed(prop) { continue; } - if obj.iter_defineable_name_rev().eq(it) + if it.eq(obj.iter_defineable_name_rev()) && handle_free_var_reference(ast_path, value, span, state, analysis).await? { return Ok(()); @@ -1894,7 +1888,7 @@ async fn handle_free_var( if var .iter_defineable_name_rev() - .eq(name.iter().map(Cow::Borrowed).rev()) + .eq(name.iter().map(|v| Cow::Borrowed(&**v)).rev()) && handle_free_var_reference(ast_path, value, span, state, analysis).await? { return Ok(()); @@ -1963,7 +1957,7 @@ async fn handle_free_var_reference( Some(TreeShakingMode::ModuleFragments) | Some(TreeShakingMode::ReexportsOnly) => export .as_ref() - .map(|export| ModulePart::export(export.to_string())), + .map(|export| ModulePart::export(export.clone())), None => None, }, state.import_externals, @@ -2122,7 +2116,7 @@ fn analyze_amd_define_with_deps( requests.push(AmdDefineDependencyElement::Module); } _ => { - let request = Request::parse_string(dep.to_string()); + let request = Request::parse_string(dep.into()); let reference = AmdDefineAssetReference::new( origin, request, @@ -2210,7 +2204,7 @@ async fn value_visitor_inner( continue; } if v.iter_defineable_name_rev() - .eq(name.iter().map(Cow::Borrowed).rev()) + .eq(name.iter().map(|v| Cow::Borrowed(&**v)).rev()) { return Ok((value.into(), true)); } @@ -2460,9 +2454,9 @@ struct ModuleReferencesVisitor<'a> { old_analyser: StaticAnalyser, import_references: &'a [Vc], analysis: &'a mut AnalyzeEcmascriptModuleResultBuilder, - esm_exports: BTreeMap, + esm_exports: BTreeMap, esm_star_exports: Vec>>, - webpack_runtime: Option<(String, Span)>, + webpack_runtime: Option<(RcStr, Span)>, webpack_entry: bool, webpack_chunks: Vec, } @@ -2491,10 +2485,10 @@ fn as_parent_path(ast_path: &AstNodePath>) -> Vec { - f(ident.sym.to_string()); + f(ident.sym.as_str().into()); } Decl::Var(var_decl) => { let decls = &*var_decl.decls; @@ -2513,10 +2507,10 @@ fn for_each_ident_in_decl(decl: &Decl, f: &mut impl FnMut(String)) { } } } -fn for_each_ident_in_pat(pat: &Pat, f: &mut impl FnMut(String)) { +fn for_each_ident_in_pat(pat: &Pat, f: &mut impl FnMut(RcStr)) { match pat { Pat::Ident(BindingIdent { id, .. }) => { - f(id.sym.to_string()); + f(id.sym.as_str().into()); } Pat::Array(ArrayPat { elems, .. }) => elems.iter().for_each(|e| { if let Some(e) = e { @@ -2532,7 +2526,7 @@ fn for_each_ident_in_pat(pat: &Pat, f: &mut impl FnMut(String)) { for_each_ident_in_pat(value, f); } ObjectPatProp::Assign(AssignPatProp { key, .. }) => { - f(key.sym.to_string()); + f(key.sym.as_str().into()); } ObjectPatProp::Rest(RestPat { arg, .. }) => { for_each_ident_in_pat(arg, f); @@ -2574,10 +2568,10 @@ impl<'a> VisitAstPath for ModuleReferencesVisitor<'a> { if export.src.is_none() { for spec in export.specifiers.iter() { - fn to_string(name: &ModuleExportName) -> String { + fn to_string(name: &ModuleExportName) -> &JsWord { match name { - ModuleExportName::Ident(ident) => ident.sym.to_string(), - ModuleExportName::Str(str) => str.value.to_string(), + ModuleExportName::Ident(ident) => &ident.sym, + ModuleExportName::Str(str) => &str.value, } } match spec { @@ -2594,8 +2588,8 @@ impl<'a> VisitAstPath for ModuleReferencesVisitor<'a> { ); } ExportSpecifier::Named(ExportNamedSpecifier { orig, exported, .. }) => { - let key = to_string(exported.as_ref().unwrap_or(orig)); - let binding_name = to_string(orig); + let key = to_string(exported.as_ref().unwrap_or(orig)).as_str().into(); + let binding_name = to_string(orig).as_str().into(); let export = { let imported_binding = if let ModuleExportName::Ident(ident) = orig { self.eval_context.imports.get_binding(&ident.to_id()) @@ -2647,8 +2641,8 @@ impl<'a> VisitAstPath for ModuleReferencesVisitor<'a> { ast_path: &mut AstNodePath>, ) { self.esm_exports.insert( - "default".to_string(), - EsmExport::LocalBinding(magic_identifier::mangle("default export"), false), + "default".into(), + EsmExport::LocalBinding(magic_identifier::mangle("default export").into(), false), ); self.analysis .add_code_gen(EsmModuleItem::new(Vc::cell(as_parent_path(ast_path)))); @@ -2663,12 +2657,12 @@ impl<'a> VisitAstPath for ModuleReferencesVisitor<'a> { match &export.decl { DefaultDecl::Class(ClassExpr { ident, .. }) | DefaultDecl::Fn(FnExpr { ident, .. }) => { self.esm_exports.insert( - "default".to_string(), + "default".into(), EsmExport::LocalBinding( ident .as_ref() - .map(|i| i.sym.to_string()) - .unwrap_or_else(|| magic_identifier::mangle("default export")), + .map(|i| i.sym.as_str().into()) + .unwrap_or_else(|| magic_identifier::mangle("default export").into()), false, ), ); @@ -2741,7 +2735,7 @@ impl<'a> VisitAstPath for ModuleReferencesVisitor<'a> { if let [ExprOrSpread { spread: None, expr }] = &call.args[..] { if let Some(Lit::Str(str)) = expr.as_lit() { self.webpack_runtime = - Some((str.value.to_string(), call.span)); + Some((str.value.as_str().into(), call.span)); return; } } @@ -2965,7 +2959,7 @@ fn is_invoking_node_process_eval(args: &[JsValue]) -> bool { } #[turbo_tasks::function] -fn maybe_decode_data_url(url: String) -> Vc { +fn maybe_decode_data_url(url: RcStr) -> Vc { if let Ok(map) = decode_data_url(&url) { Vc::cell(Some(SourceMap::new_decoded(map).cell())) } else { diff --git a/crates/turbopack-ecmascript/src/references/node.rs b/crates/turbopack-ecmascript/src/references/node.rs index d0de8f2fd6fd2..49c78c2b28ef4 100644 --- a/crates/turbopack-ecmascript/src/references/node.rs +++ b/crates/turbopack-ecmascript/src/references/node.rs @@ -1,6 +1,6 @@ use anyhow::Result; use either::Either; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbo_tasks_fs::FileSystemPath; use turbopack_core::{ file_source::FileSource, @@ -41,11 +41,10 @@ impl ModuleReference for PackageJsonReference { #[turbo_tasks::value_impl] impl ValueToString for PackageJsonReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "package.json {}", - self.package_json.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("package.json {}", self.package_json.to_string().await?,).into(), + )) } } @@ -75,7 +74,7 @@ async fn resolve_reference_from_dir( (Some(abs_path), Some(rel_path)) => Either::Right( read_matches( parent_path.root().resolve().await?, - "/ROOT/".to_string(), + "/ROOT/".into(), true, Pattern::new(abs_path.or_any_nested_file()), ) @@ -84,7 +83,7 @@ async fn resolve_reference_from_dir( .chain( read_matches( parent_path, - "".to_string(), + "".into(), true, Pattern::new(rel_path.or_any_nested_file()), ) @@ -96,7 +95,7 @@ async fn resolve_reference_from_dir( // absolute path only read_matches( parent_path.root().resolve().await?, - "/ROOT/".to_string(), + "/ROOT/".into(), true, Pattern::new(abs_path.or_any_nested_file()), ) @@ -107,7 +106,7 @@ async fn resolve_reference_from_dir( // relative path only read_matches( parent_path, - "".to_string(), + "".into(), true, Pattern::new(rel_path.or_any_nested_file()), ) @@ -151,10 +150,9 @@ impl ModuleReference for DirAssetReference { #[turbo_tasks::value_impl] impl ValueToString for DirAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "directory assets {}", - self.path.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("directory assets {}", self.path.to_string().await?,).into(), + )) } } diff --git a/crates/turbopack-ecmascript/src/references/pattern_mapping.rs b/crates/turbopack-ecmascript/src/references/pattern_mapping.rs index 35197a5e7b7f7..c655e32eb683a 100644 --- a/crates/turbopack-ecmascript/src/references/pattern_mapping.rs +++ b/crates/turbopack-ecmascript/src/references/pattern_mapping.rs @@ -11,7 +11,7 @@ use swc_core::{ }, quote, quote_expr, }; -use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, TryJoinIterExt, Value, Vc}; +use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, RcStr, TryJoinIterExt, Value, Vc}; use turbopack_core::{ chunk::{ChunkItemExt, ChunkableModule, ChunkingContext, ModuleId}, issue::{code_gen::CodeGenerationIssue, IssueExt, IssueSeverity, StyledString}, @@ -49,7 +49,7 @@ pub(crate) enum SinglePatternMapping { /// ``` ModuleLoader(ModuleId), /// External reference with request and type - External(String, ExternalType), + External(RcStr, ExternalType), } /// A mapping from a request pattern (e.g. "./module", `./images/${name}.png`) @@ -322,14 +322,17 @@ async fn to_single_pattern_mapping( CodeGenerationIssue { severity: IssueSeverity::Bug.into(), title: StyledString::Text( - "pattern mapping is not implemented for this result".to_string(), + "pattern mapping is not implemented for this result".into(), ) .cell(), - message: StyledString::Text(format!( - "the reference resolves to a non-trivial result, which is not supported yet: \ - {:?}", - resolve_item - )) + message: StyledString::Text( + format!( + "the reference resolves to a non-trivial result, which is not supported \ + yet: {:?}", + resolve_item + ) + .into(), + ) .cell(), path: origin.origin_path(), } @@ -356,9 +359,9 @@ async fn to_single_pattern_mapping( } CodeGenerationIssue { severity: IssueSeverity::Bug.into(), - title: StyledString::Text("non-ecmascript placeable asset".to_string()).cell(), + title: StyledString::Text("non-ecmascript placeable asset".into()).cell(), message: StyledString::Text( - "asset is not placeable in ESM chunks, so it doesn't have a module id".to_string(), + "asset is not placeable in ESM chunks, so it doesn't have a module id".into(), ) .cell(), path: origin.origin_path(), diff --git a/crates/turbopack-ecmascript/src/references/raw.rs b/crates/turbopack-ecmascript/src/references/raw.rs index aff666aa92c20..be2878a4830c1 100644 --- a/crates/turbopack-ecmascript/src/references/raw.rs +++ b/crates/turbopack-ecmascript/src/references/raw.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbopack_core::{ reference::ModuleReference, resolve::{pattern::Pattern, resolve_raw, ModuleResolveResult}, @@ -34,10 +34,9 @@ impl ModuleReference for FileSourceReference { #[turbo_tasks::value_impl] impl ValueToString for FileSourceReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "raw asset {}", - self.path.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("raw asset {}", self.path.to_string().await?,).into(), + )) } } diff --git a/crates/turbopack-ecmascript/src/references/require_context.rs b/crates/turbopack-ecmascript/src/references/require_context.rs index 1ae94b46a65b6..6c1db7bd6412d 100644 --- a/crates/turbopack-ecmascript/src/references/require_context.rs +++ b/crates/turbopack-ecmascript/src/references/require_context.rs @@ -13,7 +13,7 @@ use swc_core::{ }, quote, quote_expr, }; -use turbo_tasks::{primitives::Regex, Value, ValueToString, Vc}; +use turbo_tasks::{primitives::Regex, RcStr, Value, ValueToString, Vc}; use turbo_tasks_fs::{DirectoryContent, DirectoryEntry, FileSystemPath}; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -52,7 +52,7 @@ pub(crate) enum DirListEntry { } #[turbo_tasks::value(transparent)] -pub(crate) struct DirList(IndexMap); +pub(crate) struct DirList(IndexMap); #[turbo_tasks::value_impl] impl DirList { @@ -134,7 +134,7 @@ impl DirList { } #[turbo_tasks::value(transparent)] -pub(crate) struct FlatDirList(IndexMap>); +pub(crate) struct FlatDirList(IndexMap>); #[turbo_tasks::value_impl] impl FlatDirList { @@ -147,14 +147,14 @@ impl FlatDirList { #[turbo_tasks::value] #[derive(Debug)] pub struct RequireContextMapEntry { - pub origin_relative: String, + pub origin_relative: RcStr, pub request: Vc, pub result: Vc, } /// The resolved context map for a `require.context(..)` call. #[turbo_tasks::value(transparent)] -pub struct RequireContextMap(IndexMap); +pub struct RequireContextMap(IndexMap); #[turbo_tasks::value_impl] impl RequireContextMap { @@ -201,7 +201,7 @@ impl RequireContextMap { #[derive(Hash, Debug)] pub struct RequireContextAssetReference { pub inner: Vc, - pub dir: String, + pub dir: RcStr, pub include_subdirs: bool, pub path: Vc, @@ -215,7 +215,7 @@ impl RequireContextAssetReference { pub fn new( source: Vc>, origin: Vc>, - dir: String, + dir: RcStr, include_subdirs: bool, filter: Vc, path: Vc, @@ -262,12 +262,15 @@ impl ModuleReference for RequireContextAssetReference { #[turbo_tasks::value_impl] impl ValueToString for RequireContextAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "require.context {}/{}", - self.dir, - if self.include_subdirs { "**" } else { "*" }, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!( + "require.context {}/{}", + self.dir, + if self.include_subdirs { "**" } else { "*" }, + ) + .into(), + )) } } @@ -314,8 +317,8 @@ impl ModuleReference for ResolvedModuleReference { #[turbo_tasks::value_impl] impl ValueToString for ResolvedModuleReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell("resolved reference".to_string())) + async fn to_string(&self) -> Result> { + Ok(Vc::cell("resolved reference".into())) } } @@ -329,17 +332,20 @@ pub struct RequireContextAsset { origin: Vc>, map: Vc, - dir: String, + dir: RcStr, include_subdirs: bool, } #[turbo_tasks::function] -fn modifier(dir: String, include_subdirs: bool) -> Vc { - Vc::cell(format!( - "require.context {}/{}", - dir, - if include_subdirs { "**" } else { "*" }, - )) +fn modifier(dir: RcStr, include_subdirs: bool) -> Vc { + Vc::cell( + format!( + "require.context {}/{}", + dir, + if include_subdirs { "**" } else { "*" }, + ) + .into(), + ) } #[turbo_tasks::value_impl] diff --git a/crates/turbopack-ecmascript/src/references/type_issue.rs b/crates/turbopack-ecmascript/src/references/type_issue.rs index 90035b6138b39..5e6d8a8da9900 100644 --- a/crates/turbopack-ecmascript/src/references/type_issue.rs +++ b/crates/turbopack-ecmascript/src/references/type_issue.rs @@ -23,14 +23,14 @@ impl Issue for SpecifiedModuleTypeIssue { SpecifiedModuleType::CommonJs => "Specified module format (CommonJs) is not matching \ the module format of the source code (EcmaScript \ Modules)" - .to_string(), + .into(), SpecifiedModuleType::EcmaScript => "Specified module format (EcmaScript Modules) is \ not matching the module format of the source code \ (CommonJs)" - .to_string(), + .into(), SpecifiedModuleType::Automatic => "Specified module format is not matching the module \ format of the source code" - .to_string(), + .into(), }) .cell() } @@ -49,7 +49,7 @@ impl Issue for SpecifiedModuleTypeIssue { in the source file.\nIn some cases EcmaScript import/export syntax is added \ by an transform and isn't actually part of the source code. In these cases \ revisit transformation options to inject the correct syntax." - .to_string() + .into() } SpecifiedModuleType::EcmaScript => { "The EcmaScript module format was specified in the package.json that is \ @@ -59,12 +59,12 @@ impl Issue for SpecifiedModuleTypeIssue { EcmaScript mode. Either change the \"type\" field in the package.json or \ replace CommonJs syntax with EcmaScript import/export syntax in the source \ file." - .to_string() + .into() } SpecifiedModuleType::Automatic => "The module format specified in the \ package.json file is not matching the module \ format of the source code." - .to_string(), + .into(), }) .cell(), )) diff --git a/crates/turbopack-ecmascript/src/references/typescript.rs b/crates/turbopack-ecmascript/src/references/typescript.rs index e481d01c02e28..c7e177b80e366 100644 --- a/crates/turbopack-ecmascript/src/references/typescript.rs +++ b/crates/turbopack-ecmascript/src/references/typescript.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbo_tasks_fs::FileSystemPath; use turbopack_core::{ context::AssetContext, @@ -42,11 +42,10 @@ impl ModuleReference for TsConfigReference { #[turbo_tasks::value_impl] impl ValueToString for TsConfigReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "tsconfig {}", - self.tsconfig.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("tsconfig {}", self.tsconfig.to_string().await?,).into(), + )) } } @@ -54,13 +53,13 @@ impl ValueToString for TsConfigReference { #[derive(Hash, Debug)] pub struct TsReferencePathAssetReference { pub origin: Vc>, - pub path: String, + pub path: RcStr, } #[turbo_tasks::value_impl] impl TsReferencePathAssetReference { #[turbo_tasks::function] - pub fn new(origin: Vc>, path: String) -> Vc { + pub fn new(origin: Vc>, path: RcStr) -> Vc { Self::cell(TsReferencePathAssetReference { origin, path }) } } @@ -98,11 +97,10 @@ impl ModuleReference for TsReferencePathAssetReference { #[turbo_tasks::value_impl] impl ValueToString for TsReferencePathAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "typescript reference path comment {}", - self.path, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("typescript reference path comment {}", self.path,).into(), + )) } } @@ -110,13 +108,13 @@ impl ValueToString for TsReferencePathAssetReference { #[derive(Hash, Debug)] pub struct TsReferenceTypeAssetReference { pub origin: Vc>, - pub module: String, + pub module: RcStr, } #[turbo_tasks::value_impl] impl TsReferenceTypeAssetReference { #[turbo_tasks::function] - pub fn new(origin: Vc>, module: String) -> Vc { + pub fn new(origin: Vc>, module: RcStr) -> Vc { Self::cell(TsReferenceTypeAssetReference { origin, module }) } } @@ -129,9 +127,9 @@ impl ModuleReference for TsReferenceTypeAssetReference { self.origin, Request::module( self.module.clone(), - Value::new("".to_string().into()), - Vc::::default(), - Vc::::default(), + Value::new(RcStr::default().into()), + Vc::::default(), + Vc::::default(), ), ) } @@ -140,10 +138,9 @@ impl ModuleReference for TsReferenceTypeAssetReference { #[turbo_tasks::value_impl] impl ValueToString for TsReferenceTypeAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "typescript reference type comment {}", - self.module, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("typescript reference type comment {}", self.module,).into(), + )) } } diff --git a/crates/turbopack-ecmascript/src/references/util.rs b/crates/turbopack-ecmascript/src/references/util.rs index c9bd1901c726c..a464c8ff099a0 100644 --- a/crates/turbopack-ecmascript/src/references/util.rs +++ b/crates/turbopack-ecmascript/src/references/util.rs @@ -1,6 +1,6 @@ use anyhow::Result; use swc_core::{ecma::ast::Expr, quote}; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbopack_core::resolve::parse::Request; /// Creates a IIFE expression that throws a "Cannot find module" error for the @@ -26,7 +26,7 @@ pub fn throw_module_not_found_error_expr(request: &str, message: &str) -> Expr { } #[turbo_tasks::function] -pub async fn request_to_string(request: Vc) -> Result> { +pub async fn request_to_string(request: Vc) -> Result> { Ok(Vc::cell( request .await? diff --git a/crates/turbopack-ecmascript/src/side_effect_optimization/facade/module.rs b/crates/turbopack-ecmascript/src/side_effect_optimization/facade/module.rs index 5dd90a8e57756..2568e61a9f162 100644 --- a/crates/turbopack-ecmascript/src/side_effect_optimization/facade/module.rs +++ b/crates/turbopack-ecmascript/src/side_effect_optimization/facade/module.rs @@ -207,13 +207,13 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleFacadeModule { let esm_exports = esm_exports.await?; if esm_exports.exports.keys().any(|name| name == "default") { exports.insert( - "default".to_string(), + "default".into(), EsmExport::ImportedBinding( Vc::upcast(EcmascriptModulePartReference::new_part( self.module, ModulePart::exports(), )), - "default".to_string(), + "default".into(), false, ), ); diff --git a/crates/turbopack-ecmascript/src/side_effect_optimization/reference.rs b/crates/turbopack-ecmascript/src/side_effect_optimization/reference.rs index 8eba01e9fcc43..f83f8931daa65 100644 --- a/crates/turbopack-ecmascript/src/side_effect_optimization/reference.rs +++ b/crates/turbopack-ecmascript/src/side_effect_optimization/reference.rs @@ -4,7 +4,7 @@ use swc_core::{ ecma::ast::{Expr, Ident}, quote, }; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbopack_core::{ chunk::{ ChunkItemExt, ChunkableModule, ChunkableModuleReference, ChunkingContext, ChunkingType, @@ -55,9 +55,9 @@ impl EcmascriptModulePartReference { #[turbo_tasks::value_impl] impl ValueToString for EcmascriptModulePartReference { #[turbo_tasks::function] - fn to_string(&self) -> Vc { + fn to_string(&self) -> Vc { self.part - .map_or_else(|| Vc::cell("module".to_string()), |part| part.to_string()) + .map_or_else(|| Vc::cell("module".into()), |part| part.to_string()) } } @@ -134,7 +134,7 @@ impl CodeGenerateable for EcmascriptModulePartReference { "var $name = __turbopack_import__($id);" as Stmt, name = Ident::new(ident.clone().into(), DUMMY_SP), id: Expr = Expr::Lit(match &*id { - ModuleId::String(s) => s.clone().into(), + ModuleId::String(s) => s.as_str().into(), ModuleId::Number(n) => (*n as f64).into(), }) ); diff --git a/crates/turbopack-ecmascript/src/text/mod.rs b/crates/turbopack-ecmascript/src/text/mod.rs index 1fb3e20e0766c..d5d44f0be16e1 100644 --- a/crates/turbopack-ecmascript/src/text/mod.rs +++ b/crates/turbopack-ecmascript/src/text/mod.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::FileContent; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -10,8 +10,8 @@ use turbopack_core::{ use crate::utils::StringifyJs; #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("text content".to_string()) +fn modifier() -> Vc { + Vc::cell("text content".into()) } /// A source asset that exports the string content of an asset as the default @@ -36,7 +36,7 @@ impl Source for TextContentFileSource { self.source .ident() .with_modifier(modifier()) - .rename_as("*.mjs".to_string()) + .rename_as("*.mjs".into()) } } @@ -49,7 +49,7 @@ impl Asset for TextContentFileSource { return Ok(AssetContent::file(FileContent::NotFound.cell())); }; let text = content.content().to_str()?; - let code = format!("export default {};", StringifyJs(&text)); + let code: RcStr = format!("export default {};", StringifyJs(&text)).into(); let content = FileContent::Content(code.into()).cell(); Ok(AssetContent::file(content)) } diff --git a/crates/turbopack-ecmascript/src/transform/mod.rs b/crates/turbopack-ecmascript/src/transform/mod.rs index a84d2bf95fdac..121ee1bfc4bfe 100644 --- a/crates/turbopack-ecmascript/src/transform/mod.rs +++ b/crates/turbopack-ecmascript/src/transform/mod.rs @@ -18,7 +18,7 @@ use swc_core::{ }, quote, }; -use turbo_tasks::{ValueDefault, Vc}; +use turbo_tasks::{RcStr, ValueDefault, Vc}; use turbo_tasks_fs::FileSystemPath; use turbopack_core::{ environment::Environment, @@ -37,9 +37,9 @@ pub enum EcmascriptInputTransform { #[serde(default)] refresh: bool, // swc.jsc.transform.react.importSource - import_source: Vc>, + import_source: Vc>, // swc.jsc.transform.react.runtime, - runtime: Vc>, + runtime: Vc>, }, GlobalTypeofs { window_value: String, @@ -175,7 +175,7 @@ impl EcmascriptInputTransform { let config = Options { runtime: Some(runtime), development: Some(*development), - import_source: import_source.await?.clone_value(), + import_source: import_source.await?.as_deref().map(ToString::to_string), refresh: if *refresh { Some(swc_core::ecma::transforms::react::RefreshOptions { refresh_reg: "__turbopack_refresh__.register".to_string(), diff --git a/crates/turbopack-ecmascript/src/tree_shake/asset.rs b/crates/turbopack-ecmascript/src/tree_shake/asset.rs index 5c12234a16e98..c7b4b7c2d7168 100644 --- a/crates/turbopack-ecmascript/src/tree_shake/asset.rs +++ b/crates/turbopack-ecmascript/src/tree_shake/asset.rs @@ -96,7 +96,7 @@ impl Module for EcmascriptModulePartAsset { ModulePart::evaluation(), self.import_externals, )), - Vc::cell("ecmascript module evaluation".to_string()), + Vc::cell("ecmascript module evaluation".into()), )); references.push(reference); @@ -107,7 +107,7 @@ impl Module for EcmascriptModulePartAsset { ModulePart::exports(), self.import_externals, )), - Vc::cell("ecmascript reexports".to_string()), + Vc::cell("ecmascript reexports".into()), )); references.push(reference); @@ -129,7 +129,7 @@ impl Module for EcmascriptModulePartAsset { ModulePart::export(e.clone()), self.import_externals, )), - Vc::cell(format!("ecmascript export '{e}'")), + Vc::cell(format!("ecmascript export '{e}'").into()), )); references.push(reference); @@ -160,7 +160,7 @@ impl Module for EcmascriptModulePartAsset { ModulePart::internal(part_id), self.import_externals, )), - Vc::cell("ecmascript module part".to_string()), + Vc::cell("ecmascript module part".into()), ))) }) .collect::>>()?; diff --git a/crates/turbopack-ecmascript/src/tree_shake/graph.rs b/crates/turbopack-ecmascript/src/tree_shake/graph.rs index 1b6fd75f98850..fa0f83028fe73 100644 --- a/crates/turbopack-ecmascript/src/tree_shake/graph.rs +++ b/crates/turbopack-ecmascript/src/tree_shake/graph.rs @@ -23,6 +23,7 @@ use swc_core::{ utils::{find_pat_ids, private_ident, quote_ident, IdentExt}, }, }; +use turbo_tasks::RcStr; use super::{ util::{ids_captured_by, ids_used_by, ids_used_by_ignoring_nested}, @@ -271,7 +272,7 @@ impl DepGraph { required_vars.insert(id); if let Some(export) = &data[item].export { - exports.insert(Key::Export(export.to_string()), ix as u32); + exports.insert(Key::Export(export.as_str().into()), ix as u32); } } ItemId::Group(ItemIdGroupKind::ModuleEvaluation) => { @@ -1128,7 +1129,7 @@ const ASSERT_CHUNK_KEY: &str = "__turbopack_part__"; pub(crate) enum PartId { ModuleEvaluation, Exports, - Export(String), + Export(RcStr), Internal(u32), } diff --git a/crates/turbopack-ecmascript/src/tree_shake/mod.rs b/crates/turbopack-ecmascript/src/tree_shake/mod.rs index 49c8c18cf0815..f5be2ce7bdbdd 100644 --- a/crates/turbopack-ecmascript/src/tree_shake/mod.rs +++ b/crates/turbopack-ecmascript/src/tree_shake/mod.rs @@ -10,7 +10,7 @@ use swc_core::{ ModuleItem, NamedExport, Program, }, }; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbopack_core::{ident::AssetIdent, resolve::ModulePart, source::Source}; pub(crate) use self::graph::{ @@ -263,7 +263,7 @@ impl Analyzer<'_> { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub(crate) enum Key { ModuleEvaluation, - Export(String), + Export(RcStr), } /// Converts [Vc] to the index. @@ -273,7 +273,7 @@ async fn get_part_id(result: &SplitResult, part: Vc) -> Result // TODO implement ModulePart::Facade let key = match &*part { ModulePart::Evaluation => Key::ModuleEvaluation, - ModulePart::Export(export) => Key::Export(export.await?.to_string()), + ModulePart::Export(export) => Key::Export(export.await?.as_str().into()), ModulePart::Internal(part_id) => return Ok(*part_id), ModulePart::Locals | ModulePart::Exports @@ -503,7 +503,7 @@ pub(super) async fn part_of_module( swc_core::ecma::ast::ExportSpecifier::Named(ExportNamedSpecifier { span: DUMMY_SP, orig: ModuleExportName::Ident(Ident::new( - export_name.into(), + export_name.as_str().into(), DUMMY_SP, )), exported: None, @@ -579,7 +579,7 @@ pub(super) async fn part_of_module( swc_core::ecma::ast::ExportSpecifier::Named(ExportNamedSpecifier { span: DUMMY_SP, orig: ModuleExportName::Ident(Ident::new( - export_name.into(), + export_name.as_str().into(), DUMMY_SP, )), exported: None, diff --git a/crates/turbopack-ecmascript/src/tree_shake/tests.rs b/crates/turbopack-ecmascript/src/tree_shake/tests.rs index 1f7d0d345b8e4..12e443b59aafa 100644 --- a/crates/turbopack-ecmascript/src/tree_shake/tests.rs +++ b/crates/turbopack-ecmascript/src/tree_shake/tests.rs @@ -211,7 +211,7 @@ fn run(input: PathBuf) { for e in &entries { let key = match e { ItemIdGroupKind::ModuleEvaluation => Key::ModuleEvaluation, - ItemIdGroupKind::Export(_, name) => Key::Export(name.to_string()), + ItemIdGroupKind::Export(_, name) => Key::Export(name.as_str().into()), }; let index = entrypoints[&key]; diff --git a/crates/turbopack-ecmascript/src/typescript/mod.rs b/crates/turbopack-ecmascript/src/typescript/mod.rs index d8cb607ca092c..f9f5da82b40a5 100644 --- a/crates/turbopack-ecmascript/src/typescript/mod.rs +++ b/crates/turbopack-ecmascript/src/typescript/mod.rs @@ -1,6 +1,6 @@ use anyhow::Result; use serde_json::Value as JsonValue; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbo_tasks_fs::DirectoryContent; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -67,19 +67,20 @@ impl Module for TsConfigModuleAsset { .map(|s| (source, s.to_string())) }) .await?; - let compiler = compiler + let compiler: RcStr = compiler .map(|(_, c)| c) - .unwrap_or_else(|| "typescript".to_string()); + .unwrap_or_else(|| "typescript".to_string()) + .into(); references.push(Vc::upcast(CompilerReference::new( self.origin, - Request::parse(Value::new(compiler.to_string().into())), + Request::parse(Value::new(compiler.into())), ))); let require = read_from_tsconfigs(&configs, |json, source| { if let JsonValue::Array(array) = &json["ts-node"]["require"] { Some( array .iter() - .filter_map(|name| name.as_str().map(|s| (source, s.to_string()))) + .filter_map(|name| name.as_str().map(|s| (source, RcStr::from(s)))) .collect::>(), ) } else { @@ -103,7 +104,7 @@ impl Module for TsConfigModuleAsset { Some( array .iter() - .filter_map(|name| name.as_str().map(|s| (source, s.to_string()))) + .filter_map(|name| name.as_str().map(|s| (source, RcStr::from(s)))) .collect::>(), ) } else { @@ -118,7 +119,7 @@ impl Module for TsConfigModuleAsset { let mut current = self.source.ident().path().parent().resolve().await?; loop { if let DirectoryContent::Entries(entries) = &*current - .join("node_modules/@types".to_string()) + .join("node_modules/@types".into()) .read_dir() .await? { @@ -126,7 +127,7 @@ impl Module for TsConfigModuleAsset { if name.starts_with('.') { None } else { - Some((self.source, name.to_string())) + Some((self.source, name.clone())) } })); } @@ -143,9 +144,9 @@ impl Module for TsConfigModuleAsset { self.origin, Request::module( name, - Value::new("".to_string().into()), - Vc::::default(), - Vc::::default(), + Value::new(RcStr::default().into()), + Vc::::default(), + Vc::::default(), ), ))); } @@ -188,11 +189,10 @@ impl ModuleReference for CompilerReference { #[turbo_tasks::value_impl] impl ValueToString for CompilerReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "compiler reference {}", - self.request.to_string().await? - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("compiler reference {}", self.request.to_string().await?).into(), + )) } } @@ -221,11 +221,14 @@ impl ModuleReference for TsExtendsReference { #[turbo_tasks::value_impl] impl ValueToString for TsExtendsReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "tsconfig extends {}", - self.config.ident().to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!( + "tsconfig extends {}", + self.config.ident().to_string().await?, + ) + .into(), + )) } } @@ -255,11 +258,14 @@ impl ModuleReference for TsNodeRequireReference { #[turbo_tasks::value_impl] impl ValueToString for TsNodeRequireReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "tsconfig tsnode require {}", - self.request.to_string().await? - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!( + "tsconfig tsnode require {}", + self.request.to_string().await? + ) + .into(), + )) } } @@ -289,10 +295,9 @@ impl ModuleReference for TsConfigTypesReference { #[turbo_tasks::value_impl] impl ValueToString for TsConfigTypesReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "tsconfig types {}", - self.request.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("tsconfig types {}", self.request.to_string().await?,).into(), + )) } } diff --git a/crates/turbopack-ecmascript/src/utils.rs b/crates/turbopack-ecmascript/src/utils.rs index 5da03816e0846..0ac4b67e81199 100644 --- a/crates/turbopack-ecmascript/src/utils.rs +++ b/crates/turbopack-ecmascript/src/utils.rs @@ -20,14 +20,14 @@ pub fn unparen(expr: &Expr) -> &Expr { pub fn js_value_to_pattern(value: &JsValue) -> Pattern { let mut result = match value { JsValue::Constant(v) => Pattern::Constant(match v { - ConstantValue::Str(str) => str.to_string(), - ConstantValue::True => "true".to_string(), - ConstantValue::False => "false".to_string(), - ConstantValue::Null => "null".to_string(), - ConstantValue::Num(ConstantNumber(n)) => n.to_string(), - ConstantValue::BigInt(n) => n.to_string(), - ConstantValue::Regex(exp, flags) => format!("/{exp}/{flags}"), - ConstantValue::Undefined => "undefined".to_string(), + ConstantValue::Str(str) => str.as_str().into(), + ConstantValue::True => "true".into(), + ConstantValue::False => "false".into(), + ConstantValue::Null => "null".into(), + ConstantValue::Num(ConstantNumber(n)) => n.to_string().into(), + ConstantValue::BigInt(n) => n.to_string().into(), + ConstantValue::Regex(exp, flags) => format!("/{exp}/{flags}").into(), + ConstantValue::Undefined => "undefined".into(), }), JsValue::Alternatives(_, alts) => { Pattern::Alternatives(alts.iter().map(js_value_to_pattern).collect()) diff --git a/crates/turbopack-ecmascript/src/webpack/mod.rs b/crates/turbopack-ecmascript/src/webpack/mod.rs index b4bc8ad31d66b..8e0630f76ef74 100644 --- a/crates/turbopack-ecmascript/src/webpack/mod.rs +++ b/crates/turbopack-ecmascript/src/webpack/mod.rs @@ -1,6 +1,6 @@ use anyhow::Result; use swc_core::ecma::ast::Lit; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbopack_core::{ asset::{Asset, AssetContent}, file_source::FileSource, @@ -24,8 +24,8 @@ pub mod parse; pub(crate) mod references; #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("webpack".to_string()) +fn modifier() -> Vc { + Vc::cell("webpack".into()) } #[turbo_tasks::value] @@ -96,7 +96,7 @@ impl ModuleReference for WebpackChunkAssetReference { Lit::Num(num) => format!("{num}"), _ => todo!(), }; - let filename = format!("./chunks/{}.js", chunk_id); + let filename = format!("./chunks/{}.js", chunk_id).into(); let source = Vc::upcast(FileSource::new(context_path.join(filename))); ModuleResolveResult::module(Vc::upcast(WebpackModuleAsset::new( @@ -114,13 +114,13 @@ impl ModuleReference for WebpackChunkAssetReference { #[turbo_tasks::value_impl] impl ValueToString for WebpackChunkAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { + async fn to_string(&self) -> Result> { let chunk_id = match &self.chunk_id { Lit::Str(str) => str.value.to_string(), Lit::Num(num) => format!("{num}"), _ => todo!(), }; - Ok(Vc::cell(format!("webpack chunk {}", chunk_id))) + Ok(Vc::cell(format!("webpack chunk {}", chunk_id).into())) } } @@ -147,8 +147,8 @@ impl ModuleReference for WebpackEntryAssetReference { #[turbo_tasks::value_impl] impl ValueToString for WebpackEntryAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell("webpack entry".to_string())) + async fn to_string(&self) -> Result> { + Ok(Vc::cell("webpack entry".into())) } } @@ -191,10 +191,9 @@ impl ModuleReference for WebpackRuntimeAssetReference { #[turbo_tasks::value_impl] impl ValueToString for WebpackRuntimeAssetReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "webpack {}", - self.request.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("webpack {}", self.request.to_string().await?,).into(), + )) } } diff --git a/crates/turbopack-ecmascript/src/webpack/references.rs b/crates/turbopack-ecmascript/src/webpack/references.rs index 8e3dad63d7ab7..e2e1dc2dead92 100644 --- a/crates/turbopack-ecmascript/src/webpack/references.rs +++ b/crates/turbopack-ecmascript/src/webpack/references.rs @@ -49,7 +49,7 @@ pub async fn module_references( Box::new(IssueEmitter::new( source, source_map.clone(), - Some("Parsing webpack bundle failed".to_string()), + Some("Parsing webpack bundle failed".into()), )), ); HANDLER.set(&handler, || { diff --git a/crates/turbopack-ecmascript/tests/analyzer/graph/concat/graph.snapshot b/crates/turbopack-ecmascript/tests/analyzer/graph/concat/graph.snapshot index b926b3b82ab7f..d022def9690bb 100644 --- a/crates/turbopack-ecmascript/tests/analyzer/graph/concat/graph.snapshot +++ b/crates/turbopack-ecmascript/tests/analyzer/graph/concat/graph.snapshot @@ -23,7 +23,7 @@ "c", Constant( Str( - Atom( + RcStr( "--service=0.14.12", ), ), @@ -33,7 +33,7 @@ "d", Constant( Str( - Atom( + RcStr( "--service=0.14.12", ), ), diff --git a/crates/turbopack-ecmascript/tests/analyzer/graph/esbuild/graph-effects.snapshot b/crates/turbopack-ecmascript/tests/analyzer/graph/esbuild/graph-effects.snapshot index 046789c95932a..3c97beeacce15 100644 --- a/crates/turbopack-ecmascript/tests/analyzer/graph/esbuild/graph-effects.snapshot +++ b/crates/turbopack-ecmascript/tests/analyzer/graph/esbuild/graph-effects.snapshot @@ -5908,7 +5908,7 @@ Value( Constant( Str( - Atom( + RcStr( "--service=0.14.12", ), ), diff --git a/crates/turbopack-ecmascript/tests/analyzer/graph/esbuild/graph.snapshot b/crates/turbopack-ecmascript/tests/analyzer/graph/esbuild/graph.snapshot index 6ff373b2a6b96..ae1c98f9602a0 100644 --- a/crates/turbopack-ecmascript/tests/analyzer/graph/esbuild/graph.snapshot +++ b/crates/turbopack-ecmascript/tests/analyzer/graph/esbuild/graph.snapshot @@ -1039,7 +1039,7 @@ [ Constant( Str( - Atom( + RcStr( "--service=0.14.12", ), ), diff --git a/crates/turbopack-env/src/asset.rs b/crates/turbopack-env/src/asset.rs index 0533718cbb832..95af2e2d6e9e0 100644 --- a/crates/turbopack-env/src/asset.rs +++ b/crates/turbopack-env/src/asset.rs @@ -34,7 +34,7 @@ impl ProcessEnvAsset { impl Source for ProcessEnvAsset { #[turbo_tasks::function] fn ident(&self) -> Vc { - AssetIdent::from_path(self.root.join(".env.js".to_string())) + AssetIdent::from_path(self.root.join(".env.js".into())) } } diff --git a/crates/turbopack-env/src/dotenv.rs b/crates/turbopack-env/src/dotenv.rs index e66925fa2528a..b73c92258dac0 100644 --- a/crates/turbopack-env/src/dotenv.rs +++ b/crates/turbopack-env/src/dotenv.rs @@ -12,13 +12,13 @@ use crate::TryDotenvProcessEnv; pub async fn load_env(project_path: Vc) -> Result>> { let env: Vc> = Vc::upcast(CommandLineProcessEnv::new()); - let node_env = env.read("NODE_ENV".to_string()).await?; + let node_env = env.read("NODE_ENV".into()).await?; let node_env = node_env.as_deref().unwrap_or("development"); let env = Vc::upcast(CustomProcessEnv::new( env, Vc::cell(indexmap! { - "NODE_ENV".to_string() => node_env.to_string(), + "NODE_ENV".into() => node_env.into(), }), )); @@ -36,7 +36,7 @@ pub async fn load_env(project_path: Vc) -> Result Result>> { + async fn read(&self, name: RcStr) -> Result>> { let prior = self.prior.read(name).await?; - let encoded = prior.as_deref().map(|s| StringifyJs(s).to_string()); + let encoded = prior + .as_deref() + .map(|s| StringifyJs(s).to_string()) + .map(RcStr::from); Ok(Vc::cell(encoded)) } } diff --git a/crates/turbopack-env/src/issue.rs b/crates/turbopack-env/src/issue.rs index b315dc51948b8..076e17ace38a4 100644 --- a/crates/turbopack-env/src/issue.rs +++ b/crates/turbopack-env/src/issue.rs @@ -13,7 +13,7 @@ pub struct ProcessEnvIssue { impl Issue for ProcessEnvIssue { #[turbo_tasks::function] fn title(&self) -> Vc { - StyledString::Text("Error loading dotenv file".to_string()).cell() + StyledString::Text("Error loading dotenv file".into()).cell() } #[turbo_tasks::function] diff --git a/crates/turbopack-env/src/try_env.rs b/crates/turbopack-env/src/try_env.rs index f33e1cf77f45c..65d862d0c6dd5 100644 --- a/crates/turbopack-env/src/try_env.rs +++ b/crates/turbopack-env/src/try_env.rs @@ -50,7 +50,7 @@ impl ProcessEnv for TryDotenvProcessEnv { // read_all_with_prior will wrap a current error with a context containing the // failing file, which we don't really care about (we report the filepath as the // Issue context, not the description). So extract the real error. - description: StyledString::Text(e.root_cause().to_string()).cell(), + description: StyledString::Text(e.root_cause().to_string().into()).cell(), } .cell() .emit(); diff --git a/crates/turbopack-image/src/process/mod.rs b/crates/turbopack-image/src/process/mod.rs index 20548d7fee016..df63b300778b1 100644 --- a/crates/turbopack-image/src/process/mod.rs +++ b/crates/turbopack-image/src/process/mod.rs @@ -107,7 +107,7 @@ fn result_to_issue(ident: Vc, result: Result) -> Option { Err(err) => { ImageProcessingIssue { path: ident.path(), - message: StyledString::Text(format!("{}", PrettyPrintError(&err))).cell(), + message: StyledString::Text(format!("{}", PrettyPrintError(&err)).into()).cell(), issue_severity: None, title: None, } @@ -167,10 +167,10 @@ fn load_image_internal( message: StyledString::Text( "This version of Turbopack does not support AVIF images, will emit without \ optimization or encoding" - .to_string(), + .into(), ) .cell(), - title: Some(StyledString::Text("AVIF image not supported".to_string()).cell()), + title: Some(StyledString::Text("AVIF image not supported".into()).cell()), issue_severity: Some(IssueSeverity::Warning.into()), } .cell() @@ -185,10 +185,10 @@ fn load_image_internal( message: StyledString::Text( "This version of Turbopack does not support WEBP images, will emit without \ optimization or encoding" - .to_string(), + .into(), ) .cell(), - title: Some(StyledString::Text("WEBP image not supported".to_string()).cell()), + title: Some(StyledString::Text("WEBP image not supported".into()).cell()), issue_severity: Some(IssueSeverity::Warning.into()), } .cell() @@ -213,7 +213,7 @@ fn compute_blur_data( Err(err) => { ImageProcessingIssue { path: ident.path(), - message: StyledString::Text(format!("{}", PrettyPrintError(&err))).cell(), + message: StyledString::Text(format!("{}", PrettyPrintError(&err)).into()).cell(), issue_severity: None, title: None, } @@ -503,7 +503,7 @@ impl Issue for ImageProcessingIssue { #[turbo_tasks::function] fn title(&self) -> Vc { self.title - .unwrap_or(StyledString::Text("Processing image failed".to_string()).cell()) + .unwrap_or(StyledString::Text("Processing image failed".into()).cell()) } #[turbo_tasks::function] diff --git a/crates/turbopack-json/src/lib.rs b/crates/turbopack-json/src/lib.rs index 244f2a2f91529..0005a466f7914 100644 --- a/crates/turbopack-json/src/lib.rs +++ b/crates/turbopack-json/src/lib.rs @@ -11,7 +11,7 @@ use std::fmt::Write; use anyhow::{bail, Error, Result}; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbo_tasks_fs::{FileContent, FileJsonContent}; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -27,8 +27,8 @@ use turbopack_ecmascript::chunk::{ }; #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("json".to_string()) +fn modifier() -> Vc { + Vc::cell("json".into()) } #[turbo_tasks::value] diff --git a/crates/turbopack-mdx/src/lib.rs b/crates/turbopack-mdx/src/lib.rs index bb6163e67fd5b..ae7f62fefe379 100644 --- a/crates/turbopack-mdx/src/lib.rs +++ b/crates/turbopack-mdx/src/lib.rs @@ -3,7 +3,7 @@ use anyhow::{anyhow, Context, Result}; use mdxjs::{compile, MdxParseOptions, Options}; -use turbo_tasks::{Value, ValueDefault, Vc}; +use turbo_tasks::{RcStr, Value, ValueDefault, Vc}; use turbo_tasks_fs::{rope::Rope, File, FileContent, FileSystemPath}; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -27,8 +27,8 @@ use turbopack_ecmascript::{ }; #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("mdx".to_string()) +fn modifier() -> Vc { + Vc::cell("mdx".into()) } #[turbo_tasks::value(shared)] @@ -48,12 +48,12 @@ pub enum MdxParseConstructs { pub struct MdxTransformOptions { pub development: Option, pub jsx: Option, - pub jsx_runtime: Option, - pub jsx_import_source: Option, + pub jsx_runtime: Option, + pub jsx_import_source: Option, /// The path to a module providing Components to mdx modules. /// The provider must export a useMDXComponents, which is called to access /// an object of components. - pub provider_import_source: Option, + pub provider_import_source: Option, /// Determines how to parse mdx contents. pub mdx_type: Option, } @@ -136,13 +136,16 @@ async fn into_ecmascript_module_asset( let options = Options { parse: parse_options, development: transform_options.development.unwrap_or(false), - provider_import_source: transform_options.provider_import_source.clone(), + provider_import_source: transform_options + .provider_import_source + .clone() + .map(RcStr::into_owned), jsx: transform_options.jsx.unwrap_or(false), // true means 'preserve' jsx syntax. jsx_runtime, jsx_import_source: transform_options .jsx_import_source - .as_ref() - .map(|s| s.into()), + .clone() + .map(RcStr::into_owned), filepath: Some(this.source.ident().path().await?.to_string()), ..Default::default() }; diff --git a/crates/turbopack-node/src/bootstrap.rs b/crates/turbopack-node/src/bootstrap.rs index 0962b4860f169..6ed750e564864 100644 --- a/crates/turbopack-node/src/bootstrap.rs +++ b/crates/turbopack-node/src/bootstrap.rs @@ -1,7 +1,7 @@ use std::fmt::Write; use anyhow::Result; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::{RcStr, Value, Vc}; use turbo_tasks_fs::{File, FileSystemPath}; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -21,8 +21,8 @@ pub(super) struct NodeJsBootstrapAsset { } #[turbo_tasks::function] -fn node_js_bootstrap_chunk_reference_description() -> Vc { - Vc::cell("node.js bootstrap chunk".to_string()) +fn node_js_bootstrap_chunk_reference_description() -> Vc { + Vc::cell("node.js bootstrap chunk".into()) } impl NodeJsBootstrapAsset { diff --git a/crates/turbopack-node/src/embed_js.rs b/crates/turbopack-node/src/embed_js.rs index a13d379e216da..93f31eb503dd1 100644 --- a/crates/turbopack-node/src/embed_js.rs +++ b/crates/turbopack-node/src/embed_js.rs @@ -1,4 +1,4 @@ -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::{embed_directory, FileContent, FileSystem, FileSystemPath}; #[turbo_tasks::function] @@ -7,11 +7,11 @@ pub fn embed_fs() -> Vc> { } #[turbo_tasks::function] -pub(crate) fn embed_file(path: String) -> Vc { +pub(crate) fn embed_file(path: RcStr) -> Vc { embed_fs().root().join(path).read() } #[turbo_tasks::function] -pub(crate) fn embed_file_path(path: String) -> Vc { +pub(crate) fn embed_file_path(path: RcStr) -> Vc { embed_fs().root().join(path) } diff --git a/crates/turbopack-node/src/evaluate.rs b/crates/turbopack-node/src/evaluate.rs index ddecfdf496333..7870d0bbe7260 100644 --- a/crates/turbopack-node/src/evaluate.rs +++ b/crates/turbopack-node/src/evaluate.rs @@ -92,9 +92,7 @@ pub async fn get_evaluate_pool( ) -> Result> { let runtime_asset = asset_context .process( - Vc::upcast(FileSource::new(embed_file_path( - "ipc/evaluate.ts".to_string(), - ))), + Vc::upcast(FileSource::new(embed_file_path("ipc/evaluate.ts".into()))), Value::new(ReferenceType::Internal(InnerAssets::empty())), ) .module(); @@ -108,18 +106,18 @@ pub async fn get_evaluate_pool( } else { Cow::Owned(format!("{file_name}.js")) }; - let path = chunking_context.output_root().join(file_name.to_string()); + let path = chunking_context.output_root().join(file_name.into()); let entry_module = asset_context .process( Vc::upcast(VirtualSource::new( - runtime_asset.ident().path().join("evaluate.js".to_string()), + runtime_asset.ident().path().join("evaluate.js".into()), AssetContent::file( File::from("import { run } from 'RUNTIME'; run(() => import('INNER'))").into(), ), )), Value::new(ReferenceType::Internal(Vc::cell(indexmap! { - "INNER".to_string() => module_asset, - "RUNTIME".to_string() => runtime_asset + "INNER".into() => module_asset, + "RUNTIME".into() => runtime_asset }))), ) .module(); @@ -137,7 +135,7 @@ pub async fn get_evaluate_pool( let runtime_entries = { let globals_module = asset_context .process( - Vc::upcast(FileSource::new(embed_file_path("globals.ts".to_string()))), + Vc::upcast(FileSource::new(embed_file_path("globals.ts".into()))), Value::new(ReferenceType::Internal(InnerAssets::empty())), ) .module(); @@ -585,7 +583,7 @@ pub struct EvaluationIssue { impl Issue for EvaluationIssue { #[turbo_tasks::function] fn title(&self) -> Vc { - StyledString::Text("Error evaluating Node.js code".to_string()).cell() + StyledString::Text("Error evaluating Node.js code".into()).cell() } #[turbo_tasks::function] @@ -609,7 +607,8 @@ impl Issue for EvaluationIssue { self.project_dir, FormattingMode::Plain, ) - .await?, + .await? + .into(), ) .cell(), ))) diff --git a/crates/turbopack-node/src/lib.rs b/crates/turbopack-node/src/lib.rs index 92c77f407b5a9..087a765b329cd 100644 --- a/crates/turbopack-node/src/lib.rs +++ b/crates/turbopack-node/src/lib.rs @@ -11,7 +11,7 @@ use indexmap::IndexSet; pub use node_entry::{NodeEntry, NodeRenderingEntries, NodeRenderingEntry}; use turbo_tasks::{ graph::{AdjacencyMap, GraphTraversal}, - Completion, Completions, TryJoinIterExt, ValueToString, Vc, + Completion, Completions, RcStr, TryJoinIterExt, ValueToString, Vc, }; use turbo_tasks_env::ProcessEnv; use turbo_tasks_fs::{to_sys_path, File, FileSystemPath}; @@ -200,7 +200,7 @@ async fn separate_assets( fn emit_package_json(dir: Vc) -> Vc { emit( Vc::upcast(VirtualOutputAsset::new( - dir.join("package.json".to_string()), + dir.join("package.json".into()), AssetContent::file(File::from("{\"type\": \"commonjs\"}").into()), )), dir, @@ -266,7 +266,7 @@ pub async fn get_intermediate_asset( ) -> Result>> { Ok(Vc::upcast( NodeJsBootstrapAsset { - path: chunking_context.chunk_path(main_entry.ident(), ".js".to_string()), + path: chunking_context.chunk_path(main_entry.ident(), ".js".into()), chunking_context, evaluatable_assets: other_entries.with_entry(main_entry), } @@ -278,7 +278,7 @@ pub async fn get_intermediate_asset( #[turbo_tasks::value(shared)] pub struct ResponseHeaders { pub status: u16, - pub headers: Vec<(String, String)>, + pub headers: Vec<(RcStr, RcStr)>, } pub fn register() { diff --git a/crates/turbopack-node/src/pool.rs b/crates/turbopack-node/src/pool.rs index 2dd964a1aa9c0..e1ef873927ec3 100644 --- a/crates/turbopack-node/src/pool.rs +++ b/crates/turbopack-node/src/pool.rs @@ -28,7 +28,7 @@ use tokio::{ sync::{OwnedSemaphorePermit, Semaphore}, time::{sleep, timeout}, }; -use turbo_tasks::{duration_span, Vc}; +use turbo_tasks::{duration_span, RcStr, Vc}; use turbo_tasks_fs::{json::parse_json_with_source_context, FileSystemPath}; use turbopack_ecmascript::magic_identifier::unmangle_identifiers; @@ -309,7 +309,7 @@ impl OutputStreamHandler { impl NodeJsPoolProcess { async fn new( cwd: &Path, - env: &HashMap, + env: &HashMap, entrypoint: &Path, assets_for_source_mapping: Vc, assets_root: Vc, @@ -688,7 +688,7 @@ enum AcquiredPermits { pub struct NodeJsPool { cwd: PathBuf, entrypoint: PathBuf, - env: HashMap, + env: HashMap, pub assets_for_source_mapping: Vc, pub assets_root: Vc, pub project_dir: Vc, @@ -719,7 +719,7 @@ impl NodeJsPool { pub(super) fn new( cwd: PathBuf, entrypoint: PathBuf, - env: HashMap, + env: HashMap, assets_for_source_mapping: Vc, assets_root: Vc, project_dir: Vc, diff --git a/crates/turbopack-node/src/render/error_page.rs b/crates/turbopack-node/src/render/error_page.rs index 05567b8363f34..cb8737e28239a 100644 --- a/crates/turbopack-node/src/render/error_page.rs +++ b/crates/turbopack-node/src/render/error_page.rs @@ -1,33 +1,33 @@ use anyhow::{Context, Result}; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::embed_file; #[turbo_tasks::function] pub(super) async fn error_html( status_code: u16, - title: String, - details: String, -) -> Result> { + title: RcStr, + details: RcStr, +) -> Result> { let html = create_html(status_code, title, details).await?; - Ok(Vc::cell(html)) + Ok(Vc::cell(html.into())) } #[turbo_tasks::function] pub(super) async fn error_html_body( status_code: u16, - title: String, - details: String, -) -> Result> { + title: RcStr, + details: RcStr, +) -> Result> { let html = create_html(status_code, title, details).await?; let (_, body) = html.split_once("").context("no body in html")?; let (body, _) = body.split_once("").context("no body in html")?; - Ok(Vc::cell(body.to_string())) + Ok(Vc::cell(body.into())) } -async fn create_html(status_code: u16, title: String, details: String) -> Result { +async fn create_html(status_code: u16, title: RcStr, details: RcStr) -> Result { let file_content = embed_file!("src/render/error.html").await?; let file = file_content .as_content() diff --git a/crates/turbopack-node/src/render/issue.rs b/crates/turbopack-node/src/render/issue.rs index ec5e5e66ff0c1..96dfeeb7a5483 100644 --- a/crates/turbopack-node/src/render/issue.rs +++ b/crates/turbopack-node/src/render/issue.rs @@ -15,7 +15,7 @@ pub struct RenderingIssue { impl Issue for RenderingIssue { #[turbo_tasks::function] fn title(&self) -> Vc { - StyledString::Text("Error during SSR Rendering".to_string()).cell() + StyledString::Text("Error during SSR Rendering".into()).cell() } #[turbo_tasks::function] @@ -39,7 +39,9 @@ impl Issue for RenderingIssue { if let Some(status) = self.status { if status != 0 { - details.push(StyledString::Text(format!("Node.js exit code: {status}"))); + details.push(StyledString::Text( + format!("Node.js exit code: {status}").into(), + )); } } diff --git a/crates/turbopack-node/src/render/mod.rs b/crates/turbopack-node/src/render/mod.rs index 1ccc03f3c0955..a78026c2a4b2b 100644 --- a/crates/turbopack-node/src/render/mod.rs +++ b/crates/turbopack-node/src/render/mod.rs @@ -1,7 +1,7 @@ use indexmap::IndexMap; use serde::{Deserialize, Serialize}; use serde_json::Value as JsonValue; -use turbo_tasks::ReadRef; +use turbo_tasks::{RcStr, ReadRef}; use crate::{route_matcher::Param, ResponseHeaders, StructuredError}; @@ -15,13 +15,13 @@ pub mod rendered_source; #[turbo_tasks::value(shared)] #[serde(rename_all = "camelCase")] pub struct RenderData { - params: IndexMap, - method: String, - url: String, - original_url: String, - raw_query: String, - raw_headers: Vec<(String, String)>, - path: String, + params: IndexMap, + method: RcStr, + url: RcStr, + original_url: RcStr, + raw_query: RcStr, + raw_headers: Vec<(RcStr, RcStr)>, + path: RcStr, data: Option>, } @@ -54,8 +54,8 @@ enum RenderStaticIncomingMessage { #[serde(rename_all = "camelCase")] Response { status_code: u16, - headers: Vec<(String, String)>, - body: String, + headers: Vec<(RcStr, RcStr)>, + body: RcStr, }, Headers { data: ResponseHeaders, @@ -65,7 +65,7 @@ enum RenderStaticIncomingMessage { }, BodyEnd, Rewrite { - path: String, + path: RcStr, }, Error(StructuredError), } diff --git a/crates/turbopack-node/src/render/node_api_source.rs b/crates/turbopack-node/src/render/node_api_source.rs index e179ff7027b36..28a0e5ab9c0a7 100644 --- a/crates/turbopack-node/src/render/node_api_source.rs +++ b/crates/turbopack-node/src/render/node_api_source.rs @@ -1,7 +1,7 @@ use anyhow::{anyhow, Result}; use indexmap::IndexSet; use serde_json::Value as JsonValue; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::{RcStr, Value, Vc}; use turbo_tasks_env::ProcessEnv; use turbo_tasks_fs::FileSystemPath; use turbopack_core::introspect::{ @@ -26,7 +26,7 @@ pub fn create_node_api_source( route_type: RouteType, server_root: Vc, route_match: Vc>, - pathname: Vc, + pathname: Vc, entry: Vc>, render_data: Vc, debug: bool, @@ -61,7 +61,7 @@ pub struct NodeApiContentSource { base_segments: Vec, route_type: RouteType, server_root: Vc, - pathname: Vc, + pathname: Vc, route_match: Vc>, entry: Vc>, render_data: Vc, @@ -71,7 +71,7 @@ pub struct NodeApiContentSource { #[turbo_tasks::value_impl] impl NodeApiContentSource { #[turbo_tasks::function] - pub async fn get_pathname(self: Vc) -> Result> { + pub async fn get_pathname(self: Vc) -> Result> { Ok(self.await?.pathname) } } @@ -109,7 +109,7 @@ impl GetContentSourceContent for NodeApiContentSource { #[turbo_tasks::function] async fn get( &self, - path: String, + path: RcStr, data: Value, ) -> Result> { let Some(params) = &*self.route_match.params(path.clone()).await? else { @@ -145,7 +145,7 @@ impl GetContentSourceContent for NodeApiContentSource { original_url: original_url.clone(), raw_query: raw_query.clone(), raw_headers: raw_headers.clone(), - path: format!("/{}", path), + path: format!("/{}", path).into(), data: Some(self.render_data.await?), } .cell(), @@ -157,28 +157,31 @@ impl GetContentSourceContent for NodeApiContentSource { } #[turbo_tasks::function] -fn introspectable_type() -> Vc { - Vc::cell("node api content source".to_string()) +fn introspectable_type() -> Vc { + Vc::cell("node api content source".into()) } #[turbo_tasks::value_impl] impl Introspectable for NodeApiContentSource { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { introspectable_type() } #[turbo_tasks::function] - fn title(&self) -> Vc { + fn title(&self) -> Vc { self.pathname } #[turbo_tasks::function] - async fn details(&self) -> Result> { - Ok(Vc::cell(format!( - "base: {:?}\ntype: {:?}", - self.base_segments, self.route_type - ))) + async fn details(&self) -> Result> { + Ok(Vc::cell( + format!( + "base: {:?}\ntype: {:?}", + self.base_segments, self.route_type + ) + .into(), + )) } #[turbo_tasks::function] @@ -187,11 +190,11 @@ impl Introspectable for NodeApiContentSource { for &entry in self.entry.entries().await?.iter() { let entry = entry.await?; set.insert(( - Vc::cell("module".to_string()), + Vc::cell("module".into()), IntrospectableModule::new(Vc::upcast(entry.module)), )); set.insert(( - Vc::cell("intermediate asset".to_string()), + Vc::cell("intermediate asset".into()), IntrospectableOutputAsset::new(get_intermediate_asset( entry.chunking_context, entry.module, diff --git a/crates/turbopack-node/src/render/render_proxy.rs b/crates/turbopack-node/src/render/render_proxy.rs index d22fe871b1e83..bf29055843ffc 100644 --- a/crates/turbopack-node/src/render/render_proxy.rs +++ b/crates/turbopack-node/src/render/render_proxy.rs @@ -6,7 +6,7 @@ use futures::{ }; use parking_lot::Mutex; use turbo_tasks::{ - duration_span, mark_finished, prevent_gc, util::SharedError, RawVc, ValueToString, Vc, + duration_span, mark_finished, prevent_gc, util::SharedError, RawVc, RcStr, ValueToString, Vc, }; use turbo_tasks_bytes::{Bytes, Stream}; use turbo_tasks_env::ProcessEnv; @@ -95,7 +95,7 @@ async fn proxy_error( path: Vc, error: anyhow::Error, operation: Option, -) -> Result<(u16, String)> { +) -> Result<(u16, RcStr)> { let message = format!("{}", PrettyPrintError(&error)); let status = match operation { @@ -111,15 +111,15 @@ async fn proxy_error( let status_code = 500; let body = error_html( status_code, - "An error occurred while proxying the request to Node.js".to_string(), - format!("{message}\n\n{}", details.join("\n")), + "An error occurred while proxying the request to Node.js".into(), + format!("{message}\n\n{}", details.join("\n")).into(), ) .await? .clone_value(); RenderingIssue { file_path: path, - message: StyledString::Text(message).cell(), + message: StyledString::Text(message.into()).cell(), status: status.and_then(|status| status.code()), } .cell() @@ -289,11 +289,11 @@ async fn render_stream_internal( yield RenderItem::Headers(ResponseHeaders { status, headers: vec![( - "content-type".to_string(), - "text/html; charset=utf-8".to_string(), + "content-type".into(), + "text/html; charset=utf-8".into(), )], }); - yield RenderItem::BodyChunk(body.into()); + yield RenderItem::BodyChunk(body.into_owned().into_bytes().into()); return; } v => { diff --git a/crates/turbopack-node/src/render/render_static.rs b/crates/turbopack-node/src/render/render_static.rs index 458abe38977b7..59c102039098b 100644 --- a/crates/turbopack-node/src/render/render_static.rs +++ b/crates/turbopack-node/src/render/render_static.rs @@ -160,20 +160,20 @@ async fn static_error( .to_string(); body.push_str( - error_html_body(500, "Error rendering page".to_string(), message) + error_html_body(500, "Error rendering page".into(), message.into()) .await? .as_str(), ); let issue = RenderingIssue { file_path: path, - message: StyledString::Text(error).cell(), + message: StyledString::Text(error.into()).cell(), status: status.and_then(|status| status.code()), }; issue.cell().emit(); - let html = fallback_page.with_body(body); + let html = fallback_page.with_body(body.into()); Ok(html.content()) } diff --git a/crates/turbopack-node/src/render/rendered_source.rs b/crates/turbopack-node/src/render/rendered_source.rs index 51301c93a5d67..7dc57cfa900a0 100644 --- a/crates/turbopack-node/src/render/rendered_source.rs +++ b/crates/turbopack-node/src/render/rendered_source.rs @@ -1,7 +1,7 @@ use anyhow::{anyhow, Result}; use indexmap::IndexSet; use serde_json::Value as JsonValue; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::{RcStr, Value, Vc}; use turbo_tasks_env::ProcessEnv; use turbo_tasks_fs::FileSystemPath; use turbopack_core::{ @@ -49,7 +49,7 @@ pub fn create_node_rendered_source( route_type: RouteType, server_root: Vc, route_match: Vc>, - pathname: Vc, + pathname: Vc, entry: Vc>, fallback_page: Vc, render_data: Vc, @@ -89,7 +89,7 @@ pub struct NodeRenderContentSource { route_type: RouteType, server_root: Vc, route_match: Vc>, - pathname: Vc, + pathname: Vc, entry: Vc>, fallback_page: Vc, render_data: Vc, @@ -99,7 +99,7 @@ pub struct NodeRenderContentSource { #[turbo_tasks::value_impl] impl NodeRenderContentSource { #[turbo_tasks::function] - pub async fn get_pathname(self: Vc) -> Result> { + pub async fn get_pathname(self: Vc) -> Result> { Ok(self.await?.pathname) } } @@ -167,7 +167,7 @@ impl GetContentSourceContent for NodeRenderContentSource { #[turbo_tasks::function] async fn get( &self, - path: String, + path: RcStr, data: Value, ) -> Result> { let pathname = self.pathname.await?; @@ -208,7 +208,7 @@ impl GetContentSourceContent for NodeRenderContentSource { original_url: original_url.clone(), raw_query: raw_query.clone(), raw_headers: raw_headers.clone(), - path: pathname.clone_value(), + path: pathname.as_str().into(), data: Some(self.render_data.await?), } .cell(), @@ -246,28 +246,31 @@ impl GetContentSourceContent for NodeRenderContentSource { } #[turbo_tasks::function] -fn introspectable_type() -> Vc { - Vc::cell("node render content source".to_string()) +fn introspectable_type() -> Vc { + Vc::cell("node render content source".into()) } #[turbo_tasks::value_impl] impl Introspectable for NodeRenderContentSource { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { introspectable_type() } #[turbo_tasks::function] - fn title(&self) -> Vc { + fn title(&self) -> Vc { self.pathname } #[turbo_tasks::function] - async fn details(&self) -> Result> { - Ok(Vc::cell(format!( - "base: {:?}\ntype: {:?}", - self.base_segments, self.route_type - ))) + async fn details(&self) -> Result> { + Ok(Vc::cell( + format!( + "base: {:?}\ntype: {:?}", + self.base_segments, self.route_type + ) + .into(), + )) } #[turbo_tasks::function] @@ -276,11 +279,11 @@ impl Introspectable for NodeRenderContentSource { for &entry in self.entry.entries().await?.iter() { let entry = entry.await?; set.insert(( - Vc::cell("module".to_string()), + Vc::cell("module".into()), IntrospectableModule::new(Vc::upcast(entry.module)), )); set.insert(( - Vc::cell("intermediate asset".to_string()), + Vc::cell("intermediate asset".into()), IntrospectableOutputAsset::new(get_intermediate_asset( entry.chunking_context, entry.module, diff --git a/crates/turbopack-node/src/route_matcher.rs b/crates/turbopack-node/src/route_matcher.rs index 4341da5d97a17..9148b4ab09da1 100644 --- a/crates/turbopack-node/src/route_matcher.rs +++ b/crates/turbopack-node/src/route_matcher.rs @@ -1,17 +1,17 @@ use indexmap::IndexMap; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; #[turbo_tasks::value] #[derive(Debug, Clone)] #[serde(untagged)] pub enum Param { - Single(String), - Multi(Vec), + Single(RcStr), + Multi(Vec), } #[turbo_tasks::value(transparent)] #[derive(Debug, Clone)] -pub struct Params(pub Option>); +pub struct Params(pub Option>); /// Extracts parameters from a URL path. pub trait RouteMatcherRef { @@ -26,8 +26,8 @@ pub trait RouteMatcherRef { #[turbo_tasks::value_trait] pub trait RouteMatcher { /// Returns whether the given path is a match for the route. - fn matches(self: Vc, path: String) -> Vc; + fn matches(self: Vc, path: RcStr) -> Vc; /// Returns the parameters extracted from the given path. - fn params(self: Vc, path: String) -> Vc; + fn params(self: Vc, path: RcStr) -> Vc; } diff --git a/crates/turbopack-node/src/source_map/mod.rs b/crates/turbopack-node/src/source_map/mod.rs index 28484719207c1..122ca62951b86 100644 --- a/crates/turbopack-node/src/source_map/mod.rs +++ b/crates/turbopack-node/src/source_map/mod.rs @@ -225,7 +225,7 @@ async fn resolve_source_mapping( let Some(sm) = *generate_source_map.generate_source_map().await? else { return Ok(ResolvedSourceMapping::NoSourceMap); }; - let trace = SourceMapTrace::new(sm, line, column, name.map(|s| s.to_string())) + let trace = SourceMapTrace::new(sm, line, column, name.map(|s| s.clone().into())) .trace() .await?; match &*trace { @@ -237,7 +237,7 @@ async fn resolve_source_mapping( PROJECT_FILESYSTEM_NAME, "]/" )) { - let fs_path = project_dir.join(project_path.to_string()); + let fs_path = project_dir.join(project_path.into()); if lib_code { return Ok(ResolvedSourceMapping::MappedLibrary { frame: frame.clone(), diff --git a/crates/turbopack-node/src/source_map/trace.rs b/crates/turbopack-node/src/source_map/trace.rs index 48e82ca7a5b50..433ed0d523d76 100644 --- a/crates/turbopack-node/src/source_map/trace.rs +++ b/crates/turbopack-node/src/source_map/trace.rs @@ -4,7 +4,7 @@ use anyhow::Result; use mime::APPLICATION_JSON; use serde::{Deserialize, Serialize}; use serde_json::json; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::File; use turbopack_core::{ asset::AssetContent, @@ -88,7 +88,7 @@ pub struct SourceMapTrace { map: Vc, line: usize, column: usize, - name: Option, + name: Option, } /// The result of performing a source map trace. @@ -106,7 +106,7 @@ impl SourceMapTrace { map: Vc, line: usize, column: usize, - name: Option, + name: Option, ) -> Vc { SourceMapTrace { map, @@ -140,7 +140,12 @@ impl SourceMapTrace { file: t.original_file.clone().into(), line: Some(t.original_line.saturating_add(1)), column: Some(t.original_column.saturating_add(1)), - name: t.name.clone().or_else(|| this.name.clone()).map(Into::into), + name: t + .name + .clone() + .or_else(|| this.name.clone()) + .map(|v| v.into_owned()) + .map(Cow::Owned), }), _ => TraceResult::NotFound, }; diff --git a/crates/turbopack-node/src/transforms/postcss.rs b/crates/turbopack-node/src/transforms/postcss.rs index 8b242611ad2e6..1b1e1dc2332e4 100644 --- a/crates/turbopack-node/src/transforms/postcss.rs +++ b/crates/turbopack-node/src/transforms/postcss.rs @@ -3,7 +3,7 @@ use indexmap::indexmap; use indoc::formatdoc; use serde::{Deserialize, Serialize}; use turbo_tasks::{ - trace::TraceRawVcs, Completion, Completions, TaskInput, TryFlatJoinIterExt, Value, Vc, + trace::TraceRawVcs, Completion, Completions, RcStr, TaskInput, TryFlatJoinIterExt, Value, Vc, }; use turbo_tasks_bytes::stream::SingleValue; use turbo_tasks_fs::{ @@ -62,7 +62,7 @@ pub struct PostCssTransformOptions { } #[turbo_tasks::function] -fn postcss_configs() -> Vc> { +fn postcss_configs() -> Vc> { Vc::cell( [ ".postcssrc", @@ -85,7 +85,7 @@ fn postcss_configs() -> Vc> { "postcss.config.json", ] .into_iter() - .map(ToOwned::to_owned) + .map(RcStr::from) .collect(), ) } @@ -193,8 +193,8 @@ async fn extra_configs_changed( let parent_path = postcss_config_path.parent(); let config_paths = [ - parent_path.join("tailwind.config.js".to_string()), - parent_path.join("tailwind.config.ts".to_string()), + parent_path.join("tailwind.config.js".into()), + parent_path.join("tailwind.config.ts".into()), ]; let configs = config_paths @@ -264,7 +264,7 @@ pub(crate) async fn config_loader_source( }; Ok(Vc::upcast(VirtualSource::new( - postcss_config_path.append("_.loader.mjs".to_string()), + postcss_config_path.append("_.loader.mjs".into()), AssetContent::file(File::from(code).into()), ))) } @@ -284,11 +284,11 @@ async fn postcss_executor( Ok(asset_context.process( Vc::upcast(VirtualSource::new( - postcss_config_path.join("transform.ts".to_string()), - AssetContent::File(embed_file("transforms/postcss.ts".to_string())).cell(), + postcss_config_path.join("transform.ts".into()), + AssetContent::File(embed_file("transforms/postcss.ts".into())).cell(), )), Value::new(ReferenceType::Internal(Vc::cell(indexmap! { - "CONFIG".to_string() => config_asset + "CONFIG".into() => config_asset }))), )) } @@ -374,10 +374,10 @@ impl PostCssTransformedAsset { .await? .get_relative_path_to(&*css_fs_path.await?) { - css_path + css_path.into_owned() } else { // This shouldn't be an error since it can happen on virtual assets - "".to_string() + "".into() }; let config_value = evaluate_webpack_loader(WebpackLoaderContext { @@ -415,9 +415,9 @@ impl PostCssTransformedAsset { #[turbo_tasks::value] struct PostCssTransformIssue { source: Vc, - description: String, + description: RcStr, severity: Vc, - title: String, + title: RcStr, } #[turbo_tasks::value_impl] @@ -429,14 +429,12 @@ impl Issue for PostCssTransformIssue { #[turbo_tasks::function] fn title(&self) -> Vc { - StyledString::Text(self.title.to_string()).cell() + StyledString::Text(self.title.clone()).cell() } #[turbo_tasks::function] fn description(&self) -> Vc { - Vc::cell(Some( - StyledString::Text(self.description.to_string()).cell(), - )) + Vc::cell(Some(StyledString::Text(self.description.clone()).cell())) } #[turbo_tasks::function] diff --git a/crates/turbopack-node/src/transforms/util.rs b/crates/turbopack-node/src/transforms/util.rs index 39c22db52d85a..bb1fb69eff09b 100644 --- a/crates/turbopack-node/src/transforms/util.rs +++ b/crates/turbopack-node/src/transforms/util.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use serde_json::Value as JsonValue; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::{File, FileContent, FileSystem}; use turbopack_core::{ asset::AssetContent, server_fs::ServerFileSystem, virtual_source::VirtualSource, @@ -11,8 +11,8 @@ use turbopack_core::{ #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct EmittedAsset { - file: String, - content: String, + file: RcStr, + content: RcStr, source_map: Option, } diff --git a/crates/turbopack-node/src/transforms/webpack.rs b/crates/turbopack-node/src/transforms/webpack.rs index 745ca87cb0cfd..e34988866ef09 100644 --- a/crates/turbopack-node/src/transforms/webpack.rs +++ b/crates/turbopack-node/src/transforms/webpack.rs @@ -5,7 +5,7 @@ use async_trait::async_trait; use serde::{Deserialize, Serialize}; use serde_json::{json, Value as JsonValue}; use turbo_tasks::{ - trace::TraceRawVcs, Completion, TaskInput, TryJoinIterExt, Value, ValueToString, Vc, + trace::TraceRawVcs, Completion, RcStr, TaskInput, TryJoinIterExt, Value, ValueToString, Vc, }; use turbo_tasks_bytes::stream::SingleValue; use turbo_tasks_env::ProcessEnv; @@ -56,15 +56,15 @@ use crate::{ #[serde(rename_all = "camelCase")] #[turbo_tasks::value(serialization = "custom")] struct WebpackLoadersProcessingResult { - source: String, - map: Option, + source: RcStr, + map: Option, #[turbo_tasks(trace_ignore)] assets: Option>, } #[derive(Clone, PartialEq, Eq, Debug, TraceRawVcs, Serialize, Deserialize)] pub struct WebpackLoaderItem { - pub loader: String, + pub loader: RcStr, #[turbo_tasks(trace_ignore)] pub options: serde_json::Map, } @@ -78,7 +78,7 @@ pub struct WebpackLoaders { evaluate_context: Vc>, execution_context: Vc, loaders: Vc, - rename_as: Option, + rename_as: Option, resolve_options_context: Vc, } @@ -89,7 +89,7 @@ impl WebpackLoaders { evaluate_context: Vc>, execution_context: Vc, loaders: Vc, - rename_as: Option, + rename_as: Option, resolve_options_context: Vc, ) -> Vc { WebpackLoaders { @@ -129,7 +129,7 @@ impl Source for WebpackLoadersProcessedAsset { async fn ident(&self) -> Result> { Ok( if let Some(rename_as) = self.transform.await?.rename_as.as_deref() { - self.source.ident().rename_as(rename_as.to_string()) + self.source.ident().rename_as(rename_as.into()) } else { self.source.ident() }, @@ -164,7 +164,7 @@ struct ProcessWebpackLoadersResult { fn webpack_loaders_executor(evaluate_context: Vc>) -> Vc { evaluate_context.process( Vc::upcast(FileSource::new(embed_file_path( - "transforms/webpack-loaders.ts".to_string(), + "transforms/webpack-loaders.ts".into(), ))), Value::new(ReferenceType::Internal(InnerAssets::empty())), ) @@ -221,7 +221,7 @@ impl WebpackLoadersProcessedAsset { resolve_options_context: Some(transform.resolve_options_context), args: vec![ Vc::cell(content.into()), - Vc::cell(resource_path.into()), + Vc::cell(resource_path.to_string().into()), Vc::cell(json!(*loaders)), ], additional_invalidation: Completion::immutable(), @@ -309,14 +309,14 @@ pub struct LogInfo { #[serde(tag = "type", rename_all = "camelCase")] pub enum InfoMessage { FileDependency { - path: String, + path: RcStr, }, BuildDependency { - path: String, + path: RcStr, }, DirDependency { - path: String, - glob: String, + path: RcStr, + glob: RcStr, }, EmittedError { severity: IssueSeverity, @@ -329,13 +329,13 @@ pub enum InfoMessage { #[serde(rename_all = "camelCase")] pub struct WebpackResolveOptions { - alias_fields: Option>, - condition_names: Option>, + alias_fields: Option>, + condition_names: Option>, no_package_json: bool, - extensions: Option>, - main_fields: Option>, + extensions: Option>, + main_fields: Option>, no_exports_field: bool, - main_files: Option>, + main_files: Option>, no_modules: bool, prefer_relative: bool, } @@ -346,15 +346,15 @@ pub enum RequestMessage { #[serde(rename_all = "camelCase")] Resolve { options: WebpackResolveOptions, - lookup_path: String, - request: String, + lookup_path: RcStr, + request: RcStr, }, } #[derive(Serialize, Debug)] #[serde(untagged)] pub enum ResponseMessage { - Resolve { path: String }, + Resolve { path: RcStr }, } #[derive(Clone, PartialEq, Eq, TaskInput)] @@ -566,7 +566,7 @@ async fn apply_webpack_resolve_options( .extract_if(|field| matches!(field, ResolveInPackage::AliasField(..))) .collect::>(); for field in alias_fields { - if field == "..." { + if &*field == "..." { resolve_options.in_package.extend(take(&mut old)); } else { resolve_options @@ -607,7 +607,7 @@ async fn apply_webpack_resolve_options( .extract_if(|field| matches!(field, ResolveIntoPackage::MainField { .. })) .collect::>(); for field in main_fields { - if field == "..." { + if &*field == "..." { resolve_options.into_package.extend(take(&mut old)); } else { resolve_options @@ -649,7 +649,7 @@ impl Issue for BuildDependencyIssue { #[turbo_tasks::function] fn title(&self) -> Vc { - StyledString::Text("Build dependencies are not yet supported".to_string()).cell() + StyledString::Text("Build dependencies are not yet supported".into()).cell() } #[turbo_tasks::function] @@ -664,12 +664,19 @@ impl Issue for BuildDependencyIssue { #[turbo_tasks::function] async fn description(&self) -> Result> { - Ok(Vc::cell(Some(StyledString::Line(vec![ - StyledString::Text("The file at ".to_string()), - StyledString::Code(self.path.await?.to_string()), - StyledString::Text(" is a build dependency, which is not yet implemented. -Changing this file or any dependency will not be recognized and might require restarting the server".to_string()), - ]).cell()))) + Ok(Vc::cell(Some( + StyledString::Line(vec![ + StyledString::Text("The file at ".into()), + StyledString::Code(self.path.await?.to_string().into()), + StyledString::Text( + " is a build dependency, which is not yet implemented. + Changing this file or any dependency will not be recognized and might require restarting the \ + server" + .into(), + ), + ]) + .cell(), + ))) } } @@ -698,7 +705,7 @@ async fn dir_dependency_shallow(glob: Vc) -> Result { - dir_dependency(dir.read_glob(Glob::new("**".to_string()), false)).await?; + dir_dependency(dir.read_glob(Glob::new("**".into()), false)).await?; } DirectoryEntry::Symlink(symlink) => { symlink.read_link().await?; @@ -741,7 +748,7 @@ impl Issue for EvaluateEmittedErrorIssue { #[turbo_tasks::function] fn title(&self) -> Vc { - StyledString::Text("Issue while running loader".to_string()).cell() + StyledString::Text("Issue while running loader".into()).cell() } #[turbo_tasks::function] @@ -755,7 +762,8 @@ impl Issue for EvaluateEmittedErrorIssue { self.project_dir, FormattingMode::Plain, ) - .await?, + .await? + .into(), ) .cell(), ))) @@ -792,7 +800,7 @@ impl Issue for EvaluateErrorLoggingIssue { #[turbo_tasks::function] fn title(&self) -> Vc { - StyledString::Text("Error logging while running loader".to_string()).cell() + StyledString::Text("Error logging while running loader".into()).cell() } #[turbo_tasks::function] @@ -818,11 +826,13 @@ impl Issue for EvaluateErrorLoggingIssue { .logging .iter() .map(|log| match log.log_type { - LogType::Error => StyledString::Strong(fmt_args(" ".to_string(), &log.args)), - LogType::Warn => StyledString::Text(fmt_args(" ".to_string(), &log.args)), - LogType::Info => StyledString::Text(fmt_args(" ".to_string(), &log.args)), - LogType::Log => StyledString::Text(fmt_args(" ".to_string(), &log.args)), - LogType::Clear => StyledString::Strong("---".to_string()), + LogType::Error => { + StyledString::Strong(fmt_args(" ".to_string(), &log.args).into()) + } + LogType::Warn => StyledString::Text(fmt_args(" ".to_string(), &log.args).into()), + LogType::Info => StyledString::Text(fmt_args(" ".to_string(), &log.args).into()), + LogType::Log => StyledString::Text(fmt_args(" ".to_string(), &log.args).into()), + LogType::Clear => StyledString::Strong("---".into()), _ => { unimplemented!("{:?} is not implemented", log.log_type) } diff --git a/crates/turbopack-nodejs/src/chunking_context.rs b/crates/turbopack-nodejs/src/chunking_context.rs index 438c8dc7eb624..0f6d76572c05c 100644 --- a/crates/turbopack-nodejs/src/chunking_context.rs +++ b/crates/turbopack-nodejs/src/chunking_context.rs @@ -2,7 +2,7 @@ use std::iter::once; use anyhow::{bail, Context, Result}; use tracing::Instrument; -use turbo_tasks::{Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbo_tasks_fs::FileSystemPath; use turbopack_core::{ chunk::{ @@ -33,7 +33,7 @@ pub struct NodeJsChunkingContextBuilder { } impl NodeJsChunkingContextBuilder { - pub fn asset_prefix(mut self, asset_prefix: Vc>) -> Self { + pub fn asset_prefix(mut self, asset_prefix: Vc>) -> Self { self.chunking_context.asset_prefix = asset_prefix; self } @@ -75,7 +75,7 @@ pub struct NodeJsChunkingContext { /// Static assets are placed at this path asset_root_path: Vc, /// Static assets requested from this url base - asset_prefix: Vc>, + asset_prefix: Vc>, /// The environment chunks will be evaluated in. environment: Vc, /// The kind of runtime to include in the output. @@ -143,7 +143,7 @@ impl NodeJsChunkingContext { } #[turbo_tasks::function] - pub fn asset_prefix(&self) -> Vc> { + pub fn asset_prefix(&self) -> Vc> { self.asset_prefix } @@ -220,8 +220,8 @@ impl NodeJsChunkingContext { #[turbo_tasks::value_impl] impl ChunkingContext for NodeJsChunkingContext { #[turbo_tasks::function] - fn name(&self) -> Vc { - Vc::cell("unknown".to_string()) + fn name(&self) -> Vc { + Vc::cell("unknown".into()) } #[turbo_tasks::function] @@ -240,29 +240,32 @@ impl ChunkingContext for NodeJsChunkingContext { } #[turbo_tasks::function] - async fn asset_url(self: Vc, ident: Vc) -> Result> { + async fn asset_url(self: Vc, ident: Vc) -> Result> { let this = self.await?; let asset_path = ident.path().await?.to_string(); let asset_path = asset_path .strip_prefix(&format!("{}/", this.client_root.await?.path)) .context("expected client root to contain asset path")?; - Ok(Vc::cell(format!( - "{}{}", - this.asset_prefix - .await? - .as_ref() - .map(|s| s.to_owned()) - .unwrap_or_else(|| "/".to_owned()), - asset_path - ))) + Ok(Vc::cell( + format!( + "{}{}", + this.asset_prefix + .await? + .as_ref() + .map(|s| s.clone()) + .unwrap_or_else(|| "/".into()), + asset_path + ) + .into(), + )) } #[turbo_tasks::function] async fn chunk_path( &self, ident: Vc, - extension: String, + extension: RcStr, ) -> Result> { let root_path = self.chunk_root_path; let name = ident.output_name(self.context_path, extension).await?; @@ -277,7 +280,7 @@ impl ChunkingContext for NodeJsChunkingContext { #[turbo_tasks::function] async fn asset_path( &self, - content_hash: String, + content_hash: RcStr, original_asset_ident: Vc, ) -> Result> { let source_path = original_asset_ident.path().await?; @@ -293,7 +296,7 @@ impl ChunkingContext for NodeJsChunkingContext { content_hash = &content_hash[..8] ), }; - Ok(self.asset_root_path.join(asset_path)) + Ok(self.asset_root_path.join(asset_path.into())) } #[turbo_tasks::function] @@ -302,7 +305,10 @@ impl ChunkingContext for NodeJsChunkingContext { module: Vc>, availability_info: Value, ) -> Result> { - let span = tracing::info_span!("chunking", module = *module.ident().to_string().await?); + let span = tracing::info_span!( + "chunking", + module = module.ident().to_string().await?.to_string() + ); async move { let MakeChunkGroupResult { chunks, diff --git a/crates/turbopack-nodejs/src/ecmascript/node/chunk.rs b/crates/turbopack-nodejs/src/ecmascript/node/chunk.rs index 034c971686157..a06e53d7ef58c 100644 --- a/crates/turbopack-nodejs/src/ecmascript/node/chunk.rs +++ b/crates/turbopack-nodejs/src/ecmascript/node/chunk.rs @@ -1,6 +1,6 @@ use anyhow::Result; use indexmap::IndexSet; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbopack_core::{ asset::{Asset, AssetContent}, chunk::{Chunk, ChunkingContext}, @@ -41,14 +41,14 @@ impl EcmascriptBuildNodeChunk { #[turbo_tasks::value_impl] impl ValueToString for EcmascriptBuildNodeChunk { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell("Ecmascript Build Node Chunk".to_string())) + async fn to_string(&self) -> Result> { + Ok(Vc::cell("Ecmascript Build Node Chunk".into())) } } #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("ecmascript build node chunk".to_string()) +fn modifier() -> Vc { + Vc::cell("ecmascript build node chunk".into()) } #[turbo_tasks::value_impl] @@ -69,7 +69,7 @@ impl OutputAsset for EcmascriptBuildNodeChunk { #[turbo_tasks::function] fn ident(&self) -> Vc { let ident = self.chunk.ident().with_modifier(modifier()); - AssetIdent::from_path(self.chunking_context.chunk_path(ident, ".js".to_string())) + AssetIdent::from_path(self.chunking_context.chunk_path(ident, ".js".into())) } #[turbo_tasks::function] @@ -117,29 +117,29 @@ impl GenerateSourceMap for EcmascriptBuildNodeChunk { } #[turbo_tasks::function] -fn introspectable_type() -> Vc { - Vc::cell("ecmascript build node chunk".to_string()) +fn introspectable_type() -> Vc { + Vc::cell("ecmascript build node chunk".into()) } #[turbo_tasks::function] -fn introspectable_details() -> Vc { - Vc::cell("generates a production EcmaScript chunk targeting Node.js".to_string()) +fn introspectable_details() -> Vc { + Vc::cell("generates a production EcmaScript chunk targeting Node.js".into()) } #[turbo_tasks::value_impl] impl Introspectable for EcmascriptBuildNodeChunk { #[turbo_tasks::function] - fn ty(&self) -> Vc { + fn ty(&self) -> Vc { introspectable_type() } #[turbo_tasks::function] - fn title(self: Vc) -> Vc { + fn title(self: Vc) -> Vc { self.ident().to_string() } #[turbo_tasks::function] - fn details(&self) -> Vc { + fn details(&self) -> Vc { introspectable_details() } @@ -149,7 +149,7 @@ impl Introspectable for EcmascriptBuildNodeChunk { let introspectable_chunk = Vc::upcast::>(self.chunk) .resolve() .await?; - children.insert((Vc::cell("chunk".to_string()), introspectable_chunk)); + children.insert((Vc::cell("chunk".into()), introspectable_chunk)); Ok(Vc::cell(children)) } } diff --git a/crates/turbopack-nodejs/src/ecmascript/node/content.rs b/crates/turbopack-nodejs/src/ecmascript/node/content.rs index de4030482f3b6..e59f63591002d 100644 --- a/crates/turbopack-nodejs/src/ecmascript/node/content.rs +++ b/crates/turbopack-nodejs/src/ecmascript/node/content.rs @@ -76,7 +76,7 @@ impl EcmascriptBuildNodeChunkContent { code, r#" module.exports = {{ - + "#, )?; diff --git a/crates/turbopack-nodejs/src/ecmascript/node/entry/chunk.rs b/crates/turbopack-nodejs/src/ecmascript/node/entry/chunk.rs index 119c45cd0a229..2ec6829da495d 100644 --- a/crates/turbopack-nodejs/src/ecmascript/node/entry/chunk.rs +++ b/crates/turbopack-nodejs/src/ecmascript/node/entry/chunk.rs @@ -2,7 +2,7 @@ use std::io::Write; use anyhow::{bail, Result}; use indoc::writedoc; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbo_tasks_fs::{File, FileSystemPath}; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -153,19 +153,19 @@ impl EcmascriptBuildNodeEntryChunk { #[turbo_tasks::value_impl] impl ValueToString for EcmascriptBuildNodeEntryChunk { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell("Ecmascript Build Node Evaluate Chunk".to_string())) + async fn to_string(&self) -> Result> { + Ok(Vc::cell("Ecmascript Build Node Evaluate Chunk".into())) } } #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("ecmascript build node evaluate chunk".to_string()) +fn modifier() -> Vc { + Vc::cell("ecmascript build node evaluate chunk".into()) } #[turbo_tasks::function] -fn chunk_reference_description() -> Vc { - Vc::cell("chunk".to_string()) +fn chunk_reference_description() -> Vc { + Vc::cell("chunk".into()) } #[turbo_tasks::value_impl] diff --git a/crates/turbopack-nodejs/src/ecmascript/node/entry/runtime.rs b/crates/turbopack-nodejs/src/ecmascript/node/entry/runtime.rs index 2bffe218d5986..25e7f37ac389d 100644 --- a/crates/turbopack-nodejs/src/ecmascript/node/entry/runtime.rs +++ b/crates/turbopack-nodejs/src/ecmascript/node/entry/runtime.rs @@ -2,7 +2,7 @@ use std::io::Write; use anyhow::{bail, Result}; use indoc::writedoc; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbo_tasks_fs::{File, FileSystem}; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -91,8 +91,8 @@ impl EcmascriptBuildNodeRuntimeChunk { #[turbo_tasks::value_impl] impl ValueToString for EcmascriptBuildNodeRuntimeChunk { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell("Ecmascript Build Node Runtime Chunk".to_string())) + async fn to_string(&self) -> Result> { + Ok(Vc::cell("Ecmascript Build Node Runtime Chunk".into())) } } @@ -103,10 +103,10 @@ impl OutputAsset for EcmascriptBuildNodeRuntimeChunk { let ident = AssetIdent::from_path( turbopack_ecmascript_runtime::embed_fs() .root() - .join("runtime.js".to_string()), + .join("runtime.js".into()), ); - AssetIdent::from_path(self.chunking_context.chunk_path(ident, ".js".to_string())) + AssetIdent::from_path(self.chunking_context.chunk_path(ident, ".js".into())) } #[turbo_tasks::function] diff --git a/crates/turbopack-nodejs/src/ecmascript/node/version.rs b/crates/turbopack-nodejs/src/ecmascript/node/version.rs index 4c7c073736ed5..be165f3757c7d 100644 --- a/crates/turbopack-nodejs/src/ecmascript/node/version.rs +++ b/crates/turbopack-nodejs/src/ecmascript/node/version.rs @@ -1,5 +1,5 @@ use anyhow::{bail, Result}; -use turbo_tasks::{ReadRef, Vc}; +use turbo_tasks::{RcStr, ReadRef, Vc}; use turbo_tasks_fs::FileSystemPath; use turbo_tasks_hash::{encode_hex, Xxh3Hash64Hasher}; use turbopack_core::{ @@ -51,7 +51,7 @@ impl EcmascriptBuildNodeChunkVersion { #[turbo_tasks::value_impl] impl Version for EcmascriptBuildNodeChunkVersion { #[turbo_tasks::function] - fn id(&self) -> Vc { + fn id(&self) -> Vc { let mut hasher = Xxh3Hash64Hasher::new(); hasher.write_ref(&self.chunk_path); hasher.write_ref(&self.minify_type); @@ -61,6 +61,6 @@ impl Version for EcmascriptBuildNodeChunkVersion { } let hash = hasher.finish(); let hex_hash = encode_hex(hash); - Vc::cell(hex_hash) + Vc::cell(hex_hash.into()) } } diff --git a/crates/turbopack-resolve/src/ecmascript.rs b/crates/turbopack-resolve/src/ecmascript.rs index ef08b659de601..9ccbcb72c0fc1 100644 --- a/crates/turbopack-resolve/src/ecmascript.rs +++ b/crates/turbopack-resolve/src/ecmascript.rs @@ -49,8 +49,8 @@ pub async fn apply_esm_specific_options( // TODO set fully_specified when in strict ESM mode // options.fully_specified = true; for conditions in get_condition_maps(&mut options) { - conditions.insert("import".to_string(), ConditionValue::Set); - conditions.insert("require".to_string(), ConditionValue::Unset); + conditions.insert("import".into(), ConditionValue::Set); + conditions.insert("require".into(), ConditionValue::Unset); } if matches!( @@ -67,8 +67,8 @@ pub async fn apply_esm_specific_options( pub async fn apply_cjs_specific_options(options: Vc) -> Result> { let mut options: ResolveOptions = options.await?.clone_value(); for conditions in get_condition_maps(&mut options) { - conditions.insert("import".to_string(), ConditionValue::Unset); - conditions.insert("require".to_string(), ConditionValue::Set); + conditions.insert("import".into(), ConditionValue::Unset); + conditions.insert("require".into(), ConditionValue::Set); } Ok(options.into()) } diff --git a/crates/turbopack-resolve/src/node_native_binding.rs b/crates/turbopack-resolve/src/node_native_binding.rs index 52a0afaf6b2b2..8216a9da9743d 100644 --- a/crates/turbopack-resolve/src/node_native_binding.rs +++ b/crates/turbopack-resolve/src/node_native_binding.rs @@ -3,7 +3,7 @@ use indexmap::IndexMap; use lazy_static::lazy_static; use regex::Regex; use serde::{Deserialize, Serialize}; -use turbo_tasks::{TryFlatJoinIterExt, ValueToString, Vc}; +use turbo_tasks::{RcStr, TryFlatJoinIterExt, ValueToString, Vc}; use turbo_tasks_fs::{ glob::Glob, json::parse_json_rope_with_source_context, DirectoryEntry, FileContent, FileSystemEntryType, FileSystemPath, @@ -69,14 +69,17 @@ impl ModuleReference for NodePreGypConfigReference { #[turbo_tasks::value_impl] impl ValueToString for NodePreGypConfigReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { + async fn to_string(&self) -> Result> { let context_dir = self.context_dir.to_string().await?; let config_file_pattern = self.config_file_pattern.to_string().await?; let compile_target = self.compile_target.await?; - Ok(Vc::cell(format!( - "node-gyp in {} with {} for {}", - context_dir, config_file_pattern, compile_target - ))) + Ok(Vc::cell( + format!( + "node-gyp in {} with {} for {}", + context_dir, config_file_pattern, compile_target + ) + .into(), + )) } } @@ -109,7 +112,7 @@ pub async fn resolve_node_pre_gyp_files( let config_file_dir = config_file_path.parent(); let node_pre_gyp_config: NodePreGypConfigJson = parse_json_rope_with_source_context(config_file.content())?; - let mut sources: IndexMap>> = IndexMap::new(); + let mut sources: IndexMap>> = IndexMap::new(); for version in node_pre_gyp_config.binary.napi_versions.iter() { let native_binding_path = NAPI_VERSION_TEMPLATE.replace( node_pre_gyp_config.binary.module_path.as_str(), @@ -120,20 +123,22 @@ pub async fn resolve_node_pre_gyp_files( PLATFORM_TEMPLATE.replace(&native_binding_path, platform.as_str()); let native_binding_path = ARCH_TEMPLATE.replace(&native_binding_path, compile_target.arch.as_str()); - let native_binding_path = LIBC_TEMPLATE.replace( - &native_binding_path, - // node-pre-gyp only cares about libc on linux - if platform == Platform::Linux { - compile_target.libc.as_str() - } else { - "unknown" - }, - ); + let native_binding_path: RcStr = LIBC_TEMPLATE + .replace( + &native_binding_path, + // node-pre-gyp only cares about libc on linux + if platform == Platform::Linux { + compile_target.libc.as_str() + } else { + "unknown" + }, + ) + .into(); for (key, entry) in config_file_dir - .join(native_binding_path.to_string()) + .join(native_binding_path.clone()) .read_glob( - Glob::new(format!("*.{}", compile_target.dylib_ext())), + Glob::new(format!("*.{}", compile_target.dylib_ext()).into()), false, ) .await? @@ -144,16 +149,17 @@ pub async fn resolve_node_pre_gyp_files( entry { sources.insert( - format!("{native_binding_path}/{key}"), + format!("{native_binding_path}/{key}").into(), Vc::upcast(FileSource::new(dylib)), ); } } - let node_file_path = format!( + let node_file_path: RcStr = format!( "{}/{}.node", native_binding_path, node_pre_gyp_config.binary.module_name - ); + ) + .into(); let resolved_file_vc = config_file_dir.join(node_file_path.clone()); sources.insert( node_file_path, @@ -163,8 +169,8 @@ pub async fn resolve_node_pre_gyp_files( for (key, entry) in config_file_dir // TODO // read the dependencies path from `bindings.gyp` - .join("deps/lib".to_string()) - .read_glob(Glob::new("*".to_string()), false) + .join("deps/lib".into()) + .read_glob(Glob::new("*".into()), false) .await? .results .iter() @@ -172,7 +178,7 @@ pub async fn resolve_node_pre_gyp_files( match *entry { DirectoryEntry::File(dylib) => { sources.insert( - format!("deps/lib/{key}"), + format!("deps/lib/{key}").into(), Vc::upcast(FileSource::new(dylib)), ); } @@ -182,7 +188,7 @@ pub async fn resolve_node_pre_gyp_files( affecting_paths.push(symlink); } sources.insert( - format!("deps/lib/{key}"), + format!("deps/lib/{key}").into(), Vc::upcast(FileSource::new(realpath_with_links.path)), ); } @@ -234,13 +240,12 @@ impl ModuleReference for NodeGypBuildReference { #[turbo_tasks::value_impl] impl ValueToString for NodeGypBuildReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { + async fn to_string(&self) -> Result> { let context_dir = self.context_dir.to_string().await?; let compile_target = self.compile_target.await?; - Ok(Vc::cell(format!( - "node-gyp in {} for {}", - context_dir, compile_target - ))) + Ok(Vc::cell( + format!("node-gyp in {} for {}", context_dir, compile_target).into(), + )) } } @@ -255,7 +260,7 @@ pub async fn resolve_node_gyp_build_files( Regex::new(r#"['"]target_name['"]\s*:\s*(?:"(.*?)"|'(.*?)')"#) .expect("create napi_build_version regex failed"); } - let binding_gyp_pat = Pattern::new(Pattern::Constant("binding.gyp".to_owned())); + let binding_gyp_pat = Pattern::new(Pattern::Constant("binding.gyp".into())); let gyp_file = resolve_raw(context_dir, binding_gyp_pat, true); if let [binding_gyp] = &gyp_file.primary_sources().await?[..] { let mut merged_affecting_sources = @@ -265,14 +270,14 @@ pub async fn resolve_node_gyp_build_files( if let Some(captured) = GYP_BUILD_TARGET_NAME.captures(&config_file.content().to_str()?) { - let mut resolved: IndexMap>> = + let mut resolved: IndexMap>> = IndexMap::with_capacity(captured.len()); for found in captured.iter().skip(1).flatten() { let name = found.as_str(); - let target_path = context_dir.join("build/Release".to_string()); + let target_path = context_dir.join("build/Release".into()); let resolved_prebuilt_file = resolve_raw( target_path, - Pattern::new(Pattern::Constant(format!("{}.node", name))), + Pattern::new(Pattern::Constant(format!("{}.node", name).into())), true, ) .await?; @@ -280,7 +285,7 @@ pub async fn resolve_node_gyp_build_files( resolved_prebuilt_file.primary.first() { resolved.insert( - format!("build/Release/{name}.node"), + format!("build/Release/{name}.node").into(), source.resolve().await?, ); merged_affecting_sources @@ -307,9 +312,9 @@ pub async fn resolve_node_gyp_build_files( Ok(resolve_raw( context_dir, Pattern::new(Pattern::Concatenation(vec![ - Pattern::Constant(format!("prebuilds/{}/", prebuilt_dir)), + Pattern::Constant(format!("prebuilds/{}/", prebuilt_dir).into()), Pattern::Dynamic, - Pattern::Constant(".node".to_owned()), + Pattern::Constant(".node".into()), ])), true, ) @@ -320,13 +325,13 @@ pub async fn resolve_node_gyp_build_files( #[derive(Hash, Clone, Debug)] pub struct NodeBindingsReference { pub context_dir: Vc, - pub file_name: String, + pub file_name: RcStr, } #[turbo_tasks::value_impl] impl NodeBindingsReference { #[turbo_tasks::function] - pub fn new(context_dir: Vc, file_name: String) -> Vc { + pub fn new(context_dir: Vc, file_name: RcStr) -> Vc { Self::cell(NodeBindingsReference { context_dir, file_name, @@ -345,18 +350,17 @@ impl ModuleReference for NodeBindingsReference { #[turbo_tasks::value_impl] impl ValueToString for NodeBindingsReference { #[turbo_tasks::function] - async fn to_string(&self) -> Result> { - Ok(Vc::cell(format!( - "bindings in {}", - self.context_dir.to_string().await?, - ))) + async fn to_string(&self) -> Result> { + Ok(Vc::cell( + format!("bindings in {}", self.context_dir.to_string().await?,).into(), + )) } } #[turbo_tasks::function] pub async fn resolve_node_bindings_files( context_dir: Vc, - file_name: String, + file_name: RcStr, ) -> Result> { lazy_static! { static ref BINDINGS_TRY: [&'static str; 5] = [ @@ -371,7 +375,7 @@ pub async fn resolve_node_bindings_files( loop { let resolved = resolve_raw( root_context_dir, - Pattern::new(Pattern::Constant("package.json".to_owned())), + Pattern::new(Pattern::Constant("package.json".into())), true, ) .first_source() @@ -392,7 +396,7 @@ pub async fn resolve_node_bindings_files( root_context_dir = parent; } - let try_path = |sub_path: String| async move { + let try_path = |sub_path: RcStr| async move { let path = root_context_dir.join(sub_path.clone()); Ok( if matches!(*path.get_type().await?, FileSystemEntryType::File) { @@ -408,7 +412,7 @@ pub async fn resolve_node_bindings_files( let modules = BINDINGS_TRY .iter() - .map(|try_dir| try_path(format!("{}/{}", try_dir, &file_name))) + .map(|try_dir| try_path(format!("{}/{}", try_dir, &file_name).into())) .try_flat_join() .await?; Ok(ModuleResolveResult::modules(modules).cell()) diff --git a/crates/turbopack-resolve/src/resolve.rs b/crates/turbopack-resolve/src/resolve.rs index f4e1c49e8451e..9f65b51b9226a 100644 --- a/crates/turbopack-resolve/src/resolve.rs +++ b/crates/turbopack-resolve/src/resolve.rs @@ -106,7 +106,8 @@ async fn base_resolve_options( for req in EDGE_NODE_EXTERNALS { direct_mappings.insert( AliasPattern::exact(req), - ImportMapping::External(Some(format!("node:{req}")), ExternalType::CommonJs).into(), + ImportMapping::External(Some(format!("node:{req}").into()), ExternalType::CommonJs) + .into(), ); direct_mappings.insert( AliasPattern::exact(format!("node:{req}")), @@ -126,31 +127,31 @@ async fn base_resolve_options( let conditions = { let mut conditions: ResolutionConditions = [ - ("import".to_string(), ConditionValue::Unknown), - ("require".to_string(), ConditionValue::Unknown), + ("import".into(), ConditionValue::Unknown), + ("require".into(), ConditionValue::Unknown), ] .into_iter() .collect(); if opt.browser { - conditions.insert("browser".to_string(), ConditionValue::Set); + conditions.insert("browser".into(), ConditionValue::Set); } if opt.module { - conditions.insert("module".to_string(), ConditionValue::Set); + conditions.insert("module".into(), ConditionValue::Set); } if let Some(environment) = emulating { for condition in environment.resolve_conditions().await?.iter() { - conditions.insert(condition.to_string(), ConditionValue::Set); + conditions.insert(condition.clone(), ConditionValue::Set); } } for condition in opt.custom_conditions.iter() { - conditions.insert(condition.to_string(), ConditionValue::Set); + conditions.insert(condition.clone(), ConditionValue::Set); } // Infer some well-known conditions let dev = conditions.get("development").cloned(); let prod = conditions.get("production").cloned(); if prod.is_none() { conditions.insert( - "production".to_string(), + "production".into(), if matches!(dev, Some(ConditionValue::Set)) { ConditionValue::Unset } else { @@ -160,7 +161,7 @@ async fn base_resolve_options( } if dev.is_none() { conditions.insert( - "development".to_string(), + "development".into(), if matches!(prod, Some(ConditionValue::Set)) { ConditionValue::Unset } else { @@ -178,42 +179,36 @@ async fn base_resolve_options( } else { let mut ext = Vec::new(); if opt.enable_typescript && opt.enable_react { - ext.push(".tsx".to_string()); + ext.push(".tsx".into()); } if opt.enable_typescript { - ext.push(".ts".to_string()); + ext.push(".ts".into()); } if opt.enable_react { - ext.push(".jsx".to_string()); + ext.push(".jsx".into()); } - ext.push(".js".to_string()); + ext.push(".js".into()); if opt.enable_mjs_extension { - ext.push(".mjs".to_string()); + ext.push(".mjs".into()); } if opt.enable_node_native_modules { - ext.push(".node".to_string()); + ext.push(".node".into()); } - ext.push(".json".to_string()); + ext.push(".json".into()); ext }; Ok(ResolveOptions { extensions, modules: if let Some(environment) = emulating { if *environment.resolve_node_modules().await? { - vec![ResolveModules::Nested( - root, - vec!["node_modules".to_string()], - )] + vec![ResolveModules::Nested(root, vec!["node_modules".into()])] } else { Vec::new() } } else { let mut mods = Vec::new(); if let Some(dir) = opt.enable_node_modules { - mods.push(ResolveModules::Nested( - dir, - vec!["node_modules".to_string()], - )); + mods.push(ResolveModules::Nested(dir, vec!["node_modules".into()])); } mods }, @@ -224,16 +219,16 @@ async fn base_resolve_options( }]; if opt.browser { resolve_into.push(ResolveIntoPackage::MainField { - field: "browser".to_string(), + field: "browser".into(), }); } if opt.module { resolve_into.push(ResolveIntoPackage::MainField { - field: "module".to_string(), + field: "module".into(), }); } resolve_into.push(ResolveIntoPackage::MainField { - field: "main".to_string(), + field: "main".into(), }); resolve_into }, @@ -243,11 +238,11 @@ async fn base_resolve_options( unspecified_conditions: ConditionValue::Unset, }]; if opt.browser { - resolve_in.push(ResolveInPackage::AliasField("browser".to_string())); + resolve_in.push(ResolveInPackage::AliasField("browser".into())); } resolve_in }, - default_files: vec!["index".to_string()], + default_files: vec!["index".into()], import_map: Some(import_map), resolved_map: opt.resolved_map, plugins, diff --git a/crates/turbopack-resolve/src/resolve_options_context.rs b/crates/turbopack-resolve/src/resolve_options_context.rs index 6b38129b2bc25..2615a3ae5290a 100644 --- a/crates/turbopack-resolve/src/resolve_options_context.rs +++ b/crates/turbopack-resolve/src/resolve_options_context.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{ValueDefault, Vc}; +use turbo_tasks::{RcStr, ValueDefault, Vc}; use turbo_tasks_fs::FileSystemPath; use turbopack_core::{ condition::ContextCondition, @@ -44,9 +44,9 @@ pub struct ResolveOptionsContext { /// Enables the "module" field and export condition in package.json pub module: bool, #[serde(default)] - pub custom_conditions: Vec, + pub custom_conditions: Vec, #[serde(default)] - pub custom_extensions: Option>, + pub custom_extensions: Option>, #[serde(default)] /// An additional import map to use when resolving modules. /// diff --git a/crates/turbopack-resolve/src/typescript.rs b/crates/turbopack-resolve/src/typescript.rs index a781287fef8e5..0831ff6bd4ac1 100644 --- a/crates/turbopack-resolve/src/typescript.rs +++ b/crates/turbopack-resolve/src/typescript.rs @@ -2,7 +2,7 @@ use std::{collections::HashMap, fmt::Write, mem::take}; use anyhow::Result; use serde_json::Value as JsonValue; -use turbo_tasks::{Value, ValueDefault, Vc}; +use turbo_tasks::{RcStr, Value, ValueDefault, Vc}; use turbo_tasks_fs::{FileContent, FileJsonContent, FileSystemPath}; use turbopack_core::{ asset::Asset, @@ -31,13 +31,13 @@ use crate::ecmascript::get_condition_maps; pub struct TsConfigIssue { pub severity: Vc, pub source_ident: Vc, - pub message: String, + pub message: RcStr, } #[turbo_tasks::function] async fn json_only(resolve_options: Vc) -> Result> { let mut opts = resolve_options.await?.clone_value(); - opts.extensions = vec![".json".to_string()]; + opts.extensions = vec![".json".into()]; Ok(opts.cell()) } @@ -65,7 +65,7 @@ pub async fn read_tsconfigs( TsConfigIssue { severity: IssueSeverity::Error.into(), source_ident: tsconfig.ident(), - message, + message: message.into(), } .cell() .emit(); @@ -91,7 +91,8 @@ pub async fn read_tsconfigs( TsConfigIssue { severity: IssueSeverity::Error.into(), source_ident: tsconfig.ident(), - message: format!("extends: \"{}\" doesn't resolve correctly", extends), + message: format!("extends: \"{}\" doesn't resolve correctly", extends) + .into(), } .cell() .emit(); @@ -113,7 +114,7 @@ async fn resolve_extends( resolve_options: Vc, ) -> Result> { let parent_dir = tsconfig.ident().path().parent(); - let request = Request::parse_string(extends.to_string()); + let request = Request::parse_string(extends.into()); // TS's resolution is weird, and has special behavior for different import // types. There might be multiple alternatives like @@ -139,7 +140,7 @@ async fn resolve_extends( // An empty extends is treated as "./tsconfig" Request::Empty => { - let request = Request::parse_string("./tsconfig".to_string()); + let request = Request::parse_string("./tsconfig".into()); Ok(resolve(parent_dir, Value::new(ReferenceType::TypeScript(TypeScriptReferenceSubType::Undefined)), request, resolve_options).first_source()) } @@ -149,7 +150,7 @@ async fn resolve_extends( _ => { let mut result = resolve(parent_dir, Value::new(ReferenceType::TypeScript(TypeScriptReferenceSubType::Undefined)), request, resolve_options).first_source(); if result.await?.is_none() { - let request = Request::parse_string(format!("{extends}/tsconfig")); + let request = Request::parse_string(format!("{extends}/tsconfig").into()); result = resolve(parent_dir, Value::new(ReferenceType::TypeScript(TypeScriptReferenceSubType::Undefined)), request, resolve_options).first_source(); } Ok(result) @@ -177,7 +178,7 @@ async fn resolve_extends_rooted_or_relative( // to try again with it. // https://github.com/microsoft/TypeScript/blob/611a912d/src/compiler/commandLineParser.ts#L3305 if !path.ends_with(".json") && result.await?.is_none() { - let request = Request::parse_string(format!("{path}.json")); + let request = Request::parse_string(format!("{path}.json").into()); result = resolve( lookup_path, Value::new(ReferenceType::TypeScript( @@ -240,13 +241,9 @@ pub async fn tsconfig_resolve_options( } let base_url = if let Some(base_url) = read_from_tsconfigs(&configs, |json, source| { - json["compilerOptions"]["baseUrl"].as_str().map(|base_url| { - source - .ident() - .path() - .parent() - .try_join(base_url.to_string()) - }) + json["compilerOptions"]["baseUrl"] + .as_str() + .map(|base_url| source.ident().path().parent().try_join(base_url.into())) }) .await? { @@ -261,7 +258,7 @@ pub async fn tsconfig_resolve_options( if let JsonValue::Object(paths) = &json["compilerOptions"]["paths"] { let mut context_dir = source.ident().path().parent(); if let Some(base_url) = json["compilerOptions"]["baseUrl"].as_str() { - if let Some(new_context) = *context_dir.try_join(base_url.to_string()).await? { + if let Some(new_context) = *context_dir.try_join(base_url.into()).await? { context_dir = new_context; } }; @@ -279,9 +276,9 @@ pub async fn tsconfig_resolve_options( entry.map(|s| { // tsconfig paths are always relative requests if s.starts_with("./") || s.starts_with("../") { - s.to_string() + s.into() } else { - format!("./{s}") + format!("./{s}").into() } }) }) @@ -299,7 +296,8 @@ pub async fn tsconfig_resolve_options( expected\n{key}: {value:#}", key = serde_json::to_string(key)?, value = value - ), + ) + .into(), } .cell() .emit() @@ -327,11 +325,8 @@ pub async fn tsconfig_resolve_options( } #[turbo_tasks::function] -pub fn tsconfig() -> Vc> { - Vc::cell(vec![ - "tsconfig.json".to_string(), - "jsconfig.json".to_string(), - ]) +pub fn tsconfig() -> Vc> { + Vc::cell(vec!["tsconfig.json".into(), "jsconfig.json".into()]) } #[turbo_tasks::function] @@ -378,15 +373,15 @@ pub async fn type_resolve( } = &*request.await? { let m = if let Some(stripped) = m.strip_prefix('@') { - stripped.replace('/', "__") + stripped.replace('/', "__").into() } else { m.clone() }; Some(Request::module( - format!("@types/{m}"), + format!("@types/{m}").into(), Value::new(p.clone()), - Vc::::default(), - Vc::::default(), + Vc::::default(), + Vc::::default(), )) } else { None @@ -458,7 +453,7 @@ async fn apply_typescript_types_options( resolve_options: Vc, ) -> Result> { let mut resolve_options = resolve_options.await?.clone_value(); - resolve_options.extensions = vec![".tsx".to_string(), ".ts".to_string(), ".d.ts".to_string()]; + resolve_options.extensions = vec![".tsx".into(), ".ts".into(), ".d.ts".into()]; resolve_options.into_package = resolve_options .into_package .drain(..) @@ -468,7 +463,7 @@ async fn apply_typescript_types_options( unspecified_conditions, } = into { - conditions.insert("types".to_string(), ConditionValue::Set); + conditions.insert("types".into(), ConditionValue::Set); Some(ResolveIntoPackage::ExportsField { conditions, unspecified_conditions, @@ -481,10 +476,10 @@ async fn apply_typescript_types_options( resolve_options .into_package .push(ResolveIntoPackage::MainField { - field: "types".to_string(), + field: "types".into(), }); for conditions in get_condition_maps(&mut resolve_options) { - conditions.insert("types".to_string(), ConditionValue::Set); + conditions.insert("types".into(), ConditionValue::Set); } Ok(resolve_options.into()) } @@ -499,7 +494,7 @@ impl Issue for TsConfigIssue { #[turbo_tasks::function] async fn title(&self) -> Result> { Ok( - StyledString::Text("An issue occurred while parsing a tsconfig.json file.".to_string()) + StyledString::Text("An issue occurred while parsing a tsconfig.json file.".into()) .cell(), ) } diff --git a/crates/turbopack-static/src/lib.rs b/crates/turbopack-static/src/lib.rs index b135d951f7a06..dac5336fe4d8c 100644 --- a/crates/turbopack-static/src/lib.rs +++ b/crates/turbopack-static/src/lib.rs @@ -15,7 +15,7 @@ pub mod fixed; pub mod output_asset; use anyhow::Result; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbopack_core::{ asset::{Asset, AssetContent}, chunk::{ChunkItem, ChunkType, ChunkableModule, ChunkingContext}, @@ -38,8 +38,8 @@ use turbopack_ecmascript::{ use self::output_asset::StaticAsset; #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("static".to_string()) +fn modifier() -> Vc { + Vc::cell("static".into()) } #[turbo_tasks::value] @@ -128,10 +128,13 @@ impl ChunkItem for ModuleChunkItem { async fn references(&self) -> Result> { Ok(Vc::cell(vec![Vc::upcast(SingleOutputAssetReference::new( Vc::upcast(self.static_asset), - Vc::cell(format!( - "static(url) {}", - self.static_asset.ident().to_string().await? - )), + Vc::cell( + format!( + "static(url) {}", + self.static_asset.ident().to_string().await? + ) + .into(), + ), ))])) } diff --git a/crates/turbopack-static/src/output_asset.rs b/crates/turbopack-static/src/output_asset.rs index 62b441d94be6b..d7a99a57b9ed2 100644 --- a/crates/turbopack-static/src/output_asset.rs +++ b/crates/turbopack-static/src/output_asset.rs @@ -45,7 +45,7 @@ impl OutputAsset for StaticAsset { let content_hash_b16 = turbo_tasks_hash::encode_hex(content_hash); let asset_path = self .chunking_context - .asset_path(content_hash_b16, self.source.ident()); + .asset_path(content_hash_b16.into(), self.source.ident()); Ok(AssetIdent::from_path(asset_path)) } } diff --git a/crates/turbopack-swc-utils/src/emitter.rs b/crates/turbopack-swc-utils/src/emitter.rs index 7821531e7a053..ae1db280c35de 100644 --- a/crates/turbopack-swc-utils/src/emitter.rs +++ b/crates/turbopack-swc-utils/src/emitter.rs @@ -5,7 +5,7 @@ use swc_core::common::{ source_map::Pos, SourceMap, }; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbopack_core::{ issue::{analyze::AnalyzeIssue, IssueExt, IssueSeverity, IssueSource, StyledString}, source::Source, @@ -15,7 +15,7 @@ use turbopack_core::{ pub struct IssueEmitter { pub source: Vc>, pub source_map: Arc, - pub title: Option, + pub title: Option, pub emitted_issues: Vec>, } @@ -23,7 +23,7 @@ impl IssueEmitter { pub fn new( source: Vc>, source_map: Arc, - title: Option, + title: Option, ) -> Self { Self { source, @@ -44,8 +44,8 @@ impl Emitter for IssueEmitter { .collect::>() .join(""); let code = db.code.as_ref().map(|d| match d { - DiagnosticId::Error(s) => format!("error {s}"), - DiagnosticId::Lint(s) => format!("lint {s}"), + DiagnosticId::Error(s) => format!("error {s}").into(), + DiagnosticId::Lint(s) => format!("lint {s}").into(), }); let title; @@ -53,7 +53,7 @@ impl Emitter for IssueEmitter { title = t.clone(); } else { let mut message_split = message.split('\n'); - title = message_split.next().unwrap().to_string(); + title = message_split.next().unwrap().to_string().into(); message = message_split.remainder().unwrap_or("").to_string(); } @@ -76,7 +76,7 @@ impl Emitter for IssueEmitter { .cell(), source_ident: self.source.ident(), title: Vc::cell(title), - message: StyledString::Text(message).cell(), + message: StyledString::Text(message.into()).cell(), code, source, } diff --git a/crates/turbopack-test-utils/src/snapshot.rs b/crates/turbopack-test-utils/src/snapshot.rs index c23f1dd12153b..c8d34ef86b2f0 100644 --- a/crates/turbopack-test-utils/src/snapshot.rs +++ b/crates/turbopack-test-utils/src/snapshot.rs @@ -8,7 +8,7 @@ use anyhow::{anyhow, bail, Context, Result}; use once_cell::sync::Lazy; use regex::Regex; use similar::TextDiff; -use turbo_tasks::{ReadRef, TryJoinIterExt, ValueToString, Vc}; +use turbo_tasks::{RcStr, ReadRef, TryJoinIterExt, ValueToString, Vc}; use turbo_tasks_fs::{ DirectoryContent, DirectoryEntry, DiskFileSystem, File, FileContent, FileSystemEntryType, FileSystemPath, @@ -48,7 +48,7 @@ pub async fn snapshot_issues>>( }; let hash = encode_hex(plain_issue.internal_hash_ref(true)); - let path = issues_path.join(format!("{title}-{}.txt", &hash[0..6])); + let path = issues_path.join(format!("{title}-{}.txt", &hash[0..6]).into()); if !seen.insert(path) { continue; } @@ -68,12 +68,13 @@ pub async fn snapshot_issues>>( // Annoyingly, the PlainIssue.source -> PlainIssueSource.asset -> // PlainSource.path -> FileSystemPath.fs -> DiskFileSystem.root changes // for everyone. - let content = formatted + let content: RcStr = formatted .as_str() .replace(workspace_root, "WORKSPACE_ROOT") .replace(&*ANSI_REGEX, "") // Normalize syspaths from Windows. These appear in stack traces. - .replace("\\\\", "/"); + .replace("\\\\", "/") + .into(); let asset = AssetContent::file(File::from(content).into()); @@ -129,7 +130,7 @@ pub async fn diff(path: Vc, actual: Vc) -> Result< if actual != expected { if let Some(actual) = actual { if *UPDATE { - let content = File::from(actual).into(); + let content = File::from(RcStr::from(actual)).into(); path.write(content).await?; println!("updated contents of {}", path_str); } else { diff --git a/crates/turbopack-tests/tests/execution.rs b/crates/turbopack-tests/tests/execution.rs index 05ce103ee09ad..13cd56866bdfe 100644 --- a/crates/turbopack-tests/tests/execution.rs +++ b/crates/turbopack-tests/tests/execution.rs @@ -9,7 +9,8 @@ use anyhow::{Context, Result}; use dunce::canonicalize; use serde::{Deserialize, Serialize}; use turbo_tasks::{ - debug::ValueDebugFormat, trace::TraceRawVcs, Completion, TryJoinIterExt, TurboTasks, Value, Vc, + debug::ValueDebugFormat, trace::TraceRawVcs, Completion, RcStr, TryJoinIterExt, TurboTasks, + Value, Vc, }; use turbo_tasks_bytes::stream::SingleValue; use turbo_tasks_env::CommandLineProcessEnv; @@ -124,7 +125,7 @@ fn get_messages(js_results: JsResult) -> Vec { let mut messages = vec![]; if js_results.jest_result.test_results.is_empty() { - messages.push("No tests were run.".to_string()); + messages.push("No tests were run.".into()); } for test_result in js_results.jest_result.test_results { @@ -158,7 +159,7 @@ async fn run(resource: PathBuf, snapshot_mode: IssueSnapshotMode) -> Result Result> { +async fn prepare_test(resource: RcStr) -> Result> { let resource_path = canonicalize(&resource)?; assert!(resource_path.exists(), "{} does not exist", resource); assert!( @@ -194,8 +195,8 @@ async fn prepare_test(resource: String) -> Result> { resource_path.to_str().unwrap() ); - let root_fs = DiskFileSystem::new("workspace".to_string(), REPO_ROOT.clone(), vec![]); - let project_fs = DiskFileSystem::new("project".to_string(), REPO_ROOT.clone(), vec![]); + let root_fs = DiskFileSystem::new("workspace".into(), REPO_ROOT.clone(), vec![]); + let project_fs = DiskFileSystem::new("project".into(), REPO_ROOT.clone(), vec![]); let project_root = project_fs.root(); let relative_path = resource_path.strip_prefix(&*REPO_ROOT).context(format!( @@ -203,12 +204,12 @@ async fn prepare_test(resource: String) -> Result> { &*REPO_ROOT, resource_path.display() ))?; - let relative_path = sys_to_unix(relative_path.to_str().unwrap()); - let path = root_fs.root().join(relative_path.to_string()); - let project_path = project_root.join(relative_path.to_string()); - let tests_path = project_fs.root().join("crates/turbopack-tests".to_string()); + let relative_path: RcStr = sys_to_unix(relative_path.to_str().unwrap()).into(); + let path = root_fs.root().join(relative_path.clone()); + let project_path = project_root.join(relative_path.clone()); + let tests_path = project_fs.root().join("crates/turbopack-tests".into()); - let options_file = path.join("options.json".to_string()); + let options_file = path.join("options.json".into()); let mut options = TestOptions::default(); if matches!(*options_file.get_type().await?, FileSystemEntryType::File) { @@ -238,12 +239,12 @@ async fn run_test(prepared_test: Vc) -> Result> ref options, } = *prepared_test.await?; - let jest_runtime_path = tests_path.join("js/jest-runtime.ts".to_string()); - let jest_entry_path = tests_path.join("js/jest-entry.ts".to_string()); - let test_path = project_path.join("input/index.js".to_string()); + let jest_runtime_path = tests_path.join("js/jest-runtime.ts".into()); + let jest_entry_path = tests_path.join("js/jest-entry.ts".into()); + let test_path = project_path.join("input/index.js".into()); - let chunk_root_path = path.join("output".to_string()); - let static_root_path = path.join("static".to_string()); + let chunk_root_path = path.join("output".into()); + let static_root_path = path.join("static".into()); let env = Environment::new(Value::new(ExecutionEnvironment::NodeJsBuildTime( NodeJsEnvironment::default().into(), @@ -263,7 +264,7 @@ async fn run_test(prepared_test: Vc) -> Result> let mut import_map = ImportMap::empty(); import_map.insert_wildcard_alias( "esm-external/", - ImportMapping::External(Some("*".to_string()), ExternalType::EcmaScriptModule).cell(), + ImportMapping::External(Some("*".into()), ExternalType::EcmaScriptModule).cell(), ); let asset_context: Vc> = Vc::upcast(ModuleAssetContext::new( @@ -275,7 +276,7 @@ async fn run_test(prepared_test: Vc) -> Result> tree_shaking_mode: options.tree_shaking_mode, import_externals: true, rules: vec![( - ContextCondition::InDirectory("node_modules".to_string()), + ContextCondition::InDirectory("node_modules".into()), ModuleOptionsContext { tree_shaking_mode: options.tree_shaking_mode, ..Default::default() @@ -288,12 +289,12 @@ async fn run_test(prepared_test: Vc) -> Result> ResolveOptionsContext { enable_typescript: true, enable_node_modules: Some(project_root), - custom_conditions: vec!["development".to_string()], + custom_conditions: vec!["development".into()], rules: vec![( - ContextCondition::InDirectory("node_modules".to_string()), + ContextCondition::InDirectory("node_modules".into()), ResolveOptionsContext { enable_node_modules: Some(project_root), - custom_conditions: vec!["development".to_string()], + custom_conditions: vec!["development".into()], browser: true, ..Default::default() } @@ -305,7 +306,7 @@ async fn run_test(prepared_test: Vc) -> Result> ..Default::default() } .cell(), - Vc::cell("test".to_string()), + Vc::cell("test".into()), )); let chunking_context = BrowserChunkingContext::builder( @@ -386,7 +387,7 @@ async fn snapshot_issues( turbopack_test_utils::snapshot::snapshot_issues( plain_issues, - path.join("issues".to_string()), + path.join("issues".into()), &REPO_ROOT, ) .await diff --git a/crates/turbopack-tests/tests/snapshot.rs b/crates/turbopack-tests/tests/snapshot.rs index 3b5de21750c11..9d192f84c8845 100644 --- a/crates/turbopack-tests/tests/snapshot.rs +++ b/crates/turbopack-tests/tests/snapshot.rs @@ -12,7 +12,7 @@ use anyhow::{bail, Context, Result}; use dunce::canonicalize; use serde::Deserialize; use serde_json::json; -use turbo_tasks::{ReadRef, TryJoinIterExt, TurboTasks, Value, ValueToString, Vc}; +use turbo_tasks::{RcStr, ReadRef, TryJoinIterExt, TurboTasks, Value, ValueToString, Vc}; use turbo_tasks_env::DotenvProcessEnv; use turbo_tasks_fs::{ json::parse_json_with_source_context, util::sys_to_unix, DiskFileSystem, FileSystem, @@ -155,7 +155,7 @@ async fn run(resource: PathBuf) -> Result<()> { let tt = TurboTasks::new(MemoryBackend::default()); let task = tt.spawn_once_task(async move { - let out = run_test(resource.to_str().unwrap().to_string()); + let out = run_test(resource.to_str().unwrap().into()); let _ = out.resolve_strongly_consistent().await?; let captured_issues = out.peek_issues_with_path().await?; @@ -165,7 +165,7 @@ async fn run(resource: PathBuf) -> Result<()> { .try_join() .await?; - snapshot_issues(plain_issues, out.join("issues".to_string()), &REPO_ROOT) + snapshot_issues(plain_issues, out.join("issues".into()), &REPO_ROOT) .await .context("Unable to handle issues")?; Ok(Vc::<()>::default()) @@ -176,7 +176,7 @@ async fn run(resource: PathBuf) -> Result<()> { } #[turbo_tasks::function] -async fn run_test(resource: String) -> Result> { +async fn run_test(resource: RcStr) -> Result> { let test_path = canonicalize(&resource)?; assert!(test_path.exists(), "{} does not exist", resource); assert!( @@ -190,16 +190,16 @@ async fn run_test(resource: String) -> Result> { Err(_) => SnapshotOptions::default(), Ok(options_str) => parse_json_with_source_context(&options_str).unwrap(), }; - let root_fs = DiskFileSystem::new("workspace".to_string(), REPO_ROOT.clone(), vec![]); - let project_fs = DiskFileSystem::new("project".to_string(), REPO_ROOT.clone(), vec![]); + let root_fs = DiskFileSystem::new("workspace".into(), REPO_ROOT.clone(), vec![]); + let project_fs = DiskFileSystem::new("project".into(), REPO_ROOT.clone(), vec![]); let project_root = project_fs.root(); let relative_path = test_path.strip_prefix(&*REPO_ROOT)?; - let relative_path = sys_to_unix(relative_path.to_str().unwrap()); - let path = root_fs.root().join(relative_path.to_string()); - let project_path = project_root.join(relative_path.to_string()); + let relative_path: RcStr = sys_to_unix(relative_path.to_str().unwrap()).into(); + let path = root_fs.root().join(relative_path.clone()); + let project_path = project_root.join(relative_path.clone()); - let entry_asset = project_path.join(options.entry); + let entry_asset = project_path.join(options.entry.into()); let env = Environment::new(Value::new(match options.environment { SnapshotEnvironment::Browser => { @@ -209,7 +209,7 @@ async fn run_test(resource: String) -> Result> { dom: true, web_worker: false, service_worker: false, - browserslist_query: options.browserslist.to_owned(), + browserslist_query: options.browserslist.into(), } .into(), ) @@ -237,10 +237,10 @@ async fn run_test(resource: String) -> Result> { .cell(); let conditions = ModuleRuleCondition::any(vec![ - ModuleRuleCondition::ResourcePathEndsWith(".js".to_string()), - ModuleRuleCondition::ResourcePathEndsWith(".jsx".to_string()), - ModuleRuleCondition::ResourcePathEndsWith(".ts".to_string()), - ModuleRuleCondition::ResourcePathEndsWith(".tsx".to_string()), + ModuleRuleCondition::ResourcePathEndsWith(".js".into()), + ModuleRuleCondition::ResourcePathEndsWith(".jsx".into()), + ModuleRuleCondition::ResourcePathEndsWith(".ts".into()), + ModuleRuleCondition::ResourcePathEndsWith(".tsx".into()), ]); let custom_rules = ModuleRule::new( @@ -270,7 +270,7 @@ async fn run_test(resource: String) -> Result> { ignore_dynamic_requests: true, use_swc_css: options.use_swc_css, rules: vec![( - ContextCondition::InDirectory("node_modules".to_string()), + ContextCondition::InDirectory("node_modules".into()), ModuleOptionsContext { use_swc_css: options.use_swc_css, ..Default::default() @@ -286,12 +286,12 @@ async fn run_test(resource: String) -> Result> { enable_typescript: true, enable_react: true, enable_node_modules: Some(project_root), - custom_conditions: vec!["development".to_string()], + custom_conditions: vec!["development".into()], rules: vec![( - ContextCondition::InDirectory("node_modules".to_string()), + ContextCondition::InDirectory("node_modules".into()), ResolveOptionsContext { enable_node_modules: Some(project_root), - custom_conditions: vec!["development".to_string()], + custom_conditions: vec!["development".into()], ..Default::default() } .cell(), @@ -299,15 +299,15 @@ async fn run_test(resource: String) -> Result> { ..Default::default() } .cell(), - Vc::cell("test".to_string()), + Vc::cell("test".into()), )); let runtime_entries = maybe_load_env(asset_context, project_path) .await? .map(|asset| EvaluatableAssets::one(asset.to_evaluatable(asset_context))); - let chunk_root_path = path.join("output".to_string()); - let static_root_path = path.join("static".to_string()); + let chunk_root_path = path.join("output".into()); + let static_root_path = path.join("static".into()); let chunking_context: Vc> = match options.runtime { Runtime::Dev => Vc::upcast( @@ -380,9 +380,9 @@ async fn run_test(resource: String) -> Result> { .await? .as_deref() .unwrap() - .to_string(), + .into(), ) - .with_extension("entry.js".to_string()), + .with_extension("entry.js".into()), Vc::upcast(ecmascript), runtime_entries .unwrap_or_else(EvaluatableAssets::empty) @@ -466,7 +466,7 @@ async fn maybe_load_env( _context: Vc>, path: Vc, ) -> Result>>> { - let dotenv_path = path.join("input/.env".to_string()); + let dotenv_path = path.join("input/.env".into()); if !dotenv_path.read().await?.is_content() { return Ok(None); diff --git a/crates/turbopack-tests/tests/util.rs b/crates/turbopack-tests/tests/util.rs index 6723b8e7f6c93..d256f375ba71f 100644 --- a/crates/turbopack-tests/tests/util.rs +++ b/crates/turbopack-tests/tests/util.rs @@ -2,14 +2,11 @@ use std::path::PathBuf; use dunce::canonicalize; use once_cell::sync::Lazy; +use turbo_tasks::RcStr; /// The turbo repo root. Should be used as the root when building with turbopack /// against fixtures in this crate. -pub static REPO_ROOT: Lazy = Lazy::new(|| { +pub static REPO_ROOT: Lazy = Lazy::new(|| { let package_root = PathBuf::from(env!("TURBO_PNPM_WORKSPACE_DIR")); - canonicalize(package_root) - .unwrap() - .to_str() - .unwrap() - .to_string() + canonicalize(package_root).unwrap().to_str().unwrap().into() }); diff --git a/crates/turbopack-wasm/src/loader.rs b/crates/turbopack-wasm/src/loader.rs index ac81ebda5d5f5..1a16107aaf960 100644 --- a/crates/turbopack-wasm/src/loader.rs +++ b/crates/turbopack-wasm/src/loader.rs @@ -2,7 +2,7 @@ use std::fmt::Write; use anyhow::Result; use indoc::{formatdoc, writedoc}; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::File; use turbopack_core::{asset::AssetContent, source::Source, virtual_source::VirtualSource}; use turbopack_ecmascript::utils::StringifyJs; @@ -51,8 +51,10 @@ pub(crate) async fn instantiating_loader_source( exports = analysis.exports.join(", "), )?; + let code: RcStr = code.into(); + Ok(Vc::upcast(VirtualSource::new( - source.ident().path().append("_.loader.mjs".to_string()), + source.ident().path().append("_.loader.mjs".into()), AssetContent::file(File::from(code).into()), ))) } @@ -63,7 +65,7 @@ pub(crate) async fn instantiating_loader_source( pub(crate) async fn compiling_loader_source( source: Vc, ) -> Result>> { - let code = formatdoc! { + let code: RcStr = formatdoc! { r#" import wasmPath from "WASM_PATH"; @@ -71,10 +73,11 @@ pub(crate) async fn compiling_loader_source( export default mod; "# - }; + } + .into(); Ok(Vc::upcast(VirtualSource::new( - source.ident().path().append("_.loader.mjs".to_string()), + source.ident().path().append("_.loader.mjs".into()), AssetContent::file(File::from(code).into()), ))) } diff --git a/crates/turbopack-wasm/src/module_asset.rs b/crates/turbopack-wasm/src/module_asset.rs index 059bbb9ca7692..c357e7abaf597 100644 --- a/crates/turbopack-wasm/src/module_asset.rs +++ b/crates/turbopack-wasm/src/module_asset.rs @@ -1,6 +1,6 @@ use anyhow::{bail, Context, Result}; use indexmap::indexmap; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::{RcStr, Value, Vc}; use turbo_tasks_fs::FileSystemPath; use turbopack_core::{ asset::{Asset, AssetContent}, @@ -30,8 +30,8 @@ use crate::{ }; #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("wasm module".to_string()) +fn modifier() -> Vc { + Vc::cell("wasm module".into()) } /// Creates a javascript loader which instantiates the WebAssembly source and @@ -74,7 +74,7 @@ impl WebAssemblyModuleAsset { let module = self.asset_context.process( loader_source, Value::new(ReferenceType::Internal(Vc::cell(indexmap! { - "WASM_PATH".to_string() => Vc::upcast(RawWebAssemblyModuleAsset::new(self.source, self.asset_context)), + "WASM_PATH".into() => Vc::upcast(RawWebAssemblyModuleAsset::new(self.source, self.asset_context)), }))), ).module(); diff --git a/crates/turbopack-wasm/src/output_asset.rs b/crates/turbopack-wasm/src/output_asset.rs index e799d52736db4..d09ded683e061 100644 --- a/crates/turbopack-wasm/src/output_asset.rs +++ b/crates/turbopack-wasm/src/output_asset.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbopack_core::{ asset::{Asset, AssetContent}, chunk::ChunkingContext, @@ -11,8 +11,8 @@ use turbopack_core::{ use crate::source::WebAssemblySource; #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("wasm".to_string()) +fn modifier() -> Vc { + Vc::cell("wasm".into()) } /// Emits the [WebAssemblySource] at a chunk path determined by the @@ -43,7 +43,7 @@ impl OutputAsset for WebAssemblyAsset { async fn ident(&self) -> Result> { let ident = self.source.ident().with_modifier(modifier()); - let asset_path = self.chunking_context.chunk_path(ident, ".wasm".to_string()); + let asset_path = self.chunking_context.chunk_path(ident, ".wasm".into()); Ok(AssetIdent::from_path(asset_path)) } diff --git a/crates/turbopack-wasm/src/raw.rs b/crates/turbopack-wasm/src/raw.rs index 80013afc1dc5a..44301c0abca22 100644 --- a/crates/turbopack-wasm/src/raw.rs +++ b/crates/turbopack-wasm/src/raw.rs @@ -1,5 +1,5 @@ use anyhow::{bail, Result}; -use turbo_tasks::{ValueToString, Vc}; +use turbo_tasks::{RcStr, ValueToString, Vc}; use turbopack_core::{ asset::{Asset, AssetContent}, chunk::{ChunkItem, ChunkType, ChunkableModule, ChunkingContext}, @@ -21,8 +21,8 @@ use turbopack_ecmascript::{ use crate::{output_asset::WebAssemblyAsset, source::WebAssemblySource}; #[turbo_tasks::function] -fn modifier() -> Vc { - Vc::cell("wasm raw".to_string()) +fn modifier() -> Vc { + Vc::cell("wasm raw".into()) } /// Exports the relative path to the WebAssembly file without loading it. @@ -115,10 +115,7 @@ impl ChunkItem for RawModuleChunkItem { async fn references(&self) -> Result> { Ok(Vc::cell(vec![Vc::upcast(SingleOutputAssetReference::new( Vc::upcast(self.wasm_asset), - Vc::cell(format!( - "wasm(url) {}", - self.wasm_asset.ident().to_string().await? - )), + Vc::cell(format!("wasm(url) {}", self.wasm_asset.ident().to_string().await?).into()), ))])) } diff --git a/crates/turbopack-wasm/src/source.rs b/crates/turbopack-wasm/src/source.rs index 246a57d9548c6..4502617819608 100644 --- a/crates/turbopack-wasm/src/source.rs +++ b/crates/turbopack-wasm/src/source.rs @@ -55,7 +55,7 @@ impl Source for WebAssemblySource { WebAssemblySourceType::Text => self .source .ident() - .with_path(self.source.ident().path().append("_.wasm".to_string())), + .with_path(self.source.ident().path().append("_.wasm".into())), } } } diff --git a/crates/turbopack/benches/node_file_trace.rs b/crates/turbopack/benches/node_file_trace.rs index 0dd71a849bca4..18920f74cd981 100644 --- a/crates/turbopack/benches/node_file_trace.rs +++ b/crates/turbopack/benches/node_file_trace.rs @@ -2,7 +2,7 @@ use std::{collections::HashMap, fs, path::PathBuf}; use criterion::{Bencher, BenchmarkId, Criterion}; use regex::Regex; -use turbo_tasks::{TurboTasks, Value, Vc}; +use turbo_tasks::{RcStr, TurboTasks, Value, Vc}; use turbo_tasks_fs::{DiskFileSystem, FileSystem, NullFileSystem}; use turbo_tasks_memory::MemoryBackend; use turbopack::{ @@ -68,11 +68,11 @@ fn bench_emit(b: &mut Bencher, bench_input: &BenchInput) { b.to_async(rt).iter(move || { let tt = TurboTasks::new(MemoryBackend::default()); - let tests_root = bench_input.tests_root.clone(); - let input = bench_input.input.clone(); + let tests_root: RcStr = bench_input.tests_root.clone().into(); + let input: RcStr = bench_input.input.clone().into(); async move { let task = tt.spawn_once_task(async move { - let input_fs = DiskFileSystem::new("tests".to_string(), tests_root.clone(), vec![]); + let input_fs = DiskFileSystem::new("tests".into(), tests_root.clone(), vec![]); let input = input_fs.root().join(input.clone()); let input_dir = input.parent().parent(); @@ -97,7 +97,7 @@ fn bench_emit(b: &mut Bencher, bench_input: &BenchInput) { ..Default::default() } .cell(), - Vc::cell("node_file_trace".to_string()), + Vc::cell("node_file_trace".into()), ); let module = module_asset_context .process(Vc::upcast(source), Value::new(ReferenceType::Undefined)) diff --git a/crates/turbopack/examples/turbopack.rs b/crates/turbopack/examples/turbopack.rs index f73cb1cde4162..80d5d1799f2dc 100644 --- a/crates/turbopack/examples/turbopack.rs +++ b/crates/turbopack/examples/turbopack.rs @@ -8,7 +8,7 @@ use std::{ use anyhow::Result; use tokio::{spawn, time::sleep}; -use turbo_tasks::{util::FormatDuration, TurboTasks, UpdateInfo, Value, Vc}; +use turbo_tasks::{util::FormatDuration, RcStr, TurboTasks, UpdateInfo, Value, Vc}; use turbo_tasks_fs::{DiskFileSystem, FileSystem}; use turbo_tasks_memory::MemoryBackend; use turbopack::{emit_with_completion, rebase::RebasedAsset, register}; @@ -30,15 +30,15 @@ async fn main() -> Result<()> { let task = tt.spawn_root_task(|| { Box::pin(async { - let root = current_dir().unwrap().to_str().unwrap().to_string(); - let disk_fs = DiskFileSystem::new(PROJECT_FILESYSTEM_NAME.to_string(), root, vec![]); + let root: RcStr = current_dir().unwrap().to_str().unwrap().into(); + let disk_fs = DiskFileSystem::new(PROJECT_FILESYSTEM_NAME.into(), root, vec![]); disk_fs.await?.start_watching()?; // Smart Pointer cast let fs: Vc> = Vc::upcast(disk_fs); - let input = fs.root().join("demo".to_string()); - let output = fs.root().join("out".to_string()); - let entry = fs.root().join("demo/index.js".to_string()); + let input = fs.root().join("demo".into()); + let output = fs.root().join("out".into()); + let entry = fs.root().join("demo/index.js".into()); let source = FileSource::new(entry); let module_asset_context = turbopack::ModuleAssetContext::new( @@ -51,11 +51,11 @@ async fn main() -> Result<()> { enable_typescript: true, enable_react: true, enable_node_modules: Some(fs.root()), - custom_conditions: vec!["development".to_string()], + custom_conditions: vec!["development".into()], ..Default::default() } .cell(), - Vc::cell("default".to_string()), + Vc::cell("default".into()), ); let module = module_asset_context .process( diff --git a/crates/turbopack/src/evaluate_context.rs b/crates/turbopack/src/evaluate_context.rs index 1d5d1ed39892e..7a392575a2475 100644 --- a/crates/turbopack/src/evaluate_context.rs +++ b/crates/turbopack/src/evaluate_context.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::{RcStr, Value, Vc}; use turbo_tasks_env::ProcessEnv; use turbo_tasks_fs::FileSystem; use turbopack_core::{ @@ -30,7 +30,7 @@ pub async fn node_evaluate_asset_context( execution_context: Vc, import_map: Option>, transitions: Option>, - layer: String, + layer: RcStr, ) -> Result>> { let mut import_map = if let Some(import_map) = import_map { import_map.await?.clone_value() @@ -40,17 +40,17 @@ pub async fn node_evaluate_asset_context( import_map.insert_wildcard_alias( "@vercel/turbopack-node/", ImportMapping::PrimaryAlternative( - "./*".to_string(), + "./*".into(), Some(turbopack_node::embed_js::embed_fs().root()), ) .cell(), ); let import_map = import_map.cell(); - let node_env = - if let Some(node_env) = &*execution_context.env().read("NODE_ENV".to_string()).await? { - node_env.clone() + let node_env: RcStr = + if let Some(node_env) = &*execution_context.env().read("NODE_ENV".into()).await? { + node_env.as_str().into() } else { - "development".to_string() + "development".into() }; // base context used for node_modules (and context for app code will be derived @@ -59,7 +59,7 @@ pub async fn node_evaluate_asset_context( enable_node_modules: Some(execution_context.project_path().root().resolve().await?), enable_node_externals: true, enable_node_native_modules: true, - custom_conditions: vec![node_env.clone(), "node".to_string()], + custom_conditions: vec![node_env.clone(), "node".into()], ..Default::default() }; // app code context, includes a rule to switch to the node_modules context @@ -80,7 +80,7 @@ pub async fn node_evaluate_asset_context( .defines( compile_time_defines!( process.turbopack = true, - process.env.NODE_ENV = node_env, + process.env.NODE_ENV = node_env.into_owned(), process.env.TURBOPACK = true ) .cell(), diff --git a/crates/turbopack/src/lib.rs b/crates/turbopack/src/lib.rs index 1cea6fdd3ce1c..ec14591feaf05 100644 --- a/crates/turbopack/src/lib.rs +++ b/crates/turbopack/src/lib.rs @@ -30,7 +30,7 @@ use ecmascript::{ use graph::{aggregate, AggregatedGraph, AggregatedGraphNodeContent}; use module_options::{ModuleOptions, ModuleOptionsContext, ModuleRuleEffect, ModuleType}; use tracing::Instrument; -use turbo_tasks::{Completion, Value, ValueToString, Vc}; +use turbo_tasks::{Completion, RcStr, Value, ValueToString, Vc}; use turbo_tasks_fs::{glob::Glob, FileSystemPath}; pub use turbopack_core::condition; use turbopack_core::{ @@ -334,7 +334,7 @@ pub struct ModuleAssetContext { pub compile_time_info: Vc, pub module_options_context: Vc, pub resolve_options_context: Vc, - pub layer: Vc, + pub layer: Vc, transition: Option>>, } @@ -346,7 +346,7 @@ impl ModuleAssetContext { compile_time_info: Vc, module_options_context: Vc, resolve_options_context: Vc, - layer: Vc, + layer: Vc, ) -> Vc { Self::cell(ModuleAssetContext { transitions, @@ -364,7 +364,7 @@ impl ModuleAssetContext { compile_time_info: Vc, module_options_context: Vc, resolve_options_context: Vc, - layer: Vc, + layer: Vc, transition: Vc>, ) -> Vc { Self::cell(ModuleAssetContext { @@ -435,7 +435,7 @@ async fn process_default( ) -> Result> { let span = tracing::info_span!( "process module", - name = *source.ident().to_string().await?, + name = source.ident().to_string().await?.to_string(), reference_type = display(&*reference_type) ); process_default_internal( @@ -545,12 +545,11 @@ async fn process_default_internal( Some(module_type) => { ModuleIssue { ident, - title: StyledString::Text("Invalid module type".to_string()) - .cell(), + title: StyledString::Text("Invalid module type".into()).cell(), description: StyledString::Text( "The module type must be Ecmascript or Typescript to add \ Ecmascript transforms" - .to_string(), + .into(), ) .cell(), } @@ -561,12 +560,11 @@ async fn process_default_internal( None => { ModuleIssue { ident, - title: StyledString::Text("Missing module type".to_string()) - .cell(), + title: StyledString::Text("Missing module type".into()).cell(), description: StyledString::Text( "The module type effect must be applied before adding \ Ecmascript transforms" - .to_string(), + .into(), ) .cell(), } @@ -586,11 +584,11 @@ async fn process_default_internal( None => { ModuleIssue { ident, - title: StyledString::Text("Unknown module type".to_string()).cell(), + title: StyledString::Text("Unknown module type".into()).cell(), description: StyledString::Text( r"This module doesn't have an associated type. Use a known file extension, or register a loader for it. -Read more: https://nextjs.org/docs/app/api-reference/next-config-js/turbo#webpack-loaders".to_string(), +Read more: https://nextjs.org/docs/app/api-reference/next-config-js/turbo#webpack-loaders".into(), ) .cell(), } @@ -620,7 +618,7 @@ impl AssetContext for ModuleAssetContext { } #[turbo_tasks::function] - fn layer(&self) -> Vc { + fn layer(&self) -> Vc { self.layer } @@ -716,7 +714,7 @@ impl AssetContext for ModuleAssetContext { } #[turbo_tasks::function] - async fn with_transition(&self, transition: String) -> Result>> { + async fn with_transition(&self, transition: RcStr) -> Result>> { Ok( if let Some(transition) = self.transitions.await?.get(&transition) { Vc::upcast(ModuleAssetContext::new_transition( @@ -751,7 +749,7 @@ impl AssetContext for ModuleAssetContext { let mut globs = Vec::with_capacity(pkgs.len()); for pkg in pkgs { - globs.push(Glob::new(format!("**/node_modules/{{{}}}/**", pkg))); + globs.push(Glob::new(format!("**/node_modules/{{{}}}/**", pkg).into())); } Ok(Glob::alternatives(globs)) diff --git a/crates/turbopack/src/module_options/mod.rs b/crates/turbopack/src/module_options/mod.rs index 571490016cec0..7e30806beb6de 100644 --- a/crates/turbopack/src/module_options/mod.rs +++ b/crates/turbopack/src/module_options/mod.rs @@ -8,7 +8,7 @@ pub use custom_module_type::CustomModuleType; pub use module_options_context::*; pub use module_rule::*; pub use rule_condition::*; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbo_tasks_fs::{glob::Glob, FileSystemPath}; use turbopack_core::{ reference_type::{CssReferenceSubType, ReferenceType, UrlReferenceSubType}, @@ -25,7 +25,7 @@ use crate::{ #[turbo_tasks::function] async fn package_import_map_from_import_mapping( - package_name: String, + package_name: RcStr, package_mapping: Vc, ) -> Result> { let mut import_map = ImportMap::default(); @@ -38,7 +38,7 @@ async fn package_import_map_from_import_mapping( #[turbo_tasks::function] async fn package_import_map_from_context( - package_name: String, + package_name: RcStr, context_path: Vc, ) -> Result> { let mut import_map = ImportMap::default(); @@ -415,9 +415,9 @@ impl ModuleOptions { .context("execution_context is required for the postcss_transform")?; let import_map = if let Some(postcss_package) = options.postcss_package { - package_import_map_from_import_mapping("postcss".to_string(), postcss_package) + package_import_map_from_import_mapping("postcss".into(), postcss_package) } else { - package_import_map_from_context("postcss".to_string(), path) + package_import_map_from_context("postcss".into(), path) }; rules.push(ModuleRule::new( @@ -428,7 +428,7 @@ impl ModuleOptions { execution_context, Some(import_map), None, - "postcss".to_string(), + "postcss".into(), ), execution_context, options.config_location, @@ -542,11 +542,11 @@ impl ModuleOptions { webpack_loaders_options.loader_runner_package { package_import_map_from_import_mapping( - "loader-runner".to_string(), + "loader-runner".into(), loader_runner_package, ) } else { - package_import_map_from_context("loader-runner".to_string(), path) + package_import_map_from_context("loader-runner".into(), path) }; for (glob, rule) in webpack_loaders_options.rules.await?.iter() { rules.push(ModuleRule::new( @@ -576,7 +576,7 @@ impl ModuleOptions { execution_context, Some(import_map), None, - "webpack_loaders".to_string(), + "webpack_loaders".into(), ), execution_context, rule.loaders, diff --git a/crates/turbopack/src/module_options/module_options_context.rs b/crates/turbopack/src/module_options/module_options_context.rs index f8b4e6b841dab..0b4121f69cc6a 100644 --- a/crates/turbopack/src/module_options/module_options_context.rs +++ b/crates/turbopack/src/module_options/module_options_context.rs @@ -1,6 +1,6 @@ use indexmap::IndexMap; use serde::{Deserialize, Serialize}; -use turbo_tasks::{trace::TraceRawVcs, ValueDefault, Vc}; +use turbo_tasks::{trace::TraceRawVcs, RcStr, ValueDefault, Vc}; use turbopack_core::{ condition::ContextCondition, environment::Environment, resolve::options::ImportMapping, }; @@ -16,12 +16,12 @@ use super::ModuleRule; #[derive(Clone, PartialEq, Eq, Debug, TraceRawVcs, Serialize, Deserialize)] pub struct LoaderRuleItem { pub loaders: Vc, - pub rename_as: Option, + pub rename_as: Option, } #[derive(Default)] #[turbo_tasks::value(transparent)] -pub struct WebpackRules(IndexMap); +pub struct WebpackRules(IndexMap); #[derive(Default)] #[turbo_tasks::value(transparent)] @@ -104,8 +104,8 @@ impl ValueDefault for TypescriptTransformOptions { pub struct JsxTransformOptions { pub development: bool, pub react_refresh: bool, - pub import_source: Option, - pub runtime: Option, + pub import_source: Option, + pub runtime: Option, } #[turbo_tasks::value(shared)] @@ -151,7 +151,7 @@ pub struct ModuleOptionsContext { pub use_swc_css: bool, - pub side_effect_free_packages: Vec, + pub side_effect_free_packages: Vec, } #[turbo_tasks::value_impl] diff --git a/crates/turbopack/src/transition/context_transition.rs b/crates/turbopack/src/transition/context_transition.rs index 41606c246387b..a69ebfab68857 100644 --- a/crates/turbopack/src/transition/context_transition.rs +++ b/crates/turbopack/src/transition/context_transition.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use turbo_tasks::Vc; +use turbo_tasks::{RcStr, Vc}; use turbopack_core::compile_time_info::CompileTimeInfo; use turbopack_resolve::resolve_options_context::ResolveOptionsContext; @@ -11,7 +11,7 @@ pub struct ContextTransition { compile_time_info: Vc, module_options_context: Vc, resolve_options_context: Vc, - layer: Vc, + layer: Vc, } #[turbo_tasks::value_impl] @@ -21,7 +21,7 @@ impl ContextTransition { compile_time_info: Vc, module_options_context: Vc, resolve_options_context: Vc, - layer: Vc, + layer: Vc, ) -> Result> { Ok(ContextTransition { module_options_context, @@ -44,7 +44,7 @@ impl Transition for ContextTransition { } #[turbo_tasks::function] - fn process_layer(&self, _layer: Vc) -> Vc { + fn process_layer(&self, _layer: Vc) -> Vc { self.layer } diff --git a/crates/turbopack/src/transition/mod.rs b/crates/turbopack/src/transition/mod.rs index 1a84e66fca005..9540e365d362c 100644 --- a/crates/turbopack/src/transition/mod.rs +++ b/crates/turbopack/src/transition/mod.rs @@ -6,7 +6,7 @@ use std::collections::HashMap; use anyhow::Result; pub use context_transition::ContextTransition; pub use full_context_transition::FullContextTransition; -use turbo_tasks::{Value, ValueDefault, Vc}; +use turbo_tasks::{RcStr, Value, ValueDefault, Vc}; use turbopack_core::{ compile_time_info::CompileTimeInfo, context::ProcessResult, module::Module, reference_type::ReferenceType, source::Source, @@ -32,7 +32,7 @@ pub trait Transition { compile_time_info } /// Apply modifications to the layer - fn process_layer(self: Vc, layer: Vc) -> Vc { + fn process_layer(self: Vc, layer: Vc) -> Vc { layer } /// Apply modifications/wrapping to the module options context @@ -100,7 +100,7 @@ pub trait Transition { } #[turbo_tasks::value(transparent)] -pub struct TransitionsByName(HashMap>>); +pub struct TransitionsByName(HashMap>>); #[turbo_tasks::value_impl] impl ValueDefault for TransitionsByName { diff --git a/crates/turbopack/src/unsupported_sass.rs b/crates/turbopack/src/unsupported_sass.rs index 71d496cbaed34..52ead7bfe6d7a 100644 --- a/crates/turbopack/src/unsupported_sass.rs +++ b/crates/turbopack/src/unsupported_sass.rs @@ -31,10 +31,7 @@ impl UnsupportedSassResolvePlugin { impl AfterResolvePlugin for UnsupportedSassResolvePlugin { #[turbo_tasks::function] fn after_resolve_condition(&self) -> Vc { - AfterResolvePluginCondition::new( - self.root.root(), - Glob::new("**/*.{sass,scss}".to_string()), - ) + AfterResolvePluginCondition::new(self.root.root(), Glob::new("**/*.{sass,scss}".into())) } #[turbo_tasks::function] @@ -46,7 +43,7 @@ impl AfterResolvePlugin for UnsupportedSassResolvePlugin { request: Vc, ) -> Result> { let extension = fs_path.extension().await?; - if ["sass", "scss"].iter().any(|ext| ext == &*extension) { + if ["sass", "scss"].iter().any(|ext| *ext == &**extension) { UnsupportedSassModuleIssue { file_path: lookup_path, request, @@ -74,10 +71,13 @@ impl Issue for UnsupportedSassModuleIssue { #[turbo_tasks::function] async fn title(&self) -> Result> { - Ok(StyledString::Text(format!( - "Unsupported Sass request: {}", - self.request.await?.request().as_deref().unwrap_or("N/A") - )) + Ok(StyledString::Text( + format!( + "Unsupported Sass request: {}", + self.request.await?.request().as_deref().unwrap_or("N/A") + ) + .into(), + ) .cell()) } @@ -89,10 +89,8 @@ impl Issue for UnsupportedSassModuleIssue { #[turbo_tasks::function] fn description(&self) -> Vc { Vc::cell(Some( - StyledString::Text( - "Turbopack does not yet support importing Sass modules.".to_string(), - ) - .cell(), + StyledString::Text("Turbopack does not yet support importing Sass modules.".into()) + .cell(), )) } diff --git a/crates/turbopack/tests/node-file-trace.rs b/crates/turbopack/tests/node-file-trace.rs index 5bda21adb9016..ad4f2c3e000df 100644 --- a/crates/turbopack/tests/node-file-trace.rs +++ b/crates/turbopack/tests/node-file-trace.rs @@ -28,7 +28,7 @@ use rstest_reuse::{ }; use serde::{Deserialize, Serialize}; use tokio::{process::Command, time::timeout}; -use turbo_tasks::{backend::Backend, ReadRef, TurboTasks, Value, ValueToString, Vc}; +use turbo_tasks::{backend::Backend, RcStr, ReadRef, TurboTasks, Value, ValueToString, Vc}; use turbo_tasks_fs::{DiskFileSystem, FileSystem, FileSystemPath}; use turbo_tasks_memory::MemoryBackend; use turbopack::{ @@ -374,10 +374,10 @@ fn node_file_trace( let package_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let mut tests_output_root = temp_dir(); tests_output_root.push("tests_output"); - let package_root = package_root.to_string_lossy().to_string(); - let input = format!("node-file-trace/{input_path}"); + let package_root: RcStr = package_root.to_string_lossy().into(); + let input: RcStr = format!("node-file-trace/{input_path}").into(); let directory_path = tests_output_root.join(format!("{mode}_{input}")); - let directory = directory_path.to_string_lossy().to_string(); + let directory: RcStr = directory_path.to_string_lossy().into(); remove_dir_all(&directory) .or_else(|err| { @@ -403,18 +403,17 @@ fn node_file_trace( #[cfg(feature = "bench_against_node_nft")] let before_start = Instant::now(); let workspace_fs: Vc> = Vc::upcast(DiskFileSystem::new( - "workspace".to_string(), + "workspace".into(), package_root.clone(), vec![], )); let input_dir = workspace_fs.root(); - let input = input_dir.join(format!("tests/{input_string}")); + let input = input_dir.join(format!("tests/{input_string}").into()); #[cfg(not(feature = "bench_against_node_nft"))] let original_output = exec_node(package_root, input); - let output_fs = - DiskFileSystem::new("output".to_string(), directory.clone(), vec![]); + let output_fs = DiskFileSystem::new("output".into(), directory.clone(), vec![]); let output_dir = output_fs.root(); let source = FileSource::new(input); @@ -435,11 +434,11 @@ fn node_file_trace( ResolveOptionsContext { enable_node_native_modules: true, enable_node_modules: Some(input_dir), - custom_conditions: vec!["node".to_string()], + custom_conditions: vec!["node".into()], ..Default::default() } .cell(), - Vc::cell("test".to_string()), + Vc::cell("test".into()), ); let module = module_asset_context .process(Vc::upcast(source), Value::new(ReferenceType::Undefined)) @@ -456,7 +455,8 @@ fn node_file_trace( #[cfg(not(feature = "bench_against_node_nft"))] { let output = exec_node(directory.clone(), output_path); - let output = assert_output(original_output, output, expected_stderr); + let output = + assert_output(original_output, output, expected_stderr.map(From::from)); output.await } #[cfg(feature = "bench_against_node_nft")] @@ -574,7 +574,7 @@ impl Display for CommandOutput { } #[turbo_tasks::function] -async fn exec_node(directory: String, path: Vc) -> Result> { +async fn exec_node(directory: RcStr, path: Vc) -> Result> { let mut cmd = Command::new("node"); let p = path.await?; @@ -673,15 +673,15 @@ fn diff(expected: &str, actual: &str) -> String { async fn assert_output( expected: Vc, actual: Vc, - expected_stderr: Option, + expected_stderr: Option, ) -> Result> { let expected = expected.await?; let actual = actual.await?; Ok(CommandOutput::cell(CommandOutput { stdout: diff(&expected.stdout, &actual.stdout), stderr: if let Some(expected_stderr) = expected_stderr { - if actual.stderr.contains(&expected_stderr) - && expected.stderr.contains(&expected_stderr) + if actual.stderr.contains(&*expected_stderr) + && expected.stderr.contains(&*expected_stderr) { String::new() } else {