Skip to main content

big_code_analysis_ast/getter/
elixir.rs

1//! `Getter` implementation for Elixir.
2#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
3
4use super::*;
5
6// Extracts the human-readable head name from the first non-`target`
7// child of an Elixir `def` / `defp` / `defmacro` / `defmacrop` /
8// `defmodule` Call. Handles three shapes:
9//   - `Arguments` wrapper: descend one level and recurse.
10//   - `Identifier` / `Alias` leaf: return its source text.
11//   - inner `Call` (e.g. `def foo(x, y)`): return the target identifier
12//     text of that inner Call.
13// Returns `None` when the child does not match any of these shapes,
14// allowing the caller to keep scanning siblings (notably the
15// `do_block`, which is unconditionally present and never carries the
16// name).
17fn elixir_extract_head_name<'a>(node: &Node, code: &'a [u8]) -> Option<&'a str> {
18    use Elixir as E;
19
20    let text = |n: &Node| node_text(code, n);
21    match node.kind_id().into() {
22        E::Identifier | E::Alias => text(node),
23        // role-bypass: allow(FuncOpener, Container, Call) — naming, not membership: where a head's
24        // text sits
25        E::Call => text(&node.child_by_field_name("target")?),
26        E::Arguments
27        | E::Arguments2
28        | E::Arguments3
29        | E::Arguments4
30        | E::Arguments5
31        | E::CallArgumentsWithTrailingSeparator => node
32            .children()
33            .find_map(|child| elixir_extract_head_name(&child, code)),
34        _ => None,
35    }
36}
37
38impl Getter for ElixirCode {
39    // The byte-less spelling is the kind table alone: an anonymous
40    // function and the file root. `defmodule` / `def` / `defp` /
41    // `defmacro` / `defmacrop` are `call`s told apart by their target
42    // text, so only the `_with_code` spelling — the `opens` annotations
43    // of `roles/elixir.rs` (#275, #310, #1696) — labels those. Each arm
44    // is the ungated subset of its row's owners, the one a byte-less
45    // spelling can answer; the derived forward parity test pins both
46    // against the rows on every corpus node.
47    fn get_space_kind(node: &Node) -> SpaceKind {
48        use Elixir as E;
49
50        match node.kind_id().into() {
51            // role-bypass: allow(FuncOpener, Closure) — the `FuncOpener` owner with no gate
52            E::AnonymousFunction => SpaceKind::Function,
53            // role-bypass: allow(Container) — the `Container` owner with no gate
54            E::Source => SpaceKind::Unit,
55            _ => SpaceKind::Unknown,
56        }
57    }
58
59    fn get_space_kind_with_code<'a>(
60        node: &Node<'a>,
61        code: &[u8],
62        ancestors: Ancestors<'a, '_>,
63    ) -> SpaceKind {
64        crate::roles::elixir::opens_space(node, code, ancestors)
65    }
66
67    // Source-aware name extraction for the macro-shaped declarations.
68    // `def foo(x, y) do … end` parses (with the tree-sitter-elixir
69    // grammar shipped here) as
70    //   `Call { target: Identifier "def", Arguments { Call { target:
71    //     Identifier "foo", Arguments { … } } }, DoBlock { … } }`
72    // i.e. the head Call is wrapped in an `Arguments` node, not a
73    // direct child. `defmodule Foo.Bar do … end` parses similarly with
74    // the `Alias` inside `Arguments`. We descend through one
75    // `Arguments` layer when present, then either:
76    //   - return the `Identifier` / `Alias` text directly
77    //     (`defmodule Foo`, `def foo` for an arity-zero head with no
78    //     parentheses), or
79    //   - return the inner head Call's `target` text
80    //     (`def foo(x, y)`).
81    // Falls back to the trait default behaviour (`<anonymous>` for
82    // nodes without a `name` field) when the Call is not one we
83    // recognise.
84    fn get_func_space_name<'a, 'tree>(
85        node: &Node<'tree>,
86        code: &'a [u8],
87        ancestors: Ancestors<'tree, '_>,
88    ) -> Option<&'a str> {
89        use crate::lang_helpers::elixir::elixir_declaration;
90        // A `defmodule` always names its head; a method macro only
91        // outside a `quote` template, matching the func-space promotion
92        // rule (#310) — the one `elixir_declaration` lookup both rows
93        // read. Its quote-block climb reads the caller's chain rather
94        // than `Node::parent` (#1088): this fires once per *promoted*
95        // space rather than per node, but `bca function` and the
96        // suppression scan reach it through `get_func_name` on every
97        // function node, where the climb was `O(depth)` apiece.
98        if elixir_declaration(node, code, ancestors).is_some() {
99            let target_id = node.child_by_field_name("target").map(|t| t.id());
100            if let Some(name) = node
101                .children()
102                .filter(|child| Some(child.id()) != target_id)
103                .find_map(|child| elixir_extract_head_name(&child, code))
104            {
105                return Some(name);
106            }
107        }
108
109        if let Some(name) = node.child_by_field_name("name") {
110            return node_text(code, &name);
111        }
112        Some("<anonymous>")
113    }
114
115    keyword_roles!(elixir);
116
117    /// The `Comparison`, `ShortCircuit`, `CaseArm` and `Guard` rows'
118    /// payers bill as operators (#1695) — what `paying_roles!` reads —
119    /// except that the `Guard` row is not asked. Its `when` payer is
120    /// gated on a guard position, which climbs the chain of nested
121    /// `when` operators a repeated guard (`when a when b when …`)
122    /// builds: asked once per token, that is quadratic in the chain,
123    /// and the answer cannot move this reading — a `when` the gate
124    /// leaves out (a typespec's `when a: integer`) bills as an operator
125    /// through the byte-less arm all the same, and the one position
126    /// where it does not, inside an `operator_identifier` (`&when/2`),
127    /// is `get_op_type`'s first test, repeated here since this reading
128    /// comes first. The counting consumers pay that climb once per
129    /// guard, where it decides something.
130    // role-bypass: allow(Guard) — the Halstead reading of the row's one payer, which bills as
131    // an operator in every position but a name's and so skips the row's position gate
132    fn get_paying_role<'a>(
133        node: &Node<'a>,
134        code: &[u8],
135        ancestors: Ancestors<'a, '_>,
136    ) -> TokenRole {
137        use crate::roles::elixir::{case_arm, comparison, guard, short_circuit};
138        let kind = node.kind_id();
139        if guard::PAYERS.contains(&kind) {
140            return if ancestors.parent_has_kind(node, Elixir::OperatorIdentifier as u16) {
141                TokenRole::Unknown
142            } else {
143                TokenRole::Operator
144            };
145        }
146        if comparison::pays_at_token_kind(kind, node, code, ancestors)
147            || short_circuit::pays_at_token_kind(kind, node, code, ancestors)
148            || case_arm::pays_at_token_kind(kind, node, code, ancestors)
149        {
150            TokenRole::Operator
151        } else {
152            TokenRole::Unknown
153        }
154    }
155
156    fn get_op_type<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> TokenRole {
157        use Elixir as E;
158
159        // A *named* operator (`&==/2`, `&and/2`, `Kernel.||(a, b)`) is one
160        // `operator_identifier` holding the operator token. The wrapper is
161        // the operand, as `foo` is in `&foo/2`, so the token inside it must
162        // not also bill an operator (grammar-dispatch §5, #1534). The
163        // wrapper is the keeper because it exists for every spelling: `..`
164        // is a childless `operator_identifier`, so keeping the leaf would
165        // lose it.
166        if ancestors.parent_has_kind(node, E::OperatorIdentifier as u16) {
167            return TokenRole::Unknown;
168        }
169
170        match node.kind_id().into() {
171            // Sigil delimiter punctuation. The delimiter choice is
172            // spelling, not semantics — `~r/abc/` is not two divisions
173            // and `~w(a b)` opens no call — so counting these tokens
174            // made `n1`/`N1` vary with the author's delimiter choice
175            // (#1256). The `Sigil` node itself is the operand (below)
176            // and `~` the single per-sigil operator; the delimiters are
177            // suppressed exactly when their parent is the sigil — the
178            // compound-leaf guard of grammar-dispatch §5, mirroring
179            // Bash's `SimpleExpansion` parent check. Verified via
180            // `bca dump` at the pinned grammar: `/ ( { [ < > |` are the
181            // only delimiter kinds surfacing as `Sigil` children that
182            // the operator arm below also matches; the quote delimiters
183            // (`"`, `'`, `"""`, `'''`) and the closers `) } ]` have no
184            // operator arm and need no guard. Same-kind tokens outside
185            // a sigil (division `a / b`, comparison `<`, pipe `|`) fall
186            // through to the operator arm and still count.
187            // role-bypass: allow(Comparison) — a sigil delimiter's suppression, not whether `<` is a
188            // comparison: the row's `applied` gate already leaves it out
189            E::SLASH | E::LPAREN | E::LBRACE | E::LBRACK | E::LT | E::GT | E::PIPE
190                if ancestors.parent_has_kind(node, E::Sigil as u16) =>
191            {
192                TokenRole::Unknown
193            }
194            // A quoted atom's opening `:`. The quoting is spelling, not
195            // semantics — `:"a b"` names the same kind of value `:a`
196            // does — but only the quoted form surfaces its `:` as a
197            // leaf: the bare `atom` is one `token(seq(":", …))`, so its
198            // `:` reaches no arm, and Ruby's `:"a b"` opens with a
199            // single `:"` token its getter bills nothing for. Counting
200            // this leaf made `n1`/`N1` rise by one per quoted atom
201            // against both twins (#1858); the literal is the operand
202            // (below) and the `:` is suppressed exactly when its parent
203            // is the quoted atom, the compound-leaf guard of
204            // grammar-dispatch §5 the sigil arm above applies. A
205            // `quoted_keyword` needs none: its trailing `:` is the
206            // grammar's own `quoted_keyword_token1` kind, not `COLON`,
207            // and reaches no operator arm. The guard's other branch is
208            // not reachable from valid input: tree-sitter-elixir 0.3.5
209            // emits a standalone `COLON` leaf only inside a
210            // `quoted_atom` (a `::` is its own kind, and every other
211            // `:` is part of a larger token), so a `COLON` under any
212            // other parent exists only in an `ERROR` recovery, where it
213            // falls through to the operator arm and counts.
214            E::COLON if ancestors.parent_has_kind(node, E::QuotedAtom as u16) => {
215                TokenRole::Unknown
216            }
217            // Reserved-word keywords that have dedicated token kinds in
218            // the grammar — block delimiters, exception clauses, and
219            // word-form logical / membership operators. `fn` is not
220            // here: `roles/elixir.rs` declares it and `get_keyword_role`
221            // bills it (#1693).
222            // (Macro-shaped keywords like `def`/`defp`/`if`/`case`/`cond`
223            // are NOT here: they surface as `Identifier` tokens in a
224            // `Call`'s `target` field and are counted as operands below.)
225            //
226            // The comparison and short-circuit tokens sit in this arm for
227            // the spellings the `Comparison` / `ShortCircuit` rows'
228            // `applied` gate leaves out — a capture (`&==/2`, `&and/2`),
229            // a `Kernel.||(a, b)` call's name, a single-token atom or
230            // keyword, a recovered token — which bill as the operators
231            // they spell, as they did before the rows; the rows pay the
232            // applied spellings through `get_paying_role` (#1695), so
233            // for these kinds the vocabulary is the union of the two.
234            // `when` is not here: `get_paying_role` bills every spelling
235            // of the `Guard` row's payer, guard or typespec binding.
236            // role-bypass: allow(Comparison, ShortCircuit) — the operator classification of the
237            // spellings the rows' `applied` gate leaves out
238            E::Do | E::End | E::End2 | E::Else | E::After | E::Catch | E::Rescue
239            | E::Not | E::Or | E::And | E::In | E::Notin
240            // Structural punctuation acting as operators. Only the
241            // *opening* delimiter counts (the pair folds to one glyph in
242            // `get_operator_id_as_str`); the former `RPAREN`/`RBRACE`/
243            // `RBRACK` arms double-counted every balanced pair, inflating
244            // n1/N1 (#695). `LTLT`/`GTGT` are the bitstring `<<`/`>>`
245            // delimiters — left unfolded and counted as the majority of
246            // languages count their shift-like glyphs. `LPAREN2`/`LBRACK2`
247            // are defensive — the runtime `public_symbol_map` collapses them
248            // to `LPAREN`/`LBRACK` before `kind_id()`, so they never fire
249            // (#768; see the Cpp impl note).
250            | E::LPAREN | E::LPAREN2 | E::LBRACE
251            | E::LBRACK | E::LBRACK2 | E::LTLT | E::GTGT
252            | E::COMMA | E::SEMI | E::COLON | E::COLONCOLON | E::DOT
253            | E::DOTDOT | E::DOTDOTDOT | E::PERCENT | E::AT
254            // Arithmetic / unary
255            | E::PLUS | E::DASH | E::STAR | E::STARSTAR | E::SLASH
256            // Comparison
257            | E::EQEQ | E::EQEQEQ | E::BANGEQ | E::BANGEQEQ
258            | E::LT | E::GT | E::LTEQ | E::GTEQ
259            // Logical
260            | E::AMPAMP | E::PIPEPIPE | E::BANG
261            // Bitwise / Erlang-band. `TILDE` is only reachable as the
262            // sigil marker in this grammar (Elixir has no unary `~`;
263            // the Erlang-style ops are `~~~` etc.) and is kept as the
264            // deliberate single per-sigil operator (#1256).
265            | E::AMP | E::PIPE | E::CARET | E::TILDE
266            | E::AMPAMPAMP | E::PIPEPIPEPIPE | E::CARETCARETCARET | E::TILDETILDETILDE
267            | E::LTLTLT | E::GTGTGT
268            // Assignment / match
269            | E::EQ
270            // Concat / list operations
271            | E::PLUSPLUS | E::DASHDASH | E::LTGT
272            | E::PLUSPLUSPLUS | E::DASHDASHDASH
273            // Pipe / capture / generator / stab arrow
274            | E::PIPEGT | E::LTPIPEGT | E::DASHGT | E::LTDASH
275            // Map pair / default arg / regex match / range step
276            | E::EQGT | E::BSLASHBSLASH | E::EQTILDE | E::SLASHSLASH
277            // Custom / less common Elixir operators
278            | E::LTTILDE | E::TILDEGT | E::LTTILDEGT | E::LTLTTILDE | E::TILDEGTGT
279                => TokenRole::Operator,
280
281            // String literals contribute exactly one operand each when
282            // they are inert. When they carry an `interpolation` child,
283            // the interpolated expressions are already walked and counted
284            // as operands in their own right; counting the wrapping
285            // literal as well would double-count the inner identifiers'
286            // contribution (issue #180).
287            //
288            // The `#{` marker itself contributes nothing. It was an
289            // operator via `HASHLBRACE` until #1314, which settled the
290            // rule across every interpolating language: an
291            // interpolation opener is spelling, not an operation, and
292            // the interpolated expression's own operators are counted
293            // either way. Elixir spells the marker with the *same*
294            // token as Ruby, so leaving it counted here would have made
295            // the two disagree on one construct — the divergence that
296            // rule exists to remove. Elixir Halstead operator counts
297            // drop for interpolated strings, charlists and sigils.
298            // The two quoted forms interpolate the same way, and sat in
299            // the plain operand arm below until the row claimed them, so
300            // `:"q #{a}"` billed the atom and the `a` inside it while
301            // `"q #{a}"` billed only the `a` — Ruby's `BareSymbol` shape
302            // (#1353).
303            // role-bypass: allow(StringLit) — the operand classification of the literals
304            // under the row's `wraps` list, a projection the row does not answer
305            E::String | E::Charlist | E::Sigil | E::QuotedAtom | E::QuotedKeyword => {
306                Self::string_operand_type(node, crate::roles::elixir::string_lit::WRAPS)
307            }
308
309            // Operands: identifiers and literals. Sigil names/modifiers
310            // (`~r`, the trailing `i`/`u` flags) stay as operands even
311            // for interpolated sigils — they are distinct tokens with
312            // their own text.
313            //
314            // `boolean: choice("true", "false")` and `nil: "nil"` each
315            // wrap a keyword leaf, so a literal reaches the walker
316            // twice; listing the wrapper and the leaf both inflated `N2`
317            // by one per literal while the text-keyed `n2` hid it
318            // (#1253). Only the wrappers count, mirroring Ruby's `Nil` /
319            // `Nil2` split. Unlike C#, the leaves need no parent guard:
320            // those two rules are the grammar's only producers of them,
321            // and the one other position accepting the reserved words —
322            // the right-hand side of a remote dot, `Foo.nil` — aliases
323            // them to `identifier`.
324            E::Identifier | E::Alias | E::OperatorIdentifier
325            | E::SigilName | E::SigilName2 | E::SigilModifiers
326            | E::Keyword | E::Keyword2
327            | E::Integer | E::Float | E::Char
328            | E::Atom | E::Atom2
329            | E::Boolean | E::Nil
330                => TokenRole::Operand,
331
332            _ => TokenRole::Unknown,
333        }
334    }
335
336    get_operator!(Elixir);
337}