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