Skip to main content

lsp_types_max/
semantic_tokens.rs

1use std::borrow::Cow;
2
3use serde::ser::SerializeSeq;
4use serde::{Deserialize, Serialize};
5
6use crate::{
7    PartialResultParams, Range, StaticRegistrationOptions, TextDocumentIdentifier,
8    TextDocumentRegistrationOptions, WorkDoneProgressOptions, WorkDoneProgressParams,
9};
10/// A set of predefined token types. This set is not fixed
11/// and clients can specify additional token types via the
12/// corresponding client capabilities.
13///
14/// @since 3.16.0
15#[derive(Debug, Eq, PartialEq, Hash, PartialOrd, Clone, Deserialize, Serialize)]
16#[serde(untagged)]
17pub enum SemanticTokenType {
18    Known(SemanticTokenTypeEnum),
19    Custom(Cow<'static, str>),
20}
21
22#[derive(Debug, Eq, PartialEq, Hash, PartialOrd, Clone, Deserialize, Serialize)]
23#[serde(rename_all = "camelCase")]
24pub enum SemanticTokenTypeEnum {
25    Namespace,
26    Type,
27    Class,
28    Enum,
29    Interface,
30    Struct,
31    TypeParameter,
32    Parameter,
33    Variable,
34    Property,
35    EnumMember,
36    Event,
37    Function,
38    Method,
39    Macro,
40    Keyword,
41    Modifier,
42    Comment,
43    String,
44    Number,
45    Regexp,
46    Operator,
47    Decorator,
48    Label,
49}
50
51impl SemanticTokenType {
52    pub const NAMESPACE: SemanticTokenType =
53        SemanticTokenType::Known(SemanticTokenTypeEnum::Namespace);
54    pub const TYPE: SemanticTokenType = SemanticTokenType::Known(SemanticTokenTypeEnum::Type);
55    pub const CLASS: SemanticTokenType = SemanticTokenType::Known(SemanticTokenTypeEnum::Class);
56    pub const ENUM: SemanticTokenType = SemanticTokenType::Known(SemanticTokenTypeEnum::Enum);
57    pub const INTERFACE: SemanticTokenType =
58        SemanticTokenType::Known(SemanticTokenTypeEnum::Interface);
59    pub const STRUCT: SemanticTokenType = SemanticTokenType::Known(SemanticTokenTypeEnum::Struct);
60    pub const TYPE_PARAMETER: SemanticTokenType =
61        SemanticTokenType::Known(SemanticTokenTypeEnum::TypeParameter);
62    pub const PARAMETER: SemanticTokenType =
63        SemanticTokenType::Known(SemanticTokenTypeEnum::Parameter);
64    pub const VARIABLE: SemanticTokenType =
65        SemanticTokenType::Known(SemanticTokenTypeEnum::Variable);
66    pub const PROPERTY: SemanticTokenType =
67        SemanticTokenType::Known(SemanticTokenTypeEnum::Property);
68    pub const ENUM_MEMBER: SemanticTokenType =
69        SemanticTokenType::Known(SemanticTokenTypeEnum::EnumMember);
70    pub const EVENT: SemanticTokenType = SemanticTokenType::Known(SemanticTokenTypeEnum::Event);
71    pub const FUNCTION: SemanticTokenType =
72        SemanticTokenType::Known(SemanticTokenTypeEnum::Function);
73    pub const METHOD: SemanticTokenType = SemanticTokenType::Known(SemanticTokenTypeEnum::Method);
74    pub const MACRO: SemanticTokenType = SemanticTokenType::Known(SemanticTokenTypeEnum::Macro);
75    pub const KEYWORD: SemanticTokenType = SemanticTokenType::Known(SemanticTokenTypeEnum::Keyword);
76    pub const MODIFIER: SemanticTokenType =
77        SemanticTokenType::Known(SemanticTokenTypeEnum::Modifier);
78    pub const COMMENT: SemanticTokenType = SemanticTokenType::Known(SemanticTokenTypeEnum::Comment);
79    pub const STRING: SemanticTokenType = SemanticTokenType::Known(SemanticTokenTypeEnum::String);
80    pub const NUMBER: SemanticTokenType = SemanticTokenType::Known(SemanticTokenTypeEnum::Number);
81    pub const REGEXP: SemanticTokenType = SemanticTokenType::Known(SemanticTokenTypeEnum::Regexp);
82    pub const OPERATOR: SemanticTokenType =
83        SemanticTokenType::Known(SemanticTokenTypeEnum::Operator);
84
85    /// @since 3.17.0
86    pub const DECORATOR: SemanticTokenType =
87        SemanticTokenType::Known(SemanticTokenTypeEnum::Decorator);
88
89    /// @since 3.18.0
90    pub const LABEL: SemanticTokenType = SemanticTokenType::Known(SemanticTokenTypeEnum::Label);
91
92    pub const fn new(tag: &'static str) -> Self {
93        SemanticTokenType::Custom(Cow::Borrowed(tag))
94    }
95
96    pub fn as_str(&self) -> &str {
97        match self {
98            Self::Known(k) => match k {
99                SemanticTokenTypeEnum::Namespace => "namespace",
100                SemanticTokenTypeEnum::Type => "type",
101                SemanticTokenTypeEnum::Class => "class",
102                SemanticTokenTypeEnum::Enum => "enum",
103                SemanticTokenTypeEnum::Interface => "interface",
104                SemanticTokenTypeEnum::Struct => "struct",
105                SemanticTokenTypeEnum::TypeParameter => "typeParameter",
106                SemanticTokenTypeEnum::Parameter => "parameter",
107                SemanticTokenTypeEnum::Variable => "variable",
108                SemanticTokenTypeEnum::Property => "property",
109                SemanticTokenTypeEnum::EnumMember => "enumMember",
110                SemanticTokenTypeEnum::Event => "event",
111                SemanticTokenTypeEnum::Function => "function",
112                SemanticTokenTypeEnum::Method => "method",
113                SemanticTokenTypeEnum::Macro => "macro",
114                SemanticTokenTypeEnum::Keyword => "keyword",
115                SemanticTokenTypeEnum::Modifier => "modifier",
116                SemanticTokenTypeEnum::Comment => "comment",
117                SemanticTokenTypeEnum::String => "string",
118                SemanticTokenTypeEnum::Number => "number",
119                SemanticTokenTypeEnum::Regexp => "regexp",
120                SemanticTokenTypeEnum::Operator => "operator",
121                SemanticTokenTypeEnum::Decorator => "decorator",
122                SemanticTokenTypeEnum::Label => "label",
123            },
124            Self::Custom(c) => c.as_ref(),
125        }
126    }
127}
128
129impl From<String> for SemanticTokenType {
130    fn from(from: String) -> Self {
131        SemanticTokenType::Custom(Cow::from(from))
132    }
133}
134
135impl From<&'static str> for SemanticTokenType {
136    fn from(from: &'static str) -> Self {
137        SemanticTokenType::new(from)
138    }
139}
140
141impl AsRef<str> for SemanticTokenType {
142    fn as_ref(&self) -> &str {
143        self.as_str()
144    }
145}
146
147impl std::fmt::Display for SemanticTokenType {
148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        write!(f, "{}", self.as_str())
150    }
151}
152
153impl From<SemanticTokenType> for String {
154    fn from(token_type: SemanticTokenType) -> Self {
155        match token_type {
156            SemanticTokenType::Known(_) => token_type.as_str().to_string(),
157            SemanticTokenType::Custom(c) => c.into_owned(),
158        }
159    }
160}
161
162impl From<SemanticTokenType> for Cow<'static, str> {
163    fn from(token_type: SemanticTokenType) -> Self {
164        match token_type {
165            SemanticTokenType::Known(_) => Cow::Owned(token_type.as_str().to_string()),
166            SemanticTokenType::Custom(c) => c,
167        }
168    }
169}
170
171/// A set of predefined token modifiers. This set is not fixed
172/// and clients can specify additional token types via the
173/// corresponding client capabilities.
174///
175/// @since 3.16.0
176#[derive(Debug, Eq, PartialEq, Hash, PartialOrd, Clone, Deserialize, Serialize)]
177#[serde(untagged)]
178pub enum SemanticTokenModifier {
179    Known(SemanticTokenModifierEnum),
180    Custom(Cow<'static, str>),
181}
182
183#[derive(Debug, Eq, PartialEq, Hash, PartialOrd, Clone, Deserialize, Serialize)]
184#[serde(rename_all = "camelCase")]
185pub enum SemanticTokenModifierEnum {
186    Declaration,
187    Definition,
188    Readonly,
189    Static,
190    Deprecated,
191    Abstract,
192    Async,
193    Modification,
194    Documentation,
195    DefaultLibrary,
196}
197
198impl SemanticTokenModifier {
199    pub const DECLARATION: SemanticTokenModifier =
200        SemanticTokenModifier::Known(SemanticTokenModifierEnum::Declaration);
201    pub const DEFINITION: SemanticTokenModifier =
202        SemanticTokenModifier::Known(SemanticTokenModifierEnum::Definition);
203    pub const READONLY: SemanticTokenModifier =
204        SemanticTokenModifier::Known(SemanticTokenModifierEnum::Readonly);
205    pub const STATIC: SemanticTokenModifier =
206        SemanticTokenModifier::Known(SemanticTokenModifierEnum::Static);
207    pub const DEPRECATED: SemanticTokenModifier =
208        SemanticTokenModifier::Known(SemanticTokenModifierEnum::Deprecated);
209    pub const ABSTRACT: SemanticTokenModifier =
210        SemanticTokenModifier::Known(SemanticTokenModifierEnum::Abstract);
211    pub const ASYNC: SemanticTokenModifier =
212        SemanticTokenModifier::Known(SemanticTokenModifierEnum::Async);
213    pub const MODIFICATION: SemanticTokenModifier =
214        SemanticTokenModifier::Known(SemanticTokenModifierEnum::Modification);
215    pub const DOCUMENTATION: SemanticTokenModifier =
216        SemanticTokenModifier::Known(SemanticTokenModifierEnum::Documentation);
217    pub const DEFAULT_LIBRARY: SemanticTokenModifier =
218        SemanticTokenModifier::Known(SemanticTokenModifierEnum::DefaultLibrary);
219
220    pub const fn new(tag: &'static str) -> Self {
221        SemanticTokenModifier::Custom(Cow::Borrowed(tag))
222    }
223
224    pub fn as_str(&self) -> &str {
225        match self {
226            Self::Known(k) => match k {
227                SemanticTokenModifierEnum::Declaration => "declaration",
228                SemanticTokenModifierEnum::Definition => "definition",
229                SemanticTokenModifierEnum::Readonly => "readonly",
230                SemanticTokenModifierEnum::Static => "static",
231                SemanticTokenModifierEnum::Deprecated => "deprecated",
232                SemanticTokenModifierEnum::Abstract => "abstract",
233                SemanticTokenModifierEnum::Async => "async",
234                SemanticTokenModifierEnum::Modification => "modification",
235                SemanticTokenModifierEnum::Documentation => "documentation",
236                SemanticTokenModifierEnum::DefaultLibrary => "defaultLibrary",
237            },
238            Self::Custom(c) => c.as_ref(),
239        }
240    }
241}
242
243impl From<String> for SemanticTokenModifier {
244    fn from(from: String) -> Self {
245        SemanticTokenModifier::Custom(Cow::from(from))
246    }
247}
248
249impl From<&'static str> for SemanticTokenModifier {
250    fn from(from: &'static str) -> Self {
251        SemanticTokenModifier::new(from)
252    }
253}
254
255impl AsRef<str> for SemanticTokenModifier {
256    fn as_ref(&self) -> &str {
257        self.as_str()
258    }
259}
260
261impl std::fmt::Display for SemanticTokenModifier {
262    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
263        write!(f, "{}", self.as_str())
264    }
265}
266
267impl From<SemanticTokenModifier> for String {
268    fn from(token_modifier: SemanticTokenModifier) -> Self {
269        match token_modifier {
270            SemanticTokenModifier::Known(_) => token_modifier.as_str().to_string(),
271            SemanticTokenModifier::Custom(c) => c.into_owned(),
272        }
273    }
274}
275
276impl From<SemanticTokenModifier> for Cow<'static, str> {
277    fn from(token_modifier: SemanticTokenModifier) -> Self {
278        match token_modifier {
279            SemanticTokenModifier::Known(_) => Cow::Owned(token_modifier.as_str().to_string()),
280            SemanticTokenModifier::Custom(c) => c,
281        }
282    }
283}
284
285#[derive(Debug, Eq, PartialEq, Hash, PartialOrd, Clone, Deserialize, Serialize)]
286pub struct TokenFormat(Cow<'static, str>);
287
288impl TokenFormat {
289    pub const RELATIVE: TokenFormat = TokenFormat::new("relative");
290
291    pub const fn new(tag: &'static str) -> Self {
292        TokenFormat(Cow::Borrowed(tag))
293    }
294
295    pub fn as_str(&self) -> &str {
296        &self.0
297    }
298}
299
300impl From<String> for TokenFormat {
301    fn from(from: String) -> Self {
302        TokenFormat(Cow::from(from))
303    }
304}
305
306impl From<&'static str> for TokenFormat {
307    fn from(from: &'static str) -> Self {
308        TokenFormat::new(from)
309    }
310}
311
312/// @since 3.16.0
313#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
314#[serde(rename_all = "camelCase")]
315pub struct SemanticTokensLegend {
316    /// The token types a server uses.
317    pub token_types: Vec<SemanticTokenType>,
318
319    /// The token modifiers a server uses.
320    pub token_modifiers: Vec<SemanticTokenModifier>,
321}
322
323/// The actual tokens.
324#[derive(Debug, Eq, PartialEq, Copy, Clone, Default)]
325pub struct SemanticToken {
326    pub delta_line: u32,
327    pub delta_start: u32,
328    pub length: u32,
329    pub token_type: u32,
330    pub token_modifiers_bitset: u32,
331}
332
333impl SemanticToken {
334    fn deserialize_tokens<'de, D>(deserializer: D) -> Result<Vec<SemanticToken>, D::Error>
335    where
336        D: serde::Deserializer<'de>,
337    {
338        let data = Vec::<u32>::deserialize(deserializer)?;
339        let chunks = data.chunks_exact(5);
340
341        if !chunks.remainder().is_empty() {
342            return Result::Err(serde::de::Error::custom("Length is not divisible by 5"));
343        }
344
345        Result::Ok(
346            chunks
347                .map(|chunk| SemanticToken {
348                    delta_line: chunk[0],
349                    delta_start: chunk[1],
350                    length: chunk[2],
351                    token_type: chunk[3],
352                    token_modifiers_bitset: chunk[4],
353                })
354                .collect(),
355        )
356    }
357
358    fn serialize_tokens<S>(tokens: &[SemanticToken], serializer: S) -> Result<S::Ok, S::Error>
359    where
360        S: serde::Serializer,
361    {
362        let mut seq = serializer.serialize_seq(Some(tokens.len() * 5))?;
363        for token in tokens.iter() {
364            seq.serialize_element(&token.delta_line)?;
365            seq.serialize_element(&token.delta_start)?;
366            seq.serialize_element(&token.length)?;
367            seq.serialize_element(&token.token_type)?;
368            seq.serialize_element(&token.token_modifiers_bitset)?;
369        }
370        seq.end()
371    }
372
373    fn deserialize_tokens_opt<'de, D>(
374        deserializer: D,
375    ) -> Result<Option<Vec<SemanticToken>>, D::Error>
376    where
377        D: serde::Deserializer<'de>,
378    {
379        #[derive(Deserialize)]
380        #[serde(transparent)]
381        struct Wrapper {
382            #[serde(deserialize_with = "SemanticToken::deserialize_tokens")]
383            tokens: Vec<SemanticToken>,
384        }
385
386        Ok(Option::<Wrapper>::deserialize(deserializer)?.map(|wrapper| wrapper.tokens))
387    }
388
389    fn serialize_tokens_opt<S>(
390        data: &Option<Vec<SemanticToken>>,
391        serializer: S,
392    ) -> Result<S::Ok, S::Error>
393    where
394        S: serde::Serializer,
395    {
396        #[derive(Serialize)]
397        #[serde(transparent)]
398        struct Wrapper {
399            #[serde(serialize_with = "SemanticToken::serialize_tokens")]
400            tokens: Vec<SemanticToken>,
401        }
402
403        let opt = data.as_ref().map(|t| Wrapper { tokens: t.to_vec() });
404
405        opt.serialize(serializer)
406    }
407}
408
409/// @since 3.16.0
410#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
411#[serde(rename_all = "camelCase")]
412pub struct SemanticTokens {
413    /// An optional result id. If provided and clients support delta updating
414    /// the client will include the result id in the next semantic token request.
415    /// A server can then instead of computing all semantic tokens again simply
416    /// send a delta.
417    #[serde(skip_serializing_if = "Option::is_none")]
418    pub result_id: Option<String>,
419
420    /// The actual tokens. For a detailed description about how the data is
421    /// structured please see
422    /// <https://github.com/microsoft/vscode-extension-samples/blob/5ae1f7787122812dcc84e37427ca90af5ee09f14/semantic-tokens-sample/vscode.proposed.d.ts#L71>
423    #[serde(
424        deserialize_with = "SemanticToken::deserialize_tokens",
425        serialize_with = "SemanticToken::serialize_tokens"
426    )]
427    pub data: Vec<SemanticToken>,
428}
429
430/// @since 3.16.0
431#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
432#[serde(rename_all = "camelCase")]
433pub struct SemanticTokensPartialResult {
434    #[serde(
435        deserialize_with = "SemanticToken::deserialize_tokens",
436        serialize_with = "SemanticToken::serialize_tokens"
437    )]
438    pub data: Vec<SemanticToken>,
439}
440
441#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
442#[serde(rename_all = "camelCase")]
443#[serde(untagged)]
444pub enum SemanticTokensResult {
445    Tokens(SemanticTokens),
446    Partial(SemanticTokensPartialResult),
447}
448
449impl From<SemanticTokens> for SemanticTokensResult {
450    fn from(from: SemanticTokens) -> Self {
451        SemanticTokensResult::Tokens(from)
452    }
453}
454
455impl From<SemanticTokensPartialResult> for SemanticTokensResult {
456    fn from(from: SemanticTokensPartialResult) -> Self {
457        SemanticTokensResult::Partial(from)
458    }
459}
460
461/// @since 3.16.0
462#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
463#[serde(rename_all = "camelCase")]
464pub struct SemanticTokensEdit {
465    pub start: u32,
466    pub delete_count: u32,
467
468    #[serde(
469        default,
470        skip_serializing_if = "Option::is_none",
471        deserialize_with = "SemanticToken::deserialize_tokens_opt",
472        serialize_with = "SemanticToken::serialize_tokens_opt"
473    )]
474    pub data: Option<Vec<SemanticToken>>,
475}
476
477#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
478#[serde(rename_all = "camelCase")]
479#[serde(untagged)]
480pub enum SemanticTokensFullDeltaResult {
481    Tokens(SemanticTokens),
482    TokensDelta(SemanticTokensDelta),
483    PartialTokensDelta { edits: Vec<SemanticTokensEdit> },
484}
485
486impl From<SemanticTokens> for SemanticTokensFullDeltaResult {
487    fn from(from: SemanticTokens) -> Self {
488        SemanticTokensFullDeltaResult::Tokens(from)
489    }
490}
491
492impl From<SemanticTokensDelta> for SemanticTokensFullDeltaResult {
493    fn from(from: SemanticTokensDelta) -> Self {
494        SemanticTokensFullDeltaResult::TokensDelta(from)
495    }
496}
497
498/// @since 3.16.0
499#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
500#[serde(rename_all = "camelCase")]
501pub struct SemanticTokensDelta {
502    #[serde(skip_serializing_if = "Option::is_none")]
503    pub result_id: Option<String>,
504    /// For a detailed description how these edits are structured please see
505    /// <https://github.com/microsoft/vscode-extension-samples/blob/5ae1f7787122812dcc84e37427ca90af5ee09f14/semantic-tokens-sample/vscode.proposed.d.ts#L131>
506    pub edits: Vec<SemanticTokensEdit>,
507}
508
509/// Capabilities specific to the `textDocument/semanticTokens/*` requests.
510///
511/// @since 3.16.0
512#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
513#[serde(rename_all = "camelCase")]
514pub struct SemanticTokensClientCapabilities {
515    /// Whether implementation supports dynamic registration. If this is set to `true`
516    /// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`
517    /// return value for the corresponding server capability as well.
518    #[serde(skip_serializing_if = "Option::is_none")]
519    pub dynamic_registration: Option<bool>,
520
521    /// Which requests the client supports and might send to the server
522    /// depending on the server's capability. Please note that clients might not
523    /// show semantic tokens or degrade some of the user experience if a range
524    /// or full request is advertised by the client but not provided by the
525    /// server. If for example the client capability `requests.full` and
526    /// `request.range` are both set to true but the server only provides a
527    /// range provider the client might not render a minimap correctly or might
528    /// even decide to not show any semantic tokens at all.
529    pub requests: SemanticTokensClientCapabilitiesRequests,
530
531    /// The token types that the client supports.
532    pub token_types: Vec<SemanticTokenType>,
533
534    /// The token modifiers that the client supports.
535    pub token_modifiers: Vec<SemanticTokenModifier>,
536
537    /// The token formats the clients supports.
538    pub formats: Vec<TokenFormat>,
539
540    /// Whether the client supports tokens that can overlap each other.
541    #[serde(skip_serializing_if = "Option::is_none")]
542    pub overlapping_token_support: Option<bool>,
543
544    /// Whether the client supports tokens that can span multiple lines.
545    #[serde(skip_serializing_if = "Option::is_none")]
546    pub multiline_token_support: Option<bool>,
547
548    /// Whether the client allows the server to actively cancel a
549    /// semantic token request, e.g. supports returning
550    /// ErrorCodes.ServerCancelled. If a server does the client
551    /// needs to retrigger the request.
552    ///
553    /// @since 3.17.0
554    #[serde(skip_serializing_if = "Option::is_none")]
555    pub server_cancel_support: Option<bool>,
556
557    /// Whether the client uses semantic tokens to augment existing
558    /// syntax tokens. If set to `true` client side created syntax
559    /// tokens and semantic tokens are both used for colorization. If
560    /// set to `false` the client only uses the returned semantic tokens
561    /// for colorization.
562    ///
563    /// If the value is `undefined` then the client behavior is not
564    /// specified.
565    ///
566    /// @since 3.17.0
567    #[serde(skip_serializing_if = "Option::is_none")]
568    pub augments_syntax_tokens: Option<bool>,
569}
570
571#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
572#[serde(rename_all = "camelCase")]
573pub struct SemanticTokensClientCapabilitiesRequests {
574    /// The client will send the `textDocument/semanticTokens/range` request if the server provides a corresponding handler.
575    #[serde(skip_serializing_if = "Option::is_none")]
576    pub range: Option<bool>,
577
578    /// The client will send the `textDocument/semanticTokens/full` request if the server provides a corresponding handler.
579    #[serde(skip_serializing_if = "Option::is_none")]
580    pub full: Option<SemanticTokensFullOptions>,
581}
582
583#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
584#[serde(rename_all = "camelCase")]
585#[serde(untagged)]
586pub enum SemanticTokensFullOptions {
587    Bool(bool),
588    Delta {
589        /// The client will send the `textDocument/semanticTokens/full/delta` request if the server provides a corresponding handler.
590        /// The server supports deltas for full documents.
591        #[serde(skip_serializing_if = "Option::is_none")]
592        delta: Option<bool>,
593    },
594}
595
596/// @since 3.16.0
597#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
598#[serde(rename_all = "camelCase")]
599pub struct SemanticTokensOptions {
600    #[serde(flatten)]
601    pub work_done_progress_options: WorkDoneProgressOptions,
602
603    /// The legend used by the server
604    pub legend: SemanticTokensLegend,
605
606    /// Server supports providing semantic tokens for a specific range
607    /// of a document.
608    #[serde(skip_serializing_if = "Option::is_none")]
609    pub range: Option<bool>,
610
611    /// Server supports providing semantic tokens for a full document.
612    #[serde(skip_serializing_if = "Option::is_none")]
613    pub full: Option<SemanticTokensFullOptions>,
614}
615
616#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
617#[serde(rename_all = "camelCase")]
618pub struct SemanticTokensRegistrationOptions {
619    #[serde(flatten)]
620    pub text_document_registration_options: TextDocumentRegistrationOptions,
621
622    #[serde(flatten)]
623    pub semantic_tokens_options: SemanticTokensOptions,
624
625    #[serde(flatten)]
626    pub static_registration_options: StaticRegistrationOptions,
627}
628
629#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
630#[serde(rename_all = "camelCase")]
631#[serde(untagged)]
632pub enum SemanticTokensServerCapabilities {
633    SemanticTokensOptions(SemanticTokensOptions),
634    SemanticTokensRegistrationOptions(SemanticTokensRegistrationOptions),
635}
636
637impl From<SemanticTokensOptions> for SemanticTokensServerCapabilities {
638    fn from(from: SemanticTokensOptions) -> Self {
639        SemanticTokensServerCapabilities::SemanticTokensOptions(from)
640    }
641}
642
643impl From<SemanticTokensRegistrationOptions> for SemanticTokensServerCapabilities {
644    fn from(from: SemanticTokensRegistrationOptions) -> Self {
645        SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(from)
646    }
647}
648
649#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
650#[serde(rename_all = "camelCase")]
651pub struct SemanticTokensWorkspaceClientCapabilities {
652    /// Whether the client implementation supports a refresh request sent from
653    /// the server to the client.
654    ///
655    /// Note that this event is global and will force the client to refresh all
656    /// semantic tokens currently shown. It should be used with absolute care
657    /// and is useful for situation where a server for example detect a project
658    /// wide change that requires such a calculation.
659    pub refresh_support: Option<bool>,
660}
661
662#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
663#[serde(rename_all = "camelCase")]
664pub struct SemanticTokensParams {
665    #[serde(flatten)]
666    pub work_done_progress_params: WorkDoneProgressParams,
667
668    #[serde(flatten)]
669    pub partial_result_params: PartialResultParams,
670
671    /// The text document.
672    pub text_document: TextDocumentIdentifier,
673}
674
675#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
676#[serde(rename_all = "camelCase")]
677pub struct SemanticTokensDeltaParams {
678    #[serde(flatten)]
679    pub work_done_progress_params: WorkDoneProgressParams,
680
681    #[serde(flatten)]
682    pub partial_result_params: PartialResultParams,
683
684    /// The text document.
685    pub text_document: TextDocumentIdentifier,
686
687    /// The result id of a previous response. The result Id can either point to a full response
688    /// or a delta response depending on what was received last.
689    pub previous_result_id: String,
690}
691
692#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
693#[serde(rename_all = "camelCase")]
694pub struct SemanticTokensRangeParams {
695    #[serde(flatten)]
696    pub work_done_progress_params: WorkDoneProgressParams,
697
698    #[serde(flatten)]
699    pub partial_result_params: PartialResultParams,
700
701    /// The text document.
702    pub text_document: TextDocumentIdentifier,
703
704    /// The range the semantic tokens are requested for.
705    pub range: Range,
706}
707
708#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
709#[serde(rename_all = "camelCase")]
710#[serde(untagged)]
711pub enum SemanticTokensRangeResult {
712    Tokens(SemanticTokens),
713    Partial(SemanticTokensPartialResult),
714}
715
716impl From<SemanticTokens> for SemanticTokensRangeResult {
717    fn from(tokens: SemanticTokens) -> Self {
718        SemanticTokensRangeResult::Tokens(tokens)
719    }
720}
721
722impl From<SemanticTokensPartialResult> for SemanticTokensRangeResult {
723    fn from(partial: SemanticTokensPartialResult) -> Self {
724        SemanticTokensRangeResult::Partial(partial)
725    }
726}
727
728#[cfg(test)]
729mod tests {
730    use super::*;
731    use crate::tests::{test_deserialization, test_serialization};
732
733    #[test]
734    fn test_semantic_tokens_support_serialization() {
735        test_serialization(
736            &SemanticTokens {
737                result_id: None,
738                data: vec![],
739            },
740            r#"{"data":[]}"#,
741        );
742
743        test_serialization(
744            &SemanticTokens {
745                result_id: None,
746                data: vec![SemanticToken {
747                    delta_line: 2,
748                    delta_start: 5,
749                    length: 3,
750                    token_type: 0,
751                    token_modifiers_bitset: 3,
752                }],
753            },
754            r#"{"data":[2,5,3,0,3]}"#,
755        );
756
757        test_serialization(
758            &SemanticTokens {
759                result_id: None,
760                data: vec![
761                    SemanticToken {
762                        delta_line: 2,
763                        delta_start: 5,
764                        length: 3,
765                        token_type: 0,
766                        token_modifiers_bitset: 3,
767                    },
768                    SemanticToken {
769                        delta_line: 0,
770                        delta_start: 5,
771                        length: 4,
772                        token_type: 1,
773                        token_modifiers_bitset: 0,
774                    },
775                ],
776            },
777            r#"{"data":[2,5,3,0,3,0,5,4,1,0]}"#,
778        );
779    }
780
781    #[test]
782    fn test_semantic_tokens_support_deserialization() {
783        test_deserialization(
784            r#"{"data":[]}"#,
785            &SemanticTokens {
786                result_id: None,
787                data: vec![],
788            },
789        );
790
791        test_deserialization(
792            r#"{"data":[2,5,3,0,3]}"#,
793            &SemanticTokens {
794                result_id: None,
795                data: vec![SemanticToken {
796                    delta_line: 2,
797                    delta_start: 5,
798                    length: 3,
799                    token_type: 0,
800                    token_modifiers_bitset: 3,
801                }],
802            },
803        );
804
805        test_deserialization(
806            r#"{"data":[2,5,3,0,3,0,5,4,1,0]}"#,
807            &SemanticTokens {
808                result_id: None,
809                data: vec![
810                    SemanticToken {
811                        delta_line: 2,
812                        delta_start: 5,
813                        length: 3,
814                        token_type: 0,
815                        token_modifiers_bitset: 3,
816                    },
817                    SemanticToken {
818                        delta_line: 0,
819                        delta_start: 5,
820                        length: 4,
821                        token_type: 1,
822                        token_modifiers_bitset: 0,
823                    },
824                ],
825            },
826        );
827    }
828
829    #[test]
830    #[should_panic]
831    fn test_semantic_tokens_support_deserialization_err() {
832        test_deserialization(
833            r#"{"data":[1]}"#,
834            &SemanticTokens {
835                result_id: None,
836                data: vec![],
837            },
838        );
839    }
840
841    #[test]
842    fn test_semantic_tokens_edit_support_deserialization() {
843        test_deserialization(
844            r#"{"start":0,"deleteCount":1,"data":[2,5,3,0,3,0,5,4,1,0]}"#,
845            &SemanticTokensEdit {
846                start: 0,
847                delete_count: 1,
848                data: Some(vec![
849                    SemanticToken {
850                        delta_line: 2,
851                        delta_start: 5,
852                        length: 3,
853                        token_type: 0,
854                        token_modifiers_bitset: 3,
855                    },
856                    SemanticToken {
857                        delta_line: 0,
858                        delta_start: 5,
859                        length: 4,
860                        token_type: 1,
861                        token_modifiers_bitset: 0,
862                    },
863                ]),
864            },
865        );
866
867        test_deserialization(
868            r#"{"start":0,"deleteCount":1}"#,
869            &SemanticTokensEdit {
870                start: 0,
871                delete_count: 1,
872                data: None,
873            },
874        );
875    }
876
877    #[test]
878    fn test_semantic_tokens_edit_support_serialization() {
879        test_serialization(
880            &SemanticTokensEdit {
881                start: 0,
882                delete_count: 1,
883                data: Some(vec![
884                    SemanticToken {
885                        delta_line: 2,
886                        delta_start: 5,
887                        length: 3,
888                        token_type: 0,
889                        token_modifiers_bitset: 3,
890                    },
891                    SemanticToken {
892                        delta_line: 0,
893                        delta_start: 5,
894                        length: 4,
895                        token_type: 1,
896                        token_modifiers_bitset: 0,
897                    },
898                ]),
899            },
900            r#"{"start":0,"deleteCount":1,"data":[2,5,3,0,3,0,5,4,1,0]}"#,
901        );
902
903        test_serialization(
904            &SemanticTokensEdit {
905                start: 0,
906                delete_count: 1,
907                data: None,
908            },
909            r#"{"start":0,"deleteCount":1}"#,
910        );
911    }
912}