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