]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/syntax_highlighting.rs
Merge #10921
[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, SymbolKind};
17 use rustc_hash::FxHashMap;
18 use syntax::{
19     ast::{self, HasFormatSpecifier},
20     match_ast, AstNode, AstToken, Direction, 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 // enum:: Emitted for enums.
61 // function:: Emitted for free-standing functions.
62 // macro:: Emitted for macros.
63 // method:: Emitted for associated functions, also knowns as methods.
64 // namespace:: Emitted for modules.
65 // struct:: Emitted for structs.
66 // trait:: Emitted for traits.
67 // typeAlias:: Emitted for type aliases and `Self` in `impl`s.
68 // union:: Emitted for unions.
69 //
70 // - For literals:
71 // +
72 // [horizontal]
73 // boolean:: Emitted for the boolean literals `true` and `false`.
74 // character:: Emitted for character literals.
75 // number:: Emitted for numeric literals.
76 // string:: Emitted for string literals.
77 // escapeSequence:: Emitted for escaped sequences inside strings like `\n`.
78 // formatSpecifier:: Emitted for format specifiers `{:?}` in `format!`-like macros.
79 //
80 // - For operators:
81 // +
82 // [horizontal]
83 // operator:: Emitted for general operators.
84 // arithmetic:: Emitted for the arithmetic operators `+`, `-`, `*`, `/`, `+=`, `-=`, `*=`, `/=`.
85 // bitwise:: Emitted for the bitwise operators `|`, `&`, `!`, `^`, `|=`, `&=`, `^=`.
86 // comparison:: Emitted for the comparison operators `>`, `<`, `==`, `>=`, `<=`, `!=`.
87 // logical:: Emitted for the logical operators `||`, `&&`, `!`.
88 //
89 // - For punctuation:
90 // +
91 // [horizontal]
92 // punctuation:: Emitted for general punctuation.
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 //
102 // //-
103 //
104 // [horizontal]
105 // attribute:: Emitted for the `#[` `]` tokens.
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 // toolModule:: Emitted for tool modules.
119 // typeParameter:: Emitted for type parameters.
120 // unresolvedReference:: Emitted for unresolved references, names that rust-analyzer can't find the definition of.
121 // variable:: Emitted for locals, constants and statics.
122 //
123 //
124 // .Token Modifiers
125 //
126 // Token modifiers allow to style some elements in the source code more precisely.
127 //
128 // Rust-analyzer currently emits the following token modifiers:
129 //
130 // [horizontal]
131 // async:: Emitted for async functions and the `async` and `await` keywords.
132 // attribute:: Emitted for tokens inside attributes.
133 // callable:: Emitted for locals whose types implements one of the `Fn*` traits.
134 // constant:: Emitted for consts.
135 // consuming:: Emitted for locals that are being consumed when use in a function call.
136 // controlFlow:: Emitted for control-flow related tokens, this includes the `?` operator.
137 // crateRoot:: Emitted for crate names, like `serde` and `crate`.
138 // declaration:: Emitted for names of definitions, like `foo` in `fn foo() {}`.
139 // defaultLibrary:: Emitted for items from built-in crates (std, core, alloc, test and proc_macro).
140 // documentation:: Emitted for documentation comments.
141 // injected:: Emitted for doc-string injected highlighting like rust source blocks in documentation.
142 // intraDocLink:: Emitted for intra doc links in doc-strings.
143 // library:: Emitted for items that are defined outside of the current crate.
144 // mutable:: Emitted for mutable locals and statics as well as functions taking `&mut self`.
145 // public:: Emitted for items that are from the current crate and are `pub`.
146 // reference:: Emitted for locals behind a reference and functions taking `self` by reference.
147 // static:: Emitted for "static" functions, also known as functions that do not take a `self` param, as well as statics and consts.
148 // trait:: Emitted for associated trait items.
149 // unsafe:: Emitted for unsafe operations, like unsafe function calls, as well as the `unsafe` token.
150 //
151 //
152 // image::https://user-images.githubusercontent.com/48062697/113164457-06cfb980-9239-11eb-819b-0f93e646acf8.png[]
153 // image::https://user-images.githubusercontent.com/48062697/113187625-f7f50100-9250-11eb-825e-91c58f236071.png[]
154 pub(crate) fn highlight(
155     db: &RootDatabase,
156     file_id: FileId,
157     range_to_highlight: Option<TextRange>,
158     syntactic_name_ref_highlighting: bool,
159 ) -> Vec<HlRange> {
160     let _p = profile::span("highlight");
161     let sema = Semantics::new(db);
162
163     // Determine the root based on the given range.
164     let (root, range_to_highlight) = {
165         let source_file = sema.parse(file_id);
166         let source_file = source_file.syntax();
167         match range_to_highlight {
168             Some(range) => {
169                 let node = match source_file.covering_element(range) {
170                     NodeOrToken::Node(it) => it,
171                     NodeOrToken::Token(it) => it.parent().unwrap_or_else(|| source_file.clone()),
172                 };
173                 (node, range)
174             }
175             None => (source_file.clone(), source_file.text_range()),
176         }
177     };
178
179     let mut hl = highlights::Highlights::new(root.text_range());
180     traverse(
181         &mut hl,
182         &sema,
183         InFile::new(file_id.into(), &root),
184         sema.scope(&root).krate(),
185         range_to_highlight,
186         syntactic_name_ref_highlighting,
187     );
188     hl.to_vec()
189 }
190
191 fn traverse(
192     hl: &mut Highlights,
193     sema: &Semantics<RootDatabase>,
194     root: InFile<&SyntaxNode>,
195     krate: Option<hir::Crate>,
196     range_to_highlight: TextRange,
197     syntactic_name_ref_highlighting: bool,
198 ) {
199     let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
200
201     let mut current_macro_call: Option<ast::MacroCall> = None;
202     let mut current_attr_call = None;
203     let mut current_macro: Option<ast::Macro> = None;
204     let mut macro_highlighter = MacroHighlighter::default();
205     let mut inside_attribute = false;
206
207     // Walk all nodes, keeping track of whether we are inside a macro or not.
208     // If in macro, expand it first and highlight the expanded code.
209     for event in root.value.preorder_with_tokens() {
210         let event_range = match &event {
211             WalkEvent::Enter(it) | WalkEvent::Leave(it) => it.text_range(),
212         };
213
214         // Element outside of the viewport, no need to highlight
215         if range_to_highlight.intersect(event_range).is_none() {
216             continue;
217         }
218
219         match event.clone() {
220             WalkEvent::Enter(NodeOrToken::Node(node)) => {
221                 match_ast! {
222                     match node {
223                         ast::MacroCall(mcall) => {
224                             if let Some(range) = macro_call_range(&mcall) {
225                                 hl.add(HlRange {
226                                     range,
227                                     highlight: HlTag::Symbol(SymbolKind::Macro).into(),
228                                     binding_hash: None,
229                                 });
230                             }
231                             current_macro_call = Some(mcall);
232                             continue;
233                         },
234                         ast::Macro(mac) => {
235                             macro_highlighter.init();
236                             current_macro = Some(mac);
237                             continue;
238                         },
239                         ast::Item(item) => {
240                             if sema.is_attr_macro_call(&item) {
241                                 current_attr_call = Some(item);
242                             }
243                         },
244                         ast::Attr(__) => inside_attribute = true,
245                         _ => ()
246                     }
247                 }
248             }
249             WalkEvent::Leave(NodeOrToken::Node(node)) => {
250                 match_ast! {
251                     match node {
252                         ast::MacroCall(mcall) => {
253                             assert_eq!(current_macro_call, Some(mcall));
254                             current_macro_call = None;
255                         },
256                         ast::Macro(mac) => {
257                             assert_eq!(current_macro, Some(mac));
258                             current_macro = None;
259                             macro_highlighter = MacroHighlighter::default();
260                         },
261                         ast::Item(item) => {
262                             if current_attr_call == Some(item) {
263                                 current_attr_call = None;
264                             }
265                         },
266                         ast::Attr(__) => inside_attribute = false,
267                         _ => ()
268                     }
269                 }
270             }
271             _ => (),
272         }
273
274         let element = match event {
275             WalkEvent::Enter(it) => it,
276             WalkEvent::Leave(it) => {
277                 if let Some(node) = it.as_node() {
278                     inject::doc_comment(hl, sema, root.with_value(node));
279                 }
280                 continue;
281             }
282         };
283
284         let range = element.text_range();
285
286         if current_macro.is_some() {
287             if let Some(tok) = element.as_token() {
288                 macro_highlighter.advance(tok);
289             }
290         }
291
292         let descend_token = (current_macro_call.is_some() || current_attr_call.is_some())
293             && element.kind() != COMMENT;
294         let element_to_highlight = if descend_token {
295             // Inside a macro -- expand it first
296             let token = match element.clone().into_token() {
297                 Some(it) if current_macro_call.is_some() => {
298                     let not_in_tt = it.parent().map_or(true, |it| it.kind() != TOKEN_TREE);
299                     if not_in_tt {
300                         continue;
301                     }
302                     it
303                 }
304                 Some(it) => it,
305                 _ => continue,
306             };
307             let token = sema.descend_into_macros_single(token);
308             match token.parent() {
309                 Some(parent) => {
310                     // We only care Name and Name_ref
311                     match (token.kind(), parent.kind()) {
312                         (T![ident], NAME | NAME_REF) => parent.into(),
313                         (T![self] | T![super] | T![crate], NAME_REF) => parent.into(),
314                         (INT_NUMBER, NAME_REF) => parent.into(),
315                         _ => token.into(),
316                     }
317                 }
318                 None => token.into(),
319             }
320         } else {
321             element.clone()
322         };
323
324         if macro_highlighter.highlight(element_to_highlight.clone()).is_some() {
325             continue;
326         }
327
328         if let (Some(token), Some(token_to_highlight)) =
329             (element.into_token(), element_to_highlight.as_token())
330         {
331             let string = ast::String::cast(token);
332             let string_to_highlight = ast::String::cast(token_to_highlight.clone());
333             if let Some((string, expanded_string)) = string.zip(string_to_highlight) {
334                 if string.is_raw() {
335                     if inject::ra_fixture(hl, sema, &string, &expanded_string).is_some() {
336                         continue;
337                     }
338                 }
339                 highlight_format_string(hl, &string, &expanded_string, range);
340                 // Highlight escape sequences
341                 if let Some(char_ranges) = string.char_ranges() {
342                     for (piece_range, _) in char_ranges.iter().filter(|(_, char)| char.is_ok()) {
343                         if string.text()[piece_range.start().into()..].starts_with('\\') {
344                             hl.add(HlRange {
345                                 range: piece_range + range.start(),
346                                 highlight: HlTag::EscapeSequence.into(),
347                                 binding_hash: None,
348                             });
349                         }
350                     }
351                 }
352             }
353         }
354
355         if let Some((mut highlight, binding_hash)) = highlight::element(
356             sema,
357             krate,
358             &mut bindings_shadow_count,
359             syntactic_name_ref_highlighting,
360             element_to_highlight.clone(),
361         ) {
362             if inside_attribute {
363                 highlight |= HlMod::Attribute
364             }
365
366             hl.add(HlRange { range, highlight, binding_hash });
367         }
368     }
369 }
370
371 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
372     let path = macro_call.path()?;
373     let name_ref = path.segment()?.name_ref()?;
374
375     let range_start = name_ref.syntax().text_range().start();
376     let mut range_end = name_ref.syntax().text_range().end();
377     for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
378         if let T![!] | T![ident] = sibling.kind() {
379             range_end = sibling.text_range().end();
380         }
381     }
382
383     Some(TextRange::new(range_start, range_end))
384 }