]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide/src/syntax_highlighting.rs
Rollup merge of #99614 - RalfJung:transmute-is-not-memcpy, r=thomcc
[rust.git] / src / tools / rust-analyzer / crates / ide / src / syntax_highlighting.rs
1 pub(crate) mod tags;
2
3 mod highlights;
4 mod injector;
5
6 mod highlight;
7 mod format;
8 mod macro_;
9 mod inject;
10 mod escape;
11
12 mod html;
13 #[cfg(test)]
14 mod tests;
15
16 use hir::{Name, Semantics};
17 use ide_db::{FxHashMap, RootDatabase};
18 use syntax::{
19     ast, AstNode, AstToken, NodeOrToken, SyntaxKind::*, SyntaxNode, TextRange, WalkEvent, T,
20 };
21
22 use crate::{
23     syntax_highlighting::{
24         escape::highlight_escape_string, format::highlight_format_string, highlights::Highlights,
25         macro_::MacroHighlighter, tags::Highlight,
26     },
27     FileId, HlMod, HlTag,
28 };
29
30 pub(crate) use html::highlight_as_html;
31
32 #[derive(Debug, Clone, Copy)]
33 pub struct HlRange {
34     pub range: TextRange,
35     pub highlight: Highlight,
36     pub binding_hash: Option<u64>,
37 }
38
39 // Feature: Semantic Syntax Highlighting
40 //
41 // rust-analyzer highlights the code semantically.
42 // For example, `Bar` in `foo::Bar` might be colored differently depending on whether `Bar` is an enum or a trait.
43 // rust-analyzer does not specify colors directly, instead it assigns a tag (like `struct`) and a set of modifiers (like `declaration`) to each token.
44 // It's up to the client to map those to specific colors.
45 //
46 // The general rule is that a reference to an entity gets colored the same way as the entity itself.
47 // We also give special modifier for `mut` and `&mut` local variables.
48 //
49 //
50 // .Token Tags
51 //
52 // Rust-analyzer currently emits the following token tags:
53 //
54 // - For items:
55 // +
56 // [horizontal]
57 // attribute:: Emitted for attribute macros.
58 // enum:: Emitted for enums.
59 // function:: Emitted for free-standing functions.
60 // derive:: Emitted for derive macros.
61 // macro:: Emitted for function-like macros.
62 // method:: Emitted for associated functions, also knowns as methods.
63 // namespace:: Emitted for modules.
64 // struct:: Emitted for structs.
65 // trait:: Emitted for traits.
66 // typeAlias:: Emitted for type aliases and `Self` in `impl`s.
67 // union:: Emitted for unions.
68 //
69 // - For literals:
70 // +
71 // [horizontal]
72 // boolean:: Emitted for the boolean literals `true` and `false`.
73 // character:: Emitted for character literals.
74 // number:: Emitted for numeric literals.
75 // string:: Emitted for string literals.
76 // escapeSequence:: Emitted for escaped sequences inside strings like `\n`.
77 // formatSpecifier:: Emitted for format specifiers `{:?}` in `format!`-like macros.
78 //
79 // - For operators:
80 // +
81 // [horizontal]
82 // operator:: Emitted for general operators.
83 // arithmetic:: Emitted for the arithmetic operators `+`, `-`, `*`, `/`, `+=`, `-=`, `*=`, `/=`.
84 // bitwise:: Emitted for the bitwise operators `|`, `&`, `!`, `^`, `|=`, `&=`, `^=`.
85 // comparison:: Emitted for the comparison operators `>`, `<`, `==`, `>=`, `<=`, `!=`.
86 // logical:: Emitted for the logical operators `||`, `&&`, `!`.
87 //
88 // - For punctuation:
89 // +
90 // [horizontal]
91 // punctuation:: Emitted for general punctuation.
92 // attributeBracket:: Emitted for attribute invocation brackets, that is the `#[` and `]` tokens.
93 // angle:: Emitted for `<>` angle brackets.
94 // brace:: Emitted for `{}` braces.
95 // bracket:: Emitted for `[]` brackets.
96 // parenthesis:: Emitted for `()` parentheses.
97 // colon:: Emitted for the `:` token.
98 // comma:: Emitted for the `,` token.
99 // dot:: Emitted for the `.` token.
100 // semi:: Emitted for the `;` token.
101 // macroBang:: Emitted for the `!` token in macro calls.
102 //
103 // //-
104 //
105 // [horizontal]
106 // builtinAttribute:: Emitted for names to builtin attributes in attribute path, the `repr` in `#[repr(u8)]` for example.
107 // builtinType:: Emitted for builtin types like `u32`, `str` and `f32`.
108 // comment:: Emitted for comments.
109 // constParameter:: Emitted for const parameters.
110 // deriveHelper:: Emitted for derive helper attributes.
111 // enumMember:: Emitted for enum variants.
112 // generic:: Emitted for generic tokens that have no mapping.
113 // keyword:: Emitted for keywords.
114 // label:: Emitted for labels.
115 // lifetime:: Emitted for lifetimes.
116 // parameter:: Emitted for non-self function parameters.
117 // property:: Emitted for struct and union fields.
118 // selfKeyword:: Emitted for the self function parameter and self path-specifier.
119 // selfTypeKeyword:: Emitted for the Self type parameter.
120 // toolModule:: Emitted for tool modules.
121 // typeParameter:: Emitted for type parameters.
122 // unresolvedReference:: Emitted for unresolved references, names that rust-analyzer can't find the definition of.
123 // variable:: Emitted for locals, constants and statics.
124 //
125 //
126 // .Token Modifiers
127 //
128 // Token modifiers allow to style some elements in the source code more precisely.
129 //
130 // Rust-analyzer currently emits the following token modifiers:
131 //
132 // [horizontal]
133 // async:: Emitted for async functions and the `async` and `await` keywords.
134 // attribute:: Emitted for tokens inside attributes.
135 // callable:: Emitted for locals whose types implements one of the `Fn*` traits.
136 // constant:: Emitted for consts.
137 // consuming:: Emitted for locals that are being consumed when use in a function call.
138 // controlFlow:: Emitted for control-flow related tokens, this includes the `?` operator.
139 // crateRoot:: Emitted for crate names, like `serde` and `crate`.
140 // declaration:: Emitted for names of definitions, like `foo` in `fn foo() {}`.
141 // defaultLibrary:: Emitted for items from built-in crates (std, core, alloc, test and proc_macro).
142 // documentation:: Emitted for documentation comments.
143 // injected:: Emitted for doc-string injected highlighting like rust source blocks in documentation.
144 // intraDocLink:: Emitted for intra doc links in doc-strings.
145 // library:: Emitted for items that are defined outside of the current crate.
146 // mutable:: Emitted for mutable locals and statics as well as functions taking `&mut self`.
147 // public:: Emitted for items that are from the current crate and are `pub`.
148 // reference:: Emitted for locals behind a reference and functions taking `self` by reference.
149 // static:: Emitted for "static" functions, also known as functions that do not take a `self` param, as well as statics and consts.
150 // trait:: Emitted for associated trait items.
151 // unsafe:: Emitted for unsafe operations, like unsafe function calls, as well as the `unsafe` token.
152 //
153 //
154 // image::https://user-images.githubusercontent.com/48062697/113164457-06cfb980-9239-11eb-819b-0f93e646acf8.png[]
155 // image::https://user-images.githubusercontent.com/48062697/113187625-f7f50100-9250-11eb-825e-91c58f236071.png[]
156 pub(crate) fn highlight(
157     db: &RootDatabase,
158     file_id: FileId,
159     range_to_highlight: Option<TextRange>,
160     syntactic_name_ref_highlighting: bool,
161 ) -> Vec<HlRange> {
162     let _p = profile::span("highlight");
163     let sema = Semantics::new(db);
164
165     // Determine the root based on the given range.
166     let (root, range_to_highlight) = {
167         let source_file = sema.parse(file_id);
168         let source_file = source_file.syntax();
169         match range_to_highlight {
170             Some(range) => {
171                 let node = match source_file.covering_element(range) {
172                     NodeOrToken::Node(it) => it,
173                     NodeOrToken::Token(it) => it.parent().unwrap_or_else(|| source_file.clone()),
174                 };
175                 (node, range)
176             }
177             None => (source_file.clone(), source_file.text_range()),
178         }
179     };
180
181     let mut hl = highlights::Highlights::new(root.text_range());
182     let krate = match sema.scope(&root) {
183         Some(it) => it.krate(),
184         None => return hl.to_vec(),
185     };
186     traverse(
187         &mut hl,
188         &sema,
189         file_id,
190         &root,
191         krate,
192         range_to_highlight,
193         syntactic_name_ref_highlighting,
194     );
195     hl.to_vec()
196 }
197
198 fn traverse(
199     hl: &mut Highlights,
200     sema: &Semantics<'_, RootDatabase>,
201     file_id: FileId,
202     root: &SyntaxNode,
203     krate: hir::Crate,
204     range_to_highlight: TextRange,
205     syntactic_name_ref_highlighting: bool,
206 ) {
207     let is_unlinked = sema.to_module_def(file_id).is_none();
208     let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
209
210     enum AttrOrDerive {
211         Attr(ast::Item),
212         Derive(ast::Item),
213     }
214
215     impl AttrOrDerive {
216         fn item(&self) -> &ast::Item {
217             match self {
218                 AttrOrDerive::Attr(item) | AttrOrDerive::Derive(item) => item,
219             }
220         }
221     }
222
223     let mut tt_level = 0;
224     let mut attr_or_derive_item = None;
225     let mut current_macro: Option<ast::Macro> = None;
226     let mut macro_highlighter = MacroHighlighter::default();
227     let mut inside_attribute = false;
228
229     // Walk all nodes, keeping track of whether we are inside a macro or not.
230     // If in macro, expand it first and highlight the expanded code.
231     for event in root.preorder_with_tokens() {
232         use WalkEvent::{Enter, Leave};
233
234         let range = match &event {
235             Enter(it) | Leave(it) => it.text_range(),
236         };
237
238         // Element outside of the viewport, no need to highlight
239         if range_to_highlight.intersect(range).is_none() {
240             continue;
241         }
242
243         // set macro and attribute highlighting states
244         match event.clone() {
245             Enter(NodeOrToken::Node(node)) if ast::TokenTree::can_cast(node.kind()) => {
246                 tt_level += 1;
247             }
248             Leave(NodeOrToken::Node(node)) if ast::TokenTree::can_cast(node.kind()) => {
249                 tt_level -= 1;
250             }
251             Enter(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
252                 inside_attribute = true
253             }
254             Leave(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
255                 inside_attribute = false
256             }
257
258             Enter(NodeOrToken::Node(node)) if ast::Item::can_cast(node.kind()) => {
259                 match ast::Item::cast(node.clone()) {
260                     Some(ast::Item::MacroRules(mac)) => {
261                         macro_highlighter.init();
262                         current_macro = Some(mac.into());
263                         continue;
264                     }
265                     Some(ast::Item::MacroDef(mac)) => {
266                         macro_highlighter.init();
267                         current_macro = Some(mac.into());
268                         continue;
269                     }
270                     Some(item) => {
271                         if matches!(node.kind(), FN | CONST | STATIC) {
272                             bindings_shadow_count.clear();
273                         }
274
275                         if attr_or_derive_item.is_none() {
276                             if sema.is_attr_macro_call(&item) {
277                                 attr_or_derive_item = Some(AttrOrDerive::Attr(item));
278                             } else {
279                                 let adt = match item {
280                                     ast::Item::Enum(it) => Some(ast::Adt::Enum(it)),
281                                     ast::Item::Struct(it) => Some(ast::Adt::Struct(it)),
282                                     ast::Item::Union(it) => Some(ast::Adt::Union(it)),
283                                     _ => None,
284                                 };
285                                 match adt {
286                                     Some(adt) if sema.is_derive_annotated(&adt) => {
287                                         attr_or_derive_item =
288                                             Some(AttrOrDerive::Derive(ast::Item::from(adt)));
289                                     }
290                                     _ => (),
291                                 }
292                             }
293                         }
294                     }
295                     _ => (),
296                 }
297             }
298             Leave(NodeOrToken::Node(node)) if ast::Item::can_cast(node.kind()) => {
299                 match ast::Item::cast(node.clone()) {
300                     Some(ast::Item::MacroRules(mac)) => {
301                         assert_eq!(current_macro, Some(mac.into()));
302                         current_macro = None;
303                         macro_highlighter = MacroHighlighter::default();
304                     }
305                     Some(ast::Item::MacroDef(mac)) => {
306                         assert_eq!(current_macro, Some(mac.into()));
307                         current_macro = None;
308                         macro_highlighter = MacroHighlighter::default();
309                     }
310                     Some(item)
311                         if attr_or_derive_item.as_ref().map_or(false, |it| *it.item() == item) =>
312                     {
313                         attr_or_derive_item = None;
314                     }
315                     _ => (),
316                 }
317             }
318             _ => (),
319         }
320
321         let element = match event {
322             Enter(NodeOrToken::Token(tok)) if tok.kind() == WHITESPACE => continue,
323             Enter(it) => it,
324             Leave(NodeOrToken::Token(_)) => continue,
325             Leave(NodeOrToken::Node(node)) => {
326                 // Doc comment highlighting injection, we do this when leaving the node
327                 // so that we overwrite the highlighting of the doc comment itself.
328                 inject::doc_comment(hl, sema, file_id, &node);
329                 continue;
330             }
331         };
332
333         if current_macro.is_some() {
334             if let Some(tok) = element.as_token() {
335                 macro_highlighter.advance(tok);
336             }
337         }
338
339         let element = match element.clone() {
340             NodeOrToken::Node(n) => match ast::NameLike::cast(n) {
341                 Some(n) => NodeOrToken::Node(n),
342                 None => continue,
343             },
344             NodeOrToken::Token(t) => NodeOrToken::Token(t),
345         };
346         let token = element.as_token().cloned();
347
348         // Descending tokens into macros is expensive even if no descending occurs, so make sure
349         // that we actually are in a position where descending is possible.
350         let in_macro = tt_level > 0
351             || match attr_or_derive_item {
352                 Some(AttrOrDerive::Attr(_)) => true,
353                 Some(AttrOrDerive::Derive(_)) => inside_attribute,
354                 None => false,
355             };
356         let descended_element = if in_macro {
357             // Attempt to descend tokens into macro-calls.
358             match element {
359                 NodeOrToken::Token(token) if token.kind() != COMMENT => {
360                     let token = match attr_or_derive_item {
361                         Some(AttrOrDerive::Attr(_)) => {
362                             sema.descend_into_macros_with_kind_preference(token)
363                         }
364                         Some(AttrOrDerive::Derive(_)) | None => {
365                             sema.descend_into_macros_single(token)
366                         }
367                     };
368                     match token.parent().and_then(ast::NameLike::cast) {
369                         // Remap the token into the wrapping single token nodes
370                         Some(parent) => match (token.kind(), parent.syntax().kind()) {
371                             (T![self] | T![ident], NAME | NAME_REF) => NodeOrToken::Node(parent),
372                             (T![self] | T![super] | T![crate] | T![Self], NAME_REF) => {
373                                 NodeOrToken::Node(parent)
374                             }
375                             (INT_NUMBER, NAME_REF) => NodeOrToken::Node(parent),
376                             (LIFETIME_IDENT, LIFETIME) => NodeOrToken::Node(parent),
377                             _ => NodeOrToken::Token(token),
378                         },
379                         None => NodeOrToken::Token(token),
380                     }
381                 }
382                 e => e,
383             }
384         } else {
385             element
386         };
387
388         // FIXME: do proper macro def highlighting https://github.com/rust-lang/rust-analyzer/issues/6232
389         // Skip metavariables from being highlighted to prevent keyword highlighting in them
390         if descended_element.as_token().and_then(|t| macro_highlighter.highlight(t)).is_some() {
391             continue;
392         }
393
394         // string highlight injections, note this does not use the descended element as proc-macros
395         // can rewrite string literals which invalidates our indices
396         if let (Some(token), Some(descended_token)) = (token, descended_element.as_token()) {
397             if ast::String::can_cast(token.kind()) && ast::String::can_cast(descended_token.kind())
398             {
399                 let string = ast::String::cast(token);
400                 let string_to_highlight = ast::String::cast(descended_token.clone());
401                 if let Some((string, expanded_string)) = string.zip(string_to_highlight) {
402                     if string.is_raw() {
403                         if inject::ra_fixture(hl, sema, &string, &expanded_string).is_some() {
404                             continue;
405                         }
406                     }
407                     highlight_format_string(hl, &string, &expanded_string, range);
408                     highlight_escape_string(hl, &string, range.start());
409                 }
410             } else if ast::ByteString::can_cast(token.kind())
411                 && ast::ByteString::can_cast(descended_token.kind())
412             {
413                 if let Some(byte_string) = ast::ByteString::cast(token) {
414                     highlight_escape_string(hl, &byte_string, range.start());
415                 }
416             }
417         }
418
419         let element = match descended_element {
420             NodeOrToken::Node(name_like) => highlight::name_like(
421                 sema,
422                 krate,
423                 &mut bindings_shadow_count,
424                 syntactic_name_ref_highlighting,
425                 name_like,
426             ),
427             NodeOrToken::Token(token) => highlight::token(sema, token).zip(Some(None)),
428         };
429         if let Some((mut highlight, binding_hash)) = element {
430             if is_unlinked && highlight.tag == HlTag::UnresolvedReference {
431                 // do not emit unresolved references if the file is unlinked
432                 // let the editor do its highlighting for these tokens instead
433                 continue;
434             }
435             if highlight.tag == HlTag::UnresolvedReference
436                 && matches!(attr_or_derive_item, Some(AttrOrDerive::Derive(_)) if inside_attribute)
437             {
438                 // do not emit unresolved references in derive helpers if the token mapping maps to
439                 // something unresolvable. FIXME: There should be a way to prevent that
440                 continue;
441             }
442             if inside_attribute {
443                 highlight |= HlMod::Attribute
444             }
445
446             hl.add(HlRange { range, highlight, binding_hash });
447         }
448     }
449 }