use crate::lang_helpers::elixir::{
ElixirCallTarget, ElixirDeclaration, elixir_applying_operator, elixir_call_target,
elixir_declaration,
};
use crate::lang_helpers::elixir_decisions::{
elixir_clause_is_decision, elixir_is_when_operator, elixir_when_is_guard,
};
use crate::role_table;
use crate::{Ancestors, Elixir, Node};
fn applied<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
elixir_applying_operator(node, ancestors).is_some()
}
fn method_macro<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
elixir_declaration(node, code, ancestors) == Some(ElixirDeclaration::Method)
}
fn class_macro<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
elixir_declaration(node, code, ancestors) == Some(ElixirDeclaration::Module)
}
fn struct_macro<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
elixir_call_target(node, code, ancestors) == ElixirCallTarget::Defstruct
}
fn control_branch<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
matches!(
elixir_call_target(node, code, ancestors),
ElixirCallTarget::If | ElixirCallTarget::Unless
)
}
fn control_switch<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
matches!(
elixir_call_target(node, code, ancestors),
ElixirCallTarget::Case
| ElixirCallTarget::Cond
| ElixirCallTarget::With
| ElixirCallTarget::Try
| ElixirCallTarget::Receive
)
}
fn control_loop<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
matches!(
elixir_call_target(node, code, ancestors),
ElixirCallTarget::For | ElixirCallTarget::While
)
}
fn control_exit<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
elixir_call_target(node, code, ancestors).is_exit()
}
fn is_decision_clause<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
elixir_clause_is_decision(node, code, ancestors)
}
fn is_when_operator(node: &Node<'_>) -> bool {
elixir_is_when_operator(node)
}
fn is_guard<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
elixir_when_is_guard(node, code, ancestors)
}
role_table! {
lang: Elixir;
FuncOpener {
owns [
Call(text_gated_by method_macro callable opens Function),
AnonymousFunction(opens Function),
]
}
Container {
owns [
Source(opens Unit),
Call(text_gated_by class_macro opens Class),
]
}
Closure { owns [AnonymousFunction] }
Call { owns [Call] }
StringLit {
owns [String, Charlist, Sigil, QuotedAtom, QuotedKeyword]
wraps [Interpolation]
excludes [
Atom "a single token with no quoted body; the getter bills it as an operand on its own",
Keyword "a single token with no quoted body; the getter bills it as an operand on its own",
Atom2 "the hidden `_atom` choice over `atom` and `quoted_atom`, which reaches no node",
Keyword2 "the hidden `_keyword` choice over `keyword` and `quoted_keyword`, which reaches no node",
]
}
NullSafe { absent "Elixir has no `?.` or `??`" }
ElseIf { absent "Elixir has no `else if`; multi-way branching is `cond`" }
Modifier { absent "Elixir's `defp` is a declaration keyword, not a modifier" }
Primitive { absent "Elixir has no built-in type names in syntax" }
DocComment { absent "Elixir documents with `@doc` attributes, not comments" }
Comparison {
owns [
BinaryOperator(holds_payer),
BinaryOperator2(holds_payer),
BinaryOperator3(holds_payer),
]
pays [
EQEQ gated_by applied, EQEQEQ gated_by applied,
BANGEQ gated_by applied, BANGEQEQ gated_by applied,
LTEQ gated_by applied, GTEQ gated_by applied,
LT gated_by applied, GT gated_by applied,
In gated_by applied, Notin gated_by applied,
]
project "operator"
}
ShortCircuit {
owns [
BinaryOperator(holds_payer),
BinaryOperator2(holds_payer),
BinaryOperator3(holds_payer),
]
pays [
AMPAMP gated_by applied, PIPEPIPE gated_by applied,
And gated_by applied, Or gated_by applied,
]
project "operator"
}
EagerLogical { absent "Elixir's `and` / `or` and `&&` / `||` all short-circuit; `&&&` / `|||` are \
bitwise" }
Ternary { absent "Elixir has no ternary operator" }
CaseArm { owns [StabClause(text_gated_by is_decision_clause)] }
Guard {
owns [
BinaryOperator(gated_by is_when_operator no_chain),
BinaryOperator2(gated_by is_when_operator no_chain),
BinaryOperator3(gated_by is_when_operator no_chain),
]
pays [When text_gated_by is_guard]
project "operator"
}
Branch { owns [Call(text_gated_by control_branch)] }
Switch { owns [Call(text_gated_by control_switch)] }
Loop { owns [Call(text_gated_by control_loop)] }
Catch { owns [RescueBlock, CatchBlock] }
Exit { owns [Call(text_gated_by control_exit)] }
DeclKeyword { owns [Fn] }
Member { owns [Call(text_gated_by struct_macro)] }
Comment { owns [Comment] }
Docstring { absent "extraction owned by #1676" }
DocTarget { absent "a `@doc` attribute names its target by position; extraction owned by #1676" }
DocRunOpener { absent "ExDoc reads `@doc` attributes, never a comment run" }
DocRunDirective { absent "ExDoc reads `@doc` attributes, never a comment run" }
DocBodyResidual { absent "no kind holds documentation in a body beyond the definition" }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::for_each_node_with_chain;
use crate::{Checker, ElixirCode, Getter, SpaceKind};
#[cfg(feature = "elixir")]
#[test]
fn classifiers_read_the_rows_and_the_rows_say_what_the_walk_did() {
let source = b"defmodule M do\n defstruct [:a]\n def f(x), do: fn y -> y end\n defp g, do: ~s(a)\n defmacro m do\n quote do\n def h, do: 'c'\n end\n end\n IO.puts(\"a #{b}\")\n x = [:\"q a\", \"k b\": 1]\nend\n";
let mut calls = Vec::new();
let mut seen_kinds = std::collections::BTreeSet::new();
for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
let ancestors = Ancestors::known(chain);
let kind = node.kind();
let promoted = ElixirCode::promotes_to_func_space_with_code(node, source, ancestors);
let got = (
ElixirCode::is_func_with_code(node, source, ancestors),
ElixirCode::is_closure(node, ancestors),
promoted,
ElixirCode::get_space_kind_with_code(node, source, ancestors),
member::owns(node, source, ancestors),
);
seen_kinds.insert(node.kind_id());
assert_eq!(
got.3 != SpaceKind::Unknown,
promoted,
"{kind}: opens_space vs promotion"
);
assert_eq!(
ElixirCode::is_func_space_with_code(node, source, ancestors),
promoted,
"{kind}: is_func_space is what the walk promotes"
);
if node.kind_id() == Elixir::Call as u16 {
let target = node
.child_by_field_name("target")
.and_then(|t| t.utf8_text(source))
.unwrap_or("<none>")
.to_owned();
assert!(
call::owns(node, source, ancestors),
"{target}: a `call` is a Call"
);
calls.push((target, got));
return;
}
let want = match kind {
"source" => (false, false, true, SpaceKind::Unit, false),
"anonymous_function" => (false, true, true, SpaceKind::Function, false),
_ => (false, false, false, SpaceKind::Unknown, false),
};
assert_eq!(got, want, "{kind}");
assert!(
!call::owns(node, source, ancestors),
"{kind}: only a `call` is a Call"
);
assert_eq!(
string_lit::owns(node, source, ancestors),
matches!(
kind,
"string" | "charlist" | "sigil" | "quoted_atom" | "quoted_keyword"
),
"{kind}: StringLit"
);
});
let f = (true, false, true, SpaceKind::Function, false);
let none = (false, false, false, SpaceKind::Unknown, false);
assert_eq!(
calls,
[
(
"defmodule".to_owned(),
(false, false, true, SpaceKind::Class, false)
),
(
"defstruct".to_owned(),
(false, false, false, SpaceKind::Unknown, true)
),
("def".to_owned(), f),
("f".to_owned(), none),
("defp".to_owned(), f),
("defmacro".to_owned(), f),
("quote".to_owned(), none),
("def".to_owned(), none),
("IO.puts".to_owned(), none),
]
);
for kinds in [
call::OWNERS,
string_lit::OWNERS,
closure::OWNERS,
func_opener::OWNERS,
container::OWNERS,
member::OWNERS,
] {
for &k in kinds {
assert!(seen_kinds.contains(&k), "fixture never emits kind {k}");
}
}
}
#[cfg(feature = "elixir")]
#[test]
fn promotion_reads_each_calls_keyword_once() {
use crate::lang_helpers::elixir::call_keyword_reads;
let source = b"defmodule M do\n def f(x), do: g(x)\n defp g(x), do: IO.puts(x)\nend\n";
let (mut calls, mut defs) = (0, 0);
let before = call_keyword_reads::observed();
for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
if node.kind_id() == Elixir::Call as u16 {
calls += 1;
if node
.child_by_field_name("target")
.and_then(|t| t.utf8_text(source))
.is_some_and(|t| t.starts_with("def") && t != "defmodule")
{
defs += 1;
}
}
let _promoted =
ElixirCode::promotes_to_func_space_with_code(node, source, Ancestors::known(chain));
});
assert_eq!((calls, defs), (7, 2));
assert_eq!(call_keyword_reads::observed() - before, calls + defs);
}
#[cfg(feature = "elixir")]
#[test]
fn text_gated_rows_read_the_target_bytes_and_the_chain() {
let source = b"defmodule M do\n def f(x), do: x\n defmacro m do\n quote do\n def g, do: 1\n end\n end\n IO.puts(1)\nend\n";
let mut calls = Vec::new();
for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
if node.kind_id() != Elixir::Call as u16 {
return;
}
let ancestors = Ancestors::known(chain);
let target = node
.child_by_field_name("target")
.and_then(|t| t.utf8_text(source))
.unwrap_or("<none>")
.to_owned();
calls.push((
target,
func_opener::owns(node, source, ancestors),
container::owns(node, source, ancestors),
opens_space(node, source, ancestors),
));
});
assert_eq!(
calls,
[
("defmodule".to_owned(), false, true, SpaceKind::Class),
("def".to_owned(), true, false, SpaceKind::Function),
("f".to_owned(), false, false, SpaceKind::Unknown),
("defmacro".to_owned(), true, false, SpaceKind::Function),
("quote".to_owned(), false, false, SpaceKind::Unknown),
("def".to_owned(), false, false, SpaceKind::Unknown),
("IO.puts".to_owned(), false, false, SpaceKind::Unknown),
]
);
}
#[cfg(feature = "elixir")]
#[test]
fn the_quote_gate_depends_on_the_ancestor_chain() {
let source = b"def g, do: 1\n";
let mut defs = 0;
for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
if node.kind_id() == Elixir::Call as u16 {
assert!(func_opener::owns(node, source, Ancestors::known(chain)));
defs += 1;
}
});
assert_eq!(defs, 1);
}
#[cfg(feature = "elixir")]
#[test]
fn closure_and_opener_are_two_declarations() {
let source = b"def f, do: fn x -> x end\n";
let mut seen = Vec::new();
for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
let ancestors = Ancestors::known(chain);
let closure = closure::owns(node, source, ancestors);
let space = opens_space(node, source, ancestors);
if closure || space != SpaceKind::Unknown {
seen.push((node.kind(), closure, space));
}
});
assert_eq!(
seen,
[
("source", false, SpaceKind::Unit),
("call", false, SpaceKind::Function),
("anonymous_function", true, SpaceKind::Function),
]
);
assert_eq!(
func_opener::OWNERS,
&[Elixir::Call as u16, Elixir::AnonymousFunction as u16]
);
assert_eq!(
container::OWNERS,
&[Elixir::Source as u16, Elixir::Call as u16]
);
}
#[cfg(feature = "elixir")]
#[test]
fn guard_operators_own_and_their_tokens_pay_in_guard_position_only() {
let source = b"defmodule M do\n @spec f(a) :: a when a: var\n def f(x) when is_integer(x), do: x\n def g(x) do\n case x do\n y when y > 0 -> 1\n _ -> 0\n end\n end\nend\n";
let (mut owned, mut paid, mut tokens) = (Vec::new(), Vec::new(), Vec::new());
for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
let ancestors = Ancestors::known(chain);
let text = || node.utf8_text(source).expect("fixture is UTF-8").to_owned();
if guard::owns(node, source, ancestors) {
owned.push(text());
}
if node.kind_id() == Elixir::When as u16 {
tokens.push(node.start_byte());
}
if guard::pays_at_leaf(node, source, ancestors) {
paid.push(node.start_byte());
let (operator, above) = chain.split_last().expect("a `when` has a parent");
assert!(
guard::owns(operator, source, Ancestors::known(above)),
"{}",
text()
);
}
});
assert_eq!(
owned,
[
"f(a) :: a when a: var",
"f(x) when is_integer(x)",
"y when y > 0"
]
);
assert_eq!(tokens.len(), 3);
assert_eq!(paid, tokens[1..]);
}
#[cfg(feature = "elixir")]
#[test]
fn escape_sequence_parents_are_the_literals() {
let node_types: serde_json::Value = serde_json::from_str(tree_sitter_elixir::NODE_TYPES)
.expect("the grammar crate ships valid node-types.json");
let types = node_types.as_array().into_iter().flatten();
let mut names: std::collections::BTreeSet<&str> = ["escape_sequence"].into();
for t in types.clone() {
let subtypes = t["subtypes"].as_array().into_iter().flatten();
if subtypes.clone().any(|s| s["type"] == "escape_sequence")
&& let Some(name) = t["type"].as_str()
{
names.insert(name);
}
}
let parents: std::collections::BTreeSet<&str> = types
.filter(|t| {
let children = t["children"]["types"].as_array().into_iter().flatten();
let fields = t["fields"]
.as_object()
.into_iter()
.flatten()
.flat_map(|(_, f)| f["types"].as_array().into_iter().flatten());
children
.chain(fields)
.any(|c| c["type"].as_str().is_some_and(|n| names.contains(n)))
})
.filter_map(|t| t["type"].as_str())
.collect();
assert_eq!(
parents,
[
"charlist",
"quoted_atom",
"quoted_keyword",
"sigil",
"string"
]
.into_iter()
.collect()
);
}
}