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