Skip to content

Commit 6a29169

Browse files
feat(editor): add portable symbol reference formatting (#2015) (#70)
* feat(editor): format symbol and file references in Rust Core (#2015) * style(editor): apply rustfmt corrections from CI (#2015) * fix(editor): satisfy Rust clippy lints on reference formatter (#2015) * fix(editor): accept nullable LSP symbol children from Go host (#2015) * style(editor): format nullable LSP symbol child handling per Rust CI --------- Co-authored-by: lithe-support[bot] <356900028+lithe-support[bot]@users.noreply.github.com> Co-authored-by: Yao Jingxi <23722032@bjtu.edu.cn>
1 parent c928514 commit 6a29169

7 files changed

Lines changed: 419 additions & 0 deletions

File tree

‎rust/contracts/rust-core-api.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -655,6 +655,7 @@ or removing a command fails until the table changes in the same commit.
655655
| `lsp.classifyNavigationTarget` | Classify a language-server jump target as workspace, external read-only or rejected |
656656
| `lsp.declarationOrUsages` | Decide whether a go-to-declaration gesture opens the declaration or shows its usages |
657657
| `editor.lineEdit` | Apply a deterministic line-level text transform and return the replacement plus selection to restore |
658+
| `editor.copyReferenceLocation` | Format a one-based line reference from normalized document symbols; fall back to a file path when no containing symbol exists |
658659
| `editor.find` | Find text or plans bounded replacements in a borrowed document |
659660
| `editor.preferences.resolve` | Resolve persisted editor presentation preferences |
660661
| `editor.recent.reduce` | Reduce and queries bounded recent-file history |

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -597,6 +597,8 @@ pub enum EditorCommand {
597597
/// Applies a deterministic line-level editing transform
598598
/// (`editor.lineEdit`).
599599
LineEdit,
600+
/// Formats a symbol or file reference for one caret position (`editor.copyReferenceLocation`).
601+
CopyReferenceLocation,
600602
/// Finds text or plans bounded replacements in a borrowed document (`editor.find`).
601603
Find,
602604
/// Resolves persisted editor presentation preferences (`editor.preferences.resolve`).
@@ -1326,6 +1328,9 @@ impl CoreCommand {
13261328
"lsp.classifyNavigationTarget" => Some(Self::Lsp(LspCommand::ClassifyNavigationTarget)),
13271329
"lsp.declarationOrUsages" => Some(Self::Lsp(LspCommand::DeclarationOrUsages)),
13281330
"editor.lineEdit" => Some(Self::Editor(EditorCommand::LineEdit)),
1331+
"editor.copyReferenceLocation" => {
1332+
Some(Self::Editor(EditorCommand::CopyReferenceLocation))
1333+
}
13291334
"editor.find" => Some(Self::Editor(EditorCommand::Find)),
13301335
"editor.preferences.resolve" => Some(Self::Editor(EditorCommand::PreferencesResolve)),
13311336
"editor.recent.reduce" => Some(Self::Editor(EditorCommand::RecentReduce)),

‎rust/crates/core/src/runtime/dispatcher/editor.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ pub(super) fn dispatch(
2121
EditorCommand::GroupLayoutDropTargets => {
2222
plugin_response(id, payload, lithe_editor_layout::drop_targets_command)
2323
}
24+
EditorCommand::CopyReferenceLocation => plugin_response(
25+
id,
26+
payload,
27+
lithe_editor::reference_location::reference_command,
28+
),
2429
EditorCommand::Find => match lithe_editor::find::command(payload, document) {
2530
Ok(data) => CoreResponse::success(id, data),
2631
Err(error) => CoreResponse::failure(id, error),

‎rust/crates/core/src/tests/editor_dispatch.rs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,3 +135,20 @@ fn navigation_history_keeps_only_the_newest_entries() {
135135
assert_eq!(forward.len() as u64, limit);
136136
assert_eq!(forward[0]["line"], 5);
137137
}
138+
139+
#[test]
140+
fn copy_reference_location_matches_shared_fixture() {
141+
let fixture: Value = serde_json::from_str(include_str!(
142+
"../../../../fixtures/editor/copy-reference-location-v1.json"
143+
))
144+
.unwrap();
145+
for case in fixture["cases"].as_array().unwrap() {
146+
let response: Value = serde_json::from_str(&crate::execute_json(
147+
&json!({"command":"editor.copyReferenceLocation","payload":case["request"]})
148+
.to_string(),
149+
))
150+
.unwrap();
151+
assert_eq!(response["ok"], true, "{}: {response}", case["name"]);
152+
assert_eq!(response["data"], case["expected"], "{}", case["name"]);
153+
}
154+
}

‎rust/crates/editor/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ pub mod navigation_input;
1212
pub mod preferences;
1313
pub mod recent;
1414
pub mod recovery;
15+
pub mod reference_location;
1516
pub mod text_edit_plan;
1617

1718
pub use line_edit::{line_edit, LineEditRequest};
Lines changed: 242 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,242 @@
1+
//! Builds a portable reference for the caret from language-server document symbols.
2+
//!
3+
//! The host owns the document path and actual caret, while Core owns the common
4+
//! formatting and symbol-range selection rule. No language-specific source parsing is
5+
//! performed: unknown or incomplete symbols fall back to an explicit file location.
6+
7+
use lithe_protocol::{CoreError, ErrorCode};
8+
use serde::Deserialize;
9+
use serde_json::{json, Value};
10+
11+
#[derive(Deserialize)]
12+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
13+
struct Request {
14+
path: String,
15+
line: u32,
16+
utf16_column: u32,
17+
#[serde(default)]
18+
symbols: Vec<Symbol>,
19+
}
20+
21+
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)]
22+
#[serde(rename_all = "camelCase")]
23+
struct Position {
24+
line: u32,
25+
utf16_column: u32,
26+
}
27+
28+
#[derive(Deserialize)]
29+
struct Range {
30+
start: Position,
31+
end: Position,
32+
}
33+
34+
#[derive(Deserialize)]
35+
#[serde(rename_all = "camelCase")]
36+
struct Symbol {
37+
name: String,
38+
kind: u32,
39+
range: Range,
40+
#[serde(default)]
41+
detail: Option<String>,
42+
#[serde(default)]
43+
container_name: Option<String>,
44+
#[serde(default)]
45+
children: Option<Vec<Symbol>>,
46+
}
47+
48+
/// Formats the server's innermost containing symbol, with a one-based source line.
49+
/// A namespace, type or method is used only when the server reports it: the
50+
/// caller never guesses a package or method signature from the file name.
51+
pub fn reference_command(payload: Value) -> Result<Value, CoreError> {
52+
let request: Request = serde_json::from_value(payload).map_err(|_| {
53+
CoreError::new(
54+
ErrorCode::InvalidRequest,
55+
"Invalid reference location request",
56+
)
57+
})?;
58+
if request.path.is_empty() {
59+
return Err(CoreError::new(
60+
ErrorCode::InvalidRequest,
61+
"Reference location requires a file path",
62+
));
63+
}
64+
let line = u64::from(request.line) + 1;
65+
let position = Position {
66+
line: request.line,
67+
utf16_column: request.utf16_column,
68+
};
69+
let symbol = reference_symbol(&request.symbols, position);
70+
let (reference, source) = match symbol {
71+
Some(symbol) => (format!("{symbol}#L{line}"), "symbol"),
72+
None => (format!("{}#L{line}", request.path), "file"),
73+
};
74+
Ok(json!({"reference":reference, "source":source}))
75+
}
76+
77+
fn contains(range: &Range, position: Position) -> bool {
78+
range.start <= position && position < range.end
79+
}
80+
81+
fn extent(range: &Range) -> (u32, u32) {
82+
(
83+
range.end.line.saturating_sub(range.start.line),
84+
range
85+
.end
86+
.utf16_column
87+
.saturating_sub(range.start.utf16_column),
88+
)
89+
}
90+
91+
// Prefer a nested symbol chain over a flat entry, and a smaller enclosing range
92+
// when a server returns overlapping flat SymbolInformation entries.
93+
fn enclosing(symbols: &[Symbol], position: Position) -> Vec<&Symbol> {
94+
let mut best = Vec::new();
95+
let mut best_extent = (u32::MAX, u32::MAX);
96+
for symbol in symbols {
97+
if !contains(&symbol.range, position) {
98+
continue;
99+
}
100+
let mut candidate = vec![symbol];
101+
candidate.extend(enclosing(
102+
symbol.children.as_deref().unwrap_or(&[]),
103+
position,
104+
));
105+
let span = extent(&symbol.range);
106+
if candidate.len() > best.len() || (candidate.len() == best.len() && span < best_extent) {
107+
best = candidate;
108+
best_extent = span;
109+
}
110+
}
111+
best
112+
}
113+
114+
fn clean(value: &str) -> Option<&str> {
115+
let value = value.trim();
116+
(!value.is_empty() && !value.chars().any(char::is_control)).then_some(value)
117+
}
118+
119+
fn callable_name(symbol: &Symbol) -> Option<String> {
120+
let name = clean(&symbol.name)?;
121+
// LSP implementations may put a method's exact signature in its name,
122+
// or put only the parameter list in detail. Never invent the types.
123+
if name.contains('(') {
124+
return Some(name.to_owned());
125+
}
126+
if let Some(detail) = symbol.detail.as_deref().and_then(clean) {
127+
if detail.starts_with('(') {
128+
if let Some(end) = detail.find(')') {
129+
return Some(format!("{}{}", name, &detail[..=end]));
130+
}
131+
}
132+
}
133+
Some(name.to_owned())
134+
}
135+
136+
fn reference_symbol(symbols: &[Symbol], position: Position) -> Option<String> {
137+
let path = enclosing(symbols, position);
138+
let mut namespaces = Vec::new();
139+
let mut types = Vec::new();
140+
let mut callable = None;
141+
for symbol in &path {
142+
let Some(name) = clean(&symbol.name) else {
143+
continue;
144+
};
145+
match symbol.kind {
146+
// LSP SymbolKind: Module, Namespace, Package
147+
2..=4 => namespaces.push(name.to_owned()),
148+
// Class, Enum, Interface, Struct
149+
5 | 10 | 11 | 23 => types.push(name.to_owned()),
150+
// Method, Constructor, Function
151+
6 | 9 | 12 => callable = callable_name(symbol),
152+
_ => {}
153+
}
154+
}
155+
// Flat SymbolInformation includes containerName instead of nested children.
156+
// Use the server's name as-is; it may already be fully qualified.
157+
if types.is_empty() {
158+
if let Some(container) = path
159+
.last()
160+
.and_then(|s| s.container_name.as_deref())
161+
.and_then(clean)
162+
{
163+
types.push(container.to_owned());
164+
}
165+
}
166+
let mut owner = namespaces.join(".");
167+
if !types.is_empty() {
168+
if !owner.is_empty() {
169+
owner.push('.');
170+
}
171+
owner.push_str(&types.join("."));
172+
}
173+
match (owner.is_empty(), callable) {
174+
(true, None) => None,
175+
(true, Some(method)) => Some(method),
176+
(false, Some(method)) => Some(format!("{owner}#{method}")),
177+
(false, None) => Some(owner),
178+
}
179+
}
180+
181+
#[cfg(test)]
182+
mod tests {
183+
use super::*;
184+
#[test]
185+
fn server_symbol_tree_and_detail_are_preserved() {
186+
let symbols = json!([{
187+
"name":"com.example", "kind":4,
188+
"range":{"start":{"line":0,"utf16Column":0},"end":{"line":200,"utf16Column":0}},
189+
"children":[{
190+
"name":"DemoClass","kind":5,
191+
"range":{"start":{"line":1,"utf16Column":0},"end":{"line":190,"utf16Column":0}},
192+
"children":[{
193+
"name":"goHome","kind":6,"detail":"(String,Integer) : void",
194+
"range":{"start":{"line":130,"utf16Column":0},"end":{"line":144,"utf16Column":0}}
195+
}]
196+
}]
197+
}]);
198+
let data = reference_command(
199+
json!({"path":"/tmp/DemoClass.java","line":136,"utf16Column":4,"symbols":symbols}),
200+
)
201+
.unwrap();
202+
assert_eq!(
203+
data["reference"],
204+
"com.example.DemoClass#goHome(String,Integer)#L137"
205+
);
206+
assert_eq!(data["source"], "symbol");
207+
}
208+
209+
#[test]
210+
fn missing_or_nonmatching_symbols_fall_back_to_path() {
211+
for symbols in [
212+
json!([]),
213+
json!([{
214+
"name":"DemoClass","kind":5,
215+
"range":{"start":{"line":10,"utf16Column":0},"end":{"line":12,"utf16Column":0}}
216+
}]),
217+
] {
218+
let data = reference_command(json!({"path":"C:/src/DemoClass.java","line":136,"utf16Column":4,"symbols":symbols})).unwrap();
219+
assert_eq!(data["reference"], "C:/src/DemoClass.java#L137");
220+
assert_eq!(data["source"], "file");
221+
}
222+
}
223+
224+
#[test]
225+
fn flat_method_uses_its_server_container_and_exact_name() {
226+
let symbols = json!([{
227+
"name":"goHome(String,Integer)","kind":6,"containerName":"DemoClass",
228+
"range":{"start":{"line":6,"utf16Column":0},"end":{"line":9,"utf16Column":0}}
229+
}]);
230+
let data = reference_command(
231+
json!({"path":"file.java","line":7,"utf16Column":0,"symbols":symbols}),
232+
)
233+
.unwrap();
234+
assert_eq!(data["reference"], "DemoClass#goHome(String,Integer)#L8");
235+
}
236+
237+
#[test]
238+
fn rejects_empty_path_and_invalid_positions() {
239+
assert!(reference_command(json!({"path":"","line":0,"utf16Column":0})).is_err());
240+
assert!(reference_command(json!({"path":"a.java","line":-1,"utf16Column":0})).is_err());
241+
}
242+
}

0 commit comments

Comments
 (0)