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