]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide/src/syntax_highlighting.rs
Merge #4903
[rust.git] / crates / ra_ide / src / syntax_highlighting.rs
1 mod tags;
2 mod html;
3 mod injection;
4 #[cfg(test)]
5 mod tests;
6
7 use hir::{Name, Semantics};
8 use ra_ide_db::{
9     defs::{classify_name, classify_name_ref, Definition, NameClass, NameRefClass},
10     RootDatabase,
11 };
12 use ra_prof::profile;
13 use ra_syntax::{
14     ast::{self, HasFormatSpecifier},
15     AstNode, AstToken, Direction, NodeOrToken, SyntaxElement,
16     SyntaxKind::*,
17     TextRange, WalkEvent, T,
18 };
19 use rustc_hash::FxHashMap;
20
21 use crate::FileId;
22
23 use ast::FormatSpecifier;
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 // Feature: Semantic Syntax Highlighting
35 //
36 // rust-analyzer highlights the code semantically.
37 // For example, `bar` in `foo::Bar` might be colored differently depending on whether `Bar` is an enum or a trait.
38 // rust-analyzer does not specify colors directly, instead it assigns tag (like `struct`) and a set of modifiers (like `declaration`) to each token.
39 // It's up to the client to map those to specific colors.
40 //
41 // The general rule is that a reference to an entity gets colored the same way as the entity itself.
42 // We also give special modifier for `mut` and `&mut` local variables.
43 pub(crate) fn highlight(
44     db: &RootDatabase,
45     file_id: FileId,
46     range_to_highlight: Option<TextRange>,
47     syntactic_name_ref_highlighting: bool,
48 ) -> Vec<HighlightedRange> {
49     let _p = profile("highlight");
50     let sema = Semantics::new(db);
51
52     // Determine the root based on the given range.
53     let (root, range_to_highlight) = {
54         let source_file = sema.parse(file_id);
55         match range_to_highlight {
56             Some(range) => {
57                 let node = match source_file.syntax().covering_element(range) {
58                     NodeOrToken::Node(it) => it,
59                     NodeOrToken::Token(it) => it.parent(),
60                 };
61                 (node, range)
62             }
63             None => (source_file.syntax().clone(), source_file.syntax().text_range()),
64         }
65     };
66
67     let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
68     // We use a stack for the DFS traversal below.
69     // When we leave a node, the we use it to flatten the highlighted ranges.
70     let mut stack = HighlightedRangeStack::new();
71
72     let mut current_macro_call: Option<ast::MacroCall> = None;
73     let mut format_string: Option<SyntaxElement> = None;
74
75     // Walk all nodes, keeping track of whether we are inside a macro or not.
76     // If in macro, expand it first and highlight the expanded code.
77     for event in root.preorder_with_tokens() {
78         match &event {
79             WalkEvent::Enter(_) => stack.push(),
80             WalkEvent::Leave(_) => stack.pop(),
81         };
82
83         let event_range = match &event {
84             WalkEvent::Enter(it) => it.text_range(),
85             WalkEvent::Leave(it) => it.text_range(),
86         };
87
88         // Element outside of the viewport, no need to highlight
89         if range_to_highlight.intersect(event_range).is_none() {
90             continue;
91         }
92
93         // Track "inside macro" state
94         match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
95             WalkEvent::Enter(Some(mc)) => {
96                 current_macro_call = Some(mc.clone());
97                 if let Some(range) = macro_call_range(&mc) {
98                     stack.add(HighlightedRange {
99                         range,
100                         highlight: HighlightTag::Macro.into(),
101                         binding_hash: None,
102                     });
103                 }
104                 if let Some(name) = mc.is_macro_rules() {
105                     if let Some((highlight, binding_hash)) = highlight_element(
106                         &sema,
107                         &mut bindings_shadow_count,
108                         syntactic_name_ref_highlighting,
109                         name.syntax().clone().into(),
110                     ) {
111                         stack.add(HighlightedRange {
112                             range: name.syntax().text_range(),
113                             highlight,
114                             binding_hash,
115                         });
116                     }
117                 }
118                 continue;
119             }
120             WalkEvent::Leave(Some(mc)) => {
121                 assert!(current_macro_call == Some(mc));
122                 current_macro_call = None;
123                 format_string = None;
124                 continue;
125             }
126             _ => (),
127         }
128
129         // Check for Rust code in documentation
130         match &event {
131             WalkEvent::Leave(NodeOrToken::Node(node)) => {
132                 if let Some((doctest, range_mapping, new_comments)) =
133                     injection::extract_doc_comments(node)
134                 {
135                     injection::highlight_doc_comment(
136                         doctest,
137                         range_mapping,
138                         new_comments,
139                         &mut stack,
140                     );
141                 }
142             }
143             _ => (),
144         }
145
146         let element = match event {
147             WalkEvent::Enter(it) => it,
148             WalkEvent::Leave(_) => continue,
149         };
150
151         let range = element.text_range();
152
153         let element_to_highlight = if current_macro_call.is_some() {
154             // Inside a macro -- expand it first
155             let token = match element.clone().into_token() {
156                 Some(it) if it.parent().kind() == TOKEN_TREE => it,
157                 _ => continue,
158             };
159             let token = sema.descend_into_macros(token.clone());
160             let parent = token.parent();
161
162             // Check if macro takes a format string and remember it for highlighting later.
163             // The macros that accept a format string expand to a compiler builtin macros
164             // `format_args` and `format_args_nl`.
165             if let Some(name) = parent
166                 .parent()
167                 .and_then(ast::MacroCall::cast)
168                 .and_then(|mc| mc.path())
169                 .and_then(|p| p.segment())
170                 .and_then(|s| s.name_ref())
171             {
172                 match name.text().as_str() {
173                     "format_args" | "format_args_nl" => {
174                         format_string = parent
175                             .children_with_tokens()
176                             .filter(|t| t.kind() != WHITESPACE)
177                             .nth(1)
178                             .filter(|e| {
179                                 ast::String::can_cast(e.kind())
180                                     || ast::RawString::can_cast(e.kind())
181                             })
182                     }
183                     _ => {}
184                 }
185             }
186
187             // We only care Name and Name_ref
188             match (token.kind(), parent.kind()) {
189                 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
190                 _ => token.into(),
191             }
192         } else {
193             element.clone()
194         };
195
196         if let Some(token) = element.as_token().cloned().and_then(ast::RawString::cast) {
197             let expanded = element_to_highlight.as_token().unwrap().clone();
198             if injection::highlight_injection(&mut stack, &sema, token, expanded).is_some() {
199                 continue;
200             }
201         }
202
203         let is_format_string = format_string.as_ref() == Some(&element_to_highlight);
204
205         if let Some((highlight, binding_hash)) = highlight_element(
206             &sema,
207             &mut bindings_shadow_count,
208             syntactic_name_ref_highlighting,
209             element_to_highlight.clone(),
210         ) {
211             stack.add(HighlightedRange { range, highlight, binding_hash });
212             if let Some(string) =
213                 element_to_highlight.as_token().cloned().and_then(ast::String::cast)
214             {
215                 if is_format_string {
216                     stack.push();
217                     string.lex_format_specifier(|piece_range, kind| {
218                         if let Some(highlight) = highlight_format_specifier(kind) {
219                             stack.add(HighlightedRange {
220                                 range: piece_range + range.start(),
221                                 highlight: highlight.into(),
222                                 binding_hash: None,
223                             });
224                         }
225                     });
226                     stack.pop();
227                 }
228                 // Highlight escape sequences
229                 if let Some(char_ranges) = string.char_ranges() {
230                     stack.push();
231                     for (piece_range, _) in char_ranges.iter().filter(|(_, char)| char.is_ok()) {
232                         if string.text()[piece_range.start().into()..].starts_with('\\') {
233                             stack.add(HighlightedRange {
234                                 range: piece_range + range.start(),
235                                 highlight: HighlightTag::EscapeSequence.into(),
236                                 binding_hash: None,
237                             });
238                         }
239                     }
240                     stack.pop_and_inject(false);
241                 }
242             } else if let Some(string) =
243                 element_to_highlight.as_token().cloned().and_then(ast::RawString::cast)
244             {
245                 if is_format_string {
246                     stack.push();
247                     string.lex_format_specifier(|piece_range, kind| {
248                         if let Some(highlight) = highlight_format_specifier(kind) {
249                             stack.add(HighlightedRange {
250                                 range: piece_range + range.start(),
251                                 highlight: highlight.into(),
252                                 binding_hash: None,
253                             });
254                         }
255                     });
256                     stack.pop();
257                 }
258             }
259         }
260     }
261
262     stack.flattened()
263 }
264
265 #[derive(Debug)]
266 struct HighlightedRangeStack {
267     stack: Vec<Vec<HighlightedRange>>,
268 }
269
270 /// We use a stack to implement the flattening logic for the highlighted
271 /// syntax ranges.
272 impl HighlightedRangeStack {
273     fn new() -> Self {
274         Self { stack: vec![Vec::new()] }
275     }
276
277     fn push(&mut self) {
278         self.stack.push(Vec::new());
279     }
280
281     /// Flattens the highlighted ranges.
282     ///
283     /// For example `#[cfg(feature = "foo")]` contains the nested ranges:
284     /// 1) parent-range: Attribute [0, 23)
285     /// 2) child-range: String [16, 21)
286     ///
287     /// The following code implements the flattening, for our example this results to:
288     /// `[Attribute [0, 16), String [16, 21), Attribute [21, 23)]`
289     fn pop(&mut self) {
290         let children = self.stack.pop().unwrap();
291         let prev = self.stack.last_mut().unwrap();
292         let needs_flattening = !children.is_empty()
293             && !prev.is_empty()
294             && prev.last().unwrap().range.contains_range(children.first().unwrap().range);
295         if !needs_flattening {
296             prev.extend(children);
297         } else {
298             let mut parent = prev.pop().unwrap();
299             for ele in children {
300                 assert!(parent.range.contains_range(ele.range));
301
302                 let cloned = Self::intersect(&mut parent, &ele);
303                 if !parent.range.is_empty() {
304                     prev.push(parent);
305                 }
306                 prev.push(ele);
307                 parent = cloned;
308             }
309             if !parent.range.is_empty() {
310                 prev.push(parent);
311             }
312         }
313     }
314
315     /// Intersects the `HighlightedRange` `parent` with `child`.
316     /// `parent` is mutated in place, becoming the range before `child`.
317     /// Returns the range (of the same type as `parent`) *after* `child`.
318     fn intersect(parent: &mut HighlightedRange, child: &HighlightedRange) -> HighlightedRange {
319         assert!(parent.range.contains_range(child.range));
320
321         let mut cloned = parent.clone();
322         parent.range = TextRange::new(parent.range.start(), child.range.start());
323         cloned.range = TextRange::new(child.range.end(), cloned.range.end());
324
325         cloned
326     }
327
328     /// Similar to `pop`, but can modify arbitrary prior ranges (where `pop`)
329     /// can only modify the last range currently on the stack.
330     /// Can be used to do injections that span multiple ranges, like the
331     /// doctest injection below.
332     /// If `delete` is set to true, the parent range is deleted instead of
333     /// intersected.
334     ///
335     /// Note that `pop` can be simulated by `pop_and_inject(false)` but the
336     /// latter is computationally more expensive.
337     fn pop_and_inject(&mut self, delete: bool) {
338         let mut children = self.stack.pop().unwrap();
339         let prev = self.stack.last_mut().unwrap();
340         children.sort_by_key(|range| range.range.start());
341         prev.sort_by_key(|range| range.range.start());
342
343         for child in children {
344             if let Some(idx) =
345                 prev.iter().position(|parent| parent.range.contains_range(child.range))
346             {
347                 let cloned = Self::intersect(&mut prev[idx], &child);
348                 let insert_idx = if delete || prev[idx].range.is_empty() {
349                     prev.remove(idx);
350                     idx
351                 } else {
352                     idx + 1
353                 };
354                 prev.insert(insert_idx, child);
355                 if !delete && !cloned.range.is_empty() {
356                     prev.insert(insert_idx + 1, cloned);
357                 }
358             } else if let Some(_idx) =
359                 prev.iter().position(|parent| parent.range.contains(child.range.start()))
360             {
361                 unreachable!("child range should be completely contained in parent range");
362             } else {
363                 let idx = prev
364                     .binary_search_by_key(&child.range.start(), |range| range.range.start())
365                     .unwrap_or_else(|x| x);
366                 prev.insert(idx, child);
367             }
368         }
369     }
370
371     fn add(&mut self, range: HighlightedRange) {
372         self.stack
373             .last_mut()
374             .expect("during DFS traversal, the stack must not be empty")
375             .push(range)
376     }
377
378     fn flattened(mut self) -> Vec<HighlightedRange> {
379         assert_eq!(
380             self.stack.len(),
381             1,
382             "after DFS traversal, the stack should only contain a single element"
383         );
384         let mut res = self.stack.pop().unwrap();
385         res.sort_by_key(|range| range.range.start());
386         // Check that ranges are sorted and disjoint
387         assert!(res
388             .iter()
389             .zip(res.iter().skip(1))
390             .all(|(left, right)| left.range.end() <= right.range.start()));
391         res
392     }
393 }
394
395 fn highlight_format_specifier(kind: FormatSpecifier) -> Option<HighlightTag> {
396     Some(match kind {
397         FormatSpecifier::Open
398         | FormatSpecifier::Close
399         | FormatSpecifier::Colon
400         | FormatSpecifier::Fill
401         | FormatSpecifier::Align
402         | FormatSpecifier::Sign
403         | FormatSpecifier::NumberSign
404         | FormatSpecifier::DollarSign
405         | FormatSpecifier::Dot
406         | FormatSpecifier::Asterisk
407         | FormatSpecifier::QuestionMark => HighlightTag::FormatSpecifier,
408         FormatSpecifier::Integer | FormatSpecifier::Zero => HighlightTag::NumericLiteral,
409         FormatSpecifier::Identifier => HighlightTag::Local,
410     })
411 }
412
413 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
414     let path = macro_call.path()?;
415     let name_ref = path.segment()?.name_ref()?;
416
417     let range_start = name_ref.syntax().text_range().start();
418     let mut range_end = name_ref.syntax().text_range().end();
419     for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
420         match sibling.kind() {
421             T![!] | IDENT => range_end = sibling.text_range().end(),
422             _ => (),
423         }
424     }
425
426     Some(TextRange::new(range_start, range_end))
427 }
428
429 fn highlight_element(
430     sema: &Semantics<RootDatabase>,
431     bindings_shadow_count: &mut FxHashMap<Name, u32>,
432     syntactic_name_ref_highlighting: bool,
433     element: SyntaxElement,
434 ) -> Option<(Highlight, Option<u64>)> {
435     let db = sema.db;
436     let mut binding_hash = None;
437     let highlight: Highlight = match element.kind() {
438         FN_DEF => {
439             bindings_shadow_count.clear();
440             return None;
441         }
442
443         // Highlight definitions depending on the "type" of the definition.
444         NAME => {
445             let name = element.into_node().and_then(ast::Name::cast).unwrap();
446             let name_kind = classify_name(sema, &name);
447
448             if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
449                 if let Some(name) = local.name(db) {
450                     let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
451                     *shadow_count += 1;
452                     binding_hash = Some(calc_binding_hash(&name, *shadow_count))
453                 }
454             };
455
456             match name_kind {
457                 Some(NameClass::Definition(def)) => {
458                     highlight_name(db, def) | HighlightModifier::Definition
459                 }
460                 Some(NameClass::ConstReference(def)) => highlight_name(db, def),
461                 Some(NameClass::FieldShorthand { .. }) => HighlightTag::Field.into(),
462                 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
463             }
464         }
465
466         // Highlight references like the definitions they resolve to
467         NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => {
468             Highlight::from(HighlightTag::Function) | HighlightModifier::Attribute
469         }
470         NAME_REF => {
471             let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
472             match classify_name_ref(sema, &name_ref) {
473                 Some(name_kind) => match name_kind {
474                     NameRefClass::Definition(def) => {
475                         if let Definition::Local(local) = &def {
476                             if let Some(name) = local.name(db) {
477                                 let shadow_count =
478                                     bindings_shadow_count.entry(name.clone()).or_default();
479                                 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
480                             }
481                         };
482                         highlight_name(db, def)
483                     }
484                     NameRefClass::FieldShorthand { .. } => HighlightTag::Field.into(),
485                 },
486                 None if syntactic_name_ref_highlighting => highlight_name_ref_by_syntax(name_ref),
487                 None => HighlightTag::UnresolvedReference.into(),
488             }
489         }
490
491         // Simple token-based highlighting
492         COMMENT => {
493             let comment = element.into_token().and_then(ast::Comment::cast)?;
494             let h = HighlightTag::Comment;
495             match comment.kind().doc {
496                 Some(_) => h | HighlightModifier::Documentation,
497                 None => h.into(),
498             }
499         }
500         STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
501         ATTR => HighlightTag::Attribute.into(),
502         INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
503         BYTE => HighlightTag::ByteLiteral.into(),
504         CHAR => HighlightTag::CharLiteral.into(),
505         QUESTION => Highlight::new(HighlightTag::Operator) | HighlightModifier::ControlFlow,
506         LIFETIME => {
507             let h = Highlight::new(HighlightTag::Lifetime);
508             match element.parent().map(|it| it.kind()) {
509                 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
510                 _ => h,
511             }
512         }
513         T![*] => {
514             let prefix_expr = element.parent().and_then(ast::PrefixExpr::cast)?;
515
516             let expr = prefix_expr.expr()?;
517             let ty = sema.type_of_expr(&expr)?;
518             if !ty.is_raw_ptr() {
519                 return None;
520             }
521
522             let mut h = Highlight::new(HighlightTag::Operator);
523             h |= HighlightModifier::Unsafe;
524             h
525         }
526         T![!] if element.parent().and_then(ast::MacroCall::cast).is_some() => {
527             Highlight::new(HighlightTag::Macro)
528         }
529
530         k if k.is_keyword() => {
531             let h = Highlight::new(HighlightTag::Keyword);
532             match k {
533                 T![break]
534                 | T![continue]
535                 | T![else]
536                 | T![if]
537                 | T![loop]
538                 | T![match]
539                 | T![return]
540                 | T![while]
541                 | T![in] => h | HighlightModifier::ControlFlow,
542                 T![for] if !is_child_of_impl(element) => h | HighlightModifier::ControlFlow,
543                 T![unsafe] => h | HighlightModifier::Unsafe,
544                 T![true] | T![false] => HighlightTag::BoolLiteral.into(),
545                 T![self] => HighlightTag::SelfKeyword.into(),
546                 _ => h,
547             }
548         }
549
550         _ => return None,
551     };
552
553     return Some((highlight, binding_hash));
554
555     fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
556         fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
557             use std::{collections::hash_map::DefaultHasher, hash::Hasher};
558
559             let mut hasher = DefaultHasher::new();
560             x.hash(&mut hasher);
561             hasher.finish()
562         }
563
564         hash((name, shadow_count))
565     }
566 }
567
568 fn is_child_of_impl(element: SyntaxElement) -> bool {
569     match element.parent() {
570         Some(e) => e.kind() == IMPL_DEF,
571         _ => false,
572     }
573 }
574
575 fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight {
576     match def {
577         Definition::Macro(_) => HighlightTag::Macro,
578         Definition::Field(_) => HighlightTag::Field,
579         Definition::ModuleDef(def) => match def {
580             hir::ModuleDef::Module(_) => HighlightTag::Module,
581             hir::ModuleDef::Function(func) => {
582                 let mut h = HighlightTag::Function.into();
583                 if func.is_unsafe(db) {
584                     h |= HighlightModifier::Unsafe;
585                 }
586                 return h;
587             }
588             hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
589             hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
590             hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
591             hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
592             hir::ModuleDef::Const(_) => HighlightTag::Constant,
593             hir::ModuleDef::Trait(_) => HighlightTag::Trait,
594             hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
595             hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
596             hir::ModuleDef::Static(s) => {
597                 let mut h = Highlight::new(HighlightTag::Static);
598                 if s.is_mut(db) {
599                     h |= HighlightModifier::Mutable;
600                 }
601                 return h;
602             }
603         },
604         Definition::SelfType(_) => HighlightTag::SelfType,
605         Definition::TypeParam(_) => HighlightTag::TypeParam,
606         // FIXME: distinguish between locals and parameters
607         Definition::Local(local) => {
608             let mut h = Highlight::new(HighlightTag::Local);
609             if local.is_mut(db) || local.ty(db).is_mutable_reference() {
610                 h |= HighlightModifier::Mutable;
611             }
612             return h;
613         }
614     }
615     .into()
616 }
617
618 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
619     let default = HighlightTag::UnresolvedReference;
620
621     let parent = match name.syntax().parent() {
622         Some(it) => it,
623         _ => return default.into(),
624     };
625
626     let tag = match parent.kind() {
627         STRUCT_DEF => HighlightTag::Struct,
628         ENUM_DEF => HighlightTag::Enum,
629         UNION_DEF => HighlightTag::Union,
630         TRAIT_DEF => HighlightTag::Trait,
631         TYPE_ALIAS_DEF => HighlightTag::TypeAlias,
632         TYPE_PARAM => HighlightTag::TypeParam,
633         RECORD_FIELD_DEF => HighlightTag::Field,
634         MODULE => HighlightTag::Module,
635         FN_DEF => HighlightTag::Function,
636         CONST_DEF => HighlightTag::Constant,
637         STATIC_DEF => HighlightTag::Static,
638         ENUM_VARIANT => HighlightTag::EnumVariant,
639         BIND_PAT => HighlightTag::Local,
640         _ => default,
641     };
642
643     tag.into()
644 }
645
646 fn highlight_name_ref_by_syntax(name: ast::NameRef) -> Highlight {
647     let default = HighlightTag::UnresolvedReference;
648
649     let parent = match name.syntax().parent() {
650         Some(it) => it,
651         _ => return default.into(),
652     };
653
654     let tag = match parent.kind() {
655         METHOD_CALL_EXPR => HighlightTag::Function,
656         FIELD_EXPR => HighlightTag::Field,
657         PATH_SEGMENT => {
658             let path = match parent.parent().and_then(ast::Path::cast) {
659                 Some(it) => it,
660                 _ => return default.into(),
661             };
662             let expr = match path.syntax().parent().and_then(ast::PathExpr::cast) {
663                 Some(it) => it,
664                 _ => {
665                     // within path, decide whether it is module or adt by checking for uppercase name
666                     return if name.text().chars().next().unwrap_or_default().is_uppercase() {
667                         HighlightTag::Struct
668                     } else {
669                         HighlightTag::Module
670                     }
671                     .into();
672                 }
673             };
674             let parent = match expr.syntax().parent() {
675                 Some(it) => it,
676                 None => return default.into(),
677             };
678
679             match parent.kind() {
680                 CALL_EXPR => HighlightTag::Function,
681                 _ => {
682                     if name.text().chars().next().unwrap_or_default().is_uppercase() {
683                         HighlightTag::Struct
684                     } else {
685                         HighlightTag::Constant
686                     }
687                 }
688             }
689         }
690         _ => default,
691     };
692
693     tag.into()
694 }