]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide/src/syntax_highlighting.rs
Cleanup highlighting tags
[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, NameDefinition},
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, references::classify_name_ref, 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                 eprintln!("res = {:?}", res);
124                 continue;
125             }
126         }
127
128         if let Some((highlight, binding_hash)) =
129             highlight_element(&sema, &mut bindings_shadow_count, element_to_highlight)
130         {
131             res.push(HighlightedRange { range, highlight, binding_hash });
132         }
133     }
134
135     res
136 }
137
138 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
139     let path = macro_call.path()?;
140     let name_ref = path.segment()?.name_ref()?;
141
142     let range_start = name_ref.syntax().text_range().start();
143     let mut range_end = name_ref.syntax().text_range().end();
144     for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
145         match sibling.kind() {
146             T![!] | IDENT => range_end = sibling.text_range().end(),
147             _ => (),
148         }
149     }
150
151     Some(TextRange::from_to(range_start, range_end))
152 }
153
154 fn highlight_element(
155     sema: &Semantics<RootDatabase>,
156     bindings_shadow_count: &mut FxHashMap<Name, u32>,
157     element: SyntaxElement,
158 ) -> Option<(Highlight, Option<u64>)> {
159     let db = sema.db;
160     let mut binding_hash = None;
161     let highlight: Highlight = match element.kind() {
162         FN_DEF => {
163             bindings_shadow_count.clear();
164             return None;
165         }
166
167         // Highlight definitions depending on the "type" of the definition.
168         NAME => {
169             let name = element.into_node().and_then(ast::Name::cast).unwrap();
170             let name_kind = classify_name(sema, &name);
171
172             if let Some(NameDefinition::Local(local)) = &name_kind {
173                 if let Some(name) = local.name(db) {
174                     let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
175                     *shadow_count += 1;
176                     binding_hash = Some(calc_binding_hash(&name, *shadow_count))
177                 }
178             };
179
180             let h = match name_kind {
181                 Some(name_kind) => highlight_name(db, name_kind),
182                 None => highlight_name_by_syntax(name),
183             };
184             h | HighlightModifier::Definition
185         }
186
187         // Highlight references like the definitions they resolve to
188
189         // Special-case field init shorthand
190         NAME_REF if element.parent().and_then(ast::RecordField::cast).is_some() => {
191             HighlightTag::Field.into()
192         }
193         NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => return None,
194         NAME_REF => {
195             let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
196             let name_kind = classify_name_ref(sema, &name_ref)?;
197
198             if let NameDefinition::Local(local) = &name_kind {
199                 if let Some(name) = local.name(db) {
200                     let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
201                     binding_hash = Some(calc_binding_hash(&name, *shadow_count))
202                 }
203             };
204
205             highlight_name(db, name_kind)
206         }
207
208         // Simple token-based highlighting
209         COMMENT => HighlightTag::Comment.into(),
210         STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
211         ATTR => HighlightTag::Attribute.into(),
212         INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
213         BYTE => HighlightTag::ByteLiteral.into(),
214         CHAR => HighlightTag::CharLiteral.into(),
215         // FIXME: set Declaration for decls
216         LIFETIME => HighlightTag::Lifetime.into(),
217
218         k if k.is_keyword() => {
219             let h = Highlight::new(HighlightTag::Keyword);
220             match k {
221                 T![break]
222                 | T![continue]
223                 | T![else]
224                 | T![for]
225                 | T![if]
226                 | T![loop]
227                 | T![match]
228                 | T![return]
229                 | T![while] => h | HighlightModifier::Control,
230                 T![unsafe] => h | HighlightModifier::Unsafe,
231                 _ => h,
232             }
233         }
234
235         _ => return None,
236     };
237
238     return Some((highlight, binding_hash));
239
240     fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
241         fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
242             use std::{collections::hash_map::DefaultHasher, hash::Hasher};
243
244             let mut hasher = DefaultHasher::new();
245             x.hash(&mut hasher);
246             hasher.finish()
247         }
248
249         hash((name, shadow_count))
250     }
251 }
252
253 fn highlight_name(db: &RootDatabase, def: NameDefinition) -> Highlight {
254     match def {
255         NameDefinition::Macro(_) => HighlightTag::Macro,
256         NameDefinition::StructField(_) => HighlightTag::Field,
257         NameDefinition::ModuleDef(def) => match def {
258             hir::ModuleDef::Module(_) => HighlightTag::Module,
259             hir::ModuleDef::Function(_) => HighlightTag::Function,
260             hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
261             hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
262             hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
263             hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
264             hir::ModuleDef::Const(_) => HighlightTag::Constant,
265             hir::ModuleDef::Static(_) => HighlightTag::Static,
266             hir::ModuleDef::Trait(_) => HighlightTag::Trait,
267             hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
268             hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
269         },
270         NameDefinition::SelfType(_) => HighlightTag::SelfType,
271         NameDefinition::TypeParam(_) => HighlightTag::TypeParam,
272         // FIXME: distinguish between locals and parameters
273         NameDefinition::Local(local) => {
274             let mut h = Highlight::new(HighlightTag::Local);
275             if local.is_mut(db) || local.ty(db).is_mutable_reference() {
276                 h |= HighlightModifier::Mutable;
277             }
278             return h;
279         }
280     }
281     .into()
282 }
283
284 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
285     let default = HighlightTag::Function.into();
286
287     let parent = match name.syntax().parent() {
288         Some(it) => it,
289         _ => return default,
290     };
291
292     match parent.kind() {
293         STRUCT_DEF => HighlightTag::Struct.into(),
294         ENUM_DEF => HighlightTag::Enum.into(),
295         UNION_KW => HighlightTag::Union.into(),
296         TRAIT_DEF => HighlightTag::Trait.into(),
297         TYPE_ALIAS_DEF => HighlightTag::TypeAlias.into(),
298         TYPE_PARAM => HighlightTag::TypeParam.into(),
299         RECORD_FIELD_DEF => HighlightTag::Field.into(),
300         _ => default,
301     }
302 }
303
304 fn highlight_injection(
305     acc: &mut Vec<HighlightedRange>,
306     sema: &Semantics<RootDatabase>,
307     literal: ast::RawString,
308     expanded: SyntaxToken,
309 ) -> Option<()> {
310     let call_info = call_info_for_token(&sema, expanded)?;
311     let idx = call_info.active_parameter?;
312     let name = call_info.signature.parameter_names.get(idx)?;
313     if name != "ra_fixture" {
314         return None;
315     }
316     let value = literal.value()?;
317     let (analysis, tmp_file_id) = Analysis::from_single_file(value);
318
319     if let Some(range) = literal.open_quote_text_range() {
320         acc.push(HighlightedRange {
321             range,
322             highlight: HighlightTag::StringLiteral.into(),
323             binding_hash: None,
324         })
325     }
326
327     for mut h in analysis.highlight(tmp_file_id).unwrap() {
328         if let Some(r) = literal.map_range_up(h.range) {
329             h.range = r;
330             acc.push(h)
331         }
332     }
333
334     if let Some(range) = literal.close_quote_text_range() {
335         acc.push(HighlightedRange {
336             range,
337             highlight: HighlightTag::StringLiteral.into(),
338             binding_hash: None,
339         })
340     }
341
342     Some(())
343 }