Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
3 changes: 3 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)),
Expand Down
5 changes: 5 additions & 0 deletions rust/crates/core/src/runtime/dispatcher/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
31 changes: 31 additions & 0 deletions rust/crates/core/src/tests/rank_names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
);
}
}
13 changes: 13 additions & 0 deletions rust/crates/project/src/name_matching.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,19 @@ pub(crate) fn split_location(query: &str) -> (&str, Option<usize>) {
(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,
Expand Down
92 changes: 91 additions & 1 deletion rust/crates/project/src/name_ranking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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<usize>,
/// Enables qualified symbol splitting (`Class.member`, `Class#member`, `ns::member`).
#[serde(default)]
qualified_symbols: bool,
}

#[derive(Deserialize)]
Expand All @@ -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<String>,
/// Enclosing symbol or type name (such as LSP `containerName`) for qualified queries.
#[serde(default)]
container: Option<String>,
}

/// Open and recently visited paths that break ties between equally good name matches.
Expand Down Expand Up @@ -143,6 +149,10 @@ pub fn rank_names_command(payload: Value) -> Result<Value, CoreError> {
.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,
Expand All @@ -155,6 +165,11 @@ pub fn rank_names_command(payload: Value) -> Result<Value, CoreError> {
}
let context = ContextIndex::new(&request.context);

let qualified = request
.qualified_symbols
.then(|| split_qualified_symbol(query))
.flatten();

struct Hit {
ranked: RankedName,
recent_rank: usize,
Expand All @@ -164,6 +179,18 @@ pub fn rank_names_command(payload: Value) -> Result<Value, CoreError> {
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;
}
Comment on lines +182 to +193

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 File paths admit unrelated symbols

For qualified queries, rank_names_command returns symbols whose paths match the full query even when their names fail the member match. Unrelated symbols from those files appear in the results.

Learn more

The rankNames contract allows hosts to supply symbol or navigator lists. For a qualified query, the path can establish the qualifier but not the member. match_qualified rejects candidates whose symbol name fails the member match, but the caller then lets the path satisfy the whole query.

Example: A navigator list includes loadDefaults from src/config.read.ts. Searching for Config.read returns loadDefaults even though read does not match its name.

Recommended fix: Drop this path-only fallback for recognized qualified queries. Keep the direct name match for candidates whose names already include their qualifier and the existing path-only fallback for unqualified queries.

Suggested change
} 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((qualifier, member)) = qualified {
let Some(hit) = match_qualified(qualifier, member, candidate) else {
continue;
};
hit

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

} else if let Some(hit) = candidate
.path
.as_deref()
Expand Down Expand Up @@ -209,3 +236,66 @@ pub fn rank_names_command(payload: Value) -> Result<Value, CoreError> {
.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<SearchNameRange>)> {
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))?;
Comment on lines +255 to +257

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Missing qualified symbols on Windows

match_qualified drops valid symbols with short container names when their package is supplied by a backslash-separated Windows path. match_container and the path fallback both look for forward slashes in that path.

Learn more

The rankNames contract accepts full candidate paths and lets them supply a symbol's qualifier. The text matcher only compares characters case-insensitively; it does not equate the two slash characters (match_fragments). With an LSP container that only identifies the class, the package check needs to match the package prefix against the path. Both that check and the full qualifier fallback compare a forward-slash pattern against the original path.

Example: Query com.example.UserService.getUser with a candidate named getUser, container UserService, and path C:\repo\src\com\example\UserService.java. This is dropped, while the same candidate with forward slashes matches.

Recommended fix: Use lithe_platform::paths::slash_separated with the relevant Platform for the path used by both qualified comparisons. Keep the original path for open/recent identity. Test the existing dotted-package fixture with native Windows separators.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

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<i32> {
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))
Comment on lines +268 to +276

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Unverified packages in symbol results

When a candidate lacks a path, match_container accepts a class-name match without verifying the requested package. Methods from unrelated packages then appear under the same qualified query.

Learn more

The rankNames contract allows candidates without a path, but a qualified search still needs evidence for the whole qualifier. When a container does not match the whole qualifier, the fallback can combine the class from the container with the package from the path. Without a path, it currently returns the class-only match even though nothing establishes the package.

Example: Search for com.example.UserService.getUser with a candidate { "name": "getUser", "container": "UserService" } from org.other. It is returned despite having no matching package evidence.

Recommended fix: Require a matching path prefix for this fallback. Leave the full-container match available without a path.

Suggested change
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))
let (prefix, tail) = split_qualified_symbol(qualifier)?;
let tail_hit = match_name(tail, container)?;
let path = path?;
let normalized_prefix = prefix.replace("::", "/").replace('.', "/");
match_name(&normalized_prefix, path)?;
Some((tail_hit.degree / (PATH_DEGREE_DIVISOR * 2)).max(1))

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

}

#[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<Value, CoreError> {
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,
}))
}
41 changes: 41 additions & 0 deletions rust/fixtures/search/rank-names-v1.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"}]},
Expand Down
Loading