Skip to content

Commit

Permalink
Auto merge of #17058 - alibektas:13529/ratoml, r=Veykril
Browse files Browse the repository at this point in the history
feat: TOML based config for rust-analyzer

# TOML Based Config for RA

This PR ( fixes #13529 and this is a follow-up PR on #16639 ) makes rust-analyzer configurable by configuration files called `rust-analyzer.toml`. Files **must** be named `rust-analyzer.toml`. There is not a strict rule regarding where the files should be placed, but it is recommended to put them near a file that triggers server to start (i.e., `Cargo.{toml,lock}`, `rust-project.json`).

## Configuration Types

Previous configuration keys are now split into three different classes.

1. Client keys: These keys only make sense when set by the client (e.g., by setting them in `settings.json` in VSCode). They are but a small portion of this list. One such example is `rust_analyzer.files_watcher`, based on which either the client or the server will be responsible for watching for changes made to project files.
2. Global keys: These keys apply to the entire workspace and can only be set on the very top layers of the hierarchy. The next section gives instructions on which layers these are.
3. Local keys: Keys that can be changed for each crate if desired.

### How Am I Supposed To Know If A Config Is Gl/Loc/Cl ?

#17101

## Configuration Hierarchy

There are 5 levels in the configuration hierarchy. When a key is searched for, it is searched in a bottom-up depth-first fashion.

### Default Configuration

**Scope**: Global, Local, and Client

This is a hard-coded set of configurations. When a configuration key could not be found, then its default value applies.

### User configuration

**Scope**: Global, Local

If you want your configurations to apply to **every** project you have, you can do so by setting them in your `$CONFIG_DIR/rust-analyzer/rust-analyzer.toml` file, where `$CONFIG_DIR` is :

| Platform | Value                                 | Example                                  |
| ------- | ------------------------------------- | ---------------------------------------- |
| Linux   | `$XDG_CONFIG_HOME` or `$HOME`/.config | /home/alice/.config                      |
| macOS   | `$HOME`/Library/Application Support   | /Users/Alice/Library/Application Support |
| Windows | `{FOLDERID_RoamingAppData}`           | C:\Users\Alice\AppData\Roaming           |

### Client configuration

**Scope**: Global, Local, and Client

Previously, the only way to configure rust-analyzer was to configure it from the settings of the Client you are using. This level corresponds to that.

> With this PR, you don't need to port anything to benefit from new features. You can continue to use your old settings as they are.

### Workspace Root Configuration

**Scope**: Global, Local

Rust-analyzer already used the path of the workspace you opened in your Client. We used this information to create a configuration file that won't affect your other projects and define global level configurations at the same time.

### Local Configuration

**Scope**: Local

You can also configure rust-analyzer on a crate level. Although it is not an error to define global ( or client ) level keys in such files, they won't be taken into consideration by the server. Defined local keys will affect the crate in which they are defined and crate's descendants. Internally, a Rust project is split into what we call `SourceRoot`s. This, although with exceptions, is equal to splitting a project into crates.

> You may choose to have more than one `rust-analyzer.toml` files within a `SourceRoot`, but among them, the one closer to the project root will be
  • Loading branch information
bors committed Jun 6, 2024
2 parents 577b0be + 3178e5f commit 6e427d8
Show file tree
Hide file tree
Showing 19 changed files with 2,166 additions and 557 deletions.
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 8 additions & 1 deletion crates/ide/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,10 +273,17 @@ impl Analysis {
self.with_db(|db| status::status(db, file_id))
}

pub fn source_root(&self, file_id: FileId) -> Cancellable<SourceRootId> {
pub fn source_root_id(&self, file_id: FileId) -> Cancellable<SourceRootId> {
self.with_db(|db| db.file_source_root(file_id))
}

pub fn is_local_source_root(&self, source_root_id: SourceRootId) -> Cancellable<bool> {
self.with_db(|db| {
let sr = db.source_root(source_root_id);
!sr.is_library
})
}

pub fn parallel_prime_caches<F>(&self, num_worker_threads: u8, cb: F) -> Cancellable<()>
where
F: Fn(ParallelPrimeCachesProgress) + Sync + std::panic::UnwindSafe,
Expand Down
18 changes: 18 additions & 0 deletions crates/paths/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,24 @@ impl AbsPathBuf {
pub fn pop(&mut self) -> bool {
self.0.pop()
}

/// Equivalent of [`PathBuf::push`] for `AbsPathBuf`.
///
/// Extends `self` with `path`.
///
/// If `path` is absolute, it replaces the current path.
///
/// On Windows:
///
/// * if `path` has a root but no prefix (e.g., `\windows`), it
/// replaces everything except for the prefix (if any) of `self`.
/// * if `path` has a prefix but no root, it replaces `self`.
/// * if `self` has a verbatim prefix (e.g. `\\?\C:\windows`)
/// and `path` is not empty, the new path is normalized: all references
/// to `.` and `..` are removed.
pub fn push<P: AsRef<Utf8Path>>(&mut self, suffix: P) {
self.0.push(suffix)
}
}

impl fmt::Display for AbsPathBuf {
Expand Down
1 change: 1 addition & 0 deletions crates/rust-analyzer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ path = "src/bin/main.rs"
[dependencies]
anyhow.workspace = true
crossbeam-channel = "0.5.5"
dirs = "5.0.1"
dissimilar.workspace = true
itertools.workspace = true
scip = "0.3.3"
Expand Down
18 changes: 14 additions & 4 deletions crates/rust-analyzer/src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ use std::{env, fs, path::PathBuf, process::ExitCode, sync::Arc};

use anyhow::Context;
use lsp_server::Connection;
use rust_analyzer::{cli::flags, config::Config, from_json};
use rust_analyzer::{
cli::flags,
config::{Config, ConfigChange, ConfigErrors},
from_json,
};
use semver::Version;
use tracing_subscriber::fmt::writer::BoxMakeWriter;
use vfs::AbsPathBuf;
Expand Down Expand Up @@ -220,16 +224,22 @@ fn run_server() -> anyhow::Result<()> {
.filter(|workspaces| !workspaces.is_empty())
.unwrap_or_else(|| vec![root_path.clone()]);
let mut config =
Config::new(root_path, capabilities, workspace_roots, visual_studio_code_version);
Config::new(root_path, capabilities, workspace_roots, visual_studio_code_version, None);
if let Some(json) = initialization_options {
if let Err(e) = config.update(json) {
let mut change = ConfigChange::default();
change.change_client_config(json);

let error_sink: ConfigErrors;
(config, error_sink, _) = config.apply_change(change);

if !error_sink.is_empty() {
use lsp_types::{
notification::{Notification, ShowMessage},
MessageType, ShowMessageParams,
};
let not = lsp_server::Notification::new(
ShowMessage::METHOD.to_owned(),
ShowMessageParams { typ: MessageType::WARNING, message: e.to_string() },
ShowMessageParams { typ: MessageType::WARNING, message: error_sink.to_string() },
);
connection.sender.send(lsp_server::Message::Notification(not)).unwrap();
}
Expand Down
12 changes: 11 additions & 1 deletion crates/rust-analyzer/src/cli/scip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ use ide_db::LineIndexDatabase;
use load_cargo::{load_workspace_at, LoadCargoConfig, ProcMacroServerChoice};
use rustc_hash::{FxHashMap, FxHashSet};
use scip::types as scip_types;
use tracing::error;

use crate::{
cli::flags,
config::ConfigChange,
line_index::{LineEndings, LineIndex, PositionEncoding},
};

Expand All @@ -35,12 +37,20 @@ impl flags::Scip {
lsp_types::ClientCapabilities::default(),
vec![],
None,
None,
);

if let Some(p) = self.config_path {
let mut file = std::io::BufReader::new(std::fs::File::open(p)?);
let json = serde_json::from_reader(&mut file)?;
config.update(json)?;
let mut change = ConfigChange::default();
change.change_client_config(json);

let error_sink;
(config, error_sink, _) = config.apply_change(change);

// FIXME @alibektas : What happens to errors without logging?
error!(?error_sink, "Config Error(s)");
}
let cargo_config = config.cargo();
let (db, vfs, _) = load_workspace_at(
Expand Down
Loading

0 comments on commit 6e427d8

Please sign in to comment.