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