]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide/src/syntax_highlighting.rs
Merge #4034
[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, Clone)]
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     // We use a stack for the DFS traversal below.
59     // When we leave a node, the we use it to flatten the highlighted ranges.
60     let mut res: Vec<Vec<HighlightedRange>> = vec![Vec::new()];
61
62     let mut current_macro_call: Option<ast::MacroCall> = None;
63
64     // Walk all nodes, keeping track of whether we are inside a macro or not.
65     // If in macro, expand it first and highlight the expanded code.
66     for event in root.preorder_with_tokens() {
67         match &event {
68             WalkEvent::Enter(_) => res.push(Vec::new()),
69             WalkEvent::Leave(_) => {
70                 /* Flattens the highlighted ranges.
71                  *
72                  * For example `#[cfg(feature = "foo")]` contains the nested ranges:
73                  * 1) parent-range: Attribute [0, 23)
74                  * 2) child-range: String [16, 21)
75                  *
76                  * The following code implements the flattening, for our example this results to:
77                  * `[Attribute [0, 16), String [16, 21), Attribute [21, 23)]`
78                  */
79                 let children = res.pop().unwrap();
80                 let prev = res.last_mut().unwrap();
81                 let needs_flattening = !children.is_empty()
82                     && !prev.is_empty()
83                     && children.first().unwrap().range.is_subrange(&prev.last().unwrap().range);
84                 if !needs_flattening {
85                     prev.extend(children);
86                 } else {
87                     let mut parent = prev.pop().unwrap();
88                     for ele in children {
89                         assert!(ele.range.is_subrange(&parent.range));
90                         let mut cloned = parent.clone();
91                         parent.range = TextRange::from_to(parent.range.start(), ele.range.start());
92                         cloned.range = TextRange::from_to(ele.range.end(), cloned.range.end());
93                         if !parent.range.is_empty() {
94                             prev.push(parent);
95                         }
96                         prev.push(ele);
97                         parent = cloned;
98                     }
99                     if !parent.range.is_empty() {
100                         prev.push(parent);
101                     }
102                 }
103             }
104         };
105         let current = res.last_mut().expect("during DFS traversal, the stack must not be empty");
106
107         let event_range = match &event {
108             WalkEvent::Enter(it) => it.text_range(),
109             WalkEvent::Leave(it) => it.text_range(),
110         };
111
112         // Element outside of the viewport, no need to highlight
113         if range_to_highlight.intersection(&event_range).is_none() {
114             continue;
115         }
116
117         // Track "inside macro" state
118         match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
119             WalkEvent::Enter(Some(mc)) => {
120                 current_macro_call = Some(mc.clone());
121                 if let Some(range) = macro_call_range(&mc) {
122                     current.push(HighlightedRange {
123                         range,
124                         highlight: HighlightTag::Macro.into(),
125                         binding_hash: None,
126                     });
127                 }
128                 continue;
129             }
130             WalkEvent::Leave(Some(mc)) => {
131                 assert!(current_macro_call == Some(mc));
132                 current_macro_call = None;
133                 continue;
134             }
135             _ => (),
136         }
137
138         let element = match event {
139             WalkEvent::Enter(it) => it,
140             WalkEvent::Leave(_) => continue,
141         };
142
143         let range = element.text_range();
144
145         let element_to_highlight = if current_macro_call.is_some() {
146             // Inside a macro -- expand it first
147             let token = match element.clone().into_token() {
148                 Some(it) if it.parent().kind() == TOKEN_TREE => it,
149                 _ => continue,
150             };
151             let token = sema.descend_into_macros(token.clone());
152             let parent = token.parent();
153             // We only care Name and Name_ref
154             match (token.kind(), parent.kind()) {
155                 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
156                 _ => token.into(),
157             }
158         } else {
159             element.clone()
160         };
161
162         if let Some(token) = element.as_token().cloned().and_then(ast::RawString::cast) {
163             let expanded = element_to_highlight.as_token().unwrap().clone();
164             if highlight_injection(current, &sema, token, expanded).is_some() {
165                 continue;
166             }
167         }
168
169         if let Some((highlight, binding_hash)) =
170             highlight_element(&sema, &mut bindings_shadow_count, element_to_highlight)
171         {
172             current.push(HighlightedRange { range, highlight, binding_hash });
173         }
174     }
175
176     assert_eq!(res.len(), 1, "after DFS traversal, the stack should only contain a single element");
177     let mut res = res.pop().unwrap();
178     res.sort_by_key(|range| range.range.start());
179     // Check that ranges are sorted and disjoint
180     assert!(res
181         .iter()
182         .zip(res.iter().skip(1))
183         .all(|(left, right)| left.range.end() <= right.range.start()));
184     res
185 }
186
187 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
188     let path = macro_call.path()?;
189     let name_ref = path.segment()?.name_ref()?;
190
191     let range_start = name_ref.syntax().text_range().start();
192     let mut range_end = name_ref.syntax().text_range().end();
193     for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
194         match sibling.kind() {
195             T![!] | IDENT => range_end = sibling.text_range().end(),
196             _ => (),
197         }
198     }
199
200     Some(TextRange::from_to(range_start, range_end))
201 }
202
203 fn highlight_element(
204     sema: &Semantics<RootDatabase>,
205     bindings_shadow_count: &mut FxHashMap<Name, u32>,
206     element: SyntaxElement,
207 ) -> Option<(Highlight, Option<u64>)> {
208     let db = sema.db;
209     let mut binding_hash = None;
210     let highlight: Highlight = match element.kind() {
211         FN_DEF => {
212             bindings_shadow_count.clear();
213             return None;
214         }
215
216         // Highlight definitions depending on the "type" of the definition.
217         NAME => {
218             let name = element.into_node().and_then(ast::Name::cast).unwrap();
219             let name_kind = classify_name(sema, &name);
220
221             if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
222                 if let Some(name) = local.name(db) {
223                     let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
224                     *shadow_count += 1;
225                     binding_hash = Some(calc_binding_hash(&name, *shadow_count))
226                 }
227             };
228
229             match name_kind {
230                 Some(NameClass::Definition(def)) => {
231                     highlight_name(db, def) | HighlightModifier::Definition
232                 }
233                 Some(NameClass::ConstReference(def)) => highlight_name(db, def),
234                 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
235             }
236         }
237
238         // Highlight references like the definitions they resolve to
239         NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => return None,
240         NAME_REF => {
241             let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
242             match classify_name_ref(sema, &name_ref) {
243                 Some(name_kind) => match name_kind {
244                     NameRefClass::Definition(def) => {
245                         if let Definition::Local(local) = &def {
246                             if let Some(name) = local.name(db) {
247                                 let shadow_count =
248                                     bindings_shadow_count.entry(name.clone()).or_default();
249                                 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
250                             }
251                         };
252                         highlight_name(db, def)
253                     }
254                     NameRefClass::FieldShorthand { .. } => HighlightTag::Field.into(),
255                 },
256                 None => HighlightTag::UnresolvedReference.into(),
257             }
258         }
259
260         // Simple token-based highlighting
261         COMMENT => HighlightTag::Comment.into(),
262         STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
263         ATTR => HighlightTag::Attribute.into(),
264         INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
265         BYTE => HighlightTag::ByteLiteral.into(),
266         CHAR => HighlightTag::CharLiteral.into(),
267         LIFETIME => {
268             let h = Highlight::new(HighlightTag::Lifetime);
269             match element.parent().map(|it| it.kind()) {
270                 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
271                 _ => h,
272             }
273         }
274
275         k if k.is_keyword() => {
276             let h = Highlight::new(HighlightTag::Keyword);
277             match k {
278                 T![break]
279                 | T![continue]
280                 | T![else]
281                 | T![for]
282                 | T![if]
283                 | T![loop]
284                 | T![match]
285                 | T![return]
286                 | T![while] => h | HighlightModifier::ControlFlow,
287                 T![unsafe] => h | HighlightModifier::Unsafe,
288                 _ => h,
289             }
290         }
291
292         _ => return None,
293     };
294
295     return Some((highlight, binding_hash));
296
297     fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
298         fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
299             use std::{collections::hash_map::DefaultHasher, hash::Hasher};
300
301             let mut hasher = DefaultHasher::new();
302             x.hash(&mut hasher);
303             hasher.finish()
304         }
305
306         hash((name, shadow_count))
307     }
308 }
309
310 fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight {
311     match def {
312         Definition::Macro(_) => HighlightTag::Macro,
313         Definition::StructField(_) => HighlightTag::Field,
314         Definition::ModuleDef(def) => match def {
315             hir::ModuleDef::Module(_) => HighlightTag::Module,
316             hir::ModuleDef::Function(_) => HighlightTag::Function,
317             hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
318             hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
319             hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
320             hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
321             hir::ModuleDef::Const(_) => HighlightTag::Constant,
322             hir::ModuleDef::Static(_) => HighlightTag::Static,
323             hir::ModuleDef::Trait(_) => HighlightTag::Trait,
324             hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
325             hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
326         },
327         Definition::SelfType(_) => HighlightTag::SelfType,
328         Definition::TypeParam(_) => HighlightTag::TypeParam,
329         // FIXME: distinguish between locals and parameters
330         Definition::Local(local) => {
331             let mut h = Highlight::new(HighlightTag::Local);
332             if local.is_mut(db) || local.ty(db).is_mutable_reference() {
333                 h |= HighlightModifier::Mutable;
334             }
335             return h;
336         }
337     }
338     .into()
339 }
340
341 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
342     let default = HighlightTag::Function.into();
343
344     let parent = match name.syntax().parent() {
345         Some(it) => it,
346         _ => return default,
347     };
348
349     match parent.kind() {
350         STRUCT_DEF => HighlightTag::Struct.into(),
351         ENUM_DEF => HighlightTag::Enum.into(),
352         UNION_DEF => HighlightTag::Union.into(),
353         TRAIT_DEF => HighlightTag::Trait.into(),
354         TYPE_ALIAS_DEF => HighlightTag::TypeAlias.into(),
355         TYPE_PARAM => HighlightTag::TypeParam.into(),
356         RECORD_FIELD_DEF => HighlightTag::Field.into(),
357         _ => default,
358     }
359 }
360
361 fn highlight_injection(
362     acc: &mut Vec<HighlightedRange>,
363     sema: &Semantics<RootDatabase>,
364     literal: ast::RawString,
365     expanded: SyntaxToken,
366 ) -> Option<()> {
367     let call_info = call_info_for_token(&sema, expanded)?;
368     let idx = call_info.active_parameter?;
369     let name = call_info.signature.parameter_names.get(idx)?;
370     if !name.starts_with("ra_fixture") {
371         return None;
372     }
373     let value = literal.value()?;
374     let (analysis, tmp_file_id) = Analysis::from_single_file(value);
375
376     if let Some(range) = literal.open_quote_text_range() {
377         acc.push(HighlightedRange {
378             range,
379             highlight: HighlightTag::StringLiteral.into(),
380             binding_hash: None,
381         })
382     }
383
384     for mut h in analysis.highlight(tmp_file_id).unwrap() {
385         if let Some(r) = literal.map_range_up(h.range) {
386             h.range = r;
387             acc.push(h)
388         }
389     }
390
391     if let Some(range) = literal.close_quote_text_range() {
392         acc.push(HighlightedRange {
393             range,
394             highlight: HighlightTag::StringLiteral.into(),
395             binding_hash: None,
396         })
397     }
398
399     Some(())
400 }