]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/config.rs
Merge #7409 #7421
[rust.git] / crates / rust-analyzer / src / config.rs
1 //! Config used by the language server.
2 //!
3 //! We currently get this config from `initialize` LSP request, which is not the
4 //! best way to do it, but was the simplest thing we could implement.
5 //!
6 //! Of particular interest is the `feature_flags` hash map: while other fields
7 //! configure the server itself, feature flags are passed into analysis, and
8 //! tweak things like automatic insertion of `()` in completions.
9
10 use std::{convert::TryFrom, ffi::OsString, iter, path::PathBuf};
11
12 use flycheck::FlycheckConfig;
13 use hir::PrefixKind;
14 use ide::{AssistConfig, CompletionConfig, DiagnosticsConfig, HoverConfig, InlayHintsConfig};
15 use ide_db::helpers::{
16     insert_use::{InsertUseConfig, MergeBehavior},
17     SnippetCap,
18 };
19 use itertools::Itertools;
20 use lsp_types::{ClientCapabilities, MarkupKind};
21 use project_model::{CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest};
22 use rustc_hash::FxHashSet;
23 use serde::{de::DeserializeOwned, Deserialize};
24 use vfs::AbsPathBuf;
25
26 use crate::{caps::completion_item_edit_resolve, diagnostics::DiagnosticsMapConfig};
27
28 config_data! {
29     struct ConfigData {
30         /// The strategy to use when inserting new imports or merging imports.
31         assist_importMergeBehavior |
32         assist_importMergeBehaviour: MergeBehaviorDef  = "\"full\"",
33         /// The path structure for newly inserted paths to use.
34         assist_importPrefix: ImportPrefixDef           = "\"plain\"",
35
36         /// Show function name and docs in parameter hints.
37         callInfo_full: bool = "true",
38
39         /// Automatically refresh project info via `cargo metadata` on
40         /// `Cargo.toml` changes.
41         cargo_autoreload: bool           = "true",
42         /// Activate all available features.
43         cargo_allFeatures: bool          = "false",
44         /// List of features to activate.
45         cargo_features: Vec<String>      = "[]",
46         /// Run `cargo check` on startup to get the correct value for package
47         /// OUT_DIRs.
48         cargo_loadOutDirsFromCheck: bool = "false",
49         /// Do not activate the `default` feature.
50         cargo_noDefaultFeatures: bool    = "false",
51         /// Compilation target (target triple).
52         cargo_target: Option<String>     = "null",
53         /// Internal config for debugging, disables loading of sysroot crates.
54         cargo_noSysroot: bool            = "false",
55
56         /// Run specified `cargo check` command for diagnostics on save.
57         checkOnSave_enable: bool                         = "true",
58         /// Check with all features (will be passed as `--all-features`).
59         /// Defaults to `#rust-analyzer.cargo.allFeatures#`.
60         checkOnSave_allFeatures: Option<bool>            = "null",
61         /// Check all targets and tests (will be passed as `--all-targets`).
62         checkOnSave_allTargets: bool                     = "true",
63         /// Cargo command to use for `cargo check`.
64         checkOnSave_command: String                      = "\"check\"",
65         /// Do not activate the `default` feature.
66         checkOnSave_noDefaultFeatures: Option<bool>      = "null",
67         /// Check for a specific target. Defaults to
68         /// `#rust-analyzer.cargo.target#`.
69         checkOnSave_target: Option<String>               = "null",
70         /// Extra arguments for `cargo check`.
71         checkOnSave_extraArgs: Vec<String>               = "[]",
72         /// List of features to activate. Defaults to
73         /// `#rust-analyzer.cargo.features#`.
74         checkOnSave_features: Option<Vec<String>>        = "null",
75         /// Advanced option, fully override the command rust-analyzer uses for
76         /// checking. The command should include `--message-format=json` or
77         /// similar option.
78         checkOnSave_overrideCommand: Option<Vec<String>> = "null",
79
80         /// Whether to add argument snippets when completing functions.
81         completion_addCallArgumentSnippets: bool = "true",
82         /// Whether to add parenthesis when completing functions.
83         completion_addCallParenthesis: bool      = "true",
84         /// Whether to show postfix snippets like `dbg`, `if`, `not`, etc.
85         completion_postfix_enable: bool          = "true",
86         /// Toggles the additional completions that automatically add imports when completed.
87         /// Note that your client must specify the `additionalTextEdits` LSP client capability to truly have this feature enabled.
88         completion_autoimport_enable: bool       = "true",
89
90         /// Whether to show native rust-analyzer diagnostics.
91         diagnostics_enable: bool                = "true",
92         /// Whether to show experimental rust-analyzer diagnostics that might
93         /// have more false positives than usual.
94         diagnostics_enableExperimental: bool    = "true",
95         /// List of rust-analyzer diagnostics to disable.
96         diagnostics_disabled: FxHashSet<String> = "[]",
97         /// List of warnings that should be displayed with info severity.\n\nThe
98         /// warnings will be indicated by a blue squiggly underline in code and
99         /// a blue icon in the `Problems Panel`.
100         diagnostics_warningsAsHint: Vec<String> = "[]",
101         /// List of warnings that should be displayed with hint severity.\n\nThe
102         /// warnings will be indicated by faded text or three dots in code and
103         /// will not show up in the `Problems Panel`.
104         diagnostics_warningsAsInfo: Vec<String> = "[]",
105
106         /// Controls file watching implementation.
107         files_watcher: String = "\"client\"",
108
109         /// Whether to show `Debug` action. Only applies when
110         /// `#rust-analyzer.hoverActions.enable#` is set.
111         hoverActions_debug: bool           = "true",
112         /// Whether to show HoverActions in Rust files.
113         hoverActions_enable: bool          = "true",
114         /// Whether to show `Go to Type Definition` action. Only applies when
115         /// `#rust-analyzer.hoverActions.enable#` is set.
116         hoverActions_gotoTypeDef: bool     = "true",
117         /// Whether to show `Implementations` action. Only applies when
118         /// `#rust-analyzer.hoverActions.enable#` is set.
119         hoverActions_implementations: bool = "true",
120         /// Whether to show `Run` action. Only applies when
121         /// `#rust-analyzer.hoverActions.enable#` is set.
122         hoverActions_run: bool             = "true",
123         /// Use markdown syntax for links in hover.
124         hoverActions_linksInHover: bool    = "true",
125
126         /// Whether to show inlay type hints for method chains.
127         inlayHints_chainingHints: bool      = "true",
128         /// Maximum length for inlay hints. Default is unlimited.
129         inlayHints_maxLength: Option<usize> = "null",
130         /// Whether to show function parameter name inlay hints at the call
131         /// site.
132         inlayHints_parameterHints: bool     = "true",
133         /// Whether to show inlay type hints for variables.
134         inlayHints_typeHints: bool          = "true",
135
136         /// Whether to show `Debug` lens. Only applies when
137         /// `#rust-analyzer.lens.enable#` is set.
138         lens_debug: bool            = "true",
139         /// Whether to show CodeLens in Rust files.
140         lens_enable: bool           = "true",
141         /// Whether to show `Implementations` lens. Only applies when
142         /// `#rust-analyzer.lens.enable#` is set.
143         lens_implementations: bool  = "true",
144         /// Whether to show `Run` lens. Only applies when
145         /// `#rust-analyzer.lens.enable#` is set.
146         lens_run: bool              = "true",
147         /// Whether to show `Method References` lens. Only applies when
148         /// `#rust-analyzer.lens.enable#` is set.
149         lens_methodReferences: bool = "false",
150         /// Whether to show `References` lens. Only applies when
151         /// `#rust-analyzer.lens.enable#` is set.
152         lens_references: bool = "false",
153
154         /// Disable project auto-discovery in favor of explicitly specified set
155         /// of projects.\n\nElements must be paths pointing to `Cargo.toml`,
156         /// `rust-project.json`, or JSON objects in `rust-project.json` format.
157         linkedProjects: Vec<ManifestOrProjectJson> = "[]",
158
159         /// Number of syntax trees rust-analyzer keeps in memory.  Defaults to 128.
160         lruCapacity: Option<usize>                 = "null",
161
162         /// Whether to show `can't find Cargo.toml` error message.
163         notifications_cargoTomlNotFound: bool      = "true",
164
165         /// Enable Proc macro support, `#rust-analyzer.cargo.loadOutDirsFromCheck#` must be
166         /// enabled.
167         procMacro_enable: bool                     = "false",
168         /// Internal config, path to proc-macro server executable (typically,
169         /// this is rust-analyzer itself, but we override this in tests).
170         procMacro_server: Option<PathBuf>          = "null",
171
172         /// Command to be executed instead of 'cargo' for runnables.
173         runnables_overrideCargo: Option<String> = "null",
174         /// Additional arguments to be passed to cargo for runnables such as
175         /// tests or binaries.\nFor example, it may be `--release`.
176         runnables_cargoExtraArgs: Vec<String>   = "[]",
177
178         /// Path to the rust compiler sources, for usage in rustc_private projects.
179         rustcSource : Option<PathBuf> = "null",
180
181         /// Additional arguments to `rustfmt`.
182         rustfmt_extraArgs: Vec<String>               = "[]",
183         /// Advanced option, fully override the command rust-analyzer uses for
184         /// formatting.
185         rustfmt_overrideCommand: Option<Vec<String>> = "null",
186     }
187 }
188
189 impl Default for ConfigData {
190     fn default() -> Self {
191         ConfigData::from_json(serde_json::Value::Null)
192     }
193 }
194
195 #[derive(Debug, Clone)]
196 pub struct Config {
197     caps: lsp_types::ClientCapabilities,
198     data: ConfigData,
199     pub discovered_projects: Option<Vec<ProjectManifest>>,
200     pub root_path: AbsPathBuf,
201 }
202
203 #[derive(Debug, Clone, Eq, PartialEq)]
204 pub enum LinkedProject {
205     ProjectManifest(ProjectManifest),
206     InlineJsonProject(ProjectJson),
207 }
208
209 impl From<ProjectManifest> for LinkedProject {
210     fn from(v: ProjectManifest) -> Self {
211         LinkedProject::ProjectManifest(v)
212     }
213 }
214
215 impl From<ProjectJson> for LinkedProject {
216     fn from(v: ProjectJson) -> Self {
217         LinkedProject::InlineJsonProject(v)
218     }
219 }
220
221 #[derive(Clone, Debug, PartialEq, Eq)]
222 pub struct LensConfig {
223     pub run: bool,
224     pub debug: bool,
225     pub implementations: bool,
226     pub method_refs: bool,
227     pub refs: bool, // for Struct, Enum, Union and Trait
228 }
229
230 impl LensConfig {
231     pub fn any(&self) -> bool {
232         self.implementations || self.runnable() || self.references()
233     }
234
235     pub fn none(&self) -> bool {
236         !self.any()
237     }
238
239     pub fn runnable(&self) -> bool {
240         self.run || self.debug
241     }
242
243     pub fn references(&self) -> bool {
244         self.method_refs || self.refs
245     }
246 }
247
248 #[derive(Debug, Clone)]
249 pub struct FilesConfig {
250     pub watcher: FilesWatcher,
251     pub exclude: Vec<String>,
252 }
253
254 #[derive(Debug, Clone)]
255 pub enum FilesWatcher {
256     Client,
257     Notify,
258 }
259
260 #[derive(Debug, Clone)]
261 pub struct NotificationsConfig {
262     pub cargo_toml_not_found: bool,
263 }
264
265 #[derive(Debug, Clone)]
266 pub enum RustfmtConfig {
267     Rustfmt { extra_args: Vec<String> },
268     CustomCommand { command: String, args: Vec<String> },
269 }
270
271 /// Configuration for runnable items, such as `main` function or tests.
272 #[derive(Debug, Clone)]
273 pub struct RunnablesConfig {
274     /// Custom command to be executed instead of `cargo` for runnables.
275     pub override_cargo: Option<String>,
276     /// Additional arguments for the `cargo`, e.g. `--release`.
277     pub cargo_extra_args: Vec<String>,
278 }
279
280 impl Config {
281     pub fn new(root_path: AbsPathBuf, caps: ClientCapabilities) -> Self {
282         Config { caps, data: ConfigData::default(), discovered_projects: None, root_path }
283     }
284     pub fn update(&mut self, json: serde_json::Value) {
285         log::info!("updating config from JSON: {:#}", json);
286         if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
287             return;
288         }
289         self.data = ConfigData::from_json(json);
290     }
291
292     pub fn json_schema() -> serde_json::Value {
293         ConfigData::json_schema()
294     }
295 }
296
297 macro_rules! try_ {
298     ($expr:expr) => {
299         || -> _ { Some($expr) }()
300     };
301 }
302 macro_rules! try_or {
303     ($expr:expr, $or:expr) => {
304         try_!($expr).unwrap_or($or)
305     };
306 }
307
308 impl Config {
309     pub fn linked_projects(&self) -> Vec<LinkedProject> {
310         if self.data.linkedProjects.is_empty() {
311             self.discovered_projects
312                 .as_ref()
313                 .into_iter()
314                 .flatten()
315                 .cloned()
316                 .map(LinkedProject::from)
317                 .collect()
318         } else {
319             self.data
320                 .linkedProjects
321                 .iter()
322                 .filter_map(|linked_project| {
323                     let res = match linked_project {
324                         ManifestOrProjectJson::Manifest(it) => {
325                             let path = self.root_path.join(it);
326                             ProjectManifest::from_manifest_file(path)
327                                 .map_err(|e| log::error!("failed to load linked project: {}", e))
328                                 .ok()?
329                                 .into()
330                         }
331                         ManifestOrProjectJson::ProjectJson(it) => {
332                             ProjectJson::new(&self.root_path, it.clone()).into()
333                         }
334                     };
335                     Some(res)
336                 })
337                 .collect()
338         }
339     }
340
341     pub fn did_save_text_document_dynamic_registration(&self) -> bool {
342         let caps =
343             try_or!(self.caps.text_document.as_ref()?.synchronization.clone()?, Default::default());
344         caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
345     }
346     pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
347         try_or!(
348             self.caps.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration?,
349             false
350         )
351     }
352
353     pub fn location_link(&self) -> bool {
354         try_or!(self.caps.text_document.as_ref()?.definition?.link_support?, false)
355     }
356     pub fn line_folding_only(&self) -> bool {
357         try_or!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?, false)
358     }
359     pub fn hierarchical_symbols(&self) -> bool {
360         try_or!(
361             self.caps
362                 .text_document
363                 .as_ref()?
364                 .document_symbol
365                 .as_ref()?
366                 .hierarchical_document_symbol_support?,
367             false
368         )
369     }
370     pub fn code_action_literals(&self) -> bool {
371         try_!(self
372             .caps
373             .text_document
374             .as_ref()?
375             .code_action
376             .as_ref()?
377             .code_action_literal_support
378             .as_ref()?)
379         .is_some()
380     }
381     pub fn work_done_progress(&self) -> bool {
382         try_or!(self.caps.window.as_ref()?.work_done_progress?, false)
383     }
384     pub fn code_action_resolve(&self) -> bool {
385         try_or!(
386             self.caps
387                 .text_document
388                 .as_ref()?
389                 .code_action
390                 .as_ref()?
391                 .resolve_support
392                 .as_ref()?
393                 .properties
394                 .as_slice(),
395             &[]
396         )
397         .iter()
398         .any(|it| it == "edit")
399     }
400     pub fn signature_help_label_offsets(&self) -> bool {
401         try_or!(
402             self.caps
403                 .text_document
404                 .as_ref()?
405                 .signature_help
406                 .as_ref()?
407                 .signature_information
408                 .as_ref()?
409                 .parameter_information
410                 .as_ref()?
411                 .label_offset_support?,
412             false
413         )
414     }
415
416     fn experimental(&self, index: &'static str) -> bool {
417         try_or!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?, false)
418     }
419     pub fn code_action_group(&self) -> bool {
420         self.experimental("codeActionGroup")
421     }
422     pub fn hover_actions(&self) -> bool {
423         self.experimental("hoverActions")
424     }
425     pub fn status_notification(&self) -> bool {
426         self.experimental("statusNotification")
427     }
428
429     pub fn publish_diagnostics(&self) -> bool {
430         self.data.diagnostics_enable
431     }
432     pub fn diagnostics(&self) -> DiagnosticsConfig {
433         DiagnosticsConfig {
434             disable_experimental: !self.data.diagnostics_enableExperimental,
435             disabled: self.data.diagnostics_disabled.clone(),
436         }
437     }
438     pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
439         DiagnosticsMapConfig {
440             warnings_as_info: self.data.diagnostics_warningsAsInfo.clone(),
441             warnings_as_hint: self.data.diagnostics_warningsAsHint.clone(),
442         }
443     }
444     pub fn lru_capacity(&self) -> Option<usize> {
445         self.data.lruCapacity
446     }
447     pub fn proc_macro_srv(&self) -> Option<(PathBuf, Vec<OsString>)> {
448         if !self.data.procMacro_enable {
449             return None;
450         }
451
452         let path = self.data.procMacro_server.clone().or_else(|| std::env::current_exe().ok())?;
453         Some((path, vec!["proc-macro".into()]))
454     }
455     pub fn files(&self) -> FilesConfig {
456         FilesConfig {
457             watcher: match self.data.files_watcher.as_str() {
458                 "notify" => FilesWatcher::Notify,
459                 "client" | _ => FilesWatcher::Client,
460             },
461             exclude: Vec::new(),
462         }
463     }
464     pub fn notifications(&self) -> NotificationsConfig {
465         NotificationsConfig { cargo_toml_not_found: self.data.notifications_cargoTomlNotFound }
466     }
467     pub fn cargo_autoreload(&self) -> bool {
468         self.data.cargo_autoreload
469     }
470     pub fn cargo(&self) -> CargoConfig {
471         let rustc_source = self.data.rustcSource.clone().and_then(|it| {
472             AbsPathBuf::try_from(it)
473                 .map_err(|_| log::error!("rustc source directory must be an absolute path"))
474                 .ok()
475         });
476
477         CargoConfig {
478             no_default_features: self.data.cargo_noDefaultFeatures,
479             all_features: self.data.cargo_allFeatures,
480             features: self.data.cargo_features.clone(),
481             load_out_dirs_from_check: self.data.cargo_loadOutDirsFromCheck,
482             target: self.data.cargo_target.clone(),
483             rustc_source,
484             no_sysroot: self.data.cargo_noSysroot,
485         }
486     }
487     pub fn rustfmt(&self) -> RustfmtConfig {
488         match &self.data.rustfmt_overrideCommand {
489             Some(args) if !args.is_empty() => {
490                 let mut args = args.clone();
491                 let command = args.remove(0);
492                 RustfmtConfig::CustomCommand { command, args }
493             }
494             Some(_) | None => {
495                 RustfmtConfig::Rustfmt { extra_args: self.data.rustfmt_extraArgs.clone() }
496             }
497         }
498     }
499     pub fn flycheck(&self) -> Option<FlycheckConfig> {
500         if !self.data.checkOnSave_enable {
501             return None;
502         }
503         let flycheck_config = match &self.data.checkOnSave_overrideCommand {
504             Some(args) if !args.is_empty() => {
505                 let mut args = args.clone();
506                 let command = args.remove(0);
507                 FlycheckConfig::CustomCommand { command, args }
508             }
509             Some(_) | None => FlycheckConfig::CargoCommand {
510                 command: self.data.checkOnSave_command.clone(),
511                 target_triple: self
512                     .data
513                     .checkOnSave_target
514                     .clone()
515                     .or(self.data.cargo_target.clone()),
516                 all_targets: self.data.checkOnSave_allTargets,
517                 no_default_features: self
518                     .data
519                     .checkOnSave_noDefaultFeatures
520                     .unwrap_or(self.data.cargo_noDefaultFeatures),
521                 all_features: self
522                     .data
523                     .checkOnSave_allFeatures
524                     .unwrap_or(self.data.cargo_allFeatures),
525                 features: self
526                     .data
527                     .checkOnSave_features
528                     .clone()
529                     .unwrap_or(self.data.cargo_features.clone()),
530                 extra_args: self.data.checkOnSave_extraArgs.clone(),
531             },
532         };
533         Some(flycheck_config)
534     }
535     pub fn runnables(&self) -> RunnablesConfig {
536         RunnablesConfig {
537             override_cargo: self.data.runnables_overrideCargo.clone(),
538             cargo_extra_args: self.data.runnables_cargoExtraArgs.clone(),
539         }
540     }
541     pub fn inlay_hints(&self) -> InlayHintsConfig {
542         InlayHintsConfig {
543             type_hints: self.data.inlayHints_typeHints,
544             parameter_hints: self.data.inlayHints_parameterHints,
545             chaining_hints: self.data.inlayHints_chainingHints,
546             max_length: self.data.inlayHints_maxLength,
547         }
548     }
549     fn insert_use_config(&self) -> InsertUseConfig {
550         InsertUseConfig {
551             merge: match self.data.assist_importMergeBehavior {
552                 MergeBehaviorDef::None => None,
553                 MergeBehaviorDef::Full => Some(MergeBehavior::Full),
554                 MergeBehaviorDef::Last => Some(MergeBehavior::Last),
555             },
556             prefix_kind: match self.data.assist_importPrefix {
557                 ImportPrefixDef::Plain => PrefixKind::Plain,
558                 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
559                 ImportPrefixDef::BySelf => PrefixKind::BySelf,
560             },
561         }
562     }
563     pub fn completion(&self) -> CompletionConfig {
564         CompletionConfig {
565             enable_postfix_completions: self.data.completion_postfix_enable,
566             enable_imports_on_the_fly: self.data.completion_autoimport_enable
567                 && completion_item_edit_resolve(&self.caps),
568             add_call_parenthesis: self.data.completion_addCallParenthesis,
569             add_call_argument_snippets: self.data.completion_addCallArgumentSnippets,
570             insert_use: self.insert_use_config(),
571             snippet_cap: SnippetCap::new(try_or!(
572                 self.caps
573                     .text_document
574                     .as_ref()?
575                     .completion
576                     .as_ref()?
577                     .completion_item
578                     .as_ref()?
579                     .snippet_support?,
580                 false
581             )),
582         }
583     }
584     pub fn assist(&self) -> AssistConfig {
585         AssistConfig {
586             snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
587             allowed: None,
588             insert_use: self.insert_use_config(),
589         }
590     }
591     pub fn call_info_full(&self) -> bool {
592         self.data.callInfo_full
593     }
594     pub fn lens(&self) -> LensConfig {
595         LensConfig {
596             run: self.data.lens_enable && self.data.lens_run,
597             debug: self.data.lens_enable && self.data.lens_debug,
598             implementations: self.data.lens_enable && self.data.lens_implementations,
599             method_refs: self.data.lens_enable && self.data.lens_methodReferences,
600             refs: self.data.lens_enable && self.data.lens_references,
601         }
602     }
603     pub fn hover(&self) -> HoverConfig {
604         HoverConfig {
605             implementations: self.data.hoverActions_enable
606                 && self.data.hoverActions_implementations,
607             run: self.data.hoverActions_enable && self.data.hoverActions_run,
608             debug: self.data.hoverActions_enable && self.data.hoverActions_debug,
609             goto_type_def: self.data.hoverActions_enable && self.data.hoverActions_gotoTypeDef,
610             links_in_hover: self.data.hoverActions_linksInHover,
611             markdown: try_or!(
612                 self.caps
613                     .text_document
614                     .as_ref()?
615                     .hover
616                     .as_ref()?
617                     .content_format
618                     .as_ref()?
619                     .as_slice(),
620                 &[]
621             )
622             .contains(&MarkupKind::Markdown),
623         }
624     }
625     pub fn semantic_tokens_refresh(&self) -> bool {
626         try_or!(self.caps.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support?, false)
627     }
628     pub fn code_lens_refresh(&self) -> bool {
629         try_or!(self.caps.workspace.as_ref()?.code_lens.as_ref()?.refresh_support?, false)
630     }
631 }
632
633 #[derive(Deserialize, Debug, Clone)]
634 #[serde(untagged)]
635 enum ManifestOrProjectJson {
636     Manifest(PathBuf),
637     ProjectJson(ProjectJsonData),
638 }
639
640 #[derive(Deserialize, Debug, Clone)]
641 #[serde(rename_all = "snake_case")]
642 enum MergeBehaviorDef {
643     None,
644     Full,
645     Last,
646 }
647
648 #[derive(Deserialize, Debug, Clone)]
649 #[serde(rename_all = "snake_case")]
650 enum ImportPrefixDef {
651     Plain,
652     BySelf,
653     ByCrate,
654 }
655
656 macro_rules! _config_data {
657     (struct $name:ident {
658         $(
659             $(#[doc=$doc:literal])*
660             $field:ident $(| $alias:ident)?: $ty:ty = $default:expr,
661         )*
662     }) => {
663         #[allow(non_snake_case)]
664         #[derive(Debug, Clone)]
665         struct $name { $($field: $ty,)* }
666         impl $name {
667             fn from_json(mut json: serde_json::Value) -> $name {
668                 $name {$(
669                     $field: get_field(
670                         &mut json,
671                         stringify!($field),
672                         None$(.or(Some(stringify!($alias))))?,
673                         $default,
674                     ),
675                 )*}
676             }
677
678             fn json_schema() -> serde_json::Value {
679                 schema(&[
680                     $({
681                         let field = stringify!($field);
682                         let ty = stringify!($ty);
683                         (field, ty, &[$($doc),*], $default)
684                     },)*
685                 ])
686             }
687
688             #[cfg(test)]
689             fn manual() -> String {
690                 manual(&[
691                     $({
692                         let field = stringify!($field);
693                         let ty = stringify!($ty);
694                         (field, ty, &[$($doc),*], $default)
695                     },)*
696                 ])
697             }
698         }
699     };
700 }
701 use _config_data as config_data;
702
703 fn get_field<T: DeserializeOwned>(
704     json: &mut serde_json::Value,
705     field: &'static str,
706     alias: Option<&'static str>,
707     default: &str,
708 ) -> T {
709     let default = serde_json::from_str(default).unwrap();
710
711     // XXX: check alias first, to work-around the VS Code where it pre-fills the
712     // defaults instead of sending an empty object.
713     alias
714         .into_iter()
715         .chain(iter::once(field))
716         .find_map(move |field| {
717             let mut pointer = field.replace('_', "/");
718             pointer.insert(0, '/');
719             json.pointer_mut(&pointer).and_then(|it| serde_json::from_value(it.take()).ok())
720         })
721         .unwrap_or(default)
722 }
723
724 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
725     for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
726         fn key(f: &str) -> &str {
727             f.splitn(2, "_").next().unwrap()
728         }
729         assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
730     }
731
732     let map = fields
733         .iter()
734         .map(|(field, ty, doc, default)| {
735             let name = field.replace("_", ".");
736             let name = format!("rust-analyzer.{}", name);
737             let props = field_props(field, ty, doc, default);
738             (name, props)
739         })
740         .collect::<serde_json::Map<_, _>>();
741     map.into()
742 }
743
744 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
745     let doc = doc.iter().map(|it| it.trim()).join(" ");
746     assert!(
747         doc.ends_with('.') && doc.starts_with(char::is_uppercase),
748         "bad docs for {}: {:?}",
749         field,
750         doc
751     );
752     let default = default.parse::<serde_json::Value>().unwrap();
753
754     let mut map = serde_json::Map::default();
755     macro_rules! set {
756         ($($key:literal: $value:tt),*$(,)?) => {{$(
757             map.insert($key.into(), serde_json::json!($value));
758         )*}};
759     }
760     set!("markdownDescription": doc);
761     set!("default": default);
762
763     match ty {
764         "bool" => set!("type": "boolean"),
765         "String" => set!("type": "string"),
766         "Vec<String>" => set! {
767             "type": "array",
768             "items": { "type": "string" },
769         },
770         "FxHashSet<String>" => set! {
771             "type": "array",
772             "items": { "type": "string" },
773             "uniqueItems": true,
774         },
775         "Option<usize>" => set! {
776             "type": ["null", "integer"],
777             "minimum": 0,
778         },
779         "Option<String>" => set! {
780             "type": ["null", "string"],
781         },
782         "Option<PathBuf>" => set! {
783             "type": ["null", "string"],
784         },
785         "Option<bool>" => set! {
786             "type": ["null", "boolean"],
787         },
788         "Option<Vec<String>>" => set! {
789             "type": ["null", "array"],
790             "items": { "type": "string" },
791         },
792         "MergeBehaviorDef" => set! {
793             "type": "string",
794             "enum": ["none", "full", "last"],
795             "enumDescriptions": [
796                 "No merging",
797                 "Merge all layers of the import trees",
798                 "Only merge the last layer of the import trees"
799             ],
800         },
801         "ImportPrefixDef" => set! {
802             "type": "string",
803             "enum": [
804                 "plain",
805                 "by_self",
806                 "by_crate"
807             ],
808             "enumDescriptions": [
809                 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
810                 "Prefix all import paths with `self` if they don't begin with `self`, `super`, `crate` or a crate name.",
811                 "Force import paths to be absolute by always starting them with `crate` or the crate name they refer to."
812             ],
813         },
814         "Vec<ManifestOrProjectJson>" => set! {
815             "type": "array",
816             "items": { "type": ["string", "object"] },
817         },
818         _ => panic!("{}: {}", ty, default),
819     }
820
821     map.into()
822 }
823
824 #[cfg(test)]
825 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
826     fields
827         .iter()
828         .map(|(field, _ty, doc, default)| {
829             let name = format!("rust-analyzer.{}", field.replace("_", "."));
830             format!("[[{}]]{} (default: `{}`)::\n{}\n", name, name, default, doc.join(" "))
831         })
832         .collect::<String>()
833 }
834
835 #[cfg(test)]
836 mod tests {
837     use std::fs;
838
839     use test_utils::project_dir;
840
841     use super::*;
842
843     #[test]
844     fn schema_in_sync_with_package_json() {
845         let s = Config::json_schema();
846         let schema = format!("{:#}", s);
847         let schema = schema.trim_start_matches('{').trim_end_matches('}');
848
849         let package_json = project_dir().join("editors/code/package.json");
850         let package_json = fs::read_to_string(&package_json).unwrap();
851
852         let p = remove_ws(&package_json);
853         let s = remove_ws(&schema);
854
855         assert!(p.contains(&s), "update config in package.json. New config:\n{:#}", schema);
856     }
857
858     #[test]
859     fn schema_in_sync_with_docs() {
860         let docs_path = project_dir().join("docs/user/generated_config.adoc");
861         let current = fs::read_to_string(&docs_path).unwrap();
862         let expected = ConfigData::manual();
863
864         if remove_ws(&current) != remove_ws(&expected) {
865             fs::write(&docs_path, expected).unwrap();
866             panic!("updated config manual");
867         }
868     }
869
870     fn remove_ws(text: &str) -> String {
871         text.replace(char::is_whitespace, "")
872     }
873 }