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 **Rational:** 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 **Rational:** clean history is potentially useful, but rarely used.
82 But many users read changelogs.
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.
93 **Rational:** see [rust-lang/clippy#5537](https://github.com/rust-lang/rust-clippy/issues/5537).
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.
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.
105 When using multiline fixtures, use unindented raw string literals:
109 fn inline_field_shorthand() {
111 inline_local_variable,
131 There are many benefits to this:
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
138 Formatting ensures that you can use your editor's "number of selected characters" feature to correlate offsets with test's source code.
140 ## Function Preconditions
142 Express function preconditions in types and force the caller to provide them (rather than checking in callee):
146 fn frbonicate(walrus: Walrus) {
151 fn frobnicate(walrus: Option<Walrus>) {
152 let walrus = match walrus {
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.
163 Avoid splitting precondition check and precondition use across functions:
169 if let Some(contents) = string_literal_contents(s) {
174 fn string_literal_contents(s: &str) -> Option<&str> {
175 if s.starts_with('"') && s.ends_with('"') {
176 Some(&s[1..s.len() - 1])
185 if is_string_literal(s) {
186 let contents = &s[1..s.len() - 1];
190 fn is_string_literal(s: &str) -> bool {
191 s.starts_with('"') && s.ends_with('"')
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.
198 **Rational:** non-local code properties degrade under change.
200 When checking a boolean precondition, prefer `if !invariant` to `if negated_invariant`:
214 **Rational:** its useful to see the invariant relied upon by the rest of the function clearly spelled out.
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.
222 Getters should return borrowed data:
226 // Invariant: never empty
228 middle_name: Option<String>
233 fn first_name(&self) -> &str { self.first_name.as_str() }
234 fn middle_name(&self) -> Option<&str> { self.middle_name.as_ref() }
239 fn first_name(&self) -> String { self.first_name.clone() }
240 fn middle_name(&self) -> &Option<String> { &self.middle_name }
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.
251 Prefer `Default` to zero-argument `new` function
272 Prefer `Default` even it has to be implemented manually.
274 **Rational:** less typing in the common case, uniformity.
276 ## Functions Over Objects
278 Avoid creating "doer" objects.
279 That is, objects which are created only to execute a single action.
283 do_thing(arg1, arg2);
286 ThingDoer::new(arg1, arg2).do();
289 Note that this concerns only outward API.
290 When implementing `do_thing`, it might be very useful to create a context object.
293 pub fn do_thing(arg1: Arg1, arg2: Arg2) -> Res {
294 let mut ctx = Ctx { arg1, arg2 }
299 arg1: Arg1, arg2: Arg2
303 fn run(self) -> Res {
309 The difference is that `Ctx` is an impl detail here.
311 Sometimes a middle ground is acceptable if this can save some busywork:
314 ThingDoer::do(arg1, arg2);
316 pub struct ThingDoer {
317 arg1: Arg1, arg2: Arg2,
321 pub fn do(arg1: Arg1, arg2: Arg2) -> Res {
322 ThingDoer { arg1, arg2 }.run()
324 fn run(self) -> Res {
330 **Rational:** not bothering the caller with irrelevant details, not mixing user API with implementor API.
332 ## Avoid Monomorphization
334 Avoid making a lot of code type parametric, *especially* on the boundaries between crates.
338 fn frbonicate(f: impl FnMut()) {
339 frobnicate_impl(&mut f)
341 fn frobnicate_impl(f: &mut dyn FnMut()) {
346 fn frbonicate(f: impl FnMut()) {
351 Avoid `AsRef` polymorphism, it pays back only for widely used libraries:
355 fn frbonicate(f: &Path) {
359 fn frbonicate(f: impl AsRef<Path>) {
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.
369 # Premature Pessimization
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.
378 use itertools::Itertools;
380 let (first_word, second_word) = match text.split_ascii_whitespace().collect_tuple() {
386 let words = text.split_ascii_whitespace().collect::<Vec<_>>();
387 if words.len() != 2 {
392 **Rational:** not allocating is almost often faster.
394 ## Push Allocations to the Call Site
396 If allocation is inevitable, let the caller allocate the resource:
400 fn frobnicate(s: String) {
405 fn frobnicate(s: &str) {
406 let s = s.to_string();
411 **Rational:** reveals the costs.
412 It is also more efficient when the caller already owns the allocation.
416 Prefer `rustc_hash::FxHashMap` and `rustc_hash::FxHashSet` instead of the ones in `std::collections`.
418 **Rational:** they use a hasher that's significantly faster and using them consistently will reduce code size by some small amount.
424 Separate import groups with blank lines.
425 Use one `use` per crate.
427 Module declarations come before the imports.
428 Order them in "suggested reading order" for a person new to the code base.
437 // Second, external crates (both crates.io crates and other rust-analyzer crates).
438 use crate_foo::{ ... }
439 use crate_bar::{ ... }
441 // Then current crate.
444 // Finally, parent and child modules, but prefer `use crate::`.
448 **Rational:** consistency.
449 Reading order is important for new contributors.
450 Grouping by crate allows to spot unwanted dependencies easier.
454 Qualify items from `hir` and `ast`.
460 fn frobnicate(func: hir::Function, strukt: ast::Struct) {}
464 use syntax::ast::Struct;
466 fn frobnicate(func: Function, strukt: Struct) {}
469 **Rational:** avoids name clashes, makes the layer clear at a glance.
471 When implementing traits from `std::fmt` or `std::ops`, import the module:
477 impl fmt::Display for RenameError {
478 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { .. }
482 impl std::fmt::Display for RenameError {
483 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { .. }
489 impl Deref for Widget {
491 fn deref(&self) -> &str { .. }
495 **Rational:** overall, less typing.
496 Makes it clear that a trait is implemented, rather than used.
498 Avoid local `use MyEnum::*` imports.
499 **Rational:** consistency.
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.
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.
509 Specifically, if all items except one are private, always put the non-private item on top.
513 pub(crate) fn frobnicate() {
518 struct Helper { stuff: i32 }
528 struct Helper { stuff: i32 }
530 pub(crate) fn frobnicate() {
541 If there's a mixture of private and public items, put public items first.
543 Put `struct`s and `enum`s first, functions and impls last. Order type declarations in top-down manner.
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.
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).
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`
590 Many names in rust-analyzer conflict with keywords.
591 We use mangled names instead of `r#ident` syntax:
603 **Rationale:** consistency.
611 fn foo() -> Option<Bar> {
620 fn foo() -> Option<Bar> {
629 **Rational:** reduce congnitive stack usage.
633 Use `<`/`<=`, avoid `>`/`>=`.
637 assert!(lo <= x && x <= hi);
640 assert!(x >= lo && x <= hi>);
643 **Rational:** Less-then comparisons are more intuitive, they correspond spatially to [real line](https://en.wikipedia.org/wiki/Real_line).
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 :-)
651 **Rational:** much easier to edit the text and read the diff.