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