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