use crate::getter::node_text;
use crate::lang_helpers::doc_comment::{java_doc, node_bytes};
use crate::role_table;
use crate::roles::control_flow::else_if_prev_sibling_gate;
use crate::{Ancestors, Groovy, Node};
fn has_no_keyword_token<'a>(node: &Node<'a>, _code: &[u8], _ancestors: Ancestors<'a, '_>) -> bool {
comparison::project(node).is_none()
}
fn contextual_keyword_owns<'a>(
node: &Node<'a>,
_code: &[u8],
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)
)
})
}
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 {
use Groovy::*;
node_bytes(node, code) == b"var"
&& ancestors.parent(node).is_some_and(|parent| {
parent.is_error()
|| matches!(
parent.kind_id().into(),
FieldDeclaration | FormalParameter | Resource | CatchFormalParameter
)
})
}
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(pays_itself_when has_no_keyword_token),
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, 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),
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),
]
}
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] }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::GroovyCode;
use crate::test_support::for_each_node_with_chain;
#[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", "a !in b", "instanceof", "o !instanceof String"]
);
}
}