use std::cell::LazyCell;
use crate::checker::java_anonymous_class_body;
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, Checker, Java, JavaCode, Node};
crate::roles::byte_gate!(opens_with_javadoc_marker, java_doc);
fn package_takes_the_file_doc<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
ancestors
.siblings_after(node)
.find(|n| doc_target::lists_kind(n.kind_id()))
.is_none_or(|n| n.kind_id() == Java::PackageDeclaration as u16)
}
fn has_class_body(node: &Node<'_>) -> bool {
java_anonymous_class_body(node).is_some()
}
else_if_prev_sibling_gate!(Java, Else);
#[derive(PartialEq, Eq)]
struct ParameterType {
spelling: Vec<u8>,
variadic: bool,
}
fn java_parameter_type(param: &Node<'_>, code: &[u8]) -> Option<ParameterType> {
match param.kind_id().into() {
Java::FormalParameter => {
let mut spelling =
token_spelling::<JavaCode>(¶m.child_by_field_name("type")?, code);
if let Some(dims) = param.child_by_field_name("dimensions") {
spelling.extend(token_spelling::<JavaCode>(&dims, code));
}
Some(ParameterType {
spelling,
variadic: false,
})
}
Java::SpreadParameter => param
.children()
.find(|c| {
c.is_named()
&& !JavaCode::is_comment(c)
&& !matches!(
c.kind_id().into(),
Java::Modifiers | Java::Annotation | Java::MarkerAnnotation
)
})
.map(|ty| ParameterType {
spelling: token_spelling::<JavaCode>(&ty, code),
variadic: true,
}),
_ => None,
}
}
fn is_record_canonical_constructor(
ctor: &Node<'_>,
record: &Node<'_>,
components: &[ParameterType],
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_map(|p| java_parameter_type(&p, code));
components
.iter()
.all(|component| declared.next().as_ref() == Some(component))
&& declared.next().is_none()
}
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_map(|p| java_parameter_type(&p, code))
.collect::<Vec<_>>()
});
!body.children().any(|member| match member.kind_id().into() {
Java::CompactConstructorDeclaration => true,
Java::ConstructorDeclaration => {
is_record_canonical_constructor(&member, &record, &components, code)
}
_ => false,
})
}
#[inline]
#[must_use]
pub fn record_header<'a>(record: &Node<'a>) -> Option<Node<'a>> {
(record.kind_id() == Java::RecordDeclaration as u16)
.then(|| record.child_by_field_name("parameters"))
.flatten()
}
#[inline]
#[must_use]
pub fn is_record_header(list: &Node<'_>, record: &Node<'_>) -> bool {
record_header(record).is_some_and(|header| header.id() == list.id())
}
crate::observation::counter!(record_header_types_read);
#[inline]
#[must_use]
pub fn is_switch_body_kind(kind: u16) -> bool {
kind == Java::SwitchBlock as u16
}
role_table! {
lang: Java;
Comparison {
owns [
BinaryExpression(holds_payer),
InstanceofExpression,
]
pays [
EQEQ,
BANGEQ,
LTEQ,
GTEQ,
LT under BinaryExpression,
GT under BinaryExpression,
Instanceof under InstanceofExpression,
]
project "operator"
excludes [QMARK "a `?` is a ternary's decision or a wildcard bound; `Ternary` owns it"]
}
ShortCircuit {
owns [BinaryExpression(holds_payer)]
pays [AMPAMP, PIPEPIPE]
project "operator"
}
StringLit {
owns [StringLiteral, MultilineStringLiteral]
wraps [StringInterpolation]
}
FuncOpener {
owns [
MethodDeclaration(callable opens Function),
ConstructorDeclaration(callable opens Function),
CompactConstructorDeclaration(callable opens Function),
FormalParameters(callable opens Function text_gated_by opens_record_header),
StaticInitializer(opens Function),
]
}
Closure { owns [LambdaExpression] }
Container {
owns [
Program(opens Unit),
ClassDeclaration(opens Class),
EnumDeclaration(opens Class),
RecordDeclaration(opens Class),
InterfaceDeclaration(opens Interface),
AnnotationTypeDeclaration(opens Interface),
ObjectCreationExpression(opens Class gated_by has_class_body no_chain),
]
}
Call { owns [MethodInvocation] }
Guard { owns [Guard] excludes [When "a contextual keyword Halstead has never billed"] }
NullSafe { absent "Java has no optional-navigation or null-coalescing operator" }
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",
]
}
Ternary {
owns [TernaryExpression]
pays [QMARK under TernaryExpression]
project "operator"
}
CaseArm {
owns [SwitchLabel(holds_payer)]
pays [Case]
excludes [Default "the fallback label, no decision (lesson 11, #469)"]
}
Branch { owns [IfStatement] pays [If] }
Switch { owns [SwitchExpression] pays [Switch] }
Loop {
owns [ForStatement, EnhancedForStatement, WhileStatement, DoStatement]
pays [For, While]
}
Catch { owns [CatchClause] pays [Catch] }
ElseIf { owns [IfStatement(gated_by follows_else_keyword)] pays [] }
Exit { owns [ReturnStatement, ThrowStatement, YieldStatement] }
Modifier {
owns [
Public, Private, Protected, Static(not_under [ImportDeclaration, RequiresModifier]),
Abstract, Final,
Native, Strictfp, Synchronized, Transient, Volatile, Sealed, NonDASHsealed, Permits2,
]
}
DeclKeyword {
owns [Class(not_under [ClassLiteral]), Interface, Enum, Record, ATinterface]
}
Primitive { owns [Byte, Short, Int, Long, Char, Float, Double, BooleanType, VoidType] }
Member { owns [FieldDeclaration, ConstantDeclaration] }
Comment { owns [LineComment, BlockComment] }
DocComment {
owns [
LineComment(text_gated_by opens_with_javadoc_marker no_chain),
BlockComment(text_gated_by opens_with_javadoc_marker no_chain),
]
}
Docstring { absent "Java documents with comments, not string literals" }
DocTarget {
owns [
PackageDeclaration(gated_by package_takes_the_file_doc),
ModuleDeclaration,
ClassDeclaration,
InterfaceDeclaration,
EnumDeclaration,
RecordDeclaration,
AnnotationTypeDeclaration,
MethodDeclaration,
ConstructorDeclaration,
CompactConstructorDeclaration,
FieldDeclaration,
ConstantDeclaration,
AnnotationTypeElementDeclaration,
EnumConstant,
]
}
DocRunOpener { absent "javadoc attaches every doc comment to a declaration; none documents by its own content" }
DocRunDirective { absent "javadoc reads no directive comment" }
DocBodyResidual { owns [StaticInitializer, Block, SwitchBlock] }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::{ast_has_kind_id, for_each_node_with_chain};
use crate::{Checker, Getter, JavaCode, JavaParser, ParserTrait, SpaceKind};
use std::path::Path;
#[cfg(feature = "java")]
fn comparison_occurrences(source: &[u8]) -> Vec<(Java, String, bool, bool, bool)> {
let mut seen = Vec::new();
for_each_node_with_chain::<JavaCode>(source, |node, chain| {
let kind: Java = node.kind_id().into();
if !matches!(
kind,
Java::BinaryExpression
| Java::InstanceofExpression
| Java::Instanceof
| Java::LT
| Java::GT
| Java::EQEQ
| Java::QMARK
) {
return;
}
let ancestors = Ancestors::known(chain);
seen.push((
kind,
node.utf8_text(source).expect("fixture is UTF-8").to_owned(),
comparison::owns(node, source, ancestors),
comparison::pays_at_leaf(node, source, ancestors),
comparison::pays_at_wrapper(node, source, ancestors),
));
});
seen
}
#[cfg(feature = "java")]
type Answers = (bool, bool, bool, SpaceKind, bool);
#[cfg(feature = "java")]
#[test]
#[allow(clippy::too_many_lines)]
fn classifiers_read_the_rows_and_the_rows_say_what_the_walk_did() {
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";
let expected: &[(&str, Answers)] = &[
("program", (false, false, true, SpaceKind::Unit, false)),
(
"class_declaration",
(false, false, true, SpaceKind::Class, false),
),
(
"enum_declaration",
(false, false, true, SpaceKind::Class, false),
),
(
"record_declaration",
(false, false, true, SpaceKind::Class, false),
),
(
"interface_declaration",
(false, false, true, SpaceKind::Interface, false),
),
(
"annotation_type_declaration",
(false, false, true, SpaceKind::Interface, false),
),
(
"method_declaration",
(true, false, true, SpaceKind::Function, false),
),
(
"constructor_declaration",
(true, false, true, SpaceKind::Function, false),
),
(
"compact_constructor_declaration",
(true, false, true, SpaceKind::Function, false),
),
(
"static_initializer",
(false, false, true, SpaceKind::Function, false),
),
(
"lambda_expression",
(false, true, false, SpaceKind::Unknown, false),
),
(
"field_declaration",
(false, false, false, SpaceKind::Unknown, true),
),
(
"constant_declaration",
(false, false, false, SpaceKind::Unknown, true),
),
];
let none = (false, false, false, SpaceKind::Unknown, false);
let mut seen_kinds = std::collections::BTreeSet::new();
let mut anonymous = Vec::new();
let mut headers = Vec::new();
for_each_node_with_chain::<JavaCode>(source, |node, chain| {
let ancestors = Ancestors::known(chain);
let kind = node.kind();
let promoted = JavaCode::promotes_to_func_space_with_code(node, source, ancestors);
let got = (
JavaCode::is_func_with_code(node, source, ancestors),
JavaCode::is_closure(node, ancestors),
promoted,
JavaCode::get_space_kind_with_code(node, source, ancestors),
member::owns(node, source, ancestors),
);
if kind == "object_creation_expression" {
anonymous.push(got);
} else if kind == "formal_parameters" {
headers.push((node.utf8_text(source).unwrap_or("?").to_owned(), got));
} else {
let want = expected
.iter()
.find(|(k, _)| *k == kind)
.map_or(none, |(_, v)| *v);
assert_eq!(got, want, "{kind}");
}
assert_eq!(
got.3 != SpaceKind::Unknown,
promoted,
"{kind}: opens_space vs promotion"
);
assert_eq!(
JavaCode::is_func_space_with_code(node, source, ancestors),
promoted,
"{kind}: is_func_space is what the walk promotes"
);
if kind != "formal_parameters" {
assert_eq!(
(
JavaCode::is_func_space(node),
JavaCode::get_space_kind(node)
),
(promoted, got.3),
"{kind}: the byte-less spellings are the kind table"
);
}
assert_eq!(
call::owns(node, source, ancestors),
kind == "method_invocation",
"{kind}: Call"
);
assert_eq!(
string_lit::owns(node, source, ancestors),
kind == "string_literal",
"{kind}: StringLit"
);
assert_eq!(
exit::owns(node, source, ancestors),
matches!(
kind,
"return_statement" | "throw_statement" | "yield_statement"
),
"{kind}: Exit"
);
seen_kinds.insert(node.kind_id());
});
assert_eq!(
anonymous,
[(false, false, true, SpaceKind::Class, false), none, none]
);
assert_eq!(
headers,
[
("(int a)".to_owned(), none),
(
"(int q)".to_owned(),
(true, false, true, SpaceKind::Function, false)
),
("()".to_owned(), none),
("()".to_owned(), none),
("()".to_owned(), none),
("()".to_owned(), none),
("(int s)".to_owned(), none),
]
);
for kinds in [
exit::OWNERS,
call::OWNERS,
string_lit::OWNERS,
closure::OWNERS,
func_opener::OWNERS,
container::OWNERS,
member::OWNERS,
] {
for &k in kinds {
if k == Java::MultilineStringLiteral as u16 {
continue;
}
assert!(seen_kinds.contains(&k), "fixture never emits kind {k}");
}
}
}
#[test]
fn declared_owner_and_payer_lists_are_disjoint_per_role() {
use crate::roles::{elixir, python};
for (role, owners, payers) in [
("java comparison", comparison::OWNERS, comparison::PAYERS),
("java exit", exit::OWNERS, exit::PAYERS),
("java string_lit", string_lit::OWNERS, string_lit::PAYERS),
("java func_opener", func_opener::OWNERS, func_opener::PAYERS),
("java container", container::OWNERS, container::PAYERS),
("java closure", closure::OWNERS, closure::PAYERS),
("java call", call::OWNERS, call::PAYERS),
("java guard", guard::OWNERS, guard::PAYERS),
(
"python comparison",
python::comparison::OWNERS,
python::comparison::PAYERS,
),
("python exit", python::exit::OWNERS, python::exit::PAYERS),
(
"python string_lit",
python::string_lit::OWNERS,
python::string_lit::PAYERS,
),
(
"python closure",
python::closure::OWNERS,
python::closure::PAYERS,
),
(
"python func_opener",
python::func_opener::OWNERS,
python::func_opener::PAYERS,
),
(
"python container",
python::container::OWNERS,
python::container::PAYERS,
),
("python call", python::call::OWNERS, python::call::PAYERS),
(
"elixir func_opener",
elixir::func_opener::OWNERS,
elixir::func_opener::PAYERS,
),
(
"elixir container",
elixir::container::OWNERS,
elixir::container::PAYERS,
),
(
"elixir closure",
elixir::closure::OWNERS,
elixir::closure::PAYERS,
),
("elixir call", elixir::call::OWNERS, elixir::call::PAYERS),
(
"elixir string_lit",
elixir::string_lit::OWNERS,
elixir::string_lit::PAYERS,
),
] {
assert!(
!crate::roles::kinds_overlap(owners, payers),
"{role}: declared owners and payers overlap"
);
}
assert_eq!(guard::PAYERS, &[] as &[u16]);
assert_eq!((guard::PAYS_NEVER, comparison::PAYS_NEVER), (false, false));
assert_eq!(
comparison::EXCLUDED
.iter()
.map(|(k, _)| *k)
.collect::<Vec<_>>(),
[Java::QMARK as u16]
);
}
#[cfg(feature = "java")]
#[test]
fn comparison_row_separates_the_owner_from_its_token() {
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";
let seen = comparison_occurrences(source);
let expect = [
(Java::LT, "<", false, false, false),
(Java::GT, ">", false, false, false),
(
Java::BinaryExpression,
"x instanceof String s && a < b",
false,
false,
false,
),
(
Java::InstanceofExpression,
"x instanceof String s",
true,
false,
true,
),
(Java::Instanceof, "instanceof", false, true, false),
(Java::BinaryExpression, "a < b", true, false, true),
(Java::LT, "<", false, true, false),
(Java::QMARK, "?", false, false, false),
(Java::BinaryExpression, "a == b", true, false, true),
(Java::EQEQ, "==", false, true, false),
];
let want: Vec<_> = expect
.into_iter()
.map(|(k, t, o, l, w)| (k, t.to_owned(), o, l, w))
.collect();
assert_eq!(seen, want);
}
#[cfg(feature = "java")]
#[test]
fn angle_tokens_pay_only_under_a_binary_expression() {
let source = b"class A { java.util.Map<String, java.util.List<Integer>> m; boolean f(int a) { return a > 1; } }\n";
let paying: Vec<_> = comparison_occurrences(source)
.into_iter()
.filter(|(k, ..)| matches!(k, Java::LT | Java::GT))
.map(|(_, text, _, leaf, _)| (text, leaf))
.collect();
assert_eq!(
paying,
[
("<".to_owned(), false),
("<".to_owned(), false),
(">".to_owned(), false),
(">".to_owned(), false),
(">".to_owned(), true),
]
);
}
#[cfg(feature = "java")]
#[test]
fn projection_lands_on_each_owners_paying_child() {
let source = b"class A { boolean f(int a, int b, Object o) { return a <= b && o instanceof String && o instanceof String s; } }\n";
let mut projected = Vec::new();
for_each_node_with_chain::<JavaCode>(source, |node, chain| {
if comparison::owns(node, source, Ancestors::known(chain)) {
let op = comparison::project(node).expect("every owner projects to a payer");
projected.push((op.kind_id(), op.utf8_text(source).map(str::to_owned)));
}
});
assert_eq!(
projected,
[
(Java::LTEQ as u16, Some("<=".to_owned())),
(Java::Instanceof as u16, Some("instanceof".to_owned())),
(Java::Instanceof as u16, Some("instanceof".to_owned())),
]
);
}
#[cfg(feature = "java")]
#[test]
fn string_lit_row_declares_the_interpolation_child() {
let source = b"class A { String s = STR.\"Hi \\{name}!\"; String t = \"plain\"; }\n";
let mut literals = Vec::new();
for_each_node_with_chain::<JavaCode>(source, |node, chain| {
if string_lit::owns(node, source, Ancestors::known(chain)) {
literals.push((
node.utf8_text(source).map(str::to_owned),
node.wraps_any(string_lit::WRAPS),
));
}
});
assert_eq!(
literals,
[
(Some("\"Hi \\{name}!\"".to_owned()), true),
(Some("\"plain\"".to_owned()), false),
]
);
assert_eq!(string_lit::WRAPS, &[Java::StringInterpolation as u16]);
let parser = JavaParser::new(
b"class A { String b = \"\"\"\n text\n \"\"\"; }\n".to_vec(),
Path::new("a.java"),
None,
);
assert!(!ast_has_kind_id(
&parser,
Java::MultilineStringLiteral as u16
));
}
#[cfg(feature = "java")]
#[test]
fn opens_space_folds_func_opener_and_container_without_restating_kinds() {
let source = b"class A {\n static { }\n Runnable r = () -> { };\n Object o = new Object() { };\n Object p = new Object();\n}\n";
let mut spaces = Vec::new();
for_each_node_with_chain::<JavaCode>(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,
[
("program", SpaceKind::Unit, false),
("class_declaration", SpaceKind::Class, false),
("static_initializer", SpaceKind::Function, false),
("lambda_expression", SpaceKind::Unknown, true),
("object_creation_expression", SpaceKind::Class, false),
]
);
assert!(!func_opener::OWNERS.contains(&(Java::LambdaExpression as u16)));
assert!(container::OWNERS.contains(&(Java::ObjectCreationExpression as u16)));
}
#[cfg(feature = "java")]
#[test]
fn guard_row_owns_the_guard_and_pays_at_it() {
let source = b"class A { int f(Object o) { return switch (o) { case Integer i when i > 0 -> 1; default -> 0; }; } }\n";
let (mut owned, mut paid) = (Vec::new(), Vec::new());
for_each_node_with_chain::<JavaCode>(source, |node, chain| {
let ancestors = Ancestors::known(chain);
let text = || node.utf8_text(source).expect("fixture is UTF-8").to_owned();
if guard::owns(node, source, ancestors) {
owned.push(text());
}
if guard::pays_at_leaf(node, source, ancestors) {
paid.push(text());
}
});
assert_eq!(owned, ["when i > 0"]);
assert_eq!(paid, owned);
}
#[cfg(feature = "java")]
#[test]
fn plain_rows_answer_both_projections_the_same_way() {
let source = b"class A { int f(Object o) { return switch (o) { case Integer i when i > 0 -> 1; default -> 0; }; } }\n";
let mut exits = Vec::new();
let mut guards = Vec::new();
for_each_node_with_chain::<JavaCode>(source, |node, chain| {
let ancestors = Ancestors::known(chain);
if node.kind_id() == Java::ReturnStatement as u16 {
exits.push((
exit::owns(node, source, ancestors),
exit::pays_at_wrapper(node, source, ancestors),
exit::pays_at_leaf(node, source, ancestors),
));
}
if node.kind_id() == Java::Guard as u16 {
guards.push((
guard::owns(node, source, ancestors),
guard::pays_at_wrapper(node, source, ancestors),
guard::pays_at_leaf(node, source, ancestors),
));
}
});
assert_eq!(exits, [(true, true, true)]);
assert_eq!(guards, [(true, true, true)]);
}
}