Skip to main content

fallow_types/
identity.rs

1//! Stable public identity for findings.
2//!
3//! This module owns the FNV-1a 64 hash that CodeClimate fingerprints, SARIF
4//! fingerprints and security ids use, and the `finding_id` of dead-code
5//! findings. One implementation keeps the surfaces from drifting apart.
6//!
7//! A dead-code id has the form `dc1:<rule>:<16 hex digits>`. The hash input is
8//! `["dc1", rule, parts...]`, where the parts name the subject of the finding:
9//! root-relative forward-slash paths and raw symbol names. Line and column are
10//! never parts, so a line shift, a reformat or a reorder keeps the id. A
11//! rename of the file or the symbol, or another issue type, gives a new id.
12//!
13//! When several findings of one type have the same parts, they are sorted by
14//! line, column, span start and serialized finding. The first one keeps the
15//! base id. The finding at sorted position `k` gets the suffix `~k`.
16//!
17//! The canonical key is the readable form of the same input:
18//! `<rule>:<part>:<part>...`, for example `unused-export:src/utils.ts:helper`.
19//! Baselines and the audit new-only gate compare findings by this key, so the
20//! id, the baseline and the audit can never disagree on what one finding is.
21//! The key has no tiebreak suffix: a baseline stores one key for each
22//! occurrence, and the audit numbers repeated keys itself.
23//!
24//! [`stamp_dead_code_finding_ids`](crate::identity::stamp_dead_code_finding_ids) writes the ids onto a full result set. The
25//! analysis pipeline calls it before the workspace, scope, changed-file,
26//! ignore, baseline and rule filters, so a filter never changes the id of a
27//! finding that stays in the report.
28
29use crate::results::ConstantParameterFinding;
30use std::path::Path;
31
32use rustc_hash::{FxHashMap, FxHashSet};
33use serde::Serialize;
34
35use crate::discover::StableFileKey;
36use crate::output_dead_code::{
37    AbsentComponentPropFinding, BoundaryCallViolationFinding, BoundaryCoverageViolationFinding,
38    BoundaryViolationFinding, CircularDependencyFinding, DeprecatedExportInUseFinding,
39    DevDependencyInProductionFinding, DuplicateExportAliasFinding, DuplicateExportFinding,
40    DuplicatePropShapeFinding, DynamicSegmentNameConflictFinding, EmptyCatalogGroupFinding,
41    InvalidClientExportFinding, MisconfiguredDependencyOverrideFinding, MisplacedDirectiveFinding,
42    MixedClientServerBarrelFinding, NamespaceEscapeFinding, PackageCycleFinding,
43    PolicyViolationFinding, PrivateTypeLeakFinding, PropDrillingChainFinding, ReExportCycleFinding,
44    RouteCollisionFinding, TestOnlyDependencyFinding, TestOnlyExportFinding, ThinWrapperFinding,
45    TypeOnlyDependencyFinding, UnlistedBinaryFinding, UnlistedDependencyFinding,
46    UnprovidedInjectFinding, UnrenderedComponentFinding, UnresolvedCatalogReferenceFinding,
47    UnresolvedImportFinding, UnusedCatalogEntryFinding, UnusedClassMemberFinding,
48    UnusedComponentEmitFinding, UnusedComponentInputFinding, UnusedComponentOutputFinding,
49    UnusedComponentPropFinding, UnusedDependencyFinding, UnusedDependencyOverrideFinding,
50    UnusedDevDependencyFinding, UnusedEnumMemberFinding, UnusedExportFinding, UnusedFileFinding,
51    UnusedLoadDataKeyFinding, UnusedNamespaceMemberFinding, UnusedOptionalDependencyFinding,
52    UnusedProtectedClassMemberFinding, UnusedServerActionFinding, UnusedStoreMemberFinding,
53    UnusedSvelteEventFinding, UnusedTypeFinding,
54};
55use crate::output_dead_code::{
56    UnproducedCatchTagFinding, UnusedEffectLayerFinding, UnusedTaggedErrorFinding,
57};
58use crate::results::{
59    AnalysisResults, DependencyOverrideSource, ReExportCycleKind, StaleSuppression,
60    SuppressionOrigin,
61};
62
63/// The version prefix of every dead-code finding id. A change to the hash
64/// inputs moves this prefix, so an old id never matches a new finding.
65pub const DEAD_CODE_ID_SCHEME: &str = "dc1";
66
67const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
68const FNV_PRIME: u64 = 0x0100_0000_01b3;
69/// Written after each part. No UTF-8 string contains this byte, so the parts
70/// `["ab", "c"]` and `["a", "bc"]` give different hashes.
71const PART_SEPARATOR: u8 = 0xff;
72/// Joins the sorted members of a path set into one part.
73const SET_SEPARATOR: &str = "|";
74/// Stands for "every issue kind" in a suppression identity.
75const ANY_KIND: &str = "*";
76
77fn fnv1a64_update(mut hash: u64, bytes: &[u8]) -> u64 {
78    for byte in bytes {
79        hash ^= u64::from(*byte);
80        hash = hash.wrapping_mul(FNV_PRIME);
81    }
82    hash
83}
84
85/// FNV-1a 64 of `bytes`, as 16 lowercase hex digits.
86///
87/// Security ids use this form: one string, no part separators.
88#[must_use]
89pub fn fnv1a64_hex(bytes: &[u8]) -> String {
90    format!("{:016x}", fnv1a64_update(FNV_OFFSET_BASIS, bytes))
91}
92
93/// FNV-1a 64 of `parts`, with the byte `0xff` after each part, as 16
94/// lowercase hex digits.
95///
96/// CodeClimate and SARIF fingerprints and dead-code finding ids use this form.
97/// FNV-1a is used because its output is fixed across Rust versions, which is
98/// not true for `DefaultHasher`.
99#[must_use]
100pub fn fnv1a64_parts(parts: &[&str]) -> String {
101    let hash = parts.iter().fold(FNV_OFFSET_BASIS, |hash, part| {
102        fnv1a64_update(fnv1a64_update(hash, part.as_bytes()), &[PART_SEPARATOR])
103    });
104    format!("{hash:016x}")
105}
106
107/// The base id of a dead-code finding: `dc1:<rule_token>:<hash>`.
108///
109/// `rule_token` is the canonical issue code, for example `unused-export`.
110/// `parts` name the subject of the finding and never contain a line or a
111/// column. The id carries no tiebreak suffix; [`stamp_dead_code_finding_ids`]
112/// adds it when two findings share a base id.
113#[must_use]
114pub fn dead_code_finding_id(rule_token: &str, parts: &[&str]) -> String {
115    let mut input = Vec::with_capacity(parts.len() + 2);
116    input.push(DEAD_CODE_ID_SCHEME);
117    input.push(rule_token);
118    input.extend_from_slice(parts);
119    format!(
120        "{DEAD_CODE_ID_SCHEME}:{rule_token}:{}",
121        fnv1a64_parts(&input)
122    )
123}
124
125/// Joins the rule token and the parts of a canonical key.
126const KEY_SEPARATOR: char = ':';
127/// Starts the occurrence suffix of an audit key, as in a finding id.
128const OCCURRENCE_MARKER: char = '~';
129
130/// Escape `%` and `:` in one part, so the joined key splits back into the
131/// same parts. Other characters stay as they are, so the key stays readable.
132fn escape_key_part(part: &str, key: &mut String) {
133    for character in part.chars() {
134        match character {
135            '%' => key.push_str("%25"),
136            KEY_SEPARATOR => key.push_str("%3A"),
137            other => key.push(other),
138        }
139    }
140}
141
142/// The canonical key of a dead-code finding: `<rule_token>:<part>:<part>...`.
143///
144/// The key holds the same input as [`dead_code_finding_id`], in readable
145/// form. Each part escapes `%` as `%25` and `:` as `%3A`. The key never
146/// holds a line, a column or a tiebreak suffix.
147#[must_use]
148pub fn dead_code_canonical_key(rule_token: &str, parts: &[&str]) -> String {
149    let mut key = String::with_capacity(
150        rule_token.len() + parts.iter().map(|part| part.len() + 1).sum::<usize>(),
151    );
152    key.push_str(rule_token);
153    for part in parts {
154        key.push(KEY_SEPARATOR);
155        escape_key_part(part, &mut key);
156    }
157    key
158}
159
160/// The canonical keys of `findings`, in input order, with an occurrence
161/// suffix on repeated keys.
162///
163/// The first finding with a key gets the plain key. The finding at
164/// occurrence `k` (counted from 0, in input order) gets the extra part `~k`.
165/// Two key sets built this way compare by count: when the base has two
166/// occurrences and the head has three, only the third head key is absent
167/// from the base.
168#[must_use]
169pub fn dead_code_occurrence_keys<T: IdentifiedFinding>(
170    findings: &[T],
171    paths: &IdentityPaths<'_>,
172) -> Vec<String> {
173    let mut seen: FxHashMap<String, usize> = FxHashMap::default();
174    findings
175        .iter()
176        .map(|finding| {
177            let key = finding.canonical_key(paths);
178            let occurrence = seen.entry(key.clone()).or_default();
179            let numbered = if *occurrence == 0 {
180                key
181            } else {
182                format!("{key}{KEY_SEPARATOR}{OCCURRENCE_MARKER}{occurrence}")
183            };
184            *occurrence += 1;
185            numbered
186        })
187        .collect()
188}
189
190/// Turns finding paths into identity parts.
191#[derive(Debug, Clone, Copy)]
192pub struct IdentityPaths<'a> {
193    root: &'a Path,
194}
195
196impl<'a> IdentityPaths<'a> {
197    /// Paths under `root` become root-relative. Other paths stay as they are.
198    #[must_use]
199    pub const fn new(root: &'a Path) -> Self {
200        Self { root }
201    }
202
203    /// The root-relative path with forward slashes.
204    #[must_use]
205    pub fn key(&self, path: &Path) -> String {
206        StableFileKey::from_root_relative(self.root, path)
207            .as_str()
208            .to_owned()
209    }
210
211    /// The sorted, unique keys of `paths`, joined by `|`.
212    ///
213    /// Each key escapes `%` as `%25` and `|` as `%7C` before the join, so a
214    /// file name that contains `|` cannot give the same part as two files.
215    /// A key without these characters does not change.
216    #[must_use]
217    pub fn set<'p>(&self, paths: impl IntoIterator<Item = &'p Path>) -> String {
218        let mut keys: Vec<String> = paths
219            .into_iter()
220            .map(|path| escape_set_member(&self.key(path)))
221            .collect();
222        keys.sort_unstable();
223        keys.dedup();
224        keys.join(SET_SEPARATOR)
225    }
226}
227
228/// Escape the escape character first, then the separator.
229fn escape_set_member(key: &str) -> String {
230    if !key.contains(['%', '|']) {
231        return key.to_owned();
232    }
233    key.replace('%', "%25").replace('|', "%7C")
234}
235
236/// A dead-code finding that carries a stable `finding_id`.
237pub trait IdentifiedFinding: Serialize {
238    /// The canonical issue code of this finding.
239    fn rule_token(&self) -> &'static str;
240
241    /// The parts that name the subject of this finding. Never a line or a
242    /// column.
243    fn identity_parts(&self, paths: &IdentityPaths<'_>) -> Vec<String>;
244
245    /// The canonical key of this finding: the readable form of the id input.
246    /// See [`dead_code_canonical_key`].
247    fn canonical_key(&self, paths: &IdentityPaths<'_>) -> String {
248        let parts = self.identity_parts(paths);
249        let parts: Vec<&str> = parts.iter().map(String::as_str).collect();
250        dead_code_canonical_key(self.rule_token(), &parts)
251    }
252
253    /// Line, column and span start. Used only to order findings that share
254    /// a base id.
255    fn tiebreak_position(&self) -> (u32, u32, u32);
256
257    /// The stamped id, or `None` before the stamping pass.
258    fn finding_id(&self) -> Option<&str>;
259
260    /// Write the id.
261    fn set_finding_id(&mut self, id: Option<String>);
262}
263
264/// How a pass treats ids that a finding already carries.
265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
266enum StampMode {
267    /// Compute every id again from the full set.
268    All,
269    /// Keep every existing id and give an id only to findings without one.
270    Missing,
271}
272
273/// Write a `finding_id` onto every dead-code finding in `results`.
274///
275/// `root` is the project root that makes paths root-relative. The function
276/// overwrites earlier values, so a second call on the same set gives the same
277/// ids. Call it on the full result set, before any filter removes findings:
278/// the tiebreak suffix depends on the other findings with the same base id.
279pub fn stamp_dead_code_finding_ids(results: &mut AnalysisResults, root: &Path) {
280    visit_families(
281        results,
282        &mut StampPass {
283            paths: IdentityPaths::new(root),
284            mode: StampMode::All,
285        },
286    );
287}
288
289/// Give an id to each dead-code finding in `results` that has none, and keep
290/// every existing id.
291///
292/// A stage that adds findings after the scope filters (type-aware refinement)
293/// calls this. A full restamp there would compute tiebreak suffixes over a
294/// filtered set and change the id of a kept finding. A new finding whose base
295/// id is taken gets the lowest free `~k` suffix.
296pub fn stamp_missing_dead_code_finding_ids(results: &mut AnalysisResults, root: &Path) {
297    visit_families(
298        results,
299        &mut StampPass {
300            paths: IdentityPaths::new(root),
301            mode: StampMode::Missing,
302        },
303    );
304}
305
306/// Keep only the dead-code findings whose `finding_id` is in `ids`, and
307/// return the ids that matched a finding.
308///
309/// A finding without an id is removed. Fields that are not findings (entry
310/// point summary, feature flags, export usages) stay as they are.
311#[expect(
312    clippy::implicit_hasher,
313    reason = "fallow standardizes on FxHashSet across the workspace"
314)]
315pub fn retain_dead_code_findings_by_id(
316    results: &mut AnalysisResults,
317    ids: &FxHashSet<String>,
318) -> FxHashSet<String> {
319    let mut pass = RetainPass {
320        ids,
321        matched: FxHashSet::default(),
322        keep_all: false,
323    };
324    visit_families(results, &mut pass);
325    results.security_findings.retain(|finding| {
326        let keep = ids.contains(&finding.finding_id);
327        if keep {
328            pass.matched.insert(finding.finding_id.clone());
329        }
330        keep
331    });
332    pass.matched
333}
334
335/// The ids in `ids` that a dead-code finding in `results` carries.
336///
337/// The pass only reads the findings. It takes `results` mutably because it
338/// shares the family visitor with the passes that write.
339#[expect(
340    clippy::implicit_hasher,
341    reason = "fallow standardizes on FxHashSet across the workspace"
342)]
343pub fn present_dead_code_finding_ids(
344    results: &mut AnalysisResults,
345    ids: &FxHashSet<String>,
346) -> FxHashSet<String> {
347    let mut pass = RetainPass {
348        ids,
349        matched: FxHashSet::default(),
350        keep_all: true,
351    };
352    visit_families(results, &mut pass);
353    pass.matched.extend(
354        results
355            .security_findings
356            .iter()
357            .filter(|finding| ids.contains(&finding.finding_id))
358            .map(|finding| finding.finding_id.clone()),
359    );
360    pass.matched
361}
362
363/// Whether `id` has the syntax of a current dead-code finding id:
364/// `dc1:<rule>:<16 lowercase hex digits>`, with an optional `~<k>` suffix
365/// where `k` is a positive decimal number.
366#[must_use]
367pub fn is_dead_code_finding_id(id: &str) -> bool {
368    let Some(rest) = id
369        .strip_prefix(DEAD_CODE_ID_SCHEME)
370        .and_then(|rest| rest.strip_prefix(':'))
371    else {
372        return false;
373    };
374    let Some((rule, tail)) = rest.split_once(':') else {
375        return false;
376    };
377    let rule_ok = !rule.is_empty()
378        && rule
379            .bytes()
380            .all(|byte| byte.is_ascii_lowercase() || byte == b'-');
381    let (hash, suffix) = match tail.split_once('~') {
382        Some((hash, suffix)) => (hash, Some(suffix)),
383        None => (tail, None),
384    };
385    let hash_ok = hash.len() == HASH_HEX_DIGITS
386        && hash
387            .bytes()
388            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte));
389    let suffix_ok = suffix.is_none_or(|suffix| {
390        !suffix.is_empty()
391            && !suffix.starts_with('0')
392            && suffix.bytes().all(|byte| byte.is_ascii_digit())
393    });
394    rule_ok && hash_ok && suffix_ok
395}
396
397/// The number of hex digits in the hash part of a finding id.
398const HASH_HEX_DIGITS: usize = 16;
399
400/// One pass over every dead-code finding family.
401trait FamilyVisitor {
402    fn visit<T: IdentifiedFinding>(&mut self, findings: &mut Vec<T>);
403}
404
405/// Writes ids, see [`StampMode`].
406struct StampPass<'a> {
407    paths: IdentityPaths<'a>,
408    mode: StampMode,
409}
410
411impl FamilyVisitor for StampPass<'_> {
412    fn visit<T: IdentifiedFinding>(&mut self, findings: &mut Vec<T>) {
413        apply(findings, &self.paths, self.mode);
414    }
415}
416
417/// Records which of `ids` the findings carry. Removes the other findings
418/// unless `keep_all` is set.
419struct RetainPass<'a> {
420    ids: &'a FxHashSet<String>,
421    matched: FxHashSet<String>,
422    keep_all: bool,
423}
424
425impl FamilyVisitor for RetainPass<'_> {
426    fn visit<T: IdentifiedFinding>(&mut self, findings: &mut Vec<T>) {
427        let keep_all = self.keep_all;
428        findings.retain(|finding| {
429            let matched = finding
430                .finding_id()
431                .filter(|id| self.ids.contains(*id))
432                .map(|id| self.matched.insert(id.to_owned()))
433                .is_some();
434            matched || keep_all
435        });
436    }
437}
438#[expect(
439    clippy::too_many_lines,
440    reason = "one exhaustive list of finding families; splitting it would lose the compile-time guard"
441)]
442fn visit_families<V: FamilyVisitor>(results: &mut AnalysisResults, visitor: &mut V) {
443    // No `..` rest pattern: a new field fails to compile here until it is
444    // classified as a finding family or as metadata.
445    let AnalysisResults {
446        shared_state: _,
447        unused_files,
448        unused_exports,
449        unused_types,
450        private_type_leaks,
451        deprecated_exports_in_use,
452        unused_dependencies,
453        unused_dev_dependencies,
454        unused_optional_dependencies,
455        unused_enum_members,
456        unused_class_members,
457        unused_namespace_members,
458        unused_protected_class_members,
459        namespace_escapes,
460        test_only_exports,
461        unused_store_members,
462        unresolved_imports,
463        unlisted_dependencies,
464        unlisted_binaries,
465        duplicate_exports,
466        duplicate_export_aliases,
467        type_only_dependencies,
468        test_only_dependencies,
469        dev_dependencies_in_production,
470        circular_dependencies,
471        package_cycles,
472        re_export_cycles,
473        boundary_violations,
474        boundary_coverage_violations,
475        boundary_call_violations,
476        policy_violations,
477        stale_suppressions,
478        unused_catalog_entries,
479        empty_catalog_groups,
480        unresolved_catalog_references,
481        unused_dependency_overrides,
482        misconfigured_dependency_overrides,
483        invalid_client_exports,
484        mixed_client_server_barrels,
485        misplaced_directives,
486        unprovided_injects,
487        unrendered_components,
488        route_collisions,
489        dynamic_segment_name_conflicts,
490        unused_component_props,
491        absent_component_props,
492        constant_parameters,
493        unused_component_emits,
494        unused_component_inputs,
495        unused_component_outputs,
496        unused_svelte_events,
497        unused_effect_layers,
498        unused_tagged_errors,
499        unproduced_catch_tags,
500        unused_server_actions,
501        unused_load_data_keys,
502        prop_drilling_chains,
503        thin_wrappers,
504        duplicate_prop_shapes,
505        // Security findings carry their own `finding_id` from
506        // `fallow_security::identity`. The other fields are not findings.
507        security_findings: _,
508        suppressed_security_findings: _,
509        security_unresolved_edge_files: _,
510        security_unresolved_callee_sites: _,
511        security_unresolved_callee_diagnostics: _,
512        unused_load_data_keys_global_abstain: _,
513        // The cascade filter runs after the ids are stamped, so a hidden
514        // finding keeps the id it had in the report.
515        cascade_hidden: _,
516        cascade: _,
517        suppression_count: _,
518        unused_component_props_exempted: _,
519        active_suppressions: _,
520        feature_flags: _,
521        export_usages: _,
522        entry_point_summary: _,
523        render_fan_in: _,
524        react_component_intel: _,
525        semantic_reachable_files: _,
526        semantic_framework_contracts: _,
527        constant_parameter_candidates: _,
528    } = results;
529
530    visitor.visit(unused_files);
531    visitor.visit(unused_exports);
532    visitor.visit(unused_types);
533    visitor.visit(private_type_leaks);
534    visitor.visit(deprecated_exports_in_use);
535    visitor.visit(unused_dependencies);
536    visitor.visit(unused_dev_dependencies);
537    visitor.visit(unused_optional_dependencies);
538    visitor.visit(unused_enum_members);
539    visitor.visit(unused_class_members);
540    visitor.visit(unused_namespace_members);
541    visitor.visit(unused_protected_class_members);
542    visitor.visit(namespace_escapes);
543    visitor.visit(test_only_exports);
544    visitor.visit(unused_store_members);
545    visitor.visit(unresolved_imports);
546    visitor.visit(unlisted_dependencies);
547    visitor.visit(unlisted_binaries);
548    visitor.visit(duplicate_exports);
549    visitor.visit(duplicate_export_aliases);
550    visitor.visit(type_only_dependencies);
551    visitor.visit(test_only_dependencies);
552    visitor.visit(dev_dependencies_in_production);
553    visitor.visit(circular_dependencies);
554    visitor.visit(package_cycles);
555    visitor.visit(re_export_cycles);
556    visitor.visit(boundary_violations);
557    visitor.visit(boundary_coverage_violations);
558    visitor.visit(boundary_call_violations);
559    visitor.visit(policy_violations);
560    visitor.visit(stale_suppressions);
561    visitor.visit(unused_catalog_entries);
562    visitor.visit(empty_catalog_groups);
563    visitor.visit(unresolved_catalog_references);
564    visitor.visit(unused_dependency_overrides);
565    visitor.visit(misconfigured_dependency_overrides);
566    visitor.visit(invalid_client_exports);
567    visitor.visit(mixed_client_server_barrels);
568    visitor.visit(misplaced_directives);
569    visitor.visit(unprovided_injects);
570    visitor.visit(unrendered_components);
571    visitor.visit(route_collisions);
572    visitor.visit(dynamic_segment_name_conflicts);
573    visitor.visit(unused_component_props);
574    visitor.visit(absent_component_props);
575    visitor.visit(constant_parameters);
576    visitor.visit(unused_component_emits);
577    visitor.visit(unused_component_inputs);
578    visitor.visit(unused_component_outputs);
579    visitor.visit(unused_svelte_events);
580    visitor.visit(unused_effect_layers);
581    visitor.visit(unused_tagged_errors);
582    visitor.visit(unproduced_catch_tags);
583    visitor.visit(unused_server_actions);
584    visitor.visit(unused_load_data_keys);
585    visitor.visit(prop_drilling_chains);
586    visitor.visit(thin_wrappers);
587    visitor.visit(duplicate_prop_shapes);
588}
589
590fn apply<T: IdentifiedFinding>(findings: &mut [T], paths: &IdentityPaths<'_>, mode: StampMode) {
591    match mode {
592        StampMode::All => stamp(findings, paths),
593        StampMode::Missing => stamp_missing(findings, paths),
594    }
595}
596
597fn base_id<T: IdentifiedFinding>(finding: &T, paths: &IdentityPaths<'_>) -> String {
598    let parts = finding.identity_parts(paths);
599    let parts: Vec<&str> = parts.iter().map(String::as_str).collect();
600    dead_code_finding_id(finding.rule_token(), &parts)
601}
602
603/// The order of findings that share a base id: position first, then the
604/// serialized finding, so the order does not depend on the input order.
605fn tiebreak_key<T: IdentifiedFinding>(finding: &T) -> ((u32, u32, u32), String) {
606    (
607        finding.tiebreak_position(),
608        serde_json::to_string(finding).unwrap_or_default(),
609    )
610}
611
612/// Stamp one finding family. The result does not depend on the input order.
613fn stamp<T: IdentifiedFinding>(findings: &mut [T], paths: &IdentityPaths<'_>) {
614    let mut groups: FxHashMap<String, Vec<usize>> = FxHashMap::default();
615    for (index, finding) in findings.iter_mut().enumerate() {
616        finding.set_finding_id(None);
617        groups
618            .entry(base_id(finding, paths))
619            .or_default()
620            .push(index);
621    }
622    for (base, mut members) in groups {
623        if members.len() > 1 {
624            members.sort_by_cached_key(|&index| tiebreak_key(&findings[index]));
625        }
626        for (position, index) in members.into_iter().enumerate() {
627            let id = if position == 0 {
628                base.clone()
629            } else {
630                format!("{base}~{position}")
631            };
632            findings[index].set_finding_id(Some(id));
633        }
634    }
635}
636
637/// Give an id to each finding of one family that has none.
638fn stamp_missing<T: IdentifiedFinding>(findings: &mut [T], paths: &IdentityPaths<'_>) {
639    let mut missing: Vec<usize> = (0..findings.len())
640        .filter(|&index| findings[index].finding_id().is_none())
641        .collect();
642    if missing.is_empty() {
643        return;
644    }
645    let mut taken: FxHashSet<String> = findings
646        .iter()
647        .filter_map(|finding| finding.finding_id().map(str::to_owned))
648        .collect();
649    missing.sort_by_cached_key(|&index| tiebreak_key(&findings[index]));
650    for index in missing {
651        let base = base_id(&findings[index], paths);
652        let mut id = base.clone();
653        let mut suffix = 0_usize;
654        while taken.contains(&id) {
655            suffix += 1;
656            id = format!("{base}~{suffix}");
657        }
658        taken.insert(id.clone());
659        findings[index].set_finding_id(Some(id));
660    }
661}
662
663/// Implement [`IdentifiedFinding`] for a type with a `finding_id` field.
664macro_rules! identified {
665    (
666        $ty:ty,
667        token: |$t:ident| $token:expr,
668        parts: |$f:ident, $p:ident| $parts:expr,
669        position: |$g:ident| $position:expr $(,)?
670    ) => {
671        impl IdentifiedFinding for $ty {
672            fn rule_token(&self) -> &'static str {
673                let $t = self;
674                $token
675            }
676
677            fn identity_parts(&self, $p: &IdentityPaths<'_>) -> Vec<String> {
678                let $f = self;
679                $parts
680            }
681
682            fn tiebreak_position(&self) -> (u32, u32, u32) {
683                let $g = self;
684                $position
685            }
686
687            fn finding_id(&self) -> Option<&str> {
688                self.finding_id.as_deref()
689            }
690
691            fn set_finding_id(&mut self, id: Option<String>) {
692                self.finding_id = id;
693            }
694        }
695    };
696}
697
698identified!(
699    UnusedFileFinding,
700    token: |_t| "unused-file",
701    parts: |f, p| vec![p.key(&f.file.path)],
702    position: |_g| (0, 0, 0),
703);
704
705identified!(
706    UnusedExportFinding,
707    token: |_t| "unused-export",
708    parts: |f, p| vec![p.key(&f.export.path), f.export.export_name.clone()],
709    position: |g| (g.export.line, g.export.col, g.export.span_start),
710);
711
712identified!(
713    UnusedTypeFinding,
714    token: |_t| "unused-type",
715    parts: |f, p| vec![p.key(&f.export.path), f.export.export_name.clone()],
716    position: |g| (g.export.line, g.export.col, g.export.span_start),
717);
718
719identified!(
720    PrivateTypeLeakFinding,
721    token: |_t| "private-type-leak",
722    parts: |f, p| vec![
723        p.key(&f.leak.path),
724        f.leak.export_name.clone(),
725        f.leak.type_name.clone(),
726    ],
727    position: |g| (g.leak.line, g.leak.col, g.leak.span_start),
728);
729
730identified!(
731    DeprecatedExportInUseFinding,
732    token: |_t| "deprecated-export-in-use",
733    parts: |f, p| vec![p.key(&f.export.path), f.export.export_name.clone()],
734    position: |g| (g.export.line, g.export.col, g.export.span_start),
735);
736
737identified!(
738    UnusedDependencyFinding,
739    token: |_t| "unused-dependency",
740    parts: |f, p| vec![p.key(&f.dep.path), f.dep.package_name.clone()],
741    position: |g| (g.dep.line, 0, 0),
742);
743
744identified!(
745    UnusedDevDependencyFinding,
746    token: |_t| "unused-dev-dependency",
747    parts: |f, p| vec![p.key(&f.dep.path), f.dep.package_name.clone()],
748    position: |g| (g.dep.line, 0, 0),
749);
750
751identified!(
752    UnusedOptionalDependencyFinding,
753    token: |_t| "unused-optional-dependency",
754    parts: |f, p| vec![p.key(&f.dep.path), f.dep.package_name.clone()],
755    position: |g| (g.dep.line, 0, 0),
756);
757
758identified!(
759    TypeOnlyDependencyFinding,
760    token: |_t| "type-only-dependency",
761    parts: |f, p| vec![p.key(&f.dep.path), f.dep.package_name.clone()],
762    position: |g| (g.dep.line, 0, 0),
763);
764
765identified!(
766    TestOnlyDependencyFinding,
767    token: |_t| "test-only-dependency",
768    parts: |f, p| vec![p.key(&f.dep.path), f.dep.package_name.clone()],
769    position: |g| (g.dep.line, 0, 0),
770);
771
772identified!(
773    DevDependencyInProductionFinding,
774    token: |_t| "dev-dependency-in-production",
775    parts: |f, p| vec![p.key(&f.dep.path), f.dep.package_name.clone()],
776    position: |g| (g.dep.line, 0, 0),
777);
778
779identified!(
780    UnlistedDependencyFinding,
781    token: |_t| "unlisted-dependency",
782    parts: |f, _p| vec![f.dep.package_name.clone()],
783    position: |_g| (0, 0, 0),
784);
785
786identified!(
787    UnlistedBinaryFinding,
788    token: |_t| "unlisted-binary",
789    parts: |f, _p| vec![f.binary.binary_name.clone()],
790    position: |_g| (0, 0, 0),
791);
792
793identified!(
794    UnusedEnumMemberFinding,
795    token: |_t| "unused-enum-member",
796    parts: |f, p| member_parts(&f.member, p),
797    position: |g| (g.member.line, g.member.col, 0),
798);
799
800identified!(
801    UnusedClassMemberFinding,
802    token: |_t| "unused-class-member",
803    parts: |f, p| member_parts(&f.member, p),
804    position: |g| (g.member.line, g.member.col, 0),
805);
806
807identified!(
808    UnusedProtectedClassMemberFinding,
809    token: |_t| "unused-protected-class-member",
810    parts: |f, p| member_parts(&f.member, p),
811    position: |g| (g.member.line, g.member.col, 0),
812);
813
814identified!(
815    NamespaceEscapeFinding,
816    token: |_t| "namespace-escape",
817    parts: |f, p| vec![
818        p.key(&f.escape.path),
819        f.escape.local_name.clone(),
820        p.key(&f.escape.module),
821    ],
822    position: |g| (g.escape.line, g.escape.col, 0),
823);
824
825identified!(
826    TestOnlyExportFinding,
827    token: |_t| "test-only-export",
828    parts: |f, p| vec![p.key(&f.export.path), f.export.export_name.clone()],
829    position: |g| (g.export.line, g.export.col, 0),
830);
831
832identified!(
833    UnusedNamespaceMemberFinding,
834    token: |_t| "unused-namespace-member",
835    parts: |f, p| member_parts(&f.member, p),
836    position: |g| (g.member.line, g.member.col, 0),
837);
838
839identified!(
840    UnusedStoreMemberFinding,
841    token: |_t| "unused-store-member",
842    parts: |f, p| member_parts(&f.member, p),
843    position: |g| (g.member.line, g.member.col, 0),
844);
845
846fn member_parts(member: &crate::results::UnusedMember, paths: &IdentityPaths<'_>) -> Vec<String> {
847    vec![
848        paths.key(&member.path),
849        member.parent_name.clone(),
850        member.member_name.clone(),
851    ]
852}
853
854identified!(
855    UnresolvedImportFinding,
856    token: |_t| "unresolved-import",
857    parts: |f, p| vec![p.key(&f.import.path), f.import.specifier.clone()],
858    position: |g| (g.import.line, g.import.col, 0),
859);
860
861identified!(
862    DuplicateExportFinding,
863    token: |_t| "duplicate-export",
864    parts: |f, p| vec![
865        f.export.export_name.clone(),
866        p.set(f.export.locations.iter().map(|location| location.path.as_path())),
867    ],
868    position: |g| g
869        .export
870        .locations
871        .first()
872        .map_or((0, 0, 0), |location| (location.line, location.col, 0)),
873);
874
875identified!(
876    CircularDependencyFinding,
877    token: |_t| "circular-dependency",
878    parts: |f, p| vec![p.set(f.cycle.files.iter().map(std::path::PathBuf::as_path))],
879    position: |g| (g.cycle.line, g.cycle.col, 0),
880);
881
882identified!(
883    PackageCycleFinding,
884    token: |_t| "package-cycle",
885    parts: |f, p| vec![p.set(f.cycle.package_roots.iter().map(std::path::PathBuf::as_path))],
886    position: |_g| (0, 0, 0),
887);
888
889identified!(
890    ReExportCycleFinding,
891    token: |_t| "re-export-cycle",
892    parts: |f, p| vec![
893        re_export_cycle_kind(f.cycle.kind).to_owned(),
894        p.set(f.cycle.files.iter().map(std::path::PathBuf::as_path)),
895    ],
896    position: |_g| (0, 0, 0),
897);
898
899/// The wire spelling of the cycle kind, so the part matches the JSON value.
900const fn re_export_cycle_kind(kind: ReExportCycleKind) -> &'static str {
901    match kind {
902        ReExportCycleKind::MultiNode => "multi-node",
903        ReExportCycleKind::SelfLoop => "self-loop",
904    }
905}
906
907identified!(
908    BoundaryViolationFinding,
909    token: |_t| "boundary-violation",
910    parts: |f, p| vec![p.key(&f.violation.from_path), p.key(&f.violation.to_path)],
911    position: |g| (g.violation.line, g.violation.col, 0),
912);
913
914identified!(
915    BoundaryCoverageViolationFinding,
916    token: |_t| "boundary-coverage",
917    parts: |f, p| vec![p.key(&f.violation.path)],
918    position: |g| (g.violation.line, g.violation.col, 0),
919);
920
921identified!(
922    BoundaryCallViolationFinding,
923    token: |_t| "boundary-call-violation",
924    parts: |f, p| vec![p.key(&f.violation.path), f.violation.callee.clone()],
925    position: |g| (g.violation.line, g.violation.col, 0),
926);
927
928identified!(
929    PolicyViolationFinding,
930    token: |_t| "policy-violation",
931    parts: |f, p| vec![
932        p.key(&f.violation.path),
933        f.violation.pack.clone(),
934        f.violation.rule_id.clone(),
935        f.violation.matched.clone(),
936    ],
937    position: |g| (g.violation.line, g.violation.col, 0),
938);
939
940identified!(
941    StaleSuppression,
942    token: |t| if t.missing_reason {
943        "missing-suppression-reason"
944    } else {
945        "stale-suppression"
946    },
947    parts: |f, p| suppression_parts(f, p),
948    position: |g| (g.line, g.col, 0),
949);
950
951/// Path, origin kind, issue kind (or `*`), and scope or export name. The
952/// reason text is not a part: adding a reason must not change the id.
953fn suppression_parts(suppression: &StaleSuppression, paths: &IdentityPaths<'_>) -> Vec<String> {
954    let path = paths.key(&suppression.path);
955    match &suppression.origin {
956        SuppressionOrigin::Comment {
957            issue_kind,
958            is_file_level,
959            ..
960        } => vec![
961            path,
962            "comment".to_owned(),
963            issue_kind.clone().unwrap_or_else(|| ANY_KIND.to_owned()),
964            if *is_file_level { "file" } else { "line" }.to_owned(),
965        ],
966        SuppressionOrigin::JsdocTag { export_name, .. } => vec![
967            path,
968            "jsdoc_tag".to_owned(),
969            ANY_KIND.to_owned(),
970            export_name.clone(),
971        ],
972    }
973}
974
975identified!(
976    UnusedCatalogEntryFinding,
977    token: |_t| "unused-catalog-entry",
978    parts: |f, p| vec![
979        p.key(&f.entry.path),
980        f.entry.catalog_name.clone(),
981        f.entry.entry_name.clone(),
982    ],
983    position: |g| (g.entry.line, 0, 0),
984);
985
986identified!(
987    EmptyCatalogGroupFinding,
988    token: |_t| "empty-catalog-group",
989    parts: |f, p| vec![p.key(&f.group.path), f.group.catalog_name.clone()],
990    position: |g| (g.group.line, 0, 0),
991);
992
993identified!(
994    UnresolvedCatalogReferenceFinding,
995    token: |_t| "unresolved-catalog-reference",
996    parts: |f, p| vec![
997        p.key(&f.reference.path),
998        f.reference.catalog_name.clone(),
999        f.reference.entry_name.clone(),
1000    ],
1001    position: |g| (g.reference.line, 0, 0),
1002);
1003
1004identified!(
1005    UnusedDependencyOverrideFinding,
1006    token: |_t| "unused-dependency-override",
1007    parts: |f, _p| vec![override_source(f.entry.source).to_owned(), f.entry.raw_key.clone()],
1008    position: |g| (g.entry.line, 0, 0),
1009);
1010
1011identified!(
1012    MisconfiguredDependencyOverrideFinding,
1013    token: |_t| "misconfigured-dependency-override",
1014    parts: |f, _p| vec![override_source(f.entry.source).to_owned(), f.entry.raw_key.clone()],
1015    position: |g| (g.entry.line, 0, 0),
1016);
1017
1018/// The wire spelling of the override source, so the part matches the JSON
1019/// value.
1020const fn override_source(source: DependencyOverrideSource) -> &'static str {
1021    match source {
1022        DependencyOverrideSource::PnpmWorkspaceYaml => "pnpm-workspace.yaml",
1023        DependencyOverrideSource::PnpmPackageJson => "package.json",
1024    }
1025}
1026
1027identified!(
1028    InvalidClientExportFinding,
1029    token: |_t| "invalid-client-export",
1030    parts: |f, p| vec![p.key(&f.export.path), f.export.export_name.clone()],
1031    position: |g| (g.export.line, g.export.col, 0),
1032);
1033
1034identified!(
1035    MixedClientServerBarrelFinding,
1036    token: |_t| "mixed-client-server-barrel",
1037    parts: |f, p| vec![p.key(&f.barrel.path)],
1038    position: |g| (g.barrel.line, g.barrel.col, 0),
1039);
1040
1041identified!(
1042    MisplacedDirectiveFinding,
1043    token: |_t| "misplaced-directive",
1044    parts: |f, p| vec![
1045        p.key(&f.directive_site.path),
1046        f.directive_site.directive.clone(),
1047    ],
1048    position: |g| (g.directive_site.line, g.directive_site.col, 0),
1049);
1050
1051identified!(
1052    UnprovidedInjectFinding,
1053    token: |_t| "unprovided-inject",
1054    parts: |f, p| vec![p.key(&f.inject.path), f.inject.key_name.clone()],
1055    position: |g| (g.inject.line, g.inject.col, 0),
1056);
1057
1058identified!(
1059    UnrenderedComponentFinding,
1060    token: |_t| "unrendered-component",
1061    parts: |f, p| vec![p.key(&f.component.path), f.component.component_name.clone()],
1062    position: |g| (g.component.line, g.component.col, 0),
1063);
1064
1065identified!(
1066    RouteCollisionFinding,
1067    token: |_t| "route-collision",
1068    parts: |f, p| vec![p.key(&f.collision.path), f.collision.url.clone()],
1069    position: |g| (g.collision.line, g.collision.col, 0),
1070);
1071
1072identified!(
1073    DynamicSegmentNameConflictFinding,
1074    token: |_t| "dynamic-segment-name-conflict",
1075    parts: |f, p| vec![p.key(&f.conflict.path), f.conflict.position.clone()],
1076    position: |g| (g.conflict.line, g.conflict.col, 0),
1077);
1078
1079identified!(
1080    UnusedComponentPropFinding,
1081    token: |_t| "unused-component-prop",
1082    parts: |f, p| vec![
1083        p.key(&f.prop.path),
1084        f.prop.component_name.clone(),
1085        f.prop.prop_name.clone(),
1086    ],
1087    position: |g| (g.prop.line, g.prop.col, 0),
1088);
1089identified!(
1090    ConstantParameterFinding,
1091    token: |_t| "constant-parameter",
1092    parts: |f, p| vec![
1093        p.key(&f.parameter.path),
1094        f.parameter.function_name.clone(),
1095        f.parameter.parameter_name.clone(),
1096    ],
1097    position: |g| (g.parameter.line, g.parameter.col, 0),
1098);
1099identified!(
1100    AbsentComponentPropFinding,
1101    token: |_t| "absent-component-prop",
1102    parts: |f, p| vec![
1103        p.key(&f.prop.path),
1104        f.prop.component_name.clone(),
1105        f.prop.prop_name.clone(),
1106    ],
1107    position: |g| (g.prop.line, g.prop.col, 0),
1108);
1109
1110identified!(
1111    UnusedComponentEmitFinding,
1112    token: |_t| "unused-component-emit",
1113    parts: |f, p| vec![
1114        p.key(&f.emit.path),
1115        f.emit.component_name.clone(),
1116        f.emit.emit_name.clone(),
1117    ],
1118    position: |g| (g.emit.line, g.emit.col, 0),
1119);
1120
1121identified!(
1122    UnusedComponentInputFinding,
1123    token: |_t| "unused-component-input",
1124    parts: |f, p| vec![
1125        p.key(&f.input.path),
1126        f.input.component_name.clone(),
1127        f.input.input_name.clone(),
1128    ],
1129    position: |g| (g.input.line, g.input.col, 0),
1130);
1131
1132identified!(
1133    UnusedComponentOutputFinding,
1134    token: |_t| "unused-component-output",
1135    parts: |f, p| vec![
1136        p.key(&f.output.path),
1137        f.output.component_name.clone(),
1138        f.output.output_name.clone(),
1139    ],
1140    position: |g| (g.output.line, g.output.col, 0),
1141);
1142
1143identified!(
1144    DuplicateExportAliasFinding,
1145    token: |_t| "duplicate-export-alias",
1146    parts: |f, p| {
1147        let mut names = f.alias.export_names.clone();
1148        names.sort_unstable();
1149        vec![p.key(&f.alias.path), f.alias.local_name.clone(), names.join(",")]
1150    },
1151    position: |g| (g.alias.line, g.alias.col, 0),
1152);
1153
1154identified!(
1155    UnusedSvelteEventFinding,
1156    token: |_t| "unused-svelte-event",
1157    parts: |f, p| vec![
1158        p.key(&f.event.path),
1159        f.event.component_name.clone(),
1160        f.event.event_name.clone(),
1161    ],
1162    position: |g| (g.event.line, g.event.col, 0),
1163);
1164
1165identified!(
1166    UnusedEffectLayerFinding,
1167    token: |_t| "unused-effect-layer",
1168    parts: |f, p| vec![p.key(&f.layer.path), f.layer.name.clone()],
1169    position: |g| (g.layer.line, g.layer.col, 0),
1170);
1171
1172identified!(
1173    UnusedTaggedErrorFinding,
1174    token: |_t| "unused-tagged-error",
1175    parts: |f, p| vec![
1176        p.key(&f.error.path),
1177        f.error.name.clone(),
1178        f.error.tag.clone(),
1179    ],
1180    position: |g| (g.error.line, g.error.col, 0),
1181);
1182
1183identified!(
1184    UnproducedCatchTagFinding,
1185    token: |_t| "unproduced-catch-tag",
1186    parts: |f, p| vec![p.key(&f.catch_tag.path), f.catch_tag.tag.clone()],
1187    position: |g| (g.catch_tag.line, g.catch_tag.col, 0),
1188);
1189
1190identified!(
1191    UnusedServerActionFinding,
1192    token: |_t| "unused-server-action",
1193    parts: |f, p| vec![p.key(&f.action.path), f.action.action_name.clone()],
1194    position: |g| (g.action.line, g.action.col, 0),
1195);
1196
1197identified!(
1198    UnusedLoadDataKeyFinding,
1199    token: |_t| "unused-load-data-key",
1200    parts: |f, p| vec![p.key(&f.key.path), f.key.key_name.clone()],
1201    position: |g| (g.key.line, g.key.col, 0),
1202);
1203
1204identified!(
1205    PropDrillingChainFinding,
1206    token: |_t| "prop-drilling",
1207    parts: |f, p| {
1208        let origin = f.chain.hops.first();
1209        vec![
1210            origin.map(|hop| p.key(&hop.file)).unwrap_or_default(),
1211            origin.map(|hop| hop.component.clone()).unwrap_or_default(),
1212            f.chain.prop.clone(),
1213        ]
1214    },
1215    position: |g| (g.chain.hops.first().map_or(0, |hop| hop.line), 0, 0),
1216);
1217
1218identified!(
1219    ThinWrapperFinding,
1220    token: |_t| "thin-wrapper",
1221    parts: |f, p| vec![p.key(&f.wrapper.file), f.wrapper.component.clone()],
1222    position: |g| (g.wrapper.line, 0, 0),
1223);
1224
1225identified!(
1226    DuplicatePropShapeFinding,
1227    token: |_t| "duplicate-prop-shape",
1228    parts: |f, p| vec![p.key(&f.shape.file), f.shape.component.clone()],
1229    position: |g| (g.shape.line, 0, 0),
1230);
1231
1232#[cfg(test)]
1233mod tests {
1234    use std::path::PathBuf;
1235
1236    use super::*;
1237    use crate::results::{UnusedExport, UnusedFile, UnusedMember};
1238
1239    // Every expected value below comes from an independent FNV-1a 64 script,
1240    // not from this module.
1241
1242    #[test]
1243    fn fnv1a64_parts_golden_values() {
1244        assert_eq!(
1245            fnv1a64_parts(&["src/index.ts", "FEATURE_X", "3"]),
1246            "2278c9d9bd9d2dd2"
1247        );
1248        assert_eq!(
1249            fnv1a64_parts(&["fallow/unused-file", "src/orphan.ts"]),
1250            "c03b925ddb7d871a"
1251        );
1252        assert_eq!(fnv1a64_parts(&[]), "cbf29ce484222325");
1253    }
1254
1255    #[test]
1256    fn fnv1a64_hex_golden_value() {
1257        assert_eq!(
1258            fnv1a64_hex(b"security/client-server-leak:src/a.ts:3:7"),
1259            "89b6dece9d8b96d2"
1260        );
1261    }
1262
1263    #[test]
1264    fn finding_id_syntax_accepts_base_and_tiebreak_ids() {
1265        assert!(is_dead_code_finding_id(
1266            "dc1:unused-export:81a349a3b9ea3b15"
1267        ));
1268        assert!(is_dead_code_finding_id(
1269            "dc1:unused-class-member:0123456789abcdef~1"
1270        ));
1271        assert!(is_dead_code_finding_id(
1272            "dc1:unused-file:0123456789abcdef~12"
1273        ));
1274    }
1275
1276    #[test]
1277    fn finding_id_syntax_refuses_other_shapes() {
1278        for bad in [
1279            "",
1280            "dc1",
1281            "dc1:unused-export",
1282            "dc1::0123456789abcdef",
1283            "dc2:unused-export:0123456789abcdef",
1284            "dc1:unused-export:0123456789ABCDEF",
1285            "dc1:unused-export:0123456789abcde",
1286            "dc1:unused-export:0123456789abcdef0",
1287            "dc1:unused-export:0123456789abcdef~",
1288            "dc1:unused-export:0123456789abcdef~0",
1289            "dc1:unused-export:0123456789abcdef~01",
1290            "dc1:unused-export:0123456789abcdef~x",
1291            "dc1:Unused-Export:0123456789abcdef",
1292            "dc1:unused-export:0123456789abcdef:extra",
1293        ] {
1294            assert!(!is_dead_code_finding_id(bad), "{bad:?} was accepted");
1295        }
1296    }
1297
1298    #[test]
1299    fn retain_by_id_keeps_only_the_requested_findings() {
1300        let root = PathBuf::from("/repo");
1301        let mut results = AnalysisResults {
1302            unused_files: vec![
1303                UnusedFileFinding::with_actions(UnusedFile {
1304                    path: root.join("src/a.ts"),
1305                }),
1306                UnusedFileFinding::with_actions(UnusedFile {
1307                    path: root.join("src/b.ts"),
1308                }),
1309            ],
1310            ..AnalysisResults::default()
1311        };
1312        stamp_dead_code_finding_ids(&mut results, &root);
1313        let kept = results.unused_files[1]
1314            .finding_id
1315            .clone()
1316            .expect("stamped id");
1317        let ids: FxHashSet<String> = [kept.clone(), "dc1:unused-file:0000000000000000".to_owned()]
1318            .into_iter()
1319            .collect();
1320
1321        let present = present_dead_code_finding_ids(&mut results, &ids);
1322        assert_eq!(results.unused_files.len(), 2, "present only reads");
1323        let matched = retain_dead_code_findings_by_id(&mut results, &ids);
1324
1325        assert_eq!(present, matched);
1326        assert_eq!(matched, std::iter::once(kept.clone()).collect());
1327        assert_eq!(results.unused_files.len(), 1);
1328        assert_eq!(
1329            results.unused_files[0].finding_id.as_deref(),
1330            Some(kept.as_str())
1331        );
1332    }
1333
1334    #[test]
1335    fn dead_code_finding_id_golden_values() {
1336        assert_eq!(
1337            dead_code_finding_id("unused-export", &["src/utils.ts", "helper"]),
1338            "dc1:unused-export:81a349a3b9ea3b15"
1339        );
1340        assert_eq!(
1341            dead_code_finding_id("unused-file", &["src/orphan.ts"]),
1342            "dc1:unused-file:9fd2d414a2a9e611"
1343        );
1344        assert_eq!(
1345            dead_code_finding_id("unused-class-member", &["src/service.ts", "Service", "run"]),
1346            "dc1:unused-class-member:675fa79a4c2f244f"
1347        );
1348        assert_eq!(
1349            dead_code_finding_id("unused-dependency", &["package.json", "lodash"]),
1350            "dc1:unused-dependency:e2f217ff5a209568"
1351        );
1352        assert_eq!(
1353            dead_code_finding_id("duplicate-export", &["Button", "src/a.ts|src/b.ts"]),
1354            "dc1:duplicate-export:17c140e16d40660a"
1355        );
1356    }
1357
1358    fn export(root: &Path, name: &str, line: u32) -> UnusedExportFinding {
1359        UnusedExportFinding::with_actions(UnusedExport {
1360            path: root.join("src/utils.ts"),
1361            export_name: name.to_owned(),
1362            is_type_only: false,
1363            line,
1364            col: 7,
1365            span_start: line * 10,
1366            is_re_export: false,
1367            deprecated: false,
1368            deprecated_reason: None,
1369        })
1370    }
1371
1372    fn member(root: &Path, line: u32) -> UnusedClassMemberFinding {
1373        UnusedClassMemberFinding::with_actions(UnusedMember {
1374            path: root.join("src/service.ts"),
1375            parent_name: "Service".to_owned(),
1376            member_name: "run".to_owned(),
1377            kind: crate::extract::MemberKind::ClassMethod,
1378            line,
1379            col: 2,
1380        })
1381    }
1382
1383    fn ids<T: IdentifiedFinding>(findings: &[T]) -> Vec<Option<String>> {
1384        findings
1385            .iter()
1386            .map(|finding| finding.finding_id().map(str::to_owned))
1387            .collect()
1388    }
1389
1390    #[test]
1391    fn stamping_uses_root_relative_paths_and_ignores_lines() {
1392        let root = PathBuf::from("/repo");
1393        let mut results = AnalysisResults {
1394            unused_files: vec![UnusedFileFinding::with_actions(UnusedFile {
1395                path: root.join("src/orphan.ts"),
1396            })],
1397            unused_exports: vec![export(&root, "helper", 40)],
1398            ..AnalysisResults::default()
1399        };
1400
1401        stamp_dead_code_finding_ids(&mut results, &root);
1402
1403        assert_eq!(
1404            ids(&results.unused_files),
1405            vec![Some("dc1:unused-file:9fd2d414a2a9e611".to_owned())]
1406        );
1407        assert_eq!(
1408            ids(&results.unused_exports),
1409            vec![Some("dc1:unused-export:81a349a3b9ea3b15".to_owned())]
1410        );
1411    }
1412
1413    #[test]
1414    fn duplicate_subjects_get_a_tiebreak_suffix_in_line_order() {
1415        let root = PathBuf::from("/repo");
1416        let mut results = AnalysisResults {
1417            unused_class_members: vec![member(&root, 30), member(&root, 10), member(&root, 20)],
1418            ..AnalysisResults::default()
1419        };
1420
1421        stamp_dead_code_finding_ids(&mut results, &root);
1422
1423        let base = "dc1:unused-class-member:675fa79a4c2f244f";
1424        assert_eq!(
1425            ids(&results.unused_class_members),
1426            vec![
1427                Some(format!("{base}~2")),
1428                Some(base.to_owned()),
1429                Some(format!("{base}~1")),
1430            ]
1431        );
1432    }
1433
1434    #[test]
1435    fn stamping_does_not_depend_on_input_order() {
1436        let root = PathBuf::from("/repo");
1437        let forward = vec![member(&root, 10), member(&root, 20), member(&root, 30)];
1438        let mut reversed = forward.clone();
1439        reversed.reverse();
1440        let mut a = AnalysisResults {
1441            unused_class_members: forward,
1442            ..AnalysisResults::default()
1443        };
1444        let mut b = AnalysisResults {
1445            unused_class_members: reversed,
1446            ..AnalysisResults::default()
1447        };
1448
1449        stamp_dead_code_finding_ids(&mut a, &root);
1450        stamp_dead_code_finding_ids(&mut b, &root);
1451
1452        let mut a_pairs: Vec<(u32, Option<String>)> = a
1453            .unused_class_members
1454            .iter()
1455            .map(|finding| (finding.member.line, finding.finding_id.clone()))
1456            .collect();
1457        let mut b_pairs: Vec<(u32, Option<String>)> = b
1458            .unused_class_members
1459            .iter()
1460            .map(|finding| (finding.member.line, finding.finding_id.clone()))
1461            .collect();
1462        a_pairs.sort();
1463        b_pairs.sort();
1464        assert_eq!(a_pairs, b_pairs);
1465    }
1466
1467    #[test]
1468    fn stamping_twice_gives_the_same_ids() {
1469        let root = PathBuf::from("/repo");
1470        let mut results = AnalysisResults {
1471            unused_class_members: vec![member(&root, 10), member(&root, 20)],
1472            unused_exports: vec![export(&root, "helper", 3)],
1473            ..AnalysisResults::default()
1474        };
1475
1476        stamp_dead_code_finding_ids(&mut results, &root);
1477        let first = (
1478            ids(&results.unused_class_members),
1479            ids(&results.unused_exports),
1480        );
1481        stamp_dead_code_finding_ids(&mut results, &root);
1482
1483        assert_eq!(
1484            first,
1485            (
1486                ids(&results.unused_class_members),
1487                ids(&results.unused_exports),
1488            )
1489        );
1490    }
1491
1492    #[test]
1493    fn stamping_missing_ids_keeps_existing_ids_and_takes_a_free_suffix() {
1494        let root = PathBuf::from("/repo");
1495        let mut results = AnalysisResults {
1496            unused_class_members: vec![member(&root, 10), member(&root, 20)],
1497            ..AnalysisResults::default()
1498        };
1499        stamp_dead_code_finding_ids(&mut results, &root);
1500        // A filter removed the base finding; a later stage adds a new one.
1501        results.unused_class_members.remove(0);
1502        results.unused_class_members.push(member(&root, 5));
1503
1504        stamp_missing_dead_code_finding_ids(&mut results, &root);
1505
1506        let base = "dc1:unused-class-member:675fa79a4c2f244f";
1507        assert_eq!(
1508            ids(&results.unused_class_members),
1509            vec![Some(format!("{base}~1")), Some(base.to_owned())]
1510        );
1511    }
1512
1513    fn duplicate_export(root: &Path, files: &[&str]) -> DuplicateExportFinding {
1514        DuplicateExportFinding::with_actions(crate::results::DuplicateExport {
1515            export_name: "Button".to_owned(),
1516            locations: files
1517                .iter()
1518                .map(|file| crate::results::DuplicateLocation {
1519                    path: root.join(file),
1520                    line: 1,
1521                    col: 0,
1522                })
1523                .collect(),
1524        })
1525    }
1526
1527    #[test]
1528    fn a_path_set_without_special_characters_keeps_its_golden_id() {
1529        let root = PathBuf::from("/repo");
1530        let mut results = AnalysisResults {
1531            duplicate_exports: vec![duplicate_export(&root, &["src/b.ts", "src/a.ts"])],
1532            ..AnalysisResults::default()
1533        };
1534
1535        stamp_dead_code_finding_ids(&mut results, &root);
1536
1537        assert_eq!(
1538            ids(&results.duplicate_exports),
1539            vec![Some("dc1:duplicate-export:17c140e16d40660a".to_owned())]
1540        );
1541    }
1542
1543    #[test]
1544    fn a_pipe_in_a_file_name_does_not_collide_with_two_files() {
1545        let root = PathBuf::from("/repo");
1546        let paths = IdentityPaths::new(&root);
1547        let one = root.join("src/a.ts|src/b.ts");
1548        let first = root.join("src/a.ts");
1549        let second = root.join("src/b.ts");
1550
1551        assert_eq!(paths.set([one.as_path()]), "src/a.ts%7Csrc/b.ts");
1552        assert_eq!(
1553            paths.set([first.as_path(), second.as_path()]),
1554            "src/a.ts|src/b.ts"
1555        );
1556        assert_eq!(paths.set([root.join("100%.ts").as_path()]), "100%25.ts");
1557
1558        let mut results = AnalysisResults {
1559            duplicate_exports: vec![
1560                duplicate_export(&root, &["src/a.ts|src/b.ts"]),
1561                duplicate_export(&root, &["src/a.ts", "src/b.ts"]),
1562            ],
1563            ..AnalysisResults::default()
1564        };
1565        stamp_dead_code_finding_ids(&mut results, &root);
1566
1567        let stamped = ids(&results.duplicate_exports);
1568        assert_ne!(stamped[0], stamped[1]);
1569        assert!(
1570            stamped.iter().flatten().all(|id| !id.contains('~')),
1571            "the two findings must not share a base id: {stamped:?}"
1572        );
1573    }
1574
1575    #[test]
1576    fn a_package_cycle_gets_a_golden_id_from_its_sorted_package_roots() {
1577        let root = PathBuf::from("/repo");
1578        let cycle = |roots: &[&str]| {
1579            PackageCycleFinding::with_actions(crate::results::PackageCycle {
1580                packages: vec!["@x/a".to_owned(), "@x/b".to_owned()],
1581                package_roots: roots.iter().map(|dir| root.join(dir)).collect(),
1582                length: 2,
1583                edges: Vec::new(),
1584                group_truncated: false,
1585            })
1586        };
1587        let mut results = AnalysisResults {
1588            package_cycles: vec![cycle(&["packages/b", "packages/a"])],
1589            ..AnalysisResults::default()
1590        };
1591
1592        stamp_dead_code_finding_ids(&mut results, &root);
1593
1594        assert_eq!(
1595            ids(&results.package_cycles),
1596            vec![Some("dc1:package-cycle:fed127e4525389ac".to_owned())]
1597        );
1598    }
1599
1600    #[test]
1601    fn windows_separators_give_the_same_id() {
1602        let mut windows = AnalysisResults {
1603            unused_files: vec![UnusedFileFinding::with_actions(UnusedFile {
1604                path: PathBuf::from("src\\orphan.ts"),
1605            })],
1606            ..AnalysisResults::default()
1607        };
1608
1609        stamp_dead_code_finding_ids(&mut windows, Path::new(""));
1610
1611        assert_eq!(
1612            ids(&windows.unused_files),
1613            vec![Some("dc1:unused-file:9fd2d414a2a9e611".to_owned())]
1614        );
1615    }
1616
1617    #[test]
1618    fn canonical_keys_are_readable_and_escape_the_separator() {
1619        assert_eq!(
1620            dead_code_canonical_key("unused-export", &["src/utils.ts", "helper"]),
1621            "unused-export:src/utils.ts:helper"
1622        );
1623        assert_eq!(
1624            dead_code_canonical_key("unused-file", &["C:/repo/a%b.ts"]),
1625            "unused-file:C%3A/repo/a%25b.ts"
1626        );
1627        assert_ne!(
1628            dead_code_canonical_key("unused-export", &["a:b", "c"]),
1629            dead_code_canonical_key("unused-export", &["a", "b:c"])
1630        );
1631    }
1632
1633    #[test]
1634    fn the_canonical_key_and_the_id_use_the_same_parts() {
1635        let root = PathBuf::from("/repo");
1636        let paths = IdentityPaths::new(&root);
1637        let finding = member(&root, 10);
1638
1639        assert_eq!(
1640            finding.canonical_key(&paths),
1641            "unused-class-member:src/service.ts:Service:run"
1642        );
1643        assert_eq!(
1644            base_id(&finding, &paths),
1645            dead_code_finding_id("unused-class-member", &["src/service.ts", "Service", "run"])
1646        );
1647        assert_eq!(
1648            member(&root, 99).canonical_key(&paths),
1649            finding.canonical_key(&paths)
1650        );
1651    }
1652
1653    #[test]
1654    fn occurrence_keys_number_repeated_keys_in_input_order() {
1655        let root = PathBuf::from("/repo");
1656        let paths = IdentityPaths::new(&root);
1657        let findings = vec![member(&root, 10), member(&root, 20), member(&root, 30)];
1658
1659        assert_eq!(
1660            dead_code_occurrence_keys(&findings, &paths),
1661            vec![
1662                "unused-class-member:src/service.ts:Service:run".to_owned(),
1663                "unused-class-member:src/service.ts:Service:run:~1".to_owned(),
1664                "unused-class-member:src/service.ts:Service:run:~2".to_owned(),
1665            ]
1666        );
1667    }
1668
1669    #[test]
1670    fn the_suppression_reason_is_not_part_of_the_id() {
1671        let suppression = |reason: Option<&str>| StaleSuppression {
1672            path: PathBuf::from("src/a.ts"),
1673            line: 3,
1674            col: 0,
1675            origin: SuppressionOrigin::Comment {
1676                issue_kind: Some("unused-export".to_owned()),
1677                reason: reason.map(str::to_owned),
1678                is_file_level: false,
1679                is_range: false,
1680                kind_known: true,
1681            },
1682            missing_reason: false,
1683            next_line_kinds: Vec::new(),
1684            next_line_blank: false,
1685            finding_id: None,
1686            actions: Vec::new(),
1687            effective_severity: None,
1688        };
1689        let mut results = AnalysisResults {
1690            stale_suppressions: vec![suppression(None)],
1691            ..AnalysisResults::default()
1692        };
1693        let mut with_reason = AnalysisResults {
1694            stale_suppressions: vec![suppression(Some("kept for the plugin API"))],
1695            ..AnalysisResults::default()
1696        };
1697
1698        stamp_dead_code_finding_ids(&mut results, Path::new(""));
1699        stamp_dead_code_finding_ids(&mut with_reason, Path::new(""));
1700
1701        assert_eq!(
1702            ids(&results.stale_suppressions),
1703            ids(&with_reason.stale_suppressions)
1704        );
1705        assert!(
1706            ids(&results.stale_suppressions)[0]
1707                .as_deref()
1708                .is_some_and(|id| id.starts_with("dc1:stale-suppression:"))
1709        );
1710    }
1711}