big-code-analysis 2.1.0

Tool to compute and export code metrics
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
//! Which spaces carry an `npm` / `npa` block in serialized output.
//!
//! These assertions cannot be written with `check_metrics`. That helper
//! hands back `spaces::CodeMetrics`, whose `npm` / `npa` fields are plain
//! structs, and the `insta` snapshots in `npm.rs` / `npa.rs` serialize
//! those structs through `serialize_via_wire!`, which bypasses the
//! `Option`. Both surfaces are blind to the emission gate by design — it
//! lives one layer out, in `wire::CodeMetrics::from`, and the only way to
//! observe it is to serialize a whole [`FuncSpace`] and look at the keys.
//!
//! That blindness is exactly how #1197 shipped: `Npm` and `Npa` enabled
//! themselves on `Checker::is_func_space`, which means "opens a space",
//! not "is a scope that owns members". Seven of the ten languages
//! therefore emitted an all-zero block on every ordinary method, and
//! #1184 added Kotlin property accessors and `init` / `static` blocks to
//! the list, next to sibling methods that had none.
//!
//! The rule is [`SpaceKind::is_member_scope`], which `wmc` already used:
//! containers and the file unit carry the block, a function space never
//! does. Both directions are asserted below, because narrowing too far
//! would silently delete the whole-file roll-up rather than the all-zero
//! noise.
//!
//! #1197 left the rule a convention: it routed ten languages through a
//! shared predicate and let the other seven keep enabling from their own
//! node kinds. Those seven disagreed with it in both directions — a Go or
//! Rust `struct` declared inside a function put the block on that
//! *function* space, and a file whose only container sat inside a
//! function left the root without one, so the counts were serialized
//! nowhere. #1203 removed the choice: the space's own kind is now the
//! only input, recorded once per space by the walker's finalize step
//! (`spaces::compute::note_member_scope`). Every language is
//! covered below for that reason — the point is no longer that ten obey
//! a predicate, but that the rule has no per-language surface left to
//! deviate on.

use serde_json::Value;

use crate::spaces::SpaceKind;
use crate::test_support::{assert_fixtures_present, space_verbatim};
use crate::{LANG, MetricsOptions};

/// A serialized space, flattened to what these tests assert on.
struct Emitted {
    kind: SpaceKind,
    /// `None` for the unit root, which `space_verbatim` analyses without a
    /// filename. Modelled as absent rather than defaulted to `""` so a
    /// *nested* space that lost its name fails a lookup below instead of
    /// quietly matching nothing.
    name: Option<String>,
    has_npm: bool,
    has_npa: bool,
    /// Tracked alongside the other two because `wmc`'s emission is
    /// *narrower* than theirs in two language-level ways, and nothing
    /// pinned that until #1220 — which is how the book and STABILITY.md
    /// came to describe all three blocks with one rule.
    has_wmc: bool,
}

/// Analyses `source` and flattens every space in the serialized tree,
/// root first.
///
/// Serializing the [`FuncSpace`](crate::spaces::FuncSpace) rather than
/// reading `space.metrics` is the point: `metrics.npm` is always present
/// as a struct, and only the JSON key is gated.
fn emitted_spaces(lang: LANG, source: &str) -> Vec<Emitted> {
    let space = space_verbatim(lang, source.as_bytes(), MetricsOptions::default());
    let value = serde_json::to_value(&space).expect("FuncSpace must serialize");
    let mut out = Vec::new();
    flatten(&value, &mut out);
    out
}

fn flatten(value: &Value, out: &mut Vec<Emitted>) {
    let metrics = value["metrics"]
        .as_object()
        .expect("every space serializes a metrics object");
    // `expect` rather than a default on `kind`: a space missing it would
    // read as `Unknown`, which no assertion below could tell apart from a
    // space these tests are meant to skip.
    let kind = value["kind"]
        .as_str()
        .expect("every space serializes a kind");
    out.push(Emitted {
        kind: SpaceKind::from_serialized(kind),
        name: value["name"].as_str().map(str::to_owned),
        has_npm: metrics.contains_key("npm"),
        has_npa: metrics.contains_key("npa"),
        has_wmc: metrics.contains_key("wmc"),
    });
    for child in value["spaces"].as_array().into_iter().flatten() {
        flatten(child, out);
    }
}

/// One fixture per language that has an `Npm` / `Npa` impl.
///
/// Each carries a container with one public method and one public
/// attribute, at least one ordinary method, and — where the grammar has
/// one — a #1184 construct (`get`/`set`/`init`/`static`), so a single
/// fixture exercises both halves of the defect.
struct Fixture {
    lang: LANG,
    /// Names of the container spaces that must carry both blocks.
    ///
    /// Empty for Go alone, whose `Getter` has no container `SpaceKind` —
    /// `type … struct` and `type … interface` open no space, so a Go
    /// file's `npm` / `npa` live on the unit root and nowhere else.
    /// [`containers_emit_npm_and_npa`] names Go rather than skipping an
    /// empty list quietly, since a list that silently became empty for
    /// any other language would make that test vacuous for it.
    containers: &'static [&'static str],
    source: &'static str,
}

/// The fixture for `lang`.
///
/// Looked up by language rather than by index, so reordering [`FIXTURES`]
/// cannot silently pair a language with another's source.
fn fixture_source(lang: LANG) -> &'static str {
    FIXTURES
        .iter()
        .find(|f| f.lang == lang)
        .unwrap_or_else(|| panic!("no fixture for {lang:?}"))
        .source
}

/// Every space as `(kind, name)`, for an assertion message.
fn summary(spaces: &[Emitted]) -> Vec<(SpaceKind, Option<&str>)> {
    spaces.iter().map(|s| (s.kind, s.name.as_deref())).collect()
}

/// The one space named `name`, or a failure naming every space there was.
///
/// Asserting the match count rather than taking the first hit is what
/// stops a rename or a lost space from making the caller's assertions
/// vacuous.
#[track_caller]
fn only_space<'a>(lang: LANG, spaces: &'a [Emitted], name: &str) -> &'a Emitted {
    let found: Vec<&Emitted> = spaces
        .iter()
        .filter(|s| s.name.as_deref() == Some(name))
        .collect();
    assert_eq!(
        found.len(),
        1,
        "{lang:?}: expected exactly one space named {name:?}, got {:?}",
        summary(spaces)
    );
    found[0]
}

const FIXTURES: &[Fixture] = &[
    #[cfg(feature = "kotlin")]
    Fixture {
        lang: LANG::Kotlin,
        containers: &["C", "I"],
        source: "\
interface I {
    fun q(): Int
}
class C : I {
    var p: Int = 0
        get() = field
        set(v) { field = v }
    init { p = 1 }
    override fun q(): Int { return p }
}
",
    },
    #[cfg(feature = "java")]
    Fixture {
        lang: LANG::Java,
        containers: &["C", "I"],
        source: "\
interface I {
    int q();
}
class C implements I {
    public int a = 1;
    static { System.out.println(\"x\"); }
    public int q() { return a; }
}
",
    },
    #[cfg(feature = "groovy")]
    Fixture {
        lang: LANG::Groovy,
        containers: &["C", "I"],
        source: "\
interface I {
    int q()
}
class C implements I {
    public int a = 1
    static { println 'x' }
    int q() { return a }
}
",
    },
    #[cfg(feature = "javascript")]
    Fixture {
        lang: LANG::Javascript,
        containers: &["C"],
        source: "\
class C {
    a = 1;
    static { this.b = 2; }
    q() { return this.a; }
}
function top(x) { return x; }
",
    },
    #[cfg(feature = "mozjs")]
    Fixture {
        lang: LANG::Mozjs,
        containers: &["C"],
        source: "\
class C {
    a = 1;
    static { this.b = 2; }
    q() { return this.a; }
}
function top(x) { return x; }
",
    },
    #[cfg(feature = "typescript")]
    Fixture {
        lang: LANG::Typescript,
        containers: &["C", "I"],
        source: "\
interface I {
    q(): number;
}
class C implements I {
    public a: number = 1;
    static { }
    public q(): number { return this.a; }
}
function top(x: number): number { return x; }
",
    },
    #[cfg(feature = "typescript")]
    Fixture {
        lang: LANG::Tsx,
        containers: &["C", "I"],
        source: "\
interface I {
    q(): number;
}
class C implements I {
    public a: number = 1;
    static { }
    public q(): number { return this.a; }
}
function top(x: number): number { return x; }
",
    },
    #[cfg(feature = "csharp")]
    Fixture {
        lang: LANG::Csharp,
        containers: &["C", "I"],
        source: "\
interface I {
    int Q();
}
class C : I {
    public int A = 1;
    private int[] _v = new int[4];
    // An expression-bodied property and an accessor-less indexer are
    // `is_func_space` and `SpaceKind::Function` (#464, #472), so before
    // #1197 each carried an all-zero block beside `Q`, which had none.
    public int W => A;
    public int this[int i] => _v[i];
    public int Q() { return A; }
}
",
    },
    #[cfg(feature = "php")]
    Fixture {
        lang: LANG::Php,
        containers: &["C", "I"],
        source: "\
<?php
interface I {
    public function q();
}
class C implements I {
    public $a = 1;
    public function q() { return $this->a; }
}
function top($x) { return $x; }
",
    },
    #[cfg(feature = "ruby")]
    Fixture {
        lang: LANG::Ruby,
        // A Ruby `module` is `SpaceKind::Namespace`, which is a container.
        containers: &["M", "C"],
        source: "\
module M
  class C
    attr_accessor :a
    def q
      @a
    end
  end
end
",
    },
    // The seven below gated on their own node kinds until #1203. Each
    // fixture therefore declares a container *inside a function body* as
    // well as at file scope: that is the shape whose block used to land
    // on the function space, and — where the language had no other
    // container — the shape whose counts reached no serialized block at
    // all.
    #[cfg(feature = "rust")]
    Fixture {
        lang: LANG::Rust,
        containers: &["T", "S"],
        source: "\
pub struct S {
    pub a: u8,
    b: u8,
}

pub trait T {
    fn q(&self) -> u8;
}

impl S {
    pub fn m(&self) -> u8 { self.a }
}

fn top() -> u8 {
    struct Inner { pub x: u8 }
    Inner { x: 1 }.x
}
",
    },
    // Go is the one language with no container `SpaceKind` at all; see
    // `Fixture::containers`.
    #[cfg(feature = "go")]
    Fixture {
        lang: LANG::Go,
        containers: &[],
        source: "\
package main

type S struct {
    Pub  int
    priv int
}

type I interface {
    Speak() string
}

func (s S) Method() int { return s.Pub }

func Outer() int {
    type inner struct {
        X int
    }
    return inner{X: 1}.X
}
",
    },
    #[cfg(feature = "python")]
    Fixture {
        lang: LANG::Python,
        containers: &["C", "Inner"],
        source: "\
class C:
    a = 1

    def q(self):
        return self.a

def top(x):
    class Inner:
        b = 2
    return Inner
",
    },
    #[cfg(feature = "cpp")]
    Fixture {
        lang: LANG::Cpp,
        containers: &["N", "C"],
        source: "\
namespace N {
class C {
public:
    int a;
    int q() { return a; }
};
}

int top() { return 0; }
",
    },
    // Mozcpp owns no file extension, so nothing routes to it and it gets
    // no integration-snapshot coverage at all — the case
    // `.claude/rules/grammar-dispatch.md` says to pin against its
    // extension-owning sibling. `cpp_mozcpp_parity` does not cover this:
    // it compares metric *values* through `metric_sums`, so it would not
    // notice Mozcpp losing both blocks to a stray `HAS_MEMBERS = false`
    // on its impl — verified by perturbation, which fails here and
    // nowhere else. (Adding Mozcpp to the `implement_metric_trait!`
    // no-op list is *not* the hazard: it collides with the real impl and
    // fails to compile.) Same source as the Cpp fixture, deliberately,
    // so a divergence reads as one.
    #[cfg(feature = "mozcpp")]
    Fixture {
        lang: LANG::Mozcpp,
        containers: &["N", "C"],
        source: "\
namespace N {
class C {
public:
    int a;
    int q() { return a; }
};
}

int top() { return 0; }
",
    },
    #[cfg(feature = "objc")]
    Fixture {
        lang: LANG::Objc,
        // Distinct names deliberately: an `@interface C` and its
        // `@implementation C` open two spaces with the *same* name, which
        // `only_space` rejects. A `@protocol` carries the interface half
        // instead.
        containers: &["P", "C"],
        source: "\
@protocol P
- (int)r;
@end

@implementation C {
    int a;
}
- (int)q { return a; }
@end
",
    },
    #[cfg(feature = "elixir")]
    Fixture {
        lang: LANG::Elixir,
        containers: &["Outer", "Inner", "Sibling"],
        source: "\
defmodule Outer do
  defstruct [:a]
  def q, do: 1
  defp r, do: 2

  defmodule Inner do
    def s, do: 3
  end
end

defmodule Sibling do
  def t, do: 4
end
",
    },
];

/// The container spaces named by each fixture carry both blocks.
///
/// The positive half of the contract, and the guard against "fixing"
/// #1197 by disabling the metric everywhere.
#[test]
fn containers_emit_npm_and_npa() {
    assert_fixtures_present(FIXTURES);
    for fixture in FIXTURES {
        // An empty list means every following assertion is skipped, so
        // name the one language that is allowed to have one rather than
        // letting a fixture go quiet by accident.
        assert_eq!(
            fixture.containers.is_empty(),
            fixture.lang == LANG::Go,
            "{:?}: only Go has no container SpaceKind",
            fixture.lang
        );
        let spaces = emitted_spaces(fixture.lang, fixture.source);
        for want in fixture.containers {
            let space = only_space(fixture.lang, &spaces, want);
            assert!(
                matches!(
                    space.kind,
                    SpaceKind::Class
                        | SpaceKind::Interface
                        | SpaceKind::Namespace
                        | SpaceKind::Struct
                        | SpaceKind::Trait
                        | SpaceKind::Impl
                ),
                "{:?}: {want:?} should be a container kind, is {:?}",
                fixture.lang,
                space.kind
            );
            assert!(
                space.has_npm && space.has_npa,
                "{:?}: container {want:?} must emit npm and npa (npm={}, npa={})",
                fixture.lang,
                space.has_npm,
                space.has_npa
            );
        }
    }
}

/// No function space carries either block.
///
/// This is the assertion #1197 is about. The `<get>` / `<set>` /
/// `<init>` / `<static-init>` spaces #1184 introduced are ordinary
/// function spaces here and are covered by the same sweep, as are C#'s
/// expression-bodied property and indexer.
#[test]
fn function_spaces_emit_neither() {
    assert_fixtures_present(FIXTURES);
    for fixture in FIXTURES {
        let spaces = emitted_spaces(fixture.lang, fixture.source);
        let functions: Vec<&Emitted> = spaces
            .iter()
            .filter(|s| s.kind == SpaceKind::Function)
            .collect();
        // A fixture whose functions all failed to open a space would make
        // every assertion below vacuous.
        assert!(
            !functions.is_empty(),
            "{:?}: expected at least one function space, got {:?}",
            fixture.lang,
            summary(&spaces)
        );
        for space in functions {
            assert!(
                !space.has_npm && !space.has_npa,
                "{:?}: {:?} space {:?} must not emit npm/npa (npm={}, npa={})",
                fixture.lang,
                space.kind,
                space.name,
                space.has_npm,
                space.has_npa
            );
        }
    }
}

/// The whole-file roll-up survives on the unit root, exactly as `wmc`'s
/// does.
///
/// Narrowing the enable to containers alone would have deleted this — an
/// information loss, not the all-zero-noise removal #1197 asked for, and
/// it would have left `npm` / `npa` disagreeing with `wmc` about a root
/// the three metrics share a [`MetricScope`](crate::metric_catalog::MetricScope).
#[test]
fn the_file_root_keeps_its_rollup() {
    assert_fixtures_present(FIXTURES);
    for fixture in FIXTURES {
        let spaces = emitted_spaces(fixture.lang, fixture.source);
        let root = spaces.first().expect("the root space is always emitted");
        assert_eq!(root.kind, SpaceKind::Unit, "{:?}: root kind", fixture.lang);
        assert!(
            root.has_npm && root.has_npa,
            "{:?}: the unit root must keep its npm/npa roll-up (npm={}, npa={})",
            fixture.lang,
            root.has_npm,
            root.has_npa
        );
    }
}

/// No fixture emits a space the classifier left `Unknown`.
///
/// A space's kind comes from `Getter::get_space_kind_with_code`, called
/// once per promoted node by `spaces::compute::open_func_space`. So a
/// node the walker promoted — via
/// `Checker::promotes_to_func_space_with_code` — whose classifier
/// answered `Unknown` becomes a space that is not a
/// [`SpaceKind::is_member_scope`], and `note_member_scope` then records
/// a kind that suppresses `npm` / `npa` outright. That is an *absent
/// key*, not a wrong count: it reads the same as a language with no
/// containers, so no snapshot diff and no value assertion can see it.
///
/// Asserted here on the serialized kind rather than by walking nodes and
/// checking `is_func_space_with_code(n) ⇒ get_space_kind_with_code(n) !=
/// Unknown` directly. `Checker` / `Getter` methods are static and
/// monomorphised per parser type; `AstInner` hands out a `root_node` but
/// no LANG-generic way to invoke them against it, so the node-walk form
/// would need a new `run_*` dispatch arm on the macro — production
/// surface grown to host a test. The promoted-but-`Unknown` space *is*
/// that implication one step downstream, and is already observable.
///
/// **Coverage is bounded by [`FIXTURES`].** This can only fail for a
/// shape some fixture exercises. It establishes nothing about languages
/// or constructs not represented there — a partial sweep cannot show
/// absence.
///
/// **What it adds over the sweeps above** is not the Elixir case. That
/// was measured, not assumed: reverting `open_func_space` to the
/// byte-less `get_space_kind` fails 12 lib tests, every one of them
/// failing on Elixir — the only language overriding either method — and
/// both [`containers_emit_npm_and_npa`] (an `Unknown`
/// container is not a container kind) and [`function_spaces_emit_neither`]
/// are among them. So this sweep is not uniquely responsible for that
/// perturbation and should not be read as if it were.
///
/// Its own contribution is a selector hole, and specifically the
/// *partial* form of one. [`function_spaces_emit_neither`] filters
/// `kind == SpaceKind::Function`, so a space that *should* be a function
/// but classifies `Unknown` drops out of the filter rather than failing
/// the assertion; what catches the revert there is its anti-vacuity
/// guard, and only because that perturbation degrades **every** Elixir
/// function space at once, leaving the fixture with none. A fixture
/// keeping one genuine function space — an `AnonymousFunction`, which
/// the Elixir fixture happens not to have — would satisfy that guard
/// while the rest degraded silently. This sweep filters nothing, so
/// there is no set for a space to fall out of. (`.claude/rules/testing.md`:
/// "review the selector as carefully as the assertion".)
#[test]
fn no_space_is_emitted_with_an_unknown_kind() {
    assert_fixtures_present(FIXTURES);
    for fixture in FIXTURES {
        let spaces = emitted_spaces(fixture.lang, fixture.source);
        // The root is always emitted and is always `Unit`, so a fixture
        // that opened no space below it would satisfy every assertion
        // here without exercising a single classifier decision.
        assert!(
            spaces.len() > 1,
            "{:?}: expected at least one space below the root, got {:?}",
            fixture.lang,
            summary(&spaces)
        );
        for space in &spaces {
            // `assert!` rather than `assert_ne!`: the latter appends
            // "left: Unknown / right: Unknown" to a `!=` failure, which
            // reads as a contradiction next to the real message.
            assert!(
                space.kind != SpaceKind::Unknown,
                "{:?}: space {:?} was promoted to a space but classified \
                 Unknown, so it serializes no npm/npa block; every space \
                 was {:?}",
                fixture.lang,
                space.name,
                summary(&spaces)
            );
        }
    }
}

/// Every #1184 construct opens a function space that emits neither
/// block, while a plain method beside it does the same.
///
/// [`function_spaces_emit_neither`] would still pass if a
/// grammar stopped opening these spaces at all; naming them pins that
/// they exist *and* stay quiet.
// Gated on the fixtures' own features for the reason its two siblings
// below already are (9d71de34): the case list is six languages wide and
// every row carries its own `cfg`, so a feature set enabling none of
// them leaves an empty list and trips `assert_fixtures_present` — a
// failure that reads as a defect in whatever was being changed rather
// than as an unrelated build configuration. `--no-default-features
// --features rust` is one such set; the canonical minimal-langs
// configuration `rust,typescript` is not, since `typescript` supplies
// two rows (#1220).
#[test]
#[cfg(any(
    feature = "kotlin",
    feature = "java",
    feature = "groovy",
    feature = "javascript",
    feature = "mozjs",
    feature = "typescript"
))]
fn the_1184_constructs_open_quiet_function_spaces() {
    let cases: &[(LANG, &[&str])] = &[
        #[cfg(feature = "kotlin")]
        (LANG::Kotlin, &["<get>", "<set>", "<init>"]),
        #[cfg(feature = "java")]
        (LANG::Java, &["<static-init>"]),
        #[cfg(feature = "groovy")]
        (LANG::Groovy, &["<static-init>"]),
        #[cfg(feature = "javascript")]
        (LANG::Javascript, &["<static-init>"]),
        #[cfg(feature = "mozjs")]
        (LANG::Mozjs, &["<static-init>"]),
        #[cfg(feature = "typescript")]
        (LANG::Typescript, &["<static-init>"]),
        #[cfg(feature = "typescript")]
        (LANG::Tsx, &["<static-init>"]),
    ];
    assert_fixtures_present(cases);
    for (lang, names) in cases {
        let spaces = emitted_spaces(*lang, fixture_source(*lang));
        for name in *names {
            let space = only_space(*lang, &spaces, name);
            assert_eq!(space.kind, SpaceKind::Function, "{lang:?}: {name:?}");
            assert!(
                !space.has_npm && !space.has_npa,
                "{lang:?}: {name:?} must not emit npm/npa"
            );
        }
    }
}

/// Narrowing the enable predicate did not change what the containers
/// count.
///
/// The emission gate and the counters are independent — `merge` sums the
/// `_sum` fields without consulting the space kind — but that
/// independence is worth pinning rather than assuming, since a wrong
/// predicate could have skipped a `ClassBody` walk instead of just a
/// block.
#[test]
#[cfg(feature = "java")]
fn container_counts_are_independent_of_the_emission_gate() {
    let space = space_verbatim(
        LANG::Java,
        fixture_source(LANG::Java).as_bytes(),
        MetricsOptions::default(),
    );
    let class = crate::test_support::child_space(&space, "C");
    assert_eq!(class.metrics.npm.class_npm_sum(), 1, "public method `q`");
    assert_eq!(class.metrics.npa.class_npa_sum(), 1, "public attribute `a`");

    // The interface half of the same fixture, which a class-only
    // assertion would leave free to regress to zero.
    let interface = crate::test_support::child_space(&space, "I");
    assert_eq!(interface.metrics.npm.interface_npm_sum(), 1, "`I::q`");

    // The roll-up reaches the root — the sum is what `bca check` reads at
    // a container, and dropping it would be a real regression rather than
    // a shape one.
    assert_eq!(space.metrics.npm.class_npm_sum(), 1);
    assert_eq!(space.metrics.npa.class_npa_sum(), 1);
}

/// A type declared *inside a function body* leaves that function quiet
/// and is reported by the file root instead (#1203).
///
/// This is the shape Go and Rust got wrong. Neither language opens a
/// space for a `struct`, so its counts landed on whichever space enclosed
/// it — a `Function` space for a type declared in a function body, which
/// then serialized a block that #1197 had already ruled out everywhere
/// else.
///
/// The roll-up half is not a formality. Go enables `npm` at the root only
/// for a file with a direct `MethodDeclaration` child, and Rust `npa`
/// only for a module-scope `struct`, so for a file whose only container
/// sits inside a function, merely *clearing* the function's block would
/// have serialized the counts nowhere at all — they survive in the root's
/// `_sum` fields either way, which is exactly why an absence-only test
/// could not tell the two outcomes apart. Both fixtures below therefore
/// assert the root's sums include the nested declaration's members.
// Gated for the same reason as
// `a_language_with_no_member_construct_emits_neither_block` below: a
// two-language case list makes `assert_fixtures_present` a false
// failure under a feature set that enables neither.
#[test]
#[cfg(any(feature = "go", feature = "rust"))]
fn a_type_declared_inside_a_function_reaches_the_root_rollup() {
    // (language, the function holding the declaration, the root's
    // `class_na_sum` / `class_npa_sum` once the nested type is folded in)
    let cases: &[(LANG, &str, u64, u64)] = &[
        // `S{Pub, priv}` + `inner{X}` = 3 attributes, of which `Pub` and
        // `X` are exported by Go's leading-uppercase rule.
        #[cfg(feature = "go")]
        (LANG::Go, "Outer", 3, 2),
        // `S{a, b}` + `Inner{x}` = 3 fields, of which `pub a` and
        // `pub x` are public.
        #[cfg(feature = "rust")]
        (LANG::Rust, "top", 3, 2),
    ];
    assert_fixtures_present(cases);
    for (lang, holder, na_sum, npa_sum) in cases {
        let source = fixture_source(*lang);

        let spaces = emitted_spaces(*lang, source);
        let function = only_space(*lang, &spaces, holder);
        assert_eq!(function.kind, SpaceKind::Function, "{lang:?}: {holder:?}");
        assert!(
            !function.has_npm && !function.has_npa,
            "{lang:?}: {holder:?} holds a nested type but must not carry a block \
             (npm={}, npa={})",
            function.has_npm,
            function.has_npa
        );

        let root = spaces.first().expect("the root space is always emitted");
        assert!(
            root.has_npm && root.has_npa,
            "{lang:?}: the unit root must carry the roll-up (npm={}, npa={})",
            root.has_npm,
            root.has_npa
        );

        // The values behind that block, so a rule that emitted an
        // all-zero root would fail here rather than pass the key check
        // above.
        let space = space_verbatim(*lang, source.as_bytes(), MetricsOptions::default());
        assert_eq!(
            space.metrics.npa.class_na_sum(),
            *na_sum,
            "{lang:?}: root attributes, including the type declared in {holder:?}"
        );
        assert_eq!(
            space.metrics.npa.class_npa_sum(),
            *npa_sum,
            "{lang:?}: root public attributes, including the type declared in {holder:?}"
        );
    }
}

/// A C++ `namespace` carries both blocks.
///
/// Namespaces are the largest population the #1203 rule moved — 1,337 of
/// them in this repository's own integration corpora, none of which
/// serialized either block before, because C++ enabled from
/// `ClassSpecifier` / `StructSpecifier` and a namespace is neither.
/// `SpaceKind::Namespace` is asserted directly rather than through
/// [`containers_emit_npm_and_npa`]'s any-container-kind check, which
/// would still pass if the grammar started reporting `N` as a class.
#[test]
#[cfg(feature = "cpp")]
fn a_cpp_namespace_is_a_member_scope() {
    let spaces = emitted_spaces(LANG::Cpp, fixture_source(LANG::Cpp));
    let namespace = only_space(LANG::Cpp, &spaces, "N");
    assert_eq!(namespace.kind, SpaceKind::Namespace);
    assert!(
        namespace.has_npm && namespace.has_npa,
        "a namespace rolls its classes up and must carry both blocks \
         (npm={}, npa={})",
        namespace.has_npm,
        namespace.has_npa
    );
    // The narrowing #1220 found: `wmc` does *not* follow npm/npa here.
    // A namespace's member functions are free functions rather than
    // methods of a class, so `CppCode::compute` drops `SpaceKind::
    // Namespace` and the space records no kind, leaving the block
    // unserialized. The class inside the namespace still carries all
    // three — asserted below so this reads as a scope rule rather than
    // as wmc being absent from the file.
    assert!(
        !namespace.has_wmc,
        "a namespace weights no per-class complexity and must carry no wmc"
    );
    let class = only_space(LANG::Cpp, &spaces, "C");
    assert!(
        class.has_wmc && class.has_npm && class.has_npa,
        "the class inside the namespace carries all three \
         (wmc={}, npm={}, npa={})",
        class.has_wmc,
        class.has_npm,
        class.has_npa
    );
}

/// Ruby's `module` is the second construct reaching the `namespace`
/// narrowing, so the rule is space-kind-level rather than a C++ quirk.
///
/// `Getter::get_space_kind` maps `Module` to `SpaceKind::Namespace` for
/// Ruby exactly as it maps `NamespaceDefinition` for C++ and Mozcpp, and
/// `class_interface_compute` drops that kind for every language, so all
/// three spell the same rule. Pinned beside the C++ case because a doc
/// that names only C++ here reads as a language deviation and sends the
/// next reader looking for a `CppCode` special case that does not exist.
#[test]
#[cfg(feature = "ruby")]
fn a_ruby_module_is_a_namespace_without_wmc() {
    let spaces = emitted_spaces(LANG::Ruby, fixture_source(LANG::Ruby));
    let module = only_space(LANG::Ruby, &spaces, "M");
    assert_eq!(module.kind, SpaceKind::Namespace);
    assert!(
        module.has_npm && module.has_npa && !module.has_wmc,
        "a Ruby module carries npm/npa and no wmc \
         (npm={}, npa={}, wmc={})",
        module.has_npm,
        module.has_npa,
        module.has_wmc
    );
    let class = only_space(LANG::Ruby, &spaces, "C");
    assert!(
        class.has_wmc && class.has_npm && class.has_npa,
        "the class inside the module carries all three \
         (wmc={}, npm={}, npa={})",
        class.has_wmc,
        class.has_npm,
        class.has_npa
    );
}

/// Go emits no `wmc` block on any space, including the file root, while
/// its `npa` and `npm` do appear there (#1220).
///
/// `GoCode` sits in the `Wmc` no-op list rather than deviating on space
/// kind: Go's flat space model cannot attribute a method to a receiver
/// class, so there is no per-class complexity to weight. It is the one
/// language where the `Wmc` and `Npa` no-op sets differ, which is why
/// the book and STABILITY.md now scope the three-blocks rule to npm/npa
/// and describe wmc's two narrowings separately. Asserting the npa/npm
/// half in the same test is what keeps this from passing for a Go file
/// that had simply stopped emitting anything.
#[test]
#[cfg(feature = "go")]
fn go_emits_npa_and_npm_but_never_wmc() {
    let spaces = emitted_spaces(LANG::Go, fixture_source(LANG::Go));
    let root = &spaces[0];
    assert_eq!(root.kind, SpaceKind::Unit);
    assert!(
        root.has_npm && root.has_npa,
        "Go's root carries npa/npm (npm={}, npa={})",
        root.has_npm,
        root.has_npa
    );
    assert!(
        !spaces.iter().any(|space| space.has_wmc),
        "no Go space may carry a wmc block, including the unit root"
    );
}

/// A language with no class-shaped construct emits no block at all.
///
/// The file unit is a member scope like any other, so making emission
/// depend on the space kind alone would have given a shell script a
/// `class_npa_sum: 0` block on every file — noise for a grammar that
/// cannot produce anything else. `Npm::HAS_MEMBERS` / `Npa::HAS_MEMBERS`
/// keep those languages out, the way `wmc`'s no-op `compute` does by
/// never recording a kind. Asserted on the root because it is the only
/// space these fixtures have that is a member scope.
// Gated on the fixtures' own features rather than left ungated: the
// case list is three languages wide, so a feature set that enables
// others but none of these — `--no-default-features --features
// rust,typescript`, the canonical minimal-langs CI configuration —
// would trip `assert_fixtures_present` and read as a defect in
// whatever was being changed.
#[test]
#[cfg(any(feature = "bash", feature = "lua", feature = "c"))]
fn a_language_with_no_member_construct_emits_neither_block() {
    let cases: &[(LANG, &str)] = &[
        #[cfg(feature = "bash")]
        (LANG::Bash, "foo() { echo hi; }\nfoo\n"),
        #[cfg(feature = "lua")]
        (LANG::Lua, "function f(a) return a end\n"),
        #[cfg(feature = "c")]
        (LANG::C, "int add(int a, int b) { return a + b; }\n"),
    ];
    assert_fixtures_present(cases);
    for (lang, source) in cases {
        let spaces = emitted_spaces(*lang, source);
        let root = spaces.first().expect("the root space is always emitted");
        assert_eq!(root.kind, SpaceKind::Unit, "{lang:?}: root kind");
        assert!(
            !root.has_npm && !root.has_npa,
            "{lang:?}: a grammar with no member construct must emit neither \
             block (npm={}, npa={})",
            root.has_npm,
            root.has_npa
        );
    }
}

/// No Elixir `defmodule` counts a nested module's members twice.
///
/// Until #1203 the Elixir impls opened with `if !stats.is_disabled() ||
/// …  { return; }` — a first-wins guard reusing the emission flag, which
/// went away with the flag. It was inert, because the walker pushes a
/// `defmodule`'s space before running any metric against it, so a nested
/// module never reaches its parent's stats. "Was inert" is a claim about
/// walk order rather than about this file, so it is pinned here: were the
/// guard load-bearing, `Outer` would absorb `Inner`'s members twice.
#[test]
#[cfg(feature = "elixir")]
fn nested_elixir_modules_are_not_double_counted() {
    use crate::test_support::child_space;

    let root = space_verbatim(
        LANG::Elixir,
        fixture_source(LANG::Elixir).as_bytes(),
        MetricsOptions::default(),
    );

    // `def q` + `defp r`, plus `Inner`'s `def s` once through the
    // roll-up — 4 would mean `Outer` counted `s` directly as well.
    // `defp` is private, so two of the three are public.
    let outer = child_space(&root, "Outer");
    assert_eq!(outer.metrics.npm.class_nm_sum(), 3, "Outer: q, r, Inner::s");
    assert_eq!(outer.metrics.npm.class_npm_sum(), 2, "Outer: q, Inner::s");
    // `defstruct [:a]`, and Elixir struct fields are all public.
    assert_eq!(outer.metrics.npa.class_na_sum(), 1, "Outer: defstruct :a");

    let inner = child_space(outer, "Inner");
    assert_eq!(inner.metrics.npm.class_nm_sum(), 1, "Inner: s");
    assert_eq!(
        inner.metrics.npa.class_na_sum(),
        0,
        "Inner has no defstruct"
    );

    // A sibling module at file scope, which a guard that fired once per
    // *file* rather than once per space would have silenced.
    let sibling = child_space(&root, "Sibling");
    assert_eq!(sibling.metrics.npm.class_nm_sum(), 1, "Sibling: t");

    // Four methods across three modules, three of them public.
    assert_eq!(root.metrics.npm.class_nm_sum(), 4, "q, r, Inner::s, t");
    assert_eq!(root.metrics.npm.class_npm_sum(), 3, "q, Inner::s, t");
}