lsp_types/
lib.rs

1/*!
2
3Language Server Protocol types for Rust.
4
5Based on: <https://microsoft.github.io/language-server-protocol/specification>
6
7This library uses the URL crate for parsing URIs.  Note that there is
8some confusion on the meaning of URLs vs URIs:
9<http://stackoverflow.com/a/28865728/393898>.  According to that
10information, on the classical sense of "URLs", "URLs" are a subset of
11URIs, But on the modern/new meaning of URLs, they are the same as
12URIs.  The important take-away aspect is that the URL crate should be
13able to parse any URI, such as `urn:isbn:0451450523`.
14
15
16*/
17#![allow(non_upper_case_globals)]
18#![forbid(unsafe_code)]
19#[macro_use]
20extern crate bitflags;
21
22use std::{collections::HashMap, fmt::Debug};
23
24use serde::{de, de::Error as Error_, Deserialize, Serialize};
25use serde_json::Value;
26pub use url::Url;
27
28// Large enough to contain any enumeration name defined in this crate
29type PascalCaseBuf = [u8; 32];
30const fn fmt_pascal_case_const(name: &str) -> (PascalCaseBuf, usize) {
31    let mut buf = [0; 32];
32    let mut buf_i = 0;
33    let mut name_i = 0;
34    let name = name.as_bytes();
35    while name_i < name.len() {
36        let first = name[name_i];
37        name_i += 1;
38
39        buf[buf_i] = first;
40        buf_i += 1;
41
42        while name_i < name.len() {
43            let rest = name[name_i];
44            name_i += 1;
45            if rest == b'_' {
46                break;
47            }
48
49            buf[buf_i] = rest.to_ascii_lowercase();
50            buf_i += 1;
51        }
52    }
53    (buf, buf_i)
54}
55
56fn fmt_pascal_case(f: &mut std::fmt::Formatter<'_>, name: &str) -> std::fmt::Result {
57    for word in name.split('_') {
58        let mut chars = word.chars();
59        let first = chars.next().unwrap();
60        write!(f, "{}", first)?;
61        for rest in chars {
62            write!(f, "{}", rest.to_lowercase())?;
63        }
64    }
65    Ok(())
66}
67
68macro_rules! lsp_enum {
69    (impl $typ: ident { $( $(#[$attr:meta])* pub const $name: ident : $enum_type: ty = $value: expr; )* }) => {
70        impl $typ {
71            $(
72            $(#[$attr])*
73            pub const $name: $enum_type = $value;
74            )*
75        }
76
77        impl std::fmt::Debug for $typ {
78            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79                match *self {
80                    $(
81                    Self::$name => crate::fmt_pascal_case(f, stringify!($name)),
82                    )*
83                    _ => write!(f, "{}({})", stringify!($typ), self.0),
84                }
85            }
86        }
87
88        impl std::convert::TryFrom<&str> for $typ {
89            type Error = &'static str;
90            fn try_from(value: &str) -> Result<Self, Self::Error> {
91                match () {
92                    $(
93                        _ if {
94                            const X: (crate::PascalCaseBuf, usize) = crate::fmt_pascal_case_const(stringify!($name));
95                            let (buf, len) = X;
96                            &buf[..len] == value.as_bytes()
97                        } => Ok(Self::$name),
98                    )*
99                    _ => Err("unknown enum variant"),
100                }
101            }
102        }
103
104    }
105}
106
107pub mod error_codes;
108pub mod notification;
109pub mod request;
110
111mod call_hierarchy;
112pub use call_hierarchy::*;
113
114mod code_action;
115pub use code_action::*;
116
117mod code_lens;
118pub use code_lens::*;
119
120mod color;
121pub use color::*;
122
123mod completion;
124pub use completion::*;
125
126mod document_diagnostic;
127pub use document_diagnostic::*;
128
129mod document_highlight;
130pub use document_highlight::*;
131
132mod document_link;
133pub use document_link::*;
134
135mod document_symbols;
136pub use document_symbols::*;
137
138mod file_operations;
139pub use file_operations::*;
140
141mod folding_range;
142pub use folding_range::*;
143
144mod formatting;
145pub use formatting::*;
146
147mod hover;
148pub use hover::*;
149
150mod inlay_hint;
151pub use inlay_hint::*;
152
153mod inline_value;
154pub use inline_value::*;
155
156mod moniker;
157pub use moniker::*;
158
159mod progress;
160pub use progress::*;
161
162mod references;
163pub use references::*;
164
165mod rename;
166pub use rename::*;
167
168pub mod selection_range;
169pub use selection_range::*;
170
171mod semantic_tokens;
172pub use semantic_tokens::*;
173
174mod signature_help;
175pub use signature_help::*;
176
177mod type_hierarchy;
178pub use type_hierarchy::*;
179
180mod linked_editing;
181pub use linked_editing::*;
182
183mod window;
184pub use window::*;
185
186mod workspace_diagnostic;
187pub use workspace_diagnostic::*;
188
189mod workspace_folders;
190pub use workspace_folders::*;
191
192mod workspace_symbols;
193pub use workspace_symbols::*;
194
195pub mod lsif;
196
197mod trace;
198pub use trace::*;
199
200/* ----------------- Auxiliary types ----------------- */
201
202#[derive(Debug, Eq, Hash, PartialEq, Clone, Deserialize, Serialize)]
203#[serde(untagged)]
204pub enum NumberOrString {
205    Number(i32),
206    String(String),
207}
208
209/* ----------------- Cancel support ----------------- */
210
211#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
212pub struct CancelParams {
213    /// The request id to cancel.
214    pub id: NumberOrString,
215}
216
217/* ----------------- Basic JSON Structures ----------------- */
218
219/// The LSP any type
220///
221/// @since 3.17.0
222pub type LSPAny = serde_json::Value;
223
224/// LSP object definition.
225///
226/// @since 3.17.0
227pub type LSPObject = serde_json::Map<String, serde_json::Value>;
228
229/// LSP arrays.
230///
231/// @since 3.17.0
232pub type LSPArray = Vec<serde_json::Value>;
233
234/// Position in a text document expressed as zero-based line and character offset.
235/// A position is between two characters like an 'insert' cursor in a editor.
236#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Default, Deserialize, Serialize)]
237pub struct Position {
238    /// Line position in a document (zero-based).
239    pub line: u32,
240    /// Character offset on a line in a document (zero-based). The meaning of this
241    /// offset is determined by the negotiated `PositionEncodingKind`.
242    ///
243    /// If the character value is greater than the line length it defaults back
244    /// to the line length.
245    pub character: u32,
246}
247
248impl Position {
249    pub fn new(line: u32, character: u32) -> Position {
250        Position { line, character }
251    }
252}
253
254/// A range in a text document expressed as (zero-based) start and end positions.
255/// A range is comparable to a selection in an editor. Therefore the end position is exclusive.
256#[derive(Debug, Eq, PartialEq, Copy, Clone, Default, Deserialize, Serialize)]
257pub struct Range {
258    /// The range's start position.
259    pub start: Position,
260    /// The range's end position.
261    pub end: Position,
262}
263
264impl Range {
265    pub fn new(start: Position, end: Position) -> Range {
266        Range { start, end }
267    }
268}
269
270/// Represents a location inside a resource, such as a line inside a text file.
271#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
272pub struct Location {
273    pub uri: Url,
274    pub range: Range,
275}
276
277impl Location {
278    pub fn new(uri: Url, range: Range) -> Location {
279        Location { uri, range }
280    }
281}
282
283/// Represents a link between a source and a target location.
284#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
285#[serde(rename_all = "camelCase")]
286pub struct LocationLink {
287    /// Span of the origin of this link.
288    ///
289    /// Used as the underlined span for mouse interaction. Defaults to the word range at
290    /// the mouse position.
291    #[serde(skip_serializing_if = "Option::is_none")]
292    pub origin_selection_range: Option<Range>,
293
294    /// The target resource identifier of this link.
295    pub target_uri: Url,
296
297    /// The full target range of this link.
298    pub target_range: Range,
299
300    /// The span of this link.
301    pub target_selection_range: Range,
302}
303
304/// A type indicating how positions are encoded,
305/// specifically what column offsets mean.
306///
307/// @since 3.17.0
308#[derive(Debug, Eq, PartialEq, Hash, PartialOrd, Clone, Deserialize, Serialize)]
309pub struct PositionEncodingKind(std::borrow::Cow<'static, str>);
310
311impl PositionEncodingKind {
312    /// Character offsets count UTF-8 code units.
313    pub const UTF8: PositionEncodingKind = PositionEncodingKind::new("utf-8");
314
315    /// Character offsets count UTF-16 code units.
316    ///
317    /// This is the default and must always be supported
318    /// by servers
319    pub const UTF16: PositionEncodingKind = PositionEncodingKind::new("utf-16");
320
321    /// Character offsets count UTF-32 code units.
322    ///
323    /// Implementation note: these are the same as Unicode code points,
324    /// so this `PositionEncodingKind` may also be used for an
325    /// encoding-agnostic representation of character offsets.
326    pub const UTF32: PositionEncodingKind = PositionEncodingKind::new("utf-32");
327
328    pub const fn new(tag: &'static str) -> Self {
329        PositionEncodingKind(std::borrow::Cow::Borrowed(tag))
330    }
331
332    pub fn as_str(&self) -> &str {
333        &self.0
334    }
335}
336
337impl From<String> for PositionEncodingKind {
338    fn from(from: String) -> Self {
339        PositionEncodingKind(std::borrow::Cow::from(from))
340    }
341}
342
343impl From<&'static str> for PositionEncodingKind {
344    fn from(from: &'static str) -> Self {
345        PositionEncodingKind::new(from)
346    }
347}
348
349/// Represents a diagnostic, such as a compiler error or warning.
350/// Diagnostic objects are only valid in the scope of a resource.
351#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
352#[serde(rename_all = "camelCase")]
353pub struct Diagnostic {
354    /// The range at which the message applies.
355    pub range: Range,
356
357    /// The diagnostic's severity. Can be omitted. If omitted it is up to the
358    /// client to interpret diagnostics as error, warning, info or hint.
359    #[serde(skip_serializing_if = "Option::is_none")]
360    pub severity: Option<DiagnosticSeverity>,
361
362    /// The diagnostic's code. Can be omitted.
363    #[serde(skip_serializing_if = "Option::is_none")]
364    pub code: Option<NumberOrString>,
365
366    /// An optional property to describe the error code.
367    ///
368    /// @since 3.16.0
369    #[serde(skip_serializing_if = "Option::is_none")]
370    pub code_description: Option<CodeDescription>,
371
372    /// A human-readable string describing the source of this
373    /// diagnostic, e.g. 'typescript' or 'super lint'.
374    #[serde(skip_serializing_if = "Option::is_none")]
375    pub source: Option<String>,
376
377    /// The diagnostic's message.
378    pub message: String,
379
380    /// An array of related diagnostic information, e.g. when symbol-names within
381    /// a scope collide all definitions can be marked via this property.
382    #[serde(skip_serializing_if = "Option::is_none")]
383    pub related_information: Option<Vec<DiagnosticRelatedInformation>>,
384
385    /// Additional metadata about the diagnostic.
386    #[serde(skip_serializing_if = "Option::is_none")]
387    pub tags: Option<Vec<DiagnosticTag>>,
388
389    /// A data entry field that is preserved between a `textDocument/publishDiagnostics`
390    /// notification and `textDocument/codeAction` request.
391    ///
392    /// @since 3.16.0
393    #[serde(skip_serializing_if = "Option::is_none")]
394    pub data: Option<serde_json::Value>,
395}
396
397#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
398#[serde(rename_all = "camelCase")]
399pub struct CodeDescription {
400    pub href: Url,
401}
402
403impl Diagnostic {
404    pub fn new(
405        range: Range,
406        severity: Option<DiagnosticSeverity>,
407        code: Option<NumberOrString>,
408        source: Option<String>,
409        message: String,
410        related_information: Option<Vec<DiagnosticRelatedInformation>>,
411        tags: Option<Vec<DiagnosticTag>>,
412    ) -> Diagnostic {
413        Diagnostic {
414            range,
415            severity,
416            code,
417            source,
418            message,
419            related_information,
420            tags,
421            ..Diagnostic::default()
422        }
423    }
424
425    pub fn new_simple(range: Range, message: String) -> Diagnostic {
426        Self::new(range, None, None, None, message, None, None)
427    }
428
429    pub fn new_with_code_number(
430        range: Range,
431        severity: DiagnosticSeverity,
432        code_number: i32,
433        source: Option<String>,
434        message: String,
435    ) -> Diagnostic {
436        let code = Some(NumberOrString::Number(code_number));
437        Self::new(range, Some(severity), code, source, message, None, None)
438    }
439}
440
441/// The protocol currently supports the following diagnostic severities:
442#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Deserialize, Serialize)]
443#[serde(transparent)]
444pub struct DiagnosticSeverity(i32);
445lsp_enum! {
446impl DiagnosticSeverity {
447    /// Reports an error.
448    pub const ERROR: DiagnosticSeverity = DiagnosticSeverity(1);
449    /// Reports a warning.
450    pub const WARNING: DiagnosticSeverity = DiagnosticSeverity(2);
451    /// Reports an information.
452    pub const INFORMATION: DiagnosticSeverity = DiagnosticSeverity(3);
453    /// Reports a hint.
454    pub const HINT: DiagnosticSeverity = DiagnosticSeverity(4);
455}
456}
457
458/// Represents a related message and source code location for a diagnostic. This
459/// should be used to point to code locations that cause or related to a
460/// diagnostics, e.g when duplicating a symbol in a scope.
461#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
462pub struct DiagnosticRelatedInformation {
463    /// The location of this related diagnostic information.
464    pub location: Location,
465
466    /// The message of this related diagnostic information.
467    pub message: String,
468}
469
470/// The diagnostic tags.
471#[derive(Eq, PartialEq, Clone, Deserialize, Serialize)]
472#[serde(transparent)]
473pub struct DiagnosticTag(i32);
474lsp_enum! {
475impl DiagnosticTag {
476    /// Unused or unnecessary code.
477    /// Clients are allowed to render diagnostics with this tag faded out instead of having
478    /// an error squiggle.
479    pub const UNNECESSARY: DiagnosticTag = DiagnosticTag(1);
480
481    /// Deprecated or obsolete code.
482    /// Clients are allowed to rendered diagnostics with this tag strike through.
483    pub const DEPRECATED: DiagnosticTag = DiagnosticTag(2);
484}
485}
486
487/// Represents a reference to a command. Provides a title which will be used to represent a command in the UI.
488/// Commands are identified by a string identifier. The recommended way to handle commands is to implement
489/// their execution on the server side if the client and server provides the corresponding capabilities.
490/// Alternatively the tool extension code could handle the command.
491/// The protocol currently doesn’t specify a set of well-known commands.
492#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
493pub struct Command {
494    /// Title of the command, like `save`.
495    pub title: String,
496    /// The identifier of the actual command handler.
497    pub command: String,
498    /// Arguments that the command handler should be
499    /// invoked with.
500    #[serde(skip_serializing_if = "Option::is_none")]
501    pub arguments: Option<Vec<Value>>,
502}
503
504impl Command {
505    pub fn new(title: String, command: String, arguments: Option<Vec<Value>>) -> Command {
506        Command {
507            title,
508            command,
509            arguments,
510        }
511    }
512}
513
514/// A textual edit applicable to a text document.
515///
516/// If n `TextEdit`s are applied to a text document all text edits describe changes to the initial document version.
517/// Execution wise text edits should applied from the bottom to the top of the text document. Overlapping text edits
518/// are not supported.
519#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
520#[serde(rename_all = "camelCase")]
521pub struct TextEdit {
522    /// The range of the text document to be manipulated. To insert
523    /// text into a document create a range where start === end.
524    pub range: Range,
525    /// The string to be inserted. For delete operations use an
526    /// empty string.
527    pub new_text: String,
528}
529
530impl TextEdit {
531    pub fn new(range: Range, new_text: String) -> TextEdit {
532        TextEdit { range, new_text }
533    }
534}
535
536/// An identifier referring to a change annotation managed by a workspace
537/// edit.
538///
539/// @since 3.16.0
540pub type ChangeAnnotationIdentifier = String;
541
542/// A special text edit with an additional change annotation.
543///
544/// @since 3.16.0
545#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
546#[serde(rename_all = "camelCase")]
547pub struct AnnotatedTextEdit {
548    #[serde(flatten)]
549    pub text_edit: TextEdit,
550
551    /// The actual annotation
552    pub annotation_id: ChangeAnnotationIdentifier,
553}
554
555/// Describes textual changes on a single text document. The text document is referred to as a
556/// `OptionalVersionedTextDocumentIdentifier` to allow clients to check the text document version before an
557/// edit is applied. A `TextDocumentEdit` describes all changes on a version Si and after they are
558/// applied move the document to version Si+1. So the creator of a `TextDocumentEdit` doesn't need to
559/// sort the array or do any kind of ordering. However the edits must be non overlapping.
560#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
561#[serde(rename_all = "camelCase")]
562pub struct TextDocumentEdit {
563    /// The text document to change.
564    pub text_document: OptionalVersionedTextDocumentIdentifier,
565
566    /// The edits to be applied.
567    ///
568    /// @since 3.16.0 - support for AnnotatedTextEdit. This is guarded by the
569    /// client capability `workspace.workspaceEdit.changeAnnotationSupport`
570    pub edits: Vec<OneOf<TextEdit, AnnotatedTextEdit>>,
571}
572
573/// Additional information that describes document changes.
574///
575/// @since 3.16.0
576#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
577#[serde(rename_all = "camelCase")]
578pub struct ChangeAnnotation {
579    /// A human-readable string describing the actual change. The string
580    /// is rendered prominent in the user interface.
581    pub label: String,
582
583    /// A flag which indicates that user confirmation is needed
584    /// before applying the change.
585    #[serde(skip_serializing_if = "Option::is_none")]
586    pub needs_confirmation: Option<bool>,
587
588    /// A human-readable string which is rendered less prominent in
589    /// the user interface.
590    #[serde(skip_serializing_if = "Option::is_none")]
591    pub description: Option<String>,
592}
593
594#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
595#[serde(rename_all = "camelCase")]
596pub struct ChangeAnnotationWorkspaceEditClientCapabilities {
597    /// Whether the client groups edits with equal labels into tree nodes,
598    /// for instance all edits labelled with "Changes in Strings" would
599    /// be a tree node.
600    #[serde(skip_serializing_if = "Option::is_none")]
601    pub groups_on_label: Option<bool>,
602}
603
604/// Options to create a file.
605#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
606#[serde(rename_all = "camelCase")]
607pub struct CreateFileOptions {
608    /// Overwrite existing file. Overwrite wins over `ignoreIfExists`
609    #[serde(skip_serializing_if = "Option::is_none")]
610    pub overwrite: Option<bool>,
611    /// Ignore if exists.
612    #[serde(skip_serializing_if = "Option::is_none")]
613    pub ignore_if_exists: Option<bool>,
614}
615
616/// Create file operation
617#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
618#[serde(rename_all = "camelCase")]
619pub struct CreateFile {
620    /// The resource to create.
621    pub uri: Url,
622    /// Additional options
623    #[serde(skip_serializing_if = "Option::is_none")]
624    pub options: Option<CreateFileOptions>,
625
626    /// An optional annotation identifier describing the operation.
627    ///
628    /// @since 3.16.0
629    #[serde(skip_serializing_if = "Option::is_none")]
630    pub annotation_id: Option<ChangeAnnotationIdentifier>,
631}
632
633/// Rename file options
634#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
635#[serde(rename_all = "camelCase")]
636pub struct RenameFileOptions {
637    /// Overwrite target if existing. Overwrite wins over `ignoreIfExists`
638    #[serde(skip_serializing_if = "Option::is_none")]
639    pub overwrite: Option<bool>,
640    /// Ignores if target exists.
641    #[serde(skip_serializing_if = "Option::is_none")]
642    pub ignore_if_exists: Option<bool>,
643}
644
645/// Rename file operation
646#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
647#[serde(rename_all = "camelCase")]
648pub struct RenameFile {
649    /// The old (existing) location.
650    pub old_uri: Url,
651    /// The new location.
652    pub new_uri: Url,
653    /// Rename options.
654    #[serde(skip_serializing_if = "Option::is_none")]
655    pub options: Option<RenameFileOptions>,
656
657    /// An optional annotation identifier describing the operation.
658    ///
659    /// @since 3.16.0
660    #[serde(skip_serializing_if = "Option::is_none")]
661    pub annotation_id: Option<ChangeAnnotationIdentifier>,
662}
663
664/// Delete file options
665#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
666#[serde(rename_all = "camelCase")]
667pub struct DeleteFileOptions {
668    /// Delete the content recursively if a folder is denoted.
669    #[serde(skip_serializing_if = "Option::is_none")]
670    pub recursive: Option<bool>,
671    /// Ignore the operation if the file doesn't exist.
672    #[serde(skip_serializing_if = "Option::is_none")]
673    pub ignore_if_not_exists: Option<bool>,
674
675    /// An optional annotation identifier describing the operation.
676    ///
677    /// @since 3.16.0
678    #[serde(skip_serializing_if = "Option::is_none")]
679    pub annotation_id: Option<ChangeAnnotationIdentifier>,
680}
681
682/// Delete file operation
683#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
684#[serde(rename_all = "camelCase")]
685pub struct DeleteFile {
686    /// The file to delete.
687    pub uri: Url,
688    /// Delete options.
689    #[serde(skip_serializing_if = "Option::is_none")]
690    pub options: Option<DeleteFileOptions>,
691}
692
693/// A workspace edit represents changes to many resources managed in the workspace.
694/// The edit should either provide `changes` or `documentChanges`.
695/// If the client can handle versioned document edits and if `documentChanges` are present,
696/// the latter are preferred over `changes`.
697#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
698#[serde(rename_all = "camelCase")]
699pub struct WorkspaceEdit {
700    /// Holds changes to existing resources.
701    #[serde(with = "url_map")]
702    #[serde(skip_serializing_if = "Option::is_none")]
703    #[serde(default)]
704    pub changes: Option<HashMap<Url, Vec<TextEdit>>>, //    changes?: { [uri: string]: TextEdit[]; };
705
706    /// Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes
707    /// are either an array of `TextDocumentEdit`s to express changes to n different text documents
708    /// where each text document edit addresses a specific version of a text document. Or it can contain
709    /// above `TextDocumentEdit`s mixed with create, rename and delete file / folder operations.
710    ///
711    /// Whether a client supports versioned document edits is expressed via
712    /// `workspace.workspaceEdit.documentChanges` client capability.
713    ///
714    /// If a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then
715    /// only plain `TextEdit`s using the `changes` property are supported.
716    #[serde(skip_serializing_if = "Option::is_none")]
717    pub document_changes: Option<DocumentChanges>,
718
719    /// A map of change annotations that can be referenced in
720    /// `AnnotatedTextEdit`s or create, rename and delete file / folder
721    /// operations.
722    ///
723    /// Whether clients honor this property depends on the client capability
724    /// `workspace.changeAnnotationSupport`.
725    ///
726    /// @since 3.16.0
727    #[serde(skip_serializing_if = "Option::is_none")]
728    pub change_annotations: Option<HashMap<ChangeAnnotationIdentifier, ChangeAnnotation>>,
729}
730
731#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
732#[serde(untagged)]
733pub enum DocumentChanges {
734    Edits(Vec<TextDocumentEdit>),
735    Operations(Vec<DocumentChangeOperation>),
736}
737
738// TODO: Once https://github.com/serde-rs/serde/issues/912 is solved
739// we can remove ResourceOp and switch to the following implementation
740// of DocumentChangeOperation:
741//
742// #[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
743// #[serde(tag = "kind", rename_all="lowercase" )]
744// pub enum DocumentChangeOperation {
745//     Create(CreateFile),
746//     Rename(RenameFile),
747//     Delete(DeleteFile),
748//
749//     #[serde(other)]
750//     Edit(TextDocumentEdit),
751// }
752
753#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
754#[serde(untagged, rename_all = "lowercase")]
755pub enum DocumentChangeOperation {
756    Op(ResourceOp),
757    Edit(TextDocumentEdit),
758}
759
760#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
761#[serde(tag = "kind", rename_all = "lowercase")]
762pub enum ResourceOp {
763    Create(CreateFile),
764    Rename(RenameFile),
765    Delete(DeleteFile),
766}
767
768pub type DidChangeConfigurationClientCapabilities = DynamicRegistrationClientCapabilities;
769
770#[derive(Debug, Default, Eq, PartialEq, Clone, Deserialize, Serialize)]
771#[serde(rename_all = "camelCase")]
772pub struct ConfigurationParams {
773    pub items: Vec<ConfigurationItem>,
774}
775
776#[derive(Debug, Default, Eq, PartialEq, Clone, Deserialize, Serialize)]
777#[serde(rename_all = "camelCase")]
778pub struct ConfigurationItem {
779    /// The scope to get the configuration section for.
780    #[serde(skip_serializing_if = "Option::is_none")]
781    pub scope_uri: Option<Url>,
782
783    ///The configuration section asked for.
784    #[serde(skip_serializing_if = "Option::is_none")]
785    pub section: Option<String>,
786}
787
788mod url_map {
789    use std::fmt;
790    use std::marker::PhantomData;
791
792    use super::*;
793
794    pub fn deserialize<'de, D, V>(deserializer: D) -> Result<Option<HashMap<Url, V>>, D::Error>
795    where
796        D: serde::Deserializer<'de>,
797        V: de::DeserializeOwned,
798    {
799        struct UrlMapVisitor<V> {
800            _marker: PhantomData<V>,
801        }
802
803        impl<V: de::DeserializeOwned> Default for UrlMapVisitor<V> {
804            fn default() -> Self {
805                UrlMapVisitor {
806                    _marker: PhantomData,
807                }
808            }
809        }
810        impl<'de, V: de::DeserializeOwned> de::Visitor<'de> for UrlMapVisitor<V> {
811            type Value = HashMap<Url, V>;
812
813            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
814                formatter.write_str("map")
815            }
816
817            fn visit_map<M>(self, mut visitor: M) -> Result<Self::Value, M::Error>
818            where
819                M: de::MapAccess<'de>,
820            {
821                let mut values = HashMap::with_capacity(visitor.size_hint().unwrap_or(0));
822
823                // While there are entries remaining in the input, add them
824                // into our map.
825                while let Some((key, value)) = visitor.next_entry::<Url, _>()? {
826                    values.insert(key, value);
827                }
828
829                Ok(values)
830            }
831        }
832
833        struct OptionUrlMapVisitor<V> {
834            _marker: PhantomData<V>,
835        }
836        impl<V: de::DeserializeOwned> Default for OptionUrlMapVisitor<V> {
837            fn default() -> Self {
838                OptionUrlMapVisitor {
839                    _marker: PhantomData,
840                }
841            }
842        }
843        impl<'de, V: de::DeserializeOwned> de::Visitor<'de> for OptionUrlMapVisitor<V> {
844            type Value = Option<HashMap<Url, V>>;
845
846            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
847                formatter.write_str("option")
848            }
849
850            #[inline]
851            fn visit_unit<E>(self) -> Result<Self::Value, E>
852            where
853                E: serde::de::Error,
854            {
855                Ok(None)
856            }
857
858            #[inline]
859            fn visit_none<E>(self) -> Result<Self::Value, E>
860            where
861                E: serde::de::Error,
862            {
863                Ok(None)
864            }
865
866            #[inline]
867            fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
868            where
869                D: serde::Deserializer<'de>,
870            {
871                deserializer
872                    .deserialize_map(UrlMapVisitor::<V>::default())
873                    .map(Some)
874            }
875        }
876
877        // Instantiate our Visitor and ask the Deserializer to drive
878        // it over the input data, resulting in an instance of MyMap.
879        deserializer.deserialize_option(OptionUrlMapVisitor::default())
880    }
881
882    pub fn serialize<S, V>(
883        changes: &Option<HashMap<Url, V>>,
884        serializer: S,
885    ) -> Result<S::Ok, S::Error>
886    where
887        S: serde::Serializer,
888        V: serde::Serialize,
889    {
890        use serde::ser::SerializeMap;
891
892        match *changes {
893            Some(ref changes) => {
894                let mut map = serializer.serialize_map(Some(changes.len()))?;
895                for (k, v) in changes {
896                    map.serialize_entry(k.as_str(), v)?;
897                }
898                map.end()
899            }
900            None => serializer.serialize_none(),
901        }
902    }
903}
904
905impl WorkspaceEdit {
906    pub fn new(changes: HashMap<Url, Vec<TextEdit>>) -> WorkspaceEdit {
907        WorkspaceEdit {
908            changes: Some(changes),
909            document_changes: None,
910            ..Default::default()
911        }
912    }
913}
914
915/// Text documents are identified using a URI. On the protocol level, URIs are passed as strings.
916#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
917pub struct TextDocumentIdentifier {
918    // !!!!!! Note:
919    // In the spec VersionedTextDocumentIdentifier extends TextDocumentIdentifier
920    // This modelled by "mixing-in" TextDocumentIdentifier in VersionedTextDocumentIdentifier,
921    // so any changes to this type must be effected in the sub-type as well.
922    /// The text document's URI.
923    pub uri: Url,
924}
925
926impl TextDocumentIdentifier {
927    pub fn new(uri: Url) -> TextDocumentIdentifier {
928        TextDocumentIdentifier { uri }
929    }
930}
931
932/// An item to transfer a text document from the client to the server.
933#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
934#[serde(rename_all = "camelCase")]
935pub struct TextDocumentItem {
936    /// The text document's URI.
937    pub uri: Url,
938
939    /// The text document's language identifier.
940    pub language_id: String,
941
942    /// The version number of this document (it will strictly increase after each
943    /// change, including undo/redo).
944    pub version: i32,
945
946    /// The content of the opened text document.
947    pub text: String,
948}
949
950impl TextDocumentItem {
951    pub fn new(uri: Url, language_id: String, version: i32, text: String) -> TextDocumentItem {
952        TextDocumentItem {
953            uri,
954            language_id,
955            version,
956            text,
957        }
958    }
959}
960
961/// An identifier to denote a specific version of a text document. This information usually flows from the client to the server.
962#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
963pub struct VersionedTextDocumentIdentifier {
964    // This field was "mixed-in" from TextDocumentIdentifier
965    /// The text document's URI.
966    pub uri: Url,
967
968    /// The version number of this document.
969    ///
970    /// The version number of a document will increase after each change,
971    /// including undo/redo. The number doesn't need to be consecutive.
972    pub version: i32,
973}
974
975impl VersionedTextDocumentIdentifier {
976    pub fn new(uri: Url, version: i32) -> VersionedTextDocumentIdentifier {
977        VersionedTextDocumentIdentifier { uri, version }
978    }
979}
980
981/// An identifier which optionally denotes a specific version of a text document. This information usually flows from the server to the client
982#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
983pub struct OptionalVersionedTextDocumentIdentifier {
984    // This field was "mixed-in" from TextDocumentIdentifier
985    /// The text document's URI.
986    pub uri: Url,
987
988    /// The version number of this document. If an optional versioned text document
989    /// identifier is sent from the server to the client and the file is not
990    /// open in the editor (the server has not received an open notification
991    /// before) the server can send `null` to indicate that the version is
992    /// known and the content on disk is the master (as specified with document
993    /// content ownership).
994    ///
995    /// The version number of a document will increase after each change,
996    /// including undo/redo. The number doesn't need to be consecutive.
997    pub version: Option<i32>,
998}
999
1000impl OptionalVersionedTextDocumentIdentifier {
1001    pub fn new(uri: Url, version: i32) -> OptionalVersionedTextDocumentIdentifier {
1002        OptionalVersionedTextDocumentIdentifier {
1003            uri,
1004            version: Some(version),
1005        }
1006    }
1007}
1008
1009/// A parameter literal used in requests to pass a text document and a position inside that document.
1010#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
1011#[serde(rename_all = "camelCase")]
1012pub struct TextDocumentPositionParams {
1013    // !!!!!! Note:
1014    // In the spec ReferenceParams extends TextDocumentPositionParams
1015    // This modelled by "mixing-in" TextDocumentPositionParams in ReferenceParams,
1016    // so any changes to this type must be effected in sub-type as well.
1017    /// The text document.
1018    pub text_document: TextDocumentIdentifier,
1019
1020    /// The position inside the text document.
1021    pub position: Position,
1022}
1023
1024impl TextDocumentPositionParams {
1025    pub fn new(
1026        text_document: TextDocumentIdentifier,
1027        position: Position,
1028    ) -> TextDocumentPositionParams {
1029        TextDocumentPositionParams {
1030            text_document,
1031            position,
1032        }
1033    }
1034}
1035
1036/// A document filter denotes a document through properties like language, schema or pattern.
1037/// Examples are a filter that applies to TypeScript files on disk or a filter the applies to JSON
1038/// files with name package.json:
1039///
1040/// { language: 'typescript', scheme: 'file' }
1041/// { language: 'json', pattern: '**/package.json' }
1042#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
1043pub struct DocumentFilter {
1044    /// A language id, like `typescript`.
1045    #[serde(skip_serializing_if = "Option::is_none")]
1046    pub language: Option<String>,
1047
1048    /// A Uri [scheme](#Uri.scheme), like `file` or `untitled`.
1049    #[serde(skip_serializing_if = "Option::is_none")]
1050    pub scheme: Option<String>,
1051
1052    /// A glob pattern, like `*.{ts,js}`.
1053    #[serde(skip_serializing_if = "Option::is_none")]
1054    pub pattern: Option<String>,
1055}
1056
1057/// A document selector is the combination of one or many document filters.
1058pub type DocumentSelector = Vec<DocumentFilter>;
1059
1060// ========================= Actual Protocol =========================
1061
1062#[derive(Debug, PartialEq, Clone, Deserialize, Serialize, Default)]
1063#[serde(rename_all = "camelCase")]
1064pub struct InitializeParams {
1065    /// The process Id of the parent process that started
1066    /// the server. Is null if the process has not been started by another process.
1067    /// If the parent process is not alive then the server should exit (see exit notification) its process.
1068    pub process_id: Option<u32>,
1069
1070    /// The rootPath of the workspace. Is null
1071    /// if no folder is open.
1072    #[serde(skip_serializing_if = "Option::is_none")]
1073    #[deprecated(note = "Use `root_uri` instead when possible")]
1074    pub root_path: Option<String>,
1075
1076    /// The rootUri of the workspace. Is null if no
1077    /// folder is open. If both `rootPath` and `rootUri` are set
1078    /// `rootUri` wins.
1079    ///
1080    /// Deprecated in favour of `workspaceFolders`
1081    #[serde(default)]
1082    pub root_uri: Option<Url>,
1083
1084    /// User provided initialization options.
1085    #[serde(skip_serializing_if = "Option::is_none")]
1086    pub initialization_options: Option<Value>,
1087
1088    /// The capabilities provided by the client (editor or tool)
1089    pub capabilities: ClientCapabilities,
1090
1091    /// The initial trace setting. If omitted trace is disabled ('off').
1092    #[serde(default)]
1093    #[serde(skip_serializing_if = "Option::is_none")]
1094    pub trace: Option<TraceValue>,
1095
1096    /// The workspace folders configured in the client when the server starts.
1097    /// This property is only available if the client supports workspace folders.
1098    /// It can be `null` if the client supports workspace folders but none are
1099    /// configured.
1100    #[serde(skip_serializing_if = "Option::is_none")]
1101    pub workspace_folders: Option<Vec<WorkspaceFolder>>,
1102
1103    /// Information about the client.
1104    #[serde(skip_serializing_if = "Option::is_none")]
1105    pub client_info: Option<ClientInfo>,
1106
1107    /// The locale the client is currently showing the user interface
1108    /// in. This must not necessarily be the locale of the operating
1109    /// system.
1110    ///
1111    /// Uses IETF language tags as the value's syntax
1112    /// (See <https://en.wikipedia.org/wiki/IETF_language_tag>)
1113    ///
1114    /// @since 3.16.0
1115    #[serde(skip_serializing_if = "Option::is_none")]
1116    pub locale: Option<String>,
1117}
1118
1119#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
1120pub struct ClientInfo {
1121    /// The name of the client as defined by the client.
1122    pub name: String,
1123    /// The client's version as defined by the client.
1124    #[serde(skip_serializing_if = "Option::is_none")]
1125    pub version: Option<String>,
1126}
1127
1128#[derive(Debug, PartialEq, Clone, Copy, Deserialize, Serialize)]
1129pub struct InitializedParams {}
1130
1131#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
1132pub struct GenericRegistrationOptions {
1133    #[serde(flatten)]
1134    pub text_document_registration_options: TextDocumentRegistrationOptions,
1135
1136    #[serde(flatten)]
1137    pub options: GenericOptions,
1138
1139    #[serde(flatten)]
1140    pub static_registration_options: StaticRegistrationOptions,
1141}
1142
1143#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
1144pub struct GenericOptions {
1145    #[serde(flatten)]
1146    pub work_done_progress_options: WorkDoneProgressOptions,
1147}
1148
1149#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
1150pub struct GenericParams {
1151    #[serde(flatten)]
1152    pub text_document_position_params: TextDocumentPositionParams,
1153
1154    #[serde(flatten)]
1155    pub work_done_progress_params: WorkDoneProgressParams,
1156
1157    #[serde(flatten)]
1158    pub partial_result_params: PartialResultParams,
1159}
1160
1161#[derive(Debug, Eq, PartialEq, Clone, Copy, Default, Deserialize, Serialize)]
1162#[serde(rename_all = "camelCase")]
1163pub struct DynamicRegistrationClientCapabilities {
1164    /// This capability supports dynamic registration.
1165    #[serde(skip_serializing_if = "Option::is_none")]
1166    pub dynamic_registration: Option<bool>,
1167}
1168
1169#[derive(Debug, Eq, PartialEq, Clone, Copy, Default, Deserialize, Serialize)]
1170#[serde(rename_all = "camelCase")]
1171pub struct GotoCapability {
1172    #[serde(skip_serializing_if = "Option::is_none")]
1173    pub dynamic_registration: Option<bool>,
1174
1175    /// The client supports additional metadata in the form of definition links.
1176    #[serde(skip_serializing_if = "Option::is_none")]
1177    pub link_support: Option<bool>,
1178}
1179
1180#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
1181#[serde(rename_all = "camelCase")]
1182pub struct WorkspaceEditClientCapabilities {
1183    /// The client supports versioned document changes in `WorkspaceEdit`s
1184    #[serde(skip_serializing_if = "Option::is_none")]
1185    pub document_changes: Option<bool>,
1186
1187    /// The resource operations the client supports. Clients should at least
1188    /// support 'create', 'rename' and 'delete' files and folders.
1189    #[serde(skip_serializing_if = "Option::is_none")]
1190    pub resource_operations: Option<Vec<ResourceOperationKind>>,
1191
1192    /// The failure handling strategy of a client if applying the workspace edit fails.
1193    #[serde(skip_serializing_if = "Option::is_none")]
1194    pub failure_handling: Option<FailureHandlingKind>,
1195
1196    /// Whether the client normalizes line endings to the client specific
1197    /// setting.
1198    /// If set to `true` the client will normalize line ending characters
1199    /// in a workspace edit to the client specific new line character(s).
1200    ///
1201    /// @since 3.16.0
1202    #[serde(skip_serializing_if = "Option::is_none")]
1203    pub normalizes_line_endings: Option<bool>,
1204
1205    /// Whether the client in general supports change annotations on text edits,
1206    /// create file, rename file and delete file changes.
1207    ///
1208    /// @since 3.16.0
1209    #[serde(skip_serializing_if = "Option::is_none")]
1210    pub change_annotation_support: Option<ChangeAnnotationWorkspaceEditClientCapabilities>,
1211}
1212
1213#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Copy, Clone)]
1214#[serde(rename_all = "lowercase")]
1215pub enum ResourceOperationKind {
1216    Create,
1217    Rename,
1218    Delete,
1219}
1220
1221#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Copy, Clone)]
1222#[serde(rename_all = "camelCase")]
1223pub enum FailureHandlingKind {
1224    Abort,
1225    Transactional,
1226    TextOnlyTransactional,
1227    Undo,
1228}
1229
1230/// A symbol kind.
1231#[derive(Eq, PartialEq, Copy, Clone, Serialize, Deserialize)]
1232#[serde(transparent)]
1233pub struct SymbolKind(i32);
1234lsp_enum! {
1235impl SymbolKind {
1236    pub const FILE: SymbolKind = SymbolKind(1);
1237    pub const MODULE: SymbolKind = SymbolKind(2);
1238    pub const NAMESPACE: SymbolKind = SymbolKind(3);
1239    pub const PACKAGE: SymbolKind = SymbolKind(4);
1240    pub const CLASS: SymbolKind = SymbolKind(5);
1241    pub const METHOD: SymbolKind = SymbolKind(6);
1242    pub const PROPERTY: SymbolKind = SymbolKind(7);
1243    pub const FIELD: SymbolKind = SymbolKind(8);
1244    pub const CONSTRUCTOR: SymbolKind = SymbolKind(9);
1245    pub const ENUM: SymbolKind = SymbolKind(10);
1246    pub const INTERFACE: SymbolKind = SymbolKind(11);
1247    pub const FUNCTION: SymbolKind = SymbolKind(12);
1248    pub const VARIABLE: SymbolKind = SymbolKind(13);
1249    pub const CONSTANT: SymbolKind = SymbolKind(14);
1250    pub const STRING: SymbolKind = SymbolKind(15);
1251    pub const NUMBER: SymbolKind = SymbolKind(16);
1252    pub const BOOLEAN: SymbolKind = SymbolKind(17);
1253    pub const ARRAY: SymbolKind = SymbolKind(18);
1254    pub const OBJECT: SymbolKind = SymbolKind(19);
1255    pub const KEY: SymbolKind = SymbolKind(20);
1256    pub const NULL: SymbolKind = SymbolKind(21);
1257    pub const ENUM_MEMBER: SymbolKind = SymbolKind(22);
1258    pub const STRUCT: SymbolKind = SymbolKind(23);
1259    pub const EVENT: SymbolKind = SymbolKind(24);
1260    pub const OPERATOR: SymbolKind = SymbolKind(25);
1261    pub const TYPE_PARAMETER: SymbolKind = SymbolKind(26);
1262}
1263}
1264
1265/// Specific capabilities for the `SymbolKind` in the `workspace/symbol` request.
1266#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
1267#[serde(rename_all = "camelCase")]
1268pub struct SymbolKindCapability {
1269    /// The symbol kind values the client supports. When this
1270    /// property exists the client also guarantees that it will
1271    /// handle values outside its set gracefully and falls back
1272    /// to a default value when unknown.
1273    ///
1274    /// If this property is not present the client only supports
1275    /// the symbol kinds from `File` to `Array` as defined in
1276    /// the initial version of the protocol.
1277    pub value_set: Option<Vec<SymbolKind>>,
1278}
1279
1280/// Workspace specific client capabilities.
1281#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
1282#[serde(rename_all = "camelCase")]
1283pub struct WorkspaceClientCapabilities {
1284    /// The client supports applying batch edits to the workspace by supporting
1285    /// the request 'workspace/applyEdit'
1286    #[serde(skip_serializing_if = "Option::is_none")]
1287    pub apply_edit: Option<bool>,
1288
1289    /// Capabilities specific to `WorkspaceEdit`s
1290    #[serde(skip_serializing_if = "Option::is_none")]
1291    pub workspace_edit: Option<WorkspaceEditClientCapabilities>,
1292
1293    /// Capabilities specific to the `workspace/didChangeConfiguration` notification.
1294    #[serde(skip_serializing_if = "Option::is_none")]
1295    pub did_change_configuration: Option<DidChangeConfigurationClientCapabilities>,
1296
1297    /// Capabilities specific to the `workspace/didChangeWatchedFiles` notification.
1298    #[serde(skip_serializing_if = "Option::is_none")]
1299    pub did_change_watched_files: Option<DidChangeWatchedFilesClientCapabilities>,
1300
1301    /// Capabilities specific to the `workspace/symbol` request.
1302    #[serde(skip_serializing_if = "Option::is_none")]
1303    pub symbol: Option<WorkspaceSymbolClientCapabilities>,
1304
1305    /// Capabilities specific to the `workspace/executeCommand` request.
1306    #[serde(skip_serializing_if = "Option::is_none")]
1307    pub execute_command: Option<ExecuteCommandClientCapabilities>,
1308
1309    /// The client has support for workspace folders.
1310    ///
1311    /// @since 3.6.0
1312    #[serde(skip_serializing_if = "Option::is_none")]
1313    pub workspace_folders: Option<bool>,
1314
1315    /// The client supports `workspace/configuration` requests.
1316    ///
1317    /// @since 3.6.0
1318    #[serde(skip_serializing_if = "Option::is_none")]
1319    pub configuration: Option<bool>,
1320
1321    /// Capabilities specific to the semantic token requests scoped to the workspace.
1322    ///
1323    /// @since 3.16.0
1324    #[serde(skip_serializing_if = "Option::is_none")]
1325    pub semantic_tokens: Option<SemanticTokensWorkspaceClientCapabilities>,
1326
1327    /// Capabilities specific to the code lens requests scoped to the workspace.
1328    ///
1329    /// @since 3.16.0
1330    #[serde(skip_serializing_if = "Option::is_none")]
1331    pub code_lens: Option<CodeLensWorkspaceClientCapabilities>,
1332
1333    /// The client has support for file requests/notifications.
1334    ///
1335    /// @since 3.16.0
1336    #[serde(skip_serializing_if = "Option::is_none")]
1337    pub file_operations: Option<WorkspaceFileOperationsClientCapabilities>,
1338
1339    /// Client workspace capabilities specific to inline values.
1340    ///
1341    /// @since 3.17.0
1342    #[serde(skip_serializing_if = "Option::is_none")]
1343    pub inline_value: Option<InlineValueWorkspaceClientCapabilities>,
1344
1345    /// Client workspace capabilities specific to inlay hints.
1346    ///
1347    /// @since 3.17.0
1348    #[serde(skip_serializing_if = "Option::is_none")]
1349    pub inlay_hint: Option<InlayHintWorkspaceClientCapabilities>,
1350
1351    /// Client workspace capabilities specific to diagnostics.
1352    /// since 3.17.0
1353    #[serde(skip_serializing_if = "Option::is_none")]
1354    pub diagnostic: Option<DiagnosticWorkspaceClientCapabilities>,
1355}
1356
1357#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
1358#[serde(rename_all = "camelCase")]
1359pub struct TextDocumentSyncClientCapabilities {
1360    /// Whether text document synchronization supports dynamic registration.
1361    #[serde(skip_serializing_if = "Option::is_none")]
1362    pub dynamic_registration: Option<bool>,
1363
1364    /// The client supports sending will save notifications.
1365    #[serde(skip_serializing_if = "Option::is_none")]
1366    pub will_save: Option<bool>,
1367
1368    /// The client supports sending a will save request and
1369    /// waits for a response providing text edits which will
1370    /// be applied to the document before it is saved.
1371    #[serde(skip_serializing_if = "Option::is_none")]
1372    pub will_save_wait_until: Option<bool>,
1373
1374    /// The client supports did save notifications.
1375    #[serde(skip_serializing_if = "Option::is_none")]
1376    pub did_save: Option<bool>,
1377}
1378
1379#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
1380#[serde(rename_all = "camelCase")]
1381pub struct PublishDiagnosticsClientCapabilities {
1382    /// Whether the clients accepts diagnostics with related information.
1383    #[serde(skip_serializing_if = "Option::is_none")]
1384    pub related_information: Option<bool>,
1385
1386    /// Client supports the tag property to provide meta data about a diagnostic.
1387    /// Clients supporting tags have to handle unknown tags gracefully.
1388    #[serde(
1389        default,
1390        skip_serializing_if = "Option::is_none",
1391        deserialize_with = "TagSupport::deserialize_compat"
1392    )]
1393    pub tag_support: Option<TagSupport<DiagnosticTag>>,
1394
1395    /// Whether the client interprets the version property of the
1396    /// `textDocument/publishDiagnostics` notification's parameter.
1397    ///
1398    /// @since 3.15.0
1399    #[serde(skip_serializing_if = "Option::is_none")]
1400    pub version_support: Option<bool>,
1401
1402    /// Client supports a codeDescription property
1403    ///
1404    /// @since 3.16.0
1405    #[serde(skip_serializing_if = "Option::is_none")]
1406    pub code_description_support: Option<bool>,
1407
1408    /// Whether code action supports the `data` property which is
1409    /// preserved between a `textDocument/publishDiagnostics` and
1410    /// `textDocument/codeAction` request.
1411    ///
1412    /// @since 3.16.0
1413    #[serde(skip_serializing_if = "Option::is_none")]
1414    pub data_support: Option<bool>,
1415}
1416
1417#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
1418#[serde(rename_all = "camelCase")]
1419pub struct TagSupport<T> {
1420    /// The tags supported by the client.
1421    pub value_set: Vec<T>,
1422}
1423
1424impl<T> TagSupport<T> {
1425    /// Support for deserializing a boolean tag Support, in case it's present.
1426    ///
1427    /// This is currently the case for vscode 1.41.1
1428    fn deserialize_compat<'de, S>(serializer: S) -> Result<Option<TagSupport<T>>, S::Error>
1429    where
1430        S: serde::Deserializer<'de>,
1431        T: serde::Deserialize<'de>,
1432    {
1433        Ok(
1434            match Option::<Value>::deserialize(serializer).map_err(serde::de::Error::custom)? {
1435                Some(Value::Bool(false)) => None,
1436                Some(Value::Bool(true)) => Some(TagSupport { value_set: vec![] }),
1437                Some(other) => {
1438                    Some(TagSupport::<T>::deserialize(other).map_err(serde::de::Error::custom)?)
1439                }
1440                None => None,
1441            },
1442        )
1443    }
1444}
1445
1446/// Text document specific client capabilities.
1447#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
1448#[serde(rename_all = "camelCase")]
1449pub struct TextDocumentClientCapabilities {
1450    #[serde(skip_serializing_if = "Option::is_none")]
1451    pub synchronization: Option<TextDocumentSyncClientCapabilities>,
1452    /// Capabilities specific to the `textDocument/completion`
1453    #[serde(skip_serializing_if = "Option::is_none")]
1454    pub completion: Option<CompletionClientCapabilities>,
1455
1456    /// Capabilities specific to the `textDocument/hover`
1457    #[serde(skip_serializing_if = "Option::is_none")]
1458    pub hover: Option<HoverClientCapabilities>,
1459
1460    /// Capabilities specific to the `textDocument/signatureHelp`
1461    #[serde(skip_serializing_if = "Option::is_none")]
1462    pub signature_help: Option<SignatureHelpClientCapabilities>,
1463
1464    /// Capabilities specific to the `textDocument/references`
1465    #[serde(skip_serializing_if = "Option::is_none")]
1466    pub references: Option<ReferenceClientCapabilities>,
1467
1468    /// Capabilities specific to the `textDocument/documentHighlight`
1469    #[serde(skip_serializing_if = "Option::is_none")]
1470    pub document_highlight: Option<DocumentHighlightClientCapabilities>,
1471
1472    /// Capabilities specific to the `textDocument/documentSymbol`
1473    #[serde(skip_serializing_if = "Option::is_none")]
1474    pub document_symbol: Option<DocumentSymbolClientCapabilities>,
1475    /// Capabilities specific to the `textDocument/formatting`
1476    #[serde(skip_serializing_if = "Option::is_none")]
1477    pub formatting: Option<DocumentFormattingClientCapabilities>,
1478
1479    /// Capabilities specific to the `textDocument/rangeFormatting`
1480    #[serde(skip_serializing_if = "Option::is_none")]
1481    pub range_formatting: Option<DocumentRangeFormattingClientCapabilities>,
1482
1483    /// Capabilities specific to the `textDocument/onTypeFormatting`
1484    #[serde(skip_serializing_if = "Option::is_none")]
1485    pub on_type_formatting: Option<DocumentOnTypeFormattingClientCapabilities>,
1486
1487    /// Capabilities specific to the `textDocument/declaration`
1488    #[serde(skip_serializing_if = "Option::is_none")]
1489    pub declaration: Option<GotoCapability>,
1490
1491    /// Capabilities specific to the `textDocument/definition`
1492    #[serde(skip_serializing_if = "Option::is_none")]
1493    pub definition: Option<GotoCapability>,
1494
1495    /// Capabilities specific to the `textDocument/typeDefinition`
1496    #[serde(skip_serializing_if = "Option::is_none")]
1497    pub type_definition: Option<GotoCapability>,
1498
1499    /// Capabilities specific to the `textDocument/implementation`
1500    #[serde(skip_serializing_if = "Option::is_none")]
1501    pub implementation: Option<GotoCapability>,
1502
1503    /// Capabilities specific to the `textDocument/codeAction`
1504    #[serde(skip_serializing_if = "Option::is_none")]
1505    pub code_action: Option<CodeActionClientCapabilities>,
1506
1507    /// Capabilities specific to the `textDocument/codeLens`
1508    #[serde(skip_serializing_if = "Option::is_none")]
1509    pub code_lens: Option<CodeLensClientCapabilities>,
1510
1511    /// Capabilities specific to the `textDocument/documentLink`
1512    #[serde(skip_serializing_if = "Option::is_none")]
1513    pub document_link: Option<DocumentLinkClientCapabilities>,
1514
1515    /// Capabilities specific to the `textDocument/documentColor` and the
1516    /// `textDocument/colorPresentation` request.
1517    #[serde(skip_serializing_if = "Option::is_none")]
1518    pub color_provider: Option<DocumentColorClientCapabilities>,
1519
1520    /// Capabilities specific to the `textDocument/rename`
1521    #[serde(skip_serializing_if = "Option::is_none")]
1522    pub rename: Option<RenameClientCapabilities>,
1523
1524    /// Capabilities specific to `textDocument/publishDiagnostics`.
1525    #[serde(skip_serializing_if = "Option::is_none")]
1526    pub publish_diagnostics: Option<PublishDiagnosticsClientCapabilities>,
1527
1528    /// Capabilities specific to `textDocument/foldingRange` requests.
1529    #[serde(skip_serializing_if = "Option::is_none")]
1530    pub folding_range: Option<FoldingRangeClientCapabilities>,
1531
1532    /// Capabilities specific to the `textDocument/selectionRange` request.
1533    ///
1534    /// @since 3.15.0
1535    #[serde(skip_serializing_if = "Option::is_none")]
1536    pub selection_range: Option<SelectionRangeClientCapabilities>,
1537
1538    /// Capabilities specific to `textDocument/linkedEditingRange` requests.
1539    ///
1540    /// @since 3.16.0
1541    #[serde(skip_serializing_if = "Option::is_none")]
1542    pub linked_editing_range: Option<LinkedEditingRangeClientCapabilities>,
1543
1544    /// Capabilities specific to the various call hierarchy requests.
1545    ///
1546    /// @since 3.16.0
1547    #[serde(skip_serializing_if = "Option::is_none")]
1548    pub call_hierarchy: Option<CallHierarchyClientCapabilities>,
1549
1550    /// Capabilities specific to the `textDocument/semanticTokens/*` requests.
1551    #[serde(skip_serializing_if = "Option::is_none")]
1552    pub semantic_tokens: Option<SemanticTokensClientCapabilities>,
1553
1554    /// Capabilities specific to the `textDocument/moniker` request.
1555    ///
1556    /// @since 3.16.0
1557    #[serde(skip_serializing_if = "Option::is_none")]
1558    pub moniker: Option<MonikerClientCapabilities>,
1559
1560    /// Capabilities specific to the various type hierarchy requests.
1561    ///
1562    /// @since 3.17.0
1563    #[serde(skip_serializing_if = "Option::is_none")]
1564    pub type_hierarchy: Option<TypeHierarchyClientCapabilities>,
1565
1566    /// Capabilities specific to the `textDocument/inlineValue` request.
1567    ///
1568    /// @since 3.17.0
1569    #[serde(skip_serializing_if = "Option::is_none")]
1570    pub inline_value: Option<InlineValueClientCapabilities>,
1571
1572    /// Capabilities specific to the `textDocument/inlayHint` request.
1573    ///
1574    /// @since 3.17.0
1575    #[serde(skip_serializing_if = "Option::is_none")]
1576    pub inlay_hint: Option<InlayHintClientCapabilities>,
1577
1578    /// Capabilities specific to the diagnostic pull model.
1579    ///
1580    /// @since 3.17.0
1581    #[serde(skip_serializing_if = "Option::is_none")]
1582    pub diagnostic: Option<DiagnosticClientCapabilities>,
1583}
1584
1585/// Where ClientCapabilities are currently empty:
1586#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
1587#[serde(rename_all = "camelCase")]
1588pub struct ClientCapabilities {
1589    /// Workspace specific client capabilities.
1590    #[serde(skip_serializing_if = "Option::is_none")]
1591    pub workspace: Option<WorkspaceClientCapabilities>,
1592
1593    /// Text document specific client capabilities.
1594    #[serde(skip_serializing_if = "Option::is_none")]
1595    pub text_document: Option<TextDocumentClientCapabilities>,
1596
1597    /// Window specific client capabilities.
1598    #[serde(skip_serializing_if = "Option::is_none")]
1599    pub window: Option<WindowClientCapabilities>,
1600
1601    /// General client capabilities.
1602    #[serde(skip_serializing_if = "Option::is_none")]
1603    pub general: Option<GeneralClientCapabilities>,
1604
1605    /// Unofficial UT8-offsets extension.
1606    ///
1607    /// See https://clangd.llvm.org/extensions.html#utf-8-offsets.
1608    #[serde(skip_serializing_if = "Option::is_none")]
1609    #[cfg(feature = "proposed")]
1610    pub offset_encoding: Option<Vec<String>>,
1611
1612    /// Experimental client capabilities.
1613    #[serde(skip_serializing_if = "Option::is_none")]
1614    pub experimental: Option<Value>,
1615}
1616
1617#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
1618#[serde(rename_all = "camelCase")]
1619pub struct GeneralClientCapabilities {
1620    /// Client capabilities specific to regular expressions.
1621    ///
1622    /// @since 3.16.0
1623    #[serde(skip_serializing_if = "Option::is_none")]
1624    pub regular_expressions: Option<RegularExpressionsClientCapabilities>,
1625
1626    /// Client capabilities specific to the client's markdown parser.
1627    ///
1628    /// @since 3.16.0
1629    #[serde(skip_serializing_if = "Option::is_none")]
1630    pub markdown: Option<MarkdownClientCapabilities>,
1631
1632    /// Client capability that signals how the client handles stale requests (e.g. a request for
1633    /// which the client will not process the response anymore since the information is outdated).
1634    ///
1635    /// @since 3.17.0
1636    #[serde(skip_serializing_if = "Option::is_none")]
1637    pub stale_request_support: Option<StaleRequestSupportClientCapabilities>,
1638
1639    /// The position encodings supported by the client. Client and server
1640    /// have to agree on the same position encoding to ensure that offsets
1641    /// (e.g. character position in a line) are interpreted the same on both
1642    /// side.
1643    ///
1644    /// To keep the protocol backwards compatible the following applies: if
1645    /// the value 'utf-16' is missing from the array of position encodings
1646    /// servers can assume that the client supports UTF-16. UTF-16 is
1647    /// therefore a mandatory encoding.
1648    ///
1649    /// If omitted it defaults to ['utf-16'].
1650    ///
1651    /// Implementation considerations: since the conversion from one encoding
1652    /// into another requires the content of the file / line the conversion
1653    /// is best done where the file is read which is usually on the server
1654    /// side.
1655    ///
1656    /// @since 3.17.0
1657    #[serde(skip_serializing_if = "Option::is_none")]
1658    pub position_encodings: Option<Vec<PositionEncodingKind>>,
1659}
1660
1661/// Client capability that signals how the client
1662/// handles stale requests (e.g. a request
1663/// for which the client will not process the response
1664/// anymore since the information is outdated).
1665///
1666/// @since 3.17.0
1667#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
1668#[serde(rename_all = "camelCase")]
1669pub struct StaleRequestSupportClientCapabilities {
1670    /// The client will actively cancel the request.
1671    pub cancel: bool,
1672
1673    /// The list of requests for which the client
1674    /// will retry the request if it receives a
1675    /// response with error code `ContentModified``
1676    pub retry_on_content_modified: Vec<String>,
1677}
1678
1679#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
1680#[serde(rename_all = "camelCase")]
1681pub struct RegularExpressionsClientCapabilities {
1682    /// The engine's name.
1683    pub engine: String,
1684
1685    /// The engine's version
1686    #[serde(skip_serializing_if = "Option::is_none")]
1687    pub version: Option<String>,
1688}
1689
1690#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
1691#[serde(rename_all = "camelCase")]
1692pub struct MarkdownClientCapabilities {
1693    /// The name of the parser.
1694    pub parser: String,
1695
1696    /// The version of the parser.
1697    #[serde(skip_serializing_if = "Option::is_none")]
1698    pub version: Option<String>,
1699
1700    /// A list of HTML tags that the client allows / supports in
1701    /// Markdown.
1702    ///
1703    /// @since 3.17.0
1704    #[serde(skip_serializing_if = "Option::is_none")]
1705    pub allowed_tags: Option<Vec<String>>,
1706}
1707
1708#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
1709#[serde(rename_all = "camelCase")]
1710pub struct InitializeResult {
1711    /// The capabilities the language server provides.
1712    pub capabilities: ServerCapabilities,
1713
1714    /// Information about the server.
1715    #[serde(skip_serializing_if = "Option::is_none")]
1716    pub server_info: Option<ServerInfo>,
1717
1718    /// Unofficial UT8-offsets extension.
1719    ///
1720    /// See https://clangd.llvm.org/extensions.html#utf-8-offsets.
1721    #[serde(skip_serializing_if = "Option::is_none")]
1722    #[cfg(feature = "proposed")]
1723    pub offset_encoding: Option<String>,
1724}
1725
1726#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
1727pub struct ServerInfo {
1728    /// The name of the server as defined by the server.
1729    pub name: String,
1730    /// The servers's version as defined by the server.
1731    #[serde(skip_serializing_if = "Option::is_none")]
1732    pub version: Option<String>,
1733}
1734
1735#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
1736pub struct InitializeError {
1737    /// Indicates whether the client execute the following retry logic:
1738    ///
1739    /// - (1) show the message provided by the ResponseError to the user
1740    /// - (2) user selects retry or cancel
1741    /// - (3) if user selected retry the initialize method is sent again.
1742    pub retry: bool,
1743}
1744
1745// The server can signal the following capabilities:
1746
1747/// Defines how the host (editor) should sync document changes to the language server.
1748#[derive(Eq, PartialEq, Clone, Copy, Deserialize, Serialize)]
1749#[serde(transparent)]
1750pub struct TextDocumentSyncKind(i32);
1751lsp_enum! {
1752impl TextDocumentSyncKind {
1753    /// Documents should not be synced at all.
1754    pub const NONE: TextDocumentSyncKind = TextDocumentSyncKind(0);
1755
1756    /// Documents are synced by always sending the full content of the document.
1757    pub const FULL: TextDocumentSyncKind = TextDocumentSyncKind(1);
1758
1759    /// Documents are synced by sending the full content on open. After that only
1760    /// incremental updates to the document are sent.
1761    pub const INCREMENTAL: TextDocumentSyncKind = TextDocumentSyncKind(2);
1762}
1763}
1764
1765pub type ExecuteCommandClientCapabilities = DynamicRegistrationClientCapabilities;
1766
1767/// Execute command options.
1768#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
1769pub struct ExecuteCommandOptions {
1770    /// The commands to be executed on the server
1771    pub commands: Vec<String>,
1772
1773    #[serde(flatten)]
1774    pub work_done_progress_options: WorkDoneProgressOptions,
1775}
1776
1777/// Save options.
1778#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
1779#[serde(rename_all = "camelCase")]
1780pub struct SaveOptions {
1781    /// The client is supposed to include the content on save.
1782    #[serde(skip_serializing_if = "Option::is_none")]
1783    pub include_text: Option<bool>,
1784}
1785
1786#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
1787#[serde(untagged)]
1788pub enum TextDocumentSyncSaveOptions {
1789    Supported(bool),
1790    SaveOptions(SaveOptions),
1791}
1792
1793impl From<SaveOptions> for TextDocumentSyncSaveOptions {
1794    fn from(from: SaveOptions) -> Self {
1795        Self::SaveOptions(from)
1796    }
1797}
1798
1799impl From<bool> for TextDocumentSyncSaveOptions {
1800    fn from(from: bool) -> Self {
1801        Self::Supported(from)
1802    }
1803}
1804
1805#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
1806#[serde(rename_all = "camelCase")]
1807pub struct TextDocumentSyncOptions {
1808    /// Open and close notifications are sent to the server.
1809    #[serde(skip_serializing_if = "Option::is_none")]
1810    pub open_close: Option<bool>,
1811
1812    /// Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full
1813    /// and TextDocumentSyncKindIncremental.
1814    #[serde(skip_serializing_if = "Option::is_none")]
1815    pub change: Option<TextDocumentSyncKind>,
1816
1817    /// Will save notifications are sent to the server.
1818    #[serde(skip_serializing_if = "Option::is_none")]
1819    pub will_save: Option<bool>,
1820
1821    /// Will save wait until requests are sent to the server.
1822    #[serde(skip_serializing_if = "Option::is_none")]
1823    pub will_save_wait_until: Option<bool>,
1824
1825    /// Save notifications are sent to the server.
1826    #[serde(skip_serializing_if = "Option::is_none")]
1827    pub save: Option<TextDocumentSyncSaveOptions>,
1828}
1829
1830#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Deserialize, Serialize)]
1831#[serde(untagged)]
1832pub enum OneOf<A, B> {
1833    Left(A),
1834    Right(B),
1835}
1836
1837#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
1838#[serde(untagged)]
1839pub enum TextDocumentSyncCapability {
1840    Kind(TextDocumentSyncKind),
1841    Options(TextDocumentSyncOptions),
1842}
1843
1844impl From<TextDocumentSyncOptions> for TextDocumentSyncCapability {
1845    fn from(from: TextDocumentSyncOptions) -> Self {
1846        Self::Options(from)
1847    }
1848}
1849
1850impl From<TextDocumentSyncKind> for TextDocumentSyncCapability {
1851    fn from(from: TextDocumentSyncKind) -> Self {
1852        Self::Kind(from)
1853    }
1854}
1855
1856#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
1857#[serde(untagged)]
1858pub enum ImplementationProviderCapability {
1859    Simple(bool),
1860    Options(StaticTextDocumentRegistrationOptions),
1861}
1862
1863impl From<StaticTextDocumentRegistrationOptions> for ImplementationProviderCapability {
1864    fn from(from: StaticTextDocumentRegistrationOptions) -> Self {
1865        Self::Options(from)
1866    }
1867}
1868
1869impl From<bool> for ImplementationProviderCapability {
1870    fn from(from: bool) -> Self {
1871        Self::Simple(from)
1872    }
1873}
1874
1875#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
1876#[serde(untagged)]
1877pub enum TypeDefinitionProviderCapability {
1878    Simple(bool),
1879    Options(StaticTextDocumentRegistrationOptions),
1880}
1881
1882impl From<StaticTextDocumentRegistrationOptions> for TypeDefinitionProviderCapability {
1883    fn from(from: StaticTextDocumentRegistrationOptions) -> Self {
1884        Self::Options(from)
1885    }
1886}
1887
1888impl From<bool> for TypeDefinitionProviderCapability {
1889    fn from(from: bool) -> Self {
1890        Self::Simple(from)
1891    }
1892}
1893
1894#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
1895#[serde(rename_all = "camelCase")]
1896pub struct ServerCapabilities {
1897    /// The position encoding the server picked from the encodings offered
1898    /// by the client via the client capability `general.positionEncodings`.
1899    ///
1900    /// If the client didn't provide any position encodings the only valid
1901    /// value that a server can return is 'utf-16'.
1902    ///
1903    /// If omitted it defaults to 'utf-16'.
1904    ///
1905    /// @since 3.17.0
1906    #[serde(skip_serializing_if = "Option::is_none")]
1907    pub position_encoding: Option<PositionEncodingKind>,
1908
1909    /// Defines how text documents are synced.
1910    #[serde(skip_serializing_if = "Option::is_none")]
1911    pub text_document_sync: Option<TextDocumentSyncCapability>,
1912
1913    /// Capabilities specific to `textDocument/selectionRange` requests.
1914    #[serde(skip_serializing_if = "Option::is_none")]
1915    pub selection_range_provider: Option<SelectionRangeProviderCapability>,
1916
1917    /// The server provides hover support.
1918    #[serde(skip_serializing_if = "Option::is_none")]
1919    pub hover_provider: Option<HoverProviderCapability>,
1920
1921    /// The server provides completion support.
1922    #[serde(skip_serializing_if = "Option::is_none")]
1923    pub completion_provider: Option<CompletionOptions>,
1924
1925    /// The server provides signature help support.
1926    #[serde(skip_serializing_if = "Option::is_none")]
1927    pub signature_help_provider: Option<SignatureHelpOptions>,
1928
1929    /// The server provides goto definition support.
1930    #[serde(skip_serializing_if = "Option::is_none")]
1931    pub definition_provider: Option<OneOf<bool, DefinitionOptions>>,
1932
1933    /// The server provides goto type definition support.
1934    #[serde(skip_serializing_if = "Option::is_none")]
1935    pub type_definition_provider: Option<TypeDefinitionProviderCapability>,
1936
1937    /// The server provides goto implementation support.
1938    #[serde(skip_serializing_if = "Option::is_none")]
1939    pub implementation_provider: Option<ImplementationProviderCapability>,
1940
1941    /// The server provides find references support.
1942    #[serde(skip_serializing_if = "Option::is_none")]
1943    pub references_provider: Option<OneOf<bool, ReferencesOptions>>,
1944
1945    /// The server provides document highlight support.
1946    #[serde(skip_serializing_if = "Option::is_none")]
1947    pub document_highlight_provider: Option<OneOf<bool, DocumentHighlightOptions>>,
1948
1949    /// The server provides document symbol support.
1950    #[serde(skip_serializing_if = "Option::is_none")]
1951    pub document_symbol_provider: Option<OneOf<bool, DocumentSymbolOptions>>,
1952
1953    /// The server provides workspace symbol support.
1954    #[serde(skip_serializing_if = "Option::is_none")]
1955    pub workspace_symbol_provider: Option<OneOf<bool, WorkspaceSymbolOptions>>,
1956
1957    /// The server provides code actions.
1958    #[serde(skip_serializing_if = "Option::is_none")]
1959    pub code_action_provider: Option<CodeActionProviderCapability>,
1960
1961    /// The server provides code lens.
1962    #[serde(skip_serializing_if = "Option::is_none")]
1963    pub code_lens_provider: Option<CodeLensOptions>,
1964
1965    /// The server provides document formatting.
1966    #[serde(skip_serializing_if = "Option::is_none")]
1967    pub document_formatting_provider: Option<OneOf<bool, DocumentFormattingOptions>>,
1968
1969    /// The server provides document range formatting.
1970    #[serde(skip_serializing_if = "Option::is_none")]
1971    pub document_range_formatting_provider: Option<OneOf<bool, DocumentRangeFormattingOptions>>,
1972
1973    /// The server provides document formatting on typing.
1974    #[serde(skip_serializing_if = "Option::is_none")]
1975    pub document_on_type_formatting_provider: Option<DocumentOnTypeFormattingOptions>,
1976
1977    /// The server provides rename support.
1978    #[serde(skip_serializing_if = "Option::is_none")]
1979    pub rename_provider: Option<OneOf<bool, RenameOptions>>,
1980
1981    /// The server provides document link support.
1982    #[serde(skip_serializing_if = "Option::is_none")]
1983    pub document_link_provider: Option<DocumentLinkOptions>,
1984
1985    /// The server provides color provider support.
1986    #[serde(skip_serializing_if = "Option::is_none")]
1987    pub color_provider: Option<ColorProviderCapability>,
1988
1989    /// The server provides folding provider support.
1990    #[serde(skip_serializing_if = "Option::is_none")]
1991    pub folding_range_provider: Option<FoldingRangeProviderCapability>,
1992
1993    /// The server provides go to declaration support.
1994    #[serde(skip_serializing_if = "Option::is_none")]
1995    pub declaration_provider: Option<DeclarationCapability>,
1996
1997    /// The server provides execute command support.
1998    #[serde(skip_serializing_if = "Option::is_none")]
1999    pub execute_command_provider: Option<ExecuteCommandOptions>,
2000
2001    /// Workspace specific server capabilities
2002    #[serde(skip_serializing_if = "Option::is_none")]
2003    pub workspace: Option<WorkspaceServerCapabilities>,
2004
2005    /// Call hierarchy provider capabilities.
2006    #[serde(skip_serializing_if = "Option::is_none")]
2007    pub call_hierarchy_provider: Option<CallHierarchyServerCapability>,
2008
2009    /// Semantic tokens server capabilities.
2010    #[serde(skip_serializing_if = "Option::is_none")]
2011    pub semantic_tokens_provider: Option<SemanticTokensServerCapabilities>,
2012
2013    /// Whether server provides moniker support.
2014    #[serde(skip_serializing_if = "Option::is_none")]
2015    pub moniker_provider: Option<OneOf<bool, MonikerServerCapabilities>>,
2016
2017    /// The server provides linked editing range support.
2018    ///
2019    /// @since 3.16.0
2020    #[serde(skip_serializing_if = "Option::is_none")]
2021    pub linked_editing_range_provider: Option<LinkedEditingRangeServerCapabilities>,
2022
2023    /// The server provides inline values.
2024    ///
2025    /// @since 3.17.0
2026    #[serde(skip_serializing_if = "Option::is_none")]
2027    pub inline_value_provider: Option<OneOf<bool, InlineValueServerCapabilities>>,
2028
2029    /// The server provides inlay hints.
2030    ///
2031    /// @since 3.17.0
2032    #[serde(skip_serializing_if = "Option::is_none")]
2033    pub inlay_hint_provider: Option<OneOf<bool, InlayHintServerCapabilities>>,
2034
2035    /// The server has support for pull model diagnostics.
2036    ///
2037    /// @since 3.17.0
2038    #[serde(skip_serializing_if = "Option::is_none")]
2039    pub diagnostic_provider: Option<DiagnosticServerCapabilities>,
2040
2041    /// Experimental server capabilities.
2042    #[serde(skip_serializing_if = "Option::is_none")]
2043    pub experimental: Option<Value>,
2044}
2045
2046#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
2047#[serde(rename_all = "camelCase")]
2048pub struct WorkspaceServerCapabilities {
2049    /// The server supports workspace folder.
2050    #[serde(skip_serializing_if = "Option::is_none")]
2051    pub workspace_folders: Option<WorkspaceFoldersServerCapabilities>,
2052
2053    #[serde(skip_serializing_if = "Option::is_none")]
2054    pub file_operations: Option<WorkspaceFileOperationsServerCapabilities>,
2055}
2056
2057/// General parameters to to register for a capability.
2058#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
2059#[serde(rename_all = "camelCase")]
2060pub struct Registration {
2061    /// The id used to register the request. The id can be used to deregister
2062    /// the request again.
2063    pub id: String,
2064
2065    /// The method / capability to register for.
2066    pub method: String,
2067
2068    /// Options necessary for the registration.
2069    #[serde(skip_serializing_if = "Option::is_none")]
2070    pub register_options: Option<Value>,
2071}
2072
2073#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
2074pub struct RegistrationParams {
2075    pub registrations: Vec<Registration>,
2076}
2077
2078/// Since most of the registration options require to specify a document selector there is a base
2079/// interface that can be used.
2080#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
2081#[serde(rename_all = "camelCase")]
2082pub struct TextDocumentRegistrationOptions {
2083    /// A document selector to identify the scope of the registration. If set to null
2084    /// the document selector provided on the client side will be used.
2085    pub document_selector: Option<DocumentSelector>,
2086}
2087
2088#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2089#[serde(untagged)]
2090pub enum DeclarationCapability {
2091    Simple(bool),
2092    RegistrationOptions(DeclarationRegistrationOptions),
2093    Options(DeclarationOptions),
2094}
2095
2096#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2097#[serde(rename_all = "camelCase")]
2098pub struct DeclarationRegistrationOptions {
2099    #[serde(flatten)]
2100    pub declaration_options: DeclarationOptions,
2101
2102    #[serde(flatten)]
2103    pub text_document_registration_options: TextDocumentRegistrationOptions,
2104
2105    #[serde(flatten)]
2106    pub static_registration_options: StaticRegistrationOptions,
2107}
2108
2109#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2110#[serde(rename_all = "camelCase")]
2111pub struct DeclarationOptions {
2112    #[serde(flatten)]
2113    pub work_done_progress_options: WorkDoneProgressOptions,
2114}
2115
2116#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
2117#[serde(rename_all = "camelCase")]
2118pub struct StaticRegistrationOptions {
2119    #[serde(skip_serializing_if = "Option::is_none")]
2120    pub id: Option<String>,
2121}
2122
2123#[derive(Debug, Default, Eq, PartialEq, Clone, Deserialize, Serialize, Copy)]
2124#[serde(rename_all = "camelCase")]
2125pub struct WorkDoneProgressOptions {
2126    #[serde(skip_serializing_if = "Option::is_none")]
2127    pub work_done_progress: Option<bool>,
2128}
2129
2130#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
2131#[serde(rename_all = "camelCase")]
2132pub struct DocumentFormattingOptions {
2133    #[serde(flatten)]
2134    pub work_done_progress_options: WorkDoneProgressOptions,
2135}
2136
2137#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2138#[serde(rename_all = "camelCase")]
2139pub struct DocumentRangeFormattingOptions {
2140    #[serde(flatten)]
2141    pub work_done_progress_options: WorkDoneProgressOptions,
2142}
2143
2144#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2145#[serde(rename_all = "camelCase")]
2146pub struct DefinitionOptions {
2147    #[serde(flatten)]
2148    pub work_done_progress_options: WorkDoneProgressOptions,
2149}
2150
2151#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2152#[serde(rename_all = "camelCase")]
2153pub struct DocumentSymbolOptions {
2154    /// A human-readable string that is shown when multiple outlines trees are
2155    /// shown for the same document.
2156    ///
2157    /// @since 3.16.0
2158    #[serde(skip_serializing_if = "Option::is_none")]
2159    pub label: Option<String>,
2160
2161    #[serde(flatten)]
2162    pub work_done_progress_options: WorkDoneProgressOptions,
2163}
2164
2165#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2166#[serde(rename_all = "camelCase")]
2167pub struct ReferencesOptions {
2168    #[serde(flatten)]
2169    pub work_done_progress_options: WorkDoneProgressOptions,
2170}
2171
2172#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2173#[serde(rename_all = "camelCase")]
2174pub struct DocumentHighlightOptions {
2175    #[serde(flatten)]
2176    pub work_done_progress_options: WorkDoneProgressOptions,
2177}
2178
2179#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2180#[serde(rename_all = "camelCase")]
2181pub struct WorkspaceSymbolOptions {
2182    #[serde(flatten)]
2183    pub work_done_progress_options: WorkDoneProgressOptions,
2184
2185    /// The server provides support to resolve additional
2186    /// information for a workspace symbol.
2187    ///
2188    /// @since 3.17.0
2189    #[serde(skip_serializing_if = "Option::is_none")]
2190    pub resolve_provider: Option<bool>,
2191}
2192
2193#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2194#[serde(rename_all = "camelCase")]
2195pub struct StaticTextDocumentRegistrationOptions {
2196    /// A document selector to identify the scope of the registration. If set to null
2197    /// the document selector provided on the client side will be used.
2198    pub document_selector: Option<DocumentSelector>,
2199
2200    #[serde(skip_serializing_if = "Option::is_none")]
2201    pub id: Option<String>,
2202}
2203
2204/// General parameters to unregister a capability.
2205#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2206pub struct Unregistration {
2207    /// The id used to unregister the request or notification. Usually an id
2208    /// provided during the register request.
2209    pub id: String,
2210
2211    /// The method / capability to unregister for.
2212    pub method: String,
2213}
2214
2215#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2216pub struct UnregistrationParams {
2217    pub unregisterations: Vec<Unregistration>,
2218}
2219
2220#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
2221pub struct DidChangeConfigurationParams {
2222    /// The actual changed settings
2223    pub settings: Value,
2224}
2225
2226#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2227#[serde(rename_all = "camelCase")]
2228pub struct DidOpenTextDocumentParams {
2229    /// The document that was opened.
2230    pub text_document: TextDocumentItem,
2231}
2232
2233#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2234#[serde(rename_all = "camelCase")]
2235pub struct DidChangeTextDocumentParams {
2236    /// The document that did change. The version number points
2237    /// to the version after all provided content changes have
2238    /// been applied.
2239    pub text_document: VersionedTextDocumentIdentifier,
2240    /// The actual content changes.
2241    pub content_changes: Vec<TextDocumentContentChangeEvent>,
2242}
2243
2244/// An event describing a change to a text document. If range and rangeLength are omitted
2245/// the new text is considered to be the full content of the document.
2246#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2247#[serde(rename_all = "camelCase")]
2248pub struct TextDocumentContentChangeEvent {
2249    /// The range of the document that changed.
2250    #[serde(skip_serializing_if = "Option::is_none")]
2251    pub range: Option<Range>,
2252
2253    /// The length of the range that got replaced.
2254    ///
2255    /// Deprecated: Use range instead
2256    #[serde(skip_serializing_if = "Option::is_none")]
2257    pub range_length: Option<u32>,
2258
2259    /// The new text of the document.
2260    pub text: String,
2261}
2262
2263/// Describe options to be used when registering for text document change events.
2264///
2265/// Extends TextDocumentRegistrationOptions
2266#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2267#[serde(rename_all = "camelCase")]
2268pub struct TextDocumentChangeRegistrationOptions {
2269    /// A document selector to identify the scope of the registration. If set to null
2270    /// the document selector provided on the client side will be used.
2271    pub document_selector: Option<DocumentSelector>,
2272
2273    /// How documents are synced to the server. See TextDocumentSyncKind.Full
2274    /// and TextDocumentSyncKindIncremental.
2275    pub sync_kind: i32,
2276}
2277
2278/// The parameters send in a will save text document notification.
2279#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2280#[serde(rename_all = "camelCase")]
2281pub struct WillSaveTextDocumentParams {
2282    /// The document that will be saved.
2283    pub text_document: TextDocumentIdentifier,
2284
2285    /// The 'TextDocumentSaveReason'.
2286    pub reason: TextDocumentSaveReason,
2287}
2288
2289/// Represents reasons why a text document is saved.
2290#[derive(Copy, Eq, PartialEq, Clone, Deserialize, Serialize)]
2291#[serde(transparent)]
2292pub struct TextDocumentSaveReason(i32);
2293lsp_enum! {
2294impl TextDocumentSaveReason {
2295    /// Manually triggered, e.g. by the user pressing save, by starting debugging,
2296    /// or by an API call.
2297    pub const MANUAL: TextDocumentSaveReason = TextDocumentSaveReason(1);
2298
2299    /// Automatic after a delay.
2300    pub const AFTER_DELAY: TextDocumentSaveReason = TextDocumentSaveReason(2);
2301
2302    /// When the editor lost focus.
2303    pub const FOCUS_OUT: TextDocumentSaveReason = TextDocumentSaveReason(3);
2304}
2305}
2306
2307#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2308#[serde(rename_all = "camelCase")]
2309pub struct DidCloseTextDocumentParams {
2310    /// The document that was closed.
2311    pub text_document: TextDocumentIdentifier,
2312}
2313
2314#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2315#[serde(rename_all = "camelCase")]
2316pub struct DidSaveTextDocumentParams {
2317    /// The document that was saved.
2318    pub text_document: TextDocumentIdentifier,
2319
2320    /// Optional the content when saved. Depends on the includeText value
2321    /// when the save notification was requested.
2322    #[serde(skip_serializing_if = "Option::is_none")]
2323    pub text: Option<String>,
2324}
2325
2326#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2327#[serde(rename_all = "camelCase")]
2328pub struct TextDocumentSaveRegistrationOptions {
2329    /// The client is supposed to include the content on save.
2330    #[serde(skip_serializing_if = "Option::is_none")]
2331    pub include_text: Option<bool>,
2332
2333    #[serde(flatten)]
2334    pub text_document_registration_options: TextDocumentRegistrationOptions,
2335}
2336
2337#[derive(Debug, Eq, PartialEq, Clone, Copy, Default, Deserialize, Serialize)]
2338#[serde(rename_all = "camelCase")]
2339pub struct DidChangeWatchedFilesClientCapabilities {
2340    /// Did change watched files notification supports dynamic registration.
2341    /// Please note that the current protocol doesn't support static
2342    /// configuration for file changes from the server side.
2343    #[serde(skip_serializing_if = "Option::is_none")]
2344    pub dynamic_registration: Option<bool>,
2345
2346    /// Whether the client has support for relative patterns
2347    /// or not.
2348    ///
2349    /// @since 3.17.0
2350    #[serde(skip_serializing_if = "Option::is_none")]
2351    pub relative_pattern_support: Option<bool>,
2352}
2353
2354#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2355pub struct DidChangeWatchedFilesParams {
2356    /// The actual file events.
2357    pub changes: Vec<FileEvent>,
2358}
2359
2360/// The file event type.
2361#[derive(Eq, PartialEq, Hash, Copy, Clone, Deserialize, Serialize)]
2362#[serde(transparent)]
2363pub struct FileChangeType(i32);
2364lsp_enum! {
2365impl FileChangeType {
2366    /// The file got created.
2367    pub const CREATED: FileChangeType = FileChangeType(1);
2368
2369    /// The file got changed.
2370    pub const CHANGED: FileChangeType = FileChangeType(2);
2371
2372    /// The file got deleted.
2373    pub const DELETED: FileChangeType = FileChangeType(3);
2374}
2375}
2376
2377/// An event describing a file change.
2378#[derive(Debug, Eq, Hash, PartialEq, Clone, Deserialize, Serialize)]
2379pub struct FileEvent {
2380    /// The file's URI.
2381    pub uri: Url,
2382
2383    /// The change type.
2384    #[serde(rename = "type")]
2385    pub typ: FileChangeType,
2386}
2387
2388impl FileEvent {
2389    pub fn new(uri: Url, typ: FileChangeType) -> FileEvent {
2390        FileEvent { uri, typ }
2391    }
2392}
2393
2394/// Describe options to be used when registered for text document change events.
2395#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Deserialize, Serialize)]
2396pub struct DidChangeWatchedFilesRegistrationOptions {
2397    /// The watchers to register.
2398    pub watchers: Vec<FileSystemWatcher>,
2399}
2400
2401#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Deserialize, Serialize)]
2402#[serde(rename_all = "camelCase")]
2403pub struct FileSystemWatcher {
2404    /// The glob pattern to watch. See {@link GlobPattern glob pattern}
2405    /// for more detail.
2406    ///
2407    /// @since 3.17.0 support for relative patterns.
2408    pub glob_pattern: GlobPattern,
2409
2410    /// The kind of events of interest. If omitted it defaults to WatchKind.Create |
2411    /// WatchKind.Change | WatchKind.Delete which is 7.
2412    #[serde(skip_serializing_if = "Option::is_none")]
2413    pub kind: Option<WatchKind>,
2414}
2415
2416/// The glob pattern. Either a string pattern or a relative pattern.
2417///
2418/// @since 3.17.0
2419#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Deserialize, Serialize)]
2420#[serde(untagged)]
2421pub enum GlobPattern {
2422    String(Pattern),
2423    Relative(RelativePattern),
2424}
2425
2426impl From<Pattern> for GlobPattern {
2427    #[inline]
2428    fn from(from: Pattern) -> Self {
2429        Self::String(from)
2430    }
2431}
2432
2433impl From<RelativePattern> for GlobPattern {
2434    #[inline]
2435    fn from(from: RelativePattern) -> Self {
2436        Self::Relative(from)
2437    }
2438}
2439
2440/// A relative pattern is a helper to construct glob patterns that are matched
2441/// relatively to a base URI. The common value for a `baseUri` is a workspace
2442/// folder root, but it can be another absolute URI as well.
2443///
2444/// @since 3.17.0
2445#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Deserialize, Serialize)]
2446#[serde(rename_all = "camelCase")]
2447pub struct RelativePattern {
2448    /// A workspace folder or a base URI to which this pattern will be matched
2449    /// against relatively.
2450    pub base_uri: OneOf<WorkspaceFolder, Url>,
2451
2452    /// The actual glob pattern.
2453    pub pattern: Pattern,
2454}
2455
2456/// The glob pattern to watch relative to the base path. Glob patterns can have
2457/// the following syntax:
2458/// - `*` to match one or more characters in a path segment
2459/// - `?` to match on one character in a path segment
2460/// - `**` to match any number of path segments, including none
2461/// - `{}` to group conditions (e.g. `**​/*.{ts,js}` matches all TypeScript
2462///   and JavaScript files)
2463/// - `[]` to declare a range of characters to match in a path segment
2464///   (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)
2465/// - `[!...]` to negate a range of characters to match in a path segment
2466///   (e.g., `example.[!0-9]` to match on `example.a`, `example.b`,
2467///   but not `example.0`)
2468///
2469/// @since 3.17.0
2470pub type Pattern = String;
2471
2472bitflags! {
2473pub struct WatchKind: u8 {
2474    /// Interested in create events.
2475    const Create = 1;
2476    /// Interested in change events
2477    const Change = 2;
2478    /// Interested in delete events
2479    const Delete = 4;
2480}
2481}
2482
2483impl<'de> serde::Deserialize<'de> for WatchKind {
2484    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2485    where
2486        D: serde::Deserializer<'de>,
2487    {
2488        let i = u8::deserialize(deserializer)?;
2489        WatchKind::from_bits(i).ok_or_else(|| {
2490            D::Error::invalid_value(de::Unexpected::Unsigned(u64::from(i)), &"Unknown flag")
2491        })
2492    }
2493}
2494
2495impl serde::Serialize for WatchKind {
2496    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2497    where
2498        S: serde::Serializer,
2499    {
2500        serializer.serialize_u8(self.bits())
2501    }
2502}
2503
2504#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2505pub struct PublishDiagnosticsParams {
2506    /// The URI for which diagnostic information is reported.
2507    pub uri: Url,
2508
2509    /// An array of diagnostic information items.
2510    pub diagnostics: Vec<Diagnostic>,
2511
2512    /// Optional the version number of the document the diagnostics are published for.
2513    #[serde(skip_serializing_if = "Option::is_none")]
2514    pub version: Option<i32>,
2515}
2516
2517impl PublishDiagnosticsParams {
2518    pub fn new(
2519        uri: Url,
2520        diagnostics: Vec<Diagnostic>,
2521        version: Option<i32>,
2522    ) -> PublishDiagnosticsParams {
2523        PublishDiagnosticsParams {
2524            uri,
2525            diagnostics,
2526            version,
2527        }
2528    }
2529}
2530
2531#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Clone)]
2532#[serde(untagged)]
2533pub enum Documentation {
2534    String(String),
2535    MarkupContent(MarkupContent),
2536}
2537
2538/// MarkedString can be used to render human readable text. It is either a
2539/// markdown string or a code-block that provides a language and a code snippet.
2540/// The language identifier is semantically equal to the optional language
2541/// identifier in fenced code blocks in GitHub issues.
2542///
2543/// The pair of a language and a value is an equivalent to markdown:
2544///
2545/// ```${language}
2546/// ${value}
2547/// ```
2548#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2549#[serde(untagged)]
2550pub enum MarkedString {
2551    String(String),
2552    LanguageString(LanguageString),
2553}
2554
2555#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2556pub struct LanguageString {
2557    pub language: String,
2558    pub value: String,
2559}
2560
2561impl MarkedString {
2562    pub fn from_markdown(markdown: String) -> MarkedString {
2563        MarkedString::String(markdown)
2564    }
2565
2566    pub fn from_language_code(language: String, code_block: String) -> MarkedString {
2567        MarkedString::LanguageString(LanguageString {
2568            language,
2569            value: code_block,
2570        })
2571    }
2572}
2573
2574#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2575#[serde(rename_all = "camelCase")]
2576pub struct GotoDefinitionParams {
2577    #[serde(flatten)]
2578    pub text_document_position_params: TextDocumentPositionParams,
2579
2580    #[serde(flatten)]
2581    pub work_done_progress_params: WorkDoneProgressParams,
2582
2583    #[serde(flatten)]
2584    pub partial_result_params: PartialResultParams,
2585}
2586
2587/// GotoDefinition response can be single location, or multiple Locations or a link.
2588#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
2589#[serde(untagged)]
2590pub enum GotoDefinitionResponse {
2591    Scalar(Location),
2592    Array(Vec<Location>),
2593    Link(Vec<LocationLink>),
2594}
2595
2596impl From<Location> for GotoDefinitionResponse {
2597    fn from(location: Location) -> Self {
2598        GotoDefinitionResponse::Scalar(location)
2599    }
2600}
2601
2602impl From<Vec<Location>> for GotoDefinitionResponse {
2603    fn from(locations: Vec<Location>) -> Self {
2604        GotoDefinitionResponse::Array(locations)
2605    }
2606}
2607
2608impl From<Vec<LocationLink>> for GotoDefinitionResponse {
2609    fn from(locations: Vec<LocationLink>) -> Self {
2610        GotoDefinitionResponse::Link(locations)
2611    }
2612}
2613
2614#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
2615pub struct ExecuteCommandParams {
2616    /// The identifier of the actual command handler.
2617    pub command: String,
2618    /// Arguments that the command should be invoked with.
2619    #[serde(default)]
2620    pub arguments: Vec<Value>,
2621
2622    #[serde(flatten)]
2623    pub work_done_progress_params: WorkDoneProgressParams,
2624}
2625
2626/// Execute command registration options.
2627#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2628pub struct ExecuteCommandRegistrationOptions {
2629    /// The commands to be executed on the server
2630    pub commands: Vec<String>,
2631
2632    #[serde(flatten)]
2633    pub execute_command_options: ExecuteCommandOptions,
2634}
2635
2636#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2637#[serde(rename_all = "camelCase")]
2638pub struct ApplyWorkspaceEditParams {
2639    /// An optional label of the workspace edit. This label is
2640    /// presented in the user interface for example on an undo
2641    /// stack to undo the workspace edit.
2642    #[serde(skip_serializing_if = "Option::is_none")]
2643    pub label: Option<String>,
2644
2645    /// The edits to apply.
2646    pub edit: WorkspaceEdit,
2647}
2648
2649#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
2650#[serde(rename_all = "camelCase")]
2651pub struct ApplyWorkspaceEditResponse {
2652    /// Indicates whether the edit was applied or not.
2653    pub applied: bool,
2654
2655    /// An optional textual description for why the edit was not applied.
2656    /// This may be used may be used by the server for diagnostic
2657    /// logging or to provide a suitable error for a request that
2658    /// triggered the edit
2659    #[serde(skip_serializing_if = "Option::is_none")]
2660    pub failure_reason: Option<String>,
2661
2662    /// Depending on the client's failure handling strategy `failedChange` might
2663    /// contain the index of the change that failed. This property is only available
2664    /// if the client signals a `failureHandlingStrategy` in its client capabilities.
2665    #[serde(skip_serializing_if = "Option::is_none")]
2666    pub failed_change: Option<u32>,
2667}
2668
2669/// Describes the content type that a client supports in various
2670/// result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
2671///
2672/// Please note that `MarkupKinds` must not start with a `$`. This kinds
2673/// are reserved for internal usage.
2674#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Clone)]
2675#[serde(rename_all = "lowercase")]
2676pub enum MarkupKind {
2677    /// Plain text is supported as a content format
2678    PlainText,
2679    /// Markdown is supported as a content format
2680    Markdown,
2681}
2682
2683/// A `MarkupContent` literal represents a string value which content can be represented in different formats.
2684/// Currently `plaintext` and `markdown` are supported formats. A `MarkupContent` is usually used in
2685/// documentation properties of result literals like `CompletionItem` or `SignatureInformation`.
2686/// If the format is `markdown` the content should follow the [GitHub Flavored Markdown Specification](https://github.github.com/gfm/).
2687///
2688/// Here is an example how such a string can be constructed using JavaScript / TypeScript:
2689///
2690/// ```ignore
2691/// let markdown: MarkupContent = {
2692///     kind: MarkupKind::Markdown,
2693///     value: [
2694///         "# Header",
2695///         "Some text",
2696///         "```typescript",
2697///         "someCode();",
2698///         "```"
2699///     ]
2700///     .join("\n"),
2701/// };
2702/// ```
2703///
2704/// Please *Note* that clients might sanitize the return markdown. A client could decide to
2705/// remove HTML from the markdown to avoid script execution.
2706#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Clone)]
2707pub struct MarkupContent {
2708    pub kind: MarkupKind,
2709    pub value: String,
2710}
2711
2712/// A parameter literal used to pass a partial result token.
2713#[derive(Debug, Eq, PartialEq, Default, Deserialize, Serialize, Clone)]
2714#[serde(rename_all = "camelCase")]
2715pub struct PartialResultParams {
2716    #[serde(skip_serializing_if = "Option::is_none")]
2717    pub partial_result_token: Option<ProgressToken>,
2718}
2719
2720/// Symbol tags are extra annotations that tweak the rendering of a symbol.
2721///
2722/// @since 3.16.0
2723#[derive(Eq, PartialEq, Clone, Deserialize, Serialize)]
2724#[serde(transparent)]
2725pub struct SymbolTag(i32);
2726lsp_enum! {
2727impl SymbolTag {
2728    /// Render a symbol as obsolete, usually using a strike-out.
2729    pub const DEPRECATED: SymbolTag = SymbolTag(1);
2730}
2731}
2732
2733#[cfg(test)]
2734mod tests {
2735    use serde::{Deserialize, Serialize};
2736
2737    use super::*;
2738
2739    pub(crate) fn test_serialization<SER>(ms: &SER, expected: &str)
2740    where
2741        SER: Serialize + for<'de> Deserialize<'de> + PartialEq + std::fmt::Debug,
2742    {
2743        let json_str = serde_json::to_string(ms).unwrap();
2744        assert_eq!(&json_str, expected);
2745        let deserialized: SER = serde_json::from_str(&json_str).unwrap();
2746        assert_eq!(&deserialized, ms);
2747    }
2748
2749    pub(crate) fn test_deserialization<T>(json: &str, expected: &T)
2750    where
2751        T: for<'de> Deserialize<'de> + PartialEq + std::fmt::Debug,
2752    {
2753        let value = serde_json::from_str::<T>(json).unwrap();
2754        assert_eq!(&value, expected);
2755    }
2756
2757    #[test]
2758    fn one_of() {
2759        test_serialization(&OneOf::<bool, ()>::Left(true), r#"true"#);
2760        test_serialization(&OneOf::<String, ()>::Left("abcd".into()), r#""abcd""#);
2761        test_serialization(
2762            &OneOf::<String, WorkDoneProgressOptions>::Right(WorkDoneProgressOptions {
2763                work_done_progress: Some(false),
2764            }),
2765            r#"{"workDoneProgress":false}"#,
2766        );
2767    }
2768
2769    #[test]
2770    fn number_or_string() {
2771        test_serialization(&NumberOrString::Number(123), r#"123"#);
2772
2773        test_serialization(&NumberOrString::String("abcd".into()), r#""abcd""#);
2774    }
2775
2776    #[test]
2777    fn marked_string() {
2778        test_serialization(&MarkedString::from_markdown("xxx".into()), r#""xxx""#);
2779
2780        test_serialization(
2781            &MarkedString::from_language_code("lang".into(), "code".into()),
2782            r#"{"language":"lang","value":"code"}"#,
2783        );
2784    }
2785
2786    #[test]
2787    fn language_string() {
2788        test_serialization(
2789            &LanguageString {
2790                language: "LL".into(),
2791                value: "VV".into(),
2792            },
2793            r#"{"language":"LL","value":"VV"}"#,
2794        );
2795    }
2796
2797    #[test]
2798    fn workspace_edit() {
2799        test_serialization(
2800            &WorkspaceEdit {
2801                changes: Some(vec![].into_iter().collect()),
2802                document_changes: None,
2803                ..Default::default()
2804            },
2805            r#"{"changes":{}}"#,
2806        );
2807
2808        test_serialization(
2809            &WorkspaceEdit {
2810                changes: None,
2811                document_changes: None,
2812                ..Default::default()
2813            },
2814            r#"{}"#,
2815        );
2816
2817        test_serialization(
2818            &WorkspaceEdit {
2819                changes: Some(
2820                    vec![(Url::parse("file://test").unwrap(), vec![])]
2821                        .into_iter()
2822                        .collect(),
2823                ),
2824                document_changes: None,
2825                ..Default::default()
2826            },
2827            r#"{"changes":{"file://test/":[]}}"#,
2828        );
2829    }
2830
2831    #[test]
2832    fn root_uri_can_be_missing() {
2833        serde_json::from_str::<InitializeParams>(r#"{ "capabilities": {} }"#).unwrap();
2834    }
2835
2836    #[test]
2837    fn test_watch_kind() {
2838        test_serialization(&WatchKind::Create, "1");
2839        test_serialization(&(WatchKind::Create | WatchKind::Change), "3");
2840        test_serialization(
2841            &(WatchKind::Create | WatchKind::Change | WatchKind::Delete),
2842            "7",
2843        );
2844    }
2845
2846    #[test]
2847    fn test_resource_operation_kind() {
2848        test_serialization(
2849            &vec![
2850                ResourceOperationKind::Create,
2851                ResourceOperationKind::Rename,
2852                ResourceOperationKind::Delete,
2853            ],
2854            r#"["create","rename","delete"]"#,
2855        );
2856    }
2857}