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