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