fork/rust

git clone https://git.julia.blue/fork/rust

borsAuto merge of #103046 - JanBeh:PR_clarify_cmp_terminology, r=workingjubilee3bcad65fbf6

master
40.0 KiB1003 linesraw
1= User Manual
2:toc: preamble
3:sectanchors:
4:page-layout: post
5:icons: font
6:source-highlighter: rouge
7:experimental:
8
9////
10IMPORTANT: the master copy of this document lives in the https://github.com/rust-lang/rust-analyzer repository
11////
12
13At its core, rust-analyzer is a *library* for semantic analysis of Rust code as it changes over time.
14This manual focuses on a specific usage of the library -- running it as part of a server that implements the
15https://microsoft.github.io/language-server-protocol/[Language Server Protocol] (LSP).
16The LSP allows various code editors, like VS Code, Emacs or Vim, to implement semantic features like completion or goto definition by talking to an external language server process.
17
18[TIP]
19====
20[.lead]
21To improve this document, send a pull request: +
22https://github.com/rust-lang/rust-analyzer/blob/master/docs/user/manual.adoc[https://github.com/rust-analyzer/.../manual.adoc]
23
24The manual is written in https://asciidoc.org[AsciiDoc] and includes some extra files which are generated from the source code. Run `cargo test` and `cargo test -p xtask` to create these and then `asciidoctor manual.adoc` to create an HTML copy.
25====
26
27If you have questions about using rust-analyzer, please ask them in the https://users.rust-lang.org/c/ide/14["`IDEs and Editors`"] topic of Rust users forum.
28
29== Installation
30
31In theory, one should be able to just install the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>> and have it automatically work with any editor.
32We are not there yet, so some editor specific setup is required.
33
34Additionally, rust-analyzer needs the sources of the standard library.
35If the source code is not present, rust-analyzer will attempt to install it automatically.
36
37To add the sources manually, run the following command:
38
39```bash
40$ rustup component add rust-src
41```
42
43=== Toolchain
44
45Only the latest stable standard library source is officially supported for use with rust-analyzer.
46If you are using an older toolchain or have an override set, rust-analyzer may fail to understand the Rust source.
47You will either need to update your toolchain or use an older version of rust-analyzer that is compatible with your toolchain.
48
49If 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`.
50For 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
59This is the best supported editor at the moment.
60The rust-analyzer plugin for VS Code is maintained
61https://github.com/rust-lang/rust-analyzer/tree/master/editors/code[in tree].
62
63You can install the latest release of the plugin from
64https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer[the marketplace].
65
66Note that the plugin may cause conflicts with the
67https://marketplace.visualstudio.com/items?itemName=rust-lang.rust[previous official Rust plugin].
68The latter is no longer maintained and should be uninstalled.
69
70The server binary is stored in the extension install directory, which starts with `rust-lang.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
77As an exception, on NixOS, the extension makes a copy of the server and stores it under `~/.config/Code/User/globalStorage/rust-lang.rust-analyzer`.
78
79Note that we only support the two most recent versions of VS Code.
80
81==== Updates
82
83The extension will be updated automatically as new versions become available.
84It will ask your permission to download the matching language server version binary if needed.
85
86===== Nightly
87
88We ship nightly releases for VS Code.
89To help us out by testing the newest code, you can enable pre-release versions in the Code extension page.
90
91==== Manual installation
92
93Alternatively, download a VSIX corresponding to your platform from the
94https://github.com/rust-lang/rust-analyzer/releases[releases] page.
95
96Install the extension with the `Extensions: Install from VSIX` command within VS Code, or from the command line via:
97[source]
98----
99$ code --install-extension /path/to/rust-analyzer.vsix
100----
101
102If you are running an unsupported platform, you can install `rust-analyzer-no-server.vsix` and compile or obtain a server binary.
103Copy the server anywhere, then add the path to your settings.json, for example:
104[source,json]
105----
106{ "rust-analyzer.server.path": "~/.local/bin/rust-analyzer-linux" }
107----
108
109==== Building From Source
110
111Both the server and the Code plugin can be installed from source:
112
113[source]
114----
115$ git clone https://github.com/rust-lang/rust-analyzer.git && cd rust-analyzer
116$ cargo xtask install
117----
118
119You'll need Cargo, nodejs (matching a supported version of VS Code) and npm for this.
120
121Note that installing via `xtask install` does not work for VS Code Remote, instead you'll need to install the `.vsix` manually.
122
123If you're not using Code, you can compile and install only the LSP server:
124
125[source]
126----
127$ cargo xtask install --server
128----
129
130Make sure that `.cargo/bin` is in `$PATH` and precedes paths where `rust-analyzer` may also be installed.
131Specifically, `rustup` includes a proxy called `rust-analyzer`, which can cause problems if you're planning to use a source build or even a downloaded binary.
132
133=== rust-analyzer Language Server Binary
134
135Other editors generally require the `rust-analyzer` binary to be in `$PATH`.
136You can download pre-built binaries from the https://github.com/rust-lang/rust-analyzer/releases[releases] page.
137You 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`.
138
139On Linux to install the `rust-analyzer` binary into `~/.local/bin`, these commands should work:
140
141[source,bash]
142----
143$ mkdir -p ~/.local/bin
144$ 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
145$ chmod +x ~/.local/bin/rust-analyzer
146----
147
148Make sure that `~/.local/bin` is listed in the `$PATH` variable and use the appropriate URL if you're not on a `x86-64` system.
149
150You don't have to use `~/.local/bin`, any other path like `~/.cargo/bin` or `/usr/local/bin` will work just as well.
151
152Alternatively, you can install it from source using the command below.
153You'll need the latest stable version of the Rust toolchain.
154
155[source,bash]
156----
157$ git clone https://github.com/rust-lang/rust-analyzer.git && cd rust-analyzer
158$ cargo xtask install --server
159----
160
161If 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].
162On Unix, running the editor from a shell or changing the `.desktop` file to set the environment should help.
163
164==== rustup
165
166`rust-analyzer` is available in `rustup`:
167
168[source,bash]
169----
170$ rustup component add rust-analyzer
171----
172
173==== Arch Linux
174
175The `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
180Install 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
194If 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
204The `rust-analyzer` binary can be installed via https://brew.sh/[Homebrew].
205
206[source,bash]
207----
208$ brew install rust-analyzer
209----
210
211=== VS Code or VSCodium in Flatpak
212
213Setting up `rust-analyzer` with a Flatpak version of Code is not trivial because of the Flatpak sandbox.
214While the sandbox can be disabled for some directories, `/usr/bin` will always be mounted under `/run/host/usr/bin`.
215This prevents access to the system's C compiler, a system-wide installation of Rust, or any other libraries you might want to link to.
216Some compilers and libraries can be acquired as Flatpak SDKs, such as `org.freedesktop.Sdk.Extension.rust-stable` or `org.freedesktop.Sdk.Extension.llvm15`.
217
218If you use a Flatpak SDK for Rust, there should be no extra steps necessary.
219
220If you want to use Flatpak in combination with `rustup`, the following steps might help:
221
222 - both Rust and `rustup` have to be installed using https://rustup.rs. Distro packages _will not_ work.
223 - you need to launch Code, open a terminal and run `echo $PATH`
224 - using https://flathub.org/apps/details/com.github.tchx84.Flatseal[Flatseal], you must add an environment variable called `PATH`.
225   Set its value to the output from above, appending `:~/.cargo/bin`, where `~` is the path to your home directory.
226   You must replace `~`, as it won't be expanded otherwise.
227 - while Flatseal is open, you must enable access to "All user files"
228
229A C compiler should already be available via `org.freedesktop.Sdk`.
230Any other tools or libraries you will need to acquire  from Flatpak.
231
232=== Emacs
233
234Prerequisites: You have installed the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>>.
235
236To use `rust-analyzer`, you need to install and enable one of the two popular LSP client implementations for Emacs, https://github.com/joaotavora/eglot[Eglot] or https://github.com/emacs-lsp/lsp-mode[LSP Mode]. Both enable `rust-analyzer` by default in rust buffers if it is available.
237
238==== Eglot
239
240Eglot is the more minimalistic and lightweight LSP client for Emacs, integrates well with existing Emacs functionality and will be built into Emacs starting from release 29.
241
242After installing Eglot, e.g. via `M-x package-install` (not needed from Emacs 29), you can enable it via the `M-x eglot` command or load it automatically in `rust-mode` via
243
244[source,emacs-lisp]
245----
246(add-hook 'rust-mode-hook 'eglot-ensure)
247----
248
249For more detailed instructions and options see the https://joaotavora.github.io/eglot[Eglot manual] (also available from Emacs via `M-x info`) and the
250https://github.com/joaotavora/eglot/blob/master/README.md[Eglot readme].
251
252Eglot does not support the rust-analyzer extensions to the language-server protocol and does not aim to do so in the future. The https://github.com/nemethf/eglot-x#rust-analyzer-extensions[eglot-x] package adds experimental support for those LSP extensions.
253
254==== LSP Mode
255
256LSP-mode is the original LSP-client for emacs. Compared to Eglot it has a larger codebase and supports more features, like LSP protocol extensions.
257With extension packages like https://github.com/emacs-lsp/lsp-mode[LSP UI] it offers a lot of visual eyecandy.
258Further it integrates well with https://github.com/emacs-lsp/dap-mode[DAP mode] for support of the Debug Adapter Protocol.
259
260You can install LSP-mode via `M-x package-install` and then run it via the `M-x lsp` command or load it automatically in rust buffers with
261
262[source,emacs-lisp]
263----
264(add-hook 'rust-mode-hook 'lsp-deferred)
265----
266
267For more information on how to set up LSP mode and its extension package see the instructions in the https://emacs-lsp.github.io/lsp-mode/page/installation[LSP mode manual].
268Also see the https://emacs-lsp.github.io/lsp-mode/page/lsp-rust-analyzer/[rust-analyzer section] for `rust-analyzer` specific options and commands, which you can optionally bind to keys.
269
270Note the excellent https://robert.kra.hn/posts/2021-02-07_rust-with-emacs/[guide] from https://github.com/rksm[@rksm] on how to set-up Emacs for Rust development with LSP mode and several other packages.
271
272=== Vim/Neovim
273
274Prerequisites: You have installed the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>>.
275Not needed if the extension can install/update it on its own, coc-rust-analyzer is one example.
276
277There are several LSP client implementations for Vim or Neovim:
278
279==== coc-rust-analyzer
280
2811. Install coc.nvim by following the instructions at
282   https://github.com/neoclide/coc.nvim[coc.nvim]
283   (Node.js required)
2842. Run `:CocInstall coc-rust-analyzer` to install
285   https://github.com/fannheyward/coc-rust-analyzer[coc-rust-analyzer],
286   this extension implements _most_ of the features supported in the VSCode extension:
287   * automatically install and upgrade stable/nightly releases
288   * same configurations as VSCode extension, `rust-analyzer.server.path`, `rust-analyzer.cargo.features` etc.
289   * same commands too, `rust-analyzer.analyzerStatus`, `rust-analyzer.ssr` etc.
290   * inlay hints for variables and method chaining, _Neovim Only_
291
292Note: for code actions, use `coc-codeaction-cursor` and `coc-codeaction-selected`; `coc-codeaction` and `coc-codeaction-line` are unlikely to be useful.
293
294==== LanguageClient-neovim
295
2961. Install LanguageClient-neovim by following the instructions
297   https://github.com/autozimu/LanguageClient-neovim[here]
298   * The GitHub project wiki has extra tips on configuration
299
3002. Configure by adding this to your Vim/Neovim config file (replacing the existing Rust-specific line if it exists):
301+
302[source,vim]
303----
304let g:LanguageClient_serverCommands = {
305\ 'rust': ['rust-analyzer'],
306\ }
307----
308
309==== YouCompleteMe
310
311Install YouCompleteMe by following the instructions
312  https://github.com/ycm-core/YouCompleteMe#installation[here].
313
314rust-analyzer is the default in ycm, it should work out of the box.
315
316==== ALE
317
318To use the LSP server in https://github.com/dense-analysis/ale[ale]:
319
320[source,vim]
321----
322let g:ale_linters = {'rust': ['analyzer']}
323----
324
325==== nvim-lsp
326
327Neovim 0.5 has built-in language server support.
328For a quick start configuration of rust-analyzer, use https://github.com/neovim/nvim-lspconfig#rust_analyzer[neovim/nvim-lspconfig].
329Once `neovim/nvim-lspconfig` is installed, use `+lua require'lspconfig'.rust_analyzer.setup({})+` in your `init.vim`.
330
331You can also pass LSP settings to the server:
332
333[source,vim]
334----
335lua << EOF
336local nvim_lsp = require'lspconfig'
337
338local on_attach = function(client)
339    require'completion'.on_attach(client)
340end
341
342nvim_lsp.rust_analyzer.setup({
343    on_attach=on_attach,
344    settings = {
345        ["rust-analyzer"] = {
346            imports = {
347                granularity = {
348                    group = "module",
349                },
350                prefix = "self",
351            },
352            cargo = {
353                buildScripts = {
354                    enable = true,
355                },
356            },
357            procMacro = {
358                enable = true
359            },
360        }
361    }
362})
363EOF
364----
365
366See https://sharksforarms.dev/posts/neovim-rust/ for more tips on getting started.
367
368Check out https://github.com/simrat39/rust-tools.nvim for a batteries included rust-analyzer setup for Neovim.
369
370==== vim-lsp
371
372vim-lsp is installed by following https://github.com/prabirshrestha/vim-lsp[the plugin instructions].
373It can be as simple as adding this line to your `.vimrc`:
374
375[source,vim]
376----
377Plug 'prabirshrestha/vim-lsp'
378----
379
380Next you need to register the `rust-analyzer` binary.
381If it is available in `$PATH`, you may want to add this to your `.vimrc`:
382
383[source,vim]
384----
385if executable('rust-analyzer')
386  au User lsp_setup call lsp#register_server({
387        \   'name': 'Rust Language Server',
388        \   'cmd': {server_info->['rust-analyzer']},
389        \   'whitelist': ['rust'],
390        \ })
391endif
392----
393
394There 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.
395Here is an example of how to enable the proc-macro support:
396
397[source,vim]
398----
399if executable('rust-analyzer')
400  au User lsp_setup call lsp#register_server({
401        \   'name': 'Rust Language Server',
402        \   'cmd': {server_info->['rust-analyzer']},
403        \   'whitelist': ['rust'],
404        \   'initialization_options': {
405        \     'cargo': {
406        \       'buildScripts': {
407        \         'enable': v:true,
408        \       },
409        \     },
410        \     'procMacro': {
411        \       'enable': v:true,
412        \     },
413        \   },
414        \ })
415endif
416----
417
418=== Sublime Text
419
420==== Sublime Text 4:
421* Follow the instructions in link:https://github.com/sublimelsp/LSP-rust-analyzer[LSP-rust-analyzer].
422
423NOTE: Install link:https://packagecontrol.io/packages/LSP-file-watcher-chokidar[LSP-file-watcher-chokidar] to enable file watching (`workspace/didChangeWatchedFiles`).
424
425==== Sublime Text 3:
426* Install the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>>.
427* Install the link:https://packagecontrol.io/packages/LSP[LSP package].
428* From the command palette, run `LSP: Enable Language Server Globally` and select `rust-analyzer`.
429
430If 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.
431
432If 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.
433
434=== GNOME Builder
435
436GNOME Builder 3.37.1 and newer has native `rust-analyzer` support.
437If the LSP binary is not available, GNOME Builder can install it when opening a Rust file.
438
439
440=== Eclipse IDE
441
442Support for Rust development in the Eclipse IDE is provided by link:https://github.com/eclipse/corrosion[Eclipse Corrosion].
443If available in PATH or in some standard location, `rust-analyzer` is detected and powers editing of Rust files without further configuration.
444If `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.
445You'll need to close and reopen all .rs and Cargo files, or to restart the IDE, for this change to take effect.
446
447=== Kate Text Editor
448
449Support for the language server protocol is built into Kate through the LSP plugin, which is included by default.
450It is preconfigured to use rust-analyzer for Rust sources since Kate 21.12.
451
452To change rust-analyzer config options, start from the following example and put it into Kate's "User Server Settings" tab (located under the LSP Client settings):
453[source,json]
454----
455{
456    "servers": {
457        "rust": {
458            "initializationOptions": {
459                "cachePriming": {
460                    "enable": false
461                },
462                "check": {
463                    "allTargets": false
464                },
465                "checkOnSave": false
466            }
467        }
468    }
469}
470----
471Then click on apply, and restart the LSP server for your rust project.
472
473=== juCi++
474
475https://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.
476
477=== Kakoune
478
479https://kakoune.org/[Kakoune] supports LSP with the help of https://github.com/kak-lsp/kak-lsp[`kak-lsp`].
480Follow the https://github.com/kak-lsp/kak-lsp#installation[instructions] to install `kak-lsp`.
481To 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).
482
483Finally, you need to configure Kakoune to talk to `kak-lsp` (see https://github.com/kak-lsp/kak-lsp#usage[Usage section]).
484A basic configuration will only get you LSP but you can also activate inlay diagnostics and auto-formatting on save.
485The following might help you get all of this.
486
487[source,txt]
488----
489eval %sh{kak-lsp --kakoune -s $kak_session}  # Not needed if you load it with plug.kak.
490hook global WinSetOption filetype=rust %{
491    # Enable LSP
492    lsp-enable-window
493
494    # Auto-formatting on save
495    hook window BufWritePre .* lsp-formatting-sync
496
497    # Configure inlay hints (only on save)
498    hook window -group rust-inlay-hints BufWritePost .* rust-analyzer-inlay-hints
499    hook -once -always window WinSetOption filetype=.* %{
500        remove-hooks window rust-inlay-hints
501    }
502}
503----
504
505=== Helix
506
507https://docs.helix-editor.com/[Helix] supports LSP by default.
508However, it won't install `rust-analyzer` automatically.
509You can follow instructions for installing <<rust-analyzer-language-server-binary,`rust-analyzer` binary>>.
510
511=== Visual Studio 2022
512
513There are multiple rust-analyzer extensions for Visual Studio 2022 on Windows:
514
515==== rust-analyzer.vs
516
517(License: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International)
518
519https://marketplace.visualstudio.com/items?itemName=kitamstudios.RustAnalyzer[Visual Studio Marketplace]
520
521https://github.com/kitamstudios/rust-analyzer/[GitHub]
522
523Support for Rust development in the Visual Studio IDE is enabled by the link:https://marketplace.visualstudio.com/items?itemName=kitamstudios.RustAnalyzer[rust-analyzer] package. Either click on the download link or install from IDE's extension manager.
524For now link:https://visualstudio.microsoft.com/downloads/[Visual Studio 2022] is required. All editions are supported viz. Community, Professional & Enterprise.
525The package aims to provide 0-friction installation and therefore comes loaded with most things required including rust-analyzer binary. If anything it needs is missing, appropriate errors / warnings will guide the user. E.g. cargo.exe needs to be in path and the package will tell you as much.
526This package is under rapid active development. So if you encounter any issues please file it at link:https://github.com/kitamstudios/rust-analyzer/[rust-analyzer.vs].
527
528==== VS_RustAnalyzer
529
530(License: GPL)
531
532https://marketplace.visualstudio.com/items?itemName=cchharris.vsrustanalyzer[Visual Studio Marketplace]
533
534https://github.com/cchharris/VS-RustAnalyzer[GitHub]
535
536==== SourceGear Rust
537
538(License: closed source)
539
540https://marketplace.visualstudio.com/items?itemName=SourceGear.SourceGearRust[Visual Studio Marketplace]
541
542https://github.com/sourcegear/rust-vs-extension[GitHub (docs, issues, discussions)]
543
544* Free (no-cost)
545* Supports all editions of Visual Studio 2022 on Windows: Community, Professional, or Enterprise
546
547=== Lapce
548
549https://lapce.dev/[Lapce] has a Rust plugin which you can install directly.
550Unfortunately, it downloads an old version of `rust-analyzer`, but you can set the server path under Settings.
551
552=== Crates
553
554There is a package named `ra_ap_rust_analyzer` available on https://crates.io/crates/ra_ap_rust-analyzer[crates.io], for someone who wants to use it programmatically.
555
556For more details, see https://github.com/rust-lang/rust-analyzer/blob/master/.github/workflows/publish.yml[the publish workflow].
557
558== Troubleshooting
559
560Start with looking at the rust-analyzer version.
561Try **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.
562If the date is more than a week ago, it's better to update rust-analyzer version.
563
564The next thing to check would be panic messages in rust-analyzer's log.
565Log messages are printed to stderr, in VS Code you can see them in the `Output > Rust Analyzer Language Server` tab of the panel.
566To 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.
567
568To fully capture LSP messages between the editor and the server, set `"rust-analyzer.trace.server": "verbose"` config and check
569`Output > Rust Analyzer Language Server Trace`.
570
571The root cause for many "`nothing works`" problems is that rust-analyzer fails to understand the project structure.
572To debug that, first note the `rust-analyzer` section in the status bar.
573If it has an error icon and red, that's the problem (hover will have somewhat helpful error message).
574**rust-analyzer: Status** prints dependency information for the current file.
575Finally, `RA_LOG=project_model=debug` enables verbose logs during project loading.
576
577If rust-analyzer outright crashes, try running `rust-analyzer analysis-stats /path/to/project/directory/` on the command line.
578This command type checks the whole project in batch mode bypassing LSP machinery.
579
580When filing issues, it is useful (but not necessary) to try to minimize examples.
581An ideal bug reproduction looks like this:
582
583```bash
584$ git clone https://github.com/username/repo.git && cd repo && git switch --detach commit-hash
585$ rust-analyzer --version
586rust-analyzer dd12184e4 2021-05-08 dev
587$ rust-analyzer analysis-stats .
588💀 💀 💀
589```
590
591It is especially useful when the `repo` doesn't use external crates or the standard library.
592
593If you want to go as far as to modify the source code to debug the problem, be sure to take a look at the
594https://github.com/rust-lang/rust-analyzer/tree/master/docs/dev[dev docs]!
595
596== Configuration
597
598**Source:** https://github.com/rust-lang/rust-analyzer/blob/master/crates/rust-analyzer/src/config.rs[config.rs]
599
600The <<_installation,Installation>> section contains details on configuration for some of the editors.
601In 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.
602
603Some 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`.
604
605For 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].
606The 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.
607Name of the setting, ignoring the `rust-analyzer.` prefix, is used as a path, and value of the setting becomes the JSON property value.
608
609For example, a very common configuration is to enable proc-macro support, can be achieved by sending this JSON:
610
611[source,json]
612----
613{
614  "cargo": {
615    "buildScripts": {
616      "enable": true,
617    },
618  },
619  "procMacro": {
620    "enable": true,
621  }
622}
623----
624
625Please consult your editor's documentation to learn more about how to configure https://microsoft.github.io/language-server-protocol/[LSP servers].
626
627To verify which configuration is actually used by `rust-analyzer`, set `RA_LOG` environment variable to `rust_analyzer=info` and look for config-related messages.
628Logs should show both the JSON that `rust-analyzer` sees as well as the updated config.
629
630This is the list of config options `rust-analyzer` supports:
631
632include::./generated_config.adoc[]
633
634== Non-Cargo Based Projects
635
636rust-analyzer does not require Cargo.
637However, 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:
638
639[source,TypeScript]
640----
641interface JsonProject {
642    /// Path to the sysroot directory.
643    ///
644    /// The sysroot is where rustc looks for the
645    /// crates that are built-in to rust, such as
646    /// std.
647    ///
648    /// https://doc.rust-lang.org/rustc/command-line-arguments.html#--sysroot-override-the-system-root
649    ///
650    /// To see the current value of sysroot, you
651    /// can query rustc:
652    ///
653    /// ```
654    /// $ rustc --print sysroot
655    /// /Users/yourname/.rustup/toolchains/stable-x86_64-apple-darwin
656    /// ```
657    sysroot?: string;
658    /// Path to the directory with *source code* of
659    /// sysroot crates.
660    ///
661    /// By default, this is `lib/rustlib/src/rust/library`
662    /// relative to the sysroot.
663    ///
664    /// It should point to the directory where std,
665    /// core, and friends can be found:
666    ///
667    /// https://github.com/rust-lang/rust/tree/master/library.
668    ///
669    /// If provided, rust-analyzer automatically adds
670    /// dependencies on sysroot crates. Conversely,
671    /// if you omit this path, you can specify sysroot
672    /// dependencies yourself and, for example, have
673    /// several different "sysroots" in one graph of
674    /// crates.
675    sysroot_src?: string;
676    /// The set of crates comprising the current
677    /// project. Must include all transitive
678    /// dependencies as well as sysroot crate (libstd,
679    /// libcore and such).
680    crates: Crate[];
681}
682
683interface Crate {
684    /// Optional crate name used for display purposes,
685    /// without affecting semantics. See the `deps`
686    /// key for semantically-significant crate names.
687    display_name?: string;
688    /// Path to the root module of the crate.
689    root_module: string;
690    /// Edition of the crate.
691    edition: "2015" | "2018" | "2021";
692    /// Dependencies
693    deps: Dep[];
694    /// Should this crate be treated as a member of
695    /// current "workspace".
696    ///
697    /// By default, inferred from the `root_module`
698    /// (members are the crates which reside inside
699    /// the directory opened in the editor).
700    ///
701    /// Set this to `false` for things like standard
702    /// library and 3rd party crates to enable
703    /// performance optimizations (rust-analyzer
704    /// assumes that non-member crates don't change).
705    is_workspace_member?: boolean;
706    /// Optionally specify the (super)set of `.rs`
707    /// files comprising this crate.
708    ///
709    /// By default, rust-analyzer assumes that only
710    /// files under `root_module.parent` can belong
711    /// to a crate. `include_dirs` are included
712    /// recursively, unless a subdirectory is in
713    /// `exclude_dirs`.
714    ///
715    /// Different crates can share the same `source`.
716    ///
717    /// If two crates share an `.rs` file in common,
718    /// they *must* have the same `source`.
719    /// rust-analyzer assumes that files from one
720    /// source can't refer to files in another source.
721    source?: {
722        include_dirs: string[],
723        exclude_dirs: string[],
724    },
725    /// The set of cfgs activated for a given crate, like
726    /// `["unix", "feature=\"foo\"", "feature=\"bar\""]`.
727    cfg: string[];
728    /// Target triple for this Crate.
729    ///
730    /// Used when running `rustc --print cfg`
731    /// to get target-specific cfgs.
732    target?: string;
733    /// Environment variables, used for
734    /// the `env!` macro
735    env: { [key: string]: string; },
736
737    /// Whether the crate is a proc-macro crate.
738    is_proc_macro: boolean;
739    /// For proc-macro crates, path to compiled
740    /// proc-macro (.so file).
741    proc_macro_dylib_path?: string;
742}
743
744interface Dep {
745    /// Index of a crate in the `crates` array.
746    crate: number,
747    /// Name as should appear in the (implicit)
748    /// `extern crate name` declaration.
749    name: string,
750}
751----
752
753This format is provisional and subject to change.
754Specifically, the `roots` setup will be different eventually.
755
756There are three ways to feed `rust-project.json` to rust-analyzer:
757
758* Place `rust-project.json` file at the root of the project, and rust-analyzer will discover it.
759* 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).
760* Specify `"rust-analyzer.linkedProjects": [ { "roots": [...], "crates": [...] }]` inline.
761
762Relative paths are interpreted relative to `rust-project.json` file location or (for inline JSON) relative to `rootUri`.
763
764See https://github.com/rust-analyzer/rust-project.json-example for a small example.
765
766You can set the `RA_LOG` environment variable to `rust_analyzer=info` to inspect how rust-analyzer handles config and project loading.
767
768Note 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.
769To enable these compilation errors you will need to specify explicitly what command rust-analyzer should run to perform the checks using the `rust-analyzer.check.overrideCommand` configuration.
770As an example, the following configuration explicitly sets `cargo check` as the `check` command.
771
772[source,json]
773----
774{ "rust-analyzer.check.overrideCommand": ["cargo", "check", "--message-format=json"] }
775----
776
777`check.overrideCommand` requires the command specified to output json error messages for rust-analyzer to consume.
778The `--message-format=json` flag does this for `cargo check` so whichever command you use must also output errors in this format.
779See the <<Configuration>> section for more information.
780
781== Security
782
783At the moment, rust-analyzer assumes that all code is trusted.
784Here is a **non-exhaustive** list of ways to make rust-analyzer execute arbitrary code:
785
786* proc macros and build scripts are executed by default
787* `.cargo/config` can override `rustc` with an arbitrary executable
788* `rust-toolchain.toml` can override `rustc` with an arbitrary executable
789* 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.
790* rust-analyzer's syntax trees library uses a lot of `unsafe` and hasn't been properly audited for memory safety.
791
792== Privacy
793
794The 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.
795If enabled (the default), build scripts and procedural macros can do anything.
796
797The Code extension does not access the network.
798
799Any other editor plugins are not under the control of the `rust-analyzer` developers. For any privacy concerns, you should check with their respective developers.
800
801For `rust-analyzer` developers, `cargo xtask release` uses the GitHub API to put together the release notes.
802
803== Features
804
805include::./generated_features.adoc[]
806
807== Assists (Code Actions)
808
809Assists, or code actions, are small local refactorings, available in a particular context.
810They are usually triggered by a shortcut or by clicking a light bulb icon in the editor.
811Cursor position or selection is signified by `┃` character.
812
813include::./generated_assists.adoc[]
814
815== Diagnostics
816
817While 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.
818Some 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.
819
820=== Clippy
821
822To run `cargo clippy` instead of `cargo check`, you can set `"rust-analyzer.check.command": "clippy"`.
823
824include::./generated_diagnostic.adoc[]
825
826== Editor Features
827=== VS Code
828
829==== Color configurations
830
831It is possible to change the foreground/background color and font family/size of inlay hints.
832Just add this to your `settings.json`:
833
834[source,jsonc]
835----
836{
837  "editor.inlayHints.fontFamily": "Courier New",
838  "editor.inlayHints.fontSize": 11,
839
840  "workbench.colorCustomizations": {
841    // Name of the theme you are currently using
842    "[Default Dark+]": {
843      "editorInlayHint.foreground": "#868686f0",
844      "editorInlayHint.background": "#3d3d3d48",
845
846      // Overrides for specific kinds of inlay hints
847      "editorInlayHint.typeForeground": "#fdb6fdf0",
848      "editorInlayHint.parameterForeground": "#fdb6fdf0",
849    }
850  }
851}
852----
853
854==== Semantic style customizations
855
856You can customize the look of different semantic elements in the source code.
857For example, mutable bindings are underlined by default and you can override this behavior by adding the following section to your `settings.json`:
858
859[source,jsonc]
860----
861{
862  "editor.semanticTokenColorCustomizations": {
863    "rules": {
864      "*.mutable": {
865        "fontStyle": "", // underline is the default
866      },
867    }
868  },
869}
870----
871
872Most 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`:
873
874[source,jsonc]
875----
876{
877   "editor.semanticTokenColorCustomizations": {
878         "rules": {
879             "operator.unsafe": "#ff6600",
880             "function.unsafe": "#ff6600",
881             "method.unsafe": "#ff6600"
882         }
883    },
884}
885----
886
887In 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:
888
889[source,jsonc]
890----
891{
892   "editor.semanticTokenColorCustomizations": {
893         "rules": {
894             "operator.unsafe": "#ff6600"
895         },
896         "[Ayu Light]": {
897            "rules": {
898               "operator.unsafe": "#572300"
899            }
900         }
901    },
902}
903----
904
905Make sure you include the brackets around the theme name. For example, use `"[Ayu Light]"` to customize the theme Ayu Light.
906
907==== Special `when` clause context for keybindings.
908You may use `inRustProject` context to configure keybindings for rust projects only.
909For example:
910
911[source,json]
912----
913{
914  "key": "ctrl+alt+d",
915  "command": "rust-analyzer.openDocs",
916  "when": "inRustProject"
917}
918----
919More about `when` clause contexts https://code.visualstudio.com/docs/getstarted/keybindings#_when-clause-contexts[here].
920
921==== Setting runnable environment variables
922You can use "rust-analyzer.runnables.extraEnv" setting to define runnable environment-specific substitution variables.
923The simplest way for all runnables in a bunch:
924```jsonc
925"rust-analyzer.runnables.extraEnv": {
926    "RUN_SLOW_TESTS": "1"
927}
928```
929
930Or it is possible to specify vars more granularly:
931```jsonc
932"rust-analyzer.runnables.extraEnv": [
933    {
934        // "mask": null, // null mask means that this rule will be applied for all runnables
935        env: {
936             "APP_ID": "1",
937             "APP_DATA": "asdf"
938        }
939    },
940    {
941        "mask": "test_name",
942        "env": {
943             "APP_ID": "2", // overwrites only APP_ID
944        }
945    }
946]
947```
948
949You can use any valid regular expression as a mask.
950Also 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.
951
952If needed, you can set different values for different platforms:
953```jsonc
954"rust-analyzer.runnables.extraEnv": [
955    {
956        "platform": "win32", // windows only
957        env: {
958             "APP_DATA": "windows specific data"
959        }
960    },
961    {
962        "platform": ["linux"],
963        "env": {
964             "APP_DATA": "linux data",
965        }
966    },
967    { // for all platforms
968        "env": {
969             "APP_COMMON_DATA": "xxx",
970        }
971    }
972]
973```
974
975==== Compiler feedback from external commands
976
977Instead 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.
978
979To do this you need to create a new https://code.visualstudio.com/docs/editor/tasks[VS Code Task] and set `"rust-analyzer.checkOnSave": false` in preferences.
980
981For example, if you want to run https://crates.io/crates/cargo-watch[`cargo watch`] instead, you might add the following to `.vscode/tasks.json`:
982
983```json
984{
985    "label": "Watch",
986    "group": "build",
987    "type": "shell",
988    "command": "cargo watch",
989    "problemMatcher": "$rustc-watch",
990    "isBackground": true
991}
992```
993
994==== Live Share
995
996VS Code Live Share has partial support for rust-analyzer.
997
998Live Share _requires_ the official Microsoft build of VS Code, OSS builds will not work correctly.
999
1000The host's rust-analyzer instance will be shared with all guests joining the session.
1001The guests do not have to have the rust-analyzer extension installed for this to work.
1002
1003If 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.