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

Remove unused turbo-tasks items and add lint check (#90801)

### What?

Adds a lint script (`scripts/check-unused-turbo-tasks.mjs`) that detects
unused `#[turbo_tasks::function]`, `#[turbo_tasks::value]`, and
`#[turbo_tasks::value_trait]` definitions across the Rust codebase, and
removes all currently unused items.

### Why?

Dead turbo-tasks definitions add compilation overhead (each generates
trait impls, registrations, etc.) and make the codebase harder to
navigate. A lint check prevents regressions.

### How?

**New script** (`scripts/check-unused-turbo-tasks.mjs`):
1. Discovers all `.rs` files in `turbopack/crates/` and `crates/`
(excluding `turbo-tasks-macros-tests`)
2. Parses three kinds of turbo-tasks annotations:
- `#[turbo_tasks::function]` → extracts `fn` name + context (free,
inherent impl, trait impl, trait default)
   - `#[turbo_tasks::value]` → extracts `struct`/`enum` name
   - `#[turbo_tasks::value_trait]` → extracts `trait` name
3. Scans all files for identifier references, excluding definition sites
4. Reports any name that has no external references

The script is added to the `pnpm lint` command (runs in parallel with
other checks).

**Removed 23 unused items** across 18 files:

| Kind | Count | Examples |
|------|-------|---------|
| `value` (struct/enum) | 9 | `OutputAssetsWithAvailability`,
`ModuleNameMap`, `OptionModuleIds`, `LockedVersions`,
`AssetContentSnapshot` |
| `function` | 14 | `client_env`, `next_js_file`, `convert_path`,
`is_hot_module_replacement_enabled`,
`any_content_changed_of_output_asset` |

Also cleaned up imports that became unused after the removals.
parent ea56922a
...@@ -41,7 +41,6 @@ use turbo_tasks::{ ...@@ -41,7 +41,6 @@ use turbo_tasks::{
Completion, NonLocalValue, ResolvedVc, TryJoinIterExt, ValueToString, Vc, fxindexset, Completion, NonLocalValue, ResolvedVc, TryJoinIterExt, ValueToString, Vc, fxindexset,
trace::TraceRawVcs, trace::TraceRawVcs,
}; };
use turbo_tasks_env::{CustomProcessEnv, ProcessEnv};
use turbo_tasks_fs::{File, FileContent, FileSystemPath}; use turbo_tasks_fs::{File, FileContent, FileSystemPath};
use turbopack::{ use turbopack::{
ModuleAssetContext, ModuleAssetContext,
...@@ -785,14 +784,6 @@ impl AppProject { ...@@ -785,14 +784,6 @@ impl AppProject {
)) ))
} }
#[turbo_tasks::function]
fn client_env(self: Vc<Self>) -> Vc<Box<dyn ProcessEnv>> {
Vc::upcast(CustomProcessEnv::new(
self.project().env(),
self.project().next_config().env(),
))
}
#[turbo_tasks::function] #[turbo_tasks::function]
async fn client_runtime_entries(self: Vc<Self>) -> Result<Vc<EvaluatableAssets>> { async fn client_runtime_entries(self: Vc<Self>) -> Result<Vc<EvaluatableAssets>> {
Ok(get_client_runtime_entries( Ok(get_client_runtime_entries(
...@@ -1098,9 +1089,6 @@ pub fn app_entry_point_to_route( ...@@ -1098,9 +1089,6 @@ pub fn app_entry_point_to_route(
.cell() .cell()
} }
#[turbo_tasks::value(transparent)]
struct OutputAssetsWithAvailability((ResolvedVc<OutputAssets>, AvailabilityInfo));
#[derive(Copy, Clone, PartialEq, Eq, Debug, TraceRawVcs, NonLocalValue, Encode, Decode)] #[derive(Copy, Clone, PartialEq, Eq, Debug, TraceRawVcs, NonLocalValue, Encode, Decode)]
enum AppPageEndpointType { enum AppPageEndpointType {
Html, Html,
......
...@@ -766,11 +766,6 @@ impl Issue for CssGlobalImportIssue { ...@@ -766,11 +766,6 @@ impl Issue for CssGlobalImportIssue {
// TODO(PACK-4879): compute the source information by following the module references // TODO(PACK-4879): compute the source information by following the module references
} }
type FxModuleNameMap = FxIndexMap<ResolvedVc<Box<dyn Module>>, RcStr>;
#[turbo_tasks::value(transparent)]
struct ModuleNameMap(#[bincode(with = "turbo_bincode::indexmap")] pub FxModuleNameMap);
#[tracing::instrument(level = "info", name = "validate pages css imports", skip_all)] #[tracing::instrument(level = "info", name = "validate pages css imports", skip_all)]
#[turbo_tasks::function] #[turbo_tasks::function]
async fn validate_pages_css_imports_individual( async fn validate_pages_css_imports_individual(
......
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::Vc; use turbo_tasks::Vc;
use turbo_tasks_fs::{FileContent, FileSystem, FileSystemPath}; use turbo_tasks_fs::{FileSystem, FileSystemPath};
pub const VIRTUAL_PACKAGE_NAME: &str = "@vercel/turbopack-next"; pub const VIRTUAL_PACKAGE_NAME: &str = "@vercel/turbopack-next";
...@@ -11,11 +11,6 @@ pub(crate) fn next_js_fs() -> Vc<Box<dyn FileSystem>> { ...@@ -11,11 +11,6 @@ pub(crate) fn next_js_fs() -> Vc<Box<dyn FileSystem>> {
turbo_tasks_fs::embed_directory!("next", "$CARGO_MANIFEST_DIR/js/src") turbo_tasks_fs::embed_directory!("next", "$CARGO_MANIFEST_DIR/js/src")
} }
#[turbo_tasks::function]
pub(crate) async fn next_js_file(path: RcStr) -> Result<Vc<FileContent>> {
Ok(next_js_fs().root().await?.join(&path)?.read())
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub(crate) async fn next_js_file_path(path: RcStr) -> Result<Vc<FileSystemPath>> { pub(crate) async fn next_js_file_path(path: RcStr) -> Result<Vc<FileSystemPath>> {
Ok(next_js_fs().root().await?.join(&path)?.cell()) Ok(next_js_fs().root().await?.join(&path)?.cell())
......
...@@ -917,9 +917,6 @@ pub enum ModuleIds { ...@@ -917,9 +917,6 @@ pub enum ModuleIds {
Deterministic, Deterministic,
} }
#[turbo_tasks::value(transparent)]
pub struct OptionModuleIds(pub Option<ModuleIds>);
#[turbo_tasks::value(operation)] #[turbo_tasks::value(operation)]
#[derive(Copy, Clone, Debug, Deserialize)] #[derive(Copy, Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
...@@ -1409,9 +1406,6 @@ pub struct OptionSubResourceIntegrity(Option<SubResourceIntegrity>); ...@@ -1409,9 +1406,6 @@ pub struct OptionSubResourceIntegrity(Option<SubResourceIntegrity>);
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct OptionFileSystemPath(Option<FileSystemPath>); pub struct OptionFileSystemPath(Option<FileSystemPath>);
#[turbo_tasks::value(transparent)]
pub struct OptionServerActions(Option<ServerActions>);
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct IgnoreIssues(Vec<IgnoreIssue>); pub struct IgnoreIssues(Vec<IgnoreIssue>);
...@@ -1933,11 +1927,6 @@ impl NextConfig { ...@@ -1933,11 +1927,6 @@ impl NextConfig {
Vc::cell(self.experimental.gesture_transition.unwrap_or(false)) Vc::cell(self.experimental.gesture_transition.unwrap_or(false))
} }
#[turbo_tasks::function]
pub fn enable_app_new_scroll_handler(&self) -> Vc<bool> {
Vc::cell(self.experimental.app_new_scroll_handler.unwrap_or(false))
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn enable_cache_components(&self) -> Vc<bool> { pub fn enable_cache_components(&self) -> Vc<bool> {
Vc::cell(self.cache_components.unwrap_or(false)) Vc::cell(self.cache_components.unwrap_or(false))
......
...@@ -74,7 +74,8 @@ ...@@ -74,7 +74,8 @@
"types-and-precompiled": "run-p \"lint-typescript --log-order=stream\" check-compiler-fixtures types:test-lib && pnpm check-precompiled", "types-and-precompiled": "run-p \"lint-typescript --log-order=stream\" check-compiler-fixtures types:test-lib && pnpm check-precompiled",
"check-compiler-fixtures": "find crates/next-custom-transforms/tests/fixture -type f -name 'tsconfig.json' -print0 | xargs --null -n1 -I'{}' pnpm tsc --noEmit --project '{}'", "check-compiler-fixtures": "find crates/next-custom-transforms/tests/fixture -type f -name 'tsconfig.json' -print0 | xargs --null -n1 -I'{}' pnpm tsc --noEmit --project '{}'",
"validate-externals-doc": "node ./scripts/validate-externals-doc.js", "validate-externals-doc": "node ./scripts/validate-externals-doc.js",
"lint": "run-p test-types lint-typescript prettier-check \"lint-eslint .\" lint-ast-grep lint-language", "check-unused-turbo-tasks": "node scripts/check-unused-turbo-tasks.mjs",
"lint": "run-p test-types lint-typescript prettier-check \"lint-eslint .\" lint-ast-grep lint-language check-unused-turbo-tasks",
"lint-fix": "pnpm prettier-fix && pnpm lint-eslint --fix .", "lint-fix": "pnpm prettier-fix && pnpm lint-eslint --fix .",
"lint-language": "alex .", "lint-language": "alex .",
"prettier-check": "prettier --check .", "prettier-check": "prettier --check .",
......
This diff is collapsed.
...@@ -142,6 +142,8 @@ async fn test_trait_methods() { ...@@ -142,6 +142,8 @@ async fn test_trait_methods() {
async fn test_trait_methods_operation() -> Result<Vc<()>> { async fn test_trait_methods_operation() -> Result<Vc<()>> {
assert_eq!(*Value::static_trait_method().await?, 42); assert_eq!(*Value::static_trait_method().await?, 42);
assert_eq!(*Value::async_static_trait_method().await?, 42); assert_eq!(*Value::async_static_trait_method().await?, 42);
assert_eq!(*Value::default_static_trait_method().await?, 42);
assert_eq!(*Value::default_async_static_trait_method().await?, 42);
let value = Value(43).cell(); let value = Value(43).cell();
assert_eq!(*value.trait_method().await?, 43); assert_eq!(*value.trait_method().await?, 43);
......
...@@ -153,6 +153,40 @@ async fn test_struct_transparent_debug() { ...@@ -153,6 +153,40 @@ async fn test_struct_transparent_debug() {
.unwrap() .unwrap()
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_struct_option_debug() {
run_once(&REGISTRATION, || async {
let a = StructWithOption { option: None }.resolved_cell();
assert_eq!(
format!(
"{:?}",
dbg_operation(ResolvedVc::upcast(a))
.read_strongly_consistent()
.await?,
),
"StructWithOption {\n option: None,\n}",
);
let b = StructWithOption {
option: Some(Transparent(42).resolved_cell()),
}
.resolved_cell();
assert_eq!(
format!(
"{:?}",
dbg_operation(ResolvedVc::upcast(b))
.read_strongly_consistent()
.await?,
),
"StructWithOption {\n option: Some(\n 42,\n ),\n}",
);
Ok(())
})
.await
.unwrap()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_struct_vec_debug() { async fn test_struct_vec_debug() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
......
...@@ -36,34 +36,6 @@ impl AttachedFileSystem { ...@@ -36,34 +36,6 @@ impl AttachedFileSystem {
.cell()) .cell())
} }
/// Converts the given [FileSystemPath] to a path in this [FileSystem].
///
/// The given path has to be inside of the root [FileSystem], the child
/// [FileSystem] or this [AttachedFileSystem].
#[turbo_tasks::function]
pub async fn convert_path(
self: ResolvedVc<Self>,
contained_path: FileSystemPath,
) -> Result<Vc<FileSystemPath>> {
let self_fs: ResolvedVc<Box<dyn FileSystem>> = ResolvedVc::upcast(self);
let this = self.await?;
match contained_path.fs {
// already on this filesystem
fs if fs == self_fs => Ok(contained_path.cell()),
// in the root filesystem, just need to rebase on this filesystem
fs if fs == this.root_fs => Ok(self.root().await?.join(&contained_path.path)?.cell()),
// in the child filesystem, so we expand to the full path by appending to child_path
fs if fs == this.child_fs => {
Ok(self.child_path().await?.join(&contained_path.path)?.cell())
}
_ => bail!(
"path {} not part of self, the root fs or the child fs",
contained_path.value_to_string().await?
),
}
}
/// Constructs a [FileSystemPath] of the attachment point referencing /// Constructs a [FileSystemPath] of the attachment point referencing
/// this [AttachedFileSystem] /// this [AttachedFileSystem]
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -686,11 +686,6 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -686,11 +686,6 @@ impl ChunkingContext for BrowserChunkingContext {
.cell() .cell()
} }
#[turbo_tasks::function]
fn is_hot_module_replacement_enabled(&self) -> Vc<bool> {
Vc::cell(self.enable_hot_module_replacement)
}
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_configs(&self) -> Result<Vc<ChunkingConfigs>> { fn chunking_configs(&self) -> Result<Vc<ChunkingConfigs>> {
Ok(Vc::cell(self.chunking_configs.iter().cloned().collect())) Ok(Vc::cell(self.chunking_configs.iter().cloned().collect()))
......
...@@ -4,12 +4,7 @@ use turbo_tasks::{ ...@@ -4,12 +4,7 @@ use turbo_tasks::{
graph::{AdjacencyMap, GraphTraversal}, graph::{AdjacencyMap, GraphTraversal},
}; };
use crate::{ use crate::{asset::Asset, module::Module, reference::primary_referenced_modules};
asset::Asset,
module::Module,
output::{ExpandOutputAssetsInput, OutputAsset, expand_output_assets},
reference::primary_referenced_modules,
};
pub async fn get_referenced_modules( pub async fn get_referenced_modules(
parent: ResolvedVc<Box<dyn Module>>, parent: ResolvedVc<Box<dyn Module>>,
...@@ -39,24 +34,6 @@ pub async fn any_source_content_changed_of_module( ...@@ -39,24 +34,6 @@ pub async fn any_source_content_changed_of_module(
Ok(Vc::<Completions>::cell(completions).completed()) Ok(Vc::<Completions>::cell(completions).completed())
} }
/// Returns a completion that changes when any content of any asset in the whole
/// asset graph changes.
#[turbo_tasks::function]
pub async fn any_content_changed_of_output_asset(
root: ResolvedVc<Box<dyn OutputAsset>>,
) -> Result<Vc<Completion>> {
let completions =
expand_output_assets(std::iter::once(ExpandOutputAssetsInput::Asset(root)), true)
.await?
.into_iter()
.map(|m| content_changed(*ResolvedVc::upcast(m)))
.map(|v| v.to_resolved())
.try_join()
.await?;
Ok(Vc::<Completions>::cell(completions).completed())
}
/// Returns a completion that changes when the content of the given asset /// Returns a completion that changes when the content of the given asset
/// changes. /// changes.
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -366,11 +366,6 @@ pub trait ChunkingContext { ...@@ -366,11 +366,6 @@ pub trait ChunkingContext {
.cell() .cell()
} }
#[turbo_tasks::function]
fn is_hot_module_replacement_enabled(self: Vc<Self>) -> Vc<bool> {
Vc::cell(false)
}
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_configs(self: Vc<Self>) -> Vc<ChunkingConfigs> { fn chunking_configs(self: Vc<Self>) -> Vc<ChunkingConfigs> {
Vc::cell(Default::default()) Vc::cell(Default::default())
......
...@@ -475,9 +475,6 @@ pub struct ChunkItemWithAsyncModuleInfo { ...@@ -475,9 +475,6 @@ pub struct ChunkItemWithAsyncModuleInfo {
pub async_info: Option<ResolvedVc<AsyncModuleInfo>>, pub async_info: Option<ResolvedVc<AsyncModuleInfo>>,
} }
#[turbo_tasks::value(transparent)]
pub struct ChunkItemsWithAsyncModuleInfo(Vec<ChunkItemWithAsyncModuleInfo>);
pub trait ChunkItemExt { pub trait ChunkItemExt {
/// Returns the module id of this chunk item. /// Returns the module id of this chunk item.
fn id(self: Vc<Self>) -> impl Future<Output = Result<ModuleId>> + Send; fn id(self: Vc<Self>) -> impl Future<Output = Result<ModuleId>> + Send;
......
...@@ -7,9 +7,6 @@ use crate::{ ...@@ -7,9 +7,6 @@ use crate::{
module_graph::{GraphTraversalAction, ModuleGraph, ModuleGraphLayer}, module_graph::{GraphTraversalAction, ModuleGraph, ModuleGraphLayer},
}; };
#[turbo_tasks::value(transparent)]
pub struct ModulesSet(FxHashSet<ResolvedVc<Box<dyn Module>>>);
/// This lists all the modules that are async (self or transitively because they reference another /// This lists all the modules that are async (self or transitively because they reference another
/// module in this list). /// module in this list).
#[turbo_tasks::value(transparent, cell = "keyed")] #[turbo_tasks::value(transparent, cell = "keyed")]
......
...@@ -20,10 +20,6 @@ use crate::{ ...@@ -20,10 +20,6 @@ use crate::{
}, },
}; };
#[turbo_tasks::value(shared)]
#[derive(Hash, Debug)]
pub struct LockedVersions {}
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
#[derive(Debug)] #[derive(Debug)]
pub struct ExcludedExtensions(#[bincode(with = "turbo_bincode::indexset")] pub FxIndexSet<RcStr>); pub struct ExcludedExtensions(#[bincode(with = "turbo_bincode::indexset")] pub FxIndexSet<RcStr>);
......
...@@ -6,7 +6,6 @@ use turbo_tasks::{ ...@@ -6,7 +6,6 @@ use turbo_tasks::{
IntoTraitRef, NonLocalValue, OperationValue, ReadRef, ResolvedVc, State, TraitRef, Vc, IntoTraitRef, NonLocalValue, OperationValue, ReadRef, ResolvedVc, State, TraitRef, Vc,
debug::ValueDebugFormat, trace::TraceRawVcs, debug::ValueDebugFormat, trace::TraceRawVcs,
}; };
use turbo_tasks_fs::{FileContent, LinkType};
use turbo_tasks_hash::HashAlgorithm; use turbo_tasks_hash::HashAlgorithm;
use crate::asset::AssetContent; use crate::asset::AssetContent;
...@@ -68,13 +67,6 @@ pub struct VersionedAssetContent { ...@@ -68,13 +67,6 @@ pub struct VersionedAssetContent {
asset_content: ReadRef<AssetContent>, asset_content: ReadRef<AssetContent>,
} }
#[turbo_tasks::value]
#[derive(Clone)]
enum AssetContentSnapshot {
File(ReadRef<FileContent>),
Redirect { target: String, link_type: LinkType },
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl VersionedContent for VersionedAssetContent { impl VersionedContent for VersionedAssetContent {
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -26,20 +26,6 @@ impl VirtualOutputAsset { ...@@ -26,20 +26,6 @@ impl VirtualOutputAsset {
} }
.cell() .cell()
} }
#[turbo_tasks::function]
pub fn new_with_references(
path: FileSystemPath,
content: ResolvedVc<AssetContent>,
references: ResolvedVc<OutputAssets>,
) -> Vc<Self> {
VirtualOutputAsset {
path,
content,
references,
}
.cell()
}
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
......
...@@ -63,33 +63,6 @@ impl AssetGraphContentSource { ...@@ -63,33 +63,6 @@ impl AssetGraphContentSource {
}) })
} }
/// Serves all assets references by all root_assets.
#[turbo_tasks::function]
pub fn new_eager_multiple(
root_path: FileSystemPath,
root_assets: ResolvedVc<OutputAssetsSet>,
) -> Vc<Self> {
Self::cell(AssetGraphContentSource {
root_path,
root_assets,
expanded: None,
})
}
/// Serves all assets references by all root_assets. Only serve references
/// of an asset when it has served its content before.
#[turbo_tasks::function]
pub fn new_lazy_multiple(
root_path: FileSystemPath,
root_assets: ResolvedVc<OutputAssetsSet>,
) -> Vc<Self> {
Self::cell(AssetGraphContentSource {
root_path,
root_assets,
expanded: Some(State::new(FxHashSet::default())),
})
}
#[turbo_tasks::function] #[turbo_tasks::function]
async fn all_assets_map(&self) -> Result<Vc<OutputAssetsMap>> { async fn all_assets_map(&self) -> Result<Vc<OutputAssetsMap>> {
Ok(Vc::cell( Ok(Vc::cell(
......
...@@ -32,19 +32,6 @@ impl IssueFilePathContentSource { ...@@ -32,19 +32,6 @@ impl IssueFilePathContentSource {
} }
.cell() .cell()
} }
#[turbo_tasks::function]
pub fn new_description(
description: RcStr,
source: ResolvedVc<Box<dyn ContentSource>>,
) -> Vc<Self> {
IssueFilePathContentSource {
file_path: None,
description,
source,
}
.cell()
}
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
......
...@@ -133,23 +133,6 @@ impl ContentSourceContent { ...@@ -133,23 +133,6 @@ impl ContentSourceContent {
.cell()) .cell())
} }
#[turbo_tasks::function]
pub fn static_with_headers(
content: ResolvedVc<Box<dyn VersionedContent>>,
status_code: u16,
headers: ResolvedVc<HeaderList>,
) -> Vc<ContentSourceContent> {
ContentSourceContent::Static(
StaticContent {
content,
status_code,
headers,
}
.resolved_cell(),
)
.cell()
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn not_found() -> Vc<ContentSourceContent> { pub fn not_found() -> Vc<ContentSourceContent> {
ContentSourceContent::NotFound.cell() ContentSourceContent::NotFound.cell()
......
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