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