]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide/src/syntax_highlighting.rs
Fix imports
[rust.git] / crates / ra_ide / src / syntax_highlighting.rs
1 //! Implements syntax highlighting.
2
3 mod tags;
4 mod html;
5 #[cfg(test)]
6 mod tests;
7
8 use hir::{Name, Semantics};
9 use ra_ide_db::{
10     defs::{classify_name, classify_name_ref, Definition, NameClass, NameRefClass},
11     RootDatabase,
12 };
13 use ra_prof::profile;
14 use ra_syntax::{
15     ast::{self, HasQuotes, HasStringValue},
16     AstNode, AstToken, Direction, NodeOrToken, SyntaxElement,
17     SyntaxKind::*,
18     SyntaxToken, TextRange, WalkEvent, T,
19 };
20 use rustc_hash::FxHashMap;
21
22 use crate::{call_info::call_info_for_token, Analysis, FileId};
23
24 pub(crate) use html::highlight_as_html;
25 pub use tags::{Highlight, HighlightModifier, HighlightModifiers, HighlightTag};
26
27 #[derive(Debug)]
28 pub struct HighlightedRange {
29     pub range: TextRange,
30     pub highlight: Highlight,
31     pub binding_hash: Option<u64>,
32 }
33
34 pub(crate) fn highlight(
35     db: &RootDatabase,
36     file_id: FileId,
37     range_to_highlight: Option<TextRange>,
38 ) -> Vec<HighlightedRange> {
39     let _p = profile("highlight");
40     let sema = Semantics::new(db);
41
42     // Determine the root based on the given range.
43     let (root, range_to_highlight) = {
44         let source_file = sema.parse(file_id);
45         match range_to_highlight {
46             Some(range) => {
47                 let node = match source_file.syntax().covering_element(range) {
48                     NodeOrToken::Node(it) => it,
49                     NodeOrToken::Token(it) => it.parent(),
50                 };
51                 (node, range)
52             }
53             None => (source_file.syntax().clone(), source_file.syntax().text_range()),
54         }
55     };
56
57     let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
58     let mut res = Vec::new();
59
60     let mut current_macro_call: Option<ast::MacroCall> = None;
61
62     // Walk all nodes, keeping track of whether we are inside a macro or not.
63     // If in macro, expand it first and highlight the expanded code.
64     for event in root.preorder_with_tokens() {
65         let event_range = match &event {
66             WalkEvent::Enter(it) => it.text_range(),
67             WalkEvent::Leave(it) => it.text_range(),
68         };
69
70         // Element outside of the viewport, no need to highlight
71         if range_to_highlight.intersection(&event_range).is_none() {
72             continue;
73         }
74
75         // Track "inside macro" state
76         match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
77             WalkEvent::Enter(Some(mc)) => {
78                 current_macro_call = Some(mc.clone());
79                 if let Some(range) = macro_call_range(&mc) {
80                     res.push(HighlightedRange {
81                         range,
82                         highlight: HighlightTag::Macro.into(),
83                         binding_hash: None,
84                     });
85                 }
86                 continue;
87             }
88             WalkEvent::Leave(Some(mc)) => {
89                 assert!(current_macro_call == Some(mc));
90                 current_macro_call = None;
91                 continue;
92             }
93             _ => (),
94         }
95
96         let element = match event {
97             WalkEvent::Enter(it) => it,
98             WalkEvent::Leave(_) => continue,
99         };
100
101         let range = element.text_range();
102
103         let element_to_highlight = if current_macro_call.is_some() {
104             // Inside a macro -- expand it first
105             let token = match element.clone().into_token() {
106                 Some(it) if it.parent().kind() == TOKEN_TREE => it,
107                 _ => continue,
108             };
109             let token = sema.descend_into_macros(token.clone());
110             let parent = token.parent();
111             // We only care Name and Name_ref
112             match (token.kind(), parent.kind()) {
113                 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
114                 _ => token.into(),
115             }
116         } else {
117             element.clone()
118         };
119
120         if let Some(token) = element.as_token().cloned().and_then(ast::RawString::cast) {
121             let expanded = element_to_highlight.as_token().unwrap().clone();
122             if highlight_injection(&mut res, &sema, token, expanded).is_some() {
123                 continue;
124             }
125         }
126
127         if let Some((highlight, binding_hash)) =
128             highlight_element(&sema, &mut bindings_shadow_count, element_to_highlight)
129         {
130             res.push(HighlightedRange { range, highlight, binding_hash });
131         }
132     }
133
134     res
135 }
136
137 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
138     let path = macro_call.path()?;
139     let name_ref = path.segment()?.name_ref()?;
140
141     let range_start = name_ref.syntax().text_range().start();
142     let mut range_end = name_ref.syntax().text_range().end();
143     for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
144         match sibling.kind() {
145             T![!] | IDENT => range_end = sibling.text_range().end(),
146             _ => (),
147         }
148     }
149
150     Some(TextRange::from_to(range_start, range_end))
151 }
152
153 fn highlight_element(
154     sema: &Semantics<RootDatabase>,
155     bindings_shadow_count: &mut FxHashMap<Name, u32>,
156     element: SyntaxElement,
157 ) -> Option<(Highlight, Option<u64>)> {
158     let db = sema.db;
159     let mut binding_hash = None;
160     let highlight: Highlight = match element.kind() {
161         FN_DEF => {
162             bindings_shadow_count.clear();
163             return None;
164         }
165
166         // Highlight definitions depending on the "type" of the definition.
167         NAME => {
168             let name = element.into_node().and_then(ast::Name::cast).unwrap();
169             let name_kind = classify_name(sema, &name);
170
171             if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
172                 if let Some(name) = local.name(db) {
173                     let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
174                     *shadow_count += 1;
175                     binding_hash = Some(calc_binding_hash(&name, *shadow_count))
176                 }
177             };
178
179             match name_kind {
180                 Some(NameClass::Definition(def)) => {
181                     highlight_name(db, def) | HighlightModifier::Definition
182                 }
183                 Some(NameClass::ConstReference(def)) => highlight_name(db, def),
184                 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
185             }
186         }
187
188         // Highlight references like the definitions they resolve to
189         NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => return None,
190         NAME_REF => {
191             let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
192             let name_kind = classify_name_ref(sema, &name_ref)?;
193
194             match name_kind {
195                 NameRefClass::Definition(def) => {
196                     if let Definition::Local(local) = &def {
197                         if let Some(name) = local.name(db) {
198                             let shadow_count =
199                                 bindings_shadow_count.entry(name.clone()).or_default();
200                             binding_hash = Some(calc_binding_hash(&name, *shadow_count))
201                         }
202                     };
203                     highlight_name(db, def)
204                 }
205                 NameRefClass::FieldShorthand { .. } => HighlightTag::Field.into(),
206             }
207         }
208
209         // Simple token-based highlighting
210         COMMENT => HighlightTag::Comment.into(),
211         STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
212         ATTR => HighlightTag::Attribute.into(),
213         INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
214         BYTE => HighlightTag::ByteLiteral.into(),
215         CHAR => HighlightTag::CharLiteral.into(),
216         LIFETIME => {
217             let h = Highlight::new(HighlightTag::Lifetime);
218             match element.parent().map(|it| it.kind()) {
219                 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
220                 _ => h,
221             }
222         }
223
224         k if k.is_keyword() => {
225             let h = Highlight::new(HighlightTag::Keyword);
226             match k {
227                 T![break]
228                 | T![continue]
229                 | T![else]
230                 | T![for]
231                 | T![if]
232                 | T![loop]
233                 | T![match]
234                 | T![return]
235                 | T![while] => h | HighlightModifier::Control,
236                 T![unsafe] => h | HighlightModifier::Unsafe,
237                 _ => h,
238             }
239         }
240
241         _ => return None,
242     };
243
244     return Some((highlight, binding_hash));
245
246     fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
247         fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
248             use std::{collections::hash_map::DefaultHasher, hash::Hasher};
249
250             let mut hasher = DefaultHasher::new();
251             x.hash(&mut hasher);
252             hasher.finish()
253         }
254
255         hash((name, shadow_count))
256     }
257 }
258
259 fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight {
260     match def {
261         Definition::Macro(_) => HighlightTag::Macro,
262         Definition::StructField(_) => HighlightTag::Field,
263         Definition::ModuleDef(def) => match def {
264             hir::ModuleDef::Module(_) => HighlightTag::Module,
265             hir::ModuleDef::Function(_) => HighlightTag::Function,
266             hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
267             hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
268             hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
269             hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
270             hir::ModuleDef::Const(_) => HighlightTag::Constant,
271             hir::ModuleDef::Static(_) => HighlightTag::Static,
272             hir::ModuleDef::Trait(_) => HighlightTag::Trait,
273             hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
274             hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
275         },
276         Definition::SelfType(_) => HighlightTag::SelfType,
277         Definition::TypeParam(_) => HighlightTag::TypeParam,
278         // FIXME: distinguish between locals and parameters
279         Definition::Local(local) => {
280             let mut h = Highlight::new(HighlightTag::Local);
281             if local.is_mut(db) || local.ty(db).is_mutable_reference() {
282                 h |= HighlightModifier::Mutable;
283             }
284             return h;
285         }
286     }
287     .into()
288 }
289
290 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
291     let default = HighlightTag::Function.into();
292
293     let parent = match name.syntax().parent() {
294         Some(it) => it,
295         _ => return default,
296     };
297
298     match parent.kind() {
299         STRUCT_DEF => HighlightTag::Struct.into(),
300         ENUM_DEF => HighlightTag::Enum.into(),
301         UNION_DEF => HighlightTag::Union.into(),
302         TRAIT_DEF => HighlightTag::Trait.into(),
303         TYPE_ALIAS_DEF => HighlightTag::TypeAlias.into(),
304         TYPE_PARAM => HighlightTag::TypeParam.into(),
305         RECORD_FIELD_DEF => HighlightTag::Field.into(),
306         _ => default,
307     }
308 }
309
310 fn highlight_injection(
311     acc: &mut Vec<HighlightedRange>,
312     sema: &Semantics<RootDatabase>,
313     literal: ast::RawString,
314     expanded: SyntaxToken,
315 ) -> Option<()> {
316     let call_info = call_info_for_token(&sema, expanded)?;
317     let idx = call_info.active_parameter?;
318     let name = call_info.signature.parameter_names.get(idx)?;
319     if !name.starts_with("ra_fixture") {
320         return None;
321     }
322     let value = literal.value()?;
323     let (analysis, tmp_file_id) = Analysis::from_single_file(value);
324
325     if let Some(range) = literal.open_quote_text_range() {
326         acc.push(HighlightedRange {
327             range,
328             highlight: HighlightTag::StringLiteral.into(),
329             binding_hash: None,
330         })
331     }
332
333     for mut h in analysis.highlight(tmp_file_id).unwrap() {
334         if let Some(r) = literal.map_range_up(h.range) {
335             h.range = r;
336             acc.push(h)
337         }
338     }
339
340     if let Some(range) = literal.close_quote_text_range() {
341         acc.push(HighlightedRange {
342             range,
343             highlight: HighlightTag::StringLiteral.into(),
344             binding_hash: None,
345         })
346     }
347
348     Some(())
349 }