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. Only applies when
231 /// `#rust-analyzer.lens.enable#` is set.
232 lens_references: bool = "false",
233 /// Internal config: use custom client-side commands even when the
234 /// client doesn't set the corresponding capability.
235 lens_forceCustomCommands: bool = "true",
237 /// Disable project auto-discovery in favor of explicitly specified set
240 /// Elements must be paths pointing to `Cargo.toml`,
241 /// `rust-project.json`, or JSON objects in `rust-project.json` format.
242 linkedProjects: Vec<ManifestOrProjectJson> = "[]",
244 /// Number of syntax trees rust-analyzer keeps in memory. Defaults to 128.
245 lruCapacity: Option<usize> = "null",
247 /// Whether to show `can't find Cargo.toml` error message.
248 notifications_cargoTomlNotFound: bool = "true",
250 /// Enable support for procedural macros, implies `#rust-analyzer.cargo.runBuildScripts#`.
251 procMacro_enable: bool = "true",
252 /// Internal config, path to proc-macro server executable (typically,
253 /// this is rust-analyzer itself, but we override this in tests).
254 procMacro_server: Option<PathBuf> = "null",
256 /// Command to be executed instead of 'cargo' for runnables.
257 runnables_overrideCargo: Option<String> = "null",
258 /// Additional arguments to be passed to cargo for runnables such as
259 /// tests or binaries. For example, it may be `--release`.
260 runnables_cargoExtraArgs: Vec<String> = "[]",
262 /// Path to the Cargo.toml of the rust compiler workspace, for usage in rustc_private
263 /// projects, or "discover" to try to automatically find it.
265 /// Any project which uses rust-analyzer with the rustcPrivate
266 /// crates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.
268 /// This option is not reloaded automatically; you must restart rust-analyzer for it to take effect.
269 rustcSource: Option<String> = "null",
271 /// Additional arguments to `rustfmt`.
272 rustfmt_extraArgs: Vec<String> = "[]",
273 /// Advanced option, fully override the command rust-analyzer uses for
275 rustfmt_overrideCommand: Option<Vec<String>> = "null",
276 /// Enables the use of rustfmt's unstable range formatting command for the
277 /// `textDocument/rangeFormatting` request. The rustfmt option is unstable and only
278 /// available on a nightly build.
279 rustfmt_enableRangeFormatting: bool = "false",
281 /// Workspace symbol search scope.
282 workspace_symbol_search_scope: WorkspaceSymbolSearchScopeDef = "\"workspace\"",
283 /// Workspace symbol search kind.
284 workspace_symbol_search_kind: WorkspaceSymbolSearchKindDef = "\"only_types\"",
288 impl Default for ConfigData {
289 fn default() -> Self {
290 ConfigData::from_json(serde_json::Value::Null)
294 #[derive(Debug, Clone)]
296 pub caps: lsp_types::ClientCapabilities,
298 detached_files: Vec<AbsPathBuf>,
299 pub discovered_projects: Option<Vec<ProjectManifest>>,
300 pub root_path: AbsPathBuf,
301 snippets: Vec<Snippet>,
304 #[derive(Debug, Clone, Eq, PartialEq)]
305 pub enum LinkedProject {
306 ProjectManifest(ProjectManifest),
307 InlineJsonProject(ProjectJson),
310 impl From<ProjectManifest> for LinkedProject {
311 fn from(v: ProjectManifest) -> Self {
312 LinkedProject::ProjectManifest(v)
316 impl From<ProjectJson> for LinkedProject {
317 fn from(v: ProjectJson) -> Self {
318 LinkedProject::InlineJsonProject(v)
322 #[derive(Clone, Debug, PartialEq, Eq)]
323 pub struct LensConfig {
326 pub implementations: bool,
327 pub method_refs: bool,
328 pub refs: bool, // for Struct, Enum, Union and Trait
332 pub fn any(&self) -> bool {
333 self.implementations || self.runnable() || self.references()
336 pub fn none(&self) -> bool {
340 pub fn runnable(&self) -> bool {
341 self.run || self.debug
344 pub fn references(&self) -> bool {
345 self.method_refs || self.refs
349 #[derive(Clone, Debug, PartialEq, Eq)]
350 pub struct HoverActionsConfig {
351 pub implementations: bool,
352 pub references: bool,
355 pub goto_type_def: bool,
358 impl HoverActionsConfig {
359 pub const NO_ACTIONS: Self = Self {
360 implementations: false,
364 goto_type_def: false,
367 pub fn any(&self) -> bool {
368 self.implementations || self.references || self.runnable() || self.goto_type_def
371 pub fn none(&self) -> bool {
375 pub fn runnable(&self) -> bool {
376 self.run || self.debug
380 #[derive(Debug, Clone)]
381 pub struct FilesConfig {
382 pub watcher: FilesWatcher,
383 pub exclude: Vec<AbsPathBuf>,
386 #[derive(Debug, Clone)]
387 pub enum FilesWatcher {
392 #[derive(Debug, Clone)]
393 pub struct NotificationsConfig {
394 pub cargo_toml_not_found: bool,
397 #[derive(Debug, Clone)]
398 pub enum RustfmtConfig {
399 Rustfmt { extra_args: Vec<String>, enable_range_formatting: bool },
400 CustomCommand { command: String, args: Vec<String> },
403 /// Configuration for runnable items, such as `main` function or tests.
404 #[derive(Debug, Clone)]
405 pub struct RunnablesConfig {
406 /// Custom command to be executed instead of `cargo` for runnables.
407 pub override_cargo: Option<String>,
408 /// Additional arguments for the `cargo`, e.g. `--release`.
409 pub cargo_extra_args: Vec<String>,
412 /// Configuration for workspace symbol search requests.
413 #[derive(Debug, Clone)]
414 pub struct WorkspaceSymbolConfig {
415 /// In what scope should the symbol be searched in.
416 pub search_scope: WorkspaceSymbolSearchScope,
417 /// What kind of symbol is being search for.
418 pub search_kind: WorkspaceSymbolSearchKind,
421 pub struct ClientCommandsConfig {
422 pub run_single: bool,
423 pub debug_single: bool,
424 pub show_reference: bool,
425 pub goto_location: bool,
426 pub trigger_parameter_hints: bool,
430 pub fn new(root_path: AbsPathBuf, caps: ClientCapabilities) -> Self {
433 data: ConfigData::default(),
434 detached_files: Vec::new(),
435 discovered_projects: None,
437 snippets: Default::default(),
440 pub fn update(&mut self, mut json: serde_json::Value) {
441 tracing::info!("updating config from JSON: {:#}", json);
442 if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
445 self.detached_files = get_field::<Vec<PathBuf>>(&mut json, "detachedFiles", None, "[]")
447 .map(AbsPathBuf::assert)
449 self.data = ConfigData::from_json(json);
450 self.snippets.clear();
451 for (name, def) in self.data.completion_snippets.iter() {
452 if def.prefix.is_empty() && def.postfix.is_empty() {
455 let scope = match def.scope {
456 SnippetScopeDef::Expr => SnippetScope::Expr,
457 SnippetScopeDef::Type => SnippetScope::Type,
458 SnippetScopeDef::Item => SnippetScope::Item,
464 def.description.as_ref().unwrap_or(name),
468 Some(snippet) => self.snippets.push(snippet),
469 None => tracing::info!("Invalid snippet {}", name),
474 pub fn json_schema() -> serde_json::Value {
475 ConfigData::json_schema()
481 || -> _ { Some($expr) }()
484 macro_rules! try_or {
485 ($expr:expr, $or:expr) => {
486 try_!($expr).unwrap_or($or)
491 pub fn linked_projects(&self) -> Vec<LinkedProject> {
492 if self.data.linkedProjects.is_empty() {
493 self.discovered_projects
498 .map(LinkedProject::from)
504 .filter_map(|linked_project| {
505 let res = match linked_project {
506 ManifestOrProjectJson::Manifest(it) => {
507 let path = self.root_path.join(it);
508 ProjectManifest::from_manifest_file(path)
510 tracing::error!("failed to load linked project: {}", e)
515 ManifestOrProjectJson::ProjectJson(it) => {
516 ProjectJson::new(&self.root_path, it.clone()).into()
525 pub fn detached_files(&self) -> &[AbsPathBuf] {
529 pub fn did_save_text_document_dynamic_registration(&self) -> bool {
531 try_or!(self.caps.text_document.as_ref()?.synchronization.clone()?, Default::default());
532 caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
534 pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
536 self.caps.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration?,
541 pub fn location_link(&self) -> bool {
542 try_or!(self.caps.text_document.as_ref()?.definition?.link_support?, false)
544 pub fn line_folding_only(&self) -> bool {
545 try_or!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?, false)
547 pub fn hierarchical_symbols(&self) -> bool {
554 .hierarchical_document_symbol_support?,
558 pub fn code_action_literals(&self) -> bool {
565 .code_action_literal_support
569 pub fn work_done_progress(&self) -> bool {
570 try_or!(self.caps.window.as_ref()?.work_done_progress?, false)
572 pub fn will_rename(&self) -> bool {
573 try_or!(self.caps.workspace.as_ref()?.file_operations.as_ref()?.will_rename?, false)
575 pub fn change_annotation_support(&self) -> bool {
582 .change_annotation_support
586 pub fn code_action_resolve(&self) -> bool {
600 .any(|it| it == "edit")
602 pub fn signature_help_label_offsets(&self) -> bool {
609 .signature_information
611 .parameter_information
613 .label_offset_support?,
617 pub fn offset_encoding(&self) -> OffsetEncoding {
618 if supports_utf8(&self.caps) {
621 OffsetEncoding::Utf16
625 fn experimental(&self, index: &'static str) -> bool {
626 try_or!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?, false)
628 pub fn code_action_group(&self) -> bool {
629 self.experimental("codeActionGroup")
631 pub fn server_status_notification(&self) -> bool {
632 self.experimental("serverStatusNotification")
635 pub fn publish_diagnostics(&self) -> bool {
636 self.data.diagnostics_enable
638 pub fn diagnostics(&self) -> DiagnosticsConfig {
640 disable_experimental: !self.data.diagnostics_enableExperimental,
641 disabled: self.data.diagnostics_disabled.clone(),
644 pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
645 DiagnosticsMapConfig {
646 remap_prefix: self.data.diagnostics_remapPrefix.clone(),
647 warnings_as_info: self.data.diagnostics_warningsAsInfo.clone(),
648 warnings_as_hint: self.data.diagnostics_warningsAsHint.clone(),
651 pub fn lru_capacity(&self) -> Option<usize> {
652 self.data.lruCapacity
654 pub fn proc_macro_srv(&self) -> Option<(AbsPathBuf, Vec<OsString>)> {
655 if !self.data.procMacro_enable {
658 let path = match &self.data.procMacro_server {
659 Some(it) => self.root_path.join(it),
660 None => AbsPathBuf::assert(std::env::current_exe().ok()?),
662 Some((path, vec!["proc-macro".into()]))
664 pub fn expand_proc_attr_macros(&self) -> bool {
665 self.data.experimental_procAttrMacros
667 pub fn files(&self) -> FilesConfig {
669 watcher: match self.data.files_watcher.as_str() {
670 "notify" => FilesWatcher::Notify,
671 "client" | _ => FilesWatcher::Client,
673 exclude: self.data.files_excludeDirs.iter().map(|it| self.root_path.join(it)).collect(),
676 pub fn notifications(&self) -> NotificationsConfig {
677 NotificationsConfig { cargo_toml_not_found: self.data.notifications_cargoTomlNotFound }
679 pub fn cargo_autoreload(&self) -> bool {
680 self.data.cargo_autoreload
682 pub fn run_build_scripts(&self) -> bool {
683 self.data.cargo_runBuildScripts || self.data.procMacro_enable
685 pub fn cargo(&self) -> CargoConfig {
686 let rustc_source = self.data.rustcSource.as_ref().map(|rustc_src| {
687 if rustc_src == "discover" {
688 RustcSource::Discover
690 RustcSource::Path(self.root_path.join(rustc_src))
695 no_default_features: self.data.cargo_noDefaultFeatures,
696 all_features: self.data.cargo_allFeatures,
697 features: self.data.cargo_features.clone(),
698 target: self.data.cargo_target.clone(),
699 no_sysroot: self.data.cargo_noSysroot,
701 unset_test_crates: UnsetTestCrates::Only(self.data.cargo_unsetTest.clone()),
702 wrap_rustc_in_build_scripts: self.data.cargo_useRustcWrapperForBuildScripts,
706 pub fn rustfmt(&self) -> RustfmtConfig {
707 match &self.data.rustfmt_overrideCommand {
708 Some(args) if !args.is_empty() => {
709 let mut args = args.clone();
710 let command = args.remove(0);
711 RustfmtConfig::CustomCommand { command, args }
713 Some(_) | None => RustfmtConfig::Rustfmt {
714 extra_args: self.data.rustfmt_extraArgs.clone(),
715 enable_range_formatting: self.data.rustfmt_enableRangeFormatting,
719 pub fn flycheck(&self) -> Option<FlycheckConfig> {
720 if !self.data.checkOnSave_enable {
723 let flycheck_config = match &self.data.checkOnSave_overrideCommand {
724 Some(args) if !args.is_empty() => {
725 let mut args = args.clone();
726 let command = args.remove(0);
727 FlycheckConfig::CustomCommand { command, args }
729 Some(_) | None => FlycheckConfig::CargoCommand {
730 command: self.data.checkOnSave_command.clone(),
735 .or_else(|| self.data.cargo_target.clone()),
736 all_targets: self.data.checkOnSave_allTargets,
737 no_default_features: self
739 .checkOnSave_noDefaultFeatures
740 .unwrap_or(self.data.cargo_noDefaultFeatures),
743 .checkOnSave_allFeatures
744 .unwrap_or(self.data.cargo_allFeatures),
747 .checkOnSave_features
749 .unwrap_or_else(|| self.data.cargo_features.clone()),
750 extra_args: self.data.checkOnSave_extraArgs.clone(),
753 Some(flycheck_config)
755 pub fn runnables(&self) -> RunnablesConfig {
757 override_cargo: self.data.runnables_overrideCargo.clone(),
758 cargo_extra_args: self.data.runnables_cargoExtraArgs.clone(),
761 pub fn inlay_hints(&self) -> InlayHintsConfig {
763 type_hints: self.data.inlayHints_typeHints,
764 parameter_hints: self.data.inlayHints_parameterHints,
765 chaining_hints: self.data.inlayHints_chainingHints,
766 max_length: self.data.inlayHints_maxLength,
769 fn insert_use_config(&self) -> InsertUseConfig {
771 granularity: match self.data.assist_importGranularity {
772 ImportGranularityDef::Preserve => ImportGranularity::Preserve,
773 ImportGranularityDef::Item => ImportGranularity::Item,
774 ImportGranularityDef::Crate => ImportGranularity::Crate,
775 ImportGranularityDef::Module => ImportGranularity::Module,
777 enforce_granularity: self.data.assist_importEnforceGranularity,
778 prefix_kind: match self.data.assist_importPrefix {
779 ImportPrefixDef::Plain => PrefixKind::Plain,
780 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
781 ImportPrefixDef::BySelf => PrefixKind::BySelf,
783 group: self.data.assist_importGroup,
784 skip_glob_imports: !self.data.assist_allowMergingIntoGlobImports,
787 pub fn completion(&self) -> CompletionConfig {
789 enable_postfix_completions: self.data.completion_postfix_enable,
790 enable_imports_on_the_fly: self.data.completion_autoimport_enable
791 && completion_item_edit_resolve(&self.caps),
792 enable_self_on_the_fly: self.data.completion_autoself_enable,
793 add_call_parenthesis: self.data.completion_addCallParenthesis,
794 add_call_argument_snippets: self.data.completion_addCallArgumentSnippets,
795 insert_use: self.insert_use_config(),
796 snippet_cap: SnippetCap::new(try_or!(
807 snippets: self.snippets.clone(),
810 pub fn assist(&self) -> AssistConfig {
812 snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
814 insert_use: self.insert_use_config(),
817 pub fn join_lines(&self) -> JoinLinesConfig {
819 join_else_if: self.data.joinLines_joinElseIf,
820 remove_trailing_comma: self.data.joinLines_removeTrailingComma,
821 unwrap_trivial_blocks: self.data.joinLines_unwrapTrivialBlock,
822 join_assignments: self.data.joinLines_joinAssignments,
825 pub fn call_info_full(&self) -> bool {
826 self.data.callInfo_full
828 pub fn lens(&self) -> LensConfig {
830 run: self.data.lens_enable && self.data.lens_run,
831 debug: self.data.lens_enable && self.data.lens_debug,
832 implementations: self.data.lens_enable && self.data.lens_implementations,
833 method_refs: self.data.lens_enable && self.data.lens_methodReferences,
834 refs: self.data.lens_enable && self.data.lens_references,
837 pub fn hover_actions(&self) -> HoverActionsConfig {
838 let enable = self.experimental("hoverActions") && self.data.hoverActions_enable;
840 implementations: enable && self.data.hoverActions_implementations,
841 references: enable && self.data.hoverActions_references,
842 run: enable && self.data.hoverActions_run,
843 debug: enable && self.data.hoverActions_debug,
844 goto_type_def: enable && self.data.hoverActions_gotoTypeDef,
847 pub fn highlighting_strings(&self) -> bool {
848 self.data.highlighting_strings
850 pub fn hover(&self) -> HoverConfig {
852 links_in_hover: self.data.hover_linksInHover,
853 documentation: self.data.hover_documentation.then(|| {
854 let is_markdown = try_or!(
865 .contains(&MarkupKind::Markdown);
867 HoverDocFormat::Markdown
869 HoverDocFormat::PlainText
875 pub fn workspace_symbol(&self) -> WorkspaceSymbolConfig {
876 WorkspaceSymbolConfig {
877 search_scope: match self.data.workspace_symbol_search_scope {
878 WorkspaceSymbolSearchScopeDef::Workspace => WorkspaceSymbolSearchScope::Workspace,
879 WorkspaceSymbolSearchScopeDef::WorkspaceAndDependencies => {
880 WorkspaceSymbolSearchScope::WorkspaceAndDependencies
883 search_kind: match self.data.workspace_symbol_search_kind {
884 WorkspaceSymbolSearchKindDef::OnlyTypes => WorkspaceSymbolSearchKind::OnlyTypes,
885 WorkspaceSymbolSearchKindDef::AllSymbols => WorkspaceSymbolSearchKind::AllSymbols,
890 pub fn semantic_tokens_refresh(&self) -> bool {
891 try_or!(self.caps.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support?, false)
893 pub fn code_lens_refresh(&self) -> bool {
894 try_or!(self.caps.workspace.as_ref()?.code_lens.as_ref()?.refresh_support?, false)
896 pub fn insert_replace_support(&self) -> bool {
905 .insert_replace_support?,
909 pub fn client_commands(&self) -> ClientCommandsConfig {
911 try_or!(self.caps.experimental.as_ref()?.get("commands")?, &serde_json::Value::Null);
912 let commands: Option<lsp_ext::ClientCommandOptions> =
913 serde_json::from_value(commands.clone()).ok();
914 let force = commands.is_none() && self.data.lens_forceCustomCommands;
915 let commands = commands.map(|it| it.commands).unwrap_or_default();
917 let get = |name: &str| commands.iter().any(|it| it == name) || force;
919 ClientCommandsConfig {
920 run_single: get("rust-analyzer.runSingle"),
921 debug_single: get("rust-analyzer.debugSingle"),
922 show_reference: get("rust-analyzer.showReferences"),
923 goto_location: get("rust-analyzer.gotoLocation"),
924 trigger_parameter_hints: get("editor.action.triggerParameterHints"),
928 pub fn highlight_related(&self) -> HighlightRelatedConfig {
929 HighlightRelatedConfig {
930 references: self.data.highlightRelated_references,
931 break_points: self.data.highlightRelated_breakPoints,
932 exit_points: self.data.highlightRelated_exitPoints,
933 yield_points: self.data.highlightRelated_yieldPoints,
938 #[derive(Deserialize, Debug, Clone, Copy)]
939 #[serde(rename_all = "snake_case")]
940 enum SnippetScopeDef {
946 impl Default for SnippetScopeDef {
947 fn default() -> Self {
948 SnippetScopeDef::Expr
952 #[derive(Deserialize, Debug, Clone, Default)]
955 #[serde(deserialize_with = "single_or_array")]
957 #[serde(deserialize_with = "single_or_array")]
958 postfix: Vec<String>,
959 description: Option<String>,
960 #[serde(deserialize_with = "single_or_array")]
962 #[serde(deserialize_with = "single_or_array")]
963 requires: Vec<String>,
964 scope: SnippetScopeDef,
967 fn single_or_array<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
969 D: serde::Deserializer<'de>,
973 impl<'de> serde::de::Visitor<'de> for SingleOrVec {
974 type Value = Vec<String>;
976 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
977 formatter.write_str("string or array of strings")
980 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
984 Ok(vec![value.to_owned()])
987 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
989 A: serde::de::SeqAccess<'de>,
991 Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
995 deserializer.deserialize_any(SingleOrVec)
998 #[derive(Deserialize, Debug, Clone)]
1000 enum ManifestOrProjectJson {
1002 ProjectJson(ProjectJsonData),
1005 #[derive(Deserialize, Debug, Clone)]
1006 #[serde(rename_all = "snake_case")]
1007 enum ImportGranularityDef {
1009 #[serde(alias = "none")]
1011 #[serde(alias = "full")]
1013 #[serde(alias = "last")]
1017 #[derive(Deserialize, Debug, Clone)]
1018 #[serde(rename_all = "snake_case")]
1019 enum ImportPrefixDef {
1021 #[serde(alias = "self")]
1023 #[serde(alias = "crate")]
1027 #[derive(Deserialize, Debug, Clone)]
1028 #[serde(rename_all = "snake_case")]
1029 enum WorkspaceSymbolSearchScopeDef {
1031 WorkspaceAndDependencies,
1034 #[derive(Deserialize, Debug, Clone)]
1035 #[serde(rename_all = "snake_case")]
1036 enum WorkspaceSymbolSearchKindDef {
1041 macro_rules! _config_data {
1042 (struct $name:ident {
1044 $(#[doc=$doc:literal])*
1045 $field:ident $(| $alias:ident)*: $ty:ty = $default:expr,
1048 #[allow(non_snake_case)]
1049 #[derive(Debug, Clone)]
1050 struct $name { $($field: $ty,)* }
1052 fn from_json(mut json: serde_json::Value) -> $name {
1057 None$(.or(Some(stringify!($alias))))*,
1063 fn json_schema() -> serde_json::Value {
1066 let field = stringify!($field);
1067 let ty = stringify!($ty);
1069 (field, ty, &[$($doc),*], $default)
1075 fn manual() -> String {
1078 let field = stringify!($field);
1079 let ty = stringify!($ty);
1081 (field, ty, &[$($doc),*], $default)
1088 use _config_data as config_data;
1090 fn get_field<T: DeserializeOwned>(
1091 json: &mut serde_json::Value,
1092 field: &'static str,
1093 alias: Option<&'static str>,
1096 let default = serde_json::from_str(default).unwrap();
1098 // XXX: check alias first, to work-around the VS Code where it pre-fills the
1099 // defaults instead of sending an empty object.
1102 .chain(iter::once(field))
1103 .find_map(move |field| {
1104 let mut pointer = field.replace('_', "/");
1105 pointer.insert(0, '/');
1106 json.pointer_mut(&pointer).and_then(|it| serde_json::from_value(it.take()).ok())
1111 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
1112 for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
1113 fn key(f: &str) -> &str {
1114 f.splitn(2, '_').next().unwrap()
1116 assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
1121 .map(|(field, ty, doc, default)| {
1122 let name = field.replace("_", ".");
1123 let name = format!("rust-analyzer.{}", name);
1124 let props = field_props(field, ty, doc, default);
1127 .collect::<serde_json::Map<_, _>>();
1131 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
1132 let doc = doc_comment_to_string(doc);
1133 let doc = doc.trim_end_matches('\n');
1135 doc.ends_with('.') && doc.starts_with(char::is_uppercase),
1136 "bad docs for {}: {:?}",
1140 let default = default.parse::<serde_json::Value>().unwrap();
1142 let mut map = serde_json::Map::default();
1144 ($($key:literal: $value:tt),*$(,)?) => {{$(
1145 map.insert($key.into(), serde_json::json!($value));
1148 set!("markdownDescription": doc);
1149 set!("default": default);
1152 "bool" => set!("type": "boolean"),
1153 "String" => set!("type": "string"),
1154 "Vec<String>" => set! {
1156 "items": { "type": "string" },
1158 "Vec<PathBuf>" => set! {
1160 "items": { "type": "string" },
1162 "FxHashSet<String>" => set! {
1164 "items": { "type": "string" },
1165 "uniqueItems": true,
1167 "FxHashMap<String, SnippetDef>" => set! {
1170 "FxHashMap<String, String>" => set! {
1173 "Option<usize>" => set! {
1174 "type": ["null", "integer"],
1177 "Option<String>" => set! {
1178 "type": ["null", "string"],
1180 "Option<PathBuf>" => set! {
1181 "type": ["null", "string"],
1183 "Option<bool>" => set! {
1184 "type": ["null", "boolean"],
1186 "Option<Vec<String>>" => set! {
1187 "type": ["null", "array"],
1188 "items": { "type": "string" },
1190 "MergeBehaviorDef" => set! {
1192 "enum": ["none", "crate", "module"],
1193 "enumDescriptions": [
1194 "Do not merge imports at all.",
1195 "Merge imports from the same crate into a single `use` statement.",
1196 "Merge imports from the same module into a single `use` statement."
1199 "ImportGranularityDef" => set! {
1201 "enum": ["preserve", "crate", "module", "item"],
1202 "enumDescriptions": [
1203 "Do not change the granularity of any imports and preserve the original structure written by the developer.",
1204 "Merge imports from the same crate into a single use statement. Conversely, imports from different crates are split into separate statements.",
1205 "Merge imports from the same module into a single use statement. Conversely, imports from different modules are split into separate statements.",
1206 "Flatten imports so that each has its own use statement."
1209 "ImportPrefixDef" => set! {
1216 "enumDescriptions": [
1217 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
1218 "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.",
1219 "Force import paths to be absolute by always starting them with `crate` or the extern crate name they come from."
1222 "Vec<ManifestOrProjectJson>" => set! {
1224 "items": { "type": ["string", "object"] },
1226 "WorkspaceSymbolSearchScopeDef" => set! {
1228 "enum": ["workspace", "workspace_and_dependencies"],
1229 "enumDescriptions": [
1230 "Search in current workspace only",
1231 "Search in current workspace and dependencies"
1234 "WorkspaceSymbolSearchKindDef" => set! {
1236 "enum": ["only_types", "all_symbols"],
1237 "enumDescriptions": [
1238 "Search for types only",
1239 "Search for all symbols kinds"
1242 _ => panic!("{}: {}", ty, default),
1249 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
1252 .map(|(field, _ty, doc, default)| {
1253 let name = format!("rust-analyzer.{}", field.replace("_", "."));
1254 let doc = doc_comment_to_string(*doc);
1255 format!("[[{}]]{} (default: `{}`)::\n+\n--\n{}--\n", name, name, default, doc)
1257 .collect::<String>()
1260 fn doc_comment_to_string(doc: &[&str]) -> String {
1261 doc.iter().map(|it| it.strip_prefix(' ').unwrap_or(it)).map(|it| format!("{}\n", it)).collect()
1268 use test_utils::{ensure_file_contents, project_root};
1273 fn generate_package_json_config() {
1274 let s = Config::json_schema();
1275 let schema = format!("{:#}", s);
1276 let mut schema = schema
1277 .trim_start_matches('{')
1278 .trim_end_matches('}')
1280 .replace("\n", "\n ")
1281 .trim_start_matches('\n')
1284 schema.push_str(",\n");
1286 let package_json_path = project_root().join("editors/code/package.json");
1287 let mut package_json = fs::read_to_string(&package_json_path).unwrap();
1289 let start_marker = " \"$generated-start\": {},\n";
1290 let end_marker = " \"$generated-end\": {}\n";
1292 let start = package_json.find(start_marker).unwrap() + start_marker.len();
1293 let end = package_json.find(end_marker).unwrap();
1295 let p = remove_ws(&package_json[start..end]);
1296 let s = remove_ws(&schema);
1297 if !p.contains(&s) {
1298 package_json.replace_range(start..end, &schema);
1299 ensure_file_contents(&package_json_path, &package_json)
1304 fn generate_config_documentation() {
1305 let docs_path = project_root().join("docs/user/generated_config.adoc");
1306 let expected = ConfigData::manual();
1307 ensure_file_contents(&docs_path, &expected);
1310 fn remove_ws(text: &str) -> String {
1311 text.replace(char::is_whitespace, "")