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