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