1= User Manual 2:toc: preamble 3:sectanchors: 4:page-layout: post 5:icons: font 6:source-highlighter: rouge 7:experimental: 8 9//// 10IMPORTANT: the master copy of this document lives in the https://github.com/rust-analyzer/rust-analyzer repository 11//// 12 13At its core, rust-analyzer is a *library* for semantic analysis of Rust code as it changes over time. 14This manual focuses on a specific usage of the library -- running it as part of a server that implements the 15https://microsoft.github.io/language-server-protocol/[Language Server Protocol] (LSP). 16The 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. 17 18[TIP] 19==== 20[.lead] 21To improve this document, send a pull request: + 22https://github.com/rust-analyzer/rust-analyzer/blob/master/docs/user/manual.adoc[https://github.com/rust-analyzer/.../manual.adoc] 23 24The manual is written in https://asciidoc.org[AsciiDoc] and includes some extra files which are generated from the source code. Run `cargo test` and `cargo test -p xtask` to create these and then `asciidoctor manual.adoc` to create an HTML copy. 25==== 26 27If you have questions about using rust-analyzer, please ask them in the https://users.rust-lang.org/c/ide/14["`IDEs and Editors`"] topic of Rust users forum. 28 29== Installation 30 31In theory, one should be able to just install the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>> and have it automatically work with any editor. 32We are not there yet, so some editor specific setup is required. 33 34Additionally, rust-analyzer needs the sources of the standard library. 35If the source code is not present, rust-analyzer will attempt to install it automatically. 36 37To add the sources manually, run the following command: 38 39```bash 40$ rustup component add rust-src 41``` 42 43=== VS Code 44 45This is the best supported editor at the moment. 46The rust-analyzer plugin for VS Code is maintained 47https://github.com/rust-analyzer/rust-analyzer/tree/master/editors/code[in tree]. 48 49You can install the latest release of the plugin from 50https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer[the marketplace]. 51 52Note that the plugin may cause conflicts with the 53https://marketplace.visualstudio.com/items?itemName=rust-lang.rust[official Rust plugin]. 54It is recommended to disable the Rust plugin when using the rust-analyzer extension. 55 56By default, the plugin will prompt you to download the matching version of the server as well: 57 58image::https://user-images.githubusercontent.com/9021944/75067008-17502500-54ba-11ea-835a-f92aac50e866.png[] 59 60[NOTE] 61==== 62To disable this notification put the following to `settings.json` 63 64[source,json] 65---- 66{ "rust-analyzer.updates.askBeforeDownload": false } 67---- 68==== 69 70The server binary is stored in: 71 72* Linux: `~/.config/Code/User/globalStorage/matklad.rust-analyzer` 73* Linux (Remote, such as WSL): `~/.vscode-server/data/User/globalStorage/matklad.rust-analyzer` 74* macOS: `~/Library/Application\ Support/Code/User/globalStorage/matklad.rust-analyzer` 75* Windows: `%APPDATA%\Code\User\globalStorage\matklad.rust-analyzer` 76 77However, if you are using a version of the extension with a bundled server binary and you are not running NixOS, the server binary might be instead running from: `~/.vscode/extensions/matklad.rust-analyzer-VERSION`. 78 79Note that we only support two most recent versions of VS Code. 80 81==== Updates 82 83The extension will be updated automatically as new versions become available. 84It will ask your permission to download the matching language server version binary if needed. 85 86===== Nightly 87 88We ship nightly releases for VS Code. 89To help us out with testing the newest code and follow the bleeding edge of our `master`, please use the following config: 90 91[source,json] 92---- 93{ "rust-analyzer.updates.channel": "nightly" } 94---- 95 96You will be prompted to install the `nightly` extension version. 97Just click `Download now` and from that moment you will get automatic updates every 24 hours. 98 99If 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`: 100[source,json] 101---- 102{ "rust-analyzer.updates.askBeforeDownload": false } 103---- 104 105NOTE: Nightly extension should **only** be installed via the `Download now` action from VS Code. 106 107==== Manual installation 108 109Alternatively, procure both `rust-analyzer.vsix` and your platform's matching `rust-analyzer-{platform}`, for example from the 110https://github.com/rust-analyzer/rust-analyzer/releases[releases] page. 111 112Install the extension with the `Extensions: Install from VSIX` command within VS Code, or from the command line via: 113[source] 114---- 115$ code --install-extension /path/to/rust-analyzer.vsix 116---- 117 118Copy the `rust-analyzer-{platform}` binary anywhere, then add the path to your settings.json, for example: 119[source,json] 120---- 121{ "rust-analyzer.server.path": "~/.local/bin/rust-analyzer-linux" } 122---- 123 124==== Building From Source 125 126Alternatively, both the server and the Code plugin can be installed from source: 127 128[source] 129---- 130$ git clone https://github.com/rust-analyzer/rust-analyzer.git && cd rust-analyzer 131$ cargo xtask install 132---- 133 134You'll need Cargo, nodejs and npm for this. 135 136Note that installing via `xtask install` does not work for VS Code Remote, instead you'll need to install the `.vsix` manually. 137 138If you're not using Code, you can compile and install only the LSP server: 139 140[source] 141---- 142$ cargo xtask install --server 143---- 144 145=== rust-analyzer Language Server Binary 146 147Other editors generally require the `rust-analyzer` binary to be in `$PATH`. 148You can download pre-built binaries from the https://github.com/rust-analyzer/rust-analyzer/releases[releases] page. 149You will need to uncompress and rename the binary for your platform, e.g. from `rust-analyzer-aarch64-apple-darwin.gz` on Mac OS to `rust-analyzer`, make it executable, then move it into a directory in your `$PATH`. 150 151On Linux to install the `rust-analyzer` binary into `~/.local/bin`, these commands should work: 152 153[source,bash] 154---- 155$ mkdir -p ~/.local/bin 156$ curl -L https://github.com/rust-analyzer/rust-analyzer/releases/latest/download/rust-analyzer-x86_64-unknown-linux-gnu.gz | gunzip -c - > ~/.local/bin/rust-analyzer 157$ chmod +x ~/.local/bin/rust-analyzer 158---- 159 160Make sure that `~/.local/bin` is listed in the `$PATH` variable and use the appropriate URL if you're not on a `x86-64` system. 161 162You don't have to use `~/.local/bin`, any other path like `~/.cargo/bin` or `/usr/local/bin` will work just as well. 163 164Alternatively, you can install it from source using the command below. 165You'll need the latest stable version of the Rust toolchain. 166 167[source,bash] 168---- 169$ git clone https://github.com/rust-analyzer/rust-analyzer.git && cd rust-analyzer 170$ cargo xtask install --server 171---- 172 173If 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 https://github.com/rust-analyzer/rust-analyzer/issues/1811[this issue]. 174On Unix, running the editor from a shell or changing the `.desktop` file to set the environment should help. 175 176==== `rustup` 177 178`rust-analyzer` is available in `rustup`, but only in the nightly toolchain: 179 180[source,bash] 181---- 182$ rustup +nightly component add rust-analyzer-preview 183---- 184 185However, in contrast to `component add clippy` or `component add rustfmt`, this does not actually place a `rust-analyzer` binary in `~/.cargo/bin`, see https://github.com/rust-lang/rustup/issues/2411[this issue]. 186 187==== Arch Linux 188 189The `rust-analyzer` binary can be installed from the repos or AUR (Arch User Repository): 190 191- https://www.archlinux.org/packages/community/x86_64/rust-analyzer/[`rust-analyzer`] (built from latest tagged source) 192- https://aur.archlinux.org/packages/rust-analyzer-git[`rust-analyzer-git`] (latest Git version) 193 194Install it with pacman, for example: 195 196[source,bash] 197---- 198$ pacman -S rust-analyzer 199---- 200 201==== Gentoo Linux 202 203`rust-analyzer` is available in the GURU repository: 204 205- https://gitweb.gentoo.org/repo/proj/guru.git/tree/dev-util/rust-analyzer?id=9895cea62602cfe599bd48e0fb02127411ca6e81[`dev-util/rust-analyzer`] builds from source 206- https://gitweb.gentoo.org/repo/proj/guru.git/tree/dev-util/rust-analyzer-bin?id=9895cea62602cfe599bd48e0fb02127411ca6e81[`dev-util/rust-analyzer-bin`] installs an official binary release 207 208If not already, GURU must be enabled (e.g. using `app-eselect/eselect-repository`) and sync'd before running `emerge`: 209 210[source,bash] 211---- 212$ eselect repository enable guru && emaint sync -r guru 213$ emerge rust-analyzer-bin 214---- 215 216==== macOS 217 218The `rust-analyzer` binary can be installed via https://brew.sh/[Homebrew]. 219 220[source,bash] 221---- 222$ brew install rust-analyzer 223---- 224 225=== Emacs 226 227Note this excellent https://robert.kra.hn/posts/2021-02-07_rust-with-emacs/[guide] from https://github.com/rksm[@rksm]. 228 229Prerequisites: You have installed the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>>. 230 231Emacs support is maintained as part of the https://github.com/emacs-lsp/lsp-mode[Emacs-LSP] package in https://github.com/emacs-lsp/lsp-mode/blob/master/lsp-rust.el[lsp-rust.el]. 232 2331. Install the most recent version of `emacs-lsp` package by following the https://github.com/emacs-lsp/lsp-mode[Emacs-LSP instructions]. 2342. Set `lsp-rust-server` to `'rust-analyzer`. 2353. Run `lsp` in a Rust buffer. 2364. (Optionally) bind commands like `lsp-rust-analyzer-join-lines`, `lsp-extend-selection` and `lsp-rust-analyzer-expand-macro` to keys. 237 238=== Vim/NeoVim 239 240Prerequisites: You have installed the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>>. 241Not needed if the extension can install/update it on its own, coc-rust-analyzer is one example. 242 243The are several LSP client implementations for vim or neovim: 244 245==== coc-rust-analyzer 246 2471. Install coc.nvim by following the instructions at 248 https://github.com/neoclide/coc.nvim[coc.nvim] 249 (Node.js required) 2502. Run `:CocInstall coc-rust-analyzer` to install 251 https://github.com/fannheyward/coc-rust-analyzer[coc-rust-analyzer], 252 this extension implements _most_ of the features supported in the VSCode extension: 253 * automatically install and upgrade stable/nightly releases 254 * same configurations as VSCode extension, `rust-analyzer.server.path`, `rust-analyzer.cargo.features` etc. 255 * same commands too, `rust-analyzer.analyzerStatus`, `rust-analyzer.ssr` etc. 256 * inlay hints for variables and method chaining, _Neovim Only_ 257 * semantic highlighting is not implemented yet 258 259Note: for code actions, use `coc-codeaction-cursor` and `coc-codeaction-selected`; `coc-codeaction` and `coc-codeaction-line` are unlikely to be useful. 260 261==== LanguageClient-neovim 262 2631. Install LanguageClient-neovim by following the instructions 264 https://github.com/autozimu/LanguageClient-neovim[here] 265 * The GitHub project wiki has extra tips on configuration 266 2672. Configure by adding this to your vim/neovim config file (replacing the existing Rust-specific line if it exists): 268+ 269[source,vim] 270---- 271let g:LanguageClient_serverCommands = { 272\ 'rust': ['rust-analyzer'], 273\ } 274---- 275 276==== YouCompleteMe 277 278Install YouCompleteMe by following the instructions 279 https://github.com/ycm-core/YouCompleteMe#installation[here]. 280 281rust-analyzer is the default in ycm, it should work out of the box. 282 283==== ALE 284 285To use the LSP server in https://github.com/dense-analysis/ale[ale]: 286 287[source,vim] 288---- 289let g:ale_linters = {'rust': ['analyzer']} 290---- 291 292==== nvim-lsp 293 294NeoVim 0.5 has built-in language server support. 295For a quick start configuration of rust-analyzer, use https://github.com/neovim/nvim-lspconfig#rust_analyzer[neovim/nvim-lspconfig]. 296Once `neovim/nvim-lspconfig` is installed, use `+lua require'lspconfig'.rust_analyzer.setup({})+` in your `init.vim`. 297 298You can also pass LSP settings to the server: 299 300[source,vim] 301---- 302lua << EOF 303local nvim_lsp = require'lspconfig' 304 305local on_attach = function(client) 306 require'completion'.on_attach(client) 307end 308 309nvim_lsp.rust_analyzer.setup({ 310 on_attach=on_attach, 311 settings = { 312 ["rust-analyzer"] = { 313 assist = { 314 importGranularity = "module", 315 importPrefix = "by_self", 316 }, 317 cargo = { 318 loadOutDirsFromCheck = true 319 }, 320 procMacro = { 321 enable = true 322 }, 323 } 324 } 325}) 326EOF 327---- 328 329See https://sharksforarms.dev/posts/neovim-rust/ for more tips on getting started. 330 331Check out https://github.com/simrat39/rust-tools.nvim for a batteries included rust-analyzer setup for neovim. 332 333==== vim-lsp 334 335vim-lsp is installed by following https://github.com/prabirshrestha/vim-lsp[the plugin instructions]. 336It can be as simple as adding this line to your `.vimrc`: 337 338[source,vim] 339---- 340Plug 'prabirshrestha/vim-lsp' 341---- 342 343Next you need to register the `rust-analyzer` binary. 344If it is available in `$PATH`, you may want to add this to your `.vimrc`: 345 346[source,vim] 347---- 348if executable('rust-analyzer') 349 au User lsp_setup call lsp#register_server({ 350 \ 'name': 'Rust Language Server', 351 \ 'cmd': {server_info->['rust-analyzer']}, 352 \ 'whitelist': ['rust'], 353 \ }) 354endif 355---- 356 357There is no dedicated UI for the server configuration, so you would need to send any options as a value of the `initialization_options` field, as described in the <<_configuration,Configuration>> section. 358Here is an example of how to enable the proc-macro support: 359 360[source,vim] 361---- 362if executable('rust-analyzer') 363 au User lsp_setup call lsp#register_server({ 364 \ 'name': 'Rust Language Server', 365 \ 'cmd': {server_info->['rust-analyzer']}, 366 \ 'whitelist': ['rust'], 367 \ 'initialization_options': { 368 \ 'cargo': { 369 \ 'loadOutDirsFromCheck': v:true, 370 \ }, 371 \ 'procMacro': { 372 \ 'enable': v:true, 373 \ }, 374 \ }, 375 \ }) 376endif 377---- 378 379=== Sublime Text 3 380 381Prerequisites: You have installed the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>>. 382 383You also need the `LSP` package. 384To install it: 385 3861. If you've never installed a Sublime Text package, install Package Control: 387 * Open the command palette (Win/Linux: `ctrl+shift+p`, Mac: `cmd+shift+p`) 388 * Type `Install Package Control`, press enter 3892. In the command palette, run `Package control: Install package`, and in the list that pops up, type `LSP` and press enter. 390 391Finally, 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. 392The latter means that rust-analyzer is enabled by default in Rust projects. 393 394If 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. 395 396If you get an error saying `No such file or directory: 'rust-analyzer'`, see the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>> section on installing the language server binary. 397 398=== GNOME Builder 399 400GNOME Builder 3.37.1 and newer has native `rust-analyzer` support. 401If the LSP binary is not available, GNOME Builder can install it when opening a Rust file. 402 403 404=== Eclipse IDE 405 406Support for Rust development in the Eclipse IDE is provided by link:https://github.com/eclipse/corrosion[Eclipse Corrosion]. 407If available in PATH or in some standard location, `rust-analyzer` is detected and powers editing of Rust files without further configuration. 408If `rust-analyzer` is not detected, Corrosion will prompt you for configuration of your Rust toolchain and language server with a link to the __Window > Preferences > Rust__ preference page; from here a button allows to download and configure `rust-analyzer`, but you can also reference another installation. 409You'll need to close and reopen all .rs and Cargo files, or to restart the IDE, for this change to take effect. 410 411=== Kate Text Editor 412 413Support for the language server protocol is built into Kate through the LSP plugin, which is included by default. 414It is preconfigured to use Rls for rust sources, but allows you to use rust-analyzer through a simple settings change. 415In the LSP Client settings of Kate, copy the content of the third tab "default parameters" to the second tab "server configuration". 416Then in the configuration replace: 417[source,json] 418---- 419 "rust": { 420 "command": ["rls"], 421 "rootIndicationFileNames": ["Cargo.lock", "Cargo.toml"], 422 "url": "https://github.com/rust-lang/rls", 423 "highlightingModeRegex": "^Rust$" 424 }, 425---- 426With 427[source,json] 428---- 429 "rust": { 430 "command": ["rust-analyzer"], 431 "rootIndicationFileNames": ["Cargo.lock", "Cargo.toml"], 432 "url": "https://github.com/rust-analyzer/rust-analyzer", 433 "highlightingModeRegex": "^Rust$" 434 }, 435---- 436Then click on apply, and restart the LSP server for your rust project. 437 438=== juCi++ 439 440https://gitlab.com/cppit/jucipp[juCi++] has built-in support for the language server protocol, and since version 1.7.0 offers installation of both Rust and rust-analyzer when opening a Rust file. 441 442== Troubleshooting 443 444Start with looking at the rust-analyzer version. 445Try **Rust Analyzer: Show RA Version** in VS Code and `rust-analyzer --version` in the command line. 446If the date is more than a week ago, it's better to update rust-analyzer version. 447 448The next thing to check would be panic messages in rust-analyzer's log. 449Log messages are printed to stderr, in VS Code you can see then in the `Output > Rust Analyzer Language Server` tab of the panel. 450To see more logs, set the `RA_LOG=info` environment variable, this can be done either by setting the environment variable manually or by using `rust-analyzer.server.extraEnv`, note that both of these approaches require the server to be restarted. 451 452To fully capture LSP messages between the editor and the server, set `"rust-analyzer.trace.server": "verbose"` config and check 453`Output > Rust Analyzer Language Server Trace`. 454 455The root cause for many "`nothing works`" problems is that rust-analyzer fails to understand the project structure. 456To debug that, first note the `rust-analyzer` section in the status bar. 457If it has an error icon and red, that's the problem (hover will have somewhat helpful error message). 458**Rust Analyzer: Status** prints dependency information for the current file. 459Finally, `RA_LOG=project_model=debug` enables verbose logs during project loading. 460 461If rust-analyzer outright crashes, try running `rust-analyzer analysis-stats /path/to/project/directory/` on the command line. 462This command type checks the whole project in batch mode bypassing LSP machinery. 463 464When filing issues, it is useful (but not necessary) to try to minimize examples. 465An ideal bug reproduction looks like this: 466 467```bash 468$ git clone https://github.com/username/repo.git && cd repo && git switch --detach commit-hash 469$ rust-analyzer --version 470rust-analyzer dd12184e4 2021-05-08 dev 471$ rust-analyzer analysis-stats . 472 473``` 474 475It is especially useful when the `repo` doesn't use external crates or the standard library. 476 477If you want to go as far as to modify the source code to debug the problem, be sure to take a look at the 478https://github.com/rust-analyzer/rust-analyzer/tree/master/docs/dev[dev docs]! 479 480== Configuration 481 482**Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/rust-analyzer/src/config.rs[config.rs] 483 484The <<_installation,Installation>> section contains details on configuration for some of the editors. 485In general `rust-analyzer` is configured via LSP messages, which means that it's up to the editor to decide on the exact format and location of configuration files. 486 487Some clients, such as <<vs-code,VS Code>> or <<coc-rust-analyzer,COC plugin in Vim>> provide `rust-analyzer` specific configuration UIs. Others may require you to know a bit more about the interaction with `rust-analyzer`. 488 489For the later category, it might help to know that the initial configuration is specified as a value of the `initializationOptions` field of the https://microsoft.github.io/language-server-protocol/specifications/specification-current/#initialize[`InitializeParams` message, in the LSP protocol]. 490The spec says that the field type is `any?`, but `rust-analyzer` is looking for a JSON object that is constructed using settings from the list below. 491Name of the setting, ignoring the `rust-analyzer.` prefix, is used as a path, and value of the setting becomes the JSON property value. 492 493For example, a very common configuration is to enable proc-macro support, can be achieved by sending this JSON: 494 495[source,json] 496---- 497{ 498 "cargo": { 499 "loadOutDirsFromCheck": true, 500 }, 501 "procMacro": { 502 "enable": true, 503 } 504} 505---- 506 507Please consult your editor's documentation to learn more about how to configure https://microsoft.github.io/language-server-protocol/[LSP servers]. 508 509To verify which configuration is actually used by `rust-analyzer`, set `RA_LOG` environment variable to `rust_analyzer=info` and look for config-related messages. 510Logs should show both the JSON that `rust-analyzer` sees as well as the updated config. 511 512This is the list of config options `rust-analyzer` supports: 513 514include::./generated_config.adoc[] 515 516== Non-Cargo Based Projects 517 518rust-analyzer does not require Cargo. 519However, 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: 520 521[source,TypeScript] 522---- 523interface JsonProject { 524 /// Path to the directory with *source code* of 525 /// sysroot crates. 526 /// 527 /// It should point to the directory where std, 528 /// core, and friends can be found: 529 /// 530 /// https://github.com/rust-lang/rust/tree/master/library. 531 /// 532 /// If provided, rust-analyzer automatically adds 533 /// dependencies on sysroot crates. Conversely, 534 /// if you omit this path, you can specify sysroot 535 /// dependencies yourself and, for example, have 536 /// several different "sysroots" in one graph of 537 /// crates. 538 sysroot_src?: string; 539 /// The set of crates comprising the current 540 /// project. Must include all transitive 541 /// dependencies as well as sysroot crate (libstd, 542 /// libcore and such). 543 crates: Crate[]; 544} 545 546interface Crate { 547 /// Optional crate name used for display purposes, 548 /// without affecting semantics. See the `deps` 549 /// key for semantically-significant crate names. 550 display_name?: string; 551 /// Path to the root module of the crate. 552 root_module: string; 553 /// Edition of the crate. 554 edition: "2015" | "2018" | "2021"; 555 /// Dependencies 556 deps: Dep[]; 557 /// Should this crate be treated as a member of 558 /// current "workspace". 559 /// 560 /// By default, inferred from the `root_module` 561 /// (members are the crates which reside inside 562 /// the directory opened in the editor). 563 /// 564 /// Set this to `false` for things like standard 565 /// library and 3rd party crates to enable 566 /// performance optimizations (rust-analyzer 567 /// assumes that non-member crates don't change). 568 is_workspace_member?: boolean; 569 /// Optionally specify the (super)set of `.rs` 570 /// files comprising this crate. 571 /// 572 /// By default, rust-analyzer assumes that only 573 /// files under `root_module.parent` can belong 574 /// to a crate. `include_dirs` are included 575 /// recursively, unless a subdirectory is in 576 /// `exclude_dirs`. 577 /// 578 /// Different crates can share the same `source`. 579 /// 580 /// If two crates share an `.rs` file in common, 581 /// they *must* have the same `source`. 582 /// rust-analyzer assumes that files from one 583 /// source can't refer to files in another source. 584 source?: { 585 include_dirs: string[], 586 exclude_dirs: string[], 587 }, 588 /// The set of cfgs activated for a given crate, like 589 /// `["unix", "feature=\"foo\"", "feature=\"bar\""]`. 590 cfg: string[]; 591 /// Target triple for this Crate. 592 /// 593 /// Used when running `rustc --print cfg` 594 /// to get target-specific cfgs. 595 target?: string; 596 /// Environment variables, used for 597 /// the `env!` macro 598 env: { [key: string]: string; }, 599 600 /// Whether the crate is a proc-macro crate. 601 is_proc_macro: boolean; 602 /// For proc-macro crates, path to compiled 603 /// proc-macro (.so file). 604 proc_macro_dylib_path?: string; 605} 606 607interface Dep { 608 /// Index of a crate in the `crates` array. 609 crate: number, 610 /// Name as should appear in the (implicit) 611 /// `extern crate name` declaration. 612 name: string, 613} 614---- 615 616This format is provisional and subject to change. 617Specifically, the `roots` setup will be different eventually. 618 619There are three ways to feed `rust-project.json` to rust-analyzer: 620 621* Place `rust-project.json` file at the root of the project, and rust-analyzer will discover it. 622* 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). 623* Specify `"rust-analyzer.linkedProjects": [ { "roots": [...], "crates": [...] }]` inline. 624 625Relative paths are interpreted relative to `rust-project.json` file location or (for inline JSON) relative to `rootUri`. 626 627See https://github.com/rust-analyzer/rust-project.json-example for a small example. 628 629You can set the `RA_LOG` environment variable to `rust_analyzer=info` to inspect how rust-analyzer handles config and project loading. 630 631Note that calls to `cargo check` are disabled when using `rust-project.json` by default, so compilation errors and warnings will no longer be sent to your LSP client. To enable these compilation errors you will need to specify explicitly what command rust-analyzer should run to perform the checks using the `checkOnSave.overrideCommand` configuration. As an example, the following configuration explicitly sets `cargo check` as the `checkOnSave` command. 632 633[source,json] 634---- 635{ "rust-analyzer.checkOnSave.overrideCommand": ["cargo", "check", "--message-format=json"] } 636---- 637 638The `checkOnSave.overrideCommand` requires the command specified to output json error messages for rust-analyzer to consume. The `--message-format=json` flag does this for `cargo check` so whichever command you use must also output errors in this format. See the <<Configuration>> section for more information. 639 640== Security 641 642At the moment, rust-analyzer assumes that all code is trusted. 643Here is a **non-exhaustive** list of ways to make rust-analyzer execute arbitrary code: 644 645* proc macros and build scripts are executed by default 646* `.cargo/config` can override `rustc` with an arbitrary executable 647* `rust-toolchain.toml` can override `rustc` with an arbitrary executable 648* VS Code plugin reads configuration from project directory, and that can be used to override paths to various executables, like `rustfmt` or `rust-analyzer` itself. 649* rust-analyzer's syntax trees library uses a lot of `unsafe` and hasn't been properly audited for memory safety. 650 651== Privacy 652 653The LSP server performs no network access in itself, but runs `cargo metadata` which will update or download the crate registry and the source code of the project dependencies. 654If enabled (the default), build scripts and procedural macros can do anything. 655 656The Code extension automatically connects to GitHub to download updated LSP binaries and, if the nightly channel is selected, to perform update checks using the GitHub API. For `rust-analyzer` developers, using `cargo xtask release` uses the same API to put together the release notes. 657 658Any other editor plugins are not under the control of the `rust-analyzer` developers. For any privacy concerns, you should check with their respective developers. 659 660== Features 661 662include::./generated_features.adoc[] 663 664== Assists (Code Actions) 665 666Assists, or code actions, are small local refactorings, available in a particular context. 667They are usually triggered by a shortcut or by clicking a light bulb icon in the editor. 668Cursor position or selection is signified by `┃` character. 669 670include::./generated_assists.adoc[] 671 672== Diagnostics 673 674While most errors and warnings provided by rust-analyzer come from the `cargo check` integration, there's a growing number of diagnostics implemented using rust-analyzer's own analysis. 675Some of these diagnostics don't respect `\#[allow]` or `\#[deny]` attributes yet, but can be turned off using the `rust-analyzer.diagnostics.enable`, `rust-analyzer.diagnostics.enableExperimental` or `rust-analyzer.diagnostics.disabled` settings. 676 677include::./generated_diagnostic.adoc[] 678 679== Editor Features 680=== VS Code 681 682==== Color configurations 683 684It is possible to change the foreground/background color of inlay hints. 685Just add this to your `settings.json`: 686 687[source,jsonc] 688---- 689{ 690 "workbench.colorCustomizations": { 691 // Name of the theme you are currently using 692 "[Default Dark+]": { 693 "rust_analyzer.inlayHints.foreground": "#868686f0", 694 "rust_analyzer.inlayHints.background": "#3d3d3d48", 695 696 // Overrides for specific kinds of inlay hints 697 "rust_analyzer.inlayHints.foreground.typeHints": "#fdb6fdf0", 698 "rust_analyzer.inlayHints.foreground.paramHints": "#fdb6fdf0", 699 "rust_analyzer.inlayHints.background.chainingHints": "#6b0c0c81" 700 } 701 } 702} 703---- 704 705==== Semantic style customizations 706 707You can customize the look of different semantic elements in the source code. 708For example, mutable bindings are underlined by default and you can override this behavior by adding the following section to your `settings.json`: 709 710[source,jsonc] 711---- 712{ 713 "editor.semanticTokenColorCustomizations": { 714 "rules": { 715 "*.mutable": { 716 "fontStyle": "", // underline is the default 717 }, 718 } 719 }, 720} 721---- 722 723Most themes doesn't support styling unsafe operations differently yet. You can fix this by adding overrides for the rules `operator.unsafe`, `function.unsafe`, and `method.unsafe`: 724 725[source,jsonc] 726---- 727{ 728 "editor.semanticTokenColorCustomizations": { 729 "rules": { 730 "operator.unsafe": "#ff6600", 731 "function.unsafe": "#ff6600" 732 "method.unsafe": "#ff6600" 733 } 734 }, 735} 736---- 737 738In addition to the top-level rules you can specify overrides for specific themes. For example, if you wanted to use a darker text color on a specific light theme, you might write: 739 740[source,jsonc] 741---- 742{ 743 "editor.semanticTokenColorCustomizations": { 744 "rules": { 745 "operator.unsafe": "#ff6600" 746 }, 747 "[Ayu Light]": { 748 "rules": { 749 "operator.unsafe": "#572300" 750 } 751 } 752 }, 753} 754---- 755 756Make sure you include the brackets around the theme name. For example, use `"[Ayu Light]"` to customize the theme Ayu Light. 757 758==== Special `when` clause context for keybindings. 759You may use `inRustProject` context to configure keybindings for rust projects only. 760For example: 761 762[source,json] 763---- 764{ 765 "key": "ctrl+i", 766 "command": "rust-analyzer.toggleInlayHints", 767 "when": "inRustProject" 768} 769---- 770More about `when` clause contexts https://code.visualstudio.com/docs/getstarted/keybindings#_when-clause-contexts[here]. 771 772==== Setting runnable environment variables 773You can use "rust-analyzer.runnableEnv" setting to define runnable environment-specific substitution variables. 774The simplest way for all runnables in a bunch: 775```jsonc 776"rust-analyzer.runnableEnv": { 777 "RUN_SLOW_TESTS": "1" 778} 779``` 780 781Or it is possible to specify vars more granularly: 782```jsonc 783"rust-analyzer.runnableEnv": [ 784 { 785 // "mask": null, // null mask means that this rule will be applied for all runnables 786 env: { 787 "APP_ID": "1", 788 "APP_DATA": "asdf" 789 } 790 }, 791 { 792 "mask": "test_name", 793 "env": { 794 "APP_ID": "2", // overwrites only APP_ID 795 } 796 } 797] 798``` 799 800You can use any valid regular expression as a mask. 801Also 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. 802 803==== Compiler feedback from external commands 804 805Instead 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. 806 807To do this you need to create a new https://code.visualstudio.com/docs/editor/tasks[VS Code Task] and set `rust-analyzer.checkOnSave.enable: false` in preferences. 808 809For example, if you want to run https://crates.io/crates/cargo-watch[`cargo watch`] instead, you might add the following to `.vscode/tasks.json`: 810 811```json 812{ 813 "label": "Watch", 814 "group": "build", 815 "type": "shell", 816 "command": "cargo watch", 817 "problemMatcher": "$rustc-watch", 818 "isBackground": true 819} 820``` 821