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