use crate::lang_helpers::elixir::{ElixirCallTarget, elixir_call_keyword, elixir_call_target};
use crate::node::MemoQuestion;
use crate::{Ancestors, Elixir, Node};
crate::observation::counter!(guard_position_checks, cfg(test));
crate::observation::counter!(section_position_scans, cfg(test));
fn is_operand(child: &Node) -> bool {
child.is_named() && !child.is_extra()
}
fn elixir_is_binary_operator(node: &Node, operator: Elixir) -> bool {
const BINARY_OPERATOR: &str = "binary_operator";
node.kind() == BINARY_OPERATOR
&& node
.child_by_field_name("operator")
.is_some_and(|token| token.kind_id() == operator as u16)
}
#[must_use]
pub(crate) fn elixir_is_when_operator(node: &Node) -> bool {
elixir_is_binary_operator(node, Elixir::When)
}
fn elixir_is_with_argument<'a>(mut up: impl Iterator<Item = Node<'a>>, code: &'a [u8]) -> bool {
up.next()
.is_some_and(|arguments| arguments.kind() == "arguments")
&& up
.next()
.is_some_and(|call| elixir_call_keyword(&call, code) == Some("with"))
}
#[must_use]
pub fn elixir_arrow_is_with_clause<'a>(
node: &Node<'a>,
code: &'a [u8],
ancestors: Ancestors<'a, '_>,
) -> bool {
elixir_is_with_argument(ancestors.iter(node).skip(1).map(|(a, _)| a), code)
}
#[must_use]
pub fn elixir_when_alternative<'a>(when_operator: &Node<'a>) -> Option<Node<'a>> {
let right = when_operator.child_by_field_name("right")?;
if elixir_is_when_operator(&right) {
right.child_by_field_name("left")
} else {
Some(right)
}
}
#[must_use]
pub(crate) fn elixir_when_is_guard<'a>(
node: &Node<'a>,
code: &'a [u8],
ancestors: Ancestors<'a, '_>,
) -> bool {
let mut chain = ancestors.iter(node);
let Some((operator, _)) = chain.next() else {
return false;
};
ancestors.memoised(MemoQuestion::GuardOperator, &operator, || {
let memo = ancestors.node_memo(MemoQuestion::GuardOperator);
let mut operator = operator;
let mut above = chain.next();
let mut passed = Vec::new();
let answer = loop {
let Some((enclosing, _)) = above.filter(|(up, _)| elixir_is_when_operator(up)) else {
guard_position_checks::record();
break above.is_some_and(|(parent, _)| {
elixir_is_guard_position(&operator, &parent, chain.map(|(up, _)| up), code)
});
};
if let Some(known) = memo.and_then(|memo| memo.get(&enclosing)) {
break known;
}
passed.push(enclosing);
operator = enclosing;
above = chain.next();
};
if let Some(memo) = memo {
for operator in passed {
memo.set(&operator, answer);
}
}
answer
})
}
fn elixir_is_guard_position<'a>(
operator: &Node<'a>,
parent: &Node<'a>,
mut up: impl Iterator<Item = Node<'a>>,
code: &'a [u8],
) -> bool {
use Elixir as E;
if parent.kind_id() == E::StabClause as u16 {
return parent
.child_by_field_name("left")
.is_some_and(|left| left.id() == operator.id());
}
if elixir_is_binary_operator(parent, E::LTDASH) {
return elixir_is_with_argument(up, code);
}
parent.kind() == ARGUMENTS
&& up.next().is_some_and(|call| {
elixir_call_keyword(&call, code).is_some_and(|keyword| {
let target = ElixirCallTarget::from_text(keyword);
target.is_method_macro()
|| matches!(
target,
ElixirCallTarget::Defguard | ElixirCallTarget::Defguardp
)
})
})
}
#[must_use]
pub fn elixir_sole_unguarded_pattern<'a>(node: &Node<'a>) -> Option<Node<'a>> {
let left = node
.child_by_field_name("left")
.filter(|left| left.kind() == "arguments")?;
let mut patterns = left.children().filter(Node::is_named);
let sole = patterns.next()?;
patterns.next().is_none().then_some(sole)
}
fn elixir_is_bare_wildcard(pattern: &Node, code: &[u8]) -> bool {
pattern.kind_id() == Elixir::Identifier as u16 && pattern.utf8_text(code) == Some("_")
}
fn elixir_is_default_clause<'a>(
node: &Node<'a>,
code: &'a [u8],
ancestors: Ancestors<'a, '_>,
skips_head: bool,
) -> bool {
use Elixir as E;
let Some(pattern) = elixir_sole_unguarded_pattern(node) else {
return false;
};
match pattern.kind_id().into() {
E::Identifier => !skips_head && elixir_is_bare_wildcard(&pattern, code),
E::Boolean => {
pattern.utf8_text(code) == Some("true")
&& elixir_do_section_call(node, code, ancestors).is_some_and(|call| {
elixir_call_target(&call, code, ancestors) == ElixirCallTarget::Cond
})
}
_ => false,
}
}
fn elixir_clauses_skip_head<'a>(
node: &Node<'a>,
code: &'a [u8],
ancestors: Ancestors<'a, '_>,
) -> bool {
ancestors.parent_has_kind(node, Elixir::AnonymousFunction as u16)
|| elixir_do_section_call(node, code, ancestors)
.is_some_and(|call| elixir_call_target(&call, code, ancestors) == ElixirCallTarget::For)
}
fn elixir_is_first_clause<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
ancestors
.parent(node)
.and_then(|parent| {
parent
.children()
.find(|child| child.kind_id() == Elixir::StabClause as u16)
})
.is_some_and(|first| first.id() == node.id())
}
#[must_use]
pub(crate) fn elixir_clause_is_decision<'a>(
node: &Node<'a>,
code: &'a [u8],
ancestors: Ancestors<'a, '_>,
) -> bool {
use Elixir as E;
let mut up = ancestors.iter(node).map(|(ancestor, _)| ancestor);
let in_section = up.next().is_some_and(|parent| {
matches!(
parent.kind_id().into(),
E::DoBlock | E::ElseBlock | E::RescueBlock | E::CatchBlock | E::AnonymousFunction
) || (parent.kind_id() == E::Block as u16
&& up.next().is_some_and(|pair| {
elixir_pair_key(&pair, code).is_some_and(|key| DECISION_SECTION_KEYS.contains(&key))
}))
});
if !in_section {
return false;
}
let skips_head = elixir_clauses_skip_head(node, code, ancestors);
if skips_head && elixir_is_first_clause(node, ancestors) {
return false;
}
!elixir_is_default_clause(node, code, ancestors, skips_head)
}
#[must_use]
pub fn elixir_with_else_dispatches(call: &Node, code: &[u8]) -> bool {
elixir_section_has_clause(call, code, Section::Else, |clause| {
!elixir_is_catch_all(clause, code)
})
}
fn elixir_is_catch_all(clause: &Node, code: &[u8]) -> bool {
elixir_sole_unguarded_pattern(clause)
.is_some_and(|pattern| elixir_is_bare_wildcard(&pattern, code))
}
#[must_use]
pub fn elixir_receive_timeout_clause<'a>(receive: &Node<'a>, code: &'a [u8]) -> Option<Node<'a>> {
let timeout = receive.children().find_map(|child| {
elixir_section_holder(&child, code, Section::After)?
.children()
.find(|clause| clause.kind_id() == Elixir::StabClause as u16)
})?;
elixir_section_has_clause(receive, code, Section::Do, |clause| {
elixir_is_catch_all(clause, code)
})
.then_some(timeout)
}
#[must_use]
pub fn elixir_receive_dispatches(call: &Node, code: &[u8]) -> bool {
elixir_section_has_clause(call, code, Section::Do, |_| true)
}
#[derive(Clone, Copy)]
pub enum Section {
Do,
Else,
After,
}
impl Section {
const fn key(self) -> &'static str {
match self {
Self::Do => "do",
Self::Else => "else",
Self::After => "after",
}
}
}
fn elixir_section_has_clause(
call: &Node,
code: &[u8],
section: Section,
accept: impl Fn(&Node) -> bool,
) -> bool {
call.children().any(|child| {
elixir_section_holder(&child, code, section).is_some_and(|holder| {
holder
.children()
.any(|clause| clause.kind_id() == Elixir::StabClause as u16 && accept(&clause))
})
})
}
#[must_use]
pub fn elixir_call_has_section(call: &Node, code: &[u8], section: Section) -> bool {
call.children()
.any(|child| elixir_section_holder(&child, code, section).is_some())
}
fn elixir_section_holder<'a>(
child: &Node<'a>,
code: &'a [u8],
section: Section,
) -> Option<Node<'a>> {
use Elixir as E;
match (child.kind_id().into(), section) {
(E::DoBlock, Section::Do) => Some(*child),
(E::DoBlock, Section::Else) => child
.children()
.find(|c| c.kind_id() == E::ElseBlock as u16),
(E::DoBlock, Section::After) => child
.children()
.find(|c| c.kind_id() == E::AfterBlock as u16),
_ if child.kind() == ARGUMENTS => elixir_keyword_section(child, code, section.key()),
_ => None,
}
}
const DECISION_SECTION_KEYS: &[&str] = &["do", "else", "rescue", "catch"];
fn elixir_pair_key<'a>(pair: &Node<'a>, code: &'a [u8]) -> Option<&'a str> {
if pair.kind_id() != Elixir::Pair as u16 {
return None;
}
let key = pair.child_by_field_name("key")?;
let mut parts = key.children().filter(Node::is_named);
match (parts.next(), parts.next()) {
(None, _) => key
.utf8_text(code)
.and_then(|text| text.trim_end().strip_suffix(':')),
(Some(content), None) if content.kind() == "quoted_content" => content.utf8_text(code),
_ => None,
}
}
fn elixir_trailing_keywords<'a>(arguments: &Node<'a>) -> Option<Node<'a>> {
let last = arguments.children().filter(is_operand).last()?;
if last.kind() == KEYWORDS {
return Some(last);
}
if last.kind_id() != Elixir::List as u16 {
return None;
}
last.children()
.find(is_operand)
.filter(|keywords| keywords.kind() == KEYWORDS)
}
fn elixir_keyword_section<'a>(arguments: &Node<'a>, code: &'a [u8], key: &str) -> Option<Node<'a>> {
elixir_trailing_keywords(arguments)?
.children()
.find(|pair| elixir_pair_key(pair, code) == Some(key))?
.child_by_field_name("value")
}
#[derive(Clone, Copy, Debug)]
pub struct ElixirPairSection<'a> {
pub key: &'a str,
pub call: Node<'a>,
keywords: Node<'a>,
}
impl<'a> ElixirPairSection<'a> {
#[must_use]
pub fn rides_do(&self, code: &'a [u8], ancestors: Ancestors<'a, '_>) -> bool {
elixir_keywords_hold_do(&self.keywords, code, ancestors)
}
}
#[must_use]
pub fn elixir_pair_section<'a>(
pair: &Node<'a>,
code: &'a [u8],
ancestors: Ancestors<'a, '_>,
) -> Option<ElixirPairSection<'a>> {
let mut up = ancestors.iter(pair);
let (keywords, keywords_ancestors) = up.next().filter(|(node, _)| node.kind() == KEYWORDS)?;
let (bracketed, (argument, argument_ancestors)) = match up.next()? {
(list, list_ancestors) if list.kind_id() == Elixir::List as u16 => {
(true, (list, list_ancestors))
}
_ => (false, (keywords, keywords_ancestors)),
};
let mut above = argument_ancestors.iter(&argument);
let (arguments, _) = above.next()?;
let (call, _) = above.next()?;
let is_section = arguments.kind() == ARGUMENTS
&& call.kind_id() == Elixir::Call as u16
&& elixir_argument_is_trailing(&argument, argument_ancestors)
&& (!bracketed || elixir_keywords_lead_their_list(&keywords, keywords_ancestors));
let key = is_section.then(|| elixir_pair_key(pair, code)).flatten()?;
Some(ElixirPairSection {
key,
call,
keywords,
})
}
fn elixir_argument_is_trailing<'a>(argument: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
ancestors.memoised(MemoQuestion::ArgumentIsTrailing, argument, || {
section_position_scans::record();
ancestors
.siblings_after(argument)
.all(|sibling| !is_operand(&sibling))
})
}
fn elixir_keywords_lead_their_list<'a>(keywords: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
ancestors.memoised(MemoQuestion::KeywordsLeadTheirList, keywords, || {
section_position_scans::record();
ancestors
.siblings_before(keywords)
.all(|sibling| !is_operand(&sibling))
})
}
fn elixir_keywords_hold_do<'a>(
keywords: &Node<'a>,
code: &'a [u8],
ancestors: Ancestors<'a, '_>,
) -> bool {
ancestors.memoised(MemoQuestion::KeywordListHasDo, keywords, || {
section_position_scans::record();
keywords
.children()
.any(|sibling| elixir_pair_key(&sibling, code) == Some("do"))
})
}
const KEYWORDS: &str = "keywords";
const ARGUMENTS: &str = "arguments";
fn elixir_do_section_call<'a>(
node: &Node<'a>,
code: &'a [u8],
ancestors: Ancestors<'a, '_>,
) -> Option<Node<'a>> {
use Elixir as E;
let mut up = ancestors.iter(node);
let (holder, _) = up.next()?;
let (next, next_ancestors) = up.next()?;
match holder.kind_id().into() {
E::DoBlock => Some(next),
E::Block => elixir_pair_section(&next, code, next_ancestors)
.filter(|section| section.key == "do")
.map(|section| section.call),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ElixirCode;
use crate::test_support::for_each_node_with_chain;
#[cfg(feature = "elixir")]
#[test]
fn a_repeated_guard_chain_is_climbed_once_whichever_token_asks_first() {
use crate::node::FoldCache;
let depth = 32;
let guards = (0..depth).fold(String::new(), |mut s, i| {
use std::fmt::Write as _;
let _ = write!(s, " when is_integer(x{i})");
s
});
let source = format!("def f(x){guards}, do: x\n");
let source = source.as_bytes();
let tree = crate::node::Tree::new::<ElixirCode>(source);
let root = tree.get_root();
assert!(!root.has_error());
let mut tokens = Vec::new();
let mut stack = vec![(root, Vec::new())];
while let Some((node, chain)) = stack.pop() {
if node.kind_id() == Elixir::When as u16 {
tokens.push((node, chain.clone()));
}
let mut below = chain;
below.push(node);
stack.extend(node.children().map(|child| (child, below.clone())));
}
assert_eq!(tokens.len(), depth);
tokens.sort_by_key(|(token, _)| std::cmp::Reverse(token.start_byte()));
let cache = FoldCache::default();
let before = guard_position_checks::observed();
let cached: Vec<bool> = tokens
.iter()
.map(|(token, chain)| {
elixir_when_is_guard(token, source, Ancestors::known(chain).with_folds(&cache))
})
.collect();
assert_eq!(
guard_position_checks::observed() - before,
1,
"a walk lending a FoldCache checks the chain's position once"
);
let before = guard_position_checks::observed();
let uncached: Vec<bool> = tokens
.iter()
.map(|(token, chain)| elixir_when_is_guard(token, source, Ancestors::known(chain)))
.collect();
assert_eq!(guard_position_checks::observed() - before, depth);
assert_eq!(cached, uncached);
assert!(
cached.iter().all(|&guard| guard),
"every `when` of the chain is a guard"
);
}
#[cfg(feature = "elixir")]
#[test]
fn empty_call_arguments_have_no_trailing_keywords() {
let source = b"f()\ng(else: 1)\n";
let mut found = Vec::new();
for_each_node_with_chain::<ElixirCode>(source, |node, _| {
if node.kind() == ARGUMENTS {
found.push(elixir_trailing_keywords(node).map(|keywords| {
keywords
.utf8_text(source)
.expect("keywords are UTF-8")
.to_owned()
}));
}
});
assert_eq!(found, [None, Some("else: 1".to_owned())]);
}
#[cfg(feature = "elixir")]
#[test]
fn section_position_scans_run_once_per_list_under_a_cache() {
use crate::node::FoldCache;
let source = b"foo([do: 0, else: 1, else: 2, else: 3])\nbar(do: 0, else: 1, else: 2)\n";
let cache = FoldCache::default();
let before = section_position_scans::observed();
let mut cached = Vec::new();
for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
if node.kind_id() == Elixir::Pair as u16 {
let ancestors = Ancestors::known(chain).with_folds(&cache);
let section = elixir_pair_section(node, source, ancestors).expect("a section pair");
cached.push((section.key.to_owned(), section.rides_do(source, ancestors)));
}
});
let cached_scans = section_position_scans::observed() - before;
let before = section_position_scans::observed();
let mut uncached = Vec::new();
for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
if node.kind_id() == Elixir::Pair as u16 {
let ancestors = Ancestors::known(chain);
let section = elixir_pair_section(node, source, ancestors).expect("a section pair");
uncached.push((section.key.to_owned(), section.rides_do(source, ancestors)));
}
});
let uncached_scans = section_position_scans::observed() - before;
assert_eq!(cached.len(), 7);
assert_eq!(cached, uncached);
assert!(cached.iter().all(|(_, rides)| *rides));
assert_eq!((cached_scans, uncached_scans), (5, 18));
}
#[cfg(feature = "elixir")]
#[test]
fn standalone_keyword_list_has_no_owning_call() {
let source = b"[else: 1]\nf(else: 2)\n";
let mut found = Vec::new();
for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
if node.kind_id() == Elixir::Pair as u16 {
found.push(
elixir_pair_section(node, source, Ancestors::known(chain)).map(|section| {
(
section.key.to_owned(),
section
.call
.utf8_text(source)
.expect("call is UTF-8")
.to_owned(),
)
}),
);
}
});
assert_eq!(
found,
[None, Some(("else".to_owned(), "f(else: 2)".to_owned()))]
);
}
}