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