big-code-analysis-ast 2.6.0

Parse and classification layer behind big-code-analysis (internal, version-locked)
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
//! Groovy's role rows. The Halstead keyword roles (#1693), the
//! paying-construct roles — `Comparison`, `ShortCircuit`, `EagerLogical`,
//! `Ternary`, `CaseArm`, `Guard`, `NullSafe` (#1694, #1695) — the space
//! tree (#1696) and the control flow — `Branch`, `Switch`, `Loop`,
//! `Catch`, `ElseIf`, `Exit` (#1697) — and
//! the documentation rows (#1699) are declared.

use std::cell::LazyCell;

use crate::getter::node_text;
use crate::lang_helpers::doc_comment::{java_doc, node_bytes, token_spelling};
use crate::role_table;
use crate::roles::control_flow::else_if_prev_sibling_gate;
use crate::{Ancestors, Groovy, GroovyCode, Node};

/// Whether an `object_creation_expression` carries a class body, which
/// makes it an anonymous class rather than a plain `new Foo()`: Java's
/// rule (#463), reachable in Groovy since dekobon-tree-sitter-groovy
/// 0.5.0 gave the expression its `body` field (tree-sitter-groovy#68).
/// Read by field, as `opens_record_header` reads `components`; Java's
/// grammar names no field there and its gate scans for the kind. A
/// trailing closure (`new Foo().bar { }`) is a `closure` under a
/// `method_invocation`, a different node, and never reaches this.
///
/// The gate admits what the grammar calls a body, and the grammar calls
/// every `{` after `new T(…)` one. Groovy itself reads a `{` that
/// starts the next line as a closure passed to the new object, so
/// `new T()` followed by `{ int n = 1 }` on the next line opens an
/// `<anonymous>` class here with no error node to say so, and
/// `{ x -> x }` opens one around an `ERROR`
/// (`groovy_closure_on_the_line_after_new_reads_as_an_anonymous_class`).
fn has_class_body(node: &Node<'_>) -> bool {
    node.child_by_field_name("body").is_some()
}

/// Whether an `instanceof_expression` holds no keyword token.
/// The negated form `o !instanceof T` emits no operator token at all —
/// the node holds its two operands and nothing between them — so the
/// owner pays for itself there and the positive form's keyword pays
/// otherwise. `a !in b` had the same shape until
/// dekobon-tree-sitter-groovy 0.6.0 gave it a `!in` token of its own.
fn has_no_keyword_token<'a>(node: &Node<'a>, _ancestors: Ancestors<'a, '_>) -> bool {
    comparison::project(node).is_none()
}

/// Whether a contextual keyword leaf (`trait`, `record`, `sealed`,
/// `permits`, `var`) sits directly under the construct it introduces.
///
/// Valid Groovy may use any of the five as a name. The grammar parses
/// most such names as an `identifier`, but some fail into an `ERROR`
/// holding the keyword leaf: a script-level statement that opens with
/// `sealed` or `trait` (`trait = 4`, `sealed.call()`), a class member
/// that puts either after a modifier (`private boolean sealed`, `static
/// trait = 1`), and a statement opening with `var` as a name anywhere
/// (`var = 4`, `var++`). Billing the leaf there would make a variable
/// an operator (#1552, #1565, #1704).
///
/// `var` introduces a local, and since dekobon-tree-sitter-groovy 0.6.0
/// every parameter-like declaration too: a method's or constructor's
/// `formal_parameter`, a try-with-resources `resource` and a `catch`
/// parameter each hold the keyword leaf where 0.5.0 read the word as
/// their `type_identifier` (which [`spells_var`] claimed), and so does
/// a `closure_parameter`, which 0.5.0 did not parse with a `var` at
/// all. A parameter *named* `var` is an `identifier` there.
///
/// `record` is the exception since dekobon-tree-sitter-groovy 0.5.0:
/// its keyword comes from the external scanner only before a record
/// header, so a `record` used as a name is an `identifier` everywhere.
/// The leaf still strands on a line the scanner takes for a header and
/// the grammar rejects (`record a<b`), which is what its pair below
/// leaves unbilled; `groovy_declaration_keywords_are_operators_1552`
/// pins both.
fn contextual_keyword_owns<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
    use Groovy::*;

    ancestors.parent(node).is_some_and(|parent| {
        matches!(
            (node.kind_id().into(), parent.kind_id().into()),
            (Trait, TraitDeclaration)
                | (Record, RecordDeclaration)
                | (Permits, PermitsClause)
                | (
                    Sealed,
                    ClassDeclaration | InterfaceDeclaration | TraitDeclaration
                )
                | (
                    Var,
                    LocalVariableDeclaration
                        | FormalParameter
                        | ClosureParameter
                        | Resource
                        | CatchFormalParameter
                )
        )
    })
}

/// The type a `record_component` or a constructor's `formal_parameter`
/// declares — the `type` field's tokens, comments and whitespace
/// removed — or `None` for an untyped one (a bare name in a
/// `record_component` is a `type_identifier` to the pinned grammar,
/// which requires the type there and recovers an untyped list as one
/// component — `groovy_untyped_record_components_recover_as_one`) and
/// for a child that is no parameter. `def` and `var` declare no type:
/// since dekobon-tree-sitter-groovy 0.6.0 a `formal_parameter` holds
/// either as a keyword outside its `type` field, where a
/// `record_component` still reads it as its `type_identifier`, so that
/// spelling is `None` too and `record R(def a)` matches its `R(def a)`
/// as it did when both were the `type_identifier`.
fn groovy_parameter_type(param: &Node<'_>, code: &[u8]) -> Option<Vec<u8>> {
    param
        .child_by_field_name("type")
        .map(|ty| token_spelling::<GroovyCode>(&ty, code))
        .filter(|spelling| !matches!(spelling.as_slice(), b"def" | b"var"))
}

/// Whether `ctor`, a `constructor_declaration` in `record`'s body,
/// declares the record's canonical constructor: named after the record,
/// with as many formal parameters as the record's header has
/// `components` — their types, read once per header by
/// [`opens_record_header`] — each spelling the same type as its
/// component (Java's rule, JLS 8.10.4.1 and 8.8, which Groovy records
/// follow). Parameter names and annotations do not take part. The same
/// spelling, not the same type — the tokens, so a comment inside the
/// type is nothing —
/// so `java.util.List<T>` and `List<T>` are two spellings here, as in
/// `roles/java.rs`. The name test is for the grammar, not the language:
/// the grammar does not check a constructor's name, so `record R(int a)
/// { Q(int a) { } }` holds a `constructor_declaration` named `Q` in
/// `R`'s body, where arity and types alone would read it as `R`'s
/// canonical constructor.
///
/// Two grammar limitations shape what reaches this. The pinned
/// grammar parses a variable-arity component (`String... xs`) with the
/// `...` in an `ERROR` outside the `type` field while the constructor's
/// parameter has a `varargs_type`, so the two never agree and such a
/// record's header opens a space beside its canonical constructor;
/// and a compact constructor (`R { … }`) does not parse
/// (tree-sitter-groovy#72): the bare `R` is an `ERROR`, or after a
/// modifier a typeless field, and its `{ … }` an instance initializer
/// `block` of the body, so a record that writes one declares no
/// constructor here and its header opens.
fn is_record_canonical_constructor(
    ctor: &Node<'_>,
    record: &Node<'_>,
    components: &[Option<Vec<u8>>],
    code: &[u8],
) -> bool {
    let (Some(ctor_name), Some(record_name), Some(params)) = (
        ctor.child_by_field_name("name"),
        record.child_by_field_name("name"),
        ctor.child_by_field_name("parameters"),
    ) else {
        return false;
    };
    if node_bytes(&ctor_name, code) != node_bytes(&record_name, code) {
        return false;
    }
    let mut declared = params
        .children()
        .filter(|p| p.kind_id() == Groovy::FormalParameter as u16)
        .map(|p| groovy_parameter_type(&p, code));
    components
        .iter()
        .all(|component| declared.next().as_ref() == Some(component))
        && declared.next().is_none()
}

/// A record's header: the component list in the `components` field of
/// a `record_declaration`, a sibling of its `class_body` — the node the
/// `FuncOpener` row opens the implicit canonical constructor's space on
/// (#1842), and Java's twin (`roles/java.rs`, the rationale there).
/// `None` for any other node. Held once for the row's gate and for the
/// consumers that step between a record and its header (#1863); pinned
/// by `groovy_record_header_is_the_records_own_list`.
#[inline]
#[must_use]
pub fn record_header<'a>(record: &Node<'a>) -> Option<Node<'a>> {
    (record.kind_id() == Groovy::RecordDeclaration as u16)
        .then(|| record.child_by_field_name("components"))
        .flatten()
}

/// Whether `list` is `record`'s [`record_header`]: the same node, not
/// one of its kind.
#[inline]
#[must_use]
pub fn is_record_header(list: &Node<'_>, record: &Node<'_>) -> bool {
    record_header(record).is_some_and(|header| header.id() == list.id())
}

/// Whether a `record_components` list is a record's header in a record
/// that declares no canonical constructor, so the header stands for
/// the implicitly declared one (#1842): the record's [`record_header`],
/// checked by field as Java's is so a grammar bump that reuses the kind
/// elsewhere under the record opens nothing there. A written canonical
/// constructor ([`is_record_canonical_constructor`]) owns the
/// components instead; a non-canonical one is a callable of its own
/// and leaves the header open. The gate reads the record's body, so it
/// is a `fn` rather than `under [RecordDeclaration]`, and the body's
/// constructor types as bytes, so the row marks it `text_gated_by`:
/// handed no bytes, every same-arity constructor reads as canonical.
fn opens_record_header<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
    let Some(record) = ancestors.parent(node) else {
        return false;
    };
    if !is_record_header(node, &record) {
        return false;
    }
    let Some(body) = record.child_by_field_name("body") else {
        return true;
    };
    let components = LazyCell::new(|| {
        record_header_types_read::record();
        node.children()
            .filter(|p| p.kind_id() == Groovy::RecordComponent as u16)
            .map(|p| groovy_parameter_type(&p, code))
            .collect::<Vec<_>>()
    });
    !body.children().any(|member| {
        member.kind_id() == Groovy::ConstructorDeclaration as u16
            && is_record_canonical_constructor(&member, &record, &components, code)
    })
}

// Times `opens_record_header` spelled a header's component types: once
// per evaluation that meets a constructor, as Java's twin counts
// (`roles/java.rs`, #1863).
crate::observation::counter!(record_header_types_read);

/// Java's eight primitive type keywords and `void`, which Groovy
/// reserves as Java does.
const PRIMITIVE_TYPES: &[&str] = &[
    "boolean", "byte", "char", "double", "float", "int", "long", "short", "void",
];

/// Whether `node` spells a primitive type, which bills as a text-keyed
/// operator as Java's primitive keywords do (#1568).
///
/// The pinned grammar has no primitive node: a declared type is a
/// `type_identifier` (`int x = 1`, `void m()`), and a class literal's
/// receiver (`int.class`) or an uninitialised local (`int t`, which
/// parses as two expression statements) is a plain `identifier`. Groovy
/// reserves these keywords, so a name can spell one only as a member
/// selector after a `.`-family operator (`x.int`, `x?.int`, `x::int`) or
/// as a map or named-argument label (`[int: 1]`, `f(int: 1)`); those
/// stay operands.
fn spells_primitive_type<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
    use Groovy::*;

    if !node_text(code, node).is_some_and(|text| PRIMITIVE_TYPES.contains(&text)) {
        return false;
    }
    ancestors.parent(node).is_none_or(|parent| {
        let is_first_child = parent.child(0).is_some_and(|first| first.id() == node.id());
        match parent.kind_id().into() {
            FieldAccess
            | SafeNavigationExpression
            | SafeChainDotExpression
            | SpreadDotExpression
            | DirectFieldAccessExpression
            | MethodPointerExpression
            | MethodReferenceExpression => is_first_child,
            MapEntry | NamedArgument => !is_first_child,
            _ => true,
        }
    })
}

/// Whether a `type_identifier` spells `var` as the declaration
/// placeholder (#1706).
///
/// The pinned grammar emits `var` as its keyword leaf under a
/// `local_variable_declaration` and every parameter-like declaration
/// (see [`contextual_keyword_owns`]). In a field (`var field = 1`,
/// `static var s = 2`) and in the recovery of a script-level modified
/// one (`static var x`, which fails into an `ERROR` holding the word)
/// it is a `type_identifier` directly under the declaration or the
/// `ERROR`: the two parents admitted. Up to dekobon-tree-sitter-groovy
/// 0.5.0 a parameter, a resource, a `catch` parameter and a `final var`
/// local spelled it that way too. Groovy cannot declare a
/// type named `var` (`class var {}` is a compile error), but the word
/// is a legal *segment* of a qualified type (`a.var.B`, with `package
/// a.var`) and a legal import alias (`import java.lang.String as var`),
/// and both spell a `type_identifier` that names a real type wherever a
/// type is written out — a `qualified_type`, a cast, an `instanceof`, a
/// type argument, an array or generic type — so a `var` under any of
/// those stays the operand it was. An aliased `var` used bare as a
/// field's type is the one spelling the shape cannot tell from the
/// placeholder, and it bills as the keyword, as the grammar itself
/// reads one on a parameter; a `var` used as a name is an `identifier`
/// and never reaches this gate.
///
/// A `method_declaration` parent is not admitted: the invalid return
/// type `var m() {}` lands there.
fn spells_var<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
    node_bytes(node, code) == b"var"
        && ancestors.parent(node).is_some_and(|parent| {
            parent.is_error() || parent.kind_id() == Groovy::FieldDeclaration as u16
        })
}

// `else if` is an `if_statement` whose previous sibling is the bare `else`
// token — no clause wrapper — so a nested `if` under `else { … }` follows
// `{` instead (#1697).
else_if_prev_sibling_gate!(Groovy, Else);

/// The container a `switch` nests its arms in, the `Switch` owner's
/// child: where cognitive opens its level (see Java's twin, #1697).
/// A consumer's structural projection of an owner's child, not a row:
/// the `Switch` row records the kind under `excludes`, and
/// `is_else_if_is_the_row_and_the_switch_body_is_the_owners_child`
/// pins the parent/child relation (#1701). Java's twin is instead
/// claimed by its `DocBodyResidual` row, because javadoc reads a doc
/// comment inside a `switch_block` in a field initializer; whether
/// Groovydoc does the same was not measured in #1699, so this
/// language's `DocBodyResidual` row does not list the kind and the
/// exclusion here is a coverage-accounting fact, not a Groovydoc
/// one. Deciding it is the row-membership question #1797 holds.
#[inline]
#[must_use]
pub fn is_switch_body_kind(kind: u16) -> bool {
    kind == Groovy::SwitchBlock as u16
}

// Whether a `groovydoc_comment` opens with the marker Groovy's own
// `GroovydocManager` reads: the grammar marks `/** … */` as its own
// kind but also gives the empty `/**/` that kind, which documents
// nothing; a `/***` one is read, exactly as javac reads Javadoc.
crate::roles::byte_gate!(opens_with_groovydoc_marker, java_doc);

role_table! {
    lang: Groovy;
    // `command_chain` is the dekobon grammar's distinct node for Groovy's
    // command-style juxtaposed calls (`foo bar baz`), which the prior
    // amaanq grammar mis-modelled as `juxt_function_call`; it is a
    // genuine method-call form. `ObjectCreationExpression` (`new Foo()`)
    // is deliberately absent: the row follows the Java-family convention
    // (Java's `MethodInvocation`, C#'s `InvocationExpression`) of
    // counting method / function call sites only — constructor
    // invocations are an ABC concern, where Groovy's `branches` counts
    // `New` on its own (`groovy_count_token_branch`).
    Call { owns [MethodInvocation, CommandChain] }
    // One `string_literal` kind for every quoting. A GString `wraps` an
    // interpolation in either form — the long `${expr}` and the short
    // `$name` / `$obj.field` — whose inner expression is billed on its
    // own; a plain literal has neither child and is one operand. The
    // `string_fragment*` aliases are the body text the dump keeps
    // verbatim, not literals of their own.
    StringLit {
        owns [StringLiteral]
        wraps [GstringBraceInterpolation, GstringDollarInterpolation]
    }
    // The worked example of a node / token pairing (#1695). A
    // `binary_expression` owns a comparison through its `operator`
    // field, where `<` / `>` are gated to that parent (the grammar
    // also spells them as generic brackets). The dekobon grammar gives
    // Groovy's own comparisons nodes of their own, each wrapping its
    // token: `spaceship_expression` / `<=>`, `identity_expression` /
    // `===` and `!==`, `regex_find_expression` / `=~`,
    // `regex_match_expression` / `==~`, `membership_expression` /
    // `in` or `!in` (gated: the same `in` opens a `for (x in xs)`
    // header, and both are gated alike) and `instanceof_expression` /
    // `instanceof` (gated: a keyword error recovery strands under
    // `ERROR` is under no test). The negated `!instanceof` emits no
    // token at all, so that owner pays for itself exactly when it holds
    // no keyword, and once per test either way; `!in` is a token since
    // dekobon-tree-sitter-groovy 0.6.0 and pays as `in` does.
    Comparison {
        owns [
            BinaryExpression(holds_payer),
            SpaceshipExpression, IdentityExpression, RegexFindExpression, RegexMatchExpression,
            MembershipExpression,
            InstanceofExpression(pays_itself_when has_no_keyword_token),
        ]
        pays [
            EQEQ, BANGEQ, LTEQ, GTEQ,
            LT under BinaryExpression, GT under BinaryExpression,
            LTEQGT, EQEQEQ, BANGEQEQ, EQTILDE, EQEQTILDE,
            In under MembershipExpression, BANGin under MembershipExpression,
            Instanceof under InstanceofExpression,
        ]
        project "operator"
    }
    // `&&` / `||`, which the grammar emits only under a
    // `binary_expression`. The elvis `?:` is `NullSafe`'s.
    ShortCircuit {
        owns [BinaryExpression(holds_payer)]
        pays [AMPAMP, PIPEPIPE]
        project "operator"
    }
    // `&` / `|` / `^` on boolean operands evaluate both sides, but the
    // grammar emits them as the same `binary_expression` as the integral
    // forms, so the syntax alone cannot tell them apart; no consumer
    // treats them as a decision, and the three tokens bill as the
    // operators they are. A recognition boundary, recorded as the
    // kinds considered rather than as an absence.
    EagerLogical {
        owns []
        excludes [
            AMP "a boolean `&` is the integral `&`'s kind, which the grammar does not tell apart",
            PIPE "a boolean `|` is the integral `|`'s kind, which the grammar does not tell apart",
            CARET "a boolean `^` is the integral `^`'s kind, which the grammar does not tell apart",
        ]
    }
    // The `ternary_expression` owns it and its `?` pays, gated to that
    // owner: the grammar also spells `?` as a `wildcard` bound, which is
    // type syntax (#1274). The elvis `?:` is its own token under its own
    // `elvis_expression`, and is `NullSafe`'s.
    Ternary {
        owns [TernaryExpression]
        pays [QMARK under TernaryExpression]
        project "operator"
    }
    // Four structural forms, each one decision per token (#452): the
    // elvis `a ?: b` (`elvis_expression` / `?:`), the safe navigation
    // `a?.b` (`safe_navigation_expression` / `?.`), the safe chain
    // `a??.b` (`safe_chain_dot_expression` / `??.`) and the safe
    // subscript `a?[0]` (`safe_subscript_expression` / `?[`). Which of
    // the four each consumer scores is the consumer's to say
    // (`src/metrics/{abc,cyclomatic}/groovy.rs`).
    NullSafe {
        owns [
            ElvisExpression(holds_payer),
            SafeNavigationExpression(holds_payer),
            SafeChainDotExpression(holds_payer),
            SafeSubscriptExpression(holds_payer),
        ]
        pays [QMARKCOLON, QMARKDOT, QMARKQMARKDOT, QMARKLBRACK]
        project "operator"
    }
    // A `switch_case` owns a decision and its `case` keyword pays; the
    // `switch_default` and its `default` keyword are the fallback and
    // pay nothing (lesson 11, #469).
    CaseArm {
        owns [SwitchCase(holds_payer)]
        pays [Case]
        excludes [
            SwitchDefault "the fallback arm, no decision (lesson 11, #469)",
            Default "the fallback label's keyword",
        ]
    }
    Guard { absent "Groovy has no guard clause on a case or a function head" }
    // The `if_statement` owns the branch; its `if` keyword pays, once per
    // `if` and inside an `else if` chain too (#284, #1697).
    Branch { owns [IfStatement] pays [If] }
    // The `switch_expression` is the grammar's one node for the statement
    // and expression forms; its `switch` keyword pays once per switch,
    // which keeps the modified count aligned with the `case` arms (#300).
    // The `switch_block` — the arms' container, where cognitive opens its
    // level so a ternary or closure in the *subject* does not inherit
    // one — is the owner's child, not a construct of its own: no row
    // claims it, and it is excluded here rather than left as coverage
    // debt. The consumer's projection onto it is the named
    // `is_switch_body_kind` beside this table (#1701).
    Switch {
        owns [SwitchExpression]
        pays [Switch]
        excludes [SwitchBlock "the owner's child; cognitive's projection is the named `is_switch_body_kind` beside the table"]
    }
    // Every loop statement, its keyword paying: `for` once in the classic
    // and the `for (x in xs)` form, `while` once in a `while` and once in
    // a `do … while` (#284).
    Loop {
        owns [ForStatement, ForInStatement, WhileStatement, DoWhileStatement]
        pays [For, While]
    }
    Catch { owns [CatchClause] pays [Catch] }
    // Groovy spells `else if` as Java does: an `if_statement` whose
    // previous sibling is the bare `else` token. Recognition only; the
    // `Else` token pays cognitive's +1 and the `if` keyword `Branch`'s.
    ElseIf { owns [IfStatement(gated_by follows_else_keyword)] pays [] }
    // `return`, `throw`, and the Java 14+ switch-expression `yield`.
    // Implicit-return-from-closure is not an exit (consistent with Java).
    Exit { owns [ReturnStatement, ThrowStatement, YieldStatement] }
    // Every modifier (#1565). The grammar has no `modifiers` wrapper —
    // each modifier leaf sits directly under its declaration — so each
    // bills once. `sealed` and `permits` are contextual and bill only
    // under the construct they introduce; `non-sealed` cannot be spelled
    // as a name (`non-sealed` as a subtraction parses as `non`, `-` and
    // an identifier `sealed`). `default` is not here: it is one kind for
    // a `switch` label and an interface method's modifier, and bills
    // with the control keywords. The `static` of `import static` sits
    // under the `import_declaration`, a directive that qualifies no
    // declaration; Java's row reads the same parent, and the reasoning
    // (#1600) is in the comment above it.
    Modifier {
        owns [
            Public, Private, Protected, Static(not_under [ImportDeclaration]), Abstract, Final,
            Native, Strictfp, Synchronized, Transient, Volatile, NonDASHsealed,
            Sealed(gated_by contextual_keyword_owns), Permits(gated_by contextual_keyword_owns),
        ]
    }
    // The type-declaration keywords (#1552): no `*Declaration` wrapper
    // is classified, so the keyword leaf is the only node that can bill
    // one. Unlike Java's, `class` needs no class-literal gate:
    // `String.class` parses as a `field_access` whose `class` is a plain
    // `identifier`. `trait` and `record` are contextual, as `sealed` is.
    // `def` declares a method, a field or a local, as Kotlin's `fun` /
    // `val` and Perl's `my` do; it is one kind in every position. `var`
    // is the same kind of leaf under a `local_variable_declaration` or a
    // parameter-like declaration, as Kotlin's `var` is, and bills with
    // it (#1704) — gated, as `trait` and `record` are, because a
    // statement that opens with `var` as a name (`var = 4`) fails into
    // an `ERROR` holding the same leaf. Only that leaf: a `var` used as
    // a name elsewhere (`def var = 3`, `[var: 1]`, `m(var)`) is an
    // `identifier`. A field's `var field = 1` parses the word as a
    // `type_identifier`, which the `spells_var` gate claims as the
    // same keyword where it is the placeholder (#1706);
    // `Checker::keys_operator_by_text` then keys both spellings by
    // their bytes so Halstead counts one `var`, where the operand
    // reading had been Java's before #1560 gated its own.
    DeclKeyword {
        owns [
            Class, Interface, Enum, Def, Var(gated_by contextual_keyword_owns),
            TypeIdentifier(text_gated_by spells_var),
            Trait(gated_by contextual_keyword_owns), Record(gated_by contextual_keyword_owns),
        ]
    }
    // The pinned grammar has no primitive node (#1568): a primitive is
    // an `identifier` or `type_identifier` spelling one of Java's eight
    // keywords or `void`, told from a name by the bytes and by position
    // — hence `text_gated_by`. `Checker::is_primitive` keys both kinds
    // by text for the same reason.
    Primitive {
        owns [
            Identifier(text_gated_by spells_primitive_type),
            TypeIdentifier(text_gated_by spells_primitive_type),
        ]
    }
    // A method and a constructor are the callables, and so is a
    // record's header — its `record_components`, the `components`
    // field of the `record_declaration` and a sibling of the
    // `class_body` — where the body writes no canonical constructor
    // and the header stands for the implicit one (#1842, Java's shape
    // in `roles/java.rs`; the grammar has no compact-constructor kind,
    // see `opens_record_header`). `static { … }`
    // opens a space without being one (#1184). A closure opens no
    // space: the walk never promoted one (`is_func_space` left it out),
    // though the byte-less `get_space_kind` labelled it `Function` if
    // asked — the "pair that fails quietly" of grammar-dispatch §7; the
    // row records the walk's answer, as Java's does for its lambda.
    // An annotation type's element is a bodiless `method_declaration`
    // here (the grammar has no element kind), so it opens a function
    // space that `nom` and the interface's `wmc` count, where Java's
    // `annotation_type_element_declaration` opens none; the difference
    // is the grammar's, kept and documented in the book's NOM section
    // (#1865).
    FuncOpener {
        owns [
            MethodDeclaration(callable opens Function),
            ConstructorDeclaration(callable opens Function),
            RecordComponents(callable opens Function text_gated_by opens_record_header),
            StaticInitializer(opens Function),
        ]
    }
    Closure { owns [Closure] }
    // A trait is an interface with default method bodies (#247), so
    // it opens `Interface` as an annotation type does (#280). Gated
    // mapping, as Java's: `new Runnable() { … }` opens a `Class` space
    // only when it carries a body (#463).
    Container {
        owns [
            SourceFile(opens Unit),
            ClassDeclaration(opens Class),
            EnumDeclaration(opens Class),
            RecordDeclaration(opens Class),
            InterfaceDeclaration(opens Interface),
            TraitDeclaration(opens Interface),
            AnnotationTypeDeclaration(opens Interface),
            ObjectCreationExpression(opens Class gated_by has_class_body no_chain),
        ]
    }
    // A field declaration — `def field` included, whose `Def` modifier
    // the consumer reads for visibility — in a class or enum body.
    Member { owns [FieldDeclaration] }
    // The grammar tells Groovydoc apart by kind: `groovydoc_comment` is
    // the `/** … */` form, a distinct node (`GroovydocComment`) from the `//`
    // and `/* */` comments, so it sits on `DocComment` alone — under a
    // byte gate, since the kind also takes the empty `/**/` — and
    // `Comment` holds the other two. `is_comment` is the two kind tables
    // as one, which is what keeps the empty `/**/` a comment (#697,
    // #1699).
    Comment { owns [LineComment, BlockComment] }
    DocComment { owns [GroovydocComment(text_gated_by opens_with_groovydoc_marker no_chain)] }
    Docstring { absent "Groovy documents with comments, not string literals" }
    // The nodes `AstBuilder` hands to `GroovydocManager::handle`: a
    // type, a method or constructor, a field or property, an enum
    // constant. The enum constant is the one target outside the
    // space-tree rows — the parity exception `roles/doc_tests/parity.rs`
    // records.
    DocTarget {
        owns [
            ClassDeclaration,
            TraitDeclaration,
            InterfaceDeclaration,
            EnumDeclaration,
            RecordDeclaration,
            AnnotationTypeDeclaration,
            MethodDeclaration,
            ConstructorDeclaration,
            FieldDeclaration,
            EnumConstant,
        ]
    }
    DocRunOpener { absent "Groovydoc attaches every doc comment to a declaration; none documents by its own content" }
    DocRunDirective { absent "Groovydoc reads no directive comment" }
    // Beyond the callables and the closure: a `static { … }` initializer
    // opens a function space without being a callee, and an instance
    // initializer is a bare `block` of a class body (in the tree since
    // dekobon-tree-sitter-groovy 0.5.0); Groovydoc reads a doc comment
    // in either no more than one in a method body, as javadoc does in
    // Java's two. `block` is every braced body, as in Java's row. Most
    // are inside a callable or a closure, which answer first; the ones
    // that are not, besides the initializer, are the bodies of a
    // script-level `if`, `for` or `while`, which hold statements and no
    // documented declaration either.
    DocBodyResidual { owns [StaticInitializer, Block] }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::for_each_node_with_chain;
    use crate::{GroovyCode, SpaceKind};

    // One `opens_space` for the whole table, read from two rows, as
    // Java's test of the same name: the anonymous class opens a `Class`
    // only with a body; `new Object()` opens nothing; the closure is a
    // closure that opens nothing, and so is the trailing closure of
    // `new Object().with { }`, which is no class body.
    #[cfg(feature = "groovy")]
    #[test]
    fn opens_space_folds_func_opener_and_container_without_restating_kinds() {
        let source = b"class A {\n  static { }\n  def c = { x -> x }\n  Object o = new Object() { }\n  Object p = new Object()\n  Object q = new Object().with { }\n}\n";
        let mut spaces = Vec::new();
        for_each_node_with_chain::<GroovyCode>(source, |node, chain| {
            let ancestors = Ancestors::known(chain);
            let kind = opens_space(node, source, ancestors);
            let closure = closure::owns(node, source, ancestors);
            if kind != SpaceKind::Unknown || closure {
                spaces.push((node.kind(), kind, closure));
            }
        });
        assert_eq!(
            spaces,
            [
                ("source_file", SpaceKind::Unit, false),
                ("class_declaration", SpaceKind::Class, false),
                ("static_initializer", SpaceKind::Function, false),
                ("closure", SpaceKind::Unknown, true),
                ("object_creation_expression", SpaceKind::Class, false),
                ("closure", SpaceKind::Unknown, true),
            ]
        );
        assert!(!func_opener::OWNERS.contains(&(Groovy::Closure as u16)));
        assert!(container::OWNERS.contains(&(Groovy::ObjectCreationExpression as u16)));
    }

    // A node / token pairing with a negated spelling that has no token
    // (#1695): `o instanceof T` is owned by its node and paid by its
    // `instanceof`; `o !instanceof T` is owned and paid by the node,
    // since nothing else is there to pay. `a in b` and `a !in b` each
    // pay at their token, `!in` one since dekobon-tree-sitter-groovy
    // 0.6.0, where it was the node until then. One pays per test either
    // way, and the `in` of a `for` header pays nothing.
    #[cfg(feature = "groovy")]
    #[test]
    fn membership_pays_at_its_keyword_or_at_itself_when_negated() {
        let source = b"def f(a, b, o, xs) { def n = a in b; def nn = a !in b; def i = o instanceof String; def ni = o !instanceof String; for (x in xs) { } }\n";
        let mut paid = Vec::new();
        for_each_node_with_chain::<GroovyCode>(source, |node, chain| {
            let ancestors = Ancestors::known(chain);
            if comparison::pays_at_leaf(node, source, ancestors) {
                paid.push(node.utf8_text(source).expect("fixture is UTF-8").to_owned());
            }
        });
        assert_eq!(paid, ["in", "!in", "instanceof", "o !instanceof String"]);
    }
}