big-code-analysis-ast 2.6.0

Parse and classification layer behind big-code-analysis (internal, version-locked)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
//! Elixir's role rows: the text-gated fixture (#1691). `def` / `defp` /
//! `defmacro` / `defmacrop` / `defmodule` are not grammar productions —
//! each is a `call` whose `target` identifier spells the keyword — so
//! the rows that name them read source bytes, and the one nested in a
//! `quote do … end` template reads the ancestor chain (#275, #310). The
//! Halstead keyword roles (#1693), the paying-construct roles (#1694,
//! #1695), the space tree (#1696) and the control flow — `Branch`,
//! `Switch`, `Loop`, `Catch`, `Exit`, with `ElseIf` absent (#1697) — are
//! declared, and the documentation rows (#1699) with them.

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};

/// Whether an operator token applies its operator: its parent is a
/// `binary_operator`. A token also *names* the operator — `&==/2`,
/// `&and/2` and `Kernel.||(a, b)` hold it inside an
/// `operator_identifier`, and a single-token `atom` / `keyword` spells
/// it too — and under error recovery its parent can be an `ERROR` with
/// no operands, so every decision metric keys on the parent (#1531,
/// #1534). A `Kernel` remote call that names a short-circuit operator
/// applies it too, but has no `binary_operator`: that spelling is
/// text-keyed on the receiver and stays the consumers' named extra
/// (#1574, #1582).
fn applied<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
    elixir_applying_operator(node, ancestors).is_some()
}

/// A `call` whose target spells a method-defining macro, outside any
/// `quote` block — `ElixirCode::is_func_with_code`'s rule. Both space
/// gates read `elixir_declaration`, one keyword scan; the walk's
/// combined promotion reads it once more directly rather than through
/// both rows (`checker/elixir.rs`).
fn method_macro<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
    elixir_declaration(node, code, ancestors) == Some(ElixirDeclaration::Method)
}

/// A `call` whose target spells `defmodule`.
fn class_macro<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
    elixir_declaration(node, code, ancestors) == Some(ElixirDeclaration::Module)
}

/// A `call` whose target spells `defstruct`, directly in a module body:
/// the struct's fields are the module's attributes (`npa/elixir.rs`).
/// NPA asks this of each statement while visiting the module, so each
/// ask is about a node other than the visited one: computed, one read
/// each, and not stored, so the module's own word stays in the slot
/// (#1737).
fn struct_macro<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
    elixir_call_target(node, code, ancestors) == ElixirCallTarget::Defstruct
}

// The control-flow constructs are `call`s told apart by their target's
// text (#275), read once per `call` per walk through
// `elixir_call_target` (#1697): each gate below is a compare on the
// cached word. The rows say what a construct *is*; which tier a
// `case` or a `receive` pays, and whether a `with` with no dispatching
// `else` pays at all, stays the cyclomatic body's policy.

/// `if` / `unless`.
fn control_branch<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
    matches!(
        elixir_call_target(node, code, ancestors),
        ElixirCallTarget::If | ElixirCallTarget::Unless
    )
}

/// `case` / `cond` / `with` / `try` / `receive`: the constructs whose
/// arms are the `CaseArm` row's `stab_clause`s and that cyclomatic's
/// modified tier counts as one container each.
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
    )
}

/// `for` (the comprehension) / `while`.
fn control_loop<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
    matches!(
        elixir_call_target(node, code, ancestors),
        ElixirCallTarget::For | ElixirCallTarget::While
    )
}

/// `throw` / `raise` / `reraise` / `exit`: Elixir has no `return`, and
/// these are the four abrupt exits (#1270).
fn control_exit<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
    elixir_call_target(node, code, ancestors).is_exit()
}

/// Whether a `stab_clause` is a decision arm — of a `case`, `cond`,
/// `with … else`, `receive` or a `try` handler — and not the fallback
/// (`_ ->`, `true ->`, a `receive`'s `after`), nor an anonymous
/// function's head (`elixir_decisions` has the shapes, #1454).
fn is_decision_clause<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
    elixir_clause_is_decision(node, code, ancestors)
}

/// Whether a `binary_operator` is a `when` operator — a guard's, or a
/// typespec's binding clause (`@spec f(a) :: a when a: integer`), which
/// only the operator's position tells apart (#1454). That position is
/// read from the *token's* ancestor chain by the payer gate below; the
/// owner is the operator by kind, which is what the root's guard walker
/// reaches from the token.
fn is_when_operator(node: &Node<'_>) -> bool {
    elixir_is_when_operator(node)
}

/// Whether a `when` token is a guard's rather than a typespec's: the
/// operator joining a clause head or function head to its condition
/// (#1454). Reads the token's ancestor chain and the bytes: a function
/// head is told by its call's target text (`def`, `defguard`, …) and a
/// `with` clause by its call's, so the row declares it `text_gated_by`
/// (#1874).
fn is_guard<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool {
    elixir_when_is_guard(node, code, ancestors)
}

role_table! {
    lang: Elixir;

    // Both rows gate the same `Call` kind on different target text, so
    // one kind sits in two rows of two *different* roles — allowed; the
    // same-role duplicate is what the macro rejects. `AnonymousFunction`
    // (`fn … end`) opens a space and is a closure (`checker/elixir.rs`).
    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] }
    // The three literal kinds and the two quoted forms: `quoted_atom`
    // (`:"a b"`, Ruby's `delimited_symbol`) and `quoted_keyword` (the
    // `"a b":` key of a pair), each a quote-delimited body of
    // `quoted_content`, `escape_sequence` and `interpolation` like a
    // `string`'s. The bare forms are excluded below, where Ruby's
    // `simple_symbol` is claimed (#1856).
    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" }
    // The `binary_operator` node — three aliased ids — carries every
    // binary operator; its `operator` field says which, so each row's
    // owner is gated on the field, and every payer on applying its
    // operator under one (`applied`), since a token also names the
    // operator in a capture, an atom or a `Kernel.op(a, b)` call. The
    // comparison payers are the four equalities, the four orderings
    // and the membership tests `in` / `not in` (the compound is one
    // token).
    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"
    }
    // `&&` / `||` and the strict-boolean `and` / `or`, each a kind of
    // its own. A `Kernel.||(a, b)` / `Kernel.and(a, b)` remote call
    // applies the same macro and decides as the operator does; it has
    // no `binary_operator` and its `and` / `or` are a plain
    // `identifier`, so it is the consumers' text-keyed extra, not this
    // row's.
    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" }
    // Every multi-way branch — `case`, `cond`, `with … else`, `receive`,
    // a `try`'s `rescue` / `catch` / `else` — is a `Call` whose clauses
    // are `stab_clause`s, as are an anonymous function's heads; which of
    // them is a decision is a question of position and bytes the gate
    // answers (#1454, lesson 11): the owner pays at the node, since the
    // clause's `->` is punctuation. Which call the clause sits in is
    // read from the ancestor chain, so this owner is never asked with
    // `Ancestors::unknown()`.
    CaseArm { owns [StabClause(text_gated_by is_decision_clause)] }
    // A guard is the `when` operator joining a clause or function head
    // to its condition; the token pays, gated to that position by its
    // ancestor chain and by the bytes of the call keyword above a head
    // or a `with` pattern (`def`, `defguard`, `with`), since a typespec's
    // `when a: integer` spells the same token on type syntax (#1454).
    // The `binary_operator` applying `when` owns it: whether that
    // operator is a guard's is the token's question, so the owner is
    // wider than the payer and no consumer reads it at the wrapper — ABC
    // and cyclomatic both count the token. Only the payer reads the
    // bytes, so the row's `TEXT_GATED` stays `false`.
    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"
    }
    // Every control construct is a `call` told by its target's text
    // (#275, #1697), so the four rows below own the one kind under four
    // text gates and pay at the node — a `call` has no keyword token.
    // The `Switch` row names the five arm-bearing constructs; cyclomatic
    // reads it at the owner and decides per word which tier pays
    // (`case` / `cond` / `try` the modified one; `with` only when its
    // `else` dispatches; `receive` only when it dispatches, plus a
    // standard decision for an `after` clause) — the policy table lives
    // beside that body, not here.
    Branch { owns [Call(text_gated_by control_branch)] }
    Switch { owns [Call(text_gated_by control_switch)] }
    Loop { owns [Call(text_gated_by control_loop)] }
    // The `rescue` / `catch` arms of a `try` are their own kinds, each
    // nesting as a C-family `catch_clause` does; the `try` call itself
    // is the `Switch` row's and pays nothing here (#416).
    Catch { owns [RescueBlock, CatchBlock] }
    Exit { owns [Call(text_gated_by control_exit)] }
    // `fn` is the one declaration keyword the grammar gives a kind of
    // its own. `def` / `defp` / `defmodule` / `defmacro` are not
    // keywords: each is the `identifier` target of a `Call`, told from
    // any other call by its text, and is `FuncOpener` / `Container`
    // territory (R06); the `Call` row (R08) bills the call.
    DeclKeyword { owns [Fn] }
    // A `defstruct` call is the closest thing to a field-set
    // declaration: its arguments are the module's attributes, which the
    // consumer counts in the three spellings the docs admit. A third
    // row gating the same `Call` kind on its target text, beside the
    // two space rows.
    Member { owns [Call(text_gated_by struct_macro)] }
    // The one comment kind. Elixir's documentation is the `@doc` /
    // `@moduledoc` attribute — a `Call` whose argument is a string —
    // which is neither a comment nor a bare docstring; recognising it
    // is the documentation epic's D19 (#1676), so
    // its five documentation rows are absent rather than pending (#1699).
    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};

    // Until #1696 the rows restated `checker/elixir.rs` and
    // `getter/elixir.rs` and this compared the two; now the classifiers
    // read the rows, so the expected answer per node is pinned
    // independently here — `(is_func_with_code, is_closure, promoted,
    // SpaceKind, is_member)`, by the call's target text where the kind
    // is `call`.
    // The per-shape tests below do not cover membership: emptying
    // `Call` or dropping `Sigil` from `StringLit` failed none of them.
    #[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"
            );
        });
        // By target: `defmodule` a class, `defstruct` a member, the three
        // method macros functions, the quoted `def` nothing (#310), and
        // the plain calls nothing.
        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}");
            }
        }
    }

    // The walk's promotion reads a `call`'s own target once, however
    // many rows gate on it — one keyword read per `call` — which only
    // the count can tell from one per row (#310, #1696). The two method
    // macros also climb for a `quote` (#310), reading each ancestor's
    // target once on an unmemoised chain; on the walk that climb is a
    // memoised fold. The fixture's nesting makes that climb exactly one
    // read per `def`: the `defmodule` above it.
    #[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));
        // Reading both rows in turn would be 2 × calls + the climbs.
        assert_eq!(call_keyword_reads::observed() - before, calls + defs);
    }

    // Every `call` in the fixture, with what the two text-gated rows
    // make of it: the `defmodule` is a container, the `def` a function
    // opener, the `def` inside `quote` neither — the chain says so, and
    // the same bytes outside a `quote` say the opposite. `IO.puts` is a
    // remote call with no keyword target, `quote` itself is neither, and
    // the `f(x)` head of `def f(x)` is a plain call nested in the `def`.
    #[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),
            ]
        );
    }

    // The same `def` bytes with no `quote` ancestor: the row answers
    // from the chain, not from the text alone.
    #[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);
    }

    // The anonymous function opens a space and is a closure; the `def`
    // opens a space and is not; `Call` is in both space rows without
    // being named twice in either.
    #[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]
        );
    }

    // The `Guard` row's owner is every `when` operator by kind, and its
    // `when` token pays only in a guard position: a typespec's `when a:
    // var` is the same operator and token, told apart by position alone
    // (#1454). The consumers read the row at the token, so only this
    // pins the owner side — and that the two projections sit on the
    // same nodes, the operator owning and its token paying.
    #[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());
            }
            // Asked of every node, so a payer the row gained would show.
            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()
                );
            }
        });
        // Every `when` operator owns — the typespec's included, since the
        // kind alone cannot tell it apart — and `y > 0` owns nothing.
        assert_eq!(
            owned,
            [
                "f(a) :: a when a: var",
                "f(x) when is_integer(x)",
                "y when y > 0"
            ]
        );
        // Three `when` tokens; the typespec's, first, pays nothing, and
        // nothing else pays.
        assert_eq!(tokens.len(), 3);
        assert_eq!(paid, tokens[1..]);
    }

    /// The parents an `escape_sequence` can have, as the grammar's
    /// `node-types.json` declares them: the five quoted literals, each of
    /// which owns every row it spans. The root crate's `loc` arm credits
    /// a spanning escape's interior rows on that basis with no parent
    /// gate (#1816), so a grammar bump that gives the leaf a sixth parent
    /// — one that is not a literal, or a wrapper between the leaf and
    /// its literal — must change this list and that arm together. A
    /// parent can also reach the leaf through a supertype whose
    /// `subtypes` list it, so the leaf's supertypes are collected first
    /// and a parent naming any of them counts; today none does.
    // test-lang-gates: hand-written(elixir) — reads the grammar crate's
    //     `NODE_TYPES`, which exists only under the `elixir` feature
    #[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()
        );
    }
}