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, path::PathBuf};
12 use flycheck::FlycheckConfig;
14 use ide::{AssistConfig, CompletionConfig, DiagnosticsConfig, HoverConfig, InlayHintsConfig};
15 use ide_db::helpers::insert_use::MergeBehaviour;
16 use itertools::Itertools;
17 use lsp_types::{ClientCapabilities, MarkupKind};
18 use project_model::{CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest};
19 use rustc_hash::FxHashSet;
20 use serde::{de::DeserializeOwned, Deserialize};
23 use crate::{caps::enabled_completions_resolve_capabilities, diagnostics::DiagnosticsMapConfig};
27 /// The strategy to use when inserting new imports or merging imports.
28 assist_importMergeBehaviour: MergeBehaviourDef = "\"full\"",
29 /// The path structure for newly inserted paths to use.
30 assist_importPrefix: ImportPrefixDef = "\"plain\"",
32 /// Show function name and docs in parameter hints.
33 callInfo_full: bool = "true",
35 /// Automatically refresh project info via `cargo metadata` on
36 /// Cargo.toml changes.
37 cargo_autoreload: bool = "true",
38 /// Activate all available features.
39 cargo_allFeatures: bool = "false",
40 /// List of features to activate.
41 cargo_features: Vec<String> = "[]",
42 /// Run `cargo check` on startup to get the correct value for package
44 cargo_loadOutDirsFromCheck: bool = "false",
45 /// Do not activate the `default` feature.
46 cargo_noDefaultFeatures: bool = "false",
47 /// Compilation target (target triple).
48 cargo_target: Option<String> = "null",
49 /// Internal config for debugging, disables loading of sysroot crates.
50 cargo_noSysroot: bool = "false",
52 /// Run specified `cargo check` command for diagnostics on save.
53 checkOnSave_enable: bool = "true",
54 /// Check with all features (will be passed as `--all-features`).
55 /// Defaults to `rust-analyzer.cargo.allFeatures`.
56 checkOnSave_allFeatures: Option<bool> = "null",
57 /// Check all targets and tests (will be passed as `--all-targets`).
58 checkOnSave_allTargets: bool = "true",
59 /// Cargo command to use for `cargo check`.
60 checkOnSave_command: String = "\"check\"",
61 /// Do not activate the `default` feature.
62 checkOnSave_noDefaultFeatures: Option<bool> = "null",
63 /// Check for a specific target. Defaults to
64 /// `rust-analyzer.cargo.target`.
65 checkOnSave_target: Option<String> = "null",
66 /// Extra arguments for `cargo check`.
67 checkOnSave_extraArgs: Vec<String> = "[]",
68 /// List of features to activate. Defaults to
69 /// `rust-analyzer.cargo.features`.
70 checkOnSave_features: Option<Vec<String>> = "null",
71 /// Advanced option, fully override the command rust-analyzer uses for
72 /// checking. The command should include `--message-format=json` or
74 checkOnSave_overrideCommand: Option<Vec<String>> = "null",
76 /// Whether to add argument snippets when completing functions.
77 completion_addCallArgumentSnippets: bool = "true",
78 /// Whether to add parenthesis when completing functions.
79 completion_addCallParenthesis: bool = "true",
80 /// Whether to show postfix snippets like `dbg`, `if`, `not`, etc.
81 completion_postfix_enable: bool = "true",
82 /// Toggles the additional completions that automatically add imports when completed.
83 /// Note that your client have to specify the `additionalTextEdits` LSP client capability to truly have this feature enabled.
84 completion_autoimport_enable: bool = "true",
86 /// Whether to show native rust-analyzer diagnostics.
87 diagnostics_enable: bool = "true",
88 /// Whether to show experimental rust-analyzer diagnostics that might
89 /// have more false positives than usual.
90 diagnostics_enableExperimental: bool = "true",
91 /// List of rust-analyzer diagnostics to disable.
92 diagnostics_disabled: FxHashSet<String> = "[]",
93 /// List of warnings that should be displayed with info severity.\nThe
94 /// warnings will be indicated by a blue squiggly underline in code and
95 /// a blue icon in the problems panel.
96 diagnostics_warningsAsHint: Vec<String> = "[]",
97 /// List of warnings that should be displayed with hint severity.\nThe
98 /// warnings will be indicated by faded text or three dots in code and
99 /// will not show up in the problems panel.
100 diagnostics_warningsAsInfo: Vec<String> = "[]",
102 /// Controls file watching implementation.
103 files_watcher: String = "\"client\"",
105 /// Whether to show `Debug` action. Only applies when
106 /// `#rust-analyzer.hoverActions.enable#` is set.
107 hoverActions_debug: bool = "true",
108 /// Whether to show HoverActions in Rust files.
109 hoverActions_enable: bool = "true",
110 /// Whether to show `Go to Type Definition` action. Only applies when
111 /// `#rust-analyzer.hoverActions.enable#` is set.
112 hoverActions_gotoTypeDef: bool = "true",
113 /// Whether to show `Implementations` action. Only applies when
114 /// `#rust-analyzer.hoverActions.enable#` is set.
115 hoverActions_implementations: bool = "true",
116 /// Whether to show `Run` action. Only applies when
117 /// `#rust-analyzer.hoverActions.enable#` is set.
118 hoverActions_run: bool = "true",
119 /// Use markdown syntax for links in hover.
120 hoverActions_linksInHover: bool = "true",
122 /// Whether to show inlay type hints for method chains.
123 inlayHints_chainingHints: bool = "true",
124 /// Maximum length for inlay hints.
125 inlayHints_maxLength: Option<usize> = "null",
126 /// Whether to show function parameter name inlay hints at the call
128 inlayHints_parameterHints: bool = "true",
129 /// Whether to show inlay type hints for variables.
130 inlayHints_typeHints: bool = "true",
132 /// Whether to show `Debug` lens. Only applies when
133 /// `#rust-analyzer.lens.enable#` is set.
134 lens_debug: bool = "true",
135 /// Whether to show CodeLens in Rust files.
136 lens_enable: bool = "true",
137 /// Whether to show `Implementations` lens. Only applies when
138 /// `#rust-analyzer.lens.enable#` is set.
139 lens_implementations: bool = "true",
140 /// Whether to show `Run` lens. Only applies when
141 /// `#rust-analyzer.lens.enable#` is set.
142 lens_run: bool = "true",
143 /// Whether to show `Method References` lens. Only applies when
144 /// `#rust-analyzer.lens.enable#` is set.
145 lens_methodReferences: bool = "false",
147 /// Disable project auto-discovery in favor of explicitly specified set
148 /// of projects. \nElements must be paths pointing to Cargo.toml,
149 /// rust-project.json, or JSON objects in rust-project.json format.
150 linkedProjects: Vec<ManifestOrProjectJson> = "[]",
151 /// Number of syntax trees rust-analyzer keeps in memory.
152 lruCapacity: Option<usize> = "null",
153 /// Whether to show `can't find Cargo.toml` error message.
154 notifications_cargoTomlNotFound: bool = "true",
155 /// Enable Proc macro support, cargo.loadOutDirsFromCheck must be
157 procMacro_enable: bool = "false",
159 /// Command to be executed instead of 'cargo' for runnables.
160 runnables_overrideCargo: Option<String> = "null",
161 /// Additional arguments to be passed to cargo for runnables such as
162 /// tests or binaries.\nFor example, it may be '--release'.
163 runnables_cargoExtraArgs: Vec<String> = "[]",
165 /// Path to the rust compiler sources, for usage in rustc_private projects.
166 rustcSource : Option<String> = "null",
168 /// Additional arguments to rustfmt.
169 rustfmt_extraArgs: Vec<String> = "[]",
170 /// Advanced option, fully override the command rust-analyzer uses for
172 rustfmt_overrideCommand: Option<Vec<String>> = "null",
176 #[derive(Debug, Clone)]
178 pub client_caps: ClientCapsConfig,
180 pub publish_diagnostics: bool,
181 pub diagnostics: DiagnosticsConfig,
182 pub diagnostics_map: DiagnosticsMapConfig,
183 pub lru_capacity: Option<usize>,
184 pub proc_macro_srv: Option<(PathBuf, Vec<OsString>)>,
185 pub files: FilesConfig,
186 pub notifications: NotificationsConfig,
188 pub cargo_autoreload: bool,
189 pub cargo: CargoConfig,
190 pub rustfmt: RustfmtConfig,
191 pub flycheck: Option<FlycheckConfig>,
192 pub runnables: RunnablesConfig,
194 pub inlay_hints: InlayHintsConfig,
195 pub completion: CompletionConfig,
196 pub assist: AssistConfig,
197 pub call_info_full: bool,
198 pub lens: LensConfig,
199 pub hover: HoverConfig,
200 pub semantic_tokens_refresh: bool,
201 pub code_lens_refresh: bool,
203 pub linked_projects: Vec<LinkedProject>,
204 pub root_path: AbsPathBuf,
207 #[derive(Debug, Clone, Eq, PartialEq)]
208 pub enum LinkedProject {
209 ProjectManifest(ProjectManifest),
210 InlineJsonProject(ProjectJson),
213 impl From<ProjectManifest> for LinkedProject {
214 fn from(v: ProjectManifest) -> Self {
215 LinkedProject::ProjectManifest(v)
219 impl From<ProjectJson> for LinkedProject {
220 fn from(v: ProjectJson) -> Self {
221 LinkedProject::InlineJsonProject(v)
225 #[derive(Clone, Debug, PartialEq, Eq)]
226 pub struct LensConfig {
229 pub implementations: bool,
230 pub method_refs: bool,
233 impl Default for LensConfig {
234 fn default() -> Self {
235 Self { run: true, debug: true, implementations: true, method_refs: false }
240 pub fn any(&self) -> bool {
241 self.implementations || self.runnable() || self.references()
244 pub fn none(&self) -> bool {
248 pub fn runnable(&self) -> bool {
249 self.run || self.debug
252 pub fn references(&self) -> bool {
257 #[derive(Debug, Clone)]
258 pub struct FilesConfig {
259 pub watcher: FilesWatcher,
260 pub exclude: Vec<String>,
263 #[derive(Debug, Clone)]
264 pub enum FilesWatcher {
269 #[derive(Debug, Clone)]
270 pub struct NotificationsConfig {
271 pub cargo_toml_not_found: bool,
274 #[derive(Debug, Clone)]
275 pub enum RustfmtConfig {
276 Rustfmt { extra_args: Vec<String> },
277 CustomCommand { command: String, args: Vec<String> },
280 /// Configuration for runnable items, such as `main` function or tests.
281 #[derive(Debug, Clone, Default)]
282 pub struct RunnablesConfig {
283 /// Custom command to be executed instead of `cargo` for runnables.
284 pub override_cargo: Option<String>,
285 /// Additional arguments for the `cargo`, e.g. `--release`.
286 pub cargo_extra_args: Vec<String>,
289 #[derive(Debug, Clone, Default)]
290 pub struct ClientCapsConfig {
291 pub location_link: bool,
292 pub line_folding_only: bool,
293 pub hierarchical_symbols: bool,
294 pub code_action_literals: bool,
295 pub work_done_progress: bool,
296 pub code_action_group: bool,
297 pub code_action_resolve: bool,
298 pub hover_actions: bool,
299 pub status_notification: bool,
300 pub signature_help_label_offsets: bool,
304 pub fn new(root_path: AbsPathBuf) -> Self {
305 // Defaults here don't matter, we'll immediately re-write them with
307 let mut res = Config {
308 client_caps: ClientCapsConfig::default(),
310 publish_diagnostics: false,
311 diagnostics: DiagnosticsConfig::default(),
312 diagnostics_map: DiagnosticsMapConfig::default(),
314 proc_macro_srv: None,
315 files: FilesConfig { watcher: FilesWatcher::Notify, exclude: Vec::new() },
316 notifications: NotificationsConfig { cargo_toml_not_found: false },
318 cargo_autoreload: false,
319 cargo: CargoConfig::default(),
320 rustfmt: RustfmtConfig::Rustfmt { extra_args: Vec::new() },
321 flycheck: Some(FlycheckConfig::CargoCommand {
322 command: String::new(),
324 no_default_features: false,
327 extra_args: Vec::new(),
328 features: Vec::new(),
330 runnables: RunnablesConfig::default(),
332 inlay_hints: InlayHintsConfig {
334 parameter_hints: false,
335 chaining_hints: false,
338 completion: CompletionConfig::default(),
339 assist: AssistConfig::default(),
340 call_info_full: false,
341 lens: LensConfig::default(),
342 hover: HoverConfig::default(),
343 semantic_tokens_refresh: false,
344 code_lens_refresh: false,
345 linked_projects: Vec::new(),
348 res.do_update(serde_json::json!({}));
351 pub fn update(&mut self, json: serde_json::Value) {
352 log::info!("Config::update({:#})", json);
353 if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
356 self.do_update(json);
357 log::info!("Config::update() = {:#?}", self);
359 fn do_update(&mut self, json: serde_json::Value) {
360 let data = ConfigData::from_json(json);
362 self.publish_diagnostics = data.diagnostics_enable;
363 self.diagnostics = DiagnosticsConfig {
364 disable_experimental: !data.diagnostics_enableExperimental,
365 disabled: data.diagnostics_disabled,
367 self.diagnostics_map = DiagnosticsMapConfig {
368 warnings_as_info: data.diagnostics_warningsAsInfo,
369 warnings_as_hint: data.diagnostics_warningsAsHint,
371 self.lru_capacity = data.lruCapacity;
372 self.files.watcher = match data.files_watcher.as_str() {
373 "notify" => FilesWatcher::Notify,
374 "client" | _ => FilesWatcher::Client,
377 NotificationsConfig { cargo_toml_not_found: data.notifications_cargoTomlNotFound };
378 self.cargo_autoreload = data.cargo_autoreload;
380 let rustc_source = if let Some(rustc_source) = data.rustcSource {
381 let rustpath: PathBuf = rustc_source.into();
382 AbsPathBuf::try_from(rustpath)
384 log::error!("rustc source directory must be an absolute path");
391 self.cargo = CargoConfig {
392 no_default_features: data.cargo_noDefaultFeatures,
393 all_features: data.cargo_allFeatures,
394 features: data.cargo_features.clone(),
395 load_out_dirs_from_check: data.cargo_loadOutDirsFromCheck,
396 target: data.cargo_target.clone(),
397 rustc_source: rustc_source,
398 no_sysroot: data.cargo_noSysroot,
400 self.runnables = RunnablesConfig {
401 override_cargo: data.runnables_overrideCargo,
402 cargo_extra_args: data.runnables_cargoExtraArgs,
405 self.proc_macro_srv = if data.procMacro_enable {
406 std::env::current_exe().ok().map(|path| (path, vec!["proc-macro".into()]))
411 self.rustfmt = match data.rustfmt_overrideCommand {
412 Some(mut args) if !args.is_empty() => {
413 let command = args.remove(0);
414 RustfmtConfig::CustomCommand { command, args }
416 Some(_) | None => RustfmtConfig::Rustfmt { extra_args: data.rustfmt_extraArgs },
419 self.flycheck = if data.checkOnSave_enable {
420 let flycheck_config = match data.checkOnSave_overrideCommand {
421 Some(mut args) if !args.is_empty() => {
422 let command = args.remove(0);
423 FlycheckConfig::CustomCommand { command, args }
425 Some(_) | None => FlycheckConfig::CargoCommand {
426 command: data.checkOnSave_command,
427 target_triple: data.checkOnSave_target.or(data.cargo_target),
428 all_targets: data.checkOnSave_allTargets,
429 no_default_features: data
430 .checkOnSave_noDefaultFeatures
431 .unwrap_or(data.cargo_noDefaultFeatures),
432 all_features: data.checkOnSave_allFeatures.unwrap_or(data.cargo_allFeatures),
433 features: data.checkOnSave_features.unwrap_or(data.cargo_features),
434 extra_args: data.checkOnSave_extraArgs,
437 Some(flycheck_config)
442 self.inlay_hints = InlayHintsConfig {
443 type_hints: data.inlayHints_typeHints,
444 parameter_hints: data.inlayHints_parameterHints,
445 chaining_hints: data.inlayHints_chainingHints,
446 max_length: data.inlayHints_maxLength,
449 self.assist.insert_use.merge = match data.assist_importMergeBehaviour {
450 MergeBehaviourDef::None => None,
451 MergeBehaviourDef::Full => Some(MergeBehaviour::Full),
452 MergeBehaviourDef::Last => Some(MergeBehaviour::Last),
454 self.assist.insert_use.prefix_kind = match data.assist_importPrefix {
455 ImportPrefixDef::Plain => PrefixKind::Plain,
456 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
457 ImportPrefixDef::BySelf => PrefixKind::BySelf,
460 self.completion.enable_postfix_completions = data.completion_postfix_enable;
461 self.completion.enable_autoimport_completions = data.completion_autoimport_enable;
462 self.completion.add_call_parenthesis = data.completion_addCallParenthesis;
463 self.completion.add_call_argument_snippets = data.completion_addCallArgumentSnippets;
464 self.completion.merge = self.assist.insert_use.merge;
466 self.call_info_full = data.callInfo_full;
468 self.lens = LensConfig {
469 run: data.lens_enable && data.lens_run,
470 debug: data.lens_enable && data.lens_debug,
471 implementations: data.lens_enable && data.lens_implementations,
472 method_refs: data.lens_enable && data.lens_methodReferences,
475 if !data.linkedProjects.is_empty() {
476 self.linked_projects.clear();
477 for linked_project in data.linkedProjects {
478 let linked_project = match linked_project {
479 ManifestOrProjectJson::Manifest(it) => {
480 let path = self.root_path.join(it);
481 match ProjectManifest::from_manifest_file(path) {
484 log::error!("failed to load linked project: {}", e);
489 ManifestOrProjectJson::ProjectJson(it) => {
490 ProjectJson::new(&self.root_path, it).into()
493 self.linked_projects.push(linked_project);
497 self.hover = HoverConfig {
498 implementations: data.hoverActions_enable && data.hoverActions_implementations,
499 run: data.hoverActions_enable && data.hoverActions_run,
500 debug: data.hoverActions_enable && data.hoverActions_debug,
501 goto_type_def: data.hoverActions_enable && data.hoverActions_gotoTypeDef,
502 links_in_hover: data.hoverActions_linksInHover,
507 pub fn update_caps(&mut self, caps: &ClientCapabilities) {
508 if let Some(doc_caps) = caps.text_document.as_ref() {
509 if let Some(value) = doc_caps.hover.as_ref().and_then(|it| it.content_format.as_ref()) {
510 self.hover.markdown = value.contains(&MarkupKind::Markdown)
512 if let Some(value) = doc_caps.definition.as_ref().and_then(|it| it.link_support) {
513 self.client_caps.location_link = value;
515 if let Some(value) = doc_caps.folding_range.as_ref().and_then(|it| it.line_folding_only)
517 self.client_caps.line_folding_only = value
519 if let Some(value) = doc_caps
522 .and_then(|it| it.hierarchical_document_symbol_support)
524 self.client_caps.hierarchical_symbols = value
527 doc_caps.code_action.as_ref().map(|it| it.code_action_literal_support.is_some())
529 self.client_caps.code_action_literals = value;
531 if let Some(value) = doc_caps
534 .and_then(|it| it.signature_information.as_ref())
535 .and_then(|it| it.parameter_information.as_ref())
536 .and_then(|it| it.label_offset_support)
538 self.client_caps.signature_help_label_offsets = value;
541 self.completion.allow_snippets(false);
542 self.completion.active_resolve_capabilities =
543 enabled_completions_resolve_capabilities(caps).unwrap_or_default();
544 if let Some(completion) = &doc_caps.completion {
545 if let Some(completion_item) = &completion.completion_item {
546 if let Some(value) = completion_item.snippet_support {
547 self.completion.allow_snippets(value);
552 if let Some(code_action) = &doc_caps.code_action {
553 if let Some(resolve_support) = &code_action.resolve_support {
554 if resolve_support.properties.iter().any(|it| it == "edit") {
555 self.client_caps.code_action_resolve = true;
561 if let Some(window_caps) = caps.window.as_ref() {
562 if let Some(value) = window_caps.work_done_progress {
563 self.client_caps.work_done_progress = value;
567 self.assist.allow_snippets(false);
568 if let Some(experimental) = &caps.experimental {
570 |index: &str| experimental.get(index).and_then(|it| it.as_bool()) == Some(true);
572 let snippet_text_edit = get_bool("snippetTextEdit");
573 self.assist.allow_snippets(snippet_text_edit);
575 self.client_caps.code_action_group = get_bool("codeActionGroup");
576 self.client_caps.hover_actions = get_bool("hoverActions");
577 self.client_caps.status_notification = get_bool("statusNotification");
580 if let Some(workspace_caps) = caps.workspace.as_ref() {
581 if let Some(refresh_support) =
582 workspace_caps.semantic_tokens.as_ref().and_then(|it| it.refresh_support)
584 self.semantic_tokens_refresh = refresh_support;
587 if let Some(refresh_support) =
588 workspace_caps.code_lens.as_ref().and_then(|it| it.refresh_support)
590 self.code_lens_refresh = refresh_support;
595 pub fn json_schema() -> serde_json::Value {
596 ConfigData::json_schema()
600 #[derive(Deserialize)]
602 enum ManifestOrProjectJson {
604 ProjectJson(ProjectJsonData),
607 #[derive(Deserialize)]
608 #[serde(rename_all = "snake_case")]
609 enum MergeBehaviourDef {
615 #[derive(Deserialize)]
616 #[serde(rename_all = "snake_case")]
617 enum ImportPrefixDef {
623 macro_rules! _config_data {
624 (struct $name:ident {
626 $(#[doc=$doc:literal])*
627 $field:ident: $ty:ty = $default:expr,
630 #[allow(non_snake_case)]
631 struct $name { $($field: $ty,)* }
633 fn from_json(mut json: serde_json::Value) -> $name {
635 $field: get_field(&mut json, stringify!($field), $default),
639 fn json_schema() -> serde_json::Value {
642 let field = stringify!($field);
643 let ty = stringify!($ty);
644 (field, ty, &[$($doc),*], $default)
650 fn manual() -> String {
653 let field = stringify!($field);
654 let ty = stringify!($ty);
655 (field, ty, &[$($doc),*], $default)
662 use _config_data as config_data;
664 fn get_field<T: DeserializeOwned>(
665 json: &mut serde_json::Value,
669 let default = serde_json::from_str(default).unwrap();
671 let mut pointer = field.replace('_', "/");
672 pointer.insert(0, '/');
673 json.pointer_mut(&pointer)
674 .and_then(|it| serde_json::from_value(it.take()).ok())
678 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
679 for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
680 fn key(f: &str) -> &str {
681 f.splitn(2, "_").next().unwrap()
683 assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
688 .map(|(field, ty, doc, default)| {
689 let name = field.replace("_", ".");
690 let name = format!("rust-analyzer.{}", name);
691 let props = field_props(field, ty, doc, default);
694 .collect::<serde_json::Map<_, _>>();
698 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
699 let doc = doc.iter().map(|it| it.trim()).join(" ");
701 doc.ends_with('.') && doc.starts_with(char::is_uppercase),
702 "bad docs for {}: {:?}",
706 let default = default.parse::<serde_json::Value>().unwrap();
708 let mut map = serde_json::Map::default();
710 ($($key:literal: $value:tt),*$(,)?) => {{$(
711 map.insert($key.into(), serde_json::json!($value));
714 set!("markdownDescription": doc);
715 set!("default": default);
718 "bool" => set!("type": "boolean"),
719 "String" => set!("type": "string"),
720 "Vec<String>" => set! {
722 "items": { "type": "string" },
724 "FxHashSet<String>" => set! {
726 "items": { "type": "string" },
729 "Option<usize>" => set! {
730 "type": ["null", "integer"],
733 "Option<String>" => set! {
734 "type": ["null", "string"],
736 "Option<bool>" => set! {
737 "type": ["null", "boolean"],
739 "Option<Vec<String>>" => set! {
740 "type": ["null", "array"],
741 "items": { "type": "string" },
743 "MergeBehaviourDef" => set! {
745 "enum": ["none", "full", "last"],
746 "enumDescriptions": [
748 "Merge all layers of the import trees",
749 "Only merge the last layer of the import trees"
752 "ImportPrefixDef" => set! {
759 "enumDescriptions": [
760 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
761 "Prefix all import paths with `self` if they don't begin with `self`, `super`, `crate` or a crate name",
762 "Force import paths to be absolute by always starting them with `crate` or the crate name they refer to."
765 "Vec<ManifestOrProjectJson>" => set! {
767 "items": { "type": ["string", "object"] },
769 _ => panic!("{}: {}", ty, default),
776 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
779 .map(|(field, _ty, doc, default)| {
780 let name = field.replace("_", ".");
781 let name = format!("rust-analyzer.{} (default: `{}`)", name, default);
782 format!("{}::\n{}\n", name, doc.join(" "))
791 use test_utils::project_dir;
796 fn schema_in_sync_with_package_json() {
797 let s = Config::json_schema();
798 let schema = format!("{:#}", s);
799 let schema = schema.trim_start_matches('{').trim_end_matches('}');
801 let package_json = project_dir().join("editors/code/package.json");
802 let package_json = fs::read_to_string(&package_json).unwrap();
804 let p = remove_ws(&package_json);
805 let s = remove_ws(&schema);
807 assert!(p.contains(&s), "update config in package.json. New config:\n{:#}", schema);
811 fn schema_in_sync_with_docs() {
812 let docs_path = project_dir().join("docs/user/generated_config.adoc");
813 let current = fs::read_to_string(&docs_path).unwrap();
814 let expected = ConfigData::manual();
816 if remove_ws(¤t) != remove_ws(&expected) {
817 fs::write(&docs_path, expected).unwrap();
818 panic!("updated config manual");
822 fn remove_ws(text: &str) -> String {
823 text.replace(char::is_whitespace, "")