Skip to main content

lean_ctx/tools/ctx_refactor/
mod.rs

1use lsp_types::{Location, Position};
2use serde_json::Value;
3
4use crate::lsp::client::uri_to_file_path;
5
6pub fn handle(args: &Value, project_root: &str, abs_path: &str) -> String {
7    let action = args
8        .get("action")
9        .and_then(Value::as_str)
10        .unwrap_or("references");
11
12    if matches!(
13        action,
14        "replace_symbol_body" | "insert_before_symbol" | "insert_after_symbol"
15    ) {
16        return handle_symbol_edit(action, args, project_root);
17    }
18
19    if matches!(action, "rename_preview" | "rename_apply") {
20        return handle_rename_refactor(action, args, project_root);
21    }
22
23    if matches!(action, "safe_delete_preview" | "safe_delete_apply") {
24        return handle_safe_delete_refactor(action, args, project_root);
25    }
26
27    if matches!(action, "move_preview" | "move_apply") {
28        return handle_move_refactor(action, args, project_root);
29    }
30
31    if matches!(action, "inline_preview" | "inline_apply") {
32        return handle_inline_refactor(action, args, project_root);
33    }
34
35    if action == "reformat" {
36        return handle_reformat_refactor(args, project_root);
37    }
38
39    let line = args.get("line").and_then(Value::as_u64).unwrap_or(1) as u32;
40    let column = args.get("column").and_then(Value::as_u64).unwrap_or(0) as u32;
41    let scope = args
42        .get("scope")
43        .and_then(Value::as_str)
44        .unwrap_or("project");
45
46    let uri = match crate::lsp::router::open_file(abs_path, project_root) {
47        Ok(u) => u,
48        Err(e) => return format!("ERROR: {e}"),
49    };
50
51    let position = Position::new(line.saturating_sub(1), column);
52
53    // #475: the IDE symbol `rename` rewrites the target file in place; deny when
54    // it sits inside a read-only root (the other read actions below never write).
55    if action == "rename"
56        && let Some(e) = deny_if_read_only(abs_path)
57    {
58        return e;
59    }
60
61    match action {
62        "rename" => handle_rename(args, abs_path, project_root, &uri, position),
63        "references" => handle_references(abs_path, project_root, &uri, position, scope),
64        "definition" => handle_definition(abs_path, project_root, &uri, position),
65        "implementations" => handle_implementations(abs_path, project_root, &uri, position, scope),
66        "declaration" => handle_declaration(abs_path, project_root, &uri, position),
67        "type_hierarchy" => handle_type_hierarchy(args, abs_path, project_root, &uri, position),
68        "symbols_overview" => handle_symbols_overview(abs_path, project_root, &uri),
69        "inspections" => handle_inspections(args, abs_path, project_root, &uri),
70        _ => format!(
71            "ERROR: Unknown action '{action}'. Available: rename, references, definition, \
72             implementations, declaration, type_hierarchy, symbols_overview, inspections, \
73             replace_symbol_body, insert_before_symbol, insert_after_symbol, \
74             rename_preview, rename_apply, safe_delete_preview, safe_delete_apply, \
75             move_preview, move_apply, inline_preview, inline_apply, reformat."
76        ),
77    }
78}
79
80/// #475 read-only-roots default-deny for refactor writes. Returns an early
81/// `ERROR: …` string when `abs_path` resolves inside a configured read-only
82/// root, `None` otherwise. Two-phase `*_preview` actions only read and are
83/// never gated; every apply / symbol-edit / reformat / rename path routes its
84/// resolved target(s) through this before any IDE or headless write.
85fn deny_if_read_only(abs_path: &str) -> Option<String> {
86    crate::core::pathjail::enforce_writable(std::path::Path::new(abs_path))
87        .err()
88        .map(|e| format!("ERROR: {e}"))
89}
90
91fn handle_rename(
92    args: &Value,
93    file_path: &str,
94    project_root: &str,
95    uri: &lsp_types::Uri,
96    position: Position,
97) -> String {
98    let Some(new_name) = args.get("new_name").and_then(Value::as_str) else {
99        return "ERROR: 'new_name' parameter is required for rename.".to_string();
100    };
101
102    let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
103        backend.rename(uri, position, new_name)
104    });
105
106    match result {
107        Ok(Some(edit)) => format_workspace_edit(&edit, project_root),
108        Ok(None) => "No rename edits returned by language server.".to_string(),
109        Err(e) => format!("ERROR: {e}"),
110    }
111}
112
113fn handle_references(
114    file_path: &str,
115    project_root: &str,
116    uri: &lsp_types::Uri,
117    position: Position,
118    scope: &str,
119) -> String {
120    let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
121        let locs = backend.references(uri, position, scope)?;
122        Ok((locs, backend.last_truncation()))
123    });
124
125    match result {
126        Ok((locations, meta)) => {
127            let mut out = format_locations(&locations, project_root);
128            out.push_str(&truncation_note(locations.len(), meta));
129            out
130        }
131        Err(e) => format!("ERROR: {e}"),
132    }
133}
134
135fn handle_definition(
136    file_path: &str,
137    project_root: &str,
138    uri: &lsp_types::Uri,
139    position: Position,
140) -> String {
141    let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
142        backend.definition(uri, position)
143    });
144
145    match result {
146        Ok(resp) => {
147            let locations = match resp {
148                lsp_types::GotoDefinitionResponse::Scalar(loc) => vec![loc],
149                lsp_types::GotoDefinitionResponse::Array(locs) => locs,
150                lsp_types::GotoDefinitionResponse::Link(links) => links
151                    .into_iter()
152                    .map(|l| Location {
153                        uri: l.target_uri,
154                        range: l.target_selection_range,
155                    })
156                    .collect(),
157            };
158            format_locations(&locations, project_root)
159        }
160        Err(e) => format!("ERROR: {e}"),
161    }
162}
163
164fn handle_implementations(
165    file_path: &str,
166    project_root: &str,
167    uri: &lsp_types::Uri,
168    position: Position,
169    scope: &str,
170) -> String {
171    let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
172        let locs = backend.implementations(uri, position, scope)?;
173        Ok((locs, backend.last_truncation()))
174    });
175
176    match result {
177        Ok((locations, meta)) => {
178            let mut out = format_locations(&locations, project_root);
179            out.push_str(&truncation_note(locations.len(), meta));
180            out
181        }
182        Err(e) => format!("ERROR: {e}"),
183    }
184}
185
186fn handle_declaration(
187    file_path: &str,
188    project_root: &str,
189    uri: &lsp_types::Uri,
190    position: Position,
191) -> String {
192    let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
193        backend.declaration(uri, position)
194    });
195
196    match result {
197        Ok(locations) => format_locations(&locations, project_root),
198        Err(e) => format!("ERROR: {e}"),
199    }
200}
201
202use crate::lsp::backend::{
203    HierarchyDirection, InspectionDiag, InspectionInfo, SymbolOverviewItem, TypeHierarchyNode,
204};
205
206/// A resolved symbol location (project-relative path + 1-based inclusive line span).
207#[derive(Debug)]
208pub(crate) struct Resolved {
209    pub rel_path: String,
210    pub start_line: usize,
211    pub end_line: usize,
212}
213
214/// Apply a resolved edit. IDE-first: a live JetBrains backend (port file +
215/// liveness, mirroring router::select_backend) handles it via WriteCommandAction;
216/// otherwise the headless local_range_write applies the identical bytes.
217pub(crate) fn apply_symbol_edit(
218    action: &str,
219    project_root: &str,
220    edit: &crate::lsp::backend::RangeEdit,
221) -> Result<crate::lsp::backend::EditResult, String> {
222    use crate::lsp::backend::LspBackend;
223    use crate::lsp::port_discovery;
224
225    let mut backend: Box<dyn LspBackend> =
226        if let Some(pf) = port_discovery::read_port_file(project_root) {
227            if port_discovery::pid_alive(pf.pid) && port_discovery::health_ok(&pf) {
228                Box::new(crate::lsp::jetbrains_backend::JetBrainsHttpBackend::new(
229                    pf.port,
230                    pf.token,
231                    project_root.to_string(),
232                    pf.pid,
233                ))
234            } else {
235                Box::new(crate::lsp::edit_apply::HeadlessBackend)
236            }
237        } else {
238            Box::new(crate::lsp::edit_apply::HeadlessBackend)
239        };
240
241    match action {
242        "replace_symbol_body" => backend.replace_symbol_body(edit),
243        "insert_before_symbol" => backend.insert_before_symbol(edit),
244        "insert_after_symbol" => backend.insert_after_symbol(edit),
245        other => Err(format!("INTERNAL: not an edit action: {other}")),
246    }
247}
248
249/// Leading whitespace of the 1-based `line` in `content` (anchor indentation).
250pub(crate) fn anchor_indent(content: &str, line: usize) -> String {
251    content
252        .lines()
253        .nth(line.saturating_sub(1))
254        .map(|l| l.chars().take_while(|c| *c == ' ' || *c == '\t').collect())
255        .unwrap_or_default()
256}
257
258/// Prefix `indent` to the first line of `text` iff that line has no leading
259/// whitespace of its own (deterministic; the same Rust computes it for both
260/// apply paths, so the wire text is byte-identical).
261pub(crate) fn reindent_first_line(text: &str, indent: &str) -> String {
262    if text.starts_with(' ') || text.starts_with('\t') || indent.is_empty() {
263        return text.to_string();
264    }
265    format!("{indent}{text}")
266}
267
268/// True if symbol `name` denotes a container for type `ancestor`: the bare type
269/// itself (struct/enum/inherent `impl Type`) — exact match — or a trait impl,
270/// whose indexed name is `<Trait> for <Type>` (see the round-trip note in
271/// graph_provider.rs). Generic args on the impl target (`… for Type<T>`) are
272/// stripped so `Type/method` still resolves. Language-agnostic: non-Rust
273/// container names never contain `" for "`, so only the exact branch applies.
274fn container_matches_ancestor(name: &str, ancestor: &str) -> bool {
275    if name == ancestor {
276        return true;
277    }
278    match name.rsplit_once(" for ") {
279        Some((_, target)) => target.split('<').next().unwrap_or(target).trim() == ancestor,
280        None => false,
281    }
282}
283
284/// Resolve a `name_path` (`Class/method` or bare `name`) to a single symbol via
285/// the tree-sitter index (spec v2a §3/§5.3). Disambiguates a qualified path by
286/// enclosing-range containment (ancestor symbol's line span contains the leaf's).
287pub(crate) fn resolve_name_path(name_path: &str, project_root: &str) -> Result<Resolved, String> {
288    use crate::core::graph_provider;
289    let open = graph_provider::open_or_build(project_root)
290        .ok_or_else(|| "NO_SYMBOL: no symbol index available".to_string())?;
291    let gp = &open.provider;
292
293    let segments: Vec<&str> = name_path.split('/').filter(|s| !s.is_empty()).collect();
294    let leaf = *segments
295        .last()
296        .ok_or_else(|| "NO_SYMBOL: empty name_path".to_string())?;
297
298    // Exact-name leaf candidates (case-sensitive — the index may substring-match).
299    let mut leaves: Vec<_> = gp
300        .find_symbols(leaf, None, None)
301        .into_iter()
302        .filter(|s| s.name == leaf)
303        .collect();
304
305    if segments.len() >= 2 {
306        let ancestor = segments[segments.len() - 2];
307        let parents: Vec<_> = gp
308            .find_symbols(ancestor, None, None)
309            .into_iter()
310            .filter(|s| container_matches_ancestor(&s.name, ancestor))
311            .collect();
312        leaves.retain(|leaf_sym| {
313            parents.iter().any(|p| {
314                p.file == leaf_sym.file
315                    && p.start_line <= leaf_sym.start_line
316                    && leaf_sym.end_line <= p.end_line
317            })
318        });
319    }
320
321    match leaves.len() {
322        0 => Err(format!(
323            "NO_SYMBOL: '{name_path}' did not resolve to any indexed symbol"
324        )),
325        1 => Ok(Resolved {
326            rel_path: leaves[0].file.clone(),
327            start_line: leaves[0].start_line,
328            end_line: leaves[0].end_line,
329        }),
330        _ => {
331            let mut msg = format!(
332                "AMBIGUOUS_SYMBOL: '{name_path}' matches {} symbols; qualify it:\n",
333                leaves.len()
334            );
335            for s in leaves.iter().take(10) {
336                msg.push_str(&format!(
337                    "  {}:{} (L{}-{})\n",
338                    s.file, s.name, s.start_line, s.end_line
339                ));
340            }
341            Err(msg)
342        }
343    }
344}
345
346/// Read the current on-disk text covered by a usage's range, jail-checking its
347/// path first. Out-of-jail / unreadable / bad range → `Err` (spec §5.4 Multi-File
348/// jail: every plugin-reported path is re-checked against `project_root`).
349pub(crate) fn usage_range_text(
350    project_root: &str,
351    u: &crate::lsp::backend::UsageSite,
352) -> Result<String, String> {
353    let abs = crate::core::path_resolve::resolve_tool_path(Some(project_root), None, &u.path)
354        .map_err(|e| format!("CONFLICT: usage path blocked by jail: {e}"))?;
355    let content =
356        std::fs::read_to_string(&abs).map_err(|e| format!("FILE_NOT_FOUND: {abs}: {e}"))?;
357    let s = crate::lsp::edit_apply::offset_of(&content, u.range.start_line, u.range.start_char)?;
358    let e = crate::lsp::edit_apply::offset_of(&content, u.range.end_line, u.range.end_char)?;
359    if e < s {
360        return Err("POSITION_OUT_OF_RANGE: end before start".to_string());
361    }
362    Ok(content[s..e].to_string())
363}
364
365/// Stateless Multi-File integrity guard (spec §5.2). BLAKE3 over the usages
366/// canonicalized by sorted `(path, range)` plus each usage's *current* on-disk
367/// text. `context` is display-only and intentionally excluded. Re-built in
368/// `rename_apply` and compared → mismatch = `CONFLICT` (TOCTOU).
369pub(crate) fn plan_hash(
370    project_root: &str,
371    usages: &[crate::lsp::backend::UsageSite],
372) -> Result<String, String> {
373    use crate::lsp::backend::TextRange0Based;
374    let mut rows: Vec<(String, TextRange0Based, String)> = Vec::with_capacity(usages.len());
375    for u in usages {
376        let text = usage_range_text(project_root, u)?;
377        rows.push((u.path.clone(), u.range, text));
378    }
379    rows.sort_by(|a, b| {
380        a.0.cmp(&b.0)
381            .then(a.1.start_line.cmp(&b.1.start_line))
382            .then(a.1.start_char.cmp(&b.1.start_char))
383            .then(a.1.end_line.cmp(&b.1.end_line))
384            .then(a.1.end_char.cmp(&b.1.end_char))
385    });
386    let mut canon = String::new();
387    for (path, r, text) in &rows {
388        canon.push_str(&format!(
389            "{path}|{}:{}-{}:{}|{text}\n",
390            r.start_line, r.start_char, r.end_line, r.end_char
391        ));
392    }
393    Ok(crate::core::hasher::hash_hex(canon.as_bytes()))
394}
395
396mod ops;
397#[allow(clippy::wildcard_imports)]
398use ops::*;
399
400fn parse_direction(args: &Value) -> HierarchyDirection {
401    match args.get("direction").and_then(Value::as_str) {
402        Some("subtypes") => HierarchyDirection::Subtypes,
403        _ => HierarchyDirection::Supertypes,
404    }
405}
406
407fn handle_type_hierarchy(
408    args: &Value,
409    file_path: &str,
410    project_root: &str,
411    uri: &lsp_types::Uri,
412    position: Position,
413) -> String {
414    let direction = parse_direction(args);
415    let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
416        let tree = backend.type_hierarchy(uri, position, direction)?;
417        Ok((tree, backend.last_truncation()))
418    });
419    match result {
420        Ok((tree, meta)) => {
421            let mut out = format_type_hierarchy(&tree);
422            if matches!(meta, Some(m) if m.truncated) {
423                out.push_str("\n(truncated — depth/node cap reached)\n");
424            }
425            out
426        }
427        Err(e) => format!("ERROR: {e}"),
428    }
429}
430
431fn handle_symbols_overview(file_path: &str, project_root: &str, uri: &lsp_types::Uri) -> String {
432    let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
433        let items = backend.symbols_overview(uri)?;
434        Ok((items, backend.last_truncation()))
435    });
436    match result {
437        Ok((items, meta)) => {
438            let mut out = format_symbols_overview(&items);
439            out.push_str(&truncation_note(items.len(), meta));
440            out
441        }
442        Err(e) => format!("ERROR: {e}"),
443    }
444}
445
446fn handle_symbol_edit(action: &str, args: &Value, project_root: &str) -> String {
447    let (rel_path, start_line, end_line) = if let Some(np) =
448        args.get("name_path").and_then(Value::as_str)
449    {
450        match resolve_name_path(np, project_root) {
451            Ok(r) => (r.rel_path, r.start_line, r.end_line),
452            Err(e) => return format!("ERROR: {e}"),
453        }
454    } else {
455        let Some(path) = args.get("path").and_then(Value::as_str) else {
456            return "ERROR: provide 'name_path' or 'path'+'line' for symbol edits.".to_string();
457        };
458        let line = args.get("line").and_then(Value::as_u64).unwrap_or(0) as usize;
459        let end = args
460            .get("end_line")
461            .and_then(Value::as_u64)
462            .unwrap_or(line as u64) as usize;
463        if line == 0 {
464            return "ERROR: 'line' is required (1-based) when using the path fallback.".to_string();
465        }
466        (path.to_string(), line, end)
467    };
468
469    // 2) PathJail on the resolved path (v1 §4.5 seam — critical before writes).
470    let abs_path =
471        match crate::core::path_resolve::resolve_tool_path(Some(project_root), None, &rel_path) {
472            Ok(p) => p,
473            Err(e) => return format!("ERROR: path blocked by jail: {e}"),
474        };
475    // #475: replace/insert symbol edits always write; deny inside a read-only root.
476    if let Some(e) = deny_if_read_only(&abs_path) {
477        return e;
478    }
479
480    let content = match std::fs::read_to_string(&abs_path) {
481        Ok(c) => c,
482        Err(e) => return format!("ERROR: FILE_NOT_FOUND: {abs_path}: {e}"),
483    };
484
485    // 3) Build the canonical range + final wire text per action.
486    let expected_hash = args
487        .get("expected_hash")
488        .and_then(Value::as_str)
489        .map(String::from);
490    let (range, text) = match action {
491        "replace_symbol_body" => {
492            let Some(new_body) = args.get("new_body").and_then(Value::as_str) else {
493                return "ERROR: 'new_body' is required for replace_symbol_body.".to_string();
494            };
495            let end_col = content
496                .lines()
497                .nth(end_line.saturating_sub(1))
498                .map_or(0, str::len) as u32;
499            (
500                crate::lsp::backend::TextRange0Based {
501                    start_line: (start_line - 1) as u32,
502                    start_char: 0,
503                    end_line: (end_line - 1) as u32,
504                    end_char: end_col,
505                },
506                new_body.to_string(),
507            )
508        }
509        "insert_before_symbol" | "insert_after_symbol" => {
510            let Some(t) = args.get("text").and_then(Value::as_str) else {
511                return format!("ERROR: 'text' is required for {action}.");
512            };
513            let indent = anchor_indent(&content, start_line);
514            let final_text = format!("{}\n", reindent_first_line(t, &indent));
515            let insert_line = if action == "insert_before_symbol" {
516                (start_line - 1) as u32
517            } else {
518                end_line as u32
519            };
520            (
521                crate::lsp::backend::TextRange0Based {
522                    start_line: insert_line,
523                    start_char: 0,
524                    end_line: insert_line,
525                    end_char: 0,
526                },
527                final_text,
528            )
529        }
530        other => return format!("ERROR: INTERNAL: not an edit action: {other}"),
531    };
532
533    // CONFLICT guard (BLAKE3, same source as headless local_range_write): verify
534    // expected_hash against the current on-disk range BEFORE dispatch. This makes
535    // the IDE path enforce CONFLICT identically to the headless path (which also
536    // re-checks atomically). hash_hex == blake3::hash(...).to_hex().
537    if let Some(exp) = &expected_hash {
538        let s =
539            match crate::lsp::edit_apply::offset_of(&content, range.start_line, range.start_char) {
540                Ok(o) => o,
541                Err(e) => return format!("ERROR: {e}"),
542            };
543        let e = match crate::lsp::edit_apply::offset_of(&content, range.end_line, range.end_char) {
544            Ok(o) => o,
545            Err(e) => return format!("ERROR: {e}"),
546        };
547        if e < s {
548            return "ERROR: POSITION_OUT_OF_RANGE: end before start".to_string();
549        }
550        let actual = crate::core::hasher::hash_hex(&content.as_bytes()[s..e]);
551        if *exp != actual {
552            return format!(
553                "ERROR: CONFLICT: range hash mismatch (expected={exp}, actual={actual})"
554            );
555        }
556    }
557
558    let edit = crate::lsp::backend::RangeEdit {
559        abs_path,
560        rel_path,
561        range,
562        text,
563        expected_hash,
564    };
565
566    // 4) Dispatch (IDE-first, headless fallback) + format.
567    match apply_symbol_edit(action, project_root, &edit) {
568        Ok(res) => format_edit_result(action, &res),
569        Err(e) => format!("ERROR: {e}"),
570    }
571}
572
573fn format_edit_result(action: &str, res: &crate::lsp::backend::EditResult) -> String {
574    if !res.applied {
575        return format!("{action}: not applied.");
576    }
577    let r = res.new_range;
578    let body = if res.diff.is_empty() {
579        res.edited_text.clone()
580    } else {
581        res.diff.clone()
582    };
583    format!(
584        "{action} applied (L{}:{}-L{}:{}):\n{}",
585        r.start_line + 1,
586        r.start_char,
587        r.end_line + 1,
588        r.end_char,
589        body
590    )
591}
592
593fn handle_inspections(
594    args: &Value,
595    file_path: &str,
596    project_root: &str,
597    uri: &lsp_types::Uri,
598) -> String {
599    let mode = args.get("mode").and_then(Value::as_str).unwrap_or("run");
600    match mode {
601        "run" => {
602            let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
603                let diags = backend.inspections(uri)?;
604                Ok((diags, backend.last_truncation()))
605            });
606            match result {
607                Ok((diags, meta)) => {
608                    let mut out = format_inspections(&diags);
609                    out.push_str(&truncation_note(diags.len(), meta));
610                    out
611                }
612                Err(e) => format!("ERROR: {e}"),
613            }
614        }
615        "list" => {
616            let result = crate::lsp::router::with_backend(file_path, project_root, |backend, _| {
617                let items = backend.list_inspections()?;
618                Ok((items, backend.last_truncation()))
619            });
620            match result {
621                Ok((items, meta)) => {
622                    let mut out = format_inspection_list(&items);
623                    out.push_str(&truncation_note(items.len(), meta));
624                    out
625                }
626                Err(e) => format!("ERROR: {e}"),
627            }
628        }
629        other => format!("ERROR: Unknown mode '{other}' for inspections. Available: run, list."),
630    }
631}
632
633fn format_inspections(diags: &[InspectionDiag]) -> String {
634    if diags.is_empty() {
635        return "No inspection findings.".to_string();
636    }
637    let mut out = format!("{} finding(s):\n", diags.len());
638    for d in diags {
639        out.push_str(&format!(
640            "  {}:{}  {}  {}\n",
641            d.path, d.line, d.severity, d.message
642        ));
643    }
644    out
645}
646
647fn format_inspection_list(items: &[InspectionInfo]) -> String {
648    if items.is_empty() {
649        return "No inspections enabled.".to_string();
650    }
651    let mut out = format!("{} inspection(s):\n", items.len());
652    for i in items {
653        out.push_str(&format!("  {}  {}  {}\n", i.id, i.name, i.severity));
654    }
655    out
656}
657
658fn truncation_note(shown: usize, meta: Option<crate::lsp::backend::Truncation>) -> String {
659    match meta {
660        Some(m) if m.truncated => {
661            format!("\n(truncated — showing {shown} of {})\n", m.total)
662        }
663        _ => String::new(),
664    }
665}
666
667fn format_type_hierarchy(root: &TypeHierarchyNode) -> String {
668    fn walk(node: &TypeHierarchyNode, depth: usize, out: &mut String) {
669        let indent = "  ".repeat(depth);
670        out.push_str(&format!(
671            "{indent}{} ({}:{})\n",
672            node.name, node.path, node.line
673        ));
674        for child in &node.children {
675            walk(child, depth + 1, out);
676        }
677    }
678    let mut out = String::new();
679    walk(root, 0, &mut out);
680    out
681}
682
683fn format_symbols_overview(items: &[SymbolOverviewItem]) -> String {
684    if items.is_empty() {
685        return "No symbols found.".to_string();
686    }
687    let mut out = format!("{} symbol(s):\n", items.len());
688    for item in items {
689        out.push_str(&format!(
690            "  {} {} (line {})\n",
691            item.kind, item.name, item.line
692        ));
693    }
694    out
695}
696
697fn format_locations(locations: &[Location], project_root: &str) -> String {
698    if locations.is_empty() {
699        return "No results found.".to_string();
700    }
701
702    let mut out = format!("{} location(s):\n", locations.len());
703    for loc in locations {
704        let path = uri_to_file_path(&loc.uri).map_or_else(
705            || loc.uri.as_str().to_string(),
706            |p| {
707                p.strip_prefix(project_root)
708                    .map(|s| s.strip_prefix('/').unwrap_or(s).to_string())
709                    .unwrap_or(p)
710            },
711        );
712
713        let line = loc.range.start.line + 1;
714        let col = loc.range.start.character;
715        out.push_str(&format!("  {path}:{line}:{col}\n"));
716    }
717    out
718}
719
720fn format_workspace_edit(edit: &lsp_types::WorkspaceEdit, project_root: &str) -> String {
721    let mut out = String::from("Rename edits:\n");
722    let mut file_count = 0;
723    let mut edit_count = 0;
724
725    if let Some(ref changes) = edit.changes {
726        for (uri, edits) in changes {
727            let path = uri_to_file_path(uri).map_or_else(
728                || uri.as_str().to_string(),
729                |p| {
730                    p.strip_prefix(project_root)
731                        .map(|s| s.strip_prefix('/').unwrap_or(s).to_string())
732                        .unwrap_or(p)
733                },
734            );
735
736            file_count += 1;
737            out.push_str(&format!("  {path}: {} edit(s)\n", edits.len()));
738            for e in edits {
739                edit_count += 1;
740                let line = e.range.start.line + 1;
741                out.push_str(&format!("    L{line}: -> \"{}\"\n", e.new_text));
742            }
743        }
744    }
745
746    if let Some(ref doc_changes) = edit.document_changes {
747        match doc_changes {
748            lsp_types::DocumentChanges::Edits(edits) => {
749                for text_edit in edits {
750                    let path = uri_to_file_path(&text_edit.text_document.uri)
751                        .unwrap_or_else(|| text_edit.text_document.uri.as_str().to_string());
752                    file_count += 1;
753                    let edits_len = text_edit.edits.len();
754                    edit_count += edits_len;
755                    out.push_str(&format!("  {path}: {edits_len} edit(s)\n"));
756                }
757            }
758            lsp_types::DocumentChanges::Operations(ops) => {
759                for op in ops {
760                    if let lsp_types::DocumentChangeOperation::Edit(text_edit) = op {
761                        let path = uri_to_file_path(&text_edit.text_document.uri)
762                            .unwrap_or_else(|| text_edit.text_document.uri.as_str().to_string());
763                        file_count += 1;
764                        let edits_len = text_edit.edits.len();
765                        edit_count += edits_len;
766                        out.push_str(&format!("  {path}: {edits_len} edit(s)\n"));
767                    }
768                }
769            }
770        }
771    }
772
773    out.push_str(&format!(
774        "\nTotal: {edit_count} edit(s) across {file_count} file(s)."
775    ));
776    out
777}
778
779#[cfg(test)]
780mod tests;
781#[cfg(test)]
782mod tests_ops;