]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/config.rs
Merge #6650
[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::{convert::TryFrom, ffi::OsString, path::PathBuf};
11
12 use flycheck::FlycheckConfig;
13 use hir::PrefixKind;
14 use ide::{AssistConfig, CompletionConfig, DiagnosticsConfig, HoverConfig, InlayHintsConfig};
15 use ide_db::helpers::insert_use::MergeBehaviour;
16 use lsp_types::{ClientCapabilities, MarkupKind};
17 use project_model::{CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest};
18 use rustc_hash::FxHashSet;
19 use serde::Deserialize;
20 use vfs::AbsPathBuf;
21
22 use crate::diagnostics::DiagnosticsMapConfig;
23
24 #[derive(Debug, Clone)]
25 pub struct Config {
26     pub client_caps: ClientCapsConfig,
27
28     pub publish_diagnostics: bool,
29     pub diagnostics: DiagnosticsConfig,
30     pub diagnostics_map: DiagnosticsMapConfig,
31     pub lru_capacity: Option<usize>,
32     pub proc_macro_srv: Option<(PathBuf, Vec<OsString>)>,
33     pub files: FilesConfig,
34     pub notifications: NotificationsConfig,
35
36     pub cargo_autoreload: bool,
37     pub cargo: CargoConfig,
38     pub rustfmt: RustfmtConfig,
39     pub flycheck: Option<FlycheckConfig>,
40     pub runnables: RunnablesConfig,
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     pub semantic_tokens_refresh: bool,
49
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     pub method_refs: bool,
78 }
79
80 impl Default for LensConfig {
81     fn default() -> Self {
82         Self { run: true, debug: true, implementations: true, method_refs: false }
83     }
84 }
85
86 impl LensConfig {
87     pub fn any(&self) -> bool {
88         self.implementations || self.runnable() || self.references()
89     }
90
91     pub fn none(&self) -> bool {
92         !self.any()
93     }
94
95     pub fn runnable(&self) -> bool {
96         self.run || self.debug
97     }
98
99     pub fn references(&self) -> bool {
100         self.method_refs
101     }
102 }
103
104 #[derive(Debug, Clone)]
105 pub struct FilesConfig {
106     pub watcher: FilesWatcher,
107     pub exclude: Vec<String>,
108 }
109
110 #[derive(Debug, Clone)]
111 pub enum FilesWatcher {
112     Client,
113     Notify,
114 }
115
116 #[derive(Debug, Clone)]
117 pub struct NotificationsConfig {
118     pub cargo_toml_not_found: bool,
119 }
120
121 #[derive(Debug, Clone)]
122 pub enum RustfmtConfig {
123     Rustfmt { extra_args: Vec<String> },
124     CustomCommand { command: String, args: Vec<String> },
125 }
126
127 /// Configuration for runnable items, such as `main` function or tests.
128 #[derive(Debug, Clone, Default)]
129 pub struct RunnablesConfig {
130     /// Custom command to be executed instead of `cargo` for runnables.
131     pub override_cargo: Option<String>,
132     /// Additional arguments for the `cargo`, e.g. `--release`.
133     pub cargo_extra_args: Vec<String>,
134 }
135
136 #[derive(Debug, Clone, Default)]
137 pub struct ClientCapsConfig {
138     pub location_link: bool,
139     pub line_folding_only: bool,
140     pub hierarchical_symbols: bool,
141     pub code_action_literals: bool,
142     pub work_done_progress: bool,
143     pub code_action_group: bool,
144     pub code_action_resolve: bool,
145     pub hover_actions: bool,
146     pub status_notification: bool,
147     pub signature_help_label_offsets: bool,
148 }
149
150 impl Config {
151     pub fn new(root_path: AbsPathBuf) -> Self {
152         Config {
153             client_caps: ClientCapsConfig::default(),
154
155             publish_diagnostics: true,
156             diagnostics: DiagnosticsConfig::default(),
157             diagnostics_map: DiagnosticsMapConfig::default(),
158             lru_capacity: None,
159             proc_macro_srv: None,
160             files: FilesConfig { watcher: FilesWatcher::Notify, exclude: Vec::new() },
161             notifications: NotificationsConfig { cargo_toml_not_found: true },
162
163             cargo_autoreload: true,
164             cargo: CargoConfig::default(),
165             rustfmt: RustfmtConfig::Rustfmt { extra_args: Vec::new() },
166             flycheck: Some(FlycheckConfig::CargoCommand {
167                 command: "check".to_string(),
168                 target_triple: None,
169                 no_default_features: false,
170                 all_targets: true,
171                 all_features: false,
172                 extra_args: Vec::new(),
173                 features: Vec::new(),
174             }),
175             runnables: RunnablesConfig::default(),
176
177             inlay_hints: InlayHintsConfig {
178                 type_hints: true,
179                 parameter_hints: true,
180                 chaining_hints: true,
181                 max_length: None,
182             },
183             completion: CompletionConfig {
184                 enable_postfix_completions: true,
185                 enable_experimental_completions: true,
186                 add_call_parenthesis: true,
187                 add_call_argument_snippets: true,
188                 ..CompletionConfig::default()
189             },
190             assist: AssistConfig::default(),
191             call_info_full: true,
192             lens: LensConfig::default(),
193             hover: HoverConfig::default(),
194             semantic_tokens_refresh: false,
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.publish_diagnostics = data.diagnostics_enable;
210         self.diagnostics = DiagnosticsConfig {
211             disable_experimental: !data.diagnostics_enableExperimental,
212             disabled: data.diagnostics_disabled,
213         };
214         self.diagnostics_map = DiagnosticsMapConfig {
215             warnings_as_info: data.diagnostics_warningsAsInfo,
216             warnings_as_hint: data.diagnostics_warningsAsHint,
217         };
218         self.lru_capacity = data.lruCapacity;
219         self.files.watcher = match data.files_watcher.as_str() {
220             "notify" => FilesWatcher::Notify,
221             "client" | _ => FilesWatcher::Client,
222         };
223         self.notifications =
224             NotificationsConfig { cargo_toml_not_found: data.notifications_cargoTomlNotFound };
225         self.cargo_autoreload = data.cargo_autoreload;
226
227         let rustc_source = if let Some(rustc_source) = data.rustcSource {
228             let rustpath: PathBuf = rustc_source.into();
229             AbsPathBuf::try_from(rustpath)
230                 .map_err(|_| {
231                     log::error!("rustc source directory must be an absolute path");
232                 })
233                 .ok()
234         } else {
235             None
236         };
237
238         self.cargo = CargoConfig {
239             no_default_features: data.cargo_noDefaultFeatures,
240             all_features: data.cargo_allFeatures,
241             features: data.cargo_features.clone(),
242             load_out_dirs_from_check: data.cargo_loadOutDirsFromCheck,
243             target: data.cargo_target.clone(),
244             rustc_source: rustc_source,
245             no_sysroot: data.cargo_noSysroot,
246         };
247         self.runnables = RunnablesConfig {
248             override_cargo: data.runnables_overrideCargo,
249             cargo_extra_args: data.runnables_cargoExtraArgs,
250         };
251
252         self.proc_macro_srv = if data.procMacro_enable {
253             std::env::current_exe().ok().map(|path| (path, vec!["proc-macro".into()]))
254         } else {
255             None
256         };
257
258         self.rustfmt = match data.rustfmt_overrideCommand {
259             Some(mut args) if !args.is_empty() => {
260                 let command = args.remove(0);
261                 RustfmtConfig::CustomCommand { command, args }
262             }
263             Some(_) | None => RustfmtConfig::Rustfmt { extra_args: data.rustfmt_extraArgs },
264         };
265
266         self.flycheck = if data.checkOnSave_enable {
267             let flycheck_config = match data.checkOnSave_overrideCommand {
268                 Some(mut args) if !args.is_empty() => {
269                     let command = args.remove(0);
270                     FlycheckConfig::CustomCommand { command, args }
271                 }
272                 Some(_) | None => FlycheckConfig::CargoCommand {
273                     command: data.checkOnSave_command,
274                     target_triple: data.checkOnSave_target.or(data.cargo_target),
275                     all_targets: data.checkOnSave_allTargets,
276                     no_default_features: data
277                         .checkOnSave_noDefaultFeatures
278                         .unwrap_or(data.cargo_noDefaultFeatures),
279                     all_features: data.checkOnSave_allFeatures.unwrap_or(data.cargo_allFeatures),
280                     features: data.checkOnSave_features.unwrap_or(data.cargo_features),
281                     extra_args: data.checkOnSave_extraArgs,
282                 },
283             };
284             Some(flycheck_config)
285         } else {
286             None
287         };
288
289         self.inlay_hints = InlayHintsConfig {
290             type_hints: data.inlayHints_typeHints,
291             parameter_hints: data.inlayHints_parameterHints,
292             chaining_hints: data.inlayHints_chainingHints,
293             max_length: data.inlayHints_maxLength,
294         };
295
296         self.assist.insert_use.merge = match data.assist_importMergeBehaviour {
297             MergeBehaviourDef::None => None,
298             MergeBehaviourDef::Full => Some(MergeBehaviour::Full),
299             MergeBehaviourDef::Last => Some(MergeBehaviour::Last),
300         };
301         self.assist.insert_use.prefix_kind = match data.assist_importPrefix {
302             ImportPrefixDef::Plain => PrefixKind::Plain,
303             ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
304             ImportPrefixDef::BySelf => PrefixKind::BySelf,
305         };
306
307         self.completion.enable_postfix_completions = data.completion_postfix_enable;
308         self.completion.enable_experimental_completions = data.completion_enableExperimental;
309         self.completion.add_call_parenthesis = data.completion_addCallParenthesis;
310         self.completion.add_call_argument_snippets = data.completion_addCallArgumentSnippets;
311         self.completion.merge = self.assist.insert_use.merge;
312
313         self.call_info_full = data.callInfo_full;
314
315         self.lens = LensConfig {
316             run: data.lens_enable && data.lens_run,
317             debug: data.lens_enable && data.lens_debug,
318             implementations: data.lens_enable && data.lens_implementations,
319             method_refs: data.lens_enable && data.lens_methodReferences,
320         };
321
322         if !data.linkedProjects.is_empty() {
323             self.linked_projects.clear();
324             for linked_project in data.linkedProjects {
325                 let linked_project = match linked_project {
326                     ManifestOrProjectJson::Manifest(it) => {
327                         let path = self.root_path.join(it);
328                         match ProjectManifest::from_manifest_file(path) {
329                             Ok(it) => it.into(),
330                             Err(e) => {
331                                 log::error!("failed to load linked project: {}", e);
332                                 continue;
333                             }
334                         }
335                     }
336                     ManifestOrProjectJson::ProjectJson(it) => {
337                         ProjectJson::new(&self.root_path, it).into()
338                     }
339                 };
340                 self.linked_projects.push(linked_project);
341             }
342         }
343
344         self.hover = HoverConfig {
345             implementations: data.hoverActions_enable && data.hoverActions_implementations,
346             run: data.hoverActions_enable && data.hoverActions_run,
347             debug: data.hoverActions_enable && data.hoverActions_debug,
348             goto_type_def: data.hoverActions_enable && data.hoverActions_gotoTypeDef,
349             links_in_hover: data.hoverActions_linksInHover,
350             markdown: true,
351         };
352
353         log::info!("Config::update() = {:#?}", self);
354     }
355
356     pub fn update_caps(&mut self, caps: &ClientCapabilities) {
357         if let Some(doc_caps) = caps.text_document.as_ref() {
358             if let Some(value) = doc_caps.hover.as_ref().and_then(|it| it.content_format.as_ref()) {
359                 self.hover.markdown = value.contains(&MarkupKind::Markdown)
360             }
361             if let Some(value) = doc_caps.definition.as_ref().and_then(|it| it.link_support) {
362                 self.client_caps.location_link = value;
363             }
364             if let Some(value) = doc_caps.folding_range.as_ref().and_then(|it| it.line_folding_only)
365             {
366                 self.client_caps.line_folding_only = value
367             }
368             if let Some(value) = doc_caps
369                 .document_symbol
370                 .as_ref()
371                 .and_then(|it| it.hierarchical_document_symbol_support)
372             {
373                 self.client_caps.hierarchical_symbols = value
374             }
375             if let Some(value) =
376                 doc_caps.code_action.as_ref().map(|it| it.code_action_literal_support.is_some())
377             {
378                 self.client_caps.code_action_literals = value;
379             }
380             if let Some(value) = doc_caps
381                 .signature_help
382                 .as_ref()
383                 .and_then(|it| it.signature_information.as_ref())
384                 .and_then(|it| it.parameter_information.as_ref())
385                 .and_then(|it| it.label_offset_support)
386             {
387                 self.client_caps.signature_help_label_offsets = value;
388             }
389
390             self.completion.allow_snippets(false);
391             if let Some(completion) = &doc_caps.completion {
392                 if let Some(completion_item) = &completion.completion_item {
393                     if let Some(value) = completion_item.snippet_support {
394                         self.completion.allow_snippets(value);
395                     }
396                 }
397             }
398
399             if let Some(code_action) = &doc_caps.code_action {
400                 if let Some(resolve_support) = &code_action.resolve_support {
401                     if resolve_support.properties.iter().any(|it| it == "edit") {
402                         self.client_caps.code_action_resolve = true;
403                     }
404                 }
405             }
406         }
407
408         if let Some(window_caps) = caps.window.as_ref() {
409             if let Some(value) = window_caps.work_done_progress {
410                 self.client_caps.work_done_progress = value;
411             }
412         }
413
414         self.assist.allow_snippets(false);
415         if let Some(experimental) = &caps.experimental {
416             let get_bool =
417                 |index: &str| experimental.get(index).and_then(|it| it.as_bool()) == Some(true);
418
419             let snippet_text_edit = get_bool("snippetTextEdit");
420             self.assist.allow_snippets(snippet_text_edit);
421
422             self.client_caps.code_action_group = get_bool("codeActionGroup");
423             self.client_caps.hover_actions = get_bool("hoverActions");
424             self.client_caps.status_notification = get_bool("statusNotification");
425         }
426
427         if let Some(workspace_caps) = caps.workspace.as_ref() {
428             if let Some(refresh_support) =
429                 workspace_caps.semantic_tokens.as_ref().and_then(|it| it.refresh_support)
430             {
431                 self.semantic_tokens_refresh = refresh_support;
432             }
433         }
434     }
435 }
436
437 #[derive(Deserialize)]
438 #[serde(untagged)]
439 enum ManifestOrProjectJson {
440     Manifest(PathBuf),
441     ProjectJson(ProjectJsonData),
442 }
443
444 #[derive(Deserialize)]
445 #[serde(rename_all = "snake_case")]
446 enum MergeBehaviourDef {
447     None,
448     Full,
449     Last,
450 }
451
452 #[derive(Deserialize)]
453 #[serde(rename_all = "snake_case")]
454 enum ImportPrefixDef {
455     Plain,
456     BySelf,
457     ByCrate,
458 }
459
460 macro_rules! config_data {
461     (struct $name:ident { $($field:ident: $ty:ty = $default:expr,)*}) => {
462         #[allow(non_snake_case)]
463         struct $name { $($field: $ty,)* }
464         impl $name {
465             fn from_json(mut json: serde_json::Value) -> $name {
466                 $name {$(
467                     $field: {
468                         let pointer = stringify!($field).replace('_', "/");
469                         let pointer = format!("/{}", pointer);
470                         json.pointer_mut(&pointer)
471                             .and_then(|it| serde_json::from_value(it.take()).ok())
472                             .unwrap_or($default)
473                     },
474                 )*}
475             }
476         }
477
478     };
479 }
480
481 config_data! {
482     struct ConfigData {
483         assist_importMergeBehaviour: MergeBehaviourDef = MergeBehaviourDef::None,
484         assist_importPrefix: ImportPrefixDef           = ImportPrefixDef::Plain,
485
486         callInfo_full: bool = true,
487
488         cargo_autoreload: bool           = true,
489         cargo_allFeatures: bool          = false,
490         cargo_features: Vec<String>      = Vec::new(),
491         cargo_loadOutDirsFromCheck: bool = false,
492         cargo_noDefaultFeatures: bool    = false,
493         cargo_target: Option<String>     = None,
494         cargo_noSysroot: bool            = false,
495
496         checkOnSave_enable: bool                         = true,
497         checkOnSave_allFeatures: Option<bool>            = None,
498         checkOnSave_allTargets: bool                     = true,
499         checkOnSave_command: String                      = "check".into(),
500         checkOnSave_noDefaultFeatures: Option<bool>      = None,
501         checkOnSave_target: Option<String>               = None,
502         checkOnSave_extraArgs: Vec<String>               = Vec::new(),
503         checkOnSave_features: Option<Vec<String>>        = None,
504         checkOnSave_overrideCommand: Option<Vec<String>> = None,
505
506         completion_addCallArgumentSnippets: bool = true,
507         completion_addCallParenthesis: bool      = true,
508         completion_postfix_enable: bool          = true,
509         completion_enableExperimental: bool      = true,
510
511         diagnostics_enable: bool                = true,
512         diagnostics_enableExperimental: bool    = true,
513         diagnostics_disabled: FxHashSet<String> = FxHashSet::default(),
514         diagnostics_warningsAsHint: Vec<String> = Vec::new(),
515         diagnostics_warningsAsInfo: Vec<String> = Vec::new(),
516
517         files_watcher: String = "client".into(),
518
519         hoverActions_debug: bool           = true,
520         hoverActions_enable: bool          = true,
521         hoverActions_gotoTypeDef: bool     = true,
522         hoverActions_implementations: bool = true,
523         hoverActions_run: bool             = true,
524         hoverActions_linksInHover: bool    = true,
525
526         inlayHints_chainingHints: bool      = true,
527         inlayHints_maxLength: Option<usize> = None,
528         inlayHints_parameterHints: bool     = true,
529         inlayHints_typeHints: bool          = true,
530
531         lens_debug: bool            = true,
532         lens_enable: bool           = true,
533         lens_implementations: bool  = true,
534         lens_run: bool              = true,
535         lens_methodReferences: bool = false,
536
537         linkedProjects: Vec<ManifestOrProjectJson> = Vec::new(),
538         lruCapacity: Option<usize>                 = None,
539         notifications_cargoTomlNotFound: bool      = true,
540         procMacro_enable: bool                     = false,
541
542         runnables_overrideCargo: Option<String> = None,
543         runnables_cargoExtraArgs: Vec<String>   = Vec::new(),
544
545         rustfmt_extraArgs: Vec<String>               = Vec::new(),
546         rustfmt_overrideCommand: Option<Vec<String>> = None,
547
548         rustcSource : Option<String> = None,
549     }
550 }