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