]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/syntax_highlighting.rs
Merge #9007
[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 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 // .Token Modifiers
53 //
54 // Token modifiers allow to style some elements in the source code more precisely.
55 //
56 // Rust-analyzer currently emits the following token modifiers:
57 //
58 // [horizontal]
59 // associated:: Emitted for associated items.
60 // async:: Emitted for async functions and the `async` and `await` keywords.
61 // attribute:: Emitted for tokens inside attributes.
62 // callable:: Emitted for locals whose types implements one of the `Fn*` traits.
63 // consuming:: Emitted for locals that are being consumed when use in a function call.
64 // controlFlow:: Emitted for control-flow related tokens, this includes the `?` operator.
65 // declaration:: Emitted for names of definitions, like `foo` in `fn foo() {}`.
66 // documentation:: Emitted for documentation comments.
67 // injected:: Emitted for doc-string injected highlighting like rust source blocks in documentation.
68 // intraDocLink:: Emitted for intra doc links in doc-strings.
69 // library:: Emitted for items that are defined outside of the current crate.
70 // mutable:: Emitted for mutable locals and statics.
71 // static:: Emitted for "static" functions, also known as functions that do not take a `self` param.
72 // trait:: Emitted for associated trait items.
73 // unsafe:: Emitted for unsafe operations, like unsafe function calls, as well as the `unsafe` token.
74 //
75 //
76 // image::https://user-images.githubusercontent.com/48062697/113164457-06cfb980-9239-11eb-819b-0f93e646acf8.png[]
77 // image::https://user-images.githubusercontent.com/48062697/113187625-f7f50100-9250-11eb-825e-91c58f236071.png[]
78 pub(crate) fn highlight(
79     db: &RootDatabase,
80     file_id: FileId,
81     range_to_highlight: Option<TextRange>,
82     syntactic_name_ref_highlighting: bool,
83 ) -> Vec<HlRange> {
84     let _p = profile::span("highlight");
85     let sema = Semantics::new(db);
86
87     // Determine the root based on the given range.
88     let (root, range_to_highlight) = {
89         let source_file = sema.parse(file_id);
90         match range_to_highlight {
91             Some(range) => {
92                 let node = match source_file.syntax().covering_element(range) {
93                     NodeOrToken::Node(it) => it,
94                     NodeOrToken::Token(it) => it.parent().unwrap(),
95                 };
96                 (node, range)
97             }
98             None => (source_file.syntax().clone(), source_file.syntax().text_range()),
99         }
100     };
101
102     let mut hl = highlights::Highlights::new(root.text_range());
103     traverse(
104         &mut hl,
105         &sema,
106         InFile::new(file_id.into(), &root),
107         sema.scope(&root).krate(),
108         range_to_highlight,
109         syntactic_name_ref_highlighting,
110     );
111     hl.to_vec()
112 }
113
114 fn traverse(
115     hl: &mut Highlights,
116     sema: &Semantics<RootDatabase>,
117     root: InFile<&SyntaxNode>,
118     krate: Option<hir::Crate>,
119     range_to_highlight: TextRange,
120     syntactic_name_ref_highlighting: bool,
121 ) {
122     let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
123
124     let mut current_macro_call: Option<ast::MacroCall> = None;
125     let mut current_macro: Option<ast::Macro> = None;
126     let mut macro_highlighter = MacroHighlighter::default();
127     let mut inside_attribute = false;
128
129     // Walk all nodes, keeping track of whether we are inside a macro or not.
130     // If in macro, expand it first and highlight the expanded code.
131     for event in root.value.preorder_with_tokens() {
132         let event_range = match &event {
133             WalkEvent::Enter(it) | WalkEvent::Leave(it) => it.text_range(),
134         };
135
136         // Element outside of the viewport, no need to highlight
137         if range_to_highlight.intersect(event_range).is_none() {
138             continue;
139         }
140
141         // Track "inside macro" state
142         match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
143             WalkEvent::Enter(Some(mc)) => {
144                 if let Some(range) = macro_call_range(&mc) {
145                     hl.add(HlRange {
146                         range,
147                         highlight: HlTag::Symbol(SymbolKind::Macro).into(),
148                         binding_hash: None,
149                     });
150                 }
151                 current_macro_call = Some(mc.clone());
152                 continue;
153             }
154             WalkEvent::Leave(Some(mc)) => {
155                 assert_eq!(current_macro_call, Some(mc));
156                 current_macro_call = None;
157             }
158             _ => (),
159         }
160
161         match event.clone().map(|it| it.into_node().and_then(ast::Macro::cast)) {
162             WalkEvent::Enter(Some(mac)) => {
163                 macro_highlighter.init();
164                 current_macro = Some(mac);
165                 continue;
166             }
167             WalkEvent::Leave(Some(mac)) => {
168                 assert_eq!(current_macro, Some(mac));
169                 current_macro = None;
170                 macro_highlighter = MacroHighlighter::default();
171             }
172             _ => (),
173         }
174         match &event {
175             WalkEvent::Enter(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
176                 inside_attribute = true
177             }
178             WalkEvent::Leave(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
179                 inside_attribute = false
180             }
181             _ => (),
182         }
183
184         let element = match event {
185             WalkEvent::Enter(it) => it,
186             WalkEvent::Leave(it) => {
187                 if let Some(node) = it.as_node() {
188                     inject::doc_comment(hl, sema, root.with_value(node));
189                 }
190                 continue;
191             }
192         };
193
194         let range = element.text_range();
195
196         if current_macro.is_some() {
197             if let Some(tok) = element.as_token() {
198                 macro_highlighter.advance(tok);
199             }
200         }
201
202         let element_to_highlight = if current_macro_call.is_some() && element.kind() != COMMENT {
203             // Inside a macro -- expand it first
204             let token = match element.clone().into_token() {
205                 Some(it) if it.parent().map_or(false, |it| it.kind() == TOKEN_TREE) => it,
206                 _ => continue,
207             };
208             let token = sema.descend_into_macros(token.clone());
209             match token.parent() {
210                 Some(parent) => {
211                     // We only care Name and Name_ref
212                     match (token.kind(), parent.kind()) {
213                         (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
214                         _ => token.into(),
215                     }
216                 }
217                 None => token.into(),
218             }
219         } else {
220             element.clone()
221         };
222
223         if let Some(token) = element.as_token().cloned().and_then(ast::String::cast) {
224             if token.is_raw() {
225                 let expanded = element_to_highlight.as_token().unwrap().clone();
226                 if inject::ra_fixture(hl, &sema, token, expanded).is_some() {
227                     continue;
228                 }
229             }
230         }
231
232         if let Some(_) = macro_highlighter.highlight(element_to_highlight.clone()) {
233             continue;
234         }
235
236         if let Some((mut highlight, binding_hash)) = highlight::element(
237             &sema,
238             krate,
239             &mut bindings_shadow_count,
240             syntactic_name_ref_highlighting,
241             element_to_highlight.clone(),
242         ) {
243             if inside_attribute {
244                 highlight = highlight | HlMod::Attribute;
245             }
246
247             hl.add(HlRange { range, highlight, binding_hash });
248         }
249
250         if let Some(string) = element_to_highlight.as_token().cloned().and_then(ast::String::cast) {
251             highlight_format_string(hl, &string, range);
252             // Highlight escape sequences
253             if let Some(char_ranges) = string.char_ranges() {
254                 for (piece_range, _) in char_ranges.iter().filter(|(_, char)| char.is_ok()) {
255                     if string.text()[piece_range.start().into()..].starts_with('\\') {
256                         hl.add(HlRange {
257                             range: piece_range + range.start(),
258                             highlight: HlTag::EscapeSequence.into(),
259                             binding_hash: None,
260                         });
261                     }
262                 }
263             }
264         }
265     }
266 }
267
268 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
269     let path = macro_call.path()?;
270     let name_ref = path.segment()?.name_ref()?;
271
272     let range_start = name_ref.syntax().text_range().start();
273     let mut range_end = name_ref.syntax().text_range().end();
274     for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
275         match sibling.kind() {
276             T![!] | IDENT => range_end = sibling.text_range().end(),
277             _ => (),
278         }
279     }
280
281     Some(TextRange::new(range_start, range_end))
282 }