]> git.lizzy.rs Git - rust.git/blob - Contributing.md
Merge pull request #3333 from topecongiro/macro-arg-single-keyword
[rust.git] / Contributing.md
1 # Contributing
2
3 There are many ways to contribute to Rustfmt. This document lays out what they
4 are and has information on how to get started. If you have any questions about
5 contributing or need help with anything, please ask in the WG-Rustfmt channel
6 on [Discord](https://discordapp.com/invite/rust-lang). Feel free to also ask questions
7 on issues, or file new issues specifically to get help.
8
9 All contributors are expected to follow our [Code of
10 Conduct](CODE_OF_CONDUCT.md).
11
12 ## Test and file issues
13
14 It would be really useful to have people use rustfmt on their projects and file
15 issues where it does something you don't expect.
16
17
18 ## Create test cases
19
20 Having a strong test suite for a tool like this is essential. It is very easy
21 to create regressions. Any tests you can add are very much appreciated.
22
23 The tests can be run with `cargo test`. This does a number of things:
24 * runs the unit tests for a number of internal functions;
25 * makes sure that rustfmt run on every file in `./tests/source/` is equal to its
26   associated file in `./tests/target/`;
27 * runs idempotence tests on the files in `./tests/target/`. These files should
28   not be changed by rustfmt;
29 * checks that rustfmt's code is not changed by running on itself. This ensures
30   that the project bootstraps.
31
32 Creating a test is as easy as creating a new file in `./tests/source/` and an
33 equally named one in `./tests/target/`. If it is only required that rustfmt
34 leaves a piece of code unformatted, it may suffice to only create a target file.
35
36 Whenever there's a discrepancy between the expected output when running tests, a
37 colourised diff will be printed so that the offending line(s) can quickly be
38 identified.
39
40 Without explicit settings, the tests will be run using rustfmt's default
41 configuration. It is possible to run a test using non-default settings in several 
42 ways. Firstly, you can include configuration parameters in comments at the top
43 of the file. For example: to use 3 spaces per tab, start your test with
44 `// rustfmt-tab_spaces: 3`. Just remember that the comment is part of the input,
45 so include in both the source and target files! It is also possible to
46 explicitly specify the name of the expected output file in the target directory.
47 Use `// rustfmt-target: filename.rs` for this. You can also specify a custom
48 configuration by using the `rustfmt-config` directive. Rustfmt will then use
49 that toml file located in `./tests/config/` for its configuration. Including
50 `// rustfmt-config: small_tabs.toml` will run your test with the configuration
51 file found at `./tests/config/small_tabs.toml`. The final option is used when the
52 test source file contains no configuration parameter comments. In this case, the
53 test harness looks for a configuration file with the same filename as the test
54 file in the `./tests/config/` directory, so a test source file named `test-indent.rs`
55 would need a configuration file named `test-indent.toml` in that directory. As an
56 example, the `issue-1111.rs` test file is configured by the file
57 `./tests/config/issue-1111.toml`.
58
59 ## Debugging
60
61 Some `rewrite_*` methods use the `debug!` macro for printing useful information.
62 These messages can be printed by using the environment variable `RUST_LOG=rustfmt=DEBUG`.
63 These traces can be helpful in understanding which part of the code was used
64 and get a better grasp on the execution flow.
65
66 ## Hack!
67
68 Here are some [good starting issues](https://github.com/rust-lang/rustfmt/issues?q=is%3Aopen+is%3Aissue+label%3Agood-first-issue).
69
70 If you've found areas which need polish and don't have issues, please submit a
71 PR, don't feel there needs to be an issue.
72
73
74 ### Guidelines
75
76 Rustfmt bootstraps, that is part of its test suite is running itself on its
77 source code. So, basically, the only style guideline is that you must pass the
78 tests. That ensures that the Rustfmt source code adheres to our own conventions.
79
80 Talking of tests, if you add a new feature or fix a bug, please also add a test.
81 It's really easy, see above for details. Please run `cargo test` before
82 submitting a PR to ensure your patch passes all tests, it's pretty quick.
83
84 Rustfmt is post-1.0 and within major version releases we strive for backwards
85 compatibility (at least when using the default options). That means any code
86 which changes Rustfmt's output must be guarded by either an option or a version
87 check. The latter is implemented as an option called `option`. See the section on
88 [configuration](#Configuration) below.
89
90 Please try to avoid leaving `TODO`s in the code. There are a few around, but I
91 wish there weren't. You can leave `FIXME`s, preferably with an issue number.
92
93
94 ### Version-gate formatting changes
95
96 A change that introduces a different code-formatting should be gated on the
97 `version` configuration. This is to ensure the formatting of the current major
98 release is preserved, while allowing fixes to be implemented for the next
99 release.
100
101 This is done by conditionally guarding the change like so:
102
103 ```rust
104 if config.version() == Version::One { // if the current major release is 1.x
105     // current formatting
106 } else {
107     // new formatting
108 }
109 ```
110
111 This allows the user to apply the next formatting explicitly via the
112 configuration, while being stable by default.
113
114 When the next major release is done, the code block of the previous formatting
115 can be deleted, e.g., the first block in the example above when going from `1.x`
116 to `2.x`.
117
118
119 ### A quick tour of Rustfmt
120
121 Rustfmt is basically a pretty printer - that is, its mode of operation is to
122 take an AST (abstract syntax tree) and print it in a nice way (including staying
123 under the maximum permitted width for a line). In order to get that AST, we
124 first have to parse the source text, we use the Rust compiler's parser to do
125 that (see [src/lib.rs](src/lib.rs)). We shy away from doing anything too fancy, such as
126 algebraic approaches to pretty printing, instead relying on an heuristic
127 approach, 'manually' crafting a string for each AST node. This results in quite
128 a lot of code, but it is relatively simple.
129
130 The AST is a tree view of source code. It carries all the semantic information
131 about the code, but not all of the syntax. In particular, we lose white space
132 and comments (although doc comments are preserved). Rustfmt uses a view of the
133 AST before macros are expanded, so there are still macro uses in the code. The
134 arguments to macros are not an AST, but raw tokens - this makes them harder to
135 format.
136
137 There are different nodes for every kind of item and expression in Rust. For
138 more details see the source code in the compiler -
139 [ast.rs](https://dxr.mozilla.org/rust/source/src/libsyntax/ast.rs) - and/or the
140 [docs](https://doc.rust-lang.org/nightly/nightly-rustc/syntax/ast/index.html).
141
142 Many nodes in the AST (but not all, annoyingly) have a `Span`. A `Span` is a
143 range in the source code, it can easily be converted to a snippet of source
144 text. When the AST does not contain enough information for us, we rely heavily
145 on `Span`s. For example, we can look between spans to try and find comments, or
146 parse a snippet to see how the user wrote their source code.
147
148 The downside of using the AST is that we miss some information - primarily white
149 space and comments. White space is sometimes significant, although mostly we
150 want to ignore it and make our own. We strive to reproduce all comments, but
151 this is sometimes difficult. The crufty corners of Rustfmt are where we hack
152 around the absence of comments in the AST and try to recreate them as best we
153 can.
154
155 Our primary tool here is to look between spans for text we've missed. For
156 example, in a function call `foo(a, b)`, we have spans for `a` and `b`, in this
157 case, there is only a comma and a single space between the end of `a` and the
158 start of `b`, so there is nothing much to do. But if we look at
159 `foo(a /* a comment */, b)`, then between `a` and `b` we find the comment.
160
161 At a higher level, Rustfmt has machinery so that we account for text between
162 'top level' items. Then we can reproduce that text pretty much verbatim. We only
163 count spans we actually reformat, so if we can't format a span it is not missed
164 completely but is reproduced in the output without being formatted. This is
165 mostly handled in [src/missed_spans.rs](src/missed_spans.rs). See also `FmtVisitor::last_pos` in
166 [src/visitor.rs](src/visitor.rs).
167
168
169 #### Some important elements
170
171 At the highest level, Rustfmt uses a `Visitor` implementation called `FmtVisitor`
172 to walk the AST. This is in [src/visitor.rs](src/visitor.rs). This is really just used to walk
173 items, rather than the bodies of functions. We also cover macros and attributes
174 here. Most methods of the visitor call out to `Rewrite` implementations that
175 then walk their own children.
176
177 The `Rewrite` trait is defined in [src/rewrite.rs](src/rewrite.rs). It is implemented for many
178 things that can be rewritten, mostly AST nodes. It has a single function,
179 `rewrite`, which is called to rewrite `self` into an `Option<String>`. The
180 arguments are `width` which is the horizontal space we write into and `offset`
181 which is how much we are currently indented from the lhs of the page. We also
182 take a context which contains information used for parsing, the current block
183 indent, and a configuration (see below).
184
185 ##### Rewrite and Indent
186
187 To understand the indents, consider
188
189 ```
190 impl Foo {
191     fn foo(...) {
192         bar(argument_one,
193             baz());
194     }
195 }
196 ```
197
198 When formatting the `bar` call we will format the arguments in order, after the
199 first one we know we are working on multiple lines (imagine it is longer than
200 written). So, when we come to the second argument, the indent we pass to
201 `rewrite` is 12, which puts us under the first argument. The current block
202 indent (stored in the context) is 8. The former is used for visual indenting
203 (when objects are vertically aligned with some marker), the latter is used for
204 block indenting (when objects are tabbed in from the lhs). The width available
205 for `baz()` will be the maximum width, minus the space used for indenting, minus
206 the space used for the `);`. (Note that actual argument formatting does not
207 quite work like this, but it's close enough).
208
209 The `rewrite` function returns an `Option` - either we successfully rewrite and
210 return the rewritten string for the caller to use, or we fail to rewrite and
211 return `None`. This could be because Rustfmt encounters something it doesn't
212 know how to reformat, but more often it is because Rustfmt can't fit the item
213 into the required width. How to handle this is up to the caller. Often the
214 caller just gives up, ultimately relying on the missed spans system to paste in
215 the un-formatted source. A better solution (although not performed in many
216 places) is for the caller to shuffle around some of its other items to make
217 more width, then call the function again with more space.
218
219 Since it is common for callers to bail out when a callee fails, we often use a
220 `?` operator to make this pattern more succinct.
221
222 One way we might find out that we don't have enough space is when computing how much
223 space we have. Something like `available_space = budget - overhead`. Since
224 widths are unsized integers, this would cause underflow. Therefore we use
225 checked subtraction: `available_space = budget.checked_sub(overhead)?`.
226 `checked_sub` returns an `Option`, and if we would underflow `?` returns
227 `None`, otherwise, we proceed with the computed space.
228
229 ##### Rewrite of list-like expressions
230
231 Much of the syntax in Rust is lists: lists of arguments, lists of fields, lists of
232 array elements, etc. We have some generic code to handle lists, including how to
233 space them in horizontal and vertical space, indentation, comments between
234 items, trailing separators, etc. However, since there are so many options, the
235 code is a bit complex. Look in [src/lists.rs](src/lists.rs). `write_list` is the key function,
236 and `ListFormatting` the key structure for configuration. You'll need to make a
237 `ListItems` for input, this is usually done using `itemize_list`.
238
239 ##### Configuration
240
241 Rustfmt strives to be highly configurable. Often the first part of a patch is
242 creating a configuration option for the feature you are implementing. All
243 handling of configuration options is done in [src/config/mod.rs](src/config/mod.rs). Look for the
244 `create_config!` macro at the end of the file for all the options. The rest of
245 the file defines a bunch of enums used for options, and the machinery to produce
246 the config struct and parse a config file, etc. Checking an option is done by
247 accessing the correct field on the config struct, e.g., `config.max_width()`. Most
248 functions have a `Config`, or one can be accessed via a visitor or context of
249 some kind.