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 → dry_run
5//! check → 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///   - `dry_run` (bool, optional) — if true, return diff without writing
29///
30/// Returns on success:
31///   `{ file, name, parameters, return_type, extracted_range, call_site_range, syntax_valid, backup_id }`
32///
33/// Error codes:
34///   - `unsupported_language` — file is not TS/JS/TSX/Python
35///   - `this_reference_in_range` — range contains `this`/`self`
36pub fn handle_extract_function(req: &RawRequest, ctx: &AppContext) -> Response {
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    let insert_pos = if let Some(fn_node) = enclosing_fn {
271        fn_node.start_byte()
272    } else {
273        start_byte
274    };
275
276    let new_source = build_new_source(
277        &source,
278        insert_pos,
279        start_byte,
280        end_byte,
281        &extracted_fn,
282        &call_site,
283    );
284
285    // --- Return type string for the response ---
286    let return_type = match &return_kind {
287        ReturnKind::Expression(_) => "expression",
288        ReturnKind::Variable(_) => "variable",
289        ReturnKind::Void => "void",
290    };
291
292    // --- Dry-run check ---
293    if edit::is_dry_run(&req.params) {
294        let dr = edit::dry_run_diff(&source, &new_source, &path);
295        return Response::success(
296            &req.id,
297            serde_json::json!({
298                "ok": true,
299                "dry_run": true,
300                "diff": dr.diff,
301                "syntax_valid": dr.syntax_valid,
302                "parameters": free_vars.parameters,
303                "return_type": return_type,
304            }),
305        );
306    }
307
308    // --- Auto-backup before mutation ---
309    let backup_id = match edit::auto_backup(
310        ctx,
311        req.session(),
312        &path,
313        &format!("extract_function: {}", name),
314    ) {
315        Ok(id) => id,
316        Err(e) => {
317            return Response::error(&req.id, e.code(), e.to_string());
318        }
319    };
320
321    // --- Write, format, validate ---
322    let mut write_result =
323        match edit::write_format_validate(&path, &new_source, &ctx.config(), &req.params) {
324            Ok(r) => r,
325            Err(e) => {
326                return Response::error(&req.id, e.code(), e.to_string());
327            }
328        };
329
330    if let Ok(final_content) = std::fs::read_to_string(&path) {
331        write_result.lsp_diagnostics = ctx.lsp_post_write(&path, &final_content, &req.params);
332    }
333
334    let param_count = free_vars.parameters.len();
335    log::debug!(
336        "[aft] extract_function: {} from {}:{}-{} ({} params)",
337        name,
338        file,
339        start_line,
340        end_line,
341        param_count
342    );
343
344    // --- Build response ---
345    let syntax_valid = write_result.syntax_valid.unwrap_or(true);
346
347    let mut result = serde_json::json!({
348        "file": file,
349        "name": name,
350        "parameters": free_vars.parameters,
351        "return_type": return_type,
352        "syntax_valid": syntax_valid,
353        "formatted": write_result.formatted,
354    });
355
356    if let Some(ref reason) = write_result.format_skipped_reason {
357        result["format_skipped_reason"] = serde_json::json!(reason);
358    }
359
360    if write_result.validate_requested {
361        result["validation_errors"] = serde_json::json!(write_result.validation_errors);
362    }
363    if let Some(ref reason) = write_result.validate_skipped_reason {
364        result["validate_skipped_reason"] = serde_json::json!(reason);
365    }
366
367    if let Some(ref id) = backup_id {
368        result["backup_id"] = serde_json::json!(id);
369    }
370
371    write_result.append_lsp_diagnostics_to(&mut result);
372    Response::success(&req.id, result)
373}
374
375/// Find the enclosing function node for a byte position.
376fn find_enclosing_function_node<'a>(
377    root: &'a tree_sitter::Node<'a>,
378    byte_pos: usize,
379    lang: LangId,
380) -> Option<tree_sitter::Node<'a>> {
381    let fn_kinds: &[&str] = match lang {
382        LangId::TypeScript | LangId::Tsx | LangId::JavaScript => &[
383            "function_declaration",
384            "method_definition",
385            "arrow_function",
386            "lexical_declaration",
387        ],
388        LangId::Python => &["function_definition"],
389        _ => &[],
390    };
391
392    find_deepest_ancestor(root, byte_pos, fn_kinds)
393}
394
395/// Find the deepest ancestor node of given kinds containing byte_pos.
396fn find_deepest_ancestor<'a>(
397    node: &tree_sitter::Node<'a>,
398    byte_pos: usize,
399    kinds: &[&str],
400) -> Option<tree_sitter::Node<'a>> {
401    let mut result: Option<tree_sitter::Node<'a>> = None;
402    if kinds.contains(&node.kind()) && node.start_byte() <= byte_pos && byte_pos < node.end_byte() {
403        result = Some(*node);
404    }
405
406    let child_count = node.child_count();
407    for i in 0..child_count {
408        if let Some(child) = node.child(i as u32) {
409            if child.start_byte() <= byte_pos && byte_pos < child.end_byte() {
410                if let Some(deeper) = find_deepest_ancestor(&child, byte_pos, kinds) {
411                    result = Some(deeper);
412                }
413            }
414        }
415    }
416
417    result
418}
419
420/// Get the leading whitespace of a source line.
421fn get_line_indent(source: &str, line: usize) -> String {
422    source
423        .lines()
424        .nth(line)
425        .map(|l| {
426            let trimmed = l.trim_start();
427            l[..l.len() - trimmed.len()].to_string()
428        })
429        .unwrap_or_default()
430}
431
432/// Build the new source with the extracted function inserted and the range replaced.
433fn build_new_source(
434    source: &str,
435    insert_pos: usize,
436    range_start: usize,
437    range_end: usize,
438    extracted_fn: &str,
439    call_site: &str,
440) -> String {
441    let mut result = String::with_capacity(source.len() + extracted_fn.len() + 64);
442
443    // Everything before the insertion point
444    result.push_str(&source[..insert_pos]);
445
446    // The extracted function + blank line
447    result.push_str(extracted_fn);
448    result.push_str("\n\n");
449
450    // Everything between insert point and the range start (the original function
451    // declaration up to where extraction begins)
452    result.push_str(&source[insert_pos..range_start]);
453
454    // The call site replacing the original range
455    result.push_str(call_site);
456    result.push('\n');
457
458    // Everything after the range
459    result.push_str(&source[range_end..]);
460
461    result
462}
463
464// ---------------------------------------------------------------------------
465// Tests
466// ---------------------------------------------------------------------------
467
468#[cfg(test)]
469mod tests {
470    use super::*;
471    use crate::protocol::RawRequest;
472
473    fn make_request(id: &str, command: &str, params: serde_json::Value) -> RawRequest {
474        RawRequest {
475            id: id.to_string(),
476            command: command.to_string(),
477            params,
478            lsp_hints: None,
479            session_id: None,
480        }
481    }
482
483    // --- Param validation ---
484
485    #[test]
486    fn extract_function_missing_file() {
487        let req = make_request("1", "extract_function", serde_json::json!({}));
488        let ctx = crate::context::AppContext::new(
489            Box::new(crate::parser::TreeSitterProvider::new()),
490            crate::config::Config::default(),
491        );
492        let resp = handle_extract_function(&req, &ctx);
493        let json = serde_json::to_value(&resp).unwrap();
494        assert_eq!(json["success"], false);
495        assert_eq!(json["code"], "invalid_request");
496        let msg = json["message"].as_str().unwrap();
497        assert!(
498            msg.contains("file"),
499            "message should mention 'file': {}",
500            msg
501        );
502    }
503
504    #[test]
505    fn extract_function_missing_name() {
506        let req = make_request(
507            "2",
508            "extract_function",
509            serde_json::json!({"file": "/tmp/test.ts"}),
510        );
511        let ctx = crate::context::AppContext::new(
512            Box::new(crate::parser::TreeSitterProvider::new()),
513            crate::config::Config::default(),
514        );
515        let resp = handle_extract_function(&req, &ctx);
516        let json = serde_json::to_value(&resp).unwrap();
517        assert_eq!(json["success"], false);
518        assert_eq!(json["code"], "invalid_request");
519        let msg = json["message"].as_str().unwrap();
520        assert!(
521            msg.contains("name"),
522            "message should mention 'name': {}",
523            msg
524        );
525    }
526
527    #[test]
528    fn extract_function_missing_start_line() {
529        let req = make_request(
530            "3",
531            "extract_function",
532            serde_json::json!({"file": "/tmp/test.ts", "name": "foo"}),
533        );
534        let ctx = crate::context::AppContext::new(
535            Box::new(crate::parser::TreeSitterProvider::new()),
536            crate::config::Config::default(),
537        );
538        let resp = handle_extract_function(&req, &ctx);
539        let json = serde_json::to_value(&resp).unwrap();
540        assert_eq!(json["success"], false);
541        assert_eq!(json["code"], "invalid_request");
542    }
543
544    #[test]
545    fn extract_function_unsupported_language() {
546        // Create a temp .rs file (Rust is not supported for extract_function)
547        let dir = std::env::temp_dir().join("aft_test_extract");
548        std::fs::create_dir_all(&dir).ok();
549        let file = dir.join("test.rs");
550        std::fs::write(&file, "fn main() {}").unwrap();
551
552        let req = make_request(
553            "4",
554            "extract_function",
555            serde_json::json!({
556                "file": file.display().to_string(),
557                "name": "foo",
558                "start_line": 1,
559                "end_line": 2,
560            }),
561        );
562        let ctx = crate::context::AppContext::new(
563            Box::new(crate::parser::TreeSitterProvider::new()),
564            crate::config::Config::default(),
565        );
566        let resp = handle_extract_function(&req, &ctx);
567        let json = serde_json::to_value(&resp).unwrap();
568        assert_eq!(json["success"], false);
569        assert_eq!(json["code"], "unsupported_language");
570
571        std::fs::remove_dir_all(&dir).ok();
572    }
573
574    #[test]
575    fn extract_function_invalid_line_range() {
576        let dir = std::env::temp_dir().join("aft_test_extract_range");
577        std::fs::create_dir_all(&dir).ok();
578        let file = dir.join("test.ts");
579        std::fs::write(&file, "const x = 1;\n").unwrap();
580
581        let req = make_request(
582            "5",
583            "extract_function",
584            serde_json::json!({
585                "file": file.display().to_string(),
586                "name": "foo",
587                "start_line": 6,
588                "end_line": 4,
589            }),
590        );
591        let ctx = crate::context::AppContext::new(
592            Box::new(crate::parser::TreeSitterProvider::new()),
593            crate::config::Config::default(),
594        );
595        let resp = handle_extract_function(&req, &ctx);
596        let json = serde_json::to_value(&resp).unwrap();
597        assert_eq!(json["success"], false);
598        assert_eq!(json["code"], "invalid_request");
599
600        std::fs::remove_dir_all(&dir).ok();
601    }
602
603    #[test]
604    fn extract_function_this_reference_error() {
605        let fixture = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
606            .join("tests/fixtures/extract_function/sample_this.ts");
607
608        let req = make_request(
609            "6",
610            "extract_function",
611            serde_json::json!({
612                "file": fixture.display().to_string(),
613                "name": "extracted",
614                "start_line": 5,
615                "end_line": 8,
616            }),
617        );
618        let ctx = crate::context::AppContext::new(
619            Box::new(crate::parser::TreeSitterProvider::new()),
620            crate::config::Config::default(),
621        );
622        let resp = handle_extract_function(&req, &ctx);
623        let json = serde_json::to_value(&resp).unwrap();
624        assert_eq!(json["success"], false);
625        assert_eq!(json["code"], "this_reference_in_range");
626    }
627
628    #[test]
629    fn extract_function_dry_run_returns_diff() {
630        let fixture = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
631            .join("tests/fixtures/extract_function/sample.ts");
632
633        let req = make_request(
634            "7",
635            "extract_function",
636            serde_json::json!({
637                "file": fixture.display().to_string(),
638                "name": "computeResult",
639                "start_line": 15,
640                "end_line": 17,
641                "dry_run": true,
642            }),
643        );
644        let ctx = crate::context::AppContext::new(
645            Box::new(crate::parser::TreeSitterProvider::new()),
646            crate::config::Config::default(),
647        );
648        let resp = handle_extract_function(&req, &ctx);
649        let json = serde_json::to_value(&resp).unwrap();
650        assert_eq!(json["success"], true);
651        assert_eq!(json["dry_run"], true);
652        assert!(json["diff"].as_str().is_some(), "should have diff");
653        assert!(json["parameters"].is_array(), "should have parameters");
654    }
655}