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