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