Change:
% Documentation <del> `rustdoc` is the built-in tool for generating documentation. It integrates with the compiler to provide accurate hyperlinking between usage of types and their documentation. Furthermore, by not using a separate parser, it will never reject your valid Rust code. </del> <ins> Documentation is an important part of any software project, and it's first-class in Rust. Let's talk about the tooling Rust gives you to document your project. </ins> <del> # Creating Documentation </del> <ins> ## About `rustdoc` </ins> <del> Documenting Rust APIs is quite simple. To document a given item, we have "doc comments": </del> <ins> The Rust distribution includes a tool, `rustdoc`, that generates documentation. `rustdoc` is also used by Cargo through `cargo doc`. </ins> <del> ~~~ # #![allow(unused_attribute)] // the "link" crate attribute is currently required for rustdoc, but normally // isn't needed. #![crate_id = "universe"] #![crate_type= "lib"] //! Tools for dealing with universes (this is a doc comment, and is shown on //! the crate index page. The ! makes it apply to the parent of the comment, //! rather than what follows). # mod workaround_the_outer_function_rustdoc_inserts { /// Widgets are very common (this is a doc comment, and will show up on /// Widget's documentation). pub struct Widget { /// All widgets have a purpose (this is a doc comment, and will show up /// the field's documentation). purpose: String, /// Humans are not allowed to understand some widgets understandable: bool } </del> <ins> Documentation can be generated in two ways: from source code, and from standalone Markdown files. </ins> <del> pub fn recalibrate() { //! Recalibrate a pesky universe (this is also a doc comment, like above, //! the documentation will be applied to the *parent* item, so //! `recalibrate`). /* ... */ } # } ~~~ </del> <ins> ## Documenting source code </ins> <del> Documentation can also be controlled via the `doc` attribute on items. This is implicitly done by the compiler when using the above form of doc comments (converting the slash-based comments to `#[doc]` attributes). </del> <ins> The primary way of documenting a Rust project is through annotating the source code. You can use documentation comments for this purpose: </ins> <del> ~~~ #[doc = " Calculates the factorial of a number. </del> <ins> ```rust,ignore /// Constructs a new `Rc<T>`. /// /// # Examples /// /// ``` /// use std::rc::Rc; /// /// let five = Rc::new(5); /// ``` pub fn new(value: T) -> Rc<T> { // implementation goes here } ``` </ins> <del> Given the input integer `n`, this function will calculate `n!` and return it. "] pub fn factorial(n: int) -> int { if n < 2 {1} else {n * factorial(n - 1)} } # fn main() {} ~~~ </del> <ins> This code generates documentation that looks [like this][rc-new]. I've left the implementation out, with a regular comment in its place. That's the first thing to notice about this annotation: it uses `///`, instead of `//`. The triple slash indicates a documentation comment. </ins> <del> The `doc` attribute can also be used to control how rustdoc emits documentation in some cases. </del> <ins> Documentation comments are written in Markdown. Rust keeps track of these comments, and uses them when generating documentation. This is important when documenting things like enums: </ins> ``` <del> // Rustdoc will inline documentation of a `pub use` into this crate when the // `pub use` reaches across crates, but this behavior can also be disabled. #[doc(no_inline)] pub use std::option::Option; # fn main() {} </del> <ins> /// The `Option` type. See [the module level documentation](../) for more. enum Option<T> { /// No value None, /// Some value `T` Some(T), } </ins> ``` <del> Doc comments are markdown, and are currently parsed with the [hoedown][hoedown] library. rustdoc does not yet do any fanciness such as referencing other items inline, like javadoc's `@see`. One exception to this is that the first paragraph will be used as the "summary" of an item in the generated documentation: </del> <ins> The above works, but this does not: </ins> <del> ~~~ /// A whizbang. Does stuff. (this line is the summary) /// /// Whizbangs are ... struct Whizbang; ~~~ To generate the docs, run `rustdoc universe.rs`. By default, it generates a directory called `doc`, with the documentation for `universe` being in `doc/universe/index.html`. If you are using other crates with `extern crate`, rustdoc will even link to them when you use their types, as long as their documentation has already been generated by a previous run of rustdoc, or the crate advertises that its documentation is hosted at a given URL. </del> <ins> ```rust,ignore /// The `Option` type. See [the module level documentation](../) for more. enum Option<T> { None, /// No value Some(T), /// Some value `T` } ``` </ins> <del> The generated output can be controlled with the `doc` crate attribute, which is how the above advertisement works. An example from the `libstd` documentation: </del> <ins> You'll get an error: </ins> <del> ~~~ #[doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/")]; ~~~ </del> <ins> ```text hello.rs:4:1: 4:2 error: expected ident, found `}` hello.rs:4 } ^ ``` </ins> <del> The `html_root_url` is the prefix that rustdoc will apply to any references to that crate's types etc. </del> <ins> This [unfortunate error](https://github.com/rust-lang/rust/issues/22547) is correct: documentation comments apply to the thing after them, and there's no thing after that last comment. </ins> <del> rustdoc can also generate JSON, for consumption by other tools, with `rustdoc --output-format json`, and also consume already-generated JSON with `rustdoc --input-format json`. </del> <ins> [rc-new]: http://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.new </ins> <del> rustdoc also supports personalizing the output from crates' documentation, similar to markdown options. </del> <ins> ### Writing documentation comments </ins> <del> - `--html-in-header FILE`: includes the contents of `FILE` at the end of the `<head>...</head>` section. - `--html-before-content FILE`: includes the contents of `FILE` directly after `<body>`, before the rendered content (including the search bar). - `--html-after-content FILE`: includes the contents of `FILE` after all the rendered content. </del> <ins> Anyway, let's cover each part of this comment in detail: </ins> <del> # Using the Documentation </del> <ins> ``` /// Constructs a new `Rc<T>`. # fn foo() {} ``` </ins> <del> The web pages generated by rustdoc present the same logical hierarchy that one writes a library with. Every kind of item (function, struct, etc) has its own color, and one can always click on a colored type to jump to its documentation. There is a search bar at the top, which is powered by some JavaScript and a statically-generated search index. No special web server is required for the search. </del> <ins> The first line of a documentation comment should be a short summary of its functionality. One sentence. Just the basics. High level. </ins> <del> [hoedown]: https://github.com/hoedown/hoedown </del> <ins> ``` /// /// Other details about constructing `Rc<T>`s, maybe describing complicated /// semantics, maybe additional options, all kinds of stuff. /// # fn foo() {} ``` </ins> <del> # Testing the Documentation </del> <ins> Our original example had just a summary line, but if we had more things to say, we could have added more explanation in a new paragraph. </ins> <del> `rustdoc` has support for testing code examples which appear in the documentation. This is helpful for keeping code examples up to date with the source code. </del> <ins> #### Special sections </ins> <del> To test documentation, the `--test` argument is passed to rustdoc: </del> <ins> ``` /// # Examples # fn foo() {} ``` </ins> <del> ~~~ {.sh} rustdoc --test crate.rs ~~~ </del> <ins> Next, are special sections. These are indicated with a header, `#`. There are three kinds of headers that are commonly used. They aren't special syntax, just convention, for now. </ins> <del> ## Defining tests </del> <ins> ``` /// # Panics # fn foo() {} ``` </ins> <del> Rust documentation currently uses the markdown format, and rustdoc treats all code blocks as testable-by-default unless they carry a language tag of another language. In order to not run a test over a block of code, the `ignore` string can be added to the three-backtick form of markdown code block. </del> <ins> Unrecoverable misuses of a function (i.e. programming errors) in Rust are usually indicated by panics, which kill the whole current thread at the very least. If your function has a non-trivial contract like this, that is detected/enforced by panics, documenting it is very important. </ins> <del> ~~~md </del> ``` <del> // This is a testable code block </del> <ins> /// # Failures # fn foo() {} </ins> ``` <del> ```rust{.example} // This is rust and also testable ``` </del> <ins> If your function or method returns a `Result<T, E>`, then describing the conditions under which it returns `Err(E)` is a nice thing to do. This is slightly less important than `Panics`, because failure is encoded into the type system, but it's still a good thing to do. </ins> <del> ```ignore // This is not a testable code block </del> <ins> ``` /// # Safety # fn foo() {} </ins> ``` <del> // This is a testable code block (4-space indent) </del> <ins> If your function is `unsafe`, you should explain which invariants the caller is responsible for upholding. </ins> <del> ```sh # this is shell code and not tested </del> ``` <del> ~~~ </del> <ins> /// # Examples /// /// ``` /// use std::rc::Rc; /// /// let five = Rc::new(5); /// ``` # fn foo() {} ``` </ins> <del> You can specify that the test's execution should fail with the `should_fail` directive. </del> <ins> Third, `Examples`. Include one or more examples of using your function or method, and your users will love you for it. These examples go inside of code block annotations, which we'll talk about in a moment, and can have more than one section: </ins> <del> ~~~md ```should_fail // This code block is expected to generate a panic when run </del> ``` <del> ~~~ </del> <ins> /// # Examples /// /// Simple `&str` patterns: /// /// ``` /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect(); /// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]); /// ``` /// /// More complex patterns with a lambda: /// /// ``` /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect(); /// assert_eq!(v, vec!["abc", "def", "ghi"]); /// ``` # fn foo() {} ``` </ins> <del> You can specify that the code block should be compiled but not run with the `no_run` directive. </del> <ins> Let's discuss the details of these code blocks. </ins> <del> ~~~md ```no_run // This code will be compiled but not executed ``` ~~~ </del> <ins> #### Code block annotations </ins> <del> Lastly, you can specify that a code block be compiled as if `--test` were passed to the compiler using the `test_harness` directive. </del> <ins> To write some Rust code in a comment, use the triple graves: </ins> <del> ~~~md ```test_harness #[test] fn foo() { panic!("oops! (will run & register as a failed test)") } </del> ``` <del> ~~~ </del> <ins> /// ``` /// println!("Hello, world"); /// ``` # fn foo() {} ``` </ins> <del> Rustdoc also supplies some extra sugar for helping with some tedious documentation examples. If a line is prefixed with `# `, then the line will not show up in the HTML documentation, but it will be used when testing the code block (NB. the space after the `#` is required, so that one can still write things like `#[derive(Eq)]`). </del> <ins> If you want something that's not Rust code, you can add an annotation: </ins> <del> ~~~md </del> ``` <del> # /! The three following lines are comments, which are usually stripped off by # the doc-generating tool.  In order to display them anyway in this particular # case, the character following the leading '#' is not a usual space like in # these first five lines but a non breakable one. # // showing 'fib' in this documentation would just be tedious and detracts from # // what's actually being documented. # fn fib(n: int) { n + 2 } spawn(move || { fib(200); }) </del> <ins> /// ```c /// printf("Hello, worldn"); /// ``` # fn foo() {} </ins> ``` <del> ~~~ The documentation online would look like `spawn(move || { fib(200); })`, but when testing this code, the `fib` function will be included (so it can compile). </del> <ins> This will highlight according to whatever language you're showing off. If you're just showing plain text, choose `text`. It's important to choose the correct annotation here, because `rustdoc` uses it in an interesting way: It can be used to actually test your examples, so that they don't get out of date. If you have some C code but `rustdoc` thinks it's Rust because you left off the annotation, `rustdoc` will complain when trying to generate the documentation. </ins> <del> Rustdoc will automatically add a `main()` wrapper around your code, and in the right place. For example: </del> <ins> ## Documentation as tests Let's discuss our sample example documentation: ``` /// ``` /// println!("Hello, world"); /// ``` # fn foo() {} ``` You'll notice that you don't need a `fn main()` or anything here. `rustdoc` will automatically add a main() wrapper around your code, and in the right place. For example: </ins> ``` /// ```

Discussion:
E.g. , which is very extensive, and even includes a redefinition of the type! On the other hand is more detailed (i'll note that these aren't precisely equivalent, since is in that module too). Similarly, .
cc
Other somewhat relevant modules: (both module and type are rather empty atm, however) the various primitive types the other containers (most are pretty much undocumented too, unfortunately)
My gut says "Full docs in the module, types should mention 'see module for full docs'
cc me
Steve's gut sounds right to me. Would especially work better if we had sane intra-links.
Although doc'ing the type can be more "portable" in the face of re-exports.
Hm, so I'm now starting to prefer the other direction. Module-level docs are great for telling an overall narrative for people who are exploring, but they are not good when people are looking up a type/method etc. I guess the ideal option would be "both"? But I'm not really sure. As says links could help...

We should have guidelines for how docs are written. Tense, vs , all that stuff.
Fully agree. Among the things it should cover: What a docstring is First paragraph is summary Summary should usually be a single sentence, and should always have a trailing period At least for functions. Our modules almost never have the trailing period. That seems ok to me, but it's all subjective Tense, e.g. "Create a Foo" vs "Creates a Foo" Tense in summary different than tense in rest of documentation? It sometimes is. Is that ok? Proper use of inline code spans whenever referencing e.g. types, variables Proper use of code blocks (<code</code, not <code~~~~</code) Code block modifiers, e.g. , , Common headers seen in docstrings, e.g. ,
cc: Particularly .
I would like to aggregate all these ideas into a single draft document. What are your thoughts about it being an additional section to ? I believe that document needs a lot of work, and adding a rustdoc style guide would help greatly.
They should certainly be related.
It would be nice if we could settle on these things. I want to contribute to the documentation and I end up mimicking the current style in the source files, but that style differs. There's also the issue of vs , see .
I don't know if this is something we care about, but if there is a preference towards British or American spelling, I think it should be a stated part of this guide. is what made me think of this (<3 ;)
Yes, it is something we should care about. I often spell things with British colour though :sweat_smile:
Good point. My belief is that the documentation to date has been using american spelling, because I feel like I would remember if I saw British spelling in it. It would be good to codify this. Personally, I don't care which spelling rules are chosen as long as it's consistent, but given that I believe the docs are using american spelling right now, I would suggest sticking with that.