]> git.lizzy.rs Git - rust.git/blob - docs/user/manual.adoc
Add support for Rust 2021.
[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 // Master copy of this document lives in the https://github.com/rust-analyzer/rust-analyzer repository
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
23 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.
24
25 == Installation
26
27 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.
28 We are not there yet, so some editor specific setup is required.
29
30 Additionally, rust-analyzer needs the sources of the standard library.
31 If the source code is not present, rust-analyzer will attempt to install it automatically.
32
33 To add the sources manually, run the following command:
34
35 ```bash
36 $ rustup component add rust-src
37 ```
38
39 === VS Code
40
41 This is the best supported editor at the moment.
42 The rust-analyzer plugin for VS Code is maintained
43 https://github.com/rust-analyzer/rust-analyzer/tree/master/editors/code[in tree].
44
45 You can install the latest release of the plugin from
46 https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer[the marketplace].
47
48 Note that the plugin may cause conflicts with the
49 https://marketplace.visualstudio.com/items?itemName=rust-lang.rust[official Rust plugin].
50 It is recommended to disable the Rust plugin when using the rust-analyzer extension.
51
52 By default, the plugin will prompt you to download the matching version of the server as well:
53
54 image::https://user-images.githubusercontent.com/9021944/75067008-17502500-54ba-11ea-835a-f92aac50e866.png[]
55
56 [NOTE]
57 ====
58 To disable this notification put the following to `settings.json`
59
60 [source,json]
61 ----
62 { "rust-analyzer.updates.askBeforeDownload": false }
63 ----
64 ====
65
66 The server binary is stored in:
67
68 * Linux: `~/.config/Code/User/globalStorage/matklad.rust-analyzer`
69 * Linux (Remote, such as WSL): `~/.vscode-server/data/User/globalStorage/matklad.rust-analyzer`
70 * macOS: `~/Library/Application\ Support/Code/User/globalStorage/matklad.rust-analyzer`
71 * Windows: `%APPDATA%\Code\User\globalStorage\matklad.rust-analyzer`
72
73 Note that we only support two most recent versions of VS Code.
74
75 ==== Updates
76
77 The extension will be updated automatically as new versions become available.
78 It will ask your permission to download the matching language server version binary if needed.
79
80 ===== Nightly
81
82 We ship nightly releases for VS Code.
83 To help us out with testing the newest code and follow the bleeding edge of our `master`, please use the following config:
84
85 [source,json]
86 ----
87 { "rust-analyzer.updates.channel": "nightly" }
88 ----
89
90 You will be prompted to install the `nightly` extension version.
91 Just click `Download now` and from that moment you will get automatic updates every 24 hours.
92
93 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`:
94 [source,json]
95 ----
96 { "rust-analyzer.updates.askBeforeDownload": false }
97 ----
98
99 NOTE: Nightly extension should **only** be installed via the `Download now` action from VS Code.
100
101 ==== Manual installation
102
103 Alternatively, procure both `rust-analyzer.vsix` and your platform's matching `rust-analyzer-{platform}`, for example from the
104 https://github.com/rust-analyzer/rust-analyzer/releases[releases] page.
105
106 Install the extension with the `Extensions: Install from VSIX` command within VS Code, or from the command line via:
107 [source]
108 ----
109 $ code --install-extension /path/to/rust-analyzer.vsix
110 ----
111
112 Copy the `rust-analyzer-{platform}` binary anywhere, then add the path to your settings.json, for example:
113 [source,json]
114 ----
115 { "rust-analyzer.serverPath": "~/.local/bin/rust-analyzer-linux" }
116 ----
117
118 ==== Building From Source
119
120 Alternatively, both the server and the Code plugin can be installed from source:
121
122 [source]
123 ----
124 $ git clone https://github.com/rust-analyzer/rust-analyzer.git && cd rust-analyzer
125 $ cargo xtask install
126 ----
127
128 You'll need Cargo, nodejs and npm for this.
129
130 Note that installing via `xtask install` does not work for VS Code Remote, instead you'll need to install the `.vsix` manually.
131
132 If you're not using Code, you can compile and install only the LSP server:
133
134 [source]
135 ----
136 $ cargo xtask install --server
137 ----
138
139 ==== Troubleshooting
140
141 Here are some useful self-diagnostic commands:
142
143 * **Rust Analyzer: Show RA Version** shows the version of `rust-analyzer` binary.
144 * **Rust Analyzer: Status** prints some statistics about the server, and dependency information for the current file.
145 * To enable server-side logging, run with `env RA_LOG=info` and see `Output > Rust Analyzer Language Server` in VS Code's panel.
146 * To log project loading (sysroot & `cargo metadata`), set `RA_LOG=project_model=debug`.
147 * To log all LSP requests, add `"rust-analyzer.trace.server": "verbose"` to the settings and look for `Rust Analyzer Language Server Trace` in the panel.
148 * To enable client-side logging, add `"rust-analyzer.trace.extension": true` to the settings and open `Output > Rust Analyzer Client` in the panel.
149
150 === rust-analyzer Language Server Binary
151
152 Other editors generally require the `rust-analyzer` binary to be in `$PATH`.
153 You can download the pre-built binary from the https://github.com/rust-analyzer/rust-analyzer/releases[releases] page.
154 Typically, you then need to rename the binary for your platform, e.g. `rust-analyzer-mac` if you're on Mac OS, to `rust-analyzer` and make it executable in addition to moving it into a directory in your `$PATH`.
155
156 On Linux to install the `rust-analyzer` binary into `~/.local/bin`, this commands could be used
157
158 [source,bash]
159 ----
160 $ curl -L https://github.com/rust-analyzer/rust-analyzer/releases/latest/download/rust-analyzer-linux -o ~/.local/bin/rust-analyzer
161 $ chmod +x ~/.local/bin/rust-analyzer
162 ----
163
164 Ensure `~/.local/bin` is listed in the `$PATH` variable.
165
166 Alternatively, you can install it from source using the command below.
167 You'll need the latest stable version of the Rust toolchain.
168
169 [source,bash]
170 ----
171 $ git clone https://github.com/rust-analyzer/rust-analyzer.git && cd rust-analyzer
172 $ cargo xtask install --server
173 ----
174
175 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].
176 On Unix, running the editor from a shell or changing the `.desktop` file to set the environment should help.
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 === Emacs
193
194 Prerequisites: You have installed the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>>.
195
196 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].
197
198 1. Install the most recent version of `emacs-lsp` package by following the https://github.com/emacs-lsp/lsp-mode[Emacs-LSP instructions].
199 2. Set `lsp-rust-server` to `'rust-analyzer`.
200 3. Run `lsp` in a Rust buffer.
201 4. (Optionally) bind commands like `lsp-rust-analyzer-join-lines`, `lsp-extend-selection` and `lsp-rust-analyzer-expand-macro` to keys.
202
203 === Vim/NeoVim
204
205 Prerequisites: You have installed the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>>.
206 Not needed if the extension can install/update it on its own, coc-rust-analyzer is one example.
207
208 The are several LSP client implementations for vim or neovim:
209
210 ==== coc-rust-analyzer
211
212 1. Install coc.nvim by following the instructions at
213    https://github.com/neoclide/coc.nvim[coc.nvim]
214    (Node.js required)
215 2. Run `:CocInstall coc-rust-analyzer` to install
216    https://github.com/fannheyward/coc-rust-analyzer[coc-rust-analyzer],
217    this extension implements _most_ of the features supported in the VSCode extension:
218    * automatically install and upgrade stable/nightly releases
219    * same configurations as VSCode extension, `rust-analyzer.serverPath`, `rust-analyzer.cargo.features` etc.
220    * same commands too, `rust-analyzer.analyzerStatus`, `rust-analyzer.ssr` etc.
221    * inlay hints for variables and method chaining, _Neovim Only_
222    * semantic highlighting is not implemented yet
223
224 ==== LanguageClient-neovim
225
226 1. Install LanguageClient-neovim by following the instructions
227    https://github.com/autozimu/LanguageClient-neovim[here]
228    * The GitHub project wiki has extra tips on configuration
229
230 2. Configure by adding this to your vim/neovim config file (replacing the existing Rust-specific line if it exists):
231 +
232 [source,vim]
233 ----
234 let g:LanguageClient_serverCommands = {
235 \ 'rust': ['rust-analyzer'],
236 \ }
237 ----
238
239 ==== YouCompleteMe
240
241 1. Install YouCompleteMe by following the instructions
242   https://github.com/ycm-core/lsp-examples#rust-rust-analyzer[here]
243
244 2. Configure by adding this to your vim/neovim config file (replacing the existing Rust-specific line if it exists):
245 +
246 [source,vim]
247 ----
248 let g:ycm_language_server =
249 \ [
250 \   {
251 \     'name': 'rust',
252 \     'cmdline': ['rust-analyzer'],
253 \     'filetypes': ['rust'],
254 \     'project_root_files': ['Cargo.toml']
255 \   }
256 \ ]
257 ----
258
259 ==== ALE
260
261 To use the LSP server in https://github.com/dense-analysis/ale[ale]:
262
263 [source,vim]
264 ----
265 let g:ale_linters = {'rust': ['analyzer']}
266 ----
267
268 ==== nvim-lsp
269
270 NeoVim 0.5 (not yet released) has built-in language server support.
271 For a quick start configuration of rust-analyzer, use https://github.com/neovim/nvim-lspconfig#rust_analyzer[neovim/nvim-lspconfig].
272 Once `neovim/nvim-lspconfig` is installed, use `+lua require'nvim_lsp'.rust_analyzer.setup({})+` in your `init.vim`.
273
274 === Sublime Text 3
275
276 Prerequisites: You have installed the <<rust-analyzer-language-server-binary,`rust-analyzer` binary>>.
277
278 You also need the `LSP` package.
279 To install it:
280
281 1. If you've never installed a Sublime Text package, install Package Control:
282    * Open the command palette (Win/Linux: `ctrl+shift+p`, Mac: `cmd+shift+p`)
283    * Type `Install Package Control`, press enter
284 2. In the command palette, run `Package control: Install package`, and in the list that pops up, type `LSP` and press enter.
285
286 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.
287 The latter means that rust-analyzer is enabled by default in Rust projects.
288
289 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.
290
291 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.
292
293 === GNOME Builder
294
295 GNOME Builder 3.37.1 and newer has native `rust-analyzer` support.
296 If the LSP binary is not available, GNOME Builder can install it when opening a Rust file.
297
298 == Configuration
299
300 **Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/rust-analyzer/src/config.rs[config.rs]
301
302 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.
303 Please consult your editor's documentation to learn how to configure LSP servers.
304
305 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.
306 Logs should show both the JSON that rust-analyzer sees as well as the updated config.
307
308 This is the list of config options rust-analyzer supports:
309
310 include::./generated_config.adoc[]
311
312 == Non-Cargo Based Projects
313
314 rust-analyzer does not require Cargo.
315 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:
316
317 [source,TypeScript]
318 ----
319 interface JsonProject {
320     /// Path to the directory with *source code* of sysroot crates.
321     ///
322     /// It should point to the directory where std, core, and friends can be found:
323     /// https://github.com/rust-lang/rust/tree/master/library.
324     ///
325     /// If provided, rust-analyzer automatically adds dependencies on sysroot
326     /// crates. Conversely, if you omit this path, you can specify sysroot
327     /// dependencies yourself and, for example, have several different "sysroots" in
328     /// one graph of crates.
329     sysroot_src?: string;
330     /// The set of crates comprising the current project.
331     /// Must include all transitive dependencies as well as sysroot crate (libstd, libcore and such).
332     crates: Crate[];
333 }
334
335 interface Crate {
336     /// Optional crate name used for display purposes, without affecting semantics.
337     /// See the `deps` key for semantically-significant crate names.
338     display_name?: string;
339     /// Path to the root module of the crate.
340     root_module: string;
341     /// Edition of the crate.
342     edition: "2015" | "2018" | "2021";
343     /// Dependencies
344     deps: Dep[];
345     /// Should this crate be treated as a member of current "workspace".
346     ///
347     /// By default, inferred from the `root_module` (members are the crates which reside
348     /// inside the directory opened in the editor).
349     ///
350     /// Set this to `false` for things like standard library and 3rd party crates to
351     /// enable performance optimizations (rust-analyzer assumes that non-member crates
352     /// don't change).
353     is_workspace_member?: boolean;
354     /// Optionally specify the (super)set of `.rs` files comprising this crate.
355     ///
356     /// By default, rust-analyzer assumes that only files under `root_module.parent` can belong to a crate.
357     /// `include_dirs` are included recursively, unless a subdirectory is in `exclude_dirs`.
358     ///
359     /// Different crates can share the same `source`.
360     ///
361     /// If two crates share an `.rs` file in common, they *must* have the same `source`.
362     /// rust-analyzer assumes that files from one source can't refer to files in another source.
363     source?: {
364         include_dirs: string[],
365         exclude_dirs: string[],
366     },
367     /// The set of cfgs activated for a given crate, like `["unix", "feature=foo", "feature=bar"]`.
368     cfg: string[];
369     /// Target triple for this Crate.
370     ///
371     /// Used when running `rustc --print cfg` to get target-specific cfgs.
372     target?: string;
373     /// Environment variables, used for the `env!` macro
374     env: : { [key: string]: string; },
375
376     /// For proc-macro crates, path to compiles proc-macro (.so file).
377     proc_macro_dylib_path?: string;
378 }
379
380 interface Dep {
381     /// Index of a crate in the `crates` array.
382     crate: number,
383     /// Name as should appear in the (implicit) `extern crate name` declaration.
384     name: string,
385 }
386 ----
387
388 This format is provisional and subject to change.
389 Specifically, the `roots` setup will be different eventually.
390
391 There are tree ways to feed `rust-project.json` to rust-analyzer:
392
393 * Place `rust-project.json` file at the root of the project, and rust-anlayzer will discover it.
394 * 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).
395 * Specify `"rust-analyzer.linkedProjects": [ { "roots": [...], "crates": [...] }]` inline.
396
397 Relative paths are interpreted relative to `rust-project.json` file location or (for inline JSON) relative to `rootUri`.
398
399 See https://github.com/rust-analyzer/rust-project.json-example for a small example.
400
401 You can set `RA_LOG` environmental variable to `rust_analyzer=info` to inspect how rust-analyzer handles config and project loading.
402
403 == Features
404
405 include::./generated_features.adoc[]
406
407 == Assists (Code Actions)
408
409 Assists, or code actions, are small local refactorings, available in a particular context.
410 They are usually triggered by a shortcut or by clicking a light bulb icon in the editor.
411 Cursor position or selection is signified by `┃` character.
412
413 include::./generated_assists.adoc[]
414
415 == Diagnostics
416
417 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.
418 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.
419
420 include::./generated_diagnostic.adoc[]
421
422 == Editor Features
423 === VS Code
424
425 ==== Color configurations
426
427 It is possible to change the foreground/background color of inlay hints.
428 Just add this to your `settings.json`:
429
430 [source,jsonc]
431 ----
432 {
433   "workbench.colorCustomizations": {
434     // Name of the theme you are currently using
435     "[Default Dark+]": {
436       "rust_analyzer.inlayHints.foreground": "#868686f0",
437       "rust_analyzer.inlayHints.background": "#3d3d3d48",
438
439       // Overrides for specific kinds of inlay hints
440       "rust_analyzer.inlayHints.foreground.typeHints": "#fdb6fdf0",
441       "rust_analyzer.inlayHints.foreground.paramHints": "#fdb6fdf0",
442       "rust_analyzer.inlayHints.background.chainingHints": "#6b0c0c81"
443     }
444   }
445 }
446 ----
447
448 ==== Semantic style customizations
449
450 You can customize the look of different semantic elements in the source code.
451 For example, mutable bindings are underlined by default and you can override this behavior by adding the following section to your `settings.json`:
452
453 [source,jsonc]
454 ----
455 {
456   "editor.semanticTokenColorCustomizations": {
457     "rules": {
458       "*.mutable": {
459         "fontStyle": "", // underline is the default
460       },
461     }
462   },
463 }
464 ----
465
466 ==== Special `when` clause context for keybindings.
467 You may use `inRustProject` context to configure keybindings for rust projects only.
468 For example:
469
470 [source,json]
471 ----
472 {
473   "key": "ctrl+i",
474   "command": "rust-analyzer.toggleInlayHints",
475   "when": "inRustProject"
476 }
477 ----
478 More about `when` clause contexts https://code.visualstudio.com/docs/getstarted/keybindings#_when-clause-contexts[here].
479
480 ==== Setting runnable environment variables
481 You can use "rust-analyzer.runnableEnv" setting to define runnable environment-specific substitution variables.
482 The simplest way for all runnables in a bunch:
483 ```jsonc
484 "rust-analyzer.runnableEnv": {
485     "RUN_SLOW_TESTS": "1"
486 }
487 ```
488
489 Or it is possible to specify vars more granularly:
490 ```jsonc
491 "rust-analyzer.runnableEnv": [
492     {
493         // "mask": null, // null mask means that this rule will be applied for all runnables
494         env: {
495              "APP_ID": "1",
496              "APP_DATA": "asdf"
497         }
498     },
499     {
500         "mask": "test_name",
501         "env": {
502              "APP_ID": "2", // overwrites only APP_ID
503         }
504     }
505 ]
506 ```
507
508 You can use any valid regular expression as a mask.
509 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.
510
511 ==== Compiler feedback from external commands
512
513 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.
514
515 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.
516
517 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`:
518
519 ```json
520 {
521     "label": "Watch",
522     "group": "build",
523     "type": "shell",
524     "command": "cargo watch",
525     "problemMatcher": "$rustc-watch",
526     "isBackground": true
527 }
528 ```