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