]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/config.rs
feat: Add config to replace specific proc-macros with dummy expanders
[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         procMacro_dummies: FxHashMap<Box<str>, Box<[Box<str>]>>          = "{}",
305
306         /// Command to be executed instead of 'cargo' for runnables.
307         runnables_overrideCargo: Option<String> = "null",
308         /// Additional arguments to be passed to cargo for runnables such as
309         /// tests or binaries. For example, it may be `--release`.
310         runnables_cargoExtraArgs: Vec<String>   = "[]",
311
312         /// Path to the Cargo.toml of the rust compiler workspace, for usage in rustc_private
313         /// projects, or "discover" to try to automatically find it if the `rustc-dev` component
314         /// is installed.
315         ///
316         /// Any project which uses rust-analyzer with the rustcPrivate
317         /// crates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.
318         ///
319         /// This option does not take effect until rust-analyzer is restarted.
320         rustcSource: Option<String> = "null",
321
322         /// Additional arguments to `rustfmt`.
323         rustfmt_extraArgs: Vec<String>               = "[]",
324         /// Advanced option, fully override the command rust-analyzer uses for
325         /// formatting.
326         rustfmt_overrideCommand: Option<Vec<String>> = "null",
327         /// Enables the use of rustfmt's unstable range formatting command for the
328         /// `textDocument/rangeFormatting` request. The rustfmt option is unstable and only
329         /// available on a nightly build.
330         rustfmt_enableRangeFormatting: bool = "false",
331
332         /// Workspace symbol search scope.
333         workspace_symbol_search_scope: WorkspaceSymbolSearchScopeDef = "\"workspace\"",
334         /// Workspace symbol search kind.
335         workspace_symbol_search_kind: WorkspaceSymbolSearchKindDef = "\"only_types\"",
336     }
337 }
338
339 impl Default for ConfigData {
340     fn default() -> Self {
341         ConfigData::from_json(serde_json::Value::Null)
342     }
343 }
344
345 #[derive(Debug, Clone)]
346 pub struct Config {
347     pub caps: lsp_types::ClientCapabilities,
348     data: ConfigData,
349     detached_files: Vec<AbsPathBuf>,
350     pub discovered_projects: Option<Vec<ProjectManifest>>,
351     pub root_path: AbsPathBuf,
352     snippets: Vec<Snippet>,
353 }
354
355 #[derive(Debug, Clone, Eq, PartialEq)]
356 pub enum LinkedProject {
357     ProjectManifest(ProjectManifest),
358     InlineJsonProject(ProjectJson),
359 }
360
361 impl From<ProjectManifest> for LinkedProject {
362     fn from(v: ProjectManifest) -> Self {
363         LinkedProject::ProjectManifest(v)
364     }
365 }
366
367 impl From<ProjectJson> for LinkedProject {
368     fn from(v: ProjectJson) -> Self {
369         LinkedProject::InlineJsonProject(v)
370     }
371 }
372
373 #[derive(Clone, Debug, PartialEq, Eq)]
374 pub struct LensConfig {
375     pub run: bool,
376     pub debug: bool,
377     pub implementations: bool,
378     pub method_refs: bool,
379     pub refs: bool, // for Struct, Enum, Union and Trait
380     pub enum_variant_refs: bool,
381 }
382
383 impl LensConfig {
384     pub fn any(&self) -> bool {
385         self.implementations || self.runnable() || self.references()
386     }
387
388     pub fn none(&self) -> bool {
389         !self.any()
390     }
391
392     pub fn runnable(&self) -> bool {
393         self.run || self.debug
394     }
395
396     pub fn references(&self) -> bool {
397         self.method_refs || self.refs || self.enum_variant_refs
398     }
399 }
400
401 #[derive(Clone, Debug, PartialEq, Eq)]
402 pub struct HoverActionsConfig {
403     pub implementations: bool,
404     pub references: bool,
405     pub run: bool,
406     pub debug: bool,
407     pub goto_type_def: bool,
408 }
409
410 impl HoverActionsConfig {
411     pub const NO_ACTIONS: Self = Self {
412         implementations: false,
413         references: false,
414         run: false,
415         debug: false,
416         goto_type_def: false,
417     };
418
419     pub fn any(&self) -> bool {
420         self.implementations || self.references || self.runnable() || self.goto_type_def
421     }
422
423     pub fn none(&self) -> bool {
424         !self.any()
425     }
426
427     pub fn runnable(&self) -> bool {
428         self.run || self.debug
429     }
430 }
431
432 #[derive(Debug, Clone)]
433 pub struct FilesConfig {
434     pub watcher: FilesWatcher,
435     pub exclude: Vec<AbsPathBuf>,
436 }
437
438 #[derive(Debug, Clone)]
439 pub enum FilesWatcher {
440     Client,
441     Notify,
442 }
443
444 #[derive(Debug, Clone)]
445 pub struct NotificationsConfig {
446     pub cargo_toml_not_found: bool,
447 }
448
449 #[derive(Debug, Clone)]
450 pub enum RustfmtConfig {
451     Rustfmt { extra_args: Vec<String>, enable_range_formatting: bool },
452     CustomCommand { command: String, args: Vec<String> },
453 }
454
455 /// Configuration for runnable items, such as `main` function or tests.
456 #[derive(Debug, Clone)]
457 pub struct RunnablesConfig {
458     /// Custom command to be executed instead of `cargo` for runnables.
459     pub override_cargo: Option<String>,
460     /// Additional arguments for the `cargo`, e.g. `--release`.
461     pub cargo_extra_args: Vec<String>,
462 }
463
464 /// Configuration for workspace symbol search requests.
465 #[derive(Debug, Clone)]
466 pub struct WorkspaceSymbolConfig {
467     /// In what scope should the symbol be searched in.
468     pub search_scope: WorkspaceSymbolSearchScope,
469     /// What kind of symbol is being search for.
470     pub search_kind: WorkspaceSymbolSearchKind,
471 }
472
473 pub struct ClientCommandsConfig {
474     pub run_single: bool,
475     pub debug_single: bool,
476     pub show_reference: bool,
477     pub goto_location: bool,
478     pub trigger_parameter_hints: bool,
479 }
480
481 impl Config {
482     pub fn new(root_path: AbsPathBuf, caps: ClientCapabilities) -> Self {
483         Config {
484             caps,
485             data: ConfigData::default(),
486             detached_files: Vec::new(),
487             discovered_projects: None,
488             root_path,
489             snippets: Default::default(),
490         }
491     }
492     pub fn update(&mut self, mut json: serde_json::Value) {
493         tracing::info!("updating config from JSON: {:#}", json);
494         if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
495             return;
496         }
497         self.detached_files = get_field::<Vec<PathBuf>>(&mut json, "detachedFiles", None, "[]")
498             .into_iter()
499             .map(AbsPathBuf::assert)
500             .collect();
501         self.data = ConfigData::from_json(json);
502         self.snippets.clear();
503         for (name, def) in self.data.completion_snippets.iter() {
504             if def.prefix.is_empty() && def.postfix.is_empty() {
505                 continue;
506             }
507             let scope = match def.scope {
508                 SnippetScopeDef::Expr => SnippetScope::Expr,
509                 SnippetScopeDef::Type => SnippetScope::Type,
510                 SnippetScopeDef::Item => SnippetScope::Item,
511             };
512             match Snippet::new(
513                 &def.prefix,
514                 &def.postfix,
515                 &def.body,
516                 def.description.as_ref().unwrap_or(name),
517                 &def.requires,
518                 scope,
519             ) {
520                 Some(snippet) => self.snippets.push(snippet),
521                 None => tracing::info!("Invalid snippet {}", name),
522             }
523         }
524     }
525
526     pub fn json_schema() -> serde_json::Value {
527         ConfigData::json_schema()
528     }
529 }
530
531 macro_rules! try_ {
532     ($expr:expr) => {
533         || -> _ { Some($expr) }()
534     };
535 }
536 macro_rules! try_or {
537     ($expr:expr, $or:expr) => {
538         try_!($expr).unwrap_or($or)
539     };
540 }
541
542 impl Config {
543     pub fn linked_projects(&self) -> Vec<LinkedProject> {
544         if self.data.linkedProjects.is_empty() {
545             self.discovered_projects
546                 .as_ref()
547                 .into_iter()
548                 .flatten()
549                 .cloned()
550                 .map(LinkedProject::from)
551                 .collect()
552         } else {
553             self.data
554                 .linkedProjects
555                 .iter()
556                 .filter_map(|linked_project| {
557                     let res = match linked_project {
558                         ManifestOrProjectJson::Manifest(it) => {
559                             let path = self.root_path.join(it);
560                             ProjectManifest::from_manifest_file(path)
561                                 .map_err(|e| {
562                                     tracing::error!("failed to load linked project: {}", e)
563                                 })
564                                 .ok()?
565                                 .into()
566                         }
567                         ManifestOrProjectJson::ProjectJson(it) => {
568                             ProjectJson::new(&self.root_path, it.clone()).into()
569                         }
570                     };
571                     Some(res)
572                 })
573                 .collect()
574         }
575     }
576
577     pub fn detached_files(&self) -> &[AbsPathBuf] {
578         &self.detached_files
579     }
580
581     pub fn did_save_text_document_dynamic_registration(&self) -> bool {
582         let caps =
583             try_or!(self.caps.text_document.as_ref()?.synchronization.clone()?, Default::default());
584         caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
585     }
586     pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
587         try_or!(
588             self.caps.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration?,
589             false
590         )
591     }
592
593     pub fn prefill_caches(&self) -> bool {
594         self.data.cache_warmup
595     }
596
597     pub fn location_link(&self) -> bool {
598         try_or!(self.caps.text_document.as_ref()?.definition?.link_support?, false)
599     }
600     pub fn line_folding_only(&self) -> bool {
601         try_or!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?, false)
602     }
603     pub fn hierarchical_symbols(&self) -> bool {
604         try_or!(
605             self.caps
606                 .text_document
607                 .as_ref()?
608                 .document_symbol
609                 .as_ref()?
610                 .hierarchical_document_symbol_support?,
611             false
612         )
613     }
614     pub fn code_action_literals(&self) -> bool {
615         try_!(self
616             .caps
617             .text_document
618             .as_ref()?
619             .code_action
620             .as_ref()?
621             .code_action_literal_support
622             .as_ref()?)
623         .is_some()
624     }
625     pub fn work_done_progress(&self) -> bool {
626         try_or!(self.caps.window.as_ref()?.work_done_progress?, false)
627     }
628     pub fn will_rename(&self) -> bool {
629         try_or!(self.caps.workspace.as_ref()?.file_operations.as_ref()?.will_rename?, false)
630     }
631     pub fn change_annotation_support(&self) -> bool {
632         try_!(self
633             .caps
634             .workspace
635             .as_ref()?
636             .workspace_edit
637             .as_ref()?
638             .change_annotation_support
639             .as_ref()?)
640         .is_some()
641     }
642     pub fn code_action_resolve(&self) -> bool {
643         try_or!(
644             self.caps
645                 .text_document
646                 .as_ref()?
647                 .code_action
648                 .as_ref()?
649                 .resolve_support
650                 .as_ref()?
651                 .properties
652                 .as_slice(),
653             &[]
654         )
655         .iter()
656         .any(|it| it == "edit")
657     }
658     pub fn signature_help_label_offsets(&self) -> bool {
659         try_or!(
660             self.caps
661                 .text_document
662                 .as_ref()?
663                 .signature_help
664                 .as_ref()?
665                 .signature_information
666                 .as_ref()?
667                 .parameter_information
668                 .as_ref()?
669                 .label_offset_support?,
670             false
671         )
672     }
673     pub fn offset_encoding(&self) -> OffsetEncoding {
674         if supports_utf8(&self.caps) {
675             OffsetEncoding::Utf8
676         } else {
677             OffsetEncoding::Utf16
678         }
679     }
680
681     fn experimental(&self, index: &'static str) -> bool {
682         try_or!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?, false)
683     }
684     pub fn code_action_group(&self) -> bool {
685         self.experimental("codeActionGroup")
686     }
687     pub fn server_status_notification(&self) -> bool {
688         self.experimental("serverStatusNotification")
689     }
690
691     pub fn publish_diagnostics(&self) -> bool {
692         self.data.diagnostics_enable
693     }
694     pub fn diagnostics(&self) -> DiagnosticsConfig {
695         DiagnosticsConfig {
696             disable_experimental: !self.data.diagnostics_enableExperimental,
697             disabled: self.data.diagnostics_disabled.clone(),
698         }
699     }
700     pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
701         DiagnosticsMapConfig {
702             remap_prefix: self.data.diagnostics_remapPrefix.clone(),
703             warnings_as_info: self.data.diagnostics_warningsAsInfo.clone(),
704             warnings_as_hint: self.data.diagnostics_warningsAsHint.clone(),
705         }
706     }
707     pub fn lru_capacity(&self) -> Option<usize> {
708         self.data.lruCapacity
709     }
710     pub fn proc_macro_srv(&self) -> Option<(AbsPathBuf, Vec<OsString>)> {
711         if !self.data.procMacro_enable {
712             return None;
713         }
714         let path = match &self.data.procMacro_server {
715             Some(it) => self.root_path.join(it),
716             None => AbsPathBuf::assert(std::env::current_exe().ok()?),
717         };
718         Some((path, vec!["proc-macro".into()]))
719     }
720     pub fn dummy_replacements(&self) -> &FxHashMap<Box<str>, Box<[Box<str>]>> {
721         &self.data.procMacro_dummies
722     }
723     pub fn expand_proc_attr_macros(&self) -> bool {
724         self.data.experimental_procAttrMacros
725     }
726     pub fn files(&self) -> FilesConfig {
727         FilesConfig {
728             watcher: match self.data.files_watcher.as_str() {
729                 "notify" => FilesWatcher::Notify,
730                 "client" if self.did_change_watched_files_dynamic_registration() => {
731                     FilesWatcher::Client
732                 }
733                 _ => FilesWatcher::Notify,
734             },
735             exclude: self.data.files_excludeDirs.iter().map(|it| self.root_path.join(it)).collect(),
736         }
737     }
738     pub fn notifications(&self) -> NotificationsConfig {
739         NotificationsConfig { cargo_toml_not_found: self.data.notifications_cargoTomlNotFound }
740     }
741     pub fn cargo_autoreload(&self) -> bool {
742         self.data.cargo_autoreload
743     }
744     pub fn run_build_scripts(&self) -> bool {
745         self.data.cargo_runBuildScripts || self.data.procMacro_enable
746     }
747     pub fn cargo(&self) -> CargoConfig {
748         let rustc_source = self.data.rustcSource.as_ref().map(|rustc_src| {
749             if rustc_src == "discover" {
750                 RustcSource::Discover
751             } else {
752                 RustcSource::Path(self.root_path.join(rustc_src))
753             }
754         });
755
756         CargoConfig {
757             no_default_features: self.data.cargo_noDefaultFeatures,
758             all_features: self.data.cargo_allFeatures,
759             features: self.data.cargo_features.clone(),
760             target: self.data.cargo_target.clone(),
761             no_sysroot: self.data.cargo_noSysroot,
762             rustc_source,
763             unset_test_crates: UnsetTestCrates::Only(self.data.cargo_unsetTest.clone()),
764             wrap_rustc_in_build_scripts: self.data.cargo_useRustcWrapperForBuildScripts,
765         }
766     }
767
768     pub fn rustfmt(&self) -> RustfmtConfig {
769         match &self.data.rustfmt_overrideCommand {
770             Some(args) if !args.is_empty() => {
771                 let mut args = args.clone();
772                 let command = args.remove(0);
773                 RustfmtConfig::CustomCommand { command, args }
774             }
775             Some(_) | None => RustfmtConfig::Rustfmt {
776                 extra_args: self.data.rustfmt_extraArgs.clone(),
777                 enable_range_formatting: self.data.rustfmt_enableRangeFormatting,
778             },
779         }
780     }
781     pub fn flycheck(&self) -> Option<FlycheckConfig> {
782         if !self.data.checkOnSave_enable {
783             return None;
784         }
785         let flycheck_config = match &self.data.checkOnSave_overrideCommand {
786             Some(args) if !args.is_empty() => {
787                 let mut args = args.clone();
788                 let command = args.remove(0);
789                 FlycheckConfig::CustomCommand { command, args }
790             }
791             Some(_) | None => FlycheckConfig::CargoCommand {
792                 command: self.data.checkOnSave_command.clone(),
793                 target_triple: self
794                     .data
795                     .checkOnSave_target
796                     .clone()
797                     .or_else(|| self.data.cargo_target.clone()),
798                 all_targets: self.data.checkOnSave_allTargets,
799                 no_default_features: self
800                     .data
801                     .checkOnSave_noDefaultFeatures
802                     .unwrap_or(self.data.cargo_noDefaultFeatures),
803                 all_features: self
804                     .data
805                     .checkOnSave_allFeatures
806                     .unwrap_or(self.data.cargo_allFeatures),
807                 features: self
808                     .data
809                     .checkOnSave_features
810                     .clone()
811                     .unwrap_or_else(|| self.data.cargo_features.clone()),
812                 extra_args: self.data.checkOnSave_extraArgs.clone(),
813             },
814         };
815         Some(flycheck_config)
816     }
817     pub fn runnables(&self) -> RunnablesConfig {
818         RunnablesConfig {
819             override_cargo: self.data.runnables_overrideCargo.clone(),
820             cargo_extra_args: self.data.runnables_cargoExtraArgs.clone(),
821         }
822     }
823     pub fn inlay_hints(&self) -> InlayHintsConfig {
824         InlayHintsConfig {
825             type_hints: self.data.inlayHints_typeHints,
826             parameter_hints: self.data.inlayHints_parameterHints,
827             chaining_hints: self.data.inlayHints_chainingHints,
828             hide_named_constructor_hints: self.data.inlayHints_hideNamedConstructorHints,
829             max_length: self.data.inlayHints_maxLength,
830         }
831     }
832     fn insert_use_config(&self) -> InsertUseConfig {
833         InsertUseConfig {
834             granularity: match self.data.assist_importGranularity {
835                 ImportGranularityDef::Preserve => ImportGranularity::Preserve,
836                 ImportGranularityDef::Item => ImportGranularity::Item,
837                 ImportGranularityDef::Crate => ImportGranularity::Crate,
838                 ImportGranularityDef::Module => ImportGranularity::Module,
839             },
840             enforce_granularity: self.data.assist_importEnforceGranularity,
841             prefix_kind: match self.data.assist_importPrefix {
842                 ImportPrefixDef::Plain => PrefixKind::Plain,
843                 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
844                 ImportPrefixDef::BySelf => PrefixKind::BySelf,
845             },
846             group: self.data.assist_importGroup,
847             skip_glob_imports: !self.data.assist_allowMergingIntoGlobImports,
848         }
849     }
850     pub fn completion(&self) -> CompletionConfig {
851         CompletionConfig {
852             enable_postfix_completions: self.data.completion_postfix_enable,
853             enable_imports_on_the_fly: self.data.completion_autoimport_enable
854                 && completion_item_edit_resolve(&self.caps),
855             enable_self_on_the_fly: self.data.completion_autoself_enable,
856             add_call_parenthesis: self.data.completion_addCallParenthesis,
857             add_call_argument_snippets: self.data.completion_addCallArgumentSnippets,
858             insert_use: self.insert_use_config(),
859             snippet_cap: SnippetCap::new(try_or!(
860                 self.caps
861                     .text_document
862                     .as_ref()?
863                     .completion
864                     .as_ref()?
865                     .completion_item
866                     .as_ref()?
867                     .snippet_support?,
868                 false
869             )),
870             snippets: self.snippets.clone(),
871         }
872     }
873     pub fn assist(&self) -> AssistConfig {
874         AssistConfig {
875             snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
876             allowed: None,
877             insert_use: self.insert_use_config(),
878         }
879     }
880     pub fn join_lines(&self) -> JoinLinesConfig {
881         JoinLinesConfig {
882             join_else_if: self.data.joinLines_joinElseIf,
883             remove_trailing_comma: self.data.joinLines_removeTrailingComma,
884             unwrap_trivial_blocks: self.data.joinLines_unwrapTrivialBlock,
885             join_assignments: self.data.joinLines_joinAssignments,
886         }
887     }
888     pub fn call_info_full(&self) -> bool {
889         self.data.callInfo_full
890     }
891     pub fn lens(&self) -> LensConfig {
892         LensConfig {
893             run: self.data.lens_enable && self.data.lens_run,
894             debug: self.data.lens_enable && self.data.lens_debug,
895             implementations: self.data.lens_enable && self.data.lens_implementations,
896             method_refs: self.data.lens_enable && self.data.lens_methodReferences,
897             refs: self.data.lens_enable && self.data.lens_references,
898             enum_variant_refs: self.data.lens_enable && self.data.lens_enumVariantReferences,
899         }
900     }
901     pub fn hover_actions(&self) -> HoverActionsConfig {
902         let enable = self.experimental("hoverActions") && self.data.hoverActions_enable;
903         HoverActionsConfig {
904             implementations: enable && self.data.hoverActions_implementations,
905             references: enable && self.data.hoverActions_references,
906             run: enable && self.data.hoverActions_run,
907             debug: enable && self.data.hoverActions_debug,
908             goto_type_def: enable && self.data.hoverActions_gotoTypeDef,
909         }
910     }
911     pub fn highlighting_strings(&self) -> bool {
912         self.data.highlighting_strings
913     }
914     pub fn hover(&self) -> HoverConfig {
915         HoverConfig {
916             links_in_hover: self.data.hover_linksInHover,
917             documentation: self.data.hover_documentation.then(|| {
918                 let is_markdown = try_or!(
919                     self.caps
920                         .text_document
921                         .as_ref()?
922                         .hover
923                         .as_ref()?
924                         .content_format
925                         .as_ref()?
926                         .as_slice(),
927                     &[]
928                 )
929                 .contains(&MarkupKind::Markdown);
930                 if is_markdown {
931                     HoverDocFormat::Markdown
932                 } else {
933                     HoverDocFormat::PlainText
934                 }
935             }),
936         }
937     }
938
939     pub fn workspace_symbol(&self) -> WorkspaceSymbolConfig {
940         WorkspaceSymbolConfig {
941             search_scope: match self.data.workspace_symbol_search_scope {
942                 WorkspaceSymbolSearchScopeDef::Workspace => WorkspaceSymbolSearchScope::Workspace,
943                 WorkspaceSymbolSearchScopeDef::WorkspaceAndDependencies => {
944                     WorkspaceSymbolSearchScope::WorkspaceAndDependencies
945                 }
946             },
947             search_kind: match self.data.workspace_symbol_search_kind {
948                 WorkspaceSymbolSearchKindDef::OnlyTypes => WorkspaceSymbolSearchKind::OnlyTypes,
949                 WorkspaceSymbolSearchKindDef::AllSymbols => WorkspaceSymbolSearchKind::AllSymbols,
950             },
951         }
952     }
953
954     pub fn semantic_tokens_refresh(&self) -> bool {
955         try_or!(self.caps.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support?, false)
956     }
957     pub fn code_lens_refresh(&self) -> bool {
958         try_or!(self.caps.workspace.as_ref()?.code_lens.as_ref()?.refresh_support?, false)
959     }
960     pub fn insert_replace_support(&self) -> bool {
961         try_or!(
962             self.caps
963                 .text_document
964                 .as_ref()?
965                 .completion
966                 .as_ref()?
967                 .completion_item
968                 .as_ref()?
969                 .insert_replace_support?,
970             false
971         )
972     }
973     pub fn client_commands(&self) -> ClientCommandsConfig {
974         let commands =
975             try_or!(self.caps.experimental.as_ref()?.get("commands")?, &serde_json::Value::Null);
976         let commands: Option<lsp_ext::ClientCommandOptions> =
977             serde_json::from_value(commands.clone()).ok();
978         let force = commands.is_none() && self.data.lens_forceCustomCommands;
979         let commands = commands.map(|it| it.commands).unwrap_or_default();
980
981         let get = |name: &str| commands.iter().any(|it| it == name) || force;
982
983         ClientCommandsConfig {
984             run_single: get("rust-analyzer.runSingle"),
985             debug_single: get("rust-analyzer.debugSingle"),
986             show_reference: get("rust-analyzer.showReferences"),
987             goto_location: get("rust-analyzer.gotoLocation"),
988             trigger_parameter_hints: get("editor.action.triggerParameterHints"),
989         }
990     }
991
992     pub fn highlight_related(&self) -> HighlightRelatedConfig {
993         HighlightRelatedConfig {
994             references: self.data.highlightRelated_references,
995             break_points: self.data.highlightRelated_breakPoints,
996             exit_points: self.data.highlightRelated_exitPoints,
997             yield_points: self.data.highlightRelated_yieldPoints,
998         }
999     }
1000 }
1001
1002 #[derive(Deserialize, Debug, Clone, Copy)]
1003 #[serde(rename_all = "snake_case")]
1004 enum SnippetScopeDef {
1005     Expr,
1006     Item,
1007     Type,
1008 }
1009
1010 impl Default for SnippetScopeDef {
1011     fn default() -> Self {
1012         SnippetScopeDef::Expr
1013     }
1014 }
1015
1016 #[derive(Deserialize, Debug, Clone, Default)]
1017 #[serde(default)]
1018 struct SnippetDef {
1019     #[serde(deserialize_with = "single_or_array")]
1020     prefix: Vec<String>,
1021     #[serde(deserialize_with = "single_or_array")]
1022     postfix: Vec<String>,
1023     description: Option<String>,
1024     #[serde(deserialize_with = "single_or_array")]
1025     body: Vec<String>,
1026     #[serde(deserialize_with = "single_or_array")]
1027     requires: Vec<String>,
1028     scope: SnippetScopeDef,
1029 }
1030
1031 fn single_or_array<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
1032 where
1033     D: serde::Deserializer<'de>,
1034 {
1035     struct SingleOrVec;
1036
1037     impl<'de> serde::de::Visitor<'de> for SingleOrVec {
1038         type Value = Vec<String>;
1039
1040         fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
1041             formatter.write_str("string or array of strings")
1042         }
1043
1044         fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1045         where
1046             E: serde::de::Error,
1047         {
1048             Ok(vec![value.to_owned()])
1049         }
1050
1051         fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1052         where
1053             A: serde::de::SeqAccess<'de>,
1054         {
1055             Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
1056         }
1057     }
1058
1059     deserializer.deserialize_any(SingleOrVec)
1060 }
1061
1062 #[derive(Deserialize, Debug, Clone)]
1063 #[serde(untagged)]
1064 enum ManifestOrProjectJson {
1065     Manifest(PathBuf),
1066     ProjectJson(ProjectJsonData),
1067 }
1068
1069 #[derive(Deserialize, Debug, Clone)]
1070 #[serde(rename_all = "snake_case")]
1071 enum ImportGranularityDef {
1072     Preserve,
1073     #[serde(alias = "none")]
1074     Item,
1075     #[serde(alias = "full")]
1076     Crate,
1077     #[serde(alias = "last")]
1078     Module,
1079 }
1080
1081 #[derive(Deserialize, Debug, Clone)]
1082 #[serde(rename_all = "snake_case")]
1083 enum ImportPrefixDef {
1084     Plain,
1085     #[serde(alias = "self")]
1086     BySelf,
1087     #[serde(alias = "crate")]
1088     ByCrate,
1089 }
1090
1091 #[derive(Deserialize, Debug, Clone)]
1092 #[serde(rename_all = "snake_case")]
1093 enum WorkspaceSymbolSearchScopeDef {
1094     Workspace,
1095     WorkspaceAndDependencies,
1096 }
1097
1098 #[derive(Deserialize, Debug, Clone)]
1099 #[serde(rename_all = "snake_case")]
1100 enum WorkspaceSymbolSearchKindDef {
1101     OnlyTypes,
1102     AllSymbols,
1103 }
1104
1105 macro_rules! _config_data {
1106     (struct $name:ident {
1107         $(
1108             $(#[doc=$doc:literal])*
1109             $field:ident $(| $alias:ident)*: $ty:ty = $default:expr,
1110         )*
1111     }) => {
1112         #[allow(non_snake_case)]
1113         #[derive(Debug, Clone)]
1114         struct $name { $($field: $ty,)* }
1115         impl $name {
1116             fn from_json(mut json: serde_json::Value) -> $name {
1117                 $name {$(
1118                     $field: get_field(
1119                         &mut json,
1120                         stringify!($field),
1121                         None$(.or(Some(stringify!($alias))))*,
1122                         $default,
1123                     ),
1124                 )*}
1125             }
1126
1127             fn json_schema() -> serde_json::Value {
1128                 schema(&[
1129                     $({
1130                         let field = stringify!($field);
1131                         let ty = stringify!($ty);
1132
1133                         (field, ty, &[$($doc),*], $default)
1134                     },)*
1135                 ])
1136             }
1137
1138             #[cfg(test)]
1139             fn manual() -> String {
1140                 manual(&[
1141                     $({
1142                         let field = stringify!($field);
1143                         let ty = stringify!($ty);
1144
1145                         (field, ty, &[$($doc),*], $default)
1146                     },)*
1147                 ])
1148             }
1149         }
1150     };
1151 }
1152 use _config_data as config_data;
1153
1154 fn get_field<T: DeserializeOwned>(
1155     json: &mut serde_json::Value,
1156     field: &'static str,
1157     alias: Option<&'static str>,
1158     default: &str,
1159 ) -> T {
1160     let default = serde_json::from_str(default).unwrap();
1161
1162     // XXX: check alias first, to work-around the VS Code where it pre-fills the
1163     // defaults instead of sending an empty object.
1164     alias
1165         .into_iter()
1166         .chain(iter::once(field))
1167         .find_map(move |field| {
1168             let mut pointer = field.replace('_', "/");
1169             pointer.insert(0, '/');
1170             json.pointer_mut(&pointer).and_then(|it| serde_json::from_value(it.take()).ok())
1171         })
1172         .unwrap_or(default)
1173 }
1174
1175 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
1176     for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
1177         fn key(f: &str) -> &str {
1178             f.splitn(2, '_').next().unwrap()
1179         }
1180         assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
1181     }
1182
1183     let map = fields
1184         .iter()
1185         .map(|(field, ty, doc, default)| {
1186             let name = field.replace("_", ".");
1187             let name = format!("rust-analyzer.{}", name);
1188             let props = field_props(field, ty, doc, default);
1189             (name, props)
1190         })
1191         .collect::<serde_json::Map<_, _>>();
1192     map.into()
1193 }
1194
1195 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
1196     let doc = doc_comment_to_string(doc);
1197     let doc = doc.trim_end_matches('\n');
1198     assert!(
1199         doc.ends_with('.') && doc.starts_with(char::is_uppercase),
1200         "bad docs for {}: {:?}",
1201         field,
1202         doc
1203     );
1204     let default = default.parse::<serde_json::Value>().unwrap();
1205
1206     let mut map = serde_json::Map::default();
1207     macro_rules! set {
1208         ($($key:literal: $value:tt),*$(,)?) => {{$(
1209             map.insert($key.into(), serde_json::json!($value));
1210         )*}};
1211     }
1212     set!("markdownDescription": doc);
1213     set!("default": default);
1214
1215     match ty {
1216         "bool" => set!("type": "boolean"),
1217         "String" => set!("type": "string"),
1218         "Vec<String>" => set! {
1219             "type": "array",
1220             "items": { "type": "string" },
1221         },
1222         "Vec<PathBuf>" => set! {
1223             "type": "array",
1224             "items": { "type": "string" },
1225         },
1226         "FxHashSet<String>" => set! {
1227             "type": "array",
1228             "items": { "type": "string" },
1229             "uniqueItems": true,
1230         },
1231         "FxHashMap<String, SnippetDef>" => set! {
1232             "type": "object",
1233         },
1234         "FxHashMap<String, String>" => set! {
1235             "type": "object",
1236         },
1237         "Option<usize>" => set! {
1238             "type": ["null", "integer"],
1239             "minimum": 0,
1240         },
1241         "Option<String>" => set! {
1242             "type": ["null", "string"],
1243         },
1244         "Option<PathBuf>" => set! {
1245             "type": ["null", "string"],
1246         },
1247         "Option<bool>" => set! {
1248             "type": ["null", "boolean"],
1249         },
1250         "Option<Vec<String>>" => set! {
1251             "type": ["null", "array"],
1252             "items": { "type": "string" },
1253         },
1254         "MergeBehaviorDef" => set! {
1255             "type": "string",
1256             "enum": ["none", "crate", "module"],
1257             "enumDescriptions": [
1258                 "Do not merge imports at all.",
1259                 "Merge imports from the same crate into a single `use` statement.",
1260                 "Merge imports from the same module into a single `use` statement."
1261             ],
1262         },
1263         "ImportGranularityDef" => set! {
1264             "type": "string",
1265             "enum": ["preserve", "crate", "module", "item"],
1266             "enumDescriptions": [
1267                 "Do not change the granularity of any imports and preserve the original structure written by the developer.",
1268                 "Merge imports from the same crate into a single use statement. Conversely, imports from different crates are split into separate statements.",
1269                 "Merge imports from the same module into a single use statement. Conversely, imports from different modules are split into separate statements.",
1270                 "Flatten imports so that each has its own use statement."
1271             ],
1272         },
1273         "ImportPrefixDef" => set! {
1274             "type": "string",
1275             "enum": [
1276                 "plain",
1277                 "self",
1278                 "crate"
1279             ],
1280             "enumDescriptions": [
1281                 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
1282                 "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.",
1283                 "Force import paths to be absolute by always starting them with `crate` or the extern crate name they come from."
1284             ],
1285         },
1286         "Vec<ManifestOrProjectJson>" => set! {
1287             "type": "array",
1288             "items": { "type": ["string", "object"] },
1289         },
1290         "WorkspaceSymbolSearchScopeDef" => set! {
1291             "type": "string",
1292             "enum": ["workspace", "workspace_and_dependencies"],
1293             "enumDescriptions": [
1294                 "Search in current workspace only",
1295                 "Search in current workspace and dependencies"
1296             ],
1297         },
1298         "WorkspaceSymbolSearchKindDef" => set! {
1299             "type": "string",
1300             "enum": ["only_types", "all_symbols"],
1301             "enumDescriptions": [
1302                 "Search for types only",
1303                 "Search for all symbols kinds"
1304             ],
1305         },
1306         _ => panic!("{}: {}", ty, default),
1307     }
1308
1309     map.into()
1310 }
1311
1312 #[cfg(test)]
1313 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
1314     fields
1315         .iter()
1316         .map(|(field, _ty, doc, default)| {
1317             let name = format!("rust-analyzer.{}", field.replace("_", "."));
1318             let doc = doc_comment_to_string(*doc);
1319             format!("[[{}]]{} (default: `{}`)::\n+\n--\n{}--\n", name, name, default, doc)
1320         })
1321         .collect::<String>()
1322 }
1323
1324 fn doc_comment_to_string(doc: &[&str]) -> String {
1325     doc.iter().map(|it| it.strip_prefix(' ').unwrap_or(it)).map(|it| format!("{}\n", it)).collect()
1326 }
1327
1328 #[cfg(test)]
1329 mod tests {
1330     use std::fs;
1331
1332     use test_utils::{ensure_file_contents, project_root};
1333
1334     use super::*;
1335
1336     #[test]
1337     fn generate_package_json_config() {
1338         let s = Config::json_schema();
1339         let schema = format!("{:#}", s);
1340         let mut schema = schema
1341             .trim_start_matches('{')
1342             .trim_end_matches('}')
1343             .replace("  ", "    ")
1344             .replace("\n", "\n            ")
1345             .trim_start_matches('\n')
1346             .trim_end()
1347             .to_string();
1348         schema.push_str(",\n");
1349
1350         // Transform the asciidoc form link to markdown style.
1351         //
1352         // https://link[text] => [text](https://link)
1353         let url_matches = schema.match_indices("https://");
1354         let mut url_offsets = url_matches.map(|(idx, _)| idx).collect::<Vec<usize>>();
1355         url_offsets.reverse();
1356         for idx in url_offsets {
1357             let link = &schema[idx..];
1358             // matching on whitespace to ignore normal links
1359             if let Some(link_end) = link.find(|c| c == ' ' || c == '[') {
1360                 if link.chars().nth(link_end) == Some('[') {
1361                     if let Some(link_text_end) = link.find(']') {
1362                         let link_text = link[link_end..(link_text_end + 1)].to_string();
1363
1364                         schema.replace_range((idx + link_end)..(idx + link_text_end + 1), "");
1365                         schema.insert(idx, '(');
1366                         schema.insert(idx + link_end + 1, ')');
1367                         schema.insert_str(idx, &link_text);
1368                     }
1369                 }
1370             }
1371         }
1372
1373         let package_json_path = project_root().join("editors/code/package.json");
1374         let mut package_json = fs::read_to_string(&package_json_path).unwrap();
1375
1376         let start_marker = "                \"$generated-start\": {},\n";
1377         let end_marker = "                \"$generated-end\": {}\n";
1378
1379         let start = package_json.find(start_marker).unwrap() + start_marker.len();
1380         let end = package_json.find(end_marker).unwrap();
1381
1382         let p = remove_ws(&package_json[start..end]);
1383         let s = remove_ws(&schema);
1384         if !p.contains(&s) {
1385             package_json.replace_range(start..end, &schema);
1386             ensure_file_contents(&package_json_path, &package_json)
1387         }
1388     }
1389
1390     #[test]
1391     fn generate_config_documentation() {
1392         let docs_path = project_root().join("docs/user/generated_config.adoc");
1393         let expected = ConfigData::manual();
1394         ensure_file_contents(&docs_path, &expected);
1395     }
1396
1397     fn remove_ws(text: &str) -> String {
1398         text.replace(char::is_whitespace, "")
1399     }
1400 }