cargo-judge 0.7.0

Deterministic post-refactoring analysis for Rust workspaces
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
//! Fast-tier public-API-surface analysis (see todo.md §I "Public-API-
//! Oberfläche"): `undocumented-public-item`, a `syn`-only check for a
//! module-level `pub` item with no doc comment, and `semver-hazard`, a
//! `syn`-only check for two API-evolvability gaps.
//!
//! ## `semver-hazard` scope
//!
//! Two of the three sub-cases todo.md §I lists are implemented, both exact
//! syntax facts distinguished by `evidence.kind` (the same bundling
//! [`crate::rules::slop_structural::ABSTRACTION_INFLATION_RULE`] uses for its own
//! sub-patterns): a `pub enum` with at least two variants and no
//! `#[non_exhaustive]` attribute (`missing_non_exhaustive_enum`), and a
//! `pub struct` with at least one `pub` field and no `#[non_exhaustive]`
//! attribute (`missing_non_exhaustive_struct_fields`). The third sub-case —
//! a dependency's type leaking through a `pub fn`'s parameter or return type
//! (`leaked_dependency_type`) — needs type resolution across crate
//! boundaries the Fast Tier doesn't have; it lives in
//! [`crate::rules::api_surface_deep`] instead, behind the `deep` feature, reusing
//! this module's [`PubFnCandidate`] item population but wired into the same
//! `semver-hazard` rule id (see that module's docs).
//!
//! ## Item-level visibility only
//!
//! This detector checks only whether the item **itself** is written `pub` —
//! it does not propagate the full visibility chain up through enclosing
//! modules (a heuristic, not module-graph resolution, matching how
//! [`crate::rules::deps`]'s `UsageDomain` classification documents its own scope
//! boundary). A `pub fn` inside a private `mod` is not actually reachable
//! from outside the crate, but is still checked here as if it were —
//! resolving that would need semantic module-visibility resolution the Fast
//! Tier doesn't have. A known, accepted simplification, not hidden.
//!
//! ## Scope
//!
//! Checked item kinds: free `fn`, `struct`, `enum`, `trait`, `const`,
//! `static`, and `type` alias at module level, plus methods inside an
//! *inherent* `impl` block. Not checked: methods inside `impl Trait for
//! Type` (they typically inherit the trait's own documentation — see
//! [`crate::functions::FunctionSite::in_trait_impl`]'s doc comment for the
//! same exclusion reasoning elsewhere in this crate), `#[test]`-attributed
//! functions, and anything gated by `#[cfg(test)]` (on the item itself or an
//! enclosing item).

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use serde_json::json;
use syn::spanned::Spanned;
use syn::visit::{self, Visit};
use syn::{
    Attribute, ImplItemFn, ItemConst, ItemEnum, ItemFn, ItemImpl, ItemMod, ItemStatic, ItemStruct,
    ItemTrait, ItemType, Visibility,
};

use crate::finding::{Finding, Location, Origin, Severity};
use crate::functions::{has_test_attr, qualified_item_path, read_and_parse_source, type_name};
use crate::ingest::CrateInfo;

/// Rule id for a module-level `pub` item with no doc comment (see todo.md
/// §I).
pub const UNDOCUMENTED_PUBLIC_ITEM_RULE: &str = "undocumented-public-item";
/// Bump when the undocumented-public-item rule's logic changes (see todo.md
/// §5 "Regelversions-Schutz").
pub const UNDOCUMENTED_PUBLIC_ITEM_RULE_REVISION: u32 = 1;

/// Rule id shared by both `semver-hazard` sub-cases (see the module doc
/// comment's "`semver-hazard` scope" section); `evidence.kind` distinguishes
/// `missing_non_exhaustive_enum` from `missing_non_exhaustive_struct_fields`.
pub const SEMVER_HAZARD_RULE: &str = "semver-hazard";
/// Bump when any semver-hazard sub-case's logic changes, including the
/// Deep-Tier `leaked_dependency_type` sub-case in
/// [`crate::rules::api_surface_deep`] (see todo.md §5 "Regelversions-Schutz").
pub const SEMVER_HAZARD_RULE_REVISION: u32 = 2;

#[derive(Debug)]
pub enum ApiSurfaceError {
    Io(PathBuf, std::io::Error),
    Parse(PathBuf, syn::Error),
}

impl std::fmt::Display for ApiSurfaceError {
    // judge-dupe-ignore: explicit per-domain error rendering; variants and messages are intentionally distinct
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(path, err) => write!(f, "{}: failed to read file: {err}", path.display()),
            Self::Parse(path, err) => write!(f, "{}: failed to parse: {err}", path.display()),
        }
    }
}

impl std::error::Error for ApiSurfaceError {}

/// Per-crate count of public top-level API items — `pub fn`/`struct`/`enum`/
/// `trait`/`const`/`static`/`type` at module level, plus a `pub fn` inside an
/// inherent `impl` (the same item kinds
/// [`check_doc`](ApiSurfaceVisitor::check_doc) already visits for
/// `undocumented-public-item`, reused rather than duplicated). A pure count,
/// not a finding — a report metadatum like `Report.counts`/
/// `analysis_universe`, with no fail/warn/info severity of its own (see
/// todo.md §I "API-Surface-Größe pro Crate, Trend gegen Baseline").
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ApiSurfaceSize {
    pub per_crate: HashMap<String, usize>,
}

/// One crate's api-surface-size trend against a baseline (see
/// [`ApiSurfaceSize`]'s doc comment). `delta` is `None` when the baseline
/// recorded no `api_surface_size` at all — an older baseline schema, or one
/// saved by a different command — or the crate didn't exist in it yet,
/// mirroring how [`crate::health_score::Trend::NotComparable`] reports an
/// explicit reason instead of a false delta, at per-crate granularity.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CrateSizeTrend {
    pub crate_name: String,
    pub item_count: usize,
    pub delta: Option<i64>,
}

/// Computes [`CrateSizeTrend`] for every crate in `current`, sorted by crate
/// name for stable output. `baseline_size` is the baseline's stored
/// `api_surface_size` (`None` when absent — see [`CrateSizeTrend`]'s doc
/// comment).
pub fn size_trend(
    current: &ApiSurfaceSize,
    baseline_size: Option<&HashMap<String, usize>>,
) -> Vec<CrateSizeTrend> {
    let mut trend: Vec<CrateSizeTrend> = current
        .per_crate
        .iter()
        .map(|(crate_name, &item_count)| {
            let delta = baseline_size
                .and_then(|baseline| baseline.get(crate_name))
                .map(|&previous| item_count as i64 - previous as i64);
            CrateSizeTrend {
                crate_name: crate_name.clone(),
                item_count,
                delta,
            }
        })
        .collect();
    trend.sort_by(|a, b| a.crate_name.cmp(&b.crate_name));
    trend
}

/// Aggregated api-surface findings across a set of files, keeping findings
/// separate from files that could not be parsed.
#[derive(Debug, Default)]
pub struct WorkspaceApiSurface {
    pub findings: Vec<Finding>,
    pub errors: Vec<ApiSurfaceError>,
    /// Generated files skipped because `include_generated` was `false` (see
    /// todo.md §3.A "Generated-Code-Policy").
    pub excluded_generated: usize,
    /// Per-crate api-surface-size count (see [`ApiSurfaceSize`]).
    pub api_surface_size: ApiSurfaceSize,
}

/// Parses a single Rust source file, returning every
/// `undocumented-public-item`/`semver-hazard` finding, the number of public
/// top-level items counted along the way (see [`ApiSurfaceSize`]), and the
/// [`PubFnCandidate`]s collected along the way — the shared implementation
/// behind [`analyze_file`], [`analyze_workspace`], and [`pub_fn_candidates`],
/// so the item-collection walk itself is written once.
fn analyze_file_inner(
    path: &Path,
) -> Result<(Vec<Finding>, usize, Vec<PubFnCandidate>), ApiSurfaceError> {
    let (_, ast) = read_and_parse_source(
        path,
        |err| ApiSurfaceError::Io(path.to_path_buf(), err),
        |err| ApiSurfaceError::Parse(path.to_path_buf(), err),
    )?;

    let mut visitor = ApiSurfaceVisitor {
        file: path,
        path: Vec::new(),
        findings: Vec::new(),
        cfg_test_depth: 0,
        in_trait_impl: Vec::new(),
        item_count: 0,
        pub_fn_candidates: Vec::new(),
    };
    visitor.visit_file(&ast);
    Ok((
        visitor.findings,
        visitor.item_count,
        visitor.pub_fn_candidates,
    ))
}

/// Parses a single Rust source file and returns every `undocumented-public-item`
/// finding in it.
pub fn analyze_file(path: &Path) -> Result<Vec<Finding>, ApiSurfaceError> {
    analyze_file_inner(path).map(|(findings, _, _)| findings)
}

/// Parses a single Rust source file and returns its [`PubFnCandidate`]s for
/// the Deep Tier's `leaked_dependency_type` `semver-hazard` sub-case (see
/// [`crate::rules::api_surface_deep`]) — the exact same item population
/// [`analyze_file`] already computes for `undocumented-public-item`, from the
/// same walk. `pub(crate)`: only [`crate::rules::api_surface_deep`] calls this; a
/// build without the `deep` feature never does.
#[cfg_attr(not(feature = "deep"), allow(dead_code))]
pub(crate) fn pub_fn_candidates(path: &Path) -> Result<Vec<PubFnCandidate>, ApiSurfaceError> {
    analyze_file_inner(path).map(|(_, _, candidates)| candidates)
}

/// Runs [`analyze_file`] over every crate's source files and aggregates the
/// results, plus each crate's api-surface-size count (see [`ApiSurfaceSize`]).
/// Generated files are skipped unless `include_generated` is set (see
/// todo.md §3.A) — documentation completeness, and surface size, on
/// generated code isn't actionable the way it is on authored code.
pub fn analyze_workspace<'a>(
    crates: impl IntoIterator<Item = &'a CrateInfo>,
    include_generated: bool,
) -> WorkspaceApiSurface {
    let mut report = WorkspaceApiSurface::default();
    for krate in crates {
        let mut crate_item_count = 0;
        for file in &krate.source_files {
            if !include_generated && !file.kind.is_locally_reportable() {
                report.excluded_generated += 1;
                continue;
            }
            match analyze_file_inner(&file.path) {
                Ok((mut findings, item_count, _pub_fn_candidates)) => {
                    report.findings.append(&mut findings);
                    crate_item_count += item_count;
                }
                Err(err) => report.errors.push(err),
            }
        }
        report
            .api_surface_size
            .per_crate
            .insert(krate.name.clone(), crate_item_count);
    }
    report
}

/// One `pub fn` candidate for the Deep Tier's `leaked_dependency_type`
/// `semver-hazard` sub-case (see [`crate::rules::api_surface_deep`]): a module-level
/// free fn or inherent-impl method matching the exact item population
/// [`check_doc_fn`](ApiSurfaceVisitor::check_doc_fn) already computes for
/// `undocumented-public-item` — `pub`, not `#[test]`-attributed, not
/// `#[cfg(test)]`-gated, not inside a trait impl (see the module doc
/// comment's "Scope" section). Collected by the exact same walk rather than
/// re-derived, so the Fast-Tier item population and the Deep-Tier one for
/// this rule can never drift apart. Only consumed behind the `deep` feature,
/// hence the conditional allow (mirrors [`crate::functions::FunctionSite`]'s
/// same pattern).
#[derive(Debug, Clone)]
#[cfg_attr(not(feature = "deep"), allow(dead_code))]
pub struct PubFnCandidate {
    pub item_path: String,
    pub file: PathBuf,
    /// Span of just the function's identifier — enough to position a Deep
    /// Tier query on the name token, from which the fn's parameter/return
    /// types are reached structurally (see [`crate::rules::api_surface_deep`]).
    pub ident_span: proc_macro2::Span,
}

/// Walks a whole parsed file, tracking the enclosing `mod`/`impl`/`trait`/
/// item path for a finding's `item_path`, `#[cfg(test)]` nesting depth, and
/// whether the current `impl` block is a trait impl (see the module doc
/// comment's scope section).
struct ApiSurfaceVisitor<'a> {
    file: &'a Path,
    path: Vec<String>,
    findings: Vec<Finding>,
    /// Depth of nesting inside an item gated by `#[cfg(test)]` (on itself or
    /// an ancestor) — no item under this is checked (see
    /// [`attrs_have_cfg_test`]).
    cfg_test_depth: usize,
    /// Stack of "is the enclosing `impl` a trait impl" flags, one per
    /// enclosing `impl` block — mirrors [`crate::functions::Walker`]'s same
    /// stack.
    in_trait_impl: Vec<bool>,
    /// Count of `pub`, non-`#[cfg(test)]`-gated items visited so far — the
    /// api-surface-size count (see [`ApiSurfaceSize`]), incremented
    /// alongside `undocumented-public-item`'s own check in
    /// [`check_doc`](Self::check_doc) instead of a second walk.
    item_count: usize,
    /// `pub fn` candidates for the Deep Tier's `leaked_dependency_type`
    /// sub-case (see [`PubFnCandidate`]), collected alongside
    /// `undocumented-public-item`'s own check in
    /// [`check_doc_fn`](Self::check_doc_fn) instead of a second walk. Only
    /// consumed behind the `deep` feature.
    #[cfg_attr(not(feature = "deep"), allow(dead_code))]
    pub_fn_candidates: Vec<PubFnCandidate>,
}

impl ApiSurfaceVisitor<'_> {
    fn current_item_path(&self) -> String {
        qualified_item_path(self.file, &self.path)
    }

    fn current_in_trait_impl(&self) -> bool {
        self.in_trait_impl.last().copied().unwrap_or(false)
    }

    /// Shared finding constructor for both rules this module reports —
    /// `rule_id` picks the rule, `evidence` is `None` for
    /// `undocumented-public-item` and `Some(json!({"kind": ...}))` for
    /// `semver-hazard` (mirrors [`crate::rules::slop_structural`]'s single
    /// `abstraction_finding` helper backing several `evidence.kind`s).
    fn record(
        &mut self,
        rule_id: &str,
        span: proc_macro2::Span,
        evidence: Option<serde_json::Value>,
    ) {
        let item_path = self.current_item_path();
        self.findings.push(build_finding(
            self.file,
            rule_id,
            span,
            Severity::Info,
            item_path,
            evidence,
        ));
    }

    /// Whether an item is `pub` and not gated by `#[cfg(test)]` (on itself or
    /// an enclosing item) — the shared population check both
    /// [`check_doc`](Self::check_doc) and
    /// [`check_doc_fn`](Self::check_doc_fn) (for [`PubFnCandidate`]
    /// collection) test against, so the two can't independently drift.
    fn is_checkable_pub_item(&self, vis: &Visibility, attrs: &[Attribute]) -> bool {
        if self.cfg_test_depth > 0 || attrs_have_cfg_test(attrs) {
            return false;
        }
        matches!(vis, Visibility::Public(_))
    }

    /// Shared `cfg_test_depth`/`path` bookkeeping around `visit_item_fn`,
    /// `visit_impl_item_fn`, and `visit_item_impl` — identical in each except
    /// which name is pushed onto `path`, whether/how
    /// [`check_doc_fn`](Self::check_doc_fn) is called, and which
    /// `syn::visit` traversal function walks the children. Returns whether
    /// `attrs` is `#[cfg(test)]`-gated, to be undone by [`Self::exit_scope`].
    fn enter_scope(&mut self, attrs: &[Attribute], path_segment: String) -> bool {
        let gated = attrs_have_cfg_test(attrs);
        if gated {
            self.cfg_test_depth += 1;
        }
        self.path.push(path_segment);
        gated
    }

    /// Undoes [`Self::enter_scope`]'s `path`/`cfg_test_depth` bookkeeping.
    fn exit_scope(&mut self, gated: bool) {
        self.path.pop();
        if gated {
            self.cfg_test_depth -= 1;
        }
    }

    /// A `pub` item with no `#[doc = ...]` attribute (see [`has_doc_comment`]),
    /// unless it — or an enclosing item — is gated by `#[cfg(test)]`. Callers
    /// pass the item's own attrs and span *before* pushing that item's own
    /// name onto `path`, so `current_item_path` already reflects it.
    ///
    /// Also increments `item_count` for every `pub`, non-`#[cfg(test)]`-gated
    /// item this visits, whether or not it ends up flagged — that is exactly
    /// the api-surface-size count (see [`ApiSurfaceSize`]): the same item
    /// kinds this rule already checks, counted once each instead of walked a
    /// second time.
    fn check_doc(&mut self, vis: &Visibility, attrs: &[Attribute], span: proc_macro2::Span) {
        if !self.is_checkable_pub_item(vis, attrs) {
            return;
        }
        self.item_count += 1;
        if has_doc_comment(attrs) {
            return;
        }
        self.record(UNDOCUMENTED_PUBLIC_ITEM_RULE, span, None);
    }

    /// Same as [`check_doc`](Self::check_doc), additionally skipping a
    /// `#[test]`-attributed function (see todo.md §I, point 3), and
    /// collecting a [`PubFnCandidate`] for the Deep Tier's
    /// `leaked_dependency_type` sub-case when the function is in scope for
    /// it. `ident_span` is the function's own identifier span (narrower than
    /// `span`, which covers the whole item) — see [`PubFnCandidate`].
    fn check_doc_fn(
        &mut self,
        vis: &Visibility,
        attrs: &[Attribute],
        span: proc_macro2::Span,
        ident_span: proc_macro2::Span,
    ) {
        if has_test_attr(attrs) {
            return;
        }
        if self.is_checkable_pub_item(vis, attrs) {
            self.pub_fn_candidates.push(PubFnCandidate {
                item_path: self.current_item_path(),
                file: self.file.to_path_buf(),
                ident_span,
            });
        }
        self.check_doc(vis, attrs, span);
    }

    /// `semver-hazard` sub-case A: a `pub enum` with at least two variants
    /// and no `#[non_exhaustive]` attribute — adding a variant is a breaking
    /// change for an external exhaustive `match` with no wildcard arm. Same
    /// `#[cfg(test)]` exemption as [`check_doc`](Self::check_doc); a
    /// single-variant enum is exempt (see the module's `semver-hazard`
    /// scope section — a lone variant is usually deliberate, e.g. a wrapper
    /// pattern).
    fn check_semver_hazard_enum(&mut self, node: &ItemEnum) {
        if !self.is_checkable_pub_item(&node.vis, &node.attrs) {
            return;
        }
        if node.variants.len() < 2 || has_non_exhaustive(&node.attrs) {
            return;
        }
        self.record(
            SEMVER_HAZARD_RULE,
            node.span(),
            Some(json!({
                "kind": "missing_non_exhaustive_enum",
                "variant_count": node.variants.len(),
            })),
        );
    }

    /// `semver-hazard` sub-case B: a `pub struct` with at least one `pub`
    /// field and no `#[non_exhaustive]` attribute — a new or removed field
    /// is a breaking change for struct-literal syntax at consumers. A unit
    /// struct, or one whose fields are all private, already encapsulates its
    /// layout and is not checked. Same `#[cfg(test)]` exemption as
    /// [`check_doc`](Self::check_doc).
    fn check_semver_hazard_struct(&mut self, node: &ItemStruct) {
        if !self.is_checkable_pub_item(&node.vis, &node.attrs) {
            return;
        }
        if has_non_exhaustive(&node.attrs) {
            return;
        }
        let pub_field_count = node
            .fields
            .iter()
            .filter(|field| matches!(field.vis, Visibility::Public(_)))
            .count();
        if pub_field_count == 0 {
            return;
        }
        self.record(
            SEMVER_HAZARD_RULE,
            node.span(),
            Some(json!({
                "kind": "missing_non_exhaustive_struct_fields",
                "pub_field_count": pub_field_count,
            })),
        );
    }
}

/// Whether any attribute in `attrs` is a `#[doc = ...]` (covers both `///`
/// doc comments and explicit `#[doc]` attributes — `syn` desugars both the
/// same way).
pub(crate) fn has_doc_comment(attrs: &[Attribute]) -> bool {
    attrs.iter().any(|attr| attr.path().is_ident("doc"))
}

/// Builds the `Finding` both this module's [`ApiSurfaceVisitor::record`] and
/// [`crate::rules::slop::SlopVisitor::record_with_evidence`] push onto their own
/// `findings` vec — the identical `Finding` literal construction each
/// otherwise duplicated verbatim.
pub(crate) fn build_finding(
    file: &Path,
    rule_id: &str,
    span: proc_macro2::Span,
    severity: Severity,
    item_path: String,
    evidence: Option<serde_json::Value>,
) -> Finding {
    let start = span.start();
    let rule = crate::finding::RuleId::from(rule_id);
    let evidence_class = crate::finding::evidence_class_for_rule(&rule);
    Finding {
        id: format!("{rule}:{}:{}:{}", file.display(), start.line, start.column).into(),
        rule,
        severity,
        location: Location {
            file: file.to_path_buf(),
            line: crate::finding::OneBasedLine::new(start.line)
                .expect("proc-macro2 span lines are 1-based"),
            item_path,
        },
        evidence_class,
        origin: Origin::Code,
        evidence,
        limitations: None,
        caused_by: Vec::new(),
        causes: Vec::new(),
    }
}

/// Whether any attribute in `attrs` is `#[non_exhaustive]` — the exact
/// syntax fact both `semver-hazard` sub-cases turn on.
fn has_non_exhaustive(attrs: &[Attribute]) -> bool {
    attrs
        .iter()
        .any(|attr| attr.path().is_ident("non_exhaustive"))
}

/// Whether `attrs` contains a `#[cfg(...)]` attribute whose predicate
/// mentions `test` as a whole word (`#[cfg(test)]`, `#[cfg(any(test, ...))]`,
/// `#[cfg(all(test, ...))]`) — a crude but conservative parse of the
/// attribute's raw tokens, not a full `cfg` predicate evaluator (mirrors
/// `deps.rs`'s private `attrs_have_cfg_test`, kept local for the same reason
/// `type_name` is).
fn attrs_have_cfg_test(attrs: &[Attribute]) -> bool {
    attrs.iter().any(|attr| {
        if !attr.path().is_ident("cfg") {
            return false;
        }
        let syn::Meta::List(list) = &attr.meta else {
            return false;
        };
        list.tokens
            .to_string()
            .split(|c: char| !c.is_alphanumeric() && c != '_')
            .any(|word| word == "test")
    })
}

/// Generates callbacks for module-scoped items that share the same
/// cfg(test), path, documentation, and traversal lifecycle. The caller
/// supplies only the item-specific semantic check, if any.
macro_rules! visit_documented_scoped_item {
    ($method:ident, $node:ty, $traverse:ident) => {
        fn $method(&mut self, node: &'ast $node) {
            let gated = attrs_have_cfg_test(&node.attrs);
            if gated {
                self.cfg_test_depth += 1;
            }
            self.path.push(node.ident.to_string());
            self.check_doc(&node.vis, &node.attrs, node.span());
            visit::$traverse(self, node);
            self.path.pop();
            if gated {
                self.cfg_test_depth -= 1;
            }
        }
    };
    ($method:ident, $node:ty, $traverse:ident, $extra:ident) => {
        fn $method(&mut self, node: &'ast $node) {
            let gated = attrs_have_cfg_test(&node.attrs);
            if gated {
                self.cfg_test_depth += 1;
            }
            self.path.push(node.ident.to_string());
            self.check_doc(&node.vis, &node.attrs, node.span());
            self.$extra(node);
            visit::$traverse(self, node);
            self.path.pop();
            if gated {
                self.cfg_test_depth -= 1;
            }
        }
    };
}

/// Generates callbacks for leaf declarations, whose child syntax is walked
/// after removing the declaration name from the enclosing item path.
macro_rules! visit_documented_leaf_item {
    ($method:ident, $node:ty, $traverse:ident) => {
        fn $method(&mut self, node: &'ast $node) {
            let gated = attrs_have_cfg_test(&node.attrs);
            if gated {
                self.cfg_test_depth += 1;
            }
            self.path.push(node.ident.to_string());
            self.check_doc(&node.vis, &node.attrs, node.span());
            self.path.pop();
            visit::$traverse(self, node);
            if gated {
                self.cfg_test_depth -= 1;
            }
        }
    };
}

impl<'ast> Visit<'ast> for ApiSurfaceVisitor<'_> {
    fn visit_item_mod(&mut self, node: &'ast ItemMod) {
        let gated = attrs_have_cfg_test(&node.attrs);
        if gated {
            self.cfg_test_depth += 1;
        }
        if node.content.is_some() {
            self.path.push(node.ident.to_string());
            visit::visit_item_mod(self, node);
            self.path.pop();
        } else {
            visit::visit_item_mod(self, node);
        }
        if gated {
            self.cfg_test_depth -= 1;
        }
    }

    fn visit_item_impl(&mut self, node: &'ast ItemImpl) {
        let gated = self.enter_scope(&node.attrs, type_name(&node.self_ty));
        self.in_trait_impl.push(node.trait_.is_some());
        visit::visit_item_impl(self, node);
        self.in_trait_impl.pop();
        self.exit_scope(gated);
    }

    visit_documented_scoped_item!(visit_item_trait, ItemTrait, visit_item_trait);
    visit_documented_scoped_item!(
        visit_item_struct,
        ItemStruct,
        visit_item_struct,
        check_semver_hazard_struct
    );
    visit_documented_scoped_item!(
        visit_item_enum,
        ItemEnum,
        visit_item_enum,
        check_semver_hazard_enum
    );
    visit_documented_leaf_item!(visit_item_const, ItemConst, visit_item_const);
    visit_documented_leaf_item!(visit_item_static, ItemStatic, visit_item_static);
    visit_documented_leaf_item!(visit_item_type, ItemType, visit_item_type);

    fn visit_item_fn(&mut self, node: &'ast ItemFn) {
        let gated = self.enter_scope(&node.attrs, node.sig.ident.to_string());
        self.check_doc_fn(&node.vis, &node.attrs, node.span(), node.sig.ident.span());
        visit::visit_item_fn(self, node);
        self.exit_scope(gated);
    }

    fn visit_impl_item_fn(&mut self, node: &'ast ImplItemFn) {
        let gated = self.enter_scope(&node.attrs, node.sig.ident.to_string());
        if !self.current_in_trait_impl() {
            self.check_doc_fn(&node.vis, &node.attrs, node.span(), node.sig.ident.span());
        }
        visit::visit_impl_item_fn(self, node);
        self.exit_scope(gated);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ingest::SourceFile;
    use crate::test_util::TempDir;

    fn write_and_analyze(dir: &TempDir, source: &str) -> Vec<Finding> {
        let file = dir.join("lib.rs");
        std::fs::write(&file, source).unwrap();
        analyze_file(&file).unwrap()
    }

    #[test]
    fn pub_fn_without_doc_comment_is_flagged() {
        let dir = TempDir::new("api-surface-pub-fn");
        let findings = write_and_analyze(&dir, "pub fn undocumented() {}\n");
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule, UNDOCUMENTED_PUBLIC_ITEM_RULE);
        assert_eq!(findings[0].severity, Severity::Info);
        assert_eq!(
            findings[0].evidence_class,
            crate::finding::EvidenceClass::DerivedFact
        );
    }

    /// The registry's curated `example.before` for this rule (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn undocumented_public_item_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(UNDOCUMENTED_PUBLIC_ITEM_RULE)
            .expect("undocumented-public-item has a registry entry")
            .example
            .expect("undocumented-public-item has a curated example")
            .before;
        let dir = TempDir::new("api-surface-undocumented-public-item-registry-example");
        let findings = write_and_analyze(&dir, example);
        assert_eq!(
            findings
                .iter()
                .filter(|f| f.rule == UNDOCUMENTED_PUBLIC_ITEM_RULE)
                .count(),
            1
        );
    }

    #[test]
    fn pub_struct_and_pub_enum_without_doc_comment_are_flagged() {
        let dir = TempDir::new("api-surface-pub-struct-enum");
        let findings = write_and_analyze(&dir, "pub struct Foo;\n\npub enum Bar { A, B }\n");
        // `Bar` also has 2 variants and no `#[non_exhaustive]`, so it additionally
        // fires `semver-hazard` — filter down to this test's own rule.
        let undocumented: Vec<_> = findings
            .iter()
            .filter(|f| f.rule == UNDOCUMENTED_PUBLIC_ITEM_RULE)
            .collect();
        assert_eq!(undocumented.len(), 2);
    }

    #[test]
    fn pub_item_with_doc_comment_is_not_flagged() {
        let dir = TempDir::new("api-surface-documented");
        let findings = write_and_analyze(
            &dir,
            r#"
/// Does the thing.
pub fn documented() {}

/// A documented struct.
pub struct Documented;
"#,
        );
        assert!(findings.is_empty(), "unexpected findings: {findings:?}");
    }

    #[test]
    fn non_pub_item_is_not_flagged() {
        let dir = TempDir::new("api-surface-non-pub");
        let findings = write_and_analyze(
            &dir,
            "pub(crate) fn crate_visible() {}\n\nfn private() {}\n",
        );
        assert!(findings.is_empty(), "unexpected findings: {findings:?}");
    }

    #[test]
    fn method_in_trait_impl_without_own_doc_comment_is_not_flagged() {
        let dir = TempDir::new("api-surface-trait-impl");
        let findings = write_and_analyze(
            &dir,
            r#"
pub struct Foo;

pub trait Greet {
    fn hi(&self);
}

impl Greet for Foo {
    fn hi(&self) {}
}
"#,
        );
        // `Foo` and `Greet` are pub without doc comments (2 findings); the
        // trait-impl method `hi` is exempt.
        assert_eq!(findings.len(), 2);
        assert!(
            findings.iter().all(|f| f.location.item_path != "Foo::hi"),
            "trait-impl method must not be flagged: {findings:?}"
        );
    }

    #[test]
    fn pub_method_in_inherent_impl_without_doc_comment_is_flagged() {
        let dir = TempDir::new("api-surface-inherent-impl");
        let findings = write_and_analyze(
            &dir,
            r#"
pub struct Foo;

impl Foo {
    pub fn bar(&self) {}
}
"#,
        );
        assert!(
            findings.iter().any(|f| f.location.item_path == "Foo::bar"),
            "inherent-impl pub method must be flagged: {findings:?}"
        );
    }

    #[test]
    fn test_attributed_function_is_not_flagged() {
        let dir = TempDir::new("api-surface-test-fn");
        let findings = write_and_analyze(
            &dir,
            r#"
#[test]
pub fn a_test() {
    assert!(true);
}
"#,
        );
        assert!(findings.is_empty(), "unexpected findings: {findings:?}");
    }

    #[test]
    fn cfg_test_gated_item_is_not_flagged() {
        let dir = TempDir::new("api-surface-cfg-test");
        let findings = write_and_analyze(
            &dir,
            r#"
#[cfg(test)]
mod tests {
    pub fn helper() {}
}
"#,
        );
        assert!(findings.is_empty(), "unexpected findings: {findings:?}");
    }

    fn authored(path: PathBuf) -> SourceFile {
        SourceFile {
            path,
            kind: crate::ingest::SourceKind::Authored,
        }
    }

    /// A minimal [`CrateInfo`] fixture wrapping `source_files` — the other
    /// fields aren't read by this module's own analysis (mirrors
    /// `deps.rs`'s own `CrateInfo` test fixtures).
    fn test_crate(dir: &TempDir, name: &str, source_files: Vec<SourceFile>) -> CrateInfo {
        CrateInfo {
            name: name.to_string(),
            version: "0.1.0".to_string(),
            manifest_path: dir.join("Cargo.toml"),
            root: dir.to_path_buf(),
            source_files,
            entry_points: Vec::new(),
            dependencies: Vec::new(),
        }
    }

    #[test]
    fn analyze_workspace_skips_generated_files_unless_included() {
        let dir = TempDir::new("api-surface-generated");
        let authored_file = dir.join("lib.rs");
        let generated_file = dir.join("schema.rs");
        std::fs::write(&authored_file, "pub fn ok() {}\n").unwrap();
        std::fs::write(&generated_file, "pub fn also_ok() {}\n").unwrap();

        let krate = test_crate(
            &dir,
            "fixture",
            vec![
                authored(authored_file),
                SourceFile {
                    path: generated_file,
                    kind: crate::ingest::SourceKind::Generated,
                },
            ],
        );

        let excluded = analyze_workspace([&krate], false);
        assert_eq!(excluded.findings.len(), 1);
        assert_eq!(excluded.excluded_generated, 1);
        assert_eq!(excluded.api_surface_size.per_crate["fixture"], 1);

        let included = analyze_workspace([&krate], true);
        assert_eq!(included.findings.len(), 2);
        assert_eq!(included.excluded_generated, 0);
        assert_eq!(included.api_surface_size.per_crate["fixture"], 2);
    }

    #[test]
    fn analyze_workspace_counts_public_items_per_crate() {
        let dir = TempDir::new("api-surface-size");
        let file = dir.join("lib.rs");
        std::fs::write(
            &file,
            "/// Doc.\npub fn a() {}\n\n/// Doc.\npub fn b() {}\n\nfn private() {}\n",
        )
        .unwrap();
        let krate = test_crate(&dir, "fixture", vec![authored(file)]);

        let report = analyze_workspace([&krate], false);
        assert!(
            report.findings.is_empty(),
            "unexpected findings: {:?}",
            report.findings
        );
        assert_eq!(report.api_surface_size.per_crate.len(), 1);
        assert_eq!(report.api_surface_size.per_crate["fixture"], 2);
    }

    #[test]
    fn analyze_workspace_counts_each_crate_separately() {
        let dir_a = TempDir::new("api-surface-size-crate-a");
        let file_a = dir_a.join("lib.rs");
        std::fs::write(&file_a, "/// Doc.\npub fn a() {}\n").unwrap();
        let krate_a = test_crate(&dir_a, "crate-a", vec![authored(file_a)]);

        let dir_b = TempDir::new("api-surface-size-crate-b");
        let file_b = dir_b.join("lib.rs");
        std::fs::write(
            &file_b,
            "/// Doc.\npub fn a() {}\n\n/// Doc.\npub fn b() {}\n\n/// Doc.\npub fn c() {}\n",
        )
        .unwrap();
        let krate_b = test_crate(&dir_b, "crate-b", vec![authored(file_b)]);

        let report = analyze_workspace([&krate_a, &krate_b], false);
        assert_eq!(report.api_surface_size.per_crate.len(), 2);
        assert_eq!(report.api_surface_size.per_crate["crate-a"], 1);
        assert_eq!(report.api_surface_size.per_crate["crate-b"], 3);
    }

    #[test]
    fn size_trend_reports_delta_against_a_baseline() {
        let mut current = ApiSurfaceSize::default();
        current.per_crate.insert("fixture".to_string(), 5);
        let baseline = HashMap::from([("fixture".to_string(), 3)]);

        let trend = size_trend(&current, Some(&baseline));
        assert_eq!(trend.len(), 1);
        assert_eq!(trend[0].crate_name, "fixture");
        assert_eq!(trend[0].item_count, 5);
        assert_eq!(trend[0].delta, Some(2));
    }

    #[test]
    fn size_trend_is_not_comparable_without_a_baseline_size() {
        let mut current = ApiSurfaceSize::default();
        current.per_crate.insert("fixture".to_string(), 5);

        let trend = size_trend(&current, None);
        assert_eq!(trend.len(), 1);
        assert_eq!(trend[0].item_count, 5);
        assert_eq!(trend[0].delta, None);
    }

    #[test]
    fn analyze_file_reports_parse_errors() {
        let dir = TempDir::new("api-surface-parse-error");
        let file = dir.join("broken.rs");
        std::fs::write(&file, "pub fn broken( {").unwrap();

        let err = analyze_file(&file).unwrap_err();
        match err {
            ApiSurfaceError::Parse(path, _) => assert_eq!(path, file),
            other => panic!("expected a parse error, got {other:?}"),
        }
    }

    fn semver_hazard_findings(findings: &[Finding]) -> Vec<&Finding> {
        findings
            .iter()
            .filter(|f| f.rule == SEMVER_HAZARD_RULE)
            .collect()
    }

    #[test]
    fn pub_enum_with_two_variants_and_no_non_exhaustive_is_flagged() {
        let dir = TempDir::new("api-surface-semver-enum-flagged");
        let findings = write_and_analyze(
            &dir,
            r#"
/// Doc.
pub enum Bar {
    A,
    B,
}
"#,
        );
        let hits = semver_hazard_findings(&findings);
        assert_eq!(hits.len(), 1);
        assert_eq!(
            hits[0].evidence.as_ref().unwrap()["kind"],
            "missing_non_exhaustive_enum"
        );
        assert_eq!(hits[0].evidence.as_ref().unwrap()["variant_count"], 2);
        assert_eq!(hits[0].severity, Severity::Info);
        assert_eq!(
            hits[0].evidence_class,
            crate::finding::EvidenceClass::DerivedFact
        );
    }

    /// The registry's curated `example.before` for this rule (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn semver_hazard_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(SEMVER_HAZARD_RULE)
            .expect("semver-hazard has a registry entry")
            .example
            .expect("semver-hazard has a curated example")
            .before;
        let dir = TempDir::new("api-surface-semver-hazard-registry-example");
        let findings = write_and_analyze(&dir, example);
        assert_eq!(semver_hazard_findings(&findings).len(), 1);
    }

    #[test]
    fn pub_enum_with_non_exhaustive_is_not_flagged() {
        let dir = TempDir::new("api-surface-semver-enum-exempt");
        let findings = write_and_analyze(
            &dir,
            r#"
/// Doc.
#[non_exhaustive]
pub enum Bar {
    A,
    B,
}
"#,
        );
        assert!(semver_hazard_findings(&findings).is_empty());
    }

    #[test]
    fn pub_enum_with_single_variant_is_not_flagged() {
        let dir = TempDir::new("api-surface-semver-enum-single-variant");
        let findings = write_and_analyze(
            &dir,
            r#"
/// Doc.
pub enum Bar {
    A,
}
"#,
        );
        assert!(semver_hazard_findings(&findings).is_empty());
    }

    #[test]
    fn pub_struct_with_pub_field_and_no_non_exhaustive_is_flagged() {
        let dir = TempDir::new("api-surface-semver-struct-flagged");
        let findings = write_and_analyze(
            &dir,
            r#"
/// Doc.
pub struct Foo {
    pub value: i32,
}
"#,
        );
        let hits = semver_hazard_findings(&findings);
        assert_eq!(hits.len(), 1);
        assert_eq!(
            hits[0].evidence.as_ref().unwrap()["kind"],
            "missing_non_exhaustive_struct_fields"
        );
        assert_eq!(hits[0].evidence.as_ref().unwrap()["pub_field_count"], 1);
    }

    #[test]
    fn pub_struct_with_non_exhaustive_is_not_flagged() {
        let dir = TempDir::new("api-surface-semver-struct-exempt");
        let findings = write_and_analyze(
            &dir,
            r#"
/// Doc.
#[non_exhaustive]
pub struct Foo {
    pub value: i32,
}
"#,
        );
        assert!(semver_hazard_findings(&findings).is_empty());
    }

    #[test]
    fn pub_struct_with_only_private_fields_is_not_flagged() {
        let dir = TempDir::new("api-surface-semver-struct-private-fields");
        let findings = write_and_analyze(
            &dir,
            r#"
/// Doc.
pub struct Foo {
    value: i32,
}
"#,
        );
        assert!(semver_hazard_findings(&findings).is_empty());
    }

    #[test]
    fn tuple_and_unit_structs_are_not_flagged() {
        let dir = TempDir::new("api-surface-semver-struct-tuple-unit");
        let findings = write_and_analyze(
            &dir,
            r#"
/// Doc.
pub struct Tuple(i32);

/// Doc.
pub struct Unit;
"#,
        );
        assert!(semver_hazard_findings(&findings).is_empty());
    }

    #[test]
    fn analyze_workspace_hides_semver_hazard_in_generated_files_by_default() {
        let dir = TempDir::new("api-surface-semver-generated");
        let generated_file = dir.join("schema.rs");
        std::fs::write(
            &generated_file,
            r#"
/// Doc.
pub enum Bar {
    A,
    B,
}
"#,
        )
        .unwrap();

        let krate = test_crate(
            &dir,
            "fixture",
            vec![SourceFile {
                path: generated_file,
                kind: crate::ingest::SourceKind::Generated,
            }],
        );

        let excluded = analyze_workspace([&krate], false);
        assert!(semver_hazard_findings(&excluded.findings).is_empty());
        assert_eq!(excluded.excluded_generated, 1);

        let included = analyze_workspace([&krate], true);
        assert_eq!(semver_hazard_findings(&included.findings).len(), 1);
    }
}