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