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::{convert::TryFrom, ffi::OsString, iter, path::PathBuf};
12 use flycheck::FlycheckConfig;
14 use ide::{AssistConfig, CompletionConfig, DiagnosticsConfig, HoverConfig, InlayHintsConfig};
15 use ide_db::helpers::{
16 insert_use::{InsertUseConfig, MergeBehavior},
19 use itertools::Itertools;
20 use lsp_types::{ClientCapabilities, MarkupKind};
21 use project_model::{CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest};
22 use rustc_hash::FxHashSet;
23 use serde::{de::DeserializeOwned, Deserialize};
26 use crate::{caps::completion_item_edit_resolve, diagnostics::DiagnosticsMapConfig};
30 /// The strategy to use when inserting new imports or merging imports.
31 assist_importMergeBehavior |
32 assist_importMergeBehaviour: MergeBehaviorDef = "\"full\"",
33 /// The path structure for newly inserted paths to use.
34 assist_importPrefix: ImportPrefixDef = "\"plain\"",
36 /// Show function name and docs in parameter hints.
37 callInfo_full: bool = "true",
39 /// Automatically refresh project info via `cargo metadata` on
40 /// `Cargo.toml` changes.
41 cargo_autoreload: bool = "true",
42 /// Activate all available features.
43 cargo_allFeatures: bool = "false",
44 /// List of features to activate.
45 cargo_features: Vec<String> = "[]",
46 /// Run `cargo check` on startup to get the correct value for package
48 cargo_loadOutDirsFromCheck: bool = "false",
49 /// Do not activate the `default` feature.
50 cargo_noDefaultFeatures: bool = "false",
51 /// Compilation target (target triple).
52 cargo_target: Option<String> = "null",
53 /// Internal config for debugging, disables loading of sysroot crates.
54 cargo_noSysroot: bool = "false",
56 /// Run specified `cargo check` command for diagnostics on save.
57 checkOnSave_enable: bool = "true",
58 /// Check with all features (will be passed as `--all-features`).
59 /// Defaults to `#rust-analyzer.cargo.allFeatures#`.
60 checkOnSave_allFeatures: Option<bool> = "null",
61 /// Check all targets and tests (will be passed as `--all-targets`).
62 checkOnSave_allTargets: bool = "true",
63 /// Cargo command to use for `cargo check`.
64 checkOnSave_command: String = "\"check\"",
65 /// Do not activate the `default` feature.
66 checkOnSave_noDefaultFeatures: Option<bool> = "null",
67 /// Check for a specific target. Defaults to
68 /// `#rust-analyzer.cargo.target#`.
69 checkOnSave_target: Option<String> = "null",
70 /// Extra arguments for `cargo check`.
71 checkOnSave_extraArgs: Vec<String> = "[]",
72 /// List of features to activate. Defaults to
73 /// `#rust-analyzer.cargo.features#`.
74 checkOnSave_features: Option<Vec<String>> = "null",
75 /// Advanced option, fully override the command rust-analyzer uses for
76 /// checking. The command should include `--message-format=json` or
78 checkOnSave_overrideCommand: Option<Vec<String>> = "null",
80 /// Whether to add argument snippets when completing functions.
81 completion_addCallArgumentSnippets: bool = "true",
82 /// Whether to add parenthesis when completing functions.
83 completion_addCallParenthesis: bool = "true",
84 /// Whether to show postfix snippets like `dbg`, `if`, `not`, etc.
85 completion_postfix_enable: bool = "true",
86 /// Toggles the additional completions that automatically add imports when completed.
87 /// Note that your client must specify the `additionalTextEdits` LSP client capability to truly have this feature enabled.
88 completion_autoimport_enable: bool = "true",
90 /// Whether to show native rust-analyzer diagnostics.
91 diagnostics_enable: bool = "true",
92 /// Whether to show experimental rust-analyzer diagnostics that might
93 /// have more false positives than usual.
94 diagnostics_enableExperimental: bool = "true",
95 /// List of rust-analyzer diagnostics to disable.
96 diagnostics_disabled: FxHashSet<String> = "[]",
97 /// List of warnings that should be displayed with info severity.\n\nThe
98 /// warnings will be indicated by a blue squiggly underline in code and
99 /// a blue icon in the `Problems Panel`.
100 diagnostics_warningsAsHint: Vec<String> = "[]",
101 /// List of warnings that should be displayed with hint severity.\n\nThe
102 /// warnings will be indicated by faded text or three dots in code and
103 /// will not show up in the `Problems Panel`.
104 diagnostics_warningsAsInfo: Vec<String> = "[]",
106 /// Controls file watching implementation.
107 files_watcher: String = "\"client\"",
109 /// Whether to show `Debug` action. Only applies when
110 /// `#rust-analyzer.hoverActions.enable#` is set.
111 hoverActions_debug: bool = "true",
112 /// Whether to show HoverActions in Rust files.
113 hoverActions_enable: bool = "true",
114 /// Whether to show `Go to Type Definition` action. Only applies when
115 /// `#rust-analyzer.hoverActions.enable#` is set.
116 hoverActions_gotoTypeDef: bool = "true",
117 /// Whether to show `Implementations` action. Only applies when
118 /// `#rust-analyzer.hoverActions.enable#` is set.
119 hoverActions_implementations: bool = "true",
120 /// Whether to show `Run` action. Only applies when
121 /// `#rust-analyzer.hoverActions.enable#` is set.
122 hoverActions_run: bool = "true",
123 /// Use markdown syntax for links in hover.
124 hoverActions_linksInHover: bool = "true",
126 /// Whether to show inlay type hints for method chains.
127 inlayHints_chainingHints: bool = "true",
128 /// Maximum length for inlay hints. Default is unlimited.
129 inlayHints_maxLength: Option<usize> = "null",
130 /// Whether to show function parameter name inlay hints at the call
132 inlayHints_parameterHints: bool = "true",
133 /// Whether to show inlay type hints for variables.
134 inlayHints_typeHints: bool = "true",
136 /// Whether to show `Debug` lens. Only applies when
137 /// `#rust-analyzer.lens.enable#` is set.
138 lens_debug: bool = "true",
139 /// Whether to show CodeLens in Rust files.
140 lens_enable: bool = "true",
141 /// Whether to show `Implementations` lens. Only applies when
142 /// `#rust-analyzer.lens.enable#` is set.
143 lens_implementations: bool = "true",
144 /// Whether to show `Run` lens. Only applies when
145 /// `#rust-analyzer.lens.enable#` is set.
146 lens_run: bool = "true",
147 /// Whether to show `Method References` lens. Only applies when
148 /// `#rust-analyzer.lens.enable#` is set.
149 lens_methodReferences: bool = "false",
150 /// Whether to show `References` lens. Only applies when
151 /// `#rust-analyzer.lens.enable#` is set.
152 lens_references: bool = "false",
154 /// Disable project auto-discovery in favor of explicitly specified set
155 /// of projects.\n\nElements must be paths pointing to `Cargo.toml`,
156 /// `rust-project.json`, or JSON objects in `rust-project.json` format.
157 linkedProjects: Vec<ManifestOrProjectJson> = "[]",
159 /// Number of syntax trees rust-analyzer keeps in memory. Defaults to 128.
160 lruCapacity: Option<usize> = "null",
162 /// Whether to show `can't find Cargo.toml` error message.
163 notifications_cargoTomlNotFound: bool = "true",
165 /// Enable Proc macro support, `#rust-analyzer.cargo.loadOutDirsFromCheck#` must be
167 procMacro_enable: bool = "false",
168 /// Internal config, path to proc-macro server executable (typically,
169 /// this is rust-analyzer itself, but we override this in tests).
170 procMacro_server: Option<PathBuf> = "null",
172 /// Command to be executed instead of 'cargo' for runnables.
173 runnables_overrideCargo: Option<String> = "null",
174 /// Additional arguments to be passed to cargo for runnables such as
175 /// tests or binaries.\nFor example, it may be `--release`.
176 runnables_cargoExtraArgs: Vec<String> = "[]",
178 /// Path to the rust compiler sources, for usage in rustc_private projects.
179 rustcSource : Option<PathBuf> = "null",
181 /// Additional arguments to `rustfmt`.
182 rustfmt_extraArgs: Vec<String> = "[]",
183 /// Advanced option, fully override the command rust-analyzer uses for
185 rustfmt_overrideCommand: Option<Vec<String>> = "null",
189 impl Default for ConfigData {
190 fn default() -> Self {
191 ConfigData::from_json(serde_json::Value::Null)
195 #[derive(Debug, Clone)]
197 caps: lsp_types::ClientCapabilities,
199 pub discovered_projects: Option<Vec<ProjectManifest>>,
200 pub root_path: AbsPathBuf,
203 #[derive(Debug, Clone, Eq, PartialEq)]
204 pub enum LinkedProject {
205 ProjectManifest(ProjectManifest),
206 InlineJsonProject(ProjectJson),
209 impl From<ProjectManifest> for LinkedProject {
210 fn from(v: ProjectManifest) -> Self {
211 LinkedProject::ProjectManifest(v)
215 impl From<ProjectJson> for LinkedProject {
216 fn from(v: ProjectJson) -> Self {
217 LinkedProject::InlineJsonProject(v)
221 #[derive(Clone, Debug, PartialEq, Eq)]
222 pub struct LensConfig {
225 pub implementations: bool,
226 pub method_refs: bool,
227 pub refs: bool, // for Struct, Enum, Union and Trait
231 pub fn any(&self) -> bool {
232 self.implementations || self.runnable() || self.references()
235 pub fn none(&self) -> bool {
239 pub fn runnable(&self) -> bool {
240 self.run || self.debug
243 pub fn references(&self) -> bool {
244 self.method_refs || self.refs
248 #[derive(Debug, Clone)]
249 pub struct FilesConfig {
250 pub watcher: FilesWatcher,
251 pub exclude: Vec<String>,
254 #[derive(Debug, Clone)]
255 pub enum FilesWatcher {
260 #[derive(Debug, Clone)]
261 pub struct NotificationsConfig {
262 pub cargo_toml_not_found: bool,
265 #[derive(Debug, Clone)]
266 pub enum RustfmtConfig {
267 Rustfmt { extra_args: Vec<String> },
268 CustomCommand { command: String, args: Vec<String> },
271 /// Configuration for runnable items, such as `main` function or tests.
272 #[derive(Debug, Clone)]
273 pub struct RunnablesConfig {
274 /// Custom command to be executed instead of `cargo` for runnables.
275 pub override_cargo: Option<String>,
276 /// Additional arguments for the `cargo`, e.g. `--release`.
277 pub cargo_extra_args: Vec<String>,
281 pub fn new(root_path: AbsPathBuf, caps: ClientCapabilities) -> Self {
282 Config { caps, data: ConfigData::default(), discovered_projects: None, root_path }
284 pub fn update(&mut self, json: serde_json::Value) {
285 log::info!("updating config from JSON: {:#}", json);
286 if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
289 self.data = ConfigData::from_json(json);
292 pub fn json_schema() -> serde_json::Value {
293 ConfigData::json_schema()
299 || -> _ { Some($expr) }()
302 macro_rules! try_or {
303 ($expr:expr, $or:expr) => {
304 try_!($expr).unwrap_or($or)
309 pub fn linked_projects(&self) -> Vec<LinkedProject> {
310 if self.data.linkedProjects.is_empty() {
311 self.discovered_projects
316 .map(LinkedProject::from)
322 .filter_map(|linked_project| {
323 let res = match linked_project {
324 ManifestOrProjectJson::Manifest(it) => {
325 let path = self.root_path.join(it);
326 ProjectManifest::from_manifest_file(path)
327 .map_err(|e| log::error!("failed to load linked project: {}", e))
331 ManifestOrProjectJson::ProjectJson(it) => {
332 ProjectJson::new(&self.root_path, it.clone()).into()
341 pub fn did_save_text_document_dynamic_registration(&self) -> bool {
343 try_or!(self.caps.text_document.as_ref()?.synchronization.clone()?, Default::default());
344 caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
346 pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
348 self.caps.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration?,
353 pub fn location_link(&self) -> bool {
354 try_or!(self.caps.text_document.as_ref()?.definition?.link_support?, false)
356 pub fn line_folding_only(&self) -> bool {
357 try_or!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?, false)
359 pub fn hierarchical_symbols(&self) -> bool {
366 .hierarchical_document_symbol_support?,
370 pub fn code_action_literals(&self) -> bool {
377 .code_action_literal_support
381 pub fn work_done_progress(&self) -> bool {
382 try_or!(self.caps.window.as_ref()?.work_done_progress?, false)
384 pub fn code_action_resolve(&self) -> bool {
398 .any(|it| it == "edit")
400 pub fn signature_help_label_offsets(&self) -> bool {
407 .signature_information
409 .parameter_information
411 .label_offset_support?,
416 fn experimental(&self, index: &'static str) -> bool {
417 try_or!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?, false)
419 pub fn code_action_group(&self) -> bool {
420 self.experimental("codeActionGroup")
422 pub fn hover_actions(&self) -> bool {
423 self.experimental("hoverActions")
425 pub fn status_notification(&self) -> bool {
426 self.experimental("statusNotification")
429 pub fn publish_diagnostics(&self) -> bool {
430 self.data.diagnostics_enable
432 pub fn diagnostics(&self) -> DiagnosticsConfig {
434 disable_experimental: !self.data.diagnostics_enableExperimental,
435 disabled: self.data.diagnostics_disabled.clone(),
438 pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
439 DiagnosticsMapConfig {
440 warnings_as_info: self.data.diagnostics_warningsAsInfo.clone(),
441 warnings_as_hint: self.data.diagnostics_warningsAsHint.clone(),
444 pub fn lru_capacity(&self) -> Option<usize> {
445 self.data.lruCapacity
447 pub fn proc_macro_srv(&self) -> Option<(PathBuf, Vec<OsString>)> {
448 if !self.data.procMacro_enable {
452 let path = self.data.procMacro_server.clone().or_else(|| std::env::current_exe().ok())?;
453 Some((path, vec!["proc-macro".into()]))
455 pub fn files(&self) -> FilesConfig {
457 watcher: match self.data.files_watcher.as_str() {
458 "notify" => FilesWatcher::Notify,
459 "client" | _ => FilesWatcher::Client,
464 pub fn notifications(&self) -> NotificationsConfig {
465 NotificationsConfig { cargo_toml_not_found: self.data.notifications_cargoTomlNotFound }
467 pub fn cargo_autoreload(&self) -> bool {
468 self.data.cargo_autoreload
470 pub fn cargo(&self) -> CargoConfig {
471 let rustc_source = self.data.rustcSource.clone().and_then(|it| {
472 AbsPathBuf::try_from(it)
473 .map_err(|_| log::error!("rustc source directory must be an absolute path"))
478 no_default_features: self.data.cargo_noDefaultFeatures,
479 all_features: self.data.cargo_allFeatures,
480 features: self.data.cargo_features.clone(),
481 load_out_dirs_from_check: self.data.cargo_loadOutDirsFromCheck,
482 target: self.data.cargo_target.clone(),
484 no_sysroot: self.data.cargo_noSysroot,
487 pub fn rustfmt(&self) -> RustfmtConfig {
488 match &self.data.rustfmt_overrideCommand {
489 Some(args) if !args.is_empty() => {
490 let mut args = args.clone();
491 let command = args.remove(0);
492 RustfmtConfig::CustomCommand { command, args }
495 RustfmtConfig::Rustfmt { extra_args: self.data.rustfmt_extraArgs.clone() }
499 pub fn flycheck(&self) -> Option<FlycheckConfig> {
500 if !self.data.checkOnSave_enable {
503 let flycheck_config = match &self.data.checkOnSave_overrideCommand {
504 Some(args) if !args.is_empty() => {
505 let mut args = args.clone();
506 let command = args.remove(0);
507 FlycheckConfig::CustomCommand { command, args }
509 Some(_) | None => FlycheckConfig::CargoCommand {
510 command: self.data.checkOnSave_command.clone(),
515 .or(self.data.cargo_target.clone()),
516 all_targets: self.data.checkOnSave_allTargets,
517 no_default_features: self
519 .checkOnSave_noDefaultFeatures
520 .unwrap_or(self.data.cargo_noDefaultFeatures),
523 .checkOnSave_allFeatures
524 .unwrap_or(self.data.cargo_allFeatures),
527 .checkOnSave_features
529 .unwrap_or(self.data.cargo_features.clone()),
530 extra_args: self.data.checkOnSave_extraArgs.clone(),
533 Some(flycheck_config)
535 pub fn runnables(&self) -> RunnablesConfig {
537 override_cargo: self.data.runnables_overrideCargo.clone(),
538 cargo_extra_args: self.data.runnables_cargoExtraArgs.clone(),
541 pub fn inlay_hints(&self) -> InlayHintsConfig {
543 type_hints: self.data.inlayHints_typeHints,
544 parameter_hints: self.data.inlayHints_parameterHints,
545 chaining_hints: self.data.inlayHints_chainingHints,
546 max_length: self.data.inlayHints_maxLength,
549 fn insert_use_config(&self) -> InsertUseConfig {
551 merge: match self.data.assist_importMergeBehavior {
552 MergeBehaviorDef::None => None,
553 MergeBehaviorDef::Full => Some(MergeBehavior::Full),
554 MergeBehaviorDef::Last => Some(MergeBehavior::Last),
556 prefix_kind: match self.data.assist_importPrefix {
557 ImportPrefixDef::Plain => PrefixKind::Plain,
558 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
559 ImportPrefixDef::BySelf => PrefixKind::BySelf,
563 pub fn completion(&self) -> CompletionConfig {
565 enable_postfix_completions: self.data.completion_postfix_enable,
566 enable_imports_on_the_fly: self.data.completion_autoimport_enable
567 && completion_item_edit_resolve(&self.caps),
568 add_call_parenthesis: self.data.completion_addCallParenthesis,
569 add_call_argument_snippets: self.data.completion_addCallArgumentSnippets,
570 insert_use: self.insert_use_config(),
571 snippet_cap: SnippetCap::new(try_or!(
584 pub fn assist(&self) -> AssistConfig {
586 snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
588 insert_use: self.insert_use_config(),
591 pub fn call_info_full(&self) -> bool {
592 self.data.callInfo_full
594 pub fn lens(&self) -> LensConfig {
596 run: self.data.lens_enable && self.data.lens_run,
597 debug: self.data.lens_enable && self.data.lens_debug,
598 implementations: self.data.lens_enable && self.data.lens_implementations,
599 method_refs: self.data.lens_enable && self.data.lens_methodReferences,
600 refs: self.data.lens_enable && self.data.lens_references,
603 pub fn hover(&self) -> HoverConfig {
605 implementations: self.data.hoverActions_enable
606 && self.data.hoverActions_implementations,
607 run: self.data.hoverActions_enable && self.data.hoverActions_run,
608 debug: self.data.hoverActions_enable && self.data.hoverActions_debug,
609 goto_type_def: self.data.hoverActions_enable && self.data.hoverActions_gotoTypeDef,
610 links_in_hover: self.data.hoverActions_linksInHover,
622 .contains(&MarkupKind::Markdown),
625 pub fn semantic_tokens_refresh(&self) -> bool {
626 try_or!(self.caps.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support?, false)
628 pub fn code_lens_refresh(&self) -> bool {
629 try_or!(self.caps.workspace.as_ref()?.code_lens.as_ref()?.refresh_support?, false)
633 #[derive(Deserialize, Debug, Clone)]
635 enum ManifestOrProjectJson {
637 ProjectJson(ProjectJsonData),
640 #[derive(Deserialize, Debug, Clone)]
641 #[serde(rename_all = "snake_case")]
642 enum MergeBehaviorDef {
648 #[derive(Deserialize, Debug, Clone)]
649 #[serde(rename_all = "snake_case")]
650 enum ImportPrefixDef {
656 macro_rules! _config_data {
657 (struct $name:ident {
659 $(#[doc=$doc:literal])*
660 $field:ident $(| $alias:ident)?: $ty:ty = $default:expr,
663 #[allow(non_snake_case)]
664 #[derive(Debug, Clone)]
665 struct $name { $($field: $ty,)* }
667 fn from_json(mut json: serde_json::Value) -> $name {
672 None$(.or(Some(stringify!($alias))))?,
678 fn json_schema() -> serde_json::Value {
681 let field = stringify!($field);
682 let ty = stringify!($ty);
683 (field, ty, &[$($doc),*], $default)
689 fn manual() -> String {
692 let field = stringify!($field);
693 let ty = stringify!($ty);
694 (field, ty, &[$($doc),*], $default)
701 use _config_data as config_data;
703 fn get_field<T: DeserializeOwned>(
704 json: &mut serde_json::Value,
706 alias: Option<&'static str>,
709 let default = serde_json::from_str(default).unwrap();
711 // XXX: check alias first, to work-around the VS Code where it pre-fills the
712 // defaults instead of sending an empty object.
715 .chain(iter::once(field))
716 .find_map(move |field| {
717 let mut pointer = field.replace('_', "/");
718 pointer.insert(0, '/');
719 json.pointer_mut(&pointer).and_then(|it| serde_json::from_value(it.take()).ok())
724 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
725 for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
726 fn key(f: &str) -> &str {
727 f.splitn(2, "_").next().unwrap()
729 assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
734 .map(|(field, ty, doc, default)| {
735 let name = field.replace("_", ".");
736 let name = format!("rust-analyzer.{}", name);
737 let props = field_props(field, ty, doc, default);
740 .collect::<serde_json::Map<_, _>>();
744 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
745 let doc = doc.iter().map(|it| it.trim()).join(" ");
747 doc.ends_with('.') && doc.starts_with(char::is_uppercase),
748 "bad docs for {}: {:?}",
752 let default = default.parse::<serde_json::Value>().unwrap();
754 let mut map = serde_json::Map::default();
756 ($($key:literal: $value:tt),*$(,)?) => {{$(
757 map.insert($key.into(), serde_json::json!($value));
760 set!("markdownDescription": doc);
761 set!("default": default);
764 "bool" => set!("type": "boolean"),
765 "String" => set!("type": "string"),
766 "Vec<String>" => set! {
768 "items": { "type": "string" },
770 "FxHashSet<String>" => set! {
772 "items": { "type": "string" },
775 "Option<usize>" => set! {
776 "type": ["null", "integer"],
779 "Option<String>" => set! {
780 "type": ["null", "string"],
782 "Option<PathBuf>" => set! {
783 "type": ["null", "string"],
785 "Option<bool>" => set! {
786 "type": ["null", "boolean"],
788 "Option<Vec<String>>" => set! {
789 "type": ["null", "array"],
790 "items": { "type": "string" },
792 "MergeBehaviorDef" => set! {
794 "enum": ["none", "full", "last"],
795 "enumDescriptions": [
797 "Merge all layers of the import trees",
798 "Only merge the last layer of the import trees"
801 "ImportPrefixDef" => set! {
808 "enumDescriptions": [
809 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
810 "Prefix all import paths with `self` if they don't begin with `self`, `super`, `crate` or a crate name.",
811 "Force import paths to be absolute by always starting them with `crate` or the crate name they refer to."
814 "Vec<ManifestOrProjectJson>" => set! {
816 "items": { "type": ["string", "object"] },
818 _ => panic!("{}: {}", ty, default),
825 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
828 .map(|(field, _ty, doc, default)| {
829 let name = format!("rust-analyzer.{}", field.replace("_", "."));
830 format!("[[{}]]{} (default: `{}`)::\n{}\n", name, name, default, doc.join(" "))
839 use test_utils::project_dir;
844 fn schema_in_sync_with_package_json() {
845 let s = Config::json_schema();
846 let schema = format!("{:#}", s);
847 let schema = schema.trim_start_matches('{').trim_end_matches('}');
849 let package_json = project_dir().join("editors/code/package.json");
850 let package_json = fs::read_to_string(&package_json).unwrap();
852 let p = remove_ws(&package_json);
853 let s = remove_ws(&schema);
855 assert!(p.contains(&s), "update config in package.json. New config:\n{:#}", schema);
859 fn schema_in_sync_with_docs() {
860 let docs_path = project_dir().join("docs/user/generated_config.adoc");
861 let current = fs::read_to_string(&docs_path).unwrap();
862 let expected = ConfigData::manual();
864 if remove_ws(¤t) != remove_ws(&expected) {
865 fs::write(&docs_path, expected).unwrap();
866 panic!("updated config manual");
870 fn remove_ws(text: &str) -> String {
871 text.replace(char::is_whitespace, "")