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