1 //! Config used by the language server.
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.
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.
10 use std::{ffi::OsString, path::PathBuf};
12 use flycheck::FlycheckConfig;
14 AssistConfig, CompletionConfig, DiagnosticsConfig, HoverConfig, InlayHintsConfig,
17 use lsp_types::ClientCapabilities;
18 use project_model::{CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest};
19 use rustc_hash::FxHashSet;
20 use serde::Deserialize;
23 use crate::diagnostics::DiagnosticsMapConfig;
25 #[derive(Debug, Clone)]
27 pub client_caps: ClientCapsConfig,
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,
37 pub cargo_autoreload: bool,
38 pub cargo: CargoConfig,
39 pub rustfmt: RustfmtConfig,
40 pub flycheck: Option<FlycheckConfig>,
42 pub inlay_hints: InlayHintsConfig,
43 pub completion: CompletionConfig,
44 pub assist: AssistConfig,
45 pub call_info_full: bool,
47 pub hover: HoverConfig,
49 pub with_sysroot: bool,
50 pub linked_projects: Vec<LinkedProject>,
51 pub root_path: AbsPathBuf,
54 #[derive(Debug, Clone, Eq, PartialEq)]
55 pub enum LinkedProject {
56 ProjectManifest(ProjectManifest),
57 InlineJsonProject(ProjectJson),
60 impl From<ProjectManifest> for LinkedProject {
61 fn from(v: ProjectManifest) -> Self {
62 LinkedProject::ProjectManifest(v)
66 impl From<ProjectJson> for LinkedProject {
67 fn from(v: ProjectJson) -> Self {
68 LinkedProject::InlineJsonProject(v)
72 #[derive(Clone, Debug, PartialEq, Eq)]
73 pub struct LensConfig {
76 pub implementations: bool,
79 impl Default for LensConfig {
80 fn default() -> Self {
81 Self { run: true, debug: true, implementations: true }
86 pub const NO_LENS: LensConfig = Self { run: false, debug: false, implementations: false };
88 pub fn any(&self) -> bool {
89 self.implementations || self.runnable()
92 pub fn none(&self) -> bool {
96 pub fn runnable(&self) -> bool {
97 self.run || self.debug
101 #[derive(Debug, Clone)]
102 pub struct FilesConfig {
103 pub watcher: FilesWatcher,
104 pub exclude: Vec<String>,
107 #[derive(Debug, Clone)]
108 pub enum FilesWatcher {
113 #[derive(Debug, Clone)]
114 pub struct NotificationsConfig {
115 pub cargo_toml_not_found: bool,
118 #[derive(Debug, Clone)]
119 pub enum RustfmtConfig {
120 Rustfmt { extra_args: Vec<String> },
121 CustomCommand { command: String, args: Vec<String> },
124 #[derive(Debug, Clone, Default)]
125 pub struct ClientCapsConfig {
126 pub location_link: bool,
127 pub line_folding_only: bool,
128 pub hierarchical_symbols: bool,
129 pub code_action_literals: bool,
130 pub work_done_progress: bool,
131 pub code_action_group: bool,
132 pub resolve_code_action: bool,
133 pub hover_actions: bool,
134 pub status_notification: bool,
135 pub signature_help_label_offsets: bool,
139 pub fn new(root_path: AbsPathBuf) -> Self {
141 client_caps: ClientCapsConfig::default(),
144 publish_diagnostics: true,
145 diagnostics: DiagnosticsConfig::default(),
146 diagnostics_map: DiagnosticsMapConfig::default(),
148 proc_macro_srv: None,
149 files: FilesConfig { watcher: FilesWatcher::Notify, exclude: Vec::new() },
150 notifications: NotificationsConfig { cargo_toml_not_found: true },
152 cargo_autoreload: true,
153 cargo: CargoConfig::default(),
154 rustfmt: RustfmtConfig::Rustfmt { extra_args: Vec::new() },
155 flycheck: Some(FlycheckConfig::CargoCommand {
156 command: "check".to_string(),
158 no_default_features: false,
161 extra_args: Vec::new(),
162 features: Vec::new(),
165 inlay_hints: InlayHintsConfig {
167 parameter_hints: true,
168 chaining_hints: true,
171 completion: CompletionConfig {
172 enable_postfix_completions: true,
173 add_call_parenthesis: true,
174 add_call_argument_snippets: true,
175 ..CompletionConfig::default()
177 assist: AssistConfig::default(),
178 call_info_full: true,
179 lens: LensConfig::default(),
180 hover: HoverConfig::default(),
181 linked_projects: Vec::new(),
186 pub fn update(&mut self, json: serde_json::Value) {
187 log::info!("Config::update({:#})", json);
189 if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
193 let data = ConfigData::from_json(json);
195 self.with_sysroot = data.withSysroot;
196 self.publish_diagnostics = data.diagnostics_enable;
197 self.diagnostics = DiagnosticsConfig {
198 disable_experimental: !data.diagnostics_enableExperimental,
199 disabled: data.diagnostics_disabled,
201 self.diagnostics_map = DiagnosticsMapConfig {
202 warnings_as_info: data.diagnostics_warningsAsInfo,
203 warnings_as_hint: data.diagnostics_warningsAsHint,
205 self.lru_capacity = data.lruCapacity;
206 self.files.watcher = match data.files_watcher.as_str() {
207 "notify" => FilesWatcher::Notify,
208 "client" | _ => FilesWatcher::Client,
211 NotificationsConfig { cargo_toml_not_found: data.notifications_cargoTomlNotFound };
212 self.cargo_autoreload = data.cargo_autoreload;
213 self.cargo = CargoConfig {
214 no_default_features: data.cargo_noDefaultFeatures,
215 all_features: data.cargo_allFeatures,
216 features: data.cargo_features.clone(),
217 load_out_dirs_from_check: data.cargo_loadOutDirsFromCheck,
218 target: data.cargo_target.clone(),
221 self.proc_macro_srv = if data.procMacro_enable {
222 std::env::current_exe().ok().map(|path| (path, vec!["proc-macro".into()]))
227 self.rustfmt = match data.rustfmt_overrideCommand {
228 Some(mut args) if !args.is_empty() => {
229 let command = args.remove(0);
230 RustfmtConfig::CustomCommand { command, args }
232 Some(_) | None => RustfmtConfig::Rustfmt { extra_args: data.rustfmt_extraArgs },
235 self.flycheck = if data.checkOnSave_enable {
236 let flycheck_config = match data.checkOnSave_overrideCommand {
237 Some(mut args) if !args.is_empty() => {
238 let command = args.remove(0);
239 FlycheckConfig::CustomCommand { command, args }
241 Some(_) | None => FlycheckConfig::CargoCommand {
242 command: data.checkOnSave_command,
243 target_triple: data.checkOnSave_target.or(data.cargo_target),
244 all_targets: data.checkOnSave_allTargets,
245 no_default_features: data
246 .checkOnSave_noDefaultFeatures
247 .unwrap_or(data.cargo_noDefaultFeatures),
248 all_features: data.checkOnSave_allFeatures.unwrap_or(data.cargo_allFeatures),
249 features: data.checkOnSave_features.unwrap_or(data.cargo_features),
250 extra_args: data.checkOnSave_extraArgs,
253 Some(flycheck_config)
258 self.inlay_hints = InlayHintsConfig {
259 type_hints: data.inlayHints_typeHints,
260 parameter_hints: data.inlayHints_parameterHints,
261 chaining_hints: data.inlayHints_chainingHints,
262 max_length: data.inlayHints_maxLength,
265 self.completion.enable_postfix_completions = data.completion_postfix_enable;
266 self.completion.add_call_parenthesis = data.completion_addCallParenthesis;
267 self.completion.add_call_argument_snippets = data.completion_addCallArgumentSnippets;
269 self.assist.insert_use.merge = match data.assist_importMergeBehaviour {
270 MergeBehaviourDef::None => None,
271 MergeBehaviourDef::Full => Some(MergeBehaviour::Full),
272 MergeBehaviourDef::Last => Some(MergeBehaviour::Last),
275 self.call_info_full = data.callInfo_full;
277 self.lens = LensConfig {
278 run: data.lens_enable && data.lens_run,
279 debug: data.lens_enable && data.lens_debug,
280 implementations: data.lens_enable && data.lens_implementations,
283 if !data.linkedProjects.is_empty() {
284 self.linked_projects.clear();
285 for linked_project in data.linkedProjects {
286 let linked_project = match linked_project {
287 ManifestOrProjectJson::Manifest(it) => {
288 let path = self.root_path.join(it);
289 match ProjectManifest::from_manifest_file(path) {
292 log::error!("failed to load linked project: {}", e);
297 ManifestOrProjectJson::ProjectJson(it) => {
298 ProjectJson::new(&self.root_path, it).into()
301 self.linked_projects.push(linked_project);
305 self.hover = HoverConfig {
306 implementations: data.hoverActions_enable && data.hoverActions_implementations,
307 run: data.hoverActions_enable && data.hoverActions_run,
308 debug: data.hoverActions_enable && data.hoverActions_debug,
309 goto_type_def: data.hoverActions_enable && data.hoverActions_gotoTypeDef,
312 log::info!("Config::update() = {:#?}", self);
315 pub fn update_caps(&mut self, caps: &ClientCapabilities) {
316 if let Some(doc_caps) = caps.text_document.as_ref() {
317 if let Some(value) = doc_caps.definition.as_ref().and_then(|it| it.link_support) {
318 self.client_caps.location_link = value;
320 if let Some(value) = doc_caps.folding_range.as_ref().and_then(|it| it.line_folding_only)
322 self.client_caps.line_folding_only = value
324 if let Some(value) = doc_caps
327 .and_then(|it| it.hierarchical_document_symbol_support)
329 self.client_caps.hierarchical_symbols = value
332 doc_caps.code_action.as_ref().map(|it| it.code_action_literal_support.is_some())
334 self.client_caps.code_action_literals = value;
336 if let Some(value) = doc_caps
339 .and_then(|it| it.signature_information.as_ref())
340 .and_then(|it| it.parameter_information.as_ref())
341 .and_then(|it| it.label_offset_support)
343 self.client_caps.signature_help_label_offsets = value;
346 self.completion.allow_snippets(false);
347 if let Some(completion) = &doc_caps.completion {
348 if let Some(completion_item) = &completion.completion_item {
349 if let Some(value) = completion_item.snippet_support {
350 self.completion.allow_snippets(value);
356 if let Some(window_caps) = caps.window.as_ref() {
357 if let Some(value) = window_caps.work_done_progress {
358 self.client_caps.work_done_progress = value;
362 self.assist.allow_snippets(false);
363 if let Some(experimental) = &caps.experimental {
365 |index: &str| experimental.get(index).and_then(|it| it.as_bool()) == Some(true);
367 let snippet_text_edit = get_bool("snippetTextEdit");
368 self.assist.allow_snippets(snippet_text_edit);
370 self.client_caps.code_action_group = get_bool("codeActionGroup");
371 self.client_caps.resolve_code_action = get_bool("resolveCodeAction");
372 self.client_caps.hover_actions = get_bool("hoverActions");
373 self.client_caps.status_notification = get_bool("statusNotification");
378 #[derive(Deserialize)]
380 enum ManifestOrProjectJson {
382 ProjectJson(ProjectJsonData),
385 #[derive(Deserialize)]
386 #[serde(rename_all = "lowercase")]
387 enum MergeBehaviourDef {
393 macro_rules! config_data {
394 (struct $name:ident { $($field:ident: $ty:ty = $default:expr,)*}) => {
395 #[allow(non_snake_case)]
396 struct $name { $($field: $ty,)* }
398 fn from_json(mut json: serde_json::Value) -> $name {
401 let pointer = stringify!($field).replace('_', "/");
402 let pointer = format!("/{}", pointer);
403 json.pointer_mut(&pointer)
404 .and_then(|it| serde_json::from_value(it.take()).ok())
416 assist_importMergeBehaviour: MergeBehaviourDef = MergeBehaviourDef::None,
418 callInfo_full: bool = true,
420 cargo_autoreload: bool = true,
421 cargo_allFeatures: bool = false,
422 cargo_features: Vec<String> = Vec::new(),
423 cargo_loadOutDirsFromCheck: bool = false,
424 cargo_noDefaultFeatures: bool = false,
425 cargo_target: Option<String> = None,
427 checkOnSave_enable: bool = true,
428 checkOnSave_allFeatures: Option<bool> = None,
429 checkOnSave_allTargets: bool = true,
430 checkOnSave_command: String = "check".into(),
431 checkOnSave_noDefaultFeatures: Option<bool> = None,
432 checkOnSave_target: Option<String> = None,
433 checkOnSave_extraArgs: Vec<String> = Vec::new(),
434 checkOnSave_features: Option<Vec<String>> = None,
435 checkOnSave_overrideCommand: Option<Vec<String>> = None,
437 completion_addCallArgumentSnippets: bool = true,
438 completion_addCallParenthesis: bool = true,
439 completion_postfix_enable: bool = true,
441 diagnostics_enable: bool = true,
442 diagnostics_enableExperimental: bool = true,
443 diagnostics_disabled: FxHashSet<String> = FxHashSet::default(),
444 diagnostics_warningsAsHint: Vec<String> = Vec::new(),
445 diagnostics_warningsAsInfo: Vec<String> = Vec::new(),
447 files_watcher: String = "client".into(),
449 hoverActions_debug: bool = true,
450 hoverActions_enable: bool = true,
451 hoverActions_gotoTypeDef: bool = true,
452 hoverActions_implementations: bool = true,
453 hoverActions_run: bool = true,
455 inlayHints_chainingHints: bool = true,
456 inlayHints_maxLength: Option<usize> = None,
457 inlayHints_parameterHints: bool = true,
458 inlayHints_typeHints: bool = true,
460 lens_debug: bool = true,
461 lens_enable: bool = true,
462 lens_implementations: bool = true,
463 lens_run: bool = true,
465 linkedProjects: Vec<ManifestOrProjectJson> = Vec::new(),
466 lruCapacity: Option<usize> = None,
467 notifications_cargoTomlNotFound: bool = true,
468 procMacro_enable: bool = false,
470 rustfmt_extraArgs: Vec<String> = Vec::new(),
471 rustfmt_overrideCommand: Option<Vec<String>> = None,
473 withSysroot: bool = true,