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