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,
202 pub linked_projects: Vec<LinkedProject>,
203 pub root_path: AbsPathBuf,
206 #[derive(Debug, Clone, Eq, PartialEq)]
207 pub enum LinkedProject {
208 ProjectManifest(ProjectManifest),
209 InlineJsonProject(ProjectJson),
212 impl From<ProjectManifest> for LinkedProject {
213 fn from(v: ProjectManifest) -> Self {
214 LinkedProject::ProjectManifest(v)
218 impl From<ProjectJson> for LinkedProject {
219 fn from(v: ProjectJson) -> Self {
220 LinkedProject::InlineJsonProject(v)
224 #[derive(Clone, Debug, PartialEq, Eq)]
225 pub struct LensConfig {
228 pub implementations: bool,
229 pub method_refs: bool,
232 impl Default for LensConfig {
233 fn default() -> Self {
234 Self { run: true, debug: true, implementations: true, method_refs: false }
239 pub fn any(&self) -> bool {
240 self.implementations || self.runnable() || self.references()
243 pub fn none(&self) -> bool {
247 pub fn runnable(&self) -> bool {
248 self.run || self.debug
251 pub fn references(&self) -> bool {
256 #[derive(Debug, Clone)]
257 pub struct FilesConfig {
258 pub watcher: FilesWatcher,
259 pub exclude: Vec<String>,
262 #[derive(Debug, Clone)]
263 pub enum FilesWatcher {
268 #[derive(Debug, Clone)]
269 pub struct NotificationsConfig {
270 pub cargo_toml_not_found: bool,
273 #[derive(Debug, Clone)]
274 pub enum RustfmtConfig {
275 Rustfmt { extra_args: Vec<String> },
276 CustomCommand { command: String, args: Vec<String> },
279 /// Configuration for runnable items, such as `main` function or tests.
280 #[derive(Debug, Clone, Default)]
281 pub struct RunnablesConfig {
282 /// Custom command to be executed instead of `cargo` for runnables.
283 pub override_cargo: Option<String>,
284 /// Additional arguments for the `cargo`, e.g. `--release`.
285 pub cargo_extra_args: Vec<String>,
288 #[derive(Debug, Clone, Default)]
289 pub struct ClientCapsConfig {
290 pub location_link: bool,
291 pub line_folding_only: bool,
292 pub hierarchical_symbols: bool,
293 pub code_action_literals: bool,
294 pub work_done_progress: bool,
295 pub code_action_group: bool,
296 pub code_action_resolve: bool,
297 pub hover_actions: bool,
298 pub status_notification: bool,
299 pub signature_help_label_offsets: bool,
303 pub fn new(root_path: AbsPathBuf) -> Self {
304 // Defaults here don't matter, we'll immediately re-write them with
306 let mut res = Config {
307 client_caps: ClientCapsConfig::default(),
309 publish_diagnostics: false,
310 diagnostics: DiagnosticsConfig::default(),
311 diagnostics_map: DiagnosticsMapConfig::default(),
313 proc_macro_srv: None,
314 files: FilesConfig { watcher: FilesWatcher::Notify, exclude: Vec::new() },
315 notifications: NotificationsConfig { cargo_toml_not_found: false },
317 cargo_autoreload: false,
318 cargo: CargoConfig::default(),
319 rustfmt: RustfmtConfig::Rustfmt { extra_args: Vec::new() },
320 flycheck: Some(FlycheckConfig::CargoCommand {
321 command: String::new(),
323 no_default_features: false,
326 extra_args: Vec::new(),
327 features: Vec::new(),
329 runnables: RunnablesConfig::default(),
331 inlay_hints: InlayHintsConfig {
333 parameter_hints: false,
334 chaining_hints: false,
337 completion: CompletionConfig::default(),
338 assist: AssistConfig::default(),
339 call_info_full: false,
340 lens: LensConfig::default(),
341 hover: HoverConfig::default(),
342 semantic_tokens_refresh: false,
343 linked_projects: Vec::new(),
346 res.do_update(serde_json::json!({}));
349 pub fn update(&mut self, json: serde_json::Value) {
350 log::info!("Config::update({:#})", json);
351 if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
354 self.do_update(json);
355 log::info!("Config::update() = {:#?}", self);
357 fn do_update(&mut self, json: serde_json::Value) {
358 let data = ConfigData::from_json(json);
360 self.publish_diagnostics = data.diagnostics_enable;
361 self.diagnostics = DiagnosticsConfig {
362 disable_experimental: !data.diagnostics_enableExperimental,
363 disabled: data.diagnostics_disabled,
365 self.diagnostics_map = DiagnosticsMapConfig {
366 warnings_as_info: data.diagnostics_warningsAsInfo,
367 warnings_as_hint: data.diagnostics_warningsAsHint,
369 self.lru_capacity = data.lruCapacity;
370 self.files.watcher = match data.files_watcher.as_str() {
371 "notify" => FilesWatcher::Notify,
372 "client" | _ => FilesWatcher::Client,
375 NotificationsConfig { cargo_toml_not_found: data.notifications_cargoTomlNotFound };
376 self.cargo_autoreload = data.cargo_autoreload;
378 let rustc_source = if let Some(rustc_source) = data.rustcSource {
379 let rustpath: PathBuf = rustc_source.into();
380 AbsPathBuf::try_from(rustpath)
382 log::error!("rustc source directory must be an absolute path");
389 self.cargo = CargoConfig {
390 no_default_features: data.cargo_noDefaultFeatures,
391 all_features: data.cargo_allFeatures,
392 features: data.cargo_features.clone(),
393 load_out_dirs_from_check: data.cargo_loadOutDirsFromCheck,
394 target: data.cargo_target.clone(),
395 rustc_source: rustc_source,
396 no_sysroot: data.cargo_noSysroot,
398 self.runnables = RunnablesConfig {
399 override_cargo: data.runnables_overrideCargo,
400 cargo_extra_args: data.runnables_cargoExtraArgs,
403 self.proc_macro_srv = if data.procMacro_enable {
404 std::env::current_exe().ok().map(|path| (path, vec!["proc-macro".into()]))
409 self.rustfmt = match data.rustfmt_overrideCommand {
410 Some(mut args) if !args.is_empty() => {
411 let command = args.remove(0);
412 RustfmtConfig::CustomCommand { command, args }
414 Some(_) | None => RustfmtConfig::Rustfmt { extra_args: data.rustfmt_extraArgs },
417 self.flycheck = if data.checkOnSave_enable {
418 let flycheck_config = match data.checkOnSave_overrideCommand {
419 Some(mut args) if !args.is_empty() => {
420 let command = args.remove(0);
421 FlycheckConfig::CustomCommand { command, args }
423 Some(_) | None => FlycheckConfig::CargoCommand {
424 command: data.checkOnSave_command,
425 target_triple: data.checkOnSave_target.or(data.cargo_target),
426 all_targets: data.checkOnSave_allTargets,
427 no_default_features: data
428 .checkOnSave_noDefaultFeatures
429 .unwrap_or(data.cargo_noDefaultFeatures),
430 all_features: data.checkOnSave_allFeatures.unwrap_or(data.cargo_allFeatures),
431 features: data.checkOnSave_features.unwrap_or(data.cargo_features),
432 extra_args: data.checkOnSave_extraArgs,
435 Some(flycheck_config)
440 self.inlay_hints = InlayHintsConfig {
441 type_hints: data.inlayHints_typeHints,
442 parameter_hints: data.inlayHints_parameterHints,
443 chaining_hints: data.inlayHints_chainingHints,
444 max_length: data.inlayHints_maxLength,
447 self.assist.insert_use.merge = match data.assist_importMergeBehaviour {
448 MergeBehaviourDef::None => None,
449 MergeBehaviourDef::Full => Some(MergeBehaviour::Full),
450 MergeBehaviourDef::Last => Some(MergeBehaviour::Last),
452 self.assist.insert_use.prefix_kind = match data.assist_importPrefix {
453 ImportPrefixDef::Plain => PrefixKind::Plain,
454 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
455 ImportPrefixDef::BySelf => PrefixKind::BySelf,
458 self.completion.enable_postfix_completions = data.completion_postfix_enable;
459 self.completion.enable_autoimport_completions = data.completion_autoimport_enable;
460 self.completion.add_call_parenthesis = data.completion_addCallParenthesis;
461 self.completion.add_call_argument_snippets = data.completion_addCallArgumentSnippets;
462 self.completion.merge = self.assist.insert_use.merge;
464 self.call_info_full = data.callInfo_full;
466 self.lens = LensConfig {
467 run: data.lens_enable && data.lens_run,
468 debug: data.lens_enable && data.lens_debug,
469 implementations: data.lens_enable && data.lens_implementations,
470 method_refs: data.lens_enable && data.lens_methodReferences,
473 if !data.linkedProjects.is_empty() {
474 self.linked_projects.clear();
475 for linked_project in data.linkedProjects {
476 let linked_project = match linked_project {
477 ManifestOrProjectJson::Manifest(it) => {
478 let path = self.root_path.join(it);
479 match ProjectManifest::from_manifest_file(path) {
482 log::error!("failed to load linked project: {}", e);
487 ManifestOrProjectJson::ProjectJson(it) => {
488 ProjectJson::new(&self.root_path, it).into()
491 self.linked_projects.push(linked_project);
495 self.hover = HoverConfig {
496 implementations: data.hoverActions_enable && data.hoverActions_implementations,
497 run: data.hoverActions_enable && data.hoverActions_run,
498 debug: data.hoverActions_enable && data.hoverActions_debug,
499 goto_type_def: data.hoverActions_enable && data.hoverActions_gotoTypeDef,
500 links_in_hover: data.hoverActions_linksInHover,
505 pub fn update_caps(&mut self, caps: &ClientCapabilities) {
506 if let Some(doc_caps) = caps.text_document.as_ref() {
507 if let Some(value) = doc_caps.hover.as_ref().and_then(|it| it.content_format.as_ref()) {
508 self.hover.markdown = value.contains(&MarkupKind::Markdown)
510 if let Some(value) = doc_caps.definition.as_ref().and_then(|it| it.link_support) {
511 self.client_caps.location_link = value;
513 if let Some(value) = doc_caps.folding_range.as_ref().and_then(|it| it.line_folding_only)
515 self.client_caps.line_folding_only = value
517 if let Some(value) = doc_caps
520 .and_then(|it| it.hierarchical_document_symbol_support)
522 self.client_caps.hierarchical_symbols = value
525 doc_caps.code_action.as_ref().map(|it| it.code_action_literal_support.is_some())
527 self.client_caps.code_action_literals = value;
529 if let Some(value) = doc_caps
532 .and_then(|it| it.signature_information.as_ref())
533 .and_then(|it| it.parameter_information.as_ref())
534 .and_then(|it| it.label_offset_support)
536 self.client_caps.signature_help_label_offsets = value;
539 self.completion.allow_snippets(false);
540 self.completion.active_resolve_capabilities =
541 enabled_completions_resolve_capabilities(caps).unwrap_or_default();
542 if let Some(completion) = &doc_caps.completion {
543 if let Some(completion_item) = &completion.completion_item {
544 if let Some(value) = completion_item.snippet_support {
545 self.completion.allow_snippets(value);
550 if let Some(code_action) = &doc_caps.code_action {
551 if let Some(resolve_support) = &code_action.resolve_support {
552 if resolve_support.properties.iter().any(|it| it == "edit") {
553 self.client_caps.code_action_resolve = true;
559 if let Some(window_caps) = caps.window.as_ref() {
560 if let Some(value) = window_caps.work_done_progress {
561 self.client_caps.work_done_progress = value;
565 self.assist.allow_snippets(false);
566 if let Some(experimental) = &caps.experimental {
568 |index: &str| experimental.get(index).and_then(|it| it.as_bool()) == Some(true);
570 let snippet_text_edit = get_bool("snippetTextEdit");
571 self.assist.allow_snippets(snippet_text_edit);
573 self.client_caps.code_action_group = get_bool("codeActionGroup");
574 self.client_caps.hover_actions = get_bool("hoverActions");
575 self.client_caps.status_notification = get_bool("statusNotification");
578 if let Some(workspace_caps) = caps.workspace.as_ref() {
579 if let Some(refresh_support) =
580 workspace_caps.semantic_tokens.as_ref().and_then(|it| it.refresh_support)
582 self.semantic_tokens_refresh = refresh_support;
587 pub fn json_schema() -> serde_json::Value {
588 ConfigData::json_schema()
592 #[derive(Deserialize)]
594 enum ManifestOrProjectJson {
596 ProjectJson(ProjectJsonData),
599 #[derive(Deserialize)]
600 #[serde(rename_all = "snake_case")]
601 enum MergeBehaviourDef {
607 #[derive(Deserialize)]
608 #[serde(rename_all = "snake_case")]
609 enum ImportPrefixDef {
615 macro_rules! _config_data {
616 (struct $name:ident {
618 $(#[doc=$doc:literal])*
619 $field:ident: $ty:ty = $default:expr,
622 #[allow(non_snake_case)]
623 struct $name { $($field: $ty,)* }
625 fn from_json(mut json: serde_json::Value) -> $name {
627 $field: get_field(&mut json, stringify!($field), $default),
631 fn json_schema() -> serde_json::Value {
634 let field = stringify!($field);
635 let ty = stringify!($ty);
636 (field, ty, &[$($doc),*], $default)
642 fn manual() -> String {
645 let field = stringify!($field);
646 let ty = stringify!($ty);
647 (field, ty, &[$($doc),*], $default)
654 use _config_data as config_data;
656 fn get_field<T: DeserializeOwned>(
657 json: &mut serde_json::Value,
661 let default = serde_json::from_str(default).unwrap();
663 let mut pointer = field.replace('_', "/");
664 pointer.insert(0, '/');
665 json.pointer_mut(&pointer)
666 .and_then(|it| serde_json::from_value(it.take()).ok())
670 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
671 for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
672 fn key(f: &str) -> &str {
673 f.splitn(2, "_").next().unwrap()
675 assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
680 .map(|(field, ty, doc, default)| {
681 let name = field.replace("_", ".");
682 let name = format!("rust-analyzer.{}", name);
683 let props = field_props(field, ty, doc, default);
686 .collect::<serde_json::Map<_, _>>();
690 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
691 let doc = doc.iter().map(|it| it.trim()).join(" ");
693 doc.ends_with('.') && doc.starts_with(char::is_uppercase),
694 "bad docs for {}: {:?}",
698 let default = default.parse::<serde_json::Value>().unwrap();
700 let mut map = serde_json::Map::default();
702 ($($key:literal: $value:tt),*$(,)?) => {{$(
703 map.insert($key.into(), serde_json::json!($value));
706 set!("markdownDescription": doc);
707 set!("default": default);
710 "bool" => set!("type": "boolean"),
711 "String" => set!("type": "string"),
712 "Vec<String>" => set! {
714 "items": { "type": "string" },
716 "FxHashSet<String>" => set! {
718 "items": { "type": "string" },
721 "Option<usize>" => set! {
722 "type": ["null", "integer"],
725 "Option<String>" => set! {
726 "type": ["null", "string"],
728 "Option<bool>" => set! {
729 "type": ["null", "boolean"],
731 "Option<Vec<String>>" => set! {
732 "type": ["null", "array"],
733 "items": { "type": "string" },
735 "MergeBehaviourDef" => set! {
737 "enum": ["none", "full", "last"],
738 "enumDescriptions": [
740 "Merge all layers of the import trees",
741 "Only merge the last layer of the import trees"
744 "ImportPrefixDef" => set! {
751 "enumDescriptions": [
752 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
753 "Prefix all import paths with `self` if they don't begin with `self`, `super`, `crate` or a crate name",
754 "Force import paths to be absolute by always starting them with `crate` or the crate name they refer to."
757 "Vec<ManifestOrProjectJson>" => set! {
759 "items": { "type": ["string", "object"] },
761 _ => panic!("{}: {}", ty, default),
768 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
771 .map(|(field, _ty, doc, default)| {
772 let name = field.replace("_", ".");
773 let name = format!("rust-analyzer.{} (default: `{}`)", name, default);
774 format!("{}::\n{}\n", name, doc.join(" "))
783 use test_utils::project_dir;
788 fn schema_in_sync_with_package_json() {
789 let s = Config::json_schema();
790 let schema = format!("{:#}", s);
791 let schema = schema.trim_start_matches('{').trim_end_matches('}');
793 let package_json = project_dir().join("editors/code/package.json");
794 let package_json = fs::read_to_string(&package_json).unwrap();
796 let p = remove_ws(&package_json);
797 let s = remove_ws(&schema);
799 assert!(p.contains(&s), "update config in package.json. New config:\n{:#}", schema);
803 fn schema_in_sync_with_docs() {
804 let docs_path = project_dir().join("docs/user/generated_config.adoc");
805 let current = fs::read_to_string(&docs_path).unwrap();
806 let expected = ConfigData::manual();
808 if remove_ws(¤t) != remove_ws(&expected) {
809 fs::write(&docs_path, expected).unwrap();
810 panic!("updated config manual");
814 fn remove_ws(text: &str) -> String {
815 text.replace(char::is_whitespace, "")