1 //! Config used by the language server.
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.
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.
10 use std::{ffi::OsString, iter, path::PathBuf};
12 use flycheck::FlycheckConfig;
14 AssistConfig, CompletionConfig, DiagnosticsConfig, HighlightRelatedConfig, HoverConfig,
15 HoverDocFormat, InlayHintsConfig, JoinLinesConfig, Snippet, SnippetScope,
17 use ide_db::helpers::{
18 insert_use::{ImportGranularity, InsertUseConfig, PrefixKind},
21 use lsp_types::{ClientCapabilities, MarkupKind};
23 CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest, RustcSource, UnsetTestCrates,
25 use rustc_hash::{FxHashMap, FxHashSet};
26 use serde::{de::DeserializeOwned, Deserialize};
30 caps::completion_item_edit_resolve,
31 diagnostics::DiagnosticsMapConfig,
32 line_index::OffsetEncoding,
33 lsp_ext::supports_utf8,
34 lsp_ext::WorkspaceSymbolSearchScope,
35 lsp_ext::{self, WorkspaceSymbolSearchKind},
38 // Defines the server-side configuration of the rust-analyzer. We generate
39 // *parts* of VS Code's `package.json` config from this.
41 // However, editor specific config, which the server doesn't know about, should
42 // be specified directly in `package.json`.
44 // To deprecate an option by replacing it with another name use `new_name | `old_name` so that we keep
45 // parsing the old name.
48 /// How imports should be grouped into use statements.
49 assist_importGranularity |
50 assist_importMergeBehavior |
51 assist_importMergeBehaviour: ImportGranularityDef = "\"crate\"",
52 /// Whether to enforce the import granularity setting for all files. If set to false rust-analyzer will try to keep import styles consistent per file.
53 assist_importEnforceGranularity: bool = "false",
54 /// The path structure for newly inserted paths to use.
55 assist_importPrefix: ImportPrefixDef = "\"plain\"",
56 /// Group inserted imports by the https://rust-analyzer.github.io/manual.html#auto-import[following order]. Groups are separated by newlines.
57 assist_importGroup: bool = "true",
58 /// Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`.
59 assist_allowMergingIntoGlobImports: bool = "true",
61 /// Show function name and docs in parameter hints.
62 callInfo_full: bool = "true",
64 /// Automatically refresh project info via `cargo metadata` on
65 /// `Cargo.toml` changes.
66 cargo_autoreload: bool = "true",
67 /// Activate all available features (`--all-features`).
68 cargo_allFeatures: bool = "false",
69 /// Unsets `#[cfg(test)]` for the specified crates.
70 cargo_unsetTest: Vec<String> = "[\"core\"]",
71 /// List of features to activate.
72 cargo_features: Vec<String> = "[]",
73 /// Run build scripts (`build.rs`) for more precise code analysis.
74 cargo_runBuildScripts |
75 cargo_loadOutDirsFromCheck: bool = "true",
76 /// Use `RUSTC_WRAPPER=rust-analyzer` when running build scripts to
77 /// avoid compiling unnecessary things.
78 cargo_useRustcWrapperForBuildScripts: bool = "true",
79 /// Do not activate the `default` feature.
80 cargo_noDefaultFeatures: bool = "false",
81 /// Compilation target (target triple).
82 cargo_target: Option<String> = "null",
83 /// Internal config for debugging, disables loading of sysroot crates.
84 cargo_noSysroot: bool = "false",
86 /// Run specified `cargo check` command for diagnostics on save.
87 checkOnSave_enable: bool = "true",
88 /// Check with all features (`--all-features`).
89 /// Defaults to `#rust-analyzer.cargo.allFeatures#`.
90 checkOnSave_allFeatures: Option<bool> = "null",
91 /// Check all targets and tests (`--all-targets`).
92 checkOnSave_allTargets: bool = "true",
93 /// Cargo command to use for `cargo check`.
94 checkOnSave_command: String = "\"check\"",
95 /// Do not activate the `default` feature.
96 checkOnSave_noDefaultFeatures: Option<bool> = "null",
97 /// Check for a specific target. Defaults to
98 /// `#rust-analyzer.cargo.target#`.
99 checkOnSave_target: Option<String> = "null",
100 /// Extra arguments for `cargo check`.
101 checkOnSave_extraArgs: Vec<String> = "[]",
102 /// List of features to activate. Defaults to
103 /// `#rust-analyzer.cargo.features#`.
104 checkOnSave_features: Option<Vec<String>> = "null",
105 /// Advanced option, fully override the command rust-analyzer uses for
106 /// checking. The command should include `--message-format=json` or
108 checkOnSave_overrideCommand: Option<Vec<String>> = "null",
110 /// Whether to add argument snippets when completing functions.
111 /// Only applies when `#rust-analyzer.completion.addCallParenthesis#` is set.
112 completion_addCallArgumentSnippets: bool = "true",
113 /// Whether to add parenthesis when completing functions.
114 completion_addCallParenthesis: bool = "true",
115 /// Custom completion snippets.
116 completion_snippets: FxHashMap<String, SnippetDef> = "{}",
117 /// Whether to show postfix snippets like `dbg`, `if`, `not`, etc.
118 completion_postfix_enable: bool = "true",
119 /// Toggles the additional completions that automatically add imports when completed.
120 /// Note that your client must specify the `additionalTextEdits` LSP client capability to truly have this feature enabled.
121 completion_autoimport_enable: bool = "true",
122 /// Toggles the additional completions that automatically show method calls and field accesses
123 /// with `self` prefixed to them when inside a method.
124 completion_autoself_enable: bool = "true",
126 /// Whether to show native rust-analyzer diagnostics.
127 diagnostics_enable: bool = "true",
128 /// Whether to show experimental rust-analyzer diagnostics that might
129 /// have more false positives than usual.
130 diagnostics_enableExperimental: bool = "true",
131 /// List of rust-analyzer diagnostics to disable.
132 diagnostics_disabled: FxHashSet<String> = "[]",
133 /// Map of prefixes to be substituted when parsing diagnostic file paths.
134 /// This should be the reverse mapping of what is passed to `rustc` as `--remap-path-prefix`.
135 diagnostics_remapPrefix: FxHashMap<String, String> = "{}",
136 /// List of warnings that should be displayed with hint severity.
138 /// The warnings will be indicated by faded text or three dots in code
139 /// and will not show up in the `Problems Panel`.
140 diagnostics_warningsAsHint: Vec<String> = "[]",
141 /// List of warnings that should be displayed with info severity.
143 /// The warnings will be indicated by a blue squiggly underline in code
144 /// and a blue icon in the `Problems Panel`.
145 diagnostics_warningsAsInfo: Vec<String> = "[]",
147 /// Expand attribute macros.
148 experimental_procAttrMacros: bool = "true",
150 /// Controls file watching implementation.
151 files_watcher: String = "\"client\"",
152 /// These directories will be ignored by rust-analyzer. They are
153 /// relative to the workspace root, and globs are not supported. You may
154 /// also need to add the folders to Code's `files.watcherExclude`.
155 files_excludeDirs: Vec<PathBuf> = "[]",
157 /// Enables highlighting of related references while hovering your mouse above any identifier.
158 highlightRelated_references: bool = "true",
159 /// Enables highlighting of all exit points while hovering your mouse above any `return`, `?`, or return type arrow (`->`).
160 highlightRelated_exitPoints: bool = "true",
161 /// Enables highlighting of related references while hovering your mouse `break`, `loop`, `while`, or `for` keywords.
162 highlightRelated_breakPoints: bool = "true",
163 /// Enables highlighting of all break points for a loop or block context while hovering your mouse above any `async` or `await` keywords.
164 highlightRelated_yieldPoints: bool = "true",
166 /// Use semantic tokens for strings.
168 /// In some editors (e.g. vscode) semantic tokens override other highlighting grammars.
169 /// By disabling semantic tokens for strings, other grammars can be used to highlight
171 highlighting_strings: bool = "true",
173 /// Whether to show documentation on hover.
174 hover_documentation: bool = "true",
175 /// Use markdown syntax for links in hover.
177 hoverActions_linksInHover: bool = "true",
179 /// Whether to show `Debug` action. Only applies when
180 /// `#rust-analyzer.hoverActions.enable#` is set.
181 hoverActions_debug: bool = "true",
182 /// Whether to show HoverActions in Rust files.
183 hoverActions_enable: bool = "true",
184 /// Whether to show `Go to Type Definition` action. Only applies when
185 /// `#rust-analyzer.hoverActions.enable#` is set.
186 hoverActions_gotoTypeDef: bool = "true",
187 /// Whether to show `Implementations` action. Only applies when
188 /// `#rust-analyzer.hoverActions.enable#` is set.
189 hoverActions_implementations: bool = "true",
190 /// Whether to show `References` action. Only applies when
191 /// `#rust-analyzer.hoverActions.enable#` is set.
192 hoverActions_references: bool = "false",
193 /// Whether to show `Run` action. Only applies when
194 /// `#rust-analyzer.hoverActions.enable#` is set.
195 hoverActions_run: bool = "true",
197 /// Whether to show inlay type hints for method chains.
198 inlayHints_chainingHints: bool = "true",
199 /// Maximum length for inlay hints. Set to null to have an unlimited length.
200 inlayHints_maxLength: Option<usize> = "25",
201 /// Whether to show function parameter name inlay hints at the call
203 inlayHints_parameterHints: bool = "true",
204 /// Whether to show inlay type hints for variables.
205 inlayHints_typeHints: bool = "true",
207 /// Join lines inserts else between consecutive ifs.
208 joinLines_joinElseIf: bool = "true",
209 /// Join lines removes trailing commas.
210 joinLines_removeTrailingComma: bool = "true",
211 /// Join lines unwraps trivial blocks.
212 joinLines_unwrapTrivialBlock: bool = "true",
213 /// Join lines merges consecutive declaration and initialization of an assignment.
214 joinLines_joinAssignments: bool = "true",
216 /// Whether to show `Debug` lens. Only applies when
217 /// `#rust-analyzer.lens.enable#` is set.
218 lens_debug: bool = "true",
219 /// Whether to show CodeLens in Rust files.
220 lens_enable: bool = "true",
221 /// Whether to show `Implementations` lens. Only applies when
222 /// `#rust-analyzer.lens.enable#` is set.
223 lens_implementations: bool = "true",
224 /// Whether to show `Run` lens. Only applies when
225 /// `#rust-analyzer.lens.enable#` is set.
226 lens_run: bool = "true",
227 /// Whether to show `Method References` lens. Only applies when
228 /// `#rust-analyzer.lens.enable#` is set.
229 lens_methodReferences: bool = "false",
230 /// Whether to show `References` lens for Struct, Enum, Union and Trait.
231 /// Only applies when `#rust-analyzer.lens.enable#` is set.
232 lens_references: bool = "false",
233 /// Whether to show `References` lens for Enum Variants.
234 /// Only applies when `#rust-analyzer.lens.enable#` is set.
235 lens_enumVariantReferences: bool = "false",
236 /// Internal config: use custom client-side commands even when the
237 /// client doesn't set the corresponding capability.
238 lens_forceCustomCommands: bool = "true",
240 /// Disable project auto-discovery in favor of explicitly specified set
243 /// Elements must be paths pointing to `Cargo.toml`,
244 /// `rust-project.json`, or JSON objects in `rust-project.json` format.
245 linkedProjects: Vec<ManifestOrProjectJson> = "[]",
247 /// Number of syntax trees rust-analyzer keeps in memory. Defaults to 128.
248 lruCapacity: Option<usize> = "null",
250 /// Whether to show `can't find Cargo.toml` error message.
251 notifications_cargoTomlNotFound: bool = "true",
253 /// Enable support for procedural macros, implies `#rust-analyzer.cargo.runBuildScripts#`.
254 procMacro_enable: bool = "true",
255 /// Internal config, path to proc-macro server executable (typically,
256 /// this is rust-analyzer itself, but we override this in tests).
257 procMacro_server: Option<PathBuf> = "null",
259 /// Command to be executed instead of 'cargo' for runnables.
260 runnables_overrideCargo: Option<String> = "null",
261 /// Additional arguments to be passed to cargo for runnables such as
262 /// tests or binaries. For example, it may be `--release`.
263 runnables_cargoExtraArgs: Vec<String> = "[]",
265 /// Path to the Cargo.toml of the rust compiler workspace, for usage in rustc_private
266 /// projects, or "discover" to try to automatically find it.
268 /// Any project which uses rust-analyzer with the rustcPrivate
269 /// crates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.
271 /// This option is not reloaded automatically; you must restart rust-analyzer for it to take effect.
272 rustcSource: Option<String> = "null",
274 /// Additional arguments to `rustfmt`.
275 rustfmt_extraArgs: Vec<String> = "[]",
276 /// Advanced option, fully override the command rust-analyzer uses for
278 rustfmt_overrideCommand: Option<Vec<String>> = "null",
279 /// Enables the use of rustfmt's unstable range formatting command for the
280 /// `textDocument/rangeFormatting` request. The rustfmt option is unstable and only
281 /// available on a nightly build.
282 rustfmt_enableRangeFormatting: bool = "false",
284 /// Workspace symbol search scope.
285 workspace_symbol_search_scope: WorkspaceSymbolSearchScopeDef = "\"workspace\"",
286 /// Workspace symbol search kind.
287 workspace_symbol_search_kind: WorkspaceSymbolSearchKindDef = "\"only_types\"",
291 impl Default for ConfigData {
292 fn default() -> Self {
293 ConfigData::from_json(serde_json::Value::Null)
297 #[derive(Debug, Clone)]
299 pub caps: lsp_types::ClientCapabilities,
301 detached_files: Vec<AbsPathBuf>,
302 pub discovered_projects: Option<Vec<ProjectManifest>>,
303 pub root_path: AbsPathBuf,
304 snippets: Vec<Snippet>,
307 #[derive(Debug, Clone, Eq, PartialEq)]
308 pub enum LinkedProject {
309 ProjectManifest(ProjectManifest),
310 InlineJsonProject(ProjectJson),
313 impl From<ProjectManifest> for LinkedProject {
314 fn from(v: ProjectManifest) -> Self {
315 LinkedProject::ProjectManifest(v)
319 impl From<ProjectJson> for LinkedProject {
320 fn from(v: ProjectJson) -> Self {
321 LinkedProject::InlineJsonProject(v)
325 #[derive(Clone, Debug, PartialEq, Eq)]
326 pub struct LensConfig {
329 pub implementations: bool,
330 pub method_refs: bool,
331 pub refs: bool, // for Struct, Enum, Union and Trait
332 pub enum_variant_refs: bool,
336 pub fn any(&self) -> bool {
337 self.implementations || self.runnable() || self.references()
340 pub fn none(&self) -> bool {
344 pub fn runnable(&self) -> bool {
345 self.run || self.debug
348 pub fn references(&self) -> bool {
349 self.method_refs || self.refs || self.enum_variant_refs
353 #[derive(Clone, Debug, PartialEq, Eq)]
354 pub struct HoverActionsConfig {
355 pub implementations: bool,
356 pub references: bool,
359 pub goto_type_def: bool,
362 impl HoverActionsConfig {
363 pub const NO_ACTIONS: Self = Self {
364 implementations: false,
368 goto_type_def: false,
371 pub fn any(&self) -> bool {
372 self.implementations || self.references || self.runnable() || self.goto_type_def
375 pub fn none(&self) -> bool {
379 pub fn runnable(&self) -> bool {
380 self.run || self.debug
384 #[derive(Debug, Clone)]
385 pub struct FilesConfig {
386 pub watcher: FilesWatcher,
387 pub exclude: Vec<AbsPathBuf>,
390 #[derive(Debug, Clone)]
391 pub enum FilesWatcher {
396 #[derive(Debug, Clone)]
397 pub struct NotificationsConfig {
398 pub cargo_toml_not_found: bool,
401 #[derive(Debug, Clone)]
402 pub enum RustfmtConfig {
403 Rustfmt { extra_args: Vec<String>, enable_range_formatting: bool },
404 CustomCommand { command: String, args: Vec<String> },
407 /// Configuration for runnable items, such as `main` function or tests.
408 #[derive(Debug, Clone)]
409 pub struct RunnablesConfig {
410 /// Custom command to be executed instead of `cargo` for runnables.
411 pub override_cargo: Option<String>,
412 /// Additional arguments for the `cargo`, e.g. `--release`.
413 pub cargo_extra_args: Vec<String>,
416 /// Configuration for workspace symbol search requests.
417 #[derive(Debug, Clone)]
418 pub struct WorkspaceSymbolConfig {
419 /// In what scope should the symbol be searched in.
420 pub search_scope: WorkspaceSymbolSearchScope,
421 /// What kind of symbol is being search for.
422 pub search_kind: WorkspaceSymbolSearchKind,
425 pub struct ClientCommandsConfig {
426 pub run_single: bool,
427 pub debug_single: bool,
428 pub show_reference: bool,
429 pub goto_location: bool,
430 pub trigger_parameter_hints: bool,
434 pub fn new(root_path: AbsPathBuf, caps: ClientCapabilities) -> Self {
437 data: ConfigData::default(),
438 detached_files: Vec::new(),
439 discovered_projects: None,
441 snippets: Default::default(),
444 pub fn update(&mut self, mut json: serde_json::Value) {
445 tracing::info!("updating config from JSON: {:#}", json);
446 if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
449 self.detached_files = get_field::<Vec<PathBuf>>(&mut json, "detachedFiles", None, "[]")
451 .map(AbsPathBuf::assert)
453 self.data = ConfigData::from_json(json);
454 self.snippets.clear();
455 for (name, def) in self.data.completion_snippets.iter() {
456 if def.prefix.is_empty() && def.postfix.is_empty() {
459 let scope = match def.scope {
460 SnippetScopeDef::Expr => SnippetScope::Expr,
461 SnippetScopeDef::Type => SnippetScope::Type,
462 SnippetScopeDef::Item => SnippetScope::Item,
468 def.description.as_ref().unwrap_or(name),
472 Some(snippet) => self.snippets.push(snippet),
473 None => tracing::info!("Invalid snippet {}", name),
478 pub fn json_schema() -> serde_json::Value {
479 ConfigData::json_schema()
485 || -> _ { Some($expr) }()
488 macro_rules! try_or {
489 ($expr:expr, $or:expr) => {
490 try_!($expr).unwrap_or($or)
495 pub fn linked_projects(&self) -> Vec<LinkedProject> {
496 if self.data.linkedProjects.is_empty() {
497 self.discovered_projects
502 .map(LinkedProject::from)
508 .filter_map(|linked_project| {
509 let res = match linked_project {
510 ManifestOrProjectJson::Manifest(it) => {
511 let path = self.root_path.join(it);
512 ProjectManifest::from_manifest_file(path)
514 tracing::error!("failed to load linked project: {}", e)
519 ManifestOrProjectJson::ProjectJson(it) => {
520 ProjectJson::new(&self.root_path, it.clone()).into()
529 pub fn detached_files(&self) -> &[AbsPathBuf] {
533 pub fn did_save_text_document_dynamic_registration(&self) -> bool {
535 try_or!(self.caps.text_document.as_ref()?.synchronization.clone()?, Default::default());
536 caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
538 pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
540 self.caps.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration?,
545 pub fn location_link(&self) -> bool {
546 try_or!(self.caps.text_document.as_ref()?.definition?.link_support?, false)
548 pub fn line_folding_only(&self) -> bool {
549 try_or!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?, false)
551 pub fn hierarchical_symbols(&self) -> bool {
558 .hierarchical_document_symbol_support?,
562 pub fn code_action_literals(&self) -> bool {
569 .code_action_literal_support
573 pub fn work_done_progress(&self) -> bool {
574 try_or!(self.caps.window.as_ref()?.work_done_progress?, false)
576 pub fn will_rename(&self) -> bool {
577 try_or!(self.caps.workspace.as_ref()?.file_operations.as_ref()?.will_rename?, false)
579 pub fn change_annotation_support(&self) -> bool {
586 .change_annotation_support
590 pub fn code_action_resolve(&self) -> bool {
604 .any(|it| it == "edit")
606 pub fn signature_help_label_offsets(&self) -> bool {
613 .signature_information
615 .parameter_information
617 .label_offset_support?,
621 pub fn offset_encoding(&self) -> OffsetEncoding {
622 if supports_utf8(&self.caps) {
625 OffsetEncoding::Utf16
629 fn experimental(&self, index: &'static str) -> bool {
630 try_or!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?, false)
632 pub fn code_action_group(&self) -> bool {
633 self.experimental("codeActionGroup")
635 pub fn server_status_notification(&self) -> bool {
636 self.experimental("serverStatusNotification")
639 pub fn publish_diagnostics(&self) -> bool {
640 self.data.diagnostics_enable
642 pub fn diagnostics(&self) -> DiagnosticsConfig {
644 disable_experimental: !self.data.diagnostics_enableExperimental,
645 disabled: self.data.diagnostics_disabled.clone(),
648 pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
649 DiagnosticsMapConfig {
650 remap_prefix: self.data.diagnostics_remapPrefix.clone(),
651 warnings_as_info: self.data.diagnostics_warningsAsInfo.clone(),
652 warnings_as_hint: self.data.diagnostics_warningsAsHint.clone(),
655 pub fn lru_capacity(&self) -> Option<usize> {
656 self.data.lruCapacity
658 pub fn proc_macro_srv(&self) -> Option<(AbsPathBuf, Vec<OsString>)> {
659 if !self.data.procMacro_enable {
662 let path = match &self.data.procMacro_server {
663 Some(it) => self.root_path.join(it),
664 None => AbsPathBuf::assert(std::env::current_exe().ok()?),
666 Some((path, vec!["proc-macro".into()]))
668 pub fn expand_proc_attr_macros(&self) -> bool {
669 self.data.experimental_procAttrMacros
671 pub fn files(&self) -> FilesConfig {
673 watcher: match self.data.files_watcher.as_str() {
674 "notify" => FilesWatcher::Notify,
675 "client" | _ => FilesWatcher::Client,
677 exclude: self.data.files_excludeDirs.iter().map(|it| self.root_path.join(it)).collect(),
680 pub fn notifications(&self) -> NotificationsConfig {
681 NotificationsConfig { cargo_toml_not_found: self.data.notifications_cargoTomlNotFound }
683 pub fn cargo_autoreload(&self) -> bool {
684 self.data.cargo_autoreload
686 pub fn run_build_scripts(&self) -> bool {
687 self.data.cargo_runBuildScripts || self.data.procMacro_enable
689 pub fn cargo(&self) -> CargoConfig {
690 let rustc_source = self.data.rustcSource.as_ref().map(|rustc_src| {
691 if rustc_src == "discover" {
692 RustcSource::Discover
694 RustcSource::Path(self.root_path.join(rustc_src))
699 no_default_features: self.data.cargo_noDefaultFeatures,
700 all_features: self.data.cargo_allFeatures,
701 features: self.data.cargo_features.clone(),
702 target: self.data.cargo_target.clone(),
703 no_sysroot: self.data.cargo_noSysroot,
705 unset_test_crates: UnsetTestCrates::Only(self.data.cargo_unsetTest.clone()),
706 wrap_rustc_in_build_scripts: self.data.cargo_useRustcWrapperForBuildScripts,
710 pub fn rustfmt(&self) -> RustfmtConfig {
711 match &self.data.rustfmt_overrideCommand {
712 Some(args) if !args.is_empty() => {
713 let mut args = args.clone();
714 let command = args.remove(0);
715 RustfmtConfig::CustomCommand { command, args }
717 Some(_) | None => RustfmtConfig::Rustfmt {
718 extra_args: self.data.rustfmt_extraArgs.clone(),
719 enable_range_formatting: self.data.rustfmt_enableRangeFormatting,
723 pub fn flycheck(&self) -> Option<FlycheckConfig> {
724 if !self.data.checkOnSave_enable {
727 let flycheck_config = match &self.data.checkOnSave_overrideCommand {
728 Some(args) if !args.is_empty() => {
729 let mut args = args.clone();
730 let command = args.remove(0);
731 FlycheckConfig::CustomCommand { command, args }
733 Some(_) | None => FlycheckConfig::CargoCommand {
734 command: self.data.checkOnSave_command.clone(),
739 .or_else(|| self.data.cargo_target.clone()),
740 all_targets: self.data.checkOnSave_allTargets,
741 no_default_features: self
743 .checkOnSave_noDefaultFeatures
744 .unwrap_or(self.data.cargo_noDefaultFeatures),
747 .checkOnSave_allFeatures
748 .unwrap_or(self.data.cargo_allFeatures),
751 .checkOnSave_features
753 .unwrap_or_else(|| self.data.cargo_features.clone()),
754 extra_args: self.data.checkOnSave_extraArgs.clone(),
757 Some(flycheck_config)
759 pub fn runnables(&self) -> RunnablesConfig {
761 override_cargo: self.data.runnables_overrideCargo.clone(),
762 cargo_extra_args: self.data.runnables_cargoExtraArgs.clone(),
765 pub fn inlay_hints(&self) -> InlayHintsConfig {
767 type_hints: self.data.inlayHints_typeHints,
768 parameter_hints: self.data.inlayHints_parameterHints,
769 chaining_hints: self.data.inlayHints_chainingHints,
770 max_length: self.data.inlayHints_maxLength,
773 fn insert_use_config(&self) -> InsertUseConfig {
775 granularity: match self.data.assist_importGranularity {
776 ImportGranularityDef::Preserve => ImportGranularity::Preserve,
777 ImportGranularityDef::Item => ImportGranularity::Item,
778 ImportGranularityDef::Crate => ImportGranularity::Crate,
779 ImportGranularityDef::Module => ImportGranularity::Module,
781 enforce_granularity: self.data.assist_importEnforceGranularity,
782 prefix_kind: match self.data.assist_importPrefix {
783 ImportPrefixDef::Plain => PrefixKind::Plain,
784 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
785 ImportPrefixDef::BySelf => PrefixKind::BySelf,
787 group: self.data.assist_importGroup,
788 skip_glob_imports: !self.data.assist_allowMergingIntoGlobImports,
791 pub fn completion(&self) -> CompletionConfig {
793 enable_postfix_completions: self.data.completion_postfix_enable,
794 enable_imports_on_the_fly: self.data.completion_autoimport_enable
795 && completion_item_edit_resolve(&self.caps),
796 enable_self_on_the_fly: self.data.completion_autoself_enable,
797 add_call_parenthesis: self.data.completion_addCallParenthesis,
798 add_call_argument_snippets: self.data.completion_addCallArgumentSnippets,
799 insert_use: self.insert_use_config(),
800 snippet_cap: SnippetCap::new(try_or!(
811 snippets: self.snippets.clone(),
814 pub fn assist(&self) -> AssistConfig {
816 snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
818 insert_use: self.insert_use_config(),
821 pub fn join_lines(&self) -> JoinLinesConfig {
823 join_else_if: self.data.joinLines_joinElseIf,
824 remove_trailing_comma: self.data.joinLines_removeTrailingComma,
825 unwrap_trivial_blocks: self.data.joinLines_unwrapTrivialBlock,
826 join_assignments: self.data.joinLines_joinAssignments,
829 pub fn call_info_full(&self) -> bool {
830 self.data.callInfo_full
832 pub fn lens(&self) -> LensConfig {
834 run: self.data.lens_enable && self.data.lens_run,
835 debug: self.data.lens_enable && self.data.lens_debug,
836 implementations: self.data.lens_enable && self.data.lens_implementations,
837 method_refs: self.data.lens_enable && self.data.lens_methodReferences,
838 refs: self.data.lens_enable && self.data.lens_references,
839 enum_variant_refs: self.data.lens_enable && self.data.lens_enumVariantReferences,
842 pub fn hover_actions(&self) -> HoverActionsConfig {
843 let enable = self.experimental("hoverActions") && self.data.hoverActions_enable;
845 implementations: enable && self.data.hoverActions_implementations,
846 references: enable && self.data.hoverActions_references,
847 run: enable && self.data.hoverActions_run,
848 debug: enable && self.data.hoverActions_debug,
849 goto_type_def: enable && self.data.hoverActions_gotoTypeDef,
852 pub fn highlighting_strings(&self) -> bool {
853 self.data.highlighting_strings
855 pub fn hover(&self) -> HoverConfig {
857 links_in_hover: self.data.hover_linksInHover,
858 documentation: self.data.hover_documentation.then(|| {
859 let is_markdown = try_or!(
870 .contains(&MarkupKind::Markdown);
872 HoverDocFormat::Markdown
874 HoverDocFormat::PlainText
880 pub fn workspace_symbol(&self) -> WorkspaceSymbolConfig {
881 WorkspaceSymbolConfig {
882 search_scope: match self.data.workspace_symbol_search_scope {
883 WorkspaceSymbolSearchScopeDef::Workspace => WorkspaceSymbolSearchScope::Workspace,
884 WorkspaceSymbolSearchScopeDef::WorkspaceAndDependencies => {
885 WorkspaceSymbolSearchScope::WorkspaceAndDependencies
888 search_kind: match self.data.workspace_symbol_search_kind {
889 WorkspaceSymbolSearchKindDef::OnlyTypes => WorkspaceSymbolSearchKind::OnlyTypes,
890 WorkspaceSymbolSearchKindDef::AllSymbols => WorkspaceSymbolSearchKind::AllSymbols,
895 pub fn semantic_tokens_refresh(&self) -> bool {
896 try_or!(self.caps.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support?, false)
898 pub fn code_lens_refresh(&self) -> bool {
899 try_or!(self.caps.workspace.as_ref()?.code_lens.as_ref()?.refresh_support?, false)
901 pub fn insert_replace_support(&self) -> bool {
910 .insert_replace_support?,
914 pub fn client_commands(&self) -> ClientCommandsConfig {
916 try_or!(self.caps.experimental.as_ref()?.get("commands")?, &serde_json::Value::Null);
917 let commands: Option<lsp_ext::ClientCommandOptions> =
918 serde_json::from_value(commands.clone()).ok();
919 let force = commands.is_none() && self.data.lens_forceCustomCommands;
920 let commands = commands.map(|it| it.commands).unwrap_or_default();
922 let get = |name: &str| commands.iter().any(|it| it == name) || force;
924 ClientCommandsConfig {
925 run_single: get("rust-analyzer.runSingle"),
926 debug_single: get("rust-analyzer.debugSingle"),
927 show_reference: get("rust-analyzer.showReferences"),
928 goto_location: get("rust-analyzer.gotoLocation"),
929 trigger_parameter_hints: get("editor.action.triggerParameterHints"),
933 pub fn highlight_related(&self) -> HighlightRelatedConfig {
934 HighlightRelatedConfig {
935 references: self.data.highlightRelated_references,
936 break_points: self.data.highlightRelated_breakPoints,
937 exit_points: self.data.highlightRelated_exitPoints,
938 yield_points: self.data.highlightRelated_yieldPoints,
943 #[derive(Deserialize, Debug, Clone, Copy)]
944 #[serde(rename_all = "snake_case")]
945 enum SnippetScopeDef {
951 impl Default for SnippetScopeDef {
952 fn default() -> Self {
953 SnippetScopeDef::Expr
957 #[derive(Deserialize, Debug, Clone, Default)]
960 #[serde(deserialize_with = "single_or_array")]
962 #[serde(deserialize_with = "single_or_array")]
963 postfix: Vec<String>,
964 description: Option<String>,
965 #[serde(deserialize_with = "single_or_array")]
967 #[serde(deserialize_with = "single_or_array")]
968 requires: Vec<String>,
969 scope: SnippetScopeDef,
972 fn single_or_array<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
974 D: serde::Deserializer<'de>,
978 impl<'de> serde::de::Visitor<'de> for SingleOrVec {
979 type Value = Vec<String>;
981 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
982 formatter.write_str("string or array of strings")
985 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
989 Ok(vec![value.to_owned()])
992 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
994 A: serde::de::SeqAccess<'de>,
996 Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
1000 deserializer.deserialize_any(SingleOrVec)
1003 #[derive(Deserialize, Debug, Clone)]
1005 enum ManifestOrProjectJson {
1007 ProjectJson(ProjectJsonData),
1010 #[derive(Deserialize, Debug, Clone)]
1011 #[serde(rename_all = "snake_case")]
1012 enum ImportGranularityDef {
1014 #[serde(alias = "none")]
1016 #[serde(alias = "full")]
1018 #[serde(alias = "last")]
1022 #[derive(Deserialize, Debug, Clone)]
1023 #[serde(rename_all = "snake_case")]
1024 enum ImportPrefixDef {
1026 #[serde(alias = "self")]
1028 #[serde(alias = "crate")]
1032 #[derive(Deserialize, Debug, Clone)]
1033 #[serde(rename_all = "snake_case")]
1034 enum WorkspaceSymbolSearchScopeDef {
1036 WorkspaceAndDependencies,
1039 #[derive(Deserialize, Debug, Clone)]
1040 #[serde(rename_all = "snake_case")]
1041 enum WorkspaceSymbolSearchKindDef {
1046 macro_rules! _config_data {
1047 (struct $name:ident {
1049 $(#[doc=$doc:literal])*
1050 $field:ident $(| $alias:ident)*: $ty:ty = $default:expr,
1053 #[allow(non_snake_case)]
1054 #[derive(Debug, Clone)]
1055 struct $name { $($field: $ty,)* }
1057 fn from_json(mut json: serde_json::Value) -> $name {
1062 None$(.or(Some(stringify!($alias))))*,
1068 fn json_schema() -> serde_json::Value {
1071 let field = stringify!($field);
1072 let ty = stringify!($ty);
1074 (field, ty, &[$($doc),*], $default)
1080 fn manual() -> String {
1083 let field = stringify!($field);
1084 let ty = stringify!($ty);
1086 (field, ty, &[$($doc),*], $default)
1093 use _config_data as config_data;
1095 fn get_field<T: DeserializeOwned>(
1096 json: &mut serde_json::Value,
1097 field: &'static str,
1098 alias: Option<&'static str>,
1101 let default = serde_json::from_str(default).unwrap();
1103 // XXX: check alias first, to work-around the VS Code where it pre-fills the
1104 // defaults instead of sending an empty object.
1107 .chain(iter::once(field))
1108 .find_map(move |field| {
1109 let mut pointer = field.replace('_', "/");
1110 pointer.insert(0, '/');
1111 json.pointer_mut(&pointer).and_then(|it| serde_json::from_value(it.take()).ok())
1116 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
1117 for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
1118 fn key(f: &str) -> &str {
1119 f.splitn(2, '_').next().unwrap()
1121 assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
1126 .map(|(field, ty, doc, default)| {
1127 let name = field.replace("_", ".");
1128 let name = format!("rust-analyzer.{}", name);
1129 let props = field_props(field, ty, doc, default);
1132 .collect::<serde_json::Map<_, _>>();
1136 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
1137 let doc = doc_comment_to_string(doc);
1138 let doc = doc.trim_end_matches('\n');
1140 doc.ends_with('.') && doc.starts_with(char::is_uppercase),
1141 "bad docs for {}: {:?}",
1145 let default = default.parse::<serde_json::Value>().unwrap();
1147 let mut map = serde_json::Map::default();
1149 ($($key:literal: $value:tt),*$(,)?) => {{$(
1150 map.insert($key.into(), serde_json::json!($value));
1153 set!("markdownDescription": doc);
1154 set!("default": default);
1157 "bool" => set!("type": "boolean"),
1158 "String" => set!("type": "string"),
1159 "Vec<String>" => set! {
1161 "items": { "type": "string" },
1163 "Vec<PathBuf>" => set! {
1165 "items": { "type": "string" },
1167 "FxHashSet<String>" => set! {
1169 "items": { "type": "string" },
1170 "uniqueItems": true,
1172 "FxHashMap<String, SnippetDef>" => set! {
1175 "FxHashMap<String, String>" => set! {
1178 "Option<usize>" => set! {
1179 "type": ["null", "integer"],
1182 "Option<String>" => set! {
1183 "type": ["null", "string"],
1185 "Option<PathBuf>" => set! {
1186 "type": ["null", "string"],
1188 "Option<bool>" => set! {
1189 "type": ["null", "boolean"],
1191 "Option<Vec<String>>" => set! {
1192 "type": ["null", "array"],
1193 "items": { "type": "string" },
1195 "MergeBehaviorDef" => set! {
1197 "enum": ["none", "crate", "module"],
1198 "enumDescriptions": [
1199 "Do not merge imports at all.",
1200 "Merge imports from the same crate into a single `use` statement.",
1201 "Merge imports from the same module into a single `use` statement."
1204 "ImportGranularityDef" => set! {
1206 "enum": ["preserve", "crate", "module", "item"],
1207 "enumDescriptions": [
1208 "Do not change the granularity of any imports and preserve the original structure written by the developer.",
1209 "Merge imports from the same crate into a single use statement. Conversely, imports from different crates are split into separate statements.",
1210 "Merge imports from the same module into a single use statement. Conversely, imports from different modules are split into separate statements.",
1211 "Flatten imports so that each has its own use statement."
1214 "ImportPrefixDef" => set! {
1221 "enumDescriptions": [
1222 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
1223 "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.",
1224 "Force import paths to be absolute by always starting them with `crate` or the extern crate name they come from."
1227 "Vec<ManifestOrProjectJson>" => set! {
1229 "items": { "type": ["string", "object"] },
1231 "WorkspaceSymbolSearchScopeDef" => set! {
1233 "enum": ["workspace", "workspace_and_dependencies"],
1234 "enumDescriptions": [
1235 "Search in current workspace only",
1236 "Search in current workspace and dependencies"
1239 "WorkspaceSymbolSearchKindDef" => set! {
1241 "enum": ["only_types", "all_symbols"],
1242 "enumDescriptions": [
1243 "Search for types only",
1244 "Search for all symbols kinds"
1247 _ => panic!("{}: {}", ty, default),
1254 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
1257 .map(|(field, _ty, doc, default)| {
1258 let name = format!("rust-analyzer.{}", field.replace("_", "."));
1259 let doc = doc_comment_to_string(*doc);
1260 format!("[[{}]]{} (default: `{}`)::\n+\n--\n{}--\n", name, name, default, doc)
1262 .collect::<String>()
1265 fn doc_comment_to_string(doc: &[&str]) -> String {
1266 doc.iter().map(|it| it.strip_prefix(' ').unwrap_or(it)).map(|it| format!("{}\n", it)).collect()
1273 use test_utils::{ensure_file_contents, project_root};
1278 fn generate_package_json_config() {
1279 let s = Config::json_schema();
1280 let schema = format!("{:#}", s);
1281 let mut schema = schema
1282 .trim_start_matches('{')
1283 .trim_end_matches('}')
1285 .replace("\n", "\n ")
1286 .trim_start_matches('\n')
1289 schema.push_str(",\n");
1291 let package_json_path = project_root().join("editors/code/package.json");
1292 let mut package_json = fs::read_to_string(&package_json_path).unwrap();
1294 let start_marker = " \"$generated-start\": {},\n";
1295 let end_marker = " \"$generated-end\": {}\n";
1297 let start = package_json.find(start_marker).unwrap() + start_marker.len();
1298 let end = package_json.find(end_marker).unwrap();
1300 let p = remove_ws(&package_json[start..end]);
1301 let s = remove_ws(&schema);
1302 if !p.contains(&s) {
1303 package_json.replace_range(start..end, &schema);
1304 ensure_file_contents(&package_json_path, &package_json)
1309 fn generate_config_documentation() {
1310 let docs_path = project_root().join("docs/user/generated_config.adoc");
1311 let expected = ConfigData::manual();
1312 ensure_file_contents(&docs_path, &expected);
1315 fn remove_ws(text: &str) -> String {
1316 text.replace(char::is_whitespace, "")