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