use std::sync::LazyLock;
use rayon::prelude::*;
use rustc_hash::{FxHashMap, FxHashSet};
use fallow_config::{CompiledIgnoreExportRule, ResolvedConfig, Severity};
use fallow_types::extract::{ExportInfo, ExportName, ModuleInfo};
use crate::discover::FileId;
use crate::graph::{
AmbiguityParticipants, EffectiveExportResolution, ExportNamespace, ExportSymbol, ModuleGraph,
ModuleNode,
};
use crate::resolve::{has_react_native_plugin, platform_family_key};
use crate::results::{
DuplicateExport, DuplicateLocation, ExportUsage, PrivateTypeLeak, ReferenceLocation,
StaleSuppression, SuppressionOrigin, UnusedExport,
};
use crate::suppress::{IssueKind, SuppressionContext};
use crate::plugins::{ConfigExportCredit, is_export_ignored};
use super::{LineOffsetsMap, byte_offset_to_line_col, read_source};
#[path = "unused_exports_adapter.rs"]
mod adapter;
use adapter::star_re_export_overlays;
#[path = "unused_exports_cjs.rs"]
mod cjs;
#[path = "unused_exports_condition_targets.rs"]
mod condition_targets;
use condition_targets::ConditionTargetFamilies;
#[path = "unused_exports_types.rs"]
mod types;
use types::drop_types_paired_with_schemas;
pub use types::suppress_signature_backing_types;
type PluginMatchers<'a> = Vec<CompiledUsedExportRule<'a>>;
const TANSTACK_ROUTER_PLUGIN_NAME: &str = "tanstack-router";
type UnusedExportModuleResult = (Vec<UnusedExport>, Vec<UnusedExport>, Vec<StaleSuppression>);
struct UnusedExportModuleContext<'a> {
graph: &'a ModuleGraph,
config: &'a ResolvedConfig,
ignore_matchers: &'a [CompiledIgnoreExportRule],
plugin_matchers: &'a PluginMatchers<'a>,
config_export_credit: &'a ConfigExportCredit<'a>,
module_info_by_id: Option<&'a FxHashMap<FileId, &'a ModuleInfo>>,
suppressions: &'a SuppressionContext<'a>,
line_offsets_by_file: &'a LineOffsetsMap<'a>,
ambiguity: &'a AmbiguityParticipants,
schema_exports: Option<&'a FxHashMap<FileId, Vec<String>>>,
}
fn compile_plugin_matchers(
plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
) -> PluginMatchers<'_> {
let Some(pr) = plugin_result else {
return Vec::new();
};
pr.used_exports
.iter()
.filter_map(compile_used_export_rule)
.collect()
}
fn compile_tanstack_duplicate_export_matchers(
plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
) -> PluginMatchers<'_> {
let Some(pr) = plugin_result else {
return Vec::new();
};
pr.used_exports
.iter()
.filter(|rule| rule.plugin_name == TANSTACK_ROUTER_PLUGIN_NAME)
.filter_map(compile_used_export_rule)
.collect()
}
fn is_tanstack_router_active(
plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
) -> bool {
plugin_result.is_some_and(|pr| {
pr.active_plugins
.iter()
.any(|plugin| plugin == TANSTACK_ROUTER_PLUGIN_NAME)
})
}
fn is_react_native_active(plugin_result: Option<&crate::plugins::AggregatedPluginResult>) -> bool {
plugin_result.is_some_and(|pr| has_react_native_plugin(&pr.active_plugins))
}
struct CompiledUsedExportRule<'a> {
path: crate::plugins::CompiledPathRule,
exports: Vec<&'a str>,
}
impl CompiledUsedExportRule<'_> {
fn matches(&self, path: &str) -> bool {
self.path.matches(path)
}
}
fn compile_used_export_rule(
rule: &crate::plugins::PluginUsedExportRule,
) -> Option<CompiledUsedExportRule<'_>> {
Some(CompiledUsedExportRule {
path: crate::plugins::CompiledPathRule::for_used_export_rule(
&rule.rule.path,
"used_exports pattern",
)?,
exports: rule.rule.exports.iter().map(String::as_str).collect(),
})
}
fn is_export_assignment_forwarder(module: &ModuleNode) -> bool {
module.forwards_default_as_module_object()
&& module
.exports
.iter()
.all(|export| matches!(export.name, ExportName::Default))
}
fn should_skip_module(
module: &ModuleNode,
has_plugin_used_exports: bool,
include_entry_exports: bool,
) -> bool {
if module.is_entry_point() && !has_plugin_used_exports && !include_entry_exports {
return true;
}
if !module.is_reachable() {
return module.exports.iter().all(|e| e.references.is_empty());
}
if module.has_cjs_exports() && module.exports.is_empty() {
return true;
}
if is_export_assignment_forwarder(module) {
return true;
}
module.path.extension().is_some_and(|ext| ext == "svelte")
}
fn matchers_for_module<'a>(
module_path: &std::path::Path,
config_root: &std::path::Path,
ignore_matchers: &'a [CompiledIgnoreExportRule],
plugin_matchers: &'a PluginMatchers<'_>,
) -> (Vec<&'a [String]>, Vec<&'a [&'a str]>) {
if ignore_matchers.is_empty() && plugin_matchers.is_empty() {
return (Vec::new(), Vec::new());
}
let relative_path = module_path.strip_prefix(config_root).unwrap_or(module_path);
let file_str = relative_path.to_string_lossy();
let mi: Vec<&[String]> = ignore_matchers
.iter()
.filter(|rule| rule.matcher.is_match(file_str.as_ref()))
.map(|rule| rule.exports.as_slice())
.collect();
let mp: Vec<&[&str]> = plugin_matchers
.iter()
.filter(|rule| rule.matches(file_str.as_ref()))
.map(|rule| rule.exports.as_slice())
.collect();
(mi, mp)
}
fn local_export_binding_name(export: &ExportInfo) -> Option<&str> {
export.local_name.as_deref().or(match &export.name {
ExportName::Named(name) => Some(name.as_str()),
ExportName::Default => None,
})
}
fn is_js_like_source(path: &std::path::Path) -> bool {
path.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| {
matches!(
ext,
"js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "mts" | "cts"
)
})
}
fn has_route_path_segment(module_path: &std::path::Path, config_root: &std::path::Path) -> bool {
let relative_path = module_path.strip_prefix(config_root).unwrap_or(module_path);
relative_path
.to_string_lossy()
.replace('\\', "/")
.split('/')
.any(|segment| segment == "routes")
}
fn is_route_tree_generated_file(path: &std::path::Path) -> bool {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.starts_with("routeTree.gen."))
}
fn is_route_referenced_by_tanstack_generated_tree(
export_name: &str,
export: &ExportSymbol,
module: &ModuleNode,
graph: &ModuleGraph,
config_root: &std::path::Path,
) -> bool {
export_name == "Route"
&& has_route_path_segment(&module.path, config_root)
&& export.references.iter().any(|reference| {
graph
.modules
.get(reference.from_file.0 as usize)
.is_some_and(|from| is_route_tree_generated_file(&from.path))
})
}
fn same_file_program_source(path: &std::path::Path) -> Option<(String, oxc_span::SourceType)> {
if fallow_extract::is_sfc_file(path) {
return fallow_extract::sfc_merged_script_source(&read_source(path));
}
if !is_js_like_source(path) {
return None;
}
let source = read_source(path);
if source.is_empty() {
return None;
}
Some((
source,
oxc_span::SourceType::from_path(path).unwrap_or_default(),
))
}
fn collect_exports_used_in_file(module: &ModuleInfo, path: &std::path::Path) -> FxHashSet<String> {
if module.exports.is_empty() {
return FxHashSet::default();
}
let Some((source, source_type)) = same_file_program_source(path) else {
return FxHashSet::default();
};
fallow_extract::parse_bounded_or_default(&source, source_type, |parser_return| {
let semantic_ret = oxc_semantic::SemanticBuilder::new()
.with_build_nodes(true)
.build(&parser_return.program);
let semantic = semantic_ret.semantic;
let scoping = semantic.scoping();
let nodes = semantic.nodes();
let root_scope = scoping.root_scope_id();
let mut used = FxHashSet::default();
for export in module.exports.iter() {
let Some(local_name) = local_export_binding_name(export) else {
continue;
};
let name = oxc_str::Ident::from(local_name);
let Some(symbol_id) = scoping.get_binding(root_scope, name) else {
continue;
};
let has_real_use = scoping
.get_resolved_references(symbol_id)
.any(|reference| !is_inside_export_specifier(nodes, reference.node_id()));
if has_real_use {
used.insert(export.name.to_string());
}
}
used
})
}
fn is_inside_export_specifier(
nodes: &oxc_semantic::AstNodes<'_>,
node_id: oxc_syntax::node::NodeId,
) -> bool {
nodes
.ancestor_kinds(node_id)
.any(|kind| matches!(kind, oxc_ast::AstKind::ExportSpecifier(_)))
|| matches!(
nodes.parent_kind(node_id),
oxc_ast::AstKind::ExportDefaultDeclaration(_)
)
}
pub(super) fn ignore_matchers_for_module<'a>(
module_path: &std::path::Path,
config_root: &std::path::Path,
ignore_matchers: &'a [CompiledIgnoreExportRule],
) -> Vec<&'a [String]> {
if ignore_matchers.is_empty() {
return Vec::new();
}
let relative_path = module_path.strip_prefix(config_root).unwrap_or(module_path);
let file_str = relative_path.to_string_lossy();
ignore_matchers
.iter()
.filter(|rule| rule.matcher.is_match(file_str.as_ref()))
.map(|rule| rule.exports.as_slice())
.collect()
}
fn export_has_reachable_reference(
graph: &ModuleGraph,
module: &ModuleNode,
export: &ExportSymbol,
) -> bool {
if module.is_reachable() {
return !export.references.is_empty();
}
export.references.iter().any(|r| {
graph.modules.get(r.from_file.0 as usize).is_some_and(|m| {
debug_assert_eq!(
m.file_id, r.from_file,
"ModuleGraph::modules FileId-as-index invariant broken"
);
m.is_reachable()
})
})
}
fn stale_expected_unused_suppression(
module: &ModuleNode,
export: &ExportSymbol,
line_offsets_by_file: &LineOffsetsMap<'_>,
) -> StaleSuppression {
let (line, col) =
byte_offset_to_line_col(line_offsets_by_file, module.file_id, export.span.start);
StaleSuppression {
finding_id: None,
path: module.path.clone(),
line,
col,
origin: SuppressionOrigin::JsdocTag {
export_name: export.name.to_string(),
reason: export.expected_unused_reason.clone(),
},
missing_reason: false,
actions: StaleSuppression::actions_for(false),
effective_severity: None,
}
}
fn record_expected_unused_stale(
module: &ModuleNode,
export: &ExportSymbol,
ctx: &UnusedExportModuleContext<'_>,
is_referenced: bool,
stale_expected_unused: &mut Vec<StaleSuppression>,
) {
if ctx.config.rules.require_suppression_reason != Severity::Off
&& export.expected_unused_reason.is_none()
{
let (line, col) =
byte_offset_to_line_col(ctx.line_offsets_by_file, module.file_id, export.span.start);
stale_expected_unused.push(StaleSuppression {
finding_id: None,
path: module.path.clone(),
line,
col,
origin: SuppressionOrigin::JsdocTag {
export_name: export.name.to_string(),
reason: None,
},
missing_reason: true,
actions: StaleSuppression::actions_for(true),
effective_severity: None,
});
}
if is_referenced {
stale_expected_unused.push(stale_expected_unused_suppression(
module,
export,
ctx.line_offsets_by_file,
));
}
}
pub fn find_unused_exports(
graph: &ModuleGraph,
modules: &[ModuleInfo],
config: &ResolvedConfig,
plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
suppressions: &SuppressionContext<'_>,
line_offsets_by_file: &LineOffsetsMap<'_>,
) -> (Vec<UnusedExport>, Vec<UnusedExport>, Vec<StaleSuppression>) {
let mut unused_exports = Vec::new();
let mut unused_types = Vec::new();
let mut stale_expected_unused = Vec::new();
let ignore_matchers = config.compiled_ignore_exports.as_slice();
let plugin_matchers = compile_plugin_matchers(plugin_result);
let config_export_credit = ConfigExportCredit::new(
plugin_result,
config.include_entry_exports || config.workspace_settings.any_include_entry_exports(),
);
let module_info_by_id: Option<FxHashMap<FileId, &ModuleInfo>> =
if config.ignore_exports_used_in_file.is_enabled() {
Some(modules.iter().map(|m| (m.file_id, m)).collect())
} else {
None
};
let schema_exports = types::schema_exports_by_file(config, graph, modules);
let ambiguity = graph.ambiguity_participants();
let module_context = UnusedExportModuleContext {
graph,
config,
ignore_matchers,
plugin_matchers: &plugin_matchers,
config_export_credit: &config_export_credit,
module_info_by_id: module_info_by_id.as_ref(),
suppressions,
line_offsets_by_file,
ambiguity: &ambiguity,
schema_exports: schema_exports.as_ref(),
};
let module_results: Vec<UnusedExportModuleResult> = graph
.modules
.par_iter()
.map(|module| find_unused_exports_for_module(module, &module_context))
.collect();
for (exports, types, stale_expected) in module_results {
unused_exports.extend(exports);
unused_types.extend(types);
stale_expected_unused.extend(stale_expected);
}
(unused_exports, unused_types, stale_expected_unused)
}
fn find_unused_exports_for_module(
module: &ModuleNode,
ctx: &UnusedExportModuleContext<'_>,
) -> UnusedExportModuleResult {
let mut stale_expected_unused = Vec::new();
if module.exports.is_empty() && !module.has_cjs_exports() {
return (Vec::new(), Vec::new(), stale_expected_unused);
}
let (matching_ignore, matching_plugin) = matchers_for_module(
&module.path,
&ctx.config.root,
ctx.ignore_matchers,
ctx.plugin_matchers,
);
if should_skip_module(
module,
!matching_plugin.is_empty(),
ctx.config.include_entry_exports_for(&module.path),
) {
return (Vec::new(), Vec::new(), stale_expected_unused);
}
let same_file_used_exports = same_file_used_exports(module, ctx);
let re_export_names: FxHashSet<&str> = module
.re_exports
.iter()
.map(|re| re.exported_name.as_str())
.collect();
let config_credited_exports = config_credited_exports(module, ctx);
let mut match_ctx = UnusedExportMatchContext {
same_file_used_exports: &same_file_used_exports,
re_export_names: &re_export_names,
matching_ignore: &matching_ignore,
matching_plugin: &matching_plugin,
config_credited_exports: &config_credited_exports,
stale_expected_unused: &mut stale_expected_unused,
};
let (unused_exports, unused_types) =
collect_module_unused_export_findings(module, ctx, &mut match_ctx);
(unused_exports, unused_types, stale_expected_unused)
}
fn collect_module_unused_export_findings(
module: &ModuleNode,
ctx: &UnusedExportModuleContext<'_>,
match_ctx: &mut UnusedExportMatchContext<'_>,
) -> (Vec<UnusedExport>, Vec<UnusedExport>) {
let mut unused_exports = Vec::new();
let mut unused_types = Vec::new();
let schema_exports = ctx
.schema_exports
.and_then(|by_file| by_file.get(&module.file_id))
.map_or(&[][..], Vec::as_slice);
for export in &module.exports {
let is_schema = !export.is_type_only
&& schema_exports
.binary_search_by(|name| name.as_str().cmp(export_name_str(&export.name)))
.is_ok();
if let Some(unused) = unused_export_for_module(
module,
export,
is_schema,
ctx,
UnusedExportMatchContext {
same_file_used_exports: match_ctx.same_file_used_exports,
re_export_names: match_ctx.re_export_names,
matching_ignore: match_ctx.matching_ignore,
matching_plugin: match_ctx.matching_plugin,
config_credited_exports: match_ctx.config_credited_exports,
stale_expected_unused: &mut *match_ctx.stale_expected_unused,
},
) {
if export.is_type_only || is_schema {
unused_types.push(unused);
} else {
unused_exports.push(unused);
}
}
}
drop_types_paired_with_schemas(&mut unused_types);
(unused_exports, unused_types)
}
fn config_credited_exports<'a>(
module: &ModuleNode,
ctx: &UnusedExportModuleContext<'a>,
) -> Vec<&'a [String]> {
if ctx.config_export_credit.is_empty() || !ctx.config.include_entry_exports_for(&module.path) {
return Vec::new();
}
let relative_path = module.path.strip_prefix(&ctx.config.root);
let file_str = relative_path.unwrap_or(&module.path).to_string_lossy();
ctx.config_export_credit.exports_for(file_str.as_ref())
}
fn same_file_used_exports(
module: &ModuleNode,
ctx: &UnusedExportModuleContext<'_>,
) -> FxHashSet<String> {
ctx.module_info_by_id
.map_or_else(FxHashSet::default, |by_id| {
by_id
.get(&module.file_id)
.map_or_else(FxHashSet::default, |info| {
collect_exports_used_in_file(info, &module.path)
})
})
}
struct UnusedExportMatchContext<'a> {
same_file_used_exports: &'a FxHashSet<String>,
re_export_names: &'a FxHashSet<&'a str>,
matching_ignore: &'a [&'a [String]],
matching_plugin: &'a [&'a [&'a str]],
config_credited_exports: &'a [&'a [String]],
stale_expected_unused: &'a mut Vec<StaleSuppression>,
}
fn export_name_str(name: &ExportName) -> &str {
match name {
ExportName::Named(name) => name.as_str(),
ExportName::Default => "default",
}
}
fn unused_export_for_module(
module: &ModuleNode,
export: &ExportSymbol,
is_schema: bool,
ctx: &UnusedExportModuleContext<'_>,
match_ctx: UnusedExportMatchContext<'_>,
) -> Option<UnusedExport> {
let mut match_ctx = match_ctx;
let export_str = export_name_str(&export.name);
if unused_export_candidate_is_skipped(module, export, ctx, export_str, &mut match_ctx) {
return None;
}
let (line, col) =
byte_offset_to_line_col(ctx.line_offsets_by_file, module.file_id, export.span.start);
let issue_kind = if export.is_type_only || is_schema {
IssueKind::UnusedType
} else {
IssueKind::UnusedExport
};
let suppressed = ctx
.suppressions
.is_suppressed(module.file_id, line, issue_kind)
|| (is_schema
&& ctx
.suppressions
.is_suppressed(module.file_id, line, IssueKind::UnusedExport));
if suppressed {
return None;
}
let is_re_export = match_ctx.re_export_names.contains(export_str);
Some(build_unused_export(
module,
export,
export_str.to_owned(),
line,
col,
is_re_export,
))
}
fn unused_export_candidate_is_skipped(
module: &ModuleNode,
export: &ExportSymbol,
ctx: &UnusedExportModuleContext<'_>,
export_str: &str,
match_ctx: &mut UnusedExportMatchContext<'_>,
) -> bool {
let has_cross_file_ref = export_has_reachable_reference(ctx.graph, module, export);
let is_referenced = has_cross_file_ref || (module.is_reachable() && export.is_side_effect_used);
if matches!(
export.visibility,
fallow_types::extract::VisibilityTag::ExpectedUnused
) {
record_expected_unused_stale(
module,
export,
ctx,
is_referenced,
match_ctx.stale_expected_unused,
);
return true;
}
if export.visibility.suppresses_unused() || is_referenced {
return true;
}
if ctx
.ambiguity
.contains_declaration(module.file_id, export_str, export.is_type_only)
{
return true;
}
if ctx
.config
.ignore_exports_used_in_file
.suppresses(export.is_type_only)
&& match_ctx.same_file_used_exports.contains(export_str)
{
return true;
}
cjs::is_credited(module, export_str, match_ctx)
}
fn build_unused_export(
module: &ModuleNode,
export: &ExportSymbol,
export_name: String,
line: u32,
col: u32,
is_re_export: bool,
) -> UnusedExport {
UnusedExport {
path: module.path.clone(),
export_name,
is_type_only: export.is_type_only,
line,
col,
span_start: export.span.start,
is_re_export,
deprecated: export.deprecated,
deprecated_reason: export.deprecated_reason.as_deref().map(str::to_owned),
}
}
const STORYBOOK_SUFFIXES: &[&str] = &[
".stories.ts",
".stories.tsx",
".stories.js",
".stories.jsx",
".stories.mts",
".stories.cts",
".stories.mjs",
".stories.cjs",
".story.ts",
".story.tsx",
".story.js",
".story.jsx",
".story.mts",
".story.cts",
".story.mjs",
".story.cjs",
];
fn is_storybook_file(path: &std::path::Path) -> bool {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| {
STORYBOOK_SUFFIXES
.iter()
.any(|suffix| name.ends_with(suffix))
})
}
const ROUTE_CONVENTION_PATTERNS: &[&str] = &[
"**/app/**/page.{ts,tsx,js,jsx}",
"**/app/**/layout.{ts,tsx,js,jsx}",
"**/app/**/template.{ts,tsx,js,jsx}",
"**/app/**/loading.{ts,tsx,js,jsx}",
"**/app/**/error.{ts,tsx,js,jsx}",
"**/app/**/not-found.{ts,tsx,js,jsx}",
"**/app/**/route.{ts,tsx,js,jsx}",
"**/app/**/default.{ts,tsx,js,jsx}",
"**/app/**/global-error.{ts,tsx,js,jsx}",
"**/app/**/forbidden.{ts,tsx,js,jsx}",
"**/app/**/unauthorized.{ts,tsx,js,jsx}",
"**/app/global-not-found.{ts,tsx,js,jsx}",
"**/app/page.{ts,tsx,js,jsx}",
"**/app/layout.{ts,tsx,js,jsx}",
"**/app/template.{ts,tsx,js,jsx}",
"**/app/loading.{ts,tsx,js,jsx}",
"**/app/error.{ts,tsx,js,jsx}",
"**/app/not-found.{ts,tsx,js,jsx}",
"**/app/route.{ts,tsx,js,jsx}",
"**/app/default.{ts,tsx,js,jsx}",
"**/app/global-error.{ts,tsx,js,jsx}",
"**/app/**/opengraph-image.{ts,tsx,js,jsx}",
"**/app/**/twitter-image.{ts,tsx,js,jsx}",
"**/app/**/icon.{ts,tsx,js,jsx}",
"**/app/**/apple-icon.{ts,tsx,js,jsx}",
"**/app/**/manifest.{ts,tsx,js,jsx}",
"**/app/**/sitemap.{ts,tsx,js,jsx}",
"**/app/**/robots.{ts,tsx,js,jsx}",
"**/pages/**/*.{ts,tsx,js,jsx}",
"**/src/templates/**/*.{ts,tsx,js,jsx}",
"**/routes/*.{ts,tsx,js,jsx}",
"**/routes/**/route.{ts,tsx,js,jsx}",
"**/routes/**/_layout.{ts,tsx,js,jsx}",
"**/routes/**/_index.{ts,tsx,js,jsx}",
"**/routes/**/index.{ts,tsx,js,jsx}",
"**/routes/**/__root.{ts,tsx,js,jsx}",
"**/app/**/_layout.{ts,tsx,js,jsx}",
"**/app/**/+*.{ts,tsx,js,jsx}",
];
#[expect(
clippy::expect_used,
reason = "route convention globs are hard-coded and covered by entry point tests"
)]
fn build_route_convention_globset() -> globset::GlobSet {
let mut builder = globset::GlobSetBuilder::new();
for pattern in ROUTE_CONVENTION_PATTERNS {
let glob = globset::GlobBuilder::new(pattern)
.literal_separator(true)
.build()
.expect("static route-convention glob pattern must be valid");
builder.add(glob);
}
builder
.build()
.expect("static route-convention globset must build")
}
fn is_route_convention_file(absolute_path: &std::path::Path, root: &std::path::Path) -> bool {
let relative = absolute_path.strip_prefix(root).unwrap_or(absolute_path);
let normalized = relative.to_string_lossy().replace('\\', "/");
ROUTE_CONVENTION_GLOBSET.is_match(normalized.as_str())
}
static ROUTE_CONVENTION_GLOBSET: LazyLock<globset::GlobSet> =
LazyLock::new(build_route_convention_globset);
pub fn find_private_type_leaks(
graph: &ModuleGraph,
modules: &[fallow_types::extract::ModuleInfo],
config: &ResolvedConfig,
suppressions: &SuppressionContext<'_>,
line_offsets_by_file: &LineOffsetsMap<'_>,
) -> Vec<PrivateTypeLeak> {
let mut leaks = Vec::new();
for module_info in modules {
if module_info.public_signature_type_references.is_empty()
|| module_info.local_type_declarations.is_empty()
{
continue;
}
let Some(module) = graph.modules.get(module_info.file_id.0 as usize) else {
continue;
};
debug_assert_eq!(
module.file_id, module_info.file_id,
"ModuleGraph::modules FileId-as-index invariant broken"
);
if is_storybook_file(&module.path) || is_route_convention_file(&module.path, &config.root) {
continue;
}
collect_module_private_type_leaks(
module,
module_info,
suppressions,
line_offsets_by_file,
&mut leaks,
);
}
leaks
}
fn collect_module_private_type_leaks(
module: &ModuleNode,
module_info: &fallow_types::extract::ModuleInfo,
suppressions: &SuppressionContext<'_>,
line_offsets_by_file: &LineOffsetsMap<'_>,
leaks: &mut Vec<PrivateTypeLeak>,
) {
let local_types: FxHashSet<&str> = module_info
.local_type_declarations
.iter()
.map(|decl| decl.name.as_str())
.collect();
let exported_names: FxHashSet<String> = module
.exports
.iter()
.map(|export| export.name.to_string())
.collect();
let mut seen: FxHashSet<(&str, &str)> = FxHashSet::default();
for reference in &module_info.public_signature_type_references {
if reference.from_satisfies {
continue;
}
if !local_types.contains(reference.type_name.as_str())
|| exported_names.contains(&reference.type_name)
{
continue;
}
if !seen.insert((reference.export_name.as_str(), reference.type_name.as_str())) {
continue;
}
let (line, col) = byte_offset_to_line_col(
line_offsets_by_file,
module_info.file_id,
reference.span.start,
);
if suppressions.is_suppressed(module_info.file_id, line, IssueKind::PrivateTypeLeak) {
continue;
}
leaks.push(PrivateTypeLeak {
path: module.path.clone(),
export_name: reference.export_name.clone(),
type_name: reference.type_name.clone(),
line,
col,
span_start: reference.span.start,
semantic: None,
});
}
}
type DynamicReExportSources = FxHashMap<usize, FxHashMap<String, FxHashSet<usize>>>;
fn collect_dynamic_reexport_sources(
resolved_modules: &[crate::resolve::ResolvedModule],
graph: &ModuleGraph,
re_export_sources: &mut DynamicReExportSources,
) {
use crate::extract::ExportName;
use fallow_types::extract::ImportedName;
for resolved in resolved_modules {
let wrapper_idx = resolved.file_id.0 as usize;
let Some(wrapper) = graph.modules.get(wrapper_idx) else {
continue;
};
debug_assert_eq!(
wrapper.file_id, resolved.file_id,
"ModuleGraph::modules FileId-as-index invariant broken"
);
let wrapper_exports = &wrapper.exports;
for dynamic_import in &resolved.resolved_dynamic_imports {
let Some(source_file_id) = dynamic_import.target.internal_file_id() else {
continue;
};
let ImportedName::Named(name) = &dynamic_import.info.imported_name else {
continue;
};
if !wrapper_exports
.iter()
.any(|export| matches!(&export.name, ExportName::Named(n) if n == name))
{
continue;
}
let source_idx = source_file_id.0 as usize;
if source_idx >= graph.modules.len() {
continue;
}
re_export_sources
.entry(wrapper_idx)
.or_default()
.entry(name.clone())
.or_default()
.insert(source_idx);
}
}
}
struct ExportEntry {
module_idx: usize,
path: std::path::PathBuf,
file_id: FileId,
span_start: u32,
is_type_only: bool,
}
impl ExportEntry {
const fn namespaces(&self) -> &'static [ExportNamespace] {
if self.is_type_only {
&[ExportNamespace::Type]
} else {
&[ExportNamespace::Type, ExportNamespace::Value]
}
}
fn connects_importer(&self, graph: &ModuleGraph, importer: FileId, export_name: &str) -> bool {
self.namespaces().iter().any(|&namespace| {
graph.importer_connects_export_origin(importer, self.file_id, export_name, namespace)
})
}
}
fn partition_by_common_importer(
entries: &[ExportEntry],
export_name: &str,
graph: &ModuleGraph,
) -> Vec<Vec<usize>> {
let n = entries.len();
let mut union_find = UnionFind::new(n);
let mut importer_to_entries: FxHashMap<FileId, Vec<usize>> = FxHashMap::default();
for (i, entry) in entries.iter().enumerate() {
let idx = entry.file_id.0 as usize;
if idx >= graph.reverse_deps.len() {
continue;
}
for &importer in &graph.reverse_deps[idx] {
if !entry.connects_importer(graph, importer, export_name) {
continue;
}
importer_to_entries.entry(importer).or_default().push(i);
}
}
for members in importer_to_entries.values() {
if let Some((&first, rest)) = members.split_first() {
for &other in rest {
union_find.union(first, other);
}
}
}
let mut entry_index_by_file_id: FxHashMap<FileId, usize> = FxHashMap::default();
for (i, entry) in entries.iter().enumerate() {
entry_index_by_file_id.entry(entry.file_id).or_insert(i);
}
for (i, entry) in entries.iter().enumerate() {
let idx = entry.file_id.0 as usize;
if idx >= graph.reverse_deps.len() {
continue;
}
for &importer in &graph.reverse_deps[idx] {
if !entry.connects_importer(graph, importer, export_name) {
continue;
}
if let Some(&j) = entry_index_by_file_id.get(&importer) {
union_find.union(i, j);
}
}
}
union_find.components()
}
struct UnionFind {
parent: Vec<usize>,
}
impl UnionFind {
fn new(len: usize) -> Self {
Self {
parent: (0..len).collect(),
}
}
fn find(&mut self, mut x: usize) -> usize {
while self.parent[x] != x {
self.parent[x] = self.parent[self.parent[x]];
x = self.parent[x];
}
x
}
fn union(&mut self, a: usize, b: usize) {
let root_a = self.find(a);
let root_b = self.find(b);
if root_a != root_b {
self.parent[root_a] = root_b;
}
}
fn components(mut self) -> Vec<Vec<usize>> {
let mut components: FxHashMap<usize, Vec<usize>> = FxHashMap::default();
for i in 0..self.parent.len() {
let root = self.find(i);
components.entry(root).or_default().push(i);
}
components.into_values().collect()
}
}
pub fn find_duplicate_exports(
graph: &ModuleGraph,
config: &ResolvedConfig,
suppressions: &SuppressionContext<'_>,
line_offsets_by_file: &LineOffsetsMap<'_>,
resolved_modules: &[crate::resolve::ResolvedModule],
) -> Vec<DuplicateExport> {
find_duplicate_exports_with_plugins(
graph,
config,
suppressions,
line_offsets_by_file,
None,
resolved_modules,
)
}
pub(super) fn find_duplicate_exports_with_plugins(
graph: &ModuleGraph,
config: &ResolvedConfig,
suppressions: &SuppressionContext<'_>,
line_offsets_by_file: &LineOffsetsMap<'_>,
plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
resolved_modules: &[crate::resolve::ResolvedModule],
) -> Vec<DuplicateExport> {
let dynamic_re_export_sources = build_dynamic_re_export_source_map(graph, resolved_modules);
let export_locations =
collect_duplicate_export_locations(graph, config, suppressions, plugin_result);
let condition_families = ConditionTargetFamilies::build(resolved_modules);
let collapse = AlternativeFiles {
platform_families: is_react_native_active(plugin_result),
condition_families: &condition_families,
};
let mut sorted_locations: Vec<_> = export_locations.into_iter().collect();
sorted_locations.sort_by(|a, b| a.0.cmp(&b.0));
sorted_locations
.into_iter()
.filter_map(|(name, locations)| {
evaluate_duplicate_export_group(
name,
locations,
&dynamic_re_export_sources,
graph,
line_offsets_by_file,
&collapse,
)
})
.collect()
}
fn build_dynamic_re_export_source_map(
graph: &ModuleGraph,
resolved_modules: &[crate::resolve::ResolvedModule],
) -> DynamicReExportSources {
let mut re_export_sources = DynamicReExportSources::default();
collect_dynamic_reexport_sources(resolved_modules, graph, &mut re_export_sources);
re_export_sources
}
fn collect_duplicate_export_locations(
graph: &ModuleGraph,
config: &ResolvedConfig,
suppressions: &SuppressionContext<'_>,
plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
) -> FxHashMap<String, Vec<ExportEntry>> {
let ignore_matchers = config.compiled_ignore_exports.as_slice();
let tanstack_duplicate_matchers = compile_tanstack_duplicate_export_matchers(plugin_result);
let has_tanstack_router = is_tanstack_router_active(plugin_result);
let mut export_locations: FxHashMap<String, Vec<ExportEntry>> = FxHashMap::default();
for (idx, module) in graph.modules.iter().enumerate() {
collect_module_duplicate_export_locations(
&mut export_locations,
DuplicateExportModuleInput {
graph,
config,
suppressions,
ignore_matchers,
tanstack_duplicate_matchers: &tanstack_duplicate_matchers,
has_tanstack_router,
module_idx: idx,
module,
},
);
}
export_locations
}
#[derive(Clone, Copy)]
struct DuplicateExportModuleInput<'a> {
graph: &'a ModuleGraph,
config: &'a ResolvedConfig,
suppressions: &'a SuppressionContext<'a>,
ignore_matchers: &'a [CompiledIgnoreExportRule],
tanstack_duplicate_matchers: &'a PluginMatchers<'a>,
has_tanstack_router: bool,
module_idx: usize,
module: &'a ModuleNode,
}
fn collect_module_duplicate_export_locations(
export_locations: &mut FxHashMap<String, Vec<ExportEntry>>,
input: DuplicateExportModuleInput<'_>,
) {
if !input.module.is_reachable()
|| input.module.is_entry_point()
|| is_css_module_path(&input.module.path)
{
return;
}
if input
.suppressions
.is_file_suppressed(input.module.file_id, IssueKind::DuplicateExport)
{
return;
}
let matching_ignore = ignore_matchers_for_module(
&input.module.path,
&input.config.root,
input.ignore_matchers,
);
let (_, matching_tanstack_contracts) = matchers_for_module(
&input.module.path,
&input.config.root,
&[],
input.tanstack_duplicate_matchers,
);
for export in &input.module.exports {
let Some((name, entry)) = duplicate_export_entry(
export,
&input,
&matching_ignore,
&matching_tanstack_contracts,
) else {
continue;
};
export_locations.entry(name).or_default().push(entry);
}
}
fn duplicate_export_entry(
export: &ExportSymbol,
input: &DuplicateExportModuleInput<'_>,
matching_ignore: &[&[String]],
matching_tanstack_contracts: &[&[&str]],
) -> Option<(String, ExportEntry)> {
if matches!(export.name, crate::extract::ExportName::Default)
|| matches!(&export.name, crate::extract::ExportName::Named(name) if name == "default")
{
return None;
}
if export.span.start == 0 && export.span.end == 0 {
return None;
}
let name = export.name.to_string();
if is_export_ignored(&name, matching_ignore, matching_tanstack_contracts) {
return None;
}
if input.has_tanstack_router
&& is_route_referenced_by_tanstack_generated_tree(
&name,
export,
input.module,
input.graph,
&input.config.root,
)
{
return None;
}
Some((
name,
ExportEntry {
module_idx: input.module_idx,
path: input.module.path.clone(),
file_id: input.module.file_id,
span_start: export.span.start,
is_type_only: export.is_type_only,
},
))
}
fn is_css_module_path(path: &std::path::Path) -> bool {
let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
return false;
};
let Some((stem, extension)) = file_name.rsplit_once('.') else {
return false;
};
stem.ends_with(".module") && matches!(extension, "css" | "scss" | "sass" | "less")
}
struct AlternativeFiles<'a> {
platform_families: bool,
condition_families: &'a ConditionTargetFamilies,
}
fn evaluate_duplicate_export_group(
name: String,
locations: Vec<ExportEntry>,
dynamic_re_export_sources: &DynamicReExportSources,
graph: &ModuleGraph,
line_offsets_by_file: &LineOffsetsMap<'_>,
collapse: &AlternativeFiles<'_>,
) -> Option<DuplicateExport> {
let mut seen_modules: FxHashSet<usize> = FxHashSet::default();
let locations: Vec<ExportEntry> = locations
.into_iter()
.filter(|entry| seen_modules.insert(entry.module_idx))
.collect();
if locations.len() <= 1 {
return None;
}
let module_indices: FxHashSet<usize> = locations.iter().map(|e| e.module_idx).collect();
let overlays = star_re_export_overlays(&locations, &name, graph);
let independent_entries: Vec<ExportEntry> = locations
.into_iter()
.filter(|entry| {
!is_re_export_chain_member(
entry,
&name,
&module_indices,
dynamic_re_export_sources,
graph,
) && !overlays.contains(&entry.file_id)
})
.collect();
let independent_entries = if collapse.platform_families {
collapse_platform_family_entries(independent_entries)
} else {
independent_entries
};
let independent_entries = collapse.condition_families.collapse(independent_entries);
if independent_entries.len() <= 1 {
return None;
}
let components = partition_by_common_importer(&independent_entries, &name, graph);
let mut surviving_locations: Vec<DuplicateLocation> = Vec::new();
for component_indices in components {
surviving_locations.extend(component_duplicate_locations(
&component_indices,
&independent_entries,
line_offsets_by_file,
));
}
if surviving_locations.len() <= 1 {
return None;
}
Some(DuplicateExport {
export_name: name,
locations: surviving_locations,
})
}
fn collapse_platform_family_entries(entries: Vec<ExportEntry>) -> Vec<ExportEntry> {
let keep = platform_family_keep_mask(&entries);
entries
.into_iter()
.zip(keep)
.filter_map(|(entry, keep)| keep.then_some(entry))
.collect()
}
fn platform_family_keep_mask(entries: &[ExportEntry]) -> Vec<bool> {
let mut families: FxHashMap<(&std::path::Path, &str), Vec<(usize, bool)>> =
FxHashMap::default();
for (i, entry) in entries.iter().enumerate() {
let Some(key) = platform_family_key(&entry.path) else {
continue;
};
families
.entry((key.parent, key.base))
.or_default()
.push((i, key.is_platform_variant));
}
let mut keep = vec![true; entries.len()];
for members in families.into_values() {
let Some(representative) = platform_family_representative(entries, &members) else {
continue;
};
for &(i, _) in &members {
if entries[i].file_id != representative {
keep[i] = false;
}
}
}
keep
}
fn platform_family_representative(
entries: &[ExportEntry],
members: &[(usize, bool)],
) -> Option<FileId> {
let distinct_files: FxHashSet<FileId> =
members.iter().map(|&(i, _)| entries[i].file_id).collect();
if distinct_files.len() < 2 || !members.iter().any(|&(_, is_variant)| is_variant) {
return None;
}
let base_members = members
.iter()
.filter(|&&(_, is_variant)| !is_variant)
.map(|&(i, _)| &entries[i]);
let representative = match base_members.min_by_key(|entry| &entry.path) {
Some(base) => base,
None => members
.iter()
.map(|&(i, _)| &entries[i])
.min_by_key(|entry| &entry.path)?,
};
Some(representative.file_id)
}
fn is_re_export_chain_member(
entry: &ExportEntry,
export_name: &str,
group_modules: &FxHashSet<usize>,
dynamic_re_export_sources: &DynamicReExportSources,
graph: &ModuleGraph,
) -> bool {
let is_static_re_export = entry.namespaces().iter().any(|&namespace| {
matches!(
graph.resolve_export(entry.file_id, export_name, namespace),
EffectiveExportResolution::Unique(binding)
if binding.origin_file() != entry.file_id
&& group_modules.contains(&(binding.origin_file().0 as usize))
)
});
if is_static_re_export {
return true;
}
dynamic_re_export_sources
.get(&entry.module_idx)
.and_then(|exports| exports.get(export_name))
.is_some_and(|sources| sources.iter().any(|source| group_modules.contains(source)))
}
fn component_duplicate_locations(
component_indices: &[usize],
independent_entries: &[ExportEntry],
line_offsets_by_file: &LineOffsetsMap<'_>,
) -> Vec<DuplicateLocation> {
if component_indices.len() <= 1 {
return Vec::new();
}
let value_count = component_indices
.iter()
.filter(|&&i| !independent_entries[i].is_type_only)
.count();
let type_count = component_indices
.iter()
.filter(|&&i| independent_entries[i].is_type_only)
.count();
if value_count == 1 && type_count == 1 {
return Vec::new();
}
component_indices
.iter()
.map(|&i| {
let e = &independent_entries[i];
let (line, col) =
byte_offset_to_line_col(line_offsets_by_file, e.file_id, e.span_start);
DuplicateLocation {
path: e.path.clone(),
line,
col,
}
})
.collect()
}
pub fn collect_export_usages(
graph: &ModuleGraph,
line_offsets_by_file: &LineOffsetsMap<'_>,
) -> Vec<ExportUsage> {
let mut usages = Vec::new();
let file_paths: FxHashMap<FileId, &std::path::Path> = graph
.modules
.iter()
.map(|m| (m.file_id, m.path.as_path()))
.collect();
let mut source_cache: FxHashMap<FileId, (String, Vec<u32>)> = FxHashMap::default();
for module in &graph.modules {
if !module.is_reachable() {
continue;
}
for export in &module.exports {
if export.span.start == 0 && export.span.end == 0 {
continue;
}
let (line, col) =
byte_offset_to_line_col(line_offsets_by_file, module.file_id, export.span.start);
let (reference_count, reference_locations) = export_reference_locations(
export,
&file_paths,
line_offsets_by_file,
&mut source_cache,
);
usages.push(ExportUsage {
path: module.path.clone(),
export_name: export.name.to_string(),
line,
col,
reference_count,
reference_locations,
});
}
}
usages
}
fn export_reference_locations(
export: &ExportSymbol,
file_paths: &FxHashMap<FileId, &std::path::Path>,
line_offsets_by_file: &LineOffsetsMap<'_>,
source_cache: &mut FxHashMap<FileId, (String, Vec<u32>)>,
) -> (usize, Vec<ReferenceLocation>) {
let mut importing_files: FxHashSet<FileId> = FxHashSet::default();
let locations = export
.physical_references()
.filter_map(|r| {
importing_files.insert(r.from_file);
reference_location(r, file_paths, line_offsets_by_file, source_cache)
})
.collect();
(importing_files.len(), locations)
}
pub(super) fn reference_location(
reference: &crate::graph::SymbolReference,
file_paths: &FxHashMap<FileId, &std::path::Path>,
line_offsets_by_file: &LineOffsetsMap<'_>,
source_cache: &mut FxHashMap<FileId, (String, Vec<u32>)>,
) -> Option<ReferenceLocation> {
if reference.import_span.start == 0 && reference.import_span.end == 0 {
return None;
}
let ref_path = file_paths.get(&reference.from_file)?;
let (line, col) = if line_offsets_by_file.contains_key(&reference.from_file) {
byte_offset_to_line_col(
line_offsets_by_file,
reference.from_file,
reference.import_span.start,
)
} else {
let (_, offsets) = source_cache.entry(reference.from_file).or_insert_with(|| {
let src = read_source(ref_path);
let ofs = fallow_types::extract::compute_line_offsets(&src);
(src, ofs)
});
fallow_types::extract::byte_offset_to_line_col(offsets, reference.import_span.start)
};
Some(ReferenceLocation {
path: ref_path.to_path_buf(),
line,
col,
})
}
#[cfg(test)]
#[path = "unused_exports_adapter_tests.rs"]
mod adapter_tests;
#[cfg(test)]
#[path = "unused_exports_tests.rs"]
mod tests;