Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce $CONFIG_DIR/rust-analyzer/rust-analyzer.toml #18070

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions crates/load-cargo/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ pub fn load_workspace(
.collect()
};

let project_folders = ProjectFolders::new(std::slice::from_ref(&ws), &[]);
let project_folders = ProjectFolders::new(std::slice::from_ref(&ws), &[], None);
loader.set_config(vfs::loader::Config {
load: project_folders.load,
watch: vec![],
Expand Down Expand Up @@ -153,7 +153,11 @@ pub struct ProjectFolders {
}

impl ProjectFolders {
pub fn new(workspaces: &[ProjectWorkspace], global_excludes: &[AbsPathBuf]) -> ProjectFolders {
pub fn new(
workspaces: &[ProjectWorkspace],
global_excludes: &[AbsPathBuf],
user_config_dir_path: Option<&'static AbsPath>,
) -> ProjectFolders {
let mut res = ProjectFolders::default();
let mut fsc = FileSetConfig::builder();
let mut local_filesets = vec![];
Expand Down Expand Up @@ -286,6 +290,22 @@ impl ProjectFolders {
}
}

if let Some(user_config_path) = user_config_dir_path {
let ratoml_path = {
let mut p = user_config_path.to_path_buf();
p.push("rust-analyzer.toml");
p
};

let file_set_roots: Vec<VfsPath> = vec![VfsPath::from(ratoml_path.to_owned())];
let entry = vfs::loader::Entry::Files(vec![ratoml_path.to_owned()]);

res.watch.push(res.load.len());
res.load.push(entry);
local_filesets.push(fsc.len() as u64);
fsc.add_file_set(file_set_roots)
}

let fsc = fsc.build();
res.source_root_config = SourceRootConfig { fsc, local_filesets };

Expand Down
109 changes: 54 additions & 55 deletions crates/rust-analyzer/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ config_data! {
/// How many worker threads to handle priming caches. The default `0` means to pick automatically.
cachePriming_numThreads: NumThreads = NumThreads::Physical,

/// Custom completion snippets.
completion_snippets_custom: FxHashMap<String, SnippetDef> = Config::completion_snippets_default(),


/// These directories will be ignored by rust-analyzer. They are
Expand Down Expand Up @@ -438,48 +440,6 @@ config_data! {
completion_postfix_enable: bool = true,
/// Enables completions of private items and fields that are defined in the current workspace even if they are not visible at the current position.
completion_privateEditable_enable: bool = false,
/// Custom completion snippets.
completion_snippets_custom: FxHashMap<String, SnippetDef> = serde_json::from_str(r#"{
"Arc::new": {
"postfix": "arc",
"body": "Arc::new(${receiver})",
"requires": "std::sync::Arc",
"description": "Put the expression into an `Arc`",
"scope": "expr"
},
"Rc::new": {
"postfix": "rc",
"body": "Rc::new(${receiver})",
"requires": "std::rc::Rc",
"description": "Put the expression into an `Rc`",
"scope": "expr"
},
"Box::pin": {
"postfix": "pinbox",
"body": "Box::pin(${receiver})",
"requires": "std::boxed::Box",
"description": "Put the expression into a pinned `Box`",
"scope": "expr"
},
"Ok": {
"postfix": "ok",
"body": "Ok(${receiver})",
"description": "Wrap the expression in a `Result::Ok`",
"scope": "expr"
},
"Err": {
"postfix": "err",
"body": "Err(${receiver})",
"description": "Wrap the expression in a `Result::Err`",
"scope": "expr"
},
"Some": {
"postfix": "some",
"body": "Some(${receiver})",
"description": "Wrap the expression in an `Option::Some`",
"scope": "expr"
}
}"#).unwrap(),
/// Whether to enable term search based snippets like `Some(foo.bar().baz())`.
completion_termSearch_enable: bool = false,
/// Term search fuel in "units of work" for autocompletion (Defaults to 1000).
Expand Down Expand Up @@ -808,22 +768,14 @@ impl std::ops::Deref for Config {
}

impl Config {
/// Path to the root configuration file. This can be seen as a generic way to define what would be `$XDG_CONFIG_HOME/rust-analyzer/rust-analyzer.toml` in Linux.
/// This path is equal to:
///
/// |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 |
pub fn user_config_path() -> Option<&'static AbsPath> {
/// Path to the user configuration dir. This can be seen as a generic way to define what would be `$XDG_CONFIG_HOME/rust-analyzer` in Linux.
pub fn user_config_dir_path() -> Option<&'static AbsPath> {
static USER_CONFIG_PATH: LazyLock<Option<AbsPathBuf>> = LazyLock::new(|| {
let user_config_path = if let Some(path) = env::var_os("__TEST_RA_USER_CONFIG_DIR") {
std::path::PathBuf::from(path)
} else {
dirs::config_dir()?.join("rust-analyzer")
}
.join("rust-analyzer.toml");
};
Some(AbsPathBuf::assert_utf8(user_config_path))
});
USER_CONFIG_PATH.as_deref()
Expand Down Expand Up @@ -889,7 +841,7 @@ impl Config {
// IMPORTANT : This holds as long as ` completion_snippets_custom` is declared `client`.
config.snippets.clear();

let snips = self.completion_snippets_custom(None).to_owned();
let snips = self.completion_snippets_custom().to_owned();

for (name, def) in snips.iter() {
if def.prefix.is_empty() && def.postfix.is_empty() {
Expand Down Expand Up @@ -1266,7 +1218,7 @@ pub struct NotificationsConfig {
pub cargo_toml_not_found: bool,
}

#[derive(Debug, Clone)]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum RustfmtConfig {
Rustfmt { extra_args: Vec<String>, enable_range_formatting: bool },
CustomCommand { command: String, args: Vec<String> },
Expand Down Expand Up @@ -1897,6 +1849,53 @@ impl Config {
}
}

pub(crate) fn completion_snippets_default() -> FxHashMap<String, SnippetDef> {
serde_json::from_str(
r#"{
"Arc::new": {
"postfix": "arc",
"body": "Arc::new(${receiver})",
"requires": "std::sync::Arc",
"description": "Put the expression into an `Arc`",
"scope": "expr"
},
"Rc::new": {
"postfix": "rc",
"body": "Rc::new(${receiver})",
"requires": "std::rc::Rc",
"description": "Put the expression into an `Rc`",
"scope": "expr"
},
"Box::pin": {
"postfix": "pinbox",
"body": "Box::pin(${receiver})",
"requires": "std::boxed::Box",
"description": "Put the expression into a pinned `Box`",
"scope": "expr"
},
"Ok": {
"postfix": "ok",
"body": "Ok(${receiver})",
"description": "Wrap the expression in a `Result::Ok`",
"scope": "expr"
},
"Err": {
"postfix": "err",
"body": "Err(${receiver})",
"description": "Wrap the expression in a `Result::Err`",
"scope": "expr"
},
"Some": {
"postfix": "some",
"body": "Some(${receiver})",
"description": "Wrap the expression in an `Option::Some`",
"scope": "expr"
}
}"#,
)
.unwrap()
}

pub fn rustfmt(&self, source_root_id: Option<SourceRootId>) -> RustfmtConfig {
match &self.rustfmt_overrideCommand(source_root_id) {
Some(args) if !args.is_empty() => {
Expand Down
11 changes: 9 additions & 2 deletions crates/rust-analyzer/src/global_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,14 @@ impl GlobalState {
|| !self.config.same_source_root_parent_map(&self.local_roots_parent_map)
{
let config_change = {
let user_config_path = Config::user_config_path();
let user_config_path = {
let mut p = Config::user_config_dir_path().unwrap().to_path_buf();
p.push("rust-analyzer.toml");
p
};

let user_config_abs_path = Some(user_config_path.as_path());

let mut change = ConfigChange::default();
let db = self.analysis_host.raw_database();

Expand All @@ -399,7 +406,7 @@ impl GlobalState {
.collect_vec();

for (file_id, (_change_kind, vfs_path)) in modified_ratoml_files {
if vfs_path.as_path() == user_config_path {
if vfs_path.as_path() == user_config_abs_path {
change.change_user_config(Some(db.file_text(file_id)));
continue;
}
Expand Down
28 changes: 17 additions & 11 deletions crates/rust-analyzer/src/handlers/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@ use crate::{
hack_recover_crate_name,
line_index::LineEndings,
lsp::{
ext::InternalTestingFetchConfigParams,
ext::{
InternalTestingFetchConfigOption, InternalTestingFetchConfigParams,
InternalTestingFetchConfigResponse,
},
from_proto, to_proto,
utils::{all_edits_are_disjoint, invalid_params_error},
LspError,
Expand Down Expand Up @@ -2292,7 +2295,7 @@ pub(crate) fn fetch_dependency_list(
pub(crate) fn internal_testing_fetch_config(
state: GlobalStateSnapshot,
params: InternalTestingFetchConfigParams,
) -> anyhow::Result<serde_json::Value> {
) -> anyhow::Result<Option<InternalTestingFetchConfigResponse>> {
let source_root = params
.text_document
.map(|it| {
Expand All @@ -2302,15 +2305,18 @@ pub(crate) fn internal_testing_fetch_config(
.map_err(anyhow::Error::from)
})
.transpose()?;
serde_json::to_value(match &*params.config {
"local" => state.config.assist(source_root).assist_emit_must_use,
"workspace" => matches!(
state.config.rustfmt(source_root),
RustfmtConfig::Rustfmt { enable_range_formatting: true, .. }
),
_ => return Err(anyhow::anyhow!("Unknown test config key: {}", params.config)),
})
.map_err(Into::into)
Ok(Some(match params.config {
InternalTestingFetchConfigOption::AssistEmitMustUse => {
InternalTestingFetchConfigResponse::AssistEmitMustUse(
state.config.assist(source_root).assist_emit_must_use,
)
}
InternalTestingFetchConfigOption::CheckWorkspace => {
InternalTestingFetchConfigResponse::CheckWorkspace(
state.config.flycheck_workspace(source_root),
)
}
}))
}

/// Searches for the directory of a Rust crate given this crate's root file path.
Expand Down
17 changes: 15 additions & 2 deletions crates/rust-analyzer/src/lsp/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,30 @@ use serde::{Deserialize, Serialize};

pub enum InternalTestingFetchConfig {}

#[derive(Deserialize, Serialize, Debug)]
pub enum InternalTestingFetchConfigOption {
AssistEmitMustUse,
CheckWorkspace,
}

#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
pub enum InternalTestingFetchConfigResponse {
AssistEmitMustUse(bool),
CheckWorkspace(bool),
}

impl Request for InternalTestingFetchConfig {
type Params = InternalTestingFetchConfigParams;
type Result = serde_json::Value;
// Option is solely to circumvent Default bound.
type Result = Option<InternalTestingFetchConfigResponse>;
const METHOD: &'static str = "rust-analyzer-internal/internalTestingFetchConfig";
}

#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InternalTestingFetchConfigParams {
pub text_document: Option<TextDocumentIdentifier>,
pub config: String,
pub config: InternalTestingFetchConfigOption,
}
pub enum AnalyzerStatus {}

Expand Down
8 changes: 6 additions & 2 deletions crates/rust-analyzer/src/reload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,7 @@ impl GlobalState {
}

watchers.extend(
iter::once(Config::user_config_path())
iter::once(Config::user_config_dir_path())
.chain(self.workspaces.iter().map(|ws| ws.manifest().map(ManifestPath::as_ref)))
.flatten()
.map(|glob_pattern| lsp_types::FileSystemWatcher {
Expand All @@ -606,7 +606,11 @@ impl GlobalState {
}

let files_config = self.config.files();
let project_folders = ProjectFolders::new(&self.workspaces, &files_config.exclude);
let project_folders = ProjectFolders::new(
&self.workspaces,
&files_config.exclude,
Config::user_config_dir_path().to_owned(),
);

if (self.proc_macro_clients.is_empty() || !same_workspaces)
&& self.config.expand_proc_macros()
Expand Down
Loading
Loading