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