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