Description
Currently, the examples in the Rust documentation is inconsistent in style. For instance, there are many examples that use 3 space tabs (probably accidentally), while most use 4.
How do we enforce that examples are formatted correctly? We have a few options.
Rustfmt
Use rustfmt's format_code_in_doc_comments
.
While this initially seems like a good solution, there are a couple problems:
- There are currently bugs in how this works that add additional whitespace, this is a problem with one correct solution (fixing the bugs).
- Style of doc comments matches the style of the rest of the code exactly. This would enable
use_small_heuristics = "Max"
, which is very undesirable for doc comments since shorter lines should always be preferred in doc comments.
How do we solve the second problem? I see two possible ways this can be done (by changing rust-fmt).
Add docs table to rustfmt.toml
Rustfmt could add support for alternate rustfmt settings for doc comments.
edition = "2021"
unstable_features = true
use_small_heuristics = "Max"
format_code_in_doc_comments = true
[docs]
use_small_heuristics = "Default"
Add rustfmt-docs.toml
Add an additional file that has the same format as rustfmt.toml, but applies to docs.
What if changes aren't/can't be made in Rustfmt?
There are 3 main solutions in this category.
Move docs out to their own folder with another rustfmt.toml file
This is something that could be done without additional tooling.
```rust
#![doc = include_str!("../docs/name_of_example.rs")]
```
Of course, this would be a very large change from where doc comments are written today, and it could be argued that having it separated out will make things harder to follow.
Extract docs with tooling and check against rustfmt.toml file
A tool could be made (as part of tidy) to verify docs are formatted correctly. Rust code could be parsed for doc comments, and written into temporary files in the same directory with a .rustfmt folder.
Extract docs with tooling and format with another rustfmt.toml file then overwrite
A tool could be made (as part of tidy) to autoformat doc comments. Implementation details would be similar to the previous option.
How should this be approached? I see pros and cons to all solutions, but I think it's something that definitely should be solved. Are there any approaches I missed? I tried to list all of the ones I could think of, but could have missed some.