use crate::Elixir;
use crate::node::{Ancestors, FoldLane, Node, WordSlot};
#[inline]
#[must_use]
pub fn elixir_call_keyword<'a>(node: &'a Node<'a>, code: &'a [u8]) -> Option<&'a str> {
if node.kind_id() != Elixir::Call as u16 {
return None;
}
call_keyword_reads::record();
let target = node.child_by_field_name("target")?;
if target.kind_id() != Elixir::Identifier as u16 {
return None;
}
target.utf8_text(code)
}
crate::observation::counter!(call_keyword_reads, cfg(any(test, feature = "test-support")));
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
#[non_exhaustive]
pub enum ElixirCallTarget {
Other = 0,
If,
Unless,
For,
While,
Case,
Cond,
With,
Try,
Receive,
Throw,
Raise,
Reraise,
Exit,
Def,
Defp,
Defmacro,
Defmacrop,
Defmodule,
Defprotocol,
Defimpl,
Defstruct,
Defguard,
Defguardp,
Quote,
Alias,
Import,
Require,
Use,
}
impl ElixirCallTarget {
pub const ALL: [Self; 29] = [
Self::Other,
Self::If,
Self::Unless,
Self::For,
Self::While,
Self::Case,
Self::Cond,
Self::With,
Self::Try,
Self::Receive,
Self::Throw,
Self::Raise,
Self::Reraise,
Self::Exit,
Self::Def,
Self::Defp,
Self::Defmacro,
Self::Defmacrop,
Self::Defmodule,
Self::Defprotocol,
Self::Defimpl,
Self::Defstruct,
Self::Defguard,
Self::Defguardp,
Self::Quote,
Self::Alias,
Self::Import,
Self::Require,
Self::Use,
];
#[must_use]
pub fn from_text(text: &str) -> Self {
match text {
"if" => Self::If,
"unless" => Self::Unless,
"for" => Self::For,
"while" => Self::While,
"case" => Self::Case,
"cond" => Self::Cond,
"with" => Self::With,
"try" => Self::Try,
"receive" => Self::Receive,
"throw" => Self::Throw,
"raise" => Self::Raise,
"reraise" => Self::Reraise,
"exit" => Self::Exit,
"def" => Self::Def,
"defp" => Self::Defp,
"defmacro" => Self::Defmacro,
"defmacrop" => Self::Defmacrop,
"defmodule" => Self::Defmodule,
"defprotocol" => Self::Defprotocol,
"defimpl" => Self::Defimpl,
"defstruct" => Self::Defstruct,
"defguard" => Self::Defguard,
"defguardp" => Self::Defguardp,
"quote" => Self::Quote,
"alias" => Self::Alias,
"import" => Self::Import,
"require" => Self::Require,
"use" => Self::Use,
_ => Self::Other,
}
}
#[inline]
#[must_use]
pub fn is_method_macro(self) -> bool {
matches!(
self,
Self::Def | Self::Defp | Self::Defmacro | Self::Defmacrop
)
}
#[inline]
#[must_use]
pub fn is_exit(self) -> bool {
matches!(self, Self::Throw | Self::Raise | Self::Reraise | Self::Exit)
}
fn from_slot(value: u8) -> Self {
Self::ALL
.get(usize::from(value))
.copied()
.unwrap_or(Self::Other)
}
}
#[must_use]
pub fn elixir_call_target_word(target: ElixirCallTarget) -> Option<&'static str> {
use ElixirCallTarget as T;
Some(match target {
T::Other => return None,
T::If => "if",
T::Unless => "unless",
T::For => "for",
T::While => "while",
T::Case => "case",
T::Cond => "cond",
T::With => "with",
T::Try => "try",
T::Receive => "receive",
T::Throw => "throw",
T::Raise => "raise",
T::Reraise => "reraise",
T::Exit => "exit",
T::Def => "def",
T::Defp => "defp",
T::Defmacro => "defmacro",
T::Defmacrop => "defmacrop",
T::Defmodule => "defmodule",
T::Defprotocol => "defprotocol",
T::Defimpl => "defimpl",
T::Defstruct => "defstruct",
T::Defguard => "defguard",
T::Defguardp => "defguardp",
T::Quote => "quote",
T::Alias => "alias",
T::Import => "import",
T::Require => "require",
T::Use => "use",
})
}
#[inline]
#[must_use]
pub fn elixir_call_target<'a>(
node: &Node<'a>,
code: &[u8],
ancestors: Ancestors<'a, '_>,
) -> ElixirCallTarget {
if node.kind_id() != Elixir::Call as u16 {
return ElixirCallTarget::Other;
}
ElixirCallTarget::from_slot(ancestors.classified(WordSlot::ElixirCallTarget, node, || {
elixir_call_keyword(node, code).map_or(ElixirCallTarget::Other, ElixirCallTarget::from_text)
as u8
}))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ElixirDeclaration {
Module,
Method,
}
#[must_use]
pub(crate) fn elixir_declaration<'a>(
node: &Node<'a>,
code: &[u8],
ancestors: Ancestors<'a, '_>,
) -> Option<ElixirDeclaration> {
match elixir_call_target(node, code, ancestors) {
ElixirCallTarget::Defmodule => Some(ElixirDeclaration::Module),
target
if target.is_method_macro() && !elixir_is_inside_quote_block(node, code, ancestors) =>
{
Some(ElixirDeclaration::Method)
}
_ => None,
}
}
#[inline]
#[must_use]
pub(crate) fn elixir_is_inside_quote_block<'a>(
node: &Node<'a>,
code: &[u8],
ancestors: Ancestors<'a, '_>,
) -> bool {
if ancestors.memoises_folds() {
return ancestors.fold_down(
node,
0,
FoldLane::InsideQuote,
0,
|inside, ancestor, _, _| {
u8::from(inside == 1 || elixir_call_keyword(ancestor, code) == Some("quote"))
},
) == 1;
}
ancestors
.iter(node)
.any(|(n, _)| elixir_call_keyword(&n, code) == Some("quote"))
}
#[must_use]
pub fn elixir_applying_operator<'a>(
op: &Node<'a>,
ancestors: Ancestors<'a, '_>,
) -> Option<Node<'a>> {
ancestors
.parent(op)
.filter(|parent| parent.kind() == "binary_operator")
}
#[must_use]
pub fn elixir_kernel_short_circuit_name<'a>(call: &Node<'a>, code: &[u8]) -> Option<Node<'a>> {
kernel_short_circuit_parts(call, code).map(|(name, _)| name)
}
fn kernel_short_circuit_parts<'a>(call: &Node<'a>, code: &[u8]) -> Option<(Node<'a>, Node<'a>)> {
if call.kind() != "call" {
return None;
}
let dot = call.child_by_field_name("target").filter(|target| {
target.kind() == "dot"
&& target.child_by_field_name("left").is_some_and(|receiver| {
matches!(
code.get(receiver.start_byte()..receiver.end_byte()),
Some(b"Kernel" | b"Elixir.Kernel")
)
})
})?;
let name = dot.child_by_field_name("right")?;
let name = if name.kind() == "operator_identifier" {
name.child(0)?
} else {
name
};
elixir_short_circuit_name(&name, code)
.and_then(|_| call.children().find(|child| child.kind() == "arguments"))
.map(|arguments| (name, arguments))
}
#[must_use]
pub fn elixir_short_circuit_kind(kind_id: u16) -> Option<Elixir> {
match kind_id.into() {
Elixir::AMPAMP | Elixir::And => Some(Elixir::AMPAMP),
Elixir::PIPEPIPE | Elixir::Or => Some(Elixir::PIPEPIPE),
_ => None,
}
}
#[must_use]
pub fn elixir_short_circuit_name(name: &Node, code: &[u8]) -> Option<Elixir> {
if name.kind_id() != Elixir::Identifier as u16 {
return elixir_short_circuit_kind(name.kind_id());
}
match code.get(name.start_byte()..name.end_byte())? {
b"and" => Some(Elixir::AMPAMP),
b"or" => Some(Elixir::PIPEPIPE),
_ => None,
}
}
pub struct ElixirRemoteCall<'tree, 'chain> {
pub call: Node<'tree>,
pub arguments: Node<'tree>,
pub ancestors: Ancestors<'tree, 'chain>,
}
#[must_use]
pub fn elixir_applying_remote_call<'a, 'c>(
op: &Node<'a>,
code: &[u8],
ancestors: Ancestors<'a, 'c>,
) -> Option<ElixirRemoteCall<'a, 'c>> {
let mut up = ancestors.iter(op);
let (mut dot, _) = up.next()?;
if dot.kind() == "operator_identifier" {
dot = up.next()?.0;
}
if dot.kind() != "dot" {
return None;
}
let (call, call_ancestors) = up.next()?;
kernel_short_circuit_parts(&call, code)
.filter(|(name, _)| name.id() == op.id())
.map(|(_, arguments)| ElixirRemoteCall {
call,
arguments,
ancestors: call_ancestors,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ElixirCode;
use crate::node::Tree;
use crate::test_support::for_each_node_with_chain;
#[cfg(feature = "elixir")]
#[test]
fn short_circuit_name_requires_the_identifiers_source_span() {
let source = b"Kernel.and(a, b)";
let tree = Tree::new::<ElixirCode>(source);
let name = tree
.get_root()
.preorder()
.find(|node| {
node.kind_id() == Elixir::Identifier as u16 && node.utf8_text(source) == Some("and")
})
.expect("fixture contains the operator name");
assert_eq!(
elixir_short_circuit_name(&name, source),
Some(Elixir::AMPAMP)
);
assert_eq!(
elixir_short_circuit_name(&name, &source[..name.end_byte() - 1]),
None
);
}
#[cfg(feature = "elixir")]
#[test]
fn remote_call_lookup_rejects_a_root_and_keeps_its_argument_list() {
let source = b"Kernel.and(a, b)\nKernel.||(c, d)\n";
let mut recognized = Vec::new();
for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
let known = elixir_applying_remote_call(node, source, Ancestors::known(chain));
let unknown = elixir_applying_remote_call(node, source, Ancestors::unknown());
assert_eq!(
known.as_ref().map(|r| (r.call.id(), r.arguments.id())),
unknown.map(|r| (r.call.id(), r.arguments.id()))
);
if chain.is_empty() {
assert!(known.is_none());
}
if let Some(remote) = known {
assert_eq!(remote.arguments.kind(), "arguments");
assert_eq!(
remote.ancestors.parent(&remote.call).map(|p| p.kind()),
Some("source")
);
recognized.push((
node.utf8_text(source)
.expect("operator is UTF-8")
.to_owned(),
remote
.arguments
.utf8_text(source)
.expect("arguments are UTF-8")
.to_owned(),
));
}
});
assert_eq!(
recognized,
[
("and".to_owned(), "(a, b)".to_owned()),
("||".to_owned(), "(c, d)".to_owned())
]
);
}
#[cfg(feature = "elixir")]
#[test]
fn inside_quote_fold_answers_as_the_climb_does() {
use crate::node::{FoldCache, Tree};
let source = b"defmodule M do\n def a, do: 1\n defmacro m do\n quote do\n def b, do: 2\n quote do\n def c, do: 3\n end\n if true do\n def d, do: 4\n end\n end\n def e, do: 5\n end\n if true do\n if true do\n def f, do: 6\n end\n end\nend\n";
let tree = Tree::new::<ElixirCode>(source);
assert!(!tree.get_root().has_error());
let cache = FoldCache::default();
let mut answers = Vec::new();
let mut stack = vec![(tree.get_root(), 0_usize)];
let mut chain: Vec<Node> = Vec::new();
while let Some((node, depth)) = stack.pop() {
chain.truncate(depth);
if let Some(kw) = elixir_call_keyword(&node, source) {
let folded = elixir_is_inside_quote_block(
&node,
source,
Ancestors::known(&chain).with_folds(&cache),
);
let climbed = elixir_is_inside_quote_block(&node, source, Ancestors::known(&chain));
assert_eq!(folded, climbed, "`{kw}` at depth {depth}");
if ElixirCallTarget::from_text(kw).is_method_macro() {
answers.push((kw.to_owned(), folded));
}
}
chain.push(node);
let children: Vec<_> = node.children().collect();
stack.extend(children.into_iter().rev().map(|child| (child, depth + 1)));
}
let defs: Vec<_> = answers.iter().map(|(_, inside)| *inside).collect();
assert_eq!(answers.len(), 7, "{answers:?}");
assert_eq!(
defs,
[false, false, true, true, true, false, false],
"{answers:?}"
);
}
#[cfg(feature = "elixir")]
#[test]
fn call_target_is_read_once_per_call_under_a_cache() {
use crate::node::FoldCache;
const ASKS: usize = 4;
let source = b"defmodule M do\n def f(a) do\n if a, do: throw(:x)\n unless a, do: raise(\"y\")\n case a do\n _ -> g()\n end\n Kernel.exit(1)\n end\nend\n";
let cache = FoldCache::default();
let mut calls = 0;
let mut enclosing_asks = 0;
let mut answers = std::collections::HashMap::new();
let mut cached = Vec::new();
let before = call_keyword_reads::observed();
for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
if node.kind_id() != Elixir::Call as u16 {
return;
}
calls += 1;
let walk = Ancestors::for_walk_without_siblings(chain, node, &cache);
let first = elixir_call_target(node, source, walk);
let enclosing = chain
.iter()
.rev()
.find(|ancestor| ancestor.kind_id() == Elixir::Call as u16);
for _ in 1..ASKS {
if let Some(enclosing) = enclosing {
enclosing_asks += 1;
let recorded = answers[&enclosing.id()];
assert_eq!(elixir_call_target(enclosing, source, walk), recorded);
}
assert_eq!(elixir_call_target(node, source, walk), first);
}
answers.insert(node.id(), first);
cached.push(first);
});
let cached_reads = call_keyword_reads::observed() - before;
let mut uncached = Vec::new();
let before = call_keyword_reads::observed();
for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
if node.kind_id() == Elixir::Call as u16 {
let chain = Ancestors::known(chain);
for _ in 0..ASKS {
uncached.push(elixir_call_target(node, source, chain));
}
}
});
let uncached_reads = call_keyword_reads::observed() - before;
assert_eq!(
cached,
[
ElixirCallTarget::Defmodule,
ElixirCallTarget::Def,
ElixirCallTarget::Other, ElixirCallTarget::If,
ElixirCallTarget::Throw,
ElixirCallTarget::Unless,
ElixirCallTarget::Raise,
ElixirCallTarget::Case,
ElixirCallTarget::Other, ElixirCallTarget::Other, ]
);
assert_eq!(calls, cached.len());
assert_eq!(
uncached,
cached
.iter()
.flat_map(|&t| std::iter::repeat_n(t, ASKS))
.collect::<Vec<_>>()
);
assert_eq!(enclosing_asks, (calls - 1) * (ASKS - 1));
assert_eq!(
(cached_reads, uncached_reads),
(calls + enclosing_asks, ASKS * calls),
"one read per visited call plus one per ask about its enclosing call"
);
}
#[cfg(feature = "elixir")]
#[test]
fn call_target_of_a_non_call_is_other_without_a_read() {
let source = b"defmodule M do\n def f(a), do: a + 1\nend\n";
let before = call_keyword_reads::observed();
let mut seen = Vec::new();
for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
if node.kind_id() != Elixir::Call as u16 {
seen.push((
node.kind(),
elixir_call_keyword(node, source).is_some(),
call_keyword_reads::observed() - before,
elixir_call_target(node, source, Ancestors::known(chain)),
));
}
});
assert!(
seen.len() > 5,
"the fixture has non-call nodes to ask about"
);
let read = seen
.iter()
.filter(|&&(_, keyword, reads, target)| {
keyword || reads != 0 || target != ElixirCallTarget::Other
})
.map(|&(kind, ..)| kind)
.collect::<Vec<_>>();
assert_eq!(
read,
Vec::<&str>::new(),
"a non-call was read or classified"
);
assert_eq!(call_keyword_reads::observed(), before);
}
#[test]
fn call_target_round_trips_through_the_slot() {
for target in ElixirCallTarget::ALL {
assert_eq!(ElixirCallTarget::from_slot(target as u8), target);
}
assert_eq!(
ElixirCallTarget::from_slot(u8::try_from(ElixirCallTarget::ALL.len()).expect("fits")),
ElixirCallTarget::Other
);
for (index, target) in ElixirCallTarget::ALL.iter().enumerate() {
assert_eq!(*target as usize, index, "`ALL` is in discriminant order");
}
}
#[test]
fn word_round_trips_through_from_text() {
for target in ElixirCallTarget::ALL {
match elixir_call_target_word(target) {
Some(word) => assert_eq!(ElixirCallTarget::from_text(word), target, "{word}"),
None => assert_eq!(target, ElixirCallTarget::Other),
}
}
assert_eq!(ElixirCallTarget::from_text("foo"), ElixirCallTarget::Other);
}
}