]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/config.rs
Merge #6036
[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(e) => {
292                                 log::error!("failed to load linked project: {}", e);
293                                 continue;
294                             }
295                         }
296                     }
297                     ManifestOrProjectJson::ProjectJson(it) => {
298                         ProjectJson::new(&self.root_path, it).into()
299                     }
300                 };
301                 self.linked_projects.push(linked_project);
302             }
303         }
304
305         self.hover = HoverConfig {
306             implementations: data.hoverActions_enable && data.hoverActions_implementations,
307             run: data.hoverActions_enable && data.hoverActions_run,
308             debug: data.hoverActions_enable && data.hoverActions_debug,
309             goto_type_def: data.hoverActions_enable && data.hoverActions_gotoTypeDef,
310         };
311
312         log::info!("Config::update() = {:#?}", self);
313     }
314
315     pub fn update_caps(&mut self, caps: &ClientCapabilities) {
316         if let Some(doc_caps) = caps.text_document.as_ref() {
317             if let Some(value) = doc_caps.definition.as_ref().and_then(|it| it.link_support) {
318                 self.client_caps.location_link = value;
319             }
320             if let Some(value) = doc_caps.folding_range.as_ref().and_then(|it| it.line_folding_only)
321             {
322                 self.client_caps.line_folding_only = value
323             }
324             if let Some(value) = doc_caps
325                 .document_symbol
326                 .as_ref()
327                 .and_then(|it| it.hierarchical_document_symbol_support)
328             {
329                 self.client_caps.hierarchical_symbols = value
330             }
331             if let Some(value) =
332                 doc_caps.code_action.as_ref().map(|it| it.code_action_literal_support.is_some())
333             {
334                 self.client_caps.code_action_literals = value;
335             }
336             if let Some(value) = doc_caps
337                 .signature_help
338                 .as_ref()
339                 .and_then(|it| it.signature_information.as_ref())
340                 .and_then(|it| it.parameter_information.as_ref())
341                 .and_then(|it| it.label_offset_support)
342             {
343                 self.client_caps.signature_help_label_offsets = value;
344             }
345
346             self.completion.allow_snippets(false);
347             if let Some(completion) = &doc_caps.completion {
348                 if let Some(completion_item) = &completion.completion_item {
349                     if let Some(value) = completion_item.snippet_support {
350                         self.completion.allow_snippets(value);
351                     }
352                 }
353             }
354         }
355
356         if let Some(window_caps) = caps.window.as_ref() {
357             if let Some(value) = window_caps.work_done_progress {
358                 self.client_caps.work_done_progress = value;
359             }
360         }
361
362         self.assist.allow_snippets(false);
363         if let Some(experimental) = &caps.experimental {
364             let get_bool =
365                 |index: &str| experimental.get(index).and_then(|it| it.as_bool()) == Some(true);
366
367             let snippet_text_edit = get_bool("snippetTextEdit");
368             self.assist.allow_snippets(snippet_text_edit);
369
370             self.client_caps.code_action_group = get_bool("codeActionGroup");
371             self.client_caps.resolve_code_action = get_bool("resolveCodeAction");
372             self.client_caps.hover_actions = get_bool("hoverActions");
373             self.client_caps.status_notification = get_bool("statusNotification");
374         }
375     }
376 }
377
378 #[derive(Deserialize)]
379 #[serde(untagged)]
380 enum ManifestOrProjectJson {
381     Manifest(PathBuf),
382     ProjectJson(ProjectJsonData),
383 }
384
385 #[derive(Deserialize)]
386 #[serde(rename_all = "lowercase")]
387 enum MergeBehaviourDef {
388     None,
389     Full,
390     Last,
391 }
392
393 macro_rules! config_data {
394     (struct $name:ident { $($field:ident: $ty:ty = $default:expr,)*}) => {
395         #[allow(non_snake_case)]
396         struct $name { $($field: $ty,)* }
397         impl $name {
398             fn from_json(mut json: serde_json::Value) -> $name {
399                 $name {$(
400                     $field: {
401                         let pointer = stringify!($field).replace('_', "/");
402                         let pointer = format!("/{}", pointer);
403                         json.pointer_mut(&pointer)
404                             .and_then(|it| serde_json::from_value(it.take()).ok())
405                             .unwrap_or($default)
406                     },
407                 )*}
408             }
409         }
410
411     };
412 }
413
414 config_data! {
415     struct ConfigData {
416         assist_importMergeBehaviour: MergeBehaviourDef = MergeBehaviourDef::None,
417
418         callInfo_full: bool = true,
419
420         cargo_autoreload: bool           = true,
421         cargo_allFeatures: bool          = false,
422         cargo_features: Vec<String>      = Vec::new(),
423         cargo_loadOutDirsFromCheck: bool = false,
424         cargo_noDefaultFeatures: bool    = false,
425         cargo_target: Option<String>     = None,
426
427         checkOnSave_enable: bool                         = true,
428         checkOnSave_allFeatures: Option<bool>            = None,
429         checkOnSave_allTargets: bool                     = true,
430         checkOnSave_command: String                      = "check".into(),
431         checkOnSave_noDefaultFeatures: Option<bool>      = None,
432         checkOnSave_target: Option<String>               = None,
433         checkOnSave_extraArgs: Vec<String>               = Vec::new(),
434         checkOnSave_features: Option<Vec<String>>        = None,
435         checkOnSave_overrideCommand: Option<Vec<String>> = None,
436
437         completion_addCallArgumentSnippets: bool = true,
438         completion_addCallParenthesis: bool      = true,
439         completion_postfix_enable: bool          = true,
440
441         diagnostics_enable: bool                = true,
442         diagnostics_enableExperimental: bool    = true,
443         diagnostics_disabled: FxHashSet<String> = FxHashSet::default(),
444         diagnostics_warningsAsHint: Vec<String> = Vec::new(),
445         diagnostics_warningsAsInfo: Vec<String> = Vec::new(),
446
447         files_watcher: String = "client".into(),
448
449         hoverActions_debug: bool           = true,
450         hoverActions_enable: bool          = true,
451         hoverActions_gotoTypeDef: bool     = true,
452         hoverActions_implementations: bool = true,
453         hoverActions_run: bool             = true,
454
455         inlayHints_chainingHints: bool      = true,
456         inlayHints_maxLength: Option<usize> = None,
457         inlayHints_parameterHints: bool     = true,
458         inlayHints_typeHints: bool          = true,
459
460         lens_debug: bool           = true,
461         lens_enable: bool          = true,
462         lens_implementations: bool = true,
463         lens_run: bool             = true,
464
465         linkedProjects: Vec<ManifestOrProjectJson> = Vec::new(),
466         lruCapacity: Option<usize>                 = None,
467         notifications_cargoTomlNotFound: bool      = true,
468         procMacro_enable: bool                     = false,
469
470         rustfmt_extraArgs: Vec<String>               = Vec::new(),
471         rustfmt_overrideCommand: Option<Vec<String>> = None,
472
473         withSysroot: bool = true,
474     }
475 }