Search code examples
rustservo

Figure out code from what module is "use"d in a large rust project (servo)


I'm trying to read the code of servo. As an example, I'm looking at this code in layout_task.rs:

use url::Url;

..and I want to know which code this refers to (the answer is rust-url).


Solution

  • Per the Rust reference §6.1.2.2 Use declarations,

    the paths contained in use items are relative to the crate root [...]

    It is also possible to use self and super at the beginning of a use item to refer to the current and direct parent modules respectively.

    All rules regarding accessing declared modules in use declarations apply to both module declarations and extern crate declarations.

    The reference (§5 Crates and source files) does not explicitly say what a "crate root" is, but it does share that:

    A crate contains a tree of nested module scopes. The top level of this tree is a module that is anonymous [...] The Rust compiler is always invoked with a single source file as input, and always produces a single output crate. The processing of that source file may result in other source files being loaded as modules.

    So it seems that to find the crate root that the current file (layout_task.rs) belongs to, we need to figure out what source file rustc is invoked with when building the crate. With Cargo this is specified in Cargo.toml and defaults to src/lib.rs:

    [lib]
    path = "src/lib.rs"
    

    In my case, here's Cargo.toml and the lib.rs has:

    extern crate url;
    pub mod layout_task;
    

    So far so good. To find out what the extern crate refers to, we need to look at Cargo.toml again:

    [dependencies.url]
    version = "0.2"
    

    The cargo docs claim that "Dependencies from crates.io are not declared with separate sections", but apparently they can be... So we look the package up on crates.io: https://crates.io/crates/url