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)]
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    // ── parse_methods ────────────────────────────────────────────────────────
119    #[test]
120    fn parse_methods_empty_items_returns_empty_vec() {
121        let resp = json!({ "result": { "items": [], "isIncomplete": false } });
122        let methods = parse_methods(&resp).unwrap();
123        assert!(methods.is_empty());
124    }
125
126    #[test]
127    fn parse_methods_filters_non_method_kinds() {
128        // kind 2 = Method, kind 5 = Field, kind 9 = Module
129        let resp = json!({
130            "result": {
131                "items": [
132                    { "kind": 2, "label": "len(…)" },
133                    { "kind": 5, "label": "capacity" },
134                    { "kind": 9, "label": "Clone" }
135                ]
136            }
137        });
138        let methods = parse_methods(&resp).unwrap();
139        assert_eq!(methods.len(), 1);
140        assert_eq!(methods[0].name, "len");
141    }
142
143    #[test]
144    fn parse_methods_deduplicates_same_name() {
145        let resp = json!({
146            "result": {
147                "items": [
148                    { "kind": 2, "label": "clone(…)" },
149                    { "kind": 2, "label": "clone(…)" }
150                ]
151            }
152        });
153        let methods = parse_methods(&resp).unwrap();
154        assert_eq!(methods.len(), 1);
155        assert_eq!(methods[0].name, "clone");
156    }
157
158    #[test]
159    fn parse_methods_returns_sorted_names() {
160        let resp = json!({
161            "result": {
162                "items": [
163                    { "kind": 2, "label": "zip(…)" },
164                    { "kind": 2, "label": "map(…)" },
165                    { "kind": 2, "label": "filter(…)" }
166                ]
167            }
168        });
169        let methods = parse_methods(&resp).unwrap();
170        let names: Vec<&str> = methods.iter().map(|m| m.name.as_str()).collect();
171        assert_eq!(names, ["filter", "map", "zip"]);
172    }
173
174    #[test]
175    fn parse_methods_preserves_detail_and_documentation() {
176        let resp = json!({
177            "result": {
178                "items": [{
179                    "kind": 2,
180                    "label": "len(…)",
181                    "detail": "pub fn len(&self) -> usize",
182                    "documentation": { "value": "Returns the number of elements." }
183                }]
184            }
185        });
186        let methods = parse_methods(&resp).unwrap();
187        assert_eq!(methods.len(), 1);
188        assert_eq!(
189            methods[0].detail.as_deref(),
190            Some("pub fn len(&self) -> usize")
191        );
192        assert_eq!(
193            methods[0].documentation.as_deref(),
194            Some("Returns the number of elements.")
195        );
196    }
197
198    #[test]
199    fn parse_methods_no_detail_or_docs_is_none() {
200        let resp = json!({
201            "result": { "items": [{ "kind": 2, "label": "len(…)" }] }
202        });
203        let methods = parse_methods(&resp).unwrap();
204        assert!(methods[0].detail.is_none());
205        assert!(methods[0].documentation.is_none());
206    }
207
208    #[test]
209    fn parse_methods_array_result_form() {
210        // Some LSP servers return `result` as a plain array
211        let resp = json!({
212            "result": [
213                { "kind": 2, "label": "len(…)" },
214                { "kind": 2, "label": "is_empty(…)" }
215            ]
216        });
217        let methods = parse_methods(&resp).unwrap();
218        assert_eq!(methods.len(), 2);
219    }
220
221    #[test]
222    fn parse_methods_skips_empty_label() {
223        let resp = json!({
224            "result": {
225                "items": [
226                    { "kind": 2, "label": "" },
227                    { "kind": 2, "label": "len(…)" }
228                ]
229            }
230        });
231        let methods = parse_methods(&resp).unwrap();
232        assert_eq!(methods.len(), 1);
233        assert_eq!(methods[0].name, "len");
234    }
235
236    #[test]
237    fn parse_methods_unexpected_shape_returns_error() {
238        let resp = json!({ "result": "this_is_not_valid" });
239        assert!(parse_methods(&resp).is_err());
240    }
241
242    // These simulate what rust-analyzer returns for third-party crate types:
243    // the label contains the full signature e.g. `"as_str(…)"`.
244    #[test]
245    fn parse_methods_third_party_label_stripped_at_paren() {
246        let resp = json!({
247            "result": {
248                "items": [
249                    { "kind": 2, "label": "as_str(…)", "detail": "pub fn as_str(&self) -> &str" },
250                    { "kind": 2, "label": "as_object(…)" }
251                ]
252            }
253        });
254        let methods = parse_methods(&resp).unwrap();
255        let names: Vec<&str> = methods.iter().map(|m| m.name.as_str()).collect();
256        assert!(names.contains(&"as_str"));
257        assert!(names.contains(&"as_object"));
258    }
259
260    // ── parse_definition ─────────────────────────────────────────────────────
261    #[test]
262    fn parse_definition_array_form() {
263        let resp = json!({
264            "result": [{
265                "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/num/mod.rs",
266                "range": {
267                    "start": { "line": 42, "character": 0 },
268                    "end":   { "line": 42, "character": 10 }
269                }
270            }]
271        });
272        let def = parse_definition(&resp).unwrap();
273        assert_eq!(def.line, 42);
274        assert!(def.path.starts_with("library/"));
275        assert!(!def.full_path.starts_with("file://"));
276    }
277
278    #[test]
279    fn parse_definition_object_form() {
280        let resp = json!({
281            "result": {
282                "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/str/mod.rs",
283                "range": {
284                    "start": { "line": 99, "character": 4 },
285                    "end":   { "line": 99, "character": 20 }
286                }
287            }
288        });
289        let def = parse_definition(&resp).unwrap();
290        assert_eq!(def.line, 99);
291        assert!(def.path.starts_with("library/"));
292    }
293
294    #[test]
295    fn parse_definition_null_result_returns_none() {
296        let resp = json!({ "result": null });
297        assert!(parse_definition(&resp).is_none());
298    }
299
300    #[test]
301    fn parse_definition_empty_array_returns_none() {
302        let resp = json!({ "result": [] });
303        assert!(parse_definition(&resp).is_none());
304    }
305
306    #[test]
307    fn parse_definition_empty_uri_returns_none() {
308        let resp = json!({
309            "result": [{
310                "uri": "",
311                "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }
312            }]
313        });
314        assert!(parse_definition(&resp).is_none());
315    }
316
317    #[test]
318    fn parse_definition_strips_library_prefix_from_path() {
319        let resp = json!({
320            "result": [{
321                "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/num/mod.rs",
322                "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }
323            }]
324        });
325        let def = parse_definition(&resp).unwrap();
326        // path should start at "library/" not "/"
327        assert!(def.path.starts_with("library/"));
328        assert!(!def.path.starts_with('/'));
329    }
330
331    #[test]
332    fn parse_definition_src_path_fallback() {
333        // A third-party crate source — has /src/ but no /library/
334        let resp = json!({
335            "result": [{
336                "uri": "file:///home/user/myproject/src/main.rs",
337                "range": { "start": { "line": 5, "character": 0 }, "end": { "line": 5, "character": 0 } }
338            }]
339        });
340        let def = parse_definition(&resp).unwrap();
341        assert!(def.path.starts_with("src/"));
342        assert_eq!(def.line, 5);
343    }
344
345    #[test]
346    fn parse_definition_full_path_does_not_start_with_file_scheme() {
347        let resp = json!({
348            "result": [{
349                "uri": "file:///home/user/project/src/lib.rs",
350                "range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 0 } }
351            }]
352        });
353        let def = parse_definition(&resp).unwrap();
354        assert!(!def.full_path.starts_with("file://"));
355        assert!(def.full_path.starts_with('/'));
356    }
357}