]> git.lizzy.rs Git - rust.git/blob - README.md
Provide information about default.toml
[rust.git] / README.md
1 # rustfmt
2
3 A tool for formatting Rust code according to style guidelines.
4
5
6 ## How to use
7
8 You'll need a pretty up to date version of the **nightly** version of Rust. 
9 You will need a default.toml file in the current working directory when you run
10 the rustfmt command. You can look at this repo for an example default.toml file.
11
12 `cargo build` to build.
13
14 `cargo test` to run all tests.
15
16 `cargo run filename` to run on a file, if the file includes out of line modules,
17 then we reformat those too. So to run on a whole module or crate, you just need
18 to run on the top file. You'll probably want to set the `WriteMode` in the call
19 to `run` in `main()`. Eventually you should be able to set the mode from the
20 command line or from a config file or something.
21
22
23 ## Use cases
24
25 A formatting tool can be used in different ways and the different use cases can
26 affect the design of the tool. The use cases I'm particularly concerned with are:
27
28 * running on a whole repo before check-in
29   - in particular, to replace the `make tidy` pass on the Rust distro
30 * running on code from another project that you are adding to your own
31 * using for mass changes in code style over a project
32
33 Some valid use cases for a formatting tool which I am explicitly not trying to
34 address (although it would be nice, if possible):
35
36 * running 'as you type' in an IDE
37 * running on arbitrary snippets of code
38 * running on Rust-like code, specifically code which doesn't parse
39 * use as a pretty printer inside the compiler
40 * refactoring
41 * formatting totally unformatted source code
42
43
44 ## Scope and vision
45
46 I do not subscribe to the notion that a formatting tool should only change
47 whitespace. I believe that we should semantics preserving, but not necessarily
48 syntax preserving, i.e., we can change the AST of a program.
49
50 I.e., we might change glob imports to list or single imports, re-order imports,
51 move bounds to where clauses, combine multiple impls into a single impl, etc.
52
53 However, we will not change the names of variables or make any changes which
54 *could* change the semantics. To be ever so slightly formal, we might imagine
55 a compilers high level intermediate representation, we should strive to only
56 make changes which do not change the HIR, even if they do change the AST.
57
58 I would like to be able to output refactoring scripts for making deeper changes
59 though. (E.g., renaming variables to satisfy our style guidelines).
60
61 My long term goal is that all style lints can be moved from the compiler to
62 rustfmt and, as well as warning, can either fix problems or emit refactoring
63 scripts to do so.
64
65 ### Configurability
66
67 I believe reformatting should be configurable to some extent. We should read in
68 options from a configuration file and reformat accordingly. We should supply at
69 least a config file which matches the Rust style guidelines.
70
71 There should be multiple modes for running the tool. As well as simply replacing
72 each file, we should be able to show the user a list of the changes we would
73 make, or show a list of violations without corrections (the difference being
74 that there are multiple ways to satisfy a given set of style guidelines, and we
75 should distinguish violations from deviations from our own model).
76
77
78 ## Implementation philosophy
79
80 Some details of the philosophy behind the implementation.
81
82
83 ### Operate on the AST
84
85 A reformatting tool can be based on either the AST or a token stream (in Rust
86 this is actually a stream of token trees, but its not a fundamental difference).
87 There are pros and cons to the two approaches. I have chosen to use the AST
88 approach. The primary reasons are that it allows us to do more sophisticated
89 manipulations, rather than just change whitespace, and it gives us more context
90 when making those changes.
91
92 The advantage of the tokens approach are that you can operate on non-parsable
93 code. I don't care too much about that, it would be nice, but I think being able
94 to perform sophisticated transformations is more important. In the future I hope to
95 (optionally) be able to use type information for informing reformatting too. One
96 specific case of unparsable code is macros. Using tokens is certainly easier
97 here, but I believe it is perfectly solvable with the AST approach. At the limit,
98 we can operate on just tokens in the macro case.
99
100 I believe that there is not in fact that much difference between the two
101 approaches. Due to imperfect span information, under the AST approach, we
102 sometimes are reduced to examining tokens or do some re-lexing of our own. Under
103 the tokens approach you need to implement your own (much simpler) parser. I
104 believe that as the tool gets more sophisticated, you end up doing more at the
105 token-level, or having an increasingly sophisticated parser, until at the limit
106 you have the same tool.
107
108 However, I believe starting from the AST gets you more quickly to a usable and
109 useful tool.
110
111
112 ### Heuristic rather than algorithmic
113
114 Many formatting tools use a very general algorithmic or even algebraic tool for
115 pretty printing. This results in very elegant code, but I believe does not give
116 the best results. I prefer a more ad hoc approach where each expression/item is
117 formatted using custom rules. We hopefully don't end up with too much code due
118 to good old fashioned abstraction and code sharing. This will give a bigger code
119 base, but hopefully a better result.
120
121 It also means that there will be some cases we can't format and we have to give
122 up. I think that is OK. Hopefully they are rare enough that manually fixing them
123 is not painful. Better to have a tool that gives great code in 99% of cases and
124 fails in 1% than a tool which gives 50% great code and 50% ugly code, but never
125 fails.
126
127
128 ### Incremental development
129
130 I want rustfmt to be useful as soon as possible and to always be useful. I
131 specifically don't want to have to wait for a feature (or worse, the whole tool)
132 to be perfect before it is useful. The main ways this is achieved is to output
133 the source code where we can't yet reformat, be able to turn off new features
134 until they are ready, and the 'do no harm' principle (see next section).
135
136
137 ### First, do no harm
138
139 Until rustfmt it perfect, there will always be a trade-off between doing more and
140 doing existing things well. I want to err on the side of the latter.
141 Specifically, rustfmt should never take OK code and make it look worse. If we
142 can't make it better, we should leave it as is. That might mean being less
143 aggressive than we like or using configurability.
144
145
146 ### Use the source code as guidance
147
148 There are often multiple ways to format code and satisfy standards. Where this
149 is the case, we should use the source code as a hint for reformatting.
150 Furthermore, where the code has been formatted in a particular way that satisfies
151 the coding standard, it should not be changed (this is sometimes not possible or
152 not worthwhile due to uniformity being desirable, but it is a useful goal).
153
154
155 ### Architecture details
156
157 We use the AST from libsyntax. We use libsyntax's visit module to walk the AST
158 to find starting points for reformatting. Eventually, we should reformat everything
159 and we shouldn't need the visit module. We keep track of the last formatted
160 position in the code, and when we reformat the next piece of code we make sure
161 to output the span for all the code in between (handled by missed_spans.rs).
162
163 Our visitor keeps track of the desired current indent due to blocks (
164 `block_indent`). Each `visit_*` method reformats code according to this indent
165 and `IDEAL_WIDTH` and `MAX_WIDTH` (which should one day be supplied from a 
166 config file). Most reformatting done in the `visit_*` methods is a bit hackey
167 and is meant to be temporary until it can be done properly.
168
169 There are a bunch of methods called `rewrite_*`. There do the bulk of the
170 reformatting. These take the AST node to be reformatted (this may not literally
171 be an AST node from libsyntax, there might be multiple parameters describing a
172 logical node), the current indent, and the current width budget. They return a
173 `String` (or sometimes an `Option<String>`) which formats the code in the box
174 given by the indent and width budget. If the method fails, it returns `None` and
175 the calling method then has to fallback in some way to give the callee more space.
176
177 So, in summary to format a node, we calculate the width budget and then walk down
178 the tree from the node. At a leaf, we generate an actual string and then unwind,
179 combining these strings as we go back up the tree.
180
181 For example, consider a method definition:
182
183 ```
184     fn foo(a: A, b: B) {
185         ...
186     }
187 ```
188
189 We start at indent 4, the rewrite function for the whole function knows it must
190 write `fn foo(` before the arguments and `) {` after them, assuming the max width
191 is 100, it thus asks the rewrite argument list function to rewrite with an indent
192 of 11 and in a width of 86. Assuming that is possible (obviously in this case),
193 it returns a string for the arguments and it can make a string for the function
194 header. If the arguments couldn't be fitted in that space, we might try to
195 fallback to a hanging indent, so we try again with indent 8 and width 89.
196
197
198 ## Contributing
199
200 ### Test and file issues
201
202 It would be really useful to have people use rustfmt on their projects and file
203 issues where it does something you don't expect.
204
205 A really useful thing to do that on a crate from the Rust repo. If it does
206 something unexpected, file an issue; if not, make a PR to the Rust repo with the reformatted code. I hope to get the whole repo consistently rustfmt'ed and to
207 replace `make tidy` with rustfmt as a medium-term goal.
208
209 ### Create test cases
210
211 Having a strong test suite for a tool like this is essential. It is very easy
212 to create regressions. Any tests you can add are very much appreciated.
213
214 ### Hack!
215
216 Here are some [good starting issues](https://github.com/nrc/rustfmt/issues?q=is%3Aopen+is%3Aissue+label%3Aeasy).
217 Note than some of those issues tagged 'easy' are not that easy and might be better
218 second issues, rather than good first issues to fix.
219
220 If you've found areas which need polish and don't have issues, please submit a
221 PR, don't feel there needs to be an issue.