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