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