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