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