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