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