]> git.lizzy.rs Git - rust.git/blob - src/doc/trpl/documentation.md
Rollup merge of #24508 - steveklabnik:gh24228, r=alexcrichton
[rust.git] / src / doc / trpl / documentation.md
1 % Documentation
2
3 Documentation is an important part of any software project, and it's
4 first-class in Rust. Let's talk about the tooling Rust gives you to
5 document your project.
6
7 ## About `rustdoc`
8
9 The Rust distribution includes a tool, `rustdoc`, that generates documentation.
10 `rustdoc` is also used by Cargo through `cargo doc`.
11
12 Documentation can be generated in two ways: from source code, and from
13 standalone Markdown files.
14
15 ## Documenting source code
16
17 The primary way of documenting a Rust project is through annotating the source
18 code. You can use documentation comments for this purpose:
19
20 ```rust,ignore
21 /// Constructs a new `Rc<T>`.
22 ///
23 /// # Examples
24 ///
25 /// ```
26 /// use std::rc::Rc;
27 ///
28 /// let five = Rc::new(5);
29 /// ```
30 pub fn new(value: T) -> Rc<T> {
31     // implementation goes here
32 }
33 ```
34
35 This code generates documentation that looks [like this][rc-new]. I've left the
36 implementation out, with a regular comment in its place. That's the first thing
37 to notice about this annotation: it uses `///`, instead of `//`. The triple slash
38 indicates a documentation comment.
39
40 Documentation comments are written in Markdown.
41
42 Rust keeps track of these comments, and uses them when generating
43 documentation. This is important when documenting things like enums:
44
45 ```
46 /// The `Option` type. See [the module level documentation](../) for more.
47 enum Option<T> {
48     /// No value
49     None,
50     /// Some value `T`
51     Some(T),
52 }
53 ```
54
55 The above works, but this does not:
56
57 ```rust,ignore
58 /// The `Option` type. See [the module level documentation](../) for more.
59 enum Option<T> {
60     None, /// No value
61     Some(T), /// Some value `T`
62 }
63 ```
64
65 You'll get an error:
66
67 ```text
68 hello.rs:4:1: 4:2 error: expected ident, found `}`
69 hello.rs:4 }
70            ^
71 ```
72
73 This [unfortunate error](https://github.com/rust-lang/rust/issues/22547) is
74 correct: documentation comments apply to the thing after them, and there's no
75 thing after that last comment.
76
77 [rc-new]: http://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.new
78
79 ### Writing documentation comments
80
81 Anyway, let's cover each part of this comment in detail:
82
83 ```
84 /// Constructs a new `Rc<T>`.
85 # fn foo() {}
86 ```
87
88 The first line of a documentation comment should be a short summary of its
89 functionality. One sentence. Just the basics. High level.
90
91 ```
92 ///
93 /// Other details about constructing `Rc<T>`s, maybe describing complicated
94 /// semantics, maybe additional options, all kinds of stuff.
95 ///
96 # fn foo() {}
97 ```
98
99 Our original example had just a summary line, but if we had more things to say,
100 we could have added more explanation in a new paragraph.
101
102 #### Special sections
103
104 ```
105 /// # Examples
106 # fn foo() {}
107 ```
108
109 Next, are special sections. These are indicated with a header, `#`. There
110 are three kinds of headers that are commonly used. They aren't special syntax,
111 just convention, for now.
112
113 ```
114 /// # Panics
115 # fn foo() {}
116 ```
117
118 Unrecoverable misuses of a function (i.e. programming errors) in Rust are
119 usually indicated by panics, which kill the whole current thread at the very
120 least. If your function has a non-trivial contract like this, that is
121 detected/enforced by panics, documenting it is very important.
122
123 ```
124 /// # Failures
125 # fn foo() {}
126 ```
127
128 If your function or method returns a `Result<T, E>`, then describing the
129 conditions under which it returns `Err(E)` is a nice thing to do. This is
130 slightly less important than `Panics`, because failure is encoded into the type
131 system, but it's still a good thing to do.
132
133 ```
134 /// # Safety
135 # fn foo() {}
136 ```
137
138 If your function is `unsafe`, you should explain which invariants the caller is
139 responsible for upholding.
140
141 ```
142 /// # Examples
143 ///
144 /// ```
145 /// use std::rc::Rc;
146 ///
147 /// let five = Rc::new(5);
148 /// ```
149 # fn foo() {}
150 ```
151
152 Third, `Examples`. Include one or more examples of using your function or
153 method, and your users will love you for it. These examples go inside of
154 code block annotations, which we'll talk about in a moment, and can have
155 more than one section:
156
157 ```
158 /// # Examples
159 ///
160 /// Simple `&str` patterns:
161 ///
162 /// ```
163 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
164 /// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
165 /// ```
166 ///
167 /// More complex patterns with a lambda:
168 ///
169 /// ```
170 /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
171 /// assert_eq!(v, vec!["abc", "def", "ghi"]);
172 /// ```
173 # fn foo() {}
174 ```
175
176 Let's discuss the details of these code blocks.
177
178 #### Code block annotations
179
180 To write some Rust code in a comment, use the triple graves:
181
182 ```
183 /// ```
184 /// println!("Hello, world");
185 /// ```
186 # fn foo() {}
187 ```
188
189 If you want something that's not Rust code, you can add an annotation:
190
191 ```
192 /// ```c
193 /// printf("Hello, world\n");
194 /// ```
195 # fn foo() {}
196 ```
197
198 This will highlight according to whatever language you're showing off.
199 If you're just showing plain text, choose `text`.
200
201 It's important to choose the correct annotation here, because `rustdoc` uses it
202 in an interesting way: It can be used to actually test your examples, so that
203 they don't get out of date. If you have some C code but `rustdoc` thinks it's
204 Rust because you left off the annotation, `rustdoc` will complain when trying to
205 generate the documentation.
206
207 ## Documentation as tests
208
209 Let's discuss our sample example documentation:
210
211 ```
212 /// ```
213 /// println!("Hello, world");
214 /// ```
215 # fn foo() {}
216 ```
217
218 You'll notice that you don't need a `fn main()` or anything here. `rustdoc` will
219 automatically add a main() wrapper around your code, and in the right place.
220 For example:
221
222 ```
223 /// ```
224 /// use std::rc::Rc;
225 ///
226 /// let five = Rc::new(5);
227 /// ```
228 # fn foo() {}
229 ```
230
231 This will end up testing:
232
233 ```
234 fn main() {
235     use std::rc::Rc;
236     let five = Rc::new(5);
237 }
238 ```
239
240 Here's the full algorithm rustdoc uses to postprocess examples:
241
242 1. Any leading `#![foo]` attributes are left intact as crate attributes.
243 2. Some common `allow` attributes are inserted, including
244    `unused_variables`, `unused_assignments`, `unused_mut`,
245    `unused_attributes`, and `dead_code`. Small examples often trigger
246    these lints.
247 3. If the example does not contain `extern crate`, then `extern crate
248    <mycrate>;` is inserted.
249 2. Finally, if the example does not contain `fn main`, the remainder of the
250    text is wrapped in `fn main() { your_code }`
251
252 Sometimes, this isn't enough, though. For example, all of these code samples
253 with `///` we've been talking about? The raw text:
254
255 ```text
256 /// Some documentation.
257 # fn foo() {}
258 ```
259
260 looks different than the output:
261
262 ```
263 /// Some documentation.
264 # fn foo() {}
265 ```
266
267 Yes, that's right: you can add lines that start with `# `, and they will
268 be hidden from the output, but will be used when compiling your code. You
269 can use this to your advantage. In this case, documentation comments need
270 to apply to some kind of function, so if I want to show you just a
271 documentation comment, I need to add a little function definition below
272 it. At the same time, it's just there to satisfy the compiler, so hiding
273 it makes the example more clear. You can use this technique to explain
274 longer examples in detail, while still preserving the testability of your
275 documentation. For example, this code:
276
277 ```
278 let x = 5;
279 let y = 6;
280 println!("{}", x + y);
281 ```
282
283 Here's an explanation, rendered:
284
285 First, we set `x` to five:
286
287 ```
288 let x = 5;
289 # let y = 6;
290 # println!("{}", x + y);
291 ```
292
293 Next, we set `y` to six:
294
295 ```
296 # let x = 5;
297 let y = 6;
298 # println!("{}", x + y);
299 ```
300
301 Finally, we print the sum of `x` and `y`:
302
303 ```
304 # let x = 5;
305 # let y = 6;
306 println!("{}", x + y);
307 ```
308
309 Here's the same explanation, in raw text:
310
311 > First, we set `x` to five:
312 >
313 > ```text
314 > let x = 5;
315 > # let y = 6;
316 > # println!("{}", x + y);
317 > ```
318 >
319 > Next, we set `y` to six:
320 >
321 > ```text
322 > # let x = 5;
323 > let y = 6;
324 > # println!("{}", x + y);
325 > ```
326 >
327 > Finally, we print the sum of `x` and `y`:
328 >
329 > ```text
330 > # let x = 5;
331 > # let y = 6;
332 > println!("{}", x + y);
333 > ```
334
335 By repeating all parts of the example, you can ensure that your example still
336 compiles, while only showing the parts that are relevant to that part of your
337 explanation.
338
339 ### Documenting macros
340
341 Here’s an example of documenting a macro:
342
343 ```
344 /// Panic with a given message unless an expression evaluates to true.
345 ///
346 /// # Examples
347 ///
348 /// ```
349 /// # #[macro_use] extern crate foo;
350 /// # fn main() {
351 /// panic_unless!(1 + 1 == 2, “Math is broken.”);
352 /// # }
353 /// ```
354 ///
355 /// ```should_panic
356 /// # #[macro_use] extern crate foo;
357 /// # fn main() {
358 /// panic_unless!(true == false, “I’m broken.”);
359 /// # }
360 /// ```
361 #[macro_export]
362 macro_rules! panic_unless {
363     ($condition:expr, $($rest:expr),+) => ({ if ! $condition { panic!($($rest),+); } });
364 }
365 # fn main() {}
366 ```
367
368 You’ll note three things: we need to add our own `extern crate` line, so that
369 we can add the `#[macro_use]` attribute. Second, we’ll need to add our own
370 `main()` as well. Finally, a judicious use of `#` to comment out those two
371 things, so they don’t show up in the output.
372
373 ### Running documentation tests
374
375 To run the tests, either
376
377 ```bash
378 $ rustdoc --test path/to/my/crate/root.rs
379 # or
380 $ cargo test
381 ```
382
383 That's right, `cargo test` tests embedded documentation too. However, 
384 `cargo test` will not test binary crates, only library ones. This is
385 due to the way `rustdoc` works: it links against the library to be tested,
386 but with a binary, there’s nothing to link to.
387
388 There are a few more annotations that are useful to help `rustdoc` do the right
389 thing when testing your code:
390
391 ```
392 /// ```ignore
393 /// fn foo() {
394 /// ```
395 # fn foo() {}
396 ```
397
398 The `ignore` directive tells Rust to ignore your code. This is almost never
399 what you want, as it's the most generic. Instead, consider annotating it
400 with `text` if it's not code, or using `#`s to get a working example that
401 only shows the part you care about.
402
403 ```
404 /// ```should_panic
405 /// assert!(false);
406 /// ```
407 # fn foo() {}
408 ```
409
410 `should_panic` tells `rustdoc` that the code should compile correctly, but
411 not actually pass as a test.
412
413 ```
414 /// ```no_run
415 /// loop {
416 ///     println!("Hello, world");
417 /// }
418 /// ```
419 # fn foo() {}
420 ```
421
422 The `no_run` attribute will compile your code, but not run it. This is
423 important for examples such as "Here's how to start up a network service,"
424 which you would want to make sure compile, but might run in an infinite loop!
425
426 ### Documenting modules
427
428 Rust has another kind of doc comment, `//!`. This comment doesn't document the next item, but the enclosing item. In other words:
429
430 ```
431 mod foo {
432     //! This is documentation for the `foo` module.
433     //!
434     //! # Examples
435
436     // ...
437 }
438 ```
439
440 This is where you'll see `//!` used most often: for module documentation. If
441 you have a module in `foo.rs`, you'll often open its code and see this:
442
443 ```
444 //! A module for using `foo`s.
445 //!
446 //! The `foo` module contains a lot of useful functionality blah blah blah
447 ```
448
449 ### Documentation comment style
450
451 Check out [RFC 505][rfc505] for full conventions around the style and format of
452 documentation.
453
454 [rfc505]: https://github.com/rust-lang/rfcs/blob/master/text/0505-api-comment-conventions.md
455
456 ## Other documentation
457
458 All of this behavior works in non-Rust source files too. Because comments
459 are written in Markdown, they're often `.md` files.
460
461 When you write documentation in Markdown files, you don't need to prefix
462 the documentation with comments. For example:
463
464 ```
465 /// # Examples
466 ///
467 /// ```
468 /// use std::rc::Rc;
469 ///
470 /// let five = Rc::new(5);
471 /// ```
472 # fn foo() {}
473 ```
474
475 is just
476
477 ~~~markdown
478 # Examples
479
480 ```
481 use std::rc::Rc;
482
483 let five = Rc::new(5);
484 ```
485 ~~~
486
487 when it's in a Markdown file. There is one wrinkle though: Markdown files need
488 to have a title like this:
489
490 ```markdown
491 % The title
492
493 This is the example documentation.
494 ```
495
496 This `%` line needs to be the very first line of the file.
497
498 ## `doc` attributes
499
500 At a deeper level, documentation comments are sugar for documentation attributes:
501
502 ```
503 /// this
504 # fn foo() {}
505
506 #[doc="this"]
507 # fn bar() {}
508 ```
509
510 are the same, as are these:
511
512 ```
513 //! this
514
515 #![doc="/// this"]
516 ```
517
518 You won't often see this attribute used for writing documentation, but it
519 can be useful when changing some options, or when writing a macro.
520
521 ### Re-exports
522
523 `rustdoc` will show the documentation for a public re-export in both places:
524
525 ```ignore
526 extern crate foo;
527
528 pub use foo::bar;
529 ```
530
531 This will create documentation for bar both inside the documentation for the
532 crate `foo`, as well as the documentation for your crate. It will use the same
533 documentation in both places.
534
535 This behavior can be suppressed with `no_inline`:
536
537 ```ignore
538 extern crate foo;
539
540 #[doc(no_inline)]
541 pub use foo::bar;
542 ```
543
544 ### Controlling HTML
545
546 You can control a few aspects of the HTML that `rustdoc` generates through the
547 `#![doc]` version of the attribute:
548
549 ```
550 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
551        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
552        html_root_url = "http://doc.rust-lang.org/")];
553 ```
554
555 This sets a few different options, with a logo, favicon, and a root URL.
556
557 ## Generation options
558
559 `rustdoc` also contains a few other options on the command line, for further customiziation:
560
561 - `--html-in-header FILE`: includes the contents of FILE at the end of the
562   `<head>...</head>` section.
563 - `--html-before-content FILE`: includes the contents of FILE directly after
564   `<body>`, before the rendered content (including the search bar).
565 - `--html-after-content FILE`: includes the contents of FILE after all the rendered content.
566
567 ## Security note
568
569 The Markdown in documentation comments is placed without processing into
570 the final webpage. Be careful with literal HTML:
571
572 ```rust
573 /// <script>alert(document.cookie)</script>
574 # fn foo() {}
575 ```