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 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, RustcSource};
22 use rustc_hash::FxHashSet;
23 use serde::{de::DeserializeOwned, Deserialize};
27 caps::completion_item_edit_resolve, diagnostics::DiagnosticsMapConfig,
28 line_index::OffsetEncoding, lsp_ext::supports_utf8,
33 /// The strategy to use when inserting new imports or merging imports.
34 assist_importMergeBehavior |
35 assist_importMergeBehaviour: MergeBehaviorDef = "\"full\"",
36 /// The path structure for newly inserted paths to use.
37 assist_importPrefix: ImportPrefixDef = "\"plain\"",
38 /// Group inserted imports by the [following order](https://rust-analyzer.github.io/manual.html#auto-import). Groups are separated by newlines.
39 assist_importGroup: bool = "true",
40 /// Show function name and docs in parameter hints.
41 callInfo_full: bool = "true",
43 /// Automatically refresh project info via `cargo metadata` on
44 /// `Cargo.toml` changes.
45 cargo_autoreload: bool = "true",
46 /// Activate all available features (`--all-features`).
47 cargo_allFeatures: bool = "false",
48 /// List of features to activate.
49 cargo_features: Vec<String> = "[]",
50 /// Run build scripts (`build.rs`) for more precise code analysis.
51 cargo_runBuildScripts |
52 cargo_loadOutDirsFromCheck: bool = "false",
53 /// Do not activate the `default` feature.
54 cargo_noDefaultFeatures: bool = "false",
55 /// Compilation target (target triple).
56 cargo_target: Option<String> = "null",
57 /// Internal config for debugging, disables loading of sysroot crates.
58 cargo_noSysroot: bool = "false",
60 /// Run specified `cargo check` command for diagnostics on save.
61 checkOnSave_enable: bool = "true",
62 /// Check with all features (`--all-features`).
63 /// Defaults to `#rust-analyzer.cargo.allFeatures#`.
64 checkOnSave_allFeatures: Option<bool> = "null",
65 /// Check all targets and tests (`--all-targets`).
66 checkOnSave_allTargets: bool = "true",
67 /// Cargo command to use for `cargo check`.
68 checkOnSave_command: String = "\"check\"",
69 /// Do not activate the `default` feature.
70 checkOnSave_noDefaultFeatures: Option<bool> = "null",
71 /// Check for a specific target. Defaults to
72 /// `#rust-analyzer.cargo.target#`.
73 checkOnSave_target: Option<String> = "null",
74 /// Extra arguments for `cargo check`.
75 checkOnSave_extraArgs: Vec<String> = "[]",
76 /// List of features to activate. Defaults to
77 /// `#rust-analyzer.cargo.features#`.
78 checkOnSave_features: Option<Vec<String>> = "null",
79 /// Advanced option, fully override the command rust-analyzer uses for
80 /// checking. The command should include `--message-format=json` or
82 checkOnSave_overrideCommand: Option<Vec<String>> = "null",
84 /// Whether to add argument snippets when completing functions.
85 completion_addCallArgumentSnippets: bool = "true",
86 /// Whether to add parenthesis when completing functions.
87 completion_addCallParenthesis: bool = "true",
88 /// Whether to show postfix snippets like `dbg`, `if`, `not`, etc.
89 completion_postfix_enable: bool = "true",
90 /// Toggles the additional completions that automatically add imports when completed.
91 /// Note that your client must specify the `additionalTextEdits` LSP client capability to truly have this feature enabled.
92 completion_autoimport_enable: bool = "true",
94 /// Whether to show native rust-analyzer diagnostics.
95 diagnostics_enable: bool = "true",
96 /// Whether to show experimental rust-analyzer diagnostics that might
97 /// have more false positives than usual.
98 diagnostics_enableExperimental: bool = "true",
99 /// List of rust-analyzer diagnostics to disable.
100 diagnostics_disabled: FxHashSet<String> = "[]",
101 /// List of warnings that should be displayed with info severity.\n\nThe
102 /// warnings will be indicated by a blue squiggly underline in code and
103 /// a blue icon in the `Problems Panel`.
104 diagnostics_warningsAsHint: Vec<String> = "[]",
105 /// List of warnings that should be displayed with hint severity.\n\nThe
106 /// warnings will be indicated by faded text or three dots in code and
107 /// will not show up in the `Problems Panel`.
108 diagnostics_warningsAsInfo: Vec<String> = "[]",
110 /// Controls file watching implementation.
111 files_watcher: String = "\"client\"",
112 /// These directories will be ignored by rust-analyzer.
113 files_excludeDirs: Vec<PathBuf> = "[]",
115 /// Whether to show `Debug` action. Only applies when
116 /// `#rust-analyzer.hoverActions.enable#` is set.
117 hoverActions_debug: bool = "true",
118 /// Whether to show HoverActions in Rust files.
119 hoverActions_enable: bool = "true",
120 /// Whether to show `Go to Type Definition` action. Only applies when
121 /// `#rust-analyzer.hoverActions.enable#` is set.
122 hoverActions_gotoTypeDef: bool = "true",
123 /// Whether to show `Implementations` action. Only applies when
124 /// `#rust-analyzer.hoverActions.enable#` is set.
125 hoverActions_implementations: bool = "true",
126 /// Whether to show `Run` action. Only applies when
127 /// `#rust-analyzer.hoverActions.enable#` is set.
128 hoverActions_run: bool = "true",
129 /// Use markdown syntax for links in hover.
130 hoverActions_linksInHover: bool = "true",
132 /// Whether to show inlay type hints for method chains.
133 inlayHints_chainingHints: bool = "true",
134 /// Maximum length for inlay hints. Default is unlimited.
135 inlayHints_maxLength: Option<usize> = "null",
136 /// Whether to show function parameter name inlay hints at the call
138 inlayHints_parameterHints: bool = "true",
139 /// Whether to show inlay type hints for variables.
140 inlayHints_typeHints: bool = "true",
142 /// Whether to show `Debug` lens. Only applies when
143 /// `#rust-analyzer.lens.enable#` is set.
144 lens_debug: bool = "true",
145 /// Whether to show CodeLens in Rust files.
146 lens_enable: bool = "true",
147 /// Whether to show `Implementations` lens. Only applies when
148 /// `#rust-analyzer.lens.enable#` is set.
149 lens_implementations: bool = "true",
150 /// Whether to show `Run` lens. Only applies when
151 /// `#rust-analyzer.lens.enable#` is set.
152 lens_run: bool = "true",
153 /// Whether to show `Method References` lens. Only applies when
154 /// `#rust-analyzer.lens.enable#` is set.
155 lens_methodReferences: bool = "false",
156 /// Whether to show `References` lens. Only applies when
157 /// `#rust-analyzer.lens.enable#` is set.
158 lens_references: bool = "false",
160 /// Disable project auto-discovery in favor of explicitly specified set
161 /// of projects.\n\nElements must be paths pointing to `Cargo.toml`,
162 /// `rust-project.json`, or JSON objects in `rust-project.json` format.
163 linkedProjects: Vec<ManifestOrProjectJson> = "[]",
165 /// Number of syntax trees rust-analyzer keeps in memory. Defaults to 128.
166 lruCapacity: Option<usize> = "null",
168 /// Whether to show `can't find Cargo.toml` error message.
169 notifications_cargoTomlNotFound: bool = "true",
171 /// Enable support for procedural macros, implies `#rust-analyzer.cargo.runBuildScripts#`.
172 procMacro_enable: bool = "false",
173 /// Internal config, path to proc-macro server executable (typically,
174 /// this is rust-analyzer itself, but we override this in tests).
175 procMacro_server: Option<PathBuf> = "null",
177 /// Command to be executed instead of 'cargo' for runnables.
178 runnables_overrideCargo: Option<String> = "null",
179 /// Additional arguments to be passed to cargo for runnables such as
180 /// tests or binaries.\nFor example, it may be `--release`.
181 runnables_cargoExtraArgs: Vec<String> = "[]",
183 /// Path to the rust compiler sources, for usage in rustc_private projects, or "discover"
184 /// to try to automatically find it.
185 rustcSource : Option<String> = "null",
187 /// Additional arguments to `rustfmt`.
188 rustfmt_extraArgs: Vec<String> = "[]",
189 /// Advanced option, fully override the command rust-analyzer uses for
191 rustfmt_overrideCommand: Option<Vec<String>> = "null",
195 impl Default for ConfigData {
196 fn default() -> Self {
197 ConfigData::from_json(serde_json::Value::Null)
201 #[derive(Debug, Clone)]
203 caps: lsp_types::ClientCapabilities,
205 pub discovered_projects: Option<Vec<ProjectManifest>>,
206 pub root_path: AbsPathBuf,
209 #[derive(Debug, Clone, Eq, PartialEq)]
210 pub enum LinkedProject {
211 ProjectManifest(ProjectManifest),
212 InlineJsonProject(ProjectJson),
215 impl From<ProjectManifest> for LinkedProject {
216 fn from(v: ProjectManifest) -> Self {
217 LinkedProject::ProjectManifest(v)
221 impl From<ProjectJson> for LinkedProject {
222 fn from(v: ProjectJson) -> Self {
223 LinkedProject::InlineJsonProject(v)
227 #[derive(Clone, Debug, PartialEq, Eq)]
228 pub struct LensConfig {
231 pub implementations: bool,
232 pub method_refs: bool,
233 pub refs: bool, // for Struct, Enum, Union and Trait
237 pub fn any(&self) -> bool {
238 self.implementations || self.runnable() || self.references()
241 pub fn none(&self) -> bool {
245 pub fn runnable(&self) -> bool {
246 self.run || self.debug
249 pub fn references(&self) -> bool {
250 self.method_refs || self.refs
254 #[derive(Debug, Clone)]
255 pub struct FilesConfig {
256 pub watcher: FilesWatcher,
257 pub exclude: Vec<AbsPathBuf>,
260 #[derive(Debug, Clone)]
261 pub enum FilesWatcher {
266 #[derive(Debug, Clone)]
267 pub struct NotificationsConfig {
268 pub cargo_toml_not_found: bool,
271 #[derive(Debug, Clone)]
272 pub enum RustfmtConfig {
273 Rustfmt { extra_args: Vec<String> },
274 CustomCommand { command: String, args: Vec<String> },
277 /// Configuration for runnable items, such as `main` function or tests.
278 #[derive(Debug, Clone)]
279 pub struct RunnablesConfig {
280 /// Custom command to be executed instead of `cargo` for runnables.
281 pub override_cargo: Option<String>,
282 /// Additional arguments for the `cargo`, e.g. `--release`.
283 pub cargo_extra_args: Vec<String>,
287 pub fn new(root_path: AbsPathBuf, caps: ClientCapabilities) -> Self {
288 Config { caps, data: ConfigData::default(), discovered_projects: None, root_path }
290 pub fn update(&mut self, json: serde_json::Value) {
291 log::info!("updating config from JSON: {:#}", json);
292 if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
295 self.data = ConfigData::from_json(json);
298 pub fn json_schema() -> serde_json::Value {
299 ConfigData::json_schema()
305 || -> _ { Some($expr) }()
308 macro_rules! try_or {
309 ($expr:expr, $or:expr) => {
310 try_!($expr).unwrap_or($or)
315 pub fn linked_projects(&self) -> Vec<LinkedProject> {
316 if self.data.linkedProjects.is_empty() {
317 self.discovered_projects
322 .map(LinkedProject::from)
328 .filter_map(|linked_project| {
329 let res = match linked_project {
330 ManifestOrProjectJson::Manifest(it) => {
331 let path = self.root_path.join(it);
332 ProjectManifest::from_manifest_file(path)
333 .map_err(|e| log::error!("failed to load linked project: {}", e))
337 ManifestOrProjectJson::ProjectJson(it) => {
338 ProjectJson::new(&self.root_path, it.clone()).into()
347 pub fn did_save_text_document_dynamic_registration(&self) -> bool {
349 try_or!(self.caps.text_document.as_ref()?.synchronization.clone()?, Default::default());
350 caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
352 pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
354 self.caps.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration?,
359 pub fn location_link(&self) -> bool {
360 try_or!(self.caps.text_document.as_ref()?.definition?.link_support?, false)
362 pub fn line_folding_only(&self) -> bool {
363 try_or!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?, false)
365 pub fn hierarchical_symbols(&self) -> bool {
372 .hierarchical_document_symbol_support?,
376 pub fn code_action_literals(&self) -> bool {
383 .code_action_literal_support
387 pub fn work_done_progress(&self) -> bool {
388 try_or!(self.caps.window.as_ref()?.work_done_progress?, false)
390 pub fn code_action_resolve(&self) -> bool {
404 .any(|it| it == "edit")
406 pub fn signature_help_label_offsets(&self) -> bool {
413 .signature_information
415 .parameter_information
417 .label_offset_support?,
421 pub fn offset_encoding(&self) -> OffsetEncoding {
422 if supports_utf8(&self.caps) {
425 OffsetEncoding::Utf16
429 fn experimental(&self, index: &'static str) -> bool {
430 try_or!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?, false)
432 pub fn code_action_group(&self) -> bool {
433 self.experimental("codeActionGroup")
435 pub fn hover_actions(&self) -> bool {
436 self.experimental("hoverActions")
438 pub fn status_notification(&self) -> bool {
439 self.experimental("statusNotification")
442 pub fn publish_diagnostics(&self) -> bool {
443 self.data.diagnostics_enable
445 pub fn diagnostics(&self) -> DiagnosticsConfig {
447 disable_experimental: !self.data.diagnostics_enableExperimental,
448 disabled: self.data.diagnostics_disabled.clone(),
451 pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
452 DiagnosticsMapConfig {
453 warnings_as_info: self.data.diagnostics_warningsAsInfo.clone(),
454 warnings_as_hint: self.data.diagnostics_warningsAsHint.clone(),
457 pub fn lru_capacity(&self) -> Option<usize> {
458 self.data.lruCapacity
460 pub fn proc_macro_srv(&self) -> Option<(PathBuf, Vec<OsString>)> {
461 if !self.data.procMacro_enable {
465 let path = self.data.procMacro_server.clone().or_else(|| std::env::current_exe().ok())?;
466 Some((path, vec!["proc-macro".into()]))
468 pub fn files(&self) -> FilesConfig {
470 watcher: match self.data.files_watcher.as_str() {
471 "notify" => FilesWatcher::Notify,
472 "client" | _ => FilesWatcher::Client,
474 exclude: self.data.files_excludeDirs.iter().map(|it| self.root_path.join(it)).collect(),
477 pub fn notifications(&self) -> NotificationsConfig {
478 NotificationsConfig { cargo_toml_not_found: self.data.notifications_cargoTomlNotFound }
480 pub fn cargo_autoreload(&self) -> bool {
481 self.data.cargo_autoreload
483 pub fn run_build_scripts(&self) -> bool {
484 self.data.cargo_runBuildScripts || self.data.procMacro_enable
486 pub fn cargo(&self) -> CargoConfig {
487 let rustc_source = self.data.rustcSource.as_ref().map(|rustc_src| {
488 if rustc_src == "discover" {
489 RustcSource::Discover
491 RustcSource::Path(self.root_path.join(rustc_src))
496 no_default_features: self.data.cargo_noDefaultFeatures,
497 all_features: self.data.cargo_allFeatures,
498 features: self.data.cargo_features.clone(),
499 target: self.data.cargo_target.clone(),
501 no_sysroot: self.data.cargo_noSysroot,
504 pub fn rustfmt(&self) -> RustfmtConfig {
505 match &self.data.rustfmt_overrideCommand {
506 Some(args) if !args.is_empty() => {
507 let mut args = args.clone();
508 let command = args.remove(0);
509 RustfmtConfig::CustomCommand { command, args }
512 RustfmtConfig::Rustfmt { extra_args: self.data.rustfmt_extraArgs.clone() }
516 pub fn flycheck(&self) -> Option<FlycheckConfig> {
517 if !self.data.checkOnSave_enable {
520 let flycheck_config = match &self.data.checkOnSave_overrideCommand {
521 Some(args) if !args.is_empty() => {
522 let mut args = args.clone();
523 let command = args.remove(0);
524 FlycheckConfig::CustomCommand { command, args }
526 Some(_) | None => FlycheckConfig::CargoCommand {
527 command: self.data.checkOnSave_command.clone(),
532 .or_else(|| self.data.cargo_target.clone()),
533 all_targets: self.data.checkOnSave_allTargets,
534 no_default_features: self
536 .checkOnSave_noDefaultFeatures
537 .unwrap_or(self.data.cargo_noDefaultFeatures),
540 .checkOnSave_allFeatures
541 .unwrap_or(self.data.cargo_allFeatures),
544 .checkOnSave_features
546 .unwrap_or_else(|| self.data.cargo_features.clone()),
547 extra_args: self.data.checkOnSave_extraArgs.clone(),
550 Some(flycheck_config)
552 pub fn runnables(&self) -> RunnablesConfig {
554 override_cargo: self.data.runnables_overrideCargo.clone(),
555 cargo_extra_args: self.data.runnables_cargoExtraArgs.clone(),
558 pub fn inlay_hints(&self) -> InlayHintsConfig {
560 type_hints: self.data.inlayHints_typeHints,
561 parameter_hints: self.data.inlayHints_parameterHints,
562 chaining_hints: self.data.inlayHints_chainingHints,
563 max_length: self.data.inlayHints_maxLength,
566 fn insert_use_config(&self) -> InsertUseConfig {
568 merge: match self.data.assist_importMergeBehavior {
569 MergeBehaviorDef::None => None,
570 MergeBehaviorDef::Full => Some(MergeBehavior::Full),
571 MergeBehaviorDef::Last => Some(MergeBehavior::Last),
573 prefix_kind: match self.data.assist_importPrefix {
574 ImportPrefixDef::Plain => PrefixKind::Plain,
575 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
576 ImportPrefixDef::BySelf => PrefixKind::BySelf,
578 group: self.data.assist_importGroup,
581 pub fn completion(&self) -> CompletionConfig {
583 enable_postfix_completions: self.data.completion_postfix_enable,
584 enable_imports_on_the_fly: self.data.completion_autoimport_enable
585 && completion_item_edit_resolve(&self.caps),
586 add_call_parenthesis: self.data.completion_addCallParenthesis,
587 add_call_argument_snippets: self.data.completion_addCallArgumentSnippets,
588 insert_use: self.insert_use_config(),
589 snippet_cap: SnippetCap::new(try_or!(
602 pub fn assist(&self) -> AssistConfig {
604 snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
606 insert_use: self.insert_use_config(),
609 pub fn call_info_full(&self) -> bool {
610 self.data.callInfo_full
612 pub fn lens(&self) -> LensConfig {
614 run: self.data.lens_enable && self.data.lens_run,
615 debug: self.data.lens_enable && self.data.lens_debug,
616 implementations: self.data.lens_enable && self.data.lens_implementations,
617 method_refs: self.data.lens_enable && self.data.lens_methodReferences,
618 refs: self.data.lens_enable && self.data.lens_references,
621 pub fn hover(&self) -> HoverConfig {
623 implementations: self.data.hoverActions_enable
624 && self.data.hoverActions_implementations,
625 run: self.data.hoverActions_enable && self.data.hoverActions_run,
626 debug: self.data.hoverActions_enable && self.data.hoverActions_debug,
627 goto_type_def: self.data.hoverActions_enable && self.data.hoverActions_gotoTypeDef,
628 links_in_hover: self.data.hoverActions_linksInHover,
640 .contains(&MarkupKind::Markdown),
643 pub fn semantic_tokens_refresh(&self) -> bool {
644 try_or!(self.caps.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support?, false)
646 pub fn code_lens_refresh(&self) -> bool {
647 try_or!(self.caps.workspace.as_ref()?.code_lens.as_ref()?.refresh_support?, false)
651 #[derive(Deserialize, Debug, Clone)]
653 enum ManifestOrProjectJson {
655 ProjectJson(ProjectJsonData),
658 #[derive(Deserialize, Debug, Clone)]
659 #[serde(rename_all = "snake_case")]
660 enum MergeBehaviorDef {
666 #[derive(Deserialize, Debug, Clone)]
667 #[serde(rename_all = "snake_case")]
668 enum ImportPrefixDef {
674 macro_rules! _config_data {
675 (struct $name:ident {
677 $(#[doc=$doc:literal])*
678 $field:ident $(| $alias:ident)?: $ty:ty = $default:expr,
681 #[allow(non_snake_case)]
682 #[derive(Debug, Clone)]
683 struct $name { $($field: $ty,)* }
685 fn from_json(mut json: serde_json::Value) -> $name {
690 None$(.or(Some(stringify!($alias))))?,
696 fn json_schema() -> serde_json::Value {
699 let field = stringify!($field);
700 let ty = stringify!($ty);
701 (field, ty, &[$($doc),*], $default)
707 fn manual() -> String {
710 let field = stringify!($field);
711 let ty = stringify!($ty);
712 (field, ty, &[$($doc),*], $default)
719 use _config_data as config_data;
721 fn get_field<T: DeserializeOwned>(
722 json: &mut serde_json::Value,
724 alias: Option<&'static str>,
727 let default = serde_json::from_str(default).unwrap();
729 // XXX: check alias first, to work-around the VS Code where it pre-fills the
730 // defaults instead of sending an empty object.
733 .chain(iter::once(field))
734 .find_map(move |field| {
735 let mut pointer = field.replace('_', "/");
736 pointer.insert(0, '/');
737 json.pointer_mut(&pointer).and_then(|it| serde_json::from_value(it.take()).ok())
742 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
743 for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
744 fn key(f: &str) -> &str {
745 f.splitn(2, '_').next().unwrap()
747 assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
752 .map(|(field, ty, doc, default)| {
753 let name = field.replace("_", ".");
754 let name = format!("rust-analyzer.{}", name);
755 let props = field_props(field, ty, doc, default);
758 .collect::<serde_json::Map<_, _>>();
762 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
763 let doc = doc.iter().map(|it| it.trim()).join(" ");
765 doc.ends_with('.') && doc.starts_with(char::is_uppercase),
766 "bad docs for {}: {:?}",
770 let default = default.parse::<serde_json::Value>().unwrap();
772 let mut map = serde_json::Map::default();
774 ($($key:literal: $value:tt),*$(,)?) => {{$(
775 map.insert($key.into(), serde_json::json!($value));
778 set!("markdownDescription": doc);
779 set!("default": default);
782 "bool" => set!("type": "boolean"),
783 "String" => set!("type": "string"),
784 "Vec<String>" => set! {
786 "items": { "type": "string" },
788 "Vec<PathBuf>" => set! {
790 "items": { "type": "string" },
792 "FxHashSet<String>" => set! {
794 "items": { "type": "string" },
797 "Option<usize>" => set! {
798 "type": ["null", "integer"],
801 "Option<String>" => set! {
802 "type": ["null", "string"],
804 "Option<PathBuf>" => set! {
805 "type": ["null", "string"],
807 "Option<bool>" => set! {
808 "type": ["null", "boolean"],
810 "Option<Vec<String>>" => set! {
811 "type": ["null", "array"],
812 "items": { "type": "string" },
814 "MergeBehaviorDef" => set! {
816 "enum": ["none", "full", "last"],
817 "enumDescriptions": [
819 "Merge all layers of the import trees",
820 "Only merge the last layer of the import trees"
823 "ImportPrefixDef" => set! {
830 "enumDescriptions": [
831 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
832 "Prefix all import paths with `self` if they don't begin with `self`, `super`, `crate` or a crate name.",
833 "Force import paths to be absolute by always starting them with `crate` or the crate name they refer to."
836 "Vec<ManifestOrProjectJson>" => set! {
838 "items": { "type": ["string", "object"] },
840 _ => panic!("{}: {}", ty, default),
847 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
850 .map(|(field, _ty, doc, default)| {
851 let name = format!("rust-analyzer.{}", field.replace("_", "."));
852 format!("[[{}]]{} (default: `{}`)::\n{}\n", name, name, default, doc.join(" "))
861 use test_utils::project_dir;
866 fn schema_in_sync_with_package_json() {
867 let s = Config::json_schema();
868 let schema = format!("{:#}", s);
869 let mut schema = schema
870 .trim_start_matches('{')
871 .trim_end_matches('}')
873 .replace("\n", "\n ")
874 .trim_start_matches('\n')
877 schema.push_str(",\n");
879 let package_json_path = project_dir().join("editors/code/package.json");
880 let mut package_json = fs::read_to_string(&package_json_path).unwrap();
882 let start_marker = " \"$generated-start\": false,\n";
883 let end_marker = " \"$generated-end\": false\n";
885 let start = package_json.find(start_marker).unwrap() + start_marker.len();
886 let end = package_json.find(end_marker).unwrap();
887 let p = remove_ws(&package_json[start..end]);
888 let s = remove_ws(&schema);
891 package_json.replace_range(start..end, &schema);
892 fs::write(&package_json_path, &mut package_json).unwrap();
893 panic!("new config, updating package.json")
898 fn schema_in_sync_with_docs() {
899 let docs_path = project_dir().join("docs/user/generated_config.adoc");
900 let current = fs::read_to_string(&docs_path).unwrap();
901 let expected = ConfigData::manual();
903 if remove_ws(¤t) != remove_ws(&expected) {
904 fs::write(&docs_path, expected).unwrap();
905 panic!("updated config manual");
909 fn remove_ws(text: &str) -> String {
910 text.replace(char::is_whitespace, "")