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