Unverified Commit e814d045 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

[Turbopack] use FxHasher for IndexMap/Set and DashMap (#71251)

### What?

* introduce and use use FxIndexMap and FxIndexSet everywhere instead of
IndexMaps
* use FxHashing in DashMaps
parent 402edf9f
...@@ -9232,6 +9232,7 @@ dependencies = [ ...@@ -9232,6 +9232,7 @@ dependencies = [
"postcard", "postcard",
"rayon", "rayon",
"rustc-demangle", "rustc-demangle",
"rustc-hash",
"serde", "serde",
"serde_json", "serde_json",
"tungstenite 0.21.0", "tungstenite 0.21.0",
......
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use indexmap::{indexset, IndexMap, IndexSet};
use next_core::{ use next_core::{
all_assets_from_entries, all_assets_from_entries,
app_segment_config::NextSegmentConfig, app_segment_config::NextSegmentConfig,
...@@ -39,7 +38,8 @@ use next_core::{ ...@@ -39,7 +38,8 @@ use next_core::{
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::Instrument; use tracing::Instrument;
use turbo_tasks::{ use turbo_tasks::{
trace::TraceRawVcs, Completion, RcStr, TryJoinIterExt, Value, ValueToString, Vc, fxindexset, trace::TraceRawVcs, Completion, FxIndexMap, FxIndexSet, RcStr, TryJoinIterExt,
Value, ValueToString, Vc,
}; };
use turbo_tasks_env::{CustomProcessEnv, ProcessEnv}; use turbo_tasks_env::{CustomProcessEnv, ProcessEnv};
use turbo_tasks_fs::{File, FileContent, FileSystemPath}; use turbo_tasks_fs::{File, FileContent, FileSystemPath};
...@@ -831,8 +831,8 @@ impl AppEndpoint { ...@@ -831,8 +831,8 @@ impl AppEndpoint {
let server_path = node_root.join("server".into()); let server_path = node_root.join("server".into());
let mut server_assets = indexset![]; let mut server_assets = fxindexset![];
let mut client_assets = indexset![]; let mut client_assets = fxindexset![];
// assets to add to the middleware manifest (to be loaded in the edge runtime). // assets to add to the middleware manifest (to be loaded in the edge runtime).
let mut middleware_assets = vec![]; let mut middleware_assets = vec![];
...@@ -909,7 +909,7 @@ impl AppEndpoint { ...@@ -909,7 +909,7 @@ impl AppEndpoint {
}; };
let client_dynamic_imports = { let client_dynamic_imports = {
let mut client_dynamic_imports = IndexMap::new(); let mut client_dynamic_imports = FxIndexMap::default();
let mut visited_modules = VisitedDynamicImportModules::empty(); let mut visited_modules = VisitedDynamicImportModules::empty();
for refs in client_references for refs in client_references
...@@ -942,9 +942,9 @@ impl AppEndpoint { ...@@ -942,9 +942,9 @@ impl AppEndpoint {
); );
let client_references_chunks_ref = client_references_chunks.await?; let client_references_chunks_ref = client_references_chunks.await?;
let mut entry_client_chunks = IndexSet::new(); let mut entry_client_chunks = FxIndexSet::default();
// TODO(alexkirsz) In which manifest does this go? // TODO(alexkirsz) In which manifest does this go?
let mut entry_ssr_chunks = IndexSet::new(); let mut entry_ssr_chunks = FxIndexSet::default();
for chunks in client_references_chunks_ref for chunks in client_references_chunks_ref
.layout_segment_client_chunks .layout_segment_client_chunks
.values() .values()
......
...@@ -2,7 +2,6 @@ use std::collections::{HashMap, HashSet}; ...@@ -2,7 +2,6 @@ use std::collections::{HashMap, HashSet};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use futures::Future; use futures::Future;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc_core::ecma::{ use swc_core::ecma::{
ast::{CallExpr, Callee, Expr, Ident, Lit}, ast::{CallExpr, Callee, Expr, Ident, Lit},
...@@ -12,7 +11,7 @@ use tracing::{Instrument, Level}; ...@@ -12,7 +11,7 @@ use tracing::{Instrument, Level};
use turbo_tasks::{ use turbo_tasks::{
graph::{GraphTraversal, NonDeterministic, VisitControlFlow, VisitedNodes}, graph::{GraphTraversal, NonDeterministic, VisitControlFlow, VisitedNodes},
trace::TraceRawVcs, trace::TraceRawVcs,
RcStr, ReadRef, TryJoinIterExt, Value, ValueToString, Vc, FxIndexMap, RcStr, ReadRef, TryJoinIterExt, Value, ValueToString, Vc,
}; };
use turbopack_core::{ use turbopack_core::{
chunk::{ chunk::{
...@@ -29,7 +28,7 @@ use turbopack_core::{ ...@@ -29,7 +28,7 @@ use turbopack_core::{
use turbopack_ecmascript::{parse::ParseResult, resolve::esm_resolve, EcmascriptParsable}; use turbopack_ecmascript::{parse::ParseResult, resolve::esm_resolve, EcmascriptParsable};
async fn collect_chunk_group_inner<F, Fu>( async fn collect_chunk_group_inner<F, Fu>(
dynamic_import_entries: IndexMap<Vc<Box<dyn Module>>, DynamicImportedModules>, dynamic_import_entries: FxIndexMap<Vc<Box<dyn Module>>, DynamicImportedModules>,
mut build_chunk: F, mut build_chunk: F,
) -> Result<Vc<DynamicImportedChunks>> ) -> Result<Vc<DynamicImportedChunks>>
where where
...@@ -37,7 +36,7 @@ where ...@@ -37,7 +36,7 @@ where
Fu: Future<Output = Result<Vc<OutputAssets>>> + Send, Fu: Future<Output = Result<Vc<OutputAssets>>> + Send,
{ {
let mut chunks_hash: HashMap<RcStr, Vc<OutputAssets>> = HashMap::new(); let mut chunks_hash: HashMap<RcStr, Vc<OutputAssets>> = HashMap::new();
let mut dynamic_import_chunks = IndexMap::new(); let mut dynamic_import_chunks = FxIndexMap::default();
// Iterate over the collected import mappings, and create a chunk for each // Iterate over the collected import mappings, and create a chunk for each
// dynamic import. // dynamic import.
...@@ -75,7 +74,7 @@ where ...@@ -75,7 +74,7 @@ where
pub(crate) async fn collect_chunk_group( pub(crate) async fn collect_chunk_group(
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
dynamic_import_entries: IndexMap<Vc<Box<dyn Module>>, DynamicImportedModules>, dynamic_import_entries: FxIndexMap<Vc<Box<dyn Module>>, DynamicImportedModules>,
availability_info: Value<AvailabilityInfo>, availability_info: Value<AvailabilityInfo>,
) -> Result<Vc<DynamicImportedChunks>> { ) -> Result<Vc<DynamicImportedChunks>> {
collect_chunk_group_inner(dynamic_import_entries, |module| async move { collect_chunk_group_inner(dynamic_import_entries, |module| async move {
...@@ -86,7 +85,7 @@ pub(crate) async fn collect_chunk_group( ...@@ -86,7 +85,7 @@ pub(crate) async fn collect_chunk_group(
pub(crate) async fn collect_evaluated_chunk_group( pub(crate) async fn collect_evaluated_chunk_group(
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
dynamic_import_entries: IndexMap<Vc<Box<dyn Module>>, DynamicImportedModules>, dynamic_import_entries: FxIndexMap<Vc<Box<dyn Module>>, DynamicImportedModules>,
) -> Result<Vc<DynamicImportedChunks>> { ) -> Result<Vc<DynamicImportedChunks>> {
collect_chunk_group_inner(dynamic_import_entries, |module| async move { collect_chunk_group_inner(dynamic_import_entries, |module| async move {
if let Some(module) = Vc::try_resolve_downcast::<Box<dyn EvaluatableAsset>>(module).await? { if let Some(module) = Vc::try_resolve_downcast::<Box<dyn EvaluatableAsset>>(module).await? {
...@@ -104,7 +103,7 @@ pub(crate) async fn collect_evaluated_chunk_group( ...@@ -104,7 +103,7 @@ pub(crate) async fn collect_evaluated_chunk_group(
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub struct NextDynamicImportsResult { pub struct NextDynamicImportsResult {
pub client_dynamic_imports: IndexMap<Vc<Box<dyn Module>>, DynamicImportedModules>, pub client_dynamic_imports: FxIndexMap<Vc<Box<dyn Module>>, DynamicImportedModules>,
pub visited_modules: Vc<VisitedDynamicImportModules>, pub visited_modules: Vc<VisitedDynamicImportModules>,
} }
...@@ -187,8 +186,8 @@ pub(crate) async fn collect_next_dynamic_imports( ...@@ -187,8 +186,8 @@ pub(crate) async fn collect_next_dynamic_imports(
}); });
// Consolidate import mappings into a single indexmap // Consolidate import mappings into a single indexmap
let mut import_mappings: IndexMap<Vc<Box<dyn Module>>, DynamicImportedModules> = let mut import_mappings: FxIndexMap<Vc<Box<dyn Module>>, DynamicImportedModules> =
IndexMap::new(); FxIndexMap::default();
for module_mapping in imported_modules_mapping { for module_mapping in imported_modules_mapping {
let (origin_module, dynamic_imports) = &*module_mapping.await?; let (origin_module, dynamic_imports) = &*module_mapping.await?;
...@@ -423,4 +422,4 @@ pub struct DynamicImportsMap(pub (Vc<Box<dyn Module>>, DynamicImportedModules)); ...@@ -423,4 +422,4 @@ pub struct DynamicImportsMap(pub (Vc<Box<dyn Module>>, DynamicImportedModules));
pub struct OptionDynamicImportsMap(Option<Vc<DynamicImportsMap>>); pub struct OptionDynamicImportsMap(Option<Vc<DynamicImportsMap>>);
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct DynamicImportedChunks(pub IndexMap<Vc<Box<dyn Module>>, DynamicImportedOutputAssets>); pub struct DynamicImportedChunks(pub FxIndexMap<Vc<Box<dyn Module>>, DynamicImportedOutputAssets>);
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, RcStr, Vc};
use turbo_tasks::{RcStr, Vc};
use crate::{ use crate::{
project::{Instrumentation, Middleware}, project::{Instrumentation, Middleware},
...@@ -8,7 +7,7 @@ use crate::{ ...@@ -8,7 +7,7 @@ use crate::{
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub struct Entrypoints { pub struct Entrypoints {
pub routes: IndexMap<RcStr, Route>, pub routes: FxIndexMap<RcStr, Route>,
pub middleware: Option<Middleware>, pub middleware: Option<Middleware>,
pub instrumentation: Option<Instrumentation>, pub instrumentation: Option<Instrumentation>,
pub pages_document_endpoint: Vc<Box<dyn Endpoint>>, pub pages_document_endpoint: Vc<Box<dyn Endpoint>>,
......
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use indexmap::IndexMap;
use next_core::{ use next_core::{
all_assets_from_entries, create_page_loader_entry_module, get_asset_path_from_pathname, all_assets_from_entries, create_page_loader_entry_module, get_asset_path_from_pathname,
get_edge_resolve_options_context, get_edge_resolve_options_context,
...@@ -28,7 +27,9 @@ use next_core::{ ...@@ -28,7 +27,9 @@ use next_core::{
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::Instrument; use tracing::Instrument;
use turbo_tasks::{trace::TraceRawVcs, Completion, RcStr, TaskInput, TryJoinIterExt, Value, Vc}; use turbo_tasks::{
trace::TraceRawVcs, Completion, FxIndexMap, RcStr, TaskInput, TryJoinIterExt, Value, Vc,
};
use turbo_tasks_fs::{ use turbo_tasks_fs::{
self, File, FileContent, FileSystem, FileSystemPath, FileSystemPathOption, VirtualFileSystem, self, File, FileContent, FileSystem, FileSystemPath, FileSystemPathOption, VirtualFileSystem,
}; };
...@@ -95,10 +96,10 @@ impl PagesProject { ...@@ -95,10 +96,10 @@ impl PagesProject {
document: _, document: _,
error: _, error: _,
} = &*pages_structure.await?; } = &*pages_structure.await?;
let mut routes = IndexMap::new(); let mut routes = FxIndexMap::default();
async fn add_page_to_routes( async fn add_page_to_routes(
routes: &mut IndexMap<RcStr, Route>, routes: &mut FxIndexMap<RcStr, Route>,
page: Vc<PagesStructureItem>, page: Vc<PagesStructureItem>,
make_route: impl Fn(Vc<RcStr>, Vc<RcStr>, Vc<PagesStructureItem>) -> Route, make_route: impl Fn(Vc<RcStr>, Vc<RcStr>, Vc<PagesStructureItem>) -> Route,
) -> Result<()> { ) -> Result<()> {
...@@ -116,7 +117,7 @@ impl PagesProject { ...@@ -116,7 +117,7 @@ impl PagesProject {
} }
async fn add_dir_to_routes( async fn add_dir_to_routes(
routes: &mut IndexMap<RcStr, Route>, routes: &mut FxIndexMap<RcStr, Route>,
dir: Vc<PagesDirectoryStructure>, dir: Vc<PagesDirectoryStructure>,
make_route: impl Fn(Vc<RcStr>, Vc<RcStr>, Vc<PagesStructureItem>) -> Route, make_route: impl Fn(Vc<RcStr>, Vc<RcStr>, Vc<PagesStructureItem>) -> Route,
) -> Result<()> { ) -> Result<()> {
......
use std::{path::MAIN_SEPARATOR, time::Duration}; use std::{path::MAIN_SEPARATOR, time::Duration};
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use indexmap::{indexmap, map::Entry, IndexMap}; use indexmap::map::Entry;
use next_core::{ use next_core::{
all_assets_from_entries, all_assets_from_entries,
app_structure::find_app_dir, app_structure::find_app_dir,
...@@ -24,10 +24,11 @@ use serde::{Deserialize, Serialize}; ...@@ -24,10 +24,11 @@ use serde::{Deserialize, Serialize};
use tracing::Instrument; use tracing::Instrument;
use turbo_tasks::{ use turbo_tasks::{
debug::ValueDebugFormat, debug::ValueDebugFormat,
fxindexmap,
graph::{AdjacencyMap, GraphTraversal}, graph::{AdjacencyMap, GraphTraversal},
trace::TraceRawVcs, trace::TraceRawVcs,
Completion, Completions, IntoTraitRef, RcStr, ReadRef, State, TaskInput, TransientInstance, Completion, Completions, FxIndexMap, IntoTraitRef, RcStr, ReadRef, State, TaskInput,
TryFlatJoinIterExt, Value, Vc, TransientInstance, TryFlatJoinIterExt, Value, Vc,
}; };
use turbo_tasks_env::{EnvMap, ProcessEnv}; use turbo_tasks_env::{EnvMap, ProcessEnv};
use turbo_tasks_fs::{DiskFileSystem, FileSystem, FileSystemPath, VirtualFileSystem}; use turbo_tasks_fs::{DiskFileSystem, FileSystem, FileSystemPath, VirtualFileSystem};
...@@ -679,7 +680,7 @@ impl Project { ...@@ -679,7 +680,7 @@ impl Project {
#[turbo_tasks::function] #[turbo_tasks::function]
pub(super) fn edge_env(&self) -> Vc<EnvMap> { pub(super) fn edge_env(&self) -> Vc<EnvMap> {
let edge_env = indexmap! { let edge_env = fxindexmap! {
"__NEXT_BUILD_ID".into() => self.build_id.clone(), "__NEXT_BUILD_ID".into() => self.build_id.clone(),
"NEXT_SERVER_ACTIONS_ENCRYPTION_KEY".into() => self.encryption_key.clone(), "NEXT_SERVER_ACTIONS_ENCRYPTION_KEY".into() => self.encryption_key.clone(),
"__NEXT_PREVIEW_MODE_ID".into() => self.preview_props.preview_mode_id.clone(), "__NEXT_PREVIEW_MODE_ID".into() => self.preview_props.preview_mode_id.clone(),
...@@ -835,7 +836,7 @@ impl Project { ...@@ -835,7 +836,7 @@ impl Project {
pub async fn entrypoints(self: Vc<Self>) -> Result<Vc<Entrypoints>> { pub async fn entrypoints(self: Vc<Self>) -> Result<Vc<Entrypoints>> {
self.collect_project_feature_telemetry().await?; self.collect_project_feature_telemetry().await?;
let mut routes = IndexMap::new(); let mut routes = FxIndexMap::default();
let app_project = self.app_project(); let app_project = self.app_project();
let pages_project = self.pages_project(); let pages_project = self.pages_project();
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, Completion, RcStr, Vc}; use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, Completion, FxIndexMap, RcStr, Vc};
use turbopack_core::module::Modules; use turbopack_core::module::Modules;
use crate::paths::ServerPath; use crate::paths::ServerPath;
...@@ -97,4 +96,4 @@ pub enum WrittenEndpoint { ...@@ -97,4 +96,4 @@ pub enum WrittenEndpoint {
/// The routes as map from pathname to route. (pathname includes the leading /// The routes as map from pathname to route. (pathname includes the leading
/// slash) /// slash)
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct Routes(IndexMap<RcStr, Route>); pub struct Routes(FxIndexMap<RcStr, Route>);
use std::{collections::BTreeMap, io::Write, iter::once}; use std::{collections::BTreeMap, io::Write, iter::once};
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use indexmap::{map::Entry, IndexMap}; use indexmap::map::Entry;
use next_core::{ use next_core::{
next_manifests::{ActionLayer, ActionManifestWorkerEntry, ServerReferenceManifest}, next_manifests::{ActionLayer, ActionManifestWorkerEntry, ServerReferenceManifest},
util::NextRuntime, util::NextRuntime,
...@@ -17,7 +17,7 @@ use swc_core::{ ...@@ -17,7 +17,7 @@ use swc_core::{
use tracing::Instrument; use tracing::Instrument;
use turbo_tasks::{ use turbo_tasks::{
graph::{GraphTraversal, NonDeterministic}, graph::{GraphTraversal, NonDeterministic},
RcStr, TryFlatJoinIterExt, Value, ValueToString, Vc, FxIndexMap, RcStr, TryFlatJoinIterExt, Value, ValueToString, Vc,
}; };
use turbo_tasks_fs::{self, rope::RopeBuilder, File, FileSystemPath}; use turbo_tasks_fs::{self, rope::RopeBuilder, File, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
...@@ -90,7 +90,7 @@ async fn build_server_actions_loader( ...@@ -90,7 +90,7 @@ async fn build_server_actions_loader(
// which lazily imports the respective module's chunk_item id and invokes // which lazily imports the respective module's chunk_item id and invokes
// the exported action function. // the exported action function.
let mut contents = RopeBuilder::from("__turbopack_export_value__({\n"); let mut contents = RopeBuilder::from("__turbopack_export_value__({\n");
let mut import_map = IndexMap::new(); let mut import_map = FxIndexMap::default();
for (hash_id, (_layer, name, module)) in actions.iter() { for (hash_id, (_layer, name, module)) in actions.iter() {
let index = import_map.len(); let index = import_map.len();
let module_name = import_map let module_name = import_map
...@@ -197,7 +197,7 @@ async fn get_actions( ...@@ -197,7 +197,7 @@ async fn get_actions(
// Actions can be imported by both Client and RSC layers, in which case we need // Actions can be imported by both Client and RSC layers, in which case we need
// to use the RSC layer's module. We do that by merging the hashes (which match // to use the RSC layer's module. We do that by merging the hashes (which match
// in both layers) and preferring the RSC layer's action. // in both layers) and preferring the RSC layer's action.
let mut all_actions: HashToLayerNameModule = IndexMap::new(); let mut all_actions: HashToLayerNameModule = FxIndexMap::default();
for ((layer, module), actions_map) in actions.iter() { for ((layer, module), actions_map) in actions.iter() {
let module = if *layer == ActionLayer::Rsc { let module = if *layer == ActionLayer::Rsc {
*module *module
...@@ -332,7 +332,7 @@ async fn parse_actions(module: Vc<Box<dyn Module>>) -> Result<Vc<OptionActionMap ...@@ -332,7 +332,7 @@ async fn parse_actions(module: Vc<Box<dyn Module>>) -> Result<Vc<OptionActionMap
actions.retain(|_, name| all_exports.iter().any(|export| export == name)); actions.retain(|_, name| all_exports.iter().any(|export| export == name));
} }
let mut actions = IndexMap::from_iter(actions.into_iter()); let mut actions = FxIndexMap::from_iter(actions.into_iter());
actions.sort_keys(); actions.sort_keys();
Ok(Vc::cell(Some(Vc::cell(actions)))) Ok(Vc::cell(Some(Vc::cell(actions))))
} }
...@@ -396,7 +396,7 @@ fn all_export_names(program: &Program) -> Vec<Atom> { ...@@ -396,7 +396,7 @@ fn all_export_names(program: &Program) -> Vec<Atom> {
} }
/// Converts our cached [parse_actions] call into a data type suitable for /// Converts our cached [parse_actions] call into a data type suitable for
/// collecting into a flat-mapped [IndexMap]. /// collecting into a flat-mapped [FxIndexMap].
async fn parse_actions_filter_map( async fn parse_actions_filter_map(
(layer, module): (ActionLayer, Vc<Box<dyn Module>>), (layer, module): (ActionLayer, Vc<Box<dyn Module>>),
) -> Result<Option<((ActionLayer, Vc<Box<dyn Module>>), Vc<ActionMap>)>> { ) -> Result<Option<((ActionLayer, Vc<Box<dyn Module>>), Vc<ActionMap>)>> {
...@@ -407,7 +407,7 @@ async fn parse_actions_filter_map( ...@@ -407,7 +407,7 @@ async fn parse_actions_filter_map(
}) })
} }
type HashToLayerNameModule = IndexMap<String, (ActionLayer, String, Vc<Box<dyn Module>>)>; type HashToLayerNameModule = FxIndexMap<String, (ActionLayer, String, Vc<Box<dyn Module>>)>;
/// A mapping of every module which exports a Server Action, with the hashed id /// A mapping of every module which exports a Server Action, with the hashed id
/// and exported name of each found action. /// and exported name of each found action.
...@@ -418,13 +418,13 @@ struct AllActions(HashToLayerNameModule); ...@@ -418,13 +418,13 @@ struct AllActions(HashToLayerNameModule);
impl AllActions { impl AllActions {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn empty() -> Vc<Self> { pub fn empty() -> Vc<Self> {
Vc::cell(IndexMap::new()) Vc::cell(FxIndexMap::default())
} }
} }
/// Maps the hashed action id to the action's exported function name. /// Maps the hashed action id to the action's exported function name.
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
struct ActionMap(IndexMap<String, String>); struct ActionMap(FxIndexMap<String, String>);
/// An Option wrapper around [ActionMap]. /// An Option wrapper around [ActionMap].
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
......
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::IndexSet;
use next_core::emit_assets; use next_core::emit_assets;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{ use turbo_tasks::{
debug::ValueDebugFormat, trace::TraceRawVcs, Completion, RcStr, State, TryFlatJoinIterExt, debug::ValueDebugFormat, trace::TraceRawVcs, Completion, FxIndexSet, RcStr, State,
TryJoinIterExt, ValueDefault, ValueToString, Vc, TryFlatJoinIterExt, TryJoinIterExt, ValueDefault, ValueToString, Vc,
}; };
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{ use turbopack_core::{
...@@ -33,13 +32,13 @@ struct MapEntry { ...@@ -33,13 +32,13 @@ struct MapEntry {
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
struct OptionMapEntry(Option<MapEntry>); struct OptionMapEntry(Option<MapEntry>);
type PathToOutputOperation = HashMap<Vc<FileSystemPath>, IndexSet<Vc<OutputAssets>>>; type PathToOutputOperation = HashMap<Vc<FileSystemPath>, FxIndexSet<Vc<OutputAssets>>>;
// A precomputed map for quick access to output asset by filepath // A precomputed map for quick access to output asset by filepath
type OutputOperationToComputeEntry = HashMap<Vc<OutputAssets>, Vc<OptionMapEntry>>; type OutputOperationToComputeEntry = HashMap<Vc<OutputAssets>, Vc<OptionMapEntry>>;
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct VersionedContentMap { pub struct VersionedContentMap {
// TODO: turn into a bi-directional multimap, OutputAssets -> IndexSet<FileSystemPath> // TODO: turn into a bi-directional multimap, OutputAssets -> FxIndexSet<FileSystemPath>
map_path_to_op: State<PathToOutputOperation>, map_path_to_op: State<PathToOutputOperation>,
map_op_to_compute_entry: State<OutputOperationToComputeEntry>, map_op_to_compute_entry: State<OutputOperationToComputeEntry>,
} }
......
use anyhow::Result; use anyhow::Result;
use indexmap::{IndexMap, IndexSet};
use serde::Serialize; use serde::Serialize;
use turbo_tasks::{RcStr, Vc}; use turbo_tasks::{FxIndexMap, FxIndexSet, RcStr, Vc};
use turbopack_browser::ecmascript::EcmascriptDevChunk; use turbopack_browser::ecmascript::EcmascriptDevChunk;
use turbopack_core::{ use turbopack_core::{
chunk::{Chunk, ChunkItem}, chunk::{Chunk, ChunkItem},
...@@ -17,7 +16,8 @@ where ...@@ -17,7 +16,8 @@ where
{ {
let mut assets = vec![]; let mut assets = vec![];
let mut chunks = vec![]; let mut chunks = vec![];
let mut chunk_items: IndexMap<Vc<Box<dyn ChunkItem>>, IndexSet<RcStr>> = IndexMap::new(); let mut chunk_items: FxIndexMap<Vc<Box<dyn ChunkItem>>, FxIndexSet<RcStr>> =
FxIndexMap::default();
let mut modules = vec![]; let mut modules = vec![];
for asset in entry_assets { for asset in entry_assets {
let path = normalize_client_path(&asset.ident().path().await?.path); let path = normalize_client_path(&asset.ident().path().await?.path);
...@@ -64,7 +64,7 @@ where ...@@ -64,7 +64,7 @@ where
}); });
} }
let mut entrypoints = IndexMap::new(); let mut entrypoints = FxIndexMap::default();
entrypoints.insert( entrypoints.insert(
entry_name.clone(), entry_name.clone(),
WebpackStatsEntrypoint { WebpackStatsEntrypoint {
...@@ -150,7 +150,7 @@ pub struct WebpackStatsEntrypoint { ...@@ -150,7 +150,7 @@ pub struct WebpackStatsEntrypoint {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct WebpackStats { pub struct WebpackStats {
pub assets: Vec<WebpackStatsAsset>, pub assets: Vec<WebpackStatsAsset>,
pub entrypoints: IndexMap<RcStr, WebpackStatsEntrypoint>, pub entrypoints: FxIndexMap<RcStr, WebpackStatsEntrypoint>,
pub chunks: Vec<WebpackStatsChunk>, pub chunks: Vec<WebpackStatsChunk>,
pub modules: Vec<WebpackStatsModule>, pub modules: Vec<WebpackStatsModule>,
} }
...@@ -4,8 +4,7 @@ use std::{ ...@@ -4,8 +4,7 @@ use std::{
}; };
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, RcStr, Vc};
use turbo_tasks::{RcStr, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack::{transition::Transition, ModuleAssetContext}; use turbopack::{transition::Transition, ModuleAssetContext};
use turbopack_core::{file_source::FileSource, module::Module}; use turbopack_core::{file_source::FileSource, module::Module};
...@@ -389,7 +388,7 @@ impl AppPageLoaderTreeBuilder { ...@@ -389,7 +388,7 @@ impl AppPageLoaderTreeBuilder {
pub struct AppPageLoaderTreeModule { pub struct AppPageLoaderTreeModule {
pub imports: Vec<RcStr>, pub imports: Vec<RcStr>,
pub loader_tree_code: RcStr, pub loader_tree_code: RcStr,
pub inner_assets: IndexMap<RcStr, Vc<Box<dyn Module>>>, pub inner_assets: FxIndexMap<RcStr, Vc<Box<dyn Module>>>,
pub pages: Vec<Vc<FileSystemPath>>, pub pages: Vec<Vc<FileSystemPath>>,
} }
......
use std::collections::BTreeMap; use std::collections::BTreeMap;
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use indexmap::{ use indexmap::map::{Entry, OccupiedEntry};
indexmap,
map::{Entry, OccupiedEntry},
IndexMap,
};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::Instrument; use tracing::Instrument;
use turbo_tasks::{ use turbo_tasks::{
debug::ValueDebugFormat, trace::TraceRawVcs, RcStr, ResolvedVc, TaskInput, TryJoinIterExt, debug::ValueDebugFormat, fxindexmap, trace::TraceRawVcs, FxIndexMap, RcStr, ResolvedVc,
ValueDefault, ValueToString, Vc, TaskInput, TryJoinIterExt, ValueDefault, ValueToString, Vc,
}; };
use turbo_tasks_fs::{DirectoryContent, DirectoryEntry, FileSystemEntryType, FileSystemPath}; use turbo_tasks_fs::{DirectoryContent, DirectoryEntry, FileSystemEntryType, FileSystemPath};
use turbopack_core::issue::{ use turbopack_core::issue::{
...@@ -398,7 +394,7 @@ async fn get_directory_tree_internal( ...@@ -398,7 +394,7 @@ async fn get_directory_tree_internal(
pub struct AppPageLoaderTree { pub struct AppPageLoaderTree {
pub page: AppPage, pub page: AppPage,
pub segment: RcStr, pub segment: RcStr,
pub parallel_routes: IndexMap<RcStr, AppPageLoaderTree>, pub parallel_routes: FxIndexMap<RcStr, AppPageLoaderTree>,
pub modules: AppDirModules, pub modules: AppDirModules,
pub global_metadata: Vc<GlobalMetadata>, pub global_metadata: Vc<GlobalMetadata>,
} }
...@@ -517,7 +513,7 @@ impl Entrypoint { ...@@ -517,7 +513,7 @@ impl Entrypoint {
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct Entrypoints(IndexMap<AppPath, Entrypoint>); pub struct Entrypoints(FxIndexMap<AppPath, Entrypoint>);
fn is_parallel_route(name: &str) -> bool { fn is_parallel_route(name: &str) -> bool {
name.starts_with('@') name.starts_with('@')
...@@ -564,7 +560,7 @@ fn conflict_issue( ...@@ -564,7 +560,7 @@ fn conflict_issue(
fn add_app_page( fn add_app_page(
app_dir: Vc<FileSystemPath>, app_dir: Vc<FileSystemPath>,
result: &mut IndexMap<AppPath, Entrypoint>, result: &mut FxIndexMap<AppPath, Entrypoint>,
page: AppPage, page: AppPage,
loader_tree: ResolvedVc<AppPageLoaderTree>, loader_tree: ResolvedVc<AppPageLoaderTree>,
) { ) {
...@@ -623,7 +619,7 @@ fn add_app_page( ...@@ -623,7 +619,7 @@ fn add_app_page(
fn add_app_route( fn add_app_route(
app_dir: Vc<FileSystemPath>, app_dir: Vc<FileSystemPath>,
result: &mut IndexMap<AppPath, Entrypoint>, result: &mut FxIndexMap<AppPath, Entrypoint>,
page: AppPage, page: AppPage,
path: ResolvedVc<FileSystemPath>, path: ResolvedVc<FileSystemPath>,
root_layouts: ResolvedVc<FileSystemPathVec>, root_layouts: ResolvedVc<FileSystemPathVec>,
...@@ -666,7 +662,7 @@ fn add_app_route( ...@@ -666,7 +662,7 @@ fn add_app_route(
fn add_app_metadata_route( fn add_app_metadata_route(
app_dir: Vc<FileSystemPath>, app_dir: Vc<FileSystemPath>,
result: &mut IndexMap<AppPath, Entrypoint>, result: &mut FxIndexMap<AppPath, Entrypoint>,
page: AppPage, page: AppPage,
metadata: MetadataItem, metadata: MetadataItem,
) { ) {
...@@ -867,7 +863,7 @@ fn directory_tree_to_loader_tree_internal( ...@@ -867,7 +863,7 @@ fn directory_tree_to_loader_tree_internal(
let mut tree = AppPageLoaderTree { let mut tree = AppPageLoaderTree {
page: app_page.clone(), page: app_page.clone(),
segment: directory_name.clone(), segment: directory_name.clone(),
parallel_routes: IndexMap::new(), parallel_routes: FxIndexMap::default(),
modules: modules.without_leafs(), modules: modules.without_leafs(),
global_metadata, global_metadata,
}; };
...@@ -887,7 +883,7 @@ fn directory_tree_to_loader_tree_internal( ...@@ -887,7 +883,7 @@ fn directory_tree_to_loader_tree_internal(
AppPageLoaderTree { AppPageLoaderTree {
page: app_page.clone(), page: app_page.clone(),
segment: "__PAGE__".into(), segment: "__PAGE__".into(),
parallel_routes: IndexMap::new(), parallel_routes: FxIndexMap::default(),
modules: AppDirModules { modules: AppDirModules {
page: Some(page), page: Some(page),
metadata: modules.metadata, metadata: modules.metadata,
...@@ -1031,7 +1027,7 @@ fn default_route_tree( ...@@ -1031,7 +1027,7 @@ fn default_route_tree(
AppPageLoaderTree { AppPageLoaderTree {
page: app_page.clone(), page: app_page.clone(),
segment: "__DEFAULT__".into(), segment: "__DEFAULT__".into(),
parallel_routes: IndexMap::new(), parallel_routes: FxIndexMap::default(),
modules: if let Some(default) = default_component { modules: if let Some(default) = default_component {
AppDirModules { AppDirModules {
default: Some(default), default: Some(default),
...@@ -1081,7 +1077,7 @@ async fn directory_tree_to_entrypoints_internal_untraced( ...@@ -1081,7 +1077,7 @@ async fn directory_tree_to_entrypoints_internal_untraced(
app_page: AppPage, app_page: AppPage,
root_layouts: ResolvedVc<FileSystemPathVec>, root_layouts: ResolvedVc<FileSystemPathVec>,
) -> Result<Vc<Entrypoints>> { ) -> Result<Vc<Entrypoints>> {
let mut result = IndexMap::new(); let mut result = FxIndexMap::default();
let directory_tree_vc = directory_tree; let directory_tree_vc = directory_tree;
let directory_tree = &*directory_tree.await?; let directory_tree = &*directory_tree.await?;
...@@ -1184,15 +1180,15 @@ async fn directory_tree_to_entrypoints_internal_untraced( ...@@ -1184,15 +1180,15 @@ async fn directory_tree_to_entrypoints_internal_untraced(
let not_found_tree = AppPageLoaderTree { let not_found_tree = AppPageLoaderTree {
page: app_page.clone(), page: app_page.clone(),
segment: directory_name.clone(), segment: directory_name.clone(),
parallel_routes: indexmap! { parallel_routes: fxindexmap! {
"children".into() => AppPageLoaderTree { "children".into() => AppPageLoaderTree {
page: app_page.clone(), page: app_page.clone(),
segment: "/_not-found".into(), segment: "/_not-found".into(),
parallel_routes: indexmap! { parallel_routes: fxindexmap! {
"children".into() => AppPageLoaderTree { "children".into() => AppPageLoaderTree {
page: app_page.clone(), page: app_page.clone(),
segment: "__PAGE__".into(), segment: "__PAGE__".into(),
parallel_routes: IndexMap::new(), parallel_routes: FxIndexMap::default(),
modules: AppDirModules { modules: AppDirModules {
page: modules.not_found.or_else(|| Some(get_next_package(app_dir).join("dist/client/components/not-found-error.js".into()))), page: modules.not_found.or_else(|| Some(get_next_package(app_dir).join("dist/client/components/not-found-error.js".into()))),
..Default::default() ..Default::default()
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap;
use indoc::formatdoc; use indoc::formatdoc;
use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbo_tasks::{FxIndexMap, RcStr, Value, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack::{transition::Transition, ModuleAssetContext}; use turbopack::{transition::Transition, ModuleAssetContext};
use turbopack_core::{ use turbopack_core::{
...@@ -13,7 +12,7 @@ use turbopack_core::{ ...@@ -13,7 +12,7 @@ use turbopack_core::{
use turbopack_ecmascript::{magic_identifier, utils::StringifyJs}; use turbopack_ecmascript::{magic_identifier, utils::StringifyJs};
pub struct BaseLoaderTreeBuilder { pub struct BaseLoaderTreeBuilder {
pub inner_assets: IndexMap<RcStr, Vc<Box<dyn Module>>>, pub inner_assets: FxIndexMap<RcStr, Vc<Box<dyn Module>>>,
counter: usize, counter: usize,
pub imports: Vec<RcStr>, pub imports: Vec<RcStr>,
pub module_asset_context: Vc<ModuleAssetContext>, pub module_asset_context: Vc<ModuleAssetContext>,
...@@ -51,7 +50,7 @@ impl BaseLoaderTreeBuilder { ...@@ -51,7 +50,7 @@ impl BaseLoaderTreeBuilder {
server_component_transition: Vc<Box<dyn Transition>>, server_component_transition: Vc<Box<dyn Transition>>,
) -> Self { ) -> Self {
BaseLoaderTreeBuilder { BaseLoaderTreeBuilder {
inner_assets: IndexMap::new(), inner_assets: FxIndexMap::default(),
counter: 0, counter: 0,
imports: Vec::new(), imports: Vec::new(),
module_asset_context, module_asset_context,
......
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, Value, ValueToString, Vc};
use turbo_tasks::{Value, ValueToString, Vc};
use turbo_tasks_fs::{File, FileSystemPath}; use turbo_tasks_fs::{File, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
asset::AssetContent, asset::AssetContent,
...@@ -26,19 +25,19 @@ pub fn route_bootstrap( ...@@ -26,19 +25,19 @@ pub fn route_bootstrap(
asset_context, asset_context,
base_path, base_path,
bootstrap_asset, bootstrap_asset,
Vc::cell(IndexMap::new()), Vc::cell(FxIndexMap::default()),
config, config,
) )
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct BootstrapConfig(IndexMap<String, String>); pub struct BootstrapConfig(FxIndexMap<String, String>);
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl BootstrapConfig { impl BootstrapConfig {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn empty() -> Vc<Self> { pub fn empty() -> Vc<Self> {
Vc::cell(IndexMap::new()) Vc::cell(FxIndexMap::default())
} }
} }
......
use anyhow::Result; use anyhow::Result;
use indexmap::indexmap; use turbo_tasks::{fxindexmap, FxIndexMap, RcStr, Value, Vc};
use turbo_tasks::{RcStr, Value, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{context::AssetContext, module::Module, reference_type::ReferenceType}; use turbopack_core::{context::AssetContext, module::Module, reference_type::ReferenceType};
...@@ -33,16 +32,16 @@ pub async fn get_middleware_module( ...@@ -33,16 +32,16 @@ pub async fn get_middleware_module(
let source = load_next_js_template( let source = load_next_js_template(
"middleware.js", "middleware.js",
project_root, project_root,
indexmap! { fxindexmap! {
"VAR_USERLAND" => INNER.into(), "VAR_USERLAND" => INNER.into(),
"VAR_DEFINITION_PAGE" => "/middleware".into(), "VAR_DEFINITION_PAGE" => "/middleware".into(),
}, },
indexmap! {}, FxIndexMap::default(),
indexmap! {}, FxIndexMap::default(),
) )
.await?; .await?;
let inner_assets = indexmap! { let inner_assets = fxindexmap! {
INNER.into() => userland_module INNER.into() => userland_module
}; };
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap;
use tracing::Instrument; use tracing::Instrument;
use turbo_tasks::{RcStr, TryFlatJoinIterExt, TryJoinIterExt, Value, ValueToString, Vc}; use turbo_tasks::{
FxIndexMap, RcStr, TryFlatJoinIterExt, TryJoinIterExt, Value, ValueToString, Vc,
};
use turbopack_core::{ use turbopack_core::{
chunk::{availability_info::AvailabilityInfo, ChunkingContext, ChunkingContextExt}, chunk::{availability_info::AvailabilityInfo, ChunkingContext, ChunkingContextExt},
module::{Module, Modules}, module::{Module, Modules},
...@@ -30,10 +31,10 @@ pub fn client_modules_ssr_modifier() -> Vc<RcStr> { ...@@ -30,10 +31,10 @@ pub fn client_modules_ssr_modifier() -> Vc<RcStr> {
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct ClientReferencesChunks { pub struct ClientReferencesChunks {
pub client_component_client_chunks: pub client_component_client_chunks:
IndexMap<ClientReferenceType, (Vc<OutputAssets>, AvailabilityInfo)>, FxIndexMap<ClientReferenceType, (Vc<OutputAssets>, AvailabilityInfo)>,
pub client_component_ssr_chunks: pub client_component_ssr_chunks:
IndexMap<ClientReferenceType, (Vc<OutputAssets>, AvailabilityInfo)>, FxIndexMap<ClientReferenceType, (Vc<OutputAssets>, AvailabilityInfo)>,
pub layout_segment_client_chunks: IndexMap<Vc<NextServerComponentModule>, Vc<OutputAssets>>, pub layout_segment_client_chunks: FxIndexMap<Vc<NextServerComponentModule>, Vc<OutputAssets>>,
} }
/// Computes all client references chunks. /// Computes all client references chunks.
...@@ -125,11 +126,12 @@ pub async fn get_app_client_references_chunks( ...@@ -125,11 +126,12 @@ pub async fn get_app_client_references_chunks(
ssr_chunks.map(|ssr_chunks| (client_reference_ty, ssr_chunks)) ssr_chunks.map(|ssr_chunks| (client_reference_ty, ssr_chunks))
}) })
.collect(), .collect(),
layout_segment_client_chunks: IndexMap::new(), layout_segment_client_chunks: FxIndexMap::default(),
} }
.cell()) .cell())
} else { } else {
let mut client_references_by_server_component: IndexMap<_, Vec<_>> = IndexMap::new(); let mut client_references_by_server_component: FxIndexMap<_, Vec<_>> =
FxIndexMap::default();
let mut framework_reference_types = Vec::new(); let mut framework_reference_types = Vec::new();
for &server_component in app_client_references.server_component_entries.iter() { for &server_component in app_client_references.server_component_entries.iter() {
client_references_by_server_component client_references_by_server_component
...@@ -156,9 +158,9 @@ pub async fn get_app_client_references_chunks( ...@@ -156,9 +158,9 @@ pub async fn get_app_client_references_chunks(
let mut current_ssr_availability_info = AvailabilityInfo::Root; let mut current_ssr_availability_info = AvailabilityInfo::Root;
let mut current_ssr_chunks = OutputAssets::empty(); let mut current_ssr_chunks = OutputAssets::empty();
let mut layout_segment_client_chunks = IndexMap::new(); let mut layout_segment_client_chunks = FxIndexMap::default();
let mut client_component_ssr_chunks = IndexMap::new(); let mut client_component_ssr_chunks = FxIndexMap::default();
let mut client_component_client_chunks = IndexMap::new(); let mut client_component_client_chunks = FxIndexMap::default();
for (server_component, client_reference_types) in for (server_component, client_reference_types) in
client_references_by_server_component.into_iter() client_references_by_server_component.into_iter()
......
use std::io::Write; use std::io::Write;
use anyhow::Result; use anyhow::Result;
use indexmap::indexmap; use turbo_tasks::{fxindexmap, RcStr, TryJoinIterExt, Value, ValueToString, Vc};
use turbo_tasks::{RcStr, TryJoinIterExt, Value, ValueToString, Vc};
use turbo_tasks_fs::{self, rope::RopeBuilder, File, FileSystemPath}; use turbo_tasks_fs::{self, rope::RopeBuilder, File, FileSystemPath};
use turbopack::ModuleAssetContext; use turbopack::ModuleAssetContext;
use turbopack_core::{ use turbopack_core::{
...@@ -78,7 +77,7 @@ pub async fn get_app_page_entry( ...@@ -78,7 +77,7 @@ pub async fn get_app_page_entry(
let source = load_next_js_template( let source = load_next_js_template(
"app-page.js", "app-page.js",
project_root, project_root,
indexmap! { fxindexmap! {
"VAR_DEFINITION_PAGE" => page.to_string().into(), "VAR_DEFINITION_PAGE" => page.to_string().into(),
"VAR_DEFINITION_PATHNAME" => pathname.clone(), "VAR_DEFINITION_PATHNAME" => pathname.clone(),
"VAR_MODULE_GLOBAL_ERROR" => if inner_assets.contains_key(GLOBAL_ERROR) { "VAR_MODULE_GLOBAL_ERROR" => if inner_assets.contains_key(GLOBAL_ERROR) {
...@@ -87,13 +86,13 @@ pub async fn get_app_page_entry( ...@@ -87,13 +86,13 @@ pub async fn get_app_page_entry(
"next/dist/client/components/error-boundary".into() "next/dist/client/components/error-boundary".into()
}, },
}, },
indexmap! { fxindexmap! {
"tree" => loader_tree_code, "tree" => loader_tree_code,
"pages" => StringifyJs(&pages).to_string().into(), "pages" => StringifyJs(&pages).to_string().into(),
"__next_app_require__" => "__turbopack_require__".into(), "__next_app_require__" => "__turbopack_require__".into(),
"__next_app_load_chunk__" => " __turbopack_load__".into(), "__next_app_load_chunk__" => " __turbopack_load__".into(),
}, },
indexmap! {}, fxindexmap! {},
) )
.await?; .await?;
...@@ -168,24 +167,24 @@ async fn wrap_edge_page( ...@@ -168,24 +167,24 @@ async fn wrap_edge_page(
let source = load_next_js_template( let source = load_next_js_template(
"edge-ssr-app.js", "edge-ssr-app.js",
project_root, project_root,
indexmap! { fxindexmap! {
"VAR_USERLAND" => INNER.into(), "VAR_USERLAND" => INNER.into(),
"VAR_PAGE" => page.to_string().into(), "VAR_PAGE" => page.to_string().into(),
}, },
indexmap! { fxindexmap! {
"sriEnabled" => serde_json::Value::Bool(sri_enabled).to_string().into(), "sriEnabled" => serde_json::Value::Bool(sri_enabled).to_string().into(),
"nextConfig" => serde_json::to_string(next_config)?.into(), "nextConfig" => serde_json::to_string(next_config)?.into(),
"isServerComponent" => serde_json::Value::Bool(is_server_component).to_string().into(), "isServerComponent" => serde_json::Value::Bool(is_server_component).to_string().into(),
"dev" => serde_json::Value::Bool(dev).to_string().into(), "dev" => serde_json::Value::Bool(dev).to_string().into(),
"serverActions" => serde_json::to_string(&server_actions)?.into(), "serverActions" => serde_json::to_string(&server_actions)?.into(),
}, },
indexmap! { fxindexmap! {
"incrementalCacheHandler" => None, "incrementalCacheHandler" => None,
}, },
) )
.await?; .await?;
let inner_assets = indexmap! { let inner_assets = fxindexmap! {
INNER.into() => entry INNER.into() => entry
}; };
......
use anyhow::Result; use anyhow::Result;
use indexmap::indexmap; use turbo_tasks::{fxindexmap, RcStr, Value, ValueToString, Vc};
use turbo_tasks::{RcStr, Value, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack::ModuleAssetContext; use turbopack::ModuleAssetContext;
use turbopack_core::{ use turbopack_core::{
...@@ -74,7 +73,7 @@ pub async fn get_app_route_entry( ...@@ -74,7 +73,7 @@ pub async fn get_app_route_entry(
let virtual_source = load_next_js_template( let virtual_source = load_next_js_template(
"app-route.js", "app-route.js",
project_root, project_root,
indexmap! { fxindexmap! {
"VAR_DEFINITION_PAGE" => page.to_string().into(), "VAR_DEFINITION_PAGE" => page.to_string().into(),
"VAR_DEFINITION_PATHNAME" => pathname.clone(), "VAR_DEFINITION_PATHNAME" => pathname.clone(),
"VAR_DEFINITION_FILENAME" => path.file_stem().await?.as_ref().unwrap().as_str().into(), "VAR_DEFINITION_FILENAME" => path.file_stem().await?.as_ref().unwrap().as_str().into(),
...@@ -83,10 +82,10 @@ pub async fn get_app_route_entry( ...@@ -83,10 +82,10 @@ pub async fn get_app_route_entry(
"VAR_RESOLVED_PAGE_PATH" => path.to_string().await?.clone_value(), "VAR_RESOLVED_PAGE_PATH" => path.to_string().await?.clone_value(),
"VAR_USERLAND" => INNER.into(), "VAR_USERLAND" => INNER.into(),
}, },
indexmap! { fxindexmap! {
"nextConfigOutput" => output_type "nextConfigOutput" => output_type
}, },
indexmap! {}, fxindexmap! {},
) )
.await?; .await?;
...@@ -97,7 +96,7 @@ pub async fn get_app_route_entry( ...@@ -97,7 +96,7 @@ pub async fn get_app_route_entry(
) )
.module(); .module();
let inner_assets = indexmap! { let inner_assets = fxindexmap! {
INNER.into() => userland_module INNER.into() => userland_module
}; };
...@@ -138,15 +137,15 @@ async fn wrap_edge_route( ...@@ -138,15 +137,15 @@ async fn wrap_edge_route(
let source = load_next_js_template( let source = load_next_js_template(
"edge-app-route.js", "edge-app-route.js",
project_root, project_root,
indexmap! { fxindexmap! {
"VAR_USERLAND" => INNER.into(), "VAR_USERLAND" => INNER.into(),
}, },
indexmap! {}, fxindexmap! {},
indexmap! {}, fxindexmap! {},
) )
.await?; .await?;
let inner_assets = indexmap! { let inner_assets = fxindexmap! {
INNER.into() => entry INNER.into() => entry
}; };
......
use std::iter::once; use std::iter::once;
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, RcStr, Value, Vc};
use turbo_tasks::{RcStr, Value, Vc};
use turbo_tasks_env::EnvMap; use turbo_tasks_env::EnvMap;
use turbo_tasks_fs::{FileSystem, FileSystemPath}; use turbo_tasks_fs::{FileSystem, FileSystemPath};
use turbopack::{ use turbopack::{
...@@ -63,8 +62,8 @@ use crate::{ ...@@ -63,8 +62,8 @@ use crate::{
util::foreign_code_context_condition, util::foreign_code_context_condition,
}; };
fn defines(define_env: &IndexMap<RcStr, RcStr>) -> CompileTimeDefines { fn defines(define_env: &FxIndexMap<RcStr, RcStr>) -> CompileTimeDefines {
let mut defines = IndexMap::new(); let mut defines = FxIndexMap::default();
for (k, v) in define_env { for (k, v) in define_env {
defines defines
......
use std::{collections::HashSet, future::Future}; use std::{collections::HashSet, future::Future};
use anyhow::Result; use anyhow::Result;
use indexmap::{IndexMap, IndexSet};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::Instrument; use tracing::Instrument;
use turbo_tasks::{ use turbo_tasks::{
debug::ValueDebugFormat, debug::ValueDebugFormat,
graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow, VisitedNodes}, graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow, VisitedNodes},
trace::TraceRawVcs, trace::TraceRawVcs,
RcStr, ReadRef, TryJoinIterExt, ValueToString, Vc, FxIndexMap, FxIndexSet, RcStr, ReadRef, TryJoinIterExt, ValueToString, Vc,
}; };
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack::css::CssModuleAsset; use turbopack::css::CssModuleAsset;
...@@ -50,7 +49,7 @@ pub struct ClientReferenceGraphResult { ...@@ -50,7 +49,7 @@ pub struct ClientReferenceGraphResult {
/// Only the [`ClientReferenceType::EcmascriptClientReference`]s are listed in this map. /// Only the [`ClientReferenceType::EcmascriptClientReference`]s are listed in this map.
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
pub client_references_by_server_component: pub client_references_by_server_component:
IndexMap<Option<Vc<NextServerComponentModule>>, Vec<Vc<Box<dyn Module>>>>, FxIndexMap<Option<Vc<NextServerComponentModule>>, Vec<Vc<Box<dyn Module>>>>,
pub server_component_entries: Vec<Vc<NextServerComponentModule>>, pub server_component_entries: Vec<Vc<NextServerComponentModule>>,
pub server_utils: Vec<Vc<Box<dyn Module>>>, pub server_utils: Vec<Vc<Box<dyn Module>>>,
pub visited_nodes: Vc<VisitedClientReferenceGraphNodes>, pub visited_nodes: Vc<VisitedClientReferenceGraphNodes>,
...@@ -80,7 +79,7 @@ impl VisitedClientReferenceGraphNodes { ...@@ -80,7 +79,7 @@ impl VisitedClientReferenceGraphNodes {
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct ClientReferenceTypes(IndexSet<ClientReferenceType>); pub struct ClientReferenceTypes(FxIndexSet<ClientReferenceType>);
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ClientReferenceGraphResult { impl ClientReferenceGraphResult {
...@@ -90,7 +89,7 @@ impl ClientReferenceGraphResult { ...@@ -90,7 +89,7 @@ impl ClientReferenceGraphResult {
self.client_references self.client_references
.iter() .iter()
.map(|r| r.ty()) .map(|r| r.ty())
.collect::<IndexSet<_>>(), .collect::<FxIndexSet<_>>(),
) )
} }
} }
...@@ -124,7 +123,7 @@ pub async fn client_reference_graph( ...@@ -124,7 +123,7 @@ pub async fn client_reference_graph(
let mut server_component_entries = vec![]; let mut server_component_entries = vec![];
let mut server_utils = vec![]; let mut server_utils = vec![];
let mut client_references_by_server_component = IndexMap::new(); let mut client_references_by_server_component = FxIndexMap::default();
// Make sure None (for the various internal next/dist/esm/client/components/*) is listed // Make sure None (for the various internal next/dist/esm/client/components/*) is listed
// first // first
client_references_by_server_component.insert(None, Vec::new()); client_references_by_server_component.insert(None, Vec::new());
......
use std::collections::HashSet; use std::collections::HashSet;
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use indexmap::IndexMap;
use serde::{Deserialize, Deserializer, Serialize}; use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value as JsonValue; use serde_json::Value as JsonValue;
use turbo_tasks::{trace::TraceRawVcs, RcStr, TaskInput, Vc}; use turbo_tasks::{trace::TraceRawVcs, FxIndexMap, RcStr, TaskInput, Vc};
use turbo_tasks_env::EnvMap; use turbo_tasks_env::EnvMap;
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack::module_options::{ use turbopack::module_options::{
...@@ -37,7 +36,7 @@ struct CustomRoutes { ...@@ -37,7 +36,7 @@ struct CustomRoutes {
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct ModularizeImports(IndexMap<String, ModularizeImportPackageConfig>); pub struct ModularizeImports(FxIndexMap<String, ModularizeImportPackageConfig>);
#[turbo_tasks::value(serialization = "custom", eq = "manual")] #[turbo_tasks::value(serialization = "custom", eq = "manual")]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
...@@ -53,14 +52,14 @@ pub struct NextConfig { ...@@ -53,14 +52,14 @@ pub struct NextConfig {
/// custom path to a cache handler to use /// custom path to a cache handler to use
pub cache_handler: Option<RcStr>, pub cache_handler: Option<RcStr>,
pub env: IndexMap<String, JsonValue>, pub env: FxIndexMap<String, JsonValue>,
pub experimental: ExperimentalConfig, pub experimental: ExperimentalConfig,
pub images: ImageConfig, pub images: ImageConfig,
pub page_extensions: Vec<RcStr>, pub page_extensions: Vec<RcStr>,
pub react_production_profiling: Option<bool>, pub react_production_profiling: Option<bool>,
pub react_strict_mode: Option<bool>, pub react_strict_mode: Option<bool>,
pub transpile_packages: Option<Vec<RcStr>>, pub transpile_packages: Option<Vec<RcStr>>,
pub modularize_imports: Option<IndexMap<String, ModularizeImportPackageConfig>>, pub modularize_imports: Option<FxIndexMap<String, ModularizeImportPackageConfig>>,
pub dist_dir: Option<RcStr>, pub dist_dir: Option<RcStr>,
sass_options: Option<serde_json::Value>, sass_options: Option<serde_json::Value>,
pub trailing_slash: Option<bool>, pub trailing_slash: Option<bool>,
...@@ -108,8 +107,8 @@ pub struct NextConfig { ...@@ -108,8 +107,8 @@ pub struct NextConfig {
on_demand_entries: OnDemandEntriesConfig, on_demand_entries: OnDemandEntriesConfig,
powered_by_header: bool, powered_by_header: bool,
production_browser_source_maps: bool, production_browser_source_maps: bool,
public_runtime_config: IndexMap<String, serde_json::Value>, public_runtime_config: FxIndexMap<String, serde_json::Value>,
server_runtime_config: IndexMap<String, serde_json::Value>, server_runtime_config: FxIndexMap<String, serde_json::Value>,
static_page_generation_timeout: f64, static_page_generation_timeout: f64,
target: Option<String>, target: Option<String>,
typescript: TypeScriptConfig, typescript: TypeScriptConfig,
...@@ -398,8 +397,8 @@ pub enum RemotePatternProtocal { ...@@ -398,8 +397,8 @@ pub enum RemotePatternProtocal {
pub struct ExperimentalTurboConfig { pub struct ExperimentalTurboConfig {
/// This option has been replaced by `rules`. /// This option has been replaced by `rules`.
pub loaders: Option<JsonValue>, pub loaders: Option<JsonValue>,
pub rules: Option<IndexMap<RcStr, RuleConfigItemOrShortcut>>, pub rules: Option<FxIndexMap<RcStr, RuleConfigItemOrShortcut>>,
pub resolve_alias: Option<IndexMap<RcStr, JsonValue>>, pub resolve_alias: Option<FxIndexMap<RcStr, JsonValue>>,
pub resolve_extensions: Option<Vec<RcStr>>, pub resolve_extensions: Option<Vec<RcStr>>,
pub use_swc_css: Option<bool>, pub use_swc_css: Option<bool>,
pub tree_shaking: Option<bool>, pub tree_shaking: Option<bool>,
...@@ -425,7 +424,7 @@ pub enum RuleConfigItemOrShortcut { ...@@ -425,7 +424,7 @@ pub enum RuleConfigItemOrShortcut {
#[serde(rename_all = "camelCase", untagged)] #[serde(rename_all = "camelCase", untagged)]
pub enum RuleConfigItem { pub enum RuleConfigItem {
Options(RuleConfigItemOptions), Options(RuleConfigItemOptions),
Conditional(IndexMap<RcStr, RuleConfigItem>), Conditional(FxIndexMap<RcStr, RuleConfigItem>),
Boolean(bool), Boolean(bool),
} }
...@@ -864,7 +863,7 @@ impl NextConfig { ...@@ -864,7 +863,7 @@ impl NextConfig {
return Vc::cell(None); return Vc::cell(None);
} }
let active_conditions = active_conditions.into_iter().collect::<HashSet<_>>(); let active_conditions = active_conditions.into_iter().collect::<HashSet<_>>();
let mut rules = IndexMap::new(); let mut rules = FxIndexMap::default();
for (ext, rule) in turbo_rules.iter() { for (ext, rule) in turbo_rules.iter() {
fn transform_loaders(loaders: &[LoaderItem]) -> Vc<WebpackLoaderItems> { fn transform_loaders(loaders: &[LoaderItem]) -> Vc<WebpackLoaderItems> {
Vc::cell( Vc::cell(
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, RcStr, Value, Vc};
use turbo_tasks::{RcStr, Value, Vc};
use turbo_tasks_env::EnvMap; use turbo_tasks_env::EnvMap;
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack::resolve_options_context::ResolveOptionsContext; use turbopack::resolve_options_context::ResolveOptionsContext;
...@@ -29,8 +28,8 @@ use crate::{ ...@@ -29,8 +28,8 @@ use crate::{
util::{foreign_code_context_condition, NextRuntime}, util::{foreign_code_context_condition, NextRuntime},
}; };
fn defines(define_env: &IndexMap<RcStr, RcStr>) -> CompileTimeDefines { fn defines(define_env: &FxIndexMap<RcStr, RcStr>) -> CompileTimeDefines {
let mut defines = IndexMap::new(); let mut defines = FxIndexMap::default();
for (k, v) in define_env { for (k, v) in define_env {
defines defines
......
use indexmap::indexmap;
use indoc::formatdoc; use indoc::formatdoc;
use turbo_tasks::{RcStr, Value, Vc}; use turbo_tasks::{fxindexmap, RcStr, Value, Vc};
use turbo_tasks_fs::{File, FileSystemPath}; use turbo_tasks_fs::{File, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
asset::AssetContent, context::AssetContext, module::Module, reference_type::ReferenceType, asset::AssetContent, context::AssetContext, module::Module, reference_type::ReferenceType,
...@@ -33,7 +32,7 @@ pub async fn wrap_edge_entry( ...@@ -33,7 +32,7 @@ pub async fn wrap_edge_entry(
AssetContent::file(file.into()), AssetContent::file(file.into()),
); );
let inner_assets = indexmap! { let inner_assets = fxindexmap! {
"MODULE".into() => entry "MODULE".into() => entry
}; };
......
...@@ -2,10 +2,9 @@ use std::{collections::HashMap, path::Path}; ...@@ -2,10 +2,9 @@ use std::{collections::HashMap, path::Path};
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use futures::FutureExt; use futures::FutureExt;
use indexmap::IndexMap;
use indoc::formatdoc; use indoc::formatdoc;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{Completion, RcStr, Value, Vc}; use turbo_tasks::{Completion, FxIndexMap, RcStr, Value, Vc};
use turbo_tasks_bytes::stream::SingleValue; use turbo_tasks_bytes::stream::SingleValue;
use turbo_tasks_env::{CommandLineProcessEnv, ProcessEnv}; use turbo_tasks_env::{CommandLineProcessEnv, ProcessEnv};
use turbo_tasks_fetch::{fetch, HttpResponseBody}; use turbo_tasks_fetch::{fetch, HttpResponseBody};
...@@ -68,7 +67,7 @@ pub const USER_AGENT_FOR_GOOGLE_FONTS: &str = "Mozilla/5.0 (Macintosh; Intel Mac ...@@ -68,7 +67,7 @@ pub const USER_AGENT_FOR_GOOGLE_FONTS: &str = "Mozilla/5.0 (Macintosh; Intel Mac
pub const GOOGLE_FONTS_INTERNAL_PREFIX: &str = "@vercel/turbopack-next/internal/font/google/font"; pub const GOOGLE_FONTS_INTERNAL_PREFIX: &str = "@vercel/turbopack-next/internal/font/google/font";
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
struct FontData(IndexMap<RcStr, FontDataEntry>); struct FontData(FxIndexMap<RcStr, FontDataEntry>);
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub(crate) struct NextFontGoogleReplacer { pub(crate) struct NextFontGoogleReplacer {
......
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use indexmap::{indexset, IndexMap, IndexSet};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, RcStr, Value, Vc}; use turbo_tasks::{fxindexset, trace::TraceRawVcs, FxIndexMap, FxIndexSet, RcStr, Value, Vc};
use super::request::{NextFontRequest, OneOrManyStrings}; use super::request::{NextFontRequest, OneOrManyStrings};
const ALLOWED_DISPLAY_VALUES: &[&str] = &["auto", "block", "swap", "fallback", "optional"]; const ALLOWED_DISPLAY_VALUES: &[&str] = &["auto", "block", "swap", "fallback", "optional"];
pub(super) type FontData = IndexMap<RcStr, FontDataEntry>; pub(super) type FontData = FxIndexMap<RcStr, FontDataEntry>;
#[turbo_tasks::value(serialization = "auto_for_input")] #[turbo_tasks::value(serialization = "auto_for_input")]
#[derive(Clone, Debug, PartialOrd, Ord, Hash)] #[derive(Clone, Debug, PartialOrd, Ord, Hash)]
...@@ -70,7 +69,7 @@ impl Eq for Axis {} ...@@ -70,7 +69,7 @@ impl Eq for Axis {}
// https://github.com/vercel/next.js/blob/28454c6ddbc310419467e5415aee26e48d079b46/packages/font/src/google/utils.ts#L22 // https://github.com/vercel/next.js/blob/28454c6ddbc310419467e5415aee26e48d079b46/packages/font/src/google/utils.ts#L22
pub(super) fn options_from_request( pub(super) fn options_from_request(
request: &NextFontRequest, request: &NextFontRequest,
data: &IndexMap<RcStr, FontDataEntry>, data: &FxIndexMap<RcStr, FontDataEntry>,
) -> Result<NextFontGoogleOptions> { ) -> Result<NextFontGoogleOptions> {
if request.arguments.len() > 1 { if request.arguments.len() > 1 {
return Err(anyhow!( return Err(anyhow!(
...@@ -84,11 +83,11 @@ pub(super) fn options_from_request( ...@@ -84,11 +83,11 @@ pub(super) fn options_from_request(
let font_family: RcStr = request.import.replace('_', " ").into(); let font_family: RcStr = request.import.replace('_', " ").into();
let font_data = data.get(&font_family).context("Unknown font")?; let font_data = data.get(&font_family).context("Unknown font")?;
let requested_weights: IndexSet<RcStr> = argument let requested_weights: FxIndexSet<RcStr> = argument
.weight .weight
.map(|w| match w { .map(|w| match w {
OneOrManyStrings::One(one) => indexset! {one}, OneOrManyStrings::One(one) => fxindexset![one],
OneOrManyStrings::Many(many) => IndexSet::from_iter(many), OneOrManyStrings::Many(many) => many.into_iter().collect(),
}) })
.unwrap_or_default(); .unwrap_or_default();
...@@ -193,8 +192,7 @@ pub(super) fn options_from_request( ...@@ -193,8 +192,7 @@ pub(super) fn options_from_request(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, RcStr};
use turbo_tasks::RcStr;
use turbo_tasks_fs::json::parse_json_with_source_context; use turbo_tasks_fs::json::parse_json_with_source_context;
use super::{options_from_request, FontDataEntry, NextFontGoogleOptions}; use super::{options_from_request, FontDataEntry, NextFontGoogleOptions};
...@@ -202,7 +200,7 @@ mod tests { ...@@ -202,7 +200,7 @@ mod tests {
#[test] #[test]
fn test_errors_on_unknown_font() -> Result<()> { fn test_errors_on_unknown_font() -> Result<()> {
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context( let data: FxIndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -235,7 +233,7 @@ mod tests { ...@@ -235,7 +233,7 @@ mod tests {
#[test] #[test]
fn test_default_values_when_no_arguments() -> Result<()> { fn test_default_values_when_no_arguments() -> Result<()> {
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context( let data: FxIndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -278,7 +276,7 @@ mod tests { ...@@ -278,7 +276,7 @@ mod tests {
#[test] #[test]
fn test_errors_when_no_weights_chosen_no_variable() -> Result<()> { fn test_errors_when_no_weights_chosen_no_variable() -> Result<()> {
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context( let data: FxIndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -314,7 +312,7 @@ mod tests { ...@@ -314,7 +312,7 @@ mod tests {
#[test] #[test]
fn test_errors_on_unnecessary_weights() -> Result<()> { fn test_errors_on_unnecessary_weights() -> Result<()> {
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context( let data: FxIndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -353,7 +351,7 @@ mod tests { ...@@ -353,7 +351,7 @@ mod tests {
#[test] #[test]
fn test_errors_on_unvavailable_weights() -> Result<()> { fn test_errors_on_unvavailable_weights() -> Result<()> {
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context( let data: FxIndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -391,7 +389,7 @@ mod tests { ...@@ -391,7 +389,7 @@ mod tests {
#[test] #[test]
fn test_defaults_to_only_style_when_one_available() -> Result<()> { fn test_defaults_to_only_style_when_one_available() -> Result<()> {
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context( let data: FxIndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -423,7 +421,7 @@ mod tests { ...@@ -423,7 +421,7 @@ mod tests {
#[test] #[test]
fn test_defaults_to_normal_style_when_multiple() -> Result<()> { fn test_defaults_to_normal_style_when_multiple() -> Result<()> {
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context( let data: FxIndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -455,7 +453,7 @@ mod tests { ...@@ -455,7 +453,7 @@ mod tests {
#[test] #[test]
fn test_errors_on_unknown_styles() -> Result<()> { fn test_errors_on_unknown_styles() -> Result<()> {
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context( let data: FxIndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -495,7 +493,7 @@ mod tests { ...@@ -495,7 +493,7 @@ mod tests {
#[test] #[test]
fn test_errors_on_unknown_display() -> Result<()> { fn test_errors_on_unknown_display() -> Result<()> {
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context( let data: FxIndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
...@@ -536,7 +534,7 @@ mod tests { ...@@ -536,7 +534,7 @@ mod tests {
#[test] #[test]
fn test_errors_on_axes_without_variable() -> Result<()> { fn test_errors_on_axes_without_variable() -> Result<()> {
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context( let data: FxIndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#" r#"
{ {
"ABeeZee": { "ABeeZee": {
......
use std::cmp::Ordering; use std::cmp::Ordering;
use anyhow::{anyhow, bail, Context, Result}; use anyhow::{anyhow, bail, Context, Result};
use indexmap::{indexset, IndexSet}; use turbo_tasks::{fxindexset, FxIndexSet, RcStr};
use turbo_tasks::RcStr;
use super::options::{FontData, FontWeights}; use super::options::{FontData, FontWeights};
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub(super) struct FontAxes { pub(super) struct FontAxes {
pub(super) wght: IndexSet<RcStr>, pub(super) wght: FxIndexSet<RcStr>,
pub(super) ital: IndexSet<FontStyle>, pub(super) ital: FxIndexSet<FontStyle>,
pub(super) variable_axes: Option<Vec<(RcStr, RcStr)>>, pub(super) variable_axes: Option<Vec<(RcStr, RcStr)>>,
} }
...@@ -35,7 +34,7 @@ pub(super) fn get_font_axes( ...@@ -35,7 +34,7 @@ pub(super) fn get_font_axes(
let ital = { let ital = {
let has_italic = styles.contains(&"italic".into()); let has_italic = styles.contains(&"italic".into());
let has_normal = styles.contains(&"normal".into()); let has_normal = styles.contains(&"normal".into());
let mut set = IndexSet::new(); let mut set = FxIndexSet::default();
if has_normal { if has_normal {
set.insert(FontStyle::Normal); set.insert(FontStyle::Normal);
} }
...@@ -86,9 +85,9 @@ pub(super) fn get_font_axes( ...@@ -86,9 +85,9 @@ pub(super) fn get_font_axes(
let wght = match weight_axis { let wght = match weight_axis {
Some(weight_axis) => { Some(weight_axis) => {
indexset! {weight_axis} fxindexset! {weight_axis}
} }
None => indexset! {}, None => fxindexset! {},
}; };
Ok(FontAxes { Ok(FontAxes {
...@@ -99,7 +98,7 @@ pub(super) fn get_font_axes( ...@@ -99,7 +98,7 @@ pub(super) fn get_font_axes(
} }
FontWeights::Fixed(weights) => Ok(FontAxes { FontWeights::Fixed(weights) => Ok(FontAxes {
wght: IndexSet::from_iter(weights.iter().map(|w| w.to_string().into())), wght: FxIndexSet::from_iter(weights.iter().map(|w| w.to_string().into())),
ital, ital,
variable_axes: None, variable_axes: None,
}), }),
...@@ -233,7 +232,7 @@ pub(super) fn get_stylesheet_url( ...@@ -233,7 +232,7 @@ pub(super) fn get_stylesheet_url(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use anyhow::Result; use anyhow::Result;
use indexmap::indexset; use turbo_tasks::fxindexset;
use turbo_tasks_fs::json::parse_json_with_source_context; use turbo_tasks_fs::json::parse_json_with_source_context;
use super::get_font_axes; use super::get_font_axes;
...@@ -326,8 +325,8 @@ mod tests { ...@@ -326,8 +325,8 @@ mod tests {
&Some(vec!["slnt".into()]), &Some(vec!["slnt".into()]),
)?, )?,
FontAxes { FontAxes {
wght: indexset! {"100..900".into()}, wght: fxindexset! {"100..900".into()},
ital: indexset! {}, ital: fxindexset! {},
variable_axes: Some(vec![("slnt".into(), "-10..0".into())]) variable_axes: Some(vec![("slnt".into(), "-10..0".into())])
} }
); );
...@@ -367,8 +366,8 @@ mod tests { ...@@ -367,8 +366,8 @@ mod tests {
&Some(vec!["slnt".into()]), &Some(vec!["slnt".into()]),
)?, )?,
FontAxes { FontAxes {
wght: indexset! {}, wght: fxindexset! {},
ital: indexset! {}, ital: fxindexset! {},
variable_axes: Some(vec![("slnt".into(), "-10..0".into())]) variable_axes: Some(vec![("slnt".into(), "-10..0".into())])
} }
); );
...@@ -399,8 +398,8 @@ mod tests { ...@@ -399,8 +398,8 @@ mod tests {
assert_eq!( assert_eq!(
get_font_axes(&data, "Hind", &FontWeights::Fixed(vec![500]), &[], &None)?, get_font_axes(&data, "Hind", &FontWeights::Fixed(vec![500]), &[], &None)?,
FontAxes { FontAxes {
wght: indexset! {"500".into()}, wght: fxindexset! {"500".into()},
ital: indexset! {}, ital: fxindexset! {},
variable_axes: None variable_axes: None
} }
); );
...@@ -414,8 +413,8 @@ mod tests { ...@@ -414,8 +413,8 @@ mod tests {
GOOGLE_FONTS_STYLESHEET_URL, GOOGLE_FONTS_STYLESHEET_URL,
"Roboto Mono", "Roboto Mono",
&FontAxes { &FontAxes {
wght: indexset! {"500".into()}, wght: fxindexset! {"500".into()},
ital: indexset! {FontStyle::Normal}, ital: fxindexset! {FontStyle::Normal},
variable_axes: None variable_axes: None
}, },
"optional" "optional"
...@@ -433,8 +432,8 @@ mod tests { ...@@ -433,8 +432,8 @@ mod tests {
GOOGLE_FONTS_STYLESHEET_URL, GOOGLE_FONTS_STYLESHEET_URL,
"Roboto Serif", "Roboto Serif",
&FontAxes { &FontAxes {
wght: indexset! {"500".into()}, wght: fxindexset! {"500".into()},
ital: indexset! {FontStyle::Normal}, ital: fxindexset! {FontStyle::Normal},
variable_axes: Some(vec![ variable_axes: Some(vec![
("GRAD".into(), "-50..100".into()), ("GRAD".into(), "-50..100".into()),
("opsz".into(), "8..144".into()), ("opsz".into(), "8..144".into()),
...@@ -456,8 +455,8 @@ mod tests { ...@@ -456,8 +455,8 @@ mod tests {
GOOGLE_FONTS_STYLESHEET_URL, GOOGLE_FONTS_STYLESHEET_URL,
"Roboto Serif", "Roboto Serif",
&FontAxes { &FontAxes {
wght: indexset! {"500".into(), "300".into()}, wght: fxindexset! {"500".into(), "300".into()},
ital: indexset! {FontStyle::Normal, FontStyle::Italic}, ital: fxindexset! {FontStyle::Normal, FontStyle::Italic},
variable_axes: Some(vec![ variable_axes: Some(vec![
("GRAD".into(), "-50..100".into()), ("GRAD".into(), "-50..100".into()),
("opsz".into(), "8..144".into()), ("opsz".into(), "8..144".into()),
...@@ -480,8 +479,8 @@ mod tests { ...@@ -480,8 +479,8 @@ mod tests {
GOOGLE_FONTS_STYLESHEET_URL, GOOGLE_FONTS_STYLESHEET_URL,
"Nabla", "Nabla",
&FontAxes { &FontAxes {
wght: indexset! {}, wght: fxindexset! {},
ital: indexset! {}, ital: fxindexset! {},
variable_axes: Some(vec![ variable_axes: Some(vec![
("EDPT".into(), "0..200".into()), ("EDPT".into(), "0..200".into()),
("EHLT".into(), "0..24".into()), ("EHLT".into(), "0..24".into()),
...@@ -502,8 +501,8 @@ mod tests { ...@@ -502,8 +501,8 @@ mod tests {
GOOGLE_FONTS_STYLESHEET_URL, GOOGLE_FONTS_STYLESHEET_URL,
"Nabla", "Nabla",
&FontAxes { &FontAxes {
wght: indexset! {}, wght: fxindexset! {},
ital: indexset! {}, ital: fxindexset! {},
variable_axes: None, variable_axes: None,
}, },
"swap" "swap"
...@@ -521,8 +520,8 @@ mod tests { ...@@ -521,8 +520,8 @@ mod tests {
GOOGLE_FONTS_STYLESHEET_URL, GOOGLE_FONTS_STYLESHEET_URL,
"Nabla", "Nabla",
&FontAxes { &FontAxes {
wght: indexset! {}, wght: fxindexset! {},
ital: indexset! {}, ital: fxindexset! {},
variable_axes: Some(vec![]), variable_axes: Some(vec![]),
}, },
"swap" "swap"
...@@ -540,8 +539,8 @@ mod tests { ...@@ -540,8 +539,8 @@ mod tests {
GOOGLE_FONTS_STYLESHEET_URL, GOOGLE_FONTS_STYLESHEET_URL,
"Hind", "Hind",
&FontAxes { &FontAxes {
wght: indexset! {"500".into()}, wght: fxindexset! {"500".into()},
ital: indexset! {}, ital: fxindexset! {},
variable_axes: None variable_axes: None
}, },
"optional" "optional"
......
use indexmap::indexmap; use turbo_tasks::{fxindexmap, TaskInput, Value, Vc};
use turbo_tasks::{TaskInput, Value, Vc};
use turbopack::{module_options::CustomModuleType, ModuleAssetContext}; use turbopack::{module_options::CustomModuleType, ModuleAssetContext};
use turbopack_core::{ use turbopack_core::{
context::AssetContext, module::Module, reference_type::ReferenceType, resolve::ModulePart, context::AssetContext, module::Module, reference_type::ReferenceType, resolve::ModulePart,
...@@ -50,7 +49,7 @@ impl StructuredImageModuleType { ...@@ -50,7 +49,7 @@ impl StructuredImageModuleType {
} }
.cell(), .cell(),
), ),
Value::new(ReferenceType::Internal(Vc::cell(indexmap!( Value::new(ReferenceType::Internal(Vc::cell(fxindexmap!(
"IMAGE".into() => Vc::upcast(static_asset) "IMAGE".into() => Vc::upcast(static_asset)
)))), )))),
) )
......
use std::collections::{BTreeMap, HashMap}; use std::collections::{BTreeMap, HashMap};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use indexmap::{indexmap, IndexMap}; use turbo_tasks::{fxindexmap, FxIndexMap, RcStr, Value, Vc};
use turbo_tasks::{RcStr, Value, Vc};
use turbo_tasks_fs::{FileSystem, FileSystemPath}; use turbo_tasks_fs::{FileSystem, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
reference_type::{CommonJsReferenceSubType, ReferenceType}, reference_type::{CommonJsReferenceSubType, ReferenceType},
...@@ -209,7 +208,7 @@ pub async fn get_next_client_import_map( ...@@ -209,7 +208,7 @@ pub async fn get_next_client_import_map(
insert_exact_alias_map( insert_exact_alias_map(
&mut import_map, &mut import_map,
project_path, project_path,
indexmap! { fxindexmap! {
"server-only" => "next/dist/compiled/server-only/index".to_string(), "server-only" => "next/dist/compiled/server-only/index".to_string(),
"client-only" => "next/dist/compiled/client-only/index".to_string(), "client-only" => "next/dist/compiled/client-only/index".to_string(),
"next/dist/compiled/server-only" => "next/dist/compiled/server-only/index".to_string(), "next/dist/compiled/server-only" => "next/dist/compiled/server-only/index".to_string(),
...@@ -382,7 +381,7 @@ pub async fn get_next_edge_import_map( ...@@ -382,7 +381,7 @@ pub async fn get_next_edge_import_map(
insert_wildcard_alias_map( insert_wildcard_alias_map(
&mut import_map, &mut import_map,
project_path, project_path,
indexmap! { fxindexmap! {
"next/dist/build/" => "next/dist/esm/build/*".to_string(), "next/dist/build/" => "next/dist/esm/build/*".to_string(),
"next/dist/client/" => "next/dist/esm/client/*".to_string(), "next/dist/client/" => "next/dist/esm/client/*".to_string(),
"next/dist/shared/" => "next/dist/esm/shared/*".to_string(), "next/dist/shared/" => "next/dist/esm/shared/*".to_string(),
...@@ -397,7 +396,7 @@ pub async fn get_next_edge_import_map( ...@@ -397,7 +396,7 @@ pub async fn get_next_edge_import_map(
insert_exact_alias_map( insert_exact_alias_map(
&mut import_map, &mut import_map,
project_path, project_path,
indexmap! { fxindexmap! {
"next/app" => "next/dist/api/app".to_string(), "next/app" => "next/dist/api/app".to_string(),
"next/document" => "next/dist/api/document".to_string(), "next/document" => "next/dist/api/document".to_string(),
"next/dynamic" => "next/dist/api/dynamic".to_string(), "next/dynamic" => "next/dist/api/dynamic".to_string(),
...@@ -617,7 +616,7 @@ async fn insert_next_server_special_aliases( ...@@ -617,7 +616,7 @@ async fn insert_next_server_special_aliases(
insert_exact_alias_map( insert_exact_alias_map(
import_map, import_map,
project_path, project_path,
indexmap! { fxindexmap! {
"server-only" => "next/dist/compiled/server-only/empty".to_string(), "server-only" => "next/dist/compiled/server-only/empty".to_string(),
"client-only" => "next/dist/compiled/client-only/index".to_string(), "client-only" => "next/dist/compiled/client-only/index".to_string(),
"next/dist/compiled/server-only" => "next/dist/compiled/server-only/empty".to_string(), "next/dist/compiled/server-only" => "next/dist/compiled/server-only/empty".to_string(),
...@@ -634,7 +633,7 @@ async fn insert_next_server_special_aliases( ...@@ -634,7 +633,7 @@ async fn insert_next_server_special_aliases(
insert_exact_alias_map( insert_exact_alias_map(
import_map, import_map,
project_path, project_path,
indexmap! { fxindexmap! {
"server-only" => "next/dist/compiled/server-only/empty".to_string(), "server-only" => "next/dist/compiled/server-only/empty".to_string(),
"client-only" => "next/dist/compiled/client-only/error".to_string(), "client-only" => "next/dist/compiled/client-only/error".to_string(),
"next/dist/compiled/server-only" => "next/dist/compiled/server-only/empty".to_string(), "next/dist/compiled/server-only" => "next/dist/compiled/server-only/empty".to_string(),
...@@ -646,7 +645,7 @@ async fn insert_next_server_special_aliases( ...@@ -646,7 +645,7 @@ async fn insert_next_server_special_aliases(
insert_exact_alias_map( insert_exact_alias_map(
import_map, import_map,
project_path, project_path,
indexmap! { fxindexmap! {
"server-only" => "next/dist/compiled/server-only/index".to_string(), "server-only" => "next/dist/compiled/server-only/index".to_string(),
"client-only" => "next/dist/compiled/client-only/index".to_string(), "client-only" => "next/dist/compiled/client-only/index".to_string(),
"next/dist/compiled/server-only" => "next/dist/compiled/server-only/index".to_string(), "next/dist/compiled/server-only" => "next/dist/compiled/server-only/index".to_string(),
...@@ -687,14 +686,14 @@ async fn rsc_aliases( ...@@ -687,14 +686,14 @@ async fn rsc_aliases(
let react_channel = if ppr || taint { "-experimental" } else { "" }; let react_channel = if ppr || taint { "-experimental" } else { "" };
let react_client_package = get_react_client_package(&next_config).await?; let react_client_package = get_react_client_package(&next_config).await?;
let mut alias = IndexMap::new(); let mut alias = FxIndexMap::default();
if matches!( if matches!(
ty, ty,
ServerContextType::AppSSR { .. } ServerContextType::AppSSR { .. }
| ServerContextType::AppRSC { .. } | ServerContextType::AppRSC { .. }
| ServerContextType::AppRoute { .. } | ServerContextType::AppRoute { .. }
) { ) {
alias.extend(indexmap! { alias.extend(fxindexmap! {
"react" => format!("next/dist/compiled/react{react_channel}"), "react" => format!("next/dist/compiled/react{react_channel}"),
"react-dom" => format!("next/dist/compiled/react-dom{react_channel}"), "react-dom" => format!("next/dist/compiled/react-dom{react_channel}"),
"react/jsx-runtime" => format!("next/dist/compiled/react{react_channel}/jsx-runtime"), "react/jsx-runtime" => format!("next/dist/compiled/react{react_channel}/jsx-runtime"),
...@@ -709,7 +708,7 @@ async fn rsc_aliases( ...@@ -709,7 +708,7 @@ async fn rsc_aliases(
"react-dom/server.browser" => format!("next/dist/compiled/react-dom{react_channel}/server.browser"), "react-dom/server.browser" => format!("next/dist/compiled/react-dom{react_channel}/server.browser"),
}); });
} }
alias.extend(indexmap! { alias.extend(fxindexmap! {
"react-server-dom-webpack/client" => format!("next/dist/compiled/react-server-dom-turbopack{react_channel}/client"), "react-server-dom-webpack/client" => format!("next/dist/compiled/react-server-dom-turbopack{react_channel}/client"),
"react-server-dom-webpack/client.edge" => format!("next/dist/compiled/react-server-dom-turbopack{react_channel}/client.edge"), "react-server-dom-webpack/client.edge" => format!("next/dist/compiled/react-server-dom-turbopack{react_channel}/client.edge"),
"react-server-dom-webpack/server.edge" => format!("next/dist/compiled/react-server-dom-turbopack{react_channel}/server.edge"), "react-server-dom-webpack/server.edge" => format!("next/dist/compiled/react-server-dom-turbopack{react_channel}/server.edge"),
...@@ -725,7 +724,7 @@ async fn rsc_aliases( ...@@ -725,7 +724,7 @@ async fn rsc_aliases(
if runtime == NextRuntime::NodeJs { if runtime == NextRuntime::NodeJs {
match ty { match ty {
ServerContextType::AppSSR { .. } => { ServerContextType::AppSSR { .. } => {
alias.extend(indexmap! { alias.extend(fxindexmap! {
"react/jsx-runtime" => format!("next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-runtime"), "react/jsx-runtime" => format!("next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-runtime"),
"react/jsx-dev-runtime" => format!("next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-dev-runtime"), "react/jsx-dev-runtime" => format!("next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-dev-runtime"),
"react/compiler-runtime" => format!("next/dist/server/route-modules/app-page/vendored/ssr/react-compiler-runtime"), "react/compiler-runtime" => format!("next/dist/server/route-modules/app-page/vendored/ssr/react-compiler-runtime"),
...@@ -739,7 +738,7 @@ async fn rsc_aliases( ...@@ -739,7 +738,7 @@ async fn rsc_aliases(
| ServerContextType::AppRoute { .. } | ServerContextType::AppRoute { .. }
| ServerContextType::Middleware { .. } | ServerContextType::Middleware { .. }
| ServerContextType::Instrumentation { .. } => { | ServerContextType::Instrumentation { .. } => {
alias.extend(indexmap! { alias.extend(fxindexmap! {
"react/jsx-runtime" => format!("next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-runtime"), "react/jsx-runtime" => format!("next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-runtime"),
"react/jsx-dev-runtime" => format!("next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-dev-runtime"), "react/jsx-dev-runtime" => format!("next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-dev-runtime"),
"react/compiler-runtime" => format!("next/dist/server/route-modules/app-page/vendored/rsc/react-compiler-runtime"), "react/compiler-runtime" => format!("next/dist/server/route-modules/app-page/vendored/rsc/react-compiler-runtime"),
...@@ -762,7 +761,7 @@ async fn rsc_aliases( ...@@ -762,7 +761,7 @@ async fn rsc_aliases(
} }
if runtime == NextRuntime::Edge && ty.supports_react_server() { if runtime == NextRuntime::Edge && ty.supports_react_server() {
alias.extend(indexmap! { alias.extend(fxindexmap! {
"react" => format!("next/dist/compiled/react{react_channel}/react.react-server"), "react" => format!("next/dist/compiled/react{react_channel}/react.react-server"),
"next/dist/compiled/react" => format!("next/dist/compiled/react{react_channel}/react.react-server"), "next/dist/compiled/react" => format!("next/dist/compiled/react{react_channel}/react.react-server"),
"next/dist/compiled/react-experimental" => format!("next/dist/compiled/react-experimental/react.react-server"), "next/dist/compiled/react-experimental" => format!("next/dist/compiled/react-experimental/react.react-server"),
...@@ -799,7 +798,7 @@ async fn insert_optimized_module_aliases( ...@@ -799,7 +798,7 @@ async fn insert_optimized_module_aliases(
insert_exact_alias_map( insert_exact_alias_map(
import_map, import_map,
project_path, project_path,
indexmap! { fxindexmap! {
"unfetch" => "next/dist/build/polyfills/fetch/index.js".to_string(), "unfetch" => "next/dist/build/polyfills/fetch/index.js".to_string(),
"isomorphic-unfetch" => "next/dist/build/polyfills/fetch/index.js".to_string(), "isomorphic-unfetch" => "next/dist/build/polyfills/fetch/index.js".to_string(),
"whatwg-fetch" => "next/dist/build/polyfills/fetch/whatwg-fetch.js".to_string(), "whatwg-fetch" => "next/dist/build/polyfills/fetch/whatwg-fetch.js".to_string(),
...@@ -1021,7 +1020,7 @@ fn export_value_to_import_mapping( ...@@ -1021,7 +1020,7 @@ fn export_value_to_import_mapping(
fn insert_exact_alias_map( fn insert_exact_alias_map(
import_map: &mut ImportMap, import_map: &mut ImportMap,
project_path: Vc<FileSystemPath>, project_path: Vc<FileSystemPath>,
map: IndexMap<&'static str, String>, map: FxIndexMap<&'static str, String>,
) { ) {
for (pattern, request) in map { for (pattern, request) in map {
import_map.insert_exact_alias(pattern, request_to_import_mapping(project_path, &request)); import_map.insert_exact_alias(pattern, request_to_import_mapping(project_path, &request));
...@@ -1031,7 +1030,7 @@ fn insert_exact_alias_map( ...@@ -1031,7 +1030,7 @@ fn insert_exact_alias_map(
fn insert_wildcard_alias_map( fn insert_wildcard_alias_map(
import_map: &mut ImportMap, import_map: &mut ImportMap,
project_path: Vc<FileSystemPath>, project_path: Vc<FileSystemPath>,
map: IndexMap<&'static str, String>, map: FxIndexMap<&'static str, String>,
) { ) {
for (pattern, request) in map { for (pattern, request) in map {
import_map import_map
......
...@@ -4,9 +4,8 @@ pub(crate) mod client_reference_manifest; ...@@ -4,9 +4,8 @@ pub(crate) mod client_reference_manifest;
use std::collections::HashMap; use std::collections::HashMap;
use indexmap::{IndexMap, IndexSet};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, RcStr, TaskInput}; use turbo_tasks::{trace::TraceRawVcs, FxIndexMap, FxIndexSet, RcStr, TaskInput};
use crate::next_config::{CrossOriginConfig, Rewrites, RouteHas}; use crate::next_config::{CrossOriginConfig, Rewrites, RouteHas};
...@@ -97,7 +96,7 @@ pub struct EdgeFunctionDefinition { ...@@ -97,7 +96,7 @@ pub struct EdgeFunctionDefinition {
pub assets: Vec<AssetBinding>, pub assets: Vec<AssetBinding>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub regions: Option<Regions>, pub regions: Option<Regions>,
pub env: IndexMap<RcStr, RcStr>, pub env: FxIndexMap<RcStr, RcStr>,
} }
#[derive(Serialize, Default, Debug)] #[derive(Serialize, Default, Debug)]
...@@ -237,10 +236,10 @@ pub struct ClientReferenceManifest { ...@@ -237,10 +236,10 @@ pub struct ClientReferenceManifest {
pub edge_ssr_module_mapping: HashMap<ModuleId, ManifestNode>, pub edge_ssr_module_mapping: HashMap<ModuleId, ManifestNode>,
/// Mapping of server component path to required CSS client chunks. /// Mapping of server component path to required CSS client chunks.
#[serde(rename = "entryCSSFiles")] #[serde(rename = "entryCSSFiles")]
pub entry_css_files: HashMap<RcStr, IndexSet<RcStr>>, pub entry_css_files: HashMap<RcStr, FxIndexSet<RcStr>>,
/// Mapping of server component path to required JS client chunks. /// Mapping of server component path to required JS client chunks.
#[serde(rename = "entryJSFiles")] #[serde(rename = "entryJSFiles")]
pub entry_js_files: HashMap<RcStr, IndexSet<RcStr>>, pub entry_js_files: HashMap<RcStr, FxIndexSet<RcStr>>,
} }
#[derive(Serialize, Default, Debug)] #[derive(Serialize, Default, Debug)]
......
use std::io::Write; use std::io::Write;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::indexmap;
use serde::Serialize; use serde::Serialize;
use turbo_tasks::{RcStr, Value, Vc}; use turbo_tasks::{fxindexmap, FxIndexMap, RcStr, Value, Vc};
use turbo_tasks_fs::{rope::RopeBuilder, File, FileSystemPath}; use turbo_tasks_fs::{rope::RopeBuilder, File, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
...@@ -65,7 +64,7 @@ pub async fn create_page_ssr_entry_module( ...@@ -65,7 +64,7 @@ pub async fn create_page_ssr_entry_module(
const INNER_DOCUMENT: &str = "INNER_DOCUMENT"; const INNER_DOCUMENT: &str = "INNER_DOCUMENT";
const INNER_APP: &str = "INNER_APP"; const INNER_APP: &str = "INNER_APP";
let mut replacements = indexmap! { let mut replacements = fxindexmap! {
"VAR_DEFINITION_PAGE" => definition_page.clone(), "VAR_DEFINITION_PAGE" => definition_page.clone(),
"VAR_DEFINITION_PATHNAME" => definition_pathname.clone(), "VAR_DEFINITION_PATHNAME" => definition_pathname.clone(),
"VAR_USERLAND" => INNER.into(), "VAR_USERLAND" => INNER.into(),
...@@ -81,8 +80,8 @@ pub async fn create_page_ssr_entry_module( ...@@ -81,8 +80,8 @@ pub async fn create_page_ssr_entry_module(
template_file, template_file,
project_root, project_root,
replacements, replacements,
indexmap! {}, FxIndexMap::default(),
indexmap! {}, FxIndexMap::default(),
) )
.await?; .await?;
...@@ -110,7 +109,7 @@ pub async fn create_page_ssr_entry_module( ...@@ -110,7 +109,7 @@ pub async fn create_page_ssr_entry_module(
)); ));
} }
let mut inner_assets = indexmap! { let mut inner_assets = fxindexmap! {
INNER.into() => ssr_module, INNER.into() => ssr_module,
}; };
...@@ -208,14 +207,14 @@ async fn wrap_edge_page( ...@@ -208,14 +207,14 @@ async fn wrap_edge_page(
let source = load_next_js_template( let source = load_next_js_template(
"edge-ssr.js", "edge-ssr.js",
project_root, project_root,
indexmap! { fxindexmap! {
"VAR_USERLAND" => INNER.into(), "VAR_USERLAND" => INNER.into(),
"VAR_PAGE" => pathname.clone(), "VAR_PAGE" => pathname.clone(),
"VAR_MODULE_DOCUMENT" => INNER_DOCUMENT.into(), "VAR_MODULE_DOCUMENT" => INNER_DOCUMENT.into(),
"VAR_MODULE_APP" => INNER_APP.into(), "VAR_MODULE_APP" => INNER_APP.into(),
"VAR_MODULE_GLOBAL_ERROR" => INNER_ERROR.into(), "VAR_MODULE_GLOBAL_ERROR" => INNER_ERROR.into(),
}, },
indexmap! { fxindexmap! {
"pagesType" => StringifyJs("pages").to_string().into(), "pagesType" => StringifyJs("pages").to_string().into(),
"sriEnabled" => serde_json::Value::Bool(sri_enabled).to_string().into(), "sriEnabled" => serde_json::Value::Bool(sri_enabled).to_string().into(),
"nextConfig" => serde_json::to_string(next_config)?.into(), "nextConfig" => serde_json::to_string(next_config)?.into(),
...@@ -224,7 +223,7 @@ async fn wrap_edge_page( ...@@ -224,7 +223,7 @@ async fn wrap_edge_page(
"errorRouteModuleOptions" => serde_json::to_string(&get_route_module_options("/_error".into(), "/_error".into()))?.into(), "errorRouteModuleOptions" => serde_json::to_string(&get_route_module_options("/_error".into(), "/_error".into()))?.into(),
"user500RouteModuleOptions" => serde_json::to_string(&get_route_module_options("/500".into(), "/500".into()))?.into(), "user500RouteModuleOptions" => serde_json::to_string(&get_route_module_options("/500".into(), "/500".into()))?.into(),
}, },
indexmap! { fxindexmap! {
// TODO // TODO
"incrementalCacheHandler" => None, "incrementalCacheHandler" => None,
"userland500Page" => None, "userland500Page" => None,
...@@ -232,7 +231,7 @@ async fn wrap_edge_page( ...@@ -232,7 +231,7 @@ async fn wrap_edge_page(
) )
.await?; .await?;
let inner_assets = indexmap! { let inner_assets = fxindexmap! {
INNER.into() => entry, INNER.into() => entry,
INNER_DOCUMENT.into() => process_global_item(pages_structure.document(), reference_type.clone(), asset_context), INNER_DOCUMENT.into() => process_global_item(pages_structure.document(), reference_type.clone(), asset_context),
INNER_APP.into() => process_global_item(pages_structure.app(), reference_type.clone(), asset_context), INNER_APP.into() => process_global_item(pages_structure.app(), reference_type.clone(), asset_context),
......
use std::iter::once; use std::iter::once;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, RcStr, Value, Vc};
use turbo_tasks::{RcStr, Value, Vc};
use turbo_tasks_env::{EnvMap, ProcessEnv}; use turbo_tasks_env::{EnvMap, ProcessEnv};
use turbo_tasks_fs::{FileSystem, FileSystemPath}; use turbo_tasks_fs::{FileSystem, FileSystemPath};
use turbopack::{ use turbopack::{
...@@ -312,8 +311,8 @@ pub async fn get_server_resolve_options_context( ...@@ -312,8 +311,8 @@ pub async fn get_server_resolve_options_context(
.cell()) .cell())
} }
fn defines(define_env: &IndexMap<RcStr, RcStr>) -> CompileTimeDefines { fn defines(define_env: &FxIndexMap<RcStr, RcStr>) -> CompileTimeDefines {
let mut defines = IndexMap::new(); let mut defines = FxIndexMap::default();
for (k, v) in define_env { for (k, v) in define_env {
defines defines
......
...@@ -2,7 +2,6 @@ use std::collections::HashMap; ...@@ -2,7 +2,6 @@ use std::collections::HashMap;
use anyhow::Result; use anyhow::Result;
use async_trait::async_trait; use async_trait::async_trait;
use indexmap::IndexMap;
use modularize_imports::{modularize_imports, PackageConfig}; use modularize_imports::{modularize_imports, PackageConfig};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
...@@ -12,7 +11,7 @@ use swc_core::{ ...@@ -12,7 +11,7 @@ use swc_core::{
visit::FoldWith, visit::FoldWith,
}, },
}; };
use turbo_tasks::{trace::TraceRawVcs, Vc}; use turbo_tasks::{trace::TraceRawVcs, FxIndexMap, Vc};
use turbopack::module_options::{ModuleRule, ModuleRuleEffect}; use turbopack::module_options::{ModuleRule, ModuleRuleEffect};
use turbopack_ecmascript::{CustomTransformer, EcmascriptInputTransform, TransformContext}; use turbopack_ecmascript::{CustomTransformer, EcmascriptInputTransform, TransformContext};
...@@ -39,7 +38,7 @@ pub enum Transform { ...@@ -39,7 +38,7 @@ pub enum Transform {
/// Returns a rule which applies the Next.js modularize imports transform. /// Returns a rule which applies the Next.js modularize imports transform.
pub fn get_next_modularize_imports_rule( pub fn get_next_modularize_imports_rule(
modularize_imports_config: &IndexMap<String, ModularizeImportPackageConfig>, modularize_imports_config: &FxIndexMap<String, ModularizeImportPackageConfig>,
enable_mdx_rs: bool, enable_mdx_rs: bool,
) -> ModuleRule { ) -> ModuleRule {
let transformer = EcmascriptInputTransform::Plugin(Vc::cell(Box::new( let transformer = EcmascriptInputTransform::Plugin(Vc::cell(Box::new(
...@@ -60,7 +59,7 @@ struct ModularizeImportsTransformer { ...@@ -60,7 +59,7 @@ struct ModularizeImportsTransformer {
} }
impl ModularizeImportsTransformer { impl ModularizeImportsTransformer {
fn new(packages: &IndexMap<String, ModularizeImportPackageConfig>) -> Self { fn new(packages: &FxIndexMap<String, ModularizeImportPackageConfig>) -> Self {
Self { Self {
packages: packages packages: packages
.iter() .iter()
......
use indexmap::IndexMap; use turbo_tasks::{fxindexmap, RcStr, Vc};
use turbo_tasks::{RcStr, Vc};
use turbopack_core::diagnostics::{Diagnostic, DiagnosticPayload}; use turbopack_core::diagnostics::{Diagnostic, DiagnosticPayload};
/// A structure that keeps track of whether a particular Next.js feature is /// A structure that keeps track of whether a particular Next.js feature is
...@@ -38,10 +37,10 @@ impl Diagnostic for NextFeatureTelemetry { ...@@ -38,10 +37,10 @@ impl Diagnostic for NextFeatureTelemetry {
#[turbo_tasks::function] #[turbo_tasks::function]
fn payload(&self) -> Vc<DiagnosticPayload> { fn payload(&self) -> Vc<DiagnosticPayload> {
Vc::cell(IndexMap::from([( Vc::cell(fxindexmap! {
self.feature_name.clone(), self.feature_name.clone() =>
self.enabled.to_string().into(), self.enabled.to_string().into(),
)])) })
} }
} }
...@@ -78,9 +77,9 @@ impl Diagnostic for ModuleFeatureTelemetry { ...@@ -78,9 +77,9 @@ impl Diagnostic for ModuleFeatureTelemetry {
#[turbo_tasks::function] #[turbo_tasks::function]
fn payload(&self) -> Vc<DiagnosticPayload> { fn payload(&self) -> Vc<DiagnosticPayload> {
Vc::cell(IndexMap::from([( Vc::cell(fxindexmap! {
self.feature_name.clone(), self.feature_name.clone() =>
self.invocation_count.to_string().into(), self.invocation_count.to_string().into(),
)])) })
} }
} }
use std::io::Write; use std::io::Write;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::indexmap; use turbo_tasks::{fxindexmap, RcStr, TryJoinIterExt, Value, Vc};
use turbo_tasks::{RcStr, TryJoinIterExt, Value, Vc};
use turbo_tasks_fs::{ use turbo_tasks_fs::{
self, rope::RopeBuilder, File, FileContent, FileSystemPath, FileSystemPathOption, self, rope::RopeBuilder, File, FileContent, FileSystemPath, FileSystemPathOption,
}; };
...@@ -60,7 +59,7 @@ pub async fn create_page_loader_entry_module( ...@@ -60,7 +59,7 @@ pub async fn create_page_loader_entry_module(
let module = client_context let module = client_context
.process( .process(
virtual_source, virtual_source,
Value::new(ReferenceType::Internal(Vc::cell(indexmap! { Value::new(ReferenceType::Internal(Vc::cell(fxindexmap! {
"PAGE".into() => module, "PAGE".into() => module,
}))), }))),
) )
......
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use indexmap::{IndexMap, IndexSet};
use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde::{de::DeserializeOwned, Deserialize, Serialize};
use swc_core::{ use swc_core::{
common::GLOBALS, common::GLOBALS,
ecma::ast::{Expr, Lit, Program}, ecma::ast::{Expr, Lit, Program},
}; };
use turbo_tasks::{trace::TraceRawVcs, RcStr, TaskInput, ValueDefault, ValueToString, Vc}; use turbo_tasks::{
trace::TraceRawVcs, FxIndexMap, FxIndexSet, RcStr, TaskInput, ValueDefault, ValueToString, Vc,
};
use turbo_tasks_fs::{ use turbo_tasks_fs::{
self, json::parse_json_rope_with_source_context, rope::Rope, util::join_path, File, self, json::parse_json_rope_with_source_context, rope::Rope, util::join_path, File,
FileContent, FileSystemPath, FileContent, FileSystemPath,
...@@ -587,9 +588,9 @@ fn parse_config_from_js_value(module: Vc<Box<dyn Module>>, value: &JsValue) -> N ...@@ -587,9 +588,9 @@ fn parse_config_from_js_value(module: Vc<Box<dyn Module>>, value: &JsValue) -> N
pub async fn load_next_js_template( pub async fn load_next_js_template(
path: &str, path: &str,
project_path: Vc<FileSystemPath>, project_path: Vc<FileSystemPath>,
replacements: IndexMap<&'static str, RcStr>, replacements: FxIndexMap<&'static str, RcStr>,
injections: IndexMap<&'static str, RcStr>, injections: FxIndexMap<&'static str, RcStr>,
imports: IndexMap<&'static str, Option<RcStr>>, imports: FxIndexMap<&'static str, Option<RcStr>>,
) -> Result<Vc<Box<dyn Source>>> { ) -> Result<Vc<Box<dyn Source>>> {
let path = virtual_next_js_template_path(project_path, path.to_string()); let path = virtual_next_js_template_path(project_path, path.to_string());
...@@ -679,7 +680,7 @@ pub async fn load_next_js_template( ...@@ -679,7 +680,7 @@ pub async fn load_next_js_template(
// Replace all the template variables with the actual values. If a template // Replace all the template variables with the actual values. If a template
// variable is missing, throw an error. // variable is missing, throw an error.
let mut replaced = IndexSet::new(); let mut replaced = FxIndexSet::default();
for (key, replacement) in &replacements { for (key, replacement) in &replacements {
let full = format!("'{}'", key); let full = format!("'{}'", key);
...@@ -721,7 +722,7 @@ pub async fn load_next_js_template( ...@@ -721,7 +722,7 @@ pub async fn load_next_js_template(
} }
// Replace the injections. // Replace the injections.
let mut injected = IndexSet::new(); let mut injected = FxIndexSet::default();
for (key, injection) in &injections { for (key, injection) in &injections {
let full = format!("// INJECT:{}", key); let full = format!("// INJECT:{}", key);
...@@ -764,7 +765,7 @@ pub async fn load_next_js_template( ...@@ -764,7 +765,7 @@ pub async fn load_next_js_template(
} }
// Replace the optional imports. // Replace the optional imports.
let mut imports_added = IndexSet::new(); let mut imports_added = FxIndexSet::default();
for (key, import_path) in &imports { for (key, import_path) in &imports {
let mut full = format!("// OPTIONAL_IMPORT:{}", key); let mut full = format!("// OPTIONAL_IMPORT:{}", key);
let namespace = if !content.contains(&full) { let namespace = if !content.contains(&full) {
......
...@@ -106,7 +106,7 @@ struct TurboTasksBackendInner { ...@@ -106,7 +106,7 @@ struct TurboTasksBackendInner {
persisted_task_cache_log: Sharded<ChunkedVec<(Arc<CachedTaskType>, TaskId)>>, persisted_task_cache_log: Sharded<ChunkedVec<(Arc<CachedTaskType>, TaskId)>>,
task_cache: BiMap<Arc<CachedTaskType>, TaskId>, task_cache: BiMap<Arc<CachedTaskType>, TaskId>,
transient_tasks: DashMap<TaskId, Arc<TransientTask>>, transient_tasks: DashMap<TaskId, Arc<TransientTask>, BuildHasherDefault<FxHasher>>,
persisted_storage_data_log: Sharded<ChunkedVec<CachedDataUpdate>>, persisted_storage_data_log: Sharded<ChunkedVec<CachedDataUpdate>>,
persisted_storage_meta_log: Sharded<ChunkedVec<CachedDataUpdate>>, persisted_storage_meta_log: Sharded<ChunkedVec<CachedDataUpdate>>,
...@@ -161,7 +161,7 @@ impl TurboTasksBackendInner { ...@@ -161,7 +161,7 @@ impl TurboTasksBackendInner {
), ),
persisted_task_cache_log: Sharded::new(shard_amount), persisted_task_cache_log: Sharded::new(shard_amount),
task_cache: BiMap::new(), task_cache: BiMap::new(),
transient_tasks: DashMap::new(), transient_tasks: DashMap::default(),
persisted_storage_data_log: Sharded::new(shard_amount), persisted_storage_data_log: Sharded::new(shard_amount),
persisted_storage_meta_log: Sharded::new(shard_amount), persisted_storage_meta_log: Sharded::new(shard_amount),
storage: Storage::new(), storage: Storage::new(),
......
use std::{borrow::Borrow, hash::Hash}; use std::{
borrow::Borrow,
hash::{BuildHasherDefault, Hash},
};
use dashmap::{mapref::entry::Entry, DashMap}; use dashmap::{mapref::entry::Entry, DashMap};
use rustc_hash::FxHasher;
/// A bidirectional [`DashMap`] that allows lookup by key or value. /// A bidirectional [`DashMap`] that allows lookup by key or value.
/// ///
/// As keys and values are stored twice, they should be small types, such as /// As keys and values are stored twice, they should be small types, such as
/// [`Arc`][`std::sync::Arc`]. /// [`Arc`][`std::sync::Arc`].
pub struct BiMap<K, V> { pub struct BiMap<K, V> {
forward: DashMap<K, V>, forward: DashMap<K, V, BuildHasherDefault<FxHasher>>,
reverse: DashMap<V, K>, reverse: DashMap<V, K, BuildHasherDefault<FxHasher>>,
} }
impl<K, V> BiMap<K, V> impl<K, V> BiMap<K, V>
...@@ -18,8 +22,8 @@ where ...@@ -18,8 +22,8 @@ where
{ {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
forward: DashMap::new(), forward: DashMap::default(),
reverse: DashMap::new(), reverse: DashMap::default(),
} }
} }
......
use indexmap::IndexMap; use turbo_tasks::{mark_session_dependent, FxIndexMap, RcStr, Vc};
use turbo_tasks::{mark_session_dependent, RcStr, Vc};
use crate::{sorted_env_vars, EnvMap, ProcessEnv, GLOBAL_ENV_LOCK}; use crate::{sorted_env_vars, EnvMap, ProcessEnv, GLOBAL_ENV_LOCK};
...@@ -15,8 +14,8 @@ impl CommandLineProcessEnv { ...@@ -15,8 +14,8 @@ impl CommandLineProcessEnv {
} }
} }
/// Clones the current env vars into a IndexMap. /// Clones the current env vars into a FxIndexMap.
fn env_snapshot() -> IndexMap<RcStr, RcStr> { fn env_snapshot() -> FxIndexMap<RcStr, RcStr> {
let _lock = GLOBAL_ENV_LOCK.lock().unwrap(); let _lock = GLOBAL_ENV_LOCK.lock().unwrap();
sorted_env_vars() sorted_env_vars()
} }
......
use std::{env, sync::MutexGuard}; use std::{env, sync::MutexGuard};
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, RcStr, ResolvedVc, ValueToString, Vc};
use turbo_tasks::{RcStr, ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::{FileContent, FileSystemPath}; use turbo_tasks_fs::{FileContent, FileSystemPath};
use crate::{sorted_env_vars, EnvMap, ProcessEnv, GLOBAL_ENV_LOCK}; use crate::{sorted_env_vars, EnvMap, ProcessEnv, GLOBAL_ENV_LOCK};
...@@ -86,7 +85,11 @@ impl ProcessEnv for DotenvProcessEnv { ...@@ -86,7 +85,11 @@ impl ProcessEnv for DotenvProcessEnv {
} }
/// Restores the global env variables to mirror `to`. /// Restores the global env variables to mirror `to`.
fn restore_env(from: &IndexMap<RcStr, RcStr>, to: &IndexMap<RcStr, RcStr>, _lock: &MutexGuard<()>) { fn restore_env(
from: &FxIndexMap<RcStr, RcStr>,
to: &FxIndexMap<RcStr, RcStr>,
_lock: &MutexGuard<()>,
) {
for key in from.keys() { for key in from.keys() {
if !to.contains_key(key) { if !to.contains_key(key) {
env::remove_var(key); env::remove_var(key);
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, RcStr, Vc};
use turbo_tasks::{RcStr, Vc};
use crate::{EnvMap, ProcessEnv}; use crate::{EnvMap, ProcessEnv};
...@@ -32,7 +31,7 @@ impl ProcessEnv for FilterProcessEnv { ...@@ -32,7 +31,7 @@ impl ProcessEnv for FilterProcessEnv {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn read_all(&self) -> Result<Vc<EnvMap>> { async fn read_all(&self) -> Result<Vc<EnvMap>> {
let prior = self.prior.read_all().await?; let prior = self.prior.read_all().await?;
let mut filtered = IndexMap::new(); let mut filtered = FxIndexMap::default();
for (key, value) in &*prior { for (key, value) in &*prior {
let uppercase = key.to_uppercase(); let uppercase = key.to_uppercase();
for filter in &self.filters { for filter in &self.filters {
......
...@@ -9,8 +9,7 @@ mod filter; ...@@ -9,8 +9,7 @@ mod filter;
use std::{env, sync::Mutex}; use std::{env, sync::Mutex};
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, RcStr, Vc};
use turbo_tasks::{RcStr, Vc};
pub use self::{ pub use self::{
command_line::CommandLineProcessEnv, custom::CustomProcessEnv, dotenv::DotenvProcessEnv, command_line::CommandLineProcessEnv, custom::CustomProcessEnv, dotenv::DotenvProcessEnv,
...@@ -18,13 +17,13 @@ pub use self::{ ...@@ -18,13 +17,13 @@ pub use self::{
}; };
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct EnvMap(#[turbo_tasks(trace_ignore)] IndexMap<RcStr, RcStr>); pub struct EnvMap(#[turbo_tasks(trace_ignore)] FxIndexMap<RcStr, RcStr>);
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl EnvMap { impl EnvMap {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn empty() -> Vc<Self> { pub fn empty() -> Vc<Self> {
EnvMap(IndexMap::new()).cell() EnvMap(FxIndexMap::default()).cell()
} }
} }
...@@ -57,10 +56,10 @@ pub trait ProcessEnv { ...@@ -57,10 +56,10 @@ pub trait ProcessEnv {
} }
} }
pub fn sorted_env_vars() -> IndexMap<RcStr, RcStr> { pub fn sorted_env_vars() -> FxIndexMap<RcStr, RcStr> {
let mut vars = env::vars() let mut vars = env::vars()
.map(|(k, v)| (k.into(), v.into())) .map(|(k, v)| (k.into(), v.into()))
.collect::<IndexMap<_, _>>(); .collect::<FxIndexMap<_, _>>();
vars.sort_keys(); vars.sort_keys();
vars vars
} }
...@@ -78,7 +77,7 @@ pub async fn case_insensitive_read(map: Vc<EnvMap>, name: RcStr) -> Result<Vc<Op ...@@ -78,7 +77,7 @@ pub async fn case_insensitive_read(map: Vc<EnvMap>, name: RcStr) -> Result<Vc<Op
#[turbo_tasks::function] #[turbo_tasks::function]
async fn to_uppercase_map(map: Vc<EnvMap>) -> Result<Vc<EnvMap>> { async fn to_uppercase_map(map: Vc<EnvMap>) -> Result<Vc<EnvMap>> {
let map = &*map.await?; let map = &*map.await?;
let mut new = IndexMap::with_capacity(map.len()); let mut new = FxIndexMap::with_capacity_and_hasher(map.len(), Default::default());
for (k, v) in map { for (k, v) in map {
new.insert(k.to_uppercase().into(), v.clone()); new.insert(k.to_uppercase().into(), v.clone());
} }
......
...@@ -3,8 +3,9 @@ use std::{ ...@@ -3,8 +3,9 @@ use std::{
hash::Hash, hash::Hash,
}; };
use indexmap::IndexSet; use turbo_tasks::{
use turbo_tasks::{util::StaticOrArc, InvalidationReason, InvalidationReasonKind, RcStr}; util::StaticOrArc, FxIndexSet, InvalidationReason, InvalidationReasonKind, RcStr,
};
/// Invalidation was caused by a file change detected by the file watcher /// Invalidation was caused by a file change detected by the file watcher
#[derive(PartialEq, Eq, Hash)] #[derive(PartialEq, Eq, Hash)]
...@@ -33,7 +34,7 @@ static WATCH_CHANGE_KIND: WatchChangeKind = WatchChangeKind; ...@@ -33,7 +34,7 @@ static WATCH_CHANGE_KIND: WatchChangeKind = WatchChangeKind;
impl InvalidationReasonKind for WatchChangeKind { impl InvalidationReasonKind for WatchChangeKind {
fn fmt( fn fmt(
&self, &self,
reasons: &IndexSet<StaticOrArc<dyn InvalidationReason>>, reasons: &FxIndexSet<StaticOrArc<dyn InvalidationReason>>,
f: &mut Formatter<'_>, f: &mut Formatter<'_>,
) -> std::fmt::Result { ) -> std::fmt::Result {
write!( write!(
...@@ -78,7 +79,7 @@ static WATCH_START_KIND: WatchStartKind = WatchStartKind; ...@@ -78,7 +79,7 @@ static WATCH_START_KIND: WatchStartKind = WatchStartKind;
impl InvalidationReasonKind for WatchStartKind { impl InvalidationReasonKind for WatchStartKind {
fn fmt( fn fmt(
&self, &self,
reasons: &IndexSet<StaticOrArc<dyn InvalidationReason>>, reasons: &FxIndexSet<StaticOrArc<dyn InvalidationReason>>,
f: &mut Formatter<'_>, f: &mut Formatter<'_>,
) -> std::fmt::Result { ) -> std::fmt::Result {
let example = reasons[0].as_any().downcast_ref::<WatchStart>().unwrap(); let example = reasons[0].as_any().downcast_ref::<WatchStart>().unwrap();
...@@ -119,7 +120,7 @@ static WRITE_KIND: WriteKind = WriteKind; ...@@ -119,7 +120,7 @@ static WRITE_KIND: WriteKind = WriteKind;
impl InvalidationReasonKind for WriteKind { impl InvalidationReasonKind for WriteKind {
fn fmt( fn fmt(
&self, &self,
reasons: &IndexSet<StaticOrArc<dyn InvalidationReason>>, reasons: &FxIndexSet<StaticOrArc<dyn InvalidationReason>>,
f: &mut Formatter<'_>, f: &mut Formatter<'_>,
) -> std::fmt::Result { ) -> std::fmt::Result {
write!( write!(
...@@ -158,7 +159,7 @@ static INVALIDATE_FILESYSTEM_KIND: InvalidateFilesystemKind = InvalidateFilesyst ...@@ -158,7 +159,7 @@ static INVALIDATE_FILESYSTEM_KIND: InvalidateFilesystemKind = InvalidateFilesyst
impl InvalidationReasonKind for InvalidateFilesystemKind { impl InvalidationReasonKind for InvalidateFilesystemKind {
fn fmt( fn fmt(
&self, &self,
reasons: &IndexSet<StaticOrArc<dyn InvalidationReason>>, reasons: &FxIndexSet<StaticOrArc<dyn InvalidationReason>>,
f: &mut Formatter<'_>, f: &mut Formatter<'_>,
) -> std::fmt::Result { ) -> std::fmt::Result {
write!( write!(
......
use std::{hash::Hash, mem::take}; use std::{hash::Hash, mem::take};
use indexmap::IndexSet; use turbo_tasks::FxIndexSet;
use super::{balance_edge, AggregationContext}; use super::{balance_edge, AggregationContext};
/// Enqueued edges that need to be balanced. Deduplicates edges and keeps track /// Enqueued edges that need to be balanced. Deduplicates edges and keeps track
/// of aggregation numbers read during balancing. /// of aggregation numbers read during balancing.
pub struct BalanceQueue<I> { pub struct BalanceQueue<I> {
queue: IndexSet<(I, I)>, queue: FxIndexSet<(I, I)>,
} }
impl<I: Hash + Eq + Clone> BalanceQueue<I> { impl<I: Hash + Eq + Clone> BalanceQueue<I> {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
queue: IndexSet::default(), queue: FxIndexSet::default(),
} }
} }
......
...@@ -11,11 +11,11 @@ use std::{ ...@@ -11,11 +11,11 @@ use std::{
time::Instant, time::Instant,
}; };
use indexmap::IndexSet;
use parking_lot::{Mutex, MutexGuard}; use parking_lot::{Mutex, MutexGuard};
use rand::{rngs::SmallRng, Rng, SeedableRng}; use rand::{rngs::SmallRng, Rng, SeedableRng};
use ref_cast::RefCast; use ref_cast::RefCast;
use rstest::*; use rstest::*;
use turbo_tasks::FxIndexSet;
use self::aggregation_data::prepare_aggregation_data; use self::aggregation_data::prepare_aggregation_data;
use super::{ use super::{
...@@ -1032,7 +1032,7 @@ fn fuzzy(#[case] seed: u32, #[case] count: u32) { ...@@ -1032,7 +1032,7 @@ fn fuzzy(#[case] seed: u32, #[case] count: u32) {
} }
prepare_aggregation_data(&ctx, &NodeRef(nodes[0].clone())); prepare_aggregation_data(&ctx, &NodeRef(nodes[0].clone()));
let mut edges = IndexSet::new(); let mut edges = FxIndexSet::default();
for _ in 0..1000 { for _ in 0..1000 {
match r.gen_range(0..=2) { match r.gen_range(0..=2) {
......
use std::fmt::{Debug, Display}; use std::fmt::{Debug, Display};
use auto_hash_map::{AutoMap, AutoSet}; use auto_hash_map::{AutoMap, AutoSet};
use indexmap::{IndexMap, IndexSet}; use turbo_tasks::{FxIndexMap, FxIndexSet, Vc};
use turbo_tasks::Vc;
pub use turbo_tasks_macros::ValueDebugFormat; pub use turbo_tasks_macros::ValueDebugFormat;
use crate::{self as turbo_tasks}; use crate::{self as turbo_tasks};
...@@ -256,7 +255,7 @@ where ...@@ -256,7 +255,7 @@ where
} }
} }
impl<T> ValueDebugFormat for IndexSet<T> impl<T> ValueDebugFormat for FxIndexSet<T>
where where
T: ValueDebugFormat, T: ValueDebugFormat,
{ {
...@@ -271,7 +270,7 @@ where ...@@ -271,7 +270,7 @@ where
.collect::<Vec<_>>(); .collect::<Vec<_>>();
ValueDebugFormatString::Async(Box::pin(async move { ValueDebugFormatString::Async(Box::pin(async move {
let mut values_string = IndexSet::new(); let mut values_string = FxIndexSet::default();
for value in values { for value in values {
let value = match value { let value = match value {
ValueDebugFormatString::Sync(string) => string, ValueDebugFormatString::Sync(string) => string,
...@@ -284,7 +283,7 @@ where ...@@ -284,7 +283,7 @@ where
} }
} }
impl<K, V> ValueDebugFormat for IndexMap<K, V> impl<K, V> ValueDebugFormat for FxIndexMap<K, V>
where where
K: ValueDebugFormat, K: ValueDebugFormat,
V: ValueDebugFormat, V: ValueDebugFormat,
...@@ -305,7 +304,7 @@ where ...@@ -305,7 +304,7 @@ where
.collect::<Vec<_>>(); .collect::<Vec<_>>();
ValueDebugFormatString::Async(Box::pin(async move { ValueDebugFormatString::Async(Box::pin(async move {
let mut values_string = IndexMap::new(); let mut values_string = FxIndexMap::default();
for (key, value) in values { for (key, value) in values {
let key = match key { let key = match key {
ValueDebugFormatString::Sync(string) => string, ValueDebugFormatString::Sync(string) => string,
......
...@@ -7,7 +7,7 @@ use std::{ ...@@ -7,7 +7,7 @@ use std::{
}; };
use anyhow::Result; use anyhow::Result;
use indexmap::{map::Entry, IndexMap, IndexSet}; use indexmap::map::Entry;
use serde::{de::Visitor, Deserialize, Serialize}; use serde::{de::Visitor, Deserialize, Serialize};
use tokio::runtime::Handle; use tokio::runtime::Handle;
...@@ -16,7 +16,7 @@ use crate::{ ...@@ -16,7 +16,7 @@ use crate::{
manager::{current_task, with_turbo_tasks}, manager::{current_task, with_turbo_tasks},
trace::TraceRawVcs, trace::TraceRawVcs,
util::StaticOrArc, util::StaticOrArc,
TaskId, TurboTasksApi, FxIndexMap, FxIndexSet, TaskId, TurboTasksApi,
}; };
/// Get an [`Invalidator`] that can be used to invalidate the current task /// Get an [`Invalidator`] that can be used to invalidate the current task
...@@ -179,7 +179,7 @@ pub trait InvalidationReasonKind: DynamicEqHash + Send + Sync + 'static { ...@@ -179,7 +179,7 @@ pub trait InvalidationReasonKind: DynamicEqHash + Send + Sync + 'static {
/// kind. It is only called with two or more reasons. /// kind. It is only called with two or more reasons.
fn fmt( fn fmt(
&self, &self,
data: &IndexSet<StaticOrArc<dyn InvalidationReason>>, data: &FxIndexSet<StaticOrArc<dyn InvalidationReason>>,
f: &mut std::fmt::Formatter<'_>, f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result; ) -> std::fmt::Result;
} }
...@@ -221,7 +221,7 @@ enum MapEntry { ...@@ -221,7 +221,7 @@ enum MapEntry {
reason: StaticOrArc<dyn InvalidationReason>, reason: StaticOrArc<dyn InvalidationReason>,
}, },
Multiple { Multiple {
reasons: IndexSet<StaticOrArc<dyn InvalidationReason>>, reasons: FxIndexSet<StaticOrArc<dyn InvalidationReason>>,
}, },
} }
...@@ -232,7 +232,7 @@ enum MapEntry { ...@@ -232,7 +232,7 @@ enum MapEntry {
pub struct InvalidationReasonSet { pub struct InvalidationReasonSet {
next_unique_tag: usize, next_unique_tag: usize,
// We track typed and untyped entries in the same map to keep the occurence order of entries. // We track typed and untyped entries in the same map to keep the occurence order of entries.
map: IndexMap<MapKey, MapEntry>, map: FxIndexMap<MapKey, MapEntry>,
} }
impl InvalidationReasonSet { impl InvalidationReasonSet {
...@@ -245,7 +245,7 @@ impl InvalidationReasonSet { ...@@ -245,7 +245,7 @@ impl InvalidationReasonSet {
match replace( match replace(
entry, entry,
MapEntry::Multiple { MapEntry::Multiple {
reasons: IndexSet::new(), reasons: FxIndexSet::default(),
}, },
) { ) {
MapEntry::Single { MapEntry::Single {
...@@ -257,7 +257,7 @@ impl InvalidationReasonSet { ...@@ -257,7 +257,7 @@ impl InvalidationReasonSet {
}; };
return; return;
} }
let mut reasons = IndexSet::new(); let mut reasons = FxIndexSet::default();
reasons.insert(existing_reason); reasons.insert(existing_reason);
reasons.insert(reason); reasons.insert(reason);
*entry = MapEntry::Multiple { reasons }; *entry = MapEntry::Multiple { reasons };
......
...@@ -106,6 +106,7 @@ pub use manager::{ ...@@ -106,6 +106,7 @@ pub use manager::{
pub use native_function::{FunctionMeta, NativeFunction}; pub use native_function::{FunctionMeta, NativeFunction};
pub use output::OutputContent; pub use output::OutputContent;
pub use raw_vc::{CellId, RawVc, ReadRawVcFuture, ResolveTypeError}; pub use raw_vc::{CellId, RawVc, ReadRawVcFuture, ResolveTypeError};
pub use rcstr::RcStr;
pub use read_ref::ReadRef; pub use read_ref::ReadRef;
use rustc_hash::FxHasher; use rustc_hash::FxHasher;
pub use scope::scope; pub use scope::scope;
...@@ -122,7 +123,44 @@ pub use vc::{ ...@@ -122,7 +123,44 @@ pub use vc::{
VcValueTraitCast, VcValueType, VcValueTypeCast, VcValueTraitCast, VcValueType, VcValueTypeCast,
}; };
pub use crate::rcstr::RcStr; pub type FxIndexSet<T> = indexmap::IndexSet<T, BuildHasherDefault<FxHasher>>;
pub type FxIndexMap<K, V> = indexmap::IndexMap<K, V, BuildHasherDefault<FxHasher>>;
// Copied from indexmap! and indexset!
#[macro_export]
macro_rules! fxindexmap {
(@single $($x:tt)*) => (());
(@count $($rest:expr),*) => (<[()]>::len(&[$($crate::fxindexmap!(@single $rest)),*]));
($($key:expr => $value:expr,)+) => { $crate::fxindexmap!($($key => $value),+) };
($($key:expr => $value:expr),*) => {
{
let _cap = $crate::fxindexmap!(@count $($key),*);
let mut _map = $crate::FxIndexMap::with_capacity_and_hasher(_cap, Default::default());
$(
_map.insert($key, $value);
)*
_map
}
};
}
#[macro_export]
macro_rules! fxindexset {
(@single $($x:tt)*) => (());
(@count $($rest:expr),*) => (<[()]>::len(&[$($crate::fxindexset!(@single $rest)),*]));
($($value:expr,)+) => { $crate::fxindexset!($($value),+) };
($($value:expr),*) => {
{
let _cap = $crate::fxindexset!(@count $($value),*);
let mut _set = $crate::FxIndexSet::with_capacity_and_hasher(_cap, Default::default());
$(
_set.insert($value);
)*
_set
}
};
}
/// Implements [`VcValueType`] for the given `struct` or `enum`. These value types can be used /// Implements [`VcValueType`] for the given `struct` or `enum`. These value types can be used
/// inside of a "value cell" as [`Vc<...>`][Vc]. /// inside of a "value cell" as [`Vc<...>`][Vc].
......
use std::{fmt::Debug, hash::Hash, num::NonZeroU64, ops::Deref}; use std::{
fmt::Debug,
hash::{BuildHasherDefault, Hash},
num::NonZeroU64,
ops::Deref,
};
use dashmap::{mapref::entry::Entry, DashMap}; use dashmap::{mapref::entry::Entry, DashMap};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use rustc_hash::FxHasher;
use crate::{ use crate::{
id::{FunctionId, TraitTypeId, ValueTypeId}, id::{FunctionId, TraitTypeId, ValueTypeId},
...@@ -10,23 +16,27 @@ use crate::{ ...@@ -10,23 +16,27 @@ use crate::{
NativeFunction, TraitType, ValueType, NativeFunction, TraitType, ValueType,
}; };
type FxDashMap<K, V> = DashMap<K, V, BuildHasherDefault<FxHasher>>;
static FUNCTION_ID_FACTORY: IdFactory<FunctionId> = IdFactory::new(1, u32::MAX as u64); static FUNCTION_ID_FACTORY: IdFactory<FunctionId> = IdFactory::new(1, u32::MAX as u64);
static FUNCTIONS_BY_NAME: Lazy<DashMap<&'static str, FunctionId>> = Lazy::new(DashMap::new); static FUNCTIONS_BY_NAME: Lazy<FxDashMap<&'static str, FunctionId>> = Lazy::new(DashMap::default);
static FUNCTIONS_BY_VALUE: Lazy<DashMap<&'static NativeFunction, FunctionId>> = static FUNCTIONS_BY_VALUE: Lazy<FxDashMap<&'static NativeFunction, FunctionId>> =
Lazy::new(DashMap::new); Lazy::new(DashMap::default);
static FUNCTIONS: Lazy<NoMoveVec<(&'static NativeFunction, &'static str)>> = static FUNCTIONS: Lazy<NoMoveVec<(&'static NativeFunction, &'static str)>> =
Lazy::new(NoMoveVec::new); Lazy::new(NoMoveVec::new);
static VALUE_TYPE_ID_FACTORY: IdFactory<ValueTypeId> = IdFactory::new(1, u32::MAX as u64); static VALUE_TYPE_ID_FACTORY: IdFactory<ValueTypeId> = IdFactory::new(1, u32::MAX as u64);
static VALUE_TYPES_BY_NAME: Lazy<DashMap<&'static str, ValueTypeId>> = Lazy::new(DashMap::new); static VALUE_TYPES_BY_NAME: Lazy<FxDashMap<&'static str, ValueTypeId>> =
static VALUE_TYPES_BY_VALUE: Lazy<DashMap<&'static ValueType, ValueTypeId>> = Lazy::new(DashMap::default);
Lazy::new(DashMap::new); static VALUE_TYPES_BY_VALUE: Lazy<FxDashMap<&'static ValueType, ValueTypeId>> =
Lazy::new(DashMap::default);
static VALUE_TYPES: Lazy<NoMoveVec<(&'static ValueType, &'static str)>> = Lazy::new(NoMoveVec::new); static VALUE_TYPES: Lazy<NoMoveVec<(&'static ValueType, &'static str)>> = Lazy::new(NoMoveVec::new);
static TRAIT_TYPE_ID_FACTORY: IdFactory<TraitTypeId> = IdFactory::new(1, u32::MAX as u64); static TRAIT_TYPE_ID_FACTORY: IdFactory<TraitTypeId> = IdFactory::new(1, u32::MAX as u64);
static TRAIT_TYPES_BY_NAME: Lazy<DashMap<&'static str, TraitTypeId>> = Lazy::new(DashMap::new); static TRAIT_TYPES_BY_NAME: Lazy<FxDashMap<&'static str, TraitTypeId>> =
static TRAIT_TYPES_BY_VALUE: Lazy<DashMap<&'static TraitType, TraitTypeId>> = Lazy::new(DashMap::default);
Lazy::new(DashMap::new); static TRAIT_TYPES_BY_VALUE: Lazy<FxDashMap<&'static TraitType, TraitTypeId>> =
Lazy::new(DashMap::default);
static TRAIT_TYPES: Lazy<NoMoveVec<(&'static TraitType, &'static str)>> = Lazy::new(NoMoveVec::new); static TRAIT_TYPES: Lazy<NoMoveVec<(&'static TraitType, &'static str)>> = Lazy::new(NoMoveVec::new);
fn register_thing< fn register_thing<
...@@ -38,8 +48,8 @@ fn register_thing< ...@@ -38,8 +48,8 @@ fn register_thing<
value: V, value: V,
id_factory: &IdFactory<K>, id_factory: &IdFactory<K>,
store: &NoMoveVec<(V, &'static str), INITIAL_CAPACITY_BITS>, store: &NoMoveVec<(V, &'static str), INITIAL_CAPACITY_BITS>,
map_by_name: &DashMap<&'static str, K>, map_by_name: &FxDashMap<&'static str, K>,
map_by_value: &DashMap<V, K>, map_by_value: &FxDashMap<V, K>,
) { ) {
if let Entry::Vacant(e) = map_by_value.entry(value) { if let Entry::Vacant(e) = map_by_value.entry(value) {
let new_id = id_factory.get(); let new_id = id_factory.get();
...@@ -57,7 +67,7 @@ fn get_thing_id< ...@@ -57,7 +67,7 @@ fn get_thing_id<
V: Clone + Hash + Eq + Debug + Sync + Send + Debug, V: Clone + Hash + Eq + Debug + Sync + Send + Debug,
>( >(
value: V, value: V,
map_by_value: &DashMap<V, K>, map_by_value: &FxDashMap<V, K>,
) -> K { ) -> K {
if let Some(id) = map_by_value.get(&value) { if let Some(id) = map_by_value.get(&value) {
*id *id
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexSet; use turbo_tasks::{FxIndexSet, RcStr, ValueToString, Vc};
use turbo_tasks::{RcStr, ValueToString, Vc};
use turbopack_core::{ use turbopack_core::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
chunk::{Chunk, ChunkingContext, OutputChunk, OutputChunkRuntimeInfo}, chunk::{Chunk, ChunkingContext, OutputChunk, OutputChunkRuntimeInfo},
...@@ -169,7 +168,7 @@ impl Introspectable for EcmascriptDevChunk { ...@@ -169,7 +168,7 @@ impl Introspectable for EcmascriptDevChunk {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn children(&self) -> Result<Vc<IntrospectableChildren>> { async fn children(&self) -> Result<Vc<IntrospectableChildren>> {
let mut children = IndexSet::new(); let mut children = FxIndexSet::default();
let chunk = Vc::upcast::<Box<dyn Introspectable>>(self.chunk) let chunk = Vc::upcast::<Box<dyn Introspectable>>(self.chunk)
.resolve() .resolve()
.await?; .await?;
......
use std::io::Write as _; use std::io::Write as _;
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap;
use tracing::{info_span, Instrument}; use tracing::{info_span, Instrument};
use turbo_tasks::{ReadRef, TryJoinIterExt, ValueToString, Vc}; use turbo_tasks::{FxIndexMap, ReadRef, TryJoinIterExt, ValueToString, Vc};
use turbopack_core::{ use turbopack_core::{
chunk::{AsyncModuleInfo, ChunkItem, ChunkItemExt, ModuleId}, chunk::{AsyncModuleInfo, ChunkItem, ChunkItemExt, ModuleId},
code_builder::{Code, CodeBuilder}, code_builder::{Code, CodeBuilder},
...@@ -42,7 +41,7 @@ impl EcmascriptDevChunkContentEntry { ...@@ -42,7 +41,7 @@ impl EcmascriptDevChunkContentEntry {
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct EcmascriptDevChunkContentEntries( pub struct EcmascriptDevChunkContentEntries(
IndexMap<ReadRef<ModuleId>, EcmascriptDevChunkContentEntry>, FxIndexMap<ReadRef<ModuleId>, EcmascriptDevChunkContentEntry>,
); );
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -53,7 +52,7 @@ impl EcmascriptDevChunkContentEntries { ...@@ -53,7 +52,7 @@ impl EcmascriptDevChunkContentEntries {
) -> Result<Vc<EcmascriptDevChunkContentEntries>> { ) -> Result<Vc<EcmascriptDevChunkContentEntries>> {
let chunk_content = chunk_content.await?; let chunk_content = chunk_content.await?;
let entries: IndexMap<_, _> = chunk_content let entries: FxIndexMap<_, _> = chunk_content
.chunk_items .chunk_items
.iter() .iter()
.map(|&(chunk_item, async_module_info)| async move { .map(|&(chunk_item, async_module_info)| async move {
......
use std::io::Write; use std::io::Write;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use indexmap::IndexMap;
use indoc::writedoc; use indoc::writedoc;
use serde::Serialize; use serde::Serialize;
use turbo_tasks::{IntoTraitRef, TryJoinIterExt, Vc}; use turbo_tasks::{FxIndexMap, IntoTraitRef, TryJoinIterExt, Vc};
use turbo_tasks_fs::File; use turbo_tasks_fs::File;
use turbopack_core::{ use turbopack_core::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
...@@ -27,7 +26,7 @@ use super::{ ...@@ -27,7 +26,7 @@ use super::{
#[turbo_tasks::value] #[turbo_tasks::value]
pub(super) struct EcmascriptDevChunkListContent { pub(super) struct EcmascriptDevChunkListContent {
chunk_list_path: String, chunk_list_path: String,
pub(super) chunks_contents: IndexMap<String, Vc<Box<dyn VersionedContent>>>, pub(super) chunks_contents: FxIndexMap<String, Vc<Box<dyn VersionedContent>>>,
source: EcmascriptDevChunkListSource, source: EcmascriptDevChunkListSource,
} }
...@@ -71,8 +70,8 @@ impl EcmascriptDevChunkListContent { ...@@ -71,8 +70,8 @@ impl EcmascriptDevChunkListContent {
/// Computes the version of this content. /// Computes the version of this content.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn version(&self) -> Result<Vc<EcmascriptDevChunkListVersion>> { pub async fn version(&self) -> Result<Vc<EcmascriptDevChunkListVersion>> {
let mut by_merger = IndexMap::<_, Vec<_>>::new(); let mut by_merger = FxIndexMap::<_, Vec<_>>::default();
let mut by_path = IndexMap::<_, _>::new(); let mut by_path = FxIndexMap::<_, _>::default();
for (chunk_path, chunk_content) in &self.chunks_contents { for (chunk_path, chunk_content) in &self.chunks_contents {
if let Some(mergeable) = if let Some(mergeable) =
......
use std::sync::Arc; use std::sync::Arc;
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap;
use serde::Serialize; use serde::Serialize;
use turbo_tasks::{IntoTraitRef, TraitRef, Vc}; use turbo_tasks::{FxIndexMap, IntoTraitRef, TraitRef, Vc};
use turbopack_core::version::{ use turbopack_core::version::{
MergeableVersionedContent, PartialUpdate, TotalUpdate, Update, Version, VersionedContent, MergeableVersionedContent, PartialUpdate, TotalUpdate, Update, Version, VersionedContent,
VersionedContentMerger, VersionedContentMerger,
...@@ -17,8 +16,8 @@ use super::{content::EcmascriptDevChunkListContent, version::EcmascriptDevChunkL ...@@ -17,8 +16,8 @@ use super::{content::EcmascriptDevChunkListContent, version::EcmascriptDevChunkL
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct ChunkListUpdate<'a> { struct ChunkListUpdate<'a> {
/// A map from chunk path to a corresponding update of that chunk. /// A map from chunk path to a corresponding update of that chunk.
#[serde(skip_serializing_if = "IndexMap::is_empty")] #[serde(skip_serializing_if = "FxIndexMap::is_empty")]
chunks: IndexMap<&'a str, ChunkUpdate>, chunks: FxIndexMap<&'a str, ChunkUpdate>,
/// List of merged updates since the last version. /// List of merged updates since the last version.
#[serde(skip_serializing_if = "Vec::is_empty")] #[serde(skip_serializing_if = "Vec::is_empty")]
merged: Vec<Arc<serde_json::Value>>, merged: Vec<Arc<serde_json::Value>>,
...@@ -88,8 +87,8 @@ pub(super) async fn update_chunk_list( ...@@ -88,8 +87,8 @@ pub(super) async fn update_chunk_list(
// by common mergers. Then, we compute the update of each group separately. // by common mergers. Then, we compute the update of each group separately.
// Single chunk updates are computed separately and only require a stable chunk // Single chunk updates are computed separately and only require a stable chunk
// path to identify the chunk across versions. // path to identify the chunk across versions.
let mut by_merger = IndexMap::<_, Vec<_>>::new(); let mut by_merger = FxIndexMap::<_, Vec<_>>::default();
let mut by_path = IndexMap::<_, _>::new(); let mut by_path = FxIndexMap::<_, _>::default();
for (chunk_path, chunk_content) in &content.chunks_contents { for (chunk_path, chunk_content) in &content.chunks_contents {
if let Some(mergeable) = if let Some(mergeable) =
...@@ -102,7 +101,7 @@ pub(super) async fn update_chunk_list( ...@@ -102,7 +101,7 @@ pub(super) async fn update_chunk_list(
} }
} }
let mut chunks = IndexMap::<_, _>::new(); let mut chunks = FxIndexMap::<_, _>::default();
for (chunk_path, from_chunk_version) in &from.by_path { for (chunk_path, from_chunk_version) in &from.by_path {
if let Some(chunk_content) = by_path.remove(chunk_path) { if let Some(chunk_content) = by_path.remove(chunk_path) {
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, RcStr, TraitRef, TryJoinIterExt, Vc};
use turbo_tasks::{RcStr, TraitRef, TryJoinIterExt, Vc};
use turbo_tasks_hash::{encode_hex, Xxh3Hash64Hasher}; use turbo_tasks_hash::{encode_hex, Xxh3Hash64Hasher};
use turbopack_core::version::{Version, VersionedContentMerger}; use turbopack_core::version::{Version, VersionedContentMerger};
...@@ -13,10 +12,10 @@ type VersionTraitRef = TraitRef<Box<dyn Version>>; ...@@ -13,10 +12,10 @@ type VersionTraitRef = TraitRef<Box<dyn Version>>;
pub(super) struct EcmascriptDevChunkListVersion { pub(super) struct EcmascriptDevChunkListVersion {
/// A map from chunk path to its version. /// A map from chunk path to its version.
#[turbo_tasks(trace_ignore)] #[turbo_tasks(trace_ignore)]
pub by_path: IndexMap<String, VersionTraitRef>, pub by_path: FxIndexMap<String, VersionTraitRef>,
/// A map from chunk merger to the version of the merged contents of chunks. /// A map from chunk merger to the version of the merged contents of chunks.
#[turbo_tasks(trace_ignore)] #[turbo_tasks(trace_ignore)]
pub by_merger: IndexMap<Vc<Box<dyn VersionedContentMerger>>, VersionTraitRef>, pub by_merger: FxIndexMap<Vc<Box<dyn VersionedContentMerger>>, VersionTraitRef>,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
......
use std::sync::Arc; use std::sync::Arc;
use anyhow::Result; use anyhow::Result;
use indexmap::{IndexMap, IndexSet};
use serde::Serialize; use serde::Serialize;
use turbo_tasks::{IntoTraitRef, ReadRef, TryJoinIterExt, Vc}; use turbo_tasks::{FxIndexMap, FxIndexSet, IntoTraitRef, ReadRef, TryJoinIterExt, Vc};
use turbo_tasks_fs::rope::Rope; use turbo_tasks_fs::rope::Rope;
use turbopack_core::{ use turbopack_core::{
chunk::{ChunkingContext, ModuleId}, chunk::{ChunkingContext, ModuleId},
...@@ -26,11 +25,11 @@ use super::{ ...@@ -26,11 +25,11 @@ use super::{
#[serde(tag = "type", rename_all = "camelCase")] #[serde(tag = "type", rename_all = "camelCase")]
struct EcmascriptMergedUpdate<'a> { struct EcmascriptMergedUpdate<'a> {
/// A map from module id to latest module entry. /// A map from module id to latest module entry.
#[serde(skip_serializing_if = "IndexMap::is_empty")] #[serde(skip_serializing_if = "FxIndexMap::is_empty")]
entries: IndexMap<ReadRef<ModuleId>, EcmascriptModuleEntry>, entries: FxIndexMap<ReadRef<ModuleId>, EcmascriptModuleEntry>,
/// A map from chunk path to the chunk update. /// A map from chunk path to the chunk update.
#[serde(skip_serializing_if = "IndexMap::is_empty")] #[serde(skip_serializing_if = "FxIndexMap::is_empty")]
chunks: IndexMap<&'a str, EcmascriptMergedChunkUpdate>, chunks: FxIndexMap<&'a str, EcmascriptMergedChunkUpdate>,
} }
impl EcmascriptMergedUpdate<'_> { impl EcmascriptMergedUpdate<'_> {
...@@ -50,8 +49,8 @@ enum EcmascriptMergedChunkUpdate { ...@@ -50,8 +49,8 @@ enum EcmascriptMergedChunkUpdate {
#[derive(Serialize, Default)] #[derive(Serialize, Default)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct EcmascriptMergedChunkAdded { struct EcmascriptMergedChunkAdded {
#[serde(skip_serializing_if = "IndexSet::is_empty")] #[serde(skip_serializing_if = "FxIndexSet::is_empty")]
modules: IndexSet<ReadRef<ModuleId>>, modules: FxIndexSet<ReadRef<ModuleId>>,
} }
#[derive(Serialize, Default)] #[derive(Serialize, Default)]
...@@ -60,17 +59,17 @@ struct EcmascriptMergedChunkDeleted { ...@@ -60,17 +59,17 @@ struct EcmascriptMergedChunkDeleted {
// Technically, this is redundant, since the client will already know all // Technically, this is redundant, since the client will already know all
// modules in the chunk from the previous version. However, it's useful for // modules in the chunk from the previous version. However, it's useful for
// merging updates without access to an initial state. // merging updates without access to an initial state.
#[serde(skip_serializing_if = "IndexSet::is_empty")] #[serde(skip_serializing_if = "FxIndexSet::is_empty")]
modules: IndexSet<ReadRef<ModuleId>>, modules: FxIndexSet<ReadRef<ModuleId>>,
} }
#[derive(Serialize, Default)] #[derive(Serialize, Default)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct EcmascriptMergedChunkPartial { struct EcmascriptMergedChunkPartial {
#[serde(skip_serializing_if = "IndexSet::is_empty")] #[serde(skip_serializing_if = "FxIndexSet::is_empty")]
added: IndexSet<ReadRef<ModuleId>>, added: FxIndexSet<ReadRef<ModuleId>>,
#[serde(skip_serializing_if = "IndexSet::is_empty")] #[serde(skip_serializing_if = "FxIndexSet::is_empty")]
deleted: IndexSet<ReadRef<ModuleId>>, deleted: FxIndexSet<ReadRef<ModuleId>>,
} }
#[derive(Serialize)] #[derive(Serialize)]
...@@ -167,7 +166,7 @@ pub(super) async fn update_ecmascript_merged_chunk( ...@@ -167,7 +166,7 @@ pub(super) async fn update_ecmascript_merged_chunk(
return Ok(Update::None); return Ok(Update::None);
} }
let mut from_versions_by_chunk_path: IndexMap<_, _> = from let mut from_versions_by_chunk_path: FxIndexMap<_, _> = from
.versions .versions
.iter() .iter()
.map(|version| (&*version.chunk_path, version)) .map(|version| (&*version.chunk_path, version))
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, ReadRef, Vc};
use turbo_tasks::{ReadRef, Vc};
use turbopack_core::{chunk::ModuleId, code_builder::Code}; use turbopack_core::{chunk::ModuleId, code_builder::Code};
use super::{content::EcmascriptDevChunkContent, version::EcmascriptDevChunkVersion}; use super::{content::EcmascriptDevChunkContent, version::EcmascriptDevChunkVersion};
...@@ -12,9 +11,9 @@ pub(super) enum EcmascriptChunkUpdate { ...@@ -12,9 +11,9 @@ pub(super) enum EcmascriptChunkUpdate {
} }
pub(super) struct EcmascriptChunkPartialUpdate { pub(super) struct EcmascriptChunkPartialUpdate {
pub added: IndexMap<ReadRef<ModuleId>, (u64, Vc<Code>)>, pub added: FxIndexMap<ReadRef<ModuleId>, (u64, Vc<Code>)>,
pub deleted: IndexMap<ReadRef<ModuleId>, u64>, pub deleted: FxIndexMap<ReadRef<ModuleId>, u64>,
pub modified: IndexMap<ReadRef<ModuleId>, Vc<Code>>, pub modified: FxIndexMap<ReadRef<ModuleId>, Vc<Code>>,
} }
pub(super) async fn update_ecmascript_chunk( pub(super) async fn update_ecmascript_chunk(
...@@ -34,9 +33,9 @@ pub(super) async fn update_ecmascript_chunk( ...@@ -34,9 +33,9 @@ pub(super) async fn update_ecmascript_chunk(
let content = content.await?; let content = content.await?;
let entries = content.entries.await?; let entries = content.entries.await?;
let mut added = IndexMap::default(); let mut added = FxIndexMap::default();
let mut modified = IndexMap::default(); let mut modified = FxIndexMap::default();
let mut deleted = IndexMap::default(); let mut deleted = FxIndexMap::default();
for (id, from_hash) in &from.entries_hashes { for (id, from_hash) in &from.entries_hashes {
if let Some(entry) = entries.get(id) { if let Some(entry) = entries.get(id) {
......
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, RcStr, ReadRef, Vc};
use turbo_tasks::{RcStr, ReadRef, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_hash::{encode_hex, Xxh3Hash64Hasher}; use turbo_tasks_hash::{encode_hex, Xxh3Hash64Hasher};
use turbopack_core::{chunk::ModuleId, version::Version}; use turbopack_core::{chunk::ModuleId, version::Version};
...@@ -10,7 +9,7 @@ use super::content_entry::EcmascriptDevChunkContentEntries; ...@@ -10,7 +9,7 @@ use super::content_entry::EcmascriptDevChunkContentEntries;
#[turbo_tasks::value(serialization = "none")] #[turbo_tasks::value(serialization = "none")]
pub(super) struct EcmascriptDevChunkVersion { pub(super) struct EcmascriptDevChunkVersion {
pub(super) chunk_path: String, pub(super) chunk_path: String,
pub(super) entries_hashes: IndexMap<ReadRef<ModuleId>, u64>, pub(super) entries_hashes: FxIndexMap<ReadRef<ModuleId>, u64>,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -33,7 +32,8 @@ impl EcmascriptDevChunkVersion { ...@@ -33,7 +32,8 @@ impl EcmascriptDevChunkVersion {
); );
}; };
let entries = entries.await?; let entries = entries.await?;
let mut entries_hashes = IndexMap::with_capacity(entries.len()); let mut entries_hashes =
FxIndexMap::with_capacity_and_hasher(entries.len(), Default::default());
for (id, entry) in entries.iter() { for (id, entry) in entries.iter() {
entries_hashes.insert(id.clone(), *entry.hash.await?); entries_hashes.insert(id.clone(), *entry.hash.await?);
} }
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{ use turbo_tasks::{
debug::ValueDebugFormat, trace::TraceRawVcs, TryFlatJoinIterExt, TryJoinIterExt, ValueToString, debug::ValueDebugFormat, trace::TraceRawVcs, FxIndexMap, TryFlatJoinIterExt, TryJoinIterExt,
Vc, ValueToString, Vc,
}; };
use turbo_tasks_hash::Xxh3Hash64Hasher; use turbo_tasks_hash::Xxh3Hash64Hasher;
...@@ -18,7 +17,7 @@ pub struct AvailableChunkItemInfo { ...@@ -18,7 +17,7 @@ pub struct AvailableChunkItemInfo {
pub struct OptionAvailableChunkItemInfo(Option<AvailableChunkItemInfo>); pub struct OptionAvailableChunkItemInfo(Option<AvailableChunkItemInfo>);
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct AvailableChunkItemInfoMap(IndexMap<Vc<Box<dyn ChunkItem>>, AvailableChunkItemInfo>); pub struct AvailableChunkItemInfoMap(FxIndexMap<Vc<Box<dyn ChunkItem>>, AvailableChunkItemInfo>);
/// Allows to gather information about which assets are already available. /// Allows to gather information about which assets are already available.
/// Adding more roots will form a linked list like structure to allow caching /// Adding more roots will form a linked list like structure to allow caching
......
...@@ -2,8 +2,7 @@ use std::collections::HashSet; ...@@ -2,8 +2,7 @@ use std::collections::HashSet;
use anyhow::Result; use anyhow::Result;
use auto_hash_map::AutoSet; use auto_hash_map::AutoSet;
use indexmap::{IndexMap, IndexSet}; use turbo_tasks::{FxIndexMap, FxIndexSet, TryFlatJoinIterExt, TryJoinIterExt, Value, Vc};
use turbo_tasks::{TryFlatJoinIterExt, TryJoinIterExt, Value, Vc};
use super::{ use super::{
availability_info::AvailabilityInfo, available_chunk_items::AvailableChunkItemInfo, availability_info::AvailabilityInfo, available_chunk_items::AvailableChunkItemInfo,
...@@ -49,7 +48,7 @@ pub async fn make_chunk_group( ...@@ -49,7 +48,7 @@ pub async fn make_chunk_group(
.copied() .copied()
.chain(self_async_children.into_iter()) .chain(self_async_children.into_iter())
.map(|chunk_item| (chunk_item, AutoSet::<Vc<Box<dyn ChunkItem>>>::new())) .map(|chunk_item| (chunk_item, AutoSet::<Vc<Box<dyn ChunkItem>>>::new()))
.collect::<IndexMap<_, _>>(); .collect::<FxIndexMap<_, _>>();
// Propagate async inheritance // Propagate async inheritance
let mut i = 0; let mut i = 0;
...@@ -81,7 +80,7 @@ pub async fn make_chunk_group( ...@@ -81,7 +80,7 @@ pub async fn make_chunk_group(
let mut chunk_items = chunk_items let mut chunk_items = chunk_items
.into_iter() .into_iter()
.map(|chunk_item| (chunk_item, None)) .map(|chunk_item| (chunk_item, None))
.collect::<IndexMap<_, Option<Vc<AsyncModuleInfo>>>>(); .collect::<FxIndexMap<_, Option<Vc<AsyncModuleInfo>>>>();
// Insert AsyncModuleInfo for every async module // Insert AsyncModuleInfo for every async module
for (async_item, referenced_async_modules) in async_chunk_items { for (async_item, referenced_async_modules) in async_chunk_items {
...@@ -172,7 +171,7 @@ pub async fn make_chunk_group( ...@@ -172,7 +171,7 @@ pub async fn make_chunk_group(
} }
async fn references_to_output_assets( async fn references_to_output_assets(
references: IndexSet<Vc<Box<dyn ModuleReference>>>, references: FxIndexSet<Vc<Box<dyn ModuleReference>>>,
) -> Result<Vc<OutputAssets>> { ) -> Result<Vc<OutputAssets>> {
let output_assets = references let output_assets = references
.into_iter() .into_iter()
......
...@@ -4,11 +4,10 @@ use std::{ ...@@ -4,11 +4,10 @@ use std::{
}; };
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use tracing::Level; use tracing::Level;
use turbo_tasks::{RcStr, ReadRef, TryJoinIterExt, ValueToString, Vc}; use turbo_tasks::{FxIndexMap, RcStr, ReadRef, TryJoinIterExt, ValueToString, Vc};
use super::{ use super::{
AsyncModuleInfo, Chunk, ChunkItem, ChunkItemsWithAsyncModuleInfo, ChunkType, ChunkingContext, AsyncModuleInfo, Chunk, ChunkItem, ChunkItemsWithAsyncModuleInfo, ChunkType, ChunkingContext,
...@@ -58,7 +57,7 @@ pub async fn make_chunks( ...@@ -58,7 +57,7 @@ pub async fn make_chunks(
}) })
.try_join() .try_join()
.await?; .await?;
let mut map = IndexMap::<_, Vec<_>>::new(); let mut map = FxIndexMap::<_, Vec<_>>::default();
for (chunk_item, async_info, chunk_item_info) in chunk_items { for (chunk_item, async_info, chunk_item_info) in chunk_items {
map.entry(chunk_item_info.ty) map.entry(chunk_item_info.ty)
.or_default() .or_default()
...@@ -228,7 +227,7 @@ async fn package_name_split( ...@@ -228,7 +227,7 @@ async fn package_name_split(
mut name: String, mut name: String,
split_context: &mut SplitContext<'_>, split_context: &mut SplitContext<'_>,
) -> Result<()> { ) -> Result<()> {
let mut map = IndexMap::<_, Vec<ChunkItemWithInfo>>::new(); let mut map = FxIndexMap::<_, Vec<ChunkItemWithInfo>>::default();
for item in chunk_items { for item in chunk_items {
let (_, _, _, asset_ident) = &item; let (_, _, _, asset_ident) = &item;
let package_name = package_name(asset_ident); let package_name = package_name(asset_ident);
...@@ -261,7 +260,7 @@ async fn folder_split( ...@@ -261,7 +260,7 @@ async fn folder_split(
name: Cow<'_, str>, name: Cow<'_, str>,
split_context: &mut SplitContext<'_>, split_context: &mut SplitContext<'_>,
) -> Result<()> { ) -> Result<()> {
let mut map = IndexMap::<_, (_, Vec<ChunkItemWithInfo>)>::new(); let mut map = FxIndexMap::<_, (_, Vec<ChunkItemWithInfo>)>::default();
loop { loop {
for item in chunk_items { for item in chunk_items {
let (_, _, _, asset_ident) = &item; let (_, _, _, asset_ident) = &item;
...@@ -278,7 +277,7 @@ async fn folder_split( ...@@ -278,7 +277,7 @@ async fn folder_split(
if let Some(new_location) = new_location { if let Some(new_location) = new_location {
chunk_items = list; chunk_items = list;
location = new_location; location = new_location;
map = IndexMap::new(); map = FxIndexMap::default();
continue; continue;
} else { } else {
let mut key = format!("{}-{}", name, folder_name); let mut key = format!("{}-{}", name, folder_name);
......
use std::{cell::RefCell, mem::take, rc::Rc}; use std::{cell::RefCell, mem::take, rc::Rc};
use anyhow::Result; use anyhow::Result;
use indexmap::{IndexMap, IndexSet}; use turbo_tasks::{FxIndexMap, FxIndexSet, TryJoinIterExt};
use turbo_tasks::TryJoinIterExt;
#[derive(Debug, Default, Clone, Eq, PartialEq)] #[derive(Debug, Default, Clone, Eq, PartialEq)]
pub struct ContainmentTree<K, V> { pub struct ContainmentTree<K, V> {
...@@ -37,7 +36,7 @@ where ...@@ -37,7 +36,7 @@ where
let mut common_parents = values let mut common_parents = values
.iter() .iter()
.filter_map(|(key, _)| key.clone()) .filter_map(|(key, _)| key.clone())
.collect::<IndexSet<_>>(); .collect::<FxIndexSet<_>>();
Self::expand_common_parents(&mut common_parents).await?; Self::expand_common_parents(&mut common_parents).await?;
...@@ -68,7 +67,7 @@ where ...@@ -68,7 +67,7 @@ where
} }
/// Expand all common parents to include all their parents. /// Expand all common parents to include all their parents.
async fn expand_common_parents(common_parents: &mut IndexSet<K>) -> Result<()> { async fn expand_common_parents(common_parents: &mut FxIndexSet<K>) -> Result<()> {
// This is mutated while iterating, so we need to loop with index // This is mutated while iterating, so we need to loop with index
let mut i = 0; let mut i = 0;
while i < common_parents.len() { while i < common_parents.len() {
...@@ -81,7 +80,7 @@ where ...@@ -81,7 +80,7 @@ where
} }
/// Compute parent -> child relationships between common_parents. /// Compute parent -> child relationships between common_parents.
async fn compute_relationships(common_parents: &IndexSet<K>) -> Result<Vec<(Option<K>, K)>> { async fn compute_relationships(common_parents: &FxIndexSet<K>) -> Result<Vec<(Option<K>, K)>> {
common_parents common_parents
.iter() .iter()
.map(|key| { .map(|key| {
...@@ -107,8 +106,8 @@ where ...@@ -107,8 +106,8 @@ where
} }
/// Create the tree nodes. /// Create the tree nodes.
fn create_node_tree(common_parents: IndexSet<K>) -> IndexMap<K, Rc<RefCell<Node<K, V>>>> { fn create_node_tree(common_parents: FxIndexSet<K>) -> FxIndexMap<K, Rc<RefCell<Node<K, V>>>> {
let mut trees = IndexMap::<K, Rc<RefCell<Node<K, V>>>>::new(); let mut trees = FxIndexMap::<K, Rc<RefCell<Node<K, V>>>>::default();
for common_parent in common_parents { for common_parent in common_parents {
trees.insert( trees.insert(
common_parent.clone(), common_parent.clone(),
...@@ -124,7 +123,7 @@ where ...@@ -124,7 +123,7 @@ where
/// Add chunks to nodes. /// Add chunks to nodes.
fn add_values_to_tree( fn add_values_to_tree(
trees: &mut IndexMap<K, Rc<RefCell<Node<K, V>>>>, trees: &mut FxIndexMap<K, Rc<RefCell<Node<K, V>>>>,
values: Vec<(Option<K>, V)>, values: Vec<(Option<K>, V)>,
) -> Vec<V> { ) -> Vec<V> {
let mut orphan_values = Vec::new(); let mut orphan_values = Vec::new();
...@@ -146,7 +145,7 @@ where ...@@ -146,7 +145,7 @@ where
/// Nest each tree by relationship, compute the roots /// Nest each tree by relationship, compute the roots
fn treeify( fn treeify(
relationships: Vec<(Option<K>, K)>, relationships: Vec<(Option<K>, K)>,
trees: &IndexMap<K, Rc<RefCell<Node<K, V>>>>, trees: &FxIndexMap<K, Rc<RefCell<Node<K, V>>>>,
) -> Vec<Rc<RefCell<Node<K, V>>>> { ) -> Vec<Rc<RefCell<Node<K, V>>>> {
relationships relationships
.into_iter() .into_iter()
...@@ -163,7 +162,7 @@ where ...@@ -163,7 +162,7 @@ where
} }
/// Optimize tree by removing unnecessary nodes. /// Optimize tree by removing unnecessary nodes.
fn skip_unnecessary_nodes(trees: &mut IndexMap<K, Rc<RefCell<Node<K, V>>>>) { fn skip_unnecessary_nodes(trees: &mut FxIndexMap<K, Rc<RefCell<Node<K, V>>>>) {
for tree in trees.values_mut() { for tree in trees.values_mut() {
let mut tree = tree.borrow_mut(); let mut tree = tree.borrow_mut();
if tree.values.is_empty() && tree.children.len() == 1 { if tree.values.is_empty() && tree.children.len() == 1 {
......
...@@ -18,15 +18,14 @@ use std::{ ...@@ -18,15 +18,14 @@ use std::{
use anyhow::Result; use anyhow::Result;
use auto_hash_map::AutoSet; use auto_hash_map::AutoSet;
use indexmap::{IndexMap, IndexSet};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::{info_span, Span}; use tracing::{info_span, Span};
use turbo_tasks::{ use turbo_tasks::{
debug::ValueDebugFormat, debug::ValueDebugFormat,
graph::{AdjacencyMap, GraphTraversal, GraphTraversalResult, Visit, VisitControlFlow}, graph::{AdjacencyMap, GraphTraversal, GraphTraversalResult, Visit, VisitControlFlow},
trace::TraceRawVcs, trace::TraceRawVcs,
RcStr, ReadRef, ResolvedVc, TaskInput, TryFlatJoinIterExt, TryJoinIterExt, Upcast, FxIndexMap, FxIndexSet, RcStr, ReadRef, ResolvedVc, TaskInput, TryFlatJoinIterExt,
ValueToString, Vc, TryJoinIterExt, Upcast, ValueToString, Vc,
}; };
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_hash::DeterministicHash; use turbo_tasks_hash::DeterministicHash;
...@@ -187,12 +186,12 @@ pub trait ChunkableModuleReference: ModuleReference + ValueToString { ...@@ -187,12 +186,12 @@ pub trait ChunkableModuleReference: ModuleReference + ValueToString {
} }
} }
type AsyncInfo = IndexMap<Vc<Box<dyn ChunkItem>>, Vec<Vc<Box<dyn ChunkItem>>>>; type AsyncInfo = FxIndexMap<Vc<Box<dyn ChunkItem>>, Vec<Vc<Box<dyn ChunkItem>>>>;
pub struct ChunkContentResult { pub struct ChunkContentResult {
pub chunk_items: IndexSet<Vc<Box<dyn ChunkItem>>>, pub chunk_items: FxIndexSet<Vc<Box<dyn ChunkItem>>>,
pub async_modules: IndexSet<Vc<Box<dyn ChunkableModule>>>, pub async_modules: FxIndexSet<Vc<Box<dyn ChunkableModule>>>,
pub external_module_references: IndexSet<Vc<Box<dyn ModuleReference>>>, pub external_module_references: FxIndexSet<Vc<Box<dyn ModuleReference>>>,
/// A map from local module to all children from which the async module /// A map from local module to all children from which the async module
/// status is inherited /// status is inherited
pub forward_edges_inherit_async: AsyncInfo, pub forward_edges_inherit_async: AsyncInfo,
...@@ -610,12 +609,12 @@ async fn chunk_content_internal_parallel( ...@@ -610,12 +609,12 @@ async fn chunk_content_internal_parallel(
let graph_nodes: Vec<_> = traversal_result?.into_reverse_topological().collect(); let graph_nodes: Vec<_> = traversal_result?.into_reverse_topological().collect();
let mut chunk_items = IndexSet::new(); let mut chunk_items = FxIndexSet::default();
let mut async_modules = IndexSet::new(); let mut async_modules = FxIndexSet::default();
let mut external_module_references = IndexSet::new(); let mut external_module_references = FxIndexSet::default();
let mut forward_edges_inherit_async = IndexMap::new(); let mut forward_edges_inherit_async = FxIndexMap::default();
let mut local_back_edges_inherit_async = IndexMap::new(); let mut local_back_edges_inherit_async = FxIndexMap::default();
let mut available_async_modules_back_edges_inherit_async = IndexMap::new(); let mut available_async_modules_back_edges_inherit_async = FxIndexMap::default();
for graph_node in graph_nodes { for graph_node in graph_nodes {
match graph_node { match graph_node {
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, RcStr, ValueToString, Vc};
use turbo_tasks::{RcStr, ValueToString, Vc};
use turbo_tasks_hash::hash_xxh3_hash64; use turbo_tasks_hash::hash_xxh3_hash64;
use super::ModuleId; use super::ModuleId;
...@@ -30,11 +29,11 @@ impl ModuleIdStrategy for DevModuleIdStrategy { ...@@ -30,11 +29,11 @@ impl ModuleIdStrategy for DevModuleIdStrategy {
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct GlobalModuleIdStrategy { pub struct GlobalModuleIdStrategy {
module_id_map: IndexMap<RcStr, ModuleId>, module_id_map: FxIndexMap<RcStr, ModuleId>,
} }
impl GlobalModuleIdStrategy { impl GlobalModuleIdStrategy {
pub async fn new(module_id_map: IndexMap<RcStr, ModuleId>) -> Result<Vc<Self>> { pub async fn new(module_id_map: FxIndexMap<RcStr, ModuleId>) -> Result<Vc<Self>> {
Ok(GlobalModuleIdStrategy { module_id_map }.cell()) Ok(GlobalModuleIdStrategy { module_id_map }.cell())
} }
} }
......
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, RcStr, Vc};
use turbo_tasks::{RcStr, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use crate::environment::Environment; use crate::environment::Environment;
...@@ -79,7 +78,7 @@ macro_rules! definable_name_map_internal { ...@@ -79,7 +78,7 @@ macro_rules! definable_name_map_internal {
macro_rules! compile_time_defines { macro_rules! compile_time_defines {
($($more:tt)+) => { ($($more:tt)+) => {
{ {
let mut map = $crate::__private::IndexMap::new(); let mut map = $crate::__private::FxIndexMap::default();
$crate::definable_name_map_internal!(map, $($more)+); $crate::definable_name_map_internal!(map, $($more)+);
$crate::compile_time_info::CompileTimeDefines(map) $crate::compile_time_info::CompileTimeDefines(map)
} }
...@@ -90,7 +89,7 @@ macro_rules! compile_time_defines { ...@@ -90,7 +89,7 @@ macro_rules! compile_time_defines {
macro_rules! free_var_references { macro_rules! free_var_references {
($($more:tt)+) => { ($($more:tt)+) => {
{ {
let mut map = $crate::__private::IndexMap::new(); let mut map = $crate::__private::FxIndexMap::default();
$crate::definable_name_map_internal!(map, $($more)+); $crate::definable_name_map_internal!(map, $($more)+);
$crate::compile_time_info::FreeVarReferences(map) $crate::compile_time_info::FreeVarReferences(map)
} }
...@@ -164,12 +163,12 @@ impl From<String> for DefineableNameSegment { ...@@ -164,12 +163,12 @@ impl From<String> for DefineableNameSegment {
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct CompileTimeDefines(pub IndexMap<Vec<DefineableNameSegment>, CompileTimeDefineValue>); pub struct CompileTimeDefines(pub FxIndexMap<Vec<DefineableNameSegment>, CompileTimeDefineValue>);
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct CompileTimeDefinesIndividual( pub struct CompileTimeDefinesIndividual(
pub IndexMap<Vec<DefineableNameSegment>, Vc<CompileTimeDefineValue>>, pub FxIndexMap<Vec<DefineableNameSegment>, Vc<CompileTimeDefineValue>>,
); );
impl IntoIterator for CompileTimeDefines { impl IntoIterator for CompileTimeDefines {
...@@ -185,7 +184,7 @@ impl IntoIterator for CompileTimeDefines { ...@@ -185,7 +184,7 @@ impl IntoIterator for CompileTimeDefines {
impl CompileTimeDefines { impl CompileTimeDefines {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn empty() -> Vc<Self> { pub fn empty() -> Vc<Self> {
Vc::cell(IndexMap::new()) Vc::cell(FxIndexMap::default())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -237,19 +236,19 @@ impl From<CompileTimeDefineValue> for FreeVarReference { ...@@ -237,19 +236,19 @@ impl From<CompileTimeDefineValue> for FreeVarReference {
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct FreeVarReferences(pub IndexMap<Vec<DefineableNameSegment>, FreeVarReference>); pub struct FreeVarReferences(pub FxIndexMap<Vec<DefineableNameSegment>, FreeVarReference>);
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct FreeVarReferencesIndividual( pub struct FreeVarReferencesIndividual(
pub IndexMap<Vec<DefineableNameSegment>, Vc<FreeVarReference>>, pub FxIndexMap<Vec<DefineableNameSegment>, Vc<FreeVarReference>>,
); );
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl FreeVarReferences { impl FreeVarReferences {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn empty() -> Vc<Self> { pub fn empty() -> Vc<Self> {
Vc::cell(IndexMap::new()) Vc::cell(FxIndexMap::default())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -333,7 +332,7 @@ impl CompileTimeInfoBuilder { ...@@ -333,7 +332,7 @@ impl CompileTimeInfoBuilder {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use indexmap::IndexMap; use turbo_tasks::FxIndexMap;
use crate::compile_time_info::{DefineableNameSegment, FreeVarReference, FreeVarReferences}; use crate::compile_time_info::{DefineableNameSegment, FreeVarReference, FreeVarReferences};
...@@ -349,7 +348,7 @@ mod test { ...@@ -349,7 +348,7 @@ mod test {
export: Some("Buffer".into()), export: Some("Buffer".into()),
}, },
), ),
FreeVarReferences(IndexMap::from_iter(vec![ FreeVarReferences(FxIndexMap::from_iter(vec![
(vec!["FOO".into()], FreeVarReference::Value("bar".into())), (vec!["FOO".into()], FreeVarReference::Value("bar".into())),
(vec!["FOO".into()], FreeVarReference::Value(false.into())), (vec!["FOO".into()], FreeVarReference::Value(false.into())),
( (
...@@ -372,7 +371,7 @@ mod test { ...@@ -372,7 +371,7 @@ mod test {
typeof x.y = "b", typeof x.y = "b",
typeof x.y.z = "c" typeof x.y.z = "c"
), ),
FreeVarReferences(IndexMap::from_iter(vec![ FreeVarReferences(FxIndexMap::from_iter(vec![
( (
vec!["x".into(), DefineableNameSegment::TypeOf], vec!["x".into(), DefineableNameSegment::TypeOf],
FreeVarReference::Value("a".into()) FreeVarReference::Value("a".into())
......
...@@ -2,15 +2,14 @@ use std::cmp::Ordering; ...@@ -2,15 +2,14 @@ use std::cmp::Ordering;
use anyhow::Result; use anyhow::Result;
use async_trait::async_trait; use async_trait::async_trait;
use indexmap::IndexMap; use turbo_tasks::{emit, CollectiblesSource, FxIndexMap, RcStr, Upcast, Vc};
use turbo_tasks::{emit, CollectiblesSource, RcStr, Upcast, Vc};
#[turbo_tasks::value(serialization = "none")] #[turbo_tasks::value(serialization = "none")]
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct PlainDiagnostic { pub struct PlainDiagnostic {
pub category: RcStr, pub category: RcStr,
pub name: RcStr, pub name: RcStr,
pub payload: IndexMap<RcStr, RcStr>, pub payload: FxIndexMap<RcStr, RcStr>,
} }
impl Ord for PlainDiagnostic { impl Ord for PlainDiagnostic {
...@@ -44,7 +43,7 @@ impl PartialOrd for PlainDiagnostic { ...@@ -44,7 +43,7 @@ impl PartialOrd for PlainDiagnostic {
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct DiagnosticPayload(pub IndexMap<RcStr, RcStr>); pub struct DiagnosticPayload(pub FxIndexMap<RcStr, RcStr>);
/// An arbitrary payload can be used to analyze, diagnose /// An arbitrary payload can be used to analyze, diagnose
/// Turbopack's behavior. /// Turbopack's behavior.
......
...@@ -3,13 +3,12 @@ pub mod output_asset; ...@@ -3,13 +3,12 @@ pub mod output_asset;
pub mod source; pub mod source;
pub mod utils; pub mod utils;
use indexmap::IndexSet; use turbo_tasks::{FxIndexSet, RcStr, Vc};
use turbo_tasks::{RcStr, Vc};
type VcDynIntrospectable = Vc<Box<dyn Introspectable>>; type VcDynIntrospectable = Vc<Box<dyn Introspectable>>;
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct IntrospectableChildren(IndexSet<(Vc<RcStr>, VcDynIntrospectable)>); pub struct IntrospectableChildren(FxIndexSet<(Vc<RcStr>, VcDynIntrospectable)>);
#[turbo_tasks::value_trait] #[turbo_tasks::value_trait]
pub trait Introspectable { pub trait Introspectable {
...@@ -21,6 +20,6 @@ pub trait Introspectable { ...@@ -21,6 +20,6 @@ pub trait Introspectable {
Vc::<RcStr>::default() Vc::<RcStr>::default()
} }
fn children(self: Vc<Self>) -> Vc<IntrospectableChildren> { fn children(self: Vc<Self>) -> Vc<IntrospectableChildren> {
Vc::cell(IndexSet::new()) Vc::cell(FxIndexSet::default())
} }
} }
use anyhow::Result; use anyhow::Result;
use indexmap::IndexSet; use turbo_tasks::{FxIndexSet, RcStr, Vc};
use turbo_tasks::{RcStr, Vc};
use turbo_tasks_fs::FileContent; use turbo_tasks_fs::FileContent;
use super::{ use super::{
...@@ -62,7 +61,7 @@ pub async fn children_from_module_references( ...@@ -62,7 +61,7 @@ pub async fn children_from_module_references(
references: Vc<ModuleReferences>, references: Vc<ModuleReferences>,
) -> Result<Vc<IntrospectableChildren>> { ) -> Result<Vc<IntrospectableChildren>> {
let key = reference_ty(); let key = reference_ty();
let mut children = IndexSet::new(); let mut children = FxIndexSet::default();
let references = references.await?; let references = references.await?;
for reference in &*references { for reference in &*references {
let mut key = key; let mut key = key;
...@@ -107,7 +106,7 @@ pub async fn children_from_output_assets( ...@@ -107,7 +106,7 @@ pub async fn children_from_output_assets(
references: Vc<OutputAssets>, references: Vc<OutputAssets>,
) -> Result<Vc<IntrospectableChildren>> { ) -> Result<Vc<IntrospectableChildren>> {
let key = reference_ty(); let key = reference_ty();
let mut children = IndexSet::new(); let mut children = FxIndexSet::default();
let references = references.await?; let references = references.await?;
for &reference in &*references { for &reference in &*references {
children.insert((key, IntrospectableOutputAsset::new(Vc::upcast(reference)))); children.insert((key, IntrospectableOutputAsset::new(Vc::upcast(reference))));
......
...@@ -49,7 +49,7 @@ pub const SOURCE_MAP_PREFIX: &str = "turbopack://"; ...@@ -49,7 +49,7 @@ pub const SOURCE_MAP_PREFIX: &str = "turbopack://";
#[doc(hidden)] #[doc(hidden)]
pub mod __private { pub mod __private {
pub use indexmap::IndexMap; pub use turbo_tasks::FxIndexMap;
} }
pub fn register() { pub fn register() {
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexSet; use turbo_tasks::{FxIndexSet, Vc};
use turbo_tasks::Vc;
use crate::{asset::Asset, ident::AssetIdent}; use crate::{asset::Asset, ident::AssetIdent};
...@@ -38,7 +37,7 @@ impl OutputAssets { ...@@ -38,7 +37,7 @@ impl OutputAssets {
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn concatenate(&self, other: Vc<Self>) -> Result<Vc<Self>> { pub async fn concatenate(&self, other: Vc<Self>) -> Result<Vc<Self>> {
let mut assets: IndexSet<_> = self.0.iter().copied().collect(); let mut assets: FxIndexSet<_> = self.0.iter().copied().collect();
assets.extend(other.await?.iter().copied()); assets.extend(other.await?.iter().copied());
Ok(Vc::cell(assets.into_iter().collect())) Ok(Vc::cell(assets.into_iter().collect()))
} }
...@@ -52,7 +51,7 @@ impl OutputAssets { ...@@ -52,7 +51,7 @@ impl OutputAssets {
/// A set of [OutputAsset]s /// A set of [OutputAsset]s
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct OutputAssetsSet(IndexSet<Vc<Box<dyn OutputAsset>>>); pub struct OutputAssetsSet(FxIndexSet<Vc<Box<dyn OutputAsset>>>);
// TODO All Vc::try_resolve_downcast::<Box<dyn OutputAsset>> calls should be // TODO All Vc::try_resolve_downcast::<Box<dyn OutputAsset>> calls should be
// removed // removed
use std::collections::{HashSet, VecDeque}; use std::collections::{HashSet, VecDeque};
use anyhow::Result; use anyhow::Result;
use indexmap::IndexSet;
use turbo_tasks::{ use turbo_tasks::{
graph::{AdjacencyMap, GraphTraversal}, graph::{AdjacencyMap, GraphTraversal},
RcStr, TryJoinIterExt, ValueToString, Vc, FxIndexSet, RcStr, TryJoinIterExt, ValueToString, Vc,
}; };
use crate::{ use crate::{
...@@ -147,7 +146,7 @@ pub async fn referenced_modules_and_affecting_sources( ...@@ -147,7 +146,7 @@ pub async fn referenced_modules_and_affecting_sources(
module: Vc<Box<dyn Module>>, module: Vc<Box<dyn Module>>,
) -> Result<Vc<Modules>> { ) -> Result<Vc<Modules>> {
let references_set = module.references().await?; let references_set = module.references().await?;
let mut modules = IndexSet::new(); let mut modules = FxIndexSet::default();
let resolve_results = references_set let resolve_results = references_set
.iter() .iter()
.map(|r| r.resolve_reference()) .map(|r| r.resolve_reference())
...@@ -161,7 +160,7 @@ pub async fn referenced_modules_and_affecting_sources( ...@@ -161,7 +160,7 @@ pub async fn referenced_modules_and_affecting_sources(
.map(|source| Vc::upcast(RawModule::new(source))), .map(|source| Vc::upcast(RawModule::new(source))),
); );
} }
let mut resolved_modules = IndexSet::new(); let mut resolved_modules = FxIndexSet::default();
for module in modules { for module in modules {
resolved_modules.insert(module.resolve().await?); resolved_modules.insert(module.resolve().await?);
} }
......
use std::fmt::Display; use std::fmt::Display;
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, RcStr, Vc};
use turbo_tasks::{RcStr, Vc};
use crate::{module::Module, resolve::ModulePart}; use crate::{module::Module, resolve::ModulePart};
...@@ -11,13 +10,13 @@ use crate::{module::Module, resolve::ModulePart}; ...@@ -11,13 +10,13 @@ use crate::{module::Module, resolve::ModulePart};
/// ///
/// Name is usually in UPPER_CASE to make it clear that this is an inner asset. /// Name is usually in UPPER_CASE to make it clear that this is an inner asset.
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct InnerAssets(IndexMap<RcStr, Vc<Box<dyn Module>>>); pub struct InnerAssets(FxIndexMap<RcStr, Vc<Box<dyn Module>>>);
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl InnerAssets { impl InnerAssets {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn empty() -> Vc<Self> { pub fn empty() -> Vc<Self> {
Vc::cell(IndexMap::new()) Vc::cell(FxIndexMap::default())
} }
} }
......
...@@ -7,10 +7,12 @@ use std::{ ...@@ -7,10 +7,12 @@ use std::{
}; };
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::{indexmap, IndexMap, IndexSet};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::{Instrument, Level}; use tracing::{Instrument, Level};
use turbo_tasks::{trace::TraceRawVcs, RcStr, TaskInput, TryJoinIterExt, Value, ValueToString, Vc}; use turbo_tasks::{
fxindexmap, fxindexset, trace::TraceRawVcs, FxIndexMap, RcStr, TaskInput, TryJoinIterExt,
Value, ValueToString, Vc,
};
use turbo_tasks_fs::{ use turbo_tasks_fs::{
util::normalize_request, FileSystemEntryType, FileSystemPath, RealPathResult, util::normalize_request, FileSystemEntryType, FileSystemPath, RealPathResult,
}; };
...@@ -74,7 +76,7 @@ pub enum ModuleResolveResultItem { ...@@ -74,7 +76,7 @@ pub enum ModuleResolveResultItem {
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct ModuleResolveResult { pub struct ModuleResolveResult {
pub primary: IndexMap<RequestKey, ModuleResolveResultItem>, pub primary: FxIndexMap<RequestKey, ModuleResolveResultItem>,
pub affecting_sources: Vec<Vc<Box<dyn Source>>>, pub affecting_sources: Vec<Vc<Box<dyn Source>>>,
} }
...@@ -87,7 +89,7 @@ impl Default for ModuleResolveResult { ...@@ -87,7 +89,7 @@ impl Default for ModuleResolveResult {
impl ModuleResolveResult { impl ModuleResolveResult {
pub fn unresolveable() -> Self { pub fn unresolveable() -> Self {
ModuleResolveResult { ModuleResolveResult {
primary: IndexMap::new(), primary: FxIndexMap::default(),
affecting_sources: Vec::new(), affecting_sources: Vec::new(),
} }
} }
...@@ -96,7 +98,7 @@ impl ModuleResolveResult { ...@@ -96,7 +98,7 @@ impl ModuleResolveResult {
affecting_sources: Vec<Vc<Box<dyn Source>>>, affecting_sources: Vec<Vc<Box<dyn Source>>>,
) -> ModuleResolveResult { ) -> ModuleResolveResult {
ModuleResolveResult { ModuleResolveResult {
primary: IndexMap::new(), primary: FxIndexMap::default(),
affecting_sources, affecting_sources,
} }
} }
...@@ -107,7 +109,7 @@ impl ModuleResolveResult { ...@@ -107,7 +109,7 @@ impl ModuleResolveResult {
pub fn ignored_with_key(request_key: RequestKey) -> ModuleResolveResult { pub fn ignored_with_key(request_key: RequestKey) -> ModuleResolveResult {
ModuleResolveResult { ModuleResolveResult {
primary: indexmap! { request_key => ModuleResolveResultItem::Ignore }, primary: fxindexmap! { request_key => ModuleResolveResultItem::Ignore },
affecting_sources: Vec::new(), affecting_sources: Vec::new(),
} }
} }
...@@ -121,7 +123,7 @@ impl ModuleResolveResult { ...@@ -121,7 +123,7 @@ impl ModuleResolveResult {
module: Vc<Box<dyn Module>>, module: Vc<Box<dyn Module>>,
) -> ModuleResolveResult { ) -> ModuleResolveResult {
ModuleResolveResult { ModuleResolveResult {
primary: indexmap! { request_key => ModuleResolveResultItem::Module(module) }, primary: fxindexmap! { request_key => ModuleResolveResultItem::Module(module) },
affecting_sources: Vec::new(), affecting_sources: Vec::new(),
} }
} }
...@@ -131,7 +133,7 @@ impl ModuleResolveResult { ...@@ -131,7 +133,7 @@ impl ModuleResolveResult {
output_asset: Vc<Box<dyn OutputAsset>>, output_asset: Vc<Box<dyn OutputAsset>>,
) -> ModuleResolveResult { ) -> ModuleResolveResult {
ModuleResolveResult { ModuleResolveResult {
primary: indexmap! { request_key => ModuleResolveResultItem::OutputAsset(output_asset) }, primary: fxindexmap! { request_key => ModuleResolveResultItem::OutputAsset(output_asset) },
affecting_sources: Vec::new(), affecting_sources: Vec::new(),
} }
} }
...@@ -347,7 +349,7 @@ impl ModuleResolveResult { ...@@ -347,7 +349,7 @@ impl ModuleResolveResult {
let second = second.resolve().await?; let second = second.resolve().await?;
// We have at least two items, so we need to deduplicate them // We have at least two items, so we need to deduplicate them
let mut set = IndexSet::from([first, second]); let mut set = fxindexset![first, second];
for module in self.primary_modules_iter() { for module in self.primary_modules_iter() {
set.insert(module.resolve().await?); set.insert(module.resolve().await?);
} }
...@@ -445,7 +447,7 @@ impl RequestKey { ...@@ -445,7 +447,7 @@ impl RequestKey {
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct ResolveResult { pub struct ResolveResult {
pub primary: IndexMap<RequestKey, ResolveResultItem>, pub primary: FxIndexMap<RequestKey, ResolveResultItem>,
pub affecting_sources: Vec<Vc<Box<dyn Source>>>, pub affecting_sources: Vec<Vc<Box<dyn Source>>>,
} }
...@@ -512,7 +514,7 @@ impl ValueToString for ResolveResult { ...@@ -512,7 +514,7 @@ impl ValueToString for ResolveResult {
impl ResolveResult { impl ResolveResult {
pub fn unresolveable() -> Self { pub fn unresolveable() -> Self {
ResolveResult { ResolveResult {
primary: IndexMap::new(), primary: FxIndexMap::default(),
affecting_sources: Vec::new(), affecting_sources: Vec::new(),
} }
} }
...@@ -521,7 +523,7 @@ impl ResolveResult { ...@@ -521,7 +523,7 @@ impl ResolveResult {
affecting_sources: Vec<Vc<Box<dyn Source>>>, affecting_sources: Vec<Vc<Box<dyn Source>>>,
) -> ResolveResult { ) -> ResolveResult {
ResolveResult { ResolveResult {
primary: IndexMap::new(), primary: FxIndexMap::default(),
affecting_sources, affecting_sources,
} }
} }
...@@ -532,7 +534,7 @@ impl ResolveResult { ...@@ -532,7 +534,7 @@ impl ResolveResult {
pub fn primary_with_key(request_key: RequestKey, result: ResolveResultItem) -> ResolveResult { pub fn primary_with_key(request_key: RequestKey, result: ResolveResultItem) -> ResolveResult {
ResolveResult { ResolveResult {
primary: indexmap! { request_key => result }, primary: fxindexmap! { request_key => result },
affecting_sources: Vec::new(), affecting_sources: Vec::new(),
} }
} }
...@@ -542,8 +544,10 @@ impl ResolveResult { ...@@ -542,8 +544,10 @@ impl ResolveResult {
result: ResolveResultItem, result: ResolveResultItem,
affecting_sources: Vec<Vc<Box<dyn Source>>>, affecting_sources: Vec<Vc<Box<dyn Source>>>,
) -> ResolveResult { ) -> ResolveResult {
let mut primary = FxIndexMap::with_capacity_and_hasher(1, Default::default());
primary.insert(request_key, result);
ResolveResult { ResolveResult {
primary: indexmap! { request_key => result }, primary,
affecting_sources, affecting_sources,
} }
} }
...@@ -553,8 +557,10 @@ impl ResolveResult { ...@@ -553,8 +557,10 @@ impl ResolveResult {
} }
pub fn source_with_key(request_key: RequestKey, source: Vc<Box<dyn Source>>) -> ResolveResult { pub fn source_with_key(request_key: RequestKey, source: Vc<Box<dyn Source>>) -> ResolveResult {
let mut primary = FxIndexMap::with_capacity_and_hasher(1, Default::default());
primary.insert(request_key, ResolveResultItem::Source(source));
ResolveResult { ResolveResult {
primary: indexmap! { request_key => ResolveResultItem::Source(source) }, primary,
affecting_sources: Vec::new(), affecting_sources: Vec::new(),
} }
} }
...@@ -564,8 +570,10 @@ impl ResolveResult { ...@@ -564,8 +570,10 @@ impl ResolveResult {
source: Vc<Box<dyn Source>>, source: Vc<Box<dyn Source>>,
affecting_sources: Vec<Vc<Box<dyn Source>>>, affecting_sources: Vec<Vc<Box<dyn Source>>>,
) -> ResolveResult { ) -> ResolveResult {
let mut primary = FxIndexMap::with_capacity_and_hasher(1, Default::default());
primary.insert(request_key, ResolveResultItem::Source(source));
ResolveResult { ResolveResult {
primary: indexmap! { request_key => ResolveResultItem::Source(source) }, primary,
affecting_sources, affecting_sources,
} }
} }
...@@ -1526,7 +1534,7 @@ async fn handle_after_resolve_plugins( ...@@ -1526,7 +1534,7 @@ async fn handle_after_resolve_plugins(
let mut changed = false; let mut changed = false;
let result_value = result.await?; let result_value = result.await?;
let mut new_primary = IndexMap::new(); let mut new_primary = FxIndexMap::default();
let mut new_affecting_sources = Vec::new(); let mut new_affecting_sources = Vec::new();
for (key, primary) in result_value.primary.iter() { for (key, primary) in result_value.primary.iter() {
......
use std::{collections::BTreeMap, future::Future, pin::Pin}; use std::{collections::BTreeMap, future::Future, pin::Pin};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::IndexSet;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{ use turbo_tasks::{
debug::ValueDebugFormat, trace::TraceRawVcs, RcStr, TryJoinIterExt, Value, ValueToString, Vc, debug::ValueDebugFormat, trace::TraceRawVcs, FxIndexSet, RcStr, TryJoinIterExt, Value,
ValueToString, Vc,
}; };
use turbo_tasks_fs::{glob::Glob, FileSystemPath}; use turbo_tasks_fs::{glob::Glob, FileSystemPath};
...@@ -22,7 +22,7 @@ pub struct LockedVersions {} ...@@ -22,7 +22,7 @@ pub struct LockedVersions {}
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
#[derive(Debug)] #[derive(Debug)]
pub struct ExcludedExtensions(pub IndexSet<RcStr>); pub struct ExcludedExtensions(pub FxIndexSet<RcStr>);
/// A location where to resolve modules. /// A location where to resolve modules.
#[derive( #[derive(
......
...@@ -5,10 +5,9 @@ use std::{ ...@@ -5,10 +5,9 @@ use std::{
}; };
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use turbo_tasks::RcStr; use turbo_tasks::{FxIndexMap, RcStr};
use super::{ use super::{
alias_map::{AliasMap, AliasMapIter, AliasPattern, AliasTemplate}, alias_map::{AliasMap, AliasMapIter, AliasPattern, AliasTemplate},
...@@ -525,10 +524,10 @@ fn expand_folder_shorthand(key: &str, value: &mut SubpathValue) -> Result<AliasP ...@@ -525,10 +524,10 @@ fn expand_folder_shorthand(key: &str, value: &mut SubpathValue) -> Result<AliasP
#[derive(Default)] #[derive(Default)]
pub struct ResolveAliasMap(#[turbo_tasks(trace_ignore)] AliasMap<SubpathValue>); pub struct ResolveAliasMap(#[turbo_tasks(trace_ignore)] AliasMap<SubpathValue>);
impl TryFrom<&IndexMap<RcStr, Value>> for ResolveAliasMap { impl TryFrom<&FxIndexMap<RcStr, Value>> for ResolveAliasMap {
type Error = anyhow::Error; type Error = anyhow::Error;
fn try_from(object: &IndexMap<RcStr, Value>) -> Result<Self> { fn try_from(object: &FxIndexMap<RcStr, Value>) -> Result<Self> {
let mut map = AliasMap::new(); let mut map = AliasMap::new();
for (key, value) in object.iter() { for (key, value) in object.iter() {
......
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::IndexSet; use turbo_tasks::{FxIndexSet, RcStr, ValueToString, Vc};
use turbo_tasks::{RcStr, ValueToString, Vc};
use turbo_tasks_fs::File; use turbo_tasks_fs::File;
use crate::{ use crate::{
...@@ -83,7 +82,7 @@ impl Introspectable for SourceMapAsset { ...@@ -83,7 +82,7 @@ impl Introspectable for SourceMapAsset {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn children(&self) -> Result<Vc<IntrospectableChildren>> { async fn children(&self) -> Result<Vc<IntrospectableChildren>> {
let mut children = IndexSet::new(); let mut children = FxIndexSet::default();
if let Some(asset) = Vc::try_resolve_sidecast::<Box<dyn Introspectable>>(self.asset).await? if let Some(asset) = Vc::try_resolve_sidecast::<Box<dyn Introspectable>>(self.asset).await?
{ {
children.insert((Vc::cell("asset".into()), asset)); children.insert((Vc::cell("asset".into()), asset));
......
...@@ -4,8 +4,7 @@ pub mod source_map; ...@@ -4,8 +4,7 @@ pub mod source_map;
use std::fmt::Write; use std::fmt::Write;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::IndexSet; use turbo_tasks::{FxIndexSet, RcStr, TryJoinIterExt, Value, ValueDefault, ValueToString, Vc};
use turbo_tasks::{RcStr, TryJoinIterExt, Value, ValueDefault, ValueToString, Vc};
use turbo_tasks_fs::{rope::Rope, File, FileSystem}; use turbo_tasks_fs::{rope::Rope, File, FileSystem};
use turbopack_core::{ use turbopack_core::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
...@@ -63,7 +62,7 @@ impl CssChunk { ...@@ -63,7 +62,7 @@ impl CssChunk {
let mut code = CodeBuilder::default(); let mut code = CodeBuilder::default();
let mut body = CodeBuilder::default(); let mut body = CodeBuilder::default();
let mut external_imports = IndexSet::new(); let mut external_imports = FxIndexSet::default();
for css_item in &this.content.await?.chunk_items { for css_item in &this.content.await?.chunk_items {
let id = &*css_item.id().await?; let id = &*css_item.id().await?;
......
use std::{fmt::Write, sync::Arc}; use std::{fmt::Write, sync::Arc};
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use indexmap::IndexMap;
use indoc::formatdoc; use indoc::formatdoc;
use lightningcss::css_modules::CssModuleReference; use lightningcss::css_modules::CssModuleReference;
use swc_core::common::{BytePos, FileName, LineCol, SourceMap}; use swc_core::common::{BytePos, FileName, LineCol, SourceMap};
use turbo_tasks::{RcStr, Value, ValueToString, Vc}; use turbo_tasks::{FxIndexMap, RcStr, Value, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{ use turbopack_core::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
...@@ -144,7 +143,7 @@ enum ModuleCssClass { ...@@ -144,7 +143,7 @@ enum ModuleCssClass {
/// 3. class3: [Local("exported_class3), Import("class4", "./other.module.css")] /// 3. class3: [Local("exported_class3), Import("class4", "./other.module.css")]
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct ModuleCssClasses(IndexMap<String, Vec<ModuleCssClass>>); struct ModuleCssClasses(FxIndexMap<String, Vec<ModuleCssClass>>);
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ModuleCssAsset { impl ModuleCssAsset {
...@@ -165,7 +164,7 @@ impl ModuleCssAsset { ...@@ -165,7 +164,7 @@ impl ModuleCssAsset {
.context("inner asset should be CSS processable")?; .context("inner asset should be CSS processable")?;
let result = inner.get_css_with_placeholder().await?; let result = inner.get_css_with_placeholder().await?;
let mut classes = IndexMap::default(); let mut classes = FxIndexMap::default();
// TODO(alexkirsz) Should we report an error on parse error here? // TODO(alexkirsz) Should we report an error on parse error here?
if let CssWithPlaceholderResult::Ok { if let CssWithPlaceholderResult::Ok {
......
...@@ -4,7 +4,6 @@ use std::{ ...@@ -4,7 +4,6 @@ use std::{
}; };
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use indexmap::IndexMap;
use lightningcss::{ use lightningcss::{
css_modules::{CssModuleExport, CssModuleExports, CssModuleReference, Pattern, Segment}, css_modules::{CssModuleExport, CssModuleExports, CssModuleReference, Pattern, Segment},
dependencies::{Dependency, ImportDependency, Location, SourceRange}, dependencies::{Dependency, ImportDependency, Location, SourceRange},
...@@ -36,7 +35,7 @@ use swc_core::{ ...@@ -36,7 +35,7 @@ use swc_core::{
}, },
}; };
use tracing::Instrument; use tracing::Instrument;
use turbo_tasks::{RcStr, ValueToString, Vc}; use turbo_tasks::{FxIndexMap, RcStr, ValueToString, Vc};
use turbo_tasks_fs::{FileContent, FileSystemPath}; use turbo_tasks_fs::{FileContent, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
...@@ -328,7 +327,7 @@ pub enum CssWithPlaceholderResult { ...@@ -328,7 +327,7 @@ pub enum CssWithPlaceholderResult {
url_references: Vc<UnresolvedUrlReferences>, url_references: Vc<UnresolvedUrlReferences>,
#[turbo_tasks(trace_ignore)] #[turbo_tasks(trace_ignore)]
exports: Option<IndexMap<String, CssModuleExport>>, exports: Option<FxIndexMap<String, CssModuleExport>>,
#[turbo_tasks(trace_ignore)] #[turbo_tasks(trace_ignore)]
placeholders: HashMap<String, Url<'static>>, placeholders: HashMap<String, Url<'static>>,
...@@ -383,7 +382,7 @@ pub async fn process_css_with_placeholder( ...@@ -383,7 +382,7 @@ pub async fn process_css_with_placeholder(
stylesheet.to_css(cm.clone(), &code, MinifyType::NoMinify, false, false, false)?; stylesheet.to_css(cm.clone(), &code, MinifyType::NoMinify, false, false, false)?;
let exports = result.exports.map(|exports| { let exports = result.exports.map(|exports| {
let mut exports = exports.into_iter().collect::<IndexMap<_, _>>(); let mut exports = exports.into_iter().collect::<FxIndexMap<_, _>>();
exports.sort_keys(); exports.sort_keys();
......
use std::fmt::{Display, Formatter}; use std::fmt::{Display, Formatter};
use hyper::{Method, Uri}; use hyper::{Method, Uri};
use indexmap::IndexSet; use turbo_tasks::{util::StaticOrArc, FxIndexSet, InvalidationReason, InvalidationReasonKind};
use turbo_tasks::{util::StaticOrArc, InvalidationReason, InvalidationReasonKind};
/// Computation was caused by a request to the server. /// Computation was caused by a request to the server.
#[derive(PartialEq, Eq, Hash)] #[derive(PartialEq, Eq, Hash)]
...@@ -32,7 +31,7 @@ static SERVER_REQUEST_KIND: ServerRequestKind = ServerRequestKind; ...@@ -32,7 +31,7 @@ static SERVER_REQUEST_KIND: ServerRequestKind = ServerRequestKind;
impl InvalidationReasonKind for ServerRequestKind { impl InvalidationReasonKind for ServerRequestKind {
fn fmt( fn fmt(
&self, &self,
reasons: &IndexSet<StaticOrArc<dyn InvalidationReason>>, reasons: &FxIndexSet<StaticOrArc<dyn InvalidationReason>>,
f: &mut Formatter<'_>, f: &mut Formatter<'_>,
) -> std::fmt::Result { ) -> std::fmt::Result {
let example = reasons let example = reasons
...@@ -79,7 +78,7 @@ static SERVER_REQUEST_SIDE_EFFECTS_KIND: ServerRequestSideEffectsKind = ...@@ -79,7 +78,7 @@ static SERVER_REQUEST_SIDE_EFFECTS_KIND: ServerRequestSideEffectsKind =
impl InvalidationReasonKind for ServerRequestSideEffectsKind { impl InvalidationReasonKind for ServerRequestSideEffectsKind {
fn fmt( fn fmt(
&self, &self,
reasons: &IndexSet<StaticOrArc<dyn InvalidationReason>>, reasons: &FxIndexSet<StaticOrArc<dyn InvalidationReason>>,
f: &mut Formatter<'_>, f: &mut Formatter<'_>,
) -> std::fmt::Result { ) -> std::fmt::Result {
let example = reasons let example = reasons
......
...@@ -4,8 +4,10 @@ use std::{ ...@@ -4,8 +4,10 @@ use std::{
}; };
use anyhow::Result; use anyhow::Result;
use indexmap::{indexset, IndexMap, IndexSet}; use turbo_tasks::{
use turbo_tasks::{Completion, RcStr, State, TryJoinIterExt, Value, ValueToString, Vc}; fxindexset, Completion, FxIndexMap, FxIndexSet, RcStr, State, TryJoinIterExt, Value,
ValueToString, Vc,
};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{ use turbopack_core::{
asset::Asset, asset::Asset,
...@@ -20,7 +22,7 @@ use super::{ ...@@ -20,7 +22,7 @@ use super::{
}; };
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
struct OutputAssetsMap(IndexMap<RcStr, Vc<Box<dyn OutputAsset>>>); struct OutputAssetsMap(FxIndexMap<RcStr, Vc<Box<dyn OutputAsset>>>);
type ExpandedState = State<HashSet<RcStr>>; type ExpandedState = State<HashSet<RcStr>>;
...@@ -41,7 +43,7 @@ impl AssetGraphContentSource { ...@@ -41,7 +43,7 @@ impl AssetGraphContentSource {
) -> Vc<Self> { ) -> Vc<Self> {
Self::cell(AssetGraphContentSource { Self::cell(AssetGraphContentSource {
root_path, root_path,
root_assets: Vc::cell(indexset! { root_asset }), root_assets: Vc::cell(fxindexset! { root_asset }),
expanded: None, expanded: None,
}) })
} }
...@@ -55,7 +57,7 @@ impl AssetGraphContentSource { ...@@ -55,7 +57,7 @@ impl AssetGraphContentSource {
) -> Vc<Self> { ) -> Vc<Self> {
Self::cell(AssetGraphContentSource { Self::cell(AssetGraphContentSource {
root_path, root_path,
root_assets: Vc::cell(indexset! { root_asset }), root_assets: Vc::cell(fxindexset! { root_asset }),
expanded: Some(State::new(HashSet::new())), expanded: Some(State::new(HashSet::new())),
}) })
} }
...@@ -101,11 +103,11 @@ impl AssetGraphContentSource { ...@@ -101,11 +103,11 @@ impl AssetGraphContentSource {
} }
async fn expand( async fn expand(
root_assets: &IndexSet<Vc<Box<dyn OutputAsset>>>, root_assets: &FxIndexSet<Vc<Box<dyn OutputAsset>>>,
root_path: &FileSystemPath, root_path: &FileSystemPath,
expanded: Option<&ExpandedState>, expanded: Option<&ExpandedState>,
) -> Result<IndexMap<RcStr, Vc<Box<dyn OutputAsset>>>> { ) -> Result<FxIndexMap<RcStr, Vc<Box<dyn OutputAsset>>>> {
let mut map = IndexMap::new(); let mut map = FxIndexMap::default();
let mut assets = Vec::new(); let mut assets = Vec::new();
let mut queue = VecDeque::with_capacity(32); let mut queue = VecDeque::with_capacity(32);
let mut assets_set = HashSet::new(); let mut assets_set = HashSet::new();
......
use std::{fmt::Write, mem::replace}; use std::{fmt::Write, mem::replace};
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, RcStr, TaskInput, TryJoinIterExt, ValueToString, Vc}; use turbo_tasks::{
fxindexmap, trace::TraceRawVcs, FxIndexMap, RcStr, TaskInput, TryJoinIterExt, ValueToString, Vc,
};
use super::{GetContentSourceContent, GetContentSourceContents}; use super::{GetContentSourceContent, GetContentSourceContents};
...@@ -99,7 +100,7 @@ impl RouteTrees { ...@@ -99,7 +100,7 @@ impl RouteTrees {
pub struct RouteTree { pub struct RouteTree {
base: Vec<BaseSegment>, base: Vec<BaseSegment>,
sources: Vec<Vc<Box<dyn GetContentSourceContent>>>, sources: Vec<Vc<Box<dyn GetContentSourceContent>>>,
static_segments: IndexMap<RcStr, Vc<RouteTree>>, static_segments: FxIndexMap<RcStr, Vc<RouteTree>>,
dynamic_segments: Vec<Vc<RouteTree>>, dynamic_segments: Vec<Vc<RouteTree>>,
catch_all_sources: Vec<Vc<Box<dyn GetContentSourceContent>>>, catch_all_sources: Vec<Vc<Box<dyn GetContentSourceContent>>>,
fallback_sources: Vec<Vc<Box<dyn GetContentSourceContent>>>, fallback_sources: Vec<Vc<Box<dyn GetContentSourceContent>>>,
...@@ -138,7 +139,7 @@ impl RouteTree { ...@@ -138,7 +139,7 @@ impl RouteTree {
} }
async fn flat_merge(&mut self, others: impl IntoIterator<Item = &Self> + '_) -> Result<()> { async fn flat_merge(&mut self, others: impl IntoIterator<Item = &Self> + '_) -> Result<()> {
let mut static_segments = IndexMap::new(); let mut static_segments = FxIndexMap::default();
for other in others { for other in others {
debug_assert_eq!(self.base, other.base); debug_assert_eq!(self.base, other.base);
self.sources.extend(other.sources.iter().copied()); self.sources.extend(other.sources.iter().copied());
...@@ -332,7 +333,7 @@ impl RouteTree { ...@@ -332,7 +333,7 @@ impl RouteTree {
match selector_segment { match selector_segment {
BaseSegment::Static(value) => Ok(RouteTree { BaseSegment::Static(value) => Ok(RouteTree {
base, base,
static_segments: IndexMap::from([(value, inner.cell())]), static_segments: fxindexmap! { value => inner.cell() },
..Default::default() ..Default::default()
} }
.cell()), .cell()),
......
...@@ -2,7 +2,6 @@ use std::collections::HashMap; ...@@ -2,7 +2,6 @@ use std::collections::HashMap;
use anyhow::Result; use anyhow::Result;
use async_trait::async_trait; use async_trait::async_trait;
use indexmap::IndexMap;
use modularize_imports::{modularize_imports, Config, PackageConfig}; use modularize_imports::{modularize_imports, Config, PackageConfig};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
...@@ -12,7 +11,7 @@ use swc_core::{ ...@@ -12,7 +11,7 @@ use swc_core::{
visit::FoldWith, visit::FoldWith,
}, },
}; };
use turbo_tasks::trace::TraceRawVcs; use turbo_tasks::{trace::TraceRawVcs, FxIndexMap};
use turbopack_ecmascript::{CustomTransformer, TransformContext}; use turbopack_ecmascript::{CustomTransformer, TransformContext};
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, TraceRawVcs)] #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, TraceRawVcs)]
...@@ -31,7 +30,7 @@ pub struct ModularizeImportsTransformer { ...@@ -31,7 +30,7 @@ pub struct ModularizeImportsTransformer {
} }
impl ModularizeImportsTransformer { impl ModularizeImportsTransformer {
pub fn new(packages: &IndexMap<String, ModularizeImportPackageConfig>) -> Self { pub fn new(packages: &FxIndexMap<String, ModularizeImportPackageConfig>) -> Self {
Self { Self {
packages: packages packages: packages
.iter() .iter()
......
...@@ -3,7 +3,6 @@ use std::{ ...@@ -3,7 +3,6 @@ use std::{
fmt::Display, fmt::Display,
}; };
use indexmap::{IndexMap, IndexSet};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use swc_core::{ use swc_core::{
common::{comments::Comments, source_map::SmallPos, BytePos, Span, Spanned}, common::{comments::Comments, source_map::SmallPos, BytePos, Span, Spanned},
...@@ -13,7 +12,7 @@ use swc_core::{ ...@@ -13,7 +12,7 @@ use swc_core::{
visit::{Visit, VisitWith}, visit::{Visit, VisitWith},
}, },
}; };
use turbo_tasks::{RcStr, Vc}; use turbo_tasks::{FxIndexMap, FxIndexSet, RcStr, Vc};
use turbopack_core::{issue::IssueSource, source::Source}; use turbopack_core::{issue::IssueSource, source::Source};
use super::{top_level_await::has_top_level_await, JsValue, ModuleValue}; use super::{top_level_await::has_top_level_await, JsValue, ModuleValue};
...@@ -123,16 +122,16 @@ pub(crate) enum Reexport { ...@@ -123,16 +122,16 @@ pub(crate) enum Reexport {
#[derive(Default, Debug)] #[derive(Default, Debug)]
pub(crate) struct ImportMap { pub(crate) struct ImportMap {
/// Map from identifier to (index in references, exported symbol) /// Map from identifier to (index in references, exported symbol)
imports: IndexMap<Id, (usize, JsWord)>, imports: FxIndexMap<Id, (usize, JsWord)>,
/// Map from identifier to index in references /// Map from identifier to index in references
namespace_imports: IndexMap<Id, usize>, namespace_imports: FxIndexMap<Id, usize>,
/// List of (index in references, imported symbol, exported symbol) /// List of (index in references, imported symbol, exported symbol)
reexports: Vec<(usize, Reexport)>, reexports: Vec<(usize, Reexport)>,
/// Ordered list of imported symbols /// Ordered list of imported symbols
references: IndexSet<ImportMapReference>, references: FxIndexSet<ImportMapReference>,
/// True, when the module has imports /// True, when the module has imports
has_imports: bool, has_imports: bool,
......
...@@ -5,7 +5,7 @@ use std::{ ...@@ -5,7 +5,7 @@ use std::{
cmp::Ordering, cmp::Ordering,
fmt::{Display, Formatter, Write}, fmt::{Display, Formatter, Write},
future::Future, future::Future,
hash::{Hash, Hasher}, hash::{BuildHasherDefault, Hash, Hasher},
mem::take, mem::take,
pin::Pin, pin::Pin,
sync::Arc, sync::Arc,
...@@ -13,11 +13,11 @@ use std::{ ...@@ -13,11 +13,11 @@ use std::{
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use graph::VarGraph; use graph::VarGraph;
use indexmap::{IndexMap, IndexSet};
use num_bigint::BigInt; use num_bigint::BigInt;
use num_traits::identities::Zero; use num_traits::identities::Zero;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use rustc_hash::FxHasher;
use swc_core::{ use swc_core::{
common::Mark, common::Mark,
ecma::{ ecma::{
...@@ -25,7 +25,7 @@ use swc_core::{ ...@@ -25,7 +25,7 @@ use swc_core::{
atoms::{Atom, JsWord}, atoms::{Atom, JsWord},
}, },
}; };
use turbo_tasks::{RcStr, Vc}; use turbo_tasks::{FxIndexMap, FxIndexSet, RcStr, Vc};
use turbopack_core::compile_time_info::{ use turbopack_core::compile_time_info::{
CompileTimeDefineValue, DefineableNameSegment, FreeVarReference, CompileTimeDefineValue, DefineableNameSegment, FreeVarReference,
}; };
...@@ -1923,7 +1923,7 @@ impl JsValue { ...@@ -1923,7 +1923,7 @@ impl JsValue {
pub fn match_free_var_reference<'a, T>( pub fn match_free_var_reference<'a, T>(
&self, &self,
var_graph: Option<&VarGraph>, var_graph: Option<&VarGraph>,
free_var_references: &'a IndexMap<Vec<DefineableNameSegment>, T>, free_var_references: &'a FxIndexMap<Vec<DefineableNameSegment>, T>,
prefix_self: &Option<DefineableNameSegment>, prefix_self: &Option<DefineableNameSegment>,
) -> Option<&'a T> { ) -> Option<&'a T> {
if let Some(def_name_len) = self.get_defineable_name_len() { if let Some(def_name_len) = self.get_defineable_name_len() {
...@@ -1965,7 +1965,7 @@ impl JsValue { ...@@ -1965,7 +1965,7 @@ impl JsValue {
/// `self` with `prefix`, e.g. to be able to match `typeof foo` if `self` is just `foo`. /// `self` with `prefix`, e.g. to be able to match `typeof foo` if `self` is just `foo`.
pub fn match_define<'a, T>( pub fn match_define<'a, T>(
&self, &self,
defines: &'a IndexMap<Vec<DefineableNameSegment>, T>, defines: &'a FxIndexMap<Vec<DefineableNameSegment>, T>,
) -> Option<&'a T> { ) -> Option<&'a T> {
if let Some(def_name_len) = self.get_defineable_name_len() { if let Some(def_name_len) = self.get_defineable_name_len() {
for (name, value) in defines.iter() { for (name, value) in defines.iter() {
...@@ -3220,7 +3220,10 @@ impl JsValue { ...@@ -3220,7 +3220,10 @@ impl JsValue {
if values.len() == 1 { if values.len() == 1 {
*self = take(&mut values[0]); *self = take(&mut values[0]);
} else { } else {
let mut set = IndexSet::with_capacity(values.len()); let mut set = FxIndexSet::with_capacity_and_hasher(
values.len(),
BuildHasherDefault::<FxHasher>::default(),
);
for v in take(values) { for v in take(values) {
match v { match v {
JsValue::Alternatives { JsValue::Alternatives {
...@@ -3746,13 +3749,13 @@ pub fn parse_require_context(args: &[JsValue]) -> Result<RequireContextOptions> ...@@ -3746,13 +3749,13 @@ pub fn parse_require_context(args: &[JsValue]) -> Result<RequireContextOptions>
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct RequireContextValue(IndexMap<RcStr, RcStr>); pub struct RequireContextValue(FxIndexMap<RcStr, RcStr>);
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl RequireContextValue { impl RequireContextValue {
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn from_context_map(map: Vc<RequireContextMap>) -> Result<Vc<Self>> { pub async fn from_context_map(map: Vc<RequireContextMap>) -> Result<Vc<Self>> {
let mut context_map = IndexMap::new(); let mut context_map = FxIndexMap::default();
for (key, entry) in map.await?.iter() { for (key, entry) in map.await?.iter() {
context_map.insert(key.clone(), entry.origin_relative.clone()); context_map.insert(key.clone(), entry.origin_relative.clone());
...@@ -3834,8 +3837,7 @@ fn is_unresolved_id(i: &Id, unresolved_mark: Mark) -> bool { ...@@ -3834,8 +3837,7 @@ fn is_unresolved_id(i: &Id, unresolved_mark: Mark) -> bool {
#[doc(hidden)] #[doc(hidden)]
pub mod test_utils { pub mod test_utils {
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap; use turbo_tasks::{FxIndexMap, Vc};
use turbo_tasks::Vc;
use turbopack_core::{compile_time_info::CompileTimeInfo, error::PrettyPrintError}; use turbopack_core::{compile_time_info::CompileTimeInfo, error::PrettyPrintError};
use super::{ use super::{
...@@ -3884,7 +3886,7 @@ pub mod test_utils { ...@@ -3884,7 +3886,7 @@ pub mod test_utils {
ref args, ref args,
) => match parse_require_context(args) { ) => match parse_require_context(args) {
Ok(options) => { Ok(options) => {
let mut map = IndexMap::new(); let mut map = FxIndexMap::default();
map.insert("./a".into(), format!("[context: {}]/a", options.dir).into()); map.insert("./a".into(), format!("[context: {}]/a", options.dir).into());
map.insert("./b".into(), format!("[context: {}]/b", options.dir).into()); map.insert("./b".into(), format!("[context: {}]/b", options.dir).into());
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexSet; use turbo_tasks::{FxIndexSet, RcStr, TryJoinIterExt, Value, ValueToString, Vc};
use turbo_tasks::{RcStr, TryJoinIterExt, Value, ValueToString, Vc};
use turbo_tasks_fs::{File, FileSystemPath}; use turbo_tasks_fs::{File, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
...@@ -250,7 +249,7 @@ impl Introspectable for ChunkGroupFilesAsset { ...@@ -250,7 +249,7 @@ impl Introspectable for ChunkGroupFilesAsset {
#[turbo_tasks::function] #[turbo_tasks::function]
fn children(&self) -> Vc<IntrospectableChildren> { fn children(&self) -> Vc<IntrospectableChildren> {
let mut children = IndexSet::new(); let mut children = FxIndexSet::default();
children.insert(( children.insert((
Vc::cell("inner asset".into()), Vc::cell("inner asset".into()),
IntrospectableModule::new(Vc::upcast(self.module)), IntrospectableModule::new(Vc::upcast(self.module)),
......
use anyhow::Result; use anyhow::Result;
use indexmap::{IndexMap, IndexSet};
use turbo_tasks::{ use turbo_tasks::{
graph::{AdjacencyMap, GraphTraversal}, graph::{AdjacencyMap, GraphTraversal},
RcStr, TryJoinIterExt, ValueToString, Vc, FxIndexMap, FxIndexSet, RcStr, TryJoinIterExt, ValueToString, Vc,
}; };
use turbo_tasks_hash::hash_xxh3_hash64; use turbo_tasks_hash::hash_xxh3_hash64;
use turbopack_core::{ use turbopack_core::{
...@@ -18,7 +17,7 @@ pub struct PreprocessedChildrenIdents { ...@@ -18,7 +17,7 @@ pub struct PreprocessedChildrenIdents {
// ident.to_string() -> full hash // ident.to_string() -> full hash
// We save the full hash to avoid re-hashing in `merge_preprocessed_module_ids` // We save the full hash to avoid re-hashing in `merge_preprocessed_module_ids`
// if this endpoint did not change. // if this endpoint did not change.
modules_idents: IndexMap<RcStr, u64>, modules_idents: FxIndexMap<RcStr, u64>,
} }
#[derive(Clone, Hash)] #[derive(Clone, Hash)]
...@@ -48,7 +47,7 @@ pub struct ReferencedModules(Vec<Vc<ReferencedModule>>); ...@@ -48,7 +47,7 @@ pub struct ReferencedModules(Vec<Vc<ReferencedModule>>);
async fn referenced_modules(module: Vc<Box<dyn Module>>) -> Result<Vc<ReferencedModules>> { async fn referenced_modules(module: Vc<Box<dyn Module>>) -> Result<Vc<ReferencedModules>> {
let references = module.references().await?; let references = module.references().await?;
let mut set = IndexSet::new(); let mut set = FxIndexSet::default();
let modules_and_async_loaders: ModulesAndAsyncLoaders = references let modules_and_async_loaders: ModulesAndAsyncLoaders = references
.iter() .iter()
.map(|reference| async move { .map(|reference| async move {
...@@ -133,7 +132,7 @@ pub async fn children_modules_idents( ...@@ -133,7 +132,7 @@ pub async fn children_modules_idents(
.into_reverse_topological(); .into_reverse_topological();
// module_id -> full hash // module_id -> full hash
let mut modules_idents = IndexMap::new(); let mut modules_idents = FxIndexMap::default();
for child_module in children_modules_iter { for child_module in children_modules_iter {
match *child_module.await? { match *child_module.await? {
ReferencedModule::Module(module) => { ReferencedModule::Module(module) => {
...@@ -169,8 +168,8 @@ const JS_MAX_SAFE_INTEGER: u64 = (1u64 << 53) - 1; ...@@ -169,8 +168,8 @@ const JS_MAX_SAFE_INTEGER: u64 = (1u64 << 53) - 1;
// ids and another that generates the final, optimized module ids. Thoughts? // ids and another that generates the final, optimized module ids. Thoughts?
pub async fn merge_preprocessed_module_ids( pub async fn merge_preprocessed_module_ids(
preprocessed_module_ids: Vec<Vc<PreprocessedChildrenIdents>>, preprocessed_module_ids: Vec<Vc<PreprocessedChildrenIdents>>,
) -> Result<IndexMap<RcStr, ModuleId>> { ) -> Result<FxIndexMap<RcStr, ModuleId>> {
let mut merged_module_ids = IndexMap::new(); let mut merged_module_ids = FxIndexMap::default();
for preprocessed_module_ids in preprocessed_module_ids { for preprocessed_module_ids in preprocessed_module_ids {
for (module_ident, full_hash) in &preprocessed_module_ids.await?.modules_idents { for (module_ident, full_hash) in &preprocessed_module_ids.await?.modules_idents {
...@@ -186,8 +185,8 @@ pub async fn merge_preprocessed_module_ids( ...@@ -186,8 +185,8 @@ pub async fn merge_preprocessed_module_ids(
JS_MAX_SAFE_INTEGER, JS_MAX_SAFE_INTEGER,
); );
let mut module_id_map = IndexMap::new(); let mut module_id_map = FxIndexMap::default();
let mut used_ids = IndexSet::new(); let mut used_ids = FxIndexSet::default();
for (module_ident, full_hash) in merged_module_ids.iter() { for (module_ident, full_hash) in merged_module_ids.iter() {
let mut trimmed_hash = full_hash % digit_mask; let mut trimmed_hash = full_hash % digit_mask;
......
...@@ -39,7 +39,6 @@ use std::fmt::{Display, Formatter}; ...@@ -39,7 +39,6 @@ use std::fmt::{Display, Formatter};
use anyhow::Result; use anyhow::Result;
use chunk::EcmascriptChunkItem; use chunk::EcmascriptChunkItem;
use code_gen::{CodeGenerateable, CodeGeneration, CodeGenerationHoistedStmt}; use code_gen::{CodeGenerateable, CodeGeneration, CodeGenerationHoistedStmt};
use indexmap::IndexMap;
pub use parse::ParseResultSourceMap; pub use parse::ParseResultSourceMap;
use parse::{parse, ParseResult}; use parse::{parse, ParseResult};
use path_visitor::ApplyVisitors; use path_visitor::ApplyVisitors;
...@@ -60,7 +59,7 @@ pub use transform::{ ...@@ -60,7 +59,7 @@ pub use transform::{
TransformPlugin, UnsupportedServerActionIssue, TransformPlugin, UnsupportedServerActionIssue,
}; };
use turbo_tasks::{ use turbo_tasks::{
trace::TraceRawVcs, RcStr, ReadRef, ResolvedVc, TaskInput, TryJoinIterExt, Value, trace::TraceRawVcs, FxIndexMap, RcStr, ReadRef, ResolvedVc, TaskInput, TryJoinIterExt, Value,
ValueToString, Vc, ValueToString, Vc,
}; };
use turbo_tasks_fs::{rope::Rope, FileJsonContent, FileSystemPath}; use turbo_tasks_fs::{rope::Rope, FileJsonContent, FileSystemPath};
...@@ -873,8 +872,8 @@ fn process_content_with_code_gens( ...@@ -873,8 +872,8 @@ fn process_content_with_code_gens(
) { ) {
let mut visitors = Vec::new(); let mut visitors = Vec::new();
let mut root_visitors = Vec::new(); let mut root_visitors = Vec::new();
let mut early_hoisted_stmts = IndexMap::new(); let mut early_hoisted_stmts = FxIndexMap::default();
let mut hoisted_stmts = IndexMap::new(); let mut hoisted_stmts = FxIndexMap::default();
for code_gen in code_gens { for code_gen in code_gens {
for CodeGenerationHoistedStmt { key, stmt } in &code_gen.hoisted_stmts { for CodeGenerationHoistedStmt { key, stmt } in &code_gen.hoisted_stmts {
hoisted_stmts.entry(key.clone()).or_insert(stmt.clone()); hoisted_stmts.entry(key.clone()).or_insert(stmt.clone());
......
use anyhow::Result; use anyhow::Result;
use indexmap::IndexSet;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
common::DUMMY_SP, common::DUMMY_SP,
ecma::ast::{ArrayLit, ArrayPat, Expr, Ident}, ecma::ast::{ArrayLit, ArrayPat, Expr, Ident},
quote, quote,
}; };
use turbo_tasks::{trace::TraceRawVcs, ReadRef, TryFlatJoinIterExt, TryJoinIterExt, Vc}; use turbo_tasks::{
trace::TraceRawVcs, FxIndexSet, ReadRef, TryFlatJoinIterExt, TryJoinIterExt, Vc,
};
use turbopack_core::{ use turbopack_core::{
chunk::{ chunk::{
AsyncModuleInfo, ChunkableModule, ChunkableModuleReference, ChunkingContext, ChunkingType, AsyncModuleInfo, ChunkableModule, ChunkableModuleReference, ChunkingContext, ChunkingType,
...@@ -74,7 +75,7 @@ impl OptionAsyncModule { ...@@ -74,7 +75,7 @@ impl OptionAsyncModule {
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
struct AsyncModuleIdents(IndexSet<String>); struct AsyncModuleIdents(FxIndexSet<String>);
async fn get_inherit_async_referenced_asset( async fn get_inherit_async_referenced_asset(
r: Vc<Box<dyn ModuleReference>>, r: Vc<Box<dyn ModuleReference>>,
...@@ -140,7 +141,7 @@ impl AsyncModule { ...@@ -140,7 +141,7 @@ impl AsyncModule {
.try_flat_join() .try_flat_join()
.await?; .await?;
Ok(Vc::cell(IndexSet::from_iter(reference_idents))) Ok(Vc::cell(FxIndexSet::from_iter(reference_idents)))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -5,7 +5,6 @@ use std::{ ...@@ -5,7 +5,6 @@ use std::{
}; };
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
common::DUMMY_SP, common::DUMMY_SP,
...@@ -15,7 +14,7 @@ use swc_core::{ ...@@ -15,7 +14,7 @@ use swc_core::{
}, },
quote, quote_expr, quote, quote_expr,
}; };
use turbo_tasks::{trace::TraceRawVcs, RcStr, TryFlatJoinIterExt, ValueToString, Vc}; use turbo_tasks::{trace::TraceRawVcs, FxIndexMap, RcStr, TryFlatJoinIterExt, ValueToString, Vc};
use turbo_tasks_fs::glob::Glob; use turbo_tasks_fs::glob::Glob;
use turbopack_core::{ use turbopack_core::{
chunk::ChunkingContext, chunk::ChunkingContext,
...@@ -262,7 +261,7 @@ async fn handle_declared_export( ...@@ -262,7 +261,7 @@ async fn handle_declared_export(
#[turbo_tasks::value] #[turbo_tasks::value]
struct AllExportNamesResult { struct AllExportNamesResult {
esm_exports: IndexMap<RcStr, Vc<Box<dyn EcmascriptChunkPlaceable>>>, esm_exports: FxIndexMap<RcStr, Vc<Box<dyn EcmascriptChunkPlaceable>>>,
dynamic_exporting_modules: Vec<Vc<Box<dyn EcmascriptChunkPlaceable>>>, dynamic_exporting_modules: Vec<Vc<Box<dyn EcmascriptChunkPlaceable>>>,
} }
...@@ -273,14 +272,14 @@ async fn get_all_export_names( ...@@ -273,14 +272,14 @@ async fn get_all_export_names(
let exports = module.get_exports().await?; let exports = module.get_exports().await?;
let EcmascriptExports::EsmExports(exports) = &*exports else { let EcmascriptExports::EsmExports(exports) = &*exports else {
return Ok(AllExportNamesResult { return Ok(AllExportNamesResult {
esm_exports: IndexMap::new(), esm_exports: FxIndexMap::default(),
dynamic_exporting_modules: vec![module], dynamic_exporting_modules: vec![module],
} }
.cell()); .cell());
}; };
let exports = exports.await?; let exports = exports.await?;
let mut esm_exports = IndexMap::new(); let mut esm_exports = FxIndexMap::default();
let mut dynamic_exporting_modules = Vec::new(); let mut dynamic_exporting_modules = Vec::new();
esm_exports.extend(exports.exports.keys().cloned().map(|n| (n, module))); esm_exports.extend(exports.exports.keys().cloned().map(|n| (n, module)));
let star_export_names = exports let star_export_names = exports
......
...@@ -26,7 +26,6 @@ use std::{ ...@@ -26,7 +26,6 @@ use std::{
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use constant_condition::{ConstantCondition, ConstantConditionValue}; use constant_condition::{ConstantCondition, ConstantConditionValue};
use constant_value::ConstantValue; use constant_value::ConstantValue;
use indexmap::IndexSet;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use num_traits::Zero; use num_traits::Zero;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
...@@ -51,7 +50,7 @@ use swc_core::{ ...@@ -51,7 +50,7 @@ use swc_core::{
}, },
}; };
use tracing::Instrument; use tracing::Instrument;
use turbo_tasks::{RcStr, TryJoinIterExt, Upcast, Value, ValueToString, Vc}; use turbo_tasks::{FxIndexSet, RcStr, TryJoinIterExt, Upcast, Value, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{ use turbopack_core::{
compile_time_info::{ compile_time_info::{
...@@ -161,10 +160,10 @@ pub struct AnalyzeEcmascriptModuleResult { ...@@ -161,10 +160,10 @@ pub struct AnalyzeEcmascriptModuleResult {
/// A temporary analysis result builder to pass around, to be turned into an /// A temporary analysis result builder to pass around, to be turned into an
/// `Vc<AnalyzeEcmascriptModuleResult>` eventually. /// `Vc<AnalyzeEcmascriptModuleResult>` eventually.
pub struct AnalyzeEcmascriptModuleResultBuilder { pub struct AnalyzeEcmascriptModuleResultBuilder {
references: IndexSet<Vc<Box<dyn ModuleReference>>>, references: FxIndexSet<Vc<Box<dyn ModuleReference>>>,
local_references: IndexSet<Vc<Box<dyn ModuleReference>>>, local_references: FxIndexSet<Vc<Box<dyn ModuleReference>>>,
reexport_references: IndexSet<Vc<Box<dyn ModuleReference>>>, reexport_references: FxIndexSet<Vc<Box<dyn ModuleReference>>>,
evaluation_references: IndexSet<Vc<Box<dyn ModuleReference>>>, evaluation_references: FxIndexSet<Vc<Box<dyn ModuleReference>>>,
code_gens: Vec<CodeGen>, code_gens: Vec<CodeGen>,
exports: EcmascriptExports, exports: EcmascriptExports,
async_module: Vc<OptionAsyncModule>, async_module: Vc<OptionAsyncModule>,
...@@ -176,10 +175,10 @@ pub struct AnalyzeEcmascriptModuleResultBuilder { ...@@ -176,10 +175,10 @@ pub struct AnalyzeEcmascriptModuleResultBuilder {
impl AnalyzeEcmascriptModuleResultBuilder { impl AnalyzeEcmascriptModuleResultBuilder {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
references: IndexSet::new(), references: FxIndexSet::default(),
local_references: IndexSet::new(), local_references: FxIndexSet::default(),
reexport_references: IndexSet::new(), reexport_references: FxIndexSet::default(),
evaluation_references: IndexSet::new(), evaluation_references: FxIndexSet::default(),
code_gens: Vec::new(), code_gens: Vec::new(),
exports: EcmascriptExports::None, exports: EcmascriptExports::None,
async_module: Vc::cell(None), async_module: Vc::cell(None),
......
use std::{borrow::Cow, collections::HashSet}; use std::{borrow::Cow, collections::HashSet};
use anyhow::Result; use anyhow::Result;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
common::DUMMY_SP, common::DUMMY_SP,
...@@ -11,7 +10,9 @@ use swc_core::{ ...@@ -11,7 +10,9 @@ use swc_core::{
}, },
quote, quote_expr, quote, quote_expr,
}; };
use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, RcStr, TryJoinIterExt, Value, Vc}; use turbo_tasks::{
debug::ValueDebugFormat, trace::TraceRawVcs, FxIndexMap, RcStr, TryJoinIterExt, Value, Vc,
};
use turbopack_core::{ use turbopack_core::{
chunk::{ChunkItemExt, ChunkableModule, ChunkingContext, ModuleId}, chunk::{ChunkItemExt, ChunkableModule, ChunkingContext, ModuleId},
issue::{code_gen::CodeGenerationIssue, IssueExt, IssueSeverity, StyledString}, issue::{code_gen::CodeGenerationIssue, IssueExt, IssueSeverity, StyledString},
...@@ -70,7 +71,7 @@ pub(crate) enum PatternMapping { ...@@ -70,7 +71,7 @@ pub(crate) enum PatternMapping {
/// ```js /// ```js
/// require(`./images/${name}.png`) /// require(`./images/${name}.png`)
/// ``` /// ```
Map(IndexMap<String, SinglePatternMapping>), Map(FxIndexMap<String, SinglePatternMapping>),
} }
#[derive(Hash, Debug, Copy, Clone)] #[derive(Hash, Debug, Copy, Clone)]
...@@ -231,7 +232,7 @@ enum ImportMode { ...@@ -231,7 +232,7 @@ enum ImportMode {
} }
fn create_context_map( fn create_context_map(
map: &IndexMap<String, SinglePatternMapping>, map: &FxIndexMap<String, SinglePatternMapping>,
key_expr: &Expr, key_expr: &Expr,
import_mode: ImportMode, import_mode: ImportMode,
) -> Expr { ) -> Expr {
......
use std::{borrow::Cow, collections::VecDeque, sync::Arc}; use std::{borrow::Cow, collections::VecDeque, sync::Arc};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::IndexMap;
use swc_core::{ use swc_core::{
common::DUMMY_SP, common::DUMMY_SP,
ecma::{ ecma::{
...@@ -13,7 +12,7 @@ use swc_core::{ ...@@ -13,7 +12,7 @@ use swc_core::{
}, },
quote, quote_expr, quote, quote_expr,
}; };
use turbo_tasks::{primitives::Regex, RcStr, Value, ValueToString, Vc}; use turbo_tasks::{primitives::Regex, FxIndexMap, RcStr, Value, ValueToString, Vc};
use turbo_tasks_fs::{DirectoryContent, DirectoryEntry, FileSystemPath}; use turbo_tasks_fs::{DirectoryContent, DirectoryEntry, FileSystemPath};
use turbopack_core::{ use turbopack_core::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
...@@ -52,7 +51,7 @@ pub(crate) enum DirListEntry { ...@@ -52,7 +51,7 @@ pub(crate) enum DirListEntry {
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub(crate) struct DirList(IndexMap<RcStr, DirListEntry>); pub(crate) struct DirList(FxIndexMap<RcStr, DirListEntry>);
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl DirList { impl DirList {
...@@ -71,7 +70,7 @@ impl DirList { ...@@ -71,7 +70,7 @@ impl DirList {
let root_val = &*dir.await?; let root_val = &*dir.await?;
let regex = &*filter.await?; let regex = &*filter.await?;
let mut list = IndexMap::new(); let mut list = FxIndexMap::default();
let dir_content = dir.read_dir().await?; let dir_content = dir.read_dir().await?;
let entries = match &*dir_content { let entries = match &*dir_content {
...@@ -114,7 +113,7 @@ impl DirList { ...@@ -114,7 +113,7 @@ impl DirList {
let mut queue = VecDeque::from([this]); let mut queue = VecDeque::from([this]);
let mut list = IndexMap::new(); let mut list = FxIndexMap::default();
while let Some(dir) = queue.pop_front() { while let Some(dir) = queue.pop_front() {
for (k, entry) in &*dir { for (k, entry) in &*dir {
...@@ -134,7 +133,7 @@ impl DirList { ...@@ -134,7 +133,7 @@ impl DirList {
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub(crate) struct FlatDirList(IndexMap<RcStr, Vc<FileSystemPath>>); pub(crate) struct FlatDirList(FxIndexMap<RcStr, Vc<FileSystemPath>>);
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl FlatDirList { impl FlatDirList {
...@@ -154,7 +153,7 @@ pub struct RequireContextMapEntry { ...@@ -154,7 +153,7 @@ pub struct RequireContextMapEntry {
/// The resolved context map for a `require.context(..)` call. /// The resolved context map for a `require.context(..)` call.
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct RequireContextMap(IndexMap<RcStr, RequireContextMapEntry>); pub struct RequireContextMap(FxIndexMap<RcStr, RequireContextMapEntry>);
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl RequireContextMap { impl RequireContextMap {
...@@ -171,7 +170,7 @@ impl RequireContextMap { ...@@ -171,7 +170,7 @@ impl RequireContextMap {
let list = &*FlatDirList::read(dir, recursive, filter).await?; let list = &*FlatDirList::read(dir, recursive, filter).await?;
let mut map = IndexMap::new(); let mut map = FxIndexMap::default();
for (context_relative, path) in list { for (context_relative, path) in list {
if let Some(origin_relative) = origin_path.get_relative_path_to(&*path.await?) { if let Some(origin_relative) = origin_path.get_relative_path_to(&*path.await?) {
......
use std::{ use std::{fmt, hash::Hash};
fmt,
hash::{BuildHasherDefault, Hash},
};
use indexmap::IndexSet;
use petgraph::{ use petgraph::{
algo::{condensation, has_path_connecting}, algo::{condensation, has_path_connecting},
graphmap::GraphMap, graphmap::GraphMap,
prelude::DiGraphMap, prelude::DiGraphMap,
}; };
use rustc_hash::{FxHashMap, FxHashSet, FxHasher}; use rustc_hash::{FxHashMap, FxHashSet};
use swc_core::{ use swc_core::{
common::{comments::Comments, util::take::Take, Spanned, SyntaxContext, DUMMY_SP}, common::{comments::Comments, util::take::Take, Spanned, SyntaxContext, DUMMY_SP},
ecma::{ ecma::{
...@@ -24,7 +20,7 @@ use swc_core::{ ...@@ -24,7 +20,7 @@ use swc_core::{
utils::{find_pat_ids, private_ident, quote_ident, ExprCtx, ExprExt}, utils::{find_pat_ids, private_ident, quote_ident, ExprCtx, ExprExt},
}, },
}; };
use turbo_tasks::RcStr; use turbo_tasks::{FxIndexSet, RcStr};
use super::{ use super::{
util::{ util::{
...@@ -71,8 +67,6 @@ impl fmt::Debug for ItemId { ...@@ -71,8 +67,6 @@ impl fmt::Debug for ItemId {
} }
} }
type FxBuildHasher = BuildHasherDefault<FxHasher>;
/// Data about a module item /// Data about a module item
pub(crate) struct ItemData { pub(crate) struct ItemData {
/// Is the module item hoisted? /// Is the module item hoisted?
...@@ -83,10 +77,10 @@ pub(crate) struct ItemData { ...@@ -83,10 +77,10 @@ pub(crate) struct ItemData {
pub pure: bool, pub pure: bool,
/// Variables declared or bound by this module item /// Variables declared or bound by this module item
pub var_decls: IndexSet<Id, FxBuildHasher>, pub var_decls: FxIndexSet<Id>,
/// Variables read by this module item during evaluation /// Variables read by this module item during evaluation
pub read_vars: IndexSet<Id, FxBuildHasher>, pub read_vars: FxIndexSet<Id>,
/// Variables read by this module item eventually /// Variables read by this module item eventually
/// ///
...@@ -97,13 +91,13 @@ pub(crate) struct ItemData { ...@@ -97,13 +91,13 @@ pub(crate) struct ItemData {
/// - Note: This doesn’t mean they are only read “after” initial evaluation. They might also be /// - Note: This doesn’t mean they are only read “after” initial evaluation. They might also be
/// read “during” initial evaluation on any module item with SIDE_EFFECTS. This kind of /// read “during” initial evaluation on any module item with SIDE_EFFECTS. This kind of
/// interaction is handled by the module item with SIDE_EFFECTS. /// interaction is handled by the module item with SIDE_EFFECTS.
pub eventual_read_vars: IndexSet<Id, FxBuildHasher>, pub eventual_read_vars: FxIndexSet<Id>,
/// Side effects that are triggered on local variables during evaluation /// Side effects that are triggered on local variables during evaluation
pub write_vars: IndexSet<Id, FxBuildHasher>, pub write_vars: FxIndexSet<Id>,
/// Side effects that are triggered on local variables eventually /// Side effects that are triggered on local variables eventually
pub eventual_write_vars: IndexSet<Id, FxBuildHasher>, pub eventual_write_vars: FxIndexSet<Id>,
/// Any other unknown side effects that are trigger during evaluation /// Any other unknown side effects that are trigger during evaluation
pub side_effects: bool, pub side_effects: bool,
...@@ -152,7 +146,7 @@ where ...@@ -152,7 +146,7 @@ where
T: Eq + Hash + Clone, T: Eq + Hash + Clone,
{ {
pub(super) idx_graph: DiGraphMap<u32, Dependency>, pub(super) idx_graph: DiGraphMap<u32, Dependency>,
pub(super) graph_ix: IndexSet<T, BuildHasherDefault<FxHasher>>, pub(super) graph_ix: FxIndexSet<T>,
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
...@@ -329,7 +323,7 @@ impl DepGraph { ...@@ -329,7 +323,7 @@ impl DepGraph {
.chain(data.eventual_read_vars.iter()) .chain(data.eventual_read_vars.iter())
.chain(data.eventual_write_vars.iter()) .chain(data.eventual_write_vars.iter())
}) })
.collect::<IndexSet<_>>(); .collect::<FxIndexSet<_>>();
for item in group { for item in group {
if let ItemId::Group(ItemIdGroupKind::Export(id, _)) = item { if let ItemId::Group(ItemIdGroupKind::Export(id, _)) = item {
...@@ -1067,7 +1061,7 @@ impl DepGraph { ...@@ -1067,7 +1061,7 @@ impl DepGraph {
&top_level_vars, &top_level_vars,
); );
let var_decls = { let var_decls = {
let mut v = IndexSet::with_capacity_and_hasher(1, Default::default()); let mut v = FxIndexSet::with_capacity_and_hasher(1, Default::default());
v.insert(f.ident.to_id()); v.insert(f.ident.to_id());
v v
}; };
...@@ -1098,7 +1092,7 @@ impl DepGraph { ...@@ -1098,7 +1092,7 @@ impl DepGraph {
let mut vars = let mut vars =
ids_used_by(&c.class, unresolved_ctxt, top_level_ctxt, &top_level_vars); ids_used_by(&c.class, unresolved_ctxt, top_level_ctxt, &top_level_vars);
let var_decls = { let var_decls = {
let mut v = IndexSet::with_capacity_and_hasher(1, Default::default()); let mut v = FxIndexSet::with_capacity_and_hasher(1, Default::default());
v.insert(c.ident.to_id()); v.insert(c.ident.to_id());
v v
}; };
......
use std::{borrow::Cow, fmt::Write}; use std::{borrow::Cow, fmt::Write};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::IndexSet;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use swc_core::{ use swc_core::{
common::{comments::Comments, util::take::Take, SyntaxContext, DUMMY_SP, GLOBALS}, common::{comments::Comments, util::take::Take, SyntaxContext, DUMMY_SP, GLOBALS},
...@@ -13,7 +12,7 @@ use swc_core::{ ...@@ -13,7 +12,7 @@ use swc_core::{
codegen::to_code, codegen::to_code,
}, },
}; };
use turbo_tasks::{RcStr, ValueToString, Vc}; use turbo_tasks::{FxIndexSet, RcStr, ValueToString, Vc};
use turbopack_core::{ident::AssetIdent, resolve::ModulePart, source::Source}; use turbopack_core::{ident::AssetIdent, resolve::ModulePart, source::Source};
pub(crate) use self::graph::{ pub(crate) use self::graph::{
...@@ -95,8 +94,8 @@ impl Analyzer<'_> { ...@@ -95,8 +94,8 @@ impl Analyzer<'_> {
/// ///
/// ///
/// Returns all (EVENTUAL_READ/WRITE_VARS) in the module. /// Returns all (EVENTUAL_READ/WRITE_VARS) in the module.
fn hoist_vars_and_bindings(&mut self) -> IndexSet<Id> { fn hoist_vars_and_bindings(&mut self) -> FxIndexSet<Id> {
let mut eventual_ids = IndexSet::default(); let mut eventual_ids = FxIndexSet::default();
for item_id in self.item_ids.iter() { for item_id in self.item_ids.iter() {
if let Some(item) = self.items.get(item_id) { if let Some(item) = self.items.get(item_id) {
...@@ -131,7 +130,7 @@ impl Analyzer<'_> { ...@@ -131,7 +130,7 @@ impl Analyzer<'_> {
} }
/// Phase 2: Immediate evaluation /// Phase 2: Immediate evaluation
fn evaluate_immediate(&mut self, _module: &Module, eventual_ids: &IndexSet<Id>) { fn evaluate_immediate(&mut self, _module: &Module, eventual_ids: &FxIndexSet<Id>) {
for item_id in self.item_ids.iter() { for item_id in self.item_ids.iter() {
if let Some(item) = self.items.get(item_id) { if let Some(item) = self.items.get(item_id) {
// Ignore HOISTED module items, they have been processed in phase 1 already. // Ignore HOISTED module items, they have been processed in phase 1 already.
......
use std::{ use std::{fmt::Write, hash::Hash, path::PathBuf, sync::Arc};
fmt::Write,
hash::{BuildHasherDefault, Hash},
path::PathBuf,
sync::Arc,
};
use anyhow::Error; use anyhow::Error;
use indexmap::IndexSet;
use rustc_hash::FxHasher;
use serde::Deserialize; use serde::Deserialize;
use swc_core::{ use swc_core::{
common::{comments::SingleThreadedComments, util::take::Take, Mark, SourceMap, SyntaxContext}, common::{comments::SingleThreadedComments, util::take::Take, Mark, SourceMap, SyntaxContext},
...@@ -20,6 +13,7 @@ use swc_core::{ ...@@ -20,6 +13,7 @@ use swc_core::{
}, },
testing::{self, fixture, NormalizedOutput}, testing::{self, fixture, NormalizedOutput},
}; };
use turbo_tasks::FxIndexSet;
use super::{ use super::{
graph::{ graph::{
...@@ -104,7 +98,7 @@ fn run(input: PathBuf) { ...@@ -104,7 +98,7 @@ fn run(input: PathBuf) {
writeln!(s, "- Side effects").unwrap(); writeln!(s, "- Side effects").unwrap();
} }
let f = |ids: &IndexSet<Id, BuildHasherDefault<FxHasher>>| { let f = |ids: &FxIndexSet<Id>| {
let mut s = String::new(); let mut s = String::new();
for (i, id) in ids.iter().enumerate() { for (i, id) in ids.iter().enumerate() {
if i == 0 { if i == 0 {
......
use std::hash::BuildHasherDefault; use rustc_hash::FxHashSet;
use indexmap::IndexSet;
use rustc_hash::{FxHashSet, FxHasher};
use swc_core::{ use swc_core::{
common::SyntaxContext, common::SyntaxContext,
ecma::{ ecma::{
...@@ -14,6 +11,7 @@ use swc_core::{ ...@@ -14,6 +11,7 @@ use swc_core::{
visit::{noop_visit_type, Visit, VisitWith}, visit::{noop_visit_type, Visit, VisitWith},
}, },
}; };
use turbo_tasks::FxIndexSet;
use crate::TURBOPACK_HELPER; use crate::TURBOPACK_HELPER;
...@@ -194,9 +192,9 @@ impl Visit for IdentUsageCollector<'_> { ...@@ -194,9 +192,9 @@ impl Visit for IdentUsageCollector<'_> {
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub(crate) struct Vars { pub(crate) struct Vars {
/// Variables which are read. /// Variables which are read.
pub read: IndexSet<Id, BuildHasherDefault<FxHasher>>, pub read: FxIndexSet<Id>,
/// Variables which are written. /// Variables which are written.
pub write: IndexSet<Id, BuildHasherDefault<FxHasher>>, pub write: FxIndexSet<Id>,
pub found_unresolved: bool, pub found_unresolved: bool,
} }
......
use anyhow::Result; use anyhow::Result;
use indexmap::indexmap; use turbo_tasks::{fxindexmap, Vc};
use turbo_tasks::Vc;
use turbo_tasks_env::{CommandLineProcessEnv, CustomProcessEnv, ProcessEnv}; use turbo_tasks_env::{CommandLineProcessEnv, CustomProcessEnv, ProcessEnv};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
...@@ -17,7 +16,7 @@ pub async fn load_env(project_path: Vc<FileSystemPath>) -> Result<Vc<Box<dyn Pro ...@@ -17,7 +16,7 @@ pub async fn load_env(project_path: Vc<FileSystemPath>) -> Result<Vc<Box<dyn Pro
let env = Vc::upcast(CustomProcessEnv::new( let env = Vc::upcast(CustomProcessEnv::new(
env, env,
Vc::cell(indexmap! { Vc::cell(fxindexmap! {
"NODE_ENV".into() => node_env.into(), "NODE_ENV".into() => node_env.into(),
}), }),
)); ));
......
...@@ -8,13 +8,12 @@ use futures::{ ...@@ -8,13 +8,12 @@ use futures::{
pin_mut, SinkExt, StreamExt, pin_mut, SinkExt, StreamExt,
}; };
use futures_retry::{FutureRetry, RetryPolicy}; use futures_retry::{FutureRetry, RetryPolicy};
use indexmap::indexmap;
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::Value as JsonValue; use serde_json::Value as JsonValue;
use turbo_tasks::{ use turbo_tasks::{
duration_span, mark_finished, prevent_gc, util::SharedError, Completion, RawVc, TaskInput, duration_span, fxindexmap, mark_finished, prevent_gc, util::SharedError, Completion, RawVc,
TryJoinIterExt, Value, Vc, TaskInput, TryJoinIterExt, Value, Vc,
}; };
use turbo_tasks_bytes::{Bytes, Stream}; use turbo_tasks_bytes::{Bytes, Stream};
use turbo_tasks_env::ProcessEnv; use turbo_tasks_env::ProcessEnv;
...@@ -116,7 +115,7 @@ pub async fn get_evaluate_pool( ...@@ -116,7 +115,7 @@ pub async fn get_evaluate_pool(
File::from("import { run } from 'RUNTIME'; run(() => import('INNER'))").into(), File::from("import { run } from 'RUNTIME'; run(() => import('INNER'))").into(),
), ),
)), )),
Value::new(ReferenceType::Internal(Vc::cell(indexmap! { Value::new(ReferenceType::Internal(Vc::cell(fxindexmap! {
"INNER".into() => module_asset, "INNER".into() => module_asset,
"RUNTIME".into() => runtime_asset "RUNTIME".into() => runtime_asset
}))), }))),
......
...@@ -7,11 +7,10 @@ ...@@ -7,11 +7,10 @@
use std::{collections::HashMap, iter::once, thread::available_parallelism}; use std::{collections::HashMap, iter::once, thread::available_parallelism};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indexmap::IndexSet;
pub use node_entry::{NodeEntry, NodeRenderingEntries, NodeRenderingEntry}; pub use node_entry::{NodeEntry, NodeRenderingEntries, NodeRenderingEntry};
use turbo_tasks::{ use turbo_tasks::{
graph::{AdjacencyMap, GraphTraversal}, graph::{AdjacencyMap, GraphTraversal},
Completion, Completions, RcStr, TryJoinIterExt, ValueToString, Vc, Completion, Completions, FxIndexSet, RcStr, TryJoinIterExt, ValueToString, Vc,
}; };
use turbo_tasks_env::ProcessEnv; use turbo_tasks_env::ProcessEnv;
use turbo_tasks_fs::{to_sys_path, File, FileSystemPath}; use turbo_tasks_fs::{to_sys_path, File, FileSystemPath};
...@@ -172,8 +171,8 @@ async fn separate_assets( ...@@ -172,8 +171,8 @@ async fn separate_assets(
.completed()? .completed()?
.into_inner(); .into_inner();
let mut internal_assets = IndexSet::new(); let mut internal_assets = FxIndexSet::default();
let mut external_asset_entrypoints = IndexSet::new(); let mut external_asset_entrypoints = FxIndexSet::default();
for item in graph.into_reverse_topological() { for item in graph.into_reverse_topological() {
match item { match item {
......
...@@ -13,7 +13,6 @@ use std::{ ...@@ -13,7 +13,6 @@ use std::{
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use futures::join; use futures::join;
use indexmap::IndexSet;
use owo_colors::{OwoColorize, Style}; use owo_colors::{OwoColorize, Style};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{de::DeserializeOwned, Serialize}; use serde::{de::DeserializeOwned, Serialize};
...@@ -28,7 +27,7 @@ use tokio::{ ...@@ -28,7 +27,7 @@ use tokio::{
sync::{OwnedSemaphorePermit, Semaphore}, sync::{OwnedSemaphorePermit, Semaphore},
time::{sleep, timeout}, time::{sleep, timeout},
}; };
use turbo_tasks::{duration_span, RcStr, Vc}; use turbo_tasks::{duration_span, FxIndexSet, RcStr, Vc};
use turbo_tasks_fs::{json::parse_json_with_source_context, FileSystemPath}; use turbo_tasks_fs::{json::parse_json_with_source_context, FileSystemPath};
use turbopack_ecmascript::magic_identifier::unmangle_identifiers; use turbopack_ecmascript::magic_identifier::unmangle_identifiers;
...@@ -119,7 +118,7 @@ struct OutputEntry { ...@@ -119,7 +118,7 @@ struct OutputEntry {
stack_trace: Option<Arc<[u8]>>, stack_trace: Option<Arc<[u8]>>,
} }
type SharedOutputSet = Arc<Mutex<IndexSet<(OutputEntry, u32)>>>; type SharedOutputSet = Arc<Mutex<FxIndexSet<(OutputEntry, u32)>>>;
static GLOBAL_OUTPUT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); static GLOBAL_OUTPUT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
static MARKER: &[u8] = b"TURBOPACK_OUTPUT_"; static MARKER: &[u8] = b"TURBOPACK_OUTPUT_";
...@@ -737,8 +736,8 @@ impl NodeJsPool { ...@@ -737,8 +736,8 @@ impl NodeJsPool {
concurrency_semaphore: Arc::new(Semaphore::new(if debug { 1 } else { concurrency })), concurrency_semaphore: Arc::new(Semaphore::new(if debug { 1 } else { concurrency })),
bootup_semaphore: Arc::new(Semaphore::new(1)), bootup_semaphore: Arc::new(Semaphore::new(1)),
idle_process_semaphore: Arc::new(Semaphore::new(0)), idle_process_semaphore: Arc::new(Semaphore::new(0)),
shared_stdout: Arc::new(Mutex::new(IndexSet::new())), shared_stdout: Arc::new(Mutex::new(FxIndexSet::default())),
shared_stderr: Arc::new(Mutex::new(IndexSet::new())), shared_stderr: Arc::new(Mutex::new(FxIndexSet::default())),
debug, debug,
stats: Default::default(), stats: Default::default(),
} }
......
use indexmap::IndexMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue; use serde_json::Value as JsonValue;
use turbo_tasks::{RcStr, ReadRef}; use turbo_tasks::{FxIndexMap, RcStr, ReadRef};
use crate::{route_matcher::Param, ResponseHeaders, StructuredError}; use crate::{route_matcher::Param, ResponseHeaders, StructuredError};
...@@ -15,7 +14,7 @@ pub mod rendered_source; ...@@ -15,7 +14,7 @@ pub mod rendered_source;
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct RenderData { pub struct RenderData {
params: IndexMap<RcStr, Param>, params: FxIndexMap<RcStr, Param>,
method: RcStr, method: RcStr,
url: RcStr, url: RcStr,
original_url: RcStr, original_url: RcStr,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment