]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/syntax_highlighting.rs
Merge #10951
[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 // 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 //
105 // //-
106 //
107 // [horizontal]
108 // builtinAttribute:: Emitted for names to builtin attributes in attribute path, the `repr` in `#[repr(u8)]` for example.
109 // builtinType:: Emitted for builtin types like `u32`, `str` and `f32`.
110 // comment:: Emitted for comments.
111 // constParameter:: Emitted for const parameters.
112 // enumMember:: Emitted for enum variants.
113 // generic:: Emitted for generic tokens that have no mapping.
114 // keyword:: Emitted for keywords.
115 // label:: Emitted for labels.
116 // lifetime:: Emitted for lifetimes.
117 // parameter:: Emitted for non-self function parameters.
118 // property:: Emitted for struct and union fields.
119 // selfKeyword:: Emitted for the self function parameter and self path-specifier.
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     traverse(
183         &mut hl,
184         &sema,
185         InFile::new(file_id.into(), &root),
186         sema.scope(&root).krate(),
187         range_to_highlight,
188         syntactic_name_ref_highlighting,
189     );
190     hl.to_vec()
191 }
192
193 fn traverse(
194     hl: &mut Highlights,
195     sema: &Semantics<RootDatabase>,
196     root: InFile<&SyntaxNode>,
197     krate: Option<hir::Crate>,
198     range_to_highlight: TextRange,
199     syntactic_name_ref_highlighting: bool,
200 ) {
201     let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
202
203     let mut current_macro_call: Option<ast::MacroCall> = None;
204     let mut current_attr_call = None;
205     let mut current_macro: Option<ast::Macro> = None;
206     let mut macro_highlighter = MacroHighlighter::default();
207     let mut inside_attribute = false;
208
209     // Walk all nodes, keeping track of whether we are inside a macro or not.
210     // If in macro, expand it first and highlight the expanded code.
211     for event in root.value.preorder_with_tokens() {
212         let event_range = match &event {
213             WalkEvent::Enter(it) | WalkEvent::Leave(it) => it.text_range(),
214         };
215
216         // Element outside of the viewport, no need to highlight
217         if range_to_highlight.intersect(event_range).is_none() {
218             continue;
219         }
220
221         match event.clone() {
222             WalkEvent::Enter(NodeOrToken::Node(node)) => {
223                 match_ast! {
224                     match node {
225                         ast::MacroCall(mcall) => {
226                             if let Some(range) = macro_call_range(&mcall) {
227                                 hl.add(HlRange {
228                                     range,
229                                     highlight: HlTag::Symbol(SymbolKind::Macro).into(),
230                                     binding_hash: None,
231                                 });
232                             }
233                             current_macro_call = Some(mcall);
234                             continue;
235                         },
236                         ast::Macro(mac) => {
237                             macro_highlighter.init();
238                             current_macro = Some(mac);
239                             continue;
240                         },
241                         ast::Item(item) => {
242                             if sema.is_attr_macro_call(&item) {
243                                 current_attr_call = Some(item);
244                             }
245                         },
246                         ast::Attr(__) => inside_attribute = true,
247                         _ => ()
248                     }
249                 }
250             }
251             WalkEvent::Leave(NodeOrToken::Node(node)) => {
252                 match_ast! {
253                     match node {
254                         ast::MacroCall(mcall) => {
255                             assert_eq!(current_macro_call, Some(mcall));
256                             current_macro_call = None;
257                         },
258                         ast::Macro(mac) => {
259                             assert_eq!(current_macro, Some(mac));
260                             current_macro = None;
261                             macro_highlighter = MacroHighlighter::default();
262                         },
263                         ast::Item(item) => {
264                             if current_attr_call == Some(item) {
265                                 current_attr_call = None;
266                             }
267                         },
268                         ast::Attr(__) => inside_attribute = false,
269                         _ => ()
270                     }
271                 }
272             }
273             _ => (),
274         }
275
276         let element = match event {
277             WalkEvent::Enter(it) => it,
278             WalkEvent::Leave(it) => {
279                 if let Some(node) = it.as_node() {
280                     inject::doc_comment(hl, sema, root.with_value(node));
281                 }
282                 continue;
283             }
284         };
285
286         let range = element.text_range();
287
288         if current_macro.is_some() {
289             if let Some(tok) = element.as_token() {
290                 macro_highlighter.advance(tok);
291             }
292         }
293
294         let descend_token = (current_macro_call.is_some() || current_attr_call.is_some())
295             && element.kind() != COMMENT;
296         let element_to_highlight = if descend_token {
297             // Inside a macro -- expand it first
298             let token = match element.clone().into_token() {
299                 Some(it) if current_macro_call.is_some() => {
300                     let not_in_tt = it.parent().map_or(true, |it| it.kind() != TOKEN_TREE);
301                     if not_in_tt {
302                         continue;
303                     }
304                     it
305                 }
306                 Some(it) => it,
307                 _ => continue,
308             };
309             let token = sema.descend_into_macros_single(token);
310             match token.parent() {
311                 Some(parent) => {
312                     // We only care Name and Name_ref
313                     match (token.kind(), parent.kind()) {
314                         (T![ident], NAME | NAME_REF) => parent.into(),
315                         (T![self] | T![super] | T![crate], NAME_REF) => parent.into(),
316                         (INT_NUMBER, NAME_REF) => parent.into(),
317                         _ => token.into(),
318                     }
319                 }
320                 None => token.into(),
321             }
322         } else {
323             element.clone()
324         };
325
326         if macro_highlighter.highlight(element_to_highlight.clone()).is_some() {
327             continue;
328         }
329
330         if let (Some(token), Some(token_to_highlight)) =
331             (element.into_token(), element_to_highlight.as_token())
332         {
333             let string = ast::String::cast(token);
334             let string_to_highlight = ast::String::cast(token_to_highlight.clone());
335             if let Some((string, expanded_string)) = string.zip(string_to_highlight) {
336                 if string.is_raw() {
337                     if inject::ra_fixture(hl, sema, &string, &expanded_string).is_some() {
338                         continue;
339                     }
340                 }
341                 highlight_format_string(hl, &string, &expanded_string, range);
342                 // Highlight escape sequences
343                 if let Some(char_ranges) = string.char_ranges() {
344                     for (piece_range, _) in char_ranges.iter().filter(|(_, char)| char.is_ok()) {
345                         if string.text()[piece_range.start().into()..].starts_with('\\') {
346                             hl.add(HlRange {
347                                 range: piece_range + range.start(),
348                                 highlight: HlTag::EscapeSequence.into(),
349                                 binding_hash: None,
350                             });
351                         }
352                     }
353                 }
354             }
355         }
356
357         if let Some((mut highlight, binding_hash)) = highlight::element(
358             sema,
359             krate,
360             &mut bindings_shadow_count,
361             syntactic_name_ref_highlighting,
362             element_to_highlight.clone(),
363         ) {
364             if inside_attribute {
365                 highlight |= HlMod::Attribute
366             }
367
368             hl.add(HlRange { range, highlight, binding_hash });
369         }
370     }
371 }
372
373 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
374     let path = macro_call.path()?;
375     let name_ref = path.segment()?.name_ref()?;
376
377     let range_start = name_ref.syntax().text_range().start();
378     let mut range_end = name_ref.syntax().text_range().end();
379     for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
380         if let T![!] | T![ident] = sibling.kind() {
381             range_end = sibling.text_range().end();
382         }
383     }
384
385     Some(TextRange::new(range_start, range_end))
386 }