use crate::lang_helpers::doc_comment::{node_bytes, pod_comment_region};
use crate::lang_helpers::perl::{
perl_and_is_operator, perl_bareword_is_call, perl_bareword_is_key,
};
use crate::role_table;
use crate::{Ancestors, Node, Perl};
fn pod_documents(node: &Node<'_>, code: &[u8]) -> bool {
!pod_comment_region(node_bytes(node, code))
}
fn short_circuit_operator(node: &Node<'_>) -> bool {
node.children().any(|token| {
let kind = token.kind_id();
if kind == Perl::And as u16 {
perl_and_is_operator(&token, node)
} else {
short_circuit::PAYERS.contains(&kind)
}
})
}
fn applied_and<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
ancestors
.parent(node)
.is_some_and(|parent| perl_and_is_operator(node, &parent))
}
fn bareword_is_call<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
perl_bareword_is_call(node, ancestors)
}
fn die_or_exit_not_key<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
matches!(
node.utf8_text(code),
Some("die" | "exit" | "CORE::die" | "CORE::exit")
) && !perl_bareword_is_key(node, ancestors)
}
fn has_condition(node: &Node<'_>) -> bool {
node.child_by_field_name("condition").is_some()
}
role_table! {
lang: Perl;
Call {
owns [
CallExpressionWithSpacedArgs,
CallExpressionWithSub,
CallExpressionWithArgsWithBrackets,
CallExpressionWithVariable,
CallExpressionWithBareword(gated_by bareword_is_call),
CallExpressionRecursive,
MethodInvocation,
]
}
StringLit {
owns [
StringSingleQuoted,
StringDoubleQuoted,
StringQQuoted,
StringQqQuoted,
BacktickQuoted,
CommandQxQuoted,
HeredocBodyStatement,
]
wraps [Interpolation, ListItem]
}
Comparison {
owns [BinaryExpression(holds_payer)]
pays [
EQEQ, BANGEQ, LTEQ, GTEQ, LTEQGT, Eq, Ne, Lt, Gt, Le, Ge, Cmp, EQTILDE, BANGTILDE,
LT under BinaryExpression, GT under BinaryExpression,
]
project "operator"
}
ShortCircuit {
owns [
BinaryExpression(gated_by short_circuit_operator no_chain),
UnaryExpression(gated_by short_circuit_operator no_chain),
]
pays [AMPAMP, PIPEPIPE, Or, And gated_by applied_and]
project "operator"
}
EagerLogical {
owns [BinaryExpression(holds_payer)]
pays [Xor]
project "operator"
}
Ternary {
owns [TernaryExpression]
pays [QMARK]
project "operator"
}
NullSafe {
owns [BinaryExpression(holds_payer)]
pays [SLASHSLASH]
project "operator"
excludes [SLASHSLASHEQ "the compound `//=`, an assignment ABC pays as one and a decision cyclomatic pays as its own (#249)"]
}
CaseArm {
owns [WhenSimpleStatement]
excludes [When "the arm's keyword, billed as such; the arm pays"]
}
Guard { absent "Perl has no guard clause" }
Branch {
owns [
IfStatement, UnlessStatement, IfSimpleStatement, UnlessSimpleStatement,
RequireStatement(gated_by has_condition no_chain),
]
}
Switch { absent "the pinned tree-sitter-perl grammar has no `given` production; `given ($x) \
{ … }` parses as a bareword call with an ERROR tail" }
Loop {
owns [
WhileStatement, UntilStatement, ForStatement1, ForStatement2,
WhileSimpleStatement, UntilSimpleStatement, ForSimpleStatement,
]
}
Catch { absent "the pinned tree-sitter-perl grammar has no try or catch production; `eval { }` \
parses as a block and `die` as a call" }
ElseIf { owns [ElsifClause(pays_itself)] pays [] }
Exit {
owns [ReturnExpression, CallExpressionWithBareword(text_gated_by die_or_exit_not_key)]
}
Modifier { absent "Perl has no modifier keywords; `my` / `our` are declarators" }
DeclKeyword { owns [Sub, Package, My, Our, Local, State] }
Primitive { absent "Perl has no type names" }
FuncOpener {
owns [
FunctionDefinition(callable opens Function),
FunctionDefinitionWithoutSub(callable opens Function),
AnonymousFunction(opens Function),
]
}
Closure { owns [AnonymousFunction] }
Container { owns [SourceFile(opens Unit)] }
Member { absent "Perl has no container space to hold a member; a package is not one" }
Comment { owns [Comments] }
DocComment { owns [PodStatement(text_gated_by pod_documents no_chain)] }
Docstring { absent "Perl documents with POD, not string literals" }
DocTarget { absent "perldoc reads POD wherever it sits; no declaration is its target" }
DocRunOpener { absent "a POD block is documentation by its own kind, not by opening a run" }
DocRunDirective { absent "perldoc reads no directive comment" }
DocBodyResidual { absent "perldoc reads POD in any body; no kind withholds it" }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::PerlCode;
use crate::test_support::for_each_node_with_chain;
#[cfg(feature = "perl")]
#[test]
fn eager_logical_owns_xor_and_nothing_beside_it() {
let source = b"my $c = $a xor $b; my $d = $a or $b; my %h = (xor => 1);\n";
let (mut owned, mut paid) = (Vec::new(), Vec::new());
for_each_node_with_chain::<PerlCode>(source, |node, chain| {
let ancestors = Ancestors::known(chain);
let text = || node.utf8_text(source).expect("fixture is UTF-8").to_owned();
if eager_logical::owns(node, source, ancestors) {
let op = eager_logical::project(node).expect("an owner projects to its token");
assert_eq!(op.utf8_text(source), Some("xor"), "{}", text());
owned.push(text());
}
if eager_logical::pays_at_leaf(node, source, ancestors) {
paid.push(text());
}
assert!(
!(eager_logical::owns(node, source, ancestors)
&& short_circuit::owns(node, source, ancestors)),
"{}",
text()
);
});
assert_eq!(owned, ["my $c = $a xor $b"]);
assert_eq!(paid, ["xor"]);
}
#[cfg(feature = "perl")]
#[test]
fn every_kind_with_a_condition_field_is_listed_by_a_row() {
type ListsKind = fn(u16) -> bool;
let node_types: serde_json::Value = serde_json::from_str(tree_sitter_perl::NODE_TYPES)
.expect("the grammar crate ships valid node-types.json");
let carriers: Vec<&str> = node_types
.as_array()
.into_iter()
.flatten()
.filter(|node| node["fields"]["condition"].is_object())
.filter_map(|node| node["type"].as_str())
.collect();
let rows: [(Perl, ListsKind); 13] = [
(Perl::ElsifClause, else_if::lists_kind),
(Perl::ForStatement1, r#loop::lists_kind),
(Perl::IfSimpleStatement, branch::lists_kind),
(Perl::IfStatement, branch::lists_kind),
(Perl::RequireStatement, branch::lists_kind),
(Perl::TernaryExpression, ternary::lists_kind),
(Perl::UnlessSimpleStatement, branch::lists_kind),
(Perl::UnlessStatement, branch::lists_kind),
(Perl::UntilSimpleStatement, r#loop::lists_kind),
(Perl::UntilStatement, r#loop::lists_kind),
(Perl::WhenSimpleStatement, case_arm::lists_kind),
(Perl::WhileSimpleStatement, r#loop::lists_kind),
(Perl::WhileStatement, r#loop::lists_kind),
];
let names = rows.each_ref().map(|(kind, _)| <&str>::from(kind.clone()));
assert_eq!(carriers, names);
for (kind, lists) in rows {
assert!(lists(kind.clone() as u16), "no row lists {kind:?}");
}
}
}