Skip to main content

big_code_analysis_ast/lang_helpers/
elixir.rs

1//! Elixir: keyword `Call` identity (`def`, `defmodule`, `quote`, …),
2//! and applied versus named operators.
3
4use crate::Elixir;
5use crate::node::{Ancestors, FoldLane, Node, WordSlot};
6
7/// Reads the text of the `target` field of an Elixir `Call` node.
8///
9/// Most of Elixir's control-flow constructs (`if`, `unless`, `for`,
10/// `while`, `case`, `cond`, `with`, `try`) and method-defining macros
11/// (`def`, `defp`, `defmacro`, …) parse as `Call` nodes whose `target`
12/// is an `Identifier` whose source text spells the keyword. The
13/// `Cyclomatic` and `Exit` impls already follow this pattern; this
14/// helper centralises the byte-text lookup so `Cognitive` and `Abc`
15/// can share it.
16///
17/// Returns `None` for Calls whose target is not a simple identifier
18/// (e.g. `Module.func(…)` parses as `RemoteCallWithParentheses` with
19/// the dotted name as target) or when the bytes are not valid UTF-8.
20///
21/// This is the text-returning primitive, for a caller holding no
22/// [`Ancestors`] or only an ancestor iterator derived from one (the
23/// `with`-argument and guard-position walks in `elixir_decisions`), or
24/// one that wants the text rather than the word. The `quote` fold's
25/// step is the same case: the chain `fold_down` hands it lends no
26/// cache, so a cached read there would only compute. A caller holding
27/// a chain reads [`elixir_call_target`], which answers from the walk's
28/// word slot for the node the walk is visiting and computes, without
29/// storing, for any other node (#1697, #1737); asking it about an
30/// enclosing call or a module's statements costs the one read this
31/// does, so there is no judgement to make per site.
32#[inline]
33#[must_use]
34pub fn elixir_call_keyword<'a>(node: &'a Node<'a>, code: &'a [u8]) -> Option<&'a str> {
35    if node.kind_id() != Elixir::Call as u16 {
36        return None;
37    }
38    call_keyword_reads::record();
39    let target = node.child_by_field_name("target")?;
40    if target.kind_id() != Elixir::Identifier as u16 {
41        return None;
42    }
43    target.utf8_text(code)
44}
45
46// How many `call` targets were read for their keyword: the walk's
47// promotion must read one per `call`, not one per row that gates on it
48// (#310, #1696), and the metric walk one per `call` across every
49// consumer (#1697). Only the count tells a second read apart. Readable
50// from the root crate's tests through `test-support`, since the walk
51// that lends the word slot lives there.
52crate::observation::counter!(call_keyword_reads, cfg(any(test, feature = "test-support")));
53
54/// What a `call`'s `target` identifier spells, for every word some
55/// consumer tells apart — the raw identity, not a policy reading (#1697).
56/// The control-flow rows (`Branch`, `Switch`, `Loop`, `Exit`) and
57/// `Member` gate on it directly, `FuncOpener` / `Container` through the
58/// crate's `elixir_declaration` projection, and cyclomatic, cognitive,
59/// ABC, NPM and NPA branch on it; one `call` is asked by all of them
60/// while the walk visits it, and [`elixir_call_target`] answers from the
61/// walk's word slot after the first. `Other` is every other target — a
62/// user function, a remote call, a computed callee, invalid UTF-8 —
63/// cached like any answer.
64///
65/// `#[repr(u8)]` because the slot stores the discriminant; the
66/// conversion back is total, reading anything past the table as
67/// `Other`.
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69#[repr(u8)]
70#[non_exhaustive]
71pub enum ElixirCallTarget {
72    /// Any target that is none of the words below.
73    Other = 0,
74    /// `if`.
75    If,
76    /// `unless`.
77    Unless,
78    /// `for`.
79    For,
80    /// `while`.
81    While,
82    /// `case`.
83    Case,
84    /// `cond`.
85    Cond,
86    /// `with`.
87    With,
88    /// `try`.
89    Try,
90    /// `receive`.
91    Receive,
92    /// `throw`.
93    Throw,
94    /// `raise`.
95    Raise,
96    /// `reraise`.
97    Reraise,
98    /// `exit`.
99    Exit,
100    /// `def`.
101    Def,
102    /// `defp`.
103    Defp,
104    /// `defmacro`.
105    Defmacro,
106    /// `defmacrop`.
107    Defmacrop,
108    /// `defmodule`.
109    Defmodule,
110    /// `defprotocol`.
111    Defprotocol,
112    /// `defimpl`.
113    Defimpl,
114    /// `defstruct`.
115    Defstruct,
116    /// `defguard`.
117    Defguard,
118    /// `defguardp`.
119    Defguardp,
120    /// `quote`.
121    Quote,
122    /// `alias`.
123    Alias,
124    /// `import`.
125    Import,
126    /// `require`.
127    Require,
128    /// `use`.
129    Use,
130}
131
132impl ElixirCallTarget {
133    /// Every variant, in discriminant order; what a consumer that keys
134    /// its policy on the word iterates to prove the policy agrees with
135    /// the rows for all of them.
136    pub const ALL: [Self; 29] = [
137        Self::Other,
138        Self::If,
139        Self::Unless,
140        Self::For,
141        Self::While,
142        Self::Case,
143        Self::Cond,
144        Self::With,
145        Self::Try,
146        Self::Receive,
147        Self::Throw,
148        Self::Raise,
149        Self::Reraise,
150        Self::Exit,
151        Self::Def,
152        Self::Defp,
153        Self::Defmacro,
154        Self::Defmacrop,
155        Self::Defmodule,
156        Self::Defprotocol,
157        Self::Defimpl,
158        Self::Defstruct,
159        Self::Defguard,
160        Self::Defguardp,
161        Self::Quote,
162        Self::Alias,
163        Self::Import,
164        Self::Require,
165        Self::Use,
166    ];
167
168    /// The word `text` spells, `Other` for anything else.
169    #[must_use]
170    pub fn from_text(text: &str) -> Self {
171        // bca: suppress(cyclomatic) — one arm per word, a lookup table
172        match text {
173            "if" => Self::If,
174            "unless" => Self::Unless,
175            "for" => Self::For,
176            "while" => Self::While,
177            "case" => Self::Case,
178            "cond" => Self::Cond,
179            "with" => Self::With,
180            "try" => Self::Try,
181            "receive" => Self::Receive,
182            "throw" => Self::Throw,
183            "raise" => Self::Raise,
184            "reraise" => Self::Reraise,
185            "exit" => Self::Exit,
186            "def" => Self::Def,
187            "defp" => Self::Defp,
188            "defmacro" => Self::Defmacro,
189            "defmacrop" => Self::Defmacrop,
190            "defmodule" => Self::Defmodule,
191            "defprotocol" => Self::Defprotocol,
192            "defimpl" => Self::Defimpl,
193            "defstruct" => Self::Defstruct,
194            "defguard" => Self::Defguard,
195            "defguardp" => Self::Defguardp,
196            "quote" => Self::Quote,
197            "alias" => Self::Alias,
198            "import" => Self::Import,
199            "require" => Self::Require,
200            "use" => Self::Use,
201            _ => Self::Other,
202        }
203    }
204
205    /// The method-defining macros: `def` / `defp` / `defmacro` /
206    /// `defmacrop`.
207    #[inline]
208    #[must_use]
209    pub fn is_method_macro(self) -> bool {
210        matches!(
211            self,
212            Self::Def | Self::Defp | Self::Defmacro | Self::Defmacrop
213        )
214    }
215
216    /// The abrupt exits: `throw` / `raise` / `reraise` / `exit`.
217    #[inline]
218    #[must_use]
219    pub fn is_exit(self) -> bool {
220        matches!(self, Self::Throw | Self::Raise | Self::Reraise | Self::Exit)
221    }
222
223    fn from_slot(value: u8) -> Self {
224        Self::ALL
225            .get(usize::from(value))
226            .copied()
227            .unwrap_or(Self::Other)
228    }
229}
230
231/// The word `target` spells — the inverse of
232/// [`ElixirCallTarget::from_text`] — or `None` for `Other`, which is
233/// every other target. A test that builds a fixture per word, or
234/// reports coverage per word, reads this rather than carrying a second
235/// table of spellings. A free fn rather than a method so the type's
236/// `wmc` counts one lookup table, not two of the same shape.
237#[must_use]
238pub fn elixir_call_target_word(target: ElixirCallTarget) -> Option<&'static str> {
239    use ElixirCallTarget as T;
240    // bca: suppress(cyclomatic) — one arm per word, a lookup table
241    Some(match target {
242        T::Other => return None,
243        T::If => "if",
244        T::Unless => "unless",
245        T::For => "for",
246        T::While => "while",
247        T::Case => "case",
248        T::Cond => "cond",
249        T::With => "with",
250        T::Try => "try",
251        T::Receive => "receive",
252        T::Throw => "throw",
253        T::Raise => "raise",
254        T::Reraise => "reraise",
255        T::Exit => "exit",
256        T::Def => "def",
257        T::Defp => "defp",
258        T::Defmacro => "defmacro",
259        T::Defmacrop => "defmacrop",
260        T::Defmodule => "defmodule",
261        T::Defprotocol => "defprotocol",
262        T::Defimpl => "defimpl",
263        T::Defstruct => "defstruct",
264        T::Defguard => "defguard",
265        T::Defguardp => "defguardp",
266        T::Quote => "quote",
267        T::Alias => "alias",
268        T::Import => "import",
269        T::Require => "require",
270        T::Use => "use",
271    })
272}
273
274/// [`ElixirCallTarget`] of `node`: `Other` for anything but a `call`
275/// whose `target` is an `identifier` spelling one of the words. Read
276/// once per `call` per walk for the node the walk is visiting — the
277/// slot holds that node's answer (#1697, #1737) — and once per ask
278/// about any other node, which is computed and not stored; every row
279/// gate and metric consumer that wants the word goes through here, so
280/// the `call_keyword_reads` counter counts misses.
281#[inline]
282#[must_use]
283pub fn elixir_call_target<'a>(
284    node: &Node<'a>,
285    code: &[u8],
286    ancestors: Ancestors<'a, '_>,
287) -> ElixirCallTarget {
288    if node.kind_id() != Elixir::Call as u16 {
289        return ElixirCallTarget::Other;
290    }
291    ElixirCallTarget::from_slot(ancestors.classified(WordSlot::ElixirCallTarget, node, || {
292        elixir_call_keyword(node, code).map_or(ElixirCallTarget::Other, ElixirCallTarget::from_text)
293            as u8
294    }))
295}
296
297/// What a `call` declares, read from its target text once: a module or
298/// a method (outside a `quote` template — #310). The `FuncOpener` and
299/// `Container` rows and the walk's combined promotion lookup all read
300/// this one answer, so a `call` pays one keyword scan however many of
301/// them ask (#310 follow-on perf, #1696).
302#[derive(Clone, Copy, Debug, PartialEq, Eq)]
303pub(crate) enum ElixirDeclaration {
304    /// `defmodule`.
305    Module,
306    /// `def` / `defp` / `defmacro` / `defmacrop`, outside any `quote`.
307    Method,
308}
309
310/// [`ElixirDeclaration`] of `node`; `None` for anything but a `call`
311/// whose target spells a declaring macro, a method macro inside a
312/// `quote` template included.
313#[must_use]
314pub(crate) fn elixir_declaration<'a>(
315    node: &Node<'a>,
316    code: &[u8],
317    ancestors: Ancestors<'a, '_>,
318) -> Option<ElixirDeclaration> {
319    match elixir_call_target(node, code, ancestors) {
320        ElixirCallTarget::Defmodule => Some(ElixirDeclaration::Module),
321        target
322            if target.is_method_macro() && !elixir_is_inside_quote_block(node, code, ancestors) =>
323        {
324            Some(ElixirDeclaration::Method)
325        }
326        _ => None,
327    }
328}
329
330/// Returns true when `node` is lexically nested inside the `do_block` of a
331/// `quote do … end` Call (Elixir's metaprogramming template). A `def` /
332/// `defp` / `defmacro` / `defmacrop` inside `quote` does not define a
333/// method of any enclosing module — the syntax tree is a code template
334/// emitted later, when the surrounding macro is invoked. Treating those
335/// quoted Calls as methods inflates `Wmc` and disagrees with `Npm`'s
336/// direct-children classification (#310).
337///
338/// Under a walk that lent a [`FoldCache`](crate::FoldCache), the answer
339/// is folded down the chain once per ancestor — "is this, or anything
340/// above it, a `quote`" — so each query is amortised `O(1)`. The climb
341/// it replaces stopped at the first `quote` ancestor and was `O(1)` for
342/// a `def` directly inside one, but a `def` under no `quote` at all
343/// climbed to the root: one such `def` per nesting level measured
344/// quadratic (0.12 s / 0.47 s / 1.97 s at depths 1000 / 2000 / 4000,
345/// exponent 2.0) through `is_func_space_with_code` alone, which the
346/// `nom/nested-quote` probe could not see because every `def` there sits
347/// one step under a `quote` (lesson 82). Without a lent cache the climb
348/// runs as before, each step `O(1)` on a known chain and `O(depth)` with
349/// `Ancestors::unknown` (#1084).
350#[inline]
351#[must_use]
352pub(crate) fn elixir_is_inside_quote_block<'a>(
353    node: &Node<'a>,
354    code: &[u8],
355    ancestors: Ancestors<'a, '_>,
356) -> bool {
357    if ancestors.memoises_folds() {
358        return ancestors.fold_down(
359            node,
360            0,
361            FoldLane::InsideQuote,
362            0,
363            |inside, ancestor, _, _| {
364                u8::from(inside == 1 || elixir_call_keyword(ancestor, code) == Some("quote"))
365            },
366        ) == 1;
367    }
368    ancestors
369        .iter(node)
370        .any(|(n, _)| elixir_call_keyword(&n, code) == Some("quote"))
371}
372
373/// The `binary_operator` that applies `op`, an operator token, or `None`
374/// when the token is not applied there.
375///
376/// An operator token also *names* the operator: `&==/2`, `&and/2` and
377/// `Kernel.||(a, b)` hold it inside an `operator_identifier`, and the
378/// single-token `atom` / `keyword` spell it too. None of those is a
379/// `binary_operator` with operands to compare or chain, and under error
380/// recovery the parent can be an `ERROR` with no operands, so every
381/// decision metric keys on this parent rather than on the token (#1531,
382/// #1534). A remote call that names the operator still *applies* it,
383/// though; see [`elixir_applying_remote_call`].
384///
385/// Matched by rule name rather than by `kind_id`: the grammar aliases
386/// `binary_operator` to three ids (`Elixir::BinaryOperator` through
387/// `BinaryOperator3`), and a name comparison stays correct when a bump
388/// adds a fourth (grammar-dispatch §1).
389#[must_use]
390pub fn elixir_applying_operator<'a>(
391    op: &Node<'a>,
392    ancestors: Ancestors<'a, '_>,
393) -> Option<Node<'a>> {
394    ancestors
395        .parent(op)
396        .filter(|parent| parent.kind() == "binary_operator")
397}
398
399/// The name of the short-circuit operator a remote call on `Kernel` with
400/// arguments applies, or `None` for any other node: the `||` of
401/// `Kernel.||(a, b)`, or of `x |> Kernel.||(y)`, which the pipe rewrites
402/// to it. Such a call expands the `Kernel` macro exactly as `a || b`
403/// does, so it short-circuits and decides as the operator does, where a
404/// capture (`&Kernel.||/2`, a call with no arguments) only names it. It
405/// has no `binary_operator`, so its operands are the call's arguments,
406/// and under a pipe the piped value, rather than `left` / `right` fields.
407///
408/// The receiver must spell `Kernel` (or `Elixir.Kernel`): a user module
409/// may define `||/2` as an ordinary function, and `Foo.||(a, b)` neither
410/// short-circuits nor decides.
411///
412/// The grammar lexes a symbolic name as a token inside the call's
413/// `operator_identifier`, which is what is returned. `Kernel.and(a, b)`
414/// and `Kernel.or(a, b)` spell their names as a plain `identifier`, with
415/// no `And` / `Or` token to find, so that identifier is returned instead
416/// (#1582). Any other name — `Kernel.+`, `Kernel.!`, `Kernel.not`,
417/// `Kernel.in` — is a function or decides nothing, and is not found; nor
418/// is the childless `..`. [`elixir_short_circuit_name`] says which
419/// operation the name applies.
420///
421/// Every identifier a walk meets asks this of its call, so the receiver,
422/// which turns nearly all of them away without a cursor, is read before
423/// the call's children are scanned for its `arguments`.
424///
425/// Matched by rule name: `dot` and `arguments` are aliased to several
426/// ids each (grammar-dispatch §1).
427#[must_use]
428pub fn elixir_kernel_short_circuit_name<'a>(call: &Node<'a>, code: &[u8]) -> Option<Node<'a>> {
429    kernel_short_circuit_parts(call, code).map(|(name, _)| name)
430}
431
432fn kernel_short_circuit_parts<'a>(call: &Node<'a>, code: &[u8]) -> Option<(Node<'a>, Node<'a>)> {
433    if call.kind() != "call" {
434        return None;
435    }
436    let dot = call.child_by_field_name("target").filter(|target| {
437        target.kind() == "dot"
438            && target.child_by_field_name("left").is_some_and(|receiver| {
439                matches!(
440                    code.get(receiver.start_byte()..receiver.end_byte()),
441                    Some(b"Kernel" | b"Elixir.Kernel")
442                )
443            })
444    })?;
445    let name = dot.child_by_field_name("right")?;
446    let name = if name.kind() == "operator_identifier" {
447        name.child(0)?
448    } else {
449        name
450    };
451    elixir_short_circuit_name(&name, code)
452        .and_then(|_| call.children().find(|child| child.kind() == "arguments"))
453        .map(|arguments| (name, arguments))
454}
455
456/// The short-circuit operation an operator token kind applies, keyed by
457/// its symbol: `&&` for `&&` and `and`, `||` for `||` and `or`. A word
458/// form demands a boolean left operand, but it is the same conjunction or
459/// disjunction to read, so one sequence key serves both spellings.
460/// `None` for any other kind.
461#[must_use]
462pub fn elixir_short_circuit_kind(kind_id: u16) -> Option<Elixir> {
463    match kind_id.into() {
464        Elixir::AMPAMP | Elixir::And => Some(Elixir::AMPAMP),
465        Elixir::PIPEPIPE | Elixir::Or => Some(Elixir::PIPEPIPE),
466        _ => None,
467    }
468}
469
470/// [`elixir_short_circuit_kind`] for an operator's name as
471/// [`elixir_kernel_short_circuit_name`] returns it: a token, or the
472/// `identifier` spelling `Kernel.and` / `Kernel.or` (#1582), whose
473/// bytes decide. Ask it only of such a name — an identifier is an `and`
474/// operator nowhere else.
475#[must_use]
476pub fn elixir_short_circuit_name(name: &Node, code: &[u8]) -> Option<Elixir> {
477    if name.kind_id() != Elixir::Identifier as u16 {
478        return elixir_short_circuit_kind(name.kind_id());
479    }
480    match code.get(name.start_byte()..name.end_byte())? {
481        b"and" => Some(Elixir::AMPAMP),
482        b"or" => Some(Elixir::PIPEPIPE),
483        _ => None,
484    }
485}
486
487/// A recognized short-circuit `Kernel` call and the context its operands need.
488pub struct ElixirRemoteCall<'tree, 'chain> {
489    /// The call that applies the operator.
490    pub call: Node<'tree>,
491    /// The argument list found while recognizing the call.
492    pub arguments: Node<'tree>,
493    /// The call's own ancestry.
494    pub ancestors: Ancestors<'tree, 'chain>,
495}
496
497/// The `Kernel` remote call that applies `op`, a short-circuit operator's
498/// name — the call [`elixir_kernel_short_circuit_name`] answers `op` for
499/// — with its argument list and ancestry, or `None` when `op` sits
500/// anywhere else. A token's parents are the `operator_identifier`, then
501/// the `dot`, then the call; the `identifier` naming `Kernel.and` sits
502/// on the `dot` directly. Any other node fails on the first one or two
503/// parents' kinds, so the check is cheap enough to ask of every
504/// identifier a walk meets.
505#[must_use]
506pub fn elixir_applying_remote_call<'a, 'c>(
507    op: &Node<'a>,
508    code: &[u8],
509    ancestors: Ancestors<'a, 'c>,
510) -> Option<ElixirRemoteCall<'a, 'c>> {
511    let mut up = ancestors.iter(op);
512    let (mut dot, _) = up.next()?;
513    if dot.kind() == "operator_identifier" {
514        dot = up.next()?.0;
515    }
516    if dot.kind() != "dot" {
517        return None;
518    }
519    let (call, call_ancestors) = up.next()?;
520    kernel_short_circuit_parts(&call, code)
521        .filter(|(name, _)| name.id() == op.id())
522        .map(|(_, arguments)| ElixirRemoteCall {
523            call,
524            arguments,
525            ancestors: call_ancestors,
526        })
527}
528
529#[cfg(test)]
530mod tests {
531    use super::*;
532    use crate::ElixirCode;
533    use crate::node::Tree;
534    use crate::test_support::for_each_node_with_chain;
535
536    #[cfg(feature = "elixir")]
537    #[test]
538    fn short_circuit_name_requires_the_identifiers_source_span() {
539        let source = b"Kernel.and(a, b)";
540        let tree = Tree::new::<ElixirCode>(source);
541        let name = tree
542            .get_root()
543            .preorder()
544            .find(|node| {
545                node.kind_id() == Elixir::Identifier as u16 && node.utf8_text(source) == Some("and")
546            })
547            .expect("fixture contains the operator name");
548        assert_eq!(
549            elixir_short_circuit_name(&name, source),
550            Some(Elixir::AMPAMP)
551        );
552        assert_eq!(
553            elixir_short_circuit_name(&name, &source[..name.end_byte() - 1]),
554            None
555        );
556    }
557
558    #[cfg(feature = "elixir")]
559    #[test]
560    fn remote_call_lookup_rejects_a_root_and_keeps_its_argument_list() {
561        let source = b"Kernel.and(a, b)\nKernel.||(c, d)\n";
562        let mut recognized = Vec::new();
563        for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
564            let known = elixir_applying_remote_call(node, source, Ancestors::known(chain));
565            let unknown = elixir_applying_remote_call(node, source, Ancestors::unknown());
566            assert_eq!(
567                known.as_ref().map(|r| (r.call.id(), r.arguments.id())),
568                unknown.map(|r| (r.call.id(), r.arguments.id()))
569            );
570            if chain.is_empty() {
571                assert!(known.is_none());
572            }
573            if let Some(remote) = known {
574                assert_eq!(remote.arguments.kind(), "arguments");
575                assert_eq!(
576                    remote.ancestors.parent(&remote.call).map(|p| p.kind()),
577                    Some("source")
578                );
579                recognized.push((
580                    node.utf8_text(source)
581                        .expect("operator is UTF-8")
582                        .to_owned(),
583                    remote
584                        .arguments
585                        .utf8_text(source)
586                        .expect("arguments are UTF-8")
587                        .to_owned(),
588                ));
589            }
590        });
591        assert_eq!(
592            recognized,
593            [
594                ("and".to_owned(), "(a, b)".to_owned()),
595                ("||".to_owned(), "(c, d)".to_owned())
596            ]
597        );
598    }
599
600    // The memoised fold answers as the climb it replaced does, on every
601    // `call` of a fixture that has quoted and unquoted `def`s at several
602    // depths, a `quote` nested in a `quote`, and a `def` *after* a
603    // `quote` closes — where a fold that leaked state across siblings
604    // would still say "inside". Both spellings are asked through the
605    // walker's chain, one with a lent cache and one without. A fold that
606    // dropped the parent itself (`skip` of 1) is not observable here: a
607    // `def` is never a direct child of its `quote` call, since the
608    // grammar puts a `do_block` or an `arguments` list between them, so
609    // the two spellings agree on that perturbation by construction.
610    #[cfg(feature = "elixir")]
611    #[test]
612    fn inside_quote_fold_answers_as_the_climb_does() {
613        use crate::node::{FoldCache, Tree};
614        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";
615        let tree = Tree::new::<ElixirCode>(source);
616        assert!(!tree.get_root().has_error());
617        let cache = FoldCache::default();
618        let mut answers = Vec::new();
619        let mut stack = vec![(tree.get_root(), 0_usize)];
620        let mut chain: Vec<Node> = Vec::new();
621        while let Some((node, depth)) = stack.pop() {
622            chain.truncate(depth);
623            if let Some(kw) = elixir_call_keyword(&node, source) {
624                let folded = elixir_is_inside_quote_block(
625                    &node,
626                    source,
627                    Ancestors::known(&chain).with_folds(&cache),
628                );
629                let climbed = elixir_is_inside_quote_block(&node, source, Ancestors::known(&chain));
630                assert_eq!(folded, climbed, "`{kw}` at depth {depth}");
631                if ElixirCallTarget::from_text(kw).is_method_macro() {
632                    answers.push((kw.to_owned(), folded));
633                }
634            }
635            chain.push(node);
636            let children: Vec<_> = node.children().collect();
637            stack.extend(children.into_iter().rev().map(|child| (child, depth + 1)));
638        }
639        // Keyed on the `def`s only, so the expectation reads as the
640        // fixture does: `b`, `c`, `d` are quoted; `a`, `e`, `f` are not.
641        let defs: Vec<_> = answers.iter().map(|(_, inside)| *inside).collect();
642        assert_eq!(answers.len(), 7, "{answers:?}");
643        assert_eq!(
644            defs,
645            [false, false, true, true, true, false, false],
646            "{answers:?}"
647        );
648    }
649
650    // The word slot's budget (#1697, #1737): asked about one `call`
651    // several times while it is visited — as cyclomatic, cognitive, ABC
652    // and nexits ask on one visit — a walk that lent a cache through
653    // `for_walk` reads the target once per `call`, and one that lent
654    // none reads it every time. Between the repeats each `call` is also
655    // asked about its enclosing `call` through the same chain, as the
656    // `else:` pair and the `CaseArm` gate ask about theirs: that ask is
657    // computed and not stored, so it costs one read and the visited
658    // node's next ask is still served. Under the last-node-asked slot
659    // this replaced, the foreign ask evicted the entry and the repeat
660    // after it read again. The answers agree either way, so only the
661    // counter tells the two apart.
662    #[cfg(feature = "elixir")]
663    #[test]
664    fn call_target_is_read_once_per_call_under_a_cache() {
665        use crate::node::FoldCache;
666        const ASKS: usize = 4;
667        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";
668        let cache = FoldCache::default();
669        let mut calls = 0;
670        let mut enclosing_asks = 0;
671        let mut answers = std::collections::HashMap::new();
672        let mut cached = Vec::new();
673        let before = call_keyword_reads::observed();
674        for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
675            if node.kind_id() != Elixir::Call as u16 {
676                return;
677            }
678            calls += 1;
679            let walk = Ancestors::for_walk(chain, node, &cache);
680            let first = elixir_call_target(node, source, walk);
681            let enclosing = chain
682                .iter()
683                .rev()
684                .find(|ancestor| ancestor.kind_id() == Elixir::Call as u16);
685            for _ in 1..ASKS {
686                if let Some(enclosing) = enclosing {
687                    enclosing_asks += 1;
688                    // Visited earlier in pre-order, so its answer is on record.
689                    let recorded = answers[&enclosing.id()];
690                    assert_eq!(elixir_call_target(enclosing, source, walk), recorded);
691                }
692                assert_eq!(elixir_call_target(node, source, walk), first);
693            }
694            answers.insert(node.id(), first);
695            cached.push(first);
696        });
697        let cached_reads = call_keyword_reads::observed() - before;
698        let mut uncached = Vec::new();
699        let before = call_keyword_reads::observed();
700        for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
701            if node.kind_id() == Elixir::Call as u16 {
702                let chain = Ancestors::known(chain);
703                for _ in 0..ASKS {
704                    uncached.push(elixir_call_target(node, source, chain));
705                }
706            }
707        });
708        let uncached_reads = call_keyword_reads::observed() - before;
709        assert_eq!(
710            cached,
711            [
712                ElixirCallTarget::Defmodule,
713                ElixirCallTarget::Def,
714                ElixirCallTarget::Other, // f(a)
715                ElixirCallTarget::If,
716                ElixirCallTarget::Throw,
717                ElixirCallTarget::Unless,
718                ElixirCallTarget::Raise,
719                ElixirCallTarget::Case,
720                ElixirCallTarget::Other, // g()
721                ElixirCallTarget::Other, // Kernel.exit
722            ]
723        );
724        assert_eq!(calls, cached.len());
725        assert_eq!(
726            uncached,
727            cached
728                .iter()
729                .flat_map(|&t| std::iter::repeat_n(t, ASKS))
730                .collect::<Vec<_>>()
731        );
732        // Every call but the `defmodule` has an enclosing call to ask
733        // about, `ASKS - 1` times each.
734        assert_eq!(enclosing_asks, (calls - 1) * (ASKS - 1));
735        assert_eq!(
736            (cached_reads, uncached_reads),
737            (calls + enclosing_asks, ASKS * calls),
738            "one read per visited call plus one per ask about its enclosing call"
739        );
740    }
741
742    // A node that is not a `call` is `Other` before any read, and the
743    // counter shows no `target` field was read for it.
744    // `elixir_call_keyword`'s own kind check is what the counter
745    // observes; the outer early return in `elixir_call_target` is
746    // unobservable through it while the inner check stands (a slot
747    // write saved, not a correctness guard).
748    #[cfg(feature = "elixir")]
749    #[test]
750    fn call_target_of_a_non_call_is_other_without_a_read() {
751        let source = b"defmodule M do\n  def f(a), do: a + 1\nend\n";
752        let before = call_keyword_reads::observed();
753        // Collected rather than asserted per node: an `assert_eq!` with a
754        // formatted message inside the closure leaves its never-taken
755        // panic arm as uncovered lines in the coverage report, which
756        // reads as a gap in production code.
757        let mut seen = Vec::new();
758        for_each_node_with_chain::<ElixirCode>(source, |node, chain| {
759            if node.kind_id() != Elixir::Call as u16 {
760                seen.push((
761                    node.kind(),
762                    elixir_call_keyword(node, source).is_some(),
763                    call_keyword_reads::observed() - before,
764                    elixir_call_target(node, source, Ancestors::known(chain)),
765                ));
766            }
767        });
768        assert!(
769            seen.len() > 5,
770            "the fixture has non-call nodes to ask about"
771        );
772        let read = seen
773            .iter()
774            .filter(|&&(_, keyword, reads, target)| {
775                keyword || reads != 0 || target != ElixirCallTarget::Other
776            })
777            .map(|&(kind, ..)| kind)
778            .collect::<Vec<_>>();
779        assert_eq!(
780            read,
781            Vec::<&str>::new(),
782            "a non-call was read or classified"
783        );
784        assert_eq!(call_keyword_reads::observed(), before);
785    }
786
787    // Every discriminant the slot can hold converts back to the variant
788    // it came from; a value past the table — unreachable while `ALL`
789    // and the enum agree — is `Other`, never a panic.
790    #[test]
791    fn call_target_round_trips_through_the_slot() {
792        for target in ElixirCallTarget::ALL {
793            assert_eq!(ElixirCallTarget::from_slot(target as u8), target);
794        }
795        assert_eq!(
796            ElixirCallTarget::from_slot(u8::try_from(ElixirCallTarget::ALL.len()).expect("fits")),
797            ElixirCallTarget::Other
798        );
799        for (index, target) in ElixirCallTarget::ALL.iter().enumerate() {
800            assert_eq!(*target as usize, index, "`ALL` is in discriminant order");
801        }
802    }
803
804    /// `word` is the inverse of `from_text` on every target but
805    /// `Other`, which spells nothing: the one table of spellings, held
806    /// to the one table of words, so a test building a fixture per
807    /// word cannot carry a third (#1700).
808    #[test]
809    fn word_round_trips_through_from_text() {
810        for target in ElixirCallTarget::ALL {
811            match elixir_call_target_word(target) {
812                Some(word) => assert_eq!(ElixirCallTarget::from_text(word), target, "{word}"),
813                None => assert_eq!(target, ElixirCallTarget::Other),
814            }
815        }
816        assert_eq!(ElixirCallTarget::from_text("foo"), ElixirCallTarget::Other);
817    }
818}