|
| 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