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            // Reserved-word keywords that have dedicated token kinds in
195            // the grammar — block delimiters, exception clauses, and
196            // word-form logical / membership operators. `fn` is not
197            // here: `roles/elixir.rs` declares it and `get_keyword_role`
198            // bills it (#1693).
199            // (Macro-shaped keywords like `def`/`defp`/`if`/`case`/`cond`
200            // are NOT here: they surface as `Identifier` tokens in a
201            // `Call`'s `target` field and are counted as operands below.)
202            //
203            // The comparison and short-circuit tokens sit in this arm for
204            // the spellings the `Comparison` / `ShortCircuit` rows'
205            // `applied` gate leaves out — a capture (`&==/2`, `&and/2`),
206            // a `Kernel.||(a, b)` call's name, a single-token atom or
207            // keyword, a recovered token — which bill as the operators
208            // they spell, as they did before the rows; the rows pay the
209            // applied spellings through `get_paying_role` (#1695), so
210            // for these kinds the vocabulary is the union of the two.
211            // `when` is not here: `get_paying_role` bills every spelling
212            // of the `Guard` row's payer, guard or typespec binding.
213            // role-bypass: allow(Comparison, ShortCircuit) — the operator classification of the
214            // spellings the rows' `applied` gate leaves out
215            E::Do | E::End | E::End2 | E::Else | E::After | E::Catch | E::Rescue
216            | E::Not | E::Or | E::And | E::In | E::Notin
217            // Structural punctuation acting as operators. Only the
218            // *opening* delimiter counts (the pair folds to one glyph in
219            // `get_operator_id_as_str`); the former `RPAREN`/`RBRACE`/
220            // `RBRACK` arms double-counted every balanced pair, inflating
221            // n1/N1 (#695). `LTLT`/`GTGT` are the bitstring `<<`/`>>`
222            // delimiters — left unfolded and counted as the majority of
223            // languages count their shift-like glyphs. `LPAREN2`/`LBRACK2`
224            // are defensive — the runtime `public_symbol_map` collapses them
225            // to `LPAREN`/`LBRACK` before `kind_id()`, so they never fire
226            // (#768; see the Cpp impl note).
227            | E::LPAREN | E::LPAREN2 | E::LBRACE
228            | E::LBRACK | E::LBRACK2 | E::LTLT | E::GTGT
229            | E::COMMA | E::SEMI | E::COLON | E::COLONCOLON | E::DOT
230            | E::DOTDOT | E::DOTDOTDOT | E::PERCENT | E::AT
231            // Arithmetic / unary
232            | E::PLUS | E::DASH | E::STAR | E::STARSTAR | E::SLASH
233            // Comparison
234            | E::EQEQ | E::EQEQEQ | E::BANGEQ | E::BANGEQEQ
235            | E::LT | E::GT | E::LTEQ | E::GTEQ
236            // Logical
237            | E::AMPAMP | E::PIPEPIPE | E::BANG
238            // Bitwise / Erlang-band. `TILDE` is only reachable as the
239            // sigil marker in this grammar (Elixir has no unary `~`;
240            // the Erlang-style ops are `~~~` etc.) and is kept as the
241            // deliberate single per-sigil operator (#1256).
242            | E::AMP | E::PIPE | E::CARET | E::TILDE
243            | E::AMPAMPAMP | E::PIPEPIPEPIPE | E::CARETCARETCARET | E::TILDETILDETILDE
244            | E::LTLTLT | E::GTGTGT
245            // Assignment / match
246            | E::EQ
247            // Concat / list operations
248            | E::PLUSPLUS | E::DASHDASH | E::LTGT
249            | E::PLUSPLUSPLUS | E::DASHDASHDASH
250            // Pipe / capture / generator / stab arrow
251            | E::PIPEGT | E::LTPIPEGT | E::DASHGT | E::LTDASH
252            // Map pair / default arg / regex match / range step
253            | E::EQGT | E::BSLASHBSLASH | E::EQTILDE | E::SLASHSLASH
254            // Custom / less common Elixir operators
255            | E::LTTILDE | E::TILDEGT | E::LTTILDEGT | E::LTLTTILDE | E::TILDEGTGT
256                => TokenRole::Operator,
257
258            // String literals contribute exactly one operand each when
259            // they are inert. When they carry an `interpolation` child,
260            // the interpolated expressions are already walked and counted
261            // as operands in their own right; counting the wrapping
262            // literal as well would double-count the inner identifiers'
263            // contribution (issue #180).
264            //
265            // The `#{` marker itself contributes nothing. It was an
266            // operator via `HASHLBRACE` until #1314, which settled the
267            // rule across every interpolating language: an
268            // interpolation opener is spelling, not an operation, and
269            // the interpolated expression's own operators are counted
270            // either way. Elixir spells the marker with the *same*
271            // token as Ruby, so leaving it counted here would have made
272            // the two disagree on one construct — the divergence that
273            // rule exists to remove. Elixir Halstead operator counts
274            // drop for interpolated strings, charlists and sigils.
275            // role-bypass: allow(StringLit) — the operand classification of the literals
276            // under the row's `wraps` list, a projection the row does not answer
277            E::String | E::Charlist | E::Sigil => {
278                Self::string_operand_type(node, crate::roles::elixir::string_lit::WRAPS)
279            }
280
281            // Operands: identifiers and literals. Sigil names/modifiers
282            // (`~r`, the trailing `i`/`u` flags) stay as operands even
283            // for interpolated sigils — they are distinct tokens with
284            // their own text.
285            //
286            // `boolean: choice("true", "false")` and `nil: "nil"` each
287            // wrap a keyword leaf, so a literal reaches the walker
288            // twice; listing the wrapper and the leaf both inflated `N2`
289            // by one per literal while the text-keyed `n2` hid it
290            // (#1253). Only the wrappers count, mirroring Ruby's `Nil` /
291            // `Nil2` split. Unlike C#, the leaves need no parent guard:
292            // those two rules are the grammar's only producers of them,
293            // and the one other position accepting the reserved words —
294            // the right-hand side of a remote dot, `Foo.nil` — aliases
295            // them to `identifier`.
296            E::Identifier | E::Alias | E::OperatorIdentifier
297            | E::SigilName | E::SigilName2 | E::SigilModifiers
298            | E::Keyword | E::Keyword2 | E::QuotedKeyword
299            | E::Integer | E::Float | E::Char
300            | E::Atom | E::Atom2 | E::QuotedAtom
301            | E::Boolean | E::Nil
302                => TokenRole::Operand,
303
304            _ => TokenRole::Unknown,
305        }
306    }
307
308    get_operator!(Elixir);
309}