1use ide::{CompletionFieldsToResolve, InlayFieldsToResolve};
3use ide_db::{FxHashSet, line_index::WideEncoding};
4use lsp_types::{
5 CallHierarchyProvider, ChangeNotifications, CodeActionKind, CodeActionOptions,
6 CodeActionProvider, CodeLensOptions, CompletionOptions, DeclarationProvider,
7 DefinitionProvider, DocumentFormattingProvider, DocumentHighlightProvider,
8 DocumentOnTypeFormattingOptions, DocumentRangeFormattingProvider, DocumentSymbolProvider,
9 FileOperationFilter, FileOperationOptions, FileOperationPattern, FileOperationPatternKind,
10 FileOperationRegistrationOptions, FoldingRangeProvider, Full, HoverProvider,
11 ImplementationProvider, InlayHintOptions, InlayHintProvider, PositionEncodingKind,
12 ReferencesProvider, RenameOptions, RenameProvider, SaveOptions, SelectionRangeProvider,
13 SemanticTokensLegend, SemanticTokensOptions, ServerCapabilities, ServerCompletionItemOptions,
14 SignatureHelpOptions, TextDocumentSync, TextDocumentSyncKind, TextDocumentSyncOptions,
15 TypeDefinitionProvider, WorkDoneProgressOptions, WorkspaceFoldersServerCapabilities,
16 WorkspaceOptions, WorkspaceSymbolProvider,
17};
18use serde_json::json;
19
20use crate::{
21 config::{Config, RustfmtConfig},
22 line_index::PositionEncoding,
23 lsp::{ext, semantic_tokens},
24};
25
26pub fn server_capabilities(config: &Config) -> ServerCapabilities {
27 ServerCapabilities {
28 position_encoding: match config.caps().negotiated_encoding() {
29 PositionEncoding::Utf8 => Some(PositionEncodingKind::UTF8),
30 PositionEncoding::Wide(wide) => match wide {
31 WideEncoding::Utf16 => Some(PositionEncodingKind::UTF16),
32 WideEncoding::Utf32 => Some(PositionEncodingKind::UTF32),
33 _ => None,
34 },
35 },
36 text_document_sync: Some(TextDocumentSync::Options(TextDocumentSyncOptions {
37 open_close: Some(true),
38 change: Some(TextDocumentSyncKind::Incremental),
39 will_save: None,
40 will_save_wait_until: None,
41 save: if config.caps().did_save_text_document_dynamic_registration() {
42 None
43 } else {
44 Some(SaveOptions::default().into())
45 },
46 })),
47 notebook_document_sync: None,
48 selection_range_provider: Some(SelectionRangeProvider::Bool(true)),
49 hover_provider: Some(HoverProvider::Bool(true)),
50 completion_provider: Some(CompletionOptions {
51 resolve_provider: if config.client_is_neovim() {
52 config.has_completion_item_resolve_additionalTextEdits().then_some(true)
53 } else {
54 Some(config.caps().completions_resolve_provider())
55 },
56 trigger_characters: Some(vec![
57 ":".to_owned(),
58 ".".to_owned(),
59 "'".to_owned(),
60 "(".to_owned(),
61 ]),
62 all_commit_characters: None,
63 completion_item: config.caps().completion_item(),
64 work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None },
65 }),
66 signature_help_provider: Some(SignatureHelpOptions {
67 trigger_characters: Some(vec!["(".to_owned(), ",".to_owned(), "<".to_owned()]),
68 retrigger_characters: None,
69 work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None },
70 }),
71 definition_provider: Some(DefinitionProvider::Bool(true)),
72 type_definition_provider: Some(TypeDefinitionProvider::Bool(true)),
73 implementation_provider: Some(ImplementationProvider::Bool(true)),
74 references_provider: Some(ReferencesProvider::Bool(true)),
75 document_highlight_provider: Some(DocumentHighlightProvider::Bool(true)),
76 document_symbol_provider: Some(DocumentSymbolProvider::Bool(true)),
77 workspace_symbol_provider: Some(WorkspaceSymbolProvider::Bool(true)),
78 code_action_provider: Some(config.caps().code_action_capabilities()),
79 code_lens_provider: Some(CodeLensOptions {
80 resolve_provider: Some(true),
81 work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None },
82 }),
83 document_formatting_provider: Some(DocumentFormattingProvider::Bool(true)),
84 document_range_formatting_provider: match config.rustfmt(None) {
85 RustfmtConfig::Rustfmt { enable_range_formatting: true, .. } => {
86 Some(DocumentRangeFormattingProvider::Bool(true))
87 }
88 _ => Some(DocumentRangeFormattingProvider::Bool(false)),
89 },
90 document_on_type_formatting_provider: Some({
91 let mut chars = ide::Analysis::SUPPORTED_TRIGGER_CHARS.iter();
92 DocumentOnTypeFormattingOptions {
93 first_trigger_character: chars.next().unwrap().to_string(),
94 more_trigger_character: Some(chars.map(|c| c.to_string()).collect()),
95 }
96 }),
97 rename_provider: Some(RenameProvider::RenameOptions(RenameOptions {
98 prepare_provider: Some(true),
99 work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None },
100 })),
101 document_link_provider: None,
102 color_provider: None,
103 folding_range_provider: Some(FoldingRangeProvider::Bool(true)),
104 declaration_provider: Some(DeclarationProvider::Bool(true)),
105 execute_command_provider: None,
106 workspace: Some(WorkspaceOptions {
107 workspace_folders: Some(WorkspaceFoldersServerCapabilities {
108 supported: Some(true),
109 change_notifications: Some(ChangeNotifications::Bool(true)),
110 }),
111 file_operations: Some(FileOperationOptions {
112 did_create: None,
113 will_create: None,
114 did_rename: None,
115 will_rename: Some(FileOperationRegistrationOptions {
116 filters: vec![
117 FileOperationFilter {
118 scheme: Some(String::from("file")),
119 pattern: FileOperationPattern {
120 glob: String::from("**/*.rs"),
121 matches: Some(FileOperationPatternKind::File),
122 options: None,
123 },
124 },
125 FileOperationFilter {
126 scheme: Some(String::from("file")),
127 pattern: FileOperationPattern {
128 glob: String::from("**"),
129 matches: Some(FileOperationPatternKind::Folder),
130 options: None,
131 },
132 },
133 ],
134 }),
135 did_delete: None,
136 will_delete: None,
137 }),
138 text_document_content: None,
139 }),
140 call_hierarchy_provider: Some(CallHierarchyProvider::Bool(true)),
141 semantic_tokens_provider: Some(
142 SemanticTokensOptions {
143 legend: SemanticTokensLegend {
144 token_types: semantic_tokens::SupportedType::iter()
145 .map(|semantic_token_type| semantic_token_type.to_string())
146 .collect(),
147 token_modifiers: semantic_tokens::SupportedModifiers::iter()
148 .map(|semantic_token_type| semantic_token_type.to_string())
149 .collect(),
150 },
151
152 full: Some(Full::SemanticTokensFullDelta(lsp_types::SemanticTokensFullDelta {
153 delta: Some(true),
154 })),
155 range: Some(lsp_types::SemanticTokensOptionsRange::Bool(true)),
156 work_done_progress_options: Default::default(),
157 }
158 .into(),
159 ),
160 moniker_provider: None,
161 linked_editing_range_provider: None,
162 inline_value_provider: None,
163 inlay_hint_provider: Some(InlayHintProvider::InlayHintOptions(InlayHintOptions {
164 work_done_progress_options: Default::default(),
165 resolve_provider: Some(config.caps().inlay_hints_resolve_provider()),
166 })),
167 diagnostic_provider: Some(lsp_types::DiagnosticProvider::DiagnosticOptions(
168 lsp_types::DiagnosticOptions {
169 identifier: Some("rust-analyzer".to_owned()),
170 inter_file_dependencies: true,
171 workspace_diagnostics: false,
173 work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None },
174 },
175 )),
176 inline_completion_provider: None,
177 experimental: Some(json!({
178 "externalDocs": true,
179 "hoverRange": true,
180 "joinLines": true,
181 "matchingBrace": true,
182 "moveItem": true,
183 "onEnter": true,
184 "openCargoToml": true,
185 "parentModule": true,
186 "childModules": true,
187 "runnables": {
188 "kinds": [ "cargo" ],
189 },
190 "ssr": true,
191 "workspaceSymbolScopeKindFiltering": true,
192 })),
193 type_hierarchy_provider: None,
194 }
195}
196
197#[derive(Debug, PartialEq, Clone, Default)]
198pub struct ClientCapabilities(lsp_types::ClientCapabilities);
199
200impl ClientCapabilities {
201 pub fn new(caps: lsp_types::ClientCapabilities) -> Self {
202 Self(caps)
203 }
204
205 fn completions_resolve_provider(&self) -> bool {
206 let client_capabilities = self.completion_resolve_support_properties();
207 let fields_to_resolve =
208 CompletionFieldsToResolve::from_client_capabilities(&client_capabilities);
209 fields_to_resolve != CompletionFieldsToResolve::empty()
210 }
211
212 fn inlay_hints_resolve_provider(&self) -> bool {
213 let client_capabilities = self.inlay_hint_resolve_support_properties();
214 let fields_to_resolve =
215 InlayFieldsToResolve::from_client_capabilities(&client_capabilities);
216 fields_to_resolve != InlayFieldsToResolve::empty()
217 }
218
219 fn experimental_bool(&self, index: &'static str) -> bool {
220 || -> _ { self.0.experimental.as_ref()?.get(index)?.as_bool() }().unwrap_or_default()
221 }
222
223 fn experimental<T: serde::de::DeserializeOwned>(&self, index: &'static str) -> Option<T> {
224 serde_json::from_value(self.0.experimental.as_ref()?.get(index)?.clone()).ok()
225 }
226
227 #[allow(non_snake_case)]
228 pub fn has_completion_item_resolve_additionalTextEdits(&self) -> bool {
229 (|| {
230 Some(
231 self.0
232 .text_document
233 .as_ref()?
234 .completion
235 .as_ref()?
236 .completion_item
237 .as_ref()?
238 .resolve_support
239 .as_ref()?
240 .properties
241 .iter()
242 .any(|cap_string| cap_string.as_str() == "additionalTextEdits"),
243 )
244 })() == Some(true)
245 }
246
247 pub fn completion_label_details_support(&self) -> bool {
248 (|| -> _ {
249 self.0
250 .text_document
251 .as_ref()?
252 .completion
253 .as_ref()?
254 .completion_item
255 .as_ref()?
256 .label_details_support
257 })() == Some(true)
258 }
259
260 fn completion_item(&self) -> Option<ServerCompletionItemOptions> {
261 Some(ServerCompletionItemOptions {
262 label_details_support: Some(self.completion_label_details_support()),
263 })
264 }
265
266 fn code_action_capabilities(&self) -> CodeActionProvider {
267 self.0
268 .text_document
269 .as_ref()
270 .and_then(|it| it.code_action.as_ref())
271 .and_then(|it| it.code_action_literal_support.as_ref())
272 .map_or(CodeActionProvider::Bool(true), |_| {
273 CodeActionProvider::CodeActionOptions(CodeActionOptions {
274 code_action_kinds: Some(vec![
278 CodeActionKind::Empty,
279 CodeActionKind::QuickFix,
280 CodeActionKind::Refactor,
281 CodeActionKind::RefactorExtract,
282 CodeActionKind::RefactorInline,
283 CodeActionKind::RefactorRewrite,
284 ]),
285 resolve_provider: Some(true),
286 work_done_progress_options: Default::default(),
287 documentation: None,
288 })
289 })
290 }
291
292 pub fn negotiated_encoding(&self) -> PositionEncoding {
293 let client_encodings = match &self.0.general {
294 Some(general) => general.position_encodings.as_deref().unwrap_or_default(),
295 None => &[],
296 };
297
298 for enc in client_encodings {
299 if enc == &PositionEncodingKind::UTF8 {
300 return PositionEncoding::Utf8;
301 } else if enc == &PositionEncodingKind::UTF32 {
302 return PositionEncoding::Wide(WideEncoding::Utf32);
303 }
304 }
306
307 PositionEncoding::Wide(WideEncoding::Utf16)
308 }
309
310 pub fn workspace_edit_resource_operations(
311 &self,
312 ) -> Option<&[lsp_types::ResourceOperationKind]> {
313 self.0.workspace.as_ref()?.workspace_edit.as_ref()?.resource_operations.as_deref()
314 }
315
316 pub fn semantics_tokens_augments_syntax_tokens(&self) -> bool {
317 (|| -> _ {
318 self.0.text_document.as_ref()?.semantic_tokens.as_ref()?.augments_syntax_tokens
319 })()
320 .unwrap_or(false)
321 }
322
323 pub fn did_save_text_document_dynamic_registration(&self) -> bool {
324 let caps =
325 (|| -> _ { self.0.text_document.as_ref()?.synchronization })().unwrap_or_default();
326 caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
327 }
328
329 pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
330 (|| -> _ {
331 self.0.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration
332 })()
333 .unwrap_or_default()
334 }
335
336 pub fn did_change_watched_files_relative_pattern_support(&self) -> bool {
337 (|| -> _ {
338 self.0.workspace.as_ref()?.did_change_watched_files.as_ref()?.relative_pattern_support
339 })()
340 .unwrap_or_default()
341 }
342
343 pub fn location_link(&self) -> bool {
344 (|| -> _ { self.0.text_document.as_ref()?.definition?.link_support })().unwrap_or_default()
345 }
346
347 pub fn line_folding_only(&self) -> bool {
348 (|| -> _ { self.0.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only })()
349 .unwrap_or_default()
350 }
351
352 pub fn folding_range_collapsed_text(&self) -> bool {
353 (|| -> _ {
354 self.0
355 .text_document
356 .as_ref()?
357 .folding_range
358 .as_ref()?
359 .folding_range
360 .as_ref()?
361 .collapsed_text
362 })()
363 .unwrap_or_default()
364 }
365
366 pub fn hierarchical_symbols(&self) -> bool {
367 (|| -> _ {
368 self.0
369 .text_document
370 .as_ref()?
371 .document_symbol
372 .as_ref()?
373 .hierarchical_document_symbol_support
374 })()
375 .unwrap_or_default()
376 }
377
378 pub fn code_action_literals(&self) -> bool {
379 (|| -> _ {
380 self.0
381 .text_document
382 .as_ref()?
383 .code_action
384 .as_ref()?
385 .code_action_literal_support
386 .as_ref()
387 })()
388 .is_some()
389 }
390
391 pub fn work_done_progress(&self) -> bool {
392 (|| -> _ { self.0.window.as_ref()?.work_done_progress })().unwrap_or_default()
393 }
394
395 pub fn will_rename(&self) -> bool {
396 (|| -> _ { self.0.workspace.as_ref()?.file_operations.as_ref()?.will_rename })()
397 .unwrap_or_default()
398 }
399
400 pub fn change_annotation_support(&self) -> bool {
401 (|| -> _ {
402 self.0.workspace.as_ref()?.workspace_edit.as_ref()?.change_annotation_support.as_ref()
403 })()
404 .is_some()
405 }
406
407 pub fn code_action_resolve(&self) -> bool {
408 (|| -> _ {
409 Some(
410 self.0
411 .text_document
412 .as_ref()?
413 .code_action
414 .as_ref()?
415 .resolve_support
416 .as_ref()?
417 .properties
418 .as_slice(),
419 )
420 })()
421 .unwrap_or_default()
422 .iter()
423 .any(|it| it == "edit")
424 }
425
426 pub fn signature_help_label_offsets(&self) -> bool {
427 (|| -> _ {
428 self.0
429 .text_document
430 .as_ref()?
431 .signature_help
432 .as_ref()?
433 .signature_information
434 .as_ref()?
435 .parameter_information
436 .as_ref()?
437 .label_offset_support
438 })()
439 .unwrap_or_default()
440 }
441
442 pub fn text_document_diagnostic(&self) -> bool {
443 (|| -> _ { self.0.text_document.as_ref()?.diagnostic.as_ref() })().is_some()
444 }
445
446 pub fn text_document_diagnostic_related_document_support(&self) -> bool {
447 (|| -> _ { self.0.text_document.as_ref()?.diagnostic.as_ref()?.related_document_support })()
448 == Some(true)
449 }
450
451 pub fn code_action_group(&self) -> bool {
452 self.experimental_bool("codeActionGroup")
453 }
454
455 pub fn commands(&self) -> Option<ext::ClientCommandOptions> {
456 self.experimental("commands")
457 }
458
459 pub fn local_docs(&self) -> bool {
460 self.experimental_bool("localDocs")
461 }
462
463 pub fn open_server_logs(&self) -> bool {
464 self.experimental_bool("openServerLogs")
465 }
466
467 pub fn server_status_notification(&self) -> bool {
468 self.experimental_bool("serverStatusNotification")
469 }
470
471 pub fn snippet_text_edit(&self) -> bool {
472 self.experimental_bool("snippetTextEdit")
473 }
474
475 pub fn hover_actions(&self) -> bool {
476 self.experimental_bool("hoverActions")
477 }
478
479 pub fn color_diagnostic_output(&self) -> bool {
481 self.experimental_bool("colorDiagnosticOutput")
482 }
483
484 pub fn test_explorer(&self) -> bool {
485 self.experimental_bool("testExplorer")
486 }
487
488 pub fn completion_snippet(&self) -> bool {
489 (|| -> _ {
490 self.0
491 .text_document
492 .as_ref()?
493 .completion
494 .as_ref()?
495 .completion_item
496 .as_ref()?
497 .snippet_support
498 })()
499 .unwrap_or_default()
500 }
501
502 pub fn semantic_tokens_refresh(&self) -> bool {
503 (|| -> _ { self.0.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support })()
504 .unwrap_or_default()
505 }
506
507 pub fn code_lens_refresh(&self) -> bool {
508 (|| -> _ { self.0.workspace.as_ref()?.code_lens.as_ref()?.refresh_support })()
509 .unwrap_or_default()
510 }
511
512 pub fn inlay_hints_refresh(&self) -> bool {
513 (|| -> _ { self.0.workspace.as_ref()?.inlay_hint.as_ref()?.refresh_support })()
514 .unwrap_or_default()
515 }
516
517 pub fn diagnostics_refresh(&self) -> bool {
518 (|| -> _ { self.0.workspace.as_ref()?.diagnostics.as_ref()?.refresh_support })()
519 .unwrap_or_default()
520 }
521
522 pub fn inlay_hint_resolve_support_properties(&self) -> FxHashSet<&str> {
523 self.0
524 .text_document
525 .as_ref()
526 .and_then(|text| text.inlay_hint.as_ref())
527 .and_then(|inlay_hint_caps| inlay_hint_caps.resolve_support.as_ref())
528 .map(|inlay_resolve| inlay_resolve.properties.iter())
529 .into_iter()
530 .flatten()
531 .map(|s| s.as_str())
532 .collect()
533 }
534
535 pub fn completion_resolve_support_properties(&self) -> FxHashSet<&str> {
536 self.0
537 .text_document
538 .as_ref()
539 .and_then(|text| text.completion.as_ref())
540 .and_then(|completion_caps| completion_caps.completion_item.as_ref())
541 .and_then(|completion_item_caps| completion_item_caps.resolve_support.as_ref())
542 .map(|resolve_support| resolve_support.properties.iter())
543 .into_iter()
544 .flatten()
545 .map(|s| s.as_str())
546 .collect()
547 }
548
549 pub fn hover_markdown_support(&self) -> bool {
550 (|| -> _ {
551 Some(self.0.text_document.as_ref()?.hover.as_ref()?.content_format.as_ref()?.as_slice())
552 })()
553 .unwrap_or_default()
554 .contains(&lsp_types::MarkupKind::Markdown)
555 }
556
557 pub fn insert_replace_support(&self) -> bool {
558 (|| -> _ {
559 self.0
560 .text_document
561 .as_ref()?
562 .completion
563 .as_ref()?
564 .completion_item
565 .as_ref()?
566 .insert_replace_support
567 })()
568 .unwrap_or_default()
569 }
570}