diff options
author | bors[bot] <26634292+bors[bot]@users.noreply.github.com> | 2020-12-08 18:21:28 +0000 |
---|---|---|
committer | GitHub <[email protected]> | 2020-12-08 18:21:28 +0000 |
commit | b3ceee2a2764a64318d16708a3ce2d281611bd26 (patch) | |
tree | f78ffdaa994c9bce879d6f01e79bd3686a51d963 /crates | |
parent | 87e35006362686b281caf46550c0fff35cddefb4 (diff) | |
parent | 2544abbf867a7660bc2c9342181c8392774f1cca (diff) |
Merge #6761
6761: Make config.rs a single source of truth for configuration. r=matklad a=matklad
Configuration is editor-independent. For this reason, we pick
JSON-schema as the repr of the source of truth. We do specify it using
rust-macros and some quick&dirty hackery though.
The idea for syncing truth with package.json is to just do that
manually, but there's a test to check that they are actually synced.
I'll add something like `rust-analyzer --config-schema` in a follow-up
commit.
Co-authored-by: Aleksey Kladov <[email protected]>
Diffstat (limited to 'crates')
-rw-r--r-- | crates/rust-analyzer/Cargo.toml | 2 | ||||
-rw-r--r-- | crates/rust-analyzer/src/bin/args.rs | 5 | ||||
-rw-r--r-- | crates/rust-analyzer/src/bin/main.rs | 3 | ||||
-rw-r--r-- | crates/rust-analyzer/src/config.rs | 430 | ||||
-rw-r--r-- | crates/test_utils/src/lib.rs | 26 |
5 files changed, 354 insertions, 112 deletions
diff --git a/crates/rust-analyzer/Cargo.toml b/crates/rust-analyzer/Cargo.toml index 0a055b039..039976e4b 100644 --- a/crates/rust-analyzer/Cargo.toml +++ b/crates/rust-analyzer/Cargo.toml | |||
@@ -27,7 +27,7 @@ pico-args = "0.3.1" | |||
27 | oorandom = "11.1.2" | 27 | oorandom = "11.1.2" |
28 | rustc-hash = "1.1.0" | 28 | rustc-hash = "1.1.0" |
29 | serde = { version = "1.0.106", features = ["derive"] } | 29 | serde = { version = "1.0.106", features = ["derive"] } |
30 | serde_json = "1.0.48" | 30 | serde_json = { version = "1.0.48", features = ["preserve_order"] } |
31 | threadpool = "1.7.1" | 31 | threadpool = "1.7.1" |
32 | rayon = "1.5" | 32 | rayon = "1.5" |
33 | mimalloc = { version = "0.1.19", default-features = false, optional = true } | 33 | mimalloc = { version = "0.1.19", default-features = false, optional = true } |
diff --git a/crates/rust-analyzer/src/bin/args.rs b/crates/rust-analyzer/src/bin/args.rs index 8ddf1e031..0a471154e 100644 --- a/crates/rust-analyzer/src/bin/args.rs +++ b/crates/rust-analyzer/src/bin/args.rs | |||
@@ -28,6 +28,7 @@ pub(crate) enum Command { | |||
28 | StructuredSearch { debug_snippet: Option<String>, patterns: Vec<SsrPattern> }, | 28 | StructuredSearch { debug_snippet: Option<String>, patterns: Vec<SsrPattern> }, |
29 | ProcMacro, | 29 | ProcMacro, |
30 | RunServer, | 30 | RunServer, |
31 | PrintConfigSchema, | ||
31 | Version, | 32 | Version, |
32 | Help, | 33 | Help, |
33 | } | 34 | } |
@@ -135,6 +136,10 @@ impl Args { | |||
135 | return Ok(Args { verbosity, log_file: None, command: Command::Help }); | 136 | return Ok(Args { verbosity, log_file: None, command: Command::Help }); |
136 | } | 137 | } |
137 | 138 | ||
139 | if matches.contains("--print-config-schema") { | ||
140 | return Ok(Args { verbosity, log_file, command: Command::PrintConfigSchema }); | ||
141 | } | ||
142 | |||
138 | let subcommand = match matches.subcommand()? { | 143 | let subcommand = match matches.subcommand()? { |
139 | Some(it) => it, | 144 | Some(it) => it, |
140 | None => { | 145 | None => { |
diff --git a/crates/rust-analyzer/src/bin/main.rs b/crates/rust-analyzer/src/bin/main.rs index 21fba8302..defdcbd74 100644 --- a/crates/rust-analyzer/src/bin/main.rs +++ b/crates/rust-analyzer/src/bin/main.rs | |||
@@ -31,6 +31,9 @@ fn try_main() -> Result<()> { | |||
31 | setup_logging(args.log_file)?; | 31 | setup_logging(args.log_file)?; |
32 | match args.command { | 32 | match args.command { |
33 | args::Command::RunServer => run_server()?, | 33 | args::Command::RunServer => run_server()?, |
34 | args::Command::PrintConfigSchema => { | ||
35 | println!("{:#}", Config::json_schema()); | ||
36 | } | ||
34 | args::Command::ProcMacro => proc_macro_srv::cli::run()?, | 37 | args::Command::ProcMacro => proc_macro_srv::cli::run()?, |
35 | 38 | ||
36 | args::Command::Parse { no_dump } => cli::parse(no_dump)?, | 39 | args::Command::Parse { no_dump } => cli::parse(no_dump)?, |
diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 5243b50c8..345a56978 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs | |||
@@ -13,14 +13,166 @@ use flycheck::FlycheckConfig; | |||
13 | use hir::PrefixKind; | 13 | use hir::PrefixKind; |
14 | use ide::{AssistConfig, CompletionConfig, DiagnosticsConfig, HoverConfig, InlayHintsConfig}; | 14 | use ide::{AssistConfig, CompletionConfig, DiagnosticsConfig, HoverConfig, InlayHintsConfig}; |
15 | use ide_db::helpers::insert_use::MergeBehaviour; | 15 | use ide_db::helpers::insert_use::MergeBehaviour; |
16 | use itertools::Itertools; | ||
16 | use lsp_types::{ClientCapabilities, MarkupKind}; | 17 | use lsp_types::{ClientCapabilities, MarkupKind}; |
17 | use project_model::{CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest}; | 18 | use project_model::{CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest}; |
18 | use rustc_hash::FxHashSet; | 19 | use rustc_hash::FxHashSet; |
19 | use serde::Deserialize; | 20 | use serde::{de::DeserializeOwned, Deserialize}; |
20 | use vfs::AbsPathBuf; | 21 | use vfs::AbsPathBuf; |
21 | 22 | ||
22 | use crate::{caps::enabled_completions_resolve_capabilities, diagnostics::DiagnosticsMapConfig}; | 23 | use crate::{caps::enabled_completions_resolve_capabilities, diagnostics::DiagnosticsMapConfig}; |
23 | 24 | ||
25 | config_data! { | ||
26 | struct ConfigData { | ||
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\"", | ||
31 | |||
32 | /// Show function name and docs in parameter hints. | ||
33 | callInfo_full: bool = "true", | ||
34 | |||
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 | ||
43 | /// OUT_DIRs. | ||
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", | ||
51 | |||
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 | ||
73 | /// similar option. | ||
74 | checkOnSave_overrideCommand: Option<Vec<String>> = "null", | ||
75 | |||
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", | ||
85 | |||
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> = "[]", | ||
101 | |||
102 | /// Controls file watching implementation. | ||
103 | files_watcher: String = "\"client\"", | ||
104 | |||
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", | ||
121 | |||
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 | ||
127 | /// site. | ||
128 | inlayHints_parameterHints: bool = "true", | ||
129 | /// Whether to show inlay type hints for variables. | ||
130 | inlayHints_typeHints: bool = "true", | ||
131 | |||
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", | ||
146 | |||
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 | ||
156 | /// enabled. | ||
157 | procMacro_enable: bool = "false", | ||
158 | |||
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> = "[]", | ||
164 | |||
165 | /// Path to the rust compiler sources, for usage in rustc_private projects. | ||
166 | rustcSource : Option<String> = "null", | ||
167 | |||
168 | /// Additional arguments to rustfmt. | ||
169 | rustfmt_extraArgs: Vec<String> = "[]", | ||
170 | /// Advanced option, fully override the command rust-analyzer uses for | ||
171 | /// formatting. | ||
172 | rustfmt_overrideCommand: Option<Vec<String>> = "null", | ||
173 | } | ||
174 | } | ||
175 | |||
24 | #[derive(Debug, Clone)] | 176 | #[derive(Debug, Clone)] |
25 | pub struct Config { | 177 | pub struct Config { |
26 | pub client_caps: ClientCapsConfig, | 178 | pub client_caps: ClientCapsConfig, |
@@ -149,25 +301,27 @@ pub struct ClientCapsConfig { | |||
149 | 301 | ||
150 | impl Config { | 302 | impl Config { |
151 | pub fn new(root_path: AbsPathBuf) -> Self { | 303 | pub fn new(root_path: AbsPathBuf) -> Self { |
152 | Config { | 304 | // Defaults here don't matter, we'll immediately re-write them with |
305 | // ConfigData. | ||
306 | let mut res = Config { | ||
153 | client_caps: ClientCapsConfig::default(), | 307 | client_caps: ClientCapsConfig::default(), |
154 | 308 | ||
155 | publish_diagnostics: true, | 309 | publish_diagnostics: false, |
156 | diagnostics: DiagnosticsConfig::default(), | 310 | diagnostics: DiagnosticsConfig::default(), |
157 | diagnostics_map: DiagnosticsMapConfig::default(), | 311 | diagnostics_map: DiagnosticsMapConfig::default(), |
158 | lru_capacity: None, | 312 | lru_capacity: None, |
159 | proc_macro_srv: None, | 313 | proc_macro_srv: None, |
160 | files: FilesConfig { watcher: FilesWatcher::Notify, exclude: Vec::new() }, | 314 | files: FilesConfig { watcher: FilesWatcher::Notify, exclude: Vec::new() }, |
161 | notifications: NotificationsConfig { cargo_toml_not_found: true }, | 315 | notifications: NotificationsConfig { cargo_toml_not_found: false }, |
162 | 316 | ||
163 | cargo_autoreload: true, | 317 | cargo_autoreload: false, |
164 | cargo: CargoConfig::default(), | 318 | cargo: CargoConfig::default(), |
165 | rustfmt: RustfmtConfig::Rustfmt { extra_args: Vec::new() }, | 319 | rustfmt: RustfmtConfig::Rustfmt { extra_args: Vec::new() }, |
166 | flycheck: Some(FlycheckConfig::CargoCommand { | 320 | flycheck: Some(FlycheckConfig::CargoCommand { |
167 | command: "check".to_string(), | 321 | command: String::new(), |
168 | target_triple: None, | 322 | target_triple: None, |
169 | no_default_features: false, | 323 | no_default_features: false, |
170 | all_targets: true, | 324 | all_targets: false, |
171 | all_features: false, | 325 | all_features: false, |
172 | extra_args: Vec::new(), | 326 | extra_args: Vec::new(), |
173 | features: Vec::new(), | 327 | features: Vec::new(), |
@@ -175,35 +329,32 @@ impl Config { | |||
175 | runnables: RunnablesConfig::default(), | 329 | runnables: RunnablesConfig::default(), |
176 | 330 | ||
177 | inlay_hints: InlayHintsConfig { | 331 | inlay_hints: InlayHintsConfig { |
178 | type_hints: true, | 332 | type_hints: false, |
179 | parameter_hints: true, | 333 | parameter_hints: false, |
180 | chaining_hints: true, | 334 | chaining_hints: false, |
181 | max_length: None, | 335 | max_length: None, |
182 | }, | 336 | }, |
183 | completion: CompletionConfig { | 337 | completion: CompletionConfig::default(), |
184 | enable_postfix_completions: true, | ||
185 | enable_autoimport_completions: true, | ||
186 | add_call_parenthesis: true, | ||
187 | add_call_argument_snippets: true, | ||
188 | ..CompletionConfig::default() | ||
189 | }, | ||
190 | assist: AssistConfig::default(), | 338 | assist: AssistConfig::default(), |
191 | call_info_full: true, | 339 | call_info_full: false, |
192 | lens: LensConfig::default(), | 340 | lens: LensConfig::default(), |
193 | hover: HoverConfig::default(), | 341 | hover: HoverConfig::default(), |
194 | semantic_tokens_refresh: false, | 342 | semantic_tokens_refresh: false, |
195 | linked_projects: Vec::new(), | 343 | linked_projects: Vec::new(), |
196 | root_path, | 344 | root_path, |
197 | } | 345 | }; |
346 | res.do_update(serde_json::json!({})); | ||
347 | res | ||
198 | } | 348 | } |
199 | |||
200 | pub fn update(&mut self, json: serde_json::Value) { | 349 | pub fn update(&mut self, json: serde_json::Value) { |
201 | log::info!("Config::update({:#})", json); | 350 | log::info!("Config::update({:#})", json); |
202 | |||
203 | if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) { | 351 | if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) { |
204 | return; | 352 | return; |
205 | } | 353 | } |
206 | 354 | self.do_update(json); | |
355 | log::info!("Config::update() = {:#?}", self); | ||
356 | } | ||
357 | fn do_update(&mut self, json: serde_json::Value) { | ||
207 | let data = ConfigData::from_json(json); | 358 | let data = ConfigData::from_json(json); |
208 | 359 | ||
209 | self.publish_diagnostics = data.diagnostics_enable; | 360 | self.publish_diagnostics = data.diagnostics_enable; |
@@ -349,8 +500,6 @@ impl Config { | |||
349 | links_in_hover: data.hoverActions_linksInHover, | 500 | links_in_hover: data.hoverActions_linksInHover, |
350 | markdown: true, | 501 | markdown: true, |
351 | }; | 502 | }; |
352 | |||
353 | log::info!("Config::update() = {:#?}", self); | ||
354 | } | 503 | } |
355 | 504 | ||
356 | pub fn update_caps(&mut self, caps: &ClientCapabilities) { | 505 | pub fn update_caps(&mut self, caps: &ClientCapabilities) { |
@@ -434,6 +583,10 @@ impl Config { | |||
434 | } | 583 | } |
435 | } | 584 | } |
436 | } | 585 | } |
586 | |||
587 | pub fn json_schema() -> serde_json::Value { | ||
588 | ConfigData::json_schema() | ||
589 | } | ||
437 | } | 590 | } |
438 | 591 | ||
439 | #[derive(Deserialize)] | 592 | #[derive(Deserialize)] |
@@ -459,94 +612,167 @@ enum ImportPrefixDef { | |||
459 | ByCrate, | 612 | ByCrate, |
460 | } | 613 | } |
461 | 614 | ||
462 | macro_rules! config_data { | 615 | macro_rules! _config_data { |
463 | (struct $name:ident { $($field:ident: $ty:ty = $default:expr,)*}) => { | 616 | (struct $name:ident { |
617 | $( | ||
618 | $(#[doc=$doc:literal])* | ||
619 | $field:ident: $ty:ty = $default:expr, | ||
620 | )* | ||
621 | }) => { | ||
464 | #[allow(non_snake_case)] | 622 | #[allow(non_snake_case)] |
465 | struct $name { $($field: $ty,)* } | 623 | struct $name { $($field: $ty,)* } |
466 | impl $name { | 624 | impl $name { |
467 | fn from_json(mut json: serde_json::Value) -> $name { | 625 | fn from_json(mut json: serde_json::Value) -> $name { |
468 | $name {$( | 626 | $name {$( |
469 | $field: { | 627 | $field: get_field(&mut json, stringify!($field), $default), |
470 | let pointer = stringify!($field).replace('_', "/"); | ||
471 | let pointer = format!("/{}", pointer); | ||
472 | json.pointer_mut(&pointer) | ||
473 | .and_then(|it| serde_json::from_value(it.take()).ok()) | ||
474 | .unwrap_or($default) | ||
475 | }, | ||
476 | )*} | 628 | )*} |
477 | } | 629 | } |
478 | } | ||
479 | 630 | ||
631 | fn json_schema() -> serde_json::Value { | ||
632 | schema(&[ | ||
633 | $({ | ||
634 | let field = stringify!($field); | ||
635 | let ty = stringify!($ty); | ||
636 | (field, ty, &[$($doc),*], $default) | ||
637 | },)* | ||
638 | ]) | ||
639 | } | ||
640 | } | ||
480 | }; | 641 | }; |
481 | } | 642 | } |
643 | use _config_data as config_data; | ||
644 | |||
645 | fn get_field<T: DeserializeOwned>( | ||
646 | json: &mut serde_json::Value, | ||
647 | field: &'static str, | ||
648 | default: &str, | ||
649 | ) -> T { | ||
650 | let default = serde_json::from_str(default).unwrap(); | ||
651 | |||
652 | let mut pointer = field.replace('_', "/"); | ||
653 | pointer.insert(0, '/'); | ||
654 | json.pointer_mut(&pointer) | ||
655 | .and_then(|it| serde_json::from_value(it.take()).ok()) | ||
656 | .unwrap_or(default) | ||
657 | } | ||
482 | 658 | ||
483 | config_data! { | 659 | fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value { |
484 | struct ConfigData { | 660 | for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) { |
485 | assist_importMergeBehaviour: MergeBehaviourDef = MergeBehaviourDef::Full, | 661 | fn key(f: &str) -> &str { |
486 | assist_importPrefix: ImportPrefixDef = ImportPrefixDef::Plain, | 662 | f.splitn(2, "_").next().unwrap() |
487 | 663 | }; | |
488 | callInfo_full: bool = true, | 664 | assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2); |
489 | 665 | } | |
490 | cargo_autoreload: bool = true, | 666 | |
491 | cargo_allFeatures: bool = false, | 667 | let map = fields |
492 | cargo_features: Vec<String> = Vec::new(), | 668 | .iter() |
493 | cargo_loadOutDirsFromCheck: bool = false, | 669 | .map(|(field, ty, doc, default)| { |
494 | cargo_noDefaultFeatures: bool = false, | 670 | let name = field.replace("_", "."); |
495 | cargo_target: Option<String> = None, | 671 | let name = format!("rust-analyzer.{}", name); |
496 | cargo_noSysroot: bool = false, | 672 | let props = field_props(field, ty, doc, default); |
497 | 673 | (name, props) | |
498 | checkOnSave_enable: bool = true, | 674 | }) |
499 | checkOnSave_allFeatures: Option<bool> = None, | 675 | .collect::<serde_json::Map<_, _>>(); |
500 | checkOnSave_allTargets: bool = true, | 676 | map.into() |
501 | checkOnSave_command: String = "check".into(), | 677 | } |
502 | checkOnSave_noDefaultFeatures: Option<bool> = None, | 678 | |
503 | checkOnSave_target: Option<String> = None, | 679 | fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value { |
504 | checkOnSave_extraArgs: Vec<String> = Vec::new(), | 680 | let doc = doc.iter().map(|it| it.trim()).join(" "); |
505 | checkOnSave_features: Option<Vec<String>> = None, | 681 | assert!( |
506 | checkOnSave_overrideCommand: Option<Vec<String>> = None, | 682 | doc.ends_with('.') && doc.starts_with(char::is_uppercase), |
507 | 683 | "bad docs for {}: {:?}", | |
508 | completion_addCallArgumentSnippets: bool = true, | 684 | field, |
509 | completion_addCallParenthesis: bool = true, | 685 | doc |
510 | completion_postfix_enable: bool = true, | 686 | ); |
511 | completion_autoimport_enable: bool = true, | 687 | let default = default.parse::<serde_json::Value>().unwrap(); |
512 | 688 | ||
513 | diagnostics_enable: bool = true, | 689 | let mut map = serde_json::Map::default(); |
514 | diagnostics_enableExperimental: bool = true, | 690 | macro_rules! set { |
515 | diagnostics_disabled: FxHashSet<String> = FxHashSet::default(), | 691 | ($($key:literal: $value:tt),*$(,)?) => {{$( |
516 | diagnostics_warningsAsHint: Vec<String> = Vec::new(), | 692 | map.insert($key.into(), serde_json::json!($value)); |
517 | diagnostics_warningsAsInfo: Vec<String> = Vec::new(), | 693 | )*}}; |
518 | |||
519 | files_watcher: String = "client".into(), | ||
520 | |||
521 | hoverActions_debug: bool = true, | ||
522 | hoverActions_enable: bool = true, | ||
523 | hoverActions_gotoTypeDef: bool = true, | ||
524 | hoverActions_implementations: bool = true, | ||
525 | hoverActions_run: bool = true, | ||
526 | hoverActions_linksInHover: bool = true, | ||
527 | |||
528 | inlayHints_chainingHints: bool = true, | ||
529 | inlayHints_maxLength: Option<usize> = None, | ||
530 | inlayHints_parameterHints: bool = true, | ||
531 | inlayHints_typeHints: bool = true, | ||
532 | |||
533 | lens_debug: bool = true, | ||
534 | lens_enable: bool = true, | ||
535 | lens_implementations: bool = true, | ||
536 | lens_run: bool = true, | ||
537 | lens_methodReferences: bool = false, | ||
538 | |||
539 | linkedProjects: Vec<ManifestOrProjectJson> = Vec::new(), | ||
540 | lruCapacity: Option<usize> = None, | ||
541 | notifications_cargoTomlNotFound: bool = true, | ||
542 | procMacro_enable: bool = false, | ||
543 | |||
544 | runnables_overrideCargo: Option<String> = None, | ||
545 | runnables_cargoExtraArgs: Vec<String> = Vec::new(), | ||
546 | |||
547 | rustfmt_extraArgs: Vec<String> = Vec::new(), | ||
548 | rustfmt_overrideCommand: Option<Vec<String>> = None, | ||
549 | |||
550 | rustcSource : Option<String> = None, | ||
551 | } | 694 | } |
695 | set!("markdownDescription": doc); | ||
696 | set!("default": default); | ||
697 | |||
698 | match ty { | ||
699 | "bool" => set!("type": "boolean"), | ||
700 | "String" => set!("type": "string"), | ||
701 | "Vec<String>" => set! { | ||
702 | "type": "array", | ||
703 | "items": { "type": "string" }, | ||
704 | }, | ||
705 | "FxHashSet<String>" => set! { | ||
706 | "type": "array", | ||
707 | "items": { "type": "string" }, | ||
708 | "uniqueItems": true, | ||
709 | }, | ||
710 | "Option<usize>" => set! { | ||
711 | "type": ["null", "integer"], | ||
712 | "minimum": 0, | ||
713 | }, | ||
714 | "Option<String>" => set! { | ||
715 | "type": ["null", "string"], | ||
716 | }, | ||
717 | "Option<bool>" => set! { | ||
718 | "type": ["null", "boolean"], | ||
719 | }, | ||
720 | "Option<Vec<String>>" => set! { | ||
721 | "type": ["null", "array"], | ||
722 | "items": { "type": "string" }, | ||
723 | }, | ||
724 | "MergeBehaviourDef" => set! { | ||
725 | "type": "string", | ||
726 | "enum": ["none", "full", "last"], | ||
727 | "enumDescriptions": [ | ||
728 | "No merging", | ||
729 | "Merge all layers of the import trees", | ||
730 | "Only merge the last layer of the import trees" | ||
731 | ], | ||
732 | }, | ||
733 | "ImportPrefixDef" => set! { | ||
734 | "type": "string", | ||
735 | "enum": [ | ||
736 | "plain", | ||
737 | "by_self", | ||
738 | "by_crate" | ||
739 | ], | ||
740 | "enumDescriptions": [ | ||
741 | "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.", | ||
742 | "Prefix all import paths with `self` if they don't begin with `self`, `super`, `crate` or a crate name", | ||
743 | "Force import paths to be absolute by always starting them with `crate` or the crate name they refer to." | ||
744 | ], | ||
745 | }, | ||
746 | "Vec<ManifestOrProjectJson>" => set! { | ||
747 | "type": "array", | ||
748 | "items": { "type": ["string", "object"] }, | ||
749 | }, | ||
750 | _ => panic!("{}: {}", ty, default), | ||
751 | } | ||
752 | |||
753 | map.into() | ||
754 | } | ||
755 | |||
756 | #[test] | ||
757 | fn schema_in_sync_with_package_json() { | ||
758 | fn remove_ws(text: &str) -> String { | ||
759 | text.replace(char::is_whitespace, "") | ||
760 | } | ||
761 | |||
762 | let s = Config::json_schema(); | ||
763 | let schema = format!("{:#}", s); | ||
764 | let schema = schema.trim_start_matches('{').trim_end_matches('}'); | ||
765 | |||
766 | let package_json = std::env::current_dir() | ||
767 | .unwrap() | ||
768 | .ancestors() | ||
769 | .nth(2) | ||
770 | .unwrap() | ||
771 | .join("editors/code/package.json"); | ||
772 | let package_json = std::fs::read_to_string(&package_json).unwrap(); | ||
773 | |||
774 | let p = remove_ws(&package_json); | ||
775 | let s = remove_ws(&schema); | ||
776 | |||
777 | assert!(p.contains(&s), "update config in package.json. New config:\n{:#}", schema); | ||
552 | } | 778 | } |
diff --git a/crates/test_utils/src/lib.rs b/crates/test_utils/src/lib.rs index a49be4602..05940a546 100644 --- a/crates/test_utils/src/lib.rs +++ b/crates/test_utils/src/lib.rs | |||
@@ -321,12 +321,11 @@ fn lines_match_works() { | |||
321 | /// as paths). You can use a `"{...}"` string literal as a wildcard for | 321 | /// as paths). You can use a `"{...}"` string literal as a wildcard for |
322 | /// arbitrary nested JSON. Arrays are sorted before comparison. | 322 | /// arbitrary nested JSON. Arrays are sorted before comparison. |
323 | pub fn find_mismatch<'a>(expected: &'a Value, actual: &'a Value) -> Option<(&'a Value, &'a Value)> { | 323 | pub fn find_mismatch<'a>(expected: &'a Value, actual: &'a Value) -> Option<(&'a Value, &'a Value)> { |
324 | use serde_json::Value::*; | ||
325 | match (expected, actual) { | 324 | match (expected, actual) { |
326 | (&Number(ref l), &Number(ref r)) if l == r => None, | 325 | (Value::Number(l), Value::Number(r)) if l == r => None, |
327 | (&Bool(l), &Bool(r)) if l == r => None, | 326 | (Value::Bool(l), Value::Bool(r)) if l == r => None, |
328 | (&String(ref l), &String(ref r)) if lines_match(l, r) => None, | 327 | (Value::String(l), Value::String(r)) if lines_match(l, r) => None, |
329 | (&Array(ref l), &Array(ref r)) => { | 328 | (Value::Array(l), Value::Array(r)) => { |
330 | if l.len() != r.len() { | 329 | if l.len() != r.len() { |
331 | return Some((expected, actual)); | 330 | return Some((expected, actual)); |
332 | } | 331 | } |
@@ -350,17 +349,26 @@ pub fn find_mismatch<'a>(expected: &'a Value, actual: &'a Value) -> Option<(&'a | |||
350 | None | 349 | None |
351 | } | 350 | } |
352 | } | 351 | } |
353 | (&Object(ref l), &Object(ref r)) => { | 352 | (Value::Object(l), Value::Object(r)) => { |
353 | fn sorted_values(obj: &serde_json::Map<String, Value>) -> Vec<&Value> { | ||
354 | let mut entries = obj.iter().collect::<Vec<_>>(); | ||
355 | entries.sort_by_key(|it| it.0); | ||
356 | entries.into_iter().map(|(_k, v)| v).collect::<Vec<_>>() | ||
357 | } | ||
358 | |||
354 | let same_keys = l.len() == r.len() && l.keys().all(|k| r.contains_key(k)); | 359 | let same_keys = l.len() == r.len() && l.keys().all(|k| r.contains_key(k)); |
355 | if !same_keys { | 360 | if !same_keys { |
356 | return Some((expected, actual)); | 361 | return Some((expected, actual)); |
357 | } | 362 | } |
358 | 363 | ||
359 | l.values().zip(r.values()).filter_map(|(l, r)| find_mismatch(l, r)).next() | 364 | let l = sorted_values(l); |
365 | let r = sorted_values(r); | ||
366 | |||
367 | l.into_iter().zip(r).filter_map(|(l, r)| find_mismatch(l, r)).next() | ||
360 | } | 368 | } |
361 | (&Null, &Null) => None, | 369 | (Value::Null, Value::Null) => None, |
362 | // magic string literal "{...}" acts as wildcard for any sub-JSON | 370 | // magic string literal "{...}" acts as wildcard for any sub-JSON |
363 | (&String(ref l), _) if l == "{...}" => None, | 371 | (Value::String(l), _) if l == "{...}" => None, |
364 | _ => Some((expected, actual)), | 372 | _ => Some((expected, actual)), |
365 | } | 373 | } |
366 | } | 374 | } |