User Manual

At its core, rust-analyzer is a library for semantic analysis of Rust code as it changes over time. This manual focuses on a specific usage of the library — running it as part of a server that implements the Language Server Protocol (LSP). The LSP allows various code editors, like VS Code, Emacs or Vim, to implement semantic features like completion or goto definition by talking to an external language server process.

To improve this document, send a pull request:
https://github.com/rust-analyzer/…​/manual.adoc

If you have questions about using rust-analyzer, please ask them in the “IDEs and Editors” topic of Rust users forum.

Installation

In theory, one should be able to just install the rust-analyzer binary and have it automatically work with any editor. We are not there yet, so some editor specific setup is required.

Additionally, rust-analyzer needs the sources of the standard library. If the source code is not present, rust-analyzer will attempt to install it automatically.

To add the sources manually, run the following command:

1
$ rustup component add rust-src

VS Code

This is the best supported editor at the moment. The rust-analyzer plugin for VS Code is maintained in tree.

You can install the latest release of the plugin from the marketplace.

Note that the plugin may cause conflicts with the official Rust plugin. It is recommended to disable the Rust plugin when using the rust-analyzer extension.

By default, the plugin will prompt you to download the matching version of the server as well:

75067008 17502500 54ba 11ea 835a f92aac50e866

To disable this notification put the following to settings.json

1
{ "rust-analyzer.updates.askBeforeDownload": false }

The server binary is stored in:

  • Linux: ~/.config/Code/User/globalStorage/matklad.rust-analyzer

  • macOS: ~/Library/Application\ Support/Code/User/globalStorage/matklad.rust-analyzer

  • Windows: %APPDATA%\Code\User\globalStorage\matklad.rust-analyzer

Note that we only support two most recent versions of VS Code.

Updates

The extension will be updated automatically as new versions become available. It will ask your permission to download the matching language server version binary if needed.

Nightly

We ship nightly releases for VS Code. To help us out with testing the newest code and follow the bleeding edge of our master, please use the following config:

1
{ "rust-analyzer.updates.channel": "nightly" }

You will be prompted to install the nightly extension version. Just click Download now and from that moment you will get automatic updates every 24 hours.

If you don’t want to be asked for Download now every day when the new nightly version is released add the following to your settings.json:

1
{ "rust-analyzer.updates.askBeforeDownload": false }
Nightly extension should only be installed via the Download now action from VS Code.

Building From Source

Alternatively, both the server and the plugin can be installed from source:

1
2
$ git clone https://github.com/rust-analyzer/rust-analyzer.git && cd rust-analyzer
$ cargo xtask install

You’ll need Cargo, nodejs and npm for this.

Note that installing via xtask install does not work for VS Code Remote, instead you’ll need to install the .vsix manually.

Troubleshooting

Here are some useful self-diagnostic commands:

  • Rust Analyzer: Show RA Version shows the version of rust-analyzer binary

  • Rust Analyzer: Status prints some statistics about the server, like the few latest LSP requests

  • To enable server-side logging, run with env RA_LOG=info and see Output > Rust Analyzer Language Server in VS Code’s panel.

  • To log all LSP requests, add "rust-analyzer.trace.server": "verbose" to the settings and look for Rust Analyzer Language Server Trace in the panel.

  • To enable client-side logging, add "rust-analyzer.trace.extension": true to the settings and open Output > Rust Analyzer Client in the panel.

rust-analyzer Language Server Binary

Other editors generally require the rust-analyzer binary to be in $PATH. You can download the pre-built binary from the releases page. Typically, you then need to rename the binary for your platform, e.g. rust-analyzer-mac if you’re on Mac OS, to rust-analyzer and make it executable in addition to moving it into a directory in your $PATH.

On Linux to install the rust-analyzer binary into ~/.local/bin, this commands could be used

1
2
$ curl -L https://github.com/rust-analyzer/rust-analyzer/releases/latest/download/rust-analyzer-linux -o ~/.local/bin/rust-analyzer
$ chmod +x ~/.local/bin/rust-analyzer

Ensure ~/.local/bin is listed in the $PATH variable.

Alternatively, you can install it from source using the following command:

1
2
$ git clone https://github.com/rust-analyzer/rust-analyzer.git && cd rust-analyzer
$ cargo xtask install --server

If your editor can’t find the binary even though the binary is on your $PATH, the likely explanation is that it doesn’t see the same $PATH as the shell, see this issue. On Unix, running the editor from a shell or changing the .desktop file to set the environment should help.

Arch Linux

The rust-analyzer binary can be installed from the repos or AUR (Arch User Repository):

Install it with pacman, for example:

1
$ pacman -S rust-analyzer

Emacs

Prerequisites: You have installed the rust-analyzer binary.

Emacs support is maintained as part of the Emacs-LSP package in lsp-rust.el.

  1. Install the most recent version of emacs-lsp package by following the Emacs-LSP instructions.

  2. Set lsp-rust-server to 'rust-analyzer.

  3. Run lsp in a Rust buffer.

  4. (Optionally) bind commands like lsp-rust-analyzer-join-lines, lsp-extend-selection and lsp-rust-analyzer-expand-macro to keys.

Vim/NeoVim

Prerequisites: You have installed the rust-analyzer binary. Not needed if the extension can install/update it on its own, coc-rust-analyzer is one example.

The are several LSP client implementations for vim or neovim:

coc-rust-analyzer

  1. Install coc.nvim by following the instructions at coc.nvim (Node.js required)

  2. Run :CocInstall coc-rust-analyzer to install coc-rust-analyzer, this extension implements most of the features supported in the VSCode extension:

    • automatically install and upgrade stable/nightly releases

    • same configurations as VSCode extension, rust-analyzer.serverPath, rust-analyzer.cargo.features etc.

    • same commands too, rust-analyzer.analyzerStatus, rust-analyzer.ssr etc.

    • inlay hints for method chaining support, Neovim Only

    • semantic highlighting is not implemented yet

LanguageClient-neovim

  1. Install LanguageClient-neovim by following the instructions here

    • The GitHub project wiki has extra tips on configuration

  2. Configure by adding this to your vim/neovim config file (replacing the existing Rust-specific line if it exists):

    1
    2
    3
    
    let g:LanguageClient_serverCommands = {
    \ 'rust': ['rust-analyzer'],
    \ }
    

YouCompleteMe

  1. Install YouCompleteMe by following the instructions here

  2. Configure by adding this to your vim/neovim config file (replacing the existing Rust-specific line if it exists):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    let g:ycm_language_server =
    \ [
    \   {
    \     'name': 'rust',
    \     'cmdline': ['rust-analyzer'],
    \     'filetypes': ['rust'],
    \     'project_root_files': ['Cargo.toml']
    \   }
    \ ]
    

ALE

To use the LSP server in ale:

1
let g:ale_linters = {'rust': ['analyzer']}

nvim-lsp

NeoVim 0.5 (not yet released) has built-in language server support. For a quick start configuration of rust-analyzer, use neovim/nvim-lsp. Once neovim/nvim-lsp is installed, use lua require'nvim_lsp'.rust_analyzer.setup({}) in your init.vim.

Sublime Text 3

Prerequisites: You have installed the rust-analyzer binary.

You also need the LSP package. To install it:

  1. If you’ve never installed a Sublime Text package, install Package Control:

    • Open the command palette (Win/Linux: ctrl+shift+p, Mac: cmd+shift+p)

    • Type Install Package Control, press enter

  2. In the command palette, run Package control: Install package, and in the list that pops up, type LSP and press enter.

Finally, with your Rust project open, in the command palette, run LSP: Enable Language Server In Project or LSP: Enable Language Server Globally, then select rust-analyzer in the list that pops up to enable the rust-analyzer LSP. The latter means that rust-analyzer is enabled by default in Rust projects.

If it worked, you should see "rust-analyzer, Line X, Column Y" on the left side of the bottom bar, and after waiting a bit, functionality like tooltips on hovering over variables should become available.

If you get an error saying No such file or directory: 'rust-analyzer', see the rust-analyzer binary section on installing the language server binary.

GNOME Builder

Prerequisites: You have installed the rust-analyzer binary.

Gnome Builder currently has support for RLS, and there’s no way to configure the language server executable. A future version might support rust-analyzer out of the box.

  1. Rename, symlink or copy the rust-analyzer binary to rls and place it somewhere Builder can find (in PATH, or under ~/.cargo/bin).

  2. Enable the Rust Builder plugin.

GNOME Builder (Nightly)

GNOME Builder (Nightly) has now native support for rust-analyzer out of the box. If the rust-analyzer binary is not available, GNOME Builder can install it when opening a Rust source file.

Non-Cargo Based Projects

rust-analyzer does not require Cargo. However, if you use some other build system, you’ll have to describe the structure of your project for rust-analyzer in the rust-project.json format:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
interface JsonProject {
    /// Path to the directory with *source code* of sysroot crates.
    ///
    /// It should point to the directory where std, core, and friends can be found:
    /// https://github.com/rust-lang/rust/tree/master/library.
    ///
    /// If provided, rust-analyzer automatically adds dependencies on sysroot
    /// crates. Conversely, if you omit this path, you can specify sysroot
    /// dependencies yourself and, for example, have several different "sysroots" in
    /// one graph of crates.
    sysroot_src?: string;
    /// The set of crates comprising the current project.
    /// Must include all transitive dependencies as well as sysroot crate (libstd, libcore and such).
    crates: Crate[];
}

interface Crate {
    /// Path to the root module of the crate.
    root_module: string;
    /// Edition of the crate.
    edition: "2015" | "2018";
    /// Dependencies
    deps: Dep[];
    /// Should this crate be treated as a member of current "workspace".
    ///
    /// By default, inferred from the `root_module` (members are the crates which reside
    /// inside the directory opened in the editor).
    ///
    /// Set this to `false` for things like standard library and 3rd party crates to
    /// enable performance optimizations (rust-analyzer assumes that non-member crates
    /// don't change).
    is_workspace_member?: boolean;
    /// Optionally specify the (super)set of `.rs` files comprising this crate.
    ///
    /// By default, rust-analyzer assumes that only files under `root_module.parent` can belong to a crate.
    /// `include_dirs` are included recursively, unless a subdirectory is in `exclude_dirs`.
    ///
    /// Different crates can share the same `source`.
    ///
    /// If two crates share an `.rs` file in common, they *must* have the same `source`.
    /// rust-analyzer assumes that files from one source can't refer to files in another source.
    source?: {
        include_dirs: string[],
        exclude_dirs: string[],
    },
    /// The set of cfgs activated for a given crate, like `["unix", "feature=foo", "feature=bar"]`.
    cfg: string[];
    /// Target triple for this Crate.
    ///
    /// Used when running `rustc --print cfg` to get target-specific cfgs.
    target?: string;
    /// Environment variables, used for the `env!` macro
    env: : { [key: string]: string; },

    /// For proc-macro crates, path to compiles proc-macro (.so file).
    proc_macro_dylib_path?: string;
}

interface Dep {
    /// Index of a crate in the `crates` array.
    crate: number,
    /// Name as should appear in the (implicit) `extern crate name` declaration.
    name: string,
}

This format is provisional and subject to change. Specifically, the roots setup will be different eventually.

There are tree ways to feed rust-project.json to rust-analyzer:

  • Place rust-project.json file at the root of the project, and rust-anlayzer will discover it.

  • Specify "rust-analyzer.linkedProjects": [ "path/to/rust-project.json" ] in the settings (and make sure that your LSP client sends settings as a part of initialize request).

  • Specify "rust-analyzer.linkedProjects": [ { "roots": […​], "crates": […​] }] inline.

Relative paths are interpreted relative to rust-project.json file location or (for inline JSON) relative to rootUri.

You can set RA_LOG environmental variable to rust_analyzer=info to inspect how rust-analyzer handles config and project loading.

Features

Expand Macro Recursively

Source: expand_macro.rs

Shows the full macro expansion of the macro at current cursor.

Editor Action Name

VS Code

Rust Analyzer: Expand macro recursively

Extend Selection

Extends the current selection to the encompassing syntactic construct (expression, statement, item, module, etc). It works with multiple cursors.

Editor Shortcut

VS Code

Ctrl+Shift+

File Structure

Provides a tree of the symbols defined in the file. Can be used to

  • fuzzy search symbol in a file (super useful)

  • draw breadcrumbs to describe the context around the cursor

  • draw outline of the file

Editor Shortcut

VS Code

Ctrl+Shift+O

Go to Definition

Navigates to the definition of an identifier.

Editor Shortcut

VS Code

F12

Go to Implementation

Navigates to the impl block of structs, enums or traits. Also implemented as a code lens.

Editor Shortcut

VS Code

Ctrl+F12

Go to Type Definition

Navigates to the type of an identifier.

Editor Action Name

VS Code

*Go to Type Definition

Hover

Source: hover.rs

Shows additional information, like type of an expression or documentation for definition when "focusing" code. Focusing is usually hovering with a mouse, but can also be triggered with a shortcut.

Inlay Hints

Source: inlay_hints.rs

rust-analyzer shows additional information inline with the source code. Editors usually render this using read-only virtual text snippets interspersed with code.

rust-analyzer shows hints for

  • types of local variables

  • names of function arguments

  • types of chained expressions

Note: VS Code does not have native support for inlay hints yet and the hints are implemented using decorations. This approach has limitations, the caret movement and bracket highlighting near the edges of the hint may be weird: 1, 2.

Editor Action Name

VS Code

*Rust Analyzer: Toggle inlay hints

Join Lines

Source: join_lines.rs

Join selected lines into one, smartly fixing up whitespace, trailing commas, and braces.

Editor Action Name

VS Code

Rust Analyzer: Join lines

Magic Completions

Source: completion.rs

In addition to usual reference completion, rust-analyzer provides some ✨magic✨ completions as well:

Keywords like if, else while, loop are completed with braces, and cursor is placed at the appropriate position. Even though if is easy to type, you still want to complete it, to get ` { }` for free! return is inserted with a space or ; depending on the return type of the function.

When completing a function call, () are automatically inserted. If a function takes arguments, the cursor is positioned inside the parenthesis.

There are postfix completions, which can be triggered by typing something like foo().if. The word after . determines postfix completion. Possible variants are:

  • expr.ifif expr {} or if let …​ {} for Option or Result

  • expr.matchmatch expr {}

  • expr.whilewhile expr {} or while let …​ {} for Option or Result

  • expr.ref&expr

  • expr.refm&mut expr

  • expr.not!expr

  • expr.dbgdbg!(expr)

There also snippet completions:

Expressions
  • pdeprintln!(" = {:?}", );

  • ppdeprintln!(" = {:#?}", );

Items
  • tfn#[test] fn feature(){}

  • tmod

1
2
3
4
5
6
7
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_name() {}
}

Matching Brace

If the cursor is on any brace (<>(){}[]||) which is a part of a brace-pair, moves cursor to the matching brace. It uses the actual parser to determine braces, so it won’t confuse generics with comparisons.

Editor Action Name

VS Code

Rust Analyzer: Find matching brace

Memory Usage

Source: change.rs

Clears rust-analyzer’s internal database and prints memory usage statistics.

Editor Action Name

VS Code

Rust Analyzer: Memory Usage (Clears Database)

On Enter

Source: on_enter.rs

rust-analyzer can override Enter key to make it smarter:

  • Enter inside triple-slash comments automatically inserts ///

  • Enter in the middle or after a trailing space in // inserts //

This action needs to be assigned to shortcut explicitly.

VS Code

Add the following to keybindings.json:

1
2
3
4
5
{
  "key": "Enter",
  "command": "rust-analyzer.onEnter",
  "when": "editorTextFocus && !suggestWidgetVisible && editorLangId == rust"
}

On Typing Assists

Source: typing.rs

Some features trigger on typing certain characters:

  • typing let = tries to smartly add ; if = is followed by an existing expression

  • typing . in a chain method call auto-indents

    VS Code

    Add the following to settings.json:

"editor.formatOnType": true,

Parent Module

Navigates to the parent module of the current module.

Editor Action Name

VS Code

Rust Analyzer: Locate parent module

Run

Source: runnables.rs

Shows a popup suggesting to run a test/benchmark/binary at the current cursor location. Super useful for repeatedly running just a single test. Do bind this to a shortcut!

Editor Action Name

VS Code

Rust Analyzer: Run

Semantic Syntax Highlighting

rust-analyzer highlights the code semantically. For example, bar in foo::Bar might be colored differently depending on whether Bar is an enum or a trait. rust-analyzer does not specify colors directly, instead it assigns tag (like struct) and a set of modifiers (like declaration) to each token. It’s up to the client to map those to specific colors.

The general rule is that a reference to an entity gets colored the same way as the entity itself. We also give special modifier for mut and &mut local variables.

Show Syntax Tree

Source: syntax_tree.rs

Shows the parse tree of the current file. It exists mostly for debugging rust-analyzer itself.

Editor Action Name

VS Code

Rust Analyzer: Show Syntax Tree

Status

Source: status.rs

Shows internal statistic about memory usage of rust-analyzer.

Editor Action Name

VS Code

Rust Analyzer: Status

Structural Search and Replace

Source: lib.rs

Search and replace with named wildcards that will match any expression, type, path, pattern or item. The syntax for a structural search replace command is <search_pattern> =⇒> <replace_pattern>. A $<name> placeholder in the search pattern will match any AST node and $<name> will reference it in the replacement. Within a macro call, a placeholder will match up until whatever token follows the placeholder.

All paths in both the search pattern and the replacement template must resolve in the context in which this command is invoked. Paths in the search pattern will then match the code if they resolve to the same item, even if they’re written differently. For example if we invoke the command in the module foo with a pattern of Bar, then code in the parent module that refers to foo::Bar will match.

Paths in the replacement template will be rendered appropriately for the context in which the replacement occurs. For example if our replacement template is foo::Bar and we match some code in the foo module, we’ll insert just Bar.

Inherent method calls should generally be written in UFCS form. e.g. foo::Bar::baz($s, $a) will match $s.baz($a), provided the method call baz resolves to the method foo::Bar::baz. When a placeholder is the receiver of a method call in the search pattern (e.g. $s.foo()), but not in the replacement template (e.g. bar($s)), then *, & and &mut will be added as needed to mirror whatever autoderef and autoref was happening implicitly in the matched code.

The scope of the search / replace will be restricted to the current selection if any, otherwise it will apply to the whole workspace.

Placeholders may be given constraints by writing them as ${<name>:<constraint1>:<constraint2>…​}.

Supported constraints:

Constraint Restricts placeholder

kind(literal)

Is a literal (e.g. 42 or "forty two")

not(a)

Negates the constraint a

Available via the command rust-analyzer.ssr.

1
2
3
4
5
6
7
// Using structural search replace command [foo($a, $b) ==>> ($a).foo($b)]

// BEFORE
String::from(foo(y + 5, z))

// AFTER
String::from((y + 5).foo(z))
Editor Action Name

VS Code

Rust Analyzer: Structural Search Replace

Workspace Symbol

Source: symbol_index.rs

Uses fuzzy-search to find types, modules and functions by name across your project and dependencies. This is the most useful feature, which improves code navigation tremendously. It mostly works on top of the built-in LSP functionality, however # and * symbols can be used to narrow down the search. Specifically,

  • Foo searches for Foo type in the current workspace

  • foo# searches for foo function in the current workspace

  • Foo* searches for Foo type among dependencies, including stdlib

  • foo#* searches for foo function among dependencies

That is, # switches from "types" to all symbols, * switches from the current workspace to dependencies.

Editor Shortcut

VS Code

Ctrl+T

Assists (Code Actions)

Assists, or code actions, are small local refactorings, available in a particular context. They are usually triggered by a shortcut or by clicking a light bulb icon in the editor. Cursor position or selection is signified by character.

add_custom_impl

Adds impl block for derived trait.

Before
1
2
#[derive(Debug, Display)]
struct S;
After
1
2
3
4
5
6
#[derive(Display)]
struct S;

impl Debug for S {
    $0
}

add_explicit_type

Specify type for a let binding.

Before
1
2
3
fn main() {
    let x = 92;
}
After
1
2
3
fn main() {
    let x: i32 = 92;
}

add_hash

Source: raw_string.rs

Adds a hash to a raw string literal.

Before
1
2
3
fn main() {
    r#"Hello,┃ World!"#;
}
After
1
2
3
fn main() {
    r##"Hello, World!"##;
}

add_impl_default_members

Adds scaffold for overriding default impl members.

Before
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
trait Trait {
    Type X;
    fn foo(&self);
    fn bar(&self) {}
}

impl Trait for () {
    Type X = ();
    fn foo(&self) {}

}
After
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
trait Trait {
    Type X;
    fn foo(&self);
    fn bar(&self) {}
}

impl Trait for () {
    Type X = ();
    fn foo(&self) {}

    $0fn bar(&self) {}
}

add_impl_missing_members

Adds scaffold for required impl members.

Before
1
2
3
4
5
6
7
8
9
trait Trait<T> {
    Type X;
    fn foo(&self) -> T;
    fn bar(&self) {}
}

impl Trait<u32> for () {

}
After
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
trait Trait<T> {
    Type X;
    fn foo(&self) -> T;
    fn bar(&self) {}
}

impl Trait<u32> for () {
    fn foo(&self) -> u32 {
        ${0:todo!()}
    }
}

add_turbo_fish

Adds ::<_> to a call of a generic method or function.

Before
1
2
3
4
fn make<T>() -> T { todo!() }
fn main() {
    let x = make();
}
After
1
2
3
4
fn make<T>() -> T { todo!() }
fn main() {
    let x = make::<${0:_}>();
}

apply_demorgan

Apply De Morgan’s law. This transforms expressions of the form !l || !r into !(l && r). This also works with &&. This assist can only be applied with the cursor on either || or &&, with both operands being a negation of some kind. This means something of the form !x or x != y.

Before
1
2
3
fn main() {
    if x != 4 || !y {}
}
After
1
2
3
fn main() {
    if !(x == 4 && y) {}
}

auto_import

Source: auto_import.rs

If the name is unresolved, provides all possible imports for it.

Before
1
2
3
fn main() {
    let map = HashMap::new();
}
After
1
2
3
4
5
use std::collections::HashMap;

fn main() {
    let map = HashMap::new();
}

change_return_type_to_result

Change the function’s return type to Result.

Before
1
fn foo() -> i32 { 42i32 }
After
1
fn foo() -> Result<i32, ${0:_}> { Ok(42i32) }

change_visibility

Adds or changes existing visibility specifier.

Before
1
fn frobnicate() {}
After
1
pub(crate) fn frobnicate() {}

convert_to_guarded_return

Source: early_return.rs

Replace a large conditional with a guarded return.

Before
1
2
3
4
5
6
fn main() {
    if cond {
        foo();
        bar();
    }
}
After
1
2
3
4
5
6
7
fn main() {
    if !cond {
        return;
    }
    foo();
    bar();
}

expand_glob_import

Expands glob imports.

Before
1
2
3
4
5
6
7
8
mod foo {
    pub struct Bar;
    pub struct Baz;
}

use foo::*;

fn qux(bar: Bar, baz: Baz) {}
After
1
2
3
4
5
6
7
8
mod foo {
    pub struct Bar;
    pub struct Baz;
}

use foo::{Baz, Bar};

fn qux(bar: Bar, baz: Baz) {}

extract_struct_from_enum_variant

Extracts a struct from enum variant.

Before
1
enum A { One(u32, u32) }
After
1
2
3
struct One(pub u32, pub u32);

enum A { One(One) }

extract_variable

Extracts subexpression into a variable.

Before
1
2
3
fn main() {
    (1 + 2) * 4;
}
After
1
2
3
4
fn main() {
    let $0var_name = (1 + 2);
    var_name * 4;
}

fill_match_arms

Adds missing clauses to a match expression.

Before
1
2
3
4
5
6
7
enum Action { Move { distance: u32 }, Stop }

fn handle(action: Action) {
    match action {
        
    }
}
After
1
2
3
4
5
6
7
8
enum Action { Move { distance: u32 }, Stop }

fn handle(action: Action) {
    match action {
        $0Action::Move { distance } => {}
        Action::Stop => {}
    }
}

fix_visibility

Makes inaccessible item public.

Before
1
2
3
4
5
6
mod m {
    fn frobnicate() {}
}
fn main() {
    m::frobnicate() {}
}
After
1
2
3
4
5
6
mod m {
    $0pub(crate) fn frobnicate() {}
}
fn main() {
    m::frobnicate() {}
}

flip_binexpr

Source: flip_binexpr.rs

Flips operands of a binary expression.

Before
1
2
3
fn main() {
    let _ = 90 + 2;
}
After
1
2
3
fn main() {
    let _ = 2 + 90;
}

flip_comma

Source: flip_comma.rs

Flips two comma-separated items.

Before
1
2
3
fn main() {
    ((1, 2), (3, 4));
}
After
1
2
3
fn main() {
    ((3, 4), (1, 2));
}

flip_trait_bound

Flips two trait bounds.

Before
1
fn foo<T: Clone + Copy>() { }
After
1
fn foo<T: Copy + Clone>() { }

generate_derive

Adds a new #[derive()] clause to a struct or enum.

Before
1
2
3
4
struct Point {
    x: u32,
    y: u32,
}
After
1
2
3
4
5
#[derive($0)]
struct Point {
    x: u32,
    y: u32,
}

generate_from_impl_for_enum

Adds a From impl for an enum variant with one tuple field.

Before
1
enum A { One(u32) }
After
1
2
3
4
5
6
7
enum A { One(u32) }

impl From<u32> for A {
    fn from(v: u32) -> Self {
        A::One(v)
    }
}

generate_function

Adds a stub function with a signature matching the function under the cursor.

Before
1
2
3
4
5
struct Baz;
fn baz() -> Baz { Baz }
fn foo() {
    bar("", baz());
}
After
1
2
3
4
5
6
7
8
9
struct Baz;
fn baz() -> Baz { Baz }
fn foo() {
    bar("", baz());
}

fn bar(arg: &str, baz: Baz) {
    ${0:todo!()}
}

generate_impl

Adds a new inherent impl for a type.

Before
1
2
3
struct Ctx<T: Clone> {
    data: T,
}
After
1
2
3
4
5
6
7
struct Ctx<T: Clone> {
    data: T,
}

impl<T: Clone> Ctx<T> {
    $0
}

generate_new

Source: generate_new.rs

Adds a new inherent impl for a type.

Before
1
2
3
struct Ctx<T: Clone> {
     data: T,
}
After
1
2
3
4
5
6
7
struct Ctx<T: Clone> {
     data: T,
}

impl<T: Clone> Ctx<T> {
    fn $0new(data: T) -> Self { Self { data } }
}

inline_local_variable

Inlines local variable.

Before
1
2
3
4
fn main() {
    let x = 1 + 2;
    x * 4;
}
After
1
2
3
fn main() {
    (1 + 2) * 4;
}

introduce_named_lifetime

Change an anonymous lifetime to a named lifetime.

Before
1
2
3
4
5
6
7
impl Cursor<'_> {
    fn node(self) -> &SyntaxNode {
        match self {
            Cursor::Replace(node) | Cursor::Before(node) => node,
        }
    }
}
After
1
2
3
4
5
6
7
impl<'a> Cursor<'a> {
    fn node(self) -> &SyntaxNode {
        match self {
            Cursor::Replace(node) | Cursor::Before(node) => node,
        }
    }
}

invert_if

Source: invert_if.rs

Apply invert_if This transforms if expressions of the form if !x {A} else {B} into if x {B} else {A} This also works with !=. This assist can only be applied with the cursor on if.

Before
1
2
3
fn main() {
    if !y { A } else { B }
}
After
1
2
3
fn main() {
    if y { B } else { A }
}

make_raw_string

Source: raw_string.rs

Adds r# to a plain string literal.

Before
1
2
3
fn main() {
    "Hello,┃ World!";
}
After
1
2
3
fn main() {
    r#"Hello, World!"#;
}

make_usual_string

Source: raw_string.rs

Turns a raw string into a plain string.

Before
1
2
3
fn main() {
    r#"Hello,┃ "World!""#;
}
After
1
2
3
fn main() {
    "Hello, \"World!\"";
}

merge_imports

Merges two imports with a common prefix.

Before
1
2
use std::fmt::Formatter;
use std::io;
After
1
use std::{fmt::Formatter, io};

merge_match_arms

Merges identical match arms.

Before
1
2
3
4
5
6
7
8
enum Action { Move { distance: u32 }, Stop }

fn handle(action: Action) {
    match action {
        Action::Move(..) => foo(),
        Action::Stop => foo(),
    }
}
After
1
2
3
4
5
6
7
enum Action { Move { distance: u32 }, Stop }

fn handle(action: Action) {
    match action {
        Action::Move(..) | Action::Stop => foo(),
    }
}

move_arm_cond_to_match_guard

Source: move_guard.rs

Moves if expression from match arm body into a guard.

Before
1
2
3
4
5
6
7
8
enum Action { Move { distance: u32 }, Stop }

fn handle(action: Action) {
    match action {
        Action::Move { distance } => if distance > 10 { foo() },
        _ => (),
    }
}
After
1
2
3
4
5
6
7
8
enum Action { Move { distance: u32 }, Stop }

fn handle(action: Action) {
    match action {
        Action::Move { distance } if distance > 10 => foo(),
        _ => (),
    }
}

move_bounds_to_where_clause

Source: move_bounds.rs

Moves inline type bounds to a where clause.

Before
1
2
3
fn apply<T, U, F: FnOnce(T) -> U>(f: F, x: T) -> U {
    f(x)
}
After
1
2
3
fn apply<T, U, F>(f: F, x: T) -> U where F: FnOnce(T) -> U {
    f(x)
}

move_guard_to_arm_body

Source: move_guard.rs

Moves match guard into match arm body.

Before
1
2
3
4
5
6
7
8
enum Action { Move { distance: u32 }, Stop }

fn handle(action: Action) {
    match action {
        Action::Move { distance } if distance > 10 => foo(),
        _ => (),
    }
}
After
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
enum Action { Move { distance: u32 }, Stop }

fn handle(action: Action) {
    match action {
        Action::Move { distance } => if distance > 10 {
            foo()
        },
        _ => (),
    }
}

remove_dbg

Source: remove_dbg.rs

Removes dbg!() macro call.

Before
1
2
3
fn main() {
    dbg!(92);
}
After
1
2
3
fn main() {
    92;
}

remove_hash

Source: raw_string.rs

Removes a hash from a raw string literal.

Before
1
2
3
fn main() {
    r#"Hello,┃ World!"#;
}
After
1
2
3
fn main() {
    r"Hello, World!";
}

remove_mut

Source: remove_mut.rs

Removes the mut keyword.

Before
1
2
3
impl Walrus {
    fn feed(&mut self, amount: u32) {}
}
After
1
2
3
impl Walrus {
    fn feed(&self, amount: u32) {}
}

remove_unused_param

Removes unused function parameter.

Before
1
2
3
4
5
fn frobnicate(x: i32) {}

fn main() {
    frobnicate(92);
}
After
1
2
3
4
5
fn frobnicate() {}

fn main() {
    frobnicate();
}

reorder_fields

Reorder the fields of record literals and record patterns in the same order as in the definition.

Before
1
2
struct Foo {foo: i32, bar: i32};
const test: Foo = Foo {bar: 0, foo: 1}
After
1
2
struct Foo {foo: i32, bar: i32};
const test: Foo = Foo {foo: 1, bar: 0}

replace_if_let_with_match

Replaces if let with an else branch with a match expression.

Before
1
2
3
4
5
6
7
8
9
enum Action { Move { distance: u32 }, Stop }

fn handle(action: Action) {
    if let Action::Move { distance } = action {
        foo(distance)
    } else {
        bar()
    }
}
After
1
2
3
4
5
6
7
8
enum Action { Move { distance: u32 }, Stop }

fn handle(action: Action) {
    match action {
        Action::Move { distance } => foo(distance),
        _ => bar(),
    }
}

replace_impl_trait_with_generic

Replaces impl Trait function argument with the named generic.

Before
1
fn foo(bar: impl Bar) {}
After
1
fn foo<B: Bar>(bar: B) {}

replace_let_with_if_let

Replaces let with an if-let.

Before
1
2
3
4
5
6
fn main(action: Action) {
    let x = compute();
}

fn compute() -> Option<i32> { None }
After
1
2
3
4
5
6
7
fn main(action: Action) {
    if let Some(x) = compute() {
    }
}

fn compute() -> Option<i32> { None }

replace_qualified_name_with_use

Adds a use statement for a given fully-qualified name.

Before
1
fn process(map: std::collections::HashMap<String, String>) {}
After
1
2
3
use std::collections::HashMap;

fn process(map: HashMap<String, String>) {}

replace_unwrap_with_match

Replaces unwrap a match expression. Works for Result and Option.

Before
1
2
3
4
5
enum Result<T, E> { Ok(T), Err(E) }
fn main() {
    let x: Result<i32, i32> = Result::Ok(92);
    let y = x.┃unwrap();
}
After
1
2
3
4
5
6
7
8
enum Result<T, E> { Ok(T), Err(E) }
fn main() {
    let x: Result<i32, i32> = Result::Ok(92);
    let y = match x {
        Ok(a) => a,
        $0_ => unreachable!(),
    };
}

split_import

Source: split_import.rs

Wraps the tail of import into braces.

Before
1
use std::collections::HashMap;
After
1
use std::{collections::HashMap};

unwrap_block

Source: unwrap_block.rs

This assist removes if…​else, for, while and loop control statements to just keep the body.

Before
1
2
3
4
5
fn foo() {
    if true {
        println!("foo");
    }
}
After
1
2
3
fn foo() {
    println!("foo");
}

Editor Features

VS Code

Color configurations

It is possible to change the foreground/background color of inlay hints. Just add this to your settings.json:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{
  "workbench.colorCustomizations": {
    // Name of the theme you are currently using
    "[Default Dark+]": {
      "rust_analyzer.inlayHints.foreground": "#868686f0",
      "rust_analyzer.inlayHints.background": "#3d3d3d48",

      // Overrides for specific kinds of inlay hints
      "rust_analyzer.inlayHints.foreground.typeHints": "#fdb6fdf0",
      "rust_analyzer.inlayHints.foreground.paramHints": "#fdb6fdf0",
      "rust_analyzer.inlayHints.background.chainingHints": "#6b0c0c81"
    }
  }
}

Special when clause context for keybindings.

You may use inRustProject context to configure keybindings for rust projects only. For example:

1
2
3
4
5
{
  "key": "ctrl+i",
  "command": "rust-analyzer.toggleInlayHints",
  "when": "inRustProject"
}

More about when clause contexts here.

Setting runnable environment variables

You can use "rust-analyzer.runnableEnv" setting to define runnable environment-specific substitution variables. The simplest way for all runnables in a bunch:

1
2
3
"rust-analyzer.runnableEnv": {
    "RUN_SLOW_TESTS": "1"
}

Or it is possible to specify vars more granularly:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
"rust-analyzer.runnableEnv": [
    {
        // "mask": null, // null mask means that this rule will be applied for all runnables
        env: {
             "APP_ID": "1",
             "APP_DATA": "asdf"
        }
    },
    {
        "mask": "test_name",
        "env": {
             "APP_ID": "2", // overwrites only APP_ID
        }
    }
]

You can use any valid RegExp as a mask. Also note that a full runnable name is something like run bin_or_example_name, test some::mod::test_name or test-mod some::mod, so it is possible to distinguish binaries, single tests, and test modules with this masks: "^run", "^test " (the trailing space matters!), and "^test-mod" respectively.

Compiler feedback from external commands

Instead of relying on the built-in cargo check, you can configure Code to run a command in the background and use the $rustc-watch problem matcher to generate inline error markers from its output.

To do this you need to create a new VS Code Task and set rust-analyzer.checkOnSave.enable: false in preferences.

For example, if you want to run cargo watch instead, you might add the following to .vscode/tasks.json:

1
2
3
4
5
6
7
8
{
    "label": "Watch",
    "group": "build",
    "type": "shell",
    "command": "cargo watch",
    "problemMatcher": "$rustc-watch",
    "isBackground": true
}