]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/syntax_highlighting.rs
internal: Handle macro calls better in highlighting
[rust.git] / 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
11 mod html;
12 #[cfg(test)]
13 mod tests;
14
15 use hir::{InFile, Name, Semantics};
16 use ide_db::RootDatabase;
17 use rustc_hash::FxHashMap;
18 use syntax::{
19     ast::{self, HasFormatSpecifier},
20     AstNode, AstToken, NodeOrToken,
21     SyntaxKind::*,
22     SyntaxNode, TextRange, WalkEvent, T,
23 };
24
25 use crate::{
26     syntax_highlighting::{
27         format::highlight_format_string, highlights::Highlights, macro_::MacroHighlighter,
28         tags::Highlight,
29     },
30     FileId, HlMod, HlTag,
31 };
32
33 pub(crate) use html::highlight_as_html;
34
35 #[derive(Debug, Clone, Copy)]
36 pub struct HlRange {
37     pub range: TextRange,
38     pub highlight: Highlight,
39     pub binding_hash: Option<u64>,
40 }
41
42 // Feature: Semantic Syntax Highlighting
43 //
44 // rust-analyzer highlights the code semantically.
45 // For example, `Bar` in `foo::Bar` might be colored differently depending on whether `Bar` is an enum or a trait.
46 // rust-analyzer does not specify colors directly, instead it assigns a tag (like `struct`) and a set of modifiers (like `declaration`) to each token.
47 // It's up to the client to map those to specific colors.
48 //
49 // The general rule is that a reference to an entity gets colored the same way as the entity itself.
50 // We also give special modifier for `mut` and `&mut` local variables.
51 //
52 //
53 // .Token Tags
54 //
55 // Rust-analyzer currently emits the following token tags:
56 //
57 // - For items:
58 // +
59 // [horizontal]
60 // attribute:: Emitted for attribute macros.
61 // enum:: Emitted for enums.
62 // function:: Emitted for free-standing functions.
63 // derive:: Emitted for derive macros.
64 // macro:: Emitted for function-like macros.
65 // method:: Emitted for associated functions, also knowns as methods.
66 // namespace:: Emitted for modules.
67 // struct:: Emitted for structs.
68 // trait:: Emitted for traits.
69 // typeAlias:: Emitted for type aliases and `Self` in `impl`s.
70 // union:: Emitted for unions.
71 //
72 // - For literals:
73 // +
74 // [horizontal]
75 // boolean:: Emitted for the boolean literals `true` and `false`.
76 // character:: Emitted for character literals.
77 // number:: Emitted for numeric literals.
78 // string:: Emitted for string literals.
79 // escapeSequence:: Emitted for escaped sequences inside strings like `\n`.
80 // formatSpecifier:: Emitted for format specifiers `{:?}` in `format!`-like macros.
81 //
82 // - For operators:
83 // +
84 // [horizontal]
85 // operator:: Emitted for general operators.
86 // arithmetic:: Emitted for the arithmetic operators `+`, `-`, `*`, `/`, `+=`, `-=`, `*=`, `/=`.
87 // bitwise:: Emitted for the bitwise operators `|`, `&`, `!`, `^`, `|=`, `&=`, `^=`.
88 // comparison:: Emitted for the comparison operators `>`, `<`, `==`, `>=`, `<=`, `!=`.
89 // logical:: Emitted for the logical operators `||`, `&&`, `!`.
90 //
91 // - For punctuation:
92 // +
93 // [horizontal]
94 // punctuation:: Emitted for general punctuation.
95 // attributeBracket:: Emitted for attribute invocation brackets, that is the `#[` and `]` tokens.
96 // angle:: Emitted for `<>` angle brackets.
97 // brace:: Emitted for `{}` braces.
98 // bracket:: Emitted for `[]` brackets.
99 // parenthesis:: Emitted for `()` parentheses.
100 // colon:: Emitted for the `:` token.
101 // comma:: Emitted for the `,` token.
102 // dot:: Emitted for the `.` token.
103 // semi:: Emitted for the `;` token.
104 // macroBang:: Emitted for the `!` token in macro calls.
105 //
106 // //-
107 //
108 // [horizontal]
109 // builtinAttribute:: Emitted for names to builtin attributes in attribute path, the `repr` in `#[repr(u8)]` for example.
110 // builtinType:: Emitted for builtin types like `u32`, `str` and `f32`.
111 // comment:: Emitted for comments.
112 // constParameter:: Emitted for const parameters.
113 // enumMember:: Emitted for enum variants.
114 // generic:: Emitted for generic tokens that have no mapping.
115 // keyword:: Emitted for keywords.
116 // label:: Emitted for labels.
117 // lifetime:: Emitted for lifetimes.
118 // parameter:: Emitted for non-self function parameters.
119 // property:: Emitted for struct and union fields.
120 // selfKeyword:: Emitted for the self function parameter and self path-specifier.
121 // toolModule:: Emitted for tool modules.
122 // typeParameter:: Emitted for type parameters.
123 // unresolvedReference:: Emitted for unresolved references, names that rust-analyzer can't find the definition of.
124 // variable:: Emitted for locals, constants and statics.
125 //
126 //
127 // .Token Modifiers
128 //
129 // Token modifiers allow to style some elements in the source code more precisely.
130 //
131 // Rust-analyzer currently emits the following token modifiers:
132 //
133 // [horizontal]
134 // async:: Emitted for async functions and the `async` and `await` keywords.
135 // attribute:: Emitted for tokens inside attributes.
136 // callable:: Emitted for locals whose types implements one of the `Fn*` traits.
137 // constant:: Emitted for consts.
138 // consuming:: Emitted for locals that are being consumed when use in a function call.
139 // controlFlow:: Emitted for control-flow related tokens, this includes the `?` operator.
140 // crateRoot:: Emitted for crate names, like `serde` and `crate`.
141 // declaration:: Emitted for names of definitions, like `foo` in `fn foo() {}`.
142 // defaultLibrary:: Emitted for items from built-in crates (std, core, alloc, test and proc_macro).
143 // documentation:: Emitted for documentation comments.
144 // injected:: Emitted for doc-string injected highlighting like rust source blocks in documentation.
145 // intraDocLink:: Emitted for intra doc links in doc-strings.
146 // library:: Emitted for items that are defined outside of the current crate.
147 // mutable:: Emitted for mutable locals and statics as well as functions taking `&mut self`.
148 // public:: Emitted for items that are from the current crate and are `pub`.
149 // reference:: Emitted for locals behind a reference and functions taking `self` by reference.
150 // static:: Emitted for "static" functions, also known as functions that do not take a `self` param, as well as statics and consts.
151 // trait:: Emitted for associated trait items.
152 // unsafe:: Emitted for unsafe operations, like unsafe function calls, as well as the `unsafe` token.
153 //
154 //
155 // image::https://user-images.githubusercontent.com/48062697/113164457-06cfb980-9239-11eb-819b-0f93e646acf8.png[]
156 // image::https://user-images.githubusercontent.com/48062697/113187625-f7f50100-9250-11eb-825e-91c58f236071.png[]
157 pub(crate) fn highlight(
158     db: &RootDatabase,
159     file_id: FileId,
160     range_to_highlight: Option<TextRange>,
161     syntactic_name_ref_highlighting: bool,
162 ) -> Vec<HlRange> {
163     let _p = profile::span("highlight");
164     let sema = Semantics::new(db);
165
166     // Determine the root based on the given range.
167     let (root, range_to_highlight) = {
168         let source_file = sema.parse(file_id);
169         let source_file = source_file.syntax();
170         match range_to_highlight {
171             Some(range) => {
172                 let node = match source_file.covering_element(range) {
173                     NodeOrToken::Node(it) => it,
174                     NodeOrToken::Token(it) => it.parent().unwrap_or_else(|| source_file.clone()),
175                 };
176                 (node, range)
177             }
178             None => (source_file.clone(), source_file.text_range()),
179         }
180     };
181
182     let mut hl = highlights::Highlights::new(root.text_range());
183     traverse(
184         &mut hl,
185         &sema,
186         InFile::new(file_id.into(), &root),
187         sema.scope(&root).krate(),
188         range_to_highlight,
189         syntactic_name_ref_highlighting,
190     );
191     hl.to_vec()
192 }
193
194 fn traverse(
195     hl: &mut Highlights,
196     sema: &Semantics<RootDatabase>,
197     root: InFile<&SyntaxNode>,
198     krate: Option<hir::Crate>,
199     range_to_highlight: TextRange,
200     syntactic_name_ref_highlighting: bool,
201 ) {
202     let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
203
204     let mut current_macro_call: Option<ast::MacroCall> = None;
205     let mut current_attr_call = None;
206     let mut current_macro: Option<ast::Macro> = None;
207     let mut macro_highlighter = MacroHighlighter::default();
208     let mut inside_attribute = false;
209
210     // Walk all nodes, keeping track of whether we are inside a macro or not.
211     // If in macro, expand it first and highlight the expanded code.
212     for event in root.value.preorder_with_tokens() {
213         let range = match &event {
214             WalkEvent::Enter(it) | WalkEvent::Leave(it) => it.text_range(),
215         };
216
217         // Element outside of the viewport, no need to highlight
218         if range_to_highlight.intersect(range).is_none() {
219             continue;
220         }
221
222         // set macro and attribute highlighting states
223         match event.clone() {
224             WalkEvent::Enter(NodeOrToken::Node(node)) => match ast::Item::cast(node.clone()) {
225                 Some(ast::Item::MacroCall(mcall)) => {
226                     current_macro_call = Some(mcall);
227                     continue;
228                 }
229                 Some(ast::Item::MacroRules(mac)) => {
230                     macro_highlighter.init();
231                     current_macro = Some(mac.into());
232                     continue;
233                 }
234                 Some(ast::Item::MacroDef(mac)) => {
235                     macro_highlighter.init();
236                     current_macro = Some(mac.into());
237                     continue;
238                 }
239                 Some(item) if sema.is_attr_macro_call(&item) => current_attr_call = Some(item),
240                 None if ast::Attr::can_cast(node.kind()) => inside_attribute = true,
241                 _ => (),
242             },
243             WalkEvent::Leave(NodeOrToken::Node(node)) => match ast::Item::cast(node.clone()) {
244                 Some(ast::Item::MacroCall(mcall)) => {
245                     assert_eq!(current_macro_call, Some(mcall));
246                     current_macro_call = None;
247                 }
248                 Some(ast::Item::MacroRules(mac)) => {
249                     assert_eq!(current_macro, Some(mac.into()));
250                     current_macro = None;
251                     macro_highlighter = MacroHighlighter::default();
252                 }
253                 Some(ast::Item::MacroDef(mac)) => {
254                     assert_eq!(current_macro, Some(mac.into()));
255                     current_macro = None;
256                     macro_highlighter = MacroHighlighter::default();
257                 }
258                 Some(item) if current_attr_call.as_ref().map_or(false, |it| *it == item) => {
259                     current_attr_call = None
260                 }
261                 None if ast::Attr::can_cast(node.kind()) => inside_attribute = false,
262                 _ => (),
263             },
264             _ => (),
265         }
266
267         let element = match event {
268             WalkEvent::Enter(it) => it,
269             WalkEvent::Leave(NodeOrToken::Token(_)) => continue,
270             WalkEvent::Leave(NodeOrToken::Node(node)) => {
271                 inject::doc_comment(hl, sema, root.with_value(&node));
272                 continue;
273             }
274         };
275
276         if current_macro.is_some() {
277             if let Some(tok) = element.as_token() {
278                 macro_highlighter.advance(tok);
279             }
280         }
281
282         // only attempt to descend if we are inside a macro call or attribute
283         // as calling `descend_into_macros_single` gets rather expensive if done for every single token
284         let descend_token = current_macro_call.is_some() || current_attr_call.is_some();
285         let element_to_highlight = if descend_token {
286             let token = match &element {
287                 NodeOrToken::Node(_) => continue,
288                 NodeOrToken::Token(tok) => tok.clone(),
289             };
290             let in_mcall_outside_tt = current_macro_call.is_some()
291                 && token.parent().as_ref().map(SyntaxNode::kind) != Some(TOKEN_TREE);
292             let token = match in_mcall_outside_tt {
293                 // not in the macros token tree, don't attempt to descend
294                 true => token,
295                 false => sema.descend_into_macros_single(token),
296             };
297             match token.parent() {
298                 Some(parent) => {
299                     // Names and NameRefs have special semantics, use them instead of the tokens
300                     // as otherwise we won't ever visit them
301                     match (token.kind(), parent.kind()) {
302                         (T![ident], NAME | NAME_REF) => parent.into(),
303                         (T![self] | T![super] | T![crate], NAME_REF) => parent.into(),
304                         (INT_NUMBER, NAME_REF) => parent.into(),
305                         _ => token.into(),
306                     }
307                 }
308                 None => token.into(),
309             }
310         } else {
311             element.clone()
312         };
313
314         // FIXME: do proper macro def highlighting https://github.com/rust-analyzer/rust-analyzer/issues/6232
315         // Skip metavariables from being highlighted to prevent keyword highlighting in them
316         if macro_highlighter.highlight(&element_to_highlight).is_some() {
317             continue;
318         }
319
320         // string highlight injections, note this does not use the descended element as proc-macros
321         // can rewrite string literals which invalidates our indices
322         if let (Some(token), Some(token_to_highlight)) =
323             (element.into_token(), element_to_highlight.as_token())
324         {
325             let string = ast::String::cast(token);
326             let string_to_highlight = ast::String::cast(token_to_highlight.clone());
327             if let Some((string, expanded_string)) = string.zip(string_to_highlight) {
328                 if string.is_raw() {
329                     if inject::ra_fixture(hl, sema, &string, &expanded_string).is_some() {
330                         continue;
331                     }
332                 }
333                 highlight_format_string(hl, &string, &expanded_string, range);
334                 // Highlight escape sequences
335                 if let Some(char_ranges) = string.char_ranges() {
336                     for (piece_range, _) in char_ranges.iter().filter(|(_, char)| char.is_ok()) {
337                         if string.text()[piece_range.start().into()..].starts_with('\\') {
338                             hl.add(HlRange {
339                                 range: piece_range + range.start(),
340                                 highlight: HlTag::EscapeSequence.into(),
341                                 binding_hash: None,
342                             });
343                         }
344                     }
345                 }
346             }
347         }
348
349         // do the normal highlighting
350         let element = highlight::element(
351             sema,
352             krate,
353             &mut bindings_shadow_count,
354             syntactic_name_ref_highlighting,
355             element_to_highlight,
356         );
357         if let Some((mut highlight, binding_hash)) = element {
358             if inside_attribute {
359                 highlight |= HlMod::Attribute
360             }
361
362             hl.add(HlRange { range, highlight, binding_hash });
363         }
364     }
365 }