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