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