]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/semantic_tokens.rs
Merge #9031
[rust.git] / crates / rust-analyzer / src / semantic_tokens.rs
1 //! Semantic Tokens helpers
2
3 use std::ops;
4
5 use lsp_types::{
6     Range, SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokens,
7     SemanticTokensEdit,
8 };
9
10 macro_rules! define_semantic_token_types {
11     ($(($ident:ident, $string:literal)),*$(,)?) => {
12         $(pub(crate) const $ident: SemanticTokenType = SemanticTokenType::new($string);)*
13
14         pub(crate) const SUPPORTED_TYPES: &[SemanticTokenType] = &[
15             SemanticTokenType::COMMENT,
16             SemanticTokenType::KEYWORD,
17             SemanticTokenType::STRING,
18             SemanticTokenType::NUMBER,
19             SemanticTokenType::REGEXP,
20             SemanticTokenType::OPERATOR,
21             SemanticTokenType::NAMESPACE,
22             SemanticTokenType::TYPE,
23             SemanticTokenType::STRUCT,
24             SemanticTokenType::CLASS,
25             SemanticTokenType::INTERFACE,
26             SemanticTokenType::ENUM,
27             SemanticTokenType::ENUM_MEMBER,
28             SemanticTokenType::TYPE_PARAMETER,
29             SemanticTokenType::FUNCTION,
30             SemanticTokenType::METHOD,
31             SemanticTokenType::PROPERTY,
32             SemanticTokenType::MACRO,
33             SemanticTokenType::VARIABLE,
34             SemanticTokenType::PARAMETER,
35             $($ident),*
36         ];
37     };
38 }
39
40 define_semantic_token_types![
41     (ANGLE, "angle"),
42     (ARITHMETIC, "arithmetic"),
43     (ATTRIBUTE, "attribute"),
44     (BITWISE, "bitwise"),
45     (BOOLEAN, "boolean"),
46     (BRACE, "brace"),
47     (BRACKET, "bracket"),
48     (BUILTIN_TYPE, "builtinType"),
49     (CHAR, "character"),
50     (COLON, "colon"),
51     (COMMA, "comma"),
52     (COMPARISON, "comparison"),
53     (CONST_PARAMETER, "constParameter"),
54     (DOT, "dot"),
55     (ESCAPE_SEQUENCE, "escapeSequence"),
56     (FORMAT_SPECIFIER, "formatSpecifier"),
57     (GENERIC, "generic"),
58     (LABEL, "label"),
59     (LIFETIME, "lifetime"),
60     (LOGICAL, "logical"),
61     (OPERATOR, "operator"),
62     (PARENTHESIS, "parenthesis"),
63     (PUNCTUATION, "punctuation"),
64     (SELF_KEYWORD, "selfKeyword"),
65     (SEMICOLON, "semicolon"),
66     (TYPE_ALIAS, "typeAlias"),
67     (UNION, "union"),
68     (UNRESOLVED_REFERENCE, "unresolvedReference"),
69 ];
70
71 macro_rules! define_semantic_token_modifiers {
72     ($(($ident:ident, $string:literal)),*$(,)?) => {
73         $(pub(crate) const $ident: SemanticTokenModifier = SemanticTokenModifier::new($string);)*
74
75         pub(crate) const SUPPORTED_MODIFIERS: &[SemanticTokenModifier] = &[
76             SemanticTokenModifier::DOCUMENTATION,
77             SemanticTokenModifier::DECLARATION,
78             SemanticTokenModifier::DEFINITION,
79             SemanticTokenModifier::STATIC,
80             SemanticTokenModifier::ABSTRACT,
81             SemanticTokenModifier::DEPRECATED,
82             SemanticTokenModifier::READONLY,
83             $($ident),*
84         ];
85     };
86 }
87
88 define_semantic_token_modifiers![
89     (CONSTANT, "constant"),
90     (CONTROL_FLOW, "controlFlow"),
91     (INJECTED, "injected"),
92     (MUTABLE, "mutable"),
93     (CONSUMING, "consuming"),
94     (ASYNC, "async"),
95     (LIBRARY, "library"),
96     (PUBLIC, "public"),
97     (UNSAFE, "unsafe"),
98     (ATTRIBUTE_MODIFIER, "attribute"),
99     (TRAIT_MODIFIER, "trait"),
100     (CALLABLE, "callable"),
101     (INTRA_DOC_LINK, "intraDocLink"),
102 ];
103
104 #[derive(Default)]
105 pub(crate) struct ModifierSet(pub(crate) u32);
106
107 impl ops::BitOrAssign<SemanticTokenModifier> for ModifierSet {
108     fn bitor_assign(&mut self, rhs: SemanticTokenModifier) {
109         let idx = SUPPORTED_MODIFIERS.iter().position(|it| it == &rhs).unwrap();
110         self.0 |= 1 << idx;
111     }
112 }
113
114 /// Tokens are encoded relative to each other.
115 ///
116 /// This is a direct port of <https://github.com/microsoft/vscode-languageserver-node/blob/f425af9de46a0187adb78ec8a46b9b2ce80c5412/server/src/sematicTokens.proposed.ts#L45>
117 pub(crate) struct SemanticTokensBuilder {
118     id: String,
119     prev_line: u32,
120     prev_char: u32,
121     data: Vec<SemanticToken>,
122 }
123
124 impl SemanticTokensBuilder {
125     pub(crate) fn new(id: String) -> Self {
126         SemanticTokensBuilder { id, prev_line: 0, prev_char: 0, data: Default::default() }
127     }
128
129     /// Push a new token onto the builder
130     pub(crate) fn push(&mut self, range: Range, token_index: u32, modifier_bitset: u32) {
131         let mut push_line = range.start.line as u32;
132         let mut push_char = range.start.character as u32;
133
134         if !self.data.is_empty() {
135             push_line -= self.prev_line;
136             if push_line == 0 {
137                 push_char -= self.prev_char;
138             }
139         }
140
141         // A token cannot be multiline
142         let token_len = range.end.character - range.start.character;
143
144         let token = SemanticToken {
145             delta_line: push_line,
146             delta_start: push_char,
147             length: token_len as u32,
148             token_type: token_index,
149             token_modifiers_bitset: modifier_bitset,
150         };
151
152         self.data.push(token);
153
154         self.prev_line = range.start.line as u32;
155         self.prev_char = range.start.character as u32;
156     }
157
158     pub(crate) fn build(self) -> SemanticTokens {
159         SemanticTokens { result_id: Some(self.id), data: self.data }
160     }
161 }
162
163 pub(crate) fn diff_tokens(old: &[SemanticToken], new: &[SemanticToken]) -> Vec<SemanticTokensEdit> {
164     let offset = new.iter().zip(old.iter()).take_while(|&(n, p)| n == p).count();
165
166     let (_, old) = old.split_at(offset);
167     let (_, new) = new.split_at(offset);
168
169     let offset_from_end =
170         new.iter().rev().zip(old.iter().rev()).take_while(|&(n, p)| n == p).count();
171
172     let (old, _) = old.split_at(old.len() - offset_from_end);
173     let (new, _) = new.split_at(new.len() - offset_from_end);
174
175     if old.is_empty() && new.is_empty() {
176         vec![]
177     } else {
178         // The lsp data field is actually a byte-diff but we
179         // travel in tokens so `start` and `delete_count` are in multiples of the
180         // serialized size of `SemanticToken`.
181         vec![SemanticTokensEdit {
182             start: 5 * offset as u32,
183             delete_count: 5 * old.len() as u32,
184             data: Some(new.into()),
185         }]
186     }
187 }
188
189 pub(crate) fn type_index(ty: SemanticTokenType) -> u32 {
190     SUPPORTED_TYPES.iter().position(|it| *it == ty).unwrap() as u32
191 }
192
193 #[cfg(test)]
194 mod tests {
195     use super::*;
196
197     fn from(t: (u32, u32, u32, u32, u32)) -> SemanticToken {
198         SemanticToken {
199             delta_line: t.0,
200             delta_start: t.1,
201             length: t.2,
202             token_type: t.3,
203             token_modifiers_bitset: t.4,
204         }
205     }
206
207     #[test]
208     fn test_diff_insert_at_end() {
209         let before = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
210         let after = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10)), from((11, 12, 13, 14, 15))];
211
212         let edits = diff_tokens(&before, &after);
213         assert_eq!(
214             edits[0],
215             SemanticTokensEdit {
216                 start: 10,
217                 delete_count: 0,
218                 data: Some(vec![from((11, 12, 13, 14, 15))])
219             }
220         );
221     }
222
223     #[test]
224     fn test_diff_insert_at_beginning() {
225         let before = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
226         let after = [from((11, 12, 13, 14, 15)), from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
227
228         let edits = diff_tokens(&before, &after);
229         assert_eq!(
230             edits[0],
231             SemanticTokensEdit {
232                 start: 0,
233                 delete_count: 0,
234                 data: Some(vec![from((11, 12, 13, 14, 15))])
235             }
236         );
237     }
238
239     #[test]
240     fn test_diff_insert_in_middle() {
241         let before = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
242         let after = [
243             from((1, 2, 3, 4, 5)),
244             from((10, 20, 30, 40, 50)),
245             from((60, 70, 80, 90, 100)),
246             from((6, 7, 8, 9, 10)),
247         ];
248
249         let edits = diff_tokens(&before, &after);
250         assert_eq!(
251             edits[0],
252             SemanticTokensEdit {
253                 start: 5,
254                 delete_count: 0,
255                 data: Some(vec![from((10, 20, 30, 40, 50)), from((60, 70, 80, 90, 100))])
256             }
257         );
258     }
259
260     #[test]
261     fn test_diff_remove_from_end() {
262         let before = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10)), from((11, 12, 13, 14, 15))];
263         let after = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
264
265         let edits = diff_tokens(&before, &after);
266         assert_eq!(edits[0], SemanticTokensEdit { start: 10, delete_count: 5, data: Some(vec![]) });
267     }
268
269     #[test]
270     fn test_diff_remove_from_beginning() {
271         let before = [from((11, 12, 13, 14, 15)), from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
272         let after = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
273
274         let edits = diff_tokens(&before, &after);
275         assert_eq!(edits[0], SemanticTokensEdit { start: 0, delete_count: 5, data: Some(vec![]) });
276     }
277
278     #[test]
279     fn test_diff_remove_from_middle() {
280         let before = [
281             from((1, 2, 3, 4, 5)),
282             from((10, 20, 30, 40, 50)),
283             from((60, 70, 80, 90, 100)),
284             from((6, 7, 8, 9, 10)),
285         ];
286         let after = [from((1, 2, 3, 4, 5)), from((6, 7, 8, 9, 10))];
287
288         let edits = diff_tokens(&before, &after);
289         assert_eq!(edits[0], SemanticTokensEdit { start: 5, delete_count: 10, data: Some(vec![]) });
290     }
291 }