]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/config.rs
Merge #6124
[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 hir::PrefixKind;
14 use ide::{
15     AssistConfig, CompletionConfig, DiagnosticsConfig, HoverConfig, InlayHintsConfig,
16     MergeBehaviour,
17 };
18 use lsp_types::ClientCapabilities;
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
51     pub with_sysroot: bool,
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 resolve_code_action: 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             with_sysroot: true,
158             publish_diagnostics: true,
159             diagnostics: DiagnosticsConfig::default(),
160             diagnostics_map: DiagnosticsMapConfig::default(),
161             lru_capacity: None,
162             proc_macro_srv: None,
163             files: FilesConfig { watcher: FilesWatcher::Notify, exclude: Vec::new() },
164             notifications: NotificationsConfig { cargo_toml_not_found: true },
165
166             cargo_autoreload: true,
167             cargo: CargoConfig::default(),
168             rustfmt: RustfmtConfig::Rustfmt { extra_args: Vec::new() },
169             flycheck: Some(FlycheckConfig::CargoCommand {
170                 command: "check".to_string(),
171                 target_triple: None,
172                 no_default_features: false,
173                 all_targets: true,
174                 all_features: false,
175                 extra_args: Vec::new(),
176                 features: Vec::new(),
177             }),
178             runnables: RunnablesConfig::default(),
179
180             inlay_hints: InlayHintsConfig {
181                 type_hints: true,
182                 parameter_hints: true,
183                 chaining_hints: true,
184                 max_length: None,
185             },
186             completion: CompletionConfig {
187                 enable_postfix_completions: true,
188                 add_call_parenthesis: true,
189                 add_call_argument_snippets: true,
190                 ..CompletionConfig::default()
191             },
192             assist: AssistConfig::default(),
193             call_info_full: true,
194             lens: LensConfig::default(),
195             hover: HoverConfig::default(),
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.with_sysroot = data.withSysroot;
211         self.publish_diagnostics = data.diagnostics_enable;
212         self.diagnostics = DiagnosticsConfig {
213             disable_experimental: !data.diagnostics_enableExperimental,
214             disabled: data.diagnostics_disabled,
215         };
216         self.diagnostics_map = DiagnosticsMapConfig {
217             warnings_as_info: data.diagnostics_warningsAsInfo,
218             warnings_as_hint: data.diagnostics_warningsAsHint,
219         };
220         self.lru_capacity = data.lruCapacity;
221         self.files.watcher = match data.files_watcher.as_str() {
222             "notify" => FilesWatcher::Notify,
223             "client" | _ => FilesWatcher::Client,
224         };
225         self.notifications =
226             NotificationsConfig { cargo_toml_not_found: data.notifications_cargoTomlNotFound };
227         self.cargo_autoreload = data.cargo_autoreload;
228         self.cargo = CargoConfig {
229             no_default_features: data.cargo_noDefaultFeatures,
230             all_features: data.cargo_allFeatures,
231             features: data.cargo_features.clone(),
232             load_out_dirs_from_check: data.cargo_loadOutDirsFromCheck,
233             target: data.cargo_target.clone(),
234         };
235         self.runnables = RunnablesConfig {
236             override_cargo: data.runnables_overrideCargo,
237             cargo_extra_args: data.runnables_cargoExtraArgs,
238         };
239
240         self.proc_macro_srv = if data.procMacro_enable {
241             std::env::current_exe().ok().map(|path| (path, vec!["proc-macro".into()]))
242         } else {
243             None
244         };
245
246         self.rustfmt = match data.rustfmt_overrideCommand {
247             Some(mut args) if !args.is_empty() => {
248                 let command = args.remove(0);
249                 RustfmtConfig::CustomCommand { command, args }
250             }
251             Some(_) | None => RustfmtConfig::Rustfmt { extra_args: data.rustfmt_extraArgs },
252         };
253
254         self.flycheck = if data.checkOnSave_enable {
255             let flycheck_config = match data.checkOnSave_overrideCommand {
256                 Some(mut args) if !args.is_empty() => {
257                     let command = args.remove(0);
258                     FlycheckConfig::CustomCommand { command, args }
259                 }
260                 Some(_) | None => FlycheckConfig::CargoCommand {
261                     command: data.checkOnSave_command,
262                     target_triple: data.checkOnSave_target.or(data.cargo_target),
263                     all_targets: data.checkOnSave_allTargets,
264                     no_default_features: data
265                         .checkOnSave_noDefaultFeatures
266                         .unwrap_or(data.cargo_noDefaultFeatures),
267                     all_features: data.checkOnSave_allFeatures.unwrap_or(data.cargo_allFeatures),
268                     features: data.checkOnSave_features.unwrap_or(data.cargo_features),
269                     extra_args: data.checkOnSave_extraArgs,
270                 },
271             };
272             Some(flycheck_config)
273         } else {
274             None
275         };
276
277         self.inlay_hints = InlayHintsConfig {
278             type_hints: data.inlayHints_typeHints,
279             parameter_hints: data.inlayHints_parameterHints,
280             chaining_hints: data.inlayHints_chainingHints,
281             max_length: data.inlayHints_maxLength,
282         };
283
284         self.completion.enable_postfix_completions = data.completion_postfix_enable;
285         self.completion.add_call_parenthesis = data.completion_addCallParenthesis;
286         self.completion.add_call_argument_snippets = data.completion_addCallArgumentSnippets;
287
288         self.assist.insert_use.merge = match data.assist_importMergeBehaviour {
289             MergeBehaviourDef::None => None,
290             MergeBehaviourDef::Full => Some(MergeBehaviour::Full),
291             MergeBehaviourDef::Last => Some(MergeBehaviour::Last),
292         };
293         self.assist.insert_use.prefix_kind = match data.assist_importPrefix {
294             ImportPrefixDef::Plain => PrefixKind::Plain,
295             ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
296             ImportPrefixDef::BySelf => PrefixKind::BySelf,
297         };
298
299         self.call_info_full = data.callInfo_full;
300
301         self.lens = LensConfig {
302             run: data.lens_enable && data.lens_run,
303             debug: data.lens_enable && data.lens_debug,
304             implementations: data.lens_enable && data.lens_implementations,
305             method_refs: data.lens_enable && data.lens_methodReferences,
306         };
307
308         if !data.linkedProjects.is_empty() {
309             self.linked_projects.clear();
310             for linked_project in data.linkedProjects {
311                 let linked_project = match linked_project {
312                     ManifestOrProjectJson::Manifest(it) => {
313                         let path = self.root_path.join(it);
314                         match ProjectManifest::from_manifest_file(path) {
315                             Ok(it) => it.into(),
316                             Err(e) => {
317                                 log::error!("failed to load linked project: {}", e);
318                                 continue;
319                             }
320                         }
321                     }
322                     ManifestOrProjectJson::ProjectJson(it) => {
323                         ProjectJson::new(&self.root_path, it).into()
324                     }
325                 };
326                 self.linked_projects.push(linked_project);
327             }
328         }
329
330         self.hover = HoverConfig {
331             implementations: data.hoverActions_enable && data.hoverActions_implementations,
332             run: data.hoverActions_enable && data.hoverActions_run,
333             debug: data.hoverActions_enable && data.hoverActions_debug,
334             goto_type_def: data.hoverActions_enable && data.hoverActions_gotoTypeDef,
335             links_in_hover: data.hoverActions_linksInHover,
336         };
337
338         log::info!("Config::update() = {:#?}", self);
339     }
340
341     pub fn update_caps(&mut self, caps: &ClientCapabilities) {
342         if let Some(doc_caps) = caps.text_document.as_ref() {
343             if let Some(value) = doc_caps.definition.as_ref().and_then(|it| it.link_support) {
344                 self.client_caps.location_link = value;
345             }
346             if let Some(value) = doc_caps.folding_range.as_ref().and_then(|it| it.line_folding_only)
347             {
348                 self.client_caps.line_folding_only = value
349             }
350             if let Some(value) = doc_caps
351                 .document_symbol
352                 .as_ref()
353                 .and_then(|it| it.hierarchical_document_symbol_support)
354             {
355                 self.client_caps.hierarchical_symbols = value
356             }
357             if let Some(value) =
358                 doc_caps.code_action.as_ref().map(|it| it.code_action_literal_support.is_some())
359             {
360                 self.client_caps.code_action_literals = value;
361             }
362             if let Some(value) = doc_caps
363                 .signature_help
364                 .as_ref()
365                 .and_then(|it| it.signature_information.as_ref())
366                 .and_then(|it| it.parameter_information.as_ref())
367                 .and_then(|it| it.label_offset_support)
368             {
369                 self.client_caps.signature_help_label_offsets = value;
370             }
371
372             self.completion.allow_snippets(false);
373             if let Some(completion) = &doc_caps.completion {
374                 if let Some(completion_item) = &completion.completion_item {
375                     if let Some(value) = completion_item.snippet_support {
376                         self.completion.allow_snippets(value);
377                     }
378                 }
379             }
380         }
381
382         if let Some(window_caps) = caps.window.as_ref() {
383             if let Some(value) = window_caps.work_done_progress {
384                 self.client_caps.work_done_progress = value;
385             }
386         }
387
388         self.assist.allow_snippets(false);
389         if let Some(experimental) = &caps.experimental {
390             let get_bool =
391                 |index: &str| experimental.get(index).and_then(|it| it.as_bool()) == Some(true);
392
393             let snippet_text_edit = get_bool("snippetTextEdit");
394             self.assist.allow_snippets(snippet_text_edit);
395
396             self.client_caps.code_action_group = get_bool("codeActionGroup");
397             self.client_caps.resolve_code_action = get_bool("resolveCodeAction");
398             self.client_caps.hover_actions = get_bool("hoverActions");
399             self.client_caps.status_notification = get_bool("statusNotification");
400         }
401     }
402 }
403
404 #[derive(Deserialize)]
405 #[serde(untagged)]
406 enum ManifestOrProjectJson {
407     Manifest(PathBuf),
408     ProjectJson(ProjectJsonData),
409 }
410
411 #[derive(Deserialize)]
412 #[serde(rename_all = "snake_case")]
413 enum MergeBehaviourDef {
414     None,
415     Full,
416     Last,
417 }
418
419 #[derive(Deserialize)]
420 #[serde(rename_all = "snake_case")]
421 enum ImportPrefixDef {
422     Plain,
423     BySelf,
424     ByCrate,
425 }
426
427 macro_rules! config_data {
428     (struct $name:ident { $($field:ident: $ty:ty = $default:expr,)*}) => {
429         #[allow(non_snake_case)]
430         struct $name { $($field: $ty,)* }
431         impl $name {
432             fn from_json(mut json: serde_json::Value) -> $name {
433                 $name {$(
434                     $field: {
435                         let pointer = stringify!($field).replace('_', "/");
436                         let pointer = format!("/{}", pointer);
437                         json.pointer_mut(&pointer)
438                             .and_then(|it| serde_json::from_value(it.take()).ok())
439                             .unwrap_or($default)
440                     },
441                 )*}
442             }
443         }
444
445     };
446 }
447
448 config_data! {
449     struct ConfigData {
450         assist_importMergeBehaviour: MergeBehaviourDef = MergeBehaviourDef::None,
451         assist_importPrefix: ImportPrefixDef           = ImportPrefixDef::Plain,
452
453         callInfo_full: bool = true,
454
455         cargo_autoreload: bool           = true,
456         cargo_allFeatures: bool          = false,
457         cargo_features: Vec<String>      = Vec::new(),
458         cargo_loadOutDirsFromCheck: bool = false,
459         cargo_noDefaultFeatures: bool    = false,
460         cargo_target: Option<String>     = None,
461
462         checkOnSave_enable: bool                         = true,
463         checkOnSave_allFeatures: Option<bool>            = None,
464         checkOnSave_allTargets: bool                     = true,
465         checkOnSave_command: String                      = "check".into(),
466         checkOnSave_noDefaultFeatures: Option<bool>      = None,
467         checkOnSave_target: Option<String>               = None,
468         checkOnSave_extraArgs: Vec<String>               = Vec::new(),
469         checkOnSave_features: Option<Vec<String>>        = None,
470         checkOnSave_overrideCommand: Option<Vec<String>> = None,
471
472         completion_addCallArgumentSnippets: bool = true,
473         completion_addCallParenthesis: bool      = true,
474         completion_postfix_enable: bool          = true,
475
476         diagnostics_enable: bool                = true,
477         diagnostics_enableExperimental: bool    = true,
478         diagnostics_disabled: FxHashSet<String> = FxHashSet::default(),
479         diagnostics_warningsAsHint: Vec<String> = Vec::new(),
480         diagnostics_warningsAsInfo: Vec<String> = Vec::new(),
481
482         files_watcher: String = "client".into(),
483
484         hoverActions_debug: bool           = true,
485         hoverActions_enable: bool          = true,
486         hoverActions_gotoTypeDef: bool     = true,
487         hoverActions_implementations: bool = true,
488         hoverActions_run: bool             = true,
489         hoverActions_linksInHover: bool    = true,
490
491         inlayHints_chainingHints: bool      = true,
492         inlayHints_maxLength: Option<usize> = None,
493         inlayHints_parameterHints: bool     = true,
494         inlayHints_typeHints: bool          = true,
495
496         lens_debug: bool            = true,
497         lens_enable: bool           = true,
498         lens_implementations: bool  = true,
499         lens_run: bool              = true,
500         lens_methodReferences: bool = false,
501
502         linkedProjects: Vec<ManifestOrProjectJson> = Vec::new(),
503         lruCapacity: Option<usize>                 = None,
504         notifications_cargoTomlNotFound: bool      = true,
505         procMacro_enable: bool                     = false,
506
507         runnables_overrideCargo: Option<String> = None,
508         runnables_cargoExtraArgs: Vec<String>   = Vec::new(),
509
510         rustfmt_extraArgs: Vec<String>               = Vec::new(),
511         rustfmt_overrideCommand: Option<Vec<String>> = None,
512
513         withSysroot: bool = true,
514     }
515 }