Skip to main content

fallow_output/
dead_code_sarif.rs

1//! Shared dead-code SARIF output assembly.
2
3use std::path::Path;
4
5use crate::{
6    SarifDocumentInput, SarifFindingFields as SarifFields,
7    SarifSourceSnippetCache as SourceSnippetCache, append_sarif_findings as push_sarif_results,
8    build_sarif_document, build_sarif_result_with_snippet as sarif_result_with_snippet,
9    issue_output_contracts, normalize_uri, sarif::sarif_utf16_column,
10};
11use fallow_config::{RulesConfig, Severity};
12#[path = "dead_code_sarif_members.rs"]
13mod members;
14use fallow_types::{
15    issue_meta::issue_sarif_rule_description,
16    output_dead_code::*,
17    results::{
18        AnalysisResults, BoundaryCallViolation, BoundaryCoverageViolation, BoundaryViolation,
19        CircularDependency, DeprecatedExportInUse, DevDependencyInProduction, DuplicateExportAlias,
20        DuplicatePropShape, DynamicSegmentNameConflict, InvalidClientExport, MisplacedDirective,
21        MixedClientServerBarrel, PolicyViolation, PolicyViolationSeverity, PrivateTypeLeak,
22        PropDrillingChain, RouteCollision, StaleSuppression, TestOnlyDependency, ThinWrapper,
23        TypeOnlyDependency, UnproducedCatchTag, UnprovidedInject, UnrenderedComponent,
24        UnresolvedImport, UnusedComponentEmit, UnusedComponentInput, UnusedComponentOutput,
25        UnusedComponentProp, UnusedDependency, UnusedEffectLayer, UnusedExport, UnusedFile,
26        UnusedMember, UnusedServerAction, UnusedSvelteEvent, UnusedTaggedError,
27    },
28};
29use members::push_member_sarif_results;
30
31#[path = "dead_code_sarif_component_framework.rs"]
32mod component_framework;
33use component_framework::push_component_framework_sarif_results;
34#[path = "dead_code_sarif_caller_review.rs"]
35mod caller_review;
36use caller_review::{
37    push_absent_component_prop_sarif_results, push_constant_parameter_sarif_results,
38};
39
40fn relative_uri(path: &Path, root: &Path) -> String {
41    normalize_uri(
42        &path
43            .strip_prefix(root)
44            .unwrap_or(path)
45            .display()
46            .to_string(),
47    )
48}
49
50/// Read-only context threaded through the SARIF result builders: the
51/// analysis results, project root, and rule severities. Bundled so the
52/// `push_*_sarif_results` family shares one parameter instead of three.
53#[derive(Clone, Copy)]
54struct SarifCtx<'a> {
55    results: &'a AnalysisResults,
56    root: &'a Path,
57    rules: &'a RulesConfig,
58}
59
60/// The SARIF level for one finding: its saved severity when the finding
61/// carries one, otherwise the configured rule severity (a saved report from an
62/// older version has no saved severity).
63///
64/// A saved finding exists, so its rule was on when it was reported. When the
65/// config at render time sets the rule `off`, the level is `warning`.
66fn finding_level(finding: &impl GatedFinding, rule: Severity) -> &'static str {
67    match finding.effective_severity() {
68        Some(EffectiveSeverity::Error) => "error",
69        Some(EffectiveSeverity::Warn) => "warning",
70        None => match rule {
71            Severity::Error => "error",
72            Severity::Warn | Severity::Off => "warning",
73        },
74    }
75}
76
77fn configured_sarif_level(s: Severity) -> &'static str {
78    match s {
79        Severity::Error => "error",
80        Severity::Warn => "warning",
81        Severity::Off => "none",
82    }
83}
84
85/// Extract SARIF fields for an unused export or type export.
86fn sarif_export_fields(
87    export: &UnusedExport,
88    root: &Path,
89    rule_id: &'static str,
90    level: &'static str,
91    kind: &str,
92    re_kind: &str,
93) -> SarifFields {
94    let label = if export.is_re_export { re_kind } else { kind };
95    SarifFields {
96        rule_id,
97        level,
98        message: format!(
99            "{} '{}' is never imported by other modules",
100            label, export.export_name
101        ),
102        uri: relative_uri(&export.path, root),
103        region: Some((export.line, export.col + 1)),
104        source_path: Some(export.path.clone()),
105        properties: if export.is_re_export {
106            Some(serde_json::json!({ "is_re_export": true }))
107        } else {
108            None
109        },
110    }
111}
112
113fn sarif_private_type_leak_fields(
114    leak: &PrivateTypeLeak,
115    root: &Path,
116    level: &'static str,
117) -> SarifFields {
118    SarifFields {
119        rule_id: "fallow/private-type-leak",
120        level,
121        message: format!(
122            "Export '{}' references private type '{}'",
123            leak.export_name, leak.type_name
124        ),
125        uri: relative_uri(&leak.path, root),
126        region: Some((leak.line, leak.col + 1)),
127        source_path: Some(leak.path.clone()),
128        properties: None,
129    }
130}
131
132fn sarif_deprecated_export_fields(
133    export: &DeprecatedExportInUse,
134    root: &Path,
135    level: &'static str,
136) -> SarifFields {
137    SarifFields {
138        rule_id: "fallow/deprecated-export-in-use",
139        level,
140        message: export.description(),
141        uri: relative_uri(&export.path, root),
142        region: Some((export.line, export.col + 1)),
143        source_path: Some(export.path.clone()),
144        properties: Some(serde_json::json!({
145            "consumer_count": export.consumer_count,
146            "public_api": export.public_api,
147        })),
148    }
149}
150
151/// 1-based column of the `"<name>"` key inside the manifest line a dependency
152/// finding points at, falling back to 1 when the line cannot be read.
153///
154/// Every dependency declared on one line otherwise reports the same location,
155/// and a SARIF fingerprint is rule id plus location plus source snippet: a
156/// compact `package.json` collapsed all of its unused dependencies into one
157/// GitHub code scanning alert.
158fn manifest_key_column(
159    snippets: &mut SourceSnippetCache,
160    path: &Path,
161    line: u32,
162    name: &str,
163) -> u32 {
164    snippets
165        .line(path, line)
166        .and_then(|text| text.find(&format!("\"{name}\"")))
167        .and_then(|offset| u32::try_from(offset).ok())
168        .map_or(1, |offset| offset.saturating_add(1))
169}
170
171/// The manifest coordinates `manifest_key_column` needs from a dependency.
172fn dep_key(dep: &UnusedDependency) -> (&Path, u32, &str) {
173    (dep.path.as_path(), dep.line, dep.package_name.as_str())
174}
175
176/// Resolve one manifest column per finding up front, so the result closure that
177/// needs them does not have to borrow the snippet cache it reads.
178fn manifest_key_columns<'a, T: 'a>(
179    findings: &'a [T],
180    snippets: &mut SourceSnippetCache,
181    key_of: impl Fn(&'a T) -> (&'a Path, u32, &'a str),
182) -> std::vec::IntoIter<u32> {
183    findings
184        .iter()
185        .map(|finding| {
186            let (path, line, name) = key_of(finding);
187            manifest_key_column(snippets, path, line, name)
188        })
189        .collect::<Vec<_>>()
190        .into_iter()
191}
192
193/// Extract SARIF fields for an unused dependency.
194fn sarif_dep_fields(
195    dep: &UnusedDependency,
196    root: &Path,
197    rule_id: &'static str,
198    level: &'static str,
199    section: &str,
200    col: u32,
201) -> SarifFields {
202    let join_workspaces = |paths: &[std::path::PathBuf]| {
203        paths
204            .iter()
205            .map(|path| relative_uri(path, root))
206            .collect::<Vec<_>>()
207            .join(", ")
208    };
209    let workspace_context = if !dep.used_in_workspaces.is_empty() {
210        format!(
211            "; imported in other workspaces: {}",
212            join_workspaces(&dep.used_in_workspaces)
213        )
214    } else if !dep.declared_and_imported_in.is_empty() {
215        format!(
216            "; declared and imported in other workspaces: {}",
217            join_workspaces(&dep.declared_and_imported_in)
218        )
219    } else {
220        String::new()
221    };
222    SarifFields {
223        rule_id,
224        level,
225        message: format!(
226            "Package '{}' is in {} but never imported{}",
227            dep.package_name, section, workspace_context
228        ),
229        uri: relative_uri(&dep.path, root),
230        region: if dep.line > 0 {
231            Some((dep.line, col))
232        } else {
233            None
234        },
235        source_path: (dep.line > 0).then(|| dep.path.clone()),
236        properties: None,
237    }
238}
239
240/// Extract SARIF fields for an unused enum or class member.
241fn sarif_member_fields(
242    member: &UnusedMember,
243    root: &Path,
244    rule_id: &'static str,
245    level: &'static str,
246    kind: &str,
247) -> SarifFields {
248    SarifFields {
249        rule_id,
250        level,
251        message: format!(
252            "{} member '{}.{}' is never referenced",
253            kind, member.parent_name, member.member_name
254        ),
255        uri: relative_uri(&member.path, root),
256        region: Some((member.line, member.col + 1)),
257        source_path: Some(member.path.clone()),
258        properties: None,
259    }
260}
261
262/// Append the degraded-parse caveat to a SARIF result message, so a reviewer
263/// reading an annotation in CI sees the same qualifier the JSON envelope and
264/// the human report carry. Byte-identical when the finding has no caveat.
265fn with_caveats(mut fields: SarifFields, caveats: &[ReachabilityCaveat]) -> SarifFields {
266    if let Some(labels) = caveat_labels(caveats) {
267        fields.message.push_str(" (caveat: ");
268        fields.message.push_str(&labels);
269        fields.message.push(')');
270    }
271    fields
272}
273
274fn sarif_unused_file_fields(file: &UnusedFile, root: &Path, level: &'static str) -> SarifFields {
275    SarifFields {
276        rule_id: "fallow/unused-file",
277        level,
278        message: "File is not reachable from any entry point".to_string(),
279        uri: relative_uri(&file.path, root),
280        region: None,
281        source_path: None,
282        properties: None,
283    }
284}
285
286fn sarif_type_only_dep_fields(
287    dep: &TypeOnlyDependency,
288    root: &Path,
289    level: &'static str,
290    col: u32,
291) -> SarifFields {
292    SarifFields {
293        rule_id: "fallow/type-only-dependency",
294        level,
295        message: format!(
296            "Package '{}' is only imported via type-only imports (consider moving to devDependencies)",
297            dep.package_name
298        ),
299        uri: relative_uri(&dep.path, root),
300        region: if dep.line > 0 {
301            Some((dep.line, col))
302        } else {
303            None
304        },
305        source_path: (dep.line > 0).then(|| dep.path.clone()),
306        properties: None,
307    }
308}
309
310fn sarif_test_only_dep_fields(
311    dep: &TestOnlyDependency,
312    root: &Path,
313    level: &'static str,
314    col: u32,
315) -> SarifFields {
316    SarifFields {
317        rule_id: "fallow/test-only-dependency",
318        level,
319        message: format!(
320            "Package '{}' is only imported by test files (consider moving to devDependencies)",
321            dep.package_name
322        ),
323        uri: relative_uri(&dep.path, root),
324        region: if dep.line > 0 {
325            Some((dep.line, col))
326        } else {
327            None
328        },
329        source_path: (dep.line > 0).then(|| dep.path.clone()),
330        properties: None,
331    }
332}
333
334fn sarif_dev_dep_in_prod_fields(
335    dep: &DevDependencyInProduction,
336    root: &Path,
337    level: &'static str,
338    col: u32,
339) -> SarifFields {
340    SarifFields {
341        rule_id: "fallow/dev-dependency-in-production",
342        level,
343        message: format!(
344            "devDependency '{}' is imported by production code at runtime (consider moving to dependencies)",
345            dep.package_name
346        ),
347        uri: relative_uri(&dep.path, root),
348        region: if dep.line > 0 {
349            Some((dep.line, col))
350        } else {
351            None
352        },
353        source_path: (dep.line > 0).then(|| dep.path.clone()),
354        properties: None,
355    }
356}
357
358fn sarif_unresolved_import_fields(
359    import: &UnresolvedImport,
360    root: &Path,
361    level: &'static str,
362) -> SarifFields {
363    SarifFields {
364        rule_id: "fallow/unresolved-import",
365        level,
366        message: format!("Import '{}' could not be resolved", import.specifier),
367        uri: relative_uri(&import.path, root),
368        region: Some((import.line, import.col + 1)),
369        source_path: Some(import.path.clone()),
370        properties: None,
371    }
372}
373
374fn sarif_circular_dep_fields(
375    cycle: &CircularDependency,
376    root: &Path,
377    level: &'static str,
378) -> SarifFields {
379    let chain: Vec<String> = cycle.files.iter().map(|p| relative_uri(p, root)).collect();
380    let mut display_chain = chain.clone();
381    if let Some(first) = chain.first() {
382        display_chain.push(first.clone());
383    }
384    let first_uri = chain.first().map_or_else(String::new, Clone::clone);
385    let first_path = cycle.files.first().cloned();
386    SarifFields {
387        rule_id: "fallow/circular-dependency",
388        level,
389        message: format!(
390            "Circular dependency{}: {}",
391            if cycle.is_cross_package {
392                " (cross-package)"
393            } else {
394                ""
395            },
396            display_chain.join(" \u{2192} ")
397        ),
398        uri: first_uri,
399        region: if cycle.line > 0 {
400            Some((cycle.line, cycle.col + 1))
401        } else {
402            None
403        },
404        source_path: (cycle.line > 0).then_some(first_path).flatten(),
405        properties: None,
406    }
407}
408
409fn sarif_re_export_cycle_fields(
410    cycle: &fallow_types::results::ReExportCycle,
411    root: &Path,
412    level: &'static str,
413) -> SarifFields {
414    let chain: Vec<String> = cycle.files.iter().map(|p| relative_uri(p, root)).collect();
415    let first_uri = chain.first().map_or_else(String::new, Clone::clone);
416    let first_path = cycle.files.first().cloned();
417    let kind_tag = match cycle.kind {
418        fallow_types::results::ReExportCycleKind::SelfLoop => " (self-loop)",
419        fallow_types::results::ReExportCycleKind::MultiNode => "",
420    };
421    SarifFields {
422        rule_id: "fallow/re-export-cycle",
423        level,
424        message: format!("Re-export cycle{}: {}", kind_tag, chain.join(" <-> ")),
425        uri: first_uri,
426        region: (cycle.line > 0).then_some((cycle.line, cycle.col + 1)),
427        source_path: first_path,
428        properties: None,
429    }
430}
431
432fn sarif_package_cycle_fields(
433    cycle: &fallow_types::results::PackageCycle,
434    root: &Path,
435    level: &'static str,
436) -> SarifFields {
437    let anchor = cycle.edges.first();
438    let note = if cycle.group_truncated {
439        format!(
440            " ({})",
441            fallow_types::results::PackageCycle::GROUP_TRUNCATED_NOTE
442        )
443    } else {
444        String::new()
445    };
446    let package_roots: Vec<String> = cycle
447        .package_roots
448        .iter()
449        .map(|package_root| relative_uri(package_root, root))
450        .collect();
451    SarifFields {
452        rule_id: "fallow/package-cycle",
453        level,
454        message: format!("Package cycle: {}{note}", cycle.chain(" \u{2192} ")),
455        uri: anchor.map_or_else(String::new, |edge| relative_uri(&edge.path, root)),
456        region: anchor.map(|edge| (edge.line, edge.col + 1)),
457        source_path: anchor.map(|edge| edge.path.clone()),
458        properties: Some(serde_json::json!({
459            "packages": cycle.packages,
460            "package_roots": package_roots,
461            "group_truncated": cycle.group_truncated,
462        })),
463    }
464}
465
466fn sarif_boundary_coverage_fields(
467    violation: &BoundaryCoverageViolation,
468    root: &Path,
469    level: &'static str,
470) -> SarifFields {
471    SarifFields {
472        rule_id: "fallow/boundary-coverage",
473        level,
474        message: "File does not match any configured architecture boundary zone".to_string(),
475        uri: relative_uri(&violation.path, root),
476        region: Some((violation.line, violation.col + 1)),
477        source_path: Some(violation.path.clone()),
478        properties: None,
479    }
480}
481
482fn sarif_boundary_call_fields(
483    violation: &BoundaryCallViolation,
484    root: &Path,
485    level: &'static str,
486) -> SarifFields {
487    SarifFields {
488        rule_id: "fallow/boundary-call-violation",
489        level,
490        message: format!(
491            "Call to `{}` matches forbidden pattern `{}` in zone '{}'",
492            violation.callee, violation.pattern, violation.zone
493        ),
494        uri: relative_uri(&violation.path, root),
495        region: Some((violation.line, violation.col + 1)),
496        source_path: Some(violation.path.clone()),
497        properties: None,
498    }
499}
500
501fn sarif_policy_violation_fields(violation: &PolicyViolation, root: &Path) -> SarifFields {
502    let level = match violation.severity {
503        PolicyViolationSeverity::Error => "error",
504        PolicyViolationSeverity::Warn => "warning",
505    };
506    let message = match &violation.message {
507        Some(message) => format!(
508            "Policy violation `{}/{}`: `{}` is banned. {message}",
509            violation.pack, violation.rule_id, violation.matched
510        ),
511        None => format!(
512            "Policy violation `{}/{}`: `{}` is banned",
513            violation.pack, violation.rule_id, violation.matched
514        ),
515    };
516    SarifFields {
517        rule_id: "fallow/policy-violation",
518        level,
519        message,
520        uri: relative_uri(&violation.path, root),
521        region: Some((violation.line, violation.col + 1)),
522        source_path: Some(violation.path.clone()),
523        // The SARIF rule id is the static `fallow/policy-violation`; the
524        // per-rule policy identity rides in properties so code-scanning
525        // consumers can group or filter per pack rule without parsing the
526        // message. Dynamic per-rule SARIF rule synthesis is a tracked
527        // follow-up shared with boundary zone rules.
528        properties: Some(serde_json::json!({
529            "policyRule": format!("{}/{}", violation.pack, violation.rule_id),
530        })),
531    }
532}
533
534fn sarif_invalid_client_export_fields(
535    export: &InvalidClientExport,
536    root: &Path,
537    level: &'static str,
538) -> SarifFields {
539    SarifFields {
540        rule_id: "fallow/invalid-client-export",
541        level,
542        message: format!(
543            "Export '{}' is not allowed in a \"{}\" file (Next.js server-only / route-config name)",
544            export.export_name, export.directive
545        ),
546        uri: relative_uri(&export.path, root),
547        region: Some((export.line, export.col + 1)),
548        source_path: Some(export.path.clone()),
549        properties: None,
550    }
551}
552
553fn sarif_mixed_client_server_barrel_fields(
554    barrel: &MixedClientServerBarrel,
555    root: &Path,
556    level: &'static str,
557) -> SarifFields {
558    SarifFields {
559        rule_id: "fallow/mixed-client-server-barrel",
560        level,
561        message: format!(
562            "Barrel re-exports both a \"use client\" module ('{}') and a server-only module ('{}'); one import drags the other's directive across the boundary",
563            barrel.client_origin, barrel.server_origin
564        ),
565        uri: relative_uri(&barrel.path, root),
566        region: Some((barrel.line, barrel.col + 1)),
567        source_path: Some(barrel.path.clone()),
568        properties: None,
569    }
570}
571
572fn sarif_misplaced_directive_fields(
573    directive_site: &MisplacedDirective,
574    root: &Path,
575    level: &'static str,
576) -> SarifFields {
577    SarifFields {
578        rule_id: "fallow/misplaced-directive",
579        level,
580        message: format!(
581            "Directive \"{}\" is not in the leading position, so the RSC bundler ignores it; move it to the top of the file",
582            directive_site.directive
583        ),
584        uri: relative_uri(&directive_site.path, root),
585        region: Some((directive_site.line, directive_site.col + 1)),
586        source_path: Some(directive_site.path.clone()),
587        properties: None,
588    }
589}
590
591fn sarif_unprovided_inject_fields(
592    inject: &UnprovidedInject,
593    root: &Path,
594    level: &'static str,
595) -> SarifFields {
596    SarifFields {
597        rule_id: "fallow/unprovided-inject",
598        level,
599        message: format!(
600            "inject(\"{}\") has no matching provide(\"{}\") in this project; at runtime it returns undefined; provide the key or remove this inject",
601            inject.key_name, inject.key_name
602        ),
603        uri: relative_uri(&inject.path, root),
604        region: Some((inject.line, inject.col + 1)),
605        source_path: Some(inject.path.clone()),
606        properties: None,
607    }
608}
609
610fn sarif_unrendered_component_fields(
611    component: &UnrenderedComponent,
612    root: &Path,
613    level: &'static str,
614) -> SarifFields {
615    SarifFields {
616        rule_id: "fallow/unrendered-component",
617        level,
618        message: format!(
619            "component \"{}\" is reachable but rendered nowhere in this project; render it somewhere or remove it",
620            component.component_name
621        ),
622        uri: relative_uri(&component.path, root),
623        region: Some((component.line, component.col + 1)),
624        source_path: Some(component.path.clone()),
625        properties: None,
626    }
627}
628
629fn sarif_unused_component_prop_fields(
630    prop: &UnusedComponentProp,
631    root: &Path,
632    level: &'static str,
633) -> SarifFields {
634    SarifFields {
635        rule_id: "fallow/unused-component-prop",
636        level,
637        message: format!(
638            "prop \"{}\" is declared but referenced nowhere inside component \"{}\"; remove it or use it",
639            prop.prop_name, prop.component_name
640        ),
641        uri: relative_uri(&prop.path, root),
642        region: Some((prop.line, prop.col + 1)),
643        source_path: Some(prop.path.clone()),
644        properties: None,
645    }
646}
647
648fn sarif_unused_component_emit_fields(
649    emit: &UnusedComponentEmit,
650    root: &Path,
651    level: &'static str,
652) -> SarifFields {
653    SarifFields {
654        rule_id: "fallow/unused-component-emit",
655        level,
656        message: format!(
657            "emit \"{}\" is declared but emitted nowhere inside component \"{}\"; remove it or emit it",
658            emit.emit_name, emit.component_name
659        ),
660        uri: relative_uri(&emit.path, root),
661        region: Some((emit.line, emit.col + 1)),
662        source_path: Some(emit.path.clone()),
663        properties: None,
664    }
665}
666
667fn sarif_unused_effect_layer_fields(
668    layer: &UnusedEffectLayer,
669    root: &Path,
670    level: &'static str,
671) -> SarifFields {
672    SarifFields {
673        rule_id: "fallow/unused-effect-layer",
674        level,
675        message: format!(
676            "layer \"{}\" is composed only into layers that nothing uses ({}); compose it into a live layer or remove it",
677            layer.name,
678            layer.dead_consumers.join(", ")
679        ),
680        uri: relative_uri(&layer.path, root),
681        region: Some((layer.line, layer.col + 1)),
682        source_path: Some(layer.path.clone()),
683        properties: Some(serde_json::json!({
684            "dead_consumers": layer.dead_consumers,
685        })),
686    }
687}
688
689fn sarif_duplicate_export_alias_fields(
690    alias: &DuplicateExportAlias,
691    root: &Path,
692    level: &'static str,
693) -> SarifFields {
694    SarifFields {
695        rule_id: "fallow/duplicate-export-alias",
696        level,
697        message: format!(
698            "\"{}\" is exported under {} names ({}); keep one name or add the names to ignoreExports",
699            alias.local_name,
700            alias.export_names.len(),
701            alias.export_names.join(", ")
702        ),
703        uri: relative_uri(&alias.path, root),
704        region: Some((alias.line, alias.col + 1)),
705        source_path: Some(alias.path.clone()),
706        properties: Some(serde_json::json!({
707            "local_name": alias.local_name,
708            "export_names": alias.export_names,
709        })),
710    }
711}
712
713fn sarif_unused_tagged_error_fields(
714    error: &UnusedTaggedError,
715    root: &Path,
716    level: &'static str,
717) -> SarifFields {
718    SarifFields {
719        rule_id: "fallow/unused-tagged-error",
720        level,
721        message: format!(
722            "tagged error \"{}\" (tag \"{}\") is never constructed or failed with; fail with it or remove it and its {} catchTag handler(s)",
723            error.name,
724            error.tag,
725            error.catch_sites.len()
726        ),
727        uri: relative_uri(&error.path, root),
728        region: Some((error.line, error.col + 1)),
729        source_path: Some(error.path.clone()),
730        properties: Some(serde_json::json!({
731            "tag": error.tag,
732            "catch_sites": error
733                .catch_sites
734                .iter()
735                .map(|site| serde_json::json!({
736                    "uri": relative_uri(&site.path, root),
737                    "line": site.line,
738                    "column": site.col + 1,
739                }))
740                .collect::<Vec<_>>(),
741        })),
742    }
743}
744
745fn sarif_unproduced_catch_tag_fields(
746    catch_tag: &UnproducedCatchTag,
747    root: &Path,
748    level: &'static str,
749) -> SarifFields {
750    SarifFields {
751        rule_id: "fallow/unproduced-catch-tag",
752        level,
753        message: format!(
754            "catchTag handler for \"{}\" never runs: no code produces {}; remove the handler or fail with the error",
755            catch_tag.tag,
756            catch_tag.candidate_classes.join(", ")
757        ),
758        uri: relative_uri(&catch_tag.path, root),
759        region: Some((catch_tag.line, catch_tag.col + 1)),
760        source_path: Some(catch_tag.path.clone()),
761        properties: Some(serde_json::json!({
762            "tag": catch_tag.tag,
763            "candidate_classes": catch_tag.candidate_classes,
764        })),
765    }
766}
767
768fn sarif_unused_svelte_event_fields(
769    event: &UnusedSvelteEvent,
770    root: &Path,
771    level: &'static str,
772) -> SarifFields {
773    SarifFields {
774        rule_id: "fallow/unused-svelte-event",
775        level,
776        message: format!(
777            "event \"{}\" is dispatched by component \"{}\" but listened to nowhere in the project; remove it or listen for it",
778            event.event_name, event.component_name
779        ),
780        uri: relative_uri(&event.path, root),
781        region: Some((event.line, event.col + 1)),
782        source_path: Some(event.path.clone()),
783        properties: None,
784    }
785}
786
787fn sarif_unused_component_input_fields(
788    input: &UnusedComponentInput,
789    root: &Path,
790    level: &'static str,
791) -> SarifFields {
792    SarifFields {
793        rule_id: "fallow/unused-component-input",
794        level,
795        message: format!(
796            "input \"{}\" is declared but read nowhere inside component \"{}\"; remove it or use it",
797            input.input_name, input.component_name
798        ),
799        uri: relative_uri(&input.path, root),
800        region: Some((input.line, input.col + 1)),
801        source_path: Some(input.path.clone()),
802        properties: None,
803    }
804}
805
806fn sarif_unused_component_output_fields(
807    output: &UnusedComponentOutput,
808    root: &Path,
809    level: &'static str,
810) -> SarifFields {
811    SarifFields {
812        rule_id: "fallow/unused-component-output",
813        level,
814        message: format!(
815            "output \"{}\" is declared but emitted nowhere inside component \"{}\"; remove it or emit it",
816            output.output_name, output.component_name
817        ),
818        uri: relative_uri(&output.path, root),
819        region: Some((output.line, output.col + 1)),
820        source_path: Some(output.path.clone()),
821        properties: None,
822    }
823}
824
825fn sarif_unused_server_action_fields(
826    action: &UnusedServerAction,
827    root: &Path,
828    level: &'static str,
829) -> SarifFields {
830    SarifFields {
831        rule_id: "fallow/unused-server-action",
832        level,
833        message: format!(
834            "server action \"{}\" is exported from a \"use server\" file but no code in this project references it; wire it to a consumer or remove it",
835            action.action_name
836        ),
837        uri: relative_uri(&action.path, root),
838        region: Some((action.line, action.col + 1)),
839        source_path: Some(action.path.clone()),
840        properties: None,
841    }
842}
843
844fn sarif_unused_load_data_key_fields(
845    key: &fallow_types::results::UnusedLoadDataKey,
846    root: &Path,
847    level: &'static str,
848) -> SarifFields {
849    SarifFields {
850        rule_id: "fallow/unused-load-data-key",
851        level,
852        message: format!(
853            "Route data return key \"{}\" is read by no consumer (no data.<key>, page.data.<key> or useLoaderData() read); delete the key or wire a consumer",
854            key.key_name
855        ),
856        uri: relative_uri(&key.path, root),
857        region: Some((key.line, key.col + 1)),
858        source_path: Some(key.path.clone()),
859        properties: None,
860    }
861}
862
863fn sarif_prop_drilling_fields(
864    chain: &PropDrillingChain,
865    root: &Path,
866    level: &'static str,
867) -> SarifFields {
868    // Anchor at the source hop (the prop owner). Path / line come from the first
869    // hop; the message names the depth and the consumer at the chain tail.
870    let source = chain.hops.first();
871    let consumer = chain.hops.last();
872    let consumer_name = consumer.map_or("a distant component", |h| h.component.as_str());
873    SarifFields {
874        rule_id: "fallow/prop-drilling",
875        level,
876        message: format!(
877            "prop \"{}\" is forwarded unchanged through {} component(s) before \"{}\" consumes it; colocate, lift to context, or compose",
878            chain.prop, chain.depth, consumer_name
879        ),
880        uri: source.map_or_else(String::new, |hop| relative_uri(&hop.file, root)),
881        region: source.map(|hop| (hop.line, 1)),
882        source_path: source.map(|hop| hop.file.clone()),
883        properties: None,
884    }
885}
886
887fn sarif_thin_wrapper_fields(
888    wrapper: &ThinWrapper,
889    root: &Path,
890    level: &'static str,
891) -> SarifFields {
892    SarifFields {
893        rule_id: "fallow/thin-wrapper",
894        level,
895        message: format!(
896            "\"{}\" is a thin wrapper: its whole body forwards props to \"{}\"; inline it at call sites or delete it",
897            wrapper.component, wrapper.child_component
898        ),
899        uri: relative_uri(&wrapper.file, root),
900        region: Some((wrapper.line, 1)),
901        source_path: Some(wrapper.file.clone()),
902        properties: None,
903    }
904}
905
906fn sarif_duplicate_prop_shape_fields(
907    shape: &DuplicatePropShape,
908    root: &Path,
909    level: &'static str,
910) -> SarifFields {
911    SarifFields {
912        rule_id: "fallow/duplicate-prop-shape",
913        level,
914        message: format!(
915            "\"{}\" shares an identical prop shape {{{}}} with {} other component(s); extract a shared Props type or base component",
916            shape.component,
917            shape.shape.join(", "),
918            shape.group_size.saturating_sub(1)
919        ),
920        uri: relative_uri(&shape.file, root),
921        region: Some((shape.line, 1)),
922        source_path: Some(shape.file.clone()),
923        properties: None,
924    }
925}
926
927fn sarif_route_collision_fields(
928    collision: &RouteCollision,
929    root: &Path,
930    level: &'static str,
931) -> SarifFields {
932    SarifFields {
933        rule_id: "fallow/route-collision",
934        level,
935        message: format!(
936            "Route file resolves to '{}', which is also owned by {} other file(s); Next.js fails the build because a URL can have only one owner",
937            collision.url,
938            collision.conflicting_paths.len()
939        ),
940        uri: relative_uri(&collision.path, root),
941        region: Some((collision.line, collision.col + 1)),
942        source_path: Some(collision.path.clone()),
943        properties: None,
944    }
945}
946
947fn sarif_dynamic_segment_name_conflict_fields(
948    conflict: &DynamicSegmentNameConflict,
949    root: &Path,
950    level: &'static str,
951) -> SarifFields {
952    SarifFields {
953        rule_id: "fallow/dynamic-segment-name-conflict",
954        level,
955        message: format!(
956            "Dynamic segments at '{}' use different slug names ({}); Next.js requires one consistent name per dynamic path",
957            conflict.position,
958            conflict.conflicting_segments.join(", ")
959        ),
960        uri: relative_uri(&conflict.path, root),
961        region: Some((conflict.line, conflict.col + 1)),
962        source_path: Some(conflict.path.clone()),
963        properties: None,
964    }
965}
966
967fn sarif_stale_suppression_fields(
968    suppression: &StaleSuppression,
969    root: &Path,
970    level: &'static str,
971) -> SarifFields {
972    SarifFields {
973        rule_id: if suppression.missing_reason {
974            "fallow/missing-suppression-reason"
975        } else {
976            "fallow/stale-suppression"
977        },
978        level,
979        message: suppression.display_message(),
980        uri: relative_uri(&suppression.path, root),
981        region: Some((suppression.line, suppression.col + 1)),
982        source_path: Some(suppression.path.clone()),
983        properties: None,
984    }
985}
986
987fn stale_suppression_severity(suppression: &StaleSuppression, rules: &RulesConfig) -> Severity {
988    if suppression.missing_reason {
989        rules.require_suppression_reason
990    } else {
991        rules.stale_suppressions
992    }
993}
994
995fn sarif_unused_catalog_entry_fields(
996    entry: &UnusedCatalogEntryFinding,
997    root: &Path,
998    level: &'static str,
999) -> SarifFields {
1000    let entry = &entry.entry;
1001    let message = if entry.catalog_name == "default" {
1002        format!(
1003            "Catalog entry '{}' is not referenced by any workspace package",
1004            entry.entry_name
1005        )
1006    } else {
1007        format!(
1008            "Catalog entry '{}' (catalog '{}') is not referenced by any workspace package",
1009            entry.entry_name, entry.catalog_name
1010        )
1011    };
1012    SarifFields {
1013        rule_id: "fallow/unused-catalog-entry",
1014        level,
1015        message,
1016        uri: relative_uri(&entry.path, root),
1017        region: Some((entry.line, 1)),
1018        source_path: Some(entry.path.clone()),
1019        properties: None,
1020    }
1021}
1022
1023fn sarif_unused_dependency_override_fields(
1024    finding: &UnusedDependencyOverrideFinding,
1025    root: &Path,
1026    level: &'static str,
1027) -> SarifFields {
1028    let finding = &finding.entry;
1029    let mut message = format!(
1030        "Override `{}` forces version `{}` but `{}` is not declared by any workspace package or resolved in the lockfile",
1031        finding.raw_key, finding.version_range, finding.target_package,
1032    );
1033    if let Some(hint) = &finding.hint {
1034        use std::fmt::Write as _;
1035        let _ = write!(message, " ({hint})");
1036    }
1037    SarifFields {
1038        rule_id: "fallow/unused-dependency-override",
1039        level,
1040        message,
1041        uri: relative_uri(&finding.path, root),
1042        region: Some((finding.line, 1)),
1043        source_path: Some(finding.path.clone()),
1044        properties: None,
1045    }
1046}
1047
1048fn sarif_misconfigured_dependency_override_fields(
1049    finding: &MisconfiguredDependencyOverrideFinding,
1050    root: &Path,
1051    level: &'static str,
1052) -> SarifFields {
1053    let finding = &finding.entry;
1054    let message = format!(
1055        "Override `{}` -> `{}` is malformed: {}",
1056        finding.raw_key,
1057        finding.raw_value,
1058        finding.reason.describe(),
1059    );
1060    SarifFields {
1061        rule_id: "fallow/misconfigured-dependency-override",
1062        level,
1063        message,
1064        uri: relative_uri(&finding.path, root),
1065        region: Some((finding.line, 1)),
1066        source_path: Some(finding.path.clone()),
1067        properties: None,
1068    }
1069}
1070
1071fn sarif_unresolved_catalog_reference_fields(
1072    finding: &UnresolvedCatalogReferenceFinding,
1073    root: &Path,
1074    level: &'static str,
1075) -> SarifFields {
1076    let finding = &finding.reference;
1077    let catalog_phrase = if finding.catalog_name == "default" {
1078        "the default catalog".to_string()
1079    } else {
1080        format!("catalog '{}'", finding.catalog_name)
1081    };
1082    let mut message = format!(
1083        "Package '{}' is referenced via `catalog:{}` but {} does not declare it",
1084        finding.entry_name,
1085        if finding.catalog_name == "default" {
1086            ""
1087        } else {
1088            finding.catalog_name.as_str()
1089        },
1090        catalog_phrase,
1091    );
1092    if !finding.available_in_catalogs.is_empty() {
1093        use std::fmt::Write as _;
1094        let _ = write!(
1095            message,
1096            " (available in: {})",
1097            finding.available_in_catalogs.join(", ")
1098        );
1099    }
1100    SarifFields {
1101        rule_id: "fallow/unresolved-catalog-reference",
1102        level,
1103        message,
1104        uri: relative_uri(&finding.path, root),
1105        region: Some((finding.line, 1)),
1106        source_path: Some(finding.path.clone()),
1107        properties: None,
1108    }
1109}
1110
1111fn sarif_empty_catalog_group_fields(
1112    group: &EmptyCatalogGroupFinding,
1113    root: &Path,
1114    level: &'static str,
1115) -> SarifFields {
1116    let group = &group.group;
1117    SarifFields {
1118        rule_id: "fallow/empty-catalog-group",
1119        level,
1120        message: format!("Catalog group '{}' has no entries", group.catalog_name),
1121        uri: relative_uri(&group.path, root),
1122        region: Some((group.line, 1)),
1123        source_path: Some(group.path.clone()),
1124        properties: None,
1125    }
1126}
1127
1128/// Unlisted deps fan out to one SARIF result per import site, so they do not
1129/// fit `push_sarif_results`. Keep the nested-loop shape in its own helper.
1130fn push_sarif_unlisted_deps(
1131    sarif_results: &mut Vec<serde_json::Value>,
1132    deps: &[UnlistedDependencyFinding],
1133    root: &Path,
1134    rule: Severity,
1135    snippets: &mut SourceSnippetCache,
1136) {
1137    for entry in deps {
1138        let level = finding_level(entry, rule);
1139        let dep = &entry.dep;
1140        for site in &dep.imported_from {
1141            let uri = relative_uri(&site.path, root);
1142            let source_snippet = snippets.line(&site.path, site.line);
1143            sarif_results.push(sarif_result_with_snippet(
1144                "fallow/unlisted-dependency",
1145                level,
1146                &format!(
1147                    "Package '{}' is imported but not listed in package.json",
1148                    dep.package_name
1149                ),
1150                &uri,
1151                Some((site.line, site.col + 1)),
1152                source_snippet.as_deref(),
1153            ));
1154        }
1155    }
1156}
1157
1158/// Unlisted binaries fan out to one SARIF result per use site, like unlisted
1159/// dependencies.
1160fn push_sarif_unlisted_binaries(
1161    sarif_results: &mut Vec<serde_json::Value>,
1162    binaries: &[UnlistedBinaryFinding],
1163    root: &Path,
1164    rule: Severity,
1165    snippets: &mut SourceSnippetCache,
1166) {
1167    for entry in binaries {
1168        let level = finding_level(entry, rule);
1169        let binary = &entry.binary;
1170        for site in &binary.used_in {
1171            let uri = relative_uri(&site.path, root);
1172            let source_snippet = snippets.line(&site.path, site.line);
1173            sarif_results.push(sarif_result_with_snippet(
1174                "fallow/unlisted-binary",
1175                level,
1176                &format!(
1177                    "Binary '{}' is used but no installed or listed package provides it",
1178                    binary.binary_name
1179                ),
1180                &uri,
1181                Some((site.line, site.col + 1)),
1182                source_snippet.as_deref(),
1183            ));
1184        }
1185    }
1186}
1187
1188/// Duplicate exports fan out to one SARIF result per location
1189/// (SARIF 2.1.0 section 3.27.12), so they do not fit `push_sarif_results`.
1190fn push_sarif_duplicate_exports(
1191    sarif_results: &mut Vec<serde_json::Value>,
1192    dups: &[DuplicateExportFinding],
1193    root: &Path,
1194    rule: Severity,
1195    snippets: &mut SourceSnippetCache,
1196) {
1197    for dup in dups {
1198        let level = finding_level(dup, rule);
1199        let dup = &dup.export;
1200        for loc in &dup.locations {
1201            let uri = relative_uri(&loc.path, root);
1202            let source_snippet = snippets.line(&loc.path, loc.line);
1203            sarif_results.push(sarif_result_with_snippet(
1204                "fallow/duplicate-export",
1205                level,
1206                &format!("Export '{}' appears in multiple modules", dup.export_name),
1207                &uri,
1208                Some((loc.line, loc.col + 1)),
1209                source_snippet.as_deref(),
1210            ));
1211        }
1212    }
1213}
1214
1215/// Build the SARIF rules list from the current rules configuration.
1216fn build_sarif_rules(
1217    rules: &RulesConfig,
1218    rule_builder: &dyn Fn(&str, &str, &str) -> serde_json::Value,
1219) -> Vec<serde_json::Value> {
1220    let mut sarif_rules = Vec::new();
1221    for contract in issue_output_contracts() {
1222        for rule_id in contract.sarif_rule_ids {
1223            let severity = sarif_rule_severity(rules, contract.code, &rule_id);
1224            let description = issue_sarif_rule_description(&rule_id).unwrap_or_else(|| {
1225                panic!("dead-code SARIF rule {rule_id} is missing issue metadata")
1226            });
1227            sarif_rules.push(rule_builder(
1228                &rule_id,
1229                description,
1230                configured_sarif_level(severity),
1231            ));
1232        }
1233    }
1234    sarif_rules
1235}
1236
1237fn sarif_rule_severity(rules: &RulesConfig, issue_code: &str, rule_id: &str) -> Severity {
1238    if rule_id == "fallow/missing-suppression-reason" {
1239        return rules.require_suppression_reason;
1240    }
1241    dead_code_rule_severity(rules, issue_code)
1242        .unwrap_or_else(|| panic!("dead-code SARIF rule {rule_id} has no severity mapping"))
1243}
1244
1245/// Builds the complete SARIF `run` value for a dead-code analysis.
1246///
1247/// Emits one SARIF result per finding across every dead-code issue kind,
1248/// mapping each configured rule severity to a SARIF level. `rule_builder`
1249/// constructs the tool-driver rule object for a `(rule id, name, help URI)`
1250/// triple so the caller controls rule metadata.
1251#[must_use]
1252pub fn build_dead_code_sarif(
1253    results: &AnalysisResults,
1254    root: &Path,
1255    rules: &RulesConfig,
1256    rule_builder: &dyn Fn(&str, &str, &str) -> serde_json::Value,
1257) -> serde_json::Value {
1258    let mut sarif_results = Vec::new();
1259    let mut snippets = SourceSnippetCache::with_root(root);
1260    let ctx = SarifCtx {
1261        results,
1262        root,
1263        rules,
1264    };
1265
1266    push_primary_dead_code_sarif_results(&mut sarif_results, &ctx, &mut snippets);
1267    push_dependency_sarif_results(&mut sarif_results, &ctx, &mut snippets);
1268    push_member_sarif_results(&mut sarif_results, &ctx, &mut snippets);
1269    push_sarif_results(
1270        &mut sarif_results,
1271        &results.unresolved_imports,
1272        &mut snippets,
1273        |i| {
1274            sarif_unresolved_import_fields(
1275                &i.import,
1276                root,
1277                finding_level(i, rules.unresolved_imports),
1278            )
1279        },
1280    );
1281    push_misc_sarif_results(&mut sarif_results, &ctx, &mut snippets);
1282    push_graph_sarif_results(&mut sarif_results, &ctx, &mut snippets);
1283    push_catalog_sarif_results(&mut sarif_results, &ctx, &mut snippets);
1284
1285    let sarif_rules = build_sarif_rules(rules, rule_builder);
1286    let mut sarif = sarif_document(&sarif_results, &sarif_rules);
1287    annotate_cascade_hidden(&mut sarif, results.cascade_hidden);
1288    sarif
1289}
1290
1291/// Record the number of findings that the cascade filter hid in the run
1292/// `properties`, as `cascadeHidden`. SARIF has no result for a hidden
1293/// finding, so this property is the only sign of them. Absent when zero.
1294fn annotate_cascade_hidden(sarif: &mut serde_json::Value, hidden: usize) {
1295    if hidden == 0 {
1296        return;
1297    }
1298    let Some(run) = sarif
1299        .get_mut("runs")
1300        .and_then(serde_json::Value::as_array_mut)
1301        .and_then(|runs| runs.first_mut())
1302        .and_then(serde_json::Value::as_object_mut)
1303    else {
1304        return;
1305    };
1306    let properties = run
1307        .entry("properties")
1308        .or_insert_with(|| serde_json::json!({}));
1309    if let Some(properties) = properties.as_object_mut() {
1310        properties.insert("cascadeHidden".to_owned(), serde_json::json!(hidden));
1311    }
1312}
1313
1314fn push_primary_dead_code_sarif_results(
1315    sarif_results: &mut Vec<serde_json::Value>,
1316    ctx: &SarifCtx<'_>,
1317    snippets: &mut SourceSnippetCache,
1318) {
1319    let SarifCtx {
1320        results,
1321        root,
1322        rules,
1323    } = *ctx;
1324
1325    push_sarif_results(sarif_results, &results.unused_files, snippets, |finding| {
1326        with_caveats(
1327            sarif_unused_file_fields(
1328                &finding.file,
1329                root,
1330                finding_level(finding, rules.unused_files),
1331            ),
1332            &finding.reachability_caveats,
1333        )
1334    });
1335    push_sarif_results(
1336        sarif_results,
1337        &results.unused_exports,
1338        snippets,
1339        |finding| {
1340            with_caveats(
1341                sarif_export_fields(
1342                    &finding.export,
1343                    root,
1344                    "fallow/unused-export",
1345                    finding_level(finding, rules.unused_exports),
1346                    "Export",
1347                    "Re-export",
1348                ),
1349                &finding.reachability_caveats,
1350            )
1351        },
1352    );
1353    push_sarif_results(sarif_results, &results.unused_types, snippets, |finding| {
1354        with_caveats(
1355            sarif_export_fields(
1356                &finding.export,
1357                root,
1358                "fallow/unused-type",
1359                finding_level(finding, rules.unused_types),
1360                "Type export",
1361                "Type re-export",
1362            ),
1363            &finding.reachability_caveats,
1364        )
1365    });
1366    push_sarif_results(
1367        sarif_results,
1368        &results.private_type_leaks,
1369        snippets,
1370        |finding| {
1371            sarif_private_type_leak_fields(
1372                &finding.leak,
1373                root,
1374                finding_level(finding, rules.private_type_leaks),
1375            )
1376        },
1377    );
1378    push_sarif_results(
1379        sarif_results,
1380        &results.deprecated_exports_in_use,
1381        snippets,
1382        |finding| {
1383            sarif_deprecated_export_fields(
1384                &finding.export,
1385                root,
1386                finding_level(finding, rules.deprecated_exports_in_use),
1387            )
1388        },
1389    );
1390}
1391
1392fn sarif_document(
1393    sarif_results: &[serde_json::Value],
1394    sarif_rules: &[serde_json::Value],
1395) -> serde_json::Value {
1396    build_sarif_document(SarifDocumentInput {
1397        results: sarif_results,
1398        rules: sarif_rules,
1399        tool_version: env!("CARGO_PKG_VERSION"),
1400    })
1401}
1402
1403fn push_dependency_sarif_results(
1404    sarif_results: &mut Vec<serde_json::Value>,
1405    ctx: &SarifCtx<'_>,
1406    snippets: &mut SourceSnippetCache,
1407) {
1408    push_unused_dependency_sarif_results(sarif_results, ctx, snippets);
1409    push_classified_dependency_sarif_results(sarif_results, ctx, snippets);
1410}
1411
1412/// Push SARIF results for unused runtime, dev, and optional dependencies.
1413fn push_unused_dependency_sarif_results(
1414    sarif_results: &mut Vec<serde_json::Value>,
1415    ctx: &SarifCtx<'_>,
1416    snippets: &mut SourceSnippetCache,
1417) {
1418    let SarifCtx {
1419        results,
1420        root,
1421        rules,
1422    } = *ctx;
1423
1424    let mut columns =
1425        manifest_key_columns(&results.unused_dependencies, snippets, |f| dep_key(&f.dep));
1426    push_sarif_results(sarif_results, &results.unused_dependencies, snippets, |d| {
1427        with_caveats(
1428            sarif_dep_fields(
1429                &d.dep,
1430                root,
1431                "fallow/unused-dependency",
1432                finding_level(d, rules.unused_dependencies),
1433                "dependencies",
1434                columns.next().unwrap_or(1),
1435            ),
1436            &d.reachability_caveats,
1437        )
1438    });
1439    let mut columns = manifest_key_columns(&results.unused_dev_dependencies, snippets, |f| {
1440        dep_key(&f.dep)
1441    });
1442    push_sarif_results(
1443        sarif_results,
1444        &results.unused_dev_dependencies,
1445        snippets,
1446        |d| {
1447            with_caveats(
1448                sarif_dep_fields(
1449                    &d.dep,
1450                    root,
1451                    "fallow/unused-dev-dependency",
1452                    finding_level(d, rules.unused_dev_dependencies),
1453                    "devDependencies",
1454                    columns.next().unwrap_or(1),
1455                ),
1456                &d.reachability_caveats,
1457            )
1458        },
1459    );
1460    let mut columns = manifest_key_columns(&results.unused_optional_dependencies, snippets, |f| {
1461        dep_key(&f.dep)
1462    });
1463    push_sarif_results(
1464        sarif_results,
1465        &results.unused_optional_dependencies,
1466        snippets,
1467        |d| {
1468            with_caveats(
1469                sarif_dep_fields(
1470                    &d.dep,
1471                    root,
1472                    "fallow/unused-optional-dependency",
1473                    finding_level(d, rules.unused_optional_dependencies),
1474                    "optionalDependencies",
1475                    columns.next().unwrap_or(1),
1476                ),
1477                &d.reachability_caveats,
1478            )
1479        },
1480    );
1481}
1482
1483/// Push SARIF results for type-only and test-only dependency misclassifications.
1484fn push_classified_dependency_sarif_results(
1485    sarif_results: &mut Vec<serde_json::Value>,
1486    ctx: &SarifCtx<'_>,
1487    snippets: &mut SourceSnippetCache,
1488) {
1489    let SarifCtx {
1490        results,
1491        root,
1492        rules,
1493    } = *ctx;
1494
1495    let mut columns = manifest_key_columns(&results.type_only_dependencies, snippets, |f| {
1496        (
1497            f.dep.path.as_path(),
1498            f.dep.line,
1499            f.dep.package_name.as_str(),
1500        )
1501    });
1502    push_sarif_results(
1503        sarif_results,
1504        &results.type_only_dependencies,
1505        snippets,
1506        |d| {
1507            sarif_type_only_dep_fields(
1508                &d.dep,
1509                root,
1510                finding_level(d, rules.type_only_dependencies),
1511                columns.next().unwrap_or(1),
1512            )
1513        },
1514    );
1515    let mut columns = manifest_key_columns(&results.test_only_dependencies, snippets, |f| {
1516        (
1517            f.dep.path.as_path(),
1518            f.dep.line,
1519            f.dep.package_name.as_str(),
1520        )
1521    });
1522    push_sarif_results(
1523        sarif_results,
1524        &results.test_only_dependencies,
1525        snippets,
1526        |d| {
1527            sarif_test_only_dep_fields(
1528                &d.dep,
1529                root,
1530                finding_level(d, rules.test_only_dependencies),
1531                columns.next().unwrap_or(1),
1532            )
1533        },
1534    );
1535    let mut columns =
1536        manifest_key_columns(&results.dev_dependencies_in_production, snippets, |f| {
1537            (
1538                f.dep.path.as_path(),
1539                f.dep.line,
1540                f.dep.package_name.as_str(),
1541            )
1542        });
1543    push_sarif_results(
1544        sarif_results,
1545        &results.dev_dependencies_in_production,
1546        snippets,
1547        |d| {
1548            sarif_dev_dep_in_prod_fields(
1549                &d.dep,
1550                root,
1551                finding_level(d, rules.dev_dependencies_in_production),
1552                columns.next().unwrap_or(1),
1553            )
1554        },
1555    );
1556}
1557
1558fn push_misc_sarif_results(
1559    sarif_results: &mut Vec<serde_json::Value>,
1560    ctx: &SarifCtx<'_>,
1561    snippets: &mut SourceSnippetCache,
1562) {
1563    let SarifCtx {
1564        results,
1565        root,
1566        rules,
1567    } = *ctx;
1568
1569    if !results.unlisted_dependencies.is_empty() {
1570        push_sarif_unlisted_deps(
1571            sarif_results,
1572            &results.unlisted_dependencies,
1573            root,
1574            rules.unlisted_dependencies,
1575            snippets,
1576        );
1577    }
1578    if !results.unlisted_binaries.is_empty() {
1579        push_sarif_unlisted_binaries(
1580            sarif_results,
1581            &results.unlisted_binaries,
1582            root,
1583            rules.unlisted_binaries,
1584            snippets,
1585        );
1586    }
1587    if !results.duplicate_exports.is_empty() {
1588        push_sarif_duplicate_exports(
1589            sarif_results,
1590            &results.duplicate_exports,
1591            root,
1592            rules.duplicate_exports,
1593            snippets,
1594        );
1595    }
1596}
1597
1598/// Push the component-contract SARIF results (`unused-component-prop` and
1599/// `unused-component-emit`). Extracted from `push_graph_sarif_results` to keep
1600/// that function under the unit-size lint.
1601fn push_component_contract_sarif_results(
1602    sarif_results: &mut Vec<serde_json::Value>,
1603    ctx: &SarifCtx<'_>,
1604    snippets: &mut SourceSnippetCache,
1605) {
1606    push_component_member_sarif_results(sarif_results, ctx, snippets);
1607    push_component_framework_sarif_results(sarif_results, ctx, snippets);
1608    push_component_shape_sarif_results(sarif_results, ctx, snippets);
1609    push_constant_parameter_sarif_results(sarif_results, ctx, snippets);
1610}
1611
1612/// Push SARIF results for unused component props, emits, inputs, and outputs.
1613fn push_component_member_sarif_results(
1614    sarif_results: &mut Vec<serde_json::Value>,
1615    ctx: &SarifCtx<'_>,
1616    snippets: &mut SourceSnippetCache,
1617) {
1618    let SarifCtx {
1619        results,
1620        root,
1621        rules,
1622    } = *ctx;
1623    push_absent_component_prop_sarif_results(sarif_results, ctx, snippets);
1624
1625    push_sarif_results(
1626        sarif_results,
1627        &results.unused_component_props,
1628        snippets,
1629        |p| {
1630            sarif_unused_component_prop_fields(
1631                &p.prop,
1632                root,
1633                finding_level(p, rules.unused_component_props),
1634            )
1635        },
1636    );
1637    push_sarif_results(
1638        sarif_results,
1639        &results.unused_component_emits,
1640        snippets,
1641        |e| {
1642            sarif_unused_component_emit_fields(
1643                &e.emit,
1644                root,
1645                finding_level(e, rules.unused_component_emits),
1646            )
1647        },
1648    );
1649    push_sarif_results(
1650        sarif_results,
1651        &results.unused_component_inputs,
1652        snippets,
1653        |i| {
1654            sarif_unused_component_input_fields(
1655                &i.input,
1656                root,
1657                finding_level(i, rules.unused_component_inputs),
1658            )
1659        },
1660    );
1661    push_sarif_results(
1662        sarif_results,
1663        &results.unused_component_outputs,
1664        snippets,
1665        |o| {
1666            sarif_unused_component_output_fields(
1667                &o.output,
1668                root,
1669                finding_level(o, rules.unused_component_outputs),
1670            )
1671        },
1672    );
1673}
1674
1675/// Push SARIF results for prop drilling, thin wrappers, and duplicate prop shapes.
1676fn push_component_shape_sarif_results(
1677    sarif_results: &mut Vec<serde_json::Value>,
1678    ctx: &SarifCtx<'_>,
1679    snippets: &mut SourceSnippetCache,
1680) {
1681    let SarifCtx {
1682        results,
1683        root,
1684        rules,
1685    } = *ctx;
1686
1687    push_sarif_results(
1688        sarif_results,
1689        &results.prop_drilling_chains,
1690        snippets,
1691        |c| sarif_prop_drilling_fields(&c.chain, root, finding_level(c, rules.prop_drilling)),
1692    );
1693    push_sarif_results(sarif_results, &results.thin_wrappers, snippets, |w| {
1694        sarif_thin_wrapper_fields(&w.wrapper, root, finding_level(w, rules.thin_wrapper))
1695    });
1696    push_sarif_results(
1697        sarif_results,
1698        &results.duplicate_prop_shapes,
1699        snippets,
1700        |d| {
1701            sarif_duplicate_prop_shape_fields(
1702                &d.shape,
1703                root,
1704                finding_level(d, rules.duplicate_prop_shape),
1705            )
1706        },
1707    );
1708}
1709
1710fn push_graph_sarif_results(
1711    sarif_results: &mut Vec<serde_json::Value>,
1712    ctx: &SarifCtx<'_>,
1713    snippets: &mut SourceSnippetCache,
1714) {
1715    push_structure_sarif_results(sarif_results, ctx, snippets);
1716    push_framework_sarif_results(sarif_results, ctx, snippets);
1717    push_route_sarif_results(sarif_results, ctx, snippets);
1718    push_suppression_sarif_results(sarif_results, ctx, snippets);
1719}
1720
1721fn push_structure_sarif_results(
1722    sarif_results: &mut Vec<serde_json::Value>,
1723    ctx: &SarifCtx<'_>,
1724    snippets: &mut SourceSnippetCache,
1725) {
1726    push_cycle_sarif_results(sarif_results, ctx, snippets);
1727    push_boundary_sarif_results(sarif_results, ctx, snippets);
1728}
1729
1730/// Push SARIF results for circular dependencies, re-export cycles and
1731/// package cycles.
1732fn push_cycle_sarif_results(
1733    sarif_results: &mut Vec<serde_json::Value>,
1734    ctx: &SarifCtx<'_>,
1735    snippets: &mut SourceSnippetCache,
1736) {
1737    let SarifCtx {
1738        results,
1739        root,
1740        rules,
1741    } = *ctx;
1742
1743    push_sarif_results(
1744        sarif_results,
1745        &results.circular_dependencies,
1746        snippets,
1747        |c| {
1748            sarif_circular_dep_fields(
1749                &c.cycle,
1750                root,
1751                finding_level(c, rules.circular_dependencies),
1752            )
1753        },
1754    );
1755    push_sarif_results(sarif_results, &results.re_export_cycles, snippets, |c| {
1756        sarif_re_export_cycle_fields(&c.cycle, root, finding_level(c, rules.re_export_cycle))
1757    });
1758    push_sarif_results(sarif_results, &results.package_cycles, snippets, |c| {
1759        sarif_package_cycle_fields(&c.cycle, root, finding_level(c, rules.package_cycle))
1760    });
1761}
1762
1763/// Push SARIF results for boundary violations, coverage, calls, and policy violations.
1764fn push_boundary_sarif_results(
1765    sarif_results: &mut Vec<serde_json::Value>,
1766    ctx: &SarifCtx<'_>,
1767    snippets: &mut SourceSnippetCache,
1768) {
1769    let SarifCtx {
1770        results,
1771        root,
1772        rules,
1773    } = *ctx;
1774
1775    push_sarif_results(sarif_results, &results.boundary_violations, snippets, |v| {
1776        sarif_boundary_violation_fields(
1777            &v.violation,
1778            root,
1779            finding_level(v, rules.boundary_violation),
1780        )
1781    });
1782    push_sarif_results(
1783        sarif_results,
1784        &results.boundary_coverage_violations,
1785        snippets,
1786        |v| {
1787            sarif_boundary_coverage_fields(
1788                &v.violation,
1789                root,
1790                finding_level(v, rules.boundary_violation),
1791            )
1792        },
1793    );
1794    push_sarif_results(
1795        sarif_results,
1796        &results.boundary_call_violations,
1797        snippets,
1798        |v| {
1799            sarif_boundary_call_fields(
1800                &v.violation,
1801                root,
1802                finding_level(v, rules.boundary_violation),
1803            )
1804        },
1805    );
1806    push_sarif_results(sarif_results, &results.policy_violations, snippets, |v| {
1807        sarif_policy_violation_fields(&v.violation, root)
1808    });
1809}
1810
1811fn push_framework_sarif_results(
1812    sarif_results: &mut Vec<serde_json::Value>,
1813    ctx: &SarifCtx<'_>,
1814    snippets: &mut SourceSnippetCache,
1815) {
1816    push_framework_boundary_sarif_results(sarif_results, ctx, snippets);
1817    push_component_contract_sarif_results(sarif_results, ctx, snippets);
1818}
1819
1820/// Push SARIF results for client exports, barrels, directives, injects, and unrendered components.
1821fn push_framework_boundary_sarif_results(
1822    sarif_results: &mut Vec<serde_json::Value>,
1823    ctx: &SarifCtx<'_>,
1824    snippets: &mut SourceSnippetCache,
1825) {
1826    let SarifCtx {
1827        results,
1828        root,
1829        rules,
1830    } = *ctx;
1831
1832    push_sarif_results(
1833        sarif_results,
1834        &results.invalid_client_exports,
1835        snippets,
1836        |e| {
1837            sarif_invalid_client_export_fields(
1838                &e.export,
1839                root,
1840                finding_level(e, rules.invalid_client_export),
1841            )
1842        },
1843    );
1844    push_sarif_results(
1845        sarif_results,
1846        &results.mixed_client_server_barrels,
1847        snippets,
1848        |b| {
1849            sarif_mixed_client_server_barrel_fields(
1850                &b.barrel,
1851                root,
1852                finding_level(b, rules.mixed_client_server_barrel),
1853            )
1854        },
1855    );
1856    push_sarif_results(
1857        sarif_results,
1858        &results.misplaced_directives,
1859        snippets,
1860        |d| {
1861            sarif_misplaced_directive_fields(
1862                &d.directive_site,
1863                root,
1864                finding_level(d, rules.misplaced_directive),
1865            )
1866        },
1867    );
1868    push_framework_render_sarif_results(sarif_results, ctx, snippets);
1869}
1870
1871fn push_framework_render_sarif_results(
1872    sarif_results: &mut Vec<serde_json::Value>,
1873    ctx: &SarifCtx<'_>,
1874    snippets: &mut SourceSnippetCache,
1875) {
1876    let SarifCtx {
1877        results,
1878        root,
1879        rules,
1880    } = *ctx;
1881
1882    push_sarif_results(sarif_results, &results.unprovided_injects, snippets, |i| {
1883        sarif_unprovided_inject_fields(&i.inject, root, finding_level(i, rules.unprovided_injects))
1884    });
1885    push_sarif_results(
1886        sarif_results,
1887        &results.unrendered_components,
1888        snippets,
1889        |c| {
1890            sarif_unrendered_component_fields(
1891                &c.component,
1892                root,
1893                finding_level(c, rules.unrendered_components),
1894            )
1895        },
1896    );
1897}
1898
1899fn push_route_sarif_results(
1900    sarif_results: &mut Vec<serde_json::Value>,
1901    ctx: &SarifCtx<'_>,
1902    snippets: &mut SourceSnippetCache,
1903) {
1904    let SarifCtx {
1905        results,
1906        root,
1907        rules,
1908    } = *ctx;
1909
1910    push_sarif_results(sarif_results, &results.route_collisions, snippets, |c| {
1911        sarif_route_collision_fields(&c.collision, root, finding_level(c, rules.route_collision))
1912    });
1913    push_sarif_results(
1914        sarif_results,
1915        &results.dynamic_segment_name_conflicts,
1916        snippets,
1917        |c| {
1918            sarif_dynamic_segment_name_conflict_fields(
1919                &c.conflict,
1920                root,
1921                finding_level(c, rules.dynamic_segment_name_conflict),
1922            )
1923        },
1924    );
1925}
1926
1927fn push_suppression_sarif_results(
1928    sarif_results: &mut Vec<serde_json::Value>,
1929    ctx: &SarifCtx<'_>,
1930    snippets: &mut SourceSnippetCache,
1931) {
1932    let SarifCtx {
1933        results,
1934        root,
1935        rules,
1936    } = *ctx;
1937
1938    push_sarif_results(sarif_results, &results.stale_suppressions, snippets, |s| {
1939        sarif_stale_suppression_fields(
1940            s,
1941            root,
1942            finding_level(s, stale_suppression_severity(s, rules)),
1943        )
1944    });
1945}
1946
1947fn push_catalog_sarif_results(
1948    sarif_results: &mut Vec<serde_json::Value>,
1949    ctx: &SarifCtx<'_>,
1950    snippets: &mut SourceSnippetCache,
1951) {
1952    push_catalog_entry_sarif_results(sarif_results, ctx, snippets);
1953    push_dependency_override_sarif_results(sarif_results, ctx, snippets);
1954}
1955
1956/// Push SARIF results for unused catalog entries, empty groups, and unresolved references.
1957fn push_catalog_entry_sarif_results(
1958    sarif_results: &mut Vec<serde_json::Value>,
1959    ctx: &SarifCtx<'_>,
1960    snippets: &mut SourceSnippetCache,
1961) {
1962    let SarifCtx {
1963        results,
1964        root,
1965        rules,
1966    } = *ctx;
1967
1968    push_sarif_results(
1969        sarif_results,
1970        &results.unused_catalog_entries,
1971        snippets,
1972        |e| {
1973            sarif_unused_catalog_entry_fields(
1974                e,
1975                root,
1976                finding_level(e, rules.unused_catalog_entries),
1977            )
1978        },
1979    );
1980    push_sarif_results(
1981        sarif_results,
1982        &results.empty_catalog_groups,
1983        snippets,
1984        |g| sarif_empty_catalog_group_fields(g, root, finding_level(g, rules.empty_catalog_groups)),
1985    );
1986    push_sarif_results(
1987        sarif_results,
1988        &results.unresolved_catalog_references,
1989        snippets,
1990        |f| {
1991            sarif_unresolved_catalog_reference_fields(
1992                f,
1993                root,
1994                finding_level(f, rules.unresolved_catalog_references),
1995            )
1996        },
1997    );
1998}
1999
2000/// Push SARIF results for unused and misconfigured dependency overrides.
2001fn push_dependency_override_sarif_results(
2002    sarif_results: &mut Vec<serde_json::Value>,
2003    ctx: &SarifCtx<'_>,
2004    snippets: &mut SourceSnippetCache,
2005) {
2006    let SarifCtx {
2007        results,
2008        root,
2009        rules,
2010    } = *ctx;
2011
2012    push_sarif_results(
2013        sarif_results,
2014        &results.unused_dependency_overrides,
2015        snippets,
2016        |f| {
2017            sarif_unused_dependency_override_fields(
2018                f,
2019                root,
2020                finding_level(f, rules.unused_dependency_overrides),
2021            )
2022        },
2023    );
2024    push_sarif_results(
2025        sarif_results,
2026        &results.misconfigured_dependency_overrides,
2027        snippets,
2028        |f| {
2029            sarif_misconfigured_dependency_override_fields(
2030                f,
2031                root,
2032                finding_level(f, rules.misconfigured_dependency_overrides),
2033            )
2034        },
2035    );
2036}
2037
2038#[path = "dead_code_sarif_severity.rs"]
2039mod dead_code_sarif_severity;
2040use dead_code_sarif_severity::dead_code_rule_severity;
2041
2042#[path = "dead_code_sarif_boundary.rs"]
2043mod boundary_render;
2044use boundary_render::sarif_boundary_violation_fields;
2045
2046#[cfg(test)]
2047#[path = "dead_code_sarif_tests.rs"]
2048mod tests;