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