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