From 9f9beaa27c8492a6ab26322b6b5fccf44aee1e56 Mon Sep 17 00:00:00 2001 From: lleviathe <95321986+lleviathe@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:27:25 +0400 Subject: [PATCH] feat(mcp): show the callers and callees of a function with get_call_hierarchy (#4019) The built-in MCP server had no call hierarchy, so agents fell back to text search for callers. get_call_hierarchy returns one level of callers (default) or callees of the function at a position through lsp_call_hierarchy, with call sites and their line text, paging and scope like find_references; a position inside a body means the enclosing function. ide-lsp reports the hierarchy's root and the file of an outgoing call's sites. find_references now shares the document guard and the cancel/timeout race with it. Co-authored-by: lleviathe <95321986+lleviathe@users.noreply.github.com> --- crates/ide-host/src/mcp/mod.rs | 1 + crates/ide-host/src/mcp/search.rs | 2 +- crates/ide-host/src/mcp/symbols.rs | 444 ++++++++++++++++++++++++++-- crates/ide-host/tests/mcp.rs | 243 +++++++++++++++ crates/ide-lsp/src/convert.rs | 2 + crates/ide-lsp/src/lib.rs | 10 +- crates/ide-lsp/src/scope.rs | 1 + crates/ide-lsp/src/types.rs | 9 + crates/ide-lsp/tests/mock_server.rs | 27 +- docs/en/guide/mcp.mdx | 27 +- docs/zh/guide/mcp.mdx | 27 +- src/bindings.ts | 12 + 12 files changed, 747 insertions(+), 58 deletions(-) diff --git a/crates/ide-host/src/mcp/mod.rs b/crates/ide-host/src/mcp/mod.rs index ac83acef4..12edc4285 100644 --- a/crates/ide-host/src/mcp/mod.rs +++ b/crates/ide-host/src/mcp/mod.rs @@ -40,6 +40,7 @@ fn tools() -> Vec { tools.push(check::check_files()); tools.push(symbols::get_symbol_info()); tools.push(symbols::find_references()); + tools.push(symbols::get_call_hierarchy()); tools.extend(edit::tools()); tools.extend(run::tools()); tools.extend(vcs::tools()); diff --git a/crates/ide-host/src/mcp/search.rs b/crates/ide-host/src/mcp/search.rs index f1c187c16..1e456b83c 100644 --- a/crates/ide-host/src/mcp/search.rs +++ b/crates/ide-host/src/mcp/search.rs @@ -280,7 +280,7 @@ fn context(call: &Call) -> IdeResult<(u32, u32)> { /// `line`, or when longer than [`MAX_LINE_TEXT`] UTF-16 units, the part from [`SNIPPET_AROUND`] /// units before 0-based UTF-16 column `start` to as many after `end`, with `…` where it was cut. -fn snippet(line: &str, start: usize, end: usize) -> String { +pub(super) fn snippet(line: &str, start: usize, end: usize) -> String { let units: usize = line.chars().map(char::len_utf16).sum(); if units <= MAX_LINE_TEXT { return line.to_owned(); diff --git a/crates/ide-host/src/mcp/symbols.rs b/crates/ide-host/src/mcp/symbols.rs index 98bf22f78..c0174ed39 100644 --- a/crates/ide-host/src/mcp/symbols.rs +++ b/crates/ide-host/src/mcp/symbols.rs @@ -1,10 +1,13 @@ //! Quick Documentation through the project's language services. use super::tool::{Call, Output, Param, ParamType, Tool}; -use ide_core::{IdeError, IdeResult, Pos, Range}; -use ide_lsp::types::GotoKind; +use ide_core::error::ErrorKind; +use ide_core::{DocId, IdeError, IdeResult, OutlineItem, Pos, Range, RequestId, SymbolKind}; +use ide_lsp::types::{CallHierarchy, GotoKind, HierarchyDirection, HierarchyItem, ReferencesIncomplete}; use serde::Serialize; use serde_json::json; -use std::path::Path; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; pub fn get_symbol_info() -> Tool { Tool::new("get_symbol_info", "Retrieves information about the symbol at the specified position in the specified file. @@ -212,26 +215,10 @@ pub fn find_references() -> Tool { let path = call.resolve_readable(&call.str("filePath")?).await?; let page = super::page::Page::of(&call, REFERENCES_LIMIT)?; let dir = super::scope::Scope::of(&call)?; - let line = call.opt_i64("line")?.ok_or_else(|| IdeError::invalid("missing line"))?; - let column = call.opt_i64("column")?.ok_or_else(|| IdeError::invalid("missing column"))?; - let project = call.project.clone(); - let (doc, text) = call.host.blocking(move || { - let text = project.text_of(&path)?; - let doc = project.documents.open(&path)?; - Ok((doc.id, text)) - }).await?; - struct Close(std::sync::Arc, ide_core::DocId); - impl Drop for Close { fn drop(&mut self) { self.0.documents.close(self.1); } } - let _close = Close(call.project.clone(), doc); - let pos = mcp_position(&text, line, column)?; + let opened = open_at(&call, path).await?; let request = super::tool::request_id(); - let work = crate::ops::lsp::lsp_references(&call.host, &call.window, request, doc, pos, call.flag("includeDeclaration", true)?, true, false, crate::ops::Channel::new(|_| {})); - tokio::pin!(work); - let result = tokio::select! { - result = &mut work => result?, - _ = call.cancel.cancelled() => { call.host.cancel_request(request); let _ = work.await; return Err(IdeError::cancelled()); } - _ = tokio::time::sleep(std::time::Duration::from_secs(60)) => { call.host.cancel_request(request); let _ = work.await; return Err(IdeError::unavailable("references timed out; retry when analysis finishes")); } - }; + let work = crate::ops::lsp::lsp_references(&call.host, &call.window, request, opened.doc, opened.pos, call.flag("includeDeclaration", true)?, true, false, crate::ops::Channel::new(|_| {})); + let result = race(&call, request, work, "references timed out; retry when analysis finishes").await?; let mut value = serde_json::to_value(&result).map_err(|e| IdeError::internal(e.to_string()))?; // Convert every Location range at this boundary, including declarations. fn positions(value: &mut serde_json::Value) { @@ -274,6 +261,266 @@ pub fn find_references() -> Tool { /// References `find_references` lists by default. const REFERENCES_LIMIT: usize = 100; +/// A document a tool opened for the language services and the position it asked about; +/// dropping it closes the document. +#[must_use] +struct Opened { + project: Arc, + doc: DocId, + pos: Pos, +} + +impl Drop for Opened { + fn drop(&mut self) { + self.project.documents.close(self.doc); + } +} + +/// Opens `path` at the call's 1-based `line` and `column`. +async fn open_at(call: &Call, path: PathBuf) -> IdeResult { + let line = call.opt_i64("line")?.ok_or_else(|| IdeError::invalid("missing line"))?; + let column = call.opt_i64("column")?.ok_or_else(|| IdeError::invalid("missing column"))?; + let project = call.project.clone(); + let (doc, text) = call + .host + .blocking(move || { + let text = project.text_of(&path)?; + let doc = project.documents.open(&path)?; + Ok((doc.id, text)) + }) + .await?; + let mut opened = Opened { project: call.project.clone(), doc, pos: Pos::default() }; + opened.pos = mcp_position(&text, line, column)?; + Ok(opened) +} + +/// How long a tool waits for a language service request. +const LANGUAGE_SERVICE_TIMEOUT: Duration = Duration::from_secs(60); + +/// `work`, the language service `request`, until it ends; when the client cancels or +/// [`LANGUAGE_SERVICE_TIMEOUT`] passes first, the request is cancelled and `work` runs to its end. +async fn race( + call: &Call, + request: RequestId, + work: impl Future>, + timed_out: &'static str, +) -> IdeResult { + tokio::pin!(work); + tokio::select! { + result = &mut work => result, + _ = call.cancel.cancelled() => { + call.host.cancel_request(request); + let _ = work.await; + Err(IdeError::cancelled()) + } + _ = tokio::time::sleep(LANGUAGE_SERVICE_TIMEOUT) => { + call.host.cancel_request(request); + let _ = work.await; + Err(IdeError::unavailable(timed_out)) + } + } +} + +pub fn get_call_hierarchy() -> Tool { + Tool::new( + "get_call_hierarchy", + "Callers (incoming) or callees (outgoing) of the function or method at the position, from \ + the language server's call hierarchy. A position inside a function body means that function. \ + One level per call: to go deeper, call again with an item's filePath, startLine and startColumn \ + (items in libraries show a URI as filePath and cannot be expanded). \ + Positions are 1-based UTF-16. `root` is the symbol the hierarchy is for; each item's callSites \ + are where the call happens. Reports incomplete results when analysis is still running.", + call_hierarchy, + ) + .param(Param::required("filePath", ParamType::String, "Path relative to the project root")) + .param(Param::required("line", ParamType::Integer, "1-based line")) + .param(Param::required("column", ParamType::Integer, "1-based UTF-16 column")) + .param(Param::optional("direction", ParamType::String, "incoming (callers, default) or outgoing (callees)")) + .param(super::scope::param()) + .param(Param::optional("limit", ParamType::Integer, "Items to return at most (default 100)")) + .param(Param::optional("offset", ParamType::Integer, super::page::OFFSET)) +} + +/// Items `get_call_hierarchy` lists by default. +const CALLS_LIMIT: usize = 100; +/// Call sites shown per item; `callSiteCount` gives the total when there are more. +const MAX_CALL_SITES: usize = 20; +const CALLS_TIMED_OUT: &str = "call hierarchy timed out; retry when analysis finishes"; + +async fn call_hierarchy(call: Call) -> IdeResult { + let direction = match call.opt_str("direction")?.as_deref() { + None | Some("incoming") => HierarchyDirection::Incoming, + Some("outgoing") => HierarchyDirection::Outgoing, + Some(_) => return Err(IdeError::invalid("direction must be incoming or outgoing")), + }; + let page = super::page::Page::of(&call, CALLS_LIMIT)?; + let scope = super::scope::Scope::of(&call)?; + let path = call.resolve_readable(&call.str("filePath")?).await?; + let opened = open_at(&call, path).await?; + let hierarchy_at = |pos| { + let request = super::tool::request_id(); + let work = crate::ops::lsp::lsp_call_hierarchy(&call.host, &call.window, request, opened.doc, pos, direction); + race(&call, request, work, CALLS_TIMED_OUT) + }; + let mut found = match hierarchy_at(opened.pos).await { + // IDEA: inside a function body the hierarchy is the enclosing function's. + Err(e) if e.kind == ErrorKind::NotFound => { + let outline = tokio::select! { + outline = crate::ops::doc::doc_outline(&call.host, &call.window, opened.doc) => outline?, + _ = call.cancel.cancelled() => return Err(IdeError::cancelled()), + }; + let at = enclosing_callable(&outline, opened.pos).map(|f| f.selection_range.start); + let Some(at) = at.filter(|at| *at != opened.pos) else { + let Pos { line, col } = opened.pos; + return Err(IdeError::not_found(format!("no function or method at {}:{}", line + 1, col + 1))); + }; + hierarchy_at(at).await? + } + result => result?, + }; + if scope.dir().is_some() { + found.items.retain(|i| i.uri.is_none() && scope.contains(&i.path.0)); + } + let incomplete = found.incomplete; + let (mut root, items) = call_items(found, |p| call.display(p)); + let mut out = serde_json::Map::new(); + let mut items = page.take(items, &mut out); + // One file in memory at a time, as `search::fill_lines` reads them. + let mut places: Vec<&mut Place> = root + .iter_mut() + .chain(&mut items) + .flat_map(|i| std::iter::once(&mut i.at).chain(&mut i.call_sites)) + .filter(|place| place.file.is_some()) + .collect(); + places.sort_by(|a, b| a.file.cmp(&b.file)); + for in_file in places.chunk_by_mut(|a, b| a.file == b.file) { + if call.cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let Some(path) = in_file[0].file.clone() else { continue }; + if let Ok(text) = crate::ops::fs::fs_read_text(&call.host, call.window(), path).await { + fill_line_texts(in_file, &text); + } + } + Output::json(CallHierarchyOutput { root, items, page: out, incomplete }) +} + +#[derive(Serialize)] +struct CallHierarchyOutput { + #[serde(skip_serializing_if = "Option::is_none")] + root: Option, + items: Vec, + /// `total`, and `more` and `nextOffset` when items follow. + #[serde(flatten)] + page: serde_json::Map, + #[serde(skip_serializing_if = "Option::is_none")] + incomplete: Option, +} + +/// A function or method in the call hierarchy, at its name. +#[derive(Serialize, Debug)] +#[serde(rename_all = "camelCase")] +struct CallItem { + name: String, + kind: SymbolKind, + #[serde(skip_serializing_if = "Option::is_none")] + detail: Option, + #[serde(flatten)] + at: Place, + #[serde(skip_serializing_if = "Vec::is_empty")] + call_sites: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + call_site_count: Option, +} + +/// A range as the tools show it: 1-based UTF-16, with the text of its first line. +#[derive(Serialize, Debug)] +#[serde(rename_all = "camelCase")] +struct Place { + file_path: String, + start_line: u32, + start_column: u32, + end_line: u32, + end_column: u32, + #[serde(skip_serializing_if = "Option::is_none")] + line_text: Option, + /// The file `line_text` is read from; none in a library. + #[serde(skip)] + file: Option, +} + +/// The root and the items of `h`, sorted by file and position, with call sites in source +/// order, at most [`MAX_CALL_SITES`] per item. Library items show their URI. +fn call_items(h: CallHierarchy, display: impl Fn(&Path) -> String) -> (Option, Vec) { + let CallHierarchy { root, items, .. } = h; + // A file path, or the URI of a virtual document, which has no lines to read here. + let target = |path: &Path, uri: Option<&String>| match uri { + Some(uri) => (None, uri.clone()), + None => (Some(path.to_path_buf()), display(path)), + }; + let place = |(file, file_path): (Option, String), r: Range| Place { + file_path, + start_line: r.start.line + 1, + start_column: r.start.col + 1, + end_line: r.end.line + 1, + end_column: r.end.col + 1, + line_text: None, + file, + }; + let convert = |i: HierarchyItem| { + let at = target(&i.path.0, i.uri.as_ref()); + let sites_in = match &i.from_path { + Some(p) => { + let shown = p.0.to_string_lossy(); + target(&p.0, ide_core::is_virtual_uri(&shown).then(|| shown.into_owned()).as_ref()) + } + None => at.clone(), + }; + let mut sites = i.from_ranges; + sites.sort(); + sites.dedup(); + let count = sites.len(); + CallItem { + call_sites: sites.into_iter().take(MAX_CALL_SITES).map(|r| place(sites_in.clone(), r)).collect(), + call_site_count: (count > MAX_CALL_SITES).then_some(count), + at: place(at, i.selection_range), + name: i.name, + kind: i.kind, + detail: i.detail, + } + }; + let mut items: Vec = items.into_iter().map(&convert).collect(); + items.sort_by(|a, b| { + (&a.at.file_path, a.at.start_line, a.at.start_column).cmp(&( + &b.at.file_path, + b.at.start_line, + b.at.start_column, + )) + }); + (root.map(convert), items) +} + +/// Fills `lineText` of `places`, which are all in the file whose text is `text`. +fn fill_line_texts(places: &mut [&mut Place], text: &str) { + let lines: Vec<&str> = text.split('\n').collect(); + for place in places { + let Some(line) = lines.get(place.start_line as usize - 1) else { continue }; + let line = line.strip_suffix('\r').unwrap_or(line); + let start = place.start_column as usize - 1; + let end = if place.end_line == place.start_line { place.end_column as usize - 1 } else { start }; + place.line_text = Some(super::search::snippet(line, start, end)); + } +} + +/// The innermost function, method or constructor of `outline` whose extent holds `pos`, +/// as the IDE's Call Hierarchy finds it. +fn enclosing_callable(outline: &[OutlineItem], pos: Pos) -> Option<&OutlineItem> { + let item = outline.iter().find(|i| i.range.start <= pos && pos <= i.range.end)?; + enclosing_callable(&item.children, pos).or_else(|| { + matches!(item.kind, SymbolKind::Function | SymbolKind::Method | SymbolKind::Constructor).then_some(item) + }) +} + fn mcp_position(text: &str, line: i64, column: i64) -> IdeResult { if line < 1 || line > u32::MAX as i64 || column < 1 || column > u32::MAX as i64 { return Err(IdeError::invalid("line and column must be positive 1-based positions")); @@ -284,3 +531,156 @@ fn mcp_position(text: &str, line: i64, column: i64) -> IdeResult { } Ok(Pos::new((line - 1) as u32, (column - 1) as u32)) } + +#[cfg(test)] +mod tests { + use super::*; + + fn range(line: u32, col: u32, end_line: u32, end_col: u32) -> Range { + Range::new(Pos::new(line, col), Pos::new(end_line, end_col)) + } + + fn item(name: &str, path: &str, line: u32, from_ranges: Vec) -> HierarchyItem { + HierarchyItem { + name: name.into(), + kind: SymbolKind::Function, + detail: Some(format!("fn {name}()")), + path: PathBuf::from(path).into(), + uri: None, + range: range(line, 0, line + 2, 1), + selection_range: range(line, 3, line, 3 + name.len() as u32), + from_ranges, + from_path: None, + } + } + + fn shown(path: &Path) -> String { + path.strip_prefix("/p").unwrap_or(path).to_string_lossy().into_owned() + } + + fn hierarchy(root: HierarchyItem, items: Vec) -> CallHierarchy { + CallHierarchy { root: Some(root), items, incomplete: None } + } + + #[test] + fn incoming_call_sites_are_in_the_callers_file_one_based() { + let h = hierarchy( + item("price", "/p/src/lib.rs", 10, Vec::new()), + vec![item("main", "/p/src/main.rs", 2, vec![range(4, 8, 4, 13)])], + ); + let (root, items) = call_items(h, shown); + let root = serde_json::to_value(root.unwrap()).unwrap(); + assert_eq!( + root, + json!({"name":"price","kind":"function","detail":"fn price()","filePath":"src/lib.rs", + "startLine":11,"startColumn":4,"endLine":11,"endColumn":9}) + ); + assert_eq!( + serde_json::to_value(&items).unwrap(), + json!([{"name":"main","kind":"function","detail":"fn main()","filePath":"src/main.rs", + "startLine":3,"startColumn":4,"endLine":3,"endColumn":8, + "callSites":[{"filePath":"src/main.rs","startLine":5,"startColumn":9,"endLine":5,"endColumn":14}]}]) + ); + } + + #[test] + fn outgoing_call_sites_are_in_the_file_ide_lsp_names() { + let mut price = item("price", "/p/src/lib.rs", 10, vec![range(4, 8, 4, 13)]); + price.from_path = Some(PathBuf::from("/p/src/main.rs").into()); + let (_, items) = call_items(hierarchy(item("main", "/p/src/main.rs", 2, Vec::new()), vec![price]), shown); + assert_eq!(items[0].at.file_path, "src/lib.rs"); + assert_eq!(items[0].call_sites[0].file_path, "src/main.rs"); + assert_eq!(items[0].call_sites[0].file.as_deref(), Some(Path::new("/p/src/main.rs"))); + } + + #[test] + fn library_items_show_their_uri() { + let mut library = item("len", "/virtual", 0, vec![range(4, 8, 4, 11)]); + library.uri = Some("jar:file:///lib.jar!/Str.class".into()); + library.from_path = Some(PathBuf::from("/p/src/main.rs").into()); + let mut called_from_library = item("parse", "/p/src/a.rs", 3, vec![range(1, 0, 1, 4)]); + called_from_library.from_path = Some(PathBuf::from("jdt://contents/lib.jar/Caller.class").into()); + let h = hierarchy(item("main", "/p/src/main.rs", 2, Vec::new()), vec![library, called_from_library]); + let (_, items) = call_items(h, shown); + assert_eq!(items[0].at.file_path, "jar:file:///lib.jar!/Str.class"); + assert_eq!(items[0].at.file, None, "no line text for a library item"); + assert_eq!(items[0].call_sites[0].file_path, "src/main.rs"); + assert_eq!(items[1].call_sites[0].file_path, "jdt://contents/lib.jar/Caller.class"); + assert_eq!(items[1].call_sites[0].file, None); + } + + #[test] + fn call_items_are_sorted_by_file_and_line() { + let h = hierarchy( + item("price", "/p/src/lib.rs", 10, Vec::new()), + vec![ + item("c", "/p/src/main.rs", 9, Vec::new()), + item("b", "/p/src/main.rs", 2, Vec::new()), + item("a", "/p/src/a.rs", 5, Vec::new()), + ], + ); + let (_, items) = call_items(h, shown); + assert_eq!(items.iter().map(|i| i.name.as_str()).collect::>(), ["a", "b", "c"]); + } + + #[test] + fn call_sites_are_capped_with_their_count() { + let sites = (0..MAX_CALL_SITES as u32 + 5).map(|l| range(l, 0, l, 1)).collect(); + let h = hierarchy(item("price", "/p/src/lib.rs", 10, Vec::new()), vec![item("main", "/p/a.rs", 0, sites)]); + let (_, items) = call_items(h, shown); + assert_eq!(items[0].call_sites.len(), MAX_CALL_SITES); + assert_eq!(items[0].call_site_count, Some(MAX_CALL_SITES + 5)); + let one = hierarchy( + item("price", "/p/src/lib.rs", 10, Vec::new()), + vec![item("main", "/p/a.rs", 0, vec![range(1, 0, 1, 1)])], + ); + assert_eq!(call_items(one, shown).1[0].call_site_count, None); + } + + #[test] + fn call_sites_are_in_source_order_without_duplicates() { + let sites = vec![range(5, 0, 5, 1), range(1, 4, 1, 5), range(5, 0, 5, 1), range(1, 2, 1, 3)]; + let h = hierarchy(item("price", "/p/src/lib.rs", 10, Vec::new()), vec![item("main", "/p/a.rs", 0, sites)]); + let (_, items) = call_items(h, shown); + let at: Vec<_> = items[0].call_sites.iter().map(|s| (s.start_line, s.start_column)).collect(); + assert_eq!(at, [(2, 3), (2, 5), (6, 1)]); + assert_eq!(items[0].call_site_count, None); + } + + #[test] + fn line_text_is_cut_from_the_line_of_each_place() { + let h = hierarchy(item("price", "/p/src/lib.rs", 3, vec![range(0, 4, 0, 9), range(1, 0, 3, 1)]), Vec::new()); + let mut root = call_items(h, shown).0.unwrap(); + let mut places: Vec<&mut Place> = std::iter::once(&mut root.at).chain(&mut root.call_sites).collect(); + fill_line_texts(&mut places, " price();\r\nfn other() {\n\nfn price() {}"); + assert_eq!(root.at.line_text.as_deref(), Some("fn price() {}")); + assert_eq!(root.call_sites[0].line_text.as_deref(), Some(" price();")); + assert_eq!(root.call_sites[1].line_text.as_deref(), Some("fn other() {"), "a range over lines"); + } + + #[test] + fn enclosing_callable_is_the_innermost_function() { + let outline = |name: &str, kind, range, children| OutlineItem { + name: name.into(), + detail: None, + kind, + range, + selection_range: Range::new(range.start, range.start), + children, + visibility: None, + }; + let method = outline( + "total", + SymbolKind::Method, + range(2, 4, 8, 5), + vec![outline("add", SymbolKind::Function, range(3, 8, 5, 9), Vec::new())], + ); + let items = vec![outline("Cart", SymbolKind::Struct, range(0, 0, 9, 1), vec![method])]; + let name = |pos| enclosing_callable(&items, pos).map(|i| i.name.as_str()); + assert_eq!(name(Pos::new(4, 0)), Some("add")); + assert_eq!(name(Pos::new(5, 9)), Some("add"), "the end is inside"); + assert_eq!(name(Pos::new(7, 0)), Some("total")); + assert_eq!(name(Pos::new(0, 3)), None, "a struct is not callable"); + assert_eq!(name(Pos::new(12, 0)), None); + } +} diff --git a/crates/ide-host/tests/mcp.rs b/crates/ide-host/tests/mcp.rs index 8f86bfc58..491d14a95 100644 --- a/crates/ide-host/tests/mcp.rs +++ b/crates/ide-host/tests/mcp.rs @@ -662,6 +662,34 @@ async fn rust_references_and_rename_through_mcp() { assert!(std::time::Instant::now() < deadline, "language server did not find format_price references"); tokio::time::sleep(std::time::Duration::from_millis(500)).await; } + // Its callers, the callees of one of them, and the hierarchy at a call. + let callers = h.json("get_call_hierarchy", args.clone()).await; + assert_eq!(callers["root"]["name"], "format_price", "{callers}"); + let main = callers["items"].as_array().unwrap().iter().find(|i| i["name"] == "main").expect("main calls it"); + assert_eq!(main["filePath"], "src/main.rs"); + let call = main["callSites"] + .as_array() + .unwrap() + .iter() + .find(|s| s["lineText"].as_str().unwrap().contains("format_price(")) + .expect("the call in main"); + assert_eq!(call["filePath"], "src/main.rs"); + let callees = h + .json("get_call_hierarchy", json!({"filePath":"src/main.rs", "line":main["startLine"], "column":main["startColumn"], "direction":"outgoing"})) + .await; + // rust-analyzer leaves out the calls inside macro arguments, such as `format_price` in `println!`. + let parse = callees["items"].as_array().unwrap().iter().find(|i| i["name"] == "parse").expect("main calls parse"); + assert_eq!( + (&parse["filePath"], &parse["callSites"][0]["filePath"]), + (&json!("src/parser.rs"), &json!("src/main.rs")) + ); + let at_call = h + .json("get_call_hierarchy", json!({"filePath":"src/main.rs", "line":call["startLine"], "column":call["startColumn"], "direction":"outgoing"})) + .await; + assert_eq!( + (&at_call["root"]["name"], &at_call["root"]["filePath"]), + (&json!("format_price"), &json!("src/lib.rs")) + ); let result = h.json("rename_refactoring", json!({"pathInProject":"src/lib.rs", "symbolName":"format_price", "newName":"format_amount", "line":line + 1, "column":column})).await; assert_eq!(result["applied"], true, "{result}"); assert!(project.documents.text_snapshot(doc.id).unwrap().text.contains("format_amount")); @@ -979,3 +1007,218 @@ async fn http_list_and_run_require_confirmation() { assert!(result.get("headers").is_none(), "{result}"); assert!(result.get("request").is_none(), "{result}"); } + +#[tokio::test(flavor = "multi_thread")] +async fn call_hierarchy_is_listed_for_untrusted_projects() { + let h = Harness::new(); + let tools = Registry::new(h.host.clone()).tools(&h.root).unwrap(); + assert!(tools.iter().any(|t| t.name == "get_call_hierarchy")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn call_hierarchy_without_a_language_server_says_it_is_unsupported() { + let h = Harness::new(); + let error = h.error("get_call_hierarchy", json!({"filePath":"src/a.txt","line":1,"column":1})).await; + assert!(error.contains("call hierarchy"), "{error}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn call_hierarchy_rejects_an_unknown_direction() { + let h = Harness::new(); + let args = json!({"filePath":"src/a.txt","line":1,"column":1,"direction":"up"}); + assert_eq!(h.error("get_call_hierarchy", args).await, "direction must be incoming or outgoing"); +} + +/// `src/lib.rs`: `price` calls `double`; `src/main.rs`: `main` calls `price` and `show`; +/// `other/c.rs`: `helper` calls `price`; a library class calls it too. +const LIB_RS: &str = "pub fn price(cents: u64) -> u64 {\n double(cents)\n}\nfn double(v: u64) -> u64 { v * 2 }\n"; +const MAIN_RS: &str = "fn main() {\n let a = price(1);\n show(a);\n}\nfn show(v: u64) {}\n"; +const C_RS: &str = "fn helper() {\n price(2);\n}\n"; +const LIBRARY_URI: &str = "jar:file:///lib.jar!/Caller.class"; + +/// A language server for `rust` that knows the call hierarchy of the files above. +struct CallServer { + root: PathBuf, +} + +impl CallServer { + fn uri(&self, path: &str) -> String { + ide_lsp::path_to_uri_string(&self.root.join(path)) + } + fn item(&self, name: &str) -> Value { + let r = |l, c, l2, c2| json!({"start":{"line":l,"character":c},"end":{"line":l2,"character":c2}}); + let (uri, range, selection) = match name { + "price" => (self.uri("src/lib.rs"), r(0, 0, 2, 1), r(0, 7, 0, 12)), + "double" => (self.uri("src/lib.rs"), r(3, 0, 3, 34), r(3, 3, 3, 9)), + "main" => (self.uri("src/main.rs"), r(0, 0, 3, 1), r(0, 3, 0, 7)), + "show" => (self.uri("src/main.rs"), r(4, 0, 4, 18), r(4, 3, 4, 7)), + "helper" => (self.uri("other/c.rs"), r(0, 0, 2, 1), r(0, 3, 0, 9)), + _ => (LIBRARY_URI.to_owned(), r(0, 0, 9, 1), r(2, 4, 2, 10)), + }; + json!({"name":name,"kind":12,"uri":uri,"range":range,"selectionRange":selection}) + } + fn call(&self, name: &str, key: &str, sites: &[(u32, u32, u32)]) -> Value { + let sites: Vec = sites + .iter() + .map(|(l, c, c2)| json!({"start":{"line":l,"character":c},"end":{"line":l,"character":c2}})) + .collect(); + json!({key: self.item(name), "fromRanges": sites}) + } + /// The item named at `p`: on a declaration's name or on a call. + fn prepare(&self, p: &Value) -> Value { + let uri = p["textDocument"]["uri"].as_str().unwrap(); + let (line, col) = (p["position"]["line"].as_u64().unwrap(), p["position"]["character"].as_u64().unwrap()); + let on = + |path: &str, l: u64, from: u64, to: u64| uri == self.uri(path) && line == l && (from..=to).contains(&col); + let name = if on("src/lib.rs", 0, 7, 12) || on("src/main.rs", 1, 12, 17) { + "price" + } else if on("src/main.rs", 0, 3, 7) { + "main" + } else { + return Value::Null; + }; + json!([self.item(name)]) + } +} + +impl ide_jsonrpc::Handler for CallServer { + fn on_notification(&self, _: &str, _: Value) {} + fn on_request(&self, method: &str, p: Value) -> Result { + let item = p["item"]["name"].as_str().unwrap_or_default(); + Ok(match method { + "initialize" => json!({"capabilities": { + "textDocumentSync": {"openClose": true, "change": 1}, + "callHierarchyProvider": true, + "documentSymbolProvider": true, + }}), + "textDocument/prepareCallHierarchy" => self.prepare(&p), + "callHierarchy/incomingCalls" if item == "price" => json!([ + self.call("main", "from", &[(1, 12, 17)]), + self.call("helper", "from", &[(1, 4, 9)]), + self.call("Caller", "from", &[(2, 8, 13)]), + ]), + "callHierarchy/outgoingCalls" if item == "price" => json!([self.call("double", "to", &[(1, 4, 10)])]), + "callHierarchy/outgoingCalls" if item == "main" => { + json!([self.call("show", "to", &[(2, 4, 8)]), self.call("price", "to", &[(1, 12, 17)])]) + } + "textDocument/documentSymbol" if p["textDocument"]["uri"] == self.uri("src/main.rs") => { + let symbol = |name| { + let item = self.item(name); + json!({"name":name,"kind":12,"range":item["range"],"selectionRange":item["selectionRange"]}) + }; + json!([symbol("main"), symbol("show")]) + } + "callHierarchy/incomingCalls" | "callHierarchy/outgoingCalls" | "textDocument/documentSymbol" => json!([]), + _ => Value::Null, + }) + } +} + +/// The harness with the files above and [`CallServer`] serving them. +async fn call_hierarchy_harness() -> (Harness, tokio::task::JoinHandle<()>) { + let h = Harness::new(); + h.trust().await; + for (path, text) in [("src/lib.rs", LIB_RS), ("src/main.rs", MAIN_RS), ("other/c.rs", C_RS)] { + std::fs::create_dir_all(h.root.join(path).parent().unwrap()).unwrap(); + std::fs::write(h.root.join(path), text).unwrap(); + } + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = Arc::new(CallServer { root: h.root.clone() }); + let accept = tokio::spawn(async move { + let mut peers = Vec::new(); + while let Ok((stream, _)) = listener.accept().await { + let (r, w) = stream.into_split(); + peers.push(ide_jsonrpc::Peer::connect(r, w, server.clone())); + } + }); + let cfg: ide_language::LanguageServerConfig = + toml::from_str(&format!("name='calls'\ncommand='no-process-required'\nconnect='127.0.0.1:{port}'")).unwrap(); + h.host.project("main").unwrap().lsp.set_servers_hook(Box::new(move |language, _| { + if language.as_str() == "rust" { vec![cfg.clone()] } else { Vec::new() } + })); + (h, accept) +} + +fn names(result: &Value) -> Vec<&str> { + result["items"].as_array().unwrap().iter().map(|i| i["name"].as_str().unwrap()).collect() +} + +#[tokio::test(flavor = "multi_thread")] +async fn call_hierarchy_lists_callers_with_their_call_sites() { + let (h, _server) = call_hierarchy_harness().await; + let callers = h.json("get_call_hierarchy", json!({"filePath":"src/lib.rs","line":1,"column":9})).await; + assert_eq!(callers["root"]["name"], "price"); + assert_eq!(callers["root"]["filePath"], "src/lib.rs"); + assert_eq!(callers["root"]["lineText"], "pub fn price(cents: u64) -> u64 {"); + assert_eq!(callers["total"], 3); + let main = callers["items"].as_array().unwrap().iter().find(|i| i["name"] == "main").unwrap(); + assert_eq!( + main, + &json!({"name":"main","kind":"function","filePath":"src/main.rs", + "startLine":1,"startColumn":4,"endLine":1,"endColumn":8,"lineText":"fn main() {", + "callSites":[{"filePath":"src/main.rs","startLine":2,"startColumn":13,"endLine":2,"endColumn":18, + "lineText":" let a = price(1);"}]}) + ); + // An item's position is a valid input for the next level. + let main_calls = h + .json( + "get_call_hierarchy", + json!({"filePath":"src/main.rs","line":main["startLine"],"column":main["startColumn"],"direction":"outgoing"}), + ) + .await; + assert_eq!(names(&main_calls), ["price", "show"]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn outgoing_call_sites_are_in_the_file_of_the_root() { + let (h, _server) = call_hierarchy_harness().await; + // On the call `price(1)` in main.rs: the hierarchy of `price`, declared in lib.rs. + let callees = h + .json("get_call_hierarchy", json!({"filePath":"src/main.rs","line":2,"column":14,"direction":"outgoing"})) + .await; + assert_eq!(callees["root"]["filePath"], "src/lib.rs"); + assert_eq!(names(&callees), ["double"]); + assert_eq!( + callees["items"][0]["callSites"], + json!([{"filePath":"src/lib.rs","startLine":2,"startColumn":5,"endLine":2,"endColumn":11,"lineText":" double(cents)"}]) + ); + let from_main = h + .json("get_call_hierarchy", json!({"filePath":"src/main.rs","line":1,"column":4,"direction":"outgoing"})) + .await; + let price = &from_main["items"][0]; + assert_eq!((&price["filePath"], &price["callSites"][0]["filePath"]), (&json!("src/lib.rs"), &json!("src/main.rs"))); + assert_eq!(price["callSites"][0]["lineText"], " let a = price(1);"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_position_in_a_function_body_means_that_function() { + let (h, _server) = call_hierarchy_harness().await; + let body = json!({"filePath":"src/main.rs","line":2,"column":5,"direction":"outgoing"}); + let callees = h.json("get_call_hierarchy", body).await; + assert_eq!(callees["root"]["name"], "main"); + assert_eq!(names(&callees), ["price", "show"]); + let outside = h.error("get_call_hierarchy", json!({"filePath":"src/main.rs","line":6,"column":1})).await; + assert_eq!(outside, "no function or method at 6:1"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn call_hierarchy_pages_are_sorted_and_scoped() { + let (h, _server) = call_hierarchy_harness().await; + let at = |extra: Value| { + let mut args = json!({"filePath":"src/lib.rs","line":1,"column":9}); + args.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + args + }; + let first = h.json("get_call_hierarchy", at(json!({"limit":2}))).await; + assert_eq!(names(&first), ["Caller", "helper"]); + assert_eq!(first["items"][0]["filePath"], LIBRARY_URI); + assert!(first["items"][0].get("lineText").is_none(), "{first}"); + assert_eq!((&first["more"], &first["nextOffset"]), (&json!(true), &json!(2))); + let next = h.json("get_call_hierarchy", at(json!({"limit":2,"offset":2}))).await; + assert_eq!(names(&next), ["main"]); + let scoped = h.json("get_call_hierarchy", at(json!({"scope":"src"}))).await; + assert_eq!(names(&scoped), ["main"]); + assert_eq!(scoped["total"], 1); + assert_eq!(scoped["root"]["name"], "price", "the root is shown whatever the scope"); +} diff --git a/crates/ide-lsp/src/convert.rs b/crates/ide-lsp/src/convert.rs index 770e64691..aa8dfa911 100644 --- a/crates/ide-lsp/src/convert.rs +++ b/crates/ide-lsp/src/convert.rs @@ -1032,6 +1032,7 @@ pub fn call_item(conv: &Conv, item: &lsp::CallHierarchyItem, from_ranges: Vec Option, + /// The file of `from_ranges` when it is not the item's own: for an outgoing call, the + /// file of the prepared item that makes it (a path, or the URI of a virtual document). + #[serde(default)] + #[specta(optional)] + pub from_path: Option, } #[derive(Clone, Debug, Serialize, Deserialize, Type)] @@ -575,6 +580,10 @@ pub struct ServerRefactored { #[derive(Clone, Debug, Default, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct CallHierarchy { + /// The symbol the hierarchy is for: the first item the server prepared at the position. + #[serde(default)] + #[specta(optional)] + pub root: Option, pub items: Vec, pub incomplete: Option, } diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index 43f81d90d..ff75900a2 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -3934,17 +3934,32 @@ async fn navigation_rename_format_and_decorations() { let item = json!({ "name": "foo", "kind": 12, "uri": uri, "range": r(0,0,0,11), "selectionRange": r(0,3,0,6), "data": "id" }); s.respond("textDocument/prepareCallHierarchy", json!([item])); s.respond("callHierarchy/incomingCalls", json!([{ "from": { "name": "main", "kind": 12, "uri": uri, "range": r(1,0,1,6), "selectionRange": r(1,0,1,3) }, "fromRanges": [r(1,0,1,3)] }])); - let calls = h - .mgr - .call_hierarchy(doc, Pos::new(0, 4), HierarchyDirection::Incoming, Default::default()) - .await - .unwrap() - .items; + let hierarchy = + h.mgr.call_hierarchy(doc, Pos::new(0, 4), HierarchyDirection::Incoming, Default::default()).await.unwrap(); + let root = hierarchy.root.expect("the prepared item"); + assert_eq!((root.name.as_str(), root.selection_range), ("foo", rng(0, 3, 0, 6))); + assert_eq!(root.path.to_path_buf(), path); + let calls = hierarchy.items; assert_eq!(calls.len(), 1); assert_eq!(calls[0].name, "main"); assert_eq!(calls[0].from_ranges, vec![rng(1, 0, 1, 3)]); assert_eq!(s.requested("callHierarchy/incomingCalls")[0]["item"]["data"], "id"); + // Outgoing calls of each prepared item are in that item's file. + let other = path.with_file_name("b.mk"); + let second = + json!({ "name": "foo", "kind": 12, "uri": uri_of(&other), "range": r(4,0,4,11), "selectionRange": r(4,3,4,6) }); + s.respond("textDocument/prepareCallHierarchy", json!([item, second])); + s.respond("callHierarchy/outgoingCalls", json!([{ "to": { "name": "bar", "kind": 12, "uri": uri, "range": r(2,0,2,6), "selectionRange": r(2,0,2,3) }, "fromRanges": [r(0,8,0,11)] }])); + let callees = h + .mgr + .call_hierarchy(doc, Pos::new(0, 4), HierarchyDirection::Outgoing, Default::default()) + .await + .unwrap() + .items; + let from: Vec<_> = callees.iter().map(|c| c.from_path.clone().map(|p| p.into_path_buf())).collect(); + assert_eq!(from, [Some(path.clone()), Some(other)]); + // No documentSymbolProvider → None so callers fall back to tree-sitter. assert_eq!(h.mgr.document_symbols(doc).await.unwrap(), None); } diff --git a/docs/en/guide/mcp.mdx b/docs/en/guide/mcp.mdx index a5c3ba4af..bcb80159f 100644 --- a/docs/en/guide/mcp.mdx +++ b/docs/en/guide/mcp.mdx @@ -83,25 +83,26 @@ While the server runs, OpenIDEA writes its port and token to `mcp/server.json` i ## Tools -| Area | Tools | -| ------------- | --------------------------------------------------------------------------- | -| Files | `read_file`, `list_directory_tree`, `create_new_file`, `apply_patch` | -| Search | `search_text`, `search_regex`, `search_symbol`, `search_file` | -| Editors | `get_all_open_file_paths`, `get_current_file`, `open_file_in_editor` | -| Code | `get_symbol_info`, `find_references`, `rename_refactoring`, `reformat_file` | -| Problems | `get_file_problems`, `get_project_problems`, `check_files` | -| Run and build | `get_run_configurations`, `execute_run_configuration`, `build_project` | -| Commands | `run_command`, `wait_for_run`, `send_run_input`, `stop_run` | -| Command state | `get_run_status`, `read_run_output`, `list_runs` | -| Git | `get_repositories`, `git_status`, `git_diff` | -| HTTP Client | `http_list_requests`, `http_run_request` | +| Area | Tools | +| ------------- | ------------------------------------------------------------------------------------------------- | +| Files | `read_file`, `list_directory_tree`, `create_new_file`, `apply_patch` | +| Search | `search_text`, `search_regex`, `search_symbol`, `search_file` | +| Editors | `get_all_open_file_paths`, `get_current_file`, `open_file_in_editor` | +| Code | `get_symbol_info`, `find_references`, `get_call_hierarchy`, `rename_refactoring`, `reformat_file` | +| Problems | `get_file_problems`, `get_project_problems`, `check_files` | +| Run and build | `get_run_configurations`, `execute_run_configuration`, `build_project` | +| Commands | `run_command`, `wait_for_run`, `send_run_input`, `stop_run` | +| Command state | `get_run_status`, `read_run_output`, `list_runs` | +| Git | `get_repositories`, `git_status`, `git_diff` | +| HTTP Client | `http_list_requests`, `http_run_request` | Notes on what they do: - `read_file` also reads sources of dependencies and files inside jar and zip archives. - The tools that list things return one page: `limit` items (100 by default; 50 for `search_symbol`, 10 for `list_runs`), from `offset`. `total` (where counting is cheap), `more` and `nextOffset` say what follows. `list_runs` filters by `state` (`running`, `idle`, `error` or one state), `get_run_configurations` by `query`, and `get_project_problems` lists errors only unless `errorsOnly` is false. -- The query tools (the searches, `find_references`, `get_project_problems`, `git_status`, `get_all_open_file_paths`, `get_run_configurations`, `list_runs`) take `scope`: a directory, relative to the project root or absolute, that limits their results to the files in it, such as an attached project or one module. +- The query tools (the searches, `find_references`, `get_call_hierarchy`, `get_project_problems`, `git_status`, `get_all_open_file_paths`, `get_run_configurations`, `list_runs`) take `scope`: a directory, relative to the project root or absolute, that limits their results to the files in it, such as an attached project or one module. - `search_symbol` and `find_references` use the IDE's index and the language servers; `get_symbol_info` returns what Quick Documentation shows. +- `get_call_hierarchy` lists the callers of the function or method at a position, or with `direction` `outgoing` the functions it calls, one level per call. A position inside a function body means that function. To go one level deeper, call it again with an item's `filePath`, `startLine` and `startColumn`. Items in libraries show a URI as `filePath` and cannot be expanded. - `get_file_problems` and `get_project_problems` return what the Problems tool window shows, after your inspection profile is applied, rather than a fresh analysis. - `check_files` is the fresh analysis, for after an edit made by any tool: it syncs each file from disk, tells its language servers it was saved (so on-save checks such as `cargo check` run) and waits until they answered and finished. Each file gets a `status` that says whether the problems are complete, or why it could not be checked: no language server for it, or one that is not installed, misconfigured or crashed. - `rename_refactoring` renames through the language server, so references that a text search would miss are updated too. It can preview without writing. diff --git a/docs/zh/guide/mcp.mdx b/docs/zh/guide/mcp.mdx index 3a38d48f6..db64f15cd 100644 --- a/docs/zh/guide/mcp.mdx +++ b/docs/zh/guide/mcp.mdx @@ -82,25 +82,26 @@ stdio 配置大致如下(路径以你机器上的为准): ## 工具 -| 类别 | 工具 | -| ----------- | --------------------------------------------------------------------------- | -| 文件 | `read_file`、`list_directory_tree`、`create_new_file`、`apply_patch` | -| 搜索 | `search_text`、`search_regex`、`search_symbol`、`search_file` | -| 编辑器 | `get_all_open_file_paths`、`get_current_file`、`open_file_in_editor` | -| 代码 | `get_symbol_info`、`find_references`、`rename_refactoring`、`reformat_file` | -| 问题 | `get_file_problems`、`get_project_problems`、`check_files` | -| 运行与构建 | `get_run_configurations`、`execute_run_configuration`、`build_project` | -| 命令 | `run_command`、`wait_for_run`、`send_run_input`、`stop_run` | -| 命令状态 | `get_run_status`、`read_run_output`、`list_runs` | -| Git | `get_repositories`、`git_status`、`git_diff` | -| HTTP 客户端 | `http_list_requests`、`http_run_request` | +| 类别 | 工具 | +| ----------- | ------------------------------------------------------------------------------------------------- | +| 文件 | `read_file`、`list_directory_tree`、`create_new_file`、`apply_patch` | +| 搜索 | `search_text`、`search_regex`、`search_symbol`、`search_file` | +| 编辑器 | `get_all_open_file_paths`、`get_current_file`、`open_file_in_editor` | +| 代码 | `get_symbol_info`、`find_references`、`get_call_hierarchy`、`rename_refactoring`、`reformat_file` | +| 问题 | `get_file_problems`、`get_project_problems`、`check_files` | +| 运行与构建 | `get_run_configurations`、`execute_run_configuration`、`build_project` | +| 命令 | `run_command`、`wait_for_run`、`send_run_input`、`stop_run` | +| 命令状态 | `get_run_status`、`read_run_output`、`list_runs` | +| Git | `get_repositories`、`git_status`、`git_diff` | +| HTTP 客户端 | `http_list_requests`、`http_run_request` | 几点说明: - `read_file` 还能读取依赖的源代码,以及 jar 和 zip 压缩包中的文件。 - `search_symbol` 和 `find_references` 使用 IDE 的索引和语言服务器;`get_symbol_info` 返回的内容与快速文档相同。 +- `get_call_hierarchy` 列出某个位置上函数或方法的调用方,`direction` 为 `outgoing` 时列出它调用的函数,每次一层。位置在函数体内时,指的就是这个函数。要再深入一层,用某一项的 `filePath`、`startLine` 和 `startColumn` 再调用一次。库中的项以 URI 作为 `filePath`,不能继续展开。 - 列表类工具每次返回一页:从 `offset` 开始的 `limit` 项(默认 100;`search_symbol` 为 50,`list_runs` 为 10)。`total`(计数代价低的工具才有)、`more` 和 `nextOffset` 说明后面还有多少。`list_runs` 可按 `state` 过滤(`running`、`idle`、`error` 或某个具体状态),`get_run_configurations` 可按 `query` 过滤,`get_project_problems` 默认只列错误,`errorsOnly` 传 false 时也列警告。 -- 查询类工具(各搜索工具、`find_references`、`get_project_problems`、`git_status`、`get_all_open_file_paths`、`get_run_configurations`、`list_runs`)接受 `scope`:一个目录(相对项目根目录或绝对路径),只返回其中文件的结果,比如某个附加项目或某个模块。 +- 查询类工具(各搜索工具、`find_references`、`get_call_hierarchy`、`get_project_problems`、`git_status`、`get_all_open_file_paths`、`get_run_configurations`、`list_runs`)接受 `scope`:一个目录(相对项目根目录或绝对路径),只返回其中文件的结果,比如某个附加项目或某个模块。 - `get_file_problems` 和 `get_project_problems` 返回的是问题工具窗口当前显示的内容(已应用你的检查配置文件),而不是重新分析的结果。 - `check_files` 才是重新分析,适合在任何工具修改文件之后调用:它从磁盘同步每个文件,通知语言服务器文件已保存(这样 `cargo check` 等保存时检查也会运行),并等到服务器答复且分析完成。每个文件都有一个 `status`,说明问题列表是否完整,或者为什么无法检查:没有对应的语言服务器,或者服务器未安装、配置错误、已崩溃。 - `rename_refactoring` 通过语言服务器重命名,文本搜索找不到的引用也会一并更新;也可以只预览不写入。 diff --git a/src/bindings.ts b/src/bindings.ts index 4a0a7fbf7..f0c6f44ca 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -813,6 +813,11 @@ export const commands = { selectionRange: Range, /** Call sites, for call hierarchy. */ fromRanges: Range[], + /** + * The file of `from_ranges` when it is not the item's own: for an outgoing call, the + * file of the prepared item that makes it (a path, or the URI of a virtual document). + */ + fromPath?: IpcPath | null, } | null, IdeError>(__TAURI_INVOKE("lsp_prepare_type_hierarchy", { doc, pos })), /** * References of the symbol at `pos`. `project_wide` also searches project files @@ -3193,6 +3198,8 @@ export type CMakeSettings_Serialize = { }; export type CallHierarchy = { + /** The symbol the hierarchy is for: the first item the server prepared at the position. */ + root?: HierarchyItem | null, items: HierarchyItem[], incomplete: ReferencesIncomplete | null, }; @@ -6426,6 +6433,11 @@ export type HierarchyItem = { selectionRange: Range, /** Call sites, for call hierarchy. */ fromRanges: Range[], + /** + * The file of `from_ranges` when it is not the item's own: for an outgoing call, the + * file of the prepared item that makes it (a path, or the URI of a virtual document). + */ + fromPath?: IpcPath | null, }; export type HierarchyMember = {