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