Skip to content

Commit 4329b8e

Browse files
jyn514mark-i-m
authored andcommitted
Split up rustdoc page
1 parent b8065fa commit 4329b8e

File tree

3 files changed

+200
-191
lines changed

3 files changed

+200
-191
lines changed

src/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
- [Salsa](./salsa.md)
5252
- [Memory Management in Rustc](./memory.md)
5353
- [Parallel Compilation](./parallel-rustc.md)
54+
- [Rustdoc](./rustdoc-internals.md)
5455

5556
- [Part 3: Source Code Representations](./part-3-intro.md)
5657
- [Command-line arguments](./cli.md)

src/rustdoc-internals.md

Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
# Rustdoc internals
2+
3+
This page describes rustdoc's passes and modes. For an overview of rustdoc,
4+
see [`rustdoc`](./rustdoc.md).
5+
6+
## From crate to clean
7+
8+
In `core.rs` are two central items: the `DocContext` struct, and the `run_core`
9+
function. The latter is where rustdoc calls out to rustc to compile a crate to
10+
the point where rustdoc can take over. The former is a state container used
11+
when crawling through a crate to gather its documentation.
12+
13+
The main process of crate crawling is done in `clean/mod.rs` through several
14+
implementations of the `Clean` trait defined within. This is a conversion
15+
trait, which defines one method:
16+
17+
```rust,ignore
18+
pub trait Clean<T> {
19+
fn clean(&self, cx: &DocContext) -> T;
20+
}
21+
```
22+
23+
`clean/mod.rs` also defines the types for the "cleaned" AST used later on to
24+
render documentation pages. Each usually accompanies an implementation of
25+
`Clean` that takes some AST or HIR type from rustc and converts it into the
26+
appropriate "cleaned" type. "Big" items like modules or associated items may
27+
have some extra processing in its `Clean` implementation, but for the most part
28+
these impls are straightforward conversions. The "entry point" to this module
29+
is the `impl Clean<Crate> for visit_ast::RustdocVisitor`, which is called by
30+
`run_core` above.
31+
32+
You see, I actually lied a little earlier: There's another AST transformation
33+
that happens before the events in `clean/mod.rs`. In `visit_ast.rs` is the
34+
type `RustdocVisitor`, which *actually* crawls a `rustc_hir::Crate` to get the first
35+
intermediate representation, defined in `doctree.rs`. This pass is mainly to
36+
get a few intermediate wrappers around the HIR types and to process visibility
37+
and inlining. This is where `#[doc(inline)]`, `#[doc(no_inline)]`, and
38+
`#[doc(hidden)]` are processed, as well as the logic for whether a `pub use`
39+
should get the full page or a "Reexport" line in the module page.
40+
41+
The other major thing that happens in `clean/mod.rs` is the collection of doc
42+
comments and `#[doc=""]` attributes into a separate field of the Attributes
43+
struct, present on anything that gets hand-written documentation. This makes it
44+
easier to collect this documentation later in the process.
45+
46+
The primary output of this process is a `clean::Crate` with a tree of Items
47+
which describe the publicly-documentable items in the target crate.
48+
49+
### Hot potato
50+
51+
Before moving on to the next major step, a few important "passes" occur over
52+
the documentation. These do things like combine the separate "attributes" into
53+
a single string and strip leading whitespace to make the document easier on the
54+
markdown parser, or drop items that are not public or deliberately hidden with
55+
`#[doc(hidden)]`. These are all implemented in the `passes/` directory, one
56+
file per pass. By default, all of these passes are run on a crate, but the ones
57+
regarding dropping private/hidden items can be bypassed by passing
58+
`--document-private-items` to rustdoc. Note that unlike the previous set of AST
59+
transformations, the passes happen on the _cleaned_ crate.
60+
61+
(Strictly speaking, you can fine-tune the passes run and even add your own, but
62+
[we're trying to deprecate that][44136]. If you need finer-grain control over
63+
these passes, please let us know!)
64+
65+
[44136]: https://github.com/rust-lang/rust/issues/44136
66+
67+
Here is current (as of this writing) list of passes:
68+
69+
- `propagate-doc-cfg` - propagates `#[doc(cfg(...))]` to child items.
70+
- `collapse-docs` concatenates all document attributes into one document
71+
attribute. This is necessary because each line of a doc comment is given as a
72+
separate doc attribute, and this will combine them into a single string with
73+
line breaks between each attribute.
74+
- `unindent-comments` removes excess indentation on comments in order for
75+
markdown to like it. This is necessary because the convention for writing
76+
documentation is to provide a space between the `///` or `//!` marker and the
77+
text, and stripping that leading space will make the text easier to parse by
78+
the Markdown parser. (In the past, the markdown parser used was not
79+
Commonmark- compliant, which caused annoyances with extra whitespace but this
80+
seems to be less of an issue today.)
81+
- `strip-priv-imports` strips all private import statements (`use`, `extern
82+
crate`) from a crate. This is necessary because rustdoc will handle *public*
83+
imports by either inlining the item's documentation to the module or creating
84+
a "Reexports" section with the import in it. The pass ensures that all of
85+
these imports are actually relevant to documentation.
86+
- `strip-hidden` and `strip-private` strip all `doc(hidden)` and private items
87+
from the output. `strip-private` implies `strip-priv-imports`. Basically, the
88+
goal is to remove items that are not relevant for public documentation.
89+
90+
## From clean to crate
91+
92+
This is where the "second phase" in rustdoc begins. This phase primarily lives
93+
in the `html/` folder, and it all starts with `run()` in `html/render.rs`. This
94+
code is responsible for setting up the `Context`, `SharedContext`, and `Cache`
95+
which are used during rendering, copying out the static files which live in
96+
every rendered set of documentation (things like the fonts, CSS, and JavaScript
97+
that live in `html/static/`), creating the search index, and printing out the
98+
source code rendering, before beginning the process of rendering all the
99+
documentation for the crate.
100+
101+
Several functions implemented directly on `Context` take the `clean::Crate` and
102+
set up some state between rendering items or recursing on a module's child
103+
items. From here the "page rendering" begins, via an enormous `write!()` call
104+
in `html/layout.rs`. The parts that actually generate HTML from the items and
105+
documentation occurs within a series of `std::fmt::Display` implementations and
106+
functions that pass around a `&mut std::fmt::Formatter`. The top-level
107+
implementation that writes out the page body is the `impl<'a> fmt::Display for
108+
Item<'a>` in `html/render.rs`, which switches out to one of several `item_*`
109+
functions based on the kind of `Item` being rendered.
110+
111+
Depending on what kind of rendering code you're looking for, you'll probably
112+
find it either in `html/render.rs` for major items like "what sections should I
113+
print for a struct page" or `html/format.rs` for smaller component pieces like
114+
"how should I print a where clause as part of some other item".
115+
116+
Whenever rustdoc comes across an item that should print hand-written
117+
documentation alongside, it calls out to `html/markdown.rs` which interfaces
118+
with the Markdown parser. This is exposed as a series of types that wrap a
119+
string of Markdown, and implement `fmt::Display` to emit HTML text. It takes
120+
special care to enable certain features like footnotes and tables and add
121+
syntax highlighting to Rust code blocks (via `html/highlight.rs`) before
122+
running the Markdown parser. There's also a function in here
123+
(`find_testable_code`) that specifically scans for Rust code blocks so the
124+
test-runner code can find all the doctests in the crate.
125+
126+
### From soup to nuts
127+
128+
(alternate title: ["An unbroken thread that stretches from those first `Cell`s
129+
to us"][video])
130+
131+
[video]: https://www.youtube.com/watch?v=hOLAGYmUQV0
132+
133+
It's important to note that the AST cleaning can ask the compiler for
134+
information (crucially, `DocContext` contains a `TyCtxt`), but page rendering
135+
cannot. The `clean::Crate` created within `run_core` is passed outside the
136+
compiler context before being handed to `html::render::run`. This means that a
137+
lot of the "supplementary data" that isn't immediately available inside an
138+
item's definition, like which trait is the `Deref` trait used by the language,
139+
needs to be collected during cleaning, stored in the `DocContext`, and passed
140+
along to the `SharedContext` during HTML rendering. This manifests as a bunch
141+
of shared state, context variables, and `RefCell`s.
142+
143+
Also of note is that some items that come from "asking the compiler" don't go
144+
directly into the `DocContext` - for example, when loading items from a foreign
145+
crate, rustdoc will ask about trait implementations and generate new `Item`s
146+
for the impls based on that information. This goes directly into the returned
147+
`Crate` rather than roundabout through the `DocContext`. This way, these
148+
implementations can be collected alongside the others, right before rendering
149+
the HTML.
150+
151+
## Other tricks up its sleeve
152+
153+
All this describes the process for generating HTML documentation from a Rust
154+
crate, but there are couple other major modes that rustdoc runs in. It can also
155+
be run on a standalone Markdown file, or it can run doctests on Rust code or
156+
standalone Markdown files. For the former, it shortcuts straight to
157+
`html/markdown.rs`, optionally including a mode which inserts a Table of
158+
Contents to the output HTML.
159+
160+
For the latter, rustdoc runs a similar partial-compilation to get relevant
161+
documentation in `test.rs`, but instead of going through the full clean and
162+
render process, it runs a much simpler crate walk to grab *just* the
163+
hand-written documentation. Combined with the aforementioned
164+
"`find_testable_code`" in `html/markdown.rs`, it builds up a collection of
165+
tests to run before handing them off to the libtest test runner. One notable
166+
location in `test.rs` is the function `make_test`, which is where hand-written
167+
doctests get transformed into something that can be executed.
168+
169+
Some extra reading about `make_test` can be found
170+
[here](https://quietmisdreavus.net/code/2018/02/23/how-the-doctests-get-made/).
171+
172+
## Dotting i's and crossing t's
173+
174+
So that's rustdoc's code in a nutshell, but there's more things in the repo
175+
that deal with it. Since we have the full `compiletest` suite at hand, there's
176+
a set of tests in `src/test/rustdoc` that make sure the final HTML is what we
177+
expect in various situations. These tests also use a supplementary script,
178+
`src/etc/htmldocck.py`, that allows it to look through the final HTML using
179+
XPath notation to get a precise look at the output. The full description of all
180+
the commands available to rustdoc tests is in `htmldocck.py`.
181+
182+
To use multiple crates in a rustdoc test, add `// aux-build:filename.rs`
183+
to the top of the test file. `filename.rs` should be placed in an `auxiliary`
184+
directory relative to the test file with the comment. If you need to build
185+
docs for the auxiliary file, use `// build-aux-docs`.
186+
187+
In addition, there are separate tests for the search index and rustdoc's
188+
ability to query it. The files in `src/test/rustdoc-js` each contain a
189+
different search query and the expected results, broken out by search tab.
190+
These files are processed by a script in `src/tools/rustdoc-js` and the Node.js
191+
runtime. These tests don't have as thorough of a writeup, but a broad example
192+
that features results in all tabs can be found in `basic.js`. The basic idea is
193+
that you match a given `QUERY` with a set of `EXPECTED` results, complete with
194+
the full item path of each item.
195+
196+
You can run tests using the name of the folder. For example,
197+
`x.py test --stage 1 src/test/rustdoc` will run the output tests using a stage1 rustdoc.

0 commit comments

Comments
 (0)