Skip to main content

aft/commands/
extract_function.rs

1//! Handler for the `extract_function` command: extract a range of code into
2//! a new function with auto-detected parameters and return value.
3//!
4//! Follows the edit_symbol.rs pattern: validate → parse → compute →
5//! auto_backup → write_format_validate → respond.
6
7use std::path::Path;
8
9use tree_sitter::Parser;
10
11use crate::context::AppContext;
12use crate::edit;
13use crate::extract::{
14    detect_free_variables, detect_return_value, generate_call_site, generate_extracted_function,
15    ReturnKind,
16};
17use crate::indent::detect_indent;
18use crate::parser::{detect_language, grammar_for, LangId};
19use crate::protocol::{RawRequest, Response};
20
21/// Handle an `extract_function` request.
22///
23/// Params:
24///   - `file` (string, required) — target file path
25///   - `name` (string, required) — name for the new function
26///   - `start_line` (u32, required) — first line of the range to extract (1-based)
27///   - `end_line` (u32, required) — last line (exclusive, 1-based) of the range to extract
28///
29/// Returns on success:
30///   `{ file, name, parameters, return_type, extracted_range, call_site_range, syntax_valid, backup_id }`
31///
32/// Error codes:
33///   - `unsupported_language` — file is not TS/JS/TSX/Python
34///   - `this_reference_in_range` — range contains `this`/`self`
35pub fn handle_extract_function(req: &RawRequest, ctx: &AppContext) -> Response {
36    let op_id = crate::backup::new_op_id();
37    // --- Extract params ---
38    let file = match req.params.get("file").and_then(|v| v.as_str()) {
39        Some(f) => f,
40        None => {
41            return Response::error(
42                &req.id,
43                "invalid_request",
44                "extract_function: missing required param 'file'",
45            );
46        }
47    };
48
49    let name = match req.params.get("name").and_then(|v| v.as_str()) {
50        Some(n) => n,
51        None => {
52            return Response::error(
53                &req.id,
54                "invalid_request",
55                "extract_function: missing required param 'name'",
56            );
57        }
58    };
59
60    let start_line_1based = match req.params.get("start_line").and_then(|v| v.as_u64()) {
61        Some(l) if l >= 1 => l as u32,
62        Some(_) => {
63            return Response::error(
64                &req.id,
65                "invalid_request",
66                "extract_function: 'start_line' must be >= 1 (1-based)",
67            );
68        }
69        None => {
70            return Response::error(
71                &req.id,
72                "invalid_request",
73                "extract_function: missing required param 'start_line'",
74            );
75        }
76    };
77    let start_line = start_line_1based - 1;
78
79    let end_line_1based = match req.params.get("end_line").and_then(|v| v.as_u64()) {
80        Some(l) if l >= 1 => l as u32,
81        Some(_) => {
82            return Response::error(
83                &req.id,
84                "invalid_request",
85                "extract_function: 'end_line' must be >= 1 (1-based)",
86            );
87        }
88        None => {
89            return Response::error(
90                &req.id,
91                "invalid_request",
92                "extract_function: missing required param 'end_line'",
93            );
94        }
95    };
96    let end_line = end_line_1based - 1;
97
98    if start_line >= end_line {
99        return Response::error(
100            &req.id,
101            "invalid_request",
102            format!(
103                "extract_function: start_line ({}) must be less than end_line ({})",
104                start_line, end_line
105            ),
106        );
107    }
108
109    // --- Validate file ---
110    let path = match ctx.validate_path(&req.id, Path::new(file)) {
111        Ok(path) => path,
112        Err(resp) => return resp,
113    };
114    if !path.exists() {
115        return Response::error(
116            &req.id,
117            "file_not_found",
118            format!("extract_function: file not found: {}", file),
119        );
120    }
121
122    // --- Language guard (D101) ---
123    let lang = match detect_language(&path) {
124        Some(l) => l,
125        None => {
126            return Response::error(
127                &req.id,
128                "unsupported_language",
129                "extract_function: unsupported file type",
130            );
131        }
132    };
133
134    if !matches!(
135        lang,
136        LangId::TypeScript | LangId::Tsx | LangId::JavaScript | LangId::Python
137    ) {
138        return Response::error(
139            &req.id,
140            "unsupported_language",
141            format!(
142                "extract_function: only TypeScript/JavaScript/Python files are supported, got {:?}",
143                lang
144            ),
145        );
146    }
147
148    // --- Read and parse ---
149    let source = match std::fs::read_to_string(&path) {
150        Ok(s) => s,
151        Err(e) => {
152            return Response::error(
153                &req.id,
154                "file_not_found",
155                format!("extract_function: {}: {}", file, e),
156            );
157        }
158    };
159
160    let grammar = grammar_for(lang);
161    let mut parser = Parser::new();
162    if parser.set_language(&grammar).is_err() {
163        return Response::error(
164            &req.id,
165            "parse_error",
166            "extract_function: failed to initialize parser",
167        );
168    }
169    let tree = match parser.parse(source.as_bytes(), None) {
170        Some(t) => t,
171        None => {
172            return Response::error(
173                &req.id,
174                "parse_error",
175                "extract_function: failed to parse file",
176            );
177        }
178    };
179
180    // --- Convert line range to byte range ---
181    let start_byte = edit::line_col_to_byte(&source, start_line, 0);
182    let end_byte = edit::line_col_to_byte(&source, end_line, 0);
183
184    if start_byte >= source.len() {
185        return Response::error(
186            &req.id,
187            "invalid_request",
188            format!(
189                "extract_function: start_line {} is beyond end of file",
190                start_line
191            ),
192        );
193    }
194
195    // --- Detect free variables ---
196    let free_vars = detect_free_variables(&source, &tree, start_byte, end_byte, lang);
197
198    // Check for this/self
199    if free_vars.has_this_or_self {
200        let keyword = match lang {
201            LangId::Python => "self",
202            _ => "this",
203        };
204        return Response::error(
205            &req.id,
206            "this_reference_in_range",
207            format!(
208                "extract_function: selected range contains '{}' reference. Consider extracting as a method instead, or move the {} usage outside the extracted range.",
209                keyword, keyword
210            ),
211        );
212    }
213
214    // --- Find enclosing function for return value detection ---
215    let root = tree.root_node();
216    let enclosing_fn = find_enclosing_function_node(&root, start_byte, lang);
217    let enclosing_fn_end_byte = enclosing_fn.map(|n| n.end_byte());
218
219    // --- Detect return value ---
220    let return_kind = detect_return_value(
221        &source,
222        &tree,
223        start_byte,
224        end_byte,
225        enclosing_fn_end_byte,
226        lang,
227    );
228
229    // --- Detect indentation ---
230    let indent_style = detect_indent(&source, lang);
231
232    // Determine base indent (indentation of the line where the enclosing function starts,
233    // or no indent if at module level)
234    let base_indent = if let Some(fn_node) = enclosing_fn {
235        let fn_start_line = fn_node.start_position().row;
236        get_line_indent(&source, fn_start_line as usize)
237    } else {
238        String::new()
239    };
240
241    // Determine the indent of the extracted range (for the call site)
242    let range_indent = get_line_indent(&source, start_line as usize);
243
244    // --- Extract body text ---
245    let body_text = &source[start_byte..end_byte];
246    let body_text = body_text.trim_end_matches('\n');
247
248    // --- Generate function and call site ---
249    let extracted_fn = generate_extracted_function(
250        name,
251        &free_vars.parameters,
252        &return_kind,
253        body_text,
254        &base_indent,
255        lang,
256        indent_style,
257    );
258
259    let call_site = generate_call_site(
260        name,
261        &free_vars.parameters,
262        &return_kind,
263        &range_indent,
264        lang,
265    );
266
267    // --- Compute new file content ---
268    // Insert the extracted function before the enclosing function (or at the range position
269    // if there's no enclosing function).
270    //
271    // For TS/JS, when the enclosing function is wrapped in `export` (or
272    // `export default`), the parser reports the function_declaration as
273    // a child of an export_statement. If we use fn_node.start_byte() as
274    // the insertion point, the `export` keyword stays attached to the
275    // start of the file content, and the extracted function gets inserted
276    // BETWEEN `export ` and `function`, producing:
277    //   `export function newFn(...) {} \n\n function originalFn(...) {}`
278    // The export keyword silently jumps from the original function to the
279    // extracted one. Fix: if the parent is an export_statement, insert
280    // before the export_statement instead.
281    let insert_pos = if let Some(fn_node) = enclosing_fn {
282        let mut anchor = fn_node;
283        if matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript) {
284            if let Some(parent) = fn_node.parent() {
285                if parent.kind() == "export_statement" {
286                    anchor = parent;
287                }
288            }
289        }
290        anchor.start_byte()
291    } else {
292        start_byte
293    };
294
295    let new_source = build_new_source(
296        &source,
297        insert_pos,
298        start_byte,
299        end_byte,
300        &extracted_fn,
301        &call_site,
302    );
303
304    // --- Return type string for the response ---
305    let return_type = match &return_kind {
306        ReturnKind::Expression(_) => "expression",
307        ReturnKind::Variable(_) => "variable",
308        ReturnKind::Void => "void",
309    };
310
311    // --- Auto-backup before mutation ---
312    let backup_id = match edit::auto_backup(
313        ctx,
314        req.session(),
315        &path,
316        &format!("extract_function: {}", name),
317        Some(&op_id),
318    ) {
319        Ok(id) => id,
320        Err(e) => {
321            return Response::error(&req.id, e.code(), e.to_string());
322        }
323    };
324
325    // --- Write, format, validate ---
326    let mut write_result =
327        match edit::write_format_validate(&path, &new_source, &ctx.config(), &req.params) {
328            Ok(r) => r,
329            Err(e) => {
330                return Response::error(&req.id, e.code(), e.to_string());
331            }
332        };
333
334    if let Ok(final_content) = std::fs::read_to_string(&path) {
335        write_result.lsp_outcome = ctx.lsp_post_write(&path, &final_content, &req.params);
336    }
337
338    let param_count = free_vars.parameters.len();
339    log::debug!(
340        "extract_function: {} from {}:{}-{} ({} params)",
341        name,
342        file,
343        start_line,
344        end_line,
345        param_count
346    );
347
348    // --- Build response ---
349    let syntax_valid = write_result.syntax_valid.unwrap_or(true);
350
351    let mut result = serde_json::json!({
352        "file": file,
353        "name": name,
354        "parameters": free_vars.parameters,
355        "return_type": return_type,
356        "syntax_valid": syntax_valid,
357        "formatted": write_result.formatted,
358    });
359
360    if let Some(ref reason) = write_result.format_skipped_reason {
361        result["format_skipped_reason"] = serde_json::json!(reason);
362    }
363
364    if write_result.validate_requested {
365        result["validation_errors"] = serde_json::json!(write_result.validation_errors);
366    }
367    if let Some(ref reason) = write_result.validate_skipped_reason {
368        result["validate_skipped_reason"] = serde_json::json!(reason);
369    }
370
371    if let Some(ref id) = backup_id {
372        result["backup_id"] = serde_json::json!(id);
373    }
374
375    write_result.append_lsp_diagnostics_to(&mut result);
376    Response::success(&req.id, result)
377}
378
379/// Find the enclosing function node for a byte position.
380fn find_enclosing_function_node<'a>(
381    root: &'a tree_sitter::Node<'a>,
382    byte_pos: usize,
383    lang: LangId,
384) -> Option<tree_sitter::Node<'a>> {
385    let fn_kinds: &[&str] = match lang {
386        LangId::TypeScript | LangId::Tsx | LangId::JavaScript => &[
387            "function_declaration",
388            "method_definition",
389            "arrow_function",
390            "lexical_declaration",
391        ],
392        LangId::Python => &["function_definition"],
393        _ => &[],
394    };
395
396    find_deepest_ancestor(root, byte_pos, fn_kinds)
397}
398
399/// Find the deepest ancestor node of given kinds containing byte_pos.
400fn find_deepest_ancestor<'a>(
401    node: &tree_sitter::Node<'a>,
402    byte_pos: usize,
403    kinds: &[&str],
404) -> Option<tree_sitter::Node<'a>> {
405    let mut result: Option<tree_sitter::Node<'a>> = None;
406    if kinds.contains(&node.kind()) && node.start_byte() <= byte_pos && byte_pos < node.end_byte() {
407        result = Some(*node);
408    }
409
410    let child_count = node.child_count();
411    for i in 0..child_count {
412        if let Some(child) = node.child(i as u32) {
413            if child.start_byte() <= byte_pos && byte_pos < child.end_byte() {
414                if let Some(deeper) = find_deepest_ancestor(&child, byte_pos, kinds) {
415                    result = Some(deeper);
416                }
417            }
418        }
419    }
420
421    result
422}
423
424/// Get the leading whitespace of a source line.
425fn get_line_indent(source: &str, line: usize) -> String {
426    source
427        .lines()
428        .nth(line)
429        .map(|l| {
430            let trimmed = l.trim_start();
431            l[..l.len() - trimmed.len()].to_string()
432        })
433        .unwrap_or_default()
434}
435
436/// Build the new source with the extracted function inserted and the range replaced.
437fn build_new_source(
438    source: &str,
439    insert_pos: usize,
440    range_start: usize,
441    range_end: usize,
442    extracted_fn: &str,
443    call_site: &str,
444) -> String {
445    let mut result = String::with_capacity(source.len() + extracted_fn.len() + 64);
446
447    // Everything before the insertion point
448    result.push_str(&source[..insert_pos]);
449
450    // The extracted function + blank line
451    result.push_str(extracted_fn);
452    result.push_str("\n\n");
453
454    // Everything between insert point and the range start (the original function
455    // declaration up to where extraction begins)
456    result.push_str(&source[insert_pos..range_start]);
457
458    // The call site replacing the original range
459    result.push_str(call_site);
460    result.push('\n');
461
462    // Everything after the range
463    result.push_str(&source[range_end..]);
464
465    result
466}
467
468// ---------------------------------------------------------------------------
469// Tests
470// ---------------------------------------------------------------------------
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475    use crate::protocol::RawRequest;
476
477    fn make_request(id: &str, command: &str, params: serde_json::Value) -> RawRequest {
478        RawRequest {
479            id: id.to_string(),
480            command: command.to_string(),
481            params,
482            lsp_hints: None,
483            session_id: None,
484        }
485    }
486
487    // --- Param validation ---
488
489    #[test]
490    fn extract_function_missing_file() {
491        let req = make_request("1", "extract_function", serde_json::json!({}));
492        let ctx = crate::context::AppContext::new(
493            Box::new(crate::parser::TreeSitterProvider::new()),
494            crate::config::Config::default(),
495        );
496        let resp = handle_extract_function(&req, &ctx);
497        let json = serde_json::to_value(&resp).unwrap();
498        assert_eq!(json["success"], false);
499        assert_eq!(json["code"], "invalid_request");
500        let msg = json["message"].as_str().unwrap();
501        assert!(
502            msg.contains("file"),
503            "message should mention 'file': {}",
504            msg
505        );
506    }
507
508    #[test]
509    fn extract_function_missing_name() {
510        let req = make_request(
511            "2",
512            "extract_function",
513            serde_json::json!({"file": "/tmp/test.ts"}),
514        );
515        let ctx = crate::context::AppContext::new(
516            Box::new(crate::parser::TreeSitterProvider::new()),
517            crate::config::Config::default(),
518        );
519        let resp = handle_extract_function(&req, &ctx);
520        let json = serde_json::to_value(&resp).unwrap();
521        assert_eq!(json["success"], false);
522        assert_eq!(json["code"], "invalid_request");
523        let msg = json["message"].as_str().unwrap();
524        assert!(
525            msg.contains("name"),
526            "message should mention 'name': {}",
527            msg
528        );
529    }
530
531    #[test]
532    fn extract_function_missing_start_line() {
533        let req = make_request(
534            "3",
535            "extract_function",
536            serde_json::json!({"file": "/tmp/test.ts", "name": "foo"}),
537        );
538        let ctx = crate::context::AppContext::new(
539            Box::new(crate::parser::TreeSitterProvider::new()),
540            crate::config::Config::default(),
541        );
542        let resp = handle_extract_function(&req, &ctx);
543        let json = serde_json::to_value(&resp).unwrap();
544        assert_eq!(json["success"], false);
545        assert_eq!(json["code"], "invalid_request");
546    }
547
548    #[test]
549    fn extract_function_unsupported_language() {
550        // Create a temp .rs file (Rust is not supported for extract_function)
551        let dir = std::env::temp_dir().join("aft_test_extract");
552        std::fs::create_dir_all(&dir).ok();
553        let file = dir.join("test.rs");
554        std::fs::write(&file, "fn main() {}").unwrap();
555
556        let req = make_request(
557            "4",
558            "extract_function",
559            serde_json::json!({
560                "file": file.display().to_string(),
561                "name": "foo",
562                "start_line": 1,
563                "end_line": 2,
564            }),
565        );
566        let ctx = crate::context::AppContext::new(
567            Box::new(crate::parser::TreeSitterProvider::new()),
568            crate::config::Config::default(),
569        );
570        let resp = handle_extract_function(&req, &ctx);
571        let json = serde_json::to_value(&resp).unwrap();
572        assert_eq!(json["success"], false);
573        assert_eq!(json["code"], "unsupported_language");
574
575        std::fs::remove_dir_all(&dir).ok();
576    }
577
578    #[test]
579    fn extract_function_invalid_line_range() {
580        let dir = std::env::temp_dir().join("aft_test_extract_range");
581        std::fs::create_dir_all(&dir).ok();
582        let file = dir.join("test.ts");
583        std::fs::write(&file, "const x = 1;\n").unwrap();
584
585        let req = make_request(
586            "5",
587            "extract_function",
588            serde_json::json!({
589                "file": file.display().to_string(),
590                "name": "foo",
591                "start_line": 6,
592                "end_line": 4,
593            }),
594        );
595        let ctx = crate::context::AppContext::new(
596            Box::new(crate::parser::TreeSitterProvider::new()),
597            crate::config::Config::default(),
598        );
599        let resp = handle_extract_function(&req, &ctx);
600        let json = serde_json::to_value(&resp).unwrap();
601        assert_eq!(json["success"], false);
602        assert_eq!(json["code"], "invalid_request");
603
604        std::fs::remove_dir_all(&dir).ok();
605    }
606
607    #[test]
608    fn extract_function_this_reference_error() {
609        let fixture = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
610            .join("tests/fixtures/extract_function/sample_this.ts");
611
612        let req = make_request(
613            "6",
614            "extract_function",
615            serde_json::json!({
616                "file": fixture.display().to_string(),
617                "name": "extracted",
618                "start_line": 5,
619                "end_line": 8,
620            }),
621        );
622        let ctx = crate::context::AppContext::new(
623            Box::new(crate::parser::TreeSitterProvider::new()),
624            crate::config::Config::default(),
625        );
626        let resp = handle_extract_function(&req, &ctx);
627        let json = serde_json::to_value(&resp).unwrap();
628        assert_eq!(json["success"], false);
629        assert_eq!(json["code"], "this_reference_in_range");
630    }
631}