rust.md

  1# Rust
  2
  3Rust support is available natively in Zed.
  4
  5- Tree-sitter: [tree-sitter/tree-sitter-rust](https://github.com/tree-sitter/tree-sitter-rust)
  6- Language Server: [rust-lang/rust-analyzer](https://github.com/rust-lang/rust-analyzer)
  7- Debug Adapter: [CodeLLDB](https://github.com/vadimcn/codelldb) (primary), [GDB](https://sourceware.org/gdb/) (secondary, not available on Apple silicon)
  8
  9<!--
 10TBD: Polish Rust Docs. Zed is a good rust editor, good Rust docs make it look like we care about Rust (we do!)
 11TBD: Users may not know what inlayHints, don't start there.
 12TBD: Provide explicit examples not just `....`
 13-->
 14
 15## Inlay Hints
 16
 17The following configuration can be used to change the inlay hint settings for `rust-analyzer` in Rust:
 18
 19```json [settings]
 20{
 21  "lsp": {
 22    "rust-analyzer": {
 23      "initialization_options": {
 24        "inlayHints": {
 25          "maxLength": null,
 26          "lifetimeElisionHints": {
 27            "enable": "skip_trivial",
 28            "useParameterNames": true
 29          },
 30          "closureReturnTypeHints": {
 31            "enable": "always"
 32          }
 33        }
 34      }
 35    }
 36  }
 37}
 38```
 39
 40See [Inlay Hints](https://rust-analyzer.github.io/book/features.html#inlay-hints) in the Rust Analyzer Manual for more information.
 41
 42## Target directory
 43
 44The `rust-analyzer` target directory can be set in `initialization_options`:
 45
 46```json [settings]
 47{
 48  "lsp": {
 49    "rust-analyzer": {
 50      "initialization_options": {
 51        "rust": {
 52          "analyzerTargetDir": true
 53        }
 54      }
 55    }
 56  }
 57}
 58```
 59
 60A `true` setting will set the target directory to `target/rust-analyzer`. You can set a custom directory with a string like `"target/analyzer"` instead of `true`.
 61
 62## Binary
 63
 64You can configure which `rust-analyzer` binary Zed should use.
 65
 66By default, Zed will try to find a `rust-analyzer` in your `$PATH` and try to use that. If that binary successfully executes `rust-analyzer --help`, it's used. Otherwise, Zed will fall back to installing its own stable `rust-analyzer` version and use that.
 67
 68If you want to install pre-release `rust-analyzer` version instead you can instruct Zed to do so by setting `pre_release` to `true` in your `settings.json`:
 69
 70```json [settings]
 71{
 72  "lsp": {
 73    "rust-analyzer": {
 74      "fetch": {
 75        "pre_release": true
 76      }
 77    }
 78  }
 79}
 80```
 81
 82If you want to disable Zed looking for a `rust-analyzer` binary, you can set `ignore_system_version` to `true` in your `settings.json`:
 83
 84```json [settings]
 85{
 86  "lsp": {
 87    "rust-analyzer": {
 88      "binary": {
 89        "ignore_system_version": true
 90      }
 91    }
 92  }
 93}
 94```
 95
 96If you want to use a binary in a custom location, you can specify a `path` and optional `arguments`:
 97
 98```json [settings]
 99{
100  "lsp": {
101    "rust-analyzer": {
102      "binary": {
103        "path": "/Users/example/bin/rust-analyzer",
104        "arguments": []
105      }
106    }
107  }
108}
109```
110
111This `"path"` has to be an absolute path.
112
113## Alternate Targets
114
115If you want rust-analyzer to provide diagnostics for a target other than your current platform (e.g. for windows when running on macOS) you can use the following Zed lsp settings:
116
117```json [settings]
118{
119  "lsp": {
120    "rust-analyzer": {
121      "initialization_options": {
122        "cargo": {
123          "target": "x86_64-pc-windows-msvc"
124        }
125      }
126    }
127  }
128}
129```
130
131If you are using `rustup`, you can find a list of available target triples (`aarch64-apple-darwin`, `x86_64-unknown-linux-gnu`, etc) by running:
132
133```sh
134rustup target list --installed
135```
136
137## LSP tasks
138
139Zed provides tasks using tree-sitter, but rust-analyzer has an LSP extension method for querying file-related tasks via LSP.
140This is enabled by default and can be configured as
141
142```json [settings]
143"lsp": {
144  "rust-analyzer": {
145    "enable_lsp_tasks": true,
146  }
147}
148```
149
150## Manual Cargo Diagnostics fetch
151
152By default, rust-analyzer has `checkOnSave: true` enabled, which causes every buffer save to trigger a `cargo check --workspace --all-targets` command.
153If disabled with `checkOnSave: false` (see the example of the server configuration json above), it's still possible to fetch the diagnostics manually, with the `editor: run/clear/cancel flycheck` commands in Rust files to refresh cargo diagnostics; the project diagnostics editor will also refresh cargo diagnostics with `editor: run flycheck` command when the setting is enabled.
154
155## More server configuration
156
157<!--
158TBD: Is it possible to specify RUSTFLAGS? https://github.com/zed-industries/zed/issues/14334
159-->
160
161Rust-analyzer [manual](https://rust-analyzer.github.io/book/) describes various features and configuration options for rust-analyzer language server.
162Rust-analyzer in Zed runs with the default parameters.
163
164### Large projects and performance
165
166One of the main caveats that might cause extensive resource usage on large projects, is the combination of the following features:
167
168```
169rust-analyzer.checkOnSave (default: true)
170    Run the check command for diagnostics on save.
171```
172
173```
174rust-analyzer.check.workspace (default: true)
175    Whether --workspace should be passed to cargo check. If false, -p <package> will be passed instead.
176```
177
178```
179rust-analyzer.cargo.allTargets (default: true)
180    Pass --all-targets to cargo invocation
181```
182
183Which would mean that every time Zed saves, a `cargo check --workspace --all-targets` command is run, checking the entire project (workspace), lib, doc, test, bin, bench and [other targets](https://doc.rust-lang.org/cargo/reference/cargo-targets.html).
184
185While that works fine on small projects, it does not scale well.
186
187The alternatives would be to use [tasks](../tasks.md), as Zed already provides a `cargo check --workspace --all-targets` task and the ability to cmd/ctrl-click on the terminal output to navigate to the error, and limit or turn off the check on save feature entirely.
188
189Check on save feature is responsible for returning part of the diagnostics based on cargo check output, so turning it off will limit rust-analyzer with its own [diagnostics](https://rust-analyzer.github.io/book/diagnostics.html).
190
191Consider more `rust-analyzer.cargo.` and `rust-analyzer.check.` and `rust-analyzer.diagnostics.` settings from the manual for more fine-grained configuration.
192Here's a snippet for Zed settings.json (the language server will restart automatically after the `lsp.rust-analyzer` section is edited and saved):
193
194```json [settings]
195{
196  "lsp": {
197    "rust-analyzer": {
198      "initialization_options": {
199        // get more cargo-less diagnostics from rust-analyzer,
200        // which might include false-positives (those can be turned off by their names)
201        "diagnostics": {
202          "experimental": {
203            "enable": true
204          }
205        },
206        // To disable the checking entirely
207        // (ignores all cargo and check settings below)
208        "checkOnSave": false,
209        // To check the `lib` target only.
210        "cargo": {
211          "allTargets": false
212        },
213        // Use `-p` instead of `--workspace` for cargo check
214        "check": {
215          "workspace": false
216        }
217      }
218    }
219  }
220}
221```
222
223### Multi-project workspaces
224
225If you want rust-analyzer to analyze multiple Rust projects in the same folder that are not listed in `[members]` in the Cargo workspace,
226you can list them in `linkedProjects` in the local project settings:
227
228```json [settings]
229{
230  "lsp": {
231    "rust-analyzer": {
232      "initialization_options": {
233        "linkedProjects": ["./path/to/a/Cargo.toml", "./path/to/b/Cargo.toml"]
234      }
235    }
236  }
237}
238```
239
240### Snippets
241
242There's a way to get custom completion items from rust-analyzer, that will transform the code according to the snippet body:
243
244```json [settings]
245{
246  "lsp": {
247    "rust-analyzer": {
248      "initialization_options": {
249        "completion": {
250          "snippets": {
251            "custom": {
252              "Arc::new": {
253                "postfix": "arc",
254                "body": ["Arc::new(${receiver})"],
255                "requires": "std::sync::Arc",
256                "scope": "expr"
257              },
258              "Some": {
259                "postfix": "some",
260                "body": ["Some(${receiver})"],
261                "scope": "expr"
262              },
263              "Ok": {
264                "postfix": "ok",
265                "body": ["Ok(${receiver})"],
266                "scope": "expr"
267              },
268              "Rc::new": {
269                "postfix": "rc",
270                "body": ["Rc::new(${receiver})"],
271                "requires": "std::rc::Rc",
272                "scope": "expr"
273              },
274              "Box::pin": {
275                "postfix": "boxpin",
276                "body": ["Box::pin(${receiver})"],
277                "requires": "std::boxed::Box",
278                "scope": "expr"
279              },
280              "vec!": {
281                "postfix": "vec",
282                "body": ["vec![${receiver}]"],
283                "description": "vec![]",
284                "scope": "expr"
285              }
286            }
287          }
288        }
289      }
290    }
291  }
292}
293```
294
295## Debugging
296
297Zed supports debugging Rust binaries and tests out of the box with `CodeLLDB` and `GDB`. Run {#action debugger::Start} ({#kb debugger::Start}) to launch one of these preconfigured debug tasks.
298
299For more control, you can add debug configurations to `.zed/debug.json`. See the examples below.
300
301- [CodeLLDB configuration documentation](https://github.com/vadimcn/codelldb/blob/master/MANUAL.md#starting-a-new-debug-session)
302- [GDB configuration documentation](https://sourceware.org/gdb/current/onlinedocs/gdb.html/Debugger-Adapter-Protocol.html)
303
304### Build binary then debug
305
306```json [debug]
307[
308  {
309    "label": "Build & Debug native binary",
310    "build": {
311      "command": "cargo",
312      "args": ["build"]
313    },
314    "program": "$ZED_WORKTREE_ROOT/target/debug/binary",
315    // sourceLanguages is required for CodeLLDB (not GDB) when using Rust
316    "sourceLanguages": ["rust"],
317    "request": "launch",
318    "adapter": "CodeLLDB"
319  }
320]
321```
322
323### Automatically locate a debug target based on build command
324
325When you use `cargo build` or `cargo test` as the build command, Zed can infer the path to the output binary.
326
327```json [debug]
328[
329  {
330    "label": "Build & Debug native binary",
331    "adapter": "CodeLLDB",
332    "build": {
333      "command": "cargo",
334      "args": ["build"]
335    },
336    // sourceLanguages is required for CodeLLDB (not GDB) when using Rust
337    "sourceLanguages": ["rust"]
338  }
339]
340```