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::MergeBehavior;
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: MergeBehaviorDef = "\"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 must 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.\n\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.\n\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. Default is unlimited.
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.\n\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. Defaults to 128.
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, `#rust-analyzer.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 caps: lsp_types::ClientCapabilities,
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>,
290 pub fn new(root_path: AbsPathBuf) -> Self {
291 // Defaults here don't matter, we'll immediately re-write them with
293 let mut res = Config {
294 caps: lsp_types::ClientCapabilities::default(),
296 publish_diagnostics: false,
297 diagnostics: DiagnosticsConfig::default(),
298 diagnostics_map: DiagnosticsMapConfig::default(),
300 proc_macro_srv: None,
301 files: FilesConfig { watcher: FilesWatcher::Notify, exclude: Vec::new() },
302 notifications: NotificationsConfig { cargo_toml_not_found: false },
304 cargo_autoreload: false,
305 cargo: CargoConfig::default(),
306 rustfmt: RustfmtConfig::Rustfmt { extra_args: Vec::new() },
307 flycheck: Some(FlycheckConfig::CargoCommand {
308 command: String::new(),
310 no_default_features: false,
313 extra_args: Vec::new(),
314 features: Vec::new(),
316 runnables: RunnablesConfig::default(),
318 inlay_hints: InlayHintsConfig {
320 parameter_hints: false,
321 chaining_hints: false,
324 completion: CompletionConfig::default(),
325 assist: AssistConfig::default(),
326 call_info_full: false,
327 lens: LensConfig::default(),
328 hover: HoverConfig::default(),
329 semantic_tokens_refresh: false,
330 code_lens_refresh: false,
331 linked_projects: Vec::new(),
334 res.do_update(serde_json::json!({}));
337 pub fn update(&mut self, json: serde_json::Value) {
338 log::info!("updating config from JSON: {:#}", json);
339 if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
342 self.do_update(json);
343 log::info!("updated config: {:#?}", self);
345 fn do_update(&mut self, json: serde_json::Value) {
346 let data = ConfigData::from_json(json);
348 self.publish_diagnostics = data.diagnostics_enable;
349 self.diagnostics = DiagnosticsConfig {
350 disable_experimental: !data.diagnostics_enableExperimental,
351 disabled: data.diagnostics_disabled,
353 self.diagnostics_map = DiagnosticsMapConfig {
354 warnings_as_info: data.diagnostics_warningsAsInfo,
355 warnings_as_hint: data.diagnostics_warningsAsHint,
357 self.lru_capacity = data.lruCapacity;
358 self.files.watcher = match data.files_watcher.as_str() {
359 "notify" => FilesWatcher::Notify,
360 "client" | _ => FilesWatcher::Client,
363 NotificationsConfig { cargo_toml_not_found: data.notifications_cargoTomlNotFound };
364 self.cargo_autoreload = data.cargo_autoreload;
366 let rustc_source = if let Some(rustc_source) = data.rustcSource {
367 let rustpath: PathBuf = rustc_source.into();
368 AbsPathBuf::try_from(rustpath)
370 log::error!("rustc source directory must be an absolute path");
377 self.cargo = CargoConfig {
378 no_default_features: data.cargo_noDefaultFeatures,
379 all_features: data.cargo_allFeatures,
380 features: data.cargo_features.clone(),
381 load_out_dirs_from_check: data.cargo_loadOutDirsFromCheck,
382 target: data.cargo_target.clone(),
383 rustc_source: rustc_source,
384 no_sysroot: data.cargo_noSysroot,
386 self.runnables = RunnablesConfig {
387 override_cargo: data.runnables_overrideCargo,
388 cargo_extra_args: data.runnables_cargoExtraArgs,
391 self.proc_macro_srv = if data.procMacro_enable {
392 std::env::current_exe().ok().map(|path| (path, vec!["proc-macro".into()]))
397 self.rustfmt = match data.rustfmt_overrideCommand {
398 Some(mut args) if !args.is_empty() => {
399 let command = args.remove(0);
400 RustfmtConfig::CustomCommand { command, args }
402 Some(_) | None => RustfmtConfig::Rustfmt { extra_args: data.rustfmt_extraArgs },
405 self.flycheck = if data.checkOnSave_enable {
406 let flycheck_config = match data.checkOnSave_overrideCommand {
407 Some(mut args) if !args.is_empty() => {
408 let command = args.remove(0);
409 FlycheckConfig::CustomCommand { command, args }
411 Some(_) | None => FlycheckConfig::CargoCommand {
412 command: data.checkOnSave_command,
413 target_triple: data.checkOnSave_target.or(data.cargo_target),
414 all_targets: data.checkOnSave_allTargets,
415 no_default_features: data
416 .checkOnSave_noDefaultFeatures
417 .unwrap_or(data.cargo_noDefaultFeatures),
418 all_features: data.checkOnSave_allFeatures.unwrap_or(data.cargo_allFeatures),
419 features: data.checkOnSave_features.unwrap_or(data.cargo_features),
420 extra_args: data.checkOnSave_extraArgs,
423 Some(flycheck_config)
428 self.inlay_hints = InlayHintsConfig {
429 type_hints: data.inlayHints_typeHints,
430 parameter_hints: data.inlayHints_parameterHints,
431 chaining_hints: data.inlayHints_chainingHints,
432 max_length: data.inlayHints_maxLength,
435 self.assist.insert_use.merge = match data.assist_importMergeBehaviour {
436 MergeBehaviorDef::None => None,
437 MergeBehaviorDef::Full => Some(MergeBehavior::Full),
438 MergeBehaviorDef::Last => Some(MergeBehavior::Last),
440 self.assist.insert_use.prefix_kind = match data.assist_importPrefix {
441 ImportPrefixDef::Plain => PrefixKind::Plain,
442 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
443 ImportPrefixDef::BySelf => PrefixKind::BySelf,
446 self.completion.enable_postfix_completions = data.completion_postfix_enable;
447 self.completion.enable_autoimport_completions = data.completion_autoimport_enable;
448 self.completion.add_call_parenthesis = data.completion_addCallParenthesis;
449 self.completion.add_call_argument_snippets = data.completion_addCallArgumentSnippets;
450 self.completion.merge = self.assist.insert_use.merge;
452 self.call_info_full = data.callInfo_full;
454 self.lens = LensConfig {
455 run: data.lens_enable && data.lens_run,
456 debug: data.lens_enable && data.lens_debug,
457 implementations: data.lens_enable && data.lens_implementations,
458 method_refs: data.lens_enable && data.lens_methodReferences,
461 if !data.linkedProjects.is_empty() {
462 self.linked_projects.clear();
463 for linked_project in data.linkedProjects {
464 let linked_project = match linked_project {
465 ManifestOrProjectJson::Manifest(it) => {
466 let path = self.root_path.join(it);
467 match ProjectManifest::from_manifest_file(path) {
470 log::error!("failed to load linked project: {}", e);
475 ManifestOrProjectJson::ProjectJson(it) => {
476 ProjectJson::new(&self.root_path, it).into()
479 self.linked_projects.push(linked_project);
483 self.hover = HoverConfig {
484 implementations: data.hoverActions_enable && data.hoverActions_implementations,
485 run: data.hoverActions_enable && data.hoverActions_run,
486 debug: data.hoverActions_enable && data.hoverActions_debug,
487 goto_type_def: data.hoverActions_enable && data.hoverActions_gotoTypeDef,
488 links_in_hover: data.hoverActions_linksInHover,
493 pub fn update_caps(&mut self, caps: &ClientCapabilities) {
494 self.caps = caps.clone();
495 if let Some(doc_caps) = caps.text_document.as_ref() {
496 if let Some(value) = doc_caps.hover.as_ref().and_then(|it| it.content_format.as_ref()) {
497 self.hover.markdown = value.contains(&MarkupKind::Markdown)
500 self.completion.allow_snippets(false);
501 self.completion.active_resolve_capabilities =
502 enabled_completions_resolve_capabilities(caps).unwrap_or_default();
503 if let Some(completion) = &doc_caps.completion {
504 if let Some(completion_item) = &completion.completion_item {
505 if let Some(value) = completion_item.snippet_support {
506 self.completion.allow_snippets(value);
512 self.assist.allow_snippets(false);
513 if let Some(experimental) = &caps.experimental {
515 |index: &str| experimental.get(index).and_then(|it| it.as_bool()) == Some(true);
517 let snippet_text_edit = get_bool("snippetTextEdit");
518 self.assist.allow_snippets(snippet_text_edit);
521 if let Some(workspace_caps) = caps.workspace.as_ref() {
522 if let Some(refresh_support) =
523 workspace_caps.semantic_tokens.as_ref().and_then(|it| it.refresh_support)
525 self.semantic_tokens_refresh = refresh_support;
528 if let Some(refresh_support) =
529 workspace_caps.code_lens.as_ref().and_then(|it| it.refresh_support)
531 self.code_lens_refresh = refresh_support;
536 pub fn json_schema() -> serde_json::Value {
537 ConfigData::json_schema()
543 || -> _ { Some($expr) }()
546 macro_rules! try_or {
547 ($expr:expr, $or:expr) => {
548 try_!($expr).unwrap_or($or)
553 pub fn location_link(&self) -> bool {
554 try_or!(self.caps.text_document.as_ref()?.definition?.link_support?, false)
556 pub fn line_folding_only(&self) -> bool {
557 try_or!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?, false)
559 pub fn hierarchical_symbols(&self) -> bool {
566 .hierarchical_document_symbol_support?,
570 pub fn code_action_literals(&self) -> bool {
577 .code_action_literal_support
581 pub fn work_done_progress(&self) -> bool {
582 try_or!(self.caps.window.as_ref()?.work_done_progress?, false)
584 pub fn code_action_resolve(&self) -> bool {
598 .any(|it| it == "edit")
600 pub fn signature_help_label_offsets(&self) -> bool {
607 .signature_information
609 .parameter_information
611 .label_offset_support?,
616 fn experimental(&self, index: &'static str) -> bool {
617 try_or!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?, false)
619 pub fn code_action_group(&self) -> bool {
620 self.experimental("codeActionGroup")
622 pub fn hover_actions(&self) -> bool {
623 self.experimental("hoverActions")
625 pub fn status_notification(&self) -> bool {
626 self.experimental("statusNotification")
630 #[derive(Deserialize)]
632 enum ManifestOrProjectJson {
634 ProjectJson(ProjectJsonData),
637 #[derive(Deserialize)]
638 #[serde(rename_all = "snake_case")]
639 enum MergeBehaviorDef {
645 #[derive(Deserialize)]
646 #[serde(rename_all = "snake_case")]
647 enum ImportPrefixDef {
653 macro_rules! _config_data {
654 (struct $name:ident {
656 $(#[doc=$doc:literal])*
657 $field:ident: $ty:ty = $default:expr,
660 #[allow(non_snake_case)]
661 struct $name { $($field: $ty,)* }
663 fn from_json(mut json: serde_json::Value) -> $name {
665 $field: get_field(&mut json, stringify!($field), $default),
669 fn json_schema() -> serde_json::Value {
672 let field = stringify!($field);
673 let ty = stringify!($ty);
674 (field, ty, &[$($doc),*], $default)
680 fn manual() -> String {
683 let field = stringify!($field);
684 let ty = stringify!($ty);
685 (field, ty, &[$($doc),*], $default)
692 use _config_data as config_data;
694 fn get_field<T: DeserializeOwned>(
695 json: &mut serde_json::Value,
699 let default = serde_json::from_str(default).unwrap();
701 let mut pointer = field.replace('_', "/");
702 pointer.insert(0, '/');
703 json.pointer_mut(&pointer)
704 .and_then(|it| serde_json::from_value(it.take()).ok())
708 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
709 for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
710 fn key(f: &str) -> &str {
711 f.splitn(2, "_").next().unwrap()
713 assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
718 .map(|(field, ty, doc, default)| {
719 let name = field.replace("_", ".");
720 let name = format!("rust-analyzer.{}", name);
721 let props = field_props(field, ty, doc, default);
724 .collect::<serde_json::Map<_, _>>();
728 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
729 let doc = doc.iter().map(|it| it.trim()).join(" ");
731 doc.ends_with('.') && doc.starts_with(char::is_uppercase),
732 "bad docs for {}: {:?}",
736 let default = default.parse::<serde_json::Value>().unwrap();
738 let mut map = serde_json::Map::default();
740 ($($key:literal: $value:tt),*$(,)?) => {{$(
741 map.insert($key.into(), serde_json::json!($value));
744 set!("markdownDescription": doc);
745 set!("default": default);
748 "bool" => set!("type": "boolean"),
749 "String" => set!("type": "string"),
750 "Vec<String>" => set! {
752 "items": { "type": "string" },
754 "FxHashSet<String>" => set! {
756 "items": { "type": "string" },
759 "Option<usize>" => set! {
760 "type": ["null", "integer"],
763 "Option<String>" => set! {
764 "type": ["null", "string"],
766 "Option<bool>" => set! {
767 "type": ["null", "boolean"],
769 "Option<Vec<String>>" => set! {
770 "type": ["null", "array"],
771 "items": { "type": "string" },
773 "MergeBehaviorDef" => set! {
775 "enum": ["none", "full", "last"],
776 "enumDescriptions": [
778 "Merge all layers of the import trees",
779 "Only merge the last layer of the import trees"
782 "ImportPrefixDef" => set! {
789 "enumDescriptions": [
790 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
791 "Prefix all import paths with `self` if they don't begin with `self`, `super`, `crate` or a crate name.",
792 "Force import paths to be absolute by always starting them with `crate` or the crate name they refer to."
795 "Vec<ManifestOrProjectJson>" => set! {
797 "items": { "type": ["string", "object"] },
799 _ => panic!("{}: {}", ty, default),
806 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
809 .map(|(field, _ty, doc, default)| {
810 let name = format!("rust-analyzer.{}", field.replace("_", "."));
811 format!("[[{}]]{} (default: `{}`)::\n{}\n", name, name, default, doc.join(" "))
820 use test_utils::project_dir;
825 fn schema_in_sync_with_package_json() {
826 let s = Config::json_schema();
827 let schema = format!("{:#}", s);
828 let schema = schema.trim_start_matches('{').trim_end_matches('}');
830 let package_json = project_dir().join("editors/code/package.json");
831 let package_json = fs::read_to_string(&package_json).unwrap();
833 let p = remove_ws(&package_json);
834 let s = remove_ws(&schema);
836 assert!(p.contains(&s), "update config in package.json. New config:\n{:#}", schema);
840 fn schema_in_sync_with_docs() {
841 let docs_path = project_dir().join("docs/user/generated_config.adoc");
842 let current = fs::read_to_string(&docs_path).unwrap();
843 let expected = ConfigData::manual();
845 if remove_ws(¤t) != remove_ws(&expected) {
846 fs::write(&docs_path, expected).unwrap();
847 panic!("updated config manual");
851 fn remove_ws(text: &str) -> String {
852 text.replace(char::is_whitespace, "")