]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/config.rs
Merge #11214
[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 ide::{
14     AssistConfig, CompletionConfig, DiagnosticsConfig, HighlightRelatedConfig, HoverConfig,
15     HoverDocFormat, InlayHintsConfig, JoinLinesConfig, Snippet, SnippetScope,
16 };
17 use ide_db::helpers::{
18     insert_use::{ImportGranularity, InsertUseConfig, PrefixKind},
19     SnippetCap,
20 };
21 use lsp_types::{ClientCapabilities, MarkupKind};
22 use project_model::{
23     CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest, RustcSource, UnsetTestCrates,
24 };
25 use rustc_hash::{FxHashMap, FxHashSet};
26 use serde::{de::DeserializeOwned, Deserialize};
27 use vfs::AbsPathBuf;
28
29 use crate::{
30     caps::completion_item_edit_resolve,
31     diagnostics::DiagnosticsMapConfig,
32     line_index::OffsetEncoding,
33     lsp_ext::supports_utf8,
34     lsp_ext::WorkspaceSymbolSearchScope,
35     lsp_ext::{self, WorkspaceSymbolSearchKind},
36 };
37
38 // Defines the server-side configuration of the rust-analyzer. We generate
39 // *parts* of VS Code's `package.json` config from this.
40 //
41 // However, editor specific config, which the server doesn't know about, should
42 // be specified directly in `package.json`.
43 //
44 // To deprecate an option by replacing it with another name use `new_name | `old_name` so that we keep
45 // parsing the old name.
46 config_data! {
47     struct ConfigData {
48         /// How imports should be grouped into use statements.
49         assist_importGranularity |
50         assist_importMergeBehavior |
51         assist_importMergeBehaviour: ImportGranularityDef  = "\"crate\"",
52         /// Whether to enforce the import granularity setting for all files. If set to false rust-analyzer will try to keep import styles consistent per file.
53         assist_importEnforceGranularity: bool              = "false",
54         /// The path structure for newly inserted paths to use.
55         assist_importPrefix: ImportPrefixDef               = "\"plain\"",
56         /// Group inserted imports by the https://rust-analyzer.github.io/manual.html#auto-import[following order]. Groups are separated by newlines.
57         assist_importGroup: bool                           = "true",
58         /// Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`.
59         assist_allowMergingIntoGlobImports: bool           = "true",
60
61         /// Warm up caches on project load.
62         cache_warmup: bool = "true",
63
64         /// Show function name and docs in parameter hints.
65         callInfo_full: bool                                = "true",
66
67         /// Automatically refresh project info via `cargo metadata` on
68         /// `Cargo.toml` changes.
69         cargo_autoreload: bool           = "true",
70         /// Activate all available features (`--all-features`).
71         cargo_allFeatures: bool          = "false",
72         /// Unsets `#[cfg(test)]` for the specified crates.
73         cargo_unsetTest: Vec<String>   = "[\"core\"]",
74         /// List of features to activate.
75         cargo_features: Vec<String>      = "[]",
76         /// Run build scripts (`build.rs`) for more precise code analysis.
77         cargo_runBuildScripts |
78         cargo_loadOutDirsFromCheck: bool = "true",
79         /// Use `RUSTC_WRAPPER=rust-analyzer` when running build scripts to
80         /// avoid compiling unnecessary things.
81         cargo_useRustcWrapperForBuildScripts: bool = "true",
82         /// Do not activate the `default` feature.
83         cargo_noDefaultFeatures: bool    = "false",
84         /// Compilation target (target triple).
85         cargo_target: Option<String>     = "null",
86         /// Internal config for debugging, disables loading of sysroot crates.
87         cargo_noSysroot: bool            = "false",
88
89         /// Run specified `cargo check` command for diagnostics on save.
90         checkOnSave_enable: bool                         = "true",
91         /// Check with all features (`--all-features`).
92         /// Defaults to `#rust-analyzer.cargo.allFeatures#`.
93         checkOnSave_allFeatures: Option<bool>            = "null",
94         /// Check all targets and tests (`--all-targets`).
95         checkOnSave_allTargets: bool                     = "true",
96         /// Cargo command to use for `cargo check`.
97         checkOnSave_command: String                      = "\"check\"",
98         /// Do not activate the `default` feature.
99         checkOnSave_noDefaultFeatures: Option<bool>      = "null",
100         /// Check for a specific target. Defaults to
101         /// `#rust-analyzer.cargo.target#`.
102         checkOnSave_target: Option<String>               = "null",
103         /// Extra arguments for `cargo check`.
104         checkOnSave_extraArgs: Vec<String>               = "[]",
105         /// List of features to activate. Defaults to
106         /// `#rust-analyzer.cargo.features#`.
107         checkOnSave_features: Option<Vec<String>>        = "null",
108         /// Advanced option, fully override the command rust-analyzer uses for
109         /// checking. The command should include `--message-format=json` or
110         /// similar option.
111         checkOnSave_overrideCommand: Option<Vec<String>> = "null",
112
113         /// Whether to add argument snippets when completing functions.
114         /// Only applies when `#rust-analyzer.completion.addCallParenthesis#` is set.
115         completion_addCallArgumentSnippets: bool = "true",
116         /// Whether to add parenthesis when completing functions.
117         completion_addCallParenthesis: bool      = "true",
118         /// Custom completion snippets.
119         // NOTE: Keep this list in sync with the feature docs of user snippets.
120         completion_snippets: FxHashMap<String, SnippetDef> = r#"{
121             "Arc::new": {
122                 "postfix": "arc",
123                 "body": "Arc::new(${receiver})",
124                 "requires": "std::sync::Arc",
125                 "description": "Put the expression into an `Arc`",
126                 "scope": "expr"
127             },
128             "Rc::new": {
129                 "postfix": "rc",
130                 "body": "Rc::new(${receiver})",
131                 "requires": "std::rc::Rc",
132                 "description": "Put the expression into an `Rc`",
133                 "scope": "expr"
134             },
135             "Box::pin": {
136                 "postfix": "pinbox",
137                 "body": "Box::pin(${receiver})",
138                 "requires": "std::boxed::Box",
139                 "description": "Put the expression into a pinned `Box`",
140                 "scope": "expr"
141             },
142             "Ok": {
143                 "postfix": "ok",
144                 "body": "Ok(${receiver})",
145                 "description": "Wrap the expression in a `Result::Ok`",
146                 "scope": "expr"
147             },
148             "Err": {
149                 "postfix": "err",
150                 "body": "Err(${receiver})",
151                 "description": "Wrap the expression in a `Result::Err`",
152                 "scope": "expr"
153             },
154             "Some": {
155                 "postfix": "some",
156                 "body": "Some(${receiver})",
157                 "description": "Wrap the expression in an `Option::Some`",
158                 "scope": "expr"
159             }
160         }"#,
161         /// Whether to show postfix snippets like `dbg`, `if`, `not`, etc.
162         completion_postfix_enable: bool          = "true",
163         /// Toggles the additional completions that automatically add imports when completed.
164         /// Note that your client must specify the `additionalTextEdits` LSP client capability to truly have this feature enabled.
165         completion_autoimport_enable: bool       = "true",
166         /// Toggles the additional completions that automatically show method calls and field accesses
167         /// with `self` prefixed to them when inside a method.
168         completion_autoself_enable: bool       = "true",
169
170         /// Whether to show native rust-analyzer diagnostics.
171         diagnostics_enable: bool                = "true",
172         /// Whether to show experimental rust-analyzer diagnostics that might
173         /// have more false positives than usual.
174         diagnostics_enableExperimental: bool    = "true",
175         /// List of rust-analyzer diagnostics to disable.
176         diagnostics_disabled: FxHashSet<String> = "[]",
177         /// Map of prefixes to be substituted when parsing diagnostic file paths.
178         /// This should be the reverse mapping of what is passed to `rustc` as `--remap-path-prefix`.
179         diagnostics_remapPrefix: FxHashMap<String, String> = "{}",
180         /// List of warnings that should be displayed with hint severity.
181         ///
182         /// The warnings will be indicated by faded text or three dots in code
183         /// and will not show up in the `Problems Panel`.
184         diagnostics_warningsAsHint: Vec<String> = "[]",
185         /// List of warnings that should be displayed with info severity.
186         ///
187         /// The warnings will be indicated by a blue squiggly underline in code
188         /// and a blue icon in the `Problems Panel`.
189         diagnostics_warningsAsInfo: Vec<String> = "[]",
190
191         /// Expand attribute macros.
192         experimental_procAttrMacros: bool = "true",
193
194         /// Controls file watching implementation.
195         files_watcher: String = "\"client\"",
196         /// These directories will be ignored by rust-analyzer. They are
197         /// relative to the workspace root, and globs are not supported. You may
198         /// also need to add the folders to Code's `files.watcherExclude`.
199         files_excludeDirs: Vec<PathBuf> = "[]",
200
201         /// Enables highlighting of related references while hovering your mouse above any identifier.
202         highlightRelated_references: bool = "true",
203         /// Enables highlighting of all exit points while hovering your mouse above any `return`, `?`, or return type arrow (`->`).
204         highlightRelated_exitPoints: bool = "true",
205         /// Enables highlighting of related references while hovering your mouse `break`, `loop`, `while`, or `for` keywords.
206         highlightRelated_breakPoints: bool = "true",
207         /// Enables highlighting of all break points for a loop or block context while hovering your mouse above any `async` or `await` keywords.
208         highlightRelated_yieldPoints: bool = "true",
209
210         /// Use semantic tokens for strings.
211         ///
212         /// In some editors (e.g. vscode) semantic tokens override other highlighting grammars.
213         /// By disabling semantic tokens for strings, other grammars can be used to highlight
214         /// their contents.
215         highlighting_strings: bool = "true",
216
217         /// Whether to show documentation on hover.
218         hover_documentation: bool       = "true",
219         /// Use markdown syntax for links in hover.
220         hover_linksInHover |
221         hoverActions_linksInHover: bool = "true",
222
223         /// Whether to show `Debug` action. Only applies when
224         /// `#rust-analyzer.hoverActions.enable#` is set.
225         hoverActions_debug: bool           = "true",
226         /// Whether to show HoverActions in Rust files.
227         hoverActions_enable: bool          = "true",
228         /// Whether to show `Go to Type Definition` action. Only applies when
229         /// `#rust-analyzer.hoverActions.enable#` is set.
230         hoverActions_gotoTypeDef: bool     = "true",
231         /// Whether to show `Implementations` action. Only applies when
232         /// `#rust-analyzer.hoverActions.enable#` is set.
233         hoverActions_implementations: bool = "true",
234         /// Whether to show `References` action. Only applies when
235         /// `#rust-analyzer.hoverActions.enable#` is set.
236         hoverActions_references: bool      = "false",
237         /// Whether to show `Run` action. Only applies when
238         /// `#rust-analyzer.hoverActions.enable#` is set.
239         hoverActions_run: bool             = "true",
240
241         /// Whether to show inlay type hints for method chains.
242         inlayHints_chainingHints: bool              = "true",
243         /// Maximum length for inlay hints. Set to null to have an unlimited length.
244         inlayHints_maxLength: Option<usize>         = "25",
245         /// Whether to show function parameter name inlay hints at the call
246         /// site.
247         inlayHints_parameterHints: bool             = "true",
248         /// Whether to show inlay type hints for variables.
249         inlayHints_typeHints: bool                  = "true",
250         /// Whether to hide inlay hints for constructors.
251         inlayHints_hideNamedConstructorHints: bool  = "false",
252
253         /// Join lines inserts else between consecutive ifs.
254         joinLines_joinElseIf: bool = "true",
255         /// Join lines removes trailing commas.
256         joinLines_removeTrailingComma: bool = "true",
257         /// Join lines unwraps trivial blocks.
258         joinLines_unwrapTrivialBlock: bool = "true",
259         /// Join lines merges consecutive declaration and initialization of an assignment.
260         joinLines_joinAssignments: bool = "true",
261
262         /// Whether to show `Debug` lens. Only applies when
263         /// `#rust-analyzer.lens.enable#` is set.
264         lens_debug: bool            = "true",
265         /// Whether to show CodeLens in Rust files.
266         lens_enable: bool           = "true",
267         /// Whether to show `Implementations` lens. Only applies when
268         /// `#rust-analyzer.lens.enable#` is set.
269         lens_implementations: bool  = "true",
270         /// Whether to show `Run` lens. Only applies when
271         /// `#rust-analyzer.lens.enable#` is set.
272         lens_run: bool              = "true",
273         /// Whether to show `Method References` lens. Only applies when
274         /// `#rust-analyzer.lens.enable#` is set.
275         lens_methodReferences: bool = "false",
276         /// Whether to show `References` lens for Struct, Enum, Union and Trait.
277         /// Only applies when `#rust-analyzer.lens.enable#` is set.
278         lens_references: bool = "false",
279         /// Whether to show `References` lens for Enum Variants.
280         /// Only applies when `#rust-analyzer.lens.enable#` is set.
281         lens_enumVariantReferences: bool = "false",
282         /// Internal config: use custom client-side commands even when the
283         /// client doesn't set the corresponding capability.
284         lens_forceCustomCommands: bool = "true",
285
286         /// Disable project auto-discovery in favor of explicitly specified set
287         /// of projects.
288         ///
289         /// Elements must be paths pointing to `Cargo.toml`,
290         /// `rust-project.json`, or JSON objects in `rust-project.json` format.
291         linkedProjects: Vec<ManifestOrProjectJson> = "[]",
292
293         /// Number of syntax trees rust-analyzer keeps in memory. Defaults to 128.
294         lruCapacity: Option<usize>                 = "null",
295
296         /// Whether to show `can't find Cargo.toml` error message.
297         notifications_cargoTomlNotFound: bool      = "true",
298
299         /// Enable support for procedural macros, implies `#rust-analyzer.cargo.runBuildScripts#`.
300         procMacro_enable: bool                     = "true",
301         /// Internal config, path to proc-macro server executable (typically,
302         /// this is rust-analyzer itself, but we override this in tests).
303         procMacro_server: Option<PathBuf>          = "null",
304         /// These proc-macros will be ignored when trying to expand them.
305         ///
306         /// This config takes a map of crate names with the exported proc-macro names to ignore as values.
307         procMacro_ignored: FxHashMap<Box<str>, Box<[Box<str>]>>          = "{}",
308
309         /// Command to be executed instead of 'cargo' for runnables.
310         runnables_overrideCargo: Option<String> = "null",
311         /// Additional arguments to be passed to cargo for runnables such as
312         /// tests or binaries. For example, it may be `--release`.
313         runnables_cargoExtraArgs: Vec<String>   = "[]",
314
315         /// Path to the Cargo.toml of the rust compiler workspace, for usage in rustc_private
316         /// projects, or "discover" to try to automatically find it if the `rustc-dev` component
317         /// is installed.
318         ///
319         /// Any project which uses rust-analyzer with the rustcPrivate
320         /// crates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.
321         ///
322         /// This option does not take effect until rust-analyzer is restarted.
323         rustcSource: Option<String> = "null",
324
325         /// Additional arguments to `rustfmt`.
326         rustfmt_extraArgs: Vec<String>               = "[]",
327         /// Advanced option, fully override the command rust-analyzer uses for
328         /// formatting.
329         rustfmt_overrideCommand: Option<Vec<String>> = "null",
330         /// Enables the use of rustfmt's unstable range formatting command for the
331         /// `textDocument/rangeFormatting` request. The rustfmt option is unstable and only
332         /// available on a nightly build.
333         rustfmt_enableRangeFormatting: bool = "false",
334
335         /// Workspace symbol search scope.
336         workspace_symbol_search_scope: WorkspaceSymbolSearchScopeDef = "\"workspace\"",
337         /// Workspace symbol search kind.
338         workspace_symbol_search_kind: WorkspaceSymbolSearchKindDef = "\"only_types\"",
339     }
340 }
341
342 impl Default for ConfigData {
343     fn default() -> Self {
344         ConfigData::from_json(serde_json::Value::Null, &mut Vec::new())
345     }
346 }
347
348 #[derive(Debug, Clone)]
349 pub struct Config {
350     pub caps: lsp_types::ClientCapabilities,
351     data: ConfigData,
352     detached_files: Vec<AbsPathBuf>,
353     pub discovered_projects: Option<Vec<ProjectManifest>>,
354     pub root_path: AbsPathBuf,
355     snippets: Vec<Snippet>,
356 }
357
358 #[derive(Debug, Clone, Eq, PartialEq)]
359 pub enum LinkedProject {
360     ProjectManifest(ProjectManifest),
361     InlineJsonProject(ProjectJson),
362 }
363
364 impl From<ProjectManifest> for LinkedProject {
365     fn from(v: ProjectManifest) -> Self {
366         LinkedProject::ProjectManifest(v)
367     }
368 }
369
370 impl From<ProjectJson> for LinkedProject {
371     fn from(v: ProjectJson) -> Self {
372         LinkedProject::InlineJsonProject(v)
373     }
374 }
375
376 #[derive(Clone, Debug, PartialEq, Eq)]
377 pub struct LensConfig {
378     pub run: bool,
379     pub debug: bool,
380     pub implementations: bool,
381     pub method_refs: bool,
382     pub refs: bool, // for Struct, Enum, Union and Trait
383     pub enum_variant_refs: bool,
384 }
385
386 impl LensConfig {
387     pub fn any(&self) -> bool {
388         self.implementations || self.runnable() || self.references()
389     }
390
391     pub fn none(&self) -> bool {
392         !self.any()
393     }
394
395     pub fn runnable(&self) -> bool {
396         self.run || self.debug
397     }
398
399     pub fn references(&self) -> bool {
400         self.method_refs || self.refs || self.enum_variant_refs
401     }
402 }
403
404 #[derive(Clone, Debug, PartialEq, Eq)]
405 pub struct HoverActionsConfig {
406     pub implementations: bool,
407     pub references: bool,
408     pub run: bool,
409     pub debug: bool,
410     pub goto_type_def: bool,
411 }
412
413 impl HoverActionsConfig {
414     pub const NO_ACTIONS: Self = Self {
415         implementations: false,
416         references: false,
417         run: false,
418         debug: false,
419         goto_type_def: false,
420     };
421
422     pub fn any(&self) -> bool {
423         self.implementations || self.references || self.runnable() || self.goto_type_def
424     }
425
426     pub fn none(&self) -> bool {
427         !self.any()
428     }
429
430     pub fn runnable(&self) -> bool {
431         self.run || self.debug
432     }
433 }
434
435 #[derive(Debug, Clone)]
436 pub struct FilesConfig {
437     pub watcher: FilesWatcher,
438     pub exclude: Vec<AbsPathBuf>,
439 }
440
441 #[derive(Debug, Clone)]
442 pub enum FilesWatcher {
443     Client,
444     Notify,
445 }
446
447 #[derive(Debug, Clone)]
448 pub struct NotificationsConfig {
449     pub cargo_toml_not_found: bool,
450 }
451
452 #[derive(Debug, Clone)]
453 pub enum RustfmtConfig {
454     Rustfmt { extra_args: Vec<String>, enable_range_formatting: bool },
455     CustomCommand { command: String, args: Vec<String> },
456 }
457
458 /// Configuration for runnable items, such as `main` function or tests.
459 #[derive(Debug, Clone)]
460 pub struct RunnablesConfig {
461     /// Custom command to be executed instead of `cargo` for runnables.
462     pub override_cargo: Option<String>,
463     /// Additional arguments for the `cargo`, e.g. `--release`.
464     pub cargo_extra_args: Vec<String>,
465 }
466
467 /// Configuration for workspace symbol search requests.
468 #[derive(Debug, Clone)]
469 pub struct WorkspaceSymbolConfig {
470     /// In what scope should the symbol be searched in.
471     pub search_scope: WorkspaceSymbolSearchScope,
472     /// What kind of symbol is being search for.
473     pub search_kind: WorkspaceSymbolSearchKind,
474 }
475
476 pub struct ClientCommandsConfig {
477     pub run_single: bool,
478     pub debug_single: bool,
479     pub show_reference: bool,
480     pub goto_location: bool,
481     pub trigger_parameter_hints: bool,
482 }
483
484 impl Config {
485     pub fn new(root_path: AbsPathBuf, caps: ClientCapabilities) -> Self {
486         Config {
487             caps,
488             data: ConfigData::default(),
489             detached_files: Vec::new(),
490             discovered_projects: None,
491             root_path,
492             snippets: Default::default(),
493         }
494     }
495     pub fn update(
496         &mut self,
497         mut json: serde_json::Value,
498     ) -> Result<(), Vec<(String, serde_json::Error)>> {
499         tracing::info!("updating config from JSON: {:#}", json);
500         if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
501             return Ok(());
502         }
503         let mut errors = Vec::new();
504         self.detached_files =
505             get_field::<Vec<PathBuf>>(&mut json, &mut errors, "detachedFiles", None, "[]")
506                 .into_iter()
507                 .map(AbsPathBuf::assert)
508                 .collect();
509         self.data = ConfigData::from_json(json, &mut errors);
510         self.snippets.clear();
511         for (name, def) in self.data.completion_snippets.iter() {
512             if def.prefix.is_empty() && def.postfix.is_empty() {
513                 continue;
514             }
515             let scope = match def.scope {
516                 SnippetScopeDef::Expr => SnippetScope::Expr,
517                 SnippetScopeDef::Type => SnippetScope::Type,
518                 SnippetScopeDef::Item => SnippetScope::Item,
519             };
520             match Snippet::new(
521                 &def.prefix,
522                 &def.postfix,
523                 &def.body,
524                 def.description.as_ref().unwrap_or(name),
525                 &def.requires,
526                 scope,
527             ) {
528                 Some(snippet) => self.snippets.push(snippet),
529                 None => tracing::info!("Invalid snippet {}", name),
530             }
531         }
532         if errors.is_empty() {
533             Ok(())
534         } else {
535             Err(errors)
536         }
537     }
538
539     pub fn json_schema() -> serde_json::Value {
540         ConfigData::json_schema()
541     }
542 }
543
544 macro_rules! try_ {
545     ($expr:expr) => {
546         || -> _ { Some($expr) }()
547     };
548 }
549 macro_rules! try_or {
550     ($expr:expr, $or:expr) => {
551         try_!($expr).unwrap_or($or)
552     };
553 }
554
555 impl Config {
556     pub fn linked_projects(&self) -> Vec<LinkedProject> {
557         if self.data.linkedProjects.is_empty() {
558             self.discovered_projects
559                 .as_ref()
560                 .into_iter()
561                 .flatten()
562                 .cloned()
563                 .map(LinkedProject::from)
564                 .collect()
565         } else {
566             self.data
567                 .linkedProjects
568                 .iter()
569                 .filter_map(|linked_project| {
570                     let res = match linked_project {
571                         ManifestOrProjectJson::Manifest(it) => {
572                             let path = self.root_path.join(it);
573                             ProjectManifest::from_manifest_file(path)
574                                 .map_err(|e| {
575                                     tracing::error!("failed to load linked project: {}", e)
576                                 })
577                                 .ok()?
578                                 .into()
579                         }
580                         ManifestOrProjectJson::ProjectJson(it) => {
581                             ProjectJson::new(&self.root_path, it.clone()).into()
582                         }
583                     };
584                     Some(res)
585                 })
586                 .collect()
587         }
588     }
589
590     pub fn detached_files(&self) -> &[AbsPathBuf] {
591         &self.detached_files
592     }
593
594     pub fn did_save_text_document_dynamic_registration(&self) -> bool {
595         let caps =
596             try_or!(self.caps.text_document.as_ref()?.synchronization.clone()?, Default::default());
597         caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
598     }
599     pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
600         try_or!(
601             self.caps.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration?,
602             false
603         )
604     }
605
606     pub fn prefill_caches(&self) -> bool {
607         self.data.cache_warmup
608     }
609
610     pub fn location_link(&self) -> bool {
611         try_or!(self.caps.text_document.as_ref()?.definition?.link_support?, false)
612     }
613     pub fn line_folding_only(&self) -> bool {
614         try_or!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?, false)
615     }
616     pub fn hierarchical_symbols(&self) -> bool {
617         try_or!(
618             self.caps
619                 .text_document
620                 .as_ref()?
621                 .document_symbol
622                 .as_ref()?
623                 .hierarchical_document_symbol_support?,
624             false
625         )
626     }
627     pub fn code_action_literals(&self) -> bool {
628         try_!(self
629             .caps
630             .text_document
631             .as_ref()?
632             .code_action
633             .as_ref()?
634             .code_action_literal_support
635             .as_ref()?)
636         .is_some()
637     }
638     pub fn work_done_progress(&self) -> bool {
639         try_or!(self.caps.window.as_ref()?.work_done_progress?, false)
640     }
641     pub fn will_rename(&self) -> bool {
642         try_or!(self.caps.workspace.as_ref()?.file_operations.as_ref()?.will_rename?, false)
643     }
644     pub fn change_annotation_support(&self) -> bool {
645         try_!(self
646             .caps
647             .workspace
648             .as_ref()?
649             .workspace_edit
650             .as_ref()?
651             .change_annotation_support
652             .as_ref()?)
653         .is_some()
654     }
655     pub fn code_action_resolve(&self) -> bool {
656         try_or!(
657             self.caps
658                 .text_document
659                 .as_ref()?
660                 .code_action
661                 .as_ref()?
662                 .resolve_support
663                 .as_ref()?
664                 .properties
665                 .as_slice(),
666             &[]
667         )
668         .iter()
669         .any(|it| it == "edit")
670     }
671     pub fn signature_help_label_offsets(&self) -> bool {
672         try_or!(
673             self.caps
674                 .text_document
675                 .as_ref()?
676                 .signature_help
677                 .as_ref()?
678                 .signature_information
679                 .as_ref()?
680                 .parameter_information
681                 .as_ref()?
682                 .label_offset_support?,
683             false
684         )
685     }
686     pub fn offset_encoding(&self) -> OffsetEncoding {
687         if supports_utf8(&self.caps) {
688             OffsetEncoding::Utf8
689         } else {
690             OffsetEncoding::Utf16
691         }
692     }
693
694     fn experimental(&self, index: &'static str) -> bool {
695         try_or!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?, false)
696     }
697     pub fn code_action_group(&self) -> bool {
698         self.experimental("codeActionGroup")
699     }
700     pub fn server_status_notification(&self) -> bool {
701         self.experimental("serverStatusNotification")
702     }
703
704     pub fn publish_diagnostics(&self) -> bool {
705         self.data.diagnostics_enable
706     }
707     pub fn diagnostics(&self) -> DiagnosticsConfig {
708         DiagnosticsConfig {
709             disable_experimental: !self.data.diagnostics_enableExperimental,
710             disabled: self.data.diagnostics_disabled.clone(),
711         }
712     }
713     pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
714         DiagnosticsMapConfig {
715             remap_prefix: self.data.diagnostics_remapPrefix.clone(),
716             warnings_as_info: self.data.diagnostics_warningsAsInfo.clone(),
717             warnings_as_hint: self.data.diagnostics_warningsAsHint.clone(),
718         }
719     }
720     pub fn lru_capacity(&self) -> Option<usize> {
721         self.data.lruCapacity
722     }
723     pub fn proc_macro_srv(&self) -> Option<(AbsPathBuf, Vec<OsString>)> {
724         if !self.data.procMacro_enable {
725             return None;
726         }
727         let path = match &self.data.procMacro_server {
728             Some(it) => self.root_path.join(it),
729             None => AbsPathBuf::assert(std::env::current_exe().ok()?),
730         };
731         Some((path, vec!["proc-macro".into()]))
732     }
733     pub fn dummy_replacements(&self) -> &FxHashMap<Box<str>, Box<[Box<str>]>> {
734         &self.data.procMacro_ignored
735     }
736     pub fn expand_proc_attr_macros(&self) -> bool {
737         self.data.experimental_procAttrMacros
738     }
739     pub fn files(&self) -> FilesConfig {
740         FilesConfig {
741             watcher: match self.data.files_watcher.as_str() {
742                 "notify" => FilesWatcher::Notify,
743                 "client" if self.did_change_watched_files_dynamic_registration() => {
744                     FilesWatcher::Client
745                 }
746                 _ => FilesWatcher::Notify,
747             },
748             exclude: self.data.files_excludeDirs.iter().map(|it| self.root_path.join(it)).collect(),
749         }
750     }
751     pub fn notifications(&self) -> NotificationsConfig {
752         NotificationsConfig { cargo_toml_not_found: self.data.notifications_cargoTomlNotFound }
753     }
754     pub fn cargo_autoreload(&self) -> bool {
755         self.data.cargo_autoreload
756     }
757     pub fn run_build_scripts(&self) -> bool {
758         self.data.cargo_runBuildScripts || self.data.procMacro_enable
759     }
760     pub fn cargo(&self) -> CargoConfig {
761         let rustc_source = self.data.rustcSource.as_ref().map(|rustc_src| {
762             if rustc_src == "discover" {
763                 RustcSource::Discover
764             } else {
765                 RustcSource::Path(self.root_path.join(rustc_src))
766             }
767         });
768
769         CargoConfig {
770             no_default_features: self.data.cargo_noDefaultFeatures,
771             all_features: self.data.cargo_allFeatures,
772             features: self.data.cargo_features.clone(),
773             target: self.data.cargo_target.clone(),
774             no_sysroot: self.data.cargo_noSysroot,
775             rustc_source,
776             unset_test_crates: UnsetTestCrates::Only(self.data.cargo_unsetTest.clone()),
777             wrap_rustc_in_build_scripts: self.data.cargo_useRustcWrapperForBuildScripts,
778         }
779     }
780
781     pub fn rustfmt(&self) -> RustfmtConfig {
782         match &self.data.rustfmt_overrideCommand {
783             Some(args) if !args.is_empty() => {
784                 let mut args = args.clone();
785                 let command = args.remove(0);
786                 RustfmtConfig::CustomCommand { command, args }
787             }
788             Some(_) | None => RustfmtConfig::Rustfmt {
789                 extra_args: self.data.rustfmt_extraArgs.clone(),
790                 enable_range_formatting: self.data.rustfmt_enableRangeFormatting,
791             },
792         }
793     }
794     pub fn flycheck(&self) -> Option<FlycheckConfig> {
795         if !self.data.checkOnSave_enable {
796             return None;
797         }
798         let flycheck_config = match &self.data.checkOnSave_overrideCommand {
799             Some(args) if !args.is_empty() => {
800                 let mut args = args.clone();
801                 let command = args.remove(0);
802                 FlycheckConfig::CustomCommand { command, args }
803             }
804             Some(_) | None => FlycheckConfig::CargoCommand {
805                 command: self.data.checkOnSave_command.clone(),
806                 target_triple: self
807                     .data
808                     .checkOnSave_target
809                     .clone()
810                     .or_else(|| self.data.cargo_target.clone()),
811                 all_targets: self.data.checkOnSave_allTargets,
812                 no_default_features: self
813                     .data
814                     .checkOnSave_noDefaultFeatures
815                     .unwrap_or(self.data.cargo_noDefaultFeatures),
816                 all_features: self
817                     .data
818                     .checkOnSave_allFeatures
819                     .unwrap_or(self.data.cargo_allFeatures),
820                 features: self
821                     .data
822                     .checkOnSave_features
823                     .clone()
824                     .unwrap_or_else(|| self.data.cargo_features.clone()),
825                 extra_args: self.data.checkOnSave_extraArgs.clone(),
826             },
827         };
828         Some(flycheck_config)
829     }
830     pub fn runnables(&self) -> RunnablesConfig {
831         RunnablesConfig {
832             override_cargo: self.data.runnables_overrideCargo.clone(),
833             cargo_extra_args: self.data.runnables_cargoExtraArgs.clone(),
834         }
835     }
836     pub fn inlay_hints(&self) -> InlayHintsConfig {
837         InlayHintsConfig {
838             type_hints: self.data.inlayHints_typeHints,
839             parameter_hints: self.data.inlayHints_parameterHints,
840             chaining_hints: self.data.inlayHints_chainingHints,
841             hide_named_constructor_hints: self.data.inlayHints_hideNamedConstructorHints,
842             max_length: self.data.inlayHints_maxLength,
843         }
844     }
845     fn insert_use_config(&self) -> InsertUseConfig {
846         InsertUseConfig {
847             granularity: match self.data.assist_importGranularity {
848                 ImportGranularityDef::Preserve => ImportGranularity::Preserve,
849                 ImportGranularityDef::Item => ImportGranularity::Item,
850                 ImportGranularityDef::Crate => ImportGranularity::Crate,
851                 ImportGranularityDef::Module => ImportGranularity::Module,
852             },
853             enforce_granularity: self.data.assist_importEnforceGranularity,
854             prefix_kind: match self.data.assist_importPrefix {
855                 ImportPrefixDef::Plain => PrefixKind::Plain,
856                 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
857                 ImportPrefixDef::BySelf => PrefixKind::BySelf,
858             },
859             group: self.data.assist_importGroup,
860             skip_glob_imports: !self.data.assist_allowMergingIntoGlobImports,
861         }
862     }
863     pub fn completion(&self) -> CompletionConfig {
864         CompletionConfig {
865             enable_postfix_completions: self.data.completion_postfix_enable,
866             enable_imports_on_the_fly: self.data.completion_autoimport_enable
867                 && completion_item_edit_resolve(&self.caps),
868             enable_self_on_the_fly: self.data.completion_autoself_enable,
869             add_call_parenthesis: self.data.completion_addCallParenthesis,
870             add_call_argument_snippets: self.data.completion_addCallArgumentSnippets,
871             insert_use: self.insert_use_config(),
872             snippet_cap: SnippetCap::new(try_or!(
873                 self.caps
874                     .text_document
875                     .as_ref()?
876                     .completion
877                     .as_ref()?
878                     .completion_item
879                     .as_ref()?
880                     .snippet_support?,
881                 false
882             )),
883             snippets: self.snippets.clone(),
884         }
885     }
886     pub fn assist(&self) -> AssistConfig {
887         AssistConfig {
888             snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
889             allowed: None,
890             insert_use: self.insert_use_config(),
891         }
892     }
893     pub fn join_lines(&self) -> JoinLinesConfig {
894         JoinLinesConfig {
895             join_else_if: self.data.joinLines_joinElseIf,
896             remove_trailing_comma: self.data.joinLines_removeTrailingComma,
897             unwrap_trivial_blocks: self.data.joinLines_unwrapTrivialBlock,
898             join_assignments: self.data.joinLines_joinAssignments,
899         }
900     }
901     pub fn call_info_full(&self) -> bool {
902         self.data.callInfo_full
903     }
904     pub fn lens(&self) -> LensConfig {
905         LensConfig {
906             run: self.data.lens_enable && self.data.lens_run,
907             debug: self.data.lens_enable && self.data.lens_debug,
908             implementations: self.data.lens_enable && self.data.lens_implementations,
909             method_refs: self.data.lens_enable && self.data.lens_methodReferences,
910             refs: self.data.lens_enable && self.data.lens_references,
911             enum_variant_refs: self.data.lens_enable && self.data.lens_enumVariantReferences,
912         }
913     }
914     pub fn hover_actions(&self) -> HoverActionsConfig {
915         let enable = self.experimental("hoverActions") && self.data.hoverActions_enable;
916         HoverActionsConfig {
917             implementations: enable && self.data.hoverActions_implementations,
918             references: enable && self.data.hoverActions_references,
919             run: enable && self.data.hoverActions_run,
920             debug: enable && self.data.hoverActions_debug,
921             goto_type_def: enable && self.data.hoverActions_gotoTypeDef,
922         }
923     }
924     pub fn highlighting_strings(&self) -> bool {
925         self.data.highlighting_strings
926     }
927     pub fn hover(&self) -> HoverConfig {
928         HoverConfig {
929             links_in_hover: self.data.hover_linksInHover,
930             documentation: self.data.hover_documentation.then(|| {
931                 let is_markdown = try_or!(
932                     self.caps
933                         .text_document
934                         .as_ref()?
935                         .hover
936                         .as_ref()?
937                         .content_format
938                         .as_ref()?
939                         .as_slice(),
940                     &[]
941                 )
942                 .contains(&MarkupKind::Markdown);
943                 if is_markdown {
944                     HoverDocFormat::Markdown
945                 } else {
946                     HoverDocFormat::PlainText
947                 }
948             }),
949         }
950     }
951
952     pub fn workspace_symbol(&self) -> WorkspaceSymbolConfig {
953         WorkspaceSymbolConfig {
954             search_scope: match self.data.workspace_symbol_search_scope {
955                 WorkspaceSymbolSearchScopeDef::Workspace => WorkspaceSymbolSearchScope::Workspace,
956                 WorkspaceSymbolSearchScopeDef::WorkspaceAndDependencies => {
957                     WorkspaceSymbolSearchScope::WorkspaceAndDependencies
958                 }
959             },
960             search_kind: match self.data.workspace_symbol_search_kind {
961                 WorkspaceSymbolSearchKindDef::OnlyTypes => WorkspaceSymbolSearchKind::OnlyTypes,
962                 WorkspaceSymbolSearchKindDef::AllSymbols => WorkspaceSymbolSearchKind::AllSymbols,
963             },
964         }
965     }
966
967     pub fn semantic_tokens_refresh(&self) -> bool {
968         try_or!(self.caps.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support?, false)
969     }
970     pub fn code_lens_refresh(&self) -> bool {
971         try_or!(self.caps.workspace.as_ref()?.code_lens.as_ref()?.refresh_support?, false)
972     }
973     pub fn insert_replace_support(&self) -> bool {
974         try_or!(
975             self.caps
976                 .text_document
977                 .as_ref()?
978                 .completion
979                 .as_ref()?
980                 .completion_item
981                 .as_ref()?
982                 .insert_replace_support?,
983             false
984         )
985     }
986     pub fn client_commands(&self) -> ClientCommandsConfig {
987         let commands =
988             try_or!(self.caps.experimental.as_ref()?.get("commands")?, &serde_json::Value::Null);
989         let commands: Option<lsp_ext::ClientCommandOptions> =
990             serde_json::from_value(commands.clone()).ok();
991         let force = commands.is_none() && self.data.lens_forceCustomCommands;
992         let commands = commands.map(|it| it.commands).unwrap_or_default();
993
994         let get = |name: &str| commands.iter().any(|it| it == name) || force;
995
996         ClientCommandsConfig {
997             run_single: get("rust-analyzer.runSingle"),
998             debug_single: get("rust-analyzer.debugSingle"),
999             show_reference: get("rust-analyzer.showReferences"),
1000             goto_location: get("rust-analyzer.gotoLocation"),
1001             trigger_parameter_hints: get("editor.action.triggerParameterHints"),
1002         }
1003     }
1004
1005     pub fn highlight_related(&self) -> HighlightRelatedConfig {
1006         HighlightRelatedConfig {
1007             references: self.data.highlightRelated_references,
1008             break_points: self.data.highlightRelated_breakPoints,
1009             exit_points: self.data.highlightRelated_exitPoints,
1010             yield_points: self.data.highlightRelated_yieldPoints,
1011         }
1012     }
1013 }
1014
1015 #[derive(Deserialize, Debug, Clone, Copy)]
1016 #[serde(rename_all = "snake_case")]
1017 enum SnippetScopeDef {
1018     Expr,
1019     Item,
1020     Type,
1021 }
1022
1023 impl Default for SnippetScopeDef {
1024     fn default() -> Self {
1025         SnippetScopeDef::Expr
1026     }
1027 }
1028
1029 #[derive(Deserialize, Debug, Clone, Default)]
1030 #[serde(default)]
1031 struct SnippetDef {
1032     #[serde(deserialize_with = "single_or_array")]
1033     prefix: Vec<String>,
1034     #[serde(deserialize_with = "single_or_array")]
1035     postfix: Vec<String>,
1036     description: Option<String>,
1037     #[serde(deserialize_with = "single_or_array")]
1038     body: Vec<String>,
1039     #[serde(deserialize_with = "single_or_array")]
1040     requires: Vec<String>,
1041     scope: SnippetScopeDef,
1042 }
1043
1044 fn single_or_array<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
1045 where
1046     D: serde::Deserializer<'de>,
1047 {
1048     struct SingleOrVec;
1049
1050     impl<'de> serde::de::Visitor<'de> for SingleOrVec {
1051         type Value = Vec<String>;
1052
1053         fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
1054             formatter.write_str("string or array of strings")
1055         }
1056
1057         fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1058         where
1059             E: serde::de::Error,
1060         {
1061             Ok(vec![value.to_owned()])
1062         }
1063
1064         fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1065         where
1066             A: serde::de::SeqAccess<'de>,
1067         {
1068             Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
1069         }
1070     }
1071
1072     deserializer.deserialize_any(SingleOrVec)
1073 }
1074
1075 #[derive(Deserialize, Debug, Clone)]
1076 #[serde(untagged)]
1077 enum ManifestOrProjectJson {
1078     Manifest(PathBuf),
1079     ProjectJson(ProjectJsonData),
1080 }
1081
1082 #[derive(Deserialize, Debug, Clone)]
1083 #[serde(rename_all = "snake_case")]
1084 enum ImportGranularityDef {
1085     Preserve,
1086     #[serde(alias = "none")]
1087     Item,
1088     #[serde(alias = "full")]
1089     Crate,
1090     #[serde(alias = "last")]
1091     Module,
1092 }
1093
1094 #[derive(Deserialize, Debug, Clone)]
1095 #[serde(rename_all = "snake_case")]
1096 enum ImportPrefixDef {
1097     Plain,
1098     #[serde(alias = "self")]
1099     BySelf,
1100     #[serde(alias = "crate")]
1101     ByCrate,
1102 }
1103
1104 #[derive(Deserialize, Debug, Clone)]
1105 #[serde(rename_all = "snake_case")]
1106 enum WorkspaceSymbolSearchScopeDef {
1107     Workspace,
1108     WorkspaceAndDependencies,
1109 }
1110
1111 #[derive(Deserialize, Debug, Clone)]
1112 #[serde(rename_all = "snake_case")]
1113 enum WorkspaceSymbolSearchKindDef {
1114     OnlyTypes,
1115     AllSymbols,
1116 }
1117
1118 macro_rules! _config_data {
1119     (struct $name:ident {
1120         $(
1121             $(#[doc=$doc:literal])*
1122             $field:ident $(| $alias:ident)*: $ty:ty = $default:expr,
1123         )*
1124     }) => {
1125         #[allow(non_snake_case)]
1126         #[derive(Debug, Clone)]
1127         struct $name { $($field: $ty,)* }
1128         impl $name {
1129             fn from_json(mut json: serde_json::Value, error_sink: &mut Vec<(String, serde_json::Error)>) -> $name {
1130                 $name {$(
1131                     $field: get_field(
1132                         &mut json,
1133                         error_sink,
1134                         stringify!($field),
1135                         None$(.or(Some(stringify!($alias))))*,
1136                         $default,
1137                     ),
1138                 )*}
1139             }
1140
1141             fn json_schema() -> serde_json::Value {
1142                 schema(&[
1143                     $({
1144                         let field = stringify!($field);
1145                         let ty = stringify!($ty);
1146
1147                         (field, ty, &[$($doc),*], $default)
1148                     },)*
1149                 ])
1150             }
1151
1152             #[cfg(test)]
1153             fn manual() -> String {
1154                 manual(&[
1155                     $({
1156                         let field = stringify!($field);
1157                         let ty = stringify!($ty);
1158
1159                         (field, ty, &[$($doc),*], $default)
1160                     },)*
1161                 ])
1162             }
1163         }
1164     };
1165 }
1166 use _config_data as config_data;
1167
1168 fn get_field<T: DeserializeOwned>(
1169     json: &mut serde_json::Value,
1170     error_sink: &mut Vec<(String, serde_json::Error)>,
1171     field: &'static str,
1172     alias: Option<&'static str>,
1173     default: &str,
1174 ) -> T {
1175     let default = serde_json::from_str(default).unwrap();
1176
1177     // XXX: check alias first, to work-around the VS Code where it pre-fills the
1178     // defaults instead of sending an empty object.
1179     alias
1180         .into_iter()
1181         .chain(iter::once(field))
1182         .find_map(move |field| {
1183             let mut pointer = field.replace('_', "/");
1184             pointer.insert(0, '/');
1185             json.pointer_mut(&pointer).and_then(|it| match serde_json::from_value(it.take()) {
1186                 Ok(it) => Some(it),
1187                 Err(e) => {
1188                     tracing::warn!("Failed to deserialize config field at {}: {:?}", pointer, e);
1189                     error_sink.push((pointer, e));
1190                     None
1191                 }
1192             })
1193         })
1194         .unwrap_or(default)
1195 }
1196
1197 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
1198     for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
1199         fn key(f: &str) -> &str {
1200             f.splitn(2, '_').next().unwrap()
1201         }
1202         assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
1203     }
1204
1205     let map = fields
1206         .iter()
1207         .map(|(field, ty, doc, default)| {
1208             let name = field.replace("_", ".");
1209             let name = format!("rust-analyzer.{}", name);
1210             let props = field_props(field, ty, doc, default);
1211             (name, props)
1212         })
1213         .collect::<serde_json::Map<_, _>>();
1214     map.into()
1215 }
1216
1217 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
1218     let doc = doc_comment_to_string(doc);
1219     let doc = doc.trim_end_matches('\n');
1220     assert!(
1221         doc.ends_with('.') && doc.starts_with(char::is_uppercase),
1222         "bad docs for {}: {:?}",
1223         field,
1224         doc
1225     );
1226     let default = default.parse::<serde_json::Value>().unwrap();
1227
1228     let mut map = serde_json::Map::default();
1229     macro_rules! set {
1230         ($($key:literal: $value:tt),*$(,)?) => {{$(
1231             map.insert($key.into(), serde_json::json!($value));
1232         )*}};
1233     }
1234     set!("markdownDescription": doc);
1235     set!("default": default);
1236
1237     match ty {
1238         "bool" => set!("type": "boolean"),
1239         "String" => set!("type": "string"),
1240         "Vec<String>" => set! {
1241             "type": "array",
1242             "items": { "type": "string" },
1243         },
1244         "Vec<PathBuf>" => set! {
1245             "type": "array",
1246             "items": { "type": "string" },
1247         },
1248         "FxHashSet<String>" => set! {
1249             "type": "array",
1250             "items": { "type": "string" },
1251             "uniqueItems": true,
1252         },
1253         "FxHashMap<Box<str>, Box<[Box<str>]>>" => set! {
1254             "type": "object",
1255         },
1256         "FxHashMap<String, SnippetDef>" => set! {
1257             "type": "object",
1258         },
1259         "FxHashMap<String, String>" => set! {
1260             "type": "object",
1261         },
1262         "Option<usize>" => set! {
1263             "type": ["null", "integer"],
1264             "minimum": 0,
1265         },
1266         "Option<String>" => set! {
1267             "type": ["null", "string"],
1268         },
1269         "Option<PathBuf>" => set! {
1270             "type": ["null", "string"],
1271         },
1272         "Option<bool>" => set! {
1273             "type": ["null", "boolean"],
1274         },
1275         "Option<Vec<String>>" => set! {
1276             "type": ["null", "array"],
1277             "items": { "type": "string" },
1278         },
1279         "MergeBehaviorDef" => set! {
1280             "type": "string",
1281             "enum": ["none", "crate", "module"],
1282             "enumDescriptions": [
1283                 "Do not merge imports at all.",
1284                 "Merge imports from the same crate into a single `use` statement.",
1285                 "Merge imports from the same module into a single `use` statement."
1286             ],
1287         },
1288         "ImportGranularityDef" => set! {
1289             "type": "string",
1290             "enum": ["preserve", "crate", "module", "item"],
1291             "enumDescriptions": [
1292                 "Do not change the granularity of any imports and preserve the original structure written by the developer.",
1293                 "Merge imports from the same crate into a single use statement. Conversely, imports from different crates are split into separate statements.",
1294                 "Merge imports from the same module into a single use statement. Conversely, imports from different modules are split into separate statements.",
1295                 "Flatten imports so that each has its own use statement."
1296             ],
1297         },
1298         "ImportPrefixDef" => set! {
1299             "type": "string",
1300             "enum": [
1301                 "plain",
1302                 "self",
1303                 "crate"
1304             ],
1305             "enumDescriptions": [
1306                 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
1307                 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item. Prefixes `self` in front of the path if it starts with a module.",
1308                 "Force import paths to be absolute by always starting them with `crate` or the extern crate name they come from."
1309             ],
1310         },
1311         "Vec<ManifestOrProjectJson>" => set! {
1312             "type": "array",
1313             "items": { "type": ["string", "object"] },
1314         },
1315         "WorkspaceSymbolSearchScopeDef" => set! {
1316             "type": "string",
1317             "enum": ["workspace", "workspace_and_dependencies"],
1318             "enumDescriptions": [
1319                 "Search in current workspace only",
1320                 "Search in current workspace and dependencies"
1321             ],
1322         },
1323         "WorkspaceSymbolSearchKindDef" => set! {
1324             "type": "string",
1325             "enum": ["only_types", "all_symbols"],
1326             "enumDescriptions": [
1327                 "Search for types only",
1328                 "Search for all symbols kinds"
1329             ],
1330         },
1331         _ => panic!("{}: {}", ty, default),
1332     }
1333
1334     map.into()
1335 }
1336
1337 #[cfg(test)]
1338 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
1339     fields
1340         .iter()
1341         .map(|(field, _ty, doc, default)| {
1342             let name = format!("rust-analyzer.{}", field.replace("_", "."));
1343             let doc = doc_comment_to_string(*doc);
1344             format!("[[{}]]{} (default: `{}`)::\n+\n--\n{}--\n", name, name, default, doc)
1345         })
1346         .collect::<String>()
1347 }
1348
1349 fn doc_comment_to_string(doc: &[&str]) -> String {
1350     doc.iter().map(|it| it.strip_prefix(' ').unwrap_or(it)).map(|it| format!("{}\n", it)).collect()
1351 }
1352
1353 #[cfg(test)]
1354 mod tests {
1355     use std::fs;
1356
1357     use test_utils::{ensure_file_contents, project_root};
1358
1359     use super::*;
1360
1361     #[test]
1362     fn generate_package_json_config() {
1363         let s = Config::json_schema();
1364         let schema = format!("{:#}", s);
1365         let mut schema = schema
1366             .trim_start_matches('{')
1367             .trim_end_matches('}')
1368             .replace("  ", "    ")
1369             .replace("\n", "\n            ")
1370             .trim_start_matches('\n')
1371             .trim_end()
1372             .to_string();
1373         schema.push_str(",\n");
1374
1375         // Transform the asciidoc form link to markdown style.
1376         //
1377         // https://link[text] => [text](https://link)
1378         let url_matches = schema.match_indices("https://");
1379         let mut url_offsets = url_matches.map(|(idx, _)| idx).collect::<Vec<usize>>();
1380         url_offsets.reverse();
1381         for idx in url_offsets {
1382             let link = &schema[idx..];
1383             // matching on whitespace to ignore normal links
1384             if let Some(link_end) = link.find(|c| c == ' ' || c == '[') {
1385                 if link.chars().nth(link_end) == Some('[') {
1386                     if let Some(link_text_end) = link.find(']') {
1387                         let link_text = link[link_end..(link_text_end + 1)].to_string();
1388
1389                         schema.replace_range((idx + link_end)..(idx + link_text_end + 1), "");
1390                         schema.insert(idx, '(');
1391                         schema.insert(idx + link_end + 1, ')');
1392                         schema.insert_str(idx, &link_text);
1393                     }
1394                 }
1395             }
1396         }
1397
1398         let package_json_path = project_root().join("editors/code/package.json");
1399         let mut package_json = fs::read_to_string(&package_json_path).unwrap();
1400
1401         let start_marker = "                \"$generated-start\": {},\n";
1402         let end_marker = "                \"$generated-end\": {}\n";
1403
1404         let start = package_json.find(start_marker).unwrap() + start_marker.len();
1405         let end = package_json.find(end_marker).unwrap();
1406
1407         let p = remove_ws(&package_json[start..end]);
1408         let s = remove_ws(&schema);
1409         if !p.contains(&s) {
1410             package_json.replace_range(start..end, &schema);
1411             ensure_file_contents(&package_json_path, &package_json)
1412         }
1413     }
1414
1415     #[test]
1416     fn generate_config_documentation() {
1417         let docs_path = project_root().join("docs/user/generated_config.adoc");
1418         let expected = ConfigData::manual();
1419         ensure_file_contents(&docs_path, &expected);
1420     }
1421
1422     fn remove_ws(text: &str) -> String {
1423         text.replace(char::is_whitespace, "")
1424     }
1425 }