Stream: t-compiler/rust-analyzer

Topic: How to query rust-analyzer/hir database for pub declarations


Spencer Kohan (Nov 15 2020 at 19:29, on Zulip):

Hello! I heard people working on rust-analyzer are active here. Could anyone point me in the right direction for what is the best way to get the public declarations from a crate?

So far I've been combing through the source, and with trial and error I've been able to load a database using cli::load_cargo and get all the crates:

use rust_analyzer::cli::load_cargo;

fn main() -> std::io::Result<()> {
    let (host, _vfs) = load_cargo(path.as_path(), false, false).unwrap();
    let db = host.raw_database();
    let crates = Crate::all(db);
}

And it seems like crate_def_map is what I want but I can't figure out how to get a DefDatabase instance

Spencer Kohan (Nov 15 2020 at 19:39, on Zulip):

it looks like maybe I can upcast a RootDatabase to a DefDatabase, but I can't figure out how to make this work

Lukas Wirth (Nov 15 2020 at 19:47, on Zulip):

DefDatabase is just a trait implemented by the RootDatabase so you should be able to just use the functions defined on the trait on the RootDatabase instance you have there. If you have the trait imported in scope that is.

Spencer Kohan (Nov 15 2020 at 19:50, on Zulip):

Thanks, that seems to work. Maybe this is a dumb question, but what's the right way to get a CrateId from a Crate? I'm running into a private field error

Lukas Wirth (Nov 15 2020 at 19:56, on Zulip):

I believe you can't go from Crate to CrateId but instead of using Crate::all you might wanna use the SourceDb::crate_graph method in conjunction with the CrateGraph::iter method.

Lukas Wirth (Nov 15 2020 at 19:56, on Zulip):

That will give you all the crate ids, if you then want to get a Crate from said id you can query that from the database again with the id you can just index the CrateGraph with the crate id

Lukas Wirth (Nov 15 2020 at 19:57, on Zulip):

SourceDatabase is, like I believe all Database traits, also implemented for RootDatabase

Spencer Kohan (Nov 15 2020 at 20:00, on Zulip):

Ok thanks, I will try that

Spencer Kohan (Nov 15 2020 at 20:01, on Zulip):

Am I going about this the right way? I mean if my goal is to get all the public declarations for a crate, does it make sense to go through crate_def_map or is there another API/entry-point which would be better for this?

Lukas Wirth (Nov 15 2020 at 20:11, on Zulip):

I don't think so, but I also don't know the code base well enough to say this with certainty. Going through the crate_def_map should work though as you have everything you need there

Jonas Schievink [he/him] (Nov 15 2020 at 20:18, on Zulip):

You can also check out the code that builds the ImportMap from the CrateDefMap, it also looks for public items

Last update: Jul 27 2021 at 22:45UTC