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