Skip to content

Commit f8723f9

Browse files
authored
Rollup merge of rust-lang#102239 - joshtriplett:style-guide, r=calebcartwright
Move style guide to rust-lang/rust Per [RFC 3309](https://rust-lang.github.io/rfcs/3309-style-team.html).
2 parents 5e04567 + 9a72a66 commit f8723f9

14 files changed

+2008
-0
lines changed

src/bootstrap/builder.rs

+1
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,7 @@ impl<'a> Builder<'a> {
704704
doc::Miri,
705705
doc::EmbeddedBook,
706706
doc::EditionGuide,
707+
doc::StyleGuide,
707708
),
708709
Kind::Dist => describe!(
709710
dist::Docs,

src/bootstrap/doc.rs

+1
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ book!(
8282
Reference, "src/doc/reference", "reference", submodule;
8383
RustByExample, "src/doc/rust-by-example", "rust-by-example", submodule;
8484
RustdocBook, "src/doc/rustdoc", "rustdoc";
85+
StyleGuide, "src/doc/style-guide", "style-guide";
8586
);
8687

8788
fn open(builder: &Builder<'_>, path: impl AsRef<Path>) {

src/doc/index.md

+6
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,12 @@ resources useful.
113113
[The Reference](reference/index.html) is not a formal spec, but is more detailed and
114114
comprehensive than the book.
115115

116+
## The Style Guide
117+
118+
[The Rust Style Guide](style-guide/index.html) describes the standard formatting of Rust
119+
code. Most developers use rustfmt to format their code, and rustfmt's default
120+
formatting matches this style guide.
121+
116122
## The Rustonomicon
117123

118124
[The Rustonomicon](nomicon/index.html) is your guidebook to the dark arts of unsafe

src/doc/style-guide/book.toml

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
[book]
2+
title = "The Rust Style Guide"
3+
author = "The Rust Style Team"
4+
multilingual = false
5+
src = "src"
6+
7+
[output.html]
8+
git-repository-url = "https://github.com/rust-lang/rust/tree/HEAD/src/doc/style-guide/"

src/doc/style-guide/src/README.md

+190
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
# Rust Style Guide
2+
3+
## Motivation - why use a formatting tool?
4+
5+
Formatting code is a mostly mechanical task which takes both time and mental
6+
effort. By using an automatic formatting tool, a programmer is relieved of
7+
this task and can concentrate on more important things.
8+
9+
Furthermore, by sticking to an established style guide (such as this one),
10+
programmers don't need to formulate ad hoc style rules, nor do they need to
11+
debate with other programmers what style rules should be used, saving time,
12+
communication overhead, and mental energy.
13+
14+
Humans comprehend information through pattern matching. By ensuring that all
15+
Rust code has similar formatting, less mental effort is required to comprehend a
16+
new project, lowering the barrier to entry for new developers.
17+
18+
Thus, there are productivity benefits to using a formatting tool (such as
19+
rustfmt), and even larger benefits by using a community-consistent formatting,
20+
typically by using a formatting tool's default settings.
21+
22+
23+
## Formatting conventions
24+
25+
### Indentation and line width
26+
27+
* Use spaces, not tabs.
28+
* Each level of indentation must be four spaces (that is, all indentation
29+
outside of string literals and comments must be a multiple of four).
30+
* The maximum width for a line is 100 characters.
31+
* A tool should be configurable for all three of these variables.
32+
33+
34+
### Blank lines
35+
36+
Separate items and statements by either zero or one blank lines (i.e., one or
37+
two newlines). E.g,
38+
39+
```rust
40+
fn foo() {
41+
let x = ...;
42+
43+
let y = ...;
44+
let z = ...;
45+
}
46+
47+
fn bar() {}
48+
fn baz() {}
49+
```
50+
51+
Formatting tools should make the bounds on blank lines configurable: there
52+
should be separate minimum and maximum numbers of newlines between both
53+
statements and (top-level) items (i.e., four options). As described above, the
54+
defaults for both statements and items should be minimum: 1, maximum: 2.
55+
56+
57+
### [Module-level items](items.md)
58+
### [Statements](statements.md)
59+
### [Expressions](expressions.md)
60+
### [Types](types.md)
61+
62+
63+
### Comments
64+
65+
The following guidelines for comments are recommendations only, a mechanical
66+
formatter might skip formatting of comments.
67+
68+
Prefer line comments (`//`) to block comments (`/* ... */`).
69+
70+
When using line comments there should be a single space after the opening sigil.
71+
72+
When using single-line block comments there should be a single space after the
73+
opening sigil and before the closing sigil. Multi-line block comments should
74+
have a newline after the opening sigil and before the closing sigil.
75+
76+
Prefer to put a comment on its own line. Where a comment follows code, there
77+
should be a single space before it. Where a block comment is inline, there
78+
should be surrounding whitespace as if it were an identifier or keyword. There
79+
should be no trailing whitespace after a comment or at the end of any line in a
80+
multi-line comment. Examples:
81+
82+
```rust
83+
// A comment on an item.
84+
struct Foo { ... }
85+
86+
fn foo() {} // A comment after an item.
87+
88+
pub fn foo(/* a comment before an argument */ x: T) {...}
89+
```
90+
91+
Comments should usually be complete sentences. Start with a capital letter, end
92+
with a period (`.`). An inline block comment may be treated as a note without
93+
punctuation.
94+
95+
Source lines which are entirely a comment should be limited to 80 characters
96+
in length (including comment sigils, but excluding indentation) or the maximum
97+
width of the line (including comment sigils and indentation), whichever is
98+
smaller:
99+
100+
```rust
101+
// This comment goes up to the ................................. 80 char margin.
102+
103+
{
104+
// This comment is .............................................. 80 chars wide.
105+
}
106+
107+
{
108+
{
109+
{
110+
{
111+
{
112+
{
113+
// This comment is limited by the ......................... 100 char margin.
114+
}
115+
}
116+
}
117+
}
118+
}
119+
}
120+
```
121+
122+
#### Doc comments
123+
124+
Prefer line comments (`///`) to block comments (`/** ... */`).
125+
126+
Prefer outer doc comments (`///` or `/** ... */`), only use inner doc comments
127+
(`//!` and `/*! ... */`) to write module-level or crate-level documentation.
128+
129+
Doc comments should come before attributes.
130+
131+
### Attributes
132+
133+
Put each attribute on its own line, indented to the level of the item.
134+
In the case of inner attributes (`#!`), indent it to the level of the inside of
135+
the item. Prefer outer attributes, where possible.
136+
137+
For attributes with argument lists, format like functions.
138+
139+
```rust
140+
#[repr(C)]
141+
#[foo(foo, bar)]
142+
struct CRepr {
143+
#![repr(C)]
144+
x: f32,
145+
y: f32,
146+
}
147+
```
148+
149+
For attributes with an equal sign, there should be a single space before and
150+
after the `=`, e.g., `#[foo = 42]`.
151+
152+
There must only be a single `derive` attribute. Note for tool authors: if
153+
combining multiple `derive` attributes into a single attribute, the ordering of
154+
the derived names should be preserved. E.g., `#[derive(bar)] #[derive(foo)]
155+
struct Baz;` should be formatted to `#[derive(bar, foo)] struct Baz;`.
156+
157+
### *small* items
158+
159+
In many places in this guide we specify that a formatter may format an item
160+
differently if it is *small*, for example struct literals:
161+
162+
```rust
163+
// Normal formatting
164+
Foo {
165+
f1: an_expression,
166+
f2: another_expression(),
167+
}
168+
169+
// *small* formatting
170+
Foo { f1, f2 }
171+
```
172+
173+
We leave it to individual tools to decide on exactly what *small* means. In
174+
particular, tools are free to use different definitions in different
175+
circumstances.
176+
177+
Some suitable heuristics are the size of the item (in characters) or the
178+
complexity of an item (for example, that all components must be simple names,
179+
not more complex sub-expressions). For more discussion on suitable heuristics,
180+
see [this issue](https://github.com/rust-lang-nursery/fmt-rfcs/issues/47).
181+
182+
Tools should give the user an option to ignore such heuristics and always use
183+
the normal formatting.
184+
185+
186+
## [Non-formatting conventions](advice.md)
187+
188+
## [Cargo.toml conventions](cargo.md)
189+
190+
## [Principles used for deciding these guidelines](principles.md)

src/doc/style-guide/src/SUMMARY.md

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Summary
2+
3+
[Introduction](README.md)
4+
5+
- [Module-level items](items.md)
6+
- [Statements](statements.md)
7+
- [Expressions](expressions.md)
8+
- [Types](types.md)
9+
- [Non-formatting conventions](advice.md)
10+
- [`Cargo.toml` conventions](cargo.md)
11+
- [Principles used for deciding these guidelines](principles.md)

src/doc/style-guide/src/advice.md

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Other style advice
2+
3+
## Expressions
4+
5+
Prefer to use Rust's expression oriented nature where possible;
6+
7+
```rust
8+
// use
9+
let x = if y { 1 } else { 0 };
10+
// not
11+
let x;
12+
if y {
13+
x = 1;
14+
} else {
15+
x = 0;
16+
}
17+
```
18+
19+
## Names
20+
21+
* Types shall be `UpperCamelCase`,
22+
* Enum variants shall be `UpperCamelCase`,
23+
* Struct fields shall be `snake_case`,
24+
* Function and method names shall be `snake_case`,
25+
* Local variables shall be `snake_case`,
26+
* Macro names shall be `snake_case`,
27+
* Constants (`const`s and immutable `static`s) shall be `SCREAMING_SNAKE_CASE`.
28+
* When a name is forbidden because it is a reserved word (e.g., `crate`), use a
29+
trailing underscore to make the name legal (e.g., `crate_`), or use raw
30+
identifiers if possible.
31+
32+
### Modules
33+
34+
Avoid `#[path]` annotations where possible.

src/doc/style-guide/src/cargo.md

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# Cargo.toml conventions
2+
3+
## Formatting conventions
4+
5+
Use the same line width and indentation as Rust code.
6+
7+
Put a blank line between the last key-value pair in a section and the header of
8+
the next section. Do not place a blank line between section headers and the
9+
key-value pairs in that section, or between key-value pairs in a section.
10+
11+
Sort key names alphabetically within each section, with the exception of the
12+
`[package]` section. Put the `[package]` section at the top of the file; put
13+
the `name` and `version` keys in that order at the top of that section,
14+
followed by the remaining keys other than `description` in alphabetical order,
15+
followed by the `description` at the end of that section.
16+
17+
Don't use quotes around any standard key names; use bare keys. Only use quoted
18+
keys for non-standard keys whose names require them, and avoid introducing such
19+
key names when possible. See the [TOML
20+
specification](https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.4.0.md#table)
21+
for details.
22+
23+
Put a single space both before and after the `=` between a key and value. Do
24+
not indent any key names; start all key names at the start of a line.
25+
26+
Use multi-line strings (rather than newline escape sequences) for any string
27+
values that include multiple lines, such as the crate description.
28+
29+
For array values, such as a list of authors, put the entire list on the same
30+
line as the key, if it fits. Otherwise, use block indentation: put a newline
31+
after the opening square bracket, indent each item by one indentation level,
32+
put a comma after each item (including the last), and put the closing square
33+
bracket at the start of a line by itself after the last item.
34+
35+
```rust
36+
authors = [
37+
"A Uthor <[email protected]>",
38+
"Another Author <[email protected]>",
39+
]
40+
```
41+
42+
For table values, such as a crate dependency with a path, write the entire
43+
table using curly braces and commas on the same line as the key if it fits. If
44+
the entire table does not fit on the same line as the key, separate it out into
45+
a separate section with key-value pairs:
46+
47+
```toml
48+
[dependencies]
49+
crate1 = { path = "crate1", version = "1.2.3" }
50+
51+
[dependencies.extremely_long_crate_name_goes_here]
52+
path = "extremely_long_path_name_goes_right_here"
53+
version = "4.5.6"
54+
```
55+
56+
## Metadata conventions
57+
58+
The authors list should consist of strings that each contain an author name
59+
followed by an email address in angle brackets: `Full Name <email@address>`.
60+
It should not contain bare email addresses, or names without email addresses.
61+
(The authors list may also include a mailing list address without an associated
62+
name.)
63+
64+
The license field must contain a valid [SPDX
65+
expression](https://spdx.org/spdx-specification-21-web-version#h.jxpfx0ykyb60),
66+
using valid [SPDX license names](https://spdx.org/licenses/). (As an exception,
67+
by widespread convention, the license field may use `/` in place of ` OR `; for
68+
example, `MIT/Apache-2.0`.)
69+
70+
The homepage field, if present, must consist of a single URL, including the
71+
scheme (e.g. `https://example.org/`, not just `example.org`.)
72+
73+
Within the description field, wrap text at 80 columns. Don't start the
74+
description field with the name of the crate (e.g. "cratename is a ..."); just
75+
describe the crate itself. If providing a multi-sentence description, the first
76+
sentence should go on a line by itself and summarize the crate, like the
77+
subject of an email or commit message; subsequent sentences can then describe
78+
the crate in more detail.

0 commit comments

Comments
 (0)