Skip to main content

aft_parse/
extract.rs

1//! Shared extraction utilities for `extract_function` (and future `inline_symbol`).
2//!
3//! Provides:
4//! - `detect_free_variables` — classify identifier references in a byte range
5//! - `detect_return_value` — infer what the extracted function should return
6//! - `generate_extracted_function` — produce function text for TS/JS or Python
7
8use std::collections::HashSet;
9
10use tree_sitter::{Node, Tree};
11
12use crate::indent::IndentStyle;
13use crate::parser::{node_text, LangId};
14
15// ---------------------------------------------------------------------------
16// Free variable detection
17// ---------------------------------------------------------------------------
18
19/// Classification result for free variables in a selected byte range.
20#[derive(Debug)]
21pub struct FreeVariableResult {
22    /// Identifiers declared in an enclosing function scope that the range
23    /// references — these become parameters of the extracted function.
24    pub parameters: Vec<String>,
25    /// Whether `this` (JS/TS) or `self` (Python) appears in the range.
26    pub has_this_or_self: bool,
27}
28
29/// Walk the AST for a byte range and classify every identifier reference.
30///
31/// Classification rules:
32/// 1. Declared-in-range (local variable) → skip
33/// 2. Declared in enclosing function scope → parameter
34/// 3. Module-level or import → skip
35/// 4. `this` / `self` keyword → flag (error for extract_function)
36/// 5. `property_identifier` / `field_identifier` on the right side of `.` → skip
37///    (these are member accesses, not free variables)
38pub fn detect_free_variables(
39    source: &str,
40    tree: &Tree,
41    start_byte: usize,
42    end_byte: usize,
43    lang: LangId,
44) -> FreeVariableResult {
45    let root = tree.root_node();
46
47    let mut references = Vec::new();
48    collect_reference_nodes(&root, start_byte, end_byte, lang, &mut references);
49    let mut bindings = Vec::new();
50    collect_scoped_bindings(&root, source, lang, &mut bindings);
51    let mut bindings_by_name = std::collections::HashMap::<&str, Vec<&ScopedBinding>>::new();
52    for binding in &bindings {
53        bindings_by_name
54            .entry(&binding.name)
55            .or_default()
56            .push(binding);
57    }
58    let has_this_or_self = check_this_or_self(&root, source, start_byte, end_byte, lang);
59    let mut seen = HashSet::new();
60    let mut parameters = Vec::new();
61    for reference in references {
62        let name = node_text(source, &reference);
63        if is_keyword(name, lang) || is_binding_identifier(&reference) {
64            continue;
65        }
66        let Some(candidates) = bindings_by_name.get(name) else {
67            continue;
68        };
69        let binding = candidates
70            .iter()
71            .filter(|binding| {
72                binding.scope_start <= reference.start_byte()
73                    && reference.end_byte() <= binding.scope_end
74                    && (binding.hoisted || binding.declaration <= reference.start_byte())
75            })
76            .min_by_key(|binding| {
77                (
78                    binding.scope_end - binding.scope_start,
79                    std::cmp::Reverse(binding.declaration),
80                )
81            });
82        if let Some(binding) = binding {
83            if !binding.module_scope
84                && !(start_byte <= binding.declaration && binding.declaration < end_byte)
85                && seen.insert(name.to_string())
86            {
87                parameters.push(name.to_string());
88            }
89        }
90    }
91    FreeVariableResult {
92        parameters,
93        has_this_or_self,
94    }
95}
96
97/// Collect all `identifier` nodes in [start_byte, end_byte) that are genuine
98/// references (not property accesses on the right side of `.`).
99fn collect_identifier_refs(
100    node: &Node,
101    source: &str,
102    start_byte: usize,
103    end_byte: usize,
104    lang: LangId,
105    out: &mut Vec<String>,
106) {
107    // Skip nodes entirely outside the range
108    if node.end_byte() <= start_byte || node.start_byte() >= end_byte {
109        return;
110    }
111
112    let kind = node.kind();
113
114    // An `identifier` node in the range that is NOT a property/field access
115    if kind == "identifier" && node.start_byte() >= start_byte && node.end_byte() <= end_byte {
116        // Check parent: if parent is member_expression and this is the "property" field,
117        // it's a property access, not a free variable.
118        if !is_property_access(node, lang) {
119            let name = node_text(source, node).to_string();
120            // Skip language keywords that parse as identifiers
121            if !is_keyword(&name, lang) {
122                out.push(name);
123            }
124        }
125    }
126
127    // Recurse into children
128    let mut cursor = node.walk();
129    if cursor.goto_first_child() {
130        loop {
131            collect_identifier_refs(&cursor.node(), source, start_byte, end_byte, lang, out);
132            if !cursor.goto_next_sibling() {
133                break;
134            }
135        }
136    }
137}
138
139/// Check if an identifier node is a property access (right side of `.`).
140fn is_property_access(node: &Node, lang: LangId) -> bool {
141    // property_identifier and field_identifier are separate node kinds in TS/JS,
142    // so they won't even reach here. But for Python `attribute` access the child
143    // is still `identifier`.
144    if let Some(parent) = node.parent() {
145        let pk = parent.kind();
146        match lang {
147            LangId::TypeScript | LangId::Tsx | LangId::JavaScript => {
148                // member_expression: object.property — the "property" child
149                if pk == "member_expression" {
150                    if let Some(prop) = parent.child_by_field_name("property") {
151                        return prop.id() == node.id();
152                    }
153                }
154            }
155            LangId::Python => {
156                // attribute: object.attr — the "attribute" child
157                if pk == "attribute" {
158                    if let Some(attr) = parent.child_by_field_name("attribute") {
159                        return attr.id() == node.id();
160                    }
161                }
162            }
163            _ => {}
164        }
165    }
166    false
167}
168
169/// Identifiers that are language keywords and should not be treated as free variables.
170fn is_keyword(name: &str, lang: LangId) -> bool {
171    match lang {
172        LangId::TypeScript | LangId::Tsx | LangId::JavaScript => matches!(
173            name,
174            "undefined" | "null" | "true" | "false" | "NaN" | "Infinity" | "console" | "require"
175        ),
176        LangId::Python => matches!(
177            name,
178            "None"
179                | "True"
180                | "False"
181                | "print"
182                | "len"
183                | "range"
184                | "str"
185                | "int"
186                | "float"
187                | "list"
188                | "dict"
189                | "set"
190                | "tuple"
191                | "type"
192                | "super"
193                | "isinstance"
194                | "enumerate"
195                | "zip"
196                | "map"
197                | "filter"
198                | "sorted"
199                | "reversed"
200                | "any"
201                | "all"
202                | "min"
203                | "max"
204                | "sum"
205                | "abs"
206                | "open"
207                | "input"
208                | "format"
209                | "hasattr"
210                | "getattr"
211                | "setattr"
212                | "delattr"
213                | "repr"
214                | "iter"
215                | "next"
216                | "ValueError"
217                | "TypeError"
218                | "KeyError"
219                | "IndexError"
220                | "Exception"
221                | "RuntimeError"
222                | "StopIteration"
223                | "NotImplementedError"
224                | "AttributeError"
225                | "ImportError"
226                | "OSError"
227                | "IOError"
228                | "FileNotFoundError"
229        ),
230        _ => false,
231    }
232}
233
234#[derive(Debug)]
235struct ScopedBinding {
236    name: String,
237    declaration: usize,
238    scope_start: usize,
239    scope_end: usize,
240    module_scope: bool,
241    hoisted: bool,
242}
243
244fn collect_reference_nodes<'a>(
245    node: &Node<'a>,
246    start: usize,
247    end: usize,
248    lang: LangId,
249    out: &mut Vec<Node<'a>>,
250) {
251    if node.end_byte() <= start || node.start_byte() >= end {
252        return;
253    }
254    if matches!(node.kind(), "identifier" | "shorthand_property_identifier")
255        && start <= node.start_byte()
256        && node.end_byte() <= end
257        && !is_property_access(node, lang)
258    {
259        out.push(*node);
260    }
261    let mut cursor = node.walk();
262    for child in node.named_children(&mut cursor) {
263        collect_reference_nodes(&child, start, end, lang, out);
264    }
265}
266
267fn declaration_patterns<'a>(node: &Node<'a>, lang: LangId) -> Vec<Node<'a>> {
268    if matches!(node.kind(), "for_in_statement" | "for_of_statement")
269        && node.child_by_field_name("kind").is_none()
270    {
271        // A loop assignment reuses its existing binding; it does not declare
272        // a new block-local name that could shadow a module variable.
273        return Vec::new();
274    }
275    let field = match (lang, node.kind()) {
276        (
277            _,
278            "variable_declarator"
279            | "function_declaration"
280            | "function_expression"
281            | "function_definition"
282            | "class_declaration"
283            | "class_definition",
284        ) => "name",
285        (LangId::Python, "assignment" | "for_statement") => "left",
286        (LangId::Python, "as_pattern") => "alias",
287        (_, "for_in_statement" | "for_of_statement") => "left",
288        (_, "catch_clause") => "parameter",
289        _ => return Vec::new(),
290    };
291    node.child_by_field_name(field).into_iter().collect()
292}
293
294fn binding_scope<'a>(node: &Node<'a>, lang: LangId) -> Node<'a> {
295    if node.kind() == "function_expression" {
296        return *node;
297    }
298    let function_scoped = lang == LangId::Python
299        || node
300            .child_by_field_name("kind")
301            .is_some_and(|kind| kind.kind() == "var")
302        || (node.kind() == "variable_declarator"
303            && js_declaration_kind_for_declarator(node) == JsDeclarationKind::Var);
304    if matches!(
305        node.kind(),
306        "catch_clause" | "for_in_statement" | "for_of_statement"
307    ) && !function_scoped
308    {
309        return *node;
310    }
311    let mut scope = node.parent().unwrap_or(*node);
312    loop {
313        if is_function_scope_node(&scope, lang)
314            || (!function_scoped
315                && matches!(
316                    scope.kind(),
317                    "statement_block"
318                        | "for_statement"
319                        | "for_in_statement"
320                        | "for_of_statement"
321                        | "catch_clause"
322                ))
323            || scope.parent().is_none()
324        {
325            return scope;
326        }
327        scope = scope.parent().unwrap();
328    }
329}
330
331fn collect_scoped_bindings(node: &Node, source: &str, lang: LangId, out: &mut Vec<ScopedBinding>) {
332    for pattern in declaration_patterns(node, lang) {
333        let scope = binding_scope(node, lang);
334        for name in collect_binding_pattern_names(source, &pattern, lang) {
335            out.push(ScopedBinding {
336                name,
337                declaration: pattern.start_byte(),
338                scope_start: scope.start_byte(),
339                scope_end: scope.end_byte(),
340                module_scope: scope.parent().is_none(),
341                hoisted: matches!(node.kind(), "function_declaration" | "function_definition"),
342            });
343        }
344    }
345    if is_function_scope_node(node, lang) {
346        let mut names = HashSet::new();
347        collect_function_params(node, source, lang, &mut names);
348        for name in names {
349            out.push(ScopedBinding {
350                name,
351                declaration: node.start_byte(),
352                scope_start: node.start_byte(),
353                scope_end: node.end_byte(),
354                module_scope: false,
355                hoisted: true,
356            });
357        }
358    }
359    let mut cursor = node.walk();
360    for child in node.named_children(&mut cursor) {
361        collect_scoped_bindings(&child, source, lang, out);
362    }
363}
364
365/// Collect names declared (via variable declarations) within a byte range.
366fn collect_declarations_in_range(
367    node: &Node,
368    source: &str,
369    start_byte: usize,
370    end_byte: usize,
371    lang: LangId,
372    out: &mut HashSet<String>,
373) {
374    if node.end_byte() <= start_byte || node.start_byte() >= end_byte {
375        return;
376    }
377
378    for pattern in declaration_patterns(node, lang) {
379        if start_byte <= pattern.start_byte() && pattern.end_byte() <= end_byte {
380            out.extend(collect_binding_pattern_names(source, &pattern, lang));
381        }
382    }
383
384    // Recurse
385    let mut cursor = node.walk();
386    if cursor.goto_first_child() {
387        loop {
388            collect_declarations_in_range(&cursor.node(), source, start_byte, end_byte, lang, out);
389            if !cursor.goto_next_sibling() {
390                break;
391            }
392        }
393    }
394}
395
396/// Collect parameter names from a function node.
397fn collect_function_params(fn_node: &Node, source: &str, lang: LangId, out: &mut HashSet<String>) {
398    match lang {
399        LangId::TypeScript | LangId::Tsx | LangId::JavaScript => {
400            // function_declaration / arrow_function have "parameters" field
401            if let Some(params) = fn_node.child_by_field_name("parameters") {
402                collect_param_identifiers(&params, source, lang, out);
403            }
404            // For arrow functions inside lexical_declaration, drill down
405            let mut cursor = fn_node.walk();
406            if cursor.goto_first_child() {
407                loop {
408                    let child = cursor.node();
409                    if child.kind() == "variable_declarator" {
410                        if let Some(value) = child.child_by_field_name("value") {
411                            if value.kind() == "arrow_function" {
412                                if let Some(params) = value.child_by_field_name("parameters") {
413                                    collect_param_identifiers(&params, source, lang, out);
414                                }
415                            }
416                        }
417                    }
418                    if !cursor.goto_next_sibling() {
419                        break;
420                    }
421                }
422            }
423        }
424        LangId::Python => {
425            if let Some(params) = fn_node.child_by_field_name("parameters") {
426                collect_param_identifiers(&params, source, lang, out);
427            }
428        }
429        _ => {}
430    }
431}
432
433/// Walk a parameter list node and collect identifier names.
434fn collect_param_identifiers(
435    params_node: &Node,
436    source: &str,
437    lang: LangId,
438    out: &mut HashSet<String>,
439) {
440    let mut cursor = params_node.walk();
441    if cursor.goto_first_child() {
442        loop {
443            let child = cursor.node();
444            match lang {
445                LangId::TypeScript | LangId::Tsx | LangId::JavaScript => {
446                    // required_parameter, optional_parameter have pattern child,
447                    // or directly identifier
448                    if child.kind() == "required_parameter" || child.kind() == "optional_parameter"
449                    {
450                        if let Some(pattern) = child.child_by_field_name("pattern") {
451                            out.extend(collect_binding_pattern_names(source, &pattern, lang));
452                        }
453                    } else {
454                        out.extend(collect_binding_pattern_names(source, &child, lang));
455                    }
456                }
457                LangId::Python => {
458                    let binding = match child.kind() {
459                        "default_parameter" | "typed_default_parameter" => {
460                            child.child_by_field_name("name")
461                        }
462                        "typed_parameter" => child.named_child(0),
463                        "identifier" | "list_splat_pattern" | "dictionary_splat_pattern" => {
464                            Some(child)
465                        }
466                        _ => None,
467                    };
468                    if let Some(binding) = binding {
469                        out.extend(
470                            collect_binding_pattern_names(source, &binding, lang)
471                                .into_iter()
472                                .filter(|name| name != "self"),
473                        );
474                    }
475                }
476                _ => {}
477            }
478            if !cursor.goto_next_sibling() {
479                break;
480            }
481        }
482    }
483}
484
485/// Find the innermost function node that encloses `byte_pos`.
486fn find_enclosing_function<'a>(root: &Node<'a>, byte_pos: usize, lang: LangId) -> Option<Node<'a>> {
487    find_deepest_function_ancestor(root, byte_pos, lang)
488}
489
490/// Find the deepest function-like ancestor that contains `byte_pos`.
491fn find_deepest_function_ancestor<'a>(
492    node: &Node<'a>,
493    byte_pos: usize,
494    lang: LangId,
495) -> Option<Node<'a>> {
496    let mut result: Option<Node<'a>> = None;
497    if is_function_like_boundary(node, byte_pos, lang)
498        && node.start_byte() <= byte_pos
499        && byte_pos < node.end_byte()
500    {
501        result = Some(*node);
502    }
503
504    let child_count = node.child_count();
505    for i in 0..child_count {
506        if let Some(child) = node.child(i as u32) {
507            if child.start_byte() <= byte_pos && byte_pos < child.end_byte() {
508                if let Some(deeper) = find_deepest_function_ancestor(&child, byte_pos, lang) {
509                    result = Some(deeper);
510                }
511            }
512        }
513    }
514
515    result
516}
517
518fn is_function_like_boundary(node: &Node, byte_pos: usize, lang: LangId) -> bool {
519    match lang {
520        LangId::TypeScript | LangId::Tsx | LangId::JavaScript => match node.kind() {
521            "function_declaration"
522            | "method_definition"
523            | "arrow_function"
524            | "function_expression" => true,
525            "lexical_declaration" => lexical_declaration_has_function_initializer(node, byte_pos),
526            _ => false,
527        },
528        LangId::Python => node.kind() == "function_definition",
529        _ => false,
530    }
531}
532
533fn lexical_declaration_has_function_initializer(node: &Node, byte_pos: usize) -> bool {
534    let mut cursor = node.walk();
535    if cursor.goto_first_child() {
536        loop {
537            let child = cursor.node();
538            if child.kind() == "variable_declarator" {
539                if let Some(value) = child.child_by_field_name("value") {
540                    if matches!(value.kind(), "arrow_function" | "function_expression")
541                        && child.start_byte() <= byte_pos
542                        && byte_pos < child.end_byte()
543                    {
544                        return true;
545                    }
546                }
547            }
548            if !cursor.goto_next_sibling() {
549                break;
550            }
551        }
552    }
553
554    false
555}
556
557/// Check if `this` (JS/TS) or `self` (Python) appears in the byte range.
558fn check_this_or_self(
559    node: &Node,
560    source: &str,
561    start_byte: usize,
562    end_byte: usize,
563    lang: LangId,
564) -> bool {
565    if node.end_byte() <= start_byte || node.start_byte() >= end_byte {
566        return false;
567    }
568
569    if node.start_byte() >= start_byte && node.end_byte() <= end_byte {
570        let kind = node.kind();
571        match lang {
572            LangId::TypeScript | LangId::Tsx | LangId::JavaScript => {
573                if kind == "this" {
574                    return true;
575                }
576            }
577            LangId::Python => {
578                if kind == "identifier" && node_text(source, node) == "self" {
579                    // Check it's not a parameter declaration (like `def foo(self):`)
580                    if let Some(parent) = node.parent() {
581                        if parent.kind() == "parameters" {
582                            return false;
583                        }
584                    }
585                    return true;
586                }
587            }
588            _ => {}
589        }
590    }
591
592    let mut cursor = node.walk();
593    if cursor.goto_first_child() {
594        loop {
595            if check_this_or_self(&cursor.node(), source, start_byte, end_byte, lang) {
596                return true;
597            }
598            if !cursor.goto_next_sibling() {
599                break;
600            }
601        }
602    }
603
604    false
605}
606
607// ---------------------------------------------------------------------------
608// Return value detection
609// ---------------------------------------------------------------------------
610
611/// What the extracted function should return.
612#[derive(Debug, Clone, PartialEq, Eq)]
613pub enum ReturnKind {
614    /// The range contains an explicit `return expr;` → use that expression
615    Expression(String),
616    /// A variable declared in-range is used after the range in the enclosing function
617    Variable(String),
618    /// Multiple variables declared in-range are used after the range.
619    Variables(Vec<String>),
620    /// Nothing needs to be returned (void)
621    Void,
622}
623
624const RETURN_VARIABLE_ASSIGNMENT_PREFIX: &str = "\0assignment:";
625
626#[derive(Debug, Clone, Copy, PartialEq, Eq)]
627enum JsDeclarationKind {
628    Const,
629    Let,
630    Var,
631    Assignment,
632}
633
634impl JsDeclarationKind {
635    fn label(self) -> &'static str {
636        match self {
637            Self::Const => "const",
638            Self::Let => "let",
639            Self::Var => "var",
640            Self::Assignment => "assignment",
641        }
642    }
643
644    fn multi_value_group(self) -> u8 {
645        match self {
646            Self::Const => 0,
647            Self::Let | Self::Var => 1,
648            Self::Assignment => 2,
649        }
650    }
651}
652
653#[derive(Debug, Clone, PartialEq, Eq)]
654struct ReturnVariableBinding {
655    name: String,
656    bound_names: Vec<String>,
657    js_kind: JsDeclarationKind,
658    representable: bool,
659}
660
661impl ReturnVariableBinding {
662    fn encoded_for_return_kind(&self) -> String {
663        match self.js_kind {
664            JsDeclarationKind::Const => self.name.clone(),
665            JsDeclarationKind::Let => format!("let {}", self.name),
666            JsDeclarationKind::Var => format!("var {}", self.name),
667            JsDeclarationKind::Assignment => {
668                format!("{}{}", RETURN_VARIABLE_ASSIGNMENT_PREFIX, self.name)
669            }
670        }
671    }
672}
673
674fn parse_return_variable(var: &str) -> ReturnVariableBinding {
675    if let Some(name) = var.strip_prefix(RETURN_VARIABLE_ASSIGNMENT_PREFIX) {
676        return ReturnVariableBinding {
677            name: name.to_string(),
678            bound_names: vec![name.to_string()],
679            js_kind: JsDeclarationKind::Assignment,
680            representable: true,
681        };
682    }
683
684    for (prefix, js_kind) in [
685        ("let ", JsDeclarationKind::Let),
686        ("var ", JsDeclarationKind::Var),
687        ("const ", JsDeclarationKind::Const),
688    ] {
689        if let Some(name) = var.strip_prefix(prefix) {
690            return ReturnVariableBinding {
691                name: name.to_string(),
692                bound_names: vec![name.to_string()],
693                js_kind,
694                representable: true,
695            };
696        }
697    }
698
699    ReturnVariableBinding {
700        name: var.to_string(),
701        bound_names: vec![var.to_string()],
702        js_kind: JsDeclarationKind::Const,
703        representable: true,
704    }
705}
706
707#[derive(Debug, Clone, PartialEq, Eq)]
708pub struct ReturnValueError {
709    pub message: String,
710}
711
712/// Detect what the extracted code range should return.
713///
714/// Every live-out binding must be represented in the generated call. Unsupported
715/// binding shapes and incompatible JavaScript declaration kinds are rejected
716/// rather than allowing an extraction to silently discard caller state.
717pub fn detect_return_value(
718    source: &str,
719    tree: &Tree,
720    start_byte: usize,
721    end_byte: usize,
722    enclosing_fn_end_byte: Option<usize>,
723    lang: LangId,
724) -> Result<ReturnKind, ReturnValueError> {
725    let root = tree.root_node();
726    let effective_enclosing_fn_end_byte = find_enclosing_function(&root, start_byte, lang)
727        .map(|node| node.end_byte())
728        .or(enclosing_fn_end_byte);
729
730    let in_range_bindings =
731        collect_return_bindings_in_range(&root, source, start_byte, end_byte, lang);
732    let mut live_bindings = Vec::new();
733
734    // Check if any in-range declaration is used after the range in the enclosing fn
735    if let Some(fn_end) = effective_enclosing_fn_end_byte {
736        let post_range_end = fn_end.min(source.len());
737        if end_byte < post_range_end {
738            let mut post_refs: Vec<String> = Vec::new();
739            collect_identifier_refs(
740                &root,
741                source,
742                end_byte,
743                post_range_end,
744                lang,
745                &mut post_refs,
746            );
747
748            let mut seen = HashSet::new();
749            for binding in in_range_bindings {
750                let live_names = binding
751                    .bound_names
752                    .iter()
753                    .filter(|name| post_refs.contains(name))
754                    .cloned()
755                    .collect::<Vec<_>>();
756                if live_names.is_empty() {
757                    continue;
758                }
759                if !binding.representable {
760                    return Err(ReturnValueError {
761                        message: format!(
762                            "extract_function cannot preserve unsupported live-out binding shape '{}' (bindings: {})",
763                            binding.name,
764                            live_names.join(", ")
765                        ),
766                    });
767                }
768                if seen.insert(binding.name.clone()) {
769                    live_bindings.push(binding);
770                }
771            }
772        }
773    }
774
775    if let Some(expr) = find_return_in_range(&root, source, start_byte, end_byte, lang) {
776        if !live_bindings.is_empty() {
777            return Err(ReturnValueError {
778                message: format!(
779                    "extract_function cannot preserve explicit return together with live-out bindings: {}",
780                    live_bindings
781                        .iter()
782                        .map(|binding| binding.name.as_str())
783                        .collect::<Vec<_>>()
784                        .join(", ")
785                ),
786            });
787        }
788        return Ok(ReturnKind::Expression(expr));
789    }
790
791    match live_bindings.as_slice() {
792        [] => Ok(ReturnKind::Void),
793        [binding] => Ok(ReturnKind::Variable(binding.encoded_for_return_kind())),
794        bindings => {
795            if matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript) {
796                let group = bindings[0].js_kind.multi_value_group();
797                if bindings
798                    .iter()
799                    .any(|binding| binding.js_kind.multi_value_group() != group)
800                {
801                    return Err(ReturnValueError {
802                        message: format!(
803                            "extract_function cannot preserve mixed live-out binding kinds: {}",
804                            bindings
805                                .iter()
806                                .map(|binding| format!(
807                                    "{} ({})",
808                                    binding.name,
809                                    binding.js_kind.label()
810                                ))
811                                .collect::<Vec<_>>()
812                                .join(", ")
813                        ),
814                    });
815                }
816            }
817            Ok(ReturnKind::Variables(
818                bindings
819                    .iter()
820                    .map(ReturnVariableBinding::encoded_for_return_kind)
821                    .collect(),
822            ))
823        }
824    }
825}
826
827/// Collect in-range names that can be returned to preserve post-range uses.
828fn collect_return_bindings_in_range(
829    node: &Node,
830    source: &str,
831    start_byte: usize,
832    end_byte: usize,
833    lang: LangId,
834) -> Vec<ReturnVariableBinding> {
835    let mut bindings = Vec::new();
836    collect_return_bindings_recursive(node, source, start_byte, end_byte, lang, &mut bindings);
837    bindings
838}
839
840fn collect_return_bindings_recursive(
841    node: &Node,
842    source: &str,
843    start_byte: usize,
844    end_byte: usize,
845    lang: LangId,
846    out: &mut Vec<ReturnVariableBinding>,
847) {
848    if node.end_byte() <= start_byte || node.start_byte() >= end_byte {
849        return;
850    }
851
852    match lang {
853        LangId::TypeScript | LangId::Tsx | LangId::JavaScript => {
854            if node.kind() == "variable_declarator" {
855                if let Some(name_node) = node.child_by_field_name("name") {
856                    if name_node.start_byte() >= start_byte && name_node.end_byte() <= end_byte {
857                        let name = node_text(source, &name_node).to_string();
858                        let bound_names = collect_binding_pattern_names(source, &name_node, lang);
859                        out.push(ReturnVariableBinding {
860                            representable: name_node.kind() == "identifier",
861                            name,
862                            bound_names,
863                            js_kind: js_declaration_kind_for_declarator(node),
864                        });
865                    }
866                }
867            } else if is_assignment_node(node) {
868                if let Some(left) = node.child_by_field_name("left") {
869                    if left.start_byte() >= start_byte && left.end_byte() <= end_byte {
870                        let name = node_text(source, &left).to_string();
871                        out.push(ReturnVariableBinding {
872                            representable: left.kind() == "identifier",
873                            bound_names: collect_binding_pattern_names(source, &left, lang),
874                            name,
875                            js_kind: JsDeclarationKind::Assignment,
876                        });
877                    }
878                }
879            }
880        }
881        LangId::Python => {
882            if node.kind() == "assignment" {
883                if let Some(left) = node.child_by_field_name("left") {
884                    if left.start_byte() >= start_byte && left.end_byte() <= end_byte {
885                        let name = node_text(source, &left).to_string();
886                        out.push(ReturnVariableBinding {
887                            representable: left.kind() == "identifier",
888                            bound_names: collect_binding_pattern_names(source, &left, lang),
889                            name,
890                            js_kind: JsDeclarationKind::Assignment,
891                        });
892                    }
893                }
894            }
895        }
896        _ => {}
897    }
898
899    let child_count = node.child_count();
900    for i in 0..child_count {
901        if let Some(child) = node.child(i as u32) {
902            collect_return_bindings_recursive(&child, source, start_byte, end_byte, lang, out);
903        }
904    }
905}
906
907fn collect_binding_pattern_names(source: &str, node: &Node, lang: LangId) -> Vec<String> {
908    fn collect(source: &str, node: &Node, lang: LangId, out: &mut Vec<String>) {
909        match node.kind() {
910            "identifier" | "shorthand_property_identifier_pattern" => {
911                let name = node_text(source, node).to_string();
912                if !out.contains(&name) {
913                    out.push(name);
914                }
915            }
916            "pair_pattern" => {
917                if let Some(value) = node.child_by_field_name("value") {
918                    collect(source, &value, lang, out);
919                }
920            }
921            "assignment_pattern" => {
922                if let Some(left) = node.child_by_field_name("left") {
923                    collect(source, &left, lang, out);
924                }
925            }
926            "object_pattern" | "array_pattern" | "rest_pattern"
927                if matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript) =>
928            {
929                for index in 0..node.named_child_count() as u32 {
930                    if let Some(child) = node.named_child(index) {
931                        collect(source, &child, lang, out);
932                    }
933                }
934            }
935            "pattern_list"
936            | "tuple_pattern"
937            | "list_pattern"
938            | "list"
939            | "tuple"
940            | "starred_expression"
941            | "list_splat_pattern"
942            | "dictionary_splat_pattern"
943            | "as_pattern_target"
944                if lang == LangId::Python =>
945            {
946                for index in 0..node.named_child_count() as u32 {
947                    if let Some(child) = node.named_child(index) {
948                        collect(source, &child, lang, out);
949                    }
950                }
951            }
952            _ => {}
953        }
954    }
955
956    let mut names = Vec::new();
957    collect(source, node, lang, &mut names);
958    names
959}
960
961fn js_declaration_kind_for_declarator(node: &Node) -> JsDeclarationKind {
962    let Some(parent) = node.parent() else {
963        return JsDeclarationKind::Const;
964    };
965
966    match parent.kind() {
967        "variable_declaration" => JsDeclarationKind::Var,
968        "lexical_declaration" => {
969            let mut cursor = parent.walk();
970            if cursor.goto_first_child() {
971                loop {
972                    let child = cursor.node();
973                    match child.kind() {
974                        "let" => return JsDeclarationKind::Let,
975                        "const" => return JsDeclarationKind::Const,
976                        _ => {}
977                    }
978                    if !cursor.goto_next_sibling() {
979                        break;
980                    }
981                }
982            }
983            JsDeclarationKind::Const
984        }
985        _ => JsDeclarationKind::Const,
986    }
987}
988
989fn is_assignment_node(node: &Node) -> bool {
990    matches!(
991        node.kind(),
992        "assignment_expression" | "augmented_assignment_expression" | "assignment"
993    )
994}
995
996/// Visit only control flow belonging to the selected scope. Function bodies
997/// introduced inside the selection keep their own returns and suspension points.
998fn visit_extracted_control_flow(
999    node: &Node,
1000    start: usize,
1001    end: usize,
1002    lang: LangId,
1003    visitor: &mut impl FnMut(&Node) -> bool,
1004) -> bool {
1005    if node.end_byte() <= start || node.start_byte() >= end {
1006        return false;
1007    }
1008    let function = is_function_scope_node(node, lang)
1009        || (matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript)
1010            && matches!(
1011                node.kind(),
1012                "generator_function" | "generator_function_declaration"
1013            ));
1014    if function && node.start_byte() >= start {
1015        return false;
1016    }
1017    if node.start_byte() >= start && visitor(node) {
1018        return true;
1019    }
1020    let mut cursor = node.walk();
1021    for child in node.named_children(&mut cursor) {
1022        if visit_extracted_control_flow(&child, start, end, lang, visitor) {
1023            return true;
1024        }
1025    }
1026    false
1027}
1028
1029/// Refuse constructs whose caller-exit or async/generator semantics cannot be
1030/// represented by the plain helper and call site, before taking a backup or writing.
1031pub fn unsupported_extraction_control_flow(
1032    tree: &Tree,
1033    start: usize,
1034    end: usize,
1035    lang: LangId,
1036) -> Option<&'static str> {
1037    let mut reason = None;
1038    visit_extracted_control_flow(&tree.root_node(), start, end, lang, &mut |node| {
1039        reason = match node.kind() {
1040            "return_statement" => {
1041                let mut cursor = node.walk();
1042                let has_value = node.named_children(&mut cursor).any(|child| !child.is_extra());
1043                (!has_value).then_some("extract_function: selected range contains an outer bare return; caller exit cannot be preserved")
1044            }
1045            "await_expression" | "await" => Some("extract_function: selected range contains outer await; async extraction is not supported"),
1046            "yield_expression" | "yield" => Some("extract_function: selected range contains outer yield; generator extraction is not supported"),
1047            _ => None,
1048        };
1049        reason.is_some()
1050    });
1051    reason
1052}
1053
1054/// Find a fully selected outer return expression without entering nested functions.
1055fn find_return_in_range(
1056    node: &Node,
1057    source: &str,
1058    start: usize,
1059    end: usize,
1060    lang: LangId,
1061) -> Option<String> {
1062    let mut expression = None;
1063    visit_extracted_control_flow(node, start, end, lang, &mut |node| {
1064        if node.kind() == "return_statement" && node.end_byte() <= end {
1065            let text = node_text(source, node).trim();
1066            let value = text
1067                .strip_prefix("return")
1068                .unwrap_or("")
1069                .trim()
1070                .trim_end_matches(';')
1071                .trim();
1072            if !value.is_empty() {
1073                expression = Some(value.to_string());
1074                return true;
1075            }
1076        }
1077        false
1078    });
1079    expression
1080}
1081
1082// ---------------------------------------------------------------------------
1083// Function generation
1084// ---------------------------------------------------------------------------
1085
1086/// Generate the text for an extracted function.
1087pub fn generate_extracted_function(
1088    name: &str,
1089    params: &[String],
1090    return_kind: &ReturnKind,
1091    body_text: &str,
1092    base_indent: &str,
1093    lang: LangId,
1094    indent_style: IndentStyle,
1095    line_ending: &str,
1096) -> String {
1097    let indent_unit = indent_style.as_str();
1098
1099    match lang {
1100        LangId::TypeScript | LangId::Tsx | LangId::JavaScript => generate_ts_function(
1101            name,
1102            params,
1103            return_kind,
1104            body_text,
1105            base_indent,
1106            indent_unit,
1107            line_ending,
1108        ),
1109        LangId::Python => generate_py_function(
1110            name,
1111            params,
1112            return_kind,
1113            body_text,
1114            base_indent,
1115            indent_unit,
1116            line_ending,
1117        ),
1118        _ => {
1119            // Shouldn't reach here due to language guard, but produce something reasonable
1120            generate_ts_function(
1121                name,
1122                params,
1123                return_kind,
1124                body_text,
1125                base_indent,
1126                indent_unit,
1127                line_ending,
1128            )
1129        }
1130    }
1131}
1132
1133fn generate_ts_function(
1134    name: &str,
1135    params: &[String],
1136    return_kind: &ReturnKind,
1137    body_text: &str,
1138    base_indent: &str,
1139    indent_unit: &str,
1140    line_ending: &str,
1141) -> String {
1142    let params_str = params.join(", ");
1143    let mut lines = Vec::new();
1144
1145    lines.push(format!(
1146        "{}function {}({}) {{",
1147        base_indent, name, params_str
1148    ));
1149
1150    let body = reindent_body(body_text, base_indent, indent_unit, LangId::TypeScript);
1151    if !body.is_empty() {
1152        lines.push(body);
1153    }
1154
1155    // Add return statement if needed
1156    match return_kind {
1157        ReturnKind::Variable(var) => {
1158            let binding = parse_return_variable(var);
1159            lines.push(format!(
1160                "{}{}return {};",
1161                base_indent, indent_unit, binding.name
1162            ));
1163        }
1164        ReturnKind::Variables(vars) => {
1165            let names = vars
1166                .iter()
1167                .map(|var| parse_return_variable(var).name)
1168                .collect::<Vec<_>>()
1169                .join(", ");
1170            lines.push(format!(
1171                "{}{}return {{ {} }};",
1172                base_indent, indent_unit, names
1173            ));
1174        }
1175        ReturnKind::Expression(_) => {
1176            // The return is already in the body text
1177        }
1178        ReturnKind::Void => {}
1179    }
1180
1181    lines.push(format!("{}}}", base_indent));
1182    lines.join(line_ending)
1183}
1184
1185fn generate_py_function(
1186    name: &str,
1187    params: &[String],
1188    return_kind: &ReturnKind,
1189    body_text: &str,
1190    base_indent: &str,
1191    indent_unit: &str,
1192    line_ending: &str,
1193) -> String {
1194    let params_str = params.join(", ");
1195    let mut lines = Vec::new();
1196
1197    lines.push(format!("{}def {}({}):", base_indent, name, params_str));
1198
1199    let body = reindent_body(body_text, base_indent, indent_unit, LangId::Python);
1200    if !body.is_empty() {
1201        lines.push(body);
1202    }
1203
1204    // Add return statement if needed
1205    match return_kind {
1206        ReturnKind::Variable(var) => {
1207            let binding = parse_return_variable(var);
1208            lines.push(format!(
1209                "{}{}return {}",
1210                base_indent, indent_unit, binding.name
1211            ));
1212        }
1213        ReturnKind::Variables(vars) => {
1214            let names = vars
1215                .iter()
1216                .map(|var| parse_return_variable(var).name)
1217                .collect::<Vec<_>>()
1218                .join(", ");
1219            lines.push(format!("{}{}return {}", base_indent, indent_unit, names));
1220        }
1221        ReturnKind::Expression(_) => {
1222            // Already in body
1223        }
1224        ReturnKind::Void => {}
1225    }
1226
1227    lines.join(line_ending)
1228}
1229
1230/// Interior rows of multiline literals contain data, not syntactic indentation.
1231/// Keep those rows byte-for-byte while moving only the surrounding code.
1232fn reindent_body(body: &str, base: &str, unit: &str, lang: LangId) -> String {
1233    fn protect(node: &Node, protected: &mut HashSet<usize>) {
1234        if matches!(node.kind(), "string" | "template_string")
1235            && node.start_position().row < node.end_position().row
1236        {
1237            protected.extend(node.start_position().row + 1..=node.end_position().row);
1238            return;
1239        }
1240        let mut cursor = node.walk();
1241        for child in node.named_children(&mut cursor) {
1242            protect(&child, protected);
1243        }
1244    }
1245    let mut protected = HashSet::new();
1246    if let Ok(tree) =
1247        crate::parser::parse_source_with_cached_parser(std::path::Path::new("body"), body, lang)
1248    {
1249        protect(&tree.root_node(), &mut protected);
1250    }
1251    let code_lines = body
1252        .lines()
1253        .enumerate()
1254        .filter(|(row, _)| !protected.contains(row))
1255        .map(|(_, line)| line)
1256        .collect::<Vec<_>>()
1257        .join("\n");
1258    let common = common_leading_indent(&code_lines);
1259    let mut result = String::new();
1260    let mut rows = body.split_inclusive('\n').enumerate().peekable();
1261    while let Some((row, segment)) = rows.next() {
1262        let ending = if segment.ends_with("\r\n") {
1263            "\r\n"
1264        } else if segment.ends_with('\n') {
1265            "\n"
1266        } else {
1267            ""
1268        };
1269        let line = &segment[..segment.len() - ending.len()];
1270        if protected.contains(&row) {
1271            result.push_str(line);
1272        } else if !line.trim().is_empty() {
1273            result.push_str(base);
1274            result.push_str(unit);
1275            result.push_str(strip_leading_indent(line, &common));
1276        }
1277        if rows.peek().is_some() {
1278            result.push_str(ending);
1279        }
1280    }
1281    result
1282}
1283
1284fn common_leading_indent(text: &str) -> String {
1285    let mut lines = text.lines().filter(|line| !line.trim().is_empty());
1286    let Some(first) = lines.next() else {
1287        return String::new();
1288    };
1289
1290    let mut common = leading_whitespace(first).to_string();
1291    for line in lines {
1292        let indent = leading_whitespace(line);
1293        let common_len = common
1294            .char_indices()
1295            .zip(indent.char_indices())
1296            .take_while(|((_, left), (_, right))| left == right)
1297            .map(|((idx, ch), _)| idx + ch.len_utf8())
1298            .last()
1299            .unwrap_or(0);
1300        common.truncate(common_len);
1301        if common.is_empty() {
1302            break;
1303        }
1304    }
1305
1306    common
1307}
1308
1309fn leading_whitespace(line: &str) -> &str {
1310    let trimmed = line.trim_start_matches(|ch: char| ch == ' ' || ch == '\t');
1311    &line[..line.len() - trimmed.len()]
1312}
1313
1314fn strip_leading_indent<'a>(line: &'a str, indent: &str) -> &'a str {
1315    if indent.is_empty() {
1316        line
1317    } else {
1318        line.strip_prefix(indent).unwrap_or(line)
1319    }
1320}
1321
1322/// Generate the call site text that replaces the extracted range.
1323pub fn generate_call_site(
1324    name: &str,
1325    params: &[String],
1326    return_kind: &ReturnKind,
1327    indent: &str,
1328    lang: LangId,
1329) -> String {
1330    let args_str = params.join(", ");
1331
1332    match return_kind {
1333        ReturnKind::Variable(var) => match lang {
1334            LangId::TypeScript | LangId::Tsx | LangId::JavaScript => {
1335                let binding = parse_return_variable(var);
1336                match binding.js_kind {
1337                    JsDeclarationKind::Const => {
1338                        format!("{}const {} = {}({});", indent, binding.name, name, args_str)
1339                    }
1340                    JsDeclarationKind::Let => {
1341                        format!("{}let {} = {}({});", indent, binding.name, name, args_str)
1342                    }
1343                    JsDeclarationKind::Var => {
1344                        format!("{}var {} = {}({});", indent, binding.name, name, args_str)
1345                    }
1346                    JsDeclarationKind::Assignment => {
1347                        format!("{}{} = {}({});", indent, binding.name, name, args_str)
1348                    }
1349                }
1350            }
1351            LangId::Python => {
1352                let binding = parse_return_variable(var);
1353                format!("{}{} = {}({})", indent, binding.name, name, args_str)
1354            }
1355            _ => format!("{}const {} = {}({});", indent, var, name, args_str),
1356        },
1357        ReturnKind::Variables(vars) => {
1358            let bindings = vars
1359                .iter()
1360                .map(|var| parse_return_variable(var))
1361                .collect::<Vec<_>>();
1362            let names = bindings
1363                .iter()
1364                .map(|binding| binding.name.as_str())
1365                .collect::<Vec<_>>()
1366                .join(", ");
1367            match lang {
1368                LangId::TypeScript | LangId::Tsx | LangId::JavaScript => {
1369                    let declaration = match bindings[0].js_kind.multi_value_group() {
1370                        0 => "const ",
1371                        1 => "let ",
1372                        2 => "",
1373                        _ => unreachable!(),
1374                    };
1375                    if declaration.is_empty() {
1376                        format!("{}({{ {} }} = {}({}));", indent, names, name, args_str)
1377                    } else {
1378                        format!(
1379                            "{}{}{{ {} }} = {}({});",
1380                            indent, declaration, names, name, args_str
1381                        )
1382                    }
1383                }
1384                LangId::Python => format!("{}{} = {}({})", indent, names, name, args_str),
1385                _ => format!("{}const {{ {} }} = {}({});", indent, names, name, args_str),
1386            }
1387        }
1388        ReturnKind::Expression(_expr) => match lang {
1389            LangId::TypeScript | LangId::Tsx | LangId::JavaScript => {
1390                format!("{}return {}({});", indent, name, args_str)
1391            }
1392            LangId::Python => {
1393                format!("{}return {}({})", indent, name, args_str)
1394            }
1395            _ => format!("{}return {}({});", indent, name, args_str),
1396        },
1397        ReturnKind::Void => match lang {
1398            LangId::TypeScript | LangId::Tsx | LangId::JavaScript => {
1399                format!("{}{}({});", indent, name, args_str)
1400            }
1401            LangId::Python => {
1402                format!("{}{}({})", indent, name, args_str)
1403            }
1404            _ => format!("{}{}({});", indent, name, args_str),
1405        },
1406    }
1407}
1408
1409// ---------------------------------------------------------------------------
1410// Inline symbol utilities
1411// ---------------------------------------------------------------------------
1412
1413/// A detected scope conflict when inlining a function body at a call site.
1414#[derive(Debug, Clone, PartialEq, Eq)]
1415pub struct ScopeConflict {
1416    /// The variable name that conflicts.
1417    pub name: String,
1418    /// Suggested alternative name to avoid the conflict.
1419    pub suggested: String,
1420}
1421
1422/// Detect scope conflicts between the call site scope and the function body
1423/// being inlined.
1424///
1425/// Collects all variable declarations at the call site's scope level
1426/// (surrounding function body), then checks for collisions with variables
1427/// declared in `body_text`.
1428pub fn detect_scope_conflicts(
1429    source: &str,
1430    tree: &Tree,
1431    insertion_byte: usize,
1432    _param_names: &[String],
1433    body_text: &str,
1434    lang: LangId,
1435) -> Result<Vec<ScopeConflict>, crate::error::AftError> {
1436    let root = tree.root_node();
1437
1438    // 1. Find the enclosing function at the call site
1439    let enclosing_fn = find_enclosing_function(&root, insertion_byte, lang);
1440
1441    // 2. Collect all declarations in the call site's scope
1442    let mut scope_decls: HashSet<String> = HashSet::new();
1443    if let Some(fn_node) = enclosing_fn {
1444        collect_declarations_in_range(
1445            &fn_node,
1446            source,
1447            fn_node.start_byte(),
1448            fn_node.end_byte(),
1449            lang,
1450            &mut scope_decls,
1451        );
1452        collect_function_params(&fn_node, source, lang, &mut scope_decls);
1453    } else {
1454        // Module-level: collect all top-level declarations
1455        collect_declarations_in_range(
1456            &root,
1457            source,
1458            root.start_byte(),
1459            root.end_byte(),
1460            lang,
1461            &mut scope_decls,
1462        );
1463    }
1464
1465    // 3. Collect declarations in the body being inlined
1466    let mut body_decls: HashSet<String> = HashSet::new();
1467    let body_tree = crate::parser::FileParser::parse_source(
1468        std::path::Path::new("<inline-body>"),
1469        body_text,
1470        lang,
1471    )?;
1472    let body_root = body_tree.root_node();
1473    collect_declarations_in_range(
1474        &body_root,
1475        body_text,
1476        0,
1477        body_text.len(),
1478        lang,
1479        &mut body_decls,
1480    );
1481
1482    // 4. Find collisions
1483    let mut conflicts = Vec::new();
1484    for decl in &body_decls {
1485        if scope_decls.contains(decl) {
1486            conflicts.push(ScopeConflict {
1487                name: decl.clone(),
1488                suggested: format!("{}_inlined", decl),
1489            });
1490        }
1491    }
1492
1493    // Sort for deterministic output
1494    conflicts.sort_by(|a, b| a.name.cmp(&b.name));
1495    Ok(conflicts)
1496}
1497
1498/// Validate that a function has at most one return statement (suitable for inlining).
1499///
1500/// - Arrow functions with expression bodies (no `return` keyword) → valid (single-return)
1501/// - Functions with 0 returns (void) → valid
1502/// - Functions with exactly 1 return → valid
1503/// - Functions with >1 return → invalid, returns the count
1504pub fn validate_single_return(
1505    source: &str,
1506    _tree: &Tree,
1507    fn_node: &Node,
1508    lang: LangId,
1509) -> Result<(), usize> {
1510    // Arrow functions with expression bodies are always single-return
1511    if lang != LangId::Python && fn_node.kind() == "arrow_function" {
1512        if let Some(body) = fn_node.child_by_field_name("body") {
1513            if body.kind() != "statement_block" {
1514                // Expression body — implicitly single-return
1515                return Ok(());
1516            }
1517        }
1518    }
1519
1520    let count = count_return_statements(fn_node, source);
1521    if count > 1 {
1522        Err(count)
1523    } else {
1524        Ok(())
1525    }
1526}
1527
1528/// Count `return_statement` nodes in a function body (non-recursive into nested functions).
1529fn count_return_statements(node: &Node, source: &str) -> usize {
1530    let _ = source;
1531    let mut count = 0;
1532
1533    // Don't count returns in nested function bodies
1534    let nested_fn_kinds = [
1535        "function_declaration",
1536        "function_definition",
1537        "arrow_function",
1538        "method_definition",
1539    ];
1540
1541    let kind = node.kind();
1542    if kind == "return_statement" {
1543        return 1;
1544    }
1545
1546    let child_count = node.child_count();
1547    for i in 0..child_count {
1548        if let Some(child) = node.child(i as u32) {
1549            // Skip nested function definitions
1550            if nested_fn_kinds.contains(&child.kind()) {
1551                continue;
1552            }
1553            count += count_return_statements(&child, source);
1554        }
1555    }
1556
1557    count
1558}
1559
1560/// Substitute parameter names with argument expressions in a function body.
1561///
1562/// Uses tree-sitter to find `identifier` nodes matching parameter names,
1563/// replacing from end to start to preserve byte offsets. Only replaces
1564/// whole-word matches (identifiers, not substrings).
1565pub fn substitute_params(
1566    body_text: &str,
1567    param_to_arg: &std::collections::HashMap<String, String>,
1568    lang: LangId,
1569) -> Result<String, crate::error::AftError> {
1570    if param_to_arg.is_empty() && lang != LangId::Luau {
1571        return Ok(body_text.to_string());
1572    }
1573
1574    let tree = crate::parser::FileParser::parse_source(
1575        std::path::Path::new("<substitution-body>"),
1576        body_text,
1577        lang,
1578    )?;
1579
1580    // Collect identifier references that are still bound to the inlined function's
1581    // parameters. Nested functions and local shadowing declarations are skipped.
1582    let mut replacements: Vec<(usize, usize, String)> = Vec::new();
1583    let shadowed = HashSet::new();
1584    collect_param_replacements(
1585        &tree.root_node(),
1586        body_text,
1587        param_to_arg,
1588        lang,
1589        &shadowed,
1590        true,
1591        &mut replacements,
1592    );
1593
1594    // Sort by start position descending so replacements don't shift offsets
1595    replacements.sort_by(|a, b| b.0.cmp(&a.0));
1596
1597    let mut result = body_text.to_string();
1598    for (start, end, replacement) in replacements {
1599        result = format!("{}{}{}", &result[..start], replacement, &result[end..]);
1600    }
1601
1602    Ok(result)
1603}
1604
1605/// Collect identifier nodes that match parameter names for substitution.
1606fn collect_param_replacements(
1607    node: &Node,
1608    source: &str,
1609    param_to_arg: &std::collections::HashMap<String, String>,
1610    lang: LangId,
1611    shadowed: &HashSet<String>,
1612    is_root: bool,
1613    out: &mut Vec<(usize, usize, String)>,
1614) {
1615    if !is_root && is_function_scope_node(node, lang) {
1616        return;
1617    }
1618
1619    let mut current_shadowed = shadowed.clone();
1620    collect_shadowing_bindings_in_scope(node, source, param_to_arg, lang, &mut current_shadowed);
1621
1622    let kind = node.kind();
1623
1624    if kind == "identifier" {
1625        // Check it's not a property access
1626        if !is_property_access(node, lang) && !is_binding_identifier(node) {
1627            let name = node_text(source, node);
1628            if !current_shadowed.contains(name) {
1629                if let Some(replacement) = param_to_arg.get(name) {
1630                    out.push((node.start_byte(), node.end_byte(), replacement.clone()));
1631                }
1632            }
1633        }
1634    }
1635
1636    // Also handle Python-specific name node
1637    // Recurse into children
1638    let child_count = node.child_count();
1639    for i in 0..child_count {
1640        if let Some(child) = node.child(i as u32) {
1641            collect_param_replacements(
1642                &child,
1643                source,
1644                param_to_arg,
1645                lang,
1646                &current_shadowed,
1647                false,
1648                out,
1649            );
1650        }
1651    }
1652}
1653
1654fn collect_shadowing_bindings_in_scope(
1655    scope: &Node,
1656    source: &str,
1657    param_to_arg: &std::collections::HashMap<String, String>,
1658    lang: LangId,
1659    out: &mut HashSet<String>,
1660) {
1661    collect_shadowing_bindings_in_scope_recursive(
1662        scope,
1663        scope.id(),
1664        source,
1665        param_to_arg,
1666        lang,
1667        out,
1668    );
1669}
1670
1671fn collect_shadowing_bindings_in_scope_recursive(
1672    node: &Node,
1673    scope_id: usize,
1674    source: &str,
1675    param_to_arg: &std::collections::HashMap<String, String>,
1676    lang: LangId,
1677    out: &mut HashSet<String>,
1678) {
1679    if node.id() != scope_id {
1680        if is_function_scope_node(node, lang) || is_block_scope_node(node, lang) {
1681            return;
1682        }
1683    }
1684
1685    match node.kind() {
1686        "variable_declarator" => {
1687            if let Some(name) = node.child_by_field_name("name") {
1688                collect_shadowing_names_from_pattern(&name, source, param_to_arg, out);
1689            }
1690        }
1691        "catch_clause" => {
1692            if let Some(parameter) = node.child_by_field_name("parameter") {
1693                collect_shadowing_names_from_pattern(&parameter, source, param_to_arg, out);
1694            }
1695        }
1696        "for_in_statement" | "for_of_statement" => {
1697            if let Some(left) = node.child_by_field_name("left") {
1698                collect_shadowing_names_from_pattern(&left, source, param_to_arg, out);
1699            }
1700        }
1701        "assignment" if lang == LangId::Python => {
1702            if let Some(left) = node.child_by_field_name("left") {
1703                collect_shadowing_names_from_pattern(&left, source, param_to_arg, out);
1704            }
1705        }
1706        _ => {}
1707    }
1708
1709    let child_count = node.child_count();
1710    for i in 0..child_count {
1711        if let Some(child) = node.child(i as u32) {
1712            collect_shadowing_bindings_in_scope_recursive(
1713                &child,
1714                scope_id,
1715                source,
1716                param_to_arg,
1717                lang,
1718                out,
1719            );
1720        }
1721    }
1722}
1723
1724fn collect_shadowing_names_from_pattern(
1725    node: &Node,
1726    source: &str,
1727    param_to_arg: &std::collections::HashMap<String, String>,
1728    out: &mut HashSet<String>,
1729) {
1730    if node.kind() == "identifier" {
1731        let name = node_text(source, node);
1732        if param_to_arg.contains_key(name) {
1733            out.insert(name.to_string());
1734        }
1735        return;
1736    }
1737
1738    let child_count = node.child_count();
1739    for i in 0..child_count {
1740        if let Some(child) = node.child(i as u32) {
1741            collect_shadowing_names_from_pattern(&child, source, param_to_arg, out);
1742        }
1743    }
1744}
1745
1746fn is_function_scope_node(node: &Node, lang: LangId) -> bool {
1747    match lang {
1748        LangId::TypeScript | LangId::Tsx | LangId::JavaScript => matches!(
1749            node.kind(),
1750            "function_declaration" | "method_definition" | "arrow_function" | "function_expression"
1751        ),
1752        LangId::Python => node.kind() == "function_definition" || node.kind() == "lambda",
1753        _ => false,
1754    }
1755}
1756
1757fn is_block_scope_node(node: &Node, lang: LangId) -> bool {
1758    match lang {
1759        LangId::TypeScript | LangId::Tsx | LangId::JavaScript => node.kind() == "statement_block",
1760        LangId::Python => node.kind() == "block",
1761        _ => false,
1762    }
1763}
1764
1765fn is_binding_identifier(node: &Node) -> bool {
1766    let Some(parent) = node.parent() else {
1767        return false;
1768    };
1769
1770    if let Some(name) = parent.child_by_field_name("name") {
1771        if name.id() == node.id() || node_is_inside(&name, node) {
1772            return true;
1773        }
1774    }
1775    if let Some(pattern) = parent.child_by_field_name("pattern") {
1776        if pattern.id() == node.id() || node_is_inside(&pattern, node) {
1777            return true;
1778        }
1779    }
1780    if let Some(parameter) = parent.child_by_field_name("parameter") {
1781        if parameter.id() == node.id() || node_is_inside(&parameter, node) {
1782            return true;
1783        }
1784    }
1785    if let Some(left) = parent.child_by_field_name("left") {
1786        if matches!(
1787            parent.kind(),
1788            "for_in_statement" | "for_of_statement" | "assignment"
1789        ) && (left.id() == node.id() || node_is_inside(&left, node))
1790        {
1791            return true;
1792        }
1793    }
1794
1795    false
1796}
1797
1798fn node_is_inside(container: &Node, node: &Node) -> bool {
1799    container.start_byte() <= node.start_byte() && node.end_byte() <= container.end_byte()
1800}
1801
1802// ---------------------------------------------------------------------------
1803// Tests
1804// ---------------------------------------------------------------------------