JD and I have been working on a rustdoc extension that automatically links methods to method calls in the
examples/ directory of a crate. The goal is to make it easier for people reading documentation to find examples of how to use a method.
Here's what that looks like for the
By default, the UI shows a single example. The user can click "More examples" to see every instance.
The headings, e.g.
examples/returning.rs are links to the corresponding Github page for the example.
How it works
Check out the
example-analyzer repo and my rust fork for details. In short, we wrote a script that uses the rustc interface to type check every script in the
examples/ directory. We dump a JSON file of every function call mapped to
(File, Vec<Span>) pairs. Then rustdoc reads the JSON file and outputs these snippets for every method with invocations in
We're posting this here because we eventually want to merge this feature into rustdoc. We'd like to get feedback on the UI (better ways to show the examples?) and on the workflow (how to eventually get this integrated with cargo?). Here are a few concrete technical problems we encountered.
- To be able to type-check the examples, we needed a rustc invocation that included all necessary flags like extern libs. With the deprecation of
cargo build-plan, we have to hackily scrape that info from stderr by running
cargo check. What's a better way to do this?
- How do we know where to look for examples? Right now we run
cargo check --examplesto determine which files are examples, is that good enough?
- We have to serialize an identifier for methods that can be passed between the analysis and rustdoc phases. Right now we use a particular way of getting a string name of each method, but is there a more robust means of doing this? eg serializing (DefId, CrateNum) pairs or something.
Any other feedback is welcome!