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