1 Our approach to "clean code" is two-fold:
3 * We generally don't block PRs on style changes.
4 * At the same time, all code in rust-analyzer is constantly refactored.
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.
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.
16 The main things to keep an eye on are the boundaries between various components.
17 There are three kinds of changes:
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.
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.
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.
31 For the first group, the change is generally merged as long as:
33 * it works for the happy case,
35 * it doesn't panic for the unhappy case.
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.
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!
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
50 ## Crates.io Dependencies
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.
56 **Rationale:** keep compile times low, create ecosystem pressure for faster
57 compiles, reduce the number of things which might break.
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.
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.
69 If possible, write commit messages from user's perspective:
73 Goto definition works inside macros
76 Use original span for FileId
79 This makes it easier to prepare a changelog.
81 If the change adds a new user-visible functionality, consider recording a GIF with [peek](https://github.com/phw/peek) and pasting it into the PR description.
83 **Rationale:** clean history is potentially useful, but rarely used.
84 But many users read changelogs.
88 We don't enforce Clippy.
89 A number of default lints have high false positive rate.
90 Selectively patching false-positives with `allow(clippy)` is considered worse than not using Clippy at all.
91 There's `cargo xtask lint` command which runs a subset of low-FPR lints.
92 Careful tweaking of `xtask lint` is welcome.
93 Of course, applying Clippy suggestions is welcome as long as they indeed improve the code.
95 **Rationale:** see [rust-lang/clippy#5537](https://github.com/rust-lang/rust-clippy/issues/5537).
101 Most tests in rust-analyzer start with a snippet of Rust code.
102 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.
104 It also makes sense to format snippets more compactly (for example, by placing enum definitions like `enum E { Foo, Bar }` on a single line),
105 as long as they are still readable.
107 When using multiline fixtures, use unindented raw string literals:
111 fn inline_field_shorthand() {
113 inline_local_variable,
133 There are many benefits to this:
135 * less to read or to scroll past
136 * easier to understand what exactly is tested
137 * less stuff printed during printf-debugging
138 * less time to run test
140 Formatting ensures that you can use your editor's "number of selected characters" feature to correlate offsets with test's source code.
142 ## Function Preconditions
144 Express function preconditions in types and force the caller to provide them (rather than checking in callee):
148 fn frbonicate(walrus: Walrus) {
153 fn frobnicate(walrus: Option<Walrus>) {
154 let walrus = match walrus {
162 **Rationale:** this makes control flow explicit at the call site.
163 Call-site has more context, it often happens that the precondition falls out naturally or can be bubbled up higher in the stack.
165 Avoid splitting precondition check and precondition use across functions:
171 if let Some(contents) = string_literal_contents(s) {
176 fn string_literal_contents(s: &str) -> Option<&str> {
177 if s.starts_with('"') && s.ends_with('"') {
178 Some(&s[1..s.len() - 1])
187 if is_string_literal(s) {
188 let contents = &s[1..s.len() - 1];
192 fn is_string_literal(s: &str) -> bool {
193 s.starts_with('"') && s.ends_with('"')
197 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`.
198 In the "Good" version, the precondition check and usage are checked in the same block, and then encoded in the types.
200 **Rationale:** non-local code properties degrade under change.
202 When checking a boolean precondition, prefer `if !invariant` to `if negated_invariant`:
216 **Rationale:** its useful to see the invariant relied upon by the rest of the function clearly spelled out.
221 Prefer `stdx::assert_never!` to standard `assert!`.
225 If a field can have any value without breaking invariants, make the field public.
226 Conversely, if there is an invariant, document it, enforce it in the "constructor" function, make the field private, and provide a getter.
227 Never provide setters.
229 Getters should return borrowed data:
233 // Invariant: never empty
235 middle_name: Option<String>
240 fn first_name(&self) -> &str { self.first_name.as_str() }
241 fn middle_name(&self) -> Option<&str> { self.middle_name.as_ref() }
246 fn first_name(&self) -> String { self.first_name.clone() }
247 fn middle_name(&self) -> &Option<String> { &self.middle_name }
251 **Rationale:** we don't provide public API, it's cheaper to refactor than to pay getters rent.
252 Non-local code properties degrade under change, privacy makes invariant local.
253 Borrowed own data discloses irrelevant details about origin of data.
254 Irrelevant (neither right nor wrong) things obscure correctness.
258 Prefer `Default` to zero-argument `new` function
279 Prefer `Default` even it has to be implemented manually.
281 **Rationale:** less typing in the common case, uniformity.
283 Use `Vec::new` rather than `vec![]`. **Rationale:** uniformity, strength
286 ## Functions Over Objects
288 Avoid creating "doer" objects.
289 That is, objects which are created only to execute a single action.
293 do_thing(arg1, arg2);
296 ThingDoer::new(arg1, arg2).do();
299 Note that this concerns only outward API.
300 When implementing `do_thing`, it might be very useful to create a context object.
303 pub fn do_thing(arg1: Arg1, arg2: Arg2) -> Res {
304 let mut ctx = Ctx { arg1, arg2 }
309 arg1: Arg1, arg2: Arg2
313 fn run(self) -> Res {
319 The difference is that `Ctx` is an impl detail here.
321 Sometimes a middle ground is acceptable if this can save some busywork:
324 ThingDoer::do(arg1, arg2);
326 pub struct ThingDoer {
327 arg1: Arg1, arg2: Arg2,
331 pub fn do(arg1: Arg1, arg2: Arg2) -> Res {
332 ThingDoer { arg1, arg2 }.run()
334 fn run(self) -> Res {
340 **Rationale:** not bothering the caller with irrelevant details, not mixing user API with implementor API.
342 ## Avoid Monomorphization
344 Avoid making a lot of code type parametric, *especially* on the boundaries between crates.
348 fn frbonicate(f: impl FnMut()) {
349 frobnicate_impl(&mut f)
351 fn frobnicate_impl(f: &mut dyn FnMut()) {
356 fn frbonicate(f: impl FnMut()) {
361 Avoid `AsRef` polymorphism, it pays back only for widely used libraries:
365 fn frbonicate(f: &Path) {
369 fn frbonicate(f: impl AsRef<Path>) {
373 **Rationale:** 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*.
374 This allows for exceptionally good performance, but leads to increased compile times.
375 Runtime performance obeys 80%/20% rule -- only a small fraction of code is hot.
376 Compile time **does not** obey this rule -- all code has to be compiled.
379 # Premature Pessimization
383 Avoid writing code which is slower than it needs to be.
384 Don't allocate a `Vec` where an iterator would do, don't allocate strings needlessly.
388 use itertools::Itertools;
390 let (first_word, second_word) = match text.split_ascii_whitespace().collect_tuple() {
396 let words = text.split_ascii_whitespace().collect::<Vec<_>>();
397 if words.len() != 2 {
402 **Rationale:** not allocating is almost often faster.
404 ## Push Allocations to the Call Site
406 If allocation is inevitable, let the caller allocate the resource:
410 fn frobnicate(s: String) {
415 fn frobnicate(s: &str) {
416 let s = s.to_string();
421 **Rationale:** reveals the costs.
422 It is also more efficient when the caller already owns the allocation.
426 Prefer `rustc_hash::FxHashMap` and `rustc_hash::FxHashSet` instead of the ones in `std::collections`.
428 **Rationale:** they use a hasher that's significantly faster and using them consistently will reduce code size by some small amount.
434 Separate import groups with blank lines.
435 Use one `use` per crate.
437 Module declarations come before the imports.
438 Order them in "suggested reading order" for a person new to the code base.
447 // Second, external crates (both crates.io crates and other rust-analyzer crates).
448 use crate_foo::{ ... }
449 use crate_bar::{ ... }
451 // Then current crate.
454 // Finally, parent and child modules, but prefer `use crate::`.
458 **Rationale:** consistency.
459 Reading order is important for new contributors.
460 Grouping by crate allows to spot unwanted dependencies easier.
464 Qualify items from `hir` and `ast`.
470 fn frobnicate(func: hir::Function, strukt: ast::Struct) {}
474 use syntax::ast::Struct;
476 fn frobnicate(func: Function, strukt: Struct) {}
479 **Rationale:** avoids name clashes, makes the layer clear at a glance.
481 When implementing traits from `std::fmt` or `std::ops`, import the module:
487 impl fmt::Display for RenameError {
488 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { .. }
492 impl std::fmt::Display for RenameError {
493 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { .. }
499 impl Deref for Widget {
501 fn deref(&self) -> &str { .. }
505 **Rationale:** overall, less typing.
506 Makes it clear that a trait is implemented, rather than used.
508 Avoid local `use MyEnum::*` imports.
509 **Rationale:** consistency.
511 Prefer `use crate::foo::bar` to `use super::bar` or `use self::bar::baz`.
512 **Rationale:** consistency, this is the style which works in all cases.
516 Optimize for the reader who sees the file for the first time, and wants to get a general idea about what's going on.
517 People read things from top to bottom, so place most important things first.
519 Specifically, if all items except one are private, always put the non-private item on top.
523 pub(crate) fn frobnicate() {
528 struct Helper { stuff: i32 }
538 struct Helper { stuff: i32 }
540 pub(crate) fn frobnicate() {
551 If there's a mixture of private and public items, put public items first.
553 Put `struct`s and `enum`s first, functions and impls last. Order type declarations in top-down manner.
583 **Rationale:** easier to get the sense of the API by visually scanning the file.
584 If function bodies are folded in the editor, the source code should read as documentation for the public API.
588 Use boring and long names for local variables ([yay code completion](https://github.com/rust-analyzer/rust-analyzer/pull/4162#discussion_r417130973)).
589 The default name is a lowercased name of the type: `global_state: GlobalState`.
590 Avoid ad-hoc acronyms and contractions, but use the ones that exist consistently (`db`, `ctx`, `acc`).
591 Prefer American spelling (color, behavior).
595 * `res` -- "result of the function" local variable
596 * `it` -- I don't really care about the name
597 * `n_foo` -- number of foos
598 * `foo_idx` -- index of `foo`
600 Many names in rust-analyzer conflict with keywords.
601 We use mangled names instead of `r#ident` syntax:
613 **Rationale:** consistency.
621 fn foo() -> Option<Bar> {
630 fn foo() -> Option<Bar> {
639 **Rationale:** reduce congnitive stack usage.
643 Use `<`/`<=`, avoid `>`/`>=`.
647 assert!(lo <= x && x <= hi);
650 assert!(x >= lo && x <= hi>);
653 **Rationale:** Less-then comparisons are more intuitive, they correspond spatially to [real line](https://en.wikipedia.org/wiki/Real_line).
658 Use `T![foo]` instead of `SyntaxKind::FOO_KW`.
663 T![true] | T![false] => true,
670 SyntaxKind::TRUE_KW | SyntaxKind::FALSE_KW => true,
675 **Rationale:** The macro uses the familiar Rust syntax, avoiding ambiguities like "is this a brace or bracket?".
679 For `.md` and `.adoc` files, prefer a sentence-per-line format, don't wrap lines.
680 If the line is too long, you want to split the sentence in two :-)
682 **Rationale:** much easier to edit the text and read the diff.