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