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