Skip to main content

rust_meth_lib/analyzer/
parse.rs

1//! Domain types and pure parsing of `rust-analyzer` LSP responses.
2//!
3//! Nothing in this module touches a process or a socket, it only turns
4//! [`serde_json::Value`] payloads into [`Method`] / [`Definition`] values.
5//! That makes it the easiest part of the analyzer to unit test, which is
6//! why almost all of the test suite lives here.
7
8use serde_json::Value;
9
10use crate::error::{Result, RustMethError};
11
12/// LSP `CompletionItemKind` value corresponding to a Method.
13const KIND_METHOD: u64 = 2;
14
15/// Represents a method extracted from a `rust-analyzer` completion list.
16#[derive(serde::Serialize, serde::Deserialize, Clone)]
17pub struct Method {
18    /// The plain name of the method (e.g., `"len"`).
19    pub name: String,
20    /// The full method signature hint provided by the LSP server (e.g., `"pub const fn len(&self) -> usize"`).
21    pub detail: Option<String>,
22    /// Markdown or plaintext documentation extracted from the item.
23    pub documentation: Option<String>,
24}
25
26/// Contains source definition location mappings returned by an LSP `textDocument/definition` call.
27#[must_use]
28pub struct Definition {
29    /// A shortened path string tailored for display terminals (e.g., `"library/core/src/num/uint_macros.rs"`).
30    pub path: String,
31    /// The unadulterated, absolute path prefix on the local filesystem.
32    pub full_path: String,
33    /// 0-indexed line number where the source item is declared.
34    pub line: u32,
35}
36
37/// Filters, sanitizes, and deduplicates the raw JSON arrays returned by the LSP completion query.
38///
39/// # Errors
40///
41/// Returns an error if the provided JSON response does not conform to the expected LSP
42/// completion shape (missing both a top-level `result` array and an `items` sub-array).
43pub fn parse_methods(response: &Value) -> Result<Vec<Method>> {
44    let result = &response["result"];
45    let items: &[Value] = match result {
46        Value::Array(arr) => arr.as_slice(),
47        obj if obj["items"].is_array() => obj["items"].as_array().map_or(&[], Vec::as_slice),
48        _ => return Err(RustMethError::UnexpectedResponseShape(response.to_string())),
49    };
50    let mut methods: Vec<Method> = Vec::with_capacity(items.len() / 2);
51    for item in items {
52        if item["kind"].as_u64() != Some(KIND_METHOD) {
53            continue;
54        }
55        let name = item["label"]
56            .as_str()
57            .unwrap_or("")
58            .split('(')
59            .next()
60            .unwrap_or("")
61            .trim()
62            .to_string();
63        if name.is_empty() {
64            continue;
65        }
66        methods.push(Method {
67            name,
68            detail: item["detail"].as_str().map(str::to_string),
69            documentation: item["documentation"]["value"].as_str().map(str::to_string),
70        });
71    }
72    methods.sort_unstable_by(|a, b| a.name.cmp(&b.name));
73    methods.dedup_by(|a, b| a.name == b.name);
74    Ok(methods)
75}
76
77/// Normalizes the location array or object mapping payload returned by the LSP server into a [`Definition`].
78///
79/// # Panics
80///
81/// Panics if the line position value returned by the LSP protocol fails to map cleanly into a `u32`.
82#[must_use]
83pub fn parse_definition(response: &Value) -> Option<Definition> {
84    let result = &response["result"];
85    let location: &Value = match result {
86        Value::Array(arr) if !arr.is_empty() => &arr[0],
87        single if single.is_object() => single,
88        _ => return None,
89    };
90    let uri = location["uri"].as_str().unwrap_or("");
91    if uri.is_empty() {
92        return None;
93    }
94    let line = u32::try_from(location["range"]["start"]["line"].as_u64().unwrap_or(0))
95        .expect("LSP definition line should fit in u32");
96    let full_path_str = uri.strip_prefix("file://").unwrap_or(uri);
97    let path = full_path_str
98        .find("/library/")
99        .or_else(|| full_path_str.find("/src/"))
100        .map_or_else(
101            || full_path_str.to_string(),
102            |idx| full_path_str[idx + 1..].to_string(),
103        );
104    let full_path = full_path_str.to_string();
105    Some(Definition {
106        path,
107        full_path,
108        line,
109    })
110}
111
112#[cfg(test)]
113#[allow(clippy::unwrap_used)]
114mod tests {
115    use super::*;
116    use serde_json::json;
117
118    #[test]
119    fn parse_methods_empty_items_returns_empty_vec() {
120        let resp = json!({ "result": { "items": [], "isIncomplete": false } });
121        let methods = parse_methods(&resp).unwrap();
122        assert!(methods.is_empty());
123    }
124
125    #[test]
126    fn parse_methods_filters_non_method_kinds() {
127        // kind 2 = Method, kind 5 = Field, kind 9 = Module
128        let resp = json!({
129            "result": {
130                "items": [
131                    { "kind": 2, "label": "len(…)" },
132                    { "kind": 5, "label": "capacity" },
133                    { "kind": 9, "label": "Clone" }
134                ]
135            }
136        });
137        let methods = parse_methods(&resp).unwrap();
138        assert_eq!(methods.len(), 1);
139        assert_eq!(methods[0].name, "len");
140    }
141
142    #[test]
143    fn parse_methods_deduplicates_same_name() {
144        let resp = json!({
145            "result": {
146                "items": [
147                    { "kind": 2, "label": "clone(…)" },
148                    { "kind": 2, "label": "clone(…)" }
149                ]
150            }
151        });
152        let methods = parse_methods(&resp).unwrap();
153        assert_eq!(methods.len(), 1);
154        assert_eq!(methods[0].name, "clone");
155    }
156
157    #[test]
158    fn parse_methods_returns_sorted_names() {
159        let resp = json!({
160            "result": {
161                "items": [
162                    { "kind": 2, "label": "zip(…)" },
163                    { "kind": 2, "label": "map(…)" },
164                    { "kind": 2, "label": "filter(…)" }
165                ]
166            }
167        });
168        let methods = parse_methods(&resp).unwrap();
169        let names: Vec<&str> = methods.iter().map(|m| m.name.as_str()).collect();
170        assert_eq!(names, ["filter", "map", "zip"]);
171    }
172
173    #[test]
174    fn parse_methods_preserves_detail_and_documentation() {
175        let resp = json!({
176            "result": {
177                "items": [{
178                    "kind": 2,
179                    "label": "len(…)",
180                    "detail": "pub fn len(&self) -> usize",
181                    "documentation": { "value": "Returns the number of elements." }
182                }]
183            }
184        });
185        let methods = parse_methods(&resp).unwrap();
186        assert_eq!(methods.len(), 1);
187        assert_eq!(
188            methods[0].detail.as_deref(),
189            Some("pub fn len(&self) -> usize")
190        );
191        assert_eq!(
192            methods[0].documentation.as_deref(),
193            Some("Returns the number of elements.")
194        );
195    }
196
197    #[test]
198    fn parse_methods_no_detail_or_docs_is_none() {
199        let resp = json!({
200            "result": { "items": [{ "kind": 2, "label": "len(…)" }] }
201        });
202        let methods = parse_methods(&resp).unwrap();
203        assert!(methods[0].detail.is_none());
204        assert!(methods[0].documentation.is_none());
205    }
206
207    #[test]
208    fn parse_methods_array_result_form() {
209        // Some LSP servers return `result` as a plain array
210        let resp = json!({
211            "result": [
212                { "kind": 2, "label": "len(…)" },
213                { "kind": 2, "label": "is_empty(…)" }
214            ]
215        });
216        let methods = parse_methods(&resp).unwrap();
217        assert_eq!(methods.len(), 2);
218    }
219
220    #[test]
221    fn parse_methods_skips_empty_label() {
222        let resp = json!({
223            "result": {
224                "items": [
225                    { "kind": 2, "label": "" },
226                    { "kind": 2, "label": "len(…)" }
227                ]
228            }
229        });
230        let methods = parse_methods(&resp).unwrap();
231        assert_eq!(methods.len(), 1);
232        assert_eq!(methods[0].name, "len");
233    }
234
235    #[test]
236    fn parse_methods_unexpected_shape_returns_error() {
237        let resp = json!({ "result": "this_is_not_valid" });
238        assert!(parse_methods(&resp).is_err());
239    }
240
241    // These simulate what rust-analyzer returns for third-party crate types:
242    // the label contains the full signature e.g. `"as_str(…)"`.
243    #[test]
244    fn parse_methods_third_party_label_stripped_at_paren() {
245        let resp = json!({
246            "result": {
247                "items": [
248                    { "kind": 2, "label": "as_str(…)", "detail": "pub fn as_str(&self) -> &str" },
249                    { "kind": 2, "label": "as_object(…)" }
250                ]
251            }
252        });
253        let methods = parse_methods(&resp).unwrap();
254        let names: Vec<&str> = methods.iter().map(|m| m.name.as_str()).collect();
255        assert!(names.contains(&"as_str"));
256        assert!(names.contains(&"as_object"));
257    }
258
259    #[test]
260    fn parse_definition_array_form() {
261        let resp = json!({
262            "result": [{
263                "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/num/mod.rs",
264                "range": {
265                    "start": { "line": 42, "character": 0 },
266                    "end":   { "line": 42, "character": 10 }
267                }
268            }]
269        });
270        let def = parse_definition(&resp).unwrap();
271        assert_eq!(def.line, 42);
272        assert!(def.path.starts_with("library/"));
273        assert!(!def.full_path.starts_with("file://"));
274    }
275
276    #[test]
277    fn parse_definition_object_form() {
278        let resp = json!({
279            "result": {
280                "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/str/mod.rs",
281                "range": {
282                    "start": { "line": 99, "character": 4 },
283                    "end":   { "line": 99, "character": 20 }
284                }
285            }
286        });
287        let def = parse_definition(&resp).unwrap();
288        assert_eq!(def.line, 99);
289        assert!(def.path.starts_with("library/"));
290    }
291
292    #[test]
293    fn parse_definition_null_result_returns_none() {
294        let resp = json!({ "result": null });
295        assert!(parse_definition(&resp).is_none());
296    }
297
298    #[test]
299    fn parse_definition_empty_array_returns_none() {
300        let resp = json!({ "result": [] });
301        assert!(parse_definition(&resp).is_none());
302    }
303
304    #[test]
305    fn parse_definition_empty_uri_returns_none() {
306        let resp = json!({
307            "result": [{
308                "uri": "",
309                "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }
310            }]
311        });
312        assert!(parse_definition(&resp).is_none());
313    }
314
315    #[test]
316    fn parse_definition_strips_library_prefix_from_path() {
317        let resp = json!({
318            "result": [{
319                "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/num/mod.rs",
320                "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }
321            }]
322        });
323        let def = parse_definition(&resp).unwrap();
324        // path should start at "library/" not "/"
325        assert!(def.path.starts_with("library/"));
326        assert!(!def.path.starts_with('/'));
327    }
328
329    #[test]
330    fn parse_definition_src_path_fallback() {
331        // A third-party crate source, has /src/ but no /library/
332        let resp = json!({
333            "result": [{
334                "uri": "file:///home/user/myproject/src/main.rs",
335                "range": { "start": { "line": 5, "character": 0 }, "end": { "line": 5, "character": 0 } }
336            }]
337        });
338        let def = parse_definition(&resp).unwrap();
339        assert!(def.path.starts_with("src/"));
340        assert_eq!(def.line, 5);
341    }
342
343    #[test]
344    fn parse_definition_full_path_does_not_start_with_file_scheme() {
345        let resp = json!({
346            "result": [{
347                "uri": "file:///home/user/project/src/lib.rs",
348                "range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 0 } }
349            }]
350        });
351        let def = parse_definition(&resp).unwrap();
352        assert!(!def.full_path.starts_with("file://"));
353        assert!(def.full_path.starts_with('/'));
354    }
355}