Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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

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

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