Skip to main content

rust_meth_lib/
query.rs

1//! High-level builder API for querying `rust-analyzer`.
2//!
3//! [`MethodQuery`] provides a chainable interface over `query_methods` and
4//! `query_definition`, keeping call sites readable when multiple options are
5//! involved. [`filter_methods`] is also available as a standalone function for
6//! callers who already have a [`Vec<Method>`] and just need filtering.
7//!
8//! # Examples
9//!
10//! ```no_run
11//! use rust_meth_lib::query::MethodQuery;
12//! use rust_meth_lib::analyzer::find_rust_analyzer;
13//!
14//! let ra_path = find_rust_analyzer().unwrap();
15//!
16//! // Simple query with filter
17//! let methods = MethodQuery::new("Vec<u8>")
18//!     .filter("drain")
19//!     .run(&ra_path)
20//!     .unwrap();
21//!
22//! // Query with definitions, third-party type
23//! let results = MethodQuery::new("serde_json::Value")
24//!     .deps(r#"serde_json = "1.0""#)
25//!     .filter("as_")
26//!     .run_with_definitions(&ra_path)
27//!     .unwrap();
28//!
29//! for r in results {
30//!     if let Some(def) = r.definition {
31//!         println!("{} → {}:{}", r.method.name, def.path, def.line + 1);
32//!     }
33//! }
34//! ```
35
36use crate::analyzer::{Definition, Method, query_definition, query_methods};
37use crate::error::Result;
38
39/// Filters and ranks a slice of methods against a query string.
40///
41/// Scoring tiers (highest first):
42/// - **Exact match**: `name == query`
43/// - **Prefix match**: `name.starts_with(query)`
44/// - **Substring match**: `name.contains(query)`
45///
46/// Methods that don't match at all are excluded. Results are stable within
47/// each tier (input order is preserved for equal scores).
48///
49/// Pass `query = ""` or use [`filter_methods`] with an empty string to return
50/// all methods in input order.
51///
52/// # Example
53///
54/// ```no_run
55/// use rust_meth_lib::query::filter_methods;
56/// use rust_meth_lib::analyzer::{Method, find_rust_analyzer, query_methods};
57///
58/// let ra_path = find_rust_analyzer().unwrap();
59/// let methods = query_methods("HashMap<String, u32>", &ra_path, None).unwrap();
60/// let filtered = filter_methods(&methods, "get");
61/// for m in filtered {
62///     println!("{}", m.name);
63/// }
64/// ```
65#[must_use]
66pub fn filter_methods<'a>(methods: &'a [Method], query: &str) -> Vec<&'a Method> {
67    if query.is_empty() {
68        return methods.iter().collect();
69    }
70    let mut scored: Vec<(u8, &Method)> = methods
71        .iter()
72        .filter_map(|m| {
73            let score = if m.name == query {
74                3
75            } else if m.name.starts_with(query) {
76                2
77            } else if m.name.contains(query) {
78                1
79            } else {
80                return None;
81            };
82            Some((score, m))
83        })
84        .collect();
85
86    scored.sort_by_key(|a| std::cmp::Reverse(a.0));
87    scored.into_iter().map(|(_, m)| m).collect()
88}
89
90/// A method paired with its optional source location.
91///
92/// Returned by [`MethodQuery::run_with_definitions`] and
93/// [`query_definition_for_methods`]. The `definition` field is `None` when
94/// `rust-analyzer` has no source location for the method (e.g. compiler
95/// built-ins) the method is still included in results.
96pub struct MethodResult {
97    /// The method returned by the completion query.
98    pub method: Method,
99    /// The source location of the method, if resolvable.
100    pub definition: Option<Definition>,
101}
102
103/// Resolves source locations for a slice of methods in parallel.
104///
105/// Runs one [`query_definition`] call per method using [`std::thread::scope`].
106/// Methods where `rust-analyzer` returns no location are included with
107/// `definition: None` rather than being silently dropped.
108///
109/// # Errors
110///
111/// Returns an error if any underlying LSP session fails fatally. Per-method
112/// `Ok(None)` results (no source location found) are not errors.
113///
114/// # Example
115///
116/// ```no_run
117/// use rust_meth_lib::query::query_definition_for_methods;
118/// use rust_meth_lib::analyzer::{find_rust_analyzer, query_methods};
119///
120/// let ra_path = find_rust_analyzer().unwrap();
121/// let methods = query_methods("Vec<u8>", &ra_path, None).unwrap();
122/// let results = query_definition_for_methods(&methods, "Vec<u8>", None, &ra_path).unwrap();
123///
124/// for r in results {
125///     match r.definition {
126///         Some(def) => println!("{} → {}:{}", r.method.name, def.path, def.line + 1),
127///         None => println!("{} → (no source location)", r.method.name),
128///     }
129/// }
130/// ```
131pub fn query_definition_for_methods(
132    methods: &[Method],
133    type_name: &str,
134    deps: Option<&str>,
135    ra_path: &std::path::Path,
136) -> Result<Vec<MethodResult>> {
137    methods
138        .iter()
139        .map(|method| {
140            let definition = query_definition(type_name, &method.name, ra_path, deps)?;
141            Ok(MethodResult {
142                method: Method {
143                    name: method.name.clone(),
144                    detail: method.detail.clone(),
145                    documentation: method.documentation.clone(),
146                },
147                definition,
148            })
149        })
150        .collect()
151}
152
153/// A chainable builder for method queries.
154///
155/// Construct with [`MethodQuery::new`], optionally set [`deps`](MethodQuery::deps)
156/// and [`filter`](MethodQuery::filter), then call [`run`](MethodQuery::run) or
157/// [`run_with_definitions`](MethodQuery::run_with_definitions) to execute.
158///
159/// # Example
160///
161/// ```no_run
162/// use rust_meth_lib::query::MethodQuery;
163/// use rust_meth_lib::analyzer::find_rust_analyzer;
164///
165/// let ra_path = find_rust_analyzer().unwrap();
166///
167/// let methods = MethodQuery::new("String")
168///     .filter("push")
169///     .run(&ra_path)
170///     .unwrap();
171///
172/// for m in methods {
173///     println!("{}", m.name);
174/// }
175/// ```
176pub struct MethodQuery<'a> {
177    type_name: &'a str,
178    deps: Option<&'a str>,
179    filter: Option<&'a str>,
180    limit: Option<usize>,
181}
182
183impl<'a> MethodQuery<'a> {
184    /// Creates a new query for the given Rust type expression.
185    ///
186    /// # Example
187    ///
188    /// ```no_run
189    /// use rust_meth_lib::query::MethodQuery;
190    /// let q = MethodQuery::new("Vec<u8>");
191    /// ```
192    #[must_use]
193    pub const fn new(type_name: &'a str) -> Self {
194        Self {
195            type_name,
196            deps: None,
197            filter: None,
198            limit: None,
199        }
200    }
201
202    /// Sets the TOML dependency string for third-party crate types.
203    ///
204    /// Accepts the same format as `query_methods`, a raw TOML snippet that
205    /// would appear under `[dependencies]`. Multiple crates are
206    /// newline-separated.
207    ///
208    /// # Example
209    ///
210    /// ```no_run
211    /// use rust_meth_lib::query::MethodQuery;
212    /// use rust_meth_lib::analyzer::find_rust_analyzer;
213    ///
214    /// let ra_path = find_rust_analyzer().unwrap();
215    /// let methods = MethodQuery::new("serde_json::Value")
216    ///     .deps(r#"serde_json = "1.0""#)
217    ///     .run(&ra_path)
218    ///     .unwrap();
219    /// ```
220    #[must_use]
221    pub const fn deps(mut self, deps: &'a str) -> Self {
222        self.deps = Some(deps);
223        self
224    }
225
226    /// Applies a filter to the results after the query completes.
227    ///
228    /// Uses the same scoring as [`filter_methods`]: exact > prefix > substring.
229    /// Methods that don't match are excluded from results.
230    ///
231    /// # Example
232    ///
233    /// ```no_run
234    /// use rust_meth_lib::query::MethodQuery;
235    /// use rust_meth_lib::analyzer::find_rust_analyzer;
236    ///
237    /// let ra_path = find_rust_analyzer().unwrap();
238    /// let methods = MethodQuery::new("HashMap<String, u32>")
239    ///     .filter("get")
240    ///     .run(&ra_path)
241    ///     .unwrap();
242    /// ```
243    #[must_use]
244    pub const fn filter(mut self, query: &'a str) -> Self {
245        self.filter = Some(query);
246        self
247    }
248
249    /// Executes the query and returns matching methods.
250    ///
251    /// Runs [`query_methods`] then applies the filter if one was set.
252    /// Returns owned [`Method`] values.
253    ///
254    /// # Errors
255    ///
256    /// Propagates any error from the underlying LSP session.
257    pub fn run(self, ra_path: &std::path::Path) -> Result<Vec<Method>> {
258        let methods = query_methods(self.type_name, ra_path, self.deps)?;
259        let mut filtered = match self.filter {
260            Some(q) => filter_methods(&methods, q).into_iter().cloned().collect(),
261            None => methods,
262        };
263
264        if let Some(l) = self.limit {
265            filtered.truncate(l);
266        }
267
268        Ok(filtered)
269    }
270
271    /// Executes the query, applies the filter, and resolves source locations
272    /// for each matching method sequentially.
273    ///
274    /// Methods where `rust-analyzer` has no source location are included with
275    /// `definition: None` rather than being silently dropped.
276    ///
277    /// > **Note:** For third-party crate types, each definition query requires
278    /// > Cargo to resolve dependencies inside an ephemeral probe project. With
279    /// > many matching methods this can be slow. Use a tight [`filter`](MethodQuery::filter)
280    /// > to limit the number of definition queries, or prefer stdlib types where
281    /// > Cargo resolution is not required.
282    ///
283    /// # Errors
284    ///
285    /// Propagates any fatal LSP error. Per-method `Ok(None)` definition
286    /// results are not errors.
287    pub fn run_with_definitions(self, ra_path: &std::path::Path) -> Result<Vec<MethodResult>> {
288        let type_name = self.type_name;
289        let deps = self.deps;
290        let methods = self.run(ra_path)?;
291        query_definition_for_methods(&methods, type_name, deps, ra_path)
292    }
293
294    /// Limits the maximum number of methods returned after filtering.
295    ///
296    /// Useful for keeping definition resolution fast when a broad filter matches many items.
297    #[must_use]
298    pub const fn limit(mut self, limit: usize) -> Self {
299        self.limit = Some(limit);
300        self
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307    use crate::analyzer::Method;
308
309    fn make_methods(names: &[&str]) -> Vec<Method> {
310        names
311            .iter()
312            .map(|&name| Method {
313                name: name.to_string(),
314                detail: None,
315                documentation: None,
316            })
317            .collect()
318    }
319
320    #[test]
321    fn filter_empty_query_returns_all() {
322        let methods = make_methods(&["push", "pop", "len"]);
323        let result = filter_methods(&methods, "");
324        assert_eq!(result.len(), 3);
325    }
326
327    #[test]
328    fn filter_exact_match_scores_highest() {
329        let methods = make_methods(&["get_mut", "get", "get_key_value"]);
330        let result = filter_methods(&methods, "get");
331        assert_eq!(result[0].name, "get", "exact match should be first");
332    }
333
334    #[test]
335    fn filter_prefix_before_substring() {
336        let methods = make_methods(&["forget", "get_mut", "get"]);
337        let result = filter_methods(&methods, "get");
338        let names: Vec<&str> = result.iter().map(|m| m.name.as_str()).collect();
339        // "get" exact first, then prefix "get_mut", then substring "forget"
340        assert_eq!(names, ["get", "get_mut", "forget"]);
341    }
342
343    #[test]
344    fn filter_no_match_returns_empty() {
345        let methods = make_methods(&["push", "pop", "len"]);
346        let result = filter_methods(&methods, "zzz");
347        assert!(result.is_empty());
348    }
349
350    #[test]
351    fn filter_excludes_non_matching() {
352        let methods = make_methods(&["push", "pop", "get", "len"]);
353        let result = filter_methods(&methods, "get");
354        assert_eq!(result.len(), 1);
355        assert_eq!(result[0].name, "get");
356    }
357
358    #[test]
359    fn limit_truncates_results() {
360        let methods = make_methods(&["push", "pop", "len", "get", "insert"]);
361        let result = filter_methods(&methods, "");
362        let limited: Vec<&str> = result
363            .into_iter()
364            .take(3)
365            .map(|m| m.name.as_str())
366            .collect();
367        assert_eq!(limited, ["push", "pop", "len"]);
368    }
369
370    #[test]
371    fn limit_larger_than_results_returns_all() {
372        let methods = make_methods(&["push", "pop"]);
373        let result = filter_methods(&methods, "");
374        assert_eq!(result.len(), 2); // limit of 10 on 2 items returns 2
375    }
376
377    #[test]
378    fn builder_limit_truncates_after_filter() {
379        let methods = make_methods(&["get", "get_mut", "get_key_value", "get_unchecked"]);
380        // All 4 match "get", limit should cap at 2
381        let filtered: Vec<&Method> = filter_methods(&methods, "get")
382            .into_iter()
383            .take(2)
384            .collect();
385        assert_eq!(filtered.len(), 2);
386        assert_eq!(filtered[0].name, "get"); // exact match still first
387    }
388}