]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/config.rs
58539543ee81c39a7e88aff5eca22b4be2e92bb1
[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: WorskpaceSymbolSearchScopeDef = "\"workspace\"",
286         /// Workspace symbol search kind.
287         workspace_symbol_search_kind: WorskpaceSymbolSearchKindDef = "\"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                     desc.scope.map(|scope| match 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                     desc.scope.map(|scope| match 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                 WorskpaceSymbolSearchScopeDef::Workspace => WorkspaceSymbolSearchScope::Workspace,
897                 WorskpaceSymbolSearchScopeDef::WorkspaceAndDependencies => {
898                     WorkspaceSymbolSearchScope::WorkspaceAndDependencies
899                 }
900             },
901             search_kind: match self.data.workspace_symbol_search_kind {
902                 WorskpaceSymbolSearchKindDef::OnlyTypes => WorkspaceSymbolSearchKind::OnlyTypes,
903                 WorskpaceSymbolSearchKindDef::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 enum PostfixSnippetScopeDef {
958     Expr,
959     Type,
960 }
961
962 #[derive(Deserialize, Debug, Clone, Copy)]
963 enum SnippetScopeDef {
964     Expr,
965     Item,
966 }
967
968 #[derive(Deserialize, Debug, Clone)]
969 struct PostfixSnippetDef {
970     #[serde(deserialize_with = "single_or_array")]
971     description: Vec<String>,
972     #[serde(deserialize_with = "single_or_array")]
973     snippet: Vec<String>,
974     #[serde(deserialize_with = "single_or_array")]
975     requires: Vec<String>,
976     scope: Option<PostfixSnippetScopeDef>,
977 }
978
979 #[derive(Deserialize, Debug, Clone)]
980 struct SnippetDef {
981     #[serde(deserialize_with = "single_or_array")]
982     description: Vec<String>,
983     #[serde(deserialize_with = "single_or_array")]
984     snippet: Vec<String>,
985     #[serde(deserialize_with = "single_or_array")]
986     requires: Vec<String>,
987     scope: Option<SnippetScopeDef>,
988 }
989
990 fn single_or_array<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
991 where
992     D: serde::Deserializer<'de>,
993 {
994     struct SingleOrVec;
995
996     impl<'de> serde::de::Visitor<'de> for SingleOrVec {
997         type Value = Vec<String>;
998
999         fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
1000             formatter.write_str("string or array of strings")
1001         }
1002
1003         fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1004         where
1005             E: serde::de::Error,
1006         {
1007             Ok(vec![value.to_owned()])
1008         }
1009
1010         fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1011         where
1012             A: serde::de::SeqAccess<'de>,
1013         {
1014             Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
1015         }
1016     }
1017
1018     deserializer.deserialize_any(SingleOrVec)
1019 }
1020
1021 #[derive(Deserialize, Debug, Clone)]
1022 #[serde(untagged)]
1023 enum ManifestOrProjectJson {
1024     Manifest(PathBuf),
1025     ProjectJson(ProjectJsonData),
1026 }
1027
1028 #[derive(Deserialize, Debug, Clone)]
1029 #[serde(rename_all = "snake_case")]
1030 enum ImportGranularityDef {
1031     Preserve,
1032     #[serde(alias = "none")]
1033     Item,
1034     #[serde(alias = "full")]
1035     Crate,
1036     #[serde(alias = "last")]
1037     Module,
1038 }
1039
1040 #[derive(Deserialize, Debug, Clone)]
1041 #[serde(rename_all = "snake_case")]
1042 enum ImportPrefixDef {
1043     Plain,
1044     #[serde(alias = "self")]
1045     BySelf,
1046     #[serde(alias = "crate")]
1047     ByCrate,
1048 }
1049
1050 #[derive(Deserialize, Debug, Clone)]
1051 #[serde(rename_all = "snake_case")]
1052 enum WorskpaceSymbolSearchScopeDef {
1053     Workspace,
1054     WorkspaceAndDependencies,
1055 }
1056
1057 #[derive(Deserialize, Debug, Clone)]
1058 #[serde(rename_all = "snake_case")]
1059 enum WorskpaceSymbolSearchKindDef {
1060     OnlyTypes,
1061     AllSymbols,
1062 }
1063
1064 macro_rules! _config_data {
1065     (struct $name:ident {
1066         $(
1067             $(#[doc=$doc:literal])*
1068             $field:ident $(| $alias:ident)*: $ty:ty = $default:expr,
1069         )*
1070     }) => {
1071         #[allow(non_snake_case)]
1072         #[derive(Debug, Clone)]
1073         struct $name { $($field: $ty,)* }
1074         impl $name {
1075             fn from_json(mut json: serde_json::Value) -> $name {
1076                 $name {$(
1077                     $field: get_field(
1078                         &mut json,
1079                         stringify!($field),
1080                         None$(.or(Some(stringify!($alias))))*,
1081                         $default,
1082                     ),
1083                 )*}
1084             }
1085
1086             fn json_schema() -> serde_json::Value {
1087                 schema(&[
1088                     $({
1089                         let field = stringify!($field);
1090                         let ty = stringify!($ty);
1091
1092                         (field, ty, &[$($doc),*], $default)
1093                     },)*
1094                 ])
1095             }
1096
1097             #[cfg(test)]
1098             fn manual() -> String {
1099                 manual(&[
1100                     $({
1101                         let field = stringify!($field);
1102                         let ty = stringify!($ty);
1103
1104                         (field, ty, &[$($doc),*], $default)
1105                     },)*
1106                 ])
1107             }
1108         }
1109     };
1110 }
1111 use _config_data as config_data;
1112
1113 fn get_field<T: DeserializeOwned>(
1114     json: &mut serde_json::Value,
1115     field: &'static str,
1116     alias: Option<&'static str>,
1117     default: &str,
1118 ) -> T {
1119     let default = serde_json::from_str(default).unwrap();
1120
1121     // XXX: check alias first, to work-around the VS Code where it pre-fills the
1122     // defaults instead of sending an empty object.
1123     alias
1124         .into_iter()
1125         .chain(iter::once(field))
1126         .find_map(move |field| {
1127             let mut pointer = field.replace('_', "/");
1128             pointer.insert(0, '/');
1129             json.pointer_mut(&pointer).and_then(|it| serde_json::from_value(it.take()).ok())
1130         })
1131         .unwrap_or(default)
1132 }
1133
1134 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
1135     for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
1136         fn key(f: &str) -> &str {
1137             f.splitn(2, '_').next().unwrap()
1138         }
1139         assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
1140     }
1141
1142     let map = fields
1143         .iter()
1144         .map(|(field, ty, doc, default)| {
1145             let name = field.replace("_", ".");
1146             let name = format!("rust-analyzer.{}", name);
1147             let props = field_props(field, ty, doc, default);
1148             (name, props)
1149         })
1150         .collect::<serde_json::Map<_, _>>();
1151     map.into()
1152 }
1153
1154 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
1155     let doc = doc_comment_to_string(doc);
1156     let doc = doc.trim_end_matches('\n');
1157     assert!(
1158         doc.ends_with('.') && doc.starts_with(char::is_uppercase),
1159         "bad docs for {}: {:?}",
1160         field,
1161         doc
1162     );
1163     let default = default.parse::<serde_json::Value>().unwrap();
1164
1165     let mut map = serde_json::Map::default();
1166     macro_rules! set {
1167         ($($key:literal: $value:tt),*$(,)?) => {{$(
1168             map.insert($key.into(), serde_json::json!($value));
1169         )*}};
1170     }
1171     set!("markdownDescription": doc);
1172     set!("default": default);
1173
1174     match ty {
1175         "bool" => set!("type": "boolean"),
1176         "String" => set!("type": "string"),
1177         "Vec<String>" => set! {
1178             "type": "array",
1179             "items": { "type": "string" },
1180         },
1181         "Vec<PathBuf>" => set! {
1182             "type": "array",
1183             "items": { "type": "string" },
1184         },
1185         "FxHashSet<String>" => set! {
1186             "type": "array",
1187             "items": { "type": "string" },
1188             "uniqueItems": true,
1189         },
1190         "FxHashMap<String, String>" => set! {
1191             "type": "object",
1192         },
1193         "Option<usize>" => set! {
1194             "type": ["null", "integer"],
1195             "minimum": 0,
1196         },
1197         "Option<String>" => set! {
1198             "type": ["null", "string"],
1199         },
1200         "Option<PathBuf>" => set! {
1201             "type": ["null", "string"],
1202         },
1203         "Option<bool>" => set! {
1204             "type": ["null", "boolean"],
1205         },
1206         "Option<Vec<String>>" => set! {
1207             "type": ["null", "array"],
1208             "items": { "type": "string" },
1209         },
1210         "MergeBehaviorDef" => set! {
1211             "type": "string",
1212             "enum": ["none", "crate", "module"],
1213             "enumDescriptions": [
1214                 "Do not merge imports at all.",
1215                 "Merge imports from the same crate into a single `use` statement.",
1216                 "Merge imports from the same module into a single `use` statement."
1217             ],
1218         },
1219         "ImportGranularityDef" => set! {
1220             "type": "string",
1221             "enum": ["preserve", "crate", "module", "item"],
1222             "enumDescriptions": [
1223                 "Do not change the granularity of any imports and preserve the original structure written by the developer.",
1224                 "Merge imports from the same crate into a single use statement. Conversely, imports from different crates are split into separate statements.",
1225                 "Merge imports from the same module into a single use statement. Conversely, imports from different modules are split into separate statements.",
1226                 "Flatten imports so that each has its own use statement."
1227             ],
1228         },
1229         "ImportPrefixDef" => set! {
1230             "type": "string",
1231             "enum": [
1232                 "plain",
1233                 "self",
1234                 "crate"
1235             ],
1236             "enumDescriptions": [
1237                 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
1238                 "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.",
1239                 "Force import paths to be absolute by always starting them with `crate` or the extern crate name they come from."
1240             ],
1241         },
1242         "Vec<ManifestOrProjectJson>" => set! {
1243             "type": "array",
1244             "items": { "type": ["string", "object"] },
1245         },
1246         "WorskpaceSymbolSearchScopeDef" => set! {
1247             "type": "string",
1248             "enum": ["workspace", "workspace_and_dependencies"],
1249             "enumDescriptions": [
1250                 "Search in current workspace only",
1251                 "Search in current workspace and dependencies"
1252             ],
1253         },
1254         "WorskpaceSymbolSearchKindDef" => set! {
1255             "type": "string",
1256             "enum": ["only_types", "all_symbols"],
1257             "enumDescriptions": [
1258                 "Search for types only",
1259                 "Search for all symbols kinds"
1260             ],
1261         },
1262         _ => panic!("{}: {}", ty, default),
1263     }
1264
1265     map.into()
1266 }
1267
1268 #[cfg(test)]
1269 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
1270     fields
1271         .iter()
1272         .map(|(field, _ty, doc, default)| {
1273             let name = format!("rust-analyzer.{}", field.replace("_", "."));
1274             let doc = doc_comment_to_string(*doc);
1275             format!("[[{}]]{} (default: `{}`)::\n+\n--\n{}--\n", name, name, default, doc)
1276         })
1277         .collect::<String>()
1278 }
1279
1280 fn doc_comment_to_string(doc: &[&str]) -> String {
1281     doc.iter().map(|it| it.strip_prefix(' ').unwrap_or(it)).map(|it| format!("{}\n", it)).collect()
1282 }
1283
1284 #[cfg(test)]
1285 mod tests {
1286     use std::fs;
1287
1288     use test_utils::{ensure_file_contents, project_root};
1289
1290     use super::*;
1291
1292     #[test]
1293     fn generate_package_json_config() {
1294         let s = Config::json_schema();
1295         let schema = format!("{:#}", s);
1296         let mut schema = schema
1297             .trim_start_matches('{')
1298             .trim_end_matches('}')
1299             .replace("  ", "    ")
1300             .replace("\n", "\n            ")
1301             .trim_start_matches('\n')
1302             .trim_end()
1303             .to_string();
1304         schema.push_str(",\n");
1305
1306         let package_json_path = project_root().join("editors/code/package.json");
1307         let mut package_json = fs::read_to_string(&package_json_path).unwrap();
1308
1309         let start_marker = "                \"$generated-start\": {},\n";
1310         let end_marker = "                \"$generated-end\": {}\n";
1311
1312         let start = package_json.find(start_marker).unwrap() + start_marker.len();
1313         let end = package_json.find(end_marker).unwrap();
1314
1315         let p = remove_ws(&package_json[start..end]);
1316         let s = remove_ws(&schema);
1317         if !p.contains(&s) {
1318             package_json.replace_range(start..end, &schema);
1319             ensure_file_contents(&package_json_path, &package_json)
1320         }
1321     }
1322
1323     #[test]
1324     fn generate_config_documentation() {
1325         let docs_path = project_root().join("docs/user/generated_config.adoc");
1326         let expected = ConfigData::manual();
1327         ensure_file_contents(&docs_path, &expected);
1328     }
1329
1330     fn remove_ws(text: &str) -> String {
1331         text.replace(char::is_whitespace, "")
1332     }
1333 }