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