use std::cell::LazyCell;
use crate::getter::node_text;
use crate::lang_helpers::doc_comment::{java_doc, node_bytes, token_spelling};
use crate::role_table;
use crate::roles::control_flow::else_if_prev_sibling_gate;
use crate::{Ancestors, Groovy, GroovyCode, Node};
fn has_class_body(node: &Node<'_>) -> bool {
node.child_by_field_name("body").is_some()
}
fn has_no_keyword_token<'a>(node: &Node<'a>, _ancestors: Ancestors<'a, '_>) -> bool {
comparison::project(node).is_none()
}
fn contextual_keyword_owns<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
use Groovy::*;
ancestors.parent(node).is_some_and(|parent| {
matches!(
(node.kind_id().into(), parent.kind_id().into()),
(Trait, TraitDeclaration)
| (Record, RecordDeclaration)
| (Permits, PermitsClause)
| (
Sealed,
ClassDeclaration | InterfaceDeclaration | TraitDeclaration
)
| (
Var,
LocalVariableDeclaration
| FormalParameter
| ClosureParameter
| Resource
| CatchFormalParameter
)
)
})
}
fn groovy_parameter_type(param: &Node<'_>, code: &[u8]) -> Option<Vec<u8>> {
param
.child_by_field_name("type")
.map(|ty| token_spelling::<GroovyCode>(&ty, code))
.filter(|spelling| !matches!(spelling.as_slice(), b"def" | b"var"))
}
fn is_record_canonical_constructor(
ctor: &Node<'_>,
record: &Node<'_>,
components: &[Option<Vec<u8>>],
code: &[u8],
) -> bool {
let (Some(ctor_name), Some(record_name), Some(params)) = (
ctor.child_by_field_name("name"),
record.child_by_field_name("name"),
ctor.child_by_field_name("parameters"),
) else {
return false;
};
if node_bytes(&ctor_name, code) != node_bytes(&record_name, code) {
return false;
}
let mut declared = params
.children()
.filter(|p| p.kind_id() == Groovy::FormalParameter as u16)
.map(|p| groovy_parameter_type(&p, code));
components
.iter()
.all(|component| declared.next().as_ref() == Some(component))
&& declared.next().is_none()
}
#[inline]
#[must_use]
pub fn record_header<'a>(record: &Node<'a>) -> Option<Node<'a>> {
(record.kind_id() == Groovy::RecordDeclaration as u16)
.then(|| record.child_by_field_name("components"))
.flatten()
}
#[inline]
#[must_use]
pub fn is_record_header(list: &Node<'_>, record: &Node<'_>) -> bool {
record_header(record).is_some_and(|header| header.id() == list.id())
}
fn opens_record_header<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
let Some(record) = ancestors.parent(node) else {
return false;
};
if !is_record_header(node, &record) {
return false;
}
let Some(body) = record.child_by_field_name("body") else {
return true;
};
let components = LazyCell::new(|| {
record_header_types_read::record();
node.children()
.filter(|p| p.kind_id() == Groovy::RecordComponent as u16)
.map(|p| groovy_parameter_type(&p, code))
.collect::<Vec<_>>()
});
!body.children().any(|member| {
member.kind_id() == Groovy::ConstructorDeclaration as u16
&& is_record_canonical_constructor(&member, &record, &components, code)
})
}
crate::observation::counter!(record_header_types_read);
const PRIMITIVE_TYPES: &[&str] = &[
"boolean", "byte", "char", "double", "float", "int", "long", "short", "void",
];
fn spells_primitive_type<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
use Groovy::*;
if !node_text(code, node).is_some_and(|text| PRIMITIVE_TYPES.contains(&text)) {
return false;
}
ancestors.parent(node).is_none_or(|parent| {
let is_first_child = parent.child(0).is_some_and(|first| first.id() == node.id());
match parent.kind_id().into() {
FieldAccess
| SafeNavigationExpression
| SafeChainDotExpression
| SpreadDotExpression
| DirectFieldAccessExpression
| MethodPointerExpression
| MethodReferenceExpression => is_first_child,
MapEntry | NamedArgument => !is_first_child,
_ => true,
}
})
}
fn spells_var<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
node_bytes(node, code) == b"var"
&& ancestors.parent(node).is_some_and(|parent| {
parent.is_error() || parent.kind_id() == Groovy::FieldDeclaration as u16
})
}
else_if_prev_sibling_gate!(Groovy, Else);
#[inline]
#[must_use]
pub fn is_switch_body_kind(kind: u16) -> bool {
kind == Groovy::SwitchBlock as u16
}
crate::roles::byte_gate!(opens_with_groovydoc_marker, java_doc);
role_table! {
lang: Groovy;
Call { owns [MethodInvocation, CommandChain] }
StringLit {
owns [StringLiteral]
wraps [GstringBraceInterpolation, GstringDollarInterpolation]
}
Comparison {
owns [
BinaryExpression(holds_payer),
SpaceshipExpression, IdentityExpression, RegexFindExpression, RegexMatchExpression,
MembershipExpression,
InstanceofExpression(pays_itself_when has_no_keyword_token),
]
pays [
EQEQ, BANGEQ, LTEQ, GTEQ,
LT under BinaryExpression, GT under BinaryExpression,
LTEQGT, EQEQEQ, BANGEQEQ, EQTILDE, EQEQTILDE,
In under MembershipExpression, BANGin under MembershipExpression,
Instanceof under InstanceofExpression,
]
project "operator"
}
ShortCircuit {
owns [BinaryExpression(holds_payer)]
pays [AMPAMP, PIPEPIPE]
project "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"
}
NullSafe {
owns [
ElvisExpression(holds_payer),
SafeNavigationExpression(holds_payer),
SafeChainDotExpression(holds_payer),
SafeSubscriptExpression(holds_payer),
]
pays [QMARKCOLON, QMARKDOT, QMARKQMARKDOT, QMARKLBRACK]
project "operator"
}
CaseArm {
owns [SwitchCase(holds_payer)]
pays [Case]
excludes [
SwitchDefault "the fallback arm, no decision (lesson 11, #469)",
Default "the fallback label's keyword",
]
}
Guard { absent "Groovy has no guard clause on a case or a function head" }
Branch { owns [IfStatement] pays [If] }
Switch {
owns [SwitchExpression]
pays [Switch]
excludes [SwitchBlock "the owner's child; cognitive's projection is the named `is_switch_body_kind` beside the table"]
}
Loop {
owns [ForStatement, ForInStatement, WhileStatement, DoWhileStatement]
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]), Abstract, Final,
Native, Strictfp, Synchronized, Transient, Volatile, NonDASHsealed,
Sealed(gated_by contextual_keyword_owns), Permits(gated_by contextual_keyword_owns),
]
}
DeclKeyword {
owns [
Class, Interface, Enum, Def, Var(gated_by contextual_keyword_owns),
TypeIdentifier(text_gated_by spells_var),
Trait(gated_by contextual_keyword_owns), Record(gated_by contextual_keyword_owns),
]
}
Primitive {
owns [
Identifier(text_gated_by spells_primitive_type),
TypeIdentifier(text_gated_by spells_primitive_type),
]
}
FuncOpener {
owns [
MethodDeclaration(callable opens Function),
ConstructorDeclaration(callable opens Function),
RecordComponents(callable opens Function text_gated_by opens_record_header),
StaticInitializer(opens Function),
]
}
Closure { owns [Closure] }
Container {
owns [
SourceFile(opens Unit),
ClassDeclaration(opens Class),
EnumDeclaration(opens Class),
RecordDeclaration(opens Class),
InterfaceDeclaration(opens Interface),
TraitDeclaration(opens Interface),
AnnotationTypeDeclaration(opens Interface),
ObjectCreationExpression(opens Class gated_by has_class_body no_chain),
]
}
Member { owns [FieldDeclaration] }
Comment { owns [LineComment, BlockComment] }
DocComment { owns [GroovydocComment(text_gated_by opens_with_groovydoc_marker no_chain)] }
Docstring { absent "Groovy documents with comments, not string literals" }
DocTarget {
owns [
ClassDeclaration,
TraitDeclaration,
InterfaceDeclaration,
EnumDeclaration,
RecordDeclaration,
AnnotationTypeDeclaration,
MethodDeclaration,
ConstructorDeclaration,
FieldDeclaration,
EnumConstant,
]
}
DocRunOpener { absent "Groovydoc attaches every doc comment to a declaration; none documents by its own content" }
DocRunDirective { absent "Groovydoc reads no directive comment" }
DocBodyResidual { owns [StaticInitializer, Block] }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::for_each_node_with_chain;
use crate::{GroovyCode, SpaceKind};
#[cfg(feature = "groovy")]
#[test]
fn opens_space_folds_func_opener_and_container_without_restating_kinds() {
let source = b"class A {\n static { }\n def c = { x -> x }\n Object o = new Object() { }\n Object p = new Object()\n Object q = new Object().with { }\n}\n";
let mut spaces = Vec::new();
for_each_node_with_chain::<GroovyCode>(source, |node, chain| {
let ancestors = Ancestors::known(chain);
let kind = opens_space(node, source, ancestors);
let closure = closure::owns(node, source, ancestors);
if kind != SpaceKind::Unknown || closure {
spaces.push((node.kind(), kind, closure));
}
});
assert_eq!(
spaces,
[
("source_file", SpaceKind::Unit, false),
("class_declaration", SpaceKind::Class, false),
("static_initializer", SpaceKind::Function, false),
("closure", SpaceKind::Unknown, true),
("object_creation_expression", SpaceKind::Class, false),
("closure", SpaceKind::Unknown, true),
]
);
assert!(!func_opener::OWNERS.contains(&(Groovy::Closure as u16)));
assert!(container::OWNERS.contains(&(Groovy::ObjectCreationExpression as u16)));
}
#[cfg(feature = "groovy")]
#[test]
fn membership_pays_at_its_keyword_or_at_itself_when_negated() {
let source = b"def f(a, b, o, xs) { def n = a in b; def nn = a !in b; def i = o instanceof String; def ni = o !instanceof String; for (x in xs) { } }\n";
let mut paid = Vec::new();
for_each_node_with_chain::<GroovyCode>(source, |node, chain| {
let ancestors = Ancestors::known(chain);
if comparison::pays_at_leaf(node, source, ancestors) {
paid.push(node.utf8_text(source).expect("fixture is UTF-8").to_owned());
}
});
assert_eq!(paid, ["in", "!in", "instanceof", "o !instanceof String"]);
}
}