Skip to main content

big_code_analysis/
ops.rs

1// Per-language metric and AST modules deliberately consume the macro-
2// generated tree-sitter token enums via `use crate::*` and `use Foo::*`
3// inside match expressions — explicit imports would list dozens of
4// variants per arm and obscure the per-language token sets that are the
5// point of these files. Allowed at the module level rather than per
6// function so the per-language impl blocks stay readable.
7#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
8
9use std::borrow::Cow;
10
11use crate::checker::Checker;
12use crate::error::MetricsError;
13use crate::getter::Getter;
14use crate::node::{Ancestors, Node};
15use crate::spaces::{SpaceKind, line_span, push_children};
16
17use crate::halstead::{Halstead, HalsteadMaps};
18
19use crate::traits::ParserTrait;
20
21/// All operands and operators of a space.
22#[derive(Debug, Clone)]
23pub struct Ops {
24    /// The name of a function space.
25    ///
26    /// For the top-level (file-level) `Ops` the value is whatever
27    /// `Source::name` the caller supplied to the [`crate::Ast::ops`]
28    /// seam — `Some` or `None`.
29    ///
30    /// For nested spaces, `None` means an error occurred in parsing the
31    /// name of the function space from the AST.
32    pub name: Option<String>,
33    /// `true` when [`Ops::name`] was produced by lossy conversion (the
34    /// original path contained non-UTF-8 bytes and was rendered using
35    /// U+FFFD replacement characters). The explicit-name
36    /// [`crate::Ast::ops`] seam never sets it, since a caller-supplied
37    /// `String` name is UTF-8 by construction, so it is always `false`
38    /// in current code paths. Retained as a wire field for forward
39    /// compatibility; skipped from JSON output when `false` so existing
40    /// schemas keep their shape.
41    pub name_was_lossy: bool,
42    /// The first line of a function space.
43    pub start_line: usize,
44    /// The last line of a function space.
45    pub end_line: usize,
46    /// The space kind.
47    pub kind: SpaceKind,
48    /// All subspaces contained in a function space.
49    pub spaces: Vec<Ops>,
50    /// The **distinct** operands of a space — the deduplicated Halstead
51    /// operand vocabulary (`n2`), one entry per unique operand, not every
52    /// occurrence. Sorted in byte-lexicographic order, so the same input
53    /// always yields the same sequence (#1091).
54    pub operands: Vec<String>,
55    /// The **distinct** operators of a space — the deduplicated Halstead
56    /// operator vocabulary (`n1`), one entry per unique operator, not
57    /// every occurrence. Sorted in byte-lexicographic order, so the same
58    /// input always yields the same sequence (#1091).
59    pub operators: Vec<String>,
60}
61
62// Space nesting is caller-controlled, so the compiler-generated `Drop`
63// glue would recurse once per level and abort the process on a deep tree
64// (#1056). See [`crate::recursion`].
65crate::recursion::impl_iterative_drop!(Ops, spaces);
66
67impl Ops {
68    /// Project this tree into its [`crate::wire::Ops`] form — the
69    /// plain, `Deserialize`-capable record that defines the serialized
70    /// shape.
71    #[must_use]
72    pub fn to_wire(&self) -> crate::wire::Ops {
73        crate::wire::Ops::from(self)
74    }
75
76    fn new<'a, T: Getter>(
77        node: &Node<'a>,
78        code: &[u8],
79        ancestors: Ancestors<'a, '_>,
80        kind: SpaceKind,
81    ) -> Self {
82        let (start_position, end_position) = line_span(node, kind);
83        // The top-level Unit's name is overwritten by `ops_inner` with the
84        // caller-supplied name before returning, so computing it here is
85        // wasted work. Non-top-level Unit spaces have no resolvable name, so
86        // leaving `None` matches the documented "could not be resolved"
87        // semantics rather than inventing the `<anonymous>` placeholder the
88        // default getter returns. Other kinds keep the AST-derived name.
89        // Mirrors the `SpaceKind::Unit` handling in `FuncSpace::new`.
90        let name = (kind != SpaceKind::Unit)
91            .then(|| T::get_func_space_name(node, code, ancestors).map(str::to_owned))
92            .flatten();
93        Self {
94            name,
95            name_was_lossy: false,
96            spaces: Vec::new(),
97            kind,
98            start_line: start_position,
99            end_line: end_position,
100            operators: Vec::new(),
101            operands: Vec::new(),
102        }
103    }
104}
105
106#[derive(Debug, Clone)]
107struct State<'a> {
108    ops: Ops,
109    halstead_maps: HalsteadMaps<'a>,
110}
111
112/// Pushes a synthetic `Unit` root onto the state stack when the grammar
113/// hands us a non-`Unit` root.
114///
115/// Mirrors [`crate::spaces::push_synthetic_unit_root`] on the metrics
116/// seam: some grammars (e.g. tree-sitter-lua / tree-sitter-mozcpp on
117/// unparseable input) return an `ERROR` root that is not classified as a
118/// function space, so without this push the walk would never open a
119/// frame and `ops_inner` would return [`MetricsError::EmptyRoot`] for an
120/// input where `metrics()` succeeds (issue #789). A `Unit` root needs no
121/// wrapper, so nothing is pushed in that case.
122fn push_synthetic_unit_root<T: ParserTrait>(
123    state_stack: &mut Vec<State>,
124    node: &Node,
125    code: &[u8],
126) {
127    // `Ancestors::unknown()`: `node` is the tree root here, so it has
128    // no ancestors to hand over either way.
129    if T::Getter::get_space_kind_with_code(node, code, Ancestors::unknown()) != SpaceKind::Unit {
130        state_stack.push(State {
131            ops: Ops::new::<T::Getter>(node, code, Ancestors::unknown(), SpaceKind::Unit),
132            halstead_maps: HalsteadMaps::new(),
133        });
134    }
135}
136
137// Space-kind classifications `ops_inner` has performed on this thread.
138//
139// The classification only ever reaches `Ops::new`, so running it on a
140// node that opens no space is work thrown away — and nothing about the
141// walk's *output* can tell the two apart. The counter is the
142// observable: it reads one per space after the lookup was moved inside
143// the `func_space` branch, and one per *node* before, which is what
144// makes hoisting it back out a test failure rather than a silent
145// regression (#1110).
146crate::observation::counter!(space_kind_lookups);
147
148/// Classifies a node that is about to open a function space.
149///
150/// Classification happens after the decision that a space opens, the
151/// same way [`crate::spaces::compute`]'s `open_func_space` does it
152/// (#522), and through the same source-aware classifier, so a space
153/// both seams open carries the same [`SpaceKind`] in either walk.
154/// The `_with_code` variant is what lets Elixir's macro-shaped
155/// `defmodule` / `def` declarations — plain `Call` nodes distinguished
156/// only by their target identifier text — come back as `Class` /
157/// `Function` rather than `Unknown` (#275, #1130).
158///
159/// The lookup is a per-language `match` on the node's kind for most
160/// grammars, but C#'s reaches a child scan for a bodied indexer or
161/// property and Elixir's reads the `Call` target text and scans the
162/// ancestor chain for an enclosing `quote` block, so it is not free on
163/// every node either.
164fn classify_space_kind<'a, T: ParserTrait>(
165    node: &Node<'a>,
166    code: &[u8],
167    ancestors: Ancestors<'a, '_>,
168) -> SpaceKind {
169    space_kind_lookups::record();
170    T::Getter::get_space_kind_with_code(node, code, ancestors)
171}
172
173/// Render a space's vocabulary: byte-lexicographically ordered, one
174/// owned `String` per distinct entry.
175///
176/// # Order
177///
178/// `HashMap`'s hasher is randomly seeded per instance, so key order
179/// differs between two runs — and even between two parses in one
180/// process. Without a canonical order the same input renders and
181/// serializes differently every time, which makes `bca ops` output
182/// undiffable and unusable as a cache key (#1091).
183///
184/// Byte-lexicographic, not first-appearance, order: `finalize` merges
185/// a child space's maps into its parent, so an insertion-ordered map
186/// would give the parent "what it saw directly, then whatever each
187/// child contributed" — a walk artifact that shifts when nesting
188/// changes. Sorting is also stable across platforms and hasher
189/// versions, which insertion order via a different map type is not.
190///
191/// # Why the sort runs before the `String`s exist
192///
193/// Every ancestor of a space re-renders that space's whole vocabulary:
194/// `finalize` merges each child's Halstead maps into its parent, so a
195/// parent's key set is a superset of every descendant's and an entry
196/// nested `D` spaces deep is rendered `D + 1` times. Sorting the
197/// borrowed keys first makes each swap a fat pointer rather than a
198/// 24-byte `String`, and — because the `String`s are then allocated in
199/// output order — it hands every later pass over them (the wire
200/// projection, serialization, the `dump_ops` tree) a heap laid out in
201/// the order it reads. Issue #1110 measured both effects.
202///
203/// # Non-UTF-8 keys
204///
205/// Tree-sitter sources are expected to be valid UTF-8; non-UTF-8 bytes
206/// are replaced with the Unicode replacement character to keep the entry
207/// visible (rather than silently dropping it or using a sentinel string
208/// that could collide with a real identifier). That rendering is not
209/// order-preserving — `b"\xffA"` sorts after `"\u{fffd}B"` by raw bytes
210/// and before it once both are rendered — so a vocabulary that actually
211/// lost bytes is re-sorted on the rendered text, which is the order the
212/// pre-#1110 render-then-sort code produced. Valid UTF-8, which is every
213/// key in practice, takes the single sort.
214fn sorted_vocabulary(mut keys: Vec<&[u8]>) -> Vec<String> {
215    keys.sort_unstable();
216    let mut lossy = false;
217    let mut rendered: Vec<String> = keys
218        .into_iter()
219        .map(|key| match String::from_utf8_lossy(key) {
220            Cow::Borrowed(text) => text.to_owned(),
221            Cow::Owned(text) => {
222                lossy = true;
223                text
224            }
225        })
226        .collect();
227    if lossy {
228        rendered.sort_unstable();
229    }
230    rendered
231}
232
233fn compute_operators_and_operands<T: ParserTrait>(state: &mut State) {
234    let maps = &state.halstead_maps;
235
236    // Primitive-type operators live in a second map (keyed by text rather
237    // than by token id), so the operator vocabulary is the concatenation
238    // of both key sets.
239    let operators = maps
240        .operators
241        .keys()
242        .map(|k| T::Getter::get_operator_id_as_str(*k).as_bytes())
243        .chain(maps.primitive_operators.keys().copied())
244        .collect();
245
246    state.ops.operators = sorted_vocabulary(operators);
247    state.ops.operands = sorted_vocabulary(maps.operands.keys().copied().collect());
248}
249
250/// Close up to `diff_level` open spaces, folding each into its parent.
251///
252/// Only the states this pops get their vocabularies computed. The
253/// bottom state is never popped here, so the root's vocabulary is built
254/// once by [`ops_inner`] after the final drain — computing it on every
255/// call would rebuild (and, since #1091, re-sort) the whole file's
256/// vocabulary once per level-drop in the walk, and every result but the
257/// last would be overwritten.
258fn finalize<T: ParserTrait>(state_stack: &mut Vec<State>, diff_level: usize) {
259    for _ in 0..diff_level {
260        if state_stack.len() < 2 {
261            break;
262        }
263        let mut state = state_stack
264            .pop()
265            .expect("state_stack verified to have len >= 2");
266        let last_state = state_stack
267            .last_mut()
268            .expect("state_stack verified to have len >= 1 after pop");
269
270        // Populate the child's ops from its HalsteadMaps before
271        // recording it as a sub-space of the parent.
272        compute_operators_and_operands::<T>(&mut state);
273
274        // Merge child's Halstead maps into parent and record child space.
275        last_state.halstead_maps.merge(&state.halstead_maps);
276        last_state.ops.spaces.push(state.ops);
277    }
278}
279
280/// Context the ops walk carries down the tree alongside each node.
281///
282/// A named pair rather than a `(usize, usize)`: the two counts advance
283/// on different events and swapping them is silent — `level` only moves
284/// at space boundaries while `depth` counts every AST step. Mirrors
285/// [`crate::spaces::compute`]'s `Walk`, minus the comment flag this walk
286/// has no use for.
287#[derive(Clone, Copy)]
288struct Walk {
289    /// Nesting level, used to close op-spaces on the way back up.
290    level: usize,
291    /// AST depth — the number of ancestors this node has, so the root
292    /// sits at `0`. Indexes the ancestor chain the walk maintains.
293    depth: usize,
294}
295
296/// Explicit-name core of the operator/operand walk backing the
297/// [`crate::Ast::ops`] `Source`-based seam. The top-level [`Ops::name`]
298/// is whatever the caller passes in `name`; `name_was_lossy` is left at
299/// its `false` default because an explicit `String` name is never lossy.
300/// Mirrors [`crate::spaces::metrics_inner`].
301pub(crate) fn ops_inner<T: ParserTrait>(
302    parser: &T,
303    name: Option<String>,
304) -> Result<Ops, MetricsError> {
305    let code = parser.code();
306    let node = parser.root();
307    let mut cursor = node.cursor();
308    let mut stack = Vec::new();
309    // Ancestor chain of the node currently being visited, root first,
310    // maintained by the same truncate/push rule as
311    // `spaces::compute::metrics_inner` (#1084).
312    let mut chain: Vec<Node<'_>> = Vec::new();
313    let mut state_stack: Vec<State> = Vec::new();
314    let mut last_level = 0;
315
316    // Mirror `metrics_inner`: wrap a non-`Unit` (e.g. `ERROR`) root in a
317    // synthetic `Unit` frame so the walk always has a frame to populate.
318    // Without this, an `ERROR`-root parse drains the state stack and
319    // `ops_inner` returns `EmptyRoot` for inputs where `metrics()`
320    // succeeds (issue #789).
321    push_synthetic_unit_root::<T>(&mut state_stack, &node, code);
322
323    stack.push((node, Walk { level: 0, depth: 0 }));
324
325    while let Some((node, Walk { level, depth })) = stack.pop() {
326        chain.truncate(depth);
327
328        if level < last_level {
329            finalize::<T>(&mut state_stack, last_level - level);
330            last_level = level;
331        }
332
333        let ancestors = Ancestors::checked(&chain, &node);
334
335        // Same predicate `spaces::compute::metrics_inner` opens on, so
336        // the two walks agree on which nodes become spaces. The
337        // byte-less `is_func || is_func_space` this replaced could not
338        // see Elixir's macro-shaped declarations, which are `Call`
339        // nodes identified by their target text, so `bca ops` opened no
340        // space for a `defmodule` / `def` / `defp` / `defmacro` — only
341        // for `Source` and an explicit `fn … -> … end` (#1130).
342        let func_space = T::Checker::promotes_to_func_space_with_code(&node, code, ancestors);
343
344        let new_level = if func_space {
345            let kind = classify_space_kind::<T>(&node, code, ancestors);
346            let state = State {
347                ops: Ops::new::<T::Getter>(&node, code, ancestors, kind),
348                halstead_maps: HalsteadMaps::new(),
349            };
350            state_stack.push(state);
351            last_level = level + 1;
352            last_level
353        } else {
354            level
355        };
356
357        if let Some(state) = state_stack.last_mut() {
358            T::Halstead::compute(&node, code, ancestors, &mut state.halstead_maps);
359        }
360
361        chain.push(node);
362
363        // Shared with `metrics_inner` (issue #969): `push_children` is
364        // State-independent — it only moves the cursor over child nodes —
365        // so unlike the local `finalize` / `push_synthetic_unit_root`
366        // mirrors (which differ by `State` payload) it is reused directly
367        // rather than duplicated. The source-order-then-reverse ordering
368        // it encapsulates is load-bearing for suppression attribution.
369        // The returned child slice is only useful to `metrics_inner`,
370        // which seeds their cognitive nesting; `ops` just walks them.
371        push_children(
372            &mut cursor,
373            &node,
374            Walk {
375                level: new_level,
376                depth: depth + 1,
377            },
378            &mut stack,
379        );
380    }
381
382    finalize::<T>(&mut state_stack, usize::MAX);
383
384    // Reserved error path: `MetricsError::EmptyRoot` is unreachable
385    // today because the synthetic Unit push above (and every supported
386    // language's root being recognised as a `func_space`) keeps the
387    // state stack non-empty for every input, including ERROR-root,
388    // empty, whitespace-only, and comment-only sources — matching
389    // `metrics_inner`. The `ok_or` is retained so a future walker change
390    // that legitimately drains the stack surfaces a distinct error
391    // variant rather than a bare `None`. See `MetricsError::EmptyRoot`
392    // for the matching variant doc.
393    let mut state = state_stack.pop().ok_or(MetricsError::EmptyRoot)?;
394    // The root is the one state `finalize` never pops, so its vocabulary
395    // is built here — once, from the fully-merged maps.
396    compute_operators_and_operands::<T>(&mut state);
397    state.ops.name = name;
398    Ok(state.ops)
399}
400
401#[cfg(test)]
402#[allow(
403    clippy::float_cmp,
404    clippy::cast_precision_loss,
405    clippy::cast_possible_truncation,
406    clippy::cast_sign_loss,
407    clippy::similar_names,
408    clippy::doc_markdown,
409    clippy::needless_raw_string_hashes,
410    clippy::too_many_lines
411)]
412mod tests {
413    use super::Ops;
414    use crate::{Ast, LANG, Source};
415
416    #[inline]
417    fn check_ops(
418        lang: LANG,
419        source: &str,
420        file: &str,
421        correct_operators: &mut [&str],
422        correct_operands: &mut [&str],
423    ) {
424        let mut trimmed_bytes = source.trim_end().trim_matches('\n').as_bytes().to_vec();
425        trimmed_bytes.push(b'\n');
426        let ops = Ast::parse(Source::new(lang, &trimmed_bytes).with_name(Some(file.to_owned())))
427            .expect("language feature enabled")
428            .ops()
429            .expect("ops walk must yield a top-level Ops");
430
431        let operators_str: Vec<&str> = ops.operators.iter().map(AsRef::as_ref).collect();
432        let operands_str: Vec<&str> = ops.operands.iter().map(AsRef::as_ref).collect();
433
434        // Only the *expectations* are sorted here: `Ops` is documented to
435        // come back byte-lexicographically ordered (#1091), so comparing
436        // against a sorted expectation without re-sorting the actual value
437        // makes every `check_ops` caller an ordering regression test for
438        // its language.
439        correct_operators.sort_unstable();
440        assert_eq!(&operators_str[..], correct_operators);
441
442        correct_operands.sort_unstable();
443        assert_eq!(&operands_str[..], correct_operands);
444    }
445
446    #[test]
447    fn python_ops() {
448        check_ops(
449            LANG::Python,
450            "if True:
451                 a = 1 + 2",
452            "foo.py",
453            &mut ["if", "=", "+"],
454            &mut ["True", "a", "1", "2"],
455        );
456    }
457
458    #[test]
459    fn perl_pattern_operations_render_as_source_spellings() {
460        // #1314 classifies `s///` and `tr///` as Halstead operators.
461        // They are *named* nodes rather than punctuation tokens, so the
462        // `get_operator!` macro's fallback would render each kind's own
463        // name — `substitution_pattern_s`, `transliteration_tr_or_y` —
464        // into `bca ops`, which reads as a bug rather than as Perl.
465        // `PerlCode::get_operator_id_as_str` is hand-written to map
466        // them, and this is what pins that mapping: the counts alone
467        // cannot see it.
468        //
469        // `y///` is a synonym of `tr///` and shares one kind, so the
470        // two source spellings collapse to a single `tr///` entry —
471        // asserted here by the *absence* of a `y///` row in an
472        // exhaustive expectation, not by a negative assertion.
473        //
474        // The trailing `/pat/` keeps a pattern *value* in the fixture,
475        // so the test also shows the split: the operation spellings are
476        // operators while the value is an operand.
477        check_ops(
478            LANG::Perl,
479            "$s =~ s/a/b/;\n$s =~ tr/c/d/;\n$s =~ y/e/f/;\n$t = /pat/;",
480            "foo.pl",
481            &mut ["$", ";", "=", "=~", "s///", "tr///"],
482            &mut ["$s", "$t", "/pat/"],
483        );
484    }
485
486    #[test]
487    fn python_function_ops() {
488        check_ops(
489            LANG::Python,
490            "def foo():
491                 def bar():
492                     def toto():
493                        a = 1 + 1
494                     b = 2 + a
495                 c = 3 + 3",
496            "foo.py",
497            &mut ["def", "=", "+"],
498            &mut ["foo", "bar", "toto", "a", "b", "c", "1", "2", "3"],
499        );
500    }
501
502    #[test]
503    fn cpp_ops() {
504        check_ops(
505            LANG::Cpp,
506            "int a, b, c;
507             float avg;
508             avg = (a + b + c) / 3;",
509            "foo.c",
510            &mut ["int", "float", "()", "=", "+", "/", ",", ";"],
511            &mut ["a", "b", "c", "avg", "3"],
512        );
513    }
514
515    #[test]
516    fn cpp_function_ops() {
517        check_ops(
518            LANG::Cpp,
519            "main()
520            {
521              int a, b, c, avg;
522              scanf(\"%d %d %d\", &a, &b, &c);
523              avg = (a + b + c) / 3;
524              printf(\"avg = %d\", avg);
525            }",
526            "foo.c",
527            &mut ["()", "{}", "int", "&", "=", "+", "/", ",", ";"],
528            &mut [
529                "main",
530                "a",
531                "b",
532                "c",
533                "avg",
534                "scanf",
535                "\"%d %d %d\"",
536                "3",
537                "printf",
538                "\"avg = %d\"",
539            ],
540        );
541    }
542
543    #[test]
544    fn rust_ops() {
545        check_ops(
546            LANG::Rust,
547            "let: usize a = 5; let b: f32 = 7.0; let c: i32 = 3;",
548            "foo.rs",
549            &mut ["let", "usize", "=", ";", "f32", "i32"],
550            &mut ["a", "b", "c", "5", "7.0", "3"],
551        );
552    }
553
554    #[test]
555    fn rust_function_ops() {
556        check_ops(
557            LANG::Rust,
558            "fn main() {
559              let a = 5; let b = 5; let c = 5;
560              let avg = (a + b + c) / 3;
561              println!(\"{}\", avg);
562            }",
563            "foo.rs",
564            &mut ["fn", "()", "{}", "let", "=", "+", "/", ";", "!", ","],
565            &mut ["main", "a", "b", "c", "avg", "5", "3", "println", "\"{}\""],
566        );
567    }
568
569    #[test]
570    fn javascript_ops() {
571        check_ops(
572            LANG::Javascript,
573            "var a, b, c, avg;
574             let x = 1;
575             a = 5; b = 5; c = 5;
576             avg = (a + b + c) / 3;
577             console.log(\"{}\", avg);",
578            "foo.js",
579            &mut ["()", "var", "let", "=", "+", "/", ",", ".", ";"],
580            &mut [
581                "a", "b", "c", "avg", "x", "1", "3", "5", "console", "log", "\"{}\"",
582            ],
583        );
584    }
585
586    #[test]
587    fn javascript_function_ops() {
588        check_ops(
589            LANG::Javascript,
590            "function main() {
591              var a, b, c, avg;
592              let x = 1;
593              a = 5; b = 5; c = 5;
594              avg = (a + b + c) / 3;
595              console.log(\"{}\", avg);
596            }",
597            "foo.js",
598            &mut [
599                "function", "()", "{}", "var", "let", "=", "+", "/", ",", ".", ";",
600            ],
601            &mut [
602                "main", "a", "b", "c", "avg", "x", "1", "3", "5", "console", "log", "\"{}\"",
603            ],
604        );
605    }
606
607    #[test]
608    fn mozjs_ops() {
609        check_ops(
610            LANG::Mozjs,
611            "var a, b, c, avg;
612             let x = 1;
613             a = 5; b = 5; c = 5;
614             avg = (a + b + c) / 3;
615             console.log(\"{}\", avg);",
616            "foo.js",
617            &mut ["()", "var", "let", "=", "+", "/", ",", ".", ";"],
618            &mut [
619                "a", "b", "c", "avg", "x", "1", "3", "5", "console", "log", "\"{}\"",
620            ],
621        );
622    }
623
624    #[test]
625    fn mozjs_function_ops() {
626        check_ops(
627            LANG::Mozjs,
628            "function main() {
629              var a, b, c, avg;
630              let x = 1;
631              a = 5; b = 5; c = 5;
632              avg = (a + b + c) / 3;
633              console.log(\"{}\", avg);
634            }",
635            "foo.js",
636            &mut [
637                "function", "()", "{}", "var", "let", "=", "+", "/", ",", ".", ";",
638            ],
639            &mut [
640                "main", "a", "b", "c", "avg", "x", "1", "3", "5", "console", "log", "\"{}\"",
641            ],
642        );
643    }
644
645    #[test]
646    fn typescript_ops() {
647        // Issue #1261: the `: string` annotation counts exactly once,
648        // as the text-keyed `string` operator (PredefinedType wrapper)
649        // — symmetric with `: number` / `: boolean`. Under #313 its
650        // `String2` child also emitted a `"string"` operand, so one
651        // source token tallied twice.
652        check_ops(
653            LANG::Typescript,
654            "var a, b, c, avg;
655             let age: number = 32;
656             let name: string = \"John\"; let isUpdated: boolean = true;
657             a = 5; b = 5; c = 5;
658             avg = (a + b + c) / 3;
659             console.log(\"{}\", avg);",
660            "foo.ts",
661            &mut [
662                "()", "var", "let", "string", "number", "boolean", ":", "=", "+", "/", ",", ".",
663                ";",
664            ],
665            &mut [
666                "a",
667                "b",
668                "c",
669                "avg",
670                "age",
671                "name",
672                "isUpdated",
673                "32",
674                "\"John\"",
675                "true",
676                "3",
677                "5",
678                "console",
679                "log",
680                "\"{}\"",
681            ],
682        );
683    }
684
685    #[test]
686    fn typescript_function_ops() {
687        // Issue #1261: see `typescript_ops` — the `string` type keyword
688        // contributes only the primitive-typed operator, never a
689        // `"string"` operand.
690        check_ops(
691            LANG::Typescript,
692            "function main() {
693              var a, b, c, avg;
694              let age: number = 32;
695              let name: string = \"John\"; let isUpdated: boolean = true;
696              a = 5; b = 5; c = 5;
697              avg = (a + b + c) / 3;
698              console.log(\"{}\", avg);
699            }",
700            "foo.ts",
701            &mut [
702                "function", "()", "{}", "var", "let", "string", "number", "boolean", ":", "=", "+",
703                "/", ",", ".", ";",
704            ],
705            &mut [
706                "main",
707                "a",
708                "b",
709                "c",
710                "avg",
711                "age",
712                "name",
713                "isUpdated",
714                "32",
715                "\"John\"",
716                "true",
717                "3",
718                "5",
719                "console",
720                "log",
721                "\"{}\"",
722            ],
723        );
724    }
725
726    #[test]
727    fn tsx_ops() {
728        // Issue #1261: TSX exposes the `: string` type-keyword child as
729        // `String3` (vs. TS's `String2`); like TS, the keyword counts
730        // only as the `string` operator, never as an operand.
731        check_ops(
732            LANG::Tsx,
733            "var a, b, c, avg;
734             let age: number = 32;
735             let name: string = \"John\"; let isUpdated: boolean = true;
736             a = 5; b = 5; c = 5;
737             avg = (a + b + c) / 3;
738             console.log(\"{}\", avg);",
739            "foo.ts",
740            &mut [
741                "()", "var", "let", "string", "number", "boolean", ":", "=", "+", "/", ",", ".",
742                ";",
743            ],
744            &mut [
745                "a",
746                "b",
747                "c",
748                "avg",
749                "age",
750                "name",
751                "isUpdated",
752                "32",
753                "\"John\"",
754                "true",
755                "3",
756                "5",
757                "console",
758                "log",
759                "\"{}\"",
760            ],
761        );
762    }
763
764    #[test]
765    fn tsx_function_ops() {
766        // Issue #1261: see `tsx_ops` — TSX::String3 (type-keyword
767        // `string`) is an operator only, never an operand.
768        check_ops(
769            LANG::Tsx,
770            "function main() {
771              var a, b, c, avg;
772              let age: number = 32;
773              let name: string = \"John\"; let isUpdated: boolean = true;
774              a = 5; b = 5; c = 5;
775              avg = (a + b + c) / 3;
776              console.log(\"{}\", avg);
777            }",
778            "foo.ts",
779            &mut [
780                "function", "()", "{}", "var", "let", "string", "number", "boolean", ":", "=", "+",
781                "/", ",", ".", ";",
782            ],
783            &mut [
784                "main",
785                "a",
786                "b",
787                "c",
788                "avg",
789                "age",
790                "name",
791                "isUpdated",
792                "32",
793                "\"John\"",
794                "true",
795                "3",
796                "5",
797                "console",
798                "log",
799                "\"{}\"",
800            ],
801        );
802    }
803
804    // Issue #453: a `void` return type (a `predefined_type` wrapper over a
805    // `void` token) and an expression `void` (`void 0`) must collapse to a
806    // single distinct `"void"` operator. `check_ops` asserts the exact
807    // operator list, so a duplicate `"void"` — the pre-fix symptom, where
808    // the wrapper keyed `primitive_operators["void"]` and the inner token
809    // keyed `operators[Void]` — trips the assertion. This pins the lesson-4
810    // `n1 == dedupe(ops.operators)` invariant for the two `void` forms in
811    // one file.
812    #[test]
813    fn typescript_void_return_and_expression_single_operator_453() {
814        check_ops(
815            LANG::Typescript,
816            "function f(): void { return void 0; }",
817            "foo.ts",
818            &mut ["function", "()", "{}", ":", "void", "return", ";"],
819            &mut ["f", "0"],
820        );
821    }
822
823    #[test]
824    fn tsx_void_return_and_expression_single_operator_453() {
825        check_ops(
826            LANG::Tsx,
827            "function f(): void { return void 0; }",
828            "foo.tsx",
829            &mut ["function", "()", "{}", ":", "void", "return", ";"],
830            &mut ["f", "0"],
831        );
832    }
833
834    #[test]
835    fn java_ops() {
836        check_ops(
837            LANG::Java,
838            "public class Main {
839                public static void main(string args[]) {
840                      int a, b, c, avg;
841                      a = 5; b = 5; c = 5;
842                      avg = (a + b + c) / 3;
843                      MessageFormat.format(\"{0}\", avg);
844                    }
845                }",
846            "foo.java",
847            &mut [
848                "{}", "void", "()", "[]", ",", ".", ";", "int", "=", "+", "/",
849            ],
850            &mut [
851                "Main",
852                "main",
853                "args",
854                "a",
855                "b",
856                "c",
857                "avg",
858                "5",
859                "3",
860                "MessageFormat",
861                "format",
862                "\"{0}\"",
863            ],
864        );
865    }
866
867    #[test]
868    fn java_primitive_ops() {
869        check_ops(
870            LANG::Java,
871            "public class Prims {
872                byte a = 1;
873                short b = 2;
874                int c = 3;
875                long d = 4;
876                char e = 'x';
877                float f = 1.0f;
878                double g = 2.0;
879                boolean h = true;
880                boolean i = false;
881            }",
882            "foo.java",
883            // All 8 primitive-type keywords must appear as distinct operators.
884            // true/false appear as operands.
885            &mut [
886                "{}",
887                ";",
888                "=",
889                "byte",
890                "short",
891                "int",
892                "long",
893                "char",
894                "float",
895                "double",
896                "boolean_type",
897            ],
898            &mut [
899                "Prims", "a", "b", "c", "d", "e", "f", "g", "h", "i", "1", "2", "3", "4", "'x'",
900                "1.0f", "2.0", "true", "false",
901            ],
902        );
903    }
904
905    /// A `Unit` space must never carry the synthetic `<anonymous>`
906    /// placeholder that the default getter invents for nodes without a
907    /// `name` field. The public docs describe `None` as the
908    /// "name could not be resolved" state, and the metrics-side
909    /// `FuncSpace::new` already special-cases `SpaceKind::Unit` the same
910    /// way; this pins the `Ops::new` mirror so a regression to the old
911    /// `Some("<anonymous>")` initialisation fails here rather than only
912    /// surfacing for a (currently unreachable) non-top-level `Unit`
913    /// space, where `ops_inner`'s top-level override would not rescue it.
914    /// See issue #755.
915    #[cfg(feature = "rust")]
916    #[test]
917    fn unit_space_name_is_none_not_anonymous() {
918        use crate::getter::Getter;
919        use crate::node::Ancestors;
920        use crate::traits::ParserTrait;
921        use crate::{RustCode, RustParser, SpaceKind};
922
923        let code = b"fn f() {}\n";
924        let parser = RustParser::new(code.to_vec(), std::path::Path::new("foo.rs"), None);
925        let root = parser.root();
926        // The Rust `source_file` root is a `Unit` and has no `name`/`type`
927        // field, so the default getter would invent `<anonymous>`.
928        assert_eq!(SpaceKind::Unit, RustCode::get_space_kind(&root));
929
930        let ops = super::Ops::new::<RustCode>(&root, code, Ancestors::unknown(), SpaceKind::Unit);
931        assert_eq!(
932            ops.name, None,
933            "Unit space must preserve name = None, not invent <anonymous>"
934        );
935    }
936
937    /// Issue #789: an `ERROR`-root parse (here Lua partial input) where
938    /// `metrics()` succeeds must make `ops()` succeed too — the two seams
939    /// should agree. Before the synthetic-Unit-root mirror in `ops_inner`,
940    /// `ops()` returned `Err(MetricsError::EmptyRoot)` because the ERROR
941    /// root is not classified as a function space, so no frame was ever
942    /// pushed. This pins their agreement: both succeed, and the resulting
943    /// top-level `Ops` is a `Unit` whose name is the caller-supplied
944    /// `Source::name` (the intrinsic Unit name stays `None` per #755 until
945    /// `ops_inner` overrides the top-level name).
946    #[cfg(feature = "lua")]
947    #[test]
948    fn lua_error_root_ops_agrees_with_metrics_789() {
949        use crate::{MetricsOptions, SpaceKind};
950
951        // tree-sitter-lua surfaces an ERROR root for this partial input.
952        let src = b"function foo(x)\n  return x +\n".to_vec();
953        let name = "partial.lua".to_owned();
954
955        let ast = Ast::parse(Source::new(LANG::Lua, &src).with_name(Some(name.clone())))
956            .expect("lua feature enabled");
957
958        // metrics() must succeed (it already wrapped a synthetic Unit root).
959        let space = ast
960            .metrics(MetricsOptions::default())
961            .expect("metrics must yield a top-level space");
962        assert_eq!(space.kind, SpaceKind::Unit);
963
964        // ops() must now succeed in the same case rather than returning
965        // Err(EmptyRoot).
966        let ops = ast
967            .ops()
968            .expect("ops must agree with metrics and yield a top-level Ops");
969        assert_eq!(ops.kind, SpaceKind::Unit);
970        assert_eq!(
971            ops.name.as_deref(),
972            Some(name.as_str()),
973            "top-level Ops name is the caller-supplied Source::name"
974        );
975    }
976
977    /// Issue #790: `Ops::operands` / `Ops::operators` are the *distinct*
978    /// (deduplicated) Halstead operand/operator vocabularies (`n2` / `n1`),
979    /// not every occurrence. Pin the documented dedup semantics: each
980    /// vector's length equals its unique-element count. The fixture
981    /// repeats `+`, `;`, and `=` operators and the `a` operand so a
982    /// regression to non-deduplicated collection would make `len` exceed
983    /// the unique count.
984    #[cfg(feature = "rust")]
985    #[test]
986    fn ops_vocabularies_are_distinct_790() {
987        use std::collections::HashSet;
988
989        let src = b"fn main() { let a = 1 + 1; let b = a + a; }\n".to_vec();
990        let ops = Ast::parse(Source::new(LANG::Rust, &src).with_name(Some("foo.rs".to_owned())))
991            .expect("rust feature enabled")
992            .ops()
993            .expect("ops walk must yield a top-level Ops");
994
995        let unique_operators: HashSet<&String> = ops.operators.iter().collect();
996        assert_eq!(
997            ops.operators.len(),
998            unique_operators.len(),
999            "Ops::operators must be the distinct operator vocabulary (n1)"
1000        );
1001
1002        let unique_operands: HashSet<&String> = ops.operands.iter().collect();
1003        assert_eq!(
1004            ops.operands.len(),
1005            unique_operands.len(),
1006            "Ops::operands must be the distinct operand vocabulary (n2)"
1007        );
1008    }
1009
1010    /// Assert that every space in the tree carries sorted vocabularies,
1011    /// and return how many spaces were checked so a caller can prove the
1012    /// walk actually descended.
1013    ///
1014    /// The length floor is what keeps this from going quietly vacuous:
1015    /// `is_sorted` is trivially true for an empty or single-entry
1016    /// vector, so without it a fixture that stopped producing real
1017    /// vocabularies would keep passing while covering nothing.
1018    fn assert_sorted_spaces(ops: &Ops, lang: LANG) -> usize {
1019        /// Smallest vocabulary in which an ordering is observable.
1020        const MIN_OBSERVABLE: usize = 2;
1021
1022        let mut stack = vec![ops];
1023        let mut visited = 0;
1024
1025        while let Some(space) = stack.pop() {
1026            visited += 1;
1027            for (field, values) in [
1028                ("operators", &space.operators),
1029                ("operands", &space.operands),
1030            ] {
1031                assert!(
1032                    values.len() >= MIN_OBSERVABLE && values.is_sorted(),
1033                    "{lang:?} {field} of space {:?} (@{}) must hold at least \
1034                     {MIN_OBSERVABLE} entries and be sorted: {values:?}",
1035                    space.name,
1036                    space.start_line
1037                );
1038            }
1039            stack.extend(space.spaces.iter());
1040        }
1041
1042        visited
1043    }
1044
1045    /// Every space's vocabularies come back sorted, in every language.
1046    ///
1047    /// The operator vocabulary is the union of two maps — one keyed by
1048    /// token id, one keyed by text, which is where primitive types such
1049    /// as C++ `int` land — and sorting is what interleaves them rather
1050    /// than leaving the second concatenated onto the first (#1091). The
1051    /// `spans_both_maps` pair per case names one entry from each map, so
1052    /// a fixture that stopped exercising the text-keyed map fails here
1053    /// instead of silently narrowing the test's reach.
1054    #[test]
1055    fn ops_vocabularies_are_sorted_1091() {
1056        /// `(language, file name, source, (text-keyed operator,
1057        /// token-id-keyed operator that must sort after it))`.
1058        type Case = (
1059            LANG,
1060            &'static str,
1061            &'static str,
1062            (&'static str, &'static str),
1063        );
1064
1065        let cases: &[Case] = &[
1066            #[cfg(feature = "rust")]
1067            (
1068                LANG::Rust,
1069                "rust.rs",
1070                "fn zeta(quux: u32) -> u32 { let mid = quux + 1; \
1071                 let alpha = |beta: u32| beta * mid; alpha(mid) - quux }\n",
1072                ("u32", "|"),
1073            ),
1074            #[cfg(feature = "cpp")]
1075            (
1076                LANG::Cpp,
1077                "cpp.cpp",
1078                "int zeta(int quux) { double mid = quux + 1; \
1079                 char alpha = 'z'; return quux - mid + alpha; }\n",
1080                ("int", "return"),
1081            ),
1082            #[cfg(feature = "java")]
1083            (
1084                LANG::Java,
1085                "Java.java",
1086                "class Zeta { int quux(int mid) { long alpha = mid + 1; \
1087                 boolean beta = alpha > 2; return beta ? mid : 0; } }\n",
1088                ("long", "return"),
1089            ),
1090            #[cfg(feature = "python")]
1091            (
1092                LANG::Python,
1093                "python.py",
1094                "def zeta(quux):\n    mid = quux + 1\n    \
1095                 def alpha(beta):\n        return beta * mid\n    return alpha(mid) - quux\n",
1096                // Python has no primitive-type operators; both entries
1097                // come from the token-id map, so this pair only pins the
1098                // ordering, not the interleaving.
1099                ("def", "return"),
1100            ),
1101            #[cfg(feature = "typescript")]
1102            (
1103                LANG::Typescript,
1104                "ts.ts",
1105                "function zeta(quux: number): number { const mid: number = quux + 1; \
1106                 const alpha = (beta: number) => beta * mid; return alpha(mid) - quux; }\n",
1107                ("number", "return"),
1108            ),
1109        ];
1110
1111        for (lang, file, source, (from_text_map, sorts_after)) in cases {
1112            let ops = Ast::parse(
1113                Source::new(*lang, source.as_bytes()).with_name(Some((*file).to_owned())),
1114            )
1115            .expect("language feature enabled")
1116            .ops()
1117            .expect("ops walk must yield a top-level Ops");
1118
1119            let position = |needle: &str| {
1120                ops.operators
1121                    .iter()
1122                    .position(|op| op == needle)
1123                    .unwrap_or_else(|| {
1124                        panic!(
1125                            "{lang:?} operators must contain {needle:?}: {:?}",
1126                            ops.operators
1127                        )
1128                    })
1129            };
1130            assert!(
1131                position(from_text_map) < position(sorts_after),
1132                "{lang:?} must order {from_text_map:?} before {sorts_after:?}: {:?}",
1133                ops.operators
1134            );
1135
1136            assert!(
1137                assert_sorted_spaces(&ops, *lang) > 1,
1138                "{lang:?} sample must nest at least one sub-space"
1139            );
1140        }
1141    }
1142
1143    /// Two parses of the same bytes in one process must agree exactly.
1144    ///
1145    /// `RandomState` bumps its thread-local seed per instance, so the
1146    /// pre-fix code could — and did — order two `HashMap`s built from
1147    /// identical keys differently within a single run. This is the
1148    /// in-process form of the cross-run churn in #1091.
1149    #[test]
1150    #[cfg(feature = "rust")]
1151    fn ops_are_stable_across_repeated_parses_1091() {
1152        use std::fmt::Write as _;
1153
1154        // Enough distinct operands, in enough distinct spaces, that
1155        // agreement by coincidence is not a plausible explanation for a
1156        // pass.
1157        let mut src = String::new();
1158        for i in 0..40 {
1159            writeln!(src, "fn name{i}(arg{i}: u32) -> u32 {{ arg{i} + {i} }}")
1160                .expect("writing to a String cannot fail");
1161        }
1162
1163        let parse = || {
1164            Ast::parse(Source::new(LANG::Rust, src.as_bytes()).with_name(Some("foo.rs".to_owned())))
1165                .expect("rust feature enabled")
1166                .ops()
1167                .expect("ops walk must yield a top-level Ops")
1168        };
1169
1170        let (first, second) = (parse(), parse());
1171        assert!(
1172            first.operands.len() >= 40 && first.spaces.len() >= 40,
1173            "sample must have a wide vocabulary across many spaces, got {} operands \
1174             in {} spaces",
1175            first.operands.len(),
1176            first.spaces.len()
1177        );
1178        // `Ops` has no `PartialEq`, and the nested spaces are the half a
1179        // top-level vector comparison would miss, so compare the whole
1180        // serialized tree.
1181        let render =
1182            |ops: &Ops| serde_json::to_string(&ops.to_wire()).expect("wire Ops serializes to JSON");
1183        assert_eq!(render(&first), render(&second));
1184    }
1185
1186    /// A vocabulary that lost bytes is ordered by its *rendered* text.
1187    ///
1188    /// #1110 moved the sort ahead of the lossy UTF-8 rendering, which is
1189    /// only order-preserving while every key is valid UTF-8. Here it is
1190    /// not: the two string operands are `"\xffA"` and `"\u{fffd}B"`, so
1191    /// by raw bytes the first sorts *after* the second (`0xff` > `0xef`)
1192    /// and by rendered text — both start `U+FFFD`, then `A` before `B` —
1193    /// it sorts before. The rendered order is what the pre-#1110
1194    /// render-then-sort code produced and what `Ops` documents, so
1195    /// dropping the fallback re-sort flips this pair and fails here.
1196    #[test]
1197    #[cfg(feature = "rust")]
1198    fn ops_vocabulary_orders_lossy_entries_by_rendered_text_1110() {
1199        let mut src = b"fn f() { let a = \"".to_vec();
1200        src.push(0xff);
1201        src.extend_from_slice(b"A\"; let b = \"");
1202        src.extend_from_slice(&[0xef, 0xbf, 0xbd]);
1203        src.extend_from_slice(b"B\"; }\n");
1204
1205        let ops = Ast::parse(Source::new(LANG::Rust, &src).with_name(Some("foo.rs".to_owned())))
1206            .expect("rust feature enabled")
1207            .ops()
1208            .expect("ops walk must yield a top-level Ops");
1209
1210        let position = |needle: &str| {
1211            ops.operands
1212                .iter()
1213                .position(|operand| operand == needle)
1214                .unwrap_or_else(|| panic!("operands must contain {needle:?}: {:?}", ops.operands))
1215        };
1216        assert!(
1217            position("\"\u{fffd}A\"") < position("\"\u{fffd}B\""),
1218            "lossy entries must be ordered by rendered text, got {:?}",
1219            ops.operands
1220        );
1221        assert!(
1222            ops.operands.is_sorted(),
1223            "the whole vocabulary must be sorted as rendered, got {:?}",
1224            ops.operands
1225        );
1226    }
1227
1228    /// The walk classifies a space kind once per space, not once per node.
1229    ///
1230    /// Nothing in the output distinguishes the two: the classification
1231    /// only ever reaches `Ops::new`, so running it on every node produces
1232    /// the same tree and merely throws the extra answers away. #1110
1233    /// moved the call inside the `func_space` branch, mirroring
1234    /// `spaces::compute::open_func_space`; the counter is what makes
1235    /// hoisting it back out a failure. The node-count assertion is what
1236    /// makes the counts distinguishable — a fixture whose nodes and
1237    /// spaces were equal in number could not tell the two apart.
1238    #[test]
1239    // Gated on the language that guarantees a non-empty case list, so
1240    // the emptiness assertion below cannot fire on a minimal build.
1241    #[cfg(feature = "rust")]
1242    fn ops_classifies_space_kind_once_per_space_1110() {
1243        let cases: &[(LANG, &str, &str)] = &[
1244            #[cfg(feature = "rust")]
1245            (
1246                LANG::Rust,
1247                "foo.rs",
1248                "fn outer(a: u32) -> u32 { fn inner(b: u32) -> u32 { b + 1 } inner(a) * 2 }\n",
1249            ),
1250            #[cfg(feature = "python")]
1251            (
1252                LANG::Python,
1253                "foo.py",
1254                "def outer(a):\n    def inner(b):\n        return b + 1\n    return inner(a) * 2\n",
1255            ),
1256            #[cfg(feature = "cpp")]
1257            (
1258                LANG::Cpp,
1259                "foo.cpp",
1260                "struct S { int m(int a) { return a + 1; } }; int f(int b) { return b * 2; }\n",
1261            ),
1262            #[cfg(feature = "java")]
1263            (
1264                LANG::Java,
1265                "Foo.java",
1266                "class C { int m(int a) { return a + 1; } int n(int b) { return b * 2; } }\n",
1267            ),
1268            #[cfg(feature = "javascript")]
1269            (
1270                LANG::Javascript,
1271                "foo.js",
1272                "function outer(a) { function inner(b) { return b + 1; } return inner(a) * 2; }\n",
1273            ),
1274        ];
1275        crate::test_support::assert_fixtures_present(cases);
1276
1277        for (lang, file, source) in cases {
1278            let ast = crate::test_support::parse_named(*lang, file, source);
1279
1280            let before = super::space_kind_lookups::observed();
1281            let ops = ast.ops().expect("ops walk must yield a top-level Ops");
1282            let lookups = super::space_kind_lookups::observed() - before;
1283
1284            let mut spaces = 0;
1285            let mut stack = vec![&ops];
1286            while let Some(space) = stack.pop() {
1287                spaces += 1;
1288                stack.extend(space.spaces.iter());
1289            }
1290
1291            let mut nodes = 0;
1292            let mut cursor = vec![ast.as_tree_sitter().root_node()];
1293            while let Some(node) = cursor.pop() {
1294                nodes += 1;
1295                let mut walker = node.walk();
1296                cursor.extend(node.children(&mut walker));
1297            }
1298
1299            assert!(
1300                nodes > spaces * 4,
1301                "{lang:?} fixture must have many more nodes ({nodes}) than spaces ({spaces}) \
1302                 for the two counts to be distinguishable"
1303            );
1304            assert_eq!(
1305                lookups, spaces,
1306                "{lang:?} must classify once per space, not once per node ({nodes} nodes)"
1307            );
1308        }
1309    }
1310
1311    /// One flattened space: `(depth, kind, name, start_line, end_line)`.
1312    #[cfg(feature = "elixir")]
1313    type FlatSpace = (usize, crate::SpaceKind, String, usize, usize);
1314
1315    /// Flattens an `Ops` tree in preorder, so a test can pin the whole
1316    /// tree in one `assert_eq!` and see the surrounding spaces when one
1317    /// is wrong.
1318    ///
1319    /// `end_line` is carried as well as `start_line` because a change to
1320    /// the promote predicate can move a space's *extent* without moving
1321    /// its head — a `def` that swallows its sibling would keep the same
1322    /// start line.
1323    #[cfg(feature = "elixir")]
1324    fn flatten(ops: &Ops, depth: usize, out: &mut Vec<FlatSpace>) {
1325        out.push((
1326            depth,
1327            ops.kind,
1328            ops.name.clone().unwrap_or_else(|| "<none>".to_owned()),
1329            ops.start_line,
1330            ops.end_line,
1331        ));
1332        for child in &ops.spaces {
1333            flatten(child, depth + 1, out);
1334        }
1335    }
1336
1337    #[cfg(feature = "elixir")]
1338    fn elixir_ops_tree(source: &str) -> Vec<FlatSpace> {
1339        let ops = crate::test_support::parse_named(LANG::Elixir, "foo.ex", source)
1340            .ops()
1341            .expect("ops walk must yield a top-level Ops");
1342        let mut flat = Vec::new();
1343        flatten(&ops, 0, &mut flat);
1344        flat
1345    }
1346
1347    /// Issue #1130: Elixir's `defmodule` / `def` are `Call` nodes whose
1348    /// target identifier text spells the keyword, so only the
1349    /// source-aware promote predicate can recognise them. Before the
1350    /// fix `ops()` returned the bare file-level `Unit` for this input
1351    /// while `metrics()` returned the full module/function tree.
1352    #[cfg(feature = "elixir")]
1353    #[test]
1354    fn elixir_ops_opens_module_and_function_spaces_1130() {
1355        use crate::SpaceKind::{Class, Function, Unit};
1356
1357        assert_eq!(
1358            elixir_ops_tree("defmodule Foo do\n  def bar(x) do\n    x + 1\n  end\nend\n"),
1359            vec![
1360                (0, Unit, "foo.ex".to_owned(), 1, 5),
1361                (1, Class, "Foo".to_owned(), 1, 5),
1362                (2, Function, "bar".to_owned(), 2, 4),
1363            ],
1364        );
1365    }
1366
1367    /// An `AnonymousFunction` is the one Elixir space the byte-less
1368    /// predicate could already see, so this pins that the source-aware
1369    /// predicate did not lose it — and that it nests under the `def`
1370    /// space rather than being reparented to the file root.
1371    #[cfg(feature = "elixir")]
1372    #[test]
1373    fn elixir_ops_opens_anonymous_function_space() {
1374        use crate::SpaceKind::{Class, Function, Unit};
1375
1376        assert_eq!(
1377            elixir_ops_tree(
1378                "defmodule Foo do\n  def bar(list) do\n    \
1379                 Enum.map(list, fn x -> x * 2 end)\n  end\nend\n"
1380            ),
1381            vec![
1382                (0, Unit, "foo.ex".to_owned(), 1, 5),
1383                (1, Class, "Foo".to_owned(), 1, 5),
1384                (2, Function, "bar".to_owned(), 2, 4),
1385                (3, Function, "<anonymous>".to_owned(), 3, 3),
1386            ],
1387        );
1388    }
1389
1390    /// Issue #310: a `def` inside `quote do … end` is a code *template*
1391    /// emitted later by macro expansion, not a declaration of the
1392    /// enclosing module, so it opens no space. This is the case only the
1393    /// source-aware predicate can get right — the byte-less one never
1394    /// saw any `def` at all, so it was accidentally "correct" here while
1395    /// being wrong everywhere else.
1396    #[cfg(feature = "elixir")]
1397    #[test]
1398    fn elixir_ops_skips_def_inside_quote_block_310() {
1399        use crate::SpaceKind::{Class, Function, Unit};
1400
1401        // The quoted `def` heads line 4. Its name resolves to the
1402        // `<anonymous>` placeholder (the head is `unquote(name)`, not a
1403        // literal identifier), so the absence of a fourth entry — not a
1404        // name match — is what pins it out of the tree.
1405        assert_eq!(
1406            elixir_ops_tree(
1407                "defmodule Foo do\n  defmacro gen(name) do\n    quote do\n      \
1408                 def unquote(name)(x) do\n        x + 1\n      end\n    end\n  end\nend\n",
1409            ),
1410            vec![
1411                (0, Unit, "foo.ex".to_owned(), 1, 9),
1412                (1, Class, "Foo".to_owned(), 1, 9),
1413                (2, Function, "gen".to_owned(), 2, 8),
1414            ],
1415        );
1416    }
1417}