Brian Silverman | cc09f18 | 2022-03-09 15:40:20 -0800 | [diff] [blame^] | 1 | #[[ |
| 2 | ## Overview |
| 3 | |
| 4 | For [non-Cargo projects](https://rust-analyzer.github.io/manual.html#non-cargo-based-projects), |
| 5 | [rust-analyzer](https://rust-analyzer.github.io/) depends on a `rust-project.json` file at the |
| 6 | root of the project that describes its structure. The `rust_analyzer` rule facilitates generating |
| 7 | such a file. |
| 8 | |
| 9 | ### Setup |
| 10 | |
| 11 | First, add the following to the `WORKSPACE` file: |
| 12 | |
| 13 | ```python |
| 14 | load("@rules_rust//tools/rust_analyzer:deps.bzl", "rust_analyzer_deps") |
| 15 | |
| 16 | rust_analyzer_deps() |
| 17 | ``` |
| 18 | |
| 19 | Next, add the following lines to the `.bazelrc` file of your workspace: |
| 20 | ``` |
| 21 | build --repo_env=RULES_RUST_TOOLCHAIN_INCLUDE_RUSTC_SRCS=true |
| 22 | ``` |
| 23 | |
| 24 | This will ensure rust source code is available to `rust-analyzer`. Users |
| 25 | can also set `include_rustc_srcs = True` on any `rust_repository` or |
| 26 | `rust_repositories` calls in the workspace but the environment variable |
| 27 | has higher priority and can override the attribute. |
| 28 | |
| 29 | Finally, run `bazel run @rules_rust//tools/rust_analyzer:gen_rust_project` |
| 30 | whenever dependencies change to regenerate the `rust-project.json` file. It |
| 31 | should be added to `.gitignore` because it is effectively a build artifact. |
| 32 | Once the `rust-project.json` has been generated in the project root, |
| 33 | rust-analyzer can pick it up upon restart. |
| 34 | |
| 35 | #### VSCode |
| 36 | |
| 37 | To set this up using [VSCode](https://code.visualstudio.com/), users should first install the |
| 38 | [rust_analyzer plugin](https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer). |
| 39 | With that in place, the following task can be added to the `.vscode/tasks.json` file of the workspace |
| 40 | to ensure a `rust-project.json` file is created and up to date when the editor is opened. |
| 41 | |
| 42 | ```json |
| 43 | { |
| 44 | "version": "2.0.0", |
| 45 | "tasks": [ |
| 46 | { |
| 47 | "label": "Generate rust-project.json", |
| 48 | "command": "bazel", |
| 49 | "args": ["run", "@rules_rust//tools/rust_analyzer:gen_rust_project"], |
| 50 | "options": { |
| 51 | "cwd": "${workspaceFolder}" |
| 52 | }, |
| 53 | "group": "build", |
| 54 | "problemMatcher": [], |
| 55 | "presentation": { |
| 56 | "reveal": "never", |
| 57 | "panel": "dedicated", |
| 58 | }, |
| 59 | "runOptions": { |
| 60 | "runOn": "folderOpen" |
| 61 | } |
| 62 | }, |
| 63 | ] |
| 64 | } |
| 65 | ``` |
| 66 | ]]# |