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