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