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