rust-meth-lib
Core library powering rust-meth.
Discovers methods available on any Rust type by driving a rust-analyzer LSP
session.
Overview
rust-meth-lib provides the building blocks for programmatically querying
rust-analyzer:
- Spinning up and managing an LSP session (
LspTransport) - Synthesizing a temporary Rust project and injecting the target type (
Probe) - Requesting completions and go-to-definition results from
rust-analyzer - Fuzzy-filtering and ranking method results
- Exposing utilities for embedding
rust-methworkflows in other tools - Full working Examples
Please file an Issue if any problems arise.
Workspace layout
rust-meth/
├── Cargo.toml — workspace manifest
├── lib/ — rust-meth-lib (this crate)
│ ├── Cargo.toml
│ ├── README.md
│ ├── benches/
│ │ └── benchmarks.rs
│ └── src/
│ ├── lib.rs
│ ├── error.rs
│ ├── lsp.rs
│ ├── probe.rs
│ └── analyzer/
│ ├── mod.rs
│ ├── discovery.rs
│ ├── parse.rs
│ └── session.rs
└── cli/ : standalone binary crate that calls into this library
├── Cargo.toml
└── src/
└── main.rs
UI components, CLI argument parsing, interactive selection, and spinner display are now maintained in
cli/.
Public API
Key Types
| Item | Description |
|---|---|
LspTransport | Manages the stdio JSON-RPC channel to a rust-analyzer process |
Probe | Builds a temporary Cargo project that makes the target type available for LSP queries |
analyzer | High-level session orchestrator, combines Probe + LspTransport to return method completions |
Basic Usage
[dependencies]
rust-meth-lib = "0.3.0"
Full working Example:
use rust_meth_lib::analyzer::{find_rust_analyzer, query_methods};
fn main() -> rust_meth_lib::error::Result<()> {
let ra_path = find_rust_analyzer()?;
let methods = query_methods("Result<u8, &'static str>", &ra_path, None)?;
println!("Methods available for Result<u8, &'static str>");
for method in &methods {
println!("{}", method.name);
}
Ok(())
}
The exact list returned varies by toolchain.
Note
The primary APIs are intended for embedding or extending the
rust-methworkflow.
The CLI interface is maintained in a separate crate.
Builder API
MethodQuery provides a chainable interface over
query_methods and filter_methods. Use .filter() to narrow results by
match quality (exact > prefix > substring), and .run_with_definitions() to
also resolve source locations.
#![allow(unused)]
fn main() {
// Query + filter
MethodQuery::new("String")
.filter("push")
.run(&ra_path)?;
// Query + filter + source locations
MethodQuery::new("serde_json::Value")
.deps(r#"serde_json = "1.0""#)
.filter("as_str")
.run_with_definitions(&ra_path)?;
}
See builder_run.rs and
builder_definitions.rs for full examples.
Error Handling
The library uses a single
RustMethError
enum (via thiserror) and a Result<T> alias over
it:
pub type Result<T> = std::result::Result<T, RustMethError>;
| Variant | Cause |
|---|---|
Io | OS / file system errors (std::io::Error) |
Json | JSON serialization or deserialization failure |
ParseInt | String-to-integer conversion failure |
NoContentLength | LSP response missing a Content-Length header |
RecvExhausted { limit } | Message loop hit limit without matching a response |
UnexpectedResponseShape | Structurally valid JSON but missing expected fields |
RustAnalyzerNotFound | rust-analyzer not on PATH or in component directory |
MissingStdin | stdin handle wasn’t captured |
MissingStdout | stdout handle wasn’t captured |
TypeNotFound | rust-analyzer diagnostic error for the probed type |
Timeout | rust-analyzer failed to produce a usable response within retry budget |
FeatureGated | Type exists but requires a feature flag that wasn’t enabled for this probe |
All fallible functions in this crate return rust_meth_lib::Result<T>. If
you’re embedding the library, you can convert into your own error type via ?
since RustMethError implements std::error::Error.
#![allow(unused)]
fn main() {
use rust_meth_lib::{Result, analyzer::{find_rust_analyzer, query_methods}};
fn my_wrapper() -> Result<()> {
// RustAnalyzerNotFound, Io, Json, etc. all propagate with ?
let ra_path = find_rust_analyzer()?;
let _methods = query_methods("Vec<u8>", &ra_path, None)?;
Ok(())
}
}
rust-meth-lib examples
Runnable examples covering the main ways to embed rust-meth-lib in your own
tooling. Each file is self-contained and documents its own [dependencies]
snippet.
Running the Examples
To run the examples locally, clone the repo:
git clone https://github.com/saylesss88/rust-meth.git
cd rust-meth/lib
cargo run --example basic_query
The examples require rust-analyzer on your PATH:
rustup component add rust-analyzer
cargo run --example basic_query
cargo run --example method_info
cargo run --example third_party_crate # slow on first run (downloads serde_json)
cargo run --example fuzzy_filter
cargo run --example go_to_definition
cargo run --example custom_error
cargo run --example batch_query
Examples start at Getting Started
Getting Started
Runnable examples covering the main ways to embed rust-meth-lib in your own
tooling. Each file is self-contained and documents its own [dependencies]
snippet.
basic_query.rs
This example first locates the rust-analyzer binary, then it queries the
available methods on a RefCell<u8> and prints the results.
use rust_meth_lib::analyzer::{find_rust_analyzer, query_methods};
fn main() -> rust_meth_lib::error::Result<()> {
let ra_path = find_rust_analyzer()?;
let methods = query_methods("RefCell<u8>", &ra_path, None)?;
println!("Methods on RefCell<u8> ({} total):", methods.len());
for method in &methods {
println!(" {}", method.name);
}
Ok(())
}
Output
The minimal end-to-end path: find_rust_analyzer → query_methods → print
method names.
Methods on RefCell<u8> (30 total):
as_ptr
borrow
borrow_mut
clamp
clone
clone_from
clone_into
cmp
eq
ge
get_mut
gt
into
into_inner
le
lt
max
min
ne
partial_cmp
replace
replace_with
swap
take
to_owned
try_borrow
try_borrow_mut
try_borrow_unguarded
try_into
undo_leak
Limit Number of Methods Returned from Standard API
use rust_meth_lib::analyzer::{Method, find_rust_analyzer, query_methods};
fn main() -> rust_meth_lib::error::Result<()> {
// Step 1: locate the rust-analyzer binary.
//
// find_rust_analyzer checks `PATH` first, then falls back to the rustup
// component directory (~/.rustup/toolchains/<active>/bin/rust-analyzer).
// Returns `RustMethError::RustAnalyzerNotFound` if neither exists.
let ra_path = find_rust_analyzer()?;
// Step 2: query methods.
//
// query_methods spins up an ephemeral LSP session, synthesises a
// temporary Cargo project with `let _x: RefCell<u8> = todo!();`, triggers
// a completion request at the dot position, and tears everything down.
//
// The third argument is `deps: Option<&str>`: `None` means stdlib only.
let methods = query_methods("RefCell<u8>", &ra_path, None)?;
let top5: Vec<Method> = methods.into_iter().take(5).collect();
// println!("Methods on RefCell<u8> ({} total):", methods.len());
println!("First 5 methods on RefCell<u8>:");
// for method in &methods {
for method in &top5 {
println!(" {}", method.name);
}
Ok(())
}
Output
First 5 methods on RefCell<u8>:
as_ptr
borrow
borrow_mut
clamp
clone
Using the Builder API
The same query using [MethodQuery], equivalent to the above but chainable:
use rust_meth_lib::analyzer::find_rust_analyzer;
use rust_meth_lib::query::MethodQuery;
fn main() -> rust_meth_lib::error::Result<()> {
let ra_path = find_rust_analyzer()?;
let methods = MethodQuery::new("RefCell<u8>")
.run(&ra_path)?;
println!("Methods on RefCell<u8> ({} total):", methods.len());
for method in &methods {
println!(" {}", method.name);
}
Ok(())
}
The builder becomes more useful when combining options, adding a filter or resolving source locations without separate function calls:
let methods = MethodQuery::new("RefCell<u8>")
.filter("borrow")
.run(&ra_path)?;
With the filter above, the output is (I changed the print statement to match):
Methods on RefCell<u8> with borrow in their name (5 total):
borrow
borrow_mut
try_borrow
try_borrow_mut
try_borrow_unguarded
Limit the Number of Methods Returned
You can use the .limit() method to return N methods. For example, a Vec<u8>,
returns over 200 methods. To only return the first 10 sorted alphabetically:
use rust_meth_lib::analyzer::find_rust_analyzer;
use rust_meth_lib::query::MethodQuery;
fn main() -> rust_meth_lib::error::Result<()> {
let ra_path = find_rust_analyzer()?;
let methods = MethodQuery::new("Vec<u8>").limit(10).run(&ra_path)?;
println!("First 10 methods on Vec<u8>:");
for method in &methods {
println!(" {}", method.name);
}
Ok(())
}
Output
First 10 methods on Vec<u8>:
align_to
align_to_mut
allocator
append
array_windows
as_array
as_ascii
as_ascii_unchecked
as_chunks
as_chunks_mut
Querying Methods
Shows how to work with the richer fields on [Method] beyond just the name:
Method::detail: the full function signature as a string (e.g."const fn(&self) -> *mut T"), returned byrust-analyzeras the completion item’s detail field.Option<String>: not always present, especially for trait-provided methods on generic types.Method::documentation: the rustdoc string for the method, often multi-line.Option<String>: coverage varies by crate and method.
Both fields are None when rust-analyzer doesn’t return them. Methods with
neither still appear in the results from query_methods. This example filters
to only those with at least one field populated, and renders them gracefully
when the other is absent.
method_info.rs
use rust_meth_lib::analyzer::{Method, find_rust_analyzer, query_methods};
fn main() -> rust_meth_lib::error::Result<()> {
let ra_path = find_rust_analyzer()?;
let methods = query_methods("Cell<u8>", &ra_path, None)?;
// Only print methods that have at least a signature. Methods with
// neither detail nor docs still exist in the list, they're just
// less useful for display purposes.
let documented: Vec<&Method> = methods
.iter()
.filter(|m| m.detail.is_some() || m.documentation.is_some())
.collect();
println!(
"{} of {} Cell<u8> methods have signatures or docs:\n",
documented.len(),
methods.len()
);
for method in documented {
// The signature line (e.g. "pub fn push_str(&mut self, string: &str)")
if let Some(sig) = &method.detail {
println!("fn {} → {sig}", method.name);
} else {
println!("fn {} (no signature)", method.name);
}
// Rustdoc
if let Some(doc) = &method.documentation {
// Just the first sentence to keep output manageable.
let first_line = doc.lines().next().unwrap_or("").trim();
if !first_line.is_empty() {
println!(" doc: {first_line}");
}
}
println!();
}
Ok(())
}
Output
26 of 26 Cell<u8> methods have signatures or docs:
fn as_ptr → const fn(&self) -> *mut T
doc: Returns a raw pointer to the underlying data in this cell.
fn clamp → fn(self, Self, Self) -> Self
doc: Restrict a value to a certain interval.
fn clone → fn(&self) -> Self
doc: Returns a duplicate of the value.
fn clone_from → fn(&mut self, &Self)
doc: Performs copy-assignment from `source`.
fn clone_into → fn(&self, &mut <Self as ToOwned>::Owned)
doc: Uses borrowed data to replace owned data, usually by cloning.
fn cmp → fn(&self, &Self) -> Ordering
doc: This method returns an [`Ordering`] between `self` and `other`.
fn eq → fn(&self, &Rhs) -> bool
doc: Equality operator `==`.
fn ge → fn(&self, &Rhs) -> bool
doc: Tests greater than or equal to (for `self` and `other`) and is used by
fn get → const fn(&self) -> T
doc: Returns a copy of the contained value.
fn get_mut → const fn(&mut self) -> &mut T
doc: Returns a mutable reference to the underlying data.
fn gt → fn(&self, &Rhs) -> bool
doc: Tests greater than (for `self` and `other`) and is used by the `>`
fn into → fn(self) -> T
doc: Converts this type into the (usually inferred) input type.
fn into_inner → const fn(self) -> T
doc: Unwraps the value, consuming the cell.
fn le → fn(&self, &Rhs) -> bool
doc: Tests less than or equal to (for `self` and `other`) and is used by the
fn lt → fn(&self, &Rhs) -> bool
doc: Tests less than (for `self` and `other`) and is used by the `<` operator.
fn max → fn(self, Self) -> Self
doc: Compares and returns the maximum of two values.
fn min → fn(self, Self) -> Self
doc: Compares and returns the minimum of two values.
fn ne → fn(&self, &Rhs) -> bool
doc: Inequality operator `!=`.
fn partial_cmp → fn(&self, &Rhs) -> Option<Ordering>
doc: This method returns an ordering between `self` and `other` values if one exists.
fn replace → const fn(&self, T) -> T
doc: Replaces the contained value with `val`, and returns the old contained value.
fn set → const fn(&self, T)
doc: Sets the contained value.
fn swap → fn(&self, &Cell<T>)
doc: Swaps the values of two `Cell`s.
fn take → const fn(&self) -> T
doc: Takes the value of the cell, leaving `Default::default()` in its place.
fn to_owned → fn(&self) -> <Self as ToOwned>::Owned
doc: Creates owned data from borrowed data, usually by cloning.
fn try_into → fn(self) -> Result<T, <Self as TryInto<T>>::Error>
doc: Performs the conversion.
fn update → const fn(&self, impl FnOnce(T) -> T)
doc: Updates the contained value using a function.
Batch Query
Querying multiple types and aggregating the results.
query_methods_batch runs each query in parallel: one thread per type,
each with its own independent rust-analyzer subprocess. Total wall time
is roughly the cost of the slowest single query rather than the sum of all.
Errors are per-type and do not abort the batch.
batch_query.rs
For Vec<u8>, VecDeque<u8>, and LinkedList<u8>, this example returns:
- Per-type method counts: printed after all queries complete
- Common methods: the intersection across all three types
- Unique methods: what each type has that neither of the others does
use rust_meth_lib::analyzer::{find_rust_analyzer, query_methods_batch};
use rust_meth_lib::error::RustMethError;
use std::collections::{BTreeMap, BTreeSet};
fn main() -> rust_meth_lib::error::Result<()> {
let ra_path = find_rust_analyzer()?;
let queries: &[(&str, Option<&str>)] = &[
("Vec<u8>", None),
("VecDeque<u8>", None),
("LinkedList<u8>", None),
];
// All three queries run in parallel. Results come back in input order.
let batch_results = query_methods_batch(queries, &ra_path);
// -- Partition into successes and failures --
let mut results: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
let mut failures: Vec<(&str, RustMethError)> = Vec::new();
for (type_name, result) in batch_results {
match result {
Ok(methods) => {
let names: BTreeSet<String> = methods.into_iter().map(|m| m.name).collect();
println!("{type_name}: {} methods", names.len());
results.insert(type_name, names);
}
Err(e) => {
eprintln!("{type_name}: FAILED: {e}");
failures.push((type_name, e));
}
}
}
println!();
// -- Methods common to all successfully queried types --
if results.len() >= 2 {
let mut common = results.values().next().cloned().unwrap_or_default();
for set in results.values().skip(1) {
common = common.intersection(set).cloned().collect();
}
println!(
"Methods common to all {} types ({} total):",
results.len(),
common.len()
);
for name in &common {
println!(" {name}");
}
println!();
}
// -- Per-type unique methods --
//
// What does each type have that none of the others do?
for (type_name, methods) in &results {
let others_union: BTreeSet<&String> = results
.iter()
.filter(|(t, _)| *t != type_name)
.flat_map(|(_, s)| s.iter())
.collect();
let unique: Vec<&String> = methods
.iter()
.filter(|m| !others_union.contains(m))
.collect();
if unique.is_empty() {
println!("{type_name}: no unique methods");
} else {
println!("{type_name} unique methods ({}):", unique.len());
for name in unique {
println!(" {name}");
}
}
println!();
}
// -- Summary of failures --
if !failures.is_empty() {
println!("Failed queries:");
for (type_name, err) in failures {
println!(" {type_name}: {err}");
}
}
Ok(())
}
Output
Vec<u8>: 229 methods
VecDeque<u8>: 114 methods
LinkedList<u8>: 46 methods
Methods common to all 3 types (32 total):
append
clamp
clear
clone
clone_from
clone_into
cmp
contains
eq
extend
extend_one
extend_reserve
extract_if
ge
gt
into
into_iter
is_empty
iter
iter_mut
le
len
lt
max
min
ne
partial_cmp
remove
retain
split_off
to_owned
try_into
LinkedList<u8> unique methods (4):
cursor_back
cursor_back_mut
cursor_front
cursor_front_mut
Vec<u8> unique methods (156):
align_to
align_to_mut
array_windows
as_array
as_ascii
as_ascii_unchecked
as_chunks
as_chunks_mut
as_chunks_unchecked
as_chunks_unchecked_mut
as_mut
as_mut_array
as_mut_ptr
as_mut_ptr_range
as_mut_slice
as_non_null
as_ptr
as_ptr_range
as_rchunks
as_rchunks_mut
as_ref
as_simd
as_simd_mut
as_slice
chunk_by
chunk_by_mut
chunks
chunks_exact
chunks_exact_mut
chunks_mut
clone_from_slice
concat
connect
const_make_global
copy_from_slice
copy_within
dedup
dedup_by
dedup_by_key
deref
deref_mut
element_offset
ends_with
eq_ignore_ascii_case
escape_ascii
extend_from_slice
fill
fill_with
first
first_chunk
first_chunk_mut
first_mut
get_disjoint_mut
get_disjoint_unchecked_mut
get_unchecked
get_unchecked_mut
into_array
into_boxed_slice
into_chunks
into_parts
into_parts_with_alloc
into_raw_parts
into_raw_parts_with_alloc
is_ascii
is_sorted
is_sorted_by
is_sorted_by_key
join
last
last_chunk
last_chunk_mut
last_mut
leak
make_ascii_lowercase
make_ascii_uppercase
partial_sort_unstable
partial_sort_unstable_by
partial_sort_unstable_by_key
partition_dedup
partition_dedup_by
partition_dedup_by_key
peek_mut
pop
pop_if
push
push_mut
push_within_capacity
rchunks
rchunks_exact
rchunks_exact_mut
rchunks_mut
recycle
repeat
reverse
rsplit
rsplit_mut
rsplit_once
rsplitn
rsplitn_mut
select_nth_unstable
select_nth_unstable_by
select_nth_unstable_by_key
set_len
shift_left
shift_right
sort
sort_by
sort_by_cached_key
sort_by_key
sort_unstable
sort_unstable_by
sort_unstable_by_key
spare_capacity_mut
split_at
split_at_checked
split_at_mut
split_at_mut_checked
split_at_mut_unchecked
split_at_spare_mut
split_at_unchecked
split_first
split_first_chunk
split_first_chunk_mut
split_first_mut
split_inclusive
split_inclusive_mut
split_last
split_last_chunk
split_last_chunk_mut
split_last_mut
split_mut
split_once
splitn
splitn_mut
starts_with
strip_circumfix
strip_prefix
strip_suffix
subslice_range
swap_remove
swap_unchecked
swap_with_slice
to_ascii_lowercase
to_ascii_uppercase
to_vec
to_vec_in
trim_ascii
trim_ascii_end
trim_ascii_start
trim_prefix
trim_suffix
try_remove
try_shrink_to
try_shrink_to_fit
utf8_chunks
windows
VecDeque<u8> unique methods (31):
as_mut_slices
as_slices
consume
extend_front
fill_buf
has_data_left
is_read_vectored
make_contiguous
pop_back_if
pop_front_if
prepend
prepend_from_within
range
range_mut
read
read_array
read_be
read_buf
read_buf_exact
read_exact
read_le
read_line
read_to_end
read_to_string
read_until
read_vectored
retain_back
skip_until
swap_remove_back
swap_remove_front
truncate_to_range
Error Handling
All fallible functions in rust-meth-lib return rust_meth_lib::Result<T>, a
type alias over a single [RustMethError] enum. This makes it easy to propagate
errors with ? in your own code, and to convert them into your application’s
own error type when you need custom messages or behaviour.
RustMethError variants
| Variant | Cause |
|---|---|
RustAnalyzerNotFound | rust-analyzer not on PATH or in rustup component directory |
TypeNotFound | The probed type doesn’t exist or isn’t in scope |
FeatureGated | Type exists but requires a feature flag not enabled in the probe |
Timeout | rust-analyzer failed to respond within the retry budget |
Io | OS or filesystem error |
Json | JSON serialization or deserialization failure |
UnexpectedResponseShape | Structurally valid JSON but missing expected fields |
RecvExhausted | Message loop hit its limit without matching a response |
Custom error types
The most common embedding pattern is wrapping RustMethError in your own
thiserror enum. Since RustMethError implements std::error::Error, it
converts with ? directly, but a manual From impl lets you intercept
specific variants for custom messages before falling through to a generic
wrapper for everything else.
The example below intercepts RustAnalyzerNotFound and TypeNotFound to give
actionable error messages, while passing everything else through as a generic
QueryFailed.
custom_error.rs
use rust_meth_lib::analyzer::{find_rust_analyzer, query_methods};
use rust_meth_lib::error::RustMethError;
// -- Your application's error type --
#[derive(Debug, thiserror::Error)]
enum AppError {
/// rust-analyzer isn't installed, give a helpful message.
#[error("rust-analyzer not found. Install it with: rustup component add rust-analyzer")]
RustAnalyzerMissing,
/// The type the user asked about doesn't exist.
#[error(
"Unknown type `{type_name}`. Check the spelling and that any required crate is listed in deps."
)]
UnknownType { type_name: String },
/// Anything else from the library becomes a generic query failure.
#[error("LSP query failed: {0}")]
QueryFailed(RustMethError),
}
// -- Conversion --
//
// We can't use `#[from]` for everything because we want to intercept specific
// variants. Instead, write a manual `From` impl that matches the cases we care
// about and falls through to the generic wrapper for everything else.
impl From<RustMethError> for AppError {
fn from(err: RustMethError) -> Self {
match err {
RustMethError::RustAnalyzerNotFound => Self::RustAnalyzerMissing,
RustMethError::TypeNotFound { type_name, .. } => Self::UnknownType { type_name },
other => Self::QueryFailed(other),
}
}
}
// -- Application logic --
fn lookup(type_name: &str) -> Result<(), AppError> {
// find_rust_analyzer() returns RustMethError::RustAnalyzerNotFound on
// failure, which our From impl converts to AppError::RustAnalyzerMissing.
let ra_path = find_rust_analyzer()?;
// query_methods() returns RustMethError::TypeNotFound for bad type names,
// which our From impl converts to AppError::UnknownType.
let methods = query_methods(type_name, &ra_path, None)?;
println!("{type_name}: {} methods", methods.len());
for m in methods.iter().take(5) {
println!(" {}", m.name);
}
if methods.len() > 5 {
println!(" ...and {} more", methods.len() - 5);
}
Ok(())
}
fn main() {
// Use a type that will succeed.
match lookup("Vec<u8>") {
Ok(()) => {}
Err(e) => eprintln!("error: {e}"),
}
println!();
// Use a type that will fail with `TypeNotFound`, demonstrates the
// custom error message path.
match lookup("NonExistentType") {
Ok(()) => {}
Err(AppError::UnknownType { type_name }) => {
eprintln!("Type not found: `{type_name}`");
eprintln!("Tip: check spelling, or pass deps for third-party crates.");
}
Err(e) => eprintln!("error: {e}"),
}
}
Output
Vec<u8>: 229 methods
align_to
align_to_mut
allocator
append
array_windows
...and 224 more
Type not found: `NonExistentType`
Tip: check spelling, or pass deps for third-party crates.
Filtering
Filters and ranks methods against a query string without re-querying
rust-analyzer. Useful if you already have a Vec<Method> and want to narrow
results. Exact matches score highest, then prefix, then substring. Non-matching
methods are excluded entirely.
filter_methods.rs
use rust_meth_lib::analyzer::{find_rust_analyzer, query_methods};
use rust_meth_lib::query::filter_methods;
fn main() -> rust_meth_lib::error::Result<()> {
let ra_path = find_rust_analyzer()?;
let methods = query_methods("HashMap<String, u32>", &ra_path, None)?;
let filtered = filter_methods(&methods, "get");
println!("HashMap<String, u32> methods matching \"get\":\n");
for m in filtered {
println!("{}", m.name);
}
Ok(())
}
Output
HashMap<String, u32> methods matching "get":
get
get_disjoint_mut
get_disjoint_unchecked_mut
get_key_value
get_mut
fuzzy_filter.rs
query_methods returns a plain Vec<Method>: already sorted and deduplicated,
ready to filter however you like. This example shows a few patterns: substring
match, signature grep, and a simple ranked scorer. If you’re building a TUI or
editor plugin on top of the library, this is the pattern to follow.
use rust_meth_lib::analyzer::{Method, find_rust_analyzer, query_methods};
fn main() -> rust_meth_lib::error::Result<()> {
let ra_path = find_rust_analyzer()?;
let methods = query_methods("HashMap<String, u32>", &ra_path, None)?;
let query = "get";
println!("All methods containing \"{query}\":");
println!("{}", "-".repeat(40));
// -- 1. Simple substring filter --
let matched: Vec<&Method> = methods.iter().filter(|m| m.name.contains(query)).collect();
for m in &matched {
println!(" {}", m.name);
}
println!();
// -- 2. Signature grep --
//
// Filter on the `detail` field to find methods with a specific return type.
// Useful when you want to narrow results by type, not just name.
let returns_option: Vec<&Method> = methods
.iter()
.filter(|m| {
m.detail
.as_deref()
.is_some_and(|sig| sig.contains("-> Option"))
})
.collect();
println!("Methods returning Option<_>:");
println!("{}", "-".repeat(40));
for m in &returns_option {
println!(
" {} → {}",
m.name,
m.detail.as_deref().unwrap_or("(no signature)")
);
}
println!();
// -- 3. Simple ranked scorer --
//
// Score each method by how closely it matches the query: prefix match
// scores higher than substring match, exact match highest. This gives
// you a starting point for building fuzzy ranking without pulling in
// a whole fuzzy-matching crate.
println!("Ranked results for \"{query}\":");
println!("{}", "-".repeat(40));
let mut scored: Vec<(u8, &Method)> = methods
.iter()
.filter_map(|m| {
let score = if m.name == query {
3 // exact
} else if m.name.starts_with(query) {
2 // prefix
} else if m.name.contains(query) {
1 // substring
} else {
return None;
};
Some((score, m))
})
.collect();
// Sort descending by score; stable within each tier (already alpha-sorted
// from query_methods).
scored.sort_by_key(|item| std::cmp::Reverse(item.0));
for (score, m) in scored {
let label = match score {
3 => "exact ",
2 => "prefix",
_ => "substr",
};
println!(" [{label}] {}", m.name);
}
Ok(())
}
Output
All methods containing "get":
----------------------------------------
get
get_disjoint_mut
get_disjoint_unchecked_mut
get_key_value
get_mut
Methods returning Option<_>:
----------------------------------------
get → fn(&self, &Q) -> Option<&V>
get_key_value → fn(&self, &Q) -> Option<(&K, &V)>
get_mut → fn(&mut self, &Q) -> Option<&mut V>
insert → fn(&mut self, K, V) -> Option<V>
remove → fn(&mut self, &Q) -> Option<V>
remove_entry → fn(&mut self, &Q) -> Option<(K, V)>
Ranked results for "get":
----------------------------------------
[exact ] get
[prefix] get_disjoint_mut
[prefix] get_disjoint_unchecked_mut
[prefix] get_key_value
[prefix] get_mut
Definitions
This chapter covers how to locate the actual source code definitions for methods
across standard library and third-party types using rust-analyzer.
go_to_definition.rs
- Direct Definition Queries
The go_to_definition.rs example demonstrates how to query a specific type and
method combination to find its absolute and relative paths on disk, alongside
the line number.
use rust_meth_lib::analyzer::{find_rust_analyzer, query_definition};
fn main() -> rust_meth_lib::error::Result<()> {
let ra_path = find_rust_analyzer()?;
// -- Stdlib method --
print_definition("Vec<u8>", "push", &ra_path, None)?;
print_definition("String", "push_str", &ra_path, None)?;
print_definition("HashMap<String, u32>", "insert", &ra_path, None)?;
// -- Third-party method --
let serde_deps = r#"serde_json = "1.0""#;
print_definition("serde_json::Value", "as_str", &ra_path, Some(serde_deps))?;
Ok(())
}
fn print_definition(
type_name: &str,
method_name: &str,
ra_path: &std::path::Path,
deps: Option<&str>,
) -> rust_meth_lib::error::Result<()> {
print!("{type_name}::{method_name} → ");
match query_definition(type_name, method_name, ra_path, deps)? {
Some(def) => {
// `path` is the display-friendly shortened form:
// "library/core/src/num/uint_macros.rs"
//
// `full_path` is the absolute path on disk, useful if you want
// to open the file programmatically.
//
// `line` is 0-indexed (LSP convention). Add 1 for display.
println!("{}:{}", def.path, def.line + 1);
println!(" full: {}", def.full_path);
}
None => {
// Not an error, `rust-analyzer` just doesn't have a source
// location for this method. Common for compiler intrinsics.
println!("(no source location found)");
}
}
println!();
Ok(())
}
Output
Vec<u8>::push → library/alloc/src/vec/mod.rs:995
full: /home/jr/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs
String::push_str → library/alloc/src/string.rs:1104
full: /home/jr/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/string.rs
HashMap<String, u32>::insert → library/std/src/collections/hash/map.rs:1332
full: /home/jr/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/collections/hash/map.rs
serde_json::Value::as_str → src/index.crates.io-1949cf8c6b5b557f/serde_json-1.0.151/src/value/mod.rs:492
full: /home/jr/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/serde_json-1.0.151/src/value/mod.rs
builder_definitions.rs
- Builder Pattern with Definitions
The builder_definitions.rs example integrates definition lookup into the
MethodQuery builder. This allows you to filter methods and immediately
retrieve their source locations in a single workflow.
Note
For third-party types, each matching method runs a separate definition query. Use a tight filter (exact or short prefix) to limit the number of queries. Results are not cached by the results cache since definition queries return source locations rather than method lists, expect similar times on every run for third-party types.
use rust_meth_lib::analyzer::find_rust_analyzer;
use rust_meth_lib::query::MethodQuery;
fn main() -> rust_meth_lib::error::Result<()> {
let ra_path = find_rust_analyzer()?;
// -- Stdlib type -- fast --
let results = MethodQuery::new("Vec<u8>")
.filter("drain")
.run_with_definitions(&ra_path)?;
println!("Vec<u8> methods matching \"drain\" with source locations:");
for r in &results {
match &r.definition {
Some(def) => println!(" {} → {}:{}", r.method.name, def.path, def.line + 1),
None => println!(" {} → (no source location)", r.method.name),
}
}
println!();
// -- Third-party type -- use an exact filter to limit definition queries.
// Definition results are not cached, so this will always spin up
// rust-analyzer. A broad filter like "as_" would multiply this cost
// by the number of matches.
println!("Querying serde_json::Value::as_str (may be slow on first run)...");
let results = MethodQuery::new("serde_json::Value")
.deps(r#"serde_json = "1.0""#)
.filter("as_str")
.run_with_definitions(&ra_path)?;
println!("serde_json::Value methods matching \"as_str\" with source locations:");
for r in &results {
match &r.definition {
Some(def) => println!(" {} → {}:{}", r.method.name, def.path, def.line + 1),
None => println!(" {} → (no source location)", r.method.name),
}
}
Ok(())
}
Output
Vec<u8> methods matching "drain" with source locations:
drain → library/alloc/src/vec/mod.rs:3022
Querying serde_json::Value::as_str (may be slow on first run)...
serde_json::Value methods matching "as_str" with source locations:
as_str → src/index.crates.io-1949cf8c6b5b557f/serde_json-1.0.151/src/value/mod.rs:492
Builder API
Builder options
| Method | Description |
|---|---|
MethodQuery::new(type_name) | Start a query for the given type |
.deps(toml) | TOML dependency string for third-party crates |
.filter(query) | Narrow results by name (exact > prefix > substring) |
.run(&ra_path) | Execute and return Vec<Method> |
.run_with_definitions(&ra_path) | Execute and return Vec<MethodResult> with source locations |
builder_run.rs
use rust_meth_lib::analyzer::find_rust_analyzer;
use rust_meth_lib::query::MethodQuery;
fn main() -> rust_meth_lib::error::Result<()> {
let ra_path = find_rust_analyzer()?;
let methods = MethodQuery::new("String").filter("push").run(&ra_path)?;
println!("String methods matching \"push\":");
for m in &methods {
let sig = m.detail.as_deref().unwrap_or("(no signature)");
println!(" {} → {sig}", m.name);
}
Ok(())
}
Output
String methods matching "push":
push → fn(&mut self, char)
push_str → fn(&mut self, &str)
Results Cache
The results_cache example demonstrates the caching mechanism introduced in version 0.4.0.
When querying methods for a type, the library normally spins up a
rust-analyzer LSP session, which can take a few seconds. The results cache
stores these outputs as JSON in $XDG_CACHE_HOME/rust-meth/results/. Subsequent
calls, even across separate process runs, retrieve the data instantly with zero
LSP overhead.
results_cache.rs
use rust_meth_lib::analyzer::{find_rust_analyzer, query_methods};
use rust_meth_lib::results_cache::results_cache_entries;
use std::time::Instant;
fn main() -> rust_meth_lib::error::Result<()> {
let ra_path = find_rust_analyzer()?;
// Uncomment to clear the cache on every run
// rust_meth_lib::results_cache::clear_results_cache().ok();
// -- First call -- cold results cache --
println!("First call (cold cache)...");
let t1 = Instant::now();
let methods = query_methods("Vec<u8>", &ra_path, None)?;
let elapsed1 = t1.elapsed();
println!(" {} methods found in {:.2?}\n", methods.len(), elapsed1);
// Inspect what was saved
let entries = results_cache_entries();
println!("Results cache now has {} entry:", entries.len());
for e in &entries {
println!(
" {} : {} methods (ra: {})",
e.type_name, e.method_count, e.ra_version
);
}
println!();
// -- Second call -- results cache hit --
println!("Second call (warm cache)...");
let t2 = Instant::now();
let methods2 = query_methods("Vec<u8>", &ra_path, None)?;
let elapsed2 = t2.elapsed();
println!(" {} methods found in {:.2?}\n", methods2.len(), elapsed2);
// Summary
let speedup = elapsed1.as_secs_f64() / elapsed2.as_secs_f64();
println!("Speedup: {speedup:.0}x faster on cache hit");
println!("\nRun this example again to see the persistent cache kick in");
println!(
"on the very first call (~0ms instead of ~{}s).",
elapsed1.as_secs()
);
Ok(())
}
Output
First call (cold cache)...
229 methods found in 3.66s
Results cache now has 1 entry:
Vec<u8> : 229 methods (ra: rust-analyzer 1.100.0-nightly (34baba5 2026-08-16))
Second call (warm cache)...
229 methods found in 17.29ms
Speedup: 212x faster on cache hit
Run this example again to see the persistent cache kick in
on the very first call (~0ms instead of ~3s).
Note
Running this example a second time will yield a warm cache on both queries, dropping the first call’s time down to fractions of a millisecond.
Third Party Crates
Querying methods on types from external crates.
Note
The first time you query a third-party type, Cargo must download and compile the crate inside the ephemeral probe project. This can take 10-30 seconds on a cold cache. Subsequent queries still require Cargo to resolve dependencies inside the ephemeral probe project, so expect similar times on every invocation until persistent probe caching is implemented.
third_party_crate.rs
use rust_meth_lib::analyzer::{find_rust_analyzer, query_methods};
fn main() -> rust_meth_lib::error::Result<()> {
let ra_path = find_rust_analyzer()?;
// ── Single external crate ────────────────────────────────────────────────
let serde_deps = r#"serde_json = "1.0""#;
println!("Querying serde_json::Value methods (may be slow on first run)...");
let methods = query_methods("serde_json::Value", &ra_path, Some(serde_deps))?;
println!("serde_json::Value has {} methods:", methods.len());
for m in &methods {
println!(" {}", m.name);
}
println!();
// ── Multiple dependencies ────────────────────────────────────────────────
//
// If your type requires more than one crate (e.g. a type that uses serde
// traits), pass all deps as a single newline-separated string. This maps
// directly to what Cargo expects under [dependencies].
let multi_deps = "serde = { version = \"1.0\", features = [\"derive\"] }\nserde_json = \"1.0\"";
println!("Querying serde_json::Map with serde + serde_json...");
let map_methods = query_methods(
"serde_json::Map<String, serde_json::Value>",
&ra_path,
Some(multi_deps),
)?;
println!("serde_json::Map has {} methods:", map_methods.len());
for m in &map_methods {
println!(" {}", m.name);
}
Ok(())
}
Output
Querying serde_json::Value methods (may be slow on first run)...
serde_json::Value has 37 methods:
as_array
as_array_mut
as_bool
as_f64
as_i64
as_null
as_number
as_object
as_object_mut
as_str
as_u64
clone
clone_from
clone_into
eq
get
get_mut
index
index_mut
into
is_array
is_boolean
is_f64
is_i64
is_null
is_number
is_object
is_string
is_u64
ne
pointer
pointer_mut
sort_all_objects
take
to_owned
to_string
try_into
Querying serde_json::Map with serde + serde_json...
serde_json::Map has 34 methods:
append
clear
clone
clone_from
clone_into
contains_key
entry
eq
extend
extend_one
extend_reserve
get
get_key_value
get_mut
index
index_mut
insert
into
into_iter
into_values
is_empty
iter
iter_mut
keys
len
ne
remove
remove_entry
retain
sort_keys
to_owned
try_into
values
values_mut
Using the Builder API
The same queries using MethodQuery, the .deps() call keeps the dependency
string attached to the type it belongs to:
use rust_meth_lib::analyzer::find_rust_analyzer;
use rust_meth_lib::query::MethodQuery;
fn main() -> rust_meth_lib::error::Result<()> {
let ra_path = find_rust_analyzer()?;
let methods = MethodQuery::new("serde_json::Value")
.deps(r#"serde_json = "1.0""#)
.run(&ra_path)?;
println!("serde_json::Value has {} methods:", methods.len());
for m in &methods {
println!(" {}", m.name);
}
println!();
let map_methods = MethodQuery::new("serde_json::Map<String, serde_json::Value>")
.deps("serde = { version = \"1.0\", features = [\"derive\"] }\nserde_json = \"1.0\"")
.run(&ra_path)?;
println!("serde_json::Map has {} methods:", map_methods.len());
for m in &map_methods {
println!(" {}", m.name);
}
Ok(())
}
Output is identical to the above.