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