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