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