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