Skip to main content

big_code_analysis_ast/roles/
java.rs

1//! Java's role rows: one row of each shape the macro accepts, so the
2//! shapes were proven against a real grammar before any consumer read
3//! them (#1691). The Halstead keyword roles (#1693), the
4//! paying-construct roles — `Comparison`, `ShortCircuit`, `EagerLogical`,
5//! `Ternary`, `CaseArm`, `Guard`, `NullSafe` (#1694, #1695) — the space
6//! tree (#1696) and the control flow — `Branch`, `Switch`, `Loop`,
7//! `Catch`, `ElseIf`, `Exit` (#1697) — and
8//! the documentation rows (#1699) are declared.
9
10use crate::checker::java_anonymous_class_body;
11use crate::lang_helpers::doc_comment::java_doc;
12use crate::role_table;
13use crate::roles::control_flow::else_if_prev_sibling_gate;
14use crate::{Ancestors, Java, Node};
15
16// Whether a comment opens with javac's doc marker (`/**`, not `/**/`;
17// a `///` Markdown line, JEP 467), read from the bytes.
18crate::roles::byte_gate!(opens_with_javadoc_marker, java_doc);
19
20/// Whether a `package` declaration takes the file's first doc comment:
21/// javac's `attach` gives it the comment, javadoc reads a package's
22/// only from `package-info.java`, and javac's lint calls it dangling
23/// once a declaration follows — so a package documents when no
24/// declaration follows it before the next package, which is that
25/// file's shape (`package-info.java`), and a file of repeated packages
26/// — invalid, but parsed without error — is read in disjoint stretches
27/// rather than to its end from each one (#1446). The scan reads the
28/// row's *kind table* (`lists_kind`), never `owns`: asking `owns` of a
29/// sibling package would re-enter this gate from inside its own scan,
30/// quadratic on repeated packages.
31fn package_takes_the_file_doc<'a>(node: &Node<'a>, _: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
32    ancestors
33        .siblings_after(node)
34        .find(|n| doc_target::lists_kind(n.kind_id()))
35        .is_none_or(|n| n.kind_id() == Java::PackageDeclaration as u16)
36}
37
38/// Whether an `object_creation_expression` carries a `class_body`, which
39/// makes it an anonymous class rather than a plain `new Foo()` (#463).
40fn has_class_body(node: &Node<'_>, _code: &[u8]) -> bool {
41    java_anonymous_class_body(node).is_some()
42}
43
44// `else if` is an `if_statement` whose previous sibling is the bare `else`
45// token — no clause wrapper — so a nested `if` under `else { … }` follows
46// `{` instead (#1697).
47else_if_prev_sibling_gate!(Java, Else);
48
49/// The container a `switch` nests its arms in: the `switch_block`, the
50/// `Switch` owner's child — a structural fact about the construct the
51/// row recognises, pinned by
52/// `switch_body_is_the_owners_child_and_not_the_switch_rows`, not an
53/// owner of that row. The kind is claimed by `DocBodyResidual` (a
54/// `switch_block` holds a doc comment, #1699), which is a different
55/// question. Which consumer opens a level here (cognitive, so a ternary
56/// or lambda in the switch's *subject* does not inherit one, #1697) is
57/// that consumer's policy, and a consumer's structural projection of an
58/// owner's child lives as a named `fn` beside the table, as here
59/// (#1701); a DSL `body` attribute on the `Switch` row would be the
60/// declared form if a third grammar needs it.
61#[inline]
62#[must_use]
63pub fn is_switch_body_kind(kind: u16) -> bool {
64    kind == Java::SwitchBlock as u16
65}
66
67role_table! {
68    lang: Java;
69
70    // Projected and gated. A `binary_expression` owns a comparison only
71    // when its `operator` field holds one; the equality and ordering
72    // tokens pay unconditionally except `<` / `>`, which the grammar also
73    // emits as generic-type brackets. An `instanceof_expression` owns
74    // the type test — one node spans both the plain test and the Java
75    // 16 pattern form `x instanceof String s` — and its `instanceof`
76    // keyword pays, gated to that owner: the grammar spells the keyword
77    // in no other production, so one pays per test (#1461), and a
78    // keyword error recovery strands under an `ERROR` pays for no
79    // test. `?` is excluded here
80    // rather than left unmentioned: a ternary's `?` is a `Ternary`
81    // matter, a wildcard bound's is type syntax, and neither is a
82    // comparison.
83    Comparison {
84        owns [
85            BinaryExpression(holds_payer),
86            InstanceofExpression,
87        ]
88        pays [
89            EQEQ,
90            BANGEQ,
91            LTEQ,
92            GTEQ,
93            LT under BinaryExpression,
94            GT under BinaryExpression,
95            Instanceof under InstanceofExpression,
96        ]
97        project "operator"
98        excludes [QMARK "a `?` is a ternary's decision or a wildcard bound; `Ternary` owns it"]
99    }
100
101    // The same `binary_expression` owns an `&&` / `||` chain when its
102    // `operator` field holds one; the two tokens occur in no other
103    // production, so they pay ungated. `a && b || c` is a left-nested
104    // chain of these nodes, each owning one operator.
105    ShortCircuit {
106        owns [BinaryExpression(holds_payer)]
107        pays [AMPAMP, PIPEPIPE]
108        project "operator"
109    }
110
111    // `wraps`: a `string_literal` holding a `string_interpolation`
112    // child is a Java 21 string template (`STR."a \{x}"`), whose inner
113    // expressions are walked on their own. The set is what
114    // `Getter::string_operand_type` reads in `getter/java.rs` to leave
115    // such a wrapper unbilled (#420, wired by #1703).
116    // `MultilineStringLiteral` is the hidden `_multiline_string_literal`
117    // rule; the parser never emits it today, and the drift marker in the
118    // tests below pins that (grammar-dispatch §2).
119    StringLit {
120        owns [StringLiteral, MultilineStringLiteral]
121        wraps [StringInterpolation]
122    }
123
124    // Mapping. Every function opener is a `Function` space. The three
125    // `callable` owners are what `is_func` answers — a method, a
126    // constructor, and a record's compact constructor (#1160), each a
127    // function someone names at a call site. `static { … }` is not:
128    // it opens a space (#1184) and is nobody's callee, so it carries no
129    // `callable` and `nom` / `nargs` / `npm` never see it as a method.
130    // The lambda is *not* here: the walk promotes on
131    // `promotes_to_func_space_with_code`, and Java's `is_func` and
132    // `is_func_space` both leave `lambda_expression` out, so no lambda
133    // opens a space today — even though the byte-less `get_space_kind`
134    // labelled one `Function` before #1696. The row records the walk's
135    // answer, and the parity test below pins it against the walk's
136    // predicate.
137    FuncOpener {
138        owns [
139            MethodDeclaration(callable opens Function),
140            ConstructorDeclaration(callable opens Function),
141            CompactConstructorDeclaration(callable opens Function),
142            StaticInitializer(opens Function),
143        ]
144    }
145
146    // A closure that opens no space (contract 2 of #1690): recognised
147    // by `is_closure` for the arity and count metrics, promoted by
148    // nothing — see `FuncOpener` above.
149    Closure { owns [LambdaExpression] }
150
151    // Gated mapping: `new Runnable() { … }` opens a `Class` space only
152    // when it carries a body (#463). Enum, record and annotation types
153    // are class-like; annotation types map to `Interface` (#280).
154    Container {
155        owns [
156            Program(opens Unit),
157            ClassDeclaration(opens Class),
158            EnumDeclaration(opens Class),
159            RecordDeclaration(opens Class),
160            InterfaceDeclaration(opens Interface),
161            AnnotationTypeDeclaration(opens Interface),
162            ObjectCreationExpression(opens Class gated_by has_class_body no_chain),
163        ]
164    }
165
166    Call { owns [MethodInvocation] }
167
168    // A `case X when g ->` guard (Java 21) is the `guard` node, one
169    // decision paid at the node — cyclomatic counts it, ABC walks its
170    // expression as a boolean slot — and its `when` keyword bills
171    // nothing: a contextual keyword the grammar emits only here, which
172    // Halstead has never billed. R01's proof row said `pays never`,
173    // which was the Halstead reading; the counting consumers pay the
174    // node, so the owner is the paying projection (#1695).
175    Guard { owns [Guard] excludes [When "a contextual keyword Halstead has never billed"] }
176
177    NullSafe { absent "Java has no optional-navigation or null-coalescing operator" }
178    // JLS §15.22.2 makes `&` / `|` / `^` on boolean operands eager
179    // logical operators, and the grammar emits them as the same
180    // `binary_expression` as the integral forms, so the syntax alone
181    // cannot tell them apart; no consumer treats them as a decision,
182    // and the three tokens bill as the operators they are. A
183    // recognition boundary, recorded as the kinds considered rather
184    // than as an absence.
185    EagerLogical {
186        owns []
187        excludes [
188            AMP "a boolean `&` is the integral `&`'s kind, which the grammar does not tell apart",
189            PIPE "a boolean `|` is the integral `|`'s kind, which the grammar does not tell apart",
190            CARET "a boolean `^` is the integral `^`'s kind, which the grammar does not tell apart",
191        ]
192    }
193
194    // Filled in by the packages that migrate their consumers.
195    // The `ternary_expression` owns it and its `?` pays, gated to that
196    // owner: the grammar also spells `?` as a `wildcard` bound, which is
197    // type syntax (#1274). The `Comparison` row's exclusion above says
198    // the same.
199    Ternary {
200        owns [TernaryExpression]
201        pays [QMARK under TernaryExpression]
202        project "operator"
203    }
204    // A `switch_label` is the grammar's node for `case X` and `default`
205    // alike, in the colon form (`switch_block_statement_group`) and the
206    // arrow form (`switch_rule`); the label owns a decision when it
207    // holds the `case` keyword, which pays — one per label, so a
208    // fall-through run `case 2: case 3:` is two and a multi-pattern
209    // `case 2, 3 ->` is one. `default` is the fallback and pays nothing
210    // (lesson 11, #469); Halstead bills it as the keyword it is.
211    CaseArm {
212        owns [SwitchLabel(holds_payer)]
213        pays [Case]
214        excludes [Default "the fallback label, no decision (lesson 11, #469)"]
215    }
216    // The `if_statement` owns the branch; its `if` keyword pays. The
217    // keyword is the paying node because cyclomatic counts keyword
218    // tokens here (#284): the token fires once per `if`, inside an
219    // `else if` chain too, where the statement is the `ElseIf` row's
220    // and must not open a second nesting level in cognitive.
221    Branch { owns [IfStatement] pays [If] }
222    // The `switch_expression` is the grammar's one node for the
223    // statement and the Java 14 expression form alike; its `switch`
224    // keyword pays, once per switch, which keeps the modified count
225    // aligned with the `case` arms (#300). The `switch_block` — the
226    // arms' container, where cognitive opens its nesting level so a
227    // ternary or lambda in the *subject* does not inherit one (#1697:
228    // moving the level to this owner drifted) — is the owner's child,
229    // not this row's: `DocBodyResidual` claims the kind, for the doc
230    // comment its body can hold, and cognitive names it as the body of
231    // the construct this row recognises (`is_switch_body_kind`, #1701).
232    Switch { owns [SwitchExpression] pays [Switch] }
233    // Every loop statement, with its keyword paying: `for` fires once
234    // in a classic and an enhanced `for` alike, `while` once in a
235    // `while` and once in a `do … while` (#284).
236    Loop {
237        owns [ForStatement, EnhancedForStatement, WhileStatement, DoStatement]
238        pays [For, While]
239    }
240    // The `catch_clause`, paid at its `catch` keyword; `try` and
241    // `finally` are unconditional and pay nothing (#416).
242    Catch { owns [CatchClause] pays [Catch] }
243    // Java spells `else if` as an `if_statement` whose previous sibling
244    // is the bare `else` token — there is no clause wrapper — so the
245    // chained `if` is told from a nested one (`else { if … }`, whose
246    // previous sibling is `{`) by that sibling. Recognition only: the
247    // `Else` token already pays cognitive's +1 and the `if` keyword
248    // pays cyclomatic's through `Branch`, so no owner here pays at the
249    // leaf — a split row with no payers (#1697).
250    ElseIf { owns [IfStatement(gated_by follows_else_keyword)] pays [] }
251    // `return`, `throw` and a `switch` expression's `yield`, each a
252    // statement kind paid at the node.
253    Exit { owns [ReturnStatement, ThrowStatement, YieldStatement] }
254    // Every modifier, billed as C# and Kotlin bill theirs (#1565). Each
255    // is its keyword leaf, one kind apiece; the `modifiers` wrapper
256    // stays unlisted, so a modifier bills once and an annotation inside
257    // it adds only its own tokens. `default` is not here: it is one
258    // kind for a `switch` label and an interface method's modifier, and
259    // bills with the control keywords. `sealed` and `permits`
260    // (`Permits2`; `Permits` is the clause) are contextual, and the
261    // grammar parses each used as a name (`var sealed = 1`,
262    // `int permits`) as an `identifier`, so they need no gate. The
263    // `static` of `import static` and `requires static` sits under an
264    // `import_declaration` / `requires_modifier`, a directive that
265    // qualifies no declaration, and is not a modifier; what the
266    // Halstead consumer makes of directive words is its own
267    // (`java_modifiers_are_operators_1565`, #1600).
268    Modifier {
269        owns [
270            Public, Private, Protected, Static(not_under [ImportDeclaration, RequiresModifier]),
271            Abstract, Final,
272            Native, Strictfp, Synchronized, Transient, Volatile, Sealed, NonDASHsealed, Permits2,
273        ]
274    }
275    // The type-declaration keywords, billed as C# bills its own
276    // (#1552). Only the leaves: no `*_declaration` wrapper is listed, so
277    // a declaration bills its keyword once. A `class` under a
278    // `class_literal` (`C.class`) ends the literal and declares nothing:
279    // JLS §15.8.2 makes the literal a primary expression, not a literal
280    // (§3.10), so its parts are what they are anywhere else (#1566).
281    DeclKeyword {
282        owns [Class(not_under [ClassLiteral]), Interface, Enum, Record, ATinterface]
283    }
284    // Each primitive is a kind of its own (`int`, `boolean_type`, …), so
285    // none is keyed by text and `Checker::is_primitive` stays the
286    // default. `void` bills with them.
287    Primitive { owns [Byte, Short, Int, Long, Char, Float, Double, BooleanType, VoidType] }
288    // A field (`int a, b;` — one declaration, two `variable_declarator`
289    // children, which the attribute count walks) in a class, enum or
290    // record body, and an interface's or annotation type's constant.
291    // Recognition only: whether a member is public, and which body it
292    // sits in, is the consumers' reading (`npa/java.rs`). An annotation
293    // type's `int v() default 1;` (`annotation_type_element_declaration`)
294    // is an abstract method at the bytecode level and is counted by the
295    // method consumer, not here.
296    Member { owns [FieldDeclaration, ConstantDeclaration] }
297    // The two comment kinds; either can open with javac's doc marker,
298    // so both are `DocComment` owners under the byte gate and
299    // `is_comment` is the two rows' kind tables as one (#1699).
300    Comment { owns [LineComment, BlockComment] }
301    DocComment {
302        owns [
303            LineComment(text_gated_by opens_with_javadoc_marker no_chain),
304            BlockComment(text_gated_by opens_with_javadoc_marker no_chain),
305        ]
306    }
307    Docstring { absent "Java documents with comments, not string literals" }
308    // What javac attaches a doc comment to (`JavacParser`'s `attach`
309    // calls): a type, a member, an enum constant and a module. An
310    // import or a statement takes none, and an initializer's is
311    // dropped (`ignoreDanglingComments`). The package declaration is
312    // gated on the file's shape (#1446). The space-tree rows the
313    // targets overlap are `FuncOpener` / `Container` / `Member`; the
314    // targets outside those — the module, the enum constant, an
315    // annotation type's element (an abstract method at the bytecode
316    // level, counted by the method consumer and not a member here) —
317    // are the parity exceptions `roles/doc_tests/parity.rs` records.
318    DocTarget {
319        owns [
320            PackageDeclaration(gated_by package_takes_the_file_doc),
321            ModuleDeclaration,
322            ClassDeclaration,
323            InterfaceDeclaration,
324            EnumDeclaration,
325            RecordDeclaration,
326            AnnotationTypeDeclaration,
327            MethodDeclaration,
328            ConstructorDeclaration,
329            CompactConstructorDeclaration,
330            FieldDeclaration,
331            ConstantDeclaration,
332            AnnotationTypeElementDeclaration,
333            EnumConstant,
334        ]
335    }
336    DocRunOpener { absent "javadoc attaches every doc comment to a declaration; none documents by its own content" }
337    DocRunDirective { absent "javadoc reads no directive comment" }
338    // Beyond the callables and the lambda: a `static { … }` initializer
339    // (a `FuncOpener` that is nobody's callee, #1184), an instance
340    // initializer's bare `block`, and a `switch_block` — every one
341    // executable code, a field initializer's `switch` expression
342    // holding one outside any method — so javadoc reads a doc comment
343    // in each no more than one in a method body. The full answer is
344    // `func_opener::is_callable ∪ closure::owns ∪` this row, composed
345    // in `checker/java.rs`.
346    DocBodyResidual { owns [StaticInitializer, Block, SwitchBlock] }
347}
348
349#[cfg(test)]
350mod tests {
351    use super::*;
352    use crate::test_support::{ast_has_kind_id, for_each_node_with_chain};
353    use crate::{Checker, Getter, JavaCode, JavaParser, ParserTrait, SpaceKind};
354    use std::path::Path;
355
356    /// Every occurrence of each kind the `Comparison` row names, with
357    /// the row's three answers: `(kind, text, owns, leaf, wrapper)`.
358    #[cfg(feature = "java")]
359    fn comparison_occurrences(source: &[u8]) -> Vec<(Java, String, bool, bool, bool)> {
360        let mut seen = Vec::new();
361        for_each_node_with_chain::<JavaCode>(source, |node, chain| {
362            let kind: Java = node.kind_id().into();
363            if !matches!(
364                kind,
365                Java::BinaryExpression
366                    | Java::InstanceofExpression
367                    | Java::Instanceof
368                    | Java::LT
369                    | Java::GT
370                    | Java::EQEQ
371                    | Java::QMARK
372            ) {
373                return;
374            }
375            let ancestors = Ancestors::known(chain);
376            seen.push((
377                kind,
378                node.utf8_text(source).expect("fixture is UTF-8").to_owned(),
379                comparison::owns(node, source, ancestors),
380                comparison::pays_at_leaf(node, source, ancestors),
381                comparison::pays_at_wrapper(node, source, ancestors),
382            ));
383        });
384        seen
385    }
386
387    // Until #1696 the rows restated `checker/java.rs` and `getter/java.rs`
388    // and this compared the two; now the classifiers *read* the rows, so
389    // a comparison would be a forwarding check. The expected answer per
390    // kind is pinned independently here instead — on a fixture holding
391    // every kind the membership rows name, so a kind dropped from a row,
392    // or a classifier that stops reading its row, fails here rather than
393    // drifting silently (lesson 35). The per-shape tests above do not
394    // cover membership: dropping `YieldStatement` from `Exit` or
395    // `EnumDeclaration` from `Container` failed none of them.
396    /// `(is_func, is_closure, promoted, SpaceKind, is_member)`: the five
397    /// answers the space-tree and member consumers read of one node.
398    #[cfg(feature = "java")]
399    type Answers = (bool, bool, bool, SpaceKind, bool);
400
401    #[cfg(feature = "java")]
402    #[test]
403    #[allow(clippy::too_many_lines)]
404    fn classifiers_read_the_rows_and_the_rows_say_what_the_walk_did() {
405        let source = b"enum E { A; int f; }\nrecord R(int a) { R { } int g; }\ninterface I { int K = 1; void im(); }\n@interface An { int v() default 1; int C = 2; }\nclass C {\n  static { }\n  C() { }\n  String s = \"x\";\n  void m() { Runnable r = () -> m(); Object o = new Object() { }; Object p = new Object(); throw new RuntimeException(); }\n  int y(int s) { return switch (s) { default -> { yield 1; } }; }\n}\n";
406        // Per kind, as the classifiers answered before the rows and must
407        // answer after. A kind absent here answers all-false.
408        let expected: &[(&str, Answers)] = &[
409            ("program", (false, false, true, SpaceKind::Unit, false)),
410            (
411                "class_declaration",
412                (false, false, true, SpaceKind::Class, false),
413            ),
414            (
415                "enum_declaration",
416                (false, false, true, SpaceKind::Class, false),
417            ),
418            (
419                "record_declaration",
420                (false, false, true, SpaceKind::Class, false),
421            ),
422            (
423                "interface_declaration",
424                (false, false, true, SpaceKind::Interface, false),
425            ),
426            (
427                "annotation_type_declaration",
428                (false, false, true, SpaceKind::Interface, false),
429            ),
430            (
431                "method_declaration",
432                (true, false, true, SpaceKind::Function, false),
433            ),
434            (
435                "constructor_declaration",
436                (true, false, true, SpaceKind::Function, false),
437            ),
438            (
439                "compact_constructor_declaration",
440                (true, false, true, SpaceKind::Function, false),
441            ),
442            (
443                "static_initializer",
444                (false, false, true, SpaceKind::Function, false),
445            ),
446            (
447                "lambda_expression",
448                (false, true, false, SpaceKind::Unknown, false),
449            ),
450            (
451                "field_declaration",
452                (false, false, false, SpaceKind::Unknown, true),
453            ),
454            (
455                "constant_declaration",
456                (false, false, false, SpaceKind::Unknown, true),
457            ),
458        ];
459        let mut seen_kinds = std::collections::BTreeSet::new();
460        let mut anonymous = Vec::new();
461        for_each_node_with_chain::<JavaCode>(source, |node, chain| {
462            let ancestors = Ancestors::known(chain);
463            let kind = node.kind();
464            let promoted = JavaCode::promotes_to_func_space_with_code(node, source, ancestors);
465            let got = (
466                JavaCode::is_func(node, ancestors),
467                JavaCode::is_closure(node, ancestors),
468                promoted,
469                JavaCode::get_space_kind_with_code(node, source, ancestors),
470                member::owns(node, source, ancestors),
471            );
472            if kind == "object_creation_expression" {
473                // Gated on the body: `new Object() { }` opens a class;
474                // `new Object()` and `new RuntimeException()` nothing
475                // (#463), told apart by the gate; neither spelling is a
476                // function, a closure or a member.
477                anonymous.push(got);
478            } else {
479                let want = expected.iter().find(|(k, _)| *k == kind).map_or(
480                    (false, false, false, SpaceKind::Unknown, false),
481                    |(_, v)| *v,
482                );
483                assert_eq!(got, want, "{kind}");
484            }
485            // Promotion and labelling are the two halves of one answer.
486            assert_eq!(
487                got.3 != SpaceKind::Unknown,
488                promoted,
489                "{kind}: opens_space vs promotion"
490            );
491            assert_eq!(
492                JavaCode::is_func_space_with_code(node, source, ancestors),
493                promoted,
494                "{kind}: is_func_space is what the walk promotes"
495            );
496            // The byte-less pair is the kind table: the rows read no
497            // chain and no bytes, so it agrees with the `_with_code` pair
498            // on every node.
499            assert_eq!(
500                (
501                    JavaCode::is_func_space(node),
502                    JavaCode::get_space_kind(node)
503                ),
504                (promoted, got.3),
505                "{kind}: the byte-less spellings are the kind table"
506            );
507            assert_eq!(
508                call::owns(node, source, ancestors),
509                kind == "method_invocation",
510                "{kind}: Call"
511            );
512            assert_eq!(
513                string_lit::owns(node, source, ancestors),
514                kind == "string_literal",
515                "{kind}: StringLit"
516            );
517            assert_eq!(
518                exit::owns(node, source, ancestors),
519                matches!(
520                    kind,
521                    "return_statement" | "throw_statement" | "yield_statement"
522                ),
523                "{kind}: Exit"
524            );
525            seen_kinds.insert(node.kind_id());
526        });
527        assert_eq!(
528            anonymous,
529            [
530                (false, false, true, SpaceKind::Class, false),
531                (false, false, false, SpaceKind::Unknown, false),
532                (false, false, false, SpaceKind::Unknown, false),
533            ]
534        );
535        // Fixture guard: every kind the membership rows name was walked.
536        for kinds in [
537            exit::OWNERS,
538            call::OWNERS,
539            string_lit::OWNERS,
540            closure::OWNERS,
541            func_opener::OWNERS,
542            container::OWNERS,
543            member::OWNERS,
544        ] {
545            for &k in kinds {
546                // The hidden `_multiline_string_literal` is pinned unseen
547                // in `string_lit_row_declares_the_interpolation_child`.
548                if k == Java::MultilineStringLiteral as u16 {
549                    continue;
550                }
551                assert!(seen_kinds.contains(&k), "fixture never emits kind {k}");
552            }
553        }
554    }
555
556    // No gate: this reads the declared slices, which exist in every
557    // build, and parses nothing. All three tables are listed here, so
558    // the check does not depend on which grammars a build enables.
559    #[test]
560    fn declared_owner_and_payer_lists_are_disjoint_per_role() {
561        use crate::roles::{elixir, python};
562        for (role, owners, payers) in [
563            ("java comparison", comparison::OWNERS, comparison::PAYERS),
564            ("java exit", exit::OWNERS, exit::PAYERS),
565            ("java string_lit", string_lit::OWNERS, string_lit::PAYERS),
566            ("java func_opener", func_opener::OWNERS, func_opener::PAYERS),
567            ("java container", container::OWNERS, container::PAYERS),
568            ("java closure", closure::OWNERS, closure::PAYERS),
569            ("java call", call::OWNERS, call::PAYERS),
570            ("java guard", guard::OWNERS, guard::PAYERS),
571            (
572                "python comparison",
573                python::comparison::OWNERS,
574                python::comparison::PAYERS,
575            ),
576            ("python exit", python::exit::OWNERS, python::exit::PAYERS),
577            (
578                "python string_lit",
579                python::string_lit::OWNERS,
580                python::string_lit::PAYERS,
581            ),
582            (
583                "python closure",
584                python::closure::OWNERS,
585                python::closure::PAYERS,
586            ),
587            (
588                "python func_opener",
589                python::func_opener::OWNERS,
590                python::func_opener::PAYERS,
591            ),
592            (
593                "python container",
594                python::container::OWNERS,
595                python::container::PAYERS,
596            ),
597            ("python call", python::call::OWNERS, python::call::PAYERS),
598            (
599                "elixir func_opener",
600                elixir::func_opener::OWNERS,
601                elixir::func_opener::PAYERS,
602            ),
603            (
604                "elixir container",
605                elixir::container::OWNERS,
606                elixir::container::PAYERS,
607            ),
608            (
609                "elixir closure",
610                elixir::closure::OWNERS,
611                elixir::closure::PAYERS,
612            ),
613            ("elixir call", elixir::call::OWNERS, elixir::call::PAYERS),
614            (
615                "elixir string_lit",
616                elixir::string_lit::OWNERS,
617                elixir::string_lit::PAYERS,
618            ),
619        ] {
620            assert!(
621                !crate::roles::kinds_overlap(owners, payers),
622                "{role}: declared owners and payers overlap"
623            );
624        }
625        assert_eq!(guard::PAYERS, &[] as &[u16]);
626        assert_eq!((guard::PAYS_NEVER, comparison::PAYS_NEVER), (false, false));
627        assert_eq!(
628            comparison::EXCLUDED
629                .iter()
630                .map(|(k, _)| *k)
631                .collect::<Vec<_>>(),
632            [Java::QMARK as u16]
633        );
634    }
635
636    // The owner is the `binary_expression`, the payer its `<` token;
637    // `List<T>` emits the same token where nothing owns or pays. The
638    // `instanceof` test is owned by its expression node and paid by its
639    // keyword, one per test. The `&&` chain is a `binary_expression`
640    // too, and the gate keeps it out: it is `ShortCircuit`'s, not a
641    // comparison. A `?` reaches neither.
642    #[cfg(feature = "java")]
643    #[test]
644    fn comparison_row_separates_the_owner_from_its_token() {
645        let source = b"class A {\n  java.util.List<String> l;\n  boolean f(Object x, int a, int b) {\n    return x instanceof String s && a < b ? a == b : false;\n  }\n}\n";
646        let seen = comparison_occurrences(source);
647        let expect = [
648            (Java::LT, "<", false, false, false),
649            (Java::GT, ">", false, false, false),
650            (
651                Java::BinaryExpression,
652                "x instanceof String s && a < b",
653                false,
654                false,
655                false,
656            ),
657            (
658                Java::InstanceofExpression,
659                "x instanceof String s",
660                true,
661                false,
662                true,
663            ),
664            (Java::Instanceof, "instanceof", false, true, false),
665            (Java::BinaryExpression, "a < b", true, false, true),
666            (Java::LT, "<", false, true, false),
667            (Java::QMARK, "?", false, false, false),
668            (Java::BinaryExpression, "a == b", true, false, true),
669            (Java::EQEQ, "==", false, true, false),
670        ];
671        let want: Vec<_> = expect
672            .into_iter()
673            .map(|(k, t, o, l, w)| (k, t.to_owned(), o, l, w))
674            .collect();
675        assert_eq!(seen, want);
676    }
677
678    // A fixture only the `<` / `>` gate can decide: no equality token, no
679    // `instanceof`, so the comparison count is exactly the gate's answer.
680    #[cfg(feature = "java")]
681    #[test]
682    fn angle_tokens_pay_only_under_a_binary_expression() {
683        let source = b"class A { java.util.Map<String, java.util.List<Integer>> m; boolean f(int a) { return a > 1; } }\n";
684        let paying: Vec<_> = comparison_occurrences(source)
685            .into_iter()
686            .filter(|(k, ..)| matches!(k, Java::LT | Java::GT))
687            .map(|(_, text, _, leaf, _)| (text, leaf))
688            .collect();
689        assert_eq!(
690            paying,
691            [
692                ("<".to_owned(), false),
693                ("<".to_owned(), false),
694                (">".to_owned(), false),
695                (">".to_owned(), false),
696                (">".to_owned(), true),
697            ]
698        );
699    }
700
701    // A `binary_expression` projects through its `operator` field; an
702    // `instanceof_expression` has no such field, so the row's fallback
703    // finds the `instanceof` keyword among its children — in the plain
704    // test and the Java 16 pattern form alike.
705    #[cfg(feature = "java")]
706    #[test]
707    fn projection_lands_on_each_owners_paying_child() {
708        let source = b"class A { boolean f(int a, int b, Object o) { return a <= b && o instanceof String && o instanceof String s; } }\n";
709        let mut projected = Vec::new();
710        for_each_node_with_chain::<JavaCode>(source, |node, chain| {
711            if comparison::owns(node, source, Ancestors::known(chain)) {
712                let op = comparison::project(node).expect("every owner projects to a payer");
713                projected.push((op.kind_id(), op.utf8_text(source).map(str::to_owned)));
714            }
715        });
716        assert_eq!(
717            projected,
718            [
719                (Java::LTEQ as u16, Some("<=".to_owned())),
720                (Java::Instanceof as u16, Some("instanceof".to_owned())),
721                (Java::Instanceof as u16, Some("instanceof".to_owned())),
722            ]
723        );
724    }
725
726    // The template's `string_literal` wraps a `string_interpolation`;
727    // the plain literal beside it does not. Only the row's `WRAPS` set
728    // tells them apart — the declaration `Getter::string_operand_type`
729    // reads in `getter/java.rs` (#1703).
730    #[cfg(feature = "java")]
731    #[test]
732    fn string_lit_row_declares_the_interpolation_child() {
733        let source = b"class A { String s = STR.\"Hi \\{name}!\"; String t = \"plain\"; }\n";
734        let mut literals = Vec::new();
735        for_each_node_with_chain::<JavaCode>(source, |node, chain| {
736            if string_lit::owns(node, source, Ancestors::known(chain)) {
737                literals.push((
738                    node.utf8_text(source).map(str::to_owned),
739                    node.wraps_any(string_lit::WRAPS),
740                ));
741            }
742        });
743        assert_eq!(
744            literals,
745            [
746                (Some("\"Hi \\{name}!\"".to_owned()), true),
747                (Some("\"plain\"".to_owned()), false),
748            ]
749        );
750        assert_eq!(string_lit::WRAPS, &[Java::StringInterpolation as u16]);
751        // Drift marker: the hidden `_multiline_string_literal` rule is
752        // never emitted at the pinned grammar (grammar-dispatch §2).
753        let parser = JavaParser::new(
754            b"class A { String b = \"\"\"\n  text\n  \"\"\"; }\n".to_vec(),
755            Path::new("a.java"),
756            None,
757        );
758        assert!(!ast_has_kind_id(
759            &parser,
760            Java::MultilineStringLiteral as u16
761        ));
762    }
763
764    // One `opens_space` for the whole table, read from two rows: the
765    // anonymous class opens a `Class` only with a body; `new Foo()`
766    // opens nothing; the lambda is a closure that opens nothing.
767    #[cfg(feature = "java")]
768    #[test]
769    fn opens_space_folds_func_opener_and_container_without_restating_kinds() {
770        let source = b"class A {\n  static { }\n  Runnable r = () -> { };\n  Object o = new Object() { };\n  Object p = new Object();\n}\n";
771        let mut spaces = Vec::new();
772        for_each_node_with_chain::<JavaCode>(source, |node, chain| {
773            let ancestors = Ancestors::known(chain);
774            let kind = opens_space(node, source, ancestors);
775            let closure = closure::owns(node, source, ancestors);
776            if kind != SpaceKind::Unknown || closure {
777                spaces.push((node.kind(), kind, closure));
778            }
779        });
780        assert_eq!(
781            spaces,
782            [
783                ("program", SpaceKind::Unit, false),
784                ("class_declaration", SpaceKind::Class, false),
785                ("static_initializer", SpaceKind::Function, false),
786                ("lambda_expression", SpaceKind::Unknown, true),
787                ("object_creation_expression", SpaceKind::Class, false),
788            ]
789        );
790        assert!(!func_opener::OWNERS.contains(&(Java::LambdaExpression as u16)));
791        assert!(container::OWNERS.contains(&(Java::ObjectCreationExpression as u16)));
792    }
793
794    // The guard node is the one paying node (#1695): cyclomatic counts
795    // it and ABC walks its expression; its `when` keyword pays nothing.
796    #[cfg(feature = "java")]
797    #[test]
798    fn guard_row_owns_the_guard_and_pays_at_it() {
799        let source = b"class A { int f(Object o) { return switch (o) { case Integer i when i > 0 -> 1; default -> 0; }; } }\n";
800        let (mut owned, mut paid) = (Vec::new(), Vec::new());
801        for_each_node_with_chain::<JavaCode>(source, |node, chain| {
802            let ancestors = Ancestors::known(chain);
803            let text = || node.utf8_text(source).expect("fixture is UTF-8").to_owned();
804            if guard::owns(node, source, ancestors) {
805                owned.push(text());
806            }
807            if guard::pays_at_leaf(node, source, ancestors) {
808                paid.push(text());
809            }
810        });
811        assert_eq!(owned, ["when i > 0"]);
812        assert_eq!(paid, owned);
813    }
814
815    // A row with no `pays` list pays at its owners under both
816    // projections, whichever the consumer reads.
817    #[cfg(feature = "java")]
818    #[test]
819    fn plain_rows_answer_both_projections_the_same_way() {
820        let source = b"class A { int f(Object o) { return switch (o) { case Integer i when i > 0 -> 1; default -> 0; }; } }\n";
821        let mut exits = Vec::new();
822        let mut guards = Vec::new();
823        for_each_node_with_chain::<JavaCode>(source, |node, chain| {
824            let ancestors = Ancestors::known(chain);
825            if node.kind_id() == Java::ReturnStatement as u16 {
826                exits.push((
827                    exit::owns(node, source, ancestors),
828                    exit::pays_at_wrapper(node, source, ancestors),
829                    exit::pays_at_leaf(node, source, ancestors),
830                ));
831            }
832            if node.kind_id() == Java::Guard as u16 {
833                guards.push((
834                    guard::owns(node, source, ancestors),
835                    guard::pays_at_wrapper(node, source, ancestors),
836                    guard::pays_at_leaf(node, source, ancestors),
837                ));
838            }
839        });
840        assert_eq!(exits, [(true, true, true)]);
841        assert_eq!(guards, [(true, true, true)]);
842    }
843}