1use std::{env, fmt, iter, ops::Not, sync::OnceLock};
7
8use cfg::{CfgAtom, CfgDiff};
9use hir::Symbol;
10use ide::{
11 AnnotationConfig, AssistConfig, CallHierarchyConfig, CallableSnippets, CompletionConfig,
12 CompletionFieldsToResolve, DiagnosticsConfig, GenericParameterHints, GotoDefinitionConfig,
13 GotoImplementationConfig, HighlightConfig, HighlightRelatedConfig, HoverConfig, HoverDocFormat,
14 InlayFieldsToResolve, InlayHintsConfig, JoinLinesConfig, MemoryLayoutHoverConfig,
15 MemoryLayoutHoverRenderKind, RaFixtureConfig, RenameConfig, Snippet, SnippetScope,
16 SourceRootId,
17};
18use ide_db::{
19 MiniCore, SnippetCap,
20 assists::ExprFillDefaultMode,
21 imports::insert_use::{ImportGranularity, InsertUseConfig, PrefixKind},
22};
23use itertools::{Either, Itertools};
24use paths::{Utf8Path, Utf8PathBuf};
25use project_model::{
26 CargoConfig, CargoFeatures, ProjectJson, ProjectJsonData, ProjectJsonFromCommand,
27 ProjectManifest, RustLibSource, TargetDirectoryConfig,
28};
29use rustc_hash::{FxHashMap, FxHashSet};
30use semver::Version;
31use serde::{
32 Deserialize, Serialize,
33 de::{DeserializeOwned, Error},
34};
35use stdx::format_to_acc;
36use triomphe::Arc;
37use vfs::{AbsPath, AbsPathBuf, VfsPath};
38
39use crate::{
40 diagnostics::DiagnosticsMapConfig,
41 flycheck::{CargoOptions, FlycheckConfig},
42 lsp::capabilities::ClientCapabilities,
43 lsp_ext::{WorkspaceSymbolSearchKind, WorkspaceSymbolSearchScope},
44};
45
46type FxIndexMap<K, V> = indexmap::IndexMap<K, V, rustc_hash::FxBuildHasher>;
47
48mod patch_old_style;
49
50#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59pub enum MaxSubstitutionLength {
60 Hide,
61 #[serde(untagged)]
62 Limit(usize),
63}
64
65config_data! {
74 global: struct GlobalDefaultConfigData <- GlobalConfigInput -> {
84 cachePriming_enable: bool = true,
86
87 cachePriming_numThreads: NumThreads = NumThreads::Physical,
90
91 completion_snippets_custom: FxIndexMap<String, SnippetDef> =
93 Config::completion_snippets_default(),
94
95 files_exclude | files_excludeDirs: Vec<Utf8PathBuf> = vec![],
101
102 gotoImplementations_filterAdjacentDerives: bool = false,
104
105 highlightRelated_branchExitPoints_enable: bool = true,
108
109 highlightRelated_breakPoints_enable: bool = true,
112
113 highlightRelated_closureCaptures_enable: bool = true,
115
116 highlightRelated_exitPoints_enable: bool = true,
119
120 highlightRelated_references_enable: bool = true,
122
123 highlightRelated_yieldPoints_enable: bool = true,
126
127 hover_actions_debug_enable: bool = true,
129
130 hover_actions_enable: bool = true,
132
133 hover_actions_gotoTypeDef_enable: bool = true,
136
137 hover_actions_implementations_enable: bool = true,
140
141 hover_actions_references_enable: bool = false,
144
145 hover_actions_run_enable: bool = true,
147
148 hover_actions_updateTest_enable: bool = true,
151
152 hover_documentation_enable: bool = true,
154
155 hover_documentation_keywords_enable: bool = true,
158
159 hover_dropGlue_enable: bool = true,
161
162 hover_links_enable: bool = true,
164
165 hover_maxSubstitutionLength: Option<MaxSubstitutionLength> =
173 Some(MaxSubstitutionLength::Limit(20)),
174
175 hover_memoryLayout_alignment: Option<MemoryLayoutHoverRenderKindDef> =
177 Some(MemoryLayoutHoverRenderKindDef::Hexadecimal),
178
179 hover_memoryLayout_enable: bool = true,
181
182 hover_memoryLayout_niches: Option<bool> = Some(false),
184
185 hover_memoryLayout_offset: Option<MemoryLayoutHoverRenderKindDef> =
187 Some(MemoryLayoutHoverRenderKindDef::Hexadecimal),
188
189 hover_memoryLayout_padding: Option<MemoryLayoutHoverRenderKindDef> = None,
191
192 hover_memoryLayout_size: Option<MemoryLayoutHoverRenderKindDef> =
194 Some(MemoryLayoutHoverRenderKindDef::Both),
195
196 hover_show_enumVariants: Option<usize> = Some(5),
198
199 hover_show_fields: Option<usize> = Some(5),
202
203 hover_show_traitAssocItems: Option<usize> = None,
205
206 inlayHints_bindingModeHints_enable: bool = false,
208
209 inlayHints_chainingHints_enable: bool = true,
211
212 inlayHints_closingBraceHints_enable: bool = true,
214
215 inlayHints_closingBraceHints_minLines: usize = 25,
218
219 inlayHints_closureCaptureHints_enable: bool = false,
221
222 inlayHints_closureReturnTypeHints_enable: ClosureReturnTypeHintsDef =
224 ClosureReturnTypeHintsDef::Never,
225
226 inlayHints_closureStyle: ClosureStyle = ClosureStyle::ImplFn,
228
229 inlayHints_discriminantHints_enable: DiscriminantHintsDef =
231 DiscriminantHintsDef::Never,
232
233 inlayHints_expressionAdjustmentHints_disableReborrows: bool =
239 true,
240
241 inlayHints_expressionAdjustmentHints_enable: AdjustmentHintsDef =
243 AdjustmentHintsDef::Never,
244
245 inlayHints_expressionAdjustmentHints_hideOutsideUnsafe: bool = false,
247
248 inlayHints_expressionAdjustmentHints_mode: AdjustmentHintsModeDef =
250 AdjustmentHintsModeDef::Prefix,
251
252 inlayHints_genericParameterHints_const_enable: bool = true,
254
255 inlayHints_genericParameterHints_lifetime_enable: bool = false,
257
258 inlayHints_genericParameterHints_type_enable: bool = false,
260
261 inlayHints_implicitDrops_enable: ImplicitDropDef = ImplicitDropDef::Never,
263
264 inlayHints_implicitSizedBoundHints_enable: bool = false,
266
267 inlayHints_impliedDynTraitHints_enable: bool = true,
269
270 inlayHints_lifetimeElisionHints_enable: LifetimeElisionDef = LifetimeElisionDef::Never,
272
273 inlayHints_lifetimeElisionHints_useParameterNames: bool = false,
275
276 inlayHints_maxLength: Option<usize> = Some(25),
280
281 inlayHints_parameterHints_enable: bool = true,
283
284 inlayHints_parameterHints_missingArguments_enable: bool = false,
286
287 inlayHints_rangeExclusiveHints_enable: bool = false,
289
290 inlayHints_reborrowHints_enable: ReborrowHintsDef = ReborrowHintsDef::Never,
295
296 inlayHints_renderColons: bool = true,
298
299 inlayHints_typeHints_enable: bool = true,
301
302 inlayHints_typeHints_hideClosureInitialization: bool = false,
307
308 inlayHints_typeHints_hideClosureParameter: bool = false,
310
311 inlayHints_typeHints_hideInferredTypes: bool = false,
313
314 inlayHints_typeHints_hideNamedConstructor: bool = false,
316
317 inlayHints_typeHints_location: TypeHintsLocation = TypeHintsLocation::Inline,
319
320 interpret_tests: bool = false,
322
323 joinLines_joinAssignments: bool = true,
325
326 joinLines_joinElseIf: bool = true,
328
329 joinLines_removeTrailingComma: bool = true,
331
332 joinLines_unwrapTrivialBlock: bool = true,
334
335 lens_debug_enable: bool = true,
337
338 lens_enable: bool = true,
340
341 lens_implementations_enable: bool = true,
343
344 lens_location: AnnotationLocation = AnnotationLocation::AboveName,
346
347 lens_references_adt_enable: bool = false,
350
351 lens_references_enumVariant_enable: bool = false,
354
355 lens_references_method_enable: bool = false,
357
358 lens_references_trait_enable: bool = false,
361
362 lens_run_enable: bool = true,
364
365 lens_updateTest_enable: bool = true,
368
369 linkedProjects: Vec<ManifestOrProjectJson> = vec![],
374
375 lru_capacity: Option<u16> = None,
377
378 lru_query_capacities: FxHashMap<Box<str>, u16> = FxHashMap::default(),
380
381 notifications_cargoTomlNotFound: bool = true,
383
384 numThreads: Option<NumThreads> = None,
387
388 procMacro_attributes_enable: bool = true,
390
391 procMacro_enable: bool = true,
393
394 procMacro_processes: NumProcesses = NumProcesses::Concrete(2),
399
400 procMacro_server: Option<Utf8PathBuf> = None,
402
403 profiling_memoryProfile: Option<Utf8PathBuf> = None,
408
409 references_excludeImports: bool = false,
411
412 references_excludeTests: bool = false,
414
415 semanticHighlighting_comments_enable: bool = true,
421
422 semanticHighlighting_doc_comment_inject_enable: bool = true,
427
428 semanticHighlighting_nonStandardTokens: bool = true,
433
434 semanticHighlighting_operator_enable: bool = true,
439
440 semanticHighlighting_operator_specialization_enable: bool = false,
445
446 semanticHighlighting_punctuation_enable: bool = false,
451
452 semanticHighlighting_punctuation_separate_macro_bang: bool = false,
455
456 semanticHighlighting_punctuation_specialization_enable: bool = false,
461
462 semanticHighlighting_strings_enable: bool = true,
468
469 signatureInfo_detail: SignatureDetail = SignatureDetail::Full,
471
472 signatureInfo_documentation_enable: bool = true,
474
475 typing_triggerChars: Option<String> = Some("=.".to_owned()),
489
490
491 workspace_discoverConfig: Option<DiscoverWorkspaceConfig> = None,
611 }
612}
613
614config_data! {
615 local: struct LocalDefaultConfigData <- LocalConfigInput -> {
617 assist_emitMustUse: bool = false,
619
620 assist_expressionFillDefault: ExprFillDefaultDef = ExprFillDefaultDef::Todo,
622
623 assist_preferSelf: bool = false,
625
626 assist_termSearch_fuel: usize = 1800,
628
629 completion_addColonsToModule: bool = true,
633
634 completion_addSemicolonToUnit: bool = true,
638
639 completion_autoAwait_enable: bool = true,
642
643 completion_autoDyn_enable: bool = true,
645
646 completion_autoIter_enable: bool = true,
649
650 completion_autoimport_enable: bool = true,
655
656 completion_autoimport_exclude: Vec<AutoImportExclusion> = vec![
675 AutoImportExclusion::Verbose { path: "core::borrow::Borrow".to_owned(), r#type: AutoImportExclusionType::Methods },
676 AutoImportExclusion::Verbose { path: "core::borrow::BorrowMut".to_owned(), r#type: AutoImportExclusionType::Methods },
677 ],
678
679 completion_autoself_enable: bool = true,
682
683 completion_callable_snippets: CallableCompletionDef = CallableCompletionDef::FillArguments,
685
686 completion_excludeTraits: Vec<String> = Vec::new(),
694
695 completion_fullFunctionSignatures_enable: bool = false,
697
698 completion_hideDeprecated: bool = false,
701
702 completion_limit: Option<usize> = None,
704
705 completion_postfix_enable: bool = true,
707
708 completion_privateEditable_enable: bool = false,
711
712 completion_termSearch_enable: bool = false,
714
715 completion_termSearch_fuel: usize = 1000,
717
718 completion_turbofish_enable: bool = true,
720
721 diagnostics_disabled: FxHashSet<String> = FxHashSet::default(),
723
724 diagnostics_enable: bool = true,
726
727 diagnostics_experimental_enable: bool = false,
730
731 diagnostics_remapPrefix: FxHashMap<String, String> = FxHashMap::default(),
734
735 diagnostics_styleLints_enable: bool = false,
737
738 diagnostics_warningsAsHint: Vec<String> = vec![],
743
744 diagnostics_warningsAsInfo: Vec<String> = vec![],
749
750 disableFixtureSupport: bool = false,
754
755 imports_granularity_enforce: bool = false,
758
759 imports_granularity_group: ImportGranularityDef = ImportGranularityDef::Crate,
761
762 imports_group_enable: bool = true,
766
767 imports_merge_glob: bool = true,
770
771 imports_preferNoStd | imports_prefer_no_std: bool = false,
773
774 imports_preferPrelude: bool = false,
776
777 imports_prefix: ImportPrefixDef = ImportPrefixDef::ByCrate,
779
780 imports_prefixExternPrelude: bool = false,
784
785 rename_showConflicts: bool = true,
787 }
788}
789
790config_data! {
791 workspace: struct WorkspaceDefaultConfigData <- WorkspaceConfigInput -> {
792 cargo_allTargets: bool = true,
794 cargo_autoreload: bool = true,
797 cargo_buildScripts_enable: bool = true,
799 cargo_buildScripts_invocationStrategy: InvocationStrategy = InvocationStrategy::PerWorkspace,
807 cargo_buildScripts_overrideCommand: Option<Vec<String>> = None,
827 cargo_buildScripts_rebuildOnSave: bool = true,
830 cargo_buildScripts_useRustcWrapper: bool = true,
833 cargo_cfgs: Vec<String> = {
839 vec!["debug_assertions".into(), "miri".into()]
840 },
841 cargo_configPath: Option<Utf8PathBuf> = None,
845 cargo_extraArgs: Vec<String> = vec![],
847 cargo_extraEnv: FxHashMap<String, Option<String>> = FxHashMap::default(),
850 cargo_features: CargoFeaturesDef = CargoFeaturesDef::Selected(vec![]),
854 cargo_metadataExtraArgs: Vec<String> = vec![],
857 cargo_noDefaultFeatures: bool = false,
859 cargo_noDeps: bool = false,
862 cargo_sysroot: Option<String> = Some("discover".to_owned()),
869 cargo_sysrootSrc: Option<String> = None,
874 cargo_target: Option<String> = None,
878 cargo_targetDir | rust_analyzerTargetDir: Option<TargetDirectory> = None,
885
886 cfg_setTest: bool = true,
888
889 checkOnSave | checkOnSave_enable: bool = true,
891
892
893 check_allTargets | checkOnSave_allTargets: Option<bool> = None,
896 check_command | checkOnSave_command: String = "check".to_owned(),
898 check_extraArgs | checkOnSave_extraArgs: Vec<String> = vec![],
900 check_extraEnv | checkOnSave_extraEnv: FxHashMap<String, Option<String>> = FxHashMap::default(),
903 check_features | checkOnSave_features: Option<CargoFeaturesDef> = None,
908 check_ignore: FxHashSet<String> = FxHashSet::default(),
912 check_invocationStrategy | checkOnSave_invocationStrategy: InvocationStrategy = InvocationStrategy::PerWorkspace,
918 check_noDefaultFeatures | checkOnSave_noDefaultFeatures: Option<bool> = None,
921 check_overrideCommand | checkOnSave_overrideCommand: Option<Vec<String>> = None,
958 check_targets | checkOnSave_targets | checkOnSave_target: Option<CheckOnSaveTargets> = None,
965 check_workspace: bool = true,
969
970 document_symbol_search_excludeLocals: bool = true,
972
973 procMacro_ignored: FxHashMap<Box<str>, Box<[Box<str>]>> = FxHashMap::default(),
977
978 runnables_bench_command: String = "bench".to_owned(),
980 runnables_bench_overrideCommand: Option<Vec<String>> = None,
993 runnables_command: Option<String> = None,
995 runnables_doctest_overrideCommand: Option<Vec<String>> = None,
1008 runnables_extraArgs: Vec<String> = vec![],
1011 runnables_extraTestBinaryArgs: Vec<String> = vec!["--nocapture".to_owned()],
1019 runnables_test_command: String = "test".to_owned(),
1021 runnables_test_overrideCommand: Option<Vec<String>> = None,
1034
1035 rustc_source: Option<String> = None,
1044
1045 rustfmt_extraArgs: Vec<String> = vec![],
1047 rustfmt_overrideCommand: Option<Vec<String>> = None,
1056 rustfmt_rangeFormatting_enable: bool = false,
1060
1061 vfs_extraIncludes: Vec<String> = vec![],
1065
1066 workspace_symbol_search_excludeImports: bool = false,
1072 workspace_symbol_search_kind: WorkspaceSymbolSearchKindDef = WorkspaceSymbolSearchKindDef::OnlyTypes,
1074 workspace_symbol_search_limit: usize = 128,
1078 workspace_symbol_search_scope: WorkspaceSymbolSearchScopeDef = WorkspaceSymbolSearchScopeDef::Workspace,
1080 }
1081}
1082
1083config_data! {
1084 client: struct ClientDefaultConfigData <- ClientConfigInput -> {
1087
1088 files_watcher: FilesWatcherDef = FilesWatcherDef::Client,
1090
1091
1092 }
1093}
1094
1095#[derive(Debug)]
1096pub enum RatomlFileKind {
1097 Workspace,
1098 Crate,
1099}
1100
1101#[derive(Debug, Clone)]
1102#[allow(clippy::large_enum_variant)]
1103enum RatomlFile {
1104 Workspace(WorkspaceLocalConfigInput),
1105 Crate(LocalConfigInput),
1106}
1107
1108#[derive(Clone, Debug)]
1109struct ClientInfo {
1110 name: String,
1111 version: Option<Version>,
1112}
1113
1114#[derive(Clone)]
1116pub struct Config {
1117 discovered_projects_from_filesystem: Vec<ProjectManifest>,
1121 discovered_projects_from_command: Vec<ProjectJsonFromCommand>,
1124 workspace_roots: Vec<AbsPathBuf>,
1126 caps: ClientCapabilities,
1127
1128 root_path: AbsPathBuf,
1133
1134 snippets: Vec<Snippet>,
1135 client_info: Option<ClientInfo>,
1136
1137 default_config: &'static DefaultConfigData,
1138 client_config: (FullConfigInput, ConfigErrors),
1141
1142 user_config: Option<(GlobalWorkspaceLocalConfigInput, ConfigErrors)>,
1144
1145 ratoml_file: FxHashMap<SourceRootId, (RatomlFile, ConfigErrors)>,
1146
1147 source_root_parent_map: Arc<FxHashMap<SourceRootId, SourceRootId>>,
1149
1150 validation_errors: ConfigErrors,
1155
1156 detached_files: Vec<AbsPathBuf>,
1157}
1158
1159impl fmt::Debug for Config {
1160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1161 f.debug_struct("Config")
1162 .field("discovered_projects_from_filesystem", &self.discovered_projects_from_filesystem)
1163 .field("discovered_projects_from_command", &self.discovered_projects_from_command)
1164 .field("workspace_roots", &self.workspace_roots)
1165 .field("caps", &self.caps)
1166 .field("root_path", &self.root_path)
1167 .field("snippets", &self.snippets)
1168 .field("client_info", &self.client_info)
1169 .field("client_config", &self.client_config)
1170 .field("user_config", &self.user_config)
1171 .field("ratoml_file", &self.ratoml_file)
1172 .field("source_root_parent_map", &self.source_root_parent_map)
1173 .field("validation_errors", &self.validation_errors)
1174 .field("detached_files", &self.detached_files)
1175 .finish()
1176 }
1177}
1178
1179impl std::ops::Deref for Config {
1181 type Target = ClientCapabilities;
1182
1183 fn deref(&self) -> &Self::Target {
1184 &self.caps
1185 }
1186}
1187
1188impl Config {
1189 pub fn user_config_dir_path() -> Option<AbsPathBuf> {
1191 let user_config_path = if let Some(path) = env::var_os("__TEST_RA_USER_CONFIG_DIR") {
1192 std::path::PathBuf::from(path)
1193 } else {
1194 dirs::config_dir()?.join("rust-analyzer")
1195 };
1196 Some(AbsPathBuf::assert_utf8(user_config_path))
1197 }
1198
1199 pub fn same_source_root_parent_map(
1200 &self,
1201 other: &Arc<FxHashMap<SourceRootId, SourceRootId>>,
1202 ) -> bool {
1203 Arc::ptr_eq(&self.source_root_parent_map, other)
1204 }
1205
1206 fn apply_change_with_sink(&self, change: ConfigChange) -> (Config, bool) {
1210 let mut config = self.clone();
1211 config.validation_errors = ConfigErrors::default();
1212
1213 let mut should_update = false;
1214
1215 if let Some(change) = change.user_config_change {
1216 tracing::info!("updating config from user config toml: {:#}", change);
1217 if let Ok(table) = toml::from_str(&change) {
1218 let mut toml_errors = vec![];
1219 validate_toml_table(
1220 GlobalWorkspaceLocalConfigInput::FIELDS,
1221 &table,
1222 &mut String::new(),
1223 &mut toml_errors,
1224 );
1225 config.user_config = Some((
1226 GlobalWorkspaceLocalConfigInput::from_toml(table, &mut toml_errors),
1227 ConfigErrors(
1228 toml_errors
1229 .into_iter()
1230 .map(|(a, b)| ConfigErrorInner::Toml { config_key: a, error: b })
1231 .map(Arc::new)
1232 .collect(),
1233 ),
1234 ));
1235 should_update = true;
1236 }
1237 }
1238
1239 if let Some(mut json) = change.client_config_change {
1240 tracing::info!("updating config from JSON: {:#}", json);
1241
1242 if !(json.is_null() || json.as_object().is_some_and(|it| it.is_empty())) {
1243 let detached_files = get_field_json::<Vec<Utf8PathBuf>>(
1244 &mut json,
1245 &mut Vec::new(),
1246 "detachedFiles",
1247 None,
1248 )
1249 .unwrap_or_default()
1250 .into_iter()
1251 .map(AbsPathBuf::assert)
1252 .collect();
1253
1254 patch_old_style::patch_json_for_outdated_configs(&mut json);
1255
1256 let mut json_errors = vec![];
1257
1258 let input = FullConfigInput::from_json(json, &mut json_errors);
1259
1260 config.snippets.clear();
1262
1263 let snips = input
1264 .global
1265 .completion_snippets_custom
1266 .as_ref()
1267 .unwrap_or(&self.default_config.global.completion_snippets_custom);
1268 #[allow(dead_code)]
1269 let _ = Self::completion_snippets_custom;
1270 for (name, def) in snips.iter() {
1271 if def.prefix.is_empty() && def.postfix.is_empty() {
1272 continue;
1273 }
1274 let scope = match def.scope {
1275 SnippetScopeDef::Expr => SnippetScope::Expr,
1276 SnippetScopeDef::Type => SnippetScope::Type,
1277 SnippetScopeDef::Item => SnippetScope::Item,
1278 };
1279 match Snippet::new(
1280 &def.prefix,
1281 &def.postfix,
1282 &def.body,
1283 def.description.as_ref().unwrap_or(name),
1284 &def.requires,
1285 scope,
1286 ) {
1287 Some(snippet) => config.snippets.push(snippet),
1288 None => json_errors.push((
1289 name.to_owned(),
1290 <serde_json::Error as serde::de::Error>::custom(format!(
1291 "snippet {name} is invalid or triggers are missing",
1292 )),
1293 )),
1294 }
1295 }
1296
1297 config.client_config = (
1298 input,
1299 ConfigErrors(
1300 json_errors
1301 .into_iter()
1302 .map(|(a, b)| ConfigErrorInner::Json { config_key: a, error: b })
1303 .map(Arc::new)
1304 .collect(),
1305 ),
1306 );
1307 config.detached_files = detached_files;
1308 }
1309 should_update = true;
1310 }
1311
1312 if let Some(change) = change.ratoml_file_change {
1313 for (source_root_id, (kind, _, text)) in change {
1314 match kind {
1315 RatomlFileKind::Crate => {
1316 if let Some(text) = text {
1317 let mut toml_errors = vec![];
1318 tracing::info!("updating ra-toml crate config: {:#}", text);
1319 match toml::from_str(&text) {
1320 Ok(table) => {
1321 validate_toml_table(
1322 &[LocalConfigInput::FIELDS],
1323 &table,
1324 &mut String::new(),
1325 &mut toml_errors,
1326 );
1327 config.ratoml_file.insert(
1328 source_root_id,
1329 (
1330 RatomlFile::Crate(LocalConfigInput::from_toml(
1331 &table,
1332 &mut toml_errors,
1333 )),
1334 ConfigErrors(
1335 toml_errors
1336 .into_iter()
1337 .map(|(a, b)| ConfigErrorInner::Toml {
1338 config_key: a,
1339 error: b,
1340 })
1341 .map(Arc::new)
1342 .collect(),
1343 ),
1344 ),
1345 );
1346 }
1347 Err(e) => {
1348 config.validation_errors.0.push(
1349 ConfigErrorInner::ParseError {
1350 reason: e.message().to_owned(),
1351 }
1352 .into(),
1353 );
1354 }
1355 }
1356 }
1357 }
1358 RatomlFileKind::Workspace => {
1359 if let Some(text) = text {
1360 tracing::info!("updating ra-toml workspace config: {:#}", text);
1361 let mut toml_errors = vec![];
1362 match toml::from_str(&text) {
1363 Ok(table) => {
1364 validate_toml_table(
1365 WorkspaceLocalConfigInput::FIELDS,
1366 &table,
1367 &mut String::new(),
1368 &mut toml_errors,
1369 );
1370 config.ratoml_file.insert(
1371 source_root_id,
1372 (
1373 RatomlFile::Workspace(
1374 WorkspaceLocalConfigInput::from_toml(
1375 table,
1376 &mut toml_errors,
1377 ),
1378 ),
1379 ConfigErrors(
1380 toml_errors
1381 .into_iter()
1382 .map(|(a, b)| ConfigErrorInner::Toml {
1383 config_key: a,
1384 error: b,
1385 })
1386 .map(Arc::new)
1387 .collect(),
1388 ),
1389 ),
1390 );
1391 should_update = true;
1392 }
1393 Err(e) => {
1394 config.validation_errors.0.push(
1395 ConfigErrorInner::ParseError {
1396 reason: e.message().to_owned(),
1397 }
1398 .into(),
1399 );
1400 }
1401 }
1402 }
1403 }
1404 }
1405 }
1406 }
1407
1408 if let Some(source_root_map) = change.source_map_change {
1409 config.source_root_parent_map = source_root_map;
1410 }
1411
1412 if config.check_command(None).is_empty() {
1413 config.validation_errors.0.push(Arc::new(ConfigErrorInner::Json {
1414 config_key: "/check/command".to_owned(),
1415 error: serde_json::Error::custom("expected a non-empty string"),
1416 }));
1417 }
1418
1419 (config, should_update)
1420 }
1421
1422 pub fn apply_change(&self, change: ConfigChange) -> (Config, ConfigErrors, bool) {
1426 let (config, should_update) = self.apply_change_with_sink(change);
1427 let e = ConfigErrors(
1428 config
1429 .client_config
1430 .1
1431 .0
1432 .iter()
1433 .chain(config.user_config.as_ref().into_iter().flat_map(|it| it.1.0.iter()))
1434 .chain(config.ratoml_file.values().flat_map(|it| it.1.0.iter()))
1435 .chain(config.validation_errors.0.iter())
1436 .cloned()
1437 .collect(),
1438 );
1439 (config, e, should_update)
1440 }
1441
1442 pub fn add_discovered_project_from_command(
1443 &mut self,
1444 data: ProjectJsonData,
1445 buildfile: AbsPathBuf,
1446 ) {
1447 for proj in self.discovered_projects_from_command.iter_mut() {
1448 if proj.buildfile == buildfile {
1449 proj.data = data;
1450 return;
1451 }
1452 }
1453
1454 self.discovered_projects_from_command.push(ProjectJsonFromCommand { data, buildfile });
1455 }
1456
1457 pub fn workspace_roots(&self) -> &[AbsPathBuf] {
1458 &self.workspace_roots
1459 }
1460}
1461
1462#[derive(Default, Debug)]
1463pub struct ConfigChange {
1464 user_config_change: Option<Arc<str>>,
1465 client_config_change: Option<serde_json::Value>,
1466 ratoml_file_change:
1467 Option<FxHashMap<SourceRootId, (RatomlFileKind, VfsPath, Option<Arc<str>>)>>,
1468 source_map_change: Option<Arc<FxHashMap<SourceRootId, SourceRootId>>>,
1469}
1470
1471impl ConfigChange {
1472 pub fn change_ratoml(
1473 &mut self,
1474 source_root: SourceRootId,
1475 vfs_path: VfsPath,
1476 content: Option<Arc<str>>,
1477 ) -> Option<(RatomlFileKind, VfsPath, Option<Arc<str>>)> {
1478 self.ratoml_file_change
1479 .get_or_insert_with(Default::default)
1480 .insert(source_root, (RatomlFileKind::Crate, vfs_path, content))
1481 }
1482
1483 pub fn change_user_config(&mut self, content: Option<Arc<str>>) {
1484 assert!(self.user_config_change.is_none()); self.user_config_change = content;
1486 }
1487
1488 pub fn change_workspace_ratoml(
1489 &mut self,
1490 source_root: SourceRootId,
1491 vfs_path: VfsPath,
1492 content: Option<Arc<str>>,
1493 ) -> Option<(RatomlFileKind, VfsPath, Option<Arc<str>>)> {
1494 self.ratoml_file_change
1495 .get_or_insert_with(Default::default)
1496 .insert(source_root, (RatomlFileKind::Workspace, vfs_path, content))
1497 }
1498
1499 pub fn change_client_config(&mut self, change: serde_json::Value) {
1500 self.client_config_change = Some(change);
1501 }
1502
1503 pub fn change_source_root_parent_map(
1504 &mut self,
1505 source_root_map: Arc<FxHashMap<SourceRootId, SourceRootId>>,
1506 ) {
1507 assert!(self.source_map_change.is_none());
1508 self.source_map_change = Some(source_root_map);
1509 }
1510}
1511
1512#[derive(Debug, Clone, Eq, PartialEq)]
1513pub enum LinkedProject {
1514 ProjectManifest(ProjectManifest),
1515 InlineProjectJson(ProjectJson),
1516}
1517
1518impl From<ProjectManifest> for LinkedProject {
1519 fn from(v: ProjectManifest) -> Self {
1520 LinkedProject::ProjectManifest(v)
1521 }
1522}
1523
1524impl From<ProjectJson> for LinkedProject {
1525 fn from(v: ProjectJson) -> Self {
1526 LinkedProject::InlineProjectJson(v)
1527 }
1528}
1529
1530#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1531#[serde(rename_all = "camelCase")]
1532pub struct DiscoverWorkspaceConfig {
1533 pub command: Vec<String>,
1534 pub progress_label: String,
1535 pub files_to_watch: Vec<String>,
1536}
1537
1538pub struct CallInfoConfig {
1539 pub params_only: bool,
1540 pub docs: bool,
1541}
1542
1543#[derive(Clone, Debug, PartialEq, Eq)]
1544pub struct LensConfig {
1545 pub run: bool,
1547 pub debug: bool,
1548 pub update_test: bool,
1549 pub interpret: bool,
1550
1551 pub implementations: bool,
1553
1554 pub method_refs: bool,
1556 pub refs_adt: bool, pub refs_trait: bool, pub enum_variant_refs: bool,
1559
1560 pub refs_exclude_imports: bool,
1561 pub refs_exclude_tests: bool,
1562
1563 pub location: AnnotationLocation,
1565 pub filter_adjacent_derive_implementations: bool,
1566
1567 disable_ra_fixture: bool,
1568}
1569
1570#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1571#[serde(rename_all = "snake_case")]
1572pub enum AnnotationLocation {
1573 AboveName,
1574 AboveWholeItem,
1575}
1576
1577impl From<AnnotationLocation> for ide::AnnotationLocation {
1578 fn from(location: AnnotationLocation) -> Self {
1579 match location {
1580 AnnotationLocation::AboveName => ide::AnnotationLocation::AboveName,
1581 AnnotationLocation::AboveWholeItem => ide::AnnotationLocation::AboveWholeItem,
1582 }
1583 }
1584}
1585
1586impl LensConfig {
1587 pub fn any(&self) -> bool {
1588 self.run
1589 || self.debug
1590 || self.update_test
1591 || self.implementations
1592 || self.method_refs
1593 || self.refs_adt
1594 || self.refs_trait
1595 || self.enum_variant_refs
1596 }
1597
1598 pub fn none(&self) -> bool {
1599 !self.any()
1600 }
1601
1602 pub fn runnable(&self) -> bool {
1603 self.run || self.debug || self.update_test
1604 }
1605
1606 pub fn into_annotation_config<'a>(
1607 self,
1608 binary_target: bool,
1609 minicore: MiniCore<'a>,
1610 ) -> AnnotationConfig<'a> {
1611 AnnotationConfig {
1612 binary_target,
1613 annotate_runnables: self.runnable(),
1614 annotate_impls: self.implementations,
1615 annotate_references: self.refs_adt,
1616 annotate_method_references: self.method_refs,
1617 annotate_enum_variant_references: self.enum_variant_refs,
1618 references_exclude_imports: self.refs_exclude_imports,
1619 references_exclude_tests: self.refs_exclude_tests,
1620 location: self.location.into(),
1621 ra_fixture: RaFixtureConfig { minicore, disable_ra_fixture: self.disable_ra_fixture },
1622 filter_adjacent_derive_implementations: self.filter_adjacent_derive_implementations,
1623 }
1624 }
1625}
1626
1627#[derive(Clone, Debug, PartialEq, Eq)]
1628pub struct HoverActionsConfig {
1629 pub implementations: bool,
1630 pub references: bool,
1631 pub run: bool,
1632 pub debug: bool,
1633 pub update_test: bool,
1634 pub goto_type_def: bool,
1635}
1636
1637impl HoverActionsConfig {
1638 pub const NO_ACTIONS: Self = Self {
1639 implementations: false,
1640 references: false,
1641 run: false,
1642 debug: false,
1643 update_test: false,
1644 goto_type_def: false,
1645 };
1646
1647 pub fn any(&self) -> bool {
1648 self.implementations || self.references || self.runnable() || self.goto_type_def
1649 }
1650
1651 pub fn none(&self) -> bool {
1652 !self.any()
1653 }
1654
1655 pub fn runnable(&self) -> bool {
1656 self.run || self.debug || self.update_test
1657 }
1658}
1659
1660#[derive(Debug, Clone)]
1661pub struct FilesConfig {
1662 pub watcher: FilesWatcher,
1663 pub exclude: Vec<AbsPathBuf>,
1664}
1665
1666#[derive(Debug, Clone)]
1667pub enum FilesWatcher {
1668 Client,
1669 Server,
1670}
1671
1672#[derive(Debug, Clone)]
1674pub struct DocumentSymbolConfig {
1675 pub search_exclude_locals: bool,
1677}
1678
1679#[derive(Debug, Clone)]
1680pub struct NotificationsConfig {
1681 pub cargo_toml_not_found: bool,
1682}
1683
1684#[derive(Debug, Clone)]
1685pub enum RustfmtConfig {
1686 Rustfmt { extra_args: Vec<String>, enable_range_formatting: bool },
1687 CustomCommand { command: String, args: Vec<String> },
1688}
1689
1690#[derive(Debug, Clone)]
1692pub struct RunnablesConfig {
1693 pub override_cargo: Option<String>,
1695 pub cargo_extra_args: Vec<String>,
1697 pub config_path: Option<AbsPathBuf>,
1699 pub extra_test_binary_args: Vec<String>,
1701 pub test_command: String,
1703 pub test_override_command: Option<Vec<String>>,
1705 pub bench_command: String,
1707 pub bench_override_command: Option<Vec<String>>,
1709 pub doc_test_override_command: Option<Vec<String>>,
1711}
1712
1713#[derive(Debug, Clone)]
1715pub struct WorkspaceSymbolConfig {
1716 pub search_exclude_imports: bool,
1718 pub search_scope: WorkspaceSymbolSearchScope,
1720 pub search_kind: WorkspaceSymbolSearchKind,
1722 pub search_limit: usize,
1724}
1725#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1726pub struct ClientCommandsConfig {
1727 pub run_single: bool,
1728 pub debug_single: bool,
1729 pub show_reference: bool,
1730 pub goto_location: bool,
1731 pub trigger_parameter_hints: bool,
1732 pub rename: bool,
1733}
1734
1735#[derive(Debug)]
1736pub enum ConfigErrorInner {
1737 Json { config_key: String, error: serde_json::Error },
1738 Toml { config_key: String, error: toml::de::Error },
1739 ParseError { reason: String },
1740}
1741
1742#[derive(Clone, Debug, Default)]
1743pub struct ConfigErrors(Vec<Arc<ConfigErrorInner>>);
1744
1745impl ConfigErrors {
1746 pub fn is_empty(&self) -> bool {
1747 self.0.is_empty()
1748 }
1749}
1750
1751impl fmt::Display for ConfigErrors {
1752 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1753 let errors = self.0.iter().format_with("\n", |inner, f| {
1754 match &**inner {
1755 ConfigErrorInner::Json { config_key: key, error: e } => {
1756 f(key)?;
1757 f(&": ")?;
1758 f(e)
1759 }
1760 ConfigErrorInner::Toml { config_key: key, error: e } => {
1761 f(key)?;
1762 f(&": ")?;
1763 f(e)
1764 }
1765 ConfigErrorInner::ParseError { reason } => f(reason),
1766 }?;
1767 f(&";")
1768 });
1769 write!(f, "invalid config value{}:\n{}", if self.0.len() == 1 { "" } else { "s" }, errors)
1770 }
1771}
1772
1773impl std::error::Error for ConfigErrors {}
1774
1775impl Config {
1776 pub fn new(
1777 root_path: AbsPathBuf,
1778 caps: lsp_types::ClientCapabilities,
1779 workspace_roots: Vec<AbsPathBuf>,
1780 client_info: Option<lsp_types::ClientInfo>,
1781 ) -> Self {
1782 static DEFAULT_CONFIG_DATA: OnceLock<&'static DefaultConfigData> = OnceLock::new();
1783
1784 Config {
1785 caps: ClientCapabilities::new(caps),
1786 discovered_projects_from_filesystem: Vec::new(),
1787 discovered_projects_from_command: Vec::new(),
1788 root_path,
1789 snippets: Default::default(),
1790 workspace_roots,
1791 client_info: client_info.map(|it| ClientInfo {
1792 name: it.name,
1793 version: it.version.as_deref().map(Version::parse).and_then(Result::ok),
1794 }),
1795 client_config: (FullConfigInput::default(), ConfigErrors(vec![])),
1796 default_config: DEFAULT_CONFIG_DATA.get_or_init(|| Box::leak(Box::default())),
1797 source_root_parent_map: Arc::new(FxHashMap::default()),
1798 user_config: None,
1799 detached_files: Default::default(),
1800 validation_errors: Default::default(),
1801 ratoml_file: Default::default(),
1802 }
1803 }
1804
1805 pub fn rediscover_workspaces(&mut self) {
1806 let discovered = ProjectManifest::discover_all(&self.workspace_roots);
1807 tracing::info!("discovered projects: {:?}", discovered);
1808 if discovered.is_empty() {
1809 tracing::error!("failed to find any projects in {:?}", &self.workspace_roots);
1810 }
1811 self.discovered_projects_from_filesystem = discovered;
1812 }
1813
1814 pub fn remove_workspace(&mut self, path: &AbsPath) {
1815 if let Some(position) = self.workspace_roots.iter().position(|it| it == path) {
1816 self.workspace_roots.remove(position);
1817 }
1818 }
1819
1820 pub fn add_workspaces(&mut self, paths: impl Iterator<Item = AbsPathBuf>) {
1821 self.workspace_roots.extend(paths);
1822 }
1823
1824 pub fn json_schema() -> serde_json::Value {
1825 let mut s = FullConfigInput::json_schema();
1826
1827 fn sort_objects_by_field(json: &mut serde_json::Value) {
1828 if let serde_json::Value::Object(object) = json {
1829 let old = std::mem::take(object);
1830 old.into_iter().sorted_by(|(k, _), (k2, _)| k.cmp(k2)).for_each(|(k, mut v)| {
1831 sort_objects_by_field(&mut v);
1832 object.insert(k, v);
1833 });
1834 }
1835 }
1836 sort_objects_by_field(&mut s);
1837 s
1838 }
1839
1840 pub fn workspace_root_for(&self, path: &AbsPath) -> &AbsPathBuf {
1843 self.workspace_roots
1844 .iter()
1845 .filter(|root| path.starts_with(root.as_path()))
1846 .max_by_key(|root| root.as_str().len())
1847 .unwrap_or(self.default_root_path())
1848 }
1849
1850 pub fn default_root_path(&self) -> &AbsPathBuf {
1856 self.workspace_roots.first().unwrap_or(&self.root_path)
1857 }
1858
1859 pub fn caps(&self) -> &ClientCapabilities {
1860 &self.caps
1861 }
1862
1863 pub fn assist(&self, source_root: Option<SourceRootId>) -> AssistConfig {
1864 AssistConfig {
1865 snippet_cap: self.snippet_cap(),
1866 allowed: None,
1867 insert_use: self.insert_use_config(source_root),
1868 prefer_no_std: self.imports_preferNoStd(source_root).to_owned(),
1869 assist_emit_must_use: self.assist_emitMustUse(source_root).to_owned(),
1870 prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
1871 prefer_absolute: self.imports_prefixExternPrelude(source_root).to_owned(),
1872 term_search_fuel: self.assist_termSearch_fuel(source_root).to_owned() as u64,
1873 code_action_grouping: self.code_action_group(),
1874 expr_fill_default: match self.assist_expressionFillDefault(source_root) {
1875 ExprFillDefaultDef::Todo => ExprFillDefaultMode::Todo,
1876 ExprFillDefaultDef::Default => ExprFillDefaultMode::Default,
1877 ExprFillDefaultDef::Underscore => ExprFillDefaultMode::Underscore,
1878 },
1879 prefer_self_ty: *self.assist_preferSelf(source_root),
1880 show_rename_conflicts: *self.rename_showConflicts(source_root),
1881 }
1882 }
1883
1884 pub fn rename(&self, source_root: Option<SourceRootId>) -> RenameConfig {
1885 RenameConfig {
1886 prefer_no_std: self.imports_preferNoStd(source_root).to_owned(),
1887 prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
1888 prefer_absolute: self.imports_prefixExternPrelude(source_root).to_owned(),
1889 show_conflicts: *self.rename_showConflicts(source_root),
1890 }
1891 }
1892
1893 pub fn ra_fixture<'a>(&self, minicore: MiniCore<'a>) -> RaFixtureConfig<'a> {
1894 RaFixtureConfig { minicore, disable_ra_fixture: *self.disableFixtureSupport(None) }
1895 }
1896
1897 pub fn call_hierarchy<'a>(&self, minicore: MiniCore<'a>) -> CallHierarchyConfig<'a> {
1898 CallHierarchyConfig {
1899 exclude_tests: self.references_excludeTests().to_owned(),
1900 ra_fixture: self.ra_fixture(minicore),
1901 }
1902 }
1903
1904 pub fn completion<'a>(
1905 &'a self,
1906 source_root: Option<SourceRootId>,
1907 minicore: MiniCore<'a>,
1908 ) -> CompletionConfig<'a> {
1909 let client_capability_fields = self.completion_resolve_support_properties();
1910 CompletionConfig {
1911 enable_postfix_completions: self.completion_postfix_enable(source_root).to_owned(),
1912 enable_imports_on_the_fly: self.completion_autoimport_enable(source_root).to_owned()
1913 && self.caps.has_completion_item_resolve_additionalTextEdits(),
1914 enable_self_on_the_fly: self.completion_autoself_enable(source_root).to_owned(),
1915 enable_auto_iter: *self.completion_autoIter_enable(source_root),
1916 enable_auto_await: *self.completion_autoAwait_enable(source_root),
1917 enable_auto_dyn: *self.completion_autoDyn_enable(source_root),
1918 enable_private_editable: self.completion_privateEditable_enable(source_root).to_owned(),
1919 full_function_signatures: self
1920 .completion_fullFunctionSignatures_enable(source_root)
1921 .to_owned(),
1922 callable: match self.completion_callable_snippets(source_root) {
1923 CallableCompletionDef::FillArguments => Some(CallableSnippets::FillArguments),
1924 CallableCompletionDef::AddParentheses => Some(CallableSnippets::AddParentheses),
1925 CallableCompletionDef::None => None,
1926 },
1927 add_colons_to_module: *self.completion_addColonsToModule(source_root),
1928 add_semicolon_to_unit: *self.completion_addSemicolonToUnit(source_root),
1929 snippet_cap: SnippetCap::new(self.completion_snippet()),
1930 insert_use: self.insert_use_config(source_root),
1931 prefer_no_std: self.imports_preferNoStd(source_root).to_owned(),
1932 prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
1933 prefer_absolute: self.imports_prefixExternPrelude(source_root).to_owned(),
1934 snippets: self.snippets.clone().to_vec(),
1935 limit: self.completion_limit(source_root).to_owned(),
1936 enable_term_search: self.completion_termSearch_enable(source_root).to_owned(),
1937 term_search_fuel: self.completion_termSearch_fuel(source_root).to_owned() as u64,
1938 enable_turbofish: self.completion_turbofish_enable(source_root).to_owned(),
1939 fields_to_resolve: if self.client_is_neovim() {
1940 CompletionFieldsToResolve::empty()
1941 } else {
1942 CompletionFieldsToResolve::from_client_capabilities(&client_capability_fields)
1943 },
1944 exclude_flyimport: self
1945 .completion_autoimport_exclude(source_root)
1946 .iter()
1947 .map(|it| match it {
1948 AutoImportExclusion::Path(path) => {
1949 (path.clone(), ide_completion::AutoImportExclusionType::Always)
1950 }
1951 AutoImportExclusion::Verbose { path, r#type } => (
1952 path.clone(),
1953 match r#type {
1954 AutoImportExclusionType::Always => {
1955 ide_completion::AutoImportExclusionType::Always
1956 }
1957 AutoImportExclusionType::Methods => {
1958 ide_completion::AutoImportExclusionType::Methods
1959 }
1960 AutoImportExclusionType::SubItems => {
1961 ide_completion::AutoImportExclusionType::SubItems
1962 }
1963 AutoImportExclusionType::Variants => {
1964 ide_completion::AutoImportExclusionType::Variants
1965 }
1966 },
1967 ),
1968 })
1969 .collect(),
1970 exclude_traits: self.completion_excludeTraits(source_root),
1971 ra_fixture: self.ra_fixture(minicore),
1972 }
1973 }
1974
1975 pub fn completion_hide_deprecated(&self) -> bool {
1976 *self.completion_hideDeprecated(None)
1977 }
1978
1979 pub fn detached_files(&self) -> &Vec<AbsPathBuf> {
1980 &self.detached_files
1983 }
1984
1985 pub fn diagnostics(&self, source_root: Option<SourceRootId>) -> DiagnosticsConfig {
1986 DiagnosticsConfig {
1987 enabled: *self.diagnostics_enable(source_root),
1988 proc_attr_macros_enabled: self.expand_proc_attr_macros(),
1989 proc_macros_enabled: *self.procMacro_enable(),
1990 disable_experimental: !self.diagnostics_experimental_enable(source_root),
1991 disabled: self.diagnostics_disabled(source_root).clone(),
1992 expr_fill_default: match self.assist_expressionFillDefault(source_root) {
1993 ExprFillDefaultDef::Todo => ExprFillDefaultMode::Todo,
1994 ExprFillDefaultDef::Default => ExprFillDefaultMode::Default,
1995 ExprFillDefaultDef::Underscore => ExprFillDefaultMode::Underscore,
1996 },
1997 snippet_cap: self.snippet_cap(),
1998 insert_use: self.insert_use_config(source_root),
1999 prefer_no_std: self.imports_preferNoStd(source_root).to_owned(),
2000 prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
2001 prefer_absolute: self.imports_prefixExternPrelude(source_root).to_owned(),
2002 style_lints: self.diagnostics_styleLints_enable(source_root).to_owned(),
2003 term_search_fuel: self.assist_termSearch_fuel(source_root).to_owned() as u64,
2004 show_rename_conflicts: *self.rename_showConflicts(source_root),
2005 }
2006 }
2007
2008 pub fn diagnostic_fixes(&self, source_root: Option<SourceRootId>) -> DiagnosticsConfig {
2009 DiagnosticsConfig {
2011 enabled: true,
2012 disable_experimental: false,
2013 ..self.diagnostics(source_root)
2014 }
2015 }
2016
2017 pub fn expand_proc_attr_macros(&self) -> bool {
2018 self.procMacro_enable().to_owned() && self.procMacro_attributes_enable().to_owned()
2019 }
2020
2021 pub fn highlight_related(&self, _source_root: Option<SourceRootId>) -> HighlightRelatedConfig {
2022 HighlightRelatedConfig {
2023 references: self.highlightRelated_references_enable().to_owned(),
2024 break_points: self.highlightRelated_breakPoints_enable().to_owned(),
2025 exit_points: self.highlightRelated_exitPoints_enable().to_owned(),
2026 yield_points: self.highlightRelated_yieldPoints_enable().to_owned(),
2027 closure_captures: self.highlightRelated_closureCaptures_enable().to_owned(),
2028 branch_exit_points: self.highlightRelated_branchExitPoints_enable().to_owned(),
2029 }
2030 }
2031
2032 pub fn hover_actions(&self) -> HoverActionsConfig {
2033 let enable = self.caps.hover_actions() && self.hover_actions_enable().to_owned();
2034 HoverActionsConfig {
2035 implementations: enable && self.hover_actions_implementations_enable().to_owned(),
2036 references: enable && self.hover_actions_references_enable().to_owned(),
2037 run: enable && self.hover_actions_run_enable().to_owned(),
2038 debug: enable && self.hover_actions_debug_enable().to_owned(),
2039 update_test: enable
2040 && self.hover_actions_run_enable().to_owned()
2041 && self.hover_actions_updateTest_enable().to_owned(),
2042 goto_type_def: enable && self.hover_actions_gotoTypeDef_enable().to_owned(),
2043 }
2044 }
2045
2046 pub fn hover<'a>(&self, minicore: MiniCore<'a>) -> HoverConfig<'a> {
2047 let mem_kind = |kind| match kind {
2048 MemoryLayoutHoverRenderKindDef::Both => MemoryLayoutHoverRenderKind::Both,
2049 MemoryLayoutHoverRenderKindDef::Decimal => MemoryLayoutHoverRenderKind::Decimal,
2050 MemoryLayoutHoverRenderKindDef::Hexadecimal => MemoryLayoutHoverRenderKind::Hexadecimal,
2051 };
2052 HoverConfig {
2053 links_in_hover: self.hover_links_enable().to_owned(),
2054 memory_layout: self.hover_memoryLayout_enable().then_some(MemoryLayoutHoverConfig {
2055 size: self.hover_memoryLayout_size().map(mem_kind),
2056 offset: self.hover_memoryLayout_offset().map(mem_kind),
2057 alignment: self.hover_memoryLayout_alignment().map(mem_kind),
2058 padding: self.hover_memoryLayout_padding().map(mem_kind),
2059 niches: self.hover_memoryLayout_niches().unwrap_or_default(),
2060 }),
2061 documentation: self.hover_documentation_enable().to_owned(),
2062 format: {
2063 if self.caps.hover_markdown_support() {
2064 HoverDocFormat::Markdown
2065 } else {
2066 HoverDocFormat::PlainText
2067 }
2068 },
2069 keywords: self.hover_documentation_keywords_enable().to_owned(),
2070 max_trait_assoc_items_count: self.hover_show_traitAssocItems().to_owned(),
2071 max_fields_count: self.hover_show_fields().to_owned(),
2072 max_enum_variants_count: self.hover_show_enumVariants().to_owned(),
2073 max_subst_ty_len: match self.hover_maxSubstitutionLength() {
2074 Some(MaxSubstitutionLength::Hide) => ide::SubstTyLen::Hide,
2075 Some(MaxSubstitutionLength::Limit(limit)) => ide::SubstTyLen::LimitTo(*limit),
2076 None => ide::SubstTyLen::Unlimited,
2077 },
2078 show_drop_glue: *self.hover_dropGlue_enable(),
2079 ra_fixture: self.ra_fixture(minicore),
2080 }
2081 }
2082
2083 pub fn goto_definition<'a>(&self, minicore: MiniCore<'a>) -> GotoDefinitionConfig<'a> {
2084 GotoDefinitionConfig { ra_fixture: self.ra_fixture(minicore) }
2085 }
2086
2087 pub fn inlay_hints<'a>(&self, minicore: MiniCore<'a>) -> InlayHintsConfig<'a> {
2088 let client_capability_fields = self.inlay_hint_resolve_support_properties();
2089
2090 InlayHintsConfig {
2091 render_colons: self.inlayHints_renderColons().to_owned(),
2092 type_hints: self.inlayHints_typeHints_enable().to_owned(),
2093 type_hints_placement: match self.inlayHints_typeHints_location() {
2094 TypeHintsLocation::Inline => ide::TypeHintsPlacement::Inline,
2095 TypeHintsLocation::EndOfLine => ide::TypeHintsPlacement::EndOfLine,
2096 },
2097 sized_bound: self.inlayHints_implicitSizedBoundHints_enable().to_owned(),
2098 parameter_hints: self.inlayHints_parameterHints_enable().to_owned(),
2099 parameter_hints_for_missing_arguments: self
2100 .inlayHints_parameterHints_missingArguments_enable()
2101 .to_owned(),
2102 generic_parameter_hints: GenericParameterHints {
2103 type_hints: self.inlayHints_genericParameterHints_type_enable().to_owned(),
2104 lifetime_hints: self.inlayHints_genericParameterHints_lifetime_enable().to_owned(),
2105 const_hints: self.inlayHints_genericParameterHints_const_enable().to_owned(),
2106 },
2107 chaining_hints: self.inlayHints_chainingHints_enable().to_owned(),
2108 discriminant_hints: match self.inlayHints_discriminantHints_enable() {
2109 DiscriminantHintsDef::Always => ide::DiscriminantHints::Always,
2110 DiscriminantHintsDef::Never => ide::DiscriminantHints::Never,
2111 DiscriminantHintsDef::Fieldless => ide::DiscriminantHints::Fieldless,
2112 },
2113 closure_return_type_hints: match self.inlayHints_closureReturnTypeHints_enable() {
2114 ClosureReturnTypeHintsDef::Always => ide::ClosureReturnTypeHints::Always,
2115 ClosureReturnTypeHintsDef::Never => ide::ClosureReturnTypeHints::Never,
2116 ClosureReturnTypeHintsDef::WithBlock => ide::ClosureReturnTypeHints::WithBlock,
2117 },
2118 lifetime_elision_hints: match self.inlayHints_lifetimeElisionHints_enable() {
2119 LifetimeElisionDef::Always => ide::LifetimeElisionHints::Always,
2120 LifetimeElisionDef::Never => ide::LifetimeElisionHints::Never,
2121 LifetimeElisionDef::SkipTrivial => ide::LifetimeElisionHints::SkipTrivial,
2122 },
2123 hide_named_constructor_hints: self
2124 .inlayHints_typeHints_hideNamedConstructor()
2125 .to_owned(),
2126 hide_inferred_type_hints: self.inlayHints_typeHints_hideInferredTypes().to_owned(),
2127 hide_closure_initialization_hints: self
2128 .inlayHints_typeHints_hideClosureInitialization()
2129 .to_owned(),
2130 hide_closure_parameter_hints: self
2131 .inlayHints_typeHints_hideClosureParameter()
2132 .to_owned(),
2133 closure_style: match self.inlayHints_closureStyle() {
2134 ClosureStyle::ImplFn => hir::ClosureStyle::ImplFn,
2135 ClosureStyle::RustAnalyzer => hir::ClosureStyle::RANotation,
2136 ClosureStyle::WithId => hir::ClosureStyle::ClosureWithId,
2137 ClosureStyle::Hide => hir::ClosureStyle::Hide,
2138 },
2139 closure_capture_hints: self.inlayHints_closureCaptureHints_enable().to_owned(),
2140 adjustment_hints: match self.inlayHints_expressionAdjustmentHints_enable() {
2141 AdjustmentHintsDef::Always => ide::AdjustmentHints::Always,
2142 AdjustmentHintsDef::Never => match self.inlayHints_reborrowHints_enable() {
2143 ReborrowHintsDef::Always | ReborrowHintsDef::Mutable => {
2144 ide::AdjustmentHints::BorrowsOnly
2145 }
2146 ReborrowHintsDef::Never => ide::AdjustmentHints::Never,
2147 },
2148 AdjustmentHintsDef::Borrows => ide::AdjustmentHints::BorrowsOnly,
2149 },
2150 adjustment_hints_disable_reborrows: *self
2151 .inlayHints_expressionAdjustmentHints_disableReborrows(),
2152 adjustment_hints_mode: match self.inlayHints_expressionAdjustmentHints_mode() {
2153 AdjustmentHintsModeDef::Prefix => ide::AdjustmentHintsMode::Prefix,
2154 AdjustmentHintsModeDef::Postfix => ide::AdjustmentHintsMode::Postfix,
2155 AdjustmentHintsModeDef::PreferPrefix => ide::AdjustmentHintsMode::PreferPrefix,
2156 AdjustmentHintsModeDef::PreferPostfix => ide::AdjustmentHintsMode::PreferPostfix,
2157 },
2158 adjustment_hints_hide_outside_unsafe: self
2159 .inlayHints_expressionAdjustmentHints_hideOutsideUnsafe()
2160 .to_owned(),
2161 binding_mode_hints: self.inlayHints_bindingModeHints_enable().to_owned(),
2162 param_names_for_lifetime_elision_hints: self
2163 .inlayHints_lifetimeElisionHints_useParameterNames()
2164 .to_owned(),
2165 max_length: self.inlayHints_maxLength().to_owned(),
2166 closing_brace_hints_min_lines: if self.inlayHints_closingBraceHints_enable().to_owned()
2167 {
2168 Some(self.inlayHints_closingBraceHints_minLines().to_owned())
2169 } else {
2170 None
2171 },
2172 fields_to_resolve: InlayFieldsToResolve::from_client_capabilities(
2173 &client_capability_fields,
2174 ),
2175 implicit_drop_hints: match self.inlayHints_implicitDrops_enable() {
2176 ImplicitDropDef::Always => ide::ImplicitDropHints::Always,
2177 ImplicitDropDef::WithDropGlue => ide::ImplicitDropHints::WithDropGlue,
2178 ImplicitDropDef::Never => ide::ImplicitDropHints::Never,
2179 },
2180 implied_dyn_trait_hints: self.inlayHints_impliedDynTraitHints_enable().to_owned(),
2181 range_exclusive_hints: self.inlayHints_rangeExclusiveHints_enable().to_owned(),
2182 ra_fixture: self.ra_fixture(minicore),
2183 }
2184 }
2185
2186 fn insert_use_config(&self, source_root: Option<SourceRootId>) -> InsertUseConfig {
2187 InsertUseConfig {
2188 granularity: match self.imports_granularity_group(source_root) {
2189 ImportGranularityDef::Item | ImportGranularityDef::Preserve => {
2190 ImportGranularity::Item
2191 }
2192 ImportGranularityDef::Crate => ImportGranularity::Crate,
2193 ImportGranularityDef::Module => ImportGranularity::Module,
2194 ImportGranularityDef::One => ImportGranularity::One,
2195 },
2196 enforce_granularity: self.imports_granularity_enforce(source_root).to_owned(),
2197 prefix_kind: match self.imports_prefix(source_root) {
2198 ImportPrefixDef::Plain => PrefixKind::Plain,
2199 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
2200 ImportPrefixDef::BySelf => PrefixKind::BySelf,
2201 },
2202 group: self.imports_group_enable(source_root).to_owned(),
2203 skip_glob_imports: !self.imports_merge_glob(source_root),
2204 }
2205 }
2206
2207 pub fn join_lines(&self) -> JoinLinesConfig {
2208 JoinLinesConfig {
2209 join_else_if: self.joinLines_joinElseIf().to_owned(),
2210 remove_trailing_comma: self.joinLines_removeTrailingComma().to_owned(),
2211 unwrap_trivial_blocks: self.joinLines_unwrapTrivialBlock().to_owned(),
2212 join_assignments: self.joinLines_joinAssignments().to_owned(),
2213 }
2214 }
2215
2216 pub fn highlighting_non_standard_tokens(&self) -> bool {
2217 self.semanticHighlighting_nonStandardTokens().to_owned()
2218 }
2219
2220 pub fn highlighting_config<'a>(&self, minicore: MiniCore<'a>) -> HighlightConfig<'a> {
2221 HighlightConfig {
2222 strings: self.semanticHighlighting_strings_enable().to_owned(),
2223 comments: self.semanticHighlighting_comments_enable().to_owned(),
2224 punctuation: self.semanticHighlighting_punctuation_enable().to_owned(),
2225 specialize_punctuation: self
2226 .semanticHighlighting_punctuation_specialization_enable()
2227 .to_owned(),
2228 macro_bang: self.semanticHighlighting_punctuation_separate_macro_bang().to_owned(),
2229 operator: self.semanticHighlighting_operator_enable().to_owned(),
2230 specialize_operator: self
2231 .semanticHighlighting_operator_specialization_enable()
2232 .to_owned(),
2233 inject_doc_comment: self.semanticHighlighting_doc_comment_inject_enable().to_owned(),
2234 syntactic_name_ref_highlighting: false,
2235 ra_fixture: self.ra_fixture(minicore),
2236 }
2237 }
2238
2239 pub fn has_linked_projects(&self) -> bool {
2240 !self.linkedProjects().is_empty()
2241 }
2242
2243 pub fn linked_manifests(&self) -> impl Iterator<Item = &Utf8Path> + '_ {
2244 self.linkedProjects().iter().filter_map(|it| match it {
2245 ManifestOrProjectJson::Manifest(p) => Some(&**p),
2246 ManifestOrProjectJson::DiscoveredProjectJson { .. } => None,
2249 ManifestOrProjectJson::ProjectJson { .. } => None,
2250 })
2251 }
2252
2253 pub fn has_linked_project_jsons(&self) -> bool {
2254 self.linkedProjects()
2255 .iter()
2256 .any(|it| matches!(it, ManifestOrProjectJson::ProjectJson { .. }))
2257 }
2258
2259 pub fn discover_workspace_config(&self) -> Option<&DiscoverWorkspaceConfig> {
2260 self.workspace_discoverConfig().as_ref()
2261 }
2262
2263 fn discovered_projects(&self) -> Vec<ManifestOrProjectJson> {
2264 let exclude_dirs: Vec<_> =
2265 self.files_exclude().iter().map(|p| self.root_path.join(p)).collect();
2266
2267 let mut projects = vec![];
2268 for fs_proj in &self.discovered_projects_from_filesystem {
2269 let manifest_path = fs_proj.manifest_path();
2270 if exclude_dirs.iter().any(|p| manifest_path.starts_with(p)) {
2271 continue;
2272 }
2273
2274 let buf: Utf8PathBuf = manifest_path.to_path_buf().into();
2275 projects.push(ManifestOrProjectJson::Manifest(buf));
2276 }
2277
2278 for dis_proj in &self.discovered_projects_from_command {
2279 projects.push(ManifestOrProjectJson::DiscoveredProjectJson {
2280 data: dis_proj.data.clone(),
2281 buildfile: dis_proj.buildfile.clone(),
2282 });
2283 }
2284
2285 projects
2286 }
2287
2288 pub fn linked_or_discovered_projects(&self) -> Vec<LinkedProject> {
2289 let linked_projects = self.linkedProjects();
2290 let projects = if linked_projects.is_empty() {
2291 self.discovered_projects()
2292 } else {
2293 linked_projects.clone()
2294 };
2295
2296 projects
2297 .iter()
2298 .filter_map(|linked_project| match linked_project {
2299 ManifestOrProjectJson::Manifest(it) => {
2300 let path = self.root_path.join(it);
2301 ProjectManifest::from_manifest_file(path)
2302 .map_err(|e| tracing::error!("failed to load linked project: {}", e))
2303 .ok()
2304 .map(Into::into)
2305 }
2306 ManifestOrProjectJson::DiscoveredProjectJson { data, buildfile } => {
2307 let root_path = buildfile.parent().expect("Unable to get parent of buildfile");
2308
2309 Some(ProjectJson::new(None, root_path, data.clone()).into())
2310 }
2311 ManifestOrProjectJson::ProjectJson(it) => {
2312 Some(ProjectJson::new(None, &self.root_path, it.clone()).into())
2313 }
2314 })
2315 .collect()
2316 }
2317
2318 pub fn prefill_caches(&self) -> bool {
2319 self.cachePriming_enable().to_owned()
2320 }
2321
2322 pub fn publish_diagnostics(&self, source_root: Option<SourceRootId>) -> bool {
2323 self.diagnostics_enable(source_root).to_owned()
2324 }
2325
2326 pub fn diagnostics_map(&self, source_root: Option<SourceRootId>) -> DiagnosticsMapConfig {
2327 DiagnosticsMapConfig {
2328 remap_prefix: self.diagnostics_remapPrefix(source_root).clone(),
2329 warnings_as_info: self.diagnostics_warningsAsInfo(source_root).clone(),
2330 warnings_as_hint: self.diagnostics_warningsAsHint(source_root).clone(),
2331 check_ignore: self.check_ignore(source_root).clone(),
2332 }
2333 }
2334
2335 pub fn extra_args(&self, source_root: Option<SourceRootId>) -> &Vec<String> {
2336 self.cargo_extraArgs(source_root)
2337 }
2338
2339 pub fn extra_env(
2340 &self,
2341 source_root: Option<SourceRootId>,
2342 ) -> &FxHashMap<String, Option<String>> {
2343 self.cargo_extraEnv(source_root)
2344 }
2345
2346 pub fn check_extra_args(&self, source_root: Option<SourceRootId>) -> Vec<String> {
2347 let mut extra_args = self.extra_args(source_root).clone();
2348 extra_args.extend_from_slice(self.check_extraArgs(source_root));
2349 extra_args
2350 }
2351
2352 pub fn check_extra_env(
2353 &self,
2354 source_root: Option<SourceRootId>,
2355 ) -> FxHashMap<String, Option<String>> {
2356 let mut extra_env = self.cargo_extraEnv(source_root).clone();
2357 extra_env.extend(self.check_extraEnv(source_root).clone());
2358 extra_env
2359 }
2360
2361 pub fn lru_parse_query_capacity(&self) -> Option<u16> {
2362 self.lru_capacity().to_owned()
2363 }
2364
2365 pub fn lru_query_capacities_config(&self) -> Option<&FxHashMap<Box<str>, u16>> {
2366 self.lru_query_capacities().is_empty().not().then(|| self.lru_query_capacities())
2367 }
2368
2369 pub fn proc_macro_srv(&self) -> Option<AbsPathBuf> {
2370 let path = self.procMacro_server().clone()?;
2371 Some(AbsPathBuf::try_from(path).unwrap_or_else(|path| self.root_path.join(path)))
2372 }
2373
2374 pub fn dhat_output_file(&self) -> Option<AbsPathBuf> {
2375 let path = self.profiling_memoryProfile().clone()?;
2376 Some(AbsPathBuf::try_from(path).unwrap_or_else(|path| self.root_path.join(path)))
2377 }
2378
2379 pub fn ignored_proc_macros(
2380 &self,
2381 source_root: Option<SourceRootId>,
2382 ) -> &FxHashMap<Box<str>, Box<[Box<str>]>> {
2383 self.procMacro_ignored(source_root)
2384 }
2385
2386 pub fn expand_proc_macros(&self) -> bool {
2387 self.procMacro_enable().to_owned()
2388 }
2389
2390 pub fn files(&self) -> FilesConfig {
2391 FilesConfig {
2392 watcher: match self.files_watcher() {
2393 FilesWatcherDef::Client if self.did_change_watched_files_dynamic_registration() => {
2394 FilesWatcher::Client
2395 }
2396 _ => FilesWatcher::Server,
2397 },
2398 exclude: self.excluded().collect(),
2399 }
2400 }
2401
2402 pub fn excluded(&self) -> impl Iterator<Item = AbsPathBuf> + use<'_> {
2403 self.files_exclude().iter().map(|it| self.root_path.join(it))
2404 }
2405
2406 pub fn notifications(&self) -> NotificationsConfig {
2407 NotificationsConfig {
2408 cargo_toml_not_found: self.notifications_cargoTomlNotFound().to_owned(),
2409 }
2410 }
2411
2412 pub fn cargo_autoreload_config(&self, source_root: Option<SourceRootId>) -> bool {
2413 self.cargo_autoreload(source_root).to_owned()
2414 }
2415
2416 pub fn run_build_scripts(&self, source_root: Option<SourceRootId>) -> bool {
2417 self.cargo_buildScripts_enable(source_root).to_owned() || self.procMacro_enable().to_owned()
2418 }
2419
2420 pub fn cargo(&self, source_root: Option<SourceRootId>) -> CargoConfig {
2421 let rustc_source = self.rustc_source(source_root).as_ref().map(|rustc_src| {
2422 if rustc_src == "discover" {
2423 RustLibSource::Discover
2424 } else {
2425 RustLibSource::Path(self.root_path.join(rustc_src))
2426 }
2427 });
2428 let sysroot = self.cargo_sysroot(source_root).as_ref().map(|sysroot| {
2429 if sysroot == "discover" {
2430 RustLibSource::Discover
2431 } else {
2432 RustLibSource::Path(self.root_path.join(sysroot))
2433 }
2434 });
2435 let sysroot_src =
2436 self.cargo_sysrootSrc(source_root).as_ref().map(|sysroot| self.root_path.join(sysroot));
2437 let config_path = self.cargo_config_path(source_root);
2438 let extra_includes = self
2439 .vfs_extraIncludes(source_root)
2440 .iter()
2441 .map(String::as_str)
2442 .map(AbsPathBuf::try_from)
2443 .filter_map(Result::ok)
2444 .collect();
2445
2446 CargoConfig {
2447 all_targets: *self.cargo_allTargets(source_root),
2448 features: match &self.cargo_features(source_root) {
2449 CargoFeaturesDef::All => CargoFeatures::All,
2450 CargoFeaturesDef::Selected(features) => CargoFeatures::Selected {
2451 features: features.clone(),
2452 no_default_features: self.cargo_noDefaultFeatures(source_root).to_owned(),
2453 },
2454 },
2455 target: self.cargo_target(source_root).clone(),
2456 sysroot,
2457 sysroot_src,
2458 rustc_source,
2459 extra_includes,
2460 cfg_overrides: project_model::CfgOverrides {
2461 global: {
2462 let (enabled, disabled): (Vec<_>, Vec<_>) =
2463 self.cargo_cfgs(source_root).iter().partition_map(|s| {
2464 s.strip_prefix("!").map_or(Either::Left(s), Either::Right)
2465 });
2466 CfgDiff::new(
2467 enabled
2468 .into_iter()
2469 .map(|s| match s.split_once("=") {
2471 Some((key, val)) => CfgAtom::KeyValue {
2472 key: Symbol::intern(key),
2473 value: Symbol::intern(val),
2474 },
2475 None => CfgAtom::Flag(Symbol::intern(s)),
2476 })
2477 .collect(),
2478 disabled
2479 .into_iter()
2480 .map(|s| match s.split_once("=") {
2481 Some((key, val)) => CfgAtom::KeyValue {
2482 key: Symbol::intern(key),
2483 value: Symbol::intern(val),
2484 },
2485 None => CfgAtom::Flag(Symbol::intern(s)),
2486 })
2487 .collect(),
2488 )
2489 },
2490 selective: Default::default(),
2491 },
2492 wrap_rustc_in_build_scripts: *self.cargo_buildScripts_useRustcWrapper(source_root),
2493 invocation_strategy: match self.cargo_buildScripts_invocationStrategy(source_root) {
2494 InvocationStrategy::Once => project_model::InvocationStrategy::Once,
2495 InvocationStrategy::PerWorkspace => project_model::InvocationStrategy::PerWorkspace,
2496 },
2497 run_build_script_command: self.cargo_buildScripts_overrideCommand(source_root).clone(),
2498 extra_args: self.cargo_extraArgs(source_root).clone(),
2499 extra_env: self.cargo_extraEnv(source_root).clone(),
2500 target_dir_config: self.target_dir_from_config(source_root),
2501 set_test: *self.cfg_setTest(source_root),
2502 no_deps: *self.cargo_noDeps(source_root),
2503 metadata_extra_args: self.cargo_metadataExtraArgs(source_root).clone(),
2504 config_path,
2505 }
2506 }
2507
2508 pub fn cfg_set_test(&self, source_root: Option<SourceRootId>) -> bool {
2509 *self.cfg_setTest(source_root)
2510 }
2511
2512 pub(crate) fn completion_snippets_default() -> FxIndexMap<String, SnippetDef> {
2513 serde_json::from_str(
2514 r#"{
2515 "Ok": {
2516 "postfix": "ok",
2517 "body": "Ok(${receiver})",
2518 "description": "Wrap the expression in a `Result::Ok`",
2519 "scope": "expr"
2520 },
2521 "Box::pin": {
2522 "postfix": "pinbox",
2523 "body": "Box::pin(${receiver})",
2524 "requires": "std::boxed::Box",
2525 "description": "Put the expression into a pinned `Box`",
2526 "scope": "expr"
2527 },
2528 "Arc::new": {
2529 "postfix": "arc",
2530 "body": "Arc::new(${receiver})",
2531 "requires": "std::sync::Arc",
2532 "description": "Put the expression into an `Arc`",
2533 "scope": "expr"
2534 },
2535 "Some": {
2536 "postfix": "some",
2537 "body": "Some(${receiver})",
2538 "description": "Wrap the expression in an `Option::Some`",
2539 "scope": "expr"
2540 },
2541 "Err": {
2542 "postfix": "err",
2543 "body": "Err(${receiver})",
2544 "description": "Wrap the expression in a `Result::Err`",
2545 "scope": "expr"
2546 },
2547 "Rc::new": {
2548 "postfix": "rc",
2549 "body": "Rc::new(${receiver})",
2550 "requires": "std::rc::Rc",
2551 "description": "Put the expression into an `Rc`",
2552 "scope": "expr"
2553 }
2554 }"#,
2555 )
2556 .unwrap()
2557 }
2558
2559 pub fn rustfmt(&self, source_root_id: Option<SourceRootId>) -> RustfmtConfig {
2560 match &self.rustfmt_overrideCommand(source_root_id) {
2561 Some(args) if !args.is_empty() => {
2562 let mut args = args.clone();
2563 let command = args.remove(0);
2564 RustfmtConfig::CustomCommand { command, args }
2565 }
2566 Some(_) | None => RustfmtConfig::Rustfmt {
2567 extra_args: self.rustfmt_extraArgs(source_root_id).clone(),
2568 enable_range_formatting: *self.rustfmt_rangeFormatting_enable(source_root_id),
2569 },
2570 }
2571 }
2572
2573 pub fn flycheck_workspace(&self, source_root: Option<SourceRootId>) -> bool {
2574 *self.check_workspace(source_root)
2575 }
2576
2577 pub(crate) fn cargo_test_options(&self, source_root: Option<SourceRootId>) -> CargoOptions {
2578 CargoOptions {
2579 subcommand: "test".into(),
2581 target_tuples: self.cargo_target(source_root).clone().into_iter().collect(),
2582 all_targets: false,
2583 no_default_features: *self.cargo_noDefaultFeatures(source_root),
2584 all_features: matches!(self.cargo_features(source_root), CargoFeaturesDef::All),
2585 features: match self.cargo_features(source_root).clone() {
2586 CargoFeaturesDef::All => vec![],
2587 CargoFeaturesDef::Selected(it) => it,
2588 },
2589 extra_args: self.extra_args(source_root).clone(),
2590 extra_test_bin_args: self.runnables_extraTestBinaryArgs(source_root).clone(),
2591 extra_env: self.extra_env(source_root).clone(),
2592 target_dir_config: self.target_dir_from_config(source_root),
2593 set_test: true,
2594 config_path: self.cargo_config_path(source_root),
2595 }
2596 }
2597
2598 pub(crate) fn flycheck(&self, source_root: Option<SourceRootId>) -> FlycheckConfig {
2599 match &self.check_overrideCommand(source_root) {
2600 Some(args) if !args.is_empty() => {
2601 let mut args = args.clone();
2602 let command = args.remove(0);
2603 FlycheckConfig::CustomCommand {
2604 command,
2605 args,
2606 extra_env: self.check_extra_env(source_root),
2607 invocation_strategy: match self.check_invocationStrategy(source_root) {
2608 InvocationStrategy::Once => crate::flycheck::InvocationStrategy::Once,
2609 InvocationStrategy::PerWorkspace => {
2610 crate::flycheck::InvocationStrategy::PerWorkspace
2611 }
2612 },
2613 }
2614 }
2615 Some(_) | None => FlycheckConfig::Automatic {
2616 cargo_options: CargoOptions {
2617 subcommand: self.check_command(source_root).clone(),
2618 target_tuples: self
2619 .check_targets(source_root)
2620 .clone()
2621 .and_then(|targets| match &targets.0[..] {
2622 [] => None,
2623 targets => Some(targets.into()),
2624 })
2625 .unwrap_or_else(|| {
2626 self.cargo_target(source_root).clone().into_iter().collect()
2627 }),
2628 all_targets: self
2629 .check_allTargets(source_root)
2630 .unwrap_or(*self.cargo_allTargets(source_root)),
2631 no_default_features: self
2632 .check_noDefaultFeatures(source_root)
2633 .unwrap_or(*self.cargo_noDefaultFeatures(source_root)),
2634 all_features: matches!(
2635 self.check_features(source_root)
2636 .as_ref()
2637 .unwrap_or(self.cargo_features(source_root)),
2638 CargoFeaturesDef::All
2639 ),
2640 features: match self
2641 .check_features(source_root)
2642 .clone()
2643 .unwrap_or_else(|| self.cargo_features(source_root).clone())
2644 {
2645 CargoFeaturesDef::All => vec![],
2646 CargoFeaturesDef::Selected(it) => it,
2647 },
2648 extra_args: self.check_extra_args(source_root),
2649 extra_test_bin_args: self.runnables_extraTestBinaryArgs(source_root).clone(),
2650 extra_env: self.check_extra_env(source_root),
2651 config_path: self.cargo_config_path(source_root),
2652 target_dir_config: self.target_dir_from_config(source_root),
2653 set_test: *self.cfg_setTest(source_root),
2654 },
2655 ansi_color_output: self.color_diagnostic_output(),
2656 },
2657 }
2658 }
2659
2660 fn cargo_config_path(&self, source_root: Option<SourceRootId>) -> Option<AbsPathBuf> {
2661 self.cargo_configPath(source_root).as_ref().map(|path| self.root_path.join(path))
2662 }
2663
2664 fn target_dir_from_config(&self, source_root: Option<SourceRootId>) -> TargetDirectoryConfig {
2665 match &self.cargo_targetDir(source_root) {
2666 Some(TargetDirectory::UseSubdirectory(true)) => TargetDirectoryConfig::UseSubdirectory,
2667 Some(TargetDirectory::UseSubdirectory(false)) | None => TargetDirectoryConfig::None,
2668 Some(TargetDirectory::Directory(dir)) => TargetDirectoryConfig::Directory(dir.clone()),
2669 }
2670 }
2671
2672 pub fn check_on_save(&self, source_root: Option<SourceRootId>) -> bool {
2673 *self.checkOnSave(source_root)
2674 }
2675
2676 pub fn script_rebuild_on_save(&self, source_root: Option<SourceRootId>) -> bool {
2677 *self.cargo_buildScripts_rebuildOnSave(source_root)
2678 }
2679
2680 pub fn runnables(&self, source_root: Option<SourceRootId>) -> RunnablesConfig {
2681 RunnablesConfig {
2682 override_cargo: self.runnables_command(source_root).clone(),
2683 cargo_extra_args: self.runnables_extraArgs(source_root).clone(),
2684 config_path: self.cargo_config_path(source_root),
2685 extra_test_binary_args: self.runnables_extraTestBinaryArgs(source_root).clone(),
2686 test_command: self.runnables_test_command(source_root).clone(),
2687 test_override_command: self.runnables_test_overrideCommand(source_root).clone(),
2688 bench_command: self.runnables_bench_command(source_root).clone(),
2689 bench_override_command: self.runnables_bench_overrideCommand(source_root).clone(),
2690 doc_test_override_command: self.runnables_doctest_overrideCommand(source_root).clone(),
2691 }
2692 }
2693
2694 pub fn find_all_refs_exclude_imports(&self) -> bool {
2695 *self.references_excludeImports()
2696 }
2697
2698 pub fn find_all_refs_exclude_tests(&self) -> bool {
2699 *self.references_excludeTests()
2700 }
2701
2702 pub fn snippet_cap(&self) -> Option<SnippetCap> {
2703 SnippetCap::new(self.snippet_text_edit())
2706 }
2707
2708 pub fn call_info(&self) -> CallInfoConfig {
2709 CallInfoConfig {
2710 params_only: matches!(self.signatureInfo_detail(), SignatureDetail::Parameters),
2711 docs: *self.signatureInfo_documentation_enable(),
2712 }
2713 }
2714
2715 pub fn lens(&self) -> LensConfig {
2716 let enable = *self.lens_enable();
2717 LensConfig {
2718 run: enable && *self.lens_run_enable(),
2719 debug: enable && *self.lens_debug_enable(),
2720 update_test: enable && *self.lens_updateTest_enable() && *self.lens_run_enable(),
2721 interpret: enable && *self.lens_run_enable() && *self.interpret_tests(),
2722 implementations: enable && *self.lens_implementations_enable(),
2723 method_refs: enable && *self.lens_references_method_enable(),
2724 refs_adt: enable && *self.lens_references_adt_enable(),
2725 refs_trait: enable && *self.lens_references_trait_enable(),
2726 enum_variant_refs: enable && *self.lens_references_enumVariant_enable(),
2727 refs_exclude_imports: *self.references_excludeImports(),
2728 refs_exclude_tests: *self.references_excludeTests(),
2729 location: *self.lens_location(),
2730 filter_adjacent_derive_implementations: *self
2731 .gotoImplementations_filterAdjacentDerives(),
2732 disable_ra_fixture: *self.disableFixtureSupport(None),
2733 }
2734 }
2735
2736 pub fn goto_implementation(&self) -> GotoImplementationConfig {
2737 GotoImplementationConfig {
2738 filter_adjacent_derive_implementations: *self
2739 .gotoImplementations_filterAdjacentDerives(),
2740 }
2741 }
2742
2743 pub fn document_symbol(&self, source_root: Option<SourceRootId>) -> DocumentSymbolConfig {
2744 DocumentSymbolConfig {
2745 search_exclude_locals: *self.document_symbol_search_excludeLocals(source_root),
2746 }
2747 }
2748
2749 pub fn workspace_symbol(&self, source_root: Option<SourceRootId>) -> WorkspaceSymbolConfig {
2750 WorkspaceSymbolConfig {
2751 search_exclude_imports: *self.workspace_symbol_search_excludeImports(source_root),
2752 search_scope: match self.workspace_symbol_search_scope(source_root) {
2753 WorkspaceSymbolSearchScopeDef::Workspace => WorkspaceSymbolSearchScope::Workspace,
2754 WorkspaceSymbolSearchScopeDef::WorkspaceAndDependencies => {
2755 WorkspaceSymbolSearchScope::WorkspaceAndDependencies
2756 }
2757 },
2758 search_kind: match self.workspace_symbol_search_kind(source_root) {
2759 WorkspaceSymbolSearchKindDef::OnlyTypes => WorkspaceSymbolSearchKind::OnlyTypes,
2760 WorkspaceSymbolSearchKindDef::AllSymbols => WorkspaceSymbolSearchKind::AllSymbols,
2761 },
2762 search_limit: *self.workspace_symbol_search_limit(source_root),
2763 }
2764 }
2765
2766 pub fn client_commands(&self) -> ClientCommandsConfig {
2767 let commands = self.commands().map(|it| it.commands).unwrap_or_default();
2768
2769 let get = |name: &str| commands.iter().any(|it| it == name);
2770
2771 ClientCommandsConfig {
2772 run_single: get("rust-analyzer.runSingle"),
2773 debug_single: get("rust-analyzer.debugSingle"),
2774 show_reference: get("rust-analyzer.showReferences"),
2775 goto_location: get("rust-analyzer.gotoLocation"),
2776 trigger_parameter_hints: get("rust-analyzer.triggerParameterHints"),
2777 rename: get("rust-analyzer.rename"),
2778 }
2779 }
2780
2781 pub fn prime_caches_num_threads(&self) -> usize {
2782 match self.cachePriming_numThreads() {
2783 NumThreads::Concrete(0) | NumThreads::Physical => num_cpus::get_physical(),
2784 &NumThreads::Concrete(n) => n,
2785 NumThreads::Logical => num_cpus::get(),
2786 }
2787 }
2788
2789 pub fn proc_macro_num_processes(&self) -> usize {
2790 match self.procMacro_processes() {
2791 NumProcesses::Concrete(0) | NumProcesses::Physical => num_cpus::get_physical(),
2792 &NumProcesses::Concrete(n) => n,
2793 }
2794 }
2795
2796 pub fn main_loop_num_threads(&self) -> usize {
2797 match self.numThreads() {
2798 Some(NumThreads::Concrete(0)) | None | Some(NumThreads::Physical) => {
2799 num_cpus::get_physical()
2800 }
2801 &Some(NumThreads::Concrete(n)) => n,
2802 Some(NumThreads::Logical) => num_cpus::get(),
2803 }
2804 }
2805
2806 pub fn typing_trigger_chars(&self) -> &str {
2807 self.typing_triggerChars().as_deref().unwrap_or_default()
2808 }
2809
2810 pub fn visual_studio_code_version(&self) -> Option<&Version> {
2813 self.client_info
2814 .as_ref()
2815 .filter(|it| it.name.starts_with("Visual Studio Code"))
2816 .and_then(|it| it.version.as_ref())
2817 }
2818
2819 pub fn client_is_neovim(&self) -> bool {
2820 self.client_info.as_ref().map(|it| it.name == "Neovim").unwrap_or_default()
2821 }
2822}
2823macro_rules! create_bool_or_string_serde {
2826 ($ident:ident<$bool:literal, $string:literal>) => {
2827 mod $ident {
2828 pub(super) fn deserialize<'de, D>(d: D) -> Result<(), D::Error>
2829 where
2830 D: serde::Deserializer<'de>,
2831 {
2832 struct V;
2833 impl<'de> serde::de::Visitor<'de> for V {
2834 type Value = ();
2835
2836 fn expecting(
2837 &self,
2838 formatter: &mut std::fmt::Formatter<'_>,
2839 ) -> std::fmt::Result {
2840 formatter.write_str(concat!(
2841 stringify!($bool),
2842 " or \"",
2843 stringify!($string),
2844 "\""
2845 ))
2846 }
2847
2848 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
2849 where
2850 E: serde::de::Error,
2851 {
2852 match v {
2853 $bool => Ok(()),
2854 _ => Err(serde::de::Error::invalid_value(
2855 serde::de::Unexpected::Bool(v),
2856 &self,
2857 )),
2858 }
2859 }
2860
2861 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
2862 where
2863 E: serde::de::Error,
2864 {
2865 match v {
2866 $string => Ok(()),
2867 _ => Err(serde::de::Error::invalid_value(
2868 serde::de::Unexpected::Str(v),
2869 &self,
2870 )),
2871 }
2872 }
2873
2874 fn visit_enum<A>(self, a: A) -> Result<Self::Value, A::Error>
2875 where
2876 A: serde::de::EnumAccess<'de>,
2877 {
2878 use serde::de::VariantAccess;
2879 let (variant, va) = a.variant::<&'de str>()?;
2880 va.unit_variant()?;
2881 match variant {
2882 $string => Ok(()),
2883 _ => Err(serde::de::Error::invalid_value(
2884 serde::de::Unexpected::Str(variant),
2885 &self,
2886 )),
2887 }
2888 }
2889 }
2890 d.deserialize_any(V)
2891 }
2892
2893 pub(super) fn serialize<S>(serializer: S) -> Result<S::Ok, S::Error>
2894 where
2895 S: serde::Serializer,
2896 {
2897 serializer.serialize_str($string)
2898 }
2899 }
2900 };
2901}
2902create_bool_or_string_serde!(true_or_always<true, "always">);
2903create_bool_or_string_serde!(false_or_never<false, "never">);
2904
2905#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
2906#[serde(rename_all = "snake_case")]
2907#[derive(Default)]
2908enum SnippetScopeDef {
2909 #[default]
2910 Expr,
2911 Item,
2912 Type,
2913}
2914
2915#[derive(Serialize, Deserialize, Debug, Clone, Default)]
2916#[serde(default)]
2917#[serde(try_from = "SnippetDefRepr")]
2918pub(crate) struct SnippetDef {
2919 #[serde(with = "single_or_array")]
2920 #[serde(skip_serializing_if = "Vec::is_empty")]
2921 prefix: Vec<String>,
2922
2923 #[serde(with = "single_or_array")]
2924 #[serde(skip_serializing_if = "Vec::is_empty")]
2925 postfix: Vec<String>,
2926
2927 #[serde(with = "single_or_array")]
2928 #[serde(skip_serializing_if = "Vec::is_empty")]
2929 body: Vec<String>,
2930
2931 #[serde(with = "single_or_array")]
2932 #[serde(skip_serializing_if = "Vec::is_empty")]
2933 requires: Vec<String>,
2934
2935 #[serde(skip_serializing_if = "Option::is_none")]
2936 description: Option<String>,
2937
2938 scope: SnippetScopeDef,
2939}
2940
2941#[derive(Deserialize, Default)]
2946#[serde(default)]
2947struct SnippetDefRepr {
2948 #[serde(with = "single_or_array")]
2949 prefix: Vec<String>,
2950 #[serde(with = "single_or_array")]
2951 postfix: Vec<String>,
2952 #[serde(with = "single_or_array")]
2953 body: Vec<String>,
2954 #[serde(with = "single_or_array")]
2955 requires: Vec<String>,
2956 description: Option<String>,
2957 scope: SnippetScopeDef,
2958}
2959
2960impl TryFrom<SnippetDefRepr> for SnippetDef {
2961 type Error = String;
2962
2963 fn try_from(repr: SnippetDefRepr) -> Result<Self, Self::Error> {
2964 if repr.scope == SnippetScopeDef::Item && !repr.postfix.is_empty() {
2965 return Err(
2966 "'postfix' is not supported together with '\"scope\": \"item\"'; postfix snippets are not supported in item scope"
2967 .to_owned(),
2968 );
2969 }
2970 Ok(SnippetDef {
2971 prefix: repr.prefix,
2972 postfix: repr.postfix,
2973 body: repr.body,
2974 requires: repr.requires,
2975 description: repr.description,
2976 scope: repr.scope,
2977 })
2978 }
2979}
2980
2981mod single_or_array {
2982 use serde::{Deserialize, Serialize};
2983
2984 pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
2985 where
2986 D: serde::Deserializer<'de>,
2987 {
2988 struct SingleOrVec;
2989
2990 impl<'de> serde::de::Visitor<'de> for SingleOrVec {
2991 type Value = Vec<String>;
2992
2993 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2994 formatter.write_str("string or array of strings")
2995 }
2996
2997 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2998 where
2999 E: serde::de::Error,
3000 {
3001 Ok(vec![value.to_owned()])
3002 }
3003
3004 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
3005 where
3006 A: serde::de::SeqAccess<'de>,
3007 {
3008 Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
3009 }
3010 }
3011
3012 deserializer.deserialize_any(SingleOrVec)
3013 }
3014
3015 pub(super) fn serialize<S>(vec: &[String], serializer: S) -> Result<S::Ok, S::Error>
3016 where
3017 S: serde::Serializer,
3018 {
3019 match vec {
3020 [single] => serializer.serialize_str(single),
3022 slice => slice.serialize(serializer),
3023 }
3024 }
3025}
3026
3027#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3028#[serde(untagged)]
3029enum ManifestOrProjectJson {
3030 Manifest(Utf8PathBuf),
3031 ProjectJson(ProjectJsonData),
3032 DiscoveredProjectJson {
3033 data: ProjectJsonData,
3034 #[serde(serialize_with = "serialize_abs_pathbuf")]
3035 #[serde(deserialize_with = "deserialize_abs_pathbuf")]
3036 buildfile: AbsPathBuf,
3037 },
3038}
3039
3040fn deserialize_abs_pathbuf<'de, D>(de: D) -> std::result::Result<AbsPathBuf, D::Error>
3041where
3042 D: serde::de::Deserializer<'de>,
3043{
3044 let path = String::deserialize(de)?;
3045
3046 AbsPathBuf::try_from(path.as_ref())
3047 .map_err(|err| serde::de::Error::custom(format!("invalid path name: {err:?}")))
3048}
3049
3050fn serialize_abs_pathbuf<S>(path: &AbsPathBuf, se: S) -> Result<S::Ok, S::Error>
3051where
3052 S: serde::Serializer,
3053{
3054 let path: &Utf8Path = path.as_ref();
3055 se.serialize_str(path.as_str())
3056}
3057
3058#[derive(Serialize, Deserialize, Debug, Clone)]
3059#[serde(rename_all = "snake_case")]
3060enum ExprFillDefaultDef {
3061 Todo,
3062 Default,
3063 Underscore,
3064}
3065
3066#[derive(Serialize, Deserialize, Debug, Clone)]
3067#[serde(untagged)]
3068#[serde(rename_all = "snake_case")]
3069pub enum AutoImportExclusion {
3070 Path(String),
3071 Verbose { path: String, r#type: AutoImportExclusionType },
3072}
3073
3074#[derive(Serialize, Deserialize, Debug, Clone)]
3075#[serde(rename_all = "snake_case")]
3076pub enum AutoImportExclusionType {
3077 Always,
3078 Methods,
3079 SubItems,
3080 Variants,
3081}
3082
3083#[derive(Serialize, Deserialize, Debug, Clone)]
3084#[serde(rename_all = "snake_case")]
3085enum ImportGranularityDef {
3086 Preserve,
3087 Item,
3088 Crate,
3089 Module,
3090 One,
3091}
3092
3093#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
3094#[serde(rename_all = "snake_case")]
3095pub(crate) enum CallableCompletionDef {
3096 FillArguments,
3097 AddParentheses,
3098 None,
3099}
3100
3101#[derive(Serialize, Deserialize, Debug, Clone)]
3102#[serde(rename_all = "snake_case")]
3103enum CargoFeaturesDef {
3104 All,
3105 #[serde(untagged)]
3106 Selected(Vec<String>),
3107}
3108
3109#[derive(Serialize, Deserialize, Debug, Clone)]
3110#[serde(rename_all = "snake_case")]
3111pub(crate) enum InvocationStrategy {
3112 Once,
3113 PerWorkspace,
3114}
3115
3116#[derive(Serialize, Deserialize, Debug, Clone)]
3117struct CheckOnSaveTargets(#[serde(with = "single_or_array")] Vec<String>);
3118
3119#[derive(Serialize, Deserialize, Debug, Clone)]
3120#[serde(rename_all = "snake_case")]
3121enum LifetimeElisionDef {
3122 SkipTrivial,
3123 #[serde(with = "true_or_always")]
3124 #[serde(untagged)]
3125 Always,
3126 #[serde(with = "false_or_never")]
3127 #[serde(untagged)]
3128 Never,
3129}
3130
3131#[derive(Serialize, Deserialize, Debug, Clone)]
3132#[serde(rename_all = "snake_case")]
3133enum ImplicitDropDef {
3134 WithDropGlue,
3135 #[serde(with = "true_or_always")]
3136 #[serde(untagged)]
3137 Always,
3138 #[serde(with = "false_or_never")]
3139 #[serde(untagged)]
3140 Never,
3141}
3142
3143#[derive(Serialize, Deserialize, Debug, Clone)]
3144#[serde(rename_all = "snake_case")]
3145enum ClosureReturnTypeHintsDef {
3146 WithBlock,
3147 #[serde(with = "true_or_always")]
3148 #[serde(untagged)]
3149 Always,
3150 #[serde(with = "false_or_never")]
3151 #[serde(untagged)]
3152 Never,
3153}
3154
3155#[derive(Serialize, Deserialize, Debug, Clone)]
3156#[serde(rename_all = "snake_case")]
3157enum ClosureStyle {
3158 ImplFn,
3159 RustAnalyzer,
3160 WithId,
3161 Hide,
3162}
3163
3164#[derive(Serialize, Deserialize, Debug, Clone)]
3165#[serde(rename_all = "snake_case")]
3166enum TypeHintsLocation {
3167 Inline,
3168 EndOfLine,
3169}
3170
3171#[derive(Serialize, Deserialize, Debug, Clone)]
3172#[serde(rename_all = "snake_case")]
3173enum ReborrowHintsDef {
3174 Mutable,
3175 #[serde(with = "true_or_always")]
3176 #[serde(untagged)]
3177 Always,
3178 #[serde(with = "false_or_never")]
3179 #[serde(untagged)]
3180 Never,
3181}
3182
3183#[derive(Serialize, Deserialize, Debug, Clone)]
3184#[serde(rename_all = "snake_case")]
3185enum AdjustmentHintsDef {
3186 #[serde(alias = "reborrow")]
3187 Borrows,
3188 #[serde(with = "true_or_always")]
3189 #[serde(untagged)]
3190 Always,
3191 #[serde(with = "false_or_never")]
3192 #[serde(untagged)]
3193 Never,
3194}
3195
3196#[derive(Serialize, Deserialize, Debug, Clone)]
3197#[serde(rename_all = "snake_case")]
3198enum DiscriminantHintsDef {
3199 Fieldless,
3200 #[serde(with = "true_or_always")]
3201 #[serde(untagged)]
3202 Always,
3203 #[serde(with = "false_or_never")]
3204 #[serde(untagged)]
3205 Never,
3206}
3207
3208#[derive(Serialize, Deserialize, Debug, Clone)]
3209#[serde(rename_all = "snake_case")]
3210enum AdjustmentHintsModeDef {
3211 Prefix,
3212 Postfix,
3213 PreferPrefix,
3214 PreferPostfix,
3215}
3216
3217#[derive(Serialize, Deserialize, Debug, Clone)]
3218#[serde(rename_all = "snake_case")]
3219enum FilesWatcherDef {
3220 Client,
3221 Notify,
3222 Server,
3223}
3224
3225#[derive(Serialize, Deserialize, Debug, Clone)]
3226#[serde(rename_all = "snake_case")]
3227enum ImportPrefixDef {
3228 Plain,
3229 #[serde(rename = "self")]
3230 #[serde(alias = "by_self")]
3231 BySelf,
3232 #[serde(rename = "crate")]
3233 #[serde(alias = "by_crate")]
3234 ByCrate,
3235}
3236
3237#[derive(Serialize, Deserialize, Debug, Clone)]
3238#[serde(rename_all = "snake_case")]
3239enum WorkspaceSymbolSearchScopeDef {
3240 Workspace,
3241 WorkspaceAndDependencies,
3242}
3243
3244#[derive(Serialize, Deserialize, Debug, Clone)]
3245#[serde(rename_all = "snake_case")]
3246enum SignatureDetail {
3247 Full,
3248 Parameters,
3249}
3250
3251#[derive(Serialize, Deserialize, Debug, Clone)]
3252#[serde(rename_all = "snake_case")]
3253enum WorkspaceSymbolSearchKindDef {
3254 OnlyTypes,
3255 AllSymbols,
3256}
3257
3258#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq)]
3259#[serde(rename_all = "snake_case")]
3260enum MemoryLayoutHoverRenderKindDef {
3261 Decimal,
3262 Hexadecimal,
3263 Both,
3264}
3265
3266#[test]
3267fn untagged_option_hover_render_kind() {
3268 let hex = MemoryLayoutHoverRenderKindDef::Hexadecimal;
3269
3270 let ser = serde_json::to_string(&Some(hex)).unwrap();
3271 assert_eq!(&ser, "\"hexadecimal\"");
3272
3273 let opt: Option<_> = serde_json::from_str("\"hexadecimal\"").unwrap();
3274 assert_eq!(opt, Some(hex));
3275}
3276
3277#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3278#[serde(rename_all = "snake_case")]
3279#[serde(untagged)]
3280pub enum TargetDirectory {
3281 UseSubdirectory(bool),
3282 Directory(Utf8PathBuf),
3283}
3284
3285#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3286#[serde(rename_all = "snake_case")]
3287pub enum NumThreads {
3288 Physical,
3289 Logical,
3290 #[serde(untagged)]
3291 Concrete(usize),
3292}
3293
3294#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3295#[serde(rename_all = "snake_case")]
3296pub enum NumProcesses {
3297 Physical,
3298 #[serde(untagged)]
3299 Concrete(usize),
3300}
3301
3302macro_rules! _default_val {
3303 ($default:expr, $ty:ty) => {{
3304 let default_: $ty = $default;
3305 default_
3306 }};
3307}
3308use _default_val as default_val;
3309
3310macro_rules! _default_str {
3311 ($default:expr, $ty:ty) => {{
3312 let val = default_val!($default, $ty);
3313 serde_json::to_string_pretty(&val).unwrap()
3314 }};
3315}
3316use _default_str as default_str;
3317
3318macro_rules! _impl_for_config_data {
3319 (local, $(
3320 $(#[doc=$doc:literal])*
3321 $vis:vis $field:ident : $ty:ty = $default:expr,
3322 )*
3323 ) => {
3324 impl Config {
3325 $(
3326 $($doc)*
3327 #[allow(non_snake_case)]
3328 $vis fn $field(&self, source_root: Option<SourceRootId>) -> &$ty {
3329 let mut source_root = source_root.as_ref();
3330 while let Some(sr) = source_root {
3331 if let Some((file, _)) = self.ratoml_file.get(&sr) {
3332 match file {
3333 RatomlFile::Workspace(config) => {
3334 if let Some(v) = config.local.$field.as_ref() {
3335 return &v;
3336 }
3337 },
3338 RatomlFile::Crate(config) => {
3339 if let Some(value) = config.$field.as_ref() {
3340 return value;
3341 }
3342 }
3343 }
3344 }
3345 source_root = self.source_root_parent_map.get(&sr);
3346 }
3347
3348 if let Some(v) = self.client_config.0.local.$field.as_ref() {
3349 return &v;
3350 }
3351
3352 if let Some((user_config, _)) = self.user_config.as_ref() {
3353 if let Some(v) = user_config.local.$field.as_ref() {
3354 return &v;
3355 }
3356 }
3357
3358 &self.default_config.local.$field
3359 }
3360 )*
3361 }
3362 };
3363 (workspace, $(
3364 $(#[doc=$doc:literal])*
3365 $vis:vis $field:ident : $ty:ty = $default:expr,
3366 )*
3367 ) => {
3368 impl Config {
3369 $(
3370 $($doc)*
3371 #[allow(non_snake_case)]
3372 $vis fn $field(&self, source_root: Option<SourceRootId>) -> &$ty {
3373 let mut source_root = source_root.as_ref();
3374 while let Some(sr) = source_root {
3375 if let Some((RatomlFile::Workspace(config), _)) = self.ratoml_file.get(&sr) {
3376 if let Some(v) = config.workspace.$field.as_ref() {
3377 return &v;
3378 }
3379 }
3380 source_root = self.source_root_parent_map.get(&sr);
3381 }
3382
3383 if let Some(v) = self.client_config.0.workspace.$field.as_ref() {
3384 return &v;
3385 }
3386
3387 if let Some((user_config, _)) = self.user_config.as_ref() {
3388 if let Some(v) = user_config.workspace.$field.as_ref() {
3389 return &v;
3390 }
3391 }
3392
3393 &self.default_config.workspace.$field
3394 }
3395 )*
3396 }
3397 };
3398 (global, $(
3399 $(#[doc=$doc:literal])*
3400 $vis:vis $field:ident : $ty:ty = $default:expr,
3401 )*
3402 ) => {
3403 impl Config {
3404 $(
3405 $($doc)*
3406 #[allow(non_snake_case)]
3407 $vis fn $field(&self) -> &$ty {
3408 if let Some(v) = self.client_config.0.global.$field.as_ref() {
3409 return &v;
3410 }
3411
3412 if let Some((user_config, _)) = self.user_config.as_ref() {
3413 if let Some(v) = user_config.global.$field.as_ref() {
3414 return &v;
3415 }
3416 }
3417
3418
3419 &self.default_config.global.$field
3420 }
3421 )*
3422 }
3423 };
3424 (client, $(
3425 $(#[doc=$doc:literal])*
3426 $vis:vis $field:ident : $ty:ty = $default:expr,
3427 )*
3428 ) => {
3429 impl Config {
3430 $(
3431 $($doc)*
3432 #[allow(non_snake_case)]
3433 $vis fn $field(&self) -> &$ty {
3434 if let Some(v) = self.client_config.0.client.$field.as_ref() {
3435 return &v;
3436 }
3437
3438 &self.default_config.client.$field
3439 }
3440 )*
3441 }
3442 };
3443}
3444use _impl_for_config_data as impl_for_config_data;
3445
3446macro_rules! _config_data {
3447 ($(#[doc=$dox:literal])* $modname:ident: struct $name:ident <- $input:ident -> {
3449 $(
3450 $(#[doc=$doc:literal])*
3451 $vis:vis $field:ident $(| $alias:ident)*: $ty:ty = $default:expr,
3452 )*
3453 }) => {
3454 #[allow(non_snake_case)]
3456 #[derive(Debug, Clone)]
3457 struct $name { $($field: $ty,)* }
3458
3459 impl_for_config_data!{
3460 $modname,
3461 $(
3462 $vis $field : $ty = $default,
3463 )*
3464 }
3465
3466 #[allow(non_snake_case)]
3468 #[derive(Clone, Default)]
3469 struct $input { $(
3470 $field: Option<$ty>,
3471 )* }
3472
3473 impl std::fmt::Debug for $input {
3474 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3475 let mut s = f.debug_struct(stringify!($input));
3476 $(
3477 if let Some(val) = self.$field.as_ref() {
3478 s.field(stringify!($field), val);
3479 }
3480 )*
3481 s.finish()
3482 }
3483 }
3484
3485 impl Default for $name {
3486 fn default() -> Self {
3487 $name {$(
3488 $field: default_val!($default, $ty),
3489 )*}
3490 }
3491 }
3492
3493 #[allow(unused, clippy::ptr_arg)]
3494 impl $input {
3495 const FIELDS: &'static [&'static str] = &[$(stringify!($field)),*];
3496
3497 fn from_json(json: &mut serde_json::Value, error_sink: &mut Vec<(String, serde_json::Error)>) -> Self {
3498 Self {$(
3499 $field: get_field_json(
3500 json,
3501 error_sink,
3502 stringify!($field),
3503 None$(.or(Some(stringify!($alias))))*,
3504 ),
3505 )*}
3506 }
3507
3508 fn from_toml(toml: &toml::Table, error_sink: &mut Vec<(String, toml::de::Error)>) -> Self {
3509 Self {$(
3510 $field: get_field_toml::<$ty>(
3511 toml,
3512 error_sink,
3513 stringify!($field),
3514 None$(.or(Some(stringify!($alias))))*,
3515 ),
3516 )*}
3517 }
3518
3519 fn schema_fields(sink: &mut Vec<SchemaField>) {
3520 sink.extend_from_slice(&[
3521 $({
3522 let field = stringify!($field);
3523 let ty = stringify!($ty);
3524 let default = default_str!($default, $ty);
3525
3526 (field, ty, &[$($doc),*], default)
3527 },)*
3528 ])
3529 }
3530 }
3531
3532 mod $modname {
3533 #[test]
3534 fn fields_are_sorted() {
3535 super::$input::FIELDS.windows(2).for_each(|w| assert!(w[0] <= w[1], "{} <= {} does not hold", w[0], w[1]));
3536 }
3537 }
3538 };
3539}
3540use _config_data as config_data;
3541
3542#[derive(Default, Debug, Clone)]
3543struct DefaultConfigData {
3544 global: GlobalDefaultConfigData,
3545 workspace: WorkspaceDefaultConfigData,
3546 local: LocalDefaultConfigData,
3547 client: ClientDefaultConfigData,
3548}
3549
3550#[derive(Debug, Clone, Default)]
3554struct FullConfigInput {
3555 global: GlobalConfigInput,
3556 workspace: WorkspaceConfigInput,
3557 local: LocalConfigInput,
3558 client: ClientConfigInput,
3559}
3560
3561impl FullConfigInput {
3562 fn from_json(
3563 mut json: serde_json::Value,
3564 error_sink: &mut Vec<(String, serde_json::Error)>,
3565 ) -> FullConfigInput {
3566 FullConfigInput {
3567 global: GlobalConfigInput::from_json(&mut json, error_sink),
3568 local: LocalConfigInput::from_json(&mut json, error_sink),
3569 client: ClientConfigInput::from_json(&mut json, error_sink),
3570 workspace: WorkspaceConfigInput::from_json(&mut json, error_sink),
3571 }
3572 }
3573
3574 fn schema_fields() -> Vec<SchemaField> {
3575 let mut fields = Vec::new();
3576 GlobalConfigInput::schema_fields(&mut fields);
3577 LocalConfigInput::schema_fields(&mut fields);
3578 ClientConfigInput::schema_fields(&mut fields);
3579 WorkspaceConfigInput::schema_fields(&mut fields);
3580 fields.sort_by_key(|&(x, ..)| x);
3581 fields
3582 .iter()
3583 .array_windows()
3584 .for_each(|[a, b]| assert!(a.0 != b.0, "{a:?} duplicate field"));
3585 fields
3586 }
3587
3588 fn json_schema() -> serde_json::Value {
3589 schema(&Self::schema_fields())
3590 }
3591
3592 #[cfg(test)]
3593 fn manual() -> String {
3594 manual(&Self::schema_fields())
3595 }
3596}
3597
3598#[derive(Debug, Clone, Default)]
3602struct GlobalWorkspaceLocalConfigInput {
3603 global: GlobalConfigInput,
3604 local: LocalConfigInput,
3605 workspace: WorkspaceConfigInput,
3606}
3607
3608impl GlobalWorkspaceLocalConfigInput {
3609 const FIELDS: &'static [&'static [&'static str]] =
3610 &[GlobalConfigInput::FIELDS, LocalConfigInput::FIELDS];
3611 fn from_toml(
3612 toml: toml::Table,
3613 error_sink: &mut Vec<(String, toml::de::Error)>,
3614 ) -> GlobalWorkspaceLocalConfigInput {
3615 GlobalWorkspaceLocalConfigInput {
3616 global: GlobalConfigInput::from_toml(&toml, error_sink),
3617 local: LocalConfigInput::from_toml(&toml, error_sink),
3618 workspace: WorkspaceConfigInput::from_toml(&toml, error_sink),
3619 }
3620 }
3621}
3622
3623#[derive(Debug, Clone, Default)]
3627#[allow(dead_code)]
3628struct WorkspaceLocalConfigInput {
3629 workspace: WorkspaceConfigInput,
3630 local: LocalConfigInput,
3631}
3632
3633impl WorkspaceLocalConfigInput {
3634 #[allow(dead_code)]
3635 const FIELDS: &'static [&'static [&'static str]] =
3636 &[WorkspaceConfigInput::FIELDS, LocalConfigInput::FIELDS];
3637 fn from_toml(toml: toml::Table, error_sink: &mut Vec<(String, toml::de::Error)>) -> Self {
3638 Self {
3639 workspace: WorkspaceConfigInput::from_toml(&toml, error_sink),
3640 local: LocalConfigInput::from_toml(&toml, error_sink),
3641 }
3642 }
3643}
3644
3645fn get_field_json<T: DeserializeOwned>(
3646 json: &mut serde_json::Value,
3647 error_sink: &mut Vec<(String, serde_json::Error)>,
3648 field: &'static str,
3649 alias: Option<&'static str>,
3650) -> Option<T> {
3651 alias
3654 .into_iter()
3655 .chain(iter::once(field))
3656 .filter_map(move |field| {
3657 let mut pointer = field.replace('_', "/");
3658 pointer.insert(0, '/');
3659 json.pointer_mut(&pointer)
3660 .map(|it| serde_json::from_value(it.take()).map_err(|e| (e, pointer)))
3661 })
3662 .flat_map(|res| match res {
3663 Ok(it) => Some(it),
3664 Err((e, pointer)) => {
3665 tracing::warn!("Failed to deserialize config field at {}: {:?}", pointer, e);
3666 error_sink.push((pointer, e));
3667 None
3668 }
3669 })
3670 .next()
3671}
3672
3673fn get_field_toml<T: DeserializeOwned>(
3674 toml: &toml::Table,
3675 error_sink: &mut Vec<(String, toml::de::Error)>,
3676 field: &'static str,
3677 alias: Option<&'static str>,
3678) -> Option<T> {
3679 alias
3682 .into_iter()
3683 .chain(iter::once(field))
3684 .filter_map(move |field| {
3685 let mut pointer = field.replace('_', "/");
3686 pointer.insert(0, '/');
3687 toml_pointer(toml, &pointer)
3688 .map(|it| <_>::deserialize(it.clone()).map_err(|e| (e, pointer)))
3689 })
3690 .find(Result::is_ok)
3691 .and_then(|res| match res {
3692 Ok(it) => Some(it),
3693 Err((e, pointer)) => {
3694 tracing::warn!("Failed to deserialize config field at {}: {:?}", pointer, e);
3695 error_sink.push((pointer, e));
3696 None
3697 }
3698 })
3699}
3700
3701fn toml_pointer<'a>(toml: &'a toml::Table, pointer: &str) -> Option<&'a toml::Value> {
3702 fn parse_index(s: &str) -> Option<usize> {
3703 if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
3704 return None;
3705 }
3706 s.parse().ok()
3707 }
3708
3709 if pointer.is_empty() {
3710 return None;
3711 }
3712 if !pointer.starts_with('/') {
3713 return None;
3714 }
3715 let mut parts = pointer.split('/').skip(1);
3716 let first = parts.next()?;
3717 let init = toml.get(first)?;
3718 parts.map(|x| x.replace("~1", "/").replace("~0", "~")).try_fold(init, |target, token| {
3719 match target {
3720 toml::Value::Table(table) => table.get(&token),
3721 toml::Value::Array(list) => parse_index(&token).and_then(move |x| list.get(x)),
3722 _ => None,
3723 }
3724 })
3725}
3726
3727type SchemaField = (&'static str, &'static str, &'static [&'static str], String);
3728
3729fn schema(fields: &[SchemaField]) -> serde_json::Value {
3730 let map = fields
3731 .iter()
3732 .map(|(field, ty, doc, default)| {
3733 let name = field.replace('_', ".");
3734 let category = name
3735 .split_once(".")
3736 .map(|(category, _name)| to_title_case(category))
3737 .unwrap_or("rust-analyzer".into());
3738 let name = format!("rust-analyzer.{name}");
3739 let props = field_props(field, ty, doc, default);
3740 serde_json::json!({
3741 "title": category,
3742 "properties": {
3743 name: props
3744 }
3745 })
3746 })
3747 .collect::<Vec<_>>();
3748 map.into()
3749}
3750
3751fn to_title_case(s: &str) -> String {
3760 let mut result = String::with_capacity(s.len());
3761 let mut chars = s.chars();
3762 if let Some(first) = chars.next() {
3763 result.push(first.to_ascii_uppercase());
3764 for c in chars {
3765 if c.is_uppercase() {
3766 result.push(' ');
3767 }
3768 result.push(c);
3769 }
3770 }
3771 result
3772}
3773
3774fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
3775 let doc = doc_comment_to_string(doc);
3776 let doc = doc.trim_end_matches('\n');
3777 assert!(
3778 doc.ends_with('.') && doc.starts_with(char::is_uppercase),
3779 "bad docs for {field}: {doc:?}"
3780 );
3781 let default = default.parse::<serde_json::Value>().unwrap();
3782
3783 let mut map = serde_json::Map::default();
3784 macro_rules! set {
3785 ($($key:literal: $value:tt),*$(,)?) => {{$(
3786 map.insert($key.into(), serde_json::json!($value));
3787 )*}};
3788 }
3789 set!("markdownDescription": doc);
3790 set!("default": default);
3791
3792 match ty {
3793 "bool" => set!("type": "boolean"),
3794 "usize" => set!("type": "integer", "minimum": 0),
3795 "String" => set!("type": "string"),
3796 "Vec<String>" => set! {
3797 "type": "array",
3798 "items": { "type": "string" },
3799 },
3800 "Vec<Utf8PathBuf>" => set! {
3801 "type": "array",
3802 "items": { "type": "string" },
3803 },
3804 "FxHashSet<String>" => set! {
3805 "type": "array",
3806 "items": { "type": "string" },
3807 "uniqueItems": true,
3808 },
3809 "FxHashMap<Box<str>, Box<[Box<str>]>>" => set! {
3810 "type": "object",
3811 },
3812 "FxIndexMap<String, SnippetDef>" => set! {
3813 "type": "object",
3814 },
3815 "FxHashMap<String, String>" => set! {
3816 "type": "object",
3817 },
3818 "FxHashMap<Box<str>, u16>" => set! {
3819 "type": "object",
3820 },
3821 "FxHashMap<String, Option<String>>" => set! {
3822 "type": "object",
3823 },
3824 "Option<usize>" => set! {
3825 "type": ["null", "integer"],
3826 "minimum": 0,
3827 },
3828 "Option<u16>" => set! {
3829 "type": ["null", "integer"],
3830 "minimum": 0,
3831 "maximum": 65535,
3832 },
3833 "Option<String>" => set! {
3834 "type": ["null", "string"],
3835 },
3836 "Option<Utf8PathBuf>" => set! {
3837 "type": ["null", "string"],
3838 },
3839 "Option<bool>" => set! {
3840 "type": ["null", "boolean"],
3841 },
3842 "Option<Vec<String>>" => set! {
3843 "type": ["null", "array"],
3844 "items": { "type": "string" },
3845 },
3846 "ExprFillDefaultDef" => set! {
3847 "type": "string",
3848 "enum": ["todo", "default"],
3849 "enumDescriptions": [
3850 "Fill missing expressions with the `todo` macro",
3851 "Fill missing expressions with reasonable defaults, `new` or `default` constructors."
3852 ],
3853 },
3854 "ImportGranularityDef" => set! {
3855 "type": "string",
3856 "enum": ["crate", "module", "item", "one", "preserve"],
3857 "enumDescriptions": [
3858 "Merge imports from the same crate into a single use statement. Conversely, imports from different crates are split into separate statements.",
3859 "Merge imports from the same module into a single use statement. Conversely, imports from different modules are split into separate statements.",
3860 "Flatten imports so that each has its own use statement.",
3861 "Merge all imports into a single use statement as long as they have the same visibility and attributes.",
3862 "Deprecated - unless `enforceGranularity` is `true`, the style of the current file is preferred over this setting. Behaves like `item`."
3863 ],
3864 },
3865 "ImportPrefixDef" => set! {
3866 "type": "string",
3867 "enum": [
3868 "plain",
3869 "self",
3870 "crate"
3871 ],
3872 "enumDescriptions": [
3873 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
3874 "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.",
3875 "Force import paths to be absolute by always starting them with `crate` or the extern crate name they come from."
3876 ],
3877 },
3878 "Vec<ManifestOrProjectJson>" => set! {
3879 "type": "array",
3880 "items": { "type": ["string", "object"] },
3881 },
3882 "WorkspaceSymbolSearchScopeDef" => set! {
3883 "type": "string",
3884 "enum": ["workspace", "workspace_and_dependencies"],
3885 "enumDescriptions": [
3886 "Search in current workspace only.",
3887 "Search in current workspace and dependencies."
3888 ],
3889 },
3890 "WorkspaceSymbolSearchKindDef" => set! {
3891 "type": "string",
3892 "enum": ["only_types", "all_symbols"],
3893 "enumDescriptions": [
3894 "Search for types only.",
3895 "Search for all symbols kinds."
3896 ],
3897 },
3898 "LifetimeElisionDef" => set! {
3899 "type": "string",
3900 "enum": [
3901 "always",
3902 "never",
3903 "skip_trivial"
3904 ],
3905 "enumDescriptions": [
3906 "Always show lifetime elision hints.",
3907 "Never show lifetime elision hints.",
3908 "Only show lifetime elision hints if a return type is involved."
3909 ]
3910 },
3911 "ImplicitDropDef" => set! {
3912 "type":"string",
3913 "enum": [
3914 "always",
3915 "never",
3916 "with_drop_glue"
3917 ],
3918 "enumDescriptions": [
3919 "Always show drop hints.",
3920 "Never show drop hints.",
3921 "Only show drop hints for values with drop glue."
3922 ]
3923 },
3924 "ClosureReturnTypeHintsDef" => set! {
3925 "type": "string",
3926 "enum": [
3927 "always",
3928 "never",
3929 "with_block"
3930 ],
3931 "enumDescriptions": [
3932 "Always show type hints for return types of closures.",
3933 "Never show type hints for return types of closures.",
3934 "Only show type hints for return types of closures with blocks."
3935 ]
3936 },
3937 "ReborrowHintsDef" => set! {
3938 "type": "string",
3939 "enum": [
3940 "always",
3941 "never",
3942 "mutable"
3943 ],
3944 "enumDescriptions": [
3945 "Always show reborrow hints.",
3946 "Never show reborrow hints.",
3947 "Only show mutable reborrow hints."
3948 ]
3949 },
3950 "AdjustmentHintsDef" => set! {
3951 "type": "string",
3952 "enum": [
3953 "always",
3954 "never",
3955 "reborrow"
3956 ],
3957 "enumDescriptions": [
3958 "Always show all adjustment hints.",
3959 "Never show adjustment hints.",
3960 "Only show auto borrow and dereference adjustment hints."
3961 ]
3962 },
3963 "DiscriminantHintsDef" => set! {
3964 "type": "string",
3965 "enum": [
3966 "always",
3967 "never",
3968 "fieldless"
3969 ],
3970 "enumDescriptions": [
3971 "Always show all discriminant hints.",
3972 "Never show discriminant hints.",
3973 "Only show discriminant hints on fieldless enum variants."
3974 ]
3975 },
3976 "AdjustmentHintsModeDef" => set! {
3977 "type": "string",
3978 "enum": [
3979 "prefix",
3980 "postfix",
3981 "prefer_prefix",
3982 "prefer_postfix",
3983 ],
3984 "enumDescriptions": [
3985 "Always show adjustment hints as prefix (`*expr`).",
3986 "Always show adjustment hints as postfix (`expr.*`).",
3987 "Show prefix or postfix depending on which uses less parenthesis, preferring prefix.",
3988 "Show prefix or postfix depending on which uses less parenthesis, preferring postfix.",
3989 ]
3990 },
3991 "CargoFeaturesDef" => set! {
3992 "anyOf": [
3993 {
3994 "type": "string",
3995 "enum": [
3996 "all"
3997 ],
3998 "enumDescriptions": [
3999 "Pass `--all-features` to cargo",
4000 ]
4001 },
4002 {
4003 "type": "array",
4004 "items": { "type": "string" }
4005 }
4006 ],
4007 },
4008 "Option<CargoFeaturesDef>" => set! {
4009 "anyOf": [
4010 {
4011 "type": "string",
4012 "enum": [
4013 "all"
4014 ],
4015 "enumDescriptions": [
4016 "Pass `--all-features` to cargo",
4017 ]
4018 },
4019 {
4020 "type": "array",
4021 "items": { "type": "string" }
4022 },
4023 { "type": "null" }
4024 ],
4025 },
4026 "CallableCompletionDef" => set! {
4027 "type": "string",
4028 "enum": [
4029 "fill_arguments",
4030 "add_parentheses",
4031 "none",
4032 ],
4033 "enumDescriptions": [
4034 "Add call parentheses and pre-fill arguments.",
4035 "Add call parentheses.",
4036 "Do no snippet completions for callables."
4037 ]
4038 },
4039 "SignatureDetail" => set! {
4040 "type": "string",
4041 "enum": ["full", "parameters"],
4042 "enumDescriptions": [
4043 "Show the entire signature.",
4044 "Show only the parameters."
4045 ],
4046 },
4047 "FilesWatcherDef" => set! {
4048 "type": "string",
4049 "enum": ["client", "server"],
4050 "enumDescriptions": [
4051 "Use the client (editor) to watch files for changes",
4052 "Use server-side file watching",
4053 ],
4054 },
4055 "AnnotationLocation" => set! {
4056 "type": "string",
4057 "enum": ["above_name", "above_whole_item"],
4058 "enumDescriptions": [
4059 "Render annotations above the name of the item.",
4060 "Render annotations above the whole item, including documentation comments and attributes."
4061 ],
4062 },
4063 "InvocationStrategy" => set! {
4064 "type": "string",
4065 "enum": ["per_workspace", "once"],
4066 "enumDescriptions": [
4067 "The command will be executed for each Rust workspace with the workspace as the working directory.",
4068 "The command will be executed once with the opened project as the working directory.\
4069 \n\n**Warning:** This can cause errors when the Cargo configuration of the opened workspaces is different \
4070 or even only different than the default. Enabling this is not recommended."
4071 ],
4072 },
4073 "Option<CheckOnSaveTargets>" => set! {
4074 "anyOf": [
4075 {
4076 "type": "null"
4077 },
4078 {
4079 "type": "string",
4080 },
4081 {
4082 "type": "array",
4083 "items": { "type": "string" }
4084 },
4085 ],
4086 },
4087 "ClosureStyle" => set! {
4088 "type": "string",
4089 "enum": ["impl_fn", "rust_analyzer", "with_id", "hide"],
4090 "enumDescriptions": [
4091 "`impl_fn`: `impl FnMut(i32, u64) -> i8`",
4092 "`rust_analyzer`: `|i32, u64| -> i8`",
4093 "`with_id`: `{closure#14352}`, where that id is the unique number of the closure in r-a internals",
4094 "`hide`: Shows `...` for every closure type",
4095 ],
4096 },
4097 "TypeHintsLocation" => set! {
4098 "type": "string",
4099 "enum": ["inline", "end_of_line"],
4100 "enumDescriptions": [
4101 "Render type hints directly after the binding identifier.",
4102 "Render type hints after the end of the containing `let` statement when possible.",
4103 ],
4104 },
4105 "Option<MemoryLayoutHoverRenderKindDef>" => set! {
4106 "anyOf": [
4107 {
4108 "type": "null"
4109 },
4110 {
4111 "type": "string",
4112 "enum": ["both", "decimal", "hexadecimal", ],
4113 "enumDescriptions": [
4114 "Render as 12 (0xC)",
4115 "Render as 12",
4116 "Render as 0xC"
4117 ],
4118 },
4119 ],
4120 },
4121 "Option<TargetDirectory>" => set! {
4122 "anyOf": [
4123 {
4124 "type": "null"
4125 },
4126 {
4127 "type": "boolean"
4128 },
4129 {
4130 "type": "string"
4131 },
4132 ],
4133 },
4134 "NumThreads" => set! {
4135 "anyOf": [
4136 {
4137 "type": "number",
4138 "minimum": 0,
4139 "maximum": 255
4140 },
4141 {
4142 "type": "string",
4143 "enum": ["physical", "logical", ],
4144 "enumDescriptions": [
4145 "Use the number of physical cores",
4146 "Use the number of logical cores",
4147 ],
4148 },
4149 ],
4150 },
4151 "NumProcesses" => set! {
4152 "anyOf": [
4153 {
4154 "type": "number",
4155 "minimum": 0,
4156 "maximum": 255
4157 },
4158 {
4159 "type": "string",
4160 "enum": ["physical"],
4161 "enumDescriptions": [
4162 "Use the number of physical cores",
4163 ],
4164 },
4165 ],
4166 },
4167 "Option<NumThreads>" => set! {
4168 "anyOf": [
4169 {
4170 "type": "null"
4171 },
4172 {
4173 "type": "number",
4174 "minimum": 0,
4175 "maximum": 255
4176 },
4177 {
4178 "type": "string",
4179 "enum": ["physical", "logical", ],
4180 "enumDescriptions": [
4181 "Use the number of physical cores",
4182 "Use the number of logical cores",
4183 ],
4184 },
4185 ],
4186 },
4187 "Option<DiscoverWorkspaceConfig>" => set! {
4188 "anyOf": [
4189 {
4190 "type": "null"
4191 },
4192 {
4193 "type": "object",
4194 "properties": {
4195 "command": {
4196 "type": "array",
4197 "items": { "type": "string" }
4198 },
4199 "progressLabel": {
4200 "type": "string"
4201 },
4202 "filesToWatch": {
4203 "type": "array",
4204 "items": { "type": "string" }
4205 },
4206 }
4207 }
4208 ]
4209 },
4210 "Option<MaxSubstitutionLength>" => set! {
4211 "anyOf": [
4212 {
4213 "type": "null"
4214 },
4215 {
4216 "type": "string",
4217 "enum": ["hide"]
4218 },
4219 {
4220 "type": "integer"
4221 }
4222 ]
4223 },
4224 "Vec<AutoImportExclusion>" => set! {
4225 "type": "array",
4226 "items": {
4227 "anyOf": [
4228 {
4229 "type": "string",
4230 },
4231 {
4232 "type": "object",
4233 "properties": {
4234 "path": {
4235 "type": "string",
4236 },
4237 "type": {
4238 "type": "string",
4239 "enum": ["always", "methods", "sub_items", "variants"],
4240 "enumDescriptions": [
4241 "Do not show this item or its methods (if it is a trait) in auto-import completions.",
4242 "Do not show this trait's methods in auto-import completions.",
4243 "Do not show this module's all items in it in auto-import completions.",
4244 "Do not show this enum's variants in auto-import completions."
4245 ],
4246 },
4247 }
4248 }
4249 ]
4250 }
4251 },
4252 _ => panic!("missing entry for {ty}: {default} (field {field})"),
4253 }
4254
4255 map.into()
4256}
4257
4258fn validate_toml_table(
4259 known_ptrs: &[&[&'static str]],
4260 toml: &toml::Table,
4261 ptr: &mut String,
4262 error_sink: &mut Vec<(String, toml::de::Error)>,
4263) {
4264 let verify = |ptr: &String| known_ptrs.iter().any(|ptrs| ptrs.contains(&ptr.as_str()));
4265
4266 let l = ptr.len();
4267 for (k, v) in toml {
4268 if !ptr.is_empty() {
4269 ptr.push('_');
4270 }
4271 ptr.push_str(k);
4272
4273 match v {
4274 toml::Value::Table(_) if verify(ptr) => (),
4276 toml::Value::Table(table) => validate_toml_table(known_ptrs, table, ptr, error_sink),
4277 _ if !verify(ptr) => error_sink
4278 .push((ptr.replace('_', "/"), toml::de::Error::custom("unexpected field"))),
4279 _ => (),
4280 }
4281
4282 ptr.truncate(l);
4283 }
4284}
4285
4286#[cfg(test)]
4287fn manual(fields: &[SchemaField]) -> String {
4288 fields.iter().fold(String::new(), |mut acc, (field, _ty, doc, default)| {
4289 let id = field.replace('_', ".");
4290 let name = format!("rust-analyzer.{id}");
4291 let doc = doc_comment_to_string(doc);
4292 if default.contains('\n') {
4293 format_to_acc!(
4294 acc,
4295 "## {name} {{#{id}}}\n\nDefault:\n```json\n{default}\n```\n\n{doc}\n\n"
4296 )
4297 } else {
4298 format_to_acc!(acc, "## {name} {{#{id}}}\n\nDefault: `{default}`\n\n{doc}\n\n")
4299 }
4300 })
4301}
4302
4303fn doc_comment_to_string(doc: &[&str]) -> String {
4304 doc.iter()
4305 .map(|it| it.strip_prefix(' ').unwrap_or(it))
4306 .fold(String::new(), |mut acc, it| format_to_acc!(acc, "{it}\n"))
4307}
4308
4309#[cfg(test)]
4310mod tests {
4311 use std::{borrow::Cow, fs};
4312
4313 use test_utils::{ensure_file_contents, project_root};
4314
4315 use super::*;
4316
4317 #[test]
4318 fn generate_package_json_config() {
4319 let s = Config::json_schema();
4320
4321 let schema = format!("{s:#}");
4322 let mut schema = schema
4323 .trim_start_matches('[')
4324 .trim_end_matches(']')
4325 .replace(" ", " ")
4326 .replace('\n', "\n ")
4327 .trim_start_matches('\n')
4328 .trim_end()
4329 .to_owned();
4330 schema.push_str(",\n");
4331
4332 let url_matches = schema.match_indices("https://");
4336 let mut url_offsets = url_matches.map(|(idx, _)| idx).collect::<Vec<usize>>();
4337 url_offsets.reverse();
4338 for idx in url_offsets {
4339 let link = &schema[idx..];
4340 if let Some(link_end) = link.find([' ', '['])
4342 && link.chars().nth(link_end) == Some('[')
4343 && let Some(link_text_end) = link.find(']')
4344 {
4345 let link_text = link[link_end..(link_text_end + 1)].to_string();
4346
4347 schema.replace_range((idx + link_end)..(idx + link_text_end + 1), "");
4348 schema.insert(idx, '(');
4349 schema.insert(idx + link_end + 1, ')');
4350 schema.insert_str(idx, &link_text);
4351 }
4352 }
4353
4354 let package_json_path = project_root().join("editors/code/package.json");
4355 let mut package_json = fs::read_to_string(&package_json_path).unwrap();
4356
4357 let start_marker =
4358 " {\n \"title\": \"$generated-start\"\n },\n";
4359 let end_marker =
4360 " {\n \"title\": \"$generated-end\"\n }\n";
4361
4362 let start = package_json.find(start_marker).unwrap() + start_marker.len();
4363 let end = package_json.find(end_marker).unwrap();
4364
4365 let p = remove_ws(&package_json[start..end]);
4366 let s = remove_ws(&schema);
4367 if !p.contains(&s) {
4368 package_json.replace_range(start..end, &schema);
4369 ensure_file_contents(package_json_path.as_std_path(), &package_json)
4370 }
4371 }
4372
4373 #[test]
4374 fn generate_config_documentation() {
4375 let docs_path = project_root().join("docs/book/src/configuration_generated.md");
4376 let expected = FullConfigInput::manual();
4377 ensure_file_contents(docs_path.as_std_path(), &expected);
4378 }
4379
4380 fn remove_ws(text: &str) -> String {
4381 text.replace(char::is_whitespace, "")
4382 }
4383
4384 #[test]
4385 fn proc_macro_srv_null() {
4386 let mut config =
4387 Config::new(AbsPathBuf::assert(project_root()), Default::default(), vec![], None);
4388
4389 let mut change = ConfigChange::default();
4390 change.change_client_config(serde_json::json!({
4391 "procMacro" : {
4392 "server": null,
4393 }}));
4394
4395 (config, _, _) = config.apply_change(change);
4396 assert_eq!(config.proc_macro_srv(), None);
4397 }
4398
4399 #[test]
4400 fn proc_macro_srv_abs() {
4401 let mut config =
4402 Config::new(AbsPathBuf::assert(project_root()), Default::default(), vec![], None);
4403 let mut change = ConfigChange::default();
4404 change.change_client_config(serde_json::json!({
4405 "procMacro" : {
4406 "server": project_root().to_string(),
4407 }}));
4408
4409 (config, _, _) = config.apply_change(change);
4410 assert_eq!(config.proc_macro_srv(), Some(AbsPathBuf::assert(project_root())));
4411 }
4412
4413 #[test]
4414 fn proc_macro_srv_rel() {
4415 let mut config =
4416 Config::new(AbsPathBuf::assert(project_root()), Default::default(), vec![], None);
4417
4418 let mut change = ConfigChange::default();
4419
4420 change.change_client_config(serde_json::json!({
4421 "procMacro" : {
4422 "server": "./server"
4423 }}));
4424
4425 (config, _, _) = config.apply_change(change);
4426
4427 assert_eq!(
4428 config.proc_macro_srv(),
4429 Some(AbsPathBuf::try_from(project_root().join("./server")).unwrap())
4430 );
4431 }
4432
4433 #[test]
4434 fn cargo_target_dir_unset() {
4435 let mut config =
4436 Config::new(AbsPathBuf::assert(project_root()), Default::default(), vec![], None);
4437
4438 let mut change = ConfigChange::default();
4439
4440 change.change_client_config(serde_json::json!({
4441 "rust" : { "analyzerTargetDir" : null }
4442 }));
4443
4444 (config, _, _) = config.apply_change(change);
4445 assert_eq!(config.cargo_targetDir(None), &None);
4446 assert!(matches!(
4447 config.flycheck(None),
4448 FlycheckConfig::Automatic {
4449 cargo_options: CargoOptions { target_dir_config: TargetDirectoryConfig::None, .. },
4450 ..
4451 }
4452 ));
4453 }
4454
4455 #[test]
4456 fn cargo_target_dir_subdir() {
4457 let mut config =
4458 Config::new(AbsPathBuf::assert(project_root()), Default::default(), vec![], None);
4459
4460 let mut change = ConfigChange::default();
4461 change.change_client_config(serde_json::json!({
4462 "rust" : { "analyzerTargetDir" : true }
4463 }));
4464
4465 (config, _, _) = config.apply_change(change);
4466
4467 assert_eq!(config.cargo_targetDir(None), &Some(TargetDirectory::UseSubdirectory(true)));
4468 let ws_target_dir =
4469 Utf8PathBuf::from(std::env::var("CARGO_TARGET_DIR").unwrap_or("target".to_owned()));
4470 assert!(matches!(
4471 config.flycheck(None),
4472 FlycheckConfig::Automatic {
4473 cargo_options: CargoOptions { target_dir_config, .. },
4474 ..
4475 } if target_dir_config.target_dir(Some(&ws_target_dir)).map(Cow::into_owned)
4476 == Some(ws_target_dir.join("rust-analyzer"))
4477 ));
4478 }
4479
4480 #[test]
4481 fn cargo_target_dir_relative_dir() {
4482 let mut config =
4483 Config::new(AbsPathBuf::assert(project_root()), Default::default(), vec![], None);
4484
4485 let mut change = ConfigChange::default();
4486 change.change_client_config(serde_json::json!({
4487 "rust" : { "analyzerTargetDir" : "other_folder" }
4488 }));
4489
4490 (config, _, _) = config.apply_change(change);
4491
4492 assert_eq!(
4493 config.cargo_targetDir(None),
4494 &Some(TargetDirectory::Directory(Utf8PathBuf::from("other_folder")))
4495 );
4496 assert!(matches!(
4497 config.flycheck(None),
4498 FlycheckConfig::Automatic {
4499 cargo_options: CargoOptions { target_dir_config, .. },
4500 ..
4501 } if target_dir_config.target_dir(None).map(Cow::into_owned)
4502 == Some(Utf8PathBuf::from("other_folder"))
4503 ));
4504 }
4505 #[test]
4506 fn postfix_snippet_item_scope_is_invalid() {
4507 let mut config =
4508 Config::new(AbsPathBuf::assert(project_root()), Default::default(), vec![], None);
4509 let mut change = ConfigChange::default();
4510 change.change_client_config(serde_json::json!({
4511 "completion":{
4512 "snippets": {
4513 "custom":{
4514 "foo": {
4515 "postfix": "foo",
4516 "body": "foo",
4517 "scope": "item"
4518 }
4519 }
4520 }
4521 }
4522 }));
4523 let errors;
4524 (config, errors, _) = config.apply_change(change);
4525 assert!(!errors.0.is_empty(), "expected a config error for postfix+item scope");
4526 assert!(
4527 config.snippets.iter().all(|s| s.postfix_triggers.iter().all(|t| &**t != "foo")),
4528 "invalid snippet should not have been registered"
4529 );
4530 }
4531}