Rust Analyzer Vscode



Rust is an exciting programming language and I highly recommend giving it a shot. Getting started is a cinch. If you’re interested in programming Rust on Windows, follow the steps below and you’ll be up and writing code in no time.

Watch the Video On YouTube

  1. Provides support for rust-analyzer: novel LSP server for the Rust programming language. Note the extension may cause conflicts with the official Rust extension. It is recommended to disable the Rust extension when using the rust-analyzer extension.
  2. Visual Studio Code is my Rust editor of choice. Unfortunately it can't quite debug Rust out of the box. Configuring the debugger isn't hard. But there are a few steps. I've gone through them several times now. I'm writing this guide to save future me from having to remember them. Hopefully this guide is useful to a few other folks as well.

If you would rather follow in video format, you can catch a video of this post on my YouTube channel.

Prerequisites for Using Rust in VS Code

Interestingly enough, the Rust compiler requires the Microsoft C++ Build Tools to do its job. Before proceeding, you’ll need to ensure the Visual Studio Build Tools are installed on your machine. Visual Studio comes prepackaged with these build tools. However, VS Code does not. You can find the Visual Studio Build Tools 2019 version here. It is free to download and install.

I had issues where it took a lot longer to update the highlighting in vscode and got the alert “waiting for save actions from rust-analyzer” KSXGitHub May 1, 2020, 12:40pm #4. Install the rust-analyzer extension; Configuration. This extension provides configurations through VSCode's configuration settings. All the configurations are under rust-analyzer. See for more information on VSCode.

Clicking the link above will take you to a page entitled, “Thank you for downloading Visual Studio.” Don’t be fooled by this title. the download of the build tools will begin shortly after clicking the link.

Once you’ve downloaded the build tools, execute the setup. Select the option to install the C++ Build Tools and click the Install button. Upon completion, close the window entitled “Visual Studio Installer.”

Install Rust

Next, head on over to the Installation page and click the gargantuan button labeled “Rustup-Init.exe.” There are a few alternate ways to install Rust, but I don’t recommend them. Even though you may be tempted, I strongly suggest not installing Rust through Chocolatey, as it doesn’t appear to install all of the required tools in the tool chain (mainly rustup). With rustup missing, you won’t be able to get the Rust Language Server (RLS) up and running in Visual Studio Code.

When you click on the button, your browser will download the rustup-init.exe executable, which is essentially a command-line installer. Proceed along with the defaults until the installation is complete. Installing Rust will alter your machine’s PATH environment variable. So once the installation is complete, you’ll need to launch a new command prompt for changes to take affect.

Verify Rust is Installed

Open a new PowerShell window or command prompt and execute the following:

If you see a version number, the tool chain should be successfully installed. You can then verify that the latest version of Rust and all of the other tools in the tool chain are installed with the following command line:

Configure Visual Studio Code

Launch VS Code. Note that if VS Code was running before the Rust installation completed, you’ll need to restart it for the environmental changes to take affect.

There are a variety of VS Code extensions that support Rust. I found the “Rust Extension Pack” to be a great pick on the marketplace. Not only does it bundle the Rust RLS official extension, but it includes the most popular cargo and TOML plugins available. To install this extension pack:

  1. Navigate to the Extensions panel (or type Ctrl-Shift-X).
  2. Enter “Rust Extension Pack” in the search panel.
  3. Click the Install button.

The only deficiency in the Rust Extension Pack is the lack of test integration. Unfortunately, there currently isn’t a lot to choose from. However, there is one that appears to do a decent job – “Rust Test Explorer“. Follow the steps above to install this extension and you’ll be able to navigate and execute unit tests from the Test Explorer panel.

Create a Simple Hello World Project

In VS Code, open a new, empty folder. We’ll flesh out a simple Rust project from here. In the Explorer panel, create a new file named “Cargo.toml” with the following information:

Create a new directory named ‘src.’ Within that directory, create a file named main.rs with the following content:

Create a Build Task

VS Code will execute a default task every time you choose to build your code. We will configure Code to execute the “cargo build” command line every time you kick off this build process.

Open the command palette (Ctrl-Shift-P) and type in “build” and select “Tasks: Configure Default Build Task”

Select “Rust: cargo build”

This should create a tasks.json file that has a single, default build task.

Cargo Build Task in Tasks.json

Now, every time that you press Control-Shift-B or run a build from the command palette, VS Code will execute cargo build.

Configuring Unit Tests

Vscode Rust-analyzer Clippy

Just like with the Build task, Code also executes a default task when you choose to run unit tests. To get you up and running, we’ll create a simple test that always fails. Open the main.rs file and add a simple test below the main function:

Save the file and open the command palette again. Type in “task” and select “Tasks: Configure Default Test Task”

Select “Rust: cargo test”

Analyzer

This should add a cargo test task to the tasks.json file. Now, every time that you run the Test Task, VS Code will execute the “cargo test” command and provide feedback in the Terminal panel. If you would prefer to execute your unit tests from a UI, you can also execute tests directly from the Test Explorer.

If your tests aren’t showing up in Test Explorer, press the circular refresh button to refresh the test list.

Configure Debugging Configuration

The thought of typing “cargo run” every time I want to run my app is not very enticing. I also want to be able to debug my app. I thought debugging Rust in Code was going to a be a pain until I found a blog by Bryce Van Dyk, entitled “Debug Rust on Windows with Visual Studio Code and the MSVC Debugger.” His post is awesome; read through it if you get a chance.

If you don’t want to read the whole article and still want to take advantage of debugging Rust in Code, perform the following steps:

  1. Install the C/C++ extension.
  2. Install the Native Debug extension.
  3. In the Debug panel, click Show all Automatic debug configurations.
  4. Click Add Configuration…
  5. Select the “C++ (Windows)” environment. This will create a new launch.json file.
  6. Change the program value to be “${workspaceFolder}/target/debug/hello-world.exe” and save the file.

Your launch.json should look similar to mine:

Rust Analyzer Vscode Settings

Rust Debug Configuration in Launch.json

Next, you’ll need to alter your settings to allow breakpoints in Rust files.

  1. Click File | Preferences | Settings. The settings Tab will open.
  2. In the Search Settings textbox, enter the text “breakpoint”.
  3. Click the checkbox to allow setting breakpoints in any file.

Alternatively, you can open your settings.json file and add the following:

Now, when you hit F5, VS Code will start debugging a new instance of your program. You can add breakpoints where needed.

I have used many editors in the last 5 years.

Sublime Text, Vim, then CLion, then VSCode, back to Vim, briefly Onivim and now Neovim.

I find it important to experiment with different editors and IDEs in order tohave an idea of what powers they hold and how they could be included in yourdevelopment toolbox.

Over the last couple months, I have been looking at ways to “sharpen” my developmenttoolset and have been playing around with multiple vim configurations, one in whichI’d like to share today.

Neovim is a fork of vim, which is focused on extensibilityand usability. An example of this is the ability to use Lua instead of VimL forplugins providing greater flexibility for extending the editor.

In the 0.5 release of Neovim (currently nightly), the developers have introducedan Language Server Protocol(LSP) client framework (:help lsp)

This means, Neovim can act as a client to LSP servers (like rust-analyzer) andassist in building enhanced LSP tools.

LSP facilitates programming language specific features such as go-to-definition,completion, refactoring, formatting, etc. The goal of LSP is to separatelanguage support and the editor.

Why use LSP? Well, for one, it allows the developers of an editor to focus on theeditor and not of specific language support. This is a win-win for language providersand those who release tooling. This is turning a X*Y problem into X+Y.(Where X is the number of editors and Y is the number of languages). There are LSPservers available for almost every language out there.

So how do we configure Neovim LSP with rust-analyzer? Simple!

Check out this repository for the complete configuration and more

Let’s start with the prerequisites:

  • Neovim >= 0.5, see Installing Neovim
    • Currently, 0.5 can be found as anightly download,in the unstable PPAor other nightly sources. I am currently living on the bleeding edge: buildingand installing neovim from the master git branch.
  • Install rust-analyzerNote: The binary must be in your PATH

Diving in, let’s install some plugins.

The plugin manager used here is vim-plug,but any plugin manager can be used.

To install the above run the :PlugInstall command in neovim, or start it with nvim +PlugInstall.

Enable syntax highlighting and file type identification, plugin and indenting

Rust Analyzer Server

Let’s setup the rust-analyzer LSP and add completion and enable diagnostics

Now when nvim is restarted, you should be able to autocomplete and view warningsand errors inside the editor! You’ll notice, however, that the completion experienceis not like what you might be use to in VSCode or other editors.Mostly surrounding the lack of <Tab> completion to navigate the menu. Vim uses <C-N>!

<Tab> completion can be accomplished with the following

(Found in :help completion)

What about code navigation? (:help lsp)

Vscode Rust-analyzer Rustfmt

Code actions are also very useful.

Let’s improve the diagnostics experience.

You may notice, there’s a slight vertical jitter when a new diagnostic comes in.

To avoid this, you can set signcolumn

Rust Analyzer Vscode

Vscode

And to cap it off, let’s enable inlay hints!

To conclude, this introduces a basic and flexible setup for Rust development.Here’s the best part though, it’s simple to configuremore languages servers!This setup allows you, the developer, to add more lsp'(just like we did with rust-analyzer) to have a full featured cross-language experience.

Thanks for reading!

Questions? Found an error? Create an issue on Github!

Vs Code Rust Analyzer

Edits:

  • 2020-09-23: Added note about signcolumn
  • 2020-10-05: Added note about code actions and gif
  • 2020-12-17: Updated diagnostics and lsp config to reflect latest neovim developments
  • 2020-12-23: Updated tab completion config to reflect latestcompletion.nvim developments
  • 2021-02-02: Added enabled to inlay_hints function call to support more hints




Comments are closed.