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