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