]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide/src/syntax_highlighting.rs
Rollup merge of #99714 - ouz-a:issue_57961, r=oli-obk
[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::{InFile, 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 // enumMember:: Emitted for enum variants.
111 // generic:: Emitted for generic tokens that have no mapping.
112 // keyword:: Emitted for keywords.
113 // label:: Emitted for labels.
114 // lifetime:: Emitted for lifetimes.
115 // parameter:: Emitted for non-self function parameters.
116 // property:: Emitted for struct and union fields.
117 // selfKeyword:: Emitted for the self function parameter and self path-specifier.
118 // selfTypeKeyword:: Emitted for the Self type parameter.
119 // toolModule:: Emitted for tool modules.
120 // typeParameter:: Emitted for type parameters.
121 // unresolvedReference:: Emitted for unresolved references, names that rust-analyzer can't find the definition of.
122 // variable:: Emitted for locals, constants and statics.
123 //
124 //
125 // .Token Modifiers
126 //
127 // Token modifiers allow to style some elements in the source code more precisely.
128 //
129 // Rust-analyzer currently emits the following token modifiers:
130 //
131 // [horizontal]
132 // async:: Emitted for async functions and the `async` and `await` keywords.
133 // attribute:: Emitted for tokens inside attributes.
134 // callable:: Emitted for locals whose types implements one of the `Fn*` traits.
135 // constant:: Emitted for consts.
136 // consuming:: Emitted for locals that are being consumed when use in a function call.
137 // controlFlow:: Emitted for control-flow related tokens, this includes the `?` operator.
138 // crateRoot:: Emitted for crate names, like `serde` and `crate`.
139 // declaration:: Emitted for names of definitions, like `foo` in `fn foo() {}`.
140 // defaultLibrary:: Emitted for items from built-in crates (std, core, alloc, test and proc_macro).
141 // documentation:: Emitted for documentation comments.
142 // injected:: Emitted for doc-string injected highlighting like rust source blocks in documentation.
143 // intraDocLink:: Emitted for intra doc links in doc-strings.
144 // library:: Emitted for items that are defined outside of the current crate.
145 // mutable:: Emitted for mutable locals and statics as well as functions taking `&mut self`.
146 // public:: Emitted for items that are from the current crate and are `pub`.
147 // reference:: Emitted for locals behind a reference and functions taking `self` by reference.
148 // static:: Emitted for "static" functions, also known as functions that do not take a `self` param, as well as statics and consts.
149 // trait:: Emitted for associated trait items.
150 // unsafe:: Emitted for unsafe operations, like unsafe function calls, as well as the `unsafe` token.
151 //
152 //
153 // image::https://user-images.githubusercontent.com/48062697/113164457-06cfb980-9239-11eb-819b-0f93e646acf8.png[]
154 // image::https://user-images.githubusercontent.com/48062697/113187625-f7f50100-9250-11eb-825e-91c58f236071.png[]
155 pub(crate) fn highlight(
156     db: &RootDatabase,
157     file_id: FileId,
158     range_to_highlight: Option<TextRange>,
159     syntactic_name_ref_highlighting: bool,
160 ) -> Vec<HlRange> {
161     let _p = profile::span("highlight");
162     let sema = Semantics::new(db);
163
164     // Determine the root based on the given range.
165     let (root, range_to_highlight) = {
166         let source_file = sema.parse(file_id);
167         let source_file = source_file.syntax();
168         match range_to_highlight {
169             Some(range) => {
170                 let node = match source_file.covering_element(range) {
171                     NodeOrToken::Node(it) => it,
172                     NodeOrToken::Token(it) => it.parent().unwrap_or_else(|| source_file.clone()),
173                 };
174                 (node, range)
175             }
176             None => (source_file.clone(), source_file.text_range()),
177         }
178     };
179
180     let mut hl = highlights::Highlights::new(root.text_range());
181     let krate = match sema.scope(&root) {
182         Some(it) => it.krate(),
183         None => return hl.to_vec(),
184     };
185     traverse(
186         &mut hl,
187         &sema,
188         file_id,
189         &root,
190         krate,
191         range_to_highlight,
192         syntactic_name_ref_highlighting,
193     );
194     hl.to_vec()
195 }
196
197 fn traverse(
198     hl: &mut Highlights,
199     sema: &Semantics<'_, RootDatabase>,
200     file_id: FileId,
201     root: &SyntaxNode,
202     krate: hir::Crate,
203     range_to_highlight: TextRange,
204     syntactic_name_ref_highlighting: bool,
205 ) {
206     let is_unlinked = sema.to_module_def(file_id).is_none();
207     let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
208
209     enum AttrOrDerive {
210         Attr(ast::Item),
211         Derive(ast::Item),
212     }
213
214     impl AttrOrDerive {
215         fn item(&self) -> &ast::Item {
216             match self {
217                 AttrOrDerive::Attr(item) | AttrOrDerive::Derive(item) => item,
218             }
219         }
220     }
221
222     let mut tt_level = 0;
223     let mut attr_or_derive_item = None;
224     let mut current_macro: Option<ast::Macro> = None;
225     let mut macro_highlighter = MacroHighlighter::default();
226     let mut inside_attribute = false;
227
228     // Walk all nodes, keeping track of whether we are inside a macro or not.
229     // If in macro, expand it first and highlight the expanded code.
230     for event in root.preorder_with_tokens() {
231         use WalkEvent::{Enter, Leave};
232
233         let range = match &event {
234             Enter(it) | Leave(it) => it.text_range(),
235         };
236
237         // Element outside of the viewport, no need to highlight
238         if range_to_highlight.intersect(range).is_none() {
239             continue;
240         }
241
242         // set macro and attribute highlighting states
243         match event.clone() {
244             Enter(NodeOrToken::Node(node)) if ast::TokenTree::can_cast(node.kind()) => {
245                 tt_level += 1;
246             }
247             Leave(NodeOrToken::Node(node)) if ast::TokenTree::can_cast(node.kind()) => {
248                 tt_level -= 1;
249             }
250             Enter(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
251                 inside_attribute = true
252             }
253             Leave(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
254                 inside_attribute = false
255             }
256
257             Enter(NodeOrToken::Node(node)) if ast::Item::can_cast(node.kind()) => {
258                 match ast::Item::cast(node.clone()) {
259                     Some(ast::Item::MacroRules(mac)) => {
260                         macro_highlighter.init();
261                         current_macro = Some(mac.into());
262                         continue;
263                     }
264                     Some(ast::Item::MacroDef(mac)) => {
265                         macro_highlighter.init();
266                         current_macro = Some(mac.into());
267                         continue;
268                     }
269                     Some(item) => {
270                         if matches!(node.kind(), FN | CONST | STATIC) {
271                             bindings_shadow_count.clear();
272                         }
273
274                         if attr_or_derive_item.is_none() {
275                             if sema.is_attr_macro_call(&item) {
276                                 attr_or_derive_item = Some(AttrOrDerive::Attr(item));
277                             } else {
278                                 let adt = match item {
279                                     ast::Item::Enum(it) => Some(ast::Adt::Enum(it)),
280                                     ast::Item::Struct(it) => Some(ast::Adt::Struct(it)),
281                                     ast::Item::Union(it) => Some(ast::Adt::Union(it)),
282                                     _ => None,
283                                 };
284                                 match adt {
285                                     Some(adt) if sema.is_derive_annotated(&adt) => {
286                                         attr_or_derive_item =
287                                             Some(AttrOrDerive::Derive(ast::Item::from(adt)));
288                                     }
289                                     _ => (),
290                                 }
291                             }
292                         }
293                     }
294                     _ => (),
295                 }
296             }
297             Leave(NodeOrToken::Node(node)) if ast::Item::can_cast(node.kind()) => {
298                 match ast::Item::cast(node.clone()) {
299                     Some(ast::Item::MacroRules(mac)) => {
300                         assert_eq!(current_macro, Some(mac.into()));
301                         current_macro = None;
302                         macro_highlighter = MacroHighlighter::default();
303                     }
304                     Some(ast::Item::MacroDef(mac)) => {
305                         assert_eq!(current_macro, Some(mac.into()));
306                         current_macro = None;
307                         macro_highlighter = MacroHighlighter::default();
308                     }
309                     Some(item)
310                         if attr_or_derive_item.as_ref().map_or(false, |it| *it.item() == item) =>
311                     {
312                         attr_or_derive_item = None;
313                     }
314                     _ => (),
315                 }
316             }
317             _ => (),
318         }
319
320         let element = match event {
321             Enter(NodeOrToken::Token(tok)) if tok.kind() == WHITESPACE => continue,
322             Enter(it) => it,
323             Leave(NodeOrToken::Token(_)) => continue,
324             Leave(NodeOrToken::Node(node)) => {
325                 // Doc comment highlighting injection, we do this when leaving the node
326                 // so that we overwrite the highlighting of the doc comment itself.
327                 inject::doc_comment(hl, sema, InFile::new(file_id.into(), &node));
328                 continue;
329             }
330         };
331
332         if current_macro.is_some() {
333             if let Some(tok) = element.as_token() {
334                 macro_highlighter.advance(tok);
335             }
336         }
337
338         let element = match element.clone() {
339             NodeOrToken::Node(n) => match ast::NameLike::cast(n) {
340                 Some(n) => NodeOrToken::Node(n),
341                 None => continue,
342             },
343             NodeOrToken::Token(t) => NodeOrToken::Token(t),
344         };
345         let token = element.as_token().cloned();
346
347         // Descending tokens into macros is expensive even if no descending occurs, so make sure
348         // that we actually are in a position where descending is possible.
349         let in_macro = tt_level > 0
350             || match attr_or_derive_item {
351                 Some(AttrOrDerive::Attr(_)) => true,
352                 Some(AttrOrDerive::Derive(_)) => inside_attribute,
353                 None => false,
354             };
355         let descended_element = if in_macro {
356             // Attempt to descend tokens into macro-calls.
357             match element {
358                 NodeOrToken::Token(token) if token.kind() != COMMENT => {
359                     let token = match attr_or_derive_item {
360                         Some(AttrOrDerive::Attr(_)) => {
361                             sema.descend_into_macros_with_kind_preference(token)
362                         }
363                         Some(AttrOrDerive::Derive(_)) | None => {
364                             sema.descend_into_macros_single(token)
365                         }
366                     };
367                     match token.parent().and_then(ast::NameLike::cast) {
368                         // Remap the token into the wrapping single token nodes
369                         Some(parent) => match (token.kind(), parent.syntax().kind()) {
370                             (T![self] | T![ident], NAME | NAME_REF) => NodeOrToken::Node(parent),
371                             (T![self] | T![super] | T![crate] | T![Self], NAME_REF) => {
372                                 NodeOrToken::Node(parent)
373                             }
374                             (INT_NUMBER, NAME_REF) => NodeOrToken::Node(parent),
375                             (LIFETIME_IDENT, LIFETIME) => NodeOrToken::Node(parent),
376                             _ => NodeOrToken::Token(token),
377                         },
378                         None => NodeOrToken::Token(token),
379                     }
380                 }
381                 e => e,
382             }
383         } else {
384             element
385         };
386
387         // FIXME: do proper macro def highlighting https://github.com/rust-lang/rust-analyzer/issues/6232
388         // Skip metavariables from being highlighted to prevent keyword highlighting in them
389         if descended_element.as_token().and_then(|t| macro_highlighter.highlight(t)).is_some() {
390             continue;
391         }
392
393         // string highlight injections, note this does not use the descended element as proc-macros
394         // can rewrite string literals which invalidates our indices
395         if let (Some(token), Some(descended_token)) = (token, descended_element.as_token()) {
396             if ast::String::can_cast(token.kind()) && ast::String::can_cast(descended_token.kind())
397             {
398                 let string = ast::String::cast(token);
399                 let string_to_highlight = ast::String::cast(descended_token.clone());
400                 if let Some((string, expanded_string)) = string.zip(string_to_highlight) {
401                     if string.is_raw() {
402                         if inject::ra_fixture(hl, sema, &string, &expanded_string).is_some() {
403                             continue;
404                         }
405                     }
406                     highlight_format_string(hl, &string, &expanded_string, range);
407                     highlight_escape_string(hl, &string, range.start());
408                 }
409             } else if ast::ByteString::can_cast(token.kind())
410                 && ast::ByteString::can_cast(descended_token.kind())
411             {
412                 if let Some(byte_string) = ast::ByteString::cast(token) {
413                     highlight_escape_string(hl, &byte_string, range.start());
414                 }
415             }
416         }
417
418         let element = match descended_element {
419             NodeOrToken::Node(name_like) => highlight::name_like(
420                 sema,
421                 krate,
422                 &mut bindings_shadow_count,
423                 syntactic_name_ref_highlighting,
424                 name_like,
425             ),
426             NodeOrToken::Token(token) => highlight::token(sema, token).zip(Some(None)),
427         };
428         if let Some((mut highlight, binding_hash)) = element {
429             if is_unlinked && highlight.tag == HlTag::UnresolvedReference {
430                 // do not emit unresolved references if the file is unlinked
431                 // let the editor do its highlighting for these tokens instead
432                 continue;
433             }
434             if inside_attribute {
435                 highlight |= HlMod::Attribute
436             }
437
438             hl.add(HlRange { range, highlight, binding_hash });
439         }
440     }
441 }