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