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 if the `rustc-dev` component
269 /// Any project which uses rust-analyzer with the rustcPrivate
270 /// crates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.
272 /// This option does not take effect until rust-analyzer is restarted.
273 rustcSource: Option<String> = "null",
275 /// Additional arguments to `rustfmt`.
276 rustfmt_extraArgs: Vec<String> = "[]",
277 /// Advanced option, fully override the command rust-analyzer uses for
279 rustfmt_overrideCommand: Option<Vec<String>> = "null",
280 /// Enables the use of rustfmt's unstable range formatting command for the
281 /// `textDocument/rangeFormatting` request. The rustfmt option is unstable and only
282 /// available on a nightly build.
283 rustfmt_enableRangeFormatting: bool = "false",
285 /// Workspace symbol search scope.
286 workspace_symbol_search_scope: WorkspaceSymbolSearchScopeDef = "\"workspace\"",
287 /// Workspace symbol search kind.
288 workspace_symbol_search_kind: WorkspaceSymbolSearchKindDef = "\"only_types\"",
292 impl Default for ConfigData {
293 fn default() -> Self {
294 ConfigData::from_json(serde_json::Value::Null)
298 #[derive(Debug, Clone)]
300 pub caps: lsp_types::ClientCapabilities,
302 detached_files: Vec<AbsPathBuf>,
303 pub discovered_projects: Option<Vec<ProjectManifest>>,
304 pub root_path: AbsPathBuf,
305 snippets: Vec<Snippet>,
308 #[derive(Debug, Clone, Eq, PartialEq)]
309 pub enum LinkedProject {
310 ProjectManifest(ProjectManifest),
311 InlineJsonProject(ProjectJson),
314 impl From<ProjectManifest> for LinkedProject {
315 fn from(v: ProjectManifest) -> Self {
316 LinkedProject::ProjectManifest(v)
320 impl From<ProjectJson> for LinkedProject {
321 fn from(v: ProjectJson) -> Self {
322 LinkedProject::InlineJsonProject(v)
326 #[derive(Clone, Debug, PartialEq, Eq)]
327 pub struct LensConfig {
330 pub implementations: bool,
331 pub method_refs: bool,
332 pub refs: bool, // for Struct, Enum, Union and Trait
333 pub enum_variant_refs: bool,
337 pub fn any(&self) -> bool {
338 self.implementations || self.runnable() || self.references()
341 pub fn none(&self) -> bool {
345 pub fn runnable(&self) -> bool {
346 self.run || self.debug
349 pub fn references(&self) -> bool {
350 self.method_refs || self.refs || self.enum_variant_refs
354 #[derive(Clone, Debug, PartialEq, Eq)]
355 pub struct HoverActionsConfig {
356 pub implementations: bool,
357 pub references: bool,
360 pub goto_type_def: bool,
363 impl HoverActionsConfig {
364 pub const NO_ACTIONS: Self = Self {
365 implementations: false,
369 goto_type_def: false,
372 pub fn any(&self) -> bool {
373 self.implementations || self.references || self.runnable() || self.goto_type_def
376 pub fn none(&self) -> bool {
380 pub fn runnable(&self) -> bool {
381 self.run || self.debug
385 #[derive(Debug, Clone)]
386 pub struct FilesConfig {
387 pub watcher: FilesWatcher,
388 pub exclude: Vec<AbsPathBuf>,
391 #[derive(Debug, Clone)]
392 pub enum FilesWatcher {
397 #[derive(Debug, Clone)]
398 pub struct NotificationsConfig {
399 pub cargo_toml_not_found: bool,
402 #[derive(Debug, Clone)]
403 pub enum RustfmtConfig {
404 Rustfmt { extra_args: Vec<String>, enable_range_formatting: bool },
405 CustomCommand { command: String, args: Vec<String> },
408 /// Configuration for runnable items, such as `main` function or tests.
409 #[derive(Debug, Clone)]
410 pub struct RunnablesConfig {
411 /// Custom command to be executed instead of `cargo` for runnables.
412 pub override_cargo: Option<String>,
413 /// Additional arguments for the `cargo`, e.g. `--release`.
414 pub cargo_extra_args: Vec<String>,
417 /// Configuration for workspace symbol search requests.
418 #[derive(Debug, Clone)]
419 pub struct WorkspaceSymbolConfig {
420 /// In what scope should the symbol be searched in.
421 pub search_scope: WorkspaceSymbolSearchScope,
422 /// What kind of symbol is being search for.
423 pub search_kind: WorkspaceSymbolSearchKind,
426 pub struct ClientCommandsConfig {
427 pub run_single: bool,
428 pub debug_single: bool,
429 pub show_reference: bool,
430 pub goto_location: bool,
431 pub trigger_parameter_hints: bool,
435 pub fn new(root_path: AbsPathBuf, caps: ClientCapabilities) -> Self {
438 data: ConfigData::default(),
439 detached_files: Vec::new(),
440 discovered_projects: None,
442 snippets: Default::default(),
445 pub fn update(&mut self, mut json: serde_json::Value) {
446 tracing::info!("updating config from JSON: {:#}", json);
447 if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
450 self.detached_files = get_field::<Vec<PathBuf>>(&mut json, "detachedFiles", None, "[]")
452 .map(AbsPathBuf::assert)
454 self.data = ConfigData::from_json(json);
455 self.snippets.clear();
456 for (name, def) in self.data.completion_snippets.iter() {
457 if def.prefix.is_empty() && def.postfix.is_empty() {
460 let scope = match def.scope {
461 SnippetScopeDef::Expr => SnippetScope::Expr,
462 SnippetScopeDef::Type => SnippetScope::Type,
463 SnippetScopeDef::Item => SnippetScope::Item,
469 def.description.as_ref().unwrap_or(name),
473 Some(snippet) => self.snippets.push(snippet),
474 None => tracing::info!("Invalid snippet {}", name),
479 pub fn json_schema() -> serde_json::Value {
480 ConfigData::json_schema()
486 || -> _ { Some($expr) }()
489 macro_rules! try_or {
490 ($expr:expr, $or:expr) => {
491 try_!($expr).unwrap_or($or)
496 pub fn linked_projects(&self) -> Vec<LinkedProject> {
497 if self.data.linkedProjects.is_empty() {
498 self.discovered_projects
503 .map(LinkedProject::from)
509 .filter_map(|linked_project| {
510 let res = match linked_project {
511 ManifestOrProjectJson::Manifest(it) => {
512 let path = self.root_path.join(it);
513 ProjectManifest::from_manifest_file(path)
515 tracing::error!("failed to load linked project: {}", e)
520 ManifestOrProjectJson::ProjectJson(it) => {
521 ProjectJson::new(&self.root_path, it.clone()).into()
530 pub fn detached_files(&self) -> &[AbsPathBuf] {
534 pub fn did_save_text_document_dynamic_registration(&self) -> bool {
536 try_or!(self.caps.text_document.as_ref()?.synchronization.clone()?, Default::default());
537 caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
539 pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
541 self.caps.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration?,
546 pub fn location_link(&self) -> bool {
547 try_or!(self.caps.text_document.as_ref()?.definition?.link_support?, false)
549 pub fn line_folding_only(&self) -> bool {
550 try_or!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?, false)
552 pub fn hierarchical_symbols(&self) -> bool {
559 .hierarchical_document_symbol_support?,
563 pub fn code_action_literals(&self) -> bool {
570 .code_action_literal_support
574 pub fn work_done_progress(&self) -> bool {
575 try_or!(self.caps.window.as_ref()?.work_done_progress?, false)
577 pub fn will_rename(&self) -> bool {
578 try_or!(self.caps.workspace.as_ref()?.file_operations.as_ref()?.will_rename?, false)
580 pub fn change_annotation_support(&self) -> bool {
587 .change_annotation_support
591 pub fn code_action_resolve(&self) -> bool {
605 .any(|it| it == "edit")
607 pub fn signature_help_label_offsets(&self) -> bool {
614 .signature_information
616 .parameter_information
618 .label_offset_support?,
622 pub fn offset_encoding(&self) -> OffsetEncoding {
623 if supports_utf8(&self.caps) {
626 OffsetEncoding::Utf16
630 fn experimental(&self, index: &'static str) -> bool {
631 try_or!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?, false)
633 pub fn code_action_group(&self) -> bool {
634 self.experimental("codeActionGroup")
636 pub fn server_status_notification(&self) -> bool {
637 self.experimental("serverStatusNotification")
640 pub fn publish_diagnostics(&self) -> bool {
641 self.data.diagnostics_enable
643 pub fn diagnostics(&self) -> DiagnosticsConfig {
645 disable_experimental: !self.data.diagnostics_enableExperimental,
646 disabled: self.data.diagnostics_disabled.clone(),
649 pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
650 DiagnosticsMapConfig {
651 remap_prefix: self.data.diagnostics_remapPrefix.clone(),
652 warnings_as_info: self.data.diagnostics_warningsAsInfo.clone(),
653 warnings_as_hint: self.data.diagnostics_warningsAsHint.clone(),
656 pub fn lru_capacity(&self) -> Option<usize> {
657 self.data.lruCapacity
659 pub fn proc_macro_srv(&self) -> Option<(AbsPathBuf, Vec<OsString>)> {
660 if !self.data.procMacro_enable {
663 let path = match &self.data.procMacro_server {
664 Some(it) => self.root_path.join(it),
665 None => AbsPathBuf::assert(std::env::current_exe().ok()?),
667 Some((path, vec!["proc-macro".into()]))
669 pub fn expand_proc_attr_macros(&self) -> bool {
670 self.data.experimental_procAttrMacros
672 pub fn files(&self) -> FilesConfig {
674 watcher: match self.data.files_watcher.as_str() {
675 "notify" => FilesWatcher::Notify,
676 "client" | _ => FilesWatcher::Client,
678 exclude: self.data.files_excludeDirs.iter().map(|it| self.root_path.join(it)).collect(),
681 pub fn notifications(&self) -> NotificationsConfig {
682 NotificationsConfig { cargo_toml_not_found: self.data.notifications_cargoTomlNotFound }
684 pub fn cargo_autoreload(&self) -> bool {
685 self.data.cargo_autoreload
687 pub fn run_build_scripts(&self) -> bool {
688 self.data.cargo_runBuildScripts || self.data.procMacro_enable
690 pub fn cargo(&self) -> CargoConfig {
691 let rustc_source = self.data.rustcSource.as_ref().map(|rustc_src| {
692 if rustc_src == "discover" {
693 RustcSource::Discover
695 RustcSource::Path(self.root_path.join(rustc_src))
700 no_default_features: self.data.cargo_noDefaultFeatures,
701 all_features: self.data.cargo_allFeatures,
702 features: self.data.cargo_features.clone(),
703 target: self.data.cargo_target.clone(),
704 no_sysroot: self.data.cargo_noSysroot,
706 unset_test_crates: UnsetTestCrates::Only(self.data.cargo_unsetTest.clone()),
707 wrap_rustc_in_build_scripts: self.data.cargo_useRustcWrapperForBuildScripts,
711 pub fn rustfmt(&self) -> RustfmtConfig {
712 match &self.data.rustfmt_overrideCommand {
713 Some(args) if !args.is_empty() => {
714 let mut args = args.clone();
715 let command = args.remove(0);
716 RustfmtConfig::CustomCommand { command, args }
718 Some(_) | None => RustfmtConfig::Rustfmt {
719 extra_args: self.data.rustfmt_extraArgs.clone(),
720 enable_range_formatting: self.data.rustfmt_enableRangeFormatting,
724 pub fn flycheck(&self) -> Option<FlycheckConfig> {
725 if !self.data.checkOnSave_enable {
728 let flycheck_config = match &self.data.checkOnSave_overrideCommand {
729 Some(args) if !args.is_empty() => {
730 let mut args = args.clone();
731 let command = args.remove(0);
732 FlycheckConfig::CustomCommand { command, args }
734 Some(_) | None => FlycheckConfig::CargoCommand {
735 command: self.data.checkOnSave_command.clone(),
740 .or_else(|| self.data.cargo_target.clone()),
741 all_targets: self.data.checkOnSave_allTargets,
742 no_default_features: self
744 .checkOnSave_noDefaultFeatures
745 .unwrap_or(self.data.cargo_noDefaultFeatures),
748 .checkOnSave_allFeatures
749 .unwrap_or(self.data.cargo_allFeatures),
752 .checkOnSave_features
754 .unwrap_or_else(|| self.data.cargo_features.clone()),
755 extra_args: self.data.checkOnSave_extraArgs.clone(),
758 Some(flycheck_config)
760 pub fn runnables(&self) -> RunnablesConfig {
762 override_cargo: self.data.runnables_overrideCargo.clone(),
763 cargo_extra_args: self.data.runnables_cargoExtraArgs.clone(),
766 pub fn inlay_hints(&self) -> InlayHintsConfig {
768 type_hints: self.data.inlayHints_typeHints,
769 parameter_hints: self.data.inlayHints_parameterHints,
770 chaining_hints: self.data.inlayHints_chainingHints,
771 max_length: self.data.inlayHints_maxLength,
774 fn insert_use_config(&self) -> InsertUseConfig {
776 granularity: match self.data.assist_importGranularity {
777 ImportGranularityDef::Preserve => ImportGranularity::Preserve,
778 ImportGranularityDef::Item => ImportGranularity::Item,
779 ImportGranularityDef::Crate => ImportGranularity::Crate,
780 ImportGranularityDef::Module => ImportGranularity::Module,
782 enforce_granularity: self.data.assist_importEnforceGranularity,
783 prefix_kind: match self.data.assist_importPrefix {
784 ImportPrefixDef::Plain => PrefixKind::Plain,
785 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
786 ImportPrefixDef::BySelf => PrefixKind::BySelf,
788 group: self.data.assist_importGroup,
789 skip_glob_imports: !self.data.assist_allowMergingIntoGlobImports,
792 pub fn completion(&self) -> CompletionConfig {
794 enable_postfix_completions: self.data.completion_postfix_enable,
795 enable_imports_on_the_fly: self.data.completion_autoimport_enable
796 && completion_item_edit_resolve(&self.caps),
797 enable_self_on_the_fly: self.data.completion_autoself_enable,
798 add_call_parenthesis: self.data.completion_addCallParenthesis,
799 add_call_argument_snippets: self.data.completion_addCallArgumentSnippets,
800 insert_use: self.insert_use_config(),
801 snippet_cap: SnippetCap::new(try_or!(
812 snippets: self.snippets.clone(),
815 pub fn assist(&self) -> AssistConfig {
817 snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
819 insert_use: self.insert_use_config(),
822 pub fn join_lines(&self) -> JoinLinesConfig {
824 join_else_if: self.data.joinLines_joinElseIf,
825 remove_trailing_comma: self.data.joinLines_removeTrailingComma,
826 unwrap_trivial_blocks: self.data.joinLines_unwrapTrivialBlock,
827 join_assignments: self.data.joinLines_joinAssignments,
830 pub fn call_info_full(&self) -> bool {
831 self.data.callInfo_full
833 pub fn lens(&self) -> LensConfig {
835 run: self.data.lens_enable && self.data.lens_run,
836 debug: self.data.lens_enable && self.data.lens_debug,
837 implementations: self.data.lens_enable && self.data.lens_implementations,
838 method_refs: self.data.lens_enable && self.data.lens_methodReferences,
839 refs: self.data.lens_enable && self.data.lens_references,
840 enum_variant_refs: self.data.lens_enable && self.data.lens_enumVariantReferences,
843 pub fn hover_actions(&self) -> HoverActionsConfig {
844 let enable = self.experimental("hoverActions") && self.data.hoverActions_enable;
846 implementations: enable && self.data.hoverActions_implementations,
847 references: enable && self.data.hoverActions_references,
848 run: enable && self.data.hoverActions_run,
849 debug: enable && self.data.hoverActions_debug,
850 goto_type_def: enable && self.data.hoverActions_gotoTypeDef,
853 pub fn highlighting_strings(&self) -> bool {
854 self.data.highlighting_strings
856 pub fn hover(&self) -> HoverConfig {
858 links_in_hover: self.data.hover_linksInHover,
859 documentation: self.data.hover_documentation.then(|| {
860 let is_markdown = try_or!(
871 .contains(&MarkupKind::Markdown);
873 HoverDocFormat::Markdown
875 HoverDocFormat::PlainText
881 pub fn workspace_symbol(&self) -> WorkspaceSymbolConfig {
882 WorkspaceSymbolConfig {
883 search_scope: match self.data.workspace_symbol_search_scope {
884 WorkspaceSymbolSearchScopeDef::Workspace => WorkspaceSymbolSearchScope::Workspace,
885 WorkspaceSymbolSearchScopeDef::WorkspaceAndDependencies => {
886 WorkspaceSymbolSearchScope::WorkspaceAndDependencies
889 search_kind: match self.data.workspace_symbol_search_kind {
890 WorkspaceSymbolSearchKindDef::OnlyTypes => WorkspaceSymbolSearchKind::OnlyTypes,
891 WorkspaceSymbolSearchKindDef::AllSymbols => WorkspaceSymbolSearchKind::AllSymbols,
896 pub fn semantic_tokens_refresh(&self) -> bool {
897 try_or!(self.caps.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support?, false)
899 pub fn code_lens_refresh(&self) -> bool {
900 try_or!(self.caps.workspace.as_ref()?.code_lens.as_ref()?.refresh_support?, false)
902 pub fn insert_replace_support(&self) -> bool {
911 .insert_replace_support?,
915 pub fn client_commands(&self) -> ClientCommandsConfig {
917 try_or!(self.caps.experimental.as_ref()?.get("commands")?, &serde_json::Value::Null);
918 let commands: Option<lsp_ext::ClientCommandOptions> =
919 serde_json::from_value(commands.clone()).ok();
920 let force = commands.is_none() && self.data.lens_forceCustomCommands;
921 let commands = commands.map(|it| it.commands).unwrap_or_default();
923 let get = |name: &str| commands.iter().any(|it| it == name) || force;
925 ClientCommandsConfig {
926 run_single: get("rust-analyzer.runSingle"),
927 debug_single: get("rust-analyzer.debugSingle"),
928 show_reference: get("rust-analyzer.showReferences"),
929 goto_location: get("rust-analyzer.gotoLocation"),
930 trigger_parameter_hints: get("editor.action.triggerParameterHints"),
934 pub fn highlight_related(&self) -> HighlightRelatedConfig {
935 HighlightRelatedConfig {
936 references: self.data.highlightRelated_references,
937 break_points: self.data.highlightRelated_breakPoints,
938 exit_points: self.data.highlightRelated_exitPoints,
939 yield_points: self.data.highlightRelated_yieldPoints,
944 #[derive(Deserialize, Debug, Clone, Copy)]
945 #[serde(rename_all = "snake_case")]
946 enum SnippetScopeDef {
952 impl Default for SnippetScopeDef {
953 fn default() -> Self {
954 SnippetScopeDef::Expr
958 #[derive(Deserialize, Debug, Clone, Default)]
961 #[serde(deserialize_with = "single_or_array")]
963 #[serde(deserialize_with = "single_or_array")]
964 postfix: Vec<String>,
965 description: Option<String>,
966 #[serde(deserialize_with = "single_or_array")]
968 #[serde(deserialize_with = "single_or_array")]
969 requires: Vec<String>,
970 scope: SnippetScopeDef,
973 fn single_or_array<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
975 D: serde::Deserializer<'de>,
979 impl<'de> serde::de::Visitor<'de> for SingleOrVec {
980 type Value = Vec<String>;
982 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
983 formatter.write_str("string or array of strings")
986 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
990 Ok(vec![value.to_owned()])
993 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
995 A: serde::de::SeqAccess<'de>,
997 Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
1001 deserializer.deserialize_any(SingleOrVec)
1004 #[derive(Deserialize, Debug, Clone)]
1006 enum ManifestOrProjectJson {
1008 ProjectJson(ProjectJsonData),
1011 #[derive(Deserialize, Debug, Clone)]
1012 #[serde(rename_all = "snake_case")]
1013 enum ImportGranularityDef {
1015 #[serde(alias = "none")]
1017 #[serde(alias = "full")]
1019 #[serde(alias = "last")]
1023 #[derive(Deserialize, Debug, Clone)]
1024 #[serde(rename_all = "snake_case")]
1025 enum ImportPrefixDef {
1027 #[serde(alias = "self")]
1029 #[serde(alias = "crate")]
1033 #[derive(Deserialize, Debug, Clone)]
1034 #[serde(rename_all = "snake_case")]
1035 enum WorkspaceSymbolSearchScopeDef {
1037 WorkspaceAndDependencies,
1040 #[derive(Deserialize, Debug, Clone)]
1041 #[serde(rename_all = "snake_case")]
1042 enum WorkspaceSymbolSearchKindDef {
1047 macro_rules! _config_data {
1048 (struct $name:ident {
1050 $(#[doc=$doc:literal])*
1051 $field:ident $(| $alias:ident)*: $ty:ty = $default:expr,
1054 #[allow(non_snake_case)]
1055 #[derive(Debug, Clone)]
1056 struct $name { $($field: $ty,)* }
1058 fn from_json(mut json: serde_json::Value) -> $name {
1063 None$(.or(Some(stringify!($alias))))*,
1069 fn json_schema() -> serde_json::Value {
1072 let field = stringify!($field);
1073 let ty = stringify!($ty);
1075 (field, ty, &[$($doc),*], $default)
1081 fn manual() -> String {
1084 let field = stringify!($field);
1085 let ty = stringify!($ty);
1087 (field, ty, &[$($doc),*], $default)
1094 use _config_data as config_data;
1096 fn get_field<T: DeserializeOwned>(
1097 json: &mut serde_json::Value,
1098 field: &'static str,
1099 alias: Option<&'static str>,
1102 let default = serde_json::from_str(default).unwrap();
1104 // XXX: check alias first, to work-around the VS Code where it pre-fills the
1105 // defaults instead of sending an empty object.
1108 .chain(iter::once(field))
1109 .find_map(move |field| {
1110 let mut pointer = field.replace('_', "/");
1111 pointer.insert(0, '/');
1112 json.pointer_mut(&pointer).and_then(|it| serde_json::from_value(it.take()).ok())
1117 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
1118 for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
1119 fn key(f: &str) -> &str {
1120 f.splitn(2, '_').next().unwrap()
1122 assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
1127 .map(|(field, ty, doc, default)| {
1128 let name = field.replace("_", ".");
1129 let name = format!("rust-analyzer.{}", name);
1130 let props = field_props(field, ty, doc, default);
1133 .collect::<serde_json::Map<_, _>>();
1137 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
1138 let doc = doc_comment_to_string(doc);
1139 let doc = doc.trim_end_matches('\n');
1141 doc.ends_with('.') && doc.starts_with(char::is_uppercase),
1142 "bad docs for {}: {:?}",
1146 let default = default.parse::<serde_json::Value>().unwrap();
1148 let mut map = serde_json::Map::default();
1150 ($($key:literal: $value:tt),*$(,)?) => {{$(
1151 map.insert($key.into(), serde_json::json!($value));
1154 set!("markdownDescription": doc);
1155 set!("default": default);
1158 "bool" => set!("type": "boolean"),
1159 "String" => set!("type": "string"),
1160 "Vec<String>" => set! {
1162 "items": { "type": "string" },
1164 "Vec<PathBuf>" => set! {
1166 "items": { "type": "string" },
1168 "FxHashSet<String>" => set! {
1170 "items": { "type": "string" },
1171 "uniqueItems": true,
1173 "FxHashMap<String, SnippetDef>" => set! {
1176 "FxHashMap<String, String>" => set! {
1179 "Option<usize>" => set! {
1180 "type": ["null", "integer"],
1183 "Option<String>" => set! {
1184 "type": ["null", "string"],
1186 "Option<PathBuf>" => set! {
1187 "type": ["null", "string"],
1189 "Option<bool>" => set! {
1190 "type": ["null", "boolean"],
1192 "Option<Vec<String>>" => set! {
1193 "type": ["null", "array"],
1194 "items": { "type": "string" },
1196 "MergeBehaviorDef" => set! {
1198 "enum": ["none", "crate", "module"],
1199 "enumDescriptions": [
1200 "Do not merge imports at all.",
1201 "Merge imports from the same crate into a single `use` statement.",
1202 "Merge imports from the same module into a single `use` statement."
1205 "ImportGranularityDef" => set! {
1207 "enum": ["preserve", "crate", "module", "item"],
1208 "enumDescriptions": [
1209 "Do not change the granularity of any imports and preserve the original structure written by the developer.",
1210 "Merge imports from the same crate into a single use statement. Conversely, imports from different crates are split into separate statements.",
1211 "Merge imports from the same module into a single use statement. Conversely, imports from different modules are split into separate statements.",
1212 "Flatten imports so that each has its own use statement."
1215 "ImportPrefixDef" => set! {
1222 "enumDescriptions": [
1223 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
1224 "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.",
1225 "Force import paths to be absolute by always starting them with `crate` or the extern crate name they come from."
1228 "Vec<ManifestOrProjectJson>" => set! {
1230 "items": { "type": ["string", "object"] },
1232 "WorkspaceSymbolSearchScopeDef" => set! {
1234 "enum": ["workspace", "workspace_and_dependencies"],
1235 "enumDescriptions": [
1236 "Search in current workspace only",
1237 "Search in current workspace and dependencies"
1240 "WorkspaceSymbolSearchKindDef" => set! {
1242 "enum": ["only_types", "all_symbols"],
1243 "enumDescriptions": [
1244 "Search for types only",
1245 "Search for all symbols kinds"
1248 _ => panic!("{}: {}", ty, default),
1255 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
1258 .map(|(field, _ty, doc, default)| {
1259 let name = format!("rust-analyzer.{}", field.replace("_", "."));
1260 let doc = doc_comment_to_string(*doc);
1261 format!("[[{}]]{} (default: `{}`)::\n+\n--\n{}--\n", name, name, default, doc)
1263 .collect::<String>()
1266 fn doc_comment_to_string(doc: &[&str]) -> String {
1267 doc.iter().map(|it| it.strip_prefix(' ').unwrap_or(it)).map(|it| format!("{}\n", it)).collect()
1274 use test_utils::{ensure_file_contents, project_root};
1279 fn generate_package_json_config() {
1280 let s = Config::json_schema();
1281 let schema = format!("{:#}", s);
1282 let mut schema = schema
1283 .trim_start_matches('{')
1284 .trim_end_matches('}')
1286 .replace("\n", "\n ")
1287 .trim_start_matches('\n')
1290 schema.push_str(",\n");
1292 let package_json_path = project_root().join("editors/code/package.json");
1293 let mut package_json = fs::read_to_string(&package_json_path).unwrap();
1295 let start_marker = " \"$generated-start\": {},\n";
1296 let end_marker = " \"$generated-end\": {}\n";
1298 let start = package_json.find(start_marker).unwrap() + start_marker.len();
1299 let end = package_json.find(end_marker).unwrap();
1301 let p = remove_ws(&package_json[start..end]);
1302 let s = remove_ws(&schema);
1303 if !p.contains(&s) {
1304 package_json.replace_range(start..end, &schema);
1305 ensure_file_contents(&package_json_path, &package_json)
1310 fn generate_config_documentation() {
1311 let docs_path = project_root().join("docs/user/generated_config.adoc");
1312 let expected = ConfigData::manual();
1313 ensure_file_contents(&docs_path, &expected);
1316 fn remove_ws(text: &str) -> String {
1317 text.replace(char::is_whitespace, "")