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