]> git.lizzy.rs Git - rust.git/blob - docs/dev/style.md
f4748160bf15eecab1de3e64751c8ae4cebdd8fb
[rust.git] / docs / dev / style.md
1 Our approach to "clean code" is two-fold:
2
3 * We generally don't block PRs on style changes.
4 * At the same time, all code in rust-analyzer is constantly refactored.
5
6 It is explicitly OK for a reviewer to flag only some nits in the PR, and then send a follow-up cleanup PR for things which are easier to explain by example, cc-ing the original author.
7 Sending small cleanup PRs (like renaming a single local variable) is encouraged.
8
9 # General
10
11 ## Scale of Changes
12
13 Everyone knows that it's better to send small & focused pull requests.
14 The problem is, sometimes you *have* to, eg, rewrite the whole compiler, and that just doesn't fit into a set of isolated PRs.
15
16 The main things to keep an eye on are the boundaries between various components.
17 There are three kinds of changes:
18
19 1. Internals of a single component are changed.
20    Specifically, you don't change any `pub` items.
21    A good example here would be an addition of a new assist.
22
23 2. API of a component is expanded.
24    Specifically, you add a new `pub` function which wasn't there before.
25    A good example here would be expansion of assist API, for example, to implement lazy assists or assists groups.
26
27 3. A new dependency between components is introduced.
28    Specifically, you add a `pub use` reexport from another crate or you add a new line to the `[dependencies]` section of `Cargo.toml`.
29    A good example here would be adding reference search capability to the assists crates.
30
31 For the first group, the change is generally merged as long as:
32
33 * it works for the happy case,
34 * it has tests,
35 * it doesn't panic for the unhappy case.
36
37 For the second group, the change would be subjected to quite a bit of scrutiny and iteration.
38 The new API needs to be right (or at least easy to change later).
39 The actual implementation doesn't matter that much.
40 It's very important to minimize the amount of changed lines of code for changes of the second kind.
41 Often, you start doing a change of the first kind, only to realise that you need to elevate to a change of the second kind.
42 In this case, we'll probably ask you to split API changes into a separate PR.
43
44 Changes of the third group should be pretty rare, so we don't specify any specific process for them.
45 That said, adding an innocent-looking `pub use` is a very simple way to break encapsulation, keep an eye on it!
46
47 Note: if you enjoyed this abstract hand-waving about boundaries, you might appreciate
48 https://www.tedinski.com/2018/02/06/system-boundaries.html
49
50 ## Crates.io Dependencies
51
52 We try to be very conservative with usage of crates.io dependencies.
53 Don't use small "helper" crates (exception: `itertools` is allowed).
54 If there's some general reusable bit of code you need, consider adding it to the `stdx` crate.
55
56 **Rational:** keep compile times low, create ecosystem pressure for faster
57 compiles, reduce the number of things which might break.
58
59 ## Commit Style
60
61 We don't have specific rules around git history hygiene.
62 Maintaining clean git history is strongly encouraged, but not enforced.
63 Use rebase workflow, it's OK to rewrite history during PR review process.
64 After you are happy with the state of the code, please use [interactive rebase](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History) to squash fixup commits.
65
66 Avoid @mentioning people in commit messages and pull request descriptions(they are added to commit message by bors).
67 Such messages create a lot of duplicate notification traffic during rebases.
68
69 If possible, write commit messages from user's perspective:
70
71 ```
72 # GOOD
73 Goto definition works inside macros
74
75 # BAD
76 Use original span for FileId
77 ```
78
79 This makes it easier to prepare a changelog.
80
81 **Rational:** clean history is potentially useful, but rarely used.
82 But many users read changelogs.
83
84 ## Clippy
85
86 We don't enforce Clippy.
87 A number of default lints have high false positive rate.
88 Selectively patching false-positives with `allow(clippy)` is considered worse than not using Clippy at all.
89 There's `cargo xtask lint` command which runs a subset of low-FPR lints.
90 Careful tweaking of `xtask lint` is welcome.
91 Of course, applying Clippy suggestions is welcome as long as they indeed improve the code.
92
93 **Rational:** see [rust-lang/clippy#5537](https://github.com/rust-lang/rust-clippy/issues/5537).
94
95 # Code
96
97 ## Minimal Tests
98
99 Most tests in rust-analyzer start with a snippet of Rust code.
100 This snippets should be minimal -- if you copy-paste a snippet of real code into the tests, make sure to remove everything which could be removed.
101
102 It also makes sense to format snippets more compactly (for example, by placing enum definitions like `enum E { Foo, Bar }` on a single line),
103 as long as they are still readable.
104
105 When using multiline fixtures, use unindented raw string literals:
106
107 ```rust
108     #[test]
109     fn inline_field_shorthand() {
110         check_assist(
111             inline_local_variable,
112             r#"
113 struct S { foo: i32}
114 fn main() {
115     let $0foo = 92;
116     S { foo }
117 }
118 "#,
119             r#"
120 struct S { foo: i32}
121 fn main() {
122     S { foo: 92 }
123 }
124 "#,
125         );
126     }
127 ```
128
129 **Rational:**
130
131 There are many benefits to this:
132
133 * less to read or to scroll past
134 * easier to understand what exactly is tested
135 * less stuff printed during printf-debugging
136 * less time to run test
137
138 Formatting ensures that you can use your editor's "number of selected characters" feature to correlate offsets with test's source code.
139
140 ## Function Preconditions
141
142 Express function preconditions in types and force the caller to provide them (rather than checking in callee):
143
144 ```rust
145 // GOOD
146 fn frbonicate(walrus: Walrus) {
147     ...
148 }
149
150 // BAD
151 fn frobnicate(walrus: Option<Walrus>) {
152     let walrus = match walrus {
153         Some(it) => it,
154         None => return,
155     };
156     ...
157 }
158 ```
159
160 **Rational:** this makes control flow explicit at the call site.
161 Call-site has more context, it often happens that the precondition falls out naturally or can be bubbled up higher in the stack.
162
163 Avoid splitting precondition check and precondition use across functions:
164
165 ```rust
166 // GOOD
167 fn main() {
168     let s: &str = ...;
169     if let Some(contents) = string_literal_contents(s) {
170
171     }
172 }
173
174 fn string_literal_contents(s: &str) -> Option<&str> {
175     if s.starts_with('"') && s.ends_with('"') {
176         Some(&s[1..s.len() - 1])
177     } else {
178         None
179     }
180 }
181
182 // BAD
183 fn main() {
184     let s: &str = ...;
185     if is_string_literal(s) {
186         let contents = &s[1..s.len() - 1];
187     }
188 }
189
190 fn is_string_literal(s: &str) -> bool {
191     s.starts_with('"') && s.ends_with('"')
192 }
193 ```
194
195 In the "Not as good" version, the precondition that `1` is a valid char boundary is checked in `is_string_literal` and used in `foo`.
196 In the "Good" version, the precondition check and usage are checked in the same block, and then encoded in the types.
197
198 **Rational:** non-local code properties degrade under change.
199
200 When checking a boolean precondition, prefer `if !invariant` to `if negated_invariant`:
201
202 ```rust
203 // GOOD
204 if !(idx < len) {
205     return None;
206 }
207
208 // BAD
209 if idx >= len {
210     return None;
211 }
212 ```
213
214 **Rational:** its useful to see the invariant relied upon by the rest of the function clearly spelled out.
215
216 ## Getters & Setters
217
218 If a field can have any value without breaking invariants, make the field public.
219 Conversely, if there is an invariant, document it, enforce it in the "constructor" function, make the field private, and provide a getter.
220 Never provide setters.
221
222 Getters should return borrowed data:
223
224 ```rust
225 struct Person {
226     // Invariant: never empty
227     first_name: String,
228     middle_name: Option<String>
229 }
230
231 // GOOD
232 impl Person {
233     fn first_name(&self) -> &str { self.first_name.as_str() }
234     fn middle_name(&self) -> Option<&str> { self.middle_name.as_ref() }
235 }
236
237 // BAD
238 impl Person {
239     fn first_name(&self) -> String { self.first_name.clone() }
240     fn middle_name(&self) -> &Option<String> { &self.middle_name }
241 }
242 ```
243
244 **Rational:** we don't provide public API, it's cheaper to refactor than to pay getters rent.
245 Non-local code properties degrade under change, privacy makes invariant local.
246 Borrowed own data discloses irrelevant details about origin of data.
247 Irrelevant (neither right nor wrong) things obscure correctness.
248
249 ## Constructors
250
251 Prefer `Default` to zero-argument `new` function
252
253 ```rust
254 // GOOD
255 #[derive(Default)]
256 struct Foo {
257     bar: Option<Bar>
258 }
259
260 // BAD
261 struct Foo {
262     bar: Option<Bar>
263 }
264
265 impl Foo {
266     fn new() -> Foo {
267         Foo { bar: None }
268     }
269 }
270 ```
271
272 Prefer `Default` even it has to be implemented manually.
273
274 **Rational:** less typing in the common case, uniformity.
275
276 ## Functions Over Objects
277
278 Avoid creating "doer" objects.
279 That is, objects which are created only to execute a single action.
280
281 ```rust
282 // GOOD
283 do_thing(arg1, arg2);
284
285 // BAD
286 ThingDoer::new(arg1, arg2).do();
287 ```
288
289 Note that this concerns only outward API.
290 When implementing `do_thing`, it might be very useful to create a context object.
291
292 ```rust
293 pub fn do_thing(arg1: Arg1, arg2: Arg2) -> Res {
294     let mut ctx = Ctx { arg1, arg2 }
295     ctx.run()
296 }
297
298 struct Ctx {
299     arg1: Arg1, arg2: Arg2
300 }
301
302 impl Ctx {
303     fn run(self) -> Res {
304         ...
305     }
306 }
307 ```
308
309 The difference is that `Ctx` is an impl detail here.
310
311 Sometimes a middle ground is acceptable if this can save some busywork:
312
313 ```rust
314 ThingDoer::do(arg1, arg2);
315
316 pub struct ThingDoer {
317     arg1: Arg1, arg2: Arg2,
318 }
319
320 impl ThingDoer {
321     pub fn do(arg1: Arg1, arg2: Arg2) -> Res {
322         ThingDoer { arg1, arg2 }.run()
323     }
324     fn run(self) -> Res {
325         ...
326     }
327 }
328 ```
329
330 **Rational:** not bothering the caller with irrelevant details, not mixing user API with implementor API.
331
332 ## Avoid Monomorphization
333
334 Avoid making a lot of code type parametric, *especially* on the boundaries between crates.
335
336 ```rust
337 // GOOD
338 fn frbonicate(f: impl FnMut()) {
339     frobnicate_impl(&mut f)
340 }
341 fn frobnicate_impl(f: &mut dyn FnMut()) {
342     // lots of code
343 }
344
345 // BAD
346 fn frbonicate(f: impl FnMut()) {
347     // lots of code
348 }
349 ```
350
351 Avoid `AsRef` polymorphism, it pays back only for widely used libraries:
352
353 ```rust
354 // GOOD
355 fn frbonicate(f: &Path) {
356 }
357
358 // BAD
359 fn frbonicate(f: impl AsRef<Path>) {
360 }
361 ```
362
363 **Rational:** Rust uses monomorphization to compile generic code, meaning that for each instantiation of a generic functions with concrete types, the function is compiled afresh, *per crate*.
364 This allows for exceptionally good performance, but leads to increased compile times.
365 Runtime performance obeys 80%/20% rule -- only a small fraction of code is hot.
366 Compile time **does not** obey this rule -- all code has to be compiled.
367
368
369 # Premature Pessimization
370
371 ## Avoid Allocations
372
373 Avoid writing code which is slower than it needs to be.
374 Don't allocate a `Vec` where an iterator would do, don't allocate strings needlessly.
375
376 ```rust
377 // GOOD
378 use itertools::Itertools;
379
380 let (first_word, second_word) = match text.split_ascii_whitespace().collect_tuple() {
381     Some(it) => it,
382     None => return,
383 }
384
385 // BAD
386 let words = text.split_ascii_whitespace().collect::<Vec<_>>();
387 if words.len() != 2 {
388     return
389 }
390 ```
391
392 **Rational:** not allocating is almost often faster.
393
394 ## Push Allocations to the Call Site
395
396 If allocation is inevitable, let the caller allocate the resource:
397
398 ```rust
399 // GOOD
400 fn frobnicate(s: String) {
401     ...
402 }
403
404 // BAD
405 fn frobnicate(s: &str) {
406     let s = s.to_string();
407     ...
408 }
409 ```
410
411 **Rational:** reveals the costs.
412 It is also more efficient when the caller already owns the allocation.
413
414 ## Collection types
415
416 Prefer `rustc_hash::FxHashMap` and `rustc_hash::FxHashSet` instead of the ones in `std::collections`.
417
418 **Rational:** they use a hasher that's significantly faster and using them consistently will reduce code size by some small amount.
419
420 # Style
421
422 ## Order of Imports
423
424 Separate import groups with blank lines.
425 Use one `use` per crate.
426
427 Module declarations come before the imports.
428 Order them in "suggested reading order" for a person new to the code base.
429
430 ```rust
431 mod x;
432 mod y;
433
434 // First std.
435 use std::{ ... }
436
437 // Second, external crates (both crates.io crates and other rust-analyzer crates).
438 use crate_foo::{ ... }
439 use crate_bar::{ ... }
440
441 // Then current crate.
442 use crate::{}
443
444 // Finally, parent and child modules, but prefer `use crate::`.
445 use super::{}
446 ```
447
448 **Rational:** consistency.
449 Reading order is important for new contributors.
450 Grouping by crate allows to spot unwanted dependencies easier.
451
452 ## Import Style
453
454 Qualify items from `hir` and `ast`.
455
456 ```rust
457 // GOOD
458 use syntax::ast;
459
460 fn frobnicate(func: hir::Function, strukt: ast::Struct) {}
461
462 // BAD
463 use hir::Function;
464 use syntax::ast::Struct;
465
466 fn frobnicate(func: Function, strukt: Struct) {}
467 ```
468
469 **Rational:** avoids name clashes, makes the layer clear at a glance.
470
471 When implementing traits from `std::fmt` or `std::ops`, import the module:
472
473 ```rust
474 // GOOD
475 use std::fmt;
476
477 impl fmt::Display for RenameError {
478     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { .. }
479 }
480
481 // BAD
482 impl std::fmt::Display for RenameError {
483     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { .. }
484 }
485
486 // BAD
487 use std::ops::Deref;
488
489 impl Deref for Widget {
490     type Target = str;
491     fn deref(&self) -> &str { .. }
492 }
493 ```
494
495 **Rational:** overall, less typing.
496 Makes it clear that a trait is implemented, rather than used.
497
498 Avoid local `use MyEnum::*` imports.
499 **Rational:** consistency.
500
501 Prefer `use crate::foo::bar` to `use super::bar` or `use self::bar::baz`.
502 **Rational:** consistency, this is the style which works in all cases.
503
504 ## Order of Items
505
506 Optimize for the reader who sees the file for the first time, and wants to get a general idea about what's going on.
507 People read things from top to bottom, so place most important things first.
508
509 Specifically, if all items except one are private, always put the non-private item on top.
510
511 ```rust
512 // GOOD
513 pub(crate) fn frobnicate() {
514     Helper::act()
515 }
516
517 #[derive(Default)]
518 struct Helper { stuff: i32 }
519
520 impl Helper {
521     fn act(&self) {
522
523     }
524 }
525
526 // BAD
527 #[derive(Default)]
528 struct Helper { stuff: i32 }
529
530 pub(crate) fn frobnicate() {
531     Helper::act()
532 }
533
534 impl Helper {
535     fn act(&self) {
536
537     }
538 }
539 ```
540
541 If there's a mixture of private and public items, put public items first.
542
543 Put `struct`s and `enum`s first, functions and impls last. Order type declarations in top-down manner.
544
545 ```rust
546 // GOOD
547 struct Parent {
548     children: Vec<Child>
549 }
550
551 struct Child;
552
553 impl Parent {
554 }
555
556 impl Child {
557 }
558
559 // BAD
560 struct Child;
561
562 impl Child {
563 }
564
565 struct Parent {
566     children: Vec<Child>
567 }
568
569 impl Parent {
570 }
571 ```
572
573 **Rational:** easier to get the sense of the API by visually scanning the file.
574 If function bodies are folded in the editor, the source code should read as documentation for the public API.
575
576 ## Variable Naming
577
578 Use boring and long names for local variables ([yay code completion](https://github.com/rust-analyzer/rust-analyzer/pull/4162#discussion_r417130973)).
579 The default name is a lowercased name of the type: `global_state: GlobalState`.
580 Avoid ad-hoc acronyms and contractions, but use the ones that exist consistently (`db`, `ctx`, `acc`).
581 Prefer American spelling (color, behavior).
582
583 Default names:
584
585 * `res` -- "result of the function" local variable
586 * `it` -- I don't really care about the name
587 * `n_foo` -- number of foos
588 * `foo_idx` -- index of `foo`
589
590 Many names in rust-analyzer conflict with keywords.
591 We use mangled names instead of `r#ident` syntax:
592
593 ```
594 struct -> strukt
595 crate  -> krate
596 impl   -> imp
597 trait  -> trait_
598 fn     -> func
599 enum   -> enum_
600 mod    -> module
601 ```
602
603 **Rationale:** consistency.
604
605 ## Early Returns
606
607 Do use early returns
608
609 ```rust
610 // GOOD
611 fn foo() -> Option<Bar> {
612     if !condition() {
613         return None;
614     }
615
616     Some(...)
617 }
618
619 // BAD
620 fn foo() -> Option<Bar> {
621     if condition() {
622         Some(...)
623     } else {
624         None
625     }
626 }
627 ```
628
629 **Rational:** reduce congnitive stack usage.
630
631 ## Comparisons
632
633 Use `<`/`<=`, avoid `>`/`>=`.
634
635 ```rust
636 // GOOD
637 assert!(lo <= x && x <= hi);
638
639 // BAD
640 assert!(x >= lo && x <= hi>);
641 ```
642
643 **Rational:** Less-then comparisons are more intuitive, they correspond spatially to [real line](https://en.wikipedia.org/wiki/Real_line).
644
645
646 ## Documentation
647
648 For `.md` and `.adoc` files, prefer a sentence-per-line format, don't wrap lines.
649 If the line is too long, you want to split the sentence in two :-)
650
651 **Rational:** much easier to edit the text and read the diff.