Skip to main content

fallow_types/
suppress.rs

1//! Inline suppression comment types and issue kind definitions.
2
3pub use crate::issue_meta::{DEAD_CODE_FILTER_FLAGS, KNOWN_ISSUE_KIND_NAMES};
4
5/// Issue kind for suppression matching.
6///
7/// # Examples
8///
9/// ```
10/// use fallow_types::suppress::IssueKind;
11///
12/// let kind = IssueKind::parse("unused-export");
13/// assert_eq!(kind, Some(IssueKind::UnusedExport));
14///
15/// // Round-trip through discriminant
16/// let d = IssueKind::UnusedFile.to_discriminant();
17/// assert_eq!(IssueKind::from_discriminant(d), Some(IssueKind::UnusedFile));
18///
19/// // Unknown strings return None
20/// assert_eq!(IssueKind::parse("not-a-kind"), None);
21/// ```
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum IssueKind {
24    /// An unused file.
25    UnusedFile,
26    /// An unused export.
27    UnusedExport,
28    /// An unused type export.
29    UnusedType,
30    /// An exported signature that references a same-file private type.
31    PrivateTypeLeak,
32    /// An unused dependency.
33    UnusedDependency,
34    /// An unused dev dependency.
35    UnusedDevDependency,
36    /// An unused enum member.
37    UnusedEnumMember,
38    /// An unused class member.
39    UnusedClassMember,
40    /// An unresolved import.
41    UnresolvedImport,
42    /// An unlisted dependency.
43    UnlistedDependency,
44    /// A binary that a script or a process call runs, but that no installed
45    /// or listed package provides.
46    UnlistedBinary,
47    /// A duplicate export name across modules.
48    DuplicateExport,
49    /// Code duplication.
50    CodeDuplication,
51    /// A circular dependency chain.
52    CircularDependency,
53    /// A cycle or self-loop in the re-export edge subgraph (barrel files
54    /// re-exporting from each other in a loop). Structurally always a bug:
55    /// chain propagation through the cycle is a no-op.
56    ReExportCycle,
57    /// A production dependency only imported via type-only imports.
58    TypeOnlyDependency,
59    /// A production dependency only imported by test files.
60    TestOnlyDependency,
61    /// An import that crosses an architecture boundary.
62    BoundaryViolation,
63    /// A runtime file or export with no test dependency path.
64    CoverageGaps,
65    /// A detected feature flag pattern.
66    FeatureFlag,
67    /// A function exceeding complexity thresholds (health command).
68    Complexity,
69    /// A suppression comment or JSDoc tag that no longer matches any issue.
70    StaleSuppression,
71    /// A pnpm catalog entry in pnpm-workspace.yaml not referenced by any workspace package.
72    PnpmCatalogEntry,
73    /// A named pnpm catalog group in pnpm-workspace.yaml with no entries.
74    EmptyCatalogGroup,
75    /// A workspace package.json reference (`catalog:` / `catalog:<name>`) pointing at
76    /// a catalog that does not declare the consumed package.
77    UnresolvedCatalogReference,
78    /// A package-manager override whose target package is not declared in any
79    /// workspace `package.json`.
80    UnusedDependencyOverride,
81    /// A package-manager override whose key or value cannot be parsed in its
82    /// declaration source's grammar.
83    MisconfiguredDependencyOverride,
84    /// A `"use client"` file that transitively imports a module reading a
85    /// non-public `process.env` secret (security candidate).
86    SecurityClientServerLeak,
87    /// A syntactic tainted-sink candidate matched against the data-driven
88    /// security matcher catalogue (`security_matchers.toml`). ONE suppression
89    /// token covers all catalogue categories.
90    SecuritySink,
91    /// A banned call or banned import matched by a declarative rule pack
92    /// (`rulePacks` config). The bare token covers every pack rule; scoped
93    /// tokens can target one `<pack>/<rule-id>` identity.
94    PolicyViolation,
95    /// A `"use client"` file that exports a Next.js server-only /
96    /// route-segment config name (e.g. `metadata`, `revalidate`, `GET`).
97    InvalidClientExport,
98    /// A barrel file that re-exports BOTH a `"use client"` origin module AND a
99    /// server-only origin module (Next.js App Router footgun: one import drags
100    /// the other's directive context across the boundary).
101    MixedClientServerBarrel,
102    /// A `"use client"` / `"use server"` directive string written as an
103    /// expression statement after a non-directive statement (an import, a
104    /// const). It is no longer in the leading prologue, so the RSC bundler
105    /// parses it as an ordinary string and silently ignores it.
106    MisplacedDirective,
107    /// A store member (Pinia `state` / `getters` / `actions` key, or a
108    /// setup-store returned key) declared but never accessed by any consumer
109    /// project-wide. Cross-graph: the store binding is imported (the module is
110    /// reachable) yet a specific member is dead.
111    UnusedStoreMember,
112    /// A Vue `inject(KEY)` or Svelte `getContext(KEY)` whose symbol KEY is
113    /// `provide`/`setContext`'d nowhere in the analyzed project. Cross-graph
114    /// dead-half DI link: at runtime the inject returns `undefined`.
115    UnprovidedInject,
116    /// Two or more Next.js App Router route files that resolve to the same URL
117    /// within one app-root (a guaranteed `next build` failure).
118    RouteCollision,
119    /// Sibling Next.js dynamic route segments at one tree position using
120    /// different param spellings (`[id]` vs `[slug]`; a dev / runtime error
121    /// that `next build` does NOT catch).
122    DynamicSegmentNameConflict,
123    /// A component defined in the project that is exported but never rendered
124    /// (no JSX usage) anywhere across the analyzed project.
125    UnrenderedComponent,
126    /// A Vue `<script setup>` `defineProps`, Svelte 5 `$props()`, or React
127    /// declared prop that is referenced NOWHERE inside its own component.
128    /// Single-component dead-input direction.
129    UnusedComponentProp,
130    /// Used optional input absent from inspected reachable callers.
131    AbsentComponentProp,
132    /// A Vue `<script setup>` `defineEmits` declared event that is EMITTED
133    /// nowhere inside its own single-file component (no `emit('<name>')` call).
134    /// Single-file dead-input direction.
135    UnusedComponentEmit,
136    /// An Angular `@Input()` / signal `input()` / `model()` declared input that
137    /// is read NOWHERE inside its own component (neither the inline/external
138    /// template nor the class body). Single-file dead-input direction; the
139    /// Angular analogue of `unused-component-prop`.
140    UnusedComponentInput,
141    /// An Angular `@Output()` / signal `output()` declared output that is
142    /// EMITTED nowhere inside its own component (no `this.<output>.emit(...)`).
143    /// Single-file dead-output direction; the Angular analogue of
144    /// `unused-component-emit`.
145    UnusedComponentOutput,
146    /// A Next.js Server Action (an export of a `"use server"` file) that no code
147    /// in the project references (no import-and-call, no `action={fn}` binding,
148    /// no `<form action={fn}>`). Cross-graph dead-export direction, reclassified
149    /// from `unused-export` for `"use server"` files.
150    UnusedServerAction,
151    /// A SvelteKit `+page.{ts,server.ts,js,server.js}` `load()` return-object key
152    /// that no consumer reads: not off the sibling `+page.svelte`'s `data.<key>`,
153    /// nor project-wide via `page.data.<key>` / `$page.data.<key>`. A dead load
154    /// key runs a real server/DB fetch cost for data nothing renders.
155    UnusedLoadDataKey,
156    /// A React/Preact prop forwarded unchanged through `>= N` intermediate
157    /// pass-through components until a component that substantively consumes it.
158    /// Health signal, rule defaults to `off` (opt-in). Cross-graph: the chain
159    /// spans multiple components / files.
160    PropDrilling,
161    /// A React/Preact component whose entire body is `return <Child {...props}/>`
162    /// (a single spread-forwarded child render, no own value-add): pure
163    /// structural indirection, a candidate for inlining. Health signal, rule
164    /// defaults to `off` (opt-in).
165    ThinWrapper,
166    /// Three or more React/Preact components across two or more files whose
167    /// statically-harvested prop NAME set is identical after stripping ubiquitous
168    /// DOM / passthrough names (a missing shared `Props` type). Health signal,
169    /// rule defaults to `off` (opt-in). Cross-graph: the group spans multiple
170    /// components / files.
171    DuplicatePropShape,
172    /// A Svelte component dispatching a custom event via
173    /// `createEventDispatcher()` whose event name is listened to NOWHERE in the
174    /// analyzed project. Cross-file dead-output direction: the component fires an
175    /// event nothing handles.
176    UnusedSvelteEvent,
177    /// A CSS / CSS-in-JS design-token DRIFT candidate surfaced in `fallow audit`
178    /// as an advisory styling finding: a hardcoded value where a design token
179    /// exists (a Tailwind arbitrary value like `w-[13px]`, or a near-duplicate
180    /// token). Styling-domain finding produced by the health-time css pass (not
181    /// dead-code); the rule defaults to `warn` and is verdict-neutral.
182    CssTokenDrift,
183    /// A CSS / CSS-in-JS DUPLICATE declaration block: a copy-pasted rule body
184    /// repeated across selectors, a consolidation candidate. Styling-domain
185    /// advisory (rule defaults to `warn`, verdict-neutral); the audit copy of
186    /// this is changed-file-local.
187    CssDuplicateBlock,
188    /// A CSS selector / nesting / important-density complexity finding surfaced
189    /// as advisory styling feedback. Styling-domain finding produced by the
190    /// health-time css pass; defaults to `warn` and is verdict-neutral.
191    CssSelectorComplexity,
192    /// A CSS dead-surface finding, such as unused scoped SFC classes. Styling-
193    /// domain advisory surfaced in `fallow audit`; defaults to `warn` and is
194    /// verdict-neutral.
195    CssDeadSurface,
196    /// A CSS broken-reference finding, such as a class or keyframes reference
197    /// that resolves to no stylesheet definition. Styling-domain advisory
198    /// surfaced by deep CSS audit mode; defaults to `warn` and is
199    /// verdict-neutral.
200    CssBrokenReference,
201    /// A `devDependencies` package imported by production (non-test, non-config)
202    /// source code via a runtime/value import. It should be promoted to
203    /// `dependencies` because a production-only install (`pnpm install --prod`)
204    /// would omit it and break at runtime. The promote-side mirror of
205    /// `test-only-dependency` / `type-only-dependency`.
206    DevDependencyInProduction,
207    /// An export whose leading JSDoc carries `@deprecated` and that still has
208    /// at least one reachable reference. Reported at the export site with the
209    /// consumer count and a capped consumer sample.
210    DeprecatedExportInUse,
211    /// A dependency cycle between workspace packages, built from resolved
212    /// cross-package imports. Reported even when no file-level cycle exists.
213    PackageCycle,
214    /// An Effect layer whose every reference sits inside other layers that
215    /// nothing uses. A layer with zero references stays an `unused-export` or
216    /// an `unused-class-member`.
217    UnusedEffectLayer,
218    /// An Effect tagged error class that type positions or `catchTag` handlers
219    /// reference, but that no code constructs, fails with, or reads as a value.
220    UnusedTaggedError,
221    /// A `catchTag("X")` / `catchTags({ X })` handler whose project tag `X` no
222    /// code produces, when no `unused-tagged-error` finding already covers it.
223    UnproducedCatchTag,
224    /// An audit diff that weakens tests: a new skip or focus marker, removed
225    /// test cases, fewer assertions, or a lowered coverage threshold.
226    /// Audit-only, computed from the base and head text of changed files.
227    WeakenedTests,
228    /// An audit diff that adds a lint, type-check, coverage or Fallow
229    /// suppression comment. Audit-only.
230    AddedSuppression,
231    /// An audit diff that adds a test-environment branch, such as
232    /// `process.env.NODE_ENV === 'test'`, to a non-test source file.
233    /// Audit-only.
234    TestOnlyBranch,
235    /// An audit diff that edits one instance of a base clone group so that it
236    /// no longer matches its siblings, while no sibling changed. Audit-only.
237    DivergedCloneSibling,
238    /// An audit diff that adds a dependency to a `package.json`. Audit-only
239    /// and off by default.
240    AddedDependency,
241    /// One module exports one binding under two or more names, for example
242    /// `export const a = 1; export default a;`.
243    DuplicateExportAlias,
244    /// An exported member of an exported TypeScript namespace that no code
245    /// reads (`export namespace N { export const a = 1 }`).
246    UnusedNamespaceMember,
247    /// Optional shared-state inventory sites, consumed outside core detectors.
248    SharedState,
249    /// A parameter that each visible call of its function passes in one way.
250    ConstantParameter,
251    /// A `protected` class member that neither its class nor a subclass reads.
252    UnusedProtectedClassMember,
253}
254
255impl IssueKind {
256    /// Stable inventory of all issue kinds.
257    pub const ALL: &'static [Self] = &[
258        Self::UnusedFile,
259        Self::UnusedExport,
260        Self::UnusedType,
261        Self::PrivateTypeLeak,
262        Self::UnusedDependency,
263        Self::UnusedDevDependency,
264        Self::UnusedEnumMember,
265        Self::UnusedClassMember,
266        Self::UnresolvedImport,
267        Self::UnlistedDependency,
268        Self::UnlistedBinary,
269        Self::DuplicateExport,
270        Self::CodeDuplication,
271        Self::CircularDependency,
272        Self::ReExportCycle,
273        Self::TypeOnlyDependency,
274        Self::TestOnlyDependency,
275        Self::BoundaryViolation,
276        Self::CoverageGaps,
277        Self::FeatureFlag,
278        Self::Complexity,
279        Self::StaleSuppression,
280        Self::PnpmCatalogEntry,
281        Self::EmptyCatalogGroup,
282        Self::UnresolvedCatalogReference,
283        Self::UnusedDependencyOverride,
284        Self::MisconfiguredDependencyOverride,
285        Self::SecurityClientServerLeak,
286        Self::SecuritySink,
287        Self::PolicyViolation,
288        Self::InvalidClientExport,
289        Self::MixedClientServerBarrel,
290        Self::MisplacedDirective,
291        Self::UnusedStoreMember,
292        Self::UnprovidedInject,
293        Self::RouteCollision,
294        Self::DynamicSegmentNameConflict,
295        Self::UnrenderedComponent,
296        Self::UnusedComponentProp,
297        Self::AbsentComponentProp,
298        Self::UnusedComponentEmit,
299        Self::UnusedComponentInput,
300        Self::UnusedComponentOutput,
301        Self::UnusedServerAction,
302        Self::UnusedLoadDataKey,
303        Self::PropDrilling,
304        Self::ThinWrapper,
305        Self::DuplicatePropShape,
306        Self::UnusedSvelteEvent,
307        Self::CssTokenDrift,
308        Self::CssDuplicateBlock,
309        Self::CssSelectorComplexity,
310        Self::CssDeadSurface,
311        Self::CssBrokenReference,
312        Self::DevDependencyInProduction,
313        Self::DeprecatedExportInUse,
314        Self::PackageCycle,
315        Self::UnusedEffectLayer,
316        Self::UnusedTaggedError,
317        Self::UnproducedCatchTag,
318        Self::WeakenedTests,
319        Self::AddedSuppression,
320        Self::TestOnlyBranch,
321        Self::DivergedCloneSibling,
322        Self::AddedDependency,
323        Self::DuplicateExportAlias,
324        Self::UnusedNamespaceMember,
325        Self::SharedState,
326        Self::ConstantParameter,
327        Self::UnusedProtectedClassMember,
328    ];
329
330    /// Parse an issue kind from the string tokens used in CLI output and suppression comments.
331    #[must_use]
332    pub fn parse(s: &str) -> Option<Self> {
333        crate::issue_meta::issue_meta_for_token(s).and_then(|meta| meta.kind)
334    }
335
336    /// Convert to a u8 discriminant for compact cache storage.
337    #[must_use]
338    pub const fn to_discriminant(self) -> u8 {
339        match self {
340            Self::UnusedFile => 1,
341            Self::UnusedExport => 2,
342            Self::UnusedType => 3,
343            Self::PrivateTypeLeak => 4,
344            Self::UnusedDependency => 5,
345            Self::UnusedDevDependency => 6,
346            Self::UnusedEnumMember => 7,
347            Self::UnusedClassMember => 8,
348            Self::UnresolvedImport => 9,
349            Self::UnlistedDependency => 10,
350            Self::DuplicateExport => 11,
351            Self::CodeDuplication => 12,
352            Self::CircularDependency => 13,
353            Self::TypeOnlyDependency => 14,
354            Self::TestOnlyDependency => 15,
355            Self::BoundaryViolation => 16,
356            Self::CoverageGaps => 17,
357            Self::FeatureFlag => 18,
358            Self::Complexity => 19,
359            Self::StaleSuppression => 20,
360            Self::PnpmCatalogEntry => 21,
361            Self::UnresolvedCatalogReference => 22,
362            Self::UnusedDependencyOverride => 23,
363            Self::MisconfiguredDependencyOverride => 24,
364            Self::EmptyCatalogGroup => 25,
365            Self::ReExportCycle => 26,
366            Self::SecurityClientServerLeak => 27,
367            Self::SecuritySink => 28,
368            Self::PolicyViolation => 29,
369            Self::InvalidClientExport => 30,
370            Self::MixedClientServerBarrel => 31,
371            Self::MisplacedDirective => 32,
372            Self::UnusedStoreMember => 33,
373            Self::UnprovidedInject => 34,
374            Self::RouteCollision => 35,
375            Self::DynamicSegmentNameConflict => 36,
376            Self::UnrenderedComponent => 37,
377            Self::UnusedComponentProp => 38,
378            Self::UnusedComponentEmit => 39,
379            Self::UnusedServerAction => 40,
380            Self::UnusedLoadDataKey => 41,
381            Self::PropDrilling => 42,
382            Self::ThinWrapper => 43,
383            Self::DuplicatePropShape => 44,
384            Self::UnusedComponentInput => 45,
385            Self::UnusedComponentOutput => 46,
386            Self::UnusedSvelteEvent => 47,
387            Self::CssTokenDrift => 48,
388            Self::CssDuplicateBlock => 49,
389            Self::CssSelectorComplexity => 50,
390            Self::CssDeadSurface => 51,
391            Self::CssBrokenReference => 52,
392            Self::DevDependencyInProduction => 53,
393            Self::DeprecatedExportInUse => 54,
394            Self::PackageCycle => 55,
395            Self::AbsentComponentProp => 56,
396            Self::UnusedEffectLayer => 57,
397            Self::UnusedTaggedError => 58,
398            Self::UnproducedCatchTag => 59,
399            Self::WeakenedTests => 60,
400            Self::AddedSuppression => 61,
401            Self::TestOnlyBranch => 62,
402            Self::DivergedCloneSibling => 63,
403            Self::AddedDependency => 64,
404            Self::DuplicateExportAlias => 65,
405            Self::UnlistedBinary => 66,
406            Self::UnusedNamespaceMember => 67,
407            Self::SharedState => 68,
408            Self::ConstantParameter => 69,
409            Self::UnusedProtectedClassMember => 70,
410        }
411    }
412
413    /// Reconstruct from a cache discriminant.
414    #[must_use]
415    pub const fn from_discriminant(d: u8) -> Option<Self> {
416        match d {
417            1 => Some(Self::UnusedFile),
418            2 => Some(Self::UnusedExport),
419            3 => Some(Self::UnusedType),
420            4 => Some(Self::PrivateTypeLeak),
421            5 => Some(Self::UnusedDependency),
422            6 => Some(Self::UnusedDevDependency),
423            7 => Some(Self::UnusedEnumMember),
424            8 => Some(Self::UnusedClassMember),
425            9 => Some(Self::UnresolvedImport),
426            10 => Some(Self::UnlistedDependency),
427            11 => Some(Self::DuplicateExport),
428            12 => Some(Self::CodeDuplication),
429            13 => Some(Self::CircularDependency),
430            14 => Some(Self::TypeOnlyDependency),
431            15 => Some(Self::TestOnlyDependency),
432            16 => Some(Self::BoundaryViolation),
433            17 => Some(Self::CoverageGaps),
434            18 => Some(Self::FeatureFlag),
435            19 => Some(Self::Complexity),
436            20 => Some(Self::StaleSuppression),
437            21 => Some(Self::PnpmCatalogEntry),
438            22 => Some(Self::UnresolvedCatalogReference),
439            23 => Some(Self::UnusedDependencyOverride),
440            24 => Some(Self::MisconfiguredDependencyOverride),
441            25 => Some(Self::EmptyCatalogGroup),
442            26 => Some(Self::ReExportCycle),
443            27 => Some(Self::SecurityClientServerLeak),
444            28 => Some(Self::SecuritySink),
445            29 => Some(Self::PolicyViolation),
446            30 => Some(Self::InvalidClientExport),
447            31 => Some(Self::MixedClientServerBarrel),
448            32 => Some(Self::MisplacedDirective),
449            33 => Some(Self::UnusedStoreMember),
450            34 => Some(Self::UnprovidedInject),
451            35 => Some(Self::RouteCollision),
452            36 => Some(Self::DynamicSegmentNameConflict),
453            37 => Some(Self::UnrenderedComponent),
454            38 => Some(Self::UnusedComponentProp),
455            39 => Some(Self::UnusedComponentEmit),
456            40 => Some(Self::UnusedServerAction),
457            41 => Some(Self::UnusedLoadDataKey),
458            42 => Some(Self::PropDrilling),
459            43 => Some(Self::ThinWrapper),
460            44 => Some(Self::DuplicatePropShape),
461            45 => Some(Self::UnusedComponentInput),
462            46 => Some(Self::UnusedComponentOutput),
463            47 => Some(Self::UnusedSvelteEvent),
464            48 => Some(Self::CssTokenDrift),
465            49 => Some(Self::CssDuplicateBlock),
466            50 => Some(Self::CssSelectorComplexity),
467            51 => Some(Self::CssDeadSurface),
468            52 => Some(Self::CssBrokenReference),
469            53 => Some(Self::DevDependencyInProduction),
470            54 => Some(Self::DeprecatedExportInUse),
471            55 => Some(Self::PackageCycle),
472            56 => Some(Self::AbsentComponentProp),
473            57 => Some(Self::UnusedEffectLayer),
474            58 => Some(Self::UnusedTaggedError),
475            59 => Some(Self::UnproducedCatchTag),
476            60 => Some(Self::WeakenedTests),
477            61 => Some(Self::AddedSuppression),
478            62 => Some(Self::TestOnlyBranch),
479            63 => Some(Self::DivergedCloneSibling),
480            64 => Some(Self::AddedDependency),
481            65 => Some(Self::DuplicateExportAlias),
482            66 => Some(Self::UnlistedBinary),
483            67 => Some(Self::UnusedNamespaceMember),
484            68 => Some(Self::SharedState),
485            69 => Some(Self::ConstantParameter),
486            70 => Some(Self::UnusedProtectedClassMember),
487            _ => None,
488        }
489    }
490}
491
492/// One scoped rule-pack policy suppression target.
493#[derive(Debug, Clone, PartialEq, Eq, Hash)]
494pub struct PolicyRuleSuppression {
495    /// Rule-pack name.
496    pub pack: String,
497    /// Rule id within the pack.
498    pub rule_id: String,
499}
500
501impl PolicyRuleSuppression {
502    /// Build a scoped policy suppression target.
503    #[must_use]
504    pub fn new(pack: impl Into<String>, rule_id: impl Into<String>) -> Self {
505        Self {
506            pack: pack.into(),
507            rule_id: rule_id.into(),
508        }
509    }
510
511    /// Canonical suppression token.
512    #[must_use]
513    pub fn token(&self) -> String {
514        format!("policy-violation:{}/{}", self.pack, self.rule_id)
515    }
516}
517
518/// A specific suppression target parsed from a comment token.
519#[derive(Debug, Clone, PartialEq, Eq)]
520pub enum SuppressionTarget {
521    /// A regular issue-kind token such as `unused-export` or bare
522    /// `policy-violation`.
523    Issue(IssueKind),
524    /// A scoped rule-pack policy token such as
525    /// `policy-violation:team-policy/no-child-process`.
526    PolicyRule(PolicyRuleSuppression),
527}
528
529impl SuppressionTarget {
530    /// Return the regular issue kind when this target is a bare issue-kind
531    /// token.
532    #[must_use]
533    pub const fn issue_kind(&self) -> Option<IssueKind> {
534        match self {
535            Self::Issue(kind) => Some(*kind),
536            Self::PolicyRule(_) => None,
537        }
538    }
539
540    /// Canonical suppression token for output and active-suppression capture.
541    #[must_use]
542    pub fn token(&self) -> String {
543        match self {
544            Self::Issue(kind) => issue_kind_to_kebab(*kind).to_owned(),
545            Self::PolicyRule(rule) => rule.token(),
546        }
547    }
548}
549
550/// Convert an [`IssueKind`] to its canonical suppression token.
551#[must_use]
552pub fn issue_kind_to_kebab(kind: IssueKind) -> &'static str {
553    let Some(meta) = crate::issue_meta::issue_meta_by_kind(kind) else {
554        unreachable!("IssueKind {kind:?} has no metadata row");
555    };
556    meta.suppress_token.unwrap_or(meta.code)
557}
558
559/// Parse a suppression token into a structured target.
560#[must_use]
561pub fn parse_suppression_target(token: &str) -> Option<SuppressionTarget> {
562    parse_policy_rule_suppression_token(token)
563        .map(SuppressionTarget::PolicyRule)
564        .or_else(|| IssueKind::parse(token).map(SuppressionTarget::Issue))
565}
566
567/// Parse canonical scoped policy suppression tokens.
568///
569/// The plural prefix is accepted for consistency with the bare legacy alias,
570/// but output always uses singular `policy-violation:`.
571#[must_use]
572pub fn parse_policy_rule_suppression_token(token: &str) -> Option<PolicyRuleSuppression> {
573    let identity = token
574        .strip_prefix("policy-violation:")
575        .or_else(|| token.strip_prefix("policy-violations:"))?;
576    let (pack, rule_id) = identity.split_once('/')?;
577    if rule_id.contains('/') {
578        return None;
579    }
580    if !is_valid_policy_identifier(pack) || !is_valid_policy_identifier(rule_id) {
581        return None;
582    }
583    Some(PolicyRuleSuppression::new(pack, rule_id))
584}
585
586/// Whether a rule-pack name or rule id can be used inside
587/// `policy-violation:<pack>/<rule-id>` without escaping.
588#[must_use]
589pub fn is_valid_policy_identifier(value: &str) -> bool {
590    !value.is_empty()
591        && value
592            .bytes()
593            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
594}
595
596/// A suppression directive parsed from a source comment.
597///
598/// # Examples
599///
600/// ```
601/// use fallow_types::suppress::{Suppression, IssueKind};
602///
603/// // File-wide suppression (line 0, no specific kind)
604/// let file_wide = Suppression::all(0, 1);
605/// assert_eq!(file_wide.line, 0);
606///
607/// // Line-specific suppression for unused exports
608/// let line_suppress = Suppression::issue(42, 41, IssueKind::UnusedExport);
609/// assert_eq!(line_suppress.issue_kind_target(), Some(IssueKind::UnusedExport));
610/// ```
611#[derive(Debug, Clone)]
612pub struct Suppression {
613    /// 1-based line this suppression applies to. 0 = file-wide suppression.
614    /// For a range, the first line inside the range.
615    pub line: u32,
616    /// 1-based line where the suppression comment itself appears.
617    /// For `fallow-ignore-next-line`, this is `line - 1`.
618    /// For `fallow-ignore-file`, this is the actual line of the comment in the source.
619    pub comment_line: u32,
620    /// None = suppress all issue kinds on this line or file.
621    pub target: Option<SuppressionTarget>,
622    /// Human-authored reason after `--`, when present.
623    pub reason: Option<String>,
624    /// What the suppression covers: the file, one line, or a range of lines.
625    pub scope: SuppressionScope,
626}
627
628/// What one suppression covers.
629#[derive(Debug, Clone, Copy, PartialEq, Eq)]
630pub enum SuppressionScope {
631    /// A `fallow-ignore-file` marker. [`Suppression::line`] is 0.
632    File,
633    /// A `fallow-ignore-next-line` marker for [`Suppression::line`].
634    Line,
635    /// A `fallow-ignore-start` / `fallow-ignore-end` pair. The range covers
636    /// the lines from [`Suppression::line`] up to, but not including,
637    /// `end_line`. Only clone detection applies a range: the line and file
638    /// predicates of [`Suppression`] never match a range entry.
639    Range {
640        /// 1-based line of the `fallow-ignore-end` comment.
641        end_line: u32,
642    },
643}
644
645impl SuppressionScope {
646    /// The file or line scope that a plain marker for `line` has.
647    #[must_use]
648    pub const fn for_line(line: u32) -> Self {
649        if line == 0 { Self::File } else { Self::Line }
650    }
651}
652
653impl Suppression {
654    /// Build a blanket suppression.
655    #[must_use]
656    pub const fn all(line: u32, comment_line: u32) -> Self {
657        Self {
658            line,
659            comment_line,
660            target: None,
661            reason: None,
662            scope: SuppressionScope::for_line(line),
663        }
664    }
665
666    /// Build a regular issue-kind suppression.
667    #[must_use]
668    pub const fn issue(line: u32, comment_line: u32, kind: IssueKind) -> Self {
669        Self {
670            line,
671            comment_line,
672            target: Some(SuppressionTarget::Issue(kind)),
673            reason: None,
674            scope: SuppressionScope::for_line(line),
675        }
676    }
677
678    /// Build a range suppression for one issue kind.
679    ///
680    /// `first_line` is the first line inside the range, `comment_line` the
681    /// line of the `fallow-ignore-start` comment, and `end_line` the line of
682    /// the `fallow-ignore-end` comment.
683    #[must_use]
684    pub const fn range(first_line: u32, comment_line: u32, end_line: u32, kind: IssueKind) -> Self {
685        Self {
686            line: first_line,
687            comment_line,
688            target: Some(SuppressionTarget::Issue(kind)),
689            reason: None,
690            scope: SuppressionScope::Range { end_line },
691        }
692    }
693
694    /// The `fallow-ignore-end` line when this suppression is a range.
695    #[must_use]
696    pub const fn range_end_line(&self) -> Option<u32> {
697        match self.scope {
698            SuppressionScope::Range { end_line } => Some(end_line),
699            SuppressionScope::File | SuppressionScope::Line => None,
700        }
701    }
702
703    /// Whether this suppression is a range that covers `line`.
704    #[must_use]
705    pub const fn range_covers_line(&self, line: u32) -> bool {
706        match self.scope {
707            SuppressionScope::Range { end_line } => line >= self.line && line < end_line,
708            SuppressionScope::File | SuppressionScope::Line => false,
709        }
710    }
711
712    /// Build a scoped rule-pack policy suppression.
713    #[must_use]
714    pub fn policy_rule(
715        line: u32,
716        comment_line: u32,
717        pack: impl Into<String>,
718        rule_id: impl Into<String>,
719    ) -> Self {
720        Self {
721            line,
722            comment_line,
723            target: Some(SuppressionTarget::PolicyRule(PolicyRuleSuppression::new(
724                pack, rule_id,
725            ))),
726            reason: None,
727            scope: SuppressionScope::for_line(line),
728        }
729    }
730
731    /// Return a copy with a parsed suppression reason attached.
732    #[must_use]
733    pub fn with_reason(mut self, reason: Option<String>) -> Self {
734        self.reason = reason;
735        self
736    }
737
738    /// The bare issue kind if this suppression targets one.
739    #[must_use]
740    pub const fn issue_kind_target(&self) -> Option<IssueKind> {
741        match &self.target {
742            Some(SuppressionTarget::Issue(kind)) => Some(*kind),
743            Some(SuppressionTarget::PolicyRule(_)) | None => None,
744        }
745    }
746
747    /// The scoped policy target if this suppression targets one rule-pack rule.
748    #[must_use]
749    pub const fn policy_rule_target(&self) -> Option<&PolicyRuleSuppression> {
750        match &self.target {
751            Some(SuppressionTarget::PolicyRule(rule)) => Some(rule),
752            Some(SuppressionTarget::Issue(_)) | None => None,
753        }
754    }
755
756    /// Canonical token for this suppression, or `None` for blanket comments.
757    #[must_use]
758    pub fn target_token(&self) -> Option<String> {
759        self.target.as_ref().map(SuppressionTarget::token)
760    }
761
762    /// Whether the comment applies to `line`. A range never applies here.
763    #[must_use]
764    pub const fn applies_to_line(&self, line: u32) -> bool {
765        match self.scope {
766            SuppressionScope::File => true,
767            SuppressionScope::Line => self.line == line,
768            SuppressionScope::Range { .. } => false,
769        }
770    }
771
772    /// Whether this suppression covers a regular issue kind on a line.
773    ///
774    /// Scoped policy-rule targets intentionally do not match this generic
775    /// predicate. Policy detection uses [`Self::matches_policy_rule`] so the
776    /// exact pack and rule id are available.
777    #[must_use]
778    pub fn matches_issue_kind(&self, line: u32, kind: IssueKind) -> bool {
779        self.applies_to_line(line)
780            && match &self.target {
781                None => true,
782                Some(SuppressionTarget::Issue(target_kind)) => *target_kind == kind,
783                Some(SuppressionTarget::PolicyRule(_)) => false,
784            }
785    }
786
787    /// Whether this suppression covers a policy finding on a line.
788    #[must_use]
789    pub fn matches_policy_rule(&self, line: u32, pack: &str, rule_id: &str) -> bool {
790        self.applies_to_line(line)
791            && match &self.target {
792                None | Some(SuppressionTarget::Issue(IssueKind::PolicyViolation)) => true,
793                Some(SuppressionTarget::Issue(_)) => false,
794                Some(SuppressionTarget::PolicyRule(target)) => {
795                    target.pack == pack && target.rule_id == rule_id
796                }
797            }
798    }
799}
800
801/// Check if a specific issue at a given line should be suppressed.
802#[must_use]
803pub fn is_suppressed(suppressions: &[Suppression], line: u32, kind: IssueKind) -> bool {
804    suppressions
805        .iter()
806        .any(|suppression| suppression.matches_issue_kind(line, kind))
807}
808
809/// Check if the entire file is suppressed for issue types that do not have line numbers.
810#[must_use]
811pub fn is_file_suppressed(suppressions: &[Suppression], kind: IssueKind) -> bool {
812    suppressions.iter().any(|suppression| {
813        suppression.scope == SuppressionScope::File && suppression.matches_issue_kind(0, kind)
814    })
815}
816
817/// What is wrong with one `fallow-ignore-start` or `fallow-ignore-end`
818/// marker. A marker with a problem has no effect.
819#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
820#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
821#[serde(rename_all = "snake_case")]
822pub enum RangeMarkerProblemKind {
823    /// A `fallow-ignore-start` with no `fallow-ignore-end` after it.
824    UnclosedStart,
825    /// A `fallow-ignore-end` with no open `fallow-ignore-start`.
826    UnmatchedEnd,
827    /// A `fallow-ignore-start` inside an open range. The outer range applies.
828    NestedStart,
829    /// A range marker without an issue kind. A range needs
830    /// `code-duplication`.
831    MissingKind,
832    /// A range marker names an issue kind other than `code-duplication`.
833    /// The `code-duplication` part of the same marker still applies.
834    UnsupportedKind,
835    /// A range marker shares its line with code. A range marker must be on
836    /// its own line.
837    NotOwnLine,
838}
839
840impl RangeMarkerProblemKind {
841    /// Stable one-byte code for cache storage.
842    #[must_use]
843    pub const fn to_code(self) -> u8 {
844        match self {
845            Self::UnclosedStart => 1,
846            Self::UnmatchedEnd => 2,
847            Self::NestedStart => 3,
848            Self::MissingKind => 4,
849            Self::UnsupportedKind => 5,
850            Self::NotOwnLine => 6,
851        }
852    }
853
854    /// Read a code that [`Self::to_code`] wrote.
855    #[must_use]
856    pub const fn from_code(code: u8) -> Option<Self> {
857        match code {
858            1 => Some(Self::UnclosedStart),
859            2 => Some(Self::UnmatchedEnd),
860            3 => Some(Self::NestedStart),
861            4 => Some(Self::MissingKind),
862            5 => Some(Self::UnsupportedKind),
863            6 => Some(Self::NotOwnLine),
864            _ => None,
865        }
866    }
867
868    /// One-sentence description for human output.
869    #[must_use]
870    pub const fn description(self) -> &'static str {
871        match self {
872            Self::UnclosedStart => {
873                "fallow-ignore-start has no fallow-ignore-end, so it suppresses nothing"
874            }
875            Self::UnmatchedEnd => {
876                "fallow-ignore-end has no fallow-ignore-start before it (each range marker must be on its own line)"
877            }
878            Self::NestedStart => {
879                "fallow-ignore-start is inside an open range; the outer range applies"
880            }
881            Self::MissingKind => {
882                "range markers need the code-duplication kind; this marker suppresses nothing"
883            }
884            Self::UnsupportedKind => {
885                "range markers support only code-duplication; this kind is not suppressed"
886            }
887            Self::NotOwnLine => {
888                "range marker shares its line with code, so it suppresses nothing; put it on its own line"
889            }
890        }
891    }
892}
893
894/// One range marker with a problem, at a line of one file.
895#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
896#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
897pub struct RangeMarkerProblem {
898    /// 1-based line of the marker comment.
899    pub line: u32,
900    /// What is wrong with the marker.
901    #[serde(rename = "problem")]
902    pub kind: RangeMarkerProblemKind,
903    /// The kind token that the range does not support. Present only for
904    /// `unsupported_kind`.
905    #[serde(default, skip_serializing_if = "Option::is_none")]
906    pub token: Option<String>,
907}
908
909/// A suppression token that did not parse to any known `IssueKind`.
910///
911/// Emitted alongside `Suppression` when a `// fallow-ignore-*` marker contains
912/// a typo or an obsolete issue-kind name. The known tokens on the same marker
913/// are recorded as normal `Suppression` entries; this struct preserves the
914/// unknown token so the downstream `find_stale` pass can surface it as a
915/// `StaleSuppression` finding with `kind_known: false`. Without this, the
916/// entire suppression line would be discarded silently. See issue #449.
917#[derive(Debug, Clone)]
918pub struct UnknownSuppressionKind {
919    /// 1-based line where the suppression comment itself appears.
920    pub comment_line: u32,
921    /// Whether the marker was `fallow-ignore-file` (`true`) or
922    /// `fallow-ignore-next-line` (`false`).
923    pub is_file_level: bool,
924    /// The verbatim token from the marker that did not parse.
925    pub token: String,
926    /// Human-authored reason after `--`, when present.
927    pub reason: Option<String>,
928}
929
930/// Find the closest known issue-kind name to `input` when it is plausibly a typo.
931///
932/// Applies the policy of [`crate::levenshtein::closest_match`].
933#[must_use]
934pub fn closest_known_kind_name(input: &str) -> Option<&'static str> {
935    crate::levenshtein::closest_match(input, KNOWN_ISSUE_KIND_NAMES.iter().copied())
936}
937
938const _: () = assert!(std::mem::size_of::<IssueKind>() == 1);
939
940#[cfg(test)]
941mod tests {
942    use super::*;
943
944    #[test]
945    fn issue_kind_parse_accepts_registry_codes_and_aliases() {
946        for meta in crate::issue_meta::ISSUE_KIND_META
947            .iter()
948            .filter(|meta| meta.kind.is_some())
949        {
950            let expected = meta.kind;
951            assert_eq!(
952                IssueKind::parse(meta.code),
953                expected,
954                "canonical registry token {} must parse",
955                meta.code
956            );
957            for alias in meta.aliases {
958                assert_eq!(
959                    IssueKind::parse(alias),
960                    expected,
961                    "registry alias {alias} must parse as {}",
962                    meta.code
963                );
964            }
965        }
966    }
967
968    #[test]
969    fn issue_kind_parse_accepts_registry_suppression_tokens() {
970        for meta in crate::issue_meta::ISSUE_KIND_META {
971            let (Some(kind), Some(token)) = (meta.kind, meta.suppress_token) else {
972                continue;
973            };
974            assert_eq!(
975                IssueKind::parse(token),
976                Some(kind),
977                "registry suppression token {token} must parse as {}",
978                meta.code
979            );
980        }
981    }
982
983    #[test]
984    fn issue_kind_parse_accepts_diff_risk_tokens() {
985        let cases = [
986            ("weakened-tests", IssueKind::WeakenedTests),
987            ("added-suppression", IssueKind::AddedSuppression),
988            ("test-only-branch", IssueKind::TestOnlyBranch),
989            ("diverged-clone-sibling", IssueKind::DivergedCloneSibling),
990            ("added-dependency", IssueKind::AddedDependency),
991        ];
992        for (token, kind) in cases {
993            assert_eq!(IssueKind::parse(token), Some(kind), "{token}");
994            assert_eq!(issue_kind_to_kebab(kind), token);
995        }
996    }
997
998    #[test]
999    fn issue_kind_from_str_unknown() {
1000        assert_eq!(IssueKind::parse("foo"), None);
1001        assert_eq!(IssueKind::parse(""), None);
1002    }
1003
1004    #[test]
1005    fn issue_kind_from_str_near_misses() {
1006        assert_eq!(IssueKind::parse("Unused-File"), None);
1007        assert_eq!(IssueKind::parse("UNUSED-EXPORT"), None);
1008        assert_eq!(IssueKind::parse("unused_file"), None);
1009        assert_eq!(IssueKind::parse("unused-files"), None);
1010    }
1011
1012    #[test]
1013    fn discriminant_out_of_range() {
1014        // Pin exact discriminants so an inserted or reordered variant that
1015        // shifts wire values is caught. `ALL` is not discriminant-ordered, so
1016        // the mapping is spelled out explicitly, and the row count is checked
1017        // against `ALL` below so a new variant cannot be added without a row.
1018        let cases: &[(u8, IssueKind)] = &[
1019            (1, IssueKind::UnusedFile),
1020            (2, IssueKind::UnusedExport),
1021            (3, IssueKind::UnusedType),
1022            (4, IssueKind::PrivateTypeLeak),
1023            (5, IssueKind::UnusedDependency),
1024            (6, IssueKind::UnusedDevDependency),
1025            (7, IssueKind::UnusedEnumMember),
1026            (8, IssueKind::UnusedClassMember),
1027            (9, IssueKind::UnresolvedImport),
1028            (10, IssueKind::UnlistedDependency),
1029            (11, IssueKind::DuplicateExport),
1030            (12, IssueKind::CodeDuplication),
1031            (13, IssueKind::CircularDependency),
1032            (14, IssueKind::TypeOnlyDependency),
1033            (15, IssueKind::TestOnlyDependency),
1034            (16, IssueKind::BoundaryViolation),
1035            (17, IssueKind::CoverageGaps),
1036            (18, IssueKind::FeatureFlag),
1037            (19, IssueKind::Complexity),
1038            (20, IssueKind::StaleSuppression),
1039            (21, IssueKind::PnpmCatalogEntry),
1040            (22, IssueKind::UnresolvedCatalogReference),
1041            (23, IssueKind::UnusedDependencyOverride),
1042            (24, IssueKind::MisconfiguredDependencyOverride),
1043            (25, IssueKind::EmptyCatalogGroup),
1044            (26, IssueKind::ReExportCycle),
1045            (27, IssueKind::SecurityClientServerLeak),
1046            (28, IssueKind::SecuritySink),
1047            (29, IssueKind::PolicyViolation),
1048            (30, IssueKind::InvalidClientExport),
1049            (31, IssueKind::MixedClientServerBarrel),
1050            (32, IssueKind::MisplacedDirective),
1051            (33, IssueKind::UnusedStoreMember),
1052            (34, IssueKind::UnprovidedInject),
1053            (35, IssueKind::RouteCollision),
1054            (36, IssueKind::DynamicSegmentNameConflict),
1055            (37, IssueKind::UnrenderedComponent),
1056            (38, IssueKind::UnusedComponentProp),
1057            (39, IssueKind::UnusedComponentEmit),
1058            (40, IssueKind::UnusedServerAction),
1059            (41, IssueKind::UnusedLoadDataKey),
1060            (42, IssueKind::PropDrilling),
1061            (43, IssueKind::ThinWrapper),
1062            (44, IssueKind::DuplicatePropShape),
1063            (45, IssueKind::UnusedComponentInput),
1064            (46, IssueKind::UnusedComponentOutput),
1065            (47, IssueKind::UnusedSvelteEvent),
1066            (48, IssueKind::CssTokenDrift),
1067            (49, IssueKind::CssDuplicateBlock),
1068            (50, IssueKind::CssSelectorComplexity),
1069            (51, IssueKind::CssDeadSurface),
1070            (52, IssueKind::CssBrokenReference),
1071            (53, IssueKind::DevDependencyInProduction),
1072            (54, IssueKind::DeprecatedExportInUse),
1073            (55, IssueKind::PackageCycle),
1074            (56, IssueKind::AbsentComponentProp),
1075            (57, IssueKind::UnusedEffectLayer),
1076            (58, IssueKind::UnusedTaggedError),
1077            (59, IssueKind::UnproducedCatchTag),
1078            (60, IssueKind::WeakenedTests),
1079            (61, IssueKind::AddedSuppression),
1080            (62, IssueKind::TestOnlyBranch),
1081            (63, IssueKind::DivergedCloneSibling),
1082            (64, IssueKind::AddedDependency),
1083            (65, IssueKind::DuplicateExportAlias),
1084            (66, IssueKind::UnlistedBinary),
1085            (67, IssueKind::UnusedNamespaceMember),
1086            (69, IssueKind::ConstantParameter),
1087            (70, IssueKind::UnusedProtectedClassMember),
1088        ];
1089        for &(discriminant, kind) in cases {
1090            assert_eq!(kind.to_discriminant(), discriminant, "{kind:?} drifted");
1091            assert_eq!(IssueKind::from_discriminant(discriminant), Some(kind));
1092        }
1093        assert_eq!(IssueKind::from_discriminant(0), None);
1094        let max_discriminant = IssueKind::ALL
1095            .iter()
1096            .map(|kind| kind.to_discriminant())
1097            .max()
1098            .expect("IssueKind::ALL should not be empty");
1099        assert_eq!(IssueKind::from_discriminant(max_discriminant + 1), None);
1100        assert_eq!(IssueKind::from_discriminant(u8::MAX), None);
1101    }
1102
1103    #[test]
1104    fn discriminant_roundtrip() {
1105        for &kind in IssueKind::ALL {
1106            assert_eq!(
1107                IssueKind::from_discriminant(kind.to_discriminant()),
1108                Some(kind)
1109            );
1110        }
1111        assert_eq!(IssueKind::from_discriminant(0), None);
1112        let max_discriminant = IssueKind::ALL
1113            .iter()
1114            .map(|kind| kind.to_discriminant())
1115            .max()
1116            .expect("IssueKind::ALL should not be empty");
1117        assert_eq!(IssueKind::from_discriminant(max_discriminant + 1), None);
1118    }
1119
1120    #[test]
1121    fn discriminant_values_are_unique() {
1122        let discriminants: Vec<u8> = IssueKind::ALL
1123            .iter()
1124            .map(|kind| kind.to_discriminant())
1125            .collect();
1126        let mut sorted = discriminants.clone();
1127        sorted.sort_unstable();
1128        sorted.dedup();
1129        assert_eq!(
1130            discriminants.len(),
1131            sorted.len(),
1132            "discriminant values must be unique"
1133        );
1134    }
1135
1136    #[test]
1137    fn discriminant_starts_at_one() {
1138        assert_eq!(IssueKind::UnusedFile.to_discriminant(), 1);
1139    }
1140
1141    #[test]
1142    fn issue_kind_to_kebab_uses_registry_suppression_token() {
1143        for &kind in IssueKind::ALL {
1144            let meta = crate::issue_meta::issue_meta_by_kind(kind)
1145                .unwrap_or_else(|| panic!("IssueKind {kind:?} has no metadata row"));
1146            let token = issue_kind_to_kebab(kind);
1147            assert_eq!(token, meta.suppress_token.unwrap_or(meta.code));
1148            assert_eq!(IssueKind::parse(token), Some(kind));
1149        }
1150    }
1151
1152    #[test]
1153    fn suppression_line_zero_is_file_wide() {
1154        let s = Suppression::all(0, 1);
1155        assert_eq!(s.line, 0);
1156        assert!(s.issue_kind_target().is_none());
1157    }
1158
1159    #[test]
1160    fn suppression_with_specific_kind_and_line() {
1161        let s = Suppression::issue(42, 41, IssueKind::UnusedExport);
1162        assert_eq!(s.line, 42);
1163        assert_eq!(s.comment_line, 41);
1164        assert_eq!(s.issue_kind_target(), Some(IssueKind::UnusedExport));
1165    }
1166
1167    #[test]
1168    fn suppression_predicates_match_lines_and_file_wide_markers() {
1169        let suppressions = vec![
1170            Suppression::issue(42, 41, IssueKind::UnusedExport),
1171            Suppression::all(0, 1),
1172        ];
1173
1174        assert!(is_suppressed(&suppressions, 42, IssueKind::UnusedExport));
1175        assert!(is_suppressed(&suppressions, 10, IssueKind::UnusedType));
1176        assert!(is_file_suppressed(&suppressions, IssueKind::UnusedFile));
1177    }
1178
1179    #[test]
1180    fn parses_scoped_policy_suppression_token() {
1181        let target =
1182            parse_policy_rule_suppression_token("policy-violation:team-policy/no-child-process")
1183                .expect("scoped token should parse");
1184        assert_eq!(target.pack, "team-policy");
1185        assert_eq!(target.rule_id, "no-child-process");
1186        assert_eq!(
1187            target.token(),
1188            "policy-violation:team-policy/no-child-process"
1189        );
1190    }
1191
1192    #[test]
1193    fn rejects_malformed_scoped_policy_suppression_tokens() {
1194        for token in [
1195            "policy-violation:",
1196            "policy-violation:team-policy",
1197            "policy-violation:/no-child-process",
1198            "policy-violation:team-policy/",
1199            "policy-violation:team-policy/no/child-process",
1200            "policy-violation:team policy/no-child-process",
1201            "policy-violation:team-policy/no:child-process",
1202        ] {
1203            assert!(
1204                parse_policy_rule_suppression_token(token).is_none(),
1205                "{token} should be rejected"
1206            );
1207        }
1208    }
1209
1210    #[test]
1211    fn scoped_policy_suppression_matches_exact_policy_rule_only() {
1212        let suppression = Suppression::policy_rule(7, 6, "team-policy", "no-child-process");
1213        assert!(suppression.matches_policy_rule(7, "team-policy", "no-child-process"));
1214        assert!(!suppression.matches_policy_rule(7, "team-policy", "no-fs"));
1215        assert!(!suppression.matches_policy_rule(8, "team-policy", "no-child-process"));
1216        assert!(!suppression.matches_issue_kind(7, IssueKind::PolicyViolation));
1217    }
1218
1219    #[test]
1220    fn known_issue_kind_names_parses_each_entry() {
1221        for &name in KNOWN_ISSUE_KIND_NAMES.iter() {
1222            assert!(
1223                IssueKind::parse(name).is_some(),
1224                "KNOWN_ISSUE_KIND_NAMES contains '{name}' but IssueKind::parse rejects it"
1225            );
1226        }
1227    }
1228
1229    #[test]
1230    #[cfg_attr(
1231        miri,
1232        ignore = "too slow under Miri: edit distance over every issue kind in safe code"
1233    )]
1234    fn closest_known_kind_name_finds_near_misses() {
1235        assert_eq!(
1236            closest_known_kind_name("unused-exports"),
1237            Some("unused-export")
1238        );
1239        assert_eq!(closest_known_kind_name("unused-files"), Some("unused-file"));
1240        assert_eq!(closest_known_kind_name("complxity"), Some("complexity"));
1241    }
1242
1243    #[test]
1244    #[cfg_attr(
1245        miri,
1246        ignore = "too slow under Miri: edit distance over every issue kind in safe code"
1247    )]
1248    fn closest_known_kind_name_rejects_novel_strings() {
1249        assert_eq!(closest_known_kind_name("xyzzy"), None);
1250        assert_eq!(closest_known_kind_name("foo"), None);
1251        assert_eq!(closest_known_kind_name(""), None);
1252    }
1253
1254    #[test]
1255    #[cfg_attr(
1256        miri,
1257        ignore = "too slow under Miri: edit distance over every issue kind in safe code"
1258    )]
1259    fn closest_known_kind_name_skips_exact_match() {
1260        assert_eq!(closest_known_kind_name("unused-export"), None);
1261    }
1262}