diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index c227f7b7..66bdd7c5 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -653,7 +653,8 @@ or removing a command fails until the table changes in the same commit. | `workspace.orderEntries` | Order natively enumerated directory siblings | | `workspace.projectTree.rows` | Say which loaded project tree nodes show as rows, keep the selection on a row that shows, and find the row the top of the view was on, without reading the disk (from `lithe-project-tree`) | | `workspace.rowSelection.reduce` | Apply one plain, Cmd/Ctrl or Shift click, or the end of a batch, to the multi-selection of rows of workspace paths and return what a batch acts on (from `lithe-row-selection`) | -| `workspace.rankNames` | Pure ranking of candidate names that the platform enumerates itself (`{ query, candidates: [{ name, path? }], context: { openPaths, recentPaths }, limitPerTier? }`). Use it only for lists Core cannot index: Windows remote/WSL roots, symbol lists, navigator lists. Roots Core indexes go through `workspace.searchEverywhere`, so an inventory is never sent back to Core. Returns `matches: [{ index, degree, tier, nameMatchRanges }]` ordered by degree, open/recent tier, recency, then file-name order (fixture `rust/fixtures/search/rank-names-v1.json`) | +| `workspace.rankNames` | Pure ranking of candidate names that the platform enumerates itself (`{ query, candidates: [{ name, path?, container? }], context: { openPaths, recentPaths }, limitPerTier?, qualifiedSymbols? }`). Use it only for lists Core cannot index: Windows remote/WSL roots, symbol lists, navigator lists. Roots Core indexes go through `workspace.searchEverywhere`, so an inventory is never sent back to Core. When `qualifiedSymbols` is `true` and `query` is qualified (`Class.member`, `Class#member`, `ns::member`), matches `member` against `name` and `qualifier` against `container` or `path`. Returns `matches: [{ index, degree, tier, nameMatchRanges }]` ordered by degree, open/recent tier, recency, then file-name order (fixture `rust/fixtures/search/rank-names-v1.json`) | +| `workspace.symbolQuery` | Split a symbol search query (`{ query }`) into `{ query, qualifier?, member }`, separating `Class.member`, `Class#member`, and `ns::member` at the last separator so hosts can ask LSP `workspace/symbol` for `member` and rank with the full `query` | | `workspace.planDuplicate` | Name the copy of one project item next to its source (`foo.txt` → `foo copy.txt`, then `foo copy 2.txt`) from the sibling names the host has seen to exist | | `workspace.planPaste` | Name pasted project items in one destination directory: a free name is kept, a taken one gets the copy suffix, and earlier items of the same paste count as taken | | `workspace.createEntry` | Create one file, directory or symbolic link below a workspace root without replacing anything | diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 9b715879..2caf1ee7 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -683,6 +683,8 @@ pub enum WorkspaceCommand { OrderEntries, /// Ranks host-supplied candidate names with the shared matcher (`workspace.rankNames`). RankNames, + /// Splits a symbol search query into its optional qualifier and member (`workspace.symbolQuery`). + SymbolQuery, /// Plans the name of a duplicated project item (`workspace.planDuplicate`). PlanDuplicate, /// Creates a file, directory or symbolic link below a root @@ -1582,6 +1584,7 @@ impl CoreCommand { } "workspace.orderEntries" => Some(Self::Workspace(WorkspaceCommand::OrderEntries)), "workspace.rankNames" => Some(Self::Workspace(WorkspaceCommand::RankNames)), + "workspace.symbolQuery" => Some(Self::Workspace(WorkspaceCommand::SymbolQuery)), "workspace.planDuplicate" => Some(Self::Workspace(WorkspaceCommand::PlanDuplicate)), "workspace.createEntry" => Some(Self::Workspace(WorkspaceCommand::CreateEntry)), "workspace.renameEntry" => Some(Self::Workspace(WorkspaceCommand::RenameEntry)), diff --git a/rust/crates/core/src/runtime/dispatcher/workspace.rs b/rust/crates/core/src/runtime/dispatcher/workspace.rs index 724fc741..dc693776 100644 --- a/rust/crates/core/src/runtime/dispatcher/workspace.rs +++ b/rust/crates/core/src/runtime/dispatcher/workspace.rs @@ -176,6 +176,11 @@ pub(super) fn dispatch( payload, crate::project::name_ranking::rank_names_command, ), + WorkspaceCommand::SymbolQuery => plugin_response( + id, + payload, + crate::project::name_ranking::symbol_query_command, + ), WorkspaceCommand::PlanDuplicate => plugin_response( id, payload, diff --git a/rust/crates/core/src/tests/rank_names.rs b/rust/crates/core/src/tests/rank_names.rs index be5faede..b5d8db09 100644 --- a/rust/crates/core/src/tests/rank_names.rs +++ b/rust/crates/core/src/tests/rank_names.rs @@ -88,3 +88,34 @@ fn search_everywhere_context_matches_the_shared_fixture() { let _ = std::fs::remove_dir_all(root); } } + +#[test] +fn symbol_query_splits_qualified_names() { + for (input, want_qualifier, want_member) in [ + ("UserService#getUser", Some("UserService"), "getUser"), + ( + "com.example.UserService.getUser", + Some("com.example.UserService"), + "getUser", + ), + ("crate::user::get_user", Some("crate::user"), "get_user"), + ("getUser", None, "getUser"), + ("UserService.", None, "UserService."), + ] { + let response = execute_command( + "workspace.symbolQuery", + serde_json::json!({ "query": input }), + ); + assert_eq!(response["ok"], true, "{input}: {response}"); + assert_eq!( + response["data"]["qualifier"].as_str(), + want_qualifier, + "{input}" + ); + assert_eq!( + response["data"]["member"].as_str(), + Some(want_member), + "{input}" + ); + } +} diff --git a/rust/crates/project/src/name_matching.rs b/rust/crates/project/src/name_matching.rs index c0f80dec..cdf6f703 100644 --- a/rust/crates/project/src/name_matching.rs +++ b/rust/crates/project/src/name_matching.rs @@ -17,6 +17,19 @@ pub(crate) fn split_location(query: &str) -> (&str, Option) { (query, None) } +/// Splits a qualified symbol query (`Class.method`, `Class#method`, `ns::func`) at its last +/// separator into `(qualifier, member)` when both sides are non-empty. +pub(crate) fn split_qualified_symbol(query: &str) -> Option<(&str, &str)> { + let query = query.trim(); + let best = [".", "#", "::"] + .into_iter() + .filter_map(|sep| query.rfind(sep).map(|idx| (idx, sep.len()))) + .max_by_key(|(idx, len)| (*idx, *len))?; + let qualifier = query[..best.0].trim(); + let member = query[best.0 + best.1..].trim(); + (!qualifier.is_empty() && !member.is_empty()).then_some((qualifier, member)) +} + /// One match owns both its ranking and the fragments painted by native clients. pub(crate) struct NameMatch { pub(crate) degree: i32, diff --git a/rust/crates/project/src/name_ranking.rs b/rust/crates/project/src/name_ranking.rs index 2593fead..ca11e93e 100644 --- a/rust/crates/project/src/name_ranking.rs +++ b/rust/crates/project/src/name_ranking.rs @@ -6,7 +6,7 @@ //! order retain contiguous and word-boundary matching. Search Everywhere additionally //! allows ordered fragments and arbitrary letter gaps for its workspace names. -use super::name_matching::match_ranked_name as match_name; +use super::name_matching::{match_ranked_name as match_name, split_qualified_symbol}; use crate::contracts::SearchNameRange; use lithe_core_rules::file_names::FileNameKey; use lithe_protocol::{CoreError, ErrorCode}; @@ -32,6 +32,9 @@ struct RankNamesRequest { /// Keeps the best N hits of each tier; the host shows tiers as separate sections. #[serde(default)] limit_per_tier: Option, + /// Enables qualified symbol splitting (`Class.member`, `Class#member`, `ns::member`). + #[serde(default)] + qualified_symbols: bool, } #[derive(Deserialize)] @@ -41,6 +44,9 @@ struct RankCandidate { /// Full path; identifies the candidate in the context lists and is a weaker match target. #[serde(default)] path: Option, + /// Enclosing symbol or type name (such as LSP `containerName`) for qualified queries. + #[serde(default)] + container: Option, } /// Open and recently visited paths that break ties between equally good name matches. @@ -143,6 +149,10 @@ pub fn rank_names_command(payload: Value) -> Result { .path .as_ref() .is_some_and(|path| path.len() > MAX_TEXT_BYTES) + || candidate + .container + .as_ref() + .is_some_and(|container| container.len() > MAX_TEXT_BYTES) }) { return Err(CoreError::new( ErrorCode::InvalidRequest, @@ -155,6 +165,11 @@ pub fn rank_names_command(payload: Value) -> Result { } let context = ContextIndex::new(&request.context); + let qualified = request + .qualified_symbols + .then(|| split_qualified_symbol(query)) + .flatten(); + struct Hit { ranked: RankedName, recent_rank: usize, @@ -164,6 +179,18 @@ pub fn rank_names_command(payload: Value) -> Result { for (index, candidate) in request.candidates.iter().enumerate() { let (degree, ranges) = if let Some(hit) = match_name(query, &candidate.name) { (hit.degree, hit.ranges) + } else if let Some((qualifier, member)) = qualified { + if let Some(hit) = match_qualified(qualifier, member, candidate) { + hit + } else if let Some(hit) = candidate + .path + .as_deref() + .and_then(|path| match_name(query, path)) + { + ((hit.degree / PATH_DEGREE_DIVISOR).max(1), Vec::new()) + } else { + continue; + } } else if let Some(hit) = candidate .path .as_deref() @@ -209,3 +236,66 @@ pub fn rank_names_command(payload: Value) -> Result { .collect(); Ok(serde_json::json!({ "matches": matches })) } + +/// Matches a `(qualifier, member)` query against a candidate's name, container, and path. +fn match_qualified( + qualifier: &str, + member: &str, + candidate: &RankCandidate, +) -> Option<(i32, Vec)> { + let member_hit = match_name(member, &candidate.name)?; + let container_bonus = candidate + .container + .as_deref() + .filter(|container| !container.is_empty()) + .and_then(|container| match_container(qualifier, container, candidate.path.as_deref())); + if let Some(bonus) = container_bonus { + return Some((member_hit.degree + bonus, member_hit.ranges)); + } + let path = candidate.path.as_deref()?; + let normalized = qualifier.replace("::", "/").replace('.', "/"); + let path_hit = match_name(&normalized, path).or_else(|| match_name(qualifier, path))?; + Some(( + member_hit.degree + (path_hit.degree / (PATH_DEGREE_DIVISOR * 2)).max(1), + member_hit.ranges, + )) +} + +fn match_container(qualifier: &str, container: &str, path: Option<&str>) -> Option { + if let Some(hit) = match_name(qualifier, container) { + return Some((hit.degree / PATH_DEGREE_DIVISOR).max(1)); + } + let (prefix, tail) = split_qualified_symbol(qualifier)?; + let tail_hit = match_name(tail, container)?; + if let Some(path) = path { + let normalized_prefix = prefix.replace("::", "/").replace('.', "/"); + if match_name(&normalized_prefix, path).is_none() { + return None; + } + } + Some((tail_hit.degree / (PATH_DEGREE_DIVISOR * 2)).max(1)) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SymbolQueryRequest { + query: String, +} + +/// Splits a symbol search query into its optional qualifier and member name (`workspace.symbolQuery`). +pub fn symbol_query_command(payload: Value) -> Result { + let request: SymbolQueryRequest = serde_json::from_value(payload).map_err(|error| { + CoreError::new(ErrorCode::InvalidRequest, "Invalid symbol query request") + .with_details(error.to_string()) + })?; + let trimmed = request.query.trim(); + let (qualifier, member) = match split_qualified_symbol(trimmed) { + Some((qualifier, member)) => (Some(qualifier.to_string()), member.to_string()), + None => (None, trimmed.to_string()), + }; + Ok(serde_json::json!({ + "query": trimmed, + "qualifier": qualifier, + "member": member, + })) +} diff --git a/rust/fixtures/search/rank-names-v1.json b/rust/fixtures/search/rank-names-v1.json index 21f17b1e..39d475a0 100644 --- a/rust/fixtures/search/rank-names-v1.json +++ b/rust/fixtures/search/rank-names-v1.json @@ -65,6 +65,47 @@ {"index": 0, "tier": "other", "ranges": [{"start": 0, "length": 4}]} ] }, + { + "id": "dotted-filename-does-not-split-without-qualified-symbols", + "request": { + "query": "main.rs", + "candidates": [ + {"name": "rs.go", "path": "main/rs.go"}, + {"name": "main.rs", "path": "crates/app/src/main.rs"} + ] + }, + "expected": [ + {"index": 1, "tier": "other", "ranges": [{"start": 0, "length": 7}]} + ] + }, + { + "id": "qualified-symbol-matches-container-and-member", + "request": { + "query": "UserService#getUser", + "qualifiedSymbols": true, + "candidates": [ + {"name": "getUser", "path": "src/OrderService.java", "container": "OrderService"}, + {"name": "getUser", "path": "src/UserService.java", "container": "UserService"} + ] + }, + "expected": [ + {"index": 1, "tier": "other", "ranges": [{"start": 0, "length": 7}]} + ] + }, + { + "id": "dotted-qualified-symbol-matches-package-and-container", + "request": { + "query": "com.example.UserService.getUser", + "qualifiedSymbols": true, + "candidates": [ + {"name": "getUser", "path": "src/org/other/UserService.java", "container": "UserService"}, + {"name": "getUser", "path": "src/com/example/UserService.java", "container": "UserService"} + ] + }, + "expected": [ + {"index": 1, "tier": "other", "ranges": [{"start": 0, "length": 7}]} + ] + }, { "id": "blank-query-matches-nothing", "request": {"query": " ", "candidates": [{"name": "a.ts"}]},