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",
206 /// Whether to hide inlay hints for constructors.
207 inlayHints_hideNamedConstructorHints: bool = "false",
209 /// Join lines inserts else between consecutive ifs.
210 joinLines_joinElseIf: bool = "true",
211 /// Join lines removes trailing commas.
212 joinLines_removeTrailingComma: bool = "true",
213 /// Join lines unwraps trivial blocks.
214 joinLines_unwrapTrivialBlock: bool = "true",
215 /// Join lines merges consecutive declaration and initialization of an assignment.
216 joinLines_joinAssignments: bool = "true",
218 /// Whether to show `Debug` lens. Only applies when
219 /// `#rust-analyzer.lens.enable#` is set.
220 lens_debug: bool = "true",
221 /// Whether to show CodeLens in Rust files.
222 lens_enable: bool = "true",
223 /// Whether to show `Implementations` lens. Only applies when
224 /// `#rust-analyzer.lens.enable#` is set.
225 lens_implementations: bool = "true",
226 /// Whether to show `Run` lens. Only applies when
227 /// `#rust-analyzer.lens.enable#` is set.
228 lens_run: bool = "true",
229 /// Whether to show `Method References` lens. Only applies when
230 /// `#rust-analyzer.lens.enable#` is set.
231 lens_methodReferences: bool = "false",
232 /// Whether to show `References` lens for Struct, Enum, Union and Trait.
233 /// Only applies when `#rust-analyzer.lens.enable#` is set.
234 lens_references: bool = "false",
235 /// Whether to show `References` lens for Enum Variants.
236 /// Only applies when `#rust-analyzer.lens.enable#` is set.
237 lens_enumVariantReferences: bool = "false",
238 /// Internal config: use custom client-side commands even when the
239 /// client doesn't set the corresponding capability.
240 lens_forceCustomCommands: bool = "true",
242 /// Disable project auto-discovery in favor of explicitly specified set
245 /// Elements must be paths pointing to `Cargo.toml`,
246 /// `rust-project.json`, or JSON objects in `rust-project.json` format.
247 linkedProjects: Vec<ManifestOrProjectJson> = "[]",
249 /// Number of syntax trees rust-analyzer keeps in memory. Defaults to 128.
250 lruCapacity: Option<usize> = "null",
252 /// Whether to show `can't find Cargo.toml` error message.
253 notifications_cargoTomlNotFound: bool = "true",
255 /// Enable support for procedural macros, implies `#rust-analyzer.cargo.runBuildScripts#`.
256 procMacro_enable: bool = "true",
257 /// Internal config, path to proc-macro server executable (typically,
258 /// this is rust-analyzer itself, but we override this in tests).
259 procMacro_server: Option<PathBuf> = "null",
261 /// Command to be executed instead of 'cargo' for runnables.
262 runnables_overrideCargo: Option<String> = "null",
263 /// Additional arguments to be passed to cargo for runnables such as
264 /// tests or binaries. For example, it may be `--release`.
265 runnables_cargoExtraArgs: Vec<String> = "[]",
267 /// Path to the Cargo.toml of the rust compiler workspace, for usage in rustc_private
268 /// projects, or "discover" to try to automatically find it if the `rustc-dev` component
271 /// Any project which uses rust-analyzer with the rustcPrivate
272 /// crates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.
274 /// This option does not take effect until rust-analyzer is restarted.
275 rustcSource: Option<String> = "null",
277 /// Additional arguments to `rustfmt`.
278 rustfmt_extraArgs: Vec<String> = "[]",
279 /// Advanced option, fully override the command rust-analyzer uses for
281 rustfmt_overrideCommand: Option<Vec<String>> = "null",
282 /// Enables the use of rustfmt's unstable range formatting command for the
283 /// `textDocument/rangeFormatting` request. The rustfmt option is unstable and only
284 /// available on a nightly build.
285 rustfmt_enableRangeFormatting: bool = "false",
287 /// Workspace symbol search scope.
288 workspace_symbol_search_scope: WorkspaceSymbolSearchScopeDef = "\"workspace\"",
289 /// Workspace symbol search kind.
290 workspace_symbol_search_kind: WorkspaceSymbolSearchKindDef = "\"only_types\"",
294 impl Default for ConfigData {
295 fn default() -> Self {
296 ConfigData::from_json(serde_json::Value::Null)
300 #[derive(Debug, Clone)]
302 pub caps: lsp_types::ClientCapabilities,
304 detached_files: Vec<AbsPathBuf>,
305 pub discovered_projects: Option<Vec<ProjectManifest>>,
306 pub root_path: AbsPathBuf,
307 snippets: Vec<Snippet>,
310 #[derive(Debug, Clone, Eq, PartialEq)]
311 pub enum LinkedProject {
312 ProjectManifest(ProjectManifest),
313 InlineJsonProject(ProjectJson),
316 impl From<ProjectManifest> for LinkedProject {
317 fn from(v: ProjectManifest) -> Self {
318 LinkedProject::ProjectManifest(v)
322 impl From<ProjectJson> for LinkedProject {
323 fn from(v: ProjectJson) -> Self {
324 LinkedProject::InlineJsonProject(v)
328 #[derive(Clone, Debug, PartialEq, Eq)]
329 pub struct LensConfig {
332 pub implementations: bool,
333 pub method_refs: bool,
334 pub refs: bool, // for Struct, Enum, Union and Trait
335 pub enum_variant_refs: bool,
339 pub fn any(&self) -> bool {
340 self.implementations || self.runnable() || self.references()
343 pub fn none(&self) -> bool {
347 pub fn runnable(&self) -> bool {
348 self.run || self.debug
351 pub fn references(&self) -> bool {
352 self.method_refs || self.refs || self.enum_variant_refs
356 #[derive(Clone, Debug, PartialEq, Eq)]
357 pub struct HoverActionsConfig {
358 pub implementations: bool,
359 pub references: bool,
362 pub goto_type_def: bool,
365 impl HoverActionsConfig {
366 pub const NO_ACTIONS: Self = Self {
367 implementations: false,
371 goto_type_def: false,
374 pub fn any(&self) -> bool {
375 self.implementations || self.references || self.runnable() || self.goto_type_def
378 pub fn none(&self) -> bool {
382 pub fn runnable(&self) -> bool {
383 self.run || self.debug
387 #[derive(Debug, Clone)]
388 pub struct FilesConfig {
389 pub watcher: FilesWatcher,
390 pub exclude: Vec<AbsPathBuf>,
393 #[derive(Debug, Clone)]
394 pub enum FilesWatcher {
399 #[derive(Debug, Clone)]
400 pub struct NotificationsConfig {
401 pub cargo_toml_not_found: bool,
404 #[derive(Debug, Clone)]
405 pub enum RustfmtConfig {
406 Rustfmt { extra_args: Vec<String>, enable_range_formatting: bool },
407 CustomCommand { command: String, args: Vec<String> },
410 /// Configuration for runnable items, such as `main` function or tests.
411 #[derive(Debug, Clone)]
412 pub struct RunnablesConfig {
413 /// Custom command to be executed instead of `cargo` for runnables.
414 pub override_cargo: Option<String>,
415 /// Additional arguments for the `cargo`, e.g. `--release`.
416 pub cargo_extra_args: Vec<String>,
419 /// Configuration for workspace symbol search requests.
420 #[derive(Debug, Clone)]
421 pub struct WorkspaceSymbolConfig {
422 /// In what scope should the symbol be searched in.
423 pub search_scope: WorkspaceSymbolSearchScope,
424 /// What kind of symbol is being search for.
425 pub search_kind: WorkspaceSymbolSearchKind,
428 pub struct ClientCommandsConfig {
429 pub run_single: bool,
430 pub debug_single: bool,
431 pub show_reference: bool,
432 pub goto_location: bool,
433 pub trigger_parameter_hints: bool,
437 pub fn new(root_path: AbsPathBuf, caps: ClientCapabilities) -> Self {
440 data: ConfigData::default(),
441 detached_files: Vec::new(),
442 discovered_projects: None,
444 snippets: Default::default(),
447 pub fn update(&mut self, mut json: serde_json::Value) {
448 tracing::info!("updating config from JSON: {:#}", json);
449 if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
452 self.detached_files = get_field::<Vec<PathBuf>>(&mut json, "detachedFiles", None, "[]")
454 .map(AbsPathBuf::assert)
456 self.data = ConfigData::from_json(json);
457 self.snippets.clear();
458 for (name, def) in self.data.completion_snippets.iter() {
459 if def.prefix.is_empty() && def.postfix.is_empty() {
462 let scope = match def.scope {
463 SnippetScopeDef::Expr => SnippetScope::Expr,
464 SnippetScopeDef::Type => SnippetScope::Type,
465 SnippetScopeDef::Item => SnippetScope::Item,
471 def.description.as_ref().unwrap_or(name),
475 Some(snippet) => self.snippets.push(snippet),
476 None => tracing::info!("Invalid snippet {}", name),
481 pub fn json_schema() -> serde_json::Value {
482 ConfigData::json_schema()
488 || -> _ { Some($expr) }()
491 macro_rules! try_or {
492 ($expr:expr, $or:expr) => {
493 try_!($expr).unwrap_or($or)
498 pub fn linked_projects(&self) -> Vec<LinkedProject> {
499 if self.data.linkedProjects.is_empty() {
500 self.discovered_projects
505 .map(LinkedProject::from)
511 .filter_map(|linked_project| {
512 let res = match linked_project {
513 ManifestOrProjectJson::Manifest(it) => {
514 let path = self.root_path.join(it);
515 ProjectManifest::from_manifest_file(path)
517 tracing::error!("failed to load linked project: {}", e)
522 ManifestOrProjectJson::ProjectJson(it) => {
523 ProjectJson::new(&self.root_path, it.clone()).into()
532 pub fn detached_files(&self) -> &[AbsPathBuf] {
536 pub fn did_save_text_document_dynamic_registration(&self) -> bool {
538 try_or!(self.caps.text_document.as_ref()?.synchronization.clone()?, Default::default());
539 caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
541 pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
543 self.caps.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration?,
548 pub fn location_link(&self) -> bool {
549 try_or!(self.caps.text_document.as_ref()?.definition?.link_support?, false)
551 pub fn line_folding_only(&self) -> bool {
552 try_or!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?, false)
554 pub fn hierarchical_symbols(&self) -> bool {
561 .hierarchical_document_symbol_support?,
565 pub fn code_action_literals(&self) -> bool {
572 .code_action_literal_support
576 pub fn work_done_progress(&self) -> bool {
577 try_or!(self.caps.window.as_ref()?.work_done_progress?, false)
579 pub fn will_rename(&self) -> bool {
580 try_or!(self.caps.workspace.as_ref()?.file_operations.as_ref()?.will_rename?, false)
582 pub fn change_annotation_support(&self) -> bool {
589 .change_annotation_support
593 pub fn code_action_resolve(&self) -> bool {
607 .any(|it| it == "edit")
609 pub fn signature_help_label_offsets(&self) -> bool {
616 .signature_information
618 .parameter_information
620 .label_offset_support?,
624 pub fn offset_encoding(&self) -> OffsetEncoding {
625 if supports_utf8(&self.caps) {
628 OffsetEncoding::Utf16
632 fn experimental(&self, index: &'static str) -> bool {
633 try_or!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?, false)
635 pub fn code_action_group(&self) -> bool {
636 self.experimental("codeActionGroup")
638 pub fn server_status_notification(&self) -> bool {
639 self.experimental("serverStatusNotification")
642 pub fn publish_diagnostics(&self) -> bool {
643 self.data.diagnostics_enable
645 pub fn diagnostics(&self) -> DiagnosticsConfig {
647 disable_experimental: !self.data.diagnostics_enableExperimental,
648 disabled: self.data.diagnostics_disabled.clone(),
651 pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
652 DiagnosticsMapConfig {
653 remap_prefix: self.data.diagnostics_remapPrefix.clone(),
654 warnings_as_info: self.data.diagnostics_warningsAsInfo.clone(),
655 warnings_as_hint: self.data.diagnostics_warningsAsHint.clone(),
658 pub fn lru_capacity(&self) -> Option<usize> {
659 self.data.lruCapacity
661 pub fn proc_macro_srv(&self) -> Option<(AbsPathBuf, Vec<OsString>)> {
662 if !self.data.procMacro_enable {
665 let path = match &self.data.procMacro_server {
666 Some(it) => self.root_path.join(it),
667 None => AbsPathBuf::assert(std::env::current_exe().ok()?),
669 Some((path, vec!["proc-macro".into()]))
671 pub fn expand_proc_attr_macros(&self) -> bool {
672 self.data.experimental_procAttrMacros
674 pub fn files(&self) -> FilesConfig {
676 watcher: match self.data.files_watcher.as_str() {
677 "notify" => FilesWatcher::Notify,
678 "client" | _ => FilesWatcher::Client,
680 exclude: self.data.files_excludeDirs.iter().map(|it| self.root_path.join(it)).collect(),
683 pub fn notifications(&self) -> NotificationsConfig {
684 NotificationsConfig { cargo_toml_not_found: self.data.notifications_cargoTomlNotFound }
686 pub fn cargo_autoreload(&self) -> bool {
687 self.data.cargo_autoreload
689 pub fn run_build_scripts(&self) -> bool {
690 self.data.cargo_runBuildScripts || self.data.procMacro_enable
692 pub fn cargo(&self) -> CargoConfig {
693 let rustc_source = self.data.rustcSource.as_ref().map(|rustc_src| {
694 if rustc_src == "discover" {
695 RustcSource::Discover
697 RustcSource::Path(self.root_path.join(rustc_src))
702 no_default_features: self.data.cargo_noDefaultFeatures,
703 all_features: self.data.cargo_allFeatures,
704 features: self.data.cargo_features.clone(),
705 target: self.data.cargo_target.clone(),
706 no_sysroot: self.data.cargo_noSysroot,
708 unset_test_crates: UnsetTestCrates::Only(self.data.cargo_unsetTest.clone()),
709 wrap_rustc_in_build_scripts: self.data.cargo_useRustcWrapperForBuildScripts,
713 pub fn rustfmt(&self) -> RustfmtConfig {
714 match &self.data.rustfmt_overrideCommand {
715 Some(args) if !args.is_empty() => {
716 let mut args = args.clone();
717 let command = args.remove(0);
718 RustfmtConfig::CustomCommand { command, args }
720 Some(_) | None => RustfmtConfig::Rustfmt {
721 extra_args: self.data.rustfmt_extraArgs.clone(),
722 enable_range_formatting: self.data.rustfmt_enableRangeFormatting,
726 pub fn flycheck(&self) -> Option<FlycheckConfig> {
727 if !self.data.checkOnSave_enable {
730 let flycheck_config = match &self.data.checkOnSave_overrideCommand {
731 Some(args) if !args.is_empty() => {
732 let mut args = args.clone();
733 let command = args.remove(0);
734 FlycheckConfig::CustomCommand { command, args }
736 Some(_) | None => FlycheckConfig::CargoCommand {
737 command: self.data.checkOnSave_command.clone(),
742 .or_else(|| self.data.cargo_target.clone()),
743 all_targets: self.data.checkOnSave_allTargets,
744 no_default_features: self
746 .checkOnSave_noDefaultFeatures
747 .unwrap_or(self.data.cargo_noDefaultFeatures),
750 .checkOnSave_allFeatures
751 .unwrap_or(self.data.cargo_allFeatures),
754 .checkOnSave_features
756 .unwrap_or_else(|| self.data.cargo_features.clone()),
757 extra_args: self.data.checkOnSave_extraArgs.clone(),
760 Some(flycheck_config)
762 pub fn runnables(&self) -> RunnablesConfig {
764 override_cargo: self.data.runnables_overrideCargo.clone(),
765 cargo_extra_args: self.data.runnables_cargoExtraArgs.clone(),
768 pub fn inlay_hints(&self) -> InlayHintsConfig {
770 type_hints: self.data.inlayHints_typeHints,
771 parameter_hints: self.data.inlayHints_parameterHints,
772 chaining_hints: self.data.inlayHints_chainingHints,
773 hide_named_constructor_hints: self.data.inlayHints_hideNamedConstructorHints,
774 max_length: self.data.inlayHints_maxLength,
777 fn insert_use_config(&self) -> InsertUseConfig {
779 granularity: match self.data.assist_importGranularity {
780 ImportGranularityDef::Preserve => ImportGranularity::Preserve,
781 ImportGranularityDef::Item => ImportGranularity::Item,
782 ImportGranularityDef::Crate => ImportGranularity::Crate,
783 ImportGranularityDef::Module => ImportGranularity::Module,
785 enforce_granularity: self.data.assist_importEnforceGranularity,
786 prefix_kind: match self.data.assist_importPrefix {
787 ImportPrefixDef::Plain => PrefixKind::Plain,
788 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
789 ImportPrefixDef::BySelf => PrefixKind::BySelf,
791 group: self.data.assist_importGroup,
792 skip_glob_imports: !self.data.assist_allowMergingIntoGlobImports,
795 pub fn completion(&self) -> CompletionConfig {
797 enable_postfix_completions: self.data.completion_postfix_enable,
798 enable_imports_on_the_fly: self.data.completion_autoimport_enable
799 && completion_item_edit_resolve(&self.caps),
800 enable_self_on_the_fly: self.data.completion_autoself_enable,
801 add_call_parenthesis: self.data.completion_addCallParenthesis,
802 add_call_argument_snippets: self.data.completion_addCallArgumentSnippets,
803 insert_use: self.insert_use_config(),
804 snippet_cap: SnippetCap::new(try_or!(
815 snippets: self.snippets.clone(),
818 pub fn assist(&self) -> AssistConfig {
820 snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
822 insert_use: self.insert_use_config(),
825 pub fn join_lines(&self) -> JoinLinesConfig {
827 join_else_if: self.data.joinLines_joinElseIf,
828 remove_trailing_comma: self.data.joinLines_removeTrailingComma,
829 unwrap_trivial_blocks: self.data.joinLines_unwrapTrivialBlock,
830 join_assignments: self.data.joinLines_joinAssignments,
833 pub fn call_info_full(&self) -> bool {
834 self.data.callInfo_full
836 pub fn lens(&self) -> LensConfig {
838 run: self.data.lens_enable && self.data.lens_run,
839 debug: self.data.lens_enable && self.data.lens_debug,
840 implementations: self.data.lens_enable && self.data.lens_implementations,
841 method_refs: self.data.lens_enable && self.data.lens_methodReferences,
842 refs: self.data.lens_enable && self.data.lens_references,
843 enum_variant_refs: self.data.lens_enable && self.data.lens_enumVariantReferences,
846 pub fn hover_actions(&self) -> HoverActionsConfig {
847 let enable = self.experimental("hoverActions") && self.data.hoverActions_enable;
849 implementations: enable && self.data.hoverActions_implementations,
850 references: enable && self.data.hoverActions_references,
851 run: enable && self.data.hoverActions_run,
852 debug: enable && self.data.hoverActions_debug,
853 goto_type_def: enable && self.data.hoverActions_gotoTypeDef,
856 pub fn highlighting_strings(&self) -> bool {
857 self.data.highlighting_strings
859 pub fn hover(&self) -> HoverConfig {
861 links_in_hover: self.data.hover_linksInHover,
862 documentation: self.data.hover_documentation.then(|| {
863 let is_markdown = try_or!(
874 .contains(&MarkupKind::Markdown);
876 HoverDocFormat::Markdown
878 HoverDocFormat::PlainText
884 pub fn workspace_symbol(&self) -> WorkspaceSymbolConfig {
885 WorkspaceSymbolConfig {
886 search_scope: match self.data.workspace_symbol_search_scope {
887 WorkspaceSymbolSearchScopeDef::Workspace => WorkspaceSymbolSearchScope::Workspace,
888 WorkspaceSymbolSearchScopeDef::WorkspaceAndDependencies => {
889 WorkspaceSymbolSearchScope::WorkspaceAndDependencies
892 search_kind: match self.data.workspace_symbol_search_kind {
893 WorkspaceSymbolSearchKindDef::OnlyTypes => WorkspaceSymbolSearchKind::OnlyTypes,
894 WorkspaceSymbolSearchKindDef::AllSymbols => WorkspaceSymbolSearchKind::AllSymbols,
899 pub fn semantic_tokens_refresh(&self) -> bool {
900 try_or!(self.caps.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support?, false)
902 pub fn code_lens_refresh(&self) -> bool {
903 try_or!(self.caps.workspace.as_ref()?.code_lens.as_ref()?.refresh_support?, false)
905 pub fn insert_replace_support(&self) -> bool {
914 .insert_replace_support?,
918 pub fn client_commands(&self) -> ClientCommandsConfig {
920 try_or!(self.caps.experimental.as_ref()?.get("commands")?, &serde_json::Value::Null);
921 let commands: Option<lsp_ext::ClientCommandOptions> =
922 serde_json::from_value(commands.clone()).ok();
923 let force = commands.is_none() && self.data.lens_forceCustomCommands;
924 let commands = commands.map(|it| it.commands).unwrap_or_default();
926 let get = |name: &str| commands.iter().any(|it| it == name) || force;
928 ClientCommandsConfig {
929 run_single: get("rust-analyzer.runSingle"),
930 debug_single: get("rust-analyzer.debugSingle"),
931 show_reference: get("rust-analyzer.showReferences"),
932 goto_location: get("rust-analyzer.gotoLocation"),
933 trigger_parameter_hints: get("editor.action.triggerParameterHints"),
937 pub fn highlight_related(&self) -> HighlightRelatedConfig {
938 HighlightRelatedConfig {
939 references: self.data.highlightRelated_references,
940 break_points: self.data.highlightRelated_breakPoints,
941 exit_points: self.data.highlightRelated_exitPoints,
942 yield_points: self.data.highlightRelated_yieldPoints,
947 #[derive(Deserialize, Debug, Clone, Copy)]
948 #[serde(rename_all = "snake_case")]
949 enum SnippetScopeDef {
955 impl Default for SnippetScopeDef {
956 fn default() -> Self {
957 SnippetScopeDef::Expr
961 #[derive(Deserialize, Debug, Clone, Default)]
964 #[serde(deserialize_with = "single_or_array")]
966 #[serde(deserialize_with = "single_or_array")]
967 postfix: Vec<String>,
968 description: Option<String>,
969 #[serde(deserialize_with = "single_or_array")]
971 #[serde(deserialize_with = "single_or_array")]
972 requires: Vec<String>,
973 scope: SnippetScopeDef,
976 fn single_or_array<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
978 D: serde::Deserializer<'de>,
982 impl<'de> serde::de::Visitor<'de> for SingleOrVec {
983 type Value = Vec<String>;
985 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
986 formatter.write_str("string or array of strings")
989 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
993 Ok(vec![value.to_owned()])
996 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
998 A: serde::de::SeqAccess<'de>,
1000 Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
1004 deserializer.deserialize_any(SingleOrVec)
1007 #[derive(Deserialize, Debug, Clone)]
1009 enum ManifestOrProjectJson {
1011 ProjectJson(ProjectJsonData),
1014 #[derive(Deserialize, Debug, Clone)]
1015 #[serde(rename_all = "snake_case")]
1016 enum ImportGranularityDef {
1018 #[serde(alias = "none")]
1020 #[serde(alias = "full")]
1022 #[serde(alias = "last")]
1026 #[derive(Deserialize, Debug, Clone)]
1027 #[serde(rename_all = "snake_case")]
1028 enum ImportPrefixDef {
1030 #[serde(alias = "self")]
1032 #[serde(alias = "crate")]
1036 #[derive(Deserialize, Debug, Clone)]
1037 #[serde(rename_all = "snake_case")]
1038 enum WorkspaceSymbolSearchScopeDef {
1040 WorkspaceAndDependencies,
1043 #[derive(Deserialize, Debug, Clone)]
1044 #[serde(rename_all = "snake_case")]
1045 enum WorkspaceSymbolSearchKindDef {
1050 macro_rules! _config_data {
1051 (struct $name:ident {
1053 $(#[doc=$doc:literal])*
1054 $field:ident $(| $alias:ident)*: $ty:ty = $default:expr,
1057 #[allow(non_snake_case)]
1058 #[derive(Debug, Clone)]
1059 struct $name { $($field: $ty,)* }
1061 fn from_json(mut json: serde_json::Value) -> $name {
1066 None$(.or(Some(stringify!($alias))))*,
1072 fn json_schema() -> serde_json::Value {
1075 let field = stringify!($field);
1076 let ty = stringify!($ty);
1078 (field, ty, &[$($doc),*], $default)
1084 fn manual() -> String {
1087 let field = stringify!($field);
1088 let ty = stringify!($ty);
1090 (field, ty, &[$($doc),*], $default)
1097 use _config_data as config_data;
1099 fn get_field<T: DeserializeOwned>(
1100 json: &mut serde_json::Value,
1101 field: &'static str,
1102 alias: Option<&'static str>,
1105 let default = serde_json::from_str(default).unwrap();
1107 // XXX: check alias first, to work-around the VS Code where it pre-fills the
1108 // defaults instead of sending an empty object.
1111 .chain(iter::once(field))
1112 .find_map(move |field| {
1113 let mut pointer = field.replace('_', "/");
1114 pointer.insert(0, '/');
1115 json.pointer_mut(&pointer).and_then(|it| serde_json::from_value(it.take()).ok())
1120 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
1121 for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
1122 fn key(f: &str) -> &str {
1123 f.splitn(2, '_').next().unwrap()
1125 assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
1130 .map(|(field, ty, doc, default)| {
1131 let name = field.replace("_", ".");
1132 let name = format!("rust-analyzer.{}", name);
1133 let props = field_props(field, ty, doc, default);
1136 .collect::<serde_json::Map<_, _>>();
1140 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
1141 let doc = doc_comment_to_string(doc);
1142 let doc = doc.trim_end_matches('\n');
1144 doc.ends_with('.') && doc.starts_with(char::is_uppercase),
1145 "bad docs for {}: {:?}",
1149 let default = default.parse::<serde_json::Value>().unwrap();
1151 let mut map = serde_json::Map::default();
1153 ($($key:literal: $value:tt),*$(,)?) => {{$(
1154 map.insert($key.into(), serde_json::json!($value));
1157 set!("markdownDescription": doc);
1158 set!("default": default);
1161 "bool" => set!("type": "boolean"),
1162 "String" => set!("type": "string"),
1163 "Vec<String>" => set! {
1165 "items": { "type": "string" },
1167 "Vec<PathBuf>" => set! {
1169 "items": { "type": "string" },
1171 "FxHashSet<String>" => set! {
1173 "items": { "type": "string" },
1174 "uniqueItems": true,
1176 "FxHashMap<String, SnippetDef>" => set! {
1179 "FxHashMap<String, String>" => set! {
1182 "Option<usize>" => set! {
1183 "type": ["null", "integer"],
1186 "Option<String>" => set! {
1187 "type": ["null", "string"],
1189 "Option<PathBuf>" => set! {
1190 "type": ["null", "string"],
1192 "Option<bool>" => set! {
1193 "type": ["null", "boolean"],
1195 "Option<Vec<String>>" => set! {
1196 "type": ["null", "array"],
1197 "items": { "type": "string" },
1199 "MergeBehaviorDef" => set! {
1201 "enum": ["none", "crate", "module"],
1202 "enumDescriptions": [
1203 "Do not merge imports at all.",
1204 "Merge imports from the same crate into a single `use` statement.",
1205 "Merge imports from the same module into a single `use` statement."
1208 "ImportGranularityDef" => set! {
1210 "enum": ["preserve", "crate", "module", "item"],
1211 "enumDescriptions": [
1212 "Do not change the granularity of any imports and preserve the original structure written by the developer.",
1213 "Merge imports from the same crate into a single use statement. Conversely, imports from different crates are split into separate statements.",
1214 "Merge imports from the same module into a single use statement. Conversely, imports from different modules are split into separate statements.",
1215 "Flatten imports so that each has its own use statement."
1218 "ImportPrefixDef" => set! {
1225 "enumDescriptions": [
1226 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
1227 "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.",
1228 "Force import paths to be absolute by always starting them with `crate` or the extern crate name they come from."
1231 "Vec<ManifestOrProjectJson>" => set! {
1233 "items": { "type": ["string", "object"] },
1235 "WorkspaceSymbolSearchScopeDef" => set! {
1237 "enum": ["workspace", "workspace_and_dependencies"],
1238 "enumDescriptions": [
1239 "Search in current workspace only",
1240 "Search in current workspace and dependencies"
1243 "WorkspaceSymbolSearchKindDef" => set! {
1245 "enum": ["only_types", "all_symbols"],
1246 "enumDescriptions": [
1247 "Search for types only",
1248 "Search for all symbols kinds"
1251 _ => panic!("{}: {}", ty, default),
1258 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
1261 .map(|(field, _ty, doc, default)| {
1262 let name = format!("rust-analyzer.{}", field.replace("_", "."));
1263 let doc = doc_comment_to_string(*doc);
1264 format!("[[{}]]{} (default: `{}`)::\n+\n--\n{}--\n", name, name, default, doc)
1266 .collect::<String>()
1269 fn doc_comment_to_string(doc: &[&str]) -> String {
1270 doc.iter().map(|it| it.strip_prefix(' ').unwrap_or(it)).map(|it| format!("{}\n", it)).collect()
1277 use test_utils::{ensure_file_contents, project_root};
1282 fn generate_package_json_config() {
1283 let s = Config::json_schema();
1284 let schema = format!("{:#}", s);
1285 let mut schema = schema
1286 .trim_start_matches('{')
1287 .trim_end_matches('}')
1289 .replace("\n", "\n ")
1290 .trim_start_matches('\n')
1293 schema.push_str(",\n");
1295 // Transform the asciidoc form link to markdown style.
1297 // https://link[text] => [text](https://link)
1298 let url_matches = schema.match_indices("https://");
1299 let mut url_offsets = url_matches.map(|(idx, _)| idx).collect::<Vec<usize>>();
1300 url_offsets.reverse();
1301 for idx in url_offsets {
1302 let link = &schema[idx..];
1303 // matching on whitespace to ignore normal links
1304 if let Some(link_end) = link.find(|c| c == ' ' || c == '[') {
1305 if link.chars().nth(link_end) == Some('[') {
1306 if let Some(link_text_end) = link.find(']') {
1307 let link_text = link[link_end..(link_text_end + 1)].to_string();
1309 schema.replace_range((idx + link_end)..(idx + link_text_end + 1), "");
1310 schema.insert(idx, '(');
1311 schema.insert(idx + link_end + 1, ')');
1312 schema.insert_str(idx, &link_text);
1318 let package_json_path = project_root().join("editors/code/package.json");
1319 let mut package_json = fs::read_to_string(&package_json_path).unwrap();
1321 let start_marker = " \"$generated-start\": {},\n";
1322 let end_marker = " \"$generated-end\": {}\n";
1324 let start = package_json.find(start_marker).unwrap() + start_marker.len();
1325 let end = package_json.find(end_marker).unwrap();
1327 let p = remove_ws(&package_json[start..end]);
1328 let s = remove_ws(&schema);
1329 if !p.contains(&s) {
1330 package_json.replace_range(start..end, &schema);
1331 ensure_file_contents(&package_json_path, &package_json)
1336 fn generate_config_documentation() {
1337 let docs_path = project_root().join("docs/user/generated_config.adoc");
1338 let expected = ConfigData::manual();
1339 ensure_file_contents(&docs_path, &expected);
1342 fn remove_ws(text: &str) -> String {
1343 text.replace(char::is_whitespace, "")