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, PostfixSnippet, PostfixSnippetScope,
16 Snippet, SnippetScope,
18 use ide_db::helpers::{
19 insert_use::{ImportGranularity, InsertUseConfig, PrefixKind},
22 use lsp_types::{ClientCapabilities, MarkupKind};
24 CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest, RustcSource, UnsetTestCrates,
26 use rustc_hash::{FxHashMap, FxHashSet};
27 use serde::{de::DeserializeOwned, Deserialize};
31 caps::completion_item_edit_resolve,
32 diagnostics::DiagnosticsMapConfig,
33 line_index::OffsetEncoding,
34 lsp_ext::supports_utf8,
35 lsp_ext::WorkspaceSymbolSearchScope,
36 lsp_ext::{self, WorkspaceSymbolSearchKind},
39 // Defines the server-side configuration of the rust-analyzer. We generate
40 // *parts* of VS Code's `package.json` config from this.
42 // However, editor specific config, which the server doesn't know about, should
43 // be specified directly in `package.json`.
45 // To deprecate an option by replacing it with another name use `new_name | `old_name` so that we keep
46 // parsing the old name.
49 /// How imports should be grouped into use statements.
50 assist_importGranularity |
51 assist_importMergeBehavior |
52 assist_importMergeBehaviour: ImportGranularityDef = "\"crate\"",
53 /// 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.
54 assist_importEnforceGranularity: bool = "false",
55 /// The path structure for newly inserted paths to use.
56 assist_importPrefix: ImportPrefixDef = "\"plain\"",
57 /// Group inserted imports by the https://rust-analyzer.github.io/manual.html#auto-import[following order]. Groups are separated by newlines.
58 assist_importGroup: bool = "true",
59 /// Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`.
60 assist_allowMergingIntoGlobImports: bool = "true",
62 /// Show function name and docs in parameter hints.
63 callInfo_full: bool = "true",
65 /// Automatically refresh project info via `cargo metadata` on
66 /// `Cargo.toml` changes.
67 cargo_autoreload: bool = "true",
68 /// Activate all available features (`--all-features`).
69 cargo_allFeatures: bool = "false",
70 /// Unsets `#[cfg(test)]` for the specified crates.
71 cargo_unsetTest: Vec<String> = "[\"core\"]",
72 /// List of features to activate.
73 cargo_features: Vec<String> = "[]",
74 /// Run build scripts (`build.rs`) for more precise code analysis.
75 cargo_runBuildScripts |
76 cargo_loadOutDirsFromCheck: bool = "true",
77 /// Use `RUSTC_WRAPPER=rust-analyzer` when running build scripts to
78 /// avoid compiling unnecessary things.
79 cargo_useRustcWrapperForBuildScripts: bool = "true",
80 /// Do not activate the `default` feature.
81 cargo_noDefaultFeatures: bool = "false",
82 /// Compilation target (target triple).
83 cargo_target: Option<String> = "null",
84 /// Internal config for debugging, disables loading of sysroot crates.
85 cargo_noSysroot: bool = "false",
87 /// Run specified `cargo check` command for diagnostics on save.
88 checkOnSave_enable: bool = "true",
89 /// Check with all features (`--all-features`).
90 /// Defaults to `#rust-analyzer.cargo.allFeatures#`.
91 checkOnSave_allFeatures: Option<bool> = "null",
92 /// Check all targets and tests (`--all-targets`).
93 checkOnSave_allTargets: bool = "true",
94 /// Cargo command to use for `cargo check`.
95 checkOnSave_command: String = "\"check\"",
96 /// Do not activate the `default` feature.
97 checkOnSave_noDefaultFeatures: Option<bool> = "null",
98 /// Check for a specific target. Defaults to
99 /// `#rust-analyzer.cargo.target#`.
100 checkOnSave_target: Option<String> = "null",
101 /// Extra arguments for `cargo check`.
102 checkOnSave_extraArgs: Vec<String> = "[]",
103 /// List of features to activate. Defaults to
104 /// `#rust-analyzer.cargo.features#`.
105 checkOnSave_features: Option<Vec<String>> = "null",
106 /// Advanced option, fully override the command rust-analyzer uses for
107 /// checking. The command should include `--message-format=json` or
109 checkOnSave_overrideCommand: Option<Vec<String>> = "null",
111 /// Whether to add argument snippets when completing functions.
112 /// Only applies when `#rust-analyzer.completion.addCallParenthesis#` is set.
113 completion_addCallArgumentSnippets: bool = "true",
114 /// Whether to add parenthesis when completing functions.
115 completion_addCallParenthesis: bool = "true",
116 /// Custom completion snippets.
117 completion_snippets: FxHashMap<String, SnippetDef> = "{}",
118 /// Whether to show postfix snippets like `dbg`, `if`, `not`, etc.
119 completion_postfix_enable: bool = "true",
120 /// Custom postfix completion snippets.
121 completion_postfix_snippets: FxHashMap<String, PostfixSnippetDef> = "{}",
122 /// Toggles the additional completions that automatically add imports when completed.
123 /// Note that your client must specify the `additionalTextEdits` LSP client capability to truly have this feature enabled.
124 completion_autoimport_enable: bool = "true",
125 /// Toggles the additional completions that automatically show method calls and field accesses
126 /// with `self` prefixed to them when inside a method.
127 completion_autoself_enable: bool = "true",
129 /// Whether to show native rust-analyzer diagnostics.
130 diagnostics_enable: bool = "true",
131 /// Whether to show experimental rust-analyzer diagnostics that might
132 /// have more false positives than usual.
133 diagnostics_enableExperimental: bool = "true",
134 /// List of rust-analyzer diagnostics to disable.
135 diagnostics_disabled: FxHashSet<String> = "[]",
136 /// Map of prefixes to be substituted when parsing diagnostic file paths.
137 /// This should be the reverse mapping of what is passed to `rustc` as `--remap-path-prefix`.
138 diagnostics_remapPrefix: FxHashMap<String, String> = "{}",
139 /// List of warnings that should be displayed with hint severity.
141 /// The warnings will be indicated by faded text or three dots in code
142 /// and will not show up in the `Problems Panel`.
143 diagnostics_warningsAsHint: Vec<String> = "[]",
144 /// List of warnings that should be displayed with info severity.
146 /// The warnings will be indicated by a blue squiggly underline in code
147 /// and a blue icon in the `Problems Panel`.
148 diagnostics_warningsAsInfo: Vec<String> = "[]",
150 /// Expand attribute macros.
151 experimental_procAttrMacros: bool = "true",
153 /// Controls file watching implementation.
154 files_watcher: String = "\"client\"",
155 /// These directories will be ignored by rust-analyzer. They are
156 /// relative to the workspace root, and globs are not supported. You may
157 /// also need to add the folders to Code's `files.watcherExclude`.
158 files_excludeDirs: Vec<PathBuf> = "[]",
160 /// Enables highlighting of related references while hovering your mouse above any identifier.
161 highlightRelated_references: bool = "true",
162 /// Enables highlighting of all exit points while hovering your mouse above any `return`, `?`, or return type arrow (`->`).
163 highlightRelated_exitPoints: bool = "true",
164 /// Enables highlighting of related references while hovering your mouse `break`, `loop`, `while`, or `for` keywords.
165 highlightRelated_breakPoints: bool = "true",
166 /// Enables highlighting of all break points for a loop or block context while hovering your mouse above any `async` or `await` keywords.
167 highlightRelated_yieldPoints: bool = "true",
169 /// Use semantic tokens for strings.
171 /// In some editors (e.g. vscode) semantic tokens override other highlighting grammars.
172 /// By disabling semantic tokens for strings, other grammars can be used to highlight
174 highlighting_strings: bool = "true",
176 /// Whether to show documentation on hover.
177 hover_documentation: bool = "true",
178 /// Use markdown syntax for links in hover.
180 hoverActions_linksInHover: bool = "true",
182 /// Whether to show `Debug` action. Only applies when
183 /// `#rust-analyzer.hoverActions.enable#` is set.
184 hoverActions_debug: bool = "true",
185 /// Whether to show HoverActions in Rust files.
186 hoverActions_enable: bool = "true",
187 /// Whether to show `Go to Type Definition` action. Only applies when
188 /// `#rust-analyzer.hoverActions.enable#` is set.
189 hoverActions_gotoTypeDef: bool = "true",
190 /// Whether to show `Implementations` action. Only applies when
191 /// `#rust-analyzer.hoverActions.enable#` is set.
192 hoverActions_implementations: bool = "true",
193 /// Whether to show `References` action. Only applies when
194 /// `#rust-analyzer.hoverActions.enable#` is set.
195 hoverActions_references: bool = "false",
196 /// Whether to show `Run` action. Only applies when
197 /// `#rust-analyzer.hoverActions.enable#` is set.
198 hoverActions_run: bool = "true",
200 /// Whether to show inlay type hints for method chains.
201 inlayHints_chainingHints: bool = "true",
202 /// Maximum length for inlay hints. Set to null to have an unlimited length.
203 inlayHints_maxLength: Option<usize> = "25",
204 /// Whether to show function parameter name inlay hints at the call
206 inlayHints_parameterHints: bool = "true",
207 /// Whether to show inlay type hints for variables.
208 inlayHints_typeHints: bool = "true",
210 /// Join lines inserts else between consecutive ifs.
211 joinLines_joinElseIf: bool = "true",
212 /// Join lines removes trailing commas.
213 joinLines_removeTrailingComma: bool = "true",
214 /// Join lines unwraps trivial blocks.
215 joinLines_unwrapTrivialBlock: bool = "true",
216 /// Join lines merges consecutive declaration and initialization of an assignment.
217 joinLines_joinAssignments: bool = "true",
219 /// Whether to show `Debug` lens. Only applies when
220 /// `#rust-analyzer.lens.enable#` is set.
221 lens_debug: bool = "true",
222 /// Whether to show CodeLens in Rust files.
223 lens_enable: bool = "true",
224 /// Whether to show `Implementations` lens. Only applies when
225 /// `#rust-analyzer.lens.enable#` is set.
226 lens_implementations: bool = "true",
227 /// Whether to show `Run` lens. Only applies when
228 /// `#rust-analyzer.lens.enable#` is set.
229 lens_run: bool = "true",
230 /// Whether to show `Method References` lens. Only applies when
231 /// `#rust-analyzer.lens.enable#` is set.
232 lens_methodReferences: bool = "false",
233 /// Whether to show `References` lens. Only applies when
234 /// `#rust-analyzer.lens.enable#` is set.
235 lens_references: bool = "false",
236 /// Internal config: use custom client-side commands even when the
237 /// client doesn't set the corresponding capability.
238 lens_forceCustomCommands: bool = "true",
240 /// Disable project auto-discovery in favor of explicitly specified set
243 /// Elements must be paths pointing to `Cargo.toml`,
244 /// `rust-project.json`, or JSON objects in `rust-project.json` format.
245 linkedProjects: Vec<ManifestOrProjectJson> = "[]",
247 /// Number of syntax trees rust-analyzer keeps in memory. Defaults to 128.
248 lruCapacity: Option<usize> = "null",
250 /// Whether to show `can't find Cargo.toml` error message.
251 notifications_cargoTomlNotFound: bool = "true",
253 /// Enable support for procedural macros, implies `#rust-analyzer.cargo.runBuildScripts#`.
254 procMacro_enable: bool = "true",
255 /// Internal config, path to proc-macro server executable (typically,
256 /// this is rust-analyzer itself, but we override this in tests).
257 procMacro_server: Option<PathBuf> = "null",
259 /// Command to be executed instead of 'cargo' for runnables.
260 runnables_overrideCargo: Option<String> = "null",
261 /// Additional arguments to be passed to cargo for runnables such as
262 /// tests or binaries. For example, it may be `--release`.
263 runnables_cargoExtraArgs: Vec<String> = "[]",
265 /// Path to the Cargo.toml of the rust compiler workspace, for usage in rustc_private
266 /// projects, or "discover" to try to automatically find it.
268 /// Any project which uses rust-analyzer with the rustcPrivate
269 /// crates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.
271 /// This option is not reloaded automatically; you must restart rust-analyzer for it to take effect.
272 rustcSource: Option<String> = "null",
274 /// Additional arguments to `rustfmt`.
275 rustfmt_extraArgs: Vec<String> = "[]",
276 /// Advanced option, fully override the command rust-analyzer uses for
278 rustfmt_overrideCommand: Option<Vec<String>> = "null",
279 /// Enables the use of rustfmt's unstable range formatting command for the
280 /// `textDocument/rangeFormatting` request. The rustfmt option is unstable and only
281 /// available on a nightly build.
282 rustfmt_enableRangeFormatting: bool = "false",
284 /// Workspace symbol search scope.
285 workspace_symbol_search_scope: WorskpaceSymbolSearchScopeDef = "\"workspace\"",
286 /// Workspace symbol search kind.
287 workspace_symbol_search_kind: WorskpaceSymbolSearchKindDef = "\"only_types\"",
291 impl Default for ConfigData {
292 fn default() -> Self {
293 ConfigData::from_json(serde_json::Value::Null)
297 #[derive(Debug, Clone)]
299 pub caps: lsp_types::ClientCapabilities,
301 detached_files: Vec<AbsPathBuf>,
302 pub discovered_projects: Option<Vec<ProjectManifest>>,
303 pub root_path: AbsPathBuf,
304 postfix_snippets: Vec<PostfixSnippet>,
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
336 pub fn any(&self) -> bool {
337 self.implementations || self.runnable() || self.references()
340 pub fn none(&self) -> bool {
344 pub fn runnable(&self) -> bool {
345 self.run || self.debug
348 pub fn references(&self) -> bool {
349 self.method_refs || self.refs
353 #[derive(Clone, Debug, PartialEq, Eq)]
354 pub struct HoverActionsConfig {
355 pub implementations: bool,
356 pub references: bool,
359 pub goto_type_def: bool,
362 impl HoverActionsConfig {
363 pub const NO_ACTIONS: Self = Self {
364 implementations: false,
368 goto_type_def: false,
371 pub fn any(&self) -> bool {
372 self.implementations || self.references || self.runnable() || self.goto_type_def
375 pub fn none(&self) -> bool {
379 pub fn runnable(&self) -> bool {
380 self.run || self.debug
384 #[derive(Debug, Clone)]
385 pub struct FilesConfig {
386 pub watcher: FilesWatcher,
387 pub exclude: Vec<AbsPathBuf>,
390 #[derive(Debug, Clone)]
391 pub enum FilesWatcher {
396 #[derive(Debug, Clone)]
397 pub struct NotificationsConfig {
398 pub cargo_toml_not_found: bool,
401 #[derive(Debug, Clone)]
402 pub enum RustfmtConfig {
403 Rustfmt { extra_args: Vec<String>, enable_range_formatting: bool },
404 CustomCommand { command: String, args: Vec<String> },
407 /// Configuration for runnable items, such as `main` function or tests.
408 #[derive(Debug, Clone)]
409 pub struct RunnablesConfig {
410 /// Custom command to be executed instead of `cargo` for runnables.
411 pub override_cargo: Option<String>,
412 /// Additional arguments for the `cargo`, e.g. `--release`.
413 pub cargo_extra_args: Vec<String>,
416 /// Configuration for workspace symbol search requests.
417 #[derive(Debug, Clone)]
418 pub struct WorkspaceSymbolConfig {
419 /// In what scope should the symbol be searched in.
420 pub search_scope: WorkspaceSymbolSearchScope,
421 /// What kind of symbol is being search for.
422 pub search_kind: WorkspaceSymbolSearchKind,
425 pub struct ClientCommandsConfig {
426 pub run_single: bool,
427 pub debug_single: bool,
428 pub show_reference: bool,
429 pub goto_location: bool,
430 pub trigger_parameter_hints: bool,
434 pub fn new(root_path: AbsPathBuf, caps: ClientCapabilities) -> Self {
437 data: ConfigData::default(),
438 detached_files: Vec::new(),
439 discovered_projects: None,
441 postfix_snippets: Default::default(),
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.postfix_snippets = self
457 .completion_postfix_snippets
459 .flat_map(|(label, desc)| {
465 desc.scope.map(|scope| match scope {
466 PostfixSnippetScopeDef::Expr => PostfixSnippetScope::Expr,
467 PostfixSnippetScopeDef::Type => PostfixSnippetScope::Type,
476 .flat_map(|(label, desc)| {
482 desc.scope.map(|scope| match scope {
483 SnippetScopeDef::Expr => SnippetScope::Expr,
484 SnippetScopeDef::Item => SnippetScope::Item,
491 pub fn json_schema() -> serde_json::Value {
492 ConfigData::json_schema()
498 || -> _ { Some($expr) }()
501 macro_rules! try_or {
502 ($expr:expr, $or:expr) => {
503 try_!($expr).unwrap_or($or)
508 pub fn linked_projects(&self) -> Vec<LinkedProject> {
509 if self.data.linkedProjects.is_empty() {
510 self.discovered_projects
515 .map(LinkedProject::from)
521 .filter_map(|linked_project| {
522 let res = match linked_project {
523 ManifestOrProjectJson::Manifest(it) => {
524 let path = self.root_path.join(it);
525 ProjectManifest::from_manifest_file(path)
527 tracing::error!("failed to load linked project: {}", e)
532 ManifestOrProjectJson::ProjectJson(it) => {
533 ProjectJson::new(&self.root_path, it.clone()).into()
542 pub fn detached_files(&self) -> &[AbsPathBuf] {
546 pub fn did_save_text_document_dynamic_registration(&self) -> bool {
548 try_or!(self.caps.text_document.as_ref()?.synchronization.clone()?, Default::default());
549 caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
551 pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
553 self.caps.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration?,
558 pub fn location_link(&self) -> bool {
559 try_or!(self.caps.text_document.as_ref()?.definition?.link_support?, false)
561 pub fn line_folding_only(&self) -> bool {
562 try_or!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?, false)
564 pub fn hierarchical_symbols(&self) -> bool {
571 .hierarchical_document_symbol_support?,
575 pub fn code_action_literals(&self) -> bool {
582 .code_action_literal_support
586 pub fn work_done_progress(&self) -> bool {
587 try_or!(self.caps.window.as_ref()?.work_done_progress?, false)
589 pub fn will_rename(&self) -> bool {
590 try_or!(self.caps.workspace.as_ref()?.file_operations.as_ref()?.will_rename?, false)
592 pub fn change_annotation_support(&self) -> bool {
599 .change_annotation_support
603 pub fn code_action_resolve(&self) -> bool {
617 .any(|it| it == "edit")
619 pub fn signature_help_label_offsets(&self) -> bool {
626 .signature_information
628 .parameter_information
630 .label_offset_support?,
634 pub fn offset_encoding(&self) -> OffsetEncoding {
635 if supports_utf8(&self.caps) {
638 OffsetEncoding::Utf16
642 fn experimental(&self, index: &'static str) -> bool {
643 try_or!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?, false)
645 pub fn code_action_group(&self) -> bool {
646 self.experimental("codeActionGroup")
648 pub fn server_status_notification(&self) -> bool {
649 self.experimental("serverStatusNotification")
652 pub fn publish_diagnostics(&self) -> bool {
653 self.data.diagnostics_enable
655 pub fn diagnostics(&self) -> DiagnosticsConfig {
657 disable_experimental: !self.data.diagnostics_enableExperimental,
658 disabled: self.data.diagnostics_disabled.clone(),
661 pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
662 DiagnosticsMapConfig {
663 remap_prefix: self.data.diagnostics_remapPrefix.clone(),
664 warnings_as_info: self.data.diagnostics_warningsAsInfo.clone(),
665 warnings_as_hint: self.data.diagnostics_warningsAsHint.clone(),
668 pub fn lru_capacity(&self) -> Option<usize> {
669 self.data.lruCapacity
671 pub fn proc_macro_srv(&self) -> Option<(AbsPathBuf, Vec<OsString>)> {
672 if !self.data.procMacro_enable {
675 let path = match &self.data.procMacro_server {
676 Some(it) => self.root_path.join(it),
677 None => AbsPathBuf::assert(std::env::current_exe().ok()?),
679 Some((path, vec!["proc-macro".into()]))
681 pub fn expand_proc_attr_macros(&self) -> bool {
682 self.data.experimental_procAttrMacros
684 pub fn files(&self) -> FilesConfig {
686 watcher: match self.data.files_watcher.as_str() {
687 "notify" => FilesWatcher::Notify,
688 "client" | _ => FilesWatcher::Client,
690 exclude: self.data.files_excludeDirs.iter().map(|it| self.root_path.join(it)).collect(),
693 pub fn notifications(&self) -> NotificationsConfig {
694 NotificationsConfig { cargo_toml_not_found: self.data.notifications_cargoTomlNotFound }
696 pub fn cargo_autoreload(&self) -> bool {
697 self.data.cargo_autoreload
699 pub fn run_build_scripts(&self) -> bool {
700 self.data.cargo_runBuildScripts || self.data.procMacro_enable
702 pub fn cargo(&self) -> CargoConfig {
703 let rustc_source = self.data.rustcSource.as_ref().map(|rustc_src| {
704 if rustc_src == "discover" {
705 RustcSource::Discover
707 RustcSource::Path(self.root_path.join(rustc_src))
712 no_default_features: self.data.cargo_noDefaultFeatures,
713 all_features: self.data.cargo_allFeatures,
714 features: self.data.cargo_features.clone(),
715 target: self.data.cargo_target.clone(),
716 no_sysroot: self.data.cargo_noSysroot,
718 unset_test_crates: UnsetTestCrates::Only(self.data.cargo_unsetTest.clone()),
719 wrap_rustc_in_build_scripts: self.data.cargo_useRustcWrapperForBuildScripts,
723 pub fn rustfmt(&self) -> RustfmtConfig {
724 match &self.data.rustfmt_overrideCommand {
725 Some(args) if !args.is_empty() => {
726 let mut args = args.clone();
727 let command = args.remove(0);
728 RustfmtConfig::CustomCommand { command, args }
730 Some(_) | None => RustfmtConfig::Rustfmt {
731 extra_args: self.data.rustfmt_extraArgs.clone(),
732 enable_range_formatting: self.data.rustfmt_enableRangeFormatting,
736 pub fn flycheck(&self) -> Option<FlycheckConfig> {
737 if !self.data.checkOnSave_enable {
740 let flycheck_config = match &self.data.checkOnSave_overrideCommand {
741 Some(args) if !args.is_empty() => {
742 let mut args = args.clone();
743 let command = args.remove(0);
744 FlycheckConfig::CustomCommand { command, args }
746 Some(_) | None => FlycheckConfig::CargoCommand {
747 command: self.data.checkOnSave_command.clone(),
752 .or_else(|| self.data.cargo_target.clone()),
753 all_targets: self.data.checkOnSave_allTargets,
754 no_default_features: self
756 .checkOnSave_noDefaultFeatures
757 .unwrap_or(self.data.cargo_noDefaultFeatures),
760 .checkOnSave_allFeatures
761 .unwrap_or(self.data.cargo_allFeatures),
764 .checkOnSave_features
766 .unwrap_or_else(|| self.data.cargo_features.clone()),
767 extra_args: self.data.checkOnSave_extraArgs.clone(),
770 Some(flycheck_config)
772 pub fn runnables(&self) -> RunnablesConfig {
774 override_cargo: self.data.runnables_overrideCargo.clone(),
775 cargo_extra_args: self.data.runnables_cargoExtraArgs.clone(),
778 pub fn inlay_hints(&self) -> InlayHintsConfig {
780 type_hints: self.data.inlayHints_typeHints,
781 parameter_hints: self.data.inlayHints_parameterHints,
782 chaining_hints: self.data.inlayHints_chainingHints,
783 max_length: self.data.inlayHints_maxLength,
786 fn insert_use_config(&self) -> InsertUseConfig {
788 granularity: match self.data.assist_importGranularity {
789 ImportGranularityDef::Preserve => ImportGranularity::Preserve,
790 ImportGranularityDef::Item => ImportGranularity::Item,
791 ImportGranularityDef::Crate => ImportGranularity::Crate,
792 ImportGranularityDef::Module => ImportGranularity::Module,
794 enforce_granularity: self.data.assist_importEnforceGranularity,
795 prefix_kind: match self.data.assist_importPrefix {
796 ImportPrefixDef::Plain => PrefixKind::Plain,
797 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
798 ImportPrefixDef::BySelf => PrefixKind::BySelf,
800 group: self.data.assist_importGroup,
801 skip_glob_imports: !self.data.assist_allowMergingIntoGlobImports,
804 pub fn completion(&self) -> CompletionConfig {
806 enable_postfix_completions: self.data.completion_postfix_enable,
807 enable_imports_on_the_fly: self.data.completion_autoimport_enable
808 && completion_item_edit_resolve(&self.caps),
809 enable_self_on_the_fly: self.data.completion_autoself_enable,
810 add_call_parenthesis: self.data.completion_addCallParenthesis,
811 add_call_argument_snippets: self.data.completion_addCallArgumentSnippets,
812 insert_use: self.insert_use_config(),
813 snippet_cap: SnippetCap::new(try_or!(
824 postfix_snippets: self.postfix_snippets.clone(),
825 snippets: self.snippets.clone(),
828 pub fn assist(&self) -> AssistConfig {
830 snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
832 insert_use: self.insert_use_config(),
835 pub fn join_lines(&self) -> JoinLinesConfig {
837 join_else_if: self.data.joinLines_joinElseIf,
838 remove_trailing_comma: self.data.joinLines_removeTrailingComma,
839 unwrap_trivial_blocks: self.data.joinLines_unwrapTrivialBlock,
840 join_assignments: self.data.joinLines_joinAssignments,
843 pub fn call_info_full(&self) -> bool {
844 self.data.callInfo_full
846 pub fn lens(&self) -> LensConfig {
848 run: self.data.lens_enable && self.data.lens_run,
849 debug: self.data.lens_enable && self.data.lens_debug,
850 implementations: self.data.lens_enable && self.data.lens_implementations,
851 method_refs: self.data.lens_enable && self.data.lens_methodReferences,
852 refs: self.data.lens_enable && self.data.lens_references,
855 pub fn hover_actions(&self) -> HoverActionsConfig {
856 let enable = self.experimental("hoverActions") && self.data.hoverActions_enable;
858 implementations: enable && self.data.hoverActions_implementations,
859 references: enable && self.data.hoverActions_references,
860 run: enable && self.data.hoverActions_run,
861 debug: enable && self.data.hoverActions_debug,
862 goto_type_def: enable && self.data.hoverActions_gotoTypeDef,
865 pub fn highlighting_strings(&self) -> bool {
866 self.data.highlighting_strings
868 pub fn hover(&self) -> HoverConfig {
870 links_in_hover: self.data.hover_linksInHover,
871 documentation: self.data.hover_documentation.then(|| {
872 let is_markdown = try_or!(
883 .contains(&MarkupKind::Markdown);
885 HoverDocFormat::Markdown
887 HoverDocFormat::PlainText
893 pub fn workspace_symbol(&self) -> WorkspaceSymbolConfig {
894 WorkspaceSymbolConfig {
895 search_scope: match self.data.workspace_symbol_search_scope {
896 WorskpaceSymbolSearchScopeDef::Workspace => WorkspaceSymbolSearchScope::Workspace,
897 WorskpaceSymbolSearchScopeDef::WorkspaceAndDependencies => {
898 WorkspaceSymbolSearchScope::WorkspaceAndDependencies
901 search_kind: match self.data.workspace_symbol_search_kind {
902 WorskpaceSymbolSearchKindDef::OnlyTypes => WorkspaceSymbolSearchKind::OnlyTypes,
903 WorskpaceSymbolSearchKindDef::AllSymbols => WorkspaceSymbolSearchKind::AllSymbols,
908 pub fn semantic_tokens_refresh(&self) -> bool {
909 try_or!(self.caps.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support?, false)
911 pub fn code_lens_refresh(&self) -> bool {
912 try_or!(self.caps.workspace.as_ref()?.code_lens.as_ref()?.refresh_support?, false)
914 pub fn insert_replace_support(&self) -> bool {
923 .insert_replace_support?,
927 pub fn client_commands(&self) -> ClientCommandsConfig {
929 try_or!(self.caps.experimental.as_ref()?.get("commands")?, &serde_json::Value::Null);
930 let commands: Option<lsp_ext::ClientCommandOptions> =
931 serde_json::from_value(commands.clone()).ok();
932 let force = commands.is_none() && self.data.lens_forceCustomCommands;
933 let commands = commands.map(|it| it.commands).unwrap_or_default();
935 let get = |name: &str| commands.iter().any(|it| it == name) || force;
937 ClientCommandsConfig {
938 run_single: get("rust-analyzer.runSingle"),
939 debug_single: get("rust-analyzer.debugSingle"),
940 show_reference: get("rust-analyzer.showReferences"),
941 goto_location: get("rust-analyzer.gotoLocation"),
942 trigger_parameter_hints: get("editor.action.triggerParameterHints"),
946 pub fn highlight_related(&self) -> HighlightRelatedConfig {
947 HighlightRelatedConfig {
948 references: self.data.highlightRelated_references,
949 break_points: self.data.highlightRelated_breakPoints,
950 exit_points: self.data.highlightRelated_exitPoints,
951 yield_points: self.data.highlightRelated_yieldPoints,
956 #[derive(Deserialize, Debug, Clone, Copy)]
957 enum PostfixSnippetScopeDef {
962 #[derive(Deserialize, Debug, Clone, Copy)]
963 enum SnippetScopeDef {
968 #[derive(Deserialize, Debug, Clone)]
969 struct PostfixSnippetDef {
970 #[serde(deserialize_with = "single_or_array")]
971 description: Vec<String>,
972 #[serde(deserialize_with = "single_or_array")]
973 snippet: Vec<String>,
974 #[serde(deserialize_with = "single_or_array")]
975 requires: Vec<String>,
976 scope: Option<PostfixSnippetScopeDef>,
979 #[derive(Deserialize, Debug, Clone)]
981 #[serde(deserialize_with = "single_or_array")]
982 description: Vec<String>,
983 #[serde(deserialize_with = "single_or_array")]
984 snippet: Vec<String>,
985 #[serde(deserialize_with = "single_or_array")]
986 requires: Vec<String>,
987 scope: Option<SnippetScopeDef>,
990 fn single_or_array<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
992 D: serde::Deserializer<'de>,
996 impl<'de> serde::de::Visitor<'de> for SingleOrVec {
997 type Value = Vec<String>;
999 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
1000 formatter.write_str("string or array of strings")
1003 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1005 E: serde::de::Error,
1007 Ok(vec![value.to_owned()])
1010 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1012 A: serde::de::SeqAccess<'de>,
1014 Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
1018 deserializer.deserialize_any(SingleOrVec)
1021 #[derive(Deserialize, Debug, Clone)]
1023 enum ManifestOrProjectJson {
1025 ProjectJson(ProjectJsonData),
1028 #[derive(Deserialize, Debug, Clone)]
1029 #[serde(rename_all = "snake_case")]
1030 enum ImportGranularityDef {
1032 #[serde(alias = "none")]
1034 #[serde(alias = "full")]
1036 #[serde(alias = "last")]
1040 #[derive(Deserialize, Debug, Clone)]
1041 #[serde(rename_all = "snake_case")]
1042 enum ImportPrefixDef {
1044 #[serde(alias = "self")]
1046 #[serde(alias = "crate")]
1050 #[derive(Deserialize, Debug, Clone)]
1051 #[serde(rename_all = "snake_case")]
1052 enum WorskpaceSymbolSearchScopeDef {
1054 WorkspaceAndDependencies,
1057 #[derive(Deserialize, Debug, Clone)]
1058 #[serde(rename_all = "snake_case")]
1059 enum WorskpaceSymbolSearchKindDef {
1064 macro_rules! _config_data {
1065 (struct $name:ident {
1067 $(#[doc=$doc:literal])*
1068 $field:ident $(| $alias:ident)*: $ty:ty = $default:expr,
1071 #[allow(non_snake_case)]
1072 #[derive(Debug, Clone)]
1073 struct $name { $($field: $ty,)* }
1075 fn from_json(mut json: serde_json::Value) -> $name {
1080 None$(.or(Some(stringify!($alias))))*,
1086 fn json_schema() -> serde_json::Value {
1089 let field = stringify!($field);
1090 let ty = stringify!($ty);
1092 (field, ty, &[$($doc),*], $default)
1098 fn manual() -> String {
1101 let field = stringify!($field);
1102 let ty = stringify!($ty);
1104 (field, ty, &[$($doc),*], $default)
1111 use _config_data as config_data;
1113 fn get_field<T: DeserializeOwned>(
1114 json: &mut serde_json::Value,
1115 field: &'static str,
1116 alias: Option<&'static str>,
1119 let default = serde_json::from_str(default).unwrap();
1121 // XXX: check alias first, to work-around the VS Code where it pre-fills the
1122 // defaults instead of sending an empty object.
1125 .chain(iter::once(field))
1126 .find_map(move |field| {
1127 let mut pointer = field.replace('_', "/");
1128 pointer.insert(0, '/');
1129 json.pointer_mut(&pointer).and_then(|it| serde_json::from_value(it.take()).ok())
1134 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
1135 for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
1136 fn key(f: &str) -> &str {
1137 f.splitn(2, '_').next().unwrap()
1139 assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
1144 .map(|(field, ty, doc, default)| {
1145 let name = field.replace("_", ".");
1146 let name = format!("rust-analyzer.{}", name);
1147 let props = field_props(field, ty, doc, default);
1150 .collect::<serde_json::Map<_, _>>();
1154 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
1155 let doc = doc_comment_to_string(doc);
1156 let doc = doc.trim_end_matches('\n');
1158 doc.ends_with('.') && doc.starts_with(char::is_uppercase),
1159 "bad docs for {}: {:?}",
1163 let default = default.parse::<serde_json::Value>().unwrap();
1165 let mut map = serde_json::Map::default();
1167 ($($key:literal: $value:tt),*$(,)?) => {{$(
1168 map.insert($key.into(), serde_json::json!($value));
1171 set!("markdownDescription": doc);
1172 set!("default": default);
1175 "bool" => set!("type": "boolean"),
1176 "String" => set!("type": "string"),
1177 "Vec<String>" => set! {
1179 "items": { "type": "string" },
1181 "Vec<PathBuf>" => set! {
1183 "items": { "type": "string" },
1185 "FxHashSet<String>" => set! {
1187 "items": { "type": "string" },
1188 "uniqueItems": true,
1190 "FxHashMap<String, String>" => set! {
1193 "Option<usize>" => set! {
1194 "type": ["null", "integer"],
1197 "Option<String>" => set! {
1198 "type": ["null", "string"],
1200 "Option<PathBuf>" => set! {
1201 "type": ["null", "string"],
1203 "Option<bool>" => set! {
1204 "type": ["null", "boolean"],
1206 "Option<Vec<String>>" => set! {
1207 "type": ["null", "array"],
1208 "items": { "type": "string" },
1210 "MergeBehaviorDef" => set! {
1212 "enum": ["none", "crate", "module"],
1213 "enumDescriptions": [
1214 "Do not merge imports at all.",
1215 "Merge imports from the same crate into a single `use` statement.",
1216 "Merge imports from the same module into a single `use` statement."
1219 "ImportGranularityDef" => set! {
1221 "enum": ["preserve", "crate", "module", "item"],
1222 "enumDescriptions": [
1223 "Do not change the granularity of any imports and preserve the original structure written by the developer.",
1224 "Merge imports from the same crate into a single use statement. Conversely, imports from different crates are split into separate statements.",
1225 "Merge imports from the same module into a single use statement. Conversely, imports from different modules are split into separate statements.",
1226 "Flatten imports so that each has its own use statement."
1229 "ImportPrefixDef" => set! {
1236 "enumDescriptions": [
1237 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
1238 "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.",
1239 "Force import paths to be absolute by always starting them with `crate` or the extern crate name they come from."
1242 "Vec<ManifestOrProjectJson>" => set! {
1244 "items": { "type": ["string", "object"] },
1246 "WorskpaceSymbolSearchScopeDef" => set! {
1248 "enum": ["workspace", "workspace_and_dependencies"],
1249 "enumDescriptions": [
1250 "Search in current workspace only",
1251 "Search in current workspace and dependencies"
1254 "WorskpaceSymbolSearchKindDef" => set! {
1256 "enum": ["only_types", "all_symbols"],
1257 "enumDescriptions": [
1258 "Search for types only",
1259 "Search for all symbols kinds"
1262 _ => panic!("{}: {}", ty, default),
1269 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
1272 .map(|(field, _ty, doc, default)| {
1273 let name = format!("rust-analyzer.{}", field.replace("_", "."));
1274 let doc = doc_comment_to_string(*doc);
1275 format!("[[{}]]{} (default: `{}`)::\n+\n--\n{}--\n", name, name, default, doc)
1277 .collect::<String>()
1280 fn doc_comment_to_string(doc: &[&str]) -> String {
1281 doc.iter().map(|it| it.strip_prefix(' ').unwrap_or(it)).map(|it| format!("{}\n", it)).collect()
1288 use test_utils::{ensure_file_contents, project_root};
1293 fn generate_package_json_config() {
1294 let s = Config::json_schema();
1295 let schema = format!("{:#}", s);
1296 let mut schema = schema
1297 .trim_start_matches('{')
1298 .trim_end_matches('}')
1300 .replace("\n", "\n ")
1301 .trim_start_matches('\n')
1304 schema.push_str(",\n");
1306 let package_json_path = project_root().join("editors/code/package.json");
1307 let mut package_json = fs::read_to_string(&package_json_path).unwrap();
1309 let start_marker = " \"$generated-start\": {},\n";
1310 let end_marker = " \"$generated-end\": {}\n";
1312 let start = package_json.find(start_marker).unwrap() + start_marker.len();
1313 let end = package_json.find(end_marker).unwrap();
1315 let p = remove_ws(&package_json[start..end]);
1316 let s = remove_ws(&schema);
1317 if !p.contains(&s) {
1318 package_json.replace_range(start..end, &schema);
1319 ensure_file_contents(&package_json_path, &package_json)
1324 fn generate_config_documentation() {
1325 let docs_path = project_root().join("docs/user/generated_config.adoc");
1326 let expected = ConfigData::manual();
1327 ensure_file_contents(&docs_path, &expected);
1330 fn remove_ws(text: &str) -> String {
1331 text.replace(char::is_whitespace, "")