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, 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        unused_store_members,
461        unresolved_imports,
462        unlisted_dependencies,
463        unlisted_binaries,
464        duplicate_exports,
465        duplicate_export_aliases,
466        type_only_dependencies,
467        test_only_dependencies,
468        dev_dependencies_in_production,
469        circular_dependencies,
470        package_cycles,
471        re_export_cycles,
472        boundary_violations,
473        boundary_coverage_violations,
474        boundary_call_violations,
475        policy_violations,
476        stale_suppressions,
477        unused_catalog_entries,
478        empty_catalog_groups,
479        unresolved_catalog_references,
480        unused_dependency_overrides,
481        misconfigured_dependency_overrides,
482        invalid_client_exports,
483        mixed_client_server_barrels,
484        misplaced_directives,
485        unprovided_injects,
486        unrendered_components,
487        route_collisions,
488        dynamic_segment_name_conflicts,
489        unused_component_props,
490        absent_component_props,
491        constant_parameters,
492        unused_component_emits,
493        unused_component_inputs,
494        unused_component_outputs,
495        unused_svelte_events,
496        unused_effect_layers,
497        unused_tagged_errors,
498        unproduced_catch_tags,
499        unused_server_actions,
500        unused_load_data_keys,
501        prop_drilling_chains,
502        thin_wrappers,
503        duplicate_prop_shapes,
504        // Security findings carry their own `finding_id` from
505        // `fallow_security::identity`. The other fields are not findings.
506        security_findings: _,
507        suppressed_security_findings: _,
508        security_unresolved_edge_files: _,
509        security_unresolved_callee_sites: _,
510        security_unresolved_callee_diagnostics: _,
511        unused_load_data_keys_global_abstain: _,
512        // The cascade filter runs after the ids are stamped, so a hidden
513        // finding keeps the id it had in the report.
514        cascade_hidden: _,
515        cascade: _,
516        suppression_count: _,
517        unused_component_props_exempted: _,
518        active_suppressions: _,
519        feature_flags: _,
520        export_usages: _,
521        entry_point_summary: _,
522        render_fan_in: _,
523        react_component_intel: _,
524        semantic_reachable_files: _,
525        semantic_framework_contracts: _,
526        constant_parameter_candidates: _,
527    } = results;
528
529    visitor.visit(unused_files);
530    visitor.visit(unused_exports);
531    visitor.visit(unused_types);
532    visitor.visit(private_type_leaks);
533    visitor.visit(deprecated_exports_in_use);
534    visitor.visit(unused_dependencies);
535    visitor.visit(unused_dev_dependencies);
536    visitor.visit(unused_optional_dependencies);
537    visitor.visit(unused_enum_members);
538    visitor.visit(unused_class_members);
539    visitor.visit(unused_namespace_members);
540    visitor.visit(unused_protected_class_members);
541    visitor.visit(namespace_escapes);
542    visitor.visit(unused_store_members);
543    visitor.visit(unresolved_imports);
544    visitor.visit(unlisted_dependencies);
545    visitor.visit(unlisted_binaries);
546    visitor.visit(duplicate_exports);
547    visitor.visit(duplicate_export_aliases);
548    visitor.visit(type_only_dependencies);
549    visitor.visit(test_only_dependencies);
550    visitor.visit(dev_dependencies_in_production);
551    visitor.visit(circular_dependencies);
552    visitor.visit(package_cycles);
553    visitor.visit(re_export_cycles);
554    visitor.visit(boundary_violations);
555    visitor.visit(boundary_coverage_violations);
556    visitor.visit(boundary_call_violations);
557    visitor.visit(policy_violations);
558    visitor.visit(stale_suppressions);
559    visitor.visit(unused_catalog_entries);
560    visitor.visit(empty_catalog_groups);
561    visitor.visit(unresolved_catalog_references);
562    visitor.visit(unused_dependency_overrides);
563    visitor.visit(misconfigured_dependency_overrides);
564    visitor.visit(invalid_client_exports);
565    visitor.visit(mixed_client_server_barrels);
566    visitor.visit(misplaced_directives);
567    visitor.visit(unprovided_injects);
568    visitor.visit(unrendered_components);
569    visitor.visit(route_collisions);
570    visitor.visit(dynamic_segment_name_conflicts);
571    visitor.visit(unused_component_props);
572    visitor.visit(absent_component_props);
573    visitor.visit(constant_parameters);
574    visitor.visit(unused_component_emits);
575    visitor.visit(unused_component_inputs);
576    visitor.visit(unused_component_outputs);
577    visitor.visit(unused_svelte_events);
578    visitor.visit(unused_effect_layers);
579    visitor.visit(unused_tagged_errors);
580    visitor.visit(unproduced_catch_tags);
581    visitor.visit(unused_server_actions);
582    visitor.visit(unused_load_data_keys);
583    visitor.visit(prop_drilling_chains);
584    visitor.visit(thin_wrappers);
585    visitor.visit(duplicate_prop_shapes);
586}
587
588fn apply<T: IdentifiedFinding>(findings: &mut [T], paths: &IdentityPaths<'_>, mode: StampMode) {
589    match mode {
590        StampMode::All => stamp(findings, paths),
591        StampMode::Missing => stamp_missing(findings, paths),
592    }
593}
594
595fn base_id<T: IdentifiedFinding>(finding: &T, paths: &IdentityPaths<'_>) -> String {
596    let parts = finding.identity_parts(paths);
597    let parts: Vec<&str> = parts.iter().map(String::as_str).collect();
598    dead_code_finding_id(finding.rule_token(), &parts)
599}
600
601/// The order of findings that share a base id: position first, then the
602/// serialized finding, so the order does not depend on the input order.
603fn tiebreak_key<T: IdentifiedFinding>(finding: &T) -> ((u32, u32, u32), String) {
604    (
605        finding.tiebreak_position(),
606        serde_json::to_string(finding).unwrap_or_default(),
607    )
608}
609
610/// Stamp one finding family. The result does not depend on the input order.
611fn stamp<T: IdentifiedFinding>(findings: &mut [T], paths: &IdentityPaths<'_>) {
612    let mut groups: FxHashMap<String, Vec<usize>> = FxHashMap::default();
613    for (index, finding) in findings.iter_mut().enumerate() {
614        finding.set_finding_id(None);
615        groups
616            .entry(base_id(finding, paths))
617            .or_default()
618            .push(index);
619    }
620    for (base, mut members) in groups {
621        if members.len() > 1 {
622            members.sort_by_cached_key(|&index| tiebreak_key(&findings[index]));
623        }
624        for (position, index) in members.into_iter().enumerate() {
625            let id = if position == 0 {
626                base.clone()
627            } else {
628                format!("{base}~{position}")
629            };
630            findings[index].set_finding_id(Some(id));
631        }
632    }
633}
634
635/// Give an id to each finding of one family that has none.
636fn stamp_missing<T: IdentifiedFinding>(findings: &mut [T], paths: &IdentityPaths<'_>) {
637    let mut missing: Vec<usize> = (0..findings.len())
638        .filter(|&index| findings[index].finding_id().is_none())
639        .collect();
640    if missing.is_empty() {
641        return;
642    }
643    let mut taken: FxHashSet<String> = findings
644        .iter()
645        .filter_map(|finding| finding.finding_id().map(str::to_owned))
646        .collect();
647    missing.sort_by_cached_key(|&index| tiebreak_key(&findings[index]));
648    for index in missing {
649        let base = base_id(&findings[index], paths);
650        let mut id = base.clone();
651        let mut suffix = 0_usize;
652        while taken.contains(&id) {
653            suffix += 1;
654            id = format!("{base}~{suffix}");
655        }
656        taken.insert(id.clone());
657        findings[index].set_finding_id(Some(id));
658    }
659}
660
661/// Implement [`IdentifiedFinding`] for a type with a `finding_id` field.
662macro_rules! identified {
663    (
664        $ty:ty,
665        token: |$t:ident| $token:expr,
666        parts: |$f:ident, $p:ident| $parts:expr,
667        position: |$g:ident| $position:expr $(,)?
668    ) => {
669        impl IdentifiedFinding for $ty {
670            fn rule_token(&self) -> &'static str {
671                let $t = self;
672                $token
673            }
674
675            fn identity_parts(&self, $p: &IdentityPaths<'_>) -> Vec<String> {
676                let $f = self;
677                $parts
678            }
679
680            fn tiebreak_position(&self) -> (u32, u32, u32) {
681                let $g = self;
682                $position
683            }
684
685            fn finding_id(&self) -> Option<&str> {
686                self.finding_id.as_deref()
687            }
688
689            fn set_finding_id(&mut self, id: Option<String>) {
690                self.finding_id = id;
691            }
692        }
693    };
694}
695
696identified!(
697    UnusedFileFinding,
698    token: |_t| "unused-file",
699    parts: |f, p| vec![p.key(&f.file.path)],
700    position: |_g| (0, 0, 0),
701);
702
703identified!(
704    UnusedExportFinding,
705    token: |_t| "unused-export",
706    parts: |f, p| vec![p.key(&f.export.path), f.export.export_name.clone()],
707    position: |g| (g.export.line, g.export.col, g.export.span_start),
708);
709
710identified!(
711    UnusedTypeFinding,
712    token: |_t| "unused-type",
713    parts: |f, p| vec![p.key(&f.export.path), f.export.export_name.clone()],
714    position: |g| (g.export.line, g.export.col, g.export.span_start),
715);
716
717identified!(
718    PrivateTypeLeakFinding,
719    token: |_t| "private-type-leak",
720    parts: |f, p| vec![
721        p.key(&f.leak.path),
722        f.leak.export_name.clone(),
723        f.leak.type_name.clone(),
724    ],
725    position: |g| (g.leak.line, g.leak.col, g.leak.span_start),
726);
727
728identified!(
729    DeprecatedExportInUseFinding,
730    token: |_t| "deprecated-export-in-use",
731    parts: |f, p| vec![p.key(&f.export.path), f.export.export_name.clone()],
732    position: |g| (g.export.line, g.export.col, g.export.span_start),
733);
734
735identified!(
736    UnusedDependencyFinding,
737    token: |_t| "unused-dependency",
738    parts: |f, p| vec![p.key(&f.dep.path), f.dep.package_name.clone()],
739    position: |g| (g.dep.line, 0, 0),
740);
741
742identified!(
743    UnusedDevDependencyFinding,
744    token: |_t| "unused-dev-dependency",
745    parts: |f, p| vec![p.key(&f.dep.path), f.dep.package_name.clone()],
746    position: |g| (g.dep.line, 0, 0),
747);
748
749identified!(
750    UnusedOptionalDependencyFinding,
751    token: |_t| "unused-optional-dependency",
752    parts: |f, p| vec![p.key(&f.dep.path), f.dep.package_name.clone()],
753    position: |g| (g.dep.line, 0, 0),
754);
755
756identified!(
757    TypeOnlyDependencyFinding,
758    token: |_t| "type-only-dependency",
759    parts: |f, p| vec![p.key(&f.dep.path), f.dep.package_name.clone()],
760    position: |g| (g.dep.line, 0, 0),
761);
762
763identified!(
764    TestOnlyDependencyFinding,
765    token: |_t| "test-only-dependency",
766    parts: |f, p| vec![p.key(&f.dep.path), f.dep.package_name.clone()],
767    position: |g| (g.dep.line, 0, 0),
768);
769
770identified!(
771    DevDependencyInProductionFinding,
772    token: |_t| "dev-dependency-in-production",
773    parts: |f, p| vec![p.key(&f.dep.path), f.dep.package_name.clone()],
774    position: |g| (g.dep.line, 0, 0),
775);
776
777identified!(
778    UnlistedDependencyFinding,
779    token: |_t| "unlisted-dependency",
780    parts: |f, _p| vec![f.dep.package_name.clone()],
781    position: |_g| (0, 0, 0),
782);
783
784identified!(
785    UnlistedBinaryFinding,
786    token: |_t| "unlisted-binary",
787    parts: |f, _p| vec![f.binary.binary_name.clone()],
788    position: |_g| (0, 0, 0),
789);
790
791identified!(
792    UnusedEnumMemberFinding,
793    token: |_t| "unused-enum-member",
794    parts: |f, p| member_parts(&f.member, p),
795    position: |g| (g.member.line, g.member.col, 0),
796);
797
798identified!(
799    UnusedClassMemberFinding,
800    token: |_t| "unused-class-member",
801    parts: |f, p| member_parts(&f.member, p),
802    position: |g| (g.member.line, g.member.col, 0),
803);
804
805identified!(
806    UnusedProtectedClassMemberFinding,
807    token: |_t| "unused-protected-class-member",
808    parts: |f, p| member_parts(&f.member, p),
809    position: |g| (g.member.line, g.member.col, 0),
810);
811
812identified!(
813    NamespaceEscapeFinding,
814    token: |_t| "namespace-escape",
815    parts: |f, p| vec![
816        p.key(&f.escape.path),
817        f.escape.local_name.clone(),
818        p.key(&f.escape.module),
819    ],
820    position: |g| (g.escape.line, g.escape.col, 0),
821);
822
823identified!(
824    UnusedNamespaceMemberFinding,
825    token: |_t| "unused-namespace-member",
826    parts: |f, p| member_parts(&f.member, p),
827    position: |g| (g.member.line, g.member.col, 0),
828);
829
830identified!(
831    UnusedStoreMemberFinding,
832    token: |_t| "unused-store-member",
833    parts: |f, p| member_parts(&f.member, p),
834    position: |g| (g.member.line, g.member.col, 0),
835);
836
837fn member_parts(member: &crate::results::UnusedMember, paths: &IdentityPaths<'_>) -> Vec<String> {
838    vec![
839        paths.key(&member.path),
840        member.parent_name.clone(),
841        member.member_name.clone(),
842    ]
843}
844
845identified!(
846    UnresolvedImportFinding,
847    token: |_t| "unresolved-import",
848    parts: |f, p| vec![p.key(&f.import.path), f.import.specifier.clone()],
849    position: |g| (g.import.line, g.import.col, 0),
850);
851
852identified!(
853    DuplicateExportFinding,
854    token: |_t| "duplicate-export",
855    parts: |f, p| vec![
856        f.export.export_name.clone(),
857        p.set(f.export.locations.iter().map(|location| location.path.as_path())),
858    ],
859    position: |g| g
860        .export
861        .locations
862        .first()
863        .map_or((0, 0, 0), |location| (location.line, location.col, 0)),
864);
865
866identified!(
867    CircularDependencyFinding,
868    token: |_t| "circular-dependency",
869    parts: |f, p| vec![p.set(f.cycle.files.iter().map(std::path::PathBuf::as_path))],
870    position: |g| (g.cycle.line, g.cycle.col, 0),
871);
872
873identified!(
874    PackageCycleFinding,
875    token: |_t| "package-cycle",
876    parts: |f, p| vec![p.set(f.cycle.package_roots.iter().map(std::path::PathBuf::as_path))],
877    position: |_g| (0, 0, 0),
878);
879
880identified!(
881    ReExportCycleFinding,
882    token: |_t| "re-export-cycle",
883    parts: |f, p| vec![
884        re_export_cycle_kind(f.cycle.kind).to_owned(),
885        p.set(f.cycle.files.iter().map(std::path::PathBuf::as_path)),
886    ],
887    position: |_g| (0, 0, 0),
888);
889
890/// The wire spelling of the cycle kind, so the part matches the JSON value.
891const fn re_export_cycle_kind(kind: ReExportCycleKind) -> &'static str {
892    match kind {
893        ReExportCycleKind::MultiNode => "multi-node",
894        ReExportCycleKind::SelfLoop => "self-loop",
895    }
896}
897
898identified!(
899    BoundaryViolationFinding,
900    token: |_t| "boundary-violation",
901    parts: |f, p| vec![p.key(&f.violation.from_path), p.key(&f.violation.to_path)],
902    position: |g| (g.violation.line, g.violation.col, 0),
903);
904
905identified!(
906    BoundaryCoverageViolationFinding,
907    token: |_t| "boundary-coverage",
908    parts: |f, p| vec![p.key(&f.violation.path)],
909    position: |g| (g.violation.line, g.violation.col, 0),
910);
911
912identified!(
913    BoundaryCallViolationFinding,
914    token: |_t| "boundary-call-violation",
915    parts: |f, p| vec![p.key(&f.violation.path), f.violation.callee.clone()],
916    position: |g| (g.violation.line, g.violation.col, 0),
917);
918
919identified!(
920    PolicyViolationFinding,
921    token: |_t| "policy-violation",
922    parts: |f, p| vec![
923        p.key(&f.violation.path),
924        f.violation.pack.clone(),
925        f.violation.rule_id.clone(),
926        f.violation.matched.clone(),
927    ],
928    position: |g| (g.violation.line, g.violation.col, 0),
929);
930
931identified!(
932    StaleSuppression,
933    token: |t| if t.missing_reason {
934        "missing-suppression-reason"
935    } else {
936        "stale-suppression"
937    },
938    parts: |f, p| suppression_parts(f, p),
939    position: |g| (g.line, g.col, 0),
940);
941
942/// Path, origin kind, issue kind (or `*`), and scope or export name. The
943/// reason text is not a part: adding a reason must not change the id.
944fn suppression_parts(suppression: &StaleSuppression, paths: &IdentityPaths<'_>) -> Vec<String> {
945    let path = paths.key(&suppression.path);
946    match &suppression.origin {
947        SuppressionOrigin::Comment {
948            issue_kind,
949            is_file_level,
950            ..
951        } => vec![
952            path,
953            "comment".to_owned(),
954            issue_kind.clone().unwrap_or_else(|| ANY_KIND.to_owned()),
955            if *is_file_level { "file" } else { "line" }.to_owned(),
956        ],
957        SuppressionOrigin::JsdocTag { export_name, .. } => vec![
958            path,
959            "jsdoc_tag".to_owned(),
960            ANY_KIND.to_owned(),
961            export_name.clone(),
962        ],
963    }
964}
965
966identified!(
967    UnusedCatalogEntryFinding,
968    token: |_t| "unused-catalog-entry",
969    parts: |f, p| vec![
970        p.key(&f.entry.path),
971        f.entry.catalog_name.clone(),
972        f.entry.entry_name.clone(),
973    ],
974    position: |g| (g.entry.line, 0, 0),
975);
976
977identified!(
978    EmptyCatalogGroupFinding,
979    token: |_t| "empty-catalog-group",
980    parts: |f, p| vec![p.key(&f.group.path), f.group.catalog_name.clone()],
981    position: |g| (g.group.line, 0, 0),
982);
983
984identified!(
985    UnresolvedCatalogReferenceFinding,
986    token: |_t| "unresolved-catalog-reference",
987    parts: |f, p| vec![
988        p.key(&f.reference.path),
989        f.reference.catalog_name.clone(),
990        f.reference.entry_name.clone(),
991    ],
992    position: |g| (g.reference.line, 0, 0),
993);
994
995identified!(
996    UnusedDependencyOverrideFinding,
997    token: |_t| "unused-dependency-override",
998    parts: |f, _p| vec![override_source(f.entry.source).to_owned(), f.entry.raw_key.clone()],
999    position: |g| (g.entry.line, 0, 0),
1000);
1001
1002identified!(
1003    MisconfiguredDependencyOverrideFinding,
1004    token: |_t| "misconfigured-dependency-override",
1005    parts: |f, _p| vec![override_source(f.entry.source).to_owned(), f.entry.raw_key.clone()],
1006    position: |g| (g.entry.line, 0, 0),
1007);
1008
1009/// The wire spelling of the override source, so the part matches the JSON
1010/// value.
1011const fn override_source(source: DependencyOverrideSource) -> &'static str {
1012    match source {
1013        DependencyOverrideSource::PnpmWorkspaceYaml => "pnpm-workspace.yaml",
1014        DependencyOverrideSource::PnpmPackageJson => "package.json",
1015    }
1016}
1017
1018identified!(
1019    InvalidClientExportFinding,
1020    token: |_t| "invalid-client-export",
1021    parts: |f, p| vec![p.key(&f.export.path), f.export.export_name.clone()],
1022    position: |g| (g.export.line, g.export.col, 0),
1023);
1024
1025identified!(
1026    MixedClientServerBarrelFinding,
1027    token: |_t| "mixed-client-server-barrel",
1028    parts: |f, p| vec![p.key(&f.barrel.path)],
1029    position: |g| (g.barrel.line, g.barrel.col, 0),
1030);
1031
1032identified!(
1033    MisplacedDirectiveFinding,
1034    token: |_t| "misplaced-directive",
1035    parts: |f, p| vec![
1036        p.key(&f.directive_site.path),
1037        f.directive_site.directive.clone(),
1038    ],
1039    position: |g| (g.directive_site.line, g.directive_site.col, 0),
1040);
1041
1042identified!(
1043    UnprovidedInjectFinding,
1044    token: |_t| "unprovided-inject",
1045    parts: |f, p| vec![p.key(&f.inject.path), f.inject.key_name.clone()],
1046    position: |g| (g.inject.line, g.inject.col, 0),
1047);
1048
1049identified!(
1050    UnrenderedComponentFinding,
1051    token: |_t| "unrendered-component",
1052    parts: |f, p| vec![p.key(&f.component.path), f.component.component_name.clone()],
1053    position: |g| (g.component.line, g.component.col, 0),
1054);
1055
1056identified!(
1057    RouteCollisionFinding,
1058    token: |_t| "route-collision",
1059    parts: |f, p| vec![p.key(&f.collision.path), f.collision.url.clone()],
1060    position: |g| (g.collision.line, g.collision.col, 0),
1061);
1062
1063identified!(
1064    DynamicSegmentNameConflictFinding,
1065    token: |_t| "dynamic-segment-name-conflict",
1066    parts: |f, p| vec![p.key(&f.conflict.path), f.conflict.position.clone()],
1067    position: |g| (g.conflict.line, g.conflict.col, 0),
1068);
1069
1070identified!(
1071    UnusedComponentPropFinding,
1072    token: |_t| "unused-component-prop",
1073    parts: |f, p| vec![
1074        p.key(&f.prop.path),
1075        f.prop.component_name.clone(),
1076        f.prop.prop_name.clone(),
1077    ],
1078    position: |g| (g.prop.line, g.prop.col, 0),
1079);
1080identified!(
1081    ConstantParameterFinding,
1082    token: |_t| "constant-parameter",
1083    parts: |f, p| vec![
1084        p.key(&f.parameter.path),
1085        f.parameter.function_name.clone(),
1086        f.parameter.parameter_name.clone(),
1087    ],
1088    position: |g| (g.parameter.line, g.parameter.col, 0),
1089);
1090identified!(
1091    AbsentComponentPropFinding,
1092    token: |_t| "absent-component-prop",
1093    parts: |f, p| vec![
1094        p.key(&f.prop.path),
1095        f.prop.component_name.clone(),
1096        f.prop.prop_name.clone(),
1097    ],
1098    position: |g| (g.prop.line, g.prop.col, 0),
1099);
1100
1101identified!(
1102    UnusedComponentEmitFinding,
1103    token: |_t| "unused-component-emit",
1104    parts: |f, p| vec![
1105        p.key(&f.emit.path),
1106        f.emit.component_name.clone(),
1107        f.emit.emit_name.clone(),
1108    ],
1109    position: |g| (g.emit.line, g.emit.col, 0),
1110);
1111
1112identified!(
1113    UnusedComponentInputFinding,
1114    token: |_t| "unused-component-input",
1115    parts: |f, p| vec![
1116        p.key(&f.input.path),
1117        f.input.component_name.clone(),
1118        f.input.input_name.clone(),
1119    ],
1120    position: |g| (g.input.line, g.input.col, 0),
1121);
1122
1123identified!(
1124    UnusedComponentOutputFinding,
1125    token: |_t| "unused-component-output",
1126    parts: |f, p| vec![
1127        p.key(&f.output.path),
1128        f.output.component_name.clone(),
1129        f.output.output_name.clone(),
1130    ],
1131    position: |g| (g.output.line, g.output.col, 0),
1132);
1133
1134identified!(
1135    DuplicateExportAliasFinding,
1136    token: |_t| "duplicate-export-alias",
1137    parts: |f, p| {
1138        let mut names = f.alias.export_names.clone();
1139        names.sort_unstable();
1140        vec![p.key(&f.alias.path), f.alias.local_name.clone(), names.join(",")]
1141    },
1142    position: |g| (g.alias.line, g.alias.col, 0),
1143);
1144
1145identified!(
1146    UnusedSvelteEventFinding,
1147    token: |_t| "unused-svelte-event",
1148    parts: |f, p| vec![
1149        p.key(&f.event.path),
1150        f.event.component_name.clone(),
1151        f.event.event_name.clone(),
1152    ],
1153    position: |g| (g.event.line, g.event.col, 0),
1154);
1155
1156identified!(
1157    UnusedEffectLayerFinding,
1158    token: |_t| "unused-effect-layer",
1159    parts: |f, p| vec![p.key(&f.layer.path), f.layer.name.clone()],
1160    position: |g| (g.layer.line, g.layer.col, 0),
1161);
1162
1163identified!(
1164    UnusedTaggedErrorFinding,
1165    token: |_t| "unused-tagged-error",
1166    parts: |f, p| vec![
1167        p.key(&f.error.path),
1168        f.error.name.clone(),
1169        f.error.tag.clone(),
1170    ],
1171    position: |g| (g.error.line, g.error.col, 0),
1172);
1173
1174identified!(
1175    UnproducedCatchTagFinding,
1176    token: |_t| "unproduced-catch-tag",
1177    parts: |f, p| vec![p.key(&f.catch_tag.path), f.catch_tag.tag.clone()],
1178    position: |g| (g.catch_tag.line, g.catch_tag.col, 0),
1179);
1180
1181identified!(
1182    UnusedServerActionFinding,
1183    token: |_t| "unused-server-action",
1184    parts: |f, p| vec![p.key(&f.action.path), f.action.action_name.clone()],
1185    position: |g| (g.action.line, g.action.col, 0),
1186);
1187
1188identified!(
1189    UnusedLoadDataKeyFinding,
1190    token: |_t| "unused-load-data-key",
1191    parts: |f, p| vec![p.key(&f.key.path), f.key.key_name.clone()],
1192    position: |g| (g.key.line, g.key.col, 0),
1193);
1194
1195identified!(
1196    PropDrillingChainFinding,
1197    token: |_t| "prop-drilling",
1198    parts: |f, p| {
1199        let origin = f.chain.hops.first();
1200        vec![
1201            origin.map(|hop| p.key(&hop.file)).unwrap_or_default(),
1202            origin.map(|hop| hop.component.clone()).unwrap_or_default(),
1203            f.chain.prop.clone(),
1204        ]
1205    },
1206    position: |g| (g.chain.hops.first().map_or(0, |hop| hop.line), 0, 0),
1207);
1208
1209identified!(
1210    ThinWrapperFinding,
1211    token: |_t| "thin-wrapper",
1212    parts: |f, p| vec![p.key(&f.wrapper.file), f.wrapper.component.clone()],
1213    position: |g| (g.wrapper.line, 0, 0),
1214);
1215
1216identified!(
1217    DuplicatePropShapeFinding,
1218    token: |_t| "duplicate-prop-shape",
1219    parts: |f, p| vec![p.key(&f.shape.file), f.shape.component.clone()],
1220    position: |g| (g.shape.line, 0, 0),
1221);
1222
1223#[cfg(test)]
1224mod tests {
1225    use std::path::PathBuf;
1226
1227    use super::*;
1228    use crate::results::{UnusedExport, UnusedFile, UnusedMember};
1229
1230    // Every expected value below comes from an independent FNV-1a 64 script,
1231    // not from this module.
1232
1233    #[test]
1234    fn fnv1a64_parts_golden_values() {
1235        assert_eq!(
1236            fnv1a64_parts(&["src/index.ts", "FEATURE_X", "3"]),
1237            "2278c9d9bd9d2dd2"
1238        );
1239        assert_eq!(
1240            fnv1a64_parts(&["fallow/unused-file", "src/orphan.ts"]),
1241            "c03b925ddb7d871a"
1242        );
1243        assert_eq!(fnv1a64_parts(&[]), "cbf29ce484222325");
1244    }
1245
1246    #[test]
1247    fn fnv1a64_hex_golden_value() {
1248        assert_eq!(
1249            fnv1a64_hex(b"security/client-server-leak:src/a.ts:3:7"),
1250            "89b6dece9d8b96d2"
1251        );
1252    }
1253
1254    #[test]
1255    fn finding_id_syntax_accepts_base_and_tiebreak_ids() {
1256        assert!(is_dead_code_finding_id(
1257            "dc1:unused-export:81a349a3b9ea3b15"
1258        ));
1259        assert!(is_dead_code_finding_id(
1260            "dc1:unused-class-member:0123456789abcdef~1"
1261        ));
1262        assert!(is_dead_code_finding_id(
1263            "dc1:unused-file:0123456789abcdef~12"
1264        ));
1265    }
1266
1267    #[test]
1268    fn finding_id_syntax_refuses_other_shapes() {
1269        for bad in [
1270            "",
1271            "dc1",
1272            "dc1:unused-export",
1273            "dc1::0123456789abcdef",
1274            "dc2:unused-export:0123456789abcdef",
1275            "dc1:unused-export:0123456789ABCDEF",
1276            "dc1:unused-export:0123456789abcde",
1277            "dc1:unused-export:0123456789abcdef0",
1278            "dc1:unused-export:0123456789abcdef~",
1279            "dc1:unused-export:0123456789abcdef~0",
1280            "dc1:unused-export:0123456789abcdef~01",
1281            "dc1:unused-export:0123456789abcdef~x",
1282            "dc1:Unused-Export:0123456789abcdef",
1283            "dc1:unused-export:0123456789abcdef:extra",
1284        ] {
1285            assert!(!is_dead_code_finding_id(bad), "{bad:?} was accepted");
1286        }
1287    }
1288
1289    #[test]
1290    fn retain_by_id_keeps_only_the_requested_findings() {
1291        let root = PathBuf::from("/repo");
1292        let mut results = AnalysisResults {
1293            unused_files: vec![
1294                UnusedFileFinding::with_actions(UnusedFile {
1295                    path: root.join("src/a.ts"),
1296                }),
1297                UnusedFileFinding::with_actions(UnusedFile {
1298                    path: root.join("src/b.ts"),
1299                }),
1300            ],
1301            ..AnalysisResults::default()
1302        };
1303        stamp_dead_code_finding_ids(&mut results, &root);
1304        let kept = results.unused_files[1]
1305            .finding_id
1306            .clone()
1307            .expect("stamped id");
1308        let ids: FxHashSet<String> = [kept.clone(), "dc1:unused-file:0000000000000000".to_owned()]
1309            .into_iter()
1310            .collect();
1311
1312        let present = present_dead_code_finding_ids(&mut results, &ids);
1313        assert_eq!(results.unused_files.len(), 2, "present only reads");
1314        let matched = retain_dead_code_findings_by_id(&mut results, &ids);
1315
1316        assert_eq!(present, matched);
1317        assert_eq!(matched, std::iter::once(kept.clone()).collect());
1318        assert_eq!(results.unused_files.len(), 1);
1319        assert_eq!(
1320            results.unused_files[0].finding_id.as_deref(),
1321            Some(kept.as_str())
1322        );
1323    }
1324
1325    #[test]
1326    fn dead_code_finding_id_golden_values() {
1327        assert_eq!(
1328            dead_code_finding_id("unused-export", &["src/utils.ts", "helper"]),
1329            "dc1:unused-export:81a349a3b9ea3b15"
1330        );
1331        assert_eq!(
1332            dead_code_finding_id("unused-file", &["src/orphan.ts"]),
1333            "dc1:unused-file:9fd2d414a2a9e611"
1334        );
1335        assert_eq!(
1336            dead_code_finding_id("unused-class-member", &["src/service.ts", "Service", "run"]),
1337            "dc1:unused-class-member:675fa79a4c2f244f"
1338        );
1339        assert_eq!(
1340            dead_code_finding_id("unused-dependency", &["package.json", "lodash"]),
1341            "dc1:unused-dependency:e2f217ff5a209568"
1342        );
1343        assert_eq!(
1344            dead_code_finding_id("duplicate-export", &["Button", "src/a.ts|src/b.ts"]),
1345            "dc1:duplicate-export:17c140e16d40660a"
1346        );
1347    }
1348
1349    fn export(root: &Path, name: &str, line: u32) -> UnusedExportFinding {
1350        UnusedExportFinding::with_actions(UnusedExport {
1351            path: root.join("src/utils.ts"),
1352            export_name: name.to_owned(),
1353            is_type_only: false,
1354            line,
1355            col: 7,
1356            span_start: line * 10,
1357            is_re_export: false,
1358            deprecated: false,
1359            deprecated_reason: None,
1360        })
1361    }
1362
1363    fn member(root: &Path, line: u32) -> UnusedClassMemberFinding {
1364        UnusedClassMemberFinding::with_actions(UnusedMember {
1365            path: root.join("src/service.ts"),
1366            parent_name: "Service".to_owned(),
1367            member_name: "run".to_owned(),
1368            kind: crate::extract::MemberKind::ClassMethod,
1369            line,
1370            col: 2,
1371        })
1372    }
1373
1374    fn ids<T: IdentifiedFinding>(findings: &[T]) -> Vec<Option<String>> {
1375        findings
1376            .iter()
1377            .map(|finding| finding.finding_id().map(str::to_owned))
1378            .collect()
1379    }
1380
1381    #[test]
1382    fn stamping_uses_root_relative_paths_and_ignores_lines() {
1383        let root = PathBuf::from("/repo");
1384        let mut results = AnalysisResults {
1385            unused_files: vec![UnusedFileFinding::with_actions(UnusedFile {
1386                path: root.join("src/orphan.ts"),
1387            })],
1388            unused_exports: vec![export(&root, "helper", 40)],
1389            ..AnalysisResults::default()
1390        };
1391
1392        stamp_dead_code_finding_ids(&mut results, &root);
1393
1394        assert_eq!(
1395            ids(&results.unused_files),
1396            vec![Some("dc1:unused-file:9fd2d414a2a9e611".to_owned())]
1397        );
1398        assert_eq!(
1399            ids(&results.unused_exports),
1400            vec![Some("dc1:unused-export:81a349a3b9ea3b15".to_owned())]
1401        );
1402    }
1403
1404    #[test]
1405    fn duplicate_subjects_get_a_tiebreak_suffix_in_line_order() {
1406        let root = PathBuf::from("/repo");
1407        let mut results = AnalysisResults {
1408            unused_class_members: vec![member(&root, 30), member(&root, 10), member(&root, 20)],
1409            ..AnalysisResults::default()
1410        };
1411
1412        stamp_dead_code_finding_ids(&mut results, &root);
1413
1414        let base = "dc1:unused-class-member:675fa79a4c2f244f";
1415        assert_eq!(
1416            ids(&results.unused_class_members),
1417            vec![
1418                Some(format!("{base}~2")),
1419                Some(base.to_owned()),
1420                Some(format!("{base}~1")),
1421            ]
1422        );
1423    }
1424
1425    #[test]
1426    fn stamping_does_not_depend_on_input_order() {
1427        let root = PathBuf::from("/repo");
1428        let forward = vec![member(&root, 10), member(&root, 20), member(&root, 30)];
1429        let mut reversed = forward.clone();
1430        reversed.reverse();
1431        let mut a = AnalysisResults {
1432            unused_class_members: forward,
1433            ..AnalysisResults::default()
1434        };
1435        let mut b = AnalysisResults {
1436            unused_class_members: reversed,
1437            ..AnalysisResults::default()
1438        };
1439
1440        stamp_dead_code_finding_ids(&mut a, &root);
1441        stamp_dead_code_finding_ids(&mut b, &root);
1442
1443        let mut a_pairs: Vec<(u32, Option<String>)> = a
1444            .unused_class_members
1445            .iter()
1446            .map(|finding| (finding.member.line, finding.finding_id.clone()))
1447            .collect();
1448        let mut b_pairs: Vec<(u32, Option<String>)> = b
1449            .unused_class_members
1450            .iter()
1451            .map(|finding| (finding.member.line, finding.finding_id.clone()))
1452            .collect();
1453        a_pairs.sort();
1454        b_pairs.sort();
1455        assert_eq!(a_pairs, b_pairs);
1456    }
1457
1458    #[test]
1459    fn stamping_twice_gives_the_same_ids() {
1460        let root = PathBuf::from("/repo");
1461        let mut results = AnalysisResults {
1462            unused_class_members: vec![member(&root, 10), member(&root, 20)],
1463            unused_exports: vec![export(&root, "helper", 3)],
1464            ..AnalysisResults::default()
1465        };
1466
1467        stamp_dead_code_finding_ids(&mut results, &root);
1468        let first = (
1469            ids(&results.unused_class_members),
1470            ids(&results.unused_exports),
1471        );
1472        stamp_dead_code_finding_ids(&mut results, &root);
1473
1474        assert_eq!(
1475            first,
1476            (
1477                ids(&results.unused_class_members),
1478                ids(&results.unused_exports),
1479            )
1480        );
1481    }
1482
1483    #[test]
1484    fn stamping_missing_ids_keeps_existing_ids_and_takes_a_free_suffix() {
1485        let root = PathBuf::from("/repo");
1486        let mut results = AnalysisResults {
1487            unused_class_members: vec![member(&root, 10), member(&root, 20)],
1488            ..AnalysisResults::default()
1489        };
1490        stamp_dead_code_finding_ids(&mut results, &root);
1491        // A filter removed the base finding; a later stage adds a new one.
1492        results.unused_class_members.remove(0);
1493        results.unused_class_members.push(member(&root, 5));
1494
1495        stamp_missing_dead_code_finding_ids(&mut results, &root);
1496
1497        let base = "dc1:unused-class-member:675fa79a4c2f244f";
1498        assert_eq!(
1499            ids(&results.unused_class_members),
1500            vec![Some(format!("{base}~1")), Some(base.to_owned())]
1501        );
1502    }
1503
1504    fn duplicate_export(root: &Path, files: &[&str]) -> DuplicateExportFinding {
1505        DuplicateExportFinding::with_actions(crate::results::DuplicateExport {
1506            export_name: "Button".to_owned(),
1507            locations: files
1508                .iter()
1509                .map(|file| crate::results::DuplicateLocation {
1510                    path: root.join(file),
1511                    line: 1,
1512                    col: 0,
1513                })
1514                .collect(),
1515        })
1516    }
1517
1518    #[test]
1519    fn a_path_set_without_special_characters_keeps_its_golden_id() {
1520        let root = PathBuf::from("/repo");
1521        let mut results = AnalysisResults {
1522            duplicate_exports: vec![duplicate_export(&root, &["src/b.ts", "src/a.ts"])],
1523            ..AnalysisResults::default()
1524        };
1525
1526        stamp_dead_code_finding_ids(&mut results, &root);
1527
1528        assert_eq!(
1529            ids(&results.duplicate_exports),
1530            vec![Some("dc1:duplicate-export:17c140e16d40660a".to_owned())]
1531        );
1532    }
1533
1534    #[test]
1535    fn a_pipe_in_a_file_name_does_not_collide_with_two_files() {
1536        let root = PathBuf::from("/repo");
1537        let paths = IdentityPaths::new(&root);
1538        let one = root.join("src/a.ts|src/b.ts");
1539        let first = root.join("src/a.ts");
1540        let second = root.join("src/b.ts");
1541
1542        assert_eq!(paths.set([one.as_path()]), "src/a.ts%7Csrc/b.ts");
1543        assert_eq!(
1544            paths.set([first.as_path(), second.as_path()]),
1545            "src/a.ts|src/b.ts"
1546        );
1547        assert_eq!(paths.set([root.join("100%.ts").as_path()]), "100%25.ts");
1548
1549        let mut results = AnalysisResults {
1550            duplicate_exports: vec![
1551                duplicate_export(&root, &["src/a.ts|src/b.ts"]),
1552                duplicate_export(&root, &["src/a.ts", "src/b.ts"]),
1553            ],
1554            ..AnalysisResults::default()
1555        };
1556        stamp_dead_code_finding_ids(&mut results, &root);
1557
1558        let stamped = ids(&results.duplicate_exports);
1559        assert_ne!(stamped[0], stamped[1]);
1560        assert!(
1561            stamped.iter().flatten().all(|id| !id.contains('~')),
1562            "the two findings must not share a base id: {stamped:?}"
1563        );
1564    }
1565
1566    #[test]
1567    fn a_package_cycle_gets_a_golden_id_from_its_sorted_package_roots() {
1568        let root = PathBuf::from("/repo");
1569        let cycle = |roots: &[&str]| {
1570            PackageCycleFinding::with_actions(crate::results::PackageCycle {
1571                packages: vec!["@x/a".to_owned(), "@x/b".to_owned()],
1572                package_roots: roots.iter().map(|dir| root.join(dir)).collect(),
1573                length: 2,
1574                edges: Vec::new(),
1575                group_truncated: false,
1576            })
1577        };
1578        let mut results = AnalysisResults {
1579            package_cycles: vec![cycle(&["packages/b", "packages/a"])],
1580            ..AnalysisResults::default()
1581        };
1582
1583        stamp_dead_code_finding_ids(&mut results, &root);
1584
1585        assert_eq!(
1586            ids(&results.package_cycles),
1587            vec![Some("dc1:package-cycle:fed127e4525389ac".to_owned())]
1588        );
1589    }
1590
1591    #[test]
1592    fn windows_separators_give_the_same_id() {
1593        let mut windows = AnalysisResults {
1594            unused_files: vec![UnusedFileFinding::with_actions(UnusedFile {
1595                path: PathBuf::from("src\\orphan.ts"),
1596            })],
1597            ..AnalysisResults::default()
1598        };
1599
1600        stamp_dead_code_finding_ids(&mut windows, Path::new(""));
1601
1602        assert_eq!(
1603            ids(&windows.unused_files),
1604            vec![Some("dc1:unused-file:9fd2d414a2a9e611".to_owned())]
1605        );
1606    }
1607
1608    #[test]
1609    fn canonical_keys_are_readable_and_escape_the_separator() {
1610        assert_eq!(
1611            dead_code_canonical_key("unused-export", &["src/utils.ts", "helper"]),
1612            "unused-export:src/utils.ts:helper"
1613        );
1614        assert_eq!(
1615            dead_code_canonical_key("unused-file", &["C:/repo/a%b.ts"]),
1616            "unused-file:C%3A/repo/a%25b.ts"
1617        );
1618        assert_ne!(
1619            dead_code_canonical_key("unused-export", &["a:b", "c"]),
1620            dead_code_canonical_key("unused-export", &["a", "b:c"])
1621        );
1622    }
1623
1624    #[test]
1625    fn the_canonical_key_and_the_id_use_the_same_parts() {
1626        let root = PathBuf::from("/repo");
1627        let paths = IdentityPaths::new(&root);
1628        let finding = member(&root, 10);
1629
1630        assert_eq!(
1631            finding.canonical_key(&paths),
1632            "unused-class-member:src/service.ts:Service:run"
1633        );
1634        assert_eq!(
1635            base_id(&finding, &paths),
1636            dead_code_finding_id("unused-class-member", &["src/service.ts", "Service", "run"])
1637        );
1638        assert_eq!(
1639            member(&root, 99).canonical_key(&paths),
1640            finding.canonical_key(&paths)
1641        );
1642    }
1643
1644    #[test]
1645    fn occurrence_keys_number_repeated_keys_in_input_order() {
1646        let root = PathBuf::from("/repo");
1647        let paths = IdentityPaths::new(&root);
1648        let findings = vec![member(&root, 10), member(&root, 20), member(&root, 30)];
1649
1650        assert_eq!(
1651            dead_code_occurrence_keys(&findings, &paths),
1652            vec![
1653                "unused-class-member:src/service.ts:Service:run".to_owned(),
1654                "unused-class-member:src/service.ts:Service:run:~1".to_owned(),
1655                "unused-class-member:src/service.ts:Service:run:~2".to_owned(),
1656            ]
1657        );
1658    }
1659
1660    #[test]
1661    fn the_suppression_reason_is_not_part_of_the_id() {
1662        let suppression = |reason: Option<&str>| StaleSuppression {
1663            path: PathBuf::from("src/a.ts"),
1664            line: 3,
1665            col: 0,
1666            origin: SuppressionOrigin::Comment {
1667                issue_kind: Some("unused-export".to_owned()),
1668                reason: reason.map(str::to_owned),
1669                is_file_level: false,
1670                is_range: false,
1671                kind_known: true,
1672            },
1673            missing_reason: false,
1674            finding_id: None,
1675            actions: Vec::new(),
1676            effective_severity: None,
1677        };
1678        let mut results = AnalysisResults {
1679            stale_suppressions: vec![suppression(None)],
1680            ..AnalysisResults::default()
1681        };
1682        let mut with_reason = AnalysisResults {
1683            stale_suppressions: vec![suppression(Some("kept for the plugin API"))],
1684            ..AnalysisResults::default()
1685        };
1686
1687        stamp_dead_code_finding_ids(&mut results, Path::new(""));
1688        stamp_dead_code_finding_ids(&mut with_reason, Path::new(""));
1689
1690        assert_eq!(
1691            ids(&results.stale_suppressions),
1692            ids(&with_reason.stale_suppressions)
1693        );
1694        assert!(
1695            ids(&results.stale_suppressions)[0]
1696                .as_deref()
1697                .is_some_and(|id| id.starts_with("dc1:stale-suppression:"))
1698        );
1699    }
1700}