rust-meth-lib 0.4.0

Core library for rust-meth: discover methods on Rust types via rust-analyzer.
Documentation

rust-meth-lib

Crates.io Documentation License

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-meth workflows 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.4.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-meth workflow.
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.

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

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(())
}

Caching

rust-meth-lib caches at three levels to minimize repeated work:

Cache Location What it skips
In-process Memory (Arc) Probe directory creation (~65µs)
Persistent probe $XDG_CACHE_HOME/rust-meth/probes/ Cargo resolution for third-party types (~5s)
Persistent results $XDG_CACHE_HOME/rust-meth/results/ Entire LSP session (~0.02s on hit)

Cache keys include the rust-analyzer version and rust-meth-lib version, upgrades to either automatically invalidate stale entries.

use rust_meth_lib::{
    clear_results_cache, results_cache_entries,
    clear_persistent_cache, persistent_cache_entries,
    clear_probe_cache, cache_entries,
};

// Inspect what's cached
let results = results_cache_entries();
for e in results {
    println!("{}: {} methods (ra {})", e.type_name, e.method_count, e.ra_version);
}

// Clear everything
clear_results_cache().ok();
clear_persistent_cache().ok();
clear_probe_cache();

On a warm results cache, repeated queries return in ~20ms regardless of crate size. See results_cache.rs for a full demonstration.

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.

Prerequisites

rust-analyzer must be on your PATH or installed as a rustup component:

rustup component add rust-analyzer

Clone the repo:

git clone https://github.com/saylesss88/rust-meth.git

Running the Examples

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

You can find the examples in the rust-meth-lib mdBook