Skip to main content

rust_analyzer/lsp/
semantic_tokens.rs

1//! Semantic Tokens helpers
2
3use std::{fmt, ops, slice::Iter};
4
5use lsp_types::{Range, SemanticTokenModifiers, SemanticTokens, SemanticTokensEdit};
6
7macro_rules! declare_enum {
8    (
9        $(#[$attrs:meta])*
10        $visibility:vis enum $name:ident {
11            $($variant:ident),* $(,)?
12        }
13    ) => {
14        $(#[$attrs])*
15        $visibility enum $name {
16            $($variant,)*
17        }
18
19        impl $name {
20            pub(crate) fn iter() -> Iter<'static, Self> {
21                static ITEMS: &[$name] = &[
22                    $(
23                        $name::$variant,
24                    )*
25                ];
26                ITEMS.iter()
27            }
28        }
29    };
30}
31
32declare_enum! {
33    #[repr(u32)]
34    #[derive(Debug, PartialEq, Clone, Copy)]
35    pub(crate) enum SupportedType {
36        Comment,
37        Decorator,
38        EnumMember,
39        Enum,
40        Function,
41        Interface,
42        Keyword,
43        Macro,
44        Method,
45        Namespace,
46        Number,
47        Operator,
48        Parameter,
49        Property,
50        String,
51        Struct,
52        TypeParameter,
53        Variable,
54        Type,
55        Label,
56        Angle,
57        Arithmetic,
58        AttributeBracket,
59        Attribute,
60        Bitwise,
61        Boolean,
62        Brace,
63        Bracket,
64        BuiltinAttribute,
65        BuiltinType,
66        Char,
67        Colon,
68        Comma,
69        Comparison,
70        ConstParameter,
71        Const,
72        DeriveHelper,
73        Derive,
74        Dot,
75        EscapeSequence,
76        FormatSpecifier,
77        Generic,
78        InvalidEscapeSequence,
79        Lifetime,
80        Logical,
81        MacroBang,
82        Negation,
83        Parenthesis,
84        ProcMacro,
85        Punctuation,
86        SelfKeyword,
87        SelfTypeKeyword,
88        Semicolon,
89        Static,
90        ToolModule,
91        TypeAlias,
92        Union,
93        UnresolvedReference,
94    }
95}
96
97declare_enum! {
98    #[repr(u32)]
99    #[derive(Debug, PartialEq, Clone, Copy)]
100    pub(crate) enum SupportedModifiers {
101        Async,
102        Documentation,
103        Declaration,
104        Static,
105        DefaultLibrary,
106        Deprecated,
107        Associated,
108        AttributeModifier,
109        Callable,
110        Constant,
111        Consuming,
112        ControlFlow,
113        CrateRoot,
114        Injected,
115        IntraDocLink,
116        Library,
117        MacroModifier,
118        Mutable,
119        ProcMacroModifier,
120        Public,
121        Reference,
122        TraitModifier,
123        Unsafe,
124    }
125}
126
127impl fmt::Display for SupportedType {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        let string = match self {
130            SupportedType::Comment => ::lsp_types::SemanticTokenTypes::Comment.as_str(),
131            SupportedType::Decorator => ::lsp_types::SemanticTokenTypes::Decorator.as_str(),
132            SupportedType::EnumMember => ::lsp_types::SemanticTokenTypes::EnumMember.as_str(),
133            SupportedType::Enum => ::lsp_types::SemanticTokenTypes::Enum.as_str(),
134            SupportedType::Function => ::lsp_types::SemanticTokenTypes::Function.as_str(),
135            SupportedType::Interface => ::lsp_types::SemanticTokenTypes::Interface.as_str(),
136            SupportedType::Keyword => ::lsp_types::SemanticTokenTypes::Keyword.as_str(),
137            SupportedType::Macro => ::lsp_types::SemanticTokenTypes::Macro.as_str(),
138            SupportedType::Method => ::lsp_types::SemanticTokenTypes::Method.as_str(),
139            SupportedType::Namespace => ::lsp_types::SemanticTokenTypes::Namespace.as_str(),
140            SupportedType::Number => ::lsp_types::SemanticTokenTypes::Number.as_str(),
141            SupportedType::Operator => ::lsp_types::SemanticTokenTypes::Operator.as_str(),
142            SupportedType::Parameter => ::lsp_types::SemanticTokenTypes::Parameter.as_str(),
143            SupportedType::Property => ::lsp_types::SemanticTokenTypes::Property.as_str(),
144            SupportedType::String => ::lsp_types::SemanticTokenTypes::String.as_str(),
145            SupportedType::Struct => ::lsp_types::SemanticTokenTypes::Struct.as_str(),
146            SupportedType::TypeParameter => ::lsp_types::SemanticTokenTypes::TypeParameter.as_str(),
147            SupportedType::Variable => ::lsp_types::SemanticTokenTypes::Variable.as_str(),
148            SupportedType::Type => ::lsp_types::SemanticTokenTypes::Type.as_str(),
149            SupportedType::Label => ::lsp_types::SemanticTokenTypes::Label.as_str(),
150            SupportedType::Angle => "angle",
151            SupportedType::Arithmetic => "arithmetic",
152            SupportedType::AttributeBracket => "attributeBracket",
153            SupportedType::Attribute => "attribute",
154            SupportedType::Bitwise => "bitwise",
155            SupportedType::Boolean => "boolean",
156            SupportedType::Brace => "brace",
157            SupportedType::Bracket => "bracket",
158            SupportedType::BuiltinAttribute => "builtinAttribute",
159            SupportedType::BuiltinType => "builtinType",
160            SupportedType::Char => "character",
161            SupportedType::Colon => "colon",
162            SupportedType::Comma => "comma",
163            SupportedType::Comparison => "comparison",
164            SupportedType::ConstParameter => "constParameter",
165            SupportedType::Const => "const",
166            SupportedType::DeriveHelper => "deriveHelper",
167            SupportedType::Derive => "derive",
168            SupportedType::Dot => "dot",
169            SupportedType::EscapeSequence => "escapeSequence",
170            SupportedType::FormatSpecifier => "formatSpecifier",
171            SupportedType::Generic => "generic",
172            SupportedType::InvalidEscapeSequence => "invalidEscapeSequence",
173            SupportedType::Lifetime => "lifetime",
174            SupportedType::Logical => "logical",
175            SupportedType::MacroBang => "macroBang",
176            SupportedType::Negation => "negation",
177            SupportedType::Parenthesis => "parenthesis",
178            SupportedType::ProcMacro => "procMacro",
179            SupportedType::Punctuation => "punctuation",
180            SupportedType::SelfKeyword => "selfKeyword",
181            SupportedType::SelfTypeKeyword => "selfTypeKeyword",
182            SupportedType::Semicolon => "semicolon",
183            SupportedType::Static => "static",
184            SupportedType::ToolModule => "toolModule",
185            SupportedType::TypeAlias => "typeAlias",
186            SupportedType::Union => "union",
187            SupportedType::UnresolvedReference => "unresolvedReference",
188        };
189        f.write_str(string)
190    }
191}
192
193pub(crate) fn standard_fallback_type(token: SupportedType) -> Option<SupportedType> {
194    Some(match token {
195        SupportedType::Comment => SupportedType::Comment,
196        SupportedType::Decorator => SupportedType::Decorator,
197        SupportedType::EnumMember => SupportedType::EnumMember,
198        SupportedType::Enum => SupportedType::Enum,
199        SupportedType::Function => SupportedType::Function,
200        SupportedType::Interface => SupportedType::Interface,
201        SupportedType::Keyword => SupportedType::Keyword,
202        SupportedType::Macro => SupportedType::Macro,
203        SupportedType::Method => SupportedType::Method,
204        SupportedType::Namespace => SupportedType::Namespace,
205        SupportedType::Number => SupportedType::Number,
206        SupportedType::Operator => SupportedType::Operator,
207        SupportedType::Parameter => SupportedType::Parameter,
208        SupportedType::Property => SupportedType::Property,
209        SupportedType::String => SupportedType::String,
210        SupportedType::Struct => SupportedType::Struct,
211        SupportedType::TypeParameter => SupportedType::TypeParameter,
212        SupportedType::Variable => SupportedType::Variable,
213        SupportedType::Type => SupportedType::Type,
214        SupportedType::Label => SupportedType::Label,
215        _ => return None,
216    })
217}
218
219impl fmt::Display for SupportedModifiers {
220    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221        let string = match self {
222            SupportedModifiers::Async => SemanticTokenModifiers::Async.as_str(),
223            SupportedModifiers::Documentation => SemanticTokenModifiers::Documentation.as_str(),
224            SupportedModifiers::Declaration => SemanticTokenModifiers::Declaration.as_str(),
225            SupportedModifiers::Static => SemanticTokenModifiers::Static.as_str(),
226            SupportedModifiers::DefaultLibrary => SemanticTokenModifiers::DefaultLibrary.as_str(),
227            SupportedModifiers::Deprecated => SemanticTokenModifiers::Deprecated.as_str(),
228            SupportedModifiers::Associated => "associated",
229            SupportedModifiers::AttributeModifier => "attribute",
230            SupportedModifiers::Callable => "callable",
231            SupportedModifiers::Constant => "constant",
232            SupportedModifiers::Consuming => "consuming",
233            SupportedModifiers::ControlFlow => "controlFlow",
234            SupportedModifiers::CrateRoot => "crateRoot",
235            SupportedModifiers::Injected => "injected",
236            SupportedModifiers::IntraDocLink => "intraDocLink",
237            SupportedModifiers::Library => "library",
238            SupportedModifiers::MacroModifier => "macro",
239            SupportedModifiers::Mutable => "mutable",
240            SupportedModifiers::ProcMacroModifier => "procMacro",
241            SupportedModifiers::Public => "public",
242            SupportedModifiers::Reference => "reference",
243            SupportedModifiers::TraitModifier => "trait",
244            SupportedModifiers::Unsafe => "unsafe",
245        };
246        f.write_str(string)
247    }
248}
249
250const STANDARD_MOD: [SupportedModifiers; 6] = [
251    SupportedModifiers::Async,
252    SupportedModifiers::Documentation,
253    SupportedModifiers::Declaration,
254    SupportedModifiers::Static,
255    SupportedModifiers::DefaultLibrary,
256    SupportedModifiers::Deprecated,
257];
258const LAST_STANDARD_MOD: usize = STANDARD_MOD.len() - 1;
259
260#[derive(Default)]
261pub(crate) struct ModifierSet(pub(crate) u32);
262
263impl ModifierSet {
264    pub(crate) fn standard_fallback(&mut self) {
265        // Remove all non standard modifiers
266        self.0 &= !(!0u32 << LAST_STANDARD_MOD)
267    }
268}
269
270impl ops::BitOrAssign<SupportedModifiers> for ModifierSet {
271    fn bitor_assign(&mut self, rhs: SupportedModifiers) {
272        let idx = SupportedModifiers::iter().position(|it| *it == rhs).unwrap();
273        self.0 |= 1 << idx;
274    }
275}
276
277/// Tokens are encoded relative to each other.
278///
279/// This is a direct port of <https://github.com/microsoft/vscode-languageserver-node/blob/f425af9de46a0187adb78ec8a46b9b2ce80c5412/server/src/sematicTokens.proposed.ts#L45>
280pub(crate) struct SemanticTokensBuilder {
281    id: String,
282    prev_line: u32,
283    prev_char: u32,
284    data: Vec<lsp_types::SemanticToken>,
285}
286
287impl SemanticTokensBuilder {
288    pub(crate) fn new(id: String) -> Self {
289        SemanticTokensBuilder { id, prev_line: 0, prev_char: 0, data: Vec::new() }
290    }
291
292    /// Push a new token onto the builder
293    pub(crate) fn push(&mut self, range: Range, token_index: u32, modifier_bitset: u32) {
294        let mut push_line = range.start.line;
295        let mut push_char = range.start.character;
296
297        if !self.data.is_empty() {
298            push_line -= self.prev_line;
299            if push_line == 0 {
300                push_char -= self.prev_char;
301            }
302        }
303
304        // A token cannot be multiline
305        let token_len = range.end.character - range.start.character;
306
307        let token = lsp_types::SemanticToken {
308            delta_line: push_line,
309            delta_start: push_char,
310            length: token_len,
311            token_type: token_index,
312            token_modifiers_bitset: modifier_bitset,
313        };
314
315        self.data.push(token);
316
317        self.prev_line = range.start.line;
318        self.prev_char = range.start.character;
319    }
320
321    pub(crate) fn build(self) -> SemanticTokens {
322        SemanticTokens { result_id: Some(self.id), data: self.data }
323    }
324}
325
326pub(crate) fn diff_tokens(
327    old: &[lsp_types::SemanticToken],
328    new: &[lsp_types::SemanticToken],
329) -> Vec<SemanticTokensEdit> {
330    let offset = new.iter().zip(old.iter()).take_while(|&(n, p)| n == p).count();
331
332    let (_, old) = old.split_at(offset);
333    let (_, new) = new.split_at(offset);
334
335    let offset_from_end =
336        new.iter().rev().zip(old.iter().rev()).take_while(|&(n, p)| n == p).count();
337
338    let (old, _) = old.split_at(old.len() - offset_from_end);
339    let (new, _) = new.split_at(new.len() - offset_from_end);
340
341    if old.is_empty() && new.is_empty() {
342        vec![]
343    } else {
344        // The lsp data field is actually a byte-diff but we
345        // travel in tokens so `start` and `delete_count` are in multiples of the
346        // serialized size of `SemanticToken`.
347        let data = new.iter().copied().flat_map(<[u32; 5]>::from).collect();
348        vec![SemanticTokensEdit {
349            start: 5 * offset as u32,
350            delete_count: 5 * old.len() as u32,
351            data: Some(data),
352        }]
353    }
354}
355
356pub(crate) fn type_index(kind: SupportedType) -> u32 {
357    kind as u32
358}
359
360#[cfg(test)]
361mod tests {
362    use super::*;
363
364    fn from(t: (u32, u32, u32, u32, u32)) -> lsp_types::SemanticToken {
365        lsp_types::SemanticToken {
366            delta_line: t.0,
367            delta_start: t.1,
368            length: t.2,
369            token_type: t.3,
370            token_modifiers_bitset: t.4,
371        }
372    }
373
374    #[test]
375    fn test_diff_insert_at_end() {
376        let before = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
377        let after = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10)), from((11, 12, 13, 14, 15))];
378
379        let edits = diff_tokens(&before, &after);
380        assert_eq!(
381            edits[0],
382            SemanticTokensEdit { start: 10, delete_count: 0, data: Some(vec![11, 12, 13, 14, 15]) }
383        );
384    }
385
386    #[test]
387    fn test_diff_insert_at_beginning() {
388        let before = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
389        let after = [from((11, 12, 13, 14, 15)), from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
390
391        let edits = diff_tokens(&before, &after);
392        assert_eq!(
393            edits[0],
394            SemanticTokensEdit { start: 0, delete_count: 0, data: Some(vec![11, 12, 13, 14, 15]) }
395        );
396    }
397
398    #[test]
399    fn test_diff_insert_in_middle() {
400        let before = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
401        let after = [
402            from((1, 2, 3, 4, 5)),
403            from((10, 20, 30, 40, 50)),
404            from((60, 70, 80, 90, 100)),
405            from((6, 7, 8, 9, 10)),
406        ];
407
408        let edits = diff_tokens(&before, &after);
409        assert_eq!(
410            edits[0],
411            SemanticTokensEdit {
412                start: 5,
413                delete_count: 0,
414                data: Some(vec![10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
415            }
416        );
417    }
418
419    #[test]
420    fn test_diff_remove_from_end() {
421        let before = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10)), from((11, 12, 13, 14, 15))];
422        let after = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
423
424        let edits = diff_tokens(&before, &after);
425        assert_eq!(edits[0], SemanticTokensEdit { start: 10, delete_count: 5, data: Some(vec![]) });
426    }
427
428    #[test]
429    fn test_diff_remove_from_beginning() {
430        let before = [from((11, 12, 13, 14, 15)), from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
431        let after = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
432
433        let edits = diff_tokens(&before, &after);
434        assert_eq!(edits[0], SemanticTokensEdit { start: 0, delete_count: 5, data: Some(vec![]) });
435    }
436
437    #[test]
438    fn test_diff_remove_from_middle() {
439        let before = [
440            from((1, 2, 3, 4, 5)),
441            from((10, 20, 30, 40, 50)),
442            from((60, 70, 80, 90, 100)),
443            from((6, 7, 8, 9, 10)),
444        ];
445        let after = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
446
447        let edits = diff_tokens(&before, &after);
448        assert_eq!(edits[0], SemanticTokensEdit { start: 5, delete_count: 10, data: Some(vec![]) });
449    }
450}