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