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