use std::{fmt, iter, ops::Not, sync::OnceLock};
use cfg::{CfgAtom, CfgDiff};
use dirs::config_dir;
use flycheck::{CargoOptions, FlycheckConfig};
use ide::{
AssistConfig, CallableSnippets, CompletionConfig, DiagnosticsConfig, ExprFillDefaultMode,
HighlightConfig, HighlightRelatedConfig, HoverConfig, HoverDocFormat, InlayFieldsToResolve,
InlayHintsConfig, JoinLinesConfig, MemoryLayoutHoverConfig, MemoryLayoutHoverRenderKind,
Snippet, SnippetScope, SourceRootId,
};
use ide_db::{
imports::insert_use::{ImportGranularity, InsertUseConfig, PrefixKind},
SnippetCap,
};
use indexmap::IndexMap;
use itertools::Itertools;
use lsp_types::{ClientCapabilities, MarkupKind};
use paths::{Utf8Path, Utf8PathBuf};
use project_model::{
CargoConfig, CargoFeatures, ProjectJson, ProjectJsonData, ProjectManifest, RustLibSource,
};
use rustc_hash::{FxHashMap, FxHashSet};
use semver::Version;
use serde::{
de::{DeserializeOwned, Error},
Deserialize, Serialize,
};
use stdx::format_to_acc;
use triomphe::Arc;
use vfs::{AbsPath, AbsPathBuf, VfsPath};
use crate::{
caps::completion_item_edit_resolve,
diagnostics::DiagnosticsMapConfig,
line_index::PositionEncoding,
lsp_ext::{self, negotiated_encoding, WorkspaceSymbolSearchKind, WorkspaceSymbolSearchScope},
};
mod patch_old_style;
config_data! {
global: struct GlobalDefaultConfigData <- GlobalConfigInput -> {
cachePriming_enable: bool = true,
cachePriming_numThreads: NumThreads = NumThreads::Physical,
cargo_allTargets: bool = true,
pub(crate) cargo_autoreload: bool = true,
cargo_buildScripts_enable: bool = true,
cargo_buildScripts_invocationLocation: InvocationLocation = InvocationLocation::Workspace,
cargo_buildScripts_invocationStrategy: InvocationStrategy = InvocationStrategy::PerWorkspace,
cargo_buildScripts_overrideCommand: Option<Vec<String>> = None,
cargo_buildScripts_rebuildOnSave: bool = true,
cargo_buildScripts_useRustcWrapper: bool = true,
cargo_cfgs: FxHashMap<String, Option<String>> = {
let mut m = FxHashMap::default();
m.insert("debug_assertions".to_owned(), None);
m.insert("miri".to_owned(), None);
m
},
cargo_extraArgs: Vec<String> = vec![],
cargo_extraEnv: FxHashMap<String, String> = FxHashMap::default(),
cargo_features: CargoFeaturesDef = CargoFeaturesDef::Selected(vec![]),
cargo_noDefaultFeatures: bool = false,
cargo_sysroot: Option<String> = Some("discover".to_owned()),
cargo_sysrootQueryMetadata: bool = false,
cargo_sysrootSrc: Option<String> = None,
cargo_target: Option<String> = None,
cargo_targetDir | ra_ap_rust_analyzerTargetDir: Option<TargetDirectory> = None,
checkOnSave | checkOnSave_enable: bool = true,
check_allTargets | checkOnSave_allTargets: Option<bool> = None,
check_command | checkOnSave_command: String = "check".to_owned(),
check_extraArgs | checkOnSave_extraArgs: Vec<String> = vec![],
check_extraEnv | checkOnSave_extraEnv: FxHashMap<String, String> = FxHashMap::default(),
check_features | checkOnSave_features: Option<CargoFeaturesDef> = None,
check_ignore: FxHashSet<String> = FxHashSet::default(),
check_invocationLocation | checkOnSave_invocationLocation: InvocationLocation = InvocationLocation::Workspace,
check_invocationStrategy | checkOnSave_invocationStrategy: InvocationStrategy = InvocationStrategy::PerWorkspace,
check_noDefaultFeatures | checkOnSave_noDefaultFeatures: Option<bool> = None,
check_overrideCommand | checkOnSave_overrideCommand: Option<Vec<String>> = None,
check_targets | checkOnSave_targets | checkOnSave_target: Option<CheckOnSaveTargets> = None,
check_workspace: bool = true,
diagnostics_disabled: FxHashSet<String> = FxHashSet::default(),
diagnostics_enable: bool = true,
diagnostics_experimental_enable: bool = false,
diagnostics_remapPrefix: FxHashMap<String, String> = FxHashMap::default(),
diagnostics_styleLints_enable: bool = false,
diagnostics_warningsAsHint: Vec<String> = vec![],
diagnostics_warningsAsInfo: Vec<String> = vec![],
files_excludeDirs: Vec<Utf8PathBuf> = vec![],
linkedProjects: Vec<ManifestOrProjectJson> = vec![],
lru_capacity: Option<usize> = None,
lru_query_capacities: FxHashMap<Box<str>, usize> = FxHashMap::default(),
procMacro_ignored: FxHashMap<Box<str>, Box<[Box<str>]>> = FxHashMap::default(),
runnables_command: Option<String> = None,
runnables_extraArgs: Vec<String> = vec![],
runnables_extraTestBinaryArgs: Vec<String> = vec!["--show-output".to_owned()],
rustc_source: Option<String> = None,
rustfmt_extraArgs: Vec<String> = vec![],
rustfmt_overrideCommand: Option<Vec<String>> = None,
rustfmt_rangeFormatting_enable: bool = false,
}
}
config_data! {
local: struct LocalDefaultConfigData <- LocalConfigInput -> {
assist_emitMustUse: bool = false,
assist_expressionFillDefault: ExprFillDefaultDef = ExprFillDefaultDef::Todo,
assist_termSearch_fuel: usize = 400,
imports_granularity_enforce: bool = false,
imports_granularity_group: ImportGranularityDef = ImportGranularityDef::Crate,
imports_group_enable: bool = true,
imports_merge_glob: bool = true,
imports_preferNoStd | imports_prefer_no_std: bool = false,
imports_preferPrelude: bool = false,
imports_prefix: ImportPrefixDef = ImportPrefixDef::Plain,
}
}
config_data! {
client: struct ClientDefaultConfigData <- ClientConfigInput -> {
completion_autoimport_enable: bool = true,
completion_autoself_enable: bool = true,
completion_callable_snippets: CallableCompletionDef = CallableCompletionDef::FillArguments,
completion_fullFunctionSignatures_enable: bool = false,
completion_limit: Option<usize> = None,
completion_postfix_enable: bool = true,
completion_privateEditable_enable: bool = false,
completion_snippets_custom: IndexMap<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(),
completion_termSearch_enable: bool = false,
completion_termSearch_fuel: usize = 200,
files_watcher: FilesWatcherDef = FilesWatcherDef::Client,
highlightRelated_breakPoints_enable: bool = true,
highlightRelated_closureCaptures_enable: bool = true,
highlightRelated_exitPoints_enable: bool = true,
highlightRelated_references_enable: bool = true,
highlightRelated_yieldPoints_enable: bool = true,
hover_actions_debug_enable: bool = true,
hover_actions_enable: bool = true,
hover_actions_gotoTypeDef_enable: bool = true,
hover_actions_implementations_enable: bool = true,
hover_actions_references_enable: bool = false,
hover_actions_run_enable: bool = true,
hover_documentation_enable: bool = true,
hover_documentation_keywords_enable: bool = true,
hover_links_enable: bool = true,
hover_memoryLayout_alignment: Option<MemoryLayoutHoverRenderKindDef> = Some(MemoryLayoutHoverRenderKindDef::Hexadecimal),
hover_memoryLayout_enable: bool = true,
hover_memoryLayout_niches: Option<bool> = Some(false),
hover_memoryLayout_offset: Option<MemoryLayoutHoverRenderKindDef> = Some(MemoryLayoutHoverRenderKindDef::Hexadecimal),
hover_memoryLayout_size: Option<MemoryLayoutHoverRenderKindDef> = Some(MemoryLayoutHoverRenderKindDef::Both),
hover_show_enumVariants: Option<usize> = Some(5),
hover_show_fields: Option<usize> = Some(5),
hover_show_traitAssocItems: Option<usize> = None,
inlayHints_bindingModeHints_enable: bool = false,
inlayHints_chainingHints_enable: bool = true,
inlayHints_closingBraceHints_enable: bool = true,
inlayHints_closingBraceHints_minLines: usize = 25,
inlayHints_closureCaptureHints_enable: bool = false,
inlayHints_closureReturnTypeHints_enable: ClosureReturnTypeHintsDef = ClosureReturnTypeHintsDef::Never,
inlayHints_closureStyle: ClosureStyle = ClosureStyle::ImplFn,
inlayHints_discriminantHints_enable: DiscriminantHintsDef = DiscriminantHintsDef::Never,
inlayHints_expressionAdjustmentHints_enable: AdjustmentHintsDef = AdjustmentHintsDef::Never,
inlayHints_expressionAdjustmentHints_hideOutsideUnsafe: bool = false,
inlayHints_expressionAdjustmentHints_mode: AdjustmentHintsModeDef = AdjustmentHintsModeDef::Prefix,
inlayHints_implicitDrops_enable: bool = false,
inlayHints_lifetimeElisionHints_enable: LifetimeElisionDef = LifetimeElisionDef::Never,
inlayHints_lifetimeElisionHints_useParameterNames: bool = false,
inlayHints_maxLength: Option<usize> = Some(25),
inlayHints_parameterHints_enable: bool = true,
inlayHints_rangeExclusiveHints_enable: bool = false,
inlayHints_reborrowHints_enable: ReborrowHintsDef = ReborrowHintsDef::Never,
inlayHints_renderColons: bool = true,
inlayHints_typeHints_enable: bool = true,
inlayHints_typeHints_hideClosureInitialization: bool = false,
inlayHints_typeHints_hideNamedConstructor: bool = false,
interpret_tests: bool = false,
joinLines_joinAssignments: bool = true,
joinLines_joinElseIf: bool = true,
joinLines_removeTrailingComma: bool = true,
joinLines_unwrapTrivialBlock: bool = true,
lens_debug_enable: bool = true,
lens_enable: bool = true,
lens_forceCustomCommands: bool = true,
lens_implementations_enable: bool = true,
lens_location: AnnotationLocation = AnnotationLocation::AboveName,
lens_references_adt_enable: bool = false,
lens_references_enumVariant_enable: bool = false,
lens_references_method_enable: bool = false,
lens_references_trait_enable: bool = false,
lens_run_enable: bool = true,
notifications_cargoTomlNotFound: bool = true,
notifications_unindexedProject: bool = false,
numThreads: Option<NumThreads> = None,
procMacro_attributes_enable: bool = true,
procMacro_enable: bool = true,
procMacro_server: Option<Utf8PathBuf> = None,
references_excludeImports: bool = false,
references_excludeTests: bool = false,
semanticHighlighting_doc_comment_inject_enable: bool = true,
semanticHighlighting_nonStandardTokens: bool = true,
semanticHighlighting_operator_enable: bool = true,
semanticHighlighting_operator_specialization_enable: bool = false,
semanticHighlighting_punctuation_enable: bool = false,
semanticHighlighting_punctuation_separate_macro_bang: bool = false,
semanticHighlighting_punctuation_specialization_enable: bool = false,
semanticHighlighting_strings_enable: bool = true,
signatureInfo_detail: SignatureDetail = SignatureDetail::Full,
signatureInfo_documentation_enable: bool = true,
typing_autoClosingAngleBrackets_enable: bool = false,
workspace_symbol_search_kind: WorkspaceSymbolSearchKindDef = WorkspaceSymbolSearchKindDef::OnlyTypes,
workspace_symbol_search_limit: usize = 128,
workspace_symbol_search_scope: WorkspaceSymbolSearchScopeDef = WorkspaceSymbolSearchScopeDef::Workspace,
}
}
#[derive(Debug, Clone)]
pub struct Config {
discovered_projects: Vec<ProjectManifest>,
workspace_roots: Vec<AbsPathBuf>,
caps: lsp_types::ClientCapabilities,
root_path: AbsPathBuf,
snippets: Vec<Snippet>,
visual_studio_code_version: Option<Version>,
default_config: &'static DefaultConfigData,
client_config: (FullConfigInput, ConfigErrors),
user_config_path: VfsPath,
user_config: Option<(GlobalLocalConfigInput, ConfigErrors)>,
root_ratoml_path: VfsPath,
root_ratoml: Option<(GlobalLocalConfigInput, ConfigErrors)>,
ratoml_files: FxHashMap<SourceRootId, (LocalConfigInput, ConfigErrors)>,
source_root_parent_map: Arc<FxHashMap<SourceRootId, SourceRootId>>,
detached_files: Vec<AbsPathBuf>,
}
impl Config {
pub fn user_config_path(&self) -> &VfsPath {
&self.user_config_path
}
pub fn same_source_root_parent_map(
&self,
other: &Arc<FxHashMap<SourceRootId, SourceRootId>>,
) -> bool {
Arc::ptr_eq(&self.source_root_parent_map, other)
}
fn apply_change_with_sink(&self, change: ConfigChange) -> (Config, bool) {
let mut config = self.clone();
let mut should_update = false;
if let Some(change) = change.user_config_change {
if let Ok(table) = toml::from_str(&change) {
let mut toml_errors = vec![];
validate_toml_table(
GlobalLocalConfigInput::FIELDS,
&table,
&mut String::new(),
&mut toml_errors,
);
config.user_config = Some((
GlobalLocalConfigInput::from_toml(table, &mut toml_errors),
ConfigErrors(
toml_errors
.into_iter()
.map(|(a, b)| ConfigErrorInner::Toml { config_key: a, error: b })
.map(Arc::new)
.collect(),
),
));
should_update = true;
}
}
if let Some(mut json) = change.client_config_change {
tracing::info!("updating config from JSON: {:#}", json);
if !(json.is_null() || json.as_object().map_or(false, |it| it.is_empty())) {
let mut json_errors = vec![];
let detached_files = get_field::<Vec<Utf8PathBuf>>(
&mut json,
&mut json_errors,
"detachedFiles",
None,
)
.unwrap_or_default()
.into_iter()
.map(AbsPathBuf::assert)
.collect();
patch_old_style::patch_json_for_outdated_configs(&mut json);
config.client_config = (
FullConfigInput::from_json(json, &mut json_errors),
ConfigErrors(
json_errors
.into_iter()
.map(|(a, b)| ConfigErrorInner::Json { config_key: a, error: b })
.map(Arc::new)
.collect(),
),
);
config.detached_files = detached_files;
}
should_update = true;
}
if let Some(change) = change.root_ratoml_change {
tracing::info!("updating root ra-toml config: {:#}", change);
#[allow(clippy::single_match)]
match toml::from_str(&change) {
Ok(table) => {
let mut toml_errors = vec![];
validate_toml_table(
GlobalLocalConfigInput::FIELDS,
&table,
&mut String::new(),
&mut toml_errors,
);
config.root_ratoml = Some((
GlobalLocalConfigInput::from_toml(table, &mut toml_errors),
ConfigErrors(
toml_errors
.into_iter()
.map(|(a, b)| ConfigErrorInner::Toml { config_key: a, error: b })
.map(Arc::new)
.collect(),
),
));
should_update = true;
}
Err(_) => (),
}
}
if let Some(change) = change.ratoml_file_change {
for (source_root_id, (_, text)) in change {
if let Some(text) = text {
let mut toml_errors = vec![];
tracing::info!("updating ra-toml config: {:#}", text);
#[allow(clippy::single_match)]
match toml::from_str(&text) {
Ok(table) => {
validate_toml_table(
&[LocalConfigInput::FIELDS],
&table,
&mut String::new(),
&mut toml_errors,
);
config.ratoml_files.insert(
source_root_id,
(
LocalConfigInput::from_toml(&table, &mut toml_errors),
ConfigErrors(
toml_errors
.into_iter()
.map(|(a, b)| ConfigErrorInner::Toml {
config_key: a,
error: b,
})
.map(Arc::new)
.collect(),
),
),
);
}
Err(_) => (),
}
}
}
}
if let Some(source_root_map) = change.source_map_change {
config.source_root_parent_map = source_root_map;
}
let snips = self.completion_snippets_custom().to_owned();
for (name, def) in snips.iter() {
if def.prefix.is_empty() && def.postfix.is_empty() {
continue;
}
let scope = match def.scope {
SnippetScopeDef::Expr => SnippetScope::Expr,
SnippetScopeDef::Type => SnippetScope::Type,
SnippetScopeDef::Item => SnippetScope::Item,
};
#[allow(clippy::single_match)]
match Snippet::new(
&def.prefix,
&def.postfix,
&def.body,
def.description.as_ref().unwrap_or(name),
&def.requires,
scope,
) {
Some(snippet) => config.snippets.push(snippet),
None => (),
}
}
(config, should_update)
}
pub fn apply_change(&self, change: ConfigChange) -> (Config, ConfigErrors, bool) {
let (config, should_update) = self.apply_change_with_sink(change);
let e = ConfigErrors(
config
.client_config
.1
.0
.iter()
.chain(config.root_ratoml.as_ref().into_iter().flat_map(|it| it.1 .0.iter()))
.chain(config.user_config.as_ref().into_iter().flat_map(|it| it.1 .0.iter()))
.chain(config.ratoml_files.values().flat_map(|it| it.1 .0.iter()))
.cloned()
.collect(),
);
(config, e, should_update)
}
}
#[derive(Default, Debug)]
pub struct ConfigChange {
user_config_change: Option<Arc<str>>,
root_ratoml_change: Option<Arc<str>>,
client_config_change: Option<serde_json::Value>,
ratoml_file_change: Option<FxHashMap<SourceRootId, (VfsPath, Option<Arc<str>>)>>,
source_map_change: Option<Arc<FxHashMap<SourceRootId, SourceRootId>>>,
}
impl ConfigChange {
pub fn change_ratoml(
&mut self,
source_root: SourceRootId,
vfs_path: VfsPath,
content: Option<Arc<str>>,
) -> Option<(VfsPath, Option<Arc<str>>)> {
self.ratoml_file_change
.get_or_insert_with(Default::default)
.insert(source_root, (vfs_path, content))
}
pub fn change_user_config(&mut self, content: Option<Arc<str>>) {
assert!(self.user_config_change.is_none()); self.user_config_change = content;
}
pub fn change_root_ratoml(&mut self, content: Option<Arc<str>>) {
assert!(self.root_ratoml_change.is_none()); self.root_ratoml_change = content;
}
pub fn change_client_config(&mut self, change: serde_json::Value) {
self.client_config_change = Some(change);
}
pub fn change_source_root_parent_map(
&mut self,
source_root_map: Arc<FxHashMap<SourceRootId, SourceRootId>>,
) {
assert!(self.source_map_change.is_none());
self.source_map_change = Some(source_root_map.clone());
}
}
macro_rules! try_ {
($expr:expr) => {
|| -> _ { Some($expr) }()
};
}
macro_rules! try_or {
($expr:expr, $or:expr) => {
try_!($expr).unwrap_or($or)
};
}
macro_rules! try_or_def {
($expr:expr) => {
try_!($expr).unwrap_or_default()
};
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum LinkedProject {
ProjectManifest(ProjectManifest),
InlineJsonProject(ProjectJson),
}
impl From<ProjectManifest> for LinkedProject {
fn from(v: ProjectManifest) -> Self {
LinkedProject::ProjectManifest(v)
}
}
impl From<ProjectJson> for LinkedProject {
fn from(v: ProjectJson) -> Self {
LinkedProject::InlineJsonProject(v)
}
}
pub struct CallInfoConfig {
pub params_only: bool,
pub docs: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LensConfig {
pub run: bool,
pub debug: bool,
pub interpret: bool,
pub implementations: bool,
pub method_refs: bool,
pub refs_adt: bool, pub refs_trait: bool, pub enum_variant_refs: bool,
pub location: AnnotationLocation,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AnnotationLocation {
AboveName,
AboveWholeItem,
}
impl From<AnnotationLocation> for ide::AnnotationLocation {
fn from(location: AnnotationLocation) -> Self {
match location {
AnnotationLocation::AboveName => ide::AnnotationLocation::AboveName,
AnnotationLocation::AboveWholeItem => ide::AnnotationLocation::AboveWholeItem,
}
}
}
impl LensConfig {
pub fn any(&self) -> bool {
self.run
|| self.debug
|| self.implementations
|| self.method_refs
|| self.refs_adt
|| self.refs_trait
|| self.enum_variant_refs
}
pub fn none(&self) -> bool {
!self.any()
}
pub fn runnable(&self) -> bool {
self.run || self.debug
}
pub fn references(&self) -> bool {
self.method_refs || self.refs_adt || self.refs_trait || self.enum_variant_refs
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HoverActionsConfig {
pub implementations: bool,
pub references: bool,
pub run: bool,
pub debug: bool,
pub goto_type_def: bool,
}
impl HoverActionsConfig {
pub const NO_ACTIONS: Self = Self {
implementations: false,
references: false,
run: false,
debug: false,
goto_type_def: false,
};
pub fn any(&self) -> bool {
self.implementations || self.references || self.runnable() || self.goto_type_def
}
pub fn none(&self) -> bool {
!self.any()
}
pub fn runnable(&self) -> bool {
self.run || self.debug
}
}
#[derive(Debug, Clone)]
pub struct FilesConfig {
pub watcher: FilesWatcher,
pub exclude: Vec<AbsPathBuf>,
}
#[derive(Debug, Clone)]
pub enum FilesWatcher {
Client,
Server,
}
#[derive(Debug, Clone)]
pub struct NotificationsConfig {
pub cargo_toml_not_found: bool,
pub unindexed_project: bool,
}
#[derive(Debug, Clone)]
pub enum RustfmtConfig {
Rustfmt { extra_args: Vec<String>, enable_range_formatting: bool },
CustomCommand { command: String, args: Vec<String> },
}
#[derive(Debug, Clone)]
pub struct RunnablesConfig {
pub override_cargo: Option<String>,
pub cargo_extra_args: Vec<String>,
pub extra_test_binary_args: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct WorkspaceSymbolConfig {
pub search_scope: WorkspaceSymbolSearchScope,
pub search_kind: WorkspaceSymbolSearchKind,
pub search_limit: usize,
}
pub struct ClientCommandsConfig {
pub run_single: bool,
pub debug_single: bool,
pub show_reference: bool,
pub goto_location: bool,
pub trigger_parameter_hints: bool,
}
#[derive(Debug)]
pub enum ConfigErrorInner {
Json { config_key: String, error: serde_json::Error },
Toml { config_key: String, error: toml::de::Error },
}
#[derive(Clone, Debug)]
pub struct ConfigErrors(Vec<Arc<ConfigErrorInner>>);
impl ConfigErrors {
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl fmt::Display for ConfigErrors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let errors = self.0.iter().format_with("\n", |inner, f| match &**inner {
ConfigErrorInner::Json { config_key: key, error: e } => {
f(key)?;
f(&": ")?;
f(e)
}
ConfigErrorInner::Toml { config_key: key, error: e } => {
f(key)?;
f(&": ")?;
f(e)
}
});
write!(f, "invalid config value{}:\n{}", if self.0.len() == 1 { "" } else { "s" }, errors)
}
}
impl std::error::Error for ConfigErrors {}
impl Config {
pub fn new(
root_path: AbsPathBuf,
caps: ClientCapabilities,
workspace_roots: Vec<AbsPathBuf>,
visual_studio_code_version: Option<Version>,
user_config_path: Option<Utf8PathBuf>,
) -> Self {
static DEFAULT_CONFIG_DATA: OnceLock<&'static DefaultConfigData> = OnceLock::new();
let user_config_path = if let Some(user_config_path) = user_config_path {
user_config_path.join("rust-analyzer").join("rust-analyzer.toml")
} else {
let p = config_dir()
.expect("A config dir is expected to existed on all platforms ra supports.")
.join("rust-analyzer")
.join("rust-analyzer.toml");
Utf8PathBuf::from_path_buf(p).expect("Config dir expected to be abs.")
};
let user_config_path = VfsPath::from(AbsPathBuf::assert(user_config_path));
let root_ratoml_path = {
let mut p = root_path.clone();
p.push("rust-analyzer.toml");
VfsPath::new_real_path(p.to_string())
};
Config {
caps,
discovered_projects: Vec::new(),
root_path,
snippets: Default::default(),
workspace_roots,
visual_studio_code_version,
client_config: (FullConfigInput::default(), ConfigErrors(vec![])),
ratoml_files: FxHashMap::default(),
default_config: DEFAULT_CONFIG_DATA.get_or_init(|| Box::leak(Box::default())),
source_root_parent_map: Arc::new(FxHashMap::default()),
user_config: None,
user_config_path,
root_ratoml: None,
root_ratoml_path,
detached_files: Default::default(),
}
}
pub fn rediscover_workspaces(&mut self) {
let discovered = ProjectManifest::discover_all(&self.workspace_roots);
tracing::info!("discovered projects: {:?}", discovered);
if discovered.is_empty() {
tracing::error!("failed to find any projects in {:?}", &self.workspace_roots);
}
self.discovered_projects = discovered;
}
pub fn remove_workspace(&mut self, path: &AbsPath) {
if let Some(position) = self.workspace_roots.iter().position(|it| it == path) {
self.workspace_roots.remove(position);
}
}
pub fn add_workspaces(&mut self, paths: impl Iterator<Item = AbsPathBuf>) {
self.workspace_roots.extend(paths);
}
pub fn json_schema() -> serde_json::Value {
FullConfigInput::json_schema()
}
pub fn root_path(&self) -> &AbsPathBuf {
&self.root_path
}
pub fn root_ratoml_path(&self) -> &VfsPath {
&self.root_ratoml_path
}
pub fn caps(&self) -> &lsp_types::ClientCapabilities {
&self.caps
}
}
impl Config {
pub fn assist(&self, source_root: Option<SourceRootId>) -> AssistConfig {
AssistConfig {
snippet_cap: self.snippet_cap(),
allowed: None,
insert_use: self.insert_use_config(source_root),
prefer_no_std: self.imports_preferNoStd(source_root).to_owned(),
assist_emit_must_use: self.assist_emitMustUse(source_root).to_owned(),
prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
term_search_fuel: self.assist_termSearch_fuel(source_root).to_owned() as u64,
}
}
pub fn completion(&self, source_root: Option<SourceRootId>) -> CompletionConfig {
CompletionConfig {
enable_postfix_completions: self.completion_postfix_enable().to_owned(),
enable_imports_on_the_fly: self.completion_autoimport_enable().to_owned()
&& completion_item_edit_resolve(&self.caps),
enable_self_on_the_fly: self.completion_autoself_enable().to_owned(),
enable_private_editable: self.completion_privateEditable_enable().to_owned(),
full_function_signatures: self.completion_fullFunctionSignatures_enable().to_owned(),
callable: match self.completion_callable_snippets() {
CallableCompletionDef::FillArguments => Some(CallableSnippets::FillArguments),
CallableCompletionDef::AddParentheses => Some(CallableSnippets::AddParentheses),
CallableCompletionDef::None => None,
},
snippet_cap: SnippetCap::new(try_or_def!(
self.caps
.text_document
.as_ref()?
.completion
.as_ref()?
.completion_item
.as_ref()?
.snippet_support?
)),
insert_use: self.insert_use_config(source_root),
prefer_no_std: self.imports_preferNoStd(source_root).to_owned(),
prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
snippets: self.snippets.clone().to_vec(),
limit: self.completion_limit().to_owned(),
enable_term_search: self.completion_termSearch_enable().to_owned(),
term_search_fuel: self.completion_termSearch_fuel().to_owned() as u64,
}
}
pub fn detached_files(&self) -> &Vec<AbsPathBuf> {
&self.detached_files
}
pub fn diagnostics(&self, source_root: Option<SourceRootId>) -> DiagnosticsConfig {
DiagnosticsConfig {
enabled: *self.diagnostics_enable(),
proc_attr_macros_enabled: self.expand_proc_attr_macros(),
proc_macros_enabled: *self.procMacro_enable(),
disable_experimental: !self.diagnostics_experimental_enable(),
disabled: self.diagnostics_disabled().clone(),
expr_fill_default: match self.assist_expressionFillDefault(source_root) {
ExprFillDefaultDef::Todo => ExprFillDefaultMode::Todo,
ExprFillDefaultDef::Default => ExprFillDefaultMode::Default,
},
snippet_cap: self.snippet_cap(),
insert_use: self.insert_use_config(source_root),
prefer_no_std: self.imports_preferNoStd(source_root).to_owned(),
prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
style_lints: self.diagnostics_styleLints_enable().to_owned(),
term_search_fuel: self.assist_termSearch_fuel(source_root).to_owned() as u64,
}
}
pub fn expand_proc_attr_macros(&self) -> bool {
self.procMacro_enable().to_owned() && self.procMacro_attributes_enable().to_owned()
}
pub fn highlight_related(&self, _source_root: Option<SourceRootId>) -> HighlightRelatedConfig {
HighlightRelatedConfig {
references: self.highlightRelated_references_enable().to_owned(),
break_points: self.highlightRelated_breakPoints_enable().to_owned(),
exit_points: self.highlightRelated_exitPoints_enable().to_owned(),
yield_points: self.highlightRelated_yieldPoints_enable().to_owned(),
closure_captures: self.highlightRelated_closureCaptures_enable().to_owned(),
}
}
pub fn hover_actions(&self) -> HoverActionsConfig {
let enable = self.experimental("hoverActions") && self.hover_actions_enable().to_owned();
HoverActionsConfig {
implementations: enable && self.hover_actions_implementations_enable().to_owned(),
references: enable && self.hover_actions_references_enable().to_owned(),
run: enable && self.hover_actions_run_enable().to_owned(),
debug: enable && self.hover_actions_debug_enable().to_owned(),
goto_type_def: enable && self.hover_actions_gotoTypeDef_enable().to_owned(),
}
}
pub fn hover(&self) -> HoverConfig {
let mem_kind = |kind| match kind {
MemoryLayoutHoverRenderKindDef::Both => MemoryLayoutHoverRenderKind::Both,
MemoryLayoutHoverRenderKindDef::Decimal => MemoryLayoutHoverRenderKind::Decimal,
MemoryLayoutHoverRenderKindDef::Hexadecimal => MemoryLayoutHoverRenderKind::Hexadecimal,
};
HoverConfig {
links_in_hover: self.hover_links_enable().to_owned(),
memory_layout: self.hover_memoryLayout_enable().then_some(MemoryLayoutHoverConfig {
size: self.hover_memoryLayout_size().map(mem_kind),
offset: self.hover_memoryLayout_offset().map(mem_kind),
alignment: self.hover_memoryLayout_alignment().map(mem_kind),
niches: self.hover_memoryLayout_niches().unwrap_or_default(),
}),
documentation: self.hover_documentation_enable().to_owned(),
format: {
let is_markdown = try_or_def!(self
.caps
.text_document
.as_ref()?
.hover
.as_ref()?
.content_format
.as_ref()?
.as_slice())
.contains(&MarkupKind::Markdown);
if is_markdown {
HoverDocFormat::Markdown
} else {
HoverDocFormat::PlainText
}
},
keywords: self.hover_documentation_keywords_enable().to_owned(),
max_trait_assoc_items_count: self.hover_show_traitAssocItems().to_owned(),
max_fields_count: self.hover_show_fields().to_owned(),
max_enum_variants_count: self.hover_show_enumVariants().to_owned(),
}
}
pub fn inlay_hints(&self) -> InlayHintsConfig {
let client_capability_fields = self
.caps
.text_document
.as_ref()
.and_then(|text| text.inlay_hint.as_ref())
.and_then(|inlay_hint_caps| inlay_hint_caps.resolve_support.as_ref())
.map(|inlay_resolve| inlay_resolve.properties.iter())
.into_iter()
.flatten()
.cloned()
.collect::<FxHashSet<_>>();
InlayHintsConfig {
render_colons: self.inlayHints_renderColons().to_owned(),
type_hints: self.inlayHints_typeHints_enable().to_owned(),
parameter_hints: self.inlayHints_parameterHints_enable().to_owned(),
chaining_hints: self.inlayHints_chainingHints_enable().to_owned(),
discriminant_hints: match self.inlayHints_discriminantHints_enable() {
DiscriminantHintsDef::Always => ide::DiscriminantHints::Always,
DiscriminantHintsDef::Never => ide::DiscriminantHints::Never,
DiscriminantHintsDef::Fieldless => ide::DiscriminantHints::Fieldless,
},
closure_return_type_hints: match self.inlayHints_closureReturnTypeHints_enable() {
ClosureReturnTypeHintsDef::Always => ide::ClosureReturnTypeHints::Always,
ClosureReturnTypeHintsDef::Never => ide::ClosureReturnTypeHints::Never,
ClosureReturnTypeHintsDef::WithBlock => ide::ClosureReturnTypeHints::WithBlock,
},
lifetime_elision_hints: match self.inlayHints_lifetimeElisionHints_enable() {
LifetimeElisionDef::Always => ide::LifetimeElisionHints::Always,
LifetimeElisionDef::Never => ide::LifetimeElisionHints::Never,
LifetimeElisionDef::SkipTrivial => ide::LifetimeElisionHints::SkipTrivial,
},
hide_named_constructor_hints: self
.inlayHints_typeHints_hideNamedConstructor()
.to_owned(),
hide_closure_initialization_hints: self
.inlayHints_typeHints_hideClosureInitialization()
.to_owned(),
closure_style: match self.inlayHints_closureStyle() {
ClosureStyle::ImplFn => hir::ClosureStyle::ImplFn,
ClosureStyle::RustAnalyzer => hir::ClosureStyle::RANotation,
ClosureStyle::WithId => hir::ClosureStyle::ClosureWithId,
ClosureStyle::Hide => hir::ClosureStyle::Hide,
},
closure_capture_hints: self.inlayHints_closureCaptureHints_enable().to_owned(),
adjustment_hints: match self.inlayHints_expressionAdjustmentHints_enable() {
AdjustmentHintsDef::Always => ide::AdjustmentHints::Always,
AdjustmentHintsDef::Never => match self.inlayHints_reborrowHints_enable() {
ReborrowHintsDef::Always | ReborrowHintsDef::Mutable => {
ide::AdjustmentHints::ReborrowOnly
}
ReborrowHintsDef::Never => ide::AdjustmentHints::Never,
},
AdjustmentHintsDef::Reborrow => ide::AdjustmentHints::ReborrowOnly,
},
adjustment_hints_mode: match self.inlayHints_expressionAdjustmentHints_mode() {
AdjustmentHintsModeDef::Prefix => ide::AdjustmentHintsMode::Prefix,
AdjustmentHintsModeDef::Postfix => ide::AdjustmentHintsMode::Postfix,
AdjustmentHintsModeDef::PreferPrefix => ide::AdjustmentHintsMode::PreferPrefix,
AdjustmentHintsModeDef::PreferPostfix => ide::AdjustmentHintsMode::PreferPostfix,
},
adjustment_hints_hide_outside_unsafe: self
.inlayHints_expressionAdjustmentHints_hideOutsideUnsafe()
.to_owned(),
binding_mode_hints: self.inlayHints_bindingModeHints_enable().to_owned(),
param_names_for_lifetime_elision_hints: self
.inlayHints_lifetimeElisionHints_useParameterNames()
.to_owned(),
max_length: self.inlayHints_maxLength().to_owned(),
closing_brace_hints_min_lines: if self.inlayHints_closingBraceHints_enable().to_owned()
{
Some(self.inlayHints_closingBraceHints_minLines().to_owned())
} else {
None
},
fields_to_resolve: InlayFieldsToResolve {
resolve_text_edits: client_capability_fields.contains("textEdits"),
resolve_hint_tooltip: client_capability_fields.contains("tooltip"),
resolve_label_tooltip: client_capability_fields.contains("label.tooltip"),
resolve_label_location: client_capability_fields.contains("label.location"),
resolve_label_command: client_capability_fields.contains("label.command"),
},
implicit_drop_hints: self.inlayHints_implicitDrops_enable().to_owned(),
range_exclusive_hints: self.inlayHints_rangeExclusiveHints_enable().to_owned(),
}
}
fn insert_use_config(&self, source_root: Option<SourceRootId>) -> InsertUseConfig {
InsertUseConfig {
granularity: match self.imports_granularity_group(source_root) {
ImportGranularityDef::Preserve => ImportGranularity::Preserve,
ImportGranularityDef::Item => ImportGranularity::Item,
ImportGranularityDef::Crate => ImportGranularity::Crate,
ImportGranularityDef::Module => ImportGranularity::Module,
ImportGranularityDef::One => ImportGranularity::One,
},
enforce_granularity: self.imports_granularity_enforce(source_root).to_owned(),
prefix_kind: match self.imports_prefix(source_root) {
ImportPrefixDef::Plain => PrefixKind::Plain,
ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
ImportPrefixDef::BySelf => PrefixKind::BySelf,
},
group: self.imports_group_enable(source_root).to_owned(),
skip_glob_imports: !self.imports_merge_glob(source_root),
}
}
pub fn join_lines(&self) -> JoinLinesConfig {
JoinLinesConfig {
join_else_if: self.joinLines_joinElseIf().to_owned(),
remove_trailing_comma: self.joinLines_removeTrailingComma().to_owned(),
unwrap_trivial_blocks: self.joinLines_unwrapTrivialBlock().to_owned(),
join_assignments: self.joinLines_joinAssignments().to_owned(),
}
}
pub fn highlighting_non_standard_tokens(&self) -> bool {
self.semanticHighlighting_nonStandardTokens().to_owned()
}
pub fn highlighting_config(&self) -> HighlightConfig {
HighlightConfig {
strings: self.semanticHighlighting_strings_enable().to_owned(),
punctuation: self.semanticHighlighting_punctuation_enable().to_owned(),
specialize_punctuation: self
.semanticHighlighting_punctuation_specialization_enable()
.to_owned(),
macro_bang: self.semanticHighlighting_punctuation_separate_macro_bang().to_owned(),
operator: self.semanticHighlighting_operator_enable().to_owned(),
specialize_operator: self
.semanticHighlighting_operator_specialization_enable()
.to_owned(),
inject_doc_comment: self.semanticHighlighting_doc_comment_inject_enable().to_owned(),
syntactic_name_ref_highlighting: false,
}
}
pub fn has_linked_projects(&self) -> bool {
!self.linkedProjects().is_empty()
}
pub fn linked_manifests(&self) -> impl Iterator<Item = &Utf8Path> + '_ {
self.linkedProjects().iter().filter_map(|it| match it {
ManifestOrProjectJson::Manifest(p) => Some(&**p),
ManifestOrProjectJson::ProjectJson(_) => None,
})
}
pub fn has_linked_project_jsons(&self) -> bool {
self.linkedProjects().iter().any(|it| matches!(it, ManifestOrProjectJson::ProjectJson(_)))
}
pub fn linked_or_discovered_projects(&self) -> Vec<LinkedProject> {
match self.linkedProjects().as_slice() {
[] => {
let exclude_dirs: Vec<_> =
self.files_excludeDirs().iter().map(|p| self.root_path.join(p)).collect();
self.discovered_projects
.iter()
.filter(|project| {
!exclude_dirs.iter().any(|p| project.manifest_path().starts_with(p))
})
.cloned()
.map(LinkedProject::from)
.collect()
}
linked_projects => linked_projects
.iter()
.filter_map(|linked_project| match linked_project {
ManifestOrProjectJson::Manifest(it) => {
let path = self.root_path.join(it);
ProjectManifest::from_manifest_file(path)
.map_err(|e| tracing::error!("failed to load linked project: {}", e))
.ok()
.map(Into::into)
}
ManifestOrProjectJson::ProjectJson(it) => {
Some(ProjectJson::new(None, &self.root_path, it.clone()).into())
}
})
.collect(),
}
}
pub fn did_save_text_document_dynamic_registration(&self) -> bool {
let caps = try_or_def!(self.caps.text_document.as_ref()?.synchronization.clone()?);
caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
}
pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
try_or_def!(
self.caps.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration?
)
}
pub fn did_change_watched_files_relative_pattern_support(&self) -> bool {
try_or_def!(
self.caps
.workspace
.as_ref()?
.did_change_watched_files
.as_ref()?
.relative_pattern_support?
)
}
pub fn prefill_caches(&self) -> bool {
self.cachePriming_enable().to_owned()
}
pub fn location_link(&self) -> bool {
try_or_def!(self.caps.text_document.as_ref()?.definition?.link_support?)
}
pub fn line_folding_only(&self) -> bool {
try_or_def!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?)
}
pub fn hierarchical_symbols(&self) -> bool {
try_or_def!(
self.caps
.text_document
.as_ref()?
.document_symbol
.as_ref()?
.hierarchical_document_symbol_support?
)
}
pub fn code_action_literals(&self) -> bool {
try_!(self
.caps
.text_document
.as_ref()?
.code_action
.as_ref()?
.code_action_literal_support
.as_ref()?)
.is_some()
}
pub fn work_done_progress(&self) -> bool {
try_or_def!(self.caps.window.as_ref()?.work_done_progress?)
}
pub fn will_rename(&self) -> bool {
try_or_def!(self.caps.workspace.as_ref()?.file_operations.as_ref()?.will_rename?)
}
pub fn change_annotation_support(&self) -> bool {
try_!(self
.caps
.workspace
.as_ref()?
.workspace_edit
.as_ref()?
.change_annotation_support
.as_ref()?)
.is_some()
}
pub fn code_action_resolve(&self) -> bool {
try_or_def!(self
.caps
.text_document
.as_ref()?
.code_action
.as_ref()?
.resolve_support
.as_ref()?
.properties
.as_slice())
.iter()
.any(|it| it == "edit")
}
pub fn signature_help_label_offsets(&self) -> bool {
try_or_def!(
self.caps
.text_document
.as_ref()?
.signature_help
.as_ref()?
.signature_information
.as_ref()?
.parameter_information
.as_ref()?
.label_offset_support?
)
}
pub fn completion_label_details_support(&self) -> bool {
try_!(self
.caps
.text_document
.as_ref()?
.completion
.as_ref()?
.completion_item
.as_ref()?
.label_details_support
.as_ref()?)
.is_some()
}
pub fn semantics_tokens_augments_syntax_tokens(&self) -> bool {
try_!(self.caps.text_document.as_ref()?.semantic_tokens.as_ref()?.augments_syntax_tokens?)
.unwrap_or(false)
}
pub fn position_encoding(&self) -> PositionEncoding {
negotiated_encoding(&self.caps)
}
fn experimental(&self, index: &'static str) -> bool {
try_or_def!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?)
}
pub fn code_action_group(&self) -> bool {
self.experimental("codeActionGroup")
}
pub fn local_docs(&self) -> bool {
self.experimental("localDocs")
}
pub fn open_server_logs(&self) -> bool {
self.experimental("openServerLogs")
}
pub fn server_status_notification(&self) -> bool {
self.experimental("serverStatusNotification")
}
pub fn color_diagnostic_output(&self) -> bool {
self.experimental("colorDiagnosticOutput")
}
pub fn test_explorer(&self) -> bool {
self.experimental("testExplorer")
}
pub fn publish_diagnostics(&self) -> bool {
self.diagnostics_enable().to_owned()
}
pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
DiagnosticsMapConfig {
remap_prefix: self.diagnostics_remapPrefix().clone(),
warnings_as_info: self.diagnostics_warningsAsInfo().clone(),
warnings_as_hint: self.diagnostics_warningsAsHint().clone(),
check_ignore: self.check_ignore().clone(),
}
}
pub fn extra_args(&self) -> &Vec<String> {
self.cargo_extraArgs()
}
pub fn extra_env(&self) -> &FxHashMap<String, String> {
self.cargo_extraEnv()
}
pub fn check_extra_args(&self) -> Vec<String> {
let mut extra_args = self.extra_args().clone();
extra_args.extend_from_slice(self.check_extraArgs());
extra_args
}
pub fn check_extra_env(&self) -> FxHashMap<String, String> {
let mut extra_env = self.cargo_extraEnv().clone();
extra_env.extend(self.check_extraEnv().clone());
extra_env
}
pub fn lru_parse_query_capacity(&self) -> Option<usize> {
self.lru_capacity().to_owned()
}
pub fn lru_query_capacities_config(&self) -> Option<&FxHashMap<Box<str>, usize>> {
self.lru_query_capacities().is_empty().not().then(|| self.lru_query_capacities())
}
pub fn proc_macro_srv(&self) -> Option<AbsPathBuf> {
let path = self.procMacro_server().clone()?;
Some(AbsPathBuf::try_from(path).unwrap_or_else(|path| self.root_path.join(path)))
}
pub fn ignored_proc_macros(&self) -> &FxHashMap<Box<str>, Box<[Box<str>]>> {
self.procMacro_ignored()
}
pub fn expand_proc_macros(&self) -> bool {
self.procMacro_enable().to_owned()
}
pub fn files(&self) -> FilesConfig {
FilesConfig {
watcher: match self.files_watcher() {
FilesWatcherDef::Client if self.did_change_watched_files_dynamic_registration() => {
FilesWatcher::Client
}
_ => FilesWatcher::Server,
},
exclude: self.files_excludeDirs().iter().map(|it| self.root_path.join(it)).collect(),
}
}
pub fn notifications(&self) -> NotificationsConfig {
NotificationsConfig {
cargo_toml_not_found: self.notifications_cargoTomlNotFound().to_owned(),
unindexed_project: self.notifications_unindexedProject().to_owned(),
}
}
pub fn cargo_autoreload_config(&self) -> bool {
self.cargo_autoreload().to_owned()
}
pub fn run_build_scripts(&self) -> bool {
self.cargo_buildScripts_enable().to_owned() || self.procMacro_enable().to_owned()
}
pub fn cargo(&self) -> CargoConfig {
let rustc_source = self.rustc_source().as_ref().map(|rustc_src| {
if rustc_src == "discover" {
RustLibSource::Discover
} else {
RustLibSource::Path(self.root_path.join(rustc_src))
}
});
let sysroot = self.cargo_sysroot().as_ref().map(|sysroot| {
if sysroot == "discover" {
RustLibSource::Discover
} else {
RustLibSource::Path(self.root_path.join(sysroot))
}
});
let sysroot_src =
self.cargo_sysrootSrc().as_ref().map(|sysroot| self.root_path.join(sysroot));
let sysroot_query_metadata = self.cargo_sysrootQueryMetadata();
CargoConfig {
all_targets: *self.cargo_allTargets(),
features: match &self.cargo_features() {
CargoFeaturesDef::All => CargoFeatures::All,
CargoFeaturesDef::Selected(features) => CargoFeatures::Selected {
features: features.clone(),
no_default_features: self.cargo_noDefaultFeatures().to_owned(),
},
},
target: self.cargo_target().clone(),
sysroot,
sysroot_query_metadata: *sysroot_query_metadata,
sysroot_src,
rustc_source,
cfg_overrides: project_model::CfgOverrides {
global: CfgDiff::new(
self.cargo_cfgs()
.iter()
.map(|(key, val)| match val {
Some(val) => CfgAtom::KeyValue { key: key.into(), value: val.into() },
None => CfgAtom::Flag(key.into()),
})
.collect(),
vec![],
)
.unwrap(),
selective: Default::default(),
},
wrap_rustc_in_build_scripts: *self.cargo_buildScripts_useRustcWrapper(),
invocation_strategy: match self.cargo_buildScripts_invocationStrategy() {
InvocationStrategy::Once => project_model::InvocationStrategy::Once,
InvocationStrategy::PerWorkspace => project_model::InvocationStrategy::PerWorkspace,
},
invocation_location: match self.cargo_buildScripts_invocationLocation() {
InvocationLocation::Root => {
project_model::InvocationLocation::Root(self.root_path.clone())
}
InvocationLocation::Workspace => project_model::InvocationLocation::Workspace,
},
run_build_script_command: self.cargo_buildScripts_overrideCommand().clone(),
extra_args: self.cargo_extraArgs().clone(),
extra_env: self.cargo_extraEnv().clone(),
target_dir: self.target_dir_from_config(),
}
}
pub fn rustfmt(&self) -> RustfmtConfig {
match &self.rustfmt_overrideCommand() {
Some(args) if !args.is_empty() => {
let mut args = args.clone();
let command = args.remove(0);
RustfmtConfig::CustomCommand { command, args }
}
Some(_) | None => RustfmtConfig::Rustfmt {
extra_args: self.rustfmt_extraArgs().clone(),
enable_range_formatting: *self.rustfmt_rangeFormatting_enable(),
},
}
}
pub fn flycheck_workspace(&self) -> bool {
*self.check_workspace()
}
pub fn cargo_test_options(&self) -> CargoOptions {
CargoOptions {
target_triples: self.cargo_target().clone().into_iter().collect(),
all_targets: false,
no_default_features: *self.cargo_noDefaultFeatures(),
all_features: matches!(self.cargo_features(), CargoFeaturesDef::All),
features: match self.cargo_features().clone() {
CargoFeaturesDef::All => vec![],
CargoFeaturesDef::Selected(it) => it,
},
extra_args: self.extra_args().clone(),
extra_env: self.extra_env().clone(),
target_dir: self.target_dir_from_config(),
}
}
pub fn flycheck(&self) -> FlycheckConfig {
match &self.check_overrideCommand() {
Some(args) if !args.is_empty() => {
let mut args = args.clone();
let command = args.remove(0);
FlycheckConfig::CustomCommand {
command,
args,
extra_env: self.check_extra_env(),
invocation_strategy: match self.check_invocationStrategy() {
InvocationStrategy::Once => flycheck::InvocationStrategy::Once,
InvocationStrategy::PerWorkspace => {
flycheck::InvocationStrategy::PerWorkspace
}
},
invocation_location: match self.check_invocationLocation() {
InvocationLocation::Root => {
flycheck::InvocationLocation::Root(self.root_path.clone())
}
InvocationLocation::Workspace => flycheck::InvocationLocation::Workspace,
},
}
}
Some(_) | None => FlycheckConfig::CargoCommand {
command: self.check_command().clone(),
options: CargoOptions {
target_triples: self
.check_targets()
.clone()
.and_then(|targets| match &targets.0[..] {
[] => None,
targets => Some(targets.into()),
})
.unwrap_or_else(|| self.cargo_target().clone().into_iter().collect()),
all_targets: self.check_allTargets().unwrap_or(*self.cargo_allTargets()),
no_default_features: self
.check_noDefaultFeatures()
.unwrap_or(*self.cargo_noDefaultFeatures()),
all_features: matches!(
self.check_features().as_ref().unwrap_or(self.cargo_features()),
CargoFeaturesDef::All
),
features: match self
.check_features()
.clone()
.unwrap_or_else(|| self.cargo_features().clone())
{
CargoFeaturesDef::All => vec![],
CargoFeaturesDef::Selected(it) => it,
},
extra_args: self.check_extra_args(),
extra_env: self.check_extra_env(),
target_dir: self.target_dir_from_config(),
},
ansi_color_output: self.color_diagnostic_output(),
},
}
}
fn target_dir_from_config(&self) -> Option<Utf8PathBuf> {
self.cargo_targetDir().as_ref().and_then(|target_dir| match target_dir {
TargetDirectory::UseSubdirectory(true) => {
Some(Utf8PathBuf::from("target/rust-analyzer"))
}
TargetDirectory::UseSubdirectory(false) => None,
TargetDirectory::Directory(dir) if dir.is_relative() => Some(dir.clone()),
TargetDirectory::Directory(_) => None,
})
}
pub fn check_on_save(&self) -> bool {
*self.checkOnSave()
}
pub fn script_rebuild_on_save(&self) -> bool {
*self.cargo_buildScripts_rebuildOnSave()
}
pub fn runnables(&self) -> RunnablesConfig {
RunnablesConfig {
override_cargo: self.runnables_command().clone(),
cargo_extra_args: self.runnables_extraArgs().clone(),
extra_test_binary_args: self.runnables_extraTestBinaryArgs().clone(),
}
}
pub fn find_all_refs_exclude_imports(&self) -> bool {
*self.references_excludeImports()
}
pub fn find_all_refs_exclude_tests(&self) -> bool {
*self.references_excludeTests()
}
pub fn snippet_cap(&self) -> Option<SnippetCap> {
SnippetCap::new(self.experimental("snippetTextEdit"))
}
pub fn call_info(&self) -> CallInfoConfig {
CallInfoConfig {
params_only: matches!(self.signatureInfo_detail(), SignatureDetail::Parameters),
docs: *self.signatureInfo_documentation_enable(),
}
}
pub fn lens(&self) -> LensConfig {
LensConfig {
run: *self.lens_enable() && *self.lens_run_enable(),
debug: *self.lens_enable() && *self.lens_debug_enable(),
interpret: *self.lens_enable() && *self.lens_run_enable() && *self.interpret_tests(),
implementations: *self.lens_enable() && *self.lens_implementations_enable(),
method_refs: *self.lens_enable() && *self.lens_references_method_enable(),
refs_adt: *self.lens_enable() && *self.lens_references_adt_enable(),
refs_trait: *self.lens_enable() && *self.lens_references_trait_enable(),
enum_variant_refs: *self.lens_enable() && *self.lens_references_enumVariant_enable(),
location: *self.lens_location(),
}
}
pub fn workspace_symbol(&self) -> WorkspaceSymbolConfig {
WorkspaceSymbolConfig {
search_scope: match self.workspace_symbol_search_scope() {
WorkspaceSymbolSearchScopeDef::Workspace => WorkspaceSymbolSearchScope::Workspace,
WorkspaceSymbolSearchScopeDef::WorkspaceAndDependencies => {
WorkspaceSymbolSearchScope::WorkspaceAndDependencies
}
},
search_kind: match self.workspace_symbol_search_kind() {
WorkspaceSymbolSearchKindDef::OnlyTypes => WorkspaceSymbolSearchKind::OnlyTypes,
WorkspaceSymbolSearchKindDef::AllSymbols => WorkspaceSymbolSearchKind::AllSymbols,
},
search_limit: *self.workspace_symbol_search_limit(),
}
}
pub fn semantic_tokens_refresh(&self) -> bool {
try_or_def!(self.caps.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support?)
}
pub fn code_lens_refresh(&self) -> bool {
try_or_def!(self.caps.workspace.as_ref()?.code_lens.as_ref()?.refresh_support?)
}
pub fn inlay_hints_refresh(&self) -> bool {
try_or_def!(self.caps.workspace.as_ref()?.inlay_hint.as_ref()?.refresh_support?)
}
pub fn insert_replace_support(&self) -> bool {
try_or_def!(
self.caps
.text_document
.as_ref()?
.completion
.as_ref()?
.completion_item
.as_ref()?
.insert_replace_support?
)
}
pub fn client_commands(&self) -> ClientCommandsConfig {
let commands =
try_or!(self.caps.experimental.as_ref()?.get("commands")?, &serde_json::Value::Null);
let commands: Option<lsp_ext::ClientCommandOptions> =
serde_json::from_value(commands.clone()).ok();
let force = commands.is_none() && *self.lens_forceCustomCommands();
let commands = commands.map(|it| it.commands).unwrap_or_default();
let get = |name: &str| commands.iter().any(|it| it == name) || force;
ClientCommandsConfig {
run_single: get("rust-analyzer.runSingle"),
debug_single: get("rust-analyzer.debugSingle"),
show_reference: get("rust-analyzer.showReferences"),
goto_location: get("rust-analyzer.gotoLocation"),
trigger_parameter_hints: get("editor.action.triggerParameterHints"),
}
}
pub fn prime_caches_num_threads(&self) -> usize {
match self.cachePriming_numThreads() {
NumThreads::Concrete(0) | NumThreads::Physical => num_cpus::get_physical(),
&NumThreads::Concrete(n) => n,
NumThreads::Logical => num_cpus::get(),
}
}
pub fn main_loop_num_threads(&self) -> usize {
match self.numThreads() {
Some(NumThreads::Concrete(0)) | None | Some(NumThreads::Physical) => {
num_cpus::get_physical()
}
&Some(NumThreads::Concrete(n)) => n,
Some(NumThreads::Logical) => num_cpus::get(),
}
}
pub fn typing_autoclose_angle(&self) -> bool {
*self.typing_autoClosingAngleBrackets_enable()
}
pub fn visual_studio_code_version(&self) -> Option<&Version> {
self.visual_studio_code_version.as_ref()
}
}
macro_rules! create_bool_or_string_serde {
($ident:ident<$bool:literal, $string:literal>) => {
mod $ident {
pub(super) fn deserialize<'de, D>(d: D) -> Result<(), D::Error>
where
D: serde::Deserializer<'de>,
{
struct V;
impl<'de> serde::de::Visitor<'de> for V {
type Value = ();
fn expecting(
&self,
formatter: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
formatter.write_str(concat!(
stringify!($bool),
" or \"",
stringify!($string),
"\""
))
}
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
match v {
$bool => Ok(()),
_ => Err(serde::de::Error::invalid_value(
serde::de::Unexpected::Bool(v),
&self,
)),
}
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
match v {
$string => Ok(()),
_ => Err(serde::de::Error::invalid_value(
serde::de::Unexpected::Str(v),
&self,
)),
}
}
fn visit_enum<A>(self, a: A) -> Result<Self::Value, A::Error>
where
A: serde::de::EnumAccess<'de>,
{
use serde::de::VariantAccess;
let (variant, va) = a.variant::<&'de str>()?;
va.unit_variant()?;
match variant {
$string => Ok(()),
_ => Err(serde::de::Error::invalid_value(
serde::de::Unexpected::Str(variant),
&self,
)),
}
}
}
d.deserialize_any(V)
}
pub(super) fn serialize<S>(serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str($string)
}
}
};
}
create_bool_or_string_serde!(true_or_always<true, "always">);
create_bool_or_string_serde!(false_or_never<false, "never">);
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
enum SnippetScopeDef {
#[default]
Expr,
Item,
Type,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
#[serde(default)]
pub(crate) struct SnippetDef {
#[serde(with = "single_or_array")]
#[serde(skip_serializing_if = "Vec::is_empty")]
prefix: Vec<String>,
#[serde(with = "single_or_array")]
#[serde(skip_serializing_if = "Vec::is_empty")]
postfix: Vec<String>,
#[serde(with = "single_or_array")]
#[serde(skip_serializing_if = "Vec::is_empty")]
body: Vec<String>,
#[serde(with = "single_or_array")]
#[serde(skip_serializing_if = "Vec::is_empty")]
requires: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
description: Option<String>,
scope: SnippetScopeDef,
}
mod single_or_array {
use serde::{Deserialize, Serialize};
pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
D: serde::Deserializer<'de>,
{
struct SingleOrVec;
impl<'de> serde::de::Visitor<'de> for SingleOrVec {
type Value = Vec<String>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("string or array of strings")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(vec![value.to_owned()])
}
fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
}
}
deserializer.deserialize_any(SingleOrVec)
}
pub(super) fn serialize<S>(vec: &[String], serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match vec {
[single] => serializer.serialize_str(single),
slice => slice.serialize(serializer),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
enum ManifestOrProjectJson {
Manifest(Utf8PathBuf),
ProjectJson(ProjectJsonData),
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum ExprFillDefaultDef {
Todo,
Default,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum ImportGranularityDef {
Preserve,
Item,
Crate,
Module,
One,
}
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
#[serde(rename_all = "snake_case")]
pub(crate) enum CallableCompletionDef {
FillArguments,
AddParentheses,
None,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum CargoFeaturesDef {
All,
#[serde(untagged)]
Selected(Vec<String>),
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub(crate) enum InvocationStrategy {
Once,
PerWorkspace,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct CheckOnSaveTargets(#[serde(with = "single_or_array")] Vec<String>);
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum InvocationLocation {
Root,
Workspace,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum LifetimeElisionDef {
SkipTrivial,
#[serde(with = "true_or_always")]
#[serde(untagged)]
Always,
#[serde(with = "false_or_never")]
#[serde(untagged)]
Never,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum ClosureReturnTypeHintsDef {
WithBlock,
#[serde(with = "true_or_always")]
#[serde(untagged)]
Always,
#[serde(with = "false_or_never")]
#[serde(untagged)]
Never,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum ClosureStyle {
ImplFn,
RustAnalyzer,
WithId,
Hide,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum ReborrowHintsDef {
Mutable,
#[serde(with = "true_or_always")]
#[serde(untagged)]
Always,
#[serde(with = "false_or_never")]
#[serde(untagged)]
Never,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum AdjustmentHintsDef {
Reborrow,
#[serde(with = "true_or_always")]
#[serde(untagged)]
Always,
#[serde(with = "false_or_never")]
#[serde(untagged)]
Never,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum DiscriminantHintsDef {
Fieldless,
#[serde(with = "true_or_always")]
#[serde(untagged)]
Always,
#[serde(with = "false_or_never")]
#[serde(untagged)]
Never,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum AdjustmentHintsModeDef {
Prefix,
Postfix,
PreferPrefix,
PreferPostfix,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum FilesWatcherDef {
Client,
Notify,
Server,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum ImportPrefixDef {
Plain,
#[serde(rename = "self")]
#[serde(alias = "by_self")]
BySelf,
#[serde(rename = "crate")]
#[serde(alias = "by_crate")]
ByCrate,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum WorkspaceSymbolSearchScopeDef {
Workspace,
WorkspaceAndDependencies,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum SignatureDetail {
Full,
Parameters,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum WorkspaceSymbolSearchKindDef {
OnlyTypes,
AllSymbols,
}
#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
enum MemoryLayoutHoverRenderKindDef {
Decimal,
Hexadecimal,
Both,
}
#[test]
fn untagged_option_hover_render_kind() {
let hex = MemoryLayoutHoverRenderKindDef::Hexadecimal;
let ser = serde_json::to_string(&Some(hex)).unwrap();
assert_eq!(&ser, "\"hexadecimal\"");
let opt: Option<_> = serde_json::from_str("\"hexadecimal\"").unwrap();
assert_eq!(opt, Some(hex));
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
#[serde(untagged)]
pub enum TargetDirectory {
UseSubdirectory(bool),
Directory(Utf8PathBuf),
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum NumThreads {
Physical,
Logical,
#[serde(untagged)]
Concrete(usize),
}
macro_rules! _default_val {
(@verbatim: $s:literal, $ty:ty) => {{
let default_: $ty = serde_json::from_str(&$s).unwrap();
default_
}};
($default:expr, $ty:ty) => {{
let default_: $ty = $default;
default_
}};
}
use _default_val as default_val;
macro_rules! _default_str {
(@verbatim: $s:literal, $_ty:ty) => {
$s.to_owned()
};
($default:expr, $ty:ty) => {{
let val = default_val!($default, $ty);
serde_json::to_string_pretty(&val).unwrap()
}};
}
use _default_str as default_str;
macro_rules! _impl_for_config_data {
(local, $(
$(#[doc=$doc:literal])*
$vis:vis $field:ident : $ty:ty = $default:expr,
)*
) => {
impl Config {
$(
$($doc)*
#[allow(non_snake_case)]
$vis fn $field(&self, source_root: Option<SourceRootId>) -> &$ty {
let mut par: Option<SourceRootId> = source_root;
let mut traversals = 0;
while let Some(source_root_id) = par {
par = self.source_root_parent_map.get(&source_root_id).copied();
if let Some((config, _)) = self.ratoml_files.get(&source_root_id) {
if let Some(value) = config.$field.as_ref() {
return value;
}
}
traversals += 1;
if traversals >= self.source_root_parent_map.len() {
break;
}
}
if let Some((root_path_ratoml, _)) = self.root_ratoml.as_ref() {
if let Some(v) = root_path_ratoml.local.$field.as_ref() {
return &v;
}
}
if let Some(v) = self.client_config.0.local.$field.as_ref() {
return &v;
}
if let Some((user_config, _)) = self.user_config.as_ref() {
if let Some(v) = user_config.local.$field.as_ref() {
return &v;
}
}
&self.default_config.local.$field
}
)*
}
};
(global, $(
$(#[doc=$doc:literal])*
$vis:vis $field:ident : $ty:ty = $default:expr,
)*
) => {
impl Config {
$(
$($doc)*
#[allow(non_snake_case)]
$vis fn $field(&self) -> &$ty {
if let Some((root_path_ratoml, _)) = self.root_ratoml.as_ref() {
if let Some(v) = root_path_ratoml.global.$field.as_ref() {
return &v;
}
}
if let Some(v) = self.client_config.0.global.$field.as_ref() {
return &v;
}
if let Some((user_config, _)) = self.user_config.as_ref() {
if let Some(v) = user_config.global.$field.as_ref() {
return &v;
}
}
&self.default_config.global.$field
}
)*
}
};
(client, $(
$(#[doc=$doc:literal])*
$vis:vis $field:ident : $ty:ty = $default:expr,
)*
) => {
impl Config {
$(
$($doc)*
#[allow(non_snake_case)]
$vis fn $field(&self) -> &$ty {
if let Some(v) = self.client_config.0.client.$field.as_ref() {
return &v;
}
&self.default_config.client.$field
}
)*
}
};
}
use _impl_for_config_data as impl_for_config_data;
macro_rules! _config_data {
($(#[doc=$dox:literal])* $modname:ident: struct $name:ident <- $input:ident -> {
$(
$(#[doc=$doc:literal])*
$vis:vis $field:ident $(| $alias:ident)*: $ty:ty = $(@$marker:ident: )? $default:expr,
)*
}) => {
#[allow(non_snake_case)]
#[derive(Debug, Clone )]
struct $name { $($field: $ty,)* }
impl_for_config_data!{
$modname,
$(
$vis $field : $ty = $default,
)*
}
#[allow(non_snake_case)]
#[derive(Clone, Serialize, Default)]
struct $input { $(
#[serde(skip_serializing_if = "Option::is_none")]
$field: Option<$ty>,
)* }
impl std::fmt::Debug for $input {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut s = f.debug_struct(stringify!($input));
$(
if let Some(val) = self.$field.as_ref() {
s.field(stringify!($field), val);
}
)*
s.finish()
}
}
impl Default for $name {
fn default() -> Self {
$name {$(
$field: default_val!($(@$marker:)? $default, $ty),
)*}
}
}
#[allow(unused, clippy::ptr_arg)]
impl $input {
const FIELDS: &'static [&'static str] = &[$(stringify!($field)),*];
fn from_json(json: &mut serde_json::Value, error_sink: &mut Vec<(String, serde_json::Error)>) -> Self {
Self {$(
$field: get_field(
json,
error_sink,
stringify!($field),
None$(.or(Some(stringify!($alias))))*,
),
)*}
}
fn from_toml(toml: &toml::Table, error_sink: &mut Vec<(String, toml::de::Error)>) -> Self {
Self {$(
$field: get_field_toml::<$ty>(
toml,
error_sink,
stringify!($field),
None$(.or(Some(stringify!($alias))))*,
),
)*}
}
fn schema_fields(sink: &mut Vec<SchemaField>) {
sink.extend_from_slice(&[
$({
let field = stringify!($field);
let ty = stringify!($ty);
let default = default_str!($(@$marker:)? $default, $ty);
(field, ty, &[$($doc),*], default)
},)*
])
}
}
mod $modname {
#[test]
fn fields_are_sorted() {
super::$input::FIELDS.windows(2).for_each(|w| assert!(w[0] <= w[1], "{} <= {} does not hold", w[0], w[1]));
}
}
};
}
use _config_data as config_data;
#[derive(Default, Debug, Clone)]
struct DefaultConfigData {
global: GlobalDefaultConfigData,
local: LocalDefaultConfigData,
client: ClientDefaultConfigData,
}
#[derive(Debug, Clone, Default, Serialize)]
struct FullConfigInput {
global: GlobalConfigInput,
local: LocalConfigInput,
client: ClientConfigInput,
}
impl FullConfigInput {
fn from_json(
mut json: serde_json::Value,
error_sink: &mut Vec<(String, serde_json::Error)>,
) -> FullConfigInput {
FullConfigInput {
global: GlobalConfigInput::from_json(&mut json, error_sink),
local: LocalConfigInput::from_json(&mut json, error_sink),
client: ClientConfigInput::from_json(&mut json, error_sink),
}
}
fn schema_fields() -> Vec<SchemaField> {
let mut fields = Vec::new();
GlobalConfigInput::schema_fields(&mut fields);
LocalConfigInput::schema_fields(&mut fields);
ClientConfigInput::schema_fields(&mut fields);
fields.sort_by_key(|&(x, ..)| x);
fields
.iter()
.tuple_windows()
.for_each(|(a, b)| assert!(a.0 != b.0, "{a:?} duplicate field"));
fields
}
fn json_schema() -> serde_json::Value {
schema(&Self::schema_fields())
}
#[cfg(test)]
fn manual() -> String {
manual(&Self::schema_fields())
}
}
#[derive(Debug, Clone, Default, Serialize)]
struct GlobalLocalConfigInput {
global: GlobalConfigInput,
local: LocalConfigInput,
}
impl GlobalLocalConfigInput {
const FIELDS: &'static [&'static [&'static str]] =
&[GlobalConfigInput::FIELDS, LocalConfigInput::FIELDS];
fn from_toml(
toml: toml::Table,
error_sink: &mut Vec<(String, toml::de::Error)>,
) -> GlobalLocalConfigInput {
GlobalLocalConfigInput {
global: GlobalConfigInput::from_toml(&toml, error_sink),
local: LocalConfigInput::from_toml(&toml, error_sink),
}
}
}
fn get_field<T: DeserializeOwned>(
json: &mut serde_json::Value,
error_sink: &mut Vec<(String, serde_json::Error)>,
field: &'static str,
alias: Option<&'static str>,
) -> Option<T> {
alias
.into_iter()
.chain(iter::once(field))
.filter_map(move |field| {
let mut pointer = field.replace('_', "/");
pointer.insert(0, '/');
json.pointer_mut(&pointer)
.map(|it| serde_json::from_value(it.take()).map_err(|e| (e, pointer)))
})
.find(Result::is_ok)
.and_then(|res| match res {
Ok(it) => Some(it),
Err((e, pointer)) => {
tracing::warn!("Failed to deserialize config field at {}: {:?}", pointer, e);
error_sink.push((pointer, e));
None
}
})
}
fn get_field_toml<T: DeserializeOwned>(
toml: &toml::Table,
error_sink: &mut Vec<(String, toml::de::Error)>,
field: &'static str,
alias: Option<&'static str>,
) -> Option<T> {
alias
.into_iter()
.chain(iter::once(field))
.filter_map(move |field| {
let mut pointer = field.replace('_', "/");
pointer.insert(0, '/');
toml_pointer(toml, &pointer)
.map(|it| <_>::deserialize(it.clone()).map_err(|e| (e, pointer)))
})
.find(Result::is_ok)
.and_then(|res| match res {
Ok(it) => Some(it),
Err((e, pointer)) => {
tracing::warn!("Failed to deserialize config field at {}: {:?}", pointer, e);
error_sink.push((pointer, e));
None
}
})
}
fn toml_pointer<'a>(toml: &'a toml::Table, pointer: &str) -> Option<&'a toml::Value> {
fn parse_index(s: &str) -> Option<usize> {
if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
return None;
}
s.parse().ok()
}
if pointer.is_empty() {
return None;
}
if !pointer.starts_with('/') {
return None;
}
let mut parts = pointer.split('/').skip(1);
let first = parts.next()?;
let init = toml.get(first)?;
parts.map(|x| x.replace("~1", "/").replace("~0", "~")).try_fold(init, |target, token| {
match target {
toml::Value::Table(table) => table.get(&token),
toml::Value::Array(list) => parse_index(&token).and_then(move |x| list.get(x)),
_ => None,
}
})
}
type SchemaField = (&'static str, &'static str, &'static [&'static str], String);
fn schema(fields: &[SchemaField]) -> serde_json::Value {
let map = fields
.iter()
.map(|(field, ty, doc, default)| {
let name = field.replace('_', ".");
let category =
name.find('.').map(|end| String::from(&name[..end])).unwrap_or("general".into());
let name = format!("rust-analyzer.{name}");
let props = field_props(field, ty, doc, default);
serde_json::json!({
"title": category,
"properties": {
name: props
}
})
})
.collect::<Vec<_>>();
map.into()
}
fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
let doc = doc_comment_to_string(doc);
let doc = doc.trim_end_matches('\n');
assert!(
doc.ends_with('.') && doc.starts_with(char::is_uppercase),
"bad docs for {field}: {doc:?}"
);
let default = default.parse::<serde_json::Value>().unwrap();
let mut map = serde_json::Map::default();
macro_rules! set {
($($key:literal: $value:tt),*$(,)?) => {{$(
map.insert($key.into(), serde_json::json!($value));
)*}};
}
set!("markdownDescription": doc);
set!("default": default);
match ty {
"bool" => set!("type": "boolean"),
"usize" => set!("type": "integer", "minimum": 0),
"String" => set!("type": "string"),
"Vec<String>" => set! {
"type": "array",
"items": { "type": "string" },
},
"Vec<Utf8PathBuf>" => set! {
"type": "array",
"items": { "type": "string" },
},
"FxHashSet<String>" => set! {
"type": "array",
"items": { "type": "string" },
"uniqueItems": true,
},
"FxHashMap<Box<str>, Box<[Box<str>]>>" => set! {
"type": "object",
},
"IndexMap<String, SnippetDef>" => set! {
"type": "object",
},
"FxHashMap<String, String>" => set! {
"type": "object",
},
"FxHashMap<Box<str>, usize>" => set! {
"type": "object",
},
"FxHashMap<String, Option<String>>" => set! {
"type": "object",
},
"Option<usize>" => set! {
"type": ["null", "integer"],
"minimum": 0,
},
"Option<String>" => set! {
"type": ["null", "string"],
},
"Option<Utf8PathBuf>" => set! {
"type": ["null", "string"],
},
"Option<bool>" => set! {
"type": ["null", "boolean"],
},
"Option<Vec<String>>" => set! {
"type": ["null", "array"],
"items": { "type": "string" },
},
"ExprFillDefaultDef" => set! {
"type": "string",
"enum": ["todo", "default"],
"enumDescriptions": [
"Fill missing expressions with the `todo` macro",
"Fill missing expressions with reasonable defaults, `new` or `default` constructors."
],
},
"ImportGranularityDef" => set! {
"type": "string",
"enum": ["preserve", "crate", "module", "item", "one"],
"enumDescriptions": [
"Do not change the granularity of any imports and preserve the original structure written by the developer.",
"Merge imports from the same crate into a single use statement. Conversely, imports from different crates are split into separate statements.",
"Merge imports from the same module into a single use statement. Conversely, imports from different modules are split into separate statements.",
"Flatten imports so that each has its own use statement.",
"Merge all imports into a single use statement as long as they have the same visibility and attributes."
],
},
"ImportPrefixDef" => set! {
"type": "string",
"enum": [
"plain",
"self",
"crate"
],
"enumDescriptions": [
"Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
"Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item. Prefixes `self` in front of the path if it starts with a module.",
"Force import paths to be absolute by always starting them with `crate` or the extern crate name they come from."
],
},
"Vec<ManifestOrProjectJson>" => set! {
"type": "array",
"items": { "type": ["string", "object"] },
},
"WorkspaceSymbolSearchScopeDef" => set! {
"type": "string",
"enum": ["workspace", "workspace_and_dependencies"],
"enumDescriptions": [
"Search in current workspace only.",
"Search in current workspace and dependencies."
],
},
"WorkspaceSymbolSearchKindDef" => set! {
"type": "string",
"enum": ["only_types", "all_symbols"],
"enumDescriptions": [
"Search for types only.",
"Search for all symbols kinds."
],
},
"LifetimeElisionDef" => set! {
"type": "string",
"enum": [
"always",
"never",
"skip_trivial"
],
"enumDescriptions": [
"Always show lifetime elision hints.",
"Never show lifetime elision hints.",
"Only show lifetime elision hints if a return type is involved."
]
},
"ClosureReturnTypeHintsDef" => set! {
"type": "string",
"enum": [
"always",
"never",
"with_block"
],
"enumDescriptions": [
"Always show type hints for return types of closures.",
"Never show type hints for return types of closures.",
"Only show type hints for return types of closures with blocks."
]
},
"ReborrowHintsDef" => set! {
"type": "string",
"enum": [
"always",
"never",
"mutable"
],
"enumDescriptions": [
"Always show reborrow hints.",
"Never show reborrow hints.",
"Only show mutable reborrow hints."
]
},
"AdjustmentHintsDef" => set! {
"type": "string",
"enum": [
"always",
"never",
"reborrow"
],
"enumDescriptions": [
"Always show all adjustment hints.",
"Never show adjustment hints.",
"Only show auto borrow and dereference adjustment hints."
]
},
"DiscriminantHintsDef" => set! {
"type": "string",
"enum": [
"always",
"never",
"fieldless"
],
"enumDescriptions": [
"Always show all discriminant hints.",
"Never show discriminant hints.",
"Only show discriminant hints on fieldless enum variants."
]
},
"AdjustmentHintsModeDef" => set! {
"type": "string",
"enum": [
"prefix",
"postfix",
"prefer_prefix",
"prefer_postfix",
],
"enumDescriptions": [
"Always show adjustment hints as prefix (`*expr`).",
"Always show adjustment hints as postfix (`expr.*`).",
"Show prefix or postfix depending on which uses less parenthesis, preferring prefix.",
"Show prefix or postfix depending on which uses less parenthesis, preferring postfix.",
]
},
"CargoFeaturesDef" => set! {
"anyOf": [
{
"type": "string",
"enum": [
"all"
],
"enumDescriptions": [
"Pass `--all-features` to cargo",
]
},
{
"type": "array",
"items": { "type": "string" }
}
],
},
"Option<CargoFeaturesDef>" => set! {
"anyOf": [
{
"type": "string",
"enum": [
"all"
],
"enumDescriptions": [
"Pass `--all-features` to cargo",
]
},
{
"type": "array",
"items": { "type": "string" }
},
{ "type": "null" }
],
},
"CallableCompletionDef" => set! {
"type": "string",
"enum": [
"fill_arguments",
"add_parentheses",
"none",
],
"enumDescriptions": [
"Add call parentheses and pre-fill arguments.",
"Add call parentheses.",
"Do no snippet completions for callables."
]
},
"SignatureDetail" => set! {
"type": "string",
"enum": ["full", "parameters"],
"enumDescriptions": [
"Show the entire signature.",
"Show only the parameters."
],
},
"FilesWatcherDef" => set! {
"type": "string",
"enum": ["client", "server"],
"enumDescriptions": [
"Use the client (editor) to watch files for changes",
"Use server-side file watching",
],
},
"AnnotationLocation" => set! {
"type": "string",
"enum": ["above_name", "above_whole_item"],
"enumDescriptions": [
"Render annotations above the name of the item.",
"Render annotations above the whole item, including documentation comments and attributes."
],
},
"InvocationStrategy" => set! {
"type": "string",
"enum": ["per_workspace", "once"],
"enumDescriptions": [
"The command will be executed for each workspace.",
"The command will be executed once."
],
},
"InvocationLocation" => set! {
"type": "string",
"enum": ["workspace", "root"],
"enumDescriptions": [
"The command will be executed in the corresponding workspace root.",
"The command will be executed in the project root."
],
},
"Option<CheckOnSaveTargets>" => set! {
"anyOf": [
{
"type": "null"
},
{
"type": "string",
},
{
"type": "array",
"items": { "type": "string" }
},
],
},
"ClosureStyle" => set! {
"type": "string",
"enum": ["impl_fn", "ra_ap_rust_analyzer", "with_id", "hide"],
"enumDescriptions": [
"`impl_fn`: `impl FnMut(i32, u64) -> i8`",
"`ra_ap_rust_analyzer`: `|i32, u64| -> i8`",
"`with_id`: `{closure#14352}`, where that id is the unique number of the closure in r-a internals",
"`hide`: Shows `...` for every closure type",
],
},
"Option<MemoryLayoutHoverRenderKindDef>" => set! {
"anyOf": [
{
"type": "null"
},
{
"type": "string",
"enum": ["both", "decimal", "hexadecimal", ],
"enumDescriptions": [
"Render as 12 (0xC)",
"Render as 12",
"Render as 0xC"
],
},
],
},
"Option<TargetDirectory>" => set! {
"anyOf": [
{
"type": "null"
},
{
"type": "boolean"
},
{
"type": "string"
},
],
},
"NumThreads" => set! {
"anyOf": [
{
"type": "number",
"minimum": 0,
"maximum": 255
},
{
"type": "string",
"enum": ["physical", "logical", ],
"enumDescriptions": [
"Use the number of physical cores",
"Use the number of logical cores",
],
},
],
},
"Option<NumThreads>" => set! {
"anyOf": [
{
"type": "null"
},
{
"type": "number",
"minimum": 0,
"maximum": 255
},
{
"type": "string",
"enum": ["physical", "logical", ],
"enumDescriptions": [
"Use the number of physical cores",
"Use the number of logical cores",
],
},
],
},
_ => panic!("missing entry for {ty}: {default} (field {field})"),
}
map.into()
}
fn validate_toml_table(
known_ptrs: &[&[&'static str]],
toml: &toml::Table,
ptr: &mut String,
error_sink: &mut Vec<(String, toml::de::Error)>,
) {
let verify = |ptr: &String| known_ptrs.iter().any(|ptrs| ptrs.contains(&ptr.as_str()));
let l = ptr.len();
for (k, v) in toml {
if !ptr.is_empty() {
ptr.push('_');
}
ptr.push_str(k);
match v {
toml::Value::Table(_) if verify(ptr) => (),
toml::Value::Table(table) => validate_toml_table(known_ptrs, table, ptr, error_sink),
_ if !verify(ptr) => error_sink
.push((ptr.replace('_', "/"), toml::de::Error::custom("unexpected field"))),
_ => (),
}
ptr.truncate(l);
}
}
#[cfg(test)]
fn manual(fields: &[SchemaField]) -> String {
fields.iter().fold(String::new(), |mut acc, (field, _ty, doc, default)| {
let name = format!("rust-analyzer.{}", field.replace('_', "."));
let doc = doc_comment_to_string(doc);
if default.contains('\n') {
format_to_acc!(
acc,
r#"[[{name}]]{name}::
+
--
Default:
----
{default}
----
{doc}
--
"#
)
} else {
format_to_acc!(acc, "[[{name}]]{name} (default: `{default}`)::\n+\n--\n{doc}--\n")
}
})
}
fn doc_comment_to_string(doc: &[&str]) -> String {
doc.iter()
.map(|it| it.strip_prefix(' ').unwrap_or(it))
.fold(String::new(), |mut acc, it| format_to_acc!(acc, "{it}\n"))
}
#[cfg(test)]
mod tests {
use std::fs;
use test_utils::{ensure_file_contents, project_root};
use super::*;
#[test]
fn generate_package_json_config() {
let s = Config::json_schema();
let schema = format!("{s:#}");
let mut schema = schema
.trim_start_matches('[')
.trim_end_matches(']')
.replace(" ", " ")
.replace('\n', "\n ")
.trim_start_matches('\n')
.trim_end()
.to_owned();
schema.push_str(",\n");
let url_matches = schema.match_indices("https://");
let mut url_offsets = url_matches.map(|(idx, _)| idx).collect::<Vec<usize>>();
url_offsets.reverse();
for idx in url_offsets {
let link = &schema[idx..];
if let Some(link_end) = link.find(|c| c == ' ' || c == '[') {
if link.chars().nth(link_end) == Some('[') {
if let Some(link_text_end) = link.find(']') {
let link_text = link[link_end..(link_text_end + 1)].to_string();
schema.replace_range((idx + link_end)..(idx + link_text_end + 1), "");
schema.insert(idx, '(');
schema.insert(idx + link_end + 1, ')');
schema.insert_str(idx, &link_text);
}
}
}
}
let package_json_path = project_root().join("editors/code/package.json");
let mut package_json = fs::read_to_string(&package_json_path).unwrap();
let start_marker =
" {\n \"title\": \"$generated-start\"\n },\n";
let end_marker =
" {\n \"title\": \"$generated-end\"\n }\n";
let start = package_json.find(start_marker).unwrap() + start_marker.len();
let end = package_json.find(end_marker).unwrap();
let p = remove_ws(&package_json[start..end]);
let s = remove_ws(&schema);
if !p.contains(&s) {
package_json.replace_range(start..end, &schema);
ensure_file_contents(&package_json_path, &package_json)
}
}
#[test]
fn generate_config_documentation() {
let docs_path = project_root().join("docs/user/generated_config.adoc");
let expected = FullConfigInput::manual();
ensure_file_contents(&docs_path, &expected);
}
fn remove_ws(text: &str) -> String {
text.replace(char::is_whitespace, "")
}
#[test]
fn proc_macro_srv_null() {
let mut config = Config::new(
AbsPathBuf::try_from(project_root()).unwrap(),
Default::default(),
vec![],
None,
None,
);
let mut change = ConfigChange::default();
change.change_client_config(serde_json::json!({
"procMacro" : {
"server": null,
}}));
(config, _, _) = config.apply_change(change);
assert_eq!(config.proc_macro_srv(), None);
}
#[test]
fn proc_macro_srv_abs() {
let mut config = Config::new(
AbsPathBuf::try_from(project_root()).unwrap(),
Default::default(),
vec![],
None,
None,
);
let mut change = ConfigChange::default();
change.change_client_config(serde_json::json!({
"procMacro" : {
"server": project_root().display().to_string(),
}}));
(config, _, _) = config.apply_change(change);
assert_eq!(config.proc_macro_srv(), Some(AbsPathBuf::try_from(project_root()).unwrap()));
}
#[test]
fn proc_macro_srv_rel() {
let mut config = Config::new(
AbsPathBuf::try_from(project_root()).unwrap(),
Default::default(),
vec![],
None,
None,
);
let mut change = ConfigChange::default();
change.change_client_config(serde_json::json!({
"procMacro" : {
"server": "./server"
}}));
(config, _, _) = config.apply_change(change);
assert_eq!(
config.proc_macro_srv(),
Some(AbsPathBuf::try_from(project_root().join("./server")).unwrap())
);
}
#[test]
fn cargo_target_dir_unset() {
let mut config = Config::new(
AbsPathBuf::try_from(project_root()).unwrap(),
Default::default(),
vec![],
None,
None,
);
let mut change = ConfigChange::default();
change.change_client_config(serde_json::json!({
"rust" : { "analyzerTargetDir" : null }
}));
(config, _, _) = config.apply_change(change);
assert_eq!(config.cargo_targetDir(), &None);
assert!(
matches!(config.flycheck(), FlycheckConfig::CargoCommand { options, .. } if options.target_dir.is_none())
);
}
#[test]
fn cargo_target_dir_subdir() {
let mut config = Config::new(
AbsPathBuf::try_from(project_root()).unwrap(),
Default::default(),
vec![],
None,
None,
);
let mut change = ConfigChange::default();
change.change_client_config(serde_json::json!({
"rust" : { "analyzerTargetDir" : true }
}));
(config, _, _) = config.apply_change(change);
assert_eq!(config.cargo_targetDir(), &Some(TargetDirectory::UseSubdirectory(true)));
assert!(
matches!(config.flycheck(), FlycheckConfig::CargoCommand { options, .. } if options.target_dir == Some(Utf8PathBuf::from("target/rust-analyzer")))
);
}
#[test]
fn cargo_target_dir_relative_dir() {
let mut config = Config::new(
AbsPathBuf::try_from(project_root()).unwrap(),
Default::default(),
vec![],
None,
None,
);
let mut change = ConfigChange::default();
change.change_client_config(serde_json::json!({
"rust" : { "analyzerTargetDir" : "other_folder" }
}));
(config, _, _) = config.apply_change(change);
assert_eq!(
config.cargo_targetDir(),
&Some(TargetDirectory::Directory(Utf8PathBuf::from("other_folder")))
);
assert!(
matches!(config.flycheck(), FlycheckConfig::CargoCommand { options, .. } if options.target_dir == Some(Utf8PathBuf::from("other_folder")))
);
}
#[test]
fn toml_unknown_key() {
let config = Config::new(
AbsPathBuf::try_from(project_root()).unwrap(),
Default::default(),
vec![],
None,
None,
);
let mut change = ConfigChange::default();
change.change_root_ratoml(Some(
toml::toml! {
[cargo.cfgs]
these = "these"
should = "should"
be = "be"
valid = "valid"
[invalid.config]
err = "error"
[cargo]
target = "ok"
[cargo.sysroot]
non-table = "expected"
}
.to_string()
.into(),
));
let (config, e, _) = config.apply_change(change);
expect_test::expect![[r#"
ConfigErrors(
[
Toml {
config_key: "invalid/config/err",
error: Error {
inner: Error {
inner: TomlError {
message: "unexpected field",
raw: None,
keys: [],
span: None,
},
},
},
},
],
)
"#]]
.assert_debug_eq(&e);
let mut change = ConfigChange::default();
change.change_user_config(Some(
toml::toml! {
[cargo.cfgs]
these = "these"
should = "should"
be = "be"
valid = "valid"
}
.to_string()
.into(),
));
let (_, e, _) = config.apply_change(change);
expect_test::expect![[r#"
ConfigErrors(
[
Toml {
config_key: "invalid/config/err",
error: Error {
inner: Error {
inner: TomlError {
message: "unexpected field",
raw: None,
keys: [],
span: None,
},
},
},
},
],
)
"#]]
.assert_debug_eq(&e);
}
}