├── .github
└── workflows
│ └── ci.yml
├── .gitignore
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── book.toml
├── english
├── README.md
├── VERSION
├── book.toml
└── src
│ ├── SUMMARY.md
│ ├── advanced-features.md
│ ├── command-line-arguments.md
│ ├── documentation-tests.md
│ ├── how-to-read-rustdoc.md
│ ├── how-to-write-documentation.md
│ ├── linking-to-items-by-name.md
│ ├── lints.md
│ ├── passes.md
│ ├── references.md
│ ├── the-doc-attribute.md
│ ├── unstable-features.md
│ ├── website-features.md
│ ├── what-is-rustdoc.md
│ └── what-to-include.md
├── language.js
└── src
├── SUMMARY.md
├── advanced-features.md
├── command-line-arguments.md
├── documentation-tests.md
├── how-to-read-rustdoc.md
├── how-to-write-documentation.md
├── linking-to-items-by-name.md
├── lints.md
├── passes.md
├── references.md
├── the-doc-attribute.md
├── unstable-features.md
├── website-features.md
├── what-is-rustdoc.md
└── what-to-include.md
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 | on: [push, pull_request]
3 |
4 | jobs:
5 | test:
6 | name: Test
7 | runs-on: ubuntu-latest
8 | steps:
9 | - uses: actions/checkout@main
10 | - name: Update rustup
11 | run: rustup self update
12 | - name: Install Rust
13 | run: |
14 | rustup set profile minimal
15 | rustup toolchain install nightly -c rust-docs
16 | rustup default nightly
17 | - name: Install mdbook
18 | run: |
19 | mkdir bin
20 | curl -sSL https://github.com/rust-lang/mdBook/releases/download/v0.4.15/mdbook-v0.4.15-x86_64-unknown-linux-gnu.tar.gz | tar -xz --directory=bin
21 | echo "$(pwd)/bin" >> ${GITHUB_PATH}
22 | echo "$(pwd)/bin" >> $GITHUB_PATH
23 | - name: Report versions
24 | run: |
25 | rustup --version
26 | rustc -Vv
27 | mdbook --version
28 | - name: Run tests
29 | run: mdbook test
30 | - name: Build HTML
31 | run: mdbook build
32 |
33 | deploy:
34 | if: ${{ github.ref == 'refs/heads/master' }}
35 | name: Deploy
36 | runs-on: ubuntu-latest
37 | needs: test
38 | steps:
39 | - name: Deploy to server
40 | uses: appleboy/ssh-action@master
41 | with:
42 | host: ${{ secrets.SSH_HOST }}
43 | username: ${{ secrets.SSH_USERNAME }}
44 | key: ${{ secrets.SSH_KEY }}
45 | port: ${{ secrets.SSH_PORT }}
46 | script: |
47 | ./tools/rust-deploy/update-cn.sh >/dev/null 2>&1
48 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | book
2 |
--------------------------------------------------------------------------------
/LICENSE-APACHE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Rust 中文翻译项目组
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # rustdoc 手册
2 |
3 | 
4 | [](https://raw.githubusercontent.com/rust-lang-cn/rustdoc-cn/master/LICENSE-MIT)
5 | [](https://raw.githubusercontent.com/rust-lang-cn/rustdoc-cn/master/LICENSE-APACHE)
6 | [](https://github.com/rust-lang-cn/rustdoc-cn/commits/master)
7 | [](https://github.com/rust-lang-cn/rustdoc-cn/graphs/contributors)
8 | 
9 | [](https://rustwiki.org)
10 |
11 | > The Chinese Translation of [The rustdoc Book][rustdoc-book-en]
12 | >
13 | > - 首次于 2022-02-04 翻译完全部内容,欢迎纠正——最后更新时间 2022-02-04。
14 | > - [David][david] 翻译完成本文档,并加入了 Rust 翻译小组群,期待更多朋友加入 [Rust 中文翻译项目组](https://github.com/rust-lang-cn),协助我们,一起更新完善中文版,感激不尽!
15 |
16 | 这是《rustdoc 手册》中文版,翻译自 [Rust 源码中的《rustdoc Book》][rustdoc-book-src]。
17 |
18 | 在线版可在本组织官网上[阅读中文版][rustdoc-book-cn](**支持同一页面中英双语切换**)或在 Rust 官网上[阅读英文版][rustdoc-book-en]。
19 |
20 | [david]: https://github.com/wendajiang
21 | [rustdoc-book-src]: https://github.com/rust-lang/rust/tree/master/src/doc/rustdoc
22 | [rustdoc-book-cn]: https://rustwiki.org/zh-CN/rustdoc/
23 | [rustdoc-book-en]: https://doc.rust-lang.org/rustdoc/
24 |
25 | ## 构建
26 |
27 | 构建之前请先安装 `mdBook` 工具。
28 |
29 | 从 GitHub 下载仓库并构建:
30 |
31 | ```sh
32 | $ git clone https://github.com/rust-lang-cn/rustdoc-cn.git
33 | $ cd rustdoc-cn
34 | $ mdbook serve
35 | ```
36 |
37 | 然后就可以在浏览器上访问 `http://localhost:3000` 来查看文档内容了。
38 |
39 | 要生成本地图书,使用以下命令:
40 |
41 | ```sh
42 | $ mdbook build
43 | ```
44 |
45 | 即可在当前仓库目录下生存一个 `book` 子目录,可找到相应的 HTML 文件。
46 |
47 | ## 许可协议
48 |
49 | 《rustdoc 手册》(中文版与英文版 *rustdoc Book* 均) 使用以下两种协议的任一种进行授权:
50 |
51 | - Apache 2.0 授权协议,([LICENSE-APACHE](LICENSE-APACHE) 或 http://www.apache.org/licenses/LICENSE-2.0)
52 | - MIT 授权协议 ([LICENSE-MIT](LICENSE-MIT) 或 http://opensource.org/licenses/MIT)
53 |
54 | 可以根据自己选择来定。
55 |
56 | 除非您有另外说明,否则您在本仓库提交的任何贡献均按上述方式进行双重许可授权,就如 Apache 2.0 协议所规定那样,而无需附加任何其他条款或条件。
57 |
--------------------------------------------------------------------------------
/book.toml:
--------------------------------------------------------------------------------
1 | [book]
2 | title = "rustdoc 手册 中文版"
3 | description = "rustdoc 手册详细介绍了如何使用 rustdoc 命令或 cargo doc 来生成漂亮的 crate 文档,发布 crate 前很有必要熟悉 rustdoc 的相关内容。"
4 | authors = ["The Rust Project Developers"]
5 | src = "src"
6 |
7 | [output.html]
8 | additional-js = ["language.js"]
9 | # English git-repository-url = "https://github.com/rust-lang/rust/tree/master/src/doc/rustdoc"
10 | git-repository-url = "https://github.com/rust-lang-cn/rustdoc-cn"
11 | edit-url-template = "https://github.com/rust-lang-cn/rustdoc-cn/edit/master/{path}"
12 |
--------------------------------------------------------------------------------
/english/README.md:
--------------------------------------------------------------------------------
1 | # Rustdoc
2 |
3 | This is documentation for rustdoc itself, written in mdbook format.
4 | To build the book, use `x.py doc src/doc/rustdoc`.
5 | To run doctests, use `x.py test src/doc/rustdoc`.
6 |
--------------------------------------------------------------------------------
/english/VERSION:
--------------------------------------------------------------------------------
1 | commit be8450eec8fa635a9132f799012fed83ba59121e
2 | Date: Wed May 19 07:25:17 2021 +0000
3 |
4 | repo: https://github.com/rust-lang/rust
5 |
--------------------------------------------------------------------------------
/english/book.toml:
--------------------------------------------------------------------------------
1 | [book]
2 | src = "src"
3 | title = "The rustdoc book"
4 |
5 | [output.html]
6 | git-repository-url = "https://github.com/rust-lang/rust/tree/master/src/doc/rustdoc"
7 |
--------------------------------------------------------------------------------
/english/src/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # The Rustdoc Book
2 |
3 | - [What is rustdoc?](what-is-rustdoc.md)
4 | - [How to read rustdoc output](how-to-read-rustdoc.md)
5 | - [How to write documentation](how-to-write-documentation.md)
6 | - [What to include (and exclude)](what-to-include.md)
7 | - [Command-line arguments](command-line-arguments.md)
8 | - [The `#[doc]` attribute](the-doc-attribute.md)
9 | - [Documentation tests](documentation-tests.md)
10 | - [Linking to items by name](linking-to-items-by-name.md)
11 | - [Lints](lints.md)
12 | - [Advanced features](advanced-features.md)
13 | - [Unstable features](unstable-features.md)
14 | - [Website features](website-features.md)
15 | - [Passes](passes.md)
16 | - [References](references.md)
17 |
--------------------------------------------------------------------------------
/english/src/advanced-features.md:
--------------------------------------------------------------------------------
1 | # Advanced features
2 |
3 | The features listed on this page fall outside the rest of the main categories.
4 |
5 | ## `#[cfg(doc)]`: Documenting platform-specific or feature-specific information
6 |
7 | For conditional compilation, Rustdoc treats your crate the same way the compiler does. Only things
8 | from the host target are available (or from the given `--target` if present), and everything else is
9 | "filtered out" from the crate. This can cause problems if your crate is providing different things
10 | on different targets and you want your documentation to reflect all the available items you
11 | provide.
12 |
13 | If you want to make sure an item is seen by Rustdoc regardless of what platform it's targeting,
14 | you can apply `#[cfg(doc)]` to it. Rustdoc sets this whenever it's building documentation, so
15 | anything that uses that flag will make it into documentation it generates. To apply this to an item
16 | with other `#[cfg]` filters on it, you can write something like `#[cfg(any(windows, doc))]`.
17 | This will preserve the item either when built normally on Windows, or when being documented
18 | anywhere.
19 |
20 | Please note that this `cfg` is not passed to doctests.
21 |
22 | Example:
23 |
24 | ```rust
25 | /// Token struct that can only be used on Windows.
26 | #[cfg(any(windows, doc))]
27 | pub struct WindowsToken;
28 | /// Token struct that can only be used on Unix.
29 | #[cfg(any(unix, doc))]
30 | pub struct UnixToken;
31 | ```
32 |
33 | Here, the respective tokens can only be used by dependent crates on their respective platforms, but
34 | they will both appear in documentation.
35 |
36 | ### Interactions between platform-specific docs
37 |
38 | Rustdoc does not have a magic way to compile documentation 'as-if' you'd run it once for each
39 | platform (such a magic wand has been called the ['holy grail of rustdoc'][#1998]). Instead,
40 | it sees *all* of your code at once, the same way the Rust compiler would if you passed it
41 | `--cfg doc`. However, Rustdoc has a trick up its sleeve to handle platform-specific code if it
42 | *does* receive it.
43 |
44 | To document your crate, Rustdoc only needs to know the public signature of your functions.
45 | In particular, it doesn't have to know how any of your functions are implemented, so it ignores
46 | all type errors and name resolution errors with function bodies. Note that this does *not*
47 | work for anything outside a function body: since Rustdoc documents your types, it has to
48 | know what those types are! For example, this code will work regardless of the platform:
49 |
50 | ```rust,ignore (platform-specific,rustdoc-specific-behavior)
51 | pub fn f() {
52 | use std::os::windows::ffi::OsStrExt;
53 | }
54 | ```
55 |
56 | but this will not, because the unknown type is part of the function signature:
57 |
58 | ```rust,ignore (platform-specific,rustdoc-specific-behavior)
59 | pub fn f() -> std::os::windows::ffi::EncodeWide<'static> {
60 | unimplemented!()
61 | }
62 | ```
63 |
64 | For a more realistic example of code this allows, see [the rustdoc test suite][realistic-async].
65 |
66 | [#1998]: https://github.com/rust-lang/rust/issues/1998
67 | [realistic-async]: https://github.com/rust-lang/rust/blob/b146000e910ccd60bdcde89363cb6aa14ecc0d95/src/test/rustdoc-ui/error-in-impl-trait/realistic-async.rs
68 |
69 | ## Add aliases for an item in documentation search
70 |
71 | This feature allows you to add alias(es) to an item when using the `rustdoc` search through the
72 | `doc(alias)` attribute. Example:
73 |
74 | ```rust,no_run
75 | #[doc(alias = "x")]
76 | #[doc(alias = "big")]
77 | pub struct BigX;
78 | ```
79 |
80 | Then, when looking for it through the `rustdoc` search, if you enter "x" or
81 | "big", search will show the `BigX` struct first.
82 |
83 | There are some limitations on the doc alias names though: you can't use `"` or whitespace.
84 |
85 | You can add multiple aliases at the same time by using a list:
86 |
87 | ```rust,no_run
88 | #[doc(alias("x", "big"))]
89 | pub struct BigX;
90 | ```
91 |
--------------------------------------------------------------------------------
/english/src/command-line-arguments.md:
--------------------------------------------------------------------------------
1 | # Command-line arguments
2 |
3 | Here's the list of arguments you can pass to `rustdoc`:
4 |
5 | ## `-h`/`--help`: help
6 |
7 | Using this flag looks like this:
8 |
9 | ```bash
10 | $ rustdoc -h
11 | $ rustdoc --help
12 | ```
13 |
14 | This will show `rustdoc`'s built-in help, which largely consists of
15 | a list of possible command-line flags.
16 |
17 | Some of `rustdoc`'s flags are unstable; this page only shows stable
18 | options, `--help` will show them all.
19 |
20 | ## `-V`/`--version`: version information
21 |
22 | Using this flag looks like this:
23 |
24 | ```bash
25 | $ rustdoc -V
26 | $ rustdoc --version
27 | ```
28 |
29 | This will show `rustdoc`'s version, which will look something
30 | like this:
31 |
32 | ```text
33 | rustdoc 1.17.0 (56124baa9 2017-04-24)
34 | ```
35 |
36 | ## `-v`/`--verbose`: more verbose output
37 |
38 | Using this flag looks like this:
39 |
40 | ```bash
41 | $ rustdoc -v src/lib.rs
42 | $ rustdoc --verbose src/lib.rs
43 | ```
44 |
45 | This enables "verbose mode", which means that more information will be written
46 | to standard out. What is written depends on the other flags you've passed in.
47 | For example, with `--version`:
48 |
49 | ```text
50 | $ rustdoc --verbose --version
51 | rustdoc 1.17.0 (56124baa9 2017-04-24)
52 | binary: rustdoc
53 | commit-hash: hash
54 | commit-date: date
55 | host: host-triple
56 | release: 1.17.0
57 | LLVM version: 3.9
58 | ```
59 |
60 | ## `-o`/`--out-dir`: output directory path
61 |
62 | Using this flag looks like this:
63 |
64 | ```bash
65 | $ rustdoc src/lib.rs -o target/doc
66 | $ rustdoc src/lib.rs --out-dir target/doc
67 | ```
68 |
69 | By default, `rustdoc`'s output appears in a directory named `doc` in
70 | the current working directory. With this flag, it will place all output
71 | into the directory you specify.
72 |
73 |
74 | ## `--crate-name`: controlling the name of the crate
75 |
76 | Using this flag looks like this:
77 |
78 | ```bash
79 | $ rustdoc src/lib.rs --crate-name mycrate
80 | ```
81 |
82 | By default, `rustdoc` assumes that the name of your crate is the same name
83 | as the `.rs` file. `--crate-name` lets you override this assumption with
84 | whatever name you choose.
85 |
86 | ## `--document-private-items`: Show items that are not public
87 |
88 | Using this flag looks like this:
89 |
90 | ```bash
91 | $ rustdoc src/lib.rs --document-private-items
92 | ```
93 |
94 | By default, `rustdoc` only documents items that are publicly reachable.
95 |
96 | ```rust
97 | pub fn public() {} // this item is public and will be documented
98 | mod private { // this item is private and will not be documented
99 | pub fn unreachable() {} // this item is public, but unreachable, so it will not be documented
100 | }
101 | ```
102 |
103 | `--document-private-items` documents all items, even if they're not public.
104 |
105 | ## `-L`/`--library-path`: where to look for dependencies
106 |
107 | Using this flag looks like this:
108 |
109 | ```bash
110 | $ rustdoc src/lib.rs -L target/debug/deps
111 | $ rustdoc src/lib.rs --library-path target/debug/deps
112 | ```
113 |
114 | If your crate has dependencies, `rustdoc` needs to know where to find them.
115 | Passing `--library-path` gives `rustdoc` a list of places to look for these
116 | dependencies.
117 |
118 | This flag takes any number of directories as its argument, and will use all of
119 | them when searching.
120 |
121 |
122 | ## `--cfg`: passing configuration flags
123 |
124 | Using this flag looks like this:
125 |
126 | ```bash
127 | $ rustdoc src/lib.rs --cfg feature="foo"
128 | ```
129 |
130 | This flag accepts the same values as `rustc --cfg`, and uses it to configure
131 | compilation. The example above uses `feature`, but any of the `cfg` values
132 | are acceptable.
133 |
134 | ## `--extern`: specify a dependency's location
135 |
136 | Using this flag looks like this:
137 |
138 | ```bash
139 | $ rustdoc src/lib.rs --extern lazy-static=/path/to/lazy-static
140 | ```
141 |
142 | Similar to `--library-path`, `--extern` is about specifying the location
143 | of a dependency. `--library-path` provides directories to search in, `--extern`
144 | instead lets you specify exactly which dependency is located where.
145 |
146 | ## `-C`/`--codegen`: pass codegen options to rustc
147 |
148 | Using this flag looks like this:
149 |
150 | ```bash
151 | $ rustdoc src/lib.rs -C target_feature=+avx
152 | $ rustdoc src/lib.rs --codegen target_feature=+avx
153 |
154 | $ rustdoc --test src/lib.rs -C target_feature=+avx
155 | $ rustdoc --test src/lib.rs --codegen target_feature=+avx
156 |
157 | $ rustdoc --test README.md -C target_feature=+avx
158 | $ rustdoc --test README.md --codegen target_feature=+avx
159 | ```
160 |
161 | When rustdoc generates documentation, looks for documentation tests, or executes documentation
162 | tests, it needs to compile some rust code, at least part-way. This flag allows you to tell rustdoc
163 | to provide some extra codegen options to rustc when it runs these compilations. Most of the time,
164 | these options won't affect a regular documentation run, but if something depends on target features
165 | to be enabled, or documentation tests need to use some additional options, this flag allows you to
166 | affect that.
167 |
168 | The arguments to this flag are the same as those for the `-C` flag on rustc. Run `rustc -C help` to
169 | get the full list.
170 |
171 | ## `--test`: run code examples as tests
172 |
173 | Using this flag looks like this:
174 |
175 | ```bash
176 | $ rustdoc src/lib.rs --test
177 | ```
178 |
179 | This flag will run your code examples as tests. For more, see [the chapter
180 | on documentation tests](documentation-tests.md).
181 |
182 | See also `--test-args`.
183 |
184 | ## `--test-args`: pass options to test runner
185 |
186 | Using this flag looks like this:
187 |
188 | ```bash
189 | $ rustdoc src/lib.rs --test --test-args ignored
190 | ```
191 |
192 | This flag will pass options to the test runner when running documentation tests.
193 | For more, see [the chapter on documentation tests](documentation-tests.md).
194 |
195 | See also `--test`.
196 |
197 | ## `--target`: generate documentation for the specified target triple
198 |
199 | Using this flag looks like this:
200 |
201 | ```bash
202 | $ rustdoc src/lib.rs --target x86_64-pc-windows-gnu
203 | ```
204 |
205 | Similar to the `--target` flag for `rustc`, this generates documentation
206 | for a target triple that's different than your host triple.
207 |
208 | All of the usual caveats of cross-compiling code apply.
209 |
210 | ## `--default-theme`: set the default theme
211 |
212 | Using this flag looks like this:
213 |
214 | ```bash
215 | $ rustdoc src/lib.rs --default-theme=ayu
216 | ```
217 |
218 | Sets the default theme (for users whose browser has not remembered a
219 | previous theme selection from the on-page theme picker).
220 |
221 | The supplied value should be the lowercase version of the theme name.
222 | The set of available themes can be seen in the theme picker in the
223 | generated output.
224 |
225 | Note that the set of available themes - and their appearance - is not
226 | necessarily stable from one rustdoc version to the next. If the
227 | requested theme does not exist, the builtin default (currently
228 | `light`) is used instead.
229 |
230 | ## `--markdown-css`: include more CSS files when rendering markdown
231 |
232 | Using this flag looks like this:
233 |
234 | ```bash
235 | $ rustdoc README.md --markdown-css foo.css
236 | ```
237 |
238 | When rendering Markdown files, this will create a `` element in the
239 | `
` section of the generated HTML. For example, with the invocation above,
240 |
241 | ```html
242 |
243 | ```
244 |
245 | will be added.
246 |
247 | When rendering Rust files, this flag is ignored.
248 |
249 | ## `--html-in-header`: include more HTML in
250 |
251 | Using this flag looks like this:
252 |
253 | ```bash
254 | $ rustdoc src/lib.rs --html-in-header header.html
255 | $ rustdoc README.md --html-in-header header.html
256 | ```
257 |
258 | This flag takes a list of files, and inserts them into the `` section of
259 | the rendered documentation.
260 |
261 | ## `--html-before-content`: include more HTML before the content
262 |
263 | Using this flag looks like this:
264 |
265 | ```bash
266 | $ rustdoc src/lib.rs --html-before-content extra.html
267 | $ rustdoc README.md --html-before-content extra.html
268 | ```
269 |
270 | This flag takes a list of files, and inserts them inside the `` tag but
271 | before the other content `rustdoc` would normally produce in the rendered
272 | documentation.
273 |
274 | ## `--html-after-content`: include more HTML after the content
275 |
276 | Using this flag looks like this:
277 |
278 | ```bash
279 | $ rustdoc src/lib.rs --html-after-content extra.html
280 | $ rustdoc README.md --html-after-content extra.html
281 | ```
282 |
283 | This flag takes a list of files, and inserts them before the `` tag but
284 | after the other content `rustdoc` would normally produce in the rendered
285 | documentation.
286 |
287 |
288 | ## `--markdown-playground-url`: control the location of the playground
289 |
290 | Using this flag looks like this:
291 |
292 | ```bash
293 | $ rustdoc README.md --markdown-playground-url https://play.rust-lang.org/
294 | ```
295 |
296 | When rendering a Markdown file, this flag gives the base URL of the Rust
297 | Playground, to use for generating `Run` buttons.
298 |
299 |
300 | ## `--markdown-no-toc`: don't generate a table of contents
301 |
302 | Using this flag looks like this:
303 |
304 | ```bash
305 | $ rustdoc README.md --markdown-no-toc
306 | ```
307 |
308 | When generating documentation from a Markdown file, by default, `rustdoc` will
309 | generate a table of contents. This flag suppresses that, and no TOC will be
310 | generated.
311 |
312 |
313 | ## `-e`/`--extend-css`: extend rustdoc's CSS
314 |
315 | Using this flag looks like this:
316 |
317 | ```bash
318 | $ rustdoc src/lib.rs -e extra.css
319 | $ rustdoc src/lib.rs --extend-css extra.css
320 | ```
321 |
322 | With this flag, the contents of the files you pass are included at the bottom
323 | of Rustdoc's `theme.css` file.
324 |
325 | While this flag is stable, the contents of `theme.css` are not, so be careful!
326 | Updates may break your theme extensions.
327 |
328 | ## `--sysroot`: override the system root
329 |
330 | Using this flag looks like this:
331 |
332 | ```bash
333 | $ rustdoc src/lib.rs --sysroot /path/to/sysroot
334 | ```
335 |
336 | Similar to `rustc --sysroot`, this lets you change the sysroot `rustdoc` uses
337 | when compiling your code.
338 |
339 | ### `--edition`: control the edition of docs and doctests
340 |
341 | Using this flag looks like this:
342 |
343 | ```bash
344 | $ rustdoc src/lib.rs --edition 2018
345 | $ rustdoc --test src/lib.rs --edition 2018
346 | ```
347 |
348 | This flag allows `rustdoc` to treat your rust code as the given edition. It will compile doctests with
349 | the given edition as well. As with `rustc`, the default edition that `rustdoc` will use is `2015`
350 | (the first edition).
351 |
352 | ## `--theme`: add a theme to the documentation output
353 |
354 | Using this flag looks like this:
355 |
356 | ```bash
357 | $ rustdoc src/lib.rs --theme /path/to/your/custom-theme.css
358 | ```
359 |
360 | `rustdoc`'s default output includes two themes: `light` (the default) and
361 | `dark`. This flag allows you to add custom themes to the output. Giving a CSS
362 | file to this flag adds it to your documentation as an additional theme choice.
363 | The theme's name is determined by its filename; a theme file named
364 | `custom-theme.css` will add a theme named `custom-theme` to the documentation.
365 |
366 | ## `--check-theme`: verify custom themes against the default theme
367 |
368 | Using this flag looks like this:
369 |
370 | ```bash
371 | $ rustdoc --check-theme /path/to/your/custom-theme.css
372 | ```
373 |
374 | While `rustdoc`'s HTML output is more-or-less consistent between versions, there
375 | is no guarantee that a theme file will have the same effect. The `--theme` flag
376 | will still allow you to add the theme to your documentation, but to ensure that
377 | your theme works as expected, you can use this flag to verify that it implements
378 | the same CSS rules as the official `light` theme.
379 |
380 | `--check-theme` is a separate mode in `rustdoc`. When `rustdoc` sees the
381 | `--check-theme` flag, it discards all other flags and only performs the CSS rule
382 | comparison operation.
383 |
384 | ### `--crate-version`: control the crate version
385 |
386 | Using this flag looks like this:
387 |
388 | ```bash
389 | $ rustdoc src/lib.rs --crate-version 1.3.37
390 | ```
391 |
392 | When `rustdoc` receives this flag, it will print an extra "Version (version)" into the sidebar of
393 | the crate root's docs. You can use this flag to differentiate between different versions of your
394 | library's documentation.
395 |
396 | ## `@path`: load command-line flags from a path
397 |
398 | If you specify `@path` on the command-line, then it will open `path` and read
399 | command line options from it. These options are one per line; a blank line indicates
400 | an empty option. The file can use Unix or Windows style line endings, and must be
401 | encoded as UTF-8.
402 |
403 | ## `--passes`: add more rustdoc passes
404 |
405 | This flag is **deprecated**.
406 | For more details on passes, see [the chapter on them](passes.md).
407 |
408 | ## `--no-defaults`: don't run default passes
409 |
410 | This flag is **deprecated**.
411 | For more details on passes, see [the chapter on them](passes.md).
412 |
413 | ## `-r`/`--input-format`: input format
414 |
415 | This flag is **deprecated** and **has no effect**.
416 |
417 | Rustdoc only supports Rust source code and Markdown input formats. If the
418 | file ends in `.md` or `.markdown`, `rustdoc` treats it as a Markdown file.
419 | Otherwise, it assumes that the input file is Rust.
420 |
421 | ## `--nocapture`
422 |
423 | When this flag is used with `--test`, the output (stdout and stderr) of your tests won't be
424 | captured by rustdoc. Instead, the output will be directed to your terminal,
425 | as if you had run the test executable manually. This is especially useful
426 | for debugging your tests!
427 |
--------------------------------------------------------------------------------
/english/src/documentation-tests.md:
--------------------------------------------------------------------------------
1 | # Documentation tests
2 |
3 | `rustdoc` supports executing your documentation examples as tests. This makes sure
4 | that examples within your documentation are up to date and working.
5 |
6 | The basic idea is this:
7 |
8 | ```rust,no_run
9 | /// # Examples
10 | ///
11 | /// ```
12 | /// let x = 5;
13 | /// ```
14 | # fn f() {}
15 | ```
16 |
17 | The triple backticks start and end code blocks. If this were in a file named `foo.rs`,
18 | running `rustdoc --test foo.rs` will extract this example, and then run it as a test.
19 |
20 | Please note that by default, if no language is set for the block code, rustdoc
21 | assumes it is Rust code. So the following:
22 |
23 | ``````markdown
24 | ```rust
25 | let x = 5;
26 | ```
27 | ``````
28 |
29 | is strictly equivalent to:
30 |
31 | ``````markdown
32 | ```
33 | let x = 5;
34 | ```
35 | ``````
36 |
37 | There's some subtlety though! Read on for more details.
38 |
39 | ## Passing or failing a doctest
40 |
41 | Like regular unit tests, regular doctests are considered to "pass"
42 | if they compile and run without panicking.
43 | So if you want to demonstrate that some computation gives a certain result,
44 | the `assert!` family of macros works the same as other Rust code:
45 |
46 | ```rust
47 | let foo = "foo";
48 | assert_eq!(foo, "foo");
49 | ```
50 |
51 | This way, if the computation ever returns something different,
52 | the code panics and the doctest fails.
53 |
54 | ## Pre-processing examples
55 |
56 | In the example above, you'll note something strange: there's no `main`
57 | function! Forcing you to write `main` for every example, no matter how small,
58 | adds friction and clutters the output. So `rustdoc` processes your examples
59 | slightly before running them. Here's the full algorithm `rustdoc` uses to
60 | preprocess examples:
61 |
62 | 1. Some common `allow` attributes are inserted, including
63 | `unused_variables`, `unused_assignments`, `unused_mut`,
64 | `unused_attributes`, and `dead_code`. Small examples often trigger
65 | these lints.
66 | 2. Any attributes specified with `#![doc(test(attr(...)))]` are added.
67 | 3. Any leading `#![foo]` attributes are left intact as crate attributes.
68 | 4. If the example does not contain `extern crate`, and
69 | `#![doc(test(no_crate_inject))]` was not specified, then `extern crate
70 | ;` is inserted (note the lack of `#[macro_use]`).
71 | 5. Finally, if the example does not contain `fn main`, the remainder of the
72 | text is wrapped in `fn main() { your_code }`.
73 |
74 | For more about that caveat in rule 4, see "Documenting Macros" below.
75 |
76 | ## Hiding portions of the example
77 |
78 | Sometimes, you need some setup code, or other things that would distract
79 | from your example, but are important to make the tests work. Consider
80 | an example block that looks like this:
81 |
82 | ```rust,no_run
83 | /// ```
84 | /// /// Some documentation.
85 | /// # fn foo() {} // this function will be hidden
86 | /// println!("Hello, World!");
87 | /// ```
88 | # fn f() {}
89 | ```
90 |
91 | It will render like this:
92 |
93 | ```rust
94 | /// Some documentation.
95 | # fn foo() {}
96 | println!("Hello, World!");
97 | ```
98 |
99 | Yes, that's right: you can add lines that start with `# `, and they will
100 | be hidden from the output, but will be used when compiling your code. You
101 | can use this to your advantage. In this case, documentation comments need
102 | to apply to some kind of function, so if I want to show you just a
103 | documentation comment, I need to add a little function definition below
104 | it. At the same time, it's only there to satisfy the compiler, so hiding
105 | it makes the example more clear. You can use this technique to explain
106 | longer examples in detail, while still preserving the testability of your
107 | documentation.
108 |
109 | For example, imagine that we wanted to document this code:
110 |
111 | ```rust
112 | let x = 5;
113 | let y = 6;
114 | println!("{}", x + y);
115 | ```
116 |
117 | We might want the documentation to end up looking like this:
118 |
119 | > First, we set `x` to five:
120 | >
121 | > ```rust
122 | > let x = 5;
123 | > # let y = 6;
124 | > # println!("{}", x + y);
125 | > ```
126 | >
127 | > Next, we set `y` to six:
128 | >
129 | > ```rust
130 | > # let x = 5;
131 | > let y = 6;
132 | > # println!("{}", x + y);
133 | > ```
134 | >
135 | > Finally, we print the sum of `x` and `y`:
136 | >
137 | > ```rust
138 | > # let x = 5;
139 | > # let y = 6;
140 | > println!("{}", x + y);
141 | > ```
142 |
143 | To keep each code block testable, we want the whole program in each block, but
144 | we don't want the reader to see every line every time. Here's what we put in
145 | our source code:
146 |
147 | ``````markdown
148 | First, we set `x` to five:
149 |
150 | ```
151 | let x = 5;
152 | # let y = 6;
153 | # println!("{}", x + y);
154 | ```
155 |
156 | Next, we set `y` to six:
157 |
158 | ```
159 | # let x = 5;
160 | let y = 6;
161 | # println!("{}", x + y);
162 | ```
163 |
164 | Finally, we print the sum of `x` and `y`:
165 |
166 | ```
167 | # let x = 5;
168 | # let y = 6;
169 | println!("{}", x + y);
170 | ```
171 | ``````
172 |
173 | By repeating all parts of the example, you can ensure that your example still
174 | compiles, while only showing the parts that are relevant to that part of your
175 | explanation.
176 |
177 | The `#`-hiding of lines can be prevented by using two consecutive hashes
178 | `##`. This only needs to be done with the first `#` which would've
179 | otherwise caused hiding. If we have a string literal like the following,
180 | which has a line that starts with a `#`:
181 |
182 | ```rust
183 | let s = "foo
184 | ## bar # baz";
185 | ```
186 |
187 | We can document it by escaping the initial `#`:
188 |
189 | ```text
190 | /// let s = "foo
191 | /// ## bar # baz";
192 | ```
193 |
194 |
195 | ## Using `?` in doc tests
196 |
197 | When writing an example, it is rarely useful to include a complete error
198 | handling, as it would add significant amounts of boilerplate code. Instead, you
199 | may want the following:
200 |
201 | ```rust,no_run
202 | /// ```
203 | /// use std::io;
204 | /// let mut input = String::new();
205 | /// io::stdin().read_line(&mut input)?;
206 | /// ```
207 | # fn f() {}
208 | ```
209 |
210 | The problem is that `?` returns a `Result` and test functions don't
211 | return anything, so this will give a mismatched types error.
212 |
213 | You can get around this limitation by manually adding a `main` that returns
214 | `Result`, because `Result` implements the `Termination` trait:
215 |
216 | ```rust,no_run
217 | /// A doc test using ?
218 | ///
219 | /// ```
220 | /// use std::io;
221 | ///
222 | /// fn main() -> io::Result<()> {
223 | /// let mut input = String::new();
224 | /// io::stdin().read_line(&mut input)?;
225 | /// Ok(())
226 | /// }
227 | /// ```
228 | # fn f() {}
229 | ```
230 |
231 | Together with the `# ` from the section above, you arrive at a solution that
232 | appears to the reader as the initial idea but works with doc tests:
233 |
234 | ```rust,no_run
235 | /// ```
236 | /// use std::io;
237 | /// # fn main() -> io::Result<()> {
238 | /// let mut input = String::new();
239 | /// io::stdin().read_line(&mut input)?;
240 | /// # Ok(())
241 | /// # }
242 | /// ```
243 | # fn f() {}
244 | ```
245 |
246 | As of version 1.34.0, one can also omit the `fn main()`, but you will have to
247 | disambiguate the error type:
248 |
249 | ```rust,no_run
250 | /// ```
251 | /// use std::io;
252 | /// let mut input = String::new();
253 | /// io::stdin().read_line(&mut input)?;
254 | /// # Ok::<(), io::Error>(())
255 | /// ```
256 | # fn f() {}
257 | ```
258 |
259 | This is an unfortunate consequence of the `?` operator adding an implicit
260 | conversion, so type inference fails because the type is not unique. Please note
261 | that you must write the `(())` in one sequence without intermediate whitespace
262 | so that `rustdoc` understands you want an implicit `Result`-returning function.
263 |
264 | ## Showing warnings in doctests
265 |
266 | You can show warnings in doctests by running `rustdoc --test --test-args=--show-output`
267 | (or, if you're using cargo, `cargo test --doc -- --show-output`).
268 | By default, this will still hide `unused` warnings, since so many examples use private functions;
269 | you can add `#![warn(unused)]` to the top of your example if you want to see unused variables or dead code warnings.
270 | You can also use [`#![doc(test(attr(warn(unused))))]`][test-attr] in the crate root to enable warnings globally.
271 |
272 | [test-attr]: ./the-doc-attribute.md#testattr
273 |
274 | ## Documenting macros
275 |
276 | Here’s an example of documenting a macro:
277 |
278 | ```rust
279 | /// Panic with a given message unless an expression evaluates to true.
280 | ///
281 | /// # Examples
282 | ///
283 | /// ```
284 | /// # #[macro_use] extern crate foo;
285 | /// # fn main() {
286 | /// panic_unless!(1 + 1 == 2, “Math is broken.”);
287 | /// # }
288 | /// ```
289 | ///
290 | /// ```should_panic
291 | /// # #[macro_use] extern crate foo;
292 | /// # fn main() {
293 | /// panic_unless!(true == false, “I’m broken.”);
294 | /// # }
295 | /// ```
296 | #[macro_export]
297 | macro_rules! panic_unless {
298 | ($condition:expr, $($rest:expr),+) => ({ if ! $condition { panic!($($rest),+); } });
299 | }
300 | # fn main() {}
301 | ```
302 |
303 | You’ll note three things: we need to add our own `extern crate` line, so that
304 | we can add the `#[macro_use]` attribute. Second, we’ll need to add our own
305 | `main()` as well (for reasons discussed above). Finally, a judicious use of
306 | `#` to comment out those two things, so they don’t show up in the output.
307 |
308 | ## Attributes
309 |
310 | Code blocks can be annotated with attributes that help `rustdoc` do the right
311 | thing when testing your code:
312 |
313 | The `ignore` attribute tells Rust to ignore your code. This is almost never
314 | what you want as it's the most generic. Instead, consider annotating it
315 | with `text` if it's not code or using `#`s to get a working example that
316 | only shows the part you care about.
317 |
318 | ```rust
319 | /// ```ignore
320 | /// fn foo() {
321 | /// ```
322 | # fn foo() {}
323 | ```
324 |
325 | `should_panic` tells `rustdoc` that the code should compile correctly but
326 | panic during execution. If the code doesn't panic, the test will fail.
327 |
328 | ```rust
329 | /// ```should_panic
330 | /// assert!(false);
331 | /// ```
332 | # fn foo() {}
333 | ```
334 |
335 | The `no_run` attribute will compile your code but not run it. This is
336 | important for examples such as "Here's how to retrieve a web page,"
337 | which you would want to ensure compiles, but might be run in a test
338 | environment that has no network access. This attribute can also be
339 | used to demonstrate code snippets that can cause Undefined Behavior.
340 |
341 | ```rust
342 | /// ```no_run
343 | /// loop {
344 | /// println!("Hello, world");
345 | /// }
346 | /// ```
347 | # fn foo() {}
348 | ```
349 |
350 | `compile_fail` tells `rustdoc` that the compilation should fail. If it
351 | compiles, then the test will fail. However, please note that code failing
352 | with the current Rust release may work in a future release, as new features
353 | are added.
354 |
355 | ```rust
356 | /// ```compile_fail
357 | /// let x = 5;
358 | /// x += 2; // shouldn't compile!
359 | /// ```
360 | # fn foo() {}
361 | ```
362 |
363 | `edition2015`, `edition2018` and `edition2021` tell `rustdoc`
364 | that the code sample should be compiled using the respective edition of Rust.
365 |
366 | ```rust
367 | /// Only runs on the 2018 edition.
368 | ///
369 | /// ```edition2018
370 | /// let result: Result = try {
371 | /// "1".parse::()?
372 | /// + "2".parse::()?
373 | /// + "3".parse::()?
374 | /// };
375 | /// ```
376 | # fn foo() {}
377 | ```
378 |
379 | ## Syntax reference
380 |
381 | The *exact* syntax for code blocks, including the edge cases, can be found
382 | in the [Fenced Code Blocks](https://spec.commonmark.org/0.29/#fenced-code-blocks)
383 | section of the CommonMark specification.
384 |
385 | Rustdoc also accepts *indented* code blocks as an alternative to fenced
386 | code blocks: instead of surrounding your code with three backticks, you
387 | can indent each line by four or more spaces.
388 |
389 | ``````markdown
390 | let foo = "foo";
391 | assert_eq!(foo, "foo");
392 | ``````
393 |
394 | These, too, are documented in the CommonMark specification, in the
395 | [Indented Code Blocks](https://spec.commonmark.org/0.29/#indented-code-blocks)
396 | section.
397 |
398 | However, it's preferable to use fenced code blocks over indented code blocks.
399 | Not only are fenced code blocks considered more idiomatic for Rust code,
400 | but there is no way to use attributes such as `ignore` or `should_panic` with
401 | indented code blocks.
402 |
403 | ### Include items only when collecting doctests
404 |
405 | Rustdoc's documentation tests can do some things that regular unit tests can't, so it can
406 | sometimes be useful to extend your doctests with samples that wouldn't otherwise need to be in
407 | documentation. To this end, Rustdoc allows you to have certain items only appear when it's
408 | collecting doctests, so you can utilize doctest functionality without forcing the test to appear in
409 | docs, or to find an arbitrary private item to include it on.
410 |
411 | When compiling a crate for use in doctests (with `--test` option), `rustdoc` will set `#[cfg(doctest)]`.
412 | Note that they will still link against only the public items of your crate; if you need to test
413 | private items, you need to write a unit test.
414 |
415 | In this example, we're adding doctests that we know won't compile, to verify that our struct can
416 | only take in valid data:
417 |
418 | ```rust
419 | /// We have a struct here. Remember it doesn't accept negative numbers!
420 | pub struct MyStruct(pub usize);
421 |
422 | /// ```compile_fail
423 | /// let x = my_crate::MyStruct(-5);
424 | /// ```
425 | #[cfg(doctest)]
426 | pub struct MyStructOnlyTakesUsize;
427 | ```
428 |
429 | Note that the struct `MyStructOnlyTakesUsize` here isn't actually part of your public crate
430 | API. The use of `#[cfg(doctest)]` makes sure that this struct only exists while `rustdoc` is
431 | collecting doctests. This means that its doctest is executed when `--test` is passed to rustdoc,
432 | but is hidden from the public documentation.
433 |
434 | Another possible use of `#[cfg(doctest)]` is to test doctests that are included in your README file
435 | without including it in your main documentation. For example, you could write this into your
436 | `lib.rs` to test your README as part of your doctests:
437 |
438 | ```rust,no_run
439 | #[doc = include_str!("../README.md")]
440 | #[cfg(doctest)]
441 | pub struct ReadmeDoctests;
442 | ```
443 |
444 | This will include your README as documentation on the hidden struct `ReadmeDoctests`, which will
445 | then be tested alongside the rest of your doctests.
446 |
--------------------------------------------------------------------------------
/english/src/how-to-read-rustdoc.md:
--------------------------------------------------------------------------------
1 | # How to read rustdoc output
2 |
3 | Rustdoc's HTML output includes a friendly and useful navigation interface which
4 | makes it easier for users to navigate and understand your code.
5 | This chapter covers the major features of that interface,
6 | and is a great starting point for documentation authors and users alike.
7 |
8 | ## Structure
9 |
10 | The `rustdoc` output is divided into three sections.
11 | Along the left side of each page is a quick navigation bar,
12 | which shows contextual information about the current entry.
13 | The rest of the page is taken up by the search interface at the top
14 | and the documentation for the current item below that.
15 |
16 | ## The Item Documentation
17 |
18 | The majority of the screen is taken up with the documentation text for the item
19 | currently being viewed.
20 | At the top is some at-a-glance info and controls:
21 |
22 | - the type and name of the item,
23 | such as "Struct `std::time::Duration`",
24 | - a button to copy the item's path to the clipboard,
25 | which is a clipboard item
26 | - a button to collapse or expand the top-level documentation for that item
27 | (`[+]` or `[-]`),
28 | - a link to the source code (`[src]`),
29 | if [configured](the-doc-attribute.html#html_no_source),
30 | and present (the source may not be available if
31 | the documentation was created with `cargo doc --no-deps`),
32 | - and the version in which the item became stable,
33 | if it's a stable item in the standard library.
34 |
35 | Below this is the main documentation for the item,
36 | including a definition or function signature if appropriate,
37 | followed by a list of fields or variants for Rust types.
38 | Finally, the page lists associated functions and trait implementations,
39 | including automatic and blanket implementations that `rustdoc` knows about.
40 |
41 | ### Navigation
42 |
43 | Subheadings, variants, fields, and many other things in this documentation
44 | are anchors and can be clicked on and deep-linked to,
45 | which is a great way to communicate exactly what you're talking about.
46 | The typograpical character "§" appears next to lines with anchors on them
47 | when hovered or given keyboard focus.
48 |
49 | ## The Navigation Bar
50 |
51 | For example, when looking at documentation for the crate root,
52 | it shows all the crates documented in the documentation bundle,
53 | and quick links to the modules, structs, traits, functions, and macros available
54 | from the current crate.
55 | At the top, it displays a [configurable logo](the-doc-attribute.html#html_logo_url)
56 | alongside the current crate's name and version,
57 | or the current item whose documentation is being displayed.
58 |
59 | ## The Theme Picker and Search Interface
60 |
61 | When viewing `rustdoc`'s output in a browser with JavaScript enabled,
62 | a dynamic interface appears at the top of the page.
63 | To the left is the theme picker, denoted with a paint-brush icon,
64 | and the search interface, help screen, and options appear to the right of that.
65 |
66 | ### The Theme Picker
67 |
68 | Clicking on the theme picker provides a list of themes -
69 | by default `ayu`, `light`, and `dark` -
70 | which are available for viewing.
71 |
72 | ### The Search Interface
73 |
74 | Typing in the search bar instantly searches the available documentation for
75 | the string entered with a fuzzy matching algorithm that is tolerant of minor
76 | typos.
77 |
78 | By default, the search results give are "In Names",
79 | meaning that the fuzzy match is made against the names of items.
80 | Matching names are shown on the left, and the first few words of their
81 | descriptions are given on the right.
82 | By clicking an item, you will navigate to its particular documentation.
83 |
84 | There are two other sets of results, shown as tabs in the search results pane.
85 | "In Parameters" shows matches for the string in the types of parameters to
86 | functions, and "In Return Types" shows matches in the return types of functions.
87 | Both are very useful when looking for a function whose name you can't quite
88 | bring to mind when you know the type you have or want.
89 |
90 | When typing in the search bar, you can prefix your search term with a type
91 | followed by a colon (such as `mod:`) to restrict the results to just that
92 | kind of item. (The available items are listed in the help popup.)
93 |
94 | ### Shortcuts
95 |
96 | Pressing `S` while focused elsewhere on the page will move focus to the
97 | search bar, and pressing `?` shows the help screen,
98 | which includes all these shortcuts and more.
99 | Pressing `T` focuses the theme picker.
100 |
101 | When the search results are focused,
102 | the left and right arrows move between tabs and the up and down arrows move
103 | among the results.
104 | Pressing the enter or return key opens the highlighted result.
105 |
106 | When looking at the documentation for an item, the plus and minus keys expand
107 | and collapse all sections in the document.
108 |
--------------------------------------------------------------------------------
/english/src/how-to-write-documentation.md:
--------------------------------------------------------------------------------
1 | # How to write documentation
2 |
3 | Good documentation is not natural. There are opposing goals that make writing
4 | good documentation difficult. It requires expertise in the subject but also
5 | writing to a novice perspective. Documentation therefore often glazes over
6 | implementation detail, or leaves readers with unanswered questions.
7 |
8 | There are a few tenets to Rust documentation that can help guide anyone through
9 | the process of documenting libraries so that everyone has an ample opportunity
10 | to use the code.
11 |
12 | This chapter covers not only how to write documentation but specifically
13 | how to write **good** documentation. It is important to be as clear
14 | as you can, and as complete as possible. As a rule of thumb: the more
15 | documentation you write for your crate the better. If an item is public
16 | then it should be documented.
17 |
18 | ## Getting Started
19 |
20 | Documenting a crate should begin with front-page documentation. As an
21 | example, the [`hashbrown`] crate level documentation summarizes the role of
22 | the crate, provides links to explain technical details, and explains why you
23 | would want to use the crate.
24 |
25 | After introducing the crate, it is important that the front-page gives
26 | an example of how to use the crate in a real world setting. Stick to the
27 | library's role in the example, but do so without shortcuts to benefit users who
28 | may copy and paste the example to get started.
29 |
30 | [`futures`] uses inline comments to explain line by line
31 | the complexities of using a [`Future`], because a person's first exposure to
32 | rust's [`Future`] may be this example.
33 |
34 | The [`backtrace`] documentation walks through the whole process, explaining
35 | changes made to the `Cargo.toml` file, passing command line arguments to the
36 | compiler, and shows a quick example of backtrace in the wild.
37 |
38 | Finally, the front-page can eventually become a comprehensive reference
39 | how to use a crate, like [`regex`]. In this front page, all
40 | requirements are outlined, the edge cases shown, and practical examples
41 | provided. The front page goes on to show how to use regular expressions
42 | then concludes with crate features.
43 |
44 | Don't worry about comparing your crate, which is just beginning, to other more
45 | developed crates. To get the documentation to something more polished, start
46 | incrementally and put in an introduction, example, and features. Rome was not
47 | built in a day!
48 |
49 | The first lines within the `lib.rs` will compose the front-page, and they
50 | use a different convention than the rest of the rustdocs. Lines should
51 | start with `//!` which indicate module-level or crate-level documentation.
52 | Here's a quick example of the difference:
53 |
54 | ```rust,no_run
55 | //! Fast and easy queue abstraction.
56 | //!
57 | //! Provides an abstraction over a queue. When the abstraction is used
58 | //! there are these advantages:
59 | //! - Fast
60 | //! - [`Easy`]
61 | //!
62 | //! [`Easy`]: http://thatwaseasy.example.com
63 |
64 | /// This module makes it easy.
65 | pub mod easy {
66 |
67 | /// Use the abstraction function to do this specific thing.
68 | pub fn abstraction() {}
69 |
70 | }
71 | ```
72 |
73 | Ideally, this first line of documentation is a sentence without highly
74 | technical details, but with a good description of where this crate fits
75 | within the rust ecosystem. Users should know whether this crate meets their use
76 | case after reading this line.
77 |
78 | ## Documenting components
79 |
80 | Whether it is modules, structs, functions, or macros: the public
81 | API of all code should have documentation. Rarely does anyone
82 | complain about too much documentation!
83 |
84 | It is recommended that each item's documentation follows this basic structure:
85 |
86 | ```text
87 | [short sentence explaining what it is]
88 |
89 | [more detailed explanation]
90 |
91 | [at least one code example that users can copy/paste to try it]
92 |
93 | [even more advanced explanations if necessary]
94 | ```
95 |
96 | This basic structure should be straightforward to follow when writing your
97 | documentation; while you might think that a code example is trivial,
98 | the examples are really important because they can help users understand
99 | what an item is, how it is used, and for what purpose it exists.
100 |
101 | Let's see an example coming from the [standard library] by taking a look at the
102 | [`std::env::args()`][env::args] function:
103 |
104 | ``````markdown
105 | Returns the arguments which this program was started with (normally passed
106 | via the command line).
107 |
108 | The first element is traditionally the path of the executable, but it can be
109 | set to arbitrary text, and may not even exist. This means this property should
110 | not be relied upon for security purposes.
111 |
112 | On Unix systems shell usually expands unquoted arguments with glob patterns
113 | (such as `*` and `?`). On Windows this is not done, and such arguments are
114 | passed as-is.
115 |
116 | # Panics
117 |
118 | The returned iterator will panic during iteration if any argument to the
119 | process is not valid unicode. If this is not desired,
120 | use the [`args_os`] function instead.
121 |
122 | # Examples
123 |
124 | ```
125 | use std::env;
126 |
127 | // Prints each argument on a separate line
128 | for argument in env::args() {
129 | println!("{}", argument);
130 | }
131 | ```
132 |
133 | [`args_os`]: ./fn.args_os.html
134 | ``````
135 |
136 | Everything before the first empty line will be reused to describe the component
137 | in searches and module overviews. For example, the function `std::env::args()`
138 | above will be shown on the [`std::env`] module documentation. It is good
139 | practice to keep the summary to one line: concise writing is a goal of good
140 | documentation.
141 |
142 | Because the type system does a good job of defining what types a function
143 | passes and returns, there is no benefit of explicitly writing it
144 | into the documentation, especially since `rustdoc` adds hyper links to all types in the function signature.
145 |
146 | In the example above, a 'Panics' section explains when the code might abruptly exit,
147 | which can help the reader prevent reaching a panic. A panic section is recommended
148 | every time edge cases in your code can be reached if known.
149 |
150 | As you can see, it follows the structure detailed above: it starts with a short
151 | sentence explaining what the functions does, then it provides more information
152 | and finally provides a code example.
153 |
154 | ## Markdown
155 |
156 | `rustdoc` uses the [CommonMark Markdown specification]. You might be
157 | interested in taking a look at their website to see what's possible:
158 |
159 | - [CommonMark quick reference]
160 | - [current spec]
161 |
162 | In addition to the standard CommonMark syntax, `rustdoc` supports several
163 | extensions:
164 |
165 | ### Strikethrough
166 |
167 | Text may be rendered with a horizontal line through the center by wrapping the
168 | text with two tilde characters on each side:
169 |
170 | ```text
171 | An example of ~~strikethrough text~~.
172 | ```
173 |
174 | This example will render as:
175 |
176 | > An example of ~~strikethrough text~~.
177 |
178 | This follows the [GitHub Strikethrough extension][strikethrough].
179 |
180 | ### Footnotes
181 |
182 | A footnote generates a small numbered link in the text which when clicked
183 | takes the reader to the footnote text at the bottom of the item. The footnote
184 | label is written similarly to a link reference with a caret at the front. The
185 | footnote text is written like a link reference definition, with the text
186 | following the label. Example:
187 |
188 | ```text
189 | This is an example of a footnote[^note].
190 |
191 | [^note]: This text is the contents of the footnote, which will be rendered
192 | towards the bottom.
193 | ```
194 |
195 | This example will render as:
196 |
197 | > This is an example of a footnote[^note].
198 | >
199 | > [^note]: This text is the contents of the footnote, which will be rendered
200 | > towards the bottom.
201 |
202 | The footnotes are automatically numbered based on the order the footnotes are
203 | written.
204 |
205 | ### Tables
206 |
207 | Tables can be written using pipes and dashes to draw the rows and columns of
208 | the table. These will be translated to HTML table matching the shape. Example:
209 |
210 | ```text
211 | | Header1 | Header2 |
212 | |---------|---------|
213 | | abc | def |
214 | ```
215 |
216 | This example will render similarly to this:
217 |
218 | > | Header1 | Header2 |
219 | > |---------|---------|
220 | > | abc | def |
221 |
222 | See the specification for the [GitHub Tables extension][tables] for more
223 | details on the exact syntax supported.
224 |
225 | ### Task lists
226 |
227 | Task lists can be used as a checklist of items that have been completed.
228 | Example:
229 |
230 | ```md
231 | - [x] Complete task
232 | - [ ] Incomplete task
233 | ```
234 |
235 | This will render as:
236 |
237 | > - [x] Complete task
238 | > - [ ] Incomplete task
239 |
240 | See the specification for the [task list extension] for more details.
241 |
242 | ### Smart punctuation
243 |
244 | Some ASCII punctuation sequences will be automatically turned into fancy Unicode
245 | characters:
246 |
247 | | ASCII sequence | Unicode |
248 | |----------------|---------|
249 | | `--` | – |
250 | | `---` | — |
251 | | `...` | … |
252 | | `"` | “ or ”, depending on context |
253 | | `'` | ‘ or ’, depending on context |
254 |
255 | So, no need to manually enter those Unicode characters!
256 |
257 | [`backtrace`]: https://docs.rs/backtrace/0.3.50/backtrace/
258 | [commonmark markdown specification]: https://commonmark.org/
259 | [commonmark quick reference]: https://commonmark.org/help/
260 | [env::args]: https://doc.rust-lang.org/stable/std/env/fn.args.html
261 | [`Future`]: https://doc.rust-lang.org/std/future/trait.Future.html
262 | [`futures`]: https://docs.rs/futures/0.3.5/futures/
263 | [`hashbrown`]: https://docs.rs/hashbrown/0.8.2/hashbrown/
264 | [`regex`]: https://docs.rs/regex/1.3.9/regex/
265 | [standard library]: https://doc.rust-lang.org/stable/std/index.html
266 | [current spec]: https://spec.commonmark.org/current/
267 | [`std::env`]: https://doc.rust-lang.org/stable/std/env/index.html#functions
268 | [strikethrough]: https://github.github.com/gfm/#strikethrough-extension-
269 | [tables]: https://github.github.com/gfm/#tables-extension-
270 | [task list extension]: https://github.github.com/gfm/#task-list-items-extension-
271 |
--------------------------------------------------------------------------------
/english/src/linking-to-items-by-name.md:
--------------------------------------------------------------------------------
1 | # Linking to items by name
2 |
3 | Rustdoc is capable of directly linking to other rustdoc pages using the path of
4 | the item as a link. This is referred to as an 'intra-doc link'.
5 |
6 | For example, in the following code all of the links will link to the rustdoc page for `Bar`:
7 |
8 | ```rust
9 | /// This struct is not [Bar]
10 | pub struct Foo1;
11 |
12 | /// This struct is also not [bar](Bar)
13 | pub struct Foo2;
14 |
15 | /// This struct is also not [bar][b]
16 | ///
17 | /// [b]: Bar
18 | pub struct Foo3;
19 |
20 | /// This struct is also not [`Bar`]
21 | pub struct Foo4;
22 |
23 | /// This struct *is* [`Bar`]!
24 | pub struct Bar;
25 | ```
26 |
27 | Unlike normal Markdown, `[bar][Bar]` syntax is also supported without needing a
28 | `[Bar]: ...` reference link.
29 |
30 | Backticks around the link will be stripped, so ``[`Option`]`` will correctly
31 | link to `Option`.
32 |
33 | ## Valid links
34 |
35 | You can refer to anything in scope, and use paths, including `Self`, `self`, `super`, and
36 | `crate`. Associated items (functions, types, and constants) are supported, but [not for blanket
37 | trait implementations][#79682]. Rustdoc also supports linking to all primitives listed in
38 | [the standard library documentation](../std/index.html#primitives).
39 |
40 | [#79682]: https://github.com/rust-lang/rust/pull/79682
41 |
42 | You can also refer to items with generic parameters like `Vec`. The link will
43 | resolve as if you had written ``[`Vec`](Vec)``. Fully-qualified syntax (for example,
44 | `::into_iter()`) is [not yet supported][fqs-issue], however.
45 |
46 | [fqs-issue]: https://github.com/rust-lang/rust/issues/74563
47 |
48 | ```rust,edition2018
49 | use std::sync::mpsc::Receiver;
50 |
51 | /// This is a version of [`Receiver`] with support for [`std::future`].
52 | ///
53 | /// You can obtain a [`std::future::Future`] by calling [`Self::recv()`].
54 | pub struct AsyncReceiver {
55 | sender: Receiver
56 | }
57 |
58 | impl AsyncReceiver {
59 | pub async fn recv() -> T {
60 | unimplemented!()
61 | }
62 | }
63 | ```
64 |
65 | Rustdoc allows using URL fragment specifiers, just like a normal link:
66 |
67 | ```rust
68 | /// This is a special implementation of [positional parameters].
69 | ///
70 | /// [positional parameters]: std::fmt#formatting-parameters
71 | struct MySpecialFormatter;
72 | ```
73 |
74 | ## Namespaces and Disambiguators
75 |
76 | Paths in Rust have three namespaces: type, value, and macro. Item names must be unique within
77 | their namespace, but can overlap with items in other namespaces. In case of ambiguity,
78 | rustdoc will warn about the ambiguity and suggest a disambiguator.
79 |
80 | ```rust
81 | /// See also: [`Foo`](struct@Foo)
82 | struct Bar;
83 |
84 | /// This is different from [`Foo`](fn@Foo)
85 | struct Foo {}
86 |
87 | fn Foo() {}
88 | ```
89 |
90 | These prefixes will be stripped when displayed in the documentation, so `[struct@Foo]` will be
91 | rendered as `Foo`.
92 |
93 | You can also disambiguate for functions by adding `()` after the function name,
94 | or for macros by adding `!` after the macro name:
95 |
96 | ```rust
97 | /// This is different from [`foo!`]
98 | fn foo() {}
99 |
100 | /// This is different from [`foo()`]
101 | macro_rules! foo {
102 | () => {}
103 | }
104 | ```
105 |
106 | ## Warnings, re-exports, and scoping
107 |
108 | Links are resolved in the scope of the module where the item is defined, even
109 | when the item is re-exported. If a link from another crate fails to resolve, no
110 | warning is given.
111 |
112 | ```rust,edition2018
113 | mod inner {
114 | /// Link to [f()]
115 | pub struct S;
116 | pub fn f() {}
117 | }
118 | pub use inner::S; // the link to `f` will still resolve correctly
119 | ```
120 |
121 | When re-exporting an item, rustdoc allows adding additional documentation to it.
122 | That additional documentation will be resolved in the scope of the re-export, not
123 | the original, allowing you to link to items in the new crate. The new links
124 | will still give a warning if they fail to resolve.
125 |
126 | ```rust
127 | /// See also [foo()]
128 | pub use std::process::Command;
129 |
130 | pub fn foo() {}
131 | ```
132 |
133 | This is especially useful for proc-macros, which must always be defined in their own dedicated crate.
134 |
135 | Note: Because of how `macro_rules!` macros are scoped in Rust, the intra-doc links of a
136 | `macro_rules!` macro will be resolved [relative to the crate root][#72243], as opposed to the
137 | module it is defined in.
138 |
139 | If links do not look 'sufficiently like' an intra-doc link, they will be ignored and no warning
140 | will be given, even if the link fails to resolve. For example, any link containing `/` or `[]`
141 | characters will be ignored.
142 |
143 | [#72243]: https://github.com/rust-lang/rust/issues/72243
144 |
--------------------------------------------------------------------------------
/english/src/lints.md:
--------------------------------------------------------------------------------
1 | # Lints
2 |
3 | `rustdoc` provides lints to help you writing and testing your documentation. You
4 | can use them like any other lints by doing this:
5 |
6 | ```rust
7 | #![allow(rustdoc::broken_intra_doc_links)] // allows the lint, no diagnostics will be reported
8 | #![warn(rustdoc::broken_intra_doc_links)] // warn if there are broken intra-doc links
9 | #![deny(rustdoc::broken_intra_doc_links)] // error if there are broken intra-doc links
10 | ```
11 |
12 | Note that, except for `missing_docs`, these lints are only available when running `rustdoc`, not `rustc`.
13 |
14 | Here is the list of the lints provided by `rustdoc`:
15 |
16 | ## broken_intra_doc_links
17 |
18 | This lint **warns by default**. This lint detects when an [intra-doc link] fails to be resolved. For example:
19 |
20 | [intra-doc link]: linking-to-items-by-name.md
21 |
22 | ```rust
23 | /// I want to link to [`Nonexistent`] but it doesn't exist!
24 | pub fn foo() {}
25 | ```
26 |
27 | You'll get a warning saying:
28 |
29 | ```text
30 | warning: unresolved link to `Nonexistent`
31 | --> test.rs:1:24
32 | |
33 | 1 | /// I want to link to [`Nonexistent`] but it doesn't exist!
34 | | ^^^^^^^^^^^^^ no item named `Nonexistent` in `test`
35 | ```
36 |
37 | It will also warn when there is an ambiguity and suggest how to disambiguate:
38 |
39 | ```rust
40 | /// [`Foo`]
41 | pub fn function() {}
42 |
43 | pub enum Foo {}
44 |
45 | pub fn Foo(){}
46 | ```
47 |
48 | ```text
49 | warning: `Foo` is both an enum and a function
50 | --> test.rs:1:6
51 | |
52 | 1 | /// [`Foo`]
53 | | ^^^^^ ambiguous link
54 | |
55 | = note: `#[warn(rustdoc::broken_intra_doc_links)]` on by default
56 | help: to link to the enum, prefix with the item type
57 | |
58 | 1 | /// [`enum@Foo`]
59 | | ^^^^^^^^^^
60 | help: to link to the function, add parentheses
61 | |
62 | 1 | /// [`Foo()`]
63 | | ^^^^^^^
64 |
65 | ```
66 |
67 | ## private_intra_doc_links
68 |
69 | This lint **warns by default**. This lint detects when [intra-doc links] from public to private items.
70 | For example:
71 |
72 | ```rust
73 | #![warn(rustdoc::private_intra_doc_links)] // note: unnecessary - warns by default.
74 |
75 | /// [private]
76 | pub fn public() {}
77 | fn private() {}
78 | ```
79 |
80 | This gives a warning that the link will be broken when it appears in your documentation:
81 |
82 | ```text
83 | warning: public documentation for `public` links to private item `private`
84 | --> priv.rs:1:6
85 | |
86 | 1 | /// [private]
87 | | ^^^^^^^ this item is private
88 | |
89 | = note: `#[warn(rustdoc::private_intra_doc_links)]` on by default
90 | = note: this link will resolve properly if you pass `--document-private-items`
91 | ```
92 |
93 | Note that this has different behavior depending on whether you pass `--document-private-items` or not!
94 | If you document private items, then it will still generate a link, despite the warning:
95 |
96 | ```text
97 | warning: public documentation for `public` links to private item `private`
98 | --> priv.rs:1:6
99 | |
100 | 1 | /// [private]
101 | | ^^^^^^^ this item is private
102 | |
103 | = note: `#[warn(rustdoc::private_intra_doc_links)]` on by default
104 | = note: this link resolves only because you passed `--document-private-items`, but will break without
105 | ```
106 |
107 | [intra-doc links]: linking-to-items-by-name.html
108 |
109 | ## missing_docs
110 |
111 | This lint is **allowed by default**. It detects items missing documentation.
112 | For example:
113 |
114 | ```rust
115 | #![warn(missing_docs)]
116 |
117 | pub fn undocumented() {}
118 | # fn main() {}
119 | ```
120 |
121 | The `undocumented` function will then have the following warning:
122 |
123 | ```text
124 | warning: missing documentation for a function
125 | --> your-crate/lib.rs:3:1
126 | |
127 | 3 | pub fn undocumented() {}
128 | | ^^^^^^^^^^^^^^^^^^^^^
129 | ```
130 |
131 | Note that unlike other rustdoc lints, this lint is also available from `rustc` directly.
132 |
133 | ## missing_crate_level_docs
134 |
135 | This lint is **allowed by default**. It detects if there is no documentation
136 | at the crate root. For example:
137 |
138 | ```rust
139 | #![warn(rustdoc::missing_crate_level_docs)]
140 | ```
141 |
142 | This will generate the following warning:
143 |
144 | ```text
145 | warning: no documentation found for this crate's top-level module
146 | |
147 | = help: The following guide may be of use:
148 | https://doc.rust-lang.org/nightly/rustdoc/how-to-write-documentation.html
149 | ```
150 |
151 | This is currently "allow" by default, but it is intended to make this a
152 | warning in the future. This is intended as a means to introduce new users on
153 | *how* to document their crate by pointing them to some instructions on how to
154 | get started, without providing overwhelming warnings like `missing_docs`
155 | might.
156 |
157 | ## missing_doc_code_examples
158 |
159 | This lint is **allowed by default** and is **nightly-only**. It detects when a documentation block
160 | is missing a code example. For example:
161 |
162 | ```rust
163 | #![warn(rustdoc::missing_doc_code_examples)]
164 |
165 | /// There is no code example!
166 | pub fn no_code_example() {}
167 | # fn main() {}
168 | ```
169 |
170 | The `no_code_example` function will then have the following warning:
171 |
172 | ```text
173 | warning: Missing code example in this documentation
174 | --> your-crate/lib.rs:3:1
175 | |
176 | LL | /// There is no code example!
177 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
178 | ```
179 |
180 | To fix the lint, you need to add a code example into the documentation block:
181 |
182 | ```rust
183 | /// There is no code example!
184 | ///
185 | /// ```
186 | /// println!("calling no_code_example...");
187 | /// no_code_example();
188 | /// println!("we called no_code_example!");
189 | /// ```
190 | pub fn no_code_example() {}
191 | ```
192 |
193 | ## private_doc_tests
194 |
195 | This lint is **allowed by default**. It detects documentation tests when they
196 | are on a private item. For example:
197 |
198 | ```rust
199 | #![warn(rustdoc::private_doc_tests)]
200 |
201 | mod foo {
202 | /// private doc test
203 | ///
204 | /// ```
205 | /// assert!(false);
206 | /// ```
207 | fn bar() {}
208 | }
209 | # fn main() {}
210 | ```
211 |
212 | Which will give:
213 |
214 | ```text
215 | warning: Documentation test in private item
216 | --> your-crate/lib.rs:4:1
217 | |
218 | 4 | / /// private doc test
219 | 5 | | ///
220 | 6 | | /// ```
221 | 7 | | /// assert!(false);
222 | 8 | | /// ```
223 | | |___________^
224 | ```
225 |
226 | ## invalid_codeblock_attributes
227 |
228 | This lint **warns by default**. It detects code block attributes in
229 | documentation examples that have potentially mis-typed values. For example:
230 |
231 | ```rust
232 | #![warn(rustdoc::invalid_codeblock_attributes)] // note: unnecessary - warns by default.
233 |
234 | /// Example.
235 | ///
236 | /// ```should-panic
237 | /// assert_eq!(1, 2);
238 | /// ```
239 | pub fn foo() {}
240 | ```
241 |
242 | Which will give:
243 |
244 | ```text
245 | warning: unknown attribute `should-panic`. Did you mean `should_panic`?
246 | --> src/lib.rs:1:1
247 | |
248 | 1 | / /// Example.
249 | 2 | | ///
250 | 3 | | /// ```should-panic
251 | 4 | | /// assert_eq!(1, 2);
252 | 5 | | /// ```
253 | | |_______^
254 | |
255 | = note: `#[warn(rustdoc::invalid_codeblock_attributes)]` on by default
256 | = help: the code block will either not be tested if not marked as a rust one or won't fail if it doesn't panic when running
257 | ```
258 |
259 | In the example above, the correct form is `should_panic`. This helps detect
260 | typo mistakes for some common attributes.
261 |
262 | ## invalid_html_tags
263 |
264 | This lint is **allowed by default** and is **nightly-only**. It detects unclosed
265 | or invalid HTML tags. For example:
266 |
267 | ```rust
268 | #![warn(rustdoc::invalid_html_tags)]
269 |
270 | ///
282 | 2 | | ///
283 | | |_____________^
284 | |
285 | note: the lint level is defined here
286 | --> foo.rs:1:9
287 | |
288 | 1 | #![warn(rustdoc::invalid_html_tags)]
289 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^
290 |
291 | warning: unclosed HTML tag `h1`
292 | --> foo.rs:1:1
293 | |
294 | 1 | / ///
295 | 2 | | ///
296 | | |_____________^
297 |
298 | warning: 2 warnings emitted
299 | ```
300 |
301 | ## invalid_rust_codeblocks
302 |
303 | This lint **warns by default**. It detects Rust code blocks in documentation
304 | examples that are invalid (e.g. empty, not parsable as Rust). For example:
305 |
306 | ```rust
307 | /// Empty code blocks (with and without the `rust` marker):
308 | ///
309 | /// ```rust
310 | /// ```
311 | ///
312 | /// Invalid syntax in code blocks:
313 | ///
314 | /// ```rust
315 | /// '<
316 | /// ```
317 | pub fn foo() {}
318 | ```
319 |
320 | Which will give:
321 |
322 | ```text
323 | warning: Rust code block is empty
324 | --> lint.rs:3:5
325 | |
326 | 3 | /// ```rust
327 | | _____^
328 | 4 | | /// ```
329 | | |_______^
330 | |
331 | = note: `#[warn(rustdoc::invalid_rust_codeblocks)]` on by default
332 |
333 | warning: could not parse code block as Rust code
334 | --> lint.rs:8:5
335 | |
336 | 8 | /// ```rust
337 | | _____^
338 | 9 | | /// '<
339 | 10 | | /// ```
340 | | |_______^
341 | |
342 | = note: error from rustc: unterminated character literal
343 | ```
344 |
345 | ## bare_urls
346 |
347 | This lint is **warn-by-default**. It detects URLs which are not links.
348 | For example:
349 |
350 | ```rust
351 | #![warn(rustdoc::bare_urls)] // note: unnecessary - warns by default.
352 |
353 | /// http://example.org
354 | /// [http://example.net]
355 | pub fn foo() {}
356 | ```
357 |
358 | Which will give:
359 |
360 | ```text
361 | warning: this URL is not a hyperlink
362 | --> links.rs:1:5
363 | |
364 | 1 | /// http://example.org
365 | | ^^^^^^^^^^^^^^^^^^ help: use an automatic link instead: ``
366 | |
367 | = note: `#[warn(rustdoc::bare_urls)]` on by default
368 |
369 | warning: this URL is not a hyperlink
370 | --> links.rs:3:6
371 | |
372 | 3 | /// [http://example.net]
373 | | ^^^^^^^^^^^^^^^^^^ help: use an automatic link instead: ``
374 |
375 | warning: 2 warnings emitted
376 | ```
377 |
--------------------------------------------------------------------------------
/english/src/passes.md:
--------------------------------------------------------------------------------
1 | # Passes
2 |
3 | Rustdoc has a concept called "passes". These are transformations that
4 | `rustdoc` runs on your documentation before producing its final output.
5 |
6 | Customizing passes is **deprecated**. The available passes are not considered stable and may
7 | change in any release.
8 |
9 | In the past the most common use case for customizing passes was to omit the `strip-private` pass.
10 | You can do this more easily, and without risk of the pass being changed, by passing
11 | [`--document-private-items`](./unstable-features.md#--document-private-items).
12 |
--------------------------------------------------------------------------------
/english/src/references.md:
--------------------------------------------------------------------------------
1 | # References
2 |
3 | There are many great `rustdoc` references out there.
4 | If you know of other great resources, please submit a pull request!
5 |
6 | ## Official
7 |
8 | - [Learn Rust]
9 | - [Rust By Example]
10 | - [Rust Reference]
11 | - [RFC 1574: More API Documentation Conventions]
12 | - [RFC 1946: Intra Rustdoc Links]
13 |
14 | ## Community
15 | - [API Guidelines]
16 | - [Github tagged RFCs]
17 | - [Github tagged issues]
18 | - [RFC (stalled) front page styleguide]
19 | - [Guide on how to write documentation for a Rust crate]
20 |
21 |
22 | [API Guidelines]: https://rust-lang.github.io/api-guidelines/documentation.html
23 | [Github tagged RFCs]: https://github.com/rust-lang/rfcs/issues?q=label%3AT-rustdoc
24 | [Github tagged issues]: https://github.com/rust-lang/rust/issues?q=is%3Aissue+is%3Aopen+label%3AT-rustdoc
25 | [Guide on how to write documentation for a Rust crate]: https://blog.guillaume-gomez.fr/articles/2020-03-12+Guide+on+how+to+write+documentation+for+a+Rust+crate
26 | [Learn Rust]: https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#making-useful-documentation-comments
27 | [RFC 1574: More API Documentation Conventions]: https://rust-lang.github.io/rfcs/1574-more-api-documentation-conventions.html
28 | [RFC 1946: Intra Rustdoc Links]: https://rust-lang.github.io/rfcs/1946-intra-rustdoc-links.html
29 | [RFC (stalled) front page styleguide]: https://github.com/rust-lang/rfcs/pull/1687
30 | [Rust By Example]: https://doc.rust-lang.org/stable/rust-by-example/meta/doc.html
31 | [Rust Reference]: https://doc.rust-lang.org/stable/reference/comments.html#doc-comments
32 |
--------------------------------------------------------------------------------
/english/src/the-doc-attribute.md:
--------------------------------------------------------------------------------
1 | # The `#[doc]` attribute
2 |
3 | The `#[doc]` attribute lets you control various aspects of how `rustdoc` does
4 | its job.
5 |
6 | The most basic function of `#[doc]` is to handle the actual documentation
7 | text. That is, `///` is syntax sugar for `#[doc]`. This means that these two
8 | are the same:
9 |
10 | ```rust,no_run
11 | /// This is a doc comment.
12 | #[doc = " This is a doc comment."]
13 | # fn f() {}
14 | ```
15 |
16 | (Note the leading space in the attribute version.)
17 |
18 | In most cases, `///` is easier to use than `#[doc]`. One case where the latter is easier is
19 | when generating documentation in macros; the `collapse-docs` pass will combine multiple
20 | `#[doc]` attributes into a single doc comment, letting you generate code like this:
21 |
22 | ```rust,no_run
23 | #[doc = "This is"]
24 | #[doc = " a "]
25 | #[doc = "doc comment"]
26 | # fn f() {}
27 | ```
28 |
29 | Which can feel more flexible. Note that this would generate this:
30 |
31 | ```rust,no_run
32 | #[doc = "This is\n a \ndoc comment"]
33 | # fn f() {}
34 | ```
35 |
36 | but given that docs are rendered via Markdown, it will remove these newlines.
37 |
38 | Another use case is for including external files as documentation:
39 |
40 | ```rust,no_run
41 | #[doc = include_str!("../README.md")]
42 | # fn f() {}
43 | ```
44 |
45 | The `doc` attribute has more options though! These don't involve the text of
46 | the output, but instead, various aspects of the presentation of the output.
47 | We've split them into two kinds below: attributes that are useful at the
48 | crate level, and ones that are useful at the item level.
49 |
50 | ## At the crate level
51 |
52 | These options control how the docs look at a crate level.
53 |
54 | ### `html_favicon_url`
55 |
56 | This form of the `doc` attribute lets you control the favicon of your docs.
57 |
58 | ```rust,no_run
59 | #![doc(html_favicon_url = "https://example.com/favicon.ico")]
60 | ```
61 |
62 | This will put `` into your docs, where
63 | the string for the attribute goes into the `{}`.
64 |
65 | If you don't use this attribute, there will be no favicon.
66 |
67 | ### `html_logo_url`
68 |
69 | This form of the `doc` attribute lets you control the logo in the upper
70 | left hand side of the docs.
71 |
72 | ```rust,no_run
73 | #![doc(html_logo_url = "https://example.com/logo.jpg")]
74 | ```
75 |
76 | This will put `` into
77 | your docs, where the string for the attribute goes into the `{}`.
78 |
79 | If you don't use this attribute, there will be no logo.
80 |
81 | ### `html_playground_url`
82 |
83 | This form of the `doc` attribute lets you control where the "run" buttons
84 | on your documentation examples make requests to.
85 |
86 | ```rust,no_run
87 | #![doc(html_playground_url = "https://playground.example.com/")]
88 | ```
89 |
90 | Now, when you press "run", the button will make a request to this domain.
91 |
92 | If you don't use this attribute, there will be no run buttons.
93 |
94 | ### `issue_tracker_base_url`
95 |
96 | This form of the `doc` attribute is mostly only useful for the standard library;
97 | When a feature is unstable, an issue number for tracking the feature must be
98 | given. `rustdoc` uses this number, plus the base URL given here, to link to
99 | the tracking issue.
100 |
101 | ```rust,no_run
102 | #![doc(issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/")]
103 | ```
104 |
105 | ### `html_root_url`
106 |
107 | The `#[doc(html_root_url = "…")]` attribute value indicates the URL for
108 | generating links to external crates. When rustdoc needs to generate a link to
109 | an item in an external crate, it will first check if the extern crate has been
110 | documented locally on-disk, and if so link directly to it. Failing that, it
111 | will use the URL given by the `--extern-html-root-url` command-line flag if
112 | available. If that is not available, then it will use the `html_root_url`
113 | value in the extern crate if it is available. If that is not available, then
114 | the extern items will not be linked.
115 |
116 | ```rust,no_run
117 | #![doc(html_root_url = "https://docs.rs/serde/1.0")]
118 | ```
119 |
120 | ### `html_no_source`
121 |
122 | By default, `rustdoc` will include the source code of your program, with links
123 | to it in the docs. But if you include this:
124 |
125 | ```rust,no_run
126 | #![doc(html_no_source)]
127 | ```
128 |
129 | it will not.
130 |
131 | ### `test(no_crate_inject)`
132 |
133 | By default, `rustdoc` will automatically add a line with `extern crate my_crate;` into each doctest.
134 | But if you include this:
135 |
136 | ```rust,no_run
137 | #![doc(test(no_crate_inject))]
138 | ```
139 |
140 | it will not.
141 |
142 | ### `test(attr(...))`
143 |
144 | This form of the `doc` attribute allows you to add arbitrary attributes to all your doctests. For
145 | example, if you want your doctests to fail if they produce any warnings, you could add this:
146 |
147 | ```rust,no_run
148 | #![doc(test(attr(deny(warnings))))]
149 | ```
150 |
151 | ## At the item level
152 |
153 | These forms of the `#[doc]` attribute are used on individual items, to control how
154 | they are documented.
155 |
156 | ### `inline` and `no_inline`
157 |
158 |
159 |
160 | These attributes are used on `use` statements, and control where the documentation shows
161 | up. For example, consider this Rust code:
162 |
163 | ```rust,no_run
164 | pub use bar::Bar;
165 |
166 | /// bar docs
167 | pub mod bar {
168 | /// the docs for Bar
169 | pub struct Bar;
170 | }
171 | # fn main() {}
172 | ```
173 |
174 | The documentation will generate a "Re-exports" section, and say `pub use bar::Bar;`, where
175 | `Bar` is a link to its page.
176 |
177 | If we change the `use` line like this:
178 |
179 | ```rust,no_run
180 | #[doc(inline)]
181 | pub use bar::Bar;
182 | # pub mod bar { pub struct Bar; }
183 | # fn main() {}
184 | ```
185 |
186 | Instead, `Bar` will appear in a `Structs` section, just like `Bar` was defined at the
187 | top level, rather than `pub use`'d.
188 |
189 | Let's change our original example, by making `bar` private:
190 |
191 | ```rust,no_run
192 | pub use bar::Bar;
193 |
194 | /// bar docs
195 | mod bar {
196 | /// the docs for Bar
197 | pub struct Bar;
198 | }
199 | # fn main() {}
200 | ```
201 |
202 | Here, because `bar` is not public, `Bar` wouldn't have its own page, so there's nowhere
203 | to link to. `rustdoc` will inline these definitions, and so we end up in the same case
204 | as the `#[doc(inline)]` above; `Bar` is in a `Structs` section, as if it were defined at
205 | the top level. If we add the `no_inline` form of the attribute:
206 |
207 | ```rust,no_run
208 | #[doc(no_inline)]
209 | pub use bar::Bar;
210 |
211 | /// bar docs
212 | mod bar {
213 | /// the docs for Bar
214 | pub struct Bar;
215 | }
216 | # fn main() {}
217 | ```
218 |
219 | Now we'll have a `Re-exports` line, and `Bar` will not link to anywhere.
220 |
221 | One special case: In Rust 2018 and later, if you `pub use` one of your dependencies, `rustdoc` will
222 | not eagerly inline it as a module unless you add `#[doc(inline)]`.
223 |
224 | ### `hidden`
225 |
226 |
227 |
228 | Any item annotated with `#[doc(hidden)]` will not appear in the documentation, unless
229 | the `strip-hidden` pass is removed.
230 |
231 | ### `alias`
232 |
233 | This attribute adds an alias in the search index.
234 |
235 | Let's take an example:
236 |
237 | ```rust,no_run
238 | #[doc(alias = "TheAlias")]
239 | pub struct SomeType;
240 | ```
241 |
242 | So now, if you enter "TheAlias" in the search, it'll display `SomeType`.
243 | Of course, if you enter `SomeType` it'll return `SomeType` as expected!
244 |
245 | #### FFI example
246 |
247 | This doc attribute is especially useful when writing bindings for a C library.
248 | For example, let's say we have a C function that looks like this:
249 |
250 | ```c
251 | int lib_name_do_something(Obj *obj);
252 | ```
253 |
254 | It takes a pointer to an `Obj` type and returns an integer. In Rust, it might
255 | be written like this:
256 |
257 | ```ignore (using non-existing ffi types)
258 | pub struct Obj {
259 | inner: *mut ffi::Obj,
260 | }
261 |
262 | impl Obj {
263 | pub fn do_something(&mut self) -> i32 {
264 | unsafe { ffi::lib_name_do_something(self.inner) }
265 | }
266 | }
267 | ```
268 |
269 | The function has been turned into a method to make it more convenient to use.
270 | However, if you want to look for the Rust equivalent of `lib_name_do_something`,
271 | you have no way to do so.
272 |
273 | To get around this limitation, we just add `#[doc(alias = "lib_name_do_something")]`
274 | on the `do_something` method and then it's all good!
275 | Users can now look for `lib_name_do_something` in our crate directly and find
276 | `Obj::do_something`.
277 |
--------------------------------------------------------------------------------
/english/src/unstable-features.md:
--------------------------------------------------------------------------------
1 | # Unstable features
2 |
3 | Rustdoc is under active development, and like the Rust compiler, some features are only available
4 | on nightly releases. Some of these features are new and need some more testing before they're able to be
5 | released to the world at large, and some of them are tied to features in the Rust compiler that are unstable. Several features here require a matching `#![feature(...)]` attribute to
6 | enable, and thus are more fully documented in the [Unstable Book]. Those sections will link over
7 | there as necessary.
8 |
9 | [Unstable Book]: ../unstable-book/index.html
10 |
11 | ## Nightly-gated functionality
12 |
13 | These features just require a nightly build to operate. Unlike the other features on this page,
14 | these don't need to be "turned on" with a command-line flag or a `#![feature(...)]` attribute in
15 | your crate. This can give them some subtle fallback modes when used on a stable release, so be
16 | careful!
17 |
18 | ### Error numbers for `compile-fail` doctests
19 |
20 | As detailed in [the chapter on documentation tests][doctest-attributes], you can add a
21 | `compile_fail` attribute to a doctest to state that the test should fail to compile. However, on
22 | nightly, you can optionally add an error number to state that a doctest should emit a specific error
23 | number:
24 |
25 | [doctest-attributes]: documentation-tests.html#attributes
26 |
27 | ``````markdown
28 | ```compile_fail,E0044
29 | extern { fn some_func(x: T); }
30 | ```
31 | ``````
32 |
33 | This is used by the error index to ensure that the samples that correspond to a given error number
34 | properly emit that error code. However, these error codes aren't guaranteed to be the only thing
35 | that a piece of code emits from version to version, so this is unlikely to be stabilized in the
36 | future.
37 |
38 | Attempting to use these error numbers on stable will result in the code sample being interpreted as
39 | plain text.
40 |
41 | ## Extensions to the `#[doc]` attribute
42 |
43 | These features operate by extending the `#[doc]` attribute, and thus can be caught by the compiler
44 | and enabled with a `#![feature(...)]` attribute in your crate.
45 |
46 | ### `#[doc(cfg)]`: Recording what platforms or features are required for code to be present
47 |
48 | You can use `#[doc(cfg(...))]` to tell Rustdoc exactly which platform items appear on.
49 | This has two effects:
50 |
51 | 1. doctests will only run on the appropriate platforms, and
52 | 2. When Rustdoc renders documentation for that item, it will be accompanied by a banner explaining
53 | that the item is only available on certain platforms.
54 |
55 | `#[doc(cfg)]` is intended to be used alongside [`#[cfg(doc)]`][cfg-doc].
56 | For example, `#[cfg(any(windows, doc))]` will preserve the item either on Windows or during the
57 | documentation process. Then, adding a new attribute `#[doc(cfg(windows))]` will tell Rustdoc that
58 | the item is supposed to be used on Windows. For example:
59 |
60 | ```rust
61 | #![feature(doc_cfg)]
62 |
63 | /// Token struct that can only be used on Windows.
64 | #[cfg(any(windows, doc))]
65 | #[doc(cfg(windows))]
66 | pub struct WindowsToken;
67 |
68 | /// Token struct that can only be used on Unix.
69 | #[cfg(any(unix, doc))]
70 | #[doc(cfg(unix))]
71 | pub struct UnixToken;
72 |
73 | /// Token struct that is only available with the `serde` feature
74 | #[cfg(feature = "serde")]
75 | #[doc(cfg(feature = "serde"))]
76 | #[derive(serde::Deserialize)]
77 | pub struct SerdeToken;
78 | ```
79 |
80 | In this sample, the tokens will only appear on their respective platforms, but they will both appear
81 | in documentation.
82 |
83 | `#[doc(cfg(...))]` was introduced to be used by the standard library and currently requires the
84 | `#![feature(doc_cfg)]` feature gate. For more information, see [its chapter in the Unstable
85 | Book][unstable-doc-cfg] and [its tracking issue][issue-doc-cfg].
86 |
87 | ### `doc_auto_cfg`: Automatically generate `#[doc(cfg)]`
88 |
89 | `doc_auto_cfg` is an extension to the `#[doc(cfg)]` feature. With it, you don't need to add
90 | `#[doc(cfg(...)]` anymore unless you want to override the default behaviour. So if we take the
91 | previous source code:
92 |
93 | ```rust
94 | #![feature(doc_auto_cfg)]
95 |
96 | /// Token struct that can only be used on Windows.
97 | #[cfg(any(windows, doc))]
98 | pub struct WindowsToken;
99 |
100 | /// Token struct that can only be used on Unix.
101 | #[cfg(any(unix, doc))]
102 | pub struct UnixToken;
103 |
104 | /// Token struct that is only available with the `serde` feature
105 | #[cfg(feature = "serde")]
106 | #[derive(serde::Deserialize)]
107 | pub struct SerdeToken;
108 | ```
109 |
110 | It'll render almost the same, the difference being that `doc` will also be displayed. To fix this,
111 | you can use `doc_cfg_hide`:
112 |
113 | ```rust
114 | #![feature(doc_cfg_hide)]
115 | #![doc(cfg_hide(doc))]
116 | ```
117 |
118 | And `doc` won't show up anymore!
119 |
120 | [cfg-doc]: ./advanced-features.md
121 | [unstable-doc-cfg]: ../unstable-book/language-features/doc-cfg.html
122 | [issue-doc-cfg]: https://github.com/rust-lang/rust/issues/43781
123 |
124 | ### Adding your trait to the "Notable traits" dialog
125 |
126 | Rustdoc keeps a list of a few traits that are believed to be "fundamental" to
127 | types that implement them. These traits are intended to be the primary interface
128 | for their implementers, and are often most of the API available to be documented
129 | on their types. For this reason, Rustdoc will track when a given type implements
130 | one of these traits and call special attention to it when a function returns one
131 | of these types. This is the "Notable traits" dialog, accessible as a circled `i`
132 | button next to the function, which, when clicked, shows the dialog.
133 |
134 | In the standard library, some of the traits that are part of this list are
135 | `Iterator`, `Future`, `io::Read`, and `io::Write`. However, rather than being
136 | implemented as a hard-coded list, these traits have a special marker attribute
137 | on them: `#[doc(notable_trait)]`. This means that you can apply this attribute
138 | to your own trait to include it in the "Notable traits" dialog in documentation.
139 |
140 | The `#[doc(notable_trait)]` attribute currently requires the `#![feature(doc_notable_trait)]`
141 | feature gate. For more information, see [its chapter in the Unstable Book][unstable-notable_trait]
142 | and [its tracking issue][issue-notable_trait].
143 |
144 | [unstable-notable_trait]: ../unstable-book/language-features/doc-notable-trait.html
145 | [issue-notable_trait]: https://github.com/rust-lang/rust/issues/45040
146 |
147 | ### Exclude certain dependencies from documentation
148 |
149 | The standard library uses several dependencies which, in turn, use several types and traits from the
150 | standard library. In addition, there are several compiler-internal crates that are not considered to
151 | be part of the official standard library, and thus would be a distraction to include in
152 | documentation. It's not enough to exclude their crate documentation, since information about trait
153 | implementations appears on the pages for both the type and the trait, which can be in different
154 | crates!
155 |
156 | To prevent internal types from being included in documentation, the standard library adds an
157 | attribute to their `extern crate` declarations: `#[doc(masked)]`. This causes Rustdoc to "mask out"
158 | types from these crates when building lists of trait implementations.
159 |
160 | The `#[doc(masked)]` attribute is intended to be used internally, and requires the
161 | `#![feature(doc_masked)]` feature gate. For more information, see [its chapter in the Unstable
162 | Book][unstable-masked] and [its tracking issue][issue-masked].
163 |
164 | [unstable-masked]: ../unstable-book/language-features/doc-masked.html
165 | [issue-masked]: https://github.com/rust-lang/rust/issues/44027
166 |
167 |
168 | ## Document primitives
169 |
170 | This is for Rust compiler internal use only.
171 |
172 | Since primitive types are defined in the compiler, there's no place to attach documentation
173 | attributes. The `#[doc(primitive)]` attribute is used by the standard library to provide a way
174 | to generate documentation for primitive types, and requires `#![feature(rustdoc_internals)]` to
175 | enable.
176 |
177 | ## Document keywords
178 |
179 | This is for Rust compiler internal use only.
180 |
181 | Rust keywords are documented in the standard library (look for `match` for example).
182 |
183 | To do so, the `#[doc(keyword = "...")]` attribute is used. Example:
184 |
185 | ```rust
186 | #![feature(rustdoc_internals)]
187 |
188 | /// Some documentation about the keyword.
189 | #[doc(keyword = "keyword")]
190 | mod empty_mod {}
191 | ```
192 |
193 | ## Unstable command-line arguments
194 |
195 | These features are enabled by passing a command-line flag to Rustdoc, but the flags in question are
196 | themselves marked as unstable. To use any of these options, pass `-Z unstable-options` as well as
197 | the flag in question to Rustdoc on the command-line. To do this from Cargo, you can either use the
198 | `RUSTDOCFLAGS` environment variable or the `cargo rustdoc` command.
199 |
200 | ### `--markdown-before-content`: include rendered Markdown before the content
201 |
202 | Using this flag looks like this:
203 |
204 | ```bash
205 | $ rustdoc src/lib.rs -Z unstable-options --markdown-before-content extra.md
206 | $ rustdoc README.md -Z unstable-options --markdown-before-content extra.md
207 | ```
208 |
209 | Just like `--html-before-content`, this allows you to insert extra content inside the `` tag
210 | but before the other content `rustdoc` would normally produce in the rendered documentation.
211 | However, instead of directly inserting the file verbatim, `rustdoc` will pass the files through a
212 | Markdown renderer before inserting the result into the file.
213 |
214 | ### `--markdown-after-content`: include rendered Markdown after the content
215 |
216 | Using this flag looks like this:
217 |
218 | ```bash
219 | $ rustdoc src/lib.rs -Z unstable-options --markdown-after-content extra.md
220 | $ rustdoc README.md -Z unstable-options --markdown-after-content extra.md
221 | ```
222 |
223 | Just like `--html-after-content`, this allows you to insert extra content before the `` tag
224 | but after the other content `rustdoc` would normally produce in the rendered documentation.
225 | However, instead of directly inserting the file verbatim, `rustdoc` will pass the files through a
226 | Markdown renderer before inserting the result into the file.
227 |
228 | ### `--playground-url`: control the location of the playground
229 |
230 | Using this flag looks like this:
231 |
232 | ```bash
233 | $ rustdoc src/lib.rs -Z unstable-options --playground-url https://play.rust-lang.org/
234 | ```
235 |
236 | When rendering a crate's docs, this flag gives the base URL of the Rust Playground, to use for
237 | generating `Run` buttons. Unlike `--markdown-playground-url`, this argument works for standalone
238 | Markdown files *and* Rust crates. This works the same way as adding `#![doc(html_playground_url =
239 | "url")]` to your crate root, as mentioned in [the chapter about the `#[doc]`
240 | attribute][doc-playground]. Please be aware that the official Rust Playground at
241 | https://play.rust-lang.org does not have every crate available, so if your examples require your
242 | crate, make sure the playground you provide has your crate available.
243 |
244 | [doc-playground]: the-doc-attribute.html#html_playground_url
245 |
246 | If both `--playground-url` and `--markdown-playground-url` are present when rendering a standalone
247 | Markdown file, the URL given to `--markdown-playground-url` will take precedence. If both
248 | `--playground-url` and `#![doc(html_playground_url = "url")]` are present when rendering crate docs,
249 | the attribute will take precedence.
250 |
251 | ### `--sort-modules-by-appearance`: control how items on module pages are sorted
252 |
253 | Using this flag looks like this:
254 |
255 | ```bash
256 | $ rustdoc src/lib.rs -Z unstable-options --sort-modules-by-appearance
257 | ```
258 |
259 | Ordinarily, when `rustdoc` prints items in module pages, it will sort them alphabetically (taking
260 | some consideration for their stability, and names that end in a number). Giving this flag to
261 | `rustdoc` will disable this sorting and instead make it print the items in the order they appear in
262 | the source.
263 |
264 | ### `--show-type-layout`: add a section to each type's docs describing its memory layout
265 |
266 | Using this flag looks like this:
267 |
268 | ```bash
269 | $ rustdoc src/lib.rs -Z unstable-options --show-type-layout
270 | ```
271 |
272 | When this flag is passed, rustdoc will add a "Layout" section at the bottom of
273 | each type's docs page that includes a summary of the type's memory layout as
274 | computed by rustc. For example, rustdoc will show the size in bytes that a value
275 | of that type will take in memory.
276 |
277 | Note that most layout information is **completely unstable** and may even differ
278 | between compilations.
279 |
280 | ### `--resource-suffix`: modifying the name of CSS/JavaScript in crate docs
281 |
282 | Using this flag looks like this:
283 |
284 | ```bash
285 | $ rustdoc src/lib.rs -Z unstable-options --resource-suffix suf
286 | ```
287 |
288 | When rendering docs, `rustdoc` creates several CSS and JavaScript files as part of the output. Since
289 | all these files are linked from every page, changing where they are can be cumbersome if you need to
290 | specially cache them. This flag will rename all these files in the output to include the suffix in
291 | the filename. For example, `light.css` would become `light-suf.css` with the above command.
292 |
293 | ### `--extern-html-root-url`: control how rustdoc links to non-local crates
294 |
295 | Using this flag looks like this:
296 |
297 | ```bash
298 | $ rustdoc src/lib.rs -Z unstable-options --extern-html-root-url some-crate=https://example.com/some-crate/1.0.1
299 | ```
300 |
301 | Ordinarily, when rustdoc wants to link to a type from a different crate, it looks in two places:
302 | docs that already exist in the output directory, or the `#![doc(doc_html_root)]` set in the other
303 | crate. However, if you want to link to docs that exist in neither of those places, you can use these
304 | flags to control that behavior. When the `--extern-html-root-url` flag is given with a name matching
305 | one of your dependencies, rustdoc use that URL for those docs. Keep in mind that if those docs exist
306 | in the output directory, those local docs will still override this flag.
307 |
308 | ### `-Z force-unstable-if-unmarked`
309 |
310 | Using this flag looks like this:
311 |
312 | ```bash
313 | $ rustdoc src/lib.rs -Z force-unstable-if-unmarked
314 | ```
315 |
316 | This is an internal flag intended for the standard library and compiler that applies an
317 | `#[unstable]` attribute to any dependent crate that doesn't have another stability attribute. This
318 | allows `rustdoc` to be able to generate documentation for the compiler crates and the standard
319 | library, as an equivalent command-line argument is provided to `rustc` when building those crates.
320 |
321 | ### `--index-page`: provide a top-level landing page for docs
322 |
323 | This feature allows you to generate an index-page with a given markdown file. A good example of it
324 | is the [rust documentation index](https://doc.rust-lang.org/nightly/index.html).
325 |
326 | With this, you'll have a page which you can custom as much as you want at the top of your crates.
327 |
328 | Using `index-page` option enables `enable-index-page` option as well.
329 |
330 | ### `--enable-index-page`: generate a default index page for docs
331 |
332 | This feature allows the generation of a default index-page which lists the generated crates.
333 |
334 | ### `--static-root-path`: control how static files are loaded in HTML output
335 |
336 | Using this flag looks like this:
337 |
338 | ```bash
339 | $ rustdoc src/lib.rs -Z unstable-options --static-root-path '/cache/'
340 | ```
341 |
342 | This flag controls how rustdoc links to its static files on HTML pages. If you're hosting a lot of
343 | crates' docs generated by the same version of rustdoc, you can use this flag to cache rustdoc's CSS,
344 | JavaScript, and font files in a single location, rather than duplicating it once per "doc root"
345 | (grouping of crate docs generated into the same output directory, like with `cargo doc`). Per-crate
346 | files like the search index will still load from the documentation root, but anything that gets
347 | renamed with `--resource-suffix` will load from the given path.
348 |
349 | ### `--persist-doctests`: persist doctest executables after running
350 |
351 | Using this flag looks like this:
352 |
353 | ```bash
354 | $ rustdoc src/lib.rs --test -Z unstable-options --persist-doctests target/rustdoctest
355 | ```
356 |
357 | This flag allows you to keep doctest executables around after they're compiled or run.
358 | Usually, rustdoc will immediately discard a compiled doctest after it's been tested, but
359 | with this option, you can keep those binaries around for farther testing.
360 |
361 | ### `--show-coverage`: calculate the percentage of items with documentation
362 |
363 | Using this flag looks like this:
364 |
365 | ```bash
366 | $ rustdoc src/lib.rs -Z unstable-options --show-coverage
367 | ```
368 |
369 | It generates something like this:
370 |
371 | ```bash
372 | +-------------------------------------+------------+------------+------------+------------+
373 | | File | Documented | Percentage | Examples | Percentage |
374 | +-------------------------------------+------------+------------+------------+------------+
375 | | lib.rs | 4 | 100.0% | 1 | 25.0% |
376 | +-------------------------------------+------------+------------+------------+------------+
377 | | Total | 4 | 100.0% | 1 | 25.0% |
378 | +-------------------------------------+------------+------------+------------+------------+
379 | ```
380 |
381 | If you want to determine how many items in your crate are documented, pass this flag to rustdoc.
382 | When it receives this flag, it will count the public items in your crate that have documentation,
383 | and print out the counts and a percentage instead of generating docs.
384 |
385 | Some methodology notes about what rustdoc counts in this metric:
386 |
387 | * Rustdoc will only count items from your crate (i.e. items re-exported from other crates don't
388 | count).
389 | * Docs written directly onto inherent impl blocks are not counted, even though their doc comments
390 | are displayed, because the common pattern in Rust code is to write all inherent methods into the
391 | same impl block.
392 | * Items in a trait implementation are not counted, as those impls will inherit any docs from the
393 | trait itself.
394 | * By default, only public items are counted. To count private items as well, pass
395 | `--document-private-items` at the same time.
396 |
397 | Public items that are not documented can be seen with the built-in `missing_docs` lint. Private
398 | items that are not documented can be seen with Clippy's `missing_docs_in_private_items` lint.
399 |
400 | Calculating code examples follows these rules:
401 |
402 | 1. These items aren't accounted by default:
403 | * struct/union field
404 | * enum variant
405 | * constant
406 | * static
407 | * typedef
408 | 2. If one of the previously listed items has a code example, then it'll be counted.
409 |
410 | #### JSON output
411 |
412 | When using `--output-format json` with this option, it will display the coverage information in
413 | JSON format. For example, here is the JSON for a file with one documented item and one
414 | undocumented item:
415 |
416 | ```rust
417 | /// This item has documentation
418 | pub fn foo() {}
419 |
420 | pub fn no_documentation() {}
421 | ```
422 |
423 | ```json
424 | {"no_std.rs":{"total":3,"with_docs":1,"total_examples":3,"with_examples":0}}
425 | ```
426 |
427 | Note that the third item is the crate root, which in this case is undocumented.
428 |
429 | ### `-w`/`--output-format`: output format
430 |
431 | `--output-format json` emits documentation in the experimental
432 | [JSON format](https://doc.rust-lang.org/nightly/nightly-rustc/rustdoc_json_types/). `--output-format html` has no effect,
433 | and is also accepted on stable toolchains.
434 |
435 | It can also be used with `--show-coverage`. Take a look at its
436 | [documentation](#--show-coverage-get-statistics-about-code-documentation-coverage) for more
437 | information.
438 |
439 | ### `--enable-per-target-ignores`: allow `ignore-foo` style filters for doctests
440 |
441 | Using this flag looks like this:
442 |
443 | ```bash
444 | $ rustdoc src/lib.rs -Z unstable-options --enable-per-target-ignores
445 | ```
446 |
447 | This flag allows you to tag doctests with compiletest style `ignore-foo` filters that prevent
448 | rustdoc from running that test if the target triple string contains foo. For example:
449 |
450 | ```rust
451 | ///```ignore-foo,ignore-bar
452 | ///assert!(2 == 2);
453 | ///```
454 | struct Foo;
455 | ```
456 |
457 | This will not be run when the build target is `super-awesome-foo` or `less-bar-awesome`.
458 | If the flag is not enabled, then rustdoc will consume the filter, but do nothing with it, and
459 | the above example will be run for all targets.
460 | If you want to preserve backwards compatibility for older versions of rustdoc, you can use
461 |
462 | ```rust
463 | ///```ignore,ignore-foo
464 | ///assert!(2 == 2);
465 | ///```
466 | struct Foo;
467 | ```
468 |
469 | In older versions, this will be ignored on all targets, but on newer versions `ignore-gnu` will
470 | override `ignore`.
471 |
472 | ### `--runtool`, `--runtool-arg`: program to run tests with; args to pass to it
473 |
474 | Using these options looks like this:
475 |
476 | ```bash
477 | $ rustdoc src/lib.rs -Z unstable-options --runtool runner --runtool-arg --do-thing --runtool-arg --do-other-thing
478 | ```
479 |
480 | These options can be used to run the doctest under a program, and also pass arguments to
481 | that program. For example, if you want to run your doctests under valgrind you might run
482 |
483 | ```bash
484 | $ rustdoc src/lib.rs -Z unstable-options --runtool valgrind
485 | ```
486 |
487 | Another use case would be to run a test inside an emulator, or through a Virtual Machine.
488 |
489 | ### `--with-examples`: include examples of uses of items as documentation
490 |
491 | This option, combined with `--scrape-examples-target-crate` and
492 | `--scrape-examples-output-path`, is used to implement the functionality in [RFC
493 | #3123](https://github.com/rust-lang/rfcs/pull/3123). Uses of an item (currently
494 | functions / call-sites) are found in a crate and its reverse-dependencies, and
495 | then the uses are included as documentation for that item. This feature is
496 | intended to be used via `cargo doc --scrape-examples`, but the rustdoc-only
497 | workflow looks like:
498 |
499 | ```bash
500 | $ rustdoc examples/ex.rs -Z unstable-options \
501 | --extern foobar=target/deps/libfoobar.rmeta \
502 | --scrape-examples-target-crate foobar \
503 | --scrape-examples-output-path output.calls
504 | $ rustdoc src/lib.rs -Z unstable-options --with-examples output.calls
505 | ```
506 |
507 | First, the library must be checked to generate an `rmeta`. Then a
508 | reverse-dependency like `examples/ex.rs` is given to rustdoc with the target
509 | crate being documented (`foobar`) and a path to output the calls
510 | (`output.calls`). Then, the generated calls file can be passed via
511 | `--with-examples` to the subsequent documentation of `foobar`.
512 |
--------------------------------------------------------------------------------
/english/src/website-features.md:
--------------------------------------------------------------------------------
1 | # Website features
2 |
3 | These features are about using the website generated by `rustdoc`.
4 |
5 | ## Custom search engines
6 |
7 | If you find yourself often referencing online Rust docs you might enjoy using a custom search
8 | engine. This allows you to use the navigation bar directly to search a `rustdoc` website.
9 | Most browsers support this feature by letting you define a URL template containing `%s`
10 | which will be substituted for the search term. As an example, for the standard library you could use
11 | this template:
12 |
13 | ```text
14 | https://doc.rust-lang.org/stable/std/?search=%s
15 | ```
16 |
17 | Note that this will take you to a results page listing all matches. If you want to navigate to the first
18 | result right away (which is often the best match) use the following instead:
19 |
20 | ```text
21 | https://doc.rust-lang.org/stable/std/?search=%s&go_to_first=true
22 | ```
23 |
24 | This URL adds the `go_to_first=true` query parameter which can be appended to any `rustdoc` search URL
25 | to automatically go to the first result.
26 |
--------------------------------------------------------------------------------
/english/src/what-is-rustdoc.md:
--------------------------------------------------------------------------------
1 | # What is rustdoc?
2 |
3 | The standard Rust distribution ships with a tool called `rustdoc`. Its job is
4 | to generate documentation for Rust projects. On a fundamental level, Rustdoc
5 | takes as an argument either a crate root or a Markdown file, and produces HTML,
6 | CSS, and JavaScript.
7 |
8 | ## Basic usage
9 |
10 | Let's give it a try! Create a new project with Cargo:
11 |
12 | ```bash
13 | $ cargo new docs --lib
14 | $ cd docs
15 | ```
16 |
17 | In `src/lib.rs`, Cargo has generated some sample code. Delete
18 | it and replace it with this:
19 |
20 | ```rust
21 | /// foo is a function
22 | fn foo() {}
23 | ```
24 |
25 | Let's run `rustdoc` on our code. To do so, we can call it with the path to
26 | our crate root like this:
27 |
28 | ```bash
29 | $ rustdoc src/lib.rs
30 | ```
31 |
32 | This will create a new directory, `doc`, with a website inside! In our case,
33 | the main page is located in `doc/lib/index.html`. If you open that up in
34 | a web browser, you will see a page with a search bar, and "Crate lib" at the
35 | top, with no contents.
36 |
37 | ## Configuring rustdoc
38 |
39 | There are two problems with this: first, why does it
40 | think that our package is named "lib"? Second, why does it not have any
41 | contents?
42 |
43 | The first problem is due to `rustdoc` trying to be helpful; like `rustc`,
44 | it assumes that our crate's name is the name of the file for the crate
45 | root. To fix this, we can pass in a command-line flag:
46 |
47 | ```bash
48 | $ rustdoc src/lib.rs --crate-name docs
49 | ```
50 |
51 | Now, `doc/docs/index.html` will be generated, and the page says "Crate docs."
52 |
53 | For the second issue, it is because our function `foo` is not public; `rustdoc`
54 | defaults to generating documentation for only public functions. If we change
55 | our code...
56 |
57 | ```rust
58 | /// foo is a function
59 | pub fn foo() {}
60 | ```
61 |
62 | ... and then re-run `rustdoc`:
63 |
64 | ```bash
65 | $ rustdoc src/lib.rs --crate-name docs
66 | ```
67 |
68 | We now have some generated documentation. Open up `doc/docs/index.html` and
69 | check it out! It should show a link to the `foo` function's page, which
70 | is located at `doc/docs/fn.foo.html`. On that page, you'll see the "foo is
71 | a function" we put inside the documentation comment in our crate.
72 |
73 | ## Using rustdoc with Cargo
74 |
75 | Cargo also has integration with `rustdoc` to make it easier to generate
76 | docs. Instead of the `rustdoc` command, we could have done this:
77 |
78 | ```bash
79 | $ cargo doc
80 | ```
81 |
82 | Internally, this calls out to `rustdoc` like this:
83 |
84 | ```bash
85 | $ rustdoc --crate-name docs src/lib.rs -o /docs/target/doc -L
86 | dependency=/docs/target/debug/deps
87 | ```
88 |
89 | You can see this with `cargo doc --verbose`.
90 |
91 | It generates the correct `--crate-name` for us, as well as pointing to
92 | `src/lib.rs`. But what about those other arguments?
93 | - `-o` controls the *o*utput of our docs. Instead of a top-level
94 | `doc` directory, notice that Cargo puts generated documentation under
95 | `target`. That is the idiomatic place for generated files in Cargo projects.
96 | - `-L` flag helps rustdoc find the dependencies your code relies on.
97 | If our project used dependencies, we would get documentation for them as well!
98 |
99 | ## Outer and inner documentation
100 |
101 | The `///` syntax is used to document the item present after it.
102 | That's why it is called an outer documentation.
103 | There is another syntax: `//!`, which is used to document the
104 | item it is present inside. It is called an inner documentation.
105 | It is often used when documenting the entire crate,
106 | because nothing comes before it: it is the root of the crate.
107 | So in order to document an entire crate, you need to use `//!` syntax.
108 | For example:
109 |
110 | ``` rust
111 | //! This is my first rust crate
112 | ```
113 |
114 | When used in the crate root, it documents the item it is inside,
115 | which is the crate itself.
116 |
117 | For more information about the `//!` syntax, see [the Book].
118 |
119 | [the Book]: https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#commenting-contained-items
120 |
121 |
122 | ## Using standalone Markdown files
123 |
124 | `rustdoc` can also generate HTML from standalone Markdown files. Let' s
125 | give it a try: create a `README.md` file with these contents:
126 |
127 | ````text
128 | # Docs
129 |
130 | This is a project to test out `rustdoc`.
131 |
132 | [Here is a link!](https://www.rust-lang.org)
133 |
134 | ## Example
135 |
136 | ```rust
137 | fn foo() -> i32 {
138 | 1 + 1
139 | }
140 | ```
141 | ````
142 |
143 | And call `rustdoc` on it:
144 |
145 | ```bash
146 | $ rustdoc README.md
147 | ```
148 |
149 | You will find an HTML file in `docs/doc/README.html` generated from its
150 | Markdown contents.
151 |
152 | Cargo currently does not understand standalone Markdown files, unfortunately.
153 |
154 | ## Summary
155 |
156 | This covers the simplest use-cases of `rustdoc`. The rest of this book will
157 | explain all of the options that `rustdoc` has, and how to use them.
158 |
--------------------------------------------------------------------------------
/english/src/what-to-include.md:
--------------------------------------------------------------------------------
1 | # What to include (and exclude)
2 |
3 | It is easy to say everything must be documented in a project and often times
4 | that is correct, but how can we get there, and are there things that don't
5 | belong?
6 |
7 | At the top of the `src/lib.rs` or `main.rs` file in your binary project, include
8 | the following attribute:
9 |
10 | ```rust
11 | #![warn(missing_docs)]
12 | ```
13 |
14 | Now run `cargo doc` and examine the output. Here's a sample:
15 |
16 | ```text
17 | Documenting docdemo v0.1.0 (/Users/username/docdemo)
18 | warning: missing documentation for the crate
19 | --> src/main.rs:1:1
20 | |
21 | 1 | / #![warn(missing_docs)]
22 | 2 | |
23 | 3 | | fn main() {
24 | 4 | | println!("Hello, world!");
25 | 5 | | }
26 | | |_^
27 | |
28 | note: the lint level is defined here
29 | --> src/main.rs:1:9
30 | |
31 | 1 | #![warn(missing_docs)]
32 | | ^^^^^^^^^^^^
33 |
34 | warning: 1 warning emitted
35 |
36 | Finished dev [unoptimized + debuginfo] target(s) in 2.96s
37 | ```
38 |
39 | As a library author, adding the lint `#![deny(missing_docs)]` is a great way to
40 | ensure the project does not drift away from being documented well, and
41 | `#![warn(missing_docs)]` is a good way to move towards comprehensive
42 | documentation. In addition to docs, `#![deny(missing_doc_code_examples)]`
43 | ensures each function contains a usage example. In our example above, the
44 | warning is resolved by adding crate level documentation.
45 |
46 | There are more lints in the upcoming chapter [Lints][rustdoc-lints].
47 |
48 | ## Examples
49 |
50 | Of course this is contrived to be simple, but part of the power of documentation
51 | is showing code that is easy to follow, rather than being realistic. Docs often
52 | take shortcuts with error handling because examples can become complicated to
53 | follow with all the necessary set up required for a simple example.
54 |
55 | `Async` is a good example of this. In order to execute an `async` example, an
56 | executor needs to be available. Examples will often shortcut this, and leave
57 | users to figure out how to put the `async` code into their own runtime.
58 |
59 | It is preferred that `unwrap()` not be used inside an example, and some of the
60 | error handling components be hidden if they make the example too difficult to
61 | follow.
62 |
63 | ``````text
64 | /// Example
65 | /// ```rust
66 | /// let fourtytwo = "42".parse::()?;
67 | /// println!("{} + 10 = {}", fourtytwo, fourtytwo+10);
68 | /// ```
69 | ``````
70 |
71 | When rustdoc wraps that in a main function, it will fail to compile because the
72 | `ParseIntError` trait is not implemented. In order to help both your audience
73 | and your test suite, this example needs some additional code:
74 |
75 | ``````text
76 | /// Example
77 | /// ```rust
78 | /// # main() -> Result<(), std::num::ParseIntError> {
79 | /// let fortytwo = "42".parse::()?;
80 | /// println!("{} + 10 = {}", fortytwo, fortytwo+10);
81 | /// # Ok(())
82 | /// # }
83 | /// ```
84 | ``````
85 |
86 | The example is the same on the doc page, but has that extra information
87 | available to anyone trying to use your crate. More about tests in the
88 | upcoming [Documentation tests] chapter.
89 |
90 | ## What to Exclude
91 |
92 | Certain parts of your public interface may be included by default in the output
93 | of rustdoc. The attribute `#[doc(hidden)]` can hide implementation details
94 | to encourage idiomatic use of the crate.
95 |
96 | For example, an internal `macro!` that makes the crate easier to implement can
97 | become a footgun for users when it appears in the public documentation. An
98 | internal `Error` type may exist, and `impl` details should be hidden, as
99 | detailed in the [API Guidelines].
100 |
101 | ## Customizing the output
102 |
103 | It is possible to pass a custom css file to `rustdoc` and style the
104 | documentation.
105 |
106 | ```bash
107 | rustdoc --extend-css custom.css src/lib.rs
108 | ```
109 |
110 | A good example of using this feature to create a dark theme is documented [on
111 | this blog]. Just remember, dark theme is already included in the rustdoc output
112 | by clicking on the paintbrush. Adding additional options to the themes are
113 | as easy as creating a custom theme `.css` file and using the following syntax:
114 |
115 | ```bash
116 | rustdoc --theme awesome.css src/lib.rs
117 | ```
118 |
119 | Here is an example of a new theme, [Ayu].
120 |
121 | [Ayu]: https://github.com/rust-lang/rust/blob/master/src/librustdoc/html/static/themes/ayu.css
122 | [API Guidelines]: https://rust-lang.github.io/api-guidelines/documentation.html#rustdoc-does-not-show-unhelpful-implementation-details-c-hidden
123 | [Documentation tests]: documentation-tests.md
124 | [on this blog]: https://blog.guillaume-gomez.fr/articles/2016-09-16+Generating+doc+with+rustdoc+and+a+custom+theme
125 | [rustdoc-lints]: lints.md
126 |
--------------------------------------------------------------------------------
/language.js:
--------------------------------------------------------------------------------
1 | (function () {
2 | var url = window.location.href;
3 | var host = window.location.host;
4 | var home_url = window.location.protocol + '//' + window.location.host;
5 |
6 | var search = {
7 | en: "/en/",
8 | zh_CN: "/zh-CN/"
9 | }
10 |
11 | var replaceWith = {
12 | en: "/zh-CN/",
13 | zh_CN: "/en/"
14 | }
15 |
16 | var link = "";
17 | var word = "";
18 | var home = "Home";
19 | var lang = "zh-CN";
20 | var changeLang = "切换到英语";
21 |
22 | if (url.indexOf(search.en) != -1 && url.indexOf(search.en) === (url.indexOf(host) + host.length)) {
23 | link = url.replace(search.en, replaceWith.en);
24 | word = "简体中文";
25 | lang = "en";
26 | changeLang = "Switch to Chinese"
27 | } else if (url.indexOf(search.zh_CN) != -1 && url.indexOf(search.zh_CN) === (url.indexOf(host) + host.length)) {
28 | link = url.replace(search.zh_CN, replaceWith.zh_CN);
29 | word = "English";
30 | home = "首页";
31 | }
32 |
33 | var edit_id = document.getElementById("git-edit-button");
34 | if (edit_id != null && edit_id.parentNode != null) {
35 | edit_id.parentNode.target = "_blank";
36 | if (lang != "en") {
37 | edit_id.parentNode.title = "报告错误或改进本页翻译";
38 | }
39 | }
40 |
41 | var home_node = '';
42 | if (window.location.protocol == 'http:' || window.location.protocol == 'https:') {
43 | home_node = '';
44 | }
45 | var lang_node = '';
46 | if (link != '') {
47 | lang_node = ' ' + word + '';
48 | }
49 | var insertNode = document.getElementsByClassName('right-buttons');
50 | if (insertNode.length > 0) {
51 | var html = insertNode[0].innerHTML;
52 | insertNode[0].innerHTML = home_node + html + lang_node;
53 | }
54 | })()
55 |
--------------------------------------------------------------------------------
/src/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # The Rustdoc Book
2 |
3 | - [什么是 rustdoc?](what-is-rustdoc.md)
4 | - [如何阅读 rustdoc 的输出](how-to-read-rustdoc.md)
5 | - [如何写文档](how-to-write-documentation.md)
6 | - [什么被包含(和排除)](what-to-include.md)
7 | - [命令行参数](command-line-arguments.md)
8 | - [`#[doc]` 属性](the-doc-attribute.md)
9 | - [文档测试](documentation-tests.md) todo
10 | - [通过 items 名称链接](linking-to-items-by-name.md)
11 | - [Lints](lints.md)
12 | - [高级特性](advanced-features.md)
13 | - [不稳定特性](unstable-features.md)
14 | - [Website features](website-features.md)
15 | - [Passes](passes.md)
16 | - [References](references.md)
17 |
--------------------------------------------------------------------------------
/src/advanced-features.md:
--------------------------------------------------------------------------------
1 | # 高级特性
2 |
3 | 本页列出的特性不属于其他的主要类别
4 |
5 | ## `#[cfg(doc)]`: 文档平台相关或者特性相关信息
6 |
7 | 对于条件编译,rustdoc 会与编译器相同的方式处理。只生成目标主机可用的文档,其他的被 “过滤掉”。当对于不同目标提供不同的东西并且你希望文档反映你所有的可用项目,这可能会有问题。
8 |
9 | 如果你希望确保 rustdoc 可以看到某个 item,而忽略目标的平台相关信息,你可以使用 `#[cfg(doc)]`。Rustdoc 会在构建文档时设置它,所以使用了这个的 item 会确保生成到文档中,比如 `#[cfg(any(windows, doc))]` 会在 Windows 上构建以及生成所有的文档。
10 |
11 | 请注意 `cfg` 不会传递到文档测试中。
12 |
13 | 比如:
14 |
15 | ```rust
16 | /// Token struct that can only be used on Windows.
17 | #[cfg(any(windows, doc))]
18 | pub struct WindowsToken;
19 | /// Token struct that can only be used on Unix.
20 | #[cfg(any(unix, doc))]
21 | pub struct UnixToken;
22 | ```
23 |
24 | 这里,各自的 tokens 只能在各自的平台上使用,但是会同时出现在文档中。
25 |
26 | ### 特定平台文档之间的交互
27 |
28 | Rustdoc 没有什么如同你在每种平台运行一次的魔法方法来编译文档(这种魔法方式被称为 ['holy grail of rustdoc'][#1998])。代替的是,会一次读到你**所有的**代码,与 Rust 编译器通过参数 `--cfg doc` 读到的一样。但是,Rustdoc 有一个技巧可以在接收到特定平台代码时处理它。
29 |
30 | 为你的 crate 生成文档,Rustdoc 只需要知道你的公共函数签名。尤其是,不需要知道你的函数实现,所以会忽略所有函数体类型错误和名称解析错误。注意,这不适用函数体之外的东西:因为 Rustdoc 会记录类型,需要知道类型是什么。比如,无论平台如何,这些代码可以工作:
31 |
32 | ```rust,ignore (platform-specific,rustdoc-specific-behavior)
33 | pub fn f() {
34 | use std::os::windows::ffi::OsStrExt;
35 | }
36 | ```
37 |
38 | 但是这些不行,因为函数签名中存在为止类型:
39 |
40 | ```rust,ignore (platform-specific,rustdoc-specific-behavior)
41 | pub fn f() -> std::os::windows::ffi::EncodeWide<'static> {
42 | unimplemented!()
43 | }
44 | ```
45 |
46 | 更多的代码示例,请参考 [the rustdoc test suite][realistic-async]。
47 |
48 | [#1998]: https://github.com/rust-lang/rust/issues/1998
49 | [realistic-async]: https://github.com/rust-lang/rust/blob/b146000e910ccd60bdcde89363cb6aa14ecc0d95/src/test/rustdoc-ui/error-in-impl-trait/realistic-async.rs
50 |
51 | ## 增加文档搜索的 item 别名
52 |
53 | 这个特性可以通过 `doc(alias)` 属性增加 `rustdoc` 搜索 item 的别名。比如:
54 |
55 | ```rust,no_run
56 | #[doc(alias = "x")]
57 | #[doc(alias = "big")]
58 | pub struct BigX;
59 | ```
60 |
61 | 然后,当搜索时,你可以输入 "x" 或者 "big",搜索结果优先显示 `BigX` 结构。
62 |
63 | 文档别名也有一些限制:你不能使用 `"` 或者空格。
64 |
65 | 你可以使用列表一次增加多个别名:
66 |
67 | ```rust,no_run
68 | #[doc(alias("x", "big"))]
69 | pub struct BigX;
70 | ```
71 |
--------------------------------------------------------------------------------
/src/command-line-arguments.md:
--------------------------------------------------------------------------------
1 | # Command-line arguments
2 |
3 | 这里是可以传递给 `rustdoc` 的参数列表:
4 |
5 | ## `-h`/`--help`: help
6 |
7 | 这样使用:
8 |
9 | ```bash
10 | $ rustdoc -h
11 | $ rustdoc --help
12 | ```
13 |
14 | 这会展示 `rustdoc` 内置的帮助,包含了大量可用的命令行 flags。
15 |
16 | 有些 flags 是未稳定的;这个页面只会只包好稳定的参数,`--help` 会包含所有的。
17 |
18 | ## `-V`/`--version`: version information
19 |
20 | 使用该flag的方式如下:
21 |
22 | ```bash
23 | $ rustdoc -V
24 | $ rustdoc --version
25 | ```
26 |
27 | 这将显示 `rustdoc` 的版本,如下所示:
28 |
29 | ```text
30 | rustdoc 1.17.0 (56124baa9 2017-04-24)
31 | ```
32 |
33 | ## `-v`/`--verbose`: more verbose output
34 |
35 | 使用该flag的方式如下:
36 |
37 | ```bash
38 | $ rustdoc -v src/lib.rs
39 | $ rustdoc --verbose src/lib.rs
40 | ```
41 |
42 | 这将启用 "冗长模式",即会将更多信息写入标准输出。
43 | 写入的内容取决于你传入的其它标志。
44 | 例如,使用 `--version`:
45 |
46 | ```text
47 | $ rustdoc --verbose --version
48 | rustdoc 1.17.0 (56124baa9 2017-04-24)
49 | binary: rustdoc
50 | commit-hash: hash
51 | commit-date: date
52 | host: host-triple
53 | release: 1.17.0
54 | LLVM version: 3.9
55 | ```
56 |
57 | ## `-o`/`--out-dir`: output directory path
58 |
59 | 使用该flag的方式如下:
60 |
61 | ```bash
62 | $ rustdoc src/lib.rs -o target/doc
63 | $ rustdoc src/lib.rs --out-dir target/doc
64 | ```
65 |
66 | 默认情况下,`rustdoc` 的输出会出现在当前工作目录下名为 `doc` 的目录中。
67 | 使用此标记后,它将把所有输出到你指定的目录。
68 |
69 | ## `--crate-name`: controlling the name of the crate
70 |
71 | 使用该flag的方式如下:
72 |
73 | ```bash
74 | $ rustdoc src/lib.rs --crate-name mycrate
75 | ```
76 |
77 | 默认情况下,"rustdoc"会假定你的 crate 名称与".rs "文件相同。
78 | 您可以使用 `--crate-name` 来覆盖这一假设。
79 |
80 | ## `--document-private-items`: Show items that are not public
81 |
82 | 使用该flag的方式如下:
83 |
84 | ```bash
85 | $ rustdoc src/lib.rs --document-private-items
86 | ```
87 |
88 | 默认情况下,`rustdoc` 只记录可公开访问的项目。
89 |
90 | ```rust
91 | pub fn public() {} // this item is public and will be documented
92 | mod private { // this item is private and will not be documented
93 | pub fn unreachable() {} // this item is public, but unreachable, so it will not be documented
94 | }
95 | ```
96 |
97 | `--document-private-items` documents all items, even if they're not public.
98 |
99 | ## `-L`/`--library-path`: where to look for dependencies
100 |
101 | 使用该flag的方式如下:
102 |
103 | ```bash
104 | $ rustdoc src/lib.rs -L target/debug/deps
105 | $ rustdoc src/lib.rs --library-path target/debug/deps
106 | ```
107 |
108 | 如果你的 crate 有依赖库,`rustdoc` 需要知道在哪里可以找到它们。
109 | 传递 `--library-path` 会给 `rustdoc` 提供一个查找这些依赖项的列表。
110 |
111 | 这个标志可以接受任意数量的目录作为参数,并在搜索时使用所有的目录。
112 |
113 | ## `--cfg`: passing configuration flags
114 |
115 | 使用该flag的方式如下:
116 |
117 | ```bash
118 | $ rustdoc src/lib.rs --cfg feature="foo"
119 | ```
120 |
121 | 该flag接受与 `rustc --cfg` 相同的值,并用它来配置编译。
122 | 上面的例子使用了 `feature`,但任何 `cfg` 值都可以接受。
123 |
124 | ## `--extern`: specify a dependency's location
125 |
126 | 使用该flag的方式如下:
127 |
128 | ```bash
129 | $ rustdoc src/lib.rs --extern lazy-static=/path/to/lazy-static
130 | ```
131 |
132 | 与"--library-path "类似,"--extern "是关于指定的位置。
133 | library-path "提供了搜索目录,而"--extern则可以让你精
134 | 确地指定依赖项的位置。
135 |
136 | ## `-C`/`--codegen`: pass codegen options to rustc
137 |
138 | 使用该flag的方式如下:
139 |
140 | ```bash
141 | $ rustdoc src/lib.rs -C target_feature=+avx
142 | $ rustdoc src/lib.rs --codegen target_feature=+avx
143 |
144 | $ rustdoc --test src/lib.rs -C target_feature=+avx
145 | $ rustdoc --test src/lib.rs --codegen target_feature=+avx
146 |
147 | $ rustdoc --test README.md -C target_feature=+avx
148 | $ rustdoc --test README.md --codegen target_feature=+avx
149 | ```
150 |
151 | 当 rustdoc 生成文档、查找文档测试或执行文档测试时,它需要编译一些 rust 代码,至少是部分编译。
152 | 测试时,需要编译一些 rust 代码,至少是部分编译。这个flag允许你告诉 rustdoc
153 | 在运行这些编译时向 rustc 提供一些额外的 codegen 选项。
154 | 大多数情况下这些选项不会影响正常的文档运行,但如果某些内容依赖于目标特性
155 | 或者文档测试需要使用一些额外的选项,这个flag允许你影响。
156 |
157 | 该标志的参数与 rustc 的 `-C` 标志相同。运行 `rustc -C help` 以
158 | 获得完整的列表。
159 |
160 | ## `--test`: run code examples as tests
161 |
162 | 使用该flag的方式如下:
163 |
164 | ```bash
165 | $ rustdoc src/lib.rs --test
166 | ```
167 |
168 | 该flag将把你的代码示例作为测试运行。更多信息,请参阅(document-tests.md)。
169 |
170 | 另请参阅 `--test-args`。
171 |
172 | ## `--test-args`: pass options to test runner
173 |
174 | 使用该flag的方式如下:
175 |
176 | ```bash
177 | $ rustdoc src/lib.rs --test --test-args ignored
178 | ```
179 |
180 | 运行文档测试时,该flag将向测试运行器传递选项。
181 | 更多信息,请参阅(document-tests.md)。
182 |
183 | 另请参阅 `--test`。
184 |
185 | ## `--target`: generate documentation for the specified target triple
186 |
187 | 使用该flag的方式如下:
188 |
189 | ```bash
190 | $ rustdoc src/lib.rs --target x86_64-pc-windows-gnu
191 | ```
192 |
193 | 与 `rustc` 的 `--target` 标志类似,它会为与主机三元组不同的目标三元组生成文档。
194 |
195 | 交叉编译代码的所有常见注意事项均适用。
196 |
197 | ## `--default-theme`: set the default theme
198 |
199 | Using this flag looks like this:
200 |
201 | ```bash
202 | $ rustdoc src/lib.rs --default-theme=ayu
203 | ```
204 |
205 | Sets the default theme (for users whose browser has not remembered a
206 | previous theme selection from the on-page theme picker).
207 |
208 | The supplied value should be the lowercase version of the theme name.
209 | The set of available themes can be seen in the theme picker in the
210 | generated output.
211 |
212 | Note that the set of available themes - and their appearance - is not
213 | necessarily stable from one rustdoc version to the next. If the
214 | requested theme does not exist, the builtin default (currently
215 | `light`) is used instead.
216 |
217 | ## `--markdown-css`: include more CSS files when rendering markdown
218 |
219 | Using this flag looks like this:
220 |
221 | ```bash
222 | $ rustdoc README.md --markdown-css foo.css
223 | ```
224 |
225 | When rendering Markdown files, this will create a `` element in the
226 | `` section of the generated HTML. For example, with the invocation above,
227 |
228 | ```html
229 |
230 | ```
231 |
232 | will be added.
233 |
234 | When rendering Rust files, this flag is ignored.
235 |
236 | ## `--html-in-header`: include more HTML in
237 |
238 | Using this flag looks like this:
239 |
240 | ```bash
241 | $ rustdoc src/lib.rs --html-in-header header.html
242 | $ rustdoc README.md --html-in-header header.html
243 | ```
244 |
245 | This flag takes a list of files, and inserts them into the `` section of
246 | the rendered documentation.
247 |
248 | ## `--html-before-content`: include more HTML before the content
249 |
250 | Using this flag looks like this:
251 |
252 | ```bash
253 | $ rustdoc src/lib.rs --html-before-content extra.html
254 | $ rustdoc README.md --html-before-content extra.html
255 | ```
256 |
257 | This flag takes a list of files, and inserts them inside the `` tag but
258 | before the other content `rustdoc` would normally produce in the rendered
259 | documentation.
260 |
261 | ## `--html-after-content`: include more HTML after the content
262 |
263 | Using this flag looks like this:
264 |
265 | ```bash
266 | $ rustdoc src/lib.rs --html-after-content extra.html
267 | $ rustdoc README.md --html-after-content extra.html
268 | ```
269 |
270 | This flag takes a list of files, and inserts them before the `` tag but
271 | after the other content `rustdoc` would normally produce in the rendered
272 | documentation.
273 |
274 | ## `--markdown-playground-url`: control the location of the playground
275 |
276 | Using this flag looks like this:
277 |
278 | ```bash
279 | $ rustdoc README.md --markdown-playground-url https://play.rust-lang.org/
280 | ```
281 |
282 | When rendering a Markdown file, this flag gives the base URL of the Rust
283 | Playground, to use for generating `Run` buttons.
284 |
285 | ## `--markdown-no-toc`: don't generate a table of contents
286 |
287 | Using this flag looks like this:
288 |
289 | ```bash
290 | $ rustdoc README.md --markdown-no-toc
291 | ```
292 |
293 | When generating documentation from a Markdown file, by default, `rustdoc` will
294 | generate a table of contents. This flag suppresses that, and no TOC will be
295 | generated.
296 |
297 | ## `-e`/`--extend-css`: extend rustdoc's CSS
298 |
299 | Using this flag looks like this:
300 |
301 | ```bash
302 | $ rustdoc src/lib.rs -e extra.css
303 | $ rustdoc src/lib.rs --extend-css extra.css
304 | ```
305 |
306 | With this flag, the contents of the files you pass are included at the bottom
307 | of Rustdoc's `theme.css` file.
308 |
309 | While this flag is stable, the contents of `theme.css` are not, so be careful!
310 | Updates may break your theme extensions.
311 |
312 | ## `--sysroot`: override the system root
313 |
314 | Using this flag looks like this:
315 |
316 | ```bash
317 | $ rustdoc src/lib.rs --sysroot /path/to/sysroot
318 | ```
319 |
320 | Similar to `rustc --sysroot`, this lets you change the sysroot `rustdoc` uses
321 | when compiling your code.
322 |
323 | ### `--edition`: control the edition of docs and doctests
324 |
325 | Using this flag looks like this:
326 |
327 | ```bash
328 | $ rustdoc src/lib.rs --edition 2018
329 | $ rustdoc --test src/lib.rs --edition 2018
330 | ```
331 |
332 | This flag allows `rustdoc` to treat your rust code as the given edition. It will compile doctests with
333 | the given edition as well. As with `rustc`, the default edition that `rustdoc` will use is `2015`
334 | (the first edition).
335 |
336 | ## `--theme`: add a theme to the documentation output
337 |
338 | Using this flag looks like this:
339 |
340 | ```bash
341 | $ rustdoc src/lib.rs --theme /path/to/your/custom-theme.css
342 | ```
343 |
344 | `rustdoc`'s default output includes two themes: `light` (the default) and
345 | `dark`. This flag allows you to add custom themes to the output. Giving a CSS
346 | file to this flag adds it to your documentation as an additional theme choice.
347 | The theme's name is determined by its filename; a theme file named
348 | `custom-theme.css` will add a theme named `custom-theme` to the documentation.
349 |
350 | ## `--check-theme`: verify custom themes against the default theme
351 |
352 | Using this flag looks like this:
353 |
354 | ```bash
355 | $ rustdoc --check-theme /path/to/your/custom-theme.css
356 | ```
357 |
358 | While `rustdoc`'s HTML output is more-or-less consistent between versions, there
359 | is no guarantee that a theme file will have the same effect. The `--theme` flag
360 | will still allow you to add the theme to your documentation, but to ensure that
361 | your theme works as expected, you can use this flag to verify that it implements
362 | the same CSS rules as the official `light` theme.
363 |
364 | `--check-theme` is a separate mode in `rustdoc`. When `rustdoc` sees the
365 | `--check-theme` flag, it discards all other flags and only performs the CSS rule
366 | comparison operation.
367 |
368 | ### `--crate-version`: control the crate version
369 |
370 | Using this flag looks like this:
371 |
372 | ```bash
373 | $ rustdoc src/lib.rs --crate-version 1.3.37
374 | ```
375 |
376 | When `rustdoc` receives this flag, it will print an extra "Version (version)" into the sidebar of
377 | the crate root's docs. You can use this flag to differentiate between different versions of your
378 | library's documentation.
379 |
380 | ## `@path`: load command-line flags from a path
381 |
382 | If you specify `@path` on the command-line, then it will open `path` and read
383 | command line options from it. These options are one per line; a blank line indicates
384 | an empty option. The file can use Unix or Windows style line endings, and must be
385 | encoded as UTF-8.
386 |
387 | ## `--passes`: add more rustdoc passes
388 |
389 | This flag is **deprecated**.
390 | For more details on passes, see [the chapter on them](passes.md).
391 |
392 | ## `--no-defaults`: don't run default passes
393 |
394 | This flag is **deprecated**.
395 | For more details on passes, see [the chapter on them](passes.md).
396 |
397 | ## `-r`/`--input-format`: input format
398 |
399 | This flag is **deprecated** and **has no effect**.
400 |
401 | Rustdoc only supports Rust source code and Markdown input formats. If the
402 | file ends in `.md` or `.markdown`, `rustdoc` treats it as a Markdown file.
403 | Otherwise, it assumes that the input file is Rust.
404 |
405 | ## `--nocapture`
406 |
407 | When this flag is used with `--test`, the output (stdout and stderr) of your tests won't be
408 | captured by rustdoc. Instead, the output will be directed to your terminal,
409 | as if you had run the test executable manually. This is especially useful
410 | for debugging your tests!
411 |
--------------------------------------------------------------------------------
/src/documentation-tests.md:
--------------------------------------------------------------------------------
1 | # 文档测试
2 |
3 | `rustdoc` 支持将你文档中的代码示例作为测试执行。这确保了文档中的代码示例保持更新。
4 |
5 | 基本写法是这样的:
6 |
7 | ```rust,no_run
8 | /// # Examples
9 | ///
10 | /// ```
11 | /// let x = 5;
12 | /// ```
13 | # fn f() {}
14 | ```
15 |
16 | 三个反引号中的代码块。如果有一个文件名叫做`foo.rs`,运行`rustdoc --test foo.rs`会提取这个例子,然后作为测试执行。
17 |
18 | 需要注意的是,如果代码块没有设置语言,rustdoc 默认是 Rust 代码,所以下面的:
19 |
20 | ````markdown
21 | ```rust
22 | let x = 5;
23 | ```
24 | ````
25 |
26 | 跟这个是相等的
27 |
28 | ````markdown
29 | ```
30 | let x = 5;
31 | ```
32 | ````
33 |
34 | 还有一些微妙之处!请阅读获得更多详情。
35 |
36 | ## 文档测试通过或者失败
37 |
38 | 就像常规的单元测试,常规的文档测试也需要编译和运行“通过”。所以如果需要计算给出一个结果,可以使用`assert!`系列宏来检查:
39 |
40 | ```rust
41 | let foo = "foo";
42 | assert_eq!(foo, "foo");
43 | ```
44 |
45 | 这样,如果计算返回的结果不符合预期,代码就会 panic,文档测试会失败。
46 |
47 | ## 预处理例子
48 |
49 | 在上面的例子中,你注意到奇怪的事情:没有`main`函数!如果强制你为每个例子写`main`,增加了难度。
50 | 所以`rustdoc`在运行例子前会帮你处理好这个。这里是`rustdoc`预处理的完整算法:
51 |
52 | 1. 一些常用的 `allow` 属性会被插入,包括 `unused_variables`, `unused_assignments`, `unused_mut`, `unused_attributes`, 和 `dead_code`。小型示例经常出发这些警告。
53 | 2. 如果存在 `#![doc(test(attr(...)))]` 的属性会被加入。
54 | 3. `#![foo]` 属性会被作为 crate 属性保留。
55 | 4. 如果例子不包含 `extern crate`, 并且 `#![doc(test(no_crate_inject))]` 没有被指定,`extern crate ;` 被插入(注意 `#[macro_use]` 要手动写一般)。
56 | 5. 最后,如果例子不包含 `fn main`,剩下的代码会被 main 函数 wrap:`fn main() { your_code }`。
57 |
58 | 对于第 4 条的详细解释,请阅读下面的“宏的文档”
59 |
60 | ## 隐藏例子的一部分
61 |
62 | 有时,你需要一些初始代码,或者一些会分散文档注意力的代码,但是它们对测试工作是必要的。考虑下面的示例代码:
63 |
64 | ```rust,no_run
65 | /// ```
66 | /// /// Some documentation.
67 | /// # fn foo() {} // this function will be hidden
68 | /// println!("Hello, World!");
69 | /// ```
70 | # fn f() {}
71 | ```
72 |
73 | 会渲染为:
74 |
75 | ```rust
76 | /// Some documentation.
77 | # fn foo() {}
78 | println!("Hello, World!");
79 | ```
80 |
81 | 没错,这是对的,你可以加一些以 `# ` 开头的行,在输出中它们会隐藏,但是编译代码会用到。你可以利用这一点。在这个例子中,文档注释需要使用函数,但是我只想给你看文档注释,我需要加入函数的定义。同时,需要满足编译器编译,而隐藏这部分代码使得示例更清晰。你可以使用这个技术写出详细的示例代码并且保留你的可测试性文档。
82 |
83 | 比如,想象我们想要给这些代码写文档:
84 |
85 | ```rust
86 | let x = 5;
87 | let y = 6;
88 | println!("{}", x + y);
89 | ```
90 |
91 | 文档注释最终可能是这样的:
92 |
93 | > First, we set `x` to five:
94 | >
95 | > ```rust
96 | > let x = 5;
97 | > # let y = 6;
98 | > # println!("{}", x + y);
99 | > ```
100 | >
101 | > Next, we set `y` to six:
102 | >
103 | > ```rust
104 | > # let x = 5;
105 | > let y = 6;
106 | > # println!("{}", x + y);
107 | > ```
108 | >
109 | > Finally, we print the sum of `x` and `y`:
110 | >
111 | > ```rust
112 | > # let x = 5;
113 | > # let y = 6;
114 | > println!("{}", x + y);
115 | > ```
116 |
117 | 为了保持每个代码块可测试,我们要在每个代码块都有完整代码,但是我们不想文档读者每次都看到全部行代码:
118 |
119 | ````markdown
120 | First, we set `x` to five:
121 |
122 | ```
123 | let x = 5;
124 | # let y = 6;
125 | # println!("{}", x + y);
126 | ```
127 |
128 | Next, we set `y` to six:
129 |
130 | ```
131 | # let x = 5;
132 | let y = 6;
133 | # println!("{}", x + y);
134 | ```
135 |
136 | Finally, we print the sum of `x` and `y`:
137 |
138 | ```
139 | # let x = 5;
140 | # let y = 6;
141 | println!("{}", x + y);
142 | ```
143 | ````
144 |
145 | 通过复制例子的所有代码,例子可以通过编译,同时使用 `# ` 在文档中有些部分被隐藏。
146 |
147 | `#` 的隐藏可以使用两个 `##` 来消除。 如果我们有一行注释,以 `#` 开头,那么这样写:
148 |
149 | ```rust
150 | let s = "foo
151 | ## bar # baz";
152 | ```
153 |
154 | 我们可以转义第一个 `#` 来注释它:
155 |
156 | ```text
157 | /// let s = "foo
158 | /// ## bar # baz";
159 | ```
160 |
161 | ## 在文档测试中使用 `?`
162 |
163 | 当写例子时,很少会包含完整的错误处理,因为错误处理会增加很多样板代码。取而代之,你可能更希望这样:
164 |
165 | ```rust,no_run
166 | /// ```
167 | /// use std::io;
168 | /// let mut input = String::new();
169 | /// io::stdin().read_line(&mut input)?;
170 | /// ```
171 | # fn f() {}
172 | ```
173 |
174 | 问题是 `?` 返回 `Result`,测试函数不能返回任何东西,所以会有类型错误。
175 |
176 | 你可以通过自己增加返回 `Result` 的 `main` 函数来规避这个限制,因为 `Result` 实现了 `Termination` trait:
177 |
178 | ```rust,no_run
179 | /// A doc test using ?
180 | ///
181 | /// ```
182 | /// use std::io;
183 | ///
184 | /// fn main() -> io::Result<()> {
185 | /// let mut input = String::new();
186 | /// io::stdin().read_line(&mut input)?;
187 | /// Ok(())
188 | /// }
189 | /// ```
190 | # fn f() {}
191 | ```
192 |
193 | 与下节的 `# `一起,你可以得到读者舒服,编译通过的完整解决方案:
194 |
195 | ```rust,no_run
196 | /// ```
197 | /// use std::io;
198 | /// # fn main() -> io::Result<()> {
199 | /// let mut input = String::new();
200 | /// io::stdin().read_line(&mut input)?;
201 | /// # Ok(())
202 | /// # }
203 | /// ```
204 | # fn f() {}
205 | ```
206 |
207 | 从 1.34.0 版本开始,也可以省略 `fn main()`,但是你必须消除错误类型的歧义:
208 |
209 | ```rust,no_run
210 | /// ```
211 | /// use std::io;
212 | /// let mut input = String::new();
213 | /// io::stdin().read_line(&mut input)?;
214 | /// # Ok::<(), io::Error>(())
215 | /// ```
216 | # fn f() {}
217 | ```
218 |
219 | 这是 `?` 操作符隐式转换带来的不便,因为类型不唯一所以类型推断会出错。你必须写 `(())`,`rustdoc` 才能理解你想要一个隐式返回值 `Result` 的函数。
220 |
221 | ## 在文档测试中显示警告
222 |
223 | 你可以通过运行 `rustdoc --test --test-args=--show-output` 在文档测试中显示警告(或者,如果你使用 cargo,`cargo test --doc -- --show-output` 也可以)。默认会隐藏 `unused` 警告,因为很多例子使用私有函数;你可以通过在例子顶部加入`#![warn(unused)]`来对没有使用的变量或者死代码进行警告。你还可以在 crate 根使用 [`#![doc(test(attr(warn(unused))))]`][test-attr] 开启全局警告。
224 |
225 | [test-attr]: ./the-doc-attribute.md#testattr
226 |
227 | ## 宏的文档
228 |
229 | 这里是一个宏的文档的例子:
230 |
231 | ```rust
232 | /// Panic with a given message unless an expression evaluates to true.
233 | ///
234 | /// # Examples
235 | ///
236 | /// ```
237 | /// # #[macro_use] extern crate foo;
238 | /// # fn main() {
239 | /// panic_unless!(1 + 1 == 2, “Math is broken.”);
240 | /// # }
241 | /// ```
242 | ///
243 | /// ```should_panic
244 | /// # #[macro_use] extern crate foo;
245 | /// # fn main() {
246 | /// panic_unless!(true == false, “I’m broken.”);
247 | /// # }
248 | /// ```
249 | #[macro_export]
250 | macro_rules! panic_unless {
251 | ($condition:expr, $($rest:expr),+) => ({ if ! $condition { panic!($($rest),+); } });
252 | }
253 | # fn main() {}
254 | ```
255 |
256 | 你注意到三件事:我们需要自己增加 `extern crate` 一行,从而我们可以加上 `#[macro_use]` 属性。第二,我们需要自己增加 `main()`,理由同上。最后 `#` 的使用使得一些内容不会出现在输出中。
257 |
258 | ## 属性
259 |
260 | 代码块可以通过属性标注帮助 `rustdoc` 在测试例子代码时处理正确。
261 |
262 | `ignore` 属性告诉 Rust 忽略你的代码。 这个属性很通用,并且考虑标注 `文本`或者使用`#`隐藏不想展示的部分。
263 |
264 | ```rust
265 | /// ```ignore
266 | /// fn foo() {
267 | /// ```
268 | # fn foo() {}
269 | ```
270 |
271 | `should_panic` 告诉 `rustdoc` 代码应该编译通过但是运行时会 panic。如果代码没有 panic,测试失败。
272 |
273 | ```rust
274 | /// ```should_panic
275 | /// assert!(false);
276 | /// ```
277 | # fn foo() {}
278 | ```
279 |
280 | `no_run` 属性会编译你的代码但是不运行它。这对于类似 "如果获取网页" 的例子很重要,你要确保它能编译但是不想在运行测试,因为测试环境可能没有网络。这个属性也可以被用来要求代码段有未定义行为。
281 |
282 | ```rust
283 | /// ```no_run
284 | /// loop {
285 | /// println!("Hello, world");
286 | /// }
287 | /// ```
288 | # fn foo() {}
289 | ```
290 |
291 | `compile_fail` 告诉 `rustdoc` 应该编译失败。如果便已通过,测试失败。
292 | 但是需要注意现在版本 Rust 编译失败可能在将来 Rust 版本编译成功。
293 |
294 | ```rust
295 | /// ```compile_fail
296 | /// let x = 5;
297 | /// x += 2; // shouldn't compile!
298 | /// ```
299 | # fn foo() {}
300 | ```
301 |
302 | `edition2015`, `edition2018` 和 `edition2021` 告诉 `rustdoc` 代码应该使用哪个 edition 版本的 Rust 来编译。
303 |
304 | ```rust
305 | /// Only runs on the 2018 edition.
306 | ///
307 | /// ```edition2018
308 | /// let result: Result = try {
309 | /// "1".parse::()?
310 | /// + "2".parse::()?
311 | /// + "3".parse::()?
312 | /// };
313 | /// ```
314 | # fn foo() {}
315 | ```
316 |
317 | ## 语法参考
318 |
319 | 代码块的 *exact* 语法,包括边缘情况,可以在 CommonMark 说明的 [Fenced Code Blocks] 一节找到。
320 |
321 | Rustdoc 也接受 *indented* 代码块作为 fenced 代码块的替代:不使用三个反引号,而是每行以四个或者以上空格开始。
322 |
323 | ```markdown
324 | let foo = "foo";
325 | assert_eq!(foo, "foo");
326 | ```
327 |
328 | 这也在 CommonMark 说明中的 [Indented Code Blocks](https://spec.commonmark.org/0.29/#indented-code-blocks) 小节。
329 |
330 | 但是通常更常用的是 fenced 代码块。不仅是 fenced 代码块更符合 Rust 惯用法,而且 indented 代码块无法使用诸如 `ignore` 或者 `should_panic` 这些属性。
331 |
332 | ### 收集文档测试时包含 item
333 |
334 | Rustdoc 文档测试可以做到一些单元测试无法做到的事,可以扩展你的文档测试但是不出现在文档中。意味着,rustdoc 允许你有不出现在
335 | 文档中,但是会进行文档测试的 item,所以你可以利用文档测试这个功能使测试不出现在文档中,或者任意找一个私有 item 包含它。
336 |
337 | 当编译 crate 用来测试文档时(使用`--test`),`rustdoc`会设置 `#[cfg(doctest)]`。注意这只会在公共 item 上设置;如果你需要测试私有 item,你需要写单元测试。
338 |
339 | 在这个例子中,我们增加不会编译的文档测试,确保我们的结构体只会获取有效数据:
340 |
341 | ```rust
342 | /// We have a struct here. Remember it doesn't accept negative numbers!
343 | pub struct MyStruct(pub usize);
344 |
345 | /// ```compile_fail
346 | /// let x = my_crate::MyStruct(-5);
347 | /// ```
348 | #[cfg(doctest)]
349 | pub struct MyStructOnlyTakesUsize;
350 | ```
351 |
352 | 注意结构 `MyStructOnlyTakesUsize` 不是你的 crate 公共 API。`#[cfg(doctest)]` 的使用使得这个结构体只会在 `rustdoc` 收集文档测试时存在。这意味着当传递 `--test` 给 rustdoc 时才存在,在公共文档中是隐藏的。
353 |
354 | 另一个可能用到 `#[cfg(doctest)]` 的是你的 README 文件中的文档测试。
355 | 比如你可以在 `lib.rs` 写下面的代码来运行 README 中的文档测试:
356 |
357 | ```rust,no_run
358 | #[doc = include_str!("../README.md")]
359 | #[cfg(doctest)]
360 | pub struct ReadmeDoctests;
361 | ```
362 |
363 | 这会在你的隐藏结构体 `ReadmeDoctests` 中包含你的 README 作为文档,也会作为文档测试来执行。
364 |
--------------------------------------------------------------------------------
/src/how-to-read-rustdoc.md:
--------------------------------------------------------------------------------
1 | # 如何阅读 rustdoc 的输出
2 |
3 | Rustdoc 的 HTML 文件包含了一个友好且有用的导航界面,使用户可以更轻松地导航和理解您的代码。本章涵盖了该界面的主要功能,对于文档作者和用户来说都是一个很好的的开端。
4 |
5 | ## 结构
6 |
7 | `rustdoc` 的输出包含三部分,左侧是整个页面的快速导航,展示了当前条目的上下文信息。页面的右侧大版面由顶部的搜索和下面的文档页面主体组成。
8 |
9 | ## Item 文档
10 |
11 | 屏幕的主要区域展示的是 item 的文档。
12 |
13 | 顶端是一览信息:
14 |
15 | - item 的类型和名称,比如 "Struct `std::time::Duration`";
16 | - 复制 crate 路径的按钮;
17 | - 展开和收起 item 顶层文档的按钮 (`[+]` or `[-]`);
18 | - 指向源代码 ([src]) 的链接如果[已配置](the-doc-attribute.html#html_no_source)并且存在,(如果通过 `cargo doc --no-deps` 创建文档)则源码可能无效;
19 | - 如果 item 是标准库,会展示 item 稳定的版本。
20 |
21 | 下面是 item 的主要文档,包括函数签名,Rust 类型的 fields 列表或者 variants。最后,该页面列出了关联函数以及 trait 实现,包括 `rustdoc` 知道的自动和空白实现。
22 |
23 | ### 导航
24 |
25 | subheadings,variants,fields 和文档中很多元素都是锚,可以被链接,这是可以准确传递你表达的好方法。当鼠标悬停或给定键盘焦点时,印刷符号 "§" 出现在带有锚点的行旁边。
26 |
27 | ## 导航栏
28 |
29 | 比如,当查看 crate 根文档的时候,会展示所有的 crate 文档的 modules,structs,traits,functions,macros 的快速链接。在顶部,它会在当前 crate 名称和版本旁边或者当前 item 旁边展示 [configurable logo](the-doc-attribute.html#html_logo_url)。
30 |
31 | ## 主题选择和搜索栏
32 |
33 | 当在支持 JavaScript 的浏览器中打开 `rustdoc` 的输出时,页面顶部会出现一个接口,左侧是主题选择(一个画笔图标),搜索栏,帮助提示和配置按钮。【译者注:主题选择已经在配置设置中】
34 |
35 | ### 主题选择
36 |
37 | 点击主题选择会列出可选主题,默认是 `ayu`, `light`, and `dark`。
38 |
39 | ### 搜索栏
40 |
41 | 在搜索栏输入内容,会模糊匹配搜索当前的文档
42 |
43 | 默认搜索结果显示按照名称的结果,意味着模糊匹配 item 的名称,匹配的名称显示在左侧,如果有描述会显示在右侧,点击 item,你会跳转到对应的页面
44 |
45 | 还有两种结果,按照参数搜索,展示函数参数中类型的匹配结果,按返回值搜索,展示函数返回值类型的搜索结构。这两种搜索结果在你不知道函数名称,但是知道你想要的类型时非常有用。
46 |
47 | 当在搜索栏输入时,可以通过冒号前缀来限制搜索结果的类型(比如 `mod:`)
48 |
49 | ### 快捷键
50 |
51 | 按下 `S` 焦点会移动到搜索框,按下 `?` 会展示帮助界面,其中包括所有快捷键以及说明。按下 `T` 焦点移动到主题选择。【译者注:主题选择通过搜索栏的右侧 setting 按钮唤出】
52 |
53 | 当焦点在搜索结果时,左右箭头可以切换搜索的 tab,上下箭头可以移动关注的搜索结果。按下回车键可以打开高亮的结果。
54 |
55 | 当焦点在 item 文档时,加号和减号可以展开收起文档的小结。
56 |
--------------------------------------------------------------------------------
/src/how-to-write-documentation.md:
--------------------------------------------------------------------------------
1 | # 如何写文档
2 |
3 | 好的文档并不自然。存在一些矛盾的目标使得写好文档很困难。即要求对领域很专业又要写出对新手很友好的文档。文档因此经常隐去一些细节,或者留给读者一些未解答的问题。
4 |
5 | Rust 文档有一些原则指导任何人来写文档,从而每个人都有机会来使用代码。
6 |
7 | 本章不仅覆盖如何编写文档,还介绍了如何写出**好**文档。尽可能清晰完整非常重要。根据经验:你编写的文档越多你的 crate 越好。如果 item 是公共的,就应该有文档。
8 |
9 | ## 开始
10 |
11 | 编写 crate 文档首先应该从首页开始。例如 [`hashbrown`] crate 级别的文档总结了这个 crate 的角色是什么,说明了使用的详细技术,以及为什么你需要这个 crate。
12 |
13 | 在介绍了 crate 之后,首页给出使用 crate 的代码示例很重要。在代码例子中展示库如何使用,不要使用裁剪过的代码,
14 | 使得用户可以直接复制粘贴就能运行。
15 |
16 | [`futures`] 使用内联注释逐行解释使用 [`Future`] 的复杂性,因为用户接触 rust 的 [`Future`] 的第一个例子可能就是这个。
17 |
18 | [`backtrace`] 文档描述了整个使用过程,说明了 `Cargo.toml` 文件应该如何修改,传递命令行参数给编译器,并展示了一个使用 backtrace 的例子。
19 |
20 | 最后,首页会成为如何使用 crate 的综合参考,就像 [`regex`]。在这个首页,所有的依赖被列出,边缘情况被列出,实际例子被列出。然后首页继续展示如何使用正则表达式,然后还列出了 crate 的特性。
21 |
22 | 不要担心你的新 crate 与已经开发一段时间的 crate 比较。要是文档逐步完善,请逐步开始添加介绍,示例和特性。罗马不是一天建成的!
23 |
24 | `lib.rs` 的第一行开始会是首页,它们与 rustdoc 其他部分不同,要以 `//!` 开始表明这是模块级别或者 crate 级别的文档。这是一个简单的例子:
25 |
26 | ```rust,no_run
27 | //! Fast and easy queue abstraction.
28 | //!
29 | //! Provides an abstraction over a queue. When the abstraction is used
30 | //! there are these advantages:
31 | //! - Fast
32 | //! - [`Easy`]
33 | //!
34 | //! [`Easy`]: http://thatwaseasy.example.com
35 |
36 | /// This module makes it easy.
37 | pub mod easy {
38 |
39 | /// Use the abstraction function to do this specific thing.
40 | pub fn abstraction() {}
41 |
42 | }
43 | ```
44 |
45 | 理想情况下,文档第一行是没有技术细节的句子,但是很好的描述了在 Rust 生态中的位置。
46 | 阅读这行后,用户应该知道 crate 是否满足他们的需要。
47 |
48 | ## 文档组成
49 |
50 | 无论是 modules, structs, funtions, macros:代码的公共 API 都应该有文档。很少有人嫌弃文档太多!
51 |
52 | 每个 item 的文档应该都以下面的结构构成:
53 |
54 | ```text
55 | [short sentence explaining what it is]
56 |
57 | [more detailed explanation]
58 |
59 | [at least one code example that users can copy/paste to try it]
60 |
61 | [even more advanced explanations if necessary]
62 | ```
63 |
64 | 编写文档时,基本结构应该很容易遵循;你可能认为代码示例微不足道,但是它真的很重要,
65 | 能帮助用户理解 item 是什么,如何使用,以及存在的目的是什么。
66 |
67 | 让我们看一个来自 [standard library] 的例子,
68 | [`std::env::args()`][env::args] 函数:
69 |
70 | ````markdown
71 | Returns the arguments which this program was started with (normally passed
72 | via the command line).
73 |
74 | The first element is traditionally the path of the executable, but it can be
75 | set to arbitrary text, and may not even exist. This means this property should
76 | not be relied upon for security purposes.
77 |
78 | On Unix systems shell usually expands unquoted arguments with glob patterns
79 | (such as `*` and `?`). On Windows this is not done, and such arguments are
80 | passed as-is.
81 |
82 | # Panics
83 |
84 | The returned iterator will panic during iteration if any argument to the
85 | process is not valid unicode. If this is not desired,
86 | use the [`args_os`] function instead.
87 |
88 | # Examples
89 |
90 | ```
91 | use std::env;
92 |
93 | // Prints each argument on a separate line
94 | for argument in env::args() {
95 | println!("{}", argument);
96 | }
97 | ```
98 |
99 | [`args_os`]: ./fn.args_os.html
100 | ````
101 |
102 | 在第一个空行之间的所有内容都会被用于搜索和模块的简介。比如,上面的 `std::enve::args()` 函数就会在展示在 [`std::env`] 模块文档中。将摘要保持在一行是良好习惯:简介是好文档的目标。
103 |
104 | 因为类型系统很好定义了函数的参数和返回值类型,所以将其显式写入文档没有好处,尤其是 `rustdoc` 会自动在函数签名中添加指向类型的超链接。
105 |
106 | 在上面的例子中,`Panics` 小节解释了代码何时可能会意外退出,可以帮助读者规避 panic。如果你知道代码的边缘情况,尽可能增加 panic 小节。
107 |
108 | 如同你所看到的,它遵循了给出的结构建议:简短描述函数的作用,然后提供了更多信息以及最后提供了代码示例。
109 |
110 | ## Markdown
111 |
112 | `rustdoc` 使用 [CommonMark Markdown specification]。你可能会对它们的网站感兴趣:
113 |
114 | - [CommonMark quick reference]
115 | - [current spec]
116 |
117 | 补充了标准 CommonMark 语法, `rustdoc` 支持几种扩展:
118 |
119 | ### Strikethrough(删除线)
120 |
121 | 文本可以通过两个波浪线来渲染删除线:
122 |
123 | ```text
124 | An example of ~~strikethrough text~~.
125 | ```
126 |
127 | 这个例子会渲染成:
128 |
129 | > An example of ~~strikethrough text~~.
130 |
131 | 这使用 [GitHub Strikethrough extension][strikethrough]。
132 |
133 | ### Footnotes(角标)
134 |
135 | 角标会生成一个小号数字链接,点击数字链接会跳转到这个 item 的位置。角标标签类似与链接语法。例子如下:
136 |
137 | ```text
138 | This is an example of a footnote[^note].
139 |
140 | [^note]: This text is the contents of the footnote, which will be rendered
141 | towards the bottom.
142 | ```
143 |
144 | 这个例子会渲染成:
145 |
146 | > This is an example of a footnote[^note].
147 | >
148 | > [^note]:
149 | > This text is the contents of the footnote, which will be rendered
150 | > towards the bottom.
151 |
152 | 角标数字会根据角标位置自动生成。
153 |
154 | ### Tables(表格)
155 |
156 | 表格可以可以通过竖线和短横线来表示表格的行和列。被转换为符合 HTML 形状的表格。比如:
157 |
158 | ```text
159 | | Header1 | Header2 |
160 | |---------|---------|
161 | | abc | def |
162 | ```
163 |
164 | 这个例子会被渲染成类似这样:
165 |
166 | > | Header1 | Header2 |
167 | > | ------- | ------- |
168 | > | abc | def |
169 |
170 | 阅读 [GitHub Tables extension][tables] 的说明获取更多细节。
171 |
172 | ### Task lists
173 |
174 | 任务列表可以用于检查需要完成的条目。
175 | 比如:
176 |
177 | ```md
178 | - [x] Complete task
179 | - [ ] Incomplete task
180 | ```
181 |
182 | 会被渲染成:
183 |
184 | > - [x] Complete task
185 | > - [ ] Incomplete task
186 |
187 | 阅读 [task list extension] 获得更多细节。
188 |
189 | ### Smart punctuation(标点符号)
190 |
191 | 一些 ASCII 符号可以自动转换为更好看的 Unicode 符号:
192 |
193 | | ASCII sequence | Unicode |
194 | | -------------- | ---------------------------- |
195 | | `--` | – |
196 | | `---` | — |
197 | | `...` | … |
198 | | `"` | “ or ”, depending on context |
199 | | `'` | ‘ or ’, depending on context |
200 |
201 | 所以,不需要手工输入这些 Unicode 符号!
202 |
203 | [`backtrace`]: https://docs.rs/backtrace/0.3.50/backtrace/
204 | [commonmark markdown specification]: https://commonmark.org/
205 | [commonmark quick reference]: https://commonmark.org/help/
206 | [env::args]: https://doc.rust-lang.org/stable/std/env/fn.args.html
207 | [`Future`]: https://doc.rust-lang.org/std/future/trait.Future.html
208 | [`futures`]: https://docs.rs/futures/0.3.5/futures/
209 | [`hashbrown`]: https://docs.rs/hashbrown/0.8.2/hashbrown/
210 | [`regex`]: https://docs.rs/regex/1.3.9/regex/
211 | [standard library]: https://doc.rust-lang.org/stable/std/index.html
212 | [current spec]: https://spec.commonmark.org/current/
213 | [`std::env`]: https://doc.rust-lang.org/stable/std/env/index.html#functions
214 | [strikethrough]: https://github.github.com/gfm/#strikethrough-extension-
215 | [tables]: https://github.github.com/gfm/#tables-extension-
216 | [task list extension]: https://github.github.com/gfm/#task-list-items-extension-
217 |
--------------------------------------------------------------------------------
/src/linking-to-items-by-name.md:
--------------------------------------------------------------------------------
1 | # 通过名称链接 item
2 |
3 | Rustdoc 能够使用 item 的路径直接内部链接。这称为 'intra-doc link'。
4 |
5 | 比如,下面的代码可以链接 `Bar` 的页面:
6 |
7 | ```rust
8 | /// This struct is not [Bar]
9 | pub struct Foo1;
10 |
11 | /// This struct is also not [bar](Bar)
12 | pub struct Foo2;
13 |
14 | /// This struct is also not [bar][b]
15 | ///
16 | /// [b]: Bar
17 | pub struct Foo3;
18 |
19 | /// This struct is also not [`Bar`]
20 | pub struct Foo4;
21 |
22 | /// This struct *is* [`Bar`]!
23 | pub struct Bar;
24 | ```
25 |
26 | 不像常规的 markdown,`[bar][Bar]` 语法也被支持,不需要`[Bar]: ...` 链接。
27 |
28 | 反引号会被删除,所以 ``[`Option`]`` 可以正确地链接到`Option`。
29 |
30 | ## 有效链接
31 |
32 | 你可以链接作用域的任何东西,使用路径,包括 `Self`, `self`, `super`和 `crate`。Associated items (functions, types, and constants) 也是支持的,但是 [不能是空的 trait 实现][#79682]。Rustdoc 还支持 [the standard library documentation](../std/index.html#primitives) 列出的原始类型链接。
33 |
34 | [#79682]: https://github.com/rust-lang/rust/pull/79682
35 |
36 | 你还可以链接范型参数,比如 `Vec`。链接会如同你写了 ``[`Vec`](Vec)``. 但是,Fully-qualified syntax(比如,`::into_iter()`) 还 [没有被支持][fqs-issue]。
37 |
38 | [fqs-issue]: https://github.com/rust-lang/rust/issues/74563
39 |
40 | ```rust,edition2018
41 | use std::sync::mpsc::Receiver;
42 |
43 | /// This is a version of [`Receiver`] with support for [`std::future`].
44 | ///
45 | /// You can obtain a [`std::future::Future`] by calling [`Self::recv()`].
46 | pub struct AsyncReceiver {
47 | sender: Receiver
48 | }
49 |
50 | impl AsyncReceiver {
51 | pub async fn recv() -> T {
52 | unimplemented!()
53 | }
54 | }
55 | ```
56 |
57 | Rustdoc 允许使用 URL fragment specifiers,就如同普通的链接:
58 |
59 | ```rust
60 | /// This is a special implementation of [positional parameters].
61 | ///
62 | /// [positional parameters]: std::fmt#formatting-parameters
63 | struct MySpecialFormatter;
64 | ```
65 |
66 | ## Namespaces and Disambiguators(消歧义符)
67 |
68 | Rust 中的路径有三种命名空间:type, value 和 macro。Item name 在命名空间内必须唯一,但是可以与其他命名空间的 item 同名。在歧义的情况下,rustdoc 会警告歧义,并给出消除歧义的建议。
69 |
70 | ```rust
71 | /// See also: [`Foo`](struct@Foo)
72 | struct Bar;
73 |
74 | /// This is different from [`Foo`](fn@Foo)
75 | struct Foo {}
76 |
77 | fn Foo() {}
78 | ```
79 |
80 | 这些前缀展示在文档时会被删除,所以 `[struct@Foo]` 会被渲染成 `Foo`。
81 |
82 | 你也可以在函数名后加上 `()` 和在宏名后面加上 `!` 消除歧义:
83 |
84 | ```rust
85 | /// This is different from [`foo!`]
86 | fn foo() {}
87 |
88 | /// This is different from [`foo()`]
89 | macro_rules! foo {
90 | () => {}
91 | }
92 | ```
93 |
94 | ## 警告,re-exports, and scoping
95 |
96 | 即使 item 被 re-exported,链接也在 item 定义的模块内解析。如果来自另一个 crate 的链接解析失败,不会给出警告。
97 |
98 | ```rust,edition2018
99 | mod inner {
100 | /// Link to [f()]
101 | pub struct S;
102 | pub fn f() {}
103 | }
104 | pub use inner::S; // the link to `f` will still resolve correctly
105 | ```
106 |
107 | 当一个 item 被 re-export,rustdoc 允许加入额外的文档。额外的文档在 re-export 的作用域中解析,允许你链接 re-export 的 item,并且如果解析失败会给出警告。
108 |
109 | ```rust
110 | /// See also [foo()]
111 | pub use std::process::Command;
112 |
113 | pub fn foo() {}
114 | ```
115 |
116 | 这对于过程宏非常有用,过程宏必须定义在自己的 crate 中。
117 |
118 | 注意:因为 `macro_ruls!` 宏的作用域是整个 Rust,`macro_rules!` 的 intra-doc 链接在 [relative to the crate root][#72243] 解析,而不是定义的模块内。
119 |
120 | 如果链接看起来不像是 intra-doc 链接,它们会被忽略并且不会生成警告,即使链接解析失败。比如,任何包含了 `/` 或者 `[]` 字符的链接都被忽略。
121 |
122 | [#72243]: https://github.com/rust-lang/rust/issues/72243
123 |
--------------------------------------------------------------------------------
/src/lints.md:
--------------------------------------------------------------------------------
1 | # Lints
2 |
3 | `rustdoc` 提供 lints 来帮助你编写以及测试文档。你可以像使用其他 lints 来使用它们:
4 |
5 | ```rust
6 | #![allow(rustdoc::broken_intra_doc_links)] // allows the lint, no diagnostics will be reported
7 | #![warn(rustdoc::broken_intra_doc_links)] // warn if there are broken intra-doc links
8 | #![deny(rustdoc::broken_intra_doc_links)] // error if there are broken intra-doc links
9 | ```
10 |
11 | 注意,出了 `missing_docs`,这些 lints 只有当运行 `rustdoc` 的时候才会生效,`rustc` 不会。
12 |
13 | 这是`rustdoc` lints 的列表:
14 |
15 | ## broken_intra_doc_links
16 |
17 | 这个 lint 是**默认警告**。这个 lint 当 [intra-doc link] 解析错误时会提示。比如:
18 |
19 | [intra-doc link]: linking-to-items-by-name.md
20 |
21 | ```rust
22 | /// I want to link to [`Nonexistent`] but it doesn't exist!
23 | pub fn foo() {}
24 | ```
25 |
26 | 你会得到警告:
27 |
28 | ```text
29 | warning: unresolved link to `Nonexistent`
30 | --> test.rs:1:24
31 | |
32 | 1 | /// I want to link to [`Nonexistent`] but it doesn't exist!
33 | | ^^^^^^^^^^^^^ no item named `Nonexistent` in `test`
34 | ```
35 |
36 | 当存在歧义时也会得到警告,以及如何消除歧义的建议:
37 |
38 | ```rust
39 | /// [`Foo`]
40 | pub fn function() {}
41 |
42 | pub enum Foo {}
43 |
44 | pub fn Foo(){}
45 | ```
46 |
47 | ```text
48 | warning: `Foo` is both an enum and a function
49 | --> test.rs:1:6
50 | |
51 | 1 | /// [`Foo`]
52 | | ^^^^^ ambiguous link
53 | |
54 | = note: `#[warn(rustdoc::broken_intra_doc_links)]` on by default
55 | help: to link to the enum, prefix with the item type
56 | |
57 | 1 | /// [`enum@Foo`]
58 | | ^^^^^^^^^^
59 | help: to link to the function, add parentheses
60 | |
61 | 1 | /// [`Foo()`]
62 | | ^^^^^^^
63 |
64 | ```
65 |
66 | ## private_intra_doc_links
67 |
68 | 这个 lint 是**默认警告**. 这个 lint 会在 [intra-doc links] 从一个公共 item 连接一个私有 item 时提示。
69 | 比如:
70 |
71 | ```rust
72 | #![warn(rustdoc::private_intra_doc_links)] // note: unnecessary - warns by default.
73 |
74 | /// [private]
75 | pub fn public() {}
76 | fn private() {}
77 | ```
78 |
79 | 会给出这个文档中链接时损坏的:
80 |
81 | ```text
82 | warning: public documentation for `public` links to private item `private`
83 | --> priv.rs:1:6
84 | |
85 | 1 | /// [private]
86 | | ^^^^^^^ this item is private
87 | |
88 | = note: `#[warn(rustdoc::private_intra_doc_links)]` on by default
89 | = note: this link will resolve properly if you pass `--document-private-items`
90 | ```
91 |
92 | 注意到取决于你是否传递 `--document-private-items` 参数会有不同的行为!如果你有私有 item 的文档,尽管会有警告,仍然会生成这个链接:
93 |
94 | ```text
95 | warning: public documentation for `public` links to private item `private`
96 | --> priv.rs:1:6
97 | |
98 | 1 | /// [private]
99 | | ^^^^^^^ this item is private
100 | |
101 | = note: `#[warn(rustdoc::private_intra_doc_links)]` on by default
102 | = note: this link resolves only because you passed `--document-private-items`, but will break without
103 | ```
104 |
105 | [intra-doc links]: linking-to-items-by-name.html
106 |
107 | ## missing_docs
108 |
109 | 这个 lint **默认允许**。缺少文档时提示。比如:
110 |
111 | ```rust
112 | #![warn(missing_docs)]
113 |
114 | pub fn undocumented() {}
115 | # fn main() {}
116 | ```
117 |
118 | `undocumented` 函数会有下面的警告:
119 |
120 | ```text
121 | warning: missing documentation for a function
122 | --> your-crate/lib.rs:3:1
123 | |
124 | 3 | pub fn undocumented() {}
125 | | ^^^^^^^^^^^^^^^^^^^^^
126 | ```
127 |
128 | 注意不像其他 lint,这个 lint 也对 `rustc` 有效。
129 |
130 | ## missing_crate_level_docs
131 |
132 | 这个 lint 是**默认允许**。提示 crate 根没有文档。
133 | 比如:
134 |
135 | ```rust
136 | #![warn(rustdoc::missing_crate_level_docs)]
137 | ```
138 |
139 | 会生成下面的警告:
140 |
141 | ```text
142 | warning: no documentation found for this crate's top-level module
143 | |
144 | = help: The following guide may be of use:
145 | https://doc.rust-lang.org/nightly/rustdoc/how-to-write-documentation.html
146 | ```
147 |
148 | 当前默认是允许的,但是计划未来默认警告。这可以不使用`missing_docs`这种严重的警告,介绍给新用户如何给他们的 crate 写文档。
149 |
150 | ## missing_doc_code_examples
151 |
152 | 这个 lint **默认允许** 并且 **nightly-only**。当文档缺少代码示例时提示。比如:
153 |
154 | ```rust
155 | #![warn(rustdoc::missing_doc_code_examples)]
156 |
157 | /// There is no code example!
158 | pub fn no_code_example() {}
159 | # fn main() {}
160 | ```
161 |
162 | `no_code_example` 函数会有下面的警告:
163 |
164 | ```text
165 | warning: Missing code example in this documentation
166 | --> your-crate/lib.rs:3:1
167 | |
168 | LL | /// There is no code example!
169 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
170 | ```
171 |
172 | 为了修复这个 lint,你需要在文档块中加入代码示例:
173 |
174 | ```rust
175 | /// There is no code example!
176 | ///
177 | /// ```
178 | /// println!("calling no_code_example...");
179 | /// no_code_example();
180 | /// println!("we called no_code_example!");
181 | /// ```
182 | pub fn no_code_example() {}
183 | ```
184 |
185 | ## private_doc_tests
186 |
187 | 这个 lint **默认允许**。 提示私有 item 有文档测试。
188 | 比如:
189 |
190 | ```rust
191 | #![warn(rustdoc::private_doc_tests)]
192 |
193 | mod foo {
194 | /// private doc test
195 | ///
196 | /// ```
197 | /// assert!(false);
198 | /// ```
199 | fn bar() {}
200 | }
201 | # fn main() {}
202 | ```
203 |
204 | 提示:
205 |
206 | ```text
207 | warning: Documentation test in private item
208 | --> your-crate/lib.rs:4:1
209 | |
210 | 4 | / /// private doc test
211 | 5 | | ///
212 | 6 | | /// ```
213 | 7 | | /// assert!(false);
214 | 8 | | /// ```
215 | | |___________^
216 | ```
217 |
218 | ## invalid_codeblock_attributes
219 |
220 | 这个 lint **默认警告**。提示文档例子中的代码块属性有潜在的错误。比如:
221 |
222 | ```rust
223 | #![warn(rustdoc::invalid_codeblock_attributes)] // note: unnecessary - warns by default.
224 |
225 | /// Example.
226 | ///
227 | /// ```should-panic
228 | /// assert_eq!(1, 2);
229 | /// ```
230 | pub fn foo() {}
231 | ```
232 |
233 | 提示:
234 |
235 | ```text
236 | warning: unknown attribute `should-panic`. Did you mean `should_panic`?
237 | --> src/lib.rs:1:1
238 | |
239 | 1 | / /// Example.
240 | 2 | | ///
241 | 3 | | /// ```should-panic
242 | 4 | | /// assert_eq!(1, 2);
243 | 5 | | /// ```
244 | | |_______^
245 | |
246 | = note: `#[warn(rustdoc::invalid_codeblock_attributes)]` on by default
247 | = help: the code block will either not be tested if not marked as a rust one or won't fail if it doesn't panic when running
248 | ```
249 |
250 | 上面的例子中,正确的拼写是 `should_panic`。可以提示一些常用的属性 typo 错误。
251 |
252 | ## invalid_html_tags
253 |
254 | 这个 lint **默认允许** 并且是 **nightly-only**。提示没有关闭的或者无效的 HTML tag。
255 | 比如:
256 |
257 | ```rust
258 | #![warn(rustdoc::invalid_html_tags)]
259 |
260 | ///
272 | 2 | | ///
273 | | |_____________^
274 | |
275 | note: the lint level is defined here
276 | --> foo.rs:1:9
277 | |
278 | 1 | #![warn(rustdoc::invalid_html_tags)]
279 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^
280 |
281 | warning: unclosed HTML tag `h1`
282 | --> foo.rs:1:1
283 | |
284 | 1 | / ///
285 | 2 | | ///
286 | | |_____________^
287 |
288 | warning: 2 warnings emitted
289 | ```
290 |
291 | ## invalid_rust_codeblocks
292 |
293 | 这个 lint **默认警告**。提示文档中的 Rust 代码块无效(比如,空的,无法被解析为 Rust 代码)。比如:
294 |
295 | ```rust
296 | /// Empty code blocks (with and without the `rust` marker):
297 | ///
298 | /// ```rust
299 | /// ```
300 | ///
301 | /// Invalid syntax in code blocks:
302 | ///
303 | /// ```rust
304 | /// '<
305 | /// ```
306 | pub fn foo() {}
307 | ```
308 |
309 | 提示:
310 |
311 | ```text
312 | warning: Rust code block is empty
313 | --> lint.rs:3:5
314 | |
315 | 3 | /// ```rust
316 | | _____^
317 | 4 | | /// ```
318 | | |_______^
319 | |
320 | = note: `#[warn(rustdoc::invalid_rust_codeblocks)]` on by default
321 |
322 | warning: could not parse code block as Rust code
323 | --> lint.rs:8:5
324 | |
325 | 8 | /// ```rust
326 | | _____^
327 | 9 | | /// '<
328 | 10 | | /// ```
329 | | |_______^
330 | |
331 | = note: error from rustc: unterminated character literal
332 | ```
333 |
334 | ## bare_urls
335 |
336 | 这个 lint **默认警告**。提示 Url 不是一个链接。
337 | 比如:
338 |
339 | ```rust
340 | #![warn(rustdoc::bare_urls)] // note: unnecessary - warns by default.
341 |
342 | /// http://example.org
343 | /// [http://example.net]
344 | pub fn foo() {}
345 | ```
346 |
347 | 会出现:
348 |
349 | ```text
350 | warning: this URL is not a hyperlink
351 | --> links.rs:1:5
352 | |
353 | 1 | /// http://example.org
354 | | ^^^^^^^^^^^^^^^^^^ help: use an automatic link instead: ``
355 | |
356 | = note: `#[warn(rustdoc::bare_urls)]` on by default
357 |
358 | warning: this URL is not a hyperlink
359 | --> links.rs:3:6
360 | |
361 | 3 | /// [http://example.net]
362 | | ^^^^^^^^^^^^^^^^^^ help: use an automatic link instead: ``
363 |
364 | warning: 2 warnings emitted
365 | ```
366 |
--------------------------------------------------------------------------------
/src/passes.md:
--------------------------------------------------------------------------------
1 | # Passes
2 |
3 | Rustdoc 有一个概念叫做 "passes"。在 `rustdoc` 命令最终生成文档之前存在一些转换。
4 |
5 | 自定义 passes 被**废弃**了,已经可用的 passes 不会稳定可能随时会在发布中更改
6 |
7 | 过去最常用的自定义 passes 是 `strip-private` pass。你现在可以更容易的做到这个,通过传递参数 [`--document-private-items`](./unstable-features.md#--document-private-items).
8 |
--------------------------------------------------------------------------------
/src/references.md:
--------------------------------------------------------------------------------
1 | # References
2 |
3 | 有很多良好的 `rustdoc` 参考,如果你知道其他的好资源,请提交 PR!
4 |
5 | ## 官方
6 |
7 | - [Learn Rust]
8 | - [Rust By Example]
9 | - [Rust Reference]
10 | - [RFC 1574: More API Documentation Conventions]
11 | - [RFC 1946: Intra Rustdoc Links]
12 |
13 | ## 社区
14 |
15 | - [API Guidelines]
16 | - [Github tagged RFCs]
17 | - [Github tagged issues]
18 | - [RFC (stalled) front page styleguide]
19 | - [Guide on how to write documentation for a Rust crate]
20 |
21 | [API Guidelines]: https://rust-lang.github.io/api-guidelines/documentation.html
22 | [Github tagged RFCs]: https://github.com/rust-lang/rfcs/issues?q=label%3AT-rustdoc
23 | [Github tagged issues]: https://github.com/rust-lang/rust/issues?q=is%3Aissue+is%3Aopen+label%3AT-rustdoc
24 | [Guide on how to write documentation for a Rust crate]: https://blog.guillaume-gomez.fr/articles/2020-03-12+Guide+on+how+to+write+documentation+for+a+Rust+crate
25 | [Learn Rust]: https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#making-useful-documentation-comments
26 | [RFC 1574: More API Documentation Conventions]: https://rust-lang.github.io/rfcs/1574-more-api-documentation-conventions.html
27 | [RFC 1946: Intra Rustdoc Links]: https://rust-lang.github.io/rfcs/1946-intra-rustdoc-links.html
28 | [RFC (stalled) front page styleguide]: https://github.com/rust-lang/rfcs/pull/1687
29 | [Rust By Example]: https://doc.rust-lang.org/stable/rust-by-example/meta/doc.html
30 | [Rust Reference]: https://doc.rust-lang.org/stable/reference/comments.html#doc-comments
31 |
--------------------------------------------------------------------------------
/src/the-doc-attribute.md:
--------------------------------------------------------------------------------
1 | # `#[doc]` 属性
2 |
3 | `#[doc]` 属性可以让你控制 `rustdoc` 工作的各个方面。
4 |
5 | `#[doc]` 最基本的作用就是处理文档内容。就是说,`///` 就是 `#[doc]` 的语法糖。下面的两行注释是一样的:
6 |
7 | ```rust,no_run
8 | /// This is a doc comment.
9 | #[doc = " This is a doc comment."]
10 | # fn f() {}
11 | ```
12 |
13 | (请注意属性版本的开始的空格。)
14 |
15 | 在大多数情况下,`///` 比 `#[doc]` 更容易使用。一种后面更容易使用的场景是给宏生成文档;`collapse-docs` 会组合多个 `#[doc]`属性为一条文档注释,比如:
16 |
17 | ```rust,no_run
18 | #[doc = "This is"]
19 | #[doc = " a "]
20 | #[doc = "doc comment"]
21 | # fn f() {}
22 | ```
23 |
24 | 这样可能感觉更灵活。注意这跟下面的写法是一样的:
25 |
26 | ```rust,no_run
27 | #[doc = "This is\n a \ndoc comment"]
28 | # fn f() {}
29 | ```
30 |
31 | 给出的文档会渲染成 markdown,会删除换行符。
32 |
33 | 另一个有用的场景是引入外部文件:
34 |
35 | ```rust,no_run,ignore
36 | #[doc = include_str!("../README.md")]
37 | # fn f() {}
38 | ```
39 |
40 | `doc` 属性有更多的选项!不会包含在输出中,但是可以控制输出的表示。我们将它们分为两大类:在 crate 层面使用的,和在 item 层面使用的。
41 |
42 | ## crate 层面
43 |
44 | 这些选项控制文档在 crate 层面如何表示。
45 |
46 | ### `html_favicon_url`
47 |
48 | 这个 `doc` 属性让你控制你的文档图标。
49 |
50 | ```rust,no_run
51 | #![doc(html_favicon_url = "https://example.com/favicon.ico")]
52 | ```
53 |
54 | 这会在你的文档中加入 ``,属性的值会填入 `{}`。
55 |
56 | 如果你不使用这个属性,就没有图标。
57 |
58 | ### `html_logo_url`
59 |
60 | 这个 `doc` 属性可以让你控制左上角的 logo。
61 |
62 | ```rust,no_run
63 | #![doc(html_logo_url = "https://example.com/logo.jpg")]
64 | ```
65 |
66 | 这会在你的文档中加入 ``,属性的值会填入 `{}`。
67 |
68 | 如果你不使用这个属性,就没有 logo。
69 |
70 | ### `html_playground_url`
71 |
72 | 这个 `doc` 属性让你控制文档示例中的 "run" 按钮的请求到哪里。
73 |
74 | ```rust,no_run
75 | #![doc(html_playground_url = "https://playground.example.com/")]
76 | ```
77 |
78 | 现在,当你按下 "run",会向对应网站发出请求。
79 |
80 | 如果你没有使用这个属性,没有运行按钮。
81 |
82 | ### `issue_tracker_base_url`
83 |
84 | 这个 `doc` 属性在标准库中使用最多;当一个特性未稳定时,需要提供 issue number 来追踪这个特性。`rustdoc` 使用这个 number,加入到给定的基本 URL 来链接到追踪的网址。
85 |
86 | ```rust,no_run
87 | #![doc(issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/")]
88 | ```
89 |
90 | ### `html_root_url`
91 |
92 | `#[doc(html_root_url = "…")]` 属性的值表明了生成外部 crate 的 URL。当 rustdoc 需要生成一个外部 crate item 的链接时,首先检查本地外部 crate 的文档,如果存在直接链接指向。如果失败,就会使用 `--extern-html-root-url` 命令行参数的值,如果没有这个参数,才会使用 `html_root_url` ,如果还是无效,外部 item 不会链接。
93 |
94 | ```rust,no_run
95 | #![doc(html_root_url = "https://docs.rs/serde/1.0")]
96 | ```
97 |
98 | ### `html_no_source`
99 |
100 | 默认情况下,`rustdoc` 会包含你的源码链接到文档中。
101 | 但是如果你这样写:
102 |
103 | ```rust,no_run
104 | #![doc(html_no_source)]
105 | ```
106 |
107 | 就不会。
108 |
109 | ### `test(no_crate_inject)`
110 |
111 | 默认情况下,`rustdoc` 会自动加一行 `extern crate my_crate;` 到每个文档测试中。
112 | 但是如果你这样写了:
113 |
114 | ```rust,no_run
115 | #![doc(test(no_crate_inject))]
116 | ```
117 |
118 | 就不会。
119 |
120 | ### `test(attr(...))`
121 |
122 | 这个 `doc` 属性允许你对你所有的文档测试加上某个属性。比如,如果你想要你的文档测试存在警告时失败,可以这样写:
123 |
124 | ```rust,no_run
125 | #![doc(test(attr(deny(warnings))))]
126 | ```
127 |
128 | ## item 层面
129 |
130 | 这些 `#[doc]` 属性单独给 item 使用,控制 item 文档表示。
131 |
132 | ### `inline` and `no_inline`
133 |
134 |
135 |
136 | 这两个属性可以用于 `use` 声明。比如,考虑如下 Rust 代码:
137 |
138 | ```rust,no_run
139 | pub use bar::Bar;
140 |
141 | /// bar docs
142 | pub mod bar {
143 | /// the docs for Bar
144 | pub struct Bar;
145 | }
146 | # fn main() {}
147 | ```
148 |
149 | 文档会生成 "Re-exports" 小节,表示 `pub use bar::Bar;` 其中 `Bar` 会链接到自己的页面。
150 |
151 | 如果我们将代码改为:
152 |
153 | ```rust,no_run
154 | #[doc(inline)]
155 | pub use bar::Bar;
156 | # pub mod bar { pub struct Bar; }
157 | # fn main() {}
158 | ```
159 |
160 | `Bar` 就会出现在 `Structs` 小节,就像 `Bar` 就定义在顶层一样,而不是 `pub use` 的。
161 |
162 | 然后我们修改原始的例子,使 `bar` 私有:
163 |
164 | ```rust,no_run
165 | pub use bar::Bar;
166 |
167 | /// bar docs
168 | mod bar {
169 | /// the docs for Bar
170 | pub struct Bar;
171 | }
172 | # fn main() {}
173 | ```
174 |
175 | 这里,因为 `bar` 不是公共的,`Bar` 没有自己的页面,所有没有链接可以指向。`rustdoc` 将会内联定义,所以会得到与 `#[doc(inline)]` 一样的结果:`Bar` 就会出现在 `Structs` 小节,就像 `Bar` 就定义在顶层一样。如果我们加上 `no_inline` 属性:
176 |
177 | ```rust,no_run
178 | #[doc(no_inline)]
179 | pub use bar::Bar;
180 |
181 | /// bar docs
182 | mod bar {
183 | /// the docs for Bar
184 | pub struct Bar;
185 | }
186 | # fn main() {}
187 | ```
188 |
189 | 现在我们有了 `Re-exports`,并且 `Bar` 没有链接到任何页面。
190 |
191 | 一个特殊情况:在 Rust 2018 以及更高版本,如果你 `pub use` 你的依赖,`rustdoc` 不会作为 modules 内联除非你加上 `#[doc(inline)]`。
192 |
193 | ### `hidden`
194 |
195 |
196 |
197 | 任何标注了 `#[doc(hidden)]` 的 item 不会出现在文档中,除非 `strip-hidden` pass 被删除。
198 |
199 | ### `alias`
200 |
201 | 这个属性给搜索索引增加了别名。
202 |
203 | 让我们举个例子:
204 |
205 | ```rust,no_run
206 | #[doc(alias = "TheAlias")]
207 | pub struct SomeType;
208 | ```
209 |
210 | 现在,如果你输入 "TheAlias" 搜索,也会显示 `SomeType`。当然如果你输入 `SomeType` 也会显示 `SomeType`!
211 |
212 | #### FFI 例子
213 |
214 | 文档属性在写 c 库的 bingding 时尤其有用。比如,我们有一个下面这样的 C 函数:
215 |
216 | ```c
217 | int lib_name_do_something(Obj *obj);
218 | ```
219 |
220 | 它输入一个指向 `Obj` 类型的指针返回一个整数。在 Rust 中,可能会这样写:
221 |
222 | ```ignore (using non-existing ffi types)
223 | pub struct Obj {
224 | inner: *mut ffi::Obj,
225 | }
226 |
227 | impl Obj {
228 | pub fn do_something(&mut self) -> i32 {
229 | unsafe { ffi::lib_name_do_something(self.inner) }
230 | }
231 | }
232 | ```
233 |
234 | 函数已经被转换为一个方法便于使用。但是如果你想要寻找 Rust 相当的 `lib_name_do_something`,你没有办法做到。
235 |
236 | 为了避免这个限制,我们只需要在 `do_something` 方法加上 `#[doc(alias = "lib_name_do_something")]`,然后就可以了!
237 |
238 | 用户可以直接搜索 `lib_name_do_something` 然后找到`Obj::do_something`。
239 |
--------------------------------------------------------------------------------
/src/unstable-features.md:
--------------------------------------------------------------------------------
1 | # 不稳定特性
2 |
3 | Rustdoc is under active development, and like the Rust compiler, some features are only available
4 | on nightly releases. Some of these features are new and need some more testing before they're able to be
5 | released to the world at large, and some of them are tied to features in the Rust compiler that are unstable. Several features here require a matching `#![feature(...)]` attribute to
6 | enable, and thus are more fully documented in the [Unstable Book]. Those sections will link over
7 | there as necessary.
8 |
9 | [Unstable Book]: ../unstable-book/index.html
10 |
11 | ## Nightly-gated functionality
12 |
13 | These features just require a nightly build to operate. Unlike the other features on this page,
14 | these don't need to be "turned on" with a command-line flag or a `#![feature(...)]` attribute in
15 | your crate. This can give them some subtle fallback modes when used on a stable release, so be
16 | careful!
17 |
18 | ### Error numbers for `compile-fail` doctests
19 |
20 | As detailed in [the chapter on documentation tests][doctest-attributes], you can add a
21 | `compile_fail` attribute to a doctest to state that the test should fail to compile. However, on
22 | nightly, you can optionally add an error number to state that a doctest should emit a specific error
23 | number:
24 |
25 | [doctest-attributes]: documentation-tests.html#attributes
26 |
27 | ``````markdown
28 | ```compile_fail,E0044
29 | extern { fn some_func(x: T); }
30 | ```
31 | ``````
32 |
33 | This is used by the error index to ensure that the samples that correspond to a given error number
34 | properly emit that error code. However, these error codes aren't guaranteed to be the only thing
35 | that a piece of code emits from version to version, so this is unlikely to be stabilized in the
36 | future.
37 |
38 | Attempting to use these error numbers on stable will result in the code sample being interpreted as
39 | plain text.
40 |
41 | ## Extensions to the `#[doc]` attribute
42 |
43 | These features operate by extending the `#[doc]` attribute, and thus can be caught by the compiler
44 | and enabled with a `#![feature(...)]` attribute in your crate.
45 |
46 | ### `#[doc(cfg)]`: Recording what platforms or features are required for code to be present
47 |
48 | You can use `#[doc(cfg(...))]` to tell Rustdoc exactly which platform items appear on.
49 | This has two effects:
50 |
51 | 1. doctests will only run on the appropriate platforms, and
52 | 2. When Rustdoc renders documentation for that item, it will be accompanied by a banner explaining
53 | that the item is only available on certain platforms.
54 |
55 | `#[doc(cfg)]` is intended to be used alongside [`#[cfg(doc)]`][cfg-doc].
56 | For example, `#[cfg(any(windows, doc))]` will preserve the item either on Windows or during the
57 | documentation process. Then, adding a new attribute `#[doc(cfg(windows))]` will tell Rustdoc that
58 | the item is supposed to be used on Windows. For example:
59 |
60 | ```rust
61 | #![feature(doc_cfg)]
62 |
63 | /// Token struct that can only be used on Windows.
64 | #[cfg(any(windows, doc))]
65 | #[doc(cfg(windows))]
66 | pub struct WindowsToken;
67 |
68 | /// Token struct that can only be used on Unix.
69 | #[cfg(any(unix, doc))]
70 | #[doc(cfg(unix))]
71 | pub struct UnixToken;
72 |
73 | /// Token struct that is only available with the `serde` feature
74 | #[cfg(feature = "serde")]
75 | #[doc(cfg(feature = "serde"))]
76 | #[derive(serde::Deserialize)]
77 | pub struct SerdeToken;
78 | ```
79 |
80 | In this sample, the tokens will only appear on their respective platforms, but they will both appear
81 | in documentation.
82 |
83 | `#[doc(cfg(...))]` was introduced to be used by the standard library and currently requires the
84 | `#![feature(doc_cfg)]` feature gate. For more information, see [its chapter in the Unstable
85 | Book][unstable-doc-cfg] and [its tracking issue][issue-doc-cfg].
86 |
87 | ### `doc_auto_cfg`: Automatically generate `#[doc(cfg)]`
88 |
89 | `doc_auto_cfg` is an extension to the `#[doc(cfg)]` feature. With it, you don't need to add
90 | `#[doc(cfg(...)]` anymore unless you want to override the default behaviour. So if we take the
91 | previous source code:
92 |
93 | ```rust
94 | #![feature(doc_auto_cfg)]
95 |
96 | /// Token struct that can only be used on Windows.
97 | #[cfg(any(windows, doc))]
98 | pub struct WindowsToken;
99 |
100 | /// Token struct that can only be used on Unix.
101 | #[cfg(any(unix, doc))]
102 | pub struct UnixToken;
103 |
104 | /// Token struct that is only available with the `serde` feature
105 | #[cfg(feature = "serde")]
106 | #[derive(serde::Deserialize)]
107 | pub struct SerdeToken;
108 | ```
109 |
110 | It'll render almost the same, the difference being that `doc` will also be displayed. To fix this,
111 | you can use `doc_cfg_hide`:
112 |
113 | ```rust
114 | #![feature(doc_cfg_hide)]
115 | #![doc(cfg_hide(doc))]
116 | ```
117 |
118 | And `doc` won't show up anymore!
119 |
120 | [cfg-doc]: ./advanced-features.md
121 | [unstable-doc-cfg]: ../unstable-book/language-features/doc-cfg.html
122 | [issue-doc-cfg]: https://github.com/rust-lang/rust/issues/43781
123 |
124 | ### Adding your trait to the "Notable traits" dialog
125 |
126 | Rustdoc keeps a list of a few traits that are believed to be "fundamental" to
127 | types that implement them. These traits are intended to be the primary interface
128 | for their implementers, and are often most of the API available to be documented
129 | on their types. For this reason, Rustdoc will track when a given type implements
130 | one of these traits and call special attention to it when a function returns one
131 | of these types. This is the "Notable traits" dialog, accessible as a circled `i`
132 | button next to the function, which, when clicked, shows the dialog.
133 |
134 | In the standard library, some of the traits that are part of this list are
135 | `Iterator`, `Future`, `io::Read`, and `io::Write`. However, rather than being
136 | implemented as a hard-coded list, these traits have a special marker attribute
137 | on them: `#[doc(notable_trait)]`. This means that you can apply this attribute
138 | to your own trait to include it in the "Notable traits" dialog in documentation.
139 |
140 | The `#[doc(notable_trait)]` attribute currently requires the `#![feature(doc_notable_trait)]`
141 | feature gate. For more information, see [its chapter in the Unstable Book][unstable-notable_trait]
142 | and [its tracking issue][issue-notable_trait].
143 |
144 | [unstable-notable_trait]: ../unstable-book/language-features/doc-notable-trait.html
145 | [issue-notable_trait]: https://github.com/rust-lang/rust/issues/45040
146 |
147 | ### Exclude certain dependencies from documentation
148 |
149 | The standard library uses several dependencies which, in turn, use several types and traits from the
150 | standard library. In addition, there are several compiler-internal crates that are not considered to
151 | be part of the official standard library, and thus would be a distraction to include in
152 | documentation. It's not enough to exclude their crate documentation, since information about trait
153 | implementations appears on the pages for both the type and the trait, which can be in different
154 | crates!
155 |
156 | To prevent internal types from being included in documentation, the standard library adds an
157 | attribute to their `extern crate` declarations: `#[doc(masked)]`. This causes Rustdoc to "mask out"
158 | types from these crates when building lists of trait implementations.
159 |
160 | The `#[doc(masked)]` attribute is intended to be used internally, and requires the
161 | `#![feature(doc_masked)]` feature gate. For more information, see [its chapter in the Unstable
162 | Book][unstable-masked] and [its tracking issue][issue-masked].
163 |
164 | [unstable-masked]: ../unstable-book/language-features/doc-masked.html
165 | [issue-masked]: https://github.com/rust-lang/rust/issues/44027
166 |
167 |
168 | ## Document primitives
169 |
170 | This is for Rust compiler internal use only.
171 |
172 | Since primitive types are defined in the compiler, there's no place to attach documentation
173 | attributes. The `#[doc(primitive)]` attribute is used by the standard library to provide a way
174 | to generate documentation for primitive types, and requires `#![feature(rustdoc_internals)]` to
175 | enable.
176 |
177 | ## Document keywords
178 |
179 | This is for Rust compiler internal use only.
180 |
181 | Rust keywords are documented in the standard library (look for `match` for example).
182 |
183 | To do so, the `#[doc(keyword = "...")]` attribute is used. Example:
184 |
185 | ```rust
186 | #![feature(rustdoc_internals)]
187 |
188 | /// Some documentation about the keyword.
189 | #[doc(keyword = "keyword")]
190 | mod empty_mod {}
191 | ```
192 |
193 | ## Unstable command-line arguments
194 |
195 | These features are enabled by passing a command-line flag to Rustdoc, but the flags in question are
196 | themselves marked as unstable. To use any of these options, pass `-Z unstable-options` as well as
197 | the flag in question to Rustdoc on the command-line. To do this from Cargo, you can either use the
198 | `RUSTDOCFLAGS` environment variable or the `cargo rustdoc` command.
199 |
200 | ### `--markdown-before-content`: include rendered Markdown before the content
201 |
202 | Using this flag looks like this:
203 |
204 | ```bash
205 | $ rustdoc src/lib.rs -Z unstable-options --markdown-before-content extra.md
206 | $ rustdoc README.md -Z unstable-options --markdown-before-content extra.md
207 | ```
208 |
209 | Just like `--html-before-content`, this allows you to insert extra content inside the `` tag
210 | but before the other content `rustdoc` would normally produce in the rendered documentation.
211 | However, instead of directly inserting the file verbatim, `rustdoc` will pass the files through a
212 | Markdown renderer before inserting the result into the file.
213 |
214 | ### `--markdown-after-content`: include rendered Markdown after the content
215 |
216 | Using this flag looks like this:
217 |
218 | ```bash
219 | $ rustdoc src/lib.rs -Z unstable-options --markdown-after-content extra.md
220 | $ rustdoc README.md -Z unstable-options --markdown-after-content extra.md
221 | ```
222 |
223 | Just like `--html-after-content`, this allows you to insert extra content before the `` tag
224 | but after the other content `rustdoc` would normally produce in the rendered documentation.
225 | However, instead of directly inserting the file verbatim, `rustdoc` will pass the files through a
226 | Markdown renderer before inserting the result into the file.
227 |
228 | ### `--playground-url`: control the location of the playground
229 |
230 | Using this flag looks like this:
231 |
232 | ```bash
233 | $ rustdoc src/lib.rs -Z unstable-options --playground-url https://play.rust-lang.org/
234 | ```
235 |
236 | When rendering a crate's docs, this flag gives the base URL of the Rust Playground, to use for
237 | generating `Run` buttons. Unlike `--markdown-playground-url`, this argument works for standalone
238 | Markdown files *and* Rust crates. This works the same way as adding `#![doc(html_playground_url =
239 | "url")]` to your crate root, as mentioned in [the chapter about the `#[doc]`
240 | attribute][doc-playground]. Please be aware that the official Rust Playground at
241 | https://play.rust-lang.org does not have every crate available, so if your examples require your
242 | crate, make sure the playground you provide has your crate available.
243 |
244 | [doc-playground]: the-doc-attribute.html#html_playground_url
245 |
246 | If both `--playground-url` and `--markdown-playground-url` are present when rendering a standalone
247 | Markdown file, the URL given to `--markdown-playground-url` will take precedence. If both
248 | `--playground-url` and `#![doc(html_playground_url = "url")]` are present when rendering crate docs,
249 | the attribute will take precedence.
250 |
251 | ### `--sort-modules-by-appearance`: control how items on module pages are sorted
252 |
253 | Using this flag looks like this:
254 |
255 | ```bash
256 | $ rustdoc src/lib.rs -Z unstable-options --sort-modules-by-appearance
257 | ```
258 |
259 | Ordinarily, when `rustdoc` prints items in module pages, it will sort them alphabetically (taking
260 | some consideration for their stability, and names that end in a number). Giving this flag to
261 | `rustdoc` will disable this sorting and instead make it print the items in the order they appear in
262 | the source.
263 |
264 | ### `--show-type-layout`: add a section to each type's docs describing its memory layout
265 |
266 | Using this flag looks like this:
267 |
268 | ```bash
269 | $ rustdoc src/lib.rs -Z unstable-options --show-type-layout
270 | ```
271 |
272 | When this flag is passed, rustdoc will add a "Layout" section at the bottom of
273 | each type's docs page that includes a summary of the type's memory layout as
274 | computed by rustc. For example, rustdoc will show the size in bytes that a value
275 | of that type will take in memory.
276 |
277 | Note that most layout information is **completely unstable** and may even differ
278 | between compilations.
279 |
280 | ### `--resource-suffix`: modifying the name of CSS/JavaScript in crate docs
281 |
282 | Using this flag looks like this:
283 |
284 | ```bash
285 | $ rustdoc src/lib.rs -Z unstable-options --resource-suffix suf
286 | ```
287 |
288 | When rendering docs, `rustdoc` creates several CSS and JavaScript files as part of the output. Since
289 | all these files are linked from every page, changing where they are can be cumbersome if you need to
290 | specially cache them. This flag will rename all these files in the output to include the suffix in
291 | the filename. For example, `light.css` would become `light-suf.css` with the above command.
292 |
293 | ### `--extern-html-root-url`: control how rustdoc links to non-local crates
294 |
295 | Using this flag looks like this:
296 |
297 | ```bash
298 | $ rustdoc src/lib.rs -Z unstable-options --extern-html-root-url some-crate=https://example.com/some-crate/1.0.1
299 | ```
300 |
301 | Ordinarily, when rustdoc wants to link to a type from a different crate, it looks in two places:
302 | docs that already exist in the output directory, or the `#![doc(doc_html_root)]` set in the other
303 | crate. However, if you want to link to docs that exist in neither of those places, you can use these
304 | flags to control that behavior. When the `--extern-html-root-url` flag is given with a name matching
305 | one of your dependencies, rustdoc use that URL for those docs. Keep in mind that if those docs exist
306 | in the output directory, those local docs will still override this flag.
307 |
308 | ### `-Z force-unstable-if-unmarked`
309 |
310 | Using this flag looks like this:
311 |
312 | ```bash
313 | $ rustdoc src/lib.rs -Z force-unstable-if-unmarked
314 | ```
315 |
316 | This is an internal flag intended for the standard library and compiler that applies an
317 | `#[unstable]` attribute to any dependent crate that doesn't have another stability attribute. This
318 | allows `rustdoc` to be able to generate documentation for the compiler crates and the standard
319 | library, as an equivalent command-line argument is provided to `rustc` when building those crates.
320 |
321 | ### `--index-page`: provide a top-level landing page for docs
322 |
323 | This feature allows you to generate an index-page with a given markdown file. A good example of it
324 | is the [rust documentation index](https://doc.rust-lang.org/nightly/index.html).
325 |
326 | With this, you'll have a page which you can custom as much as you want at the top of your crates.
327 |
328 | Using `index-page` option enables `enable-index-page` option as well.
329 |
330 | ### `--enable-index-page`: generate a default index page for docs
331 |
332 | This feature allows the generation of a default index-page which lists the generated crates.
333 |
334 | ### `--static-root-path`: control how static files are loaded in HTML output
335 |
336 | Using this flag looks like this:
337 |
338 | ```bash
339 | $ rustdoc src/lib.rs -Z unstable-options --static-root-path '/cache/'
340 | ```
341 |
342 | This flag controls how rustdoc links to its static files on HTML pages. If you're hosting a lot of
343 | crates' docs generated by the same version of rustdoc, you can use this flag to cache rustdoc's CSS,
344 | JavaScript, and font files in a single location, rather than duplicating it once per "doc root"
345 | (grouping of crate docs generated into the same output directory, like with `cargo doc`). Per-crate
346 | files like the search index will still load from the documentation root, but anything that gets
347 | renamed with `--resource-suffix` will load from the given path.
348 |
349 | ### `--persist-doctests`: persist doctest executables after running
350 |
351 | Using this flag looks like this:
352 |
353 | ```bash
354 | $ rustdoc src/lib.rs --test -Z unstable-options --persist-doctests target/rustdoctest
355 | ```
356 |
357 | This flag allows you to keep doctest executables around after they're compiled or run.
358 | Usually, rustdoc will immediately discard a compiled doctest after it's been tested, but
359 | with this option, you can keep those binaries around for farther testing.
360 |
361 | ### `--show-coverage`: calculate the percentage of items with documentation
362 |
363 | Using this flag looks like this:
364 |
365 | ```bash
366 | $ rustdoc src/lib.rs -Z unstable-options --show-coverage
367 | ```
368 |
369 | It generates something like this:
370 |
371 | ```bash
372 | +-------------------------------------+------------+------------+------------+------------+
373 | | File | Documented | Percentage | Examples | Percentage |
374 | +-------------------------------------+------------+------------+------------+------------+
375 | | lib.rs | 4 | 100.0% | 1 | 25.0% |
376 | +-------------------------------------+------------+------------+------------+------------+
377 | | Total | 4 | 100.0% | 1 | 25.0% |
378 | +-------------------------------------+------------+------------+------------+------------+
379 | ```
380 |
381 | If you want to determine how many items in your crate are documented, pass this flag to rustdoc.
382 | When it receives this flag, it will count the public items in your crate that have documentation,
383 | and print out the counts and a percentage instead of generating docs.
384 |
385 | Some methodology notes about what rustdoc counts in this metric:
386 |
387 | * Rustdoc will only count items from your crate (i.e. items re-exported from other crates don't
388 | count).
389 | * Docs written directly onto inherent impl blocks are not counted, even though their doc comments
390 | are displayed, because the common pattern in Rust code is to write all inherent methods into the
391 | same impl block.
392 | * Items in a trait implementation are not counted, as those impls will inherit any docs from the
393 | trait itself.
394 | * By default, only public items are counted. To count private items as well, pass
395 | `--document-private-items` at the same time.
396 |
397 | Public items that are not documented can be seen with the built-in `missing_docs` lint. Private
398 | items that are not documented can be seen with Clippy's `missing_docs_in_private_items` lint.
399 |
400 | Calculating code examples follows these rules:
401 |
402 | 1. These items aren't accounted by default:
403 | * struct/union field
404 | * enum variant
405 | * constant
406 | * static
407 | * typedef
408 | 2. If one of the previously listed items has a code example, then it'll be counted.
409 |
410 | #### JSON output
411 |
412 | When using `--output-format json` with this option, it will display the coverage information in
413 | JSON format. For example, here is the JSON for a file with one documented item and one
414 | undocumented item:
415 |
416 | ```rust
417 | /// This item has documentation
418 | pub fn foo() {}
419 |
420 | pub fn no_documentation() {}
421 | ```
422 |
423 | ```json
424 | {"no_std.rs":{"total":3,"with_docs":1,"total_examples":3,"with_examples":0}}
425 | ```
426 |
427 | Note that the third item is the crate root, which in this case is undocumented.
428 |
429 | ### `-w`/`--output-format`: output format
430 |
431 | `--output-format json` emits documentation in the experimental
432 | [JSON format](https://doc.rust-lang.org/nightly/nightly-rustc/rustdoc_json_types/). `--output-format html` has no effect,
433 | and is also accepted on stable toolchains.
434 |
435 | It can also be used with `--show-coverage`. Take a look at its
436 | [documentation](#--show-coverage-get-statistics-about-code-documentation-coverage) for more
437 | information.
438 |
439 | ### `--enable-per-target-ignores`: allow `ignore-foo` style filters for doctests
440 |
441 | Using this flag looks like this:
442 |
443 | ```bash
444 | $ rustdoc src/lib.rs -Z unstable-options --enable-per-target-ignores
445 | ```
446 |
447 | This flag allows you to tag doctests with compiletest style `ignore-foo` filters that prevent
448 | rustdoc from running that test if the target triple string contains foo. For example:
449 |
450 | ```rust
451 | ///```ignore-foo,ignore-bar
452 | ///assert!(2 == 2);
453 | ///```
454 | struct Foo;
455 | ```
456 |
457 | This will not be run when the build target is `super-awesome-foo` or `less-bar-awesome`.
458 | If the flag is not enabled, then rustdoc will consume the filter, but do nothing with it, and
459 | the above example will be run for all targets.
460 | If you want to preserve backwards compatibility for older versions of rustdoc, you can use
461 |
462 | ```rust
463 | ///```ignore,ignore-foo
464 | ///assert!(2 == 2);
465 | ///```
466 | struct Foo;
467 | ```
468 |
469 | In older versions, this will be ignored on all targets, but on newer versions `ignore-gnu` will
470 | override `ignore`.
471 |
472 | ### `--runtool`, `--runtool-arg`: program to run tests with; args to pass to it
473 |
474 | Using these options looks like this:
475 |
476 | ```bash
477 | $ rustdoc src/lib.rs -Z unstable-options --runtool runner --runtool-arg --do-thing --runtool-arg --do-other-thing
478 | ```
479 |
480 | These options can be used to run the doctest under a program, and also pass arguments to
481 | that program. For example, if you want to run your doctests under valgrind you might run
482 |
483 | ```bash
484 | $ rustdoc src/lib.rs -Z unstable-options --runtool valgrind
485 | ```
486 |
487 | Another use case would be to run a test inside an emulator, or through a Virtual Machine.
488 |
489 | ### `--with-examples`: include examples of uses of items as documentation
490 |
491 | This option, combined with `--scrape-examples-target-crate` and
492 | `--scrape-examples-output-path`, is used to implement the functionality in [RFC
493 | #3123](https://github.com/rust-lang/rfcs/pull/3123). Uses of an item (currently
494 | functions / call-sites) are found in a crate and its reverse-dependencies, and
495 | then the uses are included as documentation for that item. This feature is
496 | intended to be used via `cargo doc --scrape-examples`, but the rustdoc-only
497 | workflow looks like:
498 |
499 | ```bash
500 | $ rustdoc examples/ex.rs -Z unstable-options \
501 | --extern foobar=target/deps/libfoobar.rmeta \
502 | --scrape-examples-target-crate foobar \
503 | --scrape-examples-output-path output.calls
504 | $ rustdoc src/lib.rs -Z unstable-options --with-examples output.calls
505 | ```
506 |
507 | First, the library must be checked to generate an `rmeta`. Then a
508 | reverse-dependency like `examples/ex.rs` is given to rustdoc with the target
509 | crate being documented (`foobar`) and a path to output the calls
510 | (`output.calls`). Then, the generated calls file can be passed via
511 | `--with-examples` to the subsequent documentation of `foobar`.
512 |
--------------------------------------------------------------------------------
/src/website-features.md:
--------------------------------------------------------------------------------
1 | # Website 特性
2 |
3 | 这些特性是关于使用`rustdoc`生成的网站。
4 |
5 | ## 自定义搜索引擎
6 |
7 | 如果你经常参考在线 Rust 文档,你会喜欢使用一个自定义搜索引擎。这能让你使用导航地址栏直接搜索 `rustdoc` 网站。大多数浏览器支持这种特性,让你来定义一个包含 `%S`(你搜索的内容)的 URL 模版,比如对于标准库你可以使用这个模板:
8 |
9 | ```text
10 | https://doc.rust-lang.org/stable/std/?search=%s
11 | ```
12 |
13 | 注意这会列出你搜索到的所有结果。如果你想要直接打开搜索到的第一个结果可以使用下面的模板:
14 |
15 | ```text
16 | https://doc.rust-lang.org/stable/std/?search=%s&go_to_first=true
17 | ```
18 |
19 | 这个 URL 在末尾加入了`go_to_first=true`搜索参数,会自动跳转到第一个搜索结果。
20 |
--------------------------------------------------------------------------------
/src/what-is-rustdoc.md:
--------------------------------------------------------------------------------
1 | # 什么是 rustdoc?
2 |
3 | > 中文翻译注(The Chinese translation of [The rustdoc Book][website]):
4 | >
5 | > - 👉 查看更多 Rust 官方文档中英文双语教程,包括双语版[《Rust 程序设计语言》][book-cn](出版书名为《Rust 权威指南》),本站还提供了 [Rust 标准库中文版][std-cn]。
6 | > - 《rustdoc 手册》(*rustdoc Book* 中文版)翻译自 [*rustdoc Book*][website],内容已全部翻译完成,查看此书的 [Github 翻译项目和源码][github-repo]。
7 | > - 本文版最后更新时间:2022-02-04。
8 | > - 本书主要译者:[*David*][david],[Rust 中文翻译项目组][rust-lang-cn] 成员。
9 | > - 本站支持文档中英文切换,点击页面右上角语言图标可切换到相同章节的英文页面,**英文版每天都会自动同步一次官方的最新版本**。
10 | > - 若发现当前页表达错误或帮助我们改进翻译,可点击右上角的编辑按钮打开该页对应源码文件进行编辑和修改,Rust 中文资源的开源组织发展离不开大家,感谢您的支持和帮助!
11 |
12 | 标准 Rust 版本包含了名为 `rustdoc` 的工具。它的作用是为 Rust 项目生成文档,Rustdoc 接受一个 crate 根目录或者一个 markdown 文件作为参数,生成 HTML,CSS 和 JavaScript 文件。
13 |
14 | ## 基本使用
15 |
16 | 让我们试用一下,使用 Cargo 创建一个新项目
17 |
18 | ```bash
19 | $ cargo new docs --lib
20 | $ cd docs
21 | ```
22 |
23 | 在 `src/lib.rs` 中,Cargo 生成了一些示例代码,将其删除并替换为下面的代码:
24 |
25 | ```rust
26 | /// foo is a function
27 | fn foo() {}
28 | ```
29 |
30 | 然后我们运行 `rustdoc`。我们可以在 crate 根路径执行下面的命令:
31 |
32 | ```bash
33 | $ rustdoc src/lib.rs
34 | ```
35 |
36 | 这会创建一个新目录 `doc`,其中包含一个网站。在我们的例子中,主页面是 `doc/lib/index.html`。如果你使用浏览器打开,可以看到一个带有搜索栏的页面,在顶部可以看到“Crate lib”,页面没有内容。
37 |
38 | ## 配置 rustdoc
39 |
40 | 现在有两个问题:第一,为什么我们的包名字是“lib”?第二,为什么没有任何内容?
41 |
42 | 第一个问题的原因是因为 `rustdoc` 试图更好用,像 `rustc`, 就假定我们 crate 的名字就是 crate 根目录文件的名字。为了修复这个问题,可以通过命令行传递参数:
43 |
44 | ```bash
45 | $ rustdoc src/lib.rs --crate-name docs
46 | ```
47 |
48 | 现在,将生成`doc/docs/index.html` 文件,页面名称为“Crate docs”。
49 |
50 | 对于第二个问题,因为我们的 `foo` 函数不是公共的;`rustdoc` 默认只会为公共函数生成文档,如果我们将代码修改为
51 |
52 | ```rust
53 | /// foo is a function
54 | pub fn foo() {}
55 | ```
56 |
57 | 然后重新运行 `rustdoc`:
58 |
59 | ```bash
60 | $ rustdoc src/lib.rs --crate-name docs
61 | ```
62 |
63 | 现在我们生成了文档,打开 `doc/docs/index.html`,显示了 `foo` 函数的连接页面,文件位置是 `doc/docs/fn.foo.html`。在函数的页面上,你可以看到我们写的注释“foo is a function”。
64 |
65 | ## 通过 Cargo 使用 rustdoc
66 |
67 | Cargo 整合了 `rustdoc`,使得生成文档更容易。代替 `rustdoc` 命令,我们可以这样做:
68 |
69 | ```bash
70 | $ cargo doc
71 | ```
72 |
73 | 实际上,会这样调用 `rustdoc`:
74 |
75 | ```bash
76 | $ rustdoc --crate-name docs src/lib.rs -o /docs/target/doc -L
77 | dependency=/docs/target/debug/deps
78 | ```
79 |
80 | 你可以使用 `cargo doc --verbose` 看到这个过程。
81 |
82 | 它会自动生成正确的 crate 名称 `--crate-name`,同时指向 `src/lib.rs`。但是其他的参数表示什么呢?
83 |
84 | - `-o` 控制文档的输出。请注意,Cargo 会把生成的文档放在`target`目录,而不是顶层的 `doc` 目录,。这是 Cargo 项目中生成文件的惯用位置。
85 | - `-L` 帮助 rustdoc 找到代码的依赖,如果我们的项目有依赖,也会生成依赖的文档。
86 |
87 | ## Outer 和 inner 文档
88 |
89 | `///` 语法用来对下面一个 item 生成文档,所以称为 outer 文档。还有另一种语法:`//!`,用来生成 item 内部的文档,叫做 inner 文档,通常用来对整个 crate 生成文档,因为是 crate 的根,没有 item 在前面。所以为了生成整个 crate 的文档,你需要使用 `//!`语法,例如:
90 |
91 | ```rust
92 | //! This is my first rust crate
93 | ```
94 |
95 | 当这样用的时候,会生成 item 内部的文档,也就是 crate 自己。
96 |
97 | 为了获取更多 `//!` 的信息,请看 [the Book](https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#commenting-contained-items)
98 |
99 | ## 利用单独的 Markdown 文件
100 |
101 | `rustdoc` 可以为单独的 markdown 文件生成 HTML。让我们尝试一下,创建 `README.md`,并输入如下内容:
102 |
103 | ````text
104 | # Docs
105 |
106 | This is a project to test out `rustdoc`.
107 |
108 | [Here is a link!](https://www.rust-lang.org)
109 |
110 | ## Example
111 |
112 | ```rust
113 | fn foo() -> i32 {
114 | 1 + 1
115 | }
116 | ```
117 | ````
118 |
119 | 然后运行 `rustdoc` 命令:
120 |
121 | ```bash
122 | $ rustdoc README.md
123 | ```
124 |
125 | 你能发现生成的 `docs/doc/README.html` 文件。
126 |
127 | 不过现在 Cargo 不能这样操作 markdown 文件。
128 |
129 | ## 总结
130 |
131 | 本节涵盖了 `rustdoc` 的基本使用方法。本书的剩余部分会展示 `rustdoc` 所有的可选功能,以及如何使用它们。
132 |
133 | [website]: https://doc.rust-lang.org/rustdoc/
134 | [book-cn]: https://rustwiki.org/zh-CN/book/
135 | [std-cn]: https://rustwiki.org/zh-CN/std/
136 | [github-repo]: https://github.com/rust-lang-cn/rustdoc-cn
137 | [rust-lang-cn]: https://github.com/rust-lang-cn
138 | [david]: https://github.com/wendajiang
139 |
--------------------------------------------------------------------------------
/src/what-to-include.md:
--------------------------------------------------------------------------------
1 | # 什么包含(和排除)
2 |
3 | 说起来项目中的所有内容都需要有文档简单正确,但是我们如何才能做到,以及是否还有内容没有文档?
4 |
5 | 在顶层的 `src/lib.rs` 或者你的二进制项目 `main.rs` 文件中,包含下面的属性:
6 |
7 | ```rust
8 | #![warn(missing_docs)]
9 | ```
10 |
11 | 现在运行 `cargo doc`,检查输出,这是一个例子:
12 |
13 | ```text
14 | Documenting docdemo v0.1.0 (/Users/username/docdemo)
15 | warning: missing documentation for the crate
16 | --> src/main.rs:1:1
17 | |
18 | 1 | / #![warn(missing_docs)]
19 | 2 | |
20 | 3 | | fn main() {
21 | 4 | | println!("Hello, world!");
22 | 5 | | }
23 | | |_^
24 | |
25 | note: the lint level is defined here
26 | --> src/main.rs:1:9
27 | |
28 | 1 | #![warn(missing_docs)]
29 | | ^^^^^^^^^^^^
30 |
31 | warning: 1 warning emitted
32 |
33 | Finished dev [unoptimized + debuginfo] target(s) in 2.96s
34 | ```
35 |
36 | 作为一个库作者,加入 lint `#![deny(missing_docs)]` 是一个确保项目拥有良好文档的好方法,`#![warn(missing_docs)]` 是通向良好文档的好方法。除了文档,`#![deny(missing_doc_code_examples)]` 确保每个函数有一个使用示例。在我们上面的例子中,添加 crate 级别的 lint 来警告。
37 |
38 | 下面的章节有更多 lints 的细节 [Lints][rustdoc-lints]。
39 |
40 | ## 例子
41 |
42 | 当然这很简单,但是文档的力量之一是展示的代码易于理解,而不是生产级别。文档通常会忽略错误处理,因为例子需要排除一些不必要的内容保持简单。
43 |
44 | `Async` 是一个好例子。为了执行 `async` 例子,一个 executor 是需要的,例子中通常会省略它,让用户自己将 `async` 代码放到自己的运行时。
45 |
46 | 最好不要在例子中使用 `unwrap()`,并且如果错误处理使得例子难以理解应该被隐藏起来。
47 |
48 | ````text
49 | /// Example
50 | /// ```rust
51 | /// let fourtytwo = "42".parse::()?;
52 | /// println!("{} + 10 = {}", fourtytwo, fourtytwo+10);
53 | /// ```
54 | ````
55 |
56 | 当 rustdoc wrap 这些到 main 函数中,会编译错误因为 `ParseIntError` trait 没有实现。为了同时帮助读者和测试,这个例子还需要增加些额外代码:
57 |
58 | ````text
59 | /// Example
60 | /// ```rust
61 | /// # main() -> Result<(), std::num::ParseIntError> {
62 | /// let fortytwo = "42".parse::()?;
63 | /// println!("{} + 10 = {}", fortytwo, fortytwo+10);
64 | /// # Ok(())
65 | /// # }
66 | /// ```
67 | ````
68 |
69 | 这两个例子在文档页面是相同的,但是对你 crate 的使用者有一些额外的信息。更多的文档测试内容在接下来的 [文档测试] 章节中。
70 |
71 | ## 什么被排除
72 |
73 | 默认情况下,你的公共接口可能会默认包含在 rustdoc 输出中。`#[doc(hidden)]` 属性可以隐藏实现细节来鼓励本 crate 的惯用法。
74 |
75 | 比如,一个内部的 `macro!` 使得 crate 更容易实现如果对用户暴露会使得用户困惑。一个内部的`Error`类型可能存在,并且 `impl` 细节应该被隐藏,如同 [API Guidelines] 中描述的一样。
76 |
77 | ## 自定义输出
78 |
79 | 传递一个自定义 css 文件给 `rustdoc` 定义文档的款式是可行的。
80 |
81 | ```bash
82 | rustdoc --extend-css custom.css src/lib.rs
83 | ```
84 |
85 | 一个良好的例子就是使用这个特性来创建本书的暗黑主题。记住,暗黑主题也包含在点击画笔的输出中。使用可选参数可以很容易使用自定义主题 `.css` 文件:
86 |
87 | ```bash
88 | rustdoc --theme awesome.css src/lib.rs
89 | ```
90 |
91 | 这是一个新主题 [Ayu] 的例子。
92 |
93 | [Ayu]: https://github.com/rust-lang/rust/blob/master/src/librustdoc/html/static/themes/ayu.css
94 | [API Guidelines]: https://rust-lang.github.io/api-guidelines/documentation.html#rustdoc-does-not-show-unhelpful-implementation-details-c-hidden
95 | [Documentation tests]: documentation-tests.md
96 | [on this blog]: https://blog.guillaume-gomez.fr/articles/2016-09-16+Generating+doc+with+rustdoc+and+a+custom+theme
97 | [rustdoc-lints]: lints.md
98 |
--------------------------------------------------------------------------------