1use std::path::Path;
5
6use fallow_engine::changed_files::RenamedFile;
7use rustc_hash::{FxHashMap, FxHashSet};
8
9use super::{AuditAnalysesView, DeadCodeView};
10use crate::AuditProgrammaticKeySnapshot;
11use crate::audit_keys::{
12 ComplexityBaseline, collection_keys, complexity_baseline, complexity_baseline_keys,
13 dead_code_audit_ledger, dead_code_keys, relative_key_path,
14 remap_complexity_baseline_for_renames, remap_keys_for_renames, styling_keys,
15};
16use crate::review_deltas::{boundary_edge_keys, cycle_keys};
17
18#[derive(Debug, Clone, Default)]
24pub struct AuditKeySnapshot {
25 pub type_aware_identity: Option<fallow_types::semantic::SemanticAnalysisIdentity>,
28 pub type_aware_gap_signature: Vec<String>,
31 pub syntactic_dead_code: Option<FxHashSet<String>>,
35 pub dead_code: FxHashSet<String>,
37 pub unprovable_dead_code: FxHashSet<String>,
42 pub health: ComplexityBaseline,
45 pub styling: FxHashSet<String>,
47 pub dupes: FxHashSet<String>,
49 pub dupe_groups: Vec<crate::diff_risk::clones::BaseCloneGroup>,
52 pub boundary_edges: FxHashSet<String>,
55 pub cycles: FxHashSet<String>,
57 pub public_api: FxHashSet<String>,
60 pub branching: FxHashMap<String, fallow_types::extract::FileBranching>,
64 pub inherited_health: Vec<ComplexityBaseline>,
68 pub own_config_unused_code: Option<FxHashSet<String>>,
77}
78
79impl AuditKeySnapshot {
80 #[must_use]
82 pub fn from_view(view: &AuditAnalysesView<'_>) -> Self {
83 let mut snapshot = Self::default();
84 if let Some(dead_code) = view.dead_code.as_ref() {
85 snapshot.type_aware_identity =
86 dead_code.type_aware.and_then(|meta| meta.identity.clone());
87 snapshot.type_aware_gap_signature = dead_code
88 .type_aware
89 .map_or_else(Vec::new, type_aware_gap_signature);
90 snapshot.syntactic_dead_code = dead_code.syntactic_keys.cloned();
91 snapshot.dead_code = dead_code_keys(dead_code.results, dead_code.root);
92 snapshot.unprovable_dead_code =
93 fallow_engine::unprovable::unprovable_dead_code_collections(dead_code.config)
94 .into_iter()
95 .map(str::to_owned)
96 .collect();
97 snapshot.boundary_edges = boundary_edge_keys(&dead_code.results.boundary_violations);
98 snapshot.cycles = cycle_keys(&dead_code.results.circular_dependencies, dead_code.root);
99 snapshot.public_api = dead_code.public_api.cloned().unwrap_or_default();
100 snapshot.own_config_unused_code = dead_code.own_config_unused_code.cloned();
101 }
102 if let Some(health) = view.health.as_ref() {
103 snapshot.health = complexity_baseline(health.report, health.root);
104 snapshot.styling = styling_keys(health.report, health.root);
105 snapshot.branching = health.branching.map_or_else(FxHashMap::default, |by_file| {
106 branching_keys(by_file, health.root)
107 });
108 }
109 if let Some(duplication) = view.duplication.as_ref() {
110 snapshot.dupes = duplication
111 .clone_groups
112 .iter()
113 .map(|group| crate::audit_keys::dupe_group_key(group, duplication.root))
114 .collect();
115 snapshot.dupe_groups = duplication
116 .clone_groups
117 .iter()
118 .map(|group| crate::diff_risk::clones::BaseCloneGroup {
119 instances: crate::diff_risk::clone_spans(group, duplication.root),
120 })
121 .collect();
122 }
123 snapshot
124 }
125
126 #[must_use]
129 pub fn reports_dead_code(&self, key: &str) -> bool {
130 self.dead_code.contains(key)
131 || self
132 .syntactic_dead_code
133 .as_ref()
134 .is_some_and(|syntactic| syntactic.contains(key))
135 }
136
137 pub fn forget_unused_code_used_under_own_config(&mut self, head: &DeadCodeView<'_>) {
143 let Some(own) = self.own_config_unused_code.as_ref() else {
144 return;
145 };
146 let head_keys = collection_keys(&head.results.unused_files, head.root)
147 .into_iter()
148 .chain(collection_keys(&head.results.unused_exports, head.root));
149 for key in head_keys.filter(|key| !own.contains(key)) {
150 self.dead_code.remove(&key);
151 if let Some(syntactic) = self.syntactic_dead_code.as_mut() {
152 syntactic.remove(&key);
153 }
154 }
155 }
156
157 pub fn absorb_inherited(&mut self, inherited: Self) {
168 let inherited_syntactic = inherited
169 .syntactic_dead_code
170 .unwrap_or_else(|| inherited.dead_code.clone());
171 if let Some(syntactic) = self.syntactic_dead_code.as_mut() {
172 syntactic.extend(inherited_syntactic);
173 }
174 if let Some(own) = self.own_config_unused_code.as_mut() {
177 own.extend(
178 inherited
179 .own_config_unused_code
180 .unwrap_or_else(|| inherited.dead_code.clone()),
181 );
182 }
183 if self.type_aware_identity == inherited.type_aware_identity
186 && self.type_aware_gap_signature == inherited.type_aware_gap_signature
187 {
188 self.dead_code.extend(inherited.dead_code);
189 }
190 self.unprovable_dead_code
191 .extend(inherited.unprovable_dead_code);
192 self.styling.extend(inherited.styling);
193 self.dupes.extend(inherited.dupes);
194 self.boundary_edges.extend(inherited.boundary_edges);
195 self.cycles.extend(inherited.cycles);
196 self.public_api.extend(inherited.public_api);
197 self.inherited_health.push(inherited.health);
198 self.inherited_health.extend(inherited.inherited_health);
199 }
200
201 pub fn inherit_unprovable_dead_code(&mut self, head: &DeadCodeView<'_>) {
211 if self.unprovable_dead_code.is_empty() {
212 return;
213 }
214 let ledger = dead_code_audit_ledger(head.results, head.root, head.config, None);
215 let keys: Vec<String> = ledger
216 .records()
217 .iter()
218 .filter(|record| self.unprovable_dead_code.contains(record.collection))
219 .map(|record| record.stable_key.clone())
220 .collect();
221 if let Some(syntactic) = self.syntactic_dead_code.as_mut() {
222 syntactic.extend(keys.iter().cloned());
223 }
224 self.dead_code.extend(keys);
225 }
226
227 pub fn remap_for_renames(&mut self, renames: &[RenamedFile], root: &Path) {
235 let rename_map: FxHashMap<String, String> = renames
236 .iter()
237 .filter_map(|rename| {
238 let from = relative_key_path(&rename.from, root);
239 let to = relative_key_path(&rename.to, root);
240 (from != to).then_some((from, to))
241 })
242 .collect();
243 if rename_map.is_empty() {
244 return;
245 }
246 self.dead_code = remap_keys_for_renames(&self.dead_code, &rename_map);
247 if let Some(own) = self.own_config_unused_code.as_mut() {
248 *own = remap_keys_for_renames(own, &rename_map);
249 }
250 self.health =
251 remap_complexity_baseline_for_renames(std::mem::take(&mut self.health), &rename_map);
252 self.styling = remap_keys_for_renames(&self.styling, &rename_map);
253 self.dupes = remap_keys_for_renames(&self.dupes, &rename_map);
254 self.cycles = remap_keys_for_renames(&self.cycles, &rename_map);
255 self.public_api = remap_keys_for_renames(&self.public_api, &rename_map);
256 self.branching = self
259 .branching
260 .drain()
261 .map(|(path, totals)| match rename_map.get(&path) {
262 Some(renamed) => (renamed.clone(), totals),
263 None => (path, totals),
264 })
265 .collect();
266 }
267
268 #[must_use]
271 pub fn to_programmatic(&self) -> AuditProgrammaticKeySnapshot {
272 let mut health = complexity_baseline_keys(&self.health);
273 health.extend(self.styling.iter().cloned());
274 AuditProgrammaticKeySnapshot {
275 dead_code: self.dead_code.clone(),
276 health,
277 dupes: self.dupes.clone(),
278 }
279 }
280}
281
282#[must_use]
285pub fn branching_keys(
286 by_file: &fallow_engine::health::BranchingByFile,
287 root: &Path,
288) -> FxHashMap<String, fallow_types::extract::FileBranching> {
289 by_file
290 .iter()
291 .map(|(path, totals)| (relative_key_path(path, root), *totals))
292 .collect()
293}
294
295#[must_use]
306pub fn type_aware_attribution_degrade_reason(
307 base: Option<&AuditKeySnapshot>,
308 head: Option<&fallow_types::envelope::TypeAwareMeta>,
309) -> Option<&'static str> {
310 let base = base?;
311 let base_identity = base.type_aware_identity.as_ref();
312 let head_identity = head.and_then(|meta| meta.identity.as_ref());
313 if let (Some(base_identity), Some(head_identity)) = (base_identity, head_identity)
314 && !base_identity.incompatible_fields(head_identity).is_empty()
315 {
316 return Some("their semantic analysis identities are incompatible");
317 }
318 if let Some(head) = head
319 && base.type_aware_gap_signature != type_aware_gap_signature(head)
320 {
321 return Some("their incomplete semantic query reasons or omissions differ");
322 }
323 None
324}
325
326#[must_use]
329pub fn type_aware_degrade_warning(reason: &str) -> String {
330 format!(
331 "audit compared base and head with syntactic attribution because {reason} \
332(usually a tsconfig or compiler-options change between base and head); \
333type-aware refinement still applies to head findings, and \
334semantic-only findings stay out of the new-only gate for this run; set \
335audit.typeAware: false or pass --no-type-aware to keep the gate syntactic"
336 )
337}
338
339#[must_use]
341pub fn type_aware_gap_signature(meta: &fallow_types::envelope::TypeAwareMeta) -> Vec<String> {
342 let mut signature = meta
343 .queries
344 .iter()
345 .filter(|query| query.status != fallow_types::semantic::SemanticCompleteness::Complete)
346 .map(|query| {
347 let mut omissions = query
348 .omissions
349 .iter()
350 .map(|omission| format!("{:?}:{}", omission.reason_code, omission.count))
351 .collect::<Vec<_>>();
352 omissions.sort();
353 format!(
354 "{:?}:{:?}:{}",
355 query.capability,
356 query.reason_code,
357 omissions.join(",")
358 )
359 })
360 .collect::<Vec<_>>();
361 signature.sort();
362 signature
363}