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