]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/config.rs
Merge #5985
[rust.git] / crates / rust-analyzer / src / config.rs
1 //! Config used by the language server.
2 //!
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.
5 //!
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.
9
10 use std::{ffi::OsString, path::PathBuf};
11
12 use flycheck::FlycheckConfig;
13 use ide::{
14     AssistConfig, CompletionConfig, DiagnosticsConfig, HoverConfig, InlayHintsConfig,
15     MergeBehaviour,
16 };
17 use lsp_types::ClientCapabilities;
18 use project_model::{CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest};
19 use rustc_hash::FxHashSet;
20 use serde::Deserialize;
21 use vfs::AbsPathBuf;
22
23 use crate::diagnostics::DiagnosticsMapConfig;
24
25 #[derive(Debug, Clone)]
26 pub struct Config {
27     pub client_caps: ClientCapsConfig,
28
29     pub publish_diagnostics: bool,
30     pub diagnostics: DiagnosticsConfig,
31     pub diagnostics_map: DiagnosticsMapConfig,
32     pub lru_capacity: Option<usize>,
33     pub proc_macro_srv: Option<(PathBuf, Vec<OsString>)>,
34     pub files: FilesConfig,
35     pub notifications: NotificationsConfig,
36
37     pub cargo_autoreload: bool,
38     pub cargo: CargoConfig,
39     pub rustfmt: RustfmtConfig,
40     pub flycheck: Option<FlycheckConfig>,
41
42     pub inlay_hints: InlayHintsConfig,
43     pub completion: CompletionConfig,
44     pub assist: AssistConfig,
45     pub call_info_full: bool,
46     pub lens: LensConfig,
47     pub hover: HoverConfig,
48
49     pub with_sysroot: bool,
50     pub linked_projects: Vec<LinkedProject>,
51     pub root_path: AbsPathBuf,
52 }
53
54 #[derive(Debug, Clone, Eq, PartialEq)]
55 pub enum LinkedProject {
56     ProjectManifest(ProjectManifest),
57     InlineJsonProject(ProjectJson),
58 }
59
60 impl From<ProjectManifest> for LinkedProject {
61     fn from(v: ProjectManifest) -> Self {
62         LinkedProject::ProjectManifest(v)
63     }
64 }
65
66 impl From<ProjectJson> for LinkedProject {
67     fn from(v: ProjectJson) -> Self {
68         LinkedProject::InlineJsonProject(v)
69     }
70 }
71
72 #[derive(Clone, Debug, PartialEq, Eq)]
73 pub struct LensConfig {
74     pub run: bool,
75     pub debug: bool,
76     pub implementations: bool,
77 }
78
79 impl Default for LensConfig {
80     fn default() -> Self {
81         Self { run: true, debug: true, implementations: true }
82     }
83 }
84
85 impl LensConfig {
86     pub const NO_LENS: LensConfig = Self { run: false, debug: false, implementations: false };
87
88     pub fn any(&self) -> bool {
89         self.implementations || self.runnable()
90     }
91
92     pub fn none(&self) -> bool {
93         !self.any()
94     }
95
96     pub fn runnable(&self) -> bool {
97         self.run || self.debug
98     }
99 }
100
101 #[derive(Debug, Clone)]
102 pub struct FilesConfig {
103     pub watcher: FilesWatcher,
104     pub exclude: Vec<String>,
105 }
106
107 #[derive(Debug, Clone)]
108 pub enum FilesWatcher {
109     Client,
110     Notify,
111 }
112
113 #[derive(Debug, Clone)]
114 pub struct NotificationsConfig {
115     pub cargo_toml_not_found: bool,
116 }
117
118 #[derive(Debug, Clone)]
119 pub enum RustfmtConfig {
120     Rustfmt { extra_args: Vec<String> },
121     CustomCommand { command: String, args: Vec<String> },
122 }
123
124 #[derive(Debug, Clone, Default)]
125 pub struct ClientCapsConfig {
126     pub location_link: bool,
127     pub line_folding_only: bool,
128     pub hierarchical_symbols: bool,
129     pub code_action_literals: bool,
130     pub work_done_progress: bool,
131     pub code_action_group: bool,
132     pub resolve_code_action: bool,
133     pub hover_actions: bool,
134     pub status_notification: bool,
135     pub signature_help_label_offsets: bool,
136 }
137
138 impl Config {
139     pub fn new(root_path: AbsPathBuf) -> Self {
140         Config {
141             client_caps: ClientCapsConfig::default(),
142
143             with_sysroot: true,
144             publish_diagnostics: true,
145             diagnostics: DiagnosticsConfig::default(),
146             diagnostics_map: DiagnosticsMapConfig::default(),
147             lru_capacity: None,
148             proc_macro_srv: None,
149             files: FilesConfig { watcher: FilesWatcher::Notify, exclude: Vec::new() },
150             notifications: NotificationsConfig { cargo_toml_not_found: true },
151
152             cargo_autoreload: true,
153             cargo: CargoConfig::default(),
154             rustfmt: RustfmtConfig::Rustfmt { extra_args: Vec::new() },
155             flycheck: Some(FlycheckConfig::CargoCommand {
156                 command: "check".to_string(),
157                 target_triple: None,
158                 no_default_features: false,
159                 all_targets: true,
160                 all_features: false,
161                 extra_args: Vec::new(),
162                 features: Vec::new(),
163             }),
164
165             inlay_hints: InlayHintsConfig {
166                 type_hints: true,
167                 parameter_hints: true,
168                 chaining_hints: true,
169                 max_length: None,
170             },
171             completion: CompletionConfig {
172                 enable_postfix_completions: true,
173                 add_call_parenthesis: true,
174                 add_call_argument_snippets: true,
175                 ..CompletionConfig::default()
176             },
177             assist: AssistConfig::default(),
178             call_info_full: true,
179             lens: LensConfig::default(),
180             hover: HoverConfig::default(),
181             linked_projects: Vec::new(),
182             root_path,
183         }
184     }
185
186     pub fn update(&mut self, json: serde_json::Value) {
187         log::info!("Config::update({:#})", json);
188
189         if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
190             return;
191         }
192
193         let data = ConfigData::from_json(json);
194
195         self.with_sysroot = data.withSysroot;
196         self.publish_diagnostics = data.diagnostics_enable;
197         self.diagnostics = DiagnosticsConfig {
198             disable_experimental: !data.diagnostics_enableExperimental,
199             disabled: data.diagnostics_disabled,
200         };
201         self.diagnostics_map = DiagnosticsMapConfig {
202             warnings_as_info: data.diagnostics_warningsAsInfo,
203             warnings_as_hint: data.diagnostics_warningsAsHint,
204         };
205         self.lru_capacity = data.lruCapacity;
206         self.files.watcher = match data.files_watcher.as_str() {
207             "notify" => FilesWatcher::Notify,
208             "client" | _ => FilesWatcher::Client,
209         };
210         self.notifications =
211             NotificationsConfig { cargo_toml_not_found: data.notifications_cargoTomlNotFound };
212         self.cargo_autoreload = data.cargo_autoreload;
213         self.cargo = CargoConfig {
214             no_default_features: data.cargo_noDefaultFeatures,
215             all_features: data.cargo_allFeatures,
216             features: data.cargo_features.clone(),
217             load_out_dirs_from_check: data.cargo_loadOutDirsFromCheck,
218             target: data.cargo_target.clone(),
219         };
220
221         self.proc_macro_srv = if data.procMacro_enable {
222             std::env::current_exe().ok().map(|path| (path, vec!["proc-macro".into()]))
223         } else {
224             None
225         };
226
227         self.rustfmt = match data.rustfmt_overrideCommand {
228             Some(mut args) if !args.is_empty() => {
229                 let command = args.remove(0);
230                 RustfmtConfig::CustomCommand { command, args }
231             }
232             Some(_) | None => RustfmtConfig::Rustfmt { extra_args: data.rustfmt_extraArgs },
233         };
234
235         self.flycheck = if data.checkOnSave_enable {
236             let flycheck_config = match data.checkOnSave_overrideCommand {
237                 Some(mut args) if !args.is_empty() => {
238                     let command = args.remove(0);
239                     FlycheckConfig::CustomCommand { command, args }
240                 }
241                 Some(_) | None => FlycheckConfig::CargoCommand {
242                     command: data.checkOnSave_command,
243                     target_triple: data.checkOnSave_target.or(data.cargo_target),
244                     all_targets: data.checkOnSave_allTargets,
245                     no_default_features: data
246                         .checkOnSave_noDefaultFeatures
247                         .unwrap_or(data.cargo_noDefaultFeatures),
248                     all_features: data.checkOnSave_allFeatures.unwrap_or(data.cargo_allFeatures),
249                     features: data.checkOnSave_features.unwrap_or(data.cargo_features),
250                     extra_args: data.checkOnSave_extraArgs,
251                 },
252             };
253             Some(flycheck_config)
254         } else {
255             None
256         };
257
258         self.inlay_hints = InlayHintsConfig {
259             type_hints: data.inlayHints_typeHints,
260             parameter_hints: data.inlayHints_parameterHints,
261             chaining_hints: data.inlayHints_chainingHints,
262             max_length: data.inlayHints_maxLength,
263         };
264
265         self.completion.enable_postfix_completions = data.completion_postfix_enable;
266         self.completion.add_call_parenthesis = data.completion_addCallParenthesis;
267         self.completion.add_call_argument_snippets = data.completion_addCallArgumentSnippets;
268
269         self.assist.insert_use.merge = match data.assist_importMergeBehaviour {
270             MergeBehaviourDef::None => None,
271             MergeBehaviourDef::Full => Some(MergeBehaviour::Full),
272             MergeBehaviourDef::Last => Some(MergeBehaviour::Last),
273         };
274
275         self.call_info_full = data.callInfo_full;
276
277         self.lens = LensConfig {
278             run: data.lens_enable && data.lens_run,
279             debug: data.lens_enable && data.lens_debug,
280             implementations: data.lens_enable && data.lens_implementations,
281         };
282
283         if !data.linkedProjects.is_empty() {
284             self.linked_projects.clear();
285             for linked_project in data.linkedProjects {
286                 let linked_project = match linked_project {
287                     ManifestOrProjectJson::Manifest(it) => {
288                         let path = self.root_path.join(it);
289                         match ProjectManifest::from_manifest_file(path) {
290                             Ok(it) => it.into(),
291                             Err(_) => continue,
292                         }
293                     }
294                     ManifestOrProjectJson::ProjectJson(it) => {
295                         ProjectJson::new(&self.root_path, it).into()
296                     }
297                 };
298                 self.linked_projects.push(linked_project);
299             }
300         }
301
302         self.hover = HoverConfig {
303             implementations: data.hoverActions_enable && data.hoverActions_implementations,
304             run: data.hoverActions_enable && data.hoverActions_run,
305             debug: data.hoverActions_enable && data.hoverActions_debug,
306             goto_type_def: data.hoverActions_enable && data.hoverActions_gotoTypeDef,
307         };
308
309         log::info!("Config::update() = {:#?}", self);
310     }
311
312     pub fn update_caps(&mut self, caps: &ClientCapabilities) {
313         if let Some(doc_caps) = caps.text_document.as_ref() {
314             if let Some(value) = doc_caps.definition.as_ref().and_then(|it| it.link_support) {
315                 self.client_caps.location_link = value;
316             }
317             if let Some(value) = doc_caps.folding_range.as_ref().and_then(|it| it.line_folding_only)
318             {
319                 self.client_caps.line_folding_only = value
320             }
321             if let Some(value) = doc_caps
322                 .document_symbol
323                 .as_ref()
324                 .and_then(|it| it.hierarchical_document_symbol_support)
325             {
326                 self.client_caps.hierarchical_symbols = value
327             }
328             if let Some(value) =
329                 doc_caps.code_action.as_ref().map(|it| it.code_action_literal_support.is_some())
330             {
331                 self.client_caps.code_action_literals = value;
332             }
333             if let Some(value) = doc_caps
334                 .signature_help
335                 .as_ref()
336                 .and_then(|it| it.signature_information.as_ref())
337                 .and_then(|it| it.parameter_information.as_ref())
338                 .and_then(|it| it.label_offset_support)
339             {
340                 self.client_caps.signature_help_label_offsets = value;
341             }
342
343             self.completion.allow_snippets(false);
344             if let Some(completion) = &doc_caps.completion {
345                 if let Some(completion_item) = &completion.completion_item {
346                     if let Some(value) = completion_item.snippet_support {
347                         self.completion.allow_snippets(value);
348                     }
349                 }
350             }
351         }
352
353         if let Some(window_caps) = caps.window.as_ref() {
354             if let Some(value) = window_caps.work_done_progress {
355                 self.client_caps.work_done_progress = value;
356             }
357         }
358
359         self.assist.allow_snippets(false);
360         if let Some(experimental) = &caps.experimental {
361             let get_bool =
362                 |index: &str| experimental.get(index).and_then(|it| it.as_bool()) == Some(true);
363
364             let snippet_text_edit = get_bool("snippetTextEdit");
365             self.assist.allow_snippets(snippet_text_edit);
366
367             self.client_caps.code_action_group = get_bool("codeActionGroup");
368             self.client_caps.resolve_code_action = get_bool("resolveCodeAction");
369             self.client_caps.hover_actions = get_bool("hoverActions");
370             self.client_caps.status_notification = get_bool("statusNotification");
371         }
372     }
373 }
374
375 #[derive(Deserialize)]
376 #[serde(untagged)]
377 enum ManifestOrProjectJson {
378     Manifest(PathBuf),
379     ProjectJson(ProjectJsonData),
380 }
381
382 #[derive(Deserialize)]
383 #[serde(rename_all = "lowercase")]
384 enum MergeBehaviourDef {
385     None,
386     Full,
387     Last,
388 }
389
390 macro_rules! config_data {
391     (struct $name:ident { $($field:ident: $ty:ty = $default:expr,)*}) => {
392         #[allow(non_snake_case)]
393         struct $name { $($field: $ty,)* }
394         impl $name {
395             fn from_json(mut json: serde_json::Value) -> $name {
396                 $name {$(
397                     $field: {
398                         let pointer = stringify!($field).replace('_', "/");
399                         let pointer = format!("/{}", pointer);
400                         json.pointer_mut(&pointer)
401                             .and_then(|it| serde_json::from_value(it.take()).ok())
402                             .unwrap_or($default)
403                     },
404                 )*}
405             }
406         }
407
408     };
409 }
410
411 config_data! {
412     struct ConfigData {
413         assist_importMergeBehaviour: MergeBehaviourDef = MergeBehaviourDef::None,
414
415         callInfo_full: bool = true,
416
417         cargo_autoreload: bool           = true,
418         cargo_allFeatures: bool          = false,
419         cargo_features: Vec<String>      = Vec::new(),
420         cargo_loadOutDirsFromCheck: bool = false,
421         cargo_noDefaultFeatures: bool    = false,
422         cargo_target: Option<String>     = None,
423
424         checkOnSave_enable: bool                         = true,
425         checkOnSave_allFeatures: Option<bool>            = None,
426         checkOnSave_allTargets: bool                     = true,
427         checkOnSave_command: String                      = "check".into(),
428         checkOnSave_noDefaultFeatures: Option<bool>      = None,
429         checkOnSave_target: Option<String>               = None,
430         checkOnSave_extraArgs: Vec<String>               = Vec::new(),
431         checkOnSave_features: Option<Vec<String>>        = None,
432         checkOnSave_overrideCommand: Option<Vec<String>> = None,
433
434         completion_addCallArgumentSnippets: bool = true,
435         completion_addCallParenthesis: bool      = true,
436         completion_postfix_enable: bool          = true,
437
438         diagnostics_enable: bool                = true,
439         diagnostics_enableExperimental: bool    = true,
440         diagnostics_disabled: FxHashSet<String> = FxHashSet::default(),
441         diagnostics_warningsAsHint: Vec<String> = Vec::new(),
442         diagnostics_warningsAsInfo: Vec<String> = Vec::new(),
443
444         files_watcher: String = "client".into(),
445
446         hoverActions_debug: bool           = true,
447         hoverActions_enable: bool          = true,
448         hoverActions_gotoTypeDef: bool     = true,
449         hoverActions_implementations: bool = true,
450         hoverActions_run: bool             = true,
451
452         inlayHints_chainingHints: bool      = true,
453         inlayHints_maxLength: Option<usize> = None,
454         inlayHints_parameterHints: bool     = true,
455         inlayHints_typeHints: bool          = true,
456
457         lens_debug: bool           = true,
458         lens_enable: bool          = true,
459         lens_implementations: bool = true,
460         lens_run: bool             = true,
461
462         linkedProjects: Vec<ManifestOrProjectJson> = Vec::new(),
463         lruCapacity: Option<usize>                 = None,
464         notifications_cargoTomlNotFound: bool      = true,
465         procMacro_enable: bool                     = false,
466
467         rustfmt_extraArgs: Vec<String>               = Vec::new(),
468         rustfmt_overrideCommand: Option<Vec<String>> = None,
469
470         withSysroot: bool = true,
471     }
472 }