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