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    /// A namespace binding that the code uses as a whole value, so every
254    /// export of its target module gets credit and stays unchecked.
255    NamespaceEscape,
256    /// An exported value that only test-side files use: test, story, fixture
257    /// and bench files, `production.ignore` files, and test helpers.
258    TestOnlyExport,
259}
260
261impl IssueKind {
262    /// Stable inventory of all issue kinds.
263    pub const ALL: &'static [Self] = &[
264        Self::UnusedFile,
265        Self::UnusedExport,
266        Self::UnusedType,
267        Self::PrivateTypeLeak,
268        Self::UnusedDependency,
269        Self::UnusedDevDependency,
270        Self::UnusedEnumMember,
271        Self::UnusedClassMember,
272        Self::UnresolvedImport,
273        Self::UnlistedDependency,
274        Self::UnlistedBinary,
275        Self::DuplicateExport,
276        Self::CodeDuplication,
277        Self::CircularDependency,
278        Self::ReExportCycle,
279        Self::TypeOnlyDependency,
280        Self::TestOnlyDependency,
281        Self::BoundaryViolation,
282        Self::CoverageGaps,
283        Self::FeatureFlag,
284        Self::Complexity,
285        Self::StaleSuppression,
286        Self::PnpmCatalogEntry,
287        Self::EmptyCatalogGroup,
288        Self::UnresolvedCatalogReference,
289        Self::UnusedDependencyOverride,
290        Self::MisconfiguredDependencyOverride,
291        Self::SecurityClientServerLeak,
292        Self::SecuritySink,
293        Self::PolicyViolation,
294        Self::InvalidClientExport,
295        Self::MixedClientServerBarrel,
296        Self::MisplacedDirective,
297        Self::UnusedStoreMember,
298        Self::UnprovidedInject,
299        Self::RouteCollision,
300        Self::DynamicSegmentNameConflict,
301        Self::UnrenderedComponent,
302        Self::UnusedComponentProp,
303        Self::AbsentComponentProp,
304        Self::UnusedComponentEmit,
305        Self::UnusedComponentInput,
306        Self::UnusedComponentOutput,
307        Self::UnusedServerAction,
308        Self::UnusedLoadDataKey,
309        Self::PropDrilling,
310        Self::ThinWrapper,
311        Self::DuplicatePropShape,
312        Self::UnusedSvelteEvent,
313        Self::CssTokenDrift,
314        Self::CssDuplicateBlock,
315        Self::CssSelectorComplexity,
316        Self::CssDeadSurface,
317        Self::CssBrokenReference,
318        Self::DevDependencyInProduction,
319        Self::DeprecatedExportInUse,
320        Self::PackageCycle,
321        Self::UnusedEffectLayer,
322        Self::UnusedTaggedError,
323        Self::UnproducedCatchTag,
324        Self::WeakenedTests,
325        Self::AddedSuppression,
326        Self::TestOnlyBranch,
327        Self::DivergedCloneSibling,
328        Self::AddedDependency,
329        Self::DuplicateExportAlias,
330        Self::UnusedNamespaceMember,
331        Self::SharedState,
332        Self::ConstantParameter,
333        Self::UnusedProtectedClassMember,
334        Self::NamespaceEscape,
335        Self::TestOnlyExport,
336    ];
337
338    /// Parse an issue kind from the string tokens used in CLI output and suppression comments.
339    #[must_use]
340    pub fn parse(s: &str) -> Option<Self> {
341        crate::issue_meta::issue_meta_for_token(s).and_then(|meta| meta.kind)
342    }
343
344    /// Convert to a u8 discriminant for compact cache storage.
345    #[must_use]
346    pub const fn to_discriminant(self) -> u8 {
347        match self {
348            Self::UnusedFile => 1,
349            Self::UnusedExport => 2,
350            Self::UnusedType => 3,
351            Self::PrivateTypeLeak => 4,
352            Self::UnusedDependency => 5,
353            Self::UnusedDevDependency => 6,
354            Self::UnusedEnumMember => 7,
355            Self::UnusedClassMember => 8,
356            Self::UnresolvedImport => 9,
357            Self::UnlistedDependency => 10,
358            Self::DuplicateExport => 11,
359            Self::CodeDuplication => 12,
360            Self::CircularDependency => 13,
361            Self::TypeOnlyDependency => 14,
362            Self::TestOnlyDependency => 15,
363            Self::BoundaryViolation => 16,
364            Self::CoverageGaps => 17,
365            Self::FeatureFlag => 18,
366            Self::Complexity => 19,
367            Self::StaleSuppression => 20,
368            Self::PnpmCatalogEntry => 21,
369            Self::UnresolvedCatalogReference => 22,
370            Self::UnusedDependencyOverride => 23,
371            Self::MisconfiguredDependencyOverride => 24,
372            Self::EmptyCatalogGroup => 25,
373            Self::ReExportCycle => 26,
374            Self::SecurityClientServerLeak => 27,
375            Self::SecuritySink => 28,
376            Self::PolicyViolation => 29,
377            Self::InvalidClientExport => 30,
378            Self::MixedClientServerBarrel => 31,
379            Self::MisplacedDirective => 32,
380            Self::UnusedStoreMember => 33,
381            Self::UnprovidedInject => 34,
382            Self::RouteCollision => 35,
383            Self::DynamicSegmentNameConflict => 36,
384            Self::UnrenderedComponent => 37,
385            Self::UnusedComponentProp => 38,
386            Self::UnusedComponentEmit => 39,
387            Self::UnusedServerAction => 40,
388            Self::UnusedLoadDataKey => 41,
389            Self::PropDrilling => 42,
390            Self::ThinWrapper => 43,
391            Self::DuplicatePropShape => 44,
392            Self::UnusedComponentInput => 45,
393            Self::UnusedComponentOutput => 46,
394            Self::UnusedSvelteEvent => 47,
395            Self::CssTokenDrift => 48,
396            Self::CssDuplicateBlock => 49,
397            Self::CssSelectorComplexity => 50,
398            Self::CssDeadSurface => 51,
399            Self::CssBrokenReference => 52,
400            Self::DevDependencyInProduction => 53,
401            Self::DeprecatedExportInUse => 54,
402            Self::PackageCycle => 55,
403            Self::AbsentComponentProp => 56,
404            Self::UnusedEffectLayer => 57,
405            Self::UnusedTaggedError => 58,
406            Self::UnproducedCatchTag => 59,
407            Self::WeakenedTests => 60,
408            Self::AddedSuppression => 61,
409            Self::TestOnlyBranch => 62,
410            Self::DivergedCloneSibling => 63,
411            Self::AddedDependency => 64,
412            Self::DuplicateExportAlias => 65,
413            Self::UnlistedBinary => 66,
414            Self::UnusedNamespaceMember => 67,
415            Self::SharedState => 68,
416            Self::ConstantParameter => 69,
417            Self::UnusedProtectedClassMember => 70,
418            Self::NamespaceEscape => 71,
419            Self::TestOnlyExport => 72,
420        }
421    }
422
423    /// Reconstruct from a cache discriminant.
424    #[must_use]
425    pub const fn from_discriminant(d: u8) -> Option<Self> {
426        match d {
427            1 => Some(Self::UnusedFile),
428            2 => Some(Self::UnusedExport),
429            3 => Some(Self::UnusedType),
430            4 => Some(Self::PrivateTypeLeak),
431            5 => Some(Self::UnusedDependency),
432            6 => Some(Self::UnusedDevDependency),
433            7 => Some(Self::UnusedEnumMember),
434            8 => Some(Self::UnusedClassMember),
435            9 => Some(Self::UnresolvedImport),
436            10 => Some(Self::UnlistedDependency),
437            11 => Some(Self::DuplicateExport),
438            12 => Some(Self::CodeDuplication),
439            13 => Some(Self::CircularDependency),
440            14 => Some(Self::TypeOnlyDependency),
441            15 => Some(Self::TestOnlyDependency),
442            16 => Some(Self::BoundaryViolation),
443            17 => Some(Self::CoverageGaps),
444            18 => Some(Self::FeatureFlag),
445            19 => Some(Self::Complexity),
446            20 => Some(Self::StaleSuppression),
447            21 => Some(Self::PnpmCatalogEntry),
448            22 => Some(Self::UnresolvedCatalogReference),
449            23 => Some(Self::UnusedDependencyOverride),
450            24 => Some(Self::MisconfiguredDependencyOverride),
451            25 => Some(Self::EmptyCatalogGroup),
452            26 => Some(Self::ReExportCycle),
453            27 => Some(Self::SecurityClientServerLeak),
454            28 => Some(Self::SecuritySink),
455            29 => Some(Self::PolicyViolation),
456            30 => Some(Self::InvalidClientExport),
457            31 => Some(Self::MixedClientServerBarrel),
458            32 => Some(Self::MisplacedDirective),
459            33 => Some(Self::UnusedStoreMember),
460            34 => Some(Self::UnprovidedInject),
461            35 => Some(Self::RouteCollision),
462            36 => Some(Self::DynamicSegmentNameConflict),
463            37 => Some(Self::UnrenderedComponent),
464            38 => Some(Self::UnusedComponentProp),
465            39 => Some(Self::UnusedComponentEmit),
466            40 => Some(Self::UnusedServerAction),
467            41 => Some(Self::UnusedLoadDataKey),
468            42 => Some(Self::PropDrilling),
469            43 => Some(Self::ThinWrapper),
470            44 => Some(Self::DuplicatePropShape),
471            45 => Some(Self::UnusedComponentInput),
472            46 => Some(Self::UnusedComponentOutput),
473            47 => Some(Self::UnusedSvelteEvent),
474            48 => Some(Self::CssTokenDrift),
475            49 => Some(Self::CssDuplicateBlock),
476            50 => Some(Self::CssSelectorComplexity),
477            51 => Some(Self::CssDeadSurface),
478            52 => Some(Self::CssBrokenReference),
479            53 => Some(Self::DevDependencyInProduction),
480            54 => Some(Self::DeprecatedExportInUse),
481            55 => Some(Self::PackageCycle),
482            56 => Some(Self::AbsentComponentProp),
483            57 => Some(Self::UnusedEffectLayer),
484            58 => Some(Self::UnusedTaggedError),
485            59 => Some(Self::UnproducedCatchTag),
486            60 => Some(Self::WeakenedTests),
487            61 => Some(Self::AddedSuppression),
488            62 => Some(Self::TestOnlyBranch),
489            63 => Some(Self::DivergedCloneSibling),
490            64 => Some(Self::AddedDependency),
491            65 => Some(Self::DuplicateExportAlias),
492            66 => Some(Self::UnlistedBinary),
493            67 => Some(Self::UnusedNamespaceMember),
494            68 => Some(Self::SharedState),
495            69 => Some(Self::ConstantParameter),
496            70 => Some(Self::UnusedProtectedClassMember),
497            71 => Some(Self::NamespaceEscape),
498            72 => Some(Self::TestOnlyExport),
499            _ => None,
500        }
501    }
502}
503
504/// One scoped rule-pack policy suppression target.
505#[derive(Debug, Clone, PartialEq, Eq, Hash)]
506pub struct PolicyRuleSuppression {
507    /// Rule-pack name.
508    pub pack: String,
509    /// Rule id within the pack.
510    pub rule_id: String,
511}
512
513impl PolicyRuleSuppression {
514    /// Build a scoped policy suppression target.
515    #[must_use]
516    pub fn new(pack: impl Into<String>, rule_id: impl Into<String>) -> Self {
517        Self {
518            pack: pack.into(),
519            rule_id: rule_id.into(),
520        }
521    }
522
523    /// Canonical suppression token.
524    #[must_use]
525    pub fn token(&self) -> String {
526        format!("policy-violation:{}/{}", self.pack, self.rule_id)
527    }
528}
529
530/// A specific suppression target parsed from a comment token.
531#[derive(Debug, Clone, PartialEq, Eq)]
532pub enum SuppressionTarget {
533    /// A regular issue-kind token such as `unused-export` or bare
534    /// `policy-violation`.
535    Issue(IssueKind),
536    /// A scoped rule-pack policy token such as
537    /// `policy-violation:team-policy/no-child-process`.
538    PolicyRule(PolicyRuleSuppression),
539}
540
541impl SuppressionTarget {
542    /// Return the regular issue kind when this target is a bare issue-kind
543    /// token.
544    #[must_use]
545    pub const fn issue_kind(&self) -> Option<IssueKind> {
546        match self {
547            Self::Issue(kind) => Some(*kind),
548            Self::PolicyRule(_) => None,
549        }
550    }
551
552    /// Canonical suppression token for output and active-suppression capture.
553    #[must_use]
554    pub fn token(&self) -> String {
555        match self {
556            Self::Issue(kind) => issue_kind_to_kebab(*kind).to_owned(),
557            Self::PolicyRule(rule) => rule.token(),
558        }
559    }
560}
561
562/// Convert an [`IssueKind`] to its canonical suppression token.
563#[must_use]
564pub fn issue_kind_to_kebab(kind: IssueKind) -> &'static str {
565    let Some(meta) = crate::issue_meta::issue_meta_by_kind(kind) else {
566        unreachable!("IssueKind {kind:?} has no metadata row");
567    };
568    meta.suppress_token.unwrap_or(meta.code)
569}
570
571/// Parse a suppression token into a structured target.
572#[must_use]
573pub fn parse_suppression_target(token: &str) -> Option<SuppressionTarget> {
574    parse_policy_rule_suppression_token(token)
575        .map(SuppressionTarget::PolicyRule)
576        .or_else(|| IssueKind::parse(token).map(SuppressionTarget::Issue))
577}
578
579/// Parse canonical scoped policy suppression tokens.
580///
581/// The plural prefix is accepted for consistency with the bare legacy alias,
582/// but output always uses singular `policy-violation:`.
583#[must_use]
584pub fn parse_policy_rule_suppression_token(token: &str) -> Option<PolicyRuleSuppression> {
585    let identity = token
586        .strip_prefix("policy-violation:")
587        .or_else(|| token.strip_prefix("policy-violations:"))?;
588    let (pack, rule_id) = identity.split_once('/')?;
589    if rule_id.contains('/') {
590        return None;
591    }
592    if !is_valid_policy_identifier(pack) || !is_valid_policy_identifier(rule_id) {
593        return None;
594    }
595    Some(PolicyRuleSuppression::new(pack, rule_id))
596}
597
598/// Whether a rule-pack name or rule id can be used inside
599/// `policy-violation:<pack>/<rule-id>` without escaping.
600#[must_use]
601pub fn is_valid_policy_identifier(value: &str) -> bool {
602    !value.is_empty()
603        && value
604            .bytes()
605            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
606}
607
608/// A suppression directive parsed from a source comment.
609///
610/// # Examples
611///
612/// ```
613/// use fallow_types::suppress::{Suppression, IssueKind};
614///
615/// // File-wide suppression (line 0, no specific kind)
616/// let file_wide = Suppression::all(0, 1);
617/// assert_eq!(file_wide.line, 0);
618///
619/// // Line-specific suppression for unused exports
620/// let line_suppress = Suppression::issue(42, 41, IssueKind::UnusedExport);
621/// assert_eq!(line_suppress.issue_kind_target(), Some(IssueKind::UnusedExport));
622/// ```
623#[derive(Debug, Clone)]
624pub struct Suppression {
625    /// 1-based line this suppression applies to. 0 = file-wide suppression.
626    /// For a range, the first line inside the range.
627    pub line: u32,
628    /// 1-based line where the suppression comment itself appears.
629    /// For `fallow-ignore-next-line`, this is `line - 1`.
630    /// For `fallow-ignore-file`, this is the actual line of the comment in the source.
631    pub comment_line: u32,
632    /// None = suppress all issue kinds on this line or file.
633    pub target: Option<SuppressionTarget>,
634    /// Human-authored reason after `--`, when present.
635    pub reason: Option<String>,
636    /// What the suppression covers: the file, one line, or a range of lines.
637    pub scope: SuppressionScope,
638}
639
640/// What one suppression covers.
641#[derive(Debug, Clone, Copy, PartialEq, Eq)]
642pub enum SuppressionScope {
643    /// A `fallow-ignore-file` marker. [`Suppression::line`] is 0.
644    File,
645    /// A `fallow-ignore-next-line` marker for [`Suppression::line`].
646    Line,
647    /// A `fallow-ignore-start` / `fallow-ignore-end` pair. The range covers
648    /// the lines from [`Suppression::line`] up to, but not including,
649    /// `end_line`. Only clone detection applies a range: the line and file
650    /// predicates of [`Suppression`] never match a range entry.
651    Range {
652        /// 1-based line of the `fallow-ignore-end` comment.
653        end_line: u32,
654    },
655}
656
657impl SuppressionScope {
658    /// The file or line scope that a plain marker for `line` has.
659    #[must_use]
660    pub const fn for_line(line: u32) -> Self {
661        if line == 0 { Self::File } else { Self::Line }
662    }
663}
664
665impl Suppression {
666    /// Build a blanket suppression.
667    #[must_use]
668    pub const fn all(line: u32, comment_line: u32) -> Self {
669        Self {
670            line,
671            comment_line,
672            target: None,
673            reason: None,
674            scope: SuppressionScope::for_line(line),
675        }
676    }
677
678    /// Build a regular issue-kind suppression.
679    #[must_use]
680    pub const fn issue(line: u32, comment_line: u32, kind: IssueKind) -> Self {
681        Self {
682            line,
683            comment_line,
684            target: Some(SuppressionTarget::Issue(kind)),
685            reason: None,
686            scope: SuppressionScope::for_line(line),
687        }
688    }
689
690    /// Build a range suppression for one issue kind.
691    ///
692    /// `first_line` is the first line inside the range, `comment_line` the
693    /// line of the `fallow-ignore-start` comment, and `end_line` the line of
694    /// the `fallow-ignore-end` comment.
695    #[must_use]
696    pub const fn range(first_line: u32, comment_line: u32, end_line: u32, kind: IssueKind) -> Self {
697        Self {
698            line: first_line,
699            comment_line,
700            target: Some(SuppressionTarget::Issue(kind)),
701            reason: None,
702            scope: SuppressionScope::Range { end_line },
703        }
704    }
705
706    /// The `fallow-ignore-end` line when this suppression is a range.
707    #[must_use]
708    pub const fn range_end_line(&self) -> Option<u32> {
709        match self.scope {
710            SuppressionScope::Range { end_line } => Some(end_line),
711            SuppressionScope::File | SuppressionScope::Line => None,
712        }
713    }
714
715    /// Whether this suppression is a range that covers `line`.
716    #[must_use]
717    pub const fn range_covers_line(&self, line: u32) -> bool {
718        match self.scope {
719            SuppressionScope::Range { end_line } => line >= self.line && line < end_line,
720            SuppressionScope::File | SuppressionScope::Line => false,
721        }
722    }
723
724    /// Build a scoped rule-pack policy suppression.
725    #[must_use]
726    pub fn policy_rule(
727        line: u32,
728        comment_line: u32,
729        pack: impl Into<String>,
730        rule_id: impl Into<String>,
731    ) -> Self {
732        Self {
733            line,
734            comment_line,
735            target: Some(SuppressionTarget::PolicyRule(PolicyRuleSuppression::new(
736                pack, rule_id,
737            ))),
738            reason: None,
739            scope: SuppressionScope::for_line(line),
740        }
741    }
742
743    /// Return a copy with a parsed suppression reason attached.
744    #[must_use]
745    pub fn with_reason(mut self, reason: Option<String>) -> Self {
746        self.reason = reason;
747        self
748    }
749
750    /// The bare issue kind if this suppression targets one.
751    #[must_use]
752    pub const fn issue_kind_target(&self) -> Option<IssueKind> {
753        match &self.target {
754            Some(SuppressionTarget::Issue(kind)) => Some(*kind),
755            Some(SuppressionTarget::PolicyRule(_)) | None => None,
756        }
757    }
758
759    /// The scoped policy target if this suppression targets one rule-pack rule.
760    #[must_use]
761    pub const fn policy_rule_target(&self) -> Option<&PolicyRuleSuppression> {
762        match &self.target {
763            Some(SuppressionTarget::PolicyRule(rule)) => Some(rule),
764            Some(SuppressionTarget::Issue(_)) | None => None,
765        }
766    }
767
768    /// Canonical token for this suppression, or `None` for blanket comments.
769    #[must_use]
770    pub fn target_token(&self) -> Option<String> {
771        self.target.as_ref().map(SuppressionTarget::token)
772    }
773
774    /// Whether the comment applies to `line`. A range never applies here.
775    #[must_use]
776    pub const fn applies_to_line(&self, line: u32) -> bool {
777        match self.scope {
778            SuppressionScope::File => true,
779            SuppressionScope::Line => self.line == line,
780            SuppressionScope::Range { .. } => false,
781        }
782    }
783
784    /// Whether this suppression covers a regular issue kind on a line.
785    ///
786    /// Scoped policy-rule targets intentionally do not match this generic
787    /// predicate. Policy detection uses [`Self::matches_policy_rule`] so the
788    /// exact pack and rule id are available.
789    #[must_use]
790    pub fn matches_issue_kind(&self, line: u32, kind: IssueKind) -> bool {
791        self.applies_to_line(line)
792            && match &self.target {
793                None => true,
794                Some(SuppressionTarget::Issue(target_kind)) => *target_kind == kind,
795                Some(SuppressionTarget::PolicyRule(_)) => false,
796            }
797    }
798
799    /// Whether this suppression covers a policy finding on a line.
800    #[must_use]
801    pub fn matches_policy_rule(&self, line: u32, pack: &str, rule_id: &str) -> bool {
802        self.applies_to_line(line)
803            && match &self.target {
804                None | Some(SuppressionTarget::Issue(IssueKind::PolicyViolation)) => true,
805                Some(SuppressionTarget::Issue(_)) => false,
806                Some(SuppressionTarget::PolicyRule(target)) => {
807                    target.pack == pack && target.rule_id == rule_id
808                }
809            }
810    }
811}
812
813/// Check if a specific issue at a given line should be suppressed.
814#[must_use]
815pub fn is_suppressed(suppressions: &[Suppression], line: u32, kind: IssueKind) -> bool {
816    suppressions
817        .iter()
818        .any(|suppression| suppression.matches_issue_kind(line, kind))
819}
820
821/// Check if the entire file is suppressed for issue types that do not have line numbers.
822#[must_use]
823pub fn is_file_suppressed(suppressions: &[Suppression], kind: IssueKind) -> bool {
824    suppressions.iter().any(|suppression| {
825        suppression.scope == SuppressionScope::File && suppression.matches_issue_kind(0, kind)
826    })
827}
828
829/// What is wrong with one `fallow-ignore-start` or `fallow-ignore-end`
830/// marker. A marker with a problem has no effect.
831#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
832#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
833#[serde(rename_all = "snake_case")]
834pub enum RangeMarkerProblemKind {
835    /// A `fallow-ignore-start` with no `fallow-ignore-end` after it.
836    UnclosedStart,
837    /// A `fallow-ignore-end` with no open `fallow-ignore-start`.
838    UnmatchedEnd,
839    /// A `fallow-ignore-start` inside an open range. The outer range applies.
840    NestedStart,
841    /// A range marker without an issue kind. A range needs
842    /// `code-duplication`.
843    MissingKind,
844    /// A range marker names an issue kind other than `code-duplication`.
845    /// The `code-duplication` part of the same marker still applies.
846    UnsupportedKind,
847    /// A range marker shares its line with code. A range marker must be on
848    /// its own line.
849    NotOwnLine,
850}
851
852impl RangeMarkerProblemKind {
853    /// Stable one-byte code for cache storage.
854    #[must_use]
855    pub const fn to_code(self) -> u8 {
856        match self {
857            Self::UnclosedStart => 1,
858            Self::UnmatchedEnd => 2,
859            Self::NestedStart => 3,
860            Self::MissingKind => 4,
861            Self::UnsupportedKind => 5,
862            Self::NotOwnLine => 6,
863        }
864    }
865
866    /// Read a code that [`Self::to_code`] wrote.
867    #[must_use]
868    pub const fn from_code(code: u8) -> Option<Self> {
869        match code {
870            1 => Some(Self::UnclosedStart),
871            2 => Some(Self::UnmatchedEnd),
872            3 => Some(Self::NestedStart),
873            4 => Some(Self::MissingKind),
874            5 => Some(Self::UnsupportedKind),
875            6 => Some(Self::NotOwnLine),
876            _ => None,
877        }
878    }
879
880    /// One-sentence description for human output.
881    #[must_use]
882    pub const fn description(self) -> &'static str {
883        match self {
884            Self::UnclosedStart => {
885                "fallow-ignore-start has no fallow-ignore-end, so it suppresses nothing"
886            }
887            Self::UnmatchedEnd => {
888                "fallow-ignore-end has no fallow-ignore-start before it (each range marker must be on its own line)"
889            }
890            Self::NestedStart => {
891                "fallow-ignore-start is inside an open range; the outer range applies"
892            }
893            Self::MissingKind => {
894                "range markers need the code-duplication kind; this marker suppresses nothing"
895            }
896            Self::UnsupportedKind => {
897                "range markers support only code-duplication; this kind is not suppressed"
898            }
899            Self::NotOwnLine => {
900                "range marker shares its line with code, so it suppresses nothing; put it on its own line"
901            }
902        }
903    }
904}
905
906/// One range marker with a problem, at a line of one file.
907#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
908#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
909pub struct RangeMarkerProblem {
910    /// 1-based line of the marker comment.
911    pub line: u32,
912    /// What is wrong with the marker.
913    #[serde(rename = "problem")]
914    pub kind: RangeMarkerProblemKind,
915    /// The kind token that the range does not support. Present only for
916    /// `unsupported_kind`.
917    #[serde(default, skip_serializing_if = "Option::is_none")]
918    pub token: Option<String>,
919}
920
921/// A suppression token that did not parse to any known `IssueKind`.
922///
923/// Emitted alongside `Suppression` when a `// fallow-ignore-*` marker contains
924/// a typo or an obsolete issue-kind name. The known tokens on the same marker
925/// are recorded as normal `Suppression` entries; this struct preserves the
926/// unknown token so the downstream `find_stale` pass can surface it as a
927/// `StaleSuppression` finding with `kind_known: false`. Without this, the
928/// entire suppression line would be discarded silently. See issue #449.
929#[derive(Debug, Clone)]
930pub struct UnknownSuppressionKind {
931    /// 1-based line where the suppression comment itself appears.
932    pub comment_line: u32,
933    /// Whether the marker was `fallow-ignore-file` (`true`) or
934    /// `fallow-ignore-next-line` (`false`).
935    pub is_file_level: bool,
936    /// The verbatim token from the marker that did not parse.
937    pub token: String,
938    /// Human-authored reason after `--`, when present.
939    pub reason: Option<String>,
940}
941
942/// Find the closest known issue-kind name to `input` when it is plausibly a typo.
943///
944/// Applies the policy of [`crate::levenshtein::closest_match`].
945#[must_use]
946pub fn closest_known_kind_name(input: &str) -> Option<&'static str> {
947    crate::levenshtein::closest_match(input, KNOWN_ISSUE_KIND_NAMES.iter().copied())
948}
949
950const _: () = assert!(std::mem::size_of::<IssueKind>() == 1);
951
952#[cfg(test)]
953mod tests {
954    use super::*;
955
956    #[test]
957    fn issue_kind_parse_accepts_registry_codes_and_aliases() {
958        for meta in crate::issue_meta::ISSUE_KIND_META
959            .iter()
960            .filter(|meta| meta.kind.is_some())
961        {
962            let expected = meta.kind;
963            assert_eq!(
964                IssueKind::parse(meta.code),
965                expected,
966                "canonical registry token {} must parse",
967                meta.code
968            );
969            for alias in meta.aliases {
970                assert_eq!(
971                    IssueKind::parse(alias),
972                    expected,
973                    "registry alias {alias} must parse as {}",
974                    meta.code
975                );
976            }
977        }
978    }
979
980    #[test]
981    fn issue_kind_parse_accepts_registry_suppression_tokens() {
982        for meta in crate::issue_meta::ISSUE_KIND_META {
983            let (Some(kind), Some(token)) = (meta.kind, meta.suppress_token) else {
984                continue;
985            };
986            assert_eq!(
987                IssueKind::parse(token),
988                Some(kind),
989                "registry suppression token {token} must parse as {}",
990                meta.code
991            );
992        }
993    }
994
995    #[test]
996    fn issue_kind_parse_accepts_diff_risk_tokens() {
997        let cases = [
998            ("weakened-tests", IssueKind::WeakenedTests),
999            ("added-suppression", IssueKind::AddedSuppression),
1000            ("test-only-branch", IssueKind::TestOnlyBranch),
1001            ("diverged-clone-sibling", IssueKind::DivergedCloneSibling),
1002            ("added-dependency", IssueKind::AddedDependency),
1003        ];
1004        for (token, kind) in cases {
1005            assert_eq!(IssueKind::parse(token), Some(kind), "{token}");
1006            assert_eq!(issue_kind_to_kebab(kind), token);
1007        }
1008    }
1009
1010    #[test]
1011    fn issue_kind_from_str_unknown() {
1012        assert_eq!(IssueKind::parse("foo"), None);
1013        assert_eq!(IssueKind::parse(""), None);
1014    }
1015
1016    #[test]
1017    fn issue_kind_from_str_near_misses() {
1018        assert_eq!(IssueKind::parse("Unused-File"), None);
1019        assert_eq!(IssueKind::parse("UNUSED-EXPORT"), None);
1020        assert_eq!(IssueKind::parse("unused_file"), None);
1021        assert_eq!(IssueKind::parse("unused-files"), None);
1022    }
1023
1024    #[test]
1025    fn discriminant_out_of_range() {
1026        // Pin exact discriminants so an inserted or reordered variant that
1027        // shifts wire values is caught. `ALL` is not discriminant-ordered, so
1028        // the mapping is spelled out explicitly, and the row count is checked
1029        // against `ALL` below so a new variant cannot be added without a row.
1030        let cases: &[(u8, IssueKind)] = &[
1031            (1, IssueKind::UnusedFile),
1032            (2, IssueKind::UnusedExport),
1033            (3, IssueKind::UnusedType),
1034            (4, IssueKind::PrivateTypeLeak),
1035            (5, IssueKind::UnusedDependency),
1036            (6, IssueKind::UnusedDevDependency),
1037            (7, IssueKind::UnusedEnumMember),
1038            (8, IssueKind::UnusedClassMember),
1039            (9, IssueKind::UnresolvedImport),
1040            (10, IssueKind::UnlistedDependency),
1041            (11, IssueKind::DuplicateExport),
1042            (12, IssueKind::CodeDuplication),
1043            (13, IssueKind::CircularDependency),
1044            (14, IssueKind::TypeOnlyDependency),
1045            (15, IssueKind::TestOnlyDependency),
1046            (16, IssueKind::BoundaryViolation),
1047            (17, IssueKind::CoverageGaps),
1048            (18, IssueKind::FeatureFlag),
1049            (19, IssueKind::Complexity),
1050            (20, IssueKind::StaleSuppression),
1051            (21, IssueKind::PnpmCatalogEntry),
1052            (22, IssueKind::UnresolvedCatalogReference),
1053            (23, IssueKind::UnusedDependencyOverride),
1054            (24, IssueKind::MisconfiguredDependencyOverride),
1055            (25, IssueKind::EmptyCatalogGroup),
1056            (26, IssueKind::ReExportCycle),
1057            (27, IssueKind::SecurityClientServerLeak),
1058            (28, IssueKind::SecuritySink),
1059            (29, IssueKind::PolicyViolation),
1060            (30, IssueKind::InvalidClientExport),
1061            (31, IssueKind::MixedClientServerBarrel),
1062            (32, IssueKind::MisplacedDirective),
1063            (33, IssueKind::UnusedStoreMember),
1064            (34, IssueKind::UnprovidedInject),
1065            (35, IssueKind::RouteCollision),
1066            (36, IssueKind::DynamicSegmentNameConflict),
1067            (37, IssueKind::UnrenderedComponent),
1068            (38, IssueKind::UnusedComponentProp),
1069            (39, IssueKind::UnusedComponentEmit),
1070            (40, IssueKind::UnusedServerAction),
1071            (41, IssueKind::UnusedLoadDataKey),
1072            (42, IssueKind::PropDrilling),
1073            (43, IssueKind::ThinWrapper),
1074            (44, IssueKind::DuplicatePropShape),
1075            (45, IssueKind::UnusedComponentInput),
1076            (46, IssueKind::UnusedComponentOutput),
1077            (47, IssueKind::UnusedSvelteEvent),
1078            (48, IssueKind::CssTokenDrift),
1079            (49, IssueKind::CssDuplicateBlock),
1080            (50, IssueKind::CssSelectorComplexity),
1081            (51, IssueKind::CssDeadSurface),
1082            (52, IssueKind::CssBrokenReference),
1083            (53, IssueKind::DevDependencyInProduction),
1084            (54, IssueKind::DeprecatedExportInUse),
1085            (55, IssueKind::PackageCycle),
1086            (56, IssueKind::AbsentComponentProp),
1087            (57, IssueKind::UnusedEffectLayer),
1088            (58, IssueKind::UnusedTaggedError),
1089            (59, IssueKind::UnproducedCatchTag),
1090            (60, IssueKind::WeakenedTests),
1091            (61, IssueKind::AddedSuppression),
1092            (62, IssueKind::TestOnlyBranch),
1093            (63, IssueKind::DivergedCloneSibling),
1094            (64, IssueKind::AddedDependency),
1095            (65, IssueKind::DuplicateExportAlias),
1096            (66, IssueKind::UnlistedBinary),
1097            (67, IssueKind::UnusedNamespaceMember),
1098            (69, IssueKind::ConstantParameter),
1099            (70, IssueKind::UnusedProtectedClassMember),
1100            (71, IssueKind::NamespaceEscape),
1101            (72, IssueKind::TestOnlyExport),
1102        ];
1103        for &(discriminant, kind) in cases {
1104            assert_eq!(kind.to_discriminant(), discriminant, "{kind:?} drifted");
1105            assert_eq!(IssueKind::from_discriminant(discriminant), Some(kind));
1106        }
1107        assert_eq!(IssueKind::from_discriminant(0), None);
1108        let max_discriminant = IssueKind::ALL
1109            .iter()
1110            .map(|kind| kind.to_discriminant())
1111            .max()
1112            .expect("IssueKind::ALL should not be empty");
1113        assert_eq!(IssueKind::from_discriminant(max_discriminant + 1), None);
1114        assert_eq!(IssueKind::from_discriminant(u8::MAX), None);
1115    }
1116
1117    #[test]
1118    fn discriminant_roundtrip() {
1119        for &kind in IssueKind::ALL {
1120            assert_eq!(
1121                IssueKind::from_discriminant(kind.to_discriminant()),
1122                Some(kind)
1123            );
1124        }
1125        assert_eq!(IssueKind::from_discriminant(0), None);
1126        let max_discriminant = IssueKind::ALL
1127            .iter()
1128            .map(|kind| kind.to_discriminant())
1129            .max()
1130            .expect("IssueKind::ALL should not be empty");
1131        assert_eq!(IssueKind::from_discriminant(max_discriminant + 1), None);
1132    }
1133
1134    #[test]
1135    fn discriminant_values_are_unique() {
1136        let discriminants: Vec<u8> = IssueKind::ALL
1137            .iter()
1138            .map(|kind| kind.to_discriminant())
1139            .collect();
1140        let mut sorted = discriminants.clone();
1141        sorted.sort_unstable();
1142        sorted.dedup();
1143        assert_eq!(
1144            discriminants.len(),
1145            sorted.len(),
1146            "discriminant values must be unique"
1147        );
1148    }
1149
1150    #[test]
1151    fn discriminant_starts_at_one() {
1152        assert_eq!(IssueKind::UnusedFile.to_discriminant(), 1);
1153    }
1154
1155    #[test]
1156    fn issue_kind_to_kebab_uses_registry_suppression_token() {
1157        for &kind in IssueKind::ALL {
1158            let meta = crate::issue_meta::issue_meta_by_kind(kind)
1159                .unwrap_or_else(|| panic!("IssueKind {kind:?} has no metadata row"));
1160            let token = issue_kind_to_kebab(kind);
1161            assert_eq!(token, meta.suppress_token.unwrap_or(meta.code));
1162            assert_eq!(IssueKind::parse(token), Some(kind));
1163        }
1164    }
1165
1166    #[test]
1167    fn suppression_line_zero_is_file_wide() {
1168        let s = Suppression::all(0, 1);
1169        assert_eq!(s.line, 0);
1170        assert!(s.issue_kind_target().is_none());
1171    }
1172
1173    #[test]
1174    fn suppression_with_specific_kind_and_line() {
1175        let s = Suppression::issue(42, 41, IssueKind::UnusedExport);
1176        assert_eq!(s.line, 42);
1177        assert_eq!(s.comment_line, 41);
1178        assert_eq!(s.issue_kind_target(), Some(IssueKind::UnusedExport));
1179    }
1180
1181    #[test]
1182    fn suppression_predicates_match_lines_and_file_wide_markers() {
1183        let suppressions = vec![
1184            Suppression::issue(42, 41, IssueKind::UnusedExport),
1185            Suppression::all(0, 1),
1186        ];
1187
1188        assert!(is_suppressed(&suppressions, 42, IssueKind::UnusedExport));
1189        assert!(is_suppressed(&suppressions, 10, IssueKind::UnusedType));
1190        assert!(is_file_suppressed(&suppressions, IssueKind::UnusedFile));
1191    }
1192
1193    #[test]
1194    fn parses_scoped_policy_suppression_token() {
1195        let target =
1196            parse_policy_rule_suppression_token("policy-violation:team-policy/no-child-process")
1197                .expect("scoped token should parse");
1198        assert_eq!(target.pack, "team-policy");
1199        assert_eq!(target.rule_id, "no-child-process");
1200        assert_eq!(
1201            target.token(),
1202            "policy-violation:team-policy/no-child-process"
1203        );
1204    }
1205
1206    #[test]
1207    fn rejects_malformed_scoped_policy_suppression_tokens() {
1208        for token in [
1209            "policy-violation:",
1210            "policy-violation:team-policy",
1211            "policy-violation:/no-child-process",
1212            "policy-violation:team-policy/",
1213            "policy-violation:team-policy/no/child-process",
1214            "policy-violation:team policy/no-child-process",
1215            "policy-violation:team-policy/no:child-process",
1216        ] {
1217            assert!(
1218                parse_policy_rule_suppression_token(token).is_none(),
1219                "{token} should be rejected"
1220            );
1221        }
1222    }
1223
1224    #[test]
1225    fn scoped_policy_suppression_matches_exact_policy_rule_only() {
1226        let suppression = Suppression::policy_rule(7, 6, "team-policy", "no-child-process");
1227        assert!(suppression.matches_policy_rule(7, "team-policy", "no-child-process"));
1228        assert!(!suppression.matches_policy_rule(7, "team-policy", "no-fs"));
1229        assert!(!suppression.matches_policy_rule(8, "team-policy", "no-child-process"));
1230        assert!(!suppression.matches_issue_kind(7, IssueKind::PolicyViolation));
1231    }
1232
1233    #[test]
1234    fn known_issue_kind_names_parses_each_entry() {
1235        for &name in KNOWN_ISSUE_KIND_NAMES.iter() {
1236            assert!(
1237                IssueKind::parse(name).is_some(),
1238                "KNOWN_ISSUE_KIND_NAMES contains '{name}' but IssueKind::parse rejects it"
1239            );
1240        }
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_finds_near_misses() {
1249        assert_eq!(
1250            closest_known_kind_name("unused-exports"),
1251            Some("unused-export")
1252        );
1253        assert_eq!(closest_known_kind_name("unused-files"), Some("unused-file"));
1254        assert_eq!(closest_known_kind_name("complxity"), Some("complexity"));
1255    }
1256
1257    #[test]
1258    #[cfg_attr(
1259        miri,
1260        ignore = "too slow under Miri: edit distance over every issue kind in safe code"
1261    )]
1262    fn closest_known_kind_name_rejects_novel_strings() {
1263        assert_eq!(closest_known_kind_name("xyzzy"), None);
1264        assert_eq!(closest_known_kind_name("foo"), None);
1265        assert_eq!(closest_known_kind_name(""), None);
1266    }
1267
1268    #[test]
1269    #[cfg_attr(
1270        miri,
1271        ignore = "too slow under Miri: edit distance over every issue kind in safe code"
1272    )]
1273    fn closest_known_kind_name_skips_exact_match() {
1274        assert_eq!(closest_known_kind_name("unused-export"), None);
1275    }
1276}