]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/syntax_highlighting.rs
Merge #8292
[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 // image::https://user-images.githubusercontent.com/48062697/113164457-06cfb980-9239-11eb-819b-0f93e646acf8.png[]
53 // image::https://user-images.githubusercontent.com/48062697/113187625-f7f50100-9250-11eb-825e-91c58f236071.png[]
54 pub(crate) fn highlight(
55     db: &RootDatabase,
56     file_id: FileId,
57     range_to_highlight: Option<TextRange>,
58     syntactic_name_ref_highlighting: bool,
59 ) -> Vec<HlRange> {
60     let _p = profile::span("highlight");
61     let sema = Semantics::new(db);
62
63     // Determine the root based on the given range.
64     let (root, range_to_highlight) = {
65         let source_file = sema.parse(file_id);
66         match range_to_highlight {
67             Some(range) => {
68                 let node = match source_file.syntax().covering_element(range) {
69                     NodeOrToken::Node(it) => it,
70                     NodeOrToken::Token(it) => it.parent().unwrap(),
71                 };
72                 (node, range)
73             }
74             None => (source_file.syntax().clone(), source_file.syntax().text_range()),
75         }
76     };
77
78     let mut hl = highlights::Highlights::new(root.text_range());
79     traverse(
80         &mut hl,
81         &sema,
82         InFile::new(file_id.into(), &root),
83         range_to_highlight,
84         syntactic_name_ref_highlighting,
85     );
86     hl.to_vec()
87 }
88
89 fn traverse(
90     hl: &mut Highlights,
91     sema: &Semantics<RootDatabase>,
92     root: InFile<&SyntaxNode>,
93     range_to_highlight: TextRange,
94     syntactic_name_ref_highlighting: bool,
95 ) {
96     let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
97
98     let mut current_macro_call: Option<ast::MacroCall> = None;
99     let mut current_macro: Option<ast::Macro> = None;
100     let mut macro_highlighter = MacroHighlighter::default();
101     let mut inside_attribute = false;
102
103     // Walk all nodes, keeping track of whether we are inside a macro or not.
104     // If in macro, expand it first and highlight the expanded code.
105     for event in root.value.preorder_with_tokens() {
106         let event_range = match &event {
107             WalkEvent::Enter(it) | WalkEvent::Leave(it) => it.text_range(),
108         };
109
110         // Element outside of the viewport, no need to highlight
111         if range_to_highlight.intersect(event_range).is_none() {
112             continue;
113         }
114
115         // Track "inside macro" state
116         match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
117             WalkEvent::Enter(Some(mc)) => {
118                 if let Some(range) = macro_call_range(&mc) {
119                     hl.add(HlRange {
120                         range,
121                         highlight: HlTag::Symbol(SymbolKind::Macro).into(),
122                         binding_hash: None,
123                     });
124                 }
125                 current_macro_call = Some(mc.clone());
126                 continue;
127             }
128             WalkEvent::Leave(Some(mc)) => {
129                 assert_eq!(current_macro_call, Some(mc));
130                 current_macro_call = None;
131             }
132             _ => (),
133         }
134
135         match event.clone().map(|it| it.into_node().and_then(ast::Macro::cast)) {
136             WalkEvent::Enter(Some(mac)) => {
137                 macro_highlighter.init();
138                 current_macro = Some(mac);
139                 continue;
140             }
141             WalkEvent::Leave(Some(mac)) => {
142                 assert_eq!(current_macro, Some(mac));
143                 current_macro = None;
144                 macro_highlighter = MacroHighlighter::default();
145             }
146             _ => (),
147         }
148         match &event {
149             WalkEvent::Enter(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
150                 inside_attribute = true
151             }
152             WalkEvent::Leave(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
153                 inside_attribute = false
154             }
155             _ => (),
156         }
157
158         let element = match event {
159             WalkEvent::Enter(it) => it,
160             WalkEvent::Leave(it) => {
161                 if let Some(node) = it.as_node() {
162                     inject::doc_comment(hl, sema, root.with_value(node));
163                 }
164                 continue;
165             }
166         };
167
168         let range = element.text_range();
169
170         if current_macro.is_some() {
171             if let Some(tok) = element.as_token() {
172                 macro_highlighter.advance(tok);
173             }
174         }
175
176         let element_to_highlight = if current_macro_call.is_some() && element.kind() != COMMENT {
177             // Inside a macro -- expand it first
178             let token = match element.clone().into_token() {
179                 Some(it) if it.parent().map_or(false, |it| it.kind() == TOKEN_TREE) => it,
180                 _ => continue,
181             };
182             let token = sema.descend_into_macros(token.clone());
183             match token.parent() {
184                 Some(parent) => {
185                     // We only care Name and Name_ref
186                     match (token.kind(), parent.kind()) {
187                         (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
188                         _ => token.into(),
189                     }
190                 }
191                 None => token.into(),
192             }
193         } else {
194             element.clone()
195         };
196
197         if let Some(token) = element.as_token().cloned().and_then(ast::String::cast) {
198             if token.is_raw() {
199                 let expanded = element_to_highlight.as_token().unwrap().clone();
200                 if inject::ra_fixture(hl, &sema, token, expanded).is_some() {
201                     continue;
202                 }
203             }
204         }
205
206         if let Some(_) = macro_highlighter.highlight(element_to_highlight.clone()) {
207             continue;
208         }
209
210         if let Some((mut highlight, binding_hash)) = highlight::element(
211             &sema,
212             &mut bindings_shadow_count,
213             syntactic_name_ref_highlighting,
214             element_to_highlight.clone(),
215         ) {
216             if inside_attribute {
217                 highlight = highlight | HlMod::Attribute;
218             }
219
220             hl.add(HlRange { range, highlight, binding_hash });
221         }
222
223         if let Some(string) = element_to_highlight.as_token().cloned().and_then(ast::String::cast) {
224             highlight_format_string(hl, &string, range);
225             // Highlight escape sequences
226             if let Some(char_ranges) = string.char_ranges() {
227                 for (piece_range, _) in char_ranges.iter().filter(|(_, char)| char.is_ok()) {
228                     if string.text()[piece_range.start().into()..].starts_with('\\') {
229                         hl.add(HlRange {
230                             range: piece_range + range.start(),
231                             highlight: HlTag::EscapeSequence.into(),
232                             binding_hash: None,
233                         });
234                     }
235                 }
236             }
237         }
238     }
239 }
240
241 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
242     let path = macro_call.path()?;
243     let name_ref = path.segment()?.name_ref()?;
244
245     let range_start = name_ref.syntax().text_range().start();
246     let mut range_end = name_ref.syntax().text_range().end();
247     for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
248         match sibling.kind() {
249             T![!] | IDENT => range_end = sibling.text_range().end(),
250             _ => (),
251         }
252     }
253
254     Some(TextRange::new(range_start, range_end))
255 }