1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
//! Component render fan-in: a DESCRIPTIVE blast-radius signal counting how many
//! JSX render SITES (and distinct parent components) render a given component
//! across the whole project.
//!
//! This is the COMPONENT-graph analogue of the module-level fan-in /
//! coupling-concentration metric (`FileHealthScore.fan_in` counts importing
//! MODULES; render fan-in counts JSX render CALL SITES). It is NOVEL because a
//! shared `<Button>` is rendered in far more places than it is imported: a single
//! parent that renders `<Button>` five times is five edit-ripple points, which
//! distinct-parents and distinct-files both collapse to one.
//!
//! NOT a rule, finding, IssueKind, threshold, or severity. It extends the
//! existing hotspot/coupling MACHINERY (a computed metric + a percentile,
//! surfaced as context), mirroring `compute_coupling_concentration`.
//!
//! Mechanism (no new IR, no CACHE bump): derive from the already-extracted
//! `module.render_edges`. Each `RenderEdge` is exactly one JSX render site
//! (`crates/extract/src/visitor/react.rs` pushes one edge per capitalized /
//! member JSX tag). Resolve each edge's `child_component_name` to a concrete
//! component via the shared [`ChildResolver`] and bucket the incoming count per
//! component. Gated on `react` / `react-dom` / `next` / `preact`; non-React
//! projects compute nothing (the gate fails AND `render_edges` is empty).
//!
//! UNDERCOUNT is the documented safe direction: a child rendered via a JSX
//! spread, a dynamic `createElement(var)`, or a member-expression tag
//! (`<Lib.Button/>`) resolves to `None` and increments no component's fan-in. A
//! true high-fan-in component can only be undersold, never falsely flagged.
use std::path::Path;
use rustc_hash::{FxHashMap, FxHashSet};
use fallow_types::extract::ModuleInfo;
use crate::discover::FileId;
use crate::graph::ModuleGraph;
use crate::resolve::ResolvedModule;
use crate::results::{RenderFanInComponent, RenderFanInMetric};
use super::predicates::{declares_react_runtime, is_react_file};
use super::react_resolve::{ChildResolver, CompKey};
/// The same concentration floor `compute_coupling_concentration` uses
/// (`crates/engine/src/vital_signs.rs`): the high-fan-in threshold is
/// `max(p95, FLOOR)`, so there is NO new tunable constant beyond the one
/// coupling already carries.
const CONCENTRATION_FLOOR: u32 = 10;
/// Compute the project-wide render fan-in metric. Returns `None` unless the
/// project declares `react` / `react-dom` / `next` / `preact` (the same dep gate
/// the other React analyzers use); non-React projects compute nothing.
#[must_use]
pub fn compute_render_fan_in(
graph: &ModuleGraph,
modules: &[ModuleInfo],
resolved_modules: &[ResolvedModule],
declared_deps: &FxHashSet<String>,
root: &Path,
) -> Option<RenderFanInMetric> {
if !declares_react_runtime(declared_deps) {
return None;
}
let (modules_by_id, resolved_by_id) = build_lookup_maps(modules, resolved_modules);
let resolver = ChildResolver::new(graph, &modules_by_id, &resolved_by_id);
let mut counts = seed_component_population(graph, &modules_by_id, root);
credit_render_edges(graph, &modules_by_id, &resolver, root, &mut counts);
build_render_fan_in_metric(graph, counts)
}
fn build_lookup_maps<'a>(
modules: &'a [ModuleInfo],
resolved_modules: &'a [ResolvedModule],
) -> (
FxHashMap<FileId, &'a ModuleInfo>,
FxHashMap<FileId, &'a ResolvedModule>,
) {
(
modules.iter().map(|m| (m.file_id, m)).collect(),
resolved_modules.iter().map(|m| (m.file_id, m)).collect(),
)
}
fn seed_component_population(
graph: &ModuleGraph,
modules_by_id: &FxHashMap<FileId, &ModuleInfo>,
root: &Path,
) -> FxHashMap<CompKey, FanInAccum> {
// Seed every declared component with a zero entry so a component rendered
// nowhere is a REAL 0 in the distribution (not absent), and so the
// per-component path-annotation map has an entry for every component the
// hotspot surface might query.
let mut counts: FxHashMap<CompKey, FanInAccum> = FxHashMap::default();
for node in &graph.modules {
if !node.is_reachable() || !is_react_file(&node.path) {
continue;
}
// A component DEFINED in a test/spec file must not be a fan-in target
// (its headline is test-local noise, dominated by render loops in the
// test body). Excluded from the seeded population so the percentile
// distribution and the top-N are over non-test components only.
if is_project_test_path(&node.path, root) {
continue;
}
let Some(module) = modules_by_id.get(&node.file_id) else {
continue;
};
for func in &module.component_functions {
counts
.entry(CompKey {
file: node.file_id,
name: func.name.clone(),
})
.or_default();
}
}
counts
}
fn credit_render_edges(
graph: &ModuleGraph,
modules_by_id: &FxHashMap<FileId, &ModuleInfo>,
resolver: &ChildResolver<'_>,
root: &Path,
counts: &mut FxHashMap<CompKey, FanInAccum>,
) {
// Walk every render edge, resolve its child to a concrete component, and
// credit one render SITE plus the distinct parent key. The parent key is
// `(parent_file, parent_component)`; an edge with an empty parent (a
// top-level render expression) still counts as a render site, keyed to the
// module file with an empty parent name so it collapses correctly.
for node in &graph.modules {
if !node.is_reachable() || !is_react_file(&node.path) {
continue;
}
// A render SITE whose PARENT file is a test/spec file must not count: a
// test that renders `<Page>` 146 times is not real blast radius. Skip
// the whole module's render edges so test-local render loops never
// inflate any component's fan-in.
if is_project_test_path(&node.path, root) {
continue;
}
let Some(module) = modules_by_id.get(&node.file_id) else {
continue;
};
for edge in &module.render_edges {
let Some(child_key) = resolver.resolve(node.file_id, &edge.child_component_name) else {
// Spread-only / dynamic / member-expression child: undercount
// (the safe direction). This site credits nothing.
continue;
};
let accum = counts.entry(child_key).or_default();
accum.render_sites += 1;
accum
.parents
.insert((node.file_id, edge.parent_component.clone()));
}
}
}
fn build_render_fan_in_metric(
graph: &ModuleGraph,
counts: FxHashMap<CompKey, FanInAccum>,
) -> Option<RenderFanInMetric> {
let path_by_id: FxHashMap<FileId, &Path> = graph
.modules
.iter()
.map(|node| (node.file_id, node.path.as_path()))
.collect();
let parts = collect_render_fan_in_components(&path_by_id, counts);
if parts.per_component.is_empty() {
// React declared but no inspectable components: nothing to surface.
return None;
}
let (p95_distinct_parents, high_pct) = concentration(&parts.distinct_parents_dist);
Some(RenderFanInMetric {
per_component: parts.per_component,
p95_distinct_parents,
high_pct,
max_distinct_parents: Some(parts.max_distinct_parents),
})
}
struct RenderFanInMetricParts {
per_component: Vec<RenderFanInComponent>,
distinct_parents_dist: Vec<u32>,
max_distinct_parents: u32,
}
fn collect_render_fan_in_components(
path_by_id: &FxHashMap<FileId, &Path>,
counts: FxHashMap<CompKey, FanInAccum>,
) -> RenderFanInMetricParts {
// Build the per-component detail (keyed back to file paths for the hotspot
// surface) and the distinct-parents distribution for the percentile.
let mut per_component = Vec::with_capacity(counts.len());
let mut distinct_parents_dist = Vec::with_capacity(counts.len());
let mut max_distinct_parents = 0;
for (key, accum) in counts {
let Some(path) = path_by_id.get(&key.file) else {
continue;
};
let distinct_parents = u32::try_from(accum.parents.len()).unwrap_or(u32::MAX);
// The HEADLINE is the max DISTINCT-PARENTS (honest blast radius = how many
// distinct render LOCATIONS edit-ripple to), not the max render_sites
// (which is inflated by a single parent rendering one child in a loop).
max_distinct_parents = max_distinct_parents.max(distinct_parents);
distinct_parents_dist.push(distinct_parents);
per_component.push(RenderFanInComponent {
file: (*path).to_path_buf(),
component: key.name.clone(),
render_sites: accum.render_sites,
distinct_parents,
});
}
// Deterministic ordering (path, component) so the carrier is stable across
// runs (FxHashMap iteration order is not).
per_component.sort_by(|a, b| {
a.file
.cmp(&b.file)
.then_with(|| a.component.cmp(&b.component))
});
RenderFanInMetricParts {
per_component,
distinct_parents_dist,
max_distinct_parents,
}
}
// The test-file predicate must run on the project-relative path, not the
// absolute node path: the project root itself can contain a `tests/` segment,
// and the `**/test/**` / `**/tests/**` globs anchor at any segment.
fn is_project_test_path(path: &Path, root: &Path) -> bool {
let rel = path.strip_prefix(root).unwrap_or(path);
super::predicates::is_test_or_spec_file(rel)
}
/// Running accumulator per component during the edge walk.
#[derive(Default)]
struct FanInAccum {
/// Total JSX render SITES (one per resolved render edge).
render_sites: u32,
/// Distinct `(parent_file, parent_component)` keys rendering this component.
parents: FxHashSet<(FileId, String)>,
}
/// Compute the distinct-parents concentration: `(p95, high_pct)` over the
/// per-component distinct-parents distribution. This function uses the same p95
/// index, `max(p95, CONCENTRATION_FLOOR)` threshold and one-decimal `high_pct`
/// as `compute_coupling_concentration` in `crates/engine/src/vital_signs.rs`;
/// change both together. `(None, None)`
/// on an empty population (the percentile-on-tiny-population caveat coupling
/// already carries). A singleton population is fine (its single value is the
/// p95).
#[expect(
clippy::cast_possible_truncation,
clippy::cast_precision_loss,
clippy::cast_sign_loss,
reason = "distinct-parents values are bounded by project size; same math as compute_coupling_concentration"
)]
fn concentration(distinct_parents: &[u32]) -> (Option<u32>, Option<f64>) {
if distinct_parents.is_empty() {
return (None, None);
}
let mut sorted: Vec<u32> = distinct_parents.to_vec();
sorted.sort_unstable();
let idx = (sorted.len() as f64 * 0.95).ceil() as usize;
let idx = idx.min(sorted.len()) - 1;
let p95 = sorted[idx];
let threshold = p95.max(CONCENTRATION_FLOOR);
let high_count = sorted.iter().filter(|&&fi| fi > threshold).count();
let high_pct = (high_count as f64 / sorted.len() as f64 * 1000.0).round() / 10.0;
(Some(p95), Some(high_pct))
}