Skip to main content

fallow_extract/
inventory.rs

1//! Function inventory walker for `fallow coverage upload-inventory`.
2//!
3//! Emits one [`InventoryEntry`] per function (declaration, expression, arrow,
4//! method) whose name matches what `oxc-coverage-instrument` produces at
5//! instrument time. This is the **static side** of the three-state production
6//! coverage story: uploaded inventory minus runtime-seen functions equals
7//! `untracked`.
8//!
9//! # Naming contract
10//!
11//! The cloud stores function identity as
12//! `(filePath, functionName, lineNumber)`. This walker is responsible for the
13//! `functionName` and `lineNumber` parts of that contract. Anonymous functions
14//! are named `(anonymous_N)` where `N` is a file-scoped monotonic counter that
15//! starts at 0 and increments in pre-order AST traversal each time a function
16//! is entered without a resolvable explicit name. Name resolution precedence:
17//!
18//! 1. The function's own `id` (named `function foo() {}`, named function
19//!    expression `const x = function named() {}` -> "named",
20//!    `{ k: function own() {} }` -> "own"). This matches the instrumenter and
21//!    `Function.prototype.name`.
22//! 2. A parent name: from a `MethodDefinition` (accessors carry the
23//!    instrumenter's `get ` / `set ` label), an `ObjectProperty` key
24//!    (shorthand methods, accessors, and function-valued data properties), a
25//!    `VariableDeclarator` binding, a plain `=` assignment target
26//!    (`o.foo = () => {}` -> "foo", `x = () => {}` -> "x"), the binding of a
27//!    default value (`function f(cb = () => {})` -> "cb",
28//!    `const { a = () => {} } = o` -> "a"), or an anonymous `export default`
29//!    (-> "default").
30//!    A binding, key or assignment name is given only to a function or arrow
31//!    value, through parentheses; a class value takes none.
32//! 3. The callee of the call / `new` expression that the function is a direct
33//!    argument of (`arr.map(cb)` -> "map", `foo(cb)` -> "foo",
34//!    `new Promise(cb)` -> "Promise"). This matches `oxc-coverage-instrument`'s
35//!    opt-in `name_callback_arguments` (which `@fallow-cli/beacon` enables).
36//!    Only parentheses may be between the call and the function: an array
37//!    element, an object property or a `??` operand inside an argument takes
38//!    no callee name. An optional call on a callee that is not a member access
39//!    (`foo?.(cb)`) gives no callee name, because the instrumenter wraps that
40//!    callee in its optional-chain helper. `a.b?.(cb)` still gives "b".
41//!
42//! 4. `(anonymous_N)` with the current counter value; counter then increments.
43//!    Only genuinely unnamed functions reach this: an immediately-invoked
44//!    function expression, an arrow returned from another function, or a
45//!    computed non-string-key call.
46//!
47//! Each parent and callee name is keyed on the start of the function node, as
48//! in the instrumenter's `inferred_names`, so a name never reaches a nested
49//! function.
50//!
51//! Counter scope is per-file. Reference implementation:
52//! `oxc-coverage-instrument` `src/transform/names.rs` (`resolve_function_name`,
53//! `infer_name_for_value` and `callback_argument_name`).
54
55use std::path::Path;
56
57use oxc_allocator::Allocator;
58use oxc_ast::ast::*;
59use oxc_ast_visit::{Visit, walk};
60use oxc_parser::Parser;
61use oxc_semantic::ScopeFlags;
62use oxc_span::{SourceType, Span};
63use rustc_hash::FxHashMap;
64
65use crate::js_text::JsText;
66
67/// A single static-inventory entry for one function.
68///
69/// `name` is beacon-compatible (see the module docs for the naming rule).
70/// `line` is 1-based, matching the AST span start. The `start_column` /
71/// `end_line` / `end_column` fields carry the function-node span in the
72/// 1-indexed UTF-16 convention the cross-surface `FunctionIdentity` join key
73/// expects (see `fallow_cov_protocol::FunctionIdentity::start_column`). They
74/// are descriptive metadata: the join hash is `(file, name, line)` only, so
75/// column fidelity never affects the join, only display / same-line
76/// disambiguation.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct InventoryEntry {
79    /// Beacon-compatible function name.
80    pub name: String,
81    /// 1-based source line of the function declaration (node `span.start`).
82    pub line: u32,
83    /// 1-indexed UTF-16 column of the function node start.
84    pub start_column: u32,
85    /// 1-based source line where the function node ends.
86    pub end_line: u32,
87    /// 1-indexed UTF-16 column of the function node end.
88    pub end_column: u32,
89    /// Content digest of the function's full-span source slice
90    /// (`&source[span.start..span.end]`): first 8 bytes of SHA-256 as 16
91    /// lowercase hex characters, via `fallow_cov_protocol::source_hash_for`.
92    /// The slice is the canonical body bytes (signature line + body + closing
93    /// brace, no whitespace normalization), identical for `Function` and
94    /// `ArrowFunctionExpression`. Stable across line moves, so a
95    /// moved-but-unedited function keeps the same hash. `None` for a function
96    /// with more nested functions below it than the cap in `function_hash`,
97    /// the same rule that the complexity walk applies.
98    pub source_hash: Option<String>,
99    /// Whether the name was taken from the callee of the call this function is
100    /// passed to (`arr.map(cb)` -> `map`) instead of from a declaration, a
101    /// binding, or a property key. Lets a consumer describe the function as a
102    /// callback passed to that callee rather than as a declaration.
103    pub is_callback: bool,
104}
105
106/// Rolling state for [`InventoryVisitor::line_col_utf16`]: the last resolved
107/// offset's line index, clamped byte position, and 0-based UTF-16 column.
108/// `line_idx` starts at `usize::MAX` so the first query never matches.
109#[derive(Clone, Copy)]
110struct ColCache {
111    line_idx: usize,
112    byte_end: usize,
113    utf16_units: usize,
114}
115
116impl ColCache {
117    const EMPTY: Self = Self {
118        line_idx: usize::MAX,
119        byte_end: 0,
120        utf16_units: 0,
121    };
122}
123
124#[cfg(test)]
125thread_local! {
126    /// Source bytes that the column lookups encoded on this thread.
127    static UTF16_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
128}
129
130/// Return the bytes that the column lookups encoded on this thread since the
131/// last call.
132#[cfg(test)]
133fn take_utf16_bytes() -> usize {
134    UTF16_BYTES.with(|encoded| encoded.replace(0))
135}
136
137/// A function that the inventory walk is inside.
138struct OpenFunction {
139    /// Index of its entry in [`InventoryVisitor::entries`].
140    entry: usize,
141    span: Span,
142    /// Levels of nested functions below it so far.
143    height: u32,
144}
145
146/// A resolved function name plus how it was resolved.
147struct ResolvedName {
148    name: String,
149    /// `true` only when the name came from a call / `new` callee.
150    is_callback: bool,
151}
152
153impl ResolvedName {
154    const fn named(name: String) -> Self {
155        Self {
156            name,
157            is_callback: false,
158        }
159    }
160}
161
162/// Visitor that collects [`InventoryEntry`] values in file traversal order.
163struct InventoryVisitor<'a> {
164    source: &'a str,
165    line_offsets: &'a [u32],
166    entries: Vec<InventoryEntry>,
167    /// Column cursors for span starts and span ends. One shared cursor jumps
168    /// across the whole span for each nested function on one line.
169    start_cols: ColCache,
170    end_cols: ColCache,
171    /// Open functions. The hash is computed on leave, when the height is known.
172    open: Vec<OpenFunction>,
173    /// Names that a parent gives to a function or arrow (method key, variable
174    /// binding, property key, assignment target, default value binding),
175    /// keyed on the start of the function node, as in the instrumenter's
176    /// `inferred_names`. Only the function that starts at the key can take
177    /// the name, so a name never reaches a nested function.
178    inferred_names: FxHashMap<u32, String>,
179    /// Callee names for a function or arrow that is a direct call / `new`
180    /// argument, keyed on the start of the function node. Ranks below the own
181    /// name and the parent name.
182    callback_names: FxHashMap<u32, String>,
183    /// File-scoped monotonic counter for unnamed functions.
184    anonymous_counter: u32,
185}
186
187impl<'a> InventoryVisitor<'a> {
188    fn new(source: &'a str, line_offsets: &'a [u32]) -> Self {
189        Self {
190            source,
191            line_offsets,
192            entries: Vec::new(),
193            start_cols: ColCache::EMPTY,
194            end_cols: ColCache::EMPTY,
195            open: Vec::new(),
196            inferred_names: FxHashMap::default(),
197            callback_names: FxHashMap::default(),
198            anonymous_counter: 0,
199        }
200    }
201
202    /// Resolve a function's name and advance the counter.
203    ///
204    /// Mirrors `oxc-coverage-instrument`'s two-step flow: `resolve_function_name`
205    /// reads the current counter value for the anonymous-case name, and
206    /// `add_function` advances the counter unconditionally on every
207    /// instrumented function (named or not). We collapse both into one call.
208    ///
209    /// Name precedence, matching the instrumenter's `resolve_function_name`:
210    /// function's own `id` → parent name (method key, variable binding,
211    /// property key, assignment target, default value binding) → call/`new`
212    /// callee → counter. The own name comes first, as for
213    /// `Function.prototype.name`: `const f = function g() {}` gives `g`. Both
214    /// keyed names of the function are removed in all cases.
215    fn resolve_name(&mut self, start: u32, explicit: Option<&str>) -> ResolvedName {
216        let n = self.anonymous_counter;
217        self.anonymous_counter += 1;
218        let inferred = self.inferred_names.remove(&start);
219        let callee = self.callback_names.remove(&start);
220        if let Some(name) = explicit {
221            return ResolvedName::named(name.to_owned());
222        }
223        if let Some(inferred) = inferred {
224            return ResolvedName::named(inferred);
225        }
226        if let Some(callee) = callee {
227            return ResolvedName {
228                name: callee,
229                is_callback: true,
230            };
231        }
232        ResolvedName::named(format!("(anonymous_{n})"))
233    }
234
235    /// Give `name` to `value` when it is a function or arrow, through
236    /// parentheses, as the instrumenter's `infer_name_for_value` does. Any
237    /// other value (a class among them) takes no name.
238    fn infer_name_for_value(&mut self, value: &Expression<'_>, name: Option<String>) {
239        let Some(name) = name else { return };
240        if let Some(start) = function_value_start(value) {
241            self.inferred_names.insert(start, name);
242        }
243    }
244
245    /// Give the callee name to each argument that is a function or arrow,
246    /// through parentheses, as the instrumenter's `callback_argument_name`
247    /// does. A function deeper in an argument (an array element, an object
248    /// property, a JSX attribute, a `??` operand) takes no callee name.
249    fn name_callback_arguments(&mut self, callee: &Expression<'_>, arguments: &[Argument<'_>]) {
250        let Some(name) = callee_name(callee) else {
251            return;
252        };
253        for argument in arguments {
254            if let Some(start) = argument.as_expression().and_then(function_value_start) {
255                self.callback_names.insert(start, name.clone());
256            }
257        }
258    }
259
260    fn record(&mut self, resolved: ResolvedName, span: Span) {
261        let mut start_cols = self.start_cols;
262        let (line, start_column) = self.line_col_utf16(&mut start_cols, span.start);
263        self.start_cols = start_cols;
264        let mut end_cols = self.end_cols;
265        let (end_line, end_column) = self.line_col_utf16(&mut end_cols, span.end);
266        self.end_cols = end_cols;
267        self.open.push(OpenFunction {
268            entry: self.entries.len(),
269            span,
270            height: 0,
271        });
272        self.entries.push(InventoryEntry {
273            name: resolved.name,
274            line,
275            start_column,
276            end_line,
277            end_column,
278            source_hash: None,
279            is_callback: resolved.is_callback,
280        });
281    }
282
283    /// Close the function that [`Self::record`] opened last and hash it.
284    fn leave_function(&mut self) {
285        let Some(open) = self.open.pop() else {
286            return;
287        };
288        self.entries[open.entry].source_hash =
289            crate::function_hash::function_source_hash(self.source, open.span, open.height);
290        if let Some(parent) = self.open.last_mut() {
291            parent.height = parent.height.max(open.height + 1);
292        }
293    }
294
295    /// Map a UTF-8 byte offset to `(1-based line, 1-indexed UTF-16 column)`.
296    ///
297    /// The line comes from the precomputed offset table; the column counts
298    /// UTF-16 code units from the line start to `byte_offset`, matching the
299    /// `FunctionIdentity` column convention (Istanbul / V8 / oxc all normalize
300    /// to 1-indexed UTF-16). A byte offset that does not fall on a char
301    /// boundary (it always should for an AST span) clamps to the nearest
302    /// boundary at or before it rather than panicking.
303    ///
304    /// Successive queries on the same line are answered incrementally from
305    /// [`ColCache`]: pre-order traversal emits nearby offsets, so counting
306    /// only the gap to the previous offset keeps the walk linear on
307    /// single-line (minified / generated) files instead of re-encoding the
308    /// full line prefix for every function.
309    fn line_col_utf16(&self, cache: &mut ColCache, byte_offset: u32) -> (u32, u32) {
310        let line_idx = match self.line_offsets.binary_search(&byte_offset) {
311            Ok(idx) => idx,
312            Err(idx) => idx.saturating_sub(1),
313        };
314        let line = line_idx as u32 + 1;
315        let line_start = self.line_offsets[line_idx] as usize;
316        let mut end = byte_offset as usize;
317        while end > line_start && !self.source.is_char_boundary(end) {
318            end -= 1;
319        }
320        // Both `end` and the cached position are char boundaries at or after
321        // `line_start` on the same line, so the gap slice is always valid and
322        // a backward gap never exceeds the cached column.
323        let from_cache = if cache.line_idx == line_idx {
324            if end >= cache.byte_end {
325                self.utf16_len(cache.byte_end, end)
326                    .map(|gap| cache.utf16_units + gap)
327            } else {
328                self.utf16_len(end, cache.byte_end)
329                    .map(|gap| cache.utf16_units - gap)
330            }
331        } else {
332            None
333        };
334        let col_utf16 = from_cache.unwrap_or_else(|| self.utf16_len(line_start, end).unwrap_or(0));
335        *cache = ColCache {
336            line_idx,
337            byte_end: end,
338            utf16_units: col_utf16,
339        };
340        (line, col_utf16 as u32 + 1)
341    }
342
343    /// UTF-16 code-unit count of `source[start..end]`, `None` when the range
344    /// is not sliceable.
345    fn utf16_len(&self, start: usize, end: usize) -> Option<usize> {
346        let slice = self.source.get(start..end)?;
347        #[cfg(test)]
348        UTF16_BYTES.with(|encoded| encoded.set(encoded.get() + slice.len()));
349        Some(slice.encode_utf16().count())
350    }
351}
352
353impl<'ast> Visit<'ast> for InventoryVisitor<'_> {
354    fn visit_function(&mut self, func: &Function<'ast>, flags: ScopeFlags) {
355        if func.body.is_none() {
356            walk::walk_function(self, func, flags);
357            return;
358        }
359        let resolved =
360            self.resolve_name(func.span.start, func.id.as_ref().map(|id| id.name.as_str()));
361        self.record(resolved, func.span);
362        walk::walk_function(self, func, flags);
363        self.leave_function();
364    }
365
366    fn visit_arrow_function_expression(&mut self, arrow: &ArrowFunctionExpression<'ast>) {
367        let resolved = self.resolve_name(arrow.span.start, None);
368        self.record(resolved, arrow.span);
369        walk::walk_arrow_function_expression(self, arrow);
370        self.leave_function();
371    }
372
373    fn visit_method_definition(&mut self, method: &MethodDefinition<'ast>) {
374        if let Some(name) = method.key.static_name() {
375            self.inferred_names.insert(
376                method.value.span.start,
377                accessor_label(
378                    matches!(method.kind, MethodDefinitionKind::Get),
379                    matches!(method.kind, MethodDefinitionKind::Set),
380                    &name.text(),
381                ),
382            );
383        }
384        walk::walk_method_definition(self, method);
385    }
386
387    fn visit_variable_declarator(&mut self, decl: &VariableDeclarator<'ast>) {
388        if let Some(init) = &decl.init {
389            let name = decl
390                .id
391                .get_binding_identifier()
392                .map(|id| id.name.to_string());
393            self.infer_name_for_value(init, name);
394        }
395        walk::walk_variable_declarator(self, decl);
396    }
397
398    /// Carry an object-literal key into the function it holds, matching the
399    /// instrumenter's `register_object_property`: shorthand methods, accessors
400    /// (prefixed `get ` / `set `), and function-valued data properties inherit
401    /// the key name. A data property holding anything else (a call whose
402    /// argument is a callback, most of all) inherits nothing, so the callback
403    /// still takes its own callee's name.
404    fn visit_object_property(&mut self, prop: &ObjectProperty<'ast>) {
405        let name = prop.key.static_name().map(|name| {
406            accessor_label(
407                matches!(prop.kind, PropertyKind::Get),
408                matches!(prop.kind, PropertyKind::Set),
409                &name.text(),
410            )
411        });
412        self.infer_name_for_value(&prop.value, name);
413        walk::walk_object_property(self, prop);
414    }
415
416    /// Carry an assignment target into the function assigned to it
417    /// (`client.execute = () => {}` -> "execute", `startLoad = () => {}` ->
418    /// "startLoad"), matching the instrumenter's `assignment_target_name` and
419    /// `infer_name_for_value`. Only a plain `=` gives a name. A compound or
420    /// logical operator (`+=`, `||=`, `??=`) gives none. The value can have
421    /// parentheses around it. Only a function or arrow takes the name: a class
422    /// value does not, and a function with its own name keeps that name.
423    ///
424    /// The name is keyed on the start of the value, so a function inside the
425    /// target (`f(() => 1).x = ...`) does not take it.
426    fn visit_assignment_expression(&mut self, expr: &AssignmentExpression<'ast>) {
427        if matches!(expr.operator, AssignmentOperator::Assign) {
428            self.infer_name_for_value(&expr.right, assignment_target_name(&expr.left));
429        }
430        walk::walk_assignment_expression(self, expr);
431    }
432
433    /// Name a function-valued parameter default after the parameter binding
434    /// (`function f(cb = () => 1)` -> "cb"), matching the instrumenter's
435    /// `instrument_parameter_default`.
436    fn visit_formal_parameter(&mut self, param: &FormalParameter<'ast>) {
437        if let Some(init) = &param.initializer {
438            let name = param
439                .pattern
440                .get_binding_identifier()
441                .map(|id| id.name.to_string());
442            self.infer_name_for_value(init, name);
443        }
444        walk::walk_formal_parameter(self, param);
445    }
446
447    /// Name a function-valued default in a binding pattern after its binding
448    /// (`const { a = () => 1 } = o` -> "a", `{ k: v = () => 1 }` -> "v"),
449    /// matching the instrumenter's `instrument_destructuring_default`.
450    fn visit_assignment_pattern(&mut self, pattern: &AssignmentPattern<'ast>) {
451        let name = pattern
452            .left
453            .get_binding_identifier()
454            .map(|id| id.name.to_string());
455        self.infer_name_for_value(&pattern.right, name);
456        walk::walk_assignment_pattern(self, pattern);
457    }
458
459    /// Name a function-valued default in an assignment target after an
460    /// identifier target (`[a = () => 1] = []` -> "a"), matching the
461    /// instrumenter's `simple_target_name`. A member target gives no name.
462    fn visit_assignment_target_with_default(&mut self, target: &AssignmentTargetWithDefault<'ast>) {
463        if let AssignmentTarget::AssignmentTargetIdentifier(id) = &target.binding {
464            self.infer_name_for_value(&target.init, Some(id.name.to_string()));
465        }
466        walk::walk_assignment_target_with_default(self, target);
467    }
468
469    /// Name a function-valued shorthand default in an assignment target
470    /// (`({ a = () => 1 } = o)` -> "a").
471    fn visit_assignment_target_property_identifier(
472        &mut self,
473        target: &AssignmentTargetPropertyIdentifier<'ast>,
474    ) {
475        if let Some(init) = &target.init {
476            self.infer_name_for_value(init, Some(target.binding.name.to_string()));
477        }
478        walk::walk_assignment_target_property_identifier(self, target);
479    }
480
481    /// Name an anonymous default export "default", matching the instrumenter's
482    /// `name_anonymous_default_export`. A named one keeps its own identifier.
483    fn visit_export_default_declaration(&mut self, decl: &ExportDefaultDeclaration<'ast>) {
484        let name = "default".to_owned();
485        match &decl.declaration {
486            ExportDefaultDeclarationKind::FunctionDeclaration(func) => {
487                self.inferred_names.insert(func.span.start, name);
488            }
489            kind => {
490                // `export default (() => 1)` also gives "default": the value
491                // can have parentheses around it.
492                if let Some(value) = kind.as_expression() {
493                    self.infer_name_for_value(value, Some(name));
494                }
495            }
496        }
497        walk::walk_export_default_declaration(self, decl);
498    }
499
500    /// Name each function-valued argument from the callee (`arr.map(cb)` ->
501    /// "map", `foo(cb)` -> "foo"), matching `oxc-coverage-instrument`'s
502    /// `name_callback_arguments`. The name is keyed on the start of the
503    /// argument function, so a chained call (`a.b().c(cb)`) never gives `b`
504    /// to the callback of `c`.
505    ///
506    /// An optional call on a callee that is not a member access (`foo?.(cb)`)
507    /// gives no name. The instrumenter wraps that callee in its optional-chain
508    /// helper (`enter_call_expression`), so its `callee_name` then sees a call.
509    /// A member callee (`a.b?.(cb)`, `a?.b?.(cb)`) stays native to keep `this`,
510    /// so it keeps its property name.
511    fn visit_call_expression(&mut self, call: &CallExpression<'ast>) {
512        if !(call.optional && call.callee.get_member_expr().is_none()) {
513            self.name_callback_arguments(&call.callee, &call.arguments);
514        }
515        walk::walk_call_expression(self, call);
516    }
517
518    fn visit_new_expression(&mut self, new_expr: &NewExpression<'ast>) {
519        self.name_callback_arguments(&new_expr.callee, &new_expr.arguments);
520        walk::walk_new_expression(self, new_expr);
521    }
522}
523
524/// Prefix an accessor's name the way `oxc-coverage-instrument` labels one, so
525/// a getter reads `get closed` on both sides of the join. A plain method or
526/// data property keeps its bare key.
527fn accessor_label(is_getter: bool, is_setter: bool, name: &str) -> String {
528    if is_getter {
529        return format!("get {name}");
530    }
531    if is_setter {
532        return format!("set {name}");
533    }
534    name.to_owned()
535}
536
537/// The start of a value that is a function or arrow, with the parentheses
538/// around it removed. Only such a value takes the name of a binding, a property
539/// key, an assignment target or a callee, as in the instrumenter's
540/// `infer_name_for_value`. A class value takes no name. A function with its own
541/// name keeps it, because `resolve_name` ranks the own name first.
542fn function_value_start(value: &Expression<'_>) -> Option<u32> {
543    match value.without_parentheses() {
544        Expression::FunctionExpression(func) => Some(func.span.start),
545        Expression::ArrowFunctionExpression(arrow) => Some(arrow.span.start),
546        _ => None,
547    }
548}
549
550/// Extract a name from an assignment target, matching the instrumenter's
551/// `assignment_target_name`: an identifier uses its name, a static member uses
552/// the property, a computed member uses a string-literal key, and anything else
553/// yields no name.
554fn assignment_target_name(target: &AssignmentTarget<'_>) -> Option<String> {
555    match target {
556        AssignmentTarget::AssignmentTargetIdentifier(ident) => Some(ident.name.to_string()),
557        AssignmentTarget::StaticMemberExpression(member) => Some(member.property.name.to_string()),
558        AssignmentTarget::ComputedMemberExpression(member) => match &member.expression {
559            Expression::StringLiteral(lit) => Some(lit.value.text().into_owned()),
560            _ => None,
561        },
562        _ => None,
563    }
564}
565
566/// Extract a display name from a call / `new` callee, matching
567/// `oxc-coverage-instrument`'s `callee_name`: a bare identifier keeps its name,
568/// a member access uses the (last) property, and a computed access uses a
569/// string-literal key. Anything else (a computed non-string index, a call
570/// result, a parenthesized expression) yields no name.
571fn callee_name(callee: &Expression<'_>) -> Option<String> {
572    match callee {
573        Expression::Identifier(ident) => Some(ident.name.to_string()),
574        Expression::StaticMemberExpression(member) => Some(member.property.name.to_string()),
575        Expression::ComputedMemberExpression(member) => match &member.expression {
576            Expression::StringLiteral(lit) => Some(lit.value.text().into_owned()),
577            _ => None,
578        },
579        // A parenthesized callee (`(foo)(cb)`, `(a.b)(cb)`) unwraps to its inner
580        // callee, matching the instrumenter. oxc keeps paren nodes by default
581        // (`preserve_parens`), so both sides see this node.
582        Expression::ParenthesizedExpression(paren) => callee_name(&paren.expression),
583        _ => None,
584    }
585}
586
587/// Per-function static complexity collected alongside the inventory walk.
588///
589/// Keyed to an [`InventoryEntry`] by its `source_hash`, which both this and the
590/// inventory walk derive from the identical full-span byte slice over the same
591/// parsed program (see [`InventoryEntry::source_hash`]). The hash is stable
592/// across line moves, so the pairing survives reformatting that shifts line
593/// numbers. `cyclomatic` and `cognitive` are descriptive context for downstream
594/// importance weighting, never thresholds.
595#[derive(Debug, Clone, Copy, PartialEq, Eq)]
596pub struct InventoryComplexity {
597    /// `McCabe` cyclomatic complexity (1 + decision points).
598    pub cyclomatic: u16,
599    /// `SonarSource` cognitive complexity (structural + nesting penalty).
600    pub cognitive: u16,
601}
602
603/// Parse `source` at `path` and return every function as an [`InventoryEntry`].
604///
605/// Only plain JS/TS/JSX/TSX sources are supported. Callers should skip SFC,
606/// Astro, MDX, CSS, HTML, and other non-JS inputs; those use different
607/// instrumentation paths and are out of scope for the first inventory release.
608///
609/// Errors are swallowed: the returned vector covers whatever could be parsed.
610/// This mirrors how the rest of the extract pipeline handles partial parse
611/// results.
612#[must_use]
613pub fn walk_source(path: &Path, source: &str) -> Vec<InventoryEntry> {
614    walk_source_with_complexity(path, source).0
615}
616
617/// Parse `source` at `path` once and return every function as an
618/// [`InventoryEntry`] together with a `source_hash -> InventoryComplexity` map.
619///
620/// Both the inventory entries and the complexity map come from the SAME parse
621/// (including the JSX fallback retry), so the per-function `source_hash` values
622/// line up exactly and a caller can enrich each entry's metrics by a hash
623/// lookup. Functions whose span slice could not be sliced share the empty-input
624/// hash and simply don't pair; that degrades to "no metrics", never a panic.
625///
626/// Errors are swallowed, matching [`walk_source`]: the returned data covers
627/// whatever could be parsed.
628#[must_use]
629pub fn walk_source_with_complexity(
630    path: &Path,
631    source: &str,
632) -> (Vec<InventoryEntry>, FxHashMap<String, InventoryComplexity>) {
633    let source_type = SourceType::from_path(path).unwrap_or_default();
634    let line_offsets = fallow_types::extract::compute_line_offsets(source);
635
636    let primary = walk_one_parse(source, source_type, &line_offsets);
637    if primary.0.is_empty() && !source_type.is_jsx() {
638        let jsx_type = if source_type.is_typescript() {
639            SourceType::tsx()
640        } else {
641            SourceType::jsx()
642        };
643        let retry = walk_one_parse(source, jsx_type, &line_offsets);
644        if !retry.0.is_empty() {
645            return retry;
646        }
647    }
648
649    primary
650}
651
652/// Run both the inventory and complexity visitors over a single parse of
653/// `source` under `source_type`, pairing them by `source_hash`.
654fn walk_one_parse(
655    source: &str,
656    source_type: SourceType,
657    line_offsets: &[u32],
658) -> (Vec<InventoryEntry>, FxHashMap<String, InventoryComplexity>) {
659    crate::parse_bounded(source, || {
660        walk_one_parse_unbounded(source, source_type, line_offsets)
661    })
662    .unwrap_or_default()
663}
664
665fn walk_one_parse_unbounded(
666    source: &str,
667    source_type: SourceType,
668    line_offsets: &[u32],
669) -> (Vec<InventoryEntry>, FxHashMap<String, InventoryComplexity>) {
670    let allocator = Allocator::default();
671    let parser_return = Parser::new(&allocator, source, source_type).parse();
672
673    let mut visitor = InventoryVisitor::new(source, line_offsets);
674    visitor.visit_program(&parser_return.program);
675
676    let complexity =
677        crate::complexity::compute_complexity(&parser_return.program, source, line_offsets);
678    let metrics: FxHashMap<String, InventoryComplexity> = complexity
679        .into_iter()
680        .filter_map(|fc| {
681            fc.source_hash.map(|hash| {
682                (
683                    hash,
684                    InventoryComplexity {
685                        cyclomatic: fc.cyclomatic,
686                        cognitive: fc.cognitive,
687                    },
688                )
689            })
690        })
691        .collect();
692
693    (visitor.entries, metrics)
694}
695
696#[cfg(all(test, not(miri)))]
697mod tests {
698    use super::*;
699    use std::path::PathBuf;
700
701    fn walk(source: &str) -> Vec<InventoryEntry> {
702        walk_source(&PathBuf::from("test.ts"), source)
703    }
704
705    #[test]
706    fn named_function_declaration_uses_its_own_name() {
707        let entries = walk("function foo() { return 1; }");
708        assert_eq!(entries.len(), 1);
709        assert_eq!(entries[0].name, "foo");
710        assert_eq!(entries[0].line, 1);
711    }
712
713    #[test]
714    fn const_arrow_captures_binding_name() {
715        let entries = walk("const bar = () => 42;");
716        assert_eq!(entries.len(), 1);
717        assert_eq!(entries[0].name, "bar");
718    }
719
720    #[test]
721    fn const_function_expression_keeps_its_own_name() {
722        // An own name comes first, as in the instrumenter's
723        // `resolve_function_name` and `Function.prototype.name`.
724        let entries = walk("const outer = function inner() { return 1; };");
725        assert_eq!(entries.len(), 1);
726        assert_eq!(entries[0].name, "inner");
727    }
728
729    #[test]
730    fn object_property_function_keeps_its_own_name() {
731        let entries = walk(
732            r"
733            const o = {
734              k: function own() {},
735              j: function () {},
736              m() {},
737              get g() { return 1; },
738            };
739            ",
740        );
741        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
742        assert_eq!(names, vec!["own", "j", "m", "get g"]);
743    }
744
745    #[test]
746    fn own_name_beats_binding_and_does_not_leak_inward() {
747        // The binding name is dropped when the function has its own name, so a
748        // function inside the body does not take it.
749        let entries = walk("const f = function g() { return [1].map(() => 2); };");
750        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
751        assert_eq!(names, vec!["g", "map"]);
752    }
753
754    #[test]
755    fn parenthesized_declarator_and_property_values_take_the_binding_name() {
756        // The instrumenter removes the parentheses around the value before it
757        // names the function.
758        let entries = walk(
759            r"
760            const a = (() => 1);
761            const b = (function () {});
762            const c = (function own() {});
763            const o = { k: (() => 2) };
764            ",
765        );
766        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
767        assert_eq!(names, vec!["a", "b", "own", "k"]);
768    }
769
770    #[test]
771    fn declared_class_gives_no_name_to_its_members() {
772        // A class value takes no binding name, with or without an own name. Its
773        // constructor and methods keep their keys and a field arrow stays
774        // anonymous.
775        let entries = walk(
776            r"
777            const C = class D { constructor() {} m() {} p = () => 1; };
778            const E = class { q = () => 2; };
779            ",
780        );
781        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
782        assert_eq!(
783            names,
784            vec!["constructor", "m", "(anonymous_2)", "(anonymous_3)"]
785        );
786    }
787
788    #[test]
789    fn class_methods_use_method_names() {
790        let entries = walk(
791            r"
792            class Foo {
793              bar() { return 1; }
794              baz() { return 2; }
795            }",
796        );
797        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
798        assert_eq!(names, vec!["bar", "baz"]);
799    }
800
801    #[test]
802    fn callback_argument_takes_the_callee_name() {
803        // An arrow passed as a call argument now takes the callee name (matches
804        // the instrumenter's name_callback_arguments), not the anonymous counter.
805        let entries = walk("setTimeout(() => { console.log('hi'); }, 10);");
806        assert_eq!(entries.len(), 1);
807        assert_eq!(entries[0].name, "setTimeout");
808    }
809
810    #[test]
811    fn member_callee_names_each_callback_in_source_order() {
812        let entries = walk(
813            r"
814            [1, 2, 3].map(() => 1);
815            [4, 5, 6].filter(() => true);
816            ",
817        );
818        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
819        assert_eq!(names, vec!["map", "filter"]);
820    }
821
822    #[test]
823    fn named_function_still_advances_counter_matching_instrumenter() {
824        // The counter still advances on every function (named or callee-named),
825        // matching the instrumenter, so a later genuinely-anonymous function
826        // gets the right N. Here the callback is callee-named "map".
827        let entries = walk(
828            r"
829            function named() { return 1; }
830            [1].map(() => 2);
831            ",
832        );
833        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
834        assert_eq!(names, vec!["named", "map"]);
835    }
836
837    #[test]
838    fn plain_identifier_callee_names_the_callback() {
839        let entries = walk("useMemo(() => compute());");
840        assert_eq!(entries[0].name, "useMemo");
841    }
842
843    #[test]
844    fn new_expression_callee_names_the_callback() {
845        let entries = walk("new Promise((resolve) => resolve(1));");
846        assert_eq!(entries[0].name, "Promise");
847    }
848
849    #[test]
850    fn callback_after_a_string_argument_is_named_from_the_callee() {
851        // The event/route-handler shape: the function is a later argument, after
852        // a string. It is named from the callee, not the string.
853        let entries = walk(r#"el.addEventListener("click", () => handle());"#);
854        assert_eq!(entries[0].name, "addEventListener");
855    }
856
857    #[test]
858    fn computed_string_key_callee_is_named() {
859        let entries = walk(r#"obj["handler"](() => run());"#);
860        assert_eq!(entries[0].name, "handler");
861    }
862
863    #[test]
864    fn chained_call_does_not_leak_the_earlier_callee_onto_the_later_callback() {
865        // `.then`'s callback must be "then" and `.catch`'s must be "catch": the
866        // callee subtree (`p.then(cb).catch`) is visited before the outer
867        // arguments, so the earlier callee never leaks onto the later callback.
868        let entries = walk("p.then(() => a).catch(() => b);");
869        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
870        assert_eq!(names, vec!["then", "catch"]);
871    }
872
873    #[test]
874    fn nested_callbacks_each_take_their_own_callee() {
875        let entries = walk("outer(() => inner(() => 1));");
876        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
877        assert_eq!(names, vec!["outer", "inner"]);
878    }
879
880    #[test]
881    fn binding_name_wins_over_callee() {
882        // A declarator binding is consumed on function entry, before the body's
883        // calls, so a bound arrow keeps its name even when its body is a call.
884        let entries = walk("const handler = () => run();");
885        assert_eq!(entries[0].name, "handler");
886    }
887
888    #[test]
889    fn named_function_expression_argument_keeps_its_own_id() {
890        let entries = walk("run(function inner() { return 1; });");
891        assert_eq!(entries[0].name, "inner");
892    }
893
894    #[test]
895    fn iife_callee_stays_anonymous() {
896        // The function is the callee, not an argument, so it is not a callback.
897        let entries = walk("(function () { return 1; })();");
898        assert_eq!(entries[0].name, "(anonymous_0)");
899    }
900
901    #[test]
902    fn computed_non_string_callee_stays_anonymous() {
903        let entries = walk("handlers[index](() => run());");
904        assert_eq!(entries[0].name, "(anonymous_0)");
905    }
906
907    #[test]
908    fn parenthesized_callee_unwraps_to_the_inner_name() {
909        assert_eq!(walk("(foo)(() => run());")[0].name, "foo");
910        assert_eq!(walk("(a.b)(() => run());")[0].name, "b");
911    }
912
913    #[test]
914    fn optional_call_on_a_non_member_callee_gives_no_callee_name() {
915        // The instrumenter wraps a non-member callee of an optional call in its
916        // optional-chain helper, so the callback sees a call as its callee.
917        assert_eq!(walk("foo?.(() => 1);")[0].name, "(anonymous_0)");
918        assert_eq!(walk("(foo)?.(() => 1);")[0].name, "(anonymous_0)");
919        assert_eq!(walk("(foo as any)?.(() => 1);")[0].name, "(anonymous_0)");
920        assert_eq!(walk("foo!?.(() => 1);")[0].name, "(anonymous_0)");
921        assert_eq!(walk("a?.b?.c?.(() => 1);")[0].name, "c");
922    }
923
924    #[test]
925    fn optional_call_on_a_member_callee_keeps_the_callee_name() {
926        // A receiver-bound optional call stays native in the instrumenter, so
927        // the callee keeps its property name.
928        assert_eq!(walk("a.b?.(() => 1);")[0].name, "b");
929        assert_eq!(walk("a?.b?.(() => 1);")[0].name, "b");
930        assert_eq!(walk("a['k']?.(() => 1);")[0].name, "k");
931        assert_eq!(walk("(a.b)?.(() => 1);")[0].name, "b");
932        assert_eq!(walk("a?.b(() => 1);")[0].name, "b");
933        assert_eq!(walk("a?.b?.c(() => 1);")[0].name, "c");
934    }
935
936    #[test]
937    fn optional_call_without_callee_name_still_names_a_nested_call_argument() {
938        // Only the direct arguments of the optional call lose the callee name.
939        let entries = walk("foo?.(() => 1, bar(() => 2));");
940        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
941        assert_eq!(names, vec!["(anonymous_0)", "bar"]);
942    }
943
944    #[test]
945    fn anonymous_after_named_chain_uses_next_counter_value() {
946        let entries = walk(
947            r"
948            function a() {}
949            function b() {}
950            function c() {}
951            const d = () => 4;
952            ",
953        );
954        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
955        assert_eq!(names, vec!["a", "b", "c", "d"]);
956    }
957
958    #[test]
959    fn typescript_overload_signatures_dont_emit_or_advance_counter() {
960        let entries = walk(
961            r"
962            function foo(): number;
963            function foo(s: string): string;
964            function foo(s?: string): number | string { return s ? s : 1; }
965            [1].map(() => 2);
966            ",
967        );
968        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
969        assert_eq!(names, vec!["foo", "map"]);
970    }
971
972    #[test]
973    fn export_default_named_function_keeps_explicit_name() {
974        let entries = walk("export default function foo() { return 1; }");
975        assert_eq!(entries.len(), 1);
976        assert_eq!(entries[0].name, "foo");
977    }
978
979    #[test]
980    fn export_default_anonymous_function_is_named_default() {
981        let entries = walk("export default function() { return 1; }");
982        assert_eq!(entries.len(), 1);
983        assert_eq!(entries[0].name, "default");
984    }
985
986    #[test]
987    fn export_default_anonymous_arrow_is_named_default() {
988        let entries = walk("export default () => 1;");
989        assert_eq!(entries.len(), 1);
990        assert_eq!(entries[0].name, "default");
991    }
992
993    #[test]
994    fn parenthesized_anonymous_default_export_is_named_default() {
995        assert_eq!(names("export default (() => 1);"), ["default"]);
996        assert_eq!(names("export default (function () {});"), ["default"]);
997        assert_eq!(
998            names("export default (function () { return () => 1; });"),
999            ["default", "(anonymous_1)"]
1000        );
1001        assert_eq!(names("export default (function own() {});"), ["own"]);
1002    }
1003
1004    #[test]
1005    fn nested_function_numbered_after_parent_in_traversal_order() {
1006        let entries = walk(
1007            r"
1008            function outer() {
1009              return function() { return 1; };
1010            }",
1011        );
1012        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1013        assert_eq!(names, vec!["outer", "(anonymous_1)"]);
1014    }
1015
1016    #[test]
1017    fn line_number_is_one_based_from_source_start() {
1018        let entries = walk("\n\nfunction atLineThree() {}");
1019        assert_eq!(entries.len(), 1);
1020        assert_eq!(entries[0].line, 3);
1021    }
1022
1023    #[test]
1024    fn short_jsx_in_js_file_retries_with_jsx_parser() {
1025        let entries = walk_source(&PathBuf::from("component.js"), "const A = () => <div />;");
1026        assert_eq!(entries.len(), 1);
1027        assert_eq!(entries[0].name, "A");
1028        assert_eq!(entries[0].line, 1);
1029    }
1030
1031    #[test]
1032    fn object_method_shorthand_uses_the_key_name() {
1033        let entries = walk("const obj = { run() { return 1; } };");
1034        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1035        assert_eq!(names, vec!["run"]);
1036    }
1037
1038    #[test]
1039    fn object_accessors_carry_the_get_and_set_label() {
1040        let entries = walk(
1041            r"
1042            const obj = {
1043              get closed() { return true; },
1044              set closed(value) { this.value = value; },
1045            };",
1046        );
1047        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1048        assert_eq!(names, vec!["get closed", "set closed"]);
1049    }
1050
1051    #[test]
1052    fn function_valued_object_property_uses_the_key_name() {
1053        let entries = walk("const client = { execute: async (sql) => sql.length };");
1054        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1055        assert_eq!(names, vec!["execute"]);
1056    }
1057
1058    #[test]
1059    fn object_property_holding_a_call_leaves_the_callback_to_its_callee() {
1060        // The key names only a function-valued property. A property whose value
1061        // is a call must not steal the name from that call's callback.
1062        let entries = walk("const column = { references: memo(() => other.id) };");
1063        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1064        assert_eq!(names, vec!["memo"]);
1065    }
1066
1067    #[test]
1068    fn class_accessors_carry_the_get_and_set_label() {
1069        let entries = walk(
1070            r"
1071            class Client {
1072              get closed() { return true; }
1073              set closed(value) { this.value = value; }
1074            }",
1075        );
1076        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1077        assert_eq!(names, vec!["get closed", "set closed"]);
1078    }
1079
1080    #[test]
1081    fn member_assignment_target_names_the_assigned_function() {
1082        let entries = walk(
1083            r#"
1084            client.execute = async (sql) => sql;
1085            client["rollback"] = function () { return 1; };
1086            "#,
1087        );
1088        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1089        assert_eq!(names, vec!["execute", "rollback"]);
1090    }
1091
1092    #[test]
1093    fn identifier_assignment_target_names_the_assigned_function() {
1094        // An assignment to a variable declared earlier names the function after
1095        // the variable, as the instrumenter and `Function.prototype.name` do.
1096        let entries = walk(
1097            r"
1098            let startLoad;
1099            startLoad = () => {};
1100            let handler;
1101            handler = function () { return 1; };
1102            ",
1103        );
1104        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1105        assert_eq!(names, vec!["startLoad", "handler"]);
1106    }
1107
1108    #[test]
1109    fn parenthesized_assigned_function_takes_the_target_name() {
1110        // The instrumenter removes the parentheses around the assigned value.
1111        let entries = walk(
1112            r"
1113            let x;
1114            x = (() => 1);
1115            o.m = (function () { return 2; });
1116            ",
1117        );
1118        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1119        assert_eq!(names, vec!["x", "m"]);
1120    }
1121
1122    #[test]
1123    fn assigned_function_keeps_its_own_name() {
1124        // An own name comes first, as in the instrumenter and
1125        // `Function.prototype.name`.
1126        let entries = walk(
1127            r"
1128            let n;
1129            n = function own() {};
1130            o.z = function inner() {};
1131            ",
1132        );
1133        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1134        assert_eq!(names, vec!["own", "inner"]);
1135    }
1136
1137    #[test]
1138    fn assigned_class_gives_no_name_to_its_members() {
1139        // The instrumenter names only an assigned function or arrow. A class
1140        // value must not pass the target name to its first field arrow.
1141        let entries = walk(
1142            r"
1143            let X;
1144            X = class { p = () => 1; };
1145            o.Y = class { r = () => 2; };
1146            ",
1147        );
1148        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1149        assert_eq!(names, vec!["(anonymous_0)", "(anonymous_1)"]);
1150    }
1151
1152    #[test]
1153    fn assignment_target_name_does_not_reach_the_left_side() {
1154        // A function inside the target expression is not the assigned value.
1155        let entries = walk("f(() => 1).x = () => 2;");
1156        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1157        assert_eq!(names, vec!["f", "x"]);
1158    }
1159
1160    #[test]
1161    fn compound_and_logical_assignments_give_no_name() {
1162        // The instrumenter names a function only for a plain `=`. V8 also names
1163        // `||=`, `&&=` and `??=`, but the instrumenter is the join partner.
1164        let entries = walk(
1165            r"
1166            let a;
1167            a ||= () => 1;
1168            let b;
1169            b &&= () => 2;
1170            let c;
1171            c ??= () => 3;
1172            let d = '';
1173            d += function () { return 4; };
1174            ",
1175        );
1176        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1177        assert_eq!(
1178            names,
1179            vec![
1180                "(anonymous_0)",
1181                "(anonymous_1)",
1182                "(anonymous_2)",
1183                "(anonymous_3)"
1184            ]
1185        );
1186    }
1187
1188    #[test]
1189    fn only_callee_named_functions_are_flagged_as_callbacks() {
1190        let entries = walk(
1191            r"
1192            function declared() { return 1; }
1193            const bound = () => 2;
1194            const obj = { run() { return 3; } };
1195            [1].map(() => 4);
1196            (function () { return 5; })();
1197            ",
1198        );
1199        let flags: Vec<_> = entries
1200            .iter()
1201            .map(|e| (e.name.as_str(), e.is_callback))
1202            .collect();
1203        assert_eq!(
1204            flags,
1205            vec![
1206                ("declared", false),
1207                ("bound", false),
1208                ("run", false),
1209                ("map", true),
1210                ("(anonymous_4)", false),
1211            ]
1212        );
1213    }
1214
1215    #[test]
1216    fn drizzle_style_schema_names_every_callback_after_its_callee() {
1217        // The shape a Drizzle schema module has: a table callback, a column
1218        // reference callback, and an index callback, all anonymous arrows that
1219        // the instrumenter names after the function they are passed to.
1220        let entries = walk(
1221            r#"
1222            export const users = sqliteTable("users", {
1223              id: text("id").primaryKey(),
1224              orgId: text("org_id").references(() => orgs.id),
1225            }, (table) => [index("users_org_idx").on(table.orgId)]);
1226            "#,
1227        );
1228        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1229        assert_eq!(names, vec!["references", "sqliteTable"]);
1230        assert!(entries.iter().all(|entry| entry.is_callback));
1231    }
1232
1233    fn names(source: &str) -> Vec<String> {
1234        walk_source(&PathBuf::from("test.tsx"), source)
1235            .into_iter()
1236            .map(|entry| entry.name)
1237            .collect()
1238    }
1239
1240    #[test]
1241    fn callee_name_does_not_reach_a_function_inside_a_named_argument() {
1242        // The argument function takes its own or its parent name, so the
1243        // callee name does not reach the next unnamed function inside it.
1244        assert_eq!(
1245            names("let x; foo(x = () => () => 2);"),
1246            ["x", "(anonymous_1)"]
1247        );
1248        assert_eq!(names("foo(o.x = () => () => 2);"), ["x", "(anonymous_1)"]);
1249        assert_eq!(
1250            names("foo({ k: (() => () => 1) });"),
1251            ["k", "(anonymous_1)"]
1252        );
1253        assert_eq!(
1254            names("foo({ k: function own() { return () => 1; } });"),
1255            ["own", "(anonymous_1)"]
1256        );
1257        assert_eq!(
1258            names("foo(function g() { return () => 1; });"),
1259            ["g", "(anonymous_1)"]
1260        );
1261    }
1262
1263    #[test]
1264    fn callee_name_applies_only_to_a_direct_argument() {
1265        // The instrumenter names a function after the callee only when the
1266        // function is an argument itself, through parentheses only.
1267        assert_eq!(names("foo((() => 1));"), ["foo"]);
1268        assert_eq!(names("foo([() => 1]);"), ["(anonymous_0)"]);
1269        assert_eq!(names("foo(...[() => 1]);"), ["(anonymous_0)"]);
1270        assert_eq!(names("foo((() => 1) as any);"), ["(anonymous_0)"]);
1271        assert_eq!(names("foo(a ?? (() => 1));"), ["(anonymous_0)"]);
1272        assert_eq!(
1273            names("foo(c ? () => 1 : () => 2);"),
1274            ["(anonymous_0)", "(anonymous_1)"]
1275        );
1276        assert_eq!(names("render(<B onClick={() => 1} />);"), ["(anonymous_0)"]);
1277        assert_eq!(
1278            names("extendTailwindMerge({ extend: { classGroups: [() => 1] } });"),
1279            ["(anonymous_0)"]
1280        );
1281        assert_eq!(names("push({ k: a ?? (() => 1) });"), ["(anonymous_0)"]);
1282    }
1283
1284    #[test]
1285    fn function_default_value_takes_the_binding_name() {
1286        // The instrumenter names a function-valued default after the binding
1287        // that it is the default of. A renamed property takes the binding
1288        // name (`v`), not the key (`k`).
1289        assert_eq!(names("function f(cb = () => 1) {}"), ["f", "cb"]);
1290        assert_eq!(names("function h(cb = (() => 1)) {}"), ["h", "cb"]);
1291        assert_eq!(names("function h(cb = function own() {}) {}"), ["h", "own"]);
1292        assert_eq!(names("const fn = (cb = () => 1) => cb;"), ["fn", "cb"]);
1293        assert_eq!(names("class P { m(cb = () => 1) {} }"), ["m", "cb"]);
1294        assert_eq!(
1295            names("function Button({ onClick = () => {} }) {}"),
1296            ["Button", "onClick"]
1297        );
1298        assert_eq!(names("function g({ k: v = () => 1 }) {}"), ["g", "v"]);
1299        assert_eq!(names("const { a = () => 1 } = o;"), ["a"]);
1300        assert_eq!(names("const { k: v = () => 1 } = o;"), ["v"]);
1301        assert_eq!(names("const [b = () => 1] = o;"), ["b"]);
1302        assert_eq!(names("[a = () => 1] = [];"), ["a"]);
1303        assert_eq!(names("({ a = () => 1 } = o);"), ["a"]);
1304        assert_eq!(names("({ k: v = () => 1 } = o);"), ["v"]);
1305    }
1306
1307    #[test]
1308    fn default_value_of_a_member_target_stays_anonymous() {
1309        // Only an identifier target gives its name to a default value.
1310        assert_eq!(names("({ k: o.v = () => 1 } = x);"), ["(anonymous_0)"]);
1311        assert_eq!(names("[o.v = () => 1] = x;"), ["(anonymous_0)"]);
1312    }
1313
1314    #[test]
1315    fn class_property_arrow_uses_anonymous_counter() {
1316        let entries = walk(
1317            r"
1318            class Foo {
1319              bar = () => 1;
1320            }",
1321        );
1322        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1323        assert_eq!(names, vec!["(anonymous_0)"]);
1324    }
1325
1326    #[test]
1327    fn records_one_indexed_utf16_columns() {
1328        let entries = walk("function foo() { return 1; }");
1329        assert_eq!(entries.len(), 1);
1330        assert_eq!(entries[0].start_column, 1);
1331        assert_eq!(entries[0].end_line, 1);
1332        assert!(entries[0].end_column > entries[0].start_column);
1333    }
1334
1335    #[test]
1336    fn utf16_column_counts_code_units_not_bytes() {
1337        let entries = walk("const e = \"\u{1F600}\"; const f = () => 1;");
1338        let f = entries.iter().find(|e| e.name == "f").expect("f present");
1339        let byte_prefix_len = "const e = \"\u{1F600}\"; const f = ".len() as u32;
1340        assert!(f.start_column < byte_prefix_len + 1);
1341    }
1342
1343    #[test]
1344    fn utf16_columns_stay_exact_across_a_long_single_line() {
1345        // Minified shape: many functions with non-ASCII content on one line.
1346        // Columns must match a naive full-prefix UTF-16 count even though the
1347        // walker resolves them incrementally, including the backward offset
1348        // jump from `outer`'s end to `inner`'s start and the reset to line 2.
1349        use std::fmt::Write as _;
1350        let mut src = String::new();
1351        for i in 0..40 {
1352            let _ = write!(src, "function f{i}() {{ return \"\u{1F600}\"; }} ");
1353        }
1354        src.push_str("function outer() { const inner = () => \"\u{1F600}\"; return inner; }");
1355        src.push_str("\nconst tail = () => 1;");
1356        let entries = walk(&src);
1357        let col = |byte: usize| src[..byte].encode_utf16().count() as u32 + 1;
1358
1359        for i in [0_usize, 17, 39] {
1360            let body = format!("function f{i}() {{ return \"\u{1F600}\"; }}");
1361            let start = src.find(&body).expect("function text present");
1362            let entry = entries
1363                .iter()
1364                .find(|e| e.name == format!("f{i}"))
1365                .expect("entry present");
1366            assert_eq!(entry.line, 1);
1367            assert_eq!(entry.start_column, col(start));
1368            assert_eq!(entry.end_line, 1);
1369            assert_eq!(entry.end_column, col(start + body.len()));
1370        }
1371
1372        let inner_start = src
1373            .find("() => \"\u{1F600}\"")
1374            .expect("inner arrow present");
1375        let inner = entries
1376            .iter()
1377            .find(|e| e.name == "inner")
1378            .expect("inner present");
1379        assert_eq!(inner.line, 1);
1380        assert_eq!(inner.start_column, col(inner_start));
1381
1382        let tail = entries
1383            .iter()
1384            .find(|e| e.name == "tail")
1385            .expect("tail present");
1386        let line2_start = src.find('\n').expect("newline present") + 1;
1387        let tail_start = src.rfind("() => 1").expect("tail arrow present");
1388        assert_eq!(tail.line, 2);
1389        assert_eq!(
1390            tail.start_column,
1391            src[line2_start..tail_start].encode_utf16().count() as u32 + 1
1392        );
1393    }
1394
1395    #[test]
1396    fn same_line_distinct_named_functions_have_distinct_positions() {
1397        let entries = walk("function a() {} function b() {}");
1398        let a = entries.iter().find(|e| e.name == "a").expect("a present");
1399        let b = entries.iter().find(|e| e.name == "b").expect("b present");
1400        assert_eq!(a.line, b.line, "both on line 1");
1401        assert_ne!(
1402            a.start_column, b.start_column,
1403            "same-line functions are column-disambiguated"
1404        );
1405    }
1406
1407    #[test]
1408    fn same_line_anonymous_functions_stay_distinct_via_counter() {
1409        let entries = walk("const xs = [() => 1, () => 2];");
1410        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
1411        assert_eq!(names, vec!["(anonymous_0)", "(anonymous_1)"]);
1412        assert_eq!(entries[0].line, entries[1].line, "both on line 1");
1413        assert_ne!(
1414            entries[0].name, entries[1].name,
1415            "counter keeps them distinct"
1416        );
1417    }
1418
1419    /// A chain of `levels` nested arrows on one line.
1420    fn nested_arrow_source(levels: usize) -> String {
1421        format!("export const f = {}1;\n", "()=>".repeat(levels))
1422    }
1423
1424    #[test]
1425    fn deep_nesting_keeps_the_hash_join_with_complexity() {
1426        let levels = crate::function_hash::MAX_HASHED_FUNCTION_HEIGHT as usize + 3;
1427        let source = nested_arrow_source(levels);
1428        let (entries, complexity) = walk_source_with_complexity(&PathBuf::from("a.js"), &source);
1429        assert_eq!(entries.len(), levels);
1430        // Pre-order: the outermost arrow comes first and has the most levels
1431        // of nested functions below it.
1432        for (index, entry) in entries.iter().enumerate() {
1433            let height = levels - 1 - index;
1434            let kept = height <= crate::function_hash::MAX_HASHED_FUNCTION_HEIGHT as usize;
1435            assert_eq!(entry.source_hash.is_some(), kept, "height {height}");
1436            if let Some(hash) = &entry.source_hash {
1437                assert!(
1438                    complexity.contains_key(hash),
1439                    "height {height} has no metrics"
1440                );
1441            }
1442        }
1443    }
1444
1445    #[test]
1446    fn column_lookups_stay_linear_on_nested_functions_in_one_line() {
1447        // The counter is per thread, so the walk must stay on this thread:
1448        // a thread with a registered stack keeps the bounded parse on it.
1449        const STACK: usize = 64 << 20;
1450        let (encoded, entries, source_len) = std::thread::Builder::new()
1451            .stack_size(STACK)
1452            .spawn(|| {
1453                crate::register_thread_stack(STACK);
1454                take_utf16_bytes();
1455                let source = nested_arrow_source(4_000);
1456                let entries = walk_source(&PathBuf::from("a.js"), &source);
1457                (take_utf16_bytes(), entries.len(), source.len())
1458            })
1459            .expect("probe thread should start")
1460            .join()
1461            .expect("probe thread should finish");
1462        assert_eq!(entries, 4_000);
1463        assert!(
1464            encoded <= 4 * source_len,
1465            "encoded {encoded} bytes for {source_len}"
1466        );
1467    }
1468
1469    #[test]
1470    fn source_hash_is_the_content_digest_of_the_function_span() {
1471        let src = "function foo() { return 1; }";
1472        let entries = walk(src);
1473        assert_eq!(entries.len(), 1);
1474        let hash = entries[0]
1475            .source_hash
1476            .as_deref()
1477            .expect("a shallow function keeps its hash");
1478        assert_eq!(hash, fallow_cov_protocol::source_hash_for(src.as_bytes()));
1479        assert_eq!(hash.len(), 16);
1480        assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));
1481    }
1482
1483    #[test]
1484    fn source_hash_survives_line_moves_and_tracks_body_edits() {
1485        let original = walk("function foo() { return 1; }");
1486        let moved = walk("\n\nfunction foo() { return 1; }");
1487        assert_eq!(
1488            original[0].source_hash, moved[0].source_hash,
1489            "a moved-but-unedited function must keep its source_hash"
1490        );
1491        let edited = walk("function foo() { return 2; }");
1492        assert_ne!(
1493            original[0].source_hash, edited[0].source_hash,
1494            "an edited body must change the source_hash"
1495        );
1496    }
1497}