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