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